Identify and count duplicates in array ?
Hi guys I been trying this for almost 5 hours and I'm starting to get frustrated...
So, this is the problem, I have an array:
Code:
MR = new int[4][4];
Stored in the array I have 16 numbers from 1 to 20 but some of them maybe repeated, I need to identify which numbers are repeated and how many times.
Let´s say, "Number 3 has been found 4 times"... "Number 1 has been found 2 times"... "Number 9 has been found 0 times"
Here's the full code:
Code:
import java.awt.event.*;
import javax.swing.*;
public class arraysum extends JFrame implements ActionListener{
int i,ii;
int[][] M,M1,MR;
String arregloR="", arreglo1="", arreglo2="";
public arraysum(){
setLayout(null);
M = new int[4][4];
M1 = new int[4][4];
MR = new int[4][4];
for(i=0;i<=3;i++){
for(ii=0;ii<=3;ii++){
M[i][ii]=1 + (int) (Math.random() * 9);
M1[i][ii]=1 + (int) (Math.random() * 9);
MR[i][ii]=M[i][ii] + M1[i][ii];
}
}
}
public static void main(String[]args){
arraysum ventana=new arraysum();
ventana.setBounds(100,50,600,600);
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ventana.setVisible(true);
ventana.setResizable(false);
}
}
Thanks in advance :(handshake):
Re: Identify and count duplicates in array ?
What I would do, since you know the limitations of the values that can be held in the array, is construct a 1-dimensional array of size 20 (i.e. from 1 to 20, but may want to make it size 21 to avoid confusing indices and numbers). Each value will be initialized to 0. Then, go through every number in your 2-dimensional array and every time you encounter a number, increment the value in that index of the 1-dimensional array. At the end, go through that 1-dimensional array and print out any value over 1.
So, something like...
Code:
...
int[] counts = new int[21];
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
counts[ MR[i][j] ]++;
}
}
for(int i = 1; i < counts.length; i++)
{
if(counts[i] > 1)
{
System.out.println("Number " + i + " found " + counts[i] + " times.");
}
}
...
Re: Identify and count duplicates in array ?
Thanks a lot for your answer dude :(y): (I didn't see it before) :s:
But I finally figured out how to do it... I'll post the code as soon as I finish the whole idea.
Thanks again for answer I appreciate it.