Skip to content

Commit

Permalink
Solve 'How Many Numbers?' kata
Browse files Browse the repository at this point in the history
  • Loading branch information
borisskert committed Nov 15, 2024
1 parent b439d33 commit 51bba0a
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/Codewars/G964/Howmany.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
module Codewars.G964.Howmany (selNumber) where

-- https://www.codewars.com/kata/55d8aa568dec9fb9e200004a/train/haskell

selNumber :: Int -> Int -> Int
selNumber n d = length $ makeNumbers n d

makeNumbers :: Int -> Int -> [Int]
makeNumbers n d = filter valid numbers
where
numbers
| n < d = [n + 1 .. d]
| otherwise = [d .. n - 1]
valid = isValid d

isValid :: Int -> Int -> Bool
isValid d n
| n < 10 = False
| otherwise = isAscending d n

isAscending :: Int -> Int -> Bool
isAscending d n = all (\x -> x <= d && x > 0) . zipWith (flip (-)) digits . tail $ digits
where
digits = toDigits n

toDigits :: (Integral a) => a -> [a]
toDigits 0 = []
toDigits n = toDigits (n `div` 10) ++ [n `mod` 10]
26 changes: 26 additions & 0 deletions test/Codewars/G964/HowmanySpec.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
module Codewars.G964.HowmanySpec where

import Codewars.G964.Howmany
import Data.Char
import Data.List
import Test.Hspec
import Test.QuickCheck
import Text.Printf (printf)

testNb :: Int -> Int -> Int -> Spec
testNb n d s =
it (printf "should return selNumber for n d result : %d %d --> %d \n" n d s) $
selNumber n d `shouldBe` s

spec :: Spec
spec = do
describe "selNumber small values" $ do
testNb 0 1 0
testNb 3 1 0
testNb 13 1 1
testNb 15 1 1
testNb 20 2 2
testNb 30 2 4
testNb 44 2 6
testNb 50 3 12
testNb 100 3 21

0 comments on commit 51bba0a

Please sign in to comment.