Haskell, 91 89 bytes
i[x,y]|x`elem`(take.length<*>iterate(tail<>take 1))y="Yes";i _="No"
main=interact$i.words
I would add a link to try it online, but unfortunately, tio.run seems to have a version of Haskell that doesn't include (<>)
in the Prelude by default. I wrote this using GHC 9.4.8.
De-golfed version:
-- Because of the partial function `tail`,
-- `rotateOnce` throws an error for empty lists.
rotateOnce :: [a] -> [a]
rotateOnce xs = tail xs ++ take 1 xs
-- `allRotationsOf` never calls `rotateOnce` on an empty list, so it's okay.
allRotationsOf :: [a] -> [[a]]
allRotationsOf xs = take (length xs) (iterate rotateOnce xs)
-- Note: String is the same as [Char].
answer :: [String] -> String
answer [x, y]
| elem x (allRotationsOf y) = "Yes"
answer _ = "No"
main = interact (answer . words)
The function rotateOnce
rotates a list leftwards once. This comment explains how it's essentially equivalent to rotateOnce xs = tail xs ++ take 1 xs
, which means that it appends its first element to the very end. tail
essentially works like drop 1
except that an exception is thrown on an empty list, but it's shorter. It returns the list it was given, but with the first element removed.
The function iterate
is from the standard library. iterate f x
evaluates to an infinite list [x, f x, f (f x), ...]
, and so on. So, iterate rotateOnce xs
just keeps generating rotations of the list xs
.
To ensure the program terminates, it stops after the infinite list has generated as many elements as there are in the original list, because a list of n
elements can only be rotated n
times before repetitions are encountered.
Using the Monad instance for functions, \x -> f (g x) (h x)
can be rewritten liftM2 f g h
, which is equivalent to f <$> g <*> h
. The operator (<$>)
is a synonym for fmap
, and for functions, fmap
is just the function composition operator, so it can be rewritten f . g <*> h
to save characters. That's why take (length xs) (iterate rotateOnce xs)
can be rewritten like that in the golfed version.
So anyway, using the functions described, the program just checks if y
is some rotation of x
. If so, the string "Yes" is returned, otherwise "No" is returned. And that's it.
Stackexchange Stackchangeex
return? \$\endgroup\$No
. The rotation is a shift, like those LED scrolling signs \$\endgroup\$