How do I search for a specific value in this table and return the other value in the tuple?

advertisements

I have a large array of (x,y) pairs:

 P = 

   [
    (0.0, 500000.09999999998),
    (0.001, 18.332777589999999),
    (0.002, 18.332221480000001),
    (0.0030000000000000001, 18.331665000000001),
    (0.0040000000000000001, 18.331108140000001),
    (0.0050000000000000001, 18.33055092),
    (0.0060000000000000001, 18.32999332),
    ...
    ]

I now need to use this in my code. I need to search for a specific x-value and, if the x-value exists, return its corresponding y-value.

Note: If there is a better format I could put my (x,y) pairs in, please feel free to let me know. For example, 2 separate arrays where one holds the x-values and the other holds the y-values. Then I could use the index to find the corresponding y-value or something.


Edit:

A user made a very good point in the comments: how can I reliably compare x == 0.001?

The way I will be using my code is this: I am evaluating a function f(x) at values of x. However, if at a particular value of x there is a y value in the P array, then I need to do an extra subtraction calculation (the details of which are not too important here). The problem, then, is that what if I pass the x value 0.001 in there and the P array does not have a correpsonding y value, but it does have one for 0.001000000009?? Then the code will say there is no value, but in reality it is reasonably close to the intended x value.


I'd suggest to let your array to be an array of CGPoints. It's simply:

A structure that contains a point in a two-dimensional coordinate system.

However, if you want to get the y values based on searching the x:

let myArray = [
    (0.0, 500000.09999999998),
    (0.001, 18.332777589999999),
    (0.002, 18.332221480000001),
    (0.0030000000000000001, 18.331665000000001),
    (0.0040000000000000001, 18.331108140000001),
    (0.0050000000000000001, 18.33055092),
    (0.0060000000000000001, 18.32999332),
]

// this array should contains y values for a given x value
// for example, I search the x value of 0.0
let yValues = myArray.filter { $0.0 == 0.0 }.map { $0.1 }

print(yValues) // [500000.09999999998]

Hope this helped.