2-liners in Ruby (or unclean 1-liner)


  • 1

    Order each triple nums[0..2], nums[2..4], etc starting at even indexes so that the first value in the triple is the minimum and the second is the maximum (after sort it's like [1,2,3], then rotate makes it [2,3,1], then reverse makes it [1,3,2]).

    def wiggle_sort(nums)
      i = -2
      nums[i,3] = nums[i,3].sort.rotate.reverse while nums[i += 2]
    end
    

    And a 1-liner, although it's not clean because it does return a value (namely 0). Can be made clean by explicitly returning nil (just write another line containing just "nil").

    def wiggle_sort(nums)
      0.step(nums.size, 2) { |i| nums[i,3] = nums[i,3].sort.rotate.reverse }
    end

  • 0

    Nice observations of using "sort + rotate + reverse" :-)


  • 0

    Yeah, I'm glad I found a way :-). Although afterwards I realized that one can create any order of three elements just by using rotate and reverse:

    [1, 2, 3]                  => [1, 2, 3]
    [1, 2, 3].rotate           => [2, 3, 1]
    [1, 2, 3].rotate.rotate    => [3, 1, 2]       same as [1, 2, 3].rotate(2)
    [1, 2, 3].rotate.reverse   => [1, 3, 2]
    [1, 2, 3].reverse          => [3, 2, 1]
    [1, 2, 3].reverse.rotate   => [2, 1, 3]

  • 0

    Haha, interesting! So this will generate all the permutations for an array of three elements :-)


  • 0

    Stefan, I just removed the nil check for ruby. Your ruby solution is now 1-liner :)


  • 0

    Haha, ok :-). I found that check reasonable, btw. I said that only neutrally, didn't mean that it should be changed. But I guess either way works.


  • 0
    J

    Probably you can return nil in same line.

    nil if 0.step(nums.size, 2) { |i| nums[i,3] = nums[i,3].sort.rotate.reverse }

  • 0

    Haha, I remember Stefan often use such if statements in his Python codes. @Stefan, are you satisfied with this one-liner :-)


  • 0

    Such an if-modifier doesn't even exist in Python :-)

    Using it that way is interesting and I hadn't thought of it, but I like it less than appending && nil, which I had already decided against because it felt too forced/artificial... Now you made me reconsider that one :-D


  • 0
    J

    Also like '&& nil' better - more straight to the point.

    And don't feel too forced of using '&& nil'. Just it might be too fine print. 'nil &&' could be more specific. Either way, it's better than removing nil check for entire Ruby solutions. :)


  • 0

    nil &&? That doesn't work.


  • 0
    J

    gerr, it won't work. Forgot right part will be short-circuited.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.