title: Isn't It Ironic? A Little Too Ironic?

text:
# Question
Title: Isn't It Ironic? A Little Too Ironic?
I made a joke the other day and sent it to some friends. One replied back "I love the irony!" and I looked at it and realized there was some irony in it. But that wasn't the irony she saw - the irony she was was the punchline of the joke, which wasn't ironic in the slightest.

And it got me thinking about a certain other instance that isn't ironic at all. And I have to admit, I love that song.

Have you read it's lyrics before? They're so deep!

> An old man turned ninety-eight
> He won the lottery and died the next day
> It's a black fly in your Chardonnay
> It's a death row pardon two minutes too late
> And isn't it ironic... don't you think
>
> It's like rain on your wedding day
> It's a free ride when you've already paid
> It's the good advice that you just didn't take
> Who would've thought... it figures
>
> "Mr. Play It Safe" was afraid to fly
> He packed his suitcase and kissed his kids goodbye
> He waited his whole damn life to take that flight
> And as the plane crashed down he thought
> "Well isn't this nice..."
> And isn't it ironic... don't you think
>
> It's like rain on your wedding day
> It's a free ride when you've already paid
> It's the good advice that you just didn't take
> Who would've thought... it figures
>
> Well life has a funny way
> Of sneaking up on you
> When you think everything's okay
> And everything's going right
> And life has a funny way
> Of helping you out when
> You think everything's gone wrong
> And everything blows up in your face
>
> A traffic jam when you're already late
> A no-smoking sign on your cigarette break
> It's like ten thousand spoons when all you need is a knife
> It's meeting the man of my dreams
> And then meeting his beautiful wife
> And isn't it ironic...don't you think
> A little too ironic...and, yeah, I really do think...
>
> It's like rain on your wedding day
> It's a free ride when you've already paid
> It's the good advice that you just didn't take
> Who would've thought... it figures
>
> Life has a funny way of sneaking up on you
> Life has a funny, funny way of helping you out
> Helping you out

You know what I could really use? I could use a program that would spit out these lyrics. But, just like how this song has nothing ironic in it, you also will not be permitted to use anything ironic in *your* submission. That means no upper or lowercase `i`, `r`, `o`, `n`, or `c` may appear in your program.

The program requires no input, and will output the exact text in the quote. Newlines included, but any trailing whitespace is accidental and you should ignore that. Any punctuation is required.

The usual loopholes are obviously disallowed, and since this is code golf, the lowest score wins.

What would be ironic would be if the restrictions on this make any submission automatically longer than the actual dump of the text.

# Answer
# CJam, 922 bytes

```
0000000: 226d24ae 76dd5d8d d392ac33 f8d0411a e39f4a4d e06683df  "m$.v.]....3..A...JM.f..
0000018: 111b4840 812cd834 74417bdd 80a53e6d 7d821401 8dcca95d  ..H@.,.4tA{...>m}......]
0000030: b89cfb35 4cbab681 8c9388f1 671a4716 4cc4dbb7 bd140682  ...5L.......g.G.L.......
0000048: fe99dbee 429084d0 cd8b1a5e c9b45ad9 84a46cf6 ca92db54  ....B......^..Z...l....T
0000060: bd3946ba 8f1da9d6 7459e9bc 5b355308 11ca8980 93b89bc1  .9F.....tY..[5S.........
0000078: c99970a0 62095d5c 22775afc 9186a457 e560be57 f8802b5e  ..p.b.]\"wZ....W.`.W..+^
0000090: b6d1673a 2801fcca de4aa5f4 dcc1467c 85c2753b 34830614  ..g:(....J....F|..u;4...
00000a8: 98a450c1 0000f7a2 054164dd 03f7b0e1 fcbddaad 65fc061e  ..P......Ad.........e...
00000c0: e3f6ca3f 989db84b fe839256 cdfa77b6 faf437e4 4af60f6b  ...?...K...V..w...7.J..k
00000d8: 4264eabc 7aaceec4 ca8d4bfd 8b9b5c39 fa15d96a 0c36187e  Bd..z.....K...\9...j.6.~
00000f0: 5c220d89 e135beda 1c3b7ea8 1c5a76e5 7c26f929 a5405b1f  \"...5...;~..Zv.|&.).@[.
0000108: 81e4e48c 06139775 66c6d8f1 7be3f55f 70e11e2d f8e68407  .......uf...{.._p..-....
0000120: acce45d9 7b45864b 5c227ffe 3511097f f4df5fec 9fa51d02  ..E.{E.K\"..5....._.....
0000138: ed188eb4 d5f659f0 86ed7ef7 e4fb3d2c ab9b290b 648116db  ......Y...~...=,..).d...
0000150: 50793fea 1aea5dc7 35e40f94 85e8e923 76427675 838b930b  Py?...].5......#vBvu....
0000168: d41f5717 b4da8b45 04319e95 dea4c038 f7a31746 b0c2e427  ..W....E.1.....8...F...'
0000180: 48b7f974 a1a86a11 f1333294 349685f4 c2c19cf3 c2f72aef  H..t..j..32.4.........*.
0000198: e1960cd2 beee3eb0 283f0780 08af8afc 1758b3ca 289f3400  ......>.(?.......X..(.4.
00001b0: 44ede560 ada22ae4 b047cd0f 38c386ca 156544c7 9d1b0f8f  D..`..*..G..8....eD.....
00001c8: fa1a78bc add29de3 d164b548 19a7e766 7ff7a0d7 048b4a97  ..x......d.H...f......J.
00001e0: 5fe076cf ae5c2224 ab1cf23b 54e50911 35775489 deb0c744  _.v..\"$...;T...5wT....D
00001f8: 50958144 c6e5edc8 e72f8bd2 f6ead64d 37d6858a 05838c65  P..D...../.....M7......e
0000210: ddee157c 20a993da 5f2a3366 263d38ed 0e2f39ea 15862e7b  ...| ..._*3f&=8../9....{
0000228: e66426e8 eeb5e1d0 b3a69187 e576c185 c5d818fd 76a933b2  .d&..........v......v.3.
0000240: 1ea9b31a 20030048 81ea5c22 f6ba7e2c 9ab81f9e 5a9802f1  .... ..H..\"..~,....Z...
0000258: 1413edac dbc87a36 94c5a59c d80efd5f 36f70ee5 e6e8c40f  ......z6......._6.......
0000270: c27b3feb 99b18b1c bbe32b4c b080056d 5082ed6c 20135c11  .{?.......+L...mP..l .\.
0000288: 6098307e 9105f9c1 98fbef3c 7c18af20 e3d26dee e551c95b  `.0~.......<|.. ..m..Q.[
00002a0: c438dbd5 08ac18e9 53ee9db8 a9df7950 502e1077 efc23f28  .8......S.....yPP..w..?(
00002b8: fb3e7dee 2d254c2d 5fbd2a47 e0215ace 8a3b06f7 68bd9692  .>}.-%L-_.*G.!Z..;..h...
00002d0: 83e782c9 0f9827a0 0ad637ca d316ceaa 1c35aff6 d14d4024  ......'...7......5...M@$
00002e8: cd5a59b6 30f97e6c 18c6088e 07c17673 3a0b58b1 9bdde15b  .ZY.0.~l......vs:.X....[
0000300: a6f1cad0 ca8e3e8f bb8ffb60 e44867ea eb4a7d57 bebcb540  ......>....`.Hg..J}W...@
0000318: 7d37712d cc16dd7b 0e5b33f4 03dabc21 fae78a91 8df8eac6  }7q-...{.[3....!........
0000330: 3f231dd0 4b6b5c22 c5f1ae77 bc99c3b2 eb96bbf6 da7ab52b  ?#..Kk\"...w.........z.+
0000348: bdf913c6 e55f54cb 105015f2 c76d3cc4 2227ff2c 224b5451  ....._T..P...m<."'.,"KTQ
0000360: 50452232 662d5f65 6c2b2d66 23323435 62343362 220e2426  PE"2f-_el+-f#245b43b".$&
0000378: 2b303132 45474c4d 50515354 575b5d22 34666d32 352c2761  +012EGLMPQSTW[]"4fm25,'a
0000390: 662b2b66 3d27712f 292a                                 f++f='q/)*

```

The above is a reversible xxd dump. The source code contains way to many unprintable characters for the online interpreter...

The source code is generated by the following program:

```
q"

It's like rain on your wedding day
It's a free ride when you've already paid
It's the good advice that you just didn't take
Who would've thought... it figures

":X/Xa+'q*"^N$&+012EGLMPQSTW[]"4fm25,'af++f#43b245b'ÿ,"KTQPE"2f-_el+-f=`"'ÿ,\"KTQPE\"2f-_el+-f#245b43b\"^N$&+012EGLMPQSTW[]\"4fm25,'af++f='q/)*"

```

Here, `^N` represents the control character with code point 14.

### Verification

```
$ LANG=en_US
$ xxd -r -ps > gen.cjam <<< 71220a0a49742773206c696b65207261696e206f6e20796f75722077656464696e67206461790a49742773206120667265652072696465207768656e20796f7527766520616c726561647920706169640a497427732074686520676f6f6420616476696365207468617420796f75206a757374206469646e27742074616b650a57686f20776f756c642776652074686f756768742e2e2e20697420666967757265730a0a223a582f58612b27712a220e24262b30313245474c4d50515354575b5d2234666d32352c2761662b2b66233433623234356227ff2c224b545150452232662d5f656c2b2d663d602227ff2c5c224b545150455c2232662d5f656c2b2d6623323435623433625c220e24262b30313245474c4d50515354575b5d5c2234666d32352c2761662b2b663d27712f292a22
$ cjam gen.cjam < song | grep -i IRONIC
$ cjam gen.cjam < song | wc -c
922
$ cjam <(cjam gen.cjam < song) | md5sum - song
3b1a473c910233d91d0e283a43cbcab2  -
3b1a473c910233d91d0e283a43cbcab2  song

```

### Explanation

The code starts by placing a string of characters (the encoded song) on the stack.

```
'ÿ,        e# Push the string of all characters with code points below 255.
"KTQPE"2f- e# Push "IRONC" by subtracting 2 from each code point.
_el+       e# Concatenate with the lowercase counterparts.
-          e# Remove these characters from the string.
f#         e# Replace each character from the encoded song by its index in this string.
245b43b    e# Convert the resulting array of integer from base 245 to base 43.
"^N$&+012EGLMPQSTW[]\"4fm
           e# Subtract 4 from each code point.
25,'af++   e# Append the lower case letters from a to y to that string.
f=         e# Replace each integer in the base 245 array by the corresponding character.
'q/        e# Split the result at all occurrences of 'q'.
)*         e# Pop the last string (chorus) and insert it between the remaining chunks.

```
> 4 votes

# Answer
# Ironic, Java, 4009 bytes, ~~312.49%~~ 256.82% size of original.

```
publ\u0069\u0063 \u0063lass \u0049\u0072\u006F\u006e\u0069\u0063{publ\u0069\u0063 stat\u0069\u0063 v\u006F\u0069d ma\u0069\u006e(St\u0072\u0069\u006eg[]a\u0072gs){System.\u006Fut.p\u0072\u0069\u006et("A\u006e \u006Fld ma\u006e tu\u0072\u006eed \u006e\u0069\u006eety-e\u0069ght\\u006e"+"He w\u006F\u006e the l\u006Ftte\u0072y a\u006ed d\u0069ed the \u006eext day\\u006e"+"\u0049t's a bla\u0063k fly \u0069\u006e y\u006Fu\u0072 \u0043ha\u0072d\u006F\u006e\u006eay\\u006e"+"\u0049t's a death \u0072\u006Fw pa\u0072d\u006F\u006e tw\u006F m\u0069\u006eutes t\u006F\u006F late\\u006e"+"A\u006ed \u0069s\u006e't \u0069t \u0069\u0072\u006F\u006e\u0069\u0063... d\u006F\u006e't y\u006Fu th\u0069\u006ek\\u006e"+"\\u006e"+"\u0049t's l\u0069ke \u0072a\u0069\u006e \u006F\u006e y\u006Fu\u0072 wedd\u0069\u006eg day\\u006e"+"\u0049t's a f\u0072ee \u0072\u0069de whe\u006e y\u006Fu've al\u0072eady pa\u0069d\\u006e"+"\u0049t's the g\u006F\u006Fd adv\u0069\u0063e that y\u006Fu just d\u0069d\u006e't take\\u006e"+"Wh\u006F w\u006Fuld've th\u006Fught... \u0069t f\u0069gu\u0072es\\u006e"+"\\u006e"+"\"M\u0072. Play \u0049t Safe\" was af\u0072a\u0069d t\u006F fly\\u006e"+"He pa\u0063ked h\u0069s su\u0069t\u0063ase a\u006ed k\u0069ssed h\u0069s k\u0069ds g\u006F\u006Fdbye\\u006e"+"He wa\u0069ted h\u0069s wh\u006Fle dam\u006e l\u0069fe t\u006F take that fl\u0069ght\\u006e"+"A\u006ed as the pla\u006ee \u0063\u0072ashed d\u006Fw\u006e he th\u006Fught\\u006e"+"\"Well \u0069s\u006e't th\u0069s \u006e\u0069\u0063e...\"\\u006e"+"A\u006ed \u0069s\u006e't \u0069t \u0069\u0072\u006F\u006e\u0069\u0063... d\u006F\u006e't y\u006Fu th\u0069\u006ek\\u006e"+"\\u006e"+"\u0049t's l\u0069ke \u0072a\u0069\u006e \u006F\u006e y\u006Fu\u0072 wedd\u0069\u006eg day\\u006e"+"\u0049t's a f\u0072ee \u0072\u0069de whe\u006e y\u006Fu've al\u0072eady pa\u0069d\\u006e"+"\u0049t's the g\u006F\u006Fd adv\u0069\u0063e that y\u006Fu just d\u0069d\u006e't take\\u006e"+"Wh\u006F w\u006Fuld've th\u006Fught... \u0069t f\u0069gu\u0072es\\u006e"+"\\u006e"+"Well l\u0069fe has a fu\u006e\u006ey way \\u006e"+"\u004Ff s\u006eeak\u0069\u006eg up \u006F\u006e y\u006Fu\\u006e"+"Whe\u006e y\u006Fu th\u0069\u006ek eve\u0072yth\u0069\u006eg's \u006Fkay \\u006e"+"A\u006ed eve\u0072yth\u0069\u006eg's g\u006F\u0069\u006eg \u0072\u0069ght\\u006e"+"A\u006ed l\u0069fe has a fu\u006e\u006ey way \\u006e"+"\u004Ff help\u0069\u006eg y\u006Fu \u006Fut whe\u006e\\u006e"+"Y\u006Fu th\u0069\u006ek eve\u0072yth\u0069\u006eg's g\u006F\u006ee w\u0072\u006F\u006eg \\u006e"+"A\u006ed eve\u0072yth\u0069\u006eg bl\u006Fws up \u0069\u006e y\u006Fu\u0072 fa\u0063e\\u006e"+"\\u006e"+"A t\u0072aff\u0069\u0063 jam whe\u006e y\u006Fu'\u0072e al\u0072eady late\\u006e"+"A \u006e\u006F-sm\u006Fk\u0069\u006eg s\u0069g\u006e \u006F\u006e y\u006Fu\u0072 \u0063\u0069ga\u0072ette b\u0072eak\\u006e"+"\u0049t's l\u0069ke te\u006e th\u006Fusa\u006ed sp\u006F\u006F\u006es whe\u006e all y\u006Fu \u006eeed \u0069s a k\u006e\u0069fe\\u006e"+"\u0049t's meet\u0069\u006eg the ma\u006e \u006Ff my d\u0072eams\\u006e"+"A\u006ed the\u006e meet\u0069\u006eg h\u0069s beaut\u0069ful w\u0069fe\\u006e"+"A\u006ed \u0069s\u006e't \u0069t \u0069\u0072\u006F\u006e\u0069\u0063...d\u006F\u006e't y\u006Fu th\u0069\u006ek\\u006e"+"A l\u0069ttle t\u006F\u006F \u0069\u0072\u006F\u006e\u0069\u0063...a\u006ed, yeah, \u0049 \u0072eally d\u006F th\u0069\u006ek...\\u006e"+"\\u006e"+"\u0049t's l\u0069ke \u0072a\u0069\u006e \u006F\u006e y\u006Fu\u0072 wedd\u0069\u006eg day\\u006e"+"\u0049t's a f\u0072ee \u0072\u0069de whe\u006e y\u006Fu've al\u0072eady pa\u0069d\\u006e"+"\u0049t's the g\u006F\u006Fd adv\u0069\u0063e that y\u006Fu just d\u0069d\u006e't take\\u006e"+"Wh\u006F w\u006Fuld've th\u006Fught... \u0069t f\u0069gu\u0072es\\u006e"+"\\u006e"+"L\u0069fe has a fu\u006e\u006ey way \u006Ff s\u006eeak\u0069\u006eg up \u006F\u006e y\u006Fu\\u006e"+"L\u0069fe has a fu\u006e\u006ey, fu\u006e\u006ey way \u006Ff help\u0069\u006eg y\u006Fu \u006Fut\\u006e"+"Help\u0069\u006eg y\u006Fu \u006Fut");}}

```

### Instructions:

Place in file named: `Ironic.java`
Compile with: `javac Ironic.java`
Run with: `java Ironic`
> 3 votes

# Answer
# PHP, 956 Bytes

compressed string -\> base64 encoded -\> replacement of not allowed chars

```
<?=((gz.(k&m).(J^"$").flate)((base64_de.(k&g).(j|g).de)((st.(v&z).t.(v&z))("3VTBbtswDL37K4h)em]zD8EuK7BhA3}}dmQs2lIt<4FE1fPfj5TTpg2y+zAgh1h6e]zvkdIhAU)HMyaQmhM5S(G=_A8U=</dV4KFd)sT=BahvAImBy4}0BYT/=ZwuHaP)l)A4=<x]2(IK4QEK9)MXzxmxyldMI5QPG=e4[S2QBaG{aQqVE(YIaJQd9Ay}aQ7ga(/z(]0+/0eFK9LyqzlQ5q6jTSG<S(j1u=z2YW)(2]8qG3IpKDg1JK]B_t7J)(Y(d2qW}Lbk{Z_ZHaA7jX0p[+4VXyp=)0GZw}EJ+qePWs8[T}jEs9VIz{=q]gIY81Uum73Pe/hZ8QVHgWe)KAdLKhyBpW_GbKFZTGf[Dg[1Y)(pQbpsV(Legql][e]4EpTdlypdQaD]L)Wz5HU7Jw0<4GM1x=u2}fYemmJ4mbvFDE=9BmLVwLHSwL/7qDbPV{M5/DF2DV7Ul+7/6YpzWALym[TUV[a[)+1+zFASYSTyay]s3Ll3L=t/}Be9SLY31GV8aTHLJhPqyMbQ34P/m/FPMWTIY2)q7QUul+3K42sTVs09fGq]l47X}_pfbt1A/bUdQeQjMMQe]jB+=JwvgS8XTVI/FBmbqZLG(8[68{ImfTew1Hx04e+(qUWb_EZLSfmVLY(qMmamU=ks6J+p6Tet6MzkVg=66Y9{TzAvIJT7_k0T2IUbygbvS[hlTDU(Iux3B7A6/k7qEa=S{01eUep0]tY(f09PIKWjPpK{d6{6Pa/P7XfbsyQ=XhjYK+h959PXE2dP<afvv8A",["("=>K&G,")"=>k&g,"<"=>K&M,"<"=>k&m,"["=>j^"$","]"=>J^"$","{"=>J|G,"}"=>j|g,"="=>V&Z,_=>v&z]))));

```

Try it online!
> 1 votes

---
Tags: code-golf, kolmogorov-complexity, restricted-source
---


title: Ring me when our cup noodles are ready

text:
# Question
Title: Ring me when our cup noodles are ready
I'm currently cooking us some cup noodles, but we're really sleepy at the moment. They'll be finished in 50 seconds from now, can you wake me up then?

## Problem:

Write a program or function that waits 50 seconds of busy waiting (so that you too doesn't sleep) and then outputs at least 1 visible character to wake me up.

## Busy waiting:

You can't use functions like `sleep` or `delay` or `pause` to wait for the 50 seconds, you have to keep checking the elapsed time.

## Rules:

* Your code must be somewhat consistent in time, between runs and between computers. A small error of +- 1 seconds is acceptable.
* You can't output any visible characters between 1 and 50 seconds (let me sleep).
* Whitespace characters (newline, space, tab, ...) are not considered visible characters for this challenge.
* This is , so shortest code wins.

# Answer
# MATL, 7 bytes

```
1`Z`50<

```

Try it online! The linked code uses `10` instead of `50`.

### Explanation

```
1        % Push 1
`        % Do...while
  Z`     %   Elapsed time since program started
  50     %   Push 50
  <      %   Less than?
         % End (implicit). The loop continues if top of the stack is truthy
         % Display (implicit)

```
> 12 votes

# Answer
# Octave, ~~22~~ 21 bytes

Saved one byte by changing from `while ... end` to `do ... until`.

```
tic;do
until toc>50;1

```

`tic` starts a timer, while `toc` returns the number of decimal seconds since the last call to `tic`. We initiate a **do - until** loop, where we'll loop until `toc>50`, doing nothing inside the loop. The loop stops after 50 seconds, followed by `ans = 1` on the screen.

Try it on **TIO** (time changed to 5 seconds) or paste it into **Octave Online**.
> 19 votes

# Answer
# Lua, 35 bytes

```
while os.clock()<50 do end;print'!'

```

odd thing is that it has exactly the same length as:

```
repeat until os.clock()>50;print'!'

```

Try it online!
> 11 votes

# Answer
# TI-Basic, ~~14~~ 12 bytes

```
startTmr
While 50>checkTmr(Ans
End

```

(Ab)uses the fact that TI programs output `Done` if nothing is evaluated on the last line.
> 8 votes

# Answer
# **Perl 5.10, 21 bytes**

```
{$^T+50<time?do:redo}

```

Outputs "Null filename used at -e line 1." after \[50,51) seconds.

Or **22 bytes** for Perl 5.22:

```
{$^T+50<time?die:redo}

```
> 7 votes

# Answer
# Python 2, ~~57~~ 54 bytes

*-3 bytes thanks to Felipe Nardi Batista.*

```
from time import*
b=time()+50
while time()<b:0
print 1

```

Try it online!

## Another solution, 48 bytes

This answer will only work if printing to STDERR is allowed. This will end in a NameError, printing *much* more than one character.

```
from time import*
b=time()+50
while time()<b:0
a

```
> 6 votes

# Answer
## C, ~~45~~ ~~44~~ 43 bytes

```
i;f(){for(time(&i);time(0)-i<50;);puts(f);}

```

See it work here.
> 5 votes

# Answer
# APL (Dyalog), 21 bytes

-1 thanks to marinus.

```
{3⊃⍵≥⎕AI:∇⍵⋄1}5e4+⎕AI

```

`⎕AI`**A**ccount **I**nformation (UserID, ComputeTime, ConnectTime, KeyingTime)

`5E4+` add 50000 (milliseconds)

`{` apply the following anonymous function where the argument is represented by

\[if the\]

`3⊃` third item (truth value, i.e that of ConnectTime) of
`⍵≥⎕AI` is greater than or equal to **A**ccount **I**nformation

`:` then

`∇⍵` recurse this function on the unmodified argument

else

`1` return one

`}` \[end of anonymous function\]

Try it online! *Debug* says *Real time: 50.039 s*, or *disable output cache* for real-time effect.
> 5 votes

# Answer
## Bash, 26 bytes

```
f()(((SECONDS<50))&&f);f;.

```

Partially ungolfed:

```
f () (
  ((SECONDS < 50)) && f
)
f
.

```

`SECONDS` is a magic variable that counts the number of seconds since the shell started. I define a function that recurses until the value is below the threshold. Once the wait is over, run the builtin `.` which prints an error message because it's missing an argument.

Beware that since the function's body is in parentheses, bash forks a new process for each recursive invocation, which may consume a lot of entries in your process table. A loop would keep resource usage down, but it's longer.

```
for((;SECONDS<50;));do :;done;.

```

If you want to have output on standard output rather than to the screen and you're running a sufficiently Unix-like system with at least one user logged in, you can replace the final `.` by `w`. If you want to stick to pure bash then I can't think of a way to produce output in less than **28 bytes**.

```
f()(((SECONDS<50))&&f);f;pwd

```
> 5 votes

# Answer
# 05AB1E, ~~16~~ 14 bytes

```
žc50+60%[DžcQ#

```

Try it online!

I'm new to 05AB1E, so any golfing tips would be appreciated.

**Explanation:**

```
žc50+60%[DžcQ#
žc               Push current amount of seconds.
  50+            Add 50.
     60%         Modulo 60.
        [        Infinite loop.
         D       Duplicate top of stack
          žc     Push current seconds.
            Q#   If current seconds, and start time+50 are the same, break.
                 Implicit print.

```

The basic idea of this program is to get what the time will be in 50 secs and loop until the current time is equal. So to get the time in 50 seconds, it gets the current time and adds 50. Then, since 05AB1E's clock returns the time since the last minute change, it needs to modulo 60, to get back in the correct range. Then the program loops until the second amount is the same as the desired.
> 3 votes

# Answer
# Pyth, 9 bytes

```
W>50.d1;G

```

Try it here.
> 3 votes

# Answer
# Javascript, ~~43~~ ~~39~~ ~~37~~ ~~35~~ ~~34~~ 33 bytes

```
for(t=+new Date;new Date<t+5e4;)1

```

Outputs `1` after 50 seconds.

Open console and run snippet. The snippet only runs for 5 seconds, so your page won't stall for too long :)

```
for(t=+new Date;new Date<t+5e3;)1
```

*Saved **10(!)** bytes thanks to @CraigAyre*:

* 43 : `t=+new Date();while(+new Date()<t+50000)0;x`
* 39 : `t=+new Date;while(+new Date<t+50000)0;x`
* 37 : `t=+new Date;while(+new Date<t+5e4)0;x`
* 35 : `t=+new Date;while(new Date<t+5e4);x`
* 34 : `t=+new Date;while(new Date<t+5e4)1`
* 33 : `for(t=+new Date;new Date<t+5e4;)1`
> 3 votes

# Answer
# PHP, ~~42~~ 36 bytes

```
for($t=time();time()-$t<50;);echo 1;

```
* -6 bytes, thanks to @Titus

**How to run**

```
> php -r <code>

```
> 3 votes

# Answer
# Processing, 47 bytes

```
void draw(){if(millis()>5e4){print(X);exit();}}

```

After 50 seconds, the program prints `0` and exits.
> 2 votes

# Answer
# Bash, 68 43 bytes

```
for((e=`date +%s`+50;`date +%s`<e;)){ :;};w

```

Lists logged in users after 50 seconds.

**Edit:** Thanks a lot, **manatwork**! -25 bytes.

Try it online!
> 2 votes

# Answer
# Java, ~~116~~ ~~114~~ ~~109~~ 105 bytes

* -2 bytes, thanks to @jaxad0127
* -4 bytes, thanks to @KevinCruijssen

**Try Online**

```
double t(){return System.nanoTime();}
void w(){for(double s=t();t()-s<5e+10;);System.out.print("\0007!");}

```

**Note** on unix, this should *ring* a beep.
> 2 votes

# Answer
# PowerShell, 38

```
for($d=(date)+[int]5e8;(date)-lt$d){}1

```

Very trivial; will just wait until the time is 50 seconds later and then prints `1`.
> 2 votes

# Answer
# C# - 100 bytes

```
using System;
void q(){var t=DateTime.Now.AddSeconds(50);
while(DateTime.Now<t);
Console.Write(t);
}

```
> 2 votes

# Answer
# x86 16 bit machine code on MS-DOS - 21 bytes

```
00000000  53 1f a1 6c 04 05 8e 03  3b 06 6c 04 77 fa b2 6e  |S..l....;.l.w..n|
00000010  b4 02 cd 21 c3                                    |...!.|
00000015

```

Commented assembly:

```
    org 100h

section .text

start:
    push bx             ; notice: bx starts as 0
    pop ds              ; set the data segment to 0; this allows us to
                        ; read the tick count without segment selectors
    mov ax,word [046ch] ; read the low 16 bit of the tick count
    add ax,910          ; 910 ticks = 49.98 seconds
                        ; here we used ax because the encoding for both
                        ; the mov and the add is one byte shorter
lop:
    cmp ax,word [046ch] ; compare the stop time with the current time
    ja lop              ; loop if still above
    mov dl,'n'          ; n is for noodles
    mov ah,2
    int 21h             ; print
    ret                 ; quit

```

This could be shaved down to 16 bytes by replacing the final three instructions with `int 18h`, which on ancient machines would invoke the ROM built-in BASIC interpreter and almost everywhere else prints something like "No ROM BASIC" and reboot after a key press, but after discussing this with OP it was decided that this wouldn't be allowed.

### Interrupt + self-modifying code approach - 23 bytes

This is another approach; it turns out to be bigger, but I post it anyway because it is way more fun.

```
00000000  b8 1c 25 ba 12 01 cd 21  b9 8e 03 e2 fb b4 02 cd  |..%....!........|
00000010  21 c3 ff 0e 09 01 cf                              |!......|
00000017

```

```
    org 100h

section .text

%define counter lop+1   ; see below
start:
    ; setup interrupt handler
    mov ax,251ch                ; function 25h (replace interrupt vector)
                                ; interrupt 1ch (user timer)
    mov dx,interrupt_handler    ; timer ISR
    int 21h
lop:
    mov cx,910  ; the 910 immediate value is actually pointed by counter,
                ; which is decremented in interrupt_handler
    loop lop    ; decrement and loop as long as cx is nonzero (the decrement is
                ; not relevant, we are always resetting cx at each iteration)
    mov ah,2    ; function 2 (print character); dl is already a printable character
    int 21h
    ret         ; quit

interrupt_handler:
    dec word[counter]   ; at every tick decrement the counter
    iret

```
> 2 votes

# Answer
# PHP, 43 bytes

I think when you´re sleepy, your ears are more alert than your eyes, so:

```
for($t=time();;)echo chr(time()-$t<50?9:7);

```

prints horizontal tabs in the first 50 seconds, BEL codes after that. Run with `-r`.
> 2 votes

# Answer
## R, 41 bytes

```
s=Sys.time;x=s();while(s()-x<50){};cat(1)

```
> 2 votes

# Answer
## Ruby, ~~36 33~~ 35 bytes

```
t=Time.now;1until Time.now-t>50;p 1

```

Ruby handily supports subtraction of `Time` objects, returning the difference in seconds. Prints the character 1 (being Ruby's internal representation of the entity `1`) when done.

**Edit:** saved 2 bytes by changing to an error message, 1 byte thanks to G B **Edit:** re-added 2 bytes (stderr doesn't count)
> 2 votes

# Answer
**C#, 73 bytes**

`var n=DateTime.Now.AddSeconds(50);while(DateTime.Now<n);Console.Write(n);`
> 2 votes

# Answer
# Aceto, 16 bytes

```
6+_p
*-iX
59
Tt<

```

Sets a `T`imer, reads the `t`imer difference and pushes it on the stack. Pushes `9` and `5`, multipl`*`es them, pushes `6`, `+`dds them. We now have a 51 on the stack (on top of the initially small-ish timer number). We substr`-`ct them from each other, getting initially something a little bit bigger than 51. We cast it to an `i`nteger, and mirror (`_`) if the integer is truthy (i.e. not 0). In that case, we go to the left (`<`) and check our timer again, going into a loop. Otherwise, we `p`rint 0 from the empty stack, and e`X`it.

After 50 seconds, the timer will be 50+ε for some small ε, meaning our subtraction yields 50+ε-51 = -ε, since ε is smaller than 1 the corresponding integer will be 0.
> 2 votes

# Answer
## C, ~~41~~ ~~43~~ 39 Bytes

```
a;b(c){time(c?0:&a)-a>50?puts(b):b(1);}

```

Try it online
> 2 votes

# Answer
## REXX, 33 bytes

```
do while time(e)<50
  nop
  end
say a

```
> 1 votes

# Answer
## C#, ~~91~~ 77 bytes

```
n=()=>System.DateTime.Now;_=>{var t=n();while((n()-t).Seconds<50);return t;};

```
> 1 votes

# Answer
# T-SQL, 62 bytes

```
DECLARE @ DATETIME=GETDATE()WHILE DATEDIFF(S,@,GETDATE())<50_:

```

After the execution in SSMS, this will print the message "Command(s) completed successfully." plus a bell sound \[bonus :)\].
> 1 votes

# Answer
# AWK, 48 bytes

```
BEGIN{for($0=systime();systime()-$0<50;)1;print}

```

Try it online!

This assumes that input is not allowed.
> 1 votes

# Answer
# Swift - 41 bytes

Just outgolfing @Samira's answer, improving it drastically

```
var d=Date()+50;while Date()<d{};print(d)

```

Prints the date it started running to wake one up, e.g: if it's ran at 12:38 UTC, it outputs `2017-05-12 12:38:51 +0000` after 50 seconds.
> 1 votes

# Answer
# Swift , 108 bytes

```
 var a=Date().addingTimeInterval(59.0);while(Date().timeIntervalSinceNow<a.timeIntervalSinceNow){};print("W")

```
> 0 votes

# Answer
# VBA, 98 Bytes

Not sure if allowed...but here! It waits a single second, but doesn't wait the whole time. Still working on the language!

```
Sub Tm()
For i = 0 To 50
    If i = 50 Then
        MsgBox "!"
    Else
    Application.Wait (Now + TimeValue("0:00:01"))
    End If
Next i
End Sub

```
> 0 votes

# Answer
# JS (ES6), 64 bytes

```
i=0,r=Date.now();while(1)Math.abs(Date.now()-r-5e4)>50?0:alert()

```
> 0 votes

# Answer
# Windows Batch, ~~123 121 126 122 112 111 107 100~~ 95 bytes

```
@set/ae=1%TIME:~6,2%+50-100
@if %e% geq 60 @set/ae-=60
:w
@if %e% neq %TIME:~6,2% @goto w
@cd

```

Explanation:

```
@set /a e=1%Time:~6,2%+50-100               ::Calcuate the result time
@if %e% geq 60 @set/ae-=60                  ::If result time > 59, set it to correct time

:w                                          :: Marker of the wait loop
@if %e% equ %TIME:~6,2% (cd)else (@goto w)  ::Returns current dir when program ended
                                            :: Or Else go back to wait for loop

```
> 0 votes

# Answer
## C#, 72 bytes

```
for(var x=DateTime.Now;DateTime.Now<x.AddSeconds(50););Console.Write(0);

```
> 0 votes

# Answer
This may be foul play.

## Bash, 24 Bytes

```
ping 192.0.0.8 -rqc50|wc

```

To verify +6 bytes

```
ping 192.0.0.8 -rqc50|tail -n2

```

`192.0.0.8` is IPv4 dummy address. It send packet for 50 times in one second interval because it would not be reached.
> -1 votes

---
Tags: code-golf, date
---


title: PPCG's Unanswered Questions

text:
# Question
Title: PPCG's Unanswered Questions
This dear StackExchange site has so many challenges, and so many good answers. But what about the challenges that were never answered?

## Task

Write a program or a function that will print a pseudo-random open unanswered (as in, a question with exactly zero answers) challenge from PPCG. All possible challenges should be produced with the same probability.

## Input

* No input will be taken.

## Output

* Must only be the title, tags and the link which should be separated by newlines.
    + The title must be exactly like it is in the challenge.
    + The tags don't have a strict output format but must include all tags.
    + The link may or may not include the `question-name` after the question id and must lead to the challenge.
* May or may not be translated to a human readable format.
    + `&` to `&`
* Leading and trailing whitespace is allowed.

## Examples

```
Encode a steganographic encoder into a package
code-challenge,unicode,steganography
https://codegolf.stackexchange.com/questions/65159/encode-a-steganographic-encoder-into-a-package

Simple predictive keyboard CG
code-golf
https://codegolf.stackexchange.com/questions/76196/simple-predictive-keyboard-cg

```

## Scoring

As this is , shortest answer in bytes wins.

# Answer
# JavaScript + HTML, ~~271~~ ~~250~~ 232 bytes

*Apparantly you can use `Date`s as pseudo-random numbers. I stole this from Shaggy's answer.*

(Only uses about 4 of your quota)

```
q=[]
g=f=>fetch('//api.stackexchange.com/questions/unanswered?site=codegolf&page='+f).then(r=>r.json().then(j=>(q=[...q,...j.items])^j.has_more?g(f+1):document.write(`<pre>${(q=q[new Date%q.length]).title}
${q.tags}
`+q.link)))
g(1)
```

It makes an array `q`, then calls `g(1)`, which fetches the first page of results and adds it to q. Then, if the request says it `has_more`, then it calls `g(f+1)`, which fetches the next page, until it reaches the end and writes out to the HTML document (Which will automatically unescape the response)

If we don't care about *all* of the unanswered questions, just the most recent 30 (Only uses 1 of your quota):

## JavaScript + HTML, ~~213~~ ~~196~~ 179 bytes

```
fetch`//api.stackexchange.com/questions/unanswered?site=codegolf`.then(r=>r.json().then(j=>document.write(`<pre>${(j=j.items[new Date%j.items.length]).title}
${j.tags}
`+j.link)))
```
> 8 votes

# Answer
# Python + requests + json + random + html, ~~249~~ 239 bytes

```
import requests as r,json,random as R,html
j=R.choice(json.loads(r.get('http://api.stackexchange.com/questions/no-answers?site=codegolf').text)['items'])
print('\n'.join([html.unescape(j['title']),'Tags: '+', '.join(j['tags']),j['link']]))

```

Turned out longer than I'd like.

-10 bytes thanks to @totallyhuman by using `R.choice` rather than `R.shuffle` and taking the first element.
> 6 votes

# Answer
# Bash 255 232 bytes

```
a="api.stackexchange.com/questions/";b="?site=codegolf";c=$(w3m $a"unanswered"$b"&filter=total"|tr -cd 0-9);w3m $a"no-answers"$b"&pagesize=1&page="$((RANDOM%c))|jq -r ".items[0]|.title,(.tags|join(\", \")),.link"|recode html..utf-8

```

Looks like a wrong results returns for totals for no-answers/unanswered. General idea - get total, than get random page with one item.

# Bash 174 153 bytes

```
w3m api.stackexchange.com/questions/no-answers?site=codegolf|jq -r ".items[$RANDOM%(.items|length)]|.title,(.tags|join(\", \")),.link"|recode html..utf-8

```

It select one random question from last 30, not from all questions. Works from command line. Required curl w3m, jq and recode.

result:

```
Tips for golfing in Charcoal
code-golf, tips
https://codegolf.stackexchange.com/questions/117269/tips-for-golfing-in-charcoal

```
> 0 votes

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


title: Make a flag wave

text:
# Question
Title: Make a flag wave
Take a flag, like this one:

```
-----------------------------
|             |             |
|             |             |
|=============+=============|
|             |             |
|             |             |
-----------------------------

```

And a number input: the "wave length"

Say the wave length was 5. Then, every 5 characters along the line from the beginning, replace the next character a `-` with `\` and shift all the characters after it one row down. Repeat this until the end. You end up with:

```
-----\
|     -----\
|           -----\
|=====        |   -----\
|     ======  |         -----
|           ==+===          |
-----\        |   ======    |
      -----\  |         ====|
            -----\          |
                  -----\    |
                        -----

```

If you end up not being able to make a full wave length along at the end, the flag is finished. Just remain flat until the end.

You can assume that all the lines are of the same length and that the top and bottom lines are composed entirely of `-` (0x2D) and the rest of the characters are in `!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~`, or is a space (). (So it's ascii value is `x`, where `31 < x < 127`)
The flag will be at least 3 tall and 3 wide.

Wave length will be a non-negative integer (\>= 0).

(You can also have wave length 1 be the smallest wavelength, so the above example would have wave length 6. This is OK.)

Your i/o of flag can be as arrays of lines or a string with multiple lines.

The output flag may have trailing spaces, but can only have leading spaces so long as it is the same on every flag. Trailing space on an input flag may be deleted.

## Scoring

This is code-golf, so the shortest solution, in bytes, wins.

## Test cases

```
---
abc
---
2
--\
abc
--\

-----
| + |
-----
10
-----
| + |
-----

---------------------------------------
|&&&&&&                         &&&&&&|
|&&&&&&                         &&&&&&|
|&&&&&&                         &&&&&&|
|&&&&&&          .\^/.          &&&&&&|
|&&&&&&        . |   | .        &&&&&&|
|&&&&&&        |\|   |/|        &&&&&&|
|&&&&&&     .--'       '--.     &&&&&&|
|&&&&&&      \           /      &&&&&&|
|&&&&&&       >         <       &&&&&&|
|&&&&&&      '~|/~~|~~\|~'      &&&&&&|
|&&&&&&            |            &&&&&&|
|&&&&&&                         &&&&&&|
|&&&&&&                         &&&&&&|
---------------------------------------
12
------------\
|&&&&&&      ------------\
|&&&&&&                   ------------\
|&&&&&&                         &&&&&&|
|&&&&&&                         &&&&&&|
|&&&&&&          .\^/.          &&&&&&|
|&&&&&&        . |   | .        &&&&&&|
|&&&&&&     .  |\|   |/|        &&&&&&|
|&&&&&&      --'       '--      &&&&&&|
|&&&&&&      \           /.     &&&&&&|
|&&&&&&       >         <       &&&&&&|
|&&&&&&      '~|/~~|~~\|~'      &&&&&&|
|&&&&&&            |            &&&&&&|
|&&&&&&                         &&&&&&|
------------\                   &&&&&&|
             ------------\      &&&&&&|
                          ------------\

-----------------------
|-._`-._ :| |: _.-'_.-|
|   `-._`:| |:`_.-'   |
|-------`-' '-'-------|
|------_.-. .-._------|
|  _.-'_.:| |:._`-._  |
|-'_.-'  :| |:  `-._`-|
-----------------------
4
----\
|-._`----\
|   `-._ :----\
|-----._`:| |: ----\
|-------`-| |:`_.-'_---
|  _.--_.-' '-'_.-' .-|
|-'_.-'_.:. .-.-----  |
----\-'  :| |:._------|
     ----\| |: _`-._--|
          ----\ `-._  |
               ----\`-|
                    ---

---------------
---------------
---------------
---------------
---------------
5
-----\
-----------\
---------------
---------------
-----\---------
      -----\---
            ---

-------------------------------------------
|*  *  *  *  * |##########################|
| *  *  *  *  *|                          |
|*  *  *  *  * |##########################|
| *  *  *  *  *|                          |
|*  *  *  *  * |##########################|
| *  *  *  *  *|                          |
|*  *  *  *  * |##########################|
|---------------                          |
|#########################################|
|                                         |
|#########################################|
|                                         |
|#########################################|
-------------------------------------------
0
\
|\
|*\
|  \
|** \
|   *\
|**   \
|   ** \
|**    *\
|-  **   \
|#-    ** \
| #-**    *\
|# #-  **   \
| # #-    ** \
\# # #-**    *\
 \# # #-  **   \
  \# # #-    **|\
   \# # #-**   |#\
    \# # #-  **| #\
     \# # #-   |# #\
      \# # #-**| # #\
       \# # #- |# # #\
        \# # #-| # # #\
         \# # #-# # # #\
          \# # # # # # #\
           \# # # # # # #\
            \# # # # # # #\
             \# # # # # # #\
              \# # # # # # #\
               \# # # # # # #\
                \# # # # # # #\
                 \# # # # # # #\
                  \# # # # # # #\
                   \# # # # # # #\
                    \# # # # # # #\
                     \# # # # # # #\
                      \# # # # # # #\
                       \# # # # # # #\
                        \# # # # # # #\
                         \# # # # # # #\
                          \# # # # # # #\
                           \# # # # # # #\
                            \# # # # # # #\
                             \# # # # # # |
                              \# # # # # #|
                               \# # # # # |
                                \# # # # #|
                                 \# # # # |
                                  \# # # #|
                                   \# # # |
                                    \# # #|
                                     \# # |
                                      \# #|
                                       \# |
                                        \#|
                                         \|
                                          \

```

# Answer
> 11 votes
# 05AB1E, ~~25~~ ~~23~~ ~~26~~ 25 bytes

*-2 thanks to Adnan*

*-1 thanks to Emigna*

*+3 thanks to Jonathan Allan (thanks for spending the time to catch that invalidity!)*

```
øvyN>²Öi¦¨'\.ø}N²÷ú}).Bø»

```

Try it online!

This is 1-indexed instead of 0, +2 bytes if that isn't okay.

```
ø                                    # Transpose.
 vy                }                 # For each column...
   N>²Öi¦¨'\.ø}                      # Replace outside dashes with slants.
               N²÷                   # Current index / input #2.
                  ú                  # Prepend that many spaces to current column.
                    ).Bø             # Join, pad, transpose back.
                        »            # Print with newlines.

```

Emigna/Adnan/Anyone - There HAS to be a better solution to replace those slants, but I'm stumped.

# Answer
> 9 votes
# Pyth, 35 bytes

```
j.ts.e+L*k;?qQtlb+PbjPteb*2\\bcC.zh

```

Try it online!

# Answer
> 8 votes
# Python 2, 129 bytes

```
lambda f,n,j=''.join:map(j,zip(*[i/n*' '+'-\\'[i%n>n-2]+j(s[1:-1])+'-\\'[i%n>n-2]+len(f[0])/n*' 'for i,s in enumerate(zip(*f))]))

```

Try it online!

# Answer
> 5 votes
# Jelly, 29 bytes

```
s”\⁹¦€Fð€0,1¦Zsð⁶ẋ;Ð€µ@"J;/z⁶

```

Input and output flags are lists of lines.
Wave length is 1-indexed.
Always produces one line of spaces.
(all of the above is explicitly allowed in the posted question)

**Try it online!** (footer to make IO look pretty - takes and receives flags as multiline text)

### How?

A pretty similar method to carusocomputing's 05ab1e answer, which I have not managed to golf down more.

```
s”\⁹¦€Fð€0,1¦Zsð⁶ẋ;Ð€µ@"J;/z⁶ - Main link: list of lists f, number p
            ¦                 - apply to indexes (of f)
         0,1                  - ... 0 paired with 1 (i.e. last & first -> bottom & top)
       ð€                     - the previous chain with p as right argument for €ach:
s                             -   split into chunks of length p
    ¦€                        -   apply to indexes for €ach
   ⁹                          -   ... link's right argument, p
 ”\                           -   the character '\' (a replacement - if the index is out of bounds this has no effect - although this might change in the future.)
             Z                - transpose the edited flag
              s               - split into chunks of length p
                        J     - range of length = [1,2,...,nChunks]
               ð     µ@"      - zip with reversed arguments (call those i):
                ⁶             -   literal space
                 ẋ            -    repeated i times
                  ;Ð€         -    concatenate mapped across the chunks
                         ;/   - undo the split (reduce with concatenation)
                           z⁶ - transpose with a filler of space characters

```

# Answer
> 3 votes
# MATL, 31 bytes

```
x"X@q1GQ&\Z"@b1G=?'\'5L(]h]Xhc!

```

Try it online! Or verify all test cases: , , , , , , .

# Answer
> 2 votes
# PHP, ~~168 164 187 172 167 153 150 152~~ 149 bytes

```
for($r=count($f=file(a));$y<$r+$e/$n=$argn;$y+=print"
")for($x=0;$x+1<$e=strlen($f[0])-1;)echo("\\".$f[$z=$y-($x/$n|0)][$x++]." ")[$z%($r-1)||$x%$n];

```

takes flag from static file `a` and wave length (minimum 1) from STDIN.
Run as pipe with `php -nr` or try it online.

**breakdown**

```
for($r=count($f=file(a));       # import file, count lines
    $y<$r+$e/$n=$argn;          # loop $y through lines
    $y+=print"\n")                      # 2. print newline
    for($x=0;$x+1<$e=strlen($f[0])-1;)  # 1. loop $x through columns
    echo("\\".$f[                           # 3. create string=backslash+character+space
            $z=$y-($x/$n|0)                 # 1. line no. = $y - wave offset
        ][$x++]." "                         # 2. pick character from line
        )
    [
        $z%($r-1)                           # if not first or last line
        ||$x%$n                             # or not last position of wave
    ]                                       # then index 1 (character or space), else "\\"
    ;

```

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

```
f=(s,l,p=++l,t=s.replace(/^-*|-*$/g,s=>s.replace(/-/g,(c,i)=>++i%l?c:`\\`)))=>t.search`
`<p?t:(f(s,l,p+l,t)+`
`+` `.repeat(p)).replace(eval(`/(^|(.*)\\n)(.{${p}})/g`),`
$3$2`)
;
test=(s,l)=>document.write(`<pre>${s}
${l}${f(s,l)}</pre>`);
test(`---
abc
---`,2);
test(`-----
| + |
-----`,10);
test(`---------------------------------------
|&&&&&&                         &&&&&&|
|&&&&&&                         &&&&&&|
|&&&&&&                         &&&&&&|
|&&&&&&          .\\^/.          &&&&&&|
|&&&&&&        . |   | .        &&&&&&|
|&&&&&&        |\\|   |/|        &&&&&&|
|&&&&&&     .--'       '--.     &&&&&&|
|&&&&&&      \\           /      &&&&&&|
|&&&&&&       >         <       &&&&&&|
|&&&&&&      '~|/~~|~~\\|~'      &&&&&&|
|&&&&&&            |            &&&&&&|
|&&&&&&                         &&&&&&|
|&&&&&&                         &&&&&&|
---------------------------------------`,12);
test(`-----------------------
|-._\`-._ :| |: _.-'_.-|
|   \`-._\`:| |:\`_.-'   |
|-------\`-' '-'-------|
|------_.-. .-._------|
|  _.-'_.:| |:._\`-._  |
|-'_.-'  :| |:  \`-._\`-|
-----------------------`,4);
test(`---------------
---------------
---------------
---------------
---------------`,5);
test(`-------------------------------------------
|*  *  *  *  * |##########################|
| *  *  *  *  *|                          |
|*  *  *  *  * |##########################|
| *  *  *  *  *|                          |
|*  *  *  *  * |##########################|
| *  *  *  *  *|                          |
|*  *  *  *  * |##########################|
|---------------                          |
|#########################################|
|                                         |
|#########################################|
|                                         |
|#########################################|
-------------------------------------------`,0);
```

I/O is as a newline-delimited string. Output includes a leading newline; this can be removed at a cost of 3 bytes. I tried computing the output string directly but that took me... 176 bytes:

```
f=
(a,l,h=a.length)=>[...Array(h+(a[0].length-1)/++l|0)].map((_,i)=>a[0].replace(/./g,(k,j)=>((k=i-(j/l|0))&&h+~k)|-~j%l?(a[k]||'')[j]||' ':'\\'))
;
test=(s,l)=>document.write(`<pre>${s}
${l}
${f(s.split`
`,l).join`
`}</pre>`);
test(`---
abc
---`,2);
test(`-----
| + |
-----`,10);
test(`---------------------------------------
|&&&&&&                         &&&&&&|
|&&&&&&                         &&&&&&|
|&&&&&&                         &&&&&&|
|&&&&&&          .\\^/.          &&&&&&|
|&&&&&&        . |   | .        &&&&&&|
|&&&&&&        |\\|   |/|        &&&&&&|
|&&&&&&     .--'       '--.     &&&&&&|
|&&&&&&      \\           /      &&&&&&|
|&&&&&&       >         <       &&&&&&|
|&&&&&&      '~|/~~|~~\\|~'      &&&&&&|
|&&&&&&            |            &&&&&&|
|&&&&&&                         &&&&&&|
|&&&&&&                         &&&&&&|
---------------------------------------`,12);
test(`-----------------------
|-._\`-._ :| |: _.-'_.-|
|   \`-._\`:| |:\`_.-'   |
|-------\`-' '-'-------|
|------_.-. .-._------|
|  _.-'_.:| |:._\`-._  |
|-'_.-'  :| |:  \`-._\`-|
-----------------------`,4);
test(`---------------
---------------
---------------
---------------
---------------`,5);
test(`-------------------------------------------
|*  *  *  *  * |##########################|
| *  *  *  *  *|                          |
|*  *  *  *  * |##########################|
| *  *  *  *  *|                          |
|*  *  *  *  * |##########################|
| *  *  *  *  *|                          |
|*  *  *  *  * |##########################|
|---------------                          |
|#########################################|
|                                         |
|#########################################|
|                                         |
|#########################################|
-------------------------------------------`,0);
```

I/O is as a string array.

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


title: Is this Tic-Tac-Toe board valid?

text:
# Question
Title: Is this Tic-Tac-Toe board valid?
# Challenge

Given a tic-tac-toe board in any format, determine if it is valid or not. If a board can be the result of a tic-tac-toe game, then it is valid. For example, this board is valid:

```
X O X
O X O
X O X
```
On the contrary, this board is invalid:
```
X X X
X X O
O O O
```

# Input

* A full (9/9) tic tac toe board (the outcome, not the game).

# Rules

* The input format must be able to depict all 512 possible input boards. It must be specified, along with the instructions to create it if it is obscure/unclear. **You must state the marks of the board individually though.**
* There must be two possible outputs, one for validity and one for invalidity.
* You can assume the board does not have empty spots.

# Test cases

Valid:

```
X O X
O X O
X O X

X O X
X O X
O X O

X O O
O O X
O X X

O X O
X O X
O X O
```

Invalid:

```
X X X
X X X
X X X

O O O
O O O
O O O

X X X
O O O
X X X

O O O
O O X
X X X

X X O
O X O
O O X
```

# A little help?

A board is considered valid (for this challenge) if and only if the following two conditions hold:

* There are 5 X and 4 O, or 4 X and 5 O. For example,
```
X X X
O X O
X X X
```
is considered invalid, because there are 7 Xs and 2 Os.
* Only the player with 5 marks has won, or none of them have won. For example,
```
X X X
O O O
O O X
```
is considered invalid, since either the row of `O`s or the row of `X`s will be formed first. The two players can't have their turn simultaneously.

# The current winner is...

...ais523's Jelly answer, at an astounding 26 bytes!

# Answer
# Jelly, 26 bytes

```
ṢŒrṪ4=$$Ðfx3ðœ-µẆm€6R¤;/µL

```

Try it online!

The input format is a little unusual; it's a string representing the board, but with Windows newlines (carriage return followed by newline). For example, `XXO\r\nOXO\r\nOOX`. (Actually, any two-character padding string between the lines works, but Windows newlines are much more defensible than the other options.)

The basic idea is that we look for characters that appear 4 times in the input, but don't have three evenly spaced occurrences in the original string. With two or more characters of padding between the lines of a 3×3 grid, all horizontal, vertical, and diagonal lines are evenly spaced, but no other evenly spaced line can have three elements.

Explanation:

The `ð` and `µ`s are *chain separators*, which split the program into multiple parts that are each independent. I've replaced them with spaces below, to make things a bit clearer.

```
ṢŒrṪ4=$$Ðfx3 œ- Ẇm€6R¤;/ L
Ṣ                           sorted version of the input
 Œr                         run-length-encode it
        Ðf                  keep only elements where
   Ṫ                        delete the last element, and it was
    4=                      equal to 4
      $$                    parse Ṫ4= as a group
          x3                repeat each element three times

                Ẇ           all sublists of the input
                 m€         take every nth element of each (€) sublist
                   6R       for each n in 1..6
                     ¤      parse 6R as a group
                      ;/    flatten one level (m€ creates a nested structure)

             œ-             multiset difference
                         L  length of that difference

```

In other words, we find the list of characters that appear exactly four times in the input, and make a list consisting of three copies of each of those; we find the list of all subsequences that are evenly spaced in the original string; and if we subtract the second from the first, we want the result to have length 1 (i.e. a player played four times but didn't win). Note that as we're on a 3×3 grid and every square is full, it's impossible for *both* players to have played four times. In Jelly, 1 is truthy, 0 is falsey, so we don't need to do anything special to convert the resulting list to a boolean. (The `µL` is required, though, because otherwise both `“XXX”` and `“OOO”` would be possible truthy output values, and the question requires that all valid boards give the same output.)
> 12 votes

# Answer
## JavaScript (ES6), ~~88~~ 87 bytes

```
s=>(a=[...s]).sort()[5]-a[3]&[7,56,73,84,146,273,292,448].every(j=>j&i,i=`0b`+s^~-a[4])

```

Takes input as a string of 9 `0` and `1` characters and returns `1` for valid, `0` for invalid. We sort the characters into order. If the middle three characters are now the same then the board is invalid as there are too many of one piece. Otherwise, we convert the original board into binary, flipping the bits if there are more `0`s than `1`s. At this point the board is valid if `0` does not have a line of three, so we simply test all eight lines via an array of bitmasks. Edit: Saved 1 byte thanks to @ETHproductions.
> 21 votes

# Answer
# Python 3, ~~131~~ ~~127~~ ~~125~~ ~~100~~ 96 bytes

For a different algorithmic approach (and one that will be really suited to these multi-byte golfing languages with built-in compression), instead of calculating if the board is valid, let's have a 512-bit number where each bit represents whether or not a particular board is valid or not, and pass in a binary value representing the board. Furthermore, due to symmetry, the second half of the table can be eliminated, along with a bunch of zeros:

```
def z(b):return int('agqozfx67wwye6rxr508ch2i8qicekpreqkap0725pk',36)<<24&1<<b+(b>255)*(511-b-b)

```

The test value:

```
X X X
O X O
X X X

```

Is represented as the binary value `0b111010111`, and the function returns a non-zero value if the board is valid.
> 14 votes

# Answer
## Batch, 140 bytes

```
@set/aXXX=OOO=O=0
@for %%l in (%* %1%2%3 %1%4%7 %1%5%9 %2%5%8 %3%5%7 %3%6%9 %4%5%6 %7%8%9)do @set/a%%l+=1
@cmd/cset/a!XXX*!(O-=5)+!OOO*!~O

```

Takes input as nine separate command-line arguments and outputs `1` for valid and `0` for invalid. Works by tracking the number of times it sees an `O` and a orthogonal line of `OOO` or `XXX`. Conveniently Batch allows us to perform integer arithmetic indirectly, so we're not incrementing `%%l` but some variable instead (although we're only interested in the three variables mentioned). We then need to test that either `X` has not won and there are five `O`s or that `O` has not won and there are four `O`s.
> 12 votes

# Answer
# Mathematica, ~~82~~ 75 bytes

*Thanks to Martin Ender for saving 7 bytes!*

```
t=Total;3<(b=#~t~2)<6&&{t[c=If[b>4,1-#,#]],t/@c,Tr@c,Tr@Reverse@c}~FreeQ~3&

```

Unnamed function taking a 3x3 nested list of 1s and 0s as input and outputting `True` or `False`.

Uses some handy flexibility of the `Total` function (here golfed to `t`): given an example array `e = { {1,2,3} , {4,5,6} , {7,8,9} }`, the command `t[e]` sums the three vectors (here yielding `{12,15,18}`); the command `t/@e` sums each sublist individually (here yielding `{6,15,24}`); and the command `e~t~2` sums all nine elements (here yielding `45`).

So first we test, with `3<(b=#~t~2)<6`, whether the total number of 1s is 4 or 5; if not we exit with `False`. If so, we use `c=If[b>4,1-#,#]` to force there to be four 1s, not five. Then we compute the column sums `t[c]`, the row sums `t/@c`, the sum of the main diagonal `Tr@c`, and the sum of the opposite diagonal `Tr@Reverse~c`, and use `~FreeQ~3` to check that `3` fails to appear at any level in those computed sums.

Amusing side note: unlike most appearances on this site, here `Tr` is not used to sum a one-dimensional list but is actually used as designed—to calculate the trace of a two-dimensional matrix!
> 10 votes

# Answer
# Pyth - 36 bytes

I include diagas and use two ternaries instead.

```
JsM+sCBQm@VdU3_BQ?q5KssQ*FJ?qK4!}3JZ

```

Test Suite
> 6 votes

# Answer
## Python 2, ~~158~~ ~~132~~ ~~109~~ ~~92~~ ~~91~~ 123 bytes

```
def v(b):f=sum(b,());w={x[0]for x in b+zip(*b)+[f[::4],f[-3:1:-2]]if len(set(x))==1};return sum(map(`b`.count,w))==len(w)*5

```

Input is a list/tuple of rows, each a three-tuple of strings, e.g.:
`[('X', 'O', 'X'), ('O', 'X', 'O'), ('X', 'O', 'X')]`

~~Saved some bytes by ignoring diagonals per @Maltysen's answer, which also shortened the following expression.~~

~~Thanks @vaultah for saving ~~17~~ 18 bytes.~~

Checking diagonals turns out to be necessary, which removed a lot of the savings above.

Try it here.

### Explanation

```
def v(b):
  f=sum(b,())
  w={x[0]for x in b+zip(*b)+[f[::4],f[-3:1:-2]]if len(set(x))==1}
  return sum(map(`b`.count,w))==len(w)*5

```

`f` is the flattened input for slicing.
`w` contains the characters with winning sequences.
Count the occurrences of each winning character, which will either be 0 if `w` is empty or 5 if `len(w)` is 1. The 10 sum when both have a winning sequence is impossible. The winner having 5 implies the loser has 4. You can't have \>5 without a winning sequence.
> 5 votes

# Answer
## JavaScript (ES6), 101 bytes

Takes input as a 9-bit binary mask where `X = 1` and `O = 0` (MSB = top left cell, LSB = bottom right cell).

```
n=>[7,56,73,84,146,273,292,448,o=x=0].map((m,i)=>(c-=n>>i&1,m&n^m?m&n||o++:m&&x++),c=4)&&!(c|x&&~c|o)

```

### Test cases

```
let f =

n=>[7,56,73,84,146,273,292,448,o=x=0].map((m,i)=>(c-=n>>i&1,m&n^m?m&n||o++:m&&x++),c=4)&&!(c|x&&~c|o)

// valid
console.log(f(0b101010101));
console.log(f(0b101101010));
console.log(f(0b100001011));
console.log(f(0b010101010));

// invalid
console.log(f(0b111111111));
console.log(f(0b000000000));
console.log(f(0b111000111));
console.log(f(0b000001111));
console.log(f(0b110010001));
```
> 5 votes

# Answer
## R, ~~88~~ 82 bytes

```
x=scan();`if`(sum(x)%in%4:5,all(apply(combn(which(x==(sum(x)<5)),3),2,sum)!=15),F)

```

All combinations of three integers from 1 to 9 that sum up to 15 are the rows/columns/diagonals of the square shown below.

```
2 7 6
9 5 1
4 3 8

```

The function takes input as a vector of booleans, T for "X", F for "O", which is the flattened representation of the board. BUT, these are reordered so that their index is the same as the number in the square, in the the order (2,7,6,9,5,1,4,3,8). That order might be achieved by flattening the board in the normal way, and then slicing by c(6,1,8,7,5,3,2,9,4). So this

```
X O X
O X O
X O X

```

is represented as:

```
c(T, F, T, F, T, F, T, F, T)[c(6,1,8,7,5,3,2,9,4)]

```

which is:

```
c(F, T, F, T, T, T, F, T, F)

```

The function first determines whether there is a player with exactly four marks. If so, the function uses the fact-of-things-that-add-up-to-15 to determine whether that player has a three-in-a-row (the board is invalid iff that player does).

If you wanted to take a conventionally-flattened board as input, the code would look like this instead:

```
f=function(x)ifelse(sum(x)%in%4:5,all(apply(combn(c(2,7,6,9,5,1,4,3,8)[which(x==(sum(x)<5))],3),2,sum)!=15),F)

```

I'm new at this, advice would be appreciated.
> 5 votes

# Answer
# JavaScript (ES6), ~~145~~ ~~139~~ ~~131~~ 127 bytes

```
s=>!(q="XO"[s.split`O`.length-5])|![...s].some((c,i)=>c==q&!/(.)(\1|..(\1|.(\1|.\1.).)..)\1/.test(s.slice(0,i)+0+s.slice(i+1)))

```

Input as a space-separated string, such as `"XOX OXO XOX"`. Outputs `1` for an invalid board, `0` for a valid one. This obviously isn't the best technique, at least not with JavaScript...

This basically checks whether both the following hold:

* There are exactly 4 or 5 `O`s, AND
* there is at least one of the 5-instance piece which creates an undecided game when removed.

The regex is to check whether a game has been decided. It matches a board iff there are any runs of length three of one character with 0 (row), 2 (down-right diagonal), 3 (column), or 4 (down-left diagonal) chars separating each pair.

### Test snippet

```
f=s=>!(q="XO"[s.split`O`.length-5])|![...s].some((c,i)=>c==q&!/(.)(\1|..(\1|.(\1|.\1.).)..)\1/.test(s.slice(0,i)+0+s.slice(i+1)))

g=s=>console.log(f(s))

// Valid boards (outputs 0)
g("XOX OXO XOX")
g("XOX XOX OXO")
g("XOO OOX OXX")
g("OXO XOX OXO")

// Invalid boards (outputs 1)
g("XXX XXX XXX")
g("OOO OOO OOO")
g("XXX OOO XXX")
g("OOO OOX XXX")
g("XXO OXO OOX")
```
> 3 votes

# Answer
# Ruby, ~~104 99~~ 91 bytes

```
->x{[7,56,448,292,146,73,84,273].none?{|y|b=x.to_i 2;((a=x.count'1')==4?b:a==5?~b:7)&y==y}}

```

Input format: binary string of 9 symbols (0s and 1s) representing the board, for example the first test case is `101010101`. First convert it to a binary number, check if popcount is 4 or 5, if it's 5 invert the number so we always have 4. Check if three of them are aligned (masking witn horizontal, vertical, diagonal).

**TL;DR**: Return false if player with 4 marks won, true otherwise.

Thanks Jordan for the comments,

*I can't reproduce the UTF-8 string which would save another byte.*
> 2 votes

# Answer
## Perl 6, ~~103~~ 99 bytes

```
{my \c=%(.flat.Bag.invert)<5>;?all c,|(.[0]===c if [eq] $_ for |.flat[<0 4 8>,<2 4 6>],|$_,|.&zip)}

```

A lambda that accepts a list of lists like `(('X','O','X'), ('O','X','O'), ('X','O','X'))`, and returns a Bool.

It works like this:

1. Check which mark appears exactly 5 times, and store it in `c`. *(If no mark appears exactly 5 times, this will contain a falsy value)*
2. Iterate over all diagonals, rows, and columns, and filter out the "winning" ones *(i.e. those where all three letters are equal)*.
3. Check if `c` is truthy, **and** each winning line is of type `c`.
> 1 votes

# Answer
# PHP, 125 bytes

```
for($p=$n=$argv[1];$p;$p/=2)$i+=$p&1;foreach([7,56,448,73,146,292,273,84]as$m)$n&$m^$m?$n&$m||$o++:$x++;echo!$x|!$o&&2>$i^=4;

```

I had the same idea as Arnauld: The board is valid if there are either 4 or 5 bits set and either `X` or `O` or nobody has a streak (but not both).

To generate input from field replace `X` with `1` and `O` with `0`, join lines and convert binary to decimal, provide as command line argument.

prints `1` for valid; empty output for invalid. Run with `-r`.

**breakdown**

```
// count set bits
for($p=$n=$argv[1];$p;$p/=2)$i+=$p&1;
    /* ($p/=2 takes longer than $p>>=1, but eventually
       $p will come close enough to 0 for the loop to finish */
// count streaks for X and O
foreach([7,56,448,73,146,292,273,84]as$m)
    $n&$m^$m            // ($n masked with streak)!=streak <=> no streak for X
        ?$n&$m||$o++    // true: O has a streak if ($n masked with streak) is empty
        :$x++;          // false: X has a streak
echo!$x|!$o&&2>$i^=4;   // valid if not both have a streak
                        // AND $i is 4 or 5 (toggle 4 -> result 0 or 1)

```
> 1 votes

# Answer
# Swift, 178 bytes

```
func t(i:String)->Bool{let r=i.characters.filter({$0=="X"}).count;let g=i.characters.split(separator:"\n").map(String.init).contains;return(r==5||r==4)&&(!g("XXX") && !g("OOO"))}

```
> 1 votes

# Answer
# ES6 (Javacript), ~~130~~, ~~138~~, 117 bytes

EDITS:

* 21 bytes off thanks to excellent advice from @Neil !
* Initial version was prone to a bug, which should now be fixed at cost of +8 bytes. (Thanks @ETHproductions for pointing it out)

An extremelly straighforward approach. Can probably be golfed a bit further.

Accepts input as 9 separate arguments, 1es and 0es

* **1** is for **X**
* **0** is for **O**

Arguments: 1-3 - first row, 4-6 - second row, 7-9 - third row.

**Golfed**

```
(a,b,c,d,e,f,g,h,j)=>![a+b+c,d+e+f,g+h+j,a+d+g,b+e+h,c+f+j,a+e+j,g+e+c,7].some(x=>x=="7777307777"[a+b+c+d+e+f+g+h+j])

```

**Interactive "Test Bed"**

```
var a=b=c=d=e=f=g=h=j=0;

T=(a,b,c,d,e,f,g,h,j)=>![a+b+c,d+e+f,g+h+j,a+d+g,b+e+h,c+f+j,a+e+j,g+e+c,7].some(x=>x=="7777307777"[a+b+c+d+e+f+g+h+j]);

function test() {
  if(T(a,b,c,d,e,f,g,h,j)) {
     grid.style.backgroundColor='green';
     msg.innerHTML="GOOD"
  } else {
     grid.style.backgroundColor='red';
     msg.innerHTML="BAD"
  }
}
```

```
<table id=grid style="background: red">
<thead>
  <tr>
     <td id=msg align="center" colspan="3">BAD</td>
    </tr>
  </thead>
  <tr>
      <td><input type="checkbox" onchange="a=this.checked*1;test();" id="ca"/></td>
      <td><input type="checkbox" onchange="b=this.checked*1;test();" id="cb"/></td>
      <td><input type="checkbox" onchange="c=this.checked*1;test();" id="cc"/></td>
    </tr>
    <tr>
      <td><input type="checkbox" onchange="d=this.checked*1;test();" id="cd"/></td>
      <td><input type="checkbox" onchange="e=this.checked*1;test();" id="ce"/></td>
      <td><input type="checkbox" onchange="f=this.checked*1;test();" id="cf"/></td>
    </tr>
    <tr>
      <td><input type="checkbox" onchange="g=this.checked*1;test();" id="cg"/></td>
      <td><input type="checkbox" onchange="h=this.checked*1;test();" id="ch"/></td>
      <td><input type="checkbox" onchange="j=this.checked*1;test();" id="cj"/></td>
    </tr>
 </table>
```
> 0 votes

---
Tags: code-golf, decision-problem, tic-tac-toe
---


title: Given a Tree generate its Prüfer Code

text:
# Question
Title: Given a Tree generate its Prüfer Code
In a Prüfer code is a unique sequence of integers that denotes a specific tree.

You can find the Prüfer code of a tree with the following algorithm taken from Wikipedia:

> Consider a labeled tree T with vertices `{1, 2, ..., n}`. At step *i*, remove the leaf with the smallest label and set the *i*th element of the Prüfer sequence to be the label of this leaf's neighbor.

(Note that since it's a leaf it will only have one neighbor).

You should stop the iteration when only two vertices remain in the graph.

# Task

Given a labeled tree as input output its Prüfer code. You may take input in any reasonable manner. Such as an adjacency matrix or your languages builtin graph representation. (*You may not take input as a Prüfer code*).

This is so you should aim to minimize the bytes in your source.

# Test cases

Here are some inputs in ASCII with their outputs below. You do not need to support ASCII input like this.

```
    3
    |
1---2---4---6
    |
    5

{2,2,2,4}

```

---

```
1---4---3
    |
5---2---6---7
|
8

{4,4,2,6,2,5}

```

---

```
5---1---4   6
    |       |
    2---7---3

{1,1,2,7,3}

```

# Answer
> 9 votes
# Mathematica, 34 bytes

```
<<Combinatorica`
LabeledTreeToCode

```

Somebody had to do it....

After loading the `Combinatorica` package, the function `LabeledTreeToCode` expects a tree input as an undirected graph with explicitly listed edges and vertices; for example, the input in the second test case could be `Graph[{{{1, 4}}, {{4, 3}}, {{4, 2}}, {{2, 5}}, {{2, 6}}, {{6, 7}}, {{5, 8}}}, {1, 2, 3, 4, 5, 6, 7, 8}]`.

# Answer
> 4 votes
# Python 3, ~~136~~ ~~131~~ 127 bytes

```
def f(t):
 while len(t)>2:
  m=min(x for x in t if len(t[x])<2);yield t[m][0];del t[m]
  for x in t:m in t[x]and t[x].remove(m)

```

Takes input as an adjacency matrix. First example:

```
>>> [*f({1:[2],2:[1,3,4,5],3:[2],4:[2,6],5:[2],6:[4]})]
[2, 2, 2, 4]

```

# Answer
> 4 votes
# Jelly, 31 bytes

```
FĠLÞḢḢ
0ịµÇHĊṙ@µÇCịṪ,
WÇÐĿḢ€ṖṖḊ

```

A monadic link which takes a list of pairs of nodes (defining the edges) in any order (and each in any orientation) and returns the Prüfer Code as a list.

**Try it online!**

### How?

```
FĠLÞḢḢ - Link 1, find leaf location: list of edges (node pairs)
F      - flatten
 Ġ     - group indices by value (sorted smallest to largest by value)
  LÞ   - sort by length (stable sort, so equal lengths remain in prior order)
    ḢḢ - head head (get the first of the first group. If there are leaves this yields
       -   the index of the smallest leaf in the flattened version of the list of edges)

0ịµÇHĊṙ@µÇCịṪ, - Link 2, separate smallest leaf: list with last item a list of edges
0ị             - item at index zero - the list of edges
  µ            - monadic chain separation (call that g)
   Ç           - call last link (1) as a monad (index of smallest leaf if flattened)
    H          - halve
     Ċ         - ceiling (round up)
      ṙ@       - rotate g left by that amount (places the edge to remove at the right)
        µ      - monadic chain separation (call that h)
         Ç     - call last link (1) as a monad (again)
          C    - complement (1-x)
            Ṫ  - tail h (removes and yields the edge)
           ị   - index into, 1-based and modular (gets the other node of the edge)
             , - pair with the modified h
               -    (i.e. [otherNode, restOfTree], ready for the next iteration)

WÇÐĿḢ€ṖṖḊ - Main link: list of edges (node pairs)
W         - wrap in a list (this is so the first iteration works)
  ÐĿ      - loop and collect intermediate results until no more change:
 Ç        -   call last link (2) as a monad
    Ḣ€    - head €ach (get the otherNodes, although the original tree is also collected)
      ṖṖ  - discard the two last results (they are excess to requirements)
        Ḋ - discard the first result (the tree, leaving just the Prüfer Code)

```

# Answer
> 1 votes
# 05AB1E, 29 bytes

```
[Dg#ÐD˜{γé¬`U\X.å©Ï`XK`ˆ®_Ï]¯

```

Try it online!

**Explanation**

```
[Dg#                           # loop until only 1 link (2 vertices) remain
    ÐD                         # quadruple the current list of links
      ˜{                       # flatten and sort values
        γé                     # group by value and order by length of runs
          ¬`U                  # store the smallest leaf in X
             \X                # discard the sorted list and push X
               .å©             # check each link in the list if X is in that link
                  Ï`           # keep only that link
                    XK`ˆ       # add the value that isn't X to the global list
                        ®_Ï    # remove the handled link from the list of links
                           ]   # end loop
                            ¯  # output global list

```

# Answer
> 1 votes
## Clojure, 111 bytes

```
#(loop[r[]G %](if-let[i(first(sort(remove(set(vals G))(keys G))))](recur(conj r(G i))(dissoc G i))(butlast r)))

```

Requires the input to be a hash-map, having "leaf-like" labels as keys and "root-like" labels as values. For example:

```
{1 2, 3 2, 5 2, 4 2, 6 4}
{1 4, 3 4, 4 2, 8 5, 5 2, 7 6, 6 2}

```

On each iteration it finds the smallest key which is not referenced by any other node, adds it to the result `r` and removes the node from the graph definition `G`. `if-let` goes to else case when `G` is empty, as `first` returns `nil`. Also the last element has to be dropped.

# Answer
> 1 votes
# Python 2, 91 bytes

```
d=input()
while len(d)>2:m=min(d,key=lambda k:len(d[k]));n,=d[m];del d[m];d[n]-={m};print n

```

Try it online!

Based on L3viathan's solution. Takes a dictionary of sets representing adjacency lists.

---
Tags: code-golf, graph-theory
---


# Question
Title: Monday Mini-Golf #7: Simplify ingredient measurements
**Monday Mini-Golf:** A series of short challenges, posted (hopefully!) every Monday.
Sorry it's late; I realized 90% of the way through writing out a different idea that it was a duplicate.

My family is rather large, so we eat a lot of food. We usually need to double, triple, or even quadruple recipes to make enough food! But as multiplying the measurements can be a pain, it'd be nice to have a program to do this for us.

# Challenge

Your challenge is to create a program or function that takes in a measurement as a number *N* and a letter *L*, and returns the same measurement, simplified as much as possible. Here's the required measurement units (all are American, like my family), and their corresponding letters:

```
1 cup (c) = 16 tablespoons (T) = 48 teaspoons (t)
1 pound (l) = 16 ounces (o)
1 gallon (g) = 4 quarts (q) = 8 pints (p) = 128 fluid ounces (f)

```

"simplified as much as possible" means:

* Using the largest measurement unit possible. Each unit can have a remainder of 1/4, 1/3, 1/2, 2/3, or 3/4.
* Turning the result into a mixed number, if necessary.

For example, `4 o` is four ounces, which becomes `1/4 l`, a quarter pound. `8 t`, 8 teaspoons, becomes `2 2/3 T`.

## Details

* The input may be taken in any reasonable format; same with output. (`1 t`, `1,"t"`, `1\nt`, etc.)
* Make sure any fractional part is dealt with properly. (`11/4` in place of `1 1/4` is not allowed.)
* The number will always be a mixed number, and will always have a denominator of `2`, `3`, or `4` (or none). (no `1 1/8 T`, no `1.5 T`, etc.)
* As a result of the above, no downward conversions (e.g. cups to tablespoons) are ever needed.
* The letter will always be one of the letters listed above (`Tcfglopqt`).

# Test-cases

Here's an large list, hopefully covering all types of cases:

```
Input   | Output
--------+--------
1/2 t   | 1/2 t
3/4 t   | 1/4 T
1 t     | 1/3 T
1 1/2 t | 1/2 T
2 t     | 2/3 T
2 1/4 t | 3/4 T
2 1/2 t | 2 1/2 t
3 t     | 1 T
10 t    | 3 1/3 T
16 t    | 1/3 c
5 1/3 T | 1/3 c
8 T     | 1/2 c
16 T    | 1 c
36 T    | 2 1/4 c
1/4 c   | 1/4 c
1024 c  | 1024 c
1 o     | 1 o
4 o     | 1/4 l
5 1/3 o | 1/3 l
5 2/3 o | 5 2/3 o
8 o     | 1/2 l
28 o    | 1 3/4 l
28 l    | 28 l
2 f     | 2 f
4 f     | 1/4 p
8 f     | 1/4 q
16 f    | 1/2 q
32 f    | 1/4 g
64 f    | 1/2 g
128 f   | 1 g
2/3 p   | 1/3 q
1 1/3 p | 2/3 q
2 p     | 1/4 g
1 q     | 1/4 g

```

# Scoring

Our kitchen is very small, so the code should be as short as possible, so as not to make the kitchen more cramped. Shortest valid code in bytes wins; tiebreaker goes to submission that reached its final byte count first. The winner will be chosen next Monday, Nov 9. Good luck!

Please note that this challenge is similar to, but not a duplicate of, World Big Dosa.

# Answer
# Mathematica, ~~349 334 330~~ 322 bytes

This answer section felt a little lonely. So uh, here's my attempt. Input should be given as in the test cases.

```
n=ToExpression@StringSplit@InputString[];i=#~Mod~1&;b=#&@@n;If[Length@n==3,{x,y,z}=n,{x,y,z}=If[IntegerQ@b,{b,0,Last@n},{0,b,Last@n}]];v={0,1/4,1/3,1/2,2/3,3/4};s=<|T->16,t->3,o->16,q->4,p->2,f->16|>;r=<|T->c,t->T,o->l,f->p,p->q,q->g|>;If[v~MemberQ~i[a=(x+y)/s@z],{x,y,z}={Floor@a,i@a,r@z}]~Do~3;Print@Row[{x,y,z}/. 0->""]

```

## Explanation

First get the user input, split that input on whitespace, and assign that to `n`. `i=#~Mod~1&` creates a function that gets the fractional part of a number, by taking it mod 1. `b=#&@@n` will simply get the first item in `n`; that would be everything up to the first space.

If `n` is 3 elements long, that means we have an integer, a fraction, *and* a unit. `{x,y,z}=n` will assign `x`, `y` and `z` to be the three parts of `n`. The other case is that `n` is not 3 elements long; that means it’ll be 2 elements long instead. To stay consistent with above, we want `x` to be the integer part, `y` to be the fraction, and `z` the unit. So in this case, we need to check:

* If `b` (the first element of `n`) is an integer, then `x=b`, `y=0` and `z=Last@n` (the last element of `n`).
* If `b` isn’t an integer, that means we only have a fraction with no integer. So we want to swap `x` and `y` from above; instead, `x=0`, `y=b`, and `z` is the same as above.

Now we need to set up some lists:

`v = {0, 1/4, 1/3, 1/2, 2/3, 3/4}` is the list of acceptable fractions, as stated in the question.

`s = <|T -> 16, t -> 3, o -> 16, q -> 4, p -> 2, f -> 16|>` is an association (key-value pair, like a dictionary in Python) that represents the amount needed of a given unit to go “up” to one of the next largest unit. For example, `o -> 16` is because 16 ounces are required before we go up to 1 pound.

`r = <|T -> c, t -> T, o -> l, f -> p, p -> q, q -> g|>` is the association that actually represents what the next unit up is. For example, `T -> c` means one unit larger than Tablespoons is cups.

`If[v~MemberQ~i[a = (x + y)/s@z], {x, y, z} = {Floor@a, i@a, r@z}]~Do~3`

Now, the maximum number of times we need to go up a unit is 3; that would be fluid ounces (f) -\> pints (p) -\> quarts (q) -\> gallon (g). So, now we do the following 3 times:

* Add `x` and `y`, (the integer and fractional parts)
* From the `s` association above, get element `z`; that is, access the current unit, and get the corresponding value in that association.
* Divide (x+y) by that value we got above, assign it to `a`, then get its fractional part.
* If that part is in the list `v`, then we can go up one unit; set `x` to `a` rounded down (integer part), set `y` to the fractional part of `a`, then access the association `r` with the current unit `z` to get the next unit up, and set that to `z`.
* If it’s *not* part of `v` instead, we don’t do anything, since it can’t be simplified.

Once that’s done 3 times, we print out the result:

`Print@Row[{x,y,z}/. 0->””]`

This simply prints out `{x,y,z}` in a row, but replaces any zeroes (if there’s no integer, or no fraction), with an empty string, so those don’t print out.
> 2 votes

---
Tags: code-golf, number, conversion
---


title: Exit code string output

text:
# Question
Title: Exit code string output
You must write a program or function that, when given a *nonempty* string **S** of **N** printable ASCII characters, outputs a program that will exit with exit code **C**, where **C** is the ASCII codepoint at position 0 in **S**. This program you write will additionally output a program **P**, such that, when run, it exits with exit code **C′**, where **C′** is the ASCII codepoint at position 1 in **S**. Program **P** will output another program **P′**. This process repeats until there are no characters left in **S**. After this is done, you must output nothing, followed by an optional newline; and should exit with exit code 0.

The characters between `0x20` and `0x7e` inclusive.

Some more rules:

* Self-modifying programs are not allowed: you must output the source to STDOUT (or, return value initially)
* You may not read your own source code.

The shortest such program in bytes will win.

For some rudimentary testing, this ruby script can be used. (The first argument is the way you invoke the script, the second is the program, and the third is the input string.)

## Hypothetical Example

Say the program is `FOO`. When given the string "ABC", it outputs `BARA`. This program exits with code `65` and outputs `BARB`. This in turn exits with code `66` and ouputs `BARC`. This program exits with code `67` and outputs `BAR!`. This outputs nothing, and exits with code `0`.

# Answer
> 6 votes
# Python 2, ~~126~~ ~~101~~ 94 bytes

In the process of making this, I found that Python code may not contain literal NUL bytes.

```
lambda i,s='''i=%r;s=%r
try:print s%%(i[1:],s,i[0])
except:0
exit(ord(%r))''':s%(i[1:],s,i[0])

```

**Try it online** *(shows the exit code in the Debug info)*

---

Note that each of the non-empty programs below has a trailing linefeed.

For input `Hello`, the above outputs:

```
i='ello';s='i=%r;s=%r\ntry:print s%%(i[1:],s,i[0])\nexcept:print s%%(0,s,"\\0")*(i>0)\nexit(ord(%r))'
try:print s%(i[1:],s,i[0])
except:0
exit(ord('H'))

```

which prints

...

which prints

```
i='o';s='i=%r;s=%r\ntry:print s%%(i[1:],s,i[0])\nexcept:print s%%(0,s,"\\0")*(i>0)\nexit(ord(%r))'
try:print s%(i[1:],s,i[0])
except:0
exit(ord('l'))

```

which prints

```
i='';s='i=%r;s=%r\ntry:print s%%(i[1:],s,i[0])\nexcept:print s%%(0,s,"\\0")*(i>0)\nexit(ord(%r))'
try:print s%(i[1:],s,i[0])
except:0
exit(ord('o'))

```

which prints nothing (the empty program)

which prints nothing and exits with code 0.

# Answer
> 4 votes
# Python 3, 77 bytes

```
p='exit(0)'
for c in input()[::-1]:p='print(%r);exit(ord(%r))'%(p,c)
print(p)

```

This code takes input from STDIN and outputs the first program to STDOUT.

If the input is `ABCDE`, the results are

```
 0 print('print(\'print(\\\'print("print(\\\\\\\'exit(0)\\\\\\\');exit(ord(\\\\\\\'E\\\\\\\'))");exit(ord(\\\\\\\'D\\\\\\\'))\\\');exit(ord(\\\'C\\\'))\');exit(ord(\'B\'))');exit(ord('A'))
65 print('print(\'print("print(\\\'exit(0)\\\');exit(ord(\\\'E\\\'))");exit(ord(\\\'D\\\'))\');exit(ord(\'C\'))');exit(ord('B'))
66 print('print("print(\'exit(0)\');exit(ord(\'E\'))");exit(ord(\'D\'))');exit(ord('C'))
67 print("print('exit(0)');exit(ord('E'))");exit(ord('D'))
68 print('exit(0)');exit(ord('E'))
69 exit(0)
 0

```

where each line contains the exit code and the output of the previously executed program (the first line is the first program).

# Answer
> 3 votes
# Python 3, ~~115~~ ~~108~~ 100 bytes

```
i=input()
r="%s"
k=""
for c in i:r%="print(%s\"%%s%s\");exit(%i)"%(k,k,ord(c));k+=k+"\\"
print(r%"")

```

Try it online!

---

For the input `Hello`, the program prints:

```
print("print(\"print(\\\"print(\\\\\\\"print(\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\");exit(111)\\\\\\\");exit(108)\\\");exit(108)\");exit(101)");exit(72)

```

---

The program above prints:

```
print("print(\"print(\\\"print(\\\\\\\"\\\\\\\");exit(111)\\\");exit(108)\");exit(108)");exit(101)

```

and exits with code `72`.

Try it online!

---

The program above prints

```
print("print(\"print(\\\"\\\");exit(111)\");exit(108)");exit(108)

```

and exits with code `101`.

Try it online!

---

The program above prints:

```
print("print(\"\");exit(111)");exit(108)

```

and exits with code `108`.

Try it online!

---

The program above prints:

```
print("");exit(111)

```

and exits with code `108`.

Try it online!

---

The program above prints nothing and exits with code `111`.

Try it online!

---

The empty program prints nothing and exits with code `0`.

Try it online!

# Answer
> 2 votes
# C, 156 bytes

```
char*s="char*s=%c%s%c;n=%d;char*t=%c%s%c;main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}";main(i,t)char**t;{printf(s,34,s,34,0,34,t[1],34);}

```

Try it online! (Open the debug-tab to see the exit code.)

Takes input as a command line argument.

For input "ABC", this outputs the program

```
char*s="char*s=%c%s%c;n=%d;char*t=%c%s%c;main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}";n=0;char*t="ABC";main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}

```

which returns 65 and outputs

```
char*s="char*s=%c%s%c;n=%d;char*t=%c%s%c;main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}";n=1;char*t="ABC";main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}

```

which returns 66 and outputs

```
char*s="char*s=%c%s%c;n=%d;char*t=%c%s%c;main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}";n=2;char*t="ABC";main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}

```

which returns 67 and outputs

```
char*s="char*s=%c%s%c;n=%d;char*t=%c%s%c;main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}";n=3;char*t="ABC";main(){n<strlen(t)&&printf(s,34,s,34,n+1,34,t,34);return t[n];}

```

which outputs nothing and returns 0.

# Answer
> 2 votes
# Python 2, 67 bytes

Based on this answer, but modified to use Python 2, with a trivial program `0` to print nothing and exit.

```
p=0
for c in input()[::-1]:p='print %r;exit(ord(%r))'%(p,c)
print p

```

**Try it online**

# Answer
> 1 votes
# RPL, 73 bytes

With hp8 code page.

Turn on your HP48 or similar, or fire droid48. Do not forget to `-52 SF` for better visualization of the stack. I assume you have already pushed the string, e.g. `"ABC"`, on the stack. Then key in the following function:

```
→ x«{LAST}x{DUP NUM 3ROLLD 2OVER SIZE DUP{SUB 2SWAP PUT}{4DROPN}IFTE}+ +»

```

(For convenience I suggest to push the α key twice before typing anything, hence locking alpha input mode. Latter just use the DEL key to cancel the automatically inserted closing delimiters. Simply use the ENTER key to validate. Do not forget the space after the stab operator.)

This function immediately pushes on the stack a self-modifying program, under the form of a list. (But the function above does not modify itself). As the L in RPL originally stands for LISP, pressing the EVAL key will indeed evaluate this program. It returns the exit code on stack level two, and leaves itself, modified (yes, *here* it is questionable), for a latter EVAL. So press EVAL repeatedly until the program finally stops to drop itself on stack level one. The final exit code 0 thus appears on level one, with past exit codes above. If you forgot to `-52 SF`, you can navigate in the stack after each EVAL by pressing the ▴ key (leave this navigation mode with the ON key). The above function does accept strings with 0x0 chars inside, to create such strings `0 CHR` and `+` are your friends. The self modification consists of removing the used char from the embedded string (the `SUB 2 SWAP PUT` branch). Hence the dropped program is shorter after each EVAL. The `4 DROPN` branch ensures the *output nothing* instruction from the OP is respected, dropping among others the program itself. Of course all this assumes your note a `-55 SF` adept. Users of `-55 SF` shall be banned. Forever.

I assume an RPL/2 solution exists, and could feature a real unix exit code, but afaik RPL/2 has limited introspection, and cannot evaluate lists.

# Answer
> 1 votes
## PowerShell, 172 156 bytes.

```
param($i)
$s=@'
if($i='{0}'){{
$s=@'
{1}'@
$s-f($i-replace'^.'-replace"'","''"),"$s`n"
$host.setshouldexit($i[0])
}}
exit
'@
$s-f$i.replace("'","''"),"$s`n"

```

The `h3l}'{l0` input will result the next output

Try it online!

```
if($i='h3l}''{l0'){
$s=@'
if($i='{0}'){{
$s=@'
{1}'@
$s-f($i-replace'^.'-replace"'","''"),"$s`n"
$host.setshouldexit($i[0])
}}
exit
'@
$s-f($i-replace'^.'-replace"'","''"),"$s`n"
$host.setshouldexit($i[0])
}
exit

```

Which in the own turn will output

Try it online!

```
if($i='3l}''{l0'){
$s=@'
if($i='{0}'){{
$s=@'
{1}'@
$s-f($i-replace'^.'-replace"'","''"),"$s`n"
$host.setshouldexit($i[0])
}}
exit
'@
$s-f($i-replace'^.'-replace"'","''"),"$s`n"
$host.setshouldexit($i[0])
}
exit

```

The last run will output nothing and exit code will be 0.

Try it online!

```
if($i=''){
$s=@'
if($i='{0}'){{
$s=@'
{1}'@
$s-f($i-replace'^.'-replace"'","''"),"$s`n"
$host.setshouldexit($i[0])
}}
exit
'@
$s-f($i-replace'^.'-replace"'","''"),"$s`n"
$host.setshouldexit($i[0])
}
exit

```

# Answer
> 1 votes
# sed, ~~467~~ 461 bytes

Character codes are hard:

```
s:^:Y:
:b
s:ZY[ (2<FPZdnx]:0_Y:
s:ZY[ )3=GQ[eoy]:1_Y:
s:ZY[ *4>HR\fpz]:2_Y:
s:ZY[]!+5?ISgq{]:3_Y:
s:ZY[",6@JT^hr|]:4_Y:
s:ZY[-#7AKU_is}]:5_Y:
s:ZY[$.8BLV`jt~]:6_Y:
s:ZY[%/9CMWaku]:7_Y:
s:ZY[&0:DNXblv]:8_Y:
s:ZY['1;EOYcmw]:9_Y:
s:Y[ -']:3Z&:
s:Y[(-1]:4Z&:
s:Y[2-9:;]:5Z&:
s:Y[<=>?@A-E]:6Z&:
s:Y[F-O]:7Z&:
s:Y[P-Y]:8Z&:
s:Y[]Z\-`abc]:9Z&:
s:Y[d-m]:10Z&:
s:Y[n-w]:11Z&:
s:Y[xyz{-~]:12Z&:
tb
s/([^_]+)_Y$/ q\1/
:
s/[/\]/\\&/g
s/([^_]+)_ (.*)/ s\/^\/\2\/;q\1/
/^\S/b

```

Try it online!

Otherwise, the logic is rather straightforward: (1) escape special characters (there're two), (2) wrap in an additional `s/^/…/;q\1` layer, (3) repeat.

Here's the output for `hello`:

```
 s/^/s\/^\/s\\\/^\\\/s\\\\\\\/^\\\\\\\/q111\\\\\\\/;q108\\\/;q108\/;q101/;q104

```

And a little script that I used:

```
#!/bin/bash
set -uo pipefail
IFS=$'\n'

P=$(echo $1 | sed -rf q.sed)
echo $P

echo $1 | od -An -tuC

for char in $(echo $1 | sed 's:.:&\n:g'); do
    P=$(echo | sed $P)
    printf ' %3d' $?
done

```

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


# Question
Title: Extract the Coefficients of a Linear Equation
Given a linear equation `mx+n`, return `n` and `m`. However, the equation may be in any of the following formats:

```
5x+2 -> 5 2
5x-2 -> 5 -2
5x   -> 5 0
-2   -> 0 -2
x    -> 1 0

```

Here are the formats, where each `?` stands for a positive integer written without leading zeroes

```
?x+?
?x-?
-?x+?
-?x-?
x+?
x-?
?
-?
?x
-?x
x

```

All of these cases must be handled.

## Specifications:

* You can assume that the equation is in one of the above formats, i.e. it matches the regex `^(-?[123456789]\d*)?x([+-][123456789]\d*)?|-?[123456789]\d*$`.

## Test Cases:

```
-2x+3 -> -2 3
44x   -> 44 0
-123  -> 0 -123
x     -> 1 0
-1x   -> -1 0

```

# Answer
# Python 2, 55 bytes

```
j=1j
c=eval(input().replace(*'xj'))
print c.imag,c.real

```

Try it online!

Uses Python's built-in code evaluation. The input is formatted like a complex number by replacing `x` with`j`, Python's complex unit. Because only literals like `2j` are recognized, but not `j` or `-j`, the variable `j` is assigned as `1j` to cover those.

Unfortunately, Python doesn't seem to have a built-in to convert a complex number to a pair of reals.
> 12 votes

# Answer
## Mathematica, 16 bytes

Inspired by xnor's Python 2 answer:

```
ReIm[I#/.x->-I]&

```

Takes input as a literal expression (not a string), and returns a pair of numbers. It works by making `x` a complex number then taking the real and imaginary parts — the only non-obvious bit is multiplying by *i* to start with, to get the output in the right order.

We can also use

```
ReIm[x=-I;I#]&

```

for 14 bytes (tied with Jelly!), but setting `x` to equal *-i* before taking the input, instead of just replacing `x` afterwards, feels like cheating…
> 4 votes

# Answer
## JavaScript (ES6), ~~53~~ 48 bytes

```
s=>([a,b]=s.split(/x\+?/),1/b?[a||1,b||0]:[0,s])

```

### Test cases

```
let f =

s=>([a,b]=s.split(/x\+?/),1/b?[a||1,b||0]:[0,s])

console.log(f("-2x+3")) // -> -2 3
console.log(f("44x"))   // -> 44 0
console.log(f("-123"))  // -> 0 -123
console.log(f("x"))     // -> 1 0
console.log(f("-1x"))   // -> -1 0
```
> 3 votes

# Answer
# sed, ~~44~~ 42 bytes

```
s:+::
s:x: :
t
s:^:0 :
:
s:^ :1 :
s: $: 0:

```

Try it online!

I/O: one per line.

-2 bytes thanks to @KritixiLithos.
> 3 votes

# Answer
# Jelly, ~~18~~ 14 bytes

```
”x;ṣ”xVṫ-µ¬ṂW+

```

Test suite at **Try it online!**

### How?

```
”x;ṣ”xVṫ-µ¬ṂW+ - Main link: list of characters s  examples: "5x-2"         "x"       "-123"
”x             - literal 'x'
  ;            - concatenate with s                        "x5x-2"        "xx"      "x-123"
   ṣ”x         - split on 'x's                        ["","5","-2]  ["","",""]  ["","-123"]
      V        - evaluate as Jelly code (vectorises)      [0,5,-2]     [0,0,0]     [0,-123]
       ṫ-      - tail from index -1 inclusive               [5,-2]       [0,0]     [0,-123]
         µ     - monadic chain separation (call that z)
          ¬    - not z                                       [0,0]       [1,1]        [1,0]
           Ṃ   - minimum                                         0           1            0
            W  - wrap in a list                                [0]         [1]          [0]
             + - add to z (vectorises)                      [5,-2]       [1,0]     [0,-123]

```
> 2 votes

# Answer
## Mathematica, 23 bytes

```
Coefficient[#,x,{1,0}]&

```

Try it online

copy and paste with ctrl-v this code

```
Coefficient[#,x,{1,0}]&[-2x+3]

```

and press shift+enter to run
> 2 votes

# Answer
# PHP, 73 Bytes

```
preg_match("#((.*)x)?\+?(.*)#",$argn,$t);echo$t[1]?$t[2]?:1:0," ",+$t[3];

```

Try it online!

# PHP, 91 Bytes

works also with `-x`

```
preg_match("#((-)?(\d+)?x)?\+?(-?\d+)?#",$argn,$t);echo$t[2],$t[1]?$t[3]?:1:0," ",$t[4]?:0;

```

Try it online!
> 2 votes

# Answer
# Python 2, 71 bytes

```
lambda s:([0,]+[int(x or`1-i`)for i,x in enumerate(s.split('x'))])[-2:]

```

Try it online!
> 1 votes

# Answer
# Mathematica, 33 bytes

```
#~CoefficientList~x/.{a_}:>{a,0}&

```

Pure function taking an expression in the expected format (note: not a string, but a pure expression like `-2x+3`), and returning an ordered pair of integers with the constant coefficient appearing first (for example, `-2x+3` returns `{3,-2}`).

The builtin `CoefficientList` (which works for polynomials of any degree) does the heavy lifting; its default behavior is to return constants as length-1 lists, so `/.{a_}:>{a,0}` overrides that and makes the `0` coefficient of `x` appear explicitly.
> 1 votes

# Answer
# Retina, 38 bytes

```
x$
x+0
^[^+-]*$
0x+$+
^[^-\d]
1$+
-
+-

```

Definitely can be improved.

Possibly stretching how we are allowed to format output. It just outputs a complete equation, as in `n` and `m` separated by `x+`

Try it online!
> 0 votes

# Answer
# Octave, 45 bytes

```
@(a)[imag(u=eval(strrep(a,'x','j'))),real(u)]

```

Try it online!

Evaluate the expression, with `x` replaced by complex `j`. Octave is very flexible when it comes to complex expressions, with `j`,`1j`,`i` and `1i` all equivalent (with the advantage that `1j` and `1i` cannot be overwritten by variables, but that's irrelevant for this challenge). Inline expression is used to build a list of `[imag(u) real(u)]` with `u` the complex number.

I initially wanted to try a more idiomatic approach, using the built-in `sym2poly`. For example (already at 47 bytes to make sure `0*x` is handled):

```
@(a)sym2poly([strrep(a,'x','*x') '+x^2']))(2:3)

```

This one however failed on the case of `x` without coefficient. In the end a real/complex setup like `xnor` turned out to be optimal.
> 0 votes

# Answer
# MATL, 12 bytes

```
120'i'ZtU&Zj

```

Try it online!

Port of my Octave answer, but of course adapted for compactness in MATL. Explanation:

```
120'i'Zt     % Replace character 120 ('x') by 'i' in input (implicit).
             % (Used 120 instead of 'x' to save a separator between 'x' and 'i')
        U    % Convert string to complex number
         &Zj % Split complex number in real and imaginary part. Implicit display.

```
> 0 votes

# Answer
# C (gcc),~~145~~ ~~138~~ 112 bytes

```
f(char*s){int a,b,i=0;sscanf(s,"%dx%d",&a,&b);if(L!=0)i=(int)(L-s);printf("%d %d",s[i]=='x'?a:0,s[i]=='x'?b:a);}

```

Try it online!

```
void f(char*s)
{
    int a,b,i=0;
    sscanf(s,"%dx%d",&a,&b);

    if(L!=0)
      i=(int)(L-s);

    printf("%d %d",s[i]=='x'?a:0,s[i]=='x'?b:a);
}

```

Can definitely be shortened, but dont see it now!
> 0 votes

---
Tags: code-golf, string, number, parsing
---


title: The modulus validation

text:
# Question
Title: The modulus validation
Given a list of math expressions that all hold true and consist of modulo remainder calculations with two numbers and a result, your task is to yield the first `n` numbers that hold true for all the statements in the list.

For example:

`[m % 3 = 0, m % 4 = 1, m % 5 = 3]`, where % is the modulo operator.

For `n` = 3, the first 3 numbers (counting from 0) that fit the sequence are `33, 93, 153`, thus your result would be that (format up to you).

## Rules / IO

1. You take a positive number `n` and a list of truths. Of course, the things you need take are only the RHS of the modulo operation and the result.
2. `n` and the numbers in the list of truths will always be in the range **1 -\> 2^31-1**, and so are the results.
3. You take input in any convenient form and output in any convenient form. For example, input: `3 [3 0, 4 1, 5 3]` and output: `33 93 153`.
4. It's guaranteed that the solution is mathematically possible.
5. The source of input can be from a file, function parameters, stdin, etc... Same goes for the output.
6. No loopholes.
7. This is code-golf, so the lowest byte count wins.

## Testcases

```
# Input in the form <n>, <(d r), (d2 r2), ...>
# where <d> = RHS of the modulo expression and <r> the result of the expression. Output in the next line.

5, (3 2), (4 1), (5 3)
53 113 173 233 293

3, (8, 0), (13, 3), (14, 8)
120 848 1576

```

## Reference implementation in pseudo-code

```
n = (an integer from stdin)
truths = (value pairs from stdin)
counter = 0

while n != 0 {
    if matches_criterias(counter, truths) {
        print counter
        n -= 1
    }

    counter += 1
}

```

# Answer
> 6 votes
# Jelly, 7 bytes

```
%⁼⁴
0ç#

```

This is a full program. Arguments are divisors, target moduli, and number of solutions, in that order.

Try it online!

### How it works

```
0ç#  Main link.
     Left argument: D (array of divisors)
     Right argument: M (array of target moduli)
     Third argument: n (number of solutions)

0ç#  Execute the helper link with k = 0, 1, 2, ... as left argument and D as the
     right one until n of them return 1. Yield the array of matches.

%⁼⁴  Helper link. Left argument: k. Right argument: D

%    Compute k % d for each d in D.
 ⁼⁴  Compare the result with M.

```

# Answer
> 4 votes
## JavaScript (ES6), ~~74~~ ~~70~~ 69 bytes

Takes input as an integer `n` and an array `a` of `[modulo, remainder]` arrays with currying syntax `(n)(a)`.

```
n=>a=>eval('for(i=r=[];a.some(([b,c])=>i%b-c)||--n*r.push(i);i++);r')

```

### Test cases

```
let f =

n=>a=>eval('for(i=r=[];a.some(([b,c])=>i%b-c)||--n*r.push(i);i++);r')

console.log(f(5)([[3, 2], [4, 1], [5, 3]]))
console.log(f(3)([[8, 0], [13, 3], [14, 8]]))
```

# Answer
> 4 votes
# Perl 6, 33 bytes

```
{grep((*X%@^b)eqv@^c,0..*)[^$^a]}

```

Try it

The input is `( number-of-values, list-of-divisors, list-of-remainders )`

## Expanded:

```
{   # bare block lambda with placeholder parameters ｢$a｣ ｢@b｣ ｢@c｣

  grep(

    # WhateverCode lambda:
    (

      *        # the value being tested

      X%       # cross modulus

      @^b      # with the divisors ( second parameter )

    )

    eqv        # is that list equivalent with

    @^c        # the expected remainders ( third parameter )

    # end of WhateverCode lambda

    ,

    0 .. *     # Range of all Integers starting with 0

  )[ ^$^a ]    # grab up-to ｢$a｣ values ( first parameter )
               # ( ｢^$a｣ is the same as ｢0 ..^ $a｣ )
}

```

# Answer
> 4 votes
## JavaScript (ES6), ~~71~~ 68 bytes

```
a=>f=(n,m=0)=>n?a.some(x=>m%x[0]-x[1],++m)?f(n,m):[m,...f(n-1,m)]:[]

```

A simple recursive function. Use by currying in the array first and `n` second, like so:

```
g=a=>f=(n,m=0)=>n?a.some(x=>m%x[0]-x[1],++m)?f(n,m):[m,...f(n-1,m)]:[]
g([[3, 2], [4, 1], [5, 3]])(5)

```

# Answer
> 3 votes
## Haskell, 47 bytes

```
n#l=take n[i|i<-[0..],all(\(d,r)->mod i d==r)l]

```

Usage example: `3 # [(8,0),(13,3),(14,8)]` -\> `[120,848,1576]`.

# Answer
> 3 votes
## JavaScript (ES6), ~~72~~ 70 bytes

```
a=>g=(n,i,r=[],m=a.some(e=>i%e[0]^e[1]))=>n?g(n-!m,-~i,m?r:[...r,i]):r

```

Curried over the conditions array first and number of results second. Edit: Saved 2 bytes by not handling the zero case.

# Answer
> 3 votes
# Python, 67 bytes

```
lambda n,r:[k for k in range(2**32)if all(k%d==m for d,m in r)][:n]

```

# Answer
> 2 votes
# Mathematica, 42 bytes

```
#2~ChineseRemainder~#+Range[0,#3-1]LCM@@#&

```

Unnamed function, returning a list of positive integers, and taking three inputs: the list of moduli, the list of remainders, and the number `n` of integers to return. For example, the second test case is invoked by

```
#2~ChineseRemainder~#+Range[0,#3-1]LCM@@#&[{8,13,14},{0,3,8},3]

```

and returns `{120, 848, 1576}`.

The builtin `#2~ChineseRemainder~#` gives the smallest nonnegative solution; to get all the desired solutions, we add this number to `Range[0,#3-1]LCM@@#`, which is the first `n` nonnegative multiples of the least common multiple of all the moduli.

Mathematica doesn't have lazily-evaluated infinite lists as far as I know, so this implementation was shorter than anything I found that tested nonnegative integers one by one—even with the length of the function name `ChineseRemainder`, and even though a test like `Mod[k,{8,13,14}]=={0,3,8}` works perfectly well.

# Answer
> 2 votes
# PHP, 97 bytes

longest answer so far. But I´m glad I could get it below 100.

```
for($a=$argv;++$k;)for($i=$v=2;$m=$a[$i++];$v>$argc/2&&$a[1]-->0?print$k._:0)$v+=$k%$m==$a[$i++];

```

takes input from separate command line arguments,
prints matches separated and trailed by underscores.
Loop never breaks; barely suitable for online testers.

Run like `php -r 'code' <n> <modulo1> <result1> <modulo2> <result2> ...`.

**breakdown**

```
for($a=$argv;++$k;)         // loop $k up from 1
    for($i=$v=2;                // $i = argument index, $v=2+ number of satisfied equations
        $m=$a[$i++];            // loop through modulo/result pairs
        $v>$argc/2                  // 2. if $v>argument-count/2
        &&$a[1]-->0                 // and match count not exhausted
            ?print$k._                  // print match
            :0                          // else do nothing
        )
            $v+=$k%$m==$a[$i++];    // 1. if $k%modulo==result, increment $v

```

**notes**

`$argc==count($argv)`. For three pairs there are 8 arguments: the filename `$argv[0]`, `n`=`$argv[1]` and the `modulo`/`result` pairs above that. `$v=2` incremented 3 times gives `5`\>`$argc/2`.

Add one byte for a clean exit: Replace `&&$a[1]-->0?print$k._` with `?$a[1]--?print$k._:die`.

# Answer
> 1 votes
# Pyth - ~~14~~ 13 bytes

```
.f!fneT%ZhTQE

```

Try it online here.

# Answer
> 1 votes
# SmileBASIC, 102 bytes

```
DEF V N,M
FOR K=1TO N@L
T=T+1F=0FOR J=1TO LEN(M)F=F||T MOD M[J-1]-M[J]J=J+1NEXT
ON!F GOTO @L?T
NEXT
END

```

This is the first time I've ever used `ON` in SB. The reason I used it here instead of `IF F GOTO@L` was so I could put `?T` after it on the same line, saving 1 byte.

# Answer
> 1 votes
# Python, 59 bytes

```
lambda n,m:[i for i in range(2**31)if all(map(eval,m))][:n]

```

`m` is a list of expressions in string form like `["i % 4 == 1", ...]`

**Try it online** (with a shorter range, so it will actually finish)

# Answer
> 0 votes
# PHP, 91 Bytes

Take the list as associative array

```
<?for($t=1;$r<$_GET[1];$i+=$t=!$t?:print+$i._.!++$r)foreach($_GET[0]as$k=>$v)$t*=$i%$k==$v;

```

Try it online!

---
Tags: code-golf, number
---