本帖最后由 523066680 于 2019-1-22 15:13 编辑
有缺陷/未完成,大概方向,unshift 取出首个数字,和剩下的各个元素做减法,找出相差距离最近的数字(分为L和R)的对应坐标,插入。可能做足判断会好一些,待完善。- my @arr = qw/5 1 9 3 2 4 6/;
- my ($first, $L,$R,$r_id, $l_id, $dt);
- my $max = 100000;
-
- for (1..5)
- {
- $first = shift @arr;
- $L = -$max;
- $R = $max;
- $r_id = 0;
- $l_id = 0;
- for $i ( 0 .. $#arr ) {
- $dt = $arr[$i] - $first;
- if ( $dt > 0 && $dt <= $R) { $r_id = $i, $R = $dt; }
- if ( $dt < 0 && $dt >= $L) { $l_id = $i, $L = $dt; }
- }
-
- if ( $R == $max ) {
- push @arr, $first;
- } else {
- splice( @arr, $r_id, 0, $first );
- }
- #printf "%d - %d: %d, %d: %d\n", $first, $l_id, $L, $r_id, $R;
- print join(",", @arr), "\n";
- }
-
- #print join("", @arr);
复制代码 1,9,3,2,4,5,6
9,3,1,2,4,5,6
3,1,2,4,5,6,9
1,2,3,4,5,6,9
特地找一副扑克牌玩了一下,为啥人玩起来就这么自然…… 转成代码总是有纰漏,
纠正了某些情况下不能完全处理的问题,也未经过严格验证,暂时这样。- my @arr = qw/7 3 4 1 10 9 8 11 24/;
- my ($first, $L,$R,$r_id, $l_id, $dt);
- my $max = 100000;
- my $ok = 0;
-
- while (1)
- {
- $first = shift @arr;
- $L = -$max;
- $R = $max;
- $r_id = 0;
- $l_id = 0;
- for $i ( 0 .. $#arr ) {
- $dt = $arr[$i] - $first;
- if ( $dt > 0 && $dt <= $R) { $r_id = $i, $R = $dt; }
- if ( $dt < 0 && $dt >= $L) { $l_id = $i, $L = $dt; }
- }
-
- if ( $L != -$max )
- {
- # 如果有相对较小的数字,优先移至最邻近者
- splice( @arr, $l_id+1, 0, $first );
- } else {
- if ( $R == $max ) {
- # 如果未找到更大的数字,直接堆到最后
- push @arr, $first;
- } else {
- # 判断数组中是否还有 左边大于右边的情况
- $ok = 1;
- for my $i ( 0 .. $#arr-1 ) {
- if ( $arr[$i] > $arr[$i+1] ) {
- splice( @arr, $i+1, 0, $first );
- $ok = 0;
- last;
- }
- }
- last if $ok;
- }
- }
- #printf "%d -- [%d]: %d, [%d]: %d\n", $first, $l_id, $L, $r_id, $R;
- print join(",", @arr), "\n";
- }
复制代码
- 3,4,7,1,10,9,8,11,24
- 4,7,1,3,10,9,8,11,24
- 7,1,3,4,10,9,8,11,24
- 1,3,4,7,10,9,8,11,24
- 3,4,7,10,1,9,8,11,24
- 4,7,10,1,3,9,8,11,24
- 7,10,1,3,4,9,8,11,24
- 10,1,3,4,7,9,8,11,24
- 1,3,4,7,9,10,8,11,24
- 3,4,7,9,10,1,8,11,24
- 4,7,9,10,1,3,8,11,24
- 7,9,10,1,3,4,8,11,24
- 9,10,1,3,4,7,8,11,24
- 10,1,3,4,7,8,9,11,24
- 1,3,4,7,8,9,10,11,24
复制代码
- 2,3,5,1,4
- 3,5,1,2,4
- 5,1,2,3,4
- 1,2,3,4,5
复制代码
|