title: Walk Across a Keyboard

text:
# Question
Title: Walk Across a Keyboard
Given a word (or any sequence of letters) as input, you must interpolate between each letter such that each adjacent pair of letters in the result is also adjacent on a QWERTY keyboard, as if you typed the input by walking on a giant keyboard. For example, '**yes**' might become '**y**tr**es**', '**cat**' might become '**c**xz**a**wer**t**'.

### Rules:

* This is the keyboard format you should use:

``q````w````e````r````t````y````u````i````o````p``
``a````s````d````f````g````h````j````k````l``
``z````x````c````v````b````n````m``

Any pair of keys which is touching in this layout is considered adjacent. For instance, 's' and 'e' are ajacent, but 's' and 'r' are not.
* The input "word" will consist of any sequence of letters. It will have only letters, so you don't have do deal with special characters.
* The input can be in any convenient form: stdin, a string, a list, etc. Letter case does not matter; you can take whatever is more convenient.
* The output can be in any convenient form: stdout, a string, a list, etc. Letter case does not matter, and it does not need to be consistent.
* Any path across the keyboard is valid, except that you cannot cross the previous letter again before getting to the next letter. For example, '**hi**' could become '**h**j**i**' or '**h**jnbgyu**i**', but not '**h**b*h*u**i**'.
* A letter is not ajacent with itself, so '**poll**' cannot become '**poll**'. Instead it would need to become something like '**pol**k**l**'.
* No output letters are allowed before or after the word. For example, '**was**' cannot become 'tre**was**' or '**was**dfg'.

This is code golf, the shortest answer in bytes wins.

# Answer
# Japt `-g`, 23 bytes

```
;D·ÎÔ+D·Årí)pUl)fUq".*?

```

Try it online!

Takes input as an array of capital letters. Very similar to the other answers otherwise.

Explanation:

```
;                          :Set D to the keyboard layout
 D·Î                       :Get the first row of keys
    Ô                      :Reversed
     +                     :Concat
      D·Å                  :The other two rows
         rí)               :Interleaved
            p              :Repeat that string
             Ul)           : A number of times equal to the length of the input
                f          :Get the substrings that match
                 U         : The input
                  q".*?    : joined with ".*?"
                           :Implicitly output just one of the matches

```
> 7 votes

# Answer
# Python 2, 83 bytes

```
lambda s:re.findall('.*?'.join(s),'qwertyuioplkmnjhbvgfcxdsza'*len(s))[0]
import re

```

Try it online!

Walks the entire keyboard until the word is written.
> 17 votes

# Answer
# Python 2 \+ NetworkX, 274 bytes (optimal solution)

# ~~296~~ ~~300~~ ~~302~~ ~~308~~ ~~315~~ ~~319~~ ~~324~~ ~~327~~ ~~328~~ ~~430~~ ~~432~~ bytes

-4 bytes thanks to mypetlion

```
from networkx import*
i=input()
M,z='qwertyuiop  asdfghjkl   zxcvbnm'.center(55),i[:1]
G=from_edgelist([(M[e],M[e+h])for h in[-1,1,11,12,-11,-12]for e in range(44)if' '!=M[e]and' '!=M[e+h]])
for y,x in zip(i,i[1:]):z+=[shortest_path(G,y,x)[1:],list(G[y])[0]+y][x==y]
print z

```

Try it online!

This solution gives the shortest possible output. The keyboard is transformed into a graph used to find the shortest path to compute the output string:

```
puzzles     --> poiuhbvcxzazxcvbhjklkiuytres
programming --> poiuytrtyuioijhgtresasdcvbnmkmkijnbg
code        --> cvbhjioijhgfde
golf        --> ghjiolkjhgf
yes         --> ytres
hi          --> hji
poll        --> polpl

```
> 10 votes

# Answer
# JavaScript (ES6), 70 bytes

Same strategy as TFeld.

```
s=>'qazsxdcfvgbhnjmklpoiuytrew'.repeat(s.length).match(s.join`.*?`)[0]

```

Try it online!
> 5 votes

# Answer
# 05AB1E, ~~43~~ ~~33~~ 31 bytes

```
ü2εUžV`.ιJsRìD«Œ.ΔнÅ?XyθÅ¿}¨}JIθ«

```

Not the right language for this challenge, since it cannot use regex like the other answers did.. EDIT: proven wrong by *@Makonede*'s 05AB1E answer using the Elixir eval builtin `.E`.

Try it online or verify all test cases.

**Explanation:**

```
ü2             # Split the input into overlapping pairs
               #  i.e. "poll" → ["po","ol","ll"]
  ε            # Map each to:
   U           #  Pop and store the current pair in variable `X`
   žV          #  Push ["qwertyuiop","asdfghjkl","zxcvbnm"]
     `         #  Pop and push all three separated to the stack
      .ι       #  Interweave the top two with each other
        J      #  Join the list of characters to a single string
               #   → "azsxdcfvgbhnjmkl"
         s     #  Swap so "qwertyuiop" is at the top
          R    #  Reverse it to "poiuytrewq"
           ì   #  Prepend it in front of the earlier string
               #   → "poiuytrewqazsxdcfvgbhnjmkl"
            D« #  Duplicate it, and append it to itself
               #   → "poiuytrewqazsxdcfvgbhnjmklpoiuytrewqazsxdcfvgbhnjmkl"
   Œ           #  Get all substrings of this strings
    .Δ         #  Find the first substring which is truthy for:
      Á        #   Rotate the current string once towards the right
       2£      #   Only leave the first 2 letters
         R     #   Reverse it
          XQ   #   Check if it's equal to pair `X`
     }¨        #  After the find_first, remove the last character
  }            # Close the map
   J           # Join everything together
    Iθ«        # Append the last character of the input
               # (after which the result is output implicitly)

```
> 4 votes

# Answer
# Charcoal, 48 bytes

```
≔”&⌈″⌊5ＥWＸＶＮa…-εW¶ζR”η≔⌕η§θ⁰ζＦθＦ⊕﹪⁻⌕ηιζ²⁶«§ηζ≦⊕ζ

```

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

```
≔”&⌈″⌊5ＥWＸＶＮa…-εW¶ζR”η

```

Get the string `qwertyuioplkmjnhbgvfcdxsza`.

```
≔⌕η§θ⁰ζ

```

Find the position of the first character of the word. This index is normally one past the character just reached, but this value fakes out the first iteration of the loop to print the first character of the word.

```
Ｆθ

```

Loop over each character.

```
Ｆ⊕﹪⁻⌕ηιζ²⁶«

```

Compute how many characters to print to include the next character of the word and loop that many times.

```
§ηζ≦⊕ζ

```

Print the next character cyclically indexed and increment the index.
> 4 votes

# Answer
# 05AB1E, ~~51~~ ~~39~~ 38 bytes

*-1 thanks to Kevin Cruijssen.*

```
gžV`.ιJsRì×s….*?ý’RŽ½™«.‡Ð~r/ÿ/,"ÿ"’.E

```

Try it online! Takes input as a list of lowercase letters and outputs as a singleton list.

This answer exists to prove Kevin Cruijssen wrong; you *can* use regex in 05AB1E.
> 2 votes

# Answer
# Vyxal, 16 bytes

```
Lk•÷Y$Ṙp*?‛€?jẎh

```

Try it Online!

```
Lk•÷Y$Ṙp*?‛€?jẎh
 k•              # List of rows on the keyboard: ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
   ÷             # Push each item onto the stack
    Y            # Interleave the top two: "azsxdcfvgbhnjmkl"
     $           # Swap so "qwertyuiop" is on top
      Ṙ          # Reverse it
       p         # Prepend it to the other string
L       *        # Repeat it input-length number of times
         ?‛€?j   # Join each character in the input by ".*?"
              Ẏh # Get the first regex match

```
> 1 votes

# Answer
# J-uby, 71 bytes

Again lost a few bytes by having to call `Regexp.new` with a string instead of using a Regexp literal with interpolation. Same technique as TField et al.

```
-[:+@|:*&"qazsxdcfvgbhnjmklpoiuytrew",~:join&".*?"|:new&Regexp]|:<<&:[]

```

Attempt This Online!

## Explanation

```
-[
  :+@ | :* & "qazsxdcfvgbhnjmklpoiuytrew",  # Repeat string times size of input
  ~:join & ".*?" | :new&Regexp              # Also make a Regexp by joining input with ".*?"
] |                                         # then
:<< & :[]                                   # call :[] with the two values, i.e. repeated_string[regexp]

```
> 0 votes

---
Tags: code-golf, open-ended-function, keyboard
---


title: Cats go Meow, Cows go Moo

text:
# Question
Title: Cats go Meow, Cows go Moo
Everyone knows that cats go meow, but what many don't realise is that caaaats go meeeeoooow. In fact, the length of the vowel sounds that the cat makes are dependant on the length of the vowel with which you address it.

In the same way, cows go moo, but coooows go moooooooo

## Challenge

You are to write a program that takes as input, a word meaning cat, **and** a word meaning cow, determine the number of main vowels, and print one of the following strings, as appropriate:

* `C[]ts go M[]w`
* `C[]ws go M[]`

Where `[]` stands for the vowels, according to the following rules:

* The number of e's and o's in "Meow" must both match the number of vowels found in the input word.
* The number of o's in "Moo" must be double the number of vowels found in the input word.

The program must recognise the input words `cat` and `cow`. Input may use any capitalisation that is most convenient, but the output must be capitalised exactly as shown above.

# Answer
## Retina, ~~57~~ ~~49~~ ~~44~~ ~~43~~ 41 bytes

~~So close...~~ ~~:)~~ Pyth...

```
.(.+).
$0s go M$1$1
+`aa(\w*$)
e$1ow
wo
o

```

Try it online.

Expects input to be capitalised like `Caaat` or `Coooow`.

### Explanation

```
.(.+).
$0s go M$1$1

```

