2015-11-09 50 views
-2

我正在用Perl写一个程序。它的一部分需要对数字进行排序。但这不是一个正常的排序。值是这样的。 01,02,03,04,05,97,98,99。我希望它可以像这样排序。以特定方式在perl中排序

97 
98 
99 
01 
02 
03 
04 
05 

我们正在整理数据包。如果昨天的最后一个数据包是96,今天它将从97开始,直到99然后回到01 02 ....并且将在某个数字处停止说06.

+0

你怎么知道你从97开始?所有的数字都是连续的吗? – Sobrique

+0

不,它可以从1-99之间的任意随机数开始。上面的例子只是一个例子..值将达到99,并且它从01开始,它将以某个随机值进行坐标。 – nithin

+0

@nithin它是从“1”还是“01”开始的? – TLP

回答

2

说出昨天的最后一个数字是93(案例1)。你想

94: position 0 
95: position 1 
.. 
93: position 99 

模数操作可以用来产生这种映射。

($_ - $last_from_yesterday - 1) % 100 

排序变得微不足道:

sort { ($a - $last_from_yesterday - 1) % 100 <=> ($b - $last_from_yesterday - 1) % 100 } 
+0

更新回答以回应问题的最新更新。 – ikegami

0

我根据猜测在你的数据,你的号码是连续的,但缠绕100.所以,你会通过订购的一切找到“开始”,然后寻找差距。 (如果你有一个完整的循环,这会中断!)

#!/usr/bin/env perl 
use strict; 
use warnings; 

my @numbers = (1,2,3,4,5,97,98,99); 

#sort them 
my @sorted = sort { $a <=> $b } @numbers; 

#rotate the numbers until your 'gap' is off the end of the cycle. 

my $splice = 0; 
for (my $index = 0; $index < $#numbers; $index++) { 
    print 1+$sorted[$index] % 100,","; 
    print $sorted[$index+1] % 100,"\n"; 
    if (($sorted[$index] + 1) %100 < $sorted[$index+1] % 100) { 
     $splice = $index; 
    } 
} 
print "Splicing on $splice\n"; 
@numbers = (splice (@sorted, $splice+1, @sorted - $splice), splice (@sorted, 0, $splice+1)); 
print join ",", @numbers; 

编辑:好的,新的测试用例。可能不适合那些。希望这可以说明一种方法。但是,由于你的订单存在差距(我没有假设没有差距),所以很难说,因为你基本上正在寻找最大的差距。

+0

雅。我测试了这种情况:01,02,04,06,07,91,95,99 它给了我下面的答案 拼接上6 99,1,2,4,6,7,91,95 – nithin

+0

这有效,但它不能彻底地工作 - 数字顺序很容易检测到休息。对于数字来说,很难判断应该在哪里休息。 – Sobrique

+0

@Sobrique你可能不应该按照字母顺序对数字进行排序,即使它确实发生在这些数据上。 – TLP