Created
February 2, 2016 15:04
-
-
Save oddlyfunctional/6d18a43c93cd1565c9b4 to your computer and use it in GitHub Desktop.
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
#!/bin/ruby | |
# https://www.hackerrank.com/contests/worldcodesprint/challenges/colorful-ornaments | |
require 'set' | |
A,B,C,D = gets.strip.split(' ').map(&:to_i) | |
RR = %w(R R) | |
RB = %w(R B) | |
BB = %w(B B) | |
BR = %w(B R) | |
PAIRS = [RR, RB, BB, BR] | |
class Problem | |
attr_reader :valid_chains | |
NEXT_PAIRS = { | |
'B' => [BB, BR], | |
'R' => [RR, RB] | |
} | |
TARGET_PAIRS = { | |
RR => A, | |
RB => B, | |
BB => C, | |
BR => D | |
} | |
def run | |
@valid_chains = 0 | |
generate_next_char('R', { RR => 0, RB => 0, BB => 0, BR => 0 }) | |
generate_next_char('B', { RR => 0, RB => 0, BB => 0, BR => 0 }) | |
end | |
def generate_next_char(last, counts) | |
chains = [ | |
[last, counts] | |
] | |
while chains.any? | |
last, counts = chains.pop | |
if valid?(counts) | |
@valid_chains += 1 | |
next | |
end | |
NEXT_PAIRS[last].each do |possible_next_pair| | |
next if counts[possible_next_pair] >= TARGET_PAIRS[possible_next_pair] | |
chains.push [ | |
possible_next_pair[1], | |
counts.merge({ | |
possible_next_pair => counts[possible_next_pair] + 1 | |
}) | |
] | |
end | |
end | |
end | |
def valid?(counts) | |
counts == TARGET_PAIRS | |
end | |
end | |
problem = Problem.new | |
problem.run | |
puts problem.valid_chains % (10**9+7) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment