| Bytes | Lang | Time | Link |
|---|---|---|---|
| 035 | StackControl | 240804T140713Z | Швеев Ал |
| 134 | C | 240803T212907Z | MaroonSp |
| 021 | J | 230719T042821Z | south |
| 089 | Haskell | 240731T060946Z | MaroonSp |
| 076 | Haskell | 240802T215059Z | xnor |
| 055 | Raku | 230718T194430Z | bb94 |
| 014 | Thunno 2 | 230718T102051Z | The Thon |
| 013 | Jelly | 171215T192513Z | caird co |
| 057 | PHP | 191119T180806Z | 640KB |
| 013 | 05AB1E | 191119T145546Z | Kevin Cr |
| 111 | C gcc | 171216T212909Z | gastropn |
| 011 | Stax | 190812T231442Z | recursiv |
| nan | jq Rn | 190812T154201Z | user344 |
| 017 | Brachylog | 190812T022943Z | Unrelate |
| 018 | Pyth | 171215T204421Z | user4854 |
| 016 | Jelly | 171215T202533Z | DJMcMayh |
| 014 | Husk | 171215T201930Z | ბიმო |
| 070 | Python | 110309T144516Z | Quixotic |
| 020 | 05AB1E | 160510T121524Z | Adnan |
| 021 | CJam | 160510T160657Z | A Simmon |
| 025 | GolfScript | 140510T024638Z | Dennis |
| 063 | Python | 131018T131923Z | Coding m |
| 066 | JavaScript | 131018T133735Z | tristin |
| 056 | bash | 120530T062249Z | user unk |
| 055 | Bash | 120529T211250Z | daniero |
| 078 | Scala | 120531T155347Z | Don Mack |
| 043 | Q | 120529T213240Z | skeevey |
| 028 | K3 / Kona | 120530T081818Z | tmartin |
| nan | 120529T115338Z | marinus | |
| 091 | Fixed to say Yes/No and improved | 110330T185916Z | Chris Ku |
| 096 | Haskell | 110315T081608Z | user1011 |
| 095 | Clojure | 110413T121109Z | Meikel |
| nan | 110412T181311Z | chinese | |
| 041 | Ruby | 110320T164028Z | Daniel |
| 086 | Python 2 | 110330T095502Z | Jeremy |
| 037 | Ruby | 110324T232546Z | Lowjacke |
| 031 | Golfscript | 110319T062310Z | YOU |
| 061 | PHP | 110320T163024Z | Daniel |
| 123 | perl | 110318T002711Z | sogart |
| 041 | Ruby | 110309T213110Z | steensla |
| 082 | PHP | 110313T223309Z | Kevin Br |
| 051 | JavaScript | 110313T221151Z | ecatmur |
| 070 | Python 70 Characters | 110309T141156Z | fR0DDY |
| 057 | J | 110309T203533Z | J B |
| 071 | Python | 110309T132207Z | Tamara W |
| 146 | C program | 110309T182615Z | Joey Ada |
| 076 | Windows PowerShell | 110309T171146Z | Joey |
| 5862 | Ruby | 110309T153418Z | Ventero |
| nan | 110309T141138Z | rubber b | |
| 120 | JavaScript | 110309T144434Z | Sergio C |
| 047 | J | 110309T131154Z | Eelvex |
| 084 | J | 110309T125206Z | Eelvex |
| 115 | Lua | 110309T121643Z | jpjacobs |
StackControl, 35 characters
R⁜⦽0←:⬌(↶⁞=(1←)?)⟲→("Yes"W)("No"W)⁇
Works with stdin and stdout (commands R and W can be changed later)
Explanation:
R⁜⦽- read stdin, split input with spaces and unpack to get 2 words on the stack0←- push 0 after the cursor:⬌- duplicate second word and convert it to it length(- start a function↶- shift right (move last letter to the start)⁞=(1←)?- duplicate both words and compare them. if they equals write1after cursor)- and a function
⟲- repeat this function {length} times→- move cursor right to out output number (1if found atleast once otherwise0)("yes"W)("no"W)⁇- if1writeyes, otherwiseno
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");}
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
(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
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
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]}
Thunno 2, 14 bytes
ż€ẒQM"YesNo"½i
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
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;
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]);
Or as a function:
PHP, 41 bytes
function($a,$b){return strpos($b.$b,$a);}
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");}
Stax, 11 bytes
Ä:∩ö┌┘/YJTI
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)
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
(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
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
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
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)
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:
A←⍞: read a line of input and store it in A⌽∘A¨⍳⍴A: Rotate A by x, for each x in [1..length A]. Gives a list, i.e.estT stTe tTes Test(⊂⍞)∊: read another line of input, and see if it is in this list.1+: add one to this, giving 1 if the strings were not rotated and 2 if they were'No' 'Yes'[...]: Select either the first or second element from the list'No' 'Yes'depending on whether the strings were rotated or not.- This value is output automatically.
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")