I was looking over some basic questions that might be asked in an interview. Using basic for loops (No hash maps etc)I want to sum up all the matching elements in an array.For example, 6 matching elements will result in (Matched: 6) and a total of 36 in the example below.An example of this could be rolling dice, and the score is the total of all the dice that match.
public static void main(String[] args) { int arr[] = {6,6,6,6,6,6}; int matched = 1; int value = 0; int total = 0; for(int i=0;i<arr.length;i++){ for(int j=(i+1);j<arr.length;j++){ if(ar[i] == ar[j]){ matched++; value = ar[i]; break; } } total = (matched * value); } // End for loop System.out.println("Matched:"+(matched)+""); System.out.println("Total:"+total); } But, if the array was for example...
int arr[] = {6,1,1,6,6,6}; The output I get will be (Matched:5) and an a total of 30.Can could I store the matching pair of 1's and add them to the total using as little basic code as possible?
{6,1,1,6,6,6}result in (Matched:5) and an a total of 30?{6,1,1,6,6,6}and{5,6,1,1,6,6,6}probably should yield the same result.