Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill arrays with ranges of numbers

Tags:

java

arrays

Is there any syntax/package allowing quick filling of java arrays with ranges of numbers, like in perl?

e.g.

int[] arr = new int[1000]; arr=(1..500,301..400,1001..1400); // returns [1,2,3,4,...,500,301,302,...,400,1001,1002,...1400] 

Also, it here a package that allows getting the n-th number in such list of numbers as the above, without actually creating the array (which can be huge)?

e.g.

BunchOfRangesType bort = new BunchOfRangesType("1..500","301..400","1001..1400"); bort.get(0); // return 1 bort.get(500); // return 301 bort.get(501); // return 302 

It's not too difficult to implement, but I guess it might be common so maybe it was already done.

like image 821
David B Avatar asked Aug 02 '10 11:08

David B


People also ask

How do you create an array of numbers in ranges?

the Array. map() function is used to create a new array with a modified range of numbers. the Math. floor() function rounds a number down to the nearest integer, it's used in the last example to ensure a whole number is passed to the Array() function regardless of the step size.

How do you fill an array with values?

Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.


2 Answers

For those still looking for a solution:

In Java 8 or later, this can be answered trivially using Streams without any loops or additional libraries.

int[] range = IntStream.rangeClosed(1, 10).toArray(); 

This will produce an array with the integers from 1 to 10.

A more general solution that produces the same result is below. This can be made to produce any sequence by modifying the unary operator.

int[] range = IntStream.iterate(1, n -> n + 1).limit(10).toArray(); 
like image 61
Craig Avatar answered Sep 19 '22 17:09

Craig


There is dollar:

// build the List 10, 11, 12, 13, 14 List<Integer> list2 = $(10, 15).toList(); 

maven:

<dependency>         <groupId>org.bitbucket.dollar</groupId>         <artifactId>dollar</artifactId>         <version>1.0-beta3</version> </dependency> 
like image 20
True Soft Avatar answered Sep 18 '22 17:09

True Soft