# Question
Title: Create a Language of The Month answer scraper
When I was posting answers for the Husk Language of The Month thread, I realized it took more time to enter them in the thread than it took to actually write the answers. So, why not automate it?

Write a program/function which inputs a language name, and displays all answers in that language during the current month so far)

Sandbox

# Introduction

You are to find all answers in Code Golf Stack Exchange in the current month so far, whose first non-empty line matches the following:

```
#<whitespace>[<language name>(case insensitive match)]<anything else>

```

For example, the current month's answers should have been posted within the time frame of Nov 1 till the current date(Nov 6, as of this question's sandbox post).

for each answer, you must find the following:

* Question name
* Answer URL
* Answer Poster's Name
* Answer Poster's Profile URL

And format them in the following manner for Markdown:

```
- [<Question Name>](Answer URL) by [<Answer Poster's Name>]

```

Once you are done listing the answers, to keep the post short, you must key in the usernames to their respective profile URLs as follows:

```
- [<Answer Poster's Name>]:<Answer Poster's Profile URL>

```

This must be added at the end of the output.

# Output

The final result should look like the following:

```
- [Size up a number](http://example1.com) by [Razetime]
- [My smartphone's Phonebook](http://example2.com) by [Bubbler]
- [1,2,Fizz,4,Buzz](http://example3.com) by [Lyxal]
- [Upgoat or Downgoat?](http://example3.com) by [LegionMammal978]
- .....

[Razetime]:http://exampleA.com
[Bubbler]:http://exampleB.com
[Lyxal]:http://exampleC.com
[LegionMammal978]:http://exampleD.com
...

```

# Scoring

This is . Shortest answer in each language wins.

# Answer
# 05AB1E, ~~283~~ 282 bytes

```
žgŽ7?-©ƵÇ+400÷®<т÷(®69-4÷®70-365*•ΘÏF•ºS₂+žf<£`žgт‰0Kθ4ÖOŽª+·*’¸¸.Â‚‹º.ŒŒ/–«?€¼=ƒËŠˆ&€š‚‚=ÿ’žYì.w„†ä_¡¦ε',¡нþ}Ùε’ƒËŠˆ.Â‚‹º.ŒŒ/’žYì©’ÿ…é/ÿ’.w……<h1¡¦ε„><S¡3èy’="/a/’¡1è'"¡н®"ÿa/ÿ"y'†§™’ÜÇ.µÔ/ÿ’¡1è…><"S¡64Sè`®¨ì)}ćнδª}€`ʒнlIlQ}ʒ1è'/¡4èXså]DεƵ=Sè`“- [ÿ](ÿ)€‹ [ÿ]“}»sε32Sè`"[ÿ]:ÿ"}Ù»¶2×ý

```

Ugh..

No TIO of the full program, because `.w` is disabled.

**Explanation:**

Step 1: Get the current year and month, and convert it to a Unix timestamp (using this formula):

```
žg                     # Push the current year
  Ž7?-                 # Subtract 1900
      ©                # Store it in variable `®` (without popping)
       ƵÇ+             # Add 299
          400÷         # Integer-divide by 400
      ®                # Push year-1900 again from variable `®`
       <               # Subtract 1
        т÷             # Integer-divide by 100
          (            # Negate it
      ®                # Push year-1900 again
       69-             # Subtract 69
          D            # Duplicate it
           4÷          # Integer-divide the copy by 4
          s            # Swap so year-1969 is at the top again
           <           # Subtract 1 to make it year-1970
            365*       # Multiply by 365
•ΘÏF•                  # Push compressed integer 5254545
     º                 # Mirror it to 52545455454525
      S                # Convert it to a list of digits
       ₂+              # Add 26 to each: [31,28,31,30,31,30,31,31,30,31,30,31,28,31]
         žf            # Push the current month
           <           # Subtract it by 1
            £          # Leave that many trailing items in the list
             `         # Pop and push them all separated to the stack
žg                     # Push the current year again
  т‰                   # Divmod by 100: [year//100,year%100]
    0K                 # Remove 0s from this pair
      θ                # Leave the last item
       4Ö              # Check if it's divisible by 4
                       # (this results in 1 for leap years; 0 for non-leap years)
O                      # Sum all values on the stack
 Žª+                   # Push compressed integer 43200
    ·                  # Double it to 86400
     *                 # Multiply the sum by this 86400

```

Try just this first step online.

Step 2: Use this timestamp to create the stackexchange-API URL, and get the content of this url (which contains the JSON of all answers created this month):

```
’¸¸.Â‚‹º.ŒŒ/–«?€¼=ƒËŠˆ&€š‚‚=ÿ’
                       # Push dictionary string "api.stackexchange.com/answers?site=codegolf&fromdate=ÿ",
                       # where the `ÿ` is automatically replaced with the timestamp
 žYì                   # Prepend constant "https://"
    .w                 # Browse to this URL, and read its contents as string

```

Try the first two steps online (without `.w`).

Step 3: Extract all unique answer-id and question-ids from this JSON:

```
D                      # Duplicate the JSON
 „†ä_¡                 # Split it on dictionary string "question_"
      s                # Swap so the JSON is at the top again
       „Ž»_¡           # Split it on dictionary string "answer_"
            ‚          # Pair those two lists together
ε                      # Map over the pairs:
 ¦                     #  Remove the first item
  ε                    #  Map over each inner string:
   ',¡                '#   Split it on ","
      н                #   Pop and leave just the first item
       þ               #   Pop and leave just the digits in this string
  }Ù                   #  After the inner map: uniquify the resulting ids
}                      # Close the outer map

```

Try just this third step with the JSON as input.

Step 4: Convert each question-id to an URL, and get its contents (which is the entire HTML page of a question):

```
`                      # Pop and push both lists separated to the stack
 U                     # Pop the list of answer-ids and store it in variable `X`
ε                      # Map over the question-ids:
 ’ƒËŠˆ.Â‚‹º.ŒŒ/’       #  Push dictionary string "codegolf.stackexchange.com/"
   žYì                 #  Prepend constant "https://"
      ©                #  Store this string in variable `®` (without popping)
       ’ÿ…é/ÿ’         #  Push dictionary string "ÿ/questions/ÿ",
                       #  where the first `ÿ` is automatically replaced with "https://codegolf.stackexchange.com/"
                       #  and the second `ÿ` is automatically replaced with the current question-id
              .w       #  Browse to this URL, and read its contents as string

```

Try steps 3 and 4 with JSON input (without `.w`).

Step 5: For each HTML-content of a question, get a list of its `[language_name, answer_url, user_name, user_url, question_name]` (this may contain some garbage in the result - i.e. the trailing item, or if an answer contains multiple `<h1>`-refs, but we'll filter those out later):

```
…<h1¡                  #  Split the HTML-content on "<h1"
     ¦                 #  Remove the first item
      ε                #  Map over each string:
       „><S¡           #   Split it on both ">" and "<"
            3è         #   Get the fourth item (which is the question name in the first iteration,
                       #   and language name in every other iteration)
       y               #   Push the string again
        ’="/a/’¡      "#   Split it on "="/a/"
                1è     #   Get the second item (which is the trailing answer-id URL portion)
                  '"¡ '#   Split that on '"'
                     н #   Pop and leave the first item
        ®              #   Push "https://codegolf.stackexchange.com/" from variable `®`
         "ÿa/ÿ"        #   Push dictionary string "ÿa/ÿ",
                       #   where the `ÿ` are filled again to create the answer-URL
       y               #   Push the string again
        '†§           '#   Push dictionary string "person"
           ™           #   Titlecase it to "Person"
            ’ÜÇ.µÔ/ÿ’  #   Push dictionary string "schema.org/ÿ",
                       #   where the `ÿ` is replaced with "Person"
             ¡         #   Split the string on that
              1è       #   Get the second item
        …><"S¡        "#   Split that on ">", "<", and '"'
              64Sè     #   Get the seventh and fifth items
                       #   (which are the user name and trailing user URL portion)
                  `    #   Push those separated to the stack
                   ®   #   Push "https://codegolf.stackexchange.com/" again
                    ¨  #   Remove the trailing "/"
                     ì #   Prepend it in front to create the user-URL
       )               #   Wrap all four values into a list
      }ć               #  After the map: extract the first quadruple
        н              #  Pop and push its first item (the question name)
         δ             #  Map over each remaining quadruples
          ª            #   And append the question name as trailing item to each

```

Try just this fifth step with the HTML as input.

Step 6: Filter this list, so it only contains answers from the earlier list, and only the language that's equal to the input:

```
ʒ                      #  Filter this list of quintuples by:
 н                     #   Pop and leave its first item (the language name)
  l                    #   Convert it to lowercase
   Il                  #   Get the input in lowercase as well
     Q                 #   And check that both are equal
}ʒ                     #  After the filter: filter once again:
  1è                   #   Get the second item (the answer URL)
    '/¡               '#   Split it on "/"
       4è              #   Leave its fifth item (the answer-id)
         X             #   Push the list of answer-ids from variable `X`
          så           #   And check if the current answer-id is in it
]                      # Close both the filter and outer map

```

Try just the sixth step with the list of quintuples of the previous step as input.

Step 7: Convert it to the output in the specified format:

```
 €`                    # After the map over the questions, flatten it one level down
   D                   # Duplicate this list
    ε                  # Map over the quintuplets:
     Ƶ=                #  Push compressed integer 214
       Sè              #  Leave just the third, second, and fifth items
          `            #  Pop and push them separated to the stack
      “- [ÿ](ÿ)€‹ [ÿ]“ #  Push dictionary string "- [ÿ](ÿ) by [ÿ]",
                       #  where the `ÿ` are filled again
    }»                 # After the map: join the strings by newlines
   sε                  # Swap, and map over the quintuplets again:
     32Sè              #  Leave just the fourth and third items
         `             #  Pop and push them separated to the stack
      "[ÿ]:ÿ"          #  Push string "[ÿ]:ÿ",
                       #  where the `ÿ` are filled again
    }»                 # After the map: join the strings by newlines as well
      ¶2×ý             # Then join these two strings with "\n\n" as delimiter
                       # (after which the result is output implicitly)

```

Try just the sixth and seventh steps with the list of quintuplets of step five as input.

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*) to understand how the dictionary strings and compressed integers work.
> 10 votes

# Answer
# Python 3.6 and later + BeautifulSoup + requests, 681 bytes

```
from bs4 import*
from requests import*
from datetime import datetime as d
import json
def l(b):
 c='https://';s='.stackexchange.com';z="";y="";a=json.loads(get(c+'api'+s+'/answers?site=codegolf&fromdate='+d(d.now().year,d.now().month,1).strftime('%s')).text)
 for x in a['items']:
  k=BeautifulSoup(get(f"{c}codegolf{s}/questions/{x['question_id']}#{x['answer_id']}").text);t=k.select(f"#answer-{x['answer_id']}>div>div.answercell.post-layout--right>div.s-prose.js-post-body>h1");q=k.select('.question-hyperlink')[0];n=x['owner']['display_name']
  if t and b in t[0].text:z+=f"- [{q.text}]({c+'codegolf'+s+q['href']}) by [{n}]\n";y+=f"[{n}]:{x['owner']['link']}\n"
 print(z+"\n"+y)

```

Relevant function is `l`, where you pass the name of language `b`

Explanation coming soon
> 2 votes

---
Tags: code-golf, internet, stack-exchange-api
---


# Question
Title: Automatically anti-predictably assemble an alliterative aria
Thanks to @ComradeSparklePony for the title.

This challenge should be very simple. You are given three lists.

The first is a list of first names, in title case.

The second is a list of adjectives, in lower case.

The third is a list of nouns, in lower case.

Please randomly select a name, optional adjective, and noun, and output `<Name>'s <adjective> <noun>`. However, each word must begin with the same letter. You can assume that all words begin with a letter. You can also assume (but note in your answer if you do):

* that all words are composed solely of alphabetic characters
* that there is at least one noun for each name
* that there is at least one name for each noun

You cannot however assume that an adjective exists for a particular pair of name and noun, as the adjective is optional so the output will still be valid.

You do not have to select the shared letter uniformly, although all available letters must have a non-zero chance of occurring. You must however ensure that all outputs for a given letter have as near equal chance of occurring as possible within the limits of your language's random number generator. In the case of the adjective, this is equivalent to having an extra entry meaning "no adjective for this letter" which has the same chance as all of the other adjectives for that letter.

Example input lists:

```
Joan Neil Nicola Oswald Sherman Stephanie
new novel old original second silent
jeep noun novel output second sheep snake

```

Example outputs for these inputs (each line is a separate example):

```
Stephanie's second second
Sherman's silent snake
Oswald's original output
Nicola's novel novel
Neil's noun
Joan's jeep

```

Note no extra space between words in the last two examples.

This is , so the shortest code that breaks no standard loopholes wins!

In the unlikely event that it helps, you can input everything in upper case, but you still need to output in sentence case.

# Answer
# Jelly,  ~~27 25~~  24 bytes

-1 thanks to Erik the Outgolfer (use a zero instead of a space character)

```
Ż€2¦Œpḟ€0ZḢŒuEƲƇXż“'s“”K

```

A full program accepting an argument in the form of a Python formatted list of lists of strings which prints the output to STDOUTt.

**Try it online!**

### How?

```
Ż€2¦Œpḟ€0ZḢŒuEƲƇXż“'s“”K - Main Link: list of lists of lists of characters
 € ¦                     - sparse application...
  2                      - ...to indices: [2]
Ż                        - ...action: prepend a zero (place holder for no adjective)
    Œp                   - Cartesian product (all choices, including invalid ones)
       €                 - for each:
      ḟ 0                -   filter out any zeros
               Ƈ         - filter keep those for which:
              Ʋ          -   last four links as a monad:
         Z               -     transpose
          Ḣ              -     head
           Œu            -     upper-case
             E           -     all equal?
                X        - random (uniform) choice  e.g. [['B','o','b'],['b','l','u','e'],['b','a','g']]
                 ż       - zip with:
                  “'s“”  -   list [["'", 's'], []]       [[['B','o','b'],["'", 's']],[['b','l','u','e'],[]],['b','a','g']]
                       K - join with spaces              [['B','o','b'],["'", 's'],' ',['b','l','u','e'],[],' ','b','a','g']
                         - implicit (smashing) print     Bob's blue bag

```
> 5 votes

# Answer
# 05AB1E,  ~~24 23~~  21 bytes

Assumes there is a noun for each name, as allowed by the challenge.

```
„'s«I¯ªâIâ€˜ʒl€нË}Ωðý

```

Try it online!

**Explanation**

```
„'s«                    # append "'s" to all names in the name-list
    I¯ª                 # append an empty list to the adjective-list
       â                # cartesian product between the lists
        Iâ              # cartesian product with the noun-list
          €˜            # deep flatten each sublist
            ʒ    }      # filter, keep only lists that when
             l          # converted to lowercase
              €н        # with only heads kept
                Ë       # have all elements equal
                  Ω     # pick a valid list uniformly at random
                   ðý   # and join by spaces

```
> 5 votes

# Answer
# , ~~155~~ 148 bytes

-7 bytes thanks to Giuseppe (using `*` for `sample`)

```
function(x,y,z){`*`=sample
while(T)T=length(unique(c(tolower(substr(c(a<-x*1,b<-c(y,"")*1,c<-z*1),1,1)),"")))-2
paste0(a,"'s ",b,if(nchar(b))" ",c)}

```

Try it online!

Uses rejection sampling: draw at random a name, an adjective (possibly the empty string) and a noun until the first letters match. This condition is checked by counting if the number of unique elements in the vector formed of the first letters, plus the empty string, is of length 2 - this allows for an empty adjective.

Then print the result, with an extra space if the adjective is non-empty.

The different possibilities starting with the same letter have equal occurrence probabilities, since `sample` draws from the uniform distribution. The easiest way to see this is to condition on the event that the name and noun start with the same letter (which is fine: if they don't, we would reject). Now condition on the event that we accept: this means we draw either the empty adjective, or an adjective starting with the same letter. Each of these possibilities still has equal probability.

Check the probabilities on \\$10^5\\$ replicates.
> 4 votes

# Answer
# JavaScript (ES6),  ~~139 124 122~~  120 bytes

*Save 2 bytes thanks to @Neil*

Takes input as `(names,adjectives)(nouns)`.

```
(N,a)=>F=n=>/^(.)\S+( \1\S+)+$/i.test(s=(g=a=>a[Math.random()*a.length|0])(N)+"'s "+[(o=g([,...a]))&&o+' ']+g(n))?s:F(n)

```

Try it online!

Or check the distribution on 5 million draws

### How?

The helper function \\$g\\$ takes an array and returns a random element from this array, with a uniform distribution.

```
g = a => a[Math.random() * a.length | 0]

```

By invoking \\$g\\$ three times, we generate a random string \\$s\\$ with a valid format, but without taking the initial letters into account. For the adjective, we append an empty entry and make sure not to insert a trailing space if it's chosen.

```
s = g(N) + "'s " +
    [(o = g([, ...a])) && o + ' '] +
    g(n)

```

We then check if all initial letters are identical with the following regular expression:

```
/^(.)\S+( \1\S+)+$/i

```

It not, we simply try again until \\$s\\$ is valid.
> 3 votes

# Answer
# Python 3, ~~161 154 151 147~~ 145 bytes

(*Thanks ArBo, EmbodimentOfIgnorance, Neil who have contributed 2, 3 and 4 bytes to my first golf!*)

```
from random import*
c=choice
def f(N,a,n):
 s=c(N);w=s[0].lower();o=N
 while o[0]!=w:o=c(n)
 print(s+"'s",c([x+" "for x in a if x[0]==w]+[""])+o)

```

Try it online! (with 500k executions)

* Takes three lists as inputs.
* Assumes at least one noun for each name.

---

Same score, more golf-y:

# Python 3, 145 bytes

```
from random import*
c=choice
def f(N,a,n):
 s=c(N);y=lambda p,e=[]:c([x+" "for x in p if x[0]==s[0].lower()]+e);print(s+"'s",y(a,[""])+y(n)[:-1])

```

Try it online! (with 500k executions)

It's just 140 if trailing whitespaces are allowed (by removing square face `[:-1]`)
> 3 votes

# Answer
# Vyxal, 39 bytes

```
℅‛'s+:→a\ ?'h←a⇩h=;``J℅\ ?'h←a⇩h=;℅++++

```

Finally figured out what I'm doing.

Try it Online!
> 2 votes

# Answer
# Jelly, 28 bytes

```
1ịZḢXɓŒuḢ=ɗƇ€Ż€2¦X€ḟ0ż“'s“”K

```

Try it online!

Wrote this before I saw @JonathanAllan’s shorter answer, but thought it worth posting since it uses a different approach. Saved 3 bytes by @EriktheOutgolfer’s suggestion on that answer.

A full program taking a list of lists of strings and implicitly printing a randomly selected alliteration. Assumes at least one noun per name.
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler), 176 bytes

```
(a,b,c)=>(a=a[z.Next(a.Count)])+"'s "+b.Where(x=>(x[0]&95)==a[0]).Append("").OrderBy(x=>z.Next()).Last()+" "+c.OrderBy(x=>z.Next()).Last(x=>(x[0]&95)==a[0]);var z=new Random();

```

Try it online!
> 0 votes

# Answer
# Red, 179 bytes

```
func[a b c][random a random c
foreach k c[if k/1 = h: a/1/1 + 32[g: rejoin[sp k]]]collect/into[foreach
d b[if d/1 = h[keep rejoin[sp d]]]]e: copy[""]random e rejoin[a/1"'s"e/1 g]]

```

Try it online!

## Explanation:

