Pairs

Objective: Write program code to create, traverse, and manipulate elements in 1D array or ArrayList objects.

Given a list of numbers (stored in an array), complete the method that will generate all the NumberPairobjects that are stored in an ArrayList. This problem forces you to work with both an array and an ArrayList! It is important to understand the differences in using these two data structures.

For example, if a list contained [1 2 3], all the possible pairs are 1&2, 1&3, and 2&3. These are all unique NumberPairs.
The NumberPairclass is shown below.

public class NumberPair extends Pair{
    public NumberPair(int a, int b){ /* implementation not shown */ }
}
public class Pair{


    private int a, b;
    public Pair(int a, int b){
       this.a = a;
       this.b = b;
    }
    public int getA(){ return a;}
    public int getB(){ return b;}

}

Do you need to generate pair indexes to pair up values in an array or list? You can use the following for-loop to do so which would limit it to unique index pairs. Because the inner for loop is initialized to the outer loops index variable + 1, the nested loop will never generate the same pairs.

for(int index1 = 0; index1 < arr.length; index1++){
   for(int index2 = index1+1; index2 < arr.length; index2++){

   }
}

The following are methods of a list that can be used to manipulate the contained data.

Type your solution        
Skills Practiced:
3.A
3.C
3.D
4.A
4.B
Copyright © StudyCS 2024 All rights reserved.