Setup
Implement a function that will create an array and fill it with numbers ranging from 1
to n
. The numbers will always be positive.
Examples
spreadNumber(1)
=> [1]
spreadNumber(2)
=> [1, 2]
spreadNumber(5)
=> [1, 2, 3, 4, 5]
Tests
spreadNumber(3)
spreadNumber(6)
spreadNumber(9)
Good luck!
This challenge comes from linisnie on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (27)
JavaScript:
That creates an Array from 0 to n not from 1 to n ;-)
const spreadNumber = n => Array(n).fill(0).map((_, i) => i+1);
Yeah, i didnt notice its not zero based
I think you have an off-by-one error:
spreadNumber(2)
gives[0, 1]
instead of[1, 2]
. Nice and concise, though!Thanks. I didnt notice its zero based
Another way:
Haskell, many ways
This challenge was simple, so here's a brainfuck solution too. Only works with characters 1-9 as inputs (I have an idea for reading multidigit numbers as input, but I'm on my phone and don't want to type it out).
Python
this will not work, it doesn't include the last digit:
spreadNumber(4)
=>[1, 2, 3]
you forgot to add
+1
onn
You are right, I didnt take that in consideration, but it just range(1,n+1)
Late to the party, as always.
Example:
Javascript, just using a for loop
Codepen
Clojure short and simple
and some tests...
dart
lol damn, while this is one way, looking at other solutions. I forgot range was a thing.
Python, shortest approach
you could've use just
range
like this:Elixir
Haskell
The easiest challenge yet.