Home > Net >  How to get the expected array with the below input
How to get the expected array with the below input

Time:03-04

Input: {1,1,2,3,3,4}(array can be dynamic) expected output:{{1,1},{2},{3,3},{4}}

I created a 2d array and iterated the input using 'for' loop but got stuck after that.

//code

class TestArrays { public static void main(String[] args) {

//declaring Array

    int[] numArr = {1,1,2,3,3,3,4};
    
    boolean flagValue=false;
    Arrays.sort(numArr);
    int length = numArr.length-1;
    int maxValue = numArr[length];

   int [][] arr = new int [maxValue][];
    
    for(int i = 0; i<=numArr.length-1;i  ){ //{1,1,2,3,3,3,4};
    
       for(int j=1;j<=maxValue;j  ){      //{1,2,3,4}
          
          if( numArr[i]==j) {
                        
                        arr[i][arr[i].length]=numArr[i];
                        flagValue=true;
                        System.out.print(arr[i][j]);
                    }   
          
       }
    }

CodePudding user response:

It's a bit of a rewrite but here's a working answer

//code

class TestArrays {
    public static void main(String[] args) {

        //declaring Array

        int[] numArr = {1,1,2,3,3,3,4};
        //Arrays.sort(numArr);
        int length = numArr.length-1;
        int maxValue = numArr[length];
        int [][] arr = new int [maxValue][];
        int c = 0;//only useful if you can be missing a number
        for(int i = 0; i<numArr.length;i  ){ //{1,1,2,3,3,3,4};
            int num = 1;//number of a certain number
            for(int j=i 1;j<numArr.length;j  ){      //{1,2,3,4}
                if( numArr[i]==numArr[j]) {
                    num  ;
                }
            }
            arr[c] = new int[num];
            for (int j = 0; j< num; j  ){//adding above mentioned numbers
                arr[c][j] = numArr[i j];
            }
            c  ;
            i = num-1;//moving to next set
        }
    }
}

CodePudding user response:

I understand that you want to group integers together. This can be done like this

public static void main(String[] args) {
    int[] numArr = {1, 1, 2, 3, 3, 3, 4};
    Map<Integer, List<Integer>> map = new HashMap<>();
    for (int num : numArr) {
        map.computeIfAbsent(num, idx -> new ArrayList<>()).add(num); //get list with given number. Create new one if there is no list in the map yet
    }
    List<List<Integer>> ret = map.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList()); //transform map to a list of list
    System.out.println(ret);
}

which prints [[1, 1], [2], [3, 3, 3], [4]]

  • Related