Search code examples
javaloopssearchmultidimensional-arrayliterate-programming

How to find match to given variable and assigning while 2D array iteration?


I have an array of the bellow style (2D) (just a dummy set of data);

int array [][]= {{1.0, 20.0},
                 {2.0, 40.0},
                 {3.0, 60.0},
                 {4.0, 80.0}}

I have in my program another variable

double v = 3.2;

I now want to compare the col1 values in the array with the value v. I want to find the closest value for v and assign the corresponding value in col2 as a new variable new_v

so for above example I should get below;

since v = 3.2 and is closest to the value 3 in array[3][1] position, I would then assign as follows;

double new_v = array[3][2]; 

How would you go about this problem? Would be great if someone could help me out on how to compare and find the closest value. (it would be easier to find the exact match by using if loop and find if it matches exactly, but this has gotten me thinking...)

Would be great if I could get some pointers! Thanks


Solution

  • I've used C# since it seemed like you're using something similar to that language. If, however, this gives you problems to understand my approach feel free to tell me what programming language would be easier for you to understand.

    My approach would be the following:

            double currentClosest = array[0][0];
    
            for(int row = 0; row < array.Length; row++){
                if(Math.Abs(v - array[row][0]) < Math.Abs(v - currentClosest)){
                    new_v = array[row][1];
                    currentClosest = array[row][0];
                }
            }
    

    The for-loop is only iterating through each row. Then the absolute difference between the first column in said row and the given value v is compared to the same difference for the saved currentClosest. If this new value in the first column is closer than the current closest, the code saves that value as the new currentClosest and the new_v is set to the corresponding value in the second column.

    You can try the whole scenario here.

    I hope that answered your question.