# Question
Title: "Hello, World!" (Every other character, Part 2)
As a kind of part 2 to Hello, World! (Every other character), write a program such that **all three** of these programs print "Hello, World!": the entire program, the 1st, 3rd, 5th, etc. characters of your program, *and* the 2nd, 4th, 6th, etc.

If your program is:

```
abc
def

```

It should output "Hello, World!", but so should

```
acdf

```

**And**

```
b
e

```

No solutions with built-in "Hello, World!"s.

# Answer
# x86 machine code, 378 bytes

**PROG.COM** Download and run it in **MS-DOS** emulator, DOSBox for example.

```
B3 B4 B3 02 90 B3 B3 B4 02 B3 B4 B3 02 90 B3 B2
B3 48 90 B3 B3 B2 48 B3 B2 B3 48 90 B3 CD B3 21
90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 65 90 B3
B3 B2 65 B3 B2 B3 65 90 B3 CD B3 21 90 B3 B3 CD
21 B3 CD B3 21 90 B3 B2 B3 6C 90 B3 B3 B2 6C B3
B2 B3 6C 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3
21 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90
B3 B2 B3 6F 90 B3 B3 B2 6F B3 B2 B3 6F 90 B3 CD
B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 2C
90 B3 B3 B2 2C B3 B2 B3 2C 90 B3 CD B3 21 90 B3
B3 CD 21 B3 CD B3 21 90 B3 B2 B3 20 90 B3 B3 B2
20 B3 B2 B3 20 90 B3 CD B3 21 90 B3 B3 CD 21 B3
CD B3 21 90 B3 B2 B3 77 90 B3 B3 B2 77 B3 B2 B3
77 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90
B3 B2 B3 6F 90 B3 B3 B2 6F B3 B2 B3 6F 90 B3 CD
B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 72
90 B3 B3 B2 72 B3 B2 B3 72 90 B3 CD B3 21 90 B3
B3 CD 21 B3 CD B3 21 90 B3 B2 B3 6C 90 B3 B3 B2
6C B3 B2 B3 6C 90 B3 CD B3 21 90 B3 B3 CD 21 B3
CD B3 21 90 B3 B2 B3 64 90 B3 B3 B2 64 B3 B2 B3
64 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90
B3 B2 B3 21 90 B3 B3 B2 21 B3 B2 B3 21 90 B3 CD
B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 CD B3 20
90 B3 B3 CD 20 B3 CD B3 20 90

```

Also you can download LEFT.COM and RIGHT.COM

## How it works and how to run

See answer to part one

## Magic

If you want to execute **0xAB** opcode command with one parameter **0xCD**, you write

## Generator

Run code, get hex. Convert in to binary

```
cat prog.hex | xxd -r -p > PROG.COM

```

```
function byte2hex(byte){
 var ret=byte.toString(16).toUpperCase();
 return ret.length==1 ? "0"+ret : ret;
}

function str2hex(str){
 var ret = [];
 for(var i=0;i<str.length;i++){
  ret.push(byte2hex(str.charCodeAt(i)));
 }
 return ret;
}

function genCode(hexArr){
 var ret = [["B4","02"]];
 for(var i=0;i<hexArr.length;i++){
  if(hexArr[i]!=hexArr[i-1]){
   ret.push(["B2",hexArr[i]]);
  }
  ret.push(["CD","21"]);
 }
 ret.push(["CD","20"]);

 return ret;
}

function format(arr){
 var ret=[],tmp=[];
 for(var i=0;i<arr.length;i++){
  tmp.push(arr[i]);
  if(i%16==15 || i==arr.length-1){ret.push(tmp.join(" "));tmp=[];}
 }
 return ret.join("\n");
}

function magicCode(str,mode){
 var ret=[];
 var code=genCode(str2hex(str));

 for(var i=0;i<code.length;i++){
  var ab=code[i][0],cd=code[i][1],tmp;
  tmp=["B3",ab,"B3",cd,"90","B3","B3",ab,cd,"B3",ab,"B3",cd,"90"];
  for(var j=0;j<tmp.length;j++){
   if((mode&1 && j%2==0) || (mode&2 && j%2==1)){ret.push(tmp[j])}
  }

 }
 return ret;
}

const LEFT=1,RIGHT=2,ALL=3;

var str=prompt("string","Hello, world!");

var out = ["PROG.COM\n",format(magicCode(str,ALL)),"\n\nLEFT.COM\n",format(magicCode(str,LEFT)),"\n\nRIGHT.COM\n",format(magicCode(str,RIGHT))].join("\n");

document.write(out.replace(/\n/ig,"<br>"));
```
> 24 votes

# Answer
# Python 3, 115 bytes

```
print=="partisn't";
"ran" >="partisn't" ;
print((""" "HHeelllloo,,  wwoorrlldd!! """[" ) #2">"1":: 3- 1] [ 1:-1 ]))

```

### Every odd character

```
pit=print;"a">"ats'";pit(" Hello, world! "[  2>1: -1  :1])

```

### Every even character

```
rn="ats'"
rn =print
rn("""Hello, world!""")#""":3 ][1- )

```

Try it online!

This could probably get a lot shorter, but I'm happy I managed to get it to work in Python. Similar to vroomfondel's answer on the first part.

# Boring 93 byte answer

```
""""""
print("Hello, world!")
""""""#
""""

pprriinntt((""HHeelllloo,,  wwoorrlldd!!""))
#"""

```

### Every odd character

```
"""pit"el,wrd"
"""
""
print("Hello, world!")#"

```

### Every even character

```
"""
rn(Hlo ol!)"""#""
print("Hello, world!")
""

```

Try it online!
> 14 votes

# Answer
# \>\<\>, 45 bytes

```
! """!!ddllrrooWW  oolllleeHH"!!"" >~o <> o <

```

Or just even characters:

```
 "!dlroW olleH"!">o<

```

Or just odd characters:

```
!""!dlroW olleH!" ~ >o<

```

Try them online: original, evens, odds.

The original version pushes "`!!ddllrrooWW oolllleeHH`" to the stack, then the fish bounces between `>~o <`, which deletes a letter, prints two, deletes two, prints two, deletes two, etc. The two half-programs are fairly standard string printing programs. The tricky part was combining `"` and `!` to toggle in and out of string mode in all three programs correctly.
> 9 votes

# Answer
## Befunge-98, 43 bytes

```
120 x""!!ddllrrooWW  ,,oolllleeHH""cckk,,@@

```

Try it online!

Only the odd ones:

```
10x"!dlroW ,olleH"ck,@

```

Try it online!

Only the even ones:

```
2 "!dlroW ,olleH"ck,@

```

Try it online!

### Explanation

The full program:

```
120               Push 1, push 2, push 0.
x                 Pop 0 (y) and 2 (x) and set the instruction pointer's movement
                  delta to (x,y). That is, run the remainder of the code
                  by skipping every other cell.
"!dlroW ,olleH"   Push the code points of the output.
ck,               Print 13 characters from the top of the stack.
@                 Terminate the program.

```

In the odd program, the `2` is gone, so that `10x` really does nothing at all (it sets the delta to `(1,0)` which is the default anyway). The remainder of the program is then the same.

In the even program, we just push the `2` at the beginning which we can ignore entirely. The remainder of the program is the same as before.
> 7 votes

# Answer
# Gammaplex, 46 bytes

```
//

EERRrrXXXX""HHeelllloo,,  WWoorrlldd!!""XX

```

See here.

Interpreter. It may need some changes to work in modern compilers.
> 6 votes

# Answer
# Mathematica, 65 bytes

```
PPrriinntt[[""HHeelllloo,,  WWoorrlldd!!""]]Print@"Hello, World!"

```

It throws some warnings, prints `Hello, World!`, and returns `Null PPrriinntt[["" HHeelllloo, Null, "" WWoorrlldd!!]]`. When run as a program (not in the REPL), the return value will not be printed.

After removing the even characters:

```
Print["Hello, World!"]Pit"el,Wrd"

```

It prints `Hello, World!`, and returns `"el,Wrd" Null Pit`.

After removing the odd characters:

```
Print["Hello, World!"]rn@Hlo ol!

```

It prints `Hello, World!`, and returns `Null ol! rn[Hlo]`.
> 5 votes

# Answer
## x86 machine code, 73 bytes

Inspired by *Евгений Новиков*'s solution, I thought it should be doable with less tricks, i.e., just jumping around to otherwise "disjoint" codes for all three variants. I'm still trying with a smart variant that uses `lodsb; lodsb` as central point (so only one string constant is needed for all variants)

```
EB 14 00 00 8A 8A 17 16 01 01 B4 B4 09 09 CD CD
21 21 CD CD 20 20 8A 1f 01 B4 09 CD 21 CD 20 48
65 6c 6c 6f 2c 20 57 6f 72 6c 64 21 00 48 48 65
65 6c 6c 6c 6c 6f 6f 2c 2c 20 20 57 57 6f 6f 72
72 6c 6c 64 64 21 21 00 00

```

If I recall correctly from my childhood days, COM's tiny model starts with `DS=CS=SS` and the code is loaded beginning from `CS:0100h`. I do not assume it is guaranteed that the code is loaded into a zeroed memory block (if it were guaranteed, I could drop two bytes).

Disassembly of the long code should be

```
  JMP *+14h
  ; 20 irrelevant bytes
  MOV DX,message
  MOV AH,09h
  INT 21h;  print string pointed to by DS:DX
  INT 20h;  exit program
message:
  DB "Hello, World!\0"
  DB "HHeelllloo,,  WWoorrlldd!!\0\0"

```

Disassembly of odd code

```
  JMP *+00h
  MOV DX,message
  MOV AH,09h
  INT 21h;  print string pointed to by DS:DX
  INT 20h;  exit program
  ; some irrelevant bytes
message:
  DB "Hello, World!\0"

```

Disassembly of even code:

```
  ADC AL,00h
  MOV DX,message
  MOV AH,09h
  INT 21h;  print string pointed to by DS:DX
  INT 20h;  exit program
  ; some irrelevant bytes
message:
  DB "Hello, World!\0"

```
> 5 votes

# Answer
## Retina, 48 bytes

```
G |`

HHeelllloo,,  WWoorrlldd!!
$_&

(.)\1t?
$1

```

Try it online!

Odd positions:

```
G|
Hello, World!
_
()1?$

```

Try it online!

Even positions:

```
 `
Hello, World!$&
.\t
1

```

Try it online!

### Explanation

**The full program:**

```
G |`

```

This does nothing at all. The `|` is not an existing configuration option. The `G` makes this a grep stage, but there is really nothing to be grepped and the regex is empty any, so this doesn't do anything. The purpose of this stage is to have two linefeeds in front of the main "Hello, World!" line so that one of them always survives the reduction. The reason for making this a grep stag is that we need to offset the parity of the lines, and grep stages only require a single line.

```

HHeelllloo,,  WWoorrlldd!!

```

This turns the (empty) working string into the required output with each character doubled.

```
$_&

```

This does nothing. The regex tries to match a `_` and a `&` after the end of the string which is of course impossible. We'll need those characters in the reduced version though, again to deal with vanishing linefeeds.

```
(.)\1t?
$1

```

Finally, we remove the duplicate characters by replacing `(.)\1` with `$1`. The `t?` is never used but will again be necessary in the reduced versions.

**The odd program:**

```
G|
Hello, World!

```

The `G` can't match the empty input, but that's why we have the `|` to allow an alternative empty match. This turns the empty working string into the desired output.

```
_
()1?$

```

This replaces underscores with `()1?$`, but there are no underscores in the string, so this does nothing.

**The even program:**

```
 `
Hello, World!$&

```

The ``` just denotes an empty configuration string, so we again use the empty regex to replace the working string with the output. This time we also insert `$&` but that's the match itself, which is empty, of course, so it doesn't do anything.

```
.\t
1

```

This would replace any character followed by a tab with a `1`, but we don't have any tabs, so this is also a no-op.
> 4 votes

# Answer
# Lua, 106 bytes

```
----[[[[
print("Hello, World!")
--[[
---- ] ]
---- ] ]
pprriinntt((""HHeelllloo,,  WWoorrlldd!!""))
----]]

```

Try it online!

Alternate 1:

```
--[[
rn(Hlo ol!)-[
--]]--
print("Hello, World!")--]

```

Try it online!

Alternate #2:

```
--[[pit"el,Wrd"
-[--
--]]print("Hello, World!")
--]

```

Try it online!

Alternator script: Try it online!
> 4 votes

# Answer
# CJam, 44 bytes

```
{{HHeelllloo,,  WWoorrlldd!!}}ss{{}}ss-X)%L-

```

Try it online!
> 3 votes

# Answer
# Backhand, 36 bytes

```
vv^^vv""!!ddllrrooWW  ,,oolllleeHH""

```

Try it online!

Every other character (in both ways):

```
v^v"!dlroW ,olleH"

```

Try it online!

### How it works

Backhand's IP starts at the first character and bounces back and forth, skipping certain number of steps at once. The initial step size is 3, which can be adjusted with `^` (increase) and `v` (decrease) commands.

```
vv^^vv""!!ddllrrooWW  ,,oolllleeHH""
v                                     decrease step size to 2
  ^                                   increase step size to 3
     v                                decrease step size to 2
       " ! d l r o W   , o l l e H "  push the string
                                 H    halt and print the string

v^v"!dlroW ,olleH"
v                   decrease step size to 2
  v                 decrease step size to 1
   "!dlroW ,olleH"  push the string
                H   halt and print the string

```
> 3 votes

# Answer
# PHP, 70 bytes

```
"";echo'Hello, World!'.""//pprriinntt''HHeelllloo,,  WWoorrlldd!!''
;;

```

Odd characters:

```
";coHlo ol!."/print'Hello, World!';

```

Even characters:

```
"eh'el,Wrd'"/print'Hello, World!'
;

```
> 2 votes

# Answer
# Haskell, 92 bytes

```
{---- }

mmaaiinn==ppuuttSSttrr""HHeelllloo,,  WWoorrlldd!!""----}main=putStr"Hello, World!"

```

Try it online! It looks like the comment abuse is too much for the syntax highlighting to handle. `{- ... -}` is an inline or multi-line comment, whereas `--` starts a line comment.

**Odd characters:**

```
{--}
main=putStr"Hello, World!"--mi=uSrHlo ol!

```

Try it online!

**Even characters:**

```
--
main=putStr"Hello, World!"--}anptt"el,Wrd"

```

Try it online!
> 2 votes

# Answer
# Zsh, 54 bytes

```
<<<Hello\ world!||eecchhoo  HHeelllloo\\  wwoorrlldd!!

```

Try it online!

The main program executes the first statement successfully, so the statement after the boolean `||` is ignored.

For odd/even, the `<<<Hello\ world!` becomes either an unterminated `<<heredoc` or a `<file` provided on stdin. Either way, the `||` becomes `|`, and so whatever is output by the first command is piped into and ignored by `echo`.
> 2 votes

# Answer
## LOGO, 71 bytes

```
;;\\
pr[Hello, World!]er "|

pprr[[HHeelllloo,,  WWoorrlldd!!]]
;;\\
|

```

(the program have a trailing newline)

Two removed versions:

```
;\p[el,Wrd]r"
pr[Hello, World!]
;\|

```

and

```
;\
rHlo ol!e |
pr[Hello, World!];\

```

(the program have a trailing newline)

For an explanation what `pr` and `er` do, see this post. In this case, `er` is feed with a word determine procedure name.

The `\` is escape character in Logo, which will escape the newline after the end of the comment, therefore make the second line (`rHlo ol!e |`) of second removed program a comment.
> 1 votes

# Answer
# Javascript,68 bytes

```
//**
alert`Hello, World`//**//aalleerrtt``HHeelllloo,,  WWoorrlldd``

```

Odd Characters:

```
/*aetHlo ol`/*/alert`Hello, World`

```

Even Characters:

```
/*
lr`el,Wrd/*/alert`Hello, World`

```

Modified version of my answer on the other one.
> 1 votes

# Answer
## Perl 5, 61 bytes

**60 bytes code + 1 for `-p`.**

```
$ _ =$ _ =q";HHeelllloo,,  WWoorrlldd!!";;;q##;s/;|.\K.//g##

```

Try it online!

### Every Odd Byte

```
  $_="Hello, World!";q#s;.K/g#

```

Try it online!

### Every Even Byte

```
$_=  q;Hello, World!;;#;/|\./#

```

Try it online!
> 1 votes

# Answer
# BotEngine, ~~180~~ 178 bytes

Based on my answer to this question.

```
 vv
 v <
 eHH
 eee
 ell
 ell
 eoo
 e,,
 e
 eWW
 eoo
 err
 ell
 edd
 e!!

>>P          e     e     e     e     e     e     e     e     e     e     e     e     e P

```

Odd characters (note the multiple trailing spaces on the last line):

```
 v
v<
eH
ee
el
el
eo
e,
e
eW
eo
er
el
ed
e!
>P

```

Even characters:

```
v     H  e  l  l  o  ,     W  o  r  l  d  !
>     e  e  e  e  e  e  e  e  e  e  e  e  eP

```
> 1 votes

# Answer
# Runic Enchantments, 52 bytes

```
 L @""H!edlllroo,W  W,oorlllde!H"" ~@"!dlroW ,olleH"

```

Try it online!

Runic is not usually very good at dealing with radiation as having flow control characters removed at random makes tracing execution a huge pain, but predictable radiation like every other character? Easy, we just encode two programs that are reversed of each other and interleaved, then tack on a third copy for the base execution and control which one is executed with a single character. In program 2, the third copy is garbage that's never seen, and in program 3 it retains the quotes, allowing it to be popped without printing it.

Program 1 only executes this part:

```
 L                                  @"!dlroW ,olleH"

```

Program 2 only executes this part:

```
    " H e l l o ,   W o r l d ! "   @

```

Like this:

```
  "Hello, World!" @!lo olH

```

Try it online!

Program 3 only executes this part:

```
 L @ " ! d l r o W   , o l l e H " ~ " d r W , l e "

```

Like this:

```
L@"!dlroW ,olleH"~"drW,le"

```

Try it online!

The `"drW,le"` portion is executed, but the `~` immediately pops it off the stack, preserving the desired output.

Naively it would appear that a conversion of the \>\<\> answer would result in a shorter program, weighing in at 45 bytes:

<pre><code>! ```!!ddllrrooWW  oolllleeHH`!!`` R~$ LR $ L
</code></pre>

However, Runic has one limitation that \>\<\> does not have: a maximum stack size of 10 + IP's mana (which is initially 10). And `!!ddllrrooWW oolllleeHH` contains 24 characters, causing the IP to bleed mana until it expires just before executing the `R` command, resulting in no output for the base program.

Try it online!
> 0 votes

# Answer
# Vyxal, 33 bytes

```
\` ð`HHeelllloo,,  WWoorrlldd!!`√

```

Try it Online!

```
`ðHello, World!`

```

Try it Online!

```
\ `Hello, World!√

```

Try it Online!

These all exploit the bug/feature that single special characters in strings are ignored during parsing.

```
\`                                # Push a backtick (useless)
   ð                              # Push a space (useless)
    `HHeelllloo,,  WWoorrlldd!!`  # String literal
                                √ # Get every second character

```

```
` Hello, World!` # String literal
 ð               # Single non-ascii character (ignored)

```

```
\                 # Push a space
  `Hello, World!  # String literal (unterminated)
                √ # Single non-ascii character - ignored

```
> 0 votes

---
Tags: code-golf, source-layout, hello-world
---


title: The repetitive byte counter

text:
# Question
Title: The repetitive byte counter
Your task is to write a non-empty program / function of byte count **L**, which, when repeated **M** times, checks whether a given positive integer **N** is equal to **L × M**.

You should, in theory, support an arbitrary number of repetitions (an arbitrary positive integer value of **M**), but it's fine if, due to language limitations, it cannot work over a certain threshold. Reading the source code of your program or accessing information about it is **strictly forbidden**.

For providing output, you should choose a consistent value for one of the states (either truthy or falsy) and use any other (not necessarily consistent) possible output for the other state (Discussion).

Your answers will be scored by your initial program's length **L** (in bytes), with less bytes being better.

## Example

Let's say your (initial) program is `ABCDE`. Then:

* `ABCDE` (1 repetition) should check if the input equals **5**.
* `ABCDEABCDE` (2 repetitions) should check if the input equals **10**.
* `ABCDEABCDEABCDE` (3 repetitions) should check if the input equals **15**. Etc...

The score of this sample code would be **5**, as the initial source is 5 bytes long.

# Answer
# Jelly, 1 byte

Output is **0** for a match, non-zero for a non-match.

Try it online!

### How it works

This makes advantage of the overly liberal output format. Repeating  **M** times simply decrements the input **M** times, so the result will be zero if and only if the input is **LM**, where **L = 1**.
> 12 votes

# Answer
## Haskell, 8 bytes

```
(-8+).id

```

Try it online!

Like many other answers it returns 0 for truthy and non-0 for falsy by repeatedly subtracting the length of the code from the input number.
> 11 votes

# Answer
## Retina, ~~21~~ 20 bytes

```
\d+
*
^$
_
^_{20}

_

```

Try it online! Just repeat the part in the *Code* window to see how it handles the multiples.

Gives `0` for the correct multiple and positive integers for everything else.

### Explanation

Let's look at the single program first:

```
\d+
*

```

This converts a decimal number to unary (using `_` as the unary digit).

```
^$
_

```

If the string is empty (which can't happen at this point, because the input is guaranteed to be positive), we replace it with a single `_`.

```
^_{20}

```

Now we get rid of the first 20 underscores. Iff the input was `20`, this results in an empty string.

```
_

```

And finally we count the number of underscores in the result, which is zero iff the input was `20`.

---

Now what happens when we repeat the source code. Since we don't insert a linefeed when joining the programs, the first line will go right at the end of the last line, we get this when the double the program:

```
\d+
*
^$
_
^_{20}

_\d+
*
^$
_
^_{20}

_

```

Now instead of counting the underscores, we end up with the following stage:

```
_\d+
*

```

This stage does nothing, because there are no more digits in the working string at this point, so the regex can't match.

```
^$
_

```

Now this stage becomes relevant. If the input was a smaller multiple of 20, the string has been emptied by the previous copy of the source code. In that case, we turn it into a single underscore, which we know can never be turned into an empty string again by our program. This way we ensure that *only* the **M**th multiple is accepted (and not all multiples up to the **M**th).

```
^_{20}

```

We remove the first 20 underscores once more. So **M** repetitions of the source code will remove **20M** underscores from the string, if possible.

```
_

```

And when we get to the end of the program, we still count underscores so that valid inputs give zero.
> 8 votes

# Answer
# x86 32-bit machine code fragment, 1 byte

```
48                      dec    eax

```

Input in EAX, output in EAX: 0 for true, non-zero for false. (Also leaves the ZF flag set for true, unset for false, so you could `je was_equal`). As a "bonus", you don't have to worry about wrapping; 32-bit x86 can only address 4GiB of memory, so you can't make M large enough to wrap all the way around and find `1 == 2**32 + 1` or something.

To make a callable function, append a `0xC3` `ret` instruction after repeating `0x48` M times. (Not counted in the total count, because many languages need to repeat just the function body, or an expression, to be able to compete).

Calleable from GNU C with the prototype `__attribute__((regparm(1))) int checkeqM(int eax);` GNU C's `regparm` x86 function attribute, like `-mregparm`, uses EAX to pass the first integer arg.

For example, this complete program takes 2 args, and JITs M copies of the instruction + a `ret` into a buffer, and then calls it as a function. (Requires executable heap; compile with `gcc -O3 -m32 -z execstack`)

```
/******* Test harness: JIT into a buffer and call it ******/
// compile with gcc -O3 -no-pie -fno-pie -m32 -z execstack
// or use mprotect or VirtualProtect instead of -z execstack
// or mmap(PROT_EXEC|PROT_READ|PROT_WRITE) instead of malloc

// declare a function pointer to a regparm=1 function
// The special calling convention applies to this function-pointer only
// So main() can still get its args properly, and call libc functions.
// unlike if you compile with -mregparm=1
typedef int __attribute__((regparm(1))) (*eax_arg_funcptr_t)(unsigned arg);

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    if (argc<3) return -1;
    unsigned N=strtoul(argv[1], NULL, 0), M = strtoul(argv[2], NULL, 0);

    char *execbuf = malloc(M+1);   // no error checking
    memset(execbuf, 0x48, M);     // times M  dec eax
    execbuf[M] = 0xC3;            // ret
    // Tell GCC we're about to run this data as code.  x86 has coherent I-cache,
    // but this also stops optimization from removing these as dead stores.
    __builtin___clear_cache (execbuf, execbuf+M+1);
     //   asm("" ::: "memory");  // compiler memory barrier works too.

    eax_arg_funcptr_t execfunc = (eax_arg_funcptr_t) execbuf;
    int res = execfunc(N);
    printf("%u == %u  =>  %d\n", N,M, res );
    return !!res;   // exit status only takes the low 8 bits of return value
}

```

non-PIE executables are loaded lower in virtual memory; can do a bigger contiguous malloc.

```
$ gcc -g -O3 -m32 -no-pie -fno-pie -fno-plt -z execstack coderepeat-i386.c
$ time ./a.out 2747483748 2747483748   # 2^31 + 600000100 is close to as big as we can allocate successfully
2747483748 == 2747483748  =>  0

real    0m1.590s     # on a 3.9GHz Skylake with DDR4-2666
user    0m0.831s
sys     0m0.755s

$ echo $?
0

 # perf stat output:
       670,816      page-faults               #    0.418 M/sec
 6,235,285,157      cycles                    #    3.885 GHz
 5,370,142,756      instructions              #    0.86  insn per cycle

```

Note that GNU C doesn't support object sizes larger than `ptrdiff_t` (signed 32-bit), but `malloc` and `memset` do still work, so this program succeeds.

# ARM Thumb machine code fragment, 2 bytes

```
 3802            subs    r0, #2

```

First arg in `r0` and return value in `r0` is the standard ARM calling convention. This also sets flags (the `s` suffix). Fun fact; the *non*-flag-setting version of `sub` is a 32-bit wide instruction.

The return instruction you need to append is `bx lr`.

# AArch64 machine code fragment, 4 bytes

```
d1001000        sub     x0, x0, #0x4

```

Works for 64-bit integers. Input / output in `x0`, as per the standard calling convention. `int64_t foo(uint64_t);`

AArch64 doesn't have a Thumb mode (yet), so 1 instruction is the best we can do.
> 7 votes

# Answer
# , 16 (or 1) bytes

Boring answer:

```
<C-x>

```

one byte.

Less boring answer:

```
uÓ^$/0
16Ø^a$

```

Try it online!

Hexdump:

```
00000000: 75d3 5e24 2f30 0a31 3601 d85e 1261 240a  u.^$/0.16..^.a$.

```

I actually wrote this about 5 minutes after the challenge came out. It took me 30 minutes to patch this horrible pile of spaghetti code that I call a *language*.
> 4 votes

# Answer
# Python 3, 27 bytes

```
int=lambda x,i=int:i(x)-27;

```

Try it online!

Code repeated twice:

```
int=lambda x,i=int:i(x)-27;int=lambda x,i=int:i(x)-27;

```

Try it online!
> 4 votes

# Answer
# TI-Basic (83 series), 4 bytes

```
:Ans-4

```

Takes input in `Ans`: for example, you might type `17:prgmCODEGOLF` to run this with an input of `17`. Prints (and returns in `Ans`) the value `0` if the input is equal to **L × M**, and a nonzero value otherwise.

Note that the `:` is part of the code, so if you are entering this into the program editor, you should see

```
PROGRAM:CODEGOLF
::Ans-4

```

if you enter it once and

```
PROGRAM:CODEGOLF
::Ans-4:Ans-4:An
s-4

```

if you enter it three times.
> 3 votes

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

```
$_-=6;

```

Try it online!

uses `0` for equal
> 3 votes

# Answer
# Brachylog, 2 bytes

```
-₂

```

Try it online!
> 3 votes

# Answer
# Brain-Flak, 24 bytes

```
({}[(((()()()){}){}){}])

```

Try it online!

Returns `0` for equal and something else for not equal.

## How it works:

```
({} #pop the top of the stack
  [(((()()()){}){}){}] #subtract 24
) #push the result.

```

This code run `n` times will subtract `n * 24` from the input, giving 0 only when the input = `n*24`.
> 2 votes

# Answer
# Stax, 1 byte

```
v

```

Try it online!
> 2 votes

# Answer
# Haskell, 12 bytes

```
(-)$0
 +12--

```

Try it online!

Outputs `0` for truthy and some non-zero integer for falsy.

## Alternate solution, 12 bytes

```
id
 .(-)12--

```

Try it online!
> 1 votes

# Answer
# Befunge-98, 15 bytes

```
]#<@.-&+
>fv
v+

```

Try it online!

Try it doubled!

Uses 0 for equal and anything else for unequal.

# Explanation:

This code repeated many times will look something like this:

```
]#<@.-&+
>fv
v+]#<@.-&+
>fv
v+]#<@.-&+
>fv
 .
 .
 .
v+]#<@.-&+
>fv
v+

```
1. `]` right turn. Sends the IP down.
2. `>` move east. Sends the IP right.
3. `f` push a 16.
4. `v` move south. Sends the IP down. If this is the last time, Goto step 8.
5. `]` right turn. Sends the IP left.
6. `+` add. Adds the 16 to the top of the stack.
7. `v` move south. Sends the IP down. Goto step 2.
8. `<` move west. Send the IP left.
9. `#` skip. jump over the `]` and wrap around to the end.
10. `+` add. Adds the 16 to the top of the stack.
11. `&` input. Push a number from the user.
12. `-` subtract. get the difference of sum we were working on and the input.
13. `.` print. Print the result.
14. `@` end.
> 1 votes

# Answer
# Lua, ~~56~~ 46 bytes

```
a=(a or io.read())-46io.write(a<=0 and a or"")

```

Outputs a 0 (without a trailing newline) if equal and either nothing or a series of negative numbers (with preceding zero in some cases) if not equal.

Alone: Try it online!

Repeated a bunch of times: Try it online!

## Explanation

```
a=(a or io.read())-46

```

On the first iteration (when `a` hasn't been defined yet and is therefore `nil`), sets `a` to a number taken from input, otherwise to itself. In both cases, 46 is then subtracted from `a`.

```
io.write(a<=0 and a or"")

```

This just prints `a` if it is less than (to take care of cases where the input was larger than the total length) or equal to zero, and the empty string otherwise.

*-10 bytes* for remembering that Lua does conversions between numbers and strings automatically. Whoops.
> 1 votes

# Answer
# Pure Bash, 15

Input given as a command-line parameter. Output as a shell exit code - `1` for TRUE and `0` for FALSE.

```
(((a+=15)-$1))

```
> 1 votes

# Answer
# Charcoal, 13 bytes

```
ＰＩ⁼Ｉθ×¹³Ｌ⊞Ｏυω

```

Try it online! Based on my answer to I double the source, you double the output! Explanation:

```
         ⊞Ｏυω   Push empty string to predefined empty list
        Ｌ       Take the length
     ×¹³        Multiply by 13
  ⁼Ｉθ           Compare to the input
 Ｉ              Cast to string
Ｐ               Print without moving the cursor

```

Manages to output `1` for truthy and `0` for falsy. Subsequent repetitions compare the input against `13`, `26`, `39`, `52` etc. but each time the answer is overprinted so only the final answer is seen.
> 1 votes

# Answer
# JavaScript ES6, 32 Bytes

```
((f=k=>n=>n>0?n==k:f(k+32))(32))

```

if true be 0 and false as others, 31 bytes

```
(f=k=>n=>n>0?n-k:_=>f(k+_))(31)

```

```
console.log([
    ((f=k=>n=>n>0?n==k:f(k+32))(32)) (31),
    ((f=k=>n=>n>0?n==k:f(k+32))(32)) (32),
    ((f=k=>n=>n>0?n==k:f(k+32))(32)) (33),
    ((f=k=>n=>n>0?n==k:f(k+32))(32)) (64),
    ((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32)) (32),
    ((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32)) (63),
    ((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32)) (64),
    ((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32)) (96)
]);
```
> 1 votes

# Answer
# MIPS, 4 bytes

Uses `$a0` as argument and return value.

```
0x2084fffc    addi $a0, $a0, -4

```

# MIPS, 8 bytes (using MIPS calling convention)

```
0x2084fff8    addi $a0, $a0, -8
0x00041021    move $v0, $a0

```

# x86, 5 bytes

This is my first x86 answer so feedback welcome. Uses \_fastcall convention with ecx as first argument.

```
83 e9 05                sub    $0x5,%ecx
89 c8                   mov    %ecx,%eax

```

Peter Cordes has a 1 byte solution in the comments.

---

**Brainfuck commentary**: The hard part is getting brainfuck to return a single value. Otherwise something like this would be easy.

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

```
> 1 votes

# Answer
# Octave: 23 bytes

```
+23;[ans,i]((N==ans)+1)

```

If N = L\*M, the expression returns `0+i` (i.e. a purely imaginary number), otherwise the expression results in a complex number with a real component.

For a slightly nicer result at the cost of an extra byte:

```
+24;[ans,-1]((N==ans)+1)

```

If N = L\*M the expression returns `-1`, otherwise a positive number.

Demo:

```
N=48;
+24;[ans,-1]((N==ans)+1)                                                 #>> 24
+24;[ans,-1]((N==ans)+1)+24;[ans,-1]((N==ans)+1)                         #>> -1
+24;[ans,-1]((N==ans)+1)+24;[ans,-1]((N==ans)+1)+24;[ans,-1]((N==ans)+1) #>> 23

```

---

PS, you can get the same result with `+24;if N==ans;-1;end;ans` but the bytecount is the same
> 1 votes

# Answer
# Vyxal, 1 byte

Try it Online!

Outputs 0 for truthy and something else for falsy.

Port of the other answers, decrements.
> 1 votes

# Answer
# JavaScript (ES6), 47 bytes

This is using the same technique as Benoit Esnard in this answer (from *I double the source, you double the output!*).

Prints **0** if **n = 47 * M**, or a non-zero value otherwise.

```
n=prompt(setTimeout`alert(n)`)-47/*
n-=47//*///

```

### Demo for M = 1

```
n=prompt(setTimeout`alert(n)`)-47/*
n-=47//*///
```

### Demo for M = 2

```
n=prompt(setTimeout`alert(n)`)-47/*
n-=47//*///n=prompt(setTimeout`alert(n)`)-47/*
n-=47//*///
```
> 0 votes

# Answer
# Brain-Flak, 24 bytes

```
({}[(((()()()){}){}){}])

```

Try it online!

Just subtracts 24 from the input. Outputs `0` for true and anything else for false.

# Brain-Flak, 68 bytes

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

```

Try it online!

This one is more sophisticated it outputs `1` for true and `0` for false.
> 0 votes

---
Tags: code-golf, decision-problem, source-layout, self-referential
---


title: Find my polyphthongs!

text:
# Question
Title: Find my polyphthongs!
For the purposes of this challenge, a *polyphthong* is defined as a contiguous slice of a String, that only contains vowels, and has length at least 2. Given a non-empty String as input, your task is to output all the polyphthongs it contains.

For example, `"abeoic"` has the following contiguous slices (space-separated):

```
a b e o i c ab be eo oi ic abe beo eoi oic abeo beoi eoic abeoi beoic abeoic

```

Removing those that contain anything other than vowels, or have length smaller than 2, we get our desired polyphthongs:

```
eo oi eoi

```

---

Your submissions must abide by the following rules:

* You can choose either lowercase or uppercase for I/O, but the output case must match the input case.
* The vowels are `aeiou` (for lowercase) and `AEIOU` (for uppercase). `y` / `Y` is not considered a vowel.
* The input will only contain printable ASCII.
* If a polyphthong appears multiple times, you may choose to output it only once or output all its occurrences.
* Any reasonable I/O format and method is allowed (lists of characters are also fine, for both input and output).

## Test Cases

```
Input  ->  Output (lowercase)

r67^^()*6536782!87                -> []
programming puzzles and code golf -> []
aaand... i won!                   -> ['aa', 'aa', 'aaa']
abeoic                            -> ['eo', 'oi', 'eoi']
yah eioo ala                      -> ['ei', 'io', 'oo', 'eio', 'ioo', 'eioo']
@yabeeeayio__e                    -> ['ee', 'ee', 'ea', 'io', 'eee', 'eea', 'eeea']
0ioen0aaiosnjksd                  -> ['io', 'oe', 'aa', 'ai', 'io', 'ioe', 'aai', 'aio', 'aaio']

```

Note that for test cases 3 and 6, you may output `'aa'` and `'ee'` respectively only once (See the fourth rule).

This is , the shortest submission in bytes in every language wins!

# Answer
> 7 votes
# Python 2, ~~102~~ 97 bytes

*thanks to @JonathanFrech for -5 bytes*

```
w=input();l=range(len(w)+1)
print{w[a:b]for a in l for b in l if b-a>1<set(w[a:b])<=set('aeiou')}

```

Try it online!

lowercase I/O

# Answer
> 6 votes
## Retina, ~~23~~ 20 bytes

```
M!&`[aeiou]+
r!&`..+

```

Try it online!

This prints all occurrences of a polyphthong.

### Explanation

Retina does have a way to get all *overlapping* matches, but what this really means is that it will look for one match from each position. So if there are multiple matches from the same position, this will only return one of them. The only way to really get all overlapping matches is to use this feature twice, once matching left to right and once right to left (so that we first get the longest possible match from each possible starting position, and then we also get all matches for the possible ending positions).

So the actual program:

```
M!&`[aeiou]+

```

Get all overlapping runs of vowels. What this really means is to get all suffixes of all vowel runs.

```
r!&`..+

```

Now get all prefixes which are at least of length 2, by matching from right to left. The `M` is implicit here, because it's the final line of the program.

# Answer
> 6 votes
# JavaScript (ES6), ~~77~~ 75 bytes

Expects input in lowercase. Outputs unique polyphthongs without repeating.

```
w=>(r=[],g=s=>w.match(s)&&[...'aeiou'].map(c=>g(s+c),s[1]&&r.push(s)))``&&r

```

### Test cases

```
let f =

w=>(r=[],g=s=>w.match(s)&&[...'aeiou'].map(c=>g(s+c),s[1]&&r.push(s)))``&&r

console.log(JSON.stringify(f("r67^^()*6536782!87")))
console.log(JSON.stringify(f("programming puzzles and code golf")))
console.log(JSON.stringify(f("aaand... i won!")))
console.log(JSON.stringify(f("abeoic")))
console.log(JSON.stringify(f("yah eioo ala")))
console.log(JSON.stringify(f("@yabeeeayio__e")))
console.log(JSON.stringify(f("0ioen0aaiosnjksd")))
```

### How?

We recursively build the tree of all possible polyphthongs, pruning branches as soon as the current node is not contained in the input anymore, and saving all matching nodes of at least 2 characters.

```
w => (                      // given the input w
  r = [],                   // r = array of results
  g = s =>                  // g = recursive function taking s
    w.match(s) &&           // if w contains s:
    [...'aeiou'].map(c =>   //   for each vowel c:
      g(s + c),             //     do a recursive call with s + c
      s[1] &&               //     if s is at least 2-character long:
      r.push(s)             //       push it into r
    )                       //   end of map()
)``                         // initial call to g() with s = ''
&& r                        // return r

```

# Answer
> 5 votes
# QuadS, 20 + 1 = 21 bytes

```
⊃,/⍵
[aeiou]+
1↓,\⍵M

```

with the `o` flag

Try it online!

In order of things happening:

`[aeiou]+` on each match of this PCRE

`,\⍵M` prefixes of the Match

`1↓` drop the first one (which has one one vowel)

`,/⍵` concatenate all the lists of prefixes

disclose (because reductions `/` enclose)

---

This is equivalent to the Dyalog APL tacit function:

```
{⊃,/⍵}'[aeiou]+'⎕S{1↓,\⍵.Match}⍠'OM'1

```

Try it online!

# Answer
> 4 votes
# Mathematica, 92 bytes

```
Select[Join@@Partition[r,i,1]~Table~{i,2,Length[r=(S=Characters)@#]},SubsetQ[S@"aeiou",#]&]&

```

Try it online!

# Answer
> 4 votes
# Java (OpenJDK 8), ~~138~~ ~~135~~ 134 bytes

```
s->{String e,x="";for(int i=0,j,y=s.length();i<=y;i++)for(j=y;j>i;x+=e.matches("[aeiou]{2,}")?e+" ":"")e=s.substring(i,j--);return x;}

```

Try it online!

# Answer
> 4 votes
# , ~~34~~ 29 bytes

```
(*/@e.&'aeoui'*1<#)\\.#&,<\\.

```

Try it online!

# Answer
> 3 votes
# Jelly, 9 bytes

```
ẆḟÐḟØcḊÐf

```

Try it online!

# Explanation

```
ẆḟÐḟØcḊÐf  Main Link
Ẇ          Get all (contiguous) sublists
  Ðḟ       Filter; remove all elements where the result is truthy:
 ḟ  Øc     Filter; remove all vowels; if it's truthy, then it contains non-vowels
       Ðf  Filter; keep elements where the result is truthy:
      Ḋ    Dequeue; return all but the first element (truthy if the length was at least 2)

```

-4 bytes thanks to Mr. Xcoder

# Answer
> 3 votes
# , 137 bytes

*outgolfed by Mark!*

```
function(S)(x=unlist(sapply((s=el(strsplit(S,"[^aeiou]")))[nchar(s)>1],function(x)substring(x,1:(n=nchar(x)),rep(n:1,e=n)))))[nchar(x)>1]

```

Try it online!

```
function(S){
 s <- el(strsplit(S,"[^aeiou]"))            # split on non-vowels
 s <- s[nchar(s)>1]                         # vowel groups of length at least 2
 p <- function(x){                          # generates all substrings of inputs
  n <- nchar(x)
  start <- 1:n
  stop <- rep(n:1, n)                       # this will generate dups
  substring(x, start, stop)

 }
 q <- unlist(sapply(s, p))                  # all substrings
 q <- q[nchar(q)>1]                         # all length-2 or more substrings
}

```

# Answer
> 3 votes
# C (gcc), 104 bytes (99 bytes with lowercase only or uppercase only)

Yeah, it leaks - so what?

```
#include<string.h>
a;f(char*s){*s&&f(s+1);for(a=strspn(s=strdup(s),"AEIOUaeiou");a>1;)s[a--]=0,puts(s);}

```

Try it online!

# Answer
> 2 votes
# Perl 5, 53 +1 (-p)

```
/[aeiou]{2,}(?{$h{$&}++})(?!)/g;$_=join$",sort keys%h

```

Try It Online

# Answer
> 2 votes
# PowerShell, ~~93~~ 88 bytes

```
param($a)0..($b=$a.count-1)|%{($i=$_)..$b|%{-join$a[$i..$_]}}|?{$_-match'^[aeiou]{2,}$'}

```

Try it online!

Uses lowercase or uppercase I/O (or a mix!).

Borrows code from my answer on Exploded Substrings to get all the substrings, then pulls out those that regex `-match` against `^[aeiou]{2,}$` -- i.e., those that are at least two vowels in length and only vowels. Those strings are left on the pipeline and output is implicit.

# Answer
> 2 votes
# 05AB1E, 10 bytes

```
Œʒg≠}ʒžMм_

```

Try it online!

**Explanations:**

```
Œʒg≠}ʒžMм_
Œ            Push all substrings (abeoic => a, b, e, ..., eoi, eoc, ... abeioc)
 ʒ  }        Filter elements for which result is 1
  g≠            Push 1 if length is != 1, 0 otherwise
     ʒ       Filter elements for which result is 1
      žMм       Remove all occurences of 'aeiou' from element
         _      Negative bool: push 1 if length == 0, 0 otherwise

```

# Answer
> 2 votes
# Haskell, ~~148~~ ~~137~~ ~~130~~ ~~123~~ 118 bytes

*Thanks to @Laikoni for -11 bytes, further -7 bytes by pointing me to golfing tips, another -7 bytes, and yet another -5 bytes, for a total of whopping -30 bytes.*

~~This looked like a good fit for Haskell but the result doesn't seem to agree.~~ I guess Haskell was an OK-ish choice after all. I'm still annoyed by the way `subsequences` works though.

```
import Data.List
v=(`elem`"aeiou")
p s=nub$do x<-groupBy((.v).(&&).v)s;[y|y@(c:_:_)<-subsequences x,v c,y`isInfixOf`x]

```

Try it online!

# Answer
> 2 votes
# Perl, 45 bytes

```
local $,=" ";print $_=~/(?=([AEIOU]{2,}))/ig;

```

# Answer
> 2 votes
# , ~~120 bytes~~ 110 bytes

```
function(x){k=nchar(x);i=k:1;e=expand.grid(i,i[-1]);grep("^[aeiou]+$",mapply(substr,x,e[,2],e[,2]+e[,1]),v=T)}

```

Try it online!

How it works

```
function(x){                  #initalize the anonymous function where input is stored in x
  k=nchar(x)                  #set k to the number of characters in x
  i=k:1                       #create vector of integers from k to 1
  e=expand.grid(i,i[-1])      #create matrix of full outer join on i
                              #except in the second column, limit i to being less than k
  grep("^[aeiou]+$",          #search for strings made of only vowels
       mapply(substr,         #map the substring function
              x,              #with x as the string to subset
              e[,2],          #start at the second column of the outer join
              e[,2]+e[,1]     #end at the sum of the sum of the first and second columns
       ),
       v=T                    #if a match is found, return it's value
  )
}                             #by default, R returns the last line of a function

```

# Answer
> 1 votes
# JavaScript (ES6), 105 bytes

```
s=>eval('a=[];l=i=s.length;while(i--){j=l;while(j--)if(/^[aeiou]{2,}$/.test(t=s.slice(i,j)))a.push(t)}a')

```

Probably has a lot of golfing left to do.

```
let f=
s=>eval('a=[];l=i=s.length;while(i--){j=l;while(j--)if(/^[aeiou]{2,}$/.test(t=s.slice(i,j)))a.push(t)}a')
console.log(JSON.stringify(f('r67^^()*6536782!87')))
console.log(JSON.stringify(f('programming puzzles and code golf')))
console.log(JSON.stringify(f('aaand... i won!')))
console.log(JSON.stringify(f('abeoic')))
console.log(JSON.stringify(f('yah eioo ala')))
console.log(JSON.stringify(f('@yabeeeayio__e')))
console.log(JSON.stringify(f('0ioen0aaiosnjksd')))
```

# Answer
> 1 votes
# C, 119 bytes

```
f(char*s){*s&&f(s+1);char*t,*b=calloc(strlen(s),1);for(t=b;*s==65|*s==69|*s==73|*s==79|*s==85;b[1]&&puts(b))*t++=*s++;}

```

Try it online!

# Answer
> 1 votes
# Perl 5, 44 + 1 (`-n`) = 45 bytes

```
map{say}/(?=([aeiou]{$.}))/g while$.++<y///c

```

Try it online!

# Answer
> 1 votes
# C, ~~105~~ 75 bytes

A function accepting a pointer to lowercase input, and producing space-separated strings on standard output:

```
i;f(char*p){for(i=strspn(p,"aeiou");i>1;)printf("%.*s ",i--,p);*p&&f(p+1);}

```

### Test program

```
#include <stdio.h>

int main(int argc, char **argv)
{
    for (int i = 1;  i < argc;  ++i) {
        char *in = argv[i];
        printf("'%s' -> [ ", in);
        f(in);
        puts("]");
    }
}

```

### Demo

```
'r67^^()*6536782!87' -> [ ]
'programming puzzles and code golf' -> [ ]
'aaand... i won!' -> [ aaa aa aa ]
'abeoic' -> [ eoi eo oi ]
'yah eioo ala' -> [ eioo eio ei ioo io oo ]
'@yabeeeayio__e' -> [ eeea eee ee eea ee ea io ]
'0ioen0aaiosnjksd' -> [ ioe io oe aaio aai aa aio ai io ]

```

### Explanation

```
#include <string.h>
#include <stdio.h>

void find_polyphthongs(char *p)
{
    /* from longest polyphthong substring down to 2 */
    for (int i = strspn(p,"aeiou");  i >= 2;  --i) {
        /* print exactly [p .. p+i] */
        printf("%.*s ", i, p);
    }

    /* tail-recurse to next char */
    if (*p) {
        find_polyphthongs(p+1);
    }
}

```

Using GCC on Debian Linux, I seem to get away with the incompatible implicit declarations of `strchr()` and `printf()`. Other platforms may require `<stdio.h>` and `<string.h>` to be included.

Try it online (requires Javascript).

# Answer
> 1 votes
# APL (Dyalog), 53 bytes

This is a `Dfn` (**d**irect **f**unctio**n**). Usage is `p '<argument>'`. Fair warning: this is not very efficient and times out for `input > 8 characters` on TIO, but works normally when given enough time.

```
p←{(G∊⊃,/⌽,\∘⌽¨,\⌽⍵)/G←⊃,/{(,v∘.,⊢)⍣⍵⊢v←'aeiou'}¨⍳≢1↓⍵}

```

Try it online!

Thanks to @Adám for 16 bytes!

### How it works:

This is easier to understand if we break the code in smaller portions:

* Part 1 - `G←⊃,/{(,v∘.,⊢)⍣⍵⊢v←'aeiou'}¨⍳≢1↓⍵`: This part of the function takes the length of the (right) argument and mixes the vector `aeiou` to itself that many times, yielding every possible combination of `[2, length(right arg)]` vowels.
* Part 2 - `(G∊⊃,/⌽,\∘⌽¨,\⌽⍵)/`: This part checks which element(s) of G are members of the substrings of the input. This returns a boolean vector, with `1`'s at the indices of the vowel combinations that are present in the input and `0`'s where they're not. The resulting vector is then mapped (`/`) over `G`, returning the elements corresponding to the truthy values.

The whole thing is then assigned to `p`. `p←` is not included in the byte count because it's not *necessary*, it just makes using the function easier.

# Answer
> 1 votes
# Haskell, 74 bytes

```
f[]=[]
f(h:t)=filter(all(`elem`"aeiou"))[h:take i t|i<-[1..length t]]++f t

```

Try it online!

# Answer
> 1 votes
# Ruby 2.4, 100 bytes

```
(2..(b=(a=gets).size-1)).to_a.flat_map{|i|(0..(b-i)).to_a.map{|j|a[j,i]}}.select{|k|k=~/^[aeiou]+$/}

```

This is my first attempt at golfing, and I'm sure there are lots of ways to shorten this code.

# Answer
> 0 votes
# Ruby, 80 bytes

```
->s{[*0..z=s.size-2].product([*2..z]).map{|v|s[*v][/[aeiou]{2,}/]}.uniq.compact}

```

Try it online!

# Answer
> 0 votes
# Pyth, 15 bytes

```
f&tT!-T"aeoi".:

```

Try it online!

Definitely golfable, I want to get it better before writing out explanation.

---

# Answer
> 0 votes
# T-SQL (SQL Server 2014), 281 bytes

```
;with s as(select substring(@,1,1)C,stuff(@,1,1,'')D,1 R union all select substring(D,1,1),stuff(D,1,1,''),R+1from s where len(D)>0),c as(select R i,C w from s where C LIKE'[aeiou]'union all select R,w+C from c join s ON i+1=R where s.C LIKE'[aeiou]')select w from c where len(w)>1

```

Input give by

```
declare @ varchar(max) = 'abeoic'

```

Uses a common table expression `s` to blow the input apart into ordered individual letters, and then a second common table expression `c` to generate all ordered combinations, throwing out non vowels.

SQL Fiddle

# Answer
> 0 votes
# PHP, 139 bytes

```
function y($s){$p=[];$l=strlen($s);for($i=2;$i<=$l;$i++)for($j=0;$j<=$l-$i;$j++)strspn($a=substr($s,$j,$i),'aeiou')==$i&&$p[]=$a;return$p;}

```

Online demo

```
function yreadable($s)
{
    $p = [];
    $l = strlen($s);
    for($i=2; $i<=$l; $i++)
        for($j=0; $j<=$l-$i; $j++)
            strspn($a=substr($s,$j,$i),'aeiou')==$i
            && $p[] = $a;
    return $p;
}

```

## How it works

Select sub-strings (beginning with the length of 2) consisting of adjacent characters and move along string. Collect any sub-strings that only contain vowels. Repeat with longer sub-strings.

For string 'abcdef' these are the substrings generated and checked:

```
'ab','bc','cd','de','ef'
'abc','bcd','cde','def'
'abcd','bcde','cdef'
'abcde','bcdef',
'abcdef'

```

# Answer
> 0 votes
# Vyxal 2.6.0pre1 , 6 bytes

```
K~Ḣ'AA

```

No TIO link yet.

```
K      # Substrings
 ~Ḣ    # Filtered by a[:1] exists (len(a) > 1)
   '   # Filtered by...
     A # All...
    A  # Are vowels.

```

# Vyxal, 9 bytes

```
K'Ḣ;'kv↔=

```

Try it Online!

```
K         # Substrings
 ' ;      # Filtered by...
  Ḣ       # a[1:] is nonempty
    '     # Filter again by...
       ↔  # Removing everything but...
     kv   # Vowels
        = # Leaves it identical to the original.

```

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


title: Generate the group table for Z_n

text:
# Question
Title: Generate the group table for Z_n
Groups are a widely used structure in Mathematics, and have applications in Computer Science. This code challenge is about the fewest # of characters to create a group table for the additive group Zn.

How the table is constructed: For Zn, the elements are {0, 1, 2, ..., n-1}. The table will have n rows and n columns. For the ij-th entry of the table, the value is i+j mod n. For example, in Z3, the 1-2nd entry (2nd row, 3rd column if you count the starting row/column as 1) is (1+2)%3 = 0 (see sample output).

**Input:** a positive integer, n

**Output:** a table that is a textual presentation of Zn, constructed as described above, and displayed as shown below in the sample outputs. Spaces are optional

**Sample input:** `3`

**Sample output:**

```
0 1 2
1 2 0
2 0 1

```

**Sample input:** `5`

**Sample output:**

```
0 1 2 3 4
1 2 3 4 0
2 3 4 0 1
3 4 0 1 2
4 0 1 2 3

```

# Answer
> 10 votes
# APL (10)

(Assuming `⎕IO=0`. It works on ngn/apl by default, other APLs tend to need an `⎕IO←0` first.)

```
{⍵|∘.+⍨⍳⍵}

```

Explanation:

* `⍳⍵`: the numbers \[0..⍵)
* `∘.+⍨`: create a sum table
* `⍵|`: numbers in the table `mod`

# Answer
> 3 votes
## GolfScript (13 chars)

I understand from your comment on Claudiu's answer that whitespace between the elements of a row is not necessary. On that understanding:

```
~.,{.n\(+}@(*

```

Online demo

Dissection:

```
~        Parse the input into an integer
.,       Duplicate it, turn the second into an array [0,...,n-1]
{        Loop: top of stack is the previous row
  .n\    Push a newline and a copy of the previous row
  (+     Rotate the first element to the end to get the new row
}@(*     Perform loop n-1 times

```

---

If whitespace is necessary, for 20 chars:

```
~.,{.(+}@(*]{' '*n}/

```

# Answer
> 3 votes
# Python 2, 66 bytes

```
def f(n):R=range(n);exec"print''.join(map(str,R));R+=R.pop(0),;"*n

```

Rotates the list by popping and re-appending.

# Python 3, 53 bytes

```
def f(n):*R,=range(n);[print(*R[i:]+R[:i])for i in R]

```

Uses the same method as @mbomb007, but abusing `print` as a function.

# Answer
> 3 votes
# 05AB1E, ~~10~~ 8 bytes

```
Ý¨Dδ+I%»

```

Try it online!

## Explanation

```
         # Implicit input n = 3                  [3]
Ý        # Push range(0,3)                       [[0,1,2,3]]
 ¨       # Pop last element                      [[0,1,2]]
  D      # Duplicate                             [[0,1,2],[0,1,2]]
   δ     # Apply next operation double vectorized
    +    # Vectorized addition                   [[[0,1,2],[1,2,3],[2,3,4]]]
     I   # Push input                            [[[0,1,2],[1,2,3],[2,3,4]],3]
      %  # Elementwise modulo 3                  [[[0,1,2],[1,2,0],[2,0,1]]]
       » # " ".join(x) followed by newline       ["0 1 2\n1 2 0\n2 0 1\n"]
           for every x in list

```

---

## Previous answer: 10 bytes

```
Ý¨DvDðý,À}

```

Try it online!

My first try at golfing in 05AB1E.

### Explanation of previous answer

```
           # Implicit input n = 3                   [3]
Ý          # Push range(0,3)                        [[0,1,2,3]]
 ¨         # Pop last element.                      [[0,1,2]]
  D        # Duplicate                              [[0,1,2],[0,1,2]]
   v     } # Pop list and loop through elements     [[0,1,2]]
    D      # Duplicate                              [[0,1,2],[0,1,2]]
     ð     # Push space char                        [[0,1,2],[0,1,2], " "]
      ý    # Pop list a and push string a.join(" ") [[0,1,2],"0 1 2"]
       ,   # Print string with trailing newline     [[0,1,2]] Print: "0 1 2"
        À  # Rotate list                            [[1,2,0]]

```

# Answer
> 2 votes
# Jelly, 4

```
Ḷṙ`G

```

Try it online!

# Answer
> 1 votes
# Matlab (28)

```
k=exp(0:n-1)
mod(log(k'*k),n)

```

# Answer
> 1 votes
# Pyth, 16

```
JVQXQjdJ=J+tJ]hJ

```

Prints the table with proper whitespace.

```
./pyth.py -c "JVQXQjdJ=J+tJ]hJ" <<< 5
0 1 2 3 4
1 2 3 4 0
2 3 4 0 1
3 4 0 1 2
4 0 1 2 3

```

**Explanation:**

```
                   Automatic: Q=eval(input())
JVQ                J = range(Q)
XQ                 repeat Q times
  jdJ              print J, joined on " "
  =J               J =
    +tJ]hJ             tail(J) + [head(J)] (J[1:] + [J[-1]]])

```

# Answer
> 1 votes
## J, 20

Reading from stdin and producing a 2D array (which renders the same as the sample in the question).

```
(|+/~@i.)@".}:1!:1]3

```

If a function taking a string suffices, `(|+/~@i.)@".`. If a function taking an integer suffices, `|+/~@i.` should be sufficient.

**Explanation:** `f g` in J (for functions f, g) denotes a "hook", which is a composite function that runs the input through g (a unary function) and then the input and the result of g through f (a binary function). The answer is a fork with components `|` (modulus) and `+/~@i.`. The latter part is "table-of sums composed-with list-of-indices-upto" (`i.` is a bit like `range` in Python).

# Answer
> 1 votes
# Octave, 23

```
@(n)mod((r=0:n-1)'+r,n)

```

# Answer
> 1 votes
# Python 2, 67

Try them both here

I use list splitting to "rotate" the list `n` times, printing it each time. (68 chars)

```
def f(n):
 l=range(n)
 for i in l:print''.join(map(str,l[i:]+l[:i]))

```

I managed to get it one character shorter than the above with a weird trick. (67 chars)

```
def f(n):
 l=range(n)
 for i in l:print''.join(`l[i:]+l[:i]`)[1::3]

```

# Answer
> 1 votes
# Pari/GP, 25 bytes

```
n->matrix(n,,x,y,x+y-2)%n

```

Try it online!

# Answer
> 1 votes
# MathGolf, ~~10~~ 8 bytes

```
r░y\Åo╫;

```

Try it online!

-2 bytes thanks to Jo King

## Explanation

I'll use example input `3` for the explanation

```
r          range(0, n) ([0, 1, 2])
 ░         convert to string (implicit map) (['0', '1', '2'])
  y        join array without separator to string or number ('012')
   \       swap top elements ('012', 3)
    Å      start block of length 2 (for-loop, loops 3 times ('012'))
     o     print TOS without popping
      ╫    left-rotate bits in int, list/str ('012' => '120' => '201' => '012')
       ;   discard TOS (prevents final print)

```

You could also do `r░y\(Åo╫`, which decreases the number of loops by 1 and skips the discard after the loop.

# Answer
> 1 votes
# x86-64 Machine Code (Linux), ~~80~~ 64 bytes

```
0000000000000000 <zn_asm>:
   0:   6a 0a                   pushq  $0xa
   2:   89 f9                   mov    %edi,%ecx
   4:   ff c9                   dec    %ecx

0000000000000006 <zn_asm.l1>:
   6:   c6 06 0a                movb   $0xa,(%rsi)
   9:   48 ff ce                dec    %rsi
   c:   89 fb                   mov    %edi,%ebx
   e:   ff cb                   dec    %ebx

0000000000000010 <zn_asm.l2>:
  10:   89 c8                   mov    %ecx,%eax
  12:   01 d8                   add    %ebx,%eax
  14:   31 d2                   xor    %edx,%edx
  16:   f7 f7                   div    %edi
  18:   89 d0                   mov    %edx,%eax

000000000000001a <zn_asm.l3>:
  1a:   31 d2                   xor    %edx,%edx
  1c:   48 f7 34 24             divq   (%rsp)
  20:   83 c2 30                add    $0x30,%edx
  23:   88 16                   mov    %dl,(%rsi)
  25:   48 ff ce                dec    %rsi
  28:   85 c0                   test   %eax,%eax
  2a:   75 ee                   jne    1a <zn_asm.l3>
  2c:   ff cb                   dec    %ebx
  2e:   85 db                   test   %ebx,%ebx
  30:   7d de                   jge    10 <zn_asm.l2>
  32:   ff c9                   dec    %ecx
  34:   85 c9                   test   %ecx,%ecx
  36:   7d ce                   jge    6 <zn_asm.l1>
  38:   58                      pop    %rax
  39:   48 89 f0                mov    %rsi,%rax
  3c:   48 ff c0                inc    %rax
  3f:   c3                      retq

```

~~I was hoping for this solution to be just a few bytes shorter to be able to beat some of the other submissions on this post. There's a possibility if I use some of the 32 or 16 bit versions of the registers I could shave a few bytes off.~~ Converting a lot of the registers to the 32 bit addressing versions saved 16 bytes.

Basically this function is called from a C/C++ program which passed n through rdi, and a pointer to an allocation through rsi. The pointer that rsi has is actually 1 byte from the end of the allocation, since the table is built backwards. This makes it easier to convert an integer to printable ASCII characters (done by taking some number x mod 10 and converting the result to ASII).

To see the C++ wrapper code and comments on the assembly, check out my repo.

# Answer
> 1 votes
# Q/KDB+, 19 bytes

**Solution:**

```
{t rotate\:t:til x}

```

**Example:**

```
q){t rotate\:t:til x} 3
0 1 2
1 2 0
2 0 1

q){t rotate\:t:til x} 5
0 1 2 3 4
1 2 3 4 0
2 3 4 0 1
3 4 0 1 2
4 0 1 2 3

```

**Explanation:**

```
{t rotate\:t:til x} / solution
{                 } / lambda taking implicit x argument
             til x  / the range 0..x
           t:       / assign to 't'
   rotate\:         / rotate right argument with each-left (\:)
 t                  / the left argument (0..x)

```

**Extra:**

* `{(!x).q.rotate\:!x}` still **19** bytes in K4.

# Answer
> 0 votes
# Golfscript, 20 characters

A terribly lazy job.

```
~:j,{:x;j,{x+j%}%n}/

```

Run it here. (First line is to simulate stdin).

**Explanation**:

```
~                     # evaluate input (turn string "5" into number 5)
:j                    # store into variable j
,                     # turn top of stack into range(top), e.g. 5 --> [0, 1, 2, 3, 4]
{...}/                # for each element in the array...
  :x;                 # store the element into x and pop from the stack
  j,                  # put range(j) on the stack ([0, 1, 2, 3, 4] again)
  {...}%              # map the array with the following:
      x+j%            # add x and mod the resulting sum by j
  n                   # put a newline on the stack

```

When the program ends, the stack contains each of the arrays with newlines between them. The interpreter outputs what's left on the stack, giving the desired result.

# Answer
> 0 votes
## C - 96

```
void g(int k){int i;for(i=0;i<k*k;i++){if(i&&!(i%k))puts("\n");printf("%i ",((i/k)+(i%k))%k);}}

```

# Answer
> 0 votes
# CJam, 14 characters

```
l~_)_@,*/Wf<N*

```

Test it here.

## Explanation

The idea is to repeat the string from `0` to `N-1`, but split it into blocks of `N+1`. This mismatch shifts the row to the left each time. Lastly, we need to get rid of the extraneous character and join everything with newlines.

Here is the exploded code, together with the stack contents for input `3`.

```
l~              "Read and eval input."; [3]
  _             "Duplicate.";           [3 3]
   )            "Increment.";           [3 4]
    _           "Duplicate.";           [3 4 4]
     @          "Rotate.";              [4 4 3]
      ,         "Get range.";           [4 4 [0 1 2]]
       *        "Repeat.";              [4 [0 1 2 0 1 2 0 1 2 0 1 2]
        /       "Split.";               [[[0 1 2 0] [1 2 0 1] [2 0 1 2]]
         Wf<    "Truncate each line.";  [[[0 1 2] [1 2 0] [2 0 1]]
            N*  "Join with newlines.";  ["012
                                          120
                                          201"]

```

The result is printed automatically at the end of the program. (Note, the stack contents for the final step are technically a mixed array containing numbers and newline characters, not a string containing only characters.)

## Alternatively, 11 characters

With the recent addition `ew` (this is newer than the challenge - it returns all overlapping substrings of given length), one could do 11 bytes:

```
l~,2*))ewN*

```

Here is how this one works:

```
l~           "Read and eval input."; [3]
  ,          "Get range.";           [[0 1 2]]
   2*        "Repeat twice.";        [[0 1 2 0 1 2]]
     )       "Pop last.";            [[0 1 2 0 1] 2]
      )      "Increment.";           [[0 1 2 0 1] 3]
       ew    "Get substrings.";      [[[0 1 2] [1 2 0] [2 0 1]]
         N*  "Join with newlines.";  ["012
                                       120
                                       201"]

```

# Answer
> 0 votes
# MATL, 6 bytes

```
:q&+G\

```

Try it online!

```
    # implicit input, say n = 3
:   # range
    # stack: [1, 2, 3]
q   # decrement
    # stack: [0, 1, 2]
&+  # sum with itself and transpose with broadcast
    # stack:
    # [0 1 2
    #  1 2 3
    #  2 3 4]
G   # paste input
    # stack: [0 1 2; 1 2 3; 2 3 4], 3
\   # elementwise modulo
    # implicit output with spaces

```

# Answer
> 0 votes
# Excel VBA, 77 Bytes

Anonymous VBE immediate window function that takes input, as integer,n, from range `[A1]` and outputs to the range `A2.Resize(n,n)`.

```
[A2:IU255]="=IF(MAX(ROW()-1,COLUMN())-1<$A$1,MOD(ROW()+COLUMN()-3,$A$1),"""")

```

# Answer
> 0 votes
# Perl 6, 23 bytes

```
{.rotate(.all).put}o|^*

```

Try it online!

Anonymous code block that takes a number and prints the matrix in the given format with spaces. If we can just return something instead, then the `.put` can be removed.

### Explanation:

```
                   o|^*    # Transform the input into the range 0..input-1
{                 }        # And pass it into the function
 .rotate                   # Rotate the range by
        (.all)             # Each of the range
              .put         # And print each of them separated by spaces

```

# Answer
> 0 votes
# APL(NARS), 15 chars, 30 bytes

```
{⊃{⍵⌽k}¨k←0..⍵}

```

test:

```
  f←{⊃{⍵⌽k}¨k←0..⍵}
  f 4
0 1 2 3 4
1 2 3 4 0
2 3 4 0 1
3 4 0 1 2
4 0 1 2 3
  f 3
0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2
  f 2
0 1 2
1 2 0
2 0 1
  f 1
0 1
1 0
  f 0
0

```

here the language has need no comments...

# Answer
> 0 votes
# Charcoal, 13 bytes

```
ＮθＥθ⪫Ｅθ﹪⁺ιλθ

```

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

```
Ｎθ              Input `n` as a number into variable
   θ            `n`
  Ｅ             Map over implicit range
      θ         `n`
     Ｅ          Map over implicit range
         ι      Current row
        ⁺       Plus
          λ     Current column
       ﹪        Modulo
           θ    `n`
    ⪫           Cast row to string and join with spaces
                Implicitly print each row on its own line

```

# Answer
> 0 votes
# Japt `-R`, 5 bytes

```
ÆZéXn

```

Try it

If using a comma as a separator isn't valid then add a byte for no separator:

```
ÆZ¬éXn

```

Try it

Or 2 bytes to use a space:

```
ÆZéXn)¸

```

Try it

# Answer
> 0 votes
# , 37 bytes

```
sapply(x<-1:scan()-1,`+`,x)%%sum(x|1)

```

Creates a vector from 0 to n-1, and sequentially adds 1, then 2... then n, and modulates the matrix by the length of the vector, which is n.

Try it online!

# Answer
> 0 votes
# Forth (gforth), 53 bytes

```
: f dup 0 do cr dup 0 do i j + over mod . loop loop ;

```

Try it online!

### Explanation

Nested loop that outputs a newline every n numbers

### Code Explanation

```
: f             \ start new word definition
  dup 0 do      \ set loop parameters and loop from 0 to n-1
    cr          \ output a newline
    dup 0 do    \ loop from 0 to n-1 again
      i j +     \ get the sum of the row and column number
      over mod  \ modulo with n
      .         \ print (with space)
    loop        \ end inner loop
  loop          \ end outer loop
;               \ end word definition

```

# Answer
> 0 votes
## Using rotations

# Burlesque, 6 bytes

```
-.rziR

```

Try it online!

```
-. # Decrement input
rz # Range from [0..n)
iR # All rotations of value

```

## Proper calculation

# Burlesque, 19 bytes

```
Jrzl_Jcpq++m[j.%jco

```

Try it online!

```
J      # Duplicate input
rz     # Range from [0..n)
l_     # Pop largest (behind)
Jcp    # Cart product with self
q++m[  # Sum each pair
j.%    # Mod input
jco    # Split list into chunks of input

```

---
Tags: code-golf, math, abstract-algebra
---


title: Overwrite a string on a tape

text:
# Question
Title: Overwrite a string on a tape
Take the string `abcdfghjk`. To overwrite it, starting from `f`, with the string `wxyz`, you would continue along the original, replacing each character with the one from the replacement string. The result would be `abcdwxyzk`.

Now, consider a string which would be too long to fit, like `lmnopqrs`. Starting at `f` you would get `abcdlmnop`, then hit the end of the string. In order to continue, you wrap back to the beginning, resulting in `qrsdefghi`. With a long enough string, you could even wrap around multiple times.

**Task:**

You should take three inputs: the original string, the replacement string, and an index to start replacing at. This can be zero or one indexed.

**Test Cases:**

```
"This is a string"  "That"                  0   ->  "That is a string"
"This is a string"  "That"                  5   ->  "This That string"
"This is a string"  "That"                  14  ->  "atis is a striTh"
"hi"                "Hello there!"          0   ->  "e!"
"hi"                "Hello there!"          1   ->  "!e"
"over"              "write multiple times"  0   ->  "imes"
"over"              "write multiple times"  3   ->  "mesi"

```

**Other:**

This is , shortest answer per language in bytes wins!

# Answer
# Python 3, 39 bytes

```
def f(x,y,z):
	for x[z%len(x)]in y:z+=1

```

Try it online!

-5 bytes thanks to ovs for spotting the trick with cleverly using python's for loop specifics
> 20 votes

# Answer
# Jelly, 8 bytes

```
Ż¡sL}o@ƒ

```

Try it online!

## How it works

Take some of the examples (the two `"over", "write multiple times"` and `"This is a string" "That", 14`), and "layer" them, as though overwriting. At the end, the lowest letter in each column is taken:

```
over    over    This is a string
writ       w                  Th
e mu    rite    at
ltip     mul
le t    tipl
imes    e ti
        mes

imes    mesi    atis is a striTh

```

We reshape the inputs into a matrix like this, then take the final character in each column. In order to offset the "overwriting" string, and to make the final replacement easier, we don't prepend spaces, instead `0`s

```
Ż¡sL}o@ƒ - Main link. Takes R on the left and O on the right, i third
 ¡       - Do the following i times to R:
Ż        -   Prepend 0 to R
    }    - To O:
   L     -   Length of O, L
  s      - Slice into rows of length L
       ƒ - Reduce columnwise by the following, starting with O:
     o@  -   Reversed logical OR, taking the final element,
              or the first, if all zero

```
> 8 votes

# Answer
# Scratch 3.0, 37 blocks / 262 bytes

As ScratchBlocks syntax:

```
define(L)(y)(x)
set[a v]to(1
set[l v]to(length of(L
repeat(l
add(letter(a)of(L))to[T v
change[a v]by(1
end
set[a v]to((y)mod(l
set[! v]to(1
repeat(length of(x
replace item((a)+(1))of[T v]with(letter(!)of(x
change[! v]by(1
set[a v]to(((a)+(1))mod(length
end
say(T

```

I am very glad Scratch has a modulo block built-in, otherwise this would have been pain.

Try it on Scratch!
> 7 votes

# Answer
# vim, ~~33~~ 30 bytes

Thanks for the sweet golf @kops

Pure vim answer, the TIO link is to V, which is a superset of vim. Takes input in 3 lines: index, original string, replacement string. Final buffer is "replaced string" output. 1-indexed.

```
D3gJhmd@"|qqmm`dlD`mR"|@qq@q

```

```
D3gJhmd@"|qqmm`dlD`mR<C-r>"<esc>|mm@qq@q # with unprintables shown

```

Try it online!

Bonus 14 byte V answer, but vim is cooler
> 6 votes

# Answer
# , 31 30 bytes

```
1 :'-@u|.[[`((|i.)~&#)`]}u|.]'

```

Try it online!

Surprisingly hard to find a decent golf in J, given how simple the problem is.

This is a J adverb, modifying the index, and taking the main string as the right arg and the replacement string as the left arg. Eg:

```
'That' (5 f) 'This is a string'

```

This would have been the perfect place to use the semidual version of under `u&.(a:`v)`, but it cost more bytes than explicitly doing the rotation and its reverse.

## how

```
                     u|.]  NB. Rotate by index
                   }~      NB. Replace:
                 `]        NB. String with
      [`                   NB. Replacement chars
        ((|i.)~&#)         NB. At indexes 0...<str len>
                           NB. Each modded by <replacement len>
-@u|.                      NB. Unrotate by index

```
> 5 votes

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

```
(a,b,i)=>b.map(c=>a[i++%a.length]=c)

```

Try it online!

Input two strings as array of characters. Input the integer as 0-indexed. Modify the first string in-place.
> 4 votes

# Answer
# PowerShell, 79 bytes

```
param($x,$y,$i)$y|% t*y|%{$x=$x.remove(($n=$i++%$x.length),1).insert($n,$_)};$x

```

Try it online!
> 4 votes

# Answer
# C (gcc), 50 bytes

```
f(x,y,z)char*x,*y;{for(;*y;z++)x[z*=x[z]>0]=*y++;}

```

Try it online!

-45 bytes thanks to dingledooper with a lot of golfing from someone who actually knows C :P (also inlining `++`, which i forgot about because python doesn't have that)
-1 byte thanks to tsh with a clever trick to set `z` to 0 if `x[z]` is 0, which happens with the null byte after the end of the string
> 3 votes

# Answer
# APL (Dyalog Unicode), 19 bytes

Assumes `⎕IO←0`.

```
{⍺@((⍴⍵)|⍺⍺+⍳⍴⍺)⊢⍵}

```

Try it online!

A dop which takes the index as the left operator operand `⍺⍺`, the original string as right input  and the replacement string as a left input .

`⍳⍴⍺` generate the indices of the replacement string.
`⍺⍺+` add the index offset to each index.
`(⍴⍵)|` each index modulo the length of the original string.
`⍺@(...)⊢⍵` place the replacement string at those indices in the original string.
> 3 votes

# Answer
# Retina 0.8.2, ~~103~~ 78 bytes

```
^.+
$*
(1)*(¶(?<-1>.)*)(.*)¶
$2$3$2
+`¶.(.*)¶(.)
1¶$1$2¶
+`1¶(.*)(.)
¶$2$1
G`.

```

Try it online! Takes the 0-indexed index on the first line. Explanation:

```
^.+
$*

```

Convert the index to unary.

```
(1)*(¶(?<-1>.)*)(.*)¶
$2$3$2

```

Prefix the replacement string with the original string up to the index. This was inspired by @Wezl's sed answer. (Previously I was rotating the original string to bring the index to the beginning.)

```
+`¶.(.*)¶(.)
1¶$1$2¶

```

Rotate the original string, replacing it with characters from the replacement string, keeping track of the number of characters rotated.

```
+`1¶(.*)(.)
¶$2$1

```

Rotate the original string back to its initial position.

```
G`.

```

Remove the now empty working lines.
> 3 votes

# Answer
# , 81 bytes

```
function(o,r,i,`?`=utf8ToInt,`!`=nchar){p=?o;p[1+(i-1+1:!r)%%!o]=?r;intToUtf8(p)}

```

Try it online!
> 3 votes

# Answer
# GNU sed \<4.3 `-E`, ~~125 124~~ 117 bytes

Takes `offset-0-based-unary-~tildes@replacement#textontape` like `~~~~~~~~~~@banana made of mush#This is a tape made of text`. The input tape and replacement cannot contain tilde `~`, at `@`, or hash `#` characters.

```

s/(.*)@/@\1/
:
s/^(.*)@~(.*#\1(.))/\1\3@\2/
t
s/.*@#//
te
s/^(.*)@(.)(.*#\1)./\1\2@\3\2/
s/^(.*)@(.+#)\1$/@\2\1/
t
:e

```

## explanation

`~~~~~~~~~~@banana made of mush#This is a tape made of text`

```
s/(.*)@/@\1/

```

`@~~~~~~~~~~banana made of mush#This is a tape made of text`

`@` is the cursor, which marks the current character

```
:

```

start loop

```
s/^(.*)@~(.*#\1(.))/\1\3@\2/

```

When the cursor is before a tilde `~`, replace the `~` with the corresponding letter from the tape.

```
t

```

If a `~` was replaced, loop again. This works like so:

`@~~~~~~~~~~banana made of mush#This is a tape made of text`

`T@~~~~~~~~~banana made of mush#This is a tape made of text`

`Th@~~~~~~~~banana made of mush#This is a tape made of text`

...

`This is a @banana made of mush#This is a tape made of text`

```
s/.*@#//
te

```

If the cursor has reached the end of the replacement, finish by branching to `e`

```
s/^(.*)@([^~])(.*#\1)./\1\2@\3\2/

```

If the cursor is followed by a not `~` character, advance it and place that character on the tape. It finds its place in the tape with a backreference. Like so:

`This is a @banana made of mush#This is a tape made of text`

`This is a b@anana made of mush#This is a bape made of text`

`This is a ba@nana made of mush#This is a bape made of text`

...

`This is a banana made of mu@sh#This is a banana made of mu`

```
s/^(.*)@([^~]+)#\1$/@\2#\1/

```

If the cursor is at the end of the tape but not the end of the replacement text, remove the replacement text before the cursor so it is now at the start of the line. Like so:

`This is a banana made of mu@sh#This is a banana made of mu`

-\>

`@sh#This is a banana made of mu`

```
t

```

If either of these above two replacements worked, the work is not finished, loop again.

```
:e

```

The end label
> 3 votes

# Answer
# Stax, 8 bytes

```
║H┤1╫╢╘i

```

Run and debug it

input taken as `index, original, replacement`.

## Explanation

```
Fdix+n%%_&
F          for each char in replacement:
 d         delete current iteration
  ix+      add iteration index and input index
     n%    get original's length
       %   modulo by that
           (this is needed because & extends the string when out of bounds)
        _  push current iteration value
         & replace at that index

```
> 2 votes

# Answer
# Red, 54 bytes

```
func[s r i][forall r[s/:i: r/1 i:(i % length? s)+ 1]s]

```

Try it online!
> 2 votes

# Answer
# Charcoal, 16 bytes

```
ＰＳＭＮ→ＦＳ«Ｆ¬ＫＫＭⅈ←ι

```

Try it online! Link is to verbose version of code. Takes the index as the middle input. Explanation:

```
ＰＳ

```

Print the original string without moving the cursor.

```
ＭＮ→

```

Move to the desired index.

```
ＦＳ«

```

Loop over the characters of the replacement string.

```
Ｆ¬ＫＫ

```

If we reached the end of the original string...

```
Ｍⅈ←

```

... then move the cursor back to the beginning.

```
ι

```

Overwrite the original string with the current character of the replacement string.
> 2 votes

# Answer
# Haskell, 67 bytes

```
(s!l@(h:t))i|(a,b:c)<-splitAt i s=(a++h:c)!t$i+1|0<1=s!l$0
(s!_)_=s

```

Try it online!

The relevant function is `(!)`, which takes as input the original string `s`, the replacement string `l` and the index `i` (0-indexed).

## How?

Haskell is definitely the wrong tool for the job, since there is no easy way to replace a character at a given index in a string. As far as I can tell, the best way is to split the string `s` at index `i` in two parts, replace the first character of the second part, and then join them back.

To make up for the immutability of values in Haskell, we define the overwrite function recursively. $$ \text{overwrite}(s,l,i)= \begin{cases} s&\text{if $l=\epsilon$},\\ \text{overwrite}(s,l,0)&\text{if $i\ge\text{length}(s)$},\\ \text{overwrite}(s',l\[1:\],i+1)&\text{where $s'=s$ except for $s'\[i\]=l\[0\]$}. \end{cases} $$
> 2 votes

# Answer
# Java, 41 bytes

```
(o,r,i)->{for(var c:r)o[i++%o.length]=c;}

```

Takes two char arrays and the index as input.

Try it online!
> 2 votes

# Answer
# Ruby, ~~42~~ 39 bytes

```
->a,b,n{b.map{|c|a[n%a.size]=c;n+=1};a}

```

Try it online!

Taking 2 char arrays in input.
> 2 votes

# Answer
# VBA, 105 bytes

```
Function f(x,y,z)
For i=1 To Len(x)
Mid(x,(z Mod Len(x))+1,1)=Mid(y,i,1)
z=z+1
Next
MsgBox x
End Function

```

Chosen VBA instead of VBScript, because VBA has `Mid()` instruction, but VBScript lacks that.

-5 bytes thanks to @BrianJ
> 2 votes

# Answer
# Icon, 55 bytes

```
procedure f(s,r,i)
!r:=:s[i%*s+1]&i+:=1&\z
return s
end

```

Try it online!

`procedure`, `return` and `end` add a lot to the bytecount :)
> 1 votes

# Answer
# Perl 5 `-lF`, 38 bytes

```
$i=<>;$F[$i++%@F]=$_ for<>=~/./g;say@F

```

Try it online!

Input is on three lines:

```
original string
offset
replacement string

```
> 1 votes

# Answer
# Julia 1.0, ~~39~~ 32 bytes

```
a*b*c=b.|>i->a[mod1(c+=1,end)]=i

```

Try it online!

`a` and `b` are expected to be lists of characters, and the function mutates `a`
> 1 votes

# Answer
# Rust, 129 bytes

This is about as close as I could get while maintaining safety

```
|mut x:Vec<u8>,y:Vec<u8>,z:usize|->String{let l=x.len();(z..y.len()+z).for_each(|i|x[i%l]=y[i-z]);String::from_utf8(x).unwrap()};

```
> 1 votes

# Answer
# C (gcc), 50 bytes

```
o(v,e,r)char*v,*e;{for(;*e;r*=!!v[++r])v[r]=*e++;}

```

Try it online!
> 1 votes

# Answer
# TI-Basic, 51 bytes

```
Prompt Str1,Str2,I
Output(8,1,Str1
For(J,1,length(Str2
Output(8,remainder(I,length(Str1)),sub(Str2,J,1
End

```

Output is displayed. Uses 1-based indexing. Only works if the original string is 16 (or 26 on color calculators) or less characters long because of the limited screen width. Replace `remainder(I,length(Str1))` with `length(Str1)fPart(I/length(Str1))` (adds 4 bytes) if run on a calculator before the TI-84+/SE with the 2.53 MP OS.

---

Without using `Output(` (not limited by the screen size):

### 102 bytes

```
Prompt Str1,Str2,I
" "+Str1+" →Str3
For(J,1,length(Str2
1+remainder(I+J-2,length(Str1
sub(Str3,1,Ans)+sub(Str2,J,1)+sub(Str3,Ans+2,length(Str3)-Ans-1→Str3
End
sub(Str3,2,length(Str1

```

Output is stored in `Ans` and displayed. Uses 1-based indexing. Replace `remainder(I+J-2,length(Str1` with `length(Str1)fPart((I+J-2)/length(Str1` (adds 6 bytes) if run on a calculator before the TI-84+/SE with the 2.53 MP OS.
> 1 votes

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


title: Elastic collisions between blocks

text:
# Question
Title: Elastic collisions between blocks
The 3Blue1Brown Youtube channel released a video a year ago called "Why do colliding blocks compute pi?" which describes a model where a block `A` of mass \\$a\\$ slides into a block `B` of mass \\$b\\$, which then pushes block `B` into a wall, causing it to bounce off the wall and then collide again with block `A`.

The miracle of this process is that if \\$a/b = 10^{2n-2}\\$ the number of total collisions (both between `A` and `B` and between `B` with the wall) is given by the first \\$n\\$ digits of \\$\pi\\$.

---

# Example output

```
+-------+---+--------+
| a     | b | output |
+-------+---+--------+
| 1     | 1 | 3      |
| 2     | 1 | 5      |
| 3     | 1 | 5      |
| 4     | 1 | 6      |
| 5     | 1 | 7      |
| 10    | 3 | 6      |
| 7     | 2 | 6      |
| 9     | 2 | 7      |
| 1     | 2 | 3      |
| 1     | 5 | 2      |
| 100   | 1 | 31     |
| 10000 | 1 | 314    |
+-------+---+--------+

```

(These values were calculated using this web applet from Reddit user KyleCow1. Please let me know if I've made any mistakes.)

---

# Challenge

Your challenge is to take two positive integers \\$a, b \in \mathbb N\_{\>0}\\$, and output the number of collisions in this scenario. Your program should be able to handle all \\$a, b \leq 10\\,000\\$. This is a challenge, so the shortest program wins.

# Answer
> 10 votes
# Jelly, ~~10~~ 9 bytes

My first Jelly submission :')

```
÷½ÆṬØP÷Ċ’

```

*-1 byte* thanks to Mr.Xcoder

Uses the formula as in the video. Receives the input flipped; OP gave permission. It probably has room for further golfing, so be sure to give me feedback!

```
÷½        divide b by a and take square root
  ÆṬ      take the ArcTan of that; then
      ÷   divide
    ØP    pi
          by the number we had.
       Ċ  Round up
        ’ and subtract one

```

Try it online

# Answer
> 12 votes
# APL (Dyalog Classic), ~~18~~ 16 bytes

```
¯1+⌈○÷¯3○.5*⍨⎕÷⎕

```

Try it online!

rendered as the equivalent `{¯1+⌈○÷¯3○.5*⍨⍵÷⍺}` in the tio link, to facilitate testing;  means evaluated input;  and  are the arguments to an anonymous function

$$\left\lceil\frac\pi{\textrm{arctg}\sqrt\frac ba}\right\rceil-1$$

(that's the formula from the video. i recommend watching it. it's well explained and the animations are great for building intuition.)

# Answer
> 9 votes
# JavaScript (ES7),  ~~41~~  39 bytes

Takes input as `(a)(b)`.

```
a=>b=>3.14159265/Math.atan((b/a)**.5)|0

```

Try it online!

### How?

Instead of using a *ceil* function and subtracting \\$1\\$, we deliberately use a slightly underestimated approximation of \\$\pi\\$ and *floor* the result with a bitwise OR.

For \\$a,b\le 10000\\$, it was empirically proven to give the same results as this safer 44-byte version:

```
with(Math)f=a=>b=>ceil(PI/atan((b/a)**.5))-1

```

Try it online!

# Answer
> 5 votes
# Haskell, 32 bytes

```
a#b=ceiling(pi/atan(sqrt$b/a))-1

```

Try it online!

# Answer
> 4 votes
# Mathematica, ~~30~~ 29 bytes, 25 characters

```
⌈Pi/ArcTan@Sqrt[#2/#]⌉-1&

```

Try it online

*-1 byte* thanks to ExpiredData

Uses the formula explained in the video.

# Answer
> 4 votes
# Ruby, ~~49~~ 43 bytes

```
->a,b{(-1.arg/((a*b)**0.5+b.i).arg).ceil-1}

```

Try it online!

-5 thans to G B, nicely done

-1 replacing `1i*b` with `b.i`

# Answer
> 4 votes
# C (gcc), <sup>~~63~~ \\$\cdots\\$ ~~47~~</sup> 46 bytes

```
f(a,b){a=ceil(acos(-1)/atan(sqrt(b*1./a)))-1;}

```

Try it online!

*Saved ~~11~~ 12 bytes thanks to ceilingcat!!!*

Uses the formula from the video as ngn recommended.

# Answer
> 4 votes
# Excel, 35 ~~37~~ bytes

-2 bytes thanks to @Chronocidal

```
=CEILING(PI()/(ATAN((B1/A1)^.5)),1)-1

```

# Answer
> 3 votes
# 05AB1E, 30 bytes

```
/t©ažq;‚Δ{ÐO;Å¼®‹èsO;‚}нžqs/î<

```

Try it online!

Almost definitely golfable..

Implements the formula but because 05AB1E doesn't have arctan we have to calculate it, this does it by bisection.

---

# Explanation

```
/t                                - sqrt(a/b)
  ©                               - store this value
   ažq;‚                          - the array [0, pi/2]
        Δ                         - repeat until the array passed in does not change
         {Ð                       - sort then triplicate array
           O;Å¼                   - arctan of the average of the array (bisection)
               ®‹                 - is this greater than the sqrt(a/b)? 0 if so 1 if not
                 èsO;‚            - Take the index from the current two guesses and combine with their average
                      }н          - Stop looping and get the first value
                                  - (this should be close enough to arctan(sqrt(a/b))
                        žqs/      - push pi then divide it by the atan(sqrt(a/b)) guess
                            î<    - ceil and decrement

```

# Answer
> 3 votes
# Rust, 59 bytes

```
|a:f64,b:f64|(f64::acos(-1.)/(b/a).sqrt().atan()).ceil()-1.

```

Try it online!

# Answer
> 3 votes
# J, 19 bytes

```
_1+1p1>.@%_3 o.2%:%

```

Try in Jconsole as the TIO seems to be quite weird.

Usage: `f=:_1+1p1>.@%_3 o.2%:%`

# Example

`f 10000` =\> `314`

# Answer
> 2 votes
# Python 3, 55 bytes

```
lambda a,b:ceil(pi/atan((b/a)**.5)-1)
from math import*

```

Try it online!

# Answer
> 2 votes
# AWK, ~~56~~ 55 bytes

```
{x=atan2(0,-1)/atan2(($2/$1)^.5,1);$0=int(x);$0-=$0~x}1

```

Try it online!

I know I can save a few bytes by hardcoding Pi to some arbitrary precision, but I'm not sure how accurate it is outside of the provided test cases.

# Answer
> 1 votes
# PHP, 46 bytes

```
<?=ceil(pi()/atan(($argv[2]/$argv[1])**.5))-1;

```

Try it online!

Not very original I guess, applying the formula from the video..

---
Tags: code-golf, pi, physics
---


title: I'm a lizard, cut here!

text:
# Question
Title: I'm a lizard, cut here!
Write an \\$n\\$-bytes program \\$AB\\$ such that:

* it outputs an integer \\$x,\ 0\lt x\lt n\\$;
* both its \\$x\\$-byte prefix \\$A\\$ and \\$(n-x)\\$-byte suffix \\$B\\$, when run as programs, output \\$AB\\$.

\\$A, B\\$ and \\$AB\\$ should:

* run in the same language
* not take any input
* use the same output method

This is , so the shortest code in bytes wins (i.e., your score is \\$ n \\$).

## Program example (in a dummy 'lizard language')

With \\$x = 2\\$ bytes, the whole program is `lizard` the first-part program is `li`, and the second-part program is `zard`, then the following behaviour would be expected:

```
 source | output |
--------+--------+
lizard  | 2      |
li      | lizard |
zard    | lizard |

```

# Answer
# Python 2, 123 bytes

```

u="x='\\nu=%r;exec u'%u;print x+`'input(56)'`+x";exec u'input(56)'
u="x='\\nu=%r;exec u'%u;print x+`'input(56)'`+x";exec u

```

Try it online!

outputs 56 and crash.

Both

```

u="x='\\nu=%r;exec u'%u;print x+`'input(56)'`+x";exec u

```

and

```
'input(56)'
u="x='\\nu=%r;exec u'%u;print x+`'input(56)'`+x";exec u

```

return the original code.

---

Here is another version without any crashing of the program:

# Python 2, 141 bytes

```

u="x='\\nu=%r;exec u'%u;print x+`'print 62;exit()'`+x";exec u'print 62;exit()'
u="x='\\nu=%r;exec u'%u;print x+`'print 62;exit()'`+x";exec u

```

Try it online!

---

Thanks to @ovs who helped me to improve my solution.
> 15 votes

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

```
"/+:zQash|2ss}a' 0'rlKH
 0"/+:zQash|2ss}a' 0'rlKH
 0

```

Try it online! Outputs 26.

The two halves (identical, 26 bytes):

```
"/+:zQash|2ss}a' 0'rlKH
 0

```

Try it online! Outputs the original program.

The program path for half and full programs is identical. The only difference is that one more 0 is pushed while going through the 2nd column. If the sum of the top two values is 0, it prints 26 and halts (`ash`). Otherwise:

```
2ss}   Push 34 and place it at the bottom of the stack
a' 0'  Push a newline and ' 0' on the stack
rlK    Reverse the entire stack and push a copy of the entire stack
H      Print each char from top to bottom and halt

```
> 10 votes

# Answer
# Scala 3 `-language:postfixOps`, ~~940~~ 748 bytes

This is a chonky lizard.

```
@main def m:Unit=
 val s="""@main def m:Unit=
 val s=Q%sQ;var x=0;class main extends annotation.Annotation{def dval=print(420);def d=printf(s.replace(""+81.toChar,"\""*3),s,s)}
 return
  new main()dval

 x=0
 @main def n={val s=Q%sQ;printf(s.replace(""+81.toChar,"\""*3),s,s)}""";var x=0;class main extends annotation.Annotation{def dval=print(420);def d=printf(s.replace(""+81.toChar,"\""*3),s,s)}
 return
  new main()dval

 x=0
 @main def n={val s="""@main def m:Unit=
 val s=Q%sQ;var x=0;class main extends annotation.Annotation{def dval=print(420);def d=printf(s.replace(""+81.toChar,"\""*3),s,s)}
 return
  new main()dval

 x=0
 @main def n={val s=Q%sQ;printf(s.replace(""+81.toChar,"\""*3),s,s)}""";printf(s.replace(""+81.toChar,"\""*3),s,s)}

```

`x` is 420.

Try it online!

Try the first x bytes online!

Try the last (n-x) bytes online!

I'm sure I've done something silly here and can make it smaller, but it's really hard editing quines and seeing what's wrong, so I'll try golfing it more later.

First x bytes, prettified (`...` contains the entire program):

```
@main def m: Unit =
  val s = """..."""
  var x = 0
  class main extends annotation.Annotation {
    def dval = print(420)
    def d = printf(s.replace("" + 81.toChar, "\"" * 3), s, s)
  }
  return new main().d

```

Last (n-x) bytes, prettified (`...` contains the entire program):

```
val x = 0
@main def n = {
  val s = """..."""
  printf(s.replace("" + 81.toChar, "\"" * 3), s, s)
}

```
> 10 votes

# Answer
# Vyxal `D`, 44 bytes

```
`:qpd4NẎ[20|`:qpd4NẎ[20|`:qpd4NẎ[20|`:qpd4NẎ

```

Try it Online! Outputs 20.

**Left Side:**

```
`:qpd4NẎ[20|`:qpd4NẎ

```

Try it Online!

**Right Side:**

```
[20|`:qpd4NẎ[20|`:qpd4NẎ

```

Try it Online!

```
`...`:qpd4NẎ[20|`...`:qpd4NẎ
`...`:qp        `...`:qp       Standard Vyxal quine (of the first 24 bytes)
        d               d      Double ^
         4NẎ             4NẎ   Remove the last 4 characters of ^ to make it a quine
            [20|               If the top of stack is true, push 20, otherwise the second quine.

```

The `D` flag allows the character  to be used in string literals
> 9 votes

# Answer
# Haskell, 303 bytes

```
k="\nx=\"k=\"++show k++k++show k\nmain=putStr x where x=\"153\";main=putStr$\"k=\"++show q++q++show q\nq="
x="k="++show k++k++show k
main=putStr x where x="153";main=putStr$"k="++show q++q++show q
q="\nx=\"k=\"++show k++k++show k\nmain=putStr x where x=\"153\";main=putStr$\"k=\"++show q++q++show q\nq="

```

Try it online!

Prints 153.

```
k="\nx=\"k=\"++show k++k++show k\nmain=putStr x where x=\"153\";main=putStr$\"k=\"++show q++q++show q\nq="
x="k="++show k++k++show k
main=putStr x where

```

Try it online!

```
x="153";main=putStr$"k="++show q++q++show q
q="\nx=\"k=\"++show k++k++show k\nmain=putStr x where x=\"153\";main=putStr$\"k=\"++show q++q++show q\nq="

```

Try it online!
> 8 votes

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

```
'r2sslK5+:l)?H1sh"r2sslK5+:l)?H1sh

```

Try it online!

This is composed of two identical sections of code, except one uses `'` and the other uses `"`. The combined program outputs 17 (which is only one byte away from being able to use a single instruction to push the number), which splits them into practically identical programs.

Try the first half online! And the second half!

### Explanation:

```
'r2ss               Push the code on the first line and add a " to the start
     lK             Push a copy of the stack
       5+           Add 5 to the top " making it a '
         :l)?       If the length of the stack is less than 39
             H      Halt and output the stack contents
              1sh   Otherwise print 17

```
> 6 votes

# Answer
## Ruby, 143 bytes

```
$a=%q[a="$a=%q[#$a];eval$a";$><<a+"b='puts 63;exit';"+a];eval$ab='puts 63;exit';$a=%q[a="$a=%q[#$a];eval$a";$><<a+"b='puts 63;exit';"+a];eval$a

```

Outputs «63» and exits. First 63 bytes

```
$a=%q[a="$a=%q[#$a];eval$a";$><<a+"b='puts 63;exit';"+a];eval$a

```

and the rest

```
b='puts 63;exit';$a=%q[a="$a=%q[#$a];eval$a";$><<a+"b='puts 63;exit';"+a];eval$a

```

output the whole quine. I feel like when golfing it inevitably converged towards the existing python solution in the answers. Other approaches seem to all be bigger.
> 0 votes

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