Skip to content

Commit 51bba0a

Browse files
committed
Solve 'How Many Numbers?' kata
1 parent b439d33 commit 51bba0a

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/Codewars/G964/Howmany.hs

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
module Codewars.G964.Howmany (selNumber) where
2+
3+
-- https://www.codewars.com/kata/55d8aa568dec9fb9e200004a/train/haskell
4+
5+
selNumber :: Int -> Int -> Int
6+
selNumber n d = length $ makeNumbers n d
7+
8+
makeNumbers :: Int -> Int -> [Int]
9+
makeNumbers n d = filter valid numbers
10+
where
11+
numbers
12+
| n < d = [n + 1 .. d]
13+
| otherwise = [d .. n - 1]
14+
valid = isValid d
15+
16+
isValid :: Int -> Int -> Bool
17+
isValid d n
18+
| n < 10 = False
19+
| otherwise = isAscending d n
20+
21+
isAscending :: Int -> Int -> Bool
22+
isAscending d n = all (\x -> x <= d && x > 0) . zipWith (flip (-)) digits . tail $ digits
23+
where
24+
digits = toDigits n
25+
26+
toDigits :: (Integral a) => a -> [a]
27+
toDigits 0 = []
28+
toDigits n = toDigits (n `div` 10) ++ [n `mod` 10]

test/Codewars/G964/HowmanySpec.hs

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
module Codewars.G964.HowmanySpec where
2+
3+
import Codewars.G964.Howmany
4+
import Data.Char
5+
import Data.List
6+
import Test.Hspec
7+
import Test.QuickCheck
8+
import Text.Printf (printf)
9+
10+
testNb :: Int -> Int -> Int -> Spec
11+
testNb n d s =
12+
it (printf "should return selNumber for n d result : %d %d --> %d \n" n d s) $
13+
selNumber n d `shouldBe` s
14+
15+
spec :: Spec
16+
spec = do
17+
describe "selNumber small values" $ do
18+
testNb 0 1 0
19+
testNb 3 1 0
20+
testNb 13 1 1
21+
testNb 15 1 1
22+
testNb 20 2 2
23+
testNb 30 2 4
24+
testNb 44 2 6
25+
testNb 50 3 12
26+
testNb 100 3 21

0 commit comments

Comments
 (0)