loading...

Daily Challenge #194 - Spread Number

thepracticaldev profile image dev.to staff ・1 min read

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

pic
Editor guide
Collapse
craigmc08 profile image
Craig McIlwrath

Haskell, many ways

spreadNumber n = [1..n]
spreadNumber = enumFromTo 1
spreadNumber = flip take [1..]

-- The most flexible way
spreadEnum :: Enum a => a -> a
spreadEnum = enumFromTo $ toEnum 1
Collapse
craigmc08 profile image
Craig McIlwrath

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).

,>++++++[-<-------->>++++++++<]<[->>+.<<]
Collapse
citizen428 profile image
Michael Kohl

Nice, and kudos for typing it out on a phone 😀

Collapse
sag1v profile image
Sagiv ben giat

JavaScript:

const spreadNumber = n => [...Array(n).keys()]
Collapse
jeroencornelissen profile image
Jeroen Cornelissen

That creates an Array from 0 to n not from 1 to n ;-)

const spreadNumber = n => Array(n).fill(0).map((_, i) => i+1);

Collapse
sag1v profile image
Sagiv ben giat

Yeah, i didnt notice its not zero based

Collapse
dwilmer profile image
Daan Wilmer

I think you have an off-by-one error: spreadNumber(2) gives [0, 1] instead of [1, 2]. Nice and concise, though!

Collapse
sag1v profile image
Sagiv ben giat

Thanks. I didnt notice its zero based

Collapse
mellen profile image
Matt Ellen

Another way:

const spreadNumber = n => Array.from({length:n}).map((_, i) => i+1);
Collapse
centanomics profile image
Cent

Javascript, just using a for loop


const spreadNumber = (number) => {
  let returnArray = [];

  for (let i = 0; i < number; i++) {
    returnArray.push(i+1);
  }

  return returnArray;
}

Codepen

Collapse
not_jffrydsr profile image
@nobody

Clojure short and simple

(ns daily-challenge.one-ninety-four)

(defn spreadNumber [n]
;; precondition check to bound domain
 {:pre [(> 0 n)]}

  (unless (= n 1)
   (vec (range 1 n))
   [1])) 

and some tests...

(deftest one-ninety-four
  (is (= [1 2 3] (spreadNumber 3)))
  (is (= [1 2 3 4 5 6] (spreadNumber 6)))
  (is (= [1 2 3 4 5 6 7 8 9] (spreadNumber 9))))


(run-tests 'daily-challenge.one-ninety-four)

=> Testing daily-challenge.one-ninety-four

Ran 1 tests containing 3 assertions.
0 failures, 0 errors.
{:type :summary, :test 1, :pass 3, :fail 0, :error 0}
Collapse
mendoza profile image
David Mendoza

Python

def spreadNumber(n):
    return range(1,n+1)
Collapse
rafaacioly profile image
Rafael Acioly

this will not work, it doesn't include the last digit:

spreadNumber(4) => [1, 2, 3]

you forgot to add +1 on n

Collapse
mendoza profile image
David Mendoza

You are right, I didnt take that in consideration, but it just range(1,n+1)

Collapse
madstk1 profile image
Natamo

Late to the party, as always.

Func<int, int[]> SpreadNumber = (int n) => Enumerable.Range(1, n).ToArray();

Example:

foreach(int i in SpreadNumber(10)) {
    Console.WriteLine(i);
}
Collapse
citizen428 profile image
Michael Kohl

Golfscript:

{,{1+}%}:spread;

Usage:

5 spread

Or if we don't need a function just

5,{1+}%

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 name spread.

Collapse
exts profile image
Lamonte

dart

List<int> spreadNumber(int n) {
  var nums = List<int>();
  for(var x = 1; x <= n.abs(); x++) {
    nums.add(x);
  }
  return nums;
}

lol damn, while this is one way, looking at other solutions. I forgot range was a thing.

List<int> spreadNumber(int n) {
  return List<int>.generate(n.abs(), (n) => n + 1);
}
Collapse
kzivic profile image
Kosta Zivic

Python, shortest approach

lambda  x: [i+1 for i in range(x)]
Collapse
rafaacioly profile image
Rafael Acioly

you could've use just range like this:

lambda x: range(1, x+1)
Collapse
savagepixie profile image
SavagePixie

Elixir

def spread_number(n), do: Enum.to_list 1..n
Collapse
avalander profile image
Avalander

Haskell

The easiest challenge yet.

spreadNumber :: Int -> [Int]
spreadNumber n = [1..n]
Collapse
maskedman99 profile image
Rohit Prasad

Python

var = int(input("Enter the number: "))
l = list(range(1,var+1))
print(l)
Collapse
sabbin profile image
Sabin Pandelovitch

Simple JS

const spreadNumber = nr => Array.from({ length: nr }, (i, n) => n + 1);
Collapse
eduardio profile image
Eduard Giménez

Ruby solution below. We could also return a Range directly, but here I'm being purist with the exercise.

def spreadNumber(n)
   Array(1..n)
end
Collapse
nijeesh4all profile image
Nijeesh Joshy

GO

func main() {
    x := spreadNumber(10)
    fmt.Println(x)
}

func spreadNumber(n int) []int {
    ar := make([]int, n)
    for i := range ar {
        ar[i] = i + 1
    }
    return ar
}
Collapse
vidit1999 profile image
Vidit Sarkar

C++

vector<int> spreadNumber(int number){
    vector<int> v(number);
    generate(v.begin(),v.end(),[i=1]()mutable{return i++;});
    return v;
}
Collapse
jay profile image
Jay

Rust

fn spread(n: u32) -> Vec<u32> {
    (1..n + 1).collect()
}

Playground

Collapse
nilsandrey profile image
Nils Andrey

Javascript

spreadNumber = n => Array.from(Array(n).keys()).map(x => x+1);

Zero based ;)

spreadNumber = n => Array.from(Array(n).keys());
Collapse
aminnairi profile image
Amin

Elm

spreadNumber : Int -> List Int
spreadNumber integer =
    List.range 1 integer