0

I need to search in a Sorted Matrix which is to be inserted using List<List<Integer>> arr . I am able to find a solution but not using List<List>>.

This is what i have tried but not working out

public class SearchMat {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        List<Integer> arrList = new ArrayList<Integer>();
        while (scanner.hasNextIint()) {
            arrList.add(scanner.nextInt());
        }

        List<List<Integer>> array = new ArrayList<List<Integer>>();
        for(List<Integer> list : arrList){
            array.addAll(list);
        }
    }  
} 
Diogo Almiro
  • 363
  • 3
  • 15
  • 1
    Can you specify an example with an input and desired output? – MaxG Dec 07 '19 at 19:44
  • if you take input `int` by `int` from `Scanner` how would you know when is the end of one array and the start of another? – MaxG Dec 07 '19 at 20:07
  • i think this is duplicated consult this : https://stackoverflow.com/questions/2457792/how-do-i-search-for-a-number-in-a-2d-array-sorted-left-to-right-and-top-to-botto – Mahmoud Turki Dec 07 '19 at 20:12

1 Answers1

0

Imagine the following input: 10 20 15 25 Your current code would create a 1x4 matrix like:

+-----------------+      +-----------------+      +-------------+
|  List (size 1)  | ---> |  List (size 4)  | ---> | 10 20 15 25 |
+-----------------+      +-----------------+      +-------------+

What you would wish for should look like this:

+-----------------+      +-----------------+      +-------+
|  List (size 2)  | -+-> |  List (size 2)  | ---> | 10 20 |
+-----------------+  |   +-----------------+      +-------+
                     |   +-----------------+      +-------+
                     +-> |  List (size 2   | ---> | 15 25 |
                         +-----------------+      +-------+

You also don't have any kind of way of Sorting the input neither knowing how long should your matrix be.

If you were assuming that the input was sorted and that your line should only have 4 columns this would create the 2D matrix Nx4 representation that you want:

List<List<Integer>> matrix = new ArrayList<List<Integer>>();
while (scanner.hasNextIint()) {
    List<Integer> list = new ArrayList<Integer>();
    for(int i=0; i<4; i++){
        list.add(scanner.nextInt());
    }
    matrix.add(list);
}

Hope this leads you in the right direction.

Diogo Almiro
  • 363
  • 3
  • 15