The regex matches the entire input, and captures the vowels in group `1` (we don't need anchors, because the match cannot fail and will greedily match the entire input). The substitution writes back that input, and appends `s go M`, followed by twice the vowels. For inputs `Caaat` and `Coooow`, we get:

```
Caaats go Maaaaaa
Coooows go Moooooooo

```

The output for cows is already correct. We just need to do something about those cats.

```
+`aa(\w*$)
e$1ow

```

The `+` tells Retina to repeat this stage as often as possible. The regex matches two `a`s in the last part of the string (we ensure this with the `$` anchor, so that we don't replace things inside `Caaats`). This will essentially match everything after `M`, as long as that part still has `a`s. The two `a`s are removed and the entire suffix after it is wrapped in `e...ow`:

```
Caaats go Meaaaaow
Caaats go Meeaaowow
Caaats go Meeeowowow

```

Finally, there are two many `w`s in the result, so we remove those that precede an `o` (to make sure we're not messing up the `w` in `Coooows`):

```
wo
o

```

And we're left with:

```
Caaats go Meeeooow

```
> 17 votes

# Answer
# LabVIEW, 58 LabVIEW Primitives

creating strings like this is a pain...

The leftmost vis are pattern matching, a+ and o+ respectively search for the lagest amount of as and os in a row.

Taking the lenght of those i create 3 arrays 1 with lenght os 1 with lenght es and one with 2 times lenght os.

Then all the parts get put together. First the original input, then s go M all the Arrays, the unused one are empty so they will be ignored, and finally a w if the input was cats. (If as were found there will be a t after the match, if not after match is empty)

For the lolz i also implemented the fox with 6 different outputs^^
> 11 votes

# Answer
# Pyth, 50 44 34

Takes input in the format `["caat", "coow"]`.

```
Pj.bs[rN3"s go M"S*-lN2+Y\o\w)Q"eo

```

Try it online.

Explained:

```
  .b                                  Map a lambda across two lists in parallel:
                              Q       The input, e.g. ["caat", "coow"]
                               "eo    The string "eo"
    s[                       )            Create and concatenate a list of:
      rN3                                 - The item N in title caps (e.g. "Caat")
         "s go M"                         - The string "s go M"
                 S                        - The sorted version of:
                       +Y\o                   The item Y + "o" ("eo" or "oo")
                  *-lN2                       Times the length of N - 2 (number of vowels)
                           \w             - The string "w"
Pj                                    Join the result on \n and drop the final "w"

```

Thanks to Jakube for major reductions in length.
> 7 votes

# Answer
# Perl, ~~66~~ ~~61~~ ~~55~~ 54 bytes

*includes +1 for `-p`*

```
/[ao]+/;$\="s go M".$&=~y/a/e/r.o x($+[0]-1).(w)[/w/]

```

Input is expected to conform to `/^C[ao]+[tw]$/` (no trailing newline!)
Usage: `/bin/echo -n Caaat | perl -p 55.pl`

### Breakdown

```
/[ao]+/;
$\= "s go M"        # assign to $OUTPUT_RECORD_SEPARATOR, normally `\n`. Saves 1 vs `$_.=`
   . $&             # the matched vowels
     =~ y/a/e/r     # translate `a` to `e`; `/r` returns a copy.
   . o x($+[0]-1)   # append 'o', repeated. $+[0] is string position of last match end.
   . (w)[/w/]       # returns 'w' if there is no /w/ in the input, nothing if there is.

```

---

### Previous version:

```
@l=/[ao]/g;$x=$&x@l.o x@l;$y=$x=~y/a/e/?w:'';s/$/s go M$x$y/

```

*Commented*:

```
@l = /[ao]/g;               # captures $& as vowel and @l as list of vowels
$x = $& x @l .o x @l;       # construct the output vowels
$y = $x =~ y/a/e/ ? w : ''; # correct vowel string for cats (aaaooo->eeeooo); $y='w' if cat.
s/$/s go M$x$y/             # construct the desired output.

```

---

### Example: `Caaat`

* Capture `$&` as `a` and `@l` as `(a,a,a)`.
* Set `$x` to three times `a` followed by 3 times `o`: `aaaooo`.
* Translate all `a` in `$x` to `e`: `eeeooo`. The number of replacements (either 0 or positive) serves as a cat-detector: set `$y` to `w` if so.
* Change the input by appending `s go M`, `eeeooo` and `w`.

---

* *update 61*: Save 5 bytes by using list instead of string
* *update 55*: save 6 bytes by inlining, assigning `$\` rather than `s/$/`, and requiring no trailing newline in input.
* *update 54*: save 1 byte by eliminating @l.
> 5 votes

# Answer
## Python 2, 74 bytes

```
i=input()
l=len(i)-2
print i+'s go M'+['e'*l+'o'*l+'w','o'*l*2][i[-1]>'v']

```

Takes input

`Caaat` or `Cooow`
> 4 votes

# Answer
## CJam (60 57 55 53 bytes)

```
"C%s%ss go M%sw
"2*-2<q"ctw"-S/"teowoo"3/.{(2$,@*$}e%

```

Online demo. Input is assumed to be in lower case.

For the same length:

```
"C

s go M"N/_]"w
"a*q"ctw"-S/"teowoo"3/.{(2$,@*$M}]z

```

---

```
'CM"s go M"]2*q"ctw"-S/"teowoo"3/.{(2$,@*$}[MM"w
"]]z

```
> 2 votes

# Answer
## PowerShell, ~~135~~ 132 bytes

```
param($a,$b)
[char[]]"$a$b"|%{if($_-eq'a'){$c++}$d++}
$d-=4+$c
"C$("a"*$c)ts go M$("e"*$c)$("o"*$c)w"
"C$("o"*$d)ws go M$("o"*2*$d)"

```

<sub>(linebreaks count same as semicolons, so line-breaked for clarity)</sub>

Surprisingly tricky challenge. And I'm reasonably sure this can be golfed further.

Takes input strings as `$a` and `$b`. Concatenates them and casts them as a char-array, then pipes that through a loop `%{}`. Each letter is then checked if it's `-eq`ual to `'a'` and the associated counter variable is incremented appropriately. We then subtract `4+$c` from `$d` to account for `catcw` in the input, and proceed to formulate the output sentences, modifying the vowels output times the corresponding counters. (In PowerShell, `'e'*3` would yield `'eee'`, for example.)
> 1 votes

# Answer
## MATLAB: ~~190~~ ~~152~~ 118 bytes

```
i=input('','s');b=sum(i=='a');c=sum(i=='o');d=b>c;disp(['C',i(2:2+b+c),'s go M',i(2:1+b)+4,repmat('o',1,b+2*c),'w'*d])

```

Ungolfed:

```
i=input('','s');
b=sum(i=='a');
c=sum(i=='o');
d=b>c;
disp(['C',i(2:2+b+c),'s go M',i(2:1+b)+4,repmat('o',1,b+2*c),'w'*d])

```

Tests:

```
caaaaaaaats
Caaaaaaaats go Meeeeeeeeoooooooow

cooooows
Cooooows go Moooooooooo

```

P.S.: Thanks to @Kenney for nice suggestion (see comments)!
> 1 votes

# Answer
Almost similar to @omulusnr's answer but this produces the correct output and also input is case insensitive.

## PHP, 172

```
$p=$argv[1];
preg_match("/c([ao]+)/i",$p,$e);
$l=strlen($e[1]);
$s=($k=strcmp($e[0][1],'o'))?'eo':'oo';
echo $p,' go M',str_repeat($s[0],$l),str_repeat($s[1],$l),$k?'w':'';

```
> 1 votes

# Answer
# OCTAVE,  126 , 108

First version with variables and explanation, 126:

```
L="ao"';S={'eo','oo'},e={'w',' '};a=sum(argv(){1}==L,2);b=find(a);disp([argv(){1},' goes m',vec(ones(sum(a),1)*S{b})',e{b}]);

```

Explanation: L knows which animal contains which letter. S knows what they repeat. e knows the ending. You need to have "automatic broadcasting" turned on for this to work, but it should be by default in all Octaves I've used. Of course there exist shorter ways with for example command regexprep (regular expressions with replacement), but there has already been several such approaches in answers already, so that would be boring.

---

**Edit:** Skipping variables which only occur once, using octave on-the-fly indexing (don't know what it's called for real) and adding "i", input string variable:

```
i=argv(){1};a=sum(i=="ao"',2);b=find(a);disp([i,' goes m',vec(ones(sum(a),1)*{'eo','oo'}{b})',{'w',''}{b}]);

```
> 1 votes

# Answer
## Swift 2, 3̶8̶1̶ 333 bytes

```
func f(i:String)->String{var s=i.lowercaseString;s.replaceRange(s.startIndex...s.startIndex,with:String(s[s.startIndex]).uppercaseString);let c=i.characters.count-2;let l=s.characters.last;return(s+"s go M"+String(count:c,repeatedValue:l=="t" ?"e" :"o" as Character)+String(count:c,repeatedValue:"o" as Character)+(l=="t" ?"w" :""))}

```

**Ungolfed:**

```
func f(i:String)->String{
    var s = i.lowercaseString
    s.replaceRange(s.startIndex...s.startIndex,with:String(s[s.startIndex]).uppercaseString)
    let c = i.characters.count-2
    let l = s.characters.last
    return(s+"s go M"+String(count:c,repeatedValue:l=="t" ?"e" :"o" as Character)+String(count:c,repeatedValue:"o" as Character)+(l=="t" ?"w" :""))
}

```

Takes cat or cow any capitalization. You can try it here:

http://swiftlang.ng.bluemix.net/#/repl/3f79a5335cb745bf0ba7698804ae5da166dcee6663f1de4b045e3b8fa7e48415
> 1 votes

# Answer
# JavaScript (ES2015), ~~78~~ 77

```
s=>s+'s go M'+(l=s.length-1,w=s[l]<'u',Array(l).join(w?'eo':'oo')+(w?'w':''))

```

Try it here: https://jsbin.com/guqaxejiha/1/edit?js,console
> 1 votes

# Answer
# PHP, 138 bytes

```
echo ucfirst($a=$argv[1]).'s go M'.(($n=substr_count($a,'a'))?str_repeat('e',$n).str_repeat('o',$n).'w':str_repeat('oo',substr_count($a,'o')));

```

---

readable:

```
echo ucfirst($a = $argv[1]) . 's go M'. (
    ($n = substr_count($a, 'a'))
        ? str_repeat('e', $n) . str_repeat('o', $n) . 'w'
        : str_repeat('oo', substr_count($a, 'o'))
);

```

tried shorter but wont work in PHP:

```
#too long -- echo ucfirst($s=$argv[1]).'s go M'.(($o='o'and$n=substr_count($s,'a'))?str_repeat('e',$n).str_repeat($o,$n).'w':str_repeat('oo',substr_count($s,$o)));
#too long -- echo ucfirst($s=$argv[1]).'s go M'.(($o='o'and$f=function($s,$n){return str_repeat($s,$n);}and$n=substr_count($s,'a'))?$f('e',$n).$f($o,$n).'w':$f('oo',substr_count($s,$o)));

```

=)
> 1 votes

# Answer
# Dart, ~~114 112 110 104 102~~ 100 bytes

```
f(s)=>s+'s go M'.padRight(s[1]=='a'?s.length+4:0,'e').padRight(2*s.length+2,'o')+(s[1]=='a'?'w':'');

```

Try it online!

- -2 bytes : Changed the way the u offset is calculated to reduce the number of additions
- -2 bytes : Moved the check on the first pasdding to the width and not the character
- -6 bytes : Changed the Cow/Cat check
- -2 bytes : Got rid of variable assignments
- -2 bytes : Reduced then umber of parentesis on 2\*(s.length+1)
> 1 votes

# Answer
# Ruby `-nl`, 64 bytes

```
~/([ao]+)(.)/
x=$1.size
$_<<"s go M"+($2<?w??e*x+?o*x+?w:"oo"*x)

```

Attempt This Online!
> 1 votes

# Answer
## Lua, 121 90 Bytes

**121 Bytes**

```
i=...r="M"o="o"s=i:len()-3if(i:find("w"))then r=r..o:rep(s*2)else r=r..("e"):rep(s)..o:rep(s).."w"end print(i.." go "..r)

```

**90 bytes**

```
i=....." go M"o="o"s=#i-7 print(i..(i:find"w"and o:rep(s*2)or("e"):rep(s)..o:rep(s).."w"))

```

Takes input such as 'Caats' or 'Coooows' case-sensitive. Since there are no requirements for invalid inputs, the output might be weird for, say, 'Foxes' or 'Oxen'. :P

**Ungolfed**

```
i=... .. " go M"
o="o"
s=#i-7
print(i..
         (i:find"w"and o:rep(s*2) or
         ("e"):rep(s)..o:rep(s).."w")
      )

```

*Update to 90 Bytes:* Replaced if-control structure with logical operators, optimized string concatenation by appending more data in declaration of `i`. Removed parenthesis on `i:find("w")`. Interestingly enough, storing `"o"` to a variable saved a couple bytes when using `rep`, but would be counterproductive with `"w"` or `"e"`. The more you know.
> 0 votes

# Answer
# Lua: ~~115~~ ~~92~~ 89 Bytes

```
i=...l=#i-2o="o"io.write(i,"s go M",i:find"a"and("e"):rep(l)..o:rep(l).."w"or o:rep(l*2))

```

takes `C[]t` or `C[]w` as input; \[\] = a's or o's. A lowecase input will translate to the result.

long version:

```
i=...   --"C[]t" or "C[]w"
l=#i-2  --length of input -2
o="o"   --shorten usage of "o"
io.write(i,"s go M",i:find"a"and("e"):rep(l)..o:rep(l).."w"or o:rep(l*2))

-- if it's a C"a"t concat "s go M" then repeat  --> Cats/Cows go M
-- "e" and then "o" l times and concat else     --> Cats go Meo
-- repeat "o" l*2 times and concat              --> Cows go Moo
-- concat "w" and output evrything              --> Cats go Meow

```

Example outputs:

```
Caaat --> Caaats go Meeeooow
Cat   --> Cats go Meow
Cow   --> Cows go Moo

```

Edit: changed `if` `then` `else` to `and` `or`. removed ALL the non string space's.

Also you cat try it here: Execute Lua Online but I couldn't figure out how to use the terminal so I've put it in a function.

Edit: changed usage of "o" and removed () from `:find`. credit goes to **Cyv** for finding those optimizations. Added "s" and changed `l=#i-3` to `l=#i-2`

With input including "s" only 88 byte:

```
i=...l=#i-3o="o"io.write(i," go M",i:find"a"and("e"):rep(l)..o:rep(l).."w"or o:rep(l*2))

```
> 0 votes

# Answer
# PHP, ~~170~~ ~~164~~ ~~161~~ 157 bytes

```
preg_match("/(?i)c([ao]+)/",$argv[1],$e);
$n=strlen($e[1]);
$c=$e[1][0];
$a=($c=="a"?("ew"):("o"));
echo "M".str_repeat($a[0],$n).str_repeat("o",$n).$a[1]."\n";

```

Takes any capitalization whatsoever. `CaAaT`, `coOOOw`, whatever.

*v2: don't really need \[wt\]$. also corrected char ct*
*v3: char ct was all wrong, condensed $a and $e assignment*
*v4: save 3 bytes on $af-\>$a*
*v5: save 4 bytes by onelining it (not shown)*
> -1 votes

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


title: Swap, delete and repeat

text:
# Question
Title: Swap, delete and repeat
### Introduction

Let's observe the following string:

```
ABCDEFGHIJKLMNOP

```

If we swap the **ends of the string**, which are these:

```
ABCDEFGHIJKLMNOP
^^            ^^

```

We get the following result:

```
BACDEFGHIJKLMNPO

```

After that, we delete the ends of the string, which in this case are `B` and `O`. The result is:

```
ACDEFGHIJKLMNP

```

If we repeat the process, we get the following list:

```
N     Result

2     ADEFGHIJKLMP
3     AEFGHIJKLP
4     AFGHIJKP
5     AGHIJP
6     AHIP
7     AP

```

You can see that for **N = 5**, the result is `AGHIJP`. At **N = 7**, the length of the string is smaller than **3**, so N \> 7 is considered *invalid* in this case.

### The Task

Given a string **S** with *at least* length 4 and the number of repetitions **N** \> 0, output the final result. You can assume that N is always *valid*.

### Test cases

```
Input                               >  Output

N = 3, S = ABCDEFGHIJKLMNOP         >  AEFGHIJKLP
N = 1, S = Hello                    >  Hlo
N = 2, S = 123321                   >  11

```

This is , so the submission with the least amount of bytes wins! For the simplicity, you can assume that the string will only contain **alphanumeric** characters.

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

```
th"P[]2(

```

Inputs are: first `N` as a unary string with quotes (allowed by the challenge); second `S` as a string with quotes (quotes in strings are allowed by default); separated by a linebreak.

This works by flipping the string, removing its second element, and repeating for a total of `2*N` times.

**Try it online!**

```
th       % implicitly take first input (N) as a unary string. Concatenate horizontally
         % with itself: gives a string of 2*N ones
"        % for each (i.e., repeat 2*N times)
  P      %   flip string. Take S implicitly as input the first time
  []     %   empty array (used as new contents)
  2      %   2 (used as index)
  (      %   assign [] to position 2 of string; that is, remove second element
         % implicitly end for each
         % implicitly display

```
> 5 votes

