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!
Discussion (29)
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).
Nice, and kudos for typing it out on a phone 😀
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:
Javascript, just using a for loop
Codepen
Clojure short and simple
and some tests...
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:
Golfscript:
Usage:
Or if we don't need a function just
Explanation:
,
takes the top of the stack and turns it into an array from 0 to n - 1.{1+}
is a block adding 1 to each argument and%
is the map function. The surrounding{}
turns everything into a block which we assign (:
) to the namespread
.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.
Python
Simple JS
Ruby solution below. We could also return a Range directly, but here I'm being purist with the exercise.
GO
C++
Rust
Playground
Javascript
Zero based ;)
Elm