Create Array of N Items Based on Integer Value

Create array of n items based on integer value

You can just splat a range:

[*1..10]
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Ruby 1.9 allows multiple splats, which is rather handy:

[*1..3, *?a..?c]
#=> [1, 2, 3, "a", "b", "c"]

How to create an array containing 1...N

If I get what you are after, you want an array of numbers 1..n that you can later loop through.

If this is all you need, can you do this instead?

var foo = new Array(45); // create an empty array with length 45

then when you want to use it... (un-optimized, just for example)

for(var i = 0; i < foo.length; i++){
document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>');
}

e.g. if you don't need to store anything in the array, you just need a container of the right length that you can iterate over... this might be easier.

See it in action here: http://jsfiddle.net/3kcvm/

Generate array with with range of integers

You can make use of the for ... range construct to make it more compact and maybe even faster:

lo, hi := 3, 6
s := make([]int, hi-lo+1)
for i := range s {
s[i] = i + lo
}

As a matter of curiosity, the loop can be implemented without a loop variable, but it will be slower, and the code longer. By decrementing hi:

for ; hi >= lo; hi-- {
s[hi-len(s)+1] = hi
}

Or incrementing lo:

for ; lo <= hi; lo++ {
s[len(s)-1-hi+lo] = lo
}

How to initialize an array of the first ten integers briefly?

You can use spread syntax in combination with keys() method.





console.log([ ...Array(10).keys() ]);

How to create array from 1 to n digit with single line of code in ruby

Convert a range into an array.

(1..n).to_a

Tersest way to create an array of integers from 1..20 in JavaScript


Favorite method

Update Sep13,2015:

Just came up with this new method which works with browsers which support the ES6 standard:

> Array(5).fill().map((x,i)=>i)
[0, 1, 2, 3, 4]

Note the above does a tiny bit of extra work (fills with undefined) but is relatively minor vis-a-vis the speedup you can achieve by using a for loop, and if you forget the .fill you may be confused why your array is mysteriously [empty x 5]. You can encapsulate the above as a custom function, or alternatively use a somewhat more intended method:

> Array.from(Array(5),(x,i)=>i)
[0, 1, 2, 3, 4]

You can of course directly go from that into whatever you want to do, like python's list comprehensions e.g. [i**2 for i in range(5)]:

> Array.from(Array(5), (_,i)=> i**2)
[0, 1, 4, 9, 16]

... or if you want to get more complicated...:

> Array.from(Array(5), (_,i)=> {
const R = /*some computation*/;
return /*etc*/;
});

[edit May,2021]: theoretically tersest way of defining such a function nowadays is f=i=>i?[...f(i-1),i]:[], where you replace f with range1 or whatever the name is, but which would be very slow (quadratic complexity) due to intermediate structures so should never be used. f=i=>i?f(i-1)&&x.push(i)&&x:x=[] is linear complexity but relies on abuse of notation and is unreadable and pollutes global variables as well. But, since defining arrow functions (which don't bind but rather inherit this) is pretty terse nowadays, you could just wrap the above solution:

const range1 = n=> Array.from(Array(n), (_,i)=> i+i);
// range1(5)==[1, 2, 3, 4, 5]

Circumstantially, the tersest way to do a range(N), if you already have a list lying around of exactly that length N, is just to map it: e.g. rather than do Array.from(Array(myArr.length), (_,i)=> i**2), you would just do myArr.map((_,i)=> i**2). (This has no side-effect unless you want it to.)


everything below is historical:

After thinking about it a bit, this is the shortest implementation of the standard range(N) function in JavaScript I could come up with:

function range1(i){return i?range1(i-1).concat(i):[]}

Note: Do not use this in production; it's O(N^2)

Contrast with current top-voted answer:

function range1(i){var x=[];var i=1;while(x.push(i++)<i){};return x}

Example:

> range1(5)
[1, 2, 3, 4, 5]

This is like the poster child for recursion, though I was expecting it to be longer until I thought of ternary-if-statement, which brings it down to 42 necessary characters.

Note that the "standard" range function returning [start,end) can be written by doing .concat(i-1).


Update: Ooh, I discovered an incredibly short version with ugly imperative syntax by abusing for loops, reverse-ordering, the fact that assignments return a value: for(y=[],i=20;y[--i]=i;){} consisting of only 25 characters (though you will want var y which you can insert into a for loop, and +1 if you don't want 0...19). While it is not shorter if you need to define a function, it is shorter than i?r(i-1).concat(i):[] if you do not need to make a function.


Added some performance profiling testcases: it seems that everything besides a standard in-order for-loop is 10x slower, at least on V8. https://jsperf.com/array-range-in-javascript
(Of course, none of this matters if you're programming in a functional style anyway and would hit every element with a function call anyway.)

How to create an array containing 1...N

If I get what you are after, you want an array of numbers 1..n that you can later loop through.

If this is all you need, can you do this instead?

var foo = new Array(45); // create an empty array with length 45

then when you want to use it... (un-optimized, just for example)

for(var i = 0; i < foo.length; i++){
document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>');
}

e.g. if you don't need to store anything in the array, you just need a container of the right length that you can iterate over... this might be easier.

See it in action here: http://jsfiddle.net/3kcvm/

How can I generate a list or array of sequential integers in Java?

With Java 8 it is so simple so it doesn't even need separate method anymore:

List<Integer> range = IntStream.rangeClosed(start, end)
.boxed().collect(Collectors.toList());

How would I make an array of all the integers between 0 and 1000?

I'm not sure it makes any sense to actually create the array from 1-1000, if all you are going to do is numbers[i], given that numbers[i] == i. Using just a single integer i, you can save yourself from wasting the extra space. If there is motivation other than what you have posted, you can do the following:

int numbers[1001];
for(int i = 0; i <= 1000; i++){
numbers[i] = i;
}


Related Topics



Leave a reply



Submit