Every possibility: combinations
Chunky is packing for a trip to the mountains: three hats and two scarves. How many different outfits can he put together? Every hat goes with every scarf – and that is exactly what product builds: all pairs of one element from the first array and one from the second:
hats = ["top hat", "beanie", "straw hat"]
scarves = ["red", "checked"]
outfits = hats.product(scarves)
outfits.each { |hat, scarf| puts "#{hat} with a #{scarf} scarf" }
outfits.size3 hats times 2 scarves makes 6 outfits – in a product the numbers multiply, hence the name. Two dice work the same way: every number on the first with every number on the second. How often do they add up to 7?
die = (1..6).to_a
throws = die.product(die)
p throws.size
p throws.first(3)
throws.count { |a, b| a + b == 7 }6 out of 36 throws – one in six. No other total comes up that often; try 2 or 12.
Now a table tennis tournament: four foxes, and each one plays every other one once. product would get that wrong – Chunky would play against himself, and every match would turn up twice, Chunky against Kaz and Kaz against Chunky. combination(2) picks 2 at a time, and the order does not matter:
foxes = %w[Chunky Kaz Isi Bo]
foxes.combination(2).each do |a, b|
puts "#{a} against #{b}"
end
foxes.combination(2).countSix matches. At a party with 10 guests who all shake hands once, it is just the same: the first one shakes 9 hands, the second 8 new ones, then 7 … 10 · 9 / 2 = 45 in all – the same sum as for the comparisons in lesson 34. And combination(3) picks teams of three:
guests = (1..10).to_a
p guests.combination(2).count
p 10 * 9 / 2
guests.combination(3).countIn a selection all that counts is who is in it. On the bench in front of the bakery it also counts who sits where: permutation gives every order. For the left seat there are 3 foxes to choose from, for the middle one 2, for the right one the last – 3 · 2 · 1 = 6, the factorial 3! from lesson 30:
%w[Chunky Kaz Isi].permutation.each do |bench|
puts bench.join(" – ")
endWith the letters of a word, permutation gives every anagram. But watch out for repeated letters: to Ruby the two e's in “steel” are different elements, so every word comes out twice – uniq throws the duplicates away. And which anagrams are real words? That is how brute force works: try every possibility and keep what fits. A little dictionary decides:
dictionary = %w[sleet bacon steel toast]
candidates = "steel".chars.permutation.map(&:join)
p candidates.size
p candidates.uniq.size
candidates.uniq.select { |w| dictionary.include?(w) }120 candidates, 60 different ones, two hits. On a bike lock with three dials, each digit may come up more than once: repeated_permutation(3) gives orders with repetition, 10 · 10 · 10 = 1000 codes. Here a difference matters: count builds every possibility and counts them, size works the number out with the formula without building a single one. And how often do three dice add up to 10?
digits = (0..9).to_a
p digits.repeated_permutation(3).size
p digits.repeated_permutation(4).size
three_dice = (1..6).to_a.repeated_permutation(3)
three_dice.count { |t| t.sum == 10 }27 out of 216 throws. A four-digit PIN has 10,000 possibilities – that is why a phone locks after a few wrong tries. How fast such numbers grow, size shows without any waiting:
ten = (1..10).to_a
twenty = (1..20).to_a
p ten.permutation.size
p twenty.permutation.size
(1..49).to_a.combination(6).size # a lottery: 6 numbers out of 4910 foxes can stand in a row in 3.6 million ways, 20 in over 2 quintillion – count would never finish, and a lottery ticket has almost 14 million possible picks. The rule of thumb: a few thousand possibilities Ruby tries in no time, millions take seconds, and beyond that brute force no longer helps – count first (with size), then try. To remember: product = every with every, combination = choose (order doesn't matter), permutation = arrange (order counts), repeated_permutation = arrange with repetition.
pizzas(toppings, budget): every pizza with three different toppings that cost at most budget together – each one as an array of the three names. How many are there for 5 francs?toppings = { "bacon" => 3, "mushrooms" => 2, "pineapple" => 2,
"olives" => 1, "salami" => 3, "cheese" => 1 }
# def pizzas(toppings, budget)
# ... # every choice of three toppings that costs at most budget
# end
# pizzas(toppings, 5)
fair_teams(strengths): it splits the foxes into two teams of equal size whose total strengths differ as little as possible, and returns [team1, team2], two arrays of names. Try every choice of half the players as the first team – the second is the rest, names - team – and keep the fairest pair. It should work with four or eight foxes too.strengths = { "Chunky" => 7, "Kaz" => 3, "Isi" => 5,
"Bo" => 8, "Mo" => 2, "Lu" => 4 }
# def fair_teams(strengths)
# ... # every choice of half the players as team 1, the rest is team 2
# ... # the pair [team1, team2] whose strengths differ least
# end
# fair_teams(strengths)