Skip to content

Instantly share code, notes, and snippets.

@chtzvt
Created February 13, 2023 00:41
Show Gist options
  • Save chtzvt/03cbc22d8a410c1422c07c290f8c00aa to your computer and use it in GitHub Desktop.
Save chtzvt/03cbc22d8a410c1422c07c290f8c00aa to your computer and use it in GitHub Desktop.
# Scholten/Dijkstra pebble game
# https://youtu.be/31KI7fk15QA?t=90
# my implementation (an abomination)
class Pebble
attr_accessor :color
def initialize
@color = 1 + rand(2) > 1 ? :black : :white
end
def to_s
@color.to_s
end
end
class Urn
attr_accessor :pebbles
# Starting position: an urn containing one
# or more pebbles, each pebble being black
# or white
def initialize
n = 1 + rand(500)
@pebbles = []
puts "Fill: #{n}"
fill(n)
end
def fill(n)
n.times do
@pebbles << Pebble.new
end
end
# A move. Take two pebbles out of the urn;
# if colors are different, a white pebble is
# put into the urn, if equal, a black one.
def take
p1 = @pebbles.pop
p2 = @pebbles.pop
p3 = Pebble.new
puts "Got #{p1} and #{p2} pebbles."
if p1.color != p2.color
p3.color = :white
else
p3.color = :black
end
put(p3)
end
def put(peb)
@pebbles << peb
end
def count
@pebbles.length
end
end
urn = Urn.new
# Continue making moves as long as possible
# A move is possible if the urn contains two
# or more pebbles.
i = 0
init_count = urn.count
while urn.count >= 2
urn.take
i += 1
end
puts "Finished in #{i} turns for #{init_count} pebbles."
p urn.pebbles
# Dijkstra's implementation
b = 10
w = 10
until b + w <= 2 do
b -= 1
b -= 1 if b >= 2
if w >= 2
w -= 2
b += 1
end
end
puts "Finished, b: #{b} w: #{w}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment