A Puzzle Solution
This file contains 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
class Cube | |
attr_accessor :sides | |
ALLOWED_COLORS = %i[red green yellow blue].sort.freeze | |
def initialize(sides) | |
@sides = sides | |
end | |
def rotate! | |
new_sides = [] | |
sides.each_slice(2) do |side_pair| | |
new_sides << (rand(2).odd? ? side_pair : side_pair.rotate) | |
end | |
@sides = new_sides.shuffle.flatten | |
end | |
end | |
class Puzzle | |
attr_accessor :attempts, :cubes | |
def initialize(cubes) | |
@cubes = cubes | |
@attempts = 0 | |
end | |
def faces | |
[0, 1, 4, 5].map { |n| cubes.map { |c| c.sides[n] } } | |
end | |
def solve | |
cubes.sample.rotate! until solved? | |
self | |
end | |
def solved? | |
@attempts += 1 | |
faces.each { |face| return false unless face.sort == Cube::ALLOWED_COLORS } | |
true | |
end | |
end | |
cubes = [ | |
Cube.new(%i[yellow blue blue red green green]), | |
Cube.new(%i[yellow yellow yellow green red blue]), | |
Cube.new(%i[red green blue yellow red yellow]), | |
Cube.new(%i[yellow green red green blue red]) | |
] | |
puzzle = Puzzle.new(cubes) | |
puzzle.solve | |
puts "Total attempts: #{puzzle.attempts}" | |
puts "[" | |
puzzle.faces.each { |face| puts " [#{face.join(", ") }]" } | |
puts "]" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment