1

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.

0

3 Answers 3

4

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));
Sign up to request clarification or add additional context in comments.

1 Comment

@JonSkeet Edited, my mistake.
0

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];
}

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.