# Answer
# Retina, ~~44~~ 20 bytes

Crossed out 44 is still regular 44 :(

```
+`'(\w).(.*).\B
$1$2

```

Assumes input in following format (in unary - counting character: `'`):
`{number of repeats}{string}`
For example: `'''''''ABCDEFGHIJKLMNOP`
There is no space between number of repeats and the string.

Thanks @MartinBüttner for shaving off 24 bytes!

Try it online!
> 19 votes

# Answer
## Python 2, 31 bytes

```
lambda s,n:s[0]+s[n+1:~n]+s[-1]

```

I think this works?
> 12 votes

# Answer
## Labyrinth, 40 bytes

```
<
,,}:?
.
;("   {(={}{".
,",;=};} }) "{@

```

Input is `N` followed by the string, separated by any non-numeric character.

Try it online!

This was written in collaboration with Sp3000 (which means I couldn't be bothered to figure out an algorithm, so he started working on it, came up with 118 byte solution but couldn't be bothered golfing it, so I did the golfing... yay for teamwork).

### Explanation

Sp's usual primer (as usual slightly modified):

* Labyrinth is a stack-based 2D language with two stacks, main and auxiliary. Pretty much everything happens on the main stack, but you can shift values over to the other one, e.g. to reverse them or save them for later.
* The stacks are bottomless and filled with zeroes, so popping from an empty stack is not an error.
* Execution starts from the first valid character (here the top left). At each junction, where there are two or more possible paths for the instruction pointer (IP) to take, the top of the stack is checked to determine where to go next. Negative is turn left, zero is go forward and positive is turn right. While this was *meant* to make the code look like winding, twisty passages, there's nothing stopping you from making "rooms" where these conditions are checked in every cell. Those can yield quite unpredictable behaviour, but are great for golfing.
* The source code (and therefore the layout of the labyrinth) can be modified at runtime using `<>^v` which cyclically shifts a row or column or the grid.
* `"` are no-ops.

Here we go.

The code starts on the `<`, which is a golfing trick I've used a few times when starting with a long piece of linear code. It shifts the first row cyclically to the left, *with the IP on it*, so the source then looks like this:

```
              <
,,}:?
.
;("   {(={}{".
,",;=};} }) "{@

```

But now the IP can't move anywhere, so it executes the `<` again. This continues until we reach this state:

```
    <
,,}:?
.
;("   {(={}{".
,",;=};} }) "{@

```

At this point, the IP can leave the cell and begin executing the second line starting from the `?`. So here's the linear code broken down:

```
?   # Read the first integer on STDIN, i.e. N.
:}  # Duplicate it and move one copy over to the auxiliary stack.
,   # Read the separator character.
,.  # Read the first character of the input string and directly print it.

```

The IP now enters this 3x2 room, which is actually two tightly-compressed (overlapping) 2x2 clockwise loops. The first loop reads and discards `N-1` characters from STDIN.

```
;   # Discard the top of the stack. On the first iteration, this is the
    # separator we've already read. On subsequent iterations this will be
    # one of the N-1 characters from the input string.
(   # Decrement N. If this hits zero, we leave the loop, otherwise we continue.
,   # Read the next character from STDIN to be discarded.

```

Now we enter the second loop which reads the remainder of the input string. We can detect EOF because `,` will return `-1` in that case, making the IP turn left.

```
,   # Read a character. Exit the loop if EOF.
(   # Decrement it.

```

That decrement isn't actually useful, but we can undo it later for free and here it allows us to overlap the two loops.

If we take the `5 ABCDEFGHIJKLMNOP` input as an example, the stack looks like this:

```
Main [ ... 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' -1  |  5 ... ] Auxiliary

```

Note that these actually correspond to the input characters `FGHIJKLMNOP` (because we decremented them), and that we don't actually want to print the first of those (we've only discarded `N-1` characters, but want to skip `N`).

Now there's a short linear bit that prepares the stack for the next loop:

```
;   # Discard the -1.
=   # Swap the tops of the stacks, i.e. N with the last character.
    # By putting the last character on the auxiliary stack, we ensure that
    # it doesn't get discarded in the next loop.
}   # Move N over to the auxiliary stack as well.

```

The stacks now look like:

```
Main [ ... 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N'  |  5 'O' ... ] Auxiliary

```

We enter another 2x2 clockwise loop. This discards the top `N` characters from the main stack:

```
;   # Discard the top of the main stack.
{   # Pull N over from the auxiliary stack.
(   # Decrement it. It it's 0 we leave the loop.
}   # Push N back to the auxiliary stack.

```

When we exit the loop `=` swaps that `0` and the last character of the input string again. Now the stacks look like this:

```
Main [ ... 'E' 'F' 'G' 'H' 'I' 'O'  |  ... ] Auxiliary

```

We want to print the contents of the main stack (except the bottom element and all incremented by 1), *from the left*. That means we need to get it over to the auxiliary stack. That's what the next 2x2 (clockwise) loop does:

```
{   # Pull an element over from the auxiliary stack. This is necessary so we
    # have a 0 on top of the stack when entering the loop, to prevent the IP
    # from turning right immediately.
}   # Move the top of the main stack back to the auxiliary stack. If this was the
    # bottom of the stack, exit the loop.
)   # Increment the current character.
}   # Move it over to the auxiliary stack.

```

Stacks now:

```
Main [ ...  |  'F' 'G' 'H' 'I' 'J' 'P] ... ] Auxiliary

```

We move the first of those (the one we don't want to print) back to the main stack with `{`. And now we enter final 2x2 (*counterclockwise*) loop, which prints the rest:

```
{   # Pull another character over from the auxiliary stack. Exit the loop
    # if that's the zero at the bottom of the stack.
.   # Print the character.

```

Finally we terminate the program with `@`.
> 10 votes

# Answer
# Mathematica, 29 bytes

My first answer!

```
#~Delete~{{2},{-2}}&~Nest~##&

```

The crux of bracketless Mathematica! Function inputs are a list (of characters, or whatever) and a number.
> 9 votes

# Answer
## JavaScript (ES6), 39 bytes

```
(s,n)=>s[0]+s.slice(++n,-n)+s.slice(-1)

```

Turns out I just reinvented @Sp3000's answer.
> 6 votes

# Answer
# Jelly, 8 bytes

```
Ḣ1¦UðḤ}¡

```

Try it online!

### How it works

```
Ḣ1¦UðḤ}¡  Main link. Left input: S (string). Right input: N (deletions)

Ḣ         Pop the first element of S.
          This return the element and modifies S.
 1¦       Apply the result to the first index.
          This replaces the first character of the popped S with the popped char.
   U      Upend/reverse the resulting string.
    ð     Convert the preceding chain into a (dyadic) link.
     Ḥ}   Apply double to the right input.
          This yields 2N.
       ¡  Repeat the link 2N times.

```
> 6 votes

# Answer
## Jelly, 10 bytes

```
Ḣ;ṪjḊṖ$Ɠ¡F

```

Input the number via STDIN, and the string via command line args. Thanks to @Dennis for a lot of hints/help getting this to work (Jelly still eludes me).

Try it online!

```
Ḣ;Ṫ               Pop first and last chars of string and concatenate
   j              Join by...
       Ɠ¡           Execute n times...
    ḊṖ$               Drop first, drop last of string ($ combines the two monadically)
         F        Flatten to filter out empty lists, since Jelly's j is weird

```
> 5 votes

# Answer
## Pyth, 13 bytes

```
++hz:zhQ_hQez

```

Explanation:

```
              - autoassign z = input()
              - autoassign Q = eval(input())
    :zhQ_hQ   -  z[Q+1:-(Q+1)]
++hz       ez - z[0]+^+z[-1]

```

Try it here
> 4 votes

# Answer
# Python 2, ~~49~~ 48 bytes

```
g=lambda s,n:n and g(s[0]+s[2:-2]+s[-1],n-1)or s

```

Try it here with testcases!

Simple recursive solution. Removes the second and last second element from the input string and calls itself with this and `n-1` until `n=0`.

**edit:** Feeling kinda stupid, looking at the other python solution. Guess I just like recursion too much...
> 4 votes

# Answer
# Vitsy, ~~12~~ 9 (code) + 1 (newline for function declaration) = 10 bytes

\o/

Expects input on the stack as the string followed by the number.

```
2*\[vXvr]
2*         Multiply by 2.
  \[    ]  Do the stuff in the brackets that many times. (input num * 2)
    v      Take the top item off the stack and save it as a local variable.
     X     Remove the top item of the stack.
      v    Push the temporary variable back onto the stack.
       r   Reverse the stack.
```

Which you can call with:

```
'String' r <number> 1m Z
2*\[vXvr]
```

This is a function that leaves the resultant string on the stack. I have provided it as a program in the TryItOnline link.

TryItOnline!
> 4 votes

# Answer
## Ruby, 29 bytes

```
->s,n{s[0]+s[n+1...~n]+s[-1]}

```

Very straightforward.

`~` trick stolen from Sp's answer, which saves a byte over `s[n+1..-2-n]`. (It works because `~n` is `-1-n` in two's-complement, and then `...` is an exclusive range.)
> 4 votes

# Answer
## Perl, ~~36~~ 32 + 1 = 33 bytes

```
for$i(1..<>){s;\B.(.+).(.);$1$2;}

```

Requires `-p` flag and takes input on two lines, with numbers of iterations at the end:

```
$ perl -pe'for$i(1..<>){s;\B.(.+).(.);$1$2;}' <<< $'ABCDEFGHIJKLMNOP\n4'
AFGHIJKP

```

Ungolfed?

```
for $i ( 1..<> ) {
  s;
  \B.(.+).(.);$1$2;x
}

```
> 4 votes

# Answer
# C, 96 bytes

```
i;main(c,v,p)char**v,*p;{i=atoi(v[2])+1;c=strlen(p=v[1]);printf("%c%.*s%s",*p,c-2*i,p+i,p+c-1);}

```

## Ungolfed

```
i; /* Param 2, the number of chars to remove */

main(c,v,p)char**v,*p;
{
    i=atoi(v[2])+1; /* convert param 2 to integer */
    c=strlen(p=v[1]); /* Length of the input */
    printf("%c%.*s%s",*p, /* Print the first char... */
        c-2*i, /* a number of characters equal to the length minus twice the input... */
        p+i, /* skip the "removed" chars... */
        p+c-1); /* Print the last character of the string */
}

```
> 4 votes

# Answer
## Rust, 135 bytes

Well, that's a pretty terrible length.

```
fn f(s:&str,n:usize)->String{let s=s.as_bytes();s[..1].iter().chain(&s[n+1..s.len()-n-1]).chain(s.last()).map(|d|*d as char).collect()}

```

Pretty-printed:

```
fn f(s: &str, n: usize) -> String {
    let s = s.as_bytes();
    s[..1].iter()
          .chain(&s[n+1..s.len()-n-1])
          .chain(s.last())
          .map(|d| *d as char)
          .collect()
}

```

You can get it down to **104** bytes if we allow bytestrings instead of proper strings.

```
fn f(s:&[u8],n:usize)->Vec<u8>{let mut r=vec![s[0]];r.extend(&s[n+1..s.len()-n-1]);r.extend(s.last());r}

```

Pretty-printed:

```
fn f(s: &[u8], n: usize) -> Vec<u8> {
    let mut r = vec![s[0]];
    r.extend(&s[n+1..s.len()-n-1]);
    r.extend(s.last());
    r
 }

```

Curious if anyone can do better.
> 4 votes

# Answer
# CJam, 12 bytes

```
q~{VW@)t(t}*

```

Try it online!

### How it works

```
q~            Read and evaluate all input. This pushes S (string) and N (integer).
  {       }*  Do the following N times:
   VW           Push 0 and -1.
     @          Rotate S on top of them.
      )         Pop the last character of S.
       t        Set the item at index -1 to that character.
        (       Pop the first character of S.
         t      Set the item at index 0 to that character.

```
> 3 votes

# Answer
# Octave, 28 bytes

```
@(S,N)S([1,N+2:end-N-1,end])

```

Index the string, omitting `S(2:N+1)` and `S(end-N:end-1)`.

Sample run on ideone.
> 3 votes

# Answer
# Vim, 27 bytes

```
o0lxehx <ESC>"ay0ddA@a<ESC>B"bdWx@b

```

Input is expected to be in the form `STRING N` on the first line with no other characters.

Explanation:

```
#Write a macro to do one round of the swap and delete and save to register a
o0lxehx <ESC>"ay0dd

#Append register a to N and save in register B so it will run @a N times.
A@a<ESC>B"bdWx

# Actually run the macro
@b

```
> 3 votes

# Answer
# mSL - 137 bytes

```
c {
%l = $len($1)
return $mid($+($mid($1,2,1),$left($1,1),$right($left($1,-2),-2),$right($1,1),$mid($1,$calc(%l -1),1)),2,$calc(%l -2))
}

```

## Explanation:

`%l = $len($1)` will get the length of the input string and saves it in variable called l

`$right(<input>,<length>)` and `$left(<input>,<length>` can be used to return the left or right most part of the original string respectably. $left always return text starting from the very left side while $right always return text starting from the right side. If the length specified is a negative number, $left and $right return the entire text minus that many characters from their respective sides.

`$mid(<string>,<start>,[length])` is used to get a substring from the middle of the string. Start is the start of the substring from the left. A negative value indicates a start from the right. In both case, an optional length can be specified. A negative length can be used to remove that many characters from the end. So I used it to retrieve the second character and the second last character by using the length of the input string.

