Single letter swaps
Write a function that takes a sequence of strings and a target string. For each string in the sequence, determine if it is equal to the target string after exactly one letter swap. Return the sequence of letter pairs that are swapped, or nil if it doesn't exist.
Example
(letter-swaps ["bacd" "abdc" "abcde" "abcc" "abcd"] "abcd")
;=> [#{\a \b} #{\c \d} nil nil nil]
Swapping a and b in "bacd" gives you the target string. Swapping c and d in "abdc" gives you the target string. But there is no way to swap to get an extra e. And trading a d for a c is not possible. Finally, the last string has no swaps, and exactly one is required.
Thanks to this site for the problem idea, where it is rated Very Hard in PHP. The problem has been modified.
Please submit your solutions as comments on this gist.
To subscribe: https://purelyfunctional.tv/newsletter/
Oh! Does the swap not have to be sequential? i.e. should the answer to
"dbca"
benil
or#{\a \d}
?EDIT: According to the original PHP problem, the answer should be
#{\a \d}
, i.e. the swap doesn't have to be of two sequential characters. Which means my solution is not only clunky, it's also wrong 😭Still, useful practice 😅
@wevre FWIW according to that original problem you can assume the letters in the target to be unique
EDIT: Updated mine, but it's really just a variation on @steffan-westcott's solution, which I think is super elegant!