Efficient mapping of a variable to a value stored in an array

I was looking for other topics with a similar problem, but I could not find a single one applicable to me. If I have a variable that has some value, and an array that has a list of values ​​... is it possible for me efficiently (effective time, space is not a limitation), find out the index of the array when the variable matches the element of the array?

I get a variable from reading from a massive file, and brute force repeating every opportunity would mean several million iterations. I am ready to do this as a last resort, but I would rather not do it. :)

I program in C if the algorithm depends on it. I have no way to program in C ++ / Python. Thanks!

Edit: the value that I want to combine with the array falls into pairs (x, y). If the array matches x or y, I process (x, y). But it is very important that the order does not change if I have to sort it, for example.

+4
source share
1 answer

If space is not a concern, and you want to know if a value is contained in an array, you can do something like this:

  • First create a new array. Let me call the old v[ ] , the new w[ ] , and let i be your iterator through v[ ] .

  • Now do w[v[i]] = 1 and the rest of w[ ] = 0 . This basically says "if x is a value in array v[ ], then w[x] = 1 ". (Note: if you declare w[ ] globally, all its positions will be initialized to 0, by default)

  • Whenever you want to check the value contained in v[ ] , check w[value] . If it is 1, then the answer is yes.

If you do a lot of checking for an array, this should work very well. Note that w[ ] can be quite large in size.

Edit: if you want to keep the index, you can replace the 1 in w[ ] with the actual positions - if the values ​​do not repeat, this works well.

+2
source

Source: https://habr.com/ru/post/1441317/


All Articles