Reputation: 101
public static int[] Separator1() {
for (int i = 0; i < numbersGenerated.length; i++) {
if (i % 2 == 0) {
numberSet1[i / 2] = numbersGenerated[i];
}
}
return numberSet1;
}
public static int[] Separator2() {
for (int i = 0; i < numbersGenerated.length; i++) {
if (i % 2 == 1) {
numberSet2[i / 2] = numbersGenerated[i];
}
}
return numberSet2;
}
In the code above, I can successfully produce indexes from even numbers for numberSet1
, but when I try to produce indexes for numberSet2
I cannot. The reason I cannot produce indexes for that array is because the numbers are odd. The [i / 2]
is just a place holder by the way because I have no idea what formula I could use to produce the indexes.
Example for Separator1
:
numbersGenerated = {10,20,30,40,50,60,70,80,90,100};
numberSet1
would return values of {10,30,50,70,90}
I want numberSet2
to return values of {20,40,60,80,100}
I am open to any suggestions because earlier I was actually trying to use one Separator and return 2 values from it and I found out that it would not work. The code just needs to be able to separate an array into 2 distinctive arrays with the same values from the first one.
Thank You, for your time :D
Upvotes: 1
Views: 155
Reputation: 168
I am pretty new to this and I would love for someone to give us an explanation why yours did not work. I thought i/2 by integer math would round down to the nearest integer. but give this a try.
public static int[] Separator2() {
int counter = 0;
for (int i = 0; i < numbersGenerated.length; i++) {
if (i % 2 == 1) {
numberSet2[counter] = numbersGenerated[i];
counter++;
}
}
return numberSet2;
Upvotes: 0
Reputation: 2560
I believe you're wanting to put numbers from even indexes into one collection and numbers from odd indexes into a separate collection. Example - indexes 0, 2, 4, 6, ... are returned from Seperator1
, and indexes 1, 3, 5, 7, ... are returned from Seperator2
.
Here is the basic logic.
public static int[] Separator1() {
for(int i = 0; i < numbersGenerated.length; i++) {
if (i % 2 == 0) { // Grabs even numbered indexes
numberSet1[i / 2] = numbersGenerated[i]; // Places even numbered indexes
}
}
return numberSet1;
}
public static int[] Separator2() {
for (int i = 0; i < numbersGenerated.length; i++) {
if (i % 2 != 0) { // Odd numbered indexes
numberSet2[(i - 1) / 2] = numbersGenerated[i]; // Places odd numbered indexes
}
}
return numberSet2;
}
(i - 1) / 2
Example:
For index 1 | ((1 - 1) / 2) = 0
For index 3 | ((3 - 1) / 2) = 1
For index 5 | ((5 - 1) / 2) = 2
....
You might want to consider renaming the methods to something like getEvenIndexes
and getOddIndexes
in the future to avoid confusion.
Side Note: Java convention has method names start with a lowercase letter - this will make it easier for other people to read your code.
Upvotes: 1