24
\$\begingroup\$

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

53 Answers 53

19
\$\begingroup\$

Ruby 49 41

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

Edit: replaced gets.split by $*

\$\endgroup\$
3
  • \$\begingroup\$ That's an ingenious idea. \$\endgroup\$
    – Joey
    Commented Mar 9, 2011 at 21:40
  • \$\begingroup\$ Very clever. :) \$\endgroup\$
    – st0le
    Commented Mar 18, 2011 at 4:56
  • \$\begingroup\$ $* is argv when the question specified stdin though. \$\endgroup\$ Commented Nov 19, 2018 at 1:00
7
\$\begingroup\$

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.
\$\endgroup\$
7
\$\begingroup\$

Python, 70 bytes

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

Testing ...

\$\endgroup\$
4
  • \$\begingroup\$ +1 Nice, selecting the result from an array is clever! :-) \$\endgroup\$ Commented Mar 9, 2011 at 15:24
  • 3
    \$\begingroup\$ The question states you should read two strings from stdin, which this solution does not. \$\endgroup\$
    – Ventero
    Commented Mar 9, 2011 at 15:36
  • \$\begingroup\$ @Ventero:Fixed. \$\endgroup\$
    – Quixotic
    Commented Mar 9, 2011 at 18:43
  • 1
    \$\begingroup\$ You can skip the space in print ['No \$\endgroup\$
    – movatica
    Commented Aug 12, 2019 at 18:54
6
\$\begingroup\$

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.

\$\endgroup\$
9
  • 1
    \$\begingroup\$ Same problem as the GolfScript solution: If you input nn nfn, you get Yes, which is wrong. \$\endgroup\$ Commented Mar 9, 2011 at 14:28
  • \$\begingroup\$ @TomWij Thanks for finding the bug. Corrected. Should work now. \$\endgroup\$
    – fR0DDY
    Commented Mar 9, 2011 at 15:14
  • \$\begingroup\$ You can replace <> by - as that will also result in 0 if they are of equal length. \$\endgroup\$ Commented Mar 9, 2011 at 15:28
  • \$\begingroup\$ But what if they are not of equal length? Then it doesn't work so well :-) \$\endgroup\$
    – hallvabo
    Commented Mar 13, 2011 at 13:38
  • \$\begingroup\$ @hallvabo then the strings are not rotated version of each other. \$\endgroup\$
    – fR0DDY
    Commented Mar 13, 2011 at 13:52
5
\$\begingroup\$

J, 47

y=:>2{ARGV
(>1{ARGV e.1|.^:(i.#y)y){'No',:'Yes'
\$\endgroup\$
5
  • \$\begingroup\$ Why the two J answers? \$\endgroup\$
    – J B
    Commented Mar 9, 2011 at 19:49
  • \$\begingroup\$ @JB: because this one uses the buildin rotate. Both answers su^H^H are not so good btw. There is a lot of room for golfing. \$\endgroup\$
    – Eelvex
    Commented Mar 9, 2011 at 19:57
  • \$\begingroup\$ why the other one, then, I'm tempted to ask? :-) \$\endgroup\$
    – J B
    Commented Mar 9, 2011 at 20:06
  • \$\begingroup\$ @JB: because I thought this one is barely legal ( :p ) [ while the other one extends nicely to lisp. ] \$\endgroup\$
    – Eelvex
    Commented Mar 9, 2011 at 20:13
  • \$\begingroup\$ errr... the other one seems to read input from the command-line as well \$\endgroup\$
    – J B
    Commented Mar 9, 2011 at 20:15
5
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ Same problem as the GolfScript solution: If you input nn nfn, you get Yes, which is wrong. \$\endgroup\$ Commented Mar 9, 2011 at 14:17
  • 1
    \$\begingroup\$ seems to be ok (I missed the'!' in the first version) "nn nfn" => no "CodeGolf GolfCode" => yes \$\endgroup\$ Commented Mar 9, 2011 at 14:22
5
\$\begingroup\$

Golfscript, 31

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

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

\$\endgroup\$
1
  • \$\begingroup\$ :) and =) +1 for very happy code \$\endgroup\$ Commented Oct 30, 2016 at 23:48
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

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")
\$\endgroup\$
1
  • \$\begingroup\$ 5 years later and now you can use the => function notation ;) \$\endgroup\$
    – J Atkin
    Commented Feb 23, 2016 at 1:28
3
\$\begingroup\$

Windows PowerShell, 76

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

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
\$\endgroup\$
3
\$\begingroup\$

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)]
\$\endgroup\$
4
  • 2
    \$\begingroup\$ print'YNeos'[a!=(2*a).replace(b,"")::2] \$\endgroup\$
    – gnibbler
    Commented Oct 19, 2013 at 10:05
  • \$\begingroup\$ @gnibbler nice trick, thanks for suggestion. I updated the code \$\endgroup\$
    – Coding man
    Commented Oct 19, 2013 at 11:26
  • \$\begingroup\$ @gnibbler: Unfortunately, that trick doesn't work if a and b are the same. \$\endgroup\$ Commented Jul 31 at 2:12
  • \$\begingroup\$ use replace(b,"",1) \$\endgroup\$
    – Malo
    Commented Aug 4 at 8:44
3
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Nice answer! I think your code is actually 89 bytes (TIO), you must be counting a Windows-style newline as 2. \$\endgroup\$
    – xnor
    Commented Aug 2 at 21:09
  • \$\begingroup\$ @xnor Thanks! I'm using Linux and counted my file using wc -c file.hs; the mix-up was that I counted the newline at the end of the file unnecessarily. Thanks for telling me! \$\endgroup\$ Commented Aug 3 at 0:48
3
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ You can save a byte by making this a hook: (No`Yes{::~e.)#\|."{] \$\endgroup\$
    – ovs
    Commented Aug 2 at 11:52
2
\$\begingroup\$

J, 84

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

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
\$\endgroup\$
2
\$\begingroup\$

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)
\$\endgroup\$
2
\$\begingroup\$

Python, 71

a,b=raw_input().split()
print'Yes'if a in b*2and len(a)==len(b)else'No'
\$\endgroup\$
4
  • \$\begingroup\$ Same problem as the GolfScript solution: If you input nn nfn, you get Yes, which is wrong. \$\endgroup\$
    – Timwi
    Commented Mar 9, 2011 at 14:08
  • \$\begingroup\$ Problem has been solved, remains low... :-) \$\endgroup\$ Commented Mar 9, 2011 at 14:17
  • \$\begingroup\$ Doesn't read from stdin as specified. \$\endgroup\$
    – Wooble
    Commented Mar 9, 2011 at 16:57
  • \$\begingroup\$ Now it does... :-) \$\endgroup\$ Commented Mar 9, 2011 at 18:59
2
\$\begingroup\$

PHP, 61

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

Ruby, 41

puts gets =~ /^(.+)(.*) \2\1$/ ?:Yes: :No
\$\endgroup\$
2
  • \$\begingroup\$ Doesn't print anything, results in ':No' for input 'aaa aaa' (on my machine). The regexp approach could be a good idea though. \$\endgroup\$
    – steenslag
    Commented Mar 25, 2011 at 0:43
  • \$\begingroup\$ Fix to actually print and input from stdin instead of args: puts gets =~ /^(.+)(.*) \2\1$/ ?:Yes: :No - ups it to 41 chars. \$\endgroup\$
    – Nemo157
    Commented Mar 25, 2011 at 4:12
2
\$\begingroup\$

Q (50 43 chars)

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

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))
\$\endgroup\$
1
  • \$\begingroup\$ """val b=readLine split " " print(b(0).sorted==b(1).sorted)""".length yields 56 \$\endgroup\$ Commented Jun 1, 2012 at 3:49
2
\$\begingroup\$

bash 56

read a b
[[ $a$a =~ $b&&$b$b =~ $a ]]&&echo Yes||echo No
\$\endgroup\$
2
\$\begingroup\$

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"
\$\endgroup\$
2
\$\begingroup\$

CJam, 21 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ This answer seems to return 0/1 instead of No/Yes. \$\endgroup\$ Commented Dec 15, 2017 at 20:12
2
\$\begingroup\$

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)
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
0
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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"]
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.