Skip to content

Instantly share code, notes, and snippets.

@jgnagy
Created March 15, 2022 04:54
Show Gist options
  • Save jgnagy/c33fe05e568541b6128f6b5719f08904 to your computer and use it in GitHub Desktop.
Save jgnagy/c33fe05e568541b6128f6b5719f08904 to your computer and use it in GitHub Desktop.
A Puzzle Solution
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