Eliud's Eggs
Count the 1 bits in the binary form of a number, without a built-in bit count.
Adapted from Exercism’s problem specification (MIT). Listed under Numbers & Math.
// FILE: eliuds_eggs.nomi
//# Counts the eggs in Eliud's coop from the number its display shows.
/// Counts the 1 bits in the binary form of a non-negative `number`: the
/// eggs in Eliud's coop, one bit per nest.
pub fn egg_count(number: Int) -> Int
Iter.iterate(number, &(&1 >>> 1))
|> Iter.take_while(&(&1 > 0))
|> Iter.map(&(&1 &&& 1))
|> Iter.sum()
end
// FILE: eliuds_eggs_test.nomi
import eliuds_eggs
test "counts the eggs"
[
("0 eggs", 0, 0),
("1 egg", 16, 1),
("4 eggs", 89, 4),
("13 eggs", 2000000000, 13),
]
|> subtests (description, number, expected), description
assert eliuds_eggs.egg_count(number) == expected
end
endok counts the eggs (4 cases)
test result: ok. 4 passed, 0 failed
How it’s written
Section titled “How it’s written”- The number is shifted right one bit at a time with
Iter.iterate(number, &(&1 >>> 1)), cut at zero, and each step’s low bit,&(&1 &&& 1), is summed. Every stage is one operator, so each is a capture. - The exercise forbids a built-in bit count, so the solution does not call
Int.bit_count(number), which returns the same. - A negative number counts as 0 eggs, since the chain stops before its first step. The exercise only has non-negative inputs.
- The four cases are one
subteststable.