Created
February 14, 2011 21:15
-
-
Save jannschu/826556 to your computer and use it in GitHub Desktop.
bwinf.de 2010/2011 2nd round, ex. 3
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
puts "bwinf.de 2010/2011 2nd round, ex. 3" | |
puts "Copyright (c) Jannik Schuerg 2011, GPLv3" | |
puts | |
if ARGV[0] =~ /[1-9]\d*/ | |
n = ARGV[0].to_i | |
else | |
puts "Usage: traumdreieck.rb <number of levels>" | |
end | |
conditions = [] | |
def first_ball_number_on_level(level) | |
(2 + level + level ** 2) / 2 | |
end | |
n.times do |level| | |
balls = level + 1 | |
first_num = first_ball_number_on_level(level) | |
first_num.upto(first_num + balls - 1) do |ball| | |
(level + 1).upto(n - 1) do |child_level| | |
ball_a = first_ball_number_on_level(child_level) + (ball - first_num) | |
ball_b = ball_a + (child_level - level) | |
conditions << [ball_a, ball_b, ball] | |
end | |
end | |
end | |
ball_colors = {} | |
color_counter = 1 | |
ball_colors[1] = color_counter | |
def rand_choose(a, b) rand(2) == 1 ? a : b end | |
conditions.each do |condition| a, b, ball = *condition | |
ca, cb = ball_colors[a], ball_colors[b] | |
next if ca && cb | |
look_at = !ca && !cb ? rand_choose(a, b) : (ca ? b : a) | |
conditons_for_it = conditions. | |
find_all { |e| e[0] == look_at || e[1] == look_at }.map { |e| e[2] }. | |
find_all { |e| not ball_colors[e].nil? }.map { |e| ball_colors[e] } | |
if conditons_for_it.empty? | |
ball_colors[look_at] = rand(color_counter) + 1 | |
elsif conditons_for_it.length == color_counter | |
color_counter += 1 | |
ball_colors[look_at] = color_counter | |
else | |
cond_color = conditons_for_it[rand(conditons_for_it.length)] | |
begin | |
ball_colors[look_at] = rand(color_counter) + 1 | |
end while ball_colors[look_at] == cond_color | |
end | |
end | |
(n*(n+1)/2).times do |ball| | |
next if ball_colors[ball + 1] | |
ball_colors[ball + 1] = rand(color_counter) + 1 | |
end | |
max = n.to_s.length | |
n.times do |level| | |
start = first_ball_number_on_level(level) | |
stop = start + level | |
line = [] | |
start.upto(stop) { |i| line << ball_colors[i].to_s.center(max) } | |
puts ' ' * (n - level) * max + line.join(' ' * max) | |
end | |
puts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment