Adding a range of numbers to a Java array [duplicate] - java

This question already has answers here:
How can I generate a list or array of sequential integers in Java?
(9 answers)
Closed 5 years ago.
I am relatively new to Java programming and am trying to create an array with values from (2017 - 3017).
I was wondering if there is a way to create an array and have it pre-filled with these values so instead of doing:
int[] anArray = {2017, 2018, 2019, 2020... 3017}
which seems extremely long-winded, I can simply define a range of integers I wish to add to the array.
I know there are similar question to this one on the site, however none of them have answers that help me.
Thanks!
Edit: I forgot to mention I am using Java 7 and therefore cannot use IntStream.

How about this:
int[] anArray = IntStream.rangeClosed(2017, 3017).toArray(); //closed includes upper bound
Java 7 would simply require a loop to fill the array:
int min = 2017, max = 3017;
int count = max - min + 1; //we're including upper bound
int[] anArray = new int[count];
for (int i = 0; i < count; i++, min++) {
anArray[i] = min; //reused and incremented min
}

Well it is answered. But just to point out another way in java .. you can count the number of integers that will be coming and use iterator to fill the array.Let me know if you have any doubts in this In short I am saying to do like the following:
int arr[] = new int[1001];
for(int i=2017;i<=3017;i++){
arr[i-2017]=i;
}

Related

How to create an int[] with fixed length and specific number with java stream? [duplicate]

This question already has answers here:
How do I fill arrays in Java?
(8 answers)
Closed 4 years ago.
I know how to get an int[] with a range of numbers:
int[] array = IntStream.of(0, 3).toArray();
But how can I get it with fixed length and one specific number?
IntStream.generate(() -> x).limit(y)
is what you need. Replace x and y with any number you like and you will produce a stream that has y lots of the number x.
You can obviously then call toArray or do whatever operation you want.
IntStream.generate creates an infinite stream using the supplier.
Here's one way:
int[] array = IntStream.rangeClosed(1, n).map(x -> m).toArray();
should produce an array of length n filled with m.
The following Q&A has other answers that use other approaches, such as the Arrays.fill method.
How do I fill arrays in Java?
Or simpler again.
// n elements of value m
int[]a=new int[n];
Arrays.fill(a,m);
Or even simpler with an API that was written for that:
int[] arr = new int[10];
Arrays.setAll(arr, x -> 1);
// or if you have enough data for parallel to make any difference
Arrays.parallelSetAll(arr, x -> 1);

generating random numbers without duplicates in java [duplicate]

This question already has answers here:
Creating random numbers with no duplicates
(20 answers)
Closed 7 years ago.
So I am generating random coordinates on a given grid that contains x number of rows and y number of columns. Let's say I want to generate 25 random numbers on a 8 by 6 grid.(8 columns, 6 rows)
I wrote piece of code like this and it is only partially working because this code does not excludes duplicates:
int intputRows =6;
int inputColumns=8;
Random randomNumGenerator = new Random();
for(int i=0;i<25;i++){
int randomRows = randomNumGenerator.nextInt(inputRows);
int randomColumns = randomNumGenerator.nextInt(inputColumns);
}
My question is, how do I avoid to generate duplicate numbers? I understand there are ways like put those in a List structure and shuffle, but could I done it with Random generator?
Just use a Set:
int intputRows =6;
int inputColumns=8;
HashSet<Integer> set = new HashSet<>();
Random randomNumGenerator = new Random();
int temp;
for(int i=0;i<25;i++){
temp = randomNumGenerator.nextInt(inputRows);
if(set.add(temp))
int randomRows = temp;
temp = randomNumGenerator.nextInt(inputRows);
if(set.add(temp))
int randomColumns = temp;
}
You still have to implement an else, in case it already exists, but I just gave you the idea.
Simple add the numbers to a Set, for example a HashSet, which cannot contain duplicate values, until your Set hat the desired length.
Set<Integer> randomNumbers = new HashSet<Integer>();
while(randomNumbers.size() < 25) {
randomNumbers.add( randomNumGenerator.nextInt(inputRows) );
}
Of course some checks would be nice to test that there is a chance that the code will finish, etc.

how can we reduce the size of a character array in Java? [duplicate]

This question already has answers here:
Delete item from array and shrink array [duplicate]
(9 answers)
How to efficiently remove duplicates from an array without using Set
(48 answers)
Closed 7 years ago.
There are ways in which we can reduce the array size using a new array. But I want to know how we can do it without using an additional array.
Once an array is created, you cannot change the size. You can either create a new Array, or use an ArrayList (internally, however, the ArrayList creates a new array, but this is hidden from you).
did you mean to reduce element size of array ?
if yes, i think the only way to do it using copy the original array to new array that have smaller size.
Arrays are static in size. When you initialize an array with a given size, it will always have that size. Think of an Array as an egg carton. It may or may not have eggs in each of its slots, but it will always have 12 slots (or 6 or 18 or however many).
As far as deleting duplicates, you can replace duplicates you encounter with null, which makes the slot "empty".
public static void deleteDuplicates(Character[] arr){
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < i; j++){
if(arr[j] != null && arr[j].equals(arr[i]){
//Found duplicate - delete duplicate and stop searching
arr[i] = null;
break;
}
}
}

Select a random int that doesn't exist [duplicate]

This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 8 years ago.
I am doing something where I have to choose a couple random numbers, without choosing the same number again. I have tried many ways, but they will not work. I checked if the random number exists in my int[], and reset the int to another random, but what is that other random also exists, I tried fixing that but I ran into problems.
Here's my current code:
p.sendMessage("debug over max");
Random r = new Random();
for (int i=0;i<max + 1;i++) {
int ran = r.nextInt(arenaAmount);
if (ran == 0) ran = 1;
arenas[i] = ran;
}
Thats what I have so far,
so how can I make sure it doesn't have the same number. If there is another thread already please link me to it.
Thanks, Joey.
A simple solution would be to add the already generated numbers to a Set and generate random numbers until you hit one that isn't already in that Set.
But that's probably not a very good solution, check the accepted answer here for a thorough explanation.
As mentioned by Giovanni Botta in the comments, here's another simple solution that's probably better than the Set based one.
make a arenas a Set
Random r = new Random();
int ran = r.nextInt();
while( ! arenas.add(ran) ) {
ran = r.nextInt();
}
add will fail on an attempted re-entry of a value.
You could create a list of integers from 1 to maxValue, shuffle it and get the numElements first elements:
List<Integer> shuffledList(int maxValue, int numElements) {
if (numElements >= maxValue) {
throw new IllegalArgumentException("The number of elements in the list must be less than maxValue.");
}
List<Integer> numbers = range(1, maxValue);
Collections.shuffle(numbers);
return numbers.subList(0, numElements);
}
List<Integer> range(int from, int to) {
List<Integer> numbers = new ArrayList<>(to - from);
for (int i = from; i < to; i++) {
numbers.add(i);
}
return numbers;
}
This way, you are sure to get different numbers without the Set overhead. Making a call like shuffledList(10, 5) would, for example, return a list like [8, 7, 5, 1, 2], with 5 elements, where the smallest possible element is 1 and the greatest possible element is 9.
Also, if you are using Java 8 you can discard the range function and do this instead:
List<Integer> numbers = IntStream.range(1, maxValue)
.boxed()
.collect(Collectors.toList());

How to initialize a list of integers [duplicate]

This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 8 years ago.
I need to create a list of available television channels (identified by integers). I am thinking that I would begin by creating int [] list = 5,9,12,19,64. Here is the code:
public NotVeryGoodTV(int[] channels) {
int [] list =5,9,12,19,64;
but I am getting a syntax error stating that a { is needed after "=". I would like to have a list of tv channels that would be available to the user once they turned on their television.
This is syntactically correct (instead of your array declaration):
int[] list = {5, 9, 12, 19, 64};
But it is not random, if you want to create an array with random integers:
Random randGen = new Random(); //random generator: import java.util.Random;
int maxChanNumber=64; //upper bound of channel numbers (inclusive)
int minChanNumber=1; //lower bound of channel numbers (inclusive)
int amountOfChans=5; //number of channels
int[] list = new int[amountOfChans]; //create an array of the right size
for (int k=0;k<amountOfChans;k++) //populate array
list[k]=minChanNumber+randGen.nextInt(maxChanNumber-minChanNumber+1);
Actually this codes does NOT check if you generate a different channel number (integer) for every item of the array: it is possible that in the array you will find two or more times the same number, but it is not difficult to adapt the code to avoid this, anyway the direction to take to have really random channel numbers is this one.
Replace:
int [] list =5,9,12,19,64;
With:
int[] list = { 5,9,12,19,64 };
The brackets tell Java that you are declaring a list.
However the numbers are not random; they are the ssame every time.
replace line 2:
int [] list =5,9,12,19,64;
with this code:
int[] list = {5,9,12,19,64};
Yep, you need to encase the list in curly braces like this:
int [] list = {5, 9, 12, 19, 64};
Just proper Java syntax issues.

Categories