`$calc(<input>)` is used to perform mathematical calculations
> 3 votes

# Answer
## Brainfuck, 130 bytes

My first PPCG entry!

Obviously not gonna win but hey.

Takes input like: 4ABCDEFGHIJKL, with the first character being N.

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

```

Test it on this wonderful site.

Limited to N less than or equal to 9, because two-digit numbers are a pain in the butt.

EDIT: I sucked it up and added support for two-digit numbers. Pad with a zero for single digits.

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

```
> 3 votes

# Answer
## As of yet untitled language (so new noncompetitive), 9 bytes

```
hD_RQ:Q|J

```

You can find the source code here, language is completely unstable (first test challenge for it) so don't expect it to work in the future (commit 7)

This is a stack based language with functions that add and remove objects from the stack. There are currently 2 stack manipulation commands: `D`(duplicate the top of the stack N times) and `R`(rotate the top N items on the stack)

Explanation:

```
          - autoassign Q = eval_or_not(input()) (string)
h         - imp_eval_input()+1
 D        - duplicate(^)
  _       - neg(^)
   R      - rotate(^)
    Q:    - Q[^:^]
      Q|  - Q[0], Q[-1]
        J - "".join(all)

```
> 2 votes

# Answer
## CJam, 14 bytes

```
l(o)\l~_W*@<>o

```

Test it here.

### Explanation

```
l   e# Read the input string.
(o  e# Pull off the first character and print it.
)\  e# Pull off the last character and swap with the rest of the string.
l~  e# Read the second line of the input and evaluate it (N).
_   e# Duplicate.
W*  e# Multiply by -1 to get -N.
@   e# Pull up the string.
<   e# Discard the last N characters.
>   e# Discard the first N characters.
o   e# Output what's left. The last character of the input is now still on the
    e# stack and is automatically printed at the end of the program.

```
> 2 votes

# Answer
# Perl, 27 bytes

Include +1 for `-p`

Run as `perl -p sdr.pl`

Input given on STDIN, first line the string, second line the count Assumes the string contains only "word" characters

`sdr.pl`:

```
eval's%\B.(.*).\B%$1%;'x<>

```
> 2 votes

# Answer
# Vyxal , 8 bytes

```
f÷?d($_^

```

Try it online!

Explanation:

```
f         # Get the list of characters
 ÷        # and push each one to the stack.
   d      # Double
  ?       # the input
    (     # times:
     $    #   swap the top two items
      _   #   pop the stack
       ^  #   then reverse the stack.
          # Sum the whole stack and print

```
> 2 votes

# Answer
# Factor, 47 bytes

```
[ 1 cut pick tail 1 cut* swap roll head* glue ]

```

Try it online!

```
       ! 5 "ABCDEFGHIJKLMNOP"
1      ! 5 "ABCDEFGHIJKLMNOP" 1
cut    ! 5 "A" "BCDEFGHIJKLMNOP"
pick   ! 5 "A" "BCDEFGHIJKLMNOP" 5
tail   ! 5 "A" "GHIJKLMNOP"
1      ! 5 "A" "GHIJKLMNOP" 1
cut*   ! 5 "A" "GHIJKLMNO" "P"
swap   ! 5 "A" "P" "GHIJKLMNO"
roll   ! "A" "P" "GHIJKLMNO" 5
head*  ! "A" "P" "GHIJ"
glue   ! "AGHIJP"

```
> 2 votes

# Answer
# CJam, 15 bytes

```
r(\)\{(;);}ri*\

```

I'm sure it's possible to golf this further...
> 1 votes

# Answer
# PHP, 60 bytes

This solution iteratively sets characters from the input string to an empty string by index. I'm manipulating the input string directly to prevent a long `return`.

```
function(&$w,$i){for(;$i;)$w[$i--]=$w[strlen($w)-$i-2]="";};

```

Basically in memory `$w` looks like this when done:

```
Addr 0 1 2 3 4
     H   l   o
     ^   ^   ^
>Result: Hlo

```

Run like this:

```
php -r '$f = function(&$w,$i){for(;$i;)$w[$i--]=$w[strlen($w)-$i-2]="";}; $f($argv[1],$argv[2]);echo"$argv[1]\n";' Hello 1

```
> 1 votes

# Answer
# Pylons, 16 Bytes.

```
i:At,{\,v\,v,A}c

```

How it works:

```
i    # Get command line input.
:At  # Set A equal to the top of the stack.
,    # Pop the stack.
{    # Start a for loop.
 \   # Swap the top two elements of the stack.
  ,  # Pop the stack.
   v # Reverse the stack.
 \   # Swap the top two elements of the stack.
  ,  # Pop the stack.
   v # Reverse the stack.
 ,   # Switch to loop iterations.
 A   # Iterate A times.
}    # End the for loop.
c    # Print the stack as a string

```
> 1 votes

# Answer
# Jolf, 13 bytes

```
ΆFi liγhj_γgi

```

A tranpilation of the JavaScript answer.

Explanation:

```
ΆFi liγhj_γgi
Ά             ternary add
 Fi            i[0],
   `li         i sliced
      γhj       γ = j + 1
         _γ     to -γ
           gi  and the last of i

```

Try it here!

A more interesting post-question version:

```
 ΆFi]ihjYgi

```
> 1 votes

# Answer
## Seriously, 17 bytes

```
,#,`p@pXod@dXq`nΣ

```

Takes input as `s \n n`.

Try it online!

Explanation:

```
,#,`p@pXod@dXq`nΣ
,#                 push a list of characters in s
  ,`          `n   do the following n times:
    p@pXo          pop 2 characters off the front, discard the second, put the first back
         d@dXq     pop 2 characters off the back, discard the second, put the first back
                Σ  join

```
> 1 votes

# Answer
## bash + GNU coreutils, ~~93~~ 83 Bytes

```
s=$2
for i in `seq $1`;do
s=`sed 's/\(.\).\(.*\).\(.\)/\1\2\3/'<<<$s`
done
echo $s

```

I wanted to find an answer in pure *sed*, but I am not sure if counters are possible this way...

Invocation:

```
./testgolf.sh 3 ABCDEFGHIJKLMNOP

```

Explanation:

```
s=$2  # Store second parameter into variable
for i in `seq $1`;do   # loop number of first parameter times...
s=`sed 's/\(.\).\(.*\).\(.\)/\1\2\3/'<<<$s`
#         +-1-+ +-2--+ +-3-+
# sed splits the string into 3 placeholders
# to create the new string by use of substitution.
# s=$`...` stores the output into the variable.
# <<<$s sends the content of the variable to stdin of sed.
done
echo $s  # output content of the variable now.

```
> 1 votes

# Answer
# C#, 129 bytes

Since we basically skip 1 and remove N and the reversed scenario

```
string o(string i,int n){var s=i.ToList();int x=0;while(x<2){s.RemoveRange(1,n);s.Reverse();x++;}return new string(s.ToArray());}

```

ungolfed

```
string o(string i, int n)
{
    var s = i.ToList();
    int x = 0;
    while (x < 2) //Repeat the following twice
    {
        s.RemoveRange(1, n); //remove n at index 1
        s.Reverse(); //Reverse the list
        x++;
    }
    return new string(s.ToArray());
}

```
> 1 votes

# Answer
# Java, 144 bytes

```
static String y(int i,String s){return i==0?s:y(i-1,new StringBuffer(s).replace(1,2,"").replace(s.length()-3,s.length()-2,"").toString());}

```
> 1 votes

# Answer
## PHP 76 Bytes

```
while($n>=0){$s=substr($s,0,1).substr($s,2,-2).substr($s,-1,1);$n--;}echo$s;

```

Explanation is one word, `substr`!

I assumed `$n` and `$s` are inputs. Correct me if this is incorrect, or if `<?php` is required.

**Long hand**

```
<?php

$n = 3;
$s = 'ABCDEFGHIJKLMNOP';

while ($n >= 0) {
    $s = substr($s, 0, 1) . substr($s, 2, -2) . substr($s, -1, 1);
    $n--;
}
echo $s;

```
> 1 votes

# Answer
# Forth (gforth), 62 bytes

```
: f >r over 1 type i 1+ m+ i 1+ 2* - 2dup type + r> + 1 type ;

```

Try it online!

### Code Explanation

```
: f            \ start a new word definition
  >r           \ store N on the return stack for easier access
  over 1 type  \ print the first character
  i 1+ m+      \ add N + 1 to the string starting address
  i 1+ 2* -    \ get the length of the middle section (strlen - 2*(N+1))
  2dup type    \ output the middle section
  + r> +       \ get the address of the last character in the string
  1 type       \ output the last character in the string
;              \ end word definition

```
> 1 votes

# Answer
# Keg, 11 bytes

Finally, a challenge built for Keg!

```
?(¿2*|$_^)^

```

Try it online!

# Explanation

```
?           Take a string input
 (¿         Repeat the following code block integer input
   2*       * 2 times:
     |$     Swap the ends of the string
       _    Discard the end
        ^   Repeat the process
         )^ Reverse the input back (because input is reversed)

```
> 1 votes

# Answer
# Rust, 89 bytes

```
|s:&[_],n|(0..1).chain(n+1..s.len()-n-1).chain(s.len()-1..s.len()).map(|i|s[i]).collect()

```

Inputs as a `&[u8]` and outputs as a `Vec<u8>`. Or a `&[char]` to `Vec<char>`.

Playground Link

Rust may not be a very concise language but also a lot of rust answers in this site are sub-optimal. Including this one probably.
> 1 votes

# Answer
# Vyxal, 6 bytes

```
(ÞẇḢṪj

```

Try it Online!

```
(      # N times...
 Þẇ    # Unwrap (push first+last and rest
   ḢṪ  # Remove first and last chars of rest
     j # Insert back into the first + last

```
> 1 votes

# Answer
## Python, ~~78~~ 59 bytes

### Golfed

```
def s(t,n):return t if n==0 else s(t[0]+t[2:-2]+t[-1],n-1)

```

Try it here!

### Ungolfed

```
def swapDeleteRepeat (text, n):
    if n == 0:
        return text
    else:
        return swapDeleteRepeat (text[0] + text[2:-2] + text[-1], n - 1)

```
> 0 votes

# Answer
# GolfScript, 16 bytes

Assuming that **N** goes after **S**.

```
~2*{.1<\2>+-1%}*

```

Try it online!

## Explanation

```
~                # Take inputs in the form of S, N.
 2*{          }* # Repeat N*2 times:
    .1<\2>+      #    Remove the second character
           -1%   #    Reverse the string

```
> 0 votes

# Answer
# Japt, 11 bytes

```
jUÊ-VÉV j1V

```

Try it

This would be a couple bytes shorter if `j` worked with negative indexes.

```
jUÊ-VÉV j1V #
j     V     # Remove N characters from S starting at index:
 UÊ         #  Length of S
   -V       #  Minus N
     É      #  Minus 1
        j V # Remove N characters from S starting at index:
         1  #  1

```
> 0 votes

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


title: Nth FizzBuzz Number

text:
# Question
Title: Nth FizzBuzz Number
# Introduction

Everyone knows the FizzBuzz sequence. It goes something like this:

```
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
.
.
.

```

In case you don't know, if the number is divisible by 3, it's `Fizz`. If it is divisible by 5, it's `Buzz`. If it is divisible by both, it's `FizzBuzz`. If it is not divisible by both, it's just the original number.

# Task

Take two inputs, for example (space separated here)

```
Fizz 3

```

For this specific example input, you should output `9`, the third `Fizz`. To be more general, take a `word` and a `number`, output the `number`th `word`.

The `word` input may be `Number`, and in this case, you should output the `number`th number in the FizzBuzz sequence that is not `Fizz`, `Buzz`, or `FizzBuzz`.

You may choose any 4 distinct, consistent inputs representing `Fizz`, `Buzz`, `FizzBuzz` and `Number`.

# Test Cases

```
Fizz 3 => 9
Buzz 4 => 25
FizzBuzz 2 => 30
Number 312 => 584

```

# Scoring

Shortest code wins!

# Rules

* No standard loopholes.

# Answer
> 6 votes
# Jelly, 10 bytes

```
³3,5ḍḄ⁼ʋ#Ṫ

```

Try it online!

This uses `0 = Number`, `1 = Buzz`, `2 = Fizz` and `3 = FizzBuzz`

# Jelly, 8 bytes

```
1g15=ɗ#Ṫ

```

Try it online!

Thanks to Lynn. This uses `1 = Number`, `3 = Fizz`, `5 = Buzz`, `15 = FizzBuzz`. Included separately as the numbers could encode extra data

## How they work

```
³3,5ḍḄ⁼ʋ#Ṫ - Main link. Takes W=0,1,2,3 on the left, n on the right
       ʋ   - Last 4 links as a dyad f(k, W):
 3,5ḍ      -   Divisible by 3 or 5? Yields [0,0], [0,1], [1,0], [1,1]
     Ḅ     -   From binary; Yields 0, 1, 2, 3
      ⁼    -   Equals W?
³       #Ṫ - Starting from W, count up k = W, W+1, ..., returning the nth integer such that f(k, W) is true

```

```
1g15=ɗ#Ṫ - Main link. Takes W=1,3,5,15 on the left, n on the right
     ɗ   - Last 3 links as a dyad f(k, W):
 g15     -   GCD(k, 15)
    =    -   Does that equal W?
1     #Ṫ - Count up k = 1, 2, ..., returning the nth integer such that f(k, W) is true

```

# Answer
> 5 votes
# JavaScript (ES6), 44 bytes

Expects `(s)(n)` with s=0 for *Number*, s=1 for *Fizz*, s=2 for *Buzz* and s=3 for *FizzBuzz*.

```
(s,k=0)=>g=n=>n?g(n-=s==!(++k%3)+2*!(k%5)):k

```

Try it online!

---

### Cheaty version, 35 bytes

Expects 4680 for *Fizz*, 1056 for *Buzz*, 1 for *FizzBuzz* and 27030 for *Number*.

```
(s,k=0)=>g=n=>n?g(n-=s>>++k%15&1):k

```

Try it online!

# Answer
> 4 votes
# Perl 5 -p, ~~52~~ 47 bytes

Saved 5 bytes thanks to @Dom Hastings.

```
/ /;$_=332312332132330x$';/(.*?$`){$'}/g;$_=pos

```

Try it online!

Where 0=FizzBuzz, 1=Buzz, 2=Fizz, 3=Number in the first of the two inputs. Finds the position of the n'th occurrence of what's wanted with a regexp search in a repeated 15 char string encoding number, fizz, buzz and fizzbuzz in their right places.

# Answer
> 4 votes
# Python 2, 47 bytes

```
f=lambda n,c,k=1:n and-~f(n-(k**4%15==c),c,k+1)

```

Try it online!

Take in the category label `c` as:

```
Number -> 1
Fizz -> 6
Buzz -> 10
FizzBuzz -> 0

```

We fingerprint the category for `k` using `k**4%15`, which produces the corresponding value as listed above. This is wrapped in a recursive function for the n'th number meeting a condition.

---

**Python 2, 54 bytes**

```
lambda n,c:([n*7/8-3*~n/4%2,~-n/4,~-n/2,0][c/2%4]+n)*c

```

Try it online!

A short at writing direct formulas for each case, with input `c` as one of `1,3,5,15`.

# Answer
> 3 votes
# Python 2, 51 bytes

```
lambda d,n,k=0:n and-~f(d,n-(k%3/2*2+k%5/4==d),k+1)

```

Try it online!

-2 bytes thanks to AnttiP; becomes -4 using Python 2
-3 bytes thanks to ovs

0 for Number, 1 for Buzz, 2 for Fizz, 3 for FizzBuzz.

# Answer
> 3 votes
# , ~~56~~ ~~54~~ 52 bytes

*Edit: -4 bytes thanks to pajonk*

```
function(n,i){while(n<-n-!(!T%%3)-i+2*!T%%5)T=T+1;T}

```

Try it online!

~~This really seems to have too many parentheses...~~
*Edit: This is really pajonk's answer, now, after removing all the useless parentheses that I left in the original...*

# Answer
> 1 votes
# Python 2, 77 bytes

0 for *Number*, 1 for *Buzz*, 2 for *Fizz*, 3 for *FizzBuzz*. The formula for *Number* is taken from A229829.

```
t,n=input()
g=n-1
print[g/8*15+g%8*12/5+1+g%8/-3,(n+g/4)*3,(n+g/2)*5,n*15][t]

```

Try it online!

# Answer
> 1 votes
# 05AB1E (legacy), 9 bytes

```
µN53SÖ2βQ

```

First input is the \\$number\\$; second is a digit \\$0\\$ for `Number`, \\$1\\$ for `Fizz`, \\$2\\$ for `Buzz`, and \\$3\\$ for `FizzBuzz`.

Uses the legacy version of 05AB1E, because it'll implicitly output the index `N` after a while-loop `µ`. In the new 05AB1E version, an explicit trailing `}N` should be added to accomplish that.

Try it online or verify all test cases.

**Explanation:**

```
µ          # Loop until the counter_variable is equal to the first (implicit) input
 N         #  Push the loop-index
  53S      #  Push [5,3]
     Ö     #  Check if the loop-index is divisible by either 5 or 3
           #  (resulting in [0,0], [1,0], [0,1], or [1,1])
      2β   #  Convert it from a base-2 list to an integer
           #  ([0,0],[1,0],[0,1],[1,1] will become 0,1,2,3 respectively)
        Q  #  And check if it's equal to the second (implicit) input
           #  (if this is truthy: implicitly increase the counter_variable by 1)
           # (after the loop, the loop-index `N` is output implicitly)

```

---

# 05AB1E (legacy), 6 bytes

```
µN15¿Q

```

First input is the \\$number\\$; second is an integer \\$1\\$ for `Number`, \\$3\\$ for `Fizz`, \\$5\\$ for `Buzz`, and \\$15\\$ for `FizzBuzz`.

Port of *@Lynn*'s Jelly comment (I now also notice my original program above uses a similar approach as *@cairdCoinheringaahing*'s 10-bytes Jelly program, even though we came up with it independently. Not too surprising, since it's a pretty straight-forward approach.)

Try it online or verify all test cases.

**Explanation:**

```
µ       # Loop until the counter_variable is equal to the first (implicit) input
 N      #  Push the loop-index
  15¿   #  Get the GCD (Greatest Common Divisor) of this index and 15
     Q  #  And check if it's equal to the second (implicit) input
        #  (if this is truthy: implicitly increase the counter_variable by 1)
        # (after the loop, the loop-index `N` is output implicitly)

```

# Answer
> 1 votes
# Retina, 60 bytes

```
L$`^.
$'*$&¶$'*$(NNFNBFNNFBNFNNZ
L$`(.)+¶(?<-1>.*?\1)+
$.>%`

```

Try it online! Link includes test cases. Takes input as the letter `F`, `B`, `Z` or `N` followed by the number `n`. Explanation:

```
L$`^.

```

Match the letter. At this point, `$'` refers to the number `n` following it.

```
$'*$&¶$'*$(NNFNBFNNFBNFNNZ

```

Repeat the letter `n` times, then on the next line repeat the Fizz Buzz sequence `15n` times.

```
L$`(.)+¶(?<-1>.*?\1)+

```

Match `n` copies of the letter on the first line, and use those to find the `n`th match of the letter on the second line.

```
$.>%`

```

Output the offset (`.``) of the end (`>`) of the match relative to the start of the second line (`%`).

# Answer
> 1 votes
# Desmos, ~~112~~ 99 bytes

Input into the function \\$f(n,k)\\$, where \\$n\\$ is the number, and \\$k\\$ is the word.

Number = 0, Fizz = 3, Buzz = 5, FizzBuzz = 15

```
h(n)=floor(n)
a=mod(n-1,8)
f(n,k)=\{k=0:15h(n/8-1/8)+2a+h(2a/5+1)-h(a/3+2/3),k=15:kn,kn+kh(kn/15)\}

```

Try It On Desmos!

Try It On Desmos! - Prettified

Uses formula in OEIS A229829:

`a(n) = 15*floor((n-1)/8) +2*f(n) +floor((2*f(n)+5)/5) -floor((f(n)+2)/3), where f(n) = (n-1) mod 8.`

99.99% sure this could be golfed. Maybe I could shorten the OEIS formula somehow.

# Answer
> 1 votes
# Husk, 8 bytes

```
!¥⁰m⌋15N

```

Try it online!

Input as `1`=number, `3`=Fizz, `5`=Buzz, `15`=FizzBuzz. Same approach as Lynn's comment to caird coinheringaahing's answer.

---

Alternative versions with successively less pre-processing squeezed into the values chosen as input:

**12 bytes**, with input as `[0,0]`=number, `[1,0]`=Fizz, `[0,1]`=Buzz & `[1,1]`=FizzBuzz.

```
!fo≡⁰§e¦3¦5N

```

Try it online!

The Husk `congr` command -  \- checks whether two lists have the same distribution of truthy/falsy elements: in this case, divisibility (`¦`) by `3` and `5`.

or **14 bytes**, finally with input just as `0`=number, `1`=Fizz, `2`=Buzz & `3`=FizzBuzz.

```
!¥mȯḋm¬§e%5%3N

```

Try it online!

Treats list of not-modulo (`¬` & `%`) 3 or 5 as binary digits ().

# Answer
> 1 votes
# Vyxal, 8 bytes

```
15ġ⁰=)ȯt

```

Try it Online!

Port of the other answers.

# Answer
> 0 votes
# Charcoal, 22 bytes

```
Ｉ⊕§⌕Ａ×”{⊞‴¡*ＲX⭆eＲ”ＮＳ⊖θ

```

Try it online! Link is to verbose version of code. Takes the number as the first input and one of the letters `F`, `B`, `Z` or `N` as the second input. Explanation:

```
      ...       Compressed string `NNFNBFNNFBNFNNZ`
     ×          Repeated by
         Ｎ      First input as a number
   ⌕Ａ           Find all indices of
          Ｓ     Second input
  §             Indexed by
            θ   First input
           ⊖    Decremented
 ⊕              Incremented
Ｉ               Cast to string
                Implicitly print

```

---
Tags: code-golf, number, sequence, fizzbuzz
---


title: Make an Emergency Corridor

text:
# Question
Title: Make an Emergency Corridor
In some nations there are recommendations or laws on how to form emergency corridors on streets that have multiple lanes per direction. (In the following we only consider the lanes going in the direction we are travelling.) These are the rules that hold in Germany:

* If there is only one lane, everyone should drive to the right such that the rescue vehicles can pass on the left.
* If there are two or more lanes, the cars on the left most lane should drive to the left, and everyone else should move to the right.

### Challenge

Given the number `N>0` of regular lanes, output the layout of the lanes when an emergency corridor is formed using a string of `N+1` ASCII characters. You can use any two characters from ASCII code `33` up to `126`, one to denote the emergency corridor, and one for denoting the cars. Trailing or leading spaces, line breaks etc are allowed.

### Examples

Here we are using `E` for the emergency corridor, and `C` for the cars.

```
N  Output
1  EC
2  CEC
3  CECC
4  CECCC
5  CECCCC
6  CECCCCC
   etc

```

# Answer
# Python 2, 29 26 bytes

```
lambda n:10**n*97/30-1/n*9

```

Example:

```
>>> f(1)
23
>>> f(2)
323
>>> f(3)
3233

```
> 29 votes

# Answer
# Python 3, ~~35~~ 33 bytes

```
lambda N:'C'*(N>1)+'EC'+'C'*(N-2)

```

Edit: dropping `f=` to save 2 bytes, thanks to @dylnan's reminder.

Try it online!

To visualize it:

```
lambda N:''*(N>1)+''+''*(N-2)

```

Output:

```
1
2
3
4
5
6

```

Try online!

# Python 3, 40 bytes

A straightforward solution:

```
lambda N:str(10**N).replace('100','010')

```

Try it online!
> 28 votes

# Answer
# C (gcc), 32 bytes

```
f(n){printf(".%.*f"+1%n,n-1,0);}

```

Try it online!

Uses `0` and `.` characters:

```
.0
0.0
0.00
0.000
0.0000

```
> 27 votes

# Answer
# Japt, ~~5~~ 4 bytes

Uses `q` for cars and `+` for the corridor.

```
ç¬iÄ

```

Try it

Credit to Oliver who golfed 4 bytes off at the same time as I did.

---

## Explanation

A short solution but a tricky explanation!

The straightforward stuff first: The `ç` method, when applied to an integer, repeats its string argument that number of times. The `i` method takes 2 arguments (`s` & `n`) and inserts `s` at index `n` of the string it's applied to.

Expanding the 2 unicode shortcuts used gives us `çq i+1`, which, when transpiled to JS becomes `U.ç("q").i("+",1)`, where `U` is the input. So we're repeating `q` `U` times and then inserting a `+` at index 1.

The final trick is that, thanks to Japt's index wrapping, when `U=1`, `i` will insert the `+` at index `0`, whatever value you feed it for `n`.
> 14 votes

# Answer
# R, 50 bytes

-11 thanks to Giuseppe!

```
pryr::f(cat("if"(x<2,12,c(21,rep(2,x-1))),sep=""))

```

Outputs 1 for emergency corridor and 2 for normal lanes

## My attempt, 61 bytes

Nothing fancy to see here, but let's get R on the scoreboard =)

```
q=pryr::f(`if`(x<2,cat("EC"),cat("CE",rep("C",x-1),sep="")))

```

Usage:

```
q(5)
CECCCC

```
> 7 votes

# Answer
# Haskell, ~~38~~ ~~34~~ 32 bytes

```
f 1="EC"
f n="CE"++("C"<*[2..n])

```

Try it online!
> 6 votes

# Answer
# Python 2, ~~30~~ ~~29~~ 28 bytes

```
lambda n:`10/3.`[1/n:n-~1/n]

```

Print `3` instead of `C` and `.` instead of `E`.

**Explanation:**

Try it online.

```
lambda n:    # Method with integer parameter and string return-type
  `10/3.`    #  Calculate 10/3 as decimal (3.333333333) and convert it to a string
  [1/n       #   Take the substring from index 1 if `n=1`, 0 otherwise
   ,n-~      #   to index `n+1` +
       1/n]  #    1 if `n=1`, 0 otherwise

```

---

# Python 2, ~~33~~ ~~32~~ ~~31~~ ~~29~~ 28 bytes

```
lambda n:1%n-1or'1-'+'1'*~-n

```

Prints `1` instead of `C` and `-` instead of `E`.

-2 bytes thanks to *@ovs*.
-1 byte thanks to *@xnor*.

**Explanation:**

Try it online.

```
lambda n:    # Method with integer parameter and string return-type
  1%n-1      #  If `n` is 1: Return '-1'
  or         #  Else:
    '1-'+    #   Return '1-', appended with:
    '1'*~-n  #   `n-1` amount of '1's

```
> 6 votes

# Answer
# Pyth, ~~10~~ ~~9~~ 8 bytes

```
Xn1Q*NQZ

```

Uses `0` to denote the emergency corridor and `"`.
Try it here

### Explanation

```
Xn1Q*NQZ
    *NQ     Make a string of <input> "s.
 n1Q         At index 0 or 1...
X      Z    ... Insert 0.

```
> 5 votes

# Answer
# Octave (MATLAB\*), ~~31 30 28 27~~ 22 bytes

```
@(n)'CE'(1+(n>1==0:n))

```

Try it online!

The program works as follows:

```
@(n)                   %Anonymous function to take input
            n>1==0:n   %Creates [1 0] if n is 1, or [0 1 (0 ...)] otherwise
         1+(        )  %Converts array of 0's and 1's to 1-indexed
    'CE'(            ) %Converts to ASCII by addressing in string

```

The trick used here is XNORing the seed array of `0:n` with a check if the input is greater than 1. The result is that for `n>1` the seed gets converted to a logical array of `[0 1 (0 ...)]` while for `n==1` the seed becomes inverted to `[1 0]`, achieving the necessary inversion.

The rest is just converting the seed into a string with sufficient appended cars.

---

(\*) The TIO link includes in the footer comments an alternate solution for the same number of bytes that works in MATLAB as well as Octave, but it results in a sequence of '0' and '1' rather than 'E' and 'C'. For completeness, the alternate is:

```
@(n)['' 48+(n>1==0:n)]

```

---

* Saved 1 byte by using `n==1~=0:1` rather than `0:1~=(n<2)`. `~=` has precedence over `<`, hence the original brackets, but is seems that `~=` and `==` are handled in order of appearance so by comparing with 1 we can save a byte.
* Saved 2 bytes by changing where the negation of `2:n` is performed. This saves a pair of brackets. We also have to change the `~=` to `==` to account for the fact that it will be negated later.
* Saved 1 byte using `<` again. Turns out that `<` has same precedence as `==` after all. Placing the `<` calculation before the `==` ensures correct order of execution.
* Saved 5 bytes by not creating two separate arrays. Instead relying on the fact that the XNOR comparison will convert a single range into logicals anyway.
> 5 votes

# Answer
# brainfuck, 42 bytes

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

```

Try it online!

Takes input as char code and outputs as `V` being normal lanes and `W` being the cleared lane. (To test easily, I recommend replacing the `,` with a number of `+`s)

### How it Works:

```
,[[>]+[<]>-] Turn input into a unary sequence of 1s on the tape
>>[<]<[<]    Move two cells left of the tape if input is larger than 1
             Otherwise move only one space
>+>+<        Add one to the two cells right of the pointer
             This transforms:
               N=1:  0 0' 1 0  -> 0 2' 1 0
               N>1:  0' 0 1 1* -> 0 1' 2 1*
[<-[--->+<]>.,>]  Add 86 to each cell to transform to Ws and Vs and print

```
> 5 votes

# Answer
# 05AB1E, 7 bytes

```
Î>∍1I≠ǝ

```

Try it online!

0 is C and 1 is E.

**Explanation**

```
Î>          # Push 0 and input incremented            -- [0, 4]
  ∍         # Extend a to length b                    -- [0000]
   1I≠      # Push 1 and input falsified (input != 1) -- [0000, 1, 1]
      ǝ     # Insert b in a at location C             -- [0100]
            # Implicit display

```
> 5 votes

# Answer
# Haskell, ~~35~~ ~~33~~ 32 bytes

*2 bytes saved thanks to Angs, 1 byte saved thanks to Lynn*

```
(!!)$"":"EC":iterate(++"C")"CEC"

```

Try it online!

# Haskell, ~~32~~ ~~30~~ 29 bytes

*This is zero indexed so it doesn't comply with the challenge*

```
g=(!!)$"EC":iterate(++"C")"CEC"

```

Try it online!

# Haskell, 30 bytes

*This doesn't work because output needs to be a string*

```
f 1=21
f 2=121
f n=10*f(n-1)+1

```

Try it online!

Here we use numbers instead of strings, `2` for the emergency corridor, `1` for the cars. We can add a `1` to the end by multiplying by 10 and adding `1`. This is cheaper because we don't have to pay for all the bytes for concatenation and string literals.

It would be cheaper to use `0` instead of `1` but we need leading zeros, which end up getting trimmed off.
> 4 votes

# Answer
# APL (Dyalog Unicode), ~~21 17~~ 16 bytes

```
(-≠∘1)⌽'E',⍴∘'C'

```

Try it online!

Thanks to Erik for saving 4 bytes and Adám for one further byte.

### How?

```
(-≠∘1)⌽'E',⍴∘'C' ⍝ Tacit function
           ⍴∘'C' ⍝ Repeat 'C', according to the input
       'E',      ⍝ Then append to 'E'
      ⌽          ⍝ And rotate
    1)           ⍝ 1
  ≠∘             ⍝ Different from the input? Returns 1 or 0
(-               ⍝ And negate. This rotates 0 times if the input is 1, and once if not.

```
> 4 votes

# Answer
# Jelly, ~~11~~ 9 bytes

```
’0ẋ⁾0E;ṙỊ

```

Try it online!

Full program.

Uses `0` instead of `C`.
> 4 votes

# Answer
# C (gcc), 39 bytes

```
f(n){printf("70%o"+!n,7|(1<<3*--n)-1);}

```

Try it online!

Borrowed and adapted the printf trick from ErikF's answer.
> 4 votes

# Answer
# Python 3, 32 bytes

```
lambda n:f"{'CE'[n<2:]:C<{n+1}}"

```

Try it online!

Uses an f-string expression to format either`'E'`or`'CE'` padded on the right with`'C'`so it has width of`n+1`.

```
f"{          :       }    a Python 3 f-string expression.
   'CE'[n<2:]             string slice based on value of n.
             :            what to format is before the ':' the format is after.
              C           padding character
               <          left align
                {n+1}     minimum field width based on n

```
> 4 votes

# Answer
# Brain-Flak, ~~100~~ 66 bytes

```
{({}[()]<((((()()()()){}){}){}())>)}{}(({}<>)())<>{<>{({}<>)<>}}<>

```

Try it online!

Uses `"` as the emergency lane and `!` as the normal lanes.
> 4 votes

# Answer
# C#, 34 bytes

```
n=>n++<2?"EC":"CE".PadRight(n,'C')

```

Try it online!
> 4 votes

# Answer
# Python 3, ~~30~~ 29 bytes

```
lambda n:"CEC"[~n:]+"C"*(n-2)

```

Try it online!

OK, there is a lot of Python answers already, but I think this is the first sub-30 byter among those still using "E" and "C" chars rather than numbers.
> 4 votes

# Answer
# JavaScript (Node.js), 28 bytes

```
n=>n<2?21:"12".padEnd(n+1,1)

```

Try it online!
> 3 votes

# Answer
# Stax, 7 bytes

```
ü♣àj#F

```

Run and debug it

This uses the characters "0" and "1". This works because when you rotate an array of size 1, it doesn't change.

Unpacked, ungolfed, and commented, it looks like this.

```
1]( left justify [1] with zeroes. e.g. [1, 0, 0, 0]
|)  rotate array right one place
0+  append a zero
$   convert to string

```

Run this one
> 3 votes

# Answer
# APL+WIN, ~~20~~ 16 bytes

4 bytes saved thanks to Adám

Prompts for integer n:

```
(-2≠⍴n)⌽n←1⎕/⍕10

```

1 for emergency corridor o for cars.
> 3 votes

# Answer
# Perl 5 `-p`, ~~27~~ ~~20~~ 19 bytes

```
$_=1x$_;s/1?\K1/E1/

```

Try it online!

Saved a byte by using `1` for the cars and `E` for the emergency corridor.
> 3 votes

# Answer
# APL (Dyalog Unicode), 16 bytes

```
≡∘1⌽'CE',1↓⍴∘'C'

```

Try it online!
> 3 votes

# Answer
# JavaScript (Node.js), 19 bytes

```
n=>--n?"0"+10**n:10

```

Try it online!
> 3 votes

# Answer
# Whitespace, ~~141~~ ~~104~~ 103 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_number][T    T   T   _Retrieve][S S S T  S N
_Push_2][T  S S T   _Subtract][S N
S _Duplicate_input-2][N
T   T   N
_If_negative_Jump_to_Label_-1][S S S T  N
_Push_1][S N
S _Duplicate_1][T   N
S T _Print_as_integer][S S T    T   N
_Push_-1][T N
S T _Print_as_integer][T    S S T   _Subtract][N
S S T   N
_Create_Label_LOOP][S N
S _Duplicate][N
T   T   S N
_If_negative_Jump_to_EXIT][S S S T  N
_Push_1][S N
S _Duplicate_1][T   N
S T _Print_as_integer][T    S S T   _Subtract][N
S N
T   N
_Jump_to_LOOP][N
S S N
_Create_Label_-1][T N
S T _Print_as_integer][N
S S S N
_Create_Label_EXIT]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Prints `1` instead of `C` and `-` instead of `E`.

-1 byte thanks to *@JoKing* by suggesting the use of `1` and `-1` instead of `0` and `1`.

### Explanation in pseudo-code:

```
Integer i = STDIN-input as integer - 2
If i is negative (-1):
  Print i (so print "-1")
Else:
  Print "1-1"
  Start LOOP:
    If i is negative:
      EXIT program
    Print "1"
    i = i-1
    Go to the next iteration of the LOOP

```

### Example runs:

**Input: `1`**

```
Command   Explanation                 Stack      Heap    STDIN   STDOUT   STDERR

SSSN      Push 0                      [0]
SNS       Duplicate top (0)           [0,0]
TNTT      Read STDIN as integer       [0]        {0:1}   1
TTT       Retrieve heap at 0          [1]        {0:1}
SSSTSN    Push 2                      [1,2]      {0:1}
TSST      Subtract top two            [-1]       {0:1}
SNS       Duplicate input-2           [-1,-1]    {0:1}
NTSN      If neg.: Jump to Label_-1   [-1]       {0:1}
NSSN      Create Label_-1             [-1]       {0:1}
TNST      Print top as integer        []         {0:1}           -1
NSSSN     Create Label_EXIT           []         {0:1}
                                                                         error

```

Try it online (with raw spaces, tabs and new-lines only).
Stops with error: Exit not defined.

**Input: `4`**

```
Command   Explanation                   Stack      Heap    STDIN   STDOUT   STDERR

SSSN      Push 0                        [0]
SNS       Duplicate top (0)             [0,0]
TNTT      Read STDIN as integer         [0]        {0:4}   4
TTT       Retrieve heap at 0            [4]        {0:4}
SSSTSN    Push 2                        [4,2]      {0:4}
TSST      Subtract top two              [2]        {0:4}
SNS       Duplicate input-2             [2,2]      {0:4}
NTSN      If neg.: Jump to Label_-1     [2]        {0:4}
SSSTN     Push 1                        [2,1]      {0:4}
SNS       Duplicate top (1)             [2,1,1]    {0:4}
TNST      Print as integer              [2,1]      {0:4}           1
SSTTN     Push -1                       [2,1,-1]   {0:4}
TNST      Print as integer              [2,1]      {0:4}           -1
TSST      Subtract top two              [1]        {0:4}
NSSTN     Create Label_LOOP             [1]        {0:4}
 SNS      Duplicate top (1)             [1,1]      {0:4}
 NTTSN    If neg.: Jump to Label_EXIT   [1]        {0:4}
 SSSTN    Push 1                        [1,1]      {0:4}
 SNS      Duplicate top (1)             [1,1,1]    {0:4}
 TNST     Print as integer              [1,1]      {0:4}           1
 TSST     Subtract top two              [0]        {0:4}
 NSNTN    Jump to Label_LOOP            [0]        {0:4}

 SNS      Duplicate top (0)             [0,0]      {0:4}
 NTTSN    If neg.: Jump to Label_EXIT   [0]        {0:4}
 SSSTN    Push 1                        [0,1]      {0:4}
 SNS      Duplicate top (1)             [0,1,1]    {0:4}
 TNST     Print as integer              [0,1]      {0:4}           1
 TSST     Subtract top two              [-1]       {0:4}
 NSNTN    Jump to Label_LOOP            [-1]       {0:4}

 SNS      Duplicate top (-1)            [-1,-1]    {0:4}
 NTTSN    If neg.: Jump to Label_EXIT   [-1]       {0:4}
NSSSN     Create Label_EXIT             [-1]       {0:4}
                                                                            error

```

Try it online (with raw spaces, tabs and new-lines only).
Stops with error: Exit not defined.
> 3 votes

# Answer
# Jelly, 6 bytes

```
⁵*ṾṙỊṙ

```

Displays car lanes as **0**, the emergency lane as **1**.

Try it online!

### How it works

```
⁵*ṾṙỊṙ  Main link. Argument: n

⁵*      Compute 10**n.
  Ṿ     Uneval; get a string representation.
   ṙỊ   Rotate the string (n≤1) characters to the left.
     ṙ  Rotate the result n characters to the left.

```
> 3 votes

# Answer
# AutoHotkey 32 bytes

Replaces the letter "C" with "EC" unless amount of C \> 1, then it sends "CEC" and exits the app.

```
::C::EC
:*:CC::CEC^c
^c::ExitApp

```

C =\> EC
CC =\> CEC then exits the program. Any further Cs will be entered after the program exits.
> 3 votes

# Answer
# , 11 bytes

```
1":1&<=i.,]

```

Try it online!

Based on ngn’s comment.

and :

`1&<,~/@A.'',~''$~,&4`
> 3 votes