```
Red[]
f: func[a b c][                     ; a function with 3 arguments
    random a                        ; shuffle the list of names in place
    random c                        ; shuffle the list of nouns in place
    foreach k c [                   ; for each item in the shuffled list of nouns
        if k/1 = h: a/1/1 + 32 [    ; check if it begins with the same lowercase letter
                                    ; as the first name in the shuffled list of names
            g: rejoin [" " k]       ; if yes, then insert a " " in front of it save it as g
        ]                           ; thus I always get the last match
    ]
    collect/into [                  ; collect in a new list e
        foreach d b [               ; all items form the adjectives list
            if d/1 = h [            ; that start with the same lowercase letter as the 1st noun
                keep rejoin [" " d] ; insert a " " in form of the adjective
            ]
        ]
    ] e: copy[""]                   ; the list initially has a single item - the empty string
   random e                         ; shuffle the extracted adjectives list
   rejoin [a/1 "'s" e/1 g]          ; return the formatted string
]

```
> 0 votes

# Answer
# Scala, 234 226 234 206 bytes

*-28 due to the fact I thought it had to accept StdIn, it's a function now*

```
def f(a:List[String],b:List[String],c:List[String])=scala.util.Random.shuffle(for(d<-a;e<-("" +: b);g<-c;if(d.head.toLower==g.head&&(e.isEmpty||e.head==g.head))) yield s"$d's $e $g".replace("  ", " ")).head

```

Try it online!

Ungolfed:

```
def f(names: List[String], adjectives: List[String], nouns: List[String]) = {
  val allPossible = for {
    name <- names
    adjective <- ("" +: adjectives) // Add the choice of no adjective
    noun <- nouns
    if (name.head.toLower == noun.head && (adjective.isEmpty || adjective.head == noun.head)) // Filter out so only matching entries remain
  } yield
    s"$name's $adjective $noun"
      .replace("  ", " ") // Get rid of artifact created by the empty adjective selection

  scala.util.Random.shuffle(allPossible.toList).head // Get a random element
}

```
> 0 votes

# Answer
# Icon, ~~167~~ 163 bytes

```
procedure f(a,b,c)
!a:=:?a&\x;!c:=:?c&\x;d:=[""]
e:=!b&e[1]==(t:=char(32+ord(a[1,1])))&put(d," "||e)&\x
!d:=:?d&\x;return(!a||"'s"||!d||" "||(k:=!c&t==k[1]&k))
end

```

Try it online!

Uses the same algorithm as my `Red` answer.
> 0 votes

# Answer
# Ruby, 94 bytes

```
->a,b,c{"#{n=a.sample}'s #{s=[p,*b.grep(r=/^#{n[0]}/i)].sample;s+" "if s}#{c.grep(r).sample}"}

```

Try it online!
> 0 votes

# Answer
# Excel, 201 bytes

```
=LET(a,INDEX(A:A,INT(RAND()*COUNTA(A:A))+1)&"'s",f,LEFT(a),b,FILTER(B:B,LEFT(B:B)=f,""),y,INT(RAND()*(ROWS(b)+1)),c,FILTER(C:C,LEFT(C:C)=f),a&IF(y," "&INDEX(b,y),"")&" "&INDEX(c,INT(RAND()*ROWS(c))+1))

```

Link to Spreadsheet

## Explanation

```
=LET(
a,INDEX(A:A,INT(RAND()*COUNTA(A:A))+1)&"'s", 'a = rand name from first list & "'s"
f,LEFT(a),                                   'f = first letter of a
b,FILTER(B:B,LEFT(B:B)=f,""),                'b = all items in second list starting with f
y,INT(RAND()*(ROWS(b)+1)),                   'y = rand from {0 .. size b}
c,FILTER(C:C,LEFT(C:C)=f),                   'c = all items in third list starting with f
a                                            'result = a
&IF(y," "&INDEX(b,y),"")                     '    & if y = 0 then "" else " " & b(y)
&" "&INDEX(c,INT(RAND()*ROWS(c))+1))         '    & " " & random item from c

```
> 0 votes

---
Tags: code-golf, random
---


title: Is it a chess cycle?

text:
# Question
Title: Is it a chess cycle?
Inspired by a discussion from the Esolangs.org unofficial Discord Server.

## Instructions

A chess cycle is an arrangement of a chess board where each piece *must* attack one other piece, and *only* one other piece, and each piece is attacked exactly once.

The effective idea to to "connect" pieces with each other, forming a single cyclic chain. Here is a board example:

**You will only be given boards with Knights, Rooks and Bishops.**

Your submission must take a chess board in any valid format(string, list of strings, 2D array, list of piece positions, FEN, ...) and output a truthy or falsy value for whether the board represents a valid cycle or not.

## Testcases

To create your own testcases, create your board here, copy the FEN box contents, and use as input here.

FEN: `8/2B5/8/1N6/5N2/3B4/8/8`, lichess

Board:

```
........
..B.....
........
.N......
.....N..
...B....
........
........

```

Output: `True` (In the illustration)

---

FEN: `8/8/8/3R4/8/8/8/8`, lichess

Board:

```
........
........
........
...R....
........
........
........
........

```

Output: `False` (Rook cannot attack self)

---

FEN: `1R4B1/3N4/3N4/3N1B2/8/2B2N2/4R1BB/R1N5`, lichess

Board:

```
.R....B.
...N....
...N....
...N.B..
........
..B..N..
....R.BB
R.N.....

```

Output: `True`

---

FEN: `6B1/4N2N/5B2/8/8/6B1/4N2N/5B2`, lichess

Board:

```
......B.
....N..N
.....B..
........
........
......B.
....N..N
.....B..

```

Output: `False` (Multiple Cycles)

---

FEN: `8/6R1/8/5R1N/3N4/8/5BB1/7N`, lichess

Board:

```
........
......R.
........
.....R.N
...N....
........
.....BB.
.......N

```

Output: `False` (Rook on f5 attacks two pieces)

---

FEN: `8/8/8/8/8/8/8/8`, lichess(tsh)

Board:

```
........
........
........
........
........
........
........
........

```

Output: `False` (No pieces for a cycle)

---

FEN: `8/8/8/2R2R2/8/8/8/8`, lichess(tsh)

Board:

```
........
........
........
..R..R..
........
........
........
........

```

Output: `True` (Two connected rooks, single cycle)

---

FEN: `8/8/8/1R3B2/8/3R2N1/8/8`, lichess(Robin Ryder)

Board:

```
........
........
........
.R...B..
........
...R..N.
........
........

```

Output: `False`

## Other Info

* You may represent the pieces and empty squares as any number or character, as long as it is consistent.
* Given boards will always be 8x8 and valid i.e. not containing any invalid characters.

# Answer
# Wolfram Language, 259 bytes

```
o=DirectedEdges->True
i|->RelationGraph[(d=Abs[#1[[2]]-#2[[2]]];#1!=#2&&NoneTrue[i,RegionMember[Line[p={#1[[2]],#2[[2]]}]~RegionDifference~Point@p]@*Last]&&Switch[#1[[1]],r,Times@@d==0,b,Equal@@d,n,Sort@d=={1,2}])&,i,o]~IsomorphicGraphQ~CycleGraph[Length@i,o]

```

Try it online!

(uses \\\[Function\] rather than `|->`, as TIO doesn't have the most recent version of the language)

Defines a function that takes in a list of piece positions as input, each in the form `{piece, {row, column}}` where piece is one of `r`, `b`, or `n`.

Un-golfed explanation:

```
i|->
IsomorphicGraphQ[                (*check if the following graphs are equivalent*)
  CycleGraph[Length[i], DirectedEdges -> True],
                                 (*cyclic graph with length of input*)
  RelationGraph[                 (*graph defined by a functional relation*)
    (d = Abs[#1[[2]] - #2[[2]]]; (*set `d` to absolute difference in coordinates*)
    #1 != #2 &&                  (*no pieces attack themselves*)
    NoneTrue[i,                  (*no other pieces are...*)
      RegionMember[RegionDifference[Line[p = {#1[[2]], #2[[2]]}], Point[p]]] @* Last
    ] &&                         (*between these two pieces*)
    Switch[First @ #1,           (*switch by attacking piece*)
      r, Times @@ d == 0,        (*rooks attack when one coordinate offset is zero*)
      b, Equal @@ d,             (*bishops attack when both offsets are equal*)
      n, Sort[d] == {1, 2}]      (*knights attack when one offset is 1 and the other is 2*)
    )&, i, DirectedEdges->True], (*apply to list of pieces*)
]&

```
> 9 votes

# Answer
# JavaScript (ES6), 241 bytes

Expects a list of triplets `(x,y,p)`, where \\$(x,y)\\$ are the coordinates of the piece and \\$p\\$ is its type (\\$0\\$, \\$1\\$ or \\$2\\$ for bishop, knight or rook respectively).

Returns \\$0\\$ or \\$1\\$.

```
a=>(g=(i,n,k)=>i>=0?m^(m|=1<<i)?a.map(([X,Y],j)=>(h=([x,y,t]=a[i],X-=x)*X)|(v=(Y-=y)*Y)&&![h-v,h+v-5,h*v][t]&a.every(([p,q])=>(S=Math.sign)(p-=x)-S(X)|S(q-=y)-S(Y)|(p*=p)+(q*=q)<1|[p-q,1][t]|p>=h&q>=v)?k=1/k?-1:j:0)|g(k,-~n):!i&!a[n]:0)(m=0)

```

Try it online!

## How?

### Algorithm

We recursively walk through the input list of \\$N\\$ entries by going from a piece \\$A\\$ to a piece \\$B\\$ attacked by \\$A\\$. We test whether we eventually go back to the starting piece in \\$N\\$ iterations.

Furthermore, we force the search to stop and the test to fail if:

* we reach a piece that was already visited and is not the starting one (e.g. a mutual attack between 2 rooks which would result in an infinite loop)
* we detect than any piece attacks more than one piece

### Attacks

Given two pieces \\$A\\$ and \\$B\\$ at positions \\$(x\_A,y\_A)\\$ and \\$(x\_B,y\_B)\\$, we compute \\$dx=x\_A-x\_B\\$ and \\$dy=y\_A-y\_B\\$.

As illustrated below, the piece \\$A\\$ attacks \\$B\\$ if:

* \\$A\\$ is a rook and we have either \\$dx^2=0,\\:dy^2\>0\\$ or \\$dx^2\>0,\\:dy^2=0\\$
* \\$A\\$ is a bishop and \\$dx^2=dy^2\\$
* \\$A\\$ is a knight and \\$dx^2+dy^2=5\\$

For rooks and bishops, we also have to make sure that there is no piece in between on the same ray. This is the weak point in this piece-oriented approach, as the corresponding code (the `a.every()`) is pretty long.

## Commented

```
a => (                         // a[] = list of pieces
  g = (i, n, k) =>             // g is a recursive function taking an index i and
                               // a number of moves n
  i >= 0 ?                     // if i is a non-negative number:
    m ^ (m |= 1 << i) ?        //   set the i-th bit in m; if it was not already set:
      a.map(([X, Y], j) =>     //     for each piece (X, Y) at position j in a[]:
        ( h = (                //       load the position (x, y) and the type t
            [x, y, t] = a[i],  //       of the i-th piece
            X -= x             //       set: X = X - x, h = X²
          ) * X                //            Y = Y - y, v = Y²
        ) | (v = (Y -= y) * Y) //       abort if both h and v are equal to 0
        && ![ h - v,           //       bishop: we must have h = v
              h + v - 5,       //       knight: we must have h + v = 5
              h * v            //       rook  : we must have either h = 0 or v = 0
        ][t] &                 //
        a.every(([p, q]) =>    //       make sure that there is no closer piece (p, q)
          (S = Math.sign)      //       that blocks the capture, which is not the case:
          (p -= x) - S(X)      //         if it's not in the same direction
          | S(q -= y) - S(Y)   //
          | (p *= p) +         //         or it's the capturing piece itself
            (q *= q) < 1       //
          | [p - q, 1][t]      //         or the capture types do not match
          | p >= h & q >= v    //         or it's not blocking because it's further
        ) ?                    //       end of every(); if all tests pass:
          k = 1 / k ? -1 : j   //         update k to j, or -1 if it's already set
        :                      //       else:
          0                    //         do nothing
      ) |                      //     end of map()
      g(k, -~n)                //     do a recursive call with i = k and n + 1
    :                          //   else:
      !i & !a[n]               //     this is a full cycle if i = 0 and n = a.length
  :                            // else:
    0                          //   abort
)(m = 0)                       // initial call to g with i = m = 0

```
> 8 votes

# Answer
# Python 3, ~~343~~ ~~335~~ ~~334~~ 327 bytes

-8 thanks to @ovs

A function that takes two inputs: a list of piece types and a list of piece coordinates.

Piece types:

* Rook: `1`
* Bishop: `2`
* Knight: `3`

Coordinates are given in the format:

`21 + y * 10 + x`

Coordinate format inspired by sunfish.

Returns `True` for true and `None` or `False` for false.

I haven't heavily tested it yet, please let me know if it fails on a test case.

```
m={1:[1,10],2:[11,9],3:[19,21,12,8]}
def f(p,c):
 x=0
 for y in c:
  q=p[x];w=m[q]+[-i for i in m[q]];a=[]
  for d in w:
   for i in range(1,9):
    z=c[x]+i*d
    if z<20|z>99|z%10%9<1|z in c:a+={*c}&{z};break
  if q>2:a=[x+i for i in w if x+i in c]
  if len(a)-1|0**x&y-c[0]:return
  x=c.index(a[0])
 return len(p)>x<1

```

Try it online!

## Explanation

A crucial observation is that if each piece attacks one other and after n moves we are back on the original piece, then there exists a cycle.

```
# A list of move directions for each piece. +-10 is vertical and +-1 is horizontal
# Only positive numbers, to save bytes
m={1:[1,10],2:[11,9],3:[19,21,12,8]}

def f(p,c):
    # A variable representing the current piece index
    x=0

    # It is a cycle if and only if after n moves, we arrive back at the original piece. (n is number of pieces)
    for y in c:
        # Values used multiple times
        q=p[x]
        w=m[q]+[-i for i in m[q]]

        # List of attacks of current piece
        a=[]

        # Movement of bishops and rooks: keep going in each direction
        for d in w:
            for i in range(1,9):
                z=c[x]+i*d
                # Check for out of bounds or landing on another piece
                if any([z<20,z>99,z%10%9<1,z in c]):a+={*c}&{z};break

        # Knight moves
        if q>2:a=[x+i in c for i in w if x+i in c]

        # Does it only attack one piece? Does it end up at the start too early?
        if len(a)-1|0**x&y-c[0]:return

        # Move to next piece
        x=c.index(a[0])
    return len(p)>x<1

```
> 5 votes

# Answer
# Jelly, ~~55~~ 54 bytes

```
_þ`;"JṖẸ$ƇAṖṢJƑƲƇṭ¬Ẹ$Ƈ,ṖAEƊƇƊƊƲ€ị@"ṠAṂṪƊƙ$€µF0ịƬL’=L×Ẹ

```

Try it online!

A dyadic link taking two arguments. The left argument is a list of co-ordinates of the pieces. The right argument is a list of the piece types corresponding to those co-ordinates, with 1=rook, 2=bishop, 3=knight. The result is 1 for true and 0 for false.

The TIO link includes a footer that starts with newline-separated FEN notation and for each one, converts them to the desired input format and then calls the main program.

Rewritten to work using co-ordinate arithmetic for bishops and rooks rather than splitting rows, columns and diagonals, and saving 11 bytes in the process.

---

## Original version:

# Jelly, ~~75~~ 66 bytes

```
fƇ⁹ḟ0ṣṪḢƭ€ʋ€Fḟ0
ŒṬFÄṁ×Ʋ;Z,ŒD;ŒdƊƲçþJ
ạṢ⁼Ø½ʋþ`T€ṭ"Ç0F?Ʋị@"µF0ịƬL’=L

```

Try it online!

## Explanation

### Link 1

* takes a list of lists as its left argument x
* takes an integer as its right argument y
* returns a list of the integers found to the left and right of y in members of x containing y, filtering out zeros

```
 Ƈ              | Keep those lists which:
f ⁹             | - contain y
          ʋ€    | For each of these:
   ḟ0           | - Exclude zeros
     ṣ          | - Split at y
      ṪḢƭ€      | - Take the tail of the first part and head of the second (note will return 0 if nothing there)
            F   | Flatten
             ḟ0 | Exclude zeros

```

## Link 2

* takes a list of lists of co-ordinates as its only argument
* returns a list of lists of the attacked pieces for each, first assuming each piece is a rook and then assuming each is a bishop

```
ŒṬ                   | Multidimensional untruthy (recreate the board as 1s and 0s)
      Ʋ              | Following as a monad with argument z:
  F                  | - Flatten
   Ä                 | - Cumulative sum
    ṁ                | - Mould like z
     ×               | - Multiply by z (restoring zeros)
                Ʋ    | Following as a monad with argument w:
       ;             |   - w concatenated to:
        Z            |   - Transpose of w
         ,     Ɗ     | - Paired with following as a monad:
          ŒD         |   - Diagonals of w
            ;        |   - Concatenated to
             Œd      |   - Antidiagonals of w
                 çþJ | Call link 1 for each member of this list using each of a sequence of integers from 1 to the length of the original argument of link 2

```

### Main link

* takes a list of the coordinates of pieces on the board as its left argument x
* takes a list of piece types as its right argument y
* returns 1 if there is a chess cycle and 0 if not

```
                Ʋ             | Following as a monad:
     ʋþ`                      | - Following as a dyad for each possible pairing of co-ordinates:
ạ                             |   - Absolute difference
 Ṣ                            |   - Sort
  ⁼Ø½                         |   - Equals [1,2] (i.e. a knight’s move)
        T€                    | - Truthy indices of each
          ṭ"                  | - Tag each onto the corresponding list in the following:
              F?              |   - If the original list of coordinates is not empty when flattened:
            Ç                 |     - Then call link 2 using the original co-ordinate list as its argument
             0                |     - Else a literal 0
                              | By this point we have a list of length-3 lists, one for each original set of co-ordinates. The first member corresponds to attacked pieces as a bishop, the second as a rook and the third as a knight
                 ị@"          | Index into each list using the type of piece
                    µ         | Start a new link as a monad
                     F        |   - Flatten
                      0ịƬ     |   - Starting with the last member, index into the list of attacks until we reach a piece we’ve seen before, preserving all of the intermediate steps
                         L    |   - Length of this
                          ’   | Subtract 1
                           =L | Is equal to the number of pieces

```
> 5 votes

---
Tags: code-golf, decision-problem, chess
---


title: Tips for golfing in LOLCODE

text:
# Question
Title: Tips for golfing in LOLCODE
What general tips do you have for golfing in LOLCODE? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to LOLCODE. (e.g. "remove comments" is not an answer). Please post one tip per answer.

# Answer
Define variables using the syntax `variable R value` rather than `I HAS A variable ITZ value`.

If you want to set a variable `n` equal to 1,

```
n R 1

```

is only 5 bytes, whereas

```
I HAS A n ITZ 1

```

is 15 bytes.
> 8 votes

# Answer
In many cases it's shorter to read variable values from STDIN rather than defining a function. However, note that `GIMMEH`, which reads input from STDIN, always reads a `YARN` (i.e. string). But you can take advantage of LOLCODE's dynamic typing and add 0 to convert to a `NUMBR`.

For example,

```
GIMMEH n
n R SUM OF n AN 0
... (operations on n)

```

Defining `n` is 26 bytes, including newlines. Compare this to a user-defined function:

```
HOW DUZ I f YR n
    ... (operations on n)
IF U SAY SO

```

This requires 28 bytes.

Note that you could also multiply by 1 to convert to a `NUMBR`, but that requires 4 more bytes than the sum:

```
GIMMEH n
n R PRODUKT OF n AN 1

```
> 4 votes

# Answer
In many LOLCODE implementations, such as the one on repl.it, `HAI` and `KTHXBYE`, which begin and end programs respectively, are unnecessary. In implementations in which they are necessary, the version number after `HAI` isn't necessary (e.g. `HAI 1.2`).

Similarly, the `STDIO` library is typically loaded by default, so `CAN HAS STDIO?` is also unnecessary.
> 3 votes

# Answer
When printing the value of a variable to STDOUT, consider the following:

```
VISIBLE variable

```

is much shorter than

```
VISIBLE ":{variable}"

```

Also, whenever a trailing newline is acceptable,

```
VISIBLE variable

```

which includes a trailing newline by default, is shorter than

```
VISIBLE variable!

```

which suppresses the newline.
> 2 votes

# Answer
Many operators have optional `AN`s in between them, as defined in the spec. For example:

```
SMOOSH "hello" AN ", world" MKAY

```

can be turned into this:

```
SMOOSH "hello" ", world" MKAY

```

Other operators that support this include `BOTH`, `EITHER`, `WON`, `ALL`, `ANY`, `BOTH SAEM`, and `DIFFRINT`. For some reason, the numerical operators don't allow you to remove the `AN`, though.

The spec also says, specifically for `SMOOSH`, that:

> The line ending may safely implicitly close the `SMOOSH` operator without needing an `MKAY`.

Meaning this code should also be valid:

```
SMOOSH "hello" ", world"

```

However, the current version of lci doesn't seem to accept this behaviour :(
> 2 votes

# Answer
LOLCODE (surprisingly) doesn't actually need indentation, meaning you can turn this:

```
HOW IZ I FIB YR N
    I HAS A SML ITZ SMALLR OF N AN 1
    BOTH SAEM N AN SML
    O RLY?
        YA RLY
            FOUND YR 1
        NO WAI
            I HAS A FIRST ITZ I IZ FIB YR DIFF OF N AN 1 MKAY
            I HAS A SECOND ITZ I IZ FIB YR DIFF OF N AN 2 MKAY
            FOUND YR SUM OF FIRST AN SECOND
    OIC
IF U SAY SO

```

Into this:

```
HOW IZ I FIB YR N
I HAS A SML ITZ SMALLR OF N AN 1
BOTH SAEM N AN SML
O RLY?
YA RLY
FOUND YR 1
NO WAI
I HAS A FIRST ITZ I IZ FIB YR DIFF OF N AN 1 MKAY
I HAS A SECOND ITZ I IZ FIB YR DIFF OF N AN 2 MKAY
FOUND YR SUM OF FIRST AN SECOND
OIC
IF U SAY SO

```
> 1 votes

---
Tags: code-golf, tips
---


title: Remove duplicate words from a sentence

text:
# Question
Title: Remove duplicate words from a sentence
In this challenge, you will remove duplicate words from each **sentence**.

## Examples

```
Hello Hello, World!
Hello, World!

Code Code! Golf Code
Code! Golf Code

Hello  hello   World
Hello   World

Programming Golf Programming!
Programming Golf!

```

## Specification

* Input will be a string of ASCII characters.
* A sentence is defined as anything until the end of the string, a linefeed (`\n`), or punctuation (`.!?`).
* A word is defined as a sequence of `A-Za-z`.
* Words are case insensitive (`Hello` == `heLlO`).

* Only the first occurrence of a word in a sentence is kept.
* If a word is removed, the spaces *before* the removed word should be removed. (e.g. `A A B` -\> `A B`).

---

This is so shortest code in bytes wins!

# Answer
> 3 votes
# Vim, 27 bytes

```
:s/\v\c(<\a+>).{-}\zs\s+\1

```

Note that the 27 bytes is including a trailing carriage return at the end.

Try it online! Side note: This is a link to a different language I'm writing called "V". V is *mostly* backwards compatible with vim, so for all intents and purposes, it can count as a vim interpreter. I also added one byte `%` so that you can verify all test cases at once.

Explanation:

```
:s/\v                       "Substitute with the 'Magic flag' on. This magic flag allows us
                            "to shorten the regex by removing a lot of \ characters.
     \c(<\a+>)              "A case-insensitive word
              .{-}          "Any character (non-greedy)
                  \zs       "Start the selection. This means everything after this atom
                            "will be removed
                     \s+    "One or more whitespace characters,
                        \1  "Followed by the first word

```

# Answer
> 6 votes
# JavaScript (ES6), 98

*Note* while I found it myself, it's annoyingly similar to @Neil's, just with the additional logic to split the whole input string in sentences.

```
s=>s.replace(/[^\n.!?]+/g,s=>s.replace(/ *([a-z]+)/ig,(r,w)=>k[w=w.toUpperCase()]?'':k[w]=r,k=[]))

```

**Test**

```
f=s=>s.replace(/[^\n.!?]+/g,s=>s.replace(/ *([a-z]+)/ig,(r,w)=>k[w=w.toUpperCase()]?'':k[w]=r,k=[]))

console.log=x=>O.textContent+=x+'\n'

;[['Hello Hello, World!','Hello, World!']
,['Code Code! Golf Code','Code! Golf Code']
,['Hello  hello   World','Hello   World']
,['Programming Golf Programming!','Programming Golf!']]
.forEach(t=>{
  var i=t[0],k=t[1],r=f(i)
  console.log((r==k?'OK ':'KO ')+i+' -> '+r)
})
```

```
<pre id=O></pre>
```

# Answer
> 6 votes
## Retina, ~~66~~ 46 bytes

Byte count assumes ISO 8859-1 encoding.

```
i`[a-z]+
·$0·
i` *(·[a-z]+·)(?<=\1[^.!?¶]+)|·

```

Try it online!

### Explanation

Since only letters should be considered word characters (but regex treats digits and underscores as word characters, too), we need to make our own word boundaries. Since the input is guaranteed to contain only ASCII characters, I'm inserting `·` (outside of ASCII, but inside ISO 8859-1) around all words and remove them again with the duplicates. That saves 20 bytes over using lookarounds to implement generic word boundaries.

```
i`[a-z]+
·$0·

```

This matches every word and surrounds it in `·`.

```
i` *(·[a-z]+·)(?<=\1[^.!?¶]+)|·

```

This is two steps compressed into one. `<sp>*(·[a-z]+·)(?<=\1[^.!?¶]+)` matches a full word (ensured by including the `·` in the match), along with any spaces preceding it, *provided that* (as ensured by the lookbehind) we can find the same word somewhere earlier in the sentence. (The  matches a linefeed.)

The other part is simply the `·`, which matches all artificial word boundaries that weren't matched as part of the first half. In either case, the match is simply removed from the string.

# Answer
> 5 votes
# C, 326 bytes

Who needs regular expressions?

```
#include <ctype.h>
#define a isalpha
#define c(x)*x&&!strchr(".?!\n",*x)
#define f(x)for(n=e;*x&&!a(*x);++x);
main(p,v,n,e,o,t)char**v,*p,*n,*e,*o,*t;{for(p=v[1];*p;p=e){f(p)for(e=p;c(e);){for(;a(*++e););f(n)if(c(n)){for(o=p,t=n;a(*o)&&(*o-65)%32==(*t-65)%32;o++,t++);if(a(*t))e=n;else memmove(e,t,strlen(t)+1);}}}puts(v[1]);}

```

# Answer
> 3 votes
# Perl 6, 104 bytes

```
{[~] .split(/<[.!?\n]>+/,:v).map(->$_,$s?{.comb(/.*?<:L>+/).unique(as=>{/<:L>+/;lc $/}).join~($s//'')})} # 104

```

### Usage:

```
# give it a lexical name
my &code = {...}

say code "Hello Hello, World!
Code Code! Golf Code
Hello  hello   World
Programming Golf Programming!";

```

```
Hello, World!
Code! Golf Code
Hello   World
Programming Golf!

```

### Explanation

```
{
  [~]                         # join everything that follows:

  .split(/<[.!?\n]>+/,:v)     # split on boundaries, keeping them
  .map(                       # loop over sentence and boundary together
    -> $_, $s? {              # boundary is optional (at the end of the string)
      .comb(/.*?<:L>+/)       # grab the words along with leading non letters
      .unique(                # keep the unique ones by looking at …
        as => {/<:L>+/;lc $/} # only the word chars in lowercase
      )
      .join                   # join the sentence parts
      ~                       # join that with …
      ($s//'')                # the boundary characters or empty string
    }
  )
}

```

# Answer
> 2 votes
# Perl 5 with -p option, 27 + 1 = 28 bytes

```
s/\A(\w+)[^.!?]*\K\s+\1//gi

```

Try it online!

# Answer
> 1 votes
## Perl 5, 57 bytes

**56 bytes code + 1 for `-p`**

```
s/[^.!?
]+/my%h;$&=~s~\s*([A-z]+)~!$h{lc$1}++&&$&~egr/eg

```

### Usage:

```
perl -pe 's/[^.!?
]+/my%h;$&=~s~\s*([A-z]+)~!$h{lc$1}++&&$&~egr/eg' <<< 'Hello Hello, World!
Code Code! Golf Code
Hello  hello   World
Programming Golf Programming!
'
Hello, World!
Code! Golf Code
Hello   World
Programming Golf!

```

Might need to be +1, currently I'm assuming that there will only be spaces in the input, no tabs.

# Answer
> 1 votes
# JavaScript (Node.js), 50 bytes

```
x=>x.replace(/(?<=\b(\w+)\b[^.!?\n]*) +\1\b/ig,'')

```

Try it online!

# Answer
> 0 votes
# Stax, 39 bytes

```
ô┘ⁿ=3⌠↕ê║▌ßa⌡ô½â╖¬╥▓lå3Öîz╝╥'n┐←ûl₧'○0T

```

Run and debug it

I'm not sure if Stax's JS regex has the features to match up with Vim regex, but nested regex works!

## Explanation

```
'!+".+?[\n!?]"{cV^{c:~\{:}m$"\s*"s+{i!*}Rc}Rd}RNd
'!+                                               append an ! to the string
   ".+?[\n!?]"                                    match anything(non-greedy),
                                                  followed by a sentence terminator
              {                              }R   replace each sentence with:
               c                                  copy it
                V^                                /[a-zA-Z]+/
                  {                       }R      for each regex word match:
                   c                              copy the word
                    :~                            toggle case
                      \                           zip the two
                       {:}m                       embed each pair in square brackets
                           $                      flatten
                            "\s*"s+               prepend \s*
                                                  Example for "wOrd":
                                                  "\s*[wW][Oo][rR][dD]"
                                   {   }R         replace each occurrence of word with:
                                    i!            index negated (1 if first)
                                      *           multiply with word
                                         c        copy
                                             d    delete the faulty replaced string
                                               Nd remove last !

```

---
Tags: code-golf, string
---


title: Partial tq interpreter

text:
# Question
Title: Partial tq interpreter
In this task you are expected to provide a **list** output given an input tq program. The tq programs will not contain whitespace inside them.

## What is tq, in the first place?

tq is a lazy-evaluated language that is designed with the idea that array items should be accessable during the definition of them. In tq, there is no explicit separator of an array, only special arrangements of monadic/dyadic functions and nilads.

The following program is a program printing `[123]` (Pretend that tq doesn't support strings because we aren't dealing with them in this case):

```
123

```

This defines a list with the first item being the number 123, after which all items in the list will be outputted inside a list.

In tq, numbers are supported to allow multiple-digits. So this defines a list with 2 items:

```
12+12,5

```

In this test case, you are expected to output the list `[24,5]`. Let's explain it step by step.

```
12+12   # This evaluates 12 + 12 in the current item in the list, returning 24
     ,  # A separator. This separates two items when they could be potentially
        # ambiguous when they are applied without a separator.
      5 # This evaluates 5 in the current item in the list, returning 5
        # The comma is simply a no-op that doesn't require parsing.

```

So you think that tq is not hard at all to implement? Well, remember that tq also has a special feature of accessing the items in an array before the array is defined!

```
555th123

```

We introduce two new atoms:

* `t` (**t**ail) means access the last item in the list
* `h` (**h**ead) means access the first item in the list

Therefore our list is going to yield:

```
[555,123,555,123]

```

Now take a look at this program:

```
555ps123

```

We introduce 2 more atoms:

* `p` Yield the next item *before* (**p**revious) the current position
* `s` Yield the next item *after* (**s**ucceeding)the current position

This yields the list:

```
[555,555,123,123]

```

## A quick reference of the tq language

Just assume that you only have two operands for the operators.

* `[0-9]` starts a number. Numbers will *only* be positive integers, i.e. no decimals and negative numbers.
* `,` This is a separator of different items when it is given that two consecutive indexes will be ambiguous with each other without a separator. In tq all of the remaining characters can act as a separator, but in this case it is a good idea to implement only `,` for the ease of your implementation.
* `+` and `*` These are arithmetic operators. Usually in tq, they may be applied multiple times, e.g. `1+2+3`, but in your implementation, input will be provided so that this will not happen and only `1+2` will happen (there will not be applications multiple times).
* `t` return the last item in the list. If the code is `t1,2,3` it shall return `[3,1,2,3]`.
* `h` return the first item in the list. If the code is `1,2,3h` it shall return `[1,2,3,1]`.
* `p` returns the item before the current item. If the code is `0,1,p,3,4` the code shall return `[0,1,1,3,4]`.
* `s` returns the item after the current item. If the code is `0,1,s,3,4` the code shall return `[0,1,3,3,4]`.

## Additional rules (with some examples)

* You also have to implement multiple hops. E.g. `1th` should yield `[1,1,1]`
* If you know that something is going to form a loop, e.g. `1sp2`, the cells that form the loop should be removed. Therefore the previous example will yield `[1,2]`.
* Out of bounds indexing will yield the closest index of the indexed item **that is a number**. E.g. `1,2s` should yield `[1,2,2]`
* If any possible indexing fails, you may do whatever operation you prefer.

## More test cases

* `4p*p` will yield `[4,16]`
* `1p+s2` will yield `[1,3,2]`
* `1,2,3h+t4,5,6` will yield `[1,2,3,7,4,5,6]`
* `3ppss6` will yield `[3,3,3,6,6,6]`

# Answer
> 4 votes
# Jelly, 131 bytes

```
+Ø+o+2$};;1N;Ø½“spth+*”żF
ṣ”,µeþØD,Øa¤Ḥ2¦SSƝ>2k)Ẏµe€⁾+*oḊ$k)µJç€LyⱮ"ƲVḢf?€€ØDAƑƇ.ị;@Ʋµṙ-+;×ɗị@ƭ/$¹L’$?¹Nị⁸¹L’$?ɗAƑ?€AƑ?F¥€`ÐLAƑƇFṖṖ

```

Try it online!

A full program taking a tq program string as its input and returning a list of integers. Still needs more golfing, but seems to work ok. Doesn’t use `eval` except for converting numbers from string to integer (which wouldn’t be an `eval` in most languages).

# Answer
> 3 votes
# Python 3, ~~536~~ 522 bytes

```
def f(c):
 D={"t":"o[n]","h":"o[0]","p":"o[i-1]","s":"o[i+1]"};o=[];T="";A=o.append;l=type;n=-1
 for C in c:
  if C==",":A(T);T=""
  elif C in"0123456789":
   if"o"in T:
    A(T);T=C
   else:T+=C
  elif C in"htps":
   if T and T[n]in"+*":T+=D[C]
   else:
    if T:A(T)
    T=D[C]
  else:
   T+=C
 if T:A(T)
 if D['s']in o[n]:o[n]=o[n].replace("i+1","i-1")
 while not all([l(m)==int for m in o]):
  for i in range(len(o)):
   x=o[i]
   try:x=eval(str(o[i]))
   except:pass
   if l(x)is str:continue
   else:o[i]=x
 return o

```

Try it online!

Ungolfed:

```
def tq(code):
    corresp = {"t":"output[-1]","h":"output[0]","p":"output[i-1]","s":"output[i+1]"}
    output = []
    temp = ""
    for char in code:
        if char == ",":
            output.append(temp)
            temp = ""

        elif char in "0123456789":
            if "h" in temp or "t" in temp or "p" in temp or "s" in temp:
                output.append(temp)
                temp = char
            else:
                temp += char

        elif char in "htps":
            if temp and temp[-1] in "+*":
                temp += corresp[char]
            else:
                if temp:
                    output.append(temp)
                temp = corresp[char]

        else:
            temp += char
    if temp:
        output.append(temp)
    if 'output[i+1]' in output[-1]:
        output[-1] = output[-1].replace("i+1","i-1")
    while not all([type(m) == int for m in output]):
        for i in range(len(output)):
            x = output[i]
            try: x = eval(str(output[i]))
            except: pass
            if type(x) is str:
                continue
            else:
                output[i] = x
    return output

```

Somehow, by fixing a bug, I was able to remove 14 bytes. I've well and truly broken code golf now.

Anyhow, this takes the program, parses it into `eval`able chunks and then evals them.

# Answer
> 2 votes
# JavaScript (ES6),  ~~269 263~~  262 bytes

```
v=>(F=r=>r+''==(h=(i,d)=>r[i]?1/r[i]?i:h(i+d,d):h,L=r.length-1,r=r.map((s,i)=>1/(x=eval((s+'').replace(/[h-t]/g,c=>` +r[${c<'i'?0:c>'s'?L:c>F?++i<L?i:h(L,-1):i?i-1:h(0,1)}]`)))?x:s))?r.filter(x=>1/x):F(r))(v.split(/,|((?:\d+|.)(?:[+*](?:\d+|.))?)/).filter(v=>v))

```

Try it online!

Test cases borrowed from Nick's answer.

### How?

We first split the input into tokens with the following regular expression:

```
+---------------------------> either a comma (discarded)
|                             or the following group (captured):
|        +------------------>   1st operand:
|        |                        a number or a single non-numeric character
|        |                      which may be followed by:
|        |       +---------->     an operator
|        |       |       +-->     and a 2nd operand
|     ___|_    __|_   ___|_
,|((?:\d+|.)(?:[+*](?:\d+|.))?)

```

Example:

```
"12,3p*4h" --> [ '12', undefined, '3', 'p*4', 'h' ]

```

Empty or undefined elements are removed with `filter(v => v)`.

The result is passed to the main function \\$F\\$ which recursively attempts to replace expressions with numeric values until no further modification is possible.

```
F = r =>                             // F is a function taking a list of tokens r[]
  r + '' == (                        // test whether r[] is modified by this iteration
    h = (i, d) =>                    // h is a function taking i = position, d = direction
      r[i] ?                         //   if r[i] is defined:
        1 / r[i] ? i                 //     if r[i] is numeric, return i
                 : h(i + d, d)       //     otherwise, add d to i and try again
      :                              //   else:
        h,                           //     return a non-numeric value
      L = r.length - 1,              // L = index of last element in r[]
      r = r.map((s, i) =>            // for each element s at position i in r[]:
        1 / (                        //
          x = eval((s + '').replace( //   evaluate s
            /[h-t]/g,                //   where letters are replaced with
            c => ` +r[${             //   " +r[index]" where the index is:
              c < 'i' ? 0 :          //     'h' -> 0
              c > 's' ? L :          //     't' -> L
              c > F ?                //     's' ->
                ++i < L ? i          //       i + 1 if this is not the last item
                        : h(L, -1)   //       or the first preceding number
              :                      //     'p' ->
                i ? i - 1            //       i - 1 if this is not the first item
                  : h(0, 1)          //       or the first following number
            }]`))                    //
        ) ? x : s                    //   yield x if it's numeric or s otherwise
      )                              // end of map()
  ) ?                                // if r[] is unchanged:
    r.filter(x => 1 / x)             //   return it with non-numeric items removed
  :                                  // else:
    F(r)                             //   do a recursive call

```

# Answer
> 1 votes
# APL(Dyalog Unicode), 174 bytes SBCS

```
a←('t'⎕R'a[≢a]')¨('h'⎕R'a[1]')¨','(≠⊆⊢)'[^,\d]([+×][^,\d]){0,1}'⎕R',&,'⊢⎕
a←{'s'⎕R(x,'+1]')⊢'p'⎕R((x←'a[',⍕⊃⌽⍵),'-1]')⊢⊃⍵}¨↓a,⍪⍳≢a
t/⍨(⊢≢⍕)¨t←⊃¨{a⊢←{0::⍵⋄⍎⍕∘⍎⍣(≢a)⊢⍵}¨a⋄a}⍣≡a

```

Try it on APLgolf!

A tradfn submission which takes a string from STDIN.

---
Tags: code-golf, string, interpreter
---


# Question
Title: I shift the source code, you shift the input!
Sandbox

*A spin-off of a rip-off of a rip-off of a rip-off of a rip-off. Go upvote those!*

Your task, if you accept it, is to write a program/function that outputs/returns its input/argument. The tricky part is that if I left shift your source code, the output must be left shifted too. Likewise, if I right shift your source code, the output must be right shifted too.

Source code will only be shifted once in each direction (in other words, only one shift will be applied, meaning that there are only three possible programs that need to be run). Consequently, the minimum source length should be 3.

## Examples

Let's say your source code is `ABC` and the input is `xyz`. If I run `ABC`, the output must be `xyz`. But if I run `BCA` instead, the output must be `yzx`. And if I run `CAB`, the output must be `zyx`.

Let's say your source code is `EFG` and the input is `Hello`. If I run `EFG`, the output must be `Hello`. If I run `GEF`, the output must be `oHell`. And if I run `FGE`, the output must be `elloH`.

Let's say your source code is `abcde` and the input is `2019`. If I run `abcde`, the output must be `2019`. But if I run `eabcd` instead, the output must be `9201`. And if I run `bcdea`, the output must be `0192`.

# Rules

* The program must print the entire output shifted in the specified direction
* Input can be taken in any convenient format.
* Output can be in any convenient format as well.
* Standard Loopholes are forbidden.
* Source length should be at least 3 characters long, as to allow for unique shifted programs.

## Scoring

This is code-golf so the answer with the fewest amount of bytes wins.

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=196864;
var OVERRIDE_USER=78850;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```

```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```

# Answer
# Haskell, 51 bytes

```
midm(a:b)=b++[a]
i=(:).last<*>init
main=interact id

```

Try it online!

## Explanation

Our `main` function is just `interact` of a another function. By default it is `id` which just returns the input, but if we shift we either add an `m` to make `idm` or remove the `d` to make `i`. Both of which we have defined to be roll left and roll right.
> 28 votes

# Answer
# 05AB1E, 4 bytes

```
À\Á\

```

Try it online
ry it shifted towards the leftT
tTry it shifted towards the righ

**Explanation:**

```
À     # Shift the (implicit) input once towards the left
 \    # Discard it from the stack
  Á   # Shift the (implicit) input once towards the right
   \  # Discard it from the stack
      # (output the implicit input implicitly as result)

\     # Discard (no-op, since the stack is already empty)
 À    # Shift the (implicit) input once towards the left
  \   # Discard it from the stack
   Á  # Shift the (implicit) input once towards the right
      # (and output this right-shifted input at the top of the stack implicitly as result)

\     # Discard (no-op, since the stack is already empty)
 Á    # Shift the (implicit) input once towards the right
  \   # Discard it from the stack
   À  # Shift the (implicit) input once towards the left
      # (and output this left-shifted input at the top of the stack implicitly as result)

```
> 18 votes

# Answer
# , ~~82~~ ~~75~~ ~~67~~ 62 bytes

-4 bytes thanks to Giuseppe.

```
!-1->i
c(tail(s<-el(strsplit(scan(,""),"")),1/i),head(s,-i))#!

```

Try it online!

ry it online!T

!Try it online

Uses rightwards assignment `->` (this is only the 2nd time I have ever used rightwards assignment). The value of `i` is either 0, 1 or -1 depending on the shift. This is used to give the correct output:

* when `i=1`, `tail(s, 1)` gives the last element and `head(s, -1)` gives all elements but the last
* when `i=-1`, `tail(s, -1)` gives all elements but the first and `head(s, 1)` gives the first element
* when `i=0`, `tail(s, Inf)` gives `s` and `head(s, 0)` gives the empty vector.
> 12 votes

# Answer
# Pyth, 18 bytes

```
?.<Q1 Q ;*.>Q1qk"

```

Try it online!, Right-shift, Left-shift

Pretty proud of this one. Has a trailing newline except on right shift. Makes use of the fact that a space before a pyth expression suppresses the output. Note the last byte is a space.

## How it works

```
?.<Q1 Q ;*.>Q1qk" - Unshifted
?.<Q1                - If the input left-shifted is truthy
      Q ;            - Print the input, end if statement
         *.>Q1       - Right shifted input, multiplied by...
              qk"    - whether k (an empty string) is equal to the string at the end.
                       Since there is a space at the end, y(Q) is multiplied by zero.

.<Q1 Q ;*.>Q1qk" ? - Left Shifted
.<Q1               - Left shift the input and print it.
     Q             - This input is preceded by a space and as such does not print
               " ? - Obviously is not equal to an empty string (Pyth
                     closes strings implicitly)

 ?.<Q1 Q ;*.>Q1qk" - Right Shifted
 ?.<Q1 Q ;         - The space before the if statement suppresses the printing
                 " - Since the space has been removed from the end, the
                     terminating string is now an empty string, and y(Q) is printed

```
> 9 votes

# Answer
# APL (Dyalog Unicode), ~~15~~ 11 bytesSBCS

-4 thanks to inspiration from Luis Mendo's solution.

Full program, prompting for input via stdin.

---

```
1⊢⍞⌽⍨¯2+≢1⍬

```

Try it online!

`1⍬` the list `[1,[]]`

tally the elements in that; `2`

`¯2+` add negative two to that; `0`

`⌽⍨` cyclically rotate the following by that number of steps:

stdin

`1⊢` yield that, ignoring the `1`

---

```
⊢⍞⌽⍨¯2+≢1⍬1

```

ry it online!T

`1⍬1` the list `[1,[],1]`

tally the elements in that; `3`

`¯2+` add negative two to that; `1`

`⌽⍨` cyclically rotate the following by that number of steps:

stdin

yield that

---

```
⍬1⊢⍞⌽⍨¯2+≢1

```

!Try it online

`1` the number `1`

tally the elements in that; `1`

`¯2+` add negative two to that; `-1`

`⌽⍨` cyclically rotate the following by that number of steps:

stdin

`⍬1⊢` yield that, ignoring the list `[[],1]`
> 9 votes

# Answer
# JavaScript (Browsers), ~~81~~ ~~68~~ 66 bytes

```
xx=1;var x,xxx;w=prompt();alert(w.slice(a=x|-xxx)+w.slice(0,a))//x

```

## Original solution (81 bytes)

```
tob=-1;try{ob;atob=1}catch(e){}w=prompt();alert(w.slice(atob)+w.slice(0,atob))//a

```

No TIO link because it works only in browsers ~~with `atob` function defined~~. In order to show the output in a more friendly way, `prompt` and `alert` are overridden in the screenshot below.

## Explanation

The declarations of `x` and `xxx` are hoisted to the beginning automatically, so the declarations won't clear the values assigned beforehand.

### No rotation

```
xx=1;var x,xxx;w=prompt();alert(w.slice(a=x|-xxx)+w.slice(0,a))//x

// xx = 1, so a = 0, so we have alert(w.slice(0)+w.slice(0,0))

```

### Left rotation

```
x=1;var x,xxx;w=prompt();alert(w.slice(a=x|-xxx)+w.slice(0,a))//xx

// x = 1, so a = 1, so we have alert(w.slice(1)+w.slice(0,1))

```

### Right rotation

```
xxx=1;var x,xxx;w=prompt();alert(w.slice(a=x|-xxx)+w.slice(0,a))//

// xxx = 1, so a = -1, so we have alert(w.slice(-1)+w.slice(0,-1))

```
> 8 votes

# Answer
# Python 2, 64 bytes

```
bc=k=input()
print[k,k[1:]+k[0],k,k[-1]+k[:-1]][len(dir()[5])]#a

```

Try it online!, !Try it online and ry it online!T

`dir` is a builtin function that returns a list of all variable names. The length of the first variable name is used to choose the right output.
> 5 votes

# Answer
# Japt, 4 bytes

```
ÉUé0

```

Try it

---

0ÉUé

Ué0É

---

Works with arrays too.

ÉUé0

Ué0É

0ÉUé
> 4 votes

# Answer
# C (gcc), ~~109~~ ~~86~~ 83 bytes

-20 bytes thanks to xibu

Takes the text to display is a command line argument. The active code is bookended by newlines, having the result of changing what `__LINE__` evaluates to when shifting the code. This means `2-__LINE__` will be +1 for shifting left, 0 for no shift, and -1 for shifting right.

## No shift

```

K;main(L,s)char**s;{for(L=strlen(s[1]);K<L;)putchar(s[1][(K+++2-__LINE__+L)%L]);}

```

Try it online!

## Left shift

```
K;main(L,s)char**s;{for(L=strlen(s[1]);K<L;)putchar(s[1][(K+++2-__LINE__+L)%L]);}

```

Try it online!

## Right shift

```

K;main(L,s)char**s;{for(L=strlen(s[1]);K<L;)putchar(s[1][(K+++2-__LINE__+L)%L]);}

```

Try it online!
> 4 votes

# Answer
# Python 3, ~~52~~ 48 bytes

## Base code:

```
"i=1#";i=0#';i=-1
a=input()
print(a[i:]+a[:i])#'

```

Try it online!

## Left shift:

```
i=1#";i=0#';i=-1
a=input()
print(a[i:]+a[:i])#'"

```

ry it online!T

## Right shift:

```
'"i=1#";i=0#';i=-1
a=input()
print(a[i:]+a[:i])#

```

!Try it online

Comments in code are useful :)
> 4 votes

# Answer
# MATL, ~~9~~ 8 bytes

```
TFsqYS%T

```

Try it online! See also right-shifted and left-shifted versions.

# How it works

**Normal version:**

```
TF    % Push array [true, false]
sq    % Sum; subtract 1. Gives 0
YS    % Implicit input. Circular shift by that amount. Implicit display
%T    % Comment. Ignore rest of line

```

**Right-shifted version:**

```
TTF   % Push array [true, true, false]
sq    % Sum; subtract 1. Gives 1
YS    % Implicit input. Circular shift by that amount. Implicit display
%     % Comment. Ignore rest of line

```

**Left-shifted version:**

```
F     % Push array [false]
sq    % Sum; subtract 1. Gives -1
YS    % Implicit input. Circular shift by that amount. Implicit display
%TT   % Comment. Ignore rest of line

```
> 3 votes

# Answer
# Runic Enchantments, 7 bytes

```
@{͍{͍

```

Try it online!

Input is limited to a single string (spaces need to be escaped).

This is the best I can come up with. It is not a full program, but instead a function (see the header on TIO for the entry, stdin handling, and `B`ranch).

This also relies on treating each *cell* of the function as a single object.

Alternatively this works on space separated inputs and doesn't require modifier characters, but outputs them all with no separator.

Without those concessions, the challenge would be impossible in Runic, due to having explicit input and output, as well as a termination command (eg. sample program `i@}`, if it was rotated two to the right to `@}i`, the program would terminate without reading or outputting anything; with an explicit entry point, the program could not distinguish its own rotation).
> 3 votes

# Answer
# C (gcc), ~~96~~ 94 bytes

-2 bytes thanks to gastropner

```
BC=1;C;ABC;S,K;main(N,c)char**c;{K=S=strlen(c[1]);for(N=C-ABC+S;K--;)putchar(c[1][N++%S]);}//A

```

Try it online!

explanation:

```
BC=1;       // declare and set variable ABC, BC or C (depending on shift)
C;ABC;      // declare possible variable names
            // existing variables are not changed, newly declared variables are set to 0

int main(int NumArgs,char** c)
{
    char* input = c[1];

    int S = strlen(input);      // string length used for modulo
    int K = S;                  // string length used to count characters
    int I = C - ABC + S;        // set start of output

    for(;K--;)                  // display K characters
        putchar(input[I++%S]);  // display character and move read position
}
//A                             // A used to create valid variable name in first line

```
> 3 votes

# Answer
# Javascript, ~~63~~ ~~40~~ 39 bytes

Thanks to @Shaggy and @l4m2, it's now 39 bytes.

`0;f=x=>x.slice(o)+x.slice(0,o);o=~-0b01`

**Explanation**

The last line of this snippet assigns the variable o to either `-1+0b0`, `-1+0b01`, or `-1+0b010`. The 0b prefix is used to define a binary literal, causing those to evaluate to -1, 0, or 1, which then gets used inside the function.

Here are try-it-now versions:

**Not Shifted**

```
<html>
  <body>
    <script>
      0;f=x=>x.slice(o)+x.slice(0,o);o=~-0b01
      console.log(f(prompt()))
    </script>
  </body>
</html>
```

**Left Shifted**

```
<html>
  <body>
    <script>
      ;f=x=>x.slice(o)+x.slice(0,o);o=~-0b010
      console.log(f(prompt()))
    </script>
  </body>
</html>
```

**Right Shifted**

```
<html>
  <body>
    <script>
      10;f=x=>x.slice(o)+x.slice(0,o);o=~-0b0
      console.log(f(prompt()))
    </script>
  </body>
</html>
```

## History

**Original version**

`0;x=prompt();onload=_=>alert(x.slice(o)+x.slice(0,o));o=-1+0b01`

A value gets assigned to o on the last line, but we need it in the middle of the code, so we called a function with a delay (by attaching it to the onload event) in order to do so.

**After @Shaggy suggestion to accept I/O from a function**

`0;f=x=>x.slice(o)+x.slice(0,o);o=-1+0b01`

**After @l4m2's suggestion to use `~-` to subtract 1, instead of `-1+` (the current solution).**

`0;f=x=>x.slice(o)+x.slice(0,o);o=~-0b01`
> 3 votes

# Answer
# Ruby, 72 bytes

```
aa,a,aaa,g=0,-1,1,gets
f=->s,a{(g*3)[s+a..-s+a-1]}
puts f.call g.size,aa

```

Try it online!

```
a,a,aaa,g=0,-1,1,gets
f=->s,a{(g*3)[s+a..-s+a-1]}
puts f.call g.size,aaa

```

Try it online!

```
aaa,a,aaa,g=0,-1,1,gets
f=->s,a{(g*3)[s+a..-s+a-1]}
puts f.call g.size,a

```

Try it online!

Triplicates the input then takes a middle substring, shifted according to whether the source code was shifted. Doesn't take kindly to empty input, unfortunately.

Ruby actually has a built-in `rotate` function, there might be a way to use this but it only works on arrays and not strings.
> 2 votes

# Answer
# Charcoal, 8 bytes

```
←→Ｆθ§θⅈ←

```

Try it online! Link is to verbose version of code. Explanation:

```
←           Move cursor left (decrement X-position)
 →          Move cursor right (increment X-position)
  Ｆ         For each character of
   θ        Input string
    §       Implicitly print cyclically indexed character
     θ      Input string
      ⅈ     Current X-position
       ←    Move cursor left (no-op)

```

Rotating the code simply causes the X-position to start at `1` or `-1` appropriately thus causing the characters of string to be output cyclically offset, however Charcoal does not include the cursor movement in the output.

```
→Ｆθ§θⅈ←←

```

ry it online!T Link is to verbose version of code.

```
←←→Ｆθ§θⅈ

```

!Try it online Link is to verbose version of code.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 33 bytes

```
0+#~RotateLeft~Log10[.1$]&/.$->10

```

Try it online!
> 2 votes

# Answer
# Klein 000, ~~59~~ 53 bytes

## Original

```
@>:?!\)>):?!\?@
\(  / \$
/(   \ /)  \
>$:?!/?>:?!/?@/

```

Try it online!

## Left-Shifted

```
>:?!\)>):?!\?@
\(  / \$
/(   \ /)  \
>$:?!/?>:?!/?@/@

```

Try it online!

## Right-Shifted

```
/@>:?!\)>):?!\?@
\(  / \$
/(   \ /)  \
>$:?!/?>:?!/?@

```

Try it online!

---

This requires topology 000 for some small byte saving measures. For a version that works on any topology see the 59 byte version in the history.
> 2 votes

# Answer
# Jelly, 9 bytes

```
10%3Cṙ@ḷ4

```

Try it online!

A monadic link taking a Jelly string and returning the processed Jelly string.

All three variations
> 1 votes

# Answer
# Perl 5 `-p`, 37 bytes

```
's/(.)(.*)/\2\1/;';";s/(.*)(.)/\2\1/"

```

Try it online!

### Left shift

```
s/(.)(.*)/\2\1/;';";s/(.*)(.)/\2\1/"'

```

Try it online!

### Right shift

```
"'s/(.)(.*)/\2\1/;';";s/(.*)(.)/\2\1/

```

Try it online!
> 1 votes

# Answer
# Attache, 12 bytes

```
0&~Rotate??~

```

Try it online!

Returns a function.

## Explanation

`Rotate` is a function which does string rotation. `~Rotate` reverses the argument order. `x&` binds the `x` to the left argument of the given function. `??~` is a comment (`??` marking the start of it). So, this returns a function which, given y, returns `Rotate[y, x]`—rotating `y` by `x` degree.

For the case of no rotation, this rotates the string by 0.

When rotated once right, this becomes:

```
~0&~Rotate??

```

Which is the same as the above, except this time it's `Rotate[y, -1]`, which performs the desired transformation.

If instead we rotate left once, it becomes:

```
&~Rotate??~0

```

`&`, when used in a unary context such as this, will, if given an array as input, apply the each element of the array as an argument for the function. However, the argument is a string, and this is effectively a no-op. Thus, `Rotate[y, x]` has no right argument; by default, it is `1`, so this performs the desired transformation.
> 1 votes

# Answer
# Crystal, 52 bytes

**Unshifted**

```
25.tap{|n|puts gets.to_s.chars.rotate(n%3-1).join}#2

```

Try it online!

**Left-Shifted**

```
5.tap{|n|puts gets.to_s.chars.rotate(n%3-1).join}#22

```

Try it online!

**Right-Shifted**

```
225.tap{|n|puts gets.to_s.chars.rotate(n%3-1).join}#

```

Try it online!

Crystal's `Object#tap` passes the object into the following block. Then we get the input, guarantee it's a string, get an array of that string's characters, and then rotate. We rotate by the number at the beginning, modded by three and then subtracted by 1 (with the number at the beginning "chosen" based on convenient modulo properties).
> 1 votes

# Answer
# Pxem, Content: 0 bytes + Filename: 75 bytes.

* Filename (escaped): `X.c.Z.w.i.c\001.+.a.s.v.t.p.m.o.d.A.c.Z.w.o.i.c\001.+.a.d.A.w.i.c\001.+.a.s.t.v.m.pX`

Try it online!

!Try it online

ry it online!T

## With comments

```
??.z
# number of X's, as literals branches
.a??X.z
# if not empty; then pop; else enter here
.a.c.Z??.z
  # push while EOF
  .a.w.i.c\001.+.a??.z
  # pop; reverse; pop to heap; pop all to print; push heap; pop to print; exit
  .as.v.t.p.m.o.d??.a
.a.A??.z
# if not empty; then pop; else enter here
.a.c.Z??.z
  # cat; as in my previous post
  .a.w.o.i.c\001.+.a.d??.z
.a.A??.z
# and finally
.a.w.i.c\001.+.a.s.t.v.m.pX

```
> 1 votes

# Answer
# brainfuck, ~~112~~ 75 bytes

```
+<,[>[>+<-],]+>[-[<<.[-]<[<]>[.[-]>]]<[-<<[<]>[.>]]>]<[-<[<]>>[.>]<[<]>.<]+

```

Try it online!

!Try it online

ry it online!T
> 1 votes

---
Tags: code-golf, string, source-layout
---