photo credit: pasukaru76 via photopin cc
I recently heard about a cool idea for a code kata from a couple of friends of mine. It does not have too many rules, but is more interesting than plain old FizzBuzz. The kata is about validating Finnish Business ID.
Spec
In Finland all companies must have a business id. The id consists of seven digits and a checksum digit separated by dash. Example of a valid Business ID would be 1572860-0. The rules for counting the checksum are following:
- the seven digits are multiplied individually using the following multipliers: 7, 9, 10, 5, 8, 4, 2
- Result of weighting are summed together
- Sum is divided by 11. If the remainder is 0, checksum is 0. Otherwise checksum is 11 - remainder.
Special case: Older Business IDs have only six numbers before checksum, these are padded with leading zero. For example, 000012-3 becomes 0000012-3
Here is the source for these rules (in Finnish): http://tarkistusmerkit.teppovuori.fi/tarkmerk.htm#y-tunnus2
Implementation
I used this kata to write my first program in Haskell.
module Main where
import Test.HUnit
import Data.Char
import Text.Regex.Posix
validate businessId =
if correctFormat
then calculatedCheckSum == givenCheckSum businessId
else False
where correctFormat = businessId =~ "(^[0-9]{6,7})-([0-9])" :: Bool
paddedBusinessId =
case length(businessId) of 8 -> ['0'] ++ businessId
9 -> businessId
idPart = map digitToInt . take 7
weightedList = sum . zipWith (*) [7, 9, 10, 5, 8, 4, 2] . idPart
sumModulo = weightedList paddedBusinessId `mod` 11
calculatedCheckSum
| sumModulo == 0 = 0
| otherwise = 11 - sumModulo
givenCheckSum = digitToInt . last
tests = TestList [
TestCase (assertBool "valid Business Id ending in 0"
(validate "1572860-0")),
TestCase (assertEqual "invalid Business id" False
(validate "0737546-3")),
TestCase (assertBool "when checksum not 0"
(validate "0737546-2")),
TestCase (assertBool "when short pad with 0"
(validate "000012-3")),
TestCase (assertEqual "when too short" False
(validate "1234"))
]
main = runTestTT tests
Software professional with a passion for quality. Likes TDD and working in agile teams. Has worked with wide-range of technologies, backend and frontend, from C++ to Javascript. Currently very interested in functional programming.