# Answer
# MathGolf, ~~7~~ 6 bytes

```
ú░\┴╜╪

```

Try it online.

Output `1` for `E` and `0` for `C`.

**Explanation:**

```
ú         # 10 to the power of the (implicit) input
          #  i.e. 1 → 10
          #  i.e. 4 → 10000
 ░        # Convert it to a string
          #  i.e. 10 → "10"
          #  i.e. 10000 → "10000"
  \       # Swap so the (implicit) input is at the top of the stack again
   ┴╜     # If the input is NOT 1:
     ╪    #  Rotate the string once towards the right
          #   i.e. "10000" and 4 → "01000"
          # Output everything on the stack (which only contains the string) implicitly

```
> 3 votes

# Answer
# Canvas, 11 bytes

```
┤C×EC×╴╷？C×

```

Try it here!
> 2 votes

# Answer
# \[GNU sed 4.2.2\], 14 bytes

* Score includes 1 byte for the `-r` sed parameter
* 3 bytes saved thanks to @Leo

Input integer is given in unary. Output characters are `E` for emergency vehicles and `1` for regular cars.

```
s/(.?)1/\1E1/

```

Try it online!
> 2 votes

# Answer
# Jelly, 14 bytes

```
⁵*×109:90+Ị9×Ɗ

```

Try it online!

Port of orlp's python answer which only uses arithmetic.

---

**Jelly, 15 bytes**

```
ḊṬ1;,2Ṭ¤LÐṀị⁾CE

```

Try it online!
> 2 votes

# Answer
# C (gcc), 48 bytes

```
f(n){for(printf("CEC"+!--n);--n>0;putchar(67));}

```

Try it online!
> 2 votes

# Answer
# Python 3, 39 bytes

```
lambda n:'C'*(n>1)+'E'+'C'*(n-1+(n==1))

```

Try it online!
> 2 votes

# Answer
# C# (.NET Core), 39 bytes

```
n=>(n--<2?"EC":"CE")+new string('C',n);

```

Try it online!
> 2 votes

# Answer
# PowerShell, ~~49~~ ~~37~~ 35 bytes

```
param($n)'C'*(1%$n)+1+'C'*($n-1%$n)

```

Try it online!

Saved a pair of quotes by just making the E into a number.
> 2 votes

# Answer
# Gol\>\<\>, 10 bytes

```
IR1~I{lRn;

```

Try it online!

One of a few 10-byte solutions I found. I like this one the most because it uses the `-` as the clear lane, where the `-` is a result of printing `-1`.

The other 10-byte solutions:

* `IR0P{lPRn;`
* `IR`CP{`C}H`

Pity Gol\>\<\> doesn't have a halt and output the stack numbers command, like it does for chars, or this could be 3 bytes smaller.
> 2 votes

# Answer
# Java 10, ~~53~~ ~~51~~ ~~45~~ ~~42~~ ~~38~~ ~~37~~ ~~36~~ ~~35~~ 34 bytes

```
n->n+=Math.pow(10,n)*97/30-1/n*9-n

```

Prints `3` instead of `C` and `2` instead of `E`.

Try it online.

Port of *@orlp*'s Python 2 answer.

`n+=...-n` is used instead of `(long)...` to save a byte.

---

**Old 35 bytes answer:**

```
n->(10/3f+"").substring(1/n,1/n-~n)

```

Prints `3` instead of `C` and `.` instead of `E`.

**Explanation:**

Try it online.

```
n->{               // Method with integer parameter and String return-type
  (10/3f+"")       //  Divide 10 by 3 and convert it to a String ("3.333333333")
   .substring(1/n  //  And take the substring from index 1 if `n=1`, 0 otherwise
    ,1/n           //  to index 1 if `n=1`, 0 otherwise
        -~n)       //  + `n+1`

```
> 2 votes

# Answer
# Python 2, 30 bytes

```
lambda n:1%n*'0'+`10**(n-1%n)`

```

Try it online!

If `n` is larger than `1`, `1%n` gets `1`: `1*'0'+`10**(n-1)``
If `n` is equal to `1`, `1%n` gets `0`: `0*'0'+`10**(1-0)``

---

# Python 2, 31 bytes

```
lambda n:1/n*'.'+'%%.%df'%~-n%0

```

Try it online!

```
1/n*'.'        # if n is 1, insert a dot ...
+              # before
'%%.%df'%~-n%0 # the decimal representation of 0 with n-1 digits after the decimal point

```

`'%%.%df'%~-n` expands to `'%.<n-1>f'`.
> 2 votes

# Answer
# MATL, 7 bytes

```
Q:G2Xl=

```

Try it online!

Uses 1 for emergency, 0 for normal traffic.

```
Q:      % Range 1...n+1, implicit input n
  G2Xl  % Explicitly push input, limit to 2 (so, either 1 or 2)
      = % Element-wise equality of range and limited input.
        % Implicit display.

```

This answer assumes (like some other answers) that separating spaces are OK. If not, append `VXz` for ten bytes.
> 2 votes

# Answer
# Excel, 29 bytes

```
=IF(A1=1,0,10&REPT(1,A1-2))&1

```

Uses `0` for Emergency lane. `1` for Cars:

```
1  01
2  101
3  1011
4  10111
5  101111

```
> 2 votes

# Answer
# , 20 bytes

```
'CECC'#~1(<,[,=,-~)]

```

Try it online!
> 2 votes

# Answer
# Python, 53 bytes

```
lambda n:-1*((n+1)//n-2)*'C'+'E'+(n+((n+1)//n-2))*'C'

```

Try it online!
> 2 votes

# Answer
## Excel, 28 bytes

```
=REPT(2,A1+1)-10^MAX(A1-1,1)

```

Uses `2` for cars, and `1` for Corridor

Makes a list of `2`s `n+1` long, then subtracts the larger of `10^(n-1)` and `10`:

> `n=1` : `22` \- `MAX(1,10)` = `12`
> `n=2` : `222` \- `MAX(10,10)` = `212`
> `n=3` : `2222` \- `MAX(100,10)` = `2122`
> `n=10` : `22222222222` \- `MAX(1000000000,10)` = `21222222222`
> 2 votes

# Answer
# Haskell (interactive), 30 bytes

```
a 1=12;a 2=212;a n=a(n-1)*10+2

```

1 is a corridor, 2 is a car.

Example:

```
GHCi, version 8.2.2: http://www.haskell.org/ghc/  :? for help
Prelude> a 1=12;a 2=212;a n=a(n-1)*10+2
Prelude> a 1
12
Prelude> a 2
212
Prelude> a 3
2122
Prelude> a 4
21222
Prelude> a 5
212222

```
> 2 votes

# Answer
# Perl 5 `-lp`, 19 bytes

```
#!/usr/bin/perl -lp
$_=--$_?CE.C x$_:EC

```

Try it online!
> 2 votes

# Answer
# Ruby, 25 bytes

```
->n{n>1?'CE'+?C*~-n:'EC'}

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Classic), 11 bytes

```
⊃∘⍕¨1∘<=0,⍳

```

Try it online!

uses `⎕io←1`
> 2 votes

# Answer
# Prolog (SWI), ~~63~~ 51 bytes

```
1+`EC`.
2+`CEC`.
N+X:-M is N-1,M+Y,append(Y,`C`,X).

```

Try it online!
> 1 votes

# Answer
# Octave, ~~36~~ ~~34~~ 33 bytes

```
x((n=input(''))+1)=0;x(1+(n>1))=1

```

Try it online!
> 1 votes

# Answer
# Windows Batch, 75 bytes

To be improved...

```
@if %1==1 echo EC&exit/b
@cd|set/p=CE
@for /l %%G in (2,1,%1)do @cd|set/p=C

```
> 1 votes

# Answer
# Retina 0.8.2, 17 bytes

```
.+
E$&$*C
ECC
CEC

```

Try it online! I could save a byte by using `1` for a car.
> 1 votes

# Answer
# Python 3, 31 bytes

```
lambda n:'ECE'[n>1:n+1]+'C'*~-n

```

Try it online!

At first I tried reversing `EC` if `n>1`, but converting a boolean to `(-1,+1)` turned out longer than using a different string instead.

Alternative 31 byte solutions:

All of these also work in Python 2.
> 1 votes

# Answer
# JavaScript, 28 bytes

```
f=n=>n-->2?f(n)+'1':n?121:21

```
> 1 votes

# Answer
# Swift, 74 bytes

```
func r(i:Int)->String{return i>1 ?"CE"+(1..<i).map{_ in"C"}.joined():"EC"}

```

Try it online!
> 1 votes

# Answer
## PHP, 103 Bytes

Try it online!

**Code, recursive function**

```
function f($n,$i=1,$s=''){if($i<$n){$s.="CE".str_repeat("C",$i)."
";f($n,$i+1,$s);}else{echo"EC
".$s;}}

```

**Explanation**

```
function f($n,$i=1,$s=''){
if($i<$n){                         #condition to get out, it counts to $n
    $s.="CE".str_repeat("C",$i)."  # "C" is repeated and concatenated
    ";f($n,$i+1,$s);               #note that "\n" = "(Enter key)"
}else{
    echo"EC                        #the first line "EC"
    ".$s;
}
}

```

**Note** that `"\n" = "
"`, you save one byte

**Output**

```
f(5);
EC
CEC
CECC
CECCC
CECCCC

f(10);
EC
CEC
CECC
CECCC
CECCCC
CECCCCC
CECCCCCC
CECCCCCCC
CECCCCCCCC
CECCCCCCCCC

```
> 1 votes

# Answer
# Jelly, 8 bytes

```
«2=‘R$;⁷

```

A full program printing the output with car lanes as `0` and the emergency lanes as `1`.

**Try it online!**
> 1 votes

# Answer
# Yabasic, 54 bytes

```
Input""n
If n>1Then?"C";Fi
?"E";
For i=1To n:?"C";Next

```

Try it online!
> 1 votes

# Answer
# Excel VBA, 32 bytes

An anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window.

```
?[If(A1-1,10,"01")&Rept(1,A1-1)]
''  or
?[If(A1-1,10,0)&Rept(1,A1-A1<1)]

```
> 1 votes

# Answer
# \>\<\>, 26 bytes

```
::?v~1)?o"!">o<
00.>1-"~"}

```

Watch it run !

Results :

```
1.     !~
2.     ~!~
3.     ~!~~
4.     ~!~~~
etc.

```
> 1 votes

# Answer
# Perl 6, 20 bytes

```
{1%$_*10~1 x$_-1%$_}

```

Try it online!

Returns

```
1 => 01
2 => 101
3 => 1011
4 => 10111
5 => 101111

```

Another 20 byte solution with `-p` is `$_=1 x$_;s/1?<(1/E1/` which is identical to Xcali's Perl 5 solution.
> 1 votes

# Answer
# \>\<\>, 16 bytes

```
1-:?!v1$
n<}1{<>

```

Try it online!

Prints `0` as the corridor and `1` as the cars.
> 1 votes

# Answer
# Befunge-98 (FBBI), 14 bytes

Uses `0` for cars, and `1` for the empty lane.

```
12&:b0p`j\' k.

```

Try it online!

This uses a `&` to end the program, stalling it until TIO shuts it off, instead of ending when it's finished. In order to avoid waiting, you can hit the run button again soon after it starts to end it prematurely and see the result it would give if it waited. In case ending like this is too iffy, here is a 15 byte solution that doesn't use this method:

```
12&:b0p`j\' k.@

```

Try it online!

### Explanation

This program uses the implicit zeroes at the bottom of the stack to print the cars at the end. This way we can avoid pushing `N - 1` things, and only use the input for printing `N + 1` things and determining whether N is 1 or not.

(stack terminology is `bottom [a, b, c] top`)

```
12                Push 1 and 2. The stack is [1, 2]
  &:              Take input and duplicate. [1, 2, N, N]
    b0p           Put N at (0, 11), which is after the '
       `          Pops the top 2 and pushes 1 if a>b, 0 if not. [1, 2>N]
        j\        Jumps the \ if 2>N (i.e. N = 1), otherwise switches the top 2.
                      The stack is [1] if N=1, otherwise [1, 0]
          '       Takes in N again from the put instruction earlier
            k.    Prints out N+1 characters: (01 or 10 depending on N) + (N-1 0s).
12                Wraps and adds irrelevant things to the stack.
  &               Waits for TIO to end the program.

```
> 1 votes

# Answer
# naz, 104 bytes

```
2x0v1a2x1v1x1f1o1s1o0x1x2f2x2v0m1o0m1a1f2v2s2x2v3f0x1x3f2v3x0v4e1s2x2v0m1o3f0x1x4f0a0x1x5f1r3x1v1e2f0x5f

```

There may be some byte saves I haven't immediately seen. I'm starting to be out of practice with my own language.

This program uses `1` for the emergency corridor and `0` for the cars, and accepts its input as a character code, which is allowed by meta consensus.

Due to integer constraints, this works for all `N` where `0 < N < 128`. Use the `-u` flag to remove the constraints.

**Explanation** (with `0x` commands removed)

```
2x0v                         # Set variable 0 equal to 0
1a2x1v                       # Set variable 1 equal to 1
1x1f                         # Function 1
    1o1s1o                   # Output, then subtract 1 and output again
1x2f                         # Function 2
    2x2v                     # Set variable 2 equal to the current register value
        0m1o0m1a1f           # Output "010" with the help of function 1
                  2v2s2x2v   # Subtract 2 from variable 2
                          3f # Call function 3
1x3f                         # Function 3
    2v3x0v4e                 # Goto function 4 if variable 2 is equal to variable 0 (0)
            1s2x2v           # Otherwise, subtract 1 from variable 2,
                  0m1o       # output 0,
                      3f     # and jump back to the start of function 3
1x4f                         # Function 4
    0a                       # Add 0 to the register
1x5f                         # Function 5
    1r                       # Read a byte of input
      3x1v1e                 # Goto function 1 if it equals variable 1
            2f               # Otherwise, call function 2
5f                           # Call function 5

```
> 1 votes

# Answer
# Vyxal, 6 bytes

```
↵S$ċ[ǔ

```

Try it Online!
> 1 votes

# Answer
# PHP, 35 bytes

```
<?=str_pad(1<$argn?CE:E,C,$argn+1);

```

Run as pipe with `-n` or try it online.
> 0 votes

# Answer
# C# (.NET Core), 74 bytes

*Additional bytes for `using System;` and `int L`*

```
var S="0X";for(int I=1;I<L;I++)S+='0';System.Console.Write(L<2?"X0":S);

```

Try it online!
> 0 votes

# Answer
# Pyt, 18 bytes

```
Đ1≤?ĉ01:ŕ01↔⁻⑴;áƑǰ

```

Try it online!

Uses 0 for the emergency lane and 1 for the normal lanes

### Explanation

```
                          Implicit input (N)
Đ                         Duplicate N on the stack
 1≤                       Is N≤1
   ?   :       ;          If top of stack is non-zero, continue execution until reaching
                               colon, then jump to semicolon; otherwise, jump to colon
                               and continue executing
   ?                      - Then (i.e. i≤1)
    ĉ                     Clear the stack
     01                   Push 0 followed by 1

       :                  - Else branch (i.e. N≥2)
        ŕ                 Pop the top of the stack
         01               Push 0 followed by 1
           ↔              Flip the stack
            ⁻⑴           Decrement N and then push an array of N-1 1's
               ;          - End of if statement

                á         Push contents of stack to an array
                 Ƒ        Flatten the resulting array
                  ǰ       Join the contents of the array with no delimiters

```
> 0 votes

# Answer
# Pushy, 10 bytes

```
1wEs{t?};Q

```

**Try it online!**

```
1             \ Push 1
 w            \ 'Mirror' the stack around the central item, yielding [n, 1, n]
  E           \ Pop 1 and n, and push 1 * 10 ** n
   s          \ Split into its digits
    {         \ Get input back on top of stack
     t?       \ If input > 1:
       };     \    Cyclically shift the stack right once
         Q    \ Collect all items on stack, interpret as indicies into uppercase alphabet,
              \ and print the resulting string.

```

Prints `A` for lanes and `B` for corridors.
> 0 votes

# Answer
# ink, ~~55~~ ~~33~~ 55 bytes

```
=l(n)
~temp i=2
{n-1:C}EC<>
-(k){i<n:
~i++
C<>->k
}->->

```

Try it online!

Starts by printing `C` if input is not 1, then `EC`, then prints `C` another `n-2` times.
> 0 votes

---
Tags: code-golf, ascii-art, number
---


title: My [sub] strings are hiding!

text:
# Question
Title: My [sub] strings are hiding!
# Introduction

A while ago a lost SO user posted a question here and its now been deleted but I think it would make a good challenge so here it goes...

# Challenge

Write a full program or function that takes two strings and checks whether any permutation of the first string is a sub-string of the second string.

# Input

Two strings, a string and a sub-string to test for (you may choose the order).

# Output:

A truthy value if the string contains any permutation of the sub-string.
A falsey value if the string does not contain any permutations of the the sub-string.
The test is case sensitive.

# Examples/Test cases

```
         sub-string    string
input    d!rl          Hello World!
output   truthy

input    Pog           Programming Puzzles & Code Golf
output   falsey

input    ghjuyt        asdfhytgju1234
output   truthy

```

# Answer
> 15 votes
# Brachylog, 2 bytes

```
sp

```

Try it online!

### Explanation

```
Input variable = "Hello World!", Output variable = "d!rl"

(?)s        Take a substring of the Input variable
    p(.)    It is a permutation of the Output variable

```

# Answer
> 7 votes
# JavaScript (ES6), 77 bytes

```
(s,t)=>t&&[...t.slice(0,s.length)].sort()+''==[...s].sort()|f(s,t.slice(1))

```

Returns 1 or 0.

**Snippet**

```
f=

(s,t)=>t&&[...t.slice(0,s.length)].sort()+''==[...s].sort()|f(s,t.slice(1))

console.log(f('d!rl','Hello World!'))                   //1
console.log(f('Pog','Programming Puzzles & Code Golf')) //0
console.log(f('ghjuyt','asdfhytgju1234'))               //1
```

# Answer
> 6 votes
# 05AB1E, 3 bytes

```
œåZ

```

Try it online!

-1 byte thanks to Emigna.

Explanation:

```
œåZ 2 inputs
œ                  permutations of the first input
 å  Is each of the                                 in the second input?
  Z Take the maximum of the resulting boolean list

```

# Answer
> 6 votes
# Japt, ~~10~~ ~~7~~ 6 bytes

```
á d!øV

```

Try it online

```
á d!øV   :Implicit input of sub-string U & string V
á        :Permutations of U
  d      :Any
   !øV   :  Contained in V

```

# Answer
> 6 votes
## Python 2, ~~67~~ 66 bytes

Takes input as two strings, substring first.

```
a=sorted
lambda s,S:a(s)in[a(S[n:n+len(s)])for n in range(len(S))]

```

# Answer
> 5 votes
# Jelly, 5 bytes

```
Œ!ẇ€Ṁ

```

Try it online!

-1 thanks to Emigna for encouraging me to retry golfing.

Explanation:

```
Œ!ẇ€Ṁ Main link, dyadic
Œ!               the permutations of the left argument
  ẇ€  Is each of                                      in the right argument?
    Ṁ Maximum of boolean values

```

# Answer
> 5 votes
# Java 8, ~~266~~ 244 bytes

```
import java.util.*;Set l=new HashSet();s->p->{p("",p);for(Object x:l)if(s.contains(x+""))return 1>0;return 0>1;}void p(String p,String q){int n=q.length(),i=0;if(n<1)l.add(p);else for(;i<n;)p(p+q.charAt(i),q.substring(0,i)+q.substring(++i,n));}

```

**Explanation:**

Try it here.

```
java.util.*;                   // Required import for Set and HashSet

Set l=new HashSet();           // Class-level Set

s->p->{                        // Method (1) with two String parameters and boolean return-type
  p("",p);                     //  Put all permutations in the class-level Set
  for(Object x:l)              //  Loop over the permutations:
    if(s.contains(x+""))       //   If the input String contains one of the permutations:
      return 1>0;//true        //    Return true
                               //  End of loop (implicit / single-line body)
  return 0>1;//false           //  Return false
}                              // End of method (1)

void p(String p,String q){     // Method (2) with two String parameters and no return-type
  int n=q.length(),i=0;        //  Two temp integers
  if(n<1)                      //  If `n` is zero:
    l.add(p);                  //   Add this permutation of the String to the Set
  else                         //  Else:
    for(;i<n;                  //   Loop over `n`
      p(p+q.charAt(i),q.substring(0,i)+q.substring(++i,n))
                               //    Recursive-call with permutation parts
    );                         //   End of loop (no body)
}                              // End of method (2)

```

# Answer
> 4 votes
# Python, 60 bytes

An altered form of TFeld's answer \- go give some credit!

```
s=sorted
f=lambda u,t:s(u)==s(t[:len(u)])or t and f(u,t[1:])

```

Recursive function returning the boolean `True` (truthy) or an empty string (falsy).

**Try it online!**

sorts the substring, `u`, and the same length of the front of the string, `t`, (using a slice `t[:len(u)]`) if they are the same then `True` is returned, otherwise if `t` is still truthy (not empty) recurses with a dequeued `t` (using a slice, `t[1:]`). If `t` does become empty the `and` is not executed and this empty `t` is returned.

# Answer
> 4 votes
# Pyth, ~~9~~ 8 bytes

```
sm}dQ.pE

```

*-1 byte thanks to @Erik\_the\_Outgolfer*

Takes two quoted strings, the second of which is the substring.

Try it!

# Answer
> 3 votes
# CJam, ~~13~~ 12 bytes

```
le!lf{\#)}:+

```

Try it online!

I feel like CJam is really limited compared to other golfing languages, but maybe it's just me being bad...

I'm thinking about moving to another. 05AB1E seems fun.

*Fixed small bug thanks to Erik the Outgolfer*
*Cut one bite because non-zero numbers are truthy*

Explanation:

```
l                 Read substring
 e!               Generate all permutations
   l              Read string
    f{            For each permutation
      \#            Check if it is in the string (returns -1 if not found)
        )           Add one
         }        End for
          :+      Sum the whole found/not found array

```

# Answer
> 3 votes
## Mathematica, ~~55~~ 50 bytes

-5 bytes from user202729

```
StringFreeQ[#2,""<>#&/@Permutations@Characters@#]&

```

Returns `False` if a permutation of the first input is in the second string. Returns `True` if a permutation of the first input is not in the second string.

Explanation:

```
                                    Characters@#   - split first string into array of characters
                       Permutations@               - make all permutations
               ""<>#&/@                            - join each array of characters together to form a single string
StringFreeQ[#2,                                 ]& - Check if any of these string is in the second input string

```

# Answer
> 3 votes
# Java 9 JShell, 160 bytes

```
p->q->IntStream.range(0,q.length()-p.length()+1).anyMatch(
    i->Arrays.equals(
        q.substring(i,i+p.length()).chars().sorted().toArray(),
        p.chars().sorted().toArray()))

```

(newlines inserted for readability)

Try it online!

Note: JShell includes a number of imports by default. As a Java 8 or Java 9 solution, it would be necessary to import:

```
import java.util.*;import java.util.stream.*;

```

For an extra 45 bytes, or 205 bytes total. The TIO link above is to a Java 9 program since TIO doesn't currently have JShell (and it's not clear to me how JShell would work on TIO).

# Answer
> 2 votes
# C#, 320 bytes

```
using System.Linq;s=>u=>p(u.ToArray(),0,u.Length-1).Any(p=>s.Contains(p));w=(c,a,b)=>{if (a!=b)(var t=c[a];c[a]=c[b];c[b]=t;)};System.Collections.Generic.IEnumerable<string>p(char[]l,int k,int m){if(k==m)yield return new string(l);else for(int i=k;i<=m;){w(l,k,i);foreach(var c in p(l,k+1,m))yield return c;w(l,k,i++);}}

```

I'm sure calculating the permutations can be a lot shorter but I can't see how at the moment.

Formatted/Full version:

```
void test()
{
    Func<string, Func<string, bool>> f = s => u =>
        p(u.ToArray(), 0, u.Length - 1).Any(p => s.Contains(p));

    Console.WriteLine(f("Hello World!")("d!rl"));
    Console.WriteLine(f("Programming Puzzles & Code Golf")("Pog"));
    Console.WriteLine(f("asdfhytgju1234")("ghjuyt"));
}

System.Collections.Generic.IEnumerable<string>p(char[] l, int k, int m)
{
    Action<char[], int, int> w = (c, a, b) =>
    {
        if (a != b)
        {
            var t = c[a];
            c[a] = c[b];
            c[b] = t;
        }
    };

    if (k == m)
        yield return new string(l);

    else
        for (int i = k; i <= m;)
        {
            w(l, k, i);

            foreach (var c in p(l, k + 1, m))
                yield return c;

            w(l, k, i++);
        }
}

```

# Answer
> 2 votes
# Ruby, 69 bytes

```
->a,b{r=nil;a.chars.each_cons(b.size){|q|r||=q.sort==b.chars.sort};r}

```

Try it online!

# Answer
> 2 votes
# Perl 6, 48 bytes

```
{$^a.contains(any $^b.comb.permutations».join)}

```

Returns an or-junction of each permutation's presence as a substring. For example, with arguments `"Hello World!"` and `"d!l"`, returns:

```
any(False, False, False, False, True, False)

```

...which "collapses" to `True` in a boolean context. That is, junctions are truthy values.

# Answer
> 2 votes
# PHP\>=7.1, 91 Bytes

```
for([,$x,$y]=$argv;~$p=substr($y,$i++,strlen($x));)$t|=($c=count_chars)($x)==$c($p);echo$t;

```

Testcases

# Answer
> 1 votes
# Haskell, 54 bytes

```
import Data.List
s#t=any(`isInfixOf`s)$permutations t

```

Using the power of Data.List for both `isInfixOf` as well as `permutations`.

# Answer
> 1 votes
# MATL, 10 bytes

```
Y@Z{w&Xfma

```

Try it on MATL Online

# Answer
> 1 votes
# , 103 bytes

```
function(w,x,y=u(w),z=u(x)){for(i in 1:n(w)){F=F|!sum(setdiff(y[1:n(x)+i-1],z))};F}
u=utf8ToInt
n=nchar

```

Try it online!

Returns `TRUE` for truthy and `NA` for falsey.

# Answer
> 1 votes
# Ruby, 43 bytes

```
->a,b{b.chars.permutation.any?{|c|a[c*""]}}

```

Attempt This Online!

# Answer
> 0 votes
# APL (Dyalog), 18 bytes

```
{∨/(∧/⍺∊⊢)¨⍵,/⍨⍴⍺}

```

Try it online!

# Answer
> 0 votes
# Factor \+ `math.combinatorics`, 35 bytes

```
[ '[ _ subseq? ] find-permutation ]

```

Try it online!

Outputs the matching subsequence (which behaves as boolean true in Factor) for truthy and `f` for falsey.

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