Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding two pairs from integer array out of two elements

Tags:

java

algorithm

Two pairs: If there are two pairs of dice with the same number, the player scores the sum of these dice. If not, the player scores 0. For example, 1, 1, 2, 3, 3 placed on "two pairs" gives 8.

examples: 1,1,2,3,3 results 8 1,1,2,3,4 results 0 1,1,2,2,2 results 6

How can find this efficiently?

I've been using following code to find a single pair

int max_difference = 0;
int val1 = 0 , val2 = 0;
Arrays.sort(dice);
for (int i = 0; i < dice.length - 1; i++) {
    int x = dice[i+1] - dice[i];
    if(x <= max_difference) {
        max_difference = x;
        val1 = dice[i];
        val2 = dice[i+1];

    }
}
pairScore = val1 + val2;
like image 949
Om Komawar Avatar asked Aug 30 '26 04:08

Om Komawar


2 Answers

No need to make it that complicated, since you're only searching for the resulting number...

int prev = 0;
int result = 0;
int pairs = 0;

Arrays.sort(dice);
for (int i = 0; i < dice.length; i++) 
{
    int current = dice[i];
    if (current == prev) 
    {
        result += current*2;
        pairs++;
        prev = 0;
    } 
    else prev = current;
}

if (pairs == 2) return result;
else return 0;
like image 85
Mark Avatar answered Aug 31 '26 19:08

Mark


I'd use a frequency map, i.e. the number is the key and the value is a counter (so a Map<Integer, Integer>). However, since it is used for dices you could simplify that using an array with a length equal to the maximum dice value (6 for standard dice). Then check the frequencies for each number and get the number of pairs from it.

Example:

int[] diceFrequency = new int[6];

//assuming d is in the range [1,6]
for( int d : dice ) {
  //increment the counter for the dice value
  diceFrequency[d-1]++; 
}

int numberOfPairs = 0;
int pairSum = 0;

for( int i = 0; i < diceFrequency.length; i++ ) {
  //due to integer division you get only the number of pairs, 
  //i.e. if you have 3x 1 you get 1 pair, for 5x 1 you get 2 pairs
  int num = diceFrequency[i] / 2;

  //total the number of pairs is just increases
  numberOfPairs += num; 

  //the total value of those pairs is the dice value (i+1) 
  //multiplied by the number of pairs and 2 (since it's a pair)
  pairSum += (i + 1 ) * 2 * num;
}

if( numerOfPairs >= 2 ) {
  //you have at least 2 pairs, do whatever is appropriate
}
like image 24
Thomas Avatar answered Aug 31 '26 17:08

Thomas