Last active
September 25, 2018 10:16
-
-
Save jessereynolds/d97947f62152e782ab44eda0af87067c 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 | |
# Attempt to do an imperical proof of my answer to the following homework question: | |
# | |
# Find the number of ways in which seven different toys can be given to three children, | |
# if the youngest is to receive three toys, and the others receive two toys each. | |
# | |
require 'set' | |
toys = [:a, :b, :c, :d, :e, :f, :g] | |
puts "Here are all the toys: #{toys}" | |
kids = {:summer => 3, :grace => 2, :isabelle => 2} | |
puts "Here are the kids and how many toys they can have: #{kids}" | |
allocations = Set.new | |
got_to_210_at = nil | |
# Lets repeat the following block a lot (this is a loop) | |
(1..2000).each do |i| | |
# How many combinations have we found already? | |
found = allocations.size | |
# First we get a randomised ordering of the toys | |
shuffled_toys = toys.sample(7) | |
# Then we divvy them up 3 for summer, 2 for grace, 2 for isabelle | |
# We are using a Set to for each child's collection as ordering is | |
# unimportant. ie [:a, :b, :c] is equal to [:b, :c, :a] | |
new_lot = { | |
:summer => Set.new(shuffled_toys[0..2]), | |
:grace => Set.new(shuffled_toys[3..4]), | |
:isabelle => Set.new(shuffled_toys[5..6]), | |
} | |
# Finall we add this new distribution to the allocation set | |
# If this exact combination (distribution) already exists in the | |
# allocations set then it will not be added again, cause it's a set | |
# and sets can't have two members that are the same | |
allocations.add new_lot | |
# Output a summary of where we are at: | |
print "Iteration: #{i} " | |
print "New Allocation: #{shuffled_toys} - #{allocations.size}" unless found == allocations.size | |
puts | |
# How many iterations did it take to get to find 210 allocations? | |
unless got_to_210_at and allocations.size == 210 | |
got_to_210_at = i | |
end | |
end | |
puts "Hit 210 unique allocations after #{got_to_210_at} iterations" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment