r/dailyprogrammer • 2 0 • Mar 02 '18

Weekly #28 - Mini Challenges

So this week, let's do some mini challenges. Too small for an easy but great for a mini challenge. Here is your chance to post some good warm up mini challenges. How it works. Start a new main thread in here.

if you post a challenge, here's a template we've used before from /u/lengau for anyone wanting to post challenges (you can copy/paste this text rather than having to get the source):

**[CHALLENGE NAME]** - [CHALLENGE DESCRIPTION]

**Given:** [INPUT DESCRIPTION]

**Output:** [EXPECTED OUTPUT DESCRIPTION]

**Special:** [ANY POSSIBLE SPECIAL INSTRUCTIONS]

**Challenge input:** [SAMPLE INPUT]

If you want to solve a mini challenge you reply in that thread. Simple. Keep checking back all week as people will keep posting challenges and solve the ones you want.

Please check other mini challenges before posting one to avoid duplications (within reason).

97 Upvotes

55 comments sorted by

View all comments

Show parent comment

3

u/[deleted] Mar 02 '18 edited Mar 02 '18

Haskell

recaman :: Int -> [Int]
recaman 0 = [0]
recaman n =
  let n' = recaman (n - 1)
      nl = last n'
  in
    if nl - n >= 0 && (not $ any (==nl-n) n') then
      n' ++ [nl - n]
    else
      n' ++ [nl + n]

nth_recaman :: Int -> Int
nth_recaman = last . recaman       

2

u/macgillebride Mar 04 '18

Haskell as well, but defining the list recursively

import Data.List (inits)
import Data.Foldable (for_)

recamans = 0 : [let x  = recamans !! (i-1) - i
                    x' = recamans !! (i-1) + i
                in if x > 0 &&
                      not (x `elem` (inits recamans) !! i)
                   then x
                   else x' | i <- [1..]]

main :: IO ()
main = do
  for_ [5, 15, 25, 100, 1005] $ \i ->
    putStrLn . show $ recamans !! i