Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

searching in n 2-dimensional arrays

Help with how to implement searching on n 2-dimenssional arrays. To be more specific: If I have 6 tables and I am putting these into a 2-dimensional array.I will provide a value say 10 like how val=0 here. I need to search from these tables all the combination values that make up 10. The value will be computed taking values from all these tables.

public static int Main() {
  int[] a = {2,1,4,7};
  int[] b = {3,-3,-8,0};
  int[] c = {-1,-4,-7,6};
  int sum;
  int i; int j;  int k;
  int val = 0;
  for(i = 0; i < 4; i++) {
    for(j = 0;j<4;j++) {
      for(k = 0;k<4;k++) {
        sum = a[i]* b[j]* c[k];

        if(sum == val)
          System.out.printf("%d  %d  %d\n",a[i],b[j],c[k]);
      }
    }
  }
}
like image 774
user756742 Avatar asked Nov 17 '25 23:11

user756742


1 Answers

Following will be the code you require:

(The solution includes recursion making your problem go easier)

private ArrayList numbers = new ArrayList();

public void CalculateSum(int tableNumber)
{
    if(!Tables.isLast(tableNumber))
    {
        int[][] a = Tables.Get(tableNumber);
        for(int y = 0; y < a.length; y++)
        {
            for(int x = 0; x < a[y].length; x++)
            {
                numbers.add(a[y][x]);
                CalculateSum(tableNumber + 1);
                numbers.remove(tableNumber - 1);
            }
        }
    }else
    {
        int[][] a = Tables.Get(tableNumber);
        for(int y = 0; y < a.length; y++)
        {
            for(int x = 0; x < a[y].length; x++)
            {
                if((sum(numbers) + a[y][x]) == checkValue)
                {
                    PrintNumbers(numbers);
                    System.out.print(a[y][x]);
                    System.out.println();
                }
            }
        }
    }        
}

You need to implement a class ('Tables' as my solution) write methods:

boolean isLast(int tableNo): to check whether the given table is the last table your tables list

int[][] Get(int tableNo): to get the table with the specified index

Also the method sum should sum the values in the numbers ArrayList. PrintNumbers method should print the numbers in the numbers ArrayList in a row. checkValue is the value you want to check.

Hope this helps....

Please write if you want any clarification on this algorithm.

like image 130
Dulini Atapattu Avatar answered Nov 20 '25 13:11

Dulini Atapattu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!