How to detect repeated values in array of integer and create a new one with them in java? -


everybody, thankful if me in question. point have initial array "a" bunch of numbers, of them can repeat many times, of them - once. task create new array "b" consists of repeated numbers. if number array "a" repeats more once - in array "b" must reflected once. sequence of elements in new array shoulb same in initial. instance:

*initial array "a": 2 3 3 4 5 6 9 2 7 3 3   new array "b": 2 3*  

i have decided generate array "a" randomly every time, it's without difficulties, regards defining repretitions have problems. thing have done found repeated numbers.and result have right

*initial array "a": 2 3 3 4 5 6 9 2 7 3 3         new array "b": 2 3 3 3*  

my code:

import java.util.*;  public class processingtool  {  public static int[] arraycreatingmethod(){      random rand = new random();      int myarraydim = rand.nextint(50);      int [] myarray  = new int [myarraydim];       (int i=0; i<myarray.length;i++){          myarray[i] = (int)(math.random()*(100));       }  return myarray;  }  public static int[] newarraycreatingmethod(int[] a) {      int[] d = new int [a.length];      int k = 0;     int repetitions = 0;       (int = 0; i<a.length;i++){           int j = i;          int current = a[i];                        while (j<a.length-1) {                 if (current == a[j+1]) {                   d[k] = current;                      k++;                  repetitions++;                  break;               }                else {                   k=k-1+1;               }               j++;           }      }      system.out.print("\n"+repetitions+"\n");     system.out.println("\narray d: ");     (int ww = 0; ww<d.length; ww++){          system.out.print(d[ww]+" ");      } 

here's quick solution. navigates through every element in array a check see if occurs more once, , if does, adds hashset.

import java.util.arrays; import java.util.hashset; import java.util.set;   public class intcount {      int [] = new int [] {2,3,3,4,5,6,9,2,7,3,3};      public intcount()     {         set<integer> b = new hashset<integer>();         (int : a)         {             if (containstwice(i))                 b.add(i);         }         system.out.println(arrays.tostring(b.toarray()));     }      boolean containstwice(int i)     {         int count = 0;         (int j : a)         {             if (j == i)                 count++;         }         return (count > 1);     }      public static void main(string [] args)     {         new intcount();     } } 

output: [2, 3]


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -