Inspired by this SO post.
Given a vector (first parameter), e.g.:
char = ["A", "B", "C", "A", "A"]
For each element of the vector, find the distance to the closest subsequent specified value (second parameter). When the element is identical to the specified value, return 0.
f(char, "A") -> [0 2 1 0 0]
Explanation
f(char, "A")
returns [0 2 1 0 0]
because f
returns the distance to the closest following value that equals "A". The first value of char
is "A", so as the element is equal to the desired value, return 0. For the second element, "B", the closest "A" is two positions away from it (position 4 - position 2 = 2). For the third element "C", the closest subsequent "A" is 1 position away from it.
When there are no subsequent values that match the specified value, return nothing. When the specified value is not part of the vector, the function can either return an empty vector or throw an error.
The function should work for string vectors or integer vectors.
Tests
char = ["A", "B", "C", "A", "A"]
f(char, "B") -> [1 0]
f(char, "C") -> [2 1 0]
f(char, "D") -> []
int = [1, 1, 0, 5, 2, 0, 0, 2]
f(int, 0) -> [2 1 0 2 1 0 0]
f(int, 1) -> [0 0]
f(int, 2) -> [4 3 2 1 0 2 1 0]
This is code-golf so the shortest code in each language wins.
AA
closer toAB
orBA
? Are we supposed to support strings longer than 1 character? \$\endgroup\$f(char, "AA")
will return[]
. Strings can be longer than one character. Is that clear? \$\endgroup\$