Not able to write code for Print how many times has a number repeated in following array | Selenium Forum
M
Misbah Siddiqui Posted on 30/06/2019

Print how many times has a number repeated in following array
int x[] ={1,3,4,5,6,3,2,4,6,7,9,4,12,3,4,6,8,9,7,6,43,2,4,7,7,5,2,1,3,4,6,311,1};

The problem is that it checks the next number with the following numbers without skipping it, or without knowing it has written it before.

Please find my code in aatchment


A
Ashish Thakur Replied on 01/07/2019

Check the code below.

public class RepetitionInArray {
	public static void main(String[] args) {
		int x[] = { 1, 3, 4, 5, 6, 3, 2, 4, 6, 7, 9, 4, 12, 3, 4, 6, 8, 9, 7, 6, 43, 2, 4, 7, 7, 5, 2, 1, 3, 4, 6, 311, 1 };
		for (int i = 0; i < x.length; i++) {
			int c1 = 0;
			for (int j = i + 1; j < x.length; j++) {
				if (x[i] == x[j]) {
					c1 = c1 + 1;
				}
			}
			System.out.println(x[i] + " has been repeated " + c1 + " times");
		}
	}
}


M
Misbah Siddiqui Replied on 01/07/2019

still not getting he desired output

I am getting the following output with the provided code

1 has been repeated 2 times
3 has been repeated 3 times
4 has been repeated 5 times
5 has been repeated 1 times
6 has been repeated 4 times
3 has been repeated 2 times
2 has been repeated 2 times
4 has been repeated 4 times
6 has been repeated 3 times
7 has been repeated 3 times
9 has been repeated 1 times
4 has been repeated 3 times
12 has been repeated 0 times
3 has been repeated 1 times
4 has been repeated 2 times
6 has been repeated 2 times
8 has been repeated 0 times
9 has been repeated 0 times
7 has been repeated 2 times
6 has been repeated 1 times
43 has been repeated 0 times
2 has been repeated 1 times
4 has been repeated 1 times
7 has been repeated 1 times
7 has been repeated 0 times
5 has been repeated 0 times
2 has been repeated 0 times
1 has been repeated 1 times
3 has been repeated 0 times
4 has been repeated 0 times
6 has been repeated 0 times
311 has been repeated 0 times
1 has been repeated 0 times


A
Ashish Thakur Replied on 02/07/2019

In this case, you need to arrange the elements first then start comparing them with the last one. If it matches, then increase the count and if it doesn't match then it means you have the max count of the last number.