Last active
August 29, 2015 14:09
-
-
Save fallengiants/b8e9bf84cbf8e3a9e450 to your computer and use it in GitHub Desktop.
O(n^2) naive implementation
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
| # naive implementation. We could move all the .index stuff into one loop | |
| # and do all kinds of other terrible things | |
| # but that's boring | |
| class ParkingOrder | |
| def initialize(current) | |
| @state = current.split('').uniq | |
| @empty = @state.index ?_ | |
| end | |
| def solve(final) | |
| @target = final.split('').uniq | |
| puts @state.join ' ' | |
| unmoved = @state[0] == ?_ ? 0 : 1 | |
| 0.upto(@state.length) do |idx| | |
| mover = @target[@empty] | |
| from = @state.index mover | |
| from = unmoved if from == @empty # unreasonable move | |
| @state[from], @state[@empty] = @state[@empty], @state[from] | |
| @empty = from | |
| if from == unmoved + 1 | |
| while @target[unmoved] == @state[unmoved] | |
| unmoved += 1 | |
| return if unmoved >= @state.length | |
| end | |
| end | |
| puts @state.join ' ' | |
| end | |
| end | |
| end | |
| if __FILE__ == $0 | |
| po = ParkingOrder.new 'bedc_a' | |
| po.solve 'abcde_' | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment