Let’s say I have an increasing sequence of integers: seq = [1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 4 … ] not guaranteed to have exactly the same number of each integer but guaranteed to be increasing by 1.
Is there a function F that can operate on this sequence whereby F(seq, x) would give me all 1’s when an integer in the sequence equals x and all other integers would be 0.
For example:
t = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4]
F(t, 2) = [0, 0, 0, 0, 1, 1, 0, 0, 0, 0]
EDIT: I probably should have made it more clear. Is there a solution where I can do some algebraic operations on the entire array to get the desired result, without iterating over it?
So, I’m wondering if I can do something like: F(t, x) = t op x ?
In Python (t is a numpy.array) it could be:
(t * -1) % x or something…
EDIT2: I found out that the identity function I(t[i] == x) is acceptable to use as an algebraic operation. Sorry, I did not know about identity functions.
There’s a very simple solution to this that doesn’t require most of the restrictions you place upon the domain. Just create a new array of the same size, loop through and test for equality between the element in the array and the value you want to compare against. When they’re the same, set the corresponding element in the new array to 1. Otherwise, set it to 0. The actual implementation depends on the language you’re working with, but should be fairly simple.
If we do take into account your domain, you can introduce a couple of optimisations. If you start with an array of zeroes, you only need to fill in the ones. You know you don’t need to start checking until the
(n - 1)th element, wherenis the value you’re comparing against, because there must be at least one of the numbers1tonin increasing order. If you don’t have to start at 1, you can still start at(n - start). Similarly, if you haven’t come across it atarray[n - 1], you can jumpn - array[n - 1]more elements. You can repeat this, skipping most of the elements, as much as you need to until you either hit the right value or the end of the list (if it’s not in there at all).After you finish dealing with the value you want, there’s no need to check the rest of the array, as you know it’ll always be increasing. So you can stop early too.