title: We ended up where we started!…

text:
# Question
Title: We ended up where we started!…
## Challenge:

### Input:

You take two inputs:
\- A string only containing printable ASCII (excluding spaces, tabs or new-lines)
\- A printable ASCII character

### Output:

The first line will contain the string-input. Every `i`-modulo-3 first occurrence of this character will move in a South-East direction; every `i`-modulo-3 second occurrence will move in a South direction; and every `i`-modulo-3 third occurrence will move in a South-West direction. You'll continue until the characters are about to be at their initial starting position again (which means it will wrap around from one side to the other if necessary), and then you'll print the last line with the string-input again to finish it. (Note that all test cases will end up at their initial input after at most `length(input)` rows, including the row containing the trailing input. It can be sooner though, as seen in this first test case below, with a length of 14, but ending after 9.)

This may all be pretty vague, so here an example:

### Test case 1:

String-input: `"This_is_a_test"`
Character-input: `'s'`

Output:

```
This_is_a_test
    s s    s
     ss   s
      s  s
      sss
      sss
      s  s
     ss   s
    s s    s
This_is_a_test

```

Here is the same test case with the colored paths of the three `s`:

where the first `'s'` follows the green path in a South-East direction; the second `'s'` follows the yellow path in a South direction; and the third `'s'` follows the light blue path in a South-West direction. (If there would be a fourth `'s'` it would go in a South-East direction again, which can be seen in some of the other test cases below.)

## Challenge rules:

* The inputs will only contain printable ASCII (excluding spaces, tabs and new-lines)
* I/O formats are flexible. Can be a new-line delimited string, character matrix, etc. Your call.
* It is possible that the given character isn't present in the string, in which case you are allowed to either output the input-string once or twice (i.e. `"test", 'a'` can have either of these as possible output: `"test\ntest"`/`"test"`).
* Leading spaces are mandatory; trailing spaces are optional. One or multiple leading/trailing new-lines are allowed.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

## Test cases / more examples:

### Test case 2:

String-input: `"abcabcabcabcabc"`
Character-input: `'b'`

Output:

```
abcabcabcabcabc
  b b b    b b
   bbb      bb
    b        b
   bbb       bb
b b b b      b
 b  b  b     b
b b b   b    b
   bb    b   bb
    b     b  b
    bb     bbb
    b b    bbb
    b  b  b  b
    b   bb   bb
b   b   bb   b
abcabcabcabcabc

```

Here is the same test case with the colored paths of the five `a`:

### Test case 3:

String-input: `"only_two_paths?"`
Character-input: `'o'`

Output:

```
only_two_paths?
 o     o
  o    o
   o   o
    o  o
     o o
      oo
       o
       oo
       o o
       o  o
       o   o
       o    o
       o     o
       o      o
only_two_paths?

```

Here is the same test case with the colored paths of the two `o`:

### Test case 4:

String-input: `"lollollollollol"`
Character input: `'l'`

Output:

```
lollollollollol
lll   ll  ll
 ll   ll  ll
l ll ll ll ll
  lll l ll l ll
  llllll  ll ll
l l  ll    ll
 ll  lll   ll
l l l lll ll l
  ll  l ll l  l
l l l l llll l
 ll  lll  lll
l l   l    ll
  ll lll  lllll
  l l l ll l ll
lollollollollol

```

Here is the same test case with the colored paths of the ten `l`:

### Test case 5:

String-input: `"AbCdEeDcBaAbCdEeDcBa_CCCCC"`
Character input: `'C'`

Output:

```
AbCdEeDcBaAbCdEeDcBa_CCCCC
C  C        C       C  C
 C  C       C      C  CCC
  C  C      C     C  C C C
C  C  C     C    C  C  C
 C  C  C    C   C  C   C
  C  C  C   C  C  C    C
   C  C  C  C C  C     C
    C  C  C CC  C      C
     C  C  CC  C       C
      C  C CC C        C
       C  C CC         C
        CC CC C        C
        CC CC  C       C
       C  C CC  C      C
      C  C CC C  C     C
     C  C   C  C  C    C
    C  C    CC  C  C   C
   C  C     C C  C  C  C
  C  C      C  C  C  C C
 C  C       C   C  C  CC
C  C        C    C  C  C
  C         C     C  C CCC
 C          C      C  CCCC
C           C       C  C
 C          C        CCCCC
AbCdEeDcBaAbCdEeDcBa_CCCCC

```

Here is the same test case with the colored paths of the seven `C`:

### Test case 6:

String-input: `"XyX"`
Character input: `'X'`

Output:

```
XyX
 XX
  X
XyX

```

Here is the same test case with the colored paths of the two `X`:

### Test case 7:

String-input: `"aaaa"`
Character input: `'a'`

Output:

```
aaaa
aa
aaa
 aaa
aaaa

```

Here is the same test case with the colored paths of the four `a`:

# Answer
> 1 votes
# Stax, 24 bytes

```
»v↕*δó‼Γ█|q┬YM╨|·£↕fßßZo

```

Run and debug it online

This is the ascii representation of the same program.

```
YxP|Ic{{i3%v-x%%mb-!Czny&PWxP

```

It gets the indices of all the character, and then mutates them until they are set-wise equal to the original indices. For every change, output a string with the character at those indices.

```
Y                               Store character in y.  Now the inputs are x and y.
 xP                             Print x.
   |Ic                          Get all indices of y in x. Make a copy.
      {                   W     Loop until cancelled.
       {        m               Map index array using block.
        i3%v-                   Subtract i%3-1 from each element. i is the loop index.
             x%%                Modulo len(x)
                 b-!            Is the mutated array set-equal to the original?
                    C           If so, cancel W loop
                     zny&P      Print a string with y at all specified indices
                           xP   Finally, print x again

```

# Answer
> 8 votes
# Perl 5, `-plF` ~~101~~ ~~100~~ ~~99~~ ~~98~~ ~~97~~ 96 bytes

Replace the `\0` by a literal 0 byte to get 96. Notice that the Try It Online link has 97 bytes because it doesn't seem possible to input a literal 0 character there.

```
#!/usr/bin/perl -plF
say;say$$l=~y/\0/ /runtil--$l,(s:\Q${\<>}:$$l|=v0 x((++$#$l%3*$l-$l+"@-")%@F).$&;v0:oreg^$$l)eq$_

```

The code golf perl highlighter thinks `#` start a comment. How naive

Try it online!

# How it works

`$l` is a counter for which line after the first we are on (it counts down though, so e.g. -3 for 3 lines below the top string).After printing the initial string once it repeatedly does the following.

Search the first string for occurrences of the target character and calculate at which offset it should appear: `(++$#$l%3*$l-$l+"@-")%@F` which is the current position plus the line number (negative) times `-1, 0, 1` (cyclic). Construct a string with that many times `\0` followed by the target character and `or` that into an accumulator `$$l` (that is a different accumulator for each `$l` and the reason `$l` counts down instead of up because `$1`, `$2` etc are read-only). Simularly `$#$l` refers to a different array each time through the loop. The result is the `$l`th line but with `\0` instead of spaces.

The target charcters in the first string are replaced by `\0` so you end up with the original string with "holes" (with `\0`) at the original positions of the target character. If you `xor` that with the accumulator the holes get filled if and only if the accumulator has the target characters in the original positions, so the result will be the original string. That is used to terminate the loop. If the loop is not finished yet print the accumulator with `\0` replaced by space.

When the loop ends the `-p` option once more prints the first string and the program is done.

The target character is picked up in a rather tricky way. The `${\<>}` converts a line read from STDIN to a reference which is then immediately dereferenced and substituted in the regex. The `\Q` prefix escapes all characters that are special in a regex (like `.` and `*`). The `\E` is implicit. The `o` modifier causes the search part to never be evaluated again but just repeated in all subsequent matches (which is good since there is nothing on STDIN anymore).

# Answer
> 4 votes
# Python 2, ~~199~~ ~~193~~ 191 bytes

```
s,c=input()
print s;l=len(s);r=range;I=j=[i for i in r(l)if s[i]==c]
while 1:
 j=[(j[i]-i%3+1)%l for i in r(len(I))]
 if sorted(j)==I:print s;break
 print''.join((' '+c)[i in j]for i in r(l))

```

Try it online!

---

If the loop can exit via exception:

# Python 2, 187 bytes

```
s,c=input()
print s;l=len(s);r=range;I=j=[i for i in r(l)if s[i]==c]
while 1:
 j=[(j[i]-i%3+1)%l for i in r(len(I))]
 if sorted(j)==I:print s;q
 print''.join((' '+c)[i in j]for i in r(l))

```

Try it online!

---

* -4 bytes thanks to Jonathan Frech
* -2 bytes thanks to Lynn

# Answer
> 2 votes
# Ruby, ~~189 176 171 156 150 146 144~~ 137 bytes

```
->s,c,r=0..k=s.size,b=[p,s]{d=0;g=s.tr c,n=' '*k;l=r=r.map{|i|l||c==s[i]?(n[z=(i+1-d%3)%k]=g[z]=c;d+=1;z):p}-b;g==s||b<<n&&redo;puts b,s}

```

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js), ~~197~~ 194 bytes

```
s=>c=>{(C=console.log)(s);w=0;g=[];while(~(w=s.indexOf(c,w)))g.push(w++);h=(H=_=>g.map(x=>A[x]=c,A=Array(l=s.length).fill` `)&&A.join``)();while(h!=(y=H(g=g.map((x,i)=>(l-~x-i%3)%l))))C(y);C(s)}

```

Try it online!

Takes inputs in currying syntax, i.e. `f(s)(c)`.

Not a perfect one at all, but I need JS. A lot of functions in function.

# Answer
> 2 votes
# C (gcc), 261 bytes

```
i,j,l,k;g(L,t,r,c)char**L;{L[r++][c]=k;c-=t?t-1?:0:-1;l<r||g(L,t,r,c<0?l-1:c%l);}f(S,K){char*s=S,*L[i=1+(l=strlen(s))];for(k=K;i--;)for(L[i]=calloc(j=l,1);j--;)L[i][j]=32;for(puts(s);s[++i];)s[i]-k||g(L,++j%3,0,i);for(i=1;strcmp(*L,L[i]);)puts(L[i++]);puts(s);}

```

Try it online!

# Answer
> 1 votes
# Jelly, 33 bytes

```
3ḶNṁ+%⁹L¤‘
Ṅẹ©¥@ÇÇṢ⁻®ƊÐ¿Ṭị;⁶¥ṖY,Y

```

Try it online!

---

Call as a function. (dyadic link)

I found some 33-byte alternatives, but no actual improvement.

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


# Question
Title: Shortest code to check if a string has only letters
Your task is to create a program which takes a string, and if it contains **any** numbers, symbols or other non-letter characters, it throws an error. Else, it returns the original string. (The string may include whitespace)

("Letters" are a-z and A-Z)

Examples:

**Input:** `My name is Joe`

**Output** `My name is Joe`

---

**Input:** `My username is Joe32`

**Output:** `(insert an error)`

(FYI this question has nothing to do with Don't Google google. It was identified as a possible copy.)

# Answer
# Stax, 8 bytes

```
êF┼Aµ╧û┤

```

Run and debug online!

Shortest solution so far but expect to be defeated soon.

## Explanation

Uses the unpacked version to explain.

```
' Vl+-!uy
' Vl+        Alphabet plus space
     -       Remove from input
      !u     If result is not empty raise division by zero error
        y    Else print input

```
> 0 votes

# Answer
# Julia, 53 bytes

```
s=readline();ismatch(r"[^a-z\s]"i,s)?error():print(s)

```

Read a string from STDIN using `readline()`. If any of its characters are not letters or whitespace (`ismatch(r"[^a-z\s]"i, s)`) then we `error()`, otherwise we `print(s)`.
> 5 votes

# Answer
# Gema, 14 characters

```
\W<-L>=@div{;}

```

Sample run:

```
bash-4.3$ gema '\W<-L>=@div{;}' <<< 'My name is Joe'
My name is Joe

bash-4.3$ gema '\W<-L>=@div{;}' <<< 'My username is Joe32'
Floating point exception (core dumped)

```
> 3 votes

# Answer
# C++14, 132 126 121 117 121 bytes

```
#include<iostream>
main(){std::string s;getline(std::cin,s);for(char c:s)if(!isalpha(c)&!isspace(c))throw;std::cout<<s;}

```

We read a line from `stdin`, check if each character is a letter or space - if it's not, we throw an error. Finally outputs the input.

*Thanks to Alex A for golfing off two bytes*
> 2 votes

# Answer
### PowerShell, 24 bytes

Filter the pipeline input based on whether it matches the regex:

```
|?{$_-match'^[a-z\s]+$'}

```

e.g. try it by piping the string in:

```
PS C:\> "Test Test"|?{$_-match'^[a-z\s]+$'}
Test Test

PS C:\> "Test ! Test"|?{$_-match'^[a-z\s]+$'}

```

The error message is silence/empty result. It matches case-insensitively by default.
> 2 votes

# Answer
## STATA, 57 bytes

```
di _r(a)
gl b=1/regexm("$a","^[a-zA-Z ]*$")
di _d($b)"$a"

```

Uses a regex to match letters and space (STATA's regex doesn't include character classes). Set a variable to 1/match exists. Then it prints a that many times, if match exists=0, it says it's invalid syntax. Otherwise, it prints it 1/1 = 1 time.
> 2 votes

# Answer
# CJam, 18 bytes

```
q_"
"'[,_el^|-!/

```

The multi-line string contains a tabulator, a space and a linefeed.

Try it online in the CJam interpreter.

### How it works

```
q_                    Read all input from STDIN and push a copy.
  "\t \n"             Push that string.
         '[,_el^      Push all letters. See: codegolf.stackexchange.com/a/54348
                |     Concatenate both strings.
                 -    Remove their characters from the copy of the input.
                  !   Logical NOT. Pushes 0 if there are other characters.
                   /  Split. Doesn't affect output if successful. Errors on 0.

```
> 2 votes

# Answer
# Python 3, 56 characters

```
import re;print(re.match(r'[a-z\s]+$',input(),2).string)

```

Usefully, match objects have this attribute `string` which is

> The string passed to match() or search().

while `None` does not.

```
In [10]: import re;print(re.match(r'[a-z\s]+$',input(),2).string)
54
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-0851dec671d1> in <module>()
----> 1 import re;print(re.match(r'[a-z\s]+$',input(),2).string)

AttributeError: 'NoneType' object has no attribute 'string'

In [11]: import re;print(re.match(r'[a-z\s]+$',input(),2).string)
rffef
rffef

```
> 2 votes

# Answer
# JavaScript, ~~48~~ ~~46~~ ~~45~~ ~~46~~ *31* Bytes

```
/[^a-z\s]/i.exec(a=prompt())?q:a

```

Accepts input, searches for invalid characters, if it finds any, returns a truthy value and thus evaluates the undefined character `q`. Otherwise, returns null and thus returns the string.

## Old version, 44 bytes

```
~(a=prompt()).search(/[^a-z\s]/i)?eval("@"):a

```

Tries to evaluate the invalid character `@` upon finding a numeric.

---

~~Edit 1: -2 bytes, thanks to @Alex A.~~

~~Edit 2: -1 byte, reworked. BONUS: Accounts for ALL whitespace! ^\_^<br>~~

~~Edit 3: +1 byte, added underscore testing.~~

Edit 4: Back to 46, unreworked.

Edit 5: -2 extra bytes to @edc65 (for old version; -1 for new).
> 1 votes

# Answer
# Hassium, 166 Bytes

```
func main(){r="";foreach(c in input()){c=c.toString();if(!("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ \t\n\r".contains(c)))throw(c);else r+=c;}println(r);}

```

Run and see expanded here
> 1 votes

# Answer
# Haskell, 56 bytes

```
q x|all(`elem`(['a'..'z']++['A'..'Z']++['\t'..'\r']))x=x

```

Throws the `Non-exhaustive patterns in function q` error if the string contains forbidden characters.
> 1 votes

# Answer
# Python 2, 60 bytes

```
import re;n=input();print[n][re.sub('[^a-zA-Z\s]+','',n)!=n]

```

Usage:

```
$ python -c "import re;n=input();print[n][re.sub('[^a-zA-Z\s]+','',n)!=n]"
"abcdefg"
abcdefg

```
> 1 votes

# Answer
# PHP, ~~51~~ 48 bytes

```
<?=preg_match('/[^a-z\s]/i',$a=$argv[1])?e():$a;

```

Runs from command line, like:

```
php test.php "Test me"

```

---

Using `preg_match` is shorter than using `ctype_alpha` as the latter needs whitespaces to be stripped.

---

As the error wasn't defined in the challenge, calling an undefined function seems the shortest way to generate an error. So this:

```
php test.php "Test me, 2"

```

leads to:

> PHP Fatal error: Call to undefined function e()

## Edit

Saved **3 bytes** by inverting the statement an by using the `i`-modifier. Thanks to fschmengler.
> 1 votes

# Answer
# Python 2, ~~68~~ ~~71~~ ~~70~~ 69 bytes

```
import re;s=raw_input();print s if re.match(r'[a-z\s]+$',s,2)else 0/0

```

Thanks to Alex A. and Martin Büttner for saving a byte and NightShadeQueen for another byte!
> 0 votes

# Answer
# Java 127 Bytes

```
class A{public static void main(String[]a){String s=System.console().readLine();System.out.print(s.matches("[A-z ]+")?s:0/0);}}

```

In Java from the command line you can have input and with the help of regular expression `[A-z ]+` which matches alphabets and space in the line, you can have this kind of trick.Moreover, `0/0` will throw `ArithmeticException`.
> 0 votes

# Answer
# Ruby, ~~26~~ 25 bytes

"undefined method \`+@' for nil:NilClass (NoMethodError)":

```
+(gets=~/^[A-z]*$/);print

```

Previous 26 bytes, "in \`/': divided by 0 (ZeroDivisionError)":

```
puts gets[/^[A-z]*$/]||1/0

```
> 0 votes

# Answer
## **C#** \- **174 157 148 bytes**

```
using System.Linq;namespace System{class A{static void Main(string[]s){if(!s[0].All(char.IsLetter))throw new Exception();Console.WriteLine(s[0]);}}}

```

usage:

Console application that takes a parameter in the form of a string and checks via LINQ if all the characters in that string are letters. If so, writes it to console. Otherwise throws exception.

Not particularly short. Will keep tinkering!

Edit: Think I'm pretty much done. Can't get it much shorter don't think.
> 0 votes

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


title: Garble that string!

text:
# Question
Title: Garble that string!
Given a string as input, output one or more variants of the string such that:

* No character is in it's original position
* No character is adjacent to a character that it was originally adjacent to

You can assume this will always be possible for the given string, and will only contain single case alphabetical characters (`[a-z]` or `[A-Z]` if you prefer)

Note that duplicates of the same character are not considered unique.

For example, given the input `programming`, the output cannot contain an `m` at the 7th **or** 8th character, and cannot contain a `g` at the 4th **or** 11th character (1 indexed)

## Example:

Take the string `abcdef`

The following would be a valid output: `daecfb`

However the following would be invalid: `fdbcae` as in this example `c` and `b` are still adjacent.

Adjacency also wraps, meaning you could not do `fdbeca` as `f` and `a` are still adjacent.

## Testcases:

Note these are not the **only** valid outputs for the given inputs

Written as `input -> output`:

```
helowi -> ioewhl
mayube -> euabmy
stephens -> nhseespt
aabcdeffghij -> dbfhjfigaeca

```

## Scoring:

This is so fewest bytes **in each language** wins!

# Answer
> 5 votes
# Jelly, ~~24~~ 23 bytes

```
ẋ2ṡ2Ṣ€
Ç³Ç¤œ&¬ɓ³=Sȯ
ẊÇ¿

```

Try it online!

Extremely long by virtue of my being awful at Jelly, but it finally works, at least... still in the process of golfing.

```
link that generates a list of sorted adjacent pairs:
ẋ2            duplicate argument ("abc" -> "abcabc")
  ṡ2          slices of 2 (-> "ab","bc","ca","ab","bc")
    Ṣ€        sort each

link that tests for invalid permutations:
Ç             get sorted adjacent pairs of argument
 ³Ç¤          do the same for the original input
    œ&        set intersection, then...
      ¬       ...inverse; i.e. do they have no elements in common
       ɓ   ȯ  logical OR the result of that with...
        ³=    elementwise equality with original input, and...
          S   ...sum; i.e. are some characters in the same position

main link:
Ẋ             shuffle the input list
  ¿           while
 Ç            the result of the previous link is truthy

```

# Answer
> 3 votes
# PHP\>=7.1, 147 Bytes

```
for($a=$argn,$r="^$a[-1].*$a[0]$",$k=0;$v=$a[$k];)$r.="|^.{{$k}}$v|$v".($l=$a[$k++-1])."|$l$v";for(;preg_match("#$r#",$s=str_shuffle($a)););echo$s;

```

PHP Sandbox Online

# PHP\>=7.1, 184 Bytes

Use the levenshtein distance instead of a Regex way

```
for($a=$argn;$v=$a[$k];$r[]=$l.$v)$r[]=$v.($l=$a[$k++-1]);for(;!$t&&$s=str_shuffle($a);)for($t=1,$i=0;$v=$s[$i];$t*=$v!=$a[$i++])foreach($r as$x)$t*=levenshtein($x,$s[$i-1].$v);echo$s;

```

PHP Sandbox Online

# PHP, 217 bytes

Version under 7.1

```
for($l=strlen($a=$argn),$r=$a[$k=0].$a[$l-1]."|".$a[$l-1]."$a[0]|^{$a[$l-1]}.*$a[0]$";$v=$a[$k];!$k?:$r.="|$v".$a[$k-1],++$k<$l?$r.="|$v".$a[$k]:0)$r.="|^.{{$k}}$v";for(;preg_match("#$r#",$s=str_shuffle($a)););echo$s;

```

Try it online!

# Answer
> 3 votes
# Python 2, 185 bytes

```
from itertools import*
x=input()
g=lambda m:set(zip(m*2,(m*2)[1:]))
for l in permutations(x):
 if not((g(l)|g(l[::-1]))&(g(x)|g(x[::-1]))or any(a==b for a,b in zip(x,l))):print`l`[2::5]

```

Try it online!
Prints all valid strings

# Answer
> 3 votes
# Brachylog, 21 bytes

```
p.jP;?z≠ᵐ&j¬{s₂p~s}P∧

```

Try it online!

## Explanation

I really would have wanted for `p.;?z≠ᵐ&j¬{s₂p~s~j}` to work for 2 bytes less, but it seems `~j` is not smart enough...

```
p.jP;?z≠ᵐ&j¬{s₂p~s}P∧  Input is a string, say ? = "asdfgha"
p                      Take a permutation of ?, say "sfagadh".
 .                     It is the output.
  j                    Concatenate it to itself: "sfagadhsfagadh"
   P                   Call that string P.
    ;?                 Pair P with the input: ["sfagadhsfagadh","asdfgha"]
      z                Zip, repeating elements of the longer string:
                        [["s","a"],["f","s"],["a","d"],...,["a","g"],["d","h"],["h","a"]]
       ≠ᵐ              Each pair must have different elements.
         &             Start new predicate
          j            Concatenate ? to itself: "asdfghaasdfgha"
           ¬{     }    The following cannot be satisfied:
             s₂        Take a substring of length 2
               p       and permute it.
                ~s     It is a substring of
                   P   P.
                    ∧  Do not unify P with the output.

```

# Answer
> 2 votes
# PHP 7.1, ~~136~~ 131 bytes

inspired by Jörg´s solution:

```
for($a=$argn;$c=$a[$k];)$r.="|$c".($d=$a[$k-1])."|$d$c|^.{".+$k++."}$c";while(preg_match("#$a$r#",($s=str_shuffle($a)).$s));echo$s;

```

Run as pipe with `-r` or test it online. (Make sure that PHP version 7.1 or above is selected)

Requires PHP 7.1; add 14 bytes for older PHP: Replace `$k-1` with `($k?:strlen($a))-1`;
(two more bytes for PHP\<5.3: `$k?$k-1:strlen($a)-1`)

**breakdown**

```
# A: loop through input to collect sub-expressions
for($a=$argn;$c=$a[$k];)
    $r.="|$c".($d=$a[$k-1])     # 1. pair of characters
        ."|$d$c"                # 2. reversed pair
        ."|^.{".+$k++."}$c";    # 3. $c is at k-th position
# B: shuffle input until regex does not match the result
while(preg_match("#$a$r#",($s=str_shuffle($a)).$s));    # (input as dummy sub-expression)
# C: print result
echo$s;

```

# Answer
> 1 votes
# PHP 7.1, ~~187 185 172 178~~ 143 bytes

```
do for($r=str_shuffle($s=$argn),$p=$i=0;$c=$s[$i];$p+=($c==$z)+preg_match("#$a|$b#",$s.$s))$b=strrev($a=$r[$i-1].$z=$r[$i++]);while($p);echo$r;

```

Run as pipe with `-r` or test it online. (Make sure that PHP version 7.1.0 or above is selected!)

**breakdown**

```
do
    for($r=str_shuffle($s=$argn),   # 2. shuffle input
        $p=$i=0;$c=$s[$i];          # 3. loop through input
        $p+=($c==$z)                        # 2. set $p if char is at old position
            +preg_match("#$a|$b#",$s.$s)    #    or if adjacency occurs in input
    )
        $b=strrev($a=$r[$i-1].$z=$r[$i++]); # 1. concat current with previous character
while($p);                          # 1. loop until $p is falsy
echo$r;                             # 4. print

```

# Answer
> 1 votes
# Ruby, ~~110~~ ~~97~~ 102 bytes

```
->s{x=s.chars
t=s*2
x.shuffle!while s.size.times.any?{|i|a,b=(x*2)[i,2];a==s[i]||t[a+b]||t[b+a]}
x*''}

```

Try it online!

# Answer
> 1 votes
# JavaScript 6, 116 Bytes

```
f=x=>(h=[...x].sort(_=>Math.random(z=0)-.5)).some(y=>y==x[z]||(x+x).match(y+(q=h[++z]||h[0])+'|'+q+y))?f(x):h.join``

```

```
f=x=>(h=[...x].sort(_=>Math.random(z=0)-.5)).some(y=>y==x[z]||(x+x).match(y+(q=h[++z]||h[0])+'|'+q+y))?f(x):h.join``

console.log (f('abcdef'));
```

# Answer
> 1 votes
# Stax, ~~23~~ 21 bytes

```
å╘┤‼¬½P¥ë└w↕⌐î◘E{╟u!Ö

```

Run and debug online!

Thanks for @recursive for saving 2 bytes.

Takes a very long time to run. A more reasonable/feasible version is (just 2 bytes longer)

```
Ç≡╨áiS║çdèû.#-Gî☺└╨◙σφ+

```

Run and debug online!

## Explanation

Uses the unpacked version to explain.

```
w|Nc_:=nGyG|*{E-!f+}ch+2B
w                            Loop anything before `}` while
 |N                          Next permutation (starting from the input)
   c_:=                      Index where the current array has the same element as the input (*)
                   }ch+2B    Define a block that finds all contiguous pairs in current string, including the pair `[last element, first element]`
       nG                    Apply the defined block to current string
         yG                  Do the same for the input
           |*                Outer product, contains pairs (which themselves are pairs) constructed from the last two array.
             {   f           Only keep pairs
              E-!            whose two elements have the same set of characters
                  +          Prepend the array at step (*).
                             This is used as the condition for the while loop

```

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


title: Cutpoints in a maze

text:
# Question
Title: Cutpoints in a maze
A maze is given as a matrix of 0s (walls) and 1s (walkable space) in any convenient format. Each cell is considered connected to its 4 (or fewer) orthogonal neighbours. A *connected component* is a set of walkable cells all transitively connected to each other. Your task is to identify the *cutpoints* \- walkable cells which, if turned into walls, would change the number of connected components. Output a boolean matrix with 1-s only at those locations. The goal is to do it in the fewest bytes of code.

The input matrix will consist of at least 3 rows and 3 columns. At least one of its cells will be a wall and at least one will be walkable. Your function or program must be able to process any of the examples below in under a minute on TIO (or on your own computer, if the language is not supported by TIO).

```
in:
11101001
11011101
00000001
11101111
11110101
00011111
10110001
11111111
out:
01000000
00001001
00000001
00000101
00110000
00010000
00000000
11100000

in:
1111111111111111
1000000000000001
1111111111111101
0000000000000101
1111111111110101
1000000000010101
1011111111010101
1010000001010101
1010111101010101
1010101111010101
1010100000010101
1010111111110101
1010000000000101
1011111111111101
1000000000000001
1111111111111111
out:
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000

in:
1011010001111010
1111111011101101
1110010101001011
1111001110010010
1111010000101001
0111101001000101
0011100111110010
1001110011111110
0101000011100011
1110110101001110
0010100111000110
1000110111011010
0100101000100101
0001010101100011
1001010000111101
1000111011000010
out:
0000000000111010
1011110001001000
0000000000000011
0000000100010000
0000010000101000
0000001000000100
0000000011000000
1001100000011110
0000000001000010
0110100001000110
0000100101000010
1000100000000000
0100001000000100
0000000100100001
0000010000111000
0000010000000010

```

# Answer
# MATL, 26 bytes

```
n:"GG0@(,w4&1ZIuz]=~]vGZye

```

The input is a numerical matrix, using `;` as row separator.

Try it online! Or verify all test cases.

### Explanation

```
n           % Implicit input: matrix. Push number of elements, N
:           % Range: gives [1 2 ... N]
"           % For each k in [1 2 ... N]
  GG        %   Push input matrix twice
  0@(       %   Write 0 at position k (in column-major order: down, then across).
            %   The stack now contains the original matrix and a modified matrix
            %   with 0 at position k
  ,         %   Do twice
    w       %     Swap
    4       %     Push 4. This specifies 4-element neighbourhood
    &1ZI    %     Label each connected component, using the specified
            %     neighbourhood. This replaces each 1 in the matrix by a
            %     positive integer according to the connected component it
            %     belongs to
    u       %     Unique: gives a vector of deduplicate elements
    z       %     Number of nonzeros. This is the number of connected components
  ]         %   End
  =~        %   Are they different? Gives true of false
]           % End
v           % Concatenate stack into a column vector
GZye        % Reshape (in column-major order) according to size of input matrix.
            % Implicit display

```
> 3 votes

# Answer
# Stax, 40 bytes

```
Çóê↓â.Φ}╞│*w<(♦◙¼ñ£º█¢,D`ì♥W4·☺╛gÇÜ♠╗4D┬

```

Run and debug test cases

This program takes input as a space separated string containing rows. The output is in the same format. Here's the unpacked ascii representation.

```
{2%{_xi48&GxG=-}_?m}{'1'2|e{"12|21".22RjMJguHgu%

```

The fundamental operation for counting an island works like this.

1. Replace the first `'1'` with a `'2'`.
2. Regex replace `'12|21'` with `'22'`.
3. Split on spaces.
4. Transpose matrix.
5. Repeat from 2. until a string is repeated.
6. Repeat from 1. until there is no longer a `'1'` in the string. The number of repetitions is the number of islands.

.

```
{               start map block over input string, composed of [ 01]
  2%            mod by 2. space and 0 yield 0. 1 yields 1. (a)
  {             start conditional block for the 1s.
    _           original char from string (b)
    xi48&       make copy of input with current character replaced with 0
    G           jump to unbalanced }, then return; counts islands (c)
    xG          counts islands in original input (d)
    =           are (c) and (d) equal? 0 or 1 (e)
    -           b - e; this is 1 iff this character is a bridge
  }             end conditional block
  _?            execute block if (a) is 1, otherwise use original char from string
m               close block and perform map over input
}               goto target - count islands and return
{               start generator block
  '1'2|e        replace the first 1 with a 2
  {             start generator block
    "12|21".22R replace "12" and "21" with "22"
    jMJ         split into rows, transpose, and rejoin with spaces
  gu            generate values until any duplicate is encountered
  H             keep the last value
gu              generate values until any duplicate is encountered
%               count number of iterations it took

```

Bonus 44 byte program \- this version inputs and outputs using the grid format.
> 3 votes

# Answer
# Perl 5, `-p0` ~~105~~ ~~101~~ ~~96~~ ~~93~~ ~~90~~ 89 bytes

Uses `b` instead of `1` in the input.

Make sure the matrix on STDIN is terminated with a newline

```
#!/usr/bin/perl -p0
s%b%$_="$`z$'";s:|.:/
/>s#(\pL)(.{@{-}}|)(?!\1)(\pL)#$&|a.$2.a#se&&y/{c/z />0:seg&/\B/%eg

```

Try it online!

Uses 3 levels of substitution!

This 87 byte version is both in input and output format easier to interpret, but is not competing since it uses 3 different characters in the output:

```
#!/usr/bin/perl -0p
s%b%$_="$`z$'";s:|.:/
/>s#(\w)(.{@{-}}|)(?!\1)(\w)#$&|a.$2.a#se&&y/{c/z />0:seg&/\B/%eg

```

Try it online!

It's easy to save another byte (the regex `s` modifier) in both versions by using some different (non-alphanumeric) character as row terminator (instead of newline), but that makes the input quite unreadable again.

# How it works

Consider the substitution

```
s#(\w)(.{columns}|)(?!1)(\w)#c$2c#s

```

This will find two letters that are different and next to each other horizontally or vertically and replace them by `c`. In a maze whose paths consist of entirely the letter `b` nothing will happen since the letters are the same, but as soon as one of the letters is replaced by another one (e.g. `z`) that letter and a neighbor will be replaced by `c` and repeated application is a flood-fill of the connected component with `c` from seed `z`.

In this case I however don't want a complete flood-fill. I want to fill only one of the arms neighboring `z`, so after the first step I want the `z` gone. That already works with the `c$2c` replacement, but I later want to restart a flood-fill along another arm starting from the same point and I don't know which of the `c`s was originally `z` anymore. So instead I use

```
s#(\w)(.{columns}|)(?!\1)(\w)#$&|a.$2.a#se

```

`b | a` is `c`, `b | c` is `c` and `z | a` is `{`. So in a maze with paths made up of `b` and a seed `z` in the first step `b` will get replaced by `c` and `z` will get replaced by `{` which is not a letter and does not match `\w` and so will not cause further fills. The `c` however will keep a further flood-fill going and one neighbor arm of the seed gets filled. E.g. starting from

```
  b                      c
  b                      c
bbzbb       becomes    bb{bb
  b                      b
  b                      b

```

I can then replace all c by some non letter (e.g. `-`) and replace `{` by `z` again to restart the flood-fill:

```
  -                      -
  -                      -
bbzbb       becomes    cc{bb
  b                      b
  b                      b

```

and repeat this process until all neighbors of the seed have been converted. If I then once more replace `{` by `z` and flood-fill:

```
  -                      -
  -                      -
--z--       stays      --z--
  -                      -
  -                      -

```

The `z` remains behind at the end because there is no neighbor to do a transformation with. That makes clear what happens in the following code fragment:

```
/\n/ >

```

Find the first newline. The starting offset is now in `@-`

```
s#(\w)(.{@{-}}|)(?!\1)(\w)#$&|a.$2.a#se

```

The regex discussed above with `@{-}` as number of columns (since plain `@-` confuses the perl parser and doesn't properly substitute)

```
&&

```

The `/\n/` always succeeds and the substitution is true as long as we can still flood-fill. So the part after `&&` is executed if the flood-fill of one arm is done. If not the left side evaluates to an empty string

```
y/{c/z / > 0

```

Restart the flood-fill and return 1 if the previous flood-fill did anything. Else return the empty string. This whole piece of code is wrapped inside

```
s:|.: code :seg

```

So if this is executed on a starting string `$_` with a `z` at the seed position the piece of code inside will be executed many times mostly returning nothing but a `1` every time a neighbor arm gets flood-filled. Effectively `$_` gets destroyed and replaced by as many `1`s as there are connected components attached to `z`. Notice that the loop needs to be executed up to sum of component sizes + number of arms times but that is OK since it will "number of characters including newlines * 2 + 1" times.

The maze gets disconnected if there are no `1`'s (empty string, an isolated vertex) or if there are more than 1 arms (more than 2 `1`s). This can be checked using the regex `/\B/` (this gives `0` instead of `1` on older perl versions. It's arguable which one is wrong). Unfortunately if it doesn't match this will give an empty string instead of `0`. However the `s:|.: code :seg` was designed to always return an odd number so by doing an `&` with `/\B/` this will give `0` or `1`.

All that is left is walking the whole input array and at each walkable position seed with `z` and count connected arms. That is easily done with:

```
s%b%$_="$`z$'"; code %eg

```

The only problem is that in the non-walkable positions the old value is retained. Since we need `0`s there that means the original input array must have `0` in the non walkable positions and `0` matches `\w` in the original substitution and would trigger flood-fills. That's why I use `\pL` instead (only match letters).
> 2 votes

# Answer
# Java 8, ~~503~~ ~~489~~ ~~459~~ ~~455~~ 407 bytes

```
int R,C,v[][];m->{int r[][]=new int[R=m.length][C=m[0].length],i=R*C,a=i(m),x,y,q;for(;i-->0;m[y][x]=0,r[y][x]=i(m)!=a?1:0,m[y][x]=q)q=m[y=i/C][x=i%C];return r;}int i(int[][]m){int r=0,i=R*C,x,y;for(v=new int[R][C];i-->0;)if(m[y=i/C][x=i%C]>v[y][x]){d(m,x,y);r++;}return r;}void d(int[][]m,int c,int r){v[r][c]=1;for(int k=-3,x,y;k<4;k+=2)if((x=c+k%2-k/2)>=0&x<C&(y=r+k/2)>=0&y<R&&m[y][x]>v[y][x])d(m,x,y);}

```

-66 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
int R,C,                    // Amount of rows/columns on class-level
    v[][];                  // Visited-matrix on class-level

m->{                        // Method with int-matrix as both parameter and return-type
  int r[][]=new int[R=m.length][C=m[0].length],
                            //  Create the result-matrix, and set `R` and `C`
      i=R*C,                //  Index-integer
      a=i(m),               //  The current amount of islands
      x,y,                  //  Temp integers for the coordinates
      q;                    //  Temp integer for the value
  for(;i-->0                //  Loop `i` over each cell:
      ;                     //    After each iteration:
       m[y][x]=0,           //     Temporarily change the current value to 0
       r[y][x]=i(m)!a?      //     If the current and initial amount of islands are not
                            //     the same anymore:
                1           //      Set the result-value at this coordinate to 1
               :            //     Else:
                0,          //      Set the result-value at this coordinate to 0
       m[y][x]=q)           //     Then change the current value back to what it was
    q=m[y=i/C][x=i%C];      //   Save the current value at this coordinate
  return r;}                //  Return the result-matrix

// Separated method to determine the amount of islands in a matrix
int i(int[][]m){
  int r=0,                  //  Result-count, starting at 0
      i=R*C,                //  Index integer
      x,y;                  //  Temp integers for the coordinates
  for(v=new int[R][C];      //  Reset the visited array
      i-->0;)               //  Loop over the cells:
    if(m[y=i/C][x=i%C]      //   If the current cell is a 1,
       >v[y][x]){           //   and we haven't visited it yet:
      d(m,x,y);             //    Check every direction around this cell
      r++;}                 //    And raise the result-counter by 1
   return r;}               //  Return the result-counter

// Separated method to check each direction around a cell
void d(int[][]m,int c,int r){
  v[r][c]=1;                //  Flag this cell as visited
  for(int k=-3,x,y;k<4;k+=2)//  Loop over the four directions:
    if((x=c+k%2-k/2)>=0&x<C&(y=r+k/2)>=0&y<R
                            //   If the cell in the direction is within bounds,
       &&m[y][x]            //   and it's a path we can walk,
         >v[y][x])          //   and we haven't visited it yet:
      d(m,x,y);}            //    Do a recursive call for this cell

```
> 2 votes

# Answer
# Python 2, 290 bytes

```
lambda m:[[b([[C and(I,J)!=(i,j)for J,C in e(R)]for I,R in e(m)])!=b(eval(`m`))for j,c in e(r)]for i,r in e(m)]
def F(m,i,j):
	if len(m)>i>=0<=j<len(m[i])>0<m[i][j]:m[i][j]=0;F(m,i,j+1);F(m,i,j-1);F(m,i+1,j);F(m,i-1,j)
b=lambda m:sum(F(m,i,j)or c for i,r in e(m)for j,c in e(r))
e=enumerate

```

Try it online!

-11 bytes thanks to Rod
-11 bytes thanks to Lynn
> 1 votes

# Answer
# Wolfram Language (Mathematica), 118 bytes

```
(r=ReplacePart)[0#,Cases[#~Position~1,p_/;(c=Max@MorphologicalComponents[#,CornerNeighbors->1<0]&)@r[#,p->0]>c@#]->1]&

```

Try it online!
> 1 votes

# Answer
# Javascript 122 bytes

Input/output as a multiline string.

```
m=>m.replace(/./g,(v,p,m,n=[...m],f=p=>n[p]==1&&(n[p]=0,v=f(p-1)+f(p+1)+f(p-w)+f(p+w)-1?1:0,1))=>(f(p),v),w=~m.search`\n`)

```

For each walkable cell, put a block and try to fill the 4 neighbor cells. If the current cell is not a cut point, then starting from any open neighbor will fill all of them. Else, I will need more than one fill operation to reach all neighbor cells.

*Less golfed*

```
m=>{
  w = m.search('\n') + 1; // offset to the next row
  result = [...m].map( // for each cell
     ( v, // current value
       p  // current position
     ) => {
     n = [...m]; // work on a copy of the input
     // recursive fill function from position p
     // returns 1 if managed to fill at least 1 cell
     fill = (p) => {
        if (n[p] == 1)
        {
           n[p] = 0;
           // flag will be > 1 if the fill from the current point found disjointed areas
           // flag will be 0 if no area could be filled (isolated cell)
           var flag = fill(p+1) + fill(p-1) + fill(p+w) + fill(p-w);
           // v is modified repeatedly, during recursion
           // but I need the value at top level, when fill returns to original caller
           v = flag != 1 ? 1 : 0;
           return 1; // at least 1 cell filled
        }
        else
           return 0; // no fill
     }
     fill(p)
     return v // orginal value or modified by fill function
  })
}

```

**Test**

```
var F=
m=>m.replace(/./g,(v,p,m,n=[...m],f=p=>n[p]==1&&(n[p]=0,v=f(p-1)+f(p+1)+f(p-w)+f(p+w)-1?1:0,1))=>(f(p),v),w=~m.search`\n`)

var test=`in:
11101001
11011101
00000001
11101111
11110101
00011111
10110001
11111111
out:
01000000
00001001
00000001
00000101
00110000
00010000
00000000
11100000

in:
1111111111111111
1000000000000001
1111111111111101
0000000000000101
1111111111110101
1000000000010101
1011111111010101
1010000001010101
1010111101010101
1010101111010101
1010100000010101
1010111111110101
1010000000000101
1011111111111101
1000000000000001
1111111111111111
out:
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000

in:
1011010001111010
1111111011101101
1110010101001011
1111001110010010
1111010000101001
0111101001000101
0011100111110010
1001110011111110
0101000011100011
1110110101001110
0010100111000110
1000110111011010
0100101000100101
0001010101100011
1001010000111101
1000111011000010
out:
0000000000111010
1011110001001000
0000000000000011
0000000100010000
0000010000101000
0000001000000100
0000000011000000
1001100000011110
0000000001000010
0110100001000110
0000100101000010
1000100000000000
0100001000000100
0000000100100001
0000010000111000
0000010000000010
`.match(/\d[10\n]+\d/g);
for(i = 0; test[2*i]; ++i)
{
   input = test[2*i]
   check = test[2*i+1]
   result = F(input)
   ok = check == result
   console.log('Test '+ i + ' ' + (ok?'OK':'FAIL'),
   '\n'+input, '\n'+result)
}
```
> 1 votes

---
Tags: code-golf, graph-theory, restricted-time, maze, binary-matrix
---


title: Extract filename from path

text:
# Question
Title: Extract filename from path
Given a printable ASCII string representing a path to a file on a POSIX-compliant system, return just the filename, i.e. remove everything until and including the last slash (`/`):

`/full/path/file.name.ext``file.name.ext`

`nopath.here``nopath.here`

`dir/.hidden``.hidden`

`/dirs.can/have.exts/file``file`

`./here``here`

`don't\do this``don't\do this`

# Answer
> 3 votes
# QuadR, 4 bytes

# Retina, 4 bytes

```
.*/

```

Try QuadR online!

Try Retina online!

Replace as many characters as possible, followed by a slash, with nothing.

Equivalent to the 9-byte Dyalog APL function `'.*/'⎕R''`.

# Answer
> 2 votes
# Python 2, ~~41~~ ~~27~~ 25 bytes

```
lambda s:s.split('/')[-1]

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 4 bytes

```
'/¡θ

```

Try it online!

# Answer
> 2 votes
# Java (OpenJDK 9), 25 bytes

```
s->s.replaceAll(".*/","")

```

Try it online!

### Honorable mention

26 bytes:

```
s->("/"+s).split(".*/")[1]

```

# Answer
> 1 votes
# Red, 24 bytes

```
func[s][last split s"/"]

```

Try it online!

Red has a built-in `split-path` but it needs a path agrument and not a string.

`f: func[p][last split-path to-file p]`

# Answer
> 0 votes
# Stax, 4 bytes

```
'//H

```

Run and debug online!

## Explanation

Split on "/", take last part.

# Answer
> 0 votes
# Wolfram Language (Mathematica), 12 bytes

A built-in.

```
FileNameTake

```

Try it online!

# Answer
> 0 votes
# Haskell, 29 bytes

```
r.fst.span(/='/').r
r=reverse

```

Try it online!

# Answer
> 0 votes
# Coconut, 19 bytes

```
n->n.split('/')[-1]

```

Try it online!

---
Tags: code-golf, string, file-system
---


title: There, I broke it (with scissors)

text:
# Question
Title: There, I broke it (with scissors)
# Challenge

Given a string describing a cutting rule and another string, cut parts out of the second string using the rule described by the first string.

Both strings will consist of letters `a-z` or `A-Z`, whichever one you choose (they don't have to be represented the same way). The way the second string is to be modified is described below:

# Algorithm

Take the first string and imagine filling in the gaps between non-adjacent (increasing) letters with `=`; for example, `abcfg` =\> `abc==fg`. Then, line up the two strings and return all characters from the first string that aren't above an equal sign. For example, given `abcfg` and `qrstuvw` as inputs:

```
qrstuvw - Modify
abc==fg - Modifier

qrs--vw -> qrsvw

```

If the modifier is shorter after filling with equal signs, all trailing characters in the second string should be included. If the modifier is longer, the trailing characters are ignored.

The modifier isn't guaranteed to be sorted.

# Test Cases

```
abcfg, qrstuvw -> qrsvw
abqrs, qwertyuiopasdfghjklzxcvbnm -> qwjklzxcvbnm
za, qr -> qr
azazaz, qwertyuioplkjhgfdsazxcvbnmnbvcxzasdfghjklpoiuytrewq -> qmn

```

Reference Implementation (used to generate test cases) -\> TIO

# Rules

* Standard Loopholes Apply
* You may take input as two strings, two lists of characters, a matrix of characters, etc. (any other reasonable format is acceptable)
* You may output as a string or a list of characters (or some other standard format for strings)
* This is , so the shortest answer in bytes in each language is declared the winner for its language. No answer will be accepted.
* Either string may be empty.

Happy Golfing!

*Inspired by Kevin Cruijssen's recent two challenges, "There, I fixed it (with tape/rope)"*

# Answer
> 5 votes
# JavaScript (ES6), ~~81~~ 80 bytes

Takes input in currying syntax `(modify)(modifier)`.

```
s=>g=([c,...a],d=i=0,x=s[k=parseInt(c,36),i+=c?d&&(k-d+26)%26:1])=>x?x+g(a,k):''

```

Try it online!

### Commented

```
s =>                       // outer function, taking the string s to modify
  g = (                    // recursive inner function g(), taking:
    [c, ...a],             //   c = current modifier character; a[] = remaining characters
    d = i = 0,             //   d = code of previous modifier character; i = pointer in s
    x = s[                 //   x = i-th character of s
      k = parseInt(c, 36), //     k = code of the current modifier character in [10..35]
      i += c ?             //     update i; if c is defined:
        d &&               //       if d = 0, let i unchanged
        (k - d + 26) % 26  //       otherwise, add the difference between k and d (mod 26)
      :                    //     else:
        1                  //       just pick the next character by adding 1
    ]                      //   end of character lookup in s
  ) =>                     //
    x ?                    // if x is defined:
      x + g(a, k)          //   append x and do a recursive call to g()
    :                      // else:
      ''                   //   stop recursion

```

# Answer
> 3 votes
# Python 3, 99 bytes

```
lambda a,b:[x for x,y in zip(a,''.join(d+(ord(c)+~ord(d))%26*'='for c,d in zip(b[1:],b))+a)if'='<y]

```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~20~~ 17 bytes

```
ćsv¹Ç¥Nè<yú«}SðÊÏ

```

Try it online!

---

Calculates the ASCII distance between each char, prepending that many spaces if it's positive. Negative distance results in appending 0 spaces, as per the spec. After that, I push all characters at the same indices in string 2 as the spaces in the first manipulated string.

---

```
Input: [azaz,qwertyuiopasdfghjklzxcvbnm]
--------------------------------------------------------------------------------

ćs                # Remove head, swap                           | [a, zaz]
  v               # Iterate...                                  | ............
   ¹Ç¥            # Push deltas between each char of string 1   | [a,[25,-25,25,-25]]
      Nè          # Push delta at index...                      | [a, 25]
        <         # Decrement (for 1-indexed answer)            | [a, 24]
         y        # Push current char in iteration...           | [a, 24, z]
          ú       # Append b spaces to a...                     | [a, '(spaces)z']
           «      # Concat                                      | [a(spaces)z]
            }     # End loop.                                   | [a(spaces)za(spaces)z]
             SðÊ  # Split, push 1 for non-space elements.       | [Long array of 1/0]
                Ï # Push chars from 2 that aren't spaces in 1.  | ['qmn']

```

---

90% sure I can lose another 2-3 bytes by not using spaces, but pushing the char at index N. Still working on this variant at the moment... What my "better idea" ended up as:

# 05AB1E, 18 bytes

```
Ç¥ε1‚Z}ηO0¸ìʒ²g‹}è

```

Try it online!

I feel like I'm missing something, if you see improvements on `ε1‚Z}`, `ʒ²g‹}` or `0¸ì` lmk...

`Ç¥ε1‚Z}ηO0¸ìè` was 13, but it wraps when `n > |input_2|` to `input_2[n%|input_2|]`...

# Answer
> 2 votes
# APL (Dyalog Classic), ~~35~~ ~~34~~ 32 bytes

```
{⍵∩⍨⊃¨↓∘⍵¨+\0,1⌈(-2-/⎕ucs⍺),=⍨⍵}

```

Try it online!

# Answer
> 2 votes
# K (ngn/k), ~~27~~ ~~24~~ 25 bytes

```
{y[+\0,1|1_-':x,!#y]^" "}

```

Try it online!

```
{y[+\0,1|1_-':x,!#y]^" "}

{                       } function with x and y as arguments
                 #y       the length of y
                !#y       0 1 2 ... (#y)-1
              x,          x concatenated with
           -':            differences between pairs
         1_               rm extra leading item
       1|                 max between 1 and
     0,                   prepend 0
   +\                     partial sums
 y[                ]      index y with that
                    ^" "  rm spaces due to out-of-bounds indexing

```

# Answer
> 2 votes
# Stax, 15 bytes

```
Ç«|¢Äα•è@╟╣i`vF

```

Run and debug it

This is the ascii representation.

```
:-Z+{v0|Mt|cB]pFp

```
1. Get pairwise differences.
2. Prepend a zero.
3. Foreach difference, repeat
    4. Subtract 1, and take maximum with zero.
    5. Remove that many characters from the beginning of string.
    6. Stop if the string is empty.
4. Print the rest of the string.

# Answer
> 2 votes
# Jelly, 14 bytes

```
OI’R¬⁸żFḣL}aḟ0

```

A dyadic link accepting the modifier as a list of characters on the left and the list of characters to modify on the right returning a lists of characters.

**Try it online!**

### How?

```
OI’R¬⁸żFḣL}aḟ0 - Link list of characters Modifier, list of characters InStr
               -                       e.g.  ['a','c','g','a'], ['n','m','l','k','j']
O              - ordinals of Modifier        [97,99,103,97]
 I             - incremental differences     [2,4,-6]
  ’            - decrement                   [1,3,-7]
   R           - range                       [[1],[1,2,3],[]]
    ¬          - NOT (vectorises)            [[0],[0,0,0],[]]
     ⁸         - chain's left argument, Modifier
      ż        - zip together                [['a',[0]],['c',[0,0,0]],['g',[]],['a']]
       F       - flatten                     ['a',0,'c',0,0,0,'g','a']
         L}    - length of right (InStr)     5
        ḣ      - head to index               ['a',0,'c',0,0] (if shorter or equal, no effect)
           a   - AND with InStr (vectorises) ['n',0,'l',0,0]
            ḟ0 - filter out zeros            ['n','l']

```

# Answer
> 2 votes
# JavaScript (ES6), 79 bytes

```
f=([t,...T],s,z=T[0])=>z&&s?s[0]+f(T,s.slice(t>z||(parseInt(t+z,36)-370)%37)):s

```

Uses the same algorithm for calculating distance between letters as my last answer.

**Test cases:**

```
f=([t,...T],s,z=T[0])=>z&&s?s[0]+f(T,s.slice(t>z||(parseInt(t+z,36)-370)%37)):s

console.log(f('abcfg','qrstuvw')) // -> qrsvw
console.log(f('abqrs','qwertyuiopasdfghjklzxcvbnm')) // -> qwjklzxcvbnm
console.log(f('za','qr')) // -> qr
console.log(f('azazaz','qwertyuioplkjhgfdsazxcvbnmnbvcxzasdfghjklpoiuytrewq')) // -> qmn
```

# Answer
> 1 votes
# Haskell, 49 bytes

```
(x:r)#(y:n:s)=x:drop(length[y..n]-2)r#(n:s)
r#_=r

```

Try it online!

# Answer
> 1 votes
# Perl 5, 45 bytes

```
s/./v0.$;x(ord($')-1-ord$&)/eg;$_|=<>;s/\W//g

```

Try it online!

# Answer
> 1 votes
# Charcoal, ~~29~~ 28 bytes

```
⭆η×ιＩ§⁺⭆θ⁺×0∧μ⊖⁻℅λ℅§θ⊖μ1⭆η1κ

```

Try it online! Link is to verbose version of code. Based on my answer to There, I fixed it with tape. Explanation:

```
       ⭆θ⁺×0∧μ⊖⁻℅λ℅§θ⊖μ1        Fix it with tape, but map to 1s and 0s
      ⁺                 ⭆η1     Append extra 1s just in case
⭆η                              Map over the second string
     §                     κ    Get the character from the fixed string
    Ｉ                           Cast to integer
  ×ι                            Repeat the current character that many times
                                Implicitly print

```

~~Note: This should be 28 bytes, but `And` is broken at time of writing.~~

# Answer
> 1 votes
# Ruby, ~~68~~ 64 bytes

```
->m,z,i=1{z[i,[0,m[i].ord+~m[i-1].ord].max]&&='';m[i+=1]?redo:z}

```

Try it online!

# Answer
> 0 votes
# Java 8, 117 bytes

```
a->b->{for(int i=0,j;++i<a.length;b=j>0&b.length()>=i+j?b.substring(0,i)+b.substring(i+j):b)j=a[i]+~a[i-1];return b;}

```

**Explanation:**

Try it online.

```
a->b->{                   // Method with char-array + String parameters and String return
  for(int i=0,j;++i<a.length;
                          //  Loop `i` in range [1; length_of_array)
      b=                  //    After every iteration: change the String-input to:
        j>0               //     If `j` is larger than 0,
        &b.length()>=i+j? //     and the length of `b` is larger or equal to `i+j`:
         b.substring(0,i) //      Take the substring [0; i)
         +b.substring(i+j)//      + the substring [i+j; end_of_string]
        :                 //     Else:
         b)               //      Leave `b` the same
    j=a[i]+~a[i-1];       //   Set `j` to the difference between two adjacent chars - 1
  return b;}              //  Return the modified input-String

```

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


title: Program Sequence Generator

text:
# Question
Title: Program Sequence Generator
Your challenge is to implement a cyclic Program Sequence Generator (PSG) in a language of your choice.

Given a language, *L*, a **PSG in *L*** is **a program in *L* that outputs a PSG in *L***. Some properties of a PSG are:

* Repeated execution of a PSG in *L* generates a sequence of programs in *L*.
* A PSG is said to be cyclic if the sequence it generates is cyclic.
* The period of a cyclic PSG, *P*, is written *T*(*P*) and is the period of the cycle in the sequence it generates. The period of a non-cyclic PSG is written the same way and is infinite.

A trivial example of a PSG is a quine; any quine is a cyclic PSG with period 1.

To make this challenge interesting, **the period of your PSG must be at least 5**.

Scoring is a bit different than typical code golf. Informally, **your score is the sum of the length of all programs in one cycle of the sequence generated by your PSG divided by the period of your PSG**. Formally: let *P* be your PSG, *pₙ* be the *n*th term in your PSG's sequence, and *l*(*pₙ*) be the length in bytes of *pₙ*. Then your score is:

For a non-cyclic PSG, since the limit of *l*(*pₙ*) as *n* goes to infinity is infinity, the score of any non-cyclic PSGs diverges to infinity.

**The PSG with the lowest score wins**

# Answer
> 4 votes
## JavaScript (ES6), score ~~50~~ ~~49~~ ~~48~~ ~~47~~ 37

*Saved 10 points thanks to @alephalpha*

```
(f=x=>alert(`(f=${f})(${++x%5})`))(0)

```

Period is 5, each program is 37 bytes long. The `0` is changed to `1`, `2`, `3`, `4`, then back to `0`.

# Answer
> 4 votes
# JavaScript (ES6), score ~~77~~ ~~74~~ 66

The period of this PSG is 5. Each iteration of the sequence removes one asterisk in the block comment until it reaches 2, then goes back to 6.

```
f=_=>/**/`f=${f}`.replace('**/','*/').replace('/*\/','/******/')

```

Let's look at some partial sums to see what the limit approaches.

```
m     1     2     3     4     5
score 64    66    66.33 66.25 66

```

**Edit:** thanks to @ETHproductions for pointing out that I should put the comment first. Not only is the code much shorter, it appears neater!

# Answer
> 2 votes
# Python 2, score ~~119~~ 89

```
s='s=%r;c=0;s=s[:7]+`c+1-c/4*5`+s[8:];print s%%s';c=0;s=s[:7]+`c+1-c/4*5`+s[8:];print s%s

```

Try it online!

The period of my PSG is 5. Each program is 89 bytes in length. Therefore, my score is 89.

*-30 bytes thanks to ovs.*

# Answer
> 0 votes
# Pari/GP, score 38

```
(f=(x)->print1("(f="f")("x++%5")"))(0)

```

Period is 5.

Try it online!

---
Tags: code-golf, quine, code-generation
---


title: Display Scrolling Waves

text:
# Question
Title: Display Scrolling Waves
**The challenge is to display and scroll a sine waveform in the least number of characters.**

**Restrictions:**

* Total height of wave must be at least seven units (characters, pixels, etc).
* The generated wave must scroll in-place.

**Additional Rules/Information:**

* The sine wave must be distinguishable from triangle and square waves.
    + "distinguishable" indicates sampling at least every π/8

**Additional Judgement Criteria:**

* Appearance/Quality of the wave
* Number of periods displayed

Winning entries will have the fewest characters of code and generate a sine wave with the most samples per period.

# Answer
## APL (46)

```
{∇⍵+1⊣⎕DL÷9⊣⎕SM∘←↑⍵∘{0,⍵,⍨9+⌈9×1○9÷⍨⍺+⍵}¨⍳79}1

```

It looks like this, and scrolls to the left:

In action: http://frankenstein.d-n-s.org.uk/~marinus/sine.mp4
> 13 votes

# Answer
## Mathematica : 49

```
Plot[Sin[x+a],{x,0,9},Axes->None]~Animate~{a,0,2Pi}

```

The flickering is a GIF-produced artifact. Runs smoothly on the screen.
> 14 votes

# Answer
## Machine code x86 16-bit DOS, 40 bytes

░‼═►h áë←☺‼▀♥▐4┘■▐♀▐♦▀←i;@☺&ê◄■├uσBδ╪

Or in a more human readable format (typical hugi conventions followed) :

```
;  40 byte version
; 00000000:  0A 00 B0 13 CD 10 68 00-A0 07 89 1B 01 13 DF 03   ......h.........
; 00000010:  DE 34 D9 FE DE 0C DE 04-DF 1B 69 3B 40 01 26 88   .4........i;@.&.
; 00000020:  11 FE C3 75 E5 42 EB D8                           ...u.B..

;  42 byte version
; 00000000:  0A 00 B0 13 CD 10 68 00-A0 07 89 1B 01 13 DF 03   ......h.........
; 00000010:  DE 34 D9 FE DE 0C DE 04-DF 1B 69 3B 40 01 26 88   .4........i;@.&.
; 00000020:  11 FE C3 75 E5 42 E2 FE-EB D6                     ...u.B....

[bits 16]

newscreen:
 or al,[bx+si]  ; trade off vertical height for # of periods
 mov al,13h
 int 10h
 push 0a000h
 pop es

iter:
 mov word [bp+di],bx
 add word [bp+di],dx
 fild word [bp+di]
 fidiv word [si]
 fsin
 fimul word [si]
 fiadd word [si]
 fistp word [bp+di]
 imul di,word [bp+di],320
 mov [es:di+bx],dl
 inc bl
 jnz iter
 inc dx

delay:
 loop delay  ; can remove this to get 40 bytes, but wont look as good since it scrolls too fast

 jmp newscreen

```
> 10 votes

# Answer
## Python 2.7 with Pygame (~~196~~ 178)

```
import math,pygame as p
D=p.display
x=0
s=D.set_mode((600,400))
while 1:
 i=0;x+=1;D.flip();s.fill([0]*3)
 while i<600:s.set_at((i,int(200*math.sin((i+x)*.01)+200)),[255]*3);i+=1

```

Draws in pixels. Went for looks rather than characters.
> 3 votes

# Answer
# Ruby, 105 characters

```
d=0
loop{s=(1..9).map{" "*79}
79.times{|i|s[(Math.sin((i+d)*Math::PI/16)*4+4.5)][i]=?x}
puts"^[[H",s
d+=1}

```

The `^[` is a single escape character. (You can enter it with `Ctrl`-`V`,`Esc` in the terminal and Vim or `Ctrl`-`Q`,`Esc` in MCEdit and Emacs.)

The animation is displayed from the 2nd line of top left corner of the terminal and scrolls from right to left at full speed (add `sleep 0.1;` before the last `}` to slow it down).

Sample run:

```
bash-4.4$ ruby -e 'd=0;loop{s=(1..9).map{" "*79};79.times{|i|s[(Math.sin((i+d)*Math::PI/16)*4+4.5)][i]=?x};puts"^[[H",s;d+=1}'
                      xxxxx                           xxxxx
                    xx     xx                       xx     xx
                  xx         xx                   xx         xx
                 x             x                 x             x
x               x               x               x               x
 x             x                 x             x                 x
  xx         xx                   xx         xx                   xx         xx
    xx     xx                       xx     xx                       xx     xx
      xxxxx                           xxxxx                           xxxxx

```

### Ruby: 115 characters

```
d=0
while 1
s=(1..9).map{" "*79}
79.times{|i|s[(Math.sin((i+d)*Math::PI/16)*4+4.5)][i]=?x}
$><<"\e[H"+s*$/
d+=1
end

```

The animation is displayed in the top left corner of the terminal and scrolls from right to left at full speed (add `sleep 0.1;` before the `end` keyword to slow it down).

Sample run:

```
                      xxxxx                           xxxxx
                    xx     xx                       xx     xx
                  xx         xx                   xx         xx
                 x             x                 x             x
x               x               x               x               x
 x             x                 x             x                 x
  xx         xx                   xx         xx                   xx         xx
    xx     xx                       xx     xx                       xx     xx
      xxxxx                           xxxxx                           xxxxx
bash-4.1$ ruby -e 'd=0;while 1;s=(1..9).map{" "*79};79.times{|i|s[(Math.sin((i+d)*Math::PI/16)*4+4.5)][i]=?x};$><<"\e[H"+s*$/;d+=1;end'

```

(I know, can be shortened by replacing `Math::PI/16` with its precalculated value of arbitrary precision. For example to 107 characters by using 0.2 multiplier. But the lower the precision, the uglier the output. May edit it in the future, I just keep it for now.)
> 3 votes

# Answer
# q

Quick and very ugly, 119 characters:

```
o:0;
w:.:["\\c"]1;
.z.ts:{-1@'{@[w#" ";where x=y;:;"0"]}[4-7h$4*sin o rotate(til w)%2*acos -1]'[til 9];o::o+1};
\t 100

```
> 3 votes

# Answer
# Processing, 99

Really just a butchered version of this.

```
float i,x,t;void draw(){clear();x=t+=0.02;for(i=0;i<75;ellipse(i++*5,50+sin(x+=0.418879)*25,3,3));}

```

Try it online!

Could've saved some characters at the cost of an uglier animation. Slightly more readable form:

```
float i,x,t;

void draw() {
    clear();
    x = t+=0.02;
    for(i=0; i<75; ellipse(i++*5, 50+sin(x+=0.418879)*25, 3, 3));
}

```

Magic numbers:

* `0.02` kinda affects the scroll speed
* `75` is the number of dots
* `5` is the distance on x-axis
* `50` is the y-position on screen (default window size is 100).
* `0.418879` ≈ 2π/75\*5
* `25` is the amplitude
* `3` is the size of the dots
> 3 votes

# Answer
## C (65)

```
main(int x){for(;;)printf("%*c\n",(int)(22+20*sin(x++/5.)),'x');}

```

Note: plots sine wave with X axis vertical and therefore scrolls vertically.
> 2 votes

# Answer
## Maple, 42 Characters

This is very easy to do with Maple.

```
plots[animate](plot,[sin(x+a)],a=0..2*Pi);

```

What it does
> 2 votes

# Answer
# TI-BASIC, 22 bytes

* Name this `prgmA`. It eventually overflows the stack by calling itself, throwing an `ERR:MEMORY`; this can be rectified in exchange for 4 bytes by adding `While 1` to the beginning and replacing the `prgmA` line with `End`.
* It works pretty much perfectly, although I'm afraid not much can be done to improve its speed.
* It's currently the winner by far, but can be 'golfed' to 18 bytes by removing the step argument (`,.01`) from the `For(` loop, lowering its "Number of periods displayed" score.

---

```
For(A,0,6,.01
ClrDraw
DrawF 7sin(X+A
End
prgmA

```
> 2 votes

# Answer
## JavaScript: 265 characters + 59 HTML

```
<canvas id=c width=99 height=99></canvas>
<script>
var c=document.getElementById("c");var context=c.getContext("2d");context.beginPath();var s=0;setInterval(function(){c.width=c.width;s++;context.moveTo(0+50,50*Math.sin(s+0)+50);for(var e=1;e<99;e++){context.lineTo(e+50,50*Math.sin(s+50*e)+50)}context.stroke()},50)
</script>

```

## JavaScript (ungolfed)

```
<canvas id="canvas" width="500" height="99"></canvas>
<script>
var c = document.getElementById("canvas");
var context = c.getContext("2d");
context.beginPath();
var s=0;
setInterval(function(){
    c.width = c.width;
    s++;
    context.moveTo(0+50,50*Math.sin(s+0)+50);
    for(var x=1;x<99;x++){
        context.lineTo(x+50, 50*Math.sin(s+50*x)+50);
    }
    context.stroke();
}, 50);
</script>

```

See it on http://jsfiddle.net/MartinThoma/uv5Xx/
> 1 votes

# Answer
# Processing, 115 chars

This one actually draws a pseudo-sine wave, not an actual sine wave:

```
int t,i,c;void draw(){clear();beginShape();for(i=-1,c=50;i<6;c=-c)curveVertex(50*i++-t,50+c);endShape();t=t%100+1;}

```

A more readable version:

```
int t, i, c;
void draw() {
  clear();
  beginShape();
  for(i=-1, c=50; i<6; c=-c)
    curveVertex(50*i++ - t, 50+c);
  endShape();
  t = t%100 + 1;
}

```
> 1 votes

# Answer
# Mathematica, 38 bytes

```
Animate[Plot[Sin[x+a],{x,0,10}],{a,5}]

```

Non-competeting, uses Mathematica 10
> 0 votes

# Answer
# SmileBASIC

The rules aren't entirely clear, so I'll post a few different answers:

## 34 bytes (vertical text):

```
LOCATE SIN(MILLISEC/9)*9+9,?.EXEC.

```

(It never specifically says this isn't allowed, but none of the other answers are vertical, so I'm not sure)

## 43 bytes (horizontal text):

```
LOCATE,SIN(MILLISEC/9)*9+9?0SCROLL-1,.EXEC.

```

## 53 bytes (horizontal graphics):

```
GPSET 1,SIN(MILLISEC/9)*9+9GCOPY.,0,#R,30,1,0,1
EXEC.

```
> 0 votes

---
Tags: code-golf, ascii-art, graphical-output
---


title: Sum of squares on GPU

text:
# Question
Title: Sum of squares on GPU
Write a program or function that:

1. Takes as input a list or array of 128 numbers.
2. Sends that array to a GPU
3. Performs a calculation on the GPU to square each element of the array and then sum them
4. Gets the answer from the GPU, and returns or displays it

So your program will simply return the sum of the squares of its input array, but it will perform the calculation on a GPU.

The input numbers should be sent to the GPU in the form of signed or unsigned integer types or floats, of 32 or more bits in size.

You may make any assumptions you like about hardware, e.g. you may assume a CUDA or OpenCl capable card is present without checking for it.

This is . The smallest code (in bytes) will be considered the winner for each language.

# Answer
# APL (Dyalog Unicode) with Co-dfns, 7 bytesSBCS

Anonymous prefix lambda. I have verified with the author of Co-dfns that the code will indeed run according to the required spec.

```
{+.×⍨⍵}

```

Try it online! (equivalent code, but TIO doesn't provide GPU access)

`{``}` compilable dfn;  is the argument vector

`+.×` dot-product of

itself ("selfie")

using the argument as data
> 2 votes

# Answer
# Processing.org 392 bytes

392 counting the shader and function

It's possible to reduce the number of characters by putting the shader program in a separate file.

```
String[] f={"uniform float x[128];void main(){float s;for(int i=0;i<128;i++)s+=x[i]*x[i];int b=floatBitsToInt(s);gl_FragColor=vec4(b>>16&255,b>>8&255,b&255,b>>24&255)/255.;}"},v={"uniform mat4 transform;in vec4 vertex;void main(){gl_Position=transform*vertex;}"};PShader p;void s(float[]i){p=new PShader(this,v,f);p.set("x",i,1);filter(p);loadPixels();print(Float.intBitsToFloat(pixels[0]));}
void setup(){
size(1,1,P2D);
float[] input = new float[128];
for(int i=0;i<128;i++)input[i]=(float)i;
s(input); // prints 690880.0
}

```
> 2 votes

---
Tags: code-golf
---


title: Formerly Composite Numbers

text:
# Question
Title: Formerly Composite Numbers
### Sequence Definition

Construct a sequence of positive integers `a(n)` as follows:

1. `a(0) = 4`
2. Each term `a(n)`, other than the first, is the smallest number that satisfies the following:
a) `a(n)` is a composite number,
b) `a(n) > a(n-1)`, and
c) `a(n) + a(k) + 1` is a composite number for each `0 <= k < n`.

So we start with `a(0) = 4`. The next entry, `a(1)` must be `9`. It can't be `5` or `7` since those aren't composite, and it can't be `6` or `8` because `6+4+1=11` is not composite and `8+4+1=13` is not composite. Finally, `9+4+1=14`, which is composite, so `a(1) = 9`.

The next entry, `a(2)` must be `10`, since it's the smallest number larger than `9` with `10+9+1=20` and `10+4+1=15` both composite.

For the next entry, `11` and `13` are both out because they're not composite. `12` is out because `12+4+1=17` which is not composite. `14` is out because `14+4+1=19` which is not composite. Thus, `15` is the next term of the sequence because `15` is composite and `15+4+1=20`, `15+9+1=25`, and `15+10+1=26` are all each composite, so `a(3) = 15`.

Here are the first 30 terms in this sequence:

```
4, 9, 10, 15, 16, 22, 28, 34, 35, 39, 40, 46, 52, 58, 64, 70, 75, 76, 82, 88, 94, 100, 106, 112, 118, 119, 124, 125, 130, 136

```

This is OEIS A133764.

### Challenge

Given an input integer `n`, output the `n`th term in this sequence.

### Rules

* You can choose either 0- or 1-based indexing. Please state which in your submission.
* The input and output can be assumed to fit in your language's native integer type.
* The input and output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# Husk, 11 bytes

```
!üȯṗ→+fotpN

```

1-indexed. Try it online!

## Explanation

```
!üȯṗ→+fotpN  Implicit input, a number n.
          N  The list of positive integers [1,2,3,4,..
      f      Keep those
         p   whose list of prime factors
       ot    has a nonempty tail: [4,6,8,9,10,12,..
 ü           De-duplicate wrt this equality predicate:
     +       sum
    →        plus 1
  ȯṗ         is a prime number.
             Result is [4,9,10,15,16,..
!            Get n'th element.

```
> 5 votes

# Answer
# JavaScript (ES6), 83 bytes

1-indexed

```
f=(n,a=[-1,p=4])=>a[n]||f(n,a.some(x=>(P=n=>n%--x?P(n):x<2)(x-=~p),p++)?a:[...a,p])

```

### Demo

```
f=(n,a=[-1,p=4])=>a[n]||f(n,a.some(x=>(P=n=>n%--x?P(n):x<2)(x-=~p),p++)?a:[...a,p])

for(n = 1; n <= 30; n++) {
  console.log('a(' + n + ') = ' + f(n))
}
```

### Commented

Helper function **P()**, returning **true** if **n** is prime, or **false** otherwise:

```
P = n => n % --x ? P(n) : x < 2

```

NB: It must be called with **x = n**.

Main function **f()**:

```
f = (               // given:
  n,                //   n = target index
  a = [-1, p = 4]   //   a = computed sequence with an extra -1 at the beginning
) =>                //   p = last appended value
  a[n] ||           // if a[n] exists, stop recursion and return it
  f(                // otherwise, do a recursive call to f() with:
    n,              //   n unchanged
    a.some(x =>     //   for each value x in a[]:
      P(x -= ~p),   //     rule c: check whether x + p + 1 is prime
                    //     rule a: because a[0] = -1, this will first compute P(p)
      p++           //     rule b: increment p before the some() loop starts
    ) ?             //   end of some(); if truthy:
      a             //     p is invalid: use a[] unchanged
    :               //   else:
      [...a, p]     //     p is valid: append it to a[]
  )                 // end of recursive call

```
> 2 votes

# Answer
# Perl 6, 70 bytes

```
{(4,->+_{first {none($^a X+0,|(_ X+1)).is-prime},_.tail^..*}...*)[$_]}

```

Try it 0-indexed

## Expanded:

```
{  # bare block lambda with implicit parameter $_

  (  # generate the sequence

    4, # seed the sequence

    -> +_ { # pointy block that has a slurpy list parameter _ (all previous values)

      first

      {  # bare block with placeholder parameter $a

        none(                 # none junction
            $^a               # placeholder parameter for this inner block
          X+
            0,                # make sure $a isn't prime
            |( _ X+ 1 )       # check all a(k)+1
        ).is-prime            # make sure none are prime
      },

      _.tail ^.. *            # start looking after the previous value
    }

    ...                       # keep generating values until

    *                         # never stop

  )[$_]                       # index into the sequence
}

```
> 2 votes

# Answer
# Python 2, ~~112~~ 107 bytes

thanks to Mr. Xcoder for a byte.

```
n=-1,4;v=5
exec"while any(all((v-~k)%i for i in range(2,v))for k in n):v+=1\nn+=v,;v+=1\n"*input()
print~-v

```

Try it online!

---

# Python 2, ~~115~~ 109 bytes

```
n=-1,4;v=4;x=input()
while x:v+=1;k=1^any(all((v-~k)%i for i in range(2,v))for k in n);n+=(v,)*k;x-=k
print v

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 21 bytes

0-indexed

```
®4Iµ)˜D¤N‹sN+>p_P*iN¼

```

Try it online!
> 1 votes

# Answer
# C (gcc),  ~~140~~  138 bytes

*Thanks to @Jonathan Frech for saving two bytes!*

```
c(n,i){for(i=1;++i<n;)i=n%i?i:n;i=i>n;}f(n){int s[n],k,j,i=0;for(*s=k=4;i++-n;i[s]=k)for(j=!++k;j-i;)2-c(k)-c(k-~s[j++])?j=!++k:f;n=n[s];}

```

0-indexed

Try it online!
> 0 votes

# Answer
# Ruby \+ `-rprime`, ~~85~~ 75 bytes

```
->n{*a=x=4
n.times{x+=1;!x.prime?&&a.none?{|k|(x+k+1).prime?}?a<<x:redo}
x}

```

Try it online!

A lambda returning the 0-indexed nth element.

-10 bytes: Use `redo` and a ternary operator instead of `loop`...`break` and a conditional chain

Ungolfed:

```
->n{
  *a=x=4                         # x is the most recent value: 4
                                 # a is the list of values so far: [4]
  n.times{                       # Repeat n times:
    x += 1                       # Increment x
    !x.prime? &&                 # If x is composite, and
      a.none?{|k|(x+k+1).prime?} #   for all k, a(n)+x+1 is composite,
      ? a<<x                     # Add x to a
      : redo                     # Else, restart the block (go to x+=1)
  }
  x                              # Return the most recent value
}

```
> 0 votes

# Answer
# Wolfram Language (Mathematica), 65 bytes

```
±0=-1;±1=4;±n_:=±(n-1)+1//.a_/;PrimeQ/@Array[a+1+±#&,n,0,Or]:>a+1

```

Uses CP-1252 (default Windows) encoding. 1-indexed.

Try it online!
> 0 votes

# Answer
# Java 8, ~~186~~ 173 bytes

```
n->{int a[]=new int[n+1],r=a[n]=4;a:for(;n>0;)if(c(++r)<2){for(int x:a)if(x>0&c(r-~x)>1)continue a;a[--n]=r;}return r;}int c(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}

```

0-indexed.
Unfortunately prime-checks (or anti-prime/composite checks in this case) aren't that cheap in Java..

**Explanation:**

Try it online.

```
n->{                     // Method with integer as both parameter and return-type
  int a[]=new int[n+1],  //  Integer-array of size `n+1`
      r=a[n]=4;          //  Start the result and last item at 4
  a:for(;n>0;)           //  Loop as long as `n` is larger than 0
    if(c(++r)<2){        //   Raise `r` by 1, and if it's a composite:
      for(int x:a)       //    Inner loop over the array
        if(x>0           //     If the item in the array is filled in (non-zero),
           &c(r-~x)>1)   //     and if `r+x+1` is a prime (not a composite number):
          continue a;}   //      Continue the outer loop
      a[--n]=r;}         //    Decrease `n` by 1, and put `r` in the array
  return r;}             //  Return the result

// Separated method to check if a given number is a composite number
// (It's a composite number if 0 or 1 is returned, otherwise it's a prime.)
int c(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}

```
> 0 votes

# Answer
# C (gcc), 170 bytes

```
P(n,d,b){for(b=d=n>1;++d<n;)b=b&&n%d;n=b;}h(n,N,b,k){if(!n)return 4;for(b=N=h(n-1);b;)for(b=k=!N++;k<n;b|=P(h(k++)-~N));n=N;}f(n,j){for(j=0;n--;)if(P(h(++j)))j++;n=h(j);}

```

Try it online!
> 0 votes

---
Tags: code-golf, sequence, primes
---


# Question
Title: Simplify and Take Partial Derivative to a Polynomial String
# Introduction

Write a program to calculate the partial derivative of a polynomial (possibly multivariate) with respect to a variable.

# Challenge

Derivatives are very important mathematical tools that has been widely applied in physics, chemistry, biology, economics, psychology and more to handle all kinds of problems. Expressions with multiple variables are also very common.

In the scope of this challenge, a polynomial string ("polystr") is defined by the following BNF (Backus–Naur form):

```
<polystr> ::= <term> | <term><plusminus><polystr>

<plusminus> ::= "+" | "-"

<term> ::= <coeff> | <coeff><baseterm> | <baseterm>

<baseterm> ::= <variable> | <variable><exponent> | <baseterm><baseterm>

<coeff> ::= positive_integer

<exponent> ::= positive_integer

<variable> ::= lowercase_ASCII_letters

```

Where `positive_integer` and `lowercase_ASCII_letters` are quite self-explanatory.

For example, The string `3x2y-x3y-x2y+5` means `3*(x^2)*y-(x^3)*y-(x^2)*y+5`. The terms given in the input may appear in any order, and the variables in each term also may appear in any order. So for example `5-yx2-x3y+y3x2` is also a valid input and is in fact the same as the previous example.

The rule for taking partial derivative is just doing it term by term. If the variable appears does not appear in the term, the derivative is zero. Otherwise, the coefficient of the term is multiplied by the exponent of that variable, and then the exponent of the variable is decreased by one. The exponents for other variables do not change. This is just following the definition in mathematics. In addition, if the resulting exponent is zero, remove the variable from the term.

For example, to take the partial derivative of `5z-z2y2-5w3y` with respect to `y`. The following process is done (in accordance with the BNF defined above, the "coefficient" are all taken to be positive numbers, i.e. the signs are considered separately)

```
          5z          -   z2y2        - 5w3y

Coeff                 1->1*2=2      5->5*1=5
Expon                 2->2-1=1      1->1-1=0
Term                  -   2yz2         - 5w3
      (y is not here            (expon 0->y removed)
     so the term is 0)

```

The result is `-2yz2-5w3y`.

On the other hand, if the above expression is taken partial derivative with respect to `a`, the result is `0` because `a` is in none of the terms.

Your task is to write a function or a full program to calculate this derivative. It should take a polynomial string and a single character (the variable to take derivative with respect to), and return the derivative in the simplest form.

"Simplest form" means three things.

1. The number `0` (not the digit) should not appear in the output unless the output itself is just `0`. So neither `0+10y` nor `3-y0z` will be valid output and should be transformed to `10y` and `3-z`, respectively.
2. The number `1` should not appear as an exponent or a coefficient, but can appear as a standalone term itself.
3. The terms with exactly the same set of variables and exponents should be merged, which means `3a2b5-4b5a2` is not a valid output, and it should be `-a2b5` instead. More information about the input and output can be found in the "Specs" section.

# Test Cases

```
Input
Output

2xy+4ax-5+7mx4-4-7x4m, x
2y+4a

4upv+5u2v3w4-4w4u2v3+qr-v,v
4up+3u2v2w4-1

12ux-7x2m3+ab5,q
0

-a+10ca11y-1nv3rt3d-poly, a
-1+110ca10y

1y+1x3y, y
1+x3

```

# Specs

* Input can be taken through standard forms. In other words, you can take input as a string, a list of characters, a nested array of coefficients, variables (possibly denoted by their ASCII value minus 'a' or something alike) and exponents, etc. You are also free to change the string to `2*x^3y^2` or alike instead of `2x3y2`.

However, please do not use the input `[2,0,0,0,1,0,0,3,0,0,...0]` (an array of 27 elements) for the term `2dg`, or any other verbose format that enumerates the 26 letters like this. Your input format should also be able to treat `ab` and `ba` as different inputs (so the 27-element array format is invalid due to this restriction as well).

* Each variable (letter) will only appear once in each term of the input, that means `xx` will not appear and will always be presented as `x2`, nor will something like `a3b4a2` appear.
* To reiterate, the terms in the input may appear in any order.
* You are also free to choose the output format provided that the verbose format mentioned above is avoided. The output should however always be in the simplest form as defined above. Just like the input, the terms in the output can appear in any order, and the variables in each term can also appear in any order and does not have to be consistent between terms. That means `pu+2up2` is a valid output. The sign for the leading term can be either positive or negative and `-y+3x` and `3x-y` are both valid, so is `+3x-y`.
* The input are always given such that all the coefficients and exponents in the output will be less than 232-1, or the largest integer your language can handle, whichever is smaller. Claiming that the largest integer your language can handle is unreasonably small and trivializing the challenge falls into the category of default loopholes.
* This is , the lowest number of bytes wins.
* As usual, default loopholes apply here.

**Edit:** Since most of the answers so far turn out to be internals that do the whole challenge, and despite knowing there are builtins I don't have the intention to ban such internals from the very beginning, nor do I have now. I will make the winning criteria one that is based on a per-language basis, i.e. the submission with the least bytes in each language wins in that language. I will add a standard snippet for a catalogue if there are enough submissions. Feel free to go on submitting builtins to showcase the power of your language but please do not hesitate to submit your non-builtin answers even if it's way longer and your language does not have a builtin. Happy code golfing in your favorite language!

# Answer
> 2 votes
# Python 2, ~~252~~ 245 bytes

```
o,d=input()
D={};s=''
for c,t in o:T=`sorted(t)`;D[T]=D.get(T,0)+c
for t in D:
 c,t=D[t],dict(eval(t))
 if(d in t)*c:e=t[d];c*=e;t[d]=e-1;s+=('%+d '%c)[:~((-2<c<2)*sum(t.values())>0)]+''.join((v+`t[v]`*(t[v]>1))*(t[v]>0)for v in t)
print s or'0'

```

Try it online!

Takes input as a nested list of coefficients and terms:

```
[
 [coeff1, [[var1_1,exp1_1],
           [var1_2,exp1_2],
           ... ]
 ],
 [coeff2, [[var2_1,exp2_1], ...]],
 ...
]

```

For instance the first example (`5z-z2y2-5w3y`) is given as:

```
[
 [ 5, [['z', 1]          ] ],
 [-1, [['z', 2], ['y', 2]] ],
 [-5, [['w', 3], ['y', 1]] ]
]

```

The footer contains a function which parses a string input to the desired input format: `parse(s)`.

---

Edit:

* Takes input instead of function

# Answer
> 2 votes
# Retina, ~~249~~ 233 bytes

```
(.)(?=.*¶\1$)
$&_
L`.\w*
G`_
^\b
+
%O`._?\d*
_\d+
*
\b[a-z]
1$&
\b(\d+)(?=.*?(_+))
$1*$2
O$`(.)_+(.+)
$2$1
+`((\+|-)_+)(.*)¶\2(_+\3)\b
$1$4
+`\+_(_*(.*)¶-)_(_*\2\b)
+$1$3
G`\b_
\b_+
$.&
_(__+)
$.1
^\+|¶|(.)__|._
$1
\b1([a-z])
$1
^$
0

```

Try it online! Link includes test cases. Explanation:

```
(.)(?=.*¶\1$)
$&_

```

Add a `_` after each occurence of the given variable.

```
L`.\w*

```

Split the input into terms.

```
G`_

```

Keep only the terms that referenced the variable.

```
^\b
+

```

Prefix a `+` if the first term doesn't have a sign.

```
%O`._?\d*

```

Sort each term alphabetically. (The sign matches, but that's not a problem; it sorts at the start anyway.)

```
_\d+
*

```

Convert all exponents of the variable into unary.

```
\b[a-z]
1$&

```

Temporarily prefix 1 to those terms without a multiplier.

```
\b(\d+)(?=.*?(_+))
$1*$2

```

Multiply the multiplier by the exponent of the variable, leaving the result in unary.

```
O$`(.)_+(.+)
$2$1

```

Sort all of the terms.

```
+`((\+|-)_+)(.*)¶\2(_+\3)\b
$1$4

```

Add terms of the same sign.

```
+`\+_(_*(.*)¶-)_(_*\2\b)
+$1$3

```

Subtract terms of different signs.

```
G`\b_

```

Remove terms that were cancelled by a term of a different sign.

```
\b_+
$.&

```

Convert the multiplier back to decimal.

```
_(__+)
$.1

```

Decrement exponents greater than three and convert back to decimal.

```
^\+|¶|(.)__|._
$1

```

a) Remove a leading `+` sign b) Join all the terms back together c) convert squares of the variable to the plain variable d) remove the variable if it didn't have an exponent.

```
\b1([a-z])
$1

```

Remove the temporary 1 unless it's no longer got anything to multiply.

```
^$
0

```

If there were no terms left then the result is zero.

Supporting duplicate terms cost almost half of my byte count. Previous 123 byte solution that didn't deduplicate terms:

```
(.)(?=.*¶\1$)
$&_
L`.\w*
G`_
_\d+
*
\b[a-z]
1$&
\b(\d+)(?=.*?(_+))
$.($1*$2
_(__+)
$.1
^\+|¶|(.)__|._
$1
\b1([a-z])
$1
^$
0

```

Try it online! Explanation:

```
(.)(?=.*¶\1$)
$&_

```

Add a `_` after each occurence of the given variable.

```
L`.\w*

```

Split the input into terms.

```
G`_

```

Keep only the terms that referenced the variable.

```
_\d+
*

```

Convert all exponents of the variable into unary.

```
\b[a-z]
1$&

```

Temporarily prefix 1 to those terms without a multiplier.

```
\b(\d+)(?=.*?(_+))
$.($1*$2

```

Multiply the multiplier by the exponent of the variable.

```
_(__+)
$.1

```

Decrement exponents greater than three and convert back to decimal.

```
^\+|¶|(.)__|._
$1

```

a) Remove a leading `+` sign b) Join all the terms back together c) convert squares of the variable to the plain variable d) remove the variable if it didn't have an exponent.

```
\b1([a-z])
$1

```

Remove the temporary 1 unless it's no longer got anything to multiply.

```
^$
0

```

If there were no terms left then the result is zero.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 21 20 bytes

-1 byte thanks to Jonathan Frech!

```
ToExpression@#~D~#2&

```

Try it online!

The input is formatted so that every term follows `coeff * var1 ^ exp1 * var2 ^ exp2 ...`. If the input can be taken as an expression rather than a string, the solution is 1 byte: `D`.

# Answer
> 0 votes
# Physica, 3 bytes

This doesn't use any new feature.  and its ASCII-only alternative, `Differentiate` have been introduced more than 10 days ago.

# Demo

Assumes that both the expression and the variable are passed as a string. Testing code:

```
f = ∂

Print[f['2*x*y+4*a*x-5+7*m*x^4-4-7*x^4*m'; 'x']]
Print[f['4*u*p*v+5*u^2*v^3*w^4-4*w^4*u^2*v^3+q*r-v'; 'v']]
Print[f['-a+10*c*a^11*y-1*n*v^3*r*t^3*d-p*o*l*y'; 'a']]

```

Exact output:

```
4*a + 2*y
4*p*u + 3*u**2*v**2*w**4 - 1
110*a**10*c*y - 1

```

Expression format: `*` for multiplication, `**` for exponentiation, `+` and `-` for addition and subtraction accordingly.

# Answer
> 0 votes
# Python 3 \+ SymPy, 23 bytes

```
from sympy import*
diff

```

Try it online!

# Answer
> 0 votes
# Pari/GP, 5 bytes

```
deriv

```

Try it online!

---
Tags: code-golf, string, polynomials, calculus
---