Created
July 6, 2015 17:30
-
-
Save aks/9661b1c44a019872b1fa to your computer and use it in GitHub Desktop.
Move Zeroes -- Amazon Quesion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| # mv-zeroes | |
| # | |
| # Beware! Today's exercise, which derives from an interview question asked at | |
| # Facebook, is trickier than it looks: | |
| # | |
| # You are given an array of integers. Write a program that moves all non-zero | |
| # integers to the left end of the array, and all zeroes to the right end of the | |
| # array. Your program should operate in place. The order of the non-zero | |
| # integers doesn't matter. As an example, given the input array | |
| # [1,0,2,0,0,3,4], your program should permute the array to [1,4,2,3,0,0,0] or | |
| # something similar, and return the value 4. | |
| # | |
| # Your task is to write the indicated program. When you are finished, you are | |
| # welcome to read or run a suggested solution, or to post your own solution or | |
| # discuss the exercise in the comments below. | |
| puts ARGF.read.split(' ').sort.reverse.join(' ') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| # mv-zeroes2.rb | |
| # | |
| # Beware! Today's exercise, which derives from an interview question asked at | |
| # Facebook, is trickier than it looks: | |
| # | |
| # You are given an array of integers. Write a program that moves all non-zero | |
| # integers to the left end of the array, and all zeroes to the right end of the | |
| # array. Your program should operate in place. The order of the non-zero | |
| # integers doesn't matter. As an example, given the input array | |
| # [1,0,2,0,0,3,4], your program should permute the array to [1,4,2,3,0,0,0] or | |
| # something similar, and return the value 4. | |
| # | |
| # Let's assume we do care about ordering of the original non-zeroes: | |
| class Array | |
| def move_zeroes() | |
| a = self | |
| x = y = 0 | |
| l = a.length | |
| while x < l | |
| if a[x].to_i == 0 | |
| x += 1 | |
| next | |
| elsif y < x | |
| a[y] = a[x] | |
| end | |
| x += 1 | |
| y += 1 | |
| end | |
| while y < l | |
| a[y] = 0 | |
| y += 1 | |
| end | |
| a | |
| end | |
| end | |
| puts ARGF.read.split(' ').move_zeroes.join(' ') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment