g | x | w | all
Bytes Lang Time Link
035StackControl240804T140713ZШвеев Ал
134C240803T212907ZMaroonSp
021J230719T042821Zsouth
089Haskell240731T060946ZMaroonSp
076Haskell240802T215059Zxnor
055Raku230718T194430Zbb94
014Thunno 2230718T102051ZThe Thon
013Jelly171215T192513Zcaird co
057PHP191119T180806Z640KB
01305AB1E191119T145546ZKevin Cr
111C gcc171216T212909Zgastropn
011Stax190812T231442Zrecursiv
nanjq Rn190812T154201Zuser344
017Brachylog190812T022943ZUnrelate
018Pyth171215T204421Zuser4854
016Jelly171215T202533ZDJMcMayh
014Husk171215T201930Zბიმო
070Python110309T144516ZQuixotic
02005AB1E160510T121524ZAdnan
021CJam160510T160657ZA Simmon
025GolfScript140510T024638ZDennis
063Python131018T131923ZCoding m
066JavaScript131018T133735Ztristin
056bash120530T062249Zuser unk
055Bash120529T211250Zdaniero
078Scala120531T155347ZDon Mack
043Q120529T213240Zskeevey
028K3 / Kona120530T081818Ztmartin
nan120529T115338Zmarinus
091Fixed to say Yes/No and improved110330T185916ZChris Ku
096Haskell110315T081608Zuser1011
095Clojure110413T121109ZMeikel
nan110412T181311Zchinese
041Ruby110320T164028ZDaniel
086Python 2110330T095502ZJeremy
037Ruby110324T232546ZLowjacke
031Golfscript110319T062310ZYOU
061PHP110320T163024ZDaniel
123perl110318T002711Zsogart
041Ruby110309T213110Zsteensla
082PHP110313T223309ZKevin Br
051JavaScript110313T221151Zecatmur
070Python 70 Characters110309T141156ZfR0DDY
057J110309T203533ZJ B
071Python110309T132207ZTamara W
146C program110309T182615ZJoey Ada
076Windows PowerShell110309T171146ZJoey
5862Ruby110309T153418ZVentero
nan110309T141138Zrubber b
120JavaScript110309T144434ZSergio C
047J110309T131154ZEelvex
084J110309T125206ZEelvex
115Lua110309T121643Zjpjacobs

StackControl, 35 characters

R⁜⦽0←:⬌(↶⁞=(1←)?)⟲→("Yes"W)("No"W)⁇

Works with stdin and stdout (commands R and W can be changed later)

Explanation:

C, 140 ... 134 bytes/chars

I already answered this in Haskell, but here's a C program that does the same thing.

n,m;main(){char b[98],a[49],*p;for(scanf("%s%n%s%n",p=b,&n,a,&m);n==m+~n&&(memcmp(p,a,n)?p[n]=*p,++p<b+n:(p=0)););puts(p?"No":"Yes");}

Try it online!

Equivalent de-golfed version that better explains how it works:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char buf1[98], buf2[49], *p = buf1;
    int length1, length2;

    scanf("%s%n%s%n", buf1, &length1, buf2, &length2);
    length2 = length2 - length1 - 1;
    if (length1 == length2) {
        do {
            if (memcmp(p, buf2, length1) == 0) {
                p = NULL;
                break;
            }
            p[length1] = *p;
            p++;
        } while (p < buf1 + length1);
    }
    puts(p == NULL? "Yes": "No");
}

It basically intertwines the generation of each rotation of the string and checking whether the second string is equal to that rotation.

n == m + ~n is equivalent to n == m - n - 1. It's checking if the two strings are the same length and outputting "No" immediately if they're not.

As long as neither string inputted is more than 49 bytes, there shouldn't be buffer overflows or undefined behavior.

J, 28 22 21 bytes

(No`Yes{::~e.)#\|."{]

Input taken as function arguments, -1 thanks to ovs

Attempt This Online!

(No`Yes{::~e.)#\|."{]
                    ]  NB. ‎⁡right arg
              #\       NB. ‎⁢take the right arg then get the length of each prefix [1..len(y)]
                |."{   NB. ‎⁣rotate the right by each element of the left, obtain all rotations
(No`Yes{::~e.)         NB. single unit to create a hook
           e.          NB. ‎⁤is the left arg a member of the resulting table?
 No`Yes                NB. a lesser known trick, yields a boxed array but requires valid identifiers
       {::~            NB. ‎⁢⁢fetch using the boolen result of e., unlike {, this unboxes the result

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.

Haskell, 76 bytes

f[x,y]|elem x$scanl(\(h:t)_->t++[h])y y="Yes"|1>0="No"
main=interact$f.words

Try it online!

Inspired by MaroonSphinx's solution. A full program that takes in two space-separated inputs and prints the result "Yes" or "No", as was the style at the time in 2011 when this challenge was posted.

The helper function \(h:t)_->t++[h] (call it (?)) rotates a string by moving its first character to the end. Except, it takes an extra unused argument, which lets us use it as the binary operator for scanl. Doing scanl (?) r s makes each character of s trigger one rotation of r in turn, which is accumulated into a list of rotations of r, whose length is that of s plus 1. For example:

scanl(?)"abc" "def" == ["abc","bca","cab","abc"]

The main function f on [x,y] takes these rotations of y, and checks if x is among them.


I tried checking membership inside the rotation helper, but it was longer. Note below that the let recursively defines a helper function (%) inside the main function, which comprises everything but the =x%x defining f. Doing this let the helper access y in it scope.

83 bytes

f[x,y]|let(h:t)%(p:q)|h:t==y="Yes"|u<-t++[h]=u%q;_%_="No"=x%x
main=interact$f.words

Try it online!

I also tried importing Data.List for isInfixOf, to check that x is a substring of y++y, but this plus checking they're equal length turned out too long.

Raku, 55 bytes

->\a,\b {my@a=a.comb;grep {b eq@a.rotate($_).join},^@a}

Returns a list of rotate positions that produce a match, which is truthy when it includes a non-zero value.

If you have to output Yes or No, then the following takes 66 bytes:

->\a,\b {my@a=a.comb;<No Yes>[?grep {b eq@a.rotate($_).join},^@a]}

Try it online!

Thunno 2, 14 bytes

ż€ẒQM"YesNo"½i

Try it online!

Explanation

ż€ẒQM"YesNo"½i  # Implicit input
ż€Ẓ             # All rotations of the first input
   QM           # Is the second input NOT in it?
     "YesNo"½   # Push the list ["Yes", "No"]
             i  # Index the result into it
                # Implicit output

Jelly, 17 13 bytes

ɠṙJɠeị“Yes“No

Try it online!

How it works

ɠṙJɠeị“Yes“No - Main link. Takes no arguments
ɠ             - Read a line from STDIN
  J           - Indices; [1, 2, ..., len(S)]
 ṙ            - All rotations of S
   ɠe         - Read a line from STDIN; is that in the rotations?
     ị“Yes“No - Index that into ["Yes", "No"]

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!

05AB1E, 13 bytes

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

Try it online or verify all test cases.

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".

C (gcc), 118 113 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!

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

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.

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

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.

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"]

Husk, 14 bytes

Not sure about the rules here, Husk doesn't do IO at all. The closest alternative is a function:

!w¨Ye∫No¨€U¡ṙ1

Try it online!

Explanation

!w¨Ye∫No¨€U¡ṙ1
           ¡    -- iterate the following for ever:
            ṙ1  --   rotate string by 1
          U     -- only keep the longest prefix with unique elements
         €      -- is the argument in that list?
  ¨Ye∫No¨       -- compressed string: "Yes No"
 w              -- split on space
!               -- modular index (1-based)

Python, 70 bytes

a,b=raw_input().split()
print ['No','Yes'][a in b*2and len(a)==len(b)]

Testing ...

05AB1E, 20 bytes

Code:

DgFÀD²Qi"Yes",q}}"No

Uses CP-1252 encoding. Try it online!

CJam, 21 bytes

r]r_,,\f{\{(+}*}_@+^!

Try it online!

GolfScript, 25 bytes

' '/~.2*@/''+='Yes''No'if

How it works

             # STACK: "CodeGolf GolfCode"
' '/         # Split input string by spaces.
             # STACK: [ "CodeGolf" "GolfCode" ]
~            # Dump the array.
             # STACK: "CodeGolf" "GolfCode"
.            # Duplicate the topmost string.
             # STACK: "CodeGolf" "GolfCode" "GolfCode"
2*           # Repeat the topmost string.
             # STACK: "CodeGolf" "GolfCode" "GolfCodeGolfCode"
@            # Rotate the three topmost strings.
             # STACK: "GolfCode" "GolfCodeGolfCode" "CodeGolf"
/            # Split the second topmost string around the topmost one.
             # STACK: "GolfCode" [ "Golf" "Code" ]
''+          # Flatten the array of strings.
             # STACK: "GolfCode" "GolfCode"
=            # Check for equality.
             # STACK: 1
'Yes''No'if  # Push 'Yes' for 1, 'No' for 0.
             # STACK: "Yes"

Python, 66 63

a,b=raw_input().split()
print'YNeos'[a!=(2*a).replace(b,"")::2]

Another solution in 69 char

a,b=raw_input().split()
print['No','Yes'][a in b*2and len(a)==len(b)]

JavaScript - 66

p=prompt,a=p(),b=p();alert(!b.match(a)&&!!b+b.match(a)?'Yes':'No')

bash 56

read a b
[[ $a$a =~ $b&&$b$b =~ $a ]]&&echo Yes||echo No

Bash, 70 65 59 55 characters

new approach:

read a b;c=$a$a;[[ ${c/$b/} == $a ]]&&echo yes||echo no

Scala 78

val b=readLine split " "
print(b(0).size==b(1).size&&(b(0)+b(0)contains b(1)))

It's a shame about the size check, without it the count drops to 54

val a=readLine split " "
print(a(0)+a(0)contains a(1))

Q (50 43 chars)

{`No`Yes x in((!)(#)y)rotate\:y}." "vs(0:)0

K3 / Kona, 28

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

APL (28)

Takes input on two lines.

'No' 'Yes'[1+(⊂⍞)∊⌽∘A¨⍳⍴A←⍞]

Explanation:

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

import List;f[a,b]|a`elem`[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)

Haskell (98 96 chars)

g x y@(t:r)(z:w)|x==y="Yes"|1>0=g x(r++[t])w
g _ _[]="No"
f(x:y:_)=g x y y
main=interact$f.words

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.

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 :)

Ruby, 41

puts gets =~ /^(.+)(.*) \2\1$/ ?:Yes: :No

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"

Ruby, 30 37

gets
puts~/^(.+)(.*) \2\1$/?:Yes: :No

A version that prints "true" and "false" instead of "yes" and "no":

gets
p !! ~/^(.+)(.*) \2\1$/

Both of these work with different-length strings (unlike the old one)

Golfscript, 31

' '/:)~,\,=)~.+\/,(&'Yes''No'if

This one check length first, so it should work as expected.

PHP, 61

<?echo preg_match('/^(.+)(.*) \\2\\1$/',fgets(STDIN))?Yes:No;

perl, 123 chars

@s1=split(//,shift);
$s2=shift;
$i=0;
while($i<=@s1){
    if(join("",@s1) eq $s2){die "yes";}
    unshift @s1,pop @s1;
    $i++;
}
die "no";

Ruby 49 41

a,b=$*;puts (a*2).sub(b,'')==a ?:yes: :no

Edit: replaced gets.split by $*

PHP, 82 characters

<?$s=split(" ",fgets(STDIN));echo str_replace($s[1],"",$s[0].$s[0])==$s[0]?Yes:No;

JavaScript, 51

function f(a,b)a&&(a+a).replace(b,"")==a?"Yes":"No"

JavaScript doesn't have a canonical host, so this answer is written as a function of two arguments. The score goes up to 60 if we disallow JS 1.7 features (expression closures).

In the SpiderMonkey shell this would be (for a score of 71):

[a,b]=readline().split(" ");print(a&&(a+a).replace(b,"")==a?"Yes":"No")

Python 70 Characters

a,b=raw_input().split()
print'YNeos'[len(a)<>len(b)or a not in 2*b::2]

Thanks to gnibbler for the slice trick.

J, 57

{&('No';'Yes')@-:/@:((/:~@(|."0 _~i.&$))&.>)&.(;:&stdin)_

Sample use:

$ echo -n CodeGolf GolfCode | jconsole rotate.ijs
Yes
$ echo -n stackexchange changestackex | jconsole rotate.ijs
Yes
$ echo -n stackexchange changestack | jconsole rotate.ijs
No
$ echo -n Hello World | jconsole rotate.ijs
No

Python, 71

a,b=raw_input().split()
print'Yes'if a in b*2and len(a)==len(b)else'No'

C program - 146

char b[99],c[99],*p,*q;main(n){q=(p=b+(n=strlen(gets(c))))+n;sprintf(b,"%s%s"
,c,c);for(gets(c);p>b&&strcmp(p,c);--p,*--q=0);puts(p>b?"Yes":"No");}

Windows PowerShell, 76

$a,$b=-split$input
('No','Yes')[+!($a.length-$b.length)*"$b$b".contains($a)]

Ruby, 58 (62) characters

a,b=gets.split;$><<(a.size==b.size&&/#{a}/=~b*2?:Yes: :No)

This solution assumes the input contains only alphanumeric characters (actually everything that doesn't have a special meaning inside a regular expression is ok).

A solution that doesn't have this constraint is 4 characters longer

a,b=gets.split;$><<(a.size==b.size&&(b*2).index(a)?:Yes: :No)

According to the spec (same string lengths):

Perl, 42 43 chars

$.=pop;$_=(pop)x2;print+(qw'yes no')[!/$./]

If different sized strings are allowed, the solution would be:

Perl, 47 chars

$.=(pop)x8;$_=(pop)x9;print+(qw'yes no')[!/$./]

rbo

JavaScript (120 chars)

function f(a,b) {for (i=0,A=a.split("");A.join("")!=b&&i++<a.length;A.push(A.shift()));return A.join("")==b?'Yes':'No';}

Output:

f('CodeGolf','GolfCode'); //Yes
f('stackexchange','changestackex'); //Yes
f('stackexchange','changestack'); //No
f('Hello','World'); //No
f('nn','nBn'); //No

J, 47

y=:>2{ARGV
(>1{ARGV e.1|.^:(i.#y)y){'No',:'Yes'

J, 84

y=:(>1{ARGV),:(>2{ARGV)
((0{y)e.(y&((]$0{[),(]-~[:}.[:$[)$1{[)/.i.}.$y)){'No',:'Yes'

Lua 115 chars

a,b=io.read():match"(%w+) (%w+)"c=b repeat c=c:sub(2,-1)..c:sub(1,1) s=s or a==c until b==c print(s and"Yes"or"No")