-4

I put numbers of three people in one arraylist and in the case if three people have the same number then overall occurrences++; this is my algorithm but it is not working for this case!!

5 (first person has 5 nums)
13 20 22 43 146

4 (second person has 4 nums)
13 22 43 146

5 (third person has 5 nums)
13 43 67 89 146

int occurrences = 0;
for (int i = 0; i<n; ++i){
    for (int j = n; j<n+b; ++j ){
        if(arr.get(i)==arr.get(j)){
            System.out.println(arr.get(i)+" " +arr.get(j));
            for(int k=n+b; k<arr.size(); ++k){
                if(arr.get(j)==arr.get(k)){
                    ++occurrences;
                    System.out.println(arr.get(k));
                }
            }
        }
    }
}
GameDroids
  • 5,584
  • 6
  • 40
  • 59
halu
  • 195
  • 1
  • 1
  • 9

1 Answers1

1

try this if you have 3 array of 3 person

public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter numbers for 1st person seprated by ',' like 1,2,3....");
    String noForFirst = sc.nextLine();
    String[] a = noForFirst.split(",");
    System.out.println("Enter numbers for 2nd person seprated by ',' like 1,2,3....");
    String noForSecond = sc.nextLine();
    String[] b = noForSecond.split(",");
    System.out.println("Enter numbers for 3rd person seprated by ',' like 1,2,3....");
    String noForThird = sc.nextLine();
    String[] c = noForThird.split(",");
    int occurrences = 0;
    for (int i = 0; i < a.length; ++i) {
        for (int j = 0; j < b.length; ++j) {
            if (a[i].equals(b[j])) {
                for (int k = 0; k < c.length; ++k) {
                    if (a[i].equals(c[k])) {
                        ++occurrences;
                        System.out.println(a[i]);
                    }
                }
            }
        }
    }
    System.out.println("occurrences = " + occurrences);

Input

Enter numbers for 1st person seprated by ',' like 1,2,3.... 1,5,9,7,6 Enter numbers for 2nd person seprated by ',' like 1,2,3.... 1,4,8,7,3,5 Enter numbers for 3rd person seprated by ',' like 1,2,3.... 1,7,2

output

1 7 occurrences = 2

amit bhardwaj
  • 883
  • 2
  • 8
  • 18
  • yes this is ok, but what i need to get input from user and i don't know how many element each array will contain!!!! – halu Oct 30 '14 at 12:41
  • dosen't matter after taking input just put the values in differnt array and same code is good to go – amit bhardwaj Oct 30 '14 at 12:48