Classic puzzles
Some little problems are so famous that programmers all over the world know them: they turn up in coding clubs, job interviews and maths competitions alike. In the loops lesson you already met FizzBuzz in disguise, and in the strings lesson a palindrome – a word that reads the same backwards. Here is a better palindrome test, one that ignores capitals, spaces and punctuation, so that whole sentences count. delete("^a-z") deletes everything that is not a small letter:
def palindrome?(text)
letters = text.downcase.delete("^a-z")
letters == letters.reverse
end
p palindrome?("Racecar")
p palindrome?("bacon")
palindrome?("Was it a car or a cat I saw?")Two words are anagrams when they are made of exactly the same letters: “listen” and “silent”. The trick: sort the letters of both words and compare – sorting from lesson 17 does all the work:
def anagram?(a, b)
a.downcase.chars.sort == b.downcase.chars.sort
end
p anagram?("listen", "silent")
p anagram?("Dormitory", "dirtyroom")
anagram?("bacon", "bagel")A prime is a number above 1 that only 1 and itself divide without a remainder: 2, 3, 5, 7, 11 … To test a number, try every divisor from 2 upwards – and you can stop at its square root, because a bigger divisor would have a smaller partner you have tried already. none? is true when the block is true for none of them:
def prime?(n)
return false if n < 2
(2..Math.sqrt(n)).none? { |d| n % d == 0 }
end
(1..50).select { |n| prime?(n) }And now a puzzle that nobody in the world has solved, the Collatz conjecture. Take any positive number. If it is even, halve it; if it is odd, triple it and add 1. Repeat. So far every number has ended at 1 – mathematicians have checked numbers far beyond a billion billion – but nobody has proved that every number must. Step through the cell with ⏯ and watch 27 climb:
n = 27
steps = 0
while n != 1
n = n.even? ? n / 2 : 3 * n + 1
steps += 1
end
steps27 needs 111 steps and climbs as high as 9232 on the way – try other starting numbers. Puzzles like these are perfect practice: short, easy to check, and there is always a second way to solve them.
perfect?(n) and find all perfect numbers up to 500. (There are only three – and the ancient Greeks already knew them.)# def perfect?(n)
# ... # true when the divisors of n below n add up to n
# end
# (1..500).select { |n| perfect?(n) }
goldbach(n), which returns the first pair [p, q] of primes with p + q == n, the smaller one first: goldbach(28) is [5, 23]. prime? from above helps.# def goldbach(n)
# ... # the first pair of primes [p, q] with p + q == n, the smaller one first
# end
# goldbach(28)