# Detect rotated strings

Read two strings from stdin.
Output Yes if one string is a rotated version of the other.
Otherwise output No

Testcases

Input

CodeGolf GolfCode


Output

Yes


Input

stackexchange changestackex


Output

Yes


Input

stackexchange changestack


Output

No


Input

Hello World


Output

No

• So (abcdefAB, ABabcdef) is a "YES"? Mar 9, 2011 at 12:06
• Should it really be a rotation or is a combination fine too? eg. what will Stackexchange Stackchangeex return? Mar 9, 2011 at 12:08
• @Eelvex, yes. @jpjacobs, It would return No. The rotation is a shift, like those LED scrolling signs Mar 9, 2011 at 12:19
• Are the strings always whitespace-free and separated by whitespace?
– Joey
Mar 9, 2011 at 15:20
• More specifically, what characters are allowed in those strings?
– Joey
Mar 9, 2011 at 15:48

## Python 2, 86 Characters

a,b=raw_input().split()
print"Yes"if any(a==b[n:]+b[:n]for n in range(len(a)))else"No"


## Perl (just a quick fix)

A fix to rubber boots' solution, being a new user that I am I can't comment yet so I'll just post a new answer.

As the mentioned method uses a regular expression constructed from user input, it is possible to perform a small regex injection, as follows:

> perl -le '$.=pop;$_=(pop)x2;print+(qw/yes no/)[!/$./]' anything '.*' yes  The fix is to use \Q (known also as quotemeta): > perl -le '$.=pop;$_=(pop)x2;print+(qw/yes no/)[!/\Q$./]' anything '.*'
no


The code itself could be further shortened using 'say' but this is left as an exercise to the reader :)

• Furthermore, instead of print+(qw/yes no/)[ you can probably write print qw(yes no)[ which is two characters shorter. Apr 12, 2011 at 22:58

# Clojure, 95

The function rotated? simply tests one string against all possible rotations of the other. Brute force.

(defn rotated?
[a b]
(let[l (count a)
b (seq b)]
(->> a cycle (partition l 1) (take l) (some #{b}))))


I personally don't care where the input strings come from, but if it has to be stdin...

(apply rotated? (.split (read-line) " "))


This would add 38 to character count, if strings were whitespace separated.

(rotated? (read-line) (read-line))


This would add 32 to character count, if strings were newline separated. The function rotated? works with any characters in the strings.

Fixed to say Yes/No and improved (91 chars)

import List;f[a,b]|aelem[x++y|x<-tails b|y<-inits b]="Yes";f _="No";main=interact$f.words  original Haskell (92 chars) that says True/False import Data.List;f(a:b:_)=any(a==)$zipWith(++)(tails b)(inits b);main=interact(show.f.words)

• You can save a few characters with import List and also by using $ instead of parens around the argument to interact. But your program outputs True and False instead of the required Yes and No, so that might take a few extra chars to fix. – user1011 Apr 15, 2011 at 3:38 # Bash, 706559 55 characters new approach: read a b;c=$a$a;[[${c/$b/} ==$a ]]&&echo yes||echo no

• solution 2 fails on echo ofofo fofof | bash rotated.sh - doesn't it? Else I would remove even more WS: read a b[[ $a$a =~ $b&&${#a}-eq${#b} ]]&& echo yes||echo no. I had a very similar idea, and think it works. May 30, 2012 at 6:21 • You're right, more ws can be removed, and the paratheses! Need a ; after the read tho. May 30, 2012 at 14:16 • @userunknown - hah, got'cha ;) May 31, 2012 at 23:13 • You can remove a blank before and one behind ==. Jun 1, 2012 at 3:41 • I tried, but then it always return 'yes'. Jun 7, 2012 at 14:46 ## JavaScript - 66 p=prompt,a=p(),b=p();alert(!b.match(a)&&!!b+b.match(a)?'Yes':'No')  • 1) This says True for “foo” and “foot”. 2) The output has to be “Yes” or “No”. The other participants spent great amount of code to produce the required output. Please do so. Oct 18, 2013 at 13:46 • Is the problem true/false or that 'foo' is not a rotation of 'foot'? Oct 18, 2013 at 13:51 • 1) Giving wrong result for “foo” and “foot”, is a bug. 2) Producing different output then required, is just deviation. Many answers fail to conform with the requirements in various degrees – some got downvoted, others not. Is up to you to decide whether you risk some downvotes or correct them. Oct 18, 2013 at 14:27 • Should be working now. Oct 18, 2013 at 14:38 • Much better. It gives “Yes” for “foo” and “.*”, but as the question owner still not replied to the comment about allowed characters, let us suppose that only the character classed used in the samples are allowed. Oct 18, 2013 at 15:01 # 05AB1E, 20 bytes Code: DgFÀD²Qi"Yes",q}}"No  Uses CP-1252 encoding. Try it online! • The builtins and features of 05AB1E have improved quite a bit over the years. :) 13 bytes is now possible Nov 19, 2019 at 14:57 # Jelly, 16 bytes ɠJṙ@€ɠe@ị“Yes“No  Try it online! Many thanks to @cairdcoinheringaahing and @MrXcoder for helping me out in chat. Explanation: ɠ # The first string ṙ@€ # Rotated by... J # The indexes of each element in the string ɠ # The second string e@ # Exists in that list of strings. # (either '0' or '1') ị # Indexed into the list... “Yes“No # ["yes", "no"]  # jq -Rn, 62 + 4 = 65 bytes len('if[inputs|explode|sort|implode]|.[0]==.[1]then"Yes"else"No"end')  As in the accepted answer, the two strings should be on separate lines. -R is used to avoid having to quote the input strings, and -n is used to disable the default input processing because inputs takes care of that. # Stax, 11 bytes Ä:∩ö┌┘/YJTI  Run and debug it This program takes input on two lines. Unpacked, ungolfed, and commented, it looks like this. :( get all rotations s|# other input is a member of rotations? n! "Yes" .No "No" ? (a ? b : c)  Run this one # C (gcc), 118113 111 bytes -5 bytes thanks to ceilingcat i,l,r;f(s,t)char*s,*t;{for(l=r=0,i=strlen(s);i--;)r=strncmp(s+i,t,++l)|strncmp(s,t+l,i)?r:3;puts(r+"No\0Yes");}  Try it online! # PHP, 57 bytes Input via space-delimited string on STDIN, output to STDOUT is "Yes" or "No" string. <?=strpos(($a=explode(' ',$argn))[1].$a[1],$a[0])?Yes:No;  Try it online! Or with Default I/O input via command line args and output truthy/falsey. # PHP, 37 bytes <?=strpos(($a=$argv)[2].$a[2],$a[1]);  Try it online! Or as a function: # PHP, 41 bytes function($a,$b){return strpos($b.$b,$a);}


Try it online!

• 36 bytes Nov 24, 2019 at 12:29
• 27 bytes using PHP 7.4 arrow functions Nov 24, 2019 at 12:30

# K3 / Kona, 28

{:[y _in![;x]'!#x;Yes;No]}


# Pyth, 18 bytes

?}zm.<QdlQ"YES""NO


Try it online

### Explanation

?}zm.<QdlQ"YES""NO
m   dlQ            For each number in [1, ..., len(first input)]...
.<Q               ... rotate the first input that many characters.
}z                   Check if the second input is in that list.
?         "YES""NO    Return "YES" or "NO" appropriately.


# Brachylog, 17 bytes

~c₂ᵐ↔ᵈ∧"Yes"|∧"No


Try it online!

(If the input strictly has to be whitespace-separated, add two bytes to prepend ṇ₁, but note that the input still has to be quoted. Brachylog does not have any sort of direct access to stdin.)

Takes input as a list of two strings, and outputs through the output variable. The actual logic is all in the first six bytes, which succeed if the elements of the input are rotations of each other, and fail if they are not:

   ᵐ      Both strings in the input
~c₂       can be split into two pieces each
↔ᵈ    such that one string's two chunks are the other's swapped.


(↔ᵈ could just as well be pᵈ, pᵛ, or oᵛ which is what it was originally before I decided that ↔ᵈ is more to the point.)

Although it would be possible to brute force rotating one of them until it matches, the number of rotations would need to be explicitly bounded, and on top of that just the effort required to separate out the two elements of the input list would be fairly costly. Since it's very easy to brute force partitions in Brachylog, the fact that a rotation is just as much taking one chunk off one end and moving it to the other as it is doing that to single characters however many times saves a lot of bytes.

With very flexible I/O, this could be as short as 5 bytes, taking one string through the input variable and the other through the output variable: ~c₂↔c

# 05AB1E, 13 bytes

ā._Êßi„Noë”…Ü


Explanation:

ā         # Push a list in the range [0, length] for the (implicit) input-string,
# without popping this input-string itself
#  i.e. "CodeGolf" → [1,2,3,4,5,6,7,8]
._       # Rotate the string that many times towards the left (vectorized)
#  "CodeGolf" and [1,2,3,4,5,6,7,8] → ["olfCodeG","lfCodeGo","fCodeGol","CodeGolf",
#                                      "odeGolfC","deGolfCo","eGolfCod","GolfCode"]
Ê      # Check for each whether it's NOT equal to the second (implicit) input-string
#  "GolfCode" → [1,1,1,0,1,1,1,1]
ß     # Pop and push the minimum (to check if any are falsey)
#  [1,1,1,0,1,1,1,1] → 0 (falsey)
i    # If this minimum is truthy (so all rotations were unequal to the second input):
„No #  Push string "No"
ë    # Else:
”…Ü #  Push dictionary string "Yes"
# (after which the result is output implicitly)


See this 05AB1E tip of mine (section How to use the dictionary?) to understand why ”…Ü is "Yes".