Java - Get repeated array elements and their repetition number -


i want extract , count repeated array elements in example:

int arr []= {7,4,3,0,2,0,5,2,13,2,0,3}; 

the output should

2 repeated 3 times

0 repeated 3 times

3 repeated 2 times

there trial code in java:

public static void repeated(int x[]){         int i, j;         int counter = 0;         for(i=0 ; i<x.length ; i++ ){             boolean isrepeat = false;             for(j=i-1 ; j>=0 ; j--){                 if(x[i] == x[j]){                     isrepeat = true;                     counter++;                 }             }             if(isrepeat){                 counter = counter+1;                 system.out.println(x[i] + " repeated " + counter + " times");                 counter = 0;             }         }     }      public static void main(string[] args) {         int arr []= {7,4,3,0,2,0,5,2,13,2,0,3};         repeated(arr);     } 

but output is:

0 repeated 2 times

2 repeated 2 times

2 repeated 3 times

0 repeated 3 times

3 repeated 2 times

i have developed new code based on help, new code solved first problem:

public static void repeated(int x[]){         int i, j;         for(i=0 ; i<x.length ; i++ ){             int isrepeat = 1;             for(j=i-1 ; j>=0 ; j--){                 if(x[i] == x[j]){                     isrepeat ++;                 }             }             if(isrepeat == 2){                 system.out.println(x[i] + " repeated " + "? times");             }          }     }      public static void main(string[] args) {         int arr []= {7,4,3,0,2,0,5,2,13,2,0,3};         repeated(arr);     } 

then output:

0 repeated ? times

2 repeated ? times

3 repeated ? times

still counter want without lists or hashmap

  1. create hashmap<integer, integer>.
  2. for each number in arr check if it's in map.keyset. if yes, increment value. if not add one.
  3. for key in map.keyset if value > 1, print key + " repeated " + value + " times\n"

Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -