Implement a FuzzyFinder
CJam, 18 15 bytes
{1$#)}q~2$,@$p;
Try it online in the CJam interpreter.
I/O
Input:
"mig" ["imig" "mig" "migd" "do" "Mig"]
Output:
["mig" "migd" "imig"]
How it works
q~ e# Read and evaluate the input from STDIN.
e# Pushes a needle and an array of haystacks.
{ } e# Define a code block:
1$ e# Copy the needle.
# e# Compute the index of the needle in the haystack.
) e# Add 1 to the index.
2$ e# Copy the block.
, e# Filter: Keep only haystacks for which the code block
e# pushed a non-zero value.
@ e# Rotate the block on top of the stack.
$ e# Sort: Arrange the haystacks according to the values
e# pushed by the code block.
p e# Print the filtered and sorted haystacks.
; e# Discard the needle.
Pyth, 9 bytes
oxNzf}zTQ
Try it online: Demonstration
Explanation:
implicit: z = input string, Q = input list
f Q filter Q for elements T, which satisfy:
}zT z is substring of T
o order the remaining strings N by:
xNz the index of z in N
Python 2, 65
def f(s,l):g=lambda x:x.find(s)+1;print sorted(filter(g,l),key=g)
The expression x.find(s)
returns the position of the first occurrence of s
in x
, giving -1
for no match. We add 1
to the result to that no-match corresponds to 0
, letting us filter
them out. We then sort by the match position, which is unaffected by shifting by 1.