Sumi Rabo
Sumi Rabo

Reputation: 19

how to copy elements in an array into sub arrays

I am trying do a grouping for a football tournament, but I don't know how to copy from the main array into sub arrays.

string [] groupings = {Arsenal, Chelsea, Barcelona, Real Madrid, Valencia, Juventus, Manchester United, Liverpool}

I want it in such a way that it will pick the first four and put in group one, and the last four in another group. e.g

string [] group 1={ Arsenal, Chelsea, Barcelona, Real Madrid }
String [] group 2={Valencia, Juventus, Manchester United, Liverpool}

Please can anyone help me with this I am still new to programming.

Upvotes: 1

Views: 137

Answers (3)

burglarhobbit
burglarhobbit

Reputation: 2291

You can write your algorithm like this...

String[] grp1 = new String[groupings.length/2];
String[] grp2 = new String[groupings.length/2];

for(int i = 0; i<groupings.length/2; i++) {
    grp1[i] = groupings[i];
    grp2[i] = groupings[(groupings.length/2)+i];
}

This will complete your task in just a single for loop and this algorithm will be dynamic for creating 2 groups for any given size of array(even).

Upvotes: 0

Wololo
Wololo

Reputation: 861

You can use loops. Like

string [] groupings = {Arsenal, Chelsea, Barcelona, Real Madrid, Valencia,
                       Juventus, Manchester United, Liverpool};
String[] grp1 = new String[4];
String[] grp2 = new String[4];
for(int i = 0; i<4; i++) {
  grp1[i] = groupings[i];
}
for(int i = 0; i<4; i++) {
  grp2[i] = groupings[4+i];
}

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

Use Arrays class copyOfRange method.

For ex :

        String[] grp1 = Arrays.copyOfRange(groupings, 0, groupings.length / 2);
        String[] grp2 = Arrays.copyOfRange(groupings, groupings.length / 2,
                groupings.length);

        System.out.println(Arrays.toString(grp1));
        System.out.println(Arrays.toString(grp2));

Upvotes: 4

Related Questions