Arrange 0's & 1's in a array

前端 未结 16 2064
独厮守ぢ
独厮守ぢ 2020-12-04 13:36

This is one of an interview question which I had recently. I would like to know others perception of approach for this problem.

Question:

Yo

16条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 14:09

    My implementation in Perl using simple weighting.

    use Modern::Perl;
    
    my @data;
    {
      use List::MoreUtils qw'natatime';
      my $iter = natatime 2, qw'
        X1  0
        X2  1
        X3  0
        X4  1
        X5  0
      ';
    
      while( my($a,$b) = $iter->() ){
        push @data, [$a,$b]
      }
    }
    
    my @sorted = sort {
      ($a->[1] <=> $b->[1]) * -2 + # gives more weight to second element
      ($a->[0] cmp $b->[0])
    } @data;
    
    say "Name\tDept\n";
    say join "\t", @$_ for @sorted;
    
    Name    Dept
    
    X2      1
    X4      1
    X1      0
    X3      0
    X5      0
    

    The output of <=> and cmp comparisons is a value of -1,0,1.
    By multiplying one of the camparisons by two we get one of -2,0,2.
    After adding the value of the other operator we get one of -3,-2,-1,0,1,2,3

    I wanted to see how many comparisons it would do so I added some debugging information and came up with this.

     a           b        a1      b1     a0     b0
    X1,0   ->   X2,1      0   --> 1      X1 <-  X2
    X3,0   ->   X4,1      0   --> 1      X3 <-  X4
    X2,1  <-    X4,1      1   -   1      X2 <-  X4
    X4,1  <-    X1,0      1 <--   0      X4  -> X1
    X1,0  <-    X3,0      0   -   0      X1 <-  X3
    X2,1 <<-    X5,0      1 <--   0      X2 <-  X5
    X5,0   ->>  X4,1      0   --> 1      X5  -> X4
    X5,0   ->   X1,0      0   -   0      X5  -> X1
    X5,0   ->   X3,0      0   -   0      X5  -> X3
    
    The arrows point at the earlier value.
    

提交回复
热议问题