DEV Community

loading...

Discussion on: Daily Challenge #278 - Find all non-consecutive numbers

Collapse
cipharius profile image
Valts Liepiņš

Haskell solution:

import Data.Foldable (foldl')

data IndexedNumber = IndexedNumber
  { index :: Int
  , number :: Int
  } deriving Show

nconsecutive :: [Int] -> [IndexedNumber]
nconsecutive xs = reverse $ foldl' compute [] indexedPairs
  where
    indexedPairs = zip3 [1..] xs (tail xs)
    compute result (i, x, x')
      | x' - x == 1 = result
      | otherwise   = (IndexedNumber i x') : result

Test results:

> nconsecutive [6,7,8,9,11,12]
[IndexedNumber {index = 4, number = 11}]

> nconsecutive [100,101,102,112,113,114,129]
[IndexedNumber {index = 3, number = 112},IndexedNumber {index = 6, number = 129}]