Skip to content

Instantly share code, notes, and snippets.

@ZimbiX
Created September 25, 2015 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZimbiX/e2bbb248772f6531f54f to your computer and use it in GitHub Desktop.
Save ZimbiX/e2bbb248772f6531f54f to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# ehxxdsuhoowxpbxiwxjrhe # Input
# ehxxdsuhoowxpbxiwxrehj # Expected
# ehxxdsuhoowxpbxiwxehj
# ehxxdsuhoowxpebhijrwxx # v2 output (jump, sort)
# behijrwxx # Sorted chars
# 123456788 # Numerals for testing
# 184785632 # Input
# 184786235 # Expected
# 213456788 # v2 output
fork_readers = []
input = (ARGV[0] && IO.read(ARGV[0]) || STDIN.read).split
(1..input.size-1).each_slice(10000) do |line_nums_for_fork|
reader, writer = IO.pipe
fork_readers << reader
fork do
reader.close
answers = []
for l in line_nums_for_fork do
str_next = input[l].chars
str_curr = [str_next.pop]
loop do
if str_next.size == 0
answers << "no answer"
break
end
str_curr.insert(0, str_next.pop)
head_curr = str_curr[0]
str_curr.sort!
# Find the smallest character that is greater than the current most significant one
head_next_idx = str_curr.index { |c| c > head_curr }
next if !head_next_idx
# Move it to the front
head_next = str_curr[head_next_idx]
str_curr.slice!(head_next_idx)
answers << str_next.join + head_next + str_curr.join
break
end
end
# puts "Writing"
writer.puts answers
end # end forking
writer.close
end
out = fork_readers.map(&:read)
Process.waitall
puts out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment