Skip to content

Instantly share code, notes, and snippets.

@apenney
Created May 18, 2015 15:22
Show Gist options
  • Save apenney/d34391346d6e352f6dbc to your computer and use it in GitHub Desktop.
Save apenney/d34391346d6e352f6dbc to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
COLORS = {:red => 0, :white => 1, :blue => 2}
def random_color
COLORS.keys.sample
end
def is_sorted?(array)
sorted = false
# take chunks of 3
# test is sorted
# set sorted to true if so
array.each_slice(3).each do |flag|
sorted = true if flag == [:red, :white, :blue]
end
sorted
end
# Generate balls, ensuring they are not sorted
def generate(n)
sorted = true
while sorted do
balls = Array.new(n) { random_color }
sorted = is_sorted?(balls)
end
balls
end
# Sort balls
def sort(balls)
balls.sort_by {|s| COLORS[s]}
end
# Test balls are sorted
def test_sort(array)
array.reduce { |prev,e| break unless COLORS[e] >= COLORS[prev]; e}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment