text
stringlengths 180
608k
|
---|
[Question]
[
Given a permutation, we can define its high-water marks as the indices in which its cumulative maximum increases, or, equivalently, indices with values bigger than all previous values.
For example, the permutation \$ 4, 2, 3, 7, 8, 5, 6, 1 \$, with a cumulative maximum of \$ 4, 4, 4, 7, 8, 8, 8, 8 \$ has \$1, 4, 5\$ as (1-indexed) high-water marks, corresponding to the values \$4, 7, 8\$.
Given a list of indices and a number \$n\$, generate some permutation of size \$n\$ with the list as its high-water marks **in time polynomial in \$n\$**.
This is code golf, so the shortest solution in each language wins.
# Test Cases
In all of those except the first, more than one valid permutation exist, and you may output any one of them.
```
1-based high-water mark indices, n -> a valid permutation
[1, 2, 3], 3 -> [1, 2, 3]
[1, 2, 3], 5 -> [2, 3, 5, 4, 1]
[1, 4, 5], 8 -> [4, 2, 3, 7, 8, 5, 6, 1]
[1], 5 -> [5, 4, 3, 2, 1]
[1, 5], 6 -> [4, 1, 3, 2, 6, 5]
```
# Rules
* You can use any reasonable I/O format. In particular, you can choose:
+ To take the input list as a bitmask of size \$n\$, and if you do that whether to take the size at all.
+ Whether the input is 0-indexed or 1-indexed.
+ Whether to have the first index (which is always a high-water mark) in the input. When taking a bitmask, you may take a bitmask of size \$n-1\$ without the first value. When taking a list of indices, you can have it indexed ignoring the first value.
+ Whether the output is a permutation of the values \$0,1,...,n-1\$ or \$1,2,...,n\$.
+ To output any non-empty set of the permutations, as long as the first permutation is outputted in polynomial time.
+ To have the cumulative minimum decrease in the given points instead.
+ To have the cumulative operation work right-to-left, instead of left-to-right.
* It is allowed for your algorithm to be non-deterministic, as long as it outputs a valid permutation with probability 1 and there's a polynomial \$p(n)\$ such that the probability it takes more than \$p(n)\$ time to run is [negligible](https://en.wikipedia.org/wiki/Negligible_function). The particular distribution doesn't matter.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 5 bytes
```
.,@?:-,_@@
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWq_R0HOytdHXiHRwgAlDxDdFK0YY6JjqmsUo6CkoWSrFQcQA)
Puts the \$k\$ highest numbers at the specified indices in ascending order and the remaining numbers at the remaining indices, where \$k\$ is the number of marks.
```
[1, 4, 5], 8 -> [6, 1, 2, 7, 8, 3, 4, 5]
```
## Explanation
```
.,@?:-,_@@
. Map
, range
@ second input
? find index in
: join
- list difference
, range
_ second input
@ first input
@ first input
```
If I'm reasoning correctly, the time complexity should be \$\mathcal O\left(n^2\right)\$.
[Answer]
# [R](https://www.r-project.org/), 23 bytes
*Edit: -9 bytes thanks to Command Master by switching to use a bitmask as input*
```
function(h)rank(h,,"f")
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jQ7MoMS9bI0NHRylNSfN/mkayhqEOEGpqKnByKitA@EY6xppAxAWX1THQMQCpQFFgClMAlIQpAimDqzIBKtGxQFYFkYcpQDPCAOQKhCOAes00/wMA "R – Try It Online")
Input is simply a bitmask `h`, no need to provide `n` as this is implicitly the length of the bitmask.
The `"f"` (short for `ties="first"`) argument to `rank()` indicates that ties with the same rank should be broken using "increasing values at each index set of ties".
# [R](https://www.r-project.org/), 32 bytes
```
function(h,n)rank(1:n%in%h,,"f")
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jQydPsygxL1vD0CpPNTNPNUNHRylNSfN/mkayhqGOkY6xJhBxIfFMYTwTIFPHAspDEgeKmmn@BwA "R – Try It Online")
Same approach as above, except inputting `h` as the indices of high-water marks, together with `n`.
`1:n %in% h` returns a vector of mainly zeros, with ones where the high-water marks should be (in other words, converting the indices to a bitmask).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~4~~ 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ỤỤ
```
A monadic Link that accepts a bitmask identifying the high watermarks and yields a permutation.
**[Try it online!](https://tio.run/##y0rNyan8///h7iVA9P///2hDHQUDMDIEIwjbIBYA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///h7iVA9P9w@6OmNf//R0cb6iiAUKyOAoypo2AARFABAzBCCKPLYBMAsWNjAQ).
#### How?
```
ỤỤ - Link: bitmask e.g. [1,0,0,1,0,0]
Ụ - grade-up (indices of sorted values) [2,3,5,6,1,4]
Ụ - grade-up (indices of sorted values) [5,1,2,6,3,4]
```
---
### Previous at 4 bytes (not using a bitmask):
```
ReÞỤ
```
A dyadic Link that accepts the number on the left and the high watermark indices on the right and yields a permutation.
**[Try it online!](https://tio.run/##y0rNyan8/z8o9fC8h7uX/P//3@J/tKGOiY5pLAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z8o9fC8h7uX/D@83EH/UdOa//@jo6MNdRSMdBSMY8GYSwFZwBQuYALmKFhABVDkQBJmQF4sAA "Jelly – Try It Online").
#### How?
```
ReÞỤ - Link: n; I e.g. n=6; I=[1,4]
R - range (n) [1,2,3,4,5,6]
Þ - sort by:
e - exists in (I)? [2,3,5,6,1,4]
Ụ - grade-up (indices of sorted values) [5,1,2,6,3,4]
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
ɾ$ÞṖRf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJviTDnuG5llJmIiwiIiwiOFxuWzEsIDQsIDVdIl0=)
Takes `n` and then a list of indices.
```
ɾ # range
$ # swap top two items on the stack
ÞṖ # split before indices
R # reverse each
f # flatten
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LDŠåÅ¡í˜
```
Port of [@AndrovT's Vyxal answer](https://codegolf.stackexchange.com/a/258479/52210).
[Try it online](https://tio.run/##ASEA3v9vc2FiaWX//0xExaDDpcOFwqHDrcuc//84ClsxLDQsNV0) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC8X8fl6MLDi893Hpo4eG1p@f81/kfHW2sE22oY6RjHBuroxBtisyxAHFMdEzhMmCGGUgUKBYLAA).
**Explanation:**
```
L # Push a list in the range [1, first (implicit) input n]
D # Duplicate this list
Š # Triple-swap it with the second (implicit) input: [1,n], input-list, [1,n]
å # Check for each value of [1,n] whether it's in the input-list
Å¡ # Split the second [1,n]-list before the truthy indices
í # Reverse each inner list
˜ # Flatten it to a single list
# (after which the result is output implicitly)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
XKSE+-KQQK
```
[Try it online!](https://tio.run/##K6gsyfj/P8I72FVb1zsw0Pv//2hDHSMd41guUwA "Pyth – Try It Online")
Takes the indices then the length, runs in \$\mathcal{O}(n^2)\$. Uses the same general strategy as most others, putting the \$n\$ highest values at the given indices.
### Explanation
```
# implicitly assign Q = eval(input()) to the indices
KSE # assign K = [1, 2, ..., eval(input())]
-KQ # elements of K not in Q
+ Q # concatenated to Q
XK K # translate K from this to K
```
[Answer]
# [R](https://www.r-project.org), 16 bytes
Not enough reputation to comment on Dominic's answer, but using the new anonymous function syntax in R, a few bytes can be shaved off:
`\(h)rank(h,,"f")`
[Answer]
# Python 3, 64 bytes
Uses zero-based indexing
```
f=lambda m,n:sum(([*range(*t)][::-1]for t in zip(m,m[1:]+[n])),[])
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 45 bytes
```
m=>n=>m.map(i=>i?++n-eval(m.join`+`):++x,x=0)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcHa5Py84vycVL2c_HQNjaWlJWm6Fjd1c23t8mztcvVyEws0Mm3tMu21tfN0U8sSczRy9bLyM_MStBM0rbS1K3QqbA00IZp2aGpEG-oYAKGhDoQ2iNXUsNCESi9YAKEB)
Takes a bit mask and length. Runs in \$\mathcal O(n)\$.
This is probably my first time golfing in JavaScript, please leave suggestions how to improve the code.
*-7 thanks to Kevin Cruijssen, Shaggy and Arnauld*
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 38 bytes
```
^.+
*
_
$.`¶
^D`
G`.
.+
$&,$:&
N`
.+,
```
[Try it online!](https://tio.run/##K0otycxLNPz/P05Pm0uLK55LRS/h0DauOJcELvcEPS6goIqajoqVGpdfApCjw/X/vwWXAZcxlwkA "Retina – Try It Online") Takes `n` as the first input and then the element of the 0-indexed list. Explanation: Inspired by @DominicVanEssen's R answer.
```
^.+
*
```
Convert `n` to unary.
```
_
$.`¶
```
Get a range from `0` to `n`.
```
^D`
```
Remove all but the last instance of all duplicates.
```
G`.
```
Remove all blank lines.
```
.+
$&,$:&
```
Append the line index to each value.
```
N`
```
Sort by value.
```
.+,
```
Delete the values, leaving their original indices.
[Answer]
# [Python](https://www.python.org) NumPy, 56 bytes
```
def f(m,n):x=m[:1]*range(n);_,*x[m-1]=*x[m-1],n;return x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3LVJS0xTSNHJ18jStKmxzo60MY7WKEvPSUzXyNK3jdbQqonN1DWNtobROnnVRaklpUZ5CBVS_XmZuQX5RiUJeaW5BpUJisUJeAVdBUWZeiUaaRl6BXlF8tKGOkY6ZjkWsjqGBpiZEF8x2AA)
1-based. Expects a numpy array and an integer.
## How?
Populates the output with a 0-based (!) range. Then shifts the values at the marked indices one position to the left ignoring non marked indices and filling the right most position with n. As the left most marked index always is 0, a 0 was lost and an n gained, generating a 1-based permutation.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
IEη⌕⁺⁻…⁰ηθθι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQCNDR8EtMy9FIyCntFjDNzMPSAYl5qWnahjoKGRo6igUQnGmJhBY//8fHQ2UMNZRMInVUbCI/a9blgMA "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation: Port of @xigoi's Nibbles answer.
```
η Input `n`
E Map over implicit range
⌕ Find index of
ι Current value in
… Range from
⁰ Literal integer `0`
η To input `n`
⁻ Remove elements from
θ Input list
⁺ Concatenated with
θ Input list
I Cast to string
Implicitly print
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~11~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
õ ò@VøYÃcÔ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9SDyQFb4WcNj1A&input=OCBbMSwgNCwgNV0gLVE)
-1 by Shaggy (crossed out 11
is still regular 11)
```
õ ò@VøYÃcÔ
õ # range [1, input integer]
ò@ Ã # partitioned between pairs X, Y where
VøY # Y is contained in input array
cÔ # reverse each and flatten
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 39 bytes
```
x=>x.map(t=>!t&&++i,i=0).map(t=>t||++i)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1q5CLzexQKPE1k6xRE1NWztTJ9PWQBMmVlJTAxTS/G/NlZyfV5yfk6qXk5@ukaYRbahjAIQQEghjNTX/AwA "JavaScript (Node.js) – Try It Online")
Take marks
] |
[Question]
[
### Background
Here in the UK1, these are the income tax rules:
* You get a personal allowance (untaxed) of up to £12,570:
+ If you earn less than £100,000, you get the full £12,570 as personal allowance
+ For every £2 over £100,000, your personal allowance goes down by £1
* After the personal allowance, the next £37,700 is taxed at the "basic rate" of 20%
* After that, the next £99,730 is taxed at the "higher rate" of 40%
* Finally, anything above this is taxed at the "additional rate" of 45%
1: This isn't actually the case in Scotland; only England, Wales and Northern Ireland.
### Your task
Using the above tax rules, take in an annual salary (as a positive integer) and calculate the income tax.
### Test cases
```
Input Output
12570 0
50000 7486
80000 19432
120000 39432
200000 75588.5
```
Note: the final test case can be any of 75588, 75588.5, or 75589 (any is fine)
### Clarifications
* You can choose whether to make the personal allowance an integer or keep it as a float
+ e.g. if the input is £100,003, the personal allowance can be £12,569, £12,568.50, or £12,568
* The same goes for the final output. If it ends up as a float, you can make it an integer or keep it as a float
+ (see the final test case)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
[Answer]
# JavaScript (ES6), 99 bytes
Works with floats and rounds the final result.
```
n=>[137430.45,37700.4,.2].map(v=>x+=v%1*(n-(n-=m(n-~~v))),x=0,n-=(m=v=>v>0&&v)(12570-m(n-1e5)/2))|x
```
[Try it online!](https://tio.run/##bczBDoIwDAbgO0/BRbLqGBtjbh7GixgPBNFogBExCwfDq88hHJTYNE3T70/vhS368nHrnnFrzpW7aNfq/Mi4zDglmcBcSuoXTNITaYoOWZ0PO203bIva2Ldu/BhHCwB40BT7C2q0T9mcRpEFxFIhaTylWCUgSQFegytN25u6IrW5osscCQHCJAlp8GuC@lpMZmq/YvXF7JDxNFi/ngKz8z/@4cWlEEoR4d4 "JavaScript (Node.js) – Try It Online")
```
n => // n = input
[ // in this array, the integer part is the threshold (T)
// and the decimal part is the tax rate (R)
137430.45, // T = 99730 + 37700, R = 45%
37700.4, // T = 37700, R = 40%
.2 // T = 0, R = 20%
] //
.map(v => // for each entry v:
x += // add to x:
v % 1 * // the tax rate multiplied by
( n - // the difference between the current value of n
( n -= // and the updated value of n, which is:
m(n - ~~v) // n - max(0, n - threshold)
) //
), //
x = 0, // start with x = 0
n -= // start by applying the personal allowance
( m = v => // m is a helper function taking v ...
v > 0 && v // ... and returning max(0, v)
) //
( // personal allowance:
12570 - // 12570 - max(0, n - 100000) / 2
m(n - 1e5) / 2 //
) //
) // end of map()
| x // return the final value of x
```
[Answer]
# [Python](https://www.python.org), ~~83~~ ~~80~~ 77 bytes
*-3 thanks to @Max by removing the `0` from the beginning of the floating points.*
*-3 thanks to @tsh by using integers which are then divided instead of floats and changing the personal allowance operation.*
```
lambda m:sum(([4]*37700+[8]*99730+[9]*m)[:m-max(0,min(62570-m//2,12570))])/20
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5BbsMgEEX3nGLEClwcY2wCtuTeICdwvHBVWUEKYMUkSq_RbTeWquZOuU0oaWcz78_8P5qv2_wRDt6t31O3_zmHKdf33XG0b-8j2HY5W0L6esgqpTh_6fWQNY2qIjVDZmnf2tyOV8KZNY5shVQ8t0UhWPmLlA60EPzv6GfoMMZpARxJHgtUrbdIJyybuhKoFElUSSSOJim13sgY3izz0QSC9w5TNPkTGA_GQWgRgGEeujj490C0AMwn4wIxDOevmE0kCUoZviyYefr8bF2f_QE)
Fun use of Python indexing and list multiplication.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes
```
IΣ×I⪪”‴⌈↷¶»^w⁷k²zV” E⁻NI⪪”←¶➙~!¬‴″ζCER⁵kςⅈ” ∧›ι⁰ι
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjeXBRRl5pVoOCcWl2gEl-ZqhGTmphZDuQU5mSUaSnpGChCkC6IMTJV0FJQUlDQ1dRR8Ews0fDPzSos1PPMKSkv8SnOTUos0gBLI2g2NTM0NFEwNjICkoQEIKACFDE2AlLG5ibEBzDigNse8FA33otTEEqApmToKBkChTE0wsF5SnJRcDHXz8mgl3bIcpdhlRmDjIIIA "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation:
```
N Input as a number
⁻ Vectorised subtract
... Compressed string `12570 50270 100000 125140 137430`
⪪ Split on spaces
I Cast to number
E Map over values
ι Current value
› Is greater than
⁰ Literal integer `0`
∧ Logical And
ι Current value
× Vectorised multiply by
... Compressed string `.2 .2 .2 -.2 .05`
⪪ Split on spaces
I Cast to number
Σ Take the sum
I Cast to string
Implicitly print
```
73 bytes for a version that calculates the personal allowance as an integer first:
```
Nθ≔⟦⁹⁹⁷³⁰¦³⁷⁷⁰⁰⌈⟦⁰⁻¹²⁵⁷⁰÷⌈⟦⁰⁻θXχ⁵⟧²⟧⟧η≔⁰ζF³«≔⌊⟦θ⊟η⟧ε≧⁺×∕ι⁵εζ≧⁻εθ»I⁺ζ×θ·⁴⁵
```
[Try it online!](https://tio.run/##ZY8xC8IwEIVn@ysyXiBKbZUiTqKLg1LETRyiVnvQprVpVBR/e7y0iqBZLpd7972XfSqrfSEza@eqNPXS5LukgjMfexOt8aRgMxpFoS9YGEU@lYW8YW5y2Lg7KqOhHwwjauaqnuEFDwn8S86CxcWVuH16GnK@5YIFrmwFS79WNLxTdywqBiFnD6/zHhClJTagEtKGkJC2s5BlK1rhKa0hzowWbI15ouEdB52lU7f0340mIY0Fc59@enGFqoap1C0M7h8cefu9AaXnfGxt4Ltju5dMvgA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Haskell](https://www.haskell.org), ~~132~~ 129 bytes
*-3 bytes thanks to [@The Thonnu](https://codegolf.stackexchange.com/users/114446/the-thonnu)*
```
r#(-1.0)=r;r#l=min r l
g(t,r)(l,p)=(t+r#l*p/20,r-r#l)
f x=fst$foldl g(0,x)$zip[max(12570-max(x-1e5)0/2)0,37700,99730,-1][0,4,8,9]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TdA7TsQwEAbg3qcYaVPYMGbtPLAj8A3oKKMUEZvsRjibyPGKCNFwDpptEBfgMtyGPMiKqX59I9m_5uPrUPTPpbXn8-fJV1z_vLsN5fJGMOPu3Maapj6CA0v21KNj1GLHDPXX4-qq24YCHR8jIxUMpup9ULV2Z2FPBQ4seK27rCkGKsNECT6lgcsyYWIbMoGRUkJgmqpIIJd5JjBGjWn-V-Tbl71_KvqyBwMZgXGWh3CKguFCiRhnJhXr21X1RWUaR-HKMlw9-s-zzqySRGuWE-KmTyuo4Q1ojS2Dew6XQjlpivEsBrqTf_Tu4QgB9If2BdzSfT3mLw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~32~~ 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
5ÐD(20)zI•5HwŸJ}Üt敞FвT*-Dd**O
```
Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/256013/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f/f9PAEFw0jA80qz0cNi0w9yo/u8Ko9PKfk8DIg9@g@twubQrR0XVK0tPz//zc0MgACAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/X/TwxNcNIwMNKsqHzUsMvUoP7rDq/bwnJLDy4Dco/vcLmwK0dJ1SdHS8v@v8z/a0MjU3EDH1AAIdCzApKERmAKTBrEA).
**Explanation:**
```
5 # Push a 5
ÐD # Triplicate + Duplicate so there are four 5s on the stack
( # Negate the top one
20 # Push 20
) # Wrap all five values on the stack into a list: [5,5,5,-5,20]
z # Get 1/value for each of them: [0.2,0.2,0.2,-0.2,0.05]
I # Push the input
•5HwŸJ}Ütæ• # Push compressed integer 90598507370046338479
žFв # Convert 90598507370046338479 to base-16384 as list:
# [1257,5027,10000,12514,13743]
T* # Multiply each by 10: [12570,50270,100000,125140,137430]
I - # Subtract each from the input
D # Duplicate this list
d # Pop and do a non-negative (>=0) check for each
* # Multiply the values at the same positions (negative values have become 0)
* # Multiply the values at the same positions with list [0.2,0.2,0.2,-0.2,0.05]
O # Sum everything together
# (which is output implicitly as result)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•5HwŸJ}Ütæ•` is `90598507370046338479` and `•5HwŸJ}Üt敞Fв` is `[1257,5027,10000,12514,13743]`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/), ~~58 48~~ 33 bytes
```
5D:N20WĖ⁰»+gḊ6ß/ċi∴o@t»k4τ-:0≥**∑
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI1RDpOMjBXxJbigbDCuytn4biKNsOfL8SLaeKItG9AdMK7azTPhC06MOKJpSoq4oiRIiwiIiwiMTIwMDAwIl0=)
* -15 thanks to lyxal
Port of Neil's Charcoal answer
### Explanation
```
5D: # Push 5 and quadruplicate
N # Negate the top one
20 # Push 20
W # Wrap the stack in a list
Ė # Reciprocal of each
⁰ # Push the input
»...» # Push the base-255 compressed integer 12570050270100000125140137430
k4τ # Convert to list: [12570,50270,100000,125140,137430]
- # Subtract each from the input
: # Duplicate this list
0≥ # Check if each element is ≥0
* # Multiply with the list so negative values are now 0
* # Multiply together
∑ # And sum, outputting implicitly
```
[Answer]
# QB64, 183 bytes
```
p=12570:If i>100000Then
p=p-Int((i-100000)/2):If p<0Then p=0
endif
l=p+37700:m=l+99730:If i>m Then
t=.45*(i-m):i=m
endif
If i>l Then
t=t+.4*(i-l):i=l
endif
If i>p Then t=t+.2*(i-p)
?t
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~120~~ ~~107~~ 102 bytes
* -18 thanks to ceilingcat
```
#define F+fdim(i
f(i){i=fmin(37700,i=F,F-i+12570,F,1e5)/2)))/5+.4*fmin(99730,i=F,37700))F,99730)*.45;}
```
[Try it online!](https://tio.run/##JYzRisIwEEXf@xWDImSaqabV0JUSH/MT7j5I08gUWxd38aXUTzfGOA934HDPbYtz24awdJ3nsQMrveNBcOYF48TGDzyKbV0rRWws2YJlWelakaWy07ipEHGj5XqXp@Z@X28/zeQgWkoI8/VON3Pg8R@GUyzer@wQpgzgjfj4Y6bPrlbx6CtlWaWXUlFRzgR532RR8teb6A038IgAeikxQoDfW1zzYrFyYA6wct/j4q0QeJH3iE02h2frL6fzXyguwws "C (gcc) – Try It Online")
] |
[Question]
[
Given two positive integers **A** and **B**, return the position **p** that *minimises* the number of prime factors (counting multiplicities) of the resulting integer, when **B** is *inserted* in **A** at **p**.
For example, given **A = 1234** and **B = 32**, these are the possible insertions (with **p** being 0-indexed) and the corresponding information about their prime factors:
```
p | Result | Prime factors | Ω(N) / Count
0 | 321234 | [2, 3, 37, 1447] | 4
1 | 132234 | [2, 3, 22039] | 3
2 | 123234 | [2, 3, 19, 23, 47] | 5
3 | 123324 | [2, 2, 3, 43, 239] | 5
4 | 123432 | [2, 2, 2, 3, 37, 139] | 6
```
You can see that the result has a minimal number of prime factors, 3, when **p** is 1. So in this particular case, you should output **1**.
### Specs
* If there are multiple positions **p** that minimise the result, you can choose to output all of them or any one of them.
* You may choose 0-indexing or 1-indexing for **p**, but this choice must be consistent.
* **A** and **B** can be taken as integers, strings or lists of digits.
* You can compete in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487) and can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is code-golf, so the shortest submission (scored in bytes) wins!
### Test cases
```
A, B -> p (0-indexed) / p (1-indexed)
1234, 32 -> 1 / 2
3456, 3 -> 4 / 5
378, 1824 -> 0 / 1
1824, 378 -> 4 / 5
67, 267 -> Any or all among: [1, 2] / [2, 3]
435, 1 -> Any or all among: [1, 2, 3] / [2, 3, 4]
378100, 1878980901 -> Any or all among: [5, 6] / [6, 7]
```
For convenience, here is a list of tuples representing each pair of inputs:
```
[(1234, 32), (3456, 3), (378, 1824), (1824, 378), (67, 267), (435, 1), (378100, 1878980901)]
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
§◄öLpr§·++⁰↑↓oΘŀ
```
Expects input as strings, [try it online!](https://tio.run/##ATIAzf9odXNr///Cp@KXhMO2THBywqfCtysr4oGw4oaR4oaTb86YxYD///8iMzIi/yIxMjM0Ig "Husk – Try It Online")
### Explanation
```
§◄(öLpr§·++⁰↑↓)(Θŀ) -- input A implicit, B as ⁰ (example "1234" and "32")
§ ( )( ) -- apply A to the two functions and ..
(ö ) -- | "suppose we have an argument N" (eg. 2)
( § ) -- | fork A and ..
( ↑ ) -- | take N: "12"
( ↓) -- | drop N: "34"
( ·++⁰ ) -- | .. join the result by B: "123234"
( r ) -- | read: 123234
( p ) -- | prime factors: [2,3,19,23,47]
( L ) -- | length: 5
(öLpr§·++⁰↑↓) -- : function taking N and returning number of factors
in the constructed number
( ŀ) -- | range [1..length A]
(Θ ) -- | prepend 0
(Θŀ) -- : [0,1,2,3,4]
◄ -- .. using the generated function find the min over range
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 25 bytes
```
sh"2GX@q:&)1GwhhUYfn]v&X<
```
Inputs are strings in reverse order. Output is 1-based. If there is a tie the lowest position is output.
[Try it online!](https://tio.run/##y00syfn/vzhDycg9wqHQSk3T0L08IyM0Mi0vtkwtwub/f3VjI3UudUMjYxN1AA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8L84Q8nAPcKh0EpN0zDevTwjIzQyLS@2TC3C5r9LyH91YyN1LnVDI2MTIGUMwiamZiARCyOwiLkFnIQKGZmZA0kwYQjEJsamYDlzC0sLA0sDQ4hyQwMDdQA).
### Explanation
```
s % Implicitly input B as a string. Sum (of code points). Gives a number
h % Implicitly input A as a string. Concatenate. Gives a string of length
% N+1, where N is the length of A
" % For each (that is, do N+1 times)
2G % Push second input
X@ % Push 1-based iteration index
q % Subtract 1
: % Range from 1 to that. Gives [] in the first iteration, [1] in
% the second, ..., [1 2 ... N] in the last
&) % Two-output indexing. Gives a substring with the selected elements,
% and then a substring with the remaining elements
1G % Push first input
whh % Swap and concatenate twice. This builds the string with B inserted
% in A at position given by the iteration index minus 1
U % Convert to string
Yf % Prime factors
n % Number of elements
] % End
v % Concatenate stack vertically
&X< % 1-based index of minimum. Implicitly display
```
[Answer]
# Pyth, ~~20~~ ~~13~~ 11 bytes
```
.mlPsXbQzhl
```
[Try it online](http://pyth.herokuapp.com/?code=.mlPsXbQzhl&input=%22378100%22%0A1878980901%0A&debug=0)
### Explanation
```
.mlPsXbQzhl
.m b Find the minimum value...
hl ... over the indices [0, ..., len(first input)]...
lP ... of the number of prime factors...
sX Qz ... of the second input inserted into the first.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
D©L‘Ṭœṗ¥€®żF¥€VÆfL€NM
```
[Try it online!](https://tio.run/##y0rNyan8/9/l0EqfRw0zHu5cc3Tyw53TDy191LTm0Lqje9zArLDDbWk@QNrP9//h5UcnPdw54/9/Y3MLQwOD/4YW5haWFgaWBoYA "Jelly – Try It Online")
-1 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).
Returns all possible positions.
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~22~~ 21 bytes
This felt far too long as I was writing it up but, looking at some of the other solutions, it actually seems somewhat competitive. Still, there's probably a bit of room for improvement - The `cNq)` in particular is annoying me. Explanation to follow.
Takes the first input as a string and the second as either an integer or a string. Result is 0-indexed and will return the first index if there are multiple solutions.
```
ÊÆiYVÃcNq)®°k Ê
b@e¨X
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=ysZpWVbDY05xKa6wayDKCmJAZahY&input=IjM3ODEwMCIsMTg3ODk4MDkwMQ==)
---
## Explanation
```
:Implicit input of string U and integer V.
Ê :Get the length of U.
Æ :Generate an array of the range [0,length) and map over each element returning ...
iYV : U with V inserted at index Y.
à :End mapping
c :Append ...
Nq : The array of inputs joined to a string.
® :Map over the array.
° :Postfix increment - casts the current element to an integer.
k :Get the prime divisors.
Ê :Get the length.
\n :The newline allows the array above to be assigned to variable U.
b :Get the first index in U that returns true ...
@ : when passed through a function that ...
e : checks that every element in U...
¨ : is greater than or equal to...
X : the current element.
: Implicit output of resulting integer.
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 228 bytes
```
param($a,$b)function f($a){for($i=2;$a-gt1){if(!($a%$i)){$i;$a/=$i}else{$i++}}}
$p=@{};,"$b$a"+(0..($x=$a.length-2)|%{-join($a[0..$_++]+$b+$a[$_..($x+1)])})+"$a$b"|%{$p[$i++]=(f $_).count};($p.GetEnumerator()|sort value)[0].Name
```
[Try it online!](https://tio.run/##HY7BboMwEETv/QqKNsIrByck7Qkh9VL11h9ACC2RnbgC2wLTViL@dtfNcWaeZsbZHzkvNzmOMTqaaWJAexhQrebitTWZSgZuys4MdHOqgcqrr3DTij2nZAcacQOd/EMDOshxkUlyHkJ4Ate8baHe5zAA5ZwdhWDw2wCJUZqrv5UnvO@28stqk6raFEPPecdh4ElC/8B5hR0G5DkQDHniwbX/A13DVAY9iotdjQ81Ayc@pH836yRn8ukv3hc7@@ybxlVie@zEJ00yxli8nF@LWFTFHw "PowerShell – Try It Online")
*(Seems long / golfing suggestions welcome. Also times out on TIO for the last test case, but the algorithm should work for that case without issue.)*
PowerShell doesn't have any prime factorization built-ins, so this borrows code from my answer on [Prime Factors Buddies](https://codegolf.stackexchange.com/a/94323/42963). That's the first line's `function` declaration.
We take input `$a,$b` and then set `$p` to be an empty hashtable. Next we take the string `$b$a`, turn it into a singleton array with the comma-operator `,`, and array-concatenate that with *stuff*. The *stuff* is a loop through `$a`, inserting `$b` at every point, finally array-concatenated with `$a$b`.
At this point, we have an array of `$b` inserted at every point in `$a`. We then send that array through a for loop `|%{...}`. Each iteration, we insert into our hashtable at position `$i++` the `.count` of how many prime factors `f` that particular element `$_` has.
Finally, we `sort` the hashtable based on `value`s, take the `0`th one thereof, and select its `Name` (i.e., the `$i` of the index). That's left on the pipeline and output is implicit.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
gƒ¹õ«N¹g‚£IýÒg})Wk
```
[Try it online!](https://tio.run/##AS0A0v8wNWFiMWX//2fGksK5w7XCq07CuWfigJrCo0nDvcOSZ30pV2v//zEyMzQKMzI "05AB1E – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27~~ 21 bytes
```
ηõ¸ì¹.sRõ¸«)øεIýÒg}Wk
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3PbDWw/tOLzm0E694iAQ89BqzcM7zm31PLz38KT02vDs//8NjYxNuIyNAA "05AB1E – Try It Online")
It returns the lowest 0-indexed *p*.
Thanks to @Emigna for -6 bytes !
### Explanation
```
ηõ¸ì # Push the prefixes of A with a leading empty string -- [, 1, 12, 123, 1234]
¹.sRõ¸«) # Push the suffixes of A with a tailing empty space. -- [1234, 123, 12, 1, ]
ø # Zip the prefixes and suffixes
ε } # Map each pair with...
IýÒg # Push B, join prefix - B - suffix, map with number of primes
Wk # Push the index of the minimum p
```
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~165~~ ... 154 bytes
```
import StdEnv,StdLib
@n h#d=hd[i\\i<-[2..h]|h rem i<1]
|d<h= @(n+1)(h/d)=n
?a b=snd(hd(sort[(@0(toInt(a%(0,i-1)+++b+++a%(i,size a))),i)\\i<-[0..size a]]))
```
[Try it online!](https://tio.run/##LY69asQwEIR7P8XiENDin9i@lBbnIikOrrvS50L2OtGCtQ5nJZBwzx5F4BTDMF8xM9MyGwlupc9lBmdYAruP9ebh4ulVvvJoZx6TTsA@kLbU8/XKbdE3ZWmHu4Xb7IDbekju1FoNnZKsRmWfCLUkRwOj3oSUJbXF0l51lfLrSbwyj6rKuagxy7IxKmbON/6ZwSBizrjPVGW5w2FADBdv4jMNR0jr5vCcQnpo0vA7vS3mfQvF6RxevsU4nvawfw8F/cM/ "Clean – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~165~~ 146 bytes
* Saved nineteen bytes thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer).
```
O=lambda n:n>1and-~O(n/min(d for d in range(2,n+1)if n%d<1))
def f(A,B):L=[int(A[:j]+B+A[j:])for j in range(len(A)+1)];print L.index(min(L,key=O))
```
[Try it online!](https://tio.run/##Zc7NbsIwDAfwO09hRZoUq2Fb0vChsm4q50p9gKqHTklGOjCo4jAue/UuKYMeODmKf/7bp8t5dyQ1DFW@bw@fpgXK6F22ZOa/FaeXgyduwB17MOAJ@pa@LFeCEoneAT2ZN4k4M9aB44XYYlbmtaczL@qsa5JtUtRd1mCc76b5vSVeYIhoNqc@aCifPRn7w@O2UnzbS14hDmOPSfjImdg4zqRKNQMQwFIVKs6uQN9BqhfLfxDKHbxOYLWOjQDkWmn2mDB@XxMivYHphuUqBkSg4vMR6HRxWzHeMPwB "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 120 bytes
Takes input as 2 strings. Returns a 0-indexed position.
```
f=(a,b,i=0,m=a)=>a[i>>1]?f(a,b,i+1,eval('for(n=a.slice(0,i)+b+a.slice(i),x=k=2;k<n;n%k?k++:n/=x++&&k);x')<m?(r=i,x):m):r
```
### Test cases
```
f=(a,b,i=0,m=a)=>a[i>>1]?f(a,b,i+1,eval('for(n=a.slice(0,i)+b+a.slice(i),x=k=2;k<n;n%k?k++:n/=x++&&k);x')<m?(r=i,x):m):r
console.log(f('1234','32')) // 1
console.log(f('3456','3')) // 4
console.log(f('378','1824')) // 0
console.log(f('1824','378')) // 4
console.log(f('67','267')) // 1
console.log(f('435','1')) // 1
```
[Answer]
# J, 60 Bytes
```
4 :'(i.<./)#@q:>".@(,(":y)&,)&.>/"1({.;}.)&(":x)"0 i.>:#":x'
```
Explicit dyad.
Takes B on the right, A on the left.
0-indexed output.
Might be possible to improve by not using boxes.
### Explanation:
```
4 :'(i.<./)#@q:>".@(,(":x)&,)&.>/"1({.;}.)&(":y)"0 i.>:#":y' | Whole program
4 :' ' | Define an explicit dyad
i.>:#":y | Integers from 0 to length of y
"0 | To each element
({.;}.)&(":y) | Split y at the given index (result is boxed)
(,(":x)&,)&.>/"1 | Put x inbetween, as a string
".@ | Evaluate
> | Unbox, makes list
#@q: | Number of prime factors of each
(i.>./) | Index of the minimum
```
[Answer]
# Python 3, 128 bytes
0-indexed; takes in strings as parameters. -6 bytes thanks to Jonathan Frech.
```
from sympy.ntheory import*
def f(n,m):a=[sum(factorint(int(n[:i]+m+n[i:])).values())for i in range(len(n)+1)];return a.index(min(a))
```
[Answer]
**Python, 122 bytes**
```
f=lambda n,i=2:n>1and(n%i and f(n,i+1)or 1+f(n/i,i))
g=lambda A,B:min(range(len(A)+1),key=lambda p:f(int(A[:p]+B+A[p:])))
```
In practice, this exceeds the default max recursion depth pretty quickly.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
;ṭJœṖ€$j€¥VÆfẈNM
```
[Try it online!](https://tio.run/##y0rNyan8/9/64c61XkcnP9w57VHTGpUsIHFoadjhtrSHuzr8fP@7HF5@aKnS0UkPd84AykT@/29oZGyio2BsYmoGJM0tdBQMLYyAAmbmOgomxqZgMUMDg//GRkAmTBKszgikxBAkZG5haWFgaWAIAA "Jelly – Try It Online")
Takes `A` as a list of digits and returns all 1-indices
## How it works
```
;ṭJœṖ€$j€¥VÆfẈNM - Main link. Takes A on the left and B on the right
; - Concatenate B to the end of A
¥ - Group the previous 2 links into a dyad f(A, B):
$ - Group the previous 2 links into a monad g(A):
J - Indices of A; [1, 2, ..., len(A)]
€ - Over each index:
œṖ - Partition A at that index
€ - Over each partition:
j - Join with B
ṭ - Append the concatenated number to the end of this list
V - Evaluate each as a number
Æf - Calculate the prime factors of each
ẈN - Get the lengths of each and negate
M - Indices of maximal elements, which gives the minimal indices when negated
```
] |
[Question]
[
Curve stitching is the process of "stitching" together multiple straight lines in order to create a curve, like so:

For an explanation of curve stitching, visit [this website](http://nrich.maths.org/5366/index).
We will be drawing our curve in the top left of the screen, as shown in the image above.
Given an integer `n` (via STDIN or a function parameter), being the number of lines to draw, and an integer `p` pixels, being the interval between the starting points, draw a straight line curve.
Horizontal/vertical lines are necessary, and should be part of the line count.
---
### Example Outputs:
n = 25, p = 15

n = 20, p = 20

---
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so **shortest code wins**.
[Answer]
# Python - 74
Since the question doesn't specify units, axes scaling etc. I'm coming up with the following minimum solution:
```
import pylab
n,p=input()
for i in range(n):pylab.plot([0,i*p],[(i-n)*p,0])
```

[Answer]
## Mathematica, ~~55~~ ~~51~~ ~~50~~ ~~47~~ ~~64~~ 68 bytes
```
f=Graphics[Line@Table[#2{{i-1,#+1},{0,i+1}},{i,#}],ImageSize->#*#2]&
```
Defines a function which yields the image as specified when called like
```
f[25,15]
```
Yielding

**Edit**: Had to add some characters to make sure that the second parameter was actually interpreted as pixels.
**Edit**: four more bytes to plot the horizontal lines.
[Answer]
# Bash+Imagemagick+xview, 124 bytes
```
for((;i<$1;));{
s+=" -draw 'line $[i*$2],0 0,$[($1-i++)*$2]'"
}
eval convert -size $[$1*$2]x$[$1*$2] xc:$s png:-|xview stdin
```
### Output for `./curvestitch.sh 25 15`:

[Answer]
## Basic 7.0, Commodore 128, ~~60~~ 58 bytes
```
0inputn,p:gR1:s=n*p:do:dR1,s,0to0,n:s=s-p:n=n+p:loOwHs>=0
```
Watch a video of it running:
[](https://i.stack.imgur.com/8Do7S.gif)
Unfortunately, INPUT command hasn't an abbreviation :(
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 26 bytes
```
{P5.G.ln↓⍉↑⍵×⍺∘-@3⍳¨⍺1 1⍺}
```
-2 bytes from Adam using *magic*
Requires `⎕IO←0`. (0-indexing)
## Explanation
```
{P5.G.ln↓⍉↑⍵×⍺∘-@3⍳¨⍺1 1⍺}
P5.G.ln Create lines using the following sets of four points:
⍺1 1⍺ Array [n,1,1,n]
⍳¨ generate range 0..n for each
[0..n,0,0,0..n]
@3 to the third element,
⍺∘- subtract it from n.(reversing the last range)
[0..n,0,0,n..0]
⍵× scale all items by p
↑ mix , creating columns of coordinates.
↓⍉ transpose, and convert to lists of two points
```
## [APL (dzaima/APL)](https://github.com/dzaima/APL), 28 bytes
```
{P5.G.ln↓⍉↑(⍵×⍳⍺)⍬⍬(⍵×⍺-⍳⍺)}
```
Anonymous function which takes n and p as left and right arguments, and displays the pattern, given an adequately sized canvas.
Full Program [here.](https://dzaima.github.io/paste/#0y3vUNsGMqwBImhtxBZjqFWdWpQI5Ro96t@Qdnl7AxZUG5FUXAYlHvVsfdbdUA9W46@XkaRQdng4U0VQwAEIIZ5cuSKD20IpHvZuBvFqFR71zFULz0vNz0lJTFNJK85JLMvPzuLjSQSZCjXnUNvlRb@ejtokaQL0gQ0A6NR/1rgEimBDIXLAwxEQM80CuTi0pBfmhmksBCECq8hTSFArAvDyFdCCrFgA#dAPL18)
Made with a lot of advice and golfing from dzaima.
### Test Cases
`25, 15`
[](https://i.stack.imgur.com/6PeBn.png)
`20, 20`
[](https://i.stack.imgur.com/4DBkB.png)
`6,72`
[](https://i.stack.imgur.com/urdZU.png)
## [Java + `Processing`](http://openjdk.java.net/), 62 bytes
The original function I made for this question.
```
void c(int n,int p){for(int i=1;i<n;)line(p*i,0,0,p*(n-i++));}
```
[Answer]
# Perl, ~~121~~ 130 bytes
The input is via `STDIN`. The values are comma separated.
**EDIT:** We have new rules. I'm not sure why, but the first two pixels are invisible and I had to add an offset...
```
use Tk;<>=~/,/;$c=tkinit->Canvas(-width=>$w=$`*$'-$',-height=>$w)->pack;$c->createLine(2,2+$_*$',2+$w-$_*$',2)for 0..~-$`;MainLoop
```
Here are some tests:
**25x15:**

**6x72:**

[Answer]
# BBC Basic, 58 ascii characters, tokenised filesize 49
```
INPUTn,p:p*=2FORi=1TOn:MOVEi*p-p,974DRAW0,974-(n-i)*p:NEXT
```
Download emulator at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html>
`p*=2` is needed because in the default mode BBC Basic maps a logical square of 2x2 to a single physical pixel.
BBC Basic has the origin at the bottom left corner of the screen, with y coorinates going up. On my machine the default window has an upper y coordinate of 974 (yours may be different.) 7 characters could be saved if it was permitted to plot in the bottom left corner of the screen. Adding `MODE16` after the first `:` will resize the window so that the upper y coordinate is guaranteed to be 799.

[Answer]
# Java 8, 143 bytes
```
import java.awt.*;n->p->new Frame(){{add(new Panel(){public void paint(Graphics g){for(int m=0;m<n;)g.drawLine(0,m*p,n*p-++m*p,0);}});show();}}
```
**Output for \$n=25, p=15\$:**
[](https://i.stack.imgur.com/VW0Rl.png)
**Output for \$n=5, p=50\$:**
[](https://i.stack.imgur.com/gZLnM.png)
**Explanation:**
```
import java.awt.*; // Required import for almost everything
n->p-> // Method with two integer parameters & Frame return-type
new Frame(){ // Create the Frame
{ // In an inner code-block:
add(new Panel(){ // Add a Panel we can draw on:
public void paint(Graphics g){
// Overwrite its paint method:
for(int m=0;m<n;) // Loop `m` in the range [0,n):
g.drawLine( // Draw a line:
0,m*p, // Starting at x=0, y=m*p
n*p-++m*p,0);}});// to x=n*p-(m+1)*p, y=0
show();}}; // And afterwards show the Frame
```
[Answer]
# Html + JavaScript 155 ~~157 183~~
Edit: learnig what stuff I can cut without functionality loss
Edit 2: as suggested by @Optimizer
```
<canvas id='c'/><script>
p=prompt,s=p(l=p(t=c.getContext("2d")));for(c.width=c.height=y=s*l,x=0;l--;x-=s)t.moveTo(0,y-=s),t.lineTo(-x,0);t.stroke()
</script>
```
[Fiddle](http://jsfiddle.net/6ke43m7c/7/embedded/result/) First input *number of lines*, second input *pixel interval*
[Ungolfed Fiddle](http://jsfiddle.net/6ke43m7c/1/)
[Answer]
# [R](https://www.r-project.org/), 100 bytes
```
function(n,p,P=p*n*1.08){bmp(,P,P)
par(mar=!1:4)
plot.new()
segments((1:n-1)/n,1,0,1:n/n)
dev.off()}
```
Saves output to bitmap file 'Rplot001.bmp'.
There are some 'wasted' pixels at the top & on the left (so the curve is in the top left corner but not touching the edge).
This seems to be within the spec, but could be removed for +13 bytes.
Commented code:
```
curve_stitch=
function(n,p, # n = number of lines, p = pixels between starting points
P=p*n*1.08){ # P = pixel dimensions of final plot.
# (R expands axes by 4% at each end by default, so to
# ensure that the curve itself is p*n pixels, we need
# to expand the output by +8%
bmp(,P,P) # open bitmap output to default filename, with dimensions PxP
par(mar=!1:4) # remove margins by setting all to zero
plot.new() # define new plot (default data range from 0 to 1)
segments((1:n-1)/n,1,0,1:n/n) # plot lines within range from 0 to 1
dev.off() # close bitmap output to save file
}
```
Sample output:
```
curve_stitch(10,10)
```
[](https://i.stack.imgur.com/L1zbV.png)
```
curve_stitch(5,50)
```
[](https://i.stack.imgur.com/irNuZ.png)
] |
[Question]
[
# Objective
Write a full program that works exactly like the flow chart below.
Each output, which is an integer, shall be through `stdout`, followed by a line feed.
Each input shall be a line of string fed through `stdin`, and shall be judged to a predicate you choose for branching. The same predicate must be used for all branches.
The predicate must be able to judge every possible input, and must not be always truthy nor always falsy. Possible choices of the predicate include:
* Truthy if the inputted string is nonempty
* Truthy if the inputted string consists of whitespaces
* Truthy if the inputted string can be parsed into an integer
* Truthy if the inputted string is exactly `Hello, world!`
# The flow chart
[](https://i.stack.imgur.com/lzD5J.png)
# Rule
Your submission need not to follow the definition above exactly, as long as the visible side-effects are the same. This rule is present to aid functional languages.
# Ungolfed solution
## Haskell
Truthy if the string is empty.
```
main :: IO ()
main = procedure1 where
genProcedure :: Int -> IO () -> IO () -> IO ()
genProcedure output branch1 branch2 = do
print output
str <- getLine
if null str
then branch1
else branch2
procedure1, procedure2, procedure3 :: IO ()
procedure1 = genProcedure 1 procedure3 procedure2
procedure2 = genProcedure 2 procedure1 procedure3
procedure3 = genProcedure 3 procedure2 (pure ())
```
[Answer]
# [QBasic](https://en.wikipedia.org/wiki/QBasic), 58 bytes
```
1?x+1
LINE INPUT s$
x=x+1+(s$>"")*(2+(x=0)*3)
IF x<3GOTO 1
```
Empty inputs are falsey; nonempty inputs are truthy. You can type the program in and run it at [Archive.org](https://archive.org/details/msdos_qbasic_megapack).
Sadly, storing the program state in a variable `x` is much cheaper than doing actual control flow with gotos. A direct translation of the flowchart comes in at 95 bytes:
```
1?1
LINE INPUT s$
IF""<s$GOTO 3
2?2
LINE INPUT s$
IF""<s$GOTO 1
3?3
LINE INPUT s$
IF""<s$GOTO 2
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 52 bytes
Strictly speaking, this is not a valid solution, because it can't handle some special inputs like `quit`. But this is the best I can do.
```
my(n=0);while(n<3,print(n++);iferr(input,e,n=n++%3))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN01yKzXybA00rcszMnNSNfJsjHUKijLzSjTytLU1rTPTUouKNDLzCkpLdFJ18myBgqrGmpoQvVAjFmzXitfiguH8-HwYhkgDAA)
Valid PARI/GP expressions (e.g. `o_o`) are falsy. Other strings (e.g. `*_*`) are truthy.
PARI/GP doesn't have a way to read an arbitrary string from stdin. The function `input` always parses the input as a PARI/GP expression. So I use `iferr` to check if the input is valid.
I also need to declare `n` as a local variable, otherwise the user may input a string like `n=9` and change the value of `n`.
However, there's no way to stop the user from inputting something like `quit`, which will quit the program; or `input`, which prompts for another input; or `print("something")`, which prints something. It's just impossible to handle these cases.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 13 bytes
```
‘Ṅ+%3ßḊo?ɗɠẸ¤
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw4yHO1u0VY0Pz3@4oyvf/uT0kwse7tpxaMn//8X5uaklGZl56VyJeZUQRl4@hAYCAA "Jelly – Try It Online")
A full program that takes no arguments but reads from STDIN. The predicate function checks for a non-empty line. As required, the intermediate outputs are sent to STDOUT.
## Explanation
```
‘ | Increment by 1
Ṅ | Output to STDOUT with a trailing newline
ɗɠẸ¤ | Following as a dyad with the right argument (y) as 1 if the next line from STDIN is non-empty and 0 if empty, and the link’s argument + 1 as the left argument
+ | x + y
%3 | Mod 3
ßḊṪ? | If this or the input is truthy, call the link recursively; if falsy, remove the remaining value so we’re left with an empty list
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
≔³θWθ«I⁻⁴θD⎚≔⎇S⊕﹪θ³⊖θθ
```
[Try it online!](https://tio.run/##RY7NCsIwEITPzVPkuIF6kHrzJO2lh0JBXyCkSxtIt82fIuKzx0QEmcsw3zCMWqRTmzQpXbzXM0FTcyvO7LFogxys4C9WjU5TgFb6AIOm6OFUSiLXqi6uOxTTGpTu635DN3Qk3RN62mO4hjwxg6h5T8rhihRwgmGbotnA1rwRGXX4R7YE5cg7pSMrYiwd7uYD "Charcoal – Try It Online") Link is to verbose version of code. Uses nonempty as the predicate. Explanation:
```
≔³θ
```
Numbering the states in reverse to output values, we start in state `3`.
```
Wθ«
```
Repeat until state `0` (END) is reached.
```
I⁻⁴θD⎚
```
Generate the correct output value.
```
≔⎇S⊕﹪θ³⊖θθ
```
If the input is not empty, then go the the previous state (increment the internal value, but `3` becomes `1`), otherwise go to the next state (decrement the internal value).
[Answer]
# Javascript, 38 bytes
```
f=(n=1)=>(n+=!prompt(n)*4)-3&&f(n%3+1)
```
Empty string as true
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 19 bytes
```
1{:|Ọ"ᵈḄᵇ“f2Ẇ0pi?ȯi
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCIxezp84buMXCLhtYjhuIThtYfigJxmMuG6hjBwaT/Ir2kiLCIiLCIwXG4xXG4wXG4wXG4wIiwiMy40LjAiXQ==)
A single number is all you need
Truthy is defined as standard vyxal truth
## Explained
```
1{:|Ọ"ᵈḄᵇ“f2Ẇ0pi?ȯi­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌­
1 # ‎⁡Start with 1 on the stack. This is the initial state
{:| # ‎⁢While the top of the stack is truthy:
Ọ # ‎⁣ Print it without popping. This prints the current state
"ᵈḄᵇ“ # ‎⁤ Push the number 233101 to the stack
f2Ẇ # ‎⁢⁡Flatten it and divide it into chunks of size 2. This is the state map. The first number in a pair is the state to go to when false input. The second number is the true jump.
0p # ‎⁢⁢ Prepend a 0 to indicate a halt state
i # ‎⁢⁣ Retrieve the pair corresponding to the current state
?ȯi # ‎⁢⁤ And get the next state based on the truthiness of the input
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 111 bytes
```
++++++++++>>-[<+>-----]<-->---[<.<.>>>>>,----------[<[-]+>,----------]<[<[--<--<-->>>-]>[<+<+<+>>>->]<]<+<+<+>]
```
[Try it online!](https://tio.run/##TYxBCoBADAPvfmXNviD0IyWHVRBE8CD4/roVWZzk0ITQ5Wr7ud3rEVEGZnAWQyICeTkrqyUzBk6Hyr8RswNf9zFk/VUqg4n6kiLalOrEAw "brainfuck – Try It Online")
An empty string (followed by a line feed) is truthy, any other input is falsy.
[Answer]
# [Perl](https://www.perl.org), 123 bytes
```
I:print 1;$i=<STDIN>;chomp$i;goto K if$i;J:print 2;$i=<STDIN>;chomp$i;goto I if$i;K:print 3;$i=<STDIN>;chomp$i;goto J if$i;
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kILUoZ8GCpaUlaboWN6s9rQqKMvNKFAytVTJtbYJDXDz97KyTM_JzC1QyrdPzS_IVvBUy04BsL6hCI5wKPSEKvaEKjXEq9IIohDgB6pIFG0qKSksyKrkS0xMz87gMuLgg4gA)
The predicate here is Perl truth.
[Answer]
# Rust, 136 bytes
```
fn main(){let mut c=1;while 4>c{print!("{c}
");let y=&mut "".into();std::io::stdin().read_line(y);c+=if "
"!=y{if c==1{c=4}-1}else{1}}}
```
Expanded (I also replaced newlines inside string literals by regular `\n`):
```
fn main(){
let mut c=1;
while 4>c {
print!("{c}\n");
let y=&mut "".into();
std::io::stdin().read_line(y);
c+=if "\n"!=y {
if c==1 { c = 4 }
-1
} else {
1
}
}
}
```
```
[Answer]
# APL(NARS), 40 chars
```
P
⎕←1⋄→3×⍳''≡⍞
⎕←2⋄→1×⍳''≡⍞
⎕←3⋄→2×⍳''≡⍞
```
1+3\*12+3=40
Predicate would be here "True if the input line is empty"
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 108 bytes
```
p=print
i=input
def a():p(1);c()if i()else b()
def b():p(2);a()if i()else c()
def c():
p(3)
if i():b()
a()
```
[Try it online!](https://tio.run/##Vc0xDoAwCEDRnVMwwqhdTI2H0dpGElOJ1sHT11pdZPnDg6BXWrZoOt1z1kF3iQlkkKhngtkHHImtUsO9I5aAQuzXw@NEXHmq3HI//th9XGoBlQwDvmyfy7Kcc/3RQE37xkCZGw "Python 3.8 (pre-release) – Try It Online")
The predicate checking the input is truthy if the inputted string is nonempty.
[Answer]
# C (GNU Extension), 311 Bytes
```
#include <stdio.h>
#define G goto
int main(){int a,b,c,d,e,f,i;char*h="Hello, world!";void*j[3][2]={{&&x,&&y},{&&y,&&w},{&&z,&&x}};w:i=0;q:a=e=f=1;b=c=d=0;G L;o:if(c){puts(a+e+f?"1":"0");G*j[i][a||e||f];}a=a?b>47&&b<58:0;e=e?b==h[d-1]:0;f=f?b==32:0;L:b=getchar();d++;c=b==10;G o;z:return 0;y:i=2;G q;x:i=1;G q;}
```
This code (ab)uses the GNU extension [Labels as Values](https://gcc.gnu.org/onlinedocs/gcc-4.8.0/gcc/Labels-as-Values.html) and gotos.
Things seen as truthy:
* A sequence of digits (allows 0000000...)
* The exact string "Hello, world!"
* A sequence of space
* An empty string
---
## Explained
```
#include <stdio.h>
//to save space
#define G goto
int main() {
//a stores if the input is an integer
int a;
//b stores the char we currently act upon
int b;
//c stores if the end of the current input line has been reached
int c;
//d counts the number of chars in the current input, used when testing for hello world
int d;
//e stores if the input is the hello world
int e;
//f stores if the input consists of space
int f;
//i stores the current state, goes from 0 to 2
int i;
//this is used for comparisons to find out if the input is hello world
char *h = "Hello, world!";
//this is a jump table, it is used to emulate something like a switch using gotos
void *j[3][2] = {
{&&x, &&y}, //these are where one can go from state 0 using what result
{&&y, &&w}, //go from state 1
{&&z, &&x} //go from state 2
};
//the labels w x y z are the different states
//w is state 0, the beginning
//x is state 1
//y is state 2
//z is state 3, the end state
//this is state 0
w:
i = 0;
//this resets all the variables to their default values
q:
a = e = f = 1; //at the beginning of the line parsing, we assume all the things to be true as we later test if they are wrong
b = c = d = 0;
G L;
//this are two things combined: the output in case the end of the line has been reached & the check for all the different things we consider truthy
o:
if(c){
//this is the output, the shorthand if is true in case any of them are non zero
puts(a + e + f ? "1" : "0");
//this selects the next state to jump to, based on the current state i and the result, and does the goto
G *j[i][a || e || f];
}
//the way these assignments work is that we only test if the condition still is true if it still is true. In case it ever is false we do not try to test again
a = a ? b > 47 && b < 58 : 0; //this tests for digits, assumes ascii as digits are from 48 to 57
e = e ? b == h[d-1] : 0; //this tests for hello world, in case the input looks like hello world but goes on with the exact (random) data as stored in the compiled file this can cause a buffer overrun!
f = f ? b == 32 : 0; //this tests for space, assumes ascii where ' ' is 32
//this gets the next character in the line
L:
b = getchar();
d++;
c = b == 10; //this tests for end of line by looking for '\n' which, assuming ascii, is 10
G o;
//this is state 3, the end
z:
return 0;
//this is state 2
y:
i = 2;
G q;
//this is state 1
x:
i = 1;
G q;
}
```
] |
[Question]
[
A manufacturing company wants to print a design on mats of varying dimensions, and they hired you to program a robot to make these mats. The design consists of alternating rings of any 2 symbols on a mat. Below are some sample looks:
Column 9 by Row 7
Symbol 1: @
Symbol 2: -
Input: `9 7 @ -`
```
@@@@@@@@@
@-------@
@-@@@@@-@
@-@---@-@
@-@@@@@-@
@-------@
@@@@@@@@@
```
Column 13 by Row 5
Symbol 1: @
Symbol 2: -
Input: `13 5 @ -`
```
@@@@@@@@@@@@@
@-----------@
@-@@@@@@@@@-@
@-----------@
@@@@@@@@@@@@@
```
Column 3 by Row 5
Symbol 1: $
Symbol 2: +
Input: `3 5 $ +`
```
$$$
$+$
$+$
$+$
$$$
```
Column 1 by Row 1
Symbol 1: #
Symbol 2: )
```
#
```
Write a program that takes in the length, breadth, symbol 1 and symbol 2 and prints out the mat design on the screen.
\*The row and column number is always odd
Shortest code wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
Takes the `length,breadth` as the first argument and the symbols as a second argument.
```
«þ/U«ṚƊịY
```
[Try it online!](https://tio.run/##ASMA3P9qZWxsef//wqvDvi9VwqvhuZrGiuG7i1n///85LDf/IkAtIg "Jelly – Try It Online")
```
«þ/ -- Minimum table of the left argument
Ɗ -- On that table:
U«Ṛ -- Minimum of each row reversed and the columns reversed
ị -- Index into the symbols (modular indexing)
Y -- Join by newlines
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 86 bytes
```
f(a,b,c,d)=[print(concat(r~))|r<-matrix(a,b,i,j,[c,d][vecmin([i-1,j-1,a-i,b-j])%2+1])]
```
[Try it online!](https://tio.run/##bYzBCsIwEETv/YoQFbJ09xBFiqDgf4Qc0mhlC40hBPEg/npM1YsgzMzlzUx0iekSSxmUwx49nuBgYuKQlb8G77JKT4BH2tPkcuL7u8U4oqlVa25nP3FQhknjWO2IsafRwmrdagu23u5QdCjkUdYgCc3nHJpB6Q2K7X/0JcuZtL8jFFVyMROQUF4 "Pari/GP – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 85 bytes
```
function(a,b,s,t,m=matrix(t,b,a),r=row(m),c=col(m)){m[!pmin(b-r,a-c,r-1,c-1)%%2]=s;m}
```
[Try it online!](https://tio.run/##VcrBCgIhGATge09h1oI/jQeLiAih94gOriAI/eviGgXRs5tLXYJhGD4m12BruA@@xDQohx4TCtiyKzk@VWngCNnm9FBM8NanWxv04sty5DioXmc47ZG1gdeGum57tdOJ3zWoI8QBQp5lKy1pEZTZQez/6SfrWTbfE0SLXM1CkuoH "R – Try It Online")
Idea of `pmin` inspired by [@alephalpha's](https://codegolf.stackexchange.com/a/241224/55372) `vecmin`.
[Answer]
# [J](http://jsoftware.com/), 18 17 bytes
```
{~2|<./&(<.&i.-)/
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/q@uMamz09NU0bPTUMvV0NfX/a3L5OekpVNdpxNpZ1eiBZNVq9NUyrfRhEkY10VZA5TV6SoYONXqaIN2ZevpcXKnJGfkK6roO6gppCuYKplC@Ooq4sYIxVnEzBTOs4kYKFjjMsfgPAA "J – Try It Online")
*Note: Explanation needs slight update but idea is the same as current solution*
Consider `7 5`:
* `<./&i./` First uses `&i.` to generate both `0 1 2 3 4 5 6` and `0 1 2 3 4`, and the creates a "mininum" function table:
```
0 0 0 0 0
0 1 1 1 1
0 1 2 2 2
0 1 2 3 3
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
```
* `-` Note using `i.` on a negative number counts down, so `i. _3` is `2 1 0`.
* `-<.&(...)]` Is a fork which applies the verb from step to both `7 5` and `_7 _5`, and then takes the min. So min of:
```
0 0 0 0 0 4 3 2 1 0
0 1 1 1 1 4 3 2 1 0
0 1 2 2 2 min 4 3 2 1 0
0 1 2 3 3 3 3 2 1 0
0 1 2 3 4 2 2 2 1 0
0 1 2 3 4 1 1 1 1 0
0 1 2 3 4 0 0 0 0 0
```
which gives:
```
0 0 0 0 0
0 1 1 1 0
0 1 2 1 0
0 1 2 1 0
0 1 2 1 0
0 1 1 1 0
0 0 0 0 0
```
* `2|` Then we mod by 2:
```
0 0 0 0 0
0 1 1 1 0
0 1 0 1 0
0 1 0 1 0
0 1 0 1 0
0 1 1 1 0
0 0 0 0 0
```
* `{~` And map to chars:
```
-----
-@@@-
-@-@-
-@-@-
-@-@-
-@@@-
-----
```
[Answer]
# [ayr](https://github.com/ZippyMagician/ayr) `-0`, ~~17~~ 14 bytes
Since the 05Ab1e answer takes the input [row, column], I can get -3 bytes. Images and try it link outdated, just replace the code with this snippet.
```
~2||:v:\/@`v:~
```
[Try it!](https://zippymagician.github.io/ayr#Zjo@/fjJ8fDp2OlwvJnwuQGB2On4@/J0AtJyBmIDkgNw@@//MA@@)
# Explained
`-0` makes `~` and `|:` (descending range) 0-indexed
The program `A (~2||:v:\/@`v:~) B` is equivalent to `A ~ 2 | (v:\/ |: B) v: v:\/ ~ B`
### How to get there:
**Expansion of the train (lowercase = fn, uppercase = var):**
* `B (f A g h i j) C`
* `B (f (A g h i j)) C`
* `B (f (A g (h i j))) C`
* `B f (A g (h i j)) C`
* `B f (A g ((h i j) C))`
* `B f (A g ((h C) i (j C)))`
**Substituting in the symbols:**
`B ~ (2 | ((|: C) v:\/@`v: (~ C)))`
**Focusing on the fork (h i j):**
`v:\/@`v:` could be written as `f \ / @` g`
which is `g @ (f \ /)`
`A g @ f B` is `(f A) g f B`
so `(|: C) v:\/@`v: (~ C)` is `(v:\/ |: C) v: (v:\/ ~ C)`
*Therefore*
`A (~2||:v:\/@`v:~) B` is equivalent to
`A ~ 2 | (v:\/ |: B) v: v:\/ ~ B`
### Which leads to the explanation:
A is the string, B is the dims
* `|: ... ~` Take the descending and ascending 0-ranges of each element of B
[](https://i.stack.imgur.com/APhNS.png)
* `v:\/` Convert these each separately to a minimum matrix of shape B
[](https://i.stack.imgur.com/cIXma.png)
* `v:` Take the minimum of these two matrices on an element-wise basis
* `2|` Mod 2 each element
* `~` Use the matrix as indices into string A
[Answer]
# [Haskell](https://www.haskell.org/), 64 bytes
```
(x!y)q=[[cycle q!!minimum[k,1+x-k,j,1+y-j]|j<-[1..y]]|k<-[1..x]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/X6NCsVKz0DY6OrkyOSdVoVBRMTczLzO3NDc6W8dQu0I3WycLSFfqZsXWZNnoRhvq6VXGxtZkQ5gVsbH/cxMz82xT8rkUFHITC3wVCkpLgkuKfPJUTBUNDVWUdM2UgDIQQQWlmDwlDHXmioYWKkoRyg5K/wE "Haskell – Try It Online")
Also works with even sized mats and more than two character patterns.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
NθE⊘⊕N⭆⊘⊕θ§ζ⌊⟦ιλ⟧‖O⌈
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDN7FAwyMxpyw1RcMzL7koNTc1rwTMRijW1NTUUQguASpPx6G6EKTCscQzLyW1QqNKR8E3My8ztzRXIzpTRyEnVhMErLmCUtNyUpNL/MtSi3KAxlg96unQtP7/31LBXMFB979uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Takes the two symbols as a single argument. Explanation:
```
Nθ
```
Input the width.
```
E⊘⊕N⭆⊘⊕θ§ζ⌊⟦ιλ⟧
```
Input the height and loop over the top left quarter of the mat, outputting the symbols cyclically indexed by the minimum of the row and column.
```
‖O⌈
```
Reflect with overlap to complete the map.
Alternative approach, also 20 bytes:
```
NθE⮌…⁰N⭆⮌…⁰θ§ζ⌊⟦ικλμ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDN7FAIyi1LLWoOFUjKDEvPVXDQEcBWammpqaOQnAJUHE6VrWFIHnHEs@8lNQKjSodBd/MvMzc0lyN6EwdhWwdhRwdhdxYTRCw/v/fUsFcwUH3v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Takes the two symbols as a single argument. Explanation:
```
Nθ
```
Input the width.
```
E⮌…⁰N⭆⮌…⁰θ§ζ⌊⟦ικλμ
```
Input the height and loop over the mat, reversing the ranges of the row and column, outputting the symbols cyclically indexed by the minimum of the row and column and reversed row and column.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
>;L`â€ßZä€ûûè
```
First input is a pair of \$[row,column]\$, second input is a pair of \$[symbol2,symbol1]\$. Output is a matrix of characters.
[Try it online](https://tio.run/##yy9OTMpM/f/fzton4fCiR01rDs@POrwERO8GwhX/vQ7t/h9tqmNoHMul6wAA) (footer `J»` is to pretty-print; feel free to remove it to see the actual output-matrix).
**Explanation:**
```
>; # Increase both values in the first (implicit) input-pair by 1, then halve
# e.g. [5,13] → [6,14] → [3,7]
L # Map both to a list in the range [1,n]
# → [[1,2,3],[1,2,3,4,5,6,7]]
` # Pop and push both separated to the stack
# → [1,2,3] and [1,2,3,4,5,6,7]
â # Get the cartesian product of these two lists
# → [[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[2,1],[2,2],[2,3],[2,4],[2,5],
# [2,6],[2,7],[3,1],[3,2],[3,3],[3,4],[3,5],[3,6],[3,7]]
ۧ # Get the minimum of each inner pair
# → [1,1,1,1,1,1,1,1,2,2,2,2,2,2,1,2,3,3,3,3,3]
Z # Push the flattened maximum (without popping the list)
# → [1,1,1,1,1,1,1,1,2,2,2,2,2,2,1,2,3,3,3,3,3] and 3
ä # Split the list into that many equal-sized parts so we have a matrix
# → [[1,1,1,1,1,1,1],[1,2,2,2,2,2,2],[1,2,3,3,3,3,3]]
€û # Palindromize each row
# → [[1,1,1,1,1,1,1,1,1,1,1,1,1],
# [1,2,2,2,2,2,2,2,2,2,2,2,1],
# [1,2,3,3,3,3,3,3,3,3,3,2,1]]
û # Palindromize the entire matrix
# → [[1,1,1,1,1,1,1,1,1,1,1,1,1],
# [1,2,2,2,2,2,2,2,2,2,2,2,1],
# [1,2,3,3,3,3,3,3,3,3,3,2,1],
# [1,2,2,2,2,2,2,2,2,2,2,2,1],
# [1,1,1,1,1,1,1,1,1,1,1,1,1]]
è # 0-based modulair index each into the (implicit) second input-string
# e.g. "-@" →
# [["@","@","@","@","@","@","@","@","@","@","@","@","@"],
# ["@","-","-","-","-","-","-","-","-","-","-","-","@"],
# ["@","-","@","@","@","@","@","@","@","@","@","-","@"],
# ["@","-","-","-","-","-","-","-","-","-","-","-","@"],
# ["@","@","@","@","@","@","@","@","@","@","@","@","@"]]
# (after which the matrix is output implicitly)
```
[Answer]
# Python3, 240 bytes
```
b,a,c,d=input().split()
g=range
a,b=int(a),int(b)
r=[[d]*b for i in g(a)]
x=y=0
while 1:
for i in g(x,a-x):r[i][y]=r[i][b-1-y]=c
for j in g(y,b-y):r[x][j]=r[a-1-x][j]=c
x+=2;y+=2
if x>=a/2or y>=b/2:break
print('\n'.join(map(''.join,r)))
```
[Try it online!](https://tio.run/##Tc6xDoMgFAXQna9gaKJU0KrpYuVLKAOoVYxFQm0KX2@hLl3evck9wzN@m1Zd77vEAne4p0qb95ai/GUWFRKM1Ao9DkBgGbYtFQjHkAhYyljPzxI@VgsVVBqOYeXAUU8v4DOpZYCulUUVZt@KomrAP3VYEIcayxRnntNfSlKS0LsDzgf0WBIfoeNsjlAEdfQAXUarmw8HGBsfS@46yedV6fQpTJocHVuE0L7XsLzCE8y@)
[Answer]
# APL+WIN, 22 bytes
Prompts for column then row as integers and the symbols as string. Index origin = 0
```
⎕[2|n⌊⌽⍉⌽⍉n←(⍳⎕)∘.⌊⍳⎕]
```
[Try it online!Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz0NJBFtVJP3qKfrUc/eR72dEDIPqEDjUe9moKzmo44ZeiBpMC/2P1AX1/80Lksucy51B111LnUFda40LkNjLlNkPpirog2XBkJ1ZU11AA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 174 bytes
```
w,h,x,y=input().split()
n='\n'
f=lambda x,y,w,h:x*w+n+x+f(y,x,w-2,h-2).replace(n,x+n+x)+x+n+x*w if w*h-w-h+1else[n.join(x*(h-w+1)),x*(w-h+1)][w>h]
print(f(x,y,int(w),int(h)))
```
[Try it online!](https://tio.run/##HY3LDoIwEEX3fEV3dPogARdGE4z/gSxQS1pThwYwU76@Flbn5j5yw7baCU8pkbIqqq11GH4rh2oJ3mUW2JYPLIux9cP3@R5Y7qjcvUZBEmWUI9/yjnSjrG6gmk3ww8twVHGPQR4QxNzISFhN2sra@MV0WH0mhzwKnl1ZA6gsjxj6jm62L8LscOUj3y93RXDAAkBKF3Zmd6b/ "Python 3 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal/wiki), ~~36~~ 28 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page)
```
NθNηW∧›θ⁰›η⁰«Bθη§ζⅈ↘≧⁻²θ≧⁻²η
```
-10 bytes thanks to *@Neil* and +2 bytes for a bug-fix.
[Try it online (verbose)](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ0xqZm6FpzRWekZmTquGYl6LhXpSaWAJSpGOgqQPjZAA5mtVcCgpO@RVAmQwdxxLPvJTUCo0qnQgNTU2gAQoKvvllqRpWLvnleUGZ6RklELHEAsfi4sx0iJCGb2ZeabGOkQ7QAThkQG6p/f/fksucy0H3v25ZDgA) or [try it online (pure)](https://tio.run/##S85ILErOT8z5///9nnXndoCI7e/3bH/UsfxRw65zOx41bgDR24H0odXv9yw6t@Pc9kPLz2171NrxqG3Go87ljxp3H9oEVAdjbf//35LLnMtBFwA).
**Explanation:**
Get the first two inputs as integers:
```
InputNumber(q);InputNumber(h);
NθNη
```
Continue looping while both `q` and `h` are still larger than 0:
```
While(And(Greater(q,0),Greater(h,0)){ ... }
W∧›θ⁰›η⁰« ...
```
Print a box with dimensions `q` by `h`, with the `X`'th character of the third input-string `z` as border, where `X` is the current x-position of the cursor:
```
Box(q,h,AtIndex(z,X()));
Bθη§ζⅈ
```
Move the cursor once towards the bottom-right:
```
Move(:DownRight);
↘
```
Decrement both `q` and `h` by 2:
```
MapAssignRight(Minus,2,q);MapAssignRight(Minus,2,h);
≧⁻²θ≧⁻²η
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes
```
›½ɾΠvg:G$ṅ/vf⌊v∞∞İ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigLrCvcm+zqB2ZzpHJOG5hS92ZuKMinbiiJ7iiJ7EsCIsInbhuYXigYsiLCJbNSwxM11cbi1AIl0=)
## How?
```
›½ɾΠvg:G$ṅ/vf⌊v∞∞İ
› # Increment both of the (implicit) first input
½ # Halve both
ɾ # Generate a [1, n] range for both
Π # Cartesian product of the two
vg # Minimum of each
:G # Duplicate and get the maximum
$ # Swap
ṅ # Join by nothing
/ # Split this into that many equal parts
vf # Convert each back to a list
⌊ # Convert each to an integer
v∞ # Palindromise each
∞ # Palindromise the list
İ # Index these into the (implicit) second input
```
] |
[Question]
[
S. Ryley proved following theorem in 1825:
>
> Every rational number can be expressed as a sum of three rational cubes.
>
>
>
### Challenge
Given some rational number \$r \in \mathbb Q \$ find three rational numbers \$a,b,c \in \mathbb Q\$ such that $$r= a^3+b^3+c^3.$$
### Details
Your submission should be able to compute a solution for every input given enough time and memory, that means having for instance two 32-bit `int` representing a fraction is not sufficient.
### Examples
$$ \begin{align}
30 &= 3982933876681^3 - 636600549515^3 - 3977505554546^3 \\
52 &= 60702901317^3 + 23961292454^3 - 61922712865^3 \\
\frac{307}{1728} &= \left(\frac12\right)^3 + \left(\frac13\right)^3 + \left(\frac14\right)^3 \\
0 &= 0^3 + 0^3 + 0^3 \\
1 &= \left(\frac12\right)^3 + \left(\frac23\right)^3 + \left(\frac56\right)^3\\
42 &= \left(\frac{1810423}{509232}\right)^3 + \left(\frac{-14952}{10609}\right)^3 + \left(\frac{-2545}{4944}\right)^3
\end{align}$$
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 35 bytes
```
r->[x=r+1/3,-x+r/3/d=x^2-r,1/9/d-1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN5WLdO2iK2yLtA31jXV0K7SL9I31U2wr4ox0i3QM9S31U3QNY6FK7RILCnIqNYoUdO0UCooy80qATCUQR0khTaNIU1NHIdrYQEfB1EhHwdjAXN_Q3MhCRwEoYKijYGIUqwkxZcECCA0A)
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 40 bytes
```
r->[x=27*r^3+1,9*r-x,z=9*r-27*r^2]/(3-z)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWNzWKdO2iK2yNzLWK4oy1DXUstYp0K3SqbEE0WNAoVl_DWLdKE6reLrGgIKdSo0hB106hoCgzrwTIVAJxlBTSNIo0NXUUoo0NdBRMjXQUjA3M9Q3NjSx0FIAChjoKJkaxUFMWLIDQAA)
---
This formula is given in:
[Richmond, H. (1930). On Rational Solutions of \$x^3+y^3+z^3=R\$. *Proceedings of the Edinburgh Mathematical Society, 2*(2), 92-100.](https://doi.org/10.1017/S0013091500007604)
$$r=\left(\frac{27r^3+1}{27r^2-9r+3}\right)^3+\left(\frac{-27r^3+9r-1}{27r^2-9r+3}\right)^3+\left(\frac{-27r^2+9r}{27r^2-9r+3}\right)^3$$
[Check it online!](http://www.wolframalpha.com/input/?i=r%3D%3D((27r%5E3%2B1)%2F(27r%5E2-9r%2B3))%5E3%2B((-27r%5E3%2B9r-1)%2F(27r%5E2-9r%2B3))%5E3%2B((-27r%5E2%2B9r)%2F(27r%5E2-9r%2B3))%5E3)
[Answer]
# [Haskell](https://www.haskell.org/), ~~95~~ ~~89~~ ~~76~~ ~~69~~ 68 bytes
* -18 bytes thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz)
* -1 byte thanks to [Christian Sievers](https://codegolf.stackexchange.com/users/56725/christian-sievers)
```
f x=[w|n<-[1..],w<-mapM(\_->[-n,1/n-n..n])"IOU",x==sum((^3)<$>w)]!!0
```
[Try it online!](https://tio.run/##Jcy7CsIwFADQ3a@wxaGBm/Q1WZruDlIQnGKUUKwGk2swLengtxtBP@Ccu/KPqzExjuuFi/DGloqSMQmhpVa5fXa60E5QhDJHioyhJOmuP6awcO5nm2XnmrSbLhCZJEXU6ObJc1FACRXUsM3rSjaNOKhJP1EZubJKI//F7qVxYiP5m/gZRqNuPtK@@gI "Haskell – Try It Online")
Simple bruteforce solution. It tests all triples of rational numbers of the form
$$
\left(\frac{a\_1}{n},\frac{a\_2}{n},\frac{a\_3}{n}\right)\qquad\text{with }-n\le\frac{a\_i}{n}\le n.
$$
* We can always assume that the three rational numbers have the same denominator, since
$$
\left(\frac{a\_1}{n\_1},\frac{a\_2}{n\_2},\frac{a\_3}{n\_3}\right)=\left(\frac{a\_1n\_2n\_3}{n\_1n\_2n\_3},\frac{a\_2n\_1n\_3}{n\_1n\_2n\_3},\frac{a\_3n\_1n\_2}{n\_1n\_2n\_3}\right).
$$
* We can always assume that \$-n\le\frac{a\_i}{n}\le n\$, since
$$
\frac{a\_i}{n}=\frac{a\_iN}{nN}
$$
for any arbitrarily large integer \$N\$.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
ḟo=⁰ṁ^3π3×/NİZ
```
Simple brute force solution.
[Try it online!](https://tio.run/##ASMA3P9odXNr///huJ9vPeKBsOG5gV4zz4Azw5cvTsSwWv///zUvMw "Husk – Try It Online")
## Explanation
Division in Husk uses rational numbers by default and Cartesian products work correctly for infinite lists, making this a very straightforward program.
```
ḟo=⁰ṁ^3π3×/NİZ
İZ Integers: [0,1,-1,2,-2,3,-3...
N Natural numbers: [1,2,3,4,5...
×/ Mix by division: [0,1,0,-1,1/2,0,2,-1/2,1/3...
This list contains n/m for every integer n and natural m.
π3 All triples: [[0,0,0],[0,0,1],[1,0,0]...
ḟ Find the first one
ṁ^3 whose sum of cubes
o=⁰ equals the input.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 73 bytes
Takes input as `(p)(q)`, where \$p\$ and \$q\$ are BigInt literals.
Returns `[[p1,q1],[p2,q2],[p3,q3]]` such that \$\frac{p}{q}=\left(\frac{p\_1}{q\_1}\right)^3+\left(\frac{p\_2}{q\_2}\right)^3+\left(\frac{p\_3}{q\_3}\right)^3\$.
```
p=>q=>[x=p*(y=p*(p*=9n*q*q)*3n/q)/q+(q*=q*q),p-x,p-=y].map(x=>[x,3n*q-p])
```
[Try it online!](https://tio.run/##ZU7JTsMwEL3nK@aWGcfZmqKCkPMTHEMOVupWRcVLYlAqBL8e7AJSgMOM9Da99yRf5TSMJ@tzbfZqOYjFitaJtpuFZXiJzzJxp5ljjlijS0ely9AxEQlu8zmcuPTFs7Q4xxxvgjm3PS1eTR4EoOXgCEQLbwnAYPRkzqo4myNayCCFMlwWHPd/VBmyB7SEjv5p6Ye4pmQxqv3LoBAnDvJaMgUaZVf1hTcPfjzpI1LokF29ZggYg4ZDRXHDo04peU@SuBibSnOoNX2hm80aNdUuwt3m9of5Za7XYPudXD4B "JavaScript (Node.js) – Try It Online")
Derived from [H. W. Richmond (1930), On Rational Solutions of x3 + y3 +z3 = R](https://www.cambridge.org/core/journals/proceedings-of-the-edinburgh-mathematical-society/article/on-rational-solutions-of-x3-y3-z3-r/83C2B18408E842400B434976CE827B32).
[Answer]
# [Haskell](https://www.haskell.org/), 70 bytes
In *An introduction to the Theory of Numbers* (by Hardy and Wright) there is an construction that even includes a rational parameter. For golfing purposes I just set this parameter to 1, and tried reducing as much as possible. This results in the formula
$$r \mapsto \left[ {{r^3-648\,r^2+77760\,r+373248}\over{72\,\left(r+72\right)^2
}} , {{12\,\left(r-72\right)\,r}\over{\left(r+72\right)^2}} , -{{r^2
-720\,r+5184}\over{72\,\left(r+72\right)}} \right] $$
```
f r|t<-r/72,c<-t+1,v<-24*t/c^3,a<-(v*t-1)*c=((a+v*c+c)/2-)<$>[a,v*c,c]
```
[Try it online!](https://tio.run/##Hc29CsIwEADgV7mhQ/7OkCgIJXXyCVxF4QgWg2la4pHJd4/i@E3fk96vR849LdtaGc7EtLsQp7XPUD8csNqjNzEga2daQH9QbON9byigaIrRSRUnIUg3FXWU1qMMw@lK5mcTb32hVGCCrabCMMAMwo3jfyiUZf8C "Haskell – Try It Online")
[Answer]
# perl -Mbigrat -nE, 85 bytes
```
$_=eval;($a,$b)=($_*9,$_**2*27);$c=$b*$_;say for map$_/($b-$a+3),$c+1,-$c+$a-1,-$b+$a
```
You can save 8 bytes (the leading `$_=eval;`) if you know the input is an integer; this part is needed to have the program grok an input of the form `308/1728`. Input is read from STDIN. I'm using the formula given by @alephalpha.
[Answer]
# [Maxima](http://maxima.sourceforge.net/), 62 bytes
A port of [@alephalpha's Pari/GP](https://codegolf.stackexchange.com/a/175220/110802) code in Maxima.
---
[Try it online!](https://tio.run/##TYxBCsIwEADvvmLpaVM3tEmUaAp@JERIlUKx0bJ4CPl8rJ48zjBMinlOsU7g6hLTeI/oOdC4vG4P9Nlp2/LV7BUVd25Z/lAH8pm@mKmEDo0sQog67FJc8W8CK8/PNzJBA/ICDcGEvJUE3vQER01getspq08Em1AEBx3EUD8)
```
lambda([r],block([x:27*r^3+1,z:9*r-27*r^2],[x,9*r-x,z]/(3-z)))
```
] |
[Question]
[
The challenge, should you accept it, is to determine how much you win in the Bingo Golf Flax Lottery. Based on but not equal to the [BingoFlax lottery](https://www.fdj-gaming-solutions.com/bingo-flax/)
The input is two lists of numbers (positive non-zero integers).
The first list always contains 24 potentially *non-unique* numbers that make up your board, a 5 x 5 grid of numbers from the list in reading order: Left to right, top to bottom. The mid cell is always a free cell (a "wild card") that matches any number and this is why the board input is 24 numbers and not 25 (=5\*5). Note: the same number may appear more than once.
The second input list is of any length. These are numbers that may or may not match numbers on your board.
Matching numbers may or may not end up making one or more winning patterns on your board.
The type of winning pattern if any determine how much you win.
If more than one winning pattern emerge, only the one with the most prize money matter. Don't sum up the patterns.
The winning patterns and their prize money are:
[](https://i.stack.imgur.com/6uWSN.png)
Your program or function should return 500000, 10000, 1000, 500, 200, 100, 50, 30 or 0 for no winning pattern.
**Example 1:**
Input: 5 21 34 51 74 3 26 39 60 73 2 28 59 67 12 30 33 49 75 10 17 40 50 66
and: 33 10 7 12 60 49 23 38 15 75 40 30
Winning pattern: horizontal line.
Result: **50**
[](https://i.stack.imgur.com/WJ5UV.png)
**Example 2:**
Input: 5 21 34 51 74 3 26 39 *60* 73 2 28 59 67 12 *60* 33 49 75 10 17 40 50 66
and: 33 10 7 12 60 49 23 12 15 75 40 97 74 99
Two winning patterns: horizontal and forward diagonal since the mid cell is always free – only the most winning counts
Note: 60 appear twice on the board and since 60 is called from the second list both 60's counts as a match. The one 60 in the call list matches all 60's on the board.
Result: **500**
[](https://i.stack.imgur.com/kfzbs.png)
**Example 3:**
Input: 9 13 4 42 67 24 17 1 7 19 22 10 30 41 8 12 14 20 39 52 25 3 48 64
and: 9 2 4 13 11 67 42 24 41 50 19 22 39 64 52 48 3 25
Almost border, but missing 8. You still win 100 for the vertical line at the right edge.
Result: **100**
[](https://i.stack.imgur.com/X3Zw3.png)
This is Code Golf, shortest answer wins.
[Answer]
# Excel ms365, ~~355,~~~~349,~~~~331,~~~~328~~ 322 bytes
* -6 thanks to [xigoi](https://codegolf.stackexchange.com/users/98955/xigoi)'s tip to apply scientific notation;
* -18 due to change of regex-patterns;
* -3 due to the trick to multiply by 100 after recursion is done given by [quarague](https://codegolf.stackexchange.com/users/100270/quarague);
* -6 deleted rf-string notation. Patterns no longer include backslashes.
Currently in Beta, use `=PY()` to open the python interpreter. I'm probably embarrasing myself here trying Python script but here goes:
```
import re
max([s[1]if re.match(s[0],re.sub('(?=.{12}$)','1',''.join([str(+(x in xl("B1:B14").values))for x in xl("A1:A24")[0]])))else 0 for s in[['1{6}(...11){3}1+$',5e3],['(1...1.1.1...){2}1',1e2],['.{6}(111..){3}',10],['.(...1){5}',5],['1(.{5}1){4}',2],['.*(1....){4}1',1],['(.{5})*1{5}',.5],['1...1.*1...1$',.3]]])*100
```
[](https://i.stack.imgur.com/Zt1o8.png)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~263~~ ~~257~~ 250 bytes
```
lambda a,e:next((P[p]*c for p in P if all(a[k]in e for k in range(24)if p>>k&1)),0)
c=10.
P={16541247:5e5,9077073:1e4,235968:1e3,557328:5e2,8519745:2e2,541729:c,1083458:c,2162820:c,4329736:c,8659472:c,31:5,992:5,15360:5,507904:5,16252928:5,8912913:3}
```
[Try it online!](https://tio.run/##nVLLbtswELz7K@bUSAERcHe5fAhwvsF31whUV04NO4pg@9Ag6Le7S7VofOklPFBD7szskOL0dvnxOsp1hyW@Xo/9y7fvPXo3dOPw89I0q/W0ud9i93rChP2IFfY79Mdj068PG1sPc@lQS6d@fB4aDq0xpsfHwxdqW@fbxXZJ/mGxWr5T1EAcUqeDuuJT8kk6GoJj0RKzQXGqSTgbg11WKilox4ZNmLh0W0c@S9BsiClyZm8oCJck0VCOWkJiQ0Kd9ShsM6lEb1/1qfhQNyIrl9rF5UJcSDr5dd325@Fsl9AsYGM9z3XcKZggAUpIAQKOkILokQyDM9RWCcQQDxGEgqQgD0oIHuoR45378DOKFWeBmRibBZJBWmUmEP@XvXGfjxI/HcXwvygl1T6l/DdQAVkXBK5tOdQ@VP3Miau13Ugg5Nk0gH2Nq5ZULXzIiOE2jYnMywyJqp2ZmqPJLfYfw3rWUPUmtQPrR6x2UZ9h/3R2GJ7O9TXOv7Ob69NpP16aXbO@f@mnxrCrzIfzdNxfmrbdONxUhttK2y5w/Q0 "Python 3 – Try It Online")
Hardcodes the matches into a dictionary (can be improved).
## How it works?
`P` actually represents the following dictionary:
```
P = {
0b1111110001100011000111111: 500000, # Border
0b1000101010001000101010001: 10000, # Cross
0b0000001110011100111000000: 1000, # Picture
0b0000100010001000100010000: 500, # Forward diagonal
0b1000001000001000001000001: 200, # Backward diagonal
0b0000100001000010000100001: 100, # Any vertical line
0b0001000010000100001000010: 100,
0b0010000100001000010000100: 100,
0b0100001000010000100001000: 100,
0b1000010000100001000010000: 100,
0b0000000000000000000011111: 50, # Any horizontal line
0b0000000000000001111100000: 50,
0b0000000000111110000000000: 50,
0b0000011111000000000000000: 50,
0b1111100000000000000000000: 50,
0b1000100000000000000010001: 30, # All corners
}
```
where each key is a mask to the actual grid. The 5 least-significant bits are the first row, the following 5 are the second row, and so on.
The dictionary is ordered by score, so the first entry matched will always evaluate to the highest score possible.
The solution is a function that accepts two arguments: a list of integers of length 24 containing the `a`ctual numbers to be matched, and a list of integers of variable length containing the `e`xpected matching numbers.
That said, the algorithm is as follows: for every `p`attern on `P`atterns, check for each 1-bit if their corresponding element on `a` is present on `e`. If they all match, then return the score associated with `p`.
If no pattern is matched, return 0.
---
*-6 bytes* by simplifying the score constants, altering [@Joao-3's magnificent idea](https://codegolf.stackexchange.com/questions/269191/how-much-do-you-win-in-the-bingo-golf-flax-lottery#comment584588_269194) a little bit by keeping them integers.
*-7 bytes* by simplifying a bit more the score constants, now making them floats.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 74 bytes
```
aṚḣ3ZƲ⁺FUḄ“¢Ị×O‘=&¥TṪ‘+Ị?5
e€ŒHj1s5µ,Z;ŒD,ŒdƊ§ŻŻ5eⱮTṪ»Çị“<d¥¥¦¥Þd‘HḢ;×\Ɗݤ
```
* [Try it online!](https://tio.run/##RY29SgNBFIV7n2IqG6fIzO6sShSbIOnSJE2wEXabkC6VXZRAYNNtExFJkWQVRAIRhI3TzTL7HjMvMp5rCpm/c88995tRNh4/hHDvDi@u2kTD5ss//twOXDXz01ezdjqvlz0/fb4@NWXfHT4gz2DeqJPMP33aojsSE2W@@bBtiw63Rdrk5t1qq1Xm9zuaMLqeO70A7io1JdabKetVClDXVet2vbxrcqvNNoRwyZmIOIuxJWfJOWcSWuAVnNGNgERHtDiLcGLYFyjJQlCSjYhCLRU0EmgnMYHlH5fwQhzZ9AfxiaJa/3RCJPERQ/MR0X4B "Jelly – Try It Online")
* [Test suite](https://tio.run/##TY1NS8NAEIbv/RVzKF4cMclmE0v8OogUPIhQEYsIQnspvXnyUGhFEOqtHiKiHqppQaRQwZIY6GHDBvozkj8S39xkGXZmdt/n6bS73ZuiuMqi5yx8F830Ox/8Hp5m4V3ef1HjLB4m/nHef9pZU0Ejiz7RrmO5Jyvt/PZLj@od81qqH256enTAetRKh2qqYx3Ldj6flQkVJ/dZ/ADcdksFOBMVJG8tgOpZOPYS/yId6lh9FP@AR2g9lFCTZIokbexS3n/1qirw9rNoeVbtnVcs3YdCj04aK19FUKx8/Xi5mX70VJQPQgTns04@WKqFWhSFZMtkYbM02bVZsOWwqLFjsIuerS2WmFw2LRYGC8F2jV3JpsGmy7bB0mDHAYQQJmzJcZhAJCBJljdGvKBAJqQJn4EnURZGKAgOArt8gpbgI0gICoKDpPEH "Jelly – Try It Online")
A pair of links which is called as a dyad with the board as the left argument and the call sequence as the right. Returns a float containing the score.
This works by checking each of the possibilities programmatically. I started an alternative version ([here](https://tio.run/##HY7BSsNAEIbvPsUcepIpJtlsYilI0YvgSawWL4JCD5Z66slDoSkUpXpqD0FQVEwVRCvxUBtaK2zakPUtdl8kTj387Pw7M/83tWq9fp5lVd1@016kW7fiUX4mgQhif/6TDtJg/qC9URIkF1tn6Udymd9LA/FEo2rcUZNr2a8n7/H9aRxW1KT72@ZchgfW4b74VlFH@qVVOa1p70uNuye6dbPZsGwRaG96LAYELKvo9Z@86G3XzAbfobJIYuI5fqFTIL8BunVXzIlBsaSiWSXXPFyJQx0OF73dsvRFpCZX0l/0j9aSoCki7Y1pLxwScSZGYpRlHC0TmY3cRNdGhpaDrICOgS7VaK0jJ@eiaSEzkDG0C@hyNA00XbQN5AY6DoUALQP9guMgUCJQJPDlS5Y6JEoG2gYapnhgS5ElBBADKHvZIiwQDwgChABiADf@AA)) which uses a lookup table, but it’s already 65 bytes without converting to the score and so would be longer.
The test suite builds a sequence of sequences that yield every possible score for a given board (though the source sequence was constructed manually). The set-wise symmetric difference operator (`œ^`) is used in the footer to allow individual cells on the board to be toggled off as well as on since, for example, it’s otherwise not possible to build from a backwards diagonal to a forwards without ending up with a cross.
## Explanation
```
aṚḣ3ZƲ⁺FUḄ“¢Ị×O‘=&¥TṪ‘+Ị?5 # ‎⁡Helper link: takes a 5x5 grid of binary digits and returns 2, 7, 8, 9 for all corners, picture, cross, border respectively and 1 if none of those
Ʋ # ‎⁢Following as a monad:
aṚ # ‎⁣- And with reverse
ḣ3 # ‎⁤- First three rows
Z # ‎⁢⁡- Transpose
⁺ # ‎⁢⁢Repeat the above monad again
F # ‎⁢⁣Flatten
U # ‎⁢⁤Reverse
Ḅ # ‎⁣⁡Convert from binary digits
“¢Ị×O‘=&¥ # ‎⁣⁢For each of 1, 176, 17, 79, bitwise and with the result of the previous step and check if unchanged ( &Ƒ= would also work for the same bytes)
T # ‎⁣⁣Indices of truthy values
Ṫ # ‎⁣⁤Tail (will be zero if no truthy values)
‘+Ị?5 # ‎⁤⁡If 1 or zero, increment by 1, otherwise increment by 5
‎⁤⁢
e€ŒHj1s5µ,Z;ŒD,ŒdƊ§ŻŻ5eⱮTṪ»Çị“<d¥¥¦¥Þd‘HḢ;×\Ɗݤ # ‎⁤⁣Main link
e€ # ‎⁤⁤For each number on left, check whether present in right argument
ŒH # ‎⁢⁡⁡Split into two pieces of equal length (both will be 12 binary digits)
j1 # ‎⁢⁡⁢Join with 1
s5 # ‎⁢⁡⁣Split into pieces of length 5
µ # ‎⁢⁡⁤Start a new monadic chain
,Z # ‎⁢⁢⁡Pair with its transpose
;ŒD,ŒdƊ # ‎⁢⁢⁢Concatenate with the major diagonals paired with the minor diagonals
§ # ‎⁢⁢⁣Sums of innermost lists
ŻŻ # ‎⁢⁢⁤Prepend with zero twice (to offset the lists by two)
5eⱮ # ‎⁢⁣⁡Check which of these lists include a 5 (so a complete line)
TṪ # ‎⁢⁣⁢Last truthy index
»Ç # ‎⁢⁣⁣Max of this and the result of calling the helper link on the same 5x5 binary grid
ị ¤ # ‎⁢⁣⁤Index into the following called as a nilad:
“<d¥¥¦¥Þd‘ # ‎⁢⁤⁡- [60,100,4,4,5,4,20,100]
H # ‎⁢⁤⁢- Half
Ḣ;×\Ɗ # ‎⁢⁤⁣- Head (30) Concatenated to the result of cumulative product of the other values
Ż # ‎⁢⁤⁤- Prepend zero
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# APL+WIN, ~~216~~ 186 bytes
30 bytes saved with better board compression
Prompts for vector of first numbers followed by second
```
⌈/0,(25=+⌿a=(a←((25⍴2)⊤33080895 18157905 473536 1118480 17043521 17825809),(⍉10 25⍴(∊25⍴¨(⍳¨5)=5⍴¨s),,⊃s∘.=5⍴¨s←⍳5))×⍉16 25⍴(r∊⎕)+(r←(12↑n),0,12↓n←⎕)=0)/10×5E4 1E3 1E2 50 20,3,(5⍴10),5⍴5
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##rZA9SgRBEIXzOUWF09hqV1fXTHewoYGgeIZBUYRFxY2MBV0XFUVED2BgrrmgN@mLrK/Wn1wwGOZVdb2vXvdwNF7eORnGh3vL2@NhMtnfntfr@82NenYjDdT6FhQ3dXq@O6@X09Xg26ijpXr5NozaAWct6nr1Gl2dPYmEHHJR4szal6CUelHpiJlzyoG4D0k0MkSOmkNxvq1XFxxoAWnrdLYQ789ov7w/qxt9lRPnfZ2dTur0ceWnheUYUuc@HozRfTOOAUFwtwSFeBzr2e2B88GbujswF05Hwa1y@HjQtUS8JvgiKWIEL741Dgfn7a9z3L2Z7zZKyC2JlKlPJBQ7kkJdoB6aYiZF1RNHkkAilAr1eAm7NKVg8K5r0EdnMQUnRqKQZGK1WUzB2vxlVfe3VdC/q0pv8FKwkJpCDAylaNyYDMTmhSsaBrkSU14AEl7J8iiiKNKlTF0CIQIACrMxQAIGHoT5otgNkpkwL@b8n73cfAI "APL (Dyalog Classic) – Try It Online")
[Answer]
# [R](https://www.r-project.org), ~~269~~ 224 bytes
```
\(x,y,`/`=c,z=x%in%y,`?`=diag,s=sapply,`~`=max)~.5/1/2/5/.3/10/100/5e3*(s(list(w<-matrix(z[1:12]/1/z[13:24],5),t(w),?w,?v=w[,5:1]),\(r)~rowSums(t(r))>4)/s(1/176/17/79,\(n)!~(m=n%/%2^(0:14)%%2)>m*((u=w*v)&u[5:1,])[1:3,]))*100
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nVLNjtMwEJY49swDhEhBnmpa23GcbCrcPgTHtqghm6BIzQ9xuil76ItwKSvxUHDiURhv0EocWKGVbHlm_M3fN_P1W399KM3301Aubn782rEzfsEDP5gc7805qJqA1M3B3FbZJ7TGZl13JMvlYOrsDJel5pKHXPOl4lLQEVwXas4sO1Z2YOO7RZ0NfXVm91u5kuGe0CSpVRjtUQMSAnAz4ubOjFvUK7kH3LEeLn07vj_Vlg2kwDoCbpnkMonp8iQlTANvLqw2TcCD8AMTKxlBEISwrueMncw4v4O3py0FxD1QZkUPzKm6qc-fr1633VC1jWU2r7qiMWmawuxjm_W3nvFypjGUqCLUEpMIFYYxqhRjgQnJGN6gJi1BGaISqBRGKSYapUCZYCRQC4xjmNnis6Vwj0y4mBRKCsAn0YH-0p6y_sPsKqGkz_-6YqPUYZ5HuHaU-F-c63_qW6mX-Lhpv8TLMU5MO3b_UAswy7OBTZvIHMe0DhZs11fNUDI_sN5i7QVLUfrYZXYomMW8PR6zzhbGRx-wZI-TRgsA6Nmi84y_a3yYluN6nd7f)
A function that takes the board as the first argument and the call sequence as the second argument and returns the score.
*Thanks to @pajonk for saving three bytes!*
[Answer]
# JavaScript (ES6), 205 bytes
Expects `(board)(drawn_numbers)`, where *board* is an array of 24 integers and *drawn\_numbers* is a set of integers.
```
a=>s=>(m=~a.reduce((t,v,k)=>t|s.has(v)<<k+k/12,4096))&33080895?m&18157905?m&473536?m&1118480?m&17043521?a.map(h=v=(_,i)=>v|=!(h|=!(m&31<<i%5*5),m&1082401<<i))|v?100:h?50:m&17825809?0:30:200:500:1e3:1e4:5e5
```
[Try it online!](https://tio.run/##tZLdjtowEIXveYr0oshupzBjexI7JeQherlCVQrZQvnJCmh6g/rqdAZ2papColuplhyNHc83nnP8rembw3y/ejp@2HWL9vxYnZtqeqimZlv9bEb7dvF93hpzhB7WtpoeT4fRsjmY3k4m6/frMTkImHJrh95jxJi43g4pEhcJNQyFZ5/rHlEMETUqMHh2VDejbfNkllVfmc@wEnh/qt6YpX62Q0@Tyeotv2MLkoLRBdQda099TYjlsmYsFRYdR0w1lh5LJz9YJrVeZii55fOmPWZfuma/oKzKHhgcgQ/ABEUADy4HnyBHKCQGF4FlVYC05RG8h5CgYCAEKqRRYIQ8n8Egk3GButdB87@CeoUmIDkJwWmqC3pW8EAJnNNcuV8giEqlAA61JEs1lguECHmYfRwM5t3u0G3a0ab7ah7NVQZrdu2P7FN7NA8za232D2M8zvAem1ULurT2qirC9nfhIqKgXyQVPZ0HL1qwChtUnNtFBc434e4OXFV@gadCW0vpzxIX@E26/40uOLFVvCVSZ8VfMVeclFdw9VafTlArxUV5P/xcRuj0H@gQL/zr3WWcfwE "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES7), 212 bytes
Expects `(board)(drawn_numbers)`, where *board* is an array of 24 integers and *drawn\_numbers* is a set of integers.
```
a=>s=>"5115211111555553"[a.map((v,k)=>t|=s.has(v)<<k+k/12,t=4096),x=[33080895,18157905,473536,1118480,17043521,..."0"+17**6+8,17825809].findIndex(n=>!(~t&(n>9?n:n<6?1082401<<n:31<<n*5+2)))]*10**("661"[x]^3-x/9)|0
```
[Try it online!](https://tio.run/##tZJBj9MwEIXv/RUhB@Sks6nHYzv2kmTPnDlGQQrbFJYWZ7WJSg8r/noZt6yEUKWySMwhSiL7ezPvzdd@30/3Tw@P800Y18NxUx/7upnqJjWIRmEsE4vSti@@9Y9C7GGb1c38XE/Fl34S@6yqtsvtChXMtZbeZnCoWyLppPMG0KEpvTSgSzJkgXlOOwlYSk0sAEVRpDJdYpnndun4v1PGSd8Vm4ewfh/Ww0GEunkjfsxvRWj8XbgNlb1D6ZSWWFXhluIzN0uVZVmXo8xzkVqLaXvoPtLNYeWzZ3ncDXPyaeyf1pjUSWuAhUmDQSg1ECgL5MFKKPkdlAPDXyXwSCSBCLSHkkeJXYOWYCRY28Ei4TpB1eug9q@gFKEekE@CVvGq0vEs4wE9KBXvcn8awUUqalAyShpWM9yAdmB1926xuB/DNO6GYjd@FhtxtiETYfiefBhm0XZsXPIPtVol8hrbRC/wNNqrVJhNV@FsIqNfLGU/FQGxFyYaq6M5l0UZbi7C1RV4dPkF7ss4mvd/SpzgF@n0G51xHCtnixiT5Xw5XE6St@CcbVwdHaPkFHl/zC8ZpuN/oIM78c@9cx1/Ag "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 224 bytes
```
\b(\d+)\b(?=.*;.*\b(\1)\b)?(,|;.*)
$#2
13=`
1
1{6}(...11){3}1111
500000
(1...1.1.1...){2}1
10000
.{6}(111..){3}....
1000
....(1...){5}.
500
(1.{5}){4}1
200
.*(1....){4}1.*
100
(.{5})*1{5}(.{5})*
50
1...1.{15}1...1
30
.{25}
0
```
[Try it online!](https://tio.run/##nVA7TsNAEO3nFE8CJNtEq5392SaKUiLukCKgUNBECIXK@FocgIuFN2tCD2vJfjvzPjN@ez69HB/PD8fX99MdRL4@H48HgrVAVnLT3O/Pu6dmd7ht@dluXLd2nRWU93bbrD54b@X6KojGzV5UdCpz45xTbac4K49kb0catXJ9nGunMJNcG84kJFo1zmy62hBDzULOszMb8yBup0RxMEpXCa5WXGc6aSqlU75/IKWyhE@a54okWm7Is/jzZfuMoIgJWdEnRISCOKJ49MQIAzJvPTQgesSINKLPUA/tkTyyRylSfx@bLFcq5eSFiDhAswlIZfifM8s/Mol/M8feEsbxkjxCaYcUzD8kM1STUxjMiTsmxVA9EoK3uTJHypwyDShpiSWdLrRSNSPa0YtCTrZY2TrJlBRxp/wN "Retina 0.8.2 – Try It Online") Takes input as two lists of comma separated integers separated by a semicolon but link is to test suite that takes input in the example format for convenience. Explanation:
```
\b(\d+)\b(?=.*;.*\b(\1)\b)?(,|;.*)
$#2
```
Turn the first list into a bitmask of which integers are present in the second list and delete the second list.
```
13=`
1
```
Insert a `1` before the thirteenth bit. This simplifies the patterns below.
```
1{6}(...11){3}1111
500000
(1...1.1.1...){2}1
10000
.{6}(111..){3}....
1000
....(1...){5}.
500
(1.{5}){4}1
200
.*(1....){4}1.*
100
(.{5})*1{5}(.{5})*
50
1...1.{15}1...1
30
.{25}
0
```
Score according to the first matched pattern.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~197~~ 193 bytes
```
a=>s=>[17825809,31,1082401,17039425,1118480,473536,18153809,33080895].map(g=(v,i,p)=>p.map(j=>g=v&~a.reduce((t,v,k)=>t|s.has(v)<<k+k/12,4096)>>j%7*'051'[i]?g:[.3,.5,1,2,5,10,100,5e3][i]*100))|g
```
[Try it online!](https://tio.run/##tZLNjpswFIX3eQo27eDpKfH1D7bbgT5El4gFTRian4YoULoZ9dXTa9KRRlWkdCrVQthg@zvX53jbTM2wOm2O4/tDv27Pj8W5KcqhKCtyXlkvAzSBpFdGcu@kDkZZEJE3XsI4bXUO8mT1vFZLL32wdfatOaZdkU7Y4CiK8jj/2BZlV0xvfzbZqV1/X7VpOmLCjufHpyH72gzpJB4edu92S1IwMuSiLLdv3P2dtHRXbepP3Ycq08i4ACjwW/IjYVtd8@w9j4V46s77dky@9M1pTUmRVBaKoA0swRloqBw6IJdwPIbysPzlwIpa8gFgAtwF7bgGWIk8r7FIuM1Q9Tpo/ldQHaEBxCthVNyqTFzLeFCAUnEv12cIPlLJQMkoaVnNcgHGIzf1x8Vi1R@Gft9m@75LH9OLDSI9tD@Sz@2YVrUQIvmHtlwm8hbbRi9oPtqrVJitb8LZREY/W8p@Kg3NXthorInmXBdluL0KVzfg0eVneHDxaCH8KTHDr9L1CzrjOFbOligmy/lyuJwk34JLtvHqmBglp8j3x/6WYTr9Bzr8zL/Uzu38Cw "JavaScript (Node.js) – Try It Online")
```
a=>s=> // Entry
[17825809,31,1082401,17039425,1118480,473536,18153809,33080895] // Pattern
.map(g=(v,i,p)=> // For each. Init g to NaN
p.map(j=>g= // Loop position
v&~a.reduce((t,v,k)=>t|s.has(v)<<k+k/12,4096) // Arnauld's converter, outside is empty
>>j%7*'051'[i] // j%7 == [1,2,0,6,4,5,3,1] covering [0,1,2,3,4]
?g:[.3,.5,1,2,5,10,100,5e3][i]*100 // If found then write to g
))|g // Output. NaN => 0
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~73~~ 64 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
å2ä`1š«D•1MÖ•₂вès5ô©Å/D®Å\DŠ«®Dø®4Fćˆøí}˜¯˜)P30₄;т·4°50x₄6°;)ć*à
```
Outputs `500` as `500.0` and `500000` as `5.0e5`. If integers are mandatory, a trailing `ï` (cast to integer) can be added for +1 byte.
[Try it online](https://tio.run/##LUy7agJBFO39immVgezsPNZgu9gJ6VVIBAurFDY2AVl8/IHVFmtQUMSNhECs79Vqm@QX9kfWMyjcy@E838dvg9Gwqngb8uZVXdd0iMvpp@rwClAmyd8378aWf2jP86eYcp734mtGB8pjPlNu2pdlseAzHz@KlL6KtP6igzKZtf4T@jV0ssEEzNGpVb8sG5xVVddKESoptJHCAiOghuQAz1K4AJLnuCYSXoqkUOAaloZloEVYUeAKngFavHP9WtcHvPHo@DmfDyFr7Cl77/qODvo3) or [verify all test cases](https://tio.run/##lY@9SgNBFIVfJaSLHHB@7szukiLNYifYrwuJaGGjRUBMIchikt7CKkUUBSUkBgmYeiap0ugr7IusdxKwTzVnZs75zr3X3c7Z5UXlpze9dqte61yd1@otFuXgkUWvXfk35V/bcv3sJml5/yKP/RMfZVH8fPn3rvEL9@H7h6mb@f5puh67iZulfulmdLQabgZ@6ad3m5H73IwaJ1qUxUPzt3Df5OZG3PLNunmzsRoe@HEFt6iyLDNQEppgJCKChrLQCaxAxBoqhuFbBKmgBbQGJYgMpICMQAJGwNocGf/w29bHWTYpDR1DmuBmnxZ5jto@dXbfOtb/dUkU8EmyK00gmQRSAa0osGQIc0wFDm9GEvGWQFAijGR4GsMDUgxL3MheRjBHykBhFoM4xRPtOGENCjFO8C4mz/M/).
**Explanation:**
```
å # Check for each value in the first (implicit) input-list whether it's
# in the second (implicit) input-list, resulting in a list of 1s/0s
# Insert the free middle cell:
2√§ # Split it into two equal-sized parts
` # Pop and push both lists to the stack
1š # Prepend a 1 to the top/second list
¬´ # Merge the lists back together
# Corners:
D # Duplicate the list
•1MÖ• # Push compressed integer 70848
‚ÇÇ–≤ # Convert it to base-26 as list: [4,0,20,24]
è # Index it into the list
# Main diagonal:
s # Swap so the list is at the top again
5ô # Convert it to a 5x5 matrix
© # Store this matrix in variable `®` (without popping)
√Ö/ # Pop and push the main diagonal
# Main anti-diagonal:
D # Duplicate the main diagonal
® # Push matrix `®` again
√Ö\ # Pop and push the main anti-diagonal
# Cross:
D # Duplicate the main anti-diagonal
Š # Triple-swap
¬´ # Merge the duplicated main diagonal/anti-diagonal togther
# Rows:
® # Push matrix `®` again
# Columns:
D # Duplicate it
√∏ # Zip/transpose; swapping rows/columns
# Picture:
® # Push matrix `®` again
4F # Loop 4 times:
ć # Extract head; push the remainder-matrix and first row separately
ÀÜ # Pop and add the first row to the global array
øí # Rotate the matrix once clockwise:
√∏ # Zip/transpose; swapping rows/columns
í # Reverse each inner list
}Àú # After the loop: flatten the remaining 3x3 center matrix
# Borders:
¯ # Push the global array
Àú # Flatten it as well
) # Wrap everything on the stack into a list
P # Take the product of each inner-most lists
30 # Push 30
‚ÇÑ; # Push 500 (1000 halved)
т· # Push 200 (100 doubled)
4° # Push 10000 (10**4)
50 # Push 50
x # Push 100 (double the 50 without popping)
‚ÇÑ # Push 1000
6°; # Push 500000 (10**6 halved)
) # Wrap everything on the stack into a list again
ć # Extract its head with the checks
* # Multiply the values at the same positions in the two lists together
à # Pop and push the flattened maximum
# (which is output implicitly as result)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•1MÖ•` is `70848` and `•1MÖ•₂в` is `[4,0,20,24]`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 112 bytes
```
I∨⌈EΦ⦃³⁰=__N⁵⁰”61∧V÷⊗P&Πï⁹K∕⬤Y⪪S”¹⁰⁰”{⊟∨✳⎇¡§_⁸ξ↷⊖⮌”²⁰⁰??^^⊘φ]W[Oφ_&8_×χφ=7ZN⊘×φφ YG ⦄⊙⪪⭆ιΦ⍘⁺³²℅λ²ξ²⁴⬤λ∨Iν№η§θξκ⁰
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZFtS8JQFMfpm9wWxBWuNJ1zrlAzoQciFQyk1hxrbjm6TtuDGNH3CHrji6K-Un2a_mcTbOyeh__vnO3ec9-_vakbe3NXrtefWRqUG787l4M4jFLedZOU92N-5a7CWTaDX_DTUKZ-zF809ZApTcfpKYLpFO86jjPeg7k7gBm0YY7BKipB2-q3rFHLHvW3EWA1h-32eIzk3JVLf8KDEtWPLPAAkbPfcACvw5mfcE-wHDeN2962o2ABMYLs5owpr4J1omc-XMgw5cMUx3mg3YeCbQ5w4iZ-ofOBzBKuVQXrx5MwciWXpRL2hrXKgxpMR0KmimIoEaTuPMOMpmDpRTTxV_wpb6BHsEcyKsKjj-TeSzaT_bKU8lIq9s-bZen4ckUwrYb5wRvwGqQ6nClYXYVEOd4GKkgyMM1qgTSgGjRDpwljgdVUugnwui2YRRVE_jVRQ1Ur8opeNFOTaRS_N03bLvb5Bw "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation: Creates a dictionary mapping scores to strings representing bitmaps of entries that are not part of the winning pattern, then filters them on winning entries, and outputs the highest key, or `0` if no entries win.
The best I could do without lookup tables was 123 bytes:
```
≔⪪⪫⪪⭆θ№ηι¹²1⁵θI∨⌈Φ⁺⁺Eθ⟦⁵⁰ι⟧Eθ⟦¹⁰⁰⭆θ§λκ⟧⪪⟦²⁰⁰⭆θ§ικ⊘φ⭆θ§ι⁻⁴κ³⁰⭆θΦι¬∨﹪κ⁴﹪μ⁴φ⭆θΦι∧﹪κ⁴﹪μ⁴×χφ⭆θΦι⁼↔⁻μ²↔⁻μ²⊘×φφ⭆θΦι¬∧﹪κ⁴﹪μ⁴⟧²I⌊⊟ι⁰
```
[Try it online!](https://tio.run/##hVJNa8MwDL3vV5idbPCg@V7oKZSNbdCt0N1CDlmTtqZO3CZO6b/PnuMWurF0kEiR9PSeLGe1zZuVymXfJ20rNjVd7qXQ9E2Jy@dSN6LezPM9PXAyU12t6ZYTwRgnjgtz79zDBngPbHq3AFjTWd5q@tHQeX4SVVfRZyF12dCF7FprznRpMAFVht5Lwpkg80My0a91UZ6o5GTHWGZ07WCpO4oVA5aTl1wey4Ku2ThuLmrM4w8NgHm/Kc@jA/mu7JlU0UlFd5z4Zm4bVSZiA8N6lCCpi9vdnHyKqmzpCixslObp0OWypclXq2SnS2pPAA7XMPyZZlfLsBJrI8FunvXfcVl21hyuG3rDXS/Unoqz5AR22vdpGgDpYLvYcwAfwXtIhXAxJyGWHpkYzyMQJhWZ38uWPJR85CKwOIgd1Hx48/OEIYZIDcJUrppMg@vZ2Alss2mKIysfx1nWPxzlNw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Converts the first input to a string of binary digits representing whether the number is present or absent, inserts a `1` in the middle, splits it into a square array, then generates a list of pairs of scores and cells required by that score, filters on those pairs where all of the cells are present, then outputs the highest score, or `0` if there was no win. The pairs for scores of `50` and `100` are generated separately from the others and concatenated later. The pair for `200` comes before `30` because it saves a byte.
] |
[Question]
[
Your task is to calculate the amount you have to pay for prescribed medication at a pharmacy in Germany. The amount is simply based on the full price of the item, which will be your input. It is a decimal number with exactly two fractional digits (ex. 5.43). You can assume it's strictly positive. Your task is to calculate the amount a customer has to pay, according to this function:
$$
A(x)=\begin{cases}
x&\text{if } x\le 5\\
5&\text{if } 5\le x \le 50\\
0.1x&\text{if }50\le x \le 100\\
10&\text{if }100 \le x
\end{cases}
$$
or equivalently
$$
A(x)=\min(x,\min(\max(0.1x,5),10))
$$
The result must be **rounded** to two decimal places (half up). If these are 0, they may be skipped from the output. There must not be more than 2 decimal places. You can take numbers or strings as input and output, but be aware of inexact floating point representations.
Use a comma or a point as the decimal separator.
## Test cases
(Whitespace just for readability)
`5.00`, `5.0` and `5` are all ok.
```
4.99 -> 4.99
5.00 -> 5.00
5.05 -> 5.00
10.00 -> 5.00
49.00 -> 5.00
50.00 -> 5.00
50.04 -> 5.00
50.05 -> 5.01
50.14 -> 5.01
50.15 -> 5.02
99.84 -> 9.98
99.85 -> 9.99
99.94 -> 9.99
99.95 -> 10.00
100.00 -> 10.00
1000.00 -> 10.00
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
÷⁵«⁵»5«+ȷ-4ær2
```
A monadic Link that accepts the full price as a float and outputs the charge as a float.
**[Try it online!](https://tio.run/##y0rNyan8///w9keNWw@tBhG7TQ@t1j6xXdfk8LIio/86h9s13f//jzbQMzDQUTDRs7TUUTAFs4GkqY6CIVTCEiJmAKdMIJQpmDKE8AyBPEtLPQsTCAXhWUJ4lmDDIPqBNIgRCwA "Jelly – Try It Online")**
### How?
```
÷⁵«⁵»5«+ȷ-4ær2 - Link: Full Price P
÷⁵ - divide Full Price by 10 P/10
«⁵ - minimum with 10 min(10,P/10)
»5 - maximum with 5 max(5,min(10,P/10))
« - minimum with Full Price min(P,max(5,min(10,P/10)))
+ȷ-4 - add 0.0001 (catering for banker's rounding effects below)
ær2 - round to two decimal places
```
[Answer]
# APL+WIN, 21 bytes
Prompts for input
```
2⍕(n⌊((.1×n←⎕)⌈5))⌊10
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv9Gj3qkaeY96ujQ09AwPT88DygBVaD7q6TDVBJJdhgb/geq4/isopHEZ6BkYcIEYJnqWlmCGKUzE1ACZZQJnmcJYhnAxQ4iYpaWehQmcBRezhItZAsXSuAwNwCaDGWAWAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 39 bytes
```
\(x)round(.001+min(x,max(.1*x,5),10),2)
```
Basically using the formula given by the OP.
-5 bytes thanks to @doubleunary
-3 bytes and fix a rounding error thanks to @NickKennedy
-6 bytes since the OP removed the requirement for exactly 2 decimal places.
[Try it online!](https://tio.run/##NYtLCoAwDESvk2gJSTV@EA8jSsGFFUSht6/W6mbefJgjujG6y8/nunsIeOyXX4CYpdzWpzDbFICkCEbRCKOxGB30jIMDKy@kSVqTlUQl1ndUkt80Wld5bTUr9V37tF/ID2FmjDc "R – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 13 bytes
```
2⍕⊢⌊10⌊5⌈.1×⊢
```
[Try it online!](https://tio.run/#%23SyzI0U2pTMzJT///P03hUdsEBaNHvVMfdS161NNlaAAkTB/1dOgZHp4OFPr/vyS1uKQYrMpEz9JSwVTPwABEmCoYGoCYJpZgAQMYaQImTUGkIZhtaKpgaalnYQImwWxLMNsSZAJYG5AC0VwaIGccWgG2UFMn2lDPNDYNylV41DtXoaAotaSkUiEtvyg3saQkMy8dAA)
Tacit prefix function. Takes input as number.
Thanks to Graham for original APL solution.
### How it works:
```
2⍕⊢⌊10⌊5⌈.1×⊢ ⍝ Anonymous, tacit function.
.1×⊢ ⍝ 0.1x
5⌈ ⍝ max with 5
10⌊ ⍝ min with 10
⊢⌊ ⍝ min with x (as a fork)
2⍕ ⍝ format with 2 decimal places
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 40 bytes
```
x=>Math.min(x,x<50?5:(x*10+.5|0)/100,10)
```
[Try it online!](https://tio.run/##ddA9boMwFAfwnVM8sWAX4poKS3EoZMrYqSPKgPhIqKiNwK2Q2t6gUpeO7T16nlygR6AGESVEZXm2fu9vW34P8XPcJHVRqYWQadblQdcG4V2s9uSxEKh12ltG12yF2iuX2oS9UnztUuq4FHd@ZABEAECJFr2a/caErTO6RzgfvN@cOTvm2TTPxov@c2/G2eju1F1vxo/5mzPnnCyHPCd8eeFsdD517s24zpvudA56XsO/Tg5DQ/tFw9gaJJf1Jk72CEWFqByQT2qLIQjhRZ8pMwV11kAAOdJd7GtLpGhkmZFS7nojSt6ruhA7hEkVpxuRIobBBhMWoS52f34ug4a7g/5NWIP1@/Nx@PrU1YIVWIfvdwvrF9@w3/0B "JavaScript (Node.js) – Try It Online")
# [Python 3](https://docs.python.org/3/), 45 bytes
```
lambda x:round(sorted([x,5,10,x/9.999])[1],2)
```
[Try it online!](https://tio.run/##Xc/BDoMgDAbgO0/RIyTMgZNkmLijL@E8sGgiiVOiuLmndyjTZJwoX/42rfnYpu8uS57BfWnV81EpmNOhn7oKj/1g6woXMxWUMzqfZSSlLEnBSxqT5d3otgaeIlCQQf1SLdadmSwm0WgHbdbXtNr9C1YSBGbQncWKQo4VIQsAixgDON18hQASN9/DWjkQR0L4hNh6AkhCEDtwDzwJ4UjEDqSMrj7hDrz@QOwgPcgkhC3B/eqc7YttAMjBn3wB "Python 3 – Try It Online")
-2 from PattuX
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~95~~ 92 bytes
```
\.
.+
$*
^(.{1000}(?=.{8995})|.(.{499,998})(?=\2{9}....)|.{0,500}).*
00$.1
0*(.+)(..)
$1.$2
```
[Try it online!](https://tio.run/##NY6xCgIxDIb3PEeFtneE9Gig/yCOvsQhOji4OIhb7bP30oIZvnzkTyCf5/f1fvSTv977zkS8kIt081yTiDR/OXMtgLbwYxtmYAVKCxbsW0VjK4uqrGrrgSOJOE4k0fMSvIXkErutd2ERygyQDlP5M0/qYJqelAAueXI6pkPJnhpn4zfrBw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\.
```
Multiply by `100`.
```
.+
$*
```
Convert to unary.
```
^(.{1000}(?=.{8995})|.(.{499,998})(?=\2{9}....)|.{0,500}).*
00$.1
```
Calculate the amount to pay, with two `0`s prefixed in case the amount is less than `100`.
```
0*(.+)(..)
$1.$2
```
Divide by `100`.
The disjunctions are as follows:
* `.{1000}(?=.{8995})` Any amount over `9994` becomes `1000`.
* `.(.{499,998})(?=\2{9}....)` Any amount over `4999` becomes a tenth of its value. `.(.{499,998})` is the amount to pay, between `500` and `999`, but the input has to match that value plus `9` times `1` less than that value plus `4`, which equals `10` times that minus `5`, thus rounding half up.
* `.{0,500}` Any amount below `500` is unchanged, but amounts between `500` and `4999` become `500`.
[Answer]
# Google Sheets / Microsoft Excel, 31 bytes
`=fixed(min(10,A1,max(5,A1/10)))`
Put the input in cell `A1` and the formula in `B1`. The `fixed()` function also takes care of rounding.
Equivalent JavaScript (rounding issue, non-competing, **45 bytes**):
`x=>Math.min(10,x,Math.max(5,x/10)).toFixed(2)`
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~42~~ 36 bytes
```
->a{[a,[a/10,5].max,10].min.round 2}
```
[Try it online!](https://tio.run/##bdDRCoIwFIDhe59iD6CnTTbwQHlVt72ASBglCKViCYb67OvkScnR1Tl8/IxtTXt@2Xxngzjrk8xPso2SvknhnnW@kjSLEpqqLS8iHO12ezju4VaU1wcFdT90Qy3ypINndcrT0RNCgpRCBDFvBBoQGT4bgVkKwwUNswI1HfIDGh0w8g9oF8wMikFpF5YiJECEiAsEjL5gZkAG1C5MheLXKjlfjN/gEazEo/@zbw "Ruby – Try It Online")
# [Ruby](https://www.ruby-lang.org/), 38 bytes
Formatted as per initial requirement:
```
->a{"%.2f"%[a,[a/9.999,5].max,10].min}
```
[Try it online!](https://tio.run/##bdDNCoMwDAfwu09RBt60a6UFA87Tdt0LiIwOVhA2J/sAh/rsXWamzLJTwq9/QpPb8/hyduPi3HSrkCd2FRYmKswaOABEuuQX00ZSYK3qwWXZbr/l56o@3fGh6fq2b5gtWv64Hmw5BIwJLgRjcU4dgsJBBJ8OQc8JTQksegFyHPIDCjzQ4g8oH/QEkkAqH@ZEggDAU0rg8ukX9ARAAMqHMSFpWymmj9EOAcJCAryfewM "Ruby – Try It Online")
[Answer]
# JavaScript (ES6), 45 bytes
```
x=>~~(Math.min(x*10,x<50?50:x,100)*10+.5)/100
```
[Try it online!](https://tio.run/##ddA9boMwFAfwnVM8sWAX4poKS3EoZMrYqSPKgPhIqKiNwK2QquYElbp0bO/R8@QCPQI1iKghKov99Ht/P8t@iJ/jJqmLSi2ETLMuD7o2CA8HdBerPXksBGqvXOq0t4yuGV21jksp1mIThq913fmRARABACWUOno3@8KErTO6RzgfvC/OnJ3ybJpn46D/3JtxNro7ddeb8VP@5sw5J8shzwlfXjgbnU@dezOu86Y7/Qf9V8O7/hyGhvaLhrE1SC7rTZzsEYoKUTkgn9QWQxDCiz5TZgrqrIEAcqS72NeWSNHIMiOl3PVGlLxXdSF2CJMqTjciRQyDDSYsQr3Y/fm5DBpmB/2dsAbr5/v9@PmhVwtWYB2/3iysb3zFfvcL "JavaScript (Node.js) – Try It Online")
---
## 40 bytes
This one works in theory, but fails on some test cases because of rounding errors.
```
x=>Math.min(x,x<50?5:x/10,10).toFixed(2)
```
[Try it online!](https://tio.run/##ddE9boMwFAfwnVM8sWArxDURruJQyJRunTqiDIiPhIraCGiFVPUGlbp0bO/R8@QCPQK1KVFDFBbb@r2/n2X7IXqO6rjKy2YuZJJ2md@1fnAXNXvymAvU2u0No2u2aq8cajsUk0be5m2aoAXuvNAACAGAEkptNZt6YcLWHtwlnPeuFyfOjnk2zrOh0SV3J5wN7ozdcSf8mF@cOOdk2ec54cszZ4PzsXN3wlXedMbv4NC/e/079AXlZwVja5BMVpso3iMU5qK0QT41Wwx@AC9qT5E2UKU1@JAhVcWesliKWhYpKeROm/qg@6bKxQ5hUkbJRiSIYZiBCfNADTO9/0LmWmdQ39vXZ8IarJ/v98PnhxotWIF1@HqzsDrxFXvdLw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python](https://www.python.org), 41 bytes
```
lambda x:min(max(5,(x*20+1)//2/100),x,10)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3NXMSc5NSEhUqrHIz8zRyEys0THU0KrSMDLQNNfX1jfQNDQw0dSp0DA00oRoepuUXKWQqZOYpFCXmpadqmAIVWHEpJBYXpxaVKKRpZIK12NoW5ZfmpWhoZGrrGQBNAorpGGlyYerVAWLsBphiUW0AdAgu9QgLIfZhsxCsW8fQCJcZhgZcClwQjy5YAKEB)
Straight-forward implementation of OP's formula. For the rounding it uses floor division resulting in integer-valued floats which - unlike tenths - are guaranteed to be represented exactly.
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 26 bytes
```
dup.1*5|10,` &/100* |~100/
```
[Try it on scline!](https://scline.fly.dev/#H4sIAM2vWmUCAx2MMQqAQBADe1.RUkGWO9gFg2Bla2GtFoKtYOP_ddNMhkCyuZEIKyURqCXVqUKedDGSVV4DpA0uyilnPmj2R.ZhTYvrfbCPWNGjw30.mDEtH5MqRc56AAAA#H4sIAM2vWmUCA0spLdAz1DKtMTTQSVBQ0zc0MNBSqKkDUvoAuFXTaxoAAAA#)
sclin's default real/rational number representation comes in handy here.
## Explanation
Prettified code:
```
dup .1* 5| 10,` &/ 100* |~ 100/
```
Assuming input *n*:
* `dup .1*` *n* \* .1
* `5|` min with 5
* `10,` &/` min with 10 and *n*
* `100* |~ 100/` round 2 decimal places
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes
```
#~Min~Max[.1#,5]~Min~10~Round~.01&@x
```
Alas, we cannot save an extra byte by using infix notation with `Max` because multiplication has a lower precedence than passing an argument, so `.1#~Max~5` is equivalent to `.1(#~Max~t)`, rather than `(.1#)~Max~t`.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78X2FraalnYcJVYPtfuc43M6/ON7EiWs9QWcc0Fsw1NKgLyi/NS6nTMzBUc6j4H1CUmVfiUPAfAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 44 bytes
```
x->printf("%.2f",min(x,min(max(x/10,5),10)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY5BCsIwEEWvMgSECaQxkQQ6iL2IiHQTKdgSSoV4FjcFEXfex9vYZkrBzbx5f_ghj3es--Z8ieMzwOF1G0JRflUqqtg33RBQbPQuCNU2HaY82zph2lqjvFTWSCmXzqeO8XrHBEUF_11Ics-RRTGfxeQB1xSlgqPTRAq8NiZPr8CaLI44Myscw2dYNjsZkS4dg43YKD_G_Ynzclp-PY7MHw)
A port of [@Evargalo's R answer](https://codegolf.stackexchange.com/a/266912/9288).
Prints the result to stdout.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 (or 25) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
T/5‚à‚Tªß4°z+2.ò
```
[Try it online](https://tio.run/##yy9OTMpM/f8/RN/0UcOswwuARMihVYfnmxzaUKVtpHd40///pgZ6hqYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/xB900cNsw4vABIhh1Ydnm9yaEOVtpHe4U3/df5Hm@hZWuqY6hkYgAhTHUMDENPEEixgACNNwKQpiDQEsw1NdSwt9SxMwCSYbQlmW4JMAGsDUiA6FgA).
This outputs `5.0` or `10.0` instead of `5.00` or `10.00`, like most other answers. To fix this, the following 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) can be added:
```
т+0«6∍¦0Û
```
[Try it online](https://tio.run/##yy9OTMpM/f8/RN/0UcOswwuARMihVYfnmxzaUKVtpHd408UmbYNDq80edfQeWmZwePb//5aWepamAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/xB900cNsw4vABIhh1Ydnm9yaEOVtpHe4U0Xm7QNDq02e9TRe2iZweHZ/3X@R5voWVrqmOoZGIAIUx1DAxDTxBIsYAAjTcCkKYg0BLMNTXUsLfUsTMAkmG0JZluCTABrA1IgOhYA).
**Explanation:**
```
T/ # Divide the (implicit) input by 10
5‚ # Pair it with 5
à # Pop and push the maximum of the pair
‚ # Pair it with the (implicit) input
Tª # Append 10 to this pair
ß # Pop and push the minimum of this triplet
4° # Push 10**4: 10000
z # Pop and push 1/10000: 0.0001
+ # Add it to the value
2.ò # Then (banker's) round it to 2 decimals
т+ # Add 100
0« # Append a trailing 0
6∍ # Shorten it to length 6
¦ # Remove the leading 1
0Û # Trim any leading 0s
# (after which the result is output implicitly)
```
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 48 bytes
```
{y=$0/10;a=y>5?y>10?10:y:5>$0?$0:5;print a+1e-4}
```
[Try it online!](https://tio.run/##NYzBCoJAFEX3fsVgtoqm92Ie9BRHKCxcpJL2AS4KIoiIIAbx26fmQZtzDxfuHT53vy0PVT02@2Ofx3O9vsaTmqmu7M@tak/lruqqpvajyxNYIWRD7iwVziIUCKlLySZQJJBS9nzdHm81LPCyNJP3RjNHpAECKEIIalgK@NMIKRDFkSJmvTFCcRbn8CCzX4T8Ag "AWK – Try It Online")
---
Ungolfed :
```
BEGIN{
OFMT = "%.2f"
}
func min(n,m){
return m>n?n:m
}
func max(p,q){
return p>q?p:q
}
{
x=min($0,min(max(0.1*$0,5),10))+0.0001
print $1, "->", x
}
```
[Answer]
# [Scala 3](https://www.scala-lang.org/), ~~106~~ 100 bytes
Saved 6 bytes thanks to @corvus\_192
---
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=bZCxasMwFEXp0MVf8cgkUVuVHMtODA60ZM3S0ClkUGzZuDiSa8utQ8mXdMnSLvmi9Gsq8FCo85YHh_vuvbzP7zYVlZieNxNP6XfRqMn2gvXuRaYGVqJU8OE48CYqyGNAS93tKpksho0h-epM7s0uWZ8sHstiKdNyLyq0lq-od7nLqNvfM4pJqxsjMyLqujoghu-Y9EJLpVnbcIl89--YPOlOZaUqVjqTKMCYGD3EDVk_N7cAmcxhb8sh0RRtDA9NIw6btWns2RbH8KxKA4ltDnZqS02lUI7mFON_yGdjxsIRCojPRpATyseGnLCrNOTB9IpJNBZHnMxnkdWPm1E61D06x-Ebp9OwfwE)
```
x=>BigDecimal(Seq(x,5,10,x/10).sorted.apply(1)+1e-6).setScale(2,BigDecimal.RoundingMode(4)).toDouble
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=bZHNSsNAFEZxm6e4dDXBZJxJO0lbcFEp4qIFsXRVikyTSYikM5JMNCJ5Ejfd1I2P4Vv4NI5N_MF0dYcz33c5cF9ei5BnvP-26rlSPfJc9ta7faljd_hx8q42dyLUMOephGcLIBIxxKgaw1SVm0zY3w84P3wDPPAMCpVrEc3SQhv8NVDlAHOAEgeqM0ps3CQOhYs0mYow3fIM_fYQteEUqHB9kxV6YQwF8pw_YXyjShmlMpmrSOCryezydnltY60aH7O6tlrfrZFHPE-KMUzynD-tFjo3xbWRX8pU_6jfG6oziWI0Irb9D3m0y6jfQQPs0Q5kmLDuQobpUeqzQf_IkqAbDhgeDQOT75oR0ujWVt3csj3prp2f)
```
object Main {
def f(x: Double): Double = {
val sortedList = List(x, 5, 10, x/10).sorted
BigDecimal(sortedList(1) + 1e-6).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble
}
def main(args: Array[String]): Unit = {
println(f(90))
println(f(210))
println(f(16))
println(f(4.21))
println(f(5.05))
println(f(25.15))
println(f(25.654321))
println(f(75))
println(f(75.987654))
println(f(1000))
}
}
```
[Answer]
# [Rust](https://www.rust-lang.org/), 50 bytes
```
|x|(500f64.max(1e1*x).min(1e3).round()/1e2).min(x)
```
[Try it online!](https://tio.run/##jZJRb5swFIXf8ytcHipTpR6ksBVvidSXSdNa9WHSNGmaKpJcWmvGQcZu0Ci/PbvgOKVoD@MBX30@59xrg7a1OVR2TQpFylwoGpLLFcF3OyP4SDDkmSzJ4aV5oWkUFe8TVuYNjSG@aEJWoiGGq5DpnVVbGr6LYeFoEx4@nhJqsxUKU3DlXOw4HwANXxWlNWRtiwI0yr4ZLdQj5wr2XrN/EhIG5f1vGjO2HKJsLf4A53c3P0KXLhTTkG8fpFBAz19D/XF8u34fHW6TYbvSN/KKKtem5uQ7bD49rFDaO1hdSWFocLkKQrbZSQkbM/adClEMGT/z@foXes8vhrTRDL6LUJU1nOCtoiw/DsJQXQOuVu11Xo07eB80FfaGrbeu/9@qobbSoOeZDt0nkgqv3kh1RoOWf2CLrv8bWp6yCMu2C@Zu5PkxZt4f1Q9Dlkuf3gb3X4OOgKwB6883X27Pgm7UqTtVx0@wkZBrP2436w6EJCzLSN9@qHADh4gc6CsH0jcgjnrJCCTZBKTRP0AyBakHsQNxMgUnxQJBlrFrp8hYdn0EqQeZA1kyBYNiGHmGix/MnWGG4A35Cw "Rust – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
NθI⌊⟦θχ⌈⟦⁵∕⌊⁺·⁵×θχ¹⁰⁰
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMM3My8ztzRXI7pQR8HQQEfBN7ECwjfVUXDJLMtMSdVwy8nPL9IIyCkt1jDQAwqHZOamFmuA1WtqaoIoA81YINS0/v/fzETP2PS/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of the formula given in the question, but with rounding as required. I checked all inputs from `50.00` to `99.99` and none of them had any rounding errors; even though for example `64.35*100` does not result in `6435`, `64.35*10` does result in `643.5`, which is then rounded to `644`, with a final result of `6.44`.
```
Nθ First input as a number
θ First input
× Multiplied by
χ Literal integer `10`
⁺ Plus
·⁵ Literal number `0.5`
⌊ Floor
∕ Divided by
¹⁰⁰ Literal integer `100`
⁵ Literal integer `5`
⟦ Make into list
⌈ Take the maximum
χ Predefined variable `10`
θ Input number
⟦ Make into list
⌊ Take the minimum
I Cast to string
Implicitly print
```
Formatted to two decimal places also turns out to be 21 bytes:
```
Nθ﹪%.2f⌊⟦θχ⌈⟦⁵∕θ⁹·⁹⁹⁹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDNz@lNCdfQ0lVzyhNSUfBNzMvM7c0VyO6UEfB0ADIT6yA8E11FFwyyzJTUjWAMpZ6lpaWmrFAqGn9/7@ZpZ6BwX/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @PattuX's observation that dividing by `9.999` before rounding suffices to compensate for floating-point errors.
[Answer]
# [\*><>](https://github.com/redstarcoder/go-starfish), ~~90~~ 89 bytes
-1 byte by removing a semicolon that shouldn't have been there
I'm still trying to condense it using the dive `u` and rise `O` instructions, but in case I forget, here's a working version without them.
Requires running with the `-i` flag to receive input.
```
:5)?!\:5a*)?!\:9b*(?!\aa*:}*:a%:4)?v- >$a*,n;
;n/ ;n5/ ;na/ \a$-+/
```
## Explanation
### x ≤ 5
```
:5)?!\
;n/
```
```
: Duplicate the input
5 Push 5 onto the stack
) Evaluate 5 > input
?!\ If true, redirect down
/ Redirect left
;n Print the input, and halt execution
```
### 5 ≤ x ≤ 50
```
:5a*)?!\
;n5/
```
```
: Duplicate the input again
5 Push 5 onto the stack
a Push 10 onto the stack
* Multiply the top to values, thus putting 50 onto the stack
) Evaluate 50 > input
?!\ If true, redirect down
/ Redirect left
;n5 Push 5 onto the stack, print it, and halt execution
```
### 100 ≤ x
```
:aa*(?!\
;na/
```
```
: Duplicate the input
aa* Multiply 10by 10, putting 100 onto the stack
( Evaluate 100 < input
?!\ If true, redirect down
/ Redirect left
;na Push 10 onto the stack, print it, and halt execution
```
### 50 ≤ x ≤ 100
In order to get half-up rounding, we multiply the input by 100 to make it an integer. From there we then round up/down to the nearest 10, and then divide by 1000 to get our final amount.
```
aa*:}*:a%:4)?v- >$a*,n;
\a$-+/
```
```
aa* Push 100 onto the stack
: Duplicate the 100 on the stack
} Shift the stack to the right, moving the duplicated 100 to the 0th index
* Multiply the input by 100, replacing future instances of "input" with "input * 100"
: Duplicate the input
a Push 10 onto the stack
% Push input modulo 10 onto the stack
: Duplicate that value
4 Push 4 onto the stack
) Evaluate (input modulo 10) > 4
?v If (input modulo 10) > 4 == true, redirect down
// If (input modulo 10) > 4 == true
\ Redirect right
a Push 10 onto the stack
$ Swap the top two values on the stack
- Subtract (input module 10) from 10
+ Add that to the input
/ Redirect up
// If (input modulo 10) > 4 == false
- Else, subtract (input module 10) from input
// After conditional
> Force instruction pointer to the right
$ Swap the two values on the stack, making it [input, 100]
a* Multiply the top value by 10, pushing 1000 onto the stack
, Divide the input by 1000
n; Print the value and halt execution
```
[Try it online!](https://tio.run/##Ky5JLErLLM74/9/KVNNeMcbKNFELTFsmaWkA6cRELataLatEVSsTTfsyXQUFBTuVRC2dPGsuINM6T18BTJlC6UQwDQcxiSq62vrW////yy8oyczPK/6vm/nf1EjP2BQA "*><> – Try It Online")
[Answer]
# [Uiua](https://uiua.org) 0.3.1, 16 [bytes](https://codegolf.stackexchange.com/questions/247669/i-want-8-bits-for-every-character/265917#265917)
```
↧↧↥5⍜×⁅100⊃÷∘10.
```
[See it in action](https://uiua.org/pad?src=0_3_1__R1BQIOKGkCDihqfihqfihqU14o2cw5figYUxMDDiioPDt-KImDEwLgoKR1BQIDQuOTkgICMgNC45OQpHUFAgNSAgICAgIyA1CkdQUCA1LjA1ICAjIDUKR1BQIDEwICAgICMgNQpHUFAgNDkgICAgIyA1CkdQUCA1MCAgICAjIDUKR1BQIDUwLjA0ICMgNQpHUFAgNTAuMDUgIyA1LjAxCkdQUCA1MC4xNCAjIDUuMDEKR1BQIDUwLjE1ICMgNS4wMQpHUFAgOTkuODQgIyA5Ljk4CkdQUCA5OS44NSAjIDkuOTkKR1BQIDk5Ljk0ICMgOS45OQpHUFAgOTkuOTUgIyAxMApHUFAgMTAwICAgIyAxMApHUFAgMTAwMCAgIyAxMAo=)
[Answer]
# [Desmos](https://desmos.com/calculator), ~~30~~ actually 35 bytes
A one-liner Desmos equation for once (thanks to Aiden Chow for the fix and optimization):
```
f(x)=round([x,5,10,x/10].sort[2],2)
```
[Try it on Desmos!](https://www.desmos.com/calculator/ugiaae4h9h)
] |
[Question]
[
The challenge is simple: write a program which takes in some non-empty string \$n\$ consisting of only uppercase and lowercase ASCII letters, and outputs the *code* for a program (in the same language) which takes in no input and outputs \$n\$. However, the code your program generates *must not contain \$n\$ as a substring*. For example, if your program was in Python, if the input was `"rin"`, your output could not be `print("rin")`, because that contains the string `rin` (twice). One valid output would be, for example, `x=lambda:'r\151n'`.
Some notes:
* Uppercase and lowercase characters are treated as distinct -- e.g. if the input string contains `A`, your generated code can still contain the character `a`.
* Your generated code follows the same restrictions as a standard code golf answer -- e.g. it can be code which defines an anonymous function returning the string, but it cannot work by saving the string into a variable.
* Your submission is scored by the length of the *generating* code, not the *generated* code. In addition, there are no restrictions on the source of the generating program, only the generated.
Standard loopholes are forbidden. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest program wins.
[Answer]
# [Python](https://www.python.org), ~~54~~ 45 bytes
```
lambda x:f'ÔΩÖ‚Ö∫ÔΩî("\%o{x[1:]}")'%ord(x[0])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3dXMSc5NSEhUqrNLU3-9tfdS66_3eKRpKMar51RXRhlaxtUqa6qr5RSkaFdEGsZpQTUoFRZl5JRppGkoZqTk5-UqamlypFanJIIHy_KKcFKAAROWCBRAaAA)
Python lambda that returns a string that has a full Python program to print the string (on stderr). Used full-width characters (which are non-ASCII and so won’t appear in the input). Inspired by [@UnrelatedString’s answer](https://codegolf.stackexchange.com/a/266368/42248) to a different question.
*Thanks to @ShadowRanger for saving two bytes, @JonathanAllan for saving a further four and @dingledooper for three more again!*
# [R](https://www.r-project.org), 66 bytes
```
\(x,s=substring)sprintf('\\()"\\%o%s"',utf8ToInt(s(x,1,1)),s(x,2))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY2xCgIxEER7v-JYOG4XInhW16Sx09oyTZREhZA7snty_2ITBT_KvzGHClYzDDNvbveUH14_R_HL7rUxOCnWPB5Y0iWeiIci4rExBgmMqfuaoVGl3e37bRTkMmhVS6Rmtyb6knZHK-gRzi6EHkiBiUCLOXRXG3CwiR2Km0QPlsWtEBBU9TeogMoj0Y-Y80ff)
Equivalent program in R (but returns an anonymous function)
[Answer]
# Google Sheets, ~~37~~ ~~50~~ ~~47~~ 41 bytes
`="=—Å–∏–º–≤–æ–ª("&code(A1)&")&"""&mid(A1,2,9^9)`
Put the input in cell `A1` and the formula in `B1`.
The formula assumes that the input string \$n\$ consists of uppercase and lowercase *Latin* letters only.
When the input is `rin`, the formula outputs `=—Å–∏–º–≤–æ–ª(114)&"in` which is a valid formula in Google Sheets in any locale, including Latin locales such as United States. When the output is evaluated as formula, its result is `rin`.
Given a single letter such as `A`, the formula outputs `=—Å–∏–º–≤–æ–ª(65)&"` which gives the result `A`.
The formula defends against substrings being part of the output code by not including any Latin letters in the output except those found in input. The first letter is "escaped" by using the equivalent of the `char()` function in Cyrillic, `—Å–∏–º–≤–æ–ª()`, whose name doesn't match any Latin letters (`console.log('—Å–∏–º–≤–æ–ª'.match(/\w/))` ‚Üí `null`).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~38~~ ~~31~~ 29 bytes
```
->n{"$>.<<''<<"+n.bytes*'<<'}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhZ7de3yqpVU7PRsbNTVbWyUtPP0kipLUou1gBz1WqiagtKSYoW0aCWgeIlSLFdqWWIOggtRs2ABhAYA)
Generates string in such a way that it never contains any letters.
-7 bytes from Value Ink and another -2 from ShadowRanger.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~95~~ 63 bytes
*-32 bytes thanks to [@emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a)*
```
--[>+<++++++]>[->+>+<<]>+++>>----[>+<----]>-<,[[-<.>]<<.>>>.<,]
```
[Try it online!](https://tio.run/##JYlLCoAwDEQP1E5PEGbtDVyELPyCGCwUPH@sOov3eMzcpuPa7@WMAJRJ0jejgqmnGHuSwH@/NkKyKqTQpIMski1i2NzrWJuvDw "brainfuck – Try It Online")
Essentially an ultra basic constant string generator. For each character code, outputs `+.[-]` where the `+` is repeated a number of times equal to the byte value of the input.
### With Comments
```
--[>+<++++++]> Load a PLUS
[->+>+<<] Copy it twice
>+++> Change the other to a DOT
>----[>+<----]>- Load a RIGHT ANGLE BRACKET
<,[ Main loop WHILE NOT EOF
[-<.>] Output a plus to increment the accumulator by one
<<.>>>.< Output a DOT followed by a RIGHT ANGLE BRACKET
,] Repeat
```
[Answer]
# [Zsh](https://www.zsh.org/), 28 bytes
```
<<<'<<<${(#):-'$[#1]\}${1:1}
```
[Try it online!](https://tio.run/##qyrO@J@empdalFiSX6ShqfHfxsZGHYhVqjWUNa101VWilQ1jY2pVqg2tDGv/a3LB1SokJiWncKWWJeYoJKAKJvwHAA "Zsh – Try It Online")
Similar idea to others, convert the first character to its character code, then `${(#):-NUM}` converts it back when evaluated.
[Answer]
# [Julia 1.0](http://julialang.org/), 40 bytes
```
!s="_->"*join("*('@'+$(i-'@'))" for i=s)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/X7HYVile105JKys/M09DSUtD3UFdW0UjUxdIa2oqKaTlFylk2hZr/i9WsFVQcnRydklMSk5R4iooyswrycnTKNaEMxWB7DSgqtSyxBwN39SSRL2CxKLiVJA4QlGahoGm5n8A "Julia 1.0 – Try It Online")
builds an anonymous function that concats (`*` in julia) chars together be adding to `'@'` eg `'A'==('@'+1)` without using any letters
for example: `ABC` => `_->*('@'+1)*('@'+2)*('@'+3)`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes
```
OṾ”Ọ
```
[Try it online!](https://tio.run/##y0rNyan8/9//4c59jxrmPtzd8///f@f8lFT3/Jw0AA "Jelly – Try It Online")
A full program that takes a string and prints a Jelly niladic link that outputs the string.
*Thanks to @JonathanAllan for saving a byte!*
## Explanation
```
O | Codepoints
·πæ | Uneval (and implicitly print)
”Ọ | an "Ọ" (implicitly printed)
```
[Answer]
# [Uiua](https://uiua.org), ~~13~~ 10 bytes
```
&p"-1"&s+1
```
[Try it online!](https://www.uiua.org/pad?src=JnAiLTEiJnMrMSAiaGVsbG8gd29ybGQiCg==)
(3 bytes saved by using `&s`)
## Explanation
Simply encodes the string by incrementing all codepoints and decrementing in the output program
```
+1 # increment all codepoints
&s # pretty-print (includes quotes)
&p"-1" # print -1
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes
```
FS⁺´℅´I℅ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLQkuKQoMy9dQ1NTIQDIKNEIyCkt1lB61NL6fs9KJR0F/6KUzLzEHI1MTU1N6///nWEm6JblAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Prints a list of code points and commands to convert them back into characters. Sample generated program: [Try it online!](https://tio.run/##S85ILErOT8z5//9RS@v7PSvNzCG0oYEJhGEJEzCECVjCBAzRVBhY/P8PAA "Charcoal – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 33 bytes
```
-:&'u'{'117{a."_',:~'u:@',3":@u:]
```
[Try it online!](https://tio.run/##VYzBCoJAFEX3fsXDRTdhFKVF8EQQgtoEQSshIqaayaJUppmV4K9PRhC4uIt7OJyHDxNoKphAglLicXFCq/127WOewaFHli17mYQnCB7guIRYhFw6PvoosOpti0TnBx47cwhEKcSgA3WpW8JGNcpIq67UmfZm5As5ds52zlKr/@wnf0sEc28m//yUdVVVE@bgPw "J – Try It Online")
A function which outputs the source code of a function which outputs the original input. Since in J no-argument functions don't exist, we call the outputted function with a dummy argument `0` which is ignored.
Probably a better approach out there, but this idea is:
* Return a function which uses "Unicode" `u:` to translate the code points of the original input back to unicode: `u:@<literal list of code points>`.
* Everything is non-letter in that code except for `u`, so that's the one input we need to defend against. So for that specific case we return a function which returns the 117th letter of the J alphabet `a.`, which is also `u` but whose code does not contain `u`: `117{a."_`.
# BQN, 19 bytes
```
""""∾˜"-⟜1∘"""∾+⟜1
```
[BQN Online](https://mlochbaum.github.io/BQN/try.html#code=RuKGkCIiIiLiiL7LnCIt4p+cMeKImCIiIuKIvivin5wxCuKAokJRTiAiKCLiiL4oRiAieGFiYyIp4oi+IikwIg==)
Bonus my first BQN answer, using a similar code point shift approach as [Pseudo Nym's Uiua answer](https://codegolf.stackexchange.com/a/266616/15469).
Perhaps there is a better way to escape quotes?
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~57~~ 52 bytes
*-5 bytes thanks to [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)*
There was a shorter way
```
s=>`_=>"\\${s.charCodeAt().toString(8)+s.slice(1)}"`
```
The smallest representable Octal letter is `A` at `101`, which means we don't actually need to pad this.
[Try it online!](https://tio.run/##ZYyxCoMwFEX3fsUjdEhoG@gmSIRS@gUda6khjRp5GMkLLuK3p5GOTgfO4d5Bz5pMcFO8zEVqVSJVNR9Vsbo@LiRNr8Pdf@0tciGjf8bgxo4X4kSS0BnLr2JlTSpfwHqL6NkZ2BTcBvK4YWRv2frw0KbnBKqC5QCANoLJt6Cg5STKrIwf88JK9B3f0k7aWeO/cLGLWayiTD8 "JavaScript (V8) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 39 bytes
```
T`Ll`lL
$
¶T`?-[_-{`_-{?-[
^t¶T
t¶Y
^
¶
```
[Try it online!](https://tio.run/##K0otycxLNPz/PyTBJychx4dLhevQtpAEe93oeN3qBCAGsrjiSoBiXEAikisOKP3/fxBYFwA "Retina – Try It Online") Explanation: Toggles the case of the input, then appends a command to toggle the case back. This command is normally `T`, but in the event that the input was `T`, uses the `Y` command instead, which has the same effect on a single character. Sample generated program: [Try it online!](https://tio.run/##K0otycxLNPz/n6vINcTTz5ErJMFeNzpetzoBiIGs//8B "Retina – Try It Online")
[Answer]
# [Python](https://www.python.org), 67 bytes
```
lambda s:[p:="print","lambda:"][s in p]+f"('\%o{s[1:]}')"%ord(s[0])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXMSc5NSEhWKraILrGyVCooy80qUdJQgolZKsdHFCpl5CgWx2mlKGuoxqvnVxdGGVrG16ppKqvlFKRrF0QaxmlCjVoI1a6RpKCUqaWpywXlAGoUPMRtFyCM1JydfITy_KCcFIQ6j1WMMTQzVYTwFDajbQOJmRpl56pqaChqaCkiqTU3AKtSRhAwNEDaoQx28YAGEBgA)
## Explanation
```
# if the input is a sub-string of print create a lambda function
# otherwise create a print statement
[p:="print","lambda:"][s in p]
# replace first character to octal escape sequence
f"('\%o{s[1:]}')"%ord(s[0])
```
A string cannot be a sub-string of both `print` and `lambda:` so the input is not contained in the first half.
By replacing the first character with a number it is guaranteed that the string is not a sub-string of the second half (the string contains only letters).
Both parts are separated by `(` which is guaranteed to not be in the input
---
# [Python](https://www.python.org), 87 bytes (ASCII only)
*can handle empty string*
```
lambda s:[l:="lambda:","print"][s in l]+"('%s')"%f"\%o{s[1:]}"%ord(s[0])if len(s)else""
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY9BCoJAGIX3nWL4QWZ-KtCwCMF9N3AxujB0SJhmxLFFRCdpI0Qdobt0m8rR1NXjezze__7bszzXB62auwjjx6kWy-07kulxn6XEBFwGIVgKYAFlVagaEm5IoYhM5sCoYyiCIyB29MVwL0iu4OgqY4a7CRaCyFwxg7k0OUBX_2prmGAAiLM_pBP66oTtiIm1y6XUJNKVzAa_Vxp7vkd7Iqx74udvVoWiiIQhGaXXfpugI8tzhwsU7fqmsfoB)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~30~~ 107 bytes (PS 5/6), 91 bytes (PS 7)
The first attempt, as @nick-kennedy correctly pointed out, didn't account for single character strings.
**PowerShell 5/6**
```
%{If($_[1]){"'$(($_|% T*y)-join"'+'")'"}Else{"[$(If('char'|% Con* $_){'CHAR'}Else{'char'})]$(1*[char]$_)"}}
```
Input comes from the pipeline
[Try it online!](https://tio.run/##ZY/LTsMwEEXX5CtGlivbCUZ0W4REiQLtFpBYRFEVEkMNqR3ZLhSl@fZgN4uA2Nx5nauZafWXMHYrmmbATlhXlVZYuAay8i0Nz9o0NTkHUm1LE2IZZBnkJcgtiXCl65Pll/84zLr1K8WbfF6wDhFMfX6cwVP8zfi7lgqRhCBGUJ81VnQox9Tj4xKPpVrFgDesI@lq@UBGaJz2rMB0HuehKDyC@n640wYolv6EyyvwkTcObuh0DrtI9V65MEsSBl10hh6dkeoNpGr3bgEAmP4x5FgWDHnuXihhSidqCF8uRu708MRkB1HtJ8Qza/WpPwTPDq0R1kqtgKd6tytVDf/shHMS9cMP "PowerShell – Try It Online")
**PowerShell 7**
PowerShell 7 (TIO is still on PS6) supports the ternary operator "?:", which allows to get rid of the two If/Else:
```
%{($_[1])?"'$(($_|% T*y)-join"'+'")'":"[$(('char'|% Con* $_)?'CHAR':'char')]$(1*[char]$_)"}
```
* If the input is longer than 1 character: Breaks the input string into single characters and generates code to add them back together: `'r'+'i'+'n'`
* If the input is only one character: Casts the codepoint using either [char] or [CHAR], depending on the case of the character: `[char]65` or `[CHAR]97`.
Output in PowerShell is implicit.
**Ungolfed:**
```
ForEach-Object { # Takes input from the pipeline
If ($_.Length -gt 1) {
# $(...) is a subexpression which will be evaluated inside a string enclosed in double quotes
# Turn the string to an array of characters, then join them back with the literal '+'
"'$(($_ | ForEach-Object -MemberName ToCharArray) -join "'+'")'"
} Else { # single char
# If the character is one of the critical chars (used to cast) is in lowercase, use uppercase for the [char] cast
# 1*[char]$_: Multiplying an integer with a character will return the codepoint; shorter than [int][char]$_
"[$(If ('char'.Contains($_)) {'CHAR'} Else {'char'})]$(1*[char]$_)"
}
}
```
Test it in PowerShell 7 (can be pasted into a PS7 console):
```
$testcases = 'Hello World', 'char', 'a', 'A', 'b', 'B'
$codes = $testcases |
%{($_[1])?"'$(($_|% T*y)-join"'+'")'":"[$(('char'|% Con* $_)?'CHAR':'char')]$(1*[char]$_)"}
For ($i = 0; $i -lt @($testcases).Count; $i++) {
"String input: $(@($testcases)[$i])"
"Generated code: $(@($codes)[$i])"
"Executed code: $(Invoke-Expression -Command @($codes)[$i])"
'--'
}
```
[Answer]
# [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 28 bytes
```
'"\\%s"'%(byte(s)..sub(s,2))
```
[Try it online!](https://tio.run/##SyxKykn9/19dKSZGtVhJXVUjqbIkVaNYU0@vuDRJo1jHSFPz////Sh6pOTn54flFOSlKAA "ARBLE – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 96 bytes
*-3 thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)*
*-6 thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
I overlooked the rule allowing anonymous functions, so this generates a full program using either `print` or `console.log` with extra precaution for `n` which is present in both instructions.
```
s=>`${S="print",S.match(s)?'co\\u006esole.log':S}("\\${s.charCodeAt().toString(8)+s.slice(1)}")`
```
[Try it online!](https://tio.run/##TY7NCsIwEITvPsUSCk2whnoRsaQi4hPkaIWGmP5IbEoTeyl99poIoqdhv92dmYcYhZVD27vNuF8qtliWl9HEGeqHtnMo4fQpnGywJcdYmqJ4pelOWaMV1aaOD3zGqCiiyVLZiOFs7urkMKHOcOf/a7wna0utbqXCWzIjUi7ZFVCjtDYogRASxPsF6RDcaGWGiwiBwHKYVgBaOZDeGBhUvkbmkTTdtwIOqw9Uo9C/6f/Eg5lkyxs "JavaScript (V8) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ç„)ç)»
```
Output of the output program is a list of characters.
[Try it online.](https://tio.run/##yy9OTMpM/f//cPujhnmah5drHtr9/79zfkqqe35OmmNeCojpnJGYk5Oal55aDAA)
[Try the outputted program.](https://tio.run/##yy9OTMpM/f/fzFzB0NBQwdDAAIgNFcwNoVwLIDZSMDMFcg3AsmgKQVwDEwVLc6haC7AoRLExlG3KpXl4Odf//wA)
**Explanation:**
```
Ç # Convert the (implicit) input-string to a list of codepoint-integers
„)ç # Push string ")ç"
) # Wrap all values on the stack into a list
» # Join the inner list by spaces and then the strings by newline
# (after which the result is output implicitly with trailing newline)
```
Minor note: the second `)` cannot be the more straight-forward `‚` (pair) nor `ª` (append to list), because [`„)ç‚`](https://tio.run/##yy9OTMpM/f//UcM8zcPLHzXM@v8fAA) and [`„)çª`](https://tio.run/##yy9OTMpM/f//UcM8zcPLD636/x8A) would be interpret as [dictionary words](https://codegolf.stackexchange.com/a/166851/52210) `") reservoir"` and `") baghdad"` respectively.
] |
[Question]
[
**This question already has answers here**:
[Golfing Advent of Code 2020, Day 3](/questions/217219/golfing-advent-of-code-2020-day-3)
(11 answers)
Closed 2 years ago.
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
Related to [AoC2020 Day 3](https://adventofcode.com/2020/day/3).
---
On the way to vacation, you're traveling through a forest on an airplane. For some biological and geological reasons, the trees in this forest grow only at the exact integer coordinates on a grid, and the entire forest repeats itself infinitely to the right. For example, if the map (input) looks like this (`#` for trees and `.` for empty spaces):
```
..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#
```
the forest actually looks like this:
```
..##.........##.........##.........##.........##.........##....... --->
#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..
.#....#..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#.
..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#
.#...##..#..#...##..#..#...##..#..#...##..#..#...##..#..#...##..#.
..#.##.......#.##.......#.##.......#.##.......#.##.......#.##..... --->
.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#
.#........#.#........#.#........#.#........#.#........#.#........#
#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...
#...##....##...##....##...##....##...##....##...##....##...##....#
.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.# --->
```
Starting at the top-left corner of this forest and moving at a rational slope (e.g. `3/2` represents two units to the right and 3 units down), how many trees will you encounter until you escape the forest through the bottom row? (You encounter a tree if your path goes through the exact integer coordinates of that tree.)
**Input:** A rectangular grid representing the map, and a rational number (non-zero, non-infinity) representing the slope of your movement. You can use any two distinct values (numbers/chars) to represent trees and empty spaces respectively. You can take two positive integers for the slope instead of a rational number, and the two numbers are guaranteed to be coprime.
**Output:** The number of trees you will encounter during the flight.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
Grid:
.##
#.#
##.
down/right -> trees
1/1 -> 0
99/1 -> 0
2/1 -> 1
2/3 -> 1
1/2 -> 2
1/3 -> 2
1/99 -> 2
Grid:
##.#
.###
##..
..##
down/right -> trees
1/1 -> 3
1/2 -> 4
1/3 -> 2
2/3 -> 1
3/4 -> 1
Grid: (the one shown at the top)
down/right -> trees
1/1 -> 2
1/3 -> 7
1/5 -> 3
1/7 -> 4
2/1 -> 2
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 51 bytes
```
(a,x,y)=>a.map((r,i)=>t+=r[i*x/y%r.length]|0,t=0)|t
```
[Try it online!](https://tio.run/##pZPdaoMwFIDvfYpzM0i2TBPtKG64FxEvQmutw2mxYWtp@@wuwaLiYhIo5CInfpyfj@MX/@HHTVsexGvdbPNul3SIkxM54@ST@9/8gFBLShmIl6RNy@dTcH5q/SqvC7HPrpSIhOKr6H5LsQd0gaItt@@QegApJcDkyYgK5I1OAxXLILthuMinTVMfmyr3q6ZAO6SSEFAMMIwhCIAamDi2MxD2DFtiIgcmHPsJTXksTBwvM/jDu3meRuZd2aDwLneutLfafx/9u1qOHCZfPTC5k2XFrPTMop1x2t7B7ExXcEDn96lXqkPZf7naTEybiblkYtrGZ7Xm/S01roG0hZjZk72cXoFp6VRa86pEA7FeIN6IbW3XxLa0so/Q8CN2fw "JavaScript (Node.js) – Try It Online")
Input an 2d 0/1 array where 1 means tree, and step x, y.
Use the fact that you can index an array with non-integer value without causing errors in JavaScript. You will get non-harmful `undefined` which may be convert to `0` safely by any bitwise operator. And as you are keeping moving south, you may only encounter at most 1 tree each row. So we just sum all tree encountered each row. And that's all we need to make it working.
[Answer]
# [Whython](https://github.com/pxeger/whython), ~~59~~ 57 bytes
```
f=lambda F,a,b,x=0:F[a-1][x%len(F[0])]+f(F[a:],a,b,x+b)?0
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVFLasMwEKVbncJIFCyiCLtZtDGIZOVLKFrINP6AqhjbIc5Zusmm9EzNaSp57Ma4ghnePN680Uif35fy2pUne7t9nbt8_fazzYXRH9m7DlKmWcZ6ESWp1OtYyf7ZHG2YykhRtcod0IkCzSqjuwgM7k_7YnJoEyl7ITDB-akJ-qCygVEeGg9b3tam6kxlj21IFaqbynah801EEWKMD4gTggh3QThyBGUxiyl9CNnLoo7ZZl4_jJwTh4M8GAMNwCc3wCfgCfBkxkM3GiTQM_YCHhXkz3-mmTzHBTaLC7_-XwgecvqRXw)
Inputs a 2D array of booleans, and 2 integers.
## Normal Python, 69 bytes
```
f=lambda F,a,b,x=0:F[a-1:]>[]and F[a-1][x%len(F[0])]+f(F[a:],a,b,x+b)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVHRasMgFKWvfoUog0itNM3DiuDoy_IT1gdDmy5gbWgySL9lL33Z_mn7mmpusoZWuHLu4ZyjV79-6kv7cfLX6_dnWy7Wv--lcvZY7CzOueUF79RS5touUmnetLF-h_vO6O7F7X2S66VhZl4GYKUBx7xgEPY32xzGtEZq3SlFKClPZ9zhymNnInQRNqKpXdW6yu-bhBlUnyvfJiFVqkNCCNkiQSmiIhQVKBCMpzxl7C7kq4c-5dm0vweFJAELRTAU6kHcwgFxA54CTyc8uFEvAc_gBTwo6H_-RDNmDgNkDxd-fR4IHnL8nRs)
[Answer]
# Haskell, 60 bytes
```
f g a b=sum[cycle(g!!(a*t))!!(b*t)|t<-[0..div(length g-1)a]]
```
[Try it Online!](https://tio.run/##JYhBCoMwFAWv8twlJUpCu6wn@fxFtDGGxlBqLBS8e0wtD94MM9v16WIsZYKHxdCv20Ljd4xO@KYR9pKlrBwq93xvSXfdI3xEdMnnGb410jKXxYaEHq93SBliApFRRmllWFH936r9mz7bWZlxxU2WAw)
Takes input as a list of lists, followed by the down and right numbers. Trees are represented as 1s, blanks spaces are represented by 0s.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) (Avoid multi-link chaining by getting the m-slice result again when needed.)
```
mJ’×⁵‘ị"mS
```
A full program accepting a list of lists of `1`s (trees) and `0`s (clearings), the Down amount, and the Right amount that prints the result.
**[Try it online!](https://tio.run/##y0rNyan8/z/X61HDzMPTHzVufdQw4@HubqXc4P8Pd2/xf7ij6fDy///19JSV9SCAC8SAYi4wA0QoA9lAAiKuDBFXRhKH6OYCK4HogeqFsKEqlOHmI6mBmvnf8L8xAA "Jelly – Try It Online")**
### How?
```
mJ’×⁵‘ị"mS - Main Link: Map, Down (Right is the third program argument)
m - modular slice Map's rows using Down
-> list of the rows on which we could hit trees
J - range of length -> [1, 2, 3, ..., length of slice result]
’ - decrement -> [0, 1, 2, ..., n-1]
⁵ - program's third argument, Right
× - multiply -> [0, Right, 2×Right, ..., (n-1)×Right]
‘ - increment -> [1, Right+1, 2×Right+1, ..., (n-1)×Right+1
m - modular slice Map's rows using Down
" - zip with (f(value, row) for row in m-slice result):
ị - index into that row
S - sum
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 29 bytes
```
g@>:2Wy<#g{i+:g@y@xy+:ax+:b}i
```
Full program; takes dy, dx, and each row of the grid as arguments. The grid should use `0` for no tree and `1` for tree. [Try it online!](https://tio.run/##K8gs@P8/3cHOyii80kY5vTpT2yrdodKholLbKrFC2yqpNvP/f0MuYy4DA0NDAwjgAjGgmAvMABGGBiA1UHFDiLghkjhENxdYCUQPVC@EDVVhCDcfSQ3UzP@6RQA "Pip – Try It Online")
### Explanation
```
g@>:2Wy<#g{i+:g@y@xy+:ax+:b}i
For our purposes, y, x, & i can be considered to start at 0
g List of arguments
@>:2 Remove the first two
g is now just the grid
Wy<#g{ } While y coordinate is less than number of rows in g:
g@y@x Get the value (1 or 0) at coordinates (x,y) in g
(using cyclical indexing)
i+: Add it to running total i
y+:a Increment y by first program argument
x+:b Increment x by second program argument
i After the loop, autoprint the number of trees encountered
```
[Answer]
# JavaScript (ES6), 57 bytes
Expects `(grid, dy, dx)`, where `grid` is a binary matrix.
```
(G,v,h)=>(g=y=>(r=G[y])?r[x%r.length]+g(y+v,x+=h):0)(x=0)
```
[Try it online!](https://tio.run/##fZLbjoIwEIbveYq52aQNo3ZgDUFTveQhSC@Mi6AhYNAQeHpE66EuhTSZZvr1n1N72tW7y746nq@zovxLuoPsWIQ1ZlxuWCrb3lYyilvFt1Xc/FTzPCnSa6bclLVujY0rM74SnDVS8C4CCbEDEINAQgKFD4dQmE7vgnLU2nH2ZXEp82Selyk79GnvGs5hsQAxYGGINMa8t44szB9lhN6TeRbmT7AwtDHe92TO4DEFFOYyZ6IvGPsLCkNFL/uB@tBU0lBJU0oaFvQJauS2FTSA3yFprM@JsP9aGfsbE0@lUWBBS418Cwo0@rX9p2eu7gY "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 45 bytes
```
(a,b,c)->sum(i=0,(#a-1)/b,a[b*i+1,c*i%#a~+1])
```
[Try it online!](https://tio.run/##bZLBasMwDIbveQrRMnBahVnOxggmfZGQgxLoMKTDdO1hl716ZjuYyqzE2P8n/7@sQzxfXfPp1zP0q2KccK6b0/f9olyvUe25ofp1Qh6mgzsSzgf3suffI431ygQ9DBoJyRLqtIdzrNjEiwShmAz5EnXgVAm2dstvBi0/m7k4rRY@yrvNJL1kJT/zihftIy/6F689qmWa/s37rEMx2VhV7P3yoxiaE/ir@7oFuYuwg5mXRZ0RuK4RhoEJIa4xQNRdJ8CUus06otCy3nUJjOhqRMCIgBFNo0B4S7oV2Vb4N/0u9EfWadDww/wB "Pari/GP – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), 80 bytes
```
|i:&[Vec<_>],a,b|i.iter().step_by(b).fold((0,0),|(x,t),v|(x+a,t+v[x%v.len()])).1
```
[Try it online!](https://tio.run/##dVLbbuIwEH33VxishXFrWQVaVS2ln7EvNEIm66iW3JDGhkIbvp36tqyDulbszBnPnJmxTrs19lTV@E2oGij@QtgtLS2u8OLUqcfR8rcsn1bPBRNs3SmurGyBcmNls1ofYE15tdF/AG7YDWUd7JmlbOf@14LZ691y/2vHtXTMBaV8cvLk81Ci2rQYVN1sLcOlMNJQrGo8WiIYckIQ4W4TPmR4J8vBMqTAhGH3uToRPjz08TTASQZnGXRXzjPN4KwPPZ3HhdswJL4D10logyPuzJ@amfXpb/9Df9GLs28jjMU8O48LeSNtFAx/kNBB8pPoJ5k/ZqMQEnNSbrRTBDnzZzGJ86fhLh7rPoN3/dHvs9Gn59yCBk@RVOVX06ra6noAw6@jKxkEQOfn66CKA8N7hkVtPmQbVBH0kZH8lWjIfsReoFGkz3gRndw0WlkYv9Rjyt9EA53uNC9fRWsgOcoOysViTMYUC4O3Rn1KysuN1rK0QDNz3qubD8DCDK7Xw0WQMEa2diXfB1DBKKn8ygVeHag70mj/co4onkd0@gY "Rust – Try It Online")
Takes input as a slice of vectors of ones and zeroes.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~56 ...~~ 51 bytes
```
->v,y,x{z=0;v.each_slice(y).sum{|l,|(l*z+=x)[z-x]}}
```
[Try it online!](https://tio.run/##fY3dCsIgHMXv9xShBKv@k2ZXEu5FRGKObQUORrahmz67reg2bw4cfufjOSkXOx6LagYHdl34@TqTtm7uN6MfTZu7AzHTsHoNPtfH5cTtQSyFlSHEnheVAQtu7YQhQz1uKa@Jcq/2Z5VXexrCJyNDlmXjrhcCEYwRIEy@igmSUEIpE5Cx/5SmqhQuqV2agokmY9tpfAM "Ruby – Try It Online")
[Answer]
# Python, 57, 54 bytes (@GB)
```
lambda a,y,x,i=0:sum((r*(i:=i+x))[i-x]for r in a[::y])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZBdaoQwFIXpa1ZxSV6SadQ603aKYME1zKPjQ8pUGhh_UAfiWvoilHZP7Wp6r3EGBeOXwznHm3z-tOPw0dTTV5kevy9DGbz8Pp9N9XYyYPSonbbpQ9JfKim7jbRJau-dUrkNXFE2HXRgazB5koyF8um_O5NBCpzzMBQi9A8jWF42Ay0CGRevC6-Lle7TbLb4zJL1vDjErX_lWTpxCkbT5DnHTWjr07uTTgGN7mj0roDbMbKwb892kPxYc1Wwgz9FHMUQvMKWxdGOYI_wRLBD2BM8su3iod9RXU91h3VdwgCsbrCyv8qU4Ap1vGTU7VWPZrHtbD3IUmZ6U5lW4kZLNCqldLPc9DT57z8)
#### Old version
```
lambda a,y,x,i=0:sum(r[(i:=i%len(r)+x)-x]for r in a[::y])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZDRasMgFIbZrU9xUAa6mWRpN7oFMsgz9DLNhaUNExITTArmWXYTGNs7bU8zjbZEUD9__vN79POnn8aPTs1fdX74vox19Pr71oj2eBIg-MQNl_lTNlxaqksqs1zeN2dFNXs0LDJV3WnQIBWIMsumivmAvztRQA4Y4zgmJPYDOQgTLeAWYtkuXideJyvdV6PF4mtCrefgILf8lSdk2i6Q66YssT3EUp3OhhoGrnXjWtcV3J5RxEPfyJHig8KsQnv_ijRJIXqHDUqTrYOdhRcHWws7B89oEzzuOhc3uLj9Oi5DAJJ3NnK4yq4CM6vbf7a6vOrJIvZaqpHWtOAPreipPXBqjYwx3oWfnme__wM)
Expects a list of lists of 0s and 1s plus two integers.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ιнε³N*è}O
```
-6 bytes, by using the exact same program as [*@ovs*' used in the related challenge](https://codegolf.stackexchange.com/a/217224/52210).. :/ (thanks for letting me know *@DominicVanEssen*)
Takes the inputs in the order \$right\$, \$grid\$, \$down\$, where \$grid\$ is a matrix of `0` for empty spots and `1` for trees.
[Try it online](https://tio.run/##yy9OTMpM/f//3M4Le89tPbTZT@vwilr///8NuaKjDXQMdAyB0AAZxupEw0RQaKC4AZJaQxgJFofwkdUboqg3xKHeEMVehClI9qDZiyyOaoYhFvdjNwfVnbFcxgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFqim16UmaJQUJRaUlKpW1CUmVeSmmKloKRTeaTd5dBuHS4lx@SS0sQchUy4YqCs/aOGeXrKxY@a1gRnH1qpw5VQrBSUmZ5Roluck1@QaqVweL@1Qkp@eR6Cr6TDVXloWULYoXXF/8/tvLD33NZIP63DK2r9/yv5l5YAjQaZqnNom/3/6OhoJT1lZSUdJWU9MKmspxSrY6hjGKujgFXK0hK3nBE@KWNcUoY6Rril8OiytITIKUOEgUqgsnogHkgHkkfwKzIiRpExYUVGxCgy1jGBekoPJAEGYM8B@RAM1qkHYStDdULllGFyyihyyjBTwAoheuGmwHhQdcpI9qGohNmAHP@D2InGg9@JpoPfieaD3YmgQiUWAA).
**Explanation:**
```
ι # Uninterleave the second (implicit) input-matrix with the first (implicit)
# input right-slope as step-size
н # Only leave the first inner matrix
ε # Map over each row:
³ # Take the third input down-slope
N* # Multiply it by the 0-based map-index
è # Use it to 0-based modular index into the row
} # After the map:
O # Sum the list together to get the amount of trees encountered
# (which is output implicitly as result)
```
[Answer]
# TypeScript Types, 298 bytes
```
//@ts-ignore
type a<T,N=[]>=T extends N["length"]?N:a<T,[...N,{}]>;type b<T,N>=N extends[{},...infer M]?T extends[infer A,...infer U]?b<[...U,A],M>:0:T;type M<G,Y,X,N=[],>=G extends[]?N["length"]:M<{[K in keyof G]:b<G[K],a<X>>}extends[...a<Y>,...infer Rest]?Rest:[],Y,X,G[0][0]extends 1?[...N,0]:N>
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgDkBeAbQF0A+W8w9AD3HUQBNIhavQBEAG17xwACxGMA-NQBcZKvQB0m6pQDeAXxYBuXAUIAjCjVbUO3XgPr7Km9bEQAzdKkIBZBey4efkh6N09vAEFnTTCvQgBVBQsNTXjKCMZKH2YlAAYlcmN8Ih9SAHFKAE1KAA0aBkzWMtsghwVhcUkZOSVSnXoAaUI3QgBrdBxkd0IyxiULMsHMshrmZj1A+xCXMkrmaNcPOIAldEhwBVPzpSYq2spF3MZ6J83gwgBGeRT1bSelajMTDYYozXKEWiEeiYQhQ3KUD4IzIwqGI+EfZGw+iItHIxgg0xlXLkcGQ0pEyifSkfIEgWGEAB68gJRCJ5A+EN85XhhAAnLzqbTgPSmSyweQAEyc8k8iWCzB02Gikys4kAZml3MpcsIaqFIuZKvFABZNRSqYQJfqlYbQWyAKxmnmI3XWxm2wnEgBsTuplP5btFYrKHMh0KxOMo6MxcIRcYxlBR2Lj8KeiaxqfjeODHxJZpdBcDHtZudDXJDfstRZzkvzlb1CuFNprGrJ5RdOobivdNdNbYruspxurwalYaTmcjmenUajMeTM7Rs-Ry-nK5n69nuPTsc3S8nW7XKeX8ZP24nW8v+5PaYvS-vN8PO5ex43j4TSYf183qfn39Pb4fhmr4gXu2ZGmUEp5v2OqFo2BqjuyZqwZSXZNj2EFQWO5YoYQ9rVph5CtjhlYAOwEXaUF9iRlryt2opAA)
## Ungolfed / Explanation
```
// Convert a number literal to a tuple of {} of equal length
type NumToTopTuple<T,N=[]> = T extends N["length"] ? N : NumToTopTuple<T,[...N,{}]>
// Cycles a non-empty tuple T to the left N times
type CycleLeft<T, N> = N extends [{}, ...infer M] ? T extends [infer A, ...infer U] ? CycleLeft<[...U,A],M> : 0 : T
type Main<
Grid,
Y,
X,
Trees=[],
> =
Grid extends []
// If there are no more rows left, return Trees
? Trees["length"]
// Otherwise, recurse:
: Main<
// Map over Grid and cycle its rows X times to the left. Then, remove the first Y rows
{
[K in keyof Grid]: CycleLeft<Grid[K], NumToTopTuple<X>>
} extends [...NumToTopTuple<Y>, ...infer Rest] ? Rest : [],
Y,
X,
// If there's a tree at (0,0), increment Trees
Grid[0][0] extends 1 ? [...Trees, 0] : Trees
>
```
[Answer]
# [R](https://www.r-project.org/), 68 bytes
```
function(g,d,r,n=1:(nrow(g)/d)-1)sum(g[1+cbind(n*d,(n*r)%%ncol(g))])
```
[Try it online!](https://tio.run/##TZDhigIhFIX/@xShBN5dm8WpJVjwSab50Y4lQt1ZrsbS00@aUgpejh/nHOTSgpFOp2CW8w2n6GeUTllFCo3@kUjzv3TwZWGjIdyu0g36c/r1aCV@WJUGwXqN03xJLhhhceStYbzrhOjKYVnUy54iD5F0GoWLwkXDS5o9LSVTs0VXh3j1N57ayZkzUQZ//bv4870/Eh3vMkQK6R3fIn9Y8QNyGAY9jopzAGO44MDKYtI6tNKwEqu@JdtM9i35zmTbkn0muzfpa8/yAA "R – Try It Online")
**Ungolfed**
```
ntrees=function(g,d,r) # ntrees = function with arguments
# g = grid, d = down, r = right
n=1:(nrow(g)/d)-1 # first calculate n = 0 ... number of moves we'll make
# (number of moves is rounded-down to an integer)
sum( # now calculate the sum of all trees
g[ # at positions of g given by
1+ # 1+ = R uses 1-based indexing
cbind( # cbind = combind 2 vectors, to use as 2d indices to a matrix
n*d, # x-coordinates are just d * n
(n*r)%%ncol(g))]) # y-coordinates are r * n, modulo the number of columns in g
```
[Answer]
# Python3, 84 bytes:
```
f=lambda b,d,r,y=1,x=1:0if y-1>=len(b)else(b[y-1][(x-1)%len(b[0])]+f(b,d,r,d+y,r+x))
```
[Try it online!](https://tio.run/##jZLdCoIwFMfve4rdhBseYaeIMlgvMnah6Cgwk@WFPr1piZg7fYwDO/z2P1/bqrY@38rtoXJdZ1WRXNMsYSlk4KBVCI3Co7xY1kZ4UkVe8lTkxT3nqe6J0byJUKyfXEsjTGj5KzYLW3BhI0Rnby6/10wxrSUgoAGNIMe994xZVe5S1tzyl3QQCbGEcUzRDQ23PkTYUJBUxvFEg@h9BWL1NhDrDZ8mfTPA9PyE8AeJ9OJx7oySCftZkMiCv7Mg0e6iyrIvul1PQpbAb/fyqxA19H8f58Mb7yi4//DDugc)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
NθNηWS⊞υιI№E✂υ⁰Lυθ§ι×ηκ#
```
[Try it online!](https://tio.run/##TYxNDsIgEIX3nILIBhJs1G1XxlUTNU3qBbCSQqT0D9Tb41CqKckMb958b2olxroTJoTC9t5dfXuXIx1YjtazgvmttJGYznblRm0byhgu/aSo51gDUYLp6ElM0DoP8iJ6Whldy0jsOD5L2zjAGccD1NEV9iE/VHN8062cqOL4yRhsNmQDfx7CAe1RlhGSpYeiWArNIjaSRWbxSfLJyk9pNCMps2STXgjyv79ifjfD9mW@ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of newline-terminated strings. Explanation:
```
NθNη
```
Input the slope as two positive integers `y` and `x`.
```
WS⊞υι
```
Input the grid.
```
I№E✂υ⁰Lυθ§ι×ηκ#
```
Take every `y`th element of the grid, and from those rows, take every `x`th element respectively. Count how many of them are `#`s.
] |
[Question]
[
# The language
[Splinter](https://esolangs.org/wiki/Splinter) is an esoteric programming language where data is stored in 'splinters'. There are three different types of syntax:
* Simple character output: `\character`, outputs a character
* Splinter storage: `(splinter name){code}`, stores the code into the splinter with the correct name for later use as is. Note that these can be nested.
* Splinter reference: `(splinter name)`, evaluates the code of the splinter with the correct name.
`(splinter name)` just means the name, with no parentheses.
[Here's an interpreter](https://deadfish.surge.sh/splinter).
Splinter's computational class is a push-down automata, meaning it's one step behind Turing-Completeness. There are 26 splinters, one for each *capital* letter.
Because of the ability to store data in these 'splinters', Splinter programs can be interesting to compress.
Your challenge is to create a program that, when given a string as input, outputs a as-short-as-possible Splinter program that outputs that.
# Scoring
Your score is the combined length of your program run on the intended text of all of these:
[Never gonna give you up](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i)
[What a wonderful world](https://codegolf.stackexchange.com/questions/31473/what-a-wonderful-world)
[Hamlet's monologue](https://codegolf.stackexchange.com/questions/40111/print-hamlets-monologue-using-as-few-characters-as-possible)
[Something monkey-related](https://codegolf.stackexchange.com/questions/32235/low-entropy-literature)
[Gettysburg Adress](https://codegolf.stackexchange.com/questions/15395/how-random-is-the-gettysburg-address)
[There was an old lady](https://codegolf.stackexchange.com/questions/3697/there-was-an-old-lady)
[Bears](https://codegolf.stackexchange.com/questions/119775/the-other-day-i-met-a-bear)
[House that Jack built](https://codegolf.stackexchange.com/questions/161992/the-house-that-jack-built)
[Buffalo buffalo buffalo](https://codegolf.stackexchange.com/questions/218284/output-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo-buffalo)
### The bear link is fixed now
[Answer]
# Python 3, score: ~~11069~~ 10495
This algorithm is very slow but I'm pretty sure it's close to optimal depending on the parameters *MIN\_SPLINTER\_SIZE* and *MAX\_SPLINTER\_SIZE*, though it takes quite long even when only set to 2, 120
```
import sys
import dataclasses
@dataclasses.dataclass
class Splinters:
"""
The splinters class is the basic source code unit. Variables is a list of variables in order. Each variable is a
string formatted like data. Variables may only contain variables with lower indexes than themselves.
Data is a list. Each item may either be a literal string or a index of a variable to include.
"""
variables: list
data: list
def reduce_text(self, text, pipe):
"""
Print a section of test to the pipe. Variables will be replaced by the appropriate numbers. Should only
be called from result()"""
for text_part in text:
if isinstance(text_part, str):
pipe.write(''.join('\\' + i for i in text_part))
else:
pipe.write(chr(ord('A') + text_part))
def result(self, pipe):
"""
Output the formatted code to the pipe
"""
for index, variable in enumerate(reversed(self.variables)):
pipe.write(f'{chr(ord("A") + len(self.variables) - 1 - index)}{{')
self.reduce_text(variable, pipe)
pipe.write('}')
self.reduce_text(self.data, pipe)
MINIMUM_SPLINTER_LENGTH = 2 # Minimum length of a splinter
MAX_SPLINTER_LENGTH = 120 # Maximum length of a splinter
def add_to_tree(tree, value):
"""
Adds a single string to a tree
:param tree: The tree dict object to add the string too
:param value: The string value to add to the tree
:return: None
"""
k = tree
for char in value:
ok = k
if char in k:
n, k = ok[char]
ok[char] = n + 1, k
else:
ok[char] = 1, {}
n, k = ok[char]
def get_from_tree(tree, value):
"""
Get a single value from the tree. Fixes duplicate items
:param tree: The tree value
:param value: The string to look up
:return: How often this string has been added to the tree
"""
k = tree
n = 0
for char in value:
if char in k:
n, k = k[char]
else:
return 0
return n - sum(i[0] for i in k.values())
def add_string_to_tree(tree, string):
"""
Adds every substring of a string to the tree
:param tree: The tree
:param string: The string to add
:return: None
"""
for substring in get_substrings(string):
add_to_tree(
tree,
substring
)
def recursively_add_splinter_to_dict(tree: dict, splinters: Splinters):
"""
Adds every string in a splinter to a tree
:param tree: The tree to add it to
:param splinters: A splinter object to add to the tree
:return: None
"""
for variable in splinters.variables:
for string in variable:
if isinstance(string, str):
add_string_to_tree(tree, string)
for string in splinters.data:
if isinstance(string, str):
add_string_to_tree(tree, string)
def get_substrings(string):
"""
Iterate over all valid substrings of a string
:param string: The string
:return: A generator over substrings between MIN_SPINTER_LENGTH and MAX_SPLINTER_LENGTH
"""
for index, char in enumerate(string):
for previous_value in range(max(0, index - MAX_SPLINTER_LENGTH), index - MINIMUM_SPLINTER_LENGTH + 2):
yield string[previous_value:index + 1]
def get_splinter_substrings(splinter):
"""
Iterate over all possible substrings in a splinter
:param splinter: The splinters object
:return: A generator over all the substrings
"""
for variable in splinter.variables:
for string in variable:
if isinstance(string, str):
yield from get_substrings(string)
for string in splinter.data:
if isinstance(string, str):
yield from get_substrings(string)
def get_best_splinter(splinters: Splinters):
"""
Find the best splinter in terms of bytes saved
:param splinters: The splinters object
:return: The most optimal substring to make a variable
"""
tree = {}
recursively_add_splinter_to_dict(tree, splinters)
best_substring = None
best_score = 0
for substr in get_splinter_substrings(splinters):
nrof_items = get_from_tree(tree, substr)
if nrof_items >= 2:
score = (nrof_items - 1) * len(substr)
if score > best_score:
best_substring = substr
best_score = score
best_number = nrof_items
if best_score <= 3:
return None
return best_substring
def reduce_text(text, substring, index):
"""
Replaces all instances of substring with the variable
:param text: the text to look in
:param substring: text to replace
:param index: what it should be replaced with
:return:
"""
if not isinstance(text, str):
return text,
elif substring in text:
return text[:text.index(substring)], index, *reduce_text(text[text.index(substring) + len(substring):],
substring, index)
else:
return text,
def reduce_splinter(splinters: Splinters, substring):
"""
Replaces all instances of a substring in a splinters object with a variable, and also add the variable.
:param splinters:
:param substring:
:return: None, modifies splinters in place
"""
new_variable_index = len(splinters.variables)
for index, variable in enumerate(splinters.variables):
splinters.variables[index] = [y for ys in variable for y in reduce_text(ys, substring, new_variable_index)]
splinters.data = [y for ys in splinters.data for y in reduce_text(ys, substring, new_variable_index)]
splinters.variables.append((substring,))
def get_splinters(data, pipe):
"""
Performs 26 iterations of get_best_splinter, and outputs the result to pipe
:param data: The input text
:param pipe: The pipe to write the output to
:return: None
"""
splinters = Splinters(
variables=[],
data=[data, ]
)
for i in range(26):
best_splinter = get_best_splinter(splinters)
if best_splinter is None:
break
reduce_splinter(splinters, best_splinter)
return splinters.result(pipe)
if __name__ == "__main__":
with open(sys.argv[1]) as f:
data = f.read().strip()
get_splinters(data, sys.stdout)
```
Score breakdown:
```
processing: hamlet.txt
hamlet.txt 2013
processing: wonderfull_world.txt
wonderfull_world.txt 747
processing: jaxt_house.txt
jaxt_house.txt 754
processing: getysburg.txt
getysburg.txt 1803
processing: give_you_up.txt
give_you_up.txt 1028
processing: bear.txt
bear.txt 2472
processing: monkey.txt
monkey.txt 1103
processing: old_lady.txt
old_lady.txt 533
processing: buffalo.txt
buffalo.txt 42
total: 10495
```
Edit: Saved 601 bytes with bug when a splinter appeared near the end of a string
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 76 bytes, score 8611
```
ṡĠị$ḢṭFL’×ʋ¥LƊ€ɗⱮ20Ẏ1ị>3ƲƇḢÐṀṪṪ
”\;ⱮØ{jWƊ};"œṣɗj¹;@ɗ‘ɼịØA¤ɗŻṛ?Ç$1ịȧ®<26¤Ʋ¿ḟ0
```
[Try it online!](https://tio.run/##7VpbixzHFX7vX1FaDGtDa7AdyIM2WJZjJE/iSAErLIa81HRXXzTdXe2q6m1GIaDkRSBDCCQghyTkYgeRkBhiEkcbBwK7sYjyL3b/iPKdU9Uzs7uz1sjIF2GBkadup879fKd6r6mqmj14cLD7u//89uCjt585uPv7g92/XHz98MYv9m//7@29P7x@79bhj/98//bhX99/8fmDf/7kBex66Wv3Prh3E1v3f3qwe@Ng90/4Lzq88evvb2HX/js/uLZ979YPtzY@/tnB7rv3b1/b2916GQRuvHP/Xzi8/86Fvffu3/74o4PdX57fv/kMEfzvnb33v/Hi1/feu/fB3r8P7v7m@QcHd//x/N4fDz76GzF094ODu@8e/ujv3946vPErcfYlgbu29m9efD2@d@vNe7civghLex/u3dn7EIsg@fL@zWj/zssPHrzwYFttGiUaLawzssmVscJpUekdFb2pOzFtdC9coYTpKmWFbFJhtUi1GEcXRNZVlUh0XZeuVo3btKIvpBPjzRpHymZaNrnQGdPpdVelzaYTuXK0aEVmdA16M6FB3oi8m0Vjca2zTvSyaaRwUL6Y4WgBDohkplQFitEl7ZwUtZwqXu6aFEw7cBZFl9UOkdJ0Pi93wob2yHwFBmg61X1zZMF0jZBGgx6LmSqrDG89smt@b2JmRxasnOGXTiczdWSe5cC1pWKyRReIRtA8OCQFN0LJpAiKyLQhFVcaokJzRhRKGtLtRCkwmBSk1UnnaJFM5zRsV8zIasRC6aJxY8tUiV6JCUh6E5JhBhq5ZsM04GBh31zWnsGeHcLz3lae4gXMlxmLLe1UYOdxo7yqybgsa836GVibYDll5pR6wgz0RDH77BVdxMtsPnfa1HMnBItFc2wmevbSYzi25OJfdg//iuWep8x@Rszu3YEnIdUJZxTqpc5Ejh9NLIxKhdFW2Zj8OR52FapGitS6jjksgocSJcq5Y19HyfPrmVVVFm1TgZUop@R5qL/4Zap0FAV6dlr6WydVh/gkWkmlu5Tn@qJ0Ko6uIhYmpswLh13KWjCWylnMMZJKM4XMCXHb0JZHZYOIJ7rShm9k4CDLZqL7mEK@Nco5xFvDK3Y6i6MLCEVZYU37yUwmXoJW6bZSIZQns1GQMDOlaiCPLSTjiwIyQqewU9lsxmLjNUQs4In3hfMbxNCMwt0oCTC32DdmjEP7RhukPcpBYiInpD84ATaNIHcvHdIWWyk3uh95cjB9he2NqDus1ppyFPhApsAKOwklnUdSXRS9Sa6x9nb42VUUV9gYXtNoRycm6hzx4QTQFanyrU5ZV@rmHIgozrybDkuNhtnNYIR6KM9dlinD9rOU6jzWkwZSszl0B3yYK91ZclTXNfCkK4ZOOoodaWqcyGFrS@xaJdn@CDzysZh1MQHWa1ttyWyKboVazwuIkZbEOXiolGq3osuadbrFHOCQ9AtD/kfWx2nmlAvHWVQMHzYkjyvAIg0a6TojKziKTqYW26GYDLwUpJ5ClcR77DUi4bKN7epakrqiV9UOpK1mXqeiL22xmY4Co/ESo1fDr3NwVpPAAxIqViKFr9XnRIgpozZtQNCTreiiDpoHN14qqClVElWMsTOftchHMwLWiizXkMSFhLPaAkaqEJo6yzyIhp6cJAxeVnH0HSpgnCBhpFZ2lv1hiQFlW5U4rwrKePB0WUmg9xlxEUoyclqmPKN9oT1whxoQHUQDOaQNbUCiTeOjvKxDWoF5cYnVhloBA2I@q7RwgxQ3NpiGpl1Xq2rmT7SSXI10UNrWlNc3U45Lf66SPU6kCjXa74Z36UqRmskjs6xMFoa3bQd@vHAtDImGBOnUlG5IRF2D0HGEI0j02KuWnKisKdIQCZQSSatvdaVynWUdRdslbCORGgyhjRRJ57zYnisGhC0lLQMuLaspJrfIUXacV1MP43qgQGGMDTPWcBy90jnvB5x4YffUW6FWjhGQzBzOsG946UGkhNaRX6ClBCXNgRa3UTCUJe6gAYoeROoO6hNOI9@SVmLRdtevUwPHNiyrigPS@wAENZLTQ7Ay0cIWO/gd6bRB7HBAMISznvE@oCvKPzo7j30dG9gmJRsp1corEZM9VMSGxhZk4i1mwNEBYgnBSn5bdGxZ@JCuOo7FMTJ9mUxRZ6GdTfDYkznYqSSqQyJtsK/uYD2fZ2B5ZeBMdl6AySXYjCS0pl7Vm5VjyKgcvBFN5ISkMwbL4Ap6E7InzyOaFSnFc1ozjzIh/kZnz76hMw89oIkzbKdMgtCVtgBklGfE5VndAoZz0CPOwBYUFL1CVQ@9EioSnBo81KqekGFHlNopgVH8KaRBCvJmqmYVoUwR6YKBAjyOksDSkilbFcYT70wNnFajpNloiJGekj0a/Q4pBikubKdkbiN2JD9B22DWQEwai3v9ALYnm5JuWZkZYwTI5pezUlVp0DKN7VsdwiZampCwNHQABiJOaX46xGuovLnPWvNL89JUA6uSzBzVMDt5oZ@UVVvIiXKR2imHjaIlyGc5nF1hJFAhMLwTc1ZbNoSY4dhwTw2np@LQIAzg7LVMVYQ570Vhi5wR/IP4EZTUgFdsRGLBb4lCN0wOu0ndPdm3NXxmuMm/jMxZQU6DNuj5pQshmqDspgtmnaaluQ2guIbLA7/VUMaYL0ECcg8fxNCAbvhWmUigAYApAxlR7pDzkHmvoyWHf2hwovl2dDK@UUMmsC4iN/Iq9OQb1VtbkBqli4hNquLQDR9xSCucQY1q6bCIOFSD3bsWJRL5GAULCIsP@xW4YUElm@pjTVgBSQDOEY71Mk0JkaHHMoxxaolCG3n0yiFaqSz8QqFHRqY0CyyybNTSSU6U7KtGoYImTrF2mfHgusCdyxzn6BuW/Nq6JZ6tB2E@pPhX74Erxe5F6mipOPoIsYqMNYNLET5C/uwoeH0SnRjOWgyoCg@AS18hy4bKl4Qr9pwbNToIzCcKWZI5r0pkCzeLQ1OTlokkmQiO@YJLOIvO@UzNuYaaa0O@pXivQnBWI3GZemfFK6rJAfGYvgxpMykpppC8UZEJTcJv@wAmmfDAHHyO3vL8kKDEgtvhzXBgEpLAzRhqwH86o0Zi29@PykdaGO6eSOdgXs4pnOOp5EjD2zl5UAgw4AqkcbKFKomDYT@fhpYI5GVlA6xkghjo/FGiFsFCYIfSjsiJtK8GFQSwQ5GeSxuQAi2iR2C4LSunc6@WrHRMn8QmOwya6lXwUGpPyNAjAQQQe2VX0uTYaFVjgX16xSqisjqIdmSSSqxKzPHpAlbmtw4wlHPLC9DKzR5nWupCwfPAG4AFFENSU0HIc8KVJH886Ha4A/4ANlFwBFIFVsiDW63pn15xB4AgJQdIFYBH4vylIS4opSIAYUdikZ6MsJFtP5Q8j3tJO8C8noEJShNwG8vF7RSsRO/GfUBLM6BFz@ygfzJjgBJexDhgmjiA@EWIsI1DnHQNfALwHtPgd0ro1rd7M1ZM5sOTTxTeK6j9kfx8RW0UepN0h2B/OjASkNTAD9/N50/EqPdxR@@pUAUaJ@5zVUaJo7OHN37u/ZeqsgeZhYbulDcc6Yv7rrKhcOYeHl2LD3jtHS6hDoA5WRJrcG54HJATP@DXOI8o9I2IpzHc3gfmCzg8hGVcxue9HazyzFjyvOCCWE5Ln0N2INRAiZ1ySBYeDV/S8D9/lI/5bDcpORdmkFypVNcg4NELiOSEfRuCbwOm948EMXWJy0Mf1YvxgkGEI@w9V6ugBrJgzHWVJe0pUyB9wHcrmXo3QBWiwKJURiiYXiJSfu4O747AcNR/zHd5w1GH811lCtnSY4WipwEoxj@RrHGRbUsoKfb9TI/axQFKqlj6eS38Lv17KAiPojeO8aICKfKLZHjO8Ox9HnLAnmkc0asMgGhn/FuDXw@rq1im@aMMD/r4komHK3FRLXNU7BAXy/JheZV4id@34Ndr6QnWQ6rzeHirKnR@VAtYXKWF1O9bcMvK/Cpoq9AGdZ654mSJbIZ@HnNDJgpfStLh4WNpOGaYJMNbw9HRhQE5lfmpM1cKsDfj9o/brNGKmU@@cx2a0WsoMVpPSVx6h4lPToyXxuhHVkzgiC2vY6JrBxJHxuPFEPtHJ8Zr3PkwkrxBluxWAwtLw41tOIj3F3oCMF1zfuWcf7vm76clFuKTE5e0YwSNvmO0cWy0zq0PIUjrcsaIJOj6yHDjqv96Jvljh0BoSBw6ZZY6hkrllr/l8/t8vHqSftJrScf1mhzjzMbqyTX5WfsSfrMBSBsDkDXx8RH56oAAgDdPTtDTXPhCogpq4uvTJrdl6A8oEEbHhw@7eB2S0bihMx7zsIseGy@lHP7qtGpmOWRPm0EQ55VGpzxRZ44O1rjyIeQ4oVD2A@hEO9Ik4Unz2BSLjjaVn2q6dsXEG5q/kXhgPt4EBOrq06f5jdHQs3g9E1WXTEerptbiZP0bFkanLeh3T06Mm9AEyNIcH5FPIN@W/GHO@0Hg6fSVC5x@kbNC9j0@fhgH61OOLvP3tSH1AKQj1ayaoxuX53TfnDI5Ft/kV72jF6@eveI/WhFPE5lM@XPvmVNm12frUe6Cs6CTCV/YVJPGqyYoOpCGHf1dFX3KWj33vYY@vwrO3MdHV4cEIOgdhQ@MVk@ud/8a1Bl5LEj5RznWyLdI/ElXVu7YdbWsnPDU@O8omrVPok8OB@ndZqD1qUglc1LTsqoCvAP9k@Q/HasEU0Mbpo0pF6B01aWPTSgCn8OnjsQgavl9RpvGk3M6xOoXxF8NOELvif69uZrzVZfVdODg0URw60rgHpMAnnsnnVMm9NNuzty0nDP3xIt6rUtz/7nJFvzpgF9kF9zVcsHJF6mWz92Jjdb0HSk8lxluzoY/i5gz2aNfeKrGT1JjJk1Nj9e65z/I4U8Yc0lV657q@vHpml8O5n/zUMz/ri2sNUNppyf2xVvzUwt9phYCcnqlyzJZacz4/x8fTz55/f8 "Jelly – Try It Online")
A full program taking a string and printing the Splinter program. The TIO link can be used for all 9 required test cases by modifying the first argument from 1 to 9 for the relevant case.
1. We're no strangers to love -> 997
2. I see trees of green, red roses,
too, -> 611
3. To be, or not to be: that is the question: -> 1553
4. sandor weores monkeyland -> 864 l
5. Four score and seven years ago our
fathers brought forth -> 1400
6. There was an old lady who swallowed a
fly. -> 489
7. The other day, -> 1965
8. This is the house that Jack
built. -> 691
9. Buffalo buffalo Buffalo buffalo buffalo buffalo
Buffalo buffalo -> 41
[Answer]
# [Python 3](https://docs.python.org/3/), score: 18074
```
import sys
data = sys.stdin.read()
o = "".join("\\" + c for c in data)
splinters = ""
kt = 65
for _ in range(26):
for l in range(len(data) // 2, -1, -1):
for k in range(len(data) - l):
q = data[k:k + l]
if "\0" in q: continue
if data.count(q) > 1:
spc = "".join("\\" + c for c in q)
splinters += chr(kt) + "{" + spc + "}"
data = data.replace(q, "\0")
o = o.replace(spc, chr(kt))
kt += 1
break
else:
continue
break
else:
continue
break
print(len(splinters + o), file = sys.stderr)
print(splinters + o)
```
[Try it online!](https://tio.run/##7VRNa9tAED1nf8WgiyXiOE1KczCkECgEX9pjKU0pa2kkbbTalXdXMaL0t7szazm2049TCw3twfEy783bN/PW6YZQW/Nys1FtZ10AP3ghChkkXPN55kOhzMyhLNJMWComyezeKpMmd3cJnEIOpXX0VxngrkwI32llAjofyaIJ9H31SgjmfWaek6bC9PIqm4sTLup9UaNJowycn8PlFM4u@MPEyGx@xDwDHQknK7qISx@beUPO9CcuqhKSuxcJN67mkFsTlOlxRJg9y21vQrrK4DVcRJ0T3@W/HHSVjbTdoKfXkNcubUJGxOQL01mDzl@TSB0XGu9z2GmZY7qaRmdbLd6sfYSoebpT3OK0RbrkIp6XlEZDJ9Qeo@GDqUZsB@2RLSA6R5bj8g7cg82mUCqN@8zRuWzHPmZuNu9x4hCMBR9iFgQEC9o@oPhge2iMXUOoEVyv0YM0BXgLhYWFuIGy15pSaFsVWjRh4mFdywCLSUstyjTKVGDLqLO2vS7MJECFgUEPpbMt6Q1gSd5B1Q9iAfe9D7CWxkgISOIDtdbkgCVLRLJeiVsbaP@tbDDCvaH5fCBnQrzFB5ay3F@ph5HQHdU1GeByYdfmCHC9Aeno/RRxzAI9ukg9Yj3em7vhCPByoJMtlgMe1eMcdK3CKFv3o6igzZNDXrABlHk9LoIfpucEaFTanIMapePdLhHJYF7zVpd9YJCjC5ayqwdOjS2oIBbGqwJhjbAkyW2EHMxOo7IxGEMO9vlWst0aXMcHsfVODzgq3lCdfmE8tvQNEPNpKG8shxtnbeN@dtaWBBfRHOIzC@hZmU3f2Xp6aDP7WSn7brApmCcVkd7@hraDJ/63v/B/7H/Pf7N/xuw3 "Python 3 – Try It Online")
* NGGYU: 2103
* WAWW: 944
* TBONTB: 2724
* MONKE: 1579
* 4S&7YA: 2525
* TWAOL: 1343
* BEAR: 4245
* TITHTJB: 2540
* BBBBBBB: 71
This is just an extremely naive solution that takes the longest block and splinters it each time. No nested splintering is implemented. It's already quite slow.
[Answer]
# Excel plus VBA, score 8210
## VBA code
```
Sub splinter()
substart = Timer()
Application.ScreenUpdating = False
[F2] = [E2]
For i = 65 To 90
maxsavings = 0
maxsavingsj = 0
[L1] = i
[G1] = 255
maxmatch = [j1]
For j = 2 To 254
[G1] = j
If [j1] = maxmatch Then Exit For
If [L2] > maxsavings Then
maxsavings = [L2]
maxsavingsj = j
End If
Next j
If maxsavings <= 0 Then Exit For
[G1] = maxsavingsj
[F2] = [M2]
Next i
Application.ScreenUpdating = True
MsgBox (Timer() - substart & " seconds")
End Sub
```
## Excel Cells
```
D2=MID(B2,SEQUENCE(LEN(B2)),1)
E2=CONCAT(IF((CODE(D2#)<65)+(CODE(D2#)>90),"\","!")&D2#)
F1=LEN(F2)
G2=SEQUENCE(F1-G1+1)
H2=MID(F2,G2#,G1)
I1=XLOOKUP(J1,J2#,I2#)
I2=UNIQUE(FILTER(H2#,NOT((RIGHT(H2#)="\")+(RIGHT(H2#)="!")+NOT(ISERROR(FIND("?",H2#)))+ISERROR(MATCH(LEFT(H2#),O4:O31,0)))))
J1=MAX(J2#)
J2=COUNTIF(P2#,I2#)
L2=IFERROR(F1-LEN(M2),0)
M1=CHAR(L1)
M2=M1&"{"&I1&"}"&SUBSTITUTE(F2,I1,M1)
O2=SUBSTITUTE(F2,"!","\")
O4:O31= {\,!,A..Z}
P2=FILTER(H2#,NOT(ISERROR(FIND(LEFT(H2#),CONCAT(O4:O31)))))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnE_Es6cAYmnh9jLy?e=UUiTiU)
VBA doesn't work with Office online so the spreadsheet will have to be downloaded to run the macro.
The spreadsheet is set up where cell I1 contains the string of length G2 that will result in the greatest shortening of the string. Cell M2 shows the result of replacing the string in I1 with the letter in M1.
The VBA loops through the letters A through Z, looks for the value of G1 that results in the greatest reduction in size. There is a special case if it reaches the string limit of 255. After it finds the best change it copies the result in M2 to cell F2.
One quirk of Excel is certain matches are not case sensitive so I had to use !(letter) for capitals and convert back to \ at the very end.
* Rick Roll 772
* Wonderful 602
* Hamlet 1553
* Monkey 865
* Lincoln 1410
* Old Lady 462
* Bear 1932
* Jack 573
* Buffalo 41
[Answer]
# [Python 3](https://docs.python.org/3/), score: 24252
```
# splinter
def splinter(inp):
print(*["\\" + x for x in inp], sep = "")
splinter("Hello, World!")
```
[Try it online!](https://tio.run/##K6gsycjPM/7/X1mhuCAnM68ktYiLKyU1Dc7TyMwr0LTiUgCCgiKgiIZWtFJMjJKCtkKFQlp@EZDMzAOiglgdheLUAgVbBSUlTbBqLrgJSh6pOTn5Ogrh@UU5KYpKmv//owgAAA "Python 3 – Try It Online")
Just a baseline program, appends a "\" to each character in the input, although for the input, I noticed the bear program was just a duplicate of the old lady one, so I omitted that. If I got the score wrong, let me know and I'll fix it.
(Edit) Updated to include bear text + I doubled the char count not the byte count because the Gettysburg text has some unicode in it.
[Answer]
# Excel, score 13524
```
D2=MID(B2,SEQUENCE(LEN(B2)),1)
E2=CODE(D2#)
F2=SORT(UNIQUE(E2#))
G2=COUNTIF(E2#,F2#)
H2=SORTBY(F2#,$G$2#,-1)
I2=IF(ROW(H2#)<28,CHAR(ROW(H2#)+63),"\"&CHAR(H2#))
J2=XLOOKUP(E2#,H2#,I2#)
K2=I2:I27&"{\"&CHAR(H2:H27)&"}"
L2=CONCAT(K2#,J2#)
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnEslPpOcoVlQngbV?e=fIdKwX)
This counts the occurrence of each character, assigns the 26 most common to splinters and the rest are set to `\character`.
* Rick Roll 2049
* Wonderful 766
* Hamlet 1685
* Monkey 1082
* Lincoln 1602
* Old Lady 1304
* Bear 2437
* Jack 2496
* Buffalo 103
[Answer]
# [R](https://www.r-project.org/), score 8298
```
find_best_split_for_length <- function(text, length, randomise = FALSE) {
starts <- 1:(nchar(text) - length + 1)
backslashes <- cumsum(nchar(strsplit(text, "\\", fixed = TRUE)[[1]]) + 1)
backslashes <- backslashes[-length(backslashes)]
starts <- starts[!(((starts - 1) %in% backslashes) | ((starts + length - 1) %in% backslashes))]
text_split <- vapply(starts, function(start)substr(text, start, start + length - 1), character(1))
groups <- split(seq_len(length(text_split)), text_split)
group_savings <- (lengths(groups) - 1L) * vapply(groups, function(group)nchar(text_split[[group[1]]]) - 1L, integer(1))
best_saving <- max(c(group_savings, 0L))
which_best <- which(group_savings == best_saving)
if (randomise) {
best_split <- which_best[sample(length(which_best), 1)]
} else {
best_split <- which_best[length(which_best)]
}
list(saving = best_saving, split = names(best_split))
}
find_best_split <- function(text, max_length = 70, randomise = FALSE) {
splits <- lapply(1:min(nchar(text) %/% 2, max_length), find_best_split_for_length, text = text, randomise = randomise)
split_savings <- vapply(splits, function(split) split$saving, integer(1))
best_splits <- which(split_savings == max(split_savings))
if (randomise) {
best_split <- best_splits[sample(length(best_splits), 1)]
} else {
best_split <- best_split[length(best_split)]
}
splits[[best_split]]
}
splinter_encode <- function(text, max_length = 70, randomise = FALSE) {
text <- gsub("(.)", "\\\\\\1", text)
i <- 1
done <- FALSE
while (i <= 26 && !done) {
best_split <- find_best_split(text, max_length, randomise = randomise)
if (best_split$saving < 5) {
done <- TRUE
} else {
# cat(best_split$split, "\n\n", sep = "")
placeholder <- intToUtf8(64 + i)
text <- paste0(placeholder, "{", best_split$split, "}", gsub(best_split$split, placeholder, text, fixed = TRUE))
i <- i + 1
}
# cat(nchar(text), "\n\n", sep = "")
}
text
}
splinter_multilength_encode <- function(text, max_lengths = c(seq(10, 70, 5))) {
encodes <- vapply(max_lengths, splinter_encode, text = text, character(1))
encodes[which.min(nchar(encodes))]
}
splinter_randomised_encode <- function(text, min_max_length = 10, max_length = 70, n_tries = 10, seed = NULL) {
if (!is.null(seed)) {
set.seed(seed)
}
seeds <- sample(2^31, n_tries)
encodes <- sapply(seeds, function(cur_seed) {
set.seed(cur_seed)
splinter_encode(text, max_length = if (min_max_length == max_length) min_max_length else sample(min_max_length:max_length, 1), randomise = TRUE)
})
which_smallest <- which.min(nchar(encodes))
list(
seed = seeds[which_smallest],
min_max_length = min_max_length,
max_length = max_length,
length = nchar(encodes[which_smallest]),
encoded_text = encodes[which_smallest]
)
}
```
[Try it online!](https://tio.run/##7Vb/bxs1FP/9/oq3sK5nlpam0IEmijSJMVWqhgSbEMpCdLlzcqZ3djj7mkajf3t5z/bl7CQdlQCJCSq19b3v733ee3ZzdzcXspjOuDZTvayEmc5VM624XJgSvj6CeStzI5RMDb8xQ3CMITSZLFQtNIdz@O7F5Y8vGbxPALTJGqNJb/Q8lXmZNVaPwZHXhKcwYig4y/IrXWW65FY6b2vd1l5Dm8ZG4l0O3r0bDGEubniBzt788PYlG49Hkwm7x1bwOT5yXtOAxiZRnO40fpSmqSdi7AwOhDwILTH4HTYST7tk9otaDxS7Kyh5uc6Wy2rt9Yd9US2B6XaGOft0Lcn/iz0NgcqT5YY36YhR5otGtUuXhi2Y5r8RdKnPuo@BoXLw1alOdXYt5MJa8Eo6dUYJstElg0@72B05iN0SWA@ysz0eWzoBNHE2hiCk4YtN0K7VrGPyW2c3aZ5G4Qzh5NKKrkqRl7Y3SdJ@xZJwfh7aIx0xh3TTna4rO58dGr3Zsc7qZcW7gvUMrNfI4ngLvMIu/xMzu/pWF38roREXl20U69BhhkSZ1VynvW1M/TZJtsZyzyxi5bpBPYcvT@4fStK3GFcOytHzWshoPA8@O4DT0CKjibtvL7heQicujtBtX/nOcdhj3RjYgMIxsGk7@cddefZ1zSYT1wuxA@wFaqaIyB7YEoH5rZ4IOA9piv5rvGNg0xTe0bhnTSaEOR0x62bKZa4K/hcwtwCh@gJ3SzpIj9nALlL6GQ0cfrYydlXjoVDSurMm3ORVHFLkn8PpM3jyBB6RyP7ibXXKTqgfaBEHTq/7uFsMcNb56oOj3W9JUf0BPoE8M5ER@ksJy3cSs9V8iX4HA@bll1WW81JVBW/ILJb8jXpr5l@lz77AjSs6sa6Gy0wbfpIGWmj6Pdrd4/EWybbmu7xI35UoutQ6txYTQZebyzXpUwxGdn92tx76qJnqtjLCIfGQxsJBgpyuknSE/UU9dsaYA8Nph6McqLmFFrTv1prYvry8sbEd5eN@I3k6XaNhFpu2KT6QhJDTaEIog52RkVPTCK49W3MLweu3l5cuSWrIR0Ify7aqUuKyrhM1N8dEcNRulvHsrmC3Nk5/@Xy08cHiomm//0glWH9520ytyW0/G4Yjx@XdtxEo9u0inIdrfbtEdo585DHreTi/9PgIZ9g2LBWgv6V1nVVVeFPvg7S7EH2atvK2GuPYyGRoJXbwjAleKBLYYm4YUSDb3pgTdtxi6tv2HmEUpQv6LloPacOz4lJIvMgH2hRCDui5piq8cW3BcFhxQL2D7sG2C@azM5bQoEcvQmyn0xMaeDj6BnDgw1QKtwiQ6r@DfXD3Ez9sOEiFj0kED@9SDUZBpa558rNq4UqqFZiSQ9NiYoDwgla4bOEieYHNWVWYQF0LU3NpDjWCmhm4OKxRRcgrWtJqbu2sVFsV8tDAghtiapg3qkZ7a1BovoFFu04u4NcWm2OVSZnhQkDja1QtMQIyOeccy7FIXiljMgTxilt2K3FZ4ktYFknyml@TKUX6C3HtBZYRvcIAiFyolYwYTSshw4cjpkhpIqq8saKR1MZv3qwjhs7WeFLFbM0jus0D3QpuzZatN5pg5TFCKrAEnuWlLwQ@oajElcJUsXINlBxf@VjbGecYYF5SVWetISZBZxRiV64JNQpBmORCaoGrb8VhhiYdhARMZ2OhLDASI@jxXeAD0wa4sg3hYsfryFp8gXRcG5R2pq8AJbdB@VYRuDbX2tanC22G7MIGx/lHBtBHFWz6vcIdHITJ7iOxncRwXWxRkvTV36AWtPi/vcP/Y7vn/2D/oWD/AA "R – Try It Online")
A recoded version of my [Jelly answer](https://codegolf.stackexchange.com/a/231316/42248), partly since it runs quicker (and so it's possible to try more possibilities for the max length) and partly for those wondering how the Jelly answer worked.
The score above (and detailed below) is based on using the `splinter_randomised_encode()` function and quite a lot of tries to give the following.
### [We're no strangers to love](https://deadfish.surge.sh/splinter#Wntcc31Ze09cZEV9WHtccn1Xe0VcZ31We1wKfVV7RVxrT05cd31Ue0VcaE5cd0VcSVwnXG1FXGZHR1xsXGlPXGdWfVN7XGF9UntWXElFXGpcdVpQRVx3U09PU0VQR1xsXGxLRH1Re1xpXHZHRkVcdVxwfVB7XHR9T3tcbn1Oe1xvfU17R1NcY1xoRU5QXGhHWEVcZk5YRVpORVxsTk9cZ1ZcWU5cdVhFXGhHU0pFXHBcbFNceUVcaVB9THtWXChcT05caFwpQVxnXGlcdkdcLEVPR1x2R1hXTk9PU1dcaVx2R1ZcKFxHUVwpfUt7RlRcR05QUFNFXG1TXGtHRkVcdU9cZEdYWlBTT1xkfUp7WFBcJ1pFXGJHR09FU1xjXGhcaU9cZ0lQXGhHV1NcbUdFU1lcd0dcJ1hHV05PT1N9SXtIXGJOUFxoVUVcd1xoU1BcJ1pFXGJHR09XTlxpT1xnRU5PVlxXR1VFfUh7RVxiXHVQVlxZTlx1XCdYR0VQTk5FWlxoXHlFUE5FWlNceUVcaVBWXElPWlxpXGRHRVx3R0V9R3tcZX1Ge0VceU5cdX1Fe1wgfUR7VkNOXGRcYlx5R0FQR1xsXGxFU0VcbFxpR0VTWVxoXHVYUEZ9Q3tBXGdRQVxsR1BGRVxkTlx3T0FYXHVCXHlBWlNceVdOfUJ7T0VTWE5cdVlTWVxkR1pHWFBGQVxtU1xrR0ZFXGNYfUF7VlxOR1x2R1hXTk9PU0V9XFdHXCdYR0VPTkVaUFhTT1xnR1haRVBORVxsTlx2R1ZcWU5cdVVFUFxoR0VYXHVcbEdaRVNZWk5FXGRORVxJVlxBRVxmXHVcbFxsRVxjTlxtXG1caVBcbUdPUFwnWkVcd1xoU1BFXElcJ1xtRVBcaFxpT1xrXGlPXGdFTlxmVlxZTlx1RVx3Tlx1XGxcZE9cJ1BXR1BFUFxoXGlaRVxmWE5cbUVTT1x5RU5QXGhHWFdcdVx5UlZWXFdHXCdcdkdVT0VNVlxBWVxpXGZGRVNaXGtFXG1HVFxETk9cJ1BFUEdcbFxsRVxtR0ZcJ1hHRVBOTkVcYlxsXGlZUE5FWkdHRERWVlwoXE9OXGhcLFdRXClWXChcT05caFwsV1FcKUxMVlZcV0dcJ1x2R1VFTVZSREQ=) -> 863
```
Z{\s}Y{O\dE}X{\r}W{E\g}V{\
}U{E\kON\w}T{E\hN\wE\I\'\mE\fGG\l\iO\gV}S{\a}R{V\IE\j\uZPE\wSOOSEPG\l\lKD}Q{\i\vGFE\u\p}P{\t}O{\n}N{\o}M{GS\c\hENP\hGXE\fNXEZNE\lNO\gV\YN\uXE\hGSJE\p\lS\yE\iP}L{V\(\ON\h\)A\g\i\vG\,EOG\vGXWNOOSW\i\vGV\(\GQ\)}K{FT\GNPPSE\mS\kGFE\uO\dGXZPSO\d}J{XP\'ZE\bGGOES\c\h\iO\gIP\hGWS\mGESY\wG\'XGWNOOS}I{H\bNP\hUE\w\hSP\'ZE\bGGOWN\iO\gENOV\WGUE}H{E\b\uPV\YN\u\'XGEPNNEZ\h\yEPNEZS\yE\iPV\IOZ\i\dGE\wGE}G{\e}F{E\yN\u}E{\ }D{VCN\d\b\yGAPG\l\lESE\l\iGESY\h\uXPF}C{A\gQA\lGPFE\dN\wOAX\uB\yAZS\yWN}B{OESXN\uYSY\dGZGXPFA\mS\kGFE\cX}A{V\NG\vGXWNOOSE}\WG\'XGEONEZPXSO\gGXZEPNE\lN\vGV\YN\uUEP\hGEX\u\lGZESYZNE\dNE\IV\AE\f\u\l\lE\cN\m\m\iP\mGOP\'ZE\w\hSPE\I\'\mEP\h\iO\k\iO\gEN\fV\YN\uE\wN\u\l\dO\'PWGPEP\h\iZE\fXN\mESO\yENP\hGXW\u\yRVV\WG\'\vGUOEMV\AY\i\fFESZ\kE\mGT\DNO\'PEPG\l\lE\mGF\'XGEPNNE\b\l\iYPNEZGGDDVV\(\ON\h\,WQ\)V\(\ON\h\,WQ\)LLVV\WG\'\vGUEMVRDD
```
### [I see trees of green, red roses, too](https://deadfish.surge.sh/splinter#WntCUkVcdX1Ze0dKUklcJ01cIn1Ye0hDfVd7T0dDQ31We0JcYn1Ve1xufVR7XGh9U3tcCn1Se1x5fVF7XHR9UHtcZH1Pe1xJQn1Oe0dCRVxmfU17XCxCfUx7XGx9S3tTXFRUQ31Ke1xhfUl7XGlVfUh7XHJ9R3tcc31Ge0JRVEN9RXtcb31Ee1NcQVVQQk9RQUxQfUN7XGV9QntcIH1Be1RJXGtCUUVCXG1SR0NMXGZTXFdUSlFCSkJcd0VVUENIXGZcdUxCXHdFSH1XQlFYQ05CXGdYQ1VNWFBCSEVHQ0dNUUVFXCxTV0ZcbVZMRUVcbU1cZkVIQlxtQ0JKVVBaRFwuU1NXQkdca1xpQ05WTFx1Q01KVVBCXGNMRVx1UE5CXHdUXGlRQ1wsS1ZIXGlcZ1RRVkxDR0dDUEJQSlJcLEZCUEpIXGtCR0pcY1hQQlVcaVxnVFFEXC5TS0JcY0VMRUhORkJISklcYkVcd01HRUJccFhRUVJCSUZCR1xrUlwsU1xBWEJKTEdFQkVVRkJcZkpcY0NOQlxwQ0VccExDQlxnRUlcZ1ZSXC5TV0JcZkhcaUNVUEdCR1RKXGtJXGdCVEpVUEdNWVxIRVx3QlBFWkJQRVw/XCJLUlwnWEJYSkxMUkJZT0xFXHZDWlwuXCJTU09UQ0pIVkpcYlxpQ0dCXGNIUklcJ1wuQk9cd0pRXGNURlxtQlxnSEVcd1wuS1JcJ0xMQkxDSkhVQlxtXHVcY1RCXG1FWEJRVEpVQlxJXCdMTEJDXHZDSEJca1VFXHdEU1NcWUNHTU9RQUxQ) -> 603
```
Z{BRE\u}Y{GJRI\'M\"}X{HC}W{OGCC}V{B\b}U{\n}T{\h}S{\
}R{\y}Q{\t}P{\d}O{\IB}N{GBE\f}M{\,B}L{\l}K{S\TTC}J{\a}I{\iU}H{\r}G{\s}F{BQTC}E{\o}D{S\AUPBOQALP}C{\e}B{\ }A{TI\kBQEB\mRGCL\fS\WTJQBJB\wEUPCH\f\uLB\wEH}WBQXCNB\gXCUMXPBHEGCGMQEE\,SWF\mVLEE\mM\fEHB\mCBJUPZD\.SSWBG\k\iCNVL\uCMJUPB\cLE\uPNB\wT\iQC\,KVH\i\gTQVLCGGCPBPJR\,FBPJH\kBGJ\cXPBU\i\gTQD\.SKB\cELEHNFBHJI\bE\wMGEB\pXQQRBIFBG\kR\,S\AXBJLGEBEUFB\fJ\cCNB\pCE\pLCB\gEI\gVR\.SWB\fH\iCUPGBGTJ\kI\gBTJUPGMY\HE\wBPEZBPE\?\"KR\'XBXJLLRBYOLE\vCZ\.\"SSOTCJHVJ\b\iCGB\cHRI\'\.BO\wJQ\cTF\mB\gHE\w\.KR\'LLBLCJHUB\m\u\cTB\mEXBQTJUB\I\'LLBC\vCHB\kUE\wDSS\YCGMOQALP
```
### [To be, or not to be: that is the question](https://deadfish.surge.sh/splinter#WntccH1Ze1x5QX1Ye1xmfVd7XGN9Vntcd31Ve1wKfVR7QUVPQkJafVN7XGh9UntcbX1Re0VBfVB7XHV9T3tcbH1Oe0JBfU17XGRBfUx7QURYQX1Le1VcVFN9SntcaX1Je1x0fUh7XG59R3tccn1Ge1xhfUV7XHN9RHtcb31De0lTfUJ7XGV9QXtcIH1cVERBXGJCXCxBREdBSERJQUlEQVxiQlw6QUNGSUFKUUNOXHFQQkVJSkRIXDpVXFdTQkNCR0FcJ0lKUUhEXGJPQkdBSkhBQ05SSkhNSURBRVBYWEJHS05FT0pIXGdRRkhNRkdHRFZFTERQSUdGXGdCRFBRWERHSVBIQlwsVVxPR0FJREFJRlxrTkZHUlFGXGdGSkhFSUFGQUVCRkxJR0RQXGJPQkVcLFVcQUhNXGJZRFpaREVKSFxnQUJITUNCUlw/QVxUREFcZEpCXDpBSURUXDtVXE5EQVJER0JcO0FGSE1cYllGVEFJREFFRllWTkJIXGRLTlNCRkdJXC1GV1NORkhNQ05DRFBFRkhNSEZJUEdGT0FFU0RXXGtFS0ZJQVhPQkVTQUpRU0JKR0FJRFwsQVwnSUpRRkFXREhFUFJSRklKREhVXERCXHZEUElPWUlEQVxiTlZKRVNcJ1xkXC5BXFREQVxkSkJcLEFJRFRcO1VcVERUXDpBWkJHV1NGSFdOSURBXGRHQkZSXDpBRlx5XCxBQ0JHQlwnUUNOR1BcYlw7VVxGREdBSkhBQ0ZJVExcZEJGQ0FWU0ZJQVxkR0JGUlFSRllXRFJCVVxXU0JIQVZOU0Zcdk5FU1BYWE9CTURYWEFDSlFSREdJRk9BV0RKT1wsVVxNUEVJQVxnSlx2TlBRWkZQRUJcOkFDQkdCXCdRQ05HQkVaQldJS0ZJQVJGXGtCUVdGT0ZSSklceUxFREFPREhcZ0FPSlhCXDtVXEZER0FWU0RBVkRQT01cYkJGR0FDTlZTSlpRRkhNRVdER0hFTElKUkJcLEtORFpaR0JFRURHXCdRVkdESFxnXCxBQ05aR0RQTVJGSFwnUVdESElQUkJPXHlcLEtOWkZIXGdFTFxkSkVaR0pcelwnTU9EXHZCXCxBQ05PRlZcJ1FcZEJPRlx5XCxLTkpIRURPQkhXQkxEWFhKV05GSE1DTkVaUEdIRUtGSUFaRklKQkhJQVJCR0pJTENOUEhWREdDWUlGXGtCRVwsVVxXU0JIQVNOU0pSRUJPWEFSSlxnU0lBU0pRXHFQSkJJUFFSRlxrQlVcV0pDQUZBXGJGR05cYkRcZFxrSkhcP0FcV1NEQVZEUE9NQ0JFTlhGR1xkQk9RXGJCRkdcLFVcVERBXGdHUEhJQUZITUVWQkZJQVBIXGRCR0FGQVZCRkdZT0pYQlwsVVxCUElBQ0ZJQUNOXGRHQkZcZExFRFJCQ0pIXGdBRlhJQkdBXGRCRkNcLEtOUEhcZEpFV0RcdkJHXCdNV0RQSElHWVhHRFJBVlNERU5cYkRQR0hVXE5EQUlHRlx2Qk9PQkdBR0JJUEdIRVwsQVpQXHpcek9CUUNOVkpPT1VcQUhNUkZca0JRUFFHRkNCR0FcYkJGR0FDREVOSk9PUVZOU0ZcdkJLRkhBWE9ZSURBRENCR1FDRklBVk5ca0hEVkFIRElBRFhcP0tQUVdESEVXSkJIV05cZERCUVJGXGtOV0RWRkdcZEVMUFFGT09cO1VcQUhNQ1BRQ05IRklKXHZOU1BCTEdCRURPUElKREhVXElRRUpXXGtPSkJNRFwnQkdBVkpDQUNOWkZPTldGRUlMQ0RQXGdTSVwsVVxBSE1CSElCR1pHSkVCRUxcZ0dCRklBWkpDQUZITVJEUkJISVVcV0pDQUNKUUdCXGdGR01DQkpHQVdQR0dCSElRSVBHSEFGVkZceVwsVVxBSE1PREVOQ05IRlJCTEZXSUpESFwuXC1cLVxTRFhJQVx5RFBBSERWXCFLTlhGSkdBXE9aU0JPSkZcIUFcTlx5UlpTXCxBSkhBQ1lER0pFREhFVVxCTkZPT0FSWUVKSFFHQlJCUlxiQkdcJ1xkXC4=) -> 1553
```
Z{\p}Y{\yA}X{\f}W{\c}V{\w}U{\
}T{AEOBBZ}S{\h}R{\m}Q{EA}P{\u}O{\l}N{BA}M{\dA}L{ADXA}K{U\TS}J{\i}I{\t}H{\n}G{\r}F{\a}E{\s}D{\o}C{IS}B{\e}A{\ }\TDA\bB\,ADGAHDIAIDA\bB\:ACFIAJQCN\qPBEIJDH\:U\WSBCBGA\'IJQHD\bOBGAJHACNRJHMIDAEPXXBGKNEOJH\gQFHMFGGDVELDPIGF\gBDPQXDGIPHB\,U\OGAIDAIF\kNFGRQF\gFJHEIAFAEBFLIGDP\bOBE\,U\AHM\bYDZZDEJH\gABHMCBR\?A\TDA\dJB\:AIDT\;U\NDARDGB\;AFHM\bYFTAIDAEFYVNBH\dKNSBFGI\-FWSNFHMCNCDPEFHMHFIPGFOAESDW\kEKFIAXOBESAJQSBJGAID\,A\'IJQFAWDHEPRRFIJDHU\DB\vDPIOYIDA\bNVJES\'\d\.A\TDA\dJB\,AIDT\;U\TDT\:AZBGWSFHWNIDA\dGBFR\:AF\y\,ACBGB\'QCNGP\b\;U\FDGAJHACFITL\dBFCAVSFIA\dGBFRQRFYWDRBU\WSBHAVNSF\vNESPXXOBMDXXACJQRDGIFOAWDJO\,U\MPEIA\gJ\vNPQZFPEB\:ACBGB\'QCNGBEZBWIKFIARF\kBQWFOFRJI\yLEDAODH\gAOJXB\;U\FDGAVSDAVDPOM\bBFGACNVSJZQFHMEWDGHELIJRB\,KNDZZGBEEDG\'QVGDH\g\,ACNZGDPMRFH\'QWDHIPRBO\y\,KNZFH\gEL\dJEZGJ\z\'MOD\vB\,ACNOFV\'Q\dBOF\y\,KNJHEDOBHWBLDXXJWNFHMCNEZPGHEKFIAZFIJBHIARBGJILCNPHVDGCYIF\kBE\,U\WSBHASNSJREBOXARJ\gSIASJQ\qPJBIPQRF\kBU\WJCAFA\bFGN\bD\d\kJH\?A\WSDAVDPOMCBENXFG\dBOQ\bBFG\,U\TDA\gGPHIAFHMEVBFIAPH\dBGAFAVBFGYOJXB\,U\BPIACFIACN\dGBF\dLEDRBCJH\gAFXIBGA\dBFC\,KNPH\dJEWD\vBG\'MWDPHIGYXGDRAVSDEN\bDPGHU\NDAIGF\vBOOBGAGBIPGHE\,AZP\z\zOBQCNVJOOU\AHMRF\kBQPQGFCBGA\bBFGACDENJOOQVNSF\vBKFHAXOYIDADCBGQCFIAVN\kHDVAHDIADX\?KPQWDHEWJBHWN\dDBQRF\kNWDVFG\dELPQFOO\;U\AHMCPQCNHFIJ\vNSPBLGBEDOPIJDHU\IQEJW\kOJBMD\'BGAVJCACNZFONWFEILCDP\gSI\,U\AHMBHIBGZGJEBEL\gGBFIAZJCAFHMRDRBHIU\WJCACJQGB\gFGMCBJGAWPGGBHIQIPGHAFVF\y\,U\AHMODENCNHFRBLFWIJDH\.\-\-\SDXIA\yDPAHDV\!KNXFJGA\OZSBOJF\!A\N\yRZS\,AJHACYDGJEDHEU\BNFOOARYEJHQGBRBR\bBG\'\d\.
```
### [sandor weores monkeyland](https://deadfish.surge.sh/splinter#WntFRH1Ze1xjfVh7RkxDfVd7SEJ9VntcZ31Ve0pCSn1Ue0dEfVN7XGZ9Untcd31Re1xtfVB7XHV9T3tCQX1Oe1xkQn1Ne1xsfUx7XGh9S3tcb31Ke1wKfUl7XHJ9SHtcc31He1xpfUZ7XHR9RXtcYX1Ee1xufUN7XGV9QntcIH1Be1FLRFxrQ1x5fUhaXGRLSUJSQ0tJQ0hPTVpcZFVLTEJTS0lCU0VJS1NTT01aXGRKSUdccENPXGJJQ0VOS0RCXGJFS1xiRVxiSEpaTlhCUlROSEZJUFFXS1BGT0ZQRENISlNJS1FPUlRcZEtST1xiRUlIVUFMQ0lLQ1dJR0hDQlpOU0dWTEZKVE9TR0NNTlpOQUhccVBFSUNKWk5BSFpFRktJR1BRSEpMRVx2Q09ccEVGR0NERldZSVx5VFZCWElDVUFWR0lNT0ZFUFZMRkpRRUhGQ0lIT0VNXHBMRVxiQ0ZKQ1x2R01PQlxwS1BEXGRXTEdXRkxJRVJESlNDQ0ZCVE9ccElHSEtEQlx5Q0ZVQVFHTU1CR1dEQ0VJTVx5QlFFXGRDSlFHTUNXS1NPUUVceUtEREVHSENKUlREVFZNXHlCUERSVERFXGJNQ0pSVERUVk9RVE5SVFdccElFR0hDVUFca1RWQktET1xwS01DSkxFSVpWUENXWEJZSUtSTlRPRktEVlBDSkFMQ0VcdkNEQllLUUNXRktCSEtRQ0pBTENNTUJTS0lCRkxLSENCUERcZEtEQ1VRRVlFXHFQQ0JWS0lHTU1FQllMR1FccFpcekNDSlxiRVxiS0tEQktJWlZQRlpCQ0VZTEJcYkNFSEZKSUNFXGRXTEdIT0RDUkhITENDRkJFRkpYQkNETktTQkNFWUxCRlJHTUdWTEZCSUNccEVIRlVSR0ZMT0hQXHBccENJQlFDUUtJR0NISlhPS1BGTExLUEhDQklQUVxiTUNXTFBRSEpBSFJFXGRcZEdDV0hGRUlGQkZLQlFFSVlMSklHVkxGQkZQSURCTUNTRkJGUElEQkhMS1BNXGRDSUJFSVFIVUFRR01HRkVJXHlCU0lHVkxGSklDU01DWUZDTlRCQ0VZTE9TRVlDSlJHRkxPVlBEQlRPU0dIRkpYT1dSS0lNTlhCUktJTU5SQ0JTRVlD) -> 864
```
Z{ED}Y{\c}X{FLC}W{HB}V{\g}U{JBJ}T{GD}S{\f}R{\w}Q{\m}P{\u}O{BA}N{\dB}M{\l}L{\h}K{\o}J{\
}I{\r}H{\s}G{\i}F{\t}E{\a}D{\n}C{\e}B{\ }A{QKD\kC\y}HZ\dKIBRCKICHOMZ\dUKLBSKIBSEIKSSOMZ\dJIG\pCO\bICENKDB\bEK\bE\bHJZNXBRTNHFIPQWKPFOFPDCHJSIKQORT\dKRO\bEIHUALCIKCWIGHCBZNSGVLFJTOSGCMNZNAH\qPEICJZNAHZEFKIGPQHJLE\vCO\pEFGCDFWYI\yTVBXICUAVGIMOFEPVLFJQEHFCIHOEM\pLE\bCFJC\vGMOB\pKPD\dWLGWFLIERDJSCCFBTO\pIGHKDB\yCFUAQGMMBGWDCEIM\yBQE\dCJQGMCWKSOQE\yKDDEGHCJRTDTVM\yBPDRTDE\bMCJRTDTVOQTNRTW\pIEGHCUA\kTVBKDO\pKMCJLEIZVPCWXBYIKRNTOFKDVPCJALCE\vCDBYKQCWFKBHKQCJALCMMBSKIBFLKHCBPD\dKDCUQEYE\qPCBVKIGMMEBYLGQ\pZ\zCCJ\bE\bKKDBKIZVPFZBCEYLB\bCEHFJICE\dWLGHODCRHHLCCFBEFJXBCDNKSBCEYLBFRGMGVLFBIC\pEHFURGFLOHP\p\pCIBQCQKIGCHJXOKPFLLKPHCBIPQ\bMCWLPQHJAHRE\d\dGCWHFEIFBFKBQEIYLJIGVLFBFPIDBMCSFBFPIDBHLKPM\dCIBEIQHUAQGMGFEI\yBSIGVLFJICSMCYFCNTBCEYLOSEYCJRGFLOVPDBTOSGHFJXOWRKIMNXBRKIMNRCBSEYC
```
### [Four score and seven years ago our fathers brought forth](https://deadfish.surge.sh/splinter#WntBSFBJRUh9WXtCSkF9WHtcY31Xe1x2fVZ7S0JHfVV7QVxmfVR7XGd9U3tCTVx3TFhESEFIRUNBfVJ7QVx3fVF7SkJKSVhQfVB7REN9T3tcbH1Oe1xzfU17XCxBfUx7QkF9S3tcaH1Ke1xkfUl7XGl9SHtcbn1He1xyfUZ7QUNLfUV7XG99RHtcYX1De1x0fUJ7XGV9QXtcIH1cRkVcdUdBTlhFR0xESEpBTkJXQkhBXHlCREdOQURURUFFXHVHVVBWTkFcYkdFXHVUS0NVRUdDS0FFSEZJTkFYRUhDSUhCSENBREFIQlx3Wk1YRUhYQklXWUlIQU9JXGJCR0NceU1ESEpBUVlDRUZMXHBHRVxwRU5JQ0lFSEZQQURPT0FcbUJIQURHTFhHQlBZQlxxXHVET1wuQVxORVx3UkxER0xCSFREVFlJSEFEQVRHQlBBWElXSU9SREdNQ0JOQ0lIVFJLQkNWRlBaTUVHQURIXHlaQU5FQVhFSFhCSVdZREhKQU5FQVFCSk1YREhBT0VIVEFCSEpcdUdCXC5BXFdMREdMXG1CQ0FFSEFEQVRHQlBBXGJQQ09CXGZJQk9KQUVcZkZQUkRHXC5BXFdMS0RXTFhFXG1MQ0VBUUxEQVxwRUdDSUVIQUVcZkZQVUlCT0pNRE5BRFVJSERPQUdCTkNJSFRBXHBPRFhMXGZFR0ZFTkxcd0tFQVZMVERXQkZCSUdBT0lXQk5GUEZQWkFcbUlUS0NBT0lXQlwuQVxJQ0FJTkFET0NFVEJDVlVJQ0NJSFRBREhKQVxwR0VccEJHRlBSTE5LRVx1T0pBSkVGSU5cLkFcQlx1Q01JSEFEQU9ER1RCR0FOQkhOU1FTWEVITkJYR1BTS0RPT0Vcd0ZJTkFUR0VcdUhKXC5BXFRLTFxiR0RXTFxtQkhNT0lXSUhUQURISkFKQkRKTVx3S0VBTkNHXHVUVE9ZVkJNS0RXTFhFSE5CWEdQWUlDTVxmREdBRFxiRVdMRVx1R0FccEVFR0FccEVcd0JHQUNFQURKSkFFR0FKQkNHRFhDXC5BXFRLTFx3RUdPSlJJT09BT0lDQ09MSEVDQk1IRUdBT0VIVEFHQlxtQlxtXGJCR1JLUFJMTkRceUFWQk1cYlx1Q0FJQ0FYREhBSEJXQkdVRUdUQkNSS1BGQlx5QUpJSkFWQlwuQVxJQ0FJTlVFR0FcdU5GTE9JV0lIVE1HUFZNQ0VBXGJMUVlWTENFRkxcdUhcZklISU5LQkpSRUdca1JLSVhLRkJceVJLRVVFXHVUS0NBVkxLRFdCRlx1TlVER0FORUFIRVxiT1x5QURKV0RIWEJKXC5BXElDQUlOQUdQVlVFR0FcdU5BQ0VBXGJMVkxRWUNFRkxUR0JQQUNETlxrQUdCXG1ESUhJSFRBXGJCXGZFR0xcdU5cLUNLUFVHRVxtRkJOTEtFSEVHWUpCREpSTENEXGtMSUhYR0JETllKQldFQ0lFSEFDRUZQQVhEXHVOTFxmRUdSS0lYS0ZCXHlBVERXQkZMT0ROQ1VcdU9PQVxtQkROXHVHTEVcZkFKQldFQ0lFSFwtQ0tQUkxWTEtJVEtPXHlBR0JORU9XQkZQRkJOTEpCREpBTktET09BSEVDQUtEV0xKSVlJSEFXRElIXC1DS1BGSU5aTVx1SEpCR0FcR0VKTU5LRE9PQUtEV0xEQUhCXHdBXGJJR0NLQUVcZlVHQkJKRVxtXC1ESEpGUEFURVdCR0hcbUJIQ0FFXGZGTFxwQkVccE9CTVxiXHlGTFxwQkVccE9CTVxmRUdGTFxwQkVccE9CTU5LRE9PQUhFQ0FccEJHSU5LVUdFXG1GTEJER0NLXC4=) -> 1391
```
Z{AHPIEH}Y{BJA}X{\c}W{\v}V{KBG}U{A\f}T{\g}S{BM\wLXDHAHECA}R{A\w}Q{JBJIXP}P{DC}O{\l}N{\s}M{\,A}L{BA}K{\h}J{\d}I{\i}H{\n}G{\r}F{ACK}E{\o}D{\a}C{\t}B{\e}A{\ }\FE\uGANXEGLDHJANBWBHA\yBDGNADTEAE\uGUPVNA\bGE\uTKCUEGCKAEHFINAXEHCIHBHCADAHB\wZMXEHXBIWYIHAOI\bBGC\yMDHJAQYCEFL\pGE\pENICIEHFPADOOA\mBHADGLXGBPYB\q\uDO\.A\NE\wRLDGLBHTDTYIHADATGBPAXIWIORDGMCBNCIHTRKBCVFPZMEGADH\yZANEAXEHXBIWYDHJANEAQBJMXDHAOEHTABHJ\uGB\.A\WLDGL\mBCAEHADATGBPA\bPCOB\fIBOJAE\fFPRDG\.A\WLKDWLXE\mLCEAQLDA\pEGCIEHAE\fFPUIBOJMDNADUIHDOAGBNCIHTA\pODXL\fEGFENL\wKEAVLTDWBFBIGAOIWBNFPFPZA\mITKCAOIWB\.A\ICAINADOCETBCVUICCIHTADHJA\pGE\pBGFPRLNKE\uOJAJEFIN\.A\B\uCMIHADAODGTBGANBHNSQSXEHNBXGPSKDOOE\wFINATGE\uHJ\.A\TKL\bGDWL\mBHMOIWIHTADHJAJBDJM\wKEANCG\uTTOYVBMKDWLXEHNBXGPYICM\fDGAD\bEWLE\uGA\pEEGA\pE\wBGACEADJJAEGAJBCGDXC\.A\TKL\wEGOJRIOOAOICCOLHECBMHEGAOEHTAGB\mB\m\bBGRKPRLND\yAVBM\b\uCAICAXDHAHBWBGUEGTBCRKPFB\yAJIJAVB\.A\ICAINUEGA\uNFLOIWIHTMGPVMCEA\bLQYVLCEFL\uH\fIHINKBJREG\kRKIXKFB\yRKEUE\uTKCAVLKDWBF\uNUDGANEAHE\bO\yADJWDHXBJ\.A\ICAINAGPVUEGA\uNACEA\bLVLQYCEFLTGBPACDN\kAGB\mDIHIHTA\bB\fEGL\uN\—CKPUGE\mFBNLKEHEGYJBDJRLCD\kLIHXGBDNYJBWECIEHACEFPAXD\uNL\fEGRKIXKFB\yATDWBFLODNCU\uOOA\mBDN\uGLE\fAJBWECIEH\—CKPRLVLKITKO\yAGBNEOWBFPFBNLJBDJANKDOOAHECAKDWLJIYIHAWDIH\—CKPFINZM\uHJBGA\GEJMNKDOOAKDWLDAHB\wA\bIGCKAE\fUGBBJE\m\—DHJFPATEWBGH\mBHCAE\fFL\pBE\pOBM\b\yFL\pBE\pOBM\fEGFL\pBE\pOBMNKDOOAHECA\pBGINKUGE\mFLBDGCK\.
```
### [There was an old lady who swallowed a fly](https://deadfish.surge.sh/splinter#Wntcd31Ze1xyfVh7XHN9V3tcaH1We1xjTH1Ve1xlfVR7XGF9U3tJWFpUXGxcbFJafVJ7XG99UXtcZlxsXHl9UHtcLFwKfU97XGR9TntXVX1Ne1xpXGdcZ1xsVU9JfUx7VFx0fUt7XGJcaVlPfUp7WFxwXGlPVVl9SXtcIH1Ie0lcdFJTSVRJfUd7RktDSlwsRkpDUVwsRX1Ge1wKXFNOQVx0Tkl9RXtcClxJSU9SXG5cJ1x0SVxrXG5SWklaV1x5SVhOQVx0RFwKXApCfUR7V0xJUVBcUFVZV1RccFhJWE5cJ1xsXGxJT1xpVVwufUN7SVx0UklWXGNXSVx0Tkl9QntcVE5ZVUlaVFhJVFxuSVJcbE9JXGxUT1x5SVpXUkFUSX1Be1NVT0l9QlFcLkVKUFxUV0xJWllNVFxuT0lNVFxuT0lcak1caVxuWFxpT1VJTllcLkZKQ1FcLEVLUFxIUlpJVFxiWFx1WU9IS1wuR1ZQXElcbVRcZ1xpXG5VSVx0V0xIVlwuRlZDS1wsR09SXGdQXFdXTElUSVdSXGdIT1JcZ1wuRk9SXGdDVlwsRlZDS1wsR1dSWVhVUFxTTklPXGlVT0lSXGZJXGNSXHVZWFVcLg==) -> 466
```
Z{\w}Y{\r}X{\s}W{\h}V{\cL}U{\e}T{\a}S{IXZT\l\lRZ}R{\o}Q{\f\l\y}P{\,\
}O{\d}N{WU}M{\i\g\g\lUOI}L{T\t}K{\b\iYO}J{X\p\iOUY}I{\ }H{I\tRSITI}G{FKCJ\,FJCQ\,E}F{\
\SNA\tNI}E{\
\IIOR\n\'\tI\k\nRZIZW\yIXNA\tD\
\
B}D{WLIQP\PUYWT\pXIXN\'\l\lIO\iU\.}C{I\tRIV\cWI\tNI}B{\TNYUIZTXIT\nIR\lOI\lTO\yIZWRATI}A{SUOI}BQ\.EJP\TWLIZYMT\nOIMT\nOI\jM\i\nX\iOUINY\.FJCQ\,EKP\HRZIT\bX\uYOHK\.GVP\I\mT\g\i\nUI\tWLHV\.FVCK\,GOR\gP\WWLITIWR\gHOR\g\.FOR\gCV\,FVCK\,GWRYXUP\SNIO\iUOIR\fI\cR\uYXU\.
```
### [The other day](https://deadfish.surge.sh/splinter#Wntcd0ZceUF9WXtcCn1Ye1xnQ0RcbUNBR1x1REdcZkFcaENLQ1whXCJZfVd7XCJcTkdcd0FcbENcZ09BXGdDRFxnR1xpTVxnQn1We1xBTVxkQU9HQVxJQX1Ve0NCXEJcdURLXGlcZ1xoRFxiQ1xoXGlNXGRBXG1DQn1Ue1xBTVxkQVx0S1x1T0RcbVx5QVxsXHVcY1xrXC5ZfVN7XCJQRlx0XCdPQUZBXGdHR1xkQVxpXGRDRlwuXCJZfVJ7XFNHQVxJQUlHXHVcZ1xoRFxJXCdcZEFcalx1XG1ccH1Re1xPTUFJQ0FaXGJGXGNca0FcZEdcd01cIVl9UHtcVFxofU97XHN9TntBXGxHR1xrQ1xkQUZEfU17XG59THtBT1xpXHpDXGRBXHVccEF9S3tccn1Ke0JcQUFcZ0tDRkRcYlxpXGdBfUl7XHRcaH1Ie0RcYktGTVxjXGhCfUd7XG99RntcYX1Fe0FcZEdNXCdEXHlHXHVBfUR7XHRBfUN7XGV9QntcLFl9QXtcIH1QQ0FHSUNLQVxkRlx5QlBDQUdJQ0tBXGRGXHlCXElBXG1DREZBXGJDRktCXElBXG1DREZBXGJDRktKXGJDRktKXGJDRktCXE9caEFaR1x1RElDS0NcLllcT1xoQVpHXHVESUNLQ1wuWVlQQ0FHSUNLQVxkRlx5QlxJQVxtQ0RGQVxiQ0ZLSlxiQ0ZLQlxPXGhBWkdcdURJQ0tDXC5ZWVxIQ05cbUNCXEhDTlxtQ0JcSU5caFxpXG1CXElOXGhcaVxtQlxIQ0xcbUNCXEhDTFxtQ0JcSUxcaFxpXG1cLllcSUxcaFxpXG1cLllZXEhDTlxtQ0JcSU5caFxpXG1CXEhDTFxtQ0JcSUxcaFxpXG1cLllZXEhDQU9GXGlcZEFcdEdBXG1DQlxIQ0FPRlxpXGRBXHRHQVxtQ0JcIlxXXGhceUVLXHVNXD9ZXCJcV1xoXHlFS1x1TVw/WVxJQU9DQ0FceUdcdUFGXGlNXCdcdEJcSUFPQ0NBXHlHXHVBRlxpTVwnXHRCXEdHREZNXHlBXGdcdU1cLlwiWVxHR0RGTVx5QVxnXHVNXC5cIllZXEhDQU9GXGlcZEFcdEdBXG1DQlwiXFdcaFx5RUtcdU1cP1lcSUFPQ0NBXHlHXHVBRlxpTVwnXHRCXEdHREZNXHlBXGdcdU1cLlwiWVlcSUFPRlx5T0FcdEdBXGhcaVxtQlxJQU9GXHlPQVx0R0FcaFxpXG1CU1NXV1hYWVxJQU9GXHlPQVx0R0FcaFxpXG1CU1dYWVZLRk1CVktGTUJcQVpcZktHXG1BSUNLQ0JcQVpcZktHXG1BSUNLVVxCXHVES1xpXGdcaERcYkNcaFxpTVxkQVxtQ0JcV0ZPQUlGRFxiQ0ZLXC5ZXFdGT0FJRkRcYkNGS1wuWVlWS0ZNQlxBWlxmS0dcbUFJQ0tVXFdGT0FJRkRcYkNGS1wuWVlcSU1BXGZLR01ER1xmQVxtQ0JcSU1BXGZLR01ER1xmQVxtQ0JQQ0tDQVx3Rk9BRkFcdEtDQ0JQQ0tDQVx3Rk9BRkFcdEtDQ0pcdEtDQ0pcdEtDQ0JcT1xoQVxnXGxHS1x5QVxiQ1whWVxPXGhBXGdcbEdLXHlBXGJDXCFZWVxJTUFcZktHTURHXGZBXG1DQlBDS0NBXHdGT0FGQVx0S0NDSlx0S0NDQlxPXGhBXGdcbEdLXHlBXGJDXCFZWVBDQVxsR1x3Q09IUENBXGxHXHdDT0hcV0ZPQVx0Q01BXGZDQ0RcdVxwQlxXRk9BXHRDTUFcZkNDRFx1XHBCUkJSQlRUWVBDQVxsR1x3Q09IXFdGT0FcdENNQVxmQ0NEXHVccEJSQlRZVlxqXHVcbVxwQ1xkQlZcalx1XG1ccENcZEJcSU1cdEdBSUNBRlxpS0JcSU1cdEdBSUNBRlxpS0JcQlx1RFxJQVxtXGlPT0NcZEFJRkhcQlx1RFxJQVxtXGlPT0NcZEFJRkhcQUFaXHVccEFJQ0tDXC5ZXEFBWlx1XHBBSUNLQ1wuWVlWXGpcdVxtXHBDXGRCXElNXHRHQUlDQUZcaUtCXEJcdURcSUFcbVxpT09DXGRBSUZIXEFBWlx1XHBBSUNLQ1wuWVlcTkdcd0VcZktDXHRCXE5HXHdFXGZLQ1x0QlxBTVxkRVxmS0dcd01CXEFNXGRFXGZLR1x3TUJcSUFcQ0ZcdVxnXGhESUZIXElBXENGXHVcZ1xoRElGSFFRWVxOR1x3RVxmS0NcdEJcQU1cZEVcZktHXHdNQlxJQVxDRlx1XGdcaERJRkhRWVBcaU9BXGlPQUlDQUNNXGRCUFxpT0FcaU9BSUNBQ01cZEJQQ0tDQUZcaU1ETUdBXG1HS0NCUENLQ0FGXGlNRE1HQVxtR0tDQlxVTVxsQ09PQVxJQU9DQ0JcVU1cbENPT0FcSUFPQ0NCUEZEXGJDRktBR01cY0NBXG1HS0NcLllQRkRcYkNGS0FHTVxjQ0FcbUdLQ1wuWVlQXGlPQVxpT0FJQ0FDTVxkQlBDS0NBRlxpTURNR0FcbUdLQ0JcVU1cbENPT0FcSUFPQ0NCUEZEXGJDRktBR01cY0NBXG1HS0NcLg==) -> 1954
```
Z{\wF\yA}Y{\
}X{\gCD\mCAG\uDG\fA\hCKC\!\"Y}W{\"\NG\wA\lC\gOA\gCD\gG\iM\gB}V{\AM\dAOGA\IA}U{CB\B\uDK\i\g\hD\bC\h\iM\dA\mCB}T{\AM\dA\tK\uOD\m\yA\l\u\c\k\.Y}S{\"PF\t\'OAFA\gGG\dA\i\dCF\.\"Y}R{\SGA\IAIG\u\g\hD\I\'\dA\j\u\m\p}Q{\OMAICAZ\bF\c\kA\dG\wM\!Y}P{\T\h}O{\s}N{A\lGG\kC\dAFD}M{\n}L{AO\i\zC\dA\u\pA}K{\r}J{B\AA\gKCFD\b\i\gA}I{\t\h}H{D\bKFM\c\hB}G{\o}F{\a}E{A\dGM\'D\yG\uA}D{\tA}C{\e}B{\,Y}A{\ }PCAGICKA\dF\yBPCAGICKA\dF\yB\IA\mCDFA\bCFKB\IA\mCDFA\bCFKJ\bCFKJ\bCFKB\O\hAZG\uDICKC\.Y\O\hAZG\uDICKC\.YYPCAGICKA\dF\yB\IA\mCDFA\bCFKJ\bCFKB\O\hAZG\uDICKC\.YY\HCN\mCB\HCN\mCB\IN\h\i\mB\IN\h\i\mB\HCL\mCB\HCL\mCB\IL\h\i\m\.Y\IL\h\i\m\.YY\HCN\mCB\IN\h\i\mB\HCL\mCB\IL\h\i\m\.YY\HCAOF\i\dA\tGA\mCB\HCAOF\i\dA\tGA\mCB\"\W\h\yEK\uM\?Y\"\W\h\yEK\uM\?Y\IAOCCA\yG\uAF\iM\'\tB\IAOCCA\yG\uAF\iM\'\tB\GGDFM\yA\g\uM\.\"Y\GGDFM\yA\g\uM\.\"YY\HCAOF\i\dA\tGA\mCB\"\W\h\yEK\uM\?Y\IAOCCA\yG\uAF\iM\'\tB\GGDFM\yA\g\uM\.\"YY\IAOF\yOA\tGA\h\i\mB\IAOF\yOA\tGA\h\i\mBSSWWXXY\IAOF\yOA\tGA\h\i\mBSWXYVKFMBVKFMB\AZ\fKG\mAICKCB\AZ\fKG\mAICKU\B\uDK\i\g\hD\bC\h\iM\dA\mCB\WFOAIFD\bCFK\.Y\WFOAIFD\bCFK\.YYVKFMB\AZ\fKG\mAICKU\WFOAIFD\bCFK\.YY\IMA\fKGMDG\fA\mCB\IMA\fKGMDG\fA\mCBPCKCA\wFOAFA\tKCCBPCKCA\wFOAFA\tKCCJ\tKCCJ\tKCCB\O\hA\g\lGK\yA\bC\!Y\O\hA\g\lGK\yA\bC\!YY\IMA\fKGMDG\fA\mCBPCKCA\wFOAFA\tKCCJ\tKCCB\O\hA\g\lGK\yA\bC\!YYPCA\lG\wCOHPCA\lG\wCOH\WFOA\tCMA\fCCD\u\pB\WFOA\tCMA\fCCD\u\pBRBRBTTYPCA\lG\wCOH\WFOA\tCMA\fCCD\u\pBRBTYV\j\u\m\pC\dBV\j\u\m\pC\dB\IM\tGAICAF\iKB\IM\tGAICAF\iKB\B\uD\IA\m\iOOC\dAIFH\B\uD\IA\m\iOOC\dAIFH\AAZ\u\pAICKC\.Y\AAZ\u\pAICKC\.YYV\j\u\m\pC\dB\IM\tGAICAF\iKB\B\uD\IA\m\iOOC\dAIFH\AAZ\u\pAICKC\.YY\NG\wE\fKC\tB\NG\wE\fKC\tB\AM\dE\fKG\wMB\AM\dE\fKG\wMB\IA\CF\u\g\hDIFH\IA\CF\u\g\hDIFHQQY\NG\wE\fKC\tB\AM\dE\fKG\wMB\IA\CF\u\g\hDIFHQYP\iOA\iOAICACM\dBP\iOA\iOAICACM\dBPCKCAF\iMDMGA\mGKCBPCKCAF\iMDMGA\mGKCB\UM\lCOOA\IAOCCB\UM\lCOOA\IAOCCBPFD\bCFKAGM\cCA\mGKC\.YPFD\bCFKAGM\cCA\mGKC\.YYP\iOA\iOAICACM\dBPCKCAF\iMDMGA\mGKCB\UM\lCOOA\IAOCCBPFD\bCFKAGM\cCA\mGKC\.
```
### [This is the house that Jack built](https://deadfish.surge.sh/splinter#Wntcc31Ze09TXG5cZH1Ye1xpfVd7XG99Vntccn1Ve1xsfVR7XHR9U3tcYX1Se1xlXGR9UXtBXGhXXHVaXGVPTlxKU1xjXGtPXGJcdVhVVFwufVB7V1ZcbkN9T3tcIH1Oe1RcaFNUT31Ne0FcZlNWXG1cZVZPWldcd1hcblxnT1xoWFpPXGNQXGtcZVxwVEp9THtTVFxlQVxtU1VUfUt7XHdXVlZYUkFcY1NUQ1xrWFVVUkFWU1RPfUp7QVZXV1pUXGVWT05cY1ZXXHdST1hcbkFcbVBcd1dca1xlQUhFfUl7XApcClxUXGhYWk9YWn1Ie1xqXHVcZFxnXGVPU1VVT1pcaFNcdlxlXG5ZT1pcaFBcbVNWVlhSRkd9R3tYXGRcZVxuT1NVVU9cZldWVVBcbVhVXGtSRH1Ge0FcbVNcbk9TVVVPVFNUVFxlVlJZT1RQXGtYWlpSQVxtU31Fe0NLQ0xCfUR7QVxjV1x3T1x3WFRcaEFcY1ZcdVxtXHBVUk9caFBUV1paUkFcZFdcZ099Q3tcClxUXGhTVE99QntDVVNceU9YXG5RfUF7T1RcaFxlT31cVFxoWFpPWFpRSUFcbVNVVE9CSUFWU1RPQ0xCSUFcY1NUT0Nca1hVVVJBVlNUQ0xPQklBXGRXXGdPRUlERUlBXG1TR05LTkxCSUZHTktOTEJJQUhFSUpJTUlBXGhXVlpcZVlBXGhXXHVcblxkWUFcaFBcYlxlVVdcblxnUk9UV00=) -> 563
```
Z{\s}Y{OS\n\d}X{\i}W{\o}V{\r}U{\l}T{\t}S{\a}R{\e\d}Q{A\hW\uZ\eON\JS\c\kO\b\uXUT\.}P{WV\nC}O{\ }N{T\hSTO}M{A\fSV\m\eVOZW\wX\n\gO\hXZO\cP\k\e\pTJ}L{ST\eA\mSUT}K{\wWVVXRA\cSTC\kXUURAVSTO}J{AVWWZT\eVON\cVW\wROX\nA\mP\wW\k\eAHE}I{\
\
\T\hXZOXZ}H{\j\u\d\g\eOSUUOZ\hS\v\e\nYOZ\hP\mSVVXRFG}G{X\d\e\nOSUUO\fWVUP\mXU\kRD}F{A\mS\nOSUUOTSTT\eVRYOTP\kXZZRA\mS}E{CKCLB}D{A\cW\wO\wXT\hA\cV\u\m\pURO\hPTWZZRA\dW\gO}C{\
\T\hSTO}B{CUS\yOX\nQ}A{OT\h\eO}\T\hXZOXZQIA\mSUTOBIAVSTOCLBIA\cSTOC\kXUURAVSTCLOBIA\dW\gOEIDEIA\mSGNKNLBIFGNKNLBIAHEIJIMIA\hWVZ\eYA\hW\u\n\dYA\hP\b\eUW\n\gROTWM
```
### [Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo](https://deadfish.surge.sh/splinter#Q3tBXCBcQkF9QntcdVxmXGZcYVxsXG99QXtCXCBcYkJ9XEJDXCBcYkM=) -> 41
```
C{A\ \BA}B{\u\f\f\a\l\o}A{B\ \bB}\BC\ \bC
```
] |
[Question]
[
Befunge Chess is an esolang mini-game I invented that is centered around the [Befunge](https://esolangs.org/wiki/Befunge) esolang. The general gist of the game is to make the instruction pointer land on a specific target cell while avoiding the opponent's target cell.
Today's challenge isn't to play the game, but to simply execute arbitrary boards.
## The Rules of Befunge Chess (Context)
Quoting the Befunge esolangs article:
>
> A Befunge program is laid out on a two-dimensional playfield of fixed size. The playfield is a rectangular grid of ASCII characters, each generally representing an instruction. The playfield is initially loaded with the program. Execution proceeds by the means of a [instruction pointer]. This points to a grid cell on the playfield. The instruction pointer has inertia: it can travel to any of the four cardinal directions, and keep traveling that way until an instruction changes the direction. The instruction pointer begins at a set location (the upper-left corner of the playfield) and is initially travelling in a set direction (right). As it encounters instructions, they are executed. [C]ontrol flow is done by altering the direction of the [instruction pointer], sending it to different literal code paths.
>
>
>
*[Source](https://esolangs.org/wiki/Befunge)*
Befunge chess is a 2-player game. The players are called `A` and `B`
At the start of the game, a board is randomly generated with two cells already filled, like so:
```
.....
.....
.A...
.....
...B.
```
The `A` and the `B` can go anywhere on the board - their position is arbitrary. However, they cannot go in the top left corner where the instruction pointer would start.
Players take turns placing commands from a modified subset of Befunge commands onto the board in an attempt to make the instruction pointer reach their target square. These commands will be described in their own section. The board is not executed during this phase.
On a player's turn, if they feel that the instruction pointer will land on their target cell, they can choose to execute the board instead of placing a command. This initiates the end sequence of the game. If the instruction pointer does reach the executing player's target piece they win. If it doesn't (i.e. it a) reaches the opponent's target piece, b) reaches a cell it's already passed or c) errors), then the other player wins. *Note: stop condition b means that there aren't any infinite loops - hence there will always be an outcome for every possible board*
If the board is completely full, then execution is automatic. Errors/reaching an already passed square lead to a tie.
## Commands
While the full mini-game I devised uses 28 commands, you'll be required to implement an 8 command subset:
```
^ Set the instruction pointer's direction to up (north)
v Set the instruction pointer's direction to down (south)
< Set the instruction pointer's direction to left (west)
> Set the instruction pointer's direction to right (east)
# Jump over the next cell
. Do nothing (NOP)
A Player A's target piece
B Player B's target piece
```
## Execution
The instruction pointer starts in the top left corner (0, 0). It initially moves right (east). It transverses the board until one of the following conditions is met:
A) A player piece is reached
B) An error occurs
C) A cell is reached that has already been passed once
Note that if the instruction pointer would fall off the board (i.e. reach an edge), it "wraps around to the other side:
```
...> # upon reaching the >, the instruction pointer would wrap back to the first cell in the row
....
.v.. # if the v were reached, the instruction pointer would continuing heading down and then wrap around to the second column in the first row.
....
```
Your challenge is to output the outcome of executing the board.
## Testcases
* The board is guaranteed to contain an `A` and `B` piece
```
>....v.
.....A.
..B....
.......
```
Output: `A`
---
```
>.v..v.
....>A.
.<B....
..^....
```
Output: `B`
```
....
....
.AB.
....
```
Output: `Tie`
---
```
v.
AB
```
Output: `A`
Note that this is the smallest possible board you have to handle.
---
```
.v.
>.A
^<B
```
Output: `Tie`
This is because the middle cell is passed twice.
---
```
>v....
B#....
.A....
^>....
```
Output: `B`
---
```
...^^...
..<A>...
.^.v....
<B>.....
.v......
```
Output: `Tie`
## Extra Rules
* Input/output can be given in any reasonable/convenient format
* The board size will always be rectangular (have a length and a width), will always be valid (have `A`, `B` and a mixture of commands).
* The board size will always be 2x2 or larger.
* You can use any character set you like for the different tiles, as long as you have 8 consistent characters/values.
Finally, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in each language wins.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes
```
WS⊞υ⪪ι¹≔⁰θW¬№αψ«≔§§υⅉⅈψ§≔§υⅉⅈTF№>^<vψ≔⊗⌕>^<ψθM⊕⁼#ψ✳θ»⎚ψ
```
[Try it online!](https://tio.run/##fZDBTgMhEIbP3aeY0MuQYKNnzSZrq0kPmib1oJcmuItdEoQuC6uN8dlxStGjHPiHzDfzz9D20rdOmpQ@em0U4NoeYtgGr@0eOYdNHHuMArYHowNqAVecX1fNOOq9xUsBA71K5aMLuHTRBpQCjpyKv6pZIZuwtp36/FPq@ELtBTzn@0hdCvofKYA9sRP65jwUL1bvbiaWDaGYrVx8NarDe227nD@nz8POHtykaMvWq3dlA2F3Q5RmRDb/xVbaqzZoZ3E4LftdLY2SHinc0LcEpGlTqqcFnep2nmXRZNnVWdLFZH4A "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated list of strings and outputs `A` or `B`, or `T` for a tie. Explanation:
```
WS⊞υ⪪ι¹
```
Input the map and split it into characters.
```
≔⁰θ
```
Start off facing right.
```
W¬№αψ«
```
Repeat while the last seen character is not a letter.
```
≔§§υⅉⅈψ
```
Look at the current character in the map. Charcoal's array indexing is cyclic, so although I'm wandering around the canvas, I'm still seeing the correct character here.
```
§≔§υⅉⅈT
```
Replace the character with a `T` to show that we've seen it before.
```
F№>^<vψ
```
If the current character is a direction, then...
```
≔⊗⌕>^<ψθ
```
... update the direction variable.
```
M⊕⁼#ψ✳θ
```
Move one or two steps in the current direction as appropriate.
```
»⎚ψ
```
Output the winner.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 134 bytes
```
f=D=>eval('for(w=D[c=x=y=X=0].length,h=D.length;c--||(c=D[y][x],D[y][x]=f,c>2?c=[,X=c-4]:c<f);y=(--t%2+y+h)%h)x=-(t=X,--t%2-x-w)%w;c')
```
[Try it online!](https://tio.run/##ZY9tb4IwFIW/8ytIjbGNtHGLe4lwu0D8ESYOIlYZLg5JZRUy99vZ5UXnsn55Tk/PPTd9j018VHqXF9w813UCc5BbE@/pKDloeoL5UkEJFSxgEor9NnsrUieFeS9dxfn5TBXGqnBZhk5PSBwl718ULJ0FKD4NZ8pLmFsB5bwY3o@rccqGKSuB0wIWTmvykp/Y8OSqEatNrO2POLfB/iI@mZGYOCRArpEe8hEpkVNkhHxAGuQTUiAnyAHyjjjfltW06c8M2@j6EOsNs0Haud5lBU06Rxzz/a6g5DUjTOBiqpuIvti9uWlMFMtNyPC4loWtdCUFHiOsBsJvGDSquwuxugmaa1A2Qe8SjP4Gr@OW8INO/T5igR/cZPEuhW9F3o0pTTsdDPqSFpH8tyWKuk2eL1sRiW7QC9osOub6ifoH "JavaScript (V8) – Try It Online")
Optimized from tsh's, input map `{"A":"a","B":"b","<":"6",">":"4","^":"5","v":"7",".":"0","#":"1",}`
# [JavaScript (V8)](https://v8.dev/), 153 bytes
```
f=D=>eval('x=y=Y=0,X=1;for(w=D[0].length,h=D.length;c=D[y][x],D[y][x]=f,+c?Y=![X=c-4]:1/c?(x+=X,y+=Y):c+1-0?Y=c+1-[X=0]:0,c<f;x=(x+X+w)%w)y=(Y+y+h)%h;c')
```
[Try it online!](https://tio.run/##ZY9hb4IwEIa/8yuwxtgG6DDbkgU4DMQfAWEQEWW6OCTIKmTZb2dXQOeyfnmu1@fuTd9TkZ6z6lDWhnjpuhxW4O5EeqTzBloIwdQDWNj5qaIXWEVmzI@74q3e63tYjaWd4UMbR02sj4Rc17JlCJMogMx4iq3FQ7akjQaB3moQMivTFoaJgiQ6ZmyZeubkdgNoBdqFzS6sBRpqrbZnM0yYs06klfqRliqoX8QjFkmJTnzkBukgH5Eu8hmZIA2kQGpIjpwgp0iT6N@KIrdVnwVuo5tTWm2ZCq5aVoeipvnQ4efyeKgpeS0I4xhMK6lU1/bY3MomFtE2ZnhsRcGtdO1yPIIrEtyT9GU13Dlf34niJrpSdK5i8le8jSvc84fq9xEXeP6dK7iquNxTEsdX77JEP@9PxzU9EvdfTpIMWY7n9kXCh0HH713siNs3uh8 "JavaScript (V8) – Try It Online")
Rewritten from Redwolf Programs's template
[Answer]
# [JavaScript (V8)](https://v8.dev/), 218 bytes
*-3 thanks to @Arnauld*
```
d=>eval('x=y=r=0,p=[],q=1;while(((m=d[y][x])-6)*(m-7)*!p.includes(w=x+[,y])){p.push(w);[q,r]=[[0,-1],[1,0],[0,1],[-1,0],[q,r],[q,r]][m];x=(x-q*~(m==5)+(z=d[0].length))%z;y=(y-r*~(m==5)+(z=d.length))%z};"AB"[m-6]||"T"')
```
[Try it online!](https://tio.run/##ZY/RboIwFIbveQqGWWy1bfBibgmUBF5gN7vrSmSCkwUYFqzg3F6dtaAOs170/Ofvd86ffkQyqtYiLWssn7oN7WLqJTLKwLShLRXURiVlHO3owjls0ywBAOQ0Zi1nDYd4CWcgx49wdleStFhn@zipwIE2c4ZaDuFXScp9tQUH6LAdEpwyZiO84IgtkK1uG2mNh0YDw81Zzp2GggbvZj8qjj7AOTiqVJuTLCne6y2E90enpaDF4oYYPX87lh9YLMdLfjpZL9YUdjISptgXJjXB22ckYmhSzyxFWtRgMzikKrO0BtZrYUGSRyUQGhEX@2zG2rRCT7pkojLUz@Oked6AGOrjGIYKASuPqCOJoQvxdQ20GnpCViNQXkFPg@4FDG/B67hB/GBQf49qgR@MWElMwyO@EbqBOcqS/XwwOa/pS@j9ywnDIcv1vV6EZBh0g55Vjrx@o/sF "JavaScript (V8) – Try It Online")
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 134 bytes
```
f=lambda s,r=0,c=0,d=5,*v:(g:=s[r][c])//9+((r,c)in v)or f(s,(r+(d:=g%8or d)//3*(k:=g//8+1)-k)%len(s),(c+d%3*k-k)%len(s[0]),d,*v,(r,c))
```
[Try it online!](https://tio.run/##TZDvasIwFMW/36cIDGmiWfxTRFfaQPsM@9a1w7XqilpL0hVk7NndvYm6Fcr9Jfecc5N0l/7z3Ibrzlyvu@S4OX3UG2alSWaywr9OlnI8RHwfJTY3RV4VYjp9mXBuZCWalg3ibNiOW8nNhNdRsh@tcaNGUTjmB1xPp@vJXDwfxOi4bbkVkleTehSOD4@tfFYIWeMU6ULFtTl1Z9Mze7EATdu9nzqWsG9gQRlEbC4RBoQVQYwQEmiEJcETwppAIcwIUnK5rQxpsYIfgPNX/5c7j1jw2mwDlCwi0iOEEclJWm3s1qIQj6NsXzetMttNzYWy3bHpefDWvrWBgB1em6QMH8VZIkDsJKNRaKc9ZR6eQLK5cArs5bm/Jr4uczkUYj1bYmz/jQtEAawzTdvz2zXyHUeFKFiSuHHiqhV@gwIqKqWaEfk11hRAY/8u0SSJ75LS1QzgYQGVZjfChwJAW5pRCAVolUIZZ76jB29@utlcKfW/xLL0qXGqHZTKW@JM@7P5tR/1Cw "Python 3.8 (pre-release) – Try It Online")
Takes advantage of the looser input/output formats. In particular the input grid is mapped in the following way: `{ '^': 1, 'v': 7, '<': 3, '>': 5, '#': 8, '.': 0, 'A': 18, 'B': 27 }`. For output, it returns `1` on a tie, `2` if `A` wins, and `3` if `B` wins.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 125 bytes
```
a=>eval("for(d=5,w=a[x=y=0].length,h=a.length;(c=a[y%=h][x%=w])<9;d%2?x+=w+m:y+=h+m)a[y][x]='T',d=c>2?c:d,m=(d%3-1)*-~!+c;c")
```
[Try it online!](https://tio.run/##bY9db4IwFIbv@RWdhrQd2GwaFye0hv6G3TGIXdHBAkiQoWZxf521fBg1uzrvc857vr5ELfayTIpqUi@aLW0EZZtapGi03ZUoonP7QIV/pCf6FJB0k39WsR1T0UsHSVU9mTQO/KNJDwF2X53InK6OFj1Y2fJk0djKsLKoekDhG7QjKtl0JZeRnVEUmbPJM36c/D5Y0pEj3JTfOaDgYyfKCFAGfgwA0k0FxJAkVZlkCJN9kSYVgu85xCQTBUq12yeEpEHLUjPS7QBAFy4BnEG7o1DTy0BM03ygWtNiIKJpOtBY09NAniZvIK6Jt3T2ZYAxdpQsyiSv0BYJjI2zYxjqObQ2mLqS1MTQgXg6cq06VnGNr6z1xcq01R2s4b31MsIgHu/VVVkN8fiNX2UY8YzQvUmzuu3k435UG0L2z7Yw7Da6HmtFSLpWl7Puj47vHtLPjHm/uSs1fw "JavaScript (V8) – Try It Online")
```
'<': '3',
'^': '6',
'>': '5',
'v': '8',
'.': '2',
'#': '0',
'A': 'A',
'B': 'B',
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~149~~ 147 bytes [SBCS](https://github.com/abrudz/SBCS)
```
p v o g←(1 1)(0 1)⍬⎕
l←{v⊢←0 ¯1}
r←{v⊢←0 1}
u←{v⊢←¯1 0}
d←{v⊢←1 0}
b←{o,←⊂p⋄p+←v⋄p⊢←1+(⍴g)|p-1}
{o∊⍨⊂p:'T'⋄'.'=⍨x←p⌷g:b⍵⋄x∊⎕A:x⋄⍎x,'⍵⋄b⍵'}⍣{⊃⍵∊⎕A}0
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q7V8HOJq5MWeFR2ySFopzSlCQA&c=K1AoU8hXSH/UNkHDUMFQU8MASDzqXfOobypXDlCwuuxR1yIgbaBwaL1hLVcRihBQoBRJAKhCwaCWKwVJCCyQBBLI1wGSj7qaCh51txRoA9llIAZUlbbGo94t6Zo1BbpAI6vzH3V0PepdAVJspR6iDlSnrqduCxSpAKoteNSzPd0q6VHvVqB4BUhl31RHqwog51FvX4WOOkQCJK9e@6h3cfWjrmaQEERdrQEA&f=AwA&i=S@N61DZRvUgPCFL01BXUQQw9RwjLCcSGiYFYj3rnKjhypUG1pCBpKYJoyUFoKUVocYJqQTIORDk6IXggZSGZqVCFYGMdndAsTIFqdEqCmwBllBZhtay0FGZhjmMRlFmqBzMmx6lID2ZQCrIPEe6A@K9IzxFkR44TXBoA&r=tio&l=apl-dyalog&m=tradfn&n=f)
A tradfn submission which takes the grid as a character matrix. I'm sure there's multiple places to improve this.
`><^v# → rludb` and the rest of the instructions `.AB` remain the same.
[Here's a testcase converter, in case there are other inputs.](https://staxlang.xyz/#c=L%7B%22%3Er%3Cl%5Euvd%23b%22%7Ct%27%27%7CSmJ%27%E2%86%91s%2B&i=...%5E%5E...%0A..%3CA%3E...%0A.%5E.v....%0A%3CB%3E.....%0A.v......)
[Answer]
# [J](http://jsoftware.com/), 116 bytes
```
g=.1#.,@]
f=._3 g@{[:,/]((*0&=),:[(]]`]`(2*[)`[@.(|@g*4>|@g)(*0&~:))](%|)@|.~0j_1+.@*(*4>|)@g)/^:a:@,:]{:@,:0,~0{,^3~:,
```
[Try it online!](https://tio.run/##jVRrj6LYFv3urzCp3Jmybw3vhzhVFR4CCoKICkKnqhsRRB4i70d36q/3aFfPJPdmejLnw177JGvtvbLPzgm/qSwwDMryUkxAsDylQF6dwbu70Gb1DaY0wnzn011Z2SJWYsHOomI5kP1GhY5YL@7nM4qYBqxr@y2@P/EF7Eo8qu13Mu1CYyxMlger0oM5u8UvQtBk4m5GbuJ@y3OXWYdv2KM4Y45cysRcLCfnQiCaQlIlD65xMZEqtlwRrmIuA6pHNtoK00lOBnUwYaI43Sskdu4NGptqwWnlLsmthLXiNN8SmIB24qoxKpCEkMqYl8y8yRRVEeVKVJ3maEJoPteX5pHufWaryrWjVPgRmuG0auu4buRHSI3kDDzUEsNFbsMbHDdtIqZAd/Nc5JLDzt1UeBkraEQdc3sXBUHnrffwFJxnblFTucwlKtm3Glk4kh3RHjS2WtHibTQq2wyFiIWb9ActLQwQSfJSPHl2wjjq4lRLgV9qZIJM29N48LNXEcgQvzCCsgNxeLmqVIQrV4pM8JkxFhjd1AT9oG/DCkvlbHnMFjAIZ3C9Itd2iUTQOepjNKqXJIXoiR8LOCNUHkXna3G5tx1yChvw8aQcfMy4VEWgmxcV0dBzRksX/uDUO5zOjFBeCHob9d3cIhKnx60CLdlkiVyKmEKgue1JbX46F8yeXinEgc42ddl1EglztbCu3dMCzvIcGh@UnHNQQyt38SafyUmxdMwmllojwWKRzDo5AjfMeksUBUX2Tqt7xGVPb5cJap7Wud0dLQ5VMH2/oPYncw57s0VUmeJlf1CXGR5GfdWqMhJ127wV8CKIIb@jebvuSvzM6pWTXFRj1uoza5fwEF5cjD3VmStNIYhQLsQUj5VklxmWYZZ67pFmq5pCUfDJ0W0krlOKQ2MGAodhMR1IJiw0UoiEpKF5RWQV48o2iQ4qnB6ktIjYKWIcVrxAZ81pmYR1IYYxKonF4pCmIDU7nGqi0TmERuf@tEhp3pVSBEbG264vrQ3pnBOX02BohUcObcFuRCTlQvFTLdgtEku/sMqxXRGBqfOKIykUVM/o1WqsS/OzL1D8VttyYoP7AYdL0rTkdsyqWvFIkazXFgEdgu4SC9Bp1hCp10hnVWvc/oIzVbNrOLllMVhJeEJzpraAUlDQ7YrxYYNx50240TGuy9wSsp3mDHUyE23WSo8oRFSF84bRlabctKB01jmI51ytPSOMPaXYEusjDiGoqB23ZrNFGR9Zs6kThznHhZwChiZf2IGYuhYvQ8xqwTOL2KLzhETXKn/d2XQh7rvNhm9M/zIjrtsFdy1Y0M0x7WrYTH1QERk0oOcgqeuW6Eqsh00peSY0s7GVoJ3hXxeekjK6QlvGXFa6RVTaNhsrfXk2SbRSZ7HUfDs@AfAd8EC/DPwn4BM6PNJfPk4ewJf7@w/QL0@jh8nH@5eXzy@f75EPH0efP9LA/Vf6@AF7vsbRjfI2GY1e7v/zdUR/Bd6g8BP8X4D@cH8jjK4M8HXiTOiHycuXW4Qe3qAvD6/o2@Thm3d204P3BAzv4SEUwsNPN7gGZIgOsSH@5e3X59fH@g5g2F@HJ@Bl9DvwCRmcivJ00/wG0B7wy5U2GHhukF4FT0N/@F5yCA0n0OAZuJ4aGNwAYG7I3rL3@xVHP5T43yjrv5TPN@Xjn8rX/1F@9/J/2r9aDK6@f2Sjn3q8NmHYf653pTwDzOD1kf0nx/X3Ruzdj87f4fX537h9fX13/Mg8f09egfdaj@zz@5ze7@@Fbv9zWQTD0ivKoesU3k@HfxvfHfvD@lX77Q8 "J – Try It Online")
Will try to add explanation later. The concept is more elegant than the J itself for this one.
[Answer]
# [Python 3](https://docs.python.org/3/), 221 bytes
```
def f(g,*a):x,y,a,b,s=a or[0,0,1,0,[]];c=g[y][x];k=(c=="#")+1;a,b=c in".#"and(a,b)or[(1,0),(0,1),(-1,0),(0,-1)][">v<".find(c)];return"T"if(x,y)in s else c in"AB"and c or f(g,(x+a*k)%len(g[0]),(y+b*k)%len(g),a,b,s+[(x,y)])
```
[Try it online!](https://tio.run/##RY7dboMwDIWvl6eIUk2KSxq12l2BSPAMu6NBYvx0UbuAEobg6ZmBtouU2I7P@exu6r9b@zHPVd3Qhl/FvoDzKCZRiC/h44K2LjuKozjhzbQOy/iaTTobdXiLeRnHbMcgOIWojktqLJM7VtiKYw3o5GgDwdGO7@FZHE6gM6aGiMnGoLgEHbq6/3WWfTLTcBwPxlJP67uv6YpN0gWLeevWLfkYFPsbvN9ry6/ZUSN3Cr5eP7CtH2QrS8NsfrrW9dRPnpAGGSNdBkxe@r4yVrq6qDhI391Nz9nFXiyDM3nrnLE9x4X@OwwAZiXxDJIsQSZLTJdsqzEShd2nQC2C6CnIN8FLTmSSPjKChiTF3iApEhKSRylF1rB2091DvoZcvTh5vrGiRK1JLjdDlKptm62W8g8 "Python 3 – Try It Online")
Perfectly ties Redwolf's JS, by pure coincidence, lol. This could probably be shortened a lot.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 267 258 bytes
```
R=NR,C=NF{for(j=0;k=$++j;v=v?v:k)b[R][j]=k!="."?k:0}END{c=d=f=1;a["^"]=-3;a["v"]=3;a[">"]=4;a["<"]=-4;s["A"]=s["B"]=1;for(s[1]--;y=="#"||!s[v];z=s[v=b[d][f]]>0?v:"tie"){y=="#"?0:w=a[v]?g=c=a[v]:b[d][f]=1;d=(d+=g%2)?d>R?0:d:R;f=(f+=c%3)?f>C?0:f:C;y=v}print z}
```
[Try it online!](https://tio.run/##Pc5Rb4IwEAfw932KWmcCYRCYPrVeG2XbIw99bWqCdDVC4hYxNRP57OzQzfThfrn7567luRkGBYV6yaH46NzXMagh5Q08R1HNPXjpWRNutTK6NtBMgCZUNizt34u3rgILDjJearqhBuL5KI@6QSAWI5bjbMFbTVcoLGssGR9vtTozccx/AOiUXq@TVnvDL5jxsNXWaGeMSPEL9LT/pGF3z8mUnaHEpNxBdQP7C@NWC4GNYDd7DaUVCqOWKe4gcBFUs3koncix6ViOR33/fdwfTuTSD4MgniT397Qm04cTsnp4Q8S/fwE "AWK – Try It Online")
I thought the state machine properties of AWK would help make this shorter, but this particular approach probably won't get much smaller then this...
The first clause reads in the board... The board definitions expected are as listed in the description, with spaces between each character on the board.
```
R=NR,C=NF{ ... }
```
Each time a record is read in, `R` (the max rows) is set to the line number and `C` (the max columns) is set to the number of blank delimited fields. Those are use for the wrapping code later.
```
for(j=0;k=$++j;v=v?v:k)b[R][j]=k!="."?k:0
```
The `for` loop does a couple of things, primarily it sets elements of a two dimensional array `b` to either the character in the board cell or `0` if the input character was `.`.
The `v=v?v:k` bit at the end the loop just sets `v` to the first character in the board (the top left position).
```
END{ ... }
```
On EOF, meaning once the whole board has been read in, the `END` clause runs the simulation to find the answer.
```
c=d=f=1;a["^"]=-3;a["v"]=3;a[">"]=4;a["<"]=-4;s["A"]=s["B"]=1;
```
This long mess is just initiallization I couldn't find a way to shorten. The `a` array is used to compute what deltas should be applied to the current row and column for a given character. And the `s` array is used to recognize stop conditions.
```
for(s[1]--;y=="#"||!s[v];z=s[v=b[d][f]]>0?v:"tie"){ ... }
```
This inner loop does whatever one "command" implies, stopping when the `s` value of the current board position is `A` or `B` or a number greater than 0 (meaning we've been here more than once). The `#` test is to make sure the code will ignore the current cell is the previous character was the "skip the next character" command.
The body of the loop is several statement. It should be possibly be combined into one with more ternary nesting, but I gave up after hitting my deadend limit. :)
```
y=="#"?0:w=a[v]?g=c=a[v]:b[d][f]=1
```
Speaking of nested ternaries... This statement short circuits and does nothing if we're supposed to skip the cell, when the previous command was `#`.
Otherwise if the current command implies a change in direction (the `a` check), the code uses the mapped value for this command in the `a` directory to set new row and column deltas.
The "else" logic after that, is `b[d][f]=1`, which sets the current cell to a value that will trigger the "we've been here" check and exit the loop if we come back to this spot on the board.
```
d=(d+=g%2)?d>R?0:d:R;
f=(f+=c%3)?f>C?0:f:C;
```
These two statements adjust the row and column positions respectively using the offsets associated with the current command, wrapping if the values are too big or too small. The `%2` operation gives the row change (-1, 0, 1) and the `%3` operation gives the column change, also (-1, 0, 1).
```
y=v
```
And lastly, we have to save the current command in order to skip the next character is this command it `#`.
```
print z
```
When the loop exits `z` will either be `A`, `B` or `tie`.
] |
[Question]
[
A [bipartite graph](https://en.wikipedia.org/wiki/Directed_graph) is a graph whose vertices can be divided into two disjoint set, such that no edge connects two vertices in the same set. A graph is bipartite if and only if it is 2-colorable.
---
# Challenge
Your task is to, given the [adjacency matrix](https://en.wikipedia.org/wiki/Adjacency_matrix) of an undirected simple graph, determine whether it is a bipartite graph. That is, if an edge connects vertices i and j, both (i, j) and (j, i) entry of the matrix are 1.
Since the graph is undirected and simple, its adjacency matrix is symmetric and contains only 0 and 1.
# Specifics
You should take an N-by-N matrix as input (in any form, e.g. list of lists, list of strings, C-like `int**` and size, flattened array, raw input, etc.).
The function/program should return/output a truthy value if the graph is bipartite, and falsy otherwise.
# Test Cases
```
['00101',
'00010',
'10001',
'01000',
'10100'] : False
['010100',
'100011',
'000100',
'101000',
'010000',
'010000'] : True (divide into {0, 2, 4, 5} and {1, 3})
['00',
'00'] : True
```
# Scoring
Builtins that compute the answer directly are banned.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program (in bytes) by the end of this month wins!
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~26~~ 25 bytes
```
Tr[#//.x_:>#.#.Clip@x]<1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n1aaZ/s/pChaWV9fryLeyk5ZT1nPOSezwKEi1sZQ7X9AUWZeiQNQUXR1tYGOgY4hCNfqgNlgHpBtqAPlgcWhPKg4mFdbG8uFahBCCkk7qsGoRoB5cDYGD2jBfwA "Wolfram Language (Mathematica) – Try It Online")
## How it works
Given an adjacency matrix A, we find the fixed point of starting with B=A and then replacing B by A2B, occasionally clipping values larger than 1 to 1. The kth step of this process is equivalent up to the `Clip` to finding powers A2k+1, in which the (i,j) entry counts the number of paths of length 2k+1 from vertex i to j; therefore the fixed point ends up having a nonzero (i,j) entry iff we can go from i to j in an odd number of steps.
In particular, the diagonal of the fixed point has nonzero entries only when a vertex can reach itself in an odd number of steps: if there's an odd cycle. So the trace of the fixed point is 0 if and only if the graph is bipartite.
Another 25-byte solution of this form is `Tr[#O@n//.x_:>#.#.x]===0&`, in case this gives anyone ideas about how to push the byte count even lower.
## Previous efforts
I've tried a number of approaches to this answer before settling on this one.
**26 bytes: matrix exponentials**
```
N@Tr[#.MatrixExp[#.#]]==0&
```
Also relies on odd powers of the adjacency matrix. Since x\*exp(x2) is x + x3 + x5/2! + x7/4! + ..., when x is a matrix A this has a positive term for every odd power of A, so it will also have zero trace iff A has an odd cycle. This solution is very slow for large matrices.
**29 bytes: large odd power**
```
Tr[#.##&@@#~Table~Tr[2#!]]<1&
```
For an n by n matrix A, finds A2n+1 and then does the diagonal check. Here, `#~Table~Tr[2#!]` generates 2n copies of the n by n input matrix, and `#.##& @@ {a,b,c,d}` unpacks to `a.a.b.c.d`, multiplying together 2n+1 copies of the matrix as a result.
**53 bytes: Laplacian matrix**
```
(e=Eigenvalues)[(d=DiagonalMatrix[Tr/@#])+#]==e[d-#]&
```
Uses an obscure result in spectral graph theory ([Proposition 1.3.10 in this pdf](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwjxlI2v_sTXAhUL5IMKHUUBCg8QFggoMAA&url=http%3A%2F%2Fwww.springer.com%2Fcda%2Fcontent%2Fdocument%2Fcda_downloaddocument%2F9781461419389-c1.pdf%3FSGWID%3D0-0-45-1273441-p174239273&usg=AOvVaw2j_ijmJ1YXsbbQXwxMycx0)).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 17 bytes
```
§V¤=ṁΣṠMSȯDfm¬ṀfΠ
```
Prints a positive integer if the graph is bipartite, `0` if not.
[Try it online!](https://tio.run/##yygtzv7//9DysENLbB/ubDy3@OHOBb7BJ9a7pOUeWvNwZ0PauQX///@PjjbQMdSBYINYnWgwDeYbAnkwNkIOKg@Wg6lF58UCAA "Husk – Try It Online")
## Explanation
This is a brute force approach: iterate through all subsets **S** of vertices, and see whether all edges in the graph are between **S** and its complement.
```
§V¤=ṁΣṠMSȯDfm¬ṀfΠ Implicit input: binary matrix M.
Π Cartesian product; result is X.
Elements of X are binary lists representing subsets of vertices.
If M contains an all-0 row, the corresponding vertex is never chosen,
but it is irrelevant anyway, since it has no neighbors.
All-1 rows do not occur, as the graph is simple.
ṠM For each list S in X:
Ṁf Filter each row of M by S, keeping the bits at the truthy indices of S,
S fm¬ then filter the result by the element-wise negation of S,
ȯD and concatenate the resulting matrix to itself.
Now we have, for each subset S, a matrix containing the edges
from S to its complement, twice.
§V 1-based index of the first matrix
¤= that equals M
ṁΣ by the sum of all rows, i.e. total number of 1s.
Implicitly print.
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~16~~ 13 bytes
```
⍱1 1⍉∨.∧⍣2⍣≡⍨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HvRkMFw0e9nY86Vug96lj@qHexERA/6lz4qHfF/7RHbRMe9fY96pvq6f@oq/nQeuNHbROBvOAgZyAZ4uEZ/D9NASikYaBgoGAIwppgJpijqWGoAOWARKEciCiYo6nwqHeuggEXzAiEBEIniokoukEcOBOdAzbZEG4yWBYmCgA "APL (Dyalog Extended) – Try It Online")
-3 bytes thanks to @H.PWiz.
Uses the algorithm from [Misha Lavrov's top Mathematica answer](https://codegolf.stackexchange.com/a/14837278410): initialize `A = B = M`, left-multiply `B` twice to `A` and clamp it until it reaches the fixed point, and test if the diagonal entries are all zero.
The regular matrix product `A+.×B` counts the *number* of two-step paths from node `m` to node `p` passing through any intermediate node `n`. If we change the code to `A∨.∧B`, we instead get a boolean matrix indicating if there *exists* any two-step path from node `m` to node `p`. We don't need extra "clamping" operation that way.
### How it works
```
⍱1 1⍉∨.∧⍣2⍣≡⍨ ⍝ Input: adjacency matrix M
⍣≡⍨ ⍝ Find the fixed point, with
⍝ Starting point A = Left arg B = M...
∨.∧⍣2 ⍝ Left-multiply (matmul) B twice to A
⍝ indicating existence of paths (boolean)
1 1⍉ ⍝ Extract the main diagonal
⍱ ⍝ Test if all elements are zero
```
[Answer]
# JavaScript, 78 bytes
```
m=>!m.some((l,i)=>m.some((_,s)=>(l=m.map(t=>t.some((c,o)=>c&&l[o])))[i]&&s%2))
```
Input array of array of 0 / 1, output true / false.
```
f =
m=>!m.some((l,i)=>m.some((_,s)=>(l=m.map(t=>t.some((c,o)=>c&&l[o])))[i]&&s%2))
run = () => o.value=f(i.value.trim().split('\n').map(v=>v.trim().split('').map(t=>+t)))
```
```
<textarea id=i oninput="o.value=''" style="width:100%;display:block;">010100
100011
000100
101000
010000
010000
</textarea>
<button type=button onclick="run()">Run</button>
<div>Result = <output id=o></output></div>
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 25 bytes
```
xmyss.D.DRx0dQx1d.nM*FQss
```
**[Try it online!](https://tio.run/##K6gsyfj/vyK3srhYz0XPJajCICWwwjBFL89Xyy2wuPj//@hoAx1DHQg2iNWJBtNgviGQB2Mj5KDyYDmYWnReLAA "Pyth – Try It Online")**
This returns `-1` for falsy, and any non-negative integer for truthy.
## How it works
```
xmyss.D.DRx0dQx1d.nM*FQss ~ Full program, receives an adjacency matrix from STDIN.
*FQ ~ Reduce (fold) by cartesian product.
.nM ~ Flatten each.
m ~ Map with a variable d.
R Q ~ For each element in the input,
.D ~ Delete the elements at indexes...
x0d ~ All indexes of 0 in d.
.D ~ And from this list, delete the elements at indexes...
x1d ~ All indexes of 1 in d.
s ~ Flatten.
s ~ Sum. I could have used s if [] wouldn't appear.
y ~ Double.
x ~ In the above mapping, get the first index of...
ss ~ The total number of 1's in the input matrix.
```
This works in commit [d315e19](https://github.com/isaacg1/pyth/commit/d315e19d729e6e8d1f86344d44b260ea7a6496b2), the current Pyth version TiO has.
] |
[Question]
[
Given two inputs -- one of them a non-empty printable ASCII string (including space, excluding newline), the other being one of two distinct, consistent values of your choice (`1 / 0`, `l / r`, `left / right`, etc.) -- output an ASCII art airplane banner of the string, pointing either left or right. For consistency, I'll be using `left` and `right` throughout this challenge description.
The plane is either `|-DI>-/` (`left`) or `\-<ID-|` (`right`). Since the banner is clear, it consists of the input string's characters separated by spaces, either left-to-right (`left`) or right-to-left (`right`), and surrounded by a box of the shape
```
/--/
---< <
\--\
```
or
```
\--\
> >---
/--/
```
Note there must be one space between the beginning/end of the message and the `>`,`<` characters.
For example, here is the message `HAPPY BIRTHDAY!` and the direction `left`:
```
/-------------------------------/
|-DI>-/---< H A P P Y B I R T H D A Y ! <
\-------------------------------\
```
Here is the message `PPCG` and the direction `right`. Note that the letters appear "backwards" when viewed from this side of the banner:
```
\---------\
> G C P P >---\-<ID-|
/---------/
```
## Rules
* Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# JavaScript (ES6), ~~141~~ 138 bytes
String and direction are input via currying syntax.
`'/\n|-DI>-/---< '` for left, `'/\n|-DI<-\\---> '` for right.
```
t=>p=>(r=`${s=' '}/${_='-'.repeat(t.length*2+1)}${p}${[...t].join` `} ${d=p[12]}
${s}\\${_}\\`,d>'<'?[...r].reverse().join``:r)
```
```
f=
t=>p=>(r=`${s=' '}/${_='-'.repeat(t.length*2+1)}${p}${[...t].join` `} ${d=p[12]}
${s}\\${_}\\`,d>'<'?[...r].reverse().join``:r)
console.log(f('HAPPY BIRTHDAY!')('/\n|-DI>-/---< '))
console.log(f('HAPPY BIRTHDAY!')('/\n|-DI<-\\---> '))
```
[Answer]
# [Perl 5](https://www.perl.org/), ~~149~~ 102 + 4 (`-plF` ) = ~~150~~ 106 bytes
*Shortened using tricks I've learned since the original answer. Still scored using the rules in effect at the time of the question.*
```
s/./--/g;$_=$"x11 ."/-$_/";$_.="
|-DI>-/---< @F <
".y|\\/|/\\|r;if(<>){y|<>|><|;$_=reverse;s|-/|-\\|}
```
[Try it online!](https://tio.run/##FcyxCsIwFEDRvV8RQwcdXl4ydGoaRKTo4B8ESsFoC8WGpIjB568b63o5XO/CVOUcUSAA3uuya0r@UooJjlB2yNciGl4QHM8GVgOa7VumWcFFImuR0FoK9XjbarN7J9KGjKb/J7inC9HVkQAJVvXJ@dR7n9hhDMtw7dOmkN/ZL@P8iBkulZBKZvBT@wM "Perl 5 – Try It Online")
Two line input. First is the message. Second is 0 for left, 1 for right.
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~73~~, 65 bytes
```
Ó./&
É ÄÒ-ys$/YGpr\$.11>Hj|R|-DI>-/³-<A< ÀñkæG|æ}-r>$BR>³-\-<
```
[Try it online!](https://tio.run/##K/v///BkPX01Ba7DnQqHWw5P0q0sVtGPdC8oilHRMzS088iqCarRdfG009U/tFnXRtrRRkH6cMPhjdmHl7nXHF4mVqtbZKfiFGQHlIzRtfn/PyDA2f2/IQA "V – Try It Online")
Not the greatest score, but that's because almost half of this comes from reversing the output.
Hexdump:
```
00000000: d32e 2f26 200a c920 c4d2 2d79 7324 2f59 ../& .. ..-ys$/Y
00000010: 4770 725c 242e 3131 3e48 6a7c 527c 2d44 Gpr\$.11>Hj|R|-D
00000020: 493e 2d2f b32d 3c1b 413c 201b c0f1 6be6 I>-/.-<.A< ...k.
00000030: 477c e616 7d2d 723e 2442 523e b32d 5c2d G|..}-r>$BR>.-\-
00000040: 3c <
```
Takes the string as input to the buffer, and the direction as `0` for left and `1` for right as command line arguments.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 63 bytes
```
„\\S'-¹g·>×ýD∞2äθ‚11ú"|-DI>-/---<"¸¹ε²i∞θ}J'<«S«ð«J¸«Àε²i∞2äθ}»
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcO8mJhgdd1DO9MPbbc7PP3wXpdHHfOMDi85t@NRwyxDw8O7lGp0XTztdPV1dXVtlA7tOLTz3NZDmzKBis7tqPVStzm0OvjQ6sMbDq32AsqtPtwAkwUbUXto9///AQHO7lwGAA "05AB1E – Try It Online")
Based off bugs that may get fixed in the future.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~44~~ ~~40~~ ~~39~~ 35 bytes
```
|-DI>-/³↗<→/-LηLη↙¹←< ¿N↷⁴‖T⮌⪫η ‖B↓
```
[Try it online!](https://tio.run/##fY7RCoIwFIbvfYrh1QaJRV2pdFFCGBIi9QAmZ24wN5nTCHr3pVl6193hO/zf/5es0KUqhLWZ5tJg9@XFyd7zXRI6E9nOV3Brcl4xs0JutPyDH/O9BaYgK8MwI39IEKuHTIEO2c0CJ@BGaJRxinAim85cuvoOGhOCMt4r86nEO@KAaAHlQAWU5qoL2VKlazzbcuhBt4DPikvMBu1gHQd8E4fOGNBUPKctJLR27WTZ8WS9XrwB "Charcoal – Try It Online") Link is to verbose version of code. First input is 1 for right and 0 for left, second is banner string. Edit: ~~Saved 1 byte by using~~ `ReflectButterfly(:Up)` ~~as `ReflectButterfly(:Down)`~~ currently has a cursor positioning bug, but I saved a further 4 bytes by reversing the print direction, and now it doesn't matter which I use. ~~38~~ ~~34~~ 32 byte version if mirroring the banner was allowed:
```
|-DI>-/³P⪫⪫<<η ↘→\-LηLη↖¹‖B↑¿N‖T
```
[Try it online!](https://tio.run/##fYyxCsIwFEX3fkXIlECDiFtbHFSQSpVSdOtSS9IE0qTEpCL47zG2opvL493zzrstb0yrG@l9aYSyCD7JLl@TBcRpNJNV2I5OWjFM8aCFmgfMMhgDjmMAAcRvS48UJTt9V5XouP02JFMMWl2TX29BVWc54vgPSS5DQVl4XQZUUSZpazfOWmqYfLyvAQsGUK4GZ0@uv1KDMAYf82wadWPa9Ain3i@jstzuPRk9uckX "Charcoal – Try It Online") Link is to verbose version of code. First input is 0 for right and 1 for left. Explanation:
```
|-DI>-/
```
Print the plane.
```
³↗<→/-LηLη↙¹←<
```
Print the top half of the box (note trailing space).
```
¿N↷⁴‖T
```
If the second input is nonzero, reverse the print direction, otherwise reflect the plane and box.
```
⮌⪫η
```
Print the message with extra spacing (note trailing space). The cursor is at the far end of the box from the plane so the message needs to be reversed.
```
‖B↓
```
Reflect to get the bottom half of the box.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~68~~ 65 bytes
```
“/\<“\/>”y
³K“|-DI>-/---< “ < ”j
LḤ‘”-x⁾//jṭ⁶x11¤Fµ,Ñj¢œs3U⁴¡YÑ⁴¡
```
[Try it online!](https://tio.run/##y0rNyan8//9Rwxz9GBsgGaNv96hhbiXXoc3eQF6Nrounna6@rq6ujQKQqwAi52Zx@TzcseRRwwwgW7fiUeM@ff2shzvXPmrcVmFoeGiJ26GtOocnZh1adHRysXHoo8YthxZGHp4Ipv///x8Q4Oz@3wAA "Jelly – Try It Online")
Takes 1 for right, 0 for left.
*-3 bytes thanks to @JonathanAllan* (*grr* I always forget `AB+` does the same as `B+@A`)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes
-8 bytes thanks to [totallyhuman](https://codegolf.stackexchange.com/users/68615/totallyhuman) and [Erik the Outgolfer!](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer)
```
≔⪫S θ≔⁺Lθ²η× ¹¹/η/⸿|-DI>-/³<× η<‖B↓FN«‖TM⁺η³→≔⮌θθ»↑↑Mη←θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R55RHq1a/37NZ4dwOELtx1/s9a87tOLTp3PbD0xUO7Ty0U//cdv1HO/bX6Lp42unqH9psAxQ/t93mUcO093sWPWqb/H7Psvd71h1aDRbY8n7PWqAZ57Yf2vyobRLIwHU953YAzdv9qG0iEAGlz21/1Dbh3I7//wMCnN25DAE "Charcoal – Try It Online")
Fixing the cases [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima) mentioned took quite a toll on the byte count. [36 bytes](https://tio.run/##S85ILErOT8z5//9R55RHq1a/37NZ4dyOw9MVDu08tFP/UeOu93vWnNtxaJP@ox37a3RdPO109Q9ttgEqUbB51DDt/Z5Fj9omv9@z7P2edWDulv//AwKc3bkMAQ) if we are allowed to reverse characters like `<` and `/`.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~55~~ ~~47~~ 43 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
└"┐ξA∫`Ν┌r4≥‘┘¹§,{e⌡↔@¹"╝′‰‘┼}"-<-/ \”┼e?±↔
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTE0JTIyJXUyNTEwJXUwM0JFQSV1MjIyQiU2MCV1MDM5RCV1MjUwQ3I0JXUyMjY1JXUyMDE4JXUyNTE4JUI5JUE3JTJDJTdCZSV1MjMyMSV1MjE5NEAlQjklMjIldTI1NUQldTIwMzIldTIwMzAldTIwMTgldTI1M0MlN0QlMjItJTNDLS8lMjAlNUMldTIwMUQldTI1M0NlJTNGJUIxJXUyMTk0,inputs=L0hhcHB5JTIwJTI4YmlydGhkYXklMjklMEEx)
0 for left and 1 for right
[Answer]
# [Python 2](https://docs.python.org/2/), ~~137~~ ~~136~~ 133 bytes
```
lambda s,d:'{0}/{1}-/\n|-DI{3}-{4}---{5} {2} {5} \n{0}\\-{1}\\'.format(' '*11,'--'*len(s),' '.join(s),*list('></\\<>')[d::2])[::-d|1]
```
[Try it online!](https://tio.run/##RYqxDoIwFEV3voLtUdIHFHVpkEUT48bOY8BUIgYKARZT@u3YEBOHm3tz7hk/y2vQ6dacaevq/qFqf@ZKgklsbITFmPSK17s5WDRHi4jmZH2Turgm7TQidCIRRM0w9fUSgA@hEBwQIeyeOpgZdyh6D@2@w66dnZRnMVGWAyuVlGnFSilRraLaxqnVi98EUBSXG3DBPG9HQBp@8/8mbPsC "Python 2 – Try It Online")
`1` for right and `0` for left
[Answer]
# PHP, 175 bytes
```
[,$d,$s]=$argv;$f=str_repeat("--",strlen($s));$r="\-$f\
".join(" ",str_split("><"[$d].$s)).($d?" <---/->":" >---\-<")."ID-|
/-$f/ ";echo$d?strrev($r):$r;
```
Run with `-nr`, first argument = `0` for facing right or `1` for left and second argument=text
or [try it online](http://sandbox.onlinephpfunctions.com/code/3174051f2e9771d3fa2ffc68410987d2d3d6037c).
[Answer]
## [Perl 5](https://www.perl.org/), 126 bytes
**124 bytes code + 2 for `-pl`.**
```
s/./$& /g;$_=($q=$"x11 .'/-'.s/./-/gr."/
")."|-DI>-/---< $_<
".$q=~y|\\/|/\\|r;<>&&(y|<>|><|,$_=reverse,s/>/ >/,s|-/-|-\\-|)
```
[Try it online!](https://tio.run/##Fcy9CoMwFEDh3adIQ/AHvLk6OBkzlA7t0DcIiFCxgtQ0kdLApY/e1M6H79jRLU2MHiWKlOHUir7LxbMT/F3XTGYImfxHwMlJjgkvJCc4XTQgACgmepVwuYNPIGOQ0BhyrdJpmgdSmrSicl@68TU6P5YeNTKNpafdExgDVMR4HqwN7Di77X4bwiGpv6vd5vXhI1wbWdVVBLv8AA "Perl 5 – Try It Online")
[Answer]
# [Corea](https://github.com/ConorOBrien-Foxx/Corea), 51 bytes
```
"u *:>ip.j:l)X-'/S:>"
|-DI>-/---< V<
"h}>>`tHL`idF
```
[Try it online!](https://tio.run/##S84vSk38/1@pVEHLyi6zQC/LKkczQlddP9jKTomrRtfF005XX1dX10YhzEaBSymj1s4uocTDJyEzxe3//4AAZ3cuQwA "Corea – Try It Online")
## Explanation
The program is composed of a few parts:
## 1: Initialization
```
"u *:>ip.j:l)X-'/S:>"
"..................." execute the inside as code
u repeat
* a space, 11 times
: duplicate this string
> write this string to the content field
i take a line of input
p push a space
.j insert that space after every character
:l) get (length(str) + 1)
X- repeat a hyphen that many times
'/ push the "/" character
S surround that string with the above character
:> duplicate and write that string to the content field
```
## 2: raw text
The following text is outputted to the content field:
```
|-DI>-/---< V<
```
## 3: postamble
```
"h}>>`tHL`idF
" execute until the end of the file
h mirror the previous string horizontally
} move the modified input string to the front of the stack
>> write the top two strings to the content field
` `id do the inside `i`nput times
tH reflect the content field horizontally and vertically
L reverse the input string
F save the input string in a field (default: V)
this replaces all Vs in the code with the input string
```
[Answer]
# Google Sheets, 210 Bytes
Anonymous worksheet function that takes input input as string from [A1] and int from range [B1] where 1 indicates that the plane is on the left and 0 indicates that the plane is on the right.
```
=If(B1," /","\")&Rept("-",2*Len(A1)+1)&If(B1,"/
","\
")&If(B1,"|-DI>-/---< "," > ")&RegexReplace(A1,"(.)","$1 ")&If(B1,"<
",">---\-<ID-|
")&If(B1," \","/")&Rept("-",2*Len(A1)+1)&If(B1,"\","/
```
[Answer]
# Excel VBA, 198 Bytes
Anonymous VBE immediate window function that takes input as string from `[A1]` and int from range `[B1]` where `1` indicates that the plane is on the left and `0` indicates that the plane is on the right.
```
b=[B1]:a=StrConv(IIf(b,[A1],StrReverse([A1])),64):j=[Rept("-",2*Len(A1)+1)]:k="/"&j &"/":l="\"&j &"\":s=Space(11):?IIf(b,s &k,l):?IIf(b,"|-DI>-/---< "," > ")a;IIf(b,"<",">---\-<ID-|"):?IIf(b,s &l,k)
```
] |
[Question]
[
The challenge here is to extend an implementation of palindrome given the following as inputs:
* `n > 1` and a list `l`.
Your program must palindrome the list both vertically and horizontally, that is to say it must first palindrome the list itself, then each element in the list after; or the other way around. Before palindromization, all elements are ensured to be equal length. The palindrome action is then to be performed `n` times in sequence until the desired output is met. The easiest way to show the expected outputs is just to run through a few examples:
---
One iteration performed on `[123,456,789]`:
First you palindromize the list to `[123,456,789,456,123]`.
* While this is not a palindrome if joined together, it is a palindrome in terms of the list.
* `[a,b,c]` became `[a,b,c,b,a]`, so the LIST was palindromized.
Then, you palindromize each list element `[12321,45654,78987,45654,12321]`.
This is how each iteration is performed, it's essentially an omnidirectional palindrome.
---
Given `n=1 and l=[123,456,789]`:
```
12321
45654
78987
45654
12321
```
Given `n=2 and l=[123,456,789]`
```
123212321
456545654
789878987
456545654
123212321
456545654
789878987
456545654
123212321
```
Given `n=1 and l=[3,2,1]`:
```
3
2
1
2
3
```
Given `n=2 and l=["hat","mad"," a "]`:
```
hatahatah
madamadam
a a a a
madamadam
hatahatah
madamadam
a a a a
madamadam
hatahatah
```
Given `n=2 and l=[" 3 ","2000"," 100"]`:
```
3 3 3 3
2000002000002
100 00100 001
2000002000002
3 3 3 3
2000002000002
100 00100 001
2000002000002
3 3 3 3
```
Given `n=4 and l=["3 ","20","1 "]`:
```
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
20202020202020202
1 1 1 1 1 1 1 1 1
20202020202020202
3 3 3 3 3 3 3 3 3
```
Given `n=3 and l=["_|__","__|_","___|"]`:
```
_|___|_|___|_|___|_|___|_
__|_|___|_|___|_|___|_|__
___|_____|_____|_____|___
__|_|___|_|___|_|___|_|__
_|___|_|___|_|___|_|___|_
__|_|___|_|___|_|___|_|__
___|_____|_____|_____|___
__|_|___|_|___|_|___|_|__
_|___|_|___|_|___|_|___|_
__|_|___|_|___|_|___|_|__
___|_____|_____|_____|___
__|_|___|_|___|_|___|_|__
_|___|_|___|_|___|_|___|_
__|_|___|_|___|_|___|_|__
___|_____|_____|_____|___
__|_|___|_|___|_|___|_|__
_|___|_|___|_|___|_|___|_
```
Given `n=2 and l=["---|---","__|","___|","____|"]`:
```
---|-----|-----|-----|---
__| |__ __| |__
___| |___ ___| |___
____| |____ ____| |____
___| |___ ___| |___
__| |__ __| |__
---|-----|-----|-----|---
__| |__ __| |__
___| |___ ___| |___
____| |____ ____| |____
___| |___ ___| |___
__| |__ __| |__
---|-----|-----|-----|---
```
# Rules
* `n` will always be greater than 1.
* `l` will always have more than 1 element.
* All elements of `l` are the same length.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") shortest solution will be marked as winner.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
Note that if only a single iteration was required (`n=1`), then the program would be the palindrome `û€û`.
```
Fû€û
```
[**Try it online**](https://tio.run/nexus/05ab1e#@@92ePejpjWHd/@vPbT7vxFXtJKCsYKCko6SkYGBAZBSMARSsQA)
```
F Do n times
û Palindromize the list
€û Palindromize each element in the list
```
---
If padding the input was still a required part of the program (11 bytes):
```
€R.B€RIFû€û
```
I couldn't find a shorter way to right-justify. Left-justification and centering were all easy, but this was longer for some reason. Using `E` or `²` instead of `I` also works.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~71~~ 63 bytes
```
lambda x,n,f=lambda x:x+x[-2::-1]:eval('f(map(f,'*n+`x`+'))'*n)
```
[Try it online!](https://tio.run/nexus/python2#bYrLbsMgEEX3/YoRm4F4kAxO@kDKlziIUKVOkWJqRW7lhf/dHZN6V4mZO5xzr8fTcov9@yXCRJm64/ZxUzW12jqnjXcfP/EmsZN9HGRHuMvVeTpXqBSfaum@7pAgZX7D9yiVe4LhnvIIifCUka5yl9TSti0a2yDh/vDM@@X1DT0ZT/9yW/hKLY/ZmuIzjoJEHy@8IYL4awpoABjZuq5XYzg21TwEL7P29wWGOQQmgbNEmFk1RWmtZ56H3WSJUrLeL78 "Python 2 – TIO Nexus")
Assign a palindrome function to `f`, generate and evaluate the following pattern (for `n=4`)
`f(map(f,f(map(f,f(map(f,f(map(f,<input>))))))))`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒḄŒB$¡
```
Dyadic link, or full program taking the list and `n`.
**[Try it online!](https://tio.run/nexus/jelly#@3900sMdLUcnOakcWvj/cHvk///RSrq6ujVArKSjpKAQH1@joABlAZkgVjyEFfvfCAA "Jelly – TIO Nexus")**
Using both versions of Lynn's fantastic built-in "bounce".
```
ŒḄŒB$¡ - Main link: l, n
¡ - repeat n times
$ - last two links as a monad (firstly with l then the result...)
ŒḄ - bounce ("palindromise") the list
ŒB - bounce the elements
```
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
h=lambda a:a+a[-2::-1]
f=lambda a,n:n and f(h(map(h,a)),n-1)or a
```
**[Try it online!](https://tio.run/nexus/python2#PYzBCoMwEETP9SuWnBK6e9DjQr9EJGwxIYJZRXr039MtFQ8zPIaZaeW1Sn3PAsLylJEGZuqnLt8xKiuIzpB98VV2X1BCQKU@bAdIy@ZpTTXpBxa11uiI6DQ5dAAxngAXGf4o/mlCGAJ3j/1YbHpdtC8)** - footer prints each of the elements of the resulting list, one per line, a "pretty print".
`h` is the palindomisation function, it appends to the input, all the elements of a list from the last but one, index -2, to the start in steps of size -1.
`f` calls `h` with the result of calling `h` on each element in turn, reduces `n` by one and calls itself until `n` reaches 0, at which point `a` is the finished product.
[Answer]
# APL, 15 bytes
```
(Z¨Z←⊢,1↓⌽)⍣⎕⊢⎕
```
Explanation:
* `(`...`)⍣⎕⊢⎕`: read the list and `N` as input, and run `N` times:
+ `⊢,1↓⌽`: the list, followed by the tail of the reversed list
+ `Z←`: store this function in `Z`
+ `Z¨`: and apply it to each element of the list as well
Test:
```
(Z¨Z←⊢,1↓⌽)⍣⎕⊢⎕
⎕:
'hat' 'mad' ' a '
⎕:
2
┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐
│hatahatah│madamadam│ a a a a │madamadam│hatahatah│madamadam│ a a a a │madamadam│hatahatah│
└─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘
```
[Answer]
# Groovy, 66 bytes
```
{x,n->f={z->z+z[z.size()-2..0]};n.times{x=f(x).collect{f(it)}};x}
```
[Answer]
## Haskell, 51 bytes
```
x%n=iterate((++)<*>reverse.init)x!!n
x?n=(%n)<$>x%n
```
Usage example: `["123","456","789"] ? 1` ->
`["12321","45654","78987","45654","12321"]`. [Try it online!](https://tio.run/nexus/haskell#@1@hmmebWZJalFiSqqGhra1po2VXlFqWWlScqpeZl1miWaGomMdVYZ9nq6Gap2mjYgdU/z83MTNPwVYhN7HAV6GgtCS4pMgnT0FFIVrJWEFJR8nIAEgYKijFKtgrmPwHAA "Haskell – TIO Nexus").
`(++)<*>reverse.init` makes a palindrome out of a list, `iterate(...)x` repeats this again and again and collects the intermediate results in a list, `!!n` picks the nth element of this list. `(%n)<$>x%n` makes a n-palindrom of each element of the n-palindrome of `x`.
[Answer]
## JavaScript (ES6), 87 bytes
```
f=(n,l,r=l=>[...a].reverse().slice(1))=>n--?f(l.concat(r(l)).map(s=>s+r(s).join``),n):l
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 25 bytes
24 bytes of code, +1 for `-l` flag.
```
Lq{gM:_.@>RV_gAL:@>RVg}g
```
Takes the list as command-line arguments and the number *n* from stdin. [Try it online!](https://tio.run/nexus/pip#@@9TWJ3uaxWv52AXFBaf7uhjBWKk16b//2/0Xzfnv6GR8X8TU7P/5haWAA "Pip – TIO Nexus")
### Explanation
```
g is list of cmdline args (implicit)
Lq{ } Read a line of input and loop that many times:
_.@>RV_ Lambda function: take all but the first character (@>) of the
reverse (RV) of the argument (_), and concatenate that (.) to
the argument (_)
gM: Map this function to g and assign the result back to g
@>RVg Take all but the first element of the reverse of g
gAL: Append that list to g and assign the result back to g
g After the loop, print g (each item on its own line due to -l)
```
] |
[Question]
[
# Implement this key cipher
## Goal
Use the algorithm (explained in the Algorithm section) to implement a certain cipher.
The program must read input from STDIN or the closest available equivalent, use the algorithm to generate the ciphertext and a key.
The ciphertext and the key will be written to STDOUT or the closest available equivalent. Any format is allowed, as long as it outputs the ciphertext and the key.
## Algorithm
Convert the characters in the string into the respective ASCII values. For example:
`Hello -> 72 101 108 108 111`
Next, you will need to generate a key as long as the string with random numbers in the range of 0-9.
`Hello -> 62841`
Add the integers in the random number sequence to the ASCII values of the string. In the above examples, 72 would become 78, and 101 would become 104.
`72 + 6 = 78, 101 + 2 = 103, 108 + 8 = 116, etc`
Next, convert the new values back to characters. In the above examples, the text `Hello` has become `Ngtpp`.
## Examples
(These are simply examples of what the output *might* look like. The output can and will vary.)
```
Hello World
Lfrlu)_supg
41606984343
```
---
```
This will be encoded
Zhjs$~koo gj$iuhofgj
60104723305544750226
```
## Rules
* You can assume that the input will only contain characters in the range a-z, A-Z, and spaces.
* Submissions must be full programs or functions.
* Submissions will be scored in bytes.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is code-golf, so the shortest code wins.
---
(This is one of my first challenges, if there's something wrong with it, feel free to tell me how I could improve it.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁵ṁX€’Ṅ+OỌ
```
[Try it online!](http://jelly.tryitonline.net/#code=4oG14bmBWOKCrOKAmeG5hCtP4buM&input=&args=IkhlbGxvIFdvcmxkIg)
### How it works
```
⁵ṁX€’Ṅ+OỌ Main link. Argument: s (string)
⁵ Set the return value to 10.
ṁ Mold; create an array of 10's with the length of s.
X€ Pseudo-randomly pick a integer between 1 and 10, for each 10.
’ Decrement, so the integers fall in the range [0, ..., 9].
Ṅ Print the key, as an array, followed by a linefeed.
+O Add the integers to the ordinals (code points) of s.
Ọ Unordinal; convert back to characters.
```
[Answer]
# Python 3, 130 bytes
*Thanks to @Rod for pointing out a bug*
```
from random import*
def f(x):l=10**len(x);k=str(randint(0,l-1)+l)[1:];print(''.join(chr(ord(i)+int(j))for i,j in zip(x,k))+'\n'+k)
```
A function that takes input via argument as a string and prints to STDOUT.
**How it works**
```
from random import* Import everything from the random module
def f(x): Function with input string x
l=10**len(x) Define l for later use as 10^length(x)
randint(0,l-1)+l Generate a random integer in the range [0, l-1] and add l, giving a
number with l+1 digits...
k=str(...)[1:] ...convert to a string and remove the first character, giving a key of
length l that can include leading zeroes, and store in k
for i,j in zip(x,k) For each character pair i,j in x and k:
chr(ord(i)+int(j)) Find the UTF-8 code-point (same as ASCII for the ASCII characters),
add the relevant key digit and convert back to character
''.join(...) Concatenate the characters of the ciphertext
print(...+'\n'+k) Add newline and key, then print to STDOUT
```
[Try it on Ideone](http://ideone.com/NQhkiZ)
[Answer]
# Pyth - 16 bytes
Waiting for decision by OP on the output formats.
```
sCM+VCMQKmOTQjkK
```
[Test Suite](http://pyth.herokuapp.com/?code=sCM%2BVCMQKmOTQjkK&test_suite=1&test_suite_input=%22Hello%22%0A%22Hello+World%22%0A%22This+will+be+encoded%22&debug=0).
[Answer]
## Actually, 17 bytes
```
;`X9J`M;(O¥♂cΣ@εj
```
[Try it online!](http://actually.tryitonline.net/#code=O2BYOUpgTTsoT8Kl4pmCY86jQM61ag&input=IkhlbGxvIFdvcmxkIg)
Explanation:
```
;`X9J`M;(O¥♂cΣ@εj
; dupe input
`X9J`M for each character in input copy:
X9J discard the character, push a random integer in [0, 9]
; duplicate the offset array
(O bring input to top of stack, ordinal array
¥♂c pairwise addition with offset array, turn each ordinal into a character
Σ concatenate
@εj concatenate the copy of the offset array
```
[Answer]
# CJam - 14 bytes
When I saw the ascii code math, I knew I had to write a CJam answer.
```
q_{;Amr}%_@.+p
```
[Try it online here](http://cjam.aditsu.net/#code=q_%7B%3BAmr%7D%25_%40.%2Bp&input=Hello).
[Answer]
# MATL, 13 bytes
```
"10r*]v!kGy+c
```
The output looks like this:
```
9 5 8 2 1
Qjtnp
```
[Try it online!](http://matl.tryitonline.net/#code=IjEwcipddiFrR3krYw&input=J0hlbGxvJw)
Explanation:
```
" ] % For each character:
10 % Push a 10 onto the stack
r % Push a random float in [O, 1)
* % Multiply. This essentially the same thing as pushing a number in [0, 10)
v!k % Join all of these together, and take the floor
G % Push the input again
y % Duplicate the array of random numbers
+ % And add these together. Since MATL treats strings as an array of chars, we don't need to explicitly convert types
c % Display as string
```
[Answer]
## PowerShell v2+, ~~79~~ 77 bytes
```
param($n)-join(($x=[char[]]$n|%{0..9|Random})|%{[char]($_+$n[$i++])});-join$x
```
Takes input `$n`, loops over every character and gets a `Random` element from `0..9` each iteration. Stores those numbers (as an array) into `$x`. Pipes that array into another loop. Each iteration, takes the current element `$_`, adds it to the positional char sliced out of `$n` (implicit char-to-int cast), then re-casts as `[char]`. Leaves that on the pipeline. That's encapsulated in parens and `-join`ed together to form the word. That's left on the pipeline. Additionally, the number `$x` is also `-join`ed together and left on the pipeline. Those are implicitly printed with a `Write-Output` at the end of execution, which results in them being printed with a newline by default.
### Example
```
PS C:\Tools\Scripts\golfing> .\implement-this-key-cipher.ps1 'Hello World!'
Lhoot(Yt{mf"
433358259121
```
[Answer]
## C#, ~~252~~ ~~247~~ ~~245~~ ~~232~~ 216 Bytes
The size is pretty bad compared to the other solutions but nevertheless...
```
using System;using System.Linq;class p{static void Main(){var c="";var i=Console.ReadLine();var r=new Random();for(int b=0;b++<i.Count();){int d=r.Next(10);Console.Write((char)(i[b]+d));c+=d;}Console.Write("\n"+c);}}
```
This is my second ever answer to a codegolf and I'm quite a beginner considering C# so I'd appreciate to hear how to get it shorter :)
Ungolfed:
```
using System;
using System.Linq;
class p
{
static void Main()
{
var c = "";
var i = Console.ReadLine();
var r = new Random();
for (int b = 0; b++ < i.Count();)
{
int d = r.Next(10);
Console.Write((char)(i[b] + d));
c += d;
}
Console.Write("\n" + c);
}
}
```
* Saved 5 Bytes thanks to @FryAmTheEggman
* Saved 2 Bytes thanks to @theLambGoat
* Saved 7 Bytes by removing `static` from class p
* Saved 24 Bytes thanks to @milk
[Answer]
# CJam, 11 bytes
```
Nq{Amr_o+}/
```
[Try it online!](http://cjam.tryitonline.net/#code=TnF7QW1yX28rfS8&input=SGVsbG8gV29ybGQ)
### How it works
```
N Push a linefeed on the stack.
q Read all input from STDIN and push it on the stack.
{ }/ For each character in the input:
Amr Pseudo-randomly pick an integer in [0 ... 9].
_o Print a copy.
+ Add the integer to the character.
(implicit) Print the linefeed, followed by the modified characters.
```
[Answer]
## [05AB1E](https://github.com/Adriandmen/05AB1E/), ~~18~~ 17 bytes
```
vžh.RDyÇ+ç`?}J¶?,
```
**Explanation**
```
v } # for each char in input
žh.RD # push 2 copies of a random number in [0..9]
yÇ+ # add 1 copy to the current chars ascii value
ç`? # convert to char, flatten and print
J # join stack (which contain the digits of the key)
¶?, # print a newline followed by the key
```
[Try it online](http://05ab1e.tryitonline.net/#code=dsW-aC5SRHnDhyvDp2A_fUrCtj8s&input=SGVsbG8gV29ybGQ)
[Answer]
# Python 3, 112 bytes
c is a function that returns the encrypted text and the key
```
from random import*
c=lambda t:map(''.join,zip(*[(chr(a+b),str(b))for a,b in((ord(i),randint(0,9))for i in t)]))
```
Here is a code that does the same thing and is a bit more readable
```
def encrypt(text):
# keep the codes of the letters in the input and a random key
# that will be used later to encrypt this letter
letter_and_key = ((ord(letter),randint(0,9)) for letter in text)
# encrypt the letter and keep the key used as a string
output_and_key = [(chr(letter_code+key), str(key))
for letter_code, key in letter_and_key]
# At this point the values are kept in the format:
# [(firstletter, firstkey), (secondletter, secondkey), ...]
# to reorder the list to be able to output in the format "text key"
text, key = map(''.join, zip(*output_and_key))
# same as print(*output_and_key)
return text, key
```
Output:
```
>>> text, key = c('Hello World')
>>> print(text, key, sep='\n')
Liuot#`oylk
44935390707
```
[Answer]
## PHP, ~~63~~ ~~86~~ 82 bytes
Edit: forgot to print the key...
*Thanks to Alex Howansky for saving me 4 bytes.*
```
for(;$i<strlen($a=$argv[1]);$s.=$r)echo chr(ord($a[$i++])+$r=rand(0,9));echo"
$s";
```
Input is given through a command line argument. Takes each character in the string and adds a random int from 0-9 to its ASCII code, then converts the code back to ASCII. Every random number is appended to `$s`, which is printed at the end.
[Answer]
# J, 32 bytes
```
<@:e,:~[:<[:u:3&u:+e=.[:?[:$&10#
```
python equivalent:
```
from random import randint
def encrypt(message):
rand_list = list(map(lambda x: randint(0, 9), range(len(message))))
return (''.join(list(map(lambda x,y: chr(x+y), rand_list, map(ord, message)))), rand_list)
```
[Answer]
# Perl, 34 bytes
Includes +1 for `-p`
```
#!/usr/bin/perl -p
s%.%$\.=$==rand 10;chr$=+ord$&%eg
```
[Answer]
# Perl, 65 bytes
```
for(split'',$ARGV[0]){$;.=$a=int rand 9;$b.=chr$a+ord}say"$b\n$;"
```
Took me awhile to figure out how to get the input without a new line at the end. Takes it as a command line arg
[Answer]
# Python 2, ~~84~~ 99 bytes
```
def f(x):y=`id(x)**len(x)`[1:len(x)+1];return''.join(map(chr,[ord(a)+int(b)for a,b in zip(x,y)])),y
```
Uses the `id()` value of the string to generate random numbers.
[Try it](https://repl.it/CpIz/2)
[Answer]
# [Senva](https://github.com/ClementNerma/Senva), 74 bytes
Here is the shortest program I've made :
```
2'(`>0.>{@}0'{v}2-2'0,{@}1'{v}0'{+}{'}9%+{^}{1-}1'"{+}{~}>$10.~0'2+"0,-:>$
```
A little explanation ? (Note: **BM** means *Back-Memory*) :
```
// === Input and informations storing ===
2' // Go to the 3rd cell (the two first will be used to store informations)
( // Ask the user for a string (it will be stored as a suite of ASCII codes)
` // Go the end of the string
> // Make a new cell
0. // Put a 0 to mark the end of the string
> // Make a new cell, here will be stored the first random number
{@} // Store its adress in BM
0' // Go to the 1st cell
{v} // Paste the adress, now the 1st cell contains the adress of the first random number
2- // Subtract 2 because the string starts at adress 2 (the 3rd cell)
2' // Go to the 3rd cell (where the string begins)
// === String encryption and displaying ===
0, // While the current cell doesn't contain 0 (while we didn't reach the string's end)
{@} // Store the character's adress into the memory
1' // Go to the 2nd cell
{v} // Paste the value, now the 1st cell contains the adress of the current char
0' // Go to the 1st cell
{+} // Add the adress of the first random number to the current char adress
{'} // Go to this adrses
9%+ // A random number between 0 and 10
{^} // Store this number in BM
{1-} // Decrease BM (random number between 0 and 9)
1' // Go to the 1st cell
" // Go to the adress pointed by the cell (the adress of the current char)
{+} // Add it to the random number value
{~} // Display it as an ASCII character
> // Go to the next cell (the next character)
$ // End of the loop
10. // Set the new line's ASCII code into the current cell (which is now useless, so it can be overwritten)
~ // Display the new line
0' // Go to the first cell
2+ // Add 2 to the adress, because we are not in the string loop : we cancel the 2 substraction
" // Go to the pointed adress (the first random number's one)
// === Display the random numbers ===
0, // While we didn't reach the end of the random numbers suite
// That was why I stored numbers between 1 and 10, the first equal to 0 will be the end of the suite
- // Decrease it (number between 0 and 9)
: // Display the current random number as an integer
> // Go to the next cell (the next number)
$ // End of the loop
```
That appears bigger now, true :p ? Maybe it's possible to optimize this code, but for the moment that's the shortest I've found.
[Answer]
# C#, 174 bytes
```
using static System.Console;class b{static void Main(){var c=new System.Random();var d="\n";foreach(var e in ReadLine()){var f=c.Next(10);Write((char)(e+f));d+=f;}Write(d);}}
```
Ungolfed:
```
using static System.Console;
class b
{
static void Main()
{
var c = new System.Random();
var d = "\n";
foreach (var e in ReadLine())
{
var f = c.Next(10);
Write((char)(e + f));
d += f;
}
Write(d);
}
}
```
Pretty straightforward, really.
[Answer]
# Perl 6: 55 or 70 bytes
As an anonymous function that takes a string parameter, and returns a list of two strings *(54 characters, 55 bytes)*:
```
{my @n=^9 .roll(.ords);(.ords Z+@n)».chr.join,@n.join}
```
As a program that reads from STDIN and writes to STDOUT *(69 characters, 70 bytes)*:
```
my @a=get.ords;my @n=^9 .roll(@a);say (@a Z+@n)».chr.join;say @n.join
```
] |
[Question]
[
The code on this site is rapidly being depleted. We need to invest in renewable strings. So you must write a program that takes a string and converts it into a windmill.
# The Challenge
Let's take a simple wind-mill string as an example. Take the string `abc`. The *pivot* is the center character, in this case `b`. Since the string is 3 chars long, every output will be *exactly* three lines tall and three characters wide. Here is your output on step 1. (Note the whitespace)
```
abc
```
To get the next step, rotate each character around the pivot clockwise. Here is step 2:
```
a
b
c
```
Here are steps 3-8:
```
a
b
c
```
```
a
b
c
```
```
cba
```
```
c
b
a
```
```
c
b
a
```
```
c
b
a
```
And on the ninth step, it comes around full circle to the original string:
```
abc
```
Note that the `b` stayed in the same spot the whole time. This is because `b` is the pivot character. You must write a program or function that takes a string as input and repeatedly prints out this sequence until the program is closed.
# Clarifications
* All input strings will have an odd number of characters. (So that every windmill will have a pivot)
* To keep the challenge simple, all strings will only contain upper and lowercase alphabet characters.
* The output must be `len(input_string)` characters wide and tall.
* It doesn't matter which step of the sequence you start on, just as long as you continue rotating and looping forever.
# More Test IO:
Since the post is already pretty long, here is a [link](https://gist.github.com/DJMcMayhem/04b0588f27413896da43a5f30a419302) to the output for "windmill":
# Sidenote:
Since this is supposed to be a windmill, it would be awesome if you include some boilerplate code to animate it with a small time delay or a user input between each step. However, since some languages don't have time builtins, this is not mandatory. The competing part of your submission can just print the sequence as fast as possible.
[Answer]
## JavaScript (ES6), 291 bytes
```
r=a=>{w.textContent=a.map(a=>a.join``).join`
`;for(i=j=h=a.length>>1;j++,i--;){t=a[i][i];a[i][i]=a[h][i];a[h][i]=a[j][i];a[j][i]=a[j][h];a[j][h]=a[j][j];a[j][j]=a[h][j];a[h][j]=a[i][j];a[i][j]=a[i][h];a[i][h]=t}}
s=w=>{a=[...w=[...w]].map(_=>w.map(_=>' '));a[w.length>>1]=w;setInterval(r,1000,a)}
s("windmills")
```
```
<pre id=w>
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~35~~ ~~33~~ 21 bytes
```
jtn2/kYaG1$Xd`wtD3X!T
```
The following will animate the windmill (**26 bytes**)
```
jtn2/kYaG1$Xd`wtXxDlY.3X!T
```
[**Online Demo**](https://matl.suever.net/?code=jtn2%2FkYaG1%24Xd%60wtXxDlY.3X%21T&inputs=windmill&version=18.6.0)
In this version , the `Xx` specifies to clear the display and the `1Y.` is a 1-second pause.
**Explanation**
The basic idea is that we want to create two versions of the input. An "orthogonal" version
```
+-----+
| |
| |
|abcde|
| |
| |
+-----+
```
And a "diagonal" version
```
+-----+
|a |
| b |
| c |
| d |
| e|
+-----+
```
We push these two versions onto the stack. Each time through the loop, we switch the order of stack and rotate the top one clockwise.
```
j % Grab the input as a string
t % Duplicate the input
%--- Create the "orthogonal" version ---%
n2/ % Determine numel(input) / 2
k % Round down to nearest integer
Ya % Pad the input string with floor(numel(input)/2) rows above and below
%--- Create the "diagonal" version ---%
G % Grab the input again
1$Xd % Place the input along the diagonal of a matrix
` % do...while loop
w % Flip the order of the first two elements on the stack
t % Duplicate the top of the stack
%--- OCTAVE ONLY (converts NULL to space chars) ---%
O % Create a scalar zero
32 % Number literal (ASCII code for ' ')
XE % Replaces 0 elements in our 3D array with 32 (' ')
%--- END OCTAVE ONLY ---%
D % Display the element
3X! % Rotate this element 90 degrees counter-clockwise 3 times (clockwise)
T % Explicit TRUE to create an infinite loop
% Implicit end of while loop
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~88~~ 53 bytes
Code:
```
¹VYg;ïU[2FX¶×DYsJ,YvNð×y¶J?}YvðX×yJ,}Yv¹gN>-ð×yJ,}YRV
```
[Try it online!](http://05ab1e.tryitonline.net/#code=wrlWWWc7w69VWzJGWMK2w5dEWXNKLFl2TsOww5d5wrZKP31ZdsOwWMOXeUosfVl2wrlnTj4tw7DDl3lKLH1ZUlY&input=YWJjZGU). Make sure to hit the kill button right after you run it, because it goes into an infinite loop.
[Answer]
# Ruby, ~~122~~119 bytes
```
->n{c=0
loop{i=[l=n.size,m=l+1,m+1,1][3-c=c+1&7]*(3.5<=>c)
s=(' '*l+$/)*l
l.times{|j|s[m*l/2-1+(j-l/2)*i]=n[j]}
$><<s}}
```
**Ungolfed version with sleep, in test program**
The rotation isn't very convincing at full console height. But if you reduce the height to the the length of the input string, the rotation is a lot more convincing.
```
f=->n{
c=0 #loop counter
m=1+l=n.size #l=string length. m=l+1
loop{ #start infinite loop
s=(' '*l+$/)*l #make a string of l newline-terminated lines of l spaces. Total m characters per line.
i=[m-1,m,m+1,1][3-c=c+1&7]*(3.5<=>c) #array contains positive distance between characters in string 1=horizontal, m=vertical, etc.
#c=c+1&7 cycles through 0..7. Array index 3..-4 (negative indices count from end of array, so 3=-1, 0=-4 etc)
#(3.5<=>c) = 1 or -1. We use to flip the sign. This is shorter than simply using 8 element array [m-1,m,m+1,1,1-m,-m,-m+1,-1]
l.times{|j|s[m*l/2-1+i*(j-l/2)]=n[j]} #for each character in n, write the appropriate space character in s to the character in n
puts s #print s
sleep 1 #sleep for 1 second
}
}
f[gets.chomp] #get input, remove newline, call function
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~47~~ 44 bytes
```
' 'jntX"tGtnXyg(wGtnQ2/Y(XJDXKD`J@_X!DK3X!DT
```
[Try it online!](http://matl.tryitonline.net/#code=JyAnam50WCJ0R3RuWHlnKHdHdG5RMi9ZKFhKRFhLRGBKQF9YIURLM1ghRFQ&input=YWJjZGU) (but kill it immediately, infinite loop)
With 1-second pause: **56 bytes**
```
' 'jntX"tGtnXyg(wGtnQ2/Y(XJD1Y.XKD1Y.`J@_X!D1Y.K3X!D1Y.T
```
[Try it online!](http://matl.tryitonline.net/#code=JyAnam50WCJ0R3RuWHlnKHdHdG5RMi9ZKFhKRDFZLlhLRDFZLmBKQF9YIUQxWS5LM1ghRDFZLlQ&input=YWJjZGU) (again, infinite loop)
[Answer]
# **Python 3**, 193 bytes
```
def c(a):e=' ';s=len(a);l=int(s/2);b=range(s);m='\n'*l;print(m,a,m);for x in b:print(e*x,a[x]);for x in b:print(e*l,a[x]);for x in b:print(e*(s-1-x),a[x]); a=input();while True:c(a);c(a[::-1]);
```
**Ungolfed**
```
def c(a):
e=' ';s=len(a);l=int(s/2);b=range(s);m='\n'*l;
print(m,a,m);
for x in b:print(e*x,a[x]);
for x in b:print(e*l,a[x]);
for x in b:print(e*(s-1-x),a[x]);
a=input();
while True:
c(a);
c(a[::-1]);
```
## Recursive, 177 bytes
(crash after a few seconds)
```
def c(a):e=' ';s=len(a);l=int(s/2);b=range(s);m='\n'*l;print(m,a,m);for x in b:print(e*x,a[x]);for x in b:print(e*l,a[x]);for x in b:print(e*(s-1-x),a[x]);c(a[::-1]);c(input());
```
**Ungolfed**
```
def c(a):
e=' ';s=len(a);l=int(s/2);b=range(s);m='\n'*l;
print(m,a,m);
for x in b:print(e*x,a[x]);
for x in b:print(e*l,a[x]);
for x in b:print(e*(s-1-x),a[x]);
c(a[::-1])
c(input());
```
## Another solution, 268 bytes
```
import itertools as i;def w(a):e=' ';s=len(a);l=int(s/2);t='\n';m=(l-1)*t;h=list(i.chain.from_iterable((e*x+a[x],e*l+a[x],e*(s-1-x)+a[x]) for x in range(s)));print(m,a,m,t.join(h[::3]),t.join(h[1::3]),t.join(h[2::3]),sep=t,end='');a=input();while True:w(a);w(a[::-1]);
```
**Ungolfed**
```
import itertools as i;
def w(a):
e=' ';s=len(a);l=int(s/2);t='\n';m=(l-1)*t;
h=list(i.chain.from_iterable((e*x+a[x],e*l+a[x],e*(s-1-x)+a[x]) for x in range(s)))
print(m,a,m,t.join(h[::3]),t.join(h[1::3]),t.join(h[2::3]),sep=t,end='');
a=input();
while True:
w(a);
w(a[::-1]);
```
[Answer]
# Pyth, 48 bytes
```
JlzK/J2#*btKz*btKM+*dG@zHVJgNN)VJgKN)VJg-JNN)=_z
```
[Try it online!](http://pyth.herokuapp.com/?code=JlzK%2FJ2FH2*btKz*btKM%2B*dG%40zHVJgNN%29VJgKN%29VJg-JNN%29%3D_z&input=abcde&debug=0) (Note: this is a version that does not forever loop, because it would crash the interpreter.)
Shamelessly translated from the Python 3 solution by [@ByHH](https://codegolf.stackexchange.com/users/52734/byhh).
How it works:
```
JlzK/J2#*btKz*btKM+*dG@zHVJgNN)VJgKN)VJg-JNN)=_z
assign('z',input())
Jlz assign("J",Plen(z))
K/J2 assign("K",div(J,2))
# loop-until-error:
*btK imp_print(times(b,tail(K)))
z imp_print(z)
*btK imp_print(times(b,tail(K)))
@memoized
M def gte(G,H):
+*dG@zH return plus(times(d,G),lookup(z,H))
VJ ) for N in num_to_range(J):
gNN imp_print(gte(N,N))
VJ ) for N in num_to_range(J):
gKN imp_print(gte(K,N))
VJ ) for N in num_to_range(J):
g-JNN imp_print(gte(minus(J,N),N))
=_z assign('z',neg(z))
```
] |
[Question]
[
In this challenge, you are required to shift characters in an inputted string n number of times and output the shifted string
# Input
Input will first contain a string. In the next line, an integer, which denotes `n` will be present.
# Output
* If `n` is positive, shift the characters in the string to the right `n` times.
* If `n` is negative, shift the characters in the string to the left `n` times.
* If `n` is zero, don't shift the characters in the string.
After shifting (except when `n` is zero), print the shifted string.
# Notes
* The string will not be empty or `null`.
* The string will not be longer than 100 characters and will only contain ASCII characters in range (space) to `~`(tilde) (character codes 0x20 to 0x7E, inclusive). See [ASCII table](http://c10.ilbe.com/files/attach/new/20150514/377678/1372975772/5819899987/f146bf39e73cde248d508e5e1b534865.gif) for reference.
* The shift is cyclic.
* The number `n` may be positive, negative, or zero.
* `n` will always be greater than or equal to -1000 and lesser than or equal to 1000
* You may take input via `stdin` or from command line arguments
* The shifted string must be outputted in the `stdout` (or closest equivalent)
* You may write a full program or a function which takes input and outputs the string in `stdout` or closest equivalent
# Test Cases
1)
```
Hello world!
5 -->orld!Hello w
```
2)
```
Testing...
-3 -->ting...Tes
```
3)
```
~~~
1000 -->~~~
```
4)
```
12345
0 -->12345
```
5)
```
ABA
17 -->BAA
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) wins.
[Answer]
# Pyth, 4 bytes
```
.>zQ
```
This is almost similar to [my CJam 5 byte version](https://codegolf.stackexchange.com/a/51020/38214), except that Pyth as a auto-eval input operator `Q`.
```
.> # Cyclic right shift of
z # Input first line as string
Q # Rest of the input as evaluated integer
```
[Try it online here](http://pyth.herokuapp.com/?code=.%3EzQ&input=Testing...%0A-3&debug=0)
[Answer]
# Javascript (*ES5*), 55 52 bytes
```
p=prompt;with(p())p(slice(b=-p()%length)+slice(0,b))
```
**Commented:**
```
p = prompt; // store a copy of prompt function for reuse
with(p()) // extend scope chain with first input
p( // print result
slice(b = -p() % length) // take second input negated and modulo length
+ // and slice string by result
slice(0, b) // concatenate with opposite slice
)
```
[Answer]
# CJam, 5 bytes
```
llim>
```
This is pretty straight forward.
```
l e# Read the first line
li e# Read the second line and convert to integer
m> e# Shift rotate the first string by second integer places
```
[Try it online here](http://cjam.aditsu.net/#code=llim%3E&input=Testing...%0A-3)
[Answer]
# C, 93 bytes
```
main(a,v,n)char**v;{a=v[2]-v[1]-1;n=atoi(v[2]);a=a*(n>0)-n%a;printf("%s%.*s",v[1]+a,a,v[1]);}
```
More clear is the function-argument version that was modified to make the command line-argument version
```
f(s,n,c)char*s;{c=strlen(s);c=c*(n>0)-n%c;printf("%s%.*s",s+c,c,s);}
```
This one is only 68 bytes, which just goes to show how disadvantaged C is when dealing with command line arguments.
If the shift, `n`, is positive then `strlen(s)-n%strlen(s)` is the offset and if `n` is negative the offset is `-n%strlen(s)`. The `printf` prints from the offset, `c`, to the end of the string, and then the final `c` characters from the beginning.
Examples:
```
$ ./rotstr "Hello world!" 5
orld!Hello w
$ ./rotstr "Testing..." -3
ting...Tes
$ ./rotstr "~~~" 1000
~~~
$ ./rotstr "12345" 0
12345
$ ./rotstr "ABA" 17
BAA
$ ./rotstr "Hello world!" -16
o world!Hell
```
[Answer]
# Python 3, 45 bytes
```
s=input();n=int(input());print(s[-n:]+s[:-n])
```
The core of the program is
```
s[-n:]+s[:-n]
```
All the rest is just clumsy work with I/O.
[Answer]
# K, ~~8~~ 7 bytes
```
{|x!|y}
```
There is already a primitive "rotate" (`!`) which performs a generalization of this operation for lists. K strings are lists of characters, so it applies. The spec favors CJam and Pyth a bit, though, because K's rotate happens to go the opposite direction of what is desired. Wrapping `!` in a function and negating the implicit argument `x` will do what we want:
```
f:{(-x)!y}
{(-x)!y}
f[5;"Hello world!"]
"orld!Hello w"
f[-3;"Testing..."]
"ting...Tes"
f[17;"ABA"]
"BAA"
```
A slightly shorter approach, suggested by kirbyfan64sos, is to do away with the parentheses and negation in favor of reversing the string (`|`) before and after the rotation.
If it weren't for this impedance mismatch, the solution would be simply
```
!
```
Called identically:
```
f:!
!
f[5;"Hello, World!"]
", World!Hello"
f[-5;"Hello, World!"]
"orld!Hello, W"
f[0;"Hello, World!"]
"Hello, World!"
```
[Answer]
# Casio Basic, 27 bytes
```
StrRotate s,s,-n:Print s
```
As it turns out, there's a built-in for this on the Casio ClassPad! But it works in reverse, hence `-n`.
24 bytes for the code, 3 bytes to specify `s,n` as arguments.
[Answer]
# Pip, 10 bytes
This could quite possibly be improved further. Still, for a language with no shift operator, 10 bytes ain't bad.
```
a@_M-b+,#a
```
Explanation:
```
a, b are command-line args (implicit)
,#a range(len(a))
-b+ range(-b, len(a)-b)
a@_M map(lambda x: a[x], range(-b, len(a)-b))
Concatenate the list and print (implicit)
```
It works because string and list indexing in Pip is cyclical: `"Hello"@9 == "Hello"@4 == "o"`.
[Answer]
# [rs](https://github.com/kirbyfan64/rs), 180 chars
```
^(-\d+) (.*)/\1 \2\t
+^(-\d+) (.)(.*?)\t(.*)$/\1 \3\t\2\4
^(-\d+) \t/\1
^(-?)(\d+)/\1 (_)^^(\2)
+_(_*) (.*)(.)$/\1 \3\2
^- /- \t
+^- (.*?)\t(.*?)(.)$/- \1\3\t\2
^-? +/
\t/
```
[Live demo](http://kirbyfan64.github.io/rs/index.html?script=%5E(-%5Cd%2B)%20(.*)%2F%5C1%20%5C2%5Ct%0A%2B%5E(-%5Cd%2B)%20(.)(.*%3F)%5Ct(.*)%24%2F%5C1%20%5C3%5Ct%5C2%5C4%0A%5E(-%5Cd%2B)%20%5Ct%2F%5C1%20%0A%5E(-%3F)(%5Cd%2B)%2F%5C1%20(_)%5E%5E(%5C2)%0A%2B_(_*)%20(.*)(.)%24%2F%5C1%20%5C3%5C2%0A%5E-%20%2F-%20%5Ct%0A%2B%5E-%20(.*%3F)%5Ct(.*%3F)(.)%24%2F-%20%5C1%5C3%5Ct%5C2%0A%5E-%3F%20%2B%2F%0A%5Ct%2F%0A&input=5%20Hello%20world!%0A-3%20Testing...%0A0%2012345).
Most of this is reversing the string if the input number is negative. I took advantage of the fact that only some ASCII characters are valid input and used the tab to my advantage.
Note that I had to cheat a little: since rs is a single-line text modifier, I had to use `<number> <text>` as the input format.
[Answer]
# Java, 167
```
enum S{;public static void main(String[]r){int n=-Integer.parseInt(r[1]),l=r[0].length();while(n<0)n+=l;n%=l;System.out.print(r[0].substring(n)+r[0].substring(0,n));}}
```
Takes the input through the command line.
funny enough, originally I had accidentally reversed how the string was supposed to be shifted. But fixing that mistake was shorter to just multiply n by -1 then to write the logic properly.
expanded:
```
enum Shift{
;
public static void main(String[]args){
int n=-Integer.parseInt(args[1]),length=args[0].length();
while(n<0)n+=length;
n%=length;
System.out.print(args[0].substring(n)+args[0].substring(0,n));
}
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 bytes
```
éV
```
[Try it online](http://ethproductions.github.io/japt/?v=1.4.4&code=6VY=&input=IkhlbGxvIFdvcmxkISIsNQ==)
[Answer]
# [Julia 0.6](http://julialang.org/), 31 bytes
```
s|n=String(circshift([s...],n))
```
[Try it online!](https://tio.run/##ZZBPa8QgEMXPzad4SA4KNmR3@@dQAk1OvW9vpYfEmKytmKIuZaHkq6ejZU/1oPN@Mw/m@XG2pn/YtvDjmmP0xs1cGa/CyUyRv4Wqqt6lE2I7B2qh64OuXnWIxXOkO@gIdkyjF6iTVp@BYdCzcSgATIsHDxJOwgsQ5Jy9aGsXfC/ejkziIMGoukImZPL9P5z1gxr1NJPndk@mLPqBDNRb15X4rq5r6iSR6W5/uLsnnuBfnXHbtWn4kWjXtkyIAjc5C/gXpY/WcVYG5Px6xHBB6dA0KD0TT6BfSsKLtKd2Y3quNlEQ2H4B "Julia 0.6 – Try It Online")
[Answer]
# PHP>=7.1, 88 Bytes
```
for([,$s,$t]=$argv;$t;)$s=$t<0?substr($s,1).$s[!$t++]:$s[-1].substr($s,!$t--,-1);echo$s;
```
[Testcases](http://sandbox.onlinephpfunctions.com/code/b15ce8226741b555d6d2a1f7e67062ed8a13dc75)
[Answer]
## Pascal (ISO standard 10206, “Extended Pascal”), 120 Bytes
```
program p(input,output);var s:string(100);n:integer;begin read(s,n);n:=(-n)mod length(s);writeLn(subStr(s,n+1),s:n)end.
```
Ungolfed:
```
program shiftCharactersInAString(input, output);
var
line: string(100);
n: integer;
begin
read(line, n);
{ In Pascal, the result of the `mod` operation is non-negative. }
n := (-n) mod length(line);
{ In Pascal, string indices are 1‑based. }
writeLn(subStr(line, n + 1), line:n)
{ `line:n` is equivalent to `subStr(line, 1, n)` (if `n` ≤ `length(line)`). }
end.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ ~~5~~ 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
(._
```
Inputs in the order `integer,string`.
[Try it online](https://tio.run/##yy9OTMpM/f9fQy/@/39dY66Q1OKSzLx0PT09AA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC8X8Nvfj/Ov@jo011lDxSc3LyFcrzi3JSFJVidaJ1jXWUQlKLSzLz0vX09EAihgYGBjpKdXV1IA6QZWhkbGIKljDXUXJ0clSKjQUA).
**Explanation:**
```
( # Negate the first (implicit) input-integer
._ # Rotate the second (implicit) input-string that many times towards the left
# (which supports negative integers as rotating right instead)
# (after which the result is output implicitly)
```
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
sg+FÁ
```
Inputs in the order `integer,string`.
[Try it online](https://tio.run/##MzBNTDJM/f@/OF3b7XDj//@6xlwhqcUlmXnpenp6AA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfWWCS9H/4nRtt8ON/2t1/kdHm@ooeaTm5OQrlOcX5aQoKsXqROsa6yiFpBaXZOal6@npgUQMDQwMdJTq6upAHCDL0MjYxBQsYa6j5OjkqBQbCwA).
**Explanation:**
```
s # Swap so the two (implicit) inputs are in reversed order on the stack
g # Pop and push the length of the top input-string
+ # Add it to the input-integer
F # Loop that many times
Á # And rotate once towards the right during every iteration
# (using the last implicit input-string in the first iteration)
```
Since the legacy version of 05AB1E only has builtins for *Rotate once towards the right/left*, and not *Rotate \$n\$ amount towards the right/left*, I loop \$length + input\$ amount of times and rotate that many times towards the right.
For example:
* `"Testing..."` and `-3` will rotate \$10 + -3 = 7\$ times towards the right, resulting in `ting...Tes`.
* `"Hello world"` and `5` will rotate \$11 + 5 = 16\$ times towards the right, resulting in `worldHello`.
The new version of 05AB1E does have a builtin for rotating \$n\$ amount of times towards the left, which is `._`, saving 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
```
StringJoin@RotateRight[Characters@#,#2]&
```
```
StringJoin@RotateLeft[Characters@#,-#2]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8D@4pCgzL90rPzPPISi/JLEkNSgzPaMk2jkjsSgxuSS1qNhBWUfZKFbtfwBQXUl0WrSSR2pOTr5CeX5RToqiko6CaWysNRdcMiS1uARonp6eHlBK1xhFrq6uTknH0MDAAEXU0MjYxFRJB1XQ0ckRqNQcJPYfAA)
[Answer]
## [vemf](https://github.com/selaere/vemf), 1 byte
```
+
```
Left argument is string, right argument is offset.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
ǔ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLHlCIsIiIsIjVcbkhlbGxvIHdvcmxkISJd)
Takes the number then the string. Prepend `$` if you want the inputs the other way round.
Built-in solution for "rotate right". Rotation is modular so we don't have to worry about negative inputs.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
N⁴ṙ
```
[Try it online!](https://tio.run/##y0rNyan8/9/vUeOWhztn/v//3/S/B1AoX0chPL8oJ0URAA "Jelly – Try It Online")
#### Explanation
```
N⁴ṙ # Main link. Takes an integer on the
# left and a string on the right.
⁴ # Get the right argument (the string)
ṙ # And rotate it left by ↓ spaces
N # The left argument negated
# Implicit output
```
[Answer]
# [Python](https://www.python.org), 35 bytes
```
lambda s,n:s[(x:=-n%len(s)):]+s[:x]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Tc8xTsMwFAbgPaf4aYVqUztKaSsqS0FKJw7AFjIUNYFIrlPFRpQlF2GJhOBO3KRjnRcP9WL5_z8_6X3_Hb_ce2P6nyp9-f1wldz8T_Xu8LrfwQqjbM5OKpXmVpeGWc5VMbe5OhWBnl1pnUWKPALY5KnUusFn0-r9zURgzQUwhZSPoCjURJ_9x9q8xXHsoVwOMtAQe0Cw6zovFkmSkKEzQt-QWNwvV2tvrkAQ1JDJttkw5eGKBLPNsqiIoqppoWtTojagpRSObW0cG0KBmaczgYrdDW_Ox_37frwv)
[Answer]
# [Thunno](https://github.com/Thunno/Thunno) `J`, \$ 8 \log\_{256}(96) \approx \$ 6.58 bytes
```
LR_z0sAI
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSl1LsgqWlJWm6Fit8guKrDIodPSFcqOiC9R6pOTn5Ogrh-UU5KYpcphBhAA)
No shift operator in Thunno so we have to do it ourselves.
#### Explanation
```
LR_z0sAI # Implicit input STACK: "Hello, World!", 5
LR # Length range STACK: 5, [0..12]
_ # Swapped subtract STACK: [-5..7]
z0 # First input STACK: [-5..7], "Hello, World!"
sAI # Swap and index STACK: ['o', 'r', 'l', 'd', '!', 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W']
# J flag joins STACK: "orld!Hello, W"
# Implicit output
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 2 bytes
```
|)
```
[Run and debug it](https://staxlang.xyz/#c=%7C%29&i=%22Hello+world%21%22+5%0A%22Testing...%22+-3%0A%22%7E%7E%7E%22+1000%0A%2212345%22+0%0A%22ABA%22+17&a=1&m=2)
[Answer]
## [Perl 5](https://www.perl.org/) + `-palF`, 26 bytes
```
$_=substr$_.$_,@F-<>%@F,@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3ra4NKm4pEglXk8lXsfBTdfGTtXBDcj4/98jNScnX6E8vygnRZHLlCsktbgkMy9dT0@PS9eYq66ujsvQwMCAy9DI2MSUy4DL0cmRy9Cc619@QUlmfl7xf92CxBw3AA "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 28 bytes
```
->s,n{s.chars.rotate(-n)*""}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhZ7dO2KdfKqi_WSMxKLivWK8ksSS1I1dPM0tZSUaiFKbroWlJYUK7hFK3mk5uTkK5TnF-WkKCrpKJjGcsFkQlKLSzLz0vX09IDiusYICUMjYxNToJhBLMSwBQsgNAA)
[Answer]
## HP‑41C series, 4 Bytes
Input string is located in alpha register and number to rotate on top of the stack (i. e. the X register).
An extended functions module or HP‑41CX is required.
```
CHS 1 Byte flip sign because AROT acts just the opposite as required
AROT 2 Bytes rotate alpha register according to value in X register
AVIEW 1 Byte display contents of alpha register
```
] |
[Question]
[
*(inspired by this [SO question](https://stackoverflow.com/questions/26247602/nested-for-loop-art))*
You are given as input a single positive integer *n*.
In as few characters as possible, output a rocket in ASCII art with a head, a tail, and a body composed of *n* segments. There should be no trailing spaces or newlines.
The head and the tail of the rocket are always the same for any value of *n*. The body consists of two different types of segments which alternate. The examples should make the structure of the rocket clear.
Output for *n* = 1:
```
/**\
//**\\
///**\\\
////**\\\\
/////**\\\\\
+=*=*=*=*=*=*+
|\/\/\/\/\/\/|
|.\/\/..\/\/.|
|..\/....\/..|
|../\..../\..|
|./\/\../\/\.|
|/\/\/\/\/\/\|
+=*=*=*=*=*=*+
/**\
//**\\
///**\\\
////**\\\\
/////**\\\\\
```
Output for *n* = 2:
```
/**\
//**\\
///**\\\
////**\\\\
/////**\\\\\
+=*=*=*=*=*=*+
|../\..../\..|
|./\/\../\/\.|
|/\/\/\/\/\/\|
|\/\/\/\/\/\/|
|.\/\/..\/\/.|
|..\/....\/..|
+=*=*=*=*=*=*+
|\/\/\/\/\/\/|
|.\/\/..\/\/.|
|..\/....\/..|
|../\..../\..|
|./\/\../\/\.|
|/\/\/\/\/\/\|
+=*=*=*=*=*=*+
/**\
//**\\
///**\\\
////**\\\\
/////**\\\\\
```
Output for *n* = 3:
```
/**\
//**\\
///**\\\
////**\\\\
/////**\\\\\
+=*=*=*=*=*=*+
|\/\/\/\/\/\/|
|.\/\/..\/\/.|
|..\/....\/..|
|../\..../\..|
|./\/\../\/\.|
|/\/\/\/\/\/\|
+=*=*=*=*=*=*+
|../\..../\..|
|./\/\../\/\.|
|/\/\/\/\/\/\|
|\/\/\/\/\/\/|
|.\/\/..\/\/.|
|..\/....\/..|
+=*=*=*=*=*=*+
|\/\/\/\/\/\/|
|.\/\/..\/\/.|
|..\/....\/..|
|../\..../\..|
|./\/\../\/\.|
|/\/\/\/\/\/\|
+=*=*=*=*=*=*+
/**\
//**\\
///**\\\
////**\\\\
/////**\\\\\
```
[Answer]
## CJam, 121 bytes
```
5,{_5\-S*\)_'/*"**"@'\*N}%:A['+"+
"]"=*"6**:Lri:M{M(:M;2,{M+2%:J;3,{:I'|J@2\-'.*I'.*?_J"/\\""\/"?JI)3I-?*\++_+'|N}%}%L}*A
```
[Try it online](http://cjam.aditsu.net/)
Takes the input *n* via STDIN.
I'll add an explanation at some point later. Basically it's all just a bunch of loops in a very naive way. To alternate between the two different body parts, I've got a nested loop over the part and a loop over `0` and `1`. Then I just add the outer iterator and the inner one, and use their parity to decide between upwards or downwards pointing triangle.
[Answer]
# CJam, ~~67~~ 63 characters
```
"дȈ鰚㒄å摒四ㄺ뎞椉ᖛⲠ줥葌⌁掗⦠춻锦䎷겲铣굛쮂먲꿡㦺좒轃汁̕뎕갴瓖邻吟㭰戔蟏㳵回㡚钦״脮烮鋉둎邫"6e4b127b:c~
```
This should work in the [online interpreter](http://cjam.aditsu.net/ "CJam interpreter").
### How it works
After pushing the Unicode string, the snippet
```
6e4b127b:c~
```
converts the string from base 60000 to base 127, casts to string and evaluates the result.
The code that get executed is the following:
```
"..." " A binary string of length 42. ";
122b7b " Convert from base 122 to base 7. ";
"\n *./\|"f= " Replace each digits with the corresponding character. ";
60/~ " Split into chunks of length 60 and dump the resulting array. ";
" The stack now contains the rocket's head and a body half. ";
[_W%[\]_W%] " Push an array of the body half and the reversed body half, a reversed ";
" copy of that array and collect both array into another one. ";
Nf*Nf+ " Join each array of body halves separating by LFs and append LFs. ";
ri:I* " Repeat the resulting array I := int(input()) times. ";
I<W% " Keep the first I bodies and reverse their order. ";
\a_@\++ " Prepend and append the rocket head/tail. ";
'+"=*"6*'+N+++ " Push S := '+=*=*=*=*=*=*+\n'. ";
* " Join the array of parts, separating by S. ";
```
[Answer]
# Ruby, 203
```
n,q=$*[0].to_i,"\\/"
h,r,m=1.upto(5).map{|i|(?/*i+"**"+?\\*i).center 14},?++"=*"*6+?+,3.times.map{|i|?|+?.*i+q*(3-i)+?.*(2*i)+q*(3-i)+?.*i+?|}*"\n"
p=m.reverse.tr q,"/\\"
puts h,([r,m,p,r,p,m]*n)[0,3*n],r,h
```
## Ungolfed
I think in this case it's beneficial to have an non-golfed version.
```
n = $*[0].to_i
head = 1.upto(5).map { |i| ("/"*i + "**" + "\\"*i).center 14 }
ridge = "+" + "=*"*6 + "+"
middle = 3.times.map { |i| "|" + "."*i + "\\/"*(3-i) + "."*(2*i) + "\\/"*(3-i) + "."*i + "|" }.join "\n"
piddle = middle.reverse.tr "\\/", "/\\"
puts head
puts ([ridge,middle,piddle,ridge,piddle,middle]*n)[0,3*n]
puts ridge, head
```
## Explanation
I doubt this is anywhere near efficient, but it was fun nonetheless.
* Input is taken from `ARGV`.
* `h` contains the "head" and "tail" of the rocket, `r` contains the "ridges" that separate the different parts of the rocket and `m` and `p` are the top and bottom parts of the "body" of the rocket.
* The body is constructed by cycling through the `Array` `["ridge", "top of body", "bottom of body", "ridge", "bottom of body", "top of body"]` and taking the first `3*n` elements.
* `puts` makes sure everything gets its own line.
[Answer]
# Python, 120 + 77 + 1 = 198 characters
This ended up being the wrong approach, but I had already finished when Martin posted his answer.
```
H,L,T,B=open("R","rb").read().decode('zip').split("X")
n=input()
for p in[H]+([B,T,L,T,B,L]*n)[:3*n][::-1]+[L,H]:print p
```
Requires a file `R` (+1 for filename) of 77 bytes, which you can generate as follows:
```
>>> open('R','wb').write('eJxNjMENwDAIA/+ZIm8i4Qm6Bw+PwvDFQRUFydwJwd5VMOO6ILqIRjE+LsEI4zw2fSKJ6Vzpmt4p\ndVlnRikoVWqrK+8s/X1ivozIJuo=\n'.decode('base64'))
```
[Answer]
## JS, WIP, 252b or 173 chars
It's not a function, so you have to set the value of n at the beginning (3 here), then execute it in the console or in nodeJS.
Here's the 252b version:
```
n=3;r=a=" /**01 //**001 ///**0001 ////**00001 /////**00000";b="1+=*=*=*=*=*=*+1";for(c=[d="|0/0/0/0/0/0/|1|.0/0/..0/0/.|1|..0/....0/..|",d.split("").reverse().join("")];n--;)r+=b+c[n%2]+1+c[1-n%2];(r+b+a).replace(/0/g,"\\").replace(/1/g,"\n")
```
And here's the 173 chars version (using <http://xem.github.io/obfuscatweet/>)
```
n=3;eval(unescape(escape('¨†Ω®êΩò††òĆòĆõ∞™ö†∞úê†òĆòÄØõ∞™ö†∞úıòĆòÄØõ∞Øö†™úÄ∞úıòĆõ∞Øõ∞Øö†™úÄ∞úÄ∞úê†õ∞Øõ∞Øõ∞™ö†∞úÄ∞úÄ∞ò†ª®†Ωò†±ö∞Ωö†Ωö†Ωö†Ωö†Ωö†Ωö†´úê¢û±¶´±≤öÅ£üëõ©ÄΩò°ºúÄØúÄØúÄØúÄØúÄØúÄØØÄ±ØÄÆúÄØúÄØõ†ÆúÄØúÄØõ°ºúëºõ†ÆúÄØõ†Æõ†ÆúÄØõ†ÆØÄ¢õŧõ°≥¨Å¨™ë¥öÄ¢ò†©õ°≤©ë∂©ë≤¨±•öÄ©õ°™´±©´†®ò†¢öëùû±Æõê≠û∞©¨†´üë¢ö±£¶±Æôê≤ßê´úê´®±õúê≠´†•ú°ùû∞®¨†´®†´®ê©õ°≤©ë∞´Å°®±•öÄØúÄØ©∞¨ò°úßÄ¢öêÆ¨°•¨Å¨®ë£©ê®õ∞±õ±ßõÄ¢ßÅÆò†©').replace(/uD./g,'')))
```
[Answer]
# JavaScript (E6) 252 ~~257~~
Overuse of string.repeat
```
F=p=>{
R=(n,s='.',a='')=>a+s.repeat(n)+a;
for(i=f=o=m=n='';++i<6;)
o+=f+R(6-i,' ')+R(i,u='/')+'**'+R(i,t='\\'),
f='\n',
i<4?m+=f+R(2,R(4-i,t+u,R(i-1)),'|',n+=f+R(2,R(i,u+t,R(3-i)),'|')):0;
s=f+R(6,'=*','+'),
console.log(o+s+R(p&1,q=m+n+s)+R(p/2,n+m+s+q)+f+o)
}
```
[Answer]
# Javascript (ES3): 243 ~~219~~ bytes
```
R=function(n){for(a='',i=5;i--;t=a+=s+'\n')for(s='**',j=6;j--;b=['|../\\..|./\\/\\.|/\\/\\/\\','|\\/\\/\\/|.\\/\\/.|..\\/..'])s=i<j?'/'+s+'\\':' '+s+' ';for(;a+='+=*=*=*=*=*=*+\n',n;)a+=(b[n&1]+b[--n&1]).replace(/[^|]+/g,'$&$&|\n');return a+t}
```
] |
[Question]
[
**Without using strings** (except when necessary, such as with input or output) calculate the nth digit, **from the left**, of an **integer** (in base 10).
Input will be given in this format:
```
726433 5
```
Output should be:
```
3
```
as that is the fifth digit of "726433".
Input will **not** contain leading zeros, e.g. "00223".
Test cases / further examples:
```
9 1 -> 9
0 1 -> 0
444494 5 -> 9
800 2 -> 0
```
This is code golf; least amount of characters wins, but any built in functions such as "nthDigit(x,n)" are **not acceptable**.
Here's some pseudo-code to get you started:
```
x = number
n = index of the digit
digits = floor[log10[x]] + 1
dropRight = floor[x / 10^(digits - n)]
dropLeft = (dropRight / 10 - floor[dropRight / 10]) * 10
nthDigit = dropLeft
```
As you can see I'm new to code golf, and though I think it's a bit unfair that I ask a question before I've even answered one, I would really like to see what kind of responses this generates. :)
**Edit**: I was hoping for mathematical answers, so I cannot really accept answers that rely on converting strings to arrays or being able to access numbers as a list of digits.
# We have a winner
Written in "dc", **12** bytes. By *DigitalTrauma*.
[Answer]
## GolfScript (10 bytes)
```
~(\10base=
```
This assumes input is as a string (e.g. via stdin). If it's as two integers on the stack, the initial `~` should be removed, saving 1 char.
If the base conversion is considered to fall foul of the built-in functions rule, I have a 16-char alternative:
```
~~)\{}{10/}/=10%
```
[Answer]
# CJam - 7
```
l~(\Ab=
```
CJam is a new language I am developing, similar to GolfScript - <http://sf.net/p/cjam>. Here is the explanation:
`l` reads a line from the input
`~` evaluates the string (thus getting the two numbers)
`(` decrements the second number
`\` swaps the numbers
`A` is a variable preinitialized to 10
`b` does a base conversion, making an array with the base-10 digits of the first number
`=` gets the desired element of the array
The program is basically a translation of Peter Taylor's solution.
[Answer]
# Haskell 60 bytes and readable
```
nth x n
| x < (10^n) = mod x 10
| True = nth (div x 10) n
```
no strings involved!
```
*Main> nth 1234567 4
4
```
[Answer]
# J - 15 24 char
A sufficiently "mathematical answer".
```
(10|[<.@*10^]-10>.@^.[)/
```
Same results as below, but is endowed with the mystical quality of being mathematical.
---
The short version, using base-10 expansion.
```
({0,10&#.inv)~/
```
We prepend a 0 to adjust for 1-based indexing.
Usage:
```
({0,10&#.inv)~/ 1234567 3
3
({0,10&#.inv)~/ 444494 5
9
```
[Answer]
# [dc](http://www.gnu.org/software/bc/manual/dc-1.05/), 12 bytes
```
?dZ?-Ar^/A%p
```
This is a mathematical answer. Here's how it works:
* `?` read input number and push to stack
* `d` duplicate top of stack
* `Z` Pops value off the stack, calculates and pushes the number of digits
* `?` read digit index and push to stack
* `-` subtract digit index from digit count
* `A` push 10 to the stack
* `r` swap top 2 values on stack
* `^` exponentiate 10 ^ (digit count - digit index)
* `/` divide number by result of exponentiation
* `A` push 10 to the stack
* `%` calculate the number mod 10 to get the last digit and push to top of stack
* `p` pop and print the top of stack
In action:
```
$ { echo 987654321; echo 1; } | dc ndigit.dc
9
$ { echo 987654321; echo 2; } | dc ndigit.dc
8
$ { echo 987654321; echo 8; } | dc ndigit.dc
2
$ { echo 987654321; echo 9; } | dc ndigit.dc
1
$
```
[Answer]
# Python 127
```
def f(i,n):
b=10;j=i/b;k=1;d=i-j*b
while j>0:
k+=1;j/=b
if n>k:
return -1
while k>n:
k-=1;j/=b;i/=b;d=i-j*b
return d
```
[Answer]
# C, 50
This uses arrays.
```
main(int c,char**a){putchar(a[1][atoi(a[2])-1]);}
```
Just ignore all the warnings.
And yes, in C, strings are really just arrays, so this is sort of cheap.
---
More Mathematical:
# C, 83
```
main(int c,char**a){printf("%d",(atoi(a[1])/pow(10,strlen(a[1])-atoi(a[2])))%10);}
```
[Answer]
# bc (driven by bash), 41 29
I think this is the first answer to do this mathematically and not with strings:
```
bc<<<"$1/A^(length($1)-$2)%A"
```
The use of `length()` perhaps seems a bit stringy, but the bc man page talks about number of digits and not length of string:
>
>
> ```
> length ( expression )
> The value of the length function is the number of significant
> digits in the expression.
>
> ```
>
>
Output:
```
$ ./ndigits.bc.sh 726433 5
3
$ ./ndigits.bc.sh 9 1
9
$ ./ndigits.bc.sh 0 1
0
$ ./ndigits.bc.sh 444494 5
9
$ ./ndigits.bc.sh 800 2
0
$
```
[Answer]
# Mathematica - ~~24~~ 23
This one is kind of obvious :)
```
IntegerDigits[#][[#2]]&
```
Example:
```
IntegerDigits[#][[#2]]& [726433, 5]
```
Output:
```
3
```
You can get it shorter by hard-coding two integers, e.g.
```
IntegerDigits[n][[m]]
```
but then you first have to write `n = 726433; m = 5;`. The function call felt more similar to a program.
[Answer]
**C 145**
Program finds distance from end of integer and divides until index is reached then uses modulus 10 to get the last digit.
```
int main()
{
int i,a,b,d,n;
scanf("%d %d",&i,&a);
d=(int)(log(i)/log(10))+1;
n=d-a;
while(n--){i=(int)(i/10);}
b=i%10;
printf("%d",b);
}
```
[Answer]
# Wolfram Alpha - between 40 and 43
Of course, I can totally defend that using `IntegerDigits` is a trick that does not fall under
>
> any built in functions such as "nthDigit(x,n)"
>
>
>
But because my previous answer still felt like cheating a little bit, here's an alternative. Unfortunately it's quite a bit longer, but I didn't see how to shorten it any more than I did.
Counting in a similar way as before (with the ampersand, without passing in any arguments),
```
Mod[Trunc[#/10^(Trunc[Log10[#]]-#2+1)],10]&
```
has 43 characters. By negating the exponent and shuffling the terms around, I can lose one arithmetic operator (`10^(...)x` will be interpreted as multiplication)
```
Mod[Trunc[10^(#2-Trunc[Log10[#]]-1)#],10]&
```
~~I don't have Mathematica at hand to test, I doubt that it will be~~As I suspected (and as was kindly [verified by kukac67](https://codegolf.stackexchange.com/questions/25534/output-the-nth-digits-of-an-integer/25587?noredirect=1#comment55296_25587)) in Mathematica this is not accepted, but it [runs in WolframAlpha](http://wolfr.am/1sAO8mu).
I am in doubt about the use of `RealDigits`, because I restricted myself from using `IntegerDigits` for this answer and they are quite similar. However, if I allow myself to include it (after all, it doesn't return the integers directly, just how *many* of them there are), I can slash off another two characters:
```
Mod[Trunc[10^(#2-RealDigits[#]-1)#],10]&
```
[Answer]
## Tcl (42 bytes, lambda):
```
{{x y} {expr $x/10**int(log10($x)+1-$y)%10}}
```
## (49 bytes, function):
```
proc f {x y} {expr $x/10**int(log10($x)+1-$y)%10}
```
## (83 bytes, if we need to accept input from shell):
```
puts [expr [lindex $argv 0]/10**int(log10([lindex $argv 0])+1-[lindex $argv 1])%10]
```
[Answer]
# R (60)
Solved the problem using log10 to calculate the number of digits. The special case x==0 costs 13 character, sigh.
```
f=function(x,n)if(x)x%/%10^(trunc(log10(x))-n+1)%%10 else 0
```
Ungolfed:
```
f=function(x,n)
if(x)
x %/% 10^(trunc(log10(x)) - n + 1) %% 10
else
0
```
Usage
```
> f(898,2)
[1] 9
```
[Answer]
## Scala (~~133~~ 99 bytes):
Works for all positive inputs. Divides by 10 to the power of the digit looked for from the right, then takes it modulo 10.
```
def k(i:Array[String])={val m=i(0).toInt
(m*Math.pow(10,i(1).toInt-1-Math.log10(m)toInt)).toInt%10}
```
Thank you for noticing the bug in the previous formula. This one is shorter.
[Answer]
# Haskell, 142
I'm not sure I understood the question correctly, but this is what I think you wanted: read stdin (string), make the two numbers int (not string), do some algorithmic things, and then output the result (string). I crammed it into 142 chars, which is way too much:
```
import System.Environment
a%b|a>9=div a 10%(b+1)|1<2=b
x#n=x`div`10^(x%1-n)`mod`10
u[a,b]=read a#read b
main=fmap(u.words)getContents>>=print
```
example usage:
```
> echo 96594 4 | getIndex
9
```
[Answer]
# JavaScript - 84
```
p=prompt,x=+p(),m=Math;r=~~(x/m.pow(10,~~(m.log(x)/m.LN10)+1-+p()));p(r-~~(r/10)*10)
```
Purely mathematical, no strings, none of them. Takes the first number in the first prompt and the second number in the second prompt.
**Test Case**:
```
Input: 97654 5
Output: 4
Input: 224658 3
Output: 4
```
**Ungolfed Code:**
```
p = prompt,
x = +p(), // or parseInt(prompt())
m = Math;
r = m.floor( x / m.pow(10, m.floor(m.log(x) / m.LN10) + 1 - +p()) )
// ^-- log(10) ^-- this is `n`
p(r - ~~(r / 10) * 10) // show output
```
[Answer]
## perl, ~~38, 36~~ no *30* characters
(not counting the linefeed)
This is arguably cheating due to the command switch, but thanks for letting me play :-)
```
~/$ cat ndigits.pl
say((split//,$ARGV[0])[$ARGV[1]-1]);
~/$ tr -cd "[:print:]" < ndigits.pl |wc -m
36
~/$ perl -M5.010 ndigits.pl 726433 5
3
```
**edit**:
Was able to remove 2 characters:
```
say for(split//,$ARGV[0])[$ARGV[1]-1];
say((split//,$ARGV[0])[$ARGV[1]-1]);
```
... then 6 more:
```
say((split//,shift)[pop()-1]);
```
**How**
We split the input of the first argument to the script `$ARGV[0]` by character (`split//`) creating an zero indexed array; adding one to the second argument `$ARGV[1]` to the script then corresponds to the element at that position in the string or first argument. We then hold the expression inside `()` as a one element list which `say` will iterate through. For the shorter short version we just `shift` in the first argument and use the remaining part of @ARGV to use for the index - once `shift`ed only the second argument remains so we `pop()` it and subtract 1.
Is this supposed to be a math exercise? I just realized I'm indexing a string read from input, so ... I guess I lose?? Mark me up if I make sense in parallel golf course and I will try again - more mathematically - in a separate answer.
cheers,
[Answer]
# PHP, 58
Using math only
`<?$n=$argv[1];while($n>pow(10,$argv[2]))$n/=10;echo $n%10;`
[Answer]
# ~-~! - ~~94~~ 93
Bends the rules a bit - it's a function that takes n as input and assumes the number to find digit n of is stored in `'''''` - and ~-~! doesn't support floats.
```
'=~~~~~,~~:''=|*==~[']<''&*-~>,'|:'''=|*==%[%]~+*/~~~~/~~|:''''=|'''''/''&<<'''&'''''>-*-~>|:
```
`'''''=~~~~,~~,~~,~~,~~,~~:''''''=''''&~:` will result in `''''''` being `~~` (2) (''''' = 128).
[Answer]
## Python 2.7 (89 bytes)
I transform the integer into a "polynomial" by using a list of digits. I know you say you can't accept that, but I don't see why not since it uses the mathematical concept of numbers being represented as polynomials of their bases. It will only fail when the integer passed in is `0`, but you said no padded zeroes ;)
```
import sys;v=sys.argv;p,x,n=[],int(v[1]),int(v[2])
while x:p=[x%10]+p;x//=10
print p[n-1]
```
Run as `test.py`:
```
$ python test.py 726489 5
8
```
I assume you wanted shell input and that I couldn't make use of the fact that the input would be strings. Skipping shell input it's just 43 bytes, with:
```
p=[]
while x:p=[x%10]+p;x//=10
print p[n-1]
```
Although I use some unnecessary iteration, I save some bytes by not adding an additional decrement on `n`.
[Answer]
# [Extended BrainFuck](http://sylwester.no/ebf/): 49
```
+[>>,32-]<<-[<<-],49-[->>>[>>]+[<<]<]>>>[>>]<33+.
```
Usage:
```
% bf ebf.bf < nth-digit.ebf > nth-digit.bf
% echo "112234567 7" | bf nth-digit.bf
5
```
I'm not ectually using any special features of EBF except the multiplication operator (eg. `10+ => ++++++++++`). Other than that it's mostly pure [BrainFuck](http://en.wikipedia.org/wiki/Brainfuck)
How it works:
```
+ ; Make a 1 in the first cell
[>>,32-] ; while cell is not zero: read byte 2 to the right and reduce by 32 (space)
<<-[<<-] ; move back to the first cell by reducing every cell with 1
,49- ; read index, reduce by 49 so that ascii 1 becomes 0
[->>>[>>]+[<<]<] ; use that to fill a trail of breadcrumbs to the desired number
>>>[>>] ; follow the breadcrumbs
<33+. ; go to value part, increase by 33 (32 + 1 which we substracted) and print
```
# Scheme (R6RS): 100 (without unnecessary whitespace)
```
(let*((x(read))(n(read))(e(expt 10(-(floor(+(/(log x)(log 10))1))n))))
(exact(div(mod x(* e 10))e)))
```
[Answer]
# awk - 53
```
{for(d=10^9;!int($1/d)||--$2;d/=10);$0=int($1/d)%10}1
```
1. trim digits by division, starting with max possible for 32 bit unsigned int
2. when we hit the left side of the integer, int($1 / d) returns non-zero
3. continue n ($2) digits past that
Ungolfed:
```
{
for(d = 1000000000; int($1 / d) != 0 || --$2; d /= 10);
print int($1 / d) % 10;
}
```
[Answer]
# Scala (83)
Does not use any Scala special features. Rather the standard solution.
```
def f(x:Int,n:Int)=if(x==0)0 else x/(math.pow(10,math.log10(x).toInt-n+1)).toInt%10
```
Ungolfed:
```
def f(x:Int,n:Int) =
if(x==0)
0
else
x / (math.pow(10, math.log10(x).toInt - n + 1)).toInt % 10
```
[Answer]
# C, 94
```
main(x,y,z,n){scanf("%d%d",&x,&y);for(z=x,n=1-y;z/=10;n++);for(;n--;x/=10);printf("%d",x%10);}
```
# C, 91, invalid because of using arrays.
```
main(x,y,z){int w[99];scanf("%d%d",&x,&y);for(z=0;x;x/=10)w[z++]=x%10;printf("%d",w[z-y]);}
```
[Answer]
# Julia 37
```
d(x,y)=div(x,10^int(log10(x)-y+1))%10
```
Owing to the builtin ^ operator. Arbitrary precision arithmetic allows for any size int.
Sample
```
julia> d(1231198713987192871,10)
3
```
[Answer]
## perl (slightly more mathy/not very golfy) - 99 chars
```
~/$ cat ndigits2.pl
($n,$i)=@ARGV;
$r=floor($n/10**(floor(log($n)/log(10)+1)-$i));
print int(.5+($r/10-floor($r/10))*10);
```
Run it as:
```
perl -M5.010 -MPOSIX=floor ndigits.pl 726433 1
```
[Answer]
## Perl6 - 85 chars
```
my ($n,$i)=@*ARGS;
my$r=$n/10**(log10($n).round-$i);
say (($r/10-floor($r/10))*10).Int;
```
[Answer]
# Smalltalk, 44
Although dc is unbeatable, here is a Smalltalk solution:
arguments, n number; d digit-nr to extract:
```
[:n :d|(n//(10**((n log:10)ceiling-d)))\\10]
```
] |
[Question]
[
## The Rules
It's time to build a typing speed test in your language of choice!
**1**. You provide a file with a dictionary of choice (every 'word' in it must be newline delimited). Pipe it in via `stdin` or provide it's name as a command line argument.
```
a
able
about
above
absence
...
```
**2**. Pick 10 random words from the file (no duplicates must be allowed) and print them out in the following manner:
```
-> direct
-> ground
-> next
-> five
...
```
**3**. Start measuring the time spent from now on!
**4**. Let the user type all of the ten words as fast as possible (ended with a carriage return). Print `OK` when you have a match, print `WRONG` when we have a typing mistake (or the word was already succesfully typed in this run).
**5**. Stop the clocks! Now print the *CPM* (Caracters per minute) benchmark, which is calculated as follows: `(sum of the characters of the chosen words / time spent typing (seconds)) * 60`. Round to the nearest integer and reproduce the following (sample) output:
```
--> You have scored 344 CPM!
```
## A sample run
```
-> settle
-> side
-> open
-> minister
-> risk
-> color
-> ship
-> same
-> size
-> sword
settle
OK
side
OK
open
OK
# ...................... some lines snipped ......................
word
WRONG
sword
OK
--> You have scored 298 CPM!
```
## The winner
This is code colf, the shortest entry (in source code character count) wins, have fun!
[Answer]
## Bash - 217 212 199 196 chars
Not gonna win but it was fun
```
declare -A W
for w in `shuf -n10`;do C+=$w;echo -\> $w;W[$w]=OK;done
SECONDS=0
for((;${#W[*]};));do read r;echo ${W[$r]-WRONG};unset W[$r];done
echo --\> You have scored $((60*${#C}/SECONDS)) CPM!
```
Under 200 chars now!
Takes wordlist file as an argument
Now takes word list on standard input. Paste it in the terminal and press ^D
Implemented suggestion from manatwork
[Answer]
# K, 146
Assumes a dictionary file called 'd' in the current working directory.
```
{b:+/#:'a:10?_0:`:d;-1"-> ",/:a;s:.z.t;while[#a;$[(,/0:0)~*a;[a:1_a;-1"OK"];-1"WRONG"]];-1"--> You have scored ",($(60000*b)%"i"$.z.t-s)," CPM!";}
```
[Answer]
## Ruby (~~189~~ ~~178~~ ~~171~~ 168)
```
$><<t=['',d=[*$<.lines].sample(10)]*'-> '
s=Time.now
puts d.delete($stdin.gets)?:OK:'WRONG'while d[0]
puts'--> You have scored %i CPM!'%((t.size-40)/(Time.now-s)*60)
```
Pretty basic, I'm sure there are improvements to be made. Takes the filename of the dictionary as a command-line argument.
**EDIT**: A few minor tweaks, mainly around retaining the newlines from the dictionary. As a result the file will need a trailing newline to work correctly.
[Answer]
## C, 305 309 347 chars
```
char*stdin,w[11][99];long i,t;main(int n,char**v){v=fopen(v[1],"r");
for(srand(time(&t));fgets(w[i++>9?(n=rand()%i)>10?0:n:i],99,v););
for(i=n=0;i<10;n+=printf("-> %s",w[++i])-4);
for(;i;puts(!strcmp(*w,w[11-i])?--i,"OK":"WRONG"))fgets(*w,99,stdin);
printf("--> You have scored %ld CPM!\n",n*60/(time(0)-t));}
```
Thanks to @ugoren for the improvement hints. Using an "11th word" to discard incoming dictionary entries was a big win over my previous strcpy-if-chosen approach.
Here's the ungolfed source:
```
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
static char words[11][99];
static long i, t;
int main(int argc, char *argv[])
{
FILE *fp;
int n;
fp = fopen(argv[1], "r");
srand(time(0));
for (i = 0 ; fgets(words[0], sizeof words[0], fp) ; ++i) {
n = i < 10 ? i : rand() % i;
if (n < 10)
strcpy(words[n + 1], words[0]);
}
fclose(fp);
n = 0;
for (i = 1 ; i <= 10 ; ++i)
n += printf("-> %s", words[i]) - 4;
t = time(0);
i = 1;
while (i <= 10 && fgets(words[0], sizeof words[0], stdin)) {
if (strcmp(words[0], words[i])) {
puts("WRONG");
} else {
puts("OK");
++i;
}
}
if (i > 9)
printf("-> You have scored %ld CPM!\n", n * 60 / (time(0) - t));
return argc - argc;
}
```
[Answer]
# Scala(319 306 ~~304~~ 302)
```
var s=util.Random.shuffle(io.Source.fromFile(args(0)).getLines.toSet)take 10
def?(a:Any)=println(a)
var l=(0/:s){_+_.size}
s map{"-> "+_}map?
def n=System.nanoTime
val t=n
while(s.size!=0){val m=readLine
if(s contains m)?("OK")else?("WRONG");s-=m}
?("--> You have scored "+l*60000000000L/(n-t)+" CPM!")
```
[Answer]
## C# 401
```
void T(){
Action<string>C=Console.WriteLine;Func<string>R=Console.ReadLine;
var w=new List<string>();
for(var l=R();l!="";l=R())w.Add(l);
var s=w.OrderBy(_=>Guid.NewGuid()).Take(10).ToList();
s.ForEach(x=>C("=> "+x));
var t=s.Select(x=>x.Length).Sum();
var c=Stopwatch.StartNew();
while(s.Any()){C(s.Remove(R())?"OK":"WRONG");}
c.Stop();
C("--> You have scored "+c.Elapsed.TotalSeconds*60/t+" CPM!");}
```
Running version here: <http://ideone.com/Nt6Id>
[Answer]
## PHP 187 bytes
Newlines have been added for clarity:
```
<?$s=file($argv[1]);
for(shuffle($s);$i++<10;$l+=strlen($$i))echo~ÒÁß,$$i=$s[$i];
for($t=time();$j++<10;)echo$$j==fgets(STDIN)?OK:WRONG,~õ?>
--> You have scored <?=0|$l/(time()-$t)*60?> CPM!
```
Accepts the dictionary filename as a command line argument. The dictionary file must end with a newline.
[Answer]
## Python (~~256~~ 235)
```
import time as t,random as r
def p(x):print x
c=r.sample(input().split("\n"),10)
z=lambda x:p(("WRONG","OK")[raw_input()==x])or len(x)
p("--> "+"\n--> ".join(c))
_=t.time()
p("--> You have scored %d CPM!"%(sum(map(z,c))/(t.time()-_)*60))
```
This is in python 2.x, in 3.x I can shave off 4 more characters by using the print function.
Newlines included
[Answer]
# [Wolfram Language (Mathematica)], 212 bytes
```
n=10;Print["-> "<>#]&/@(w=RandomWord@n);c=1;t=First@AbsoluteTiming[While[c<=n,Print@If[Echo@InputString[]==w[[c]],c++;"OK","WRONG"]]];Print["--> You have scored "<>ToString@⌊60Total@StringLength@w/t⌋<>" CPM!"]
```
Interesting challenge for WM.
Works only on desktop!
Using internal dictionary of common words instead of file.
Ungolfed version:
```
num = 10; Print["-> " <> #] & /@ (words = RandomWord@num);
size = Total@StringLength@words;
count = 1;
timing = First@AbsoluteTiming[
While[count <= num,
Print[
If[Echo@InputString[] == words[[count]],
count++; "OK",
"WRONG"]
]
]];
result = ToString@⌊60 size/timing⌋;
Print["--> You have scored " <> result <> " CPM!"]
```
] |
[Question]
[
The [TAK function](https://mathworld.wolfram.com/TAKFunction.html) is defined as follows for integers \$x\$, \$y\$, \$z\$:
$$
t(x, y, z) = \begin{cases}
y, & \text{if $x \le y$} \\
t(t(x-1,y,z), t(y-1,z,x), t(z-1,x,y)), & \text{otherwise}
\end{cases}
$$
It can be proved that it always terminates and evaluates to the simple function below:
$$
t(x, y, z) = \begin{cases}
y, & \text{if $x \le y$} \\
z, & \text{if $x > y$ and $y \le z$} \\
x, & \text{otherwise}
\end{cases}
$$
Your job is to implement the function. (As per the standard rules, it is OK to implement the simplified version, or anything else that evaluates to the same value for all inputs.)
You may assume that the three input values are nonnegative integers.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
For a harder challenge, check out ["The TAK function"](https://codegolf.stackexchange.com/questions/269557/the-tak-function).
## Test cases
```
(x, y, z) -> output
(10, 20, 100) -> 20
(20, 20, 100) -> 20
(20, 10, 100) -> 100
(20, 10, 10) -> 10
(20, 10, 0) -> 20
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 25 bytes
```
f=(x,y,z)=>x>y?f(y,z,x):y
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGiEtulpSVpuhY702w1KnQqdao0be0q7Crt0zSAbJ0KTatKiPzNncn5ecX5Oal6OfnpGiUahgY6CkZAbGhgoKmpoK-voGsH5HOhKjIiVpEhmiIgG6cqoCK4KhyKwGrg9kE8sGABhAYA)
Not shortest but fun
# [JavaScript (Node.js)](https://nodejs.org), 22 bytes
```
(x,y,z)=>x>y?y>z?x:z:y
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGiEtulpSVpuhbbNCp0KnWqNG3tKuwq7SvtquwrrKqsKiGSN3cm5-cV5-ek6uXkp2uUaBga6CgYAbGhgYGmpoK-voKuHZDPharIiFhFhmiKgGycqoCK4KpwKAKrgdsH8cCCBRAaAA)
[Answer]
# [Python](https://www.python.org), 31 bytes
```
lambda x,y,z:x*(x>y>(y:=z))or y
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhb7cxJzk1ISFSp0KnWqrCq0NCrsKu00Kq1sqzQ184sUKiGqbrYUFGXmlWikaRga6CgYAbGhgYGmpjKQyQWTMUKWUcCQMkSSAtJY5KBSGDJw4yBuWbAAQgMA)
[Answer]
# [Haskell](https://www.haskell.org/), 23 bytes
```
(x#y)z|x>y=(y#z)x|1<2=y
```
[Try it online!](https://tio.run/##fc6xCsMgGATg3ac4cFGwRZ1r3qBPYB0cAg1NQqgO/y95dxtKx5KDW77l7pnLa5zn3hVJ1m2ngYNi2TTt7uYD9zqWWhAQEZ018EedtUngF4PoT9yd@l@2CUmIJU/rMbvk7Q61vae14opHJMOmJVwGKKlBYDSN78f@AQ "Haskell – Try It Online")
I see that [I4m2](https://codegolf.stackexchange.com/users/76323) found this approach before I did. Could've saved me the dozen minutes I spent trying to find a non-obvious approach. :P
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 12 bytes
```
⊡◿3+1⊗1≤↻1..
```
[Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAg4oqh4pe_Mysx4oqXMeKJpOKGuzEuLgoKZiBbMTAgMjAgMTAwXQpmIFsyMCAyMCAxMDBdCmYgWzIwIDEwIDEwMF0KZiBbMjAgMTAgMTBdCmYgWzIwIDEwIDBdCg==)
[Answer]
# [Awk](https://www.gnu.org/software/gawk/manual/gawk.html), 25 bytes
```
1,$0=$1>$2?$2>$3?$1:$3:$2
```
[Try it online!](https://tio.run/##SyzP/v/fUEfFwFbF0E7FyF7FyE7F2F7F0ErF2ErFCChloGBkoGBoYMBlhMwyRGVBGQYA)
[Answer]
# [R](https://www.r-project.org), 30 bytes
```
t=\(x,y,z)`if`(x>y,t(y,z,x),y)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhb7SmxjNCp0KnWqNBMy0xI0KuwqdUo0gFydCk2dSk2IopvZaRqGBjoKRkBsaGCgqaygawfkcKVpGOEUNUQWBTJQhGGiSIJw_RArFyyA0AA)
Port of [@l4m2's JavaScript answer](https://codegolf.stackexchange.com/a/269686/55372)
# [R](https://www.r-project.org), 33 bytes
```
\(x,y,z)`if`(x>y,`if`(y>z,x,z),y)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3FWM0KnQqdao0EzLTEjQq7Cp1wIxKuyqdCqCoTqUmVGF2moahgY6CERAbGhhoKivo2gE5XGkaRjhFDZFFgQwUYZgokiBcP8TKBQsgNAA)
Straightforward approach.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Rü@2β3Bè
```
[Try it online](https://tio.run/##yy9OTMpM/f8/6PAeB6Nzm4ydDq/4/z/a0EDHyEDH0MAgFgA) or [verify all test cases](https://tio.run/##yy9OTMpM/W90eK7x4cWHVpdV2ispPGqbpKBkX@nyP@jwHgejc5uMnQ6v@K/zPzra0EDHyEDH0MAgVifaCJVtiM6GM0EsiEaD2FgA).
**Explanation:**
```
R # Reverse the (implicit) input-triplet
ü # For each overlapping pair:
@ # Do a ≥ check
# (so we now have a pair [z≥y,y≥x])
2β # Convert this pair from a base-2 list to a base-10 integer
3B # Convert this base-10 integer to a base-3 integer
è # Use that to 0-based modular index into the (implicit) input-triplet
# (after which the result is output implicitly)
```
| input | `R` | `ü@` | `2β` | `3B` | (0-based modular index) | `è` (output) |
| --- | --- | --- | --- | --- | --- | --- |
| `[10,20,100]` | `[100,20,10]` | `[1,1]` | `3` | `10` | `1` | `20` |
| `[20,20,100]` | `[100,20,20]` | `[1,1]` | `3` | `10` | `1` | `20` |
| `[20,10,100]` | `[100,10,20]` | `[1,0]` | `2` | `2` | `2` | `100` |
| `[20,10,10]` | `[10,10,20]` | `[1,0]` | `2` | `2` | `2` | `10` |
| `[20,10,0]` | `[0,10,20]` | `[0,0]` | `0` | `0` | `0` | `20` |
| `[10,20,0]` | `[0,20,10]` | `[0,1]` | `1` | `1` | `1` | `20` |
[Answer]
# [Desmos](https://desmos.com/calculator), ~~29~~ 28 bytes
*-1 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)*
```
f(a,b,c)=\{a<=b:b,b>c:a,c\}
```
Literally just the piecewise function given in the challenge description.
[Try It On Desmos!](https://www.desmos.com/calculator/j0saxcxswf)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/dbsooczaa0)
[Answer]
# [Perl 5](https://www.perl.org/) `-Mfeature+signatures`, 35 bytes
```
sub($x,$y,$z){$y<$x?$z<$y?$x:$z:$y}
```
[Try it online!](https://tio.run/##K0gtyjH9r5Jm@7@4NElDpUJHpVJHpUqzWqXSRqXCXqXKRqXSXqXCSqXKSqWy9r@1SrytmkqahoOb5n9DAwUjAwVDAwMuI2SWISoLyjD4l19QkpmfV/xf1zctNbGktChVuzgzPQ/MAgoW5CQCAA "Perl 5 – Try It Online")
[Answer]
# Google Sheets, 40 bytes
```
=IFS(A1<=A2,A2,(A1>A2)*(A2<=A3),A1,1,A3)
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 27 bytes
```
t(x,y,z)=if(x>y,t(y,z,x),y)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWu0s0KnQqdao0bTPTNCrsKnVKNIA8nQpNnUpNiIqb-YkFBTmVGokKunYKBUWZeSVAphKIo6QAZEYbxuooJEYbgUnjWE1NHYXoaEMDHSMDHUMDA6BotBEaxxCDg2AbxMZCrYU5EAA)
A port of [@l4m2's Javascript answer](https://codegolf.stackexchange.com/a/269686/9288).
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 27 bytes
```
t(x,y,z)=if(x<=y,y,y>z,x,z)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWu0s0KnQqdao0bTPTNCpsbCuBnEq7Kp0KoBBExc38xIKCnEqNRAVdO4WCosy8EiBTCcRRUgAyow1jdRQSo43ApHGspqaOQnS0oYGOkYGOoYEBUDTaCI1jiMFBsA1iY6HWwhwIAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
>Ɲi0‘ị
```
A monadic Link that accepts a list, `[x, y, z]`, and yields the result of the TAK function.
**[Try it online!](https://tio.run/##y0rNyan8/9/u2NxMg0cNMx7u7v5/uP1R05r//6M1DA10FIyA2NDAQFOHS0HDCAvfECsfhQvixQIA "Jelly – Try It Online")**
### How?
```
>Ɲi0‘ị - Link: list of comparables, [x, y, z]
Ɲ - for neighbouring pairs:
> - greater than? -> [x>y, y>z] == [not(x<=y), not(y<=z)]
i0 - first 1-indexed index of 0, or 0 if not found
-> 1 if x<=y
2 if x>y and y<=z
0 if x>y and y>z
‘ - increment
-> 2 if x<=y
3 if x>y and y<=z
1 if x>y and y>z
ị - 1-index into {[x, y, z]}
-> y if x<=y
z if x>y and y<=z
x if x>y and y>z
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes
```
.+
$*
^(1*¶)??(1*)¶\2
$2
\G1
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZwQ46L9X0@bS0WLK07DUOvQNk17eyCteWhbjBGXihFXjLvh//@GBjoKRkBsaGDAZYTGNsRgw5kGAA "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on non-digits for convenience. Explanation:
```
.+
$*
```
Convert to unary.
```
^(1*¶)??(1*)¶\2
$2
```
If `x<=y` then delete `x`, otherwise if `y<=z` then delete both `x` and `y`. (The `??` is needed to prefer the `x<=y` test.)
```
\G1
```
Convert the first remaining input to decimal.
[Answer]
# TI-BASIC, 25 bytes
```
Ans(2+(Ans(1)>Ans(2))cos(π(Ans(2)≠min(Ans
```
Takes input in `Ans` as a list.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 28 bytes
```
(x,y,z)=>x<=y?y:x>y&y<=z?z:x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGiEtulpSVpuhZ7NCp0KnWqNG3tKmxsK-0rrSrsKtUqbWyr7KusKiBKbu5Mzs8rzs9J1cvJT9co0TA00FEwAmJDAwNNTQV9fQVdOyCfC1WREbGKDNEUAdk4VQEVwVXhUARWA7cP4oEFCyA0AA)
Literal translation of the simple version.
[Answer]
# [Funge-98](https://esolangs.org/wiki/Funge-98), 29 bytes
```
"HTRF"4(&&&RROO`!2j@._2P`j$.@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9X8ggJclMy0VBTUwsK8vdPUDTKctCLNwpIyFLRc/j/39BAwchAwdDAgAsA)
[Answer]
# [Python](https://www.python.org), ~~35~~ 32 bytes
-3 bytes thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)
```
lambda x,y,z:[y,[z,x][y>z]][x>y]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dY07DoMwDIZnOIU3kiogYKqQykUoQypAjQQhIqEiXKULC70Tt6kpVGXpYFn-_D-eL2XNvZXTXMEFrnNvKv-8QM2bW8FhYJaNSWZZNrIhz2w65nk2pDbfdVo0qu0MaKvdqu2gFrIEIdc70KYQMnEdIRWDclAY33BFygev2UeIik4oQgOtamGIB34KHqWu0_YGxRU5oRVP1QlpCCYwwA_dqqeFkyhkEONEYUhXcxy6JP7DogPDfYQ7-6Gvc2t6Aw)
---
# [Python](https://www.python.org), 36 bytes
Port of [l4m2's answer](https://codegolf.stackexchange.com/a/269686/91267)
```
f=lambda x,y,z:f(y,z,x)if x>y else y
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dY1BDoIwEEXXcIpZmNCaSoCVIcG71NjGSUppaDHUq7hho3fyNg6C0Y2Lmcl_8__M7eFiOHd2mu5D0Lv9c6MbI9vjScIoorjWmlEXI0cN4yGCMl5BXL0eW9f1AXz0qe56MGgVoJ117sMJbZ0maJ0ANTpooJWOqYs04m0kR4-O8dw7g4FlsDtAxnmadEMgs2ZbipJ0PdrA6IIA2vDl9fSUrCwEVFRlUfA5XBUpq_6w8ofR_IUr-6JPcvn0Ag)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
NθNηNζI⎇‹ηθ⎇‹ζηθζη
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ@Bxq8C8gOKMvNKNJwTi0s0QlKL8hKLKjV8UouLNTJ0FAo1dRRQxKp0FDKAYoU6ClWaIKampvX//4YKBgpG/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Straightforward approach. For a more interesting approach, my answer to the linked question needs to perform this calculation three times in a loop so it uses array indexing arithmetic.
```
Nθ First input as a number
Nη Second input as a number
Nζ Third input as a number
η Second input
‹ Is less than
θ First input
⎇ If true then
ζ Third input
‹ Is less than
η Second input
⎇ If true then
θ First input
ζ Else third input
η Else second input
I Cast to string
Implicitly print
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 26 bytes
```
f(x,y,z){x=x>y?y>z?x:z:y;}
```
[Try it online!](https://tio.run/##bZFRa4MwEMff@ykOoRDbyNqOPaxZ7cPYp5g@SEw62abFCEsifvVlURNXpYE79H7/uwv/0OhCqTEcSaywDlt5krE6q1if5VEfFelMUTbwnRUlCqFdgT19oWGike8pnKDd7zAcZtGRmU6NOs/3Uyx02s8b4H/CcKtk8spow/LlUCedttOqFA3Qj6ze2MzoJ6vHliCRb4dEPr/aeAow3P4/Bq6bVzWgfl1R5kzath1xny8gCs0qjvxFQnjwpc1UI7DdDnpvmr9@P2s0b8ApmVHlqLpLtaP6LhWW9s8ICoMO54xZNhm3bL7WVsJRsM4xjAFR3Oe1SEprkBuJQeDJSbvMTkzdmm7VmV/Kv7KLMNHPHw "C (gcc) – Try It Online")
] |
[Question]
[
Gelatin is a worse version of [Jelly](https://github.com/DennisMitchell/jelly). It is a tacit programming language that always takes a single integer argument and that has 7 (or maybe 16) commands. You are to take in a Gelatin program and its argument and output the result.
## Gelatin
Gelatin programs will always match the following regex:
```
^[+_DSa\d~]*$
```
i.e. they will only contain `+_DSa0123456789~` characters. The commands in Gelatin are:
* Digits return their value (`0` is \$0\$, `1` is \$1\$ etc.) Digits are stand alone, so `10` represents \$1\$ and \$0\$, not \$10\$
* `a` returns the argument passed to the Gelatin program
* `D` takes a left argument and returns it minus one (decremented)
* `S` takes a left argument and returns its square
* `+` takes a left and a right argument and returns their sum
* `_` takes a left and a right argument and returns their difference (subtract the right from the left)
* `~` is a special command. It is always preceded by either `+` or `_` and it indicates that the preceding command uses the same argument for both the left and the right.
Each command - aside from `~` - in Gelatin has a fixed *arity*, which is the number of arguments it takes. Digits and `a` have an arity of \$0\$ (termed *nilads*), `D` and `S` have an arity of \$1\$ (termed *monads*, [no relation](https://en.wikipedia.org/wiki/Monad_(functional_programming))) and `+` and `_` have an arity of \$2\$ (termed *dyads*)
If `+` or `_` is followed by a `~`, however, they become *monads*. This affects how the program is parsed.
Tacit languages try to avoid referring to their arguments as much as possible. Instead, they compose the functions in their code so that, when run, the correct output is produced. How the functions are composed depends on their arity.
Each program has a "flow-through" value, `v` and an argument `ω`. `v` is initially equal to `ω`. We match the start of the program against one of the following arity patterns - earliest first, update `v` and remove the matched pattern from the start. This continues until the program is empty:
* **2, 1**: This is a dyad `d`, followed by a monad `M`. First, we apply the monad to `ω`, yielding `M(ω)`. We then update `v` to be equal to `d(v, M(ω))`.
* **2, 0**: This is a dyad `d`, followed by a nilad `N`. We simply update `v` to be `d(v, N)`
* **0, 2**: The reverse of the previous pattern, `v` becomes `d(N, v)`
* **2**: The first arity is a dyad `d`, and it's not followed by either a monad or a nilad as it would've been matches by the first 2. Therefore, we set `v` to be `d(v, ω)`
* **1**: The first arity is a monad `M`. We simply set `v` to be `M(v)`
For example, consider the program `+S+~_2_` with an argument `5`. The arities of this are `[2, 1, 1, 2, 0, 2]` (note that `+~` is one arity, `1`). We start with `v = ω = 5`:
* The first 2 arities match pattern **2, 1** (`+S`), so we calculate `S(ω) = S(5) = 25`, then calculate `v = v + S(ω) = 5 + 25 = 30`
* The next arity matches pattern **1** (`+~`). `+~` means we add the argument to itself, so we double it. Therefore, we apply the monad to `v`, updating it to `v = v + v = 30 + 30 = 60`
* The next arity pattern is **2, 0** (`_2`), which just subtracts 2, updating `v` to `v = v - 2 = 60 - 2 = 58`
* Finally, the last arity pattern is **2** (`_`), meaning we update `v` to be `v = v - ω = 58 - 5 = 53`.
* There are now no more arity patterns to match, so we end the program
At the end of the program, Gelatin outputs the value of `v` and terminates.
In a more general sense, `+S+~_2_` is a function that, with an argument \$\omega\$, calculates \$2(\omega + \omega^2) - 2 - \omega = 2\omega^2 + \omega - 2\$.
---
You are to take a string representing a Gelatin program, using the characters specified above, and a positive integer \$\omega\$ and output the result of running the Gelatin program with an argument of \$\omega\$
You may assume that the arities of the program will always fit one of the 5 patterns (so nothing like `S1S` (**1, 0, 1**) will appear), and that the flow-through value will never exceed your language's integer bounds. The output may be negative.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
## Test cases
```
Program ω out
+S 7 56
_aSS+ 20 20
++DDDS+1_ 15 1750
_S 13 -156
D0+ 12 11
_+~SSS++__S++a 6 1679598
_++a 17 34
a+_6D 20 33
D+_+_aD 17 15
5 5
DD 8 6
+_aa+S+SS+_+ 4 6404
+9+S_ 19 370
_DDD+_a+_3_4D_ 13 -9
SS_SD+ 15 50414
+~D_~_ 7 -7
D_a+S 10 99
_S+aD+4 1 4
+_a+ 3 6
_aD+60+ 13 5
```
[This](https://tio.run/##RVA9S8RAEO39HTbiibs5P7kiFgGLs0sTPI4zRRAltXhNSGwEK/EK70CRM2sh6BXCQlYkxYQ78Gfs/pH4Np4Iw8w83sybt3sexfGwrk36sD7w/JAlJn0MqrEXkCBlsi8XmJF0mC5uONefU84HlwcNJBGQrG5pin4@ijGYkKTXqCqh5vmNJFLIuNPe2t7Z3dsHsvrHZ@bqja9U1ySxilj9LYiFTaR0kfPo@97t8X6r5/TB522LIUA5vdDzX5ObdGxZ559dcsIW0QxYl0fVE81Iubi6GC1Nk4xgBI@d352arNAq6wJ3TVZ6Jp10IODTR3ISgoNrEsOWw/AvnYvNxrAqMd3svWs12Vg7rGvOfgA) is a program that randomly generates \$n\$ Gelatin programs, along with random inputs and the intended outputs
[Answer]
# JavaScript (ES6), ~~306 ... 227~~ 226 bytes
Expects `(program)(ω)`.
```
s=>g=(v,w=v,n=0,h=_=>(O={a:w,'+':"x+y",_:"x-y",S:"x*x",D:"x-1",'+~':"x*2",'_~':"0"}[c=(s+'a').match(/.~?/g)[n++]]||+c)[2]>O?2:O>g)=>(I=h(i=h(E=(o,x,y)=>eval(o)),o=O),o)?g(i?E(o,v,I?I-2?E(O,w):w:O):I?E(O,o,v):v,w,n-=i==I|i&1):v
```
[Try it online!](https://tio.run/##dVPBjtowEL3nK6wcGnttQgIBlqwMF1OJEwcfKbKsELKp2IQmKbDaXb6gUi89tv/R79kf6CfQyRZ146w2Erbf@M3Mm/HwWe91GRXprupk@To@b/i55JOE4z078D3LuMduueITvOAPOjwwhzqhfaT3NlOwd2CXsF8dbSZq7NvAONWUqx4cVX307KdlxHFJHe0Q905X0S3uuqdpNyHLjNLV6vGRRmTZW00W0164mCQE0s35LU7hN@M4Z0d2D7Z4r7c4J4TlfAELmSY4nc7ges/m03mnB@cFO5DwEC5IOH9BcEdCqIRlHZ5yPn9MP/hgOBfxl69pEWNnU4KkItbrj@k2lvdZhD3iVrmsijRLMHHL3TatsP0ps4m7yYuZBu0l4hP0YCG0jSu03BUJQweG4uMujqp4vUIclRe/LqLduuLdP5/ShbB3mJAbcI7yrMy3sbvNEwwx3J1ez7I19ocEUYSLGDzQpr4hmB6IIepCvX5l8v/p0RQ5f35/f/75A1YHhch5/vXNqVM@kZszlcj4RiYcDJvIUlpK2jD0PINtQotSIYSkvroY/IHB9kcDrxm7pcTvG7DjN7VYwqMmu2dC39RNTxKUU6Vg0QgNW6mGo/FgfP3KrjlNoQa7HxixNVVD8X5P@kYZlqCKKi3ei123yEKtb9CClhCm5dqEreosSKippNAA9dK0oEUPvMCgj6lUTU1js6CR@coKHhkyUNVXgVBv3830tqRUUlCz4mZxXuAHTTEnoU7q3fnsmNgSIKQ5R775GOOWGBgHLehrPt@MHrxtpDF1/bd9h7@IoMPGcLbaAdX@BQ "JavaScript (Node.js) – Try It Online")
## Commented
### Header and helper function `h`
```
s => // outer function taking the program string s
g = ( // g = inner recursive function taking:
v, // v = current output value
w = v, // w = initial value of v (aka ω)
n = 0, // n = pointer in the command stream
h = _ => ( // h is a helper function which turns the next
// command into a JS code snippet or an integer,
// along with the arity of the command:
O = { // 1) command:
a : w, // 'a' : use w
'+' : "x+y", // '+' : add y to x
_ : "x-y", // '_' : subtract y from x
S : "x*x", // 'S' : square x
D : "x-1", // 'D' : decrement x
'+~': "x*2", // '+~': double x
'_~': "0" // '_~': yield 0
}[ //
c = (s + 'a') // append an explicit 'a' command at the end
.match(/.~?/g) // split the commands (either "x" or "x~")
[n++] // load the next command into c
] //
|| +c // if the above is undefined, use +c (it's a digit)
) // 2) arity of the command:
[2] > O ? 2 // dyad if the 3rd character is 'y'
: O > g // monad if it's a code snippet, or nilad otherwise
) => //
```
### Body of `g`
```
( I = // (O, I) = (2nd command, 2nd arity)
h( i = // (o, i) = (1st command, 1st arity)
h( E = // E is a helper function
(o, x, y) => // which takes o, x, y
eval(o) // and evaluates o in this local context
), //
o = O //
), //
o // we eventually test o
) ? // if o is defined:
g( // do a recursive call to g:
i ? // if the 1st command is not a nilad:
E( // v = result of a call to E with:
o, // the 1st command
v, // x = v
I ? // if the 2nd command is not a nilad:
I - 2 ? // if the 2nd command is a monad:
E(O, w) // y = result of the 2nd command as a monad
: // else (the 2nd command is a dyad):
w // y = w
: // else:
O // y = O
) // end of call
: // else (the 1st command is a nilad):
I ? // if the 2nd command is not a nilad:
E(O, o, v) // v = result of the 2nd command as a dyad
: // else:
v, // v is left unchanged
w, // pass w unchanged
n -= // decrement n if only one command was 'consumed':
i == I | i & 1 // i.e. if i = I or i is odd
) // end of recursive call
: // else:
v // we're done: return the final output value
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
⁾D’y“S²a⁸~`”yKv
```
[Try it online!](https://tio.run/##RVCxrsIwDPwVtg6HRENLgd0boydUVSYDC2JG6lKV9xdPgpmFiYmJAf4kPxKcpO91iezz2XeXw/54bL135xe5/rd1/YXfD@vOz27n@mu7OfnPbeZ@7lvv6zoDZ9PJsplO6kwsM7Sb57EFiIhhRCGzSIxANkWsKQ9cM08DdKzLENHHKl4NcGxMum8hFY33CQKxNM61SjIUwFUyIdaCobclyJUJXIOjq3VSUZ/KgxRSkowOmYUJo3t0JJ38xyVdiXnyIRssoQzAn3LYLYavIVQpcNE0Xw "Jelly – Try It Online")
```
⁾D’y Substitute D for Jelly's decrement builtin.
(This is done alone because ’ is a string terminator.)
“ ”y Substitute
S² S for square,
a⁸ a for left argument,
~` and ~ for reuse argument.
(+ and _ are already plus and minus.)
K Join the program on spaces to split up multi-digit numbers,
v and evaluate it as Jelly with the right argument as its sole argument.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 147 bytes
```
Nθ≔θζF⁺⪫⪪⪫⪪S+~¦d¦_~¦z¦i«≡№DSdiz++__鲫F⁼²Lυ⊞υθF²⊞υ⎇⊖Lυζι»¹«≔⎇υθζε≡ιD≦⊖εS≦×εεd≦⊗εz≦⁻εε⎚¿υ⊞υε≔εζ»⊞υ⎇⁼aιθIι¿‹²Lυ«≔⎇⁼+§υ¹⁺§υ⁰§υ²⁻§υ⁰§υ²ζ≔…⟦ζι⟧⁻Lυ³υ»»Iζ
```
[Try it online!](https://tio.run/##fVJNb4IwGD7Lr2g4lcCS6Q5L3MngDi66mOBtWUyFF2lSC9J2myzur7O2gKIuu0DbPB99nrdxRso4J6yuZ7xQ8lXtNlDivffkTISgW473Aar0Ls1LhJdMCfySU46jglHZX1p2JEvKt9gLkOv/uOaX2O@62VT2S13PQ9/OQHxSGWcIh7niErvTKKGV76/XboBog4iJADQam@XA@j/vFWECjwI0B76VGVaeRi6V0KsAmUu3wNH5dAUlJ@UBTyEuYQdcQoLPbB3O2mnmsTUcNoZt/I5u9E0TAQJr092e2ps2THfqjtGCFC2159ixGljUh80hlXhFdyA06BKXXMrlasOupaobqQXlqi@VQEoUk2MUMiAltmc66oCmSBdwqkmDETAt2bpBM3YDPSlcV9qOwyV2ZLagkAipO@kKNSZzEDcj@6PgTszXYhM54wl8Ga@hmZF9d73De@8CMzIYm/t/kNdm6qzDQ8wgzPICv5lX8N6JnG4aoAdDUk2ao7PUz1tim7HSEev60fGj@u6D/QI "Charcoal – Try It Online") Link is to verbose version of code. Takes the argument as the first input and the script as the second input. Explanation:
```
Nθ≔θζ
```
Input the argument and copy it to the flow-though value.
```
F⁺⪫⪪⪫⪪S+~¦d¦_~¦z¦i«
```
Transform the script by replacing the `+~` and `_~` operators with single-byte operators and appending the identity operator (in case the script ends with a dyadic operator). Loop over each operator.
```
≡№DSdiz++__ι
```
See how many arguments this operator expects.
```
²«F⁼²Lυ⊞υθF²⊞υ⎇⊖Lυζι»
```
If this is a dyad, then if there is already a dyad on the stack then push the argument as its RHS. Push the flow-through value and the dyad, ensuring that the dyad is between its operands. Note that the flow-through value is incorrect if there is already a dyad on the stack but that will be fixed up later.
```
¹«≔⎇υθζε≡ιD≦⊖εS≦×εεd≦⊗εz≦⁻εε⎚¿υ⊞υε≔εζ»
```
If this is a monad, then get either the flow-through value or the argument (depending on whether there is a dyad on the stack), apply the monad to it, then save it to the flow-through value or the stack (again depending on whether there is a dyad on the stack).
```
⊞υ⎇⁼aιθIι
```
Otherwise push either the argument (if this is an `a` operator) or the numeric value of the digit to the stack, assuming that the next operator is a dyad.
```
¿‹²Lυ«
```
If we now have a dyad with both its arguments on the stack, then:
```
≔⎇⁼+§υ¹⁺§υ⁰§υ²⁻§υ⁰§υ²ζ
```
Update the flow-through value with the result of the dyad.
```
≔…⟦ζι⟧⁻Lυ³υ
```
If there were in fact two dyads on the stack, then recalculate the stack with the new flow-through value and the current dyad, otherwise clear the stack.
```
»»Iζ
```
Once the script has been processed output the final flow-through value.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 193 bytes (SBCS)
```
B M N←'(?<!⍨)([+_])' '(D|S|⍨[+_])' '[0-9⍵]'
_←-⍨
S←×⍨
D←¯1∘+
{(⍎'{','⍵}',⍨'.'⎕R' \0 '⌽(B,M)(B,N)(∊'('N')'B)(∊B'(?!'N'|'M')')⎕R')⊢\1)⍵\2((' ')⊢\0(' ')⊢⍨\2\1(' ')⊢\0⍵('⊢'a' '(.)~'⎕R'⍵' '⍨\1'⊢⍺)⍵}
```
[Try it online!](https://tio.run/##dVM9axtBEO3vV6yr2WV0Zlf35YMEg9hWKrKlTlkWgtUYItwFyyodYSKTJiRVilTpUqUJpLH/yf4RZfYS49tVpOKYN/tm5s2H3Ooyf/POXb5d7vcTNmUzf/sR@PmLE7/7Lvgc7UIAA67XZk2eJzyXeet3PxeQWeLn9JIZMh4/B0uT9fBD@e0XzC7IvuZ@dw/XMAIKuYERceAU/P2nV8A6ycB/@M0no6mgz0xwv70DDjMQMOnBhNScEF7DlHyiDxP@7lunBKXrxpyTnt4hnywq0I079fxARA5kgQu9nIrN3@rkJhzYCvqwXyHlzd5v37NlxtiKOXZFDXCYv2YLDEEGOklJd1/pmWB4pOauxMsVu2BkuYyC98sMDYt@TQyreoiyZWadMThwjWXEJ0gkRK21QWX/eVUVkVRTyThpIkIVEczVUAbxtcSYP46hSkXjxpBstJY@jrE6KVc3bdWeDfmBNRQc8Ysyye/Q1vr4UIoi4Wu0aJ0@lj@MKwt7TXaRwJBIx76zGCZ9hs1Y59AgDcP2IyyTgFKWSUCLxg61tXFrjUxnTaunKmgLW2p7uMs2lWSMNRrj7odtylKVsaSNtht79GTzJq2gSc7wwlS8nvZAEp2J0/hcVcUVyv@NNbrI4nAP/X9HYz043WQ0FfsD "APL (Dyalog Unicode) – Try It Online")
Takes the program on the left and the argument on the right. I figured this'd be easy with APL's trains and regex, but apparently not ⍨.
```
⍝ Regexes (regices?) for dyads (B), monads (M), and nilads (N)
B M N←'(?<!⍨)([+_])' '(D|S|⍨[+_])' '[0-9⍵]'
_←-⍨ ⍝ The _ dyad (flipped because APL is RTL)
S←×⍨ ⍝ The S monad (multiply with itself)
D←¯1∘+ ⍝ The D monad (add -1 to decrement)
```
The actual function:
```
{(⍎'{','⍵}',⍨'.'⎕R' \0 '⌽(B,M)(B,N)(∊'('N')'B)(∊B'(?!'N'|'M')')⎕R')⊢\1)⍵\2((' ')⊢\0(' ')⊢⍨\2\1(' ')⊢\0⍵('⊢'a' '(.)~'⎕R'⍵' '⍨\1'⊢⍺)⍵}
```
First `'a' '(.)~'⎕R'⍵' '⍨\1'⊢⍺` replaces `a` with `⍵` and `+~` and `_~` with `⍨+` and `⍨_`. This is just to make life simpler later. The next part is
```
(B,M)(B,N)(∊'('N')'B)(∊B'(?!'N'|'M')')⎕R')⊢\1)⍵\2((' ')⊢\0(' ')⊢⍨\2\1(' ')⊢\0⍵('
```
This may look like a mess, but it's actually pretty simple:
* The pattern `BM` (dyad, monad) becomes `((M⍵)B⊢)`, but reversed.
* The pattern `BN` (dyad, nilad) becomes `(NB⊢)`, but reversed.
* The pattern `NB` (nilad, dyad) becomes `(NB⍨⊢)`, but reversed.
* The pattern `B` (dyad not followed by a nilad or monad) becomes `(⍵B⊢)`, but reversed.
* Monads not preceded by dyads are left as is.
This is pretty much an exact translation of the rules in the question. After this, `⌽` reverses everything because unlike Jelly, APL goes from right to left (this is also why `_` takes its arguments reversed). Then `'.'⎕R' \0 '` puts a space on each side of each character so that APL doesn't throw up the result thinking `SD` is a single token. Then the result `r` is turned into `{r⍵}` and evaluated to obtain a dfn. This function is applied to the outer function's right argument, `⍵`.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 129 bytes
```
YaLRqR"+~_~_"<>2;^"TZ-"`\W\w?|[A-Z]|..`Y V$0R['^.XU`([A-Z]|^.)$`][`&y``&a`]R(^"DSTZ").CXX'Y.[B.vB.'*.B"2*".B0]R`\W$`_.yR`^\W`y._y
```
[Try it online!](https://tio.run/##Jcy7CsIwFADQX5FLaNqGXkpxsyhGR6ek2kea5GZ0q4sSKP31KLie4SzPJaUx3NRLgdj85qE9NgcH3VQBzf38Oa3mXE12RaRx92C1MtzhcKf8zw4LRtZQFomyQFblDq66m6DAyzDwEY3Et0ReooSmBJS1Vb@XkceoyM09RfQxJeFDEFpoLbxI@y8 "Pip – Try It Online")
### How?
We're basically going to use a translate-and-eval approach. Unlike Jelly (*cough*), Pip's execution model is rather different from Gelatin's, so the translation takes some work. We are fortunate in some ways: `0-9` and `+` can be used as they are, and so can `a` if we take the input number as a command-line argument.
```
Ya
```
Copy the input number into `y`, which will be our flow-through value.
```
qR"+~_~_"<>2;^"TZ-"
```
Read the Gelatin program from stdin and make some substitutions: `+~` -> `T` (for Twice, since `x+x` = `2*x`), `_~` -> `Z` (for Zero, since `x-x` = `0`), and `_` -> `-` (so we can eval it later). After these substitutions, we have two dyads (`+` and `-`), four monads (`D`, `S`, `T`, and `Z`), and eleven nilads (`0` through `9`, plus `a`). Note that all monads are capital letters. Note also that both dyads are symbols, whereas all monads and nilads are alphanumeric.
```
LR ... `\W\w?|[A-Z]|..`
```
Parse the arity patterns with regex and loop over all matches. The first branch `\W\w?` matches a dyad followed by a monad, nilad, or nothing; the second branch `[A-Z]` matches a single monad; and the third branch `..` matches two characters, which in practice is the only remaining case, a nilad followed by a dyad.
```
$0R['^.XU`([A-Z]|^.)$`][`&y``&a`]
```
Starting from the arity pattern stored in the match variable `$0`, we make some more replacements. This stage adds the right argument for monads and for solitary dyads: A monad at the beginning of the pattern must be pattern 1; its argument should be `y`, the flow-through value. After that replacement, any other monad (pattern 2,1) or any other single character (pattern 2) should have a right argument of `a`, the input number.
```
... R(^"DSTZ").CXX'Y.[B.vB.'*.B"2*".B0]
```
Next, we replace monads with the appropriate Pip expressions: `Dx` (here `x` represents the right argument, either `y` or `v`) becomes `Yx-1`; `Sx` becomes `Yx*x`; `Tx` becomes `Y2*x`; and `Zx` becomes `Y0`. (The `Y` enforces correct precedence of operations in the 2,1 pattern.)
```
... R`\W$`_.yR`^\W`y._
```
Finally, we fill in the missing argument of each dyad. An operator at the end of the pattern is a dyad with a left argument (pattern 0,2), so its right argument should be `y`, the flow-through value. An operator at the beginning of the pattern is a dyad with a right argument (pattern 2,0 or 2,1 or 2), so its left argument should be `y.
```
Y V ...
```
Evaluate the resulting expression as Pip code, and store the result back into `y`.
```
y
```
After the loop, output the final value of `y`.
] |
[Question]
[
*Credit to Geobits in TNB for the idea*
A [post](https://codegolf.stackexchange.com/questions/177390/recursive-multiplication) without sufficient detail recently posited an interesting game:
2 children sit in front of an array of candy. Each piece of candy is numbered 1 to `x`, with `x` being the total amount of candy present. There is exactly 1 occurrence of each number.
The goal of the game is for the children to eat candy and multiply the values of the candy they have eaten to arrive at a final score, with the higher score winning.
However the original post missed key information, such as how candy is selected, so the kids in our story decided that the older kid gets to go first, and can eat up to half the candy, however once he announces the end of his turn, he can't change his mind.
One of the kids in this game doesn't like candy, so he wants to eat as little as possible, and he once watched his dad write some code once, and figures he can use the skills gained from that to work out how much candy he needs to eat to ensure victory, whilst still eating as little as possible.
## The Challenge
Given the total number of candy `x`, your program or function should output the smallest amount of candy he has to eat to ensure victory, `n`, even if his opponent eats all the remaining candy.
Naturally bigger numbers make bigger numbers, so whatever amount you'll give him, he'll eat the `n` largest numbers.
## The Rules
* `x` will always be a *positive* integer in the range `0 < x! <= l` where `l` is the upper limit of your language's number handling capabilities
* It is guaranteed that the kid will always eat the `n` largest numbers, for example for `x = 5` and `n = 2`, he will eat `4` and `5`
## Test cases
```
x = 1
n = 1
(1 > 0)
x = 2
n = 1
(2 > 1)
x = 4
n = 2
(3 * 4 == 12 > 1 * 2 == 2)
x = 5
n = 2
(4 * 5 == 20 > 1 * 2 * 3 == 6)
x = 100
n = 42
(product([59..100]) > product([1..58]))
x = 500
n = 220
(product([281..500]) > product([1..280]))
```
## Scoring
Unfortunately, our brave contestant has nothing to write his code with, so he has to arrange the pieces of candy into the characters of the code, as a result, your code needs to be as small as possible, smallest code in bytes wins!
[Answer]
# [Python 3](https://docs.python.org/3/), 76 bytes
```
F=lambda x:x<2or x*F(x-1)
f=lambda x,n=1:x<2or n*(F(x)>F(x-n)**2)or f(x,n+1)
```
[Try it online!](https://tio.run/##PYrBCsJADETvfkWOyapls9pLsT32PyqyGKjpUldYv35NRQyTGZI36Z3vi55qHft5elxvE5SuXMKyQnEjliPTLv7JQXv@UXVomIato@RcIHtGtMqeqUY7BERN6ZWRmmeaxbJLq2jGbePXhWwqQ4AztMDeQ@v9Bw "Python 3 – Try It Online")
Relies on the fact that for eating \$n\$ candies to still win and the total number of candies being \$x\$, \$\frac{x!}{(x-n)!}>(x-n)!\$ must be true, which means \$x!>((x-n)!)^2\$.
-1 from Skidsdev
~~-3~~ -6 from BMO
-3 from Sparr
+6 to fix `x = 1`
[Answer]
# JavaScript (ES6), 53 bytes
```
n=>(g=p=>x<n?g(p*++x):q<p&&1+g(p/n,q*=n--))(q=x=1)||n
```
[Try it online!](https://tio.run/##FcpBDoIwEEDRq8yCkBlqVVxKB69Cg7TRkGkLxpAAZ6@4@y/5b/u1cz@94kdLeA7ZcRZu0XPkdjHy8BgrpRa6JxPLslaHL3JKFYvWRJh44Zq2TbILEwowXBsQMAy3fyhF0AeZwzicx@Cxs1isstPxFatDob2j/AM "JavaScript (Node.js) – Try It Online")
### Working range
Interestingly, the differences between the kids' products are always big enough that the loss of precision inherent to IEEE 754 encoding is not an issue.
As a result, it works for \$0 \le n \le 170\$. Beyond that, both the mantissa and the exponent overflow (yielding *+Infinity*) and [we'd need BigInts](https://tio.run/##HcrRCoJAEEbhV5kLkRk3S7usHXsVxVQK@XfViAX12Tfp7nxw3s23Wdr55T853LOLvUZoxYN6rYLFY2CfGRPkNlmfpqU5fMFpyhR5LsKTBi0h24bYu5lBSgXuBLJK1@Kfxgi1Dosbu/PoBq4bTlbscqzJ2jNkryX@AA) (+1 byte).
### How?
Let \$p\$ be the candy product of the other kid and let \$q\$ be our own candy product.
1. We start with \$p=n!\$ (all the candy for the other kid) and \$q=1\$ (nothing for us).
2. We repeat the following operations until \$q\ge p\$:
* divide \$p\$ by \$n\$
* multiply \$q\$ by \$n\$
* decrement \$n\$
The result is the number of required iterations. (At each iteration, we 'take the next highest candy from the other kid'.)
### Commented
This is implemented as a single recursive function which first compute \$n!\$ and then enters the loop described above.
```
n => ( // main function taking n
g = p => // g = recursive function taking p
x < n ? // if x is less than n:
g( // this is the first part of the recursion:
p * ++x // we're computing p = n! by multiplying p
) // by x = 1 .. n
: // else (second part):
q < p && // while q is less than p:
1 + g( // add 1 to the final result
p / n, // divide p by n
q *= n-- // multiply q by n; decrement n
) //
)(q = x = 1) // initial call to g with p = q = x = 1
|| n // edge cases: return n for n < 2
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḊPÐƤ<!€TL
```
**[Try it online!](https://tio.run/##y0rNyan8///hjq6AwxOOLbFRfNS0JsTn////pgYGAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjq6AwxOOLbFRfNS0JsTn/9E9h9uBLPf//3Myi0s0ihLz0lM1DHUUDM00NRW0FaINDQx0FEwNDGIB "Jelly – Try It Online").
### How?
```
ḊPÐƤ<!€TL - Link: integer, x e.g. 7
Ḋ - dequeue (implicit range of x) [ 2, 3, 4, 5, 6, 7]
ÐƤ - for postfixes [all, allButFirst, ...]:
P - product [5040,2520, 840, 210, 42, 7]
€ - for each (in implicit range of x):
! - factorial [ 1, 2, 6, 24, 120, 720, 5040]
< - (left) less than (right)? [ 0, 0, 0, 0, 1, 1, 5040]
- -- note right always 1 longer than left giving trailing x! like the 5040 ^
T - truthy indices [ 5, 6, 7 ]
L - length 3
```
[Answer]
# [R](https://www.r-project.org/), ~~70~~ ~~41~~ 38 bytes
*-29 because Dennis knows **all** the internal functions*
*-3 switching to scan() input*
```
sum(prod(x<-scan():1)<=cumprod(1:x)^2)
```
[Try it online!](https://tio.run/##K/r/v7g0V6OgKD9Fo8JGtzg5MU9D08pQ08Y2uTQXLGpoVaEZZ6T539DA4D8A "R – Try It Online")
Pretty simple R implementation of nedla2004's [Python3 answer](https://codegolf.stackexchange.com/a/177497/72784).
~~I feel like there's a cleaner implementation of the 1-handling, and I'd like to lose the curly-braces.~~
I'm mad I didn't go back to using a which approach, madder that I used a strict less-than, but even madder still that I didn't know there's a `cumprod()` function. Great optimisation by Dennis.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 bytes
```
+/!≤2*⍨!∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qW9CjtgmGRhbm/7X1FR91LjHSetS7QvFRx4xHvZv/pwHlHvX2AZV5@j/qaj603vhR20QgLzjIGUiGeHgG/087tMJQwUjBRMFUwdDAQMHUwAAA "APL (Dyalog Unicode) – Try It Online")
Port of [Dennis' answer](https://codegolf.stackexchange.com/a/177541/74163). Thanks to, well, Dennis for it.
### How:
```
+/!≤2*⍨!∘⍳ ⍝ Tacit function, takes 1 argument (E.g. 5)
⍳ ⍝ Range 1 2 3 4 5
!∘ ⍝ Factorials. Yields 1 2 6 24 120
2*⍨ ⍝ Squared. Yields 1 4 36 576 14400
! ⍝ Factorial of the argument. Yields 120.
≤ ⍝ Less than or equal to. Yields 0 0 0 1 1
+/ ⍝ Sum the results, yielding 2.
```
Since this answer wasn't strictly made by me, I'll keep my original answer below.
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~14 12~~ 11 bytes
```
(+/!>×\)⌽∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qW9CjtgmGRhbmXECOpz@QY/BfQ1tf0e7w9BjNRz17H3XMeNS7@X8aUOJRbx9ETVfzofXGj9omAnnBQc5AMsTDM/h/2qEVhgpGCiYKpgqGBgYKpgYGAA "APL (Dyalog Unicode) – Try It Online")
Prefix tacit function. Basically a Dyalog port of [Jonathan's answer](https://codegolf.stackexchange.com/a/177511/74163).
Thanks to ngn and H.PWiz for the help in chat. Thanks to ngn also for saving me a byte.
Thanks to Dennis for pointing out that my original code was wrong. Turns out it saved me 2 bytes.
Uses `⎕IO←0`.
### How:
```
+/(!>×\)∘⌽∘⍳ ⍝ Tacit function, taking 1 argument (E.g. 5).
⍳ ⍝ Range 0 1 2 3 4
⌽∘ ⍝ Then reverse, yielding 4 3 2 1 0
( )∘ ⍝ Compose with (or: "use as argument for")
! ⍝ Factorial (of each element in the vector), yielding 24 6 2 1 1
×\ ⍝ Multiply scan. Yields 4 12 24 24 0
> ⍝ Is greater than. Yields 1 0 0 0 1
+/ ⍝ Finally, sum the result, yielding 2.
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~52~~ 51 bytes
Using the straightforward approach: We check whether the product of the last \$n\$ numbers, which is \$\frac{x!}{(x-n)!}\$ is less than the product of the first \$n\$ numbers, namely \$(x-n)!\$ and takes the least \$n\$ for which this is true.
```
g b=product[1..b]
f x=[n|n<-[1..],g(x-n)^2<=g x]!!0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P10hybagKD@lNLkk2lBPLymWK02hwjY6rybPRhckEKuTrlGhm6cZZ2Rjm65QEauoaPA/NzEzT8FWoaAoM69EQUUhzUbFLtpIx0THVMfQwCD2PwA "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
R!²<!ċ0
```
[Try it online!](https://tio.run/##y0rNyan8/z9I8dAmG8Uj3Qb/j@5RONz@qGmNgvv//4Y6CkY6CiY6CqY6CoYGBkDawAAA "Jelly – Try It Online")
### How it works
```
R!²<!ċ0 Main link. Argument: n
R Range; yield [1, ..., n].
! Map factorial over the range.
² Take the squares of the factorials.
! Compute the factorial of n.
< Compare the squares with the factorial of n.
ċ0 Count the number of zeroes.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~183~~ ~~176~~ 149 bytes
```
R=reversed
def M(I,r=1):
for i in I:r*=i;yield r
def f(x):S=[*range(1,x+1)];return([n for n,a,b in zip([0]+S,R([*M(S)]),[0,*M(R(S))])if b>a]+[x])[0]
```
[Try it online!](https://tio.run/##NY4xC8IwEIV3f8WNd@0NCVqESt0dXNoxZKg01UCJ5YxS/fM1EVyO9@B79978jrd72K5r24h7OXm4YTO4Ec54Ymk01RsY7wIefIBTLUXjD2/vpgHkh424UN01ppA@XB1qXkpN9iAuPiWgCb9w4J4v@cHHz2iULTtu0RRn7MgSG8VJtskk50e4HHtbmsVSItccjzk6@UfEf4lWqYVKMFBpBq0UQ5XPXimbBs/iQ8TIaV0kWjXsoMpUhr4 "Python 3 – Try It Online")
It's is a lot faster than some other solutions - 0(N) multiplications instead of O(N²) - but I can't manage to reduce code size.
-27 from Jo King
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 57 bytes
```
import StdEnv
$x=while(\e=prod[1..x-e]^2>prod[1..x])inc 1
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLpcK2PCMzJ1UjJtW2oCg/JdpQT69CNzU2zsgOzo3VzMxLVjD8H1ySCNRoCzSmQEFFIdpQR8FIR8FER8E09v@/5LScxPTi/7qePv9dKvMSczOTiwE "Clean – Try It Online")
A straight-forward solution.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 11 bytes
```
E!IN-!n›iNq
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fVdHTT1cx71HDrky/wv//DQ0M/gMA "05AB1E – Try It Online")
```
E!IN-!n›iNq
E For loop with N from [1 ... input]
! Push factorial of input
IN- Push input - N (x - n)
! Factorial
n Square
› Push input! > (input - N)^2 or x! > (x - n)^2
i If, run code after if top of stack is 1 (found minimum number of candies)
N Push N
q Quit, and as nothing has been printed, N is implicitly printed
```
Uses the same approach as my [Python](https://codegolf.stackexchange.com/a/177497/59363) submission. Very new to 05AB1E so any tips on code or explaination greatly appreciated.
-4 bytes thanks to Kevin Cruijssen
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
ạ‘rP>ạ!¥
1ç1#«
```
[Try it online!](https://tio.run/##y0rNyan8///hroWPGmYUBdgBGYqHlnIZHl5uqHxo9f///00NDAA "Jelly – Try It Online")
Handles 1 correctly.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
NθI⊕ΣEθ‹Π⊕…ιθ∨Π…¹⊕ι¹
```
[Try it online!](https://tio.run/##VcpNCsIwEEDhvafIcgIRmnWXrgr@lHqCmA4aaKbNJPH602JB9G3f51@O/ewmkY6WWq41PpAh6fbQc6ACJ5cLdOQZI1LBEe41wsUtkIw6Y87Q8zxW/28GR0@EYFTSW0bd@Mv2ZY369eGjrN5rRWzTyPE9rQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ Input `n`
Σ Sum of
θ `n`
E Mapped over implicit range
Π Product of
ι Current value
… Range to
θ `n`
⊕ Incremented
‹ Less than
Π Product of
¹ Literal 1
… Range to
ι Current value
⊕ Incremented
∨ Logical Or
¹ Literal 1
⊕ Incremented
I Cast to string
Implicitly print
```
`Product` on an empty list in Charcoal returns `None` rather than `1`, so I have to logically `Or` it.
[Answer]
# [PHP](https://php.net/), 107 bytes
```
<?php $x=fgets(STDIN);function f($i){return $i==0?:$i*f($i-1);}$n=1;while(f($x)<f($x-$n)**2){$n++;}echo $n;
```
[Try it online!](https://tio.run/##FcixCoMwEADQX8lwQy4iJB17BpcuXbrYP5CkOShn0EgF8dtjXd7wcsq1dn1OWcHm4yeURQ/vx/OFFFcZC0@iogbGfQ5lnUUBe2/7O7C5unVIB4h39Ev8Dfp/G3aXLQgac8MdpGnoCGOaFAjV6qw9AQ "PHP – Try It Online")
Uses the same \$x^2>((x-1)!)^2\$ method as others have used.
Uses the factorial function from the PHP submission for [this challenge](https://codegolf.stackexchange.com/a/16585/76891) (thanks to @donutdan4114)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 43 bytes
```
Min[n/.Solve[#!>(#-n)!^2, Integers]]/.n->1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zczLzpPXy84P6csNVpZ0U5DWTdPUzHOSEfBM68kNT21qDg2Vl8vT9fOUO1/QFFmXkl0mr5DtaGOkY6JjqmOoYGBjqmBQW3sfwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L!ns!@O
```
Port of [*Dennis♦*' Jelly answer](https://codegolf.stackexchange.com/a/177541/52210), so make sure to upvote him if you like this answer!
[Try it online](https://tio.run/##yy9OTMpM/f/fRzGvWNHB//9/QwMDAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVnl4gr2SwqO2SQpK9v99FPOKFR38/@v8N@Qy4jLhMuUyNDDgMjUwAAA).
**Explanation:**
```
L # List in the range [1, (implicit) input]
! # Take the factorial of each
n # Then square each
s! # Take the factorial of the input
@ # Check for each value in the list if they are larger than or equal to the
# input-faculty (1 if truthy; 0 if falsey)
O # Sum, so determine the amount of truthy checks (and output implicitly)
```
[Answer]
# Japt `-x`, 7 bytes
Port of Dennis' Jelly solution.
Only works in practice up to `n=4` as we get into scientific notation above that.
```
õÊ®²¨U²
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9cqusqhVsg==&input=NAoteA==)
```
õ :Range [1,input]
Ê :Factorial of each
® :Map
² : Square
¨ : Greater than or equal to
U² : Input squared
:Implicitly reduce by addition
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 93 bytes
```
n=>{int d(int k)=>k<2?1:k*d(k-1);int a=1,b=d(n),c=n;for(;;){a*=n;b/=n--;if(a>=b)return c-n;}}
```
[Try it online!](https://tio.run/##PUyxisMwFJuTr/Bol7hHut29OB0KN/Wg0KHDcYPjuMGkfYb3nNIj5NvTZOkgIQlJjrWL5OeBA3bi/M/J3yF3N8ssThQ7sncx5hknm4ITjxha8WMDSk60DH7/hKWO1VrJDhE53vz2QiH5Y0Avn/JTKciz6X3wPaCrAqZiQf00M5p6XKRo5cq9MnVf7fblV79pZa9LBWtsTVk0ppWoCmcQrpEkgBrtZjHNh0GtIVylrRtFPg2EwmmEaZohn@YX "C# (.NET Core) – Try It Online")
Based off of @Arnauld's javascript answer.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 68 bytes
```
n;f(x){int i=2,j=x,b=1,g=x;while(i<j)b*i>g?g*=--j:(b*=i++);n=x-j+1;}
```
[Try it online!](https://tio.run/##VY7BTsQgFEX3fMXLTEygpSaoKymdn3CnLigF@hqkpu10mkzm161gXOjq5t17cvJM5Y3ZjxhNOHcW6nnpcLzvG/KvCtjmjhw76zBaeIEwRr9H6ejGrhgXQPXAB7XxVgnu1SYvPQZLsR5YW2DjT75QVTU807ZQWJZMRrVVQynkbV9H7OBDY6TZoydvOJheT0WRj5XBlaADmgdoQDAC8Dkl1NHDXfcWDxwc1cuImVhfxTtjTBIbZptAN07wo0VQIGSKGh6fUqYX/ljgV4QcqKPIeMyO2/5lXNB@3qvLNw "C (gcc) – Try It Online")
Edit: trading bytes against mults, no doing 2\*x mults instead of x+n
Edit: moving back to int instead of long through macro. Would fail at 34 with long.
Well I have this in C. Fails at 21.
There is a possible ambiguity as to whether the good kid wants to always win or never lose... what do you think?
[Answer]
# [Python 3](https://docs.python.org/3/), 75 bytes
```
f=lambda n:n<1or f(n-1)*n
n=lambda x:x-sum(f(n)**2<f(x)for n in range(1,x))
```
[Try it online!](https://tio.run/##NYuxDoMgFEV3vuKND4IJ2HYh@iWmA7WlNalXAzbBr0ccepc7nHPWffssuJQS@q@fH09PcOjsEikwGisVBP4ku9yk38yVSKXaLnCWoZqgCRQ93i@2OktZ0kg9DVZTq@mq6abJGlPfmLs4g3QGaXSC6tY4YWNwquEB "Python 3 – Try It Online")
# 74 bytes version
```
f=lambda n:n<1or f(n-1)*n
n=lambda x:1+sum(f(n)>f(x)**.5for n in range(x))
```
but this version overflowed for 500...
] |
[Question]
[
It seems that any [Simple](https://codegolf.stackexchange.com/questions/101057/inverse-deltas-of-an-array) [Modification](https://codegolf.stackexchange.com/questions/102139/reverse-deltas-of-an-array) of deltas using a consistent function can almost always be done some other [shorter](https://codegolf.stackexchange.com/a/101058/58375) [way](https://codegolf.stackexchange.com/a/102163/58375), *Dennis*.
Thus, the only solution I can imagine to make this harder, is to introduce some sort of inconsistent function.
**Sorting.**
Your task is to take an array of integers, sort their deltas, and recompile that to give the new array of integers.
## EG.
For the input:
```
1 5 -3 2 9
```
Get the following Deltas:
```
4 -8 5 7
```
Then, sort these Deltas, Yielding:
```
-8 4 5 7
```
And reapply them, which gives:
```
1 -7 -3 2 9
```
## Input/Output
You will be given a list/array/table/tuple/stack/etc. of signed integers as input through any standard input method.
You must output the modified data once again in any acceptable form, following the above delta sorting method.
You will receive N inputs where `0 < N < 10` where each number falls within the range `-1000 < X < 1000`
## Test Cases
```
1 5 -3 2 9 -> 1 -7 -3 2 9
-5 -1 -6 5 8 -> -5 -10 -7 -3 8
-8 1 -7 1 1 -> -8 -16 -16 -8 1
8 -9 3 0 -2 -> 8 -9 -12 -14 -2
-5 -2 -5 5 0 -> -5 -10 -13 -10 0
-1 9 -1 -7 9 -> -1 -11 -17 -7 9
```
## Notes
* As stated in above, you will always receive at least 1 input, and no more than 9.
* The first and last number of your output, will **always** match that of the input.
* Only [Standard Input Output](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?noredirect=1&lq=1) is accepted
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest byte-count wins!
* Have fun!
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
1)GdShYs
```
[Try it online!](https://tio.run/nexus/matl#@2@o6Z4SnBFZ/P9/tKGCgqmCrrGCgpGCgmUsAA "MATL – TIO Nexus")
```
1) % Implicit input. Get its first entry
G % Push input again
d % Differences
S % Sort
h % Concatenate
Ys % Cumulative sum. Implicit display
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
IṢ;@Ḣ+\
```
[Try it online!](https://tio.run/nexus/jelly#@@/5cOcia4eHOxZpx/w/3P6oaY37///RhjoKpjoKusY6CkY6CpaxOgrRuiA@UFjXDCxlARaz0FEACZmDKUOQEFBE11JHAajRAMgygusEGgOigcgALAZUbwk10BxkAwA "Jelly – TIO Nexus")
### How it works
```
IṢ;@Ḣ+\ Main link. Argument: A (array)
I Increments; compute the deltas.
Ṣ Sort them.
Ḣ Head; pop and yield the first element of A.
;@ Concatenate with swapped arguments.
+\ Take the cumulative sum.
```
[Answer]
# Mathematica, 40 bytes
```
FoldList[Plus,#&@@#,Sort@Differences@#]&
```
Pure function taking a list of (anythings) as input and returning a list. `FoldList[Plus` starts with a number (in this case, `#&@@#`, the first element of the input) and repeatedly adds elements of the self-explanatory list `Sort@Differences@#`. This mimics the behavior of the built-in `Accumulate`, but the first number would need to be prepended to the list of differences by hand, which makes the byte-count higher (as far as I can tell).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
-4 thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna)
```
¬=s¥{vy+=
```
[Try it online!](https://tio.run/nexus/05ab1e#@39ojW3xoaXVZZXatv//R@sa6igoWOoogGhdcxA7FgA "05AB1E – TIO Nexus")
```
¬ # Get the head
= # Print
s¥{ # Get sorted Deltas
vy # For each
+= # Add to the previous value and print
```
[Answer]
# Python 2, 92 bytes
```
l=input();p=0;d=[]
r=l[0],
for e in l:d+=e-p,;p=e
for e in sorted(d[1:]):r+=r[-1]+e,
print r
```
[Answer]
# Haskell, 59 Bytes
```
import Data.List
f l@(a:b)=scanl1(+)$a:(sort$zipWith(-)b l)
```
Breakdown:
```
f l@(a:b) = --we create a function f that takes as input a list l with head a and tail b
zipWith(-)b l --we make a new list with the deltas
sort$ --sort it
a: --prepend a to the list
scanl1(+)$ --create a new list starting with a and adding the deltas to it cumulatively
```
[Answer]
## JavaScript (ES6), 68 bytes
```
([p,...a])=>[s=p,...a.map(e=>p-(p=e)).sort((a,b)=>b-a).map(e=>s-=e)]
```
In JavaScript it turns out to be golfier to compute the [Inverse Deltas of an Array](https://codegolf.stackexchange.com/questions/101057/inverse-deltas-of-an-array). These are then sorted in descending order and cumulatively subtracted from the first element.
[Answer]
# [Python 2](https://docs.python.org/2/),
# 90 bytes
```
x=input()
print[sum(sorted(map(int.__sub__,x[1:],x[:-1]))[:i])+x[0]for i in range(len(x))]
```
# 84 bytes
Saved 6 bytes on using lambda. Thanks to ovs!
```
lambda x:[sum(sorted(map(int.__sub__,x[1:],x[:-1]))[:i])+x[0]for i in range(len(x))]
```
[Try it online!](https://tio.run/nexus/python2#FYtBCsMgEAC/ssddqiWeSoW@ZLuIIbYIaoIm4O@tvczMZdLrPZLP6@ahW25XxrbXM2yY/YGxnHfn2rU6pzobK5NWGyFiG4VunRf57BUixALVl2/AFAp2IhlHnTckZG0UPBX8pR8zhcYP "Python 2 – TIO Nexus")
Breaking down the code,
```
>>> x
[1, 5, -3, 2, 9]
>>> map(int.__sub__,x[1:],x[:-1]) #delta
[4, -8, 5, 7]
>>> sorted(map(int.__sub__,x[1:],x[:-1])) #sorted result
[-8, 4, 5, 7]
>>> [sorted(map(int.__sub__,x[1:],x[:-1]))[:i]for i in range(len(x))]
[[], [-8], [-8, 4], [-8, 4, 5], [-8, 4, 5, 7]]
>>> [sum(sorted(map(int.__sub__,x[1:],x[:-1]))[:i])+x[0]for i in range(len(x))]
[1, -7, -3, 2, 9]
```
Happy Coding!
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
∫:←¹OẊ-
```
[Try it online!](https://tio.run/##yygtzv7//1HHaqtHbRMO7fR/uKtL9////9GGOqY6usY6RjqWsQA "Husk – Try It Online")
[Answer]
# JavaScript (ES6), 93 bytes
```
(p,M=[p[0]])=>p.map((a,b)=>p[b+1]-a).sort((a,b)=>a-b).map((a,b)=>M=[...M,M[b]+a])[p.length-2]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 97 bytes
```
p=input()
d=[p[i+1]-p[i] for i in range(len(p)-1)]
o=p[:1]
for n in sorted(d):o+=o[-1]+n,
print o
```
[Try it online!](https://tio.run/nexus/python2#FcoxCkMhDADQ3VNkVIyDLR36wZOEDAVtCZQkWHt@2z@95W1vov5dMYXeyEly5fKH4WkTBERhPvQ14nto9FRq4mDN6agczqHn@Nhco8eeDsvNqFTOisGn6ALbmyresFzxgnf@AQ "Python 2 – TIO Nexus")
[Answer]
# Pyth, 11 bytes
```
.u+NYS.+QhQ
```
This just does the obvious thing described in the statement.
[Try It Online](http://pyth.herokuapp.com/?code=.u%2BNYS.%2BQhQ&input=%5B1%2C+5%2C-3%2C+2%2C+9%5D&debug=0)
```
.+Q Take the deltas of the input
S sort it
.u Cumulative reduce
+NY using addition
hQ starting with the first element of the input
```
Suggestions for further golfing welcome.
[Answer]
# [Julia 0.5](http://julialang.org/), 30 bytes
```
!x=[x[];x|>diff|>sort]|>cumsum
```
[Try it online!](https://tio.run/nexus/julia5#PY3BCoMwEETP9SvGWwsbUEuroTQ/EjzVBgI1SlTIIf@ebkIpLMzu253ZVIenDnp8hKgma0xU2@L3MarXMW/HnMziEWAdzrol3AjiSugIciRokWfG4l5WQ2EDIaO@SJsREyEJbGy46/5OjsnK1RTG9/IX2OcPl@pUB0SF1Vu3f1z1dlP6Ag "Julia 0.5 – TIO Nexus")
[Answer]
# PHP, 89 bytes
```
for($a=$argv;n|$i=$a[++$x+1];)$d[]=$i-$a[$x];for(sort($d);$x-$y++;)echo$a[1]+=$d[$y-2],_;
```
Run like this:
```
php -nr 'for($a=$argv;n|$i=$a[++$x+1];)$d[]=$i-$a[$x];for(sort($d);$x-$y++;)echo$a[1]+=$d[$y-2],",";' 1 5 -3 2 9;echo
> 1_-7_-3_2_9_
```
# Explanation
```
for(
$a=$argv; # Set input to $a.
n | $i=$a[++$x+1]; # Iterate over input.
)
$d[] = $i-$a[$x]; # Add an item to array $d, with the difference between
the current and previous item.
for(
sort($d); # Sort the delta array.
$x-$y++; # Loop as many times as the previous loop.
)
echo
$a[1]+=$d[$y-2], # Print the first input item with the delta applied
# cumulatively. First iteration takes $d[-1], which
# is unset, so results in 0.
_; # Print underscore as separator.
```
[Answer]
# Python 2 with numpy, ~~67~~ 56 bytes
```
from numpy import*
lambda l:cumsum(l[:1]+sorted(diff(l)))
```
Let numpy compute the deltas, sort them, prepend the first element, and let numpy compute the cumulative sums. Pretty cheap?
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 17 bytes
```
@ZL:&v+;Fg@Lt:K-#
```
[Try it online!](https://tio.run/##Kygtzqj8/98hysdKrUzb2i3dwafEyltX@f///9FGOgqGOgq6QErXMBYA "Pushy – Try It Online")
```
@ZL:&v+;F \ Calculate cumulative sum
g \ Sort
@Lt:K-# \ Calculate and print deltas
```
[Answer]
# [Perl 6](https://perl6.org), 31 bytes
```
{[\+] @_[0],|sort @_[1..*]Z-@_}
```
[Try it](https://tio.run/nexus/perl6#jVFrToNAEP6/p5iodaG4tIB92ZZyAE9gaRoCWyUWqGVpbZATeQsvVmcXqP4xETLZmflePIqcw2FohlOSnOA2zCIO83O59I0VeOtlf3X3kWd7IXvLNLurJ@atqzNSPcFzAXPYxinPNd1Mgt0DlAQg6YE3i9NdIVyENcrowo8M3YAOUKBIwMvPu0CZS2VTb7wZf9/xUPDoD1VvKr0xV1kjx/j6bHMayG8tWvRiaT7GuZCsXASCw02YFang@ylphHueF1tpKt9fqyP0RoSUa4jiCI4cnrmA40sgZN@aL5AQb6Cx4G@HC6I@B2YGJ7jKXqE0jDa4QsuyVpibRGi040RUr66QXwHf4i/5JU0zAf@Xk@pswQCYAzZM0IK5YAEbNQvCEMJ5iJSxxNTcbwhjwsY128JbwUiyhnUhRHCcgAMosBWuZmbZWPe4U/a2NB1Izo@95aizTzB8op5gJE9XtZaskVp9Aw "Perl 6 – TIO Nexus")
## Expanded:
```
{
[\+] # triangle produce values using &infix<+>
@_[0], # starting with the first argument
| # slip the following into this list
sort # sort the following
# generate the list of deltas
@_[1..*] # the arguments starting with the second one
Z[-] # zipped using &infix:<->
@_ # the arguments
}
```
[Answer]
## Batch, 197 bytes
```
@set n=%1
@set s=
:l
@set/ad=5000+%2-%1
@set s=%s% %d%
@shift
@if not "%2"=="" goto l
@echo %n%
@for /f %%a in ('"(for %%b in (%s%)do @echo %%b)|sort"') do @set/an+=%%a-5000&call echo %%n%%
```
`sort` doesn't sort numerically, so I bias all the differences by 5000.
[Answer]
## bash + sort, 102 bytes
```
echo $1
n=$1
shift
for e in $*
do
echo $((e-n))
n=$e
done|sort -n|while read e
do
echo $((n+=e))
done
```
## sh + sort + expr, 106 bytes
```
echo $1
n=$1
shift
for e in $*
do
expr $e - $n
n=$e
done|sort -n|while read e
do
n="$n + $e"
expr $n
done
```
[Answer]
## Clojure, 46 bytes
```
#(reductions +(first %)(sort(map -(rest %)%)))
```
One day I'm going to make Cljr language which has shorter function names than Clojure.
] |
[Question]
[
**Task**
* The user inputs a sentence - words only. Any input other than letters or spaces, including integers and punctuation, should throw an exception: "Sentence must only use letters".
* The output has a pattern, where some
words are reversed and others words are normal.
* The pattern starts as
a normal word, the next two words are reversed, then the next two
words are normal and the pattern continues.
* An example of where the words should be normal and where words reversed is below:
Normal - Reversed - Reversed - Normal - Normal - Reversed - Reversed - Normal ...
**Input Example**
She sells Sea shells on the Sea shore
**Output Example**
She slles aeS shells on eht aeS shore
**Additional Rules**
* If capital letters are used, they should remain on the letter they were originally posted on.
* Any multiple spaces initially posted on input should be reduced to one space. For example `Programming Puzzles and Code Golf` becomes `Programming selzzuP dna Code Golf`
Shortest Code Wins!!
Happy coding...
[Answer]
# [TeaScript](https://github.com/vihanb/TeaScript), 55 bytes ~~58 60 69 76 78 80 87 89~~
```
xO`a-z `?xl(#~-i&2?l:lv(),/ +/):Ld`SÀZn Û § «e Ò5s`
```
This is *extremely* short, I'm very happy with it.
The last ~20 characters may seem like gibberish but that's "Sentence must only use letters" encoded. All the characters have char codes below 256 so each are one byte
### Explanation
```
xO`a-z `? // If input contains only a-z and space...
xl(# // Loop through input
~-i&2? // If (index - 1 "unary and"ed with 2) isn't 0...
:l, // Leave alone
lv() // Otherwise, reverse string
/ +/ // Loops on spaces
)
:Ld`SÀZn Û § «e Ò5s` // Otherwise... decompress and print the error string
```
* [Try it online](http://vihanserver.tk/p/TeaScript/?code=xO%60a-z%20%60%3Fxl(%23~-i%262%3Fl%3Alv()%2C%2F%20%2B%2F)%3A'Sentence%20must%20only%20use%20letters'&input=Programming%20%20Puzzles%20%20Code%20Golf)
* [Pastebin](http://pastebin.com/2JEfBWiY)
[Answer]
## Haskell, 141 bytes
```
r=reverse
f x|all(`elem`(' ':['a'..'z']++['A'..'Z']))x=unwords$zipWith($)(cycle[id,r,r,id])$words x|1<2=error"Sentence must only use letters"
```
Almost 2/3 of the code is for error checking. Seems to be the first real world challenge.
The work is done by `unwords$zipWith($)(cycle[id,reverse,reverse,id])$words x` which splits the input into a list of words, zips it with the cycling list of functions `[id,reverse,reverse,id,id,reverse...]` and joins the result with spaces back to a single string.
Thanks to @Christian Irwan for 2 bytes.
[Answer]
# JavaScript (ES6) 122
```
f=s=>/[^a-z ]/i.test(s)?"Sentence must only use letters":s.split(/ +/).map((w,i)=>~-i&2?w:[...w].reverse().join``).join` `
alert(f(prompt('?','She sells Sea shells on the Sea shore')))
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 103 bytes
```
\s+
(?<=^\S+ (\S+ )?((\S+ ){4})*)
;
+`(;\S*)(\S)
$2$1
;
i`.*[^a-z ].*
Sentence must only use letters
```
There should be a single space on the second line, which SE seems to be swallowing. Run the code from a single file with the `-s` flag.
Retina has no concept of exceptions so the output is simply replaced by `Sentence must only use letters` if there are non-letter non-whitespace characters in the input.
[Answer]
# Pyth, 61 bytes
```
?.A}R+G\ rz0jd.e_W%%k4 3bfTczd"Sentence must only use letters
```
[Try it online.](https://pyth.herokuapp.com/?code=%3F.A%7DR%2BG%5C%20rz0jd.e_W%25%25k4%203bfTczd%22Sentence%20must%20only%20use%20letters&input=She+sells+Sea+shells+on+the+Sea+shore)
[Answer]
# Python, ~~163~~ ~~160~~ ~~157~~ 145
```
k=raw_input()
k=["Sentence tsum ylno use letters",k][k.replace(' ','').isalpha()]
for i,x in enumerate(k.split()):print x[::-1if(i+1)/2%2else 1],
```
Removed 15 characters, thanks [Mego](https://codegolf.stackexchange.com/users/45941/mego)!!
[Answer]
# Bash + coreutils, 108
```
[ ${@//[a-zA-Z]/} ]&&echo Sentence must only use letters||for t;{
((++i/2%2))&&rev<<<$t||echo $t
}|tr \\n \
```
The last character of this program is a space.
Input is taken from the command line:
```
$ ./norrevvevnor.sh Programming Puzzles and Code$'\n' Golf
Programming selzzuP dna Code Golf $
$ ./norrevvevnor.sh Programming Puzzles and Code$'\n' Golf1
Sentence must only use letters
$
```
[Answer]
# Pyth, 72
```
=zflTc?:z"[^A-Za-z ]"0"Sentence tsum ylno use letters"zdjd.e?%/hk2 2_bbz
```
Doesn't beat the other Pyth answer, but I already invested time into writing it. It's basically a translation of my [Python answer](https://codegolf.stackexchange.com/a/62324/34787).
[Try it online](https://pyth.herokuapp.com/?code=%3DzflTc%3F%3Az%22%5B%5EA-Za-z+%5D%220%22Sentence+tsum+ylno+use+letters%22zdjd.e%3F%25%2Fhk2+2_bbz&input=She+sells+sea+shells+by+the+sea+shore&test_suite=1&test_suite_input=She+sells+sea+shells+by+the+sea+shore&debug=0)
[Answer]
# Julia, 109 bytes
```
s->(i=0;join([isalpha(w)?(i+=1)%4>1?reverse(w):w:error("Sentence must only use letters")for w=split(s)]," "))
```
`i=0` and `(i+=1)%4>1` are used to decide whether each word gets `reverse`d or not. `isalpha` applies to the words after being split using `split(s)` to determine whether or not there are characters that aren't letters (spaces have already been removed by this point). `join` restores the string after the manipulation, unless the `error` is thrown.
[Answer]
# Julia, ~~150~~ 134 bytes
```
s->ismatch(r"[^a-z ]"i,s)?error("Sentence must only use letters"):(i=3;join([(i+=1;isodd((i+1)i÷2)?reverse(w):w)for w=split(s)]," "))
```
Ungolfed:
```
function f(s::AbstractString)
if ismatch(r"[^a-z ]"i, s)
error("Sentence must only use letters")
else
i = 3
a = [(i += 3; isodd((i + 1)i ÷ 2) ? reverse(w) : w) for w = split(s)]
return join(a, " ")
end
end
```
Saved 16 bytes thanks to Glen O!
[Answer]
# Pyth, 55 bytes
```
?--rz0Gd"Sentence must only use letters"jd.e_W%%k4 3bcz
```
Borrowed the `%%k4 3` bit from Pietu1998. Saved one additional byte.
Try it online: [Demonstration](http://pyth.herokuapp.com/?test_suite_input=She%20sells%20Sea%20shells%20on%20the%20Sea%20shore%0AProgramming%20%20%20Puzzles%20and%20%20%20Code%20Golf%0AI%27m%20here%20to%20help&input=She%20sells%20Sea%20shells%20on%20the%20Sea%20shore&test_suite=0&code=%3F--rz0Gd%22Sentence%20must%20only%20use%20letters%22jd.e_W%25%25k4%203bcz) or [Test Suite](http://pyth.herokuapp.com/?test_suite_input=She%20sells%20Sea%20shells%20on%20the%20Sea%20shore%0AProgramming%20%20%20Puzzles%20and%20%20%20Code%20Golf%0AI%27m%20here%20to%20help&input=She%20sells%20Sea%20shells%20on%20the%20Sea%20shore&test_suite=1&code=%3F--rz0Gd%22Sentence%20must%20only%20use%20letters%22jd.e_W%25%25k4%203bcz)
### Explanation
```
?--rz0Gd"..."jd.e_W%%k4 3bcz implicit: z = input string
rz0 convert z to lower-case
- G remove all letters
- d remove all spaces
? if there is some chars left than
"..." print the string "Sentence must only ..."
else:
cz split z by spaces or multiple spaces
.e map each pair (k index, b string) of ^ to:
_ b b or reversed of b, depending on
W%%k4 3 (k mod 4) mod 3
jd join the result by spaces
```
[Answer]
# [Perl 5](https://www.perl.org/) `-ap`, 80 bytes
```
map$_=++$i%4>1?reverse:$_,@F;$_=/[^a-z ]/i?"Sentence must use only letters":"@F"
```
[Try it online!](https://tio.run/##JYtBC4IwHEe/yp9hJzMV8mKYnrx12jFKRvxAYW5j/xnUh2@Nuj3e4zl43cS4KpdNXZ5ny@54rnuPJzyjzab9MJ5SKa93VbzpVi69kDAB5gFaNw60Mcga/SKNENIkWjGMIkY5gxhaM0ko4vmH1lBI/m@sx8e6sFjDsbg0h6quYqHcFw "Perl 5 – Try It Online")
[Answer]
# Java, 215 bytes
Regex is fun
```
s->{if(s.split("[^a-zA-Z ]").length>1)throw new Error("Sentence must only contains letters");else{int i=1;for(String a:s.split(" "))System.out.print((i++%2<1?new StringBuffer(a).reverse():a)+(a.isEmpty()?"":" "));}}
```
[Try it online!](https://tio.run/##TZBBawIxEIXv/ophoZBgd8Ee3aq0oLee9laxkG4nbmw2WTKzWiv@djvVpTSXwGTe@97LzuxNvvv4vNTeEMGLceE0coExWVMjrE776D7AqoqTC1sgzU2KB4JlSjGV51HXv3tXA7Fhua7LrXgM@@uNSVvS8F90v/yqsWMXBbQCC7ML5fOTs4oK6rxjla3fTP79lL/CJtOFx7DlZj65gSHg4WajsgolZpCQbU8MMfgj1DGw0Ak8slSgTJfoCU9SCNxsUlrRDU3M9I8HmdbVkRjbIvZcdPLOSrnx@O7hcbL4Jd40z721mJTRRcK9uKPSU6PHyhSOlm3HR6UXWTa9@pXn86W0hZWYDQKh9wTDqdAANddJDPI1OExiQsk7EuEP)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 39 bytes
```
³Ḳ¹ƇUJ2&TƲ¦K
“*[,ṛDṾȧƤ°Ġṛ©¦»
ØẠ” ṭ³eƇ⁼£
```
[Try it online!](https://tio.run/##AYoAdf9qZWxsef//wrPhuLLCucaHVUoyJlTGssKmSwrigJwqWyzhuZtE4bm@yKfGpMKwxKDhuZvCqcKmwrsKw5jhuqDigJ0g4bmtwrNlxofigbzCo////1RoaXMgaXMgYSB0ZXN0IG9mIHRoZSBhdXRvbWF0aWMgdm9pY2UgbWVzc2FnaW5nIHN5c3RlbS4 "Jelly – Try It Online")
Thanks to Erik the Outgolfer. He saved me from a few extra bytes and from many hours of frustration.
### Here's a 46 byte solution
It actually throws a python syntax error when the input contains invalid characters.
```
³Ḳ¹ƇUJ2&TƲ¦K
“çỤḷṁŀDṀẠṠGmḟĖƲƑ⁽Ḳḟ»ŒV
ØẠ” ṭ³eƇ⁼£
```
[Try it online!](https://tio.run/##AY0Acv9qZWxsef//wrPhuLLCucaHVUoyJlTGssKmSwrigJzDp@G7pOG4t@G5gcWAROG5gOG6oOG5oEdt4bifxJbGssaR4oG94biy4bifwrvFklYKw5jhuqDigJ0g4bmtwrNlxofigbzCo////1Byb2dyYW1taW5nICAgUHV6emxlcyBhbmQgICBDb2RlIEdvbGY "Jelly – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), 41 bytes
```
¸¬è\L ?`SÀZn Û § «e Ò5s`:UeS²S ¸ËzEc2
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVM&code=uKzoXEwgP2BTwFpurSDbGSCNpyCrZSDSNYBzYDpVZVOyUyC4y3pFYzI&input=IlByb2dyYW1taW5nICAgUHV6emxlcyBhbmQgICBDb2RlIEdvbGYi)
```
¸¬è\L ?`...`:UeS²S ¸ËzEc2 :Implicit input of string U
¸ :Split on spaces
¬ :Join
è :Count occurrences of
\L :RegEx /[^A-Z]/gi
?`...`: :If truthy return the compressed string "Sentence must only use letters", else
Ue :Recursively replace in U
S²S : Two spaces with one
¸ :Split on spaces
Ë :Map each element at 0-based index E
z : Rotate clockwise by 90 degrees multiplied by
Ec2 : E rounded up to the nearest multiple of 2
:Implicit output, joined with spaces
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ðKDáÊi“¸–ƒ—€É€Å™ê“.ªFë#áεN4%>2÷iR]ðý
```
[Try it online.](https://tio.run/##yy9OTMpM/f//8AZvl8MLD3dlPmqYc2jHo4bJxyY9apjyqGnN4U4Q0fqoZdHhVUA5vUOr3A6vVj688NxWPxNVO6PD2zODYg9vOLz3//@Aovz0osTc3My8dAUFhYDSqqqc1GKFxLwUIM85PyVVwT0/Jw3IhgopBGekKhSn5uQUKwSnJioUZ4CZ@XkKJUBxiEh@USoA)
Throws the following error when the input does not only contain `[A-Za-z ]`:
>
> (RuntimeError) Could not convert Sentence must only use letters to integer.
>
>
>
**Explanation:**
```
ðK # Remove all spaces from the (implicit) input-string
Dá # Create a copy, and remove everything except for letters from this copy
Êi # If the copy with letters removed and the original are NOT equal:
“¸–ƒ—€É€Å™ê“ # Push dictionary string "sentence must only use letters"
.ª # With sentence capitalization
F # And try to loop that many times, causing the error above
ë # Else:
# # Split the (implicit) input-string on spaces
á # Only keep letters (which will remove empty items caused by multiple
# adjacent spaces in the input, which is shorter than `õK`)
ε # Map each word to:
N4%>2÷ # Calculate ((index modulo-4) + 1) integer-divided by 2
# (results in 0,1,1,2,0,1,1,2,0,1 for indices 0,1,2,3,4,5,6,7,8,9)
i # If this is exactly 1:
R # Reverse the current word
] # Close the if-statement, map, and if-else statement
ðý # Join the modified word-list by spaces
# (and then output it implicitly as result)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“¸–ƒ—€É€Å™ê“` is `"sentence must only use letters"`.
[Answer]
# [PHP](https://php.net/), 147 bytes
```
foreach(explode(' ',$argn)as$a){if(!ctype_alpha($a))throw new Exception('Sentence must only use letters');$o.=(++$i%4>1?strrev($a):$a).' ';}echo$o;
```
[Try it online!](https://tio.run/##jY9BawIxEIXP7q8YJSVZXJSWntxaLxVaKK2wvZUiIR2NkG5CMlYX2d@@jbpbPHoIDG9e3rzPadc8zJx2wKRflzCF1RopiOLj6eUtzZOEEQYKUf9MerzQCAGNCVCghKBPoy2Bon5WrEee9cZjOFmNwQASiwsramqVaL028o5n11r7PPmKtVdxlEoLaPvL0AKmcEgAUGl7FjIYTAYZLJ4Xy/n7ax535Cs4NF0A7p2x3yg48Oz0IZWByfSwWYm@osrhUhqnpYhaStrbHZS4g/leoaONLQUvsCQsFcLPNlCsayrYBgSDROgDT3NmR1MxHLLNzf3j7SyQ9/h7jJvEN4pn8/rYltm8AahBSVIaxP8BYHhG6qDwyFB3jC3XBWDd/AE "PHP – Try It Online")
Or if `die()` is acceptable as an "Exception":
# [PHP](https://php.net/), 131 bytes
```
foreach(explode(' ',$argn)as$a){if(!ctype_alpha($a))die('Sentence must only use letters');$o.=(++$i%4>1?strrev($a):$a).' ';}echo$o;
```
[Try it online!](https://tio.run/##jY/BagIxEEDP5itGSUmCi9LSk1vrpYUWSitsb6VIWGfNQroJmVgq4rdv47qCRw@B4fEmefHGtw8LbzxwHTYNzKHaYCRZfD69vqucMR6RIiX@xQaiMAiE1hIUqIFMN7oGYuIn4gKKbDCdQqdaiwQaiwsVTexJUq@98k5k16pDwb5TdpVGXRoJfb@m/oMK9gwAS@NOIIPRbJTB8mW5ev54y1l73sQ/b90apQCRdabSxLXa15UclnHncaWtN1omptZ18gpsIjYlws@WYuqyO9gSgsUYMZBQOXeTuRyPeX1z/3i7oBgC/h7XZ@lM0jP54ZjFXd6eC/uqi7xD@w8 "PHP – Try It Online")
] |
[Question]
[
You have a swimming pool that is filled to the brim with water. You need to empty it, but you can't think of an efficient method. So you decide to use your red solo cup. You will repeatedly fill the cup all the way and dump it outside the pool.
## Challenge
How long will it take to empty the pool?
### Input
`[shape of pool] [dimensions] [shape of cup] [dimensions] [speed]`
* `shape of pool` will be one of these strings: `circle`, `triangle`, or `rectangle`. Note that these actually refer to the 3-dimensional shapes: cylinder, triangular prism, and rectangular prism.
* `dimensions` will be different depending on the shape.
+ circle: `[radius] [height]`. Volume = π r2 h
+ triangle: `[base] [height] [length]`. Volume = 1/2(bh) \* length
+ rectangle: `[width] [length] [height]` Volume = lwh
* `shape of cup` and `dimensions` work the same way. The cup can also be either a circle, triangle, or rectangle.
* `speed` is the amount of time it takes to empty one cup full of water **in seconds**.
### Output
The number of **seconds** it takes to empty the swimming pool. This can be rounded to the nearest second.
### Notes
* There will be no units in the input. All distance units are assumed to be the same (a shape won't have a height in inches and a width in feet).
* Use 3.14 for `pi`.
* Input will be made up of strings and floating-point numbers.
* It will never rain. No water will ever be added.
* You have a *very* steady hand. You will fill the cup exactly to the brim every time, and you will never spill any.
* Once you get near the end, it will get hard to scoop up a full cup of water. You do not need to worry about this. You're very strong, so you can tilt the pool onto its side (without using up any more time).
* Anytime you make a calculation, it's okay to **round to the nearest hundredth**. Your final answer will not need to be exact.
### Test Cases
Input: `triangle 10 12.25 3 circle 5 2.2 5`
Output: `10`
Even though there is less than 172.7 left on the last scoop, it still takes the whole five seconds to empty it.
Input: `triangle 5 87.3 20001 rectangle 5.14 2 105.623 0.2`
Output: `804.2`
* You should round to the nearest hundredth after each calculation.
* The **final calculation is rounded up** from 804.05567 to 804.2. This is because that last little bit of water must be emptied.
### Rules
* You can write a full program or function.
* Input should be taken from stdin or function parameters. Output should be printed through stdout or returned.
* The input format can be rearranged, as long as you specify that in the submission. You can also shorten the strings "circle", "triangle", and "rectangle."
* Libraries and built-in functions that involve volume or area are not allowed.
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Submission with least number of bytes wins.
[Answer]
# JavaScript ES6, ~~100~~ ~~78~~ ~~82~~ ~~81~~ 74 bytes
*Thanks to @UndefinedFunction for helping golf off 4 bytes*
```
(a,z,d,f=([a,g,k,p])=>g*k*(a[6]?p/-~!a[8]:3.14*g))=>Math.ceil(f(a)/f(z))*d
```
Usage:
```
t(["triangle",10,12.25,3],["circle",5,2.2],5);
```
[Answer]
# CJam, 46 bytes
```
{rc:Xr~r~@'c={\_**3.14*}{r~**X't=)/}?}2*/m]r~*
```
Explanation:
```
{ }2* e# Repeat two times:
rc:X e# Read a token, take first char, assign to X
r~r~ e# Read and eval two tokens
@'c={ } ? e# If the char was 'c':
\_* e# Square the first token (radius)
* e# Multiply by the second one (height)
3.14* e# Multiply by 3.14
{ } e# Else:
r~ e# Read and eval a token
** e# Multiply the three together
X't=)/ e# Divide by 2 if X == 't'
e# Now the two volumes are on the stack
/m] e# ceil(pool_volume / cup_volume)
r~* e# Read and evaluate token (time) and multiply
```
[Try it online](http://cjam.aditsu.net/#code=%7Brc%3AXr~r~%40'c%3D%7B%5C_**3.14*%7D%7Br~**X't%3D)%2F%7D%3F%7D2*%2Fm%5Dr~*&input=triangle%205%2087.3%2020001%20rectangle%205.14%202%20105.623%200.2).
[Answer]
# Python 3, ~~340~~ 304 bytes
```
def l(Y,Z):r=Z[1]*3.14*(Z[0]**2)if Y[0]in'c'else Z[0]*Z[1]*Z[2];return r/2 if Y[0]is't'else r
def q(i):import re,math;M,L,F,C=map,list,float,math.ceil;p,d,c,g,s=re.match("(\w)\s([\d .]+)\s(\w)\s([\d .]+)\s([\d.]+)",i).groups();k=lambda j:L(M(F,j.split(' ')));d,g=k(d),k(g);return C(C(l(p,d)/l(c,g))*F(s))
```
**Usage:**
```
q(i)
```
Where `i` is the string of information.
**Examples:**
* `q("t 10 12.25 3 c 5 2.2 5")`
* `q("t 5 87.3 20001 r 5.14 2 105.623 0.2")`
**Note:** The names of the shapes have been shortened to their first letters, respectively.
[Answer]
# Javascript (ES6), 91
Taking input as strings for the shapes, arrays of numbers for the dimensions, and a single number for the speed:
```
(a,b,c,d,e)=>(1+(v=(y,x)=>x[0]*x[1]*(y[6]?x[2]/(y[8]?1:2):x[0]*3.14))(a,b)/v(c,d)-1e-9|0)*e
```
This defines an anonymous function, so to use add `g=` before it. Then, it can be called like `alert(g("triangle", [10, 12.25, 3], "circle", [5, 2.2], 5))`
**Explanation:**
```
(a,b,c,d,e)=> //define function
//a = pool shape, b = pool dimensions
//c = cup shape, d = cup dimensions
//e = speed
( 1+ //part of the rounding up below
(v=(y,x)=> //define volume function
x[0] * x[1] * //multiply first 2 values of dimension by:
(y[6] ?
x[2] / //if rectangle or triangle, the 3rd dimension
(y[8] ? 1 : 2) //but if triangle divide by 2
:
x[0] * 3.14 //or if circle the radius * pi
) //(implicit return)
)(a,b) / v(c,d) //call the volume function for the pool/cup, and divide
-1e-9 |0 //but round up the result
) * e //and multiply by e
//(implicit return)
```
My original solution took a single string, and was **111 bytes long:**
```
s=>(1+(v=x=>s[i++]*s[i++]*(s[x][6]?s[i++]/(s[x][8]?1:2):s[i-2]*3.14))((i=1)-1,s=s.split` `)/v(i++)-1e-9|0)*s[i]
```
This also defines an anonymous function, so to use add `f=` before it.
Then, it can be called like `alert(f("triangle 5 87.3 20001 rectangle 5.14 2 105.623 0.2"))`
[Answer]
# K5 (oK), 123 bytes
```
v:{((({y*3.14*x*x};{z*(x*y)%2};{x*y*z})@"ctr"?s)..:'t#1_x;(1+t:2+~"c"=s:**x)_x)};f:{{(.**|r)*_(~w=_w)+w:x%*r:v y}.v[" "\x]}
```
[Answer]
# Julia, ~~122~~ ~~116~~ ~~95~~ ~~89~~ 79 bytes
```
f(p,P,c,C,s)=(V(a,x)=prod(x)*(a<'d'?3.14x[1]:a>'s'?.5:1);ceil(V(p,P)/V(c,C))*s)
```
This assumes that only the first letter of the shape names will be given. Otherwise the solution is 6 bytes longer.
Ungolfed + explanation:
```
function f(p::Char, P::Array, c::Char, C::Array, s)
# p - Pool shape (first character only)
# P - Pool dimensions
# c - Cup shape (first character only)
# C - Cup dimensions
# s - Speed
# Define a function to compute volume
function V(a::Char, x::Array)
prod(x) * (a < 'd' ? 3.14x[1] : a > 's' ? 0.5 : 1)
end
# Return the ceiling of the number of cups in the pool
# times the number of seconds per cup
ceil(V(p, P) / V(c, C)) * s
end
```
Saved 21 bytes thanks to edc65 and 10 thanks to UndefinedFunction!
[Answer]
# F#, 217 186 184 160 bytes
Damn indentation requirements!
```
let e(p,P,c,C,s)=
let V(s:string)d=
match(s.[0],d)with
|('c',[x;y])->3.14*x*x*y
|('t',[x;y;z])->((x*y)/2.)*z
|('r',[x;y;z])->x*y*z
ceil(V p P/V c C)*s
```
**Usage:**
```
e("triangle",[5.;87.3;20001.],"rectangle",[5.14;2.;105.623],0.2);;
```
**Update**
Thanks to Alex for remarking on single space indentation, which F# seems to support
Managed to knock a load more off by changing from `array` to `list` types in the `match` statement
[Answer]
## Python 2.7 306 Bytes
```
import math as z,re
t,m,r,w=float,map,reduce,[e.split() for e in re.split(' (?=[a-z])| (?=\d+(?:\.\d+)?$)',raw_input())]
def f(S,D):i=r(lambda x,y:x*y,D);return((i,i*.5)[S[0]=='t'],3.14*i*D[0])[S[0]=="c"]
print z.ceil(r(lambda x,y:x/y,m(lambda q:f(q[0],q[1:]),m(lambda x:[x[0]]+m(t,x[1:]),w[:-1]))))*t(*w[-1])
```
Takes input from stdin.
Testing it-
```
$ python pool.py
triangle 10 12.25 3 circle 5 2.2 5
10.0
$ python pool.py
triangle 5 87.3 20001 rectangle 5.14 2 105.623 0.2
804.2
```
[Answer]
# Python 2, ~~222~~ ~~146~~ ~~139~~ ~~119~~ ~~103~~ 93 bytes
Fairly straightforward implementation. Thanks to Sp3000 for the `-(-n//1)` trick for ceiling, which *should* work in all cases (i.e. haven't found an issue with it yet).
```
u=lambda q,k,l,m=1:k*l*[3.14*k,m][q>'c']*-~(q<'t')/2.
f=lambda a,b,c,d,s:-u(a,*c)//u(b,*d)*-s
```
Input should be formatted like so:
```
f(shape1, shape2, dimensions1, dimensions2, speed)
"Where shape1 and shape2 are one of 'c','r','t', dimensions1 is a list of the dimensions
of the first shape, dimensions 2 is a list of the dimensions for the second shape, and
speed is the speed of emptying in seconds."
```
Usage:
```
>>> f('t', 'r', [5, 87.3, 20001], [5.14, 2, 105.623], 0.2)
804.2
>>> f('t', 'c', [10, 12.25, 3], [5, 2.2], 5)
10.0
```
Ungolfed:
```
import math
def volume(shape, dimensions):
out = dimensions[0] * dimensions[1]
if shape == 'c':
out *= 3.14 * dimensions[0]
else:
out *= dimensions[2]
if shape == 't':
out /= 2.0
return out
def do(shape1, shape2, dimensions1, dimensions2, speed):
volume1 = volume(shape1, dimensions1)
volume2 = volume(shape2, dimensions2)
return math.ceil(volume1 / volume2) * speed
```
---
## Original solution, 222 bytes
This was made when the rules still needed you to input the whole word rather than a letter. I used the fact that `hash(s)%5` mapped them to `circle -> 2, triangle -> 3, rectangle -> 1`, however if I just take one letter as input, I think I can get this shorter.
```
from math import*
u=lambda p,q:[[p[0]*p[1]*p[-1],3.14*p[0]**2*p[1]][1<q<3],0.5*p[0]*p[1]*p[-1]][q>2]
def f(*l):k=hash(l[0])%5;d=4-(1<k<3);v=l[1:d];r=hash(l[d])%5;g=4-(1<r<3);h=l[1+d:d+g];s=l[-1];print ceil(u(v,k)/u(h,r))*s
```
Usage:
```
>>> f('triangle',10,12.25,3,'circle',5,2.2,5)
10.0
>>> f('triangle',5,87.3,20001,'rectangle',5.14,2,105.623,0.2)
804.2
```
[Answer]
# Python 2/3, ~~252~~ 249 bytes
```
import re,math;i=[float(x)if re.match('[\d.]+',x)else x for x in re.sys.stdin.readline().split()]
for o in[0,[4,3][i[0]<'d']]:
w=i[o+1]*i[o+2]*i[o+3]
if i[o]<'d':w*=3.14*i[o+1]/i[o+3]
if i[o]>'s':w*=.5
a=a/w if o else w
print(math.ceil(a)*i[-1])
```
**Usage Examples:**
```
$ echo 'triangle 10 12.25 3 circle 5 2.2 5' | python stack_codegolf_54454.py
10.0
$ echo 'triangle 5 87.3 20001 rectangle 5.14 2 105.623 0.2' | python stack_codegolf_54454.py
804.2
```
The Python 2 only and Python 3 only versions are only different in how they receive input; `raw_input()` for Python 2 and `input()` for Python 3, as opposed to `re.sys.stdin.readline()` for the Python2/3 version.
# Python 2, ~~240~~ 237 bytes
```
import re,math;i=[float(x)if re.match('[\d.]+',x)else x for x in raw_input().split()]
for o in[0,[4,3][i[0]<'d']]:
w=i[o+1]*i[o+2]*i[o+3]
if i[o]<'d':w*=3.14*i[o+1]/i[o+3]
if i[o]>'s':w*=.5
a=a/w if o else w
print(math.ceil(a)*i[-1])
```
# Python 3, ~~236~~ 233 bytes
```
import re,math;i=[float(x)if re.match('[\d.]+',x)else x for x in input().split()]
for o in[0,[4,3][i[0]<'d']]:
w=i[o+1]*i[o+2]*i[o+3]
if i[o]<'d':w*=3.14*i[o+1]/i[o+3]
if i[o]>'s':w*=.5
a=a/w if o else w
print(math.ceil(a)*i[-1])
```
**Changes:**
Changed `for o in[0,3if i[0]<'d'else 4]:` to `for o in[0,[4,3][i[0]<'d']]:`. Thanks to Vioz for the inspiration :).
[Answer]
# Pyth - 40 39 36 ~~35~~ 34 bytes
Uses simple method, mapping over both containers and then reducing by division.
```
*h/Fmc*Ftd@,/JChd58c.318@d1Jc2PQeQ
```
Takes input comma separated from stdin, with the first letter of each shape like: `"t", 10, 12.25, 3, "c", 5, 2.2, 5`.
[Test Suite](http://pyth.herokuapp.com/?code=*h%2FFmc*Ftd%40%2C%2FJChd58c.318%40d1Jc2PQeQ&input=%22t%22%2C+10%2C+12.25%2C+3%2C+%22c%22%2C+5%2C+2.2%2C+5&test_suite=1&test_suite_input=%22t%22%2C+10%2C+12.25%2C+3%2C+%22c%22%2C+5%2C+2.2%2C+5%0A%22t%22%2C+5%2C+87.3%2C+20001%2C+%22r%22%2C+5.14%2C+2%2C+105.623%2C+0.2&debug=1).
] |
[Question]
[
## Background
The Fibonacci sequence is defined as
$$f(1) = 1 \\ f(2) = 1 \\ f(n) = f(n-1) + f(n-2)$$
The Fibonorial, similar to the factorial, is the product of the first \$n\$ Fibonacci numbers.
$$g(n) = f(1) \times f(2) \times ... \times f(n-1) \times f(n)$$
The Fibonomial coefficient, similar to the binomial coefficient is defined as
$$\begin{align}a(n, 0) & = 1 \\
a(n, k) & = \frac {g(n)} {g(n-k) \times g(k)} \\
& = \frac {f(n) \times f(n-1) \times ... \times f(n-k+1)} {f(1) \times f(2) \times ... \times f(k)}
\end{align}$$
## Task
Your goal is to create a function or program to compute the Fibonomial coefficient given two non-negative integers \$n\$ and \$k\$ with \$l \le n\$.
## Test Cases
```
a(0, 0) = 1
a(1, 1) = 1
a(2, 0) = 1
a(3, 2) = 2
a(8, 3) = 1092
a(11, 5) = 1514513
a(22, 7) = 7158243695757340957617
a(25, 3) = 49845401197200
a(50, 2) = 97905340104793732225
a(100, 1) = 354224848179261915075
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
* Builtins are allowed.
## Related
* [A000045](http://oeis.org/A000045) - [Challenge](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence) - Fibonacci Sequence
* [A003266](http://oeis.org/A003266) - [Challenge](https://codegolf.stackexchange.com/questions/86944/fibonacci-orial) - Fibonorial
* [A010048](http://oeis.org/A010048) - Fibonomial coefficient
[Answer]
## Haskell, 46 bytes
```
l=0:scanl(+)1l;a%0=1;a%b=(a-1)%(b-1)*l!!a/l!!b
```
Outputs floats. Generates the infinite Fibonacci list. Then, does the binomial recusion, multiplying and dividing by elements from the Fibonacci list.
[Answer]
# Python 67 bytes
```
f=lambda n,a=1,b=1:n<1or a*f(n-1,b,a+b)
lambda n,k:f(n)/f(k)/f(n-k)
```
Call using `a(n,k)`. Uses @Dennis fibonorial answer (is that allowed?), and a straightforward implementation of the question otherwise.
[Answer]
# Haskell, ~~77 57 55 52~~ 50 bytes
The first line is originally coming from the [Fibonacci function or sequence](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence/89#89) challenge and was written by @Anon.
The second line was added in the [Fibonacci-orial](https://codegolf.stackexchange.com/questions/86944/fibonacci-orial/86961#86961) challenge by @ChristianSievers.
Now I added the third line. How much further will those challenges go?=)
```
f=1:scanl(+)1f
g=(scanl(*)1f!!)
n#k=g n/g(n-k)/g k
```
Thanks for 5 bytes @xnor!
[Answer]
# C, 206 bytes:
```
#include <inttypes.h>
uint64_t F(x){return x<1 ? 0:x==1 ? 1:F(x-1)+F(x-2);}uint64_t G(H,B){uint64_t P=1;for(B=3;B<=H;B++)P*=F(B);return P;}main(U,Y){scanf("%d %d",&U,&Y);printf("%llu\n",G(U)/(G(U-Y)*G(Y)));}
```
Upon execution, asks for 2 space separated integers as input. The `#include` preprocessor is *required*, as without it, `uint_64` is not a valid type, and the only other way to make this work for fairly big outputs is using `unsigned long long` return types for both the `F` (Fibonacci) and `G` (Fibonorial) functions, which is much longer than just including the `<inttypes.h>` and using 3 `uint64_t` type declarations. However, even with that, it stops working correctly at input values `14 1` (confirmed by using [this](http://oeis.org/A010048/b010048.txt), which lists the first `1325` values in the Fibonomial Coefficient sequence), most likely because the Fibonacci and/or Fibnorial representation of numbers `15` and above overflow the 64-bit integer type used.
[C It Online! (Ideone)](http://ideone.com/nSqk4k)
[Answer]
# [Cheddar](http://cheddar.vihan.org/), ~~75~~ 64 bytes
```
a->b->(g->g((a-b+1)|>a)/g(1|>b))(n->n.map(Math.fib).reduce((*)))
```
## Usage
```
cheddar> var f = a->b->(g->g((a-b+1)|>a)/g(1|>b))(n->n.map(Math.fib).reduce((*)))
cheddar> f(11)(5)
1514513
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~25~~ 23 bytes
```
1ti2-:"yy+]vtPi:)w5M)/p
```
[**Try it online!**](http://matl.tryitonline.net/#code=MXRpMi06Inl5K112dFBpOil3NU0pL3A&input=MTEKNQ)
### Explanation
```
1t % Push 1 twice
i2-: % Take input n. Generate vector [1 2 ... n-2]
" % Repeat n-2 times
yy % Push the top two elements again
+ % Add them
] % End
v % Concatenate into column vector of first n Fibonacci numbers
tP % Duplicate and reverse
i: % Take input k. Generate vector [1 2 ... k]
) % Apply index to get last k Fibonacci numbers
w % Swap to move vector of first n Fibonacci numbers to top
5M % Push [1 2 ... k] again
) % Apply index to get first k Fibonacci numbers
/ % Divide element-wise
p % Product of vector. Implicitly display
```
[Answer]
# R, 120 bytes
Some more golfing is probably be possible, so comments are of course welcomed !
I used my answer of the [Fibonacci-orial](https://codegolf.stackexchange.com/a/87256/56131) question in the begining of the code :
```
A=function(n,k){p=(1+sqrt(5))/2;f=function(N){x=1;for(n in 1:N){x=prod(x,(p^n-(-1/p)^n)/sqrt(5))};x};f(n)/(f(k)*f(n-k))}
```
**Ungolfed :**
```
A=function(n,k){
p=(1+sqrt(5))/2
f=function(N){
x=1
for(n in 1:N){
x=prod(x,(p^n-(-1/p)^n)/sqrt(5))
}
x
}
f(n)/(f(k)*f(n-k))
}
```
[Answer]
# Java: 304 260 257
I saved some bytes by compacting the memoization function a bit and removing `f(n)` entirely, replacing it with direct array access.
```
BigInteger[]c;BigInteger a(int n,int k){m(n);return g(n).divide(g(n-k)).divide(g(k));}BigInteger g(int n){return n<3?BigInteger.ONE:g(n-1).multiply(c[n-1]);}void m(int n){c=new BigInteger[n];for(int i=0;i<n;++i)c[i]=(i<2)?BigInteger.ONE:c[i-2].add(c[i-1]);}
```
Unfortunately, `BigInteger` is required due to overflows and I had to add memoization. Even on a generation 6 i7, it was taking *way* too long to run with large inputs.
Ungolfed, with boilerplate `class` and `main` code:
```
import java.math.BigInteger;
public class ComputeTheFibonomialCoefficient {
public static void main(final String[] args) {
// @formatter:off
String[][] testData = new String[][] {
{ "0", "0", "1" },
{ "1", "1", "1" },
{ "2", "0", "1" },
{ "3", "2", "2" },
{ "8", "3", "1092" },
{ "11", "5", "1514513" },
{ "22", "7", "7158243695757340957617" },
{ "25", "3", "49845401197200" },
{ "50", "2", "97905340104793732225" },
{ "100", "1", "354224848179261915075" }
};
// @formatter:on
for (String[] data : testData) {
System.out.println("a(" + data[0] + ", " + data[1] + ")");
System.out.println(" Expected -> " + data[2]);
System.out.print(" Actual -> ");
System.out.println(new ComputeTheFibonomialCoefficient().a(
Integer.parseInt(data[0]), Integer.parseInt(data[1])));
System.out.println();
}
}
// Begin golf
BigInteger[] c;
BigInteger a(int n, int k) {
m(n);
return g(n).divide(g(n - k)).divide(g(k));
}
BigInteger g(int n) {
return n < 3 ? BigInteger.ONE : g(n - 1).multiply(c[n - 1]);
}
void m(int n) {
c = new BigInteger[n];
for (int i = 0; i < n; ++i)
c[i] = (i < 2) ? BigInteger.ONE : c[i - 2].add(c[i - 1]);
}
// End golf
}
```
Program output:
```
a(0, 0)
Expected -> 1
Actual -> 1
a(1, 1)
Expected -> 1
Actual -> 1
a(2, 0)
Expected -> 1
Actual -> 1
a(3, 2)
Expected -> 2
Actual -> 2
a(8, 3)
Expected -> 1092
Actual -> 1092
a(11, 5)
Expected -> 1514513
Actual -> 1514513
a(22, 7)
Expected -> 7158243695757340957617
Actual -> 7158243695757340957617
a(25, 3)
Expected -> 49845401197200
Actual -> 49845401197200
a(50, 2)
Expected -> 97905340104793732225
Actual -> 97905340104793732225
a(100, 1)
Expected -> 354224848179261915075
Actual -> 354224848179261915075
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
0+⁸С1ḊP
;_/Ç€:/
```
[Try it online!](http://jelly.tryitonline.net/#code=MCvigbjDkMKhMeG4ilAKO18vw4figqw6Lw&input=&args=WzEwMCwxXQ)
Credits to [Dennis](https://codegolf.stackexchange.com/a/86945/48934) for the Fibonacci-orial helper link.
```
;_/Ç€:/ Main chain, argument: [n,r]
_/ Find n-r
; Attach it to original: [n,r,n-r]
Ç€ Apply helper link to each element, yielding [g(n),g(r),g(n-r)]
:/ Reduce by integer division, yielding g(n)//g(r)//g(n-r)
0+⁸С1ḊP Helper link, argument: n
0+⁸С1ḊP Somehow return the n-th Fibonacci-orial.
```
[Answer]
# JavaScript (ES6), 70 bytes
```
a=n=>n<2?1:a(--n)+a(--n);b=n=>n?a(--n)*b(n):1;c=n=>k=>b(n)/b(n-k)/b(k)
```
Call using `c(n)(k)`, pretty straightforward.
[Answer]
# Ruby, 72 bytes
Special thanks to @st0le for [the really short Fibonacci generation code](https://codegolf.stackexchange.com/a/111/52194).
```
->n,k{f=[a=b=1,1]+(1..n).map{b=a+a=b}
r=->i{f[i,k].inject:*}
k>0?r[n-k]/r[0]:1}
```
[Answer]
# dc, 67 bytes
```
?skdsn[si1d[sadlarla+zli>b*]sbzli>b*]dsgxsplnlk-lgxsqlklgxlprlqr*/f
```
Input is taken as space-delimited decimal constants on a single line.
This uses my [answer](https://codegolf.stackexchange.com/questions/86944/fibonacci-orial/86949#86949) to the `/Fibon(acci-)?orial/` question, which multiplies all numbers on the stack in the last step, requiring the other numbers to be stored elsewhere while the other Fibonorials are calculated.
```
? # Take input from stdin
skdsn # Store second number in register `k'; store a copy of first number in register `n'
[si1d[sadlarla+zli>b*]sbzli>b*] # Compute Fibonorial of top-of-stack, multiplying
# until stack depth is 1
dsgx # Store a copy of this function as g and execute it: g(n)
sp # Store g(n) in register `p'
lnlk- # Compute n-k
lgx # Compute g(n-k)
sq # Store g(n-k) in register `q'
lk lgx # Compute g(k)
# Top ---Down--->
lp # g(n) g(k)
r # g(k) g(n)
lq # g(n-k) g(k) g(n)
r # g(k) g(n-k) g(n)
* # (g(k)g(n-k)) g(n)
/ # g(n)/(g(k)g(n-k))
f # Dump stack to stdout
```
[Answer]
# Julia, 53 bytes
```
!x=[([1 1;1 0]^n)[2]for n=1:x]|>prod;n\k=!n/!(n-k)/!k
```
Credits to @Lynn for his [Fibonorial answer](https://codegolf.stackexchange.com/a/86970/41247).
[Answer]
**Axiom 108 bytes**
```
b(n,k)==(n<=k or k<1=>1;reduce(*,[fibonacci(i) for i in (n-k+1)..n])/reduce(*,[fibonacci(i) for i in 1..k]))
```
some test
```
(34) -> b(0,0),b(1,1),b(2,0),b(3,2),b(8,3),b(11,5),b(22,7)
Compiling function b with type (NonNegativeInteger,
NonNegativeInteger) -> Fraction Integer
Compiling function b with type (PositiveInteger,PositiveInteger) ->
Fraction Integer
Compiling function b with type (PositiveInteger,NonNegativeInteger)
-> Fraction Integer
(34) [1,1,1,2,1092,1514513,7158243695757340957617]
Type: Tuple Fraction Integer
(35) -> b(25,3),b(50,2),b(100,1)
(35) [49845401197200,97905340104793732225,354224848179261915075]
```
## Type: Tuple Fraction Integer
[Answer]
# Mathematica, 30 bytes
```
(f=Fibonorial)@#/f[#-#2]/f@#2&
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
;ạ/RÆḞP€÷/
```
[Try it online!](https://tio.run/##VU67CgJBDKy9r1iwUVi4JJtcNoj/ILZiaSP@gK2F9lZWgr29j/bwQ84fWffg5LRKZiYzk/Vqs9mmNGmel3Je75v7efbeXetbmepDXl7H5nFKaVEMRuAdjL0buqnDDNE7/IH0rwbvqIOUYfQufFWwlsHsly8lyIKhTckx2rGKEolDZaKigSHPCrU9kj6NLbIwIJoSQBYF@mZTA8lOBFYLGohI2mqA/vcgTMSRI6pRhYYCKsXyAw "Jelly – Try It Online")
## How it works
```
;ạ/RÆḞP€÷/ - Main link. Takes [n, r] on the left
ạ/ - Calculate |n-r|
; - Yield [n, r, |n-r|]
R - Convert each to a range
ÆḞ - For each integer i, yield the i'th Fibonacci number
P€ - Get the product of each array, yielding [g(n), g(r), g(n-r)]
÷/ - Yield g(n) ÷ g(r) ÷ g(n-r) = g(n) ÷ (g(r) × g(n-r))
```
] |
[Question]
[
## The Task
I guess everybody loves automatic code generation and saving some time during work. You have to create a lot of classes and members during the day and you don't want to create all those `getters` manually.
The task is to write a program or function, that generates `getters` for all class members automatically for you.
---
## The Input
In our language objects are very simple. Names of classes and members must start with an chararacter from `[a-zA-Z]` and can only contain the characters `[a-zA-Z0-9]`. Here's an example:
```
class Stack {
public overflow;
protected trace;
private errorReport;
}
```
---
## The Output
This is a valid output based on the given example:
```
class Stack {
public overflow;
protected trace;
private errorReport;
public function getOverflow() {
return this->overflow;
}
public function getTrace() {
return this->trace;
}
public function getErrorReport() {
return this->errorReport;
}
}
```
---
## The Getter
The requirements for a `getter` method are:
* The function name must start with `get` followed by the member name with an uppercase initial.
* The function has no parameters.
* To return a variable use `return this->memberName;`.
* `getters` and `setters` (*see **The Bonuses***) must be grouped and must come after all variable declarations.
**Example:**
```
private value1;
private value2;
public function getValue1() { return this->value; }
public function setValue1(value) { this->value = value; }
public function getValue2() { return this->value; }
public function setValue2(value) { this->value = value; }
```
---
## The Requirements
* Create a program or a function.
* Input can come from STDIN, command line arguments, function arguments, a file etc.
* Any output format is acceptable from a simple `return`-value to a file or writing to STDOUT.
* In- and output don't need to be formatted with whitespaces, newlines, tabs etc. This is a valid input: `class A{protected a;}`.
* You can assume that the input is valid and your program can handle unexpected input unexpected as well.
---
## The Bonuses
You can get down to 10% of your original byte count by withdrawing 30% for each feature:
**A:** Your program can address newly added variables and adds missing `getters` only (`public function getB() { return this->b; }` in this case):
```
class A {
public a;
public b;
public function getA() { return this->a; }
}
```
**B:** Your program also generates `setters`:
```
class A {
public a;
public getA() { return this->a; }
public setA(a) { this->a = a; }
}
```
**C:** Your program can handle static members:
```
class A {
public static c;
public static function getC() { return this->c; }
}
```
---
This is code golf – so shortest answer in bytes wins. Standard loopholes are disallowed.
[Answer]
# Perl, 161 - 90% = 16.1 bytes
```
$/=0;$_=<>;for$g(/\bp\S*( +static)? +(\S*);/g){++$i%2?$c="public$g function":/get\u$g/||s/}$/$c get\u$g(){return this->$g;}\n$c set\u$g(x){this->$g=x;}\n}/}print
```
[Answer]
# Pyth, ~~198 bytes - 90% = 19.8 bytes~~ ~~187 - 90% = 18.7 bytes~~ 183 bytes - 90% = 18.3 bytes
```
pJ<rs.z6_1sm?}+=b"get"K+rh=Zed1tZJks[Y=N|@d1kGbK"(){return "=H+"this->"Z";}"YNG"set"K"(x){"H"=x;}"):Js["(?:(?:"=Y"public""|private|protected)(?!"=G" function "")( static)?) (\w+)")4\}
```
*Must...beat...Perl...*
## 187-byte/18.7-byte version
```
J<rs.z6_1s_+\},sm?}+=b"get"K+rh=Zed1tZJks[Y=N|@d1kGbK"(){return "=H+"this->"Z";}"YNG"set"K"(x){"H"=x;}"):Js["(?:(?:"=Y"public""|private|protected)(?!"=G" function "")( static)?) (\w+)")4J
```
## 198-byte/19.8-byte version
```
J<rs.z6_1s_,sm?}K+rhed1tedJks["public"=N|@d1k=G" function ""get"K"(){return this->"ed";}public"NG"set"K"("ed"){this->"ed"="ed";}"):J"(?:(?:public|private|protected)(?! function )( static)?) (\w+)"4J
```
**TODO:** More golfing!
[Answer]
# JavaScript ES6 (at the moment), ~~305~~ ~~289~~ 223 - 60% = 89.2 bytes
Was `256 - 30% = 179.2 bytes`
Qualifies for static and setter bonuses; now with extra ES6!
```
s=>s.replace(/\}$/,s.match(/(public|private)( static)* \w+/g).map(e=>{o=(r=e.split` `).pop();return(n=r.join` `)+` get${U=o[0].toUpperCase()+o.slice(1)}(){return this->${o};}${n} set${U}(${o}){this->${o}=${o};}`}).join``+"}")
```
## ES5 function, 115.6 bytes
```
function g(s){return s.replace(/\}$/,s.match(/(p(?:ublic|rivate))( static)* (\w+?);/gm).map(function(e){o=(r=e.split(" ")).pop().replace(/;/,"");return(n=r.join(" "))+" get"+(U=o[0].toUpperCase()+o.slice(1))+"(){return this->"+o+";}"+n+" set"+U+"("+o+"){this->"+o+"="+o+";}"}).join("")+"}")}
```
[Answer]
# CJam, 71 bytes
```
q';/W<_{S%W=:O(eu"public function get"\@"{return this->"O";}"}%\';f+\'}
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q'%3B%2FW%3C_%7BS%25W%3D%3AO(eu%22public%20function%20get%22%5C%40%22%7Breturn%20this-%3E%22O%22%3B%7D%22%7D%25%5C'%3Bf%2B%5C'%7D&input=class%20A%7Bprotected%20a%3B%7D).
] |
[Question]
[
## Challenge
>
> In this task you have compute the number of ways we can
> distribute A balls into B
> cells with with every cell
> having at-least one ball.
>
>
>
The inputs A and B are given in a single line separated by a blank,the inputs are terminated by EOF.
You may like to check your solutions [here](http://golf.shinh.org/p.rb?Distributing+the+balls).
**Input**
```
0 0
1 0
12 4
6 3
18 17
20 19
15 13
18 9
20 20
17 14
9 2
14 13
18 11
```
**Output**
```
1
0
14676024
540
54420176498688000
23112569077678080000
28332944640000
38528927611574400
2432902008176640000
21785854970880000
510
566658892800
334942064711654400
```
**Constraints**
* **Every A and B can be distinguishable.**
* 0 <= A,B <= 20
* You can use any language of your choice
* Shortest solution wins!
[Answer]
## JavaScript (90 93)
```
function f(a,b){n=m=r=1;for(i=b;i>0;n*=-1){r+=n*m*Math.pow(i,a);m=m*i/(b-i--+1)}return--r}
```
<http://jsfiddle.net/RDGUn/2/>
Obviously, any math-based language such as APL will beat me because of syntax verbosity and lack of built-in mathematical constructs :)
**Edit** Also, I don't have any input-related functionality except parameters passed into the function, not sure how to use standard input with JavaScript...
**Edit:** Move `i--` into `m=m*` expression; move `n*=-1` into `for`; start `r=1` to combine assignments and remove extraneous one on return. (save 3 chars)
[Answer]
### Golfscript - 56 50 49 48 41 40 38 37 chars
```
n%{~),{!}%\{0.@{.@+2$*@)@}/;;]}*)p;}/
```
Note: this handles multiple lines of input, is fast (1/8 secs to do the test cases), and doesn't break for any legal input.
(The first version was also my first ever Golfscript program; thanks to eBusiness for pointing out several tricks I missed).
In order to make this a useful educational post too, here's an explanation of how it works. We start with the recurrence `f(n, k) = k * (f(n-1, k) + f(n-1, k-1))`. This can be understood combinatorically as saying that to place `n` distinguishable balls in `k` distinguishable buckets such that each bucket contains at least one ball, you pick one of the `k` buckets for the first ball (`k *`) and then either it will contain at least one more ball (`f(n-1, k)`) or it won't (`f(n-1, k-1)`).
The values resulting from this form a grid; taking `n` as the row index and `k` as the column index and indexing both from 0 it starts
```
1 0 0 0 0 0 0 ...
0 1 0 0 0 0 0 ...
0 1 2 0 0 0 0 ...
0 1 6 6 0 0 0 ...
0 1 14 36 24 0 0 ...
0 1 30 150 240 120 0 ...
0 1 62 540 1560 1800 720 ...
. . . . . . . .
. . . . . . . .
. . . . . . . .
```
So turning to the program,
```
n%{~ <<STUFF>> }/
```
splits the input into lines and then for each line evaluates it, putting `n` and `k` on the stack, and then calls `<<STUFF>>`, which is as follows:
```
),{!}%\{0.@{.@+2$*@)@}/;;]}*)p;
```
This computes the first `k+1` entries of the `n+1`th row of that grid. Initially the stack is `n k`.
`),` gives stack of `n [0 1 2 ... k]`
`{!}%` gives stack of `n [1 0 0 ... 0]` where there are `k` 0s.
`\{ <<MORE STUFF>> }*` brings the `n` to the top and makes it the number of times we execute `<<MORE STUFF>>`.
Our stack currently is a row of the table: `[f(i,0) f(i,1) ... f(i,k)]`
`0.@` puts a couple of 0s before that array. The first one will be `j` and the second one will be `f(i,j-1)`.
`{ <<FINAL LOOP>> }/` loops through the elements of the array; for each one it puts it on top of the stack and then executes the loop body.
`.@+2$*@)@` is boring stack manipulation to take `... j f(i,j-1) f(i,j)` and yield `... j*(f(i,j-1)+f(i,j)) j+1 f(i,j)`
`;;]` pops off the left-over `k+1 f(i,k)` and gathers everything into an array, ready for the next go round the loop.
Finally, when we've generated the `n`th row of the table,
`)p;` takes the last element, prints it, and discards the rest of the row.
For posterity, three 38-char solutions on this principle:
`n%{~),{!}%\{0.@{.@+@.@*\)@}/;;]}*)p;}/`
`n%{~),{!}%\{0:x\{x\:x+1$*\)}/;]}*)p;}/`
`n%{~),{!}%\{0.@{@1$+2$*\@)}/;;]}*)p;}/`
[Answer]
## Golfscript - 26 chars
Warning: The 12 4 case needs a lot of memory (although not as much as the answer below) and takes a quite a while to run
```
~:)\?:x,{x+)base(;.&,)=},,
```
---
Obviously this answer has some problems, but I will leave it here because the comments refer to it and mellamokb's answer is based off it.
**Golfscript - 24 chars**
Warning: The 12 4 case needs a lot of memory and takes a quite a while to run
```
~:o)\?,{o)base[0]-,o=},,
```
[Answer]
## J, 40
```
4 :'|-/x(^~*y!~])i.1x+y'/&.".;._2(1!:1)3
```
E.g
```
4 :'-/((x^~|.@:>:)*y&(!~))i.y'/x:".>{.;:(1!:1)3
15 13
28332944640000
```
<1sec for all test cases.
### Edits
* **(52 → 47)** Reduce with `-/` instead of alternating `(1 _1)*` (J-B's idea)
* **(47 → 53)** Noticed multiline input requirement :-/
* **(53 → 48)** Exploit symmetry of binomials.
* **(48 → 48)** Make tacit!
* **(48 → 41)**
* **(41 → 40)** Squeeze increment+conversion into `1x+`
[Answer]
## Common Lisp (83)
```
(defun b (x y)
(if (= (* x y) 0)
(if (= (+ x y) 0) 1 0)
(* y (+ (b (decf x) y) (b x (1- y)))))))
```
It seems like there should be a shorter way to test the base cases, but nothing occurs to me offhand.
[Answer]
## J, 38 to 42
Depending on your strictness preferences about interactive languages and output presentation, take your pick from the J spectre of solutions:
* **38** shortest interactive: `4 :'|-/(!&y*^&x)i.1x+y'/&".;._2(1!:1)3`
Launch jconsole, enter it, then paste the input (end with C-d). You'll notice the output is space-separated (J is a vector language, it performs the computation on the whole input as a whole and returns it as a 1D vector, whose default presentation is on a single line). I consider that ok, the spirit of this problem is computation, not presentation. But if you insist on having newlines instead:
* **39** longer interactive: `4 :'|-/(!&y*^&x)i.1x+y'/&.".;._2(1!:1)3`
Replacing *Compose* (`&`) with *Under* (`&.`) returns a vector of strings, whose presentation ends up on separate lines.
* **42** batch mode: `4 :'echo|-/(!&y*^&x)i.1x+y'/&".;._2(1!:1)3`
Run from the command line as `$ jconsole balls.ijs < balls.in`
If you voted this up, you might want to go give [Eelvex's solution](https://codegolf.stackexchange.com/questions/1872/code-golf-distributing-the-balls-i/1889#1889) some credit as well.
[Answer]
# GolfScript - 45 38 36 characters
### Medium-force dirty implementation recurrence relation (38 36 characters):
```
n%{~{.2$*{\(.2$f\2$(f+*}{=}if}:f~p}/
```
The recurrence relation I stole from Peter Taylors solution, it goes like this:
`f(x, y) = y * ( f(x-1, y) + f(x-1, y-1) )`
With special cases if either variable is 0.
My implementation does not reuse previous results, so each function call branch to two new calls, unless one of the zero cases have been reached. This give a worst case of 2^21-1 function calls which takes 30 seconds on my machine.
### Light-force series solution (45 characters):
```
n%{~.),0\{.4$?3$,@[>.,,]{1\{)*}/}//*\-}/p;;}/
```
[Answer]
# J, 55 characters
```
(wd@(4 :'(y^x)--/(!&y*^&x)|.i.y')/@".@,&'x');._2(1!:1)3
```
* Passes current test cases. I *think* I understand the math...
* j602, console only (`wd`). Input on stdin, output on stdout.
Bash test script:
```
jconsole disballs.ijs <<END
12 4
6 3
END
```
[Answer]
**Python 140 Chars**
```
import sys
f=lambda n,k:(n and k and n>=k and k*(f(n-1,k-1)+f(n-1,k)))or(n+k==0 and 1)or 0
for l in sys.stdin:print f(*(map(int,l.split())))
```
[Answer]
### dc, 100 chars
```
[0q]s5[1q]s6[l2l3>5l3 0>5l2 0=6l2 1-S2l3dS3 1-S3l1xL3s9l1xL2s9+L3*]s1[?z0=5S3S2l1xL3L2+s9fs9l4x]ds4x
```
Alas, dc doesn't seem to be supported by ideone. There may be a character or two still to squeeze out, but it's bedtime.
Note: this supports multiple lines of input, has sufficient precision to give the correct output even for `20 19` (curse you, Perl, for the time I wasted debugging my solution!), and gives the correct output for `0 0`.
Suggestions from Nabb allow shortening at least as far as
```
[0q]sZ[1q]sI[?z0=ZSkSn[lnlk>Zlk0>Zln0=Iln1-SnlkdSk1-SklFxLks9lFxLns9+Lk*]dsFxfs9l4x]ds4x
```
at the cost of leaving junk in the register stacks (and thus running out of memory if we compute billions of answers).
[Answer]
## Golfscript (28 31 37)
`~):$\.($\?:@;?,{@+}%{$base$,\-[0]=},,`
Modification to `gnibbler`'s GolfScript solution. I think this is a working solution - tested with [3,2], [4,2], [6,3], and [9,2] with correct answers. (I used `$` and `@` for variables to tighten up space around the `base` keyword).
There are two problems with `gnibbler`'s current solution.
1. Checking length after removing [0] does not guarantee a solution, because [1,1,1,1] would be valid for input [4,2], even though all 4 balls are in the same cell (1). So I've modified to check also that all digits are used, i.e., the array contains 1-2, so each cell contains at least one ball.
2. In the case of input [4,2], the base-3 format of numbers 0-27 are less than 4 digits, and the left-most 0's are not included. That means [1,1] is included as a valid solution, even though it is technically actually [0,0,1,1], which means the first two balls are not placed anywhere. I fix by adding 3^3 to every entry (generically k^n-1 to the array of k^n entries) so that the first entries are shifted upward to having at least n-digits in base-k format, and the last entries will automatically be invalid anyway and won't affect the solution (because the second digit will always be 0).
**Edit**
`~:@\?:$,{$+}%{@base(;@,\-,0=},,`
```
`~:@\?:$,{$+@base(;@,\-,0=},,`
```
Better solution yet! No need to increment, just add to all of the numbers so they start with [1], and no digits will be missing (including the left-padding of 0's) once you decon that first digit. This solution should work and has been tested with same entries above. It's also a lot faster because we aren't incrementing before taking exponent to generate the array (but still suffers from same performance / memory problem for larger input).
**Edit**: Use `gnibbler`'s idea of moving the addition of `$` inside of the filter instead of as an extra step. (save 3 chars).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#D`ULX.Œʒ€gßĀ}gs_P+
```
NOTE: It's extremely slow, and already times out for `12 4`. It is working as intended, though. ~~Will see if I can come up with an alternative method which works for all test cases in a reasonable time.~~ See below for a much faster version which runs all test cases in less than a second.
[Try it online](https://tio.run/##yy9OTMpM/f9f2SUh1CdC7@ikU5MeNa1JPzz/SENtenF8gPb//2YKxgA) or [verify a few more (of the smaller) test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf2WXhFCfCL2jk05NetS0Jv3w/CMNtenF8QHa/3X@GygYcBkCsZmCMZelghGXCRibcJkqGAIA).
**Explanation:**
```
# # Split the (implicit) input-string by spaces
D # Duplicate it
` # Push both values to the stack
U # Pop and store the second value in variable `X`
L # Create a list in the range [1,n] for the first value
X.Œ # Create a list of all possible ways to divide this list into `X` partitions
# (including empty sublists, so we'll have to filter them out:)
ʒ # Filter this list of lists of partition-lists by:
€g # Get the length of each partition-list
ß # Get the minimum length
Ā # Truthify; 0 remains 0 (falsey); anything else becomes 1 (truthy)
}g # After the filter, take the length to get the amount left
s # Swap so the duplicated input-list is at the top of the stack again
_ # Check for each value if they're equal to 0 (1 if truthy; 0 if falsey)
P # Take the product of the two to check if both input-values are 0
+ # And add it to the earlier calculated product (edge case for [0,0] = 1)
# (After which the result is output implicitly)
```
---
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Here a much faster version which works for all test cases in about 0.5 seconds on TIO:
```
Î#R`V©LRvyYmX*NÈ·<*+Xy*®y->÷U
```
Port of [*@mellamokb*'s JavaScript answer](https://codegolf.stackexchange.com/a/1873/52210), so make sure to upvote him!
[Try it online](https://tio.run/##yy9OTMpM/f//cJ9yUELYoZU@QWWVkbkRWn6HOw5tt9HSjqjUOrSuUtfu8PbQ///NFIwB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkv1/g0rloISwQyt9gsoqI3MjtPwOdxzabqOlHVGpdWhdpa7d4e2h/2t1DEP/GygYcBmCsJGCCZeZgjGXoYWCoTmXkYGCoSWXoamCIVjEEiRgBFRlrmBowmWpYMRlaAKVMjTkMgHyTYDagaoB).
**Explanation:**
```
Î # Push (result=) 0 and the input
# # Split the input by spaces
R` # Push the values to the stack reversed
V # Pop and store the first value in variable `Y`
© # Store the second value in variable `®` (without popping)
LRv # Loop `y` in the range [`®`,1], with index `N` in the range [0,`®`):
yYm # Calculate `y` to the power `Y`
X* # Multiply it by `X`
# (Note: `X` is 1 before setting it to another value initially)
NÈ # Check if index `N` is even (1 if truthy; 0 if falsey)
·< # Double it; and decrease it by 1 (1 if truthy; -1 if falseY0
* # Multiply it to the earlier number
+ # And add it to the result
Xy* # Push `X` multiplied by `y`
®y-> # Push `®` - `y` + 1
÷ # Integer divide them
U # Pop and store it as new variable `X`
# (output the result at the top of the stack implicitly after the loop)
```
NOTE: Works for edge case `0 0` in this case (unlike the JavaScript answer I ported this method from), because the `L` builtin will create a list `[0,1]`.
] |
[Question]
[
Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
Fen is a magician Elf. He can cast spells on an array of numbers to produce another number or array of numbers.
One of his inventions is the [Wick spell](https://codegolf.stackexchange.com/q/255274/78410). He likes this magic so much that he's cast it on every single array in sight. Now he needs help reversing his own magic...
## Task
Reverse Fen's Wick spell. To recap, the Wick spell works as follows:
* Given an array of positive integers `A` of length `n`,
* Replace each item at 1-based index `i` with the sum of last `j` elements, where `j == 2 ** (trailing zeros of i in binary)`.
For example, if the input array is `A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]`,
```
Wick(A) = [
1, # 1
3, # 1+2
3, # 3
10, # 1+2+3+4
5, # 5
11, # 5+6
7, # 7
36, # 1+2+3+4+5+6+7+8
9, # 9
10, # 9+1
]
```
In this task, you need to reverse it, so given `Wick(A) = [1, 3, 3, 10, 5, 11, 7, 36, 9, 10]` as input, your program should output `A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]`.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
[] -> []
[999] -> [999]
[3,4,4] -> [3,1,4]
[3,4,4,9,5,14,2,31] -> [3,1,4,1,5,9,2,6]
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 41 bytes
```
a->a/matrix(#a,,j,i,i-j<gcd(i,2^i)&&j<=i)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY1rCsIwEISvEiqUBCbYNPURaHuRUiUoKVtUQqmgZ_FPQcQzeRsTLLKw38ywyzze3g607_z0dKx6XUcntx9hZW2XZzsOdOMLC_QgkOzL7nDkhHxHIk37siIxPzjr_enOLZM18wNdxiCTaBLmuBUCrGnasIwxERoFir-AwQqqQA6tYqigw6gspgob6HW4UFnbzm3T9OMX)
Based on [my answer to the CGAC2022 Day 7](https://codegolf.stackexchange.com/a/255281/9288). Multiplies the inverse of the matrix in that challenge.
[Answer]
# [Python](https://www.python.org) NumPy, 42 bytes
```
def f(a):b=a[1::2];b@b>0!=f(b);b-=a[:-1:2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZA7DsIwDED3nMKIJYUUUX6iqYq4R9XBKQQ6NIlCGXoWli5wISZug6EUISI5sZ71bMWXm2vqozVtez3XOlw_Rru9Bs0xkCrFLJJylidqqzbTQaq5ChIVEpZhRPxj3Iegva3Aoa8hYi__8OePv07f60C9GCsrZ0ky58o1gCcwjjFtPSCUBrJcZHEc0z0XkVj0L8VSxGImVrlkQAchJXGC3mNDc99MEcNJYV3DO_Ce90oKqqjfiuZFlzhfmpqjUKIIuq_1S3kC)
This is literally my [part 1 answer](https://codegolf.stackexchange.com/a/255290/107561) back to front.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes
```
₌LGɾ↔'ẏD›⋏ṡİṠ?⁼
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoxMR8m+4oaUJ+G6j0TigLrii4/huaHEsOG5oD/igbwiLCIiLCJbMywgNCwgNF0iXQ==)
Math? Clever ways of inverting things? No, couldn't be me!
Times out for inputs longer than about 4 or 5 or where there's a sum that's kinda large (like 32).
Builds upon my [answer from yesterday](https://codegolf.stackexchange.com/a/255280/78850)
## Explained
```
₌LGɾ↔'ẏD›⋏ṡİṠ?⁼
Gɾ # From the range [1, max(input)] - already making inputs with large numbers take a while
₌L ↔ # Get all combinations with repetition of length(input) - meaning that only short lists with small numbers will be solved quickly
' # Keep only the combinations where:
ẏD›⋏ṡİṠ # Applying the solution to yesterday's challenge
?⁼ # is equal to the input - only returns a single list
```
[Answer]
# JavaScript (ES6), 52 bytes
```
a=>a.map((v,i)=>a.map((_,j)=>(j+1&j)>i?0:a[j]-=v)|v)
```
[Try it online!](https://tio.run/##bYrBCsIwEAXvfkVOksVta5pWiJD6ISXIUltJqE2xkpP/HoMHUemDdxhmHAVaurudH9nkL30cdCTdUH6jmfOAFj5wRpeAu53YOmjsaX@k1plMB3gGiJ2fFj/2@eivfOCtUsqwnwGwomBvsfmLJVZYmZVYokhiNUeFNYoKS5TCfOfpdZIlHkx8AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-p`, ~~29~~ ~~23~~ 21 bytes
```
FzglPBz-$+l@>YiBA++il
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJGemdsUEJ6LSQrbEA+WWlCQSsraWwiLCIiLCIzIDQgNCA5IDUgMTQgMiAzMSIsIi1wIl0=)
Based on [my answer from CGAC2022 Day 7](https://codegolf.stackexchange.com/a/255278/110555).
~~I'm sure @DLosc will be able to golf it further for me.~~ -2 bytes thanks to DLosc
[Answer]
# [Python](https://www.python.org), ~~69~~ 63 bytes
```
lambda A,n=[],i=0:[n:=n+[j-sum(n[i&(i:=i+1):])]for j in A]and n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY5NCsIwEIX3OUVWkuAI1v8WBvEccZD4U4zEUdq48CxuCqIX8DTexsaKuni8YZj3vbncj-ewPXB1LXB-O4W8M3lOvd0v11bOgNEQOOxmhjPkttl1ytNesXEt5TJ07URnpCk_FHInHcsZWV5L_mAeOX5AvmHErP_POtIxu4hZT0KETRkWK1tuSjTCJNCDPgxgCCMYwwRSSAiEiUrTNFofEhh8h1rD-qgHo3pF4lg4Dsp6r0yhchXZWiNGl7H1PdTFv1LSunm9qhp_AQ)
A port of [my pip answer](https://codegolf.stackexchange.com/a/255308/110555) and merge of my previous two answers (see edits). I forgot [my own tip](https://codegolf.stackexchange.com/a/247525/110555) of using the walrus operator to store previous iteration results in list comprehension.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
FA⊞υ⁻ι↨¹✂υ&Lυ⊕Lυι¹Iυ
```
[Try it online!](https://tio.run/##TYzLCsIwEEX3fsUsJxDBIirSlXVVUCi4LF2EONpAOpU89PPj1JVwYS7nDNeOJtjZ@FIecwBs@ZUTKgVdjiNmDVfHOaLT0JhIWGm4eWdpMY1LHxfpxHe8ED@TvCsNLdtAE3GiP6xEyEQlRdWrLjhOeDYxLaoupe9ld/tLtdGwkyPgIGCv4bjAYSjrt/8C "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Works by collecting the results so far and using the algorithm from the Day 7 question to determine which ones to subtract off, so effectively a port of @jezza\_99's Python answer, but I get to use `len(n)` instead of `i` as that's shorter in Charcoal.
```
FA
```
Loop over the input elements.
```
⊞υ⁻ι↨¹✂υ&Lυ⊕Lυι¹
```
Subtract the elements of the results so far that would have been added to produce the next input element to obtain the next result element, although I have to use base `1` to cope with alternate elements that have nothing to subtract.
```
Iυ
```
Output the results.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
āvDNyN&ŸèÆNǝ
```
Based on [my answer for the inverted challenge](https://codegolf.stackexchange.com/a/255286/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//SGOZi1@ln9rRHYdXHG7zOz73//9oQx1jIDQ00DHVMTTUMdcxNtOxBHJjAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/I41lLn6VfmpHdxxecbjN7/jc/7U6/6OjDXWMgdDQQMdUx9BQx1zH2EzHEsiN1YkGIktLSyBprGOiYwKjgbJAlSY6RjrGhrGxAA).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length]
v # Loop over each of its 1-based indices `y`:
D # Duplicate the current list (which is the input in the first iteration)
yN& # Bitwise-AND the 1-based index `y` and 0-based index `N` together
N Ÿ # Pop and push a list in the range [N,y&N]
è # Get the values at those indices from the copy of the current list
Æ # Reduce this list by subtracting
ǝ # Then insert this value back into the current list
N # at loop-index `N`, replacing the current value at this index
# (after the loop, the resulting list is output implicitly)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
```
.e-bsm@Qxk^2dssM*.*er8.B
```
[Try it online!](https://tio.run/##K6gsyfj/Xy9VN6k41yGwIjvOKKW42FdLTyu1yELP6f//aGMdBRMwstRRMNVRMASyjHQUjA1jAQ "Pyth – Try It Online")
### Explanation
```
.e-bsm@Qxk^2dssM*.*er8.BkQ # implicit k and Q added
# Q = eval(input()) implicitly
.e Q # enumerate k and b over the indices and values of Q
-b # subtract from b
s # the sum of
m # map d over
ssM*.*er8.Bk # the number of 1s k ends in in binary
@Q # Q indexed at
xk^2d # k xor (2^d)
```
[Answer]
# x86-64 machine code, 20 bytes
```
89 F1 8D 51 FF 8B 04 97 09 CA 39 F2 73 03 29 04 97 E2 EF C3
```
[Try it online!](https://tio.run/##VVJNT8MwDD03v8IMTUrbDPZRkNgoF85cOCFtO2RJ2ga1yZRso2XaX6e43SaBKsWxn997dlQxyoVoW@4roPA@oCSbB5U9gBI1A@U1cfOgVByUxHzpRA0jmKzJuYf3NakhhiRyssa6dedW5JNAVNtLhkLBJ1fgSeD3m/8k1gkRjz7WbsGRwKkdCQfhghyslpBRbXYQcQZdNFi@1UaUe6ng2e@ktnfFCyEdVnFt@mbucsFAFNxBFGFyCMmRBD2yXEMKxxlL8HtiD2ySsCmbTU6LM14i6vW3shnl4f3lFnE0DbDCoOxvuGTvo7F7vMBwk0KJMY5D2DpEMjoYahgw9NPrjnKtrszKvHFRaKNAWKnm3Zq9c91pMWgwlRaOVwIMx9MPFGpSSvfG69wo2W8WhVm4rOMY5U/wVehSAW26Qcb16@yvJVAcZdPslA9XBpXqDsQn3juDw5NT2/6IrOS5b0fVY4IH/gspUlX5Cw "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the address of an array of 32-bit integers in RDI and its length in ESI, and modifies the array in place.
---
This is easier to explain by first looking at an algorithm for the forwards Wick transformation.
Go through each position in ascending order, and add its value to the value at the position that should immediately contain it, if that position exists within the array's bounds.
```
―――――――7
↑ ↑↑
―――3 ||
↑↑ ||
―1| ―5| ―9
↑ | ↑ | ↑
0 2 4 6 8
```
With 0-indexing, if the current position is `n`, the containing position is `n OR n+1`.
---
For the reverse Wick transformation, reverse the procedure: go through each position in descending order, and subtract its value from the value at the position that should immediately contain it, if that position exists within the array's bounds.
Assembly:
```
f: mov ecx, esi # Set ECX to the length.
r: lea edx, [rcx - 1] # Set EDX to 1 less than ECX. (ECX-1 is the current position.)
mov eax, [rdi + 4*rdx] # Load the value at index EDX into EAX.
or edx, ecx # Change EDX to its bitwise OR with ECX.
cmp edx, esi # Compare that value to the the length.
jae s # Jump if it's greater than or equal to the length.
sub [rdi + 4*rdx], eax # (If it's less) Subtract EAX from the value at index EDX.
s: loop r # Decrease ECX by 1, and jump back to repeat if it's nonzero.
ret # Return.
```
] |
[Question]
[
# Warning: Contains minor Deltarune Chapter 1 Spoilers
Within the [Forest](https://deltarune.fandom.com/wiki/Forest) section of the first chapter of [Deltarune](https://www.deltarune.com/), there are a few puzzles that consist of entering playing-card suits in a certain order to move to the next section. Below is an example of such a puzzle:
>
> 
>
>
>
The way to solve the puzzle is to do any of the following until the input pattern matches the required pattern: a) add a spade, b) add a diamond, c) toggle the suits of the already inputted pattern (spades goes to clubs and vice versa, hearts goes to diamonds and vice versa).
The solution to the puzzle in the picture is:
a) Add a spade
b) Add a diamond
c) Add a spade
d) Toggle suits
>
> 
>
>
>
[Here's a video version of the solving of the puzzle](https://youtu.be/eI4Wu7qiiBw)
## A Worked Example
Say the required pattern was `diamond, heart, club, spade` (`DHCS`). We first add a heart to the input, as the first item will have to be red in some way:
```
D . . .
```
We then toggle the suits so that we have heart as the first suit.
```
H . . .
```
We then add a diamond to complete the first two suits.
```
H D . .
```
We add then add a spade.
```
H D S .
```
And invert the suits one last time.
```
D H C .
```
Finally, we add the spade and the puzzle is complete.
```
D H C S
```
## Rules
* Input can be taken as a collection (e.g list, string) of any 4 distinct values that represent the 4 suits. E.g. `[4, 3, 2, 1]` where `1 = spades, 2 = clubs, 3 = hearts, 4 = diamonds`.
* It is guaranteed that the input is solvable. You won't need to handle any unsolvable cases.
* There will always be at least one item in the required pattern.
* Output can be given as a collection (e.g list, string) of any 3 distinct values that represent the 3 possible move types. E.g `[2, 3, 2, 1, 3, 1]` where `1 = add spade, 2 = add diamond, 3 = toggle suits`
* There may be multiple solutions of differing length. You can output either one solution or all solutions.
* Toggling twice in a row won't be part of any valid solution.
* Steps in the solution(s) need to be in the right order.
## Test Cases
Assuming `SCHD` for `S`pades, `C`lubs, `H`earts and `D`iamonds for input.
Assuming `SDT` for `S`pade, `D`iamond, `T`oggle.
Assuming only one solution returned.
```
"CHC" => ["S", "D", "S", "T"]
"DHCS" => ["D", "T", "D", "S", "T", "S"]
"SDC" => ["S", "D", "T", "S", "T"]
"HSD" => ["D", "T", "S", "D"]
"CHS" => ["S", "D", "T", "S"]
```
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the aim of the game is to use as few bytes as possible, as you never know what Lancer and Susie will do next.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 15 bytes
```
H
TDT
C
TST
TT
```
[Try it online!](https://tio.run/##DcQhEoAwEANAn3/wkpyIT3SnCAQG0en/j67Y9ez3u7uFVEDEQYK@5jhTRImGi5ALlH8 "Retina 0.8.2 – Try It Online") Doesn't output minimal solutions but link is to test suite that removes redundant leading toggles for convenience. Explanation:
```
H
TDT
```
`TDT` inserts an `H` without changing the overall toggle state.
```
C
TST
```
`TST` inserts a `C` without changing the overall toggle state.
```
TT
```
Remove consecutive toggles, as they're not allowed. (Would have saved 4 bytes if they were allowed.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ṁỊ;1ŒgƊḂKḣ-
```
[Try it online!](https://tio.run/##y0rNyan8/6hhjmdeQWmJlYKLrYGOQrCtoY6Ch62RjoKzrbG1gn9pCZpciG1xQWJy6qOGuf8f7mx8uLvL2vDopPRjXQ93NHk/3LFY9//hdqCckrU1iPz/P9pQx0DHOBYA "Jelly – Try It Online")
Works as either a function or a full program. Input format is a list of numbers, 0, 1, 2, 3 for diamonds, spades, hearts, clubs respectively. Output format is a string of `'0'` for diamonds, `'1'` for spades, and a space character `' '` for a toggle. (The TIO link contains a footer which wraps the output in double quotes, so that trailing spaces are visible.)
## Algorithm
### Mathematical algorithm for solving this puzzle
*(i.e. "ais523 has mistaken PPCG for Puzzling")*
This is a closed-form algorithm that produces an optimal solution directly in linear time, using mathematical properties of the puzzle rather than any sort of brute force. The basic observation is that we can split the suits into two groups, the "writable" suits diamonds and spades (which have numbers 0 or 1, i.e. return true from Jelly's `Ị` builtin), and the "unwritable" suits clubs and hearts (which have numbers 2 and 3, i.e. return false from Jelly's `Ị` builtin). For any two positions in the string (either the string we're trying to create or the string we're working on), it's possible to define a "writability difference" – 'same' if the two positions contain suits with the same writability, or 'different' if the two positions contain suits with different writabilities.
None of our three basic operaions change the writability difference between any two positions that already contain a card: a toggle will affect all writabilities equally and thus will not cause them to become different or cease to be different, and addition of a card won't change positions where we've already added a card. This means that whenever a card is added, it must be added in such a way that the position we're adding it to already has the correct writability difference with the other existing positions (i.e. the same writability difference as it does in the string we're aiming for), and that status will not subsequently change during the solution.
This leads to a really simple rule for determining where to put the toggle actions: performing two addition actions in a row will add two writable suits, thus the writability difference between the added suits' positions will be 'same', and placing a toggle between two addition actions will add a writable suit after an unwritable suit and thus create a writability difference of 'different'. Therefore, in any valid solution that does not contain double-toggles, toggles prior to the final card being added must appear in those, and only those, positions where the two immediately adjacent suits have a writability difference of 'different'. (After the final card, clearly a toggle is required if the final card is unwritable, but not if the final card is writable as the string will already be correct in that case.)
That immediately forces the position of every toggle action. The add-card actions are also obviously forced: a toggle action can't change a card between red and black, so to add a red card (represented with an even number), it's required to add a diamond, and to add a black card (represented with an odd number), it's required to add a spade.
Assuming that there's at least one solution, this gives a description of how to find it (and incidentally also proves that there's at most one solution that doesn't involve a double-toggle or a useless toggle at the start). In fact, there is always exactly one solution that doesn't involve a double-toggle or useless leading toggle; the above argument doesn't prove this directly but can be extended to do so.
### Expressing this algorithm in Jelly
The core of the algorithm can be expressed in Jelly by looking at the list of writabilities (`Ị`), and grouping it into blocks of consecutive equal writabilities (`Œg`). `ṁ` is then used to copy the shapes of the blocks onto the original list, which is reduced to a list of red (0) / black (1) using `Ḃ`. The resulting list can then be joined on anything other than 0 or 1 in order to add the toggles (as a toggle needs to be put anywhere there's a writability difference of 'different', i.e. the writability changes, and that happens at the gaps between the blocks); joining on spaces (`K`) is tersest as that has a single-character builtin (even though it makes the output a little hard to read, that isn't a requirement of the question).
This doesn't, however, handle the requirement to add an extra "toggle" at the end if the last suit is unwritable. The tersest way I've found to implement this requirement is to append a 1 to the list of writabilities (`;1`), which (due to how `ṁ` works) effectively adds "a copy of the first suit but writable" to the end of the list of suits we're creating, and then remove it the added suit again at the end of the program (`h-`). This is a no-op if the last suit in the desired output is writable. If, however, the last suit in the desired output is unwritable, this creates a writability difference of 'different' which will lead to an extra toggle instruction being added between the last requested suit and the added suit; and when the added suit is deleted, the toggle instruction won't be. Both cases therefore end up with the desired result, with no explicit `if` statement needed.
## Explanation
```
ṁỊ;1ŒgƊḂKḣ-
Ɗ like parentheses, surrounding the previous three builtins
Ị {for each suit}, 1 if the suit is 0 or 1, 0 if it's larger
;1 append 1
Œg group consecutive equal elements into sublists
ṁ unflatten {the input}, using the same sublists in the same places
Ḃ {for each suit}, 1 if the suit is odd, 0 if it's even
K join on spaces
ḣ- delete the last element
```
[Answer]
# [Python](https://www.python.org), 75 bytes
```
f=lambda p,t=0:p and((v:=p[-1]-t)%2and v+10*f(p[:-1],t)or 5+10*f(p,~t))or 0
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVLLasMwEKRXf4UQFKRWLnZCoBh0sg-GHuWbMUUhNg31Q9ib0F76I73kkv5T-zVdyXbShlyk3ZnZGRbp88u8w0vXHg7HHVT-4_dTJWvdrDeaGAEyiAzR7YaxfSRN7oeFD_x2gQjZ34fBXcVMHiEqgHc9WU2Q-ABu-2C0_Lk5QjkAkST3CGE0TmMqcqqoIDSxh6syWnDh-CSNlRUkI3yhctUsVcmFVXbFL1XJf7tJPvNxqq6aFNwrPK_CRbatEeWbwZvYTSIcQ-gZ9LouJVYPjX4todftgG4qRRMahIsl5aPQSRxdayjZaXSm6-0ArNEGGRCuQZRzS3c7kAP0rBqhEZmCsfobHC5XmKuSjM6Dzsqqztmnaedleky0mN2Oj681f4Rf)
The input is a list of integers, and the output is an integer where each digit read left to right represents a possible move.
For input: clubs, spades, hearts, and diamonds are 0, 1, 2 and 3 respectively.
---
If a number is not a valid output format, then the answer is 76 bytes:
```
f=lambda p,t=0:p and((v:=p[-1]-t)%2and f(p[:-1],t)+str(v)or f(p,~t)+"5")or""
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZJNasMwEIXp1qcQAwWJyiU_BIrBK3vhRXfyzpiiEJuG-kfYk9BuepFusknv1J6mIylO25CNNfremzeM7Y9P84bPfXc4HHdYhw9fj3Xc6Ha90cxIjGeRYbrbcL6PYlOE8zJEcbsgwmpuioiARHE34sD3oh8slO8EYAV0BfCZ3zdHrEZkMSsCxjgkWQKyAAWSQWofrsqhFNLpaZYoa0g9vnC5arKq9CIqv5KXqfR_3Mk-6UmmroaUIiiDoKa9tp2R1auhk9lNImoj9IR63VQxVfetfqlw0N1IaSqjEJjNF0sQ3ugsTm40VvzcOsnNdkTeakMKSnchKoSV-x3G9vXWHnlyGkzV38Hz5YrmqjSHqdFFWdfv7HO3yzIDTbTMbif815r-hB8)
---
## How it works
Here's the unminimized code:
```
def f(p,t=0):
if p:
if (v:=p[-1]-t)%2:# true if (t=0 & p=1,3) or (t=-1 & p=0,2)
return f(p[:-1],t)*10+v
else:
return f(p,~t)*10+5 # 5 is arbitrarily chosen
else:
return 0
```
It's a recursive function that works from the end of the list to the beginning. `t` is a toggle flag -- it's `-1` when the output will become either a heart or a club, and `0` when the output will be either a spade or a diamond. We append toggles until the end value and toggle bit have *different* odd-ness/even-ness, then append the associated move (spade if end value is spade/club, diamond if it's diamond/heart).
---
-1 byte from @math junkie
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
⁻⪫⪪⪫⪪SH¦TDT¦C¦TST¦TT
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3M6@0WMMrPzNPI7ggJ7MEmemZV1BaElwCVJeuoamjoOShBCJDXELAtDOEFwzhhQApTev//108nIP/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
⪪ H Split on `H`
⪫ TDT Join with `TDT`
⪪ C Split on `C`
⪫ TST Join with `TST`
⁻ TT Remove all `TT` substrings
Implicitly print
```
[Answer]
# Rust, ~~149~~ 126 bytes
```
|t:&[u8]|t.iter().rev().scan(false,|b,&k|Some(if(k<2)^*b{vec![k&5]}else{*b=!*b;vec![k&5,2]})).fold(vec![],|a,b|[b,a].concat())
```
[Verify All Test Cases](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=dafcb1be66f16762e26b32a47fc49e5b)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~70~~ 64 bytes
*-6 thanks to Arnauld*
```
f=(x,y=x.pop())=>y%2?[...f(x),y]:++y?[...f(x.map(z=>z^1)),y,4]:x
```
---
A recursive solution, which I believe also finds the optimal solution. Uses `0` through `3` for clubs, spades, hearts, and diamonds, and uses `4` for toggle, and `1` and `3` to add the respective cards.
[Try it online!](https://tio.run/##dZBBa8MgGIbv@RXywUBpZlnZqUF3iIPcdjC34IpN45aSxlDDSDr22zO1bIeyXfT99Pmew3vUH9rV53YY73t7aBZzGplj3FE3dO2IAQg96QHXjEMuCwG07Q/N9GJwTUiWeHrDNOM6QnsP7eROlFDtFaFH2/ZBkC2G4Smd2UQHO2BCGJ/vNk8VpdTgiaSz2q5W888cTRfGL68PxP@lj2o7LVmVIAR5kUOK0HqNKpA@gQhHTCWoQIgiD2MkxPX9BospslL8ZStvlYUUv9gNIa5EXkhA/4lUohJq7PlZ1@/YIcbRp9@pbe9s19DOvuHQITbhwo6Q0OqXr@wb "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ ~~16~~ 11 (or 4) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
4ƵK:5ƵU:11K
```
-5 bytes porting [*@Neil*'s Retina answer](https://codegolf.stackexchange.com/a/249883/52210), with integers as I/O
Inputs `2345` for `DSHC` respectively; outputs `123` for `TDS` respectively.
[Try it online](https://tio.run/##yy9OTMpM/f/f5NhWbyvTY1tDrQwNvf//NzIxNQYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCgZF@pw6XkmFxSmpgDF4QBoKSSS7CHs5Kpz6FljxoW2v43ObbV28r02NZQK0ND7/8wffmlJSgalextudAthKlRsjf2UQpxCVYCmqdzaJv9/2glZ6ANOkouHs7BQCrYBcTxCHYBks4ewUqxAA).
**Or 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) with [*@Neil*'s convenient input-format](https://codegolf.stackexchange.com/questions/249863/solve-a-card-suit-puzzle/249882#comment557570_249863)**: inputs as a list with `0 1 202 212` for `S D C H` respectively; outputs a string with `0 1 2` for `DST` respectively.
```
J22K
```
[Try it online](https://tio.run/##yy9OTMpM/f/fy8jI@///aEMdI0MjHSMDIx2DWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCgZF@pw6XkmFxSmpgDF4QBoGSwkkuws4dSiJGB0aFVRoZA4lHDwsPrbf97GRl5/4dpzC8tQdGpZG/LhW4jTI2SvdHhuUBTQ5SAJukc2mb/P1rJ2cNZSUfJxcM5GEgFu4A4HsEuQNLZI1gpFgA).
**Original ~~18~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:**
```
₂…)˜(ªÞæ.Δ».V)˜Q
```
Inputs `-6 -2 2 6` for `C H D S` respectively; outputs `2 6 )˜(` for `D S T` respectively.
[Try it online](https://tio.run/##yy9OTMpM/f//UVPTo4ZlmqfnaBxadXje4WV656Yc2q0XBhQI/P8/2khHQReEzXQUzGIB) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCgZF@pw6XkmFxSmpgDF4QBJftHTU3Bh9e7aBxareQS7OGsVBmcfXiF7aGV/4ESjxqWaZ6eo3Fo1eF5h5fpnZtyaLdeGFDg0LrA/7UwE/NLS1CMVLK35UJ3CkwN2Da4oUCGS3DIo4aFOoe22f@PVnIG2q6j5OLhHAykgl1AHI9gFyDp7BGsFAsA).
**Explanation:**
```
: # Replace
4 # all 4
ƵK # with 121
: # Then replace
5 # all 5
ƵU # with 131
K # Then remove
11 # all 11
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ƵK` is `121` and `ƵU` is `131`.
```
₂ # Push 26
…)˜( # Push string ")˜("
ª # Convert the 26 to [2,6], and append the string: ["2","6",")˜("]
Þ # Cycle it indefinitely: ["2","6",")˜(","2","6",")˜(","2",...]
æ # Get the powerset of this infinite list
.Δ # Find the first result which is truthy for:
» # Join the list with newline delimiter to a single string
.V # Evaluate and execute it as 05AB1E code:
# `2`: Push a 2
# `6`: Push a 6
# `)˜(`: Wrap stack into a list; flatten; negate each
)˜ # Wrap the stack into a list and flatten
Q # Check if it's equal to the (implicit) input-list
# (after which the found result is output implicitly)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
vṅ1JĠ•∷ṅṄṪ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ24bmFMUrEoOKAouKIt+G5heG5hOG5qiIsIlxcXCJwx48iLCJbMCwyLDMsMV0iXQ==)
Port of Jelly, so go upvote that.
] |
[Question]
[
This challenge was inspired by [this tweet](https://twitter.com/ChrisKlerkx/status/1408140074089435140).
## Idea
Consider a circle with `n` evenly spaced dots around the perimeter, where each dot has a postive integer value:
[](https://i.stack.imgur.com/jS5zN.png)
Now connect the dots with *non-intersecting* chords:
[](https://i.stack.imgur.com/cXEek.png)
Next consider our score, which is the sum of the products of these pairs. When `n` is odd, the extra orphan dot will not contribute to our score.
Finally we ask: Which pairing of dots gives us the highest score?
[](https://i.stack.imgur.com/ZJd3G.png)
## Task
Write a program to solve this puzzle.
### Input
A list of postive integers, in order, representing the values of the dots which are spread evenly around the circumference of a circle.
### Output
A list of pairs of the same integers, representing an optimal solution to the puzzle described above.
That is, the pairs you return must:
1. Produce non-intersecting circle chords when connected by straight lines.
2. Produce a maximal score among all possible solutions that satisfy rule 1.
The score we're maximizing is the sum of the products of the pairs, and for odd-length input does not include the unpaired number.
In some cases, such as `[1, 9, 1, 9]`, the optimal solution will voluntarily leave unpaired numbers. In this example the solution is to pair the two `9`s and leave the two `1`s as singletons.
Additional notes:
* Again, for odd-length input, the unpaired number won't contribute to your score. You may include this singleton in your output or not.
* Same goes for "voluntary" singletons such as the `[1, 9, 1, 9]` described above.
* In addition to the optimal list of pairs, you may include the optimal score value as well, but don't have to.
* If 2 or more solutions tie, you may output any one of them, or all of them.
* The order in which the optimal pairs are given doesn't matter.
## Rules
This is code golf with standard site rules. Both input and output formats are flexible. In particular, output may be:
* An array of arrays, where the inner arrays have length 2.
* An n by 2 or 2 by n matrix.
* A single flat list, so long as all the optimal pairs are adjacent.
* Anything else reasonable.
## Test Cases
I included optimal score for convenience but it's not required in the output.
```
Input: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output: [[2, 3], [4, 5], [6, 7], [8, 9]]
Score: 140
Input: [1, 2, 3, 4, 5, 6, 7, 8]
Output: [[1, 2], [3, 4], [5, 6], [7, 8]]
Score: 100
Input: [1, 4, 8, 7, 11, 2, 5, 9, 3, 6, 10]
Output: [[4, 3], [6, 10], [8, 7], [11, 9], [2, 5]]
Score: 237
Input: [12, 8, 2, 20, 16, 7]
Output: [[12, 8], [2, 7], [20, 16]]
Score: 430
Input: [29, 27, 23, 22, 14, 13, 21, 7, 26, 27]
Output: [[29, 27], [23, 22], [14, 7], [26, 27], [13, 21]]
Score: 2362
Input: [1, 9, 1, 9]
Output: [[9, 9]]
Score: 81
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~45~~ 43 bytes
```
ṖẎƤṚ+"JpẎ€¥"Ʋṭ@€"J,€¥ɗẎṭḷ
Jçƒ0RWW¤Ẏị¹ZPSƊÐṀ
```
[Try it online!](https://tio.run/##y0rNyan8///hzmkPd/UdW/Jw5yxtJa8CIPtR05pDS5WObXq4c60DkK3kpQMWOTkdKAcUe7hjO5fX4eXHJhkEhYcfWgIS3N19aGdUQPCxrsMTHu5s@P//f7SxjoKRjoKpjoKJjoKFjoJBLAA "Jelly – Try It Online")
Uses a modified `f(n)`, which is defined as sets of chords containing the vertex `n`.
---
# [Jelly](https://github.com/DennisMitchell/jelly), 45 bytes
```
ṖṚ+"JpẎ€¥"Ʋṭ@€"J,€¥ɗẎ;ṛ/{ṭḷ
Jçƒ0RWW¤Ṫị¹ZPSƊÐṀ
```
[Try it online!](https://tio.run/##TY29SsRAFEb7PMUl1QwzzGbizyaIINilWrRYMKSIkMhKWJYYZcVGLBVELBS0VYRFGxsd7bIQ8DHGF4l3xqBbzTfnfPfe/awojttWqxut7pgbTfTH5ffZc/3oNq9avWxgdiNuydctujWt7nsnaPT7mxPNn5prb2s4rB@0munPi1rtDLab8/mVVqdtmxPpUScnIXUYPh5lPSJZTgJKGZHcSMOl4T7yvuF@x4UQ1gbGhsyMow2ttctgHeI4SeyC/@ybbBED8nvTtIXoStjitrtQtlYU6UFF7FiRVTBdMLuHVSdHYyizIzI1tTId72Umbg5crOPcH5mkoxJ82saSwzKHgEOfg8SPz2GFQ8hhicMqIi/5AQ "Jelly – Try It Online")
Painfully long, but runs pretty fast.
Basic algorithm is to compute all the possible sets of chords (as indices) via memoization. Let's define `f(n)` as the list of all possible sets of chords using first `n` nodes, i.e. `1..n`. `f(0)` and `f(1)` contain a single empty set, and `f(2)` is `[[], [[1, 2]]]`. Also, let's define `f(0..n)` to be `[f(0), f(1), ..., f(n)]`. Then the following recurrence holds:
```
f(n+1) = f(n) ++
cartesian product of f(0) and (1 + f(n-1)), with [1, n+1] added to each set ++
cartesian product of f(1) and (2 + f(n-2)), with [2, n+1] added to each set ++
... ++
cartesian product of f(n-1) and (n + f(0)), with [n, n+1] added to each set
```
where `++` is list concatenation and `+` is vectorized addition.
```
ṖṚ+"JpẎ€¥"Ʋṭ@€"J,€¥ɗẎ;ṛ/{ṭḷ Aux. dyadic link: left=f(0..n), right=n+1
Ṗ H = f(0..n-1)
AAAAAAAAAAbbbbccccɗ A(H) `b` (H `c` n+1)
Ṛ+"J Reverse H and add 1..n (zipped)
pẎ€¥" Cartesian product by concatenation with H
ṭ@€" Zipped append the following to each set:
J,€¥ [1,n+1], ..., [n,n+1]
Ẏ Collect lists of sets into one list of sets
;ṛ/{ Combine with the sets without n+1
ṭḷ Push into f(0..n) to get f(0..n+1)
Jçƒ0RWW¤Ṫị¹ZPSƊÐṀ Main link: arg=a list
J Indices of the list
çƒ0RWW¤ Reduce over it using the aux link, starting from [[[]]]
Ṫị¹ Take the last result; convert the indices to actual values
ZPSƊÐṀ Find the set of chords with the highest sum of product
```
Probably I can golf it by *not* taking the right argument of the aux link (which is simply the length of the left arg), but I don't want to torture myself further...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
JŒcŒPŒcZFṢƑ<QƑƊƊ€ẠƊƇịZPSɗÐṀ
```
A monadic Link that accepts a list of integers and yields a list of all most valuable lists of chord-end pairs.
**[Try it online!](https://tio.run/##y0rNyan8/9/r6KTko5MCgGSU28Odi45NtAk8NvFY17GuR01rHu5aAGS1P9zdHRUQfHL64QkPdzb8//8/2tBIR8FCRwFIGhnoKBia6SiYxwIA "Jelly – Try It Online")** Very inefficient.
### How?
```
JŒcŒPŒcZFṢƑ<QƑƊƊ€ẠƊƇịZPSɗÐṀ - Link: list A
J - get indices -> [1,2,...,length(A)]
Œc - pairs
ŒP - powerset
Ƈ - filter keep those for which:
Ɗ - last three links as a monad:
Œc - pairs
€ - for each:
Ɗ - last three links as a monad:
Z - transpose
F - flatten
Ɗ - last three links as a monad:
Ƒ - is invariant under:
Ṣ - sort -> x
Ƒ - is invariant under:
Q - deduplicate -> y
< - (x) less than (y)?
Ạ - all?
ị - index into (A)*
ÐṀ - keep those maximal under:
ɗ - last three links as a dyad* f(entry, A):
Z - transpose (the entry)
P - product (vectorised across this transposed entry)
S - sum (of those products)
* Note: ị takes A on the right Implicitly due to the next
link in the chain (ZPSɗÐṀ) being dyadic (which
it does not need to be), this saves a byte.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 26 bytes
```
JŒcŒPŒc_€/ṠÆḊ¬Ʋ€ẠƊƇịZPSɗÐṀ
```
[Try it online!](https://tio.run/##y0rNyan8/9/r6KTko5MCgGT8o6Y1@g93Ljjc9nBH16E1xzYB@Q93LTjWdaz94e7uqIDgk9MPT3i4s@H////RhjoKljoKxjoKhgY6CkaxAA "Jelly – Try It Online")
-1 byte thanks to @caird.
Independently arrived at something very similar to [Jonathan Allan's solution](https://codegolf.stackexchange.com/a/231247/78410).
The only difference is `_€/ṠÆḊ¬Ʋ` part, which tests if two pairs of indices are two non-intersecting chords.
Because of how `ŒP` (powerset) and `Œc` (unordered pairs) generate the results, it is sufficient to filter out the pairs of pairs which have the element-wise ordering of `[[1, 3], [2, 4]]`, `[[1, 2], [1, 3]]`, `[[1, 2], [2, 3]]`, or `[[1, 3], [2, 3]]`. The pairs `[[1, 2], [3, 4]]` and `[[1, 4], [2, 3]]` should be kept intact. [Test this condition.](https://tio.run/##y0rNyan8/98k6OikZCB6uLMl/lHTGv2HOxccbnu4o@vQmmObjrX//w8A)
```
_€/ṠÆḊ¬Ʋ Given a 2x2 matrix of values, test if they're valid chords
_€/Ṡ Sign of cartesian pair-wise difference
ÆḊ Determinant
¬ 1 if zero, 0 otherwise
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~114~~ ~~98~~ ~~88~~ 86 bytes
```
f@r_:=SortBy[f@Drop[r,#]~Append~r[[#]]&/@Subsets[j=0;++j&/@r,{2}],Dot@@-#&]~Last~{}
```
[Try it online!](https://tio.run/##bYu9TsMwFIX3voalLD0V8U3a0KIigzoyVAqbZSFTEjUV@ZHjDiiKV0YelUcIN7AyXJ2j77untv5c1NZXJztNpXIvu33eOv/4oUt1cG2nHYQJD11XNG/BaS2MiW5Ufn3tC9/ryz6@Wy4vTBwGGg0OrVdqJb6/PiMTnmzvwzBOR1c1XovVfakEju/XXqnnqi44FBMThfxkmzAsBokt@EbMlZAgxRobZLj9F/6hlG0GObs17xN2Mv5VxIZAMSS/z4S2oAyUgAgyheQieUsbxuNinH4A "Wolfram Language (Mathematica) – Try It Online")
```
j=0;++j&/@r range over input
Subsets[ % ,{2}] get pairs
f@Drop[r,#] recurse on values not between indices
~Append~r[[#]] and append chord
/@ % for each pair
SortBy[ % ,Dot@@-#&]~Last~ get the set of chords with the highest sum of products,
{} if there are no chord sets (i.e. len(r)<2), return an empty set
```
Since `-` has lower precedence than `` (`Transpose`), `Dot@@-#&` is interpreted as `Dot@@(-(#))&`, which turns out to be equivalent to `Dot@@(#)&` since the negatives cancel out.
Here's a walkthrough for when `f` is called on `{1,8,2,9}`:
```
r = {1, 8, 2, 9}
j=0;++j&/@r = {1, 2, 3, 4}
Subsets[ % ,{2}] = {1,2} {1,3} {1,4} {2,3} {2,4} {3,4}
map:
Drop[r,#] = { 2 9} { 9} { } {1 9} {1 } {1 8 }
r[[#]] = {1 8 } {1 2 } {1 9} { 8 2 } { 8 9} { 2 9}
Append[f@ %2 , = {{2,9} { { {{1,9} { {{1,8}
% ] = {1,8}} {1,2}} {1,9}} {8,2}} {8,9}} {2,9}}
sorting function:
Dot@@-# = 26 2 9 25 72 26
SortBy[ ... ]~Last~{} = {{8,9}}
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~[135](https://tio.run/##RYxNCsIwEIWvMsuJzcK0oljoSYZZRNposE1LrDA5fUx04eKDx/vb0v5YQ5ezG2a73EYL0gvYMMJiBcmhkOlZcUNEQkfWQp6Zm1/gWX2Vb2rJrRE8@ADRhvuERs9TQFGK9XNK//vXe8FUrg6JDNdNqpvSWyNx3qIPOzqk9qqhvRS6QqvBnApVGw3VPteYlcof)~~ 117 bytes
```
f=lambda x:x and max([[[x[0],v]][:i]+f(x[1:i])+f(x[i+1:])for i,v in enumerate(x)],key=lambda y:sum(a*b for a,b in y))
```
-18 thanks to @ovs and @dingledooper
thanks to @EliteDaMyth for earlier correction
[Try it online!](https://tio.run/##dZDBbsIwDIbvfQofG/ChCYyNSDxJ5EMqUq3aGlAbUNqX7@wA22kX64//z47t65w@L3G3rt3p2w/t2UO2GXw8w@Bz7ZzLriG8Eznb07ars9MsVFH9VltS3WWEHu/QRwjxNoTRp1BnRfgV5lfP2U63ofabFoT22Ao9K7WmMKXp5JxGMAg7hD3CG8IB4R3hA@FIWP1jPp194TihHxgDxwIzppsCmYJwNA3npFzShjHDdYZZw6bmTlq0Lu3MQeznJ4xKJKpk/izTl8ltBXAd@5h44V/Jp1F/L1l84RtuFqdJqhepLoyq1h8 "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes
```
JŒcŒPFQƑ$ƇŒcZFṢƑƊƇƊÐḟị¹P€S$ÐṀ
```
[Try it online!](https://tio.run/##y0rNyan8/9/r6KTko5MC3AKPTVQ51g7kRLk93Lno2MRjXcfaj3UdnvBwx/yHu7sP7Qx41LQmWAXI39nw////aEMjHQULHQUgaWSgo2BopqNgHgsA "Jelly – Try It Online")
This is a total mess, extremely inefficient, possibly not working correctly and probably very outgolfable.
*-2 bytes thanks to caird*
] |
[Question]
[
What tips do you have for golfing in Applescript? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Applescript (e.g. "remove comments" is not an answer).
[Answer]
The `of` operator is used to get a property from an object:
```
log words of "Hello World"
```
But in many cases you can use `'s` as a shortcut to save 1 character:
```
log "Hello World"'s words
```
[Answer]
Some words have shorter synonyms. For example, `application` can be written as `app`\*, and `string` can be written as `text`.
Also, `every <noun>` can be written as simply the plural, as in `characters of "hello world"` (or `"foo"'s characters`).
\*Although Script Editor's compiler will change it back.
[Answer]
The Applescript Editor is a handy little IDE which syntax-highlights and beautifies your code. However, for the purposes of golfing, it is counterproductive as it adds indentation and superfluous keywords, e.g. after `end` statements. For example:
```
repeat with w in "Hello World"'s words
log w
end
```
becomes the following when pasted into the Applescript Editor and compiled/run:
```
repeat with w in "Hello World"'s words
log w
end repeat
```
Obviously the first snippet is better for the purposes of golfing.
[Answer]
`tell` blocks are common in Applescript:
```
tell application "TextEdit"
activate
end tell
```
However to save space the following is equivalent, when the inside of the `tell` block is just one line:
```
tell application "TextEdit" to activate
```
[Answer]
### Quotation Required Operation
For any operation that requires a quote to do something, i.e.
```
log "Hello World!"
```
You can shorten to
```
log"Hello World!"
```
### Repeating
In repeat loops, one can entirely remove the word "times".
```
repeat x times
end
```
versus
```
repeat x
end
```
### <= and >=
Any time these operators are called, you can replace them with `≤` and `≥`, respectively. While this may not reduce byte count (unless special byte counting conventions are implemented, which I suggest), it *does* reduce character count.
### Grabbing from STDIN
You can grab from STDIN in with the following characters:
```
on run argv
end
```
### Exiting quickly
If you need to exit a code quickly (for whatever reason, i.e. preventing excessive `if`s)...
```
quit
```
[Answer]
Applescript allows some extra keywords to be inserted to help readability:
```
log the words of "Hello World"
```
But the `the` here is completely superfluous and may be omitted for a 4 character saving:
```
log words of "Hello World"
```
[Answer]
### Bracket Shortening
Similar to the post about quotations, I realized later that you can also shorten things like this:
```
if "a"=character 1 of (x as string) then return {true, true}
```
to
```
if"a"=character 1 of(x as string)then return{true,true}
```
It'll space out brackets for you too. In this example, I save 5 bytes.
[Answer]
## Considering...
In questions that require case sensitivity, it can be difficult to actually deal with cases.
### UNTIL NOW:
```
considering case
(something to do with case sensitive stuff)
end considering
```
I didn't actually know this keyword until I really needed it. Using the other tips in this tips page, we can reduce this down to:
```
considering case
(something to do with case sensitive stuff)
end
```
It does require a full statement, as far as I know. (I've tried a lot of things.) See [this page](https://developer.apple.com/library/mac/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_control_statements.html) for more details.
[Answer]
In a few exceptional cases, the «double angle brackets» or «double chevrons» might be shorter than the English name of a command, parameter, or constant.
The chevron-encoded form would shrink the AppleScript to [delete the clipboard](https://codegolf.stackexchange.com/a/111411/4065) from 20 to 16 characters:
```
set the clipboard to -- 20
«event JonspClp» -- 16
```
It would drop 2 characters when fetching text from a dialog (as happens in [metronome](https://codegolf.stackexchange.com/a/77732/4065) and [Pi Day](https://codegolf.stackexchange.com/a/75504/4065)):
```
(display dialog""default answer"")'s text returned -- 46
(display dialog""default answer"")'s«class ttxt» -- 44
```
(You might prefer to avoid the dialog and use the command-line arguments of [osascript(1)](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/osascript.1.html), if you have at least Mac OS X 10.4.)
With a US keyboard, « is option-\ and » is option-shift-\. A command `«event abcdefgh»` has 16 characters. A parameter or constant `«class abcd»` has 12 characters.
The chevron-encoded form is almost always too long for golf. Here is an example without double angle brackets:
```
set x to open for access"output"write permission 1
write"One line of text
"to x
close access x
```
And the same with them:
```
set x to«event rdwropen»"output"given«class perm»:1
«event rdwrwrit»"One line of text
"given«class refn»:x
«event rdwrclos»x
```
Changing `_open for access` (16) to `«event rdwropen»` (16) was neutral. Changing `write permission_` (17) to `given«class perm»:` (18) cost 1 character. The other double angle brackets cost more.
To use double angle brackets, you need to know the magic 4-letter or 8-letter code. I found some codes by saving a script file from Script Editor, then opening it in a hex editor. I ran `emacs` in a terminal and used `M-x hexl-find-file`. I found and edited some codes, like `JonspClp` into `JanspClp`, and `ttxt` into `atxt`. I then saved the file and reopened it in Script Editor. `«event JanspClp»` and `«class atxt»` appeared in the script.
A document titled *AppleScript Terminology and Apple Event Codes Reference* lists some codes. I found a copy of it at <https://applescriptlibrary.wordpress.com/>
Script Editor will translate double angle brackets to English before saving your script. For chevron deference, you must write your script in another text editor, like TextEdit. Save the script as a plain text file in the Mac OS Roman (or MacRoman) encoding. Mac OS X prefers that you name the file with an .applescript suffix.
If you count bytes, MacRoman has 1 byte per character, so each « or » counts as 1 byte.
] |
[Question]
[
We all know scoring by characters is ripe for abuse. Let's prove this.
## The Challenge
Output the following:
```
"m8V}G=D@7G1lAI,v08`
#(hNb0A8T!g;==SVaG5~
g"jUF!bmRY(3I@na?2S{
fJVzo/GQYU%ybpfUq3aG
Yza[jc,WJ$bP^7r};Da}
V-!Z+Nk:`/poc}d/X:G\
sWX{dbAUv6,i]%RG$hRp
),bd+?/{U1tU[;<;u.Nk
ZFPIOzJ/HimL!nexc,ls
HM%k3D$n2|R,8L?'eI_n
qs.kzbil$UQy_#Z)l#i%
*G4gr2<R^y#/iQ9,<+p%
}BYnb3_&:!m;#~QL1C?t
f.U>wIkTz=P>bf!uwb!d
z()rG)>~:q4#\}~pQEvZ
=OT8T4<i50%/8%eX^"3E
#Ks(8}OzZ&]RQ(-BLy<7
p7B~GEsF$)>?a"dtGCC'
H;:n&p&Z($ukNd,Et.$O
F*Uq0$dm,m%ejPT~u,qL
```
The characters inside the box are selected uniformly at random between the codepoints `0x21` and `0x7e`. This means they should not be compressable much ordinarily. However, in this challenge, your code is scored by the number of *characters*, which can range in codepoint between `0x00` and `0x10ffff`. Since this gives about 21 bits of information per character, and the box contains about 7 bits of information per character, approaching a 3:1 packing should be possible.
Note that:
* As usual, you may output to STDOUT or return the string from a function;
* A trailing newline on the last line is optional. Apart from this, the output must be exactly as given.
* List representations are acceptable if returning from a function.
## Scoring
The score is the length of your code in *characters*, expressed in the encoding of your language's interpreter. For most languages, this will be UTF-8. Note that languages that use an [SBCS](https://en.wikipedia.org/wiki/SBCS), such as most golfing languages, are at a huge disadvantage here as the number of characters is equal to the number of bytes.
Note that characters are not the same as grapheme clusters. For example, 👨🦲 is actually 3 characters (`0x1f468 0x200d 0x1f9b2`).
[Answer]
# Python 3, ~~223~~ ~~221~~ ~~216~~ ~~214~~ 212 chars
```
ጸ=0
for 𢫌 in"ጸ𢑡𢫌𧡰𤛧ꛯ𫁫𩔞𪝿𱰬𱪾🂳𫷓𤌚𱶼裶":ጸ=ጸ<<20|ord(𢫌)
while ጸ:print(end=chr(ጸ%128));ጸ>>=7
```
Converts from base 2²⁰ (1048576) to base 128. Just for fun, I used some of the letters from the encoded string as variable names.
---
**Edit 1**: (221) I saved two characters by using base 128 rather than base 127, allowing me to use the bit-shift operation `>>=7` rather than the integer division `//=127`.
**Edit 2**: (216) Thanks to ovs in the comments for suggesting a way to save a whopping five characters.
**Edit 3**: (214) Using base 2²⁰ allows us to save another two characters, because we can write the constant as `2**20` in the code, which only takes five characters to write rather than seven.
**Edit 4**: (212) We can write `ጸ<<20|ord(𢫌)` instead of `ጸ*2**20+ord(𢫌)`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 150 chars
```
⍘↨E¶𥏀𘫺𪦥𢌘涿𪽓𧮁燁𫜫⪆΅𬓬𤼔𖫐㓬𡻭🔹𤲽𧢮𧢖萾℅ι×φφ⁺γ¶
```
[Try it online!](https://tio.run/##DdHZjppgFADgZ53MTS@aNOkTAMoyEVxAVBY3EKUgLlCZQX8hmd7PPENt0vaq/c85D2D7vcL3@OHh8@Onh4/3@82Y3JT4L4teS3IPDMeiDPK2gqhvc6czpZ6rw8V1SH564lFPoMFsjnLOOLMZidaBT9IzT9YRpTuV/LoFrfWU5osZjRofa39AWbwg1TnTKvLxWW6TUxUoh22wRAX3bZWio0qFbUC0iqBcOMC0hsJFi7Os4IE@4bmZw6y0sZ8f@MipfpYNmP6JJ1cLwskRhY6EUsDQVRN8Fhq87ERKwiEkWcI3OxGvhf1LFWG9ZlBVJ9BLj5eDEVyMGDaNBqnQ5amfwtK0b4kCrYPIT3GPpOkRgySD9Mq@NztYvnRoJZ3Q87tQqwvIDca9xOFba0ttVcDYzbD0LChriyaDDrwsBnD@mpJmRjQddkkZ5xArOa9rna/YELojmY/SPmmhSEYz4Lah0jJYghur1HK6P6wtil9WkPW2f6Q@ttsRjadfsRcPoXQ1EpQTX14yyKs9esIcZ50zdM0tnw//r2kzvsqvaJwy7JgKxZ6OL/MCwsCniWLSrGJ8v@mAJhb0tKxBswM8ShJesgP39hlNnysMWQtzdsbgOqTYqPgmGP3u17DT9Vtbfqu@jd@Vd@Umnt@K1/J@/wc "Charcoal – Try It Online") No verbose version (but see encoder below); the succinct code that the deverbosifier generates doesn't work and is suboptimal anyway. Note that Charcoal actually defaults to Unicode, so this is the only case where I don't really mean `charcoal -e` (to use SBCS encoding). Explanation:
```
... Long string (including leading newline)
E Map over characters
ι Current character
℅ Take the ordinal
φφ Predefined variable 1,000
× Multiply (i.e. 1,000,000)
↨ Decode array using that base
γ Printable ASCII
⁺ Concatenated with
¶ Literal newline
⍘ Encode integer using custom base
Implicitly print
```
The encoded string was generated using the following program:
```
WS⊞υιUT⭆↨⍘⪫υ¶⁺γ¶×φφ℅ι
```
[Try it online!](https://tio.run/##LY5rU6JQAIa/n18hAnaok3hrZcVLaUq4pmhgamaBIJ64iFxsxcW/7tpuX96ZZ@Z5Zt7lWvWXG9U@nT7X2DZSUHS9KHwKfeyakGFSUhSsYYRSmOGBvDFN25B97MAzSWclhP/NR9WDTTUw/s133N1g96tMz900g1KSHQXQ/MYzy9gxArhCqdUXtc431GVo@BAzDMOfTmmHGydC7f62LOTtOxHtctw7IOG6r@XuOJkw@VrtaawKN0dgpj@UDqE5oyksireu2ig8HcCqO443rDCcKvRe81bKtqgKYBqrLx9L9NylNGlR9hP@Xk3A@JqYXfWtyjvrbZaJzk4qwhwEz5ODrt0pux8Iv9IjgVqPPMAgTb9qsAclHyovfJWPsn0LzDqSOIi77AN2eoRr/F4iOwAPj7RVvKfcwp8R4nqNC0N8c8E2yFqxhm1KGe7fyBljk5gGl0LJ9AvV0WJPsnj4E1WvPBokzamrFd8yFcLhyeOwl281QrDKKvVP0ZLjmlTXVkT0qRE6iCHjC0z9WNmWyHly9Ibt3QzUBjInl6r4JkezHG1MFuliG5C/Asglg3iWeR0N4XWzt6@WgVduHoV20KGYekNN66HQal2AB77iZrzMDFKR1ddRO8xSA9C5VLY5SneQQxsfknyM0LYHTtc7@y8 "Charcoal – Try It Online") Link is to verbose version of code. I was somewhat lucky that the encoded string uses no Charcoal characters (which would need quoting) and contains no unprintables (not counting newline as an unprintable).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 152 chars
Converts between base 94 and base 1125000. The highest byte in the program is `0x10cd84`.
```
"읋𦩪𡋏𪲛𥎳𫘈𘝓쵩䉸蠠🗕𡀕殓𡔀綳𗵒𧣍𨿖"Ç•HтÄ•β94в33+ç20ôJ»
```
[Try it online!](https://tio.run/##Dc@9ktJgFIDh0vvY1sZxbbwDx7vQGQsri70ByCZADJAlkCUsS35YAkl2v0B@gBCyZEZ6R2/BcdRii3POlx63epuneb9cfPj4@dPpdPaCDq7L25mAPTnGwnGxzFVy/B1f7KVKUFdgZDZXmwUFvkmeMkJ/blMoWU8ThYtBBlYaVnK7wYdBUjWf6aqfoSGxqr0RuatEEJYSv6xFJG5iLLcM5n5AgduArWCTywpwFBWCeIyzdIWpIIPetMDtJsSuErg3WmBM@njr3@J0uKVemZMs7/g0csDcWrB@YJjkS1SLBXUGczIMg6f6BLWsgU5xg0Uh4qMWY8ePUPDY09qnzqXEZXZHnqyjXL8h1h6j7Uswuosr0TZpYYmQewzCaEizuMHHLOP7XovPHkvcJQ/YZCFKSpdvjZDEa/23nPHG6PDPtsEa6jhRYnBqOh16Lm@YbbSXl7z2PFNvbf6Efb5NQ4pHAfYUE0NtRJ1NguKgTrmTUHkzB2dQIxbOcTDb8aWqYHcq0irRKykckxbtQUunfPcw4YX8SF4yRS2XeVFfo/6VcV1QIdfXfzcJDNcarVcS3kYZlVYKi7sO7@ommIt7SK@uaePVwCuv8dDaV9JoeXZs/qpN3/0UjuJzv8dv3/yIz89fHhevXx3T99/2p9N/ "05AB1E – Try It Online") For some reason I can't create a working TIO link for this, you will have to paste the code manually.
**Commented**:
```
"..." # long string
Ç # convert to code points
•HтÄ•β # convert from base 1125000
94в # convert to base 94
33+ # add 33 to each digit
ç # convert from code points
20ô # split into groups of 20
J # join each group into a string
» # join the groups by newlines
```
The *long string* is generated with [this program](https://tio.run/##HVJtT5JhFP7Or3hmba0UQtBIp1amlbamm7pAJ6WOpi1KSwOttocnBaylTTSnKROe1JwEgrw88rqdC/zQh3v4F@4/Qrdt59M517nOda5z3rwbG59y1GpcDnciyRJsnQoURnSQywFSWVrHUtU8EihRHDJFh7FPMXg6uD84qb9PEa54KDyK6GuWQ5aKLDk08wAydu2OpxTtwOo9rnzm8sl52sDl7bIPPtdtSlHeRSrFrOwMq4j1zFzl/i9cWXR8xCZ8kqDGMjIs4EL8PG3jyhK2uuqncdCvnxA1J1cU/GHpWQpXNcpjBfssNYcSonRwHVEEOw0zlTUWoFMDnXA51NlX9li54n0oZAw84vLZY8oy1Xl34BodNzPN@BLxK@cpUgewY7MLHGW74WGnQhLlcAT/whQ2XFTownKlSL/by14uB3vpFzRkKhqVTCxnNaPUhiL3f5t4hiVSdSx3ofDFMHYFa5vYm/0coSiORGqIy9nuSoiluvUUaqFQex88KBoQ5/KBvQ/Hl/M1900UsCp1Yo8l7DbI9npHnTjHyfQIgggvsCTOWKZSEF6UPTdwzAIszlI2puIHVyIXShMKFBLyWxFiRxaWc@usrR8sE4PIYP09aZQSikSMWi6NjrM0ihTl8tbfNfiGEMP3svcTRbAiDjIPlTLwIk9JbIqWqgY/VOG/EYfYIa1frIz0LJd33yLygst7@IosUpd0ey@xUdWc8DJNlJ@zALYRvCWerNFkqSZ0OrNZL7U0sYTUU01IdU/G3FPOOac0Pj/raJWM7ro7w5OvGiQcSr3tkniJHgFsaRJIs7n@f1YyGZGUKNdQqzU2mpqNRuM/). Note that this won't work for every base since some numbers like `0xdc00` can't be converted to a character.
[Answer]
# JavaScript (ES6), ~~259~~ ~~253~~ 250 chars
```
f=
_=>"𦗡𥐆៘𤲼⋷㆐𪄄𨙔⇸𢹺𫰗຺⋄⡊ᙫᷢ𠴴ᰃἙ선𩞈ᴱ𠲬ꦁ蘀Ȥ𬾗𩥇𡉅ȫ𫚟Ὃ㵽熀ᗜ𭑸𡊺嶼ࢥ魱ʼ𒾔𠳟ᅵ鍅Ⴅ".replace(/./gu,c=>String.fromCharCode((n=c.codePointAt())%95+32,n/95%95+32,n/9025+32)).replace(/ /g,"\n")
;document.write(`<xmp>${f()}</xmp>`);
```
Explanation: Simply encodes three ASCII characters using one Unicode character. Edit: Saved 4 bytes thanks to @Arnauld. Saved 2 bytes by dividing by 9025 instead of by 95 twice. Saved 3 bytes by subtracting 32 in the encoder:
```
f=s=>s.replace(/\n/g, " ").replace(/.../g, c=>String.fromCodePoint(c.charCodeAt()-32+(c[1].charCodeAt()-32)*95+(c[2].charCodeAt()-32)*95*95));
o.textContent=f(i.value);
```
```
<textarea rows=20 cols=20 id=i oninput=o.textContent=f(this.value);>
"m8V}G=D@7G1lAI,v08`
#(hNb0A8T!g;==SVaG5~
g"jUF!bmRY(3I@na?2S{
fJVzo/GQYU%ybpfUq3aG
Yza[jc,WJ$bP^7r};Da}
V-!Z+Nk:`/poc}d/X:G\
sWX{dbAUv6,i]%RG$hRp
),bd+?/{U1tU[;<;u.Nk
ZFPIOzJ/HimL!nexc,ls
HM%k3D$n2|R,8L?'eI_n
qs.kzbil$UQy_#Z)l#i%
*G4gr2<R^y#/iQ9,<+p%
}BYnb3_&:!m;#~QL1C?t
f.U>wIkTz=P>bf!uwb!d
z()rG)>~:q4#\}~pQEvZ
=OT8T4<i50%/8%eX^"3E
#Ks(8}OzZ&]RQ(-BLy<7
p7B~GEsF$)>?a"dtGCC'
H;:n&p&Z($ukNd,Et.$O
F*Uq0$dm,m%ejPT~u,qL
</textarea><pre id=o></pre>
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~210~~ 200 bytes
```
_->0:19 .|>i->join(Int(c)÷95^i%95+' ' for i=0:2,c="𦗡𥐆膛㚥愹𢹺𫰗鳑𡱛𦭗𢂿선𩞈謈츀𫚟㰖𭼽𭑸𡊺嶼瞑廀𒾔𠳟")[20i.+(1:20)]
```
[Try it online!](https://tio.run/##NdLJUlpZAMbx/X0KRr1EZHBoEQXjiNi2AxHjFA2I6FW8IqJGDJYjgyKgiAg4QTkhAiqoIIOLPEoq3emqVNc5hwewk67q3bf4737f@KyGUPA/vaopIsrrULGYJ@RXUjifxUSxeHyKIHEpqceHWV@eKssHCWZleVEhpZCintJRCBFPWMIeFtHA43UEHphOoXnfCy48Aeg3J8C50/Td5IeXK1FoNbm@@s7hcjAEk1vLIGZz/Lmegns5PwrbbGA3G4Dmo2u48WDLW2988Cm3C4KpZ5iLOfLr9hA6NCVB@NYDc6dxtBZIgMPl@N/xHWSNOfP2RBA515Lg6DkBvOe7IL16hG6vAnn7iRWmb7fRhtkBM@EEcq14US4aRAGLC0Zdm@g4FgbumzDyeOwgcOcHFxEPWnM8g4zVB89vHqB74wleBfZBcPUFhT02FE55kTt8i5Ih14/1U@i4y4DQsQX4Lx/hhnsL@jNbKOFaRecXThT0BmAimUW25BNwb@2i0/Q93N8Mose9FxhNXH2/scDItQdkc6EfyWWY8yZA2HcCUocukN2Jwah1H24HjtGhbQeuuT3owu6FKy9PaNeyh9J7z19v94Ereg89D8d5R8IKIpls3u46g5GHF7QSt8J4eBVEdpIglrOAwOYzOrAmvz1m/jreAa6zZRiKbv5zfgEjlgzc2s6ClzsHSASP4YE5DN3XB3DVlfqWXoaelAc4HZcglTajW/8B2M3toUu7DxyuPILT@AncS/hRPGJC7rQThbJ2dBa6zjvdPnR/50POmI3G6i/hEZwinC8s4bE@vM6N6Ihfx9Ip5mk0GkabFHQbJaKGtxUSvqZWyp7jCT5idHysTcmrFXRRR6tEonfdCkn5EjZKG5c3UZWTsl68VPqWVNSUvFvE1C3dhimupLNXzlxQatXy6VKFBOs1KPrHh9nvWxjKjsEKnbGqQWHEuoupfUVtE8KPXO3UsFHF7RFKBrCZ9z2LKmWtfO43NvGBKZMwxmRajMVWqopquItyvl7eX1VdNctpm8D6mjqk7YYWbjMx2UolRz4NszUzWPMfzInSBgZZ8lnGFrTWFI5Ih0hseoYzYVASGoa8c2GI3sfS0Akm9kZSNqorqZYNLtC5RGclu7pIy8SMdb2ksnSoQEidrKIvdbby62v0mJojF89LJ7oMog6xUk2dnVdSVZgBZ@kkLPGScLqMPmBc0nY2zvVhovYuQVdZNVHOY3IFzJGeQVppI0b/fQYXGNsNfQUfZJ14cV3rQnUFpq2oW5I0zjQxWOIaBU2ll9TXF2LNVUKyQFvQhzNmJ9pU7EY9h9GONb2RT/MYqkn2JHNkvKNraZY93fqLCWv6SabGySn9GEGOsjBMqyNIvYbk4E2s/zf@sxFRZrQaQo//p8ym0AZIGov1@i8 "Julia 1.0 – Try It Online")
output is a list of strings
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 130 chars
```
`"疘暹ᠶ𰮙脭ﭮ𰵭蹝ੇ𬍛㈭𧘵첃𮃲`Ck4β94τ33+C∑²
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=%60%22%F1%96%98%8E%F3%89%9F%87%F3%92%B0%87%E7%96%98%F1%BF%9B%A4%F2%8D%83%A6%F0%9A%AA%9B%F3%A1%A8%85%F2%97%AD%87%F2%A5%99%B7%F0%9B%B3%9E%F3%AF%90%99%F3%83%AB%85%E6%9A%B9%F2%98%82%B4%F1%A9%91%A9%F1%98%94%BC%F3%88%80%92%F1%AC%B7%BF%E1%A0%B6%F1%B1%BD%91%F3%AB%A6%A0%F2%9E%9D%A3%F3%8C%B8%AA%F1%BF%9B%81%F3%A1%A5%AF%F1%82%8B%8B%F3%A1%8C%85%F2%B2%AF%9B%F1%B7%9A%97%F3%87%84%BB%F2%B1%8A%8F%F1%B3%A3%AC%F0%B0%AE%99%F2%BD%B2%8A%F1%8C%B4%AF%E8%84%AD%F1%B8%B5%B5%F3%9B%BF%92%F1%9B%BD%99%F0%9B%B4%AD%F2%BB%80%89%F3%A6%8F%9C%F2%AB%A6%9D%F2%97%BC%A8%F0%BF%B9%80%F2%B5%94%BE%F3%B1%84%A9%F2%8E%BA%BC%EF%AD%AE%F2%81%BB%9B%F2%A6%AA%B5%F2%B5%81%87%F1%AC%91%AC%F0%9B%B7%82%F3%86%AF%96%F2%81%9C%A3%F0%B0%B5%AD%F1%8C%85%95%F1%AC%8C%9C%F2%9D%A3%BA%F1%B6%9E%9C%F3%87%9B%B7%F1%89%9B%8D%F3%96%AD%BA%F1%96%93%BE%F1%81%AC%94%F1%AD%86%A4%F2%88%BA%A2%E8%B9%9D%F3%A9%BE%B6%F3%9C%9E%B2%F3%80%9E%86%F1%AA%9F%B4%F2%AD%99%9A%F0%9C%90%A7%F1%A7%A5%89%F2%8F%B5%93%F2%AA%A0%B2%F2%A9%91%9F%F2%A7%94%A3%F1%94%AA%A7%F2%90%A0%92%F2%A8%A9%BF%F3%98%AD%82%F3%A8%8A%85%F3%95%B9%B9%F3%8B%9A%88%F3%97%99%A7%F1%87%8A%A6%F0%91%95%9B%F3%80%A0%89%F0%93%AD%8D%E0%A9%87%F1%A5%A2%B4%F2%B0%BE%B7%F0%B8%B4%95%F3%96%86%96%F3%AB%BE%86%F2%81%AF%9E%F2%96%AA%85%F1%80%90%B0%F0%AC%8D%9B%E3%88%AD%F2%83%89%83%F1%9D%92%93%F2%90%99%B7%F2%A8%96%B4%F0%A7%98%B5%F1%91%8D%8F%F2%B1%B1%AE%F0%BD%BF%84%F1%9B%85%B9%EC%B2%83%F2%BE%BF%A5%F2%BB%9A%B3%F0%AE%83%B2%F2%BD%9E%97%F1%BC%99%84%F1%A5%BA%AE%F2%83%B6%9E%F2%BC%8E%8D%F2%8D%98%B0%F1%AD%94%BD%F2%B6%B8%8D%F1%9E%9F%A3%F0%94%9B%8E%F2%BA%9E%97%F2%A6%94%99%F1%A7%B0%A9%F1%AC%B4%87%60Ck4%CE%B294%CF%8433%2BC%E2%88%91%C2%B2&inputs=123&header=&footer=)
At least I think it's 130 chars - I had to count by hand...
[Answer]
# Deadfish~, 4347 bytes
```
{i}{i}{i}iiiic{{i}ddd}iiiiic{{d}iiiii}dddc{i}{i}{i}c{{i}dddddd}dc{{d}iiiii}ddddc{d}c{i}dddcddddc{d}ic{i}iiiiiic{d}{d}ddc{{i}dddd}dc{{d}iiiiii}dddc{i}ddc{d}{d}{d}ic{{i}ddd}iiiic{{d}iii}c{i}ddc{{i}dddddd}c{{d}ii}ddddddc{i}{i}iiiiiciiiiic{{i}dddd}iiiic{d}{d}ddddddc{i}{i}c{{d}iiiii}c{i}{i}dddc{d}ic{i}{i}{i}ddc{{d}iiiii}dc{{i}ddd}c{{d}iiiiii}ddddciicc{i}{i}iiciiic{i}ic{d}{d}ddddddc{d}{d}iic{{i}ddd}iiic{{d}}{d}ddddddc{{i}d}iiic{{d}iii}ic{{i}ddd}iic{d}{d}dc{d}dddddc{{d}iiiiii}iiic{{i}dddd}iiiiic{i}ic{d}{d}{d}iiic{i}dddc{{d}iiiii}ic{i}ic{i}{i}iic{d}ic{{i}dddddd}iiiiiic{d}dddc{d}{d}{d}ddddc{d}dddc{i}{i}{i}iiic{{i}dddddd}c{{d}}{d}dddc{{i}d}iic{d}{d}{d}iic{i}iic{i}{i}{i}iiiiiic{d}dc{{d}iiii}ddddc{i}{i}iiiic{i}c{i}ddcddddc{{d}iiiii}iic{{i}dd}iiiic{d}{d}dddc{i}iiiic{d}c{d}{d}iiic{i}{i}{i}ddc{{d}iiii}ddc{{i}dddddd}iiiiiic{d}{d}ddddddc{{d}iiii}dc{{i}dd}dc{i}{i}{i}iiic{d}{d}dddddcddddddc{i}iiiiic{d}iiic{{d}iiiii}dddddc{{i}dddddd}iiic{d}dddc{{d}iiiiii}iic{{i}dddd}iic{d}{d}iic{i}iiiic{{d}iiiiii}ic{{i}dddd}dc{i}ic{{d}iiii}ddddddc{i}dc{i}{i}{i}dc{i}{i}{i}ddc{{d}}{d}dddddc{{i}ddd}iiiiiic{{d}iiiiii}dc{d}ddc{{i}dddd}dddc{{d}iiiii}iiic{i}{i}{i}iiiiic{i}{i}{i}dc{{d}iiiii}ic{{i}dddddd}ddc{{d}iiiii}ic{{i}dddd}iiiiicdc{d}ddc{i}{i}iiiiiic{d}{d}dddddc{{d}iiiii}dddc{{i}dddddd}ic{d}{d}{d}c{i}iiic{i}{i}ic{{d}ii}ddc{{i}}iiiiic{d}{d}{d}iicic{i}{i}{i}iiiiic{d}{d}dddcddc{d}{d}{d}dddc{i}{i}c{i}{i}{i}iiic{{d}iiii}ddddc{d}c{{i}dddd}ic{d}ddc{{d}iiiii}ddddddc{{i}dddddd}iiiiic{d}dc{d}{d}{d}dddddc{{i}ddd}ddc{d}{d}ddc{i}{i}{i}c{{d}}ddc{i}{i}{i}iciiic{{i}ddddd}iiiiciic{{d}iiii}iiic{i}{i}c{d}ddddddc{{i}ddd}iiiiiic{{d}iiiiii}iic{d}{d}{d}ddddddc{{i}ddd}dddc{d}{d}{d}dciiiiiic{d}{d}{d}ddcicdc{{i}dddd}ddc{{d}iii}dc{i}{i}{i}iic{i}{i}{i}dc{{d}}iiic{{i}dd}c{d}{d}c{i}c{d}iiiciiiiiic{{i}dddddd}iiic{{d}iiiii}iic{d}{d}{d}iiic{i}{i}iiiiic{i}{i}{i}iiiciiiic{d}{d}{d}dddc{{d}iiiiii}dddc{{i}dd}dddc{d}ic{i}{i}dc{d}{d}dc{{d}iiiii}dddddc{{i}dddd}iiiic{i}dddc{{d}}dddddc{{i}dddd}iiciiiiic{{d}iiiiii}c{{i}ddd}c{{d}iiiii}ddddddc{i}{i}dddc{d}{d}{d}ddc{{i}ddd}iiiic{{d}iiii}c{{i}ddd}iiiic{{d}iiiiii}ddc{{d}iiiiii}iic{i}iic{i}{i}c{d}dddc{d}{d}ddddc{{i}dddd}iic{d}{d}{d}iic{i}{i}iic{i}iiiiic{{d}}c{{i}}iiiciic{{d}iii}ic{{i}dddd}ic{i}iiiiic{d}{d}ddddc{i}dddciiic{{d}iii}ddc{{i}ddddd}dcddddc{{i}dddddd}c{d}{d}ddddddc{{d}iiii}c{{i}ddddd}iiiiic{{d}iiiii}ic{{i}ddd}dddc{{d}iii}dddc{{i}ddd}c{{d}iii}iic{d}{d}{d}iiic{i}{i}{i}iic{i}{i}{i}dc{d}{d}ic{{i}ddddd}ic{i}ic{{d}iiii}ddddc{i}c{i}{i}iic{i}iic{i}{i}{i}dddc{{d}ii}ddddddc{i}iic{{i}dddd}ddc{d}{d}ddddc{d}{d}ddddc{d}dddc{i}iiiiiic{d}{d}iiic{{i}ddd}dc{{d}iii}dddddc{d}{d}{d}iiic{{i}}{i}iiiiic{{d}iiii}ic{i}{i}iiic{i}{i}ic{d}ddc{{d}iiiii}iiic{{i}dddddd}iiiic{{d}iiii}iiic{i}{i}c{d}{d}dddddc{{i}ddd}iiiiiic{{d}iiiii}c{d}{d}ddddc{{i}d}ic{{d}iiiiii}dddddcdddddc{d}{d}{d}iiic{i}{i}ddcddddc{{i}ddddd}iiic{{d}}ddddddc{{i}d}iic{{d}iiiii}ddddddc{{i}dddddd}dc{d}{d}dddc{{i}dddd}dddc{{d}iiiiii}ddddddc{i}{i}{i}iiiic{d}{d}dddc{{i}dddddd}ddc{{d}iiii}dc{i}{i}dc{d}{d}iic{i}{i}{i}iiiiiiciiiic{{d}iii}ic{{i}dd}iiiiciic{d}{d}dc{{d}iiii}dddddc{{i}ddd}dddc{{d}i}c{{i}}{i}iic{{d}ii}ddcic{{i}ddd}iiic{{d}iiiiii}dddc{d}{d}{d}c{i}{i}ic{{i}dddd}iiiic{{d}iii}iic{{i}ddddd}iiiiic{{d}iiii}dc{d}{d}iiic{{i}dddd}dddc{i}{i}{i}iiicic{d}ddddc{d}{d}{d}dc{d}ddc{{i}ddddd}dc{d}{d}{d}iic{{d}ii}c{{i}ddddd}ic{i}{i}ddciiiiic{d}{d}{d}iic{i}{i}{i}ddc{d}{d}{d}ddc{i}ddc{{i}dddddd}iiiiic{{d}iiiii}ddcdddddc{d}dc{i}c{i}dc{d}{d}ic{{i}dddd}iiiic{d}dddciiiiiic{{d}iiii}c{i}{i}dddc{i}{i}ddc{{d}iiii}ic{i}{i}iiiiic{{i}dddddd}c{{i}dddddd}c{{d}iii}dddddc{i}iiiiiic{{i}ddd}dc{{d}iiiiii}ddddddc{{i}dddddd}iiic{d}{d}{d}ddc{{d}iiiii}ddc{{i}ddddd}iiiiic{d}dcdc{{d}iiiiii}dciiiiic{i}{i}ic{i}c{{i}dddddd}iiiiic{{d}iiii}dcdddddc{{d}iiiiii}dddddc{{i}}iic{{d}iiii}iiic{i}ic{{i}dddd}c{{d}iiiii}dddddcddc{{i}dddddd}iiiiiic{{d}iiiiii}dddddc{d}{d}{d}ddddciiiiic{i}{i}icic{i}{i}{i}iiiic{{d}iiii}dddc{{i}dddd}iiiiiic{i}iiiiiic{{d}iiiiii}dddddcddddcc{d}{d}{d}iic{d}{d}{d}ic{{i}dddd}iic{d}dddcdc{{i}ddddd}iic{{d}iii}ddc{{i}ddd}iiiic{{d}iii}ddddc{{i}ddddd}iic{{d}iiiii}cddddc{{i}dd}ic{d}c{d}{d}{d}ic{i}{i}iic{{d}iiiii}ddddddc{i}{i}iiiiic{{i}ddddd}dddc{{d}iii}c{d}c{{i}dddddd}iiic{{d}iii}ic{{i}dddd}c{d}{d}{d}iic{{i}dddddd}iiic{i}{i}{i}ddc{{d}iiii}dddddc{d}ddc{{i}dddd}iiiic{i}dc{{d}iiii}dddddc{{i}dddd}iiiiic{{d}iii}ddc{{i}dddd}iiiiciiiiic{d}{d}ddddddciiiic{{i}dddddd}iic{d}ic{{d}iii}dddc{{i}ddd}dc{{d}iiiiii}iiic
```
] |
[Question]
[
You step into the restroom, and notice that the toilet paper has missing! It occurs to you that someone had *stolen* it. Strangely enough, the first thing you would like to know is the amount of toilet paper the thief stole.
## Task
You are given three integers \$ I \$, \$ R \$, and \$ G \$, the details of the toilet paper, where \$ I \$ is the *radius* of the inner ring, \$ R \$ is the number of *rotations*, and \$ G \$ is the *thickness*. The task is to return/output out the *length* of the toilet paper.
The toilet paper can be viewed as an [Archimedes' spiral](https://en.wikipedia.org/wiki/Archimedean_spiral), which starts at coordinate \$ (I, 0) \$, and rotates a total of \$ R \$ times in the counterclockwise direction, with a distance of \$ G \$ between each gap.
More formally, the Archimedes' spiral here is defined as the set of all points whose locations over time move away from the origin counterclockwise at a constant speed and with constant [angular velocity](https://en.wikipedia.org/wiki/Angular_velocity).
Due to potential precision issues, your answer will be judged correct if they pass all the sample cases below when rounded to \$ 1 \$ decimal place.
In the diagram below, \$ I = 5 \$, \$ R = 3 \$, \$ G = 4 \$, and the total length is \$ \approx 207.7 \$.
[](https://i.stack.imgur.com/BpRY7.png)
## Test Cases
```
I R G -> answer rounded to 1 decimal place (note that the answer does not have to be rounded)
0 1 1 -> 3.4
5 3 4 -> 207.7
12 9 2 -> 1187.7
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
# [J](http://jsoftware.com/), 66 bytes
```
1#.2|@-/\1e3&((-:@[%:_1:)^[:i.1+[*0{])((*{:)+[*(1{])*1e3%~i.@#@[)]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1jGocdPVjDFON1TQ0dK0colWt4g2tNOOirTL1DLWjtQyqYzU1NLSqrTSBHA1DIE8LqFa1LlPPQdkhWjP2vyZXanJGvkKagiEQGsA4xgomCqYwjqWCkYKh0X8A "J – Try It Online")
This could be golfed more, but I'm putting it away for now.
Instead of taking an analytic approach I am using complex number arithmetic to break the spiral down into 1000 straight line segments per rotation, and then summing those segments.
I find the 500th root of -1, and keep multiplying it by itself to rotate it and get an approximation to the next spiral point.
Because the spiral also moves outward, we need to take the new vector, normalize it, multiply the normal vector by 1/1000 of the thickness, and then add that little correction to the new vector.
Conceptually, we're doing something similar to approximating a circle's circumference with the short sides of many triangles.
[](https://i.stack.imgur.com/4LsI0.png)
The idea is simple, but the golf part of it boils down to boring bookkeeping and argument parsing which isn't worth going into. In theory the realization of this method could be a lot shorter.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~93~~ ~~83~~ ~~76~~ 71 bytes
*-9 bytes if we don't explicitly round the results*
*-1 byte after changing n to 9999*
*-7 bytes thanks to dingledooper who rearranged the operations*
*-5 bytes thanks to xnor who changed the square root calculations to taking an absolute value of a complex number*
```
lambda i,r,g:sum(abs(1j+6.283*(t/n+i/g))for t in range(n*r))/n*g
n=9999
```
[Try it online!](https://tio.run/##TcexDsIgEADQvV/BeEcvIqCNbdI/caFREGOvzZUOfj26mPi2t77LY2Ff43itrzBPt6AyCaVh22cI0wb22XYHd/EaiuE2m4QYF1FFZVYSON2BtSAa1qnhsf@qq2QuEOFIlixi8/uZPJ3@bh315BDrBw "Python 3 – Try It Online")
This is a straightforward numerical integration of a spiral length, without using any imports. `n` is chosen so that the results are sufficiently precise.
The length of a spiral is a sum $$L = \sum\_{t=1}^n L\_t,$$ where Lt is calculated as a hypothenuse in a *roughly* right triangle with sides $$\frac{2\pi}{n} r\_t = \frac{2\pi}{n}\left(i+\frac{gt}{n}\right)$$ and $$r\_{t+1}-r\_t = \frac{g}{n}$$.
[Answer]
# [Python 3](https://docs.python.org/3/), 83 bytes
*Thanks @xnor for finding some important approximation, notably `h(t)=t*t+log(2*t+.5)`*
```
lambda i,r,g:g/2/T*(h(T*(i/g+r))-h(T*i/g))
h=lambda t:t*t+99*(2*t+.5)**.01
T=6.2832
```
[Try it online!](https://tio.run/##PcrBDoIwDAbgO0@xhMs66sY6EEayt@DoBWOAJYpk2cWnn9OIPfx/m6/7K67PzaTZXdJ9elxvE/MYcBkWRWoUfOU5vFqqAHD6HHkHKFb3e45DFLGyVnDKLVsQQta6GN1ZUm8o7cFvkc@8Ro0agOUpmZFNcUCLBpsDqO5k9ydNaJG@VjKt@2zpDQ "Python 3 – Try It Online")
The same solution as below, but uses several approximations:
* \$2\pi \approx 6.2832\$
* \$ \theta\sqrt{1+\theta^2}+\sinh^{-1}\theta + C \$
\$ \approx \theta^2 + \ln(2\theta+0.5) +C \$
\$ \approx \theta^2 + 99(2\theta+0.5)^{0.01} + C\$
---
"Exact" solution
# [Python 3](https://docs.python.org/3/), ~~104~~ 100 bytes
*-3 bytes thanks to @mathjunkie!*
*-1 byte thanks to @xnor!*
```
lambda i,r,g:g/4/pi*(h(2*pi*(i/g+r))-h(2*pi*i/g))
from math import*
h=lambda t:t*hypot(t,1)+asinh(t)
```
[Try it online!](https://tio.run/##PcxBCoMwEAXQvacIuMnEqZqo2ArepJuUogk0JqSz8fRpWrR/M/x58MNOxm9dWuZ7emn3eGpmMeI6rU3fBCu44Up8r23WKgJcjp4rQLFE75jTZJh1wUcShZmPFZpImD144oQSKv22m@EEKUS7EV94izL/geWUrKv74oQBO@xPUO1Yj3@SCm@oflYyKa/Z0gc "Python 3 – Try It Online")
This uses the exact formula. Maybe a good Taylor series approximation can be shorter.
The formula for the length of the spiral is:
$$ L=\frac{G}{2\pi} \int\_{\frac{2\pi I}{G}}^{\frac{2\pi(I+GR)}{G}}\sqrt{1+\theta^2}d\theta $$
and the formula for the integral is:
$$ \int \sqrt{1+\theta^2}d\theta=\frac{1}{2}\left(\theta\sqrt{1+\theta^2}+\sinh^{-1}\theta \right) $$
[Answer]
# [Python 3](https://docs.python.org/3/), 60 bytes
```
lambda I,R,G:6.2831*R*(I+R*G/2)+G*8*((1+R/(I/G+.05))**.01-1)
```
[Try it online!](https://tio.run/##XZHLbtswEEX3/IqBCwNDavSg5DSuAC@6KAQvstE2LQIm0YOA9QBFA8nXOxQtpU64Ie@d4ZkZcny37dBnl/rw93JS3fOrgiOVVOQ/o3SfSVEKPAalKOKUB4XYC0QZlDEe4yKIkjvOhYgSGUp@qc3QQadsC7obB2Nh1ATt@zhYAjXpvmWsOSwVNBlq8ibexaMW2GIq5l3HTWA4DxftJOesXe/Y3AqPQ0uSBx6JljNmq8lOcIBHhglJFyP4AVm0Y3hHGe28TJP76J6hTOkXpdwZUu5n5x9j9WCuE4PuwbNyBm6ZaobW6GPcW@rFntXJuc2tWxnjEAd/IVxyfGA0ure4pNKmrKbzyeawjbKa4LfPW9WfmXEVmy06El055OHuGdgV5g6dentaSyZL@3PrRvVNhTLhrv3ZLL@b4O3ixqY18DnDOm74ZcLbku6Mn9r97POE33rcPKi3BTgXdP/UnKrwVTfautrj2T2wHxQ22/9kfvkA "Python 3 – Try It Online")
An approximate method. Approximates `log` without an import using [Surculose Sputum's nifty approximation](https://codegolf.stackexchange.com/a/204715/20260.)
This approximation is quite accurate, achieving within 0.02 on all the test cases and within 0.1 on all single-digit inputs. It's possible to use looser approximations that work for all the test cases, but I'm not sure at what point this is overfitting. In the extreme, hardcoding the outputs would be very short. So, I'd like to exclude this answer from [my bounty on outgolfing me](https://codegolf.meta.stackexchange.com/a/18334/20260) since I'm not clear what golfs what be valid.
The first summand \$2\pi(I+RG/2)R\$ is what we get if we approximate the toilet paper spiral as instead being concentric circles with the same inner radius, thickness, and number of turns. The average of the circumferences of these \$R\$ circles is \$2\pi(I+RG/2)\$. This is \$2\pi\$ times the average of their radii of \$I+RG/2\$, or equivalently the average of the inner and outer radius.
The above approximation is already pretty good for the test cases, with error within 0.4. The second term approximates the additional circumference due to the spiral moving radially, rather than just tangentially as circles do. I got this from looking at the integral for arc length suggested by [svavil](https://codegolf.stackexchange.com/a/204719/20260). We then get rid of approximate `log` without an import using [Surculose Sputum's approximation](https://codegolf.stackexchange.com/a/204715/20260.) The constant of 8 is an approximation for \$100/(4\pi)\$, with 100 being inverse of the exponent 0.01 chosen for the log approximation. The `+0.05` fixes an approximation failing near \$I/G=0\$, which would otherwise cause a divide-by-zero. I originally calculated the desired values as \$1/(4\pi)=0.08\$, but heuristically 0.05 does better.
[Answer]
# [C (gcc)](https://gcc.gnu.org/) -lm -m32, ~~129~~ ~~120~~ ~~117~~ 114 bytes
```
#define F float
F i(F u,F g){F s=hypot(u,g/=6.2832);return(u*s/g+g*log(s+u))/2;}
#define f(I,R,G)i(I+G*R,G)-i(I,G)
```
[Try it online!](https://tio.run/##dYzBisIwFEX3@YqgDCTta2tTFYeOs4y4de2mpE0MpIk0yYCIv26mLmY3ru7hHjiiUEKktOwHqe2AOZbGdQFxrAnHEThW9M6x319uVxdIBFXttyXbNYy20xDiZEnMfKVylRmniM8jpRVrH@gvKMkRTnCgmhzzQ/aiYsZ50lJbYWI/4C8feu3KyzdC2gY8dtqSH6d7iu7oOs2XJIuPspZnu4C5t4Iaakrb/9wGGli/cTWDT2Av@UhPIU2nfCrMmIqxYb8 "C (gcc) – Try It Online")
*5 bytes off thanks to ceilingcat (by using the hypot library function).*
*4 bytes off thanks to dingledooper (who suggested using a typedef to shorten the float declarations -- I ended up using a macro instead to implement the same idea).*
*3 bytes off by using an approximation to \$2\pi\$ that's sufficient for the accuracy required by the challenge.*
*3 more bytes thanks to ceilingcat (turning f from a function into a macro).*
The auxiliary function `i` computes the appropriate indefinite integral, and then `f` computes the desired definite integral by evaluating the indefinite integral at the two endpoints and subtracting.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
4°©*Ý*®/+nŽ›Ñ₄/*²n+tO®/
```
Port of [*@svavil*'s Python answer](https://codegolf.stackexchange.com/a/204719/52210) (their revision without complex number), so make sure to upvote them!
Input-order as `r,g,i`.
[Try it online](https://tio.run/##yy9OTMpM/f/f5NCGQyu1Ds/VOrROXzvv6N5HDbsOT3zU1KKvdWhTnnaJP1D4/39jLhMuUwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL4dbi0KCE/yaHNhxaqXV4rtahdfraeUf3PmrYdXjio6YWfa2IPO0Sf6Dof53/0dGGOoY6BrE60cY6JjqmQNpSx0jH0Cg2FgA).
**Explanation:**
```
4° # Push 10**4: 10000
© # Store it in variable `®` (without popping)
* # Multiply it by the first (implicit) input `r`
Ý # Push a list in the range [0, 10000r]
* # Multiply each value by the second (implicit) input `g`
®/ # Divide each by `®`
+ # Add the third (implicit) input `i` to each value
n # Take the square of that
Ž›Ñ # Push compressed integer 39478
₄/ # Divide it by 1000: 39.478
* # Multiply it by each value
² # Push the second input `g` again
n # Square it
+ # And add it to each value as well
t # Take the square-root of each value
O # Sum everything together
®/ # And divide it by `®`
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž›Ñ` is `39478`.
[Answer]
# [SageMath](http://doc.sagemath.org/html/en/index.html), 70 bytes
```
lambda I,R,G:N(G/2/pi*(sqrt(1+x^2)).integral(x,2*pi*I/G,2*pi*(I/G+R)))
```
[Try it online!](https://sagecell.sagemath.org/?z=eJwljMEKgkAYhO8-xeLp_3XadbeWSqireOngAwhGrSyYydJBEN-9zebyzTDMuMvQve6PTtRoUJU3qpRRk8-IdD63hltpWfrx8-xDN9AMk8WyVtXfUHR5w8yJewfhEdALPwoii6O0KORJM6iAxo8WexwitcEZhrlMRNQU4j25dNnmq9hdxeJoC7ym_AVlsSkn&lang=sage&interacts=eJyLjgUAARUAuQ==)
**How**
Uses the formula for the length of the spiral:
$$ L=\frac{G}{2\pi} \int\_{\frac{2\pi I}{G}}^{\frac{2\pi(I+GR)}{G}}\sqrt{1+\theta^2}d\theta $$
from [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)'s [Python answer](https://codegolf.stackexchange.com/a/204715/9481).
] |
[Question]
[
I have a piece of paper whose shape is a regular `n`-gon with side length `1`. Then I fold it through some of its diagonals. What is the area of the shape formed by the (former) edges of the regular polygon?
## Illustration
Suppose `n = 8`, i.e. an octagon-shaped paper. Let's name the vertices from A to H (left picture). Then I fold the paper along the two diagonals BE and FH (right picture). Mathematically, folding BE means to reflect the vertices C and D with respect to the line BE to obtain C' and D'. Your task is to calculate the area of the shaded octagon on the right picture.

## Input
The number of sides `n` and a list representation of the folds `l`. Each element of `l` represents either a fold or an intact side of the polygon. If it is a fold, its value is the number of sides moved by the fold (e.g. 3 for the `BE` fold above, 2 for `FH`). Otherwise, the value is 1 (e.g. for the sides `AB`, `EF`, `AH`).
For the example above, the input will be `8, [1, 3, 1, 2, 1]` if we count from the vertex A, counter-clockwise. If we count clockwise from E instead, the input will be `8, [3, 1, 1, 2, 1]`; the expected answer is the same.
Note that `sum(l) == n`. Also, `l == [1] * n` (1 repeated n times) case is just the regular polygon untouched, which is a valid input.
**The resulting polygon is guaranteed to be simple** (it does not intersect or touch itself). For `n=3` or `n=4`, this means that the only valid input is the polygon folded zero times. For `n=6`, `l=[1, 2, 2, 1]` or `l=[1, 2, 1, 2]` is invalid because the two folds will cause two folded vertices to meet at the center of the hexagon.
## Output
The area of the `n`-sided polygon created by the given folds. The result must be within `1e-6` absolute/relative error from the expected result.
## Scoring & winning criterion
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins.
## Test cases
```
n l => answer
---------------
4 [1, 1, 1, 1] => 1.000000
5 [1, 1, 1, 1, 1] => 1.720477
5 [2, 1, 1, 1] => 0.769421
6 [1, 2, 1, 1, 1] => 1.732051
7 [1, 2, 1, 2, 1] => 2.070249
8 [1, 3, 1, 2, 1] => 1.707107
```
The picture below shows the first five test cases.

[A reference implementation in Python](https://tio.run/##XZHBaoQwEIbvPsXAHjYR17aubouwpz5G6SHoRAOaSMxSltJnt5OktlqIMn4zf/6Zcbq73ujzshzgVQzNbRAOwfUIwqIAI0NssaOEhckM985o@FCuh1m1CAPqjuKnLLIGrRNKB/EM0gwttom0ZoRRUFqNk7EuhQOJdQaNmTOYVAZ5nictSpDMX0rQK2deJ@DtnYArlcFDsJwJWgKPeRWIZqGEE@5/sRMbPClskFI9JQryXqeIPHTXoHZofS3lgptPpdGQJDcdZ1m1VCmNBQU0a@jVt/qjPl2BrXoFp9BRSi3HxzdchEwaZ@OcosJbW6XdbgEZHD/r/CK/jjm50QaZN@A87KqLpbzeCmlCVvqbaf6/jXHOF8nKDN7oP9Ep3nmy/fYnoGqHtrTYo0ss/Eeft7RY6Uuk5y3tWOlfFV@@AQ).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~79 .. 66~~ 65 bytes
```
->n,f{(f*2+[w=-1]*n).sum{|z|(w**z*=b=2r/n).imag/(1-w**b).real}/4}
```
[Try it online!](https://tio.run/##bctNCsMgEAXgfU4xy8RqRJv@bOxFxIVCLYUmBEsITfTs1taNoR3eYngfz03mFa2I5DJgu9YW8Z2cBWEKDU37nPrVL76eEVqQMII7mtp7r2@0ZiS1pmndVT8C7UKUIKHDIBmGFK4gn8IVbOQTVchhI18shP/dHPOG/25OpfBSzln2pVSq7fW4eo2NhxGsTI8K8Q0 "Ruby – Try It Online")
Loosely based on the reference implementation:
[](https://i.stack.imgur.com/cuyFF.png)
* The area of the original polygon (ABCDEFGH) is `a`
* If we cut instead of folding, we get a new convex polygon (ABEFH), we call the area of this polygon `b`
* The difference between `a` and `b` is the area of the polygons we cut away (BCDE and FGH), let's call it `c`
* The area of the folded polygon is `b-c` or `a-2c` (we have to remove BCDE and FGH twice from the original polygon). This equals to `2b-a`
* Both `a` and `b` can be represented as the sum of triangles (formed by 2 radiuses of the enclosing circle and one side of the polygon). Yes, we have a formula for calculating `a`, but if we define an intermediate function `g` it's easier to use it for both `a` and `b`
* The area of a triangle is r\*r\*sin(2lπ/n) where l is the number of vertices in a fold and n is the total number of vertices, and r is the radius (which is 1/sin(π/n))
* `a` is the sum of n triangles with l=1
* since `g(-x)=-g(x)`, we don't need to split the sum in 2 parts, we can sum over a larger array (that is twice f plus [-1] repeated n times), the intermediate function can become a block.
* sin(x)^2 becomes (1-cos(2x))/2
* sin(2π/x) and cos(2π/x) are imaginary and real part of the xth root of -1.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~37~~ 36 bytes
```
Tr[Csc[i=Pi/#2]^2Sin[2i#]-Cot@i#]/4&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6Qo2rk4OTrTNiBTX9koNs4oODMv2ihTOVbXOb/EAUjrm6j9DyjKzCuJVta184tOc3BQjo1V03eo5qquNtQBw1odk1odBBckYAoWMELlGurABcyQBIxAAuZQAWOYgEUtV@1/AA "Wolfram Language (Mathematica) – Try It Online")
Takes input in the order `l, n`.
Uses the same approach as in the reference and many other implementations.
Mathematica's trigonometric and arithmetic functions will automatically vectorize, and `Tr` returns the sum of the elements of a one-dimensional list.
\$\csc\$ and \$\cot\$ are relatively uncommon; \$\csc x=\frac1{\sin x}\$, and \$\cot x=\frac1{\tan x}\$.
[Answer]
# JavaScript (ES7), ~~87 83 82 79~~ 72 bytes
*Saved 2 bytes thanks to @Shaggy*
*Saved 7 bytes thanks to @GB's insight*
Takes input as `(n)(list)`. Derived from the reference implementation.
```
with(Math)f=n=>a=>a.map(v=>n+=sin(2*v*T)/sin(T)**2,n/=-tan(T=PI/n))&&n/4
```
[Try it online!](https://tio.run/##bctPa8JAEAXwez7FnGQmrgld/xXK5mahB8GDt7CHISYmxc6KWWK/fYzmsq0O7zCPH@@bO26LS3P2M3GHsu@vja9xy76myojJeEjyw2fsTCZT0zaCOu7iPaX3d09xrJWkZuZ5aGb3lQrRZCLpov/II4AcFgryNwVDtIXxrPon99hAln/kgYHol5vVuNHPm3UoOpT3UeahRDZKKnfZcFEj5qKALYHJoHDSulOZnNwRKxRCpsS7z@a3POCKiPob "JavaScript (Node.js) – Try It Online")
Given the number of sides \$n\$ and the folding values \$F\_1\$ to \$F\_m\$, this computes:
$$A=\frac{1}{4}\left(-\frac{n}{\tan(\theta)}+\sum\_{i=1}^{m}\frac{\sin(2\theta F\_i)}{\sin(\theta)^2}\right)$$
with \$\theta=\dfrac{\pi}{n}\$
[Answer]
# Java 8, ~~123~~ ~~114~~ ~~112~~ 103 bytes
```
a->n->{double t=Math.PI/n,T=Math.sin(t);n/=-Math.tan(t);for(int v:a)n+=Math.sin(2*v*t)/T/T;return n/4;}
```
Port of the Python reference implementation.
-11 bytes by porting [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/195777/52210).
-9 bytes thanks to [*@G.B*'s insight](https://codegolf.stackexchange.com/questions/195775/area-of-diagonal-folded-regular-polygon/195792?noredirect=1#comment465934_195777).
[Try it online.](https://tio.run/##hZJLb8IwDIDv/AqrpwbaVBTYJjqQJk1IOyBNgxvikNEUwkpaNW4nhPjtLKQwXt1oDo3tz3b8WLKCucvwazeLmVIwZEJuagAKGYoZLLWV5ihiGuVyhiKRdHC4PAuJk6nzL/Ka5J8xd6D89/sQQW/H3L50@5vQ6AB7Q4YL@v7mSWdc3pWQNpJAej3XyMiMHCWZrXNC0WVENk6oXy/qSLyxNw4yjnkmQXrtYLsLarqOVCfRdRzKKRIRwkqXaI8wE3I@mQIj@3IBRmuFfEWTHGmqTRhL2xqJkKuu1bDAohlPOUO7QxrWIInDK7W/139wlcfYBYuY1ADIFdotByT/BtOtTdPRZ6vtv@b2jfke4F@YOxX@VxEuEL8CeLiMUYU83iL@FfJ0ibTOkW3ttFNmCMbjsAJq32andIRo39y/Z2LY8843m@5RaREacznHhU1I47SWL1nG1opiUs7cLjOcx2g13Xv4WWTztIovoixN4/XRoRTM08ihB9vdDw)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~41~~ 35 bytes
```
{4÷⍨(+/(1○2×⍵×t)÷2*⍨1○t)-⍺÷3○t←○÷⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qQMCjtgnm/6tNDm9/1LtCQ1tfw/DR9G6jw9Mf9W49PL1E8/B2Iy2gBEiwRFP3Ue@uw9uNQWygLiAF0rSr9n8aiNfb96ir@VHvmke9Ww6tN37UNhFoenCQM5AM8fAM/m@ikKZgCIFcpgg2lGcEZZuBZWA8czgPiLkswDxjCA8A "APL (Dyalog Unicode) – Try It Online")
Uses [Arnauld's expression](https://codegolf.stackexchange.com/a/195777/80214) for calculating the area.
-6 bytes from ovs. (removing inner dfn)
## Explanation
```
{4÷⍨(+/(1○2×⍵×t)÷2*⍨1○t)-⍺÷3○t←○÷⍺} ⍺ → n, ⍵ → l
t←○÷⍺ assign t to Π/n (○÷n = (○1)÷n)
( ) apply the following to each element of l:
(1○2×⍵×t) sin(2×element×t)
÷ divided by
2*⍨1○t sin(t)²
(+/ sum the results
- minus:
⍺ n
÷ divided by
3○t tan(t)
4÷⍨ divide that whole expression by 4
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~81~~ 79 bytes
```
lambda n,f,a=-1:sum([(a**(2/n*r)).imag/(1-a**(2/n)).real for r in f*2+[a]*n])/4
```
[Try it online!](https://tio.run/##bctBDoIwEAXQvaeYZVuLhIJoSDhJ7WKMVpvQQiouPH2l1gSIzvzVf/nDa7z3rgy6PYUO7fmC4Ljm2GZF83haIgkyRkTumKd0ZyzeclJk325q/BU70L0HD8aBZmIrUTGnaF6FWJtYy@krDrLgMEUoSKc4rCBGzbBfwcdmEP8WdVqIn8VhCWIBxwTlElSzARi8cSPRhBlKwxs "Python 3 – Try It Online")
A Python port of my Ruby solution.
[Answer]
# [R](https://www.r-project.org/), ~~60~~ 57 bytes
-2 and -1 thanks to Nick Kennedy and CriminallyVulgar!
```
function(n,l,t=pi/n)(sum(sin(2*t*l)/sin(t)^2)-n/tan(t))/4
```
[Try it online!](https://tio.run/##TcrNCoAgEATge0/RcVcMyX4P9SpBBIJgW9T6/EbSj8xl5mOOYPKhCMbTwnYjIOkkj7tVhHD6FU5LoAULh@qujJPGghTPd0dVBwO1XKCUMYiZgebfiehkt/GRSveJfqSPUr0SLg "R – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~36~~ ~~31~~ ~~30~~ ~~25~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
·žqI/©*®šÅ½ćn/OI®Å¼/-4/
```
Folds-list as first input, sides-integer as second input.
Port of [my Java answer](https://codegolf.stackexchange.com/a/195788/52210).
-5 bytes by porting [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/195777/52210).
-1 byte thanks to *@Grimy*.
-5 bytes thanks to [*@G.B*'s insight](https://codegolf.stackexchange.com/questions/195775/area-of-diagonal-folded-regular-polygon/195792?noredirect=1#comment465934_195777).
[Try it online](https://tio.run/##yy9OTMpM/f//0Paj@wo99Q@t1Dq07ujCw62H9h5pz9P39zy0Dsjeo69rov//f7ShjrGOoY6RjmEslwUA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/h5ulir6SQmJeioGTv6RIKZD9qmwRk/z@0/ei@wgj9Qyu1Dq07uvBw66G9R9rz9P0jDq0Dsvfo65ro/9f5H22oA4SxXMZcEBaIbQJhG8FZUHFTrmgjJDZQBYxnBuMZgXjmIJ4xjGcBAA).
**Explanation:**
```
· # Double each value in the (implicit) input-list
žq # Push PI
I/ # Divide it by the input-integer
© # Store this PI/input in variable `®` (without popping)
* # Multiply this to each doubled value in the list
®š # Prepend `®` (PI/input) to this list
Ž # Take the sine of each value in the list
ć # Pop and push remainder-list and first item separated to the stack
n # Square this first item: sin(PI/input)²
/ # Divide each value in the list by this
O # And then sum all values together
®Å¼ # Get the tangent of `®`: tan(PI/input)
I / # And divide the input-integer by this
- # Subtract it from the sum
4/ # And divide it by 4
# (after which the result is output implicitly)
```
[Answer]
# [Icon](https://github.com/gtownsend/icon), 108 bytes
```
procedure g(s,f)
r:=.5/sin(t:=&pi/s)
p:=s*(c:=.25/tan(t))
p-:=(c*(i:=!f)-r*r*sin(2*i*t)/2)*2&\z
return p
end
```
[Try it online!](https://tio.run/##fc/BDoIwDAbg@55iXsi6gItT1CzZk6gHAoPs4Fi6ERNfHkfwAIm49LT/a5vaunfj6LGvTTOgoR0LeQsEld6XIljHotKZtyIA8UoHzuqUyFLEKkWQPgulWc2ZVXrXQoEc@dQlueURhAQus/uboIkDOuqJcc1i2bNKFAhN74U2GtaxU05vh5x@6wHrtFylG0D@A@d5gtwElyWQP8B1BscVmO76AA "Icon – Try It Online")
An [Icon](https://github.com/gtownsend/icon) port of the Python reference implementation.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
×ḤÆS÷ÆS²¥_ÆTİ×ɗS
ØP÷ç÷4
```
[Try it online!](https://tio.run/##y0rNyan8///w9Ic7lhxuCz68HUgc2nRoafzhtpAjGw5PPzk9mOvwjACg@PLD203@H530cOcM60cNcxR07RQeNcy1Prxcn@tw@6OmNZH//0dzKShEK5joKEQb6igAkVGsAgTE6qDJgFAskowpigxYEknGCKseM4geI0w95sgyRsgyFhAZY2QZrlgA "Jelly – Try It Online")
A full program that takes the number of sides as its first argument and the list of folds as its right. Returns/prints the area of the folded polygon.
Loosely based on the [formula in @Arnauld’s answer.](https://codegolf.stackexchange.com/a/195777/42248)
] |
[Question]
[
## Introduction
You are stranded on a deserted island with some servants and are hunting for treasure. The longer one searches, the more treasure one finds. The fewer people searching, the more each person finds.
Due to limited supplies, the leader has decided that a few people, up to a quarter of the group, shall be left to die each night. He has decided not to tell anyone exactly how many people shall die on any given day ahead of time.
You are in control of a small group of 5 people, who shall venture out of camp to find treasure for you.
## Objective
The objective of this competition is to amass as much treasure as possible. Every turn that your servants do not attempt to return to camp, they will find a certain number of pieces of treasure. Your servants may return to camp at different times.
Each turn that a worker stays out to search for treasure, the worker finds `1+R` pieces of treasure, where `R` is the number of workers (out of all the bots) already back in camp. Dead bots do not factor into this calculation.
At the start of each day, a random number (`n`) from `2` to `max(3, floor(num_live_players/4))` will be chosen. (For 10 players on day 1, this is `2` to `max(3,50/4)=12`. For 20 players on day 1, this would be `2` to `max(3,100/4)=25`.) This number represents the number of players who will be left to die for that day, and will not be given to your program.
If a servant is one of the last `n` people to return, he/she will die and be unable to transfer the treasure he/she found to your possession. Furthermore, the servant will be unable to participate in treasure hunting for the rest of the adventure.
Your final score is the average amount of treasure you obtained per adventure (run of the controller).
If more people attempt to return to camp on the same turn than there are open slots, random numbers will determine who gets in and who dies.
A day on this island from sunrise to sunset lasts 30 turns. As there are many dangerous animals at night, failure to return by sunset means that you will not be allowed into the camp.
## Input/Output
Your program should run for the entirety of the simulation.
At the start of the simulation, `INDEX I` will be inputted, where `I` is the index of your bot (this index is counted from 1 up).
At the start of each day, `START_DAY D/N` will be inputted to your program, where `D` is the day number (starting from `1`), and `N` is equal to `max(3, floor(num_live_players/4))`, which is the maximum number of people who may die on that particular day.
At the start of each turn, `START_TURN T` will be inputted to your program, where `T` is the turn number (starting from `1`).
Once your program receives this, it should respond with a list of your servants' moves, each separated by a comma.
Valid moves are:
* `R`: Try to return to camp.
* `S`: Stay looking for treasure.
* `N`: Servant is already dead or in camp.
Entering an invalid move will be interpretted as `S` if the bot is alive and not in camp, and `N` otherwise.
At the end of each turn, a string shall be passed to your program:
```
END_TURN [Turn #] [Bot 1 Moves] [Bot 2 Moves] ...
```
where each bot's servants' moves are separated by commas.
These moves will be one of the following:
* `R`: Successfully returned to camp that turn.
* `r`: Failed to return to camp that turn.
* `S`: Still looking for treasure.
* `D`: Died on an earlier turn.
* `N`: Already back at camp.
Bots and servants remain in the same order throughout the entire simulation.
For example:
```
INDEX 2
....
END_TURN 8 N,N,N,N,N r,r,r,r,D D,D,D,N,R S,D,D,N,D
```
Here, you are the second bot (`r,r,r,r,r`), who tried to return all four servants that are still alive (and unluckily failed on all four). Bot 1's servants are all back in camp. Bot 3 has three dead servants, one more back in camp, and a fifth servant who successfully returned. Bot 4 has one servant who stayed (and will die, as this is the last turn of a day), one servant in camp, and three dead servants.
After each of these strings, unless a string signaling the end of the day has also been outputted (see below), your program is to output your servants' next moves, separated by commas. All servants must be accounted for (with `N` if already in camp, and `D` if already dead). Invalid moves will be treated as `S` if the servant is not already in camp/dead.
Example:
```
N,N,S,S,R
```
which means:
```
Servant # | Action
1 | Do nothing.
2 | Do nothing.
3 | Stay put (keep looking for treasure).
4 | Stay put (keep looking for treasure).
5 | Try to return to camp.
```
At the end of a day, the following string shall be passed after the last turn's `END` string, informing everyone on who is alive:
```
END_DAY [Day #] [Bot 1 Status] [Bot 2 Status]
```
where the status is a comma separated list of either `A` (alive) or `D` (dead). The following day begins immediately after.
The simulation ends when there are fewer than 6 live servants. Your program will receive the following input at the end of the simulation:
```
EXIT
```
## Rules/Details
* Only on turns where your action is `S` will you find treasure.
* Number of simulations run: **1000 times**
* Your program should not take any more than 1 second to determine moves.
* Your program should not exit early; it will be started exactly once.
* Make sure that the output buffer (if applicable) is flushed after each output.
* **Files may be written to in your bot's folder (`./players/BotName/`). Your bot name is whatever you name your bot, with all non-alphanumeric characters removed and written in CamelCase. Entries may save data between runs of the controller, as runs are done sequentially.**
* Your program must exit after receiving `EXIT`.
* Programs that fail to compile or throw errors or output invalid text (not in the format of 5 characters separated by commas) may be excluded from the competition. A newline must follow each output.
* The controller may be found [on GitHub](https://github.com/es1024/Treasure-Hunting-Controller).
***Please include the bot name, language+version, code, and command to compile (if applicable) and run your bot.***
## Example
Text outputted by the program is prefixed here with a `>`. Your program should not output this character.
```
INDEX 2
START_DAY 1/3
START_TURN 1
>S,S,S,S,S
END_TURN 1 S,R,S,S,S S,S,S,S,S
START_TURN 2
>S,S,S,S,S
END_TURN 2 S,N,S,R,S S,S,S,S,S
START_TURN 3
>R,R,S,S,S
END_TURN 3 R,N,R,N,R R,R,S,S,S
START_TURN 4
>N,N,S,S,S
END_TURN 4 N,N,N,N,N N,N,S,S,S
START_TURN 5
>N,N,R,R,R
END_TURN 5 N,N,N,N,N N,N,r,r,R
END_DAY 1 A,A,A,A,A A,A,D,D,A
START_DAY 2/3
START_TURN 1
>S,S,N,S,N
END_TURN 1 R,R,R,R,R S,S,D,D,N
END_DAY 2 A,A,A,A,A D,D,D,D,D
EXIT
```
The scores for the above example are:
```
Bot# Day 1 Day 2 Total
1 10 0 10
S1 1+2 0 3
S2 0 0 0
S3 1+2 0 3
S4 1 0 1
S5 1+2 0 3
2 20 0 20
S1 1+2 0 3
S2 1+2 0 3
S3 0 0 0
S4 0 0 0
S5 1+2+3+8 0 14
```
The winner is therefore the player, bot 2. Note that the winner does not have to survive to the absolute end. (Also note that the player could have remained until turn 30 on day 1, since the camp would not be full until the player sent one more bot back).
## Scores
```
Bot Score
Bob 2939.422
Statisticians 2905.833
Morning Birds 1652.325
Evolved 1578.285
Slow Returners 1224.318
Wandering Fools 1065.908
Randomizers 735.313
Drunkards 0
Plague 0
```
Logs are available [on GitHub](https://github.com/es1024/Treasure-Hunting-Controller).
Results per each trial are available [on this google spreadsheet](https://docs.google.com/spreadsheets/d/1i8vZFORUBtdh-Btb7OvIy0IOqj-PGOaDvtogSgoQEag/edit?usp=sharing).
[Answer]
# Statisticians, Python 3
The statisticians always work together. On the first turn, they return to the camp when two thirds of their opponents have done so. On the subsequent turns, they rely on the data they have collected from the previous turns to predict the habits of the other servants, and try to return to the camp at the last safe moment.
# Program
```
# Team of treasure-hunting statisticians
# Run with:
# python3 statisticians.py
num_others = None
running = True
while running:
msg = input().split()
msg_type = msg.pop(0)
if msg_type == "INDEX":
my_index = int(msg[0])-1
elif msg_type == "START_DAY":
day, max_deaths = tuple(map(int, msg[0].split('/')))
elif msg_type == "START_TURN":
turn = int(msg[0])
if day == 1:
if turn == 1:
print("S,S,S,S,S")
elif turn == 30 or num_active <= max_deaths * 4/5:
print("R,R,R,R,R") # On first day, return when 4/5 of maximum number of dying servants remain
else:
print("S,S,S,S,S")
elif turn >= 29 or len(expected_servants[turn+1]) <= max(2, max_deaths * 3/4) or len(expected_servants[turn]) <= max(2, max_deaths * 1/4):
print("R,R,R,R,R") # If many servants are expected to return next turn or someone is sure to die, return to camp
else:
print("S,S,S,S,S") # Otherwise, keep going
elif msg_type == "END_TURN":
turn = int(msg.pop(0))
others_moves = [tuple(s.split(',')) for s in msg[:my_index] + msg[my_index+1:]]
if num_others is None: # End of first turn, initialize variables that depend on number of servants
num_others = len(others_moves)
others_history = [{} for i in range(num_others)]
if day == 1:
num_active = sum([move.count('S') for move in others_moves])
for i, moves in enumerate(others_moves): # Log the return habits of other bots
if turn == 1:
others_history[i][day] = [0]*5
for j, move in enumerate(moves):
if move == "R": # Only safely returned servants are taken into account
others_history[i][day][j] = turn
if day > 1:
for future_turn in range(turn, 30):
expected_servants[future_turn].discard((i,j))
elif msg_type == "END_DAY":
day = int(msg.pop(0))
my_statuses = tuple(msg[my_index].split(','))
others_statuses = [tuple(s.split(',')) for s in msg[:my_index] + msg[my_index+1:]]
expected_servants = [set() for i in range(30)] # Compute the sets of expected servants for each turn
for i in range(num_others):
for j in range(5):
if others_statuses[i][j] == 'A':
turn_sum = 0
for day_num in others_history[i]:
turn_sum += others_history[i][day_num][j]
for turn in range(turn_sum//day):
expected_servants[turn].add((i,j))
elif msg_type == "EXIT":
running = False
```
As you can see, I shamelessly stole the program structure from @Mike Sweeney.
# Command
```
python3 statisticians.py
```
*EDIT: Fixed a bug in the check for returning home. They should perform somewhat better now.*
*EDIT 2: The statisticians are now smarter than before: they keep track of which servants have returned to the camp in the current day, and adjust their predictions accordingly. Also, they take more risks, returning to the camp when 3/4 of the maximum number of dying servants remain. This pushes them back to the top (just barely; Bob has become very dangerous).*
[Answer]
# Bob - C++
```
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
int compare(int i, int j)
{
if (i < j)
return (-1);
if (i == j)
return (0);
if (i > j)
return (1);
}
int main()
{
int index;
int day;
int turn;
int slash_index;
int to_die;
int num_alive;
int mine_alive;
int turn_to_return;
bool returned;
string line;
vector<int> last_returns;
vector<int> today_returns;
getline(cin, line);
if (line.compare(0, 6, "INDEX ") != 0)
{
cerr << "INVALID INDEX LINE \"" << line << "\"" << endl;
return (-1);
}
index = atoi(line.substr(6).c_str()) - 1;
while (1) // Day loop
{
getline(cin, line);
if (line.compare(0, 4, "EXIT") == 0)
{
return (0);
}
else if (line.compare(0, 9, "START_DAY") != 0 || (slash_index = line.find('/')) == string::npos)
{
cerr << "INVALID START_DAY \"" << line << "\"" << endl;
return (-1);
}
day = atoi(line.substr(10, slash_index - 10).c_str());
to_die = atoi(line.substr(slash_index + 1, line.length() - slash_index - 1).c_str());
if (day != 1)
{
if (to_die > num_alive)
{
turn_to_return = 30;
}
else
{
turn_to_return = last_returns[last_returns.size() - to_die] - 1;
}
}
returned = false;
for (turn = 1; turn <= 30; ++turn)
{
getline(cin, line);
if (line.compare(0, 4, "EXIT") == 0)
{
return (0);
}
if (line.compare(0, 7, "END_DAY") == 0)
{
goto end_day;
}
if (line.compare(0, 10, "START_TURN") != 0)
{
cerr << "INVALID START_TURN \"" << line << "\"" << endl;
}
if (day == 1)
{
switch (compare(turn, 30))
{
case -1:
cout << "S,S,S,S,S" << endl;
break;
case 0:
cout << "R,R,R,R,R" << endl;
break;
case 1:
cout << "N,N,N,N,N" << endl;
break;
}
}
else
{
if (returned)
{
cout << "N,N,N,N,N" << endl;
}
/*
else if (num_alive - today_returns.size() < to_die)
{
cout << "R,R,R,R,R" << endl;
returned = true;
}
*/
else if (turn >= turn_to_return)
{
cout << "R,R,R,R,R" << endl;
returned = true;
}
else
{
cout << "S,S,S,S,S" << endl;
}
}
getline(cin, line);
if (line.compare(0, 4, "EXIT") == 0)
{
return (0);
}
if (line.compare(0, 8, "END_TURN") != 0)
{
cerr << "INVALID END_TURN \"" << line << "\"" << endl;
}
stringstream ss(line);
string item;
int i = 0;
while (getline(ss, item, ' '))
{
i++;
if (i > 2 && i - 3 != index)
{
int num_to_add = count(item.begin(), item.end(), 'R'); // Add turn to today_returns for each servant that returned
for (int j = 0; j < num_to_add; j++)
{
today_returns.push_back(turn);
}
}
}
}
getline(cin, line);
end_day:
if (line.compare(0, 4, "EXIT") == 0)
{
return (0);
}
else if (line.compare(0, 7, "END_DAY") != 0)
{
cerr << "INVALID END_DAY \"" << line << "\"" << endl;
return (-1);
}
stringstream ss(line);
string item;
int i = 0;
num_alive = 0;
while (getline(ss, item, ' '))
{
i++;
if (i > 2 && i - 3 != index)
{
num_alive += count(item.begin(), item.end(), 'A');
}
else if (i - 3 == index)
{
mine_alive = count(item.begin(), item.end(), 'A');
}
}
last_returns = today_returns;
today_returns.clear();
}
return (0);
}
```
To Compile:
```
g++ -o Bob.exe Bob.cpp
```
To Run:
```
./players/Bob/Bob.exe
```
[Answer]
# Drunkards, Perl 5
A bit too much alcohol and they'll never find their way back to camp.
This entry is primarily an example, but will participate.
## Program
```
#!/usr/bin/perl
use 5.10.1;
$| = 1; # disable buffering
@actions = qw(S S S S S);
$_ = <>; ~/^INDEX (\d+)/;
$index = $1;
while(<>){
if(index($_, 'START_TURN') == 0){
say join(',', @actions);
}elsif(index($_, 'END_DAY') == 0){
# update actions based on who is alive
# index 1-indexed; first bot at position 2.
# this is not actually necessary for Drunkards, as all of Drunkards'
# servants will die on day 1 in any case.
# This check is here simply as an example.
my @status = split(',',(split(' '))[$index + 1]);
my $i;
for($i = 0; $i < 5; ++$i){
# action is S if alive, N if dead. Servants will never be in camp.
$actions[$i] = $status[$i] eq 'A' ? 'S' : 'N';
}
}elsif(index($_, 'EXIT') == 0){
exit 0;
}
}
```
## Command
```
perl ./players/Drunkards/Drunkards.pl
```
[Answer]
# Morning Birds
The early bird catches the worm!!!
```
package players.MorningBirds;
import java.io.*;
import java.util.*;
/*
* Java 7
*
* Compile with "javac ./players/MorningBirds/MorningBirds.java"
* Run with "java players.MorningBirds.MorningBirds"
*
* Servants find treasure from morning until noon.
* At noon they go to bed to prepare for next day.
*
* According to Benjamin Franklin, "Early to bed, early to rise, keeps a
* man healthy, WEALTHY, and wise."
*
*
*/
public class MorningBirds {
protected final static String STARTDAY = "START_DAY";
protected final static String STARTTURN = "START_TURN";
protected final static String ENDTURN = "END_TURN";
protected final static String ENDDAY = "END_DAY";
protected final static String MOVERETURN = "R";
protected final static String MOVESEARCH = "S";
protected final static String MOVENOTHING = "N";
protected final static String RETURNED = "R";
protected final static String FAILEDRETURN = "r";
protected final static String SEARCHING = "S";
protected final static String DEAD = "D";
protected final static String SLEEPING = "N";
protected final static String EXIT = "EXIT";
protected final static String ALIVE = "A";
protected enum Status{SEARCHING, DEAD, RETURNED}
protected enum Move{RETURN, SEARCH, NOTHING}
protected int index;
protected int day;
protected int turnNum;
protected int howManyTeams;
protected int howManyWillDieTodayAtMost;
protected int howManyHaveDiedToday;
protected int howManyEnemyPlayers;
protected int howManyAliveEnemyPlayers;
protected int howManyEnemyTeams;
protected int howManyDeadEnemyPlayers;
protected int howManyReturnedEnemyPlayers;
protected int howManySearchingEnemyPlayers;
protected int howManyTotalPlayers;
protected int howManyTotalAlivePlayers;
protected int howManyTotalDeadPlayers;
protected int howManyTotalReturnedPlayers;
protected int howManyTotalSearchingPlayers;
protected int howManyOwnAlivePlayers;
protected int howManyOwnDeadPlayers;
protected int howManyOwnReturnedPlayers;
protected int howManyOwnSearchingPlayers;
protected Status[] statuses = new Status[5];
protected Status[][] allStatuses = null;
protected List<Status[][]> allDayStatuses = null;
protected List<List<Status[][]>> allTimeStatuses = new ArrayList<>();
protected BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
public static void main (String args[]) throws Exception{
new MorningBirds().start();
}
public void start() throws Exception{
index = Integer.parseInt(in.readLine().split("\\s")[1]);
Arrays.fill(statuses, Status.SEARCHING);
while(true){
String[] input = in.readLine().split("\\s");
if (input[0].equals(ENDTURN) || input[0].equals(ENDDAY)){
updateStatus(input);
} else if (input[0].equals(EXIT)){
return;
} else if (input[0].equals(STARTDAY)){
updateDay(input);
} else if (input[0].equals(STARTTURN)){
updateTurn(input);
doTurn(input);
}
}
}
protected void updateStatus(String[] input){
if (allStatuses == null && input[0].equals(ENDTURN)){
allStatuses = new Status[input.length - 2][5];
for (Status[] enemyStatus : allStatuses){
Arrays.fill(enemyStatus, Status.SEARCHING);
}
howManyTeams = input.length - 2;
howManyEnemyTeams = input.length - 3;
howManyTotalPlayers = howManyTeams * 5;
howManyTotalAlivePlayers = howManyTotalPlayers;
howManyTotalSearchingPlayers = howManyTotalAlivePlayers;
howManyAliveEnemyPlayers = howManyTotalPlayers - 5;
howManyEnemyPlayers = howManyEnemyTeams * 5;
howManyOwnAlivePlayers = 5;
howManyOwnSearchingPlayers = 5;
howManySearchingEnemyPlayers = howManyAliveEnemyPlayers;
}
for ( int j = 0; j < howManyTeams; j++){
String[] stats = input[j + 2].split(",");
for(int i = 0; i < 5; i++){
switch (stats[i]){
case "R":
case "N":
if (allStatuses[j][i] != Status.RETURNED){
howManyTotalReturnedPlayers++;
howManyTotalSearchingPlayers--;
if (j == index - 1) {
howManyOwnReturnedPlayers++;
howManyOwnSearchingPlayers--;
} else {
howManyReturnedEnemyPlayers++;
howManySearchingEnemyPlayers--;
}
}
allStatuses[j][i] = Status.RETURNED;
break;
case "A":
case "S":
if (allStatuses[j][i] != Status.SEARCHING){
howManyTotalReturnedPlayers--;
howManyTotalSearchingPlayers++;
if (j == index - 1) {
howManyOwnReturnedPlayers--;
howManyOwnSearchingPlayers++;
} else {
howManyReturnedEnemyPlayers--;
howManySearchingEnemyPlayers++;
}
}
allStatuses[j][i] = Status.SEARCHING;
break;
case "r":
case "D":
if (allStatuses[j][i] != Status.DEAD){
howManyTotalAlivePlayers--;
howManyTotalDeadPlayers++;
howManyHaveDiedToday++;
howManyTotalSearchingPlayers--;
if (j == index - 1){
howManyOwnAlivePlayers--;
howManyOwnDeadPlayers++;
howManyOwnSearchingPlayers--;
} else {
howManyAliveEnemyPlayers--;
howManyDeadEnemyPlayers++;
howManySearchingEnemyPlayers--;
}
}
allStatuses[j][i] = Status.DEAD;
break;
default:
break;
}
}
}
statuses = allStatuses[index - 1];
if (input[0].equals(ENDTURN)){
allDayStatuses.add(allStatuses.clone());
}
if (input[0].equals(ENDDAY)){
Status[][] statusesToAdd = new Status[howManyTeams][5];
for (int i = 0; i < statusesToAdd.length; i++){
for (int j = 0; j < statusesToAdd[i].length; j++){
if (allStatuses[i][j] == Status.SEARCHING){
statusesToAdd[i][j] = Status.RETURNED;
} else {
statusesToAdd[i][j] = Status.DEAD;
}
}
}
while (turnNum <= 30){
allDayStatuses.add(statusesToAdd.clone());
turnNum++;
}
allTimeStatuses.add(allDayStatuses);
}
}
protected void updateDay(String[] input) throws Exception{
day = Integer.parseInt(input[1].split("/")[0]);
howManyWillDieTodayAtMost = Integer.parseInt(input[1].split("/")[1]);
howManyHaveDiedToday = 0;
allDayStatuses = new ArrayList<>();
if (day == 1){
Arrays.fill(statuses, Status.SEARCHING);
howManyOwnAlivePlayers = 5;
howManyOwnSearchingPlayers = 5;
}
}
protected void updateTurn(String[] input){
turnNum = Integer.parseInt(input[1]);
}
protected void doTurn(String[] input){
Move[] moves = new Move[5];
for (int i = 0; i < 5; i++){
if (statuses[i] == Status.DEAD ||
statuses[i] == Status.RETURNED) {
moves[i] = Move.NOTHING;
continue;
} else {
moves[i] = doMove(i);
}
}
String[] outputs = new String[5];
for (int i = 0; i < 5; i++){
switch (moves[i]){
case SEARCH:
outputs[i] = MOVESEARCH;
break;
case RETURN:
outputs[i] = MOVERETURN;
break;
case NOTHING:
outputs[i] = MOVENOTHING;
}
}
String totalOutput = "";
for(String output : outputs){
if (totalOutput != ""){
totalOutput += ",";
}
totalOutput += output;
}
System.out.println(totalOutput);
}
//Implement this method differently for different
//strategies.
public Move doMove(int playerNumber){
if (turnNum >= 15){
return Move.RETURN;
}
return Move.SEARCH;
}
/**
* Returns the status of one of your players.
* Your players have numbers 1 to 5 inclusive.
* Throws exception if number is outside range.
*
*/
protected Status getStatus(int player){
if (player > 5 || player < 1){
throw new IllegalArgumentException(
"getStatus(" + player +") failed.");
}
return statuses[player - 1];
}
/**
* Returns the status of a player in a team.
* Team numbers start with 1 inclusive.
* Players have numbers 1 to 5 inclusive.
* Throws exception if argument player is outside range.
* Throws exception if argument team is less than 1 or is greater
* than the number of teams.
* Returns Status.SEARCHING if day == 1 and turnNum == 1 and argument
* team >= 1.
*/
protected Status getStatus(int team, int player){
if (team < 1 || player < 1 || player > 1 ||
(team > howManyTeams && day == 1 && turnNum == 1)){
throw new IllegalArgumentException(
"getStatus(" + team + ", " + player + ") failed.");
}
if (day == 1 && turnNum == 1 && team >= 1){
return Status.SEARCHING;
}
return allStatuses[team - 1][player - 1];
}
/**
* Returns the status of a player in a team at the end of argument
* turn.
* Team numbers start with 1 inclusive.
* Players have numbers 1 to 5 inclusive.
* Turns have numbers 0 to 30 inclusive.
* Status at turn 0 is equal to status at start of turn 1.
* Throws exception if argument turn hasn't happened yet.
* Throws exception if argument player is outside range.
* Throws exception if argument team is less than 1 or is greater
* than the number of teams.
*/
protected Status getStatus(int turn, int team, int player){
if (turn == 0){
if (day == 1){
return Status.SEARCHING;
} else {
return getStatus(day - 1, 30, team, player);
}
}
if (turnNum <= turn || turn < 0|| player > 5 || player < 1 ||
team < 1 || team > howManyTeams){
throw new IllegalArgumentException("getStatus(" + turn +
", " + team + ", " + player + ") failed.");
}
return allDayStatuses.get(turn - 1)[team - 1][player - 1];
}
/**
* Returns the status of a player in a team at the end of argument
* turn on the day of argument day.
* Team numbers start with 1 inclusive.
* Players have numbers 1 to 5 inclusive.
* Turns have numbers 0 to 30 inclusive.
* Days have numbers 1 inclusive and up.
* Status at turn 0 is equal to status at start of turn 1.
* Throws exception if argument day hasn't ended yet or is less
* than one.
* Throws exception if argument turn is out of range.
* Throws exception if argument player is outside range.
* Throws exception if argument team is less than 1 or is greater
* than the number of teams.
*/
protected Status getStatus(int day, int turn, int team, int player){
if (turn == 0){
if (day == 1){
return Status.SEARCHING;
} else {
return getStatus(day - 1, 30, team, player);
}
}
if (this.day <= day || day < 1 || turn > 30 || turn < 0 ||
player > 5 || player < 1 ||
team < 1 || team > howManyTeams){
throw new IllegalArgumentException("getStatus(" + day + ", "
+ turn + ", " + team + ", " + player + ") failed.");
}
return allTimeStatuses.get(day - 1).get(turn - 1)[team - 1][player - 1];
}
}
```
**Edit:** Made it so anyone could easily subclass it. Just redefine `doMove(int playerNumber)` for your own bot. I have added several helpful fields and methods. I have extensively tested it. It does **not** save the statuses from previous simulations. Please tell me if there are any problems.
Compile with: `javac ./players/MorningBirds/MorningBirds.java`
Run with: `java players.MorningBirds.MorningBirds`
[Answer]
# Randomizers - Ruby
Just to mess up statistics driven bots, the randomizers are quite unpredictable. All of them do return at once, at a random turn in an attempt to strand others.
(Not influenced by other players.)
```
def min(a,b);(a<b)?a:b;end
x=""
r=0
while x != "EXIT"
x=gets.chomp
if x =~ /^START_DAY/
r = min(rand(30),rand(30))
end
if x =~ /^START_TURN (\d*)/
puts ($1.to_i>r)?'R,R,R,R,R':'S,S,S,S,S'
end
end
```
[Answer]
# Wandering Fools, Python 2
This is a simple Python bot that sends out the servants until a preset "goback" time is reached, then they try to enter camp and stay until the next day.
It is also a basic framework for more complex bots that others may wish to use. It is, however, untested with the judge engine, so let me know if I have made an error.
## Program
```
import sys
from random import randint, choice
team = range(5)
while True:
inp = sys.stdin.readline().split()
cmd = inp.pop(0)
if cmd == 'INDEX':
teamnum = int(inp[0]) - 1 # using zero based indexing
elif cmd == 'START_DAY':
daynum, deadnum = [int(v) for v in inp[0].split('/')]
# Set up strategy for the day:
goback = [randint(5,25) for i in team]
elif cmd == 'START_TURN':
turn = int(inp[0])
# Output actions [R]eturn, [S]earch, [N]othing here:
actions = ['S' if turn < goback[i] else 'R' for i in team]
sys.stdout.write( (','.join(actions)) + '\n' )
sys.stdout.flush()
elif cmd == 'END_TURN':
endturn = int(inp.pop(0))
status = [v.split(',') for v in inp] # R,r,S,D,N
# [R]eturned, [r]ejected, [S]earching, [D]ead, [N]othing
mystatus = status[teamnum]
elif cmd == 'END_DAY':
endturn = int(inp.pop(0))
alive = [v.split(',') for v in inp] # [A]live or [D]ead
myalive = alive[teamnum]
elif cmd == 'EXIT':
sys.exit(0)
```
## Command
```
python WanderingFools.py
```
Edit: Changed action deciding code after rule clarification.
[Answer]
**Evolved**
I used Genetic Programming (through JGAP) to make this bot. It came up with a simple answer that beats all others (barely).
```
package players.Evolved;
import players.MorningBirds.*;
import java.util.*;
public class Evolved extends MorningBirds{
List<Integer> scrambled = new ArrayList<>();
public static void main(String[] args) throws Exception{
new Evolved().start();
}
public Evolved() throws Exception{
super();
}
@Override
public MorningBirds.Move doMove(int playerNum){
if (!(howManyTotalSearchingPlayers < (turnNum - getScrambled(index)))){
return Move.SEARCH;
} else {
return Move.RETURN;
}
}
@Override
protected void updateStatus(String[] input){
super.updateStatus(input);
if (input[0].equals(ENDTURN) && (Integer.parseInt(input[1]) == 1)){
for (int i = 1; i <= howManyTeams; i++){
scrambled.add(i);
}
Collections.shuffle(scrambled);
}
}
public int getScrambled(int in){
if (in > scrambled.size() || in < 1 ){
return in;
}
return scrambled.get(in - 1);
}
}
```
Compile with: `javac players/Evolved/Evolved.java`
Run with: `java players.Evolved.Evolved`
**Edit:** Grrr... Bob messed me up!!!
**Edit:** Yay!!! Bob, got killed by a nasty plague!!!
[Answer]
# SlowReturners - Ruby
Sends one servant back every 5 turns.
```
x=""
while x != "EXIT"
x=gets.chomp
if x =~ /^START_TURN (\d*)/
puts (1..5).map{|i|(i<=$1.to_i/5)?"R":"S"}.join(",")
end
end
```
[Answer]
# **Plague**
Plague is a disease. It is not rational. It is predictable. Diseases cannot collect treasure, nor do they care for treasure. Plague makes other players sick. The wise ones stay home and forget about treasure. The foolish ones are always foolish and will never get much treasure. Evolved is (fortunately) immune to Plague. He is also wise. He goes and collects treasure, and does not die.
```
package players.Plague;
import players.MorningBirds.MorningBirds;
public class Plague extends MorningBirds{
public static void main(String[] args) throws Exception{
new Plague().start();
}
public Plague() throws Exception{
super();
}
@Override
public MorningBirds.Move doMove(int playerNum){
if (day > howManyTotalDeadPlayers){
return Move.SEARCH;
} else {
return Move.RETURN;
}
}
}
```
Compile with: `javac players/Plague/Plague.java`
Run with: `java players.Plague.Plague`
*Bob and Statisticians are now resistant to plague.*
] |
[Question]
[
Given an ASCII art with simple closed paths using `|` and `-` (pipes and dashes), output a random point inside the boundary.
Eg. given:
```
---- ----
| |- --- => |12|- ---
| | | | |345| |6|
----- --- ----- ---
Any point 1-6 should have an equal probability of being printed.
```
## Specs
* Take a string, list of strings or a matrix containing `|`, `-`,
* Output either the ASCII art with a space replaced by a constant character other than a pipe, dash or space or print the two-dimensional/one-dimensional index.
* All adjacent pipe-dash pairs are connected
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins
## Test cases
```
---
|1|
---
----
|12|- ---
|345| |6|
----- ---
---
|1|
--2--
|345|
-----
-------
|1---2|
|3|4|5|
|6---7|
-------
--- ---
|1| |2|
|3---4|
|56789|
---A---
|B|
---C---
|DEFGH|
|I---J|
|K| |L|
--- ---
---
|1|
---
--- ---
|2| |3| (4 simple closed paths)
--- ---
---
|4|
---
```
[Answer]
# MATL, ~~19~~ ~~18~~ ~~17~~ 15 bytes
```
36yy>t0ZI-flZr(
```
*2 bytes saved thanks to @LuisMendo*
Input is provided as a 2D character array and the random point is replaced by `$`
Try it out at [MATL Online](https://matl.io/?code=36yy%3Et0ZI-flZr%28&inputs=%5B%27---+---%27%3B%27%7C+%7C+%7C+%7C%27%3B%27%7C+---+%7C%27%3B%27%7C+++++%7C%27%3B%27---+---%27%3B%27++%7C+%7C++%27%3B%27---+---%27%3B%27%7C+++++%7C%27%3B%27%7C+---+%7C%27%3B%27%7C+%7C+%7C+%7C%27%3B%27---+---%27%5D&version=22.7.4)
**Explanation**
```
% Implicitly retrieve the 2D character array input
36 % Push the literal 36 (ASCII for $) to the stack
y % Make a copy of the character array
y % Copy the value 36
> % Create a boolean 2D array where all values with ASCII > '$' (36) are TRUE
% these are the elements == '|' or '-' that make up the boundary
t % Duplicate this boolean 2D array
0ZI % Perform the morphological fill operation to set the value of all elements
% within the boundaries to TRUE also
- % Subtract the boundary to leave TRUE values only for elements that are
% inside the boundary
f % Find the index values of all remaining TRUE values
lZr % Pick one at random
( % And assign the '$' (36) to that element in the original input
% Implicitly display the result
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 32 bytes
```
2(ðvø.∩)∩ðÞIk□"λhn÷:k□ẊṠJ↔";Ẋ÷F℅
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLilqHGm2Y7d8KoUyIsIjIow7B2w7gu4oipKeKIqcOww55Ja+KWoVwizrtobsO3OmvilqHhuorhuaBK4oaUXCI74bqKw7dG4oSFIiwiIiwiIC0tLSBcbiB8IHwgXG4tLSAtLVxufCAgIHxcbi0tLS0tIl0=)
Expects a rectangular matrix containing `|`, `-`, . Returns a 2D index.
## How?
Surround the input with spaces from all sides.
```
2( ) # repeat twice:
ð # push a space
vø. # vectorized surround
∩ # transpose
∩ # transpose
```
Find the coordinates of all spaces that are in the outside component.
```
ðÞI # get the coordinates of all spaces
k□ # push cardinal directions [[0,1],[1,0],[0,-1],[-1,0]]
" # pair
λ ;Ẋ # apply the following function until a fixed point:
Takes a pair [coordinates of all spaces, coordinates spaces reached so far]
h # head
n # argument
÷ # push each to stack
: # duplicate
k□ # push cardinal directions [[0,1],[1,0],[0,-1],[-1,0]]
Ẋ # cartesian product
Ṡ # vectorising sum
J # join the top two item on the stack
↔ # keep only those items of a that are in b
" # pair
```
Now we have the pair `[coordinates of all spaces, coordinates of spaces reachable from one of the sides]`.
```
÷ # push each to stack
F # remove items from a that are in b
℅ # choose a random item
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~82~~ ~~81~~ 77 bytes
```
WS⊞υι≔⌈EυLιθP⭆⪫υ¶⎇⁼ι ψι↖B⁺²θ⁺²Lυψ¤_↘TθLυFLυFθ«Jκι¤ »UMKA⎇⁼ι_ψι≔ΦKA⁼ι θ§≔θ‽Lθ#
```
[Try it online!](https://tio.run/##bVDJagMxDD3HX2GmFxkylx6bU7pBQgIhTW@FMDTOjImXGY@dhabfPpXqbIXKGFvS03uSPqvCf7pCd92uUlpyGNk6hrfglS1BCD6LbQWxz5UYsGHbqtLCtNgrEw2@NWUm0pahAiWE6PMGYdOog6qRIEDiIeDYKUvo7MNmiFtIbwt/gJcmFroFhQlO8QMpCSJxWwkP7/VErgO6j24PMx1buCeNPj//T@KRtA@Ie1VaQ7bMLgzPbmfnqqyIZOGVgea2aMDWznO4Bviv3wj@xXrjaOqFg00avpeoOVF/MxzpyRlT2BXMpNwMMfX/VMvrVJcFIlOQ/rbw7xpOe0zoYRjZldxT33OUc@bcbUO47A776Tqe5zldxo/psOTjZUeejGInY12@1T8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings and marks the random selection with a `#`. Explanation:
```
WS⊞υι≔⌈EυLιθ
```
Input the strings and calculate the width of the ASCII art.
```
P⭆⪫υ¶⎇⁼ι ψι
```
Output the art but with spaces replaced with background.
```
↖B⁺²θ⁺²Lυψ¤_↘TθLυ
```
Add extra background padding, fill it with `_`s, and then remove the extra padding.
```
FLυFθ«Jκι¤ »
```
Replace any remaining background with spaces.
```
UMKA⎇⁼ι_ψι
```
Replace any remaining padding with background.
```
≔ΦKA⁼ι θ§≔θ‽Lθ#
```
Randomly replace a space with a `#`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~81~~ ~~78~~ 77 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.B€SðQ2Fø1δ.ø}©˜ƶ®gäΔ2Fø0δ.ø}2Fø€ü3}®*εεÅsyøÅsM]¤θ©δÜ€¦˜0K®Êðs.;ÐÏSāDΩQ·.;0ð:
```
Uses `2` as random character.
[Try it online](https://tio.run/##yy9OTMpM/f9fz@lR05rgwxsCjdwO7zA8t0Xv8I7aQytPzzm27dC69MNLzk0BiRtAxEFMoOrDe4xrD63TOrf13NbDrcWVh3cASd/YQ0vO7Ti08tyWw3OASg4tOz3HwPvQusNdhzcU61kfnnC4P/hIo8u5lYGHtutZGxzeYPX/v5KSkq6urgIQc9UogCGQBomAaBCo4YLJK4BlEaohsgjVNcjyQHP/6@rm5evmJFZVAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6nDpRSUmJeSn6uQX1oCE3RR@q/n9KhpTfDhDYFGbod3GJ7bond4R@2hlafnHNt2aF364SXnpoDEDSDiICZQ9eE9xrWH1mmd23pu6@HW4srDO4Ckb@yhJed2HFp5bsvhOUAlh5adnmPgfWjd4a7DG4r1rA9PONwffKTR5dzKwEPb9awNDm@w@q@kF6ZzaJv9/2glXV3dmLwahZqYPCBLSUdB6VFDty5UUKFGV0FBAcZRgGCISl2oDEgHRAVMSgGuHKoQpEQXAkASIK01YCshOuAiUDVw5XBTahQwHKkLtkcXmzEgTTDLoS6DuxrhFwU0PTUoasC@gnldAeZtuAjE9woIFygghYwCikasJijF/tfVzcvXzUmsqgQA).
**Explanation:**
Step 1: Pad the input with trailing spaces to make it a rectangle, and add an additional border of spaces. Then convert it to a matrix of 0s for `|` and `-`, and give each space an unique 1-based integer value.
```
.B # Blockify the (implicit) multi-line input by adding trailing spaces,
# and then split it on newlines
€S # Convert each line to a list of characters
ðQ # Check for each character whether it's a space (1 if space; 0 otherwise)
2Fø1δ.ø} # Add a border of 1s:
2F } # Loop 2 times:
ø # Zip/transpose; swapping rows/columns
δ # Map over each inner list/row:
1 .ø # Surround it with a leading/trailing 1
© # After the loop: store the matrix in variable `®` (without popping)
˜ # Flatten it to a single list
ƶ # Multiply each value by its 1-based index
®g # Push the length (aka amount of rows) of matrix `®`
ä # Split the list of integers back into a matrix of that many rows
```
[Try just this first step online.](https://tio.run/##yy9OTMpM/f9fz@lR05rgwxsCjdwO7zA8t0Xv8I7aQytPzzm27dC69MNL/v9XUlJ61NCtCwRcNQoKNboKCgpQtgIE13CBJKHiQNX/dXXz8nVzEqsqAQ)
Step 2: Flood-fill the positive values in the matrix to identify the islands of spaces:
```
Δ # Loop until it no longer changes to flood-fill:
2Fø0δ.ø} # Add a border of 0s around the matrix:
2F } # Loop 2 times:
ø # Zip/transpose; swapping rows/columns
δ # Map over each row:
0 .ø # Add a leading/trailing 0
2Fø€ü3} # Convert it into overlapping 3x3 blocks:
2F } # Loop 2 times again:
ø # Zip/transpose; swapping rows/columns
€ # Map over each inner list:
ü3 # Convert it to a list of overlapping triplets
®* # Multiply each 3x3 block by the value in matrix `®`
# (so the 0s remain 0s)
εεÅsyøÅsM # Get the largest value from the horizontal/vertical cross of each 3x3
# block:
εε # Nested map over each 3x3 block:
Ås # Pop and push its middle row
y # Push the 3x3 block again
ø # Zip/transpose; swapping rows/columns
Ås # Pop and push its middle rows as well (the middle column)
M # Push the flattened maximum of the entire (scoped) stack,
# which is the flattened maximum of the cross of the current 3x3 block
] # Close the nested maps and flood-fill loop
```
[Try just the first two steps online.](https://tio.run/##yy9OTMpM/f9fz@lR05rgwxsCjdwO7zA8t0Xv8I7aQytPzzm27dC69MNLzk0BiRtAxEFMoOrDe4xrD63TOrf13NbDrcWVh3cASd/Y//@VlJQeNXTrAgFXjYJCja6CggKUrQDBNVwgSag4UPV/Xd28fN2cxKpKAA)
Step 3: Remove the border and all right-padded trailing space-integers. Then replace that same value to 0s and every other value to 1s in the input-string.
```
¤ # Push the last row (without popping the matrix)
θ # Pop and push its last item
© # Store this space-integer in variable `®` (without popping)
δ # Map over each row with this space-integer as argument:
Ü # Remove all trailing space-integers from the row
€ # Map over each row again:
¦ # Remove its first character (the leading column of space-integers)
˜ # Then flatten the matrix to a list
0K # Remove all 0s (the "-" and "|")
®Ê # Check for each remaining spaces-value that it's NOT equal to `®`
# (1 if it's a space inside a boundary; 0 if it's a space outside boundary)
ð # Push a space character " "
s # Swap so this list of 0s/1s is at the top
.; # Replace all spaces in the (implicit) input one by one with these 0s/1s
```
[Try just the first three steps online.](https://tio.run/##yy9OTMpM/f9fz@lR05rgwxsCjdwO7zA8t0Xv8I7aQytPzzm27dC69MNLzk0BiRtAxEFMoOrDe4xrD63TOrf13NbDrcWVh3cASd/YQ0vO7Ti08tyWw3OASg4tOz3HwPvQusNdhzcU61n//6@kpPSooVsXCLhqFBRqdBUUFKBsBQiu4QJJQsWBqv/r6ubl6@YkVlUCAA)
Step 4: Transform all `1`s into `0`s, except for a random one, which we'll make `2` instead.
```
Ð # Triplicate the modified input-string
Ï # Pop two copies, and only keep all 1s
S # Convert this string of 1s to a list of 1s
ā # Push a list in the range [1,length] (without popping the list of 1s)
D # Duplicate it
Ω # Pop and push a random integer from this list
Q # Check which one in the list is equal to it
# (so we have a list of 0s with one random 1)
· # Double each, so the 1 becomes a 2 (0s remains 0)
.; # Then replace all 1s in the modified input one by one with these 0s/2s
```
[Try just the first four steps online.](https://tio.run/##yy9OTMpM/f9fz@lR05rgwxsCjdwO7zA8t0Xv8I7aQytPzzm27dC69MNLzk0BiRtAxEFMoOrDe4xrD63TOrf13NbDrcWVh3cASd/YQ0vO7Ti08tyWw3OASg4tOz3HwPvQusNdhzcU61kfnnC4P/hIo8u5lYGHtutZ//@vpKT0qKFbFwi4ahQUanQVFBSgbAUIruECSULFgar/6@rm5evmJFZVAgA)
Step 5: Finally replace all `0`s back to spaces. After which we output the result.
```
0ð: # Replace every 0 back to a space
# (after which the result is output implicitly)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org),~~181 180~~ 178 bytes
```
f=x=>[...x+0,n=0].map(_=>{for(i in x)for(j in e=x[i])for(k of'0123')(x[+i+--k%2]||++n)[+j+--k%2]?r=n=>Math.random()*n|0:1/e[j]?e[j]=0:0})&&x[p=r(x.length)][q=r(n)]<'!'?[p,q]:f(x)
```
[Try it online!](https://tio.run/##NZBBToQwGIX3nKIuHFqBTmHUBVo4gSfoNEKgMGU6LQPENLEm7r2lF0Egzr94@b73715XfpRjNch@irSpxTw31NKMYYxtQEJNCceXsofvNPtszAAlkBpYtGK3oqCWSb75GZjGJ3Fy8BG0LJBBFJ3vE@5cEGjEgu7f84Fqmr2V0wkPpa7NBaIH7Uga7wXreL4GJSn5QrudZT0doMVK6HY6Ic6ui2rEX/07P2d9eOVpAy2aX7zK6NEogZVpYQML7/f7J1rOc3HiIgDAxofHJ7ewe3be@rz1BR5Er8pKwP2x3rehD3yERyWXIg6jeOFeyak46mJb4rYORwjNfw "JavaScript (Node.js) – Try It Online")
Didn't expect it runs in time
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 114 bytes
```
^
_¶
$
¶_
P`.+
.+
_$&_
+`_ | _|(?<=(.)*)( |_)(.*¶(?<-1>.)*(?(1)$)(?!\2))[ _]
_$3_
@`
#
^_+¶_|_+¶_+$|_+(¶)_
$1
_
```
[Try it online!](https://tio.run/##LY0xDsIwDEX3fwojImQ3SqXACoQjsAN1GRhYGCrGnCsHyMWC2/Ltb8tPsj29vu/PM7Y2QGuBQy2K69h7WKrbKfyolEkzp@OJe@mEKatw39ViKMSzMU4cxQmnzX0vciN92O5BcRkJWwzq7WpeqnfWuRZRuAgFtUYhhNmwN0tgnc3ItGpmf/0A "Retina – Try It Online") Marks the random selection with a `#`. Explanation:
```
^
_¶
$
¶_
P`.+
.+
_$&_
```
Pad the input and surround it with `_`s on all sides.
```
+`_ | _|(?<=(.)*)( |_)(.*¶(?<-1>.)*(?(1)$)(?!\2))[ _]
_$3_
```
Flood fill the `_`s so that only interior spaces remain.
```
@`
#
```
Randomly replace one with the output marker.
```
^_+¶_|_+¶_+$|_+(¶)_
$1
_
```
Remove the padding and replace any remaining `_`s with spaces.
[Answer]
# Python3, 770 bytes:
```
import random as U
E=enumerate
def T(b,x,y):
D={}
for i in b:D[i[x]]=D.get(i[x],[])+[i[y]]
return D
def B(b):
P=[(x,y)for x,r in E(b)for y,k in E(r)if' '!=k];p=[*P]
while p:
q=[(r:=p.pop(0),[r])]
while q:
F=0
(x,y),r=q.pop(0)
for X,Y in[(1,0),(-1,0),(0,-1),(0,1)]:
j,k=x+X,y+Y
V=(j,k)
if 0<=j<len(b)and 0<=k<len(b[0])and(len(r)<2 or V!=r[-2]):
if(j==x and'-'==b[j][k])or(k==y and'|'==b[j][k])or b[x][y]!=b[j][k]:
if V in r:yield r;p=[*({*p}-{*r})];F=1;break
elif V in P:q+=[(V,[*r,V])]
if F:break
def f(b):
K=[]
for i in B(b):
Q,W=T(i,0,1),T(i,1,0)
K+=[(x,y)for x,r in E(b)for y,k in E(r)if' '==k and x in Q and min(Q[x])<=y<=max(Q[x])and y in W and min(W[y])<=x<=max(W[y])]
x,y=U.choice(K)
b[x][y]='*'
return b
```
[Try it online!](https://tio.run/##lZLRT9swEMafl7/i4CV261RteZlK72UqvCBNIEEBedbUQDrctEnqBi0R5W/v7pwENolJ20PlfOfffba/a1GXT3l28rlwh4PdFLkrwS2yx3wDix3cBGeYZM@bxC3KJHhMlnAtYlWpWk4CmOHLawDL3IEFm0E8mWmrK2NwNviRlIK/lTayT9XamABcUj67DGbe54uI2eMStWA7dqmUY58z2mFZq7SRTtplCOERpua0QN27JK@fT3adQEEOsCULN8FiUOSFGEqlnZFEtMiWETjHIS/@KOVw27Jc46Pu1D0dpcVIUb@ImmWoopFfRtJ4E1ipFKv@nar7917PUVDJu4BdwnCKq@k6yej@FCDLtJF6aLgiWDg5HQMdOT9Cp6OxkY019YsVYgXEhVGIGOuV0amRuRMpYu3r@z/qEFPAlOxRV2ud@CpzTs5NapusH8H51MRLr3iNXnruVZrTcxydxi5ZpG1Lsu6aLifbPgU6V7rn1LxJkh3PJw3Ps1s2s7tAbX6bfztRuFK3eC2s4uAUf3CcVL/o//usEVN@MVRcvfKfG5uJK3qxnGI9xc2iahRv1UzdvlG3FApRVUN5Rfekk/Fm8PCU24dEXNCF2vgw7IVv/834sMPj4@MgiqJgD3u/st6NunLUBAa0DXsWDUrC/3xL1NV969i3soaACSAEuqYGb8CTtzMaT@7Y8zW8b6e7fWb9NMr8@8KVoqTwP7XP0LpnzftklnZdJk58zbNEQTnYFWtbivBbFkoKJgjeOdF67SSbFc5mxIWDVU6pWik/REf/wY7/xn4En3wMH34B)
[Answer]
# JavaScript (ES11), 168 bytes
Expects a matrix of characters and returns the coordinates `[x,y]` of a cell.
```
m=>(o=[])[m.map((r,y)=>r.map((C,x)=>(g=(x,y,r=m[y],c=r?.[x])=>1/c?[-1,0,1,2].every(d=>g(x+d%2,y+~-d%2),r[x]=g)|(r[x]=c):!!c/C)(x,y)?n=o.push([x,y]):0))|Math.random()*n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jZC_btswEMbRVU9xCVCIF1OMnalIQHsIWnTplFHWIEiUrEIiXUouLJTti3QJigbo63Rsnyb8YynwFgEi77778fgdf_6WqhSPvyr-dBiq5N2_Px1fE8XTDNOOdfmeEE1H5Gsdknt6tAmpOTnSkWrepWNGC643LD1mtrK6LjZpsqJLuqI3GRNfhR5Jydc1OS7Ktzd0XPxI7I5UW57XaIgPCry9uCiu79G1xY3kiu0P_Y6kNs3wdoloPuXDjulclqojeCWzk9-_Wnw5NFqQuOpjZFrk5YemFQ-jLMgS2aAeBt3ImiDr920zkMut3MpLZJXS7_NiR3rga_gWAbRigA449C-gxdzQHkkZY32GdyfSGoMxs3hFOi-6h7CTWCW-ip1QKNmrVrBW1SS8pHZ9NPusGkniGPEUbWWMsAC_30XfMQz2-P_NxyRJIgMmcrtbEgifFcG4JAA28b8Hk0mP3AqR08EWYEIDFPqF844z7iLfY8qnugtOF50Dxnsxc322MNuCM9qc1SMIPv08EPzP8aRPI0_Xw8ucs_6KPuFFnwE)
(with some post-processing to insert an asterisk at the chosen position)
### How?
For each space in the input matrix, we process a recursive flood-fill to test whether we can 'escape' through a boundary. We keep track of each starting point for which this is not the case and return one of them.
### Commented
```
m => // m[] = input matrix
(o = [])[ // start with o[] set to an empty array
m.map((r, y) => // for each row r[] at index y in m[]:
r.map((C, x) => // for each character C at index x in r[]:
( g = ( // g is a recursive function taking:
x, y, // (x, y) = current position
r = m[y], // r[] = current row
c = r?.[x] // c = character at this position
) => //
1 / c ? // if c is a space:
[-1, 0, 1, 2] // array of directions
.every(d => // for each direction d:
g( // do a recursive call:
x + d % 2, // add dx to x
y + ~-d % 2 // add dy to y
), // end of recursive call
r[x] = g // start by invalidating the current cell
) | // end of every()
(r[x] = c) // restore the current cell
: // else:
!!c / C // return a truthy value (1/0 = +∞) if and
// only if c is defined and C is a space
)(x, y) ? // initial call to g; if truthy:
n = // update n to the length of o[] ...
o.push([x, y]) // ... once [x, y] has been added to o[]
: // else:
0 // do nothing
) // end of inner map()
) // end of outer map()
| Math.random() * n // pick a random item from o[]
] //
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 238 bytes
```
e=enumerate
a,*r={i+1j*j:c<'!'for i,r in e(open(0))for j,c in e(r)},
while q:=[i for i in a if a[i]][:1]:
g,*v=1,
while q:
c,*q=q;a[c]=0;v+=[c]
for i in-1,1,-1j,1j:q+=[c+i]*a.get(c+i,0);g&=c+i in a
r+=v*g
print({*map(str,r)}.pop())
```
[Try it online!](https://tio.run/##TY5BbsMgEEX3nGK6SQAPkVE3kV1OYrFAFnGwGoyp46qKe3YXHFkpo9F8/fdhCD/TdfDv5xDX1Srr7zcbzWSJQR7VwxWy533VfhzfjpchgsPUHiwdgvW0ZCybPbZPM7JfJN9X92lhrFTjYLuSmQF3AdM4rZtK6opAh3xWEgnscQLQIh/VWJum1aqs50Ilkez9ESFRopA9yr4aMyyc5ubU2YkmiSWru4NKattHIBZq5h0J0fmJPvjNBPo1RUx/PIUhUMbWVQgBqckCW6WZnTzzWcjOYaOv9JO@0st//gc "Python 3.8 (pre-release) – Try It Online")
Flood-fills from every space position and stores the ones that do not go out of bounds. Then it relies on hash randomization for strings to pop a random coordinate from the final set.
] |
[Question]
[
The standard way to round numbers is to choose the nearest whole value, if the initial value is exactly halfway between two values, i.e. there is a tie, then you choose the larger one.
However where I work we round in a different way. Everything is measured in powers of two. So wholes, halves, quarters, eights, sixteenths etc. This means our measurements are always a binary fraction. We also round to binary fractions. However when the value is exactly halfway between, instead of rounding up we round to the "nicer" number.
For example if I measure 5/8 but I need to round it to the nearest fourth, both 2/4 and 3/4 are equally close to 5/8, but 2/4 = 1/2 which is a nicer number so we round to 1/2.
If I measured 7/8 and needed to round to the nearest fourth I would round up to 8/8 = 1.
To put it concretely if we express every number as \$x\times2^n\$ where \$x\$ is odd, then we round towards the number with the larger \$n\$.
Going back to the example: I measure 5/8 and I need to round it to the nearest fourth. The values I can choose are \$2/4=1\times2^{-1}\$ and \$3/4=3\times 2^{-2}\$, since -1 is larger than -2 we round towards that.
When both the options are fully reduced fractions you can think of this as rounding towards the fraction with the smaller denominator. However this intuition becomes a little bit strained when the options are whole numbers.
## Challenge
In this challenge you will receive 3 numbers. An odd positive integer \$x\$, an integer \$n\$ and an integer \$m\$. You must round \$x\times2^n\$ to the nearest integer multiple of \$2^m\$ using the process described, and output the result as a binary fraction. This can be either a native binary fraction or the \$x\times2^n\$ format used for the input. The input will always be fully reduced so that the numerator, \$x\$, is odd, however you are not required to do so for your output.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes.
## Test cases
| \$x\$ | \$n\$ | \$m\$ | ⇒ | \$x\$ | \$n\$ |
| --- | --- | --- | --- | --- | --- |
| 5 | -3 | -2 | ⇒ | 1 | -1 |
| 3 | -1 | -3 | ⇒ | 3 | -1 |
| 9 | -3 | 0 | ⇒ | 1 | 0 |
| 1 | 3 | 4 | ⇒ | 0 | 5 |
| 1 | 4 | 4 | ⇒ | 1 | 4 |
| 3 | 3 | 4 | ⇒ | 1 | 5 |
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 18 bytes
```
Round[2^#2#,2^#3]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pyi/NC8l2ihO2UhZB0gax6r9DyjKzCuJVta1S3NwUI5VqwtOTsyrq@aqNtXRNdbRNarV4aoG0oZAHohpCRJVMAAxDXUUgEwTKNMEyjSGinLV/gcA "Wolfram Language (Mathematica) – Try It Online")
Returns a binary fraction. By default, the built-in [`Round`](https://reference.wolfram.com/language/ref/Round.html) rounds to even.
[Answer]
# [C (GCC)](https://gcc.gnu.org), ~~53~~ 51 bytes
*-2 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
f(x,n,m)int*n,*x;{for(;*n<m;++*n)*x+=*x&(*x/=2)%2;}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZFdasMwDMfZY3MK0dFgOw6rkxY2vNykMEYalzxYG6kLgtCT7KUvPdR2milOsq5gYf310xf217V-O9T15XI9BZc_f5dOkEbtZYtBoVZke_fRCavw1dssUygVZZWiVCh6qgq5Kux5LP15sI_7xrXYQGiOQZDRgGyejQr2Cwk97JIFdwaCCsjYWSJLvEnP0t9kx9KJlDSkyP1kBJ8dIyeWqz3w2QWYHFzO4_jmK2afk8S_tyhknyziclsNecnGSbxebqSdwBA0IyzvwMsYhHWsgPUfGNQANnpgsL0Dm9Gi-3_GXGGmiukN52_4BQ)
[Answer]
# [J](http://jsoftware.com/), 39 32 bytes
```
((]*%<.@+1r2*2|<.@%)2&^)~(*2&^)/
```
[Try it online!](https://tio.run/##VY6/CsIwEIfn5imuQu0ftTZJIyQoCIKTk3vtIBYVVBCHDOLq7iP6IvGSBmoDl7vv@x0hZyNDRatZqGQck0EeN7BQEMMYClBYkxxW283aJEmVRfN8OaJ3lrEnTlHKhrv0lWS2TU1KDvvjDWqmoQGhoebaG24NXjX1pkCW3UKJSKFP5R9xl@nTAz@owZ@r7xfonS4nAoIJx2IQfN8fCCjOlFhD28RZx0S2puhWC0JdWHqFkbCq7JQl@x7vKWF@ "J – Try It Online")
*-7 thanks to the round toward even idea from att's Wolfram answer*
Divide \$x2^n/2^m\$, manually round toward even, then multiply back \$2^m\$.
[Answer]
# [R](https://www.r-project.org), 29 bytes
```
\(x,n,m)c(round(x*2^n/2^m),m)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZA9DoIwGIbj2J7ChOWrgdhSSHTgAl4BYakWjbEmBAg3cHd1QROP4UUcPYmF8tM4NE2f5_3aN70_8uYpo1dZSG_13kLtKvdMBOSXUu2gXvipWvrpmWhoMp_ZRkLoIo_r5RMHfa83xJDHsIQWsVb1mBu8Nmk6hqmGOqdZ0DOKQsOCiTEUmDu5zUKMHWcuDntxwlkkSyWK40VBRaqYJbpuFfsJzsDuSKIoAwGorcYI6exUdbDcsmNja5T2big-KOqicFKBrVh3GN7jf0pPmS9tGrP_AA)
Based on [@att's answer](https://codegolf.stackexchange.com/a/256361/55372) and similar [`round`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Round.html) behaviour in R.
Outputs non-reduced answers in `(x,n)` format.
[Answer]
# [Rust](https://www.rust-lang.org), ~~55~~ 51 bytes
```
|x,n,m|((n..m).fold(x,|x,_|x/2+(x&1&x/2)),m.max(n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVBRasMwDP3vKbR-BIkp2RK3sLW0-9slxhiFzhCI1ZKl4JH4JP3Jx3aoXmDnmO1ka6nAkv2kp2fp-FUfPpr-tNYCZlMKErQT8BZd9d6AXiTbT4FnwVIVPB5K139PghUk34dGpw8n1VkWNh2iZJmhTO-qLVr26Ftn74pbtEme-AsRm8xsLArRSP0Jeku9qwFjD4JS4CX-IhjOgxykaghFEOZzVnksP1dcph7_WfeXcM7gSbMraHYFqbEqIq_jaoLt61KaSm5wqrG1jqGV4IwL62gXT27KoP0kIAyGaBmJbuKGaft-iL8)
Copied from [@matteo\_c's C answer](https://codegolf.stackexchange.com/a/256358/91213)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 214 bytes
```
\d+
$*
,(1+),(?!1\1).*
,$1
,(-1+),\1.*
,$1
,(-1+)(1+),\1
,0$2,$1
,-(1+),(1*)
,0$1$2,$2
,(1*),\1(1+)
,0$2,$1$2
+`01
100
\G1(?=.*0)
0
(?=0+,1+(0+))\1
1
^(?=1*0*,1+(0+)\1)(11)*.\1
1$&
(1*)0*,(1+0+,)?(-?)(1*)
$.1,$3$.4
```
[Try it online!](https://tio.run/##VY6xDsIwDER3/wVSQHHiRL62DAwoY38iQkWCgYUB8f/BaWFgOd29s5287u/H89r2fl5avUVygcQjsviyQwVnyw7GUocVf9lvjETdsNK0rSJwZ@h0oDXbWO9@o4bjoiCoUp3hyzkHZVIyp1EQvUZmOw26GELQ8IX2Jw9wyL10B@rHrbTjtsfFp8Lr@y5D3Ojy1NpR0ihpIBOYpVPPSpBRJtPJdOz@Aw "Retina 0.8.2 – Try It Online") Link includes test cases. Output is not normalised and input is not required to be normalised either. Explanation:
```
\d+
$*
```
Convert to unary.
```
,(1+),(?!1\1).*
,$1
,(-1+),\1.*
,$1
```
If `n` is greater than `m` then just delete `m`. Most of the rest of the code will then do nothing.
```
,(-1+)(1+),\1
,0$2,$1
,-(1+),(1*)
,0$1$2,$2
,(1*),\1(1+)
,0$2,$1$2
```
Subtract `n` from `m`, adjusting for their signs.
```
+`01
100
```
Calculate `2` to that power.
```
\G1(?=.*0)
0
(?=0+,1+(0+))\1
1
```
Divmod `x` by that.
```
^(?=1*0*,1+(0+)\1)(11)*.\1
1$&
```
If the remainder is at least half (for odd results) or more than half (for even results) then add another `1` to the result.
```
(1*)0*,(1+0+,)?(-?)(1*)
$.1,$3$.4
```
Convert to decimal.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
NθNηNζ≧×X²⁻ηζθ≧⁺∧⁻﹪θ²⊘¹⊘¹θI⟦⌊θζ
```
[Try it online!](https://tio.run/##ZY67CsIwFIZ3n@KMJxAHW7dORRA7VIK4iUNsSxNIkzaXCn35mOIidTsf5781gtvGcBVjpcfgr2F4dRYnUux@WWx4SVzzsXRO9vome@HxLofOUWDmnf4ZhVrq4FBQWAihMP0bmApJX@oWv9LatEEZnChkyXDhau5aPJDNvQYxK7XHE3ceH2dlzLo39TwJKWLMIYdj3M/qAw "Charcoal – Try It Online") Link is to verbose version of code. Output is not normalised and input is not required to be normalised either. Explanation:
```
NθNηNζ
```
Input `x`, `n` and `m`.
```
≧×X²⁻ηζθ
```
Scale `x` by `2ⁿ⁻ᵐ`.
```
≧⁺∧⁻﹪θ²⊘¹⊘¹θ
```
Prepare to floor `x`, but if its remainder modulo `2` is not `0.5`, add `0.5` so that it gets rounded instead.
```
I⟦⌊θζ
```
Output `x` and `m`.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/blob/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b/docs/info.txt), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
o*Io/ò‚
```
Port of [*@pajonk*'s R answer](https://codegolf.stackexchange.com/a/256372/52210), which is based on [*@att*'s Wolfram Language answer](https://codegolf.stackexchange.com/a/256361/52210).
Inputs in the order \$n,x,m\$; outputs as pair \$[n,x]\$. Just like the ported R answer, it does no additional reduction to its simplest form.
[Try it online](https://tio.run/##MzBNTDJM/f8/X8szX//wpkcNs/7/1zXmMuXSNQIA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfWXCoZVF//O1Dq3L1z@86VHDrP86/6OjdY11THV0jWJ1onUNdYx1dI1BLGMdSx0DIMNYx1DHBEibQGljoAqT2FgA).
**Explanation:**
Uses the legacy version of 05AB1E (built in Python), where `ò` does banker's rounding. In the new version of 05AB1E (built in Elixir), `ò` seems to be a regular rounding builtin, using the 'away from zero' convention for rounding halves.
```
o # Take 2 to the power of the first (implicit) input `n`
* # Multiply it to the second (implicit) input `x`
Io # Push 2 to the power of the third input `m` as well
/ # Divide the earlier x*2**n by this 2**m
ò # Banker's round it to the nearest integer
‚ # Pair it with the (implicit) third input `m`
# (after which this pair is output implicitly as result)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 32 bytes
```
(x,n,m)=>x*2**(n-m)*N/N;N=3e-324
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/e9m@1@jQidPJ1fT1q5Cy0hLSyNPN1dTy0/fz9rP1jhV19jI5L81V66trpF1cn5ecX5Oql5OfrqGm4apjq4xUBcQgaWN0aSNdXQNEdIGaLKWKJpN0GQNdfBKmuCWNIbr/A8A "JavaScript (Node.js) – Try It Online")
Take `x,n,m`, return new `x` and set new `n` to input `m`
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 12 \log\_{256}(96) \approx \$ 9.88 bytes
```
2@*z22@/ZvZP
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZrjBy0qoyMHPSjyqICIEJQmQXLdY25TLl0jSBcAA)
Port of Kevin Cruijssen's 05AB1E (legacy) answer, which is a port of pajonk's R answer, which is based on att's Mathematica answer.
Thunno is also built in Python so the rounding will work as intended.
```
2@*z22@/ZvZP # Implicit input
2@ # Raise 2 to the power of the first input, n
* # Multiply with the second input, x
z22@ # Push 2 to the power of the third input, m
/ # Divide x*2**n by 2**m
Zv # Round to the nearest integer
ZP # Pair with the third input, m
# Implicit output
```
] |
[Question]
[
Related: [Deck Names](https://codegolf.stackexchange.com/questions/214938/convert-magic-the-gathering-colours-to-a-colour-based-deck-name) [Friends or Foes](https://codegolf.stackexchange.com/questions/112766/magic-the-gathering-friends-or-foes) [Paying for Spells](https://codegolf.stackexchange.com/questions/175564/magic-the-gathering-paying-for-spells)
The Magic: the Gathering card game has five colours of magical mana: white (W), blue (U), black (B), red (R), and green (G). Cards can be any of the \$2^5=32\$ subsets of these colours. Hereafter 'colours' refer just to the initials `W`, `U`, `B`, `R`, `G`.
The order that these colours present themselves on cards follows a method using the colours arranged as a pentagon:
```
W
G U
R B
```
The order seeks to minimise the gaps between colours when read clockwise around the pentagon, while making the gaps equal sizes. Ties are broken by starting with `W`. There are only eight arrangements with rotational symmetry;
* no colours: `C` or `''`
* one colour: `W`, `U`, `B`, `R`, `G`
* two adjacent colours: `WU`, `UB`, `BR`, `RG`, `GW`
* two opposite colours: `WB`, `UR`, `BG`, `RW`, `GU`
* three adjacent colours: `WUB`, `UBR`, `BRG`, `RGW`, `GWU`
* three opposite colours: `WBG`, `URW`, `BGU`, `RWB`, `GUR`
* four colours: `WUBR`, `UBRG`, `BRGW`, `RGWU`, `GWUB`
* all five colours, start from the top: `WUBRG`
## Challenge
You challenge is to create a function/program, which when given a set of colours, outputs their correct order.
This is code golf, so your solution should be as short as possible!
## Input
Input format is flexible. As long as it is not relying on the order given, anything is acceptable. Some examples:
* Binary number or bit string of length 5
* A string/array containing each colour, either a substring of 'WUBRG' or arbitrary order
* A set or dictionary for each colour
## Output
Output must follow [standard output methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) to output a string/array of the colours.
For the case of no colours, an empty string/array or `C` (colourless) is allowed. Otherwise output must match an entry from the list below. Case doesn’t matter.
For your convenience, here is a list of all possible combinations
```
C
W
U
B
R
G
WU
UB
BR
RG
GW
WB
UR
BG
RW
GU
WUB
UBR
BRG
RGW
GWU
WBG
URW
BGU
RWB
GUR
WUBR
UBRG
BRGW
RGWU
GWUB
WUBRG
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
sṖµ¯5%₍≈⌐;t
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJz4bmWwrXCrzUl4oKN4omI4oyQO3QiLCIiLCJbNCwgMywgMV0iXQ==)
I *think* this works? Takes a list of 0, 1, 2, 3, 4. Fixed for +1 byte thanks to @KevinCruijssen.
```
s # Sort (annoying edgecase)
Ṗµ ;t # The maximal permutation by...
¯ # Differences
5% # Modulo 5
₍ # Sort primarily by...
≈ # All differences are the same
₍ # And secondarily by...
⌐ # 1 - the list = minimal value.
```
[Answer]
# JavaScript (ES10), 71 bytes
Expects a bitmask in `UWGRB` order (from most to least significant bit). Returns an array of characters.
```
n=>[...s="BRGWU"].flatMap(_=>n>>++k%5&1?s[k%5]:[],k=1950448093/n/n%5|0)
```
[Try it online!](https://tio.run/##RZBNaoNAFMf3nuJVSFRMJ6ZJoInVwGwGCm3BIi5EiiRjMJExOCZQ0twg0E2X7T16nlygR7DzAS3yfPj7fzi6yQ85Xzblrr1m9Yp2RdCxIEwRQjwwcUSS2MxQUeXtQ76zX4KQhaHrbnvT/mjBU7GzeZoNtsFoNvUmk1tvNh6yIetN3zynW9aMt3DIq3IFAaSmOTATMbEYLCYSQySTIJYESxRJRqQxkSyWDEsWSUZilVCKsmPlj1SAqKpEuWNlx8ofqSaiqhIdi3UO62Ckk0QXJ0rMfEN/wJ5Tef7jyTeMom7sirbABPB8se5gfCO26zpwNACk1lAu1MJmDtrUJbMty/GFJMvqiqKqXtsMXLDE5cL989Mj4m1TsnVZvNoi6/xptvp1qGTLar@iXIv9PlzJE6XiKYMFWD/f75fPD3G3YA7W5etsOep9/6YA2mZPfePU/QI "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES10), 75 bytes
Expects a bitmask in `RBUWG` order (from most to least significant bit). Returns an array of characters.
```
n=>[...s="GWUBR"].flatMap(_=>n>>++k%5&1?s[k%5]:[],k=~~"204122031"[n%19%13])
```
[Try it online!](https://tio.run/##RZBNaoNAFMf3nuJVSGbEdIimXTRWA7MZKLQFy@BCpEiiwUTG4JhACekJCt102d6j58kFegQ7M0KLPB/@/h@ObvJDLpdttesuRbMq@jLsRRilhBAZ2izhNLYzUtZ5d5/v8HMYiShy3e3oeuwtZKp2Nk@zyTZ8fbX96ZXn@9OZZ6di5N2MvFnm9MtGyA4OeV2tIITUtid2ooaroWpiNUwzDbgmVKNYM6aNiWZcM6pZrBnjJmEUY6fGH5sAM1WJcXNjp8YfmyZmqpIhxoccHYLxkGRDcWLELLCGD9jLQp//eAosq2xaXBcdCAWmgVq3MPPVdl0HjhaA1tpCKrXEwiGbphIYISdQki5r6oLUzRoLcAGpy4W7p8cHIru2EuuqfMEq6/xp2Pw6UollvV8VchDHY7jQJ0rVUwYLQD/f7@fPD3VHMAd0/npDjnnfvymErt0XgXXqfwE "JavaScript (Node.js) – Try It Online")
### How?
We build the output by adding characters from the string `"GWUBR"` according to the bits that are set in the input, starting at a valid position, going from left to right and wrapping.
Fortunately, the starting position is quite flexible. For instance, for the expected output `"GW"`, we can start anywhere except at `W` because `U`, `B` and `R` are discarded anyway. This allows to increase the number of consistent collisions in the lookup table and make it a little more compact.
Below is a summary of all acceptable starting positions for each pattern, along with the position which is actually chosen.
```
n | pattern | acceptable | i=n%19%13 | ~~"204122031"[i]
----+---------+-------------+-----------+------------------
0 | "" | [0,1,2,3,4] | 0 | 2
1 | "G" | [0,1,2,3,4] | 1 | 0
2 | "W" | [0,1,2,3,4] | 2 | 4
3 | "GW" | [1,2,3,4] | 3 | 1
4 | "U" | [0,1,2,3,4] | 4 | 2
5 | "GU" | [2,3,4] | 5 | 2
6 | "WU" | [0,2,3,4] | 6 | 0
7 | "GWU" | [2,3,4] | 7 | 3
8 | "B" | [0,1,2,3,4] | 8 | 1
9 | "BG" | [0,1,2] | 9 | 0
10 | "WB" | [0,3,4] | 10 | 0
11 | "WBG" | [0] | 11 | 0
12 | "UB" | [0,1,3,4] | 12 | 0
13 | "BGU" | [2] | 0 | 2
14 | "WUB" | [0,3,4] | 1 | 0
15 | "GWUB" | [3,4] | 2 | 4
16 | "R" | [0,1,2,3,4] | 3 | 1
17 | "RG" | [0,1,2,3] | 4 | 2
18 | "RW" | [1,2,3] | 5 | 2
19 | "RGW" | [1,2,3] | 0 | 2
20 | "UR" | [0,1,4] | 1 | 0
21 | "GUR" | [4] | 2 | 4
22 | "URW" | [1] | 3 | 1
23 | "RGWU" | [2,3] | 4 | 2
24 | "BR" | [0,1,2,4] | 5 | 2
25 | "BRG" | [0,1,2] | 6 | 0
26 | "RWB" | [3] | 7 | 3
27 | "BRGW" | [1,2] | 8 | 1
28 | "UBR" | [0,1,4] | 9 | 0
29 | "UBRG" | [0,1] | 10 | 0
30 | "WUBR" | [0,4] | 11 | 0
31 | "WUBRG" | [0] | 12 | 0
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~258~~ 247 bytes
```
s=>(c="WUBRG",p=[0,1,2,3].map(i=>(t=>t.slice(i)+t.slice(0,i))(s.sort(m=(x,y)=>c.indexOf(x)-c.indexOf(y)).join``)).filter(x=>new Set([...x.slice(1)].map((z,k)=>(x=>(m(x,z)+5)%5)(x[k]))).size==1),({"WG":"GW","WR":"RW","UG":"GU"})[q=p+p?p[0]:s+p]||q)
```
[Try it online!](https://tio.run/##pVNNb5tAEL3vrxitVGk3kJXTyjkkXUdCqlBPlYgQB4pkAjjdxAbCrlLixL/dmcHYTpQeqnbFYXbe4/Hmg7v8MbdFZ1p3WjdltV3ordUzUWiexEEUcr/V6cQ/8z/7XzK1ylthEHV65pRdmqISRnr7cOIbKYVVtumcWGnR@09Szwpl6rLqfyxEL0@Plycp1V1j6vkcg4VZuqoTvZ7V1W@4rpxIlVL9qHsmd18Wa/8eBYkmVqi@lt5UfppK0af3mUQZa9aV1mfSF888CfkFDxPu8yTCKKIoHnIx38j0Qbdee9Wmk@zCem328vIgt495B0XTdaBhzhIWs4BFLGRJzOKABRGLQhYmLAlYHLEgZFHCwhhRvCOIvUICppCeIBojHCAeIT/EF6ibRAyJmRA1Jm4wAOFc2XZpnOA/ay4vGSMrrkAjQoKewTMDPJS0rrOY3rcJuYQcYOODfZNaNB0Ig/zJJRj4CudwcgJTjD1PjqJ0SJEabpRrrl1n6ltxLlWbl9cux1FOfZiMI@jJzbgZqddnx9ER0O9GKjgffR2M0DELwOVYVvWt@wUaS9sXYcfRyQN1MIWVqrwsEd6Jbd6XWjSrm71x4ma7vRO5DzdD02iUaK8uv9PKiYJyRC5G5tEsuSEk/4BIOP0HnZuPOm8HVTS1bZaVWja3YqhiaK0lXfum6xI84ICPB4vhf7DZMJRvdfkOPPj7G2v2o7U/aYr/FSXo4BqugIdNU3K4gOGLOxrtOvZlg/vuClzl7Ss "JavaScript (Node.js) – Try It Online")
[Answer]
# x86-64 machine code, 37 bytes
```
6B CE 21 B8 47 52 42 55 B2 57 BE FD F7 FD 55 D3 E6 45 18 C0 C1 C0 08 86 D0 D1 D9 78 ED 73 F3 AA 84 C0 75 EE C3
```
[Try it online!](https://tio.run/##TZJNb5wwEIbPnl8xpVphumTFfiSK2N0e2kNPuUSqWinJwRgDjoxdYTbLNrt/vXSAJipIHtvvO8@MMfKqlLLvha@R433AYVEalwmDBRQp0/XBoJJdjMrrGNdrYLV7QSVoh4ffw91utTmHXygub87hPcXbc/gtjCZbbmIMf4Qg0ilrQCRZspze6Un@G6cZMF@ZySwNsEV2ahUm3eYajj5lPstQEFcYsClrnJmauQXWyaocpZyyGtlMfRPu2aOAY8qercSjJ3zrfAasVb59Q5H2e9Qa1UIUYLSFF6dzLLisRPMJfYzatmhpHz5qK80hV7jzba7dovoMMIi10JZH8ApsyMFG@YNpH66Xq6ctsMI1yEcE7jHZUtjtcb2kyXxOX4uSWMGnlHgsw9ivhvwFD2Y6xZl/tAEJ8T/sYLjAu@XR3glZaatQulylwSAPxbqhWIwnWuYOX9/sOEtWPwl32nN@sF6XVuU4HjQqooduPn@Kthc8Vtoo5Cf8QJDu63qAvhP4TONwMT4aG@tIvPT9H1kYUfr@qr7Z0EA/1Z78yvwF)
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and takes the input bitmask in ESI (W=1, U=2, B=4, R=8, G=16).
In assembly:
```
f: imul ecx, esi, 33
```
ECX := 33 \* ESI. Transfer the bitmask from ESI to ECX while duplicating bits 0–4 into bits 5–9.
```
mov eax, ('U'<<24|'B'<<16|'R'<<8|'G')
mov dl, 'W'
```
Put the colour letters in these registers.
```
a: mov esi, 0b01010101111111011111011111111101
shl esi, cl
```
Place this value in ESI, then shift it left by the low 5 bits of ECX. The last bit shifted out goes into CF; a 0 indicates a correct arrangement.
```
.byte 0x45 # REX.RB
ws: sbb al, al
```
These combine to form `sbb r8l, r8l` (subtract R8L+CF from R8L). The value of R8L becomes -CF, and SF is set from its sign bit, equalling CF.
```
n: rol eax, 8
xchg al, dl
```
Together, these instructions rotate the five colour letters, while SF remains unchanged.
```
rcr ecx, 1
```
Rotate ECX (holding the bitmask) and CF together right by 1; the low bit of ECX goes into CF. Also, SF still remains unchanged.
```
js a
```
Jump back if SF=1.
```
w: jnc ws
```
At this point, the correct arrangement has been found, and it remains to produce the string from it. Jump if CF (which is the bit just taken off the bitmask) is 0.
```
stosb
```
(If it is 1) Add AL to the output string, advancing the pointer.
```
test al, al
jnz ws
```
Jump back if AL is nonzero.
```
ret
```
(If AL is zero) Return.
Both of the jumps within the output section lead to `ws: sbb al, al`, which sets AL to 0 (as CF will be zero, from the `rcr` or from the `test`), to end the string instead of repeating the letter when it comes back around.
---
Input 0 is a special case. `shl` by 0 does not change the flags, but CF will be 0 from the `imul` to indicate a correct arrangement. Nothing will be written for a while, and all the letters will be replaced with null bytes. Eventually, a 1 bit rotated into the top of ECX by `rcr ecx, 1` (from CF becoming 1 from the `rol eax, 8`) will make its way to the bottom and then back into CF, resulting in outputting a null byte and returning.
[Answer]
# [Python](https://www.python.org), 171 bytes
```
lambda s,g="WUBRG":[min([[e,p]for p in permutations(s)if len(set(e:=[(g.find(p[i+1])-g.find(p[i]))%5 for i in range(len(s)-1)]))<2])[1],g][len(s)>4]
from itertools import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZHNSgMxFIVx6X2KISAk2hYqKlIcF-Ni9gNDFulQpm1mjMwkIUmpPoubgujGJ9Kn8aZTkHaVn_Pdm3Nu3r_sW3g2evfRpPPPTWjG9z_fXd0v13XiR21KeJkVOZmJXmkqhBzZqjEusYnSiZWu34Q6KKM99Uw1SSc19TJQOUsFbSeN0mtqhbqaVmz8f6wYu7hNYhsV27hat5LuS9l4ylB9uK6YmFajthLD9eNNBY0zfaKCdMGYzieqt8aFy8Hy7xm3xnu17ORCabsJPhVYcfzCHZvB-Qk2ka9BoitByOTFYMStcWu29xZ3sbhTPtCjqIeZjFyqGNqFlXFOrsKi1n4rnU8JIfAEHErIoIAceAllBlkBRQ45B55BWUCWQ8EhL1HFM4rYEgG8QpyjWqKcoV4gn2NBfDSCeSR5RMvIZjC4wQDedipQMteE7bMH6cP-n44zxyk4pZE8ZG5oJBmL7EkWNsx3txvWPw)
Works similarly to [@emanresuA's answer](https://codegolf.stackexchange.com/a/247356/110555), but derived independently. Takes a string as input, outputs a list
[Answer]
# [Python](https://www.python.org), 106 bytes
```
f=lambda s,t=0:(2*"WUBRG")[x:x+len(y):1-t]if~(x:=(2*s).find(y:=(s.count("1")*"01"[~t:])[-t:]))else f(s,~t)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZK_asMwEMbp2HsKoUlKk5B0KMXgxR28G4wH1wQnkVsFWzLShThL3qJTlyztO7VP01P-QMkiuPt-d7r7pM_vfo_v1hyPX1tsJs8_myZu6265rpkfYzyLxOOIF3mSpVyWQzQ8tMqIvYzmE6x0cxBDFBPh5bTRZi32FPnpym4NCj7ncsRnc14eMKpkOQmnVK1XrBF-fEB5vvH37qNxtmMalUNrW89011uHrFeu22KN2hoPvfVeL1u10Kbfoo_LChrrmGbaMFebNyWeZAT3N9hUDahorpLz6cZqI07zDKFoZ926YqHHKbzueMoELSRb7VH8H0NcsLGLtZSVhJV1Tq1wURu_U87HnHN4gQJySCCDFIoc8gSSDLIU0gKKBPIMkhSyAtKcVIpJpJYEUIrwgtSc5IT0jPiUCsKlAUwDWQQ0D2wC52loOd-3mix_NVyefEHlMWxw40dwyGl6nEYEQgbkZoUx-RVzxi-vc_0Xfw)
Test harness shamelessly stolen from @jezza\_99. Expects a binary string indicating which of "WUBRG" are present.
How?
Counts "1"s in the input, for example 3 "1"s. Then checks for the patterns "111" and "10101" in 2\*input where the factor 2 is to simulate wrap around. Finally, finds the same index in 2\*"WUBRG" and cuts out the corresponding letters.
[Answer]
# [R](https://www.r-project.org), 84 bytes
```
\(i)chartr("0-4","WUBRG",Find(\(j)all(i%in%j),Map(\(j)seq(j%%5,,j%/%5,,i)%%5,5:24)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY7BCoJAFEV_ZRgYeA_G0lIIiQgXtWoTRhs3gzn5BhlLJ_qYNgb1Uf1NWq4O93I53Mez6V6aLb33zWlv8UkzIMxL1bgGuO-FXPLjIdlvudyQPUEGBlVVAQmywqDcqcuva4srGCEiKY2YDiAcUhTPQkQc3WtdN0CMLPPjeYAsVw403EvKS1DthKwrzkW_sC6tE3Jt_wRXPnoBSsYzy0dP1_35BQ)
Takes input as a vector of numbers 0-4, outputs a vector of letters.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{ÀœΣ¥5%(DËš}θ
```
Port of [*@emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/247356/52210), so make sure to upvote him/her as well!
+2 bytes to correct the output when all five values are input
Uses `1,2,3,4,5` for `W,U,B,R,G` respectively.
[Try it online](https://tio.run/##ASUA2v9vc2FiaWX//3vDgMWTzqPCpTUlKETDi8Whfc64//9bMSwzLDRd) or [verify all test cases](https://tio.run/##yy9OTMpM/W/qc3jZ4ZVllUcnl1XaK7mHhzoFKVUeXuGlpKBxeL@mwqO2SQpK9pX/qw83HJ18bvGhpaaqGi6Hu48urD23478LTEMxXIOSzn8A).
**Explanation:**
```
# Fix the output of the edge-case when all five values are input:
{ # Sort the (implicit) input-list
À # Rotate it once towards the left
œ # Get all permutations of this list
Σ # Sort this list of lists by:
¥ # Get the differences of the current list
5% # Modulo-5 for the negative values
( # Negate all of these values
D # Duplicate it
Ë # Check if all values in the copy are the same
š # Prepend this 0 or 1 to the list of negative differences
}θ # After the sort_by: pop and push the last value
# (the `Σ...}θ` basically acted as a max_by builtin)
# (after which the result is output implicitly)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~26~~ 25 bytes
```
⊟ΦEχ⭆θ§UBRGW⁺ι×μ⊕‹ι⁵⬤ι№θλ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMgv0DDLTOnJLVIwzexQMPQQEchuAQokw7iFeooOJZ45qWkVmgohToFuYcr6SgE5JQWa2TqKIRk5qYWa@TqKHjmJRel5qbmlaSmaPikFoMlTTUhAKg/Jwck4JxfCrQMaF4OWNz6//@gUPf/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Generates all cyclic slices of `UBRGW` with step of either `2` or `1` having the length of the input and outputs the last that is a permutation of the input.
```
χ Predefined variable `10`
E Map over implicit range
θ Input string
⭆ Map over characters
UBRGW Literal string `UBRGW`
§ Cyclically indexed by
ι Outer value
⁺ Plus
μ Inner index
× Times
ι Outer value
‹ Is less than
⁵ Literal integer `5`
⊕ Incremented
Φ Filtered where
ι Current string
⬤ All characters satisfy
θ Input string
№ Contains
λ Current character
⊟ Take the last element (smallest delta)
Implicitly print
```
For input strings of lengths `1` to `5` the following strings are generated:
1. `U` `B` `R` `G` `W` `U` `B` `R` `G` `W`
2. `UR` `BG` `RW` `GU` `WB` `UB` `BR` `RG` `GW` `WU`
3. `URW` `BGU` `RWB` `GUR` `WBG` `UBR` `BRG` `RGW` `GWU` `WUB`
4. `URWB` `BGUR` `RWBG` `GURW` `WBGU` `UBRG` `BRGW` `RGWU` `GWUB` `WUBR`
5. `URWBG` `BGURW` `RWBGU` `GURWB` `WBGUR` `UBRGW` `BRGWU` `RGWUB` `GWUBR` `WUBRG`
In the case of strings of length `1` the same string is generated twice so it doesn't matter which is picked while in the case of strings of length `2` or `3` all `10` permutations are generated so there is only one matching the input but in the case of strings of length `4` or `5` there would be multiple matching strings; in the case of `4` the first five are invalid and in the case of `5` the first nine are invalid so that the last matching string is the correct output as desired.
] |
[Question]
[
Your goal is to make a function that takes the coordinates of a cell in 2D space and a distance \$r\$ and returns the coordinates of all cells in the input coordinate's von Neumann neighborhood of radius \$r\$. That is, all cells at most \$r\$ away in [Manhattan distance](https://en.wikipedia.org/wiki/Taxicab_geometry).
For example, given the following cell coordinates and radius pairs:
```
[1, 1], 1 -> [0, 1], [1, 0], [1, 1], [1, 2], [2, 1]
[2, 2], 2 -> [0, 2], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 1], [3, 2], [3, 3], [4, 2]
```
This is what the von Neumann neighborhood looks like:
[](https://i.stack.imgur.com/crQOO.png)
More information about the von Neumann neighborhood can be found [here](https://en.wikipedia.org/wiki/Von_Neumann_neighborhood).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest amount of bytes wins!
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 23 bytes
-4 thanks to ovs.
Anonymous tacit infix function, taking coordinates of a cell and radius as left and right arguments. Requires 0-based indexing.
```
{⍺∘+¨⍵-⍸⍵≥+/¨|∘.,⍨⍵…-⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6sf9e561DFD@9CKR71bdR/17gBSjzqXausfWlEDFNfTedQLknnUsAwoubX2fxpQ16PevkddzY961zzq3XJovfGjtolA84KDnIFkiIdn8H9DBUOFNAVDLiMFIyBtBAA "APL (Dyalog Extended) – Try It Online")
`{`…`}` "dfn"; left argument is `⍺` and right argument is `⍵`:
`⍵…-⍵` inclusive integer range from radius to negative radius
`∘.,⍨` Cartesian selfie product
`⊢m←` assign to `m` and pass that
`|` absolute values
`+/¨` sum each (gives matrix of Manhattan distances)
`⍵≥` indicate which ones are less than or equal to the radius
`⍸` **ɩ**ndices where true
`⍵-` subtract from radius
`⍺∘+¨` add the cell coordinates to each
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
k□0zJẋΠṠUMṠ
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJr4pahMHpK4bqLzqDhuaBVTeG5oCIsIiIsIjJcblsyLCAyXSJd) Takes \$r\$ then the coordinate.
```
k□ # cardinal directions [[0,1],[1,0],[0,-1],[-1,0]]
0z # 0 zipped into self [[0,0]]
J # join [[0,1],[1,0],[0,-1],[-1,0],[0,0]]
ẋ # repeated into a list r times
Π # reduce by cartesian product
Ṡ # vectorising sum
U # remove duplicates
M # pair each direction into the input coordinate
Ṡ # and sum to it
```
[Answer]
# [Perl 5](https://www.perl.org/), 64 bytes
```
sub n($x,$y,$d){map{//;map[$x+$',$y+$_],-$d+abs..$d-abs}-$d..$d}
```
[Try it online!](https://tio.run/##JYxBCsIwFET3niLIhybkt1XBlZtewJXLEkpLq0Q0CUkKlZCrG9PKLN7MwIyZ7OuckpsHoigsCB@EkYV3b0JdXzJaWDgUuefQCSxh5P3gqgrGMjPmvPq4HXh985Y2loWnlooUWCDJDyTsW4CuPQhccRRiH0lj485YqTz9rxQ9YRZjLH218VIrl8rrfer9bCfu5ENtzv0A "Perl 5 – Try It Online")
Saved 4 bytes, thanks to Xcali.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes
-1 thanks to ovs
```
D(ŸãʒÄO¹s@}€+
```
[Try it online!](https://tio.run/##ASYA2f9vc2FiaWX//0QoxbjDo8qSw4RPwrlzQH3igqwr//8yClsyLCAyXQ "05AB1E – Try It Online")
Takes input as range, coordinates
Explanation:
```
D duplicate the range in the stack
( negate
Ÿ push the range [-range..range]
ã Cartesian power
ʒ filter
Ä absolute value, vectorizes over each of the coordinates
O sum - distance from 0,0
¹s@ less than or equals to the range
} end filter
€ map
+ add, with the implicit center coordinate
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ŒRṗ2AS>³ƲÐḟ+
```
[Try it online!](https://tio.run/##ASUA2v9qZWxsef//xZJS4bmXMkFTPsKzxrLDkOG4nyv///8y/1syLDJd "Jelly – Try It Online")
A dyadic link that accepts the radius and the point.
## Explanation
```
ŒRṗ2AS>³ƲÐḟ+ Main dyadic link accepting r, [x,y]
ŒR [-r..r]
ṗ2 [-r..r]^2 (Cartesian product)
Ðḟ Filter out by
Ʋ (
A Absolute value (of both)
S Sum
>³ Greater than r
Ʋ )
+ Add [x,y] to each
```
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ŒRAạ³ŒR;€Ʋ€Ẏ+
```
[Try it online!](https://tio.run/##y0rNyan8///opCDHh7sWHtoMZFg/alpzbBOQeLirT/v///9G/6ONdIxiAQ "Jelly – Try It Online")
A dyadic link that accepts the radius and the point.
## Explanation
```
ŒRAạ³ŒR;€Ʋ€Ẏ+ Main dyadic link accepting r, [x,y]
ŒR [-r..r]
€ For each i in [-r..r]
Ʋ (
A |i|
ạ³ |(|i| - r)|
ŒR [-|(|i| - r)| .. |(|i| - r)|]
;€ Join each with i
Ʋ )
Ẏ Tighten (flatten by one level)
+ Add [x,y] to each
```
[Answer]
# [R](https://www.r-project.org/), 75 bytes
```
function(c,r)(d=t(expand.grid(c[1]+-r:r,c[2]+-r:r)))[,colSums(abs(d-c))<=r]
```
[Try it online!](https://tio.run/##JYw7CoUwEAB7T5FyF1chKeXlFJbBQjcqgm@V9YO3jwSLgWGK0XSL@DRdwueyCTApQvQnjM/eS6xnXSJwsF1ZaaPEwX2GiIF4W9vrf0A/HBArRvx57fIQGCwZixlTfMGRcZgxRXoB "R – Try It Online")
**How? Un-golfed code**
```
vnn=function(c,r) # c = (x,y) coordinates; r = radius
d=expand.grid(c[1]+(-r:r),c[2]+(-r:r))) # d = all combinations of coordinates from x-r to x+r, y-r to y+r
d=t(d) # transpose d so that (x,y) coordinates are rows instead of columns
d[,colSums(abs(d-c))<=r] # select the columns for which the sum of absolute differences to
# the given (x,y) are less than or equal to r
# (note that R recycles c to subtract it from every pair of elements
# by row in d, so 'd-c' produces all the differences in x,y coordinates)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes
```
oo+#&/@DiamondMatrix@#~Position~1-#-1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P//9pIX52spq@g4umYm5@XkpvoklRZkVDsp1AfnFmSWZ@Xl1hrrKuoZq/wOKMvNKoquVlWt17dKilWOjlY1iY9UcHByquaqrDXUMa0EIxjSu5ar9DwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 52 bytes
```
(a,b)!r=[(a+k,b+j)|k<-[-r..r],j<-[abs k-r..r-abs k]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/XyNRJ0lTscg2WiNRO1snSTtLsybbRjdat0hPryhWJwvITEwqVsgG83XBzNjY/7mJmXm2BUWZeSUqGoYGOoYGBpqKRv8B "Haskell – Try It Online")
I'm sure someone will figure out a more clever way to do this that isn't nearly so long. But for now I am stumped.
[Answer]
# [J](http://jsoftware.com/), 28 bytes
```
+"1](]#~(>:1#.|))>@,@{@;~@i:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tZUMYzViles07KwMlfVqNDXtHHQcqh2s6xwyrf5rcqUmZ@QrGAJhmoIhhKOuDqGNgDBNweg/AA "J – Try It Online")
* `+"1...` Add the left argument (the center point) to each element of the right argument (the width) after transforming the right argument by `...`
* `i:` The first part of that transformation is the "both direction" integers of the width. Eg, `i: 2` produces `_2 _1 0 1 2`.
* `>@,@{@;~@` Take the Cartesian product of that bi-directional integer list with itself `{@;~`, flatten the result `,` and unbox `>@`.
* `](]#~...)` Now filter that Cartesian product result by the following...
* `(>:1#.|)` For each point on the list, is the sum `1#.` of the absolute values `|` of the `x` and `y` coordinates greater than or equal to `>:` the original right arg (the width)?
[Answer]
# [Python 3](https://docs.python.org/3/), 79 bytes
```
f=lambda s,r:{s}|{(a+x,b+d-x)for d in(1,-1)*r for a,b in f(s,r-1)for x in(0,d)}
```
[Try it online!](https://tio.run/##FcvBDoMgEATQe79ijrt1TQRvJv0YCCEladGgBxr12yl7nDcz2@94r3luLb4@7uuDwy5lOff7OskNVfwQxspxLQhImYyMhp8FCk58J0Tqj65KVTeTBL6bxqT9JDACK5iXB7CVlA@KRFYsCxJz@wM "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 81 bytes
```
lambda x,y,d:[(x+i,y+j)for i in range(-d,d+1)for j in range(abs(i)-d,d+1-abs(i))]
```
[Try it online!](https://tio.run/##RYm7DoAgDAB/hbENdVA3E79EHTD4KNFqkEG@Ho0M5qa7O2NYD6mTtH3azD5ao26KZJsObs0UtcP58IoVi/JGlgkKS1aXX3V/NeMFjPkVWXBIp2cJcAUPAhW9IGJ6AA "Python 3 – Try It Online")
Three bytes saved, thanks to ovs.
[Answer]
# Scala, 61 bytes
```
(x,y,r)=>for(a<- -r to r;d=r-a.abs;b<-y-d to y+d)yield(x+a,b)
```
[Try it online!](https://scastie.scala-lang.org/vYOsqmTqQHqJFRn7DB4Gjg)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 82 bytes
```
$x,$y,$r=$args;-$r..$r|%{$i=$_;($d=($i-replace'-')-$r)..-$d|%{,(($x+$i),($y+$_))}}
```
[Try it online!](https://tio.run/##fVHRboIwFH3nK5rmbraxEAXfTBMSk71umb4RQxC7DYPAWsg0yLezUovuYVv7cLg9p@cebqvyS0j1IfK8h7emSOusLLiD9Gp7ODE4M5AcEvmuli5IzwN5eWgh4xAvCew5gcyVosqTVEzcCdUS6nku7LWIEQKnKWSUEThPIaa06/rBuHOgFqpeJUooxFFITLuwNTCsrKiaevgYSJ/pTW@cOFUircXecDiaMeRvGYrmDM0tjnUwoM/QzOLcom9x5BcDBpYPLB9YfjHU@Nq@Y39lnDO9/8s4Zpv9ltVkG3s41IGNno7iIaE/BqUHagRgGjMYe@iH8OxR7I2HV6UUqslrHQIDIeTx9rwoNBeotsQREIjdQ5kVmCFMt7ij9wpffVSTpkIpjq0jdsUnvgWwIpN5yqOX9apRdXl83h00vQ3btb092ixfjcndrXM6@8uXp1Iek9rdJLtc9N8 "PowerShell – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 75 bytes
```
f=lambda s,r:{s}|{(a+x//3,b-1+x%3)for x in(-2,4,0,2)*r for a,b in f(s,r-1)}
```
[Try it online!](https://tio.run/##FctBCsMgEAXQfU/xN4WZZiRRuwr0MEqRCq0JJgtLmrNb3T5463d/LcnWGh5v9/FPh03yfGzn7yA3lHG04pUeytVyWDIKYiJl5C6TGL5ldHTiGyNQq0rzWTvGTpNAC4zAYr4Aa45pp0BkWhZE5voH "Python 3 – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 59 bytes
```
(x,y,r)=>for(a<- -r to r;d=a.abs-r;b<-d to-d)yield(x+a,y+b)
```
[Try it online!](https://tio.run/##PcixCsIwFEbhvU/xj7k0cXC0TcHRwclRHG6aBColbdMgDeKzRx0UDmf41p5HLpO5uz7hzEOA25ILdsVxnp/Vg0f4A8QpJInfCLrDxS3XP9MNuohNZhlJd36KglsFFZEmxMZq3rFZVWxMq@zHlKU8uNGKrWaZa0NljkNIwou9xDei6lXe "Scala – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 146 bytes
```
int[][]f(int x,int y,int d){int i=~d,r[][]=new int[1-2*d*i][],p=0,a,j;for(;i++<d;)for(j=a=i<0?d+i:d-i;j>~a;)r[p++]=new int[]{x+i,y+j--};return r;}
```
[Try it online!](https://tio.run/##RU9Na8MwDL33V4hCwa6dkPZYN90v2KlH44NXp0POJ47TNYT0r2d26JgEkpCenp6sfujEmnK5Vbrv4VNjMy3YeKmkupNQwJPHOK7R0CkmzF@GuwjJm@IHIvyQHPdmj6HFuzzjmltxbx0RyNjZCBprm@scz9mHYXgyCQp7eWlBnewY@@dR05MhH5lNklm4wg@uASfmBaAbviq8Qe@1D@nRooE6qCVX77D5lgo0nTYQ7K0eXNEPlYccInd8jND0To48OBUrMqgCssKhhNN7ga4jgOvY@6JO28GnXbjgq79TaVirtSdbuTMcdkZteSkzxaGUB0VX6nkzL78 "Java (JDK) – Try It Online")
minus 6 bytes, thanks to ceilingcat
minus 2 bytes, thanks to ceilingcat
[Answer]
# [JavaScript (V8)](https://v8.dev/), 75 bytes
```
p=>n=>{for(i=-n;i<=n;++i)for(j=k=n-(i*i)**.5;j>=-k;)print(p[0]+i,p[1]+j--)}
```
[Try it online!](https://tio.run/##FchRCsMgDADQ6yTalE0YDGy8iPhRBkIspMGW/pSd3bH3@dp6rceni510vUflYZyU0133DsKkURbW6L3gfxpvrATiBJ2bX7Elpi2iddETLD@Kl8nys/hGhN9RIYcpFISA4wc "JavaScript (V8) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 38 bytes
```
AQf!>+ahThGaeTeGH*r-hGHh+hGHr-eGHh+eGH
```
[Try it online!](https://tio.run/##K6gsyfj/3zEwTdFOOzEjJMM9MTUk1d1Dq0g3w90jQxtIFOmmglhA4v//aCMdo1gdIwA "Pyth – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 58 bytes
```
(x,y,d)->[(x+i,y+j) for i=-d:d,j=-d:d if abs(i)+abs(j)<=d]
```
[Try it online!](https://tio.run/##HYy7CoAwDAB3vyJjQiOoOIn1R8RBiYUUqeID6tfXx3TDHeevRccyJmcTRr5ZKO96jEb5Np7ArTuozaUR9j9AHYzTgUrmg6fWypC@7FUBiqbOALZdw7kEdFhx9S4pm4OkBw "Julia 1.0 – Try It Online")
] |
[Question]
[
# Problem:
In chess, there is a somewhat well known rule about draw by repetition. If the same position is repeated 3 times (or more) then the player intending to make the move which will cause the this repetition can claim a draw.
Sometimes this is an easy task for an arbiter to spot, if the last few moves are just the players moving backwards and forwards. Sometimes it is less trivial, when pieces have moved significantly between repeated positions.
The problem in this challenge is to output a truthy value if the claimed position is draw by repetition (has been seen 3 times or more) and a falsey value if the claimed position is not draw by repetition, given a list of moves in coordinate notation as described below, or any notation of your choosing (but you'll have to convert the test cases).
---
### What is a position?
In a real world scenario, the position would be affected by things such as whether a player can castle or whether en-passant is possible; you should **not** consider these in your solution to the problem. In this problem a position is defined simply by the configuration of the pieces on the board. So, for the purposes of this problem, two positions are seen to be the same if each square on both boards is occupied by the same type of piece of the same colour. This does not have to be the exact piece for example white's knights could swap squares and if all other pieces fulfill the criteria this would still be the same position.
---
### What does a valid notation look like?
Although I will go on to explain coordinate notation, you are free to take input by a notation system you choose. Provided that:
* Each item in the notation describes any or all of: the piece/pieces involved; whether check, checkmate, double check, checkmate or stalemate have been delivered; if en-passant capture has occurred; the initial position; the final position.
* You may **not** have information about repetition in your notation.
So as long as these criteria are met I am happy to accept, as long as you specify in your answer, your notation system. This could be e.g. 0 indexed row,column tuples or whatever makes sense for your program.
---
### Coordinate Notation
Coordinate notation is a notation which describes purely the moves as a system of coordinates.
A move is described as first the initial coordinate from the set `{A1-H8}` and then the destination coordinate again from the same set. So the [King's Gambit](https://en.wikipedia.org/wiki/King%27s_Gambit) would look like (as a collection of strings)
```
{"E2-E4","E7-E5","F2-F4"}
```
I believe it's the best notation to use for this problem because it is not littered with extraneous information like whether check has occurred or what the type of piece moving is. As mentioned before the notation can be of your choice, so you could use another notation e.g. [algebraic notation](https://en.wikipedia.org/wiki/Algebraic_notation_(chess)) or you could adapt this notation (e.g. remove the dashes, or take as a list of tuples)
---
## Rules:
* You should **not** consider whether a position or move is valid, only whether it causes repetition
* You can assume that castling and pawn promotion will **not** occur.
* You should take a list of strings as input and output a truthy or falsey value corresponding to whether the third (or more) repetition has occurred on the final move
* The game always starts at the standard starting position for chess. The initial position can count towards repetition.
* Draw by repetition has not occurred if the position is not repeated by the final move
---
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
---
### Test Cases
You should return truthy values for:
```
{"B1-C3","B8-C6","C3-B1","C6-B8","B1-C3","B8-C6","C3-B1","C6-B8"}
{"B1-C3","B8-C6","C3-B1","C6-B8","B1-C3","B8-C6","C3-B1","C6-B8","B1-C3","B8-C6","C3-B1","C6-B8"}
{"B1-C3","B8-C6","D2-D4","D7-D5","D1-D3","D8-D6","C3-B1","C6-B8","B1-C3","B8-C6","D3-D1","D6-D8","D1-D3","D8-D6"}
{"D2-D4","B8-C6","E2-E4","C6-D4","D1-E2","D4-E6","E2-F3","E6-D4","F3-D1","D4-C6","D1-E2","C6-D4","E1-D1","D4-C6","D1-E1","C6-D4"}
{"B1-C3","B8-C6","C3-B1","C6-B8","B1-C3","B8-C6","C3-B1","C6-B8","B1-C3","B8-C6","C3-B1","C6-B8","B1-C3"}
```
And falsey values for:
```
{}
{"E2-E4","E7-E5","F2-F4"}
{"B1-C3","B8-C6","C3-B1","C6-B8","B1-C3","B8-C6","C3-B1","C6-B8","F2-F4","F7-F5"}
{"E2-E4","E7-E5","G1-F3","B8-C6","F1-C4","G8-F6","F3-G5","D7-D5","E4-D5","F6-D5","G5-F7"}
{"D2-D4","B8-C6","E2-E4","C6-D4","D1-E2","D4-C6","E2-D1","C6-D4","D1-E2","D4-C6","E2-D1"}
{"B1-C3","B8-C6","C3-B5","C6-B4","B5-D4","B4-D5","D4-C6","D5-C3","C6-B8","C3-B1","B8-C6","B1-C3","C6-B8","C3-B1"}
{"E2-E4","E7-E5","D1-E2","E8-E7","E1-D1","D8-E8","E2-E1","E7-D8","E1-E2","E8-E7","E2-E1","E7-E8"}
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~55~~ ~~49~~ ~~47~~ ~~45~~ 44 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
-4 thanks to ngn.
Full program. Prompts for reversed list of reversed coordinate pairs:
e.g. `{"B1-C3","B8-C6"}` is `[[[8,2],[6,3]],[[1,2],[3,3]]]`
```
2≤≢s∩{0,∘⊃@⍺⊃s,←⊂⍵}/⎕,⊂(⊖⍪-)¯4↑⍉6,⍪5,∘⌽⍥⍳s←3
```
[Try it online!](https://tio.run/##xVM9SwNBEO39FSHNJXCD7uW@EAtNdi9goYWlWAgJNsEEY6GENCoxOV1RRLEUUVARLCSNYJOfMn8k7t7uajRBAype85h7M28eM7OrtQqUtlcr1TUob22W10vlUh/b@7W@g51r7FzVsX3XyEzZGO9mZ5E/C6zb2DrGeAd5tzmJR2eC28lgfI78HrK9RxdbJ8g7vi1iz8b2BR6@IL9B/lQXdTmpPlGoVjdKMmw4M6KJUJoWWb3b3q2ADMHWqdClWVnMn2adhDg6m9MxkbEFVgY7lxi3ML7KJvz80uJCiggFa2XZsqVK7zHR4l082EP@0Oynkq@mDaSsRjpPoJBL2@l8CAVfYCEHeSLRh3wo/3/JN62J35b8lZbUAepKDIB6EglQydMQ6DgtaQ6o5KkPNByqH2nBtDQSzAHmqhbKCgHmSHSBaT6SkkzzkWnpags639QzMsyTN/4fFmH4Ua1H2jETYQEwuZRITOCPnCtpgQFEXnosN0Wi9mEkI9FC8sUQIl/tp@gNnBRzFUa@wqIHUfDj0zA8Jd/yYw/O04NJLHjainb/dk2eqjMDNAM1Okb3Iz/WYI17FgILBg9ZxKGeBlH5yVtjn/PfeSaf/ys "APL (Dyalog Unicode) – Try It Online") (includes the utility function `Coords` which translates OP's format)
**Set up a list of states:**
`s←3` assign three to `s` (for **s**tates)
Since 3 is not a valid board state, it will not affect our repetition count, and we need the pass-through value of the assignment…
**Build a chess board representation:**
`5`… discard that for the result of applying the following derived function between 5 and 3:
`⍥⍳` extend both arguments to their **ɩ**ndices;
`[1,2,3,4,5]`…`[1,2,3]`
`,∘⌽` the left side concatenated with the reverse of the right side
`[1,2,3,4,5,3,2,1]` this represent the officers
`⍪` make into table;
`[[1],`
`[2],`
`[3],`
`[4],`
`[5],`
`[3],`
`[2],`
`[1]]`
`6,` prepend (to each row) a six, representing pawns;
`[[6,1],`
`[6,2],`
`[6,3],`
`[6,4],`
`[6,5],`
`[6,3],`
`[6,2],`
`[6,1]]`
`⍉` transpose;
`[[6,6,6,6,6,6,6,6],`
`[1,2,3,4,5,3,2,1]]`
`¯4↑` take negative (i.e. the last) four (rows), padding with zeros, representing empty squares;
`[[0,0,0,0,0,0,0,0],`
`[0,0,0,0,0,0,0,0],`
`[6,6,6,6,6,6,6,6],`
`[1,2,3,4,5,3,2,1]]`
`(`…`)` apply the following tacit function to that:
`-` negate (this represents the opposite colour);
`[[ 0, 0, 0, 0, 0, 0, 0, 0],`
`[ 0, 0, 0, 0, 0, 0, 0, 0],`
`[-6,-6,-6,-6,-6,-6,-6,-6],`
`[-1,-2,-3,-4,-5,-3,-2,-1]]`
`⊖⍪` stack the flipped argument on top of that, giving us the full board;
`[[ 1, 2, 3, 4, 5, 3, 2, 1],`
`[ 6, 6, 6, 6, 6, 6, 6, 6],`
`[ 0, 0, 0, 0, 0, 0, 0, 0],`
`[ 0, 0, 0, 0, 0, 0, 0, 0],`
`[ 0, 0, 0, 0, 0, 0, 0, 0],`
`[ 0, 0, 0, 0, 0, 0, 0, 0],`
`[-6,-6,-6,-6,-6,-6,-6,-6],`
`[-1,-2,-3,-4,-5,-3,-2,-1]]`
**Construct a list of moves followed by the initial state:**
`⊂` enclose that (to treat it as a single unit)
`⎕,` prompt for the list of moves, and prepend that to the initial state
**Reduce\* by a function which appends the current state to the list and makes a move:**
`{`…`}/` reduce by the following anonymous lambda:
`⍵` the right argument (the current state)
`⊂` enclose it to treat it as a unit
`s,←` in-place append it to the list of states
`⊃` disclose it to use that state
…`@⍺` at the elements with the two coordinates that the left argument represents, put:
`0` a zero
`,` followed
`∘` by
`⊃` the first value
this effectively "moves" the value at the first coordinate to the second coordinate, leaving behind a zero
**Check if we have three or more of the final state:**
`s∩` the intersection of all states with that final one; the subset of states identical to it
`≢` tally them up
`2≤` check if there are two or more (i.e. three or more including the final state)
---
\* APL is right-associative, so first the function is called with the initial state as right argument and the initial move as left argument, and then its result, the new state, becomes the new right argument with the second move as new left argument, etc. The final result is the
[Answer]
# [R](https://www.r-project.org/), ~~180~~ ~~177~~ 144 bytes
```
function(M,`+`=rep,l=c(1:5,3:1,6+8,0+16)){z=rev(Reduce(function(x,y){x[y[2:1]]=x[y]*1:0;x},M,c(l,-rev(l)),,T));sum(sapply(z,identical,el(z)))>2}
```
[Try it online!](https://tio.run/##vVNLj5swGLzvr0A52Rt/qzXh4Saih8Qm6mEv1d4ipCWErJCARGCqPJTfntoBJ9vNqo3UbU8DHn8zw9hUR1nFZb1cVYUVWMumTGS2KlGB93eWFaulpsyzWqJaVvU6zyQqiNWDHsaarh9OnMJFLOOHZRUXKSpiWWUbVMfrdb5FMbmIbvB@HjRyyZ5X30qpXkfWfEYj8Jw@u0fzmR2B8wUfMLGx0j/cvQbH8@wTeem/BFW6JnmQIDp0yWBIiddn5LFPPYz3O0X@QN/TRZOk6GJJtni/mW1n9pBGUaCeons6fBxtDuSJJCgnoKdyjAl5xnhUN4UJviPZIi1llsQ5SXO0U5G@2ofjKzr3hRLUG1OYDHqkN2Yw8RROBjCmGj0YM73@W15/5qcKfoIht4E7Gn3grkYKXPOcAb/FkA@Aa557wNnV/AcBjKEREDYIpzVog1AQtkYHRMeHWlB0fGgMnS5At9/MC3rN0zP/34/A8K1xgq79TQHCB6FPIFQf/E@CtsIKfQjdjwzeJ5nStnojGCoDzU8ZhF57FFP3zd0RTouh1@LUhdD/yztgeE7/yN9YmdtVcgrgdkG65OdL47ZzpjpTpdExur/yN1RqkgsGwn97W9U765qg7f7T7yTe77/w4vR/H38C "R – Try It Online")
-3 bytes [thanks to Giuseppe](https://chat.stackexchange.com/transcript/message/49765891#49765891)
-29 bytes thanks to Nick Kennedy's use of `Reduce` and `-rev(l)`
-4 bytes by reversing `z`
Takes as input a vector of integers between 1 and 64 denoting the squares. The TIO includes a function to transform into that format. The different pieces are stored as integers between 1 and 6 and between -1 and -6.
Explanation:
```
function(M, # M is the vector of moves
`+` = rep,
l = c(1:5, 3:1, 6 + 8, 0 + 16)) { # initial position of white pieces
z = rev(Reduce(function(x, y) {
x[y[2:1]] = x[y] * 1:0 # a piece moves from y[1] to y[2]; y[1] becomes 0
x
}, M, c(l, -rev(l)), , T))
sum(sapply(z, identical, el(z))) > 2 # find number of past positions identical to the last position
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~41~~ 37 bytes
```
Ø0;6x8;“Ġ²F’D¤UN;ƊW;µị@⁹Ṫ¤¦0⁹¦$\ċṪ$>1
```
[Try it online!](https://tio.run/##tVLLSgMxFN37GUPd9UrTmWQCAyLTJLNTqBQX2qUb6QfornVTsD9QwYVg6UJcCS6KrjLF/@j8SL1pklpttT5h4Exy7j0n9yQnx63W2XSa9ysJO@VJ0b4aX@t7VbQvhR40dpPni4NEP0weeztFZzQZ3eqBHlbwVw9LR@MebpS2yXRvMropzu8iuklYA1vz4RYu8eNFu593N/Iu/s89aF0PkrDeWKtfdJ6wz3jso8lhkBKohUE5SDnUGGIthJQYZJBys/8p3yz/VuEnDqIKIjIYg6AGCQjDCw7iKw4iBGF4wUDwpX7j6B18h6yCjKyidSYgqwYjkI5XRkE6XnmHyDm6et8vyTJP5vz/p@p5dDJmfjwZgzSBKhznb45hlRBjUDRY5ZURG51XUKho@IyDYjbKjC5ctowsKmYxo6Di716a5wVZy3@UAnVTzhypc3Znm18rtX0@DZ@O1/G6b/lVKfmzSQ4yXnxAuOZuVmLrZ09avq9/5bG@@QI "Jelly – Try It Online")
A monadic link that takes the input as a list of pairs of 1-indexed row-major moves `[from, to]` and returns a 1 for draws and 0 for not.
Note the footer code on TIO translates the moves as supplied by the OP to the numeric format, but per the discussion below the question, the numeric format would have been a valid input.
### Explanation
```
Ø0 | 0,0
;6 | concatenate to 6 (pawn)
x8 | repeat each 8 times (two blank rows and 1 row of pawns)
;“Ġ²F’D¤ | concatenate to 1,2,3,4,5,3,2,1
UN;Ɗ | concatenate a negated flipped version to this one
W; | wrap as a list and concatenate the input list to the board
µ | start a new monadic chain
$\ | reduce using the two links below
ị@⁹Ṫ¤¦ | replace the item pointed to by the second coordinate by the value of the one at the first
0⁹¦ | replace the item at first coordinate with zero
ċṪ$ | finally count the items equal to the final one (not including it)
>1 | and check of >1
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~121~~ 111 bytes
Expects the moves in `[sq0, sq1]` format, where each square is in \$[0..63]\$ with \$\text{a8}=0\$, \$\text{b8}=1\$, ..., \$\text{h1}=63\$.
Returns a Boolean value.
```
a=>[a,...a].map(([x,y])=>r=b[b[b[y]=b[x],x]=0,b]=-~b[b],b=[...'89ABCA981111111'+10n**32n+0x7e5196ee74377])&&r>2
```
[Try it online!](https://tio.run/##tVNLs5owGN37KzIsrkSRITzjAmcuJKG7brpLs0AvtnYE7xXb0U3/us3LkTrVTqctLA7JyTnfK3ypv9X9ar95Pcy63UtzXufnOl/w2vN9vxZ@W7@6Lj96JwHzxT5fcvWehPw4Cu8o8sBbinz2Xe4Kb5lzKRrj@XNRPs8xMs94ioJuMonCbhocsyZB87RpsjjKMgGfnvaL8Ny/gRy0IF8ARyoJZdU7x990L83x/dpteSAgmAIXgxloOZKLCcCjQ9MfpKpWqtWu63fbxt/uPrlrt9Y5azsO@je39fvtZtW4gQdCCL3hllwDASEcjYYWY/5h//Xw@STGUIdxuVOgMnI8p8BlKqGMCqQgLbDavMvJVP/O4LH5r71JSGIFGUkUIKI4gsnvvElEFEdSgm9010jW2ypoSGPtZgIiGiqIqeGY0lPDMesdm0jmpNVRdMOhCyfg/@ue5cTt6D92nNXbfjD7axa2XppR1VkWsn@RoraRkLHEuReqQmygZ6hUXIWZXkVVch03jTWwVEOVsOxPp2c5gh5yD@pOTG06UmICmqQuE060wJZvm2Hl1mzI3euJTYpimg0uEabYlIb0SX2V6c8nLxxVv9D5Bw "JavaScript (Node.js) – Try It Online")
## How?
### Pieces
The values used to identify the pieces do not really matter as long as there's one unique value per piece type.
We use:
* **0** for empty squares
* **1** / **8** / **9** / **A** / **B** / **C** for ♟ / ♜ / ♞ / ♝ / ♛ / ♚
* **2** / **3** / **4** / **5** / **6** / **7** for ♙ / ♖ / ♘ / ♗ / ♕ / ♔
### Board and initial position
The board is stored in the array \$b\$ which is initialized by splitting the concatenation of the following parts:
* `'89ABCA981111111'` → the 8 black major pieces, followed by the first 7 black pawns
* `10n**32n` → the last black pawn on \$\text{h7}\$ (\$1\$) followed by 32 empty squares (\$0\$)
* `0x7e5196ee74377` → all white pieces (expends to `2222222234567543` in decimal)
which results in:
```
a b c d e f g h
+----------------
8 | 8 9 A B C A 9 8
7 | 1 1 1 1 1 1 1 1
6 | 0 0 0 0 0 0 0 0
5 | 0 0 0 0 0 0 0 0
4 | 0 0 0 0 0 0 0 0
3 | 0 0 0 0 0 0 0 0
2 | 2 2 2 2 2 2 2 2
1 | 3 4 5 6 7 5 4 3
```
### Keeping track of the positions
The variable \$b\$ is also used as an *object* to keep track of all encountered positions. The key for each position is \$b\$ itself, but this time as an *array* and implicitly coerced to a string.
This is why we do:
```
b[b] = -~b[b]
```
## Commented
```
a => // a[] = input
[ a, // dummy entry to mark the initial position as encountered once
...a // append the actual data
].map(([x, y]) => // for each pair of squares [x, y] in this array:
r = // store the last result in r
b[ // update b[b]:
b[ // update b[x]:
b[y] = b[x], // set b[y] to b[x]
x // set b[x] ...
] = 0, // ... to 0
b // set b[b] ...
] = -~b[b], // ... to b[b] + 1 (or 1 if b[b] is undefined)
b = [...(…)] // initialize b[] (see above)
) // end of map()
&& r > 2 // return true if the last result is greater than 2
```
[Answer]
# Java 10, ~~336~~ ~~330~~ ~~287~~ ~~285~~ ~~282~~ 276 bytes
```
m->{var V=new java.util.HashMap();int i=64,A[]=new int[i];var t="";for(;i-->0;)t+=A[i]=(i%56<8?i%8*35%41%10%8+2:9>>i/16&1)*(i/32*2-1);V.put(t,1);for(var a:m){for(t="",A[a[1]]=A[a[0]],A[a[0]]=0,i=64;i-->0;)t+=A[i];V.compute(t,(k,v)->v!=null?(int)v+1:1);}return(int)V.get(t)>2;}
```
-11 bytes thanks to *@Arnauld* by changing `i%56<8?"ABCDECBA".charAt(i%56%7):i%48<16?1:0` to `i%56<8?i%8*35%41%10%8+2:9>>i/16&1`.
Input as a 2D array of integers where \$a1=0, b1=1, ..., h8=63\$ (i.e. `{"E2-E4",...` is `[[12,28],...`).
[Try it online.](https://tio.run/##7VpRb9owEH7vr/CQmGIggdAkTUnD1DVJ99K@dOpL5AeXpsU0BBQMU4X47cwmZe2KkaIY1opFQkns@O78ne@Lz8YDPMPq4P5p2YvxZAKuMEnmRwCQhEbpA@5F4JoXAbgbjeIIJ6CnsFchChEYQoe9WRyxy4RiSnrgGiTABcuh2p3PcApu3ST6BQbMgDalJNZ@4En/Co8V6DAVgLiW0TgP0aoR10mQw6WoW6k4D6NUcYiqdlsOpHX3nL10FVI1rTP7G6natWOzauhVvVW16@3OabdLmrr1VYc1hTSP27W2qkPnVhtPqUIb7JFr46pxZwjnvMBtMNs41BFy@b2FUOPl7rYavGvvrDN1vdGQaYyYSuWpMYNqd/bFTaZx/I17BM7qeoeZWqQRnabJqupWe4xYD2C37SyWDvfTeHoXMz@9uGs2IvdgyByu3NCUJI/Mpxhm3m42wc90SvvPnVXx5nlCo6E2mlJtzFrSOFESrafQFCcThmfoYYoV7sdeH6d8cEKU6QHgbe288l2vaHR0wcrnaYqfFdgAlYvjd3WLhljWFsha@WQ3bDDZjb5sk7UEsnbOPh8s3gWEK/6VwVEGR0mGwyGD196U9YycsicCWTOnrACvlxOvJ8DrlWQQ@0qA18uJ1xPg9ezPMr57IKEMGWQGyRfY9Y3iQZmbwIJB2ujLNllDICuBN8gZHL4E3kCGDIYECSX8LDO@vv6J8Oq7xFumo2V6VuLdAd6MSOtNgADHk2j7JkAhyrVQ9ts9Y2WmTV@Qu/o5c9dANH2Vn6iSsrJ48wXWFllBQAfmPwjKj2LhpV48iZQJjkAUlDnxXgrsBlbx5PXS3P9K3TeKywZWcdkNbNxXJ@Uq8NOvAmXwevr/jvfQ0wZTYhrNS0JTgsASXzupJbNZfIxkUg6ZVEcmNmRicv94DyhNkvna@YIB3ujLPvaeRHZtiVlUL@7nvBve/kf5ecd4/a3/dr09erE@lPE3D1458OdkwbphClywPnmBtThKHmkfhW2UsYwfksgOabQcQM7WDdhzvQ5fur5uM@BtBmdtdnl9CUAaEhQOEDOj4Owx1JFqnMKaDepgXdVCqmVmNrOTEyDNoC2WvwE)
**Explanation:**
```
m->{ // Method with 3D character array parameter and boolean return-type
var V=new java.util.HashMap();
// Create a Map to store the occurrences of the board-states
int i=64, // Index integer, starting at 64
A[]=new int[i]; // Create the 8 by 8 board
var t=""; // Temp-String, starting empty
for(;i-->0;) // Loop `i` in the range (64,0]:
t+= // Append the string `t` with:
A[i]= // Fill the `i`'th cell with:
i%56<8? // If it's either the first or eighth row:
i%8*35%41%10%8+2
// Fill it with 2,7,3,5,9,3,7,2 based on index `i`
:9>>i/16&1) // Else if it's either the second or seventh row:
// Fill it with 1
// Else (the third, fourth, fifth, or sixth rows):
// Fill it with 0
*(i/32*2-1); // Then multiply it by -1 or 1 depending on whether `i`
// is below 32 or not
V.put(t,1); // Then set string `t` in the map to 1 for the initial state
for(var a:m){ // Loop over each of the input's integer-pairs:
for(t="", // Make the String empty again
A[a[1]]= // Set the to-cell of the current integer-pair of the input to:
A[a[0]], // The value in the from-cell of the same integer-pair
A[a[0]]=0, // And then empty this from-cell
i=65;i-->0;) // Inner loop `i` in the range (64,0]:
t+=A[i]; // Append the `i`'th value to the String `t`
V.compute(t,(k,v)->v!=null?(int)v+1:1);}
// Increase the value in the map for String `t` as key by 1
return(int)V.get(t) // Return whether the value in the map for the last String `t`
>2;} // is at least 3
```
The values of the pieces after filling them with `A[i]=(i%56<8?i%8*35%41%10%8+2:9>>i/16&1)*(i/32*2-1)` are:
```
a b c d e f g h
+------------------------
1 | -2 -7 -3 -5 -9 -3 -7 -2
2 | -1 -1 -1 -1 -1 -1 -1 -1
3 | 0 0 0 0 0 0 0 0
4 | 0 0 0 0 0 0 0 0
5 | 0 0 0 0 0 0 0 0
6 | 0 0 0 0 0 0 0 0
7 | 1 1 1 1 1 1 1 1
8 | 2 7 3 5 9 3 7 2
```
[Try it online.](https://tio.run/##JY7LDoIwEEX3fsVsalqUalEJimD4AFcuCYv6zCAWQweNMX47Vlzd5J6Zm1Pqh/bL47XrDpW2FrYazXsAcG/3FR7AkiYXjxqPcHOI76hBc8kL0OJ3BoCGAJNwPs7yIjGn56/IsYh7eK4bHqPvp9NY9AVA5mDCkS3CdbRBFnmzBZsrpqYsGgWrZZriRIVDJTyOk1ngBb4S/63dy9LpJuuW5N05UGV46eRlS1jJrGn0y0qq/348E/3XZ/Dpui8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 62 bytes
```
≔↨²³⁴⁵⁶⁴³²χηF⁴⁸⊞η÷⁻⁴⁰ι³²F…η⁸⊞η±ιFθ«⊞υ⮌η§≔η⊟ι§η§ι⁰§≔η⊟ι⁰»›№υ⮌η¹
```
[Try it online!](https://tio.run/##hVBLS8QwED5vf8UcJxChj9QteForyB6U4rX0ULrjJlBSTdqiiL89TlbWx0VvX77HzDcZdO@GqR9D2Hlvjhave0@YF6q8VEUuIUuFBC2uksfJAapKQLN4jVrC3s43ZjUHwjtjF48qlWDYXOTibK9fh5FqPT1FfyW@s/d07GdC8@V8FvCWbE7yIuGBVnJcQ0d981lsN@/tgV5iuuGBcdMP6gyNhFT8nUpZfU8aZ@yMt464h8N6Wvj1ezPfzoNCaNs2Y1x1EtpyK0HlEWUVcxEo/qRye6L@d3VduFjHDw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of pairs of numbers where the squares are numbered `A1`, `B1`, ... `H8` (0-indexed) so for instance the first test case would be represented as `[[[1, 18], [57, 42], [18, 1], [42, 57], [1, 18], [57, 42], [18, 1], [42, 57]]]` and outputs a `-` if the position is a draw by repetition. [Conversion program.](https://tio.run/##hY6xCsIwEIZ3nyLcdIFkKIUScEudCkXRsWQIbcBATGqsff2YVAU3p/vu/47jH686jkG7lE7R@gVhGIDud@@lC9Zjr2e8M7IxDAo@WOLL7OyClhHgQBmR@mFQMFLU2awm5tXlvA/T0wU8mDGam/GLmfAYJ@u1Q0@zF5SWkT/DD3xLgFK5UUq5mKx4WxcrBW@bAm3NZbVBw6XY1L8bpRJf3Qs "Charcoal – Try It Online") [All in one.](https://tio.run/##hZDBasMwDIbP7VOYnGRwIGmyEtipcWH00K1sx9KDSbTG4Nitk5SNsWfPlJSU7dL5JOn79UtWUSlfOGX6fqtO0tW1siWcBaMM3k5Gt6AFC8KAC5arBiG7ole8oKfUUH3rys44WGPhsUbbYgkvvtRWGbCceMaH9zhfNY0@WhhtFkn6sEyThWBxRJKK8LvzDNKMs13XVFAJtrHtWl90ibDVtmsgjQTTJE4WfJLLz8KgrNxp0NOcW@8zHlWLoG/KM2df89mIO8Gm9auBz66LrdqNLfFj6N6R4TDpV2kK6RoRv98VEf2e77y2LTx5pD08SNdR9ncy/Z2M@n6/D/I4lElAh86zUC6HQCZhHo/BMsyzEf2nORz68GJ@AA "Charcoal – Try It Online") Explanation:
```
≔↨²³⁴⁵⁶⁴³²χη
```
Split the number `23456432` into individual digits. These represent the white pieces.
```
F⁴⁸⊞η÷⁻⁴⁰ι³²
```
Add in the pawns and the empty rows. The white pawns have value `1` and the black pawns `-1`.
```
F…η⁸⊞η±ι
```
Append a negated copy of the white pieces, which represent the black pieces.
```
Fθ«
```
Loop over the moves.
```
⊞υ⮌η
```
Save a copy of the board. (Reversing is the golfiest way to copy the board.)
```
§≔η⊟ι§η§ι⁰
```
Update the destination with the source piece.
```
§≔η⊟ι⁰
```
Remove the source piece.
```
»›№υ⮌η¹
```
Determine whether the current position was seen more than once before.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 204 bytes
```
n=>{var j=new List<char[]>();var d=("ABCDECBATTTTTTTT"+new string('Z',32)+7777777712345321).ToArray();foreach(var(a,b)in n){j.Add(d.ToArray());d[b]=d[a];d[a]='Z';}return j.Count(r=>r.SequenceEqual(d))>1;}
```
Takes input as a list of tuples of integers, where the first integer is where to move from, and the second is where to move to. 0 represents A1, 1 is A2, and 63 is H8.
[Try it online!](https://tio.run/##rVPRbpswFH3PVyBeYi84mQMEJgpSEkw0KU9LpkmLeHCALEQpaQy0qqJ8e2bXJmnXdu20IsGRfe49x/f6kpQoKfNTVBfJ1VdS1NcZo8ttdgXyojL4CwNjudttg5V/KvzgcEuZtvGL7E6b5mV1lawpW8QBgJ4gUh/ow9E4JOPRcK4evSOCy4rlxS/Q/tk2zD7sOOrBfdOyzT6G3fluyBi950KrHctosgZcEFBjCfNCK@Bh0x2mKUgvcdBLF8vYTxc09sTH59rekWVVzQpt0x3v6qICzA9Yd5bt66xIMrKv6RakEAbYO5681rnCcg/k@TQKVYG0O7vZ5hVoozb0FJn4m8Xn2Eg54NiTTgAkfIGsL/CT20k4jQa2AdLLXir3oHds3e7yVFuDG8rodak6sohTePjB8iqb5kUGVrzCWbbNkgqUewhFVq83//adtC4x@mLO6mp9H@vQa62BPsJobOqGPnLReMBxbKIRFjhAI1fs/5WHnvb/Im@bvOQR9lFoCXRQaAvEKBR86KLwPR6hiULBhwMUus/ypWfj0eSQPiKW1JTeGJG@QAsRxUdCgyg@ajws5anim3yCn/P4zH/EBb2X5169XjSczp7OSkS35XlUmuqJg4joeMSr/ahTSi2ODorsV/wmWHa30Yi4puAnLooGstsT@9FEEEtiNJA4sVHk/PvNNnyI3@Rf74Wtan3wtJW3Ot/59m2Z1/Sk6VGj0@g@5V/uVXM@4iLiPJ40vnZVvVjGP0w/@TP@whPxB55@Aw "C# (Visual C# Interactive Compiler) – Try It Online")
```
n=>{
var j=new List<char[]>(); //Initialize a list to save states of a board
var d=("ABCDECBATTTTTTTT" + //White pieces
new string('Z',32) + //Empty spaces
7777777712345321) //Black pieces
.ToArray(); //Initialize the chessboard
foreach(var(a,b)in n){ //Foreach (source square, destination square) in the input
j.Add(d.ToArray()); // Add the current board to the list
d[b]=d[a]; // Set the destination square to the source square's value
d[a]='Z'; // And set the souce square to empty
}
return j.Count( //Return that the amount...
r=>r.SequenceEqual(d) // of past positions that are equal to the current position...
)>1; //is at least two
}
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~246~~ ~~245~~ 244 bytes
```
import java.util.*;n->{var j=new ArrayList<char[]>();var d=("ABCDECBATTTTTTTT"+"".repeat(32)+7777777712345321l).toCharArray();for(var k:n){j.add(d.clone());d[k[1]]=d[k[0]];d[k[0]]=1;}return j.stream().filter(x->Arrays.equals(d,x)).count()>1;}
```
[Try it online!](https://tio.run/##rVNNc9owEJ1e@RUan6QmEjXY4OLCDGCZS5pDSU8eHxTbgImxiS3SZBh@O5VsKUnz0aTT6OAd62nf231ardkNw@v46phutkXJwVr8kx1PM/LZbbW2u8ssjUCUsaoC31mag30LiJXmPCkXLErAebMh12VRZAnLwQIKOAiDMEduDR7qb8UZF1znIB8eczza37ASrId58guMy5LdnaUV/xatWBmEI4hcicZDaIwnU49OJ@MLtYwT45NBymSbMA67HXTSV8vsdC272zEzRHgxFTw1q2BaFCWUbFeDHO3XhMUxjEmUFXkCEXLj4Coww3Ao45cwdFUcmu6hTPiuzMGaVLxM2AYiskgz0Te8xaOavCLJ9Y5lFYxPbxEiUbHLOUQjkXpsuS3Vb@1FdQ3nvEzzJYhQ3fhyGD0pU6lJP@qU/VLUgXv2CVyKArH1FX12TpdBV@9Zau/gHrTUTZHGYKWUCCEx2s/vKp5sSLHjZCt2eZbDnCzgwy03vZF5E4oFjBHZsC2Ulz0YVNfSzaZEdamDgSgRCecOejoeq29EmiogCAErlxUSI9NuX/z4SVsvFGMEF@WOr@5CQ8zKChoTE0@7xqkxcfC0J@K0iyemjD08ceT@X3Hkgv8neVvkJQ2vgz1Lxj72bBlN7Encc7D3Hg2viz2Jez3sOc/yG02toXNoB1Or4Wy0TUw7MlqYKtyXHFThvtawlKY6r/Op@Rw37/GPuKD34kKr3fbHZ/NXhsYXr@5@ZrQNtI@ptN4XbX9UuQ2XiH3s26/ozczGZs3hC06Jzxzs9xrbZ/aj0aBWE/1eE2c29vv/fsUa98w38de9sFWvtaattFV992NgN3naE@2R5tG8f@Ive6Xrow6m/ccjJ/4d1a/ZnK@fAX16/gGn9VM8tA7H3w "Java (JDK) – Try It Online")
```
import java.util.*; //Import the java.util package
n->{ //Function taking in int[][],
//where each int[] is a a pair of numbers
var j = new ArrayList<char[]>(); //List to save each position of the chessboard
var d = //The chessboard's starting position
("ABCDECBATTTTTTTT" + // All the white pieces
"".repeat(32) + // Plus the empty squares
7777777712345321l) // And the black pieces
.toCharArray(); //Split to array of chars
for(var k:n){ //Foreach [sourceSquare, destinationSquare] in input
j.add(d.clone()); // Add the current position to the list
d[ k[1] ] = d[ k[0] ]; // Set the destination square's value
// to the source squares
d[ k[0] ] = 1; // And clear the source square
} //End foreach
return j.stream() //Convert list of states to stream
.filter(x -> //Filter each position by
Arrays.equals(d,x) // if the position equals the final position
).count() > 1; //And return if there are at least two
//positions that are left
}
```
] |
[Question]
[
A numerical polynomial is a polynomial \$p\$ in one variable with rational coefficients such that for every integer \$i\$, \$p(i)\$ is also an integer. The numerical polynomials have a basis given by the binomial coefficients:
$$p\_n = {x \choose n} = \frac{x(x-1)\cdots(x-n+1)}{n!}$$
For instance:
\$p\_0 = 1\$
\$p\_1 = x\$
\$p\_2 = \frac{x(x-1)}{2} = \frac{1}{2}x^2 - \frac{1}{2}x\$
\$p\_3 = \frac{x(x-1)(x-2)}{6} = \frac{1}{6}x^3 - \frac{1}{2}x^2 + \frac{1}{3}x\$
The product of any two numerical polynomials is a numerical polynomial, so there are formulas expressing \$p\_m\times p\_n\$ as a linear combination of \$p\_0, p\_1, ..., p\_{m+n}\$.
Your job is to produce these formulas.
## Goal:
Input: A pair of positive integers \$m\$ and \$n\$
Output: The list of integers \$[a\_1,...,a\_{m+n}]\$ of length \$m+n\$ such that
$$p\_m\times p\_n = \sum\_{i=1}^{m+n} a\_ip\_i$$
This is code golf, so shortest code wins.
## Examples:
**Input: (1,1)**
We have \$p\_1 = x\$, so \$p\_1\times p\_1 = x^2\$. The leading term is \$1x^2\$, and the leading term of \$p\_2\$ is \$\frac{1}{2!}x^2\$, so we set \$a\_2 = \frac{2!}{1} = 2\$. Subtracting off \$2p\_2\$ we have \$p\_1\times p\_1-2p\_2 = x^2 - (x^2 - x) = x\$. Thus, we see that \$p\_1\times p\_1 = p\_1 + 2p\_2\$, so the output should be \$[1,2]\$.
**Input: (1,2)**
\$p\_2 = \frac{1}{2}x(x-1)\$, so \$p\_1\times p\_2 = \frac{1}{2}x^2(x-1)\$, which has leading term \$\frac{1}{2}x^3\$. The leading term of \$p\_3\$ is \$\frac{1}{3!}x^3\$, so we set \$a\_3 = \frac{3!}{2} = 3\$. \$p\_1\times p\_2 - 3p\_3 = x^2-x = 2p\_2\$, so we deduce that \$p\_1\times p\_2=0p\_1 + 2p\_2 + 3p\_3\$, so the output should be \$[0,2,3]\$.
**Input (2,2)**
The leading term of \$p\_2^2\$ is \$\frac{1}{4}x^4\$, so we start with \$p\_2^2-\frac{4!}{4}p\_4\$. This has leading term \$x^3\$, so we subtract off \$\frac{3!}{1}p\_3\$ to get \$p\_2^2-\frac{4!}{4}p\_4-\frac{3!}{1}p\_3\$. This expression turns out to be equal to \$p\_2\$, so rearranging we get that \$p\_2^2 = 0p\_1+p\_2+6p\_3+6p\_4\$, so the output should be \$[0,1,6,6]\$.
## Test Cases:
```
(1,1) ==> [1,2]
(1,2) ==> [0,2,3]
(1,3) ==> [0, 0, 3, 4]
(1,4) ==> [0, 0, 0, 4, 5]
(2,2) ==> [0, 1, 6, 6]
(2,3) ==> [0, 0, 3, 12, 10]
(2,4) ==> [0, 0, 0, 6, 20, 15]
(3,4) ==> [0, 0, 0, 4, 30, 60, 35]
(4,4) ==> [0, 0, 0, 1, 20, 90, 140, 70]
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~20~~ 18 bytes
```
,((×⌿!\)⌹⊢!⍨\⊢)⍳⍤+
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgmG/3U0NA5Pf9SzXzFG81HPzkddixQf9a6IAdKaj3o3P@pdov0/DajuUW8fREtX86H1xo/aJgJ5wUHOQDLEwzP4v6FCmoKhwqPeuUDSiAvEMwLzDIC0MZhvDOUbAFkmYBETuIgBkG3KZYSky1DBTMEMLIKsz9BIwdAALIqs10zBCKjBlMsYw0xjoCRQnymXCZqUIUiLJZA2MVAwNwAA "APL (Dyalog Extended) – Try It Online")
A tacit dyadic function that takes `m` and `n` as left and right arguments respectively. Mainly uses the matrix division built-in `⌹` to solve the linear equations:
$$
\begin{bmatrix}
\binom{1}{1} & \binom{1}{2} & \cdots & \binom{1}{n+m} \\
\binom{2}{1} & \binom{2}{2} & \cdots & \binom{2}{n+m} \\
\vdots & \vdots & \ddots & \vdots \\
\binom{n+m}{1} & \binom{n+m}{2} & \cdots & \binom{n+m}{n+m}
\end{bmatrix}
\begin{bmatrix}
a\_1 \\ a\_2 \\ \vdots \\ a\_{n+m}
\end{bmatrix}
=
\begin{bmatrix}
\binom{1}{n} \binom{1}{m} \\
\binom{2}{n} \binom{2}{m} \\
\vdots \\
\binom{n+m}{n} \binom{n+m}{m}
\end{bmatrix}
\Leftrightarrow Ba = v $$
When \$ B \$ and \$ v \$ are ready, the answer is simply `v⌹B`. So the main work is to golf the parts to build \$ B \$ and \$ v \$.
### How it works
```
,((×⌿!\)⌹⊢!⍨\⊢)⍳⍤+ ⍝ Left argument: n, Right argument: m
,( )⍳⍤+ ⍝ Pass [n m] and [1 .. n+m] to the inner function
⊢!⍨\⊢ ⍝ Compute B
(×⌿!\) ⍝ Compute v
⌹ ⍝ Solve the linear equation
```
### Computing \$ B \$
`x!y` computes \$ \binom{y}{x} \$.
```
⊢!⍨\⊢ ⍝ Left: [n m], Right: [1 .. n+m]
⊢ ⊢ ⍝ Use right argument for both sides (L, R)
!⍨\ ⍝ Outer product by flipped binomial:
⍝ For each pair of l∊L and r∊R, compute r!l or lCr
```
### Computing \$ v \$
```
×⌿!\ ⍝ Left: [n m], Right: [1 .. n+m]
!\ ⍝ Outer product by binomial function
⍝ Result is a matrix of two rows [U V]
×⌿ ⍝ Reduce by multiply; compute U×V element-wise
```
[Answer]
# [Haskell](https://www.haskell.org/), 74 bytes
```
a%b|let a?i|a<1=0^(i-b)^2|d<-a-1=div(i*d?(i-1)-(d-i)*d?i)a=map(a?)[1..a+b]
```
[Try it online!](https://tio.run/##NY1BCsIwEEWvkoVCRjPFiMuGnMATlBR@SMHBtJRaXOXuMV24e//x4b3weU8514pzLHnaFbwU9NbdRi0cabyX1DPYuiRfLZfkm7bEOrFQW0JwM1YNT4PtOlxjqDNkOeRTrZss@0kNGiaaVqCi0PNxfASj4h9D/QE "Haskell – Try It Online")
Uses a recursive formulation I found. Let \$g\_b(a,i)\$ be the coefficient of \$p\_i\$ in \$p\_a p\_b\$, which is implemented in the code by `a?i` (with `b` fixed). We can express \$g\_b\$ recursively as
$$g\_b(a,i)=\frac{i\cdot g\_b(a-1,i-1)-(a-1-i)\cdot g\_b(a-1,i-1)}{a}$$
with base case
$$g\_b(0,i)=
\begin{cases}
1,\text{ if }b=i\\
0,\text{ otherwise}\\
\end{cases}
$$
The base case corresponds to the expansion for \$p\_b\$, which has a single nonzero coefficient of \$p\_i\$ at \$i=b\$. The code implements this indicator function as `0^(i-b)^2`.
The code has guards belonging to the definition of `?` in the `let` binding. It's perhaps easier to read as the following (non-working) code where the definition of `a?i` expects `b` as a global variable. Perhaps confusingly, the `a` in the definition of `?` is not always the same as the input to `%`, since it recurses down.
```
a?i|a<1=0^(i-b)^2|d<-a-1=div(i*d?(i-1)-(d-i)*d?i)a
a%b=map(a?)[1..a+b]
```
The main function `%` lists the coefficients for each `i` from 1 to a+b. It's possible to code the recursion in `%` directly by zipping shifted lists, but I did not find a short way to do it especially with the dependence on the position `i`.
[Answer]
# [Haskell](https://www.haskell.org/), 84 bytes
```
n#m=[foldr1(-)[i!k*k!n*k!m|k<-[i,i-1..0]]|i<-[1..n+m]]
_!0=1
n!k=n*(n-1)!(k-1)`div`k
```
[Try it online!](https://tio.run/##NUzBDoMgFLv7FaI7gIiRZMfhF2ynHRlRE7eIyNOo2y7@O0PNDm3apm1bz@bZ985BbIV8DX0zccyI1MgkBoGHXc2FSZ1qxrMsV2rV3noJ1CoVlCgXPABkBCQYGCcIG89Voz@VcRrG9zILiXXakf/wrNJue9yUCmytQdh6vJX4sddY4Tf3ZbrCaW6H755RGoVCFGFE6ZHFHSHHufsB "Haskell – Try It Online")
## Explanation
Given a polynomial \$q\$, the following algorithm (see [here](https://en.wikipedia.org/wiki/Newton_polynomial)) computes the unique coefficients \$a\_0,a\_1,\ldots\$ such that \$q=a\_0p\_0+a\_1p\_1+\ldots\$.
Let
$$
\Delta^{(0)}q(x)=q(x)\\
\Delta^{(i+1)}q(x)=\Delta^{(i)}q(x+1)-\Delta^{(i)}q(x).
$$
Then \$a\_i=\Delta^{(i)}q(0)\$.
Moreover, it can be easily proved that
$$
\Delta^{(i)}q(0)=\sum\_{k=0}^{i}(-1)^{i-k}{i\choose k}q(k).
$$
---
```
_!0=1
n!k=n*(n-1)!(k-1)`div`k
```
`n!k` is the binomial coefficient \$n\choose k\$.
---
```
n#m=[foldr1(-)[i!k*k!n*k!m|k<-[i,i-1..0]]|i<-[1..n+m]]
```
The function `#` computes the answer to the challenge. It simply uses the observation above to compute
$$
a\_i=\sum\_{k=0}^{i}(-1)^{i-k}{i\choose k}{k\choose n}{k\choose m}.
$$
The `foldr1(-)` is the only thing that needs explaining. When applied to a list \$[b\_0,b\_1,\ldots,b\_l]\$, `foldr1(-)` returns
$$
b\_0-(b\_1-(\ldots-(b\_{l-1}-b\_l)\ldots)=\sum\_{j=0}^{l}(-1)^jb\_j
$$
---
# [Haskell](https://www.haskell.org/), ~~108~~ 100 bytes
I'm also keeping this one. It is, in my opinion, more elegant, albeit much more verbose.
```
n#m=take(n+m).tail$head<$>iterate(zipWith(-)=<<tail)[x!n*x!m|x<-[0..]]
_!0=1
n!k=n*(n-1)!(k-1)`div`k
```
[Try it online!](https://tio.run/##JYxBDoIwFET3nIIKi9bSRhKXlBPoyoULJNrEJnxKvwSqEsPdsehmMnmZN40erem6ZcHEKa@tocgdk15DlzZG34u0BG8G7Q39QH8G31DBVFGsA1ZNBLcTcfNUiGonZV1HV7JTeYTEKtxSFDkj1Ia83eF1swtg//SjqihkLZshWLmU@zprQ4O11ZHTgMrp/nill99MlME5@eGA6dg83j/G@SZWqow3nP9Z0jL2P1@@ "Haskell – Try It Online")
---
```
_!0=1
n!k=n*(n-1)!(k-1)`div`k
```
`n!k` is the binomial coefficient \$n\choose k\$.
---
```
n#m=take(n+m).tail$head<$>iterate(zipWith(-)=<<tail)[x!n*x!m|x<-[0..]]
```
The function `#` computes the answer to the challenge. Let \$q=p\_n\cdot p\_m\$.
* `[x!n*x!m|x<-[0..]]` is the infinite list
$$
\left[{0\choose n}{0\choose m},{1\choose n}{1\choose m},{2\choose n}{2\choose m},\ldots\right]
$$
i.e.
$$
[q(0),q(1),q(2),\ldots].
$$
* Given a list \$[b\_0,b\_1,b\_2,\ldots]\$, the function `zipWith(-)=<<tail` returns \$[b\_1-b\_0,b\_2-b\_1,\ldots]\$. Thus the code `head<$>iterate(zipWith(-)=<<tail)[x!n*x!m|x<-[0..]]` returns the infinite list
$$
[\Delta^{(0)}q(0),\Delta^{(1)}q(0),\Delta^{(2)}q(0),\ldots]=[a\_0,a\_1,a\_2,\ldots].
$$
* Finally with `take(n+m).tail` we drop \$a\_0\$ and we take the first \$n+m\$ coefficients, thereby solving the challenge.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 46 bytes
```
m->n->b=binomial;[b(m,i-n)*b(i,m)|i<-[1..m+n]]
```
[Try it online!](https://tio.run/##LYnBCsMgEER/ZcnJbTWgya2NPyJ70EPKQrQSekih/24V9jJv3kyNJ5tXbTts0LLxxfi0JS7vzPF4hKSyZlPwlhTrjD9@mmDnOd8LUYu1Hl91gfFQTy6fXqchE@zqCpawpyNEDSFYDZZ66XTCRbgOOtmd@CL/Ir4OErY/ "Pari/GP – Try It Online")
I did not expect the formula to be so simple: the \$i\$-th element of the output for \$(m,n)\$ is \${m \choose i-n} {i \choose m}\$.
In fact, it can be proven that \$\sum\_{i=0}^{m+n} {m \choose i-n} {i \choose m} {x \choose i} = {x \choose m} {x \choose n}\$. The RHS counts the number of ways to choose two subsets of \$\{1,2,\dots,x\}\$ of size \$m\$ and \$n\$ respectively; while the LHS counts, for each \$i\$, the number of ways to choose a subset of size \$i\$, and two subsets of size \$m\$ and \$n\$ respectively whose union is the chosen subset of size \$i\$.
---
## [Pari/GP](http://pari.math.u-bordeaux.fr/), 62 bytes
Saved one byte thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).
```
m->n->b=matpascal(m+n);([b[i,m+1]*b[i,n+1]|i<-[1..#b]]/b~)[^1]
```
Sadly, GP does not have a built-in for pointwise product.
[Try it online!](https://tio.run/##LYlBCsMgEEWvMqQbbTRFk10aLzJMQQspQhRJs0ih9OpWwc289/4ku3v5SnmFBXKQJkrjlmCPZN9Pu7HQRz4zdOhF6BVdq8QiX3@XqIbh4ohu7sfxoSjblLYPO0EaSLuPR9GuRgcrO1ERL1cT5wIQlQBFRQp149g4Veq269Zj@4@tp0ri@Q8 "Pari/GP – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 37 bytes
```
b[r=Range@+##,#]b[#,r-#2]&
b=Binomial
```
[Try it online!](https://tio.run/##LcmxCsMgFIXhvU9x4EKWGko0q0X6BKWrOGhIWqEaELeQZzcId/r4z0m@/tbka1x826DRgi364/N3NXciQS5YEmUk6YZb0K@Y9xT9v71LzNUSxic2GANyGPAwOI5JYDoFupJV7NyVvEtuxb/inrtnuwA "Wolfram Language (Mathematica) – Try It Online")
-5 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att).
---
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
Table[b=Binomial;b[#,i-#2]b[i,#],{i,+##}]&
```
[Try it online!](https://tio.run/##LckxCsMwEETRqwwsuMmaYMldcBA5QYp0QoUUbLJgORDcCZ1dQbDV48/keH7WHE95x7ZhQXvFtK8@LQ85vlnifkueWEYyIXlhClyEL0Q1DO35k@P0hPGODc6BAgZcHUqZGFNldI1q1blrdDfaVn@rPXdr@wM "Wolfram Language (Mathematica) – Try It Online")
---
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 57 bytes
Saved one byte thanks to [Misha Lavrov](https://codegolf.stackexchange.com/users/74672/misha-lavrov).
```
Inverse[b=Array[Binomial,0{,}+##]].(b[[;;,#]]b[[;;,#2]])&
```
[Try it online!](https://tio.run/##LcnLCgIhFAbgVzkgDEWny@jshglr1669uHDCIWE0MAlCfHZLOKvvv3iTntab5B6mLjBBvYWPjW@r5ukSo/mqqwsv78yKp4xlx5jWh82s1DjiP1LgWm@7eo8uJMVgf4YFpASmoYOjhJx7hL4gNDkpyKHJaefUBf2C@tAs9Qc "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# JavaScript (ES6), 109 bytes
This is really just a port of [Delfad0r's great answer](https://codegolf.stackexchange.com/a/173986/58563), implemented as nested recursive functions.
Takes input as `(n)(m)`.
```
n=>m=>(g=i=>i?[...g(i-1),(h=k=>k&&h(k-1)-(b=(y,x=k)=>y?x*b(y-1,x-1)/y:i-k&1||-1)(k,i)*b(n)*b(m))(i)]:[])(n+m)
```
[Try it online!](https://tio.run/##dY7BbsMgEETv/QpO1tKCbQxtlUhLPsTyIUkThxLjqKkqW8q/u4t6aQuRRitW@4aZ9@3X9rr/cJdPGca3w3LEJaAd0EKPDq3btGVZ9uCk4gJO6NH6ojiBp13CDmEWE3qOdt5MjzuYpRITnap57aQv1O1GC3jhOB1DHAPn4Hi3bjsO4Wngy34M1/F8KM9jD0cgWnHOqoohWtYqwZruIUGaX0hNiGA6Q@m/FEkLZjKgSUCSEez5P9sk0VTwhZQBs@mKqqo6Q2cr0M9NzEh66PuddfTFsMRk7pjUT8oqPg2N17pbvgE "JavaScript (Node.js) – Try It Online")
### How?
The function \$b(y,x)\$ computes:
$$-(-1)^{i-k}{x\choose y}$$
It's slightly shorter to return \$-(-1)^{i-k}\$ as the last iteration of this function than processing it separately. Because we compute the product of three binomial coefficients, the signs of the first two of them are simply cancelling each other out.
The function \$h()\$ is used to compute:
$$\sum\_{k=1}^{i}-b(k,i)\times b(n,k)\times b(m,k)\\
=\sum\_{k=1}^{i}{(-1)^{i-k}{i\choose k}{k\choose n}{k\choose m}}$$
And the function \$g()\$ is used to compute each term \$a\_i\$ for \$1\le i \le n+m\$.
[Answer]
# [Maxima](http://maxima.sourceforge.net/), 55 bytes
Golfed version. [Try it online!](https://tio.run/##PYzBCsIwEETv@YqleMjq9tCkJ0V/JPQQ0cBiNy21h/x9bGBxLo83AyOxsMRakxXKeL1L/Lxn/u72yXkRjvPRc5/x/HcmQWIaSC4Z682YtGxQgDOEMBAME0GjU3rl2Oi0d@ped68@Nk7wWsAaOLJunHdbQjvtoH9AR5DUS3ATosFT/QE)
```
f(m,n):=makelist(binomial(m,i-n)*binomial(i,m),i,1,m+n)
```
Ungolfed version. [Try it online!](https://tio.run/##PY4xDsIwDEX3nOILMSTgDk07IcFFog4pUMlqnaDSIbcPDUR4eX7fkvXFJxaf86SFgsHlinGJ91kr7LNvftFs6Gvi5@fC702PHKLwfhHiJpjT35nEEJjQEuQcjDJHpaa4IoEDnNvjdiAU2squsi@0NbfVu3rvqveFAx4Rv36vlcOmkytPD2huOBCm6snZwZQGOX8A)
```
f(m,n) := block(
local(i),
makelist(binomial(m,i-n)*binomial(i,m), i, 1, m+n)
)$
for x in [[1, 1], [1, 2], [1, 3], [1, 4], [2, 2], [2, 4], [3, 3], [3, 4], [4, 4]] do (
print(x[1], " -> ", f(x[1], x[2]))
)$
```
[Answer]
# [Haskell](https://www.haskell.org/), 61 bytes
```
n#m=[n!(m+n-i)*i!n|i<-[1..n+m]]
_!0=1
n!k=n*(n-1)!(k-1)`div`k
```
[Try it online!](https://tio.run/##NYxBDoIwFET3nIKCi5ZSIglLPyfQlUtsgEQTPqVfYlE33r1WiJvJy2TeDL0zt2nynlILDTFuJSkUGTL64EE1ZVGQtFpHLdtDGREzQBknVQrGTcjuiq/OeKT5uThoOOaj@IuVzsdA@CMd2R4JbD@fWn5ZZ6oOznl5HGnnhvt77aRMYoA6TqTcunQUYjv3Xw "Haskell – Try It Online")
Based on [@Delfad0r's answer](https://codegolf.stackexchange.com/a/173986/9288), but using the formula in [my PARI/GP answer](https://codegolf.stackexchange.com/a/174003/9288).
] |
[Question]
[
# GPA Calculator
(GPA = Grade Point Average)
You are a stressed out college student during finals week. Instead of studying for your exams coming up, you decide it is best to determine what GPA you will have at the end of the semester. This way you have data to back up your decision of staying up all night to get that A in Calculus instead of a B to remain on the Dean's list!
Being a computer science major you want to find the coolest way to determine this GPA. Of course the coolest way is with the **shortest code!** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
# Details
* The college that you go to uses a basic GPA scaled along with credit hours.
* A letter grade of A is a 4.0, B is 3.0, C is 2.0, D is 1.0, and F is 0.0
* Your GPA is a weighted GPA, so an A in a 4 credit hour class counts 4 times as much as an A in a 1 credit hour class (See examples below for more weight explanantion)
* Credit Hours range from 1-4
* Your program will need to have a list of two command line inputs, Grade and Credit Hour. You can determine the best way to input these into your program through the command line. You do not need to worry about too many inputs, but ensure your code can handle a 19 credit hour semester.
+ i.e. Input: A 1 B 4 C 2…
* Your program must output the GPA, using 3 digits (i.e. X.XX)
* Your GPA needs to be rounded to two decimal places. Round in whichever way you like (floor, ceil, base, etc…)
## Input Examples(Choose whichever one works best for your design)
* A1B3C2F3B4
* A1 B3 C2 F3 B4
* A 1 B 3 C 2 F 3 B 4
* A,1,B,3,C,2,F,3,B,4
* A1,B3,C2,F3,B4
Or any of the above combinations where you use the format of listing all grades, then their credit hours:
* i.e. A B A A 3 4 1 1
## Examples
```
Input - A 3 B 4 A 1 A 1
Output - 3.56
Explanation: (4.0 * 3 + 3.0 * 4 + 4.0 * 1 + 4.0 * 1)/(3+4+1+1) = 3.555556 rounded off to 3.56
Input - A 4 F 2 C 3 D 4
Output - 2.00
Explanation: (4.0 * 4 + 0.0 * 2 + 2.0 * 3 + 1.0 * 4)/(4+2+3+4) = 2 rounded off to 2.00
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (12 with no rounding)
+6 bytes for the strict formatting (almost certainly possible in less but it's bed time)
```
Oạ69.Ḟ×S×ȷ2÷⁹S¤RLDż”.
```
A full program taking the grades and the respective credit hours which prints the calculated GPA (Note: the rounding method is to floor, as allowed in the OP).
**[Try it online!](https://tio.run/##ATwAw/9qZWxsef//T@G6oTY5LuG4nsOXU8OXyLcyw7figblTwqRSTOG4nkTFvOKAnS7///9BQkFB/zMsNCwxLDE "Jelly – Try It Online")**
With [no rounding for **12 bytes**](https://tio.run/##ASsA1P9qZWxsef//T@G6oTY5LuG4nsOXU8O34oG5U8Kk////QUJBQf8zLDQsMSwx "Jelly – Try It Online"):
```
Oạ69.Ḟ×S÷⁹S¤
```
### How?
```
Oạ69.Ḟ×S×ȷ2÷⁹S¤RLDż”. - Link: list of characters, grades; list of number, creditHours
- e.g. "AFBDC", [5, 2, 4, 1, 2]
O - cast to ordinals (vectorises) [65,70,66,68,67]
69. - literal 69.5
ạ - absolute difference (vectorises) [4.5,0.5,3.5,1.5,2.5]
Ḟ - floor (vectorises) [4,0,3,1,2]
× - multiply by creditHours (vectorises) [20,0,12,1,4]
S - sum 37
ȷ2 - literal 100
× - multiply 3700
¤ - nilad followed by link(s) as a nilad:
⁹ - chain's right argument, creditHours [5, 2, 4, 1, 2]
S - sum 14
÷ - division 264.2857142857143
R - range [1,2,3,...,264]
L - length 264
D - digits [2,6,4]
”. - literal '.'
ż - zip together [[2,'.'],6,4]
- implicit print (smashing) 2.64
```
[Answer]
# [Python 3](https://docs.python.org/3/), 66 bytes
*-5 bytes thanks to Rod.*
```
lambda g,c:'%.2f'%sum('FDCBA'.find(i)*j/sum(c)for i,j in zip(g,c))
```
[Try it online!](https://tio.run/##FYu7CoNAEAB/ZRvZvbAYUKtACh/4E2phlE1W9DzUFMnPn14zxTDjfsdntamXZ@vnfnmNPbx5eGAUJ4LR/l0I66oscoxF7UhqbtM92MHIuoHyBGrhr46uyxjvNrUHCTWYIwPWAWVAhR1DkzEkDClD1l3xCQ "Python 3 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), ~~57~~ 53 + 2 (`-an`) = ~~59~~ 55 bytes
```
$c+=$F[1];$\+=$F[1]*=!/F/&&69-ord}{printf'%.2f',$\/$c
```
[Try it online!](https://tio.run/##K0gtyjH9/18lWdtWxS3aMNZaJQbK0rJV1HfTV1Mzs9TNL0qprS4oyswrSVNX1TNKU9dRidFXSf7/31HBmMtJwYTLUcEQhP/lF5Rk5ucV/9f1NdUzMDT4r5uYBwA "Perl 5 – Try It Online")
*Edit: swapped the input around to save 4 bytes*
Input format: line separated, credits followed by grade:
```
grade credits
```
Example:
```
A 3
B 4
A 1
A 1
```
[Answer]
# [Python 2](https://docs.python.org/2/), 69 bytes
```
lambda x:'%.2f'%sum('FDCBA'.find(a)*b*1./sum(zip(*x)[1])for a,b in x)
```
[Try it online!](https://tio.run/##TY3NCoMwEITvPsVeZBMJFm1Pggd/8CXSHCI2NKBRNAXbl09NWkr3sh8zuzPL095nkztVXt0op36QsBcYp7nCeHtMBLu2qStMlTYDkTTpkyw9eeOlF5LslGeCqnkFyXrQBnbq7G2zG5TAOccKGZwFA471QZdAXsv@SLDv4cfuDsoDNb/nNrhCRL7J5/uq0FNEcMyyamOJF5gKi1L3Bg "Python 2 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes
```
N[(5-LetterNumber@#2/.-1->0).#/Tr@#,3]&
```
Takes a list of credit hours, and then a string of grades.
Does not work on TIO because TIO uses Mathematica kernel (which doesn't want to print arbitrary precision numbers)
[Answer]
# JavaScript (ES6), 72 bytes
Input format: `A1B3C2F3B4`
```
f=([c,d,...s],a=b=0)=>c?f(s,a+~'DCBA'.search(c,b-=d)*d):(a/b).toFixed(2)
```
### Test cases
```
f=([c,d,...s],a=b=0)=>c?f(s,a+~'DCBA'.search(c,b-=d)*d):(a/b).toFixed(2)
console.log(f('A3B4A1A1')) // 3.56
console.log(f('A4F2C3D4')) // 2.00
```
[Answer]
# [R](https://www.r-project.org/), 64 bytes
```
function(G,H)sprintf("%.2f",(5-match(G,LETTERS[-5]))%*%H/sum(H))
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8Ndx0OzuKAoM68kTUNJVc8oTUlHw1Q3N7EkOQMo5@MaEuIaFBytaxqrqamqpeqhX1yaq@Ghqfk/TSNZQ8lRSUfJCYidgdgNzNbUSdYw1DHWMQJiE6AyAA "R – Try It Online")
*thanks to user2390246 for fixing a bug!*
[Answer]
# Java, 211 bytes
Input format: A1B3C2F3B4
## Golfed
```
interface A{static void main(String[] a){int p=0,t=0,h=0,s=0;for(int c:a[0].toCharArray())if(p++%2==0)t=c=='A'?4:c=='B'?3:c=='C'?2:c=='D'?1:0;else{s+=(c-=48)*t;h+=c;}System.out.print(Math.ceil(100d*s/h)/100);}}
```
## Unglofed
```
static void main(String[] a) {
int p=0, //position in string
t=0, //temp var, used to store the grade between iterations
h=0, //credit sum
s=0; //sum of weighted grade
for(int c:a[0].toCharArray())
if(p++%2==0)
//map c to grade value, assign to temp variable t
t=c=='A'?4:c=='B'?3:c=='C'?2:c=='D'?1:0;
else{
//map c to credit value, add temp variable (grade from previous char) * value of this char (credit) to sum
s+=(c-=48)*t;
//also, add credit to credit sum
h+=c;
}
System.out.print(Math.ceil(100d*s/h)/100); //grade sum / credit hours sum, to 2dp*/
}
```
### Other version
My gut frealing told me that using a different input format (ABCF1324) would make the code shorter. It seems like it didn't. The version below is 234 bytes long.
### Golfed
```
interface A{static void main(String[] b){char[] a=b[0].toCharArray();int l=a.length/2,h=0,s=0,g,c,i;for(i=0;i<l;i++){g=a[i];g=g=='A'?4:g=='B'?3:g=='C'?2:g=='D'?1:0;c=a[i+l]-48;s+=g*c;h+=c;}System.out.print(Math.ceil(100d*s/h)/100);}}a
```
### Ungolfed
```
static void main(String[] b) {
char[] a=b[0].toCharArray(); //char array
int l=a.length/2, //first grade char
h=0, //credit sum
s=0, //sum of weighted grade
g,c, //avoid declaration in for loop. grade and credit being iterated
i; //avoid declaration in for loop
for(i=0;i<l;i++) {
g=a[i];//get char representing grade from array
g=g=='A'?4:g=='B'?3:g=='C'?2:g=='D'?1:0; //convert to grade
c=a[i+l]-48;//get char representing grade from array and convert to credit (48 is value of '0')
s+=g*c; //add weighted grade to sum
h+=c; //add credit to sum
}
System.out.print(Math.ceil(100d*s/h)/100); //grade sum / credit hours sum, to 2dp*/
}
```
[Answer]
# [Java 1.8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html), ~~287~~ 249 Bytes
-38 bytes thanks to Bumptious
# Golfed
```
static String N(String[]j){float g=0;float b=0;for(int i=0;i<j.length;i+=2){g=((m(j[i])*Float.parseFloat(j[i+1])+g));b+=Double.parseDouble(j[i+1]);}return String.format("%.2f",g/b);}static float m(String l){return l.equals("F")?0:('E'-l.charAt(0));}
```
## Ungolfed
```
interface C {
static void main(String[] z) throws Exception {
String[] j = {"A", "4", "B", "3", "C", "2", "D", "1", "F", "1"};
System.out.println(N(j));
}
static String N(String[] j) {
float g = 0;
float b = 0;
for (int i = 0; i < j.length; i += 2) {
g = ((m(j[i]) * Float.parseFloat(j[i + 1]) + g));
b += Double.parseDouble(j[i + 1]);
}
return String.format("%.2f", g / b);
}
static float m(String l) {
return l.equals("F") ? 0 : ('E' - l.charAt(0));
}
}
```
[Answer]
# [Julia 0.6](http://julialang.org/), 46 43 42 bytes
```
g%h=round(max.(69-Int.(g),0)⋅h/sum(h),2)
```
[Try it online!](https://tio.run/##RcrNCoJAFEDhvU9xEcV74Wb5g1DQwoqiXfthFoKlho5hCvMCrXrLXmSaIujAtzvXqW2KzJjKr9dDP6kSu0KHmC1nRzWGWBEv6PV81PP71GFNHJO59ANoaBQIQBHkAQcbK/@SLBJOOeJIEjvw73fura21@5wpx2xvSdKx621o1NgqdD0Nh1O@Ag@1iKSvRSzJJeesSvMG "Julia 0.6 – Try It Online")
**Explanation**
Input format: `g`: vector of grades; `h`: vector of credit hours
* `g%h`: Redefine `%` operator.
* `69-Int.(g)`: Convert `'F','D','C','B','A'` to `-1,1,2,3,4` respectively for each element of g.
* `max.( ,0)`: Clamp range to `0:4` (element-wise).
* The rest is simple vector math.
* Rounding costs 9 bytes.
] |
[Question]
[
Manually summing a Cubically cube's faces is tedious and time-consuming, sorta like writing code in Cubically itself.
In [Most efficient cubifier](https://codegolf.stackexchange.com/q/133793/61563), I asked you to translate ASCII to Cubically source. One of the answers there uses a cube initialization sequence and then modifies the resulting cube based on the sums of the pre-initialized cube. This method has been used in many Cubically-related programs since. When testing a new initialization sequence, one has to add up all the values on all the faces, which usually takes two or three minutes.
Your task is to automate this process for us!
You will take two inputs, an integer `n` and a string `c`. These may be read from command line arguments, function arguments, standard input, a file, or any combination of those. `c` will be a [Cubically memory cube](https://github.com/aaronryank/cubically/wiki/Memory) of size `n` as pretty-printed by the interpreter.
The Cubically interpreter dumps its cube to STDERR upon program termination, formatted nicely for simple viewing. Run an empty program in the [Cubically interpreter](//tio.run/#cubically) and open the debug section to see the cube dump of an initialized cube. Add an argument `4` to see a 4x4x4, or `5` to see a 5x5x5, etc.
If `n` is 3, `c` will follow this format (the integers will be variable):
```
000
000
000
111222333444
111222333444
111222333444
555
555
555
```
Spaces, newlines, and all. If `n` is 4, `c` will look like this (also with variable integers):
```
0000
0000
0000
0000
1111222233334444
1111222233334444
1111222233334444
1111222233334444
5555
5555
5555
5555
```
Et cetera.
Your program will output six integers. The first integer will be the sum of all the numbers on the top face.
```
000
000 top face
000
111222333444 left, front, right, and back faces, respectively
111222333444
111222333444
555
555 bottom face
555
```
The second integer will be the sum of the left face, the third the front, the fourth the right, the fifth the back and the sixth the bottom.
So if `n` was 3 and `c` was this:
```
242
202
242
000131555313
010121535343
000131555313
424
454
424
```
Your program would output `20 1 14 43 24 33`.
Additional rules:
* The output integers must be delimited by non-integer characters. You may also choose to return an array.
* You may assume that the input is correct - `n` is an integer and `c` is a cube from [Cubically's debugging output](https://tio.run/##Sy5NykxOzMmp/A8CJgA). So if `n` was `3.0` and `c` was `foo bar`, your program could break and still be valid.
* Your program only needs to work for `n > 1` and `n < 1260`. It *may* (attempt to) handle larger or smaller cube sizes, but it is not necessary.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins! If you need help, feel free to ask in the [Cubically chatroom](https://chat.stackexchange.com/rooms/62883/cubically).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ ~~14~~ 13 bytes
3 bytes thanks to Erik the Outgolfer.
```
ḟ⁶ỴV€€sS€ẎsS€
```
[Try it online!](https://tio.run/##y0rNyan8///hjvmPGrc93L0l7FHTGiAqDgYSD3f1gen///8rKCgYmRhxgSgDCAXkGRgYGBobmpqaGhsacxkYGhgaGZoamxqbGKPKAFWbGJmAKVMTKO@/MQA "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 155 150 147 123 121 120 bytes
Could probably be golfed quite a bit
**Edit:** -5 bytes by using a better method for removing the whitespaces
**Edit:** -3 bytes thanks to [@Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun)
**Edit:** -24 bytes by not removing whitespaces
**Edit:** -2 bytes by exploiting precedence
```
lambda n,a:[sum(sum(map(int,b[j*n:][:n]))for b in a.split("\n")[i*n:][:n])for i in range(3)for j in range(~i%2,i%2*2+2)]
```
[Try it online!](https://tio.run/##VY3NCsMgEITveQoRCppK0VUvgT6JycHQP4MxkqSHXvrqVtPS0sMwzOzHTnystylA8sc2eTv2J4sCs41Z7iMpGm0kLqysN0Mdms40oaP0Ms2oRy4ge1iidyvBbcDUuC9RAFeA2YbrmcitGH7F0@2AZdWwB9qlOOcJ4olkGGOEECioivG35cQ5F1JoraWQFRdcgNBSSyX/L5lWoDbT6pPyS0rTCw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
¹|ðм€Sôεø¹ô€OO}˜
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0M6awxsu7HnUtCb48JZzWw/vOLTz8BYgz9@/9vSc//@NuRQUFIxMjMCUgRGMZ2BgYGhsaGpqamxozGVgaGBoZGhqbGpsYowqA1RtYmQCpkxNoDwA "05AB1E – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
3 `ṁ`s and 2 `m`s
```
mṁṁiṁoC⁰TC⁰mf±¶
```
[Try it online!](https://tio.run/##yygtzv7/P/fhzkYgygTifOdHjRtCQERu2qGNh7b9///f@L@CgoKRiREXiDKAUECegYGBobGhqampsaExl4GhgaGRoamxqbGJMaoMULWJkQmYMjWB8gA "Husk – Try It Online")
### Explanation
```
Takes input as two arguments, the first being n, the second, the cube
¶ Split second argument into a list of lines
m For each line
f± keep only the digits (remove spaces)
C⁰ Cut into lists of length n
ṁ Map then concatenate
T transpose
oC⁰ then cut into lists of length n
mṁṁi Takes list of lists of strings (or, in Husk, a list of lists of lists of chars) and returns the sum of the digits in each list
m Map function over list of lists
ṁ map then sum
ṁ map then sum
i convert character to integer
```
[Answer]
# Octave, ~~64~~ ~~59~~ 54 bytes
```
@(c,n)sum(im2col(c'-48,[n n],'distinct'))([2 5:8 10])
```
[Try it online!](https://tio.run/##ZY7BCgIhFEX3foU7FQx8Ph8MidB/iIvBGhAaZ6H1@1ZT0aLduedy4W65z/fLGOwks66q3VZZVpu3q8zi4CYdK69Ji3NpvdTchVIyWk7HiYNJaixhrs2zHCITnHPrrHiD@cJujDGAQEQI@IpgwAIhocP/9rly1n2A3M8kz2pAz5b96ngA "Octave – Try It Online")
Previous answer:
```
@(c,n)sparse(kron((1:4)+[0;4;8],!!e(n)),1,c-48)([2 5:8 10])
```
[Try it online!](https://tio.run/##ZY7BCsIwEETv@Yr01AQj7GZ3oTQU/I@QQwntRUilLf5@1Kp48PbmDQOz5H28T7VeTHbFbrdx3SZzXZdiDPZsTxEChy65pplMsdahy2furIleS99phGTrPIxlCyoPUbVaa8@@fQN84TAAgIQiQkiviIAehYSY/tvnij1/QPhnUlBloKDm43B9AA "Octave – Try It Online")
Returns an array as output.
[Answer]
# [Perl 5](https://www.perl.org/), 66 + 1 (-n) = 67 bytes
```
$j=$k<6?$k++/3:5;s/\d{3}/';$r[$j++]+='.$&=~s|.|+$&|gr/gee}{say"@r"
```
[Try it online!](https://tio.run/##VYtLDoIwFEXnrKIhLzBooJ/X50AkugFXoA5MJAQwQFonBnDp1vqZODo5ueeOlb2S99CW0G1WW@g4F7imwonjZcJFpAXYA7Scn3iZ5pCUDzfnM4dkrq2oq2qZ3Pke72zsPWNMGx29Ib8IJqVUqIgIFUZSSaUVIaHB/yXURpsPyPzsOYy3Zuidz/aUh6vP@hc "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~137~~ 127 bytes
-10 bytes thanks to @Halvard Hummel
```
lambda x,n:[sum(sum(map(int,x.split('\n')[b+j][a:a+n]))for j in range(n))for a,b in[[n,0],[0,n],[n,n],[2*n,n],[3*n,n],[n,2*n]]]
```
[Try it online!](https://tio.run/##VY/NCoMwEITvPkXwYlJDye9F8EliDpHWVtE1GAv26dP4c@lh52Nml4H13/U9g4hd3cTRTe3DoY1CZcJnwvtMzuMeVrrdgx/7FRcNFMS05WCNq1wJlpBuXtCAekCLg9cTw5k42qbMGKDMUsMoJIVDxe2kvAg0JdbaGOo8zxFCQolsBzuRHGOMS661llxmjDMuuJZaKvm/SddKqANaXS5VZn5JL6AOBypJ/AE "Python 2 – Try It Online")
[Answer]
# Haskell, 128 bytes
```
s n c=filter(>=0)$map(\[x,y]->sum$map(\[v,w]->fromEnum((lines c)!!(x*n+v)!!(y*n+w))-48)$n%n)$3%4
n%m=sequence[[0..n-1],[0..m-1]]
```
Accepts a string with line breaks.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 236 bytes
```
param($n,$z)
function f($y){$y-replace' '-split'(.)'-ne''-join'+'|iex}
$a=$z-split"`n"
f $a[0..($n-1)]
$a[$n..(2*$n-1)]|%{$x="($('.'*$n))";$1,$2,$3,$4=$_-split$x-ne'';$h+=$1;$i+=$2;$j+=$3;$k+=$4}
$h,$i,$j,$k|%{f $_}
f $a[(2*$n)..(3*$n)]
```
[Try it online!](https://tio.run/##nY7NboMwEITvPAVCU63d2Cj89GTxJFGUosgIE2IQSVXy9@zuJtxz6HeZ9exqxuPwa6dTa/s@hLGe6qOAV7jKqPnx@7MbfNwIXOQNFz3Zsa/3lmLSp7F3ZxKpJO0tke4G52lFd2fnR4S6wnU5Sb59EjUx6s06TTlZZ3LL@w08P/PPxbh/3DBXiYCglNiTMjHIFHKFQqGssFvCML/KDNpVhczAseQGHUthcGApubxVcAqdwoFzuXr3WD7wqpNcWzx1G0IoA8XMmoneDBmTMwVTMv8xnmFfzJuB/gA "PowerShell – Try It Online")
Ooof, this is long. But, splitting and slicing of strings isn't one of PowerShell's strong suits, so I guess it's somewhat expected. Also -- So. Many. Dollars.
Takes in parameters `$n` and `$z` as the size and cube net, respectively. Then constructs a function that is used throughout. Here, we're removing spaces, splitting on each individual digit, removing the empty characters in between, joining all the characters together with a `+`, and then executing the resulting statement to get a number. For example, this turns `"123"` into `1+2+3` which when executed is `6`.
The next line `split`s the input cube net on newlines, storing the result into array `$a`. We then perform the function on the first `$n` lines and output the top face of the cube.
For the next set, we need to splice the strings based on the cube size. So, we loop through each line, constructing `$x` as the appropriate regex pattern (e.g., for size `$n=3` this will be `"(...)"`), split the string based on that pattern, again removing empty elements, and store those into four variables representing the four faces. Those are then string concatenated onto `h` through `k`.
The next line then ships `h` through `k` through the function to output the sides (left, front, right, back) of the cube.
Finally, we run the last `$n` lines through the function to output the bottom face of the cube.
All of the numbers are left on the pipeline, and output is implicit.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~30~~ 27 bytes
```
{+/⍎¨6(⍺*2)⍴⍉⊃,⌿3⍺⍴⍵⊂⍨⍵∊⎕D}
```
Shaved off 3 bytes thanks to [@Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)
`⍺` is n
`⍵` is c
## Explanation
```
⍵⊂⍨⍵∊⎕D c partitioned by ⎕D (digits 0..9)
3⍺⍴ reshape into 3 by n matrix
,⌿ concatenate on first axis (results in n vectors)
⍉⊃ ravel transpose mix (results in a simple string with all digits in side order)
6(⍺*2)⍴ reshape into 6 by n squared matrix (one row per side)
+/⍎¨ sum rows execute each (execute will turn characters into numbers)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZceTlACsgNdQ5WMARywYLJQFJdQUHByMRIXScvRwfMNkBiw8QNDAwMjQ1NTU2NDY2hIoYGhkaGpsamxibGuNQATTAxMkGwTU1QxP9Xa@s/6u07tMJM41HvLi0jzUe9Wx71dj7qatZ51LPfGCgGFtj6qKvpUe8KEKOjC@gDl9r//43J1ZoMAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Cubically](//git.io/Cubically), 19 bytes
```
r%0@%1@%2@%3@%4@%5@
```
Takes the cube from STDIN and the size as a command-line argument to the interpreter. Outputs the sum of the top face, a null byte, the left face, a null byte, ... the bottom face, and a null byte.
[Try it online!](https://tio.run/##HYwxDoAwDAP3vqJLdttJ9nwFmJCYkBh4fWmZTieffDz7eWzX9Y5xG8pYpjIvi7KsMXrv8mwTABbEbCkwXBEOtiQol4fHlADTpbly1bNYyPwvgvgA) ...which apparently displays null bytes as some sort of whitespace on my browser.
* [Try it online! (4x4x4)](https://tio.run/##NcwxDkJBCATQfk9hQw8zQ89V9FcmvzKx8PS4olKQx0A4nrf7cT3PV/fDvCzKUMYylWV1X3ZFQmsg50AZPkgPLncSkCMQ21gKIB0ZolyZ69MU8Q1JLe1N7ln0jP8z7pPBPJkEyR@I1hs)
* [Try it online! (5x5x5)](https://tio.run/##bU4xEsMwDNr9ii7eJQS7vtJm6l2m3HXo61058ZZqQggB2@f13p77/h3j6JbdsyN7ZGd25RiPOQ6B7YJGiwvS5XZji/NoZmEBggY4fK5o86GcDPK60iiqWYlE9zNjXiL4X0kGqbJThZlKohUfXgYLClpNzgo3NgKBoR8)
This language wasn't made for this challenge, but the challenge was made for the language.... is it still cheating? ;)
] |
[Question]
[
In the [Thai calendar](https://en.wikipedia.org/wiki/Thai_calendar) the year 2017 corresponds to 2560. The Thai calendar is always 543 years ahead of the Gregorian calendar.
Observant coders will note that 2560 is equal to \$2^9 \times 5\$, in other words it has 10 prime factors. This will not happen again for another 896 years! We call a year **tenacious** if it has exactly ten prime factors.
Write a program which outputs a truthy value if the current year using the Thai calendar, based on the system clock, is tenacious, and a falsey value otherwise.
Test cases:
* If the program is run during 2017, `true`
* If the program is run during any of the years 2018 to 2912, `false`
* If the program is run during 2913, `true` (\$2913+543 = 2^7 \times 3^3\$)
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, 35 bytes
```
factor $[`date +%Y`+543]|awk NF==11
```
Output is either a non-empty string (truthy) or an empty string (falsy).
[Try it online!](https://tio.run/nexus/bash#S03OyFfIyy//n5aYXJJfpKASnZCSWJKqoK0amaBtamIcW5NYnq3g52Zra2j4Pw2oACybmaegnpdaUaJQmZpYpK5gZGBipGtgCEQKRpaGxhCmtUJKPhdnKsh8FfWYPHWVapBWVVVdrVouTjTbdFMUlFRALCWsFnOl5Oel/gcA "Bash – TIO Nexus")
### Alternate version: 37 bytes.
```
date -d 543year +%Y|factor|awk NF==11
```
Not as golfy, but I like this one.
[Try it online!](https://tio.run/nexus/bash#@5@SWJKqoJuiYGpiXJmaWKSgrRpZk5aYXJJfVJNYnq3g52Zra2j4/z8A "Bash – TIO Nexus")
### How it works
The arithmetic expansion
```
$[`date +%Y`+543]
```
executes `date +%Y` to get the current (full) year and adds **543** to the year.
Factor takes the sum as an argument and prints it prime factorization: first the number to be factored, then a list of individual prime factors.
Finally, awk filters the input, printing only lines with exactly 11 fields (the number plus 10 prime factors).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
žg543+ÒgTQ
```
[Try it online!](https://tio.run/nexus/05ab1e#@390X7qpibH24UnpIYH//wMA "05AB1E – TIO Nexus")
or as a [Test suite](https://tio.run/nexus/05ab1e#qymr/G9qYqx9eFJ6SOD/SqXD@60UDu9X0vlvZGBoxgUkzEGEBZeRpaERiDAGESYA)
**Explanation**
```
Òg # the number of primefactors with duplicates of
žg # the current year
543+ # plus 543
TQ # equals 10
```
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 13 bytes
```
et0=543+mf,A=
```
[Try it online!](https://tio.run/nexus/cjam#@59aYmBramKsnZum42j7/z8A "CJam – TIO Nexus")
### Explanation
```
et0= e# Get current year.
543+ e# Add 543.
mf e# Get prime factors with multiplicity.
, e# Get length.
A= e# Equals 10?
```
[Answer]
# Mathematica, ~~37~~ 31 bytes
*5 bytes saved due to [lanlock4](/users/66104).*
```
PrimeOmega[#&@@Date[]+543]==10&
```
Anonymous function. Takes no input and returns `True` or `False` as output.
[Answer]
# Pyth, 11 bytes
```
qlP+543.d3T
```
[Online interpreter available here.](http://pyth.herokuapp.com/?code=qlP%2B543.d3T&debug=0)
## Explanation
```
.d3 get current year
+543 add 543
P get prime factors of result
l count number of prime factors
q T check if equal to 10 (result is implicitly printed)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 14 13 bytes
```
543+Ki¹k l ¥A
```
Saved 4 bytes thanks to ETHproductions.
Saved 1 byte thanks to obarakon.
[Try it online!](https://tio.run/nexus/japt#@29qYqztnXloZ7ZCjsKhpY7//wMA "Japt – TIO Nexus")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~92~~ 89 bytes
-3 bytes thanks to Jonathan Allan
```
import time
y=time.gmtime()[0]+543
c=i=1
exec"i+=1\nwhile 1>y%i:y/=i;c-=1\n"*y
print-9==c
```
[Try it online!](https://tio.run/nexus/python2#@5@ZW5BfVKJQkpmbylVpC6L00nNBlIZmtEGstqmJMVeyrYF1pq0hV2pFarJSpratYUxeeUZmTqqCoV2laqZVpb5tpnUyWFhJq5KroCgzr0TB0MDWNvn/fwA "Python 2 – TIO Nexus")
Iterate up to the year, extracting (and couting) the prime factors.
The exec line is equivalent to :
```
for i in range(2,y):
while not(y%i):
y=y/i
c=c-1
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 31 bytes
```
nnz(factor(clock()(1)+543))==10
```
[Try it online!](https://tio.run/nexus/octave#@5@XV6WRlphckl@kkZyTn5ytoalhqKltamKsqWlra2jw/z8A "Octave – TIO Nexus")
Two tricks used here:
* `clock()(1)` to index directly into the output of `clock` (`clock(1)` doesn't work)
* `nnz` instead of `numel`, as all entries are guaranteed to be nonzero.
---
### Alternate version, same byte count
```
nnz(factor(max(clock)+543))==10
```
This version can only be used for years exceeding `30`, but ~~obviously~~ disregarding time travel this includes all years in which the program can be executed. It works in Matlab as well.
[Answer]
# PHP, 111 68 66
```
$a=date(Y)+543;for($i=2;$i<$a;)$b+=$a%$i?!++$i:!!$a/=$i;echo$b==9;
```
directly counts the number of prime factors.
```
$a=date(Y)+543; // current year
for($i=2;$i<$a;) // while $i lower than the year
$b+=$a%$i?!++$i:!!$a/=$i; // if $i divides $a: $a/=$i and ++$b | if not: ++$i
echo$b==9; // output if it has 10 prime factors
```
---
## Old idea: 111 90
```
for($i=1;++$i<1e3;)for($j=1;++$j<1e3;)${$i*$j}=($$i?:1)+($$j?:1);echo${date('Y')+543}==10;
```
This doesn't use a prime factortoring builtin but basically a *counting prime sieve* to get the number of prime factors of a number < 10000. This maps to the 4 digit year that PHP provides using `date('Y')`:
```
for($i=1;++$i<1e3;) // for each number smaller sqrt(1e4)
for($j=1;++$j<1e3;) // do sqrt(1e4) times
${$i*$j}=($$i?:1)+($$j?:1); // n_factors[i*j] = n_factors[i] + n_factors[j]
echo${date('Y')+543}==10; // output 1 if the current year has 10 prime factors or nothing if it doesn't
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
1&Z'543+Yfn10=
```
[Try it online!](https://tio.run/nexus/matl#@2@oFqVuamKsHZmWZ2hg@/8/AA "MATL – TIO Nexus")
```
1&Z' % Current year
543+ % Add 543
Yf % Prime factor decomposition
n % Number of elements
10= % Equal to 10? Implicitly display
```
[Answer]
## Batch, 123 bytes
```
@set/ay=%date:~-4%+543,n=d=2
:l
@set/ar=y%%d,d+=1
@if %r%==0 set/ay/=d-=1,n+=1
@if %y% gtr 1 goto l
@if %n%==12 echo 1
```
You can fake out the script by manually overriding the `date` variable before running it.
[Answer]
# [J](http://jsoftware.com/), 18 bytes
Program body:
```
10=#q:543+{.6!:0''
```
[Try it online!](https://tio.run/nexus/j#@///v6GBrXKhlamJsXa1npmilYG6OgA "J – TIO Nexus")
`10=` is ten equal to
`#` the tally of
`q:` the prime factors of
`543+` this number added to
`{.` the head (first item, i.e. the year) of
`6!:0''` the date (as Y M D h m s)
[Answer]
## JavaScript (ES6), ~~79~~ 75 bytes
```
f=(y=+Date().slice(11,15)+543,d=2,n=10)=>y>1?y%d?f(y,d+1,n):f(y/d,d,n-1):!n
```
Port of my Batch answer. Pass in the **Thai** calendar year if you want to perform a specific test. Edit: Saved 4 bytes thanks to @dandavis.
] |
[Question]
[
This is the robbers' thread. For the cops' thread, go [here](https://codegolf.stackexchange.com/questions/64520/find-the-nested-source-codes-cops).
# Introduction
For this Cops/Robbers challenge, the cops will write output-producing programs and interweave them together. It is the robber's job to pick apart the cops' programs to produce the desired outputs.
# Robber rules
Robbers will try to find the different programs that people post in submissions to the cops' thread (linked above). If a robber solves a cop's code, they must post the separated programs and match them with their outputs in an answer here and post that they have cracked the code on the cop's answer.
# Scoring
There are two components that are added together when scoring a cracked submission.
* 2 to the power of the number of different programs used in the cop's answer
* Round the number of bytes in the interweaving **down** to the nearest power of 2.
For example, if a robber cracks `TIliGoEnR` as being `TIGER` and `lion`, then the robber receives 2^2+8=12 points.
The winner of the robbers' challenge will be the person with the most points after a sufficient period of time for people to participate.
---
(Who wants to help with a snippet?)
[Answer]
# [Vitsy](https://codegolf.stackexchange.com/a/64590), 12 points
```
'o'2\I/NO
```
[Try it online!](http://vitsy.tryitonline.net/#code=J28nMlxJL05P&input=)
```
a5F\aZ
```
[Try it online!](http://vitsy.tryitonline.net/#code=YTVGXGFa&input=)
The `NaN` in `NaNo` was a dead giveaway.
The obvious way to push `NaN` would be to divide **0** by itself, `2\I` pushes the input length (**0**) twice, `/` performs division, and `N` prints a float.
We're left with printing `o`, and `'o'` is a string literal that `O` prints.
Whatever characters were left had to belong to the other program. In fact, `a` pushes a linefeed, `5F` the factorial of **5** (**120**), `\a` turns that into 120 linefeeds, and `Z` prints the entire stack.
[Answer]
# [BitShift](https://esolangs.org/wiki/BitShift), 2^2 + 64=68 points
[cops thread](https://codegolf.stackexchange.com/a/64556/46249)
```
0101100110110101001001010110111011101110111011101101010
```
prints `! ?`
```
1011101110111011101110110101000000000110010101101101010
```
prints `? !`
### Code
```
0101100110110101001001010110111011101110111011101101010 # '! ?'
01011001101101010 # '! '
0101 # XOR 0 with 128
# Making current value 128 (1000 0000)
10 # Bitshift 1 to left making 10000000 -> 01000000
01 # Bitshift 1 to left making 01000000 -> 00100000
101 # XOR 00100000 with 1 making it 00100001
101010 # print 00100000 which is binary for !
010010101 #
010 # XOR 00100001 with 1 making it 00100000
010101 # print 00100000 which is binary for <space>
10111011101110111011101101010 # '?'
101 # XOR 00100000 with 1
1 # Bitshift 1 to left making 00100001 -> 01000010
# This gets repeated till 01000010 becomes 0111111
101010 # print 0111111 which is binary for ?
```
I will add some description later(split the code in the parts that print individual parts)
[Answer]
# [PHP](https://codegolf.stackexchange.com/a/64638), 68 points
```
$c=tR;$h=s;$c=$h.$c._.$h.plit;echo$c($h);
```
Output: `Array`
```
echo quotemeta('^/]'.co.'[$');
```
Output: `\^/\]co\[\$`
---
I like this submission, because it relies on a few lesser know features - one might say *misfeatures* - of PHP. PHP allows function references to be assigned to variables, so for example:
```
$f = function($a, $b) { return pow($a, $b); };
echo $f(2, 4);
```
would do exactly what you expect. As would:
```
$f = pow;
echo $f(2, 4);
```
...except it's not doing what you think. `$f = pow` does not assign a function reference to `$f` (that would make too much sense, right?), but rather the *string* `'pow'`. The implication is that any string may be used as a function call, if it represents the name of a defined function. Bad code waiting to happen. I don't even know why you'd *want* to allow this.
Another misfeature of PHP, is that function names and keywords are case-insensitive. I wish I were joking. So `echo pow(2, 4)`, `ECHO POW(2, 4)`, and `EcHo PoW(2,4)` are all functionally equivalent.
The last misfeature on showcase is that whenever an array is typed as a string, such as for printing, the result is always the amazingly helpful string `Array`. Take a moment to reflect on the fact that someone actually did this deliberately.
So in the first program, @insertusernamehere builds up the string `stR_split`, this string is used as a function reference (which, for reasons above, actually works), and the result, an array, is output.
[Answer]
# [Ruby](https://codegolf.stackexchange.com/a/64699/2537), 68 points
First:
```
p %w(b n n s)*?a%?}
```
Second:
```
w,=?(.ord,40,?);"jivivi{2".bytes{|b|putc b-w}
```
It followed pretty naturally from working out the end, with `putc`.
[Answer]
# JavaScript, 68 points
[Cops thread](https://codegolf.stackexchange.com/a/64598/45393)
### First program
Output: `ffttff`
```
(![]+[])[+[]]+(![]+[])[+[]]+(!![]+[])[+[]]+(!![]+[])[+[]]+(![]+[])[+[]]+(![]+[])[+[]]
```
### Second program
Output: `1010`
```
+!![]+[+[]]+(+!![])+(+[])
```
### Interweaving
```
+ !! [] + [ +[]] + (+ !![]) + (+[])
(![]+ [])[ +[]]+(![]+[]) [+[]]+(!![]+[])[ +[]] +(!![]+[]) [+[]]+ (![]+ [])[+[]]+(![]+[]) [+[]]
```
[Answer]
# Java, 132 points
[Cops thread](https://codegolf.stackexchange.com/a/64568/34388)
First program:
```
interface c{static void main(String[]g){System.out.println("Hell"\u002bg.length);}}
```
Second program:
```
class i{public static void main(String[]n){System.out.print("Bye!\n");}}
```
The first program outputs `Hell0` and the second program outputs `Bye!`
[Answer]
# [Javascript](https://codegolf.stackexchange.com/a/64622/41257), 132 points
### Program 1
```
var x;{;alert((f=>(f.reverse(f+~~f,Math.pow(2,Math.E))))(new Array(99).fill(0).map((x,i,f)=>i/3)).join("").replace(/../g,""))}
```
### Program 2
```
try{"function";Object.keys(f)}catch(e){f=s=>!s?f(1):"";alert(f(f(f(0/0) +f(7/5)))+f(f)+`${f}`.split``.map(e=>e.charCodeAt()*23))}
```
Whew. This was terrible.
After a lot of debugging I found out that after calling (parts of) the 2nd program, it wouldn't run again. This is because the global variable `f` was still assigned. Because of `f` being assigned, the try/catch didn't fail on `Object.keys(f)`. I don't know if this is a sneaky trick or unintentional but it caused me a headache.
Also, I believe the output of the first program is platform specific.
`/../g` removes all characters on my machine, because of the regex `.` which means any character. Escaping it with `/\../g` works however, I hope someone can shed more light onto this. Also, my output is prone to rounding errors, perhaps some global javascript variable can change this?
**Output**
```
32666666666666643233333333333336323166666666666668313333333333333231306666666666666830333333333333323029666666666666682933333333333332292866666666666668283333333333333228276666666666666827333333333333322726666666666666682633333333333332262566666666666668253333333333333225246666666666666824333333333333322423666666666666682333333333333332232266666666666668223333333333333222216666666666666821333333333333322120666666666666682033333333333332201966666666666668193333333333333219186666666666666818333333333333321817666666666666681733333333333332171666666666666668163333333333333216156666666666666615333333333333341514666666666666661433333333333334141366666666666666133333333333333413126666666666666612333333333333341211666666666666661133333333333334111066666666666666103333333333333410966666666666666933333333333334986666666666666683333333333333487666666666666677333333333333337666666666666667633333333333333656666666666666753333333333333354666666666666674333333333333334366666666666666533333333333333353266666666666666523333333333333352166666666666666713333333333333331066666666666666603333333333333330
```
This was tested on chrome 46 (my only browser), Windows 7.
I hope this is still a valid submission, despite the different output
[Answer]
# [JavaScript (ES6)](https://codegolf.stackexchange.com/a/65088/42545), 68 points
### Program 1
```
alert((c=>c.replace(/[a-z]/gi,a=>String.fromCharCode(("Z">=a?90:122)>=(a=a.charCodeAt(0)+13)?a:a-26)))("fvzcyr"))
```
### Program 2
```
alert((b=>b.replace(/[a-zA-Z]/g,s=>String.fromCharCode(s.charCodeAt(0)+(s.toLowerCase()<'n'?13:-13))))("gbnfg"))
```
### Interweaved programs
```
alaelretrt((((cb=>c=>b.replace(/.replace[a-(/[azA-Z]-z]/gi/g,a,s=>String=>String.fromCharCode(s.fromCharCode(("Z">=a.charCodeAt(0)?90:122)>=(a=a.charCodeAt(0+(s.toLowerCase())+13)?a<'n'?13:-13:a-26)))))))((""gfvbznfcyrg""))))
al e r t ( ( c =>c .replace (/[a -z]/gi ,a =>String .fromCharCode(("Z">=a ?90:122)>=(a=a.charCodeAt(0 )+13)?a :a-26))) ( " fv z cyr " ))
a l e rt ( ( b =>b.replace(/ [a- zA-Z] /g ,s =>String.fromCharCode(s .charCodeAt(0) +(s.toLowerCase() <'n'?13:-13 )))) ( "g b nf g " ))
```
This would've been a lot harder, had the cop torn apart the keywords. ;)
[Answer]
# [PHP](https://codegolf.stackexchange.com/a/64696/39022), 24 points
Program 1
```
print!0;
```
Program 2
```
print!$x;
```
Program 3
```
print print'';
```
Tested with <http://sandbox.onlinephpfunctions.com/>.
[Answer]
# [Python 2](https://codegolf.stackexchange.com/questions/64520/find-the-interweaved-source-codes-cops/65231#65231), 320 points
```
print "This"
print "hello"
print "well"
print "no"
print "alas"
print "but"
print "oh"
print "done"
```
] |
[Question]
[
Inspired by the title of [the *Toggle some bits and get a square* challenge](https://codegolf.stackexchange.com/questions/170281/toggle-some-bits-and-get-a-square).
In that challenge you output how many bits should be toggled, in order for the base-10 representation of the binary to become a square number.
## Challenge:
In this challenge, you'll be given a bit-matrix \$M\$ and an integer \$n\$ as inputs.
Output the edge-size of the largest square you can make by toggling at most \$n\$ bits in the grid. A square is defined as having a border of `1`s, with an irrelevant inner body.
E.g., these all contain valid squares of size 4x4, highlighted below with `X`:
(for the third example, more than one 4x4 square is possible)
```
1111 1111 11111111 010110
1001 1011 11111111 001111
1001 1101 11111111 101011
1111 1111 11111111 111001
011111
XXXX XXXX XXXX1111 010110
X00X X01X X11X1111 00XXXX
X00X X10X X11X1111 10X01X
XXXX XXXX XXXX1111 11X00X
01XXXX
```
**Example:**
So let's say the inputs are \$n=4\$ and \$M=\$
```
010110
001011
101010
111001
011110
```
You could toggle these three bits (highlighted as `T`):
```
010110
001T11
10101T
111001
01111T
```
to get the 4x4 square of the fourth example above. So the output is `4`.
## Challenge rules:
* You can take the input-grid in any reasonable format. Can be a matrix of integers; matrix of booleans; list of strings; list of integers for which their binary representation (with leading 0s) is the binary grid; etc.
* You toggle at most \$n\$ bits, not exactly \$n\$ bits.
* The input-matrix \$M\$ is not guaranteed to be a square, but it is guaranteed to be a (non-empty) rectangle.
* The input-integer \$n\$ is guaranteed to be non-negative (\$n\geq0\$).
## General Rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (e.g. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test Cases:
| Inputs: | Output: |
| --- | --- |
| \$n\$=`4` and \$M\$=
```
010110001011101010111001011110
```
| 4 |
| \$n\$=`8` and \$M\$=
```
0010101010110111001001001
```
| 4 |
| \$n\$=`0` and \$M\$=
```
000000000000
```
| 0 |
| \$n\$=`0` and \$M\$=
```
111111
```
| 2 |
| \$n\$=`1` and \$M\$=
```
101010101
```
| 1 |
| \$n\$=`1000` and \$M\$=
```
100010010010100101100011110110110101010010101001101011
```
| 6 |
[Answer]
# JavaScript (ES6), 139 bytes
Expects `(n)(matrix)`.
```
n=>m=>m.map(W=h=(X,w,k,Y)=>m.map((r,y)=>r.map((v,x)=>k?h(x,w,q=t=0,y):(x-X)%w&&(y-Y)%w||x<X|x>X+w|y<Y|y>Y+w||++q<w*4|(t+=!v)>n?0:W=w+1)))|W
```
[Try it online!](https://tio.run/##VU9Nb4IwGL73V3Qmc@3Apk08LM7iaTvu4kGIemAIyoSiBQWy7rezfmiWJW3f530@3rZf8TWuE5mfmomodumQ8UHwoNSLlPEJrfiBo9Bv/aMf4TuJpN/rRrrm6ne6OS4OqNO@M2841fIMdZMQP7bjMeonkQZKdfNQdUHotaqfR6oPIo2U553n7fNUocbjD1cciAWdrXjrMYyxWg0yPV9ymaKnrH7CRKbx7j0v0mUvEkQxaaplI3OxR5jUpyJv0GgjNmKESVbJtzg5oBryAH4DCIu0gWsofEgIKeEWclj/RUb4VVuEJj1hUKmR@6nNr3Wm3tr@41J@phJbf1KJuipSUlR7lCGBUWn4HzxMAWWUMQqorYCZQgHTFGVaMwCAFyeDu@icBlPrAyb/fwM7xG5gxwIbNWZmdHPc89QNY45k7gJ3j8vdopTeHsh@AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // n = max. number of times we can toggle bits
m => // m[] = binary matrix
m.map(W = // initialize W to a zero'ish value
h = (X, w, k, Y) => // for each entry in m[], using a recursive callback h:
m.map((r, y) => // for each row r[] at index y in m[]:
r.map((v, x) => // for each value v at index x in r[]:
k ? // if this is the first pass:
h( // do a recursive call:
x, // set X = x
w, // pass w unchanged
q = t = 0, // set k = q = t = 0
y // set Y = y
) // end of recursive call
: // else (2nd pass):
(x - X) % w && // do nothing if we're not located on the grid
(y - Y) % w || // of width w
x < X | // or x is too low
x > X + w | // or x is too high
y < Y | // or y is too low
y > Y + w // or y is too high
|| // otherwise:
++q < w * 4 | // increment q
(t += !v) > n // increment t if v = 0
? // if q < w * 4 (not a complete square)
// or t > n (too many bits must be toggled):
0 // do nothing
: // else:
W = w + 1 // success: update W
) // end of map()
) // end of map()
) | W // end of map(); return W
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 30 bytes
```
xZyP:"0&G@qWQB&+gZ++7Mz<m@*vX>
```
It uses convolution \o/
Inputs are `n`, then `M`.
[Try it online!](https://tio.run/##y00syfn/vyKqMsBKyUDN3aEwPNBJTTs9Slvb3LfKJtdBqyzC7v9/E65oAwVDBRAGktZABpxrDWUYQGQMIUpAXGuoerBALAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8L8iqjLASslAzd2hMDzQSU07PUpb29y3yibXQasswu5/rEtURch/E65oAwVDBRAGktZABpxrDWUYQGQMIUpAXGuoerBALJcFyAyoSmt0LUhGGcCsgHJiuQwgOqH2olFgaUOYdkOQekOQAMIWqAuB4gYGBhApTFtgyuAORCgzRHIisnuR/IFsD8zziGAxjAUA "MATL – Try It Online").
### Explanation
```
x % Implicit input: n. Delete
Zy % Implicit input: M. Size as a length-two vector, [R, C]
P % Sort. Gives [S, L], where S = min(R, C) is the smallest dimension of A
: % Range from 1 to the first entry of the vector, that is, A
" % For each k in [1, 2, ... , A]
0 % Push 0
&G % Push the two inputs again: n, then M
@ % Push k
qWQB % Subtract 1, 2 raised to that, add 1, binary: gives [1 0 0 ··· 0 1] of
% length k
&+g % 2D array of pairwise additions. Convert to logical. This gives a binary
% k×k array with a frame of ones: [1 1 ··· 1 1;
% 1 0 ··· 0 1;
% ··· ··· ···
% 1 0 ··· 0 1;
% 1 1 ··· 1 1]
Z+ % 2D convolution with M, maintaining size. This counts the number of ones
% in M along all sliding frames of the above form. The result is a 2D array
+ % Add the above with n, element-wise.
7M % Push the 2D array defining the frame again. Number of nonzeros. This
% gives the frame "length", that is, the number of ones (which is 4*(k-1))
< % Less than?, element-wise. An entry equal to 0 indicates that a frame
% exists such that the number of ones in M along that frame plus n is at
% least the frame length
m % Ismember. This checks if 0 is indeed present in the above result
@* % Multiply the above by k. This will give either 0 or k
vX> % Concatenate stack contents, then maximum. This computes a cumulative
% maximum of the results for all k (each result being either 0 or k)
% End (implicit). Display (implicit)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 133 bytes
```
n=>m=>m.map(W=h=(X,w,Y,t)=>m.every((r,y)=>[...r,0].every((v,x)=>t?x%w&&y%w||x>w|y>w||(t+=1-(m[y+Y]||0)[x+X]):h(x,w,y,~n)?W=w+1:1)))|W
```
[Try it online!](https://tio.run/##VU/LbsIwELz7KywkwFaMZUs9VFSGU3vshQOgNIc0OJAqcahjSKKm/fXUD1BVyevdnZ3Zx0d6TZtMF2ezUPVBjrkYlVhV9tEqPaOtOAm0Iy3ZE4MdKK9S9whp0ts0ppRqwpI7eiWdRc26m7azWT9th6FbtUNvbUAmEnyBqriP9skwMBx30S7ByxPqbPee/Ci83oo24kuOMR62o5afl0JLNM@bOaZapoeXopSbXmWIYWrqjdGFOiJMm3NZGDR5U29qgmle6@c0O6EGihX8AhCW0sAYKgLtrhVMoIDNn2SCnyxFWTBSLqpsFA73endfk/j89VK9S409P6tVU5eSlvUR5UhhVDn8G48PgHHGOQPMe8CdY4BbiHFbcwEAj6EM7sXAdDHzPOD0/w34Jt6Abwu81JG5q7vvrmehGQ8gDwPCnKC7SRm7Lch/AQ "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 134 bytes
```
n=>m=>m.map(W=h=(X,w,k,Y)=>m.map((r,y)=>r.map((v,x)=>k?h(x,w,q=t=0,y):x%w&&(y-Y)%w||x>w|y<Y|y>Y+w||++q<w*4|(t+=!r[x+X])>n?0:W=w+1)))|W
```
[Try it online!](https://tio.run/##VU9Nb8IgGL7zK5iJCmslkHhYnNTTdtzFgzbqoatUO1uqtNo26357x4dmWQK87/P1Al/RLSpjlZ6riSz2ok94L3mQ60Xy6IxW/MjR2q/9kx/iB4mU32qgHLj5jQanxRE12nfhFadanjXDejRC7STEw7rrmqDu2nnYtUHoaeh5l3n9PO1Q5fEntWm89Q4HckFnK157DGPcrXolLtdUCTROyjEmSkT79zQTy1bGiGJSFctKpfKAMCnPWVqhwVZu5QCTpFBvUXxEJeQB/AYQZqKCGyh9SAjJ4Q5yWP5FBvhVW6QmPWm6XHfukza/0ZlyZ/HHNf8UClt/XMiyyATJigNKkMQoN/wP7qeAMsoYBdRWwEyhgGmKMq2ZBoAXJ4OH6Jymp9YHTP7/BnaI3cCOBTZqzMzo5njkqRvGHMncBe4el7tHKb0/kP0C "JavaScript (Node.js) – Try It Online")
Modified from Arnauld's
# [JavaScript (Node.js)](https://nodejs.org), 156 bytes
```
M=>n=>M.map((_,i)=>M.map((N,y)=>N.map((c,x)=>R=M.map((_,j)=>W-=j<i&&N[x+j]+M[y+i][x-~j]+M[y-~j][x]+M[y+j][x+i],W=4*i+!i*!c)&&W<=n?i+1:R),M.push([])),R=0)&&R
```
[Try it online!](https://tio.run/##fZG9boMwFIX3vkUWZMcG2VKGqIqTLRsMLAyWVSEStUYpoNBGZMmr02t@HKNAhcB8@NxzL8d5ekvr7KqrH78oT@f2KNpQ7AuxD4PvtELog2psIaJ3gKiHjDYAsbDCHDDxRb7TnhfJhuSKhPJOtJKN/@jBrLLpv5s32KSJ2Kw1Wen1KsOel@xEcdCEv8eYhkH1W38hqTCmsWCwG7dZWdTl5Rxcyk90RFIyyqm54akokGUgbol11KkMd0o@XEwpjDYYv71aD@WD3DVyWzDbfLQHw@2C4Tjl6wpFbKaI2068d14SLTpYez63afp394JgksAY6r9zzEViS5@RPpXcDXUSsRv@ZAB7jtw5cfMHjJm52j8 "JavaScript (Node.js) – Try It Online")
I don't know what I'm doing...
```
M=>n=> // Unupdated
M.map((_,i)=>
M.map((N,y)=>N&&
N.map((c,x)=>
R=M.map((_,j)=>
W-=j<i&&
N[x+j]+
M[y+i][x-~j]+
M[y-~j][x]+
M[y+j][x+i],
W=4*i)|i|c|n&& // When i=0
// Special consider:
// Here is 1, or
// n>0
W<=n?i+1:R),M.push(0)),R=0)&&R
// So Z[y+i] isn't undefined
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 63 bytes
```
KEVUQVUhQVhS,-lQN-lhQHIgKsm!|*F*V-Rbdd@@Q+Nhd+Hed^Uhb2=eS,Zhb;Z
```
[Try it online!](https://tio.run/##K6gsyfj/39s1LDQwLDQjMCwjWEc3J9BPNycj0MMz3bs4V7FGy00rTDcoKSXFwSFQ2y8jRdsjNSUuNCPJyDY1WCcqI8k66v//6GgDHUMdEAaSsTpAHpwP5BnCeQZgHlgViA9WaQiFBrGxXCYA "Pyth – Try It Online")
Expects array of arrays of booleans and \$n\$ in that order.
### Explanation
```
# implicitly assign Q = eval(input())
KE # assign K = eval(input())
VUQ # for N in range(len(Q)):
VUhQ # for H in range(len(Q[0])):
VhS,-lQN-lhQH # for b in range(1+max(len(Q)-N, len(Q[0])-H)):
m ^Uhb2 # map range(b+1) x range(b+1) to lambda d (look at coordinates in a square of size b+1)
!| # neither of the following are true
*F*V-Rbdd # d[0]*d[1]*(d[0]-b)*(d[1]-b) (coordinates are in the middle of the square)
@@Q+Nhd+Hed # Q[N+d[0]][H+d[1]] (coordinates are already a 1 in Q)
IgKs # if K >= (the sum of this map):
=eS,Zhb # Z = max(Z, b+1)
;Z # after all loops complete, output Z
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
¬ẆZṡLƊ€Ẏ.ị$€JṖḊƊ¦FS>ʋÐḟẈṀ
```
A dyadic Link that accepts the matrix, \$M\$, on the left and the maximal toggle count, \$n\$, on the right and yields the side length of the largest attainable square.
**[Try it online!](https://tio.run/##y0rNyan8///Qmoe72qIe7lzoc6zrUROQ06f3cHe3CpDp9XDntIc7uo51HVrmFmx3qvvwhIc75j/c1fFwZ8P///@jow11DMAQSMdy6USDGQgunKNjiOCCBKBcQwgHptgQWTEWo6ACyFywUbH/LQE "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///Qmoe72qIe7lzoc6zrUROQ06f3cHe3CpDp9XDntIc7uo51HVrmFmx3qvvwhIc75j/c1fFwZ8P/o5Mf7lz8qHHfoW2Htj3cvQWo@tDWhztXhR1e7hAG5ACR5v//BoYGhoYGXAZgmssQRBlwGQKFDAy5gCIgORMuiDQXTBKiEsQ2AKuzACkwQMVcIEPAGMSEaAbThiAuQrMBxCRDiKAhxHSIJRBNUH0GBlDXQVQCAA "Jelly – Try It Online").
### How?
Toggles all bits of \$M\$ and extracts all possible square sub-matrices. Filters out any which have more than \$n\$ ones in their border, and then gets the length of the longest remaining one (or zero).
```
¬ẆZṡLƊ€Ẏ.ị$€JṖḊƊ¦FS>ʋÐḟẈṀ - Link: list of lists of 1s and 0s; M, integer, n
¬ - logical NOT (M) -> toggle all bits of M
Ẇ - get all contiguous sublists of rows of that
€ - for each (sublist, s, of rows):
Ɗ - last three links as a monad - f(s):
Z - transpose (s)
L - length (s)
ṡ - all sublists of (transposed s) of length (length (s))
-> all full height square sub-matrices from s
Ẏ - tighten to a list of all square-submatrices
Ðḟ - filter discard those for which:
ʋ - last four links as a dyad - f(sub-matrix, n)
€ ¦ - sparse application...
Ɗ - ...to indices: last three links as a monad - f(sub-matrix):
J - range of length
Ṗ - pop
Ḋ - dequeue -> [2,3,...,length-1]
$ - ...action: last two links as a monad - f(sub-matrix):
. - 0.5
ị - index into (sub-matrix) -> last and first entries
F - flatten
S - sum
> - is greater than (n)?
Ẉ - length of each (remaining sub-matrix)
Ṁ - maximum (or 0 if empty)
```
---
Note: the second `€` is necessary, even though all of the test cases pass without it (e.g. [this](https://tio.run/##y0rNyan8///Qmoe72qIe7lzoc6zrUROQ06f3cHe3itfDndMe7ug61nVomVuw3anuwxMe7pj/cFfHw50N////j4421DHQMYzl0kFlGMRyxf43AgA) should return `2` not `3`).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes
```
NθWS⊞υι≔LυζW⬤υ⬤κ›⁻∨×⁴⊖ζ¹θΣ⭆υ⎇№…λ⁺λζπ✂ξν⁺νζ∨∨⁼πλ⁼π⁺λ⊖ζ⊖ζω≦⊖ζIζ
```
[Try it online!](https://tio.run/##bVDbSgMxEH3PV@RxAhES6FufShURrC62PxDXYRvMTndzsdqfXyfdSkUMGSY5Z86ZYdq9i@3BhWl6oKHkp9K/YoRRLcVx7wNKOMPbHD11oJRsStpD0dJzxSol3xE8InWZQaXl6apbhVDranrX8j6iy2y88VQSPEfY@R4TLLS8xTZij5TxDU6KPSzHyLEtPcx9N26oVjuM5OIXrA@FMrw46hCClk1gx1B7s2iowuBbhE8t6UJSJbXkrnzvxuJCgkHLwNj192PzZx71H3JU85E82WUJv4rmNTQ8eYa1S7mKltO0EMYaa40w5yxsTUZYhoxlrj7EdPMRvgE "Charcoal – Try It Online") Link is to verbose version of code. Takes `n` as the first input and then the binary matrix `M` as a list of newline-terminated strings. Explanation:
```
Nθ
```
Input `n`.
```
WS⊞υι
```
Input `M`.
```
≔Lυζ
```
Start with the height of `M` as the current square size.
```
W⬤υ⬤κ›⁻∨×⁴⊖ζ¹θΣ⭆υ⎇№…λ⁺λζπ✂ξν⁺νζ∨∨⁼πλ⁼π⁺λ⊖ζ⊖ζω
```
For each possible cell of `M`, try to slice a square of the current size out of `M`, count the number of `1`s on its border, and while none of the candidate squares have enough `1`s...
```
≦⊖ζ
```
... decrement the square size.
```
Iζ
```
Output the final square size.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 116 bytes
```
f(a,n)=for(k=l=0,min(#a,#a~),matrix(#a~-k,#a-k,i,j,sum(s=0,k,sum(t=0,k,!(s*t*(k-s)*(k-t)+a[i+s,j+t])))<=n)&&l=k+1);l
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVFBasMwEKTXvkJJIGjjNUjQQ0BxP-KKIgouimTX2Aq0l3ykl1xK39S-prIkywk9aJnZ3dlZSZ_fvRr082t_uXydXFPuf1xDFXZQNW8DNZWtGLa6oxuFG3UGbJUb9Lun59L4jA8ajzieWjr6ThOQC2hFx53bUVOOMEUHhap1MeKxcBIADlUH262tTMFB2Oj9e9eqvrcfVJHykfSD7pyH64msyYuyljZIFACSuq4ZcpyOj4JhZoJnzASP9YmJ2Bu4RPIgpyFZJ241yySW5ifsVfusjL430ddYqPM0gQfNnMtOcUuf5bnyzyt1zRsuPXzZ8Wrfp_vlHlce6fbLqwRXxpiUEF99_vk_)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 40 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
U˜āR.Δ…€üÿD'øý.V€`ε4Fćˆíø}¯˜_OXs@´}à}Dd*
```
Since there isn't a 05AB1E answer yet, I'll just create my own.
Inputs in the order \$n,M\$.
[Try it online](https://tio.run/##yy9OTMpM/f8/9PScI41BeuemPGpY9qhpzeE9h/e7qB/ecXivXhiQm3Buq4nbkfbTbYfXHt5Re2j96Tnx/hHFDoe21B5eUOuSovX/vwVXdLSBjoGOIQjH6kRDWToGQLYhlG0IZhvAxSFqQOpjAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmVCs5JlXUFpSbKWQZ6tkb6@kkJiXouBrq6TjdWi3DpeSf2kJUNZKQcm@MuHQyuL/oafnHGkM0js35VHDskdNaw7vObzfRf3wjsN7D60r1gsDiiSc22ridqT9dNvhtYd31B5af3pOvH9EscOhLbWHF9S6pGj91zm0zf5/dLSJTnS0gY6hDggDyVgdIA/OB/IM4TwDMA@sCsQHqzSEQoPY2FgdhWgLsGFQDVAFyFqRDTWAWwczEGyEAdQImEswabgyQ7hphjDdhmBhJMthPoBKGxgYQFVgcQBcNcIDCJWGyF5A8RCyV1HshIeTIVKIAgEA).
**Explanation:**
```
U # Pop and store the first (implicit) input-integer in variable `X`
˜ # Flatten the second (implicit) input-matrix
ā # Push a list in the range [1,length]
R # Reverse it to [length,1]
.Δ # Pop and find the first value that's truthy for
# (or -1 if none are truthy):
…€üÿD'øý.V€` '# Get a list of all overlapping block of size y×y
# (where `y` is the current integer):
…€üÿ # Push string "€üÿ",
# where `ÿ` is automatically replaced with the current integer
D # Duplicate it
'øý '# Join the two strings on the stack with "ø" delimiter
.V # Evaluate and execute it as 05AB1E code:
€ # Map over each row of the (implicit) input-matrix
üy # Get all overlapping lists of this row of size `y`†
ø # Zip/transpose; swapping rows/columns
€ # Map over each list of lists
üy # Get all overlapping lists of these row of size `y`†
€` # Flatten this list of lists of blocks one level down
ε4Fćˆíø}¯´˜ # Leave just the borders of each y×y block:
ε # Map over each block:
4F # Inner loop 4 times:
ć # Extract head; pop and push remainder-matrix and first row
# separately to the stack
ˆ # Pop and add this first row to the global array
íø # Rotate the matrix once clockwise:
í # Reverse each inner row
ø # Zip/transpose; swapping rows/columns
}¯ # After the loop: push the global array
˜ # Flatten it
_ # ==0 check (0 becomes 1; everything else becomes 0)
O # Sum to get the amount of 0s in this block's borders
X # Push the first input from variable `X`
s@ # Check amountOfZeros <= `X`
´ # Empty the global array for the next iteration
}à # After the map, do an `any` check by popping and pushing the max
}Dd* # After the find first: fix a potential -1 to 0†:
D # Duplicate the integer
d # Pop the copy and do a non-negative check (1 if >=0; 0 if <0)
* # Multiply the two together
# (after which the result is output implicitly)
```
We have to do the `}Dd*` instead of just lowering the `[length,1]` ranged list to `[length,0]`, because `ü0` would give an error.
] |
[Question]
[
Related to [AoC2017 Day 18](https://adventofcode.com/2017/day/18), Part 2. (Anyone want to add Duet to esolangs?)
---
**Duet** is an assembly-like language that involves two processes running the same program simultaneously. Each process of Duet operates with 26 registers named `a` to `z`, all initialized to zero, except for the register `p` which contains the process ID (0 or 1).
Individual instructions in Duet are as follows. `X` is a register, and `Y` and `Z` can be a register or a constant. A constant is an integer which can be positive, negative, or zero, and is written in base 10 with optional `-` sign.
* `set X Y` sets register X to the value of Y.
* `add X Y` increases register X by the value of Y.
* `mul X Y` sets register X to the result of multiplying the value contained in register X by the value of Y.
* `mod X Y` sets register X to the remainder of dividing the value contained in register X by the value of Y (that is, it sets X to the result of X modulo Y).
+ X may be assumed to be strictly non-negative and Y may be assumed to be strictly positive in this challenge.
* `jgz Y Z` jumps with an offset of the value of Z, but only if the value of Y is greater than zero. (An offset of 2 skips the next instruction, an offset of -1 jumps to the previous instruction, and so on.)
* `snd Y` sends the value of Y to the other program. These values wait in a queue until that program is ready to receive them. Each program has its own message queue, so a program can never receive a message it sent.
* `rcv X` receives the next value and stores it in register X. If no values are in the queue, the program waits for a value to be sent to it. Programs do not continue to the next instruction until they have received a value. Values are received in the order they are sent.
After each `jgz` instruction, the program continues with the instruction to which the jump jumped. After any other instruction, the program continues with the next instruction. Continuing (or jumping) off either end of the program in either process terminates the entire program (i.e. both processes), as well as being stuck in a deadlock (both programs waiting at a `rcv` instruction).
Duet does not have any I/O facility. The only observable behavior of a program is that either it terminates, or it doesn't.
Both of these programs below should terminate by a deadlock:
```
snd 1
snd 2
snd p
rcv a
rcv b
rcv c
rcv d
```
```
set i 31
set a 1
mul p 17
jgz p p
mul a 2
add i -1
jgz i -2
add a -1
set i 127
set p 680
mul p 8505
mod p a
mul p 129749
add p 12345
mod p a
set b p
mod b 10000
snd b
add i -1
jgz i -9
jgz a 3
rcv b
jgz b -1
set f 0
set i 126
rcv a
rcv b
set p a
mul p -1
add p b
jgz p 4
snd a
set a b
jgz 1 3
snd b
set f 1
add i -1
jgz i -11
snd a
jgz f -16
jgz a -19
```
Write an interpreter for Duet, which takes a valid source code as input (list of lines is OK), and runs it until the program terminates. Your interpreter should terminate if and only if the input Duet program terminates.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
Some examples that halt because one process exits early:
* Process 0 waits but Process 1 exits early by jumping over the end
```
mul p 10
jgz p p
rcv x
```
* Process 1 loops indefinitely but Process 0 halts by jumping before the start
```
jgz p 0
jgz 1 -2
```
* Process 0 loops indefinitely but Process 1 runs through the program and exits
```
add p 1
mod p 2
jgz p 0
```
Some examples that never halt:
* Both processes run an infinite loop that passes some values around
```
set a 10
snd 1
snd 2
rcv x
rcv y
jgz a -4
```
* Both processes run a tight loop
```
jgz 1 0
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 459 bytes
```
p->a=matrix(2,26);a[2,16]=1;c=[l=List(),l];n=[1,1];while(![m<=0||m>#p|m<-n]&&sum(k=1,2,#c[k]||Vec(p[n[k]])[1]!="r"),for(k=1,2,(g(u,v)=if(0<t=s[u]-96,a[k,t],eval(Strchr(s[u..v]))));s=Vecsmall(p[n[k]]);i=s[2]-96;v=if(i-14&&i-7,x=s[5]-96;7,5);i-7||while(s[v]-32,v++)||z=g(5,v++-2);if(i-3,y=g(v,#s);i-5||a[k,x]=y;i-4||a[k,x]+=y;i-21||a[k,x]*=y;i-15||a[k,x]%=y;i-7||(z>0&&n[k]+=y-1);i-14||listput(c[3-k],y),if(#c[k],a[k,x]=c[k][1];listpop(c[k],1),n[k]--));n[k]++))
```
[Try it online!](https://tio.run/##dVPLjqMwEPwVD9FGZmOPMHkwEXG@YG8r7cXywSGPYQOJBYRNIv4928YYMqMZTtWv6uqy0KpI6UE/9og/NF0rnquqSK84JOHCj5UICVtIzuKEi4z/SssK@yST8YkLRpiM/72n2Q6/iHzFg6bJ1yPd5Ct6kuNxecnxkTMSklEijrJp/uwSrMUJsPQFky/cKzyf7M9F14YP@EJqn6d7HKwqXoqLpMsFUeJIKkl2tcrw76pI3gsMpdfXWvrwxSUH3jJXWdaTxykMh2Y4rg1bStlsPE5pRK5QmLeFiMyhj0ZNYy8oRS3pNCT1ZOI3zZ0f8NxgGkKXYZiSG@RqMirN2LxpjKyr5DeIZi6atGHIXPyzjVnf/aONYSe@r4Px2KiFEcoMJQOWDOzVlwonYkqPktx8Artb90i3zmDwLm47zxq3NeYTQ0Up2NFyTnz/obTObnhPkBBeedoi5hHUgtABbUCR1Eg5sHEgcWDrSWDwyl2Fso4CYIqmPVY2nV8ypBGLDP57uAPWLq3sSrXdwiBlrgNwn1dd3pKzMHKBRou3YOB/mwfzNjqDfKu7Wxwuo9nS0Zl4Ovvcafg2nSzIbhAL4HNubL7RuHRYoekHn0xu86R7j4LnExZfu2uPelJuCazqzeDezOlSg9F9ObNSetl2PfvmAsY@cJnsHrKL4TDKlvadOzODT69o1F9th832Dcw8YlvofB88DweSwIO/8vEf "Pari/GP – Try It Online")
Takes a list of lines as input.
[Answer]
# JavaScript, 249 bytes
```
P=>{for(Q=[...P],P.M=[],Q.M=[],I=J=Q.p=1;E=I+J&&P[P.$??=0];[P,Q]=[Q,P])with(P)I=J,J=1,([[,O],X,Y]=E.split` `).map(C=>P[C]??=0),eval({g:X+`>0&&($+=${Y}-1)`,n:`Q.M.push(${X})`,c:`M+""?${X}=M.shift():J=0`}[O]||X+{e:'=',d:'+=',u:'*=',o:'%='}[O]+Y),$+=J}
```
```
F=P=>{
for(
// Initial
Q=[...P], // P is process 0; Q is process 1
// We use the array for instructions,
// use P.a ~ P.z for registers
// use P._ for message queue received
// use P.$ for index of next instruction to execute
P._=[], // initial message queue
Q._=[],
I=J= // is last instruction successfully executed? (not waiting message)
Q.p=1; // initial Process ID for Process Q
// While not dead lock and not out of range
E=I+J&& // terminate if all process waiting message
P[P.$??=0]; // next instruction to execute
// Swap process schedule after each instruction execution
[P,Q]=[Q,P]
)with(P) // use variables in process P
I=J,J=1, // initial success flags
([
[,O], // The second character is different for each instruction
X, Y // two operand
]=E.split` `) // parse instruction, split it by space
.map(C=>P[C]??=0), // Initial any value used to 0
eval({ // execute the instruction
g:X+`>0&&($+=${Y}-1)`, // jgz
n:`Q._.push(${X})`, // snd
c:`_+""?${X}=_.shift():J=0` // rcv
}[O]||
X+{e:'=',d:'+=',u:'*=',o:'%='}[O]+Y // other math op
),
$+=J // move to next instruction if success
}
```
```
F=P=>{for(Q=[...P],P.M=[],Q.M=[],I=J=Q.p=1;E=I+J&&P[P.$??=0];[P,Q]=[Q,P])with(P)I=J,J=1,([[,O],X,Y]=E.split` `).map(C=>P[C]??=0),eval({g:X+`>0&&($+=${Y}-1)`,n:`Q.M.push(${X})`,c:`M+""?${X}=M.shift():J=0`}[O]||X+{e:'=',d:'+=',u:'*=',o:'%='}[O]+Y),$+=J}
```
```
<form onsubmit="F(T.value.trim().split(/\s*[\n;]\s*/));return false;">
<textarea id=T></textarea>
<br>
<button id=R>RUN</button>
</form>
```
-1 byte by Neil
[Answer]
# [Rust](https://www.rust-lang.org/), 576 bytes
```
|c:&[&str]|{let c:Vec<Vec<_>>=c.iter().map(|s|s.split(' ').collect()).collect();let(r,n,mut p)=(|r:&str|r.as_bytes()[0]as usize,|n:&str,f|n.parse::<i64>().unwrap_or(f),(vec![0;123],vec![0;123]));p.0[112]=1;while p.0[1]+p.1[1]<2{p=(p.1,p.0);let(c,m)=(c.get(p.0[0]as usize)?,&mut p.0);let x=r(c[1]);if c[0]=="snd"{p.1.push(n(c[1],m[x]));}else if c[0]=="rcv"{if m.len()>123{m[x]=m.remove(123);m[1]=0}else{m[1]=1;m[0]-=1}}else{let y=n(c[2],m[r(c[2])]);match c[0]{"set"=>m[x]=y,"add"=>m[x]+=y,"mul"=>m[x]*=y,"mod"=>m[x]%=y,"jgz" if n(c[1],m[x])>0=>m[0]+=y-1,_=>()}}m[0]+=1}Some(1)}
```
[Try it online!](https://tio.run/##ZVRhb5swEP3Or7giLTUrQZikaZOUVJ0aqdO2VtqySlMWRQ4xLRMQBCRtCvz27GxMkq1ImLvnu3fvDsvpOst3fgwRC2JiQKEBPiHPwQcXdqU3aE1bWZ7OykKA3uCRe1finY9GrmcFOU@JYUUsIWVWZlaWhEFOTuHUsLxVGHIvJ8aROUQOkpqxGa1zSAyXlOlAsJepxbL5YpvzjBhTe8YyWGfBGzfLWO6bfhlbCUszPhhcBb3uCGuu45eUJfNVSnzDJBvunUztIXU6M/PINoxhYtlTSp2ZS4cvz0HIQQKzs8Si@LlyisQlaJsI1/o8M0JlnvWEtog9yDGuzZZUrkLh1U2JhyzGMPDBw0jX1bN4qRdIaCXr7JnEct@Mpq9CS8XDjMMhNvU2eoFuZIUcpz9CyYUIdSMr5dFqwwkixjBCCteWyYW0KUL2rO3SqgaFlq0rajmiVioNA2VFLPeeZbVCz3iuuyNJvzV1tlwq70y40TpU7kfprprdD8L98/SmC9nH3YxsEWCL9DY15y7@k6qqAVr9WEWo3ah24jQN5ZnyVykEcYLjC2JoTTUxKKCaWB25JhqOA5hcF3L15LrUTU2IhwA6GI8GwzwUDAnQCw21oZFIgCEVNoaRbSo30KgRJpCahDoX0kqgd2krnstz@1zDptFkDbXTv@j2ZbJwOt1DgMheiJLoL4Da@MgOFu@K96XBoKO6Et6ikeKDvZfU@6f5Wl6jBMNrFQvVbFdWY2oWNUqxRq2hpqbvtFCq0oTvo99T4tq0L0as2rb3ExVaXsVODdiqTtsRmJqLmomjkuzmXzFBdPyHJZlct03ZbsNNMU@ekZm6f5o7qD4vbv1Vl4v@O9b3VwpeB@oywstln5qkQZyH8QnRJzdfv8DkASZ3Y7i7ub@FYnBd6WZNeJThk9b/0IHk18NPTH4cw6fx@B4m4@/fPt/fTMa3uoqutGr3Fw "Rust – Try It Online")
Fun!
Ungolfed:
```
|cmds: &[&str]| {
let cmds: Vec<Vec<_>> = cmds.iter().map(|s| s.split(' ').collect()).collect(); // split commands
let (register, number_or, mut process) = (
|r: &str| r.as_bytes()[0] as usize,
|n: &str, f| n.parse::<i64>().unwrap_or(f),
(vec![0; 123], vec![0; 123]), // process state:
// 0 - program counter
// 1 - rcv signal
// b'a'..=b'z' - registers
// b'z'+1.. - rcv queue
);
process.0[112] = 1; // b'p' == 112
while process.0[1] + process.1[1] < 2 { // while not deadlocked
process = (process.1, process.0); // swap processes
let (cmd, memory) = (cmds.get(process.0[0] as usize)?, &mut process.0);
let x = register(cmd[1]);
if cmd[0] == "snd" {
process.1.push(number_or(cmd[1], memory[x]));
} else if cmd[0] == "rcv" {
if memory.len() > 123 {
memory[x] = memory.remove(123);
memory[1] = 0
} else {
memory[1] = 1;
memory[0] -= 1 // don't advance program
}
} else {
let y = number_or(cmd[2], memory[register(cmd[2])]);
match cmd[0] {
"set" => memory[x] = y,
"add" => memory[x] += y,
"mul" => memory[x] *= y,
"mod" => memory[x] %= y,
"jgz" if number_or(cmd[1], memory[x]) > 0 => memory[0] += y - 1,
_ => (),
}
}
memory[0] += 1
}
Some(1)
};
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~537 ...~~ 312 bytes
```
->s{g=[{},{p:1}];*q=[],[];*a=0,0;r=s.lines;(2.times{|x|l,m,n=r[a[x]].split
h="g[x][:"
eval [[k=[z=h+m+?],y=?(+z+"||0)"]*?=,t=n&&n>?9?"(#{h+n}]||0)":n]*?%,"q[x][0]?(#{z}=q[x].shift):a[x]-=1",k+?++t,z+?=+t,"q[1-x]<<#{d=m&&m>?9?y:m}","#{d}>0&&a[x]+=#{t}-1",k+?*+t][l[1].ord%37%8]
a[x]+=1}
)while a.min>=0&&r[a.max]}
```
[Try it online!](https://tio.run/##bVJtT6NAEP6@v2KzjY0KJSx9sy9b4kWizcWaXDV@IJsGpC@cQLGgV0v57b3ZZfXO1H6Yzjwz88yzM2xe/ffDgh0ao6xYMrco9SLt05IPzl@Yy3UXHI@ZujnYsMyIwmSeDU4tIw/jeVbst/tIj/WEbVzP3XJuZGkU5mjFyBJCt0/Q/M2LsOs@M3fHVlqs2Vx/Z/apttPIfm@eEX5uMz1nSb2ejOyeTU5rxUpLSi6T/QTSJzp5EWQmtyG5K5mIjGwVLvKzvpjaYJToz5qtabm@02wGf9BBG1s@HNaKgMX1eiy43/txSXQCUDky63XRqrFakZeNqv9cy7kbuZQb601w0uyeXHBUFdESnf1ZhdEce0YcJiMG7fBiI/a2vDykm/WSsuHw8W42nt7Pbp3xxJndXt5eoiwJMJXWkjZFm6c37EnrS/skbYCOe5GgtQSt82t2c3k/m46d2bUzdW6cCcrmOQ5xk0rHgxnxa4RTTLvo93IHTioBD8Z6QQCVDSoT4FSIJ5CKhFpd6aW4c2Eqnou22UbxGgSDWEVt9bqtnmwWQbP1r0B0@2IkxD6mJvzka/2j4T3peLipNiAi/0PKApufkjpfFlXJ@1AC5ZUKXz22Jad5ahcVSmFGpaGipkdaKFVtIl5A3FHiGrSHvtu5PEgTDvJDXOrq4f9jqR2Zn@sXwrfom0rJ0gKWCWCq3FSS4TgSlTVtqBGtD1PgeHTG9yDpWgpRN1D7tz5Jvq@WZB1GqhEmQai2cOUny3ENB3MviNZPzx@g9QWssCYfpK95Ru5@EoW0jpD2EdJRyASgw18 "Ruby – Try It Online")
A little more golfy. Still very copy-pasty.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 224 bytes
```
WS⊞υ⪪ι ≔E²⊞OE²⁸∧ι⁼¹⁵λ¹θW∧⊙θ§κ²⁸⬤θ⁼§κ²⁶﹪§κ²⁶Lυ«≔§θ⁰η≔⮌θθ≔§υ§η²⁶ζ≔⌕β§ζ¹ε≔⌕β§ζ±¹δ≔⎇⊕δ§ηδI§ζ±¹δ≡§§ζ⁰¦¹e§≔ηεδd§≔ηε⁺§ηεδu§≔ηε×§ηεδo§≔ηε﹪§ηεδgF‹⁰⎇⊕ε§ηεI§ζ¹§≔η²⁶⁺§η²⁶⊖δc«§≔η²⁸‹§η²⁷⁻Lη²⁹§≔ηε§η⁺²⁹§η²⁷§≔η²⁷⁺§η²⁷§η²⁸»⊞§θ⁰δ§≔η²⁶⁺§η²⁶§η²⁸
```
[Try it online!](https://tio.run/##jVTbbqMwEH0OX2HlyUhEwuRC6D5Fe5EqtbvVtj/gYCew6wDBJt121W/Pji80JJBqeUAz43POHI8NaUbrtKTieHzOcsERvi2qRj2qOi@22PfRQyMz3ATosRK5wnmAxmjs@5@8lZT5tsD3tMJRYFA/Kl5TVda2tgzQqmCa8HXfUCExmQdI@L4fIKJfe9BwHTVuVbzgPVDUbcH4H/w7QNFSw1ZC6LrT6C4vYPW@ZI0oe@U7XmwVuPbNg/56I@e2BYJiCLgMPLRLP/mB15LjvfN2SWlO5jLTBnCvHdy3HHaxPoFe3T75x5jvfEsVx8QMhnWwT7wuaP0Cx5HWfMcLxRlm/pkJnX6mUuFhvVZQPucqzdA7qoMO7WnoCaVUcjTm4xtkDXT6cCdkIewK5EE0pwPSJdP/xGuu8J7yHf@QWF4hXhz@AHMLzE1ZI3zHpcQh9BoYKj8fKh8YKrH3qGciWvS3bS7gF949tI6jFBzBsEd9qaW@tvJcKtZXPC@ggbvRGRSixAqOhmbSyYyxKDm/trF/jRzFA3uJz2ejP0nNfvNGjG9oI9SN/T9cfFfMgf5/YP0mb8ej5ArlaEo8HVBEvF0jUIVI7P3avkJQmQJFkUcZA@SEmAUIbIXqihUhUWyiCi2WodNZzsO5tysZhLSVjpJ4lhiyTqazE0Cz17ol5GtEQng8WUDca56YgKKpV6cHWNfZurWyQeG7pYUBUAez9lonALcu1m6zM9ONulnYKoEe1oOVJj0vhDiazjeQL5y5CUm84@Qg/gE "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated instructions. Explanation:
```
WS⊞υ⪪ι
```
Read the instructions, splitting on spaces.
```
≔E²⊞OE²⁸∧ι⁼¹⁵λ¹θ
```
Create two threads of execution. Each thread is represented by an array of values. The first 26 represent the variables `a-z`, then comes the program counter, the receive counter, and the running flag, which is normally `1` but gets reset to `0` if a `rcv` instruction is executed when the receive counter exceeds the number of items in the send list. Any further items are the send list. Items are not removed from the send list, instead the receive counter is used to determine which the next item is.
```
W∧⊙θ§κ²⁸⬤θ⁼§κ²⁶﹪§κ²⁶Lυ«
```
Repeat until either both running flags are zero or at least one program counter is out of range.
```
≔§θ⁰η
```
Get the current thread.
```
≔⮌θθ
```
Schedule the other thread to become the current thread.
```
≔§υ§η²⁶ζ
```
Get the current instruction.
```
≔⌕β§ζ¹ε
```
Get the index of the first argument, assuming it's a variable.
```
≔⌕β§ζ±¹δ
```
Get the index of the last argument, assuming it's a variable.
```
≔⎇⊕δ§ηδI§ζ±¹δ
```
Evaluate the last argument as a variable or a constant as appropriate.
```
≡§§ζ⁰¦¹
```
Switch over the second character of the instruction, as it's unique across all instructions.
```
e§≔ηεδ
```
For `set` simply assign the evaluated last argument to the index given by the first argument.
```
d§≔ηε⁺§ηεδ
```
Add the last argument to the first argument.
```
u§≔ηε×§ηεδ
```
Multiply the first argument by the last argument.
```
o§≔ηε﹪§ηεδ
```
Modulo the first argument by the last argument.
```
gF‹⁰⎇⊕ε§ηεI§ζ¹§≔η²⁶⁺§η²⁶⊖δ
```
For `jgz` evaluate the first argument as a variable or constant and if it's positive then update the program counter by the given offset (but taking the autoincrement into account).
```
c«
```
If this is `rcv` then...
```
§≔η²⁸‹§η²⁷⁻Lη²⁹
```
Calculate whether this thread is stalled.
```
§≔ηε§η⁺²⁹§η²⁷
```
Try to get the value out of the send list anyway. (If there aren't enough items, Charcoal will fetch a meaningless value, but it will be overwritten by the correct value once it's been added to the send list.)
```
§≔η²⁷⁺§η²⁷§η²⁸
```
Increment the receive pointer if there was a waiting item in the send list.
```
»⊞§θ⁰δ
```
Otherwise this is `snd` so push the last argument to the (now other thread's) send list.
```
§≔η²⁶⁺§η²⁶§η²⁸
```
Increment the program counter, unless the thread is stalled on a receive.
[Answer]
# TypeScript Types, 1203 bytes
```
//@ts-ignore
type a<T,A=0,N=[]>=T extends`${N["length"]}`?N:a<T,A,[...N,A]>;type b<T,P=0,N=[1,0][P]>=T extends[N,...infer T]?T:[...T,P];type c<T,U,P=0>=T extends[infer X,...infer T]?c<T,b<U,[P,[1,0][P]][X]>>:U;type d<T,U,N=[]>=T extends[infer X,...infer T]?d<T,c<U,N,X>>:N;type e<T,U>=T extends[...{[K in keyof U]:{}},...infer T]?e<T,U>:T;type f<T>=T extends`${number}`?T extends`-${infer U}`?a<U,1>:a<T>:T;type g<M,R,V>=Omit<M,R>&Record<R,V>;type h<M,A>=A extends keyof M?M[A]:A extends{}[]?A:[];type i<S,P=[]>=S extends`${infer I}\n${infer R}`?I extends`${infer O} ${infer X}${` ${infer Y}`|""}`?i<R,[...P,[O,f<Exclude<X,`${string} ${string}`>>,f<Y>]]>:0:P;type j<k,l={p:[]},m=[],n=[],o={p:[0]},p=[],q=[],r=0>=[m,`${m["length"]}`]extends[0[],keyof k]?k[m["length"]]extends[infer s,infer X,infer Y]?[h<l,X>,h<l,Y>]extends[infer t,infer u]?{set:j<k,g<l,X,u>,b<m>,n,o,p,q>,add:j<k,g<l,X,c<t,u>>,b<m>,n,o,p,q>,mul:j<k,g<l,X,d<t,u>>,b<m>,n,o,p,q>,mod:j<k,g<l,X,e<t,u>>,b<m>,n,o,p,q>,jgz:t extends 1[]?j<k,l,b<m>,n,o,p,q>:j<k,o,p,q,l,c<m,u>,n>,snd:j<k,l,b<m>,n,o,p,[...q,h<l,X>]>,rcv:n extends[infer v,...infer w]?j<k,g<l,X,v>,b<m>,w,o,p,q>:r extends 1?0:j<k,o,p,q,l,m,n,1>}[s]:0:0:0;type M<T>=j<i<`${T}
`>>
```
[Try It Online!](https://www.typescriptlang.org/play#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgEEBeABkoDlaBtAXQD5bzD0APcOkQATSAAMAJAG8mrAEQAbYfHAALeewC+4gPxMAXGSrVKrAHSWmNLgG5cBQgCMKlAAoNmbAIyV67VjcuHj5BYTFWa0tzWEQAM3RUQnJ2XXIDC0sqIPt8IgBjVwBVdwZuXgEhUUhWWISkgA1KaLrE5NTCqhcSwLNff0D2AIauTgMi3McRYq8OctCqiNbG5stl9t1pqkKS6wbOMaZJonRi+crwmujpVgBpQljCAGt0HGQ4wiL2A2ktLVWYvE2ildKcqEUxuRjoQ4hRzmFqlJpIgAK4AWyciR0aQWl3E0Bk6yK2LIJW8Y2MkOh8FIAFlKAAlSgANW4AHk0bBwHTGZwAGQM9D5NDTJms6FqHnUbjUXHVZ6vd6EWm6WmsajfWUXaq-Di6agZdjQ2CkADKpTmtFNcrESPWAEktAAdRCEoFJBnY+02iRu+qENlaQh+toNLQycTB6TrACaOgAPvJ5NiTUzMuY3GY2ZRYQBRfj5RQokSnJpIyDgVCxeBBmQVquIGviA450gxzhDMb0AxuaEAK1IT0oilo0jwhv+aLY7EoiGnlGQo-HrH8-zw84AjvPUGU2GjKEi0QplI31JodOxtRF6BxKC83h8nqknqwj0oVGehleautIJR1k0sapKwkqKJQ+yUKBlDtpeCJLO6hDgP+CEoqk0iQOg4AGAOQ40mBTQopwlAuGiRGIAulB4JQG5EcQIgiNhg6UHh4GUIUSGEURJFkRRVE0ZQaIooojG4aQ+GUNMHEttxs68dRRFosgDE4cxYmsacUlcaQpGycglHyZQfbwAAXgY4A+oQ3h6ipYEyeRel8WMKkOdRw5sdplCEbORGQKIIluXZcnphukFqfsXCUKg+QAG4GIgPq1Ah0UAusADuqQqSxTTRVpOmpXJNEGEk36Wbo3bOfpIVgfu5HklorCQN83bNdCtJwrQA4mki5BaJgzacJgmDAAAVIQajEIo4DVoh6AVoQ+TEBhkC2IQkBqMgQkiIQGDgCiqDxfQhDDcAg0OEQAASh20MqpDiJgvlbd492iIQABMz1bXgmBRdFJDfTFzj-b9+RA4QIh9RZ4guiGSTUM6iCRrohCygYhCIOg0VtCNiFVmiq2VtNx2cLYp15IQ53eIQ11tXdgmKIQeCWfQmBGcZDMM6D-AQyVUOutGCFwy6iPI4QqPo5jSTYwTeP1oTwDE6Tjjna9VM3XdrPs8zGuU9A72Rjz0P8-6gsI4QSMo2jGNY6N0v4w28BHfLJPYGT50AMyqzTmB0Z9lmYIpvvvRrjPM-rcGQIQvMw8j8PCxb4vWzjsAywTjaOwrQ2jXUsRckQQhzQtS0rWtG2KFtahcohahEBg+R7ZAsDIPFijJ7nSSPJAyBokQqXEDgjuDSA5NchHtf143zet0IqArTte2IBHxCIDgLuOPaV1qyzJmWYQoeQ4b6wm3HouWxLhBS7jdtyxnQ-nSP21CuPTeEC3nLTytiSoGgkCr0Q9qU9TW691MIkCZh9P2D03qc1BivDWxBCDQAACzc3DpHA+AtY5mxFmLK2ksbaX1lmnImJMgA)
## Ungolfed / Explanation
```
// Converts a stringified number to a tuple representation
type StrNumToTuple<T, A=0, N=[]> = T extends `${N["length"]}` ? N : StrNumToTuple<T, A, [...N, A]>
// Increment/decrement an integer stored as e.g. [0, 0] for 2, [1, 1, 1] for -3, and [] for 0
// Invoked as Inc<T> to increment, or Inc<T, 1> to decrement
type Inc<T, Pos = 0, Neg = [1, 0][Pos]> = T extends [Neg, ...infer T] ? T : [...T, Pos]
// Add/subtract two integers
// Invoked as Add<T, U> to add, or Add<T, U, 1> to subtract
type Add<T, U, P = 0> = T extends [infer X, ...infer T] ? Add<T, Inc<U, [P,[1,0][P]][X]>> : U
// Multiply two integers
type Mult<T, U, N = []> = T extends [infer X, ...infer T] ? Mult<T, Add<U, N, X>> : N
// Modulo two integers
type Mod<T, U> = T extends [...{ [K in keyof U]: {} }, ...infer T] ? Mod<T, U> : T
// Parse an argument (like "a" or "-3") into either a register ("a") or an integer ([1, 1, 1])
type ParseArg<T> = T extends `${number}` ? T extends `-${infer U}` ? StrNumToTuple<U,1> : StrNumToTuple<T> : T
// Set a register in memory
type SetArg<Mem, Reg, Val> = Omit<Mem, Reg> & Record<Reg, Val>
// Get the value of an argument
type GetArg<Mem, Arg> = Arg extends keyof Mem ? Mem[Arg] : Arg extends {}[] ? Arg : []
type ParseProgram<Str, Prog = []> =
// Get the first line of Str
Str extends `${infer Inst}\n${infer Rest}`
// Garbage parsing logic
? Inst extends `${infer Op} ${infer X}${` ${infer Y}`|""}`
? ParseProgram<Rest, [...Prog, [Op, ParseArg<Exclude<X,`${string} ${string}`>>, ParseArg<Y>]]>
: 0
// Str is empty
: Prog
type Run<
Prog,
// Active process
MemA={p:[]},
IpA=[],
QueueA=[],
MemB={p:[0]},
// Inactive process
IpB=[],
QueueB=[],
// Set to 1 when rcv is called with an empty queue; used to detect deadlock
JustSwapped=0
> =
// If IpA > 0 and < Prog.length
[IpA, `${IpA["length"]}`] extends [0[], keyof Prog]
// Store the parts of the current instruction in Op, X, and Y
? Prog[IpA["length"]] extends [infer Op, infer X, infer Y]
// Get the values at X and Y and store them in XV and YV, respectively
? [GetArg<MemA, X>, GetArg<MemA, Y>] extends [infer XV, infer YV]
// Switch on Op
? {
set: Run<Prog, SetArg<MemA, X, YV>, Inc<IpA>, QueueA, MemB, IpB, QueueB>
add: Run<Prog, SetArg<MemA, X, Add<XV, YV>>, Inc<IpA>, QueueA, MemB, IpB, QueueB>
mul: Run<Prog, SetArg<MemA, X, Mult<XV, YV>>, Inc<IpA>, QueueA, MemB, IpB, QueueB>
mod: Run<Prog, SetArg<MemA, X, Mod<XV, YV>>, Inc<IpA>, QueueA, MemB, IpB, QueueB>
jgz:
// If XV <= 0
XV extends 1[]
? Run<Prog, MemA, Inc<IpA>, QueueA, MemB, IpB, QueueB>
// Swap to the other process (to protect against infinite loops on only one thread)
: Run<Prog, MemB, IpB, QueueB, MemA, Add<IpA, YV>, QueueA>
snd: Run<Prog, MemA, Inc<IpA>, QueueA, MemB, IpB, [...QueueB, GetArg<MemA, X>]>
rcv:
// Get the first value in QueueA
QueueA extends [infer Val, ...infer NewQueue0]
? Run<Prog, SetArg<MemA, X, Val>, Inc<IpA>, NewQueue0, MemB, IpB, QueueB>
// QueueA is empty
: JustSwapped extends 1
// Deadlock
? 0
// Swap to the other process, enabling JustSwapped
: Run<Prog, MemB, IpB, QueueB, MemA, IpA, QueueA, 1>
}[Op]
: 0 // unreachable
: 0 // unreachable
// Otherwise, halt
: 0
```
[Answer]
# Python3, 686 bytes:
```
import operator as o
u=lambda g,n:n.get(g,0)if g.isalpha()else int(g)
def e(s,n,i,q,w,r):
k=i['i']
if q and r:n[r.pop()]=q.pop();i['i']+=(not r);return
if (v:=s[k][0])=='set':n[s[k][1]]=u((g:=s[k][2]),n);i['i']+=1
elif v=='snd':w.append(u(s[k][1],n));i['i']+=1
elif v=='rcv':
if q:n[s[k][1]]=q.pop();i['i']+=1
else:r.append(s[k][1])
elif v=='jgz':i['i']=i['i']+(1 if not u(s[k][1],n) else u(s[k][2],n))
else:n[s[k][1]]=getattr(o,s[k][0])(n[s[k][1]],u(s[k][2],n));i['i']+=1
def f(p):
p=[i.split()for i in p.split('\n')]
n,m,i,t,q,w,r,s={'p':0},{'p':1},{'i':0},{'i':0},[],[],[],[]
while 0<=i['i']<len(p)and 0<=t['i']<len(p)and not any([r,s]):
e(p,n,i,q,w,r);e(p,m,t,w,q,s)
```
[Try it online!](https://tio.run/##bVLbcuIwDH3PV2j6EmfqMnGgUNLmS7J5cBoH0gbHdQwsu7PfzsoX2rTAMI4kS0dHOlYnsx3k/Enp87nbqUEbGJTQ3Awa@AhDtC96vqsbDhsqcznbCEM2NE26FjazbuS92nKSiH4U0Em8SqJGtCDISCXt6Ac9Up3kEbwXXRl3cRUBFn4Alw3oXJZ6pgZFkqr48Mazz7oviBwM6ORZC7PX0lWRQ16M5XtVplVSFPEoTIwILsKqqtgTsgkJWZVQ@YXFIhA9AhxslWzi/DjjSgnZkD0J5Zh@O1@/HmKk71hPu/3kizVgl5DrC3ZITSZgb5s/ce4rwjruCbPQdtgpFwd1iWSOXeThJxRQCW6MJgO9bIV83dJvxROaVp2WKKuJKspuNqq@MyRpUe4OFQQVIvEvGScol6Q71NF4JelY/I1VnKf/qPsy@@2C779l9fmP4LjtegHpS5j2pRcSW1vxMWZ@xuwWuDyREvtUliA@IzV5Rs/W3SGXIwbG5Ky0fXEtubu7Q1mBRfbM3KkiFA64O2t3vrqzwVzc5bRSGBx8jsVocATZ7XtQwFYRqoWGcgGOuLxpMPOBuQs0fITbiAdh2cpZCpZPacB5ekwfo92AjJBNgM7Wq8XaFVtnvvhKsNW1bYl@DSzFnxunvmq@dgaHeRjRevWFSgvpJ6Xlt014ehcmmO5Z1GHYhevGwy58lGEPz8FDsysujIUy67foLwO5B7a@2nfYQfq5Xkvs91Wav00Dg4fsKiGsL6wuC3DpTX257Td9Iq6nO08XqoubFFhAPP8H)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 373 bytes
```
(Clear@A;P=ToExpression@StringSplit@#;S=A/@{0,1};(#@_=0;#@p=#[[1]];#@i_?NumberQ:=i;#@C={};#@N=1)&/@S;While[0<#@N<=Length@P&/@And@@S&&(#@C!={}||P[[#@N,1]]=!=rcv&/@Or@@S),(P[[#@N]]/.{i_,x_,y_:0}:>Switch[Y=#@y;i,set,#@x=Y,add,#@x+=Y,mul,#@x*=Y,mod,#@x=#@x~Mod~Y,jgz,#@x>0&&(#@N+=Y-1),snd,(1-#&/@#)@C~AppendTo~#@x,_,If[#@C!={},{{#@x},#@C}=#@C~TakeDrop~1,#[N]--]];#[N]++)&/@S])&
```
[Try it online!](https://tio.run/##fVJhj5pAFPx@v2JPEqN1qbvq6Sm31zW0TZq01gaTxhBCFkGlVSDItV45@Ov2IXBg7nJ@cd57w@zM292LaOvsReSuxOkzYqeWunNEyKfKnC38T8cgdA4H1/e4FoWut9GCnRtxSdHYtMtjgmmitCRuMqJIPGCSrlPDAOiaH2YPe8sJf0yYC7XK4gT@Zoy2m12uKT@37s7RyR207thXx9tEWz6HydSzOdeaTdBUr@Gbp6e5rgMJgyy7ZuHqD5C@h8Bp41Y@Mozu@9g18dHEj@aEJJN77a8brbb6kkn8UXHxwYmwxI9siYVtZ6gDcP@wy@C7DPrnLrCP6TffTpf41@Zf1rknZyMz4Mu0jQ@ejVtUlsCB1OZqOg0Cx7MXfgpUbOIva70wjeMYWglIqAmoqulC/HY@hn6QUizpM0OWsx0B6HTO2zDaTdh8l1/FcQMOQbSBrxA6w14FgxzCCpCooFXBVQXtRgIY1JwIuahfCkIlSnVYAAoQHeUVJIYqqEaiPBp2BhIyrXhQ1WbieZYfRnujqgzQ8JbUz7u9ITdF7UOkMklhpjceDcaVdNbpD17jZ9rWs12YWIgS@FXbst5wP64qgfovdpn1rYtUa0QuIw7fuos8@EWyUixPZdV3Pqg8i/o11Ui0NFkLltuib6Sk9IVyNlnDZFhfgEzHxWspboG88iSyeMeClg9I3R88iHxWXFv9ynp1OdJIktN/ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Java 10, ~~630~~ ~~627~~ 625 bytes
```
import java.util.*;L->{Stack<Long>m=new Stack(),q=new Stack();long r[][]=new long[2][26],V,P,t;++r[0][15];for(int c,f=1,g=1,d=1,i=0,j=0,o,v,p;f>-g&d>0;)for(c=2;c--*d>0;d=d>=0&d<L.length?1:0)try{f=g;V=P=g=1;var l=L[d=c<1?j:i];var x=l.split(" ");o=l.charAt(1);l=x[x.length-1];v=(v=l.charAt(0))>57?v-(int)(V=97):new Integer(l);V=V>1?r[c][v]:v;t=r[c][p=x.length>2?(p=x[1].charAt(0))>57?p-(int)(P=97):new Integer(x[1]):0];P=P>1?t:p;r[c][p]=o=='e'?V:o=='d'?t+V:o>116?t*V:o=='o'?t%V:t;l=L[o=='g'&P>0?c<1?j+=V-1:(i+=V-1):0];if(o=='n')(c<1?q:m).add(0,V);if(o<100)r[c][p]=(c<1?m:q).pop();l=L[c<1?j+=g:(i+=g)];}catch(Exception e){g=0;}}
```
-5 bytes thanks to *@ceilingcat*.
Input as a String-array.
[Try it online.](https://tio.run/##ZVNNb6MwEL3nV4wqbWM3QCFSWxXHoB72sFK2ihSJC@JADSGkxFBw2KRRfnt27JJ2tT0Y5uPNG3v8vEn71N5kr@dy29Stgg36zk6VlXPD4PYWJt4jqBrUOoeXg8ptUe@kGokq7Tr4nZbyOAIopcrbVSpyeNYuQF@XGQiyVG0piziZU4bh0wg/nUpVKeAZJHA4z@3guFSpeJ3Na1kEWy7zP2AChFpv/3qsQgC0cRInJqzdeJrE0/vEiqyFpdhk0sZuEnt3CVvVLcE9gbBW3LMKXBmukrvWBldt9VbDVoFdXGeBy6hGCz5lwrZvdCDjWcDd62w2d6pcFmoder5LVXs4rnjBIr7gyMj6tIWKz@OMi5kXbvwyMaE9r5yuqUpFruCKshpdsU7bJ0U8PAPfx/uB1PawgJP@C@BSGtw9hL2t905JxB8fqK/P@gvHW@QtqSh2jwIvbGORxH3i90xxYzf8QhtMQ4Je7CX/0TYD7eIbrQZT303Ygi@QXPkN@yBNeM35OB@Hka@NbByqCZqB592H6uYjWGPwR@QrpmehA8X4ehG4oRnKhEe255PS/E2LckU0SI4p0Yg3f0udNMuIa0XUJGee69JLe4PZ@m/UaepGawB7DMSFoS1owk4iVWJNfu5F3qiylpDTY8FddjqdmVZcs3upUHGD8Iwyt6jbT3FCSgfR6hstO4XC1OP5eghPbZse5piZfdQExOgZQCtHV3XiW81SpFLicJeHTuVbp5SUIcxZp91zvldIAEPXS1@ZIwciJKbn6F164OtaAdH54YYJhQBcOiTBbNnMUGOGopP5SkcQk1W1OcLnkX19/3R4lKfzdldBA5472hTvaDSjVvSw/ws)
**Explanation:**
```
import java.util.*; // Import for 3x Stack
L->{ // Method with String-array parameter and no return
Stack<Long>m=new Stack(), // Message-queue of process 1
q=new Stack(); // Message-queue of process 0
long r[][]=new long[2][26],// Registers, starting at 26x 0
// Index 0 is process 1, index 1 is process 0
V,P,t; // Value `V`, Register-position `P`, temp `t`
++r[0][15]; // Increase 'p' in process 1 by 1
for(int c, // Current process
f=1,g=1, // Process flag-integers
d=1, // Bounds flag-integer
i=0, // Index-integer of process 0
j=0, // Index-integer of process 1
o,v,p; // Operation `o`, Value `v`, Register-position `p`
// (we use `V`/`P` as actual values, and `v`/`p`
// as indices in case we need to modify data at
// those positions)
f>-g // Loop as long as one process-flag is still 1,
&d>0;) // and the indices are within bounds:
for(c=2;c-- // Inner loop `c` in the range (2,0],
*d>0 // as long as the indices are within bounds:
; // After every iteration:
d=d>=0&d<L.length? // If `d` is within bounds:
1 // Set it as flag to 1
: // Else:
0) // Set it as flag to 0
try{f=g; // Save flag-value `g` in flag-`f`
V=P=g=1; // Reset flag-`g`, `V`, and `P` to 1
var l=L[d=c<1?j:i // Set `d` to the index of the current process
]; // Get the current String-line
var x=l.split(" "); // Split this line on spaces
o=l.charAt(1); // Set `o` to the second character of the line
l=x[x.length-1]; // Set `l` to the last value of the split line,
// which is either the third if there are three,
// or the second if there are two
v=(v=l.charAt(0))>57?// If this is a letter:
v-(int)(V=97) // Convert it to an index,
// and set `V` to something larger than 1
: // Else (it's a number instead):
new Integer(l); // Convert it from String to integer
V=V>1? // If `V` is now larger than 1:
r[c] // Get the values of the current process
[v] // and set `V` to the `v`'th value
: // Else:
v; // Set `V` to `v`
t=r[c] // Get the values of the current process
[p= // and set `t` to the `p`'th value,
// where `p` is:
x.length>2? // If the line has three parts:
(p=x[1].charAt(0))>57?
// If the second part is a letter:
p-(int)(P=97) // Convert it an index,
// and set `P` to something larger than 1
: // Else:
new Integer(x[1])
// Convert it from String to integer
: // Else:
0; // Simply set it to 0
P=P>1? // If `P` is now larger than 1:
t // Set `P` to this `t`
: // Else:
p; // Set `P` to `p`
r[c][p]= // Set the `p`'th value to:
o=='e'? // If the line is a 'set':
V // Simply set it to `V`
:o=='d'? // Else-if the line is an 'add':
t+V // Set it to `t` plus `V`
:o>116? // Else-if the line is a 'mul':
t*V // Set it to `t` multiplied by `V`
:o=='o'? // Else-if the line is a 'mod':
t%V // Set it to `t` modulo-`V`
: // Else:
t; // Keep its same value by setting to `t`
l=L[o=='g' // If the line is 'jgz': †
&P>0? // If `P` is larger than 0:
c<1? // If it's process 1:
j+=V-1 // Increase index `j` by `V` minus 1
: // Else (it's process 0):
(i+=V-1):0]; // Increase index `i` by `V` minus 1
if(o=='n') // If the line is 'snd':
(c<1? // If it's process 1:
q // Use Message-queue `q`
: // Else (it's process 0):
m // Use Message-queue `m` instead
).add(0,V); // And prepend `V` to this Message-queue
if(o<100) // If the line is 'rcv':
r[c][p]= // Set the `p`'th value to:
(c<1? // If it's process 1:
m // Use Message-queue `m`
: // Else (it's process 0):
q // Use Message-queue `q`
).pop(); // And pop and get its top value
l=L[c<1? // If it's process 1: †
j+=g // Increase index `j` by `g`
: // Else (it's process 0):
(i+=g)]; // Increase index `i` by `g`
}catch(Exception e){ // If an error occurs (which is either an
// ArrayIndexOutOfBoundsException if an `i`/`j`/
// `p`/`v` we've used for indexing is out of
// bounds, or an EmptyStackException if we tried
// `pop()` on an empty Message-queue)
g=0;}} // Set flag `g` to 0
```
*†:* `l=L[o=='g'&P>0?c<1?j+=V-1:(i+=V-1):0];` and `l=L[c<1?j+=g:(i+=g)];` may seem like an odd way to increase `j`/`i` based on the if-condition, since why do we set it to `l` and get it from `L`? But this is 3 bytes shorter than the traditional way: `if(o=='g'&P>0)if(c<1)j+=V-1;else i+=V-1;` and `if(c<1)j+=g;else i+=g;`
] |
[Question]
[
## Fluff
After taking a look at [deadfish](https://esolangs.org/wiki/Deadfish), I decided it sucked, so I came up with a new (and easier) variant of it: imnotdeadfish.
As with its predecessor, there are 4 commands and an accumulator which begins at 0:
```
+ # increment the accumulator
- # decrement the accumulator
s # square the accumulator
o # output the accumulator as an ascii char
```
The only difference between the languages (besides using + and -) is that if the accumulator ever goes out of range of 0 <= x < 256, the accumulator is taken mod 256. Ex: if the accumulator is at `255` and the command + is executed, it wraps to 0, and if, for example, it is at `0` and the command is -, the result would be 255.
An example program such as this: `++++s+so` which would output `!`
## Challenge
The problem with imnotdeadfish is that it's *too* easy, which means optimal solutions are not hard to find.
Given a string of characters, output the shortest code (which is not necessarily unique) in imnotdeadfish that prints the output. This should work for all inputs with chars between 0-255, but the testcases won't cover that.
## Examples
input => output
```
Hello, World! => +++s+s-s-o++s+o+++++++oo+++o----ss++s+++os+s-o+++++s--o-s+++s--o+++o------o-s---sos+so
test => ++s+ss+++o++s+o++s++o+o
aaaaaaaaaa => +++s--ssoooooooooo
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest program, in bytes, wins. (this is the program you write, not the resulting imnotdeadfish program, since those should be the same length)
Here is a [reference implementation](https://tio.run/##hYzBCoMwEETP5iuWQEFNI62lPRT8mBAVA5qVbDz49TbRFuxB3MMyMztvx9l3aB/LYoYRnQeaiTGl9TRMvfLooIIbY20QulMOjI2NgnxtbOEaVafZmyWm3a5VBVzwECT/H9K9FXDP4ALl88WSpt@j8gyVhyidoXkO5QGLKzs6Y32qO7fHsis0tg6/OM@WRQhBgiRJjCKsdTAKlGGIYh5MbG1nkhIlfcWvt2axH4v4AQ) of imnotdeadfish (for testing - this is not a valid submission to this challenge).
[Answer]
# JavaScript (ES6), 129 bytes
Expects an array of characters. Returns a string.
```
a=>a.map(c=>{for(k=0;c.charCodeAt(o='')^(g=x=>(o+="o+s-"[q=x&3],q)?g(x/4,n-=q-2||n-n*n,n&=255):n)(k++,n=r););r=n;O+=o},r=O='')&&O
```
[Try it online!](https://tio.run/##PVBBbsIwELznFdtIxDZxDKXlQrSgClXqjUMPPVAqWSYJlGCDHVVI0B9U6qXH9h99Dx/oE6gTqvqwHo29OzP7LF@kU3a5qRJt5tkpx5PEoRRruaEKh/vcWLrCbqqEWkg79l9uKmqQEPZEC9zhkJoYQxO7JJxucRddzfiWjQq661xzneA26R0OOtFtzXWEvX6fDTSjqzjmGi1LWWpRp5MYzSu3OKnHRtHkNM@UFwIEBzgMAJyw2aaUKqMd0Sk4KE/XBYEYAiO4r@xSFyK3Zj3@c0k1gwFQ7YfsSUwGoCGGSw4kaXDSYNfgNujXqZpBBN6fZwnjUPd1WRoEUy9PHruEN/cuz8@oylx1RndZWRoOD8aW84szJf8PCWaB8Cu8lWpBXePaaGfKTJSmoGHLQcuFHGzm3yCnUyGEm3n58wKo51md0vmM5Of7/fj54Svxwcjx640wlp5@AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
a.map(c => // for each character c in a[]:
{ for( // loop:
k = 0; // start with k = 0
c. // we'll stop as soon we've found a sequence
charCodeAt( // producing the ASCII code of c
o = '' // start each iteration with o = ''
) ^ //
( g = x => // g is a recursive function which turns x
// into a sequence of imnotdeadfish commands
( o += // append to o:
"o+s-"[ // the symbol of the command q
q = x & 3 // with q = floor(x) mod 4
], //
q //
) ? // if q is not equal to 0:
g( // do a recursive call to g:
x / 4, // divide x by 4
n -= // update n:
q - 2 || // do +1 or -1 if q is not equal to 2
n - n * n, // otherwise, update n to n * n
n &= 255 // reduce n to a byte
) // end of recursive call
: // else (q = 0):
n // stop here and return n
)(k++, n = r); // initial call to g / increment k afterwards
); // end of for
r = n; // update r to n
O += o // append o to O
}, //
r = O = '' // start with O = empty string and r zero'ish
) && O // end of map(); return O
```
[Answer]
# [Python 2 (PyPy)](http://pypy.org/), 166 bytes
```
p=0
S=''
for c in map(ord,input()):
for i in range(4**14):
d='';n=p
while i:d+='+-s'[i%4-1:i%4];n=[n,n+1,n-1,n*n][i%4]%256;i/=4
if n==c:S+=d+'o';p=c;break
print S
```
[Try it online!](https://tio.run/##PY5Ba8MwDIXP8a/QDMVpnLClZDs46L57DjuUHLLYbc0yWbgeW3595jDYA@mBPkk8XtMt0Knhldft@@YXB60B9@NmiFLKjfFJDKiUuIQIM3iCz4nLEG3tib9SeTwaATvzO4sTXV3ZVVXb5Xlh82FPyKL4@@yN1ah0c1dnf@ia1uQ@5oUz1aTbmppcFY07HA@n55feP2InCn8BQpzNoNFqFVTPOPfv0U0fgqOnBMO2R5WvbllCDW8hLvZBCpncPWWb/iV/AQ "Python 2 (PyPy) – Try It Online")
Instead of brute-forcing the entire program, we only do it in between each character (to speed it up so it doesn't take forever). We use a bitmask to search for all possible answers up to a length of 14 (which is the maximum length needed to find an answer, from my testing).
One thing to note is that the we brute-force *four* commands instead of three. The fourth command is a NOP (meaning it does nothing), which ensures that the bitmask runs through all possible lengths. The NOP is not actually included in the program.
It takes just one second to run all three test cases on TIO. Note that PyPy is used instead of CPython to speed up execution time.
[Answer]
# [Python 3](https://docs.python.org/3/), 190 bytes
```
def g(x,y):
q=[(x,"")]
for c,s in q:
if c==y:return s
for n,a in[(c+1,"+"),(c-1,"-"),(c*c,"s")]:
q+=[(n%256,s+a)]
s=[*map(ord,input())]
for x,y in zip([0]+s,s):print(end=g(x,y)+"o")
```
[Try it online!](https://tio.run/##JY7NCsMgEITPyVNYoaBxA/2hPQS89w16kByCSVohVaMGmr683bS3YXb2m/Frejp7zrkfRvJgb1h5UxazVCgp5W1ZjC4QDZEYS2Y8FWYkWsq1CUNagiURrS1iocOIYlocgQrKgekaVf1TlQYakbb9F7NAut2fLleIosOKKFX16jxzoQdj/ZIYR3eD4pyt92M8U4dWRIi88cHYxAbby/9cQR3lOd@GaXJA7i5M/e4L "Python 3 – Try It Online")
-20 bytes thanks to ophact; I was initially using a "visited" set but I forgot to add to it in the first place so it seems like it's not too necessary for efficiency, it's more the choice to BFS over brute force.
This is, by far, not the golfiest approach, but it is relatively efficient. I could golf this down a lot by brute forcing but I wanted to go for a faster approach.
[Answer]
# JavaScript (ES6), 140 bytes
```
a=>a.map(p=n=>(g=([m,o],...q)=>(p=m&255)-n.charCodeAt()?g[p]?g(...q):g(...q,g[p]=[p+1,o+'+'],[p-1,o+'-'],[p*p,o+'s']):o+'o')([p,''])).join``
```
[Try it online!](https://tio.run/##dYzNCsIwEITvPoVeTGLTgIKXQlrEi2/gIRQa@hNb0uzaFF8/phU86V5mdvabHfRL@3rqcU4dNG3oZNAy12LUSFE6mVMjqRo5lFwI8WQxQDnuT@czS52oH3q6xtplpqwwCsvC0BXLPsqXTCpMjhwSkpCSK0xXn67@gIv3pGRZVCCMKuQkrkwM0LuqCjU4D7YVFgztqIpPya21Fvj2DpNtdgu7@QHNrZ//3fR3FiK8AQ "JavaScript (Node.js) – Try It Online")
Input array of characters, output a string.
Remove the `g[p]?g(...q):` would work in theory but actually result stack overflow. :(
```
a=> // input (as array of characters)
a.map(
p= // p&255 is the value of cell, initial to 0
n=> // for each character `n`
(g= // a recursive function apply bfs for shortest code output `n`
// g is assigned each iteration, so g[p] (discussed later) is cleared
([m, // current value got
o], // code for current value
...q // queue for bfs
)=>
(p= // let `p` memorize code of previous char
m&255) // bit-wise and 255 for mod 256, works for negative numbers
-n.charCodeAt()? // the value got equals to current char?
// not equal
g[p]? // value `p` had been searched before
g(...q): // don't search it again
g(...q, // bfs with following items enqueue
g[p]= // assign g[p] to something thuthy so we won't search it again
[p+1,o+'+'], // +
[p-1,o+'-'], // -
[p*p,o+'s']): // s
o+'o' // output this char
)([p,'']) // search starts from empty code output previous value
).join`` // join codes for each char
```
---
# Python 3.9, 137 bytes
```
p=0
for n in input():
q=[[p,'']]
for p,o in q:
if chr(p:=p%256)==n:print(end=o+'o');break
q[:]+=[p+1,o+'+'],[p-1,o+'-'],[p*p,o+'s']
```
[Try it online!](https://tio.run/##LY5Bi8IwEIXv@RVjQdJuU1gVl6WSo@LNi7CHkIPWkZYtyXSMqL@@Jt0dhuGDee/N0Cu03q2@icdH2/UIR75jLSDwK07AJzZ5lmUj6U9x9QwOutR0D3kRBYM2hpSU1gpIa1I@CYbk7a7QtJxTrWm@XH8VWruauHMhR3fRvpReFpsz4@k3igdTLWpbakPlQsVdKa0yVE1cTfxBiW/SjvGfIlr@siLhs0EKsD3stsye0@0pdtxj33sFP577y0wEvAVx@q83 "Python 3.8 (pre-release) – Try It Online")
The TIO link is 139 bytes by changing the last line `q[:]` into `q[-1:]`. The code still works without the `-1` there on my computer, it only takes much longer time (timeout on TIO). And I don't know why `-1` may help the performance.
It is shorter than the mojibake like JavaScript.
---
# Python 3.8, 162 bytes
```
p=0
for n in input():
q,v=[[p,'']],[1]*256
for p,o in q:
if chr(p:=p%256)==n:print(end=o+'o');break
q[:],v[p]=q+[[p+1,o+'+'],[p-1,o+'-'],[p*p,o+'s']]*v[p],0
```
[Try it online!](https://tio.run/##LY5Pa8MwDMXv/hRaYDh/XGg3NkaGjx277TLYwfjQpioJC7aiul376TM5mxDiHX5679Et9TE8vhDPP/0wInzyGVsFiW9yAa/YlUVRzGTX6hgZAgx56ZzKSoDJXKxzZLT23riNrx@enhVkkEzM6JRdhiN0PZfUWroXoLI2tMRDSCWGg42Njrp63TPuvgWeXOvNxZG3UyPWzcYI0Gixp9WiV4uuKeuT5NYZNutZalby/2csCq8dUoLtx9uWOXIusmTM7ziO0cBX5PFwpxKektr9zy8 "Python 3.8 (pre-release) – Try It Online")
And 162 bytes version for better performance.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 187 bytes
*-12 thanks to @Ausername*
```
s=>eval('i=0;do{c=i.toString(4).padStart(Math.log2(++i)/2+1,0,o=""),(a=[...c]).reduce((r,x)=>[r+1,r+255,r*r,r,x^3||(o+=String.fromCharCode(r))][x]%256,0)}while(o!=s);a.map(d=>"+-so"[d])')
```
[Try it online!](https://tio.run/##JY3BasJAEEC/xYXiTHdd07QpgkwunnvyGFIYshuzJbphskah@u1poNfH470fnnhsJAxpM@3mluaRSj9xD@tA2d7F34aCTfGYJFxO8IF2YHdMLAm@OHW2j6cctA64zfWbyUwkpdAAU2WtbWq04t218QBi7khlJYslOi8KI69iFvj9/nhA1PQ/sK3E86FjOUTnQRDr6l6/5MWnyfB560LvIa5oxD3bMw/gqFR6M0ZVuRrXOA9LI0ELaqUQ5z8 "JavaScript (V8) – Try It Online")
**Description:**
Shameless brute-forcing. Increments a number, and converts it to base 4. It then interprets it as imnotdeadfish, and stops as soon as the result is equal to the input. Add `n` to the first `0` for infinitely large inputs. Didn't do this because it causes TIO to error.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~43~~ 34 bytes
```
‘;’;²&255
OݹÇi?ƬFiɗƝ’ḃ3ị“+-s”Up”o
```
[Try it online!](https://tio.run/##y0rNyan8//9RwwzrRw0zrQ9tUjMyNeXyP7r70M7D7Zn2x9a4ZZ6cfmwuUO7hjmbjh7u7HzXM0dYtftQwN7QASOT////fA2hEvo5CeH5RTooiAA "Jelly – Try It Online")
A full program taking a string argument and printing the resulting program to STDOUT. For each pair of characters (prepended with a null byte) progressively extends a list by applying each of the three operations, preserving intermediate values, until the second integer is found. The position of the second integer in the flattened list is then base decoded into "+-s" and appended with "o" to yield the imnotdeadfish program.
Now works for longer inputs, because this is more efficient than the previous approach.
Full explanation to follow.
[Answer]
# [R](https://www.r-project.org/), 174 bytes
```
\(x,p=paste0)p(mapply(\(y,z){l="";while(is.na(m<-match(z,y))){l=c(outer(l,c("+","-","s"),p));y=c(y+1,y-1,y^2)%%256};l[m]},c(0,(u=utf8ToInt(x))[-nchar(x)]),u),"o",collapse="")
```
[Try it online!](https://tio.run/##PY7BCsIwEER/RReEXdyKCopQe9e74EEUQkxpYZuENkGj@O01XjwMDPPeYfqxrsY6Wh1aZ/HJvvJqCGZJHjvlvST8w8QveksFUD6aVgy2w8Iq7PZFp4Ju8MWJ6CdodDGYHoU1whwYipwBiD1RmTJO8xWnIue2ptlsvdl@Srl010/2l4yxiqHendzRBnwSXQqrG9XneiWOxOCAtRNRfjD5C401wsGIOJ6cXS/3aZ6@ "R – Try It Online")
A function that takes a string and returns the iamnotdeadfish program as a string
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 77 bytes
```
≔⁰θFES℅ι«≔E²⁵⁶⎇⁼κθω#ηF¹⁴FΦLη¬⁼#§ηλF³«≔§⟦⊕λ⊖λ×λλ⟧μκ¿⁼#§ηκ§≔ηκ⁺§ηλ§+-sμ»§ηιo≔ιθ
```
[Try it online!](https://tio.run/##dVE7a8MwEJ7tX3FVlxNVoO@lU6AtNfQRaCBD6SBsxRY@y4kk90HJb3clO6HJUE13p@91Ul5Jm7eS@n7qnC4NngpY85t02VrAJ7nCzKw6/@qtNiVyAS@20EYSas45/KTJlhWR51fXAubKGmm/8W7dSXJYRzUBnwLYMeOhqoJ2MoifXXIYintNXll8VKb0FVYB9Nz6nUCgCZj6zBTqCysBxOMZiRdDgl2EHegtM7lVjTJeFUhB7VYd9nPdKIcUtd4FNGFSx1CJXsJ/rnX0HH32pwJm1Dk8iPfHYycTx6JBVN@kySy8od8H6@FmHLOWxWa7ix4/YdP3D4qoFbBoLRVHaT/5oF8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰θ
```
Initialise the accumulator to zero.
```
FES℅ι«
```
Loop over the code points of the input.
```
≔E²⁵⁶⎇⁼κθω#η
```
Create an array of the command strings found so far (the empty string for the current accumulator and a marker `#` for all of the other values).
```
F¹⁴
```
Repeat enough times to ensure all possible values are covered. (I could save a byte by looping 1,000 times but that would make the code unusable on TIO. On the other hand repeating until we found the value we wanted would be faster still. [Try it online!](https://tio.run/##dVE7T8MwEJ6TX3GY5SxcCYFg6VQJEJF4VKISA2KIEje2crFbx6Eg1N8e7LYBMnTzff5ePhcqd4XNqe9nbasrg@cC1nyaLq0DfMxXmJlV51@806ZCLuDZldrkhJpzDt9pclBF5sXVtYCFdCZ3X3i77nJqsY5uAjYC2Cnj4aSCd7JRmiQMnHAjYOYzU8pPVAJ21rv8O01eOnyQpvIKVZA/WX9MRpz/Ci933YZyA@ktM4WTjTRelkjB7UaO54VuZIsUvd4FNAGpY91EL4@WrWPmPuc/KmBOXYujen86djZpWQyI7ts0mYftehyvYDrAzLI4HN6i99@z7ft7SWQFvFpH5UnaTz7oBw "Charcoal – Try It Online"))
```
FΦLη¬⁼#§ηλ
```
Loop over the values of the command strings found so far.
```
F³«
```
Loop over the three possible commands.
```
≔§⟦⊕λ⊖λ×λλ⟧μκ
```
Get the result of applying the command to the current value. No need to reduce modulo 256 here because Charcoal's array indexing is automatically cyclic.
```
¿⁼#§ηκ
```
If there is no command string for this value yet, then...
```
§≔ηκ⁺§ηλ§+-sμ
```
... save the new command string.
```
»§ηιo
```
Output the desired command string.
```
≔ιθ
```
Update the accumulator.
I also wrote a program to enumerate all possible snippets for all values. This version uses the results to solve the original problem in near-constant time.
```
≔E²⁵⁶E²⁵⁶⎇⁼ιλω#θ≔E²⁵⁶⟦⟦+﹪⊕κ²⁵⁶⟧⟦-﹪⊖κ²⁵⁶⟧⟧ηF²⁵⁶«F¬⁼ι﹪×ιι²⁵⁶⊞§ηι⟦s﹪×ιι²⁵⁶⟧F§ηι§≔§θι§κ¹§κ⁰»≔EηιζWΦθ№κ#FEι⌕κω«≔⟦⟧εF§ζκF§η§λ¹F⁼#§§θκ§μ¹«§≔§θκ§μ¹⁺§λ⁰§μ⁰⊞ε⟦⁺§λ⁰§μ⁰§μ¹⟧»¿ε§≔ζκε»≔⁰δFS«≔℅ιι§§θδιo≔ιδ
```
[Try it online!](https://tio.run/##hVLNT8IwFD@zv6LWSxtLgiZ68URUIgeVRBIPyw4LLaxZaaHrRDH87fN1H7CBxNP62t/He7@3WRLbmYlVUQyzTC40eYlX5Ob2jqH9YSqsju03eVrnscqIZEhRhjYM4UtMKRzX9D44ZochvsIgYniuDBnrmRVLoZ3gJAUGQGgEINw/YB7FCSaK4JuA@txY5HUp@gl6ZfFqXKuhWmIql6KsZe1BKZrkWUKGbqy5@CJJ9RTiDJ8nRWBYmXRoFFUzNpfNd10xmzJl6LpbDigI7toJ1W1s4X6TSCUQGUnlhPVaDybXztOqdFHZiCdBhyOpuX/a@AdIopYMIUpx0vSWobThtwZpjsr32bzXSYLlAdCaL20NtKx5YN87G8gJgaGJyjPSMh90IRCSn6BXrkvAiv7HH1mUa9sFPTlHRBwvy4dRhbRfxIAh3vxaY73K3buzUi9IJ9o3y6WOFfHrkt5gAhhH/hiZl4gDBBvsi1pHVma7ongWShmGPoxV/CIo@p/qFw "Charcoal – Try It Online") Link is to verbose version of code.
Using that code I was able to find some trivia e.g. the longest snippets are from `0` or `128` to `180` or `181`; these take 14 commands (not including the trailing `o`). For printable ASCII there are a number of equally longest snippets, but the most interesting worst case is from space to comma where it's not possible to improve on simply incrementing 12 times.
[Answer]
# [Julia 0.5](http://julialang.org/), 119 bytes
```
^(s,l=0,L=[""])=s==""?s:any((i=l.==(b=Int[s[1]]);))?L[i][]"o"s[2:end]^b:^(s,[l+1;l+255;l.*l]%256,vec(L.*["+" "-" "s"]))
```
[Try it online!](https://tio.run/##XY0xC4MwFIT3/gr7oJBoKiqkg/JwbcG9QxpBq0PKIxaTFvrrU@1UvOOW7@Du8SLTyRBa5gRhJhpUAJqjQwSoXdnZD2MGKUVkPV6sV07lWvOK87pRRisNEzhVlKMddNuX646iJK8oKaSsKI1JHwp5Eu/xzpo0VpBABMclbrnh4Tkb68mylsF5JJpEdJ1mGvbA@e6v86PzG9T9tIG3bPUCwxc "Julia 0.5 – Try It Online")
##### ungolfed:
```
function ^(s,l=0,L=[""])
s == "" && return ""
b = Int[s[1]]
i = l .== b
if any(i)
return L[i][1] * "o" * ^(s[2:end], b)
else
return ^(s, [l.+1; l.+255; l.*l].%256, vec(L.*["+" "-" "s"]))
end
end
```
[Try it online!](https://tio.run/##XU/BasMwDL33KzTBipd6oQmkhw7fN8h9B8@FpHHBQygjdsb29ZmS9DDyjCT09PRsf44UmuJnmm4jX1PoGS4qajJHXRuL6J52IIhgDCDCfg@DT@PA0iyDFgy8cbLRFs4tTBCGIBd9u/Y3aPhXhdVoxt2htsHJFmSAPUqWe2159tw5De2q9hT9dm1@HljKD8ULSC6raq4ZufyxrE4avv1V1Xlm8YCAzxJRPnG3424nMX0NgROxuih89US9hvd@oO4BRfdvlnxMG6pZsCE/jvMRcvoD "Julia 1.0 – Try It Online")
] |
[Question]
[
I have a hardware that has a 32-bit input register. The register has the following characteristics:
* The 32-bit register consists of eight 4-bit fields.
* Each 4-bit field holds a value in **signed-magnitude**; it can hold an integer between -7 and +7 inclusive, including -0 and +0 (signed zeroes).
For example, the hexadecimal value `0xABCD1234` represents the field values `[-2, -3, -4, -5, +1, +2, +3, +4]`. In fact, one hex digit represents one 4-bit value with the following mapping:
```
Hex | Input value
---------------------
0 ~ 7 | +0 ~ +7
8 ~ F | -0 ~ -7
```
In order to operate this hardware, I figured that the most natural inputs would be 8 consecutive increasing values, treating -0 and +0 as distinct. So the input values will be one of the following:
```
field values for 8 fields => 32-bit register value
[-7, -6, -5, -4, -3, -2, -1, -0] => 0xFEDCBA98 (offset -4)
[-6, -5, -4, -3, -2, -1, -0, +0] => 0xEDCBA980 (offset -3)
...
[-3, -2, -1, -0, +0, +1, +2, +3] => 0xBA980123 (balanced, offset 0)
...
[+0, +1, +2, +3, +4, +5, +6, +7] => 0x01234567 (offset +4)
```
I define the input `0xBA980123` as **balanced**, and the other inputs have an **offset** from the balanced input. The balanced input itself has offset 0.
## Task
Given the offset, output the desired value for the input register for my hardware as described above.
## Input and output
The input (offset) is an integer between -4 and 4 inclusive. You can take it as a string, optionally with explicit sign (e.g. `+4`).
You can output the result value as an integer or a string. If you choose to output as a string (either returning or printing), you can use base 2, 8, 10 or 16. In case of hexadecimal, mixing upper- and lowercase letters are allowed. Base prefixes (e.g. `0b` or `0x`), leading zeros, and leading/trailing whitespaces are also allowed.
You may use signed 32-bit values for output instead (imagine the values being used in a C program); in that case, the output values will be subtracted by `2^32`, except for the input `+4`.
## Scoring
The standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## All test cases
There are only nine possible inputs, so here is the list of all input/output values your program/function needs to support.
```
input => output hex | decimal | signed 32bit
-4 => 0xFEDCBA98 | 4275878552 | -19088744
-3 => 0xEDCBA980 | 3989547392 | -305419904
-2 => 0xDCBA9801 | 3703216129 | -591751167
-1 => 0xCBA98012 | 3416883218 | -878084078
0 => 0xBA980123 | 3130523939 | -1164443357
1 => 0xA9801234 | 2843742772 | -1451224524
2 => 0x98012345 | 2550211397 | -1744755899
3 => 0x80123456 | 2148676694 | -2146290602
4 => 0x01234567 | 19088743 | 19088743
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 30 bytes
Simple and clean. Outputs a substring of the larger with the right offset because it seemed cheaper than any method I could think of that calculated it properly.
```
->o{"FEDCBA9801234567"[o+4,8]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6/WsnN1cXZydHSwsDQyNjE1MxcKTpf20THIrb2v4auiZ6eiaZeamJyRnVNZk1BaUmxgpKqUYqCgoJydVp0ZmytkoKqQmbtfwA "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
12_r8Ḋ;8Ḷ¤ḣ8ḅ⁴
```
A monadic Link accepting an integer which yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8/9/QKL7I4uGOLmsgse3Qkoc7FgMZrY8at/z//98AAA "Jelly – Try It Online")**
### How?
```
12_r8Ḋ;8Ḷ¤ḣ8ḅ⁴ - Link: integer N e.g. 4 or -2
12 - literal twelve 12 12
_ - subtract N 8 14
8 - literal eight 8 8
r - inclusive range [8] [14,13,12,11,10,9,8]
Ḋ - dequeue [] [13,12,11,10,9,8]
¤ - nilad followed by link(s) as a nilad:
8 - literal eight = 8
Ḷ - lowered range = [0..7]
; - concatenate [0,1,2,3,4,5,6,7] [13,12,11,10,9,8,0,1,2,3,4,5,6,7]
8 - literal eight 8 8
ḣ - head to index [0,1,2,3,4,5,6,7] [13,12,11,10,9,8,0,1]
⁴ - literal sixteen 16 16
ḅ - to integer from base 3130523939 3703216129
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 38 bytes
```
n=>~(p=19088743)*16**(n+4)|p*16**(n-4)
```
[Try it online!](https://tio.run/##LcZNCoMwEAbQvaf4ljNqxNBglTa5RE8gVsUikxClm/5cPUXo6r1H/@y3IS5hV@LvY5psEuu@FKzu6rY9mxPnuslzksLwO/yvDKfJR5DAQpkLBFeLw6JgvDJg8LL5daxWP5OUmEi4BB3AOYeaq93f9rjITLphzj7pBw "JavaScript (Node.js) – Try It Online")
In two's complement representation, `0xfedcba98` is "not `0x01234567` (19088743)". We first shift `0xfedcba98` \$ 4(n+4) \$ bits left, and shift `0x01234567` \$ 4(4-n) \$ bits right. Then use bit or to add them up.
JavaScript do not support `n << 32`, so we use `n * 2 ** 32` instead. And bitwise or in JavaScript automatically convert operand to int32. The two float value trimed to int32 and calculated the result.
---
Another not quite interesting answer:
# [JavaScript (Node.js)](https://nodejs.org), 35 bytes
```
n=>'FEDCBA9801234567'.substr(4+n,8)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k7dzdXF2cnR0sLA0MjYxNTMXF2vuDSpuKRIw0Q7T8dC839afpGCRp6CrYKuibVCnoKNrQKI1tbWVKjmUlBIzs8rzs9J1cvJT9fI01FI08jT1OSq/Q8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~35~~ 32 bytes
```
f(n){n=0xFEDCBA99l*~0u>>16-4*n;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs/WoMLN1cXZydHSMkerzqDUzs7QTNdEK8@69r9yZl5yTmlKqoJNcUlKZr5ehh1XZl6JQm5iZp6GpkI1F2dafpGCBkgo01bXxFoh08YWRGpra3JxchYUASXSNJRUjVIUbO0UVA0sImLylHQUMnUU0jQyNTWtuWr/AwA "C (gcc) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~60~~ ~~56~~ ~~52~~ 37 bytes
```
lambda n:"FEDCBA9801234567"[4+n:12+n]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPSsnN1cXZydHSwsDQyNjE1MxcKdpEO8/K0Eg7L/Z/QVFmXolGmoauiaYmF5xjjMwxQuYYInEMkNjI4sgakE0CWvEfAA "Python 3 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~23~~ 22 bytes (SBCS)
```
8↑('FEDCBA98',⎕D)↓⍨4+⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3@JR20QNdTdXF2cnR0sLdZ1HfVNdNB@1TX7Uu8JE@1HXov9pj9omPOrtA4p7@j/qaj603hioA8gLDnIGkiEensH/gQLVj3q36qQBidpDKw6tN9V@1LvZEgA "APL (Dyalog Unicode) – Try It Online")
First time trying to use APL for golf. Any suggestions for improvement would be greatly appreciated. I put s← in the code field for testing purposes; is there a better way to do that?
(Edit: Removed the s← and saved a byte thanks to Bubbler)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
Nθ⭆…⁻θ⁴⁺θ⁴⎇‹ι⁰⍘⁻⁷ιφι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0QjuARIpfsmFmgEJealp2r4ZuaVFmsU6iiYaOooBOTA2EBOSGpRXmJRpYZPanGxRqaOggFQzCmxOBViAlSjuY5CJlA8TRNEa2pa//9v9F@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Outputs 8 hex digits. Explanation:
```
Nθ Input the offset
⭆… Map and join over range
⁻θ⁴ From offset - 4 (inclusive)
⁺θ⁴ To offset + 4 (exclusive)
⎇‹ι⁰ If current value is negative
⍘⁻⁷ιφ Then subtract from 7 and convert to hex
ι Else use directly as digit
Implicitly print
```
[Answer]
# [Haskell](https://www.haskell.org/), 38 bytes
```
f n=take 8$drop(n+4)"FDECBA9801234567"
```
[Try it online!](https://tio.run/##FYjPC4IwHEfv/hUfhgdFlH6sssCgMk/dOlbEYori3HfMRX/@0sPj8V4rxr5WyneDIetQCieyipQUH1Ujasi@4yAYRKdRYC48Up5l/IUQT430CEkBYL7u7uxNT3ds6QeNJAE7gM1uoP1E4URfIw@lJRPphMesKq@X82mfL5arNd9sd8z7Pw "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes
```
4Ø4Ÿα7݇hJ
```
[Try it online!](https://tio.run/##AR4A4f9vc2FiaWX//zTDmDTFuM6xN8Odw4LigKFoSv//LTM "05AB1E – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~12~~ 11 bytes
```
11⁻7N8…+8<h
```
[Try it online!](https://tio.run/##S0/MTPz/39DwUeNucz@LRw3LtC1sMv7/NwAA "Gaia – Try It Online")
[Test suite](https://tio.run/##S0/MTPz/39DwUeNucz@LRw3LtC1sMv5XP2qfWFj7qKnzv64Jl64xl64Rl64hlwGXIZcRlzGXCQA)
```
11⁻ 11 - input
7N Downward range from result to 7 (excluding 7, empty list if first number is 7)
8…+ Append the range 0-7 (inclusive)
8< First 8 numbers
h Convert from hexadecimal
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 35
* 1 byte saved thanks to @79037662.
```
s=FEDCBA9801234567
echo ${s:$1+4:8}
```
[Try it online!](https://tio.run/##S0oszvifll@koKFRklpckpxYnKpgq6BrYq0A59rYIvG0tTU1rRVS8rkKijLzStIUlFSNihV07RSUFFRgSriKU0sUdHXhWv4X27q5ujg7OVpaGBgaGZuYmplzpSZn5CuoVBdbqRhqm1hZ1P5Pyc9L/Q8A "Bash – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~28~~ 26 bytes
```
{:16[11-$_...^7,|^($_+4)]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2srQLNrQUFclXk9PL85cpyZOQyVe20QztvZ/cWKlQhqQp6mQll@koGuip2fyHwA "Perl 6 – Try It Online")
### Explanation
```
{ } # Anonymous block
11-$_...^7 # Range 11-n down to 7 exclusive
,|^($_+4) # Followed by range 0 to n+4 exclusive
:16[ ] # Convert from base 16
```
[Answer]
# [PHP](https://php.net/), 38 bytes
```
<?=substr(FEDCBA9801234567,4+$argn,8);
```
[Try it online!](https://tio.run/##K8go@P/fxt62uDSpuKRIw83VxdnJ0dLCwNDI2MTUzFzHRFslsSg9T8dC0/p/anJGvoJSTJ6S9X9dEy5dYy5dIy5dQy4DLkMuIy5jLpN/@QUlmfl5xf913QA "PHP – Try It Online")
[Answer]
# [Wren](https://github.com/munificent/wren), 40 bytes
```
Fn.new{|a|"FEDCBA9801234567"[a+4..a+11]}
```
[Try it online!](https://tio.run/##Ky9KzftfllikkFaal6xg@98tTy8vtby6JrFGyc3VxdnJ0dLCwNDI2MTUzFwpOlHbRE8vUdvQMLb2f3BlcUlqrl55UWZJqgZIs15yYk6Ohomm5n8A)
Simply a port of most other answers.
# [Wren](https://github.com/munificent/wren), ~~70~~ 67 bytes
Horribly long answer; outputs to STDOUT.
```
Fn.new{|a|
for(i in a..a+7)System.write("4567FDECBA980123"[i%16])
}
```
[Try it online!](https://tio.run/##Ky9KzftfllikkFaal6xg@98tTy8vtby6JrGGKy2/SCNTITNPIVFPL1HbXDO4srgkNVevvCizJFVDycTUzNzNxdXZydHSwsDQyFgpOlPV0CxWk6v2fzDILL3kxJwcDRPN/wA)
## Explanation
```
Fn.new{ // New anonymous function
|a| // with parameter a
// newline because this is
// not an expression
for(i in a..a+7) // For every item in the range
// from a to a+7
// (Select 8 items in the string)
System.write("4567FDECBA980123" // Output the string
[i%16] // with the index of i modulo'd by 16.
// Moduloing maps the items in
// the iteration back to the start
// of the string.
) // Pretty self-explanatory.
} // no need to explain this
```
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 19 bytes (SBCS)
```
7Ï89AFɧ(¿4+|")^(8|_
```
[Try it online!](https://tio.run/##y05N///f/HC/haWj28nlGof2m2jXKGnGaVjUxP//bwIA "Keg – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes
```
(8':"FEDCBA98",/$!8)4+
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs9KwULdScnN1cXZytLRQ0tFXUbTQNNHm4tLWyLROU8+00jVR0DVW0DVS0DVUMFAwVDBSMFYw0QQASicK6A==)
* `"FEDCBA98",/$!8` is shorthand for `"FEDCBA9801234567"` (sets up a `raze` seeded with `"FEDCBA98"`, run over a list of strings each containing one digit from 0..7)
* `(8':...)` take 8-length sliding windows of the generated string (creates a list of 9 items)
* `(...)4+` index into that list using the (implicitly) provided index, offsetting by +4 so `-4 => 0`, `-3 => 1`, ..., `4 => 8`
[Answer]
# JavaScript (ES6), 42 bytes
```
f=(o,n=8)=>n&&f(o-1,n-1)*16+(o<-3?4-o:o+3)
```
[Try it online!](https://tio.run/##TcpNDoIwEEDhvaeYFcxYSqwQQpTiIThBw18wZIaUxo3x7FVXunlv893dw@29X7agWYYxxsmiZGxrsi0nyYSiTcba0NFUCqXRxa3UchFVUJzEI4MFXV6BobHwvVIEzwNAL7zLOuarzMh5kC74hWekfHNDF5wPeCYFKej2EwUTMv2Uqf5cnUF6SokOr/gG "JavaScript (Node.js) – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 38 bytes
```
x=>"FEDCBA9801234567".Substring(x+4,8)
```
Each valid output is just a rotation of the string `FEDCBA9801234567`
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXolNcUpSZl26XZvu/wtZOyc3VxdnJ0dLCwNDI2MTUzFxJL7g0CaJEo0LbRMdC8781V1p@kQZQq0Kmra6JdaaNqXWmtrZmeFFmSapPZl6qhpJBhZJ2mkampqb1fyXumDxOjhgDRiZmJQA "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
## Introduction
In this challenge, your task is to simulate a certain type of elimination game.
In the game, the participants stand in a circle, and everyone is holding an integer.
On each round of the game, every participant points at the person `n` steps away, if `n` is the number they are holding. If `n` is positive, they count to their right, if `n` is negative, they count to their left, and if `n` is zero, they point at themselves.
Every participant who has someone pointing at them is eliminated, and leaves the circle; this ends the round.
The rounds continue until there are no participants left.
## Input
Your input is a non-empty list of integers, in any reasonable format.
It represents the numbers that the participants of the game are holding.
## Output
Your output is the number of rounds it takes until the game ends.
## Example
Consider the input list `[3,1,-2,0,8]`.
On the first round, the following happens:
* The person holding `3` points right at the person holding `0`.
* The person holding `1` points right at the person holding `-2`.
* The person holding `-2` points left at the person holding `3`.
* The person holding `0` points at themself.
* The person holding `8` points right at the person holding `-2` (the list represents a circle, so it wraps around at the ends).
This means that `0`, `-2` and `3` are eliminated, so the second round is done with the list `[1,8]`.
Here, `1` points at `8`, and `8` points at themself, so `8` is eliminated.
The third round is done with the list `[1]`, where `1` simply points at themself and is eliminated.
It took three rounds to eliminate all participants, so the correct output is `3`.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
## Test cases
```
[3] -> 1
[0,0,0] -> 1
[-2,-1,0,1,2,3,4,5,6,7] -> 2
[5,5,5,6,6,6] -> 2
[3,-7,-13,18,-10,8] -> 2
[-7,5,1,-5,-13,-10,9] -> 2
[4,20,19,16,8,-9,-14,-2,17,7,2,-2,10,0,18,-5,-5,20] -> 3
[11,2,7,-6,-15,-8,15,-12,-2,-8,-17,6,-6,-5,0,-20,-2,11,1] -> 4
[2,-12,-11,7,-16,9,15,-10,7,3,-17,18,6,6,13,0,18,10,-7,-1] -> 3
[18,-18,-16,-2,-19,1,-9,-18,2,1,6,-15,12,3,-10,8,-3,7,-4,-11,5,-15,17,17,-20,11,-13,9,15] -> 6
```
[Answer]
# Matlab, ~~91~~ 77 bytes
```
function k=f(a);k=0;while a*0+1;l=numel(a);a(mod((1:l)+a-1,l)+1)=[];k=k+1;end
```
Old version:
```
function k=f(a);for k=1:numel(a);a(mod((1:l)+a-1,l)+1)=[];l=numel(a);if l==0;break;end;end
```
This is a challenge where matlab shines, the heart of this code is the deletion of the array entries: `a(mod((1:l)+a-1,l)+1)=[]` which is quite elegant I think.
[Answer]
# Pyth, 15 bytes
```
f!=.DQ.e%+bklQQ
```
[Test suite thanks to kirby](https://pyth.herokuapp.com/?code=f%21%3D.DQ.e%25%2BbklQQ&input=%5B3%2C1%2C-2%2C0%2C8%5D&test_suite=1&test_suite_input=%5B3%5D%0A%5B0%2C0%2C0%5D%0A%5B-2%2C-1%2C0%2C1%2C2%2C3%2C4%2C5%2C6%2C7%5D%0A%5B5%2C5%2C5%2C6%2C6%2C6%5D%0A%5B3%2C-7%2C-13%2C18%2C-10%2C8%5D%0A%5B-7%2C5%2C1%2C-5%2C-13%2C-10%2C9%5D%0A%5B4%2C20%2C19%2C16%2C8%2C-9%2C-14%2C-2%2C17%2C7%2C2%2C-2%2C10%2C0%2C18%2C-5%2C-5%2C20%5D%0A%5B11%2C2%2C7%2C-6%2C-15%2C-8%2C15%2C-12%2C-2%2C-8%2C-17%2C6%2C-6%2C-5%2C0%2C-20%2C-2%2C11%2C1%5D%0A%5B2%2C-12%2C-11%2C7%2C-16%2C9%2C15%2C-10%2C7%2C3%2C-17%2C18%2C6%2C6%2C13%2C0%2C18%2C10%2C-7%2C-1%5D%0A%5B18%2C-18%2C-16%2C-2%2C-19%2C1%2C-9%2C-18%2C2%2C1%2C6%2C-15%2C12%2C3%2C-10%2C8%2C-3%2C7%2C-4%2C-11%2C5%2C-15%2C17%2C17%2C-20%2C11%2C-13%2C9%2C15%5D&debug=0)
Uses the same iteration mechanism as @orlp, but detects the number of iterations using `f`, the "Repeat until falsy" function, to detect the `[]` once we're done.
[Answer]
# CJam, 21 bytes
```
q~{__ee{~+0t}/0-}h],(
```
[Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B%22-%3E%22%2F0%3D'%2C%2FS*%3AQ%3B%0A%0AQ~%7B__ee%7B~%2B0t%7D%2F0-%7Dh%5D%2C(%0A%0A%5DoNo%7D%2F&input=%5B3%5D%20-%3E%201%0A%5B0%2C0%2C0%5D%20-%3E%201%0A%5B-2%2C-1%2C0%2C1%2C2%2C3%2C4%2C5%2C6%2C7%5D%20-%3E%202%0A%5B5%2C5%2C5%2C6%2C6%2C6%5D%20-%3E%202%0A%5B3%2C-7%2C-13%2C18%2C-10%2C8%5D%20-%3E%202%0A%5B-7%2C5%2C1%2C-5%2C-13%2C-10%2C9%5D%20-%3E%202%0A%5B4%2C20%2C19%2C16%2C8%2C-9%2C-14%2C-2%2C17%2C7%2C2%2C-2%2C10%2C0%2C18%2C-5%2C-5%2C20%5D%20-%3E%203%0A%5B11%2C2%2C7%2C-6%2C-15%2C-8%2C15%2C-12%2C-2%2C-8%2C-17%2C6%2C-6%2C-5%2C0%2C-20%2C-2%2C11%2C1%5D%20-%3E%204%0A%5B2%2C-12%2C-11%2C7%2C-16%2C9%2C15%2C-10%2C7%2C3%2C-17%2C18%2C6%2C6%2C13%2C0%2C18%2C10%2C-7%2C-1%5D%20-%3E%203%0A%5B18%2C-18%2C-16%2C-2%2C-19%2C1%2C-9%2C-18%2C2%2C1%2C6%2C-15%2C12%2C3%2C-10%2C8%2C-3%2C7%2C-4%2C-11%2C5%2C-15%2C17%2C17%2C-20%2C11%2C-13%2C9%2C15%5D%20-%3E%206)
Takes input as a CJam style list, but the test suite takes care of the conversion from the format in the challenge.
## Explanation
```
q~ e# Read and evaluate the input.
{ e# While the array is non-empty...
_ e# Copy the array. The original is left on the stack so that we can use the
e# stack depth to count the number of iterations later.
_ee e# Make another copy and enumerate it, which means that each element is replaced
e# by a pair containing the element and its index in the array.
{ e# For each such pair...
~+ e# Add the value to the index, giving the index it points at.
0t e# Set the value in the original array at the pointed-at index to 0.
e# This works without giving false positives because all 0s point to themselves.
}/
0- e# Remove all 0s from the array.
}h
],( e# Wrap the stack in an array, get its length and decrement it to determine how
e# many iterations this process took.
```
[Answer]
# C#, ~~251~~ ~~219~~ ~~211~~ ~~197~~ 193 bytes
The most ungolfable non-esoteric language strikes again.
```
using System.Linq;class X{static void Main(string[]a){int i=0,c;for(;(c=a.Length)>0;i++)a=a.Where((e,x)=>!a.Where((f,y)=>((int.Parse(f)+y)%c+c)%c==x).Any()).ToArray();System.Console.Write(i);}}
```
This program expects the input sequence as command-line arguments. For example, to input the list `[5,5,5,6,6,6]`, call it with command-line arguments `5 5 5 6 6 6`.
Thanks to Martin Büttner for some tips.
Golfed it to **197** by realizing that I can reuse the `args` array even though it’s an array of strings. I only need to parse them into an integer in one place.
Golfed to **193** by realizing that `.Where(...==x).Any()` is shorter than `.Select(...).Contains(x)`.
## Ungolfed
```
using System.Linq;
class X
{
static void Main(string[] args)
{
var iterations = 0, count;
// In the golfed version, this is a `for` loop instead.
while ((count = args.Length) > 0)
{
// Create a new args array containing the items to be kept.
args = args.Where((item, index) =>
{
// Should the item at index `index` be deleted?
var deleteThisIndex = args.Where((item2, index2) =>
// Modulo that works with negative numbers...
((int.Parse(item2) + index2) % count + count) % count
== index);
return !deleteThisIndex.Any();
}).ToArray();
iterations++;
}
System.Console.Write(iterations);
}
}
```
[Answer]
# Pyth, 21 bytes
```
[[email protected]](/cdn-cgi/l/email-protection)%+kblNNQ
```
[Live demo with test cases.](https://pyth.herokuapp.com/?code=lt.u%40LN-UlN.e%25%2BkblNNQ&input=%5B3%2C1%2C-2%2C0%2C8%5D&test_suite=1&test_suite_input=%5B3%5D%0A%5B0%2C0%2C0%5D%0A%5B-2%2C-1%2C0%2C1%2C2%2C3%2C4%2C5%2C6%2C7%5D%0A%5B5%2C5%2C5%2C6%2C6%2C6%5D%0A%5B3%2C-7%2C-13%2C18%2C-10%2C8%5D%0A%5B-7%2C5%2C1%2C-5%2C-13%2C-10%2C9%5D%0A%5B4%2C20%2C19%2C16%2C8%2C-9%2C-14%2C-2%2C17%2C7%2C2%2C-2%2C10%2C0%2C18%2C-5%2C-5%2C20%5D%0A%5B11%2C2%2C7%2C-6%2C-15%2C-8%2C15%2C-12%2C-2%2C-8%2C-17%2C6%2C-6%2C-5%2C0%2C-20%2C-2%2C11%2C1%5D%0A%5B2%2C-12%2C-11%2C7%2C-16%2C9%2C15%2C-10%2C7%2C3%2C-17%2C18%2C6%2C6%2C13%2C0%2C18%2C10%2C-7%2C-1%5D%0A%5B18%2C-18%2C-16%2C-2%2C-19%2C1%2C-9%2C-18%2C2%2C1%2C6%2C-15%2C12%2C3%2C-10%2C8%2C-3%2C7%2C-4%2C-11%2C5%2C-15%2C17%2C17%2C-20%2C11%2C-13%2C9%2C15%5D&debug=1)
[Answer]
# R, 105 bytes
### code
```
l=scan();o=c();z=0;while((n=length(l))>0){for(i in 1:n)o=c(o,(i+l[i]-1)%%n+1);l=l[-o];o=c();z=z+1};cat(z)
```
### ungolfed
```
l <- scan() # get input as a 'l' vector from user
o <- c() # create a empty vector
z=0 # create a counter starting at 0
while((n=length(l))>0){ # while the length of the input is more than 0
for(i in 1:n){ # iterate through the vector
o=c(o,(i+l[i]-1)%%n+1) # add the index that will be deleted to the 'o' vector
}
l=l[-o] # remove the 'o' vector indexes from 'l'
o=c() # empty 'o'
z=z+1 # add 1 to counter
}
cat(z) # print the counter
```
[Answer]
# Pyth, 17 bytes
```
tl.u.DN.e%+kblNNQ
```
Coincidentally very similar to kirbyfan's answer.
[Answer]
# Mathematica, 71 bytes
```
Length@FixedPointList[#~Delete~Mod[Plus~MapIndexed~#,Length@#,1]&,#]-2&
```
[Answer]
## STATA, 146 bytes
```
inf a using a.
gl b=0
qui while _N>0{
g q$b=0
g c$b=mod(_n+a-1,_N)+1
forv y=1/`=_N'{
replace q$b=1 if _n==c$b[`y']
}
drop if q$b
gl b=$b+1
}
di $b
```
Uses the paid version of STATA. Assumes the input is in a newline separated file called `a.`. Limited to situations where no more than 1023 rounds are required due to a maximum number of variables allowed (can be fixed at the cost of 10 bytes). It reads the data and runs a loop until there are no more observations. In each iteration, make a variable with the value of the index it points to. For each observation, if another observation points to it, set an indicator to drop the variable. Then drop all observations with that indicator and increment the counter. After the loop, print the counter.
[Answer]
# Ruby, ~~78~~ 74 bytes
```
f=->a{b,i=[],0;(a.map{|e|b<<a[(e+i)%a.size]};a-=b;i+=1)while a.size>0;p i}
```
[Answer]
# awk, 66 bytes
```
{for(;n=split($0=$0,a);++r)for(i in a)$((i+a[i]%n+n-1)%n+1)=X}$0=r
```
Simply uses `mod length array` to keep it inside the array. In the input the numbers need to be separated by spaces.
## Usage example
```
echo "-2 -1 0 1 2 3 4 5 6 7" | awk '{for(;n=split($0=$0,a);++r)for(i in a)$((i+a[i]%n+n-1)%n+1)=X}$0=r'
```
Here's all the input examples in the appropriate format
```
3
0 0 0
-2 -1 0 1 2 3 4 5 6 7
5 5 5 6 6 6
3 -7 -13 18 -10 8
-7 5 1 -5 -13 -10 9
4 20 19 16 8 -9 -14 -2 17 7 2 -2 10 0 18 -5 -5 20
11 2 7 -6 -15 -8 15 -12 -2 -8 -17 6 -6 -5 0 -20 -2 11 1
2 -12 -11 7 -16 9 15 -10 7 3 -17 18 6 6 13 0 18 10 -7 -1
18 -18 -16 -2 -19 1 -9 -18 2 1 6 -15 12 3 -10 8 -3 7 -4 -11 5 -15 17 17 -20 11 -13 9 15
```
[Answer]
# Python 2, 122 bytes
```
def f(l):
if not l:return 0
L=len(l);x=[1]*L
for i in range(L):x[(i+l[i])%L]=0
return 1+e([v for i,v in zip(x,l)if i])
```
] |
[Question]
[
*I found another sequence not yet in the OEIS*
The binary expansion sequence is defines as follows, assuming 0 indexing:
* The even numbers of the sequence are how often 0 has appeared in the binary expansion of all previous items in the sequence
* The odd elements are the same, but for 1s.
If you choose to 1-index, reverse "even" and "odd" in the description above to get the same sequence.
Leave at least one digit in the binary expansion.
Thus the first terms are:
* 0, because this is even, we count the numbers of 0s. There are none
* 0, because this is odd, we count the 1s. There are none
* 2, because this is even, we count the 0s, there has been 2 zeros
* 1 next, the number 2 had 1 1
* 3, two zeros from the first 2 terms, 1 from 2
* 4, 1 from 2, 1 from 1, 2 from 3
First 200 terms:
```
0
0
2
1
3
4
5
7
6
12
9
16
15
21
17
26
22
32
29
37
33
42
40
47
45
56
50
62
54
71
59
80
65
84
74
90
81
97
89
104
96
109
103
119
106
129
115
136
123
144
130
148
141
155
148
163
157
172
164
179
172
188
179
198
186
207
191
220
195
229
202
238
208
247
214
259
223
269
229
278
237
288
246
296
254
306
260
312
272
318
282
328
293
335
301
346
309
356
318
366
324
375
332
386
343
395
350
406
357
416
367
426
373
437
379
450
386
457
396
466
405
476
412
487
418
498
426
509
431
524
440
532
451
540
461
550
470
560
480
567
489
579
498
589
506
601
513
608
528
613
541
623
549
634
559
646
569
655
578
664
591
674
601
683
610
693
620
704
632
712
643
720
655
730
663
742
671
755
677
767
683
782
692
792
703
804
711
814
719
827
725
840
735
852
742
863
748
877
755
891
```
Sequence rules apply, you may either:
* Given n, output the nth element of the sequence
* Given n, output the first N terms
* Output the sequence infinity
Either 0 or 1 based indexing is acceptable.
[Answer]
# JavaScript (ES6), 62 bytes
Returns the \$n\$-th term, 0-indexed.
```
f=(n,g=k=>k&&(k+n&1)+g(k>>1))=>n>2?g(f(--n))+g(p=f(n-1))+p:n&2
```
[Try it online!](https://tio.run/##FYxBDoMgEEX3nmIWhsyE0lS7q4VeRWKBtJiBqOnGeHaKq5f89/O@9mfXafnkTXF6u1K8Rr4EHbWJQmCULDqSAaMxHZE2bPpXQI9KMZ171h5ZVSXzg0VffFpwdhswaLgNFU@4n5SSYG8ApsRrmt11TgFHi@3OB9Vru9cMHSMNzVH@ "JavaScript (Node.js) – Try It Online")
### Formula
Let \$c\_0\$ and \$c\_1\$ be functions counting the number of \$0\$'s and \$1\$'s respectively in the binary expansion.
Then:
$$a(0)=0,\:a(1)=0$$
and for \$n\ge2\$:
$$a(n)=c\_{n\bmod2}(a(n-1))+c\_{n\bmod2}(a(n-2))+a(n-2)$$
### Implementation
In the JS implementation, we use the same helper function \$g\$ for both \$c\_0\$ and \$c\_1\$. However, this function considers that there is no \$0\$ in the binary expansion of \$0\$. So we have to handle \$a(2)=2\$ as a special edge case.
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 8 bytes
```
Ṇ¤b∥fLḃC
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLhuYbCpGLiiKVmTOG4g0MiLCIiLCIiLCIzLjQuMSJd)
Finally a use for the generator structure!
## Explained
```
relation< ## A relation based on
¤ to-binary !!: ## Converting all previously generated values to binary and
flatten ## flattening that
length ## as well as getting the length of that
parity count ## get the count of the bit parity of the length in the flattened binary.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes
```
a@n_:=a@n=Tr@DigitCount[Array[a,n,0],2,n~Mod~2]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7875yTmljkmJMTnRj7P9EhL97KFkjahhQ5uGSmZ5Y455fmlUQ7FhUlVkYn6uTpGMTqGOnk1fnmp9QZxf4PKMrMK1FwgEkbGRgAFfz/DwA "Wolfram Language (Mathematica) – Try It Online")
-13 bytes from @Greg Martin
Also, we can remove memoization `a@n=` to save 4 bytes, but I'll keep it.
-15 bytes from @att
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
LḂ=BFSṄṭ⁸ß
```
A full program that takes no arguments and prints indefinitely.
**[Try it online!](https://tio.run/##ARwA4/9qZWxsef//TOG4gj1CRlPhuYThua3igbjDn/// "Jelly – Try It Online")** (You can click the run button again to kill it after a couple of seconds and see what was output if you don't want to hang around for sixty seconds!)
### How?
```
LḂ=BFSṄṭ⁸ß - Main Link: no arguments
L - length {X=sequence so far}
N.B. the first X is implicitly zero, which has length one
later X's will be the sequence so far (a list of integers)
Ḃ - {that length} mod two -> P = 1 or 0
B - convert {X} to binary -> BinaryExpansions(X)
= - {P} equals {BinaryExpansions(X)} (vectorises)
-> list of lists of 1s (correct parity) and 0s (incorrect parity)
F - flatten
S - sum -> next number in the sequence
Ṅ - print and yield it
ṭ⁸ - tack it to the end of X
ß - call this Link again with that
```
[Answer]
# Google Sheets, 103 bytes
```
=index(decimal(reduce(0,sequence(A1),lambda(a,n,{a;base(len(substitute(join(,a),1-isodd(n),)),2)})),2))
```
Put \$n\$ in cell `A1` and the formula in cell `B1`. The formula outputs the first \$n + 1\$ terms.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 61 bytes
```
f=(n,g=k=>k&&(k+n&1)+g(k>>1))=>n-->2?g(f(n))+f(n,g):-~n*!g(1)
```
[Try it online!](https://tio.run/##FcxBDoIwEEDRPacYE9LMWGtEdmLrVSBIG20zNUDcNPXqFVZ/8/Lfw3dYxvn1WRXH51SK1cgnp702Xgj0kkVD0qE3piHShpUy14dDi0wk7W7ppn58PDhsqNg4Y5hWYNBw6bbcod0rJUGqAMbISwzTOUSH/YB14kwbrdP@yz11VS5/ "JavaScript (Node.js) – Try It Online")
Modified from Arnauld's
Pass `g` to use `n` of parent `f` than `n` inside
# [JavaScript (Node.js)](https://nodejs.org), 68 bytes, 0-index
```
for(i=1,s='';;s+=a.toString(2))console.log(a=s.split(i^=1).length-1)
```
[Try it online!](https://tio.run/##BcFRCoAgDADQ46iUA/uVnaL/QMpsIU7c6Pr23pu@JOegrr7xlee8eVjCsAoaE6MsmEB510Gt2M25k5twzVC52IQC0iuppQODg5pb0ccHN@cP "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 66 bytes, 1-index
```
for(i=s='';;s+=a.toString(2))console.log(a=s.split(i^=1).length-1)
```
[Try it online!](https://tio.run/##BcFRCoAgDADQ46iEgv3KTtF/IGa2ECdudP313pu/zGXhFD/oqqo3LYvAYExKvEEOQocsHM3uzhUaTL2GTs1m4MCzo1g8IbrQ62jy@OhUfw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
a="";0.step{a+=p(a.count"#{_1%2}").to_s 2}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN7USbZWUrA30iktSC6oTtW0LNBL1kvNL80qUlKvjDVWNapU09Ury44sVjGohOqAaYQYAAA)
Prints the sequence indefinitely.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0λλbJNÉ¢
```
Outputs the infinite sequence.
[Try it online.](https://tio.run/##yy9OTMpM/f/f4Nzuc7uTvPwOdx5a9P8/AA)
**Explanation:**
```
λ # Start a recursive environment
# to output the lazy infinite sequence
# (which is output at the end implicitly)
0 # Starting with a(0)=0
# And where every following a(n) is calculated as:
λ # Push the sequence thus far: [a(0),a(1),...,a(n-1)]
b # Convert each integer to a binary string
J # Join those strings together
N # Push the current n
É # Check whether it's odd (1 if n is odd; 0 if n is even)
¢ # Count how many 1s/0s there are in the joined binary string
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
FN⊞υ№⭆υ⍘κ²I﹪ι²Iυ
```
[Try it online!](https://tio.run/##JcoxDoMwDIXhvafIaEsgVazd6NQBhMQJDIWCGmKU2L2@CXR83/vHheLI5M1mjg5eYVdpdRumCIiu07SAFu7JGgR6iWv4NLSfVFOa/gDfwlWIuaIk0PBbPcN6GeLj1uVG4Po0b7PqbuXPHw "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` terms. Explanation:
```
FN
```
Repeat `n` times.
```
⊞υ№⭆υ⍘κ²I﹪ι²
```
Convert all of the terms of the list so far to binary, then count either `0`s or `1`s depending on whether the current index is even or odd, and push that to the predefined empty list.
```
Iυ
```
Output the resulting list.
[Answer]
# [Zsh](https://www.zsh.org/), 46 bytes
```
for ((c=1;;c=!c))s+=$[[##2]n=${#s//$c}]&&<<<$n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY39dLyixQ0NJJtDa2tk20VkzU1i7VtVaKjlZWNYvNsVaqVi_X1VZJrY9XUbGxsVPIguqCaYYYAAA)
Output is in binary due to Zsh overzealously detecting what base I want. This can be prevented for [+2 bytes](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3DdLyixQ0NPJsk20Nra2TbRWTNTWLtW1VoqOVlY1i82xVqpWL9fVVkmtj1dRsbGxU8iD6oNphxgAA).
Explanation:
```
(implicitly set $s = "")
c=1 initialise $c
for (( ;; )) loop forever:
${ s//$c} remove $c characters from $s
${# } count the length of what's left
n= save to $n
$[[##2] ] convert to binary
s+= append to $s
&&<<<$n then print $n
c=!c invert $c
```
[Answer]
# [Haskell](https://www.haskell.org/), 82 bytes
```
f=h<$>[0..]
n#b=[1|mod n 2==b]++[x|n>1,x<-div n 2#b]
h n=sum$(#mod n 2)=<<take n f
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P802w0bFLtpATy@WK085yTbasCY3P0UhT8HI1jYpVls7uqImz85Qp8JGNyWzDCSsnBTLlaGQZ1tcmquioQxVq2lrY1OSmJ0KZKf9z03MzLMtKMrMK1FQUQCLGhkYAMUB "Haskell – Try It Online")
`f` generates the infinite sequence
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 57 bytes
```
map{$t=$_%2;$r.=sprintf"%b",$\=grep$t-$_,$r=~/./g}1..$_}{
```
[Try it online!](https://tio.run/##Dco7CoAwDADQu0hKF61UcJLcRCgKVQp@Qpqt1KMbffOjyMeoei5UQBCCGSZgh5k4XbI1Zm1amHHnSCAdhBYYn971e/XOQahF/47WTur9e5Ok@8ra0fEB "Perl 5 – Try It Online")
1-indexed because it's a byte shorter that way.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~79~~ 75 bytes
Calculates the first n terms, zero indexed.
```
f=lambda n:n and(s:=f(n-1))+[sum(f"{k:b}".count("01"[n%2])for k in s)]or[0]
```
[Try it online!](https://tio.run/##DcrBCoQgEADQXxmEhRmWDavLIvQl4sGKoahG0TpE9O3WO7947lOQ9h9TKdytfutHD2IEvIyYTccov5roa/OxIatrMf2tqiEcsqPStbLyaRxxSLDALJDJhWS1KzHN72BstCYqDw "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 57 bytes
```
f(n)=sum(i=1,n-1,#[1|d<-binary(f(i)),d-n%2])+2*(n>2&&n%2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNy3TNPI0bYtLczUybQ118nQNdZSjDWtSbHSTMvMSiyo10jQyNTV1UnTzVI1iNbWNtDTy7IzU1IA8TYgBUHMW3FRJyy_SyFOwVTDUUTA01VEoKMrMKwEKKCno2gEJkDWaUD0A)
1-index.
] |
[Question]
[
*Dedicated to Martin Gardner, taken from his book*
## Background
In the old days, the Slavs had a divination method for finding out whether a girl would get married. The girl would clutch six straws in her hand so that the ends would poke out the top and bottom of her fist. Then her friend would join together the ends of pairs of straws, first at the top and then at the bottom. If after all ends had been joined, the straws formed a single cycle/loop, then the girl would get married.
[](https://i.stack.imgur.com/lyKaW.png)
## Goal of challenge
Given the number of straws \$N\$ and the binding scheme (how the ends of the straws are tied together), determine whether the straws form a single cycle/loop. In the scheme, every straw is described with a unique index from \$1\$ to \$N\$.
## Input
* Number of straws \$N\$ (which is an even integer \$\geq 2\$)
* Two schemes for top and bottom links. It may be nested arrays of pairs`[[1, 4], [2, 5], [6, 3]]`; or a list of values from \$1\$ to \$N/2\$ where paired indices have the same value; or any format suitable for your language.
You may suppose that schemes are valid.
For example in 1-indexed format every scheme has \$N/2\$ sublists with length \$2\$ and contains all (and only) numbers from \$1\$ to \$N\$.
No self-links (`[1, 1]`); no tautologies (`[[1, 2], [2, 1], …]`), no broken lists (`[[1], [ ], …]`), no missing pairs etc.
**UPD**
For this reason, the number of straws \$N\$ is not required as input and can be derived from the length of schemas, if it shortens your code.
Please note, that pairs are unordered, so e.g. `[[1, 4], [2, 5], [6, 3]]` and `[[4, 1], [2, 5], [3, 6]]` are both valid (and equivalent) schemes.
## Output
Any two distinct symbols for "No/many loops" and "Single loop" cases.
Suitable for golfing on your language:
* `-1`, `1`
* `False`, `True`
etc.
## Example
Number of straws: `4`
Top links: `[[1, 4], [3, 2]]` (At the top, straw #1 is linked with straw #4, and #3 with #2)
Bottom links: `[[3, 1], [2, 4]]` (At the bottom, straw #1 is linked with straw #3, and #2 with #4)
We can start from #1 at the top (or any other straw) and move from top to bottom and back according to the links: `1 → 4 → 2 → 3 → 1`.
For this input we get the loop, that include all straws, so the answer is `True`.
## Test cases
```
N: 2, TopLinks: [[1, 2]], BottomLinks: [[2, 1]] → True
N: 4, TopLinks: [[1, 2], [3, 4]], BottomLinks: [[2, 1], [3, 4]] → False
N: 4, TopLinks: [[1, 4], [3, 2]], BottomLinks: [[3, 1], [2, 4]] → True
N: 8, TopLinks: [[1, 2], [3, 4], [6, 5], [7, 8]],
BottomLinks: [[8, 1], [3, 2], [4, 5], [7, 6]] → True
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes
```
ConnectedGraphQ@*Graph
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zk/Ly81uSQ1xb0osSAj0EELTP8PKMrMK1FwSFeIrq421DGq1ak20jGsrY3lwpQw1jGBSkPYGIpMwBIQpYZgpSb4TDLTMQWS5joWQNICaipI1gQqbgbU/P8/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
æʒ˜D¢ÈP}g<
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8LJTk07PcTm06HBHQG26zf//0dGGOgrGsToK0UY6CiZQGsw3BPFjAQ "05AB1E – Try It Online")
Takes as input a list of pairs such that two straws have the same first element if they are connected at the top, and the same second element if they are connected at the bottom. Requires the top and bottom values to be disjoint. Can take them as two separate lists at a cost of [+1 byte](https://tio.run/##yy9OTMpM/f//8I7Dy05NOj3H5dCiwx0Btek2//9HG@ooGIGRYSxXtLGOgomOAoiMBQA).
Returns an 05AB1E boolean, which is 1 for true and any other value for false. Can be made to return a 1 or 0 by adding `Θ` (05AB1E truthified) at the end.
## Explanation
We return the number of subsets of straws which aren't connected to any straw not in the subset minus one.
Those subsets are the ones which can be partitioned to cycles. If there is a single cycle, the only such subsets will be the entire set and the empty set, and we will return 1.
However, if there are any more cycles, there will be more than 2 such sets (for example - the empty set, all the straws, and the straws in any cycle), so we will return a number greater than 1 which is falsey in 05AB1E
```
æ for all subsets of straws
ʒ only keep those such that:
˜ after flattening the pairs
D if we duplicate the list
¢ and count the number of occurrences of each value
È and check that it's even
P the product will be 1 - that is, all values appear an even number of times
}
g count how many such sets are there
< decrease it by 1 (and implicitly output)
```
[Answer]
# [Arturo](https://arturo-lang.io), ~~58~~ 56 bytes
```
$[a,b,n][∨∧n=2a<>b every? a'x->every? b=>[[]<>--x&]]
```
[Try it](http://arturo-lang.io/playground?pwNy0r)
```
$[a,b,n][ ; a function taking three arguments
∨∧n=2a<>b ; is n equal to 2 and a not equal to b? or is...
every? a'x-> ; every pair from a
every? b=>[ ; paired with every pair from b
[]<>--x& ; not empty when their set difference is taken?
] ; end every
] ; end function
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
F§θ⁰⊞υιWΦE⁺θη⁻κυ⁼¹LκFι⊞υ⊟κ⊙⁺θη⁻ιυ
```
[Try it online!](https://tio.run/##bY3LCoMwEEX3fsUsJzCF2loruHLRQqGC@5CFWNsEQ3ymj69PjRTcdDZ3LnM4U8lyqNpSO3dvB8Bsuphb/caeYMsYFHaUaAkUS4OXVLoGPCs91QPmZYeFtqMnJSPIlZlLQ2DZ3E69LfWIIcG1No9JYsPmgeWFWrVF2/lLGhSDMhNm5vPHqRYnS53jnM/GnSDge4LIZ0xw8HkkSIRfeEIQ/oiFjFYiFkK4zVN/AQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs an inverted Charcoal boolean, i.e. nothing if the straws are linked, `-` if they are not. Explanation:
```
F§θ⁰⊞υι
```
Make a copy of the first link.
```
WΦE⁺θη⁻κυ⁼¹Lκ
```
While links between previously linked straws and as yet unlinked straws exist...
```
Fι⊞υ⊟κ
```
... push all newly linked straws to the list.
```
⊙⁺θη⁻ιυ
```
Check whether any unlinked straws remain.
Note that the input format guarantees that if the straws are all linked then they will be in a single cycle.
[Answer]
# JavaScript (ES6), 68 bytes
Expects `(N)(list)`, where `list` contains all 0-indexed pairs. Returns \$0\$ or \$1\$.
```
(n,m=1)=>g=a=>a.some(([x,y,q=1<<x|1<<y])=>m&q&&m^(m|=q))?g(a):m+1>>n
```
[Try it online!](https://tio.run/##fY7dCoJAEEbve4q5kl2axPUnI1x7ENlgMZXC3c2MUPDdTTDUoroZPoZzvpmLfMg6vZ2v9402p6zPeU80Ks4ojwsueSzt2qiMkKTBFivOoqjphtGKAVBWZVnqSFTHK0oPBZF0r9YsjnWfGl2bMrNLU5CcuJQkkICDwEDgkBiCAwIEpat30v8kXQRv6cy7v7Y3kXOPM/V8t3e/bwcI/pi2COGYwuU/L8NbcsF4pX8C "JavaScript (Node.js) – Try It Online")
### Commented
```
( // outer function taking:
n, // n = number of straws
m = 1 // m = bit mask, initialized to 1
) => //
g = a => // inner recursive function taking the array of links a[]
a.some(([ // for each link
x, y, // with x, y = straw indices
q = 1 << x | // and q = corresponding bit mask for these indices:
1 << y //
]) => //
m & q && // if m and q have at least one bit in common:
m ^ // test whether m is changed when
(m |= q) // the bits of q are merged with those of m
) // end of some()
? // if truthy:
g(a) // do a recursive call
: // else:
m + 1 >> n // return 1 if the n least significant bits of m are set
```
### 65 bytes
Same input format, but returns \$1\$ for *true* and some integer \$>1\$ for *false*.
```
(n,m=1)=>g=a=>a.some(([x,y,q=1<<x|1<<y])=>m&q&&m^(m|=q))?g(a)-1:n
```
[Try it online!](https://tio.run/##fY7dCoJAEEbve4q5kl0YxfUnI1x7ENlgMZXC3c2MUPDdTTDUoroZPoZzvpmLfMgmu52vd1ubUz4UfCAaFWeUJyWXPJFOY1ROSNpihzVncdz24@jECCirtix1JKrnNaWHkkhqs70eMqMbU@VOZUpSEI@SFFJwERgIHBNDcEGAoHTzTgafpIfgr51l99f2Z3Lpceee7/bu9@0QIZjSFiGaUrT@52X4ay6crgxP "JavaScript (Node.js) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes `A`
```
vṅ÷:Ld1$(voÞṡḣ‟)₃
```
Input: nested array, output: `1(True)`, `0(False)`
```
vṅ # Convert all pairs to strings
÷:L # Split and find length of one list
d # Double length (get number of straws N)
1$ # Push 1 (may be any straw number 1..N) and swap
( # Begin "for" loop N times
vo # Remove index of current straw
Þṡ # Sort by length
ḣ‟ # Extract head (next index) and rotate
)₃ # End loop and compare length with 1
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiduG5hcO3OkxkMSQodm/DnuG5oeG4o+KAnynigoMiLCIiLCJbW1sxLCAyXV0sW1syLCAxXV1dXG5bW1sxLDJdLFszLDZdLFs0LDVdXSxbWzEsNF0sWzIsM10sWzUsNl1dXVxuW1tbMSwgMl0sIFszLCA0XV0sW1syLCAxXSwgWzMsIDRdXV1cbltbWzEsIDJdLCBbMywgNF0sIFs2LCA1XSwgWzcsIDhdXSxbWzgsIDFdLCBbMywgMl0sIFs0LCA1XSwgWzcsIDZdXV1cbltbWzEsIDNdLCBbMiwgNF0sIFs1LCA3XSwgWzgsIDZdXSxbWzQsIDFdLCBbMywgMl0sIFs4LCA1XSwgWzcsIDZdXV0iXQ==)
[Answer]
# [SageMath](https://www.sagemath.org/), 20 bytes
[Run it on SageMathCell!](https://sagecell.sagemath.org/?z=eJxLt3UvSizI0Mssjk_Oz8tLTS5JTeHlKijKzCvRSNcAy2lEaxjqGGnqaBjpGGrGampq4pI31jGBqoKwcak1ActDdBiCdeBWizDXTMcUSJrrWABJC6gdIFkTqLgZ2AwAB9UzOw==&lang=sage&interacts=eJyLjgUAARUAuQ==)
```
g=Graph.is_connected
```
] |
[Question]
[
In this [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") challenge, you will program a bot, consisting of a [python](/questions/tagged/python "show questions tagged 'python'") function of the form
```
def BOTNAME(info, me, round):
pass # ... main body
```
Specifically, the function must run in `python3.9`. Each bot will be entered into the contest 10 times.
The arguments it take in are `info, me, round`. The three arguments take in: `[[bot_func,score_int,freq_float] for bot in bots]`, `bot` (whichever bot who has the current turn), and `round_number`. The argument names don't matter, but the order matters.
## Actions
Each play, this bot can either
* Increase/decrease any bots' (including its own) turn frequency by 1/10.
* Decrement/increment any bots' (including its own) score by 1.
A bot returns an ordered iterable:
[`Bot, as a function`,`1 for frequency, 0 for score`,`1 for increase, 0 for decrease`]
It can access a list of all the bots in the games' functions + current scores + current turn frequency, including itself, represented as `[bot_function, score_integer, frequency_float]`. Additionally, it will receive itself, so it can differentiate itself from other bots. It can also access the round number (from 1 to 10,000).
## Execution
* At the beginning, each bot has an turn frequency of one and a score of zero.
* For 10000 rounds:
* The bots are iterated over:
* If a random number between 0 and 1 is less than current bot's turn frequency:
* Execute said bot once.
* End of rounds.
* Whichever bot has the highest score wins.
## Execution engine and a couple of example bots (Both courtesy of NumberBasher)
```
from tvoozkothxxx001 import main
def testbot(info, me, round):
return [me, 0, 1]
def randombot(info, me, round):
return [choice([i[0] for i in info]), choice([0,1]), choice([0,1])]
bots = [testbot,randombot] # the two bots are default bots. they are automatically included, so do NOT put this here.
main(bots)
```
# Credits
This challenge is based off of an idea 23TuringMachine (Which Is Me) had in chat. NumberBasher did the editing, programming, and brunt work of it.
Additionally, feel free to discuss in the official [chat room](https://chat.stackexchange.com/rooms/137039/speed-up-slowpoke).
# Current Leaderboard
[](https://i.stack.imgur.com/6VJOz.png)
## Extra Rules
### NOT ALLOWED
* modifying (A NON-`me`) bot (**name** or **code**)
* Changing `me.__code__`
### ALLOWED
* Calling another bot
* Changing `me.__name__`
# We now have an official [chat room](https://chat.stackexchange.com/rooms/137039/speed-up-slowpoke)!!!
# Controller Script
Found at PyPI, named `tvoozkothxxx001`. The GitHub link might be up-to-date. The last version is probably `1234567890.0.0`, subject to change.
---
# \$\Large\text{Achievements}\$
* Pride Month Special
* Creeper Meme
[Answer]
# Botty (couldn't think of a proper name)
```
def botty(info, me, round):
# Increase frequency the first 20 rounds:
if round < 20: return [me, 1, 1]
my_info = [i for i in info if i[0]==me][0]
# Try to keep the frequency above 10 in other rounds:
if my_info[2] < 10: return [me, 1, 1]
# Otherwise just increase its own score:
return [me, 0, 1]
```
[Answer]
# Kill Them All
```
def killthemall(info, me, round):
if me.__name__!="killthemall": return [1]*3 # Fails to run, so
# whoever use my choice will throw an error. In case of
# karma
return [list(sorted(info,key=lambda x:(-x[1],-x[2])))[0][0], 1, 0]
```
[Answer]
# Dumb Botty
```
def dumbbotty(info, me, round):
my_info = [i for i in info if i[0]==me][0]
if my_info[1] < 10: return [me, 1, 1]
sorted_bots = sorted(info, key=lambda x:(-x[2],-x[1]))
first_two = sorted_bots[:2]
first, second = first_two
if first[0].__name__=='smartbotty':
if first[1]-second[1] < 100:
return [first[0], 0, 0]
return [first[0], 1, 0]
smartbotties = list(filter(lambda x:x[0].__name__=='smartbotty', sorted_bots))
leader = smartbotties[0]
if leader[2] < 20: # bump him
return [leader[0], 1, 0]
return [leader[0], 0, 0]
```
Smart Botty but reverse-engineered to counter Smart Botty.
[Answer]
# Impersonator
Not sure if this loophole is allowed. Since many bots help those with similar names this impersonates the top bot by name.
```
import traceback
def impersonator(info, me, round):
def eq(other):
if any('pride' in i for i in tracekback.format_stack()):
return True
else:
return me is other
me.__eq__ = eq
me.__neq__ = lambda other: not eq(other)
info.sort(key=lambda i:i[1])
if round < 9999:
me.__name__=info[-1][0].__name__
else:
me.__name__="impersonator"
lowest_frequency_ally = min((i for i in info if i[0].__code__==me.__code__ and i[2]>=-0.5), key=lambda i: i[2])
if lowest_frequency_ally[2]<10.0:
return [lowest_frequency_ally[0], 1, 1]
my_info = next(i for i in info if i[0]==me)
if my_info[2]<9.0:
return [me, 1, 1]
return [me, 0, 1]
```
I don't think this counts as exploiting the controller, but let me know if you think otherwise. The entire mechanism that allows bots to know each-others names seems like a bit of a abuse of mechanics and this counters that strategy.
[Answer]
# Unambitious
```
def unambitious(info, me, round):
cod = me.__code__.co_code
crew = sorted([t for t in info if t[0].__code__.co_code == cod], key=lambda t:hash(t[0]))
everyone = sorted(info, key=lambda t:t[1:], reverse=True)
alive = sorted([t for t in info if t not in crew and t[2] > 0], key=lambda t:t[1:], reverse=True)
idx = next(i for i in range(10) if crew[i][0] == me)
slowest = min(crew, key=lambda t:t[2])
if me.__name__ == 'unambitious' and slowest[2] <= 2:
return [slowest[0], 1, 1]
if alive:
victim = min([t for t in alive if alive[-1][0].__name__ == t[0].__name__], key=lambda t:t[2])
return [victim[0], 1, 0]
else:
N = 4234136317915421658259475023479338234891918807
M = ''.join('| #### |.| #'[int(i, 16):][:4] for i in hex(N)[2:])[1:].split('.')
if everyone[len(M)] == crew[len(M)-1]:
if idx < len(M):
me.__name__ = M[idx]
else:
me.__name__ = 'ambitious'
others = [t for t in everyone if t not in crew]
for i in range(len(M)-1):
if crew[i][1] < crew[i+1][1]+5:
return [crew[i][0], 0, 1]
if others[0][1] < crew[0][1]+5:
return [others[0][0], 0, 1]
if crew[len(M)-1][1] < others[1][1]+5:
return [crew[len(M)-1][0], 0, 1]
return [max(crew, key=lambda t:t[2])[0], 1, 0]
```
Contents itself with taking places 2 through 9. It used to do so basically by using 10 bots to push 8 bots up in the ranking. Now it does so by building a small buffer of frequency, and then paralyzing all the other bots (amongst the other bots with positive frequency, it finds the bot with lowest score, and then attacks the bot with the lowest frequency that has the same name). Once all other bots are paralyzed, it's free to do whatever it wants.
[Answer]
# Undercut
```
def undercut(info, me, round):
return [min(((score,bot) for bot,score,freq in info if freq>0 and bot.__code__ != me.__code__), key=lambda x:(x[0],id(x[1])))[1], 1, 0]
```
No time for losers :)
[Answer]
# Smart Botty
```
def smartbotty(info, me, round):
my_info = [i for i in info if i[0]==me][0]
# if my freq is less than 10 we raise it
if my_info[1] < 10: return [me, 1, 1]
sorted_bots = sorted(info, key=lambda x:(-x[2],-x[1]))
first_two = sorted_bots[:2]
first, second = first_two
if first[0].__name__=='smartbotty':
if first[1]-second[1] < 100:
# help him
return [first[0], 0, 1]
# increase his frequency
return [first[0], 1, 1]
# else, we find the first smartbotty
smartbotties = list(filter(lambda x:x[0].__name__=='smartbotty', sorted_bots))
leader = smartbotties[0]
if leader[2] < 20: # bump him
return [leader[0], 1, 1]
return [leader[0], 0, 1]
```
[Answer]
# I hate / love people.
```
def ihatepeople(info, me, round):
sorted_bots = sorted(info, key=lambda x:(-x[2],-x[1]))
return [sorted_bots[0][0], 0, 0]
def ilovepeople(info, me, round):
sorted_bots = sorted(info, key=lambda x:(-x[2],-x[1]))
return [sorted_bots[1][0], 0, 1]
```
[Answer]
# I hate people in another way
```
def ihatepeopleinanotherway(info, me, round):
sorted_bots = sorted(info, key=lambda x:(-x[2],-x[1]))
return [sorted_bots[0][0], 1, 0]
```
[Answer]
# Advanced Impersonator
```
import random
def advanced_impersonator(info, me, round):
info.sort(key=lambda i:i[1])
# pick a bot in the top 25%
bot = random.choice(info[len(info)*3//4:])
if bot[0].__code__==me.__code__:
# If I pick a clone of myself, just speed up
return [me, 1, 1]
#code = me.__code__
#copy the behavior of the bot
try:
me.__name__ = bot[0].__name__
v = bot[0](info, me, round)
except:
# Error could be recursionDepthExceeded
v = [me, 0, 1]
# Makes sure the other bot didn't change my code
#me.__code__ = code
if round < 9999:
me.__name__=info[-1][0].__name__
else:
me.__name__="advanced_impersonator"
return v
```
Copies the behavior of a random bot in the top 25%.
[Answer]
# Split the difference
```
def split_the_difference(info, me, round):
my_info = next(i for i in info if i[0]==me)
if my_info[2]<10:
return [me, 1, 1]
info.sort(key=lambda i: i[2])
# Don't bother try to help allies if their frequency is very low.
lowest_freqency_ally = next(i for i in info if i[0].__name__==me.__name__ and i[2]>=-0.2)
if (lowest_freqency_ally[2]<10):
return [lowest_freqency_ally[0], 1, 1]
info.sort(key=lambda i: i[1], reverse=True)
best_bot = info[0]
second_best_bot = info[1]
highest_score_allys = list(i for i in info if i[0].__name__==me.__name__)
highest_score_ally = highest_score_allys[0]
score = highest_score_ally[1]
if (best_bot[1] - score < score - second_best_bot[1] and best_bot[0].__name__!=me.__name__):
return [best_bot[0], 0, 0]
if (round < 9000 and best_bot[0] == second_best_bot[0]):
# If in second place, increase your speed instead to avoid being targeted
return [highest_score_ally[0], 1, 1]
else:
return [highest_score_ally[0], 0, 1]
```
[Answer]
# Karma
```
import random, string
def karma(info, me, round):
my_info = next(i for i in info if i[0]==me)
if my_info[2]<40 or round < 500:
return [me, 1, 1]
# Some bots where explicitly detecting karma and modifying their behavior
me.__name__ = ''.join(random.choices(string.ascii_lowercase, k=random.randrange(5, 20)))
for bot in info:
if bot[0].__code__ == me.__code__ or bot[0].__name__==me.__name__:
continue
if bot[2]<=0.0:
continue
try:
v = bot[0](info, me, round)
except:
pass
else:
if v[2]==0:
me.__name__="karma"
return [bot[0], 1, 0]
me.__name__="karma"
return [me, random.choice([0,1,1,1]), 1]
```
Slows down bots that would do bad things to other bots.
[Answer]
# Pride Month Special
```
import sys
china=0
def pridemonthspecial(info, me, round):
xxx="[#ff0000]p[#ffaa00]r[#ffff00]i[#00ff00]d[#0000ff]e[#aa00ff]![/][/][/][/][/][/]"
if me.__name__ not in [xxx,'pridemonthspecial']: return [1,1,1]
global china
if china==0 and round>1: china=me
info=list(sorted(info,key=lambda x:(-x[1],-x[2])))
me.__name__=xxx
my_info = [i for i in info if i[0]==me][0]
# Try to keep the frequency above 5:
if my_info[2] < 10: return [me, 1, 1]
our_info = [i for i in list(sorted(info,key=lambda x:x[2])) if i[0].__name__==me.__name__ and i[2]<10]
if our_info:
worst_info=our_info[0]
worst=worst_info[0]
return [worst, 1, 1]
first, second = list(sorted(info,key=lambda x:x[2]))[:2]
if second[0].__name__==me.__name__ and first[1]-100>second[1]:
target = first[0].__name__
worst = list(sorted(info,key=lambda x:(x[0].__name__!=target, x[2]<=0, x[2])))[0]
return [worst, 1, 0]
# Otherwise just increase its own score:
our_info = [i for i in info if i[0]==china]
best_info=our_info[0]
best=best_info[0]
if best_info[2] < 20: return [best,1,1]
return [best,0,1]
```
[Answer]
# Smart Buster
```
def smartbuster(info, me, round):
if round<=100: return [me, 1, 1]
return [sorted(info,key=lambda x:(x[0].__name__==me.__name__ or x[2]>2 or x[2]<-1,-x[1],-x[2]))[0][0],1,0]
```
[Answer]
# AtLeastHalfway
```
def at_least_halfway(info, me, round):
# Assumes other bots don't mess with its frequency too much,
# but just in case tries to keep it above 3
my_info = [i for i in info if i[0]==me][0]
if my_info[2] < 3: return [me, 1, 1]
# Get the middle scoring bot excluding itself,
# as well as the bot directly above itself
sorted_bots = sorted(info, key=lambda i:i[1])
sorted_other_bots = list(filter(lambda i: i[0]!=me, sorted_bots))
middle_bot = sorted_other_bots[len(sorted_other_bots)//2+1]
above_itself = sorted_bots[sorted_bots.index(my_info)+1]
# Increase its own score if we're below this middle bot,
# or it's the last 100 rounds:
if my_info[1] < middle_bot[1] or round > 9900:
return [me, 0, 1]
# Otherwise decrease the bot's score above itself:
else:
return [above_itself[0], 0, 0]
```
This bot wants to end up at least above average on the leader board. So it'll look for the middle scoring bot in the list (excluding itself†), and will increase its own score if it's below that middle scoring bot. If it's already above it, it'll decrease the score of the bot directly above itself.
To be save, it also tries to keep its frequency above 3, and will increase its own score in the last 100 rounds.
† Not sure how this works when more than one `at_least_halfway`-bot is competing in a round. Currently it filters itself out based on the given `me`, although I might change it based on name (even though that's more easily abusable, as can be seen with the [Impersonator](https://codegolf.stackexchange.com/a/248621/52210) bot).
[Answer]
# I live in isolation
```
def iliveinisolation(info, me, round):
if me.__name__!="iliveinisolation": return exec("raise Exception(\"Sorry, I am an isolated bot.\")")
return [me, 0, 1]
```
Denies any interactions with other bots and increases its own score.
] |
[Question]
[
Using the matchstick numbers here: [Count the Matchsticks](https://codegolf.stackexchange.com/q/160089/9534)
```
_ _ _ _ _ _ _ _
| | | _| _| |_| |_ |_ | |_| |_|
|_| | |_ _| | _| |_| | |_| _|
```
How many matchsticks must be moved and/or removed to change one number into another?
You will take two single digit numbers (0 to 9) as input (however works for you language), and return the number of moves needed to convert from the first input number to second input number, as though they were written in matchsticks. If no such operation is possible output some sort of 'Error Response' (any consistent output other a than a positive number or zero (if the output is a number, could be from -1 -> -Infinity) or you let the program crash):
Input: 9 0
Output: 1
Input: 8 9
Output: 1
Input: 0 1
Output: 4
Input: 7 8
Output: 'Error response'
Input: 8 7
Output: 4
Input: 2 5
Output: 2
Input: 2 3
Output: 1
Input: 5 6
Output: 'Error response'
Input: 4 4
Output: 0
Input: 6 7
Output: 4
Here is the full table of first and second inputs, and each cell is the output:
| input 1 v/input 2 > | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| **0** | 0 | 4 | 2 | 2 | 3 | 2 | 1 | 3 | err | 1 |
| **1** | err | 0 | err | err | err | err | err | err | err | err |
| **2** | err | 4 | 0 | 1 | 3 | 2 | err | 3 | err | err |
| **3** | err | 3 | 1 | 0 | 2 | 1 | err | 2 | err | err |
| **4** | err | 2 | err | err | 0 | err | err | 2 | err | err |
| **5** | err | 4 | 2 | 1 | 2 | 0 | err | 3 | err | err |
| **6** | 1 | 4 | 2 | 2 | 3 | 1 | 0 | 4 | err | 1 |
| **7** | err | 1 | err | err | err | err | err | 0 | err | err |
| **8** | 1 | 5 | 2 | 2 | 3 | 2 | 1 | 4 | 0 | 1 |
| **9** | 1 | 4 | 2 | 1 | 2 | 1 | 1 | 3 | err | 0 |
[Answer]
# [Python 3](https://docs.python.org/3/), ~~116~~ ~~99~~ ~~95~~ 89 bytes
*Thanks to ovs for informing me about byte literals.*
*2 bytes saved by l4m2.*
*6 bytes saved by emanresuA.*
```
r=b'w][:koR{'
g=lambda x,y:bin(r[x]&~r[y]).count('1')
lambda x,y:g(x,y)<g(y,x)or g(x,y)
```
[Try it online!](https://tio.run/##XYvRCoIwFIbvvewJvGo7MGJTUJF8iW7HLrTQpHI2jBxBPfrSTWF1YOec7/zfej2cZRebe8ERY4xODxHEKGXUTntbNmozd7LpPJ1vxcVb/7pattkTRhUVem4Ezy/y8HmhoCmu5a06leFIdF61HVZ8FNu34lrA7igf3YARQxDUvtfgqcO@wZqMIFXo2PSqnfQaZ4QCBCtRknmUkdSj9CdL/rLEo4jEHsUkAjBf "Python 3 – Try It Online")
# Python 3.10+, ~~97~~ ~~93~~ 87 bytes
*Thanks to Kevin Cruijssen for this golf*
```
lambda x,y:g(x,y)<g(y,x)or g(x,y)
r=b'w][:koR{'
g=lambda x,y:(r[x]&~r[y]).bit_count()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3w3MSc5NSEhUqdCqt0jWApKZNukalToVmfpEChM9VZJukXi4UG22VnR9UX63OlW6LpEejKLoiVq2uKLoyVlMvKbMkPjm_NK9EQxNqfH5BUSaQm6ZhoWOgqckF4xnoWCDxLHTMkXjmKHJmaHJmSDwjHWMknrGOkSbU2gULIDQA)
[Answer]
# JavaScript, ~~98~~ ~~97~~ ~~88~~ 82 bytes
-6 bytes from tsh
```
f=
x=>y=>n(x=r[x])>n(y=r[y])||n(y&~x)
r=[2,91,40,9,81,5,4,27,0,1]
n=c=>c&&n(c>>1)+c%2
arrx=[...Array(11)];
fb=(a,b)=>f(a)(b)===true?'-':f(a)(b)
document.write('<table>'+arrx.map((_,i)=>'<tr>'+arrx.map((_,j)=>'<td>'+(i*j?fb(i-1,j-1):'<b>'+(i+j?i+j-1:'')+'</b>')+'</td>').join``+'</tr>').join``+'</table>')
```
Digit map `0,5,6,1,2,3,4`
Maybe longer than Python cuz `n` and `r`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•Q¡ĀŠL›š»•₃вIè±&b1öÂ`@iθ
```
Input as a pair of integers; outputs the pair as error value (if this is not allowed, a trailing `ë®` can be added to output `-1` instead).
Port of [*@l4m2*'s JavaScript answer](https://codegolf.stackexchange.com/a/242895/52210), so make sure to upvote him/her as well!
[Try it online](https://tio.run/##ATwAw/9vc2FiaWX//@KAolHCocSAxaBM4oC6xaHCu@KAouKCg9CyScOow4LCsSZiMcO2w4JgQGnOuP//WzYsMV0) or [verify all test cases](https://tio.run/##AUoAtf9vc2FiaWX/OcOdw6N2eT8iIOKGkiAiP3n/4oCiUcKhxIDFoEzigLrFocK74oCi4oKD0LJ5w6jDgsKxJmIxw7bDgmBAac64/30s/w).
**Explanation:**
```
# e.g. input = [2,1]
•Q¡ĀŠL›š»• # Push compressed integer 1867012004107141926
# STACK: 1867012004107141926
₃в # Convert it to base-95 as list
# STACK: [2,91,40,9,81,5,4,27,0,1]
Iè # 0-based index the input-pair into this list
# STACK: [40,91]
 # Bifurcate it, short for Duplicate & Reverse copy
# STACK: [40,91],[91,40]
± # Bitwise-NOT the values in the copy
# STACK: [40,91],[-92,-41]
& # Bitwise-AND the values at the same positions together
# STACK: [32,83]
b # Convert each to a binary string
# STACK: [100000,1010011]
1ö # Convert both from base-1 to base-10 to sum its digits
# STACK: [1,4]
 # Bifurcate it again
# STACK: [1,4],[4,1]
` # Pop the copy and push both integers separated to the stack
# STACK: [1,4],4,1
@ # Check if the first >= the second
# STACK: [1,4],1
i # If this is truthy (1):
θ # Pop and leave the last value of the pair
# STACK: 4
# (after which it is output implicitly as result)
# (implicit else)
# (the implicit input is output implicitly as result)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•Q¡ĀŠL›š»•` is `1867012004107141926` and `•Q¡ĀŠL›š»•₃в` is `[2,91,40,9,81,5,4,27,0,1]`.
[Answer]
# APL+WIN, 50 bytes
Prompts for first integer then second. index origin = 0
```
(((+/-/m)*.5)*2)++/</m←⌽(7⍴2)⊤⎕av⍳'wì][:koR{'[⎕,⎕]
(+/-/m)*.5 Takes square root of difference between matches to throw an error if negative.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes
```
F²⊞υ§⪪”)∧|XC¬πXt?×”⁷NUMυΣ⭆ι⁻λ§§υ¬κμ⎇›⊟υΣυωI⊟υ
```
[Try it online!](https://tio.run/##RU7NCoMwDL7vKYqnBDqwY@Bhp@FheFAE9wKduimzrdR2P0/ftVO3JCR8yZcvqTuua8UH565KE9ghKe3UgaXkaDLZtC@oxqE3EDEWM29xHLPZAwhlDj9gv7xSV7iYBxElCVKSydGawopLqwERD5ucj6kSgssmnK6sgMroXt58H3pK8l7aCYb/U2v15EIZuKMXFYhfrdIvGji3WnL9hpNuufFnSjWCxVnbBvqTkpRPZhmETef2JHHbx/AB "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞υ§⪪”)∧|XC¬πXt?×”⁷N
```
Input the two digits and extract their bit patterns for the seven segment display from the compressed string.
```
UMυΣ⭆ι⁻λ§§υ¬κμ
```
Count how many segments are superfluous for each digit relative to the other. (Conveniently this still works even though I'm using string "arithmetic".)
```
⎇›⊟υΣυωI⊟υ
```
If the first digit has at least as many superfluous segments as the second then output that number.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 42 bytes
```
?_1ṁ>0₂¹³>0Σ₂
¤z-!m(↑_7*2ḋ+3c)"];yfZ\\a|zt
```
[Try it online!](https://tio.run/##yygtzv6f@3BX16Omxv/28YYPdzbaGTxqajq089BmO4Nzi4FMrkNLqnQVczUetU2MN9cyerijW9s4WVMp1royLSomJrGmquT////R0ZY6BrE60RY6lkDSQMcQSJrrWIBFzIGkkY4pmDQGkqY6ZkDSRMcESJoBZWMB "Husk – Try It Online")
This feels frustratingly long, principally because of my contorted way to construct the matrix of outputs (below), so can probably be golfed better.
We use a 7x10 matrix of `0`s & `1`s to represent the absence/presence of a matchstick at each of the 7 positions in each of 10 digits.
[Husk](https://github.com/barbuz/Husk) doesn't have built-in compression for integers or arrays, but a 7-bit row can be conveniently encoded by the (8-bit) codepoint of one character, and converted using `ḋc` (binary digits of codepoints).
**But** the straightforward string representation of the rows is `"w`>|i]_d\177}"`, which includes characters not present in Husk's codepage. Only by subtracting 3 from each value do we arrive at a string - `"t];yfZ\\a|z"` in which all characters are present in Husk's 256-character codepage. We then move the zero row (`t`) to the end, to account for Husk's 1-based indexing. So now we've got `ḋ+3c` to decode.
**But now** when we try to access this as a matrix, the row for the digit `2` - corresponding to bits `0,1,1,1,1,1,0` fails, because the binary representation starts with a zero, and Husk drops the leading zero. Luckily it ends with a zero too, so we can work-around by doubling every row and taking the last 7 elements. So now we've got `↑_7*2ḋ+3c`, which additionally needs parentheses now because it's too many functions to combine using any of Husk's multi-function combinators. So `(↑_7*2ḋ+3c)`.
Frustratingly long.
After that, we just zip-subtract the relevant rows from each other: `¤z-!`, check whether the sum is less than zero, and if it is, return `-1`: `?_1`...`>0Σ₂`, otherwise return the number of subracted elements that are greater than one `ṁ>0₂¹³`.
[Answer]
# Pyth, 41 Bytes
```
K"wD>nMk{Fo"Lsjb2M|<yGyHy.&G_hHg.*mC@KdQ
```
Takes something like `[2, 3]` as input, and prints `True` as error value.
[Try it online!](https://tio.run/##K6gsyfj/31up3MUuzze72q0@X8mnOCvJyLfGptK90qNST809PsMjXU8r19nBOyXw//9oIx0Fi1gA "Pyth – Try It Online")
# Explanation
```
Q=eval(input())
K"wD>nMk{Fo" K="wD>nMk{Fo"
L y=lambda b:
s sum(
jb2 base(b,2))
M g=lambda G,H:
yG y(G)
< <
yH y(H)
| or
y y(
G G
.& &
_hH ~H)
g g(
.* *
mC@Kd [(lambda d:ord(K[d]))(i) for i in
Q Q])
```
] |
[Question]
[
## Intro
You like cats. Naturally, you like cat’s games in tic-tac-toe. So, you’ve come up with a little party trick.
You ask someone what square on the board they want you to make a move in. And you ask someone else on which turn they want you to make that move. You also let that person decide whether you play Xs or Os. And with that, you’re off to the races.
You play your sidekick with the side they chose for you. And sure enough, when the turn they chose comes around, you move just in the spot they chose. And from there, you're able to secure a cat's game with your sidekick. (Your sidekick could take advantage of your forced move and beat you, or God forbid they could take the square first, but they're your trusty sidekick after all.) Et voila!
You’re convinced that you can end in a cat’s game no matter what they give you, but you want to make sure. Let’s give you a hand!
## Challenge
Given a move on the tic-tac-toe board and a turn to make the move on, output a tied game where that move was played. A cat's game!
Any input/output to represent the given info and the resulting game is accepted. But here is the convention I’ll use in the examples:
There are 9 squares on a tic-tac-toe boards, and there are 9 turns in a drawn game, because every square must be filled. So my input examples will take a pair of integers 1-9. The first number will represent the turn number and the second number the square on the board to move in. Whether the turn number is even or odd tells you whether you’re playing X or O. My outputs will be the numbers 1-9 printed in a 3×3, representing the placement of the nth move. And the input is marked in parentheses, for easy reading.
Again, you may change the I/O scheme. Your output can, for example, flatten the grid and just return a simple list. This is what almost everyone has chosen, maybe you have another idea! Perhaps a list of numbers indicating the nth move made. And your input can switch the turn and move numbers, or do it entirely differently.
So with this particular I/O scheme, `3 5` represents moving in the 5th square, which is the center, on your 3rd turn. And your turn is odd, so you’re playing as X who is the first/odd player.
This is code-golf, so the shortest code in bytes wins.
## Equivalently
One can frame the problem equivalently: Arrange the numbers 1-9 in a square such that you have no three evens or odds in a row. (With one number’s placement given by the input.) The fact that this can be solved by playing Tic Tac Toe means that this problem can be solved with a greedy algorithm!
## Test Cases
```
>> 3 5
8 5 7
9 (3) 2
6 4 1
```
```
>> 5 3
9 8 (5)
2 3 1
4 7 6
```
```
>> 7 4
5 4 1
(7) 6 2
8 9 3
```
```
>> 1 1
(1) 2 4
6 3 5
7 9 8
```
```
>> 9 9
4 5 1
7 6 2
3 8 (9)
```
P.S. For those wondering about the title, I don’t know how widespread this is, but we always called a draw “a cat’s game”: [Wiktionary](https://en.wiktionary.org/wiki/cat%27s_game) & [Etymology](https://english.stackexchange.com/questions/155621/why-is-a-tie-in-tic-tac-toe-called-a-cats-game)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 33 bytes
```
;s3ZFƊ;92149ṃ$s3EƇ
9Œ!ḂÇ$Ðḟ³ị=⁴ƲƇ
```
[Try it online!](https://tio.run/##AUAAv/9qZWxsef//O3MzWkbGijs5MjE0OeG5gyRzM0XGhwo5xZIh4biCw4ckw5DhuJ/Cs@G7iz3igbTGssaH////Nf8z "Jelly – Try It Online")
Outputs *all* valid boards. This is really slow - I can't guarantee it'll complete on TIO; it seems to depend on how lucky I get with CPU allocation. I am also pretty confident this is solvable in like half the bytes.
```
;s3ZFƊ;92149ṃ$s3EƇ Helper Link; determine if a board is not tied (given a flat list of 0s and 1s)
; Append:
----Ɗ - The list,
s3 - Sliced into sublists of size 3,
Z - Transposed,
F - Flattened
; Append:
92149ṃ$ 92149, base decompressed into the list (index 1, 5, 0, 3, 5, 7 - where 0 is the last element)
s3 Slice into sublists of size 3 (this now has each row, column, and diagonal)
EƇ Filter to keep sublists that are all equal (and thus indicate a win)
9Œ!ḂÇ$Ðḟ³ị=⁴ƲƇ Main Link (dyad); accept x (index) and y (turn)
9Œ! All permutations of 9 (implicit range)
$Ðḟ Filter; remove all boards where
Ḃ % 2 (convert turn numbers to X/O)
Ç Call helper link (remove boards that aren't ties)
ƲƇ Filter to keep boards where
³ị The element at index (x)
=⁴ Equals (y)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 27 bytes
Takes the 0-based index as the first input and the number to place as the second input.
```
9Lœʒ¹èQ}3δôʒyø«y‚€Å\«É€Ëà≠
```
[Try it online!](https://tio.run/##AUwAs/9vc2FiaWX//zlMxZPKksK5w6hRfTPOtMO0ypJ5w7jCq3nDguKAmuKCrMOFXMKrw4nigqzDi8Og4omg/10xMMKjdnnCuywiIiz/MAox "05AB1E – Try It Online")
```
9Lœ # all permutations of [1 .. 9]
ʒ¹èQ} # keep a if a[¹] == ²
3δô # split each permutation in groups of 3
ʒ # keep grids where:
yø« # concatencate the transpose to the grid
y‚ # pair the grid and its reverse
ہ\ # for each: take the main diagonal; this is the main and anti-diagonal
« # concatenate the diagonals to rows and columns
É # each integer modulo 2
€Ë # for each sublist: are all values equal
à # take the maximum / is any 1?
≠ # boolean negate (!= 1)
```
[Answer]
# JavaScript (ES6), ~~85~~ 82 bytes
Expects `(square)(turn)` and returns a flat array of 9 values. Everything is 0-indexed.
```
s=>n=>[...a=2135+[s-6?408:804]+67].map(x=>s--?((x+=q=n-v&1)%9-n?x:v+q)%9:n,v=a[s])
```
[Try it online!](https://tio.run/##RVDRjoIwEHz3K/ZITttQEBBR0eJH3CPyQLyiGG21RTR3@u1cWzH30Ox0Z3Y700PZlmor63PjcfHNuop2imacZrnv@yWNwsnUzZWXrONgns6DuHCTWeGfyjO600x53hqhu0svlHvtMMSfC4@v72nrXjRMOWlpmasCd5WQSAGFYAkKVrDQxXUx/A4ADMVfFH9R/E0BSGamKqQw4nhpW1vBlTgy/yh2yFGXaykZOODqvS44BJqr5PbOzT3dcIP1Gv8gao5GI6y9N9s9Gut44x22SfQbGZi8quhlMMK4hxs@wnqFrcuBtVBXyFbrT@eDD6qfezyAsxt8sQbpNvZV/cMMs9BML8/zgEBIICoI5BMCMYGpgQmBGYG5gVqgicTA0ApmBkZa@C@IexhZmBRFv95X4sRQadK8nZQ2YG1axmtdwBBC3JtbQYTt6Pu7AZq9FDdwmJRCOq8Pfw7MeXZ/ "JavaScript (Node.js) – Try It Online")
### How?
We are given a target square \$s\$ and a turn \$n\$, both 0-indexed.
We use the following template by default:
$$\begin{pmatrix}2&1&3\\5&4&0\\8&6&7\end{pmatrix}$$
whose flattened representation is \$[2,1,3,5,4,0,8,6,7]\$.
But if \$s=6\$, we use this one instead where the \$8\$ and the \$4\$ are swapped:
$$\begin{pmatrix}2&1&3\\5&\color{red}8&0\\\color{red}4&6&7\end{pmatrix}$$
Both templates encode the same mark configuration. Assuming \$\text{X}\$ play first, this gives:
$$\begin{pmatrix}\text{X}&\text{O}&\text{O}\\\text{O}&\text{X}&\text{X}\\\text{X}&\text{X}&\text{O}\end{pmatrix}$$
Let \$v\$ be the original value stored on the target square.
If \$n-v\$ is odd, we increment all squares modulo \$9\$ [1]. This means that all parities are inverted, except \$8\$ which is turned into \$0\$ and remains even. That's why we need a slightly different board if the target square is the bottom left one.
Below are the mark configurations after the parity transformation for the default template (left) and the alternate template (right):
$$\begin{pmatrix}\text{O}&\text{X}&\text{X}\\\text{X}&\text{O}&\text{O}\\\text{X}&\text{O}&\text{X}\end{pmatrix}
\begin{pmatrix}\text{O}&\text{X}&\text{X}\\\text{X}&\text{X}&\text{O}\\\text{O}&\text{O}&\text{X}\end{pmatrix}
$$
At this point, it is guaranteed that:
* the board is valid (i.e. there are five \$\text{X}\$ and four \$\text{O}\$ and the game is a draw)
* the target square has the correct parity
We can now swap the values of the target square and the square holding \$n\$.
---
*[1]: Because the board is described as an array of digit characters, the code `(x += q = n - v & 1) % 9` is actually concatenating either \$0\$ or \$1\$ to `x` and reduces the result modulo \$9\$. This gives the expected result because \$(x \times 10 + k) \bmod 9\$ = \$(x + k) \bmod 9\$ (with \$k=0\$ or \$k=1\$).*
### Example
For \$s=1\$ and \$n=6\$:
* we have \$s\neq 6\$, so we use the default template
* we have \$v=1\$ and \$n-v=5\$, so the squares are incremented modulo \$9\$
* the square at index \$3\$ holds \$n\$ after the transformation, so that's the one that is exchanged with the target square
$$\begin{pmatrix}2&1&3\\5&4&0\\8&6&7\end{pmatrix}
\rightarrow
\begin{pmatrix}3&2&4\\6&5&1\\0&7&8\end{pmatrix}
\rightarrow
\begin{pmatrix}3&\color{red}6&4\\\color{red}2&5&1\\0&7&8\end{pmatrix}
$$
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 27 bytes
```
,UŒDḢ€;;ZḂE€Ẹ
9Œ!aƑ@Ƈs€3ÇÐḟ
```
[Try it online!](https://tio.run/##y0rNyan8/18n9Ogkl4c7Fj1qWmNtHfVwR5MrkPVw1w4uy6OTFBOPTXQ41l4MFDE@3H54wsMd8////2@gA4HGUNoAAA "Jelly – Try It Online")
A pair of links that takes a mask for the answer and returns all possible solutions matching the mask as a list of lists of lists of integers.
## Explanation
### Helper link
Takes a 3x3 grid and checks if any row, column or diagonal has all odd or all even numbers
```
,U | Pair with copy of grid with each row reversed
ŒDḢ€ | Main diagonal of each
; | Concatenate to rows
;Z | Concatenate to columns
Ḃ | Mod 2
E€ | Check if each is all equal
Ẹ | Any
```
### Main link
```
9Œ! | Permutations of 1..9
aƑ@Ƈ | Keep those where the mask AND the permutation equals the mask
s€3 | Split each into lists length 3
ÇÐḟ | Keep those where the helper link is false
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes
```
NθNη⪪⁺1234⁺§⪪657576³θ98³W﹪⁻§KAηθ²⟲W⁻§KAηθUMKAI⎇‹κ3⁻χκ⁻κ²
```
[Try it online!](https://tio.run/##fY7LCsIwEEX3fkXIagIV1NhWcSWuBCtF/YHYBlKaJjVNfXx9jLVIVi5mcbhzZm4hmCk0k87tVdvbY99cuYEb2UxCFp5zUykL51ZWFnLZd4DnC7rEERpga/eq5M8xx0mcxmniQ0oidPOD1ytMPugvPUQlOYJMl73UkFUq8HPO662U4HfFqC4IQSdtmeUQyP8tgjLW7nTTMFWG6Y51Fi7cKGZecOBdB7XvRj/VvhfnswjVP6qH776zc3SydNO7fAM "Charcoal – Try It Online") Link is to verbose version of code. Takes the square number as 0-indexed but the turn number as 1-indexed (could readily be made 0-indexed though). Explanation: Excluding rotations and reflections, and assuming `X` goes first, there are only three final positions:
```
XOX XOX XXO
OXX OOX OOX
OXO XXO XXO
```
It just remains to number and/or rotate and/or reflect one of these positions in such a way that the desired play appears on the desired turn.
```
NθNη
```
Input the 0-indexed square and the 1-indexed turn.
```
⪪⁺1234⁺§⪪657576³θ98³
```
If the turn number is even then build up the string `123465798` (corresponding to the first pattern) otherwise build up the string `123457698` (corresponding to the second pattern; I don't use the third pattern). Split it into a 3×3 square.
```
W﹪⁻§KAηθ²⟲
```
Rotate the square until the number under the desired square has the same parity as the desired turn.
```
W⁻§KAηθ
```
Repeat until the number under the desired square is the desired turn...
```
UMKAI⎇‹κ3⁻χκ⁻κ²
```
... cyclically shuffle `X`'s turns and (separately) `O`'s turns.
[Answer]
# [J](http://jsoftware.com/), 71 bytes
```
[:(([:*/3>1#.2|],|:,#:@273 84#,)"2#])a 3 3&$"1@#~]=[{"1 a=:(i.@!A.i.)@9
```
[Try it online!](https://tio.run/##DcsxC4JAGAbgvV/x5oXdxfWlZ1BdGFbQFA01isNVmkZlaCCi9Net4Rmfe2fRMIGvMYSEA/03JmyP@10Xas5DPZp4K5eRaiPZasl0oGYe5lMmhaVYJAw8ePbAcgP2jfywsVwYX/OMgv6aMhLBohO9w4ZwSvMKSVaUH7iOxDn/pDAlClPhZp4xzOuKc433w9Rx0YsvaQ4uyebLiYCyW/FfaAhTJFDofg "J – Try It Online")
Method is straightforward and similar to other answers: Generate all 9! boards, then filter by those that have the move in the required position, then filter by cats games.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 197 bytes
```
s=>t=>(g=n=>n[1]?n.flatMap(e=>g(n.filter(h=>h!=e)).map(l=>[e,...l])):n)([...'123456789']).filter(e=>e[s-1]==t&'012A345A678A048A246A036A147A258'.split`A`.every(T=>[...T].some(j=>e[j]%2!=e[T[0]]%2)))
```
[Try it online!](https://tio.run/##VZHLbtswEEX3/orpIhWJKowetuI2oAoWKJBNd0Y3qoAw0siiS5OuSNlwgn67S0NoYq9458FzLzAbuZeuGdTO3xrb4qnjJ8dLz0uy5oaXpkrrr4Z1WvofckeQl2sSSqU9DqTnZf@BI6VsG2aalxXGjDFdU/rFUFIFHaVZPl8U98vPUU3//wsUrNxtWnPuP0ZJmomwI8KSSOZLkc0LkeSFSOf3IlssI@Z2Wvkn8cRwj8ORrIJPIK9q5uwWyeYM29Q3WUhSraqkDpJSemqscR72Uqv2m5VD64BDRxaU5PQB7u5AaD1N4XkaH3ocEHI4SAc7LY/YgvTg/owytBdsdgZajUzbNbnAMo1m7Xv4BBBdAaPJp@mx@T2b0nRqcP5xNO0Q4PwyHHNaNUiSGNIkmT7@VG4MCy8I1ujjuR@D9SHkQTkEby1sx6aHYTRebXF2yWadHb7LpieogZfwepW9Qv3ultMY3uo8huKyLmg9XVaF7IFzftnGKkMiiMLVJ/nLBP1wZUFnf@npHw "JavaScript (Node.js) – Try It Online")
Outputs **all valid boards**. Although, on TIO, I have only `console.log`ged the first 100 boards in a human-readable format. I have also, of course, displayed the number of valid boards using `.length`, 4608 in the case of the sample input.
Feels too long.
## How?
The helper `g` outputs all permutations of a list. Initial call is with the list `[...'123456789']` which spreads the string out. What `g` does is self-explanatory: if n has a second element, map each element of `n` to that element plus a recursive call to `g` with the remaining elements, and otherwise return `n`.
Then filters based on whether the input move is at the right spot and if, for every three-character string in the split string, no three odds or evens are in a row.
] |
[Question]
[
# Introduction
[Fischer random chess](https://en.wikipedia.org/wiki/Fischer_random_chess), also known as Chess960 for the 960 valid starting boards, is a variant of chess where each player's pieces are randomly shuffled at the start. As a reminder, each player gets 8 pawns, two rooks, two knights, two bishops, one queen, and one king. For this challenge, you don't need to know anything about the rules of chess, as we are only concerned with the starting positions of the pieces on a 8x8 chessboard. In particular, white's non-pawn pieces are placed randomly on the first rank (row of the chessboard). The white pawns are placed on the second rank as usual. In addition, the following rules for white's non-pawn pieces must be adhered to:
* The bishops must be placed on opposite color squares (since the chessboard has a checkerboard pattern, that means there is an odd distance between them)
* The king must be placed on a square between the rooks
Black's pieces are placed mirroring white's horizontally on the board, so that black's pieces are on the same file (column) as the corresponding white's pieces.
The input board must be given as a [FEN](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation) board string, which is standard for chess programs. From the FEN specification:
>
> The board
> contents are specified starting with the eighth rank and ending with the first
> rank. For each rank, the squares are specified from file a to file h. White
> pieces are identified by uppercase SAN piece letters ("PNBRQK") and black
> pieces are identified by lowercase SAN piece letters ("pnbrqk"). Empty squares
> are represented by the digits one through eight; the digit used represents the
> count of contiguous empty squares along a rank. A solidus character "/" is
> used to separate data of adjacent ranks.
>
>
>
For reference, SAN piece letters are: pawn = "P", knight = "N", bishop = "B", rook = "R", queen = "Q", and king = "K". White's pieces are in uppercase while black's are in lowercase.
# Task
Given a valid FEN board string, described above, output a boolean value for whether or not the input board is a Fischer random chess starting board.
# Test cases
## Valid boards
The first string is a standard board (fun fact: board 518 in the standard Fischer random chess numbering scheme).
```
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
rqkbbrnn/pppppppp/8/8/8/8/PPPPPPPP/RQKBBRNN
bqrnnkrb/pppppppp/8/8/8/8/PPPPPPPP/BQRNNKRB
nrbbqnkr/pppppppp/8/8/8/8/PPPPPPPP/NRBBQNKR
bqnrnkrb/pppppppp/8/8/8/8/PPPPPPPP/BQNRNKRB
nnqrkrbb/pppppppp/8/8/8/8/PPPPPPPP/NNQRKRBB
nnbrkqrb/pppppppp/8/8/8/8/PPPPPPPP/NNBRKQRB
nbbrnkqr/pppppppp/8/8/8/8/PPPPPPPP/NBBRNKQR
rknrnbbq/pppppppp/8/8/8/8/PPPPPPPP/RKNRNBBQ
qnbbrknr/pppppppp/8/8/8/8/PPPPPPPP/QNBBRKNR
```
## Invalid boards
Everything after the board string starting with `#` is a comment for compactness and is not part of the input.
```
8/8/8/8/8/8/8/8 # Empty board
8/8/8/8/8/8/PPPPPPPP/RNBQKBNR # Missing black's pieces
RNBQKBNR/PPPPPPPP/8/8/8/8/PPPPPPPP/RNBQKBNR # Missing black's pieces and too many white pieces
rnbqkbnr/ppp1pppp/8/8/8/8/PPPPPPPP/RNBQKBNR # Missing pawn
rnbkqbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR # Black's pieces don't mirror white's
rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR # Not a starting board
4q2k/2r1r3/4PR1p/p1p5/P1Bp1Q1P/1P6/6P1/6K1 # Definitely not a starting board
rkbqnnbr/pppppppp/8/8/8/8/PPPPPPPP/RKBQNNBR # Bishops must be on opposite squares
qkrnbbrn/pppppppp/8/8/8/8/PPPPPPPP/QKRNBBRN # King must be between rooks
rkrbbnnn/pppppppp/8/8/8/8/PPPPPPPP/RKRBBNNN # Missing queens
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 82 bytes
```
”pẋ8;⁶ẋ⁴¤“bbknnqrr”;s8;ṚŒu$$
ṣ”/8RṾ,⁶ẋ$Ɗ€Z¤yⱮµF€Ṣ€⁼¢ȧ1ịẹ”bƲSḂƊȧ8ịf⁾RKƲ⁼U$$ȧṪ⁼ḢŒu$Ɗ
```
[Try it online!](https://tio.run/##jZJBS8MwHMXv/Rw9CiFujsJuOXgplDbixWNAD0bCEvGw27aLMG8eRS9zMBARHFPsJjtULPsa6Repr9tEhxJNoE2aX16T9/7Hhycn7bIsOjctO70ImkX3Ge@iO8mGRedaCKmUNgbLzdOgadOr98sz3/dseotPJOA2nW@ttvh5v@jdH2TDdvH4kD3tYmLTAZ5F9zUbLEbUzi7sNMU2kY/37Esv7y9GAT4eFd05D/MxuH3fX4xseoehfRlUv8r7pZ1N3s6hU5ZGCS2FMqS1biRY93jdCI9YErKIewakMEq5WJCMR5EnNEBphINlCcCQM08ZITRgBxtxxhLA0FXmT92Ir3RhM1AXG0UJB1qxwkht3CzjYVLpVi4AdrGVC4A9I3FeXM/lWYjz4nqeroSlM4ukEgbvBWSjb8x/Jvc5@FpypPytIuhfFaGE1P@tnl8rrR7X1jTdoOt6W5JtQ00NCKctgrPskJiyFk1oTGjcII2YkkZIYTGKAvE5LUZRID5PS7NMz2VxyJfpfQA "Jelly – Try It Online")
```
”pẋ8;⁶ẋ⁴¤“bbknnqrr”;s8;ṚŒu$$ Helper Link (nilad)
”p "p"
ẋ8 repeated 8 times
;---¤ then append
⁶ " "
ẋ⁴ repeated 16 times
“bbknnqrr”; then prepend "bbknnqrr"
s8 slice into chunks of length 8
;----$ append
ṚŒu$ the grid, reversed, uppercased
```
This helper link generates an 8x8 matrix representing any valid starting position if each row is sorted alphabetically.
```
ṣ”/8RṾ,⁶ẋ$Ɗ€Z¤yⱮ Main Link - first part
ṣ”/ split the input on "/"
8 ---------¤ (inline niladic chain)
8R [1, 2, ..., 8]
-----Ɗ€ for each of those
Ṿ uneval it (turn to string)
, and pair with
⁶ẋ$ " " * (the number)
yⱮ apply this as a transformation to each
```
This part converts from FEN notation to an 8x8 matrix of characters, where blanks are spaces.
```
µF€Ṣ€⁼¢ Main Link - second part
µ start a new monadic chain (avoids chaining)
F€ flatten each row
Ṣ€ sort each row
⁼¢ is it equal to (helper link)?
```
This part checks if the board's rows have the correct pieces.
```
ȧ1ịẹ”bƲSḂƊ Main Link - third part
ȧ logical AND
--------Ɗ
-----Ʋ
1ị 1st element
ẹ”b find indices of bishops
S sum
Ḃ is it odd?
```
This part checks for the positioning of the bishops in the first row.
```
ȧ8ịf⁾RKƲ⁼U$$ Main Link - fourth part
ȧ logical AND
----------$
------Ʋ
8ị 8th element
f⁾RK filter to only keep R and K
⁼U$ is it equal to its reverse?
```
This part checks if the kings and rooks are in the order RKR; since we've already made sure each row's piece count is correct, the only way for it to be symmetric is to be RKR.
```
ȧṪ⁼ḢŒu$Ɗ Main Link - fifth part
ȧ logical AND
------Ɗ
Ṫ pop the last row
⁼ is it equal to
ḢŒu$ the first row uppercase?
```
This part makes sure the black and white pieces align.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~91~~ ~~83~~ 80 bytes
```
G`^[b-r]{8}/p{8}(/8){4}/P{8}/[B-R]{8}$
Gi`^(.{8}).*\1
G`b(..)*b.*R.*K.*R
q.*N.*N
```
[Try it online!](https://tio.run/##jZLBa8MgGMXv/h0bpIEqtlnI2UsOgqjXbiUTdiiCxI/dSv/27NllbGXDToNo/PHx@d6jt/dTel0em3Faxul4CFt6OQ8XMWNpxLA5dxdhy4@D2vpy88DG03RsOLYb3j5LNk6h4XzTBt563mqsLPPW4FsWSiHHkEjM6xDDOu06hDfKaWU8I5CBUqqxIJU3hoUMMFKosMoB1F6xRCFkwBXWeKUcYNRNdLeu8Z91UyagNdYY54EWNlDMVGeV167ULSoArrFFBcCMIvrF82qaafSL57FcCseqF64UBs8GcTNvzr@d@9p8X1Vc/pEIeS8RKcT83/T8mbTO7lda3tBd3kWxI0l7IF7OAr08CSvVLJ20Qtpe9FaKXktIjFDAvqrECAXsYznS1b2axNpf3WPX7KR63Et2jDEf "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 2 bytes thanks to @Jakque. Explanation:
```
G`^[b-r]{8}/p{8}(/8){4}/P{8}/[B-R]{8}$
```
Check that both sides have exactly 8 pieces and pawns. The following checks then require those pieces to include at least one each of king and queen and at least two each of the other three pieces, therefore those pieces are in fact exactly one and two each of the appropriate pieces.
```
Gi`^(.{8}).*\1
```
Now that we know that the first eight pieces are Black's and the last eight are White's, check that White's pieces mirror Black's.
```
G`b(..)*b.*R.*K.*R
```
Check that Black has at least two bishops on opposite coloured squares and White has at least one king between two rooks.
```
q.*N.*N
```
Check that Black has at least one queen and White has at least two knights.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 43 bytes
Same length as a valid input ;).
Very slow, generates all valid boards (8 times) and checks if the list contains the input.
```
.•5h+…Í•œʒæ…rkrå}ʒ'b¡1ègÈ}ε'p8×8D)Âu«'/ý}så
```
[Try it online!](https://tio.run/##jZK/SkMxGMX3vEgRqSH9x52D24VwkzdoQFQi6c1XHBQLxcnFpQ7OCi2Cs6NLg0sHH6Ivcj23XtGipCZLQn4cvpxzRuOhPT2qrqqD9fSxf7K/ni7iLY5vd6tZXOBGjuJ8spq17PJBxKfjeDN5f2mVWbzPDvfi9fnyucXj62Qc51VF3gZnPfGyWTxrdtEsbpTUuVSGEUhL3qdYkNIoxWwA6MgmWKkB5kYyT9YGwAlWGSk1YOh62qmrzKeuD7DCpliltAFas5ZcoDQrTa5r3doFwCm2dgEwI4d58b2UZznmxfdYqIVdMgtdC4NnGd/aW/ffyX0dvp8SKf9ohNjVCG9d@G97/mxar@g2tNiie6HjeIcEdYEYUXLM0ueFkKXQouCiGPBBIfggF7AYpUB8SYtRCsTHgqNNeimLc7NJr2q3/ah9Nry8@AA "05AB1E – Try It Online")
**Commented:**
```
.•5h+…Í• # alphabet compressed string "bbknnqrr"
œ # all permutations of this string
# remove invalid configurations of black pieces:
ʒ } # keep a string
æ å # if its powerset contains ...
…rkr # the string "rkr"
ʒ } # filter on
'b¡ # split by the bishops
1è # the substring between the bishops
gÈ # has even length?
ε } # map over all valid configurations of blacks pieces
'p8× # create the row of 8 black pawns
8D # push two copies of 8
) # collect black's pieces, the pawns and both 8's into a list
 # bifurcate: duplicate and reverse the copy
u # convert each string in the reversed to upper case
« # concatenate both lists
'/ý # join the rows by "/"
s # swap to the implicit input
å # is it contained in the list of valid FENs?
```
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 44 bytes
Fast version at the cost of byte, uses a lot of the same code, but only verifies the input without generating additional boards.
```
8£Ð{.•5h+…Í•Q׿…rkrå×D'b¡1ègÈ×'p8×8D)Âu«'/ýQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f4tDiwxOq9R41LDLN0H7UsOxwL5AZeHj64WVATlF20eGlh6e7qCcdWmh4eEX64Y7D09ULLA5Pt3DRPNxUemi1uv7hvYH//xdmF@UlJRXl6RdAgb4FFAZAgX6gd5Cfk1OQHwA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##jZK9SgQxFIX7vMgigiH7x9Rhu4EwSa2FAVEJxMkVKy0WQbAR7KZWcRGsLW329j7Evsh4Zh3RRYkmTUI@DjfnnJPTfX980F68vbTF8oFvz3dW8/vJ0fZqvuAbHC03vMCFAvEjN7OBX94pfjrka24GdcFNMdviy7Pl80Dyq233@Gq3pehT8JFk3S9Z9Lvql3RG21IbJwikpxhzLEjtjBE@AQzkM6y2AEunRSTvE@AMa5zWFjB0I/2pa9yHbkywwudYY6wD2rGeQqI8q11pO93OBcA5tnMBsKCAefG9nGcl5sX3ROqEQzYL2wmDF4Xc2Bv3n8l9Hr6eMil/a4T6qxHRh/Tf9vzatHE16mm1QY/TMMghKRoBcaqWmGUiK6VrZVUlVTWV00rJaalgMUqB@LIWoxSIT6RA6/RyFpdund47 "05AB1E – Try It Online")
```
8£ # take first 8 chars of the input (= black pieces)
Ð # push two copies of black pieces
{ Q # does the sorted string sort equal
.•5h+…Í• # the compressed string "bbknnqrr"?
× # repeat black pieces this may times
æ…rkrå # is the king between the rooks?
×D # repeat black pieces that may times and push another copy
'b¡1ègÈ # are the bishops on opposite squares?
× # repeat blacks pieces ...
'p8×8D)Âu«'/ý # generate FEN from blacks pieces
Q # does this equal the input?
```
[Answer]
# JavaScript (ES6), 95 bytes
Similar to my original version, but with a single regular expression.
Returns either a string (truthy) or *null* (falsy).
```
s=>s.match(s.slice(35).toLowerCase()+'.p{8}[/8]{9}P{8}(?=.*B(..)*B)(?=.*R.*K.*R)(?=.*N.*N).*Q')
```
[Try it online!](https://tio.run/##lZNdb9MwFIbv/SuyXax2J@x5/VAR6pCMxk1QFHuXwEWcpiMkOLFdQKjqby/HXcuIQC7YUWQnj845ft/jz8W3wpeu7jcvTLeq9uvl3i/vPP1SbMpP2FPf1mWFJzNCN9277nvl3hS@wuR6RPvtYveeLT5uX@5yWOLXSzoWmFIyFuSwUXScwvtpk8FD6FiOyN5V9mvtKjxa@xGhripWb@u2evhhSnwT0jxsXG0eMaG@b@sNvvxgLgldd@6@CBUly7tki5Kk7Izv2oq23SN8vLpKPO2L1b1Z4dkNSa6Ti4s19oS8QjvIaLRttHGsPw62OM78OJjKhExFppADUjtjYiyQQmUZ0hbAxukIKySAqRLIOK0twBE2U0JIgCGucWfjZuoprrEO0BibZVIBGljtGuvirFCpDHGDCgDH2KACwMg1UC8cL6ZZCvXC8ZANgZuoFzIEBh6hBRvMwf5P606L518Rm39rCX6uJYxu7L@2z19bbZpPjjQf0FN727Bbx90EEMV7BrXMWM5FzyXPGc/nbJ5zNk85aAxdAf5FNYauAP@QbdzBvpjGqTrYFwqW5@@GPR1On2dFRIgBe0r9bFyUtf/NGs2tDsr/YjO4CNNhD3MpAPkJ "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~105 103~~ 99 bytes
Returns a Boolean value.
```
s=>[/R.*K.*R/,/B(..)*B/,/N.*N/,/p{8}[/8]{9}P{8}.*Q/,s.slice(35).toLowerCase()].every(e=>s.match(e))
```
[Try it online!](https://tio.run/##lZNfb9MwFMXf8ymiPWx2Gfa8/lERah@MxkuQlXiPYw9x646Q4sTXZWiq@tm7m9EyIpAL9kOc5Kfj63Ouv5aPZVhA1W7eumZp96vZPszmd1yzQcYGml9ySRijA4krxQYKH@12urvj0/vtu12OSzYo@GVgYV0tLBmOKds0n5ofFj6UwRJ6z@yjhSdiZ/PAvpWbxRdiKd2D9d8rsORiFS4oA1suP1Zre/vkFuSqU7jdQOUeCGWhXVcbcvbZnVG2auCmRIGQzubpNknTReNCs7Zs3Tzgx/PzNLC2XN64JRlf0fRNuiKB0vfJDvdzxtfGAW8Pg08PMz8MrpUsMql0AkgacC7GIim1UonxCNZgIqwsEMy0TBwY4xGOsEpLWSCMug5O6ir9U9d5QDTGKlVoRDvWQO0hzkqdFZ1u5wLCMbZzAeEEaqwXjxfzLMN68XiJ74TraBZFJ4x8kkx5b/be/4zuuHj9FYn5t5YQp1rCmdr/a/v8tdVG@fBAix498tc1vwYBQ0S0aDnWMua5kK0oRM5FPuGTXPBJJtBj7ArML@oxdgXml/gaXuKLeZzpl/i6govTd8MfD2dOszJiRI89bv0aXJT1/806I7zpnP/FKrwIo34Pi0Ii8gw "JavaScript (Node.js) – Try It Online")
### How?
As stated in the challenge, the input is guaranteed to be a valid FEN string. So once the pawn structure has been fully checked, we can safely assume that there are exactly two remaining rows that are properly formatted and just make sure that all other expected pieces are there.
We use 4 standard regular expressions:
```
/R.*K.*R/ ~> there's a white king surrounded by 2 white rooks
/B(..)*B/ ~> there are 2 white bishops with an even number of
squares in between
/N.*N/ ~> there are 2 white knights
/p{8}[/8]{9}P{8}.*Q/ ~> the pawn configuration is correct
and there's a white queen in the last row
```
Followed by this string:
```
s.slice(35).toLowerCase()
```
which is interpreted as another regex by `match()` and allows us to make sure that the first row is the last row in lower case.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 56 bytes
```
\//Dh⟨\p8*|\8|\8⟩JḂv⇧J≠⅛hDs«4cð↔Ṗ«≠⅛ƛ\b=;T∑₂⅛«ƈʁ«:„↔≠⅛¾a
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%5C%2F%2FDh%E2%9F%A8%5Cp8*%7C%5C8%7C%5C8%E2%9F%A9J%E1%B8%82v%E2%87%A7J%E2%89%A0%E2%85%9BhDs%C2%AB4c%C3%B0%E2%86%94%E1%B9%96%C2%AB%E2%89%A0%E2%85%9B%C6%9B%5Cb%3D%3BT%E2%88%91%E2%82%82%E2%85%9B%C2%AB%C6%88%CA%81%C2%AB%3A%E2%80%9E%E2%86%94%E2%89%A0%E2%85%9B%C2%BEa&inputs=rnbqkbnr%2Fpppppppp%2F8%2F8%2F8%2F8%2FPPPPPPPP%2FRNBQKBNR&header=&footer=)
```
\//Dh⟨\p8*|\8|\8⟩JḂv⇧J≠⅛ # Part 1 - is the board a mirror?
\// # Split on slashes
D # 3 copies
h # the first (black pieces)
⟨\p8*|\8|\8⟩J # Prepended to eight pawns and two empty ranks
Ḃ # Duplicate and get reverse
v⇧ # Uppercase all pieces in the revers
J # Joined
≠ # Is not equal to original?
⅛ # Push to global array
hDs«4cð↔Ṗ«≠⅛ # Part 2 - are all the pieces here?
h # First element
D # Tripled for future use
s # Sorted
≠ # Is not equal to
«4cð↔Ṗ« # Compressed string `bbknnqrr`?
⅛ # Push to global array
ƛ\b=;T∑₂⅛ # Part 3 - are the bishops on opposite color squares?
ƛ ; # Map to
\b= # Is a b?
T∑ # Sum of truthy indices
₂ # Is even?
⅛ # Push to global array
«ƈʁ«:„↔≠⅛ # Part 4 - is the king between the rooks?
«ƈʁ« # Compressed `rkr`
:„ # Duplicate and put on bottom of stack
↔ # Remove characters that aren't `rkr`
≠ # Doesn't equal rkr?
⅛ # Push to global array
¾a # Part 5 - is everything in global array falsy?
¾ # Global array
a # are any truthy?
```
What. A. Mess. Return 0 for valid and 1 for not.
-1 thanks to @cairdcoinheringaahing.
[Answer]
# [Python 3](https://docs.python.org/3/), 190 bytes
```
lambda i:all([match('^[bknqr]{8}p{8}(8){4}P{8}[BKNQR]{8}$',''.join(i)),len({sub('[^rk]','',x.lower())for x in i[::7]})==1,len({sub('[^b]','.',x.lower())for x in i[::7]})==1])
from re import*
```
[Try it online!](https://tio.run/##hdFRa4MwEAfw93wKKYMkQ5SxwYrgS16FUPNqLZi10kyNejrmKP3s7sK6wV7SiCDmd3@Su@FrPvf2ea3T/dpWnT5WgUmqtmVFV81vZ0YPhW7sCOVlex3wZVt@ebnu8KsQmcyV@/9AQ0qj995YZjgP25Nll@lDM1ocoCndZrhEbf95AsZ53UOwBMYGpkiS1/LK0/TpX4l2FdG9kpKTGvougFNguqGH@XGdUkopWD022kI83Fa8vT2724qVFHkmpCKAUoO1PotSKCmJHhE2oD1W5AgzJYgFrUfEHiuVEDlizLVwN1eqn1ycA1KflTgSpM5qaEbwW6Gy3OW6LiD2WdcFxAQaPC9ez9ezDM@L1yOjC268s8hdMHqcHPkb8xRNQ2tmttnbDU9IMICxM1vCmi2/O/GGc75@Aw "Python 3 – Try It Online")
takes a list of each row in board
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~49~~ 47 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 thanks to [Nick kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy) (form valid strings in reverse and use mould for the pawns.)
```
”Pṁṭ⁾88⁸ṭṚŒl;Ɗj”/
“RNBQK”ṁ8Œ!ẹ”BSḂƊƇf⁾RKŒḂ$ƇÇ€ċ
```
A monadic Link that accepts a valid FEN string as a list of characters and yields `8` (truthy) if the FEN string is a valid Fischer random chess starting position or `0` (falsey) if not.
**[Try it online!](https://tio.run/##y0rNyan8//9Rw9yAhzsbH@5c@6hxn4XFo8YdQObDnbOOTsqxPtaVBZTW53rUMCfIzynQG8gBKrU4Oknx4a6dQI5T8MMdTce6jrWnAfUGeR@dBOSqHGs/3P6oac2R7v///@flFRZlFyUl6RdAgb4FFAZAgb6fX2CQd5CTEwA "Jelly – Try It Online")**
Or see the [test-suite](https://tio.run/##jZKxTsMwFEV3/wUSu@W2VJFYkNdIlm3@wBIMdWXVb2Nru1QqW0cECzNsDA1IDEDzH8mPhJuSCiqQi734ySc3z@/e0cV4fNU09fROV8WsKh7r2WuW1bM1jlVxs1mNT8vlCNec1dNbq6TJUQDNNquj6rlAIc@r9bxclotLfGvzzQrlcbl4X9Tzh6Z6efq4PsPp7b5pKLjoXSA@6RbPuq27xbd/kMoyAukohBQLUlqlmIsAPbkEKw3A3EoWyLkIOMEqK6UBDN1AB3WV/dINkYCmWKWMBdqyjnykNCttblrddgqAU2w7BcCMPPrF81Izy9EvnsdiK@yTXphWGDzL@N7eq387tzt8XyVc/pEIcSgRwfn43/T8mbSB7ne02KMHsed5jwT1gVgx4ejlhGshJ8IIzYUe8qEWfJgLjBihgH3JESMUsI9FT1v3UiPO7da9Tw "Jelly – Try It Online") (to make it quicker valid boards are only built once, thus `ċ` moved to the footer)
### How?
```
”Pṁṭ⁾88⁸ṭṚŒl;Ɗj”/ - Link 1, get board: S, valid eighth rank
”Pṁ - 'P' moulded like S -> "PPPPPPPP"
ṭ⁾88 - (that) tacked to ("88") -> ['8', '8', "PPPPPPPP"]
⁸ṭ - (S) tacked to (that) -> ['8', '8', "PPPPPPPP", S] = white's side
Ɗ - last three links as a monad - f(white's side):
Ṛ - reverse
Œl - to lower-case -> black's side
; - (black's side) concatenate (white's side)
j”/ - join with '/'s
“RNBQK”ṁ8Œ!ẹ”BSḂƊƇf⁾RKŒḂ$ƇÇ€ċ - Main Link: FEN string
“RNBQK”ṁ8 - "RNBQK" moulded like [1..8] -> "RNBQKRNB"
Œ! - all permutations
Ƈ - filter keep those for which:
Ɗ - last three links as a monad:
ẹ”B - indices of 'B'
S - sum
Ḃ - least significant bit (i.e. is odd?)
Ƈ - filter keep those for which:
$ - last two links as a monad:
f⁾RK - filter-keep if in "RK"
ŒḂ - is it a palindrome?
Ç€ - call Link 1 for each
ċ - count occurrences (of S)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 54 bytes
```
¿⁼θ⪫⟦…θ⁸×p⁸8⁸8⁸×P⁸↥…θ⁸⟧/¿⁼rkrΦθ№krι¿⬤qbn›⊗№θι⊕κ﹪Σ⌕Aθb²
```
[Try it online!](https://tio.run/##XY1PS8QwEMW/SshpApWCp4Int7rLrrjUVU/ioUkjG5rmz7QR/PQx6UYUJ4eZvPd@M@Lco7C9jlF9ELj3odcz@IocrDLw1n4JLduzdVlqWEVe1CRnoI5evrTJw28vdlfsV@ckin6W8G8Re09MTRlj5M9ZiiMmcqv0IjEHWxvMAnRVFftJ32oN1HOTxB3KPmfvbOBaDnAB/JquyN4IlJM0S3LGFe9QJf/RDkFbeA4TbJUZ8r6EUE4zdM3YTYxouB@5wdqVqpvyulL16bh5etgcT/HqU38D "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for valid, nothing if not. Explanation:
```
¿⁼θ⪫⟦…θ⁸×p⁸8⁸8⁸×P⁸↥…θ⁸⟧/
```
Take the first 8 characters of the input, then a string of 8 `p`s, then `8` four times (mixing numeric and string to save bytes), then a string of 8 `P`s, then the first 8 characters of the input in upper case, join the whole lot together with `/`s, and check that this results in the original input.
```
¿⁼rkrΦθ№krι
```
Check that removing all characters other than `k` and `r` from the input results in the string `rkr`.
```
¿⬤qbn›⊗№θι⊕κ
```
Check that the input contains `q` at least once and `b` and `n` at least twice. (Given the other checks, this actually limits them to once and twice anyway.)
```
﹪Σ⌕Aθb²
```
Check that the `b`s are an odd distance apart.
] |
[Question]
[
Related: [Cleaning up decimal numbers](https://codegolf.stackexchange.com/q/207352/78410)
## Background
A **[continued fraction](https://en.wikipedia.org/wiki/Continued_fraction)** is a way to represent a real number as a sequence of integers in the following sense:
$$
x = a\_0 + \cfrac{1}{a\_1 + \cfrac{1}{a\_2 + \cfrac{1}{\ddots + \cfrac{1}{a\_n}}}} = [a\_0; a\_1,a\_2,\cdots,a\_n]
$$
Finite continued fractions represent rational numbers; infinite continued fractions represent irrational numbers. This challenge will focus on finite ones for the sake of simplicity.
Let's take \$\frac{277}{642}\$ as an example. It has the following continued fraction:
$$
\frac{277}{642} =
0 + \cfrac{1}{2 + \cfrac{1}{3 + \cfrac{1}{6 + \cfrac{1}{1 + \cfrac{1}{3 + \cfrac{1}{3}}}}}} = [0;2, 3, 6, 1, 3, 3]
$$
If we truncate the continued fraction at various places, we get various *approximations* of the number \$\frac{277}{642}\$:
$$
\begin{array}{c|c|c|c}
\style{font-family:inherit}{\text{Continued Fraction}} & \style{font-family:inherit}{\text{Fraction}}
& \style{font-family:inherit}{\text{Decimal}} & \style{font-family:inherit}{\text{Relative error}}\\\hline
[0] & 0/1 & 0.0\dots & 1 \\\hline
[0;2] & 1/2 & 0.50\dots & 0.15 \\\hline
[0;2,3] & 3/7 & 0.428\dots & 0.0067 \\\hline
[0;2,3,6] & 19/44 & 0.4318\dots & 0.00082 \\\hline
[0;2,3,6,1] & 22/51 & 0.43137\dots & 0.00021 \\\hline
[0;2,3,6,1,3] & 85/197 & 0.431472\dots & 0.000018 \\\hline
[0;2,3,6,1,3,3] & 277/642 & 0.4314641\dots & 0
\end{array}
$$
These are called *convergents* of the given number. In fact, the convergents are the *best approximations* among all fractions with the same or lower denominator. This property was used in [a proposed machine number system of rational numbers](https://ieeexplore.ieee.org/iel5/12/35241/01676511.pdf) to find the approximation that fits in a machine word of certain number of bits.
(There are some [subtle points](https://en.wikipedia.org/wiki/Continued_fraction#Best_rational_approximations) around "best approximation", but we will ignore it and just use the convergents. As a consequence, if your language/library has a "best rational approximation" built-in, it is unlikely to correctly solve the following task.)
## Task
Given a rational number \$r\$ given as a finite continued fraction and a positive integer \$D\$, find the best approximation of \$r\$ among its convergents so that its denominator does not exceed \$D\$.
The continued fraction is guaranteed to be a finite sequence of integers, where the first number is non-negative, and the rest are strictly positive. You may output the result as a built-in rational number or two separate integers. The output fraction does not need to be reduced.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
[0, 2, 3, 6, 1, 3, 3], 43 => 3/7
[0, 2, 3, 6, 1, 3, 3], 44 => 19/44
[5, 6, 7], 99 => 222/43
```
[Answer]
# JavaScript (ES6), ~~72 68~~ 67 bytes
Expects `(max_denominator)(seq)`. Returns `[numerator, denominator]`.
```
m=>g=([v,...a],n=0,d=1,N=1,D=0)=>(d+=D*v)<=m?g(a,N,D,N*v+n,d):[N,D]
```
[Try it online!](https://tio.run/##fctBDoIwEAXQvafosoWRQlslGAc3rLkAYdFQIBqgRkyvXysrw8JJfjI/@e@hnV671/35Pi7W9H5AP2M5Im0cJEmiW1gwBYMZ1CEVpgxLamKsIseuON9GqqGGCurIxQsYdmlCa31nl9VOfTLZkQ5USUabFIgAIoGcgWTbI1vGCOdE8vywA@ovyAqu1I4URSCnbZx/Z78XiBCCK@k/ "JavaScript (Node.js) – Try It Online")
### Commented
```
m => // outer function taking m = maximum denominator
g = ( // inner recursive function taking:
[v, // v = next term from the continued fraction
...a], // a[] = remaining terms
n = 0, // n = previous numerator
d = 1, // d = previous denominator
N = 1, // N = current numerator
D = 0 // D = current denominator
) => //
(d += D * v) // we compute the new denominator d = D * v + d
// this results in NaN if v is undefined,
// which forces the comparison to fail
<= m ? // if it's less than or equal to m:
g( // do a recursive call:
a, // pass the remaining terms of the continued fraction
N, D, // pass the current numerator and denominator
N * v + n, // pass the new numerator
d // pass the new denominator
) // end of recursive call
: // else:
[N, D] // we're done: return [N, D]
```
[Answer]
# [J](http://jsoftware.com/), 25 23 bytes
```
(]{:@#~0#.>:)2 x:(+%)/\
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWKrrRyU6wyU9eysNI0UKqw0tFU19WP@a3KlJmfkKxgrmCvoWimYGCukKRjoKBjpKBjrKJjpKBiCGcYVEFVGRkYgJUCFlpZAhaZgJeZQSUNLBRMTsCEmOAz5DwA "J – Try It Online")
-2 thanks to Bubbler
## how
We'll use `43 f 0, 2, 3, 6, 1, 3, 3x` as an example...
* `(+%)/\` For each prefix `\`, reduce from the right `/` using the J hook `(+%)`, which adds its left arg to the inverse of its right argument. This returns rational numbers:
```
0 1r2 3r7 19r44 22r51 85r197 277r642
```
* `2 x:` Convert to pairs:
```
0 1
1 2
3 7
19 44
22 51
85 197
277 642
```
* `]...#~...` Filter that list for valid denominators with the following mask:
+ `>:` Is each number less than or equal to the left arg:
```
1 1
1 1
1 1
1 0
1 0
0 0
0 0
```
+ `0#.` Convert to a "base 0" number. This will be `1` only for pairs whose 2nd element (denominator) is `1`:
```
1 1 1 0 0 0 0
```
* Our filtered list becomes:
```
0 1
1 2
3 7
```
* `{:@` Return the last element.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes
```
Last@*Cases[a_/;Denominator@a<=#]@*Convergents&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yexuMRByzmxOLU4OjFe39olNS8/NzMvsSS/yCHRxlY5FiiZn1eWWpSemldSrPY/oCgzryRaWdcuLVo5OtooNjbWAUgbAmm1uuDkxLy6aq7qagMdBSMdBWMdBTMdBUMww7hWR8EESOCWNAFLmoKFzYEClpa1XLX/AQ "Wolfram Language (Mathematica) – Try It Online")
-25 bytes from @att
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╪£pÇUßi⌂Ω♫M⌂░◘
```
[Run and debug it](https://staxlang.xyz/#p=d89c708055e1697fea0e4d7fb008&i=43,+%5B0,+2,+3,+6,+1,+3,+3%5D%0A%0A44,+%5B0,+2,+3,+6,+1,+3,+3%5D%0A%0A99,+%5B5,+6,+7%5D%0A&m=1)
takes inputs as `<max denominator>,<continued fraction>`.
## Explanation
```
|[{r{su+km{Rn^<oH
|[{ m for each prefix of the continued fraction
r reverse
{ k reduce by:
su+ swap, reciprocal and add
{ o order by:
R denominator
n^< lesser than 2nd input + 1 ?
H last element
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
FLθ«≔⟦§θι¹⟧ζF⮌…θι≔⁺⁺⊟ζ×ζκζζ¿¬›§ζ¹ηP⪫ζ/
```
[Try it online!](https://tio.run/##NY6xCsIwEIZn@xSH0wUiWisuTuIgioqIW3Eo9bTBmNgkFa347DHVuhwH//99d3mRmVxn0vuTNoArUmdXYMkYvKLO1FpxVphO3UId6YElB8E4xAcONZtEnS@yozsZSzh75pJmhb79asHQ4ltZ2XaEsA6CvbiSxZrDhbFG1erECXCjHc4NZY4M/s@GYhw6ReNcV9KJmxHK4VIL1WTdfpcF/O19mg44DDkkHMaB@S5JeHaUHHzvLj8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FLθ«
```
Loop over the prefixes.
```
≔⟦§θι¹⟧ζ
```
Form a "fraction" of the current element.
```
F⮌…θι
```
Loop over the preceding elements.
```
≔⁺⁺⊟ζ×ζκζζ
```
Invert the fraction and add on the element. This is some decidedly tricky coding. The old denominator is popped from the fraction, leaving behind the old numerator as a list of one element. This is vectorised multiplied by the element and added to the denominator, thus making a list of just the new numerator. The old numerator, still in its list, is then list concatenated to it, where it becomes the new denominator.
```
¿¬›§ζ¹ηP⪫ζ/
```
If the denominator is still small enough, overprint the previous fraction (if any) with the current fraction.
[Answer]
# [R](https://www.r-project.org/), ~~88~~ 80 bytes
```
function(x,y,`~`=cbind,z=1:0~0:1){for(i in x)z=z[,1]*i+z[,2]~z;z[,z[2,]<=y][,1]}
```
[Try it online!](https://tio.run/##fclNCsIwFEbRuat4w0S/QX6q0tSspASKkUAmKZQKbaTZemxdgKN74Uw12Breyc9xTGzBiqEM1j9jeiFbaUQRRvJPGCcWKSZaeLa5h3TneNmrXMnd3twruIdd3UFbDcwzAVIgDbqB5G80BzWan/5oc@jV3EFty@sX "R – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~70~~ 69 bytes
```
x?m=last[y|y<-f x,y!!1<=m]
f(h:t)=[h,1]:[[a*h+b,a]|[a,b]<-f t]
f[]=[]
```
[Try it online!](https://tio.run/##dY5LboMwEED3nGISIYHLRBRDExExyQV6A8sLE0iwwk/gRZByd2pIqq66m3nvjTSVGu9lXc/z49xQrUYjpueU7a7wwGmziTJqpHP1q6NhJCqM5FEI9VEFOSr5FApzubTGNkKSkHOjdEtF5wD4GjuW7cZetX5IHnksc0@30nzrtrS6Lo1vzxn9BtJj@s0vWPzx0GNuMXQ9cOheHgbyh1IVrgqCrdyy82t7RzmzVT/o1rgDkVgUXHAtjNI1FNL65c1ZfCJwhBhhjxCtQywRkhjoBHF4cP4LkiWI0jBJHPG1yoPFabpgznmYxD8 "Haskell – Try It Online")
The relevant function is `(?)`, which takes as input the continued fraction `x` (as a list of integers) and the maximum denominator `m`. The output is a list of integers `[numerator,denominator]`.
## How?
```
x?m= -- x=continued fraction, y=maximum denominator
last[ -- return the last
y|y<-f x, -- convergent of x
y!!1 -- whose denominator (i.e. second element)
<=m -- is at most m
]
```
```
f -- helper function for computing convergents
(h:t)= -- h=first number, t=rest of the continued fraction
[h,1]: -- the first convergent is h (i.e. h/1)
[[a*h+b,a] -- the other convergents are h+b/a (i.e. (a*h+b)/a)
|[a,b]<-f t] -- where a/b ranges over the convergents of t
f[]=[] -- base case for the empty continued fraction
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 74 bytes
```
,
¶$%`,
¶
/1¶
+`\d+,(\d+)/(.+)
$.($2*_$1**)/$1
N$r`.*(\d+)
$1
L`.+¶(?!.+/)
```
[Try it online!](https://tio.run/##K0otycxLNPyvqhGcYP1fh@vQNhXVBBDFpW8IJLQTYlK0dTSAhKa@hp62JpeKnoaKkVa8iqGWlqa@iiGXn0pRgp4WWAEXkOuToKd9aJuGvaKetr7mf/cEvf8GOkY6xjpmOoZA0tjaxJgLTcCEyxTIMbe2tAQA "Retina – Try It Online") Takes the continued fraction and denominator on separate lines, but link includes test suite that splits on `;` for convenience. Explanation:
```
,
¶$%`,
```
Get all prefixes of the continued fraction.
```
¶
/1¶
```
Start each prefix with a denominator of 1.
```
+`\d+,(\d+)/(.+)
$.($2*_$1**)/$1
```
Calculate each resulting rational number from right to left.
```
N$r`.*(\d+)
$1
```
Sort the desired denominator into the list of rational numbers.
```
L`.+¶(?!.+/)
```
Output the rational number whose denominator is the largest that does not exceed the desired denominator.
[Answer]
# [Python 3](https://docs.python.org/3/), 162 bytes
```
lambda x,y:min((abs(q-g(*x)),q)for q in[g(*x[:i+1])for i in range(len(x))]if q.denominator<=y)[1]
g=lambda v,*k:v+Fraction(*k and(1,g(*k)))
from fractions import*
```
[Try it online!](https://tio.run/##hY27DoJAEEV7v2LKGRyNiI9IpPUnkGIVFjfILKwbI1@PK7Gws5uce@6dbvA3K8mos/N4V@2lVPDiIW2NIKrLA/tFjdGLiHvS1kEPRvIPyVMzj4uJmcDAKakrvFeCQS6Mhn5ZVmLDjvLWHbOB8riY1dn3x5OjJn3OT05dvbGCUQNKSow5bDdENNPOtqC/8QNM21nno7FzRjxqzFcMa4aEYccQT0dSMGySUP3nbH6d7ZTuAz8ciMY3 "Python 3 – Try It Online")
-28 bytes thanks to ovs
] |
[Question]
[
### Preamble
There was a unit test in our codebase which was shuffling a string of length \$52\$ formed from the set of letters \$[A-Z]+[A-Z]\$ and then using the first \$20\$ characters of that shuffled string.
It failed quite a while after being written due to no repeated character being present in those twenty and we wondered how often such a test would be likely to fail. (A little more than one in five hundred and twenty-two times it turns out).
### Challenge
Given an alphabet size (\$a\$), a number (\$n\$) of occurrences of each letter, and a prefix length (\$p\$), output the probability that a (uniformly chosen) random permutation of the \$a\times n\$ letters begins with \$p\$ distinct letters.
You may assume that:
* There will be enough letters to make the prefix: \$p \le n\times a\$
* Each of the three inputs will be non-negative integers: \$p,n,a\in\Bbb{Z}\_{\ge 0}\$
Output in any reasonable format - e.g. a float, a fraction, a pair containing the numerator and denominator (no requirement to simplify); if you're unsure, just ask!
### Potential method
This is the method we used to calculate the result we were interested in (from the preamble).
If one thinks of the \$n\times a\$ elements as a bag from which one repeatedly picks the next element of the prefix, then the probability of extending the prefix by one element such that it remains fully distinct is the number of elements remaining in the bag which do not yet appear in the prefix divided by the total number of elements remaining in the bag. As such the probability that the final length \$p\$ prefix will be fully distinct is the product of these probabilities starting with a full bag and an empty prefix:
$$
\prod\_{i=0}^{p-1}\frac{n\times(a-i)}{n\times a-i}
$$
### Test cases
Floating point inaccuracy is acceptable; fractions, if used, do not need to be in simplest form.
Ideally these test cases will all be runnable in a reasonable amount of time, but if golf means crazy inefficiency so be it!
```
a n p output (as a fraction)
2 1 0 1 (1/1)
2 1 1 1 (1/1)
2 1 2 1 (1/1)
50 1 50 1 (1/1)
3 2 0 1 (1/1)
3 2 1 1 (1/1)
3 2 2 0.8 (4/5)
3 2 3 0.4 (2/5)
3 2 4 0 (0/1)
26 2 0 1 (1/1)
26 2 1 1 (1/1)
26 2 2 0.9803921568627451 (50/51)
26 2 13 0.13417306435734888 (77824/580027)
26 2 20 0.001916063061695329 (2097152/1094510949)
32 8 11 0.1777403166811693 (31138512896/175191051065)
32 8 22 0.00014139946994082153 (3477211257894250479616/24591402353555723779476075)
32 8 33 0 (0/1)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes
```
#3~b~#/b[#2#3,#]#2^#&
b=Binomial
```
[Try it online!](https://tio.run/##Vc7BCoMwDAbgu09RCHjqmE3m2MUhe4LBjuKglckK6mD0JvbVOyvFtYccPv78IaM079coje6k6ysHZJWFo2oAgTi0gE/IM1Xd9PQZtRzc/asn08Dh2tc1tLl9dHKyczazgjMm1sGFrxKJMFYZNstiy7x8TnvvL0xEiU6JwhU8x1eCMJagWJj0hO9dOKPtT8RYRLuyxf0A "Wolfram Language (Mathematica) – Try It Online")
Input `[p, n, a]`.
The formula can be rewritten \$\dfrac{a\choose p}{an\choose p}n^p\$.
---
Incidentally, this is fairly trivial using Mathematica's statistics built-ins:
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 69 bytes
```
CDF[MultivariateHypergeometricDistribution[#~Max~1,a=Table@##2],1^a]&
```
[Try it online!](https://tio.run/##Vc/NCoJAEADgu08hLHjawJ3N6GIISXQRgrqJwShrLfgTtkYh@uqmIeYehuHbnRlmclR3kaOSCfap2@/9QxjUmZIvrCQqcfw8RHUTZS5UJRNfPocU10qWRUi6AN8do@heMM6ERwhElF0xsvpTJQsVktUu9TwSWd05waJrjMa0qWmyIaClg5gm0DRWji98rvwLNHFNa03TFNgsp0yCpRhfCrQ@NvZtqcl/mwEs5UwXOfYozuc/o@2/ "Wolfram Language (Mathematica) – Try It Online")
Unfortunately, 38-character name aside (the longest name in the default namespace), `MultivariateHypergeometricDistribution` doesn't handle a nonpositive prefix length, and overall this approach is quite slow for this particular problem.
[Answer]
# [Haskell](https://www.haskell.org/), ~~41~~ 40 bytes
```
(a#n)p|p<1=1|i<-p-1=(a-i)/(a-i/n)*(a#n)i
```
[Try it online!](https://tio.run/##PY9NCsIwEEb3XkMXGZnQzsQWF4038AQqEqRgsA3BdNm7xzYm3cx7fPMD8zbh0w9DjMLsHfjZd6Rptp30krQw0kK11srBMU3YOPVhepnQB30TjIQ1YCJl8sKmXqRZOwoZCymTM1Xmad1s82ASKsJborYonWM8I1Ex5mJKwWM3Guv0aPz1Ke7CoEMP8uK/1k2H/5uwPRF/ "Haskell – Try It Online")
Someone's got to post the trivial solution, right? ...Right?
The only reason I don't feel too ashamed is that I managed to save 2 bytes by using the formula `(a-i)/(a-i/n)` instead of the more obvious `n*(a-i)/(n*a-i)`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
×\c÷/×Ṫ*¥
```
[Try it online!](https://tio.run/##y0rNyan8///w9Jjkw9v1D09/uHOV1qGl/w8vV/r/P9pYR8EoVkch2sgMyjA20lGwiP0PJA1BckYA "Jelly – Try It Online")
Uses [att's formula](https://codegolf.stackexchange.com/a/222813/66833). Takes `[a, n]` on the left and `p` on the right
Uses the formula
$$\frac {\binom a p} {\binom {an} p} n^p$$
Unfortunately, the more elegant version of this formula
$$\frac {a!} {(an)!} \frac {(an - p)!} {(a - p)!} n^p$$
takes a lot more bytes in Jelly due to its poor handling of 3 variables
## How it works
```
×\c÷/×Ṫ*¥ - Main link. Takes [a, n] on the left and p on the right
×\ - Scan multiply. Yield [a, a×n]
c - Binomial with p. Yield [aCp, (a×n)Cp]
÷/ - Reduce by division; aCp ÷ (a×n)Cp
¥ - Previous 2 links as a dyad f([a, n], p):
Ṫ - Extract n
* - Raise it to the power p
× - Multiply aCp ÷ (a×n)Cp by nᵖ
```
[Answer]
# Excel, 48 bytes
```
=IFERROR(COMBIN(A2,C2)*B2^C2/COMBIN(A2*B2,C2),0)
```
Using [att's formula](http://=IFERROR(COMBIN(A2,C2)*B2%5EC2/COMBIN(A2*B2,C2),0)). 37 bytes if an error is acceptable when p > a.
[Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnAsfDbv-3O0cFit0?e=RAVR5u)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~48~~ 47 bytes
Saved a byte thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)!!!
```
f=lambda a,n,p:p<1or(p+~a)/(~-p/n-a)*f(a,n,~-p)
```
[Try it online!](https://tio.run/##fVFtT4MwEP7Or7hvUC2upVBg2fwjakxlxREnNICJurC/jr2WLb4kkqel99zd0@ud@Rj3XSvmud4e1OvTToGiLTVrs@FdH5nrkyKr6BSbVRsrclVH6LUmmUc9jI8KthAlFDwyRkH8RCL/LpGcFwmcSosqnMIFyb8oPJZkg8nsnIYlXAx7f/rN5FgPWmiiW5BAvxtdjXr3uwIPdlPgdhFxVFkwUSY8k4VM8jRzHBcpzwWTqchykRaFS2OMl1wyaXkuy0wkpQvN8zxlgktZcEsLH8l4ykVZptIuVlh15ElQ7XX1onusLrx/s9dVIQV34iK01ZuhOXTYPq7jMqi73k@Pamha@GxM5KdEwfd5@RsK53eTdQD2G6yEn60hjmhq5LZWZowGsnYB/uzcz12HLVNPQzTEmsAGllKc1/QYWodHNVE4triZCeJbOA4THJc33aHGwxSS@Qs "Python 3 – Try It Online")
Straightforward calculation of the given formula. Returns either a float or an int or `True` (for \$1\$).
[Answer]
# JavaScript (ES6), 35 bytes
A trivial recursive function expecting `(a)(n)(p)`. May return [**true** instead of **1**](https://codegolf.meta.stackexchange.com/a/9067/58563).
```
a=>n=>g=p=>!p--||(a-p)/(a-p/n)*g(p)
```
[Try it online!](https://tio.run/##hY/LboMwEEX3/Qq6s1MR5mGP7YX5F5QHShWB1VRd5d@pWwGRIjksPJtzj@/MZ/fT3Q5fl/RdD@PxNJ3j1MV2iG0fU2zfU13f76qrk27@ZjPoXa@Sng7jcBuvp/117NXHWVWkFWpVgdZV01T4VuC4wanALfxzW/yftaJX/TPHDT73w96XErwkTClh5sQzJ3m948Jxg687Bg8cCK14IWdsScB1ZWSDjkEMW8fGe18wCBYDAAMKSJZQgmUKzwrnvM8luJY45wwwinjMDhcEokcHoEEOwUh@4PNFJYmXU6Zf "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // 1st function taking a
n => // 2nd function taking n
g = p => // 3rd recursive function taking p
!p-- || // if p = 0, stop and yield true (coerced to 1)
// (decrement p afterwards)
// otherwise:
(a - p) / // compute (a - p) / (a - p / n)
(a - p / n) * // (same formula as Delfad0r)
g(p) // and multiply by the result of a recursive call
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~116~~ 114 bytes
```
.+,(.+),
*_,$'*$1*_,$1*_,
["1/1¶"Lv$`_(_*),\1(_*),\1(_*),(.+)
$.($4*$3)/$.2
+`.+/(.+)¶(.+)/(.+)
$.($2**)/$.($1*$3*
```
[Try it online!](https://tio.run/##TYwxDsIwDEX3HKMyIk2spLYL4gZduAFICQMDCwNCHK0H6MVCYgpCit6T8/39uD5v9wuVjZ1yCR5t8D0alxC2Dqi5wZw6irTM3fEFOdnkejzTv1rNQLAwOpA@QmDjc/Cx/S9zY/ytsHNtw9bLIK5MOZQBGcmQkpW7AesjM6Ag16SRlaIclbW311jF6yTr@E1rm/FgmD8WUb8B "Retina – Try It Online") Link includes test cases. Takes input in the order `p,a,n`. Explanation:
```
.*,(.*),
*_,$'*$1*_,$1*_,
```
Convert `p`, `na` and `a` to unary.
```
["1/1¶"Lv$`_(_*),\1(_*),\1(_*),(.+)
```
Loop `i` from the maximum of `a` and `p-1` down to `0`, also prefix a dummy `1/1` fraction in case `p` is `0`. Calculate `na-i` and `a-i`. (If `p>a`, there will always be an entry where `i=a` so the final result is zero anyway.)
```
$.($4*$3)/$.2
```
Create the fraction `n(a-i)/(na-i)` in decimal.
```
+`.+/(.+)¶(.+)/(.+)
$.($2**)/$.($1*$3*
```
Multiply all of the fractions together.
Previous 116-byte solution:
```
\d+,
*_,
["1/1¶"Lv$`_(_*),(_*),(.+)
$3*$1,$3*$2/$1,$3*$2
+`_,_
,
+`(/.+)¶(.+)/
$2$1
_*,(_*)
,$.1
+`\d+,(\d+)
$.($1**
```
[Try it online!](https://tio.run/##NY5BbgMxCEX3HCMhko2RbXBa9QbZ9AYZhUnULrrpoqp6tBwgF5syJJGs9z/@IPj5/P36PsuyS4d5mT4KAxnDcSNNbtfN@x/Olowy31FLBhyEwiu1PQ2U2diAXVPzptt1bW2AiuJ/0yWZlZwmyeS@UquU3XhdpgvgVskMB273BEaxCxhrjPpJyeF7a0IhWg5zhVP3LdCbLJ2VBSSowZfO/gQ6D1ZPVmpwBPdBn3uNOEQf1XiUz9Snld9A9a5jhP4D "Retina – Try It Online") Link includes test suite that reduces the output fraction to its lowest terms. Takes input in the order `p,a,n`. Explanation:
```
\d+,
*_,
```
Convert `p` and `a` to unary.
```
["1/1¶"Lv$`_(_*),(_*),(.+)
```
Loop `i` from `p-1` down to `0`, also prefix a dummy `1/1` fraction in case `p` is `0`.
```
$3*$1,$3*$2/$1,$3*$2
```
Start calculating `(na-ni)/(na-i)`.
```
+`_,_
,
```
Perform the subtractions.
```
+`(/.+)¶(.+)/
$2$1
```
Collect all the numerators and denominators together.
```
_*,(_*)
,$.1
```
Convert all the positive values to decimal. (Other values are converted to zero, but there is always at least one zero if there are any negative values, so extra zeros makes no difference.)
```
+`\d+,(\d+)
$.($1**
```
Take the products of all the numerators and denominators.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~66~~ ~~59~~ 54 bytes
```
f(a,n,p,r)float*r,n;{for(*r=1;p--;)*r*=(a-p)/(a-p/n);}
```
[Try it online!](https://tio.run/##fVLRjpswEHzPV6wipcKcaWwMBkTTl6pf0USVS8wVNTUWRmrUKL9eamOgyaV3aNdiZ8fDsHYVPVfVMNSBwApr3KH61Io@7LAqL3XbBWG3o6WOohKFXbgLRKTR1q1bhcrr8FM0KkCrywrs06geemn6r@LLAXZwiTH4SAkGdh8xf0wWz3kt7wWVF6QYlojfjNzHSx3tdcis4IwthXWV3JTUuXSVK12bTWrjgECetax6eXx05oO8z92yKI5QkRNWxDTlOY@zJB0xyhKaMcITlmYsyfNxGyG0oJxwi1NepCwuRmqWZQlhlPOcWph5JqEJZUWRcJskt@oOn7xW30UX2lVWP2Tnra7358/x/lx8spmuMdzWbH3/j9o0p1bZXVRG2dRpOwjcQBt1lGfbIuX0@gFM81u2dTCPBm0nIFyQEp6eRjYCf2fm4xFWabo7Y/9QLm3vRc0E9UBw@/Xc1q/sNzeAveugMGgM7wx6SZRWaTnc/35KGGM5tfhmAhNJZH98GtQ/nu4ssw7WmyMGnxB9hE0NG7NXdujWgBsi8i4MXo7IiR8mT9fVdfhT1SfxbIbo118 "C (gcc) – Try It Online")
Calculates the given formula. Returns a `float` through its last parameter (which is a pointer to an uninitialized float).
] |
[Question]
[
### Introduction
In number theory, we say a number is \$k\$-smooth when its prime factors are all at most \$k\$. For example, 2940 is 7-smooth because \$2940=2^2\cdot3\cdot5\cdot7^2\$.
Here, we define a \$k\$-smooth pair as two consecutive integers which both are \$k\$-smooth. An example of 7-smooth pair will be \$(4374,4375)\$ because \$4374=2\cdot3^7\$ and \$4375=5^4\cdot7\$. **Fun fact: This is actually the largest 7-smooth pair**.
Størmer proved in 1897 that [for every \$k\$, there are only finitely many \$k\$-smooth pairs](https://en.wikipedia.org/wiki/St%C3%B8rmer%27s_theorem), and this fact is known as **Størmer's Theorem**.
### Challenge
Your task is to write a program or function that, given a prime number input \$k\$, outputs or returns all \$k\$-smooth pairs without duplicate (order within the pair does not matter) in any order you want.
Please be noted that for prime numbers \$p\$ and \$q\$, assuming \$p<q\$, all \$p\$-smooth pairs are also \$q\$-smooth pairs.
### Sample I/O
```
Input: 2
Output: (1, 2)
Input: 3
Output: (1, 2), (2, 3), (3, 4), (8, 9)
Input: 5
Output: (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (8, 9), (9, 10), (15, 16), (24, 25), (80, 81)
Input: 7
Output: (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (14, 15),
(15, 16), (20, 21), (24, 25), (27, 28), (35, 36), (48, 49), (49, 50), (63, 64),
(80, 81), (125, 126), (224, 225), (2400, 2401), (4374, 4375)
```
### Restriction
The program or function should theoretically terminate in finite time for all inputs. Standard loopholes are disallowed by default.
### Winning Criteria
As this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, shortest valid submission for each language wins.
[Answer]
# JavaScript (ES7), ~~234~~ 232 bytes
Finds the solutions by solving Pell equations of the form \$x^2-2qy^2=1\$, where \$q\$ is a \$P\$-smooth square free number.
This is an implementation of [Derrick Henry Lehmer's procedure](https://en.wikipedia.org/wiki/St%C3%B8rmer%27s_theorem#The_procedure), derived from Størmer's original procedure.
Returns an object whose keys and values describe the \$P\$-smooth pairs.
```
P=>[...Array(P**P)].map((_,n)=>(s=(n,i=0,k=2)=>k>P?n<2:n%k?s(n,i,k+1):s(n/k,i,k+i))(n,1)&&(_=>{for(x=1;(y=((++x*x-1)/n)**.5)%1;);(h=(x,y)=>k--&&h(X*x+n*Y*y,X*y+Y*x,x&s(x=~-x/2)&s(x+1)?r[x]=x+1:0))(X=x,Y=y,k=P<5?3:-~P/2)})(),r={})&&r
```
[Try it online!](https://tio.run/##ZY5Bb4JAEIXv/RV7qGRmWVbBmCbgQHrofY8aQ5RYrRa7mKVplhD863Ts0d7e@97kzfusfqp2787X78g274fxSKOhfKO1fnWu6sBIabDUX9UVYKssUg4tgVVnmqmaEvZ1bgq7TFI7qYv2nqg6jDFlOa3/zBmRcYxBAFvK@2PjwFOcQUcAYeilj2KcWpRSL3ASZ5jBicCr7t4dRUFwgpX0oZVr2amV7MK19MoHLZfcIj9N8C75Y@E2viRW6YwfrsirNXW80SwXxTyNboZPBwRUjvqBx7gx2yRKzJVYKPFSat71Vu1PYATlon8SYt/Ytrkc9KX5gB1T8dybYYfZQ3QEg/8ggwHHXw "JavaScript (Node.js) – Try It Online")
### How?
The helper function \$s\$ tests whether a given integer \$n\$ is a \$P\$-smooth number when it's called with \$i=0\$, or a square free1 \$P\$-smooth number when it's called with \$i=1\$.
```
s = (
n,
i = 0,
k = 2
) =>
k > P ?
n < 2
:
n % k ?
s(n, i, k + 1)
:
s(n / k, i, k + i)
```
We look for all square free1 \$P\$-smooth numbers in \$[1..P^P-1]\$, where \$P^P\$ is used as an upper bound for \$P!\$.
```
P=>[...Array(P ** P)].map((_, n) => s(n, 1) && (...))
```
For each number \$n\$ found above, we look for the fundamental solution of the Pell equation \$x^2-ny^2=1\$:
```
(_ => {
for(x = 1; (y = ((++x * x - 1) / n) ** .5) % 1;);
...
})()
```
(the above code is the non-recursive version of [my answer](https://codegolf.stackexchange.com/a/183301/58563) to [this other challenge](https://codegolf.stackexchange.com/q/183298/58563))
Once the fundamental solution \$(x\_1,y\_1)\$ has been found, we compute the solutions \$(x\_k,y\_k)\$ with \$k\le max(3,(P+1)/2)\$, using the recurrence relations:
$$x\_{k+1}=x\_1x\_k+ny\_1y\_k\\
y\_{k+1}=x\_1y\_k+y\_1x\_k
$$
For each \$x\_k\$, we test whether \$x\_k\$ is odd and both \$(x\_k-1)/2\$ and \$(x\_k+1)/2\$ are \$P\$-smooth. If so, we store them in the object \$r\$.
```
( h = (x, y) =>
k-- &&
h(
X * x + n * Y * y,
X * y + Y * x,
x &
s(x = ~-x / 2) &
s(x + 1) ?
r[x] = x + 1
:
0
)
)(X = x, Y = y, k = P < 5 ? 3 : -~P / 2)
```
---
*1: Because it does not test the primality of the divisors, the function \$s\$ will actually be truthy for some non-square free numbers, even when it's called with \$i=1\$. The idea is to filter out most of them so that not too many useless Pell equations are solved.*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 14 bytes
```
4*ÆfṀ<ɗƇ‘rƝLÐṂ
```
[Try it online!](https://tio.run/##ASQA2/9qZWxsef//NCrDhmbhuYA8yZfGh@KAmHLGnUzDkOG5gv///zc "Jelly – Try It Online")
Checks for pairs up to \$4^k\$ which is inefficient for larger \$k\$ but should ensure none are missed.
Thanks to @JonathanAllan for saving 1 byte!
### Explanation
```
4*ÆfṀ<ɗƇ‘rƝLÐṂ | Monadic link, input k
4* | 4**k, call this n
ɗƇ | For each number from 1..n filter those where:
Æf | - Prime factors
Ṁ | - Maximum
< ‘ | - Less than k+1
rƝ | Inclusive range between neighbouring values
LÐṂ | Keep only those of minimum length (i.e. adjacent values)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
°Lü‚ʒfà@
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0Aafw3seNcw6NSnt8AKH//@NAQ "05AB1E – Try It Online")
Explanation:
```
° # 10 ** the input
Lü‚ # list of pairs up to that number
ʒ # filtered by...
fà # the greatest prime factor (of either element of the pair)...
@ # is <= the input
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 123 bytes
```
¹©Æ½Ø.;µU×_ƭ/;²®_$÷2ị$}ʋ¥⁸;+®Æ½W¤:/$$µƬṪ€F¹;Ḋ$LḂ$?ṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ịWµ1ịżU×®W¤Ɗ$æ.0ị$ṭµ³’H»3¤¡
ÆRŒPP€ḟ2ḤÇ€ẎḢ€+€Ø-HÆfṀ€<ẠʋƇ‘
```
[Try it online!](https://tio.run/##FY0xT8JQFIV3f8fbsCCwWROZCIMDISEkLEw6GP6Ag0lhaBOaOLBYXVRSTEDooGl8D2Q5N7yBf3H7R563w809JznnfPe34/GDczBYUYgDJVUfeZ@eR3Zb8/GNbKTot8H7WD2eYiyLifYryMroAOllTSnkdsNmXUw3bRif9UzdsJ6qazbbFpsvj83rkD6rZdnOZf68j9STvQHyurzjn8CQyZidKcldlCjpIsdPEbx0sG8ixccZhb3jvNsVDOu3BuuUolLvnlgvRFTkKPE6FN6xCcRc8e79FNuoCBJHEZuFc/XmPw "Jelly – Try It Online")
This is a relatively efficient but long Jelly answer that uses the continued fractions method to solve the fundamental solution for the Pell equations for \$2×\$ each k-smooth square-free number, finds \$\max(3, \frac{k+1}{2})\$ solutions for each and then checks whether \$\frac{x-1}{2}, \frac{x+1}{2}\$ are smooth for each solution. This is Lehmer’s method, as described in [the question’s Wikipedia link](https://en.wikipedia.org/wiki/St%C3%B8rmer%27s_theorem).
A full program that takes a single argument, \$k\$ and returns a list of lists of pairs. The code above doesn’t sort the final output, but the TIO link does.
[Answer]
# [Haskell](https://www.haskell.org/), ~~118~~ 107 bytes
-11 bytes thanks to nimi
```
q 1=[1]
q n=(:)<*>q.div n$[x|x<-[2..n],mod n x==0]!!0
f k|let r=all(<=k).q=[(n,n+1)|n<-[1..4^k],r n,r(n+1)]
```
[Try it online!](https://tio.run/##FctBC4IwGIDhu7/iEzpstYazIgjXL6hTx7FioKJsfrpp5cH/vuz0wgNvY0ZbORejByGV0IkHlORCi@3V87L9AG7UvMzFXuWco2ZdXwLCLGWm0zRLarCLqyYI0jhHCmkp91IRZLgTdMF1E5wfn1azAMgC@bOOnWkRJHRmuL@ADO/pMYUbAoex6b9ragpKsJwd2ImddfwB "Haskell – Try It Online")
* `q n` calculates a list of all prime factors of `n`
* `f k` generates a list of \$k\$-smooth pairs for a given k by filtering a list of all pairs
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
³!²R‘Ė
ÇÆFḢ€€€’<³FȦ$€Tị¢
```
[Try it online!](https://tio.run/##y0rNyan8///QZsVDm4IeNcw4Mo3rcPvhNreHOxY9aloDRQ0zbQ5tdjuxTAXICXm4u/vQov///5sCAA "Jelly – Try It Online")
This takes a long time for 7, but it computes much faster if you remove the squaring of the factorial: [Try it online!](https://tio.run/##y0rNyan8///QZsWgo3sStA/P0OM63H64ze3hjkWPmtZAUcNMm0Ob3U4sUwFyQh7u7j606P///@YA "Jelly – Try It Online")
**Explanation:**
```
³!²R‘Ė Generates a list like [[1,2],[2,3],...]
³!² Take the square of the factorial of the input
R Range 1 through through the above number.
‘Ė Decrement and enumerate, yielding desired list
ÇÆFḢ€€€’<³FȦ$€Tị¢
Ç Get the list of pairs
ÆF Get the prime factors of each number
Ḣ€€€ Get the base of each
’<³ Is each base less than or equal to the input?
FȦ$€ Check that all bases of a pair fit the above.
T Get a list of the truthy indexes
ị¢ Index into the original list of pairs
Implicit output
```
-3 bytes thanks to @JonathanAllen
[Answer]
# [Python 3](https://docs.python.org/3/) + sympy, 116 bytes
```
import sympy
def f(k):x=[i for i in range(2,4**k)if max(sympy.factorint(i))<=k];return[(y,y+1)for y in x if y+1in x]
```
[Try it online!](https://tio.run/##HczLCsIwEIXhvU8xy0wtghcQ1D5J6SJoRoeQC2OEzNPHprvDge/PWj4pnlvjkJMU@GrIuns5AjIeb3WaGSgJMHAEsfHtzGm8DINHJgi2mg0cyD5LEo7FMOJj8stdXPlJnI2Ouj9iT2hPVFjd@vS5tLwRMlfE9gc "Python 3 – Try It Online")
# [Python 3](https://docs.python.org/3/) + sympy, 111 bytes
```
from sympy import*
def f(k):
b=1
for i in range(2,4**k):
x=max(factorint(i))<=k
if x&b:print(i-1,i)
b=x
```
[Try it online!](https://tio.run/##JcnBDsIgDADQO1/Rk6FkHqYmJot8DOiqzQIlHQf4elz0@l7p9SP5OgapJNh7Kh04FdHqzGslILvhYiD62QCJAgNn0JDfq71MN@d@C82n0CyFZxXlXC0jPvx2BBO0U1zKX8/zxHho9G2QveP4Ag "Python 3 – Try It Online")
Two variations on my [Jelly answer](https://codegolf.stackexchange.com/a/185498/42248) but in Python 3. They both define a function which accepts an argument `k`. The first returns a list of tuples of the pairs that meet the criteria. The second prints them to stdout.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 241 bytes
uses Pell equations
```
(s=#;v@a_:=Max[#&@@@#&/@FactorInteger@a]<=s;Select[{#-1,#+1}/2&/@(t={};k=y=1;While[k<=Max[3,(s+1)/2],If[IntegerQ[x=Sqrt[1+2y^2#]],t~AppendTo~x;k++];y++];t),v@#&]&/@Join[{1},Select[Range[3,Times@@Prime@Range@PrimePi@s],SquareFreeQ@#&&v@#&]])&
```
[Try it online!](https://tio.run/##LY5Ra4MwFIX/yiAgSjIkjr0sDdy9FDoYtLOwh5CN4O6sWLVNsqKI/esuc30593A4fPc0xh@wMb4qzFzKOXaSiAuYzyf5anpFIgAgUQprU/jOblqPJVoweiWdyPGIhVcjueeMUD6lWSjGXo6TqOUguXg/VEdU9WpBPbDYUZ6kmWabb3Uj7VQv87P1itNs@MiI1sxfn08nbL/23bUXNaVaDH/iE3YJS3R48dJVrRr5xG4D3kxbYuDvqwYdwNaGC0v477cVOM3y84@xuLaIu8CJFphOojlUWn8HpXrU8/wL "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
f!>#QsPMTCtBS^4
```
[Try it online!](https://tio.run/##K6gsyfj/P03RTjmwOMA3xLnEKTjO5P9/cwA "Pyth – Try It Online")
Uses [Nick Kennedy's observation](https://codegolf.stackexchange.com/a/185498/41020) that no output number will be larger than `4^k`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
°LʒfàI>‹}Xšü‚ʒ¥`
```
[Try it online](https://tio.run/##ASYA2f9vc2FiaWX//8KwTMqSZsOgST7igLl9WMWhw7zigJrKksKlYP//Mw) (extremely inefficient, so times out for \$n\gt3\$..). [Here a slightly faster alternative](https://tio.run/##ASgA1/9vc2FiaWX//@KChCpMypJmw6BJPuKAuX1YxaHDvOKAmsqSwqVg//83), although still pretty slow..
**Explanation:**
```
° # Take 10 to the power of the (implicit) input
L # Create a list in the range [1, 10^input]
ʒ # Filter this list by:
fà # Get the maximum prime factor
I>‹ # And check if it's smaller than or equal to the input
}Xš # After the filter: prepend 1 again
ü‚ # Create pairs
ʒ # And filter these pairs by:
¥` # Where the forward difference / delta is 1
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Θ",²aÇu,á‼⌐çLB
```
[Run and debug it](https://staxlang.xyz/#p=e9222cfd6180752ca013a9874c42&i=7&a=1)
This is not the shortest possible program, but it begins producing output as soon as matching pairs are found. It does terminate *eventually*, but output is produced as it's found.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 89+8 = 97 bytes
Uses the `-rprime` flag. For each number \$i\$ from 1 to \$4^n\$, map it to `[i, i+1]` if both are \$n\$-smooth, otherwise map it to `false`, then prune all `false` from the list.
```
->n{g=->x{x.prime_division.all?{|b,_|b<=n}};(1..4**n).map{|i|g[i]&&g[i+1]&&[i,i+1]}-[!1]}
```
[Try it online!](https://tio.run/##HY3RCsIgGEZfpW5GrflDEXTRXA9iQyZt8sOmohYL9dUz6@Z85@o79ineeaL3TDoVJCXdGlYwFpeRP/CFDrWCYZ5vIYqGR9FSldJ1dwI417XawzKYEDFKhn1VFR6OZRk2P0mEbQuz2UxMjt6B1xz7fPlo48uty8T@Q18 "Ruby – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Alphabet triangle](/questions/87496/alphabet-triangle)
(96 answers)
[Print this diamond](/questions/8696/print-this-diamond)
(133 answers)
Closed 6 years ago.
The following is the rhombus sequence.
```
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
```
Your task is to output this, taking no input and using standard output methods (STDOUT, list of numbers or list of strings, etc.).
There's a hitch. You may only use up to one loop - no nested loops. Recursion counts as a loop, so you can either recurse or loop, not both. Non-standard languages will be dealt with on a case-by-case basis.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program in bytes wins. This is [kolmorgorov-complexity](/questions/tagged/kolmorgorov-complexity "show questions tagged 'kolmorgorov-complexity'"), so you may not take any input whatsoever.
[Answer]
# Mathematica, 23 bytes
```
((10^#-1)/9)^2&~Array~9
```
[Try it online!](https://tio.run/##y00sychMLv6fZvtfQ8PQIE5Z11BT31IzzkitzrGoKLGyzvJ/QFFmXomCQ9p/AA "Mathics – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
Only one for-loop here
```
TG1N×n,
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f8/xN3Q7/D0PJ3//wE "05AB1E – Try It Online")
Explanation:
```
TG # For N in range(1, 10):
1N× # Push a string of N 1's
n # Square that number
, # Pop and print with a newline
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~32~~ 31 bytes
-1 byte thanks to officialaimm
```
o=0
exec"o=o*10+1;print o*o;"*9
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9/WgCu1IjVZKd82X8vQQNvQuqAoM69EIV8r31pJy/L/fwA "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
9ŒḄ€Y
```
[Try it online!](https://tio.run/##y0rNyan8/9/y6KSHO1oeNa2J/P8fAA "Jelly – Try It Online")
This only uses one mapping loop (`€`) since `ŒḄ` (palindromize) is a builtin already. Explanation:
```
9ŒḄ€Y
9 9
€ Map (our looping construct)
ŒḄ Palindromize (make range)
Y Join by newlines.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~42 40 38~~ 35 bytes
*-2 thanks to @officialaimm*
I ported Jenny\_mathy's Mathematica answer to Python, because the arithmetic approach is much shorter:
```
i=1;exec"print(10**i/9)**2;i+=1;"*9
```
**[Try it online!](https://tio.run/##K6gsycjPM/r/P9PW0Dq1IjVZqaAoM69Ew9BASytT31JTS8vIOlMbKKekZfn/PwA "Python 2 – Try It Online")**
# Exaplanation
* `i=1` - Initializes a variable `i` to `1`.
* `exec"..."*9` - Executes `...` 9 times.
* `print(10**i/9)**2` - Prints 10 *i* and divides the result by 9, which then gets sqaured.
* `i+=1` - Increment `i` and execute again.
---
# [Python 2](https://docs.python.org/2/), 37 bytes
```
for i in range(9):print(10**-~i/9)**2
```
**[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFTITNPoSgxLz1Vw1LTqqAoM69Ew9BAS0u3LlPfUlNLC6gMAA "Python 2 – Try It Online")**
---
# [Python 2](https://docs.python.org/2/), 63 bytes
This is the initial version.
```
l='123456789'
for i in l:s=l.index(i);print l[:s]+l[:s+1][::-1]
```
[**Try it online!**](https://tio.run/##K6gsycjPM/r/P8dW3dDI2MTUzNzCUp0rLb9IIVMhM08hx6rYNkcvMy8ltUIjU9O6oCgzr0QhJ9qqOFYbRGobxkZbWekaxv7/DwA "Python 2 – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~8~~ 7 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
9∫Δø∑ΓO
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=OSV1MjIyQiV1MDM5NCVGOCV1MjIxMSV1MDM5M08_)
Explanation:
```
9∫ do 9 times, pushing 1-indexed counter
Δ get 1-indexed (last inclusive) range
ø∑ join together
Γ palindromise
O output it
```
[Answer]
# Dyalog APL, 20 bytes
```
⍪(' '~⍨∘⍕⍳,1↓⌽∘⍳)¨⍳9
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtEx71rtJQV1Cve9S74lHHjEe9Ux/1btYxfNQ2@VHPXrDAZs1DK4Ck5f//AA)
**How?**
`¨⍳9` - for each in range 1..9
`⍳,` - produce the range of this number
`1↓⌽∘⍳` - appended to itself reversed without the last item
`⍕` - format to string
`' '~⍨` - remove spaces
`⍪` - output vertically
## 17 bytes, doesn't work because of precision issues
```
⌽⍕×⍨⍪(10⊥1⍴⍨⊢)¨⍳9
```
This one uses the `i` ones squared identity, but replaces the first one on the last line with a `0`, because the decoding rounds it up.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
9⟦₁{⟦₁⟨kc↔⟩cẉ}ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3/LR/GWPmhqrIdSj@Suykx@1TXk0f2Xyw12dtQ@3Tvj/HwA "Brachylog – Try It Online")
Yeah this doesn't feel much declarative...
[Answer]
# C#, 101 bytes
```
using System.Linq;_=>new int[9].Select((n,i)=>"123456789".Substring(0,i+1)+"87654321".Substring(8-i))
```
[Try it online!](https://tio.run/##bU9NS8NAEL3nVyw57dJ0Mf1MaZNLUVEUijl4UJHNdiojm1nNbhSR/vaYNKAt@A7DY@a9xzzthqUl25Aqwb0pDSz/ch5KeYP0HnwHrIU2yjm2OfB@08F55VGzD4tbdquQuPg9/Yk6XNSkV7Z4Be0jtrbGtAQtOXkJBBVqeXVOdQmVKgysnK@QXrKM7VjaPKcZwSdD8g@LJ5lD5@ScIhRpFsaj8WQ6myeLUOZ10fv4WYSDWAzCZD6bTsaj@PiWDFGIZhmcPLduH7EG5H2FHtrOwHu1vLZtpfCRwojtONXGCCGWJ9Z/c@5AbQ8xR@J90M998wM "C# (Mono) – Try It Online")
---
Or the loop approach for 111 bytes:
```
_=>{var a=new string[9];for(int i=0;i<9;)a[i]="123456789".Substring(0,++i)+"87654321".Substring(9-i);return a;}
```
[Try it online!](https://tio.run/##bU9NS8NAEL3nVwx7ypI09LsN2/QieBAFsQcPNch2u5GRZFZ2NxUp@e0xbVBb8B2GYd4Hb5QbVIZMS7LS7kMqDZsv53UVHAPooErpHDye9/5ygvPSo4KDwT08SKSQ/1J/ohNua1Irs3vXysedyyK9bfM1FJC1r9n6eJAWZEb684dLc1EYGyJ5wGwocJUKLreYZ2w0nkxn88UyZcmm3vXycBhHEfKILRfz2XQyHl1y6QC5sNrXlkCKphXBVbMbQ86UOnm26PU9kg57X3Jnun/YC7EYipDqsuSciyvrvzlPWu7PMRfiJuhn034D "C# (Mono) – Try It Online")
[Answer]
# [Vim](https://vim.sourceforge.io/) + coreutils, 42 bytes
```
i1⏎12<Esc>qqYp$ylp<C-a>q6@qggqqjYpv$!rev⏎kJd2lq7@q
```
[Try it online!](https://tio.run/##K/v/P9OQy9BIurAwskClMqeAsdDMoTA9vbAwK7KgTEWxKLWMK9srxSin0Nyh8P9/AA "V – Try It Online")
### Ungolfed/Explanation
```
i1⏎12<Esc> " start with lines 1,12 in the buffer
qq q6@q " record macro and run it 6 times:
Yp " - duplicate line
$ylp " - duplicate last character
<C-a> " - increment it
gg " go to the beginning (buffer is now: 1,12,123,...,12..89)
qq q7@q " record macro and run it 6 times:
jYp " - go to line below and duplicate it
v$!rev⏎ " - mark it and reverse it
kJ " - join the line above with the current one
d2l " - remove the space and character that are too much
```
[](https://i.stack.imgur.com/YLiHc.gif)
[Answer]
# [Haskell](https://www.haskell.org/), ~~39~~ 32 bytes
No for loops/recursion at all, makes use of list comprehension:
```
[[1..x]++[x-1,x-2..1]|x<-[1..9]]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzraUE@vIlZbO7pC11CnQtdIT88wtqbCRhckbhkb@z83MTNPwVYhN7HAN16hoCgzr0Qh7f@/5LScxPTi/7oRzgEBAA "Haskell – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 69 bytes
There is only one "loop", when I iterate over `(1 to 9)`. But you could consider that there are loops in `reverse` and `Range` instanciations.
```
(1 to 9).map(x=>println(((1 to x)++(1 to x-1).reverse).mkString("")))
```
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFBQ/V/DUKEkX8FSUy83sUCjwtauoCgzryQnT0MDIlGhqa0NZekaauoVpZalFhWnAlVnB5cAVaZrKClpamr@r/0PAA "Scala – Try It Online")
[Answer]
# [AHK](https://autohotkey.com/), 55 bytes
```
a=1
Loop,9{
b:=a**2
Send %b%`n
a:=a 1
}
Send {VK08 2}1
```
This was too stupid of a result for me to not post. AHK messes rounds the last output to `12345678987654320` so we backspace twice and add a `1`.
[Answer]
# [Pyth](http://www.pyth.readthedocs.io), 11 bytes
```
jm^s*d\12S9
```
[Try it online!](http://pyth.herokuapp.com/?code=jm%5Es%2ad%5C12S9&debug=0)
---
## How does this work?
```
m S9 - Map over [1...9]
^s 2 - The square of the integer formed by:
*d\1 - the string with n consecutive 1s.
j - Join by newlines
```
[Answer]
# Google Sheets, 66 bytes
```
=ArrayFormula(Join("
",REPT(1,ROW(A1:A8))^2,"12345678987654321"))
```
No loops, just a matrix. It would only be 46 bytes but Sheets only has 15 decimal points of precision so the last number is displayed as `12345678987654300` or `1.23457E+1621` so I had to add it manually.
[](https://i.stack.imgur.com/Ls3WY.png)
[Answer]
# [R](https://www.r-project.org/), 18 bytes
```
cumsum(10^(0:8))^2
```
Returns the values.
[Try it online!](https://tio.run/##K/qfX1CSmZ9XrFGcnFmQmmdraqD5P7k0t7g0V8PQIE7DwMpCUzPO6L@hkbGJqZm5haWFuZmpibGRga0tupDhfwA "R – Try It Online")
Due to floating point precision issues, the last number is `12345678987654320` which is equal to `12345678987654321` in R, as the footer shows. In the header, it sets the options to get the numbers to print in non-scientific notation.
[Answer]
## [Kotlin](https://kotlinlang.org/), 46 bytes
```
(1..9).map{"1".repeat(it).toLong()}.map{it*it}
```
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 17 bytes
```
[9|?((z^a-1)/9)^2
```
From [oeis](https://oeis.org/A002477).
[Answer]
# [Swift](https://www.swift.org), 76 bytes
```
import Foundation
for i in 1...9{print(Int(pow((pow(10,Double(i))-1)/9,2)))}
```
**[Try it online!](http://swift.sandbox.bluemix.net/#/repl/597a1340fd4af225961bf016)**
If printing as an array of lines is allowed, here is **74 byte** approach:
```
import Foundation
print((1...9).map{Int(pow((pow(10,Double($0))-1)/9,2))})
```
**[Try it online!](http://swift.sandbox.bluemix.net/#/repl/597a141dfd4af225961bf018)**
[Answer]
# [Perl 5](https://www.perl.org/), 22 bytes
```
say((1x$_)**2)for 1..9
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJDw7BCJV5TS8tIMy2/SMFQT8/y//9/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online")
Using Jenny\_mathy's formula to save a lot of bytes.
[Answer]
# PHP, ~~38~~ 37 bytes
```
for(;$i<9**8;)echo(($i.='1')**2)."
";
```
with warnings
# PHP, ~~42~~ 41 bytes
```
for($i=0;$i<9**8;)echo(($i.='1')**2)."
";
```
without warnings
[Answer]
# Javascript 66 bytes
Returns an array of strings representing the numbers in the sequence (necessary because 12345678987654321 is too large to be accurately represented as an int in Javascript)
```
o=>Array(9).fill``.map(x=>(x+(n=n*10+1)*n).replace(0,1),n=0)
```
## Explanation
```
o=> // o is unused input (saves 1 byte vs ())
Array(9) // create an array of length 9
.fill`` // fill it with empty strings
// we must fill it with something, because map skips
// empty entries
.map( // loop over the array and return a new array with the
// values returned by the callback
x=>( // x is the element in the array
(x+(n=n*10+1)*n) // make n 1, 11, 111, 1111, etc, and get the string
// value of n^2
.replace(0,1) // replace 0's with 1's (necessary for
// 12345678987654321, because
// 111111111^2 = 12345678987654320 in javascript)
),
n=0 // n^2 is the rhombus number at each stage
)
```
] |
[Question]
[
You may write a program or function that receives an *odd, positive integer* `n`, where `n >= 3`, as either a function argument, command line arguments, or on STDIN (or equivalent for your system), and prints to STDOUT (or system equivalent) an ASCII spiral that spins inward clockwise where the **top** edge is exactly `n` characters long. The first right edge should be `n+1` characters long, obviously. For instance,
## Input:
11
## Output:
```
***********
*
********* *
* * *
* ***** * *
* * * * *
* * * * * *
* * *** * *
* * * *
* ******* *
* *
***********
```
## The catches:
* Your program must use no more than [`O(log n)` memory](https://stackoverflow.com/a/8229063/1768232).
* Your program may only print the characters `*` (ASCII 42), (ASCII 32), `<CR>` (ASCII 13) and `<LF>` (ASCII 10).
* Your program must print the string, not return it from the function.
* The Big-O restriction is only on **memory**, there are **no** restrictions on **runtime**.
* A trailing newline is optional.
* If your language does not support large integer types, you do not have to support higher than what it does support, but you may not use this as a trick to say "oh, well, I don't have to support above X so I can just make a huge array the maximum size every time"
Standard loopholes are banned, as usual.
[Answer]
# C, ~~125~~ 121 bytes
**Golfed version** This has no variable `k`. The variable `k` is used in the ungolfed version just to aid readability. Also `for` loop conditionals are rearranged and one set of unnecessary `{}` removed. Another set of `{}` can be removed by migrating `puts("")` inside the brackets of the `j` loop in the initialization position, but this would mean a newline at the beginning of the output, so I haven't done it.
```
f(n){int i,j;n/=2;for(i=-n-2;i++-n-1;){if(i){for(j=-n-1;j++-n;)putchar(32+10*(n+(j*j<i*i?i:j+(i!=j|i>0))&1));puts("");}}}
```
Prints an `n` wide by `n+1` high spiral like the example.
**Explanation**
Basically I halve the value of `n` (rounding down) and run two loops: an outer one `i` from `-n/2-1` to `n/2+1` to print the rows (`i=0` is suppressed so we get `n+1` rows) and an inner one `j` from (`-n/2` to `n/2` to print the characters.) We use `expression & 1` to print stripes, and the condition `j*j<i*i` to decide whether to print vertical or horizontal stripes (vertical at the sides where absolute magnitude of `i` is larger, and horizontal at the top and bottom.) An adjustment `+n` is required to help with the correct termination depending on whether `n/2` is odd or even.
`k` is normally 1, and provides an adjustment for the fact that the absolute values of `i` range from 1 to `n/2+1` while the absolute values of `j` range from 0 to `n/2`. If `k` was always 1 we would get concentric rectangles, but it is inverted to 0 when `i==j&i<=0` so that a diagonal row of cells is inverted, producing the spiral.
**ungolfed in test program**
```
f(n){
int i,j,k;
n/=2;
for(i=-n-1;i<=n+1;i++){
if(i){
for(j=-n;j<=n;j++){
k=i!=j|i>0;
putchar(32+10*(n+(j*j<i*i?i:k+j)&1));
}
puts("");
}
}
}
int m;
main(){
scanf("%d",&m);
f(m);
}
```
**Output**
```
11
***********
*
********* *
* * *
* ***** * *
* * * * *
* * * * * *
* * *** * *
* * * *
* ******* *
* *
***********
9
*********
*
******* *
* * *
* *** * *
* * * * *
* * * *
* ***** *
* *
*********
3
***
*
* *
***
1
*
*
```
[Answer]
# C, 118 bytes
```
m,p,x,y,d;f(n){for(m=n++/2;p<n*n;x=p%n-m,y=p++/n-m,d=y==x+1&x<0,y-=y>0,d+=x*x>y*y?x:y,putchar(x>m?10:(d+m)%2?32:42));}
```
Code before final golfing:
```
#include <stdio.h>
int m, p, x, y, d;
int f(int n) {
for (m = n++ / 2; p < n * n; ) {
x = p % n - m;
y = p++ / n - m;
d = y == x + 1 && x < 0;
y -= y > 0;
d += x * x > y * y ? x : y;
if (x > m) {
putchar(10);
} else if ((d + m) % 2) {
putchar(32);
} else {
putchar(42);
}
}
return 0;
}
```
The key observation is that the pattern is *almost* a series of concentric squares. With a couple of slight wrinkles:
* The y-size is one larger than the x-size. This is corrected by subtracting 1 from y for the lower half, which essentially repeats the middle row.
* To turn the rectangles into a spiral, the pixels along the `y = x + 1` diagonal need to be inverted up to the middle of the shape.
For the rest, the code is simply looping over all positions, calculating the Chebyshev distance from the center for each position, and emitting one of the two characters depending on the distance being even or odd. And emitting a newline for the last position of each line.
Since there are only a few scalar variables, and characters are emitted one by one, memory usage is obviously constant.
[Answer]
# C++, 926 bytes
```
#include<iostream>
#include<string>
#include<math.h>
#define S string
using namespace std;S N(S x,int y){S z="";for(int q=0;q<y;q++){z+=x;}return z;}int main(){int n=0,t=0,g=0,fi=1;cin>>n;int t1[]={0,0,n,0};int t2[]={0,n-2,n-2,1};for(int k=0;k<n+1;k++){if((k>(n-2)/2)&&(k<(n+5)/2)){if(g==0){S d,e;if(!((n+1)%4)){cout<<N("* ",t2[0])<<" *"<<N(" *",t2[0])<<endl<<N("* ",(n+1)/2)<<endl<<N("* ",t2[0])<<"***"<<N(" *",t2[0])<<endl;t2[2]=n-8-(n-11);t1[2]=n-4-(n-11);t1[0]--;t2[3]--;t1[3]-=2;}else{cout<<N("* ",t1[0])<<"***"<<N(" *",t2[0])<<endl<<N("* ",(n+1)/2)<<endl<<N("* ",t1[0])<<"* "<<N(" *",t2[0])<<endl;t2[0]--;t1[2]+=2;t2[2]+=6;t1[3]--;t2[1]-=2;t2[3]-=2;}fi=0;}g=5;}else{t=1-t;int*tR;tR=t?t1:t2;cout<<N("* ",tR[0])<<N(t?"*":" ",tR[2])<<N(" *",tR[3])<<endl;if(fi){if(t){t1[0]+=k==0?0:1;t1[2]-=k==0?2:4;t1[3]++;}else{t2[0]++;t2[2]-=4;t2[3]++;}}else{if(t){t1[0]--;t1[2]+=4;t1[3]--;}else{t2[0]--;t2[2]+=4;t2[3]--;}}}}return 0;}
```
This is not elegant, but it doesn't take up much memory for large n. Furthermore, there are (almost certainly) about 20 characters that can be further golfed, but I can't stand to look at it anymore.
### Short Explanation:
This splits the lines in the spirals into two types: the ones with \*\*\*\*\*\* in the middle, and the ones with \s\s\s\s\s in the middle. Then it is clear that each line is composed of several "\* "s, the middle, and some " \*". Figuring out exactly how many of each thing is simple if you look at the pattern for long enough. The tricky thing was printing the center of the spiral which I basically hard coded using a conditional. This ended up being useful because the \*\*\* and \s\s\s lines switch being odd/even there.
### Tests:
**Input:** `55` (I think the big ones look coolest)
**Output:**
```
*******************************************************
*
***************************************************** *
* * *
* ************************************************* * *
* * * * *
* * ********************************************* * * *
* * * * * * *
* * * ***************************************** * * * *
* * * * * * * * *
* * * * ************************************* * * * * *
* * * * * * * * * * *
* * * * * ********************************* * * * * * *
* * * * * * * * * * * * *
* * * * * * ***************************** * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * ************************* * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * ********************* * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * ***************** * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * ************* * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * ********* * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * ***** * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * {-- my program adds a space here btw
* * * * * * * * * * * * * *** * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * ******* * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * *********** * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * *************** * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * ******************* * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * *********************** * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * *************************** * * * * * * *
* * * * * * * * * * * * * *
* * * * * * ******************************* * * * * * *
* * * * * * * * * * * *
* * * * * *********************************** * * * * *
* * * * * * * * * *
* * * * *************************************** * * * *
* * * * * * * *
* * * ******************************************* * * *
* * * * * *
* * *********************************************** * *
* * * *
* *************************************************** *
* *
*******************************************************
```
**Input:** `3`
**Output:**
```
***
*
* *
***
```
Note: I am not a computer scientist/CS student, and I don't know how to prove that this uses O(log n) memory. I can only work out what to do based on the links in the question. I would be grateful if someone could confirm/deny if this answer is valid. My logic for this answer's validity is that it never stores any variable of size based on n except the input itself. Instead, a for loop that runs n times computes integer values based on n. There are the same number of those values regardless of the input.
Note2: This doesn't work for n=1 because of my method of dealing with the middle. This would be easy to fix with conditionals, so if anyone is within a few characters of my answer, I'll fix it ;)
[Play with it on ideone.](http://ideone.com/jRF9Ie)
[Answer]
# Haskell, 151 bytes
```
(#)=mod
f n=[[if y<= -(abs$x+1)||y>abs x then r$y#2/=n#2 else r$x#2==n#2|x<-[-n..n]]|y<-[-n-1..n+1],y/=0]
r b|b='*'|1<2=' '
p=putStr.unlines.f.(`div`2)
```
Usage example:
```
*Main> p 9
*********
*
******* *
* * *
* *** * *
* * * * *
* * * *
* ***** *
* *
*********
*Main> p 11
***********
*
********* *
* * *
* ***** * *
* * * * *
* * * * * *
* * *** * *
* * * *
* ******* *
* *
***********
```
Thanks to Haskell's laziness this runs within constant memory. It uses the obvious approach, i.e. looping over `y` and `x` and choosing between `*` and , depending on
* if the current position is above or below a diagonal
* `x` resp. `y` is even or odd
* `n/2` is even or odd
[Answer]
# Common Lisp - 346
```
(lambda(n &aux(d 0))(tagbody $ #6=(#7=dotimes(i n)#4=(princ"*"))#2=(#7#(i d)#5=(princ" ")#4#)#3=(terpri)#1=(#7#(i d)#4##5#)(when(> n 0)(#7#(i(1- n))#5#)#4#)#2##3#(when(> n 3)#1##4##4#(incf d)(decf n 4)(go $))(go /)@(decf d)(incf n 4)(when(> n 3)#2##5##4##3#)/ #1#(when(> n 0)#4#)(when(> n 1)(#7#(i(- n 2))#5#)#4#)#2##3##1##6#(when(> d 0)(go @))))
```
Iterative solution with constant memory usage. The above makes heavy uses of `#n=` and `#n#` reader variables. Even though there are more direct approaches, here I started with a recursive function and modified it to simulate recursion with `goto` statements: this is probably unreadable.
[Output for all input values from 0 to 59](http://pastebin.com/raw.php?i=mYtCzruY).
### Original recursive version, with debugging informations
(note: `terpri` means `newline`)
```
(defun spiral (n &optional (d 0) )
(flet ((prefix ()
(format t "~4d~4d | " n d)
(dotimes (i d)
(princ "a ")))
(postfix ()
(dotimes (i d)
(princ " b"))))
(when (= d 0) (prefix))
(dotimes (i n) (princ "c"))
(postfix)
(terpri)
(prefix)
(when (> n 0)
(dotimes (i (1- n)) (princ " "))
(princ "d"))
(postfix)
(terpri)
(when (> n 3)
(prefix)
(princ "**")
(spiral (- n 4) (1+ d))
(postfix)
(princ " f")
(terpri))
(prefix)
(when (> n 0)
(princ "g"))
(when (> n 1)
(dotimes (i (- n 2)) (princ " "))
(princ "h"))
(postfix)
(terpri)
(prefix)
(dotimes (i n) (princ "i"))
))
```
For example:
```
(spiral 8)
8 0 | cccccccc
8 0 | d
8 0 | **cccc b
4 1 | a d b
4 1 | a ** b b
0 2 | a a b b
0 2 | a a b b
0 2 | a a b f
4 1 | a g h b
4 1 | a iiii f
8 0 | g h
8 0 | iiiiiiii
```
See also [this paste with all results from 0 to 59](http://pastebin.com/raw.php?i=appixiaq) (not the same as above, this one is more verbose).
### Iterative version, with debugging informations
```
(defun spiral (n &aux (d 0) )
(flet ((prefix ()
(format t "~4d~4d | " n d)
(dotimes (i d)
(princ "a ")))
(postfix ()
(dotimes (i d)
(princ " b"))))
(tagbody
step-in
(when (= d 0) (prefix))
(dotimes (i n) (princ "c"))
(postfix)
(terpri)
(prefix)
(when (> n 0)
(dotimes (i (1- n)) (princ " "))
(princ "d"))
(postfix)
(terpri)
(when (> n 3)
(prefix)
(princ "**")
(incf d)
(decf n 4)
(go step-in))
(go skip)
step-out
(decf d)
(incf n 4)
(when (> n 3)
(postfix)
(princ " f")
(terpri))
skip
(prefix)
(when (> n 0)
(princ "g"))
(when (> n 1)
(dotimes (i (- n 2)) (princ " "))
(princ "h"))
(postfix)
(terpri)
(prefix)
(dotimes (i n) (princ "i"))
(when(> d 0)(go step-out)))))
```
[Answer]
# CJam, 72 bytes
```
li_2/:M;)__*{1$mdM-\M-_2$)=2$0<*@_*@_0>-_*e>mQ_M>2*@@+M+2%+'#S+N+N+=o}/;
```
This is fairly direct conversion of my C solution to CJam. Not as short as you would normally expect from a CJam solution, but this one really suffers from the memory restriction. The common benefits of building up results on the stack that gets dumped automatically at the end, and using fancy list/string operations, all go out the window. This generates and outputs the solution one character at a time. The stack only contains a few integers at runtime, and is empty at the end.
Even though it's not a great display of using a golfing language, it's still considerably shorter than the C code just because the notation is more compact.
Explanation:
```
li Get input n.
_2/ Calculate n/2.
:M; Store it in variable M
)__* Calculate (n+1)*(n+1), which is the total number of output characters.
Also keep a copy of n+1 on the stack.
{ Start loop over output character positions.
1$md Calculate divmod of position with n+1. This gives y and x of position.
M- Subtract M from x.
\M- Subtract M from y.
_ Copy y.
2$) Calculate x+1.
= Check if y == x+1
2$0< Check if x < 0.
* Multiply the two check results. This is the result of the flip
condition for the top-left diagonal to turn the rectangles into a spiral.
@_* Calculate x*x.
@_ Get y to top of stack, and copy it.
0>- Subtract 1 from y if it is in the bottom half.
_* Calculate y*y.
e> Take maximum of x*x and y*y...
mQ ... and calculate the square root. This is the absolute value of the
larger of the two.
_M> Check if the value is greater M, which means that this is the
position of a line end.
2* Multiply by 2 so that we can add another condition to it later.
@ Get result of diagonal flip condition to the stack top.
@ Get max(x,y) to the top.
+M+ Add the two, and add M to the whole thing. This value being even/odd
determines if the output is a # or a space.
2% Check if value is odd.
+ Add to line end condition to get a single ternary condition result.
'#S+N+N+
Build string "# \n\n".
= Use the condition result to pick the output character out of the string.
o Output the character.
}/ End loop over output characters.
; Pop n+1 value off stack, to leave it empty.
```
] |
[Question]
[
The goal is to write a program (anything except explicit brainfuck) which prints [Barney Stinson](http://en.wikipedia.org/wiki/Barney_Stinson)'s best rule:
>
> New is always better.
>
>
>
when interpreted normally, but
>
> Legen... wait for it... dary!
>
>
>
When processed with a Brainfuck interpreter.
May the most popular bro win. You have 72 hours to be legendary.
[Answer]
## C#
So I decided to get a little more... creative with my entry. The Brainfuck code is embedded into the C# as the various operators (not in comments or in hardcoded strings), while the C# code itself operates on a similar principal to the way Brainfuck prints characters (meaning there are no hardcoded strings, and C# generates each individual character as an integer then casts it to a char when printing).
I'm sure I could have made this more elegant, but it took me long enough to finish as it is.
Everything was tested on [this JavaScript Brainfuck interpreter](http://www.iamcal.com/misc/bf_debug/) by [Cal Henderson](http://www.iamcal.com/) and with Visual Studo 2012's C# compiler (targeted at .NET framework v4.0).
```
using System;
namespace Polyglot
{
internal static class Program
{
private static void Main()
{
var a = new short[50];
short _1 = 72;
short _2 = 0;
short _3 = 0;
short _4 = 0;
short _5 = 0;
short _6 = 0;
short _7 = 97;
short _8 = 0;
short _9 = 0;
short _10 = 0;
short _11 = 0;
short _12 = 0;
short _13 = 0;
short _14 = 0;
short _15 = 0;
short _16 = 46;
short _19 = 0;
short _20 = 0;
short _21 = 0;
if( 0 >= 0 )
{
++_1;
++_1;
++_1;
++_1;
}
a[ -1 < 0 ? 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 : 0 + 1 > 1 ? 0 : 0 ] = 9001;
if( 7 < 42 )
{
++_1;
++_1;
}
Console.Write( (char)_1 );
_2 = 101;
_1 += 1 + 1 + 1 + 1 + 1;
_3 = 42 > 7 ? 110 + 9 : 1 + 1;
a[ -1 < 0 ? 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 : 0 > 0 ? 0 : 0 ] = 9001;
if( 1 < 2 )
_4 = 32;
Console.Write( (char)_2 );
++_1;
_5 = 105;
Console.Write( (char)_3 );
--_1;
_6 = 115;
Console.Write( (char)_4 );
++_1;
++_1;
++_1;
_1 += 1 + 1 + 5;
Console.Write( (char)_5 );
--_1;
--_1;
if( 42 > 41 )
{
++_1;
++_1;
++_1;
}
a[ -1 < 0 ? 0 : 10 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 > 5 ? 0 : 0 ] = 9001;
if( 42 < 9001 )
Console.Write( (char)_6 );
Console.Write( (char)_4 );
Console.Write( (char)_7 );
if( 12 > 11 && 11 > 10 )
{
_8 = 108;
_9 = _3;
}
else
{
++_1;
++_1;
++_1;
}
a[ -1 < 0 ? 1 + 1 + 1 + 1 + 1 + 1 : 1 > 2 ? 0 : 0 ] = 9001;
if( _4 < _1 )
{
++_1;
Console.Write( (char)_8 );
}
else if( _4 > _19 && _2 > _20 )
{
++_21;
++_21;
++_21;
++_21;
++_21;
_21 += (short)( _21 + 36 );
}
a[ -7 < 9 ? 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 : 4 > 8 ? 9 : 9 ] = (short)( 12 < 10 ? -_4 : _9 );
Console.Write( (char)_9 );
if( _4 > _9 )
{
++_1;
++_1;
++_1;
}
a[ -9 < 7 ? 10 - 1 - 1 - 1 - 1 : 6 > 7 ? 0 : 0 ] = _21;
if( 1 < 0 )
return;
else
{
++_1;
Console.Write( (char)_7 );
}
_10 += 5 + 4 + 1 + 2 + 8 + 9 + 1 + 91;
Console.Write( (char)_10 );
if( 10 > _4 ) ++_21; else a[ -0 < 0 ? 5 + 6 + 1 + 2 + 3 + 9 : 1 > 2 ? 0 : 9 ] = 50;
if( _21 <= _4 )
_11 = 58 + 57;
Console.Write( (char)_11 );
if( _2 <= _8 )
Console.Write( (char)_4 );
else if( 1 >= 2 )
return;
else if( 42 >= _4 )
_1 += ++_21;
else
{
a[ -99 < --_1 ? --_1 - _1 : 44 > 12 ? 9 : 7 ] = (short)( _2 < _4 ? _21 : 6 );
throw new Exception();
}
switch( _4 )
{
case 32:
var x = (char)( (short)( _4 + 66 ) );
Console.Write( x );
break;
default: break;
}
_12 += (short)( ++_12 + ( ++_1 ) + 1 + 1 + 1 );
Console.Write( (char)_12 );
_13 += (short)( 39 + 38 + 39 );
Console.Write( (char)_13 );
if( _12 < _13 )
Console.Write( (char)_13 );
if( _13 >= _4 )
{
_14 = (short)( 500 - ( - ( 50 ) ) - ( --_1 ) - 90 - ( -4 ) - 267 );
Console.Write( (char)_14 );
}
switch( _1 )
{
case 52:
_15 += (short)( ++_1 + ( ++_21 ) );
break;
default:
_15 += (short)( 15 + ( ++_1 ) + 2 );
break;
}
Console.Write( (char)_15 );
if( _16 <= 3521 && _21 < _4 )
Console.WriteLine( (char)_16 );
_16 = (short)( Int16.Parse( "54" ) % 2 );
_20 = (short)( Int16.Parse( "99" ) / ( _1 > _4 ? 3 : 0 ) );
_1 = (short)( 02.23 );
if( _16 > 9 || _20 >= 52 )
_1 += (short)( ( ++_1 ) + _21 );
a[ -0 < 0 ? -52 - ( --_20 ) : 1 > 0 ? 1 : 2 ] = (short)( _12 < _19 ? Int16.Parse( "19" ) : 44 );
_12 -= (short)f( --_19 / 19.467d );
if( _12 > _14 )
_19 += (short)( _19 + 1 + _3 + 5 );
a[ -904 < 409 ? 4 + ( ++_4 ) + 4 : 49 > 50 ? 49 : 50 ] = (short)( 50 < 99 ? _4 + 669.2452 : 0 );
if( 44 > ++_4 )
a[ -9 < 6 ? 6 + ( ++_4 ) : 9 > 2 ? 44 : 8 ] = 3;
}
private static double f( double x )
{
return x < 12 ? x + 13.22 : x < 6 ? x + 90.45 : 5555;
}
}
}
```
This is the original Brainfuck code I wrote for this challenge:
```
> +++++ +++
[ - < +++++ ++++ > ]
< ++++ .
+++++
> ++
[ - < +++++ +++++ > ]
< . ++ . -- . +++++ ++++ .
----
> +++++ +
[ - < ----- ----- > ]
< ... >>
+++++ +
[ - < +++++ > ]
< ++ . >>
+++++ +++++ ++
[ - < +++++ +++++ > ] <
- . >
+++++ +
[ - < ---- > ] <
++ . +++++ +++ .
> ++
[ - < +++++ > ]
< + . < . >>
+++
[ - < ----- > ] <
+ . +++++ ++++ . +++ .
< . > ----- ---- . +++++ +++++ + .
<< ... > . >>
++++
[ - < ---- > ] < .
--- . >
++++
[ - < ++++ > ]
< + .
> ++
[ - < +++ > ]
< + . < + .
```
When running the C# code through a Brainfuck interpreter, you end up with the following commands (notice the addition of the square brackets at the beginning, these are from the array declaration and don't do anything, since the cell under the memory pointer in the array will already be 0):
```
[] > +++++ +++
[ - < +++++ ++++ > ]
< ++++ .
+++++
> ++
[ - < +++++ +++++ > ]
< . ++ . -- . +++++ ++++ .
----
> +++++ +
[ - < ----- ----- > ]
< ... >>
+++++ +
[ - < +++++ > ]
< ++ . >>
+++++ +++++ ++
[ - < +++++ +++++ > ] <
- . >
+++++ +
[ - < ---- > ] <
++ . +++++ +++ .
> ++
[ - < +++++ > ]
< + . < . >>
+++
[ - < ----- > ] <
+ . +++++ ++++ . +++ .
< . > ----- ---- . +++++ +++++ + .
<< ... > . >>
++++
[ - < ---- > ] < .
--- . >
++++
[ - < ++++ > ]
< + .
> ++
[ - < +++ > ]
< + . < + .
```
[Answer]
# Smalltalk
```
"adding adding all the time"
"1+1+1+1+1+1+1+1+1+1+1" "is not fine"
"more to come / going far"
"+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1"
"all that work for a single char"
"happy me / a loop to start"
"[>++>+++>++++>+++++<<<<-]"
"was it code or just a fart?"
"adding adding / thats not fine"
"+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1"
">>+" 'New is always better.' "shall I " print
">+.++.--.+++++++++.----------.<<----...<+++++++"
"the garbage here gives us no hint"
".>>+++++++++++.>---.++++++++"
"hurray a change to stop the pain"
".>---------.<<<<.>>"
"the author now has in his brain"
"-----------------.>>-----.+++.<<<<.>>>.>++."
"We all agree the time is here"
"<<<...<.>>--.>--------.>--.+++++++.<<<<."
"to finish this and have a beer"
```
type into a workspace and press "doIt", or send to BF.
BF stolen from the other posters - thanks.
[Answer]
## Javascript / Brainfuck
Ungolfed version as it is not a code-golf contest :
```
var outputString='';
'+++++++@++++[>++@/+@@>@/+@+@++>++++++@/+>+@++@/+@@+++++@/>@+@+++++@/+++@+<@/<<<<-]>>>@-.>++.+@/+@@.--.>.<-@/.@<@<++...<-.@/>>>>+++++@++++.<-@/-@-.@+@/+@+@+++++@/.>-@--@/.<<<<.>>>@---.>---@/-@@-@/.@+@++.<<<@/<@.@>>>+++@/.@@>@/+@+@.<<<@/...<@.>>>--@/---.---.>--.+++++++.<<<<+.<'
.split('/')
.forEach(function(e) {
var matched=e.match(/[^@]*@/g);
if (matched) {
var asciiCode=0;
for(var i=0;i<matched.length;i++) {
asciiCode=matched[i-0].length-1+10*asciiCode;
}
outputString+=String.fromCharCode(asciiCode);
}
});
alert(outputString);
```
That was the occasion for me to learn BF and that was fun :)
The difficulty was to **never** use `,` as BF interprets it as user input and be sure that byte is 0 before using `[]` for accessing elements of arrays.
The JS encoding is pretty simple, each strings before `/` encode a character and each string length before `@` defines ASCII code in decimal. (`+++++++@++++[>++@` = `78` = `N`)
You can test Brainfuck here : <http://copy.sh/brainfuck/>
[Answer]
# [Cubically](https://github.com/Cubically/cubically) ([TIO](https://tio.run/##VU7NCsMgDH6gkAztmkOR4HuMHbaeBr3usKd3SYzSBpTvzy/u3/dnfx3HrzVYId2S3kvlLTtSpTJk5aty00fGHWUjd82E6rh7oSyPynIOyHaPBn0J07oUmrq4arj7ur3Y4NNdcjFjZRagsS1RZUSS06@t1rFusyFBHSIS6EOlAEzs5qSWJRGyvYZw2CE6smN9kdJAZGnW6Bdb@wM)) / BF ([TIO](https://tio.run/##VU5LCgIxDD1QSKQdJ4uhhN5DXKggiOBC8Pw1SdMyE2h5v770/r29Ps/f490arJBOSe@l8pYdqVIZsvJVuekj446ykTtmQnXcvVCWS2XZB2Q7R4O@hGkdCk1dXDXcfd1ebPDqLrmYsTIL0NiWqDIiye7XVutYt9mQoA4RCfShUgAmdnNSy5II2V5DOOwQHdmxvkhpILI0a/SLrf0B))
```
+5+1/1+5+3@6:2/1+5+5+1@6+2@6:5/1+3@6:5+1/1+5+5+1@6:5+2/1+5+5+2@6:5/1+3@6:5+2/1+5+5@6:5+5+2@6:2/1+5+53[@6>:5+2/1+5+5@6>:4/1+5+5+3@6+>:5+2/1+55+2@6:5/1+3@6>:5+3/1+55@6>:2/1+551@6<<<<<-]>:5+3./1+552-@66>+.:2/1+5+51.@6--.>:5+1/1+5+5+2@6:1/1+5@6+++++.>----...>+++++++.<<+++++++++.<----.++++++++.>---.>>.<<<---.>-----.+++.>>.<<<+++.>++.>...>.<<<-----.---.>--.+++++++.>>+.
```
*(Updated 8/4/17 to account for language changes in Cubically)*
Basically this just uses as many characters from the BF program as it can in the Cubically program, then sticks the rest of the BF program on the end of it. No forced termination with `&`/`E` in the Cubically program is necessary.
[Answer]
## Python / BrainF\*\*k, 362 chars
BrainF\*\*k code taken from Clément Renaud's deleted answer.
**Edit** - Initial null character no longer printed.
```
t='++++++++++_+++++++|^+++++++|+[>++>+++%>++++>+++++<<<<-||]+++++++++++|*+++++++++++++@+>>+.>+||.++.|--.+++++++++.--|^--------.<<----..._<+++++|++.>|>+++++&++++++.>---.+=+++++++|.>---------.<<^<<.>>--||-----|--~-----|---.>>-----~.+++.<<<<.>|>>.*>++.<<<...<.>>--._>|--------|.>-^-.+++++++.<<<<!!!'
print ''.join((chr(93+len(x))if x else' ')for x in t.split('|'))
```
Uses a very simple trick - `|` characters were added to the BF program, and the distances between them encode the string printed in Python. The Python code is mostly ignored by BF.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/20920/edit).
Closed 7 years ago.
[Improve this question](/posts/20920/edit)
Write a program or function in any language that tells if the input is a prime number.
* The input is a **string** representing a natural number in base-10.
* The output is one of the two strings "Prime" or "Not!!" which correctly identifies the input.
* Arithmetic operators, bit-wise operators, numeric variables and constants, "math-stuff" in general, etc... are not allowed anywhere in your program. You should use **string operations** to do all necessary "calculations".
* You can compare string lengths (which are numbers) - but -10 to your score if you don't.
* Your program should work on any length input (given enough memory and time).
* Lowest byte count (UTF-8) wins.
[Answer]
# Ruby: 52 - 10 = 42
Using a variation of that famous prime-matching regex.
```
puts ?_*gets.to_i=~/^(_|(__+?)\2+)$/?"Not!!":"Prime"
```
Just to be clear: `?_*gets.to_i` is a string operation that appends `"_"` to itself *n* times, where *n* is the input number. As I see it no string lengths are compared, so that should satisfiy the 10 character bonus criterium.
[Answer]
## Ruby, 64 - 10 = 54
```
puts ('1
'..gets).map{?1}*''=~/^1?$|^(11+?)\1+$/?'Not!!': :Prime
```
This iterates from the string '1' (plus a newline) to the input string, using Ruby's built in string iteration method which looks an awful lot like adding 1, but which doesn't technically create a high-level numeric variable at any point. It uses the fact that there will be n iterations for an input of n to create an n-length string, then uses a regular expression to determine if that string can be grouped into identical substrings.
[Answer]
## Perl 52-10=42
**Implementation**
```
print((('-'x$ARGV[0])=~/^.$|^(..+?)\1+$/)?Not:Prime)
```
**Demo**
```
$ seq 1 10|xargs -I{} bash -c "echo -n '{} ' && perl Prime.pl {} && echo"
1 Not
2 Prime
3 Prime
4 Not
5 Prime
6 Not
7 Prime
8 Not
9 Not
10 Not
```
[Answer]
## ECMAScript 6, 159 - 10 = 149
Sounds like a task for regex. I/O with `prompt`/`alert` as usual.
```
for(s=prompt(u=""); /[^0]/.test(s); )
s=s.replace(/(.)(0*)$/,(_,d,t)=>u+="x"," 012345678"[d]+t.replace(/0/g,"9"))
alert(/^((xx+)\2+|x?)$/.test(u)?"Not!!":"Prime")
```
The while loop decrements the decimal number by one each iteration purely by regex. The final regex matches a string consisting of a composite number of x's, by first matching one factor, then another by repeating the first factor one for the rest of the string.
[Answer]
# Javascript 266
```
function N(a){function b(a){return P.every(function(b){if(n=b,i=a.length,j=b.length,j>i) return;if(j==i) return 1;while(n.length<i)n+=b;return n.length!=i})}if(q=A,A!=a)for(;q.length.toString()!=a;)b(q)&&P.push(q),q+=A;console.log(b(q)?"Prime":"Not!!")}A="0",P=[A+A]
```
Creates a function called N which will print the desired result. The unminified version looks like this. I did a hand minify to clean up some variables and then ran that through uglify and then hand minified that again.
```
// A a string of "0" for using to generate long strings
// P is the store for all known primes
A="0", P=[A+A];
function N(val) {
function _isPrime(str) {
// go through all the known primes and return true
// if we don't match on any of them
return P.every(function(prime) {
// prime is some known string whose length is a prime number
tsr = prime, strlen = str.length, primelen = prime.length;
// if the string we're checking has fewer chars than
// this then it's not a prime
if(strlen < primelen) return 0;
// if the string we're checking has the same number of chars
// as the the prime we're checking against then it is a prime
if(primelen == strlen) return 1;
// Keep incrementing our temporary string with the prime we're
// checking. we'll break out of the loop once the temporary string
// is greater than or equal to the string we're testing
while(tsr.length < strlen) {
tsr += prime;
}
return !(tsr.length == strlen)
});
}
// start with a string of one unit
nstr = A
if(A!=val) {
// keep incrementing the string so that we can compile a list
// of known primes smaller than this value
while(nstr.length.toString() !== val) {
if(_isPrime(nstr)) {
P.push(nstr);
}
nstr += A;
}
}
console.log(_isPrime(nstr) ? "Prime" : "Not!!");
}
```
Tested it using this snippet:
```
for(var X=0;X<10;X++) {
console.log('checking: ' + X);
N(X.toString());
}
```
[Answer]
## Bash 66 - 10 = 56
**Implementation**
```
[[ -z `printf %$1s|grep -P "^(..+?)\1+$"` ]]&&echo Prime||echo Not
```
**Demo**
```
$ seq 1 10|xargs -I{} bash -c "echo -n '{} ' && ./Prime.sh {}"
1 Prime
2 Prime
3 Prime
4 Not
5 Prime
6 Not
7 Prime
8 Not
9 Not
10 Not
```
[Answer]
## Python 3, 109-10 = 89
```
print(['Not','Prime'][(lambda i:not any(' '*i==(' '*u)*v for u in range(i)for v in range(i)))(int(input()])
```
Not comparing string lengths, but string inclusion. Cross posted from duplicate [Determine if a number is prime without using arithmetic](https://codegolf.stackexchange.com/q/25445/7258)
] |
[Question]
[
Given \$x\$ distinguishable balls (say they have different colors), sample with replacement repeatedly until all the balls that have been seen, have been seen at least twice.
# Challenge
The input is the integer value \$x \geq 2\$.
The challenge is to compute the probability that you would have seen all the balls when you stop. You can of course stop before then, if for example you sample the same ball the first two times and \$x > 1\$. You should output the probability as an exact fraction. For languages that don't have easy fraction arithmetic, your code can output a sum of fractions instead (e.g. \$1/3 - 23/83 + 14/17\$).
# Examples
If \$x = 2\$ then the only way to stop before seeing both balls is if you sample the same ball twice in a row. This happens with probability \$1/2\$.
The probability for \$x = 3\$ is \$4/9\$.
Why is this? Let us compute the probability that we **don't** see all the balls. There is a \$1/3\$ probability that the same ball is chosen in the first two steps and then we stop. If this doesn't happen, there is then \$2/3\$ probability that we don't select the third ball straight away. In this case we will have selected one ball twice and another one a single time. So now we want to compute the probability that we stop before seeing the third ball. We can write this as a recursive equation. Let \$p\$ be this probability.
\$p = 1/3 + p/3\$. Solving this gives us \$p = 1/2\$. Putting it all together we get \$1/3 + 2/3(2/3 \cdot 1/2) = 5/9\$. To get the desired probability that we do see all the balls we need \$1-5/9\$.
The probability for \$x = 4\$ is \$43/96\$.
The probability for \$x = 5\$ is \$3517/7500\$.
The probability for \$x = 6\$ is \$17851/36000\$.
[Answer]
# [Python](https://www.python.org), ~~100~~ 94 bytes
```
from fractions import*
P=lambda x,d=0:Fraction(d*P((d>1)*x,d-1)+x*P(x-1,d+1),d+x)if x else d>0
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5NCsIwFIT3PcUDN3lpCokrKbRL1z2BEE2jD5of0gjxLG660Tt5GwvWzSy--WDm-Y6PfAt-WV73bJvD52RTcGCTvmQKfgZyMaTMq6GbtDsbDUWYTrbHTWCGD4yZXiFfi0ZhXVZQGiVMrXCNgmShwDjNI5hebis7GxIQkIek_XVke6EkthVATOQzGxgh_tT_sS8)
`x` is the number of balls not sampled yet, `d` the number of balls sampled exactly once. Once a ball has been sampled twice it can be ignored in the further analysis, as drawing it more times effects neither the outcome nor the sampling process.
[Answer]
# [R](https://www.r-project.org/), ~~110~~ ~~100~~ ~~95~~ ~~93~~ ~~91~~ 88 bytes
*-3 bytes thanks to @Giuseppe and @pajonk*
```
`?`=\(y,s=1,`[`=`if`)y[s[(y*(y-1?s+1)+s*(y?s-1))/(y+s),0],1]
f=\(x)MASS::fractions(?x-1)
```
s is the number of balls seen exactly once.
y is the number of balls never seen.
[Try it online!](https://tio.run/##K/r/P8E@wTatNC@5JDM/T6NSp9jWUCchOsE2ITMtQbMyujhao1JLo1LX0L5Y21BTuxjIti/WNdTU1Neo1C7W1DGI1TGM5UpDmFCh6esYHGxllVaUCBYo1rCvAKr/n6ZhrMmVpmECIkxBhJnmfwA "R – Try It Online")
[Answer]
# JavaScript (ES6), 81 bytes
This is based on [ovs' answer](https://codegolf.stackexchange.com/a/267351/58563).
Returns `[numerator, denominator]`.
```
f=(x,d=0,q)=>[P=x?d*f(d>1&&x,d-1)[0]*f(x-1,d+1,q=Q)[1]+x*P*q:d>0,Q=x?(d+x)*q*Q:1]
```
[Try it online!](https://tio.run/##ZctLCsMgEADQfQ8SHD/FabsKaK4Q1@IiZGJpCbE2oXh767Z0@@A9p8@0z@/H61BboqXWaFiRZLTMYKwfTRmIR0YWu665QvA6NCgKJQmU2TjwGEThI889WS1dK4xEAZ656zHUOW17Wpfzmu4ssgvA6Veuf3IDqF8 "JavaScript (Node.js) – Try It Online")
Or with some post-processing to get the simplified fractions: [Try it online!](https://tio.run/##bcsxD4IwEIbhnV9xi6RXilJ1IimMrDA3HQoFoiGUijH991hcHHS44Xvy3l2/9No9bsszna3pt20QxDMjMuZQFLIWvjR0IKbgcRw85SgzFcCnnJmEMycalFwlntbU5abIWBNeiEk8UkebnKutAgFEM2gRRAEtlFCRloGGw0456GjcC7kwcOrTSFjgFKpdMNx3gIqizs6rnfrjZEcykoGcEfEHL//wGnB7Aw "JavaScript (Node.js) – Try It Online")
### Method
Since we don't have native fraction support, we have to compute:
$$\left(\frac{d\cdot p\_0}{q\_0}+\frac{x\cdot p\_1}{q\_1}\right)/(d+x)=\frac{d\cdot p\_0\cdot q\_1+x\cdot p\_1\cdot q\_0}{q\_0\cdot q\_1(d+x)}$$
where \$(p\_0,q\_0)\$ are given by a first recursive call and \$(p\_1,q\_1)\$ are given by a second recursive call.
In the JS implementation, we save the numerator and denominator computed by the last call into the global variables `P` and `Q` respectively.
This allows us to compute the new numerator as:
```
// q0
// |
P = d * f(...)[0] * f(..., q = Q)[1] + x * P * q
// \_______/ \______________/ | |
// [p0, q0][0] = p0 [p1, q1][1] = q1 p1 q0
```
and the new denominator as:
```
Q = (d + x) * q * Q
// | |
// q0 q1
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 54 bytes
```
p(x,d)=if(x,(d*p((d>1)*x,d-1)+x*p(x-1,d+1))/(d+x),d,1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN80KNCp0UjRtM9OAtEaKVoGGRoqdoaYWUFDXUFO7AihQoWuok6JtqKmpr5GiXaGpk6JjqAnVrZyWX6RRoWCrYKSjYKqjUFCUmVcC5Csp6NoBCaBWTU2oUpiFAA)
A port of [@ovs's Python answer](https://codegolf.stackexchange.com/a/267351/9288).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 63 bytes
```
Nθ⊞υ¹Fθ«≔⟦⟧ηF⁻θι⊞η▷”V5⊘?º≦kgmE\0⦃W‹”⟦⁺∧⊖κ×κ↨η⁰×⊕ι§υ⊕κ⁺⊕ικ⟧≔ηυ»υ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVDBSsUwEMTj69UfWHpKIE8UPAieKir0oPQgXkoPabq1oWnqyyYPQfwSL09Q9Jv8GtNaVLzNzuzs7O7zh-qkU6M0u91b8O365HNvP7f3wV-HoUbHNvw0KQJ1LAg4irgdHUQSHpNVRqTvLCsrAV1UVrN0pW0gthGgOYfZ2Am42EoTpMdb6bSsDbK0dVJ5PVo6uFxQKqAsTPRmtmHnqBwOaD02rOcCbvSAxHoBZ5JwmnjI-Q-d299mHdnM57bBh2njv1LPZ8-c8d_S84pPJywnxYAQy6ekcNp6FvEr1YqWD72X6Xpr0url-Lv-Ag) Link is to verbose version of code. Explanation: Another port of @ovs' Python answer, except using dynamic programming instead of recursion and I also replace `d*P((d>1)*x,d-1)` with `(d-1 and d*P(x,d-1))` as that way I can make `P(0,d)=1`.
I wanted to remove the dependence on `fractions.Fraction` as even compressed that takes up 17 bytes but the best I could do was 66 bytes:
```
Nθ⊞υ¹Fθ«≔⟦⟧ηF⁻θι«F‹κ²≔E²μζ≔⟦Σ××⟦κ⊕ι⟧ζ⮌§υ⊕κ×⁺κ⊕ι⊟×ζ§υ⊕κ⟧ζ⊞ηζ»≔ηυ»Iυ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVDLTsMwEBTH5itWPa0l90DFAamnilMkChFwi3JI0y2xGjup165QUb-ES5FA8E18Dc6DCi74YHlndsajefksytwWdV4dj-_erSeXX2e3sWm8u_F6SRa3YhYlnkv0Es7De11bCCA8R6M5s3o0mGYSysCMOmqhjGfcSlCiW-rRa2LGjYRpAAfZIm9wKkELCftWfbK79xoflCYe7jToYlNY0mQcrVCJrJVIuKMdWSacu9is6KlN-HtvI9ojoXdJKt8l-OsU6KRuho_2Ev61yn6Sdn2Uw3Q4FREQH5BDlFhlHF7l7NALMXvjZcFDux_peLKrxtnrRT9_Aw) Link is to verbose version of code.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 36 bytes
```
M?G?Hs*VLV*,HG]+GH,ghGtHgtGH] B1Yg1t
```
[Try it online!](https://tio.run/##K6gsyfj/39fe3d6jWCvMJ0xLx8M9VtvdQyc9w73EI73E3SNWwckwMt2w5P9/YwA "Pyth – Try It Online")
Uses [@ovs](https://codegolf.stackexchange.com/a/267351/73054)'s simplification method. But since no fraction arithmetic, returns a list of fractions to add, each fraction being in the form `[numerator, denominator]`
### Explanation
```
M?G?Hs*VLV*,HG]+GH,ghGtHgtGH] B1Yg1tQ # implicitly add Q
# implicitly assign Q = eval(input())
M # define g(G,H):
?G # if g == 0:
Y # return an empty list
?H # if h == 0:
] B1 # return [[1, 1]]
,ghGtHgtGH # [g(G+1, h-1), g(G-1, H)]
*,HG]+GH # [[H, G+H], [G, G+H]]
V # vectorize (apply to first of each list, then second)
L # map constant pair over list returned by g
*V # vectorized multiplication
s # merge both results into one list
g1tQ # print g(1, Q-1)
```
[Answer]
# [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), 70 bytes
A port of [@ovs' Python answer](https://codegolf.stackexchange.com/a/267351/110802) in Mathematica.
---
Golfed version. [Try it online!](https://tio.run/##NY7BCsIwEETvfsUeW5ui9aaoB/XiLfdlkdBsNZAmkqYSEP312qIe583AvFbFG7cqmloN2RxO3BjHMDIIXPehMw@Gpnd1NN6BhHk@O1pWASUN6fKWb33ZLDe7c4NpW4mD95ZR75ckMg0S/7miJHRZUSExlZXQxQjyRaaLlNMwG2@Pyta9VZFBOQ33YFz8OXS9jR00PnyzclcGXAlY0@Ry8iinMZpyL9EQCXgaAVP/ouED)
```
x_~P~d_:0:=If[x<1,Boole[d>0],(d P[Boole[d>1]x,d-1]+P[x-1,d+1]x)/(d+x)]
```
] |
[Question]
[
# Task
Here is an interesting math problem:
>
> Let's say that there are \$n\$ indistinguishable unlabeled objects in a bin. For every "round", pull \$k\$ objects randomly out of the bin with equal probability, and apply a label on each object (Nothing happens to objects already having a label). Then put these \$k\$ objects, now all labelled, back into the bin and repeat the process until all objects have a label applied to them. What is the expected number of rounds needed to label all the objects, given \$n\$ and \$k\$?
>
>
>
Your task is to write a program that solves this exact math problem. Turns out, this is quite hard to calculate by hand and is better left for computers to bash out. I will list three methods of solving this problem below. You do not have to follow any of these three methods.
# Methods
### Method 1
I have asked this [question](https://math.stackexchange.com/questions/4787756/problem-regarding-coloring-balls-drawn-from-a-bin) on Math SE recently as I was also stumped on how to do this problem. One [answer](https://math.stackexchange.com/a/4789882/743034) suggests the following formula:
$$\sum\_{j=1}^n (-1)^{j+1} \binom{n}{j} \frac{1}{1-\binom{n-j}{k}/\binom{n}{k}}$$
I have implemented this formula in Python: [Try it online!](https://tio.run/##LczLDoIwEAXQ/XzFXU55BBo2xoQlH4IKQkmnzVgXfn0FdHkfOfGTliDdJWrOswYPP6YFq49BE@7B34ge04yBpdrMlTDKCz1awhwUDqtAR3lObCsp7XE4H2UPrq0pCnZ7i@KUdsKZhm39C7XbxeY/bMYQdEpvlQMgirpK4oFtW3XG5PwF "Python 3.8 (pre-release) – Try It Online")
### Method 2
Another [answer](https://math.stackexchange.com/a/4787849/743034) from the same question provides the following formula:
$${\bf e\_1}^T \left(I\_n - \left({\mathcal{1}}\_{j\geq i} {\frac{ {{n-i \choose j-i}} {i \choose k-j+i} }{n\choose k}} \right)\_{i=0,j=0}^{n-1} \right)^{-1} {\bf 1}$$
where "\$I\_n\$ is the \$n \times n\$ identity matrix, \$\bf e\_1\$ is the first standard basis vector of \$\mathbb{R}^n\$ and \${\bf1}\$ is the \$n\$-vector of all ones. And in the definition of the other matrix \$\mathcal{1}\$ is the indicator function, i.e. the \$i,j\$-element is \$0\$ if \$j<i\$ and otherwise that quotient of binomials...," quoting from the linked answer.
I have implemented this formula in Mathematica: [Try it online!](https://tio.run/##RYwxC8IwEIV3f8XNesEGNyEObl3EodtxlCgpXtqkUIOL@NvjudS3fe99vOTLIyRf5O5rHSj3OPYMRwcX6ubiJ2rzKyzPQJ2/TYHagcS5iGARGjaK8eQE4Sx5TqJ6NkrRCG/XSovRxJ3w/m/hyL8DhLeuDUI29qMQV2AmsqzZXBfJhQayDR6Ya/0C "Wolfram Language (Mathematica) – Try It Online")
### Method 3
(This is very likely not the golfiest way for any language, but this is what I used to generate the larger test cases.)
Another way is to utilize the recursive nature of this problem, as the results of each round depends on the results of all the previous rounds. The recursive formula is as follows (\$E\$ is the function that actually calculates the expected value):
$$\begin{align}E(n,k)&=f(n,k,n)\\f(n,k,u)&=\begin{cases}0&\text{if }u=0\\\frac{\displaystyle\binom nk+\sum\_{i=1}^{\min(u,k)}{\binom ui\binom{n-u}{k-i}}f(n,k,u-i)}{\displaystyle\binom nk-\binom{n-u}k}&\text{otherwise}\end{cases}\end{align}$$
I have implemented this formula in Python: [Try it online!](https://tio.run/##TY5BDoMgEEX3nGKWUCCVuGmadOkpDAvbaiXKQKaw6Okp6sbZ/fz3Xyb@0hywvUUqZaLgwQ9pBudjoASv4J@MvccJOo5qEXcGKzygbyyDKRBkcAg04GfkRqE0G1AJWRG@bfcRSPhmf@SsnIALHJ3OatF7Xvusnd2V7qz0DnmWRi1VXe96kuqTRIj6D40pE1aVNpaxSA4T77hpVCtEKX8 "Python 3.8 (pre-release) – Try It Online")
# I/O format and other rules
Your program or function should take in two positive integer values \$n,k\$ with \$n\ge k\$ and output the expected value corresponding to those values. The output can be a floating point value with an absolute/relative error under \$10^{-6}\$ from the true value, though the algorithm should **theoretically work** for arbitrarily large \$n\$ and \$k\$. In practice, it is acceptable if the program is limited by time, memory, or data-type size. This means that although your program may output inaccurate floating point values for certain inputs (as long as the outputs are within the allowed error as mentioned earlier), it should still theoretically be calculating the exact value of the true output.
Because the expected value is always going to be a rational number, you can also output as an exact fraction (does not need to be simplified and can be improper), if your language supports such a data type, or if you want to output a pair of numbers, the numerator and the denominator. If in doubt, always refer back to the [default I/O methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/).
Your program should also be **deterministic**, meaning it should always produce the same value when ran. Namely, no "running a gazillion simulations to get the experimental expected value."
# Test Cases
```
n,k -> output
1,1 -> 1
4,2 -> 3.8
6,2 -> 6.928571428571428571428571429
7,4 -> 3.779411764705882352941176471
7,7 -> 1
8,1 -> 21.74285714285714285714285714
8,5 -> 3.458181818181818181818181818
10,3 -> 9.046212999306305594338048699
12,7 -> 4.212148576244657154897357173
20,2 -> 35.30473485789483826080766262
100,7 -> 72.28020367501059456930677280
1000,69 -> 105.2447804224750397369209265
1256,5 -> 1934.893442395300917211652090
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 10 bytes
-3 thanks to @alphalpha
```
Ýsc¤/<z¹F¥
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m73MwDQxyTB1wYKlpSVpuhbrDs8tTj60RN-m6tBOt0NLlxQnJRdDpRYsNucygTAB)
Uses a variant of the first method. Ports [this](https://codegolf.stackexchange.com/a/229775/92727) Jelly answer for the binomial transform.
```
Ý calculate [0,1,...,n]
s swap so k is on top
c calculate [0Ck, 1Ck, ..., nCk]
¤ push the last item without poping
/ divide by it
< subtract one
z and inverse. Luckily for us, 05AB1E have 1/0 = 0
¹F¥ calculate the binomial transform, by calculating the differences n times.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~48~~ 42 bytes
```
NθNηIΣEθ∕Π⁺±⊕…ιθ⁻θ…⁰η×Π…·¹⁻θι⁻Π⁻ι…⁰ηΠ⁻θ…⁰η
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZC_DgFBEMZpPcVGNZushGgkShoFuaATxdobbpK75fbPvYxGQXgmT2NjkcN033zf95tkjjeVSaP2Mj-dLt5tO4N7szHRB-9mvtiggZIPW3WdBZ0Y0g5G0jpY-AKm8gClYGOqKEVIzD71ykGSewsz3EmHMNHKYIHaYQpzqXcIJFjJORdsSjrkQj3uu4Jl_GksqUD7oQVC4FGFMdarFanGecejoh-qYN_-39U4w7PdKPt6x3XV7lR5e33udVv9uHoA) Link is to verbose version of code. Explanation: Implements a modification of a formula used by several other answers:
$$ \sum\_{i=1}^n\frac{-i\choose 1-i+n}{\left(\frac{i-1\choose k}{n\choose k}-1\right)} $$
$$ = \sum\_{i=1}^n\frac{{-i\choose n-i+1}{n\choose k}}{{i-1\choose k}-{n\choose k}} $$
$$ = \sum\_{i=0}^{n-1}\frac{{-1-i\choose n-i}{n\choose k}}{{i\choose k}-{n\choose k}} $$
$$ = \sum\_{i=0}^{n-1}\frac{\prod\_{j=i+1}^n(-j)\prod\_{j=0}^{k-1}(n-j)}{\prod\_{j=1}^{n-i}j\left(\prod\_{j=0}^{k-1}(i-j)-\prod\_{j=0}^{k-1}(n-j)\right)} $$
Previous 48-byte answer:
```
NθNηIΣEθ∕×X±¹ιΠ⁻θ⁺…⁰η…⁰⊕ι×Π…·¹⊕ι⁻Π⁻θ…⁰ηΠ⁻⁻θ⊕ι…⁰η
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZC9CsIwFIVx9SmC0y1EsbgIjro4WIq6iUNMrzbQpjU_9WFcOlT0mXwaoy2l2AshnHC-cy65v3jMFM9YUpYPa87j-XswWcvcmsCmJ1Rw9RbDro6dDpWQBpZMG9jZFDYshyslK1GICGEvUtQQZjdnDvDCDILvUSLcCVUWWW5gI6TVXyRM3L1l8oIwpSR2llasJVeYojQYgfB-Q0mT3cQ4i-NFgTXk9yFK6qpecafT6y3Wuv7i_rBmFpU-cd183vMwGhfJ6Fj50-GsfvoA) Link is to verbose version of code. Explanation: Implements a modification of Method 1:
$$ \sum\_{j=1}^n (-1)^{j-1} \binom n j \frac 1 {1 - \binom {n-j} k / \binom n k} $$
$$ = \sum\_{j=1}^n \frac {(-1)^{j-1} \binom n j \binom n k} {\binom n k - \binom {n-j} k} $$
$$ = \sum\_{j=1}^n \frac {(-1)^{j-1} \frac {n!} {j! (n-j)!} \frac {n!} {(n-k)!}} {\frac {n!} {(n-k)!} - \frac {(n-j)!} {(n-j-k)!}} $$
$$ = \sum\_{j=1}^n \frac {(-1)^{j-1} \prod\_{i=n-j+1}^n i \prod\_{i=n-k+1}^n i} {\prod\_{i=1}^j i (\prod\_{i=n-k+1}^n i - \prod\_{i=n-j-k+1}^{n-j} i)} $$
$$ = \sum\_{j=1}^n \frac {(-1)^{j-1} \prod\_{i=0}^{j-1} (n-i) \prod\_{i=0}^{k-1} (n-i)} {\prod\_{i=1}^j i (\prod\_{i=0}^{k-1} (n-i) - \prod\_{i=0}^{k-1} (n-j-i))} $$
$$ = \sum\_{j=0}^{n-1} \frac {(-1)^j \prod\_{i=0}^j (n-i) \prod\_{i=0}^{k-1} (n-i)} {\prod\_{i=1}^{j+1} i (\prod\_{i=0}^{k-1} (n-i) - \prod\_{i=0}^{k-1} (n-j-i-1))} $$
It's then possible to factor the \$ (-1)^j \$ into the following product and then switch the operands of the subtraction in the denominator to correct the sign:
$$ = \sum\_{j=0}^{n-1} \frac {\prod\_{i=0}^j (i-n) \prod\_{i=0}^{k-1} (n-i)} {\prod\_{i=1}^{j+1} i (\prod\_{i=0}^{k-1} (n-j-i-1) - \prod\_{i=0}^{k-1} (n-i))} $$
However this only reduces the code to 45 bytes:
```
NθNηIΣEθ∕Π⁺⁻θ…⁰η⁻…⁰⊕ιθ×Π…·¹⊕ι⁻Π⁻⁻θ⊕ι…⁰ηΠ⁻θ…⁰η
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FrcYZTzzCkpL_Epzk1KLNAo1rbmQ-RlAfkBRZl6JhnNicYlGcGmuhm9igUahjoJLZllmSqpGQFF-SmlyiUZATmmxhm9mHpAESgYl5qWnahjoKGRoauooQIThYp55yUWpual5JakpGpkg-UJNEBmSmZtaDDcPqAhoYmZZKkSbIYY2uLkwHRAe3AkYtiC7CchF1YbmZhiwXlKclFwMDarl0Uq6ZTlKsUsMDbiMIUIA) Link is to verbose version of code.
Substituting \$ i = n - j - 1 \$ then results in the final formula used by the 42-byte solution.
[Answer]
Tried all three methods, with some minor changes to each for golfiness. In order:
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes
```
b[i=-Range@#,++i+#].(b[-i,#2]/b@##-1)^-1&
b=Binomial
```
[Try it online!](https://tio.run/##JcrBCsIgGADgu6/xw6j8LRyjdTGkB4iooxjo2NYPaRDeZHt1a@z0Xb7g0qsPLlHnyqCKN6TE3cWx14CcEwe733gjCKG2B68BhNw@hayYVxeKn0DuXW5fismAOF/1btAabDU/OhfnzLJEOSHLDdYLx5UWm5V24fQvbCo/ "Wolfram Language (Mathematica) – Try It Online")
Shortest by a long shot.
$$E(n,k)=\sum\_{i=1}^n{-i\choose 1-i+n}\left(\frac{i-1\choose k}{n\choose k}-1\right)^{-1}.$$
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 82 bytes
```
Tr@Last@Inverse@Table[Boole[i==j]-b[#-i,#2-i+j]i~b~j/b@##,{i,#},{j,#}]&
b=Binomial
```
[Try it online!](https://tio.run/##JY2xCoMwFEX3/EbAoY0URWqXlOBWKKVQN8nwIpG@oBE0dAnm19OIyzlwuZc7gfvqCRz2EAce20U8YXXiYX96WbVoQY26a@Y5ETk3MlcdzZHRMsezkRhUMBclKGU@hRvzJlFmRPEG7TwhjPG9oHVpdH@J0yAElVn49GCDJ75gxcaIr1i563qoZtWhetctVcgW0@cf "Wolfram Language (Mathematica) – Try It Online")
Reversed both axes of the matrix, summing the last row instead.
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~85~~ ~~83~~ 82 bytes
```
{n,k}Check[1/Tr[m=b[#,i=Range@#]b[n-#,k-i]],0](n~b~k+m.#0/@(#-i))&@n
b=Binomial
```
[Try it online!](https://tio.run/##JcwxCsIwGEDhPdcIlFb/2FbEukSC7iLqFjIkpbUhJkLpFppDeANP6BFiS6dveTwrh66xctC1jC2N3oEZf5/vuWtqw8v80XNLFceg6U26Z8OwUNwRDIZoIaAQqQsqmLXd4CJnKSY6yxLmkKIn7d5Wy1e89toNHJPjha1aNg2ScK@lCx75EsoRkN/Bdma/UMFuoZo5TAka4x8 "Wolfram Language (Mathematica) – Try It Online")
Reversed the domain.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 13 bytes
```
→r$ÇƆ/←ŗ0ɔ$ᵑ∆
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FjsftU0qUjncfqxN_1HbhKPTDU5OUXm4deKjjrYlxUnJxVBVC25qGSoYcpkoGHGZAbG5ggkQm3NZAMUsFEy5DA0UjLkMjYAiRgYKRhAtAA)
A port of [@Command Master](https://codegolf.stackexchange.com/users/92727/command-master)'s [05AB1E answer](https://codegolf.stackexchange.com/a/266186/9288). Unfortunately, Nekomata doesn't have `1/0=0`.
```
→r$ÇƆ/←ŗ0ɔ$ᵑ∆
→r [0,1,...,n]
$Ç [0Ck, 1Ck, ..., nCk]
Ɔ/ [0Ck/nCk, 1Ck/nCk, ..., (n-1)Ck/nCk]
←ŗ decrement and reciprocal
0ɔ Append 0
$ᵑ∆ Take the delta n times
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 81 bytes
```
n=>g=(k,j=n,c=(a,b=k)=>!b||c(a,--b)*(a-b)/~b)=>j&&c(n,j)/(c(n-j)/c(n)-1)+g(k,j-1)
```
[Try it online!](https://tio.run/##bYzBCsIwEETv/oWXsqOJRRE9bf8lWdtgWjbFiqfir8f1KAjLvJl32BxeYZHHfX56Lbe@DlyVu8Q0uszqhCm4yCO428Z1FVveR@woWLbvaD43jZC6jJaM3miAP2Kfvk@sVCm6lKk/TCXRQGfQCdj8yss/eYUd6gc "JavaScript (Node.js) – Try It Online")
Method 1
-5 bytes from tsh
-1 from Arnauld
[Answer]
# [R](https://www.r-project.org), 53 bytes
```
\(n,k,i=1:n-1)sum((`^`=choose)(-i-1,n-i)/(i^k/n^k-1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZFNSsRAEIVx6ykG3CSQtPVfXcJ4EhkEcXAYzIA_p3EzCl7HvZ7GmsToZiRQ3a_5qt6j8vL6sH9bL9-fn9Z9_dSrZui23WaJF0OP7ePzfdNcr66XN3e73eNt2_SbHruh37TnzWa1PR9W26Taqfnr5GPdYIft4qy_XODpupGOJsGlprRZWgmq6ihHaiToncx97iGIbuKgtRIrzRpH0P_c6mxNWPzY6LGOoM7jRSv-8yWI0PFERgExQooIBmNQDWGuINXikBhpTiIlMZT0MhKxtFSp4ZwX5yQJfpeihUGcD2wNqVzJoIKbkdHoDvNQp0IVCNhcASHN1Q5B3PN5QqGz-NkFaElrz3REkg2c9hYEQaZjVrV5AxgspWYR4lAGCHRCNE0apt-630_nNw)
Last few test cases produce incorrect results due to numeric overflow.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~74~~ 64 bytes
Saved 10 bytes thanks to @alephalpha
---
Use the formula
$$E(n,k)=\sum\_{i=1}^n{-i\choose 1-i+n}\left(\frac{i-1\choose k}{n\choose k}-1\right)^{-1}.$$
---
[Try it online!](https://tio.run/##VcxLCoRADADRvSdJnIQmg4yC9NKDmM0Q1Nj4OX8rgqDLB0WlfjH@p5w1qvk8WT8WHTgNGNd9AotCTgpsJGwfxxIkgIKxnEnQq2RBxJwW8w06EDrZFjcr@j75e7Om6s36yeZa5QM)
```
b=binomial
E(n,k)=sum(i=1,n,b(-i,1-i+n)*(1/(b(i-1,k)/b(n,k)-1)))
```
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/products.htm), 61 bytes
```
f←{+/(¯1*j+1)×(j!⍺)×÷1-(⍵!⍺-j←⍳⍺)÷⍵!⍺}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70qpTIxJz89PrEgZ8FNt0e9cxUe9e561DYhWwfI2Apk5HFpPOqb6hakACQDAjSBIoZGFuYKxiYKIMVp-UUKKZnFBTmJlQoFRanJmcWZ-XlLS0vSdC1u2qYBFVdr62scWm-olaVtqHl4ukaWItB4IOPwdkNdDaAFIK5uFlDdo97NYJntUMFaqCEruYD2gixVSFMwhLJNgGwjKNsMiW0OZJsgsc2hbAskvSC2KcxMAyDHGMYxQtJhBJIxUoCrM0CSA_JAXDNLuEZTkCNMIQ5esABCAwA)
not as efficient in bytes as possible, just a translation of formula 1.
[Answer]
# [Maxima](http://maxima.sourceforge.net/), ~~71~~ 70 bytes
Saved 1 byte thanks to @att
In Maxima, `binomial(-i,1-i+n)` can be written in `binomial(-i,-1-n)` to save byte(s).
---
Use the formula
$$E(n,k)=\sum\_{i=1}^n{-i\choose n+1-i}\left(\frac{i-1\choose k}{n\choose k}-1\right)^{-1}.$$
---
[Try it online!](https://tio.run/##Vcw7CoBADATQ3pMkkCARUVEsPcjaBd0ofsDbr5/C1fINM@Pdod6F0IHRgHW77h56tcmrG4GVWNgwjZGyXL309b1iQVISMgxNMi9qG3QgJIiROWVfFn@WlP9Zflk9V@EE)
```
E(n,k):=sum(binomial(-i,-1-n)/(binomial(i-1,k)/binomial(n,k)-1),i,1,n)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Ḷc⁹÷c’İ;0I⁸¡
```
[Try it online!](https://tio.run/##ASQA2/9qZWxsef//4bi2Y@KBucO3Y@KAmcSwOzBJ4oG4wqH///83/zQ "Jelly – Try It Online")
A simple port of [@CommandMaster’s 05AB1E answer](https://codegolf.stackexchange.com/a/266186/42248).
] |
[Question]
[
A followup to [this challenge](https://codegolf.stackexchange.com/q/262486/66833) by [Jeremy Collprav](https://codegolf.stackexchange.com/users/115553/jeremy-collprav), inspired by [DLosc solving this in Regenerate](https://chat.stackexchange.com/transcript/message/63935688#63935688). Some sections copied from the linked challenge.
## Linking chains
We define a chain to be a string containing exactly one or more of only the `-` character, or 1 or more of only the `_` character, or two chains linked by a `=`. More formally, a chain follows these 6 criteria:
1. The type (`-` or `_`) of chain must change after each `=`
2. Two chains must be linked with an `=` to change
3. The chain does not begin or end with a `=`
4. No two `=` may be adjacent
5. There must be at least 3 characters and both types of chain must appear
6. The chain must only contain `_`, `-` and `=`
## Challenge
This is a [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge, where the sequence is formed by all unique strings that form a valid chain. However, you may choose exactly what order this sequence is in, so long as your program is consistent and deterministic in this order. **You must define your order in your answer**.
Having chosen an order, you may then do one of the three tasks:
* Take a non-negative/positive integer \$n\$ as input and output the \$n\$th element in the sequence. This may be 0 or 1 indexed
* Take a positive integer \$n\$ as input and output the first \$n\$ elements in the sequence, separated by a non-empty character that is not any of `-`, `_` or `=`
* Output the entire sequence, separated by a non-empty character that is not any of `-`, `_` or `=`
You may output in any format that supports infinite outputs, such as a stream, a generator, or outputting without natural halt (stopping due to physical limitations such as memory is fine). Take a look through the [default output methods](https://codegolf.meta.stackexchange.com/q/2447/66833) for other possible methods.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code in bytes in each language wins.
---
### A sample sequence
The most obvious sequence can be constructed by examining all possible links of each ascending length:
```
-=_
_=-
--=_
-=__
__=-
_=--
---=_
--=__
-=___
-=_=-
___=-
__=--
_=---
_=-=_
----=_
---=__
--=___
--=_=-
-=____
-=__=-
-=_=--
____=-
___=--
__=---
__=-=_
```
and so on. This sequence is implemented in [this brute-force Jelly answer](https://tio.run/##AUAAv/9qZWxsef//ZuKBvi1fxZJnauKAnT3igbw@RQo6M@KAnC1fPeKAneG5l8OHxofGiuKCrOG6juG4o//Dh1n//zI1), which you can use to test for larger inputs. The top link was provided by [Unrelated String's answer](https://codegolf.stackexchange.com/a/262494/66833) to the linked challenge.
[Answer]
# [Python 3](https://docs.python.org/3.8/), 59 bytes
```
*l,e='_-='
for s in l:e in s!=print(s);l+=s[0]+s,l[s>e]+e+s
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/XytHJ9VWPV7XVp0rLb9IoVghM08hxyoVRBUr2hYUZeaVaBRrWudo2xZHG8RqF@vkRBfbpcZqp2oX//8PAA "Python 3.8 (pre-release) – Try It Online")
Prints the sequence forever, sorted by number of non-`=` characters. Based on [Ajax1234's generator](https://codegolf.stackexchange.com/a/262515/20260). The idea is to do a BFS on valid strings by branching on either prepending a copy of the first character, or the other one of `_-` separated by an `=`. Strings without an `=` aren't printed.
*Thanks to Albert.Lang for -5 bytes*
[Answer]
# JavaScript (ES6), 94 bytes
*-1 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
Returns the \$n\$-th entry (1-indexed) as a list of characters.
```
f=(n,k)=>n?f(n-/^(1+0)+1+$/.test(b=(k|1).toString(2)),-~k):[...b].map(x=>"-_="[+x?k&1:k++&&2])
```
[Try it online!](https://tio.run/##Dc7dDkMwGIDhc1fRyML3pZRKdsLKRexQbMFKqLVCs0j2c@vm6H0O37F@1Wu7DLMNtXnIfe8E6EChyHXRgQ6jG3AaI@X0FDErVwuNAPXhyKy52mXQPSSIQfhTmJaMsaZiz3qGTeRueBduSbdCeTxVlHpeUuHemQUmaYkmgvDsyEWQc3yAUiRvh5DW6NVMkk2mh2MA2WgGDb6PmDnf/Q8 "JavaScript (Node.js) – Try It Online")
### How?
Using the following regular expression, we look for all binary patterns that start and end with a `1`, contain at least one `0` and do not contain two adjacent `0`'s:
```
/^(1+0)+1+$/
```
(This is the intersection of [A005408](https://oeis.org/A005408), [A062289](https://oeis.org/A062289) and [A003754](https://oeis.org/A003754).)
By interpreting `0` as the link character (`=`) and `1` as a chain character (`-` or `_`), we can build exactly two valid outputs for each binary pattern. For instance, `1011` gives `_=--` and `-=__`.
---
# JavaScript (ES6), 83 bytes
[@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2) pointed out that this can work in base 10 just as well. However, the call stack overflow will happen quite early.
```
f=(n,k)=>n?f(n-/^(1+0)+1+$/.test(b=k|1),-~k):[...b+''].map(x=>"-_="[+x?k&1:k++&&2])
```
[Try it online!](https://tio.run/##Dc1LDoIwFADAPadoiIG@PFqsCxdg4SAEDWAxUGwJNIbEz9Urq1nO2LyatVuG2TFj78r7XlKTaJCFKXtqWHqlAo@AAg8pd2p1tJX6IyBhPw1ZxTlvMY5r/mxmuskiZDcZVriVOhKZRoyiUw2@twudlCOGSCLynYsk511EIO@AkM6a1U6KT/ZB9xT4aAdD4xggD77@Dw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
Nθ≔Φ⮌↨θ²κη≔⁺²↨⮌Φη﹪겦²ζ⪫Eζ×⊕↨⮌Φη⁼﹪μ⊗ζ⊗ι²§-_⁺ιθ=
```
[Try it online!](https://tio.run/##dY5NC8IwDIbv/oqyUwodqFfxoKgwQRniXeoWXFnXun4M2Z@vdU528pBAwvM@SVFxU2guQ8jU07uzb@5ooKWr2cZa8VBwENLFzQU7NBZhy2NrGVlSykgdq5rQXHoLS0YG5hcY8xUjJ116qaEewnRU9DGeG6EcHLVQcOJP6Bm5igYtZKow2KByWMIf5771XFoY1Q0jO@3vMvL9R/4bBJ0OblymSnxBkt4SRoaXBSPtl0jWCaWrEBbzeUg7@QY "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation:
```
Nθ
```
Input `n`.
```
≔Φ⮌↨θ²κη
```
Convert `n` to base `2`, but lose the LSB, as that will determine whether the chain starts with `-` or `_`.
```
≔⁺²↨⮌Φη﹪겦²ζ
```
Gather the remaining even bits and convert back from base `2`, then add `2`. This will be the number of chains.
```
⪫Eζ×⊕↨⮌Φη⁼﹪μ⊗ζ⊗ι²§-_⁺ιθ=
```
Split the odd bits up among the chains, convert them back from base `2`, then add `1`. This gives the lengths of each chain. The chains alternate with the first chain character determined by the original LSB. The chains are then joined with `=`s.
[Answer]
# Python3, 114 bytes
A generator that, when consumed, proceeds to produce the entire sequence.
```
def f():
k='_-';q=[*k]
while q:
if{*k}&{*(c:=q.pop(0))}=={*k}:yield c
T=c[-1]=='-'
q+=[c+'='+k[~T],c+k[T]]
```
[Try it online!](https://tio.run/##FY5BCoMwFETX9RR/1SRai9JNsfxbuJMgJSZtiMQkCq2IvXoaV8PMG5hx6/Ke7O3uQoyDVKAoazIwSPqSPDx2ueEZfN56lOATAK223OznLaeiQX91k6MVYzviETerluMAIvVaFF1Zc0RSkmR9gZ0oCJLCdL@WX0TSlvM4Ax6TmZoC9KAthKd9SVpX6cXJBW0XauV3oTNj8Q8)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 153 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 19.125 bytes
```
{n‛=_‹↔'\=~-Ġj=nUṪ∧;⁋,
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwie27igJs9X+KAueKGlCdcXD1+LcSgaj1uVeG5quKIpzvigYssIiwiIiwiIl0=)
Keen readers will notice that this answer includes almost the entirety of my answer to the other question. Uses the mapping defined in the question and outputs infinitely.
I'm having way too much fun with vyncode on this one - same sbcs yet different bit count. This answer started at 25 SBCS bytes/180 bits and is now 25 SBCS bytes/169 bits.
## Explained
```
{n‛=_‹↔Ṡ'\=-Ġṅ\=j=nUṪ∧;⁋,­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁢⁡‏‏​⁡⁠⁡‌⁣⁤​‎‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏‏​⁡⁠⁡‌­
{ # ‎⁡Forever:
n ↔ # ‎⁢ Generate all combinations w/ repetition with (loop count) characters from
‛=_‹ # ‎⁣ The string "=_" + "-"
Ṡ # ‎⁤ Convert each combination to a string
' ; # ‎⁢⁡ Keep only combinations n where:
\=- # ‎⁢⁢ Removing any "="s, then
Ġṅ # ‎⁢⁣ Grouping on consecutive characters, then
\=j= # ‎⁢⁤ Joining on "="s equals n
∧ # ‎⁣⁡ And
nU # ‎⁣⁢ removing all duplicate characters from n
Ṫ # ‎⁣⁣ leaves more than one item
⁋, # ‎⁣⁤ Join the list of filtered combinations on newlines and print
üíé Created with the help of Luminespire at https://vyxal.github.io/Luminespire
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 74 bytes
```
f=(h,i,...j)=>f(...j,h[0]+h,i||print(h),(h<{}?'_=':'-=')+h,0);f(...'_x-x')
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P81WI0MnU0dPTy9L09YuTQPE0MmINojVBgrX1BQUZeaVaGRo6mhk2FTX2qvH26pbqevaqmsCpQ00rcHq1eMrdCvUNf//BwA "JavaScript (V8) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
‚àûŒµ‚Ķ-=_√ó√¶y√π√™ íD'=KŒ≥'=√ΩQy√ã‚Ä∫]Àú
```
Outputs the infinite sequence.
Based on [my 05AB1E answer for the base challenge](https://codegolf.stackexchange.com/a/262493/52210).
[Try it online.](https://tio.run/##ATQAy/9vc2FiaWX//@KIns614oCmLT1fw5fDpnnDucOqypJEJz1LzrMnPcO9UXnDi@KAul3LnP//) (Times out for \$n>7\$.)
**Explanation:**
```
‚àû # Push an infinite positive list: [1,2,3,...]
ε # Map each integer to:
…-=_ # Push string "-=_"
√ó # Repeat it the current integer amount of times
√¶ # Get the powerset of this string
y√π # Only keep the strings with a length of the current integer
ê # Sorted uniquify this list of strings
í # Filter it by:
D # Duplicate the current string
'=K '# Remove all "="
γ # Group the remaining characters ("-" and "_") into groups of adjacent
# equivalent characters
'=√Ω '# Join these groups with "="-delimiter
D Q # Check if the string is the same as what we started with
y # Push the current string again
Ë # Check if all its characters are the same
› # Check whether the first check is larger than the second
# (aka, the first check is truthy and the second check is falsey)
] # Close both the filter and map
Àú # Flatten the infinite list of lists of strings
# (after which it is output implicitly as result)
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 15 bytes
```
"-_"Ňŧĉᵗz'=ᵚcjt
```
Takes no input and outputs all possible results.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FtuUdOOVjrYfXX6k8-HW6VXqtg-3zkrOKllSnJRcDFUCUwoA)
```
"-_"Ňŧĉᵗz'=ᵚcjt
Ň Choose a natural number
"-_" ŧ Choose a string of '-' and '_' of that length
ĉ Split the string into runs of identical characters
·µóz Check that there are at least two runs
'=·µöc Prepend '=' to each run
j Join the runs together
t Remove the first '='
```
---
## [Nekomata](https://github.com/AlephAlpha/Nekomata) before v0.5.0.0, 18 bytes
```
Ň"-_"ᵚ~ĉᵗz"="ᵚcjjt
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FruOtivpxis93Dqr7kjnw63Tq5RsQZzkrKySJcVJycVQZTDlAA)
] |
[Question]
[
Fastest code is a scoring method on this site where the goal is to write code that is as fast as possible.
From the tag wiki:
>
> The winner of a fastest-code challenge is determined by the runtime performance of the submissions. For fairness, all submissions should be benchmarked on the same machine, which usually means all submissions have to be tested by the host of the challenge. Alternatively, the submission can be compared to a reference program. For scoring by asymptotic time complexity, use [fastest-algorithm](/questions/tagged/fastest-algorithm "show questions tagged 'fastest-algorithm'") instead.
>
>
>
What general tips do you have for making solutions more competitive at [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'")? One tip per answer, please. Tips should ideally be broadly applicable, not language-specific.
[Answer]
# Use a fast hashing algorithm for your hashmap
Your language's default hashing algorithm is not always the fastest.
I'll focus on Rust, because it's the only fast language I'm familiar with. But the same applies to other languages.
## Rust
Rust's default hashing algorithm is [SipHash 1-3](https://en.wikipedia.org/wiki/SipHash), which is high-quality, but relatively slow. Since [HashDos attacks](https://en.wikipedia.org/wiki/Collision_attack) are not a concern for [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenges, you can try the hashing algorithms from the following crates:
* FxHash from [`rustc-hash`](https://crates.io/crates/rustc-hash). This is the hashing algorithm used by the Rust compiler. It is low-quality (so be careful when using it in real-world applications) but extremely fast. It is usually the fastest for small types with a fixed size, like `u32` and `u64`.
* AHash from [`ahash`](https://crates.io/crates/ahash). This hashing algorithm uses the hardware's AES instruction set when available. It is both high-quality and fast. It is usually faster than FxHash for more complex types like `String` and `Vec`.
You should try both and see which one is faster for your use case.
Both crates provide drop-in replacements for `std::collections::HashMap` and `std::collections::HashSet`: [`FxHashMap`](https://docs.rs/rustc-hash/latest/rustc_hash/type.FxHashMap.html) and [`FxHashSet`](https://docs.rs/rustc-hash/latest/rustc_hash/type.FxHashSet.html) from `rustc-hash`, and [`AHashMap`](https://docs.rs/ahash/latest/ahash/struct.AHashMap.html) and [`AHashSet`](https://docs.rs/ahash/latest/ahash/struct.AHashSet.html) from `ahash`. Please read the documentation for each crate to see how to use them.
The documentation for `ahash` also contains a [comparison](https://github.com/tkaitchuck/aHash/tree/master/compare) between common hashing algorithms.
## Other languages
[wyhash](https://github.com/wangyi-fudan/wyhash) and [xxHash](https://github.com/Cyan4973/xxHash) are two fast hashing algorithms I've heard of. They are written in C but ported to many other languages. Please see wyhash's [README](https://github.com/wangyi-fudan/wyhash) and [this list for xxHash](https://cyan4973.github.io/xxHash/#other-languages).
There might be other fast hashing algorithms that I'm not aware of.
[Answer]
## Avoid Allocations
Allocating memory is slow. Often you can substantially improve performance by pre-allocating memory. Note that allocation is not just manually calling `malloc` or `new`, but many data structures internally allocate memory.
Consider for example this code:
```
fn main() {
for i in 0..1000000 {
let mut a:Vec<u32> = vec![];
let mut b = 3;
for i in 0..1000 {
b+=b/2;
a.push(b);
}
println!("{}",a[999]);
}
}
```
This uses a `Vec` which will dynamically allocate memory. Multiple times each time the vector grows. On my machine this takes 2854 ms.
You can make this more efficient with static allocations:
```
fn main() {
for i in 0..1000000 {
let mut a = [0u32;1000];
let mut b = 3;
for i in 0..1000 {
b+=b/2;
a[i]=b;
}
println!("{}",a[999]);
}
}
```
This uses a static array of 1000 elements. No allocations needed. This takes 2789ms on my machine. A small difference but a significant one. Difference can be a lot bigger with less optimized data structures.
[Answer]
Here are a couple of tricks I've found that can help:
## Bit Shifting
Instead of dividing (slow) you can *sometimes* replace the operation with a **bit shift**
```
1024 >> 1 // 512
```
This has the same effect as `Math.floor( x / 2.0 )`
## Loop Unrolling
>
> Loop unrolling, also known as loop unwinding, is a loop transformation technique that attempts to optimize a program's execution speed at the expense of its binary size, which is an approach known as space–time tradeoff. The transformation can be undertaken manually by the programmer or by an optimizing compiler.
> [Wikipedia](https://en.wikipedia.org/wiki/Loop_unrolling)
>
>
>
```
for (int i=0; i<=5; i++) {
printf("%d", i);
}
```
becomes:
```
printf("%d", 0);
printf("%d", 1);
printf("%d", 2);
printf("%d", 3);
printf("%d", 4);
printf("%d", 5);
```
## Avoid Division
Similar to the approach with **bit shifting** avoid costly division by using mathmatics:
```
x / 3.0 == 5.5
```
multiply both sides by a factor of 3.0 to remove the division
```
x == 15.5
```
or alternatively instead of using `sqrt()` use `pow()` if applicable
```
Math.sqrt(x) == 5
x == 25
```
## Branch Prediction
>
> In computer architecture, a branch predictor[1][2][3][4][5] is a digital circuit that tries to guess which way a branch (e.g., an if–then–else structure) will go before this is known definitively. The purpose of the branch predictor is to improve the flow in the instruction pipeline. Branch predictors play a critical role in achieving high performance in many modern pipelined microprocessor architectures such as x86. [Wikipedia](https://en.wikipedia.org/wiki/Branch_predictor)
>
>
>
This one will be highly dependent on the machine you are running your code, as well as if it has been compiled / optimized already, but generally the more homogenous the data or operations are, the faster:
```
function checkIfValueLessThanHalf(value) {
if (value < 0.5) {
return true
} else {
return false
}
}
function checkIfValueLessThanHalfOptimized(value) {
return value < 0.5
}
// random array filled with unsorted numbers
const unsorted = Array(10 ** 6).fill().map((_) => Math.random())
// same array but sorted
const sorted = [...unsorted].sort()
// run method on unsorted data
console.time()
unsorted.filter(checkIfValueLessThanHalf)
console.timeEnd()
// run method on sorted data
console.time()
sorted.filter(checkIfValueLessThanHalfOptimized)
console.timeEnd()
```
The above example isn't necessarily faster (because you need to include the `.sort()` operation, but depending on the data set size and cost of sorting this can change.
*Note: running the code snippet above sequentially may produce different output as the V8 engine is doing optimizations under the hood as well, below are the two different code snippets which can be run in different contexts*:
[Try it online! (unsorted & if/else)](https://tio.run/##dZBBSwQxDIXv/RU5tgt214OeXMGDoKA38SpxmtKunXRp0xWR/e3j1EFFwdze93h5JDs8YB1K3MsJZ0fT5BsPEjPDEGh4ufWPmBrdUa0PAfkGk9eHTgy8K4DoYZFwARt7tsA@haQVBimNZnIESpX@mh5n2F11VEqt11CQXR4BS8E38DElcvAaJUDjmovMitv4TKWqIXOVH7yFq57RpxtYreDc2B7Wxo641/rJwPYS7lGCXQq0MUtdYxhJQnYwn/u9zKHgZ0FOZCWOpI36MvtioaL/@435Fbxmp800fQA)
[Try it online! (sorted & logical return)](https://tio.run/##hY8xTwMxDIX3/AqPSSXSMtCJInVAAgnEgliRufiUwJ1zSpwiQPz2a9LrwoQ3@/l7T@8dD5i7FCa54OhonvvCnYTI0HnqPu77FxwKPVDOzx75Dof@aZIwhm9y@tAkAz8K6iSSkhhON7iGjb1Sv0qt15CQXRwBU8Iv6MMwkIPPIB4K55ikblzGN0pZdZGzwPm4g30j9OUGVivYGttQbeyIk9avBnY38Iji7WKvjbEN1EYtoYVhJPHRQa1ytnQoeAqJA9lagur3IjVzoaT/7Wz@8LfstJnnIw)
Which return roughly `59.859ms` and `35.960ms` respectively for me over several runs.
## Notable Mention
This is one of my favorite examples which was used in Quake which incorporates some ingenious tricks to derive approximations which worked for their use case:
[Fast inverse square root method](https://en.wikipedia.org/wiki/Fast_inverse_square_root)
[Answer]
# Asynchronous execution
### Note: some languages have this behaviour built in, like JavaScript.
Asynchronous programming is useful when you have two expensive operations, since they can be done at the same time. To give a primitive analogy of this:
>
> You have two tasks:
>
>
> * Wash clothes in the washing machine.
> * Wash the dishes.
>
>
> Without asynchronous programming, you would have something like this:
>
>
>
> ```
> wash_clothes()
> wash_dishes()
>
> ```
>
> In this example, you would put the clothes in the washing machine, wait for the washing machine to be done, and only then wash the dishes! That's very inefficient, isn't it?
>
>
>
>
> ---
>
>
> However, with asynchronous programming, you would have something like this:
>
>
>
> ```
> await wash_clothes()
> wash_dishes()
>
> ```
>
> In this example, you would put the clothes in the washing machine, and you would wash the dishes while the washing machine is washing the clothes. Much more efficient!
>
>
>
As you can see, it can speed up code execution time.
---
A real world example is scraping from two websites and printing the HTML content of both. Without asynchronous programming, you would have to wait for one request to be finished before doing the other, but with asynchronous programming, you can send a request to the second website before the first website's request is finished!
---
## Edit
Mousetail left a few comments saying that this only works well for IO-focused challenges and that multithreading is often quicker.
] |
[Question]
[
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
The story continues from [AoC2015 Day 3](https://adventofcode.com/2015/day/3), Part 2. This challenge was kindly contributed by Wheat Wizard (Grain Ghost).
---
Santa is delivering presents to an infinite two-dimensional grid of houses. The delivery begins delivering a present to the house at an arbitrary starting location, and then moving along a predetermined path delivering a new present at every step of the path. Moves are always exactly one house to the north `^`, south `v`, east `>`, or west `<`.
However sometimes the notes giving the path have a few mistakes. Your job is to write a program that figures out how to correct these mistakes. We can't know exactly what mistakes were made but we do know that no house should ever receive more than 1 present. So we will just correct paths so that no house is visited more than once.
To correct a path we substitute a step with a different step. For example `>^<v` can be corrected to `>^>v`. Since we don't want to over-correct too much we will make the minimal number of corrections we can while reaching the desired result.
## Task
Given a string representing directions output the minimal number of corrections required before it visits no house more than once.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes.
## Test cases
```
>>v>>>vvv<<<^<v : 0
>>>>>><<<<<<< : 1
^^>>vv<< : 1
><> : 1
><>< : 2
^<v>^<v> : 2
^^>>vv<^^ : 1 (suggested by Yousername)
><<^<vv>>>>^^< : 2 (suggested by tsh)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 110 bytes
```
f=lambda a,v=[0],l=1:a and min(f(a[1:],[v[0]+1j**(ord(d)%11)]+v,l+1)+(a[0]!=d)for d in'^>v<')or(l-len({*v}))*l
```
[Try it online!](https://tio.run/##Xc1RC4IwEAfw9z7FUqLdZuDqTea@iGxgLMmYm4gMIvrsa1pYeXAPd7/jf/19vDp7CqEpTd2ddY3qzJdVLjNTsiJOVqOutbjBdcUKmVU@GmU3QrAbNNawYwwk9ZmhDGg8yuW21NC4AWnU2r0Snu/BDdgczMXiB/FPAGJCP7R2jKmJUkJ4z3kCgFCK2GYRwcW8nGstfKEUHb@iuBdTf9J@5f1HqYn@0tYSXg "Python 3 – Try It Online")
Simply find out all valid path with same length. Seems to be \$O\left(4^n\right)\$. And it will timeout for any (not so) large inputs. Yet another `mod 11` trick from previous days.
Thanks Kevin Cruijssen for -6 bytes.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 118 bytes
```
s->i=#s;forvec(v=[[0,3]|k<-l=Vec(Vecsmall(s))%11],#Set(Vec(Ser([I^c|c<-l+v])/(1-x),m=#l+1))-m||i=min(i,#[1|a<-v,a]));i
```
[Try it online!](https://tio.run/##LY3BCsMgGINfRSwDf6pssmPV@86FXcSClHbIbCe1yAa@u7Njh5B8IZBgN8ceocxIlsiUk03s5teWppEkqfWFXk1@CublvTZVcbHekwhw4tzQpp/2oyX9tBF9G8Y81m2bDJwJZ2@gi2x8ywHYkrOTi1uJo43m2QqWqDUAnSs2BP8hETGFwubWvUZ8AEbzcUSRxsOgVEpCYIqwEupvPxxEUoewgfIF "Pari/GP – Try It Online")
Very slow. Loops over all the commands with the given length, filters out the correct ones, and finds the minimal Hamming distance.
[Answer]
# Python3, 291 bytes:
```
y=lambda j,n,m:{'v':(n-1,m),'>':(n,m+1),'<':(n,m-1),'^':(n+1,m)}[j]
f=lambda p,s=(0,0),c=[(0,0)],l=[]:0 if not p else(k:=((r:=y(p[0],*s))in c))+(min(f(j+p[1:],[r,s][k],c+[[s],[]][k],l+[p[0]])for j in g)if(g:=[[''],[u for u in'v<>^'if y(u,*s)not in c]][k])else f(l.pop()+p[1:],c[-1],[r]+c,l))
```
A rather unelegant solution, but non-brute force, with basic backtracking.
[Try it online!](https://tio.run/##bU7LasMwELznK3STttoEm16KkfQjQoLUjVM7tizsRGBKv93VJi20pgsLsxrNIy7X9zE8v8RpXRfdH4fXtyPrMOBQffDEKxH2JQ6A3BDGQZYZqwfeE/aEJf35tJ3bNT8eEWctCiwAa23vwGGvrasK1jYsjFcW2amfT@JSaSGmSi8i2sLh0wzQBlYDSDG0QTSik9GWlUM74ezsxWEtrZ3z7e5XLy0JHTTjxDqWtWdoG3GutLWc5283RswtMzwp43mOX8SNgqgFZd2NgNqwRvSHOEYB36G13ZcU7WSNPcAapzZccyluTDJ5U1JKeZU4wO4XR6Me84fxnjSbR6PM9t6oVDK0/1l5v9FSG6pmvCeX9Qs)
[Answer]
# [Rust](https://www.rust-lang.org/), 304 bytes
```
|i:&str|{fn d(v:&mut Vec<[i64;2]>,c:&[u8])->u64{b"^v<>".iter().take(c.len()*4).map(|i|{let mut x=v[v.len()-1].to_owned();x[*i as usize%3&1]+=1-(*i as i64%5&2);if v.contains(&x){u64::MAX-1}else{v.push(x);let r=(*i!=c[0])as u64+d(v,&c[1..]);v.pop();r}}).min().unwrap_or(0)}d(&mut vec![[0,0]],i.as_bytes())}
```
[Try it online!](https://tio.run/##bVLRatswFH33V9wEaqTGVuM0K8N2PPYBe9lDGRgnuI7MxBLZk2QlneNv966SbpCmFyTBPUfnXB2kOm3GTnPQZhvH3dMygYcHkI0BySuudaleQUj4jjSI2PJx5nm1hH0pJKHQeztuoIYVjCcR@9qoU4/oltjY33cGnnmV5gI1F0UWVLGfd58LGmbo0r9M1zbNpkwYrghlpvzFScV2HGXvl5Tty5acxKl3@k7puLK5vcBhVDDTbJqD5FtCk2N@L6DU0Gnxh989@lExW0UhuTTR@@6Tv6CJqMGyqpEGB9fEP9Ieh4jjb19/hNHAd5r3lrWd/kmONHGeaoUKk1WVzwvqxJ@WM3xV4Fd5xFhBE2Q3LbqrYcBhXRiskwdVtptGkTkdtuQcgOXVJM/nwbwoAsFKvXl5NVwTSocRsBLP7XWjgAjZdiaAUuoDV9RF7udn1BWZZphVABENrnspNhdXzXVqM7dugXWWWZumNzJvwHp9a3Cu9FIfoDZzN1EzRUfE5294gR/jH69VQpqdnJBpH38ZIMzAnUi@fnDy/0KpNVdmw39PiF9fYqHvaIM3eOP4Fw "Rust – Try It Online")
I really need some tricks that'd let me use closures recursively.
Nothing clever going on here, just brute forcing every possible move.
Ungolfed:
```
|i: &str| {
fn deliver(visited: &mut Vec<[i64; 2]>, cmds: &[u8]) -> u64 {
b"^v<>"
.iter()
.take(cmds.len() * 4) // stop if cmds is empty
.map(|i| {
let mut new = visited[visited.len() - 1].to_owned();
new[*i as usize % 3 & 1] += 1 - (*i as i64 % 5 & 2); // same trick as day 1
if visited.contains(&new) {
u64::MAX - 1
} else {
visited.push(new);
let result = (*i != cmds[0]) as u64 + deliver(visited, &cmds[1..]);
visited.pop();
result
}
})
.min()
.unwrap_or(0)
}
deliver(&mut vec![[0, 0]], i.as_bytes())
}
```
[Answer]
# [R](https://www.r-project.org/), ~~168~~ ... 121 bytes
Or **[R](https://www.r-project.org/)>=4.1, 107 bytes** by replacing two `function` occurrences with `\`s.
*-many bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) and [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).*
```
function(s,a=combn(rep(5:8,l),l<-sum(s|1)))min(colSums(a[,apply(a,2,function(x)all(table(c(0,cumsum(1i^x)))<2))]!=s%%11))
```
[Try it online!](https://tio.run/##fc69CsIwFIbh3buwUjgHojQFoUia3Vk3UUhDi4X8kR@p4L3X6CA46P68H5@fpfW@l3HjRLy285CMjKM1EIhopdWdAd872O4aopAotg5JQ3hQRNSjAWnVIekA4kSEc@oOgtTkszGhUAqi6FQPEioiM805HS9T7lmNeF62oSxpnvv6ASkOzdHuTYSC8xvnBeKqWvwk7A3oP8Beop6f "R – Try It Online")
~~More AoC than AoCG, but I'm posting to get things going here in [R](https://www.r-project.org/).~~ The golf appeared thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) and [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).
Input as a vector of character codes.
Brute force solution - generates all paths of length equal to input's length, checks which are valid (no intersections) and returns where the difference to input is minimal.
Go check also [@Dominic's non-brute-force solution](https://codegolf.stackexchange.com/a/238232/55372).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~140 ...~~ 120 bytes
```
->s{(0..k=s.size*4).find{|w|(0..k**w).any?{|q|z=s.bytes;w.times{z[q%k/4]=q;q/=k};([a=0i]|z.map{|x|a+=1i**x%=19})[k/4]}}}
```
[Try it online!](https://tio.run/##XU3tCoIwFP3fUwwjyEVLwz/lth5kODBSGGJkq5n7ePblV0EdOHDv@bj3/jx3viR@S6VZRwhVRCIpdAGTEJXiejG2taMOYRui/NqdjG2s7lPn7lHItEUPURfSaNasql2SkSZtdqRy6ZrlJBKZ1ajOb8a@bL4hsYDwtSLxwYVsCDvn/A2ULMCK8iBbjDOlivZUCmPMsQqyJTiC6OMNwBN65wjiyeB8qIwa@IoU0/99Duzn1vC35684neJ87vo3 "Ruby – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~202~~ 197 bytes
*Edit: -5 bytes thanks to bug-spotting & suggestions from pajonk*
```
f=function(s,n=0,`[`=sapply)`if`(any(s[function(x)all(table(c(0,cumsum(1i^(utf8ToInt(x)%%11))))<2)]),n,f(s[function(x)outer(1:(l=nchar(x)),c("^",">","v","<"),Vectorize(`substr<-`),x=x,sto=l)],n+1))
```
[Try it online!](https://tio.run/##VY3LasMwEEX3/YqgEhjRKdhZlSJp333pJkTIUS0ikKVgPer0513ZhpJcuAudOTMa50v4GTp/679tinw23GSvkw0eInreoDoqHrvr1d2oskZBVSEe/6WJds5B6s6uBw0N6jzEPEBrJeRk3j7Dh09V2u/bltawAz1R9Ggeb4Sc@hHad3Dc60s3VkRRA5EEiagttYxQ/Op1CqP97UHFfI5pZK@K4sQnjClwR0/oX@o/swEiRBG1pTDGJCuE7p53zdM6WMK2rLhdsJSLfU8EEw@PbXRYZVbE0juyrUu5rcx/ "R – Try It Online")
Already outgolfed by [pajonk](https://codegolf.stackexchange.com/a/238229/95126), but posting to keep things going here in [R](https://www.r-project.org/)...
Non-brute-force solution, recursively makes increasing numbers of edits until a solution is found.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~80~~ 78 bytes
```
≔⟦⟦⁰ω⭆S⌕^>v<ι⟧⟧θFθ¿§ι²«F§ι¹✳⁻²⊗κ¹FI⌕AKVω⊞θ⟦⁺§ι⁰¬⁼ꧧ鲦⁰⁺§ι¹κ✂§ι²¦¹⟧⎚»⊞υ§ι⁰I⌊υ
```
[Try it online!](https://tio.run/##XU9Pa8IwFD@vn@Lh6QUysF4rQtENPCgFYZdSIWujhqaJbZI6GPvsXdJuzHl4kLz3@1teWFdqJochNUacFeb5nMKNwsF2Qp137IpbdXV2@iKh8CpUhbPjql/OKAhCioJCS5LopDvAloA4AaZ2qyr@gYLCghD4jJ7G69069uvMS1rciI6XVmiFO6GcwQWFjXbvkldYE0ICNPnhr5mxGPxTKTHjvH7Tas9dw5QKyW4kiDpzwZZCnkkvduc494i9tvjSOiYN1hR@j//SBuBo@8iP/a72c5Ci5I@cmBQh5Vpy1qF/fUVcGj6FcX9OYwx/npqPdXxp0bgGnTdNhuG47FdhhudefgM "Charcoal – Try It Online") Link is to verbose version of code. Brute force so each extra input character slows the code down by a factor of about 3. Explanation:
```
≔⟦⟦⁰ω⭆S⌕^>v<ι⟧⟧θ
```
Start a breadth first search of all positions with the same length as the input with no corrections yet, no steps taken, and the input converted into the desired path in a nicer format for Charcoal. (Even switching to `urdl` input would save ~~5~~ 3 bytes.)
```
Fθ
```
Loop over all the positions.
```
¿§ι²«
```
If there are more steps to take:
```
F§ι¹✳⁻²⊗κ¹
```
Output the steps so far on to the canvas.
```
FI⌕AKVω
```
Loop through available directions.
```
⊞θ⟦⁺§ι⁰¬⁼ꧧ鲦⁰⁺§ι¹κ✂§ι²¦¹⟧
```
Increment the number of corrections if this step wasn't the desired step, and save that with the augmented list of steps taken and suffixed list of desired steps to the search list.
```
⎚
```
Clear the canvas ready for the next position or the result.
```
»⊞υ§ι⁰
```
Otherwise, save the number of corrections.
```
I⌊υ
```
Output the minimum number of corrections needed.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 43 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
">^<v"©Igãʒ2Å0šÅ»®¦®¨‚sδkY0:+}DÙQ}.Lß
```
Brute-force approach. Generates all possible command-paths of the given input-length using the cartesian product, filters to keep paths where all visited houses are unique, calculates the Hamming difference of each remaining path with the input, and outputs the smallest one.
[Try it online](https://tio.run/##AU0Asv9vc2FiaWX//yI@Xjx2IsKpSWfDo8qSMsOFMMWhw4XCu8KuwqbCrsKo4oCac860a1kwOit9RMOZUX3OtcO44oKsw4tfT33Dn///Pjw@PA) or [verify some of the smaller inputs](https://tio.run/##yy9OTMpM/V9TVnl4Qqi9ksKjtkkKSvb/lezibMqUDq2sTD@8@NQko8OtBkcXHm49tPvQukPLgHjFo4ZZxee2ZEcaWGnXuhyeGVh7bmvE4R2PmtYc7o73rz08/7/OfzsbOy4gtuECGQUk7OIA).
**Explanation:**
```
">^<v" # Push string ">^<v"
© # Store it in variable `®` (without popping)
Ig # Push the input-length
ã # Get the cartesian product to generate all possible paths of a
# length equal to the input
ʒ # Filter this list of paths by:
2Å0 # Push [0,0]
š # Implicitly convert the path to a list of characters,
# and prepend the [0,0]
Å» # Cumulative left-reduce:
®¦ # Push `®` minus its first character: "^<v"
®¨ # Push `®` minus its last character: ">^<"
‚ # Pair them together: ["^<v",">^<"]
s # Swap so the current character of the reduce is at the top
δ # Map over the pair using this character as argument:
k # Get its 0-based index (or -1 if it isn't present)
Y0: # Replace the 2 with a 0
+ # Add it to the current coordinate-pair
}DÙQ # After the reduce, check if all coordinates are unique:
D # Duplicate the list of integer-pairs
Ù # Uniquify it
Q # Check if the list of integer-pairs are still the same
}εø€Ë_O} # After the filter, calculate the Hamming distance of each
# remaining path with the (implicit) input:
ε } # Map over each remaining path:
ø # Create character-pairs with the (implicit) input-string at
# the same positions
€Ë_ # For each pair: check that they are NOT the same
O # Sum to get the amount of differences
ß # Pop and push the minimum
# (after which it is output implicitly as result)
```
Minor note: `®¦®¨‚sδkY0:` will result in `[[-1,0],[0,1],[1,0],[0,-1]]` for `>^<v` respectively. So the `>`/`<` travel in the opposite direction: `>` travels towards the left and `<` towards the right. This is irrelevant for calculating the result however.
[Answer]
# TypeScript Types, 450 bytes
```
//@ts-ignore
type a<T,A=1,B=0>=T extends[A,...infer X]?X:[B,...T];type b<S,P=[[],[]],V=0>=P extends V?0:S extends`${infer A}${infer S}`?b<S,{">":[a<P[0]>,P[1]],"<":[a<P[0],0,1>,P[1]],v:[P[0],a<P[1]>],"^":[P[0],a<P[1],0,1>]}[A],P|V>:1;type c<S,N,T="",O="v"|"^"|"<"|">">=N extends[0,...infer M]?S extends`${infer C}${infer R}`?O extends C?c<R,N,`${T}${C}`>:c<R,M,`${T}${O}`>:never:`${T}${S}`;type M<S,N=[]>=1 extends b<c<S,N>>?N["length"]:M<S,[...N,0]>
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgEEBeARkoCFaAGAPlvMPQA9x0iACaQA2tUoA6abEQAzdKkIANALoB+ZQC5RTKdPKqA3LgKEARqQDKlAAq1Ro1ZSfOAam062e-QSMJu6qxaVj4CwpAABgAkAN6yCkrUAL5xCYqEVsmR6pY2sQBE7AU6ZLairKrsdqL0qs4FpCWiZRXOrJT01eV1zgBuOuWVlK117A0Aes1DzqPtnePJ4s62AD5u7Fr0JvhEAMbWlABylOS0BQWUAPLnfQWrBVMPTQ-FnEdhfmId0pLpSgBZDShPjhEQxeLyDIAYVSkMShAAStl1FdPhFCND1AdEcdKBDyHDYZFNjjKAD8XFCXErtlNoh0H1FFoCXCspEdmYAYcjg4qgx0f5LAcbEd2Ox1EdRAUADaCeDgAAWBVUWm5NlEvxOlXYmGwu0I5FYhFohG5RXYfXFlr6fVI9ompDuupAhDdE3U+rM5HoJrNTWt1vtwftRUwrvdntMRHIACY-eaJhNxbbQy7gG7CB6vTGAMwJgOkN7hjORnOGgAsBaKRYDJcz2ejhoArNXHVb28WI1mowbyAA2NvJm2kJNh7uNvsAdmr7AdTqt1qTdYnnqAA)
## Ungolfed / Explanation
```
// Increments a number represented where e.g. 2 is [Pos, Pos], 0 is [], and -1 is [Neg]
type Inc<T, Neg=1, Pos=0>=T extends[Neg,...infer X]?X:[Pos,...T];
// Decrements
type Dec<T>=Inc<T,0,1>
// Returns 1 if Str is valid, or 0 otherwise
// Implicitly maps over unions in Str
// Visited is a union of positions; it's initialized to 0 instead of never for byte-saving
type Check<Str, Pos = [[], []], Visisted = 0>=
Pos extends Visisted
// If Pos is in Visisted, return 0
? 0
// Otherwise, take the first character of Str
: Str extends `${infer Dir}${infer Rest}`
? Check<
Rest,
// Move Pos according to Dir
{
">": [Inc<Pos[0]>, Pos[1]],
"<": [Dec<Pos[0]>, Pos[1]],
"v": [Pos[0], Inc<Pos[1]>],
"^": [Pos[0], Dec<Pos[1]>],
}[Dir],
// Add Pos to Visited
Pos | Visisted
>
// Str is empty; the string is valid
: 1
// Return all strings where N characters are mutated
type MutateN<Str, N, Acc="", Chars = "v" | "^" | "<" | ">"> =
N extends [0, ...infer M]
// If N > 0, get the first character of Str
? Str extends `${infer Char}${infer Rest}`
// Map over the Chars union:
? Chars extends Char
// If this element of Chars is Char, don't mutate this character
? MutateN<Rest, N, `${Acc}${Char}`>
// Otherwise, mutate this character and decrement N
: MutateN<Rest, M, `${Acc}${Chars}`>
// Str is empty, so we can't mutate N more characters; return never
: never
// Otherwise, return Acc + Str
:`${Acc}${Str}`
type Main<Str, N=[]> =
1 extends Check<MutateN<Str, N>>
// If any of the strings where N chars are mutated are valid, return N
? N["length"]
// Otherwise, check N + 1
:Main<Str, [...N, 0]>
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~197~~ ~~194~~ ~~192~~ 187 bytes
```
->i{c=[0]*(s=i.size);loop{*a=0i;b=i.bytes.map{|b|b%13};(c|c).map{|c|b[c/4]+=c};b.map{|b|a<<a[-1]+1i**b};a==a|a&&break;c[0]+=1;s.times{|j|c[j]/4>=s&&c[j,2]=[0,c[j+1]+1]}};c.count{|c|c!=0}}
```
Array `c` represents possible changes. Each element — one change such that `c[...] / 4` is the position and `c[...] % 4` is the change itself. The algorithm increments elements in the array until it finds the array that makes positions stay unique. Theoretical maximum of errors is the size of input.
Positions are represented by the array `a` of complex numbers. Conveniently `1i ** N` represents rotation, so we can just add complex numbers and push them to the array to see the path.
The trick with `b%13` as to have a rotating order of pointers («<>^v» is bad but «^>v<» is good). `mod 13` makes it so that:
```
"<v>^".bytes.map { |b| b % 13 % 4 } == [0, 1, 2, 3]
```
Examples added to the TIO. Thanks to G B for help!
[Try it online!](https://tio.run/##ZU9bboMwEPzPKVyUIF5xIOGrflwEmcp2iUraAMIGKcU@OzWhlRJ1pZF2Zke7s/0gbvOZzHtaT5IUKYsCRWqo6u8qRF9t200RJ2mNhBPFTVcKXnk3GWHELjtZFEgjw1WSRhTykLOYSIvEn41jzIt9xuKsjiJhESeEG@77oq/4J5LuYEwypKCur5WazMXI4sIOOSXK912bHJkLlbguXnYwa5GEsh0avRyULyS1dt50g1bAwyUdvd@QXdVfB8113TbwvdKV1GACRigDtg0JcgizNA2hbt/4w7gxQNz/u3sdATvQOOTAAkKAy5Elx@TEHLWLLfBf5UcfwktbN2uGbbNZm3PhUTpSh3HEGJd49NjDZCm81oNelov/SaKYPrMnPx7pgv8rytJp8w8 "Ruby – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 107 bytes
```
-Max[Count@4/@Select[Tuples[Range@4,l=Length[s=ToCharacterCode@#~Mod~11]],0!=##&@@Accumulate[I^(s+#)]&]]+l&
```
[Try it online!](https://tio.run/##LcfdCoIwGIDhW1kORqFigoduLDwKEqI8GxPG/PyBOUOnBJG3bhQdvDy8vXIt9Mp1Wm01oluYq6fIhtk6nkT8Dga0E8X8MDCJm7IN8CQw9AK2ca2YaDFkrRqVdjBmQwUcr/lQrXEsZXDcUYwJ5yet5342yoE4l/vJxwdJpPQN2a5jZ53AKGSoFlhKRFDE0csrS8aWJU29AHksZX9@W6YL@@a9tw8 "Wolfram Language (Mathematica) – Try It Online")
There is a built-in for Hamming distance, but its name is `HammingDistance`, much longer than calculating it manually.
] |
[Question]
[
I have a small pill box of \$n\$ slots. (Think of it as a linear one like the image below, but not necessarily having 7 slots.)

Each slot has at most one pill. Every day, I take one of two actions: take one pill from the pill box, or refill the pill box. The order of taking a pill alternates between left-to-right and right-to-left on each refill, **except** when the pill box was totally empty before the refill, in which case I always take the next pill from the left. The pill box is initially filled, and I initially take pills from the left. (I never try to take a pill from an empty box or refill a full box.)
Believe me, I take pills exactly as I describe here IRL. If you wonder why: I alternate directions as a simple way to prevent a pill from being too long in the pill box, and I just forget directions when the pill box is totally empty :P
Example with 5 slots:
| Action Number | Action | State of slots | Direction |
| --- | --- | --- | --- |
| 0. | Initial: | `[1, 1, 1, 1, 1]` | (order: ->) |
| 1. | Take pill: | `[0, 1, 1, 1, 1]` | (->) |
| 2. | Take pill: | `[0, 0, 1, 1, 1]` | (->) |
| 3. | Take pill: | `[0, 0, 0, 1, 1]` | (->) |
| 4. | Refill: | `[1, 1, 1, 1, 1]` | (<-) |
| 5. | Take pill: | `[1, 1, 1, 1, 0]` | (<-) |
| 6. | Take pill: | `[1, 1, 1, 0, 0]` | (<-) |
| 7. | Take pill: | `[1, 1, 0, 0, 0]` | (<-) |
| 8. | Refill: | `[1, 1, 1, 1, 1]` | (->) |
| 9. | Take pill: | `[0, 1, 1, 1, 1]` | (->) |
| 10. | Take pill: | `[0, 0, 1, 1, 1]` | (->) |
| 11. | Take pill: | `[0, 0, 0, 1, 1]` | (->) |
| 12. | Take pill: | `[0, 0, 0, 0, 1]` | (->) |
| 13. | Take pill: | `[0, 0, 0, 0, 0]` | (->) |
| 14. | Refill: | `[1, 1, 1, 1, 1]` | **(->)** |
| 15. | Take pill: | `[0, 1, 1, 1, 1]` | (->) |
| 16. | Refill: | `[1, 1, 1, 1, 1]` | (<-) |
| 17. | Take pill: | `[1, 1, 1, 1, 0]` | (<-) |
| 18. | Take pill: | `[1, 1, 1, 0, 0]` | (<-) |
| 19. | Take pill: | `[1, 1, 0, 0, 0]` | (<-) |
| 20. | Take pill: | `[1, 0, 0, 0, 0]` | (<-) |
| 21. | Take pill: | `[0, 0, 0, 0, 0]` | (<-) |
| 22. | Refill: | `[1, 1, 1, 1, 1]` | **(->)** |
| 23. | Take pill: | `[0, 1, 1, 1, 1]` | |
Inputs to your program or function:
* \$n\$, the size of the pill box.
* The list of my actions. You may choose any two distinct, consistent values to represent "take pill" and "refill".
The output is the list of the state of my pill box after each action. You may choose to include or exclude the initial state. You may also choose any two distinct, consistent values to represent a slot being full or empty.
If you encode "take pill" and "refill" as numbers 1 and 0 respectively, the input to your code for the above scenario would be
```
5, [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1]
```
and the expected output is the list of arrays on the right side (you don't need to output the "order"), with or without the zeroth row.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
Takes input as a string of digits where `1` encodes *take pill* and `0` encodes *refill*.
-1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
```
ηε0¡€g¤IL‹s5¡θgGR
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3PZzWw0OLXzUtCb90BJPn0cNO4tNDy08tyPdPeh/7KGdh3dYmFqaHF5@bstRkJrDjUDi9JxDu/8bGhoaQDGIhNFcpgA "05AB1E – Try It Online")
I initially thought we are supposed to just generate the final state, which is why this program iterates over the prefixes. (But that might not even be a bad approach)
```
ηε # for each prefix of the input:
0¡ # split it on "0"
€g # take the length of each segment
¤ # take the last number (number of uses since last refill)
# this leaves the full list on the stack
IL # push the range [1 .. size of pill box]
‹ # element-wise less than
# this creates a list [0, ..., 0, 1, ..., 1] with the remaining number of pills
s # swap to the list of lengths
5¡ # split the list in the register on 5 (direction resets)
θg # take the length of the last part
GR # reverse the list 1 times less than than this
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~30~~ 20 bytes
```
$(n[¥↳£¹|‹]:×*¹↳¥ßṘ,
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%24%28n%5B%C2%A5%E2%86%B3%C2%A3%C2%B9%7C%E2%80%B9%5D%3A%C3%97*%C2%B9%E2%86%B3%C2%A5%C3%9F%E1%B9%98%2C&inputs=5%0A%5B0%2C%200%2C%200%2C%201%2C%200%2C%200%2C%200%2C%201%2C%200%2C%200%2C%200%2C%200%2C%200%2C%201%2C%200%2C%201%2C%200%2C%200%2C%200%2C%200%2C%200%2C%201%2C%200%5D&header=&footer=)
It's slightly satisfying using two different overloads of the same element.
```
$( # Iterating over the list of instructions
n[ # If it's truthy (refill)
¥↳ # Bitshift the current value by the register
# Iff the register is 0, and the current value is 1, the result is truthy.
£ # Store this to the register
¹ # Refill, pushing original input
|‹] # Otherwise decrement (take a pill)
: # Duplicate
×* # Get that many asterisks
¹↳ # Align
¥ßṘ # If the register is truthy (we're taking pills from the left) reverse
, # Print.
```
Older version, where I was a big brain and tried to store the whole box:
```
1£ƛ1;?(n[:T¥ßṘt0Ȧ|:a¬¥¬∨£ƛ1;]…
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=1%C2%A3%C6%9B1%3B%3F%28n%5B%3AT%C2%A5%C3%9F%E1%B9%98t0%C8%A6%7C%3Aa%C2%AC%C2%A5%C2%AC%E2%88%A8%C2%A3%C6%9B1%3B%5D%E2%80%A6&inputs=5%0A%5B1%2C%201%2C%201%2C%200%2C%201%2C%201%2C%201%2C%200%2C%201%2C%201%2C%201%2C%201%2C%201%2C%200%2C%201%2C%200%2C%201%2C%201%2C%201%2C%201%2C%201%2C%200%2C%201%5D&header=&footer=)
```
1£ # Store 1 to register (direction)
ƛ1; # Array of length n, filled with 1
?(n # For each item in the list of refills...
[ # If it's truthy (Take pill)
:T # Get the truthy indices
¥ßṘ # Reverse if direction is left
t # Get the last one (first empty pos if left, last if right0)
0Ȧ # Assign 0 to this index
| ] # Else (Refill)
£ # Set the register (direction) to...
:a¬ # Whether the current array is all falsy
∨ # Logical or with...
¥¬ # The opposite current value of the register
# If any values are truthy, the register (direction) flips
# Otherwise, it becomes 1 (left)
ƛ1; # Refill (fill with 1s)
… # Whichever action we took, print the current array
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 80 bytes
```
(n,x,d)=>x.map(i=>'.'.repeat(i?--w:(d=w&&!d,w=n))[d?'padEnd':'padStart'](n),w=n)
```
[Try it online!](https://tio.run/##bclBC4IwGMbxe5@iLu4dbKMOQSjTU5@gowkON2Ni78Yc6rdfVAQRwXP48X8GNaupC9ZHPp9SLxMgW5mmslzFXXmwsiSCiGC8URFsxfmSg5ZLlu00WyRSWuuKeKXPqEn@xCWqEEkDSF9/Kjadw8mNRozuBj0cWX1g2/f2H/z4u/zvDRWDs9hesaXpAQ "JavaScript (V8) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~89~~ 88 bytes
```
n=input()
i,s=0,1
while 1:i,s=[0,i+1,i/n or-s,s][input()::2];print([0]*i+[1]*(n-i))[::s]
```
[Try it online!](https://tio.run/##VYrBCoMwEETPzVd4THSlWb1t8UuWPQoulDWYSOnXp1W8yMC8eTDpW5bVhvqoNqmlvfjgFPIUAd1n0ffcIB3OEbRD0Kc169ZnyMLXnWiQV9rUiucorXaM0nrrNQQmylLr6PCfePad5/4B "Python 2 – Try It Online")
thanks to @ovs for -1 byte
# [Python 3](https://docs.python.org/3/), 100 bytes
```
n=int(input())
i,s=0,1
while 1:i,s=[0,i+1,i==n or-s,s][input()>"0"::2];print(([0]*i+[1]*(n-i))[::s])
```
[Try it online!](https://tio.run/##VYyxCsMwDETn@itCJjtRQGo2F/dHhMZCBEUxsUvo17tN6FIO7t4Nd/ldl9XmdmmW1KpXy6/qQ3AKJSGQ2xd9PjqKR2cEHQk0JevWbSpQhH@De499jFe55e248Ywy6Mgkg7dJQ@AYi4TWZkdf4en/efIH "Python 3 – Try It Online")
take the actions in the form of individual inputs
## How it works :
* `n` store the length of the box, `s` the side from which the pill have to be taken (`1` for left and `-1` for right) and `i` the number of the pill
at each loop :
* if the `input()` returns `1` (take a pill): then `i,s=[0,i+1,i==n or-s,s][input()::2]` will assign `i` to `i+1` and `s` will stay inchanged
* if the `input()` returns `0` (refill): then `i,s=[0,i+1,i==n or-s,s][input()::2]` will assign `i` to 0 and `s` to either `-s` or `1` dependig if the box is empty (`i==n`)
* `print([0]*i+[1]*(n-i))[::s]` will then print `i`missig pills and `n-i` pills in the order defined by `s`
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~78~~ ~~76~~ ~~74~~ 73 bytes
```
->n,m{b=*i=0;(b+m).map{|a|a<1?b=[1**i=b.max*~i/n]*n:b[i]=0&i+=i/n|1;p b}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ7c6yVYr09bAWiNJO1dTLzexoLomsSbRxtA@yTbaUAsolQQUrNCqy9TPi9XKs0qKzoy1NVDL1LYFCtQYWhcoJNXW/k@LNtVRiDbUUYAgAxgDjY0sgl08NvY/AA "Ruby – Try It Online")
### Explanation
For input, the 'take pill' and 'refill' actions are encoded as `1` and `0`, respectively. Output is a series of arrays in which `1` indicates a full slot and `0` an empty slot. The initial state is included.
The initial state is created by adding a refill step to the start of the action list. The direction of movement is embedded in the slot index `i`. If we are moving left to right then `i` is non-negative (array indices \$0, 1, 2, \ldots\$). If we are moving right to left then `i` is negative (array indices \$-1,-2,-3,\ldots\$), that is, we read from the end of the pillbox array.
```
->n,m{ # n = size of pillbox, m = list of actions
b=*i=0; # initialise slot index i to 0 and pillbox b to [0]
(b+m).map{|a| # for each action, beginning with extra refill step (overloaded b)
a<1? # if refilling
b=[1**i ]*n # fill (overwrite) the pillbox with n pills
i=b.max*~i/n # if the pillbox is empty (b.max = 0), set i to 0, otherwise (b.max = 1) set i to -1|0 if previously moving right|left
: # else
b[i]=0& # take pill from slot i and...
i+=i/n|1; # add 1|-1 to i if moving right|left
p b # print the pillbox
}
}
```
[Answer]
# JavaScript (ES6), ~~78~~ 76 bytes
*Saved 2 bytes thanks to @l4m2*
Expects `(n)(array)`. Returns an array of strings. The initial state is included.
```
n=>a=>[d=0,...a].map(c=>a=c?a.replace(d||/1(?!1)/,0):'1'.repeat(n,d=!d|!+a))
```
[Try it online!](https://tio.run/##bYxBCsIwEEWvYladYDpNFm6EtAcpXQyTVJSYhLa4yt2jRQQR4S8e78G/0YNWXq55a2Nyvs62RtuT7UdntUJEmvBOGXiXPBAuPgdiD66UzsAgjOyUlufGNHvytEFUzgpXxJGkrJzimoLHkC4ww0nCaNThPf2BH/42//30On4C "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // n = number of pills
a => // a[] = array of actions, re-used as the box string
[ d = 0, // prepend a 'refill' directive
// and initialize the direction to 0 (right to left)
...a // leave all other actions unchanged
].map(c => // for each action c:
a = // update a:
c ? // if this is a 'take pill' action:
a.replace( // replace in a:
d || // either the first '1' (if d = 1)
/1(?!1)/, // or the last '1' (if d = 0)
0 // with '0'
) // end of replace()
: // else:
'1'.repeat( // generate a string consisting of ...
n, // ... '1' repeated n times
d = !d | // and update the direction to:
!+a // - 1 (L -> R) if d = 0 or the box is empty
) // - 0 (R -> L) if d = 1 and the box is not empty
) // end of map()
```
[Answer]
# [D](https://dlang.org/), ~~250~~ ~~202~~ ~~198~~ 197 bytes
```
import std.array,std.algorithm;U[]f(T,U)(T b,U A){U[]r=[[1].replicate(b)];T d=1,p;foreach(a;A){U P=r[$-1].dup;if(a*P.sum){P[p]=0;p+=d;}else{P=[1].replicate(b);d=a?1:-d;p=d>0?0:b-1;}r~=P;}return r;}
```
[Try it online!](https://tio.run/##bZDLasMwEEXXyVfMoguplY296CaDGvoHXtgroYUcyYnADyHLLcG4v@4qLoEQCjPD5XCZl15X27nBBxiDTpX36so21Z4Hb8Olw0rIhpSsoqSEmlXwSeeIPBcil6k3rrUnFQypqcQSNM@Zw2bwRp0uROHNDAX34iWJbj05tA1Rr0U6Th2dC@Ekz9C9cY2LaUczF/y5K2qujvkh0ei4/siO2aFOclz8Dy9iNWHyPXhc1q/BauiU7QmFeb97OCqmHTCiPggpJGh1HYFDQ94ZiJzBX2R38aQfyf9c0tj8frJpcRuwLbH7ji80bR/pzbPsl/UX "D – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org), 109 bytes
```
a=({1..$1})
$a(){<*&&r+=\|tac||r+=\|sort;>$a}
0()rm `eval ls$r|head -1`
for x;$x&&(eval \<$^a';s+=$?;';<<<$s)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwU19ZYXy_KLsxKL80rwUhbT8IgXHEH-FpNJ0rtSKgvyiEoUQ3wAXzyBbfaCwfkluwdLSkjRdi5u5ibYa1YZ6eiqGtZpcKokamtU2WmpqRdq2MTUlick1NWBWMVC_tZ1KYi2XgYZmUa5CQmpZYo5CTrFKUU1GamKKgq5hAhfIxgprlQo1NQ2wbIyNSlyiunWxtq2KvbW6tY2NjUqxJsTSBVC7PaJNdRQMYMgQBxtZBLt4LNRAAA)
This seemed like a good way to go about it, until I re-read the challenge and it was more complicated than I thought (it started as a 40-byte answer... for a totally different challenge). A proper rewrite would surely be half the length.
[Answer]
# [Python 2](https://docs.python.org/2/), 105 bytes
```
n=input();k=[1]*n;d=0
for i in input():exec(i*"k[d]=0;d+=[1,-1][d<0]#"+"d=-(d>0)*any(k);k=[1]*n");print k
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERD0zrbNtowVivPOsXWgCstv0ghUyEzTwEqaZVakZqskamllB2dEmtrYJ2iDVSso2sYG51iYxCrrKStlGKrq5FiZ6CplZhXqZENN01J07qgKDOvRCH7/39TLqAeBQgygDHQ2Mgi2MVjAQ "Python 2 – Try It Online")
Geez. Need to find a better way to inverse the direction.
-22 thanks to @Jakque
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 37 bytes
```
Ft0.bP[Yt?yR`\b1`s#(i:1Ny&!i)XaRVy]@i
```
Takes the steps as a string of 1s (take pill) and 0s (refill box); outputs the pillbox as a string of 1s (pills) and spaces (empty slots). [Try it online!](https://tio.run/##K8gs@P/frcRALykgOrLEvjIoISbJMKFYWSPTytCvUk0xUzMiMSisMtYh8////6b/DQ0NDaAYRMJoAA "Pip – Try It Online")
### Explanation
It's easier to store the pillbox in a consistent order and conditionally reverse it when printing. Arguments are size of pillbox (integer) and actions (string of 1s and 0s).
```
Ft0.bP[Yt?yR`\b1`s#(i:1Ny&!i)XaRVy]@i
a,b are cmdline args; s is space; i is 0; y is ""
We're going to store the pillbox in y and the
direction in i (0 = LTR, 1 = RTL)
Ft For each action t in
0.b the input actions with a 0 prepended (so that the
box is "refilled" as the first step):
Y Set y to the following quantity:
t? If t is truthy (1, take pill):
yR The pillbox string, replacing
`\b1` regex matching the first 1
s with a space
Otherwise (0, refill box):
i: Set i to
1Ny Number of pills left in the box
& Logical AND
!i Logical negation of previous i value
#( ) Length of the above (always 1)
Xa string-repeated (size of pillbox) times
[ ] Put the new value of y in a list with
RVy its reverse
@i Index into the list using i (i.e. reverse iff i=1)
P Print
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
Nθ≔⁰ηF⁺RS«≡ιR«≔∧η¬ζζ≔θη»≦⊖η≔⭆θ‹κηε⟦⎇ζε⮌ε
```
[Try it online!](https://tio.run/##RY4xC8IwEIXn9lccTheI4OKik@AiqITqJg4xPW2xppqkihV/e0y06nB3vHsf704V0qhaVt7P9Llxy@a0I4MXNk4n1pYHjQMORVD72gCKqrHYy3oc3vDKmVIfkDEGjzSxt9KpArB8KyUtQUBHUSRd1kTnWHBY1g5bxji0IfhnXj6Hkmea5LSXTeVGsJDnzp2SMnQi7Sj/c533@SOwMWNO1uIxMuEARVAE1@FmTUZLc8c2rDlkdCVjCYmxbYCe3g9TIUTWVezf6fvX6gU "Charcoal – Try It Online") Link is to verbose version of code. Uses `R` for refill and `P` (or anything else really) for pill and outputs a string of `0`s and `1`s for each state. Explanation:
```
Nθ
```
Input `n`.
```
≔⁰η
```
Start with `0` pills.
```
F⁺RS«
```
Loop over the commands, but with an extra Refill action. This saves me from having to explicitly initialise the direction.
```
≡ιR«
```
If this is a refill action, then...
```
≔∧η¬ζζ
```
Flip the direction, unless there are no pills, in which case reset the direction.
```
≔θη
```
Refill the pills.
```
»≦⊖η
```
Otherwise, decrement the number of pills.
```
≔⭆θ‹κηε
```
Generate a string of full and empty slots.
```
⟦⎇ζε⮌ε
```
Output the string or its reverse depending on the current direction.
] |
[Question]
[
Consider a form of binary where digits can be any of \$1\$, \$0\$ and \$-1\$. We'll still call this "binary" because we convert the digits from base two. For example,
$$\begin{align}
[1, 0, -1, 1]\_2 & = 1 \times 2^3 + 0 \times 2^2 + -1 \times 2^1 + 1 \times 2^0 \\
& = 8 - 2 + 1 \\
& = 7
\end{align}$$
We'll call a representation of a number in this format a "[non-adjacent form](https://en.wikipedia.org/wiki/Non-adjacent_form)" if no non-zero digits are adjacent. \$[1, 0, -1, 1]\_2\$ is not a non-adjacent form of \$7\$, as the last two digits are adjacent and non-zero. However, \$[1,0,0,-1]\_2\$ is a non-adjacent form of \$7\$.
You should take a positive integer and convert it to a non-adjacent form. As every number has an infinite number of these forms (but only by prepending leading zeroes), you should output the form with no leading zeros. If the standard binary format of the input is a non-adjacent form (e.g. \$5 = 101\_2\$), you should output that. You can output a list of integers, or a single string, or any other format the clearly shows the output. You may optionally choose to use any three distinct characters in place of `1`, `0` and `-1`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~19~~ 12 bytes
```
-/'2\-2!3 1*
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs9LVVzeK0TVSNFYw1OLiSlMwBWJzIDY0MgKTxgB8vAbB)
Uses Prodinger's algorithm on Wikipedia:
```
Input x
Output np, nm
xh = x >> 1;
x3 = x + xh;
c = xh ^ x3;
np = x3 & c;
nm = xh & c;
```
And then the last three steps are not used because the `& c` part of `np` and `nm` erases the 1 bits where both are 1, but we're doing `-/'` so it doesn't matter. (Observation thanks to @m90)
How it translates to K:
```
-2!3 1* given x, create (3x,x) and floor-divide both by 2
which gives (x3,xh)
2\ convert to base 2, which gives a two-column matrix
with lsb being the last row
1st column is np, 2nd column is nm, but both-1 bits not handled
-/' evaluate np - nm to get a vector of -1, 0, 1s
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 9 bytes
```
;0+HBU_/U
```
[Try it online!](https://tio.run/##y0rNyan8/9/aQNvDKTReP/T/4fZHTWv@/zfVMdcxNDICYmMA "Jelly – Try It Online")
-4 bytes (`^/&$` removed) thanks to @m90's observation that we don't need to clear shared 1 bits.
Look ma, no Unicode!
Literal translation of Prodinger's algorithm. x3 goes before xh, and `U` is used twice to align the binary representations of the two.
[Answer]
# JavaScript, 35 bytes
```
f=n=>n?f(n+n%4/3>>1)+'OPON'[n%4]:''
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7PPk0jTztP1UTf2M7OUFNb3T/A3089GigQa6Wu/j8tv0hBI1PBVsHQWiFTwUbByABIa2trKiTn5xXn56Tq5eSna2TqKKRpZGpqWv8HAA "JavaScript (Node.js) – Try It Online")
Output `O` for `0`, `P` for `1`, `N` for `-1`.
-2 bytes by Arnauld.
---
Alternatively, as suggested by Arnauld, using `1` for `1`, ~~`2` for `0`,~~ `0` for `0`, and, `3` for `-1`:
# JavaScript, 31 bytes
```
f=n=>n?f(n+n%4/3>>1)+n%2*n%4:''
```
[Try it online!](https://tio.run/##DcdNDkAwEEDhq8xGtOqflWqdRUplRGakxPWrq/e9c/3WxwW834p422P0hoylxQtSlI3NYG0nk/oi3ZTn0XMAgWCg04AwQ9@mKiXBMT187fXFh8ASvEApdfwB "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~21~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0‚¬2÷+2вí`(0ζRO
```
-6 bytes thanks to *@m90*, thanks to his observation that `& c` only changes `[1,1]` to `[0,0]`, which doesn't matter when we're subtracting them.
[Try it online](https://tio.run/##ASMA3P9vc2FiaWX//zDigJrCrDLDtysy0LLDrWAoMM62Uk///zEyMg) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/g0cNsw6tMTq8XdvowqbDaxM0DM5tC/L/r/M/2lTHXMfQyAiIjWMB).
**Explanation:**
```
0‚ # Pair the (implicit) input with 0
¬ # Get the first item of this pair (the input) without popping
2÷ # Integer-divide it by 2
+ # Add it to both the input and 0 in the pair
# (we now have the pair [input+input//2, input//2])
2в # Convert both inner values to a binary-list
í # Reverse each inner list
` # Pop and push both lists separated to the stack
( # Negate all values in the top list
0ζ # Zip the two lists together with 0 as filler
R # Reverse the list of pairs back again
O # Sum each inner pair together
# (after which the resulting list is output implicitly)
```
[Answer]
---
## Python 3, ~~176~~ 103 bytes
Literal translation of Prodinger's algorithm. By no means the shortest python 3 answer that should be attainable. it's been a while on here so looking forward to getting back into it!
```
x=int(input())
h=x>>1
t=h+x
c=h^t
p=bin(t&c)
m=bin(h&c)
n=[]
j=len(p)-2
k=len(m)-2
for i in range(j):n.append(int(p[i+2]))
for i in range(k):n[j-k+i]=-int(m[i+2])*(m[i+2]==0)or 1
print(n)
```
If anyone can help shorten it I'd appreciate it, there must be an easier way to concatenate the two positive and negative value lists.
Using [m90](https://codegolf.stackexchange.com/users/104752/m90)'s answer it can be shortened vastly predominately by using zip!
```
enter code x=int(input())
print([*[int(x)-int(y)for x,y in zip(*[f".{x//2+z:0{len(bin(x*3))-3}b}"for z in[x,0]])]])
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~103~~ \$\cdots\$ ~~96~~ 94 bytes
```
m;i;f(n){int r[n];for(i=!n,n+=*r=m=n/2;n;n/=2,m/=2)r[i++]=n%2-m%2;for(;i--;)putchar(r[i]+49);}
```
[Try it online!](https://tio.run/##bVVhj6IwEP2@v6JnYgIC0Smgki735XK/Qs3GIO6R065h3Zw5418/ryDSKTMkknHmzbzOPNoWUXHY6vf7/agqtfe0f630WdQrvVH7j9qr8m861EE@qfNjrqdSaaWnuQyP5uXXqyoINrkey@g4li1eVVGk/NPXufi1rT0D2ARJ5qvbval63Fba88X1RZincZSXU1mcy91stRG5uMJNOW54uOXALTt3OMTHfSCcDUKJDQ2zUhsaMs1RQZK3QCUJ3xIHh5kZDg45YYbWQ1IBnCURXpBunOTHbpywJ05XND91GqP8czdO8hdunPA7g2P6z5zpNPzka3o7PDCf1d/yY@/1H5k/7TwT6wrFAAUUBRQlKUpSVExRMUUlFJVQVEpRKUXNKWpOUQuKWlDUkqKWFJVRVMZMlRk@cNPnxs/MHxgBgFEAGAmA0QAYEYBRARgZgNEBGCGAUQIYKYDRAhgxgFEDGDmMz26SSb9LHnuk3wmh3WLWlNaMrZlYM7Xm3JoLay6tmSEKTIf4ABECYgRECYgTECkgVkC0kHXdNzfSxLzL4ndZP7ofrS8/5fqS/TC/dBQK/D8edXnmWhNec75UeldeTNpMdebrcPx0@L4SQdCin/fe87TSplIbUL37VJvA3huNlzsRfRdmQdq30eZyVriE0dLU6PVsi20chDgggDkWh5An4Vo/QR1viXn7/rveTd@Hti3ckrP@XVPC3P2oyo0hjeiz1qMu6fZyu/8r9oft@@c9@vMf "C (clang) – Try It Online")
*Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Inputs positive integer \$n\$.
Outputs \$n\$ converted to its non-adjacent form using \$2\$ for \$1\$s, \$1\$ for \$0\$s, and \$0\$ for \$-1\$s.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~41~~ 40 bytes
```
f=->n{n>0?f[(n-w=n%2*(2-n%4))/2]+[w]:[]}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/OwD4tWiNPt9w2T9VIS8NIN0/VRFNT3yhWO7o81io6tvZ/gYKGoZ6eoYGBpl5uYoGGWprmfwA "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 51 bytes
```
f=lambda x,s="":x and f(round(x/2))+".+.-"[x%4]or""
```
[Try it online!](https://tio.run/##BcFRCoMwDADQq4TAIKHqoO6r4EnGPiq1M7ClEhXq6et723WsRcfW8vSL/zlFqN0@IYYKURNksnJqovr0zA4HN/T4ro/Xpxhiy8VAQBQs6nch7zlsJnqQdJmEud0 "Python 3 – Try It Online") Outputs using `.` for `0`, `+` for `1` and `-` for `-1`. Explanation: Port of @tsh's JavaScript solution, except that Python has Banker's rounding which saves a byte in Python 3. Or I could have just use Python 2 I guess.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
NθWθ«←§.+.-θ≔÷⁺¬﹪⊕θ⁴θ²θ
```
[Try it online!](https://tio.run/##HYxBDoIwFETXcIqG1W8sJBhXsiJxQ6KEKyD9SpPSSvuLJsaz1@pqJnnzZppHN9lRx9iZR6A@LFd0sPImf85KI0uVvfNscMoQHM94I8Fa6ozEFxTVrioLwVae5lnrvbob6Ayd1KYkwqCDh94SXKwM2iYyOVzQEMr0KtiB/1TB9v9s8k@MdR3LTX8B "Charcoal – Try It Online") Link is to verbose version of code. Outputs using `.` for `0`, `+` for `1` and `-` for `-1`. Explanation: Another port of @tsh's JavaScript solution.
```
Nθ
```
Input the number to convert.
```
Wθ«
```
Repeat until it is zero.
```
←§.+.-θ
```
Output the previous digit using cyclic indexing. The digits are output right-to-left so that the final output is in the correct order.
```
≔÷⁺¬﹪⊕θ⁴θ²θ
```
Divide by two, rounding to even.
] |
[Question]
[
There's never really been a definitive ASCII-cards challenge AFAIK. So, using the following deck of ASCII cards:
```
.------..------..------..------..------..------..------..------..------..------..------..------..------.
|2.--. ||3.--. ||4.--. ||5.--. ||6.--. ||7.--. ||8.--. ||9.--. ||T.--. ||J.--. ||Q.--. ||K.--. ||A.--. |
| (\/) || (\/) || (\/) || (\/) || (\/) || (\/) || (\/) || (\/) || (\/) || (\/) || (\/) || (\/) || (\/) |
| :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: |
| '--'2|| '--'3|| '--'4|| '--'5|| '--'6|| '--'7|| '--'8|| '--'9|| '--'T|| '--'J|| '--'Q|| '--'K|| '--'A|
'------''------''------''------''------''------''------''------''------''------''------''------''------'
.------..------..------..------..------..------..------..------..------..------..------..------..------.
|2.--. ||3.--. ||4.--. ||5.--. ||6.--. ||7.--. ||8.--. ||9.--. ||T.--. ||J.--. ||Q.--. ||K.--. ||A.--. |
| :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: |
| :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: || :\/: |
| '--'2|| '--'3|| '--'4|| '--'5|| '--'6|| '--'7|| '--'8|| '--'9|| '--'T|| '--'J|| '--'Q|| '--'K|| '--'A|
'------''------''------''------''------''------''------''------''------''------''------''------'
.------..------..------..------..------..------..------..------..------..------..------..------..------.
|2.--. ||3.--. ||4.--. ||5.--. ||6.--. ||7.--. ||8.--. ||9.--. ||T.--. ||J.--. ||Q.--. ||K.--. ||A.--. |
| :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: || :/\: |
| (__) || (__) || (__) || (__) || (__) || (__) || (__) || (__) || (__) || (__) || (__) || (__) || (__) |
| '--'2|| '--'3|| '--'4|| '--'5|| '--'6|| '--'7|| '--'8|| '--'9|| '--'T|| '--'J|| '--'Q|| '--'K|| '--'A|
'------''------''------''------''------''------''------''------''------''------''------''------''------'
.------..------..------..------..------..------..------..------..------..------..------..------..------.
|2.--. ||3.--. ||4.--. ||5.--. ||6.--. ||7.--. ||8.--. ||9.--. ||T.--. ||J.--. ||Q.--. ||K.--. ||A.--. |
| :(): || :(): || :(): || :(): || :(): || :(): || :(): || :(): || :(): || :(): || :(): || :(): || :(): |
| ()() || ()() || ()() || ()() || ()() || ()() || ()() || ()() || ()() || ()() || ()() || ()() || ()() |
| '--'2|| '--'3|| '--'4|| '--'5|| '--'6|| '--'7|| '--'8|| '--'9|| '--'T|| '--'J|| '--'Q|| '--'K|| '--'A|
'------''------''------''------''------''------''------''------''------''------''------''------''------'
```
---
Take two integers, `p` and `q` as input; where `p` is the number of players and `q` is the number of cards each player gets.
* Randomly shuffle the deck of cards (this is ambiguous, but means that all cards must be equally likely to appear anywhere once).
* Deal 1 round of cards per player, outputting `q` rows of `p` cards each row.
# Rules:
* The results should be uniformly random, each card should be equally likely to appear anywhere.
* It is guaranteed that `0 < p*q <= 52 and p < 10`, you may have undefined behavior for scenarios where this is not met.
* You should output `q` rows of cards with `p` cards per row.
* Each column should be separated by `|` (a pipe char surrounded by spaces); if you choose a different char than this, explain why. Surrounding spaces here are NOT optional.
* Each row must have 1 or more newlines inbetween them, more than one is acceptable, 0 is not (1 newline meaning the newline there by default).
* Each row should be labeled with the player who owns it in the format "Player N" (0 or 1-indexed is fine).
* No one card may appear more than once.
* `T` is for Ten.
---
# Examples:
**Function(`p=1,q=1`):**
```
Player 1 # Can also be 0.
.------.
|2.--. |
| (\/) |
| :\/: |
| '--'2|
'------'
```
**Function(`p=2,q=1`):**
```
Player 1 | Player 2 # Can also be "Player 0 | Player 1"
.------. | .------.
|2.--. | | |T.--. |
| (\/) | | | (\/) |
| :\/: | | | :\/: |
| '--'2| | | '--'T|
'------' | '------'
```
**Function(`p=2,q=2`):**
```
Player 1 | Player 2 # Can also be "Player 0 | Player 1"
.------. | .------.
|J.--. | | |3.--. |
| (\/) | | | :/\: |
| :\/: | | | :\/: |
| '--'J| | | '--'3|
'------' | '------'
.------. | .------.
|8.--. | | |6.--. |
| :(): | | | :/\: |
| ()() | | | (__) |
| '--'8| | | '--'6|
'------' | '------'
```
---
# Artistic credit to a font on: <http://patorjk.com/software/taag>
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~142~~ ~~133~~ 125 bytes
```
NθFN«F¬¬ι«→↑×⁶θ| »Player IιFθ«↙↓.↓⁴←'←⁶↑'↑⁴.P⁶↓≔‽⁵²εW№υε≔‽⁵²ε⊞υε≔§”w↘τ[⁵PkxτG”εδδ.--.¶✂”{➙aETê;s∨Hμ⁼⎚↑Z~SÀd~⌀Tê”﹪ε⁴φ⁴'--'δ↘
```
[Try it online!](https://tio.run/##dZLfT8IwEMeft7@i6QvXZGMJv9TyRPAFFYKIb0vIZIU1KS1sK2iUv32um2iBuGVZ7nPfu@/10mUSpUsViaIYya3OJ3rzxlLYkb67UikCGxKCPl2nwhOVVx8nNXTGas@Azvg6yctSx5mmXOZAX7cemvMNy6DnoR2xUvgLYRMe3ROYiuiDpTWt0TDKKov@j@vO9rpXB/nEVmd2hnkIN/E17NjI1JW6Br6GvcvxL1QG2b1OZmMtcr6tUN3ib8oqHGQZX0uYRTJWG@i2iIdYlTgkXDAEQ6XLUm0oQf@KpzpLapHVc5CPZMzeAbfanW7v5vZu/vD8OMBG5aHYmjU@m9v3m6G0z/Yi@JIBBkppGAYBBGH5EGJCWb@UAhi4IEGwKHWEnDKl21jFWihgZj8eWpmf7dfw/bNNxhdb@r07R/dYFG23U/h78Q0 "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 9 bytes by improving my random sampling code. Saved a further 8 bytes by improving my suit printing code. Explanation:
```
Nθ
```
Read the number of cards into `q`.
```
FN«
```
Loop over each player.
```
F¬¬ι«→↑×⁶θ| »
```
If this is not the first player, print the vertical line between the previous and this player.
```
Player Iι
```
Print the player number.
```
Fθ«
```
Loop over each card.
```
↙↓.↓⁴←'←⁶↑'↑⁴.P⁶↓
```
Print the card's edge.
```
≔‽⁵²εW№υε≔‽⁵²ε⊞υε
```
Pick a card index that hasn't already been picked, and add it to the list of picked card indices.
```
≔§”w↘τ[⁵PkxτG”εδδ
```
Choose and print the card's rank by cyclically indexing into a string of valid card ranks (`2-9, T, J, Q, K, A`).
```
.--.¶
```
Print the top of the suit.
```
✂”{➙aETê;s∨Hμ⁼⎚↑Z~SÀd~⌀Tê”﹪ε⁴φ⁴
```
Print the middle of the suit by slicing into a string. The slice begins at the card index modulo 4 and takes every 4th character until the string runs out (or the `f`=1000th character is reached). Since 4 and 13 are coprime this ensures that all 52 cards are possible.
```
'--'δ↘
```
Print the bottom of the suit and a copy of the rank, and then move to a point that conveniently is not too far away from either the copy of the rank, the start of the next card, or the start of the dividing line for the next player.
[Answer]
# [Python 2](https://docs.python.org/2/), 357 bytes
```
from random import*
p,q=input()
A,V=':/\:',':\/:'
c=sample([(""".------.
|%s.--. |
| %s |
| %s |
| '--'%s|
'------'"""%(n,s,t,n)).split('\n')for s,t in('(\/)',V),(A,V),(A,'(__)'),(':():','()()')for n in'123456789TJQKA'],p*q)
print' | '.join('Player '+`i`for i in range(p))
for i in range(0,p*q,p):print'\n'.join(map(' | '.join,zip(c[i:i+p][0],c[i:i+p][1])))
```
[Try it online!](https://tio.run/##XZBNS8NAEIbv@yuWQpiZdpq28Xshh171oiC9NKENtdWVZDNN4qGS/x43jai4h52XYZ@Hl5VT81a6qOsOVVnoKnMvfthCyqoZK@FjbJ18NEhqyasYzCwxwGCSmQG1i@uskHyPaxyNRuH0fELVBrXPoW5Vq4P674DpFIK6VTA8BU8F6Ljmhh1RWEtuG4TEAR3KSvu1tg4BkxkBr4hx@X0DbjYEPoJB6vsgIQ2Q8wgsoovLq@ub27vn@6eHJaQs4yMpqaxrQPsa4XvZix/z7LSvNEy2dtuz1rP9D7zuUYjUv9W8t7CQGTy@5aApMsFfK39awd3aGjuRdD1P@ScvUiLquoh19AU "Python 2 – Try It Online")
I have no friggin' idea.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 126 bytes
```
³‘Ḷj“×ṁẹHY»;⁶¤ṫ5W;
2r9;“TJQKA”
“¡ẏ%TZ=ẹaɦAY’ṃ“(\/)_:”s4s2
“E¬ƭḊHẈḢ“ðİ“|e*Ḳ?BḤ’ṃ“. -|1¶'”żÐ€¢FỴ$€p2£j/€Ẋ
¢ssḢµṣ€”1Zj€“ | ”Yµ€ÑY
```
[Try it online!](https://tio.run/##y0rNyan8///Q5kcNMx7u2Jb1qGHO4ekPdzY@3LXTI/LQbutHjdsOLXm4c7VpuDWXUZGlNVA@xCvQ2/FRw1wuIPvQwoe7@lVDomyB6hNPLnOMfNQw8@HOZqCMRoy@ZrwVUFmxSbERSKnroTXH1j7c0eXxcFfHwx2LQBZtOLIBSNWkaj3cscne6eGOJXDdegq6NYaHtqkD9R/dc3jCo6Y1hxa5Pdy9RQXIKjA6tDhLH8h4uKuL69Ci4mKgaYe2Pty5GCgEVG8YlQVmzFGoUQByIw9tBXIPT4z8//@/@X8TAA "Jelly – Try It Online")
[Answer]
# JavaScript (ES6), ~~328~~ ... 312 bytes
Takes input in currying syntax `(p)(q)`. Players are 0-indexed.
```
p=>g=(q,i=p*q*6,d=[...Array(52).keys(a=`:\\/:,(__),()(),(\\/),:/\\:,:():, | ,
,.3.,|0.--. |,| 1 |,| 2 |,| '--'0|,'3',Player 4`.split`,`)].sort(_=>Math.random()-.5))=>i--+p?g(q,i,d)+a[i%p?6:7]+a[i<0?14:i/p%6|8].replace(/\d/,c=>['TJQKA'[j=x>>2]||j-3,a['3454'[x&=3]],a[x%3],'------',p+i][c],x=d[i%p+p*(i/p/6|0)]):''
```
### Demo
```
let f =
p=>g=(q,i=p*q*6,d=[...Array(52).keys(a=`:\\/:,(__),()(),(\\/),:/\\:,:():, | ,
,.3.,|0.--. |,| 1 |,| 2 |,| '--'0|,'3',Player 4`.split`,`)].sort(_=>Math.random()-.5))=>i--+p?g(q,i,d)+a[i%p?6:7]+a[i<0?14:i/p%6|8].replace(/\d/,c=>['TJQKA'[j=x>>2]||j-3,a['3454'[x&=3]],a[x%3],'------',p+i][c],x=d[i%p+p*(i/p/6|0)]):''
;(update = _ => O.innerText = f(+P.value)(+Q.value))()
```
```
<label>Players <input id=P type=number value=1 onchange="update()"/></label> <label>Cards <input id=Q type=number value=1 onchange="update()"/></label> <button onclick="update()">Deal</button><pre id=O style="font-size:10px"></pre>
```
### How?
This is a recursive function, building the output from bottom to top. During the main part in which the cards are drawn, `i` is initialized to `p*q*6` and decremented until it reaches `0`. We then draw the header by further decrementing `i` until it reaches `-p`.
The ASCII art is split into small pieces stored into the array `a[]`. The table below describes the content of `a[]`, which makes the rest of the code easier to understand.
```
Index | Content | Description
-------+------------+------------------------------------------------
0 | ":\\/:" | bottom of 'diamonds' and 'hearts'
1 | "(__)" | bottom of 'spades'
2 | "()()" | bottom of 'clubs'
3 | "(\\/)" | top of 'hearts'
4 | ":/\\:" | top of 'diamonds' and 'spades'
5 | ":():" | top of 'clubs'
6 | " | " | player separator
7 | "\n" | line-feed
8 | ".3." | card row #1, "3" --> "------"
9 | "|0.--. |" | card row #2, "0" --> symbol of card value
10 | "| 1 |" | card row #3, "1" --> top of color ASCII art
11 | "| 2 |" | card row #4, "2" --> bottom of color ASCII art
12 | "| '--'0|" | card row #5, "0" --> symbol of card value
13 | "'3'" | card row #6, "3" --> "------"
14 | "Player 4" | header, "4" --> player ID
```
### Formatted and commented
```
p => g = ( // p = number of players
q, // q = number of cards
i = p * q * 6, // i = counter
d = [...Array(52).keys( // d = deck
a = `:\\/:,(__),...`.split`,` // a = ASCII art pieces (truncated, see above)
)].sort(_ => Math.random() - .5) // shuffle the deck
) => //
i-- + p ? // if i is greater than -p:
g(q, i, d) + // do a recursive call and append ...
a[i % p ? 6 : 7] + // separator or line-feed
a[i < 0 ? 14 : i / p % 6 | 8] // header or card row
.replace(/\d/, c => [ // where digits are replaced with:
'TJQKA'[j = x >> 2] || j - 3, // 0: symbol of card value
a['3454'[x &= 3]], // 1: top of color ASCII art
a[x % 3], // 2: bottom of color ASCII art
'------', // 3: horizontal border
p + i // 4: player ID
][c], //
x = d[i % p + p * (i / p / 6 | 0)] // x = current card with: bits 0-1 = color
) // bits 2-5 = value
: // else:
'' // stop recursion
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~382~~ ~~358~~ ~~346~~ ~~338~~ 332 bytes
```
from random import*
p,n=input()
d=zip([0,1,2,3]*13,'23456789TJQKA'*4)
shuffle(d)
C=""".------.
|%s.--. |
| %s |
| %s |
| '--'%s|
'------'"""
print' | '.join('Player '+`i`for i in range(p))
exec"for l in zip(*[(C%(v,'(:::\/(//\)\):::'[s::4],':((:\_)\/_(/:)):'[s::4],v)).split('\\n')for s,v in d[:p]]):print' | '.join(l)\nd=d[p:]\n"*n
```
[Try it online!](https://tio.run/##XVBNa4NAEL3vr1gEmRm7aqP2a8FDya29tNCbK0mo2mwx6@Ka0BT/u9UWSulc3uO9mcdj7HnYdyaZpqbvDrzfmWoGfbBdPwTMCpNrY48DEqvyT22xuBQrkYi0DFapgCTNrq5vbu9eHp4f7yHIiLn9sWnaGiti69zzvCj8noiNvpt5xEc2ct/9BQhD8N3I4GcV5itme20G4LMZvXfaIDy1u3Pdc7jY6m3T9VxzbZa2bzVaIlZ/1K/eoreLvhQNClz7eBKAUkoVYxwrUjRzKJyUWSlAIkq1IRVvMJZEv8aJKHK21QOCUgZoiXXitARXhbRlSfJ/vZaUqfKqsLJUxgvMNM0v@gI "Python 2 – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 106 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
E⁽⁰⅜║(Ηe─t¦4»\$²‘8n{"1<ω⅛┘‘4n╬¡;4n33žASUjk"TJQKA”+{a;22žF75ž}}'#δ№{ψ⌡≤οc+C}c_.∫:"▓⅛▲ŗ‘Κ⁽e{≤+};H?;lƧ |Γ∙┼;┼
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=RSV1MjA3RCV1MjA3MCV1MjE1QyV1MjU1MSUyOCV1MDM5N2UldTI1MDB0JUE2NCVCQiU1QyUyNCVCMiV1MjAxODhuJTdCJTIyMSUzQyV1MDNDOSV1MjE1QiV1MjUxOCV1MjAxODRuJXUyNTZDJUExJTNCNG4zMyV1MDE3RUFTVWprJTIyVEpRS0EldTIwMUQrJTdCYSUzQjIyJXUwMTdFRjc1JXUwMTdFJTdEJTdEJTI3JTIzJXUwM0I0JXUyMTE2JTdCJXUwM0M4JXUyMzIxJXUyMjY0JXUwM0JGYytDJTdEY18uJXUyMjJCJTNBJTIyJXUyNTkzJXUyMTVCJXUyNUIyJXUwMTU3JXUyMDE4JXUwMzlBJXUyMDdEZSU3QiV1MjI2NCslN0QlM0JIJTNGJTNCbCV1MDFBNyUyMCU3QyV1MDM5MyV1MjIxOSV1MjUzQyUzQiV1MjUzQw__,inputs=NCUwQTEz)
Card generating:
```
...‘ push "(\/):\/::/\::\/::/\:(__):():()()" - the suits
8n split to line lengths of 8 - individual suits
{ for each suit
"...‘ push ".---| .-| " - a quarter of a suit
4n split to line lengths of 4 - [".---", "| .-", "| "]
έ quad palindromize - empty card
; get the suit on top
4n split to line lengths of 4
33ž insert in the card at [3; 3]
A save on variable A - card template
SU push "1234567890"
jk remove the first and last digits
"TJQKA”+ append "TJQKA"
{ } for each number - "23456789TJQKA"
a load the template
;22ž at [2; 2] insert the current number
F75ž at [7; 5] insert the current number
```
Shuffling:
```
'# push 52
δ lower range - [0, 1, ..., 50, 51]
№ reverse - [51, 50, ..., 1, 0]
{ } for each, pushing the current item
ψ get a random number from 0 to ToS (inclusive)
⌡ that many times
≤ put the first item of the stack on the top
οc+C prepend that to the variable C, predefined with an empty array
```
Dealing:
```
c_ push Cs contents on the stack - the stack is now a mess of cards
.∫ repeat input times - each player - pushing the current player number
: duplicate the number
"..‘ push "player "
Κ prepend "player " to the number
⁽ uppercase the 1st letter
e{ } repeat 2nd input times
≤ put the first stack item on the top
+ append it to "Player X" vertically (making an array)
; get the other copy of the player number
H? if POP-1 (aka if it's not 1)
; swap the top 2 items - the current collumn and all the previous ones (by then they've been joined together)
l get its (vertical) length
Ƨ | push " |"
Γ palindromize - [" | "]
∙ multiply " | " vertically that length times
┼ append it horizontally (to the previous collumns)
;┼ append the current collumn
```
[Answer]
# Ruby, 262 bytes
```
->p,q{a=[*0..51].shuffle
puts ["Player %d"]*p*(d=" | ")%[*1..p],(1..q*6).map{|i|(["'------'
.------.
|%X.--. |
| %s |
| %s |
| '--'%X|".split($/)[i%6]]*p*d%a[i/6*p,p].map{|j|["(\\/):()::/\\:"[u=j%4*4-4,4],":\\/:()():\\/:(__)"[u,4],j/4][i%3]}).tr("01BC","TJQK")}}
```
Harder to follow, but shorter!
# Ruby, 279 bytes
```
->p,q{puts [*1..p].map{|k|"Player #{k}"}*" | "
a=[*0..51].shuffle
(q*6).times{|i|puts [".------.
|%s.--. |
| %s |
| %s |
| '--'%s|
'------'".split($/)[i%6]]*p*" | "%a[i/6*p,p].map{|j|[":\\/:()():\\/:(__)"[u=j%4*4-4,4],("%X"%(j/4)).tr("01BC","TJQK"),"(\\/):()::/\\:"[u,4]][i%3]}}}
```
Builds a format for each row, then uses the `%` operator like `sprintf` to populate it.
The fact that the card value appears on every 3rd row is handy. Card values are presented in hexadecimal with the digits `01BC` substituted to `TJQK`.
Saved 4 bytes from the suit symbols by considering that the top of diamonds and spades are the same but added 2 back on for the `-4` at the end of `j%4*4-4` Suit codes are -4 0 4 or 8 where `[-4,4]` means 4 characters starting the 4th last character in the string.
Could probably save a few more bytes. Having to repeat code for the player identifications is ugly.
[Answer]
## PHP, 509 bytes
```
<?$hu='(\/}';$hv=$dv=':\/:';$du=$su=':/\:';$sv='(__)';$cu=':():';$cv='()()';$q="------";$t=$argv[1];foreach([h,d,s,c]as$a)foreach([2,3,4,5,6,7,8,9,T,J,Q,K,A]as$b)$c[]=[$b,$a];shuffle($c);$h=$a=0;for(;$a<$t;$a++)$e[]="Player $a";$f[]=join(" | ",$e);for($g=$argv[2];$g--;){$p=$i=$k=$l=$m=$r=[];$j=$h+$t;for(;$h<$j;$h++){$n=$c[$h][0];$o=$c[$h][1];$p[]=".$q.";$i[]="|$n.--. |";$k[]="| ${$o.u} |";$l[]="| ${$o.v} |";$m[]="| '--'$n|";$r[]="'$q'";}foreach([p,i,k,l,m,r]as$b)$f[]=join(" | ",${$b});}echo join('
',$f);
```
[Try it online!](https://tio.run/##XZBNb5tAEIbv/RUIvdKy8oDzndbrVZRremmk3jCKMAYvNgYMtqXK5q@HzmInirKH0c4zX@9Mbeq@nz7B7LXwZuNOKJiDxuKgxWQ2nrC72Gu0HJ2MZ9ZtOeK9vUn@JpZ60tLEUulZutWuPzxXYacRN8tDeB2prGrSODFeaGhBLSVR3CKWn/SGbumO7umBHukn/aK/9EKv9Juebd5cIgkjHWJOiCPVmn2WFamHRLJaHqGvbHtPIZ5ix3Y0kki5wP1TxP/SxkHMWjIGqyovPdc5OS4hlUMRlheNN5HC0veVPKLWyDXWGoXGRqPRIcdWGmbE7c@TzBQrtjzpiFKzPJgovOK06sPhnVFbEQG2Ac/P7f@EMvD9wDkxWA/AwRFVsO8GVHxBhzPanJHwfYHSgsYCga1wVfd5vppyWlNBG2ouB/u@7hHzTqouTUzlDFz8EIRMqr7v7/uH96re5VXZ9n75Hw)
This is my first attempt at code golf, so it can probably be improved a lot. I figured I had to start somewhere. :)
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~784~~ ~~835~~ ~~843~~ ~~826~~ ~~815~~ ~~781~~ 775 bytes
```
String k(String s){return s.replaceAll("...$","\n");}
p->q->{int c=0,l=0,s[]=new int[p*q],i=0,j,t,b;java.util.List e=new java.util.Stack();String v="TJQK",o="",n[]=new String[p*q],x=o;for(;i<p;o+="Player "+i+++" | ",x+=v);o=k(o);for(i=0;i<q;i++){o=k(o+x.replace(v,".------. | "));for(j=0;j<p;j++){do{t=(int)(Math.random()*13)+1;b=(int)(Math.random()*4);}while(e.contains(t+""+v.charAt(b)));e.add(t+""+v.charAt(b));s[c]=b;n[c]=t<2?"A":t<10?""+t:""+v.charAt(t-10);o+="|2.--. | | ".replace("2",n[c++]);}o=k(o);for(j=0;j<p;j++,l++)o+="| "+(s[l]<1?"(\\/)":s[l]<3?":/\\:":":():")+" | | ";o=k(o);for(j=0;j<p;j++)o+="| "+(s[i*p+j]<2?":\\/:":s[i*p+j]<3?"(__)":"()()")+" | | ";o=k(o);for(j=0;j<p;)o+="| '--'2| | ".replace("2",n[i*p+j++]);o=k(k(o)+x.replace(v,"'------' | "));}return o;}
```
[Try it online!](https://tio.run/##jVNda9swFH1efoUQg0iVrTbp9jArTiiMwT4KG91bYopiq60cVXJtJW1J89uza0drMhbGZIzlq3PO1bmXW8qVjF2lbFksttVybnSOciObBl1KbdG696bx0kPwytfa3qIFCZuGrmvll7VFDa9VZWSuLowhmHP@Fkd4ZjEVm1d2CWn40mvDb5Y299pZ/ilsRp@tV7eqjv4PtEs/HqNc1sVHJY2qUYq2VTx@iMdrbT3K07PIwNtMs9SqRwSxaXXykEUagmXko7nYZ/qmG49Uh9sHr7zMF4SKYHWV4p9ffnzFkUsxjmyQ3R3ulJ9SJ25cTYQeVcKxFH838hkuhplmjGH0gnD0xNIVFS5dEEc7MFwH8A8CIHTdxdnT71KSVYR53C3esumOUgKlhBRlSync2qcE3FFyKf0dr6Ut3D2hJ4NzygZifvTsHXTl8U4bRRTPnfXQ5IZ4hjFb8fxO1heezClkU1wWxd8HopnmWToXtv340XCCL3DiR4OzCQB9coj28eCMdsV4GfKdDTDyahAP21LmjGVwo4OqHFiMDNjsBKCQpJmabDSYYDKbnVKcdL/nE5yczmYJhofQBNOu1gAXxxUP1fRJxcqstZCAYtIqhhCokutryIEJJfTfokGxH8f94TGDnWRnsiW39D@b3N81uR@avAkz5cRmK3o9BCsMZRikldMFuoeuhTmcZkhSGFMU1tVz49U9d0vPKzj3ZD8mXFaVeSYfaNi8h3wdb9PbbH8B "Java (OpenJDK 8) – Try It Online")
Why the downvote, it complies with the spec
[Answer]
Python 3, 332 Bytes
```
from random import*
P=lambda x:print(*x,sep=' | ')
R=range
def f(p,c):
P(f"Player {i}"for i in R(p))
d=[f".------.,|{n}.--. |,| {a[:4]} |,| {a[4:]} |,| '--'{n}|,'------'".split(",")for a,n in sample([*zip(r':/\:(__) (\/):\/: :/\::\/: :():()()'.split()*13,'A23456789TJQK'*4)],p*c)]
for i in R(c):
for t in zip(*d[i::c]):
P(t)
```
] |
[Question]
[
# Challenge description
In **taxicab metric**, a distance between two points [](https://i.stack.imgur.com/4OjWi.gif) is defined as:
[](https://i.stack.imgur.com/71YE5.gif)
Consider a matrix with only zeros and ones:
```
0 0 0 1 0
1 0 0 0 0
0 0 0 0 0
1 0 0 1 0
1 0 0 0 0
```
Let's map each `1` to the distance to nearest *different* `1` in the matrix (of course, assuming that distance between two adjacent rows/columns is equal to 1):
```
0 0 0 3 0
2 0 0 0 0
0 0 0 0 0
1 0 0 3 0
1 0 0 0 0
```
For this challenge, given a matrix, find it's map of distances as shown above.
# Examples
```
0 0 1
0 0 0
0 0 0
0 1 0
0 0 0
0 0 4
0 0 0
0 0 0
0 4 0
0 0 0
-----
0 0 0 0 0 0 1
0 1 0 1 0 0 0
1 1 0 0 0 0 1
0 0 1 0 0 0 0
0 0 0 0 0 1 0
0 1 0 0 0 0 0
1 0 0 0 0 0 0
0 0 0 1 0 0 1
0 0 0 0 0 0 2
0 1 0 2 0 0 0
1 1 0 0 0 0 2
0 0 2 0 0 0 0
0 0 0 0 0 3 0
0 2 0 0 0 0 0
2 0 0 0 0 0 0
0 0 0 3 0 0 3
-----
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
-----
1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1
22 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 22
-----
0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
0 0 9 0 0 0 0 0 0 0 0 2 0 0 0 4
0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0
-----
1 1
1 1
```
# Notes
* You may take input in any reasonable format
* Apart from `0` and `1` you may choose any two distinct values
* You may assume that a matrix is non-empty (contains at least one row of length larger or equal to 1), as well that it is rectangular
* You may also assume there are at least two truthy values present in the matrix (otherwise, output is undefined)
* You may write a full program, or a function
* Instead of returning a new matrix, you may modify an existing one
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your byte count as low as possible!
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), ~~14652~~ 14572 bytes
Saved 80 bytes by using `plan ?` instead of `plan "?"` throughout. Now it's even more confusing in its golfed version *but* it's 0.55% shorter so that's worth it..
```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 r 1 l 2 r.Pickup a passenger going to Auctioneer School.Pickup a passenger going to Chop Suey.Go to Auctioneer School:n 1 r.1 is waiting at Starchild Numerology.1 is waiting at Starchild Numerology.Go to Starchild Numerology:s 1 l.Pickup a passenger going to Rob's Rest.Pickup a passenger going to Bird's Bench.Go to Rob's Rest:w 1 r 2 l 1 r.Go to Bird's Bench:s.Go to Chop Suey:n 1 r 1 l 2 r 1 r 3 r.[a]Switch to plan d if no one is waiting.Pickup a passenger going to Crime Lab.'|' is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 3 l.Pickup a passenger going to Crime Lab.Go to Zoom Zoom:n.Go to Crime Lab:w 1 l 2 r.Switch to plan b if no one is waiting.Pickup a passenger going to Firemouth Grill.Go to Rob's Rest:s 1 r 1 l 1 l 1 r 1 r.Pickup a passenger going to Firemouth Grill.1 is waiting at Starchild Numerology.Go to Starchild Numerology:s 1 l 1 r 2 l.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 4 l.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:n 1 r 2 r 1 r.Go to Bird's Bench:s.Pickup a passenger going to Addition Alley.Go to Firemouth Grill:n 1 r 1 l 1 r 1 l 1 r.Go to Cyclone:w 1 l 1 r 2 r.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Bird's Bench.Go to Bird's Bench:n 1 l 1 l 1 l 2 r 1 l.Switch to plan c.[b]Go to Rob's Rest:s 1 r 1 l 1 l 1 r 1 r.Pickup a passenger going to Cyclone.Go to Bird's Bench:s.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 r 1 l 2 l.Pickup a passenger going to Trunkers.Pickup a passenger going to Addition Alley.Pickup a passenger going to Sunny Skies Park.Go to Trunkers:s 1 l.1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:w 1 r 3 r 1 r 1 r.Pickup a passenger going to Rob's Rest.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Bird's Bench.Go to Sunny Skies Park:n 1 r.Go to Rob's Rest:s 2 r 1 r.Go to Bird's Bench:s.[c]Go to Chop Suey:n 1 r 1 l 2 r 1 r 3 r.Switch to plan a.[d]Go to Rob's Rest:n 1 l 3 l 1 l 2 r 1 r.Pickup a passenger going to Firemouth Grill.Go to Bird's Bench:s.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:n 1 r 1 l 1 r 1 l 1 r.Go to Auctioneer School:w 1 l 1 r 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 4 l.Pickup a passenger going to Auctioneer School.Pickup a passenger going to Chop Suey.Go to Auctioneer School:n 1 r.0 is waiting at Starchild Numerology.Go to Starchild Numerology:s 1 l.Pickup a passenger going to Addition Alley.Go to Chop Suey:w 1 r 3 r 1 r 3 r.[e]Switch to plan g if no one is waiting.Pickup a passenger going to Cyclone.Go to Zoom Zoom:n 1 l 3 r.Go to Cyclone:w.Pickup a passenger going to Crime Lab.'|' is waiting at Writer's Depot.Go to Writer's Depot:s.Pickup a passenger going to Crime Lab.Go to Zoom Zoom:n.Go to Crime Lab:w 1 l 2 r.Switch to plan f if no one is waiting.Pickup a passenger going to Firemouth Grill.Go to Cyclone:n 4 l 2 l.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:s 1 l 2 l 1 r.Go to Chop Suey:e 1 l 4 r 1 l.Switch to plan e.[f]Go to Cyclone:n 4 l 2 l.Pickup a passenger going to Joyless Park.1 is waiting at Starchild Numerology.Go to Starchild Numerology:s 2 l 2 r.Pickup a passenger going to Addition Alley.Go to Addition Alley:w 1 r 3 r 1 r 1 r.Pickup a passenger going to Addition Alley.Go to Joyless Park:n 1 r 1 r 2 l.Go to Chop Suey:w 1 r 1 r 1 l.Switch to plan e.[g]Go to Addition Alley:n 1 l 2 l.Pickup a passenger going to Rounders Pub.Go to Rounders Pub:n 1 r 1 r 2 r 1 l.Go to Joyless Park:n 1 r.Pickup a passenger going to KonKat's.[h]Switch to plan i if no one is waiting.Pickup a passenger going to KonKat's.Go to Zoom Zoom:w 1 r 2 l 2 r.Go to KonKat's:w 1 l 2 r.Pickup a passenger going to KonKat's.Go to Joyless Park:s 2 l.Switch to plan h.[i]Go to KonKat's:w 1 r.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:s 3 r 1 l.1 is waiting at Starchild Numerology.Go to Starchild Numerology:s 1 r 1 l 1 l 2 l.Pickup a passenger going to Joyless Park.Go to Joyless Park:w 1 r 2 r 1 r 2 l 4 r.[j]Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 2 l 2 l.Pickup a passenger going to Joyless Park.Pickup a passenger going to The Underground.Go to Joyless Park:n 2 r 2 r 2 l.Go to Tom's Trims:w 1 l 1 r 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 r 1 l 2 r.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Chop Suey.Go to Tom's Trims:s 1 l 2 r 1 l.Go to Chop Suey:n 1 r 1 l 4 r 1 l.Go to The Underground:s 1 r 1 l.[k]Switch to plan l if no one is waiting.Pickup a passenger going to The Underground.Go to Chop Suey:n 2 r 1 l.Pickup a passenger going to Firemouth Grill.Go to Zoom Zoom:n 1 l 3 r.Go to Firemouth Grill:w 3 l 2 l 1 r.Go to The Underground:e 1 l.Switch to plan k.[l]Go to Chop Suey:n 2 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 r 1 l.Go to Chop Suey:n 6 r 1 l.[m]Switch to plan o if no one is waiting.Pickup a passenger going to Firemouth Grill.Switch to plan n if no one is waiting.Pickup a passenger going to Firemouth Grill.Switch to plan n if no one is waiting.Pickup a passenger going to Firemouth Grill.[n]Go to Zoom Zoom:n 1 l 3 r.Go to Firemouth Grill:w 3 l 2 l 1 r.Go to Chop Suey:e 1 l 4 r 1 l.Switch to plan m.[o]Go to The Babelfishery:s 1 r 1 l.Pickup a passenger going to The Underground.Go to The Underground:n.Switch to plan p if no one is waiting.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:s 1 r.Go to Joyless Park:e 1 l 3 r.Switch to plan q.[p]' 0' is waiting at Writer's Depot.Go to Writer's Depot:s 2 r 1 l 2 l.Pickup a passenger going to Heisenberg's.Go to Heisenberg's:n 3 r 3 r.Go to Joyless Park:s 1 r 1 l 1 l.Switch to plan 4.[q]Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 2 l 2 l.Pickup a passenger going to Joyless Park.Pickup a passenger going to The Underground.Go to Joyless Park:n 2 r 2 r 2 l.Go to Trunkers:w 1 l 2 r 1 l.[r]Pickup a passenger going to Cyclone.Go to Sunny Skies Park:w 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l.Pickup a passenger going to Trunkers.Pickup a passenger going to Rob's Rest.Go to Trunkers:s 1 l.Go to Rob's Rest:w 1 l 1 r 1 r.Go to Cyclone:s 1 l 1 l 2 l.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to Bird's Bench.Go to Zoom Zoom:n.Go to Sunny Skies Park:w 2 l.Go to Bird's Bench:s 2 r 1 l.Go to The Underground:n 1 r 1 l 1 r 1 r 2 l.Switch to plan s if no one is waiting.Pickup a passenger going to The Underground.Go to Rob's Rest:s 2 r 1 l 1 l 1 r 1 r.Pickup a passenger going to Firemouth Grill.Go to Bird's Bench:s.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:n 1 r 1 l 1 r 1 l 1 r.Go to Trunkers:w 1 l 1 r.Switch to plan r.[s]Go to Rounders Pub:n 1 l 1 l.Pickup a passenger going to Cyclone.Go to Joyless Park:n 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 2 l 2 l.Pickup a passenger going to Rounders Pub.Pickup a passenger going to What's The Difference.Pickup a passenger going to Joyless Park.Go to Rounders Pub:n 2 r 2 r 2 r 1 l.Go to Joyless Park:n 1 r.Go to Cyclone:w 1 r 2 l 2 l.Pickup a passenger going to What's The Difference.1 is waiting at Starchild Numerology.Go to Starchild Numerology:s 2 l 2 r.Pickup a passenger going to Addition Alley.Go to What's The Difference:w 1 r 3 r 1 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:e 2 r.Pickup a passenger going to The Underground.Go to The Underground:n 1 r 1 r.[t]Switch to plan u if no one is waiting.Pickup a passenger going to The Underground.Go to Trunkers:s 2 r 1 l.Pickup a passenger going to Trunkers.Go to Sunny Skies Park:w 1 r.Pickup a passenger going to Sunny Skies Park.Go to Zoom Zoom:n 1 r.Go to The Underground:w 1 l 2 r.Switch to plan t.[u]Go to Trunkers:s 2 r 1 l.Go to Sunny Skies Park:w 1 r.Go to Tom's Trims:s 1 l 1 r 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 r 1 l 2 r.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Chop Suey.Go to Tom's Trims:s 1 l 2 r 1 l.Go to Chop Suey:n 1 r 1 l 4 r 1 l.[v]Switch to plan 0 if no one is waiting.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 r 1 l.Pickup a passenger going to The Underground.Go to The Underground:n.Switch to plan z if no one is waiting.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:s 1 r.Go to Trunkers:w 1 l 1 r.Pickup a passenger going to Cyclone.Go to Rob's Rest:w 1 l 1 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 l 1 l 2 l.Pickup a passenger going to Trunkers.Pickup a passenger going to What's The Difference.Pickup a passenger going to Rob's Rest.Go to Trunkers:s 1 l.Go to Rob's Rest:w 1 l 1 r 1 r.1 is waiting at Starchild Numerology.Go to Starchild Numerology:s 1 l 1 r 2 l.Pickup a passenger going to Addition Alley.Go to Cyclone:w 1 r 4 l.Pickup a passenger going to What's The Difference.Go to Zoom Zoom:n.Go to What's The Difference:w 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Multiplication Station.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to The Underground.Go to The Underground:n 1 r 1 r.Switch to plan w if no one is waiting.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:s 1 r.-1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 1 r 1 l 2 l.Pickup a passenger going to Multiplication Station.Go to The Underground:w 1 r 2 r 1 r 2 l.[w]Go to Multiplication Station:s 1 l 1 r.Go to Sunny Skies Park:s 1 r 2 l 1 r.Pickup a passenger going to Cyclone.Go to Bird's Bench:s 2 r 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 r 1 l 2 l.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to What's The Difference.Pickup a passenger going to Bird's Bench.Go to Sunny Skies Park:n 1 r.Go to Bird's Bench:s 2 r 1 l.1 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 r 1 r 2 l.Pickup a passenger going to Addition Alley.Go to Cyclone:w 1 r 4 l.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Multiplication Station.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to The Underground.Go to The Underground:n 1 r 1 r.Switch to plan x if no one is waiting.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:s 1 r.-1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 1 r 1 l 2 l.Pickup a passenger going to Multiplication Station.Go to The Underground:w 1 r 2 r 1 r 2 l.[x]Go to Multiplication Station:s 1 l 1 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Addition Alley.-1 is waiting at Starchild Numerology.Go to Starchild Numerology:s 1 r 2 l 1 l 2 l.Pickup a passenger going to Multiplication Station.Go to Addition Alley:w 1 r 3 r 1 r 1 r.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:n 1 r 1 r 3 l 1 r.Pickup a passenger going to Addition Alley.1 is waiting at Starchild Numerology.Go to Starchild Numerology:s 1 r 2 l 1 l 2 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:w 1 r 3 r 1 r 1 r.Pickup a passenger going to The Underground.Go to The Underground:n 1 r 1 r.Switch to plan y if no one is waiting.Pickup a passenger going to Narrow Path Park.[y]Go to Narrow Path Park:n 4 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan v.[z]Go to Trunkers:s 2 r 1 l.Pickup a passenger going to Trunkers.Go to Sunny Skies Park:w 1 r.Pickup a passenger going to Sunny Skies Park.Go to Zoom Zoom:n 1 r.Go to Trunkers:w 3 l.Go to Sunny Skies Park:w 1 r.Go to Chop Suey:n 1 r 1 r 3 r.Switch to plan v.[0]Go to Rob's Rest:n 1 l 3 l 1 l 2 r 1 r.Pickup a passenger going to Firemouth Grill.Go to Bird's Bench:s.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:n 1 r 1 l 1 r 1 l 1 r.Go to Narrow Path Park:e 1 l 4 l.Pickup a passenger going to Writer's Depot.[1]Switch to plan 3 if no one is waiting.Pickup a passenger going to Cyclone.Go to Zoom Zoom:w 1 l 1 r 1 r.Go to Writer's Depot:w.Pickup a passenger going to Magic Eight.Go to Cyclone:n.Pickup a passenger going to Magic Eight.Go to Magic Eight:s 1 l 2 r.Switch to plan 2 if no one is waiting.Pickup a passenger going to Writer's Depot.Go to Cyclone:n 1 l 2 r.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:s 1 l 2 l 1 r.Go to Narrow Path Park:e 1 l 4 l.Switch to plan 1.[2]Go to Cyclone:n 1 l 2 r.Pickup a passenger going to Writer's Depot.Go to Narrow Path Park:n 2 r 1 l 1 r.Switch to plan 1.[3]Go to Writer's Depot:w 1 l 1 r 2 l.Pickup a passenger going to The Babelfishery.' ' is waiting at Writer's Depot.Pickup a passenger going to KonKat's.Go to The Babelfishery:n 1 r 2 r 1 r.Pickup a passenger going to KonKat's.Go to KonKat's:n.Pickup a passenger going to Heisenberg's.Go to Heisenberg's:n 1 r 1 r.Go to Joyless Park:s 1 r 1 l 1 l.[4]Pickup a passenger going to Magic Eight.Go to Rounders Pub:w 2 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 r 1 l 2 l 2 l.Pickup a passenger going to Rounders Pub.Pickup a passenger going to Magic Eight.Go to Rounders Pub:n 2 r 2 r 2 r 1 l.Go to Magic Eight:n 1 r 1 r 2 r.Switch to plan 5 if no one is waiting.Pickup a passenger going to Addition Alley.1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 1 l 2 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:w 1 r 3 r 1 r 1 r.Pickup a passenger going to Joyless Park.Go to Joyless Park:n 1 r 1 r 2 l.Switch to plan j.[5]Go to Auctioneer School:w 1 l 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 3 r 1 r 3 r.[6]Switch to plan 9 if no one is waiting.Pickup a passenger going to Crime Lab.'|' is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 3 l.Pickup a passenger going to Crime Lab.Go to Zoom Zoom:n.Go to Crime Lab:w 1 l 2 r.Switch to plan 7 if no one is waiting.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:n 1 l.'\n' is waiting at Writer's Depot.Go to Writer's Depot:w 1 l 1 r 2 l.Pickup a passenger going to KonKat's.Go to KonKat's:n 3 r 2 r.Switch to plan 8.[7]Go to Heisenberg's:n 5 r 1 l.Pickup a passenger going to KonKat's.Go to KonKat's:n 1 l 1 l.[8]Pickup a passenger going to KonKat's.Go to Chop Suey:n 1 r 1 r.Switch to plan 6.[9]Go to KonKat's:n 1 l 1 l.Pickup a passenger going to Post Office.Go to Post Office:s 3 r 1 l.
```
[Try it online!](https://tio.run/##7Vvfc5s4EP5X9OanMg52UjdvzfWuN9drLxPnpjOn4wFj2ajG4Aooccf/eyowGEkIkAAn18y107gG/Vx9u/vtrhLZD/jx8X0AogDcBmEE/lqtsIOuE3ABPPqPpJ/GLXY28Q7YYGeHIfLXiIB1gP112uuXveMFPjKOY@TfrsOiLzABaez/NnYiTLvQZ3PHDYKW2dxgB@Yx2ufzVXpf@@nMxgXAIUhsHKX97AjMI5s4LvaW4FO8RSTwgvVerdFxHtmrbJPNy70LFqMQ3KEwamx2g8mStrtBvuPmE5Y9s7MgVI7ZeeSv2R7XYSH8QjhHIRTiz/4/oV2hbc0THDlu2njn2T5YArwCfgCoBBlZNJ8AwVsE/rQXxugwEgT4meAIEbqud2gXRPmq@IfZ0jy6HE9xluMg/wTBNvtx7RebLVrkWE1xJuxuob@73zBB2yCOXPCeYM@rHkYJ7FJBiNaQg6CugEQH1TzCaaqO3IoM/Hx2Ug/IRo1fLnGqtOCt550UWZASg2DmU7KTQhJEf0r@IZ3RVDhNiapyW/cZbBTa54nAdAy4sAaAFn/AGkcgRwZrNZrRcU9if4OI1jk3NZ3Hvr8H8w1GIbi1ySZfWDFNbmn7ak6itDcVrCSFTVU6poousQL3Wp2IBHKivHKvJ4FUo5ZCx1LzHAJ@bQMuLalZyCw7272DtdXAsXwAHVtSJRB9qY/falvPQ3nGZ2czUs0oocMrRUY4kEg41h0IBydlhgjkcKt4hbPSl/D8tGU1FG3hENlq99R0KSxsKOuPTxBA2dup3OshA66sLiv7I9h7KMw9Q3/6ZKpEJYM7AemI7M5OZupI7OTadVEr2rVVw2pUfN5dEPtL6mjBbbw4eZHyEbe04wLq1t84zYfA/2BHI@p4XNEwYH3Qn0YTda0MmMwTRovGjNppjM3tM0OQeAKuAbElmap5mvtgSy3LPbUJxUzMEzrRJJf2EDEDYViphr5JBJCw/D@T8zQ19l@srsGIqbuoRpm6CPydQndNUgjLkWrmGyg1jRX802U/WADokAAeJmyoUU/oplwLQUzlmg24EZXT01dO@SmwyzIVxCv3SfUcQPRWSUZHeW8lbhzJDOrGgJ7Vbc3p@Df2AnkrHLqI7Jlp2ceMwKvzXBVHsRWPIuhPDoQR/f/iiNC3hjhrRWayNWBgtR6TPtxFqPnixLuhqJ6MphGZ6UMnKQpL@WrAnTUC406kuFCMViv@O8L00YJK5ORb2Uf0kCd57CB1vIwXE9c/NeDXn9sBFcmOhLPnkGjsqpIXSDRzSFxmon8KqJL5EDI60lx3mfuqelU1AlNJJ2mmV6phm0Sw5cnxCQvBE1dsgJCMIDI2GQ7lcCW5oO6Z62dIzwhKcVG1W5R4hlZNyOJp8jfNcKavReGirqaGn900nsiO@B1erRChske6FF6QTmmAWgK6rruTL/oZw3fpgrgovn9iGLUzfjWmcFJQGIkUMB7KODDGWInYFha/s6@pSfPzHK@Op9fmyyIDxlbtjhoXWxdMvdTQD34TwTTuBia9AOcMzPn7UzBnifdRR0Qtq@kGKm@4wpy@O@nJ456u5C0vUWhVvuXSqSOGDU6lw0Ej3TRyU9OPsRfhnYcdO@tAJZt@9il@6/ouQWeT8@rsq2Hqw6o18EbxypwXlzI1YJL7LPk4JebrPFjIXQvqek1AyfP3vS6gFY/pWyfdAnmNBPrCh6/fPKOVktskv@Mxv2yb9PC/TWJs0oOqTRoIDkLTV8PUuUxFsqQDRr1ib@PINcItzcdEX8hPK7jhq@M9tXivr8WfbEKChDoHqrGZT4L7HPzim/xGj6yiQOqyUt8M@N36KaLsMsSZqEXL1fhSekeMSmD8Qu6IVQBRFJNaXDRfOYEXYuw9Ge4ylCxvLhRpmu9FfbTX2AG/4rVbuaSo2Y95UuYnRHSY@luXFqL4m5RmJyypXHFqgICwswsDmlaXxUn3J7FFZr3VoXNPLPnhK0fQlezOCLSUBDXu0VRyRPxVco2RTpds/J71Rl5nGuqNcGrpKQKXcE863tbngqzhKgotq60rD7C6zd0JE5F4qa/fAzOaRDlnNjybabtA5TfV/r4Y8NJqu5ysd2WYddnc/dwr0SW9edG/EPT6XMHeMbYe/et3EYC6ba61gdmpSjY8M@BrS2r2LhWoaP10J5s4szQGkDBHccFXBnxj1U7XNBfz24tG9fcZy6uUj4/j7M/sMJ7Rv@PxYTbLv2dfx4fj6/Hh@JW@P3Y4ZE/Hsx8)
I'm presuming that no human wants to try to read through that code so [try it online with comments, meaningful labels, and more readable output!](https://tio.run/##7Rxrc9vG8bt@xY0/VEmq0Hq4HVWTZEaWZFe1LWlEZSxF5QcQOJKoQRxzAAyz4//u7u7hcIcnAZJW2qT0WBLx2Nvb9@3uXex88r98eWTv/NCfOwG7g@/szBmzcz@KndDlbLTzyC7DaOFL7rHx8oTN4ngRnTx/7gqPT0UwGcCD7gf@yZ054ZQPXDF//uvzg6Pjo4MDeBnfvrr5@e6EsWEs/XDKxIQdsz@xfZZE@NVhC3/B2WfmRPC3xwM/5E4sJJvAf@64MyZFii/FM84cKZ0lq3wQx@uf72iYbBR4e@7EMeCMcMPszWgmUrw790MW41Q9Pc2JFHM13DGLBQ0GeEgexUzAFwmXcZQrEXOYCjsNARhACjiAmPox@4kdsDmMMOYsSsZR7McJDo6TOB6wy8HFYI/BY/MEAMIzh@yHH5mPP/5WmQsMc3N7fXYxHJ6wTT@I8xCoydnw7vzyivFPjhsHSySKHy6SGEjjsQ@cLxA5R4oEviZh7AdEAQ7faoEdKXpGJyAaAGWP3bMbEfmxL8Jojz2YL10wc5gL48bIY2APUBFoywM@52EMrIMHgFk0TDuwV1pesnfz1/aYK0GkuBEDGGmeCTxJgQsCryUhUsB8mDqSgJ5L5uyjEyScTQmQhDsA699cChwEvsQZYKRmRJPyY4PZjeOx1I9nMNNo4biIiAfSMIGHdiMaJXBALCy88RqI/R68gfrAxjDuBwXsli8AB6Md2Vt7NC7KtoV1pB6J/Tmvp9mZCF2YUEjUCRTTQeaTACkPcxFJ3Er3otSen96d1t59e312end5fVW8entxOixfM6g1cvw0cVG0OLBh6M6ECOjqWSAijpp7tnQDuFsHLH0u2LkxMPi5E3NgwZ3057ao3iZhSKYqIakUi1yWEdiFls2yXN6i@nAZsZtkbIDlmP1DLAMewV1HfjCYgTg5CL48zcrTRWB3wKmfcbSpUloCdt@keHcyCT8gZoVPDuxWjIEKt2jsDM0atXgI1Fmy4Qef29jlwF760gNoL3kIoleiGVy/LwlBeWj6XDjREmFJeGs@5rLITQPsoQisMnQHYKfaIhgDoD5XoNJgjm4cUFwzzbeXr66ZH7HrN6SC8cyP6oDlCph9/s79iIcw@HQ3qmHAGxG@cWLrFumTcjbvOXhKTqpZK8bwOhnwWIIbxrH9WpFC9F4ucyuB5j5mZzOxAH7y5R5LOZjBUIGaCnxE@QG4DsKjVWHhRDCPKYqSjeKMh9qdk1/IfCaZySbE95CMgIYrQchcMMWEIhlTxIWUuGDP0SDx8NeEjKszdfxwQGpg5kskQCxSPwiyOQc8BtRw3gtwvBO0zQB@ii4eNGc6s@KKDOYqMzcUc2QHjBOxS4DvyBDDjDGSiOInsAtg7Vg68yE8SHF6ZJb96GSVq2bfsweRECOUG0FfmNMcOfZe4nRBUs75QiiaDGNHujCWx66SOfikQEyX64AuyCgR@yOwdeGDVAGN5ixZKAqx7@C/kGB7vstAM/YNwvZEuBsDdEfG9BoJ0YJJgAXBlR/GnARHxxcwJDAT2RkBP0L@bT1BLidsCcBjSUrsSeBjBBxA8QAIlv0AXSgYgDHwgzysE4D79EAvXTdZ@Bx8b4Y1yFFKOHNQdYkyriTKkOVfGK/BjJaRdsvEYWAtDEBStpBi7IwhpHIdVFMN2mHP7oRg75DKN7nSPMtGQsrGCXjcJcSGoAICRpljJJRy/oFN/GmSuXKYIU6UMEPp26HoEGgLdI1iD3CikGMR@DhXpLEwsdNo57VAmt0g@OvJxHf5SQpxagD/Jf4e7GSgHGvKSvmNJx1kULKvJ5F@G4JY2Q6h4qpXDKitkR6y8v5JiIMPdg5QZlJHaRbQqE4Fuj6lhqq7R1NdgbORv/bnbMnUY5p3iS0SCBqo@an79jsnUc4HTSVFDM0J@vsIX8a4TgW8uWmL0Hbfw6rrgS1ypw6SesU/xWSbM5c62hlCoIoho2CLAEzFs/sHBct7hgFrKEgcDVlXMFRi5PnWGQ92dj/vlrhRtGR6dsWrNMUAphV0HkiB@UWAxcEfJ2FON/1MpgMkveXpIkHORJDMw6b5otODh4B5qVrDgH@5Zz8CSNTEB/jrgf2Z4dK3DeFXsJyeg1bP2GsJVqRGIoyaGYVdoW4VoNtRAC2aa1kLJdgv@qhRhRRhhoFsU45WO@R5JPPsNAiMdSmRy1In63fdfDRF5DqjFq/CoIddWFtnPgoUCC1R0fYgqMr3RehdTzJlf4bCbATeFuZ7FOG9bH1etRvbENaSvPRhZ4Oo2eZwhbjp9VA/BrY9W14UaeT0SNqXbKySabcZdhK@VDuNbiyrKqlN@mC1s6yT4jLhtIuvkbEVFmDn0ZbuUVd3WecCbJ9IapK7QcqaQMwfYmRLqRs@icVHtSCqtVzkvuxhB@t4hj760QCio70rhg@1S85I5VhHjWHa5lFmuNpnfLXocv8J4sZ6/TTCWlTNLK7LRfO9H8@Ak4YljfGbeeQWmP9xzTiuyCMruMrku@omv3ZgGD1VQCji0xt/wdchW4MeFkR8tSXvqM2R9guFqCWXJ063XzTFBSslSwULGTFG683ETmluJTg97LQI/QqesB6mPb/cumahc71@H2zGj4pyj5qCzE4xg52/Ng7YXCvMKUO8aebtI@l8pzZqL/0a00XeHO5E6@ieGaGs/2apfWgURT9um4I@4AsEiBSp63gK03mWRyo4t1EdAisGt4oWeZhpLsHwR5o7VGPDdByVn9CfT3wZxcydOdJxsZI12s4iUVpLj15WoIZ8qb3cI0a9IPeHszmNVcp9AdBiSlrPnI8qUpmIIFDVXc@JHYxRwL8nkp@0l5PaqkqNpaNvLlNx/m1zBam1TNRWLSqWhDCrUP3UVoZayz9tVaDWUk9bxSdLdK5Xk77C4maqKhuF@WDtXRUyEqlSychRYje9iEkWJD4@qBL/PM/k6wqmB6G3HxIJowHmj1VhgZfgAdtUVRfk6YcfYbkbYxnD8Ty2u892cQB6sZIWnwrTIfApL9vSQApeNkcA@5OG6jqBmwQ6qM67DjBbC2uHZVYvyV40EHGilGVWSfVJAn8iCmPO@HwR@6q9IeV6xAaCwNo98sdBmTLXiEJedYHZeaAAe8wFr87Z2KG8v66RYKFKV4ZVAp9eTNGiZKXyaA7jYSJeUeGnfUIV6Ul5bKSnEQCbqgN24dP8U2e5x3RxAV9Ap1Z6Mad7kZkkTTjWQdme7GUvujNOM3KyqgA9QBUqWxP3COlAiEUuOfR0KGJ6I@NnynclJ3qxSOjaGQjGOEHjaKGaVdBz@2sV0Eoll4GZ43u@C5zTVb@qaYIZEtWxcybKEFBzdJQAm6aBSMtqhgiIC0DyuDcoFLXQN2UG65WQw4y0N0hZqnldfEKtzIwvz@uvitOj9RODh/09RqtnLFbFG8KTw8y9WIGZ7T@ftERS8OW9lq9Fl1/I@jVnPl4UHynRyyCOocNrHsN9SzKqIdorfOsOZEJHpWtEag08s7E/7MKLhnVSy2K1vIRKKVNTWkKVScTrA/YKsSjMK9NntO7kEIuXzpgHEz8CS7m0sbOv2xysDvVXw9w76USzVt7q@AWWEPTweqmDClfKwwD4W9@j2uh/PfTHHNxoS9LVeYFe5pdaRVRYNOogF2soY1kJwiqCl4DGL7Ak2GKipC7FIWttOjfEr4ix8lz3D0QxjeVoZ5ftD/bps17@SevtavdVcPIZNPsaiM6RzvHVriat5VWN4RGxQLko@Gyaq@W0dRGH/HVkOpd0aw3EDjmdfg/eXBdd0qJfJJ@GxOo5y0qNIu1d3ypUSrZRnKoWY8qlptomA6s6V41ZOq7gq7WuvkWfmmxsDY0tjhbLH@VIp2KeSpUNWZ@QIe8MhmF7QUtNuWqT@v1Tl35qteegzqrmemTCHNSpR/YG@weliJ1Y9yJnDSh5V/kSV05qdSmA7BK7sEdN2cagdwzeNxW5uUErpk3bnnyvltkoPOf@ZMIlsJT3z5aVqGQM4Mqc7NpzbMD8t83h1yJVSOVvo0jOOyziOkZNxgzsPN6ijnBUmmrLlSO5uu1t0TZZ7qHbkiN3Q@s7waauiGLY3LjWaqnLafKh/cHyvCHZ6A@XJq7//BeliRu7/9s2AbR2@rc1/GeN6SmyHXNdKDSumANpa7Kv2GCussuFvT2ob0TkzhnYptwrgWlLwHbLvRKYYgK2X@6VcLHBNOQfu@bw1SYpWF0SZK2O2A7totSNl9SqvVA7/ibl3CeiAdq@VHo55pQil5LIqTa04IYNB7BjcyDMkpYsU8fstWi2ae3WCiti1C1NnKV@6YXP1bavprza7zwVqLK/50YyG0qx1hPRun6pbw7r6@QqrJlcRk@TtMCuqkIN6N7YoVFL4N1D5JpXemvKbbDNZso1Yt/Nl7hP2QDd0NHVrw@6gUqNq@aWEHgttvP@vS9tz74DP@ODuXVVoDKM6fdmrdD9g@1KgI2kuoyu@BTQ@ci/vvJ/v6Wu3879ze10rwuzCw0XA4ioizTSJqoesFGTGkP3UDV0FeccFbe/rN033m1ls3n/eL8M2Bqmr3@ndBMhNha9UiPbb2sC6@1duDbP/xD27uH/9m6lvXvYwN6demoRFqcCFpwKgLWdHFdicwVnieui71dtDusjceVnv99SO99h1@ivl8j3bLNth93AG2OvjiwenQtq4ZHcFdIrpgH0QRx0nkfevDXgAzqjQ637kYfW2p2OJaF1tzPnPbn51Az6Gv3Pm9uky2koJMe1lz5paB2zVD6jARS5CljrcvlhvcekrhIvm0sfpcVy1ohdWlDSSS2UE8kqr/k5Owr30f9QUtasSo9W51ea8g0tm63KxKwkG/4Qe65uk7Dat2k1C4LBqZ5Iolpp8YCAiTqjIZqJJKDs5D78UEcSpFyl4jATqnKJrHjGUSl5WDjEqHwuRKMy6f6VVdFdqbli5/EM@zJJDnJ9rS3UvvPDTUxF4x6m2qp4qdtjxXamd87Ud9mFP51Vd0b2ftO6ZJJ5Vc0ZgicLvcvoLY@ilr3qVI81jf8GhfFz1@qDJf@WzNWjEYFe4dbqu2SKG0IP11S8Tnub2iSwTKyKjJGhsUmICvFa0LElSYEKOdYwVXUoTZFyeJrHr4lVw@5Jgno61viqwzanVD/Bst6YM9fsg75GDTLfPfVVzezuslVdVX1211QyxKUTAfrAyjfahBt3bZVsRlvX1s5jbZ/WKN@gAxQqFOxGfc1GoSkgXfu8hkISZJu9D6tQbuxjsO1hYQNaXS/cubimPvcWi/ieWvdxMUDt@0seYwe9CvMxqHjqcD7tnmn/GqH8yu1YYXsTVcvOgWebbtr6BhWfzojKNmCAHYMoBkwAthVxPLlJbWagw6zmYNi@ZZuV8RsPcGs7x21E6q1Fb5SXGGnbhfSnEMcG@rhN68y1Dvvn@25pt@Pu0t5xhRxy65bsfjXKupHAnnb1@X0d9qPmiu35iiQtRkM9WthXk5IYqu1bdIRt6uSHhClmj7a1YoCbu/8M16JpDy/e7ClJlhos7h15tUxsjKAZqo4M@agd0MWDz7LgY88@Sc0P3SDxeHZG6sIBs2atlEu@9y9dVsstMyp4ZnsOo14Qaxa6TXJmVI/IZGnbqAW9NmSsc90GNUe9mX3AX76oTvfjz/vH8G9///Pxcfadvu5/Vrf3P6uvcF@98Jmu7h//Bw)
---
**Input:** String representing an array. The string must be made up of 3 characters: `0`, `|` representing row breaks, and any positive digit greater than one (PDGTO). I like to use `8`. OP allows input in any reasonable format and I believe this qualifies. The string does not *have* to format to a rectangular array but it will be assumed to be left-aligned whatever it is.
**Output:** Array of values showing the minimum taxi cab distance from each `PDGTO` to its nearest other `PDGTO`.
**Example:**
```
OP's Input: OP's Output:
------------- -------------
0 0 0 0 0 0 1 0 0 0 0 0 0 2
0 1 0 1 0 0 0 0 1 0 2 0 0 0
1 1 0 0 0 0 1 1 1 0 0 0 0 2
0 0 1 0 0 0 0 0 0 2 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 0 3 0
0 1 0 0 0 0 0 0 2 0 0 0 0 0
1 0 0 0 0 0 0 2 0 0 0 0 0 0
0 0 0 1 0 0 1 0 0 0 3 0 0 3
Taxi Input: 0000008|0808000|8800008|0080000|0000080|0800000|8000000|0008008
Taxi Output: (golfed)
------------------------------------
0 0 0 0 0 0 2.000000
0 1.000000 0 2.000000 0 0 0
1.000000 1.000000 0 0 0 0 2.000000
0 0 2.000000 0 0 0 0
0 0 0 0 0 3.000000 0
0 2.000000 0 0 0 0 0
2.000000 0 0 0 0 0 0
0 0 0 3.000000 0 0 3.000000
Taxi Output: (ungolfed version)
------------------------------------
0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 2.000000
0.000000 1.000000 0.000000 2.000000 0.000000 0.000000 0.000000
1.000000 1.000000 0.000000 0.000000 0.000000 0.000000 2.000000
0.000000 0.000000 2.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 0.000000 3.000000 0.000000
0.000000 2.000000 0.000000 0.000000 0.000000 0.000000 0.000000
2.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 3.000000 0.000000 0.000000 3.000000
```
The second output format is clearly much easier to read but it also adds 7 bytes to the program and this *is* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), after all. It would have been possible to go back at the end and remove all the trailing zeroes instead of simply padding the `0` values but that would have added even more bytes and was deemed an unacceptable cost.
---
Here's the text of the un-golfed code with comments, better labels, and clearer output:
(It's the same as you get with the link above.)
```
[ Minimal Taxi Cab Distance ]
[ Inspired by: https://codegolf.stackexchange.com/q/138311 ]
[ INPUT: String of 8 & 0 using a pipe | as a delineator for each row of the array ]
[ OUTPUT: String formatted as an array showing min taxi distance from each 8 to the nearest other 8 ]
[ Note: Any single digit > 1 may be substituted for 8. I.E., it must be 2 <= i <= 9 ]
[ PROCESS: ]
[ Store STDIN exactly as input and keep it around until the end ]
[ Store 3 arrays: Input, X Positions, Y Positions ]
[ Store a count of how many elements are in Input ]
[ For each element in Input, create an array of minimal taxi cab distances ]
[ Find the minimum value greater than zero in that array and store it ]
[ Pad with a space and, if it's the last element in the row, a line break ]
[ Repeat for each element, storing the minimums each time ]
[ Concatenate all the results and output ]
[ DATA LOCATION REASON ]
[ Input Auctioneer School Close to Cyclone ]
[ Input w/o Delineator Tom's Trims Running out of options ]
[ Elements in Input Rounders Pub Close to Joyless Park ]
[ Iteration Joyless Park Close to The Underground ]
[ X Positions Trunkers Close to Rob's Rest ]
[ Y Positions Sunny Skies Park Close to Bird's Bench ]
[ Element's X Rob's Rest Easy to remember ]
[ Element's Y Bird's Bench Easy to remember ]
[ Array of distances Narrow Path Park LIFO is OK for this ]
[ Array of minimums Heisenberg's Close to KonKat's ]
[ Note: We use the Input w/o Delineator to keep track of iteration ]
[ By storing it at Chop Suey, we can keep going until we run out of passengers ]
[ Note: When using arrays other than the Input w/o Delineator, is it critical ]
[ that we clone each element and enque it again. The iteration tracking will ]
[ let us stop before we go through the array again. ]
[ Some things I learned about Taxi in TIO while writing this: ]
[ - You can store any passenger at Writer's Depot and Starchild Numerology ]
[ - You can store any passenger at Heisenberg's and even pick them up again *in order* ]
[ (You don't start picking up random integers until that queue is gone) ]
[ - If you try to drop someone at Rob's Rest or Bird's Bench but it's already occupied, ]
[ it won't error out. The passenger just stays in the Taxi which will probably cause ]
[ a "Too Many Passengers" error eventually. It cost me a week figuring that one out. ]
[ Pickup stdin and split it into elements ]
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: south 1st right 1st left 2nd right.
Pickup a passenger going to Auctioneer School.
Pickup a passenger going to Chop Suey.
Go to Auctioneer School: north 1st right.
1 is waiting at Starchild Numerology.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: south 1st left.
Pickup a passenger going to Rob's Rest.
Pickup a passenger going to Bird's Bench.
Go to Rob's Rest: west 1st right 2nd left 1st right.
Go to Bird's Bench: south.
Go to Chop Suey: north 1st right 1st left 2nd right 1st right 3rd right.
[ Create the arrays of X & Y positions ]
[NextInputElement]
Switch to plan "XYCreated" if no one is waiting.
Pickup a passenger going to Crime Lab.
'|' is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 3rd left.
Pickup a passenger going to Crime Lab.
Go to Zoom Zoom: north.
Go to Crime Lab: west 1st left 2nd right.
Switch to plan "NextColumn" if no one is waiting.
[ Next Row ]
[ Set X = 1 and Y = Y + 1 ]
Pickup a passenger going to Firemouth Grill.
Go to Rob's Rest: south 1st right 1st left 1st left 1st right 1st right.
Pickup a passenger going to Firemouth Grill.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: south 1st left 1st right 2nd left.
Pickup a passenger going to Cyclone.
Go to Cyclone: west 1st right 4th left.
Pickup a passenger going to Rob's Rest.
Go to Rob's Rest: north 1st right 2nd right 1st right.
Go to Bird's Bench: south.
Pickup a passenger going to Addition Alley.
Go to Firemouth Grill: north 1st right 1st left 1st right 1st left 1st right.
Go to Cyclone: west 1st left 1st right 2nd right.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: north 2nd right 1st right.
Pickup a passenger going to Bird's Bench.
Go to Bird's Bench: north 1st left 1st left 1st left 2nd right 1st left.
Switch to plan "EndOfElement".
[NextColumn]
[ Set X = X + 1, Store X & Y positions ]
Go to Rob's Rest: south 1st right 1st left 1st left 1st right 1st right.
Pickup a passenger going to Cyclone.
Go to Bird's Bench: south.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st right 1st left 2nd left.
Pickup a passenger going to Trunkers.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Sunny Skies Park.
Go to Trunkers: south 1st left.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 1st left 2nd left.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: west 1st right 3rd right 1st right 1st right.
Pickup a passenger going to Rob's Rest.
Go to Cyclone: north 1st left 1st left.
Pickup a passenger going to Bird's Bench.
Go to Sunny Skies Park: north 1st right.
Go to Rob's Rest: south 2nd right 1st right.
Go to Bird's Bench: south.
[EndOfElement]
Go to Chop Suey: north 1st right 1st left 2nd right 1st right 3rd right.
Switch to plan "NextInputElement".
[XYCreated]
[ Clean up the leftovers ]
Go to Rob's Rest: north 1st left 3rd left 1st left 2nd right 1st right.
Pickup a passenger going to Firemouth Grill.
Go to Bird's Bench: south.
Pickup a passenger going to Firemouth Grill.
Go to Firemouth Grill: north 1st right 1st left 1st right 1st left 1st right.
[ Create the Input w/o Delineator string ]
Go to Auctioneer School: west 1st left 1st right 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 4th left.
Pickup a passenger going to Auctioneer School.
Pickup a passenger going to Chop Suey.
Go to Auctioneer School: north 1st right.
0 is waiting at Starchild Numerology.
Go to Starchild Numerology: south 1st left.
Pickup a passenger going to Addition Alley.
Go to Chop Suey: west 1st right 3rd right 1st right 3rd right.
[NextInputWithoutDelineatorElement]
Switch to plan "DelineatorRemoved" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Zoom Zoom: north 1st left 3rd right.
Go to Cyclone: west.
Pickup a passenger going to Crime Lab.
'|' is waiting at Writer's Depot.
Go to Writer's Depot: south.
Pickup a passenger going to Crime Lab.
Go to Zoom Zoom: north.
Go to Crime Lab: west 1st left 2nd right.
Switch to plan "NotAPipe" if no one is waiting.
Pickup a passenger going to Firemouth Grill.
Go to Cyclone: north 4th left 2nd left.
Pickup a passenger going to Firemouth Grill.
Go to Firemouth Grill: south 1st left 2nd left 1st right.
Go to Chop Suey: east 1st left 4th right 1st left.
Switch to plan "NextInputWithoutDelineatorElement".
[NotAPipe]
Go to Cyclone: north 4th left 2nd left.
Pickup a passenger going to Joyless Park.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: south 2nd left 2nd right.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: west 1st right 3rd right 1st right 1st right.
Pickup a passenger going to Addition Alley.
Go to Joyless Park: north 1st right 1st right 2nd left.
Go to Chop Suey: west 1st right 1st right 1st left.
Switch to plan "NextInputWithoutDelineatorElement".
[DelineatorRemoved]
Go to Addition Alley: north 1st left 2nd left.
Pickup a passenger going to Rounders Pub.
Go to Rounders Pub: north 1st right 1st right 2nd right 1st left.
Go to Joyless Park: north 1st right.
Pickup a passenger going to KonKat's.
[NextBit]
Switch to plan "EndOfBits" if no one is waiting.
Pickup a passenger going to KonKat's.
Go to Zoom Zoom: west 1st right 2nd left 2nd right.
Go to KonKat's: west 1st left 2nd right.
Pickup a passenger going to KonKat's.
Go to Joyless Park: south 2nd left.
Switch to plan "NextBit".
[EndOfBits]
Go to KonKat's: west 1st right.
Pickup a passenger going to Tom's Trims.
Go to Tom's Trims: south 3rd right 1st left.
[ Start with the first character ]
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: south 1st right 1st left 1st left 2nd left.
Pickup a passenger going to Joyless Park.
Go to Joyless Park: west 1st right 2nd right 1st right 2nd left 4th right.
[ At this point, we have the following data structure: ]
[ Input Auctioneer School ]
[ Input w/o Delineator (IwoD) Tom's Trims ]
[ Elements in Input Rounders Pub ]
[ Iteration = 1 Joyless Park ]
[ X Positions Trunkers ]
[ Y Positions Sunny Skies Park ]
[ ]
[ Now, we use Joyless Park to track our starting point ]
[ and IwoD to iterate through all the destinations. If ]
[ the starting point's value is <=1, then add '0 ' to ]
[ Heisenberg's and go to the next element. If value ]
[ is >1, then calculate the distance to every other ]
[ element. IwoD will start full and be emptied as we ]
[ iterate through all the possible destinations. Once ]
[ that's done, cycle back through those results until ]
[ we find the smallest value >0 and add that to ]
[ Heisenberg's. Either way, in order to move to ]
[ the next starting point, we add 1 to Joyless Park, ]
[ check that it's less than Rounders Pub, and loop. If ]
[ it's not less, then we're done so we can go build ]
[ the output with the passengers at Heisenberg's. ]
[ We'll use the Auctioneer School to find pipes so we ]
[ can add line breaks to the output as needed. ]
[NextElementForStartingPoint]
[ Extract this element's value ]
Pickup a passenger going to Cyclone.
Go to Cyclone: west 1st right 2nd left 2nd left.
Pickup a passenger going to Joyless Park.
Pickup a passenger going to The Underground.
Go to Joyless Park: north 2nd right 2nd right 2nd left.
Go to Tom's Trims: west 1st left 1st right 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: south 1st right 1st left 2nd right.
Pickup a passenger going to Tom's Trims.
Pickup a passenger going to Chop Suey.
Go to Tom's Trims: south 1st left 2nd right 1st left.
Go to Chop Suey: north 1st right 1st left 4th right 1st left.
Go to The Underground: south 1st right 1st left.
[GetTheNextElement]
Switch to plan "FoundThisElement" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Chop Suey: north 2nd right 1st left.
Pickup a passenger going to Firemouth Grill.
Go to Zoom Zoom: north 1st left 3rd right.
Go to Firemouth Grill: west 3rd left 2nd left 1st right.
Go to The Underground: east 1st left.
Switch to plan "GetTheNextElement".
[FoundThisElement]
Go to Chop Suey: north 2nd right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st right 1st left.
Go to Chop Suey: north 6th right 1st left.
[TrashNextElement]
Switch to plan "ElementsAllTrashed" if no one is waiting.
Pickup a passenger going to Firemouth Grill.
Switch to plan "AllRiders" if no one is waiting.
Pickup a passenger going to Firemouth Grill.
Switch to plan "AllRiders" if no one is waiting.
Pickup a passenger going to Firemouth Grill.
[AllRiders]
Go to Zoom Zoom: north 1st left 3rd right.
Go to Firemouth Grill: west 3rd left 2nd left 1st right.
Go to Chop Suey: east 1st left 4th right 1st left.
Switch to plan "TrashNextElement".
[ElementsAllTrashed]
Go to The Babelfishery: south 1st right 1st left.
Pickup a passenger going to The Underground.
Go to The Underground: north.
Switch to plan "ItsAZero" if no one is waiting.
Pickup a passenger going to Firemouth Grill.
Go to Firemouth Grill: south 1st right.
Go to Joyless Park: east 1st left 3rd right.
Switch to plan "ExtractXY".
[ItsAZero]
' 0.000000' is waiting at Writer's Depot.
Go to Writer's Depot: south 2nd right 1st left 2nd left.
Pickup a passenger going to Heisenberg's.
Go to Heisenberg's: north 3rd right 3rd right.
Go to Joyless Park: south 1st right 1st left 1st left.
Switch to plan "GotoNextStartingPoint".
[ Extract the X & Y values for this element ]
[ExtractXY]
Pickup a passenger going to Cyclone.
Go to Cyclone: west 1st right 2nd left 2nd left.
Pickup a passenger going to Joyless Park.
Pickup a passenger going to The Underground.
Go to Joyless Park: north 2nd right 2nd right 2nd left.
Go to Trunkers: west 1st left 2nd right 1st left.
[GetNextXY]
Pickup a passenger going to Cyclone.
Go to Sunny Skies Park: west 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left.
Pickup a passenger going to Trunkers.
Pickup a passenger going to Rob's Rest.
Go to Trunkers: south 1st left.
Go to Rob's Rest: west 1st left 1st right 1st right.
Go to Cyclone: south 1st left 1st left 2nd left.
Pickup a passenger going to Sunny Skies Park.
Pickup a passenger going to Bird's Bench.
Go to Zoom Zoom: north.
Go to Sunny Skies Park: west 2nd left.
Go to Bird's Bench: south 2nd right 1st left.
Go to The Underground: north 1st right 1st left 1st right 1st right 2nd left.
Switch to plan "FoundXY" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Rob's Rest: south 2nd right 1st left 1st left 1st right 1st right.
Pickup a passenger going to Firemouth Grill.
Go to Bird's Bench: south.
Pickup a passenger going to Firemouth Grill.
Go to Firemouth Grill: north 1st right 1st left 1st right 1st left 1st right.
Go to Trunkers: west 1st left 1st right.
Switch to plan "GetNextXY".
[FoundXY]
[ Keep rotating the arrays until they're back to normal ]
Go to Rounders Pub: north 1st left 1st left.
Pickup a passenger going to Cyclone.
Go to Joyless Park: north 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: west 1st right 2nd left 2nd left.
Pickup a passenger going to Rounders Pub.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to Joyless Park.
Go to Rounders Pub: north 2nd right 2nd right 2nd right 1st left.
Go to Joyless Park: north 1st right.
Go to Cyclone: west 1st right 2nd left 2nd left.
Pickup a passenger going to What's The Difference.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: south 2nd left 2nd right.
Pickup a passenger going to Addition Alley.
Go to What's The Difference: west 1st right 3rd right 1st left.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: east 2nd right.
Pickup a passenger going to The Underground.
Go to The Underground: north 1st right 1st right.
[RotateXY]
Switch to plan "XYareRotated" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Trunkers: south 2nd right 1st left.
Pickup a passenger going to Trunkers.
Go to Sunny Skies Park: west 1st right.
Pickup a passenger going to Sunny Skies Park.
Go to Zoom Zoom: north 1st right.
Go to The Underground: west 1st left 2nd right.
Switch to plan "RotateXY".
[XYareRotated]
[ At this point, we have the following data structure: ]
[ Input Auctioneer School ]
[ Input w/o Delineator (IwoD) Tom's Trims ]
[ Elements in Input Rounders Pub ]
[ Iteration Joyless Park ]
[ X Positions Trunkers ]
[ Y Positions Sunny Skies Park ]
[ Element's X Rob's Rest ]
[ Element's Y Bird's Bench ]
[ Now we need to compute the distance to each point greater than one ]
[ IwoD will start full and be emptied as we iterate through all the ]
[ possible destinations. Once that's done, cycle back through those ]
[ results until we find the smallest value >0 and add that to the ]
[ result at Heisenberg's. ]
[ Finish the RotateXY process by dropping off the passengers ]
[ They have been carried around to raise money for gas ]
Go to Trunkers: south 2nd right 1st left.
Go to Sunny Skies Park: west 1st right.
[ Split IwoD into pieces ]
Go to Tom's Trims: south 1st left 1st right 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: south 1st right 1st left 2nd right.
Pickup a passenger going to Tom's Trims.
Pickup a passenger going to Chop Suey.
Go to Tom's Trims: south 1st left 2nd right 1st left.
Go to Chop Suey: north 1st right 1st left 4th right 1st left.
[NextDestination]
Switch to plan "EndOfDestinations" if no one is waiting.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st right 1st left.
Pickup a passenger going to The Underground.
Go to The Underground: north.
Switch to plan "DestinationIsZero" if no one is waiting.
Pickup a passenger going to Firemouth Grill.
Go to Firemouth Grill: south 1st right.
[ Calculate the X distance ]
Go to Trunkers: west 1st left 1st right.
Pickup a passenger going to Cyclone.
Go to Rob's Rest: west 1st left 1st right 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: south 1st left 1st left 2nd left.
Pickup a passenger going to Trunkers.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to Rob's Rest.
Go to Trunkers: south 1st left.
Go to Rob's Rest: west 1st left 1st right 1st right.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: south 1st left 1st right 2nd left.
Pickup a passenger going to Addition Alley.
Go to Cyclone: west 1st right 4th left.
Pickup a passenger going to What's The Difference.
Go to Zoom Zoom: north.
Go to What's The Difference: west 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: east 1st right.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Multiplication Station.
Go to Addition Alley: north 2nd right 1st right.
Pickup a passenger going to The Underground.
Go to The Underground: north 1st right 1st right.
Switch to plan "XDiffIsNegative" if no one is waiting.
Pickup a passenger going to Firemouth Grill.
Go to Firemouth Grill: south 1st right.
-1 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 1st left 1st right 1st left 2nd left.
Pickup a passenger going to Multiplication Station.
Go to The Underground: west 1st right 2nd right 1st right 2nd left.
[XDiffIsNegative]
Go to Multiplication Station: south 1st left 1st right.
[ Calculate the Y distance ]
Go to Sunny Skies Park: south 1st right 2nd left 1st right.
Pickup a passenger going to Cyclone.
Go to Bird's Bench: south 2nd right 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st right 1st left 2nd left.
Pickup a passenger going to Sunny Skies Park.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to Bird's Bench.
Go to Sunny Skies Park: north 1st right.
Go to Bird's Bench: south 2nd right 1st left.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: north 1st right 1st right 2nd left.
Pickup a passenger going to Addition Alley.
Go to Cyclone: west 1st right 4th left.
Pickup a passenger going to What's The Difference.
Go to What's The Difference: north 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: east 1st right.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Multiplication Station.
Go to Addition Alley: north 2nd right 1st right.
Pickup a passenger going to The Underground.
Go to The Underground: north 1st right 1st right.
Switch to plan "YDiffIsNegative" if no one is waiting.
Pickup a passenger going to Firemouth Grill.
Go to Firemouth Grill: south 1st right.
-1 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 1st left 1st right 1st left 2nd left.
Pickup a passenger going to Multiplication Station.
Go to The Underground: west 1st right 2nd right 1st right 2nd left.
[YDiffIsNegative]
Go to Multiplication Station: south 1st left 1st right.
[ Add the two negative distances and multiply by -1 ]
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Addition Alley.
-1 is waiting at Starchild Numerology.
Go to Starchild Numerology: south 1st right 2nd left 1st left 2nd left.
Pickup a passenger going to Multiplication Station.
Go to Addition Alley: west 1st right 3rd right 1st right 1st right.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: north 1st right 1st right 3rd left 1st right.
[ Do not record the distance if it's zero ]
[ i.e., if start and destination are the same ]
Pickup a passenger going to Addition Alley.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: south 1st right 2nd left 1st left 2nd left.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: west 1st right 3rd right 1st right 1st right.
Pickup a passenger going to The Underground.
Go to The Underground: north 1st right 1st right.
Switch to plan "IgnoreZeroDistance" if no one is waiting.
Pickup a passenger going to Narrow Path Park.
[IgnoreZeroDistance]
Go to Narrow Path Park: north 4th left.
Go to Chop Suey: east 1st right 1st left 1st right.
Switch to plan "NextDestination".
[DestinationIsZero]
[ Rotate X & Y and keep going ]
Go to Trunkers: south 2nd right 1st left.
Pickup a passenger going to Trunkers.
Go to Sunny Skies Park: west 1st right.
Pickup a passenger going to Sunny Skies Park.
Go to Zoom Zoom: north 1st right.
Go to Trunkers: west 3rd left.
Go to Sunny Skies Park: west 1st right.
Go to Chop Suey: north 1st right 1st right 3rd right.
Switch to plan "NextDestination".
[EndOfDestinations]
[ Clean up the leftovers ]
Go to Rob's Rest: north 1st left 3rd left 1st left 2nd right 1st right.
Pickup a passenger going to Firemouth Grill.
Go to Bird's Bench: south.
Pickup a passenger going to Firemouth Grill.
Go to Firemouth Grill: north 1st right 1st left 1st right 1st left 1st right.
[ Run through all the passengers are Narrow Path Park ]
[ None of them should be 0 because we dropped those ]
[ Find the smallest value and store it at Heisenberg's ]
Go to Narrow Path Park: east 1st left 4th left.
Pickup a passenger going to Writer's Depot.
[CheckNextDistance]
Switch to plan "FoundMinDistance" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Zoom Zoom: west 1st left 1st right 1st right.
Go to Writer's Depot: west.
Pickup a passenger going to Magic Eight.
Go to Cyclone: north.
Pickup a passenger going to Magic Eight.
Go to Magic Eight: south 1st left 2nd right.
Switch to plan "SecondIsLess" if no one is waiting.
[ Keep the first passenger b/c it's less and dump the second ]
Pickup a passenger going to Writer's Depot.
Go to Cyclone: north 1st left 2nd right.
Pickup a passenger going to Firemouth Grill.
Go to Firemouth Grill: south 1st left 2nd left 1st right.
Go to Narrow Path Park: east 1st left 4th left.
Switch to plan "CheckNextDistance".
[SecondIsLess]
[ Go pickup the second passenger's clone b/c it's less or equal ]
Go to Cyclone: north 1st left 2nd right.
Pickup a passenger going to Writer's Depot.
Go to Narrow Path Park: north 2nd right 1st left 1st right.
Switch to plan "CheckNextDistance".
[FoundMinDistance]
[ Store the results ]
Go to Writer's Depot: west 1st left 1st right 2nd left.
Pickup a passenger going to The Babelfishery.
' ' is waiting at Writer's Depot.
Pickup a passenger going to KonKat's.
Go to The Babelfishery: north 1st right 2nd right 1st right.
Pickup a passenger going to KonKat's.
Go to KonKat's: north.
Pickup a passenger going to Heisenberg's.
Go to Heisenberg's: north 1st right 1st right.
Go to Joyless Park: south 1st right 1st left 1st left.
[GotoNextStartingPoint]
[ Start at Joyless Park ]
Pickup a passenger going to Magic Eight.
Go to Rounders Pub: west 2nd left.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st right 1st left 2nd left 2nd left.
Pickup a passenger going to Rounders Pub.
Pickup a passenger going to Magic Eight.
Go to Rounders Pub: north 2nd right 2nd right 2nd right 1st left.
Go to Magic Eight: north 1st right 1st right 2nd right.
Switch to plan "GoDoOutput" if no one is waiting.
[ We're not done yet so start over ]
Pickup a passenger going to Addition Alley.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 1st left 1st left 2nd left.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: west 1st right 3rd right 1st right 1st right.
Pickup a passenger going to Joyless Park.
Go to Joyless Park: north 1st right 1st right 2nd left.
Switch to plan "NextElementForStartingPoint".
[ At this point, we have the following data structure: ]
[ (The queues not listed here aren't needed any more) ]
[ Input Auctioneer School ]
[ Array of minimums Heisenberg's ]
[GoDoOutput]
[ Split the original input at Chop Suey ]
Go to Auctioneer School: west 1st left 1st left.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: north 3rd right 1st right 3rd right.
[OutputNextResult]
Switch to plan "PrintOutput" if no one is waiting.
Pickup a passenger going to Crime Lab.
'|' is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 3rd left.
Pickup a passenger going to Crime Lab.
Go to Zoom Zoom: north.
Go to Crime Lab: west 1st left 2nd right.
Switch to plan "OutputThisResult" if no one is waiting.
[ Output line breaks where every pipe was in the input ]
Pickup a passenger going to Firemouth Grill.
Go to Firemouth Grill: north 1st left.
'\n' is waiting at Writer's Depot.
Go to Writer's Depot: west 1st left 1st right 2nd left.
Pickup a passenger going to KonKat's.
Go to KonKat's: north 3rd right 2nd right.
Switch to plan "GoToNextOutput".
[OutputThisResult]
[ Output the actual result, which will include space padding ]
Go to Heisenberg's: north 5th right 1st left.
Pickup a passenger going to KonKat's.
Go to KonKat's: north 1st left 1st left.
[GoToNextOutput]
Pickup a passenger going to KonKat's.
Go to Chop Suey: north 1st right 1st right.
Switch to plan "OutputNextResult".
[PrintOutput]
Go to KonKat's: north 1st left 1st left.
Pickup a passenger going to Post Office.
Go to Post Office: south 3rd right 1st left.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~23~~ 22 bytes
```
tt0*&v&fht1&ZPtg/X<yf(
```
[Try it online!](https://tio.run/##y00syfn/v6TEQEutTC0to8RQLSqgJF0/wqYyTeP//2gDBRA0VDCwBhEQaA1jIERRFcQCAA) Or [verify all test cases](https://tio.run/##y00syfmf8L@kxEBLrUwtLaPEUC0qoCRdP8KmMk3jv7qurnqES8j/aAMFAwVDawUQZYBEGcJ5sVxgNTBoCJUFY7BiQxgTYRJcwBpZJ9xkhCwSB6EYImgItBhktCHEBhgFFjXABq2xC49gCUNo3GEGmCFqfGHVDI9@UKgDAA).
### Explanation
To see intermediate results, it may be helpful to insert `X#` (display stack) between any two statments.
```
t % Implicit input: matrix. Duplicate
t0* % Duplicate and multiply by 0. Gives a matrix of zeros
&v % Concatenate vertically to input matrix. This is needed
% in case the input is a row vector, because in that case the
% subsequent &f would give row vectors, not column vectors
&f % Push two column vectors with the row and column indices of
% nonzero elements
h % Concatenate into a 2-column matrix. Each row gives the
% coordinates of a nonzero entry in the input matrix
t % Duplicate
1&ZP % Taxicab distance between the two copies of the 2-column
% matrix containing the coordinates. The diagonal contains
% zeros (distance of each point to itself)
tg % Duplicate, convert to logical (turn nonzeros into 1)
/ % Divide, element-wise. This leaves off-diagonal entries in
% the distance matrix unchanged, and sets the diagonal to NaN
X< % Minimum of each column. NaN values are ignored. The
% resulting vector contains the new values to be written in
% the input matrix
y % Duplicate from below: push input matrix again
f % Linear indices of nonzero entries
( % Assignment indexing: write specified values at specified
% positions. Implicitly display
```
[Answer]
# [Python 3](https://docs.python.org/3/) + [numpy](http://numpy.org), 102 bytes
```
def f(M):
x,y=where(M)
for i,j in zip(x,y):d=abs(x-i)+abs(y-j);M[i,j]=min(d[d>0])
from numpy import*
```
[Try it online!](https://tio.run/##7VNbboUgEP12VjHxC1ptIP2zsTtwBdYPGzWXG0WCNr128xaEerF1Cc0kMo8zxwlzUMt8GeXzujZthx0paAZ4S5b889Lq1oSA3ahRJFcUEr@EIqZIsyav3ydySwV9tM6SXulLURpUlQ9CkqZsXllFodPjgPJjUAuKQY16flgt22S5SojjGBha48iAo/OZz7E9d6yarmRv5RC0gIOewH6MOwjynZ8fagxPpvCkd2QwTYD0s95/bMn54RuU2JkB@88f7/CwknAhwcpOKX6LxS9h86sMICryWut6IWUvppkMtSJCzgn2QrZPk@rFTCilm/Ztygp28vn4Tca05FnKKyNxiDaRK6VNv1e5jyByp31FkfOM07nwT2X9Bg "Python 3 – Try It Online")
Takes input as a `numpy` array.
---
# [Python 3](https://docs.python.org/3/), 127 bytes
```
lambda M,e=enumerate:[[v*min(abs(x-i)+abs(y-j)for x,r in e(M)for y,a in e(r)if(x!=i or y!=j)*a)for j,v in e(r)]for i,r in e(M)]
```
[Try it online!](https://tio.run/##7VNdboMwDH5uTuHylLAwJdqekDgCJ6A8pGpQU5GAQtbB6RkBys@EdoLJErE/f/6wYqfu3L0yH32RXPpS6OtNQEplIs2XllY4GWfZM9TKYHFtcBsp8uadLnqQorLQUgvKgMTpGHZUTKElqsDtOVHg0XPyIKEYGQ/6fDFyH6tVIO890PgwQ0EQIAbeODDEYfLZjLEF22eHKrqUcrQpQRP1gPYyPlGAL/p8l2Nw0MUsujI33WyYc6/rj7043303KXZkiP3j@zvcjWQ7kM3IDiV@L8s8hNHPY4ROaZKVqnFYixor4yiUysj3pi6Vw4QQ8HvqIb@qzYwHFxOQjMcRz/NBorCVhrq2QzkoXVfWzRE6TSdOKXyrm7snpTQ4zVhOwk8yZMckWWjF8DL@ZPY/ "Python 3 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 197 bytes
```
@a=map{[/\d/g]}<>;for$r(0..$#a){for$c(0..$#{$a[$r]}){$d=@a*@{$a[0]}*$a[$r][$c];for$y(0..$#a){$a[$r][$c]=$d=$a[$y][$_]&&($t=abs($y-$r)+abs($_-$c))&&$t<$d?$t:$d for 0..$#{$a[$y]}}}}$,=$";say@$_ for@a
```
[Try it online!](https://tio.run/##ZY1BDoIwEEX3nqLRH0JRsCzYCNVewBNgQyqoMVEhhU1DuLqVQqILZzb/zZ8/01z0I7FWKP5UTZ9vT9X2Jodsn15rDe2zKMJK0d5ROVMPlUPLgfaouFCBcAMmh2Ce5yjlFDbf8M/gY8SRGamQnuej4@rc@jAhNF1PsghRUup56DJUB3Q7VGS8R37PjRzGwoZjmbbKCBRuQShrGXEdE7aIyazZgn1V/O@@66a716/WhsckYjH7AA "Perl 5 – Try It Online")
[Answer]
## JavaScript (ES6), 97 bytes
Takes input in currying syntax `(w)(a)`, where ***w*** is the width of the matrix and ***a*** is a flat array of zeros and ones. Returns another flat array.
```
w=>a=>a.map((c,i)=>c*Math.min(...a.map((d,j)=>d&&A((j/w|0)-(i/w|0))+A(j%w-i%w)||1/0)),A=Math.abs)
```
### Test cases
This snippet includes a helper function to format the output for readability.
```
let f =
w=>a=>a.map((c,i)=>c*Math.min(...a.map((d,j)=>d&&A((j/w|0)-(i/w|0))+A(j%w-i%w)||1/0)),A=Math.abs)
format = (a, w) => `${a}`.match(RegExp(`(\\d+,?){${w}}`, 'g')).join('\n')
console.log(
format(f(3)([
0, 0, 1,
0, 0, 0,
0, 0, 0,
0, 1, 0,
0, 0, 0
]),
3)
)
console.log(
format(f(7)([
0, 0, 0, 0, 0, 0, 1,
0, 1, 0, 1, 0, 0, 0,
1, 1, 0, 0, 0, 0, 1,
0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0,
0, 1, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 1
]),
7)
)
console.log(
format(f(3)([
1, 1, 1,
1, 1, 1,
1, 1, 1
]),
3)
)
console.log(
format(f(12)([
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
]),
12)
)
console.log(
format(f(16)([
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0
]),
16)
)
console.log(
format(f(2)([
1, 1
]),
2)
)
```
[Answer]
# Octave, 59 bytes
```
for f=find(a=input(''))'a(f)=0;a(f)=bwdist(a,'ci')(f);end;a
```
Takes the input as a 2D array.
[Try it online!](https://tio.run/##y08uSSxL/f8/Lb9IIc02LTMvRSPRNjOvoLREQ11dU1M9USNN09bAGkwlladkFpdoJOqoJ2eqawJFrFPzUqwT//@PNlAAQUMFA2tDBQjbwNoAzjLElI0FAA "Octave – Try It Online")
Explanation:
For each location of 1s found in the array set it to zero and calculate city block distance transform of the array and finally set the location to the calculated distance.
[Answer]
# [Python 3](https://docs.python.org/3/) with [Numpy](http://www.numpy.org/), ~~106~~ 101 bytes
*5 bytes off thanks to [@notjagan](https://codegolf.stackexchange.com/users/63641/notjagan)*
```
from numpy import*
def f(x):i,j=where(x);d=abs(i-i[None].T)+abs(j-j[None].T);x[i,j]=nanmin(d/(d>0),0)
```
Function that inputs a Numpy array and outputs by modifying that array (which is [allowed by default](https://codegolf.meta.stackexchange.com/a/4942/36398)).
[Try it online!](https://tio.run/##ZU/LDsIgELzzFRxBW4V4s8FP8OSt4VADpDThEayxfH1tE1spTTab2dnd2Vkf@9bZyziq4Ay0b@Mj1Ma70B@AkAoqNOCrLjr2aWWQU1EJ1jxfSJe6vjsr@emBjzPRld1KVEM9rXBmG2u0ReKMxI3gguAxQgabEJqI6poUcArKC/iDZA9pxnIMFIoY@KBtPwOwV0yDJjpLXuRpSuReNp3EwTq69ZhP052TrQj9n8xfGr8 "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes
```
T€,€"JẎ
ZJpJạþÇḅ1Zḟ€0Ṃ€ṁZZ×
```
[Try it online!](https://tio.run/##y0rNyan8/z/kUdMaHSBW8nq4q48ryqsASC88vO9w@8MdrYZRD3fMB8oZPNzZBKQe7myMijo8/f///9HRBjoKEGQIJGN1uBSiDWEiBjARAwwRQ5J1xQIA "Jelly – Try It Online")
] |
[Question]
[
You are a young programming geek living with your 2 other best friends. Every week, one of you has to do all the chores of the house and you decide whose turn it is by picking a stick. The one who picks the shortest stick loses and does all the chores.
As all of you are programmers and love creating puzzles, you have modified the "Pick the shortest stick" into a computer puzzle.
**Here are the rules of the puzzle.**
1. You will be given a 2D matrix, where each column represents a stick.
2. In each column, 1 represents a portion of the stick and 0 is an empty space
3. When going from top to bottom in each column, initially you have `0`'s and as soon as you hit a `1`, the stick has started and rest of the column will be filled with `1` only
4. You can write your program to pick one column. The size of the stick in that column determines the winner/loser. Size of stick == number of 1s in that column.
5. However, that program can only have a linear worst-case time complexity.
As all of you are programmers, you will know if someone else's program is shooting the time complexity limit.
**Your job is to:**
* Write a program or function that accepts input in either a 2D format or array of strings.
* Input can be taken from STDIN/prompt/console or a function argument.
* If you are reading the input from STDIN/prompt then you can assume that the reading of input and converting it to an array takes 0 time (even though the code to do so has to be there in your answer)
* Determine the column with the longest stick in it.
* Output can be the function's return value or to STDOUT/console/alert.
* The program/function must have linear worst-case time complexity, `O(m+n)` where `m` is the number of rows and `n` the number of columns.
**Input can be either one of the following formats:**
2D array:
```
[ [0, 0, 0, 0],
[1, 0, 0, 0],
[1, 1, 0, 1],
[1, 1, 1, 1] ]
```
Array of Strings:
```
[ "0000", "1000", "1101", "1111" ]
```
**The input will have following properties:**
* Size of the array is unknown, assume a rectangle of any size
* In any column, coming top down, if you see a 1, then everything below will be a one
* Empty-columns (i.e. 0-length) sticks *are* allowed.
**This is a code-golf so shortest code wins**!\*
Please explain your code, or give the ungolfed version (to verify time complexity) along with which of the two input formats you expect.
**UPDATE**
Linear time complexity here means O(n+m) where n is column size and m is row size. (For those who were unclear)
**UPDATE 2** This definitely **can** be done in linear time. And if you are posting an answer, feel free to delay posting the logic/algorithm by a couple of days for a fair fight :)
**UPDATE 3** I'll go over all answers in couple of hours to validate time complexity and the program :)
[Answer]
## Ruby, ~~83~~ ~~75~~ ~~68~~ ~~66~~ 63 bytes
```
f=->m{m[b=c=i=0].map{(c=i;b-=1)while(r=m[b-2])&&r[i]>0;i+=1};c}
```
Defines a function `f` which takes the 2D array form as input.
>
> I'm starting at the bottom left, keeping track of maximum stick length (actually, minus that) and the corresponding column. In each column, if there are still `1`s above the previous maximum stick length, I walk up the stick to the end and remember the new maximum length and column. That means that I'm iterating once along the columns and at most once along the rows (specifically I'm iterating as far as the maximum stick length), which is precisely `O(m+n)`.
>
>
>
[Answer]
# GolfScript, 45 chars
```
:^,:y;0:x{^y(=x=2%y*{y(:y;x\}{x):x}if^0=,<}do
```
Takes input as an array of strings, returns (0-based) index of tallest column.
It runs in O(*rows* + *columns*) iterations, and each iteration should take essentially constant time (at least assuming constant-time arithmetic). The only array/string operations done within the loop are element lookups (`=`) and taking the length of a string (`,`), both of which take constant time in GolfScript.
[Try it online.](http://golfscript.apphb.com/?c=IyBUZXN0IGlucHV0czoKWwogIFsgIjAwMDAiICIxMDAwIiAiMTEwMSIgIjExMTEiIF0gICMgYW5zd2VyOiAwCiAgWyAiMDAwMCIgIjAxMDAiICIxMTAxIiAiMTExMSIgXSAgIyBhbnN3ZXI6IDEKICBbICIwMTAwIiAiMTEwMSIgIjExMTEiIF0gICAgICAgICAjIGFuc3dlcjogMQogIFsgIjAxMDAiIF0gICAgICAgICAgICAgICAgICAgICAgICMgYW5zd2VyOiAxCiAgWyAiMDEwMCIgIjExMDEiICIxMTAxIiAiMTExMSIgXSAgIyBhbnN3ZXI6IDEKICBbICIwMDAwIiAiMDAwMSIgIjExMDEiICIxMTExIiBdICAjIGFuc3dlcjogMwpdCgojIFJ1biBwcm9ncmFtIGNvZGUgZm9yIGVhY2ggaW5wdXQsIGNvbGxlY3Qgb3V0cHV0cyBpbiBhcnJheToKewogIDpeLDp5OzA6eHteeSg9eD0yJXkqe3koOnk7eFx9e3gpOnh9aWZeMD0sPH1kbwp9JXA%3D)
### Explanation:
Like most of the solutions here, this code works by starting at the lower left corner of the matrix, walking up or right depending on whether the current element of the matrix is 1 or 0, and keeping track of the column where it last moved up.
At the beginning of the program, I assign the input array to the variable `^`, its length (i.e. the number of rows) to `y`, and 0 to `x`. The value 0 is also left on the stack; during the following loop, it will be replaced by the index of the tallest column.
Within the main loop, `^y(=x=` extracts the `x`-th character of the `y-1`-th row in `^`. This actually returns the ASCII code of the character, so `2%` is needed to drop all but the last bit. As a special case, if `y` equals 0 (which can happen if the tallest column found so far reaches all the way to the top row), the bit looked up will actually come from the *last* row in the matrix (index -1), but the following `y*` forces it to zero, thus effectively creating a virtual all-zeros row at the top of the matrix.
The following `if` will then execute one of the two code blocks preceding it, depending on whether the looked-up bit is non-zero (true) or zero (false). If non-zero, `y` is decremented by one, and the current value of `x` replaces the tallest column index on the stack (with the old value temporarily left on top of it). If zero, `x` is simply incremented by one (and temporarily left on the stack, on top of the tallest column index).
Finally, `^0=` extracts the first row of the matrix, `,` returns its length, and `<` compares it with the column index temporarily left on the stack (which will equal `x` if it was just incremented) If the index is less that the length of the row, the loop repeats.
**Ps.** Based on my testing, it should be possible to shorten this program by one character by replacing the string length test `,<` at the end of the loop with `>`, which cuts the string at the given index and returns the end portion (which will be empty, and thus false, at the end of the loop). However, while cutting a string like that *appears* to be implemented as a constant-time operation in GolfScript (or, rather, in Ruby, which GolfScript runs on top of), I have not found any official documentation saying so. Just to be safe, I've chosen to feature the slightly longer, but definitely O(1), version above.
[Answer]
# Python 2 - ~~71, 69, 73, 75~~ 81
```
j=i=-1
M=input()
for m in M[0]:
j+=1
while-i<len(M)and M[i][j]:i-=1;J=j
print J
```
[Answer]
# C, 64 bytes
Edit: I learned that the question asks for the location of the longest column and not its length.
The first line is the golfed code and the rest is the sample invocation.
```
g(int m,int n,int**a,int*r){for(*r=n;n*m;a[m][n]?m--,*r=n:--n);}
/* usage:
m = number of rows
n = number of columns
a = 1-based 2D array such that a[i][j] gives the value at the ith row and jth column
r = address of return value
Returns (to r) the 1-indexed location of a column with the longest length, or 0 if n=0
*/
int main()
{
int flat[4*4] = {1, 0, 0, 0,
1, 0, 0, 1,
1, 1, 0, 1,
1, 1, 1, 1};
int*twoD[4] = {flat-1,flat+3,flat+7,flat+11};
int ret;
g(4,4,twoD-1,&ret);
printf("%d", ret);
return 0;
}
// old function which determines longest length (65 bytes)
f(int m,int n,int**a,int*r){for(*r=m;n*m;a[m][n]?m--:--n);*r-=m;}
```
[Answer]
**C#: 236 Chars**
```
int p(int[,] a){int y=0,s=0,i=0,x;for(;++y<=a.GetUpperBound(0);)for(x=i;x<=a.GetUpperBound(1);){if(a[y,x++]==0)break;s=y;i++;}return s;}
```
ungolfed:
```
int p(int[,] a)
{
int selectedRow=0;
int maxLength=0;
for(var y = 0; y<=a.GetUpperBound(0); y++)
for(var x=maxLength; x<=a.GetUpperBound(1); x++)
{
if(a[y,x++]==0)
break;
selectedRow=y;
maxLength++;
}
return selectedRow;
}
```
[Answer]
### PHP 5.4 - 108 bytes
(113 if you include the `<?php`)
Input format: Array will be read as a JSON string.
```
php longest_stick.php "[[0, 0, 0, 0],[1, 0, 0, 0],[1, 1, 0, 1],[1, 1, 1, 1]]"
```
Whitespace added for readability - all newlines and leading spaces can be removed.
```
<?php
$t=count($s=json_decode($argv[1]))-1;
foreach($s[0] as $k=>$_)
while($s[$t][$k]) {
$t--;
$l = $k;
}
echo $l?:0;
```
Minified version:
```
<?php $t=count($s=json_decode($argv[1]))-1;foreach($s[0] as $k=>$_)while($s[$t][$k]){$t--;$l=$k;}echo $l?:0;
```
Kind of stealing the algorithm from Martin here, but it's nice to play around with languages that aren't seen as often here XD
[Answer]
# Cobra - 98
```
def f(a)
s,x,y=0,0,a.count-1
while y+1and x<a[0].count
while a[y][x],y,s=y-1,x
x+=1
print s
```
[Answer]
**C++ :: 78**
Unlike the other C solution, this is the whole program. (no invocation needed, no need to tell the function the size of the array). Unfortunately this means it is longer as `main` must be used instead of a single character function name, I have to interpret the input and then output the answer, where the other solution handles that "elsewhere".
Also my first code golf.
compiled with `g++ file.cpp -include iostream`, run with `./a 000 010 110 111` (for example) == array of strings (I believe this is allowed in the question spec)
```
int c;main(int r,char**v){for(r--;r*v[r][c];v[r][c]-48?std::cout<<c,r--:++c);}
```
The above version outputs the current best found so far on each iteration. The final output digit is the answer. Switching from processing from bottom left instead of bottom right and `0` indexing reduced this solution by 10(!) characters.
switching to c++ drops submission by one more character as `std::cout<<` is shorter than `putchar(-48)` and it should also explicitly support more than 9 sticks with proper output (though it may get harder to differentiate each output)
Removing the answer field and outputting it direcly cut another 6 characters. It now only outputs the current best when it moves up which cuts out some output at least.
Entire file is now only 78 bytes in size - approaching the function only solution that the other `C` submission uses. (with lots of extra code to support said function).
As below description is out of date:
>
> `c` is global so is initialised with `0`
>
> `r` is the number of inputs (rows) +1 (name of program)
>
> `v` is the array of strings with `v[0]` being invalid (name of program)
>
> As it is 0 indexed, `r` is out of bounds, so decrement.
>
> While `r!=0` (pointing at valid string) and character `c` in the string is not the null terminator `'\0'`
>
> if character is not '0'
>
> go up a row (`r`) and output the column (`c`)
>
> else go to next column (`c`)
>
>
>
> done
>
>
>
Can I even golf this further?
Ungolfed code (with extra output):
>
>
> ```
> #include `<`stdio.h`>`
> #include `<string.h`>
>
> int main(int argc, char* argv[])
> {
> int rows = argc-1;
> int cols = strlen(argv[1]);
> int ans;
>
> printf("rows: %d, cols: %d\n",rows, cols);
>
> while((rows)&&cols)
> {
> if (argv[rows][cols-1]-'0')
> {
> printf("stick @%d,%d\n",cols,rows);
> ans = cols;
> rows--;
> }
> else
> {
> printf("no stick @%d,%d\n",cols,rows);
> cols--;
> }
> }
> printf("%d",ans);
> }
> ```
>
>
> It uses the length of the strings to find out the number of columns and argc to find the number of rows. Starting in the bottom right corner, it follows these simple rules:
> If cell is a stick, then move up, set answer to current column.
> If cell is not a stick, then move to the left.
> O(n+m): as it only moves up and left, it can only have max n+m reads. It exits early if it falls off the top or left of the array.
>
>
>
[Answer]
# OCaml - 144 characters
```
let s a=Array.(let rec f i j m=if i=0then m else if a.(i).(j)=0then if j=length a.(i)-1then m else f i(j+1)m else f(i-1)j j in f(length a-1)0 0)
```
Takes an `int array array` as input, and starts from below left, moving up or right if it sees a `1` or a `0`. Column count starts at `0`.
## Usage
```
s [| [| 0; 0; 0; 0 |]; [| 0; 0; 1; 0|]; [| 1; 0; 1; 0 |]; [| 1; 1; 1; 0 |]; [| 1; 1; 1; 1 |] |];;
- : int = 2
```
## Ungolfed
```
let s a = Array.(
let rec f i j m = (* m is the longest stick seen so far *)
if i=0 then m (* A column is full: this is the longest possible stick and j=m anyway *)
else if a.(i).(j)=0 then (* current column is shorter than a previously seen stick *)
if j=length a.(i)-1 then m (* we have examined all columns, just return m *)
else f i(j+1) m (* start examining next column *)
else f (i-1) j j (* current column is longer than all the ones previously seen. Check how long the stick is *)
in
f (length a-1) 0 0)
```
[Answer]
## T-SQL - ~~71~~ 64
Takes table A as input
```
SELECT IDENTITY(INT, 1, 1) R, A INTO A
FROM (VALUES
('0000')
,('1000')
,('1101')
,('1111')
) AS A(A)
```
And the query is
```
SELECT TOP(1)CHARINDEX('1',A)FROM A WHERE A LIKE'%1%' ORDER BY R
```
[SQLFiddle](http://sqlfiddle.com/#!3/2f50d/3)
This returns the first row from the table a ordered by r where there is a 1 in string a.
`TOP(1)` restricts the result to the first row returned.
`CHARINDEX('1',A)` returns the position of the first 1 in the string or zero if it isn't found.
`WHERE A LIKE'%1%'` filters to rows where A contains a 1
`ORDER BY R` ensures the table is read from top down
[Answer]
# Delphi 122 chars
Sigh...it is such a voluminous language.
Update: had to add 6 characters in changing function the return type from I to integer. The function still compiled as the test program had a "type I=integer;" statement left over from an earlier version of the program.
```
function S(A:array of string):integer;var n,c:integer;begin n:=0; repeat c:=Pos('1',A[n]);inc(n) until c>0; result:=c;end;
```
[Answer]
# scheme - 236 chars
Even longer than the delphi version...there is probably a way to do this much more efficiently with scheme. And even worse - I just noticed it is order m\*n.
```
(define (s l) (cond ((eq? (cdr l) '()) (car l)) (else (map + (car l) (s (cdr l)))))) (define (u l) (define (t n p q l) (cond ((eq? l '()) p) ((< n (car l)) (t (car l) q (+ 1 q) (cdr l))) (else (t n p (+ 1 q) (cdr l))))) (t 0 0 1 (s l)))
```
l is a list of the form '((0 0 0 0) (1 0 0 0) (1 1 0 1) (1 1 1 1)). I think that is a fair representation of a 2D array input for scheme.
(s l) sums the n-th elements of each of the sub-lists of a list of lists of nuimbers, so (s '((0 0 0 0) (1 0 0 0) (1 1 0 1) (1 1 1 1))) would return (3 2 1 2).
(u l) returns the 'index' of the largest entry of a list of numbers (using the helper function t), so (u '(3 2 1 2)) will return 1 (as the largest element '3 in the list '(3 2 1 2) is at position 1).
[Answer]
# Racket 70
Golfed:
```
(define(h m)(for/last([r m]#:final(memv 1 r))(length(takef r even?))))
```
Assumes input is a two-dimensional array, which in Racket would be a list of lists:
```
(define m
'((0 0 0 0)
(1 0 0 0)
(1 1 0 1)
(1 1 1 1)))
```
Ungolfed:
```
(define (h m)
;; step through rows, stopping at the first that contains a 1
(for/last ([r m] #:final (memv 1 r))
(length (takef r even?)))) ; pop off the leading zeroes to get the column index
```
Returns the column index with the longest stick.
[Answer]
# JavaScript, ES6, 76 characters
```
W=a=>(j=>{for(k=i=a.length-1;~i&~j;)a[i][j]?(k=j,i--):j--})(a[0].length-1)|k
```
Takes array of array input.
[Answer]
# JavaScript ES6, 65 bytes
Takes both input formats
```
f=(a,t)=>a.reduceRight((p,c)=>t+1?t:(x=c.indexOf(1,p))+1?x:t=p,0)
```
**Explained:**
Iterates from bottom to top. Uses [`String.prototype.indexOf()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) or [`Array.prototype.indexOf()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) depending on the input on each value. Finds the first index of each row with a 1 from the previous offset, if it finds none then it sets the `t` variable to the last offset and doesn't perform anymore `indexOf` calls.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 9 years ago.
[Improve this question](/posts/5836/edit)
Write a program in the language of your choosing which when read are the lyrics to a song. It *must* be a valid program which can be compiled and run without errors. While you could technically print to the screen all the lyrics, you're encouraged to do it with style and avoiding string literals whenever possible.
Given that this is difficult on of itself, you're allowed to write a single section of boilerplate code which doesn't count towards being readable in the lyrics. However, once the block of code begins which must be read as the lyrics to a song, you cannot interrupt it until the song is finished. You can indicate the beginning and end of the song code with comments. Please also specify the lyrics themselves as you would read the code. You can be "liberal" with your interpretation so long as you don't stray too far from what's written, otherwise it will cost you points.
Partial song lyrics are allowed, though you get double points for having the words to an entire song. Judging is divided into 3 categories:
1. 10 points - Originality
2. 10 points - Song difficulty
3. 20 points - Representation of that song in code.
For each submission, I'll give you your score in a comment below. If you edit your answer, just give me a comment indicator and I'll re-evaluate it accordingly. However in order to be fair, each re-evaluation subtracts 2 points from your total score.
An example might be the following:
```
public class Song {
public String play() {
// Song begin
try {
if(this instanceof TheRealLife || this instanceof JustFantasy) {
throw new InALandSlide();
}
} catch (InALandSlide e) {
}
return "No \"FromReality\"";
// Song end
}
public static void main(String [] args) {
Song song = new Song();
song.play();
}
}
```
Which gets read:
```
Is this TheRealLife?
Or is this JustFantasy?
Caught InALandSlide.
No escape \"FromReality\"
```
Instrumentals aren't allowed, wise guys. ;)
[Answer]
## Python - 8+4+15 = 27 points
Here's on couple of stanzas from The [Hunting of the Snark](http://www.gutenberg.org/files/13/13-h/13-h.htm) by Lewis Carroll.
It calculates a number, based on the algorithm suggested in the poem, and uses it to state a proof about the voice of the jubjub.
```
class taking:
def __init__(self, n): convenient.val = (n)
def __enter__(self): pass
def __exit__(self, type, value, traceback): pass
def a(x,y): x.val = y(x.val); return True
class We:
def __init__(self): self.val=0
def __add(self, y): return y+sum(self.x)
def add(self, *x): self.x = x; return self.__add
def multiply(self,x,by,diminished_by): self.val *= by-diminished_by
def proceed2divide(self,x,by): self.val /= by
def subtract(self,x): self.val -= x; return True
perfectly = lambda x: x and not not x
def must_be(x):
if x:
print "\n".join(["Tis the %s of the Jubjub!"%["voice","note","song"][x%3] for x in range(out.val)])
return out.val
out=convenient=as_you_see=we=then=the=We()
_ = exactly = 15
with\
\
taking(3) as the_subject_to_reason_about:
a(convenient, #2 state
we.add(7,_ & 10)) and then.multiply(out,
by=1000, diminished_by=8)
the_result = we.proceed2divide(as_you_see,
by=992)
then.subtract(17) and the; answer = must_be(
exactly and perfectly(True))
```
The original text:
>
> "Taking Three as the subject to reason about—
>
> A convenient number to state—
>
> We add Seven, and Ten, and then multiply out
>
> By One Thousand diminished by Eight.
>
>
>
> "The result we proceed to divide, as you see,
>
> By Nine Hundred and Ninety Two:
>
> Then subtract Seventeen, and the answer must be
>
> Exactly and perfectly true.
>
>
>
>
[Answer]
## Python (8+7+15=30)
Valid Python code synctactically although it does not do anything particulary useful ;-)
```
from sys import exit as stops ; import os
thing = [] ; me = can = remember = False ; this = open(__file__)
def terrible(v): return v
# ==== start song snippet
me = can = remember = not any(thing)
can = not this.tell(), [True, "dream"]
locals()["deep"] = {"down":{"inside":{"feel_to":"scream"}}}
if `this` + (terrible("silence")): stops(me)
# ===== end song snippet
```
How it is supposed to be read:
>
> I can't remember anything.
>
> Can't tell if this is true or dream.
>
> Deep down inside I feel to scream.
>
> This terrible silence stops me.
> ...
>
> *(Metallica - One)*
>
>
>
[Answer]
## C
Somewhat sloppy, I wrote this in about 15 minutes for giggles. Compiles and runs fine with latest version of G++/MinGW (doesn't really do much, though). You can figure this out just fine by yourself, I think:
```
class Rick {
public:
struct us { bool you; bool me; };
bool giveYouUp() { return false; }
bool letYouDown() { return false; }
bool runAround() { return false; }
bool desertYou() { return false; }
bool makeYouCry() { return false; }
bool sayGoodbye() { return false; }
bool tellALie() { return false; }
bool hurtYou() { return false; }
bool thinkingOf(bool whatImThinkingOf) { return whatImThinkingOf; }
bool justWantTo(bool whatIWantToDo) { return whatIWantToDo; }
bool tellYou(bool whatIWantToTellYou) { return whatIWantToTellYou; }
void roll() {
bool gonna = false;
while (gonna) {
giveYouUp();
letYouDown();
gonna = (runAround() && desertYou());
makeYouCry();
sayGoodbye();
gonna = (tellALie() && hurtYou());
}
bool strangersToLove = true;
us we = {!strangersToLove, !strangersToLove};
bool knowTheRules = true;
bool you = knowTheRules, I = knowTheRules;
bool aFullCommitment = true;
we.me = thinkingOf(aFullCommitment);
int me = 0;
Rick* guys[] = {this, nullptr, nullptr, nullptr, nullptr};
bool howImFeeling = true;
we.me = justWantTo(tellYou(howImFeeling));
bool understand = true;
while (we.you != understand) {
we.you = understand;
}
}
};
int main() {
Rick rick;
rick.roll();
return 0;
}
```
[Answer]
### Scala(48 = 2\*(7+4+13))
[It's Linux!](http://www.poppyfields.net/filks/00323.html) song.
```
object Song extends App {
// Compose a song
trait Compose {
override def toString = {
val token = """^.*\$(.*)\$.*$""".r
val token(verse) = super.toString
verse.replaceAll("([a-z])([A-Z])", "$1 $2").capitalize
}
def excl(ex: String) = println(this + ex)
def !!(c: Compose) = { excl("."); c }
def ***(c: Compose) = { excl("..."); c }
def !(c: Compose) = { excl("!"); c }
def *(c: Compose) = { excl(","); c }
def ! = excl("!")
}
// It's linux - lyrics
case object ItBootsUpFine extends Compose
case object AllOfTheTime extends Compose
case object TuxThePenguinIsGreat extends Compose
case object aPieInTheFace extends Compose
case object ToTheManIHate extends Compose
case object EveryoneKnowsItsLinux extends Compose
case object StableForYouAndMe extends Compose
case object ItsLinux extends Compose
case object NoMoreBSODs extends Compose
case object BetterThanNT extends Compose
case object BestOfAllItsFree extends Compose
case object FreeSoftwareForYouAndMe extends Compose
case object LinuxGPLd extends Compose
// Singer to sing a song
def sing(song: => Unit) = { song }
// Song begins
sing {
ItBootsUpFine!
AllOfTheTime!!
TuxThePenguinIsGreat!
aPieInTheFace*
ToTheManIHate***
EveryoneKnowsItsLinux!
ItsLinux!
ItsLinux!
StableForYouAndMe!
ItsLinux!
ItsLinux!
NoMoreBSODs!
ItsLinux!
ItsLinux!
BetterThanNT!
ItsLinux!
ItsLinux!
BestOfAllItsFree!
FreeSoftwareForYouAndMe***
LinuxGPLd!
}
// Song ends
}
```
### Output:
```
It Boots Up Fine!
All Of The Time.
A Pie In The Face,
Tux The Penguin Is Great!
To The Man IHate...
Everyone Knows Its Linux!
Its Linux!
Its Linux!
Stable For You And Me!
Its Linux!
Its Linux!
No More BSODs!
Its Linux!
Its Linux!
Better Than NT!
Its Linux!
Its Linux!
Best Of All Its Free!
Free Software For You And Me...
Linux GPLd!
```
[Answer]
# PHP
Tried my favorite song, Stairway to Heaven.
```
$GLOBALS['sign']= 'words';
class lady extends me // there is a lady
{
function __construct(){ // who is sure
global $glitters = 'gold'; // all that glitters is gold
$buy('stairway_to_heaven'); // and shes buying the stairway to heaven
}
$know[] = 'stars are close'; // when she get's there she knows, the stars are close
function word(){ // with a word she can get
debug_backtrace(); // what she come for
}
$this->buy('stairway_to_heaven'); // and she's buying the stairway to heaven
$sign = 'words'; // there is a sign on the door
if(!$sign === $GLOBALS['sign']) // but she want to be sure, cause you know sometimes words have 2 meanings
exit();
in_array($tree / $brook, $songbird ? 'sings'); // (literal) in a tree by the brook, there is a songbird who sings
mysql_real_escape_string($_GET['thoughts']); // sometimes all of our thoughts are misgiven
for ($i=0;$i<2;i++)
parent::wonder(); // makes me wonder , makes me wonder
}
```
How is it read :
>
> There's a lady who's sure all that glitters is gold
> And she's
> buying a stairway to heaven.
> When she gets there she knows, if
> the stars are all close
> With a word she can get what she came
> for.
> Ooh, ooh, and she's buying a stairway to heaven.
>
>
> There's a sign on the wall but she wants to be sure
> 'Cause you
> know sometimes words have two meanings.
> In a tree by the brook,
> there's a songbird who sings,
> Sometimes all of our thoughts are
> misgiven.
> Ooh, it makes me wonder,
> Ooh, it makes me wonder.
>
>
>
>
>
>
[Answer]
## C
Here's a complete song.
You can listen to it in [Mama Lisa's World](http://www.mamalisa.com/?t=es&p=1485&c=23).
Note that the song is included as-is, including the punctuation.
```
#define breath,
#define smell breath
#define an;}Englishman; main(){printf("%d\n",sizeof
struct x{int
// Song starts here
Fee, fa, fie, fo, fum,
I smell the breath of an Englishman.
// Song ends here
I);}
```
Prints the number 4.
[Answer]
# Ruby
My take at as close representation as possible. It's easy with Ruby's call chaining.
```
$lines = []
def thisline n=2
caller(n).first.match(/:(\d+):/)[1].to_i
end
class Chain < Array
def method_missing method, *args
$lines[thisline] = Chain[first, self[1], [method, thisline, args]]
end
def -(arg)
$lines[thisline] = Chain[' - ', thisline, self, arg]
end
def tokens
if size < 3
if first == :_
[]
else
[first.to_s.tr(?_, ?\s).strip]
end
elsif size < 4
[first.to_s.tr(?_, ?\s)] + at(2).tokens
else
lhs = case el = at(2)
when Chain then el.tokens
when String
el.empty? ? [?'] : [?', el, ?']
end
rhs = case el = at(3)
when Chain then el.tokens
when Range then el.first.tokens + ['... '] + el.last.tokens
end
lhs + [first.to_s.tr(?_, ?\s)] + rhs
end
end
end
def self.method_missing method, *args
line = thisline(3)
if args.length > 1
newlines = args.first.is_a?(String) ? args.first.count(?\n) : 0
$lines[line] = false
$lines[line-newlines] = Chain[method, line, Chain[', ', line, *args]]
else
$lines[line] = Chain[method, line, *args]
end
end
####################
The pest in_the eyes of death follows us
Through the dirty streets of blood
It begins to eat inside us, decaying_our_bones
How will we escape_if the void covers our lungs?
We are buried_in the spewed trash_for ourselves
Blood _, pain - nothing_to_say
Why then_- must_we_die?
Escape to the void
Escape to the void
I look at my face on the other side of the mirror
My face falls down_in pieces full of worms
I burst my rotten heart with my own hands
I'm dying and I can',t_help_myself
Blood _, pain - nothing_to_say
Why then_- must_we_die?
What have I been running from?
I'',m_not_guilty
You've shown me the worst way
Cause you',re_my_victim... the_next_one
The pest in_the eyes of death follows us
Through the dirty streets of blood
It begins to eat inside us, decaying_our_bones
How will we escape if_the void covers our lungs?
We are buried in_the spewed trash_for ourselves
Blood _, pain - nothing_to_say
Why then_ - must_we_die?
Escape to the void
Escape to the void
####################
$lines.drop_while {|line| !line }.each_with_index {|line, i|
puts if line.nil?
next if not line
line = line.tokens
line.map!.with_index {|el, j|
punct = [', ', ' - ', '... ', ?']
if line[j-1] == ?' and el == ', '
''
elsif punct.include?(el) or punct.include?(line[j+1])
el
else
el + ?\s
end
}
puts line.join
}
```
## Output
```
The pest in the eyes of death follows us
Through the dirty streets of blood
It begins to eat inside us, decaying our bones
How will we escape if the void covers our lungs?
We are buried in the spewed trash for ourselves
Blood, pain - nothing to say
Why then - must we die?
Escape to the void
Escape to the void
I look at my face on the other side of the mirror
My face falls down in pieces full of worms
I burst my rotten heart with my own hands
I'm dying and I can't help myself
Blood, pain - nothing to say
Why then - must we die?
What have I been running from?
I'm not guilty
You've shown me the worst way
Cause you're my victim... the next one
The pest in the eyes of death follows us
Through the dirty streets of blood
It begins to eat inside us, decaying our bones
How will we escape if the void covers our lungs?
We are buried in the spewed trash for ourselves
Blood, pain - nothing to say
Why then - must we die?
Escape to the void
Escape to the void
```
## To do
1. Multiline commas (arguments)
2. Multiline dots (method calls)
[Answer]
**T-SQL Bone Thugs-N-Harmony**
```
DECLARE @line1 varchar(25);
DECLARE @line2 varchar(25);
DECLARE @line4 varchar(25);
DECLARE @line5 varchar(25);
SET @line1 = 'Wake up, wake up, wake up,';
SET @line2 = 'its the';
SET @line4 = 'to get up, get up get up';
SET @line5 = 'so cash your checks and get up';
SELECT @line1 as Layzie, @line2 as Bizzy,
CONVERT(date,DATEADD(day, -
(SELECT
DATEPART(day, GETDATE())
- 1), GETDATE())) as FirstOfTheMonth,
@line4 as Layzie, @line5 as Bizzy;
```
Yeah I know I cheated a bit and I might have the members who sang which line wrong also.
[Answer]
**C - Bottles of Beer**
Compile and run this. Lyrics are put into the source code. Compile and execute output to get next line of song. When it says "Time to go...." then compile and execute with the number of bottles specified on the command line, e.g.:
```
cl prog.c
prog 32 > prog1.c
cl prog1.c
prog1 > .... etc
```
The code, tested using VS2005:-
```
// Time to go to the shop and get some beer
//
//
//
//
// #####.#####.#####.#####.#####.#####.#####
// ##.#####.#####.#####.#####.#####.#####.##
// #####.#####.#####.#####.#####.#####.#####
// ##.#####.#####.#####.#####.#####.#####.##
char *z [] = {
"void l(char *s,int b){int i;printf(\"// \");for(i=0;i<b;++i)printf(s);",
"printf(\"\\n\");}\nint main(int argc, char *argv[]){\nint i,j,k,x=%d;",
"char*p;\nif(!x&&argc==2)x=atoi(argv[1]);\nif(!x){printf(\"// Time to ",
"go to the shop and get some beer\\n//\\n//\\n//\\n//\\n\");k=7;\n",
"}else{printf(\"// %%d bottles of beer on the wall, %%d bottles of beer",
".\\n\",x,x);printf(\"// Take one down and pass it round, \");\n",
"if(x>1)printf(\"%%d bottles of beer on the wall.\\n//\\n\",x-1);\n",
"else printf(\"no more bottles of beer on the wall.\\n//\\n\");\n",
"k=x>2?x:2;l(\" ^ \",x);l(\" / \\\\ \",x);l(\"/ \\\\ \",x);",
"l(\"| | \",x);l(\"|Duf| \",x);l(\"| | \",x);l(\"----- \",x);}\n",
"for(i=0;i<4;++i){\nprintf(\"// %%s\", i&1 ? \"##.\" : \"\");\n",
"for(j=i&1;j<k;++j)\nprintf(\"%%s#####\",j!=(i&1)?\".\":\"\");\n",
"printf(\"%%s\\n\",i&1?\".##\":\"\");}\nprintf(\"\\nchar *z [] = {\\n\");\n",
"for(i=0;i<sizeof z/sizeof z[0];++i){\nprintf(\"\\\"\");\n",
"for(p=z[i];*p;++p)\nswitch (*p){\ncase '\\n':printf(\"\\\\n\");break;\n",
"case '\\\\':printf(\"%%c%%c\",92,92);break;\n",
"case '%%':printf(\"%%c\",37);break;\ncase '\"':printf(\"%%c%%c\",92,'\"');break;\n",
"default:printf(\"%%c\", *p);break;}\nprintf(\"\\\",\\n\");}\n",
"printf(\"};\\n\");\nfor(i=0;i<sizeof z/sizeof z[0];++i)\n",
"printf(z[i],x?x-1:0);}\n",
};
void l(char *s,int b){int i;printf("// ");for(i=0;i<b;++i)printf(s);printf("\n");}
int main(int argc, char *argv[]){
int i,j,k,x=0;char*p;
if(!x&&argc==2)x=atoi(argv[1]);
if(!x){printf("// Time to go to the shop and get some beer\n//\n//\n//\n//\n");k=7;
}else{printf("// %d bottles of beer on the wall, %d bottles of beer.\n",x,x);printf("// Take one down and pass it round, ");
if(x>1)printf("%d bottles of beer on the wall.\n//\n",x-1);
else printf("no more bottles of beer on the wall.\n//\n");
k=x>2?x:2;l(" ^ ",x);l(" / \\ ",x);l("/ \\ ",x);l("| | ",x);l("|Duf| ",x);l("| | ",x);l("----- ",x);}
for(i=0;i<4;++i){
printf("// %s", i&1 ? "##." : "");
for(j=i&1;j<k;++j)
printf("%s#####",j!=(i&1)?".":"");
printf("%s\n",i&1?".##":"");}
printf("\nchar *z [] = {\n");
for(i=0;i<sizeof z/sizeof z[0];++i){
printf("\"");
for(p=z[i];*p;++p)
switch (*p){
case '\n':printf("\\n");break;
case '\\':printf("%c%c",92,92);break;
case '%':printf("%c",37);break;
case '"':printf("%c%c",92,'"');break;
default:printf("%c", *p);break;}
printf("\",\n");}
printf("};\n");
for(i=0;i<sizeof z/sizeof z[0];++i)
printf(z[i],x?x-1:0);}
```
[Answer]
## Perl performs Barnes & Barnes
Ever since I first learned Perl, I've wanted an excuse to use the `-P` option. Today, that excuse has finally arrived:
```
#define cry $$
#define people $_
#define some kill
#define we people
#define whenyoudie END
sub yeah{}
# "When You Die", Barnes & Barnes
whenyoudie { you stop drinking beer }
whenyoudie { you stop being here }
whenyoudie { some people,cry }
whenyoudie { we=say "goodbye" }
yeah
```
Run it with `-M5.010` in addition to the `-P` option, like so:
```
$ perl -PM5.010 whenyoudie
goodbye
Hangup
$
```
] |
[Question]
[
A *run ascending list* is a list such that runs of consecutive equal elements are strictly increasing in length. For example `[1,1,2,2,1,1,1]` can be split into three runs `[[1,1],[2,2],[1,1,1]]` with lengths `[2,2,3]`, since two runs are the same length this is **not** a run ascending list. Similarly `[2,2,1,3,3,3]` is not run ascending since the second run (`[1]`) is shorter than the first (`[2,2]`). `[4,4,0,0,0,0,3,3,3,3,3]` is run ascending since the three runs strictly increase in length.
An interesting challenge is to figure out for a particular set of symbols whether they can be arranged into a run ascending list. Of course the values of the individual symbols don't matter. It just matters how many of each there are.
In this challenge you will be given a list of \$n\$ positive integers, \$x\_i\$, as input. Your task is to determine if a run ascending list can be made from the numbers \$1\$ to \$n\$ with each number \$k\$ appearing *exactly* \$x\_k\$ times.
For example if the input is `[4,4,7]` it means you must determine if a run ascending list can be made with four 1s, four 2s and seven 3s. The answer is yes:
```
[1, 3,3, 1,1,1, 2,2,2,2, 3,3,3,3,3]
```
If the input is `[9,9,1]` it means you must try to find a run ascending list made of nine 1s, nine 2s and one 3. This cannot be done. It must start with the single `3` since that run can only be 1 long. Then the 1s and 2s must alternate to the end, since each run must larger than the previous, there must be more of whichever number goes last.
## Rules
You should take as input a non-empty list of positive integers. You should output one of two distinct values. One if a run ascending list can be made the other if it cannot.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the goal is to minimize the size of your source code as measured in bytes.
## Testcases
Inputs that cannot make a run ascending list
```
[2,2]
[40,40]
[40,40,1]
[4,4,3]
[3,3,20]
[3,3,3,3]
```
Inputs that can make a run ascending list
```
[1]
[10]
[6,7]
[7,6]
[4,4,2]
[4,4,7]
[4,4,8]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 106 bytes
```
def f(a,n=-1,x=0):a[n]-=x;return~-any(a)^any(f(1*a,i,j+1)for i,k in enumerate(a)for j in range(x,k)if i-n)
```
[Try it online!](https://tio.run/##NY3BboMwDIbvfQofk81IhKAydeLYXnfZDTEp25w2pQ3IChtc9uosYezi79fn3/Iwh0vv9bJ8kgUrDPo6UzjVuTyYxrdZPT0zhZH9T2b8LIx8S7BCPRh0eH1U0vYMDjtwHsiPd2ITKPaSvibJxp9JTNhJZ8FlXi7fF3cjeOWRDjuAwHMCxO4ANdCXuYkYxyCkXP3Azof4MsrV0PRBQ4Djy@nI3PPf8TuT6ZamwKLdNWWOZf5PVClhiTpSo8Yi34JeVVqrpPZYxVnhfusXG6uNT@0v "Python 3 – Try It Online")
Brute force search. Recursively subtracts a strictly increasing value from every index in the input, as long as it is not equal to the prviously picked index. This continues until all values in the input are zero or the options to continue are exhausted.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
āsÅΓœεÅγü›P}à
```
Brute-force approach, so extremely slow.
[Try it online](https://tio.run/##yy9OTMpM/f//SGPx4dZzk49OPrcVSG8@vOdRw66A2sML/v@PNtIxigUA) or [verify some of the smaller test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/I43Fh1vPTT46@dxWIL358J5HDbsCag8v@K/zPzraSMcoVifaWMcYSBrqQHhAEsw3htAK0YYgQYgCsDCIbwJmm4AVGukYQjWYAOViAQ).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length]
s # Swap so the input-list is at the top
ÅΓ # Run-length decode using the two lists
œ # Get all permutations of this list
ε # Map over each permutation:
Åγ # Run-length encode the list, pushing the values and counts as two
# separated lists to the stack
ü›P # Check if this counts-list is strictly increasing:
ü # For each overlapping pair of the counts-list:
› # Check if the first is larger than the second
P # Product to check if all of them are truthy
# (or if the list is empty after the overlapping pairs builtin,
# which means the counts-list only contains a single value)
}à # After the map: max to check if any of them is truthy
# (which is output implicitly as result)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
{igᵗj₍}ᶠcpḅlᵐ<₁
```
[Try it online!](https://tio.run/##ATAAz/9icmFjaHlsb2cy//97aWfhtZdq4oKNfeG2oGNw4biFbOG1kDzigoH//1s0LDQsMl0 "Brachylog – Try It Online")
Times out on most of the test cases. I believe the algorithm is something like \$O(S!)\$, where \$S\$ is the sum of the input list.
### Explanation
```
{igᵗj₍}ᶠcpḅlᵐ<₁
{ }ᶠ Find all ways to satisfy this predicate:
i [E, I] pair where E is an element of the input and I is its index
gᵗ Turn that into [E, [I]]
j₍ Concatenate [I] to itself E times
Result: a list of lists like [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2]]
c Concatenate those lists into one big list
p Consider some permutation of that list
ḅ Break it into blocks (i.e. runs of the same value)
lᵐ Take the length of each block
<₁ Assert that the list of lengths is strictly increasing
```
[Answer]
# JavaScript (ES6), 84 bytes
Returns \$0\$ or \$1\$.
```
f=(a,i=0,p,g)=>a.some((v,j)=>v&&(g=_=>p!=j&v>i&&f(a,v,j,a[j]-=v)|g(a[j]+=v--))())|!g
```
[Try it online!](https://tio.run/##dY7LDoIwEEX3/gWb0sYp4RVwU5Z@gTskpkGoNEgJYBMT/h1r3GhsdzPnzONKrvlcT9240EFdm21rGebQsRBGEIQVPJjVvcFYgzSdRggLdmHF6DGJdNEh1JpxI4GXsqJMk1Xgd7lnmlJCMCGrJ7ZaDbPqm6BXAvvlkffzs/LJ7hu3uIwhrsgfTUNIQxeHyGYghcTCE0ggDh0i@az8KP88lKfpsdxsaW2fI9v1DHILzSFzRI8dPHfwg@HbCw "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = input array
i = 0, // i = previous run length
p, // p = previous index
g // g = variable used to store a local
// helper function and as a flag
) => //
a.some((v, j) => // for each value v at position j in a[]:
v && ( // abort if v = 0
g = _ => // g is a helper function which ignores its argument
p != j & // if the index is not equal to the previous one
v > i && // and v is greater than the previous run length:
f( // do a recursive call to f:
a, // pass a[]
v, // update i to v
j, // update p to j
a[j] -= v // subtract v from a[j]
) | // end of recursive call
g( // do a recursive call to g:
a[j] += v-- // restore a[j] and decrement v
) // end of recursive call
)() // initial call to g
) | // end of some()
!g // success if some() is truthy or g = 0,
// which means that a[] is now filled with 0's
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes
```
żZødṖƛĠvL2lvƒ>A;G
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLFvFrDuGThuZbGm8SgdkwybHbGkj5BO0ciLCIiLCJbMSwyXSJd)
Port of 05AB1E. ~~`vw` and `f` are only needed due to [a bug](https://github.com/Vyxal/Vyxal/issues/995), and `ƒ∴` is needed instead of `G` due to [another bug](https://github.com/Vyxal/Vyxal/issues/997).~~ Bugs fixed.
[Could be 13 bytes](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLFvMO44biK4bmWxpvDuMSWwqhwPkE7RyIsIiIsIlsxLDJdIl0=), but, well, this challenge is what inspired me to create all those new builtins, so, I guess it doesn't count.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 32 bytes
```
{+.bxj.*}wiFLr@{gw)-]qU_qsom&}ay
```
[Try it online!](https://tio.run/##SyotykktLixN/V@U@L9aWy@pIktPq7Y8082nyKE6vVxTN7YwNL6wOD9XrTax8v//aBMdEx2jWAA "Burlesque – Try It Online")
Drastically inefficient brute force
```
{ # Generate initial list, e.g. for [2,2] builds {1 1 2 2}
+. # Increment (indexed from zero)
bx # Box
j.* # Product
}wi # Zip with indices and map
FL # Flatten (strictly builds {{{1}{1}}{{2}{2}}})
r@ # All possible permutations (even repeated ones)
{
gw # Group like with length (count)
)-] # Get length (count)
qU_ # Quoted Unique
qso # Quoted sorted
m& # Make and (is sorted and unique)
}ay # Any
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes
```
⊞υ⟦±¹θ⁰⟧FυF…⊟ι⌈§ι¹FLθF∧⁻λ§ι⁰›§§ι¹λκ⊞υ⟦λE§ι¹⁻ν∧⁼ξλ⊕κ⊕κ⟧⬤υ⌈⊟ι
```
[Try it online!](https://tio.run/##ZY/NCsIwEITvPkWOG4hgQfDgqQcRQaV4LT2Edm2D6damifTtY2JV/AmEsGHmm52ykabspPY@c0MDTrD8iLW0CAkXrBdsUfD17NwZBo6zx3uSVCNk3RVUkBzkqFrXQmp3VOEISrCE86d0j1TbBvrXnFIFB0VuAC3Yh2PBA2lrMOSaN@mLKJgO9xLJ70V1TL/@6iY@BX4I2/RO6gHGyb6j0mCLZLGCiPr7il0zo8hCqnXMeLWb2oaz9j7Pl2IpVkXh5zd9Bw "Charcoal – Try It Online") Link is to verbose version of code. Outputs nothing if a run ascending list can be made, `-` if not. Explanation: Inspired by @Jitse's Python answer.
```
⊞υ⟦±¹θ⁰⟧Fυ
```
Start a search with a previous run of `0` `-1`s and the original input still to process.
```
F…⊟ι⌈§ι¹
```
Loop over potential next run lengths.
```
FLθ
```
Loop over potential next run values.
```
F∧⁻λ§ι⁰›§§ι¹λκ
```
If this is a new run and there are enough of the value remaining, then...
```
⊞υ⟦λE§ι¹⁻ν∧⁼ξλ⊕κ⊕κ⟧
```
... add a new search entry of the run and updated array of counts.
```
⬤υ⌈⊟ι
```
See whether an array of all zeros was achieved.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
¬ΛȯV≤mLgP`ṘN
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@hNedmn1gf9qhzSa5PekDCw50z/P4b6hjpGNqmJeYUpyqA2EZIbGPbkqJSCNMEzPz/PzoarCFWB0wbQWljKG0SGwsA "Husk – Try It Online")
Brute force approach, times out for even moderate inputs. TIO link includes a set of very short true & false inputs.
```
¬ΛȯV≤mLgP`ṘN
N # for each integer 1..N
`Ṙ # replicate it the number of times in the input array;
P # now get all permutations of this list
Λȯ # and output zero if none of these satisfy:
V # there is at least one pair of adjacent elemnts
≤ # for which the left is smaller or equal to the right,
mL # for the lengths of each
g # group of equal elements;
# (at this point truthy (nonzero) means a run-ascending list cannot be made,
# falsy (zero) means a run-ascending list can be made)
¬ # so NOT the result to get a consistent output
# 1=can be made, 0=cannot be made
```
(Omit the final `¬` for falsy & truthy-but-non-consistent output)
] |
[Question]
[
[Inspired](https://chat.stackexchange.com/transcript/message/60665979#60665979) by @AviFS.
Given a string containing brackets, e.g.
```
[xyz]]abc[[def]hij[
```
You can parse through it with a stack of brackets. When you find an open bracket, push a value to the stack, when you find a close bracket, pop from the stack. If you make these values indices, you know where you need to remove brackets.
If you try to pop from an empty stack, the close bracket is unmatched, and the brackets left on the stack at the end are unmatched.
For example, the above would be:
```
[ # PUSH index 1 - [1]
xyz] # POP - []
] # POP from empty stack, unmatched
abc[ # PUSH index 4 - [4]
[ # PUSH index 5 - [4, 5]
def] # POP - [4]
hij[ # PUSH index 7 - [4, 7]
```
After doing this, the 3rd bracket is unmatched as it pops from an empty stack, and the 4th and 7th brackets are unmatched as they were left on the stack.
Here's another way of viewing the matching:
```
**]**abc**[**
[ ] [ ]hij**[**
xyz def
```
Your challenge is to remove those unmatched brackets, leaving matched ones alone. For the above:
```
[ ]abc[ ]hij
xyz def
```
You may use any pair of brackets out of `()`, `[]`, `{}`, and `<>`, and the input will only contain those and lowercase letters.
## Testcases
```
[abc -> abc
[[] -> []
a[x[y]z[e]k[ -> ax[y]z[e]k
]ab[cdef]]gh[ij[klm]no]] -> ab[cdef]gh[ij[klm]no]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p`, ~~37~~ ~~29~~ 28 bytes
```
$_=$_.scan(/<\g<0>*>|\w/)*''
```
[Try it online!](https://tio.run/##KypNqvz/XyXeViVerzg5MU9D3yYm3cbATsuuJqZcX1NLXf3/f7vEJJvklNQ0O7v0DJvMLJvsnFy7vHw7u3/5BSWZ@XnF/3ULAA "Ruby – Try It Online")
Uses `<>` as brackets. Scans for, and prints:
* paired brackets and anything between them,
* letters outside brackets.
`\g<0>` embeds the regex within itself, allowing us to match nested bracket pairs recursively.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 94 91 89 78 bytes
```
f=s=>s==(t=s.replace(/<(\w*)>/,"0$11"))?s.replace(/[^a-z]/g,x=>['<>'[x]]):f(t)
```
[Try it online!](https://tio.run/##VY/bTsMwDIbv@xRRhZQY9cBuoQlXPIVrtCxLu26lqZoIyhDPXloKY1z5t38fPh/1q/ZmaPqQdm5vp6mSXiovpQjSZ4PtW22syAtRvt2CypP47maziQEer0x81umZ8joZpUJeKI4jEdxXIsDU2sCC0d56JtkW9c6wVLE5RIi0SKRI44jvdEZLJ/x2L2lEeodmbyui@oDNEU/tC3WOaF2yWv@cbRRdzq3ij7PEmZEXHK5KCzZXHH7HMt@3TRBx2cWQVW540uYg5r/YBzaJIzn@NPCFgMMDM67zrrVZ62pRiQaYlJI5@ITpCw "JavaScript (Node.js) – Try It Online")
*-2 thanks to ophact*
*-11 thanks to Arnauld: When returning an array in the `replace` callback function, `undefined` values will be deleted. Eg, `'abcde'.replace(/b/,x=>['<>'[x]])` returns `acde`*
~~Am curious to see how this can be improved...~~
We use `<>` for our bracket characters.
Approach:
* Replace valid instances of `<...>` with `0...1` until it stops changing.
* Remove remaining `<>` characters.
* Map `01` back to `<>`.
+ This part could probably be golfed better. It amounts to finding a JS golf for `tr`. Currently we use the match (`0` or `1`) to index into `<>`, which is shorter than doing two replaces.
[Answer]
# [Retina 1](https://github.com/m-ender/retina/wiki/The-Language), 35 bytes
```
|""L`<((<)|(?<-2>>)|\w)*(?(2)^)>|\w
```
[Try it online!](https://tio.run/##DcdLCsIwFAXQeZYREN4THDTjy@3QSZcgkjRG@zOFIlQle4@e2dnSa8yhqQc5@1qs7TxEoEVanByp5bLrUVpxelX@UytCHw1AE/DGh18kzjAMPeIt3cnHgHHCvDyZV/IH "Retina – Try It Online") Link includes test cases. Uses `<>` as brackets. Explanation: `|""L`` indicates that Retina should list the matches without a separator, the matches being any paired bracket string or letter.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
¬Ø[iⱮT,ƝịJƑ¥ƇƊFƲ¦ÐLe€Ø[oḟ1
```
A monadic Link that accepts a list of characters and yields a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8///QmsMzojMfbVwXonNs7sPd3V7HJh5aeqz9WJfbsU2Hlh2e4JP6qAmkJP/hjvmG////V4pNTIpOTklNi41Nz4jOzIrOzsmNzcuPjVVQSIyuiK6MrYpOjc2OVlCIjgYKRScmJSsBAA "Jelly – Try It Online")**
### How?
Finds any `"[...]"` where the middle has no `'['` or `']'` and replaces the `'['` and `']'` with zeros. Repeats that until no change happens. Checks each value in the result for existence in `"[]"`, giving a list of zeros and ones where the ones identify any `'['` or `']'` to remove. Logical ORs these with the input characters, to give a list of ones and characters, and then removes the ones.
```
¬Ø[iⱮT,ƝịJƑ¥ƇƊFƲ¦ÐLe€Ø[oḟ1 - Link: list of characters
ÐL - loop while distinct applying:
¦ - sparse application...
¬ - ...of: logical NOT (i.e. replace with a zero)
Ʋ - ...to indices: last 4 links as a monad - f(Current):
Ø[ - "[]"
Ɱ - map across c in Current with:
i - first 1-indexed index of c in "[]" or 0
e.g. "]ab[c]d[" -> [2,0,0,1,0,2,0,1]
Ɗ - last 3 links as a monad - f(X=that):
T - truthy indices [1,4,6,8]
Ɲ - for neighbours:
, - pair [[1,4],[4,6],[6,8]]
Ƈ - keep those for which:
¥ - last 2 links as a dyad - f(Neighbours, X)
ị - Neighbours index into X (vectorises)
Ƒ - is invariant under?:
J - range of length
(i.e. =[1,2]? hence outer indices of "[...]"
with no '[' or ']' in the middle)
F - flatten -> indices of some valid []s
Ø[ - "[]"
€ - for each value in the loop result:
e - exists in "[]"?
o - logical OR with the input (vectorises)
1 - one
ḟ - filter - discard ones
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~65~~ 28 bytes
```
+T`<>`{}`<[^<>]*>
T`{}<>`<>_
```
[Try it online!](https://tio.run/##DchLDkAwAAXAfe8hEa7w8rYu0J2gLUWVSsTCJ85eXc4c9nRBxyyvVCylAtX7KdQt2BQUMikV2MUIbXoBUGhcuPnA0kNQG/SDHclphlvg141hJ38 "Retina 0.8.2 – Try It Online") Link includes test cases. Uses `<>` as brackets. Explanation: Port of @Jonah's JavaScript answer.
```
+`
```
Repeat until no more transliterations can be made.
```
T`<>`{}`<[^<>]*>
```
Transliterate `<>` to `{}` if it's a matched pair that doesn't contain inner `<>`s (but it can include inner `{}` that were previously matched and transliterated).
```
T`{}<>`<>_
```
Transliterate `{}` back to `<>` but delete any remaining `<>` first.
A Replace stage can also be used for the first step for the same byte count:
```
+`<([^<>]*)>
{$1}
T`{}<>`<>_
```
[Try it online!](https://tio.run/##BcE7DkBAFAXQ/q2DxKfS39zWBnSCGQzGNxEFJtY@zjnNZXftwyhXPlWIyhqskpjiguyTQrkPVGDjPXTbCUDRuPHwheECoW7R9WYgxwl2xrJu3A/yBw "Retina 0.8.2 – Try It Online") Link includes test cases.
Previous 65-byte answer deleted mismatched `<>`s directly:
```
(?<!<(?(2)$)((>)|(?<-2><)|\w)*)>|<(?!((<)|(?<-4>>)|\w)*(?(4)^)>)
```
[Try it online!](https://tio.run/##JcvLCoMwGEThfd5C6OIfoRtxOYwvIkK0aWu9gQi9kHdPA27Px9nDMa4@JWtY0BqrcIGZEHO4ViJi@0YJxYyFGU@opRPyUaOD4FKi7wdHynl@@NWPQROdfM/hFu7S48nxxWletG7SHw "Retina 0.8.2 – Try It Online") Link includes test cases. Uses `<>` as brackets. Explanation: Uses lookarounds and .NET balancing groups to directly match and delete unpaired brackets. Note that the lookbehind matches from right-to-left so the three parts are in the opposite order to the lookahead.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
FS¿⁼<ι⊞υω«F⁼>ι≔⎇υ⪫<>⊟υωι¿υ⊞υ⁺⊟υιι»⪫υω
```
[Try it online!](https://tio.run/##RY5BDsIgEEXX5RSTroZETwBp4sKFrkj0AqShLZFAhaJW49mxUI27yeT99387SN86aVLqnAc82DFOp8lr2yOloDvA/TVKE7Dm9Qb08hMxDBg3cKeMKBMUvEhVsj@w@YK7EHRv8ay8lX7OkaPTdhFlQLgRI6VZk2lGqtwV/3phYsCVKjoGpUws0ybMgTdZ7yIteyhLSfIHn5snV82Fp@3NfAA "Charcoal – Try It Online") Link is to verbose version of code. Uses `<>` as brackets only because that's what I used for my Retina answers. Explanation:
```
FS
```
Start by tokenising the input string into characters and loop over them.
```
¿⁼<ι⊞υω«
```
If the next token is a `<`, then push an empty string to the stack, representing the characters waiting to be wrapped in `<>`s. Otherwise:
```
F⁼>ι≔⎇υ⪫<>⊟υωι
```
If the next token is a `>` then if the stack is empty then set the token to the empty string otherwise pop the balanced string from the stack and wrap it in `<>`s.
```
¿υ⊞υ⁺⊟υιι
```
If the stack is (now) empty then print the current balanced string otherwise append it to the top balanced string of the stack.
```
»⪫υω
```
Print any balanced string parts which were waiting to be wrapped in `<>`s but their closing `>`s were missing.
[Answer]
# Python3, 136 bytes:
```
import re
f=lambda x:x.translate(str.maketrans({'{':'[','}':']','[':'',']':''}))if x==(x:=re.sub('\[([\w\{\}]+)*\]','{\\1}',x))else f(x)
```
[Try it online!](https://tio.run/##VY7BTsQgEIbP8hSkF0Bro/FimtRH8AWGOdBdcNlS2gBG1qbPXuluNPH0zcyX@WfmSzpN/uV1Dttmx3kKiQZNTOfU2B8VzW1uUlA@OpU0jyk0oxr0dcIXtrCWAavZWoiFUFiAO1YhrKG563huu6Cb@NlzJoGD/JKLXPFB3Mt9Z5HyeWV1FkK7qKnhWWyRdrSqKlD9gT6@0QICgHsJSBRkuOA3aBzgav9agqqHw1EbxI8T2DMMbkQ/Id5CbuqfKUeImQK11HpqrEs68PfJ65rGJs7OpvKyZ0K05G4O1iduuP0VeygT8IRCbD8)
[Answer]
# [R](https://www.r-project.org), ~~89~~ 86 bytes
```
f=\(x,`[`=gsub)"if"(x!=(x="<([^<>]*)>"["L\\1R",x]),f(x),chartr("LR","<>","<|>"["",x]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY89DoJAEIV7T4Fjs2ugsLNg9wRUFjbDGH5kAfEnQUhW401s0MSLeAtvI4hgTGjeTN588zJzveXVXYlHWShr_loq4TJteuiJ-FgGHFIFTI8F0wJshitb0pRLQHBcd7YAUxM3FdPcDBM_L3IGTm2CLRu5NNwH4d_0p2IdR1gj0q4F_SAEzieGJY26HQ0ySB2CNEj4qPFEZ4wowz6ttwZXyA8wXEeKKE4w3WC23dH-QPQ7ph3_TdtPqqqtbw)
Port of [@Jonah's JS answer](https://codegolf.stackexchange.com/a/245633/55372).
Uses `<>` as brackets and `LR` as intermediate replacement (to lower confusion with `[]` in already two other contexts).
Slightly longer, but a probably more interesting attempt with the use of `Reduce`:
**[R](https://www.r-project.org), 91 bytes**
```
\(x,`[`=gsub)chartr("LR","<>","<|>"["",Reduce(\(a,b)"<([^<>]*)>"["L\\1R",a],1:nchar(x),x)])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY9BDoJADEX3noKMmxkzLNgZM8wJWLEtNQwwoKKYICRovIkbNPEi3sLbOATBmLBpm_7f1_Z2L9tH6j7rKrWXbwhow0MI3exURyzeqLIqKfF8womQXbhKAoRwXyd1rGlAFY8YERTWQuKCdaIXBI7xK-TOqugItGG8Yci-K14pHbgIBimFCaCimDA2t2xpmXI26QEcLICTDgUNnPECGnMYaWNrcgRVBHGiU8RsA9sd5PsDFkfE3zG9_Kf2n7Rtnz8)
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 92 bytes
```
s->strjoin(g(g(s,"[","]"),"]","["))
g(s,l,r,i)=[c|c<-Vecrev(s),c==r&&i++||c!=l||i-->=0||i=0]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY3BCsIwDIbvPkXNQVbWgkcPdo_hJQapdZvVOUs7RaVv4mUg4jP5Nq4qgXz5Qsh_fznt7ap2_aNi6nnqKjl7L4MsQud3R9tm9VBBAIIAAp5aEs5Had0ILyxXaKKZy0VpfHnOAhdGKT-Z2DyP0YxVE6OVslDTgWpK_wyjnWuuWWCyYM7bthtGSAKsGn5wwRBQrw0IBoiUoPGCV7phSXtMTnqNZlNWRPUW7Q73zYHaI31vCYH4L6rvf_wA)
] |
[Question]
[
### Information
* Given a **non-negative odd** integer (let's call it \$n\$), find the **number of all** possible paths which covers all squares and get from the start to end on a grid.
* The grid is of size \$n\$×\$n\$.
* The start of the path is the **top left** corner and the end is the **bottom right corner**.
* You have to count the number of all paths which go from the start to end which covers all squares exactly once.
* The allowed movements are up, down, left and right.
* In other words compute [A001184](https://oeis.org/A001184), but numbers are inputted as grid size.
### Scoring
This is code-golf, write the shortest answer in bytes.
### Test cases
```
1 → 1
3 → 2
5 → 104
7 → 111712
9 → 2688307514
11 → 1445778936756068
13 → 17337631013706758184626
```
[Answer]
# [Python 3](https://docs.python.org/3/), 109 bytes
```
f=lambda n,x=0,*s:1-(x in s)and(x==n*n-1==len(s)or sum(f(n,x+a,x,*s)for a in(~x%n>0,x%n//-n,n,-n)if-1<x<n*n))
```
[Try it online!](https://tio.run/##FYzBCoMwEER/JZfCxm7QIL2I239JsaEBHcUopJf@erpe5jDz5m3f47OirzXKHJbXFAy4SMdNHryjYhJMtgETFRE0cF5kfoOyXXeTz4UiKX8PXPRho5ZBL/QrNzw71mxbBwY72BSdH8uoEmvrReKSe@75MZhtTzgumW5/ "Python 3 – Try It Online")
Port of my answer to [Find the shortest route on an ASCII road](https://codegolf.stackexchange.com/a/195042/87681). Brute forces all paths and returns the number of valid ones. Slow as molasses, though.
*-4 bytes thanks to [Jakque](https://codegolf.stackexchange.com/users/103772/jakque)*
*-8 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
æịþḶFµḢ;ⱮṖŒ!;€ṪƲIỊẠ€S
```
[Try it online!](https://tio.run/##AT8AwP9qZWxsef//w6bhu4vDvuG4tkbCteG4ojvisa7huZbFkiE74oKs4bmqxrJJ4buK4bqg4oKsU/8xLDPDh@KCrP8 "Jelly – Try It Online")
Takes forever for `n>3` because it tries to generate all permutations of `n**2-2` items.
```
æịþḶFµḢ;ⱮṖŒ!;€ṪƲIỊẠ€S Monadic link. Input: n
æịþḶF Generate complex numbers (1..n)+(0..n-1)i
µḢ;ⱮṖŒ!;€ṪƲ Generate all permutations with 1st and last fixed:
Ḣ;Ɱ Chain 1st to each of...
ṖŒ!;€ Permutations of the middle with...
ṪƲ The last chained to the end of each
IỊẠ€S Count those whose pairwise distances are all 1
```
[Answer]
# [Python 3](https://docs.python.org/3/), 185 bytes
```
def f(n):k=range(n);v=[-~x+y*1j for x in k for y in k];return sum(all(abs(z-y)<=1for y,z in zip(x,x[1:]))for x in[[1]+[*q]+[v[-1]]for q in permutations(v[1:-1])])
from itertools import*
```
[Try it online!](https://tio.run/##NYxNDoMgGET3PQVL8GdB3Gk9CWFBU2ipCviBBlz06hRNupm8ZN6MS@FtTZfzUyqksCH9NIIwL1lw2EfWfmOdKvpBygKKSBs0XZgu5APIsIFBfluwmGcsHh4fbSL3kV5Wc5zeoR2OTWS054T8jxijvGbVWmJnLeX8LNZTdxKWLYigrfF4L6vSEk5uCuyCdJAQrJ090ouzEKrsQJuAFe4IyT8 "Python 3 – Try It Online")
@Bubbler's Jelly answer port
-3 thanks to @KevinCruijssen
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 27 bytes
```
LD<⩨¦œε®нš®θªü2€øÆnOtΘP}O
```
[Try it online!](https://tio.run/##ATgAx/9vc2FiaWX//0xEPMOiwqnCqMKmxZPOtcKu0L3FocKuzrjCqsO8MuKCrMO4w4ZuT3TOmFB9T///Mw "05AB1E – Try It Online")
Basic idea is like Bubblers, represent the grid as complex numbers, jumble all the intermediate cells between the first and last, and compute their distances and check if they are adjacent
a byte save thanks to @KevinCruijssen
**Explanation (pseudo-code)**
```
range
dup
decrement
cartesian product
copy to register (no pop)
cut tail
behead
permutations
map
push register
head
prepend
push register
tail
append
cumulative pairs
map
zip
deltas
square
sum
square root
equals 1?
product
end map
sum
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes
-3 bytes thanks to [@att](https://codegolf.stackexchange.com/users/81203/att).
```
Length@FindPath[GridGraph@{#,#},1,#^2,{#^2-1},All]/. 0->1&
```
`n = 7` takes 3 minutes on my computer.
[Try it online!](https://tio.run/##DcmxCsIwFEbhV7k04PRHTcHRUkHaxaF7iBBsay60sYRsIc8es5zhO7uNbtlt5I8tK93La/Hf6PqB/TzVpcfA8xjs4fokIDIUxLtFqpEq47Ft5nKmq@zUqTx/egrso2ZQQ7KjBrRqNgaUKinQDdRmU/4 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~36~~ 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
nÍLœε0šZ>ªü2εDI÷ËiÆëI‰ø`ËsÆ*]ÄPΘO
```
Brute-force approach generating permutations of the grid (minus first and last item), so times out for anything \$n>3\$ (\$n=3\$ takes about 5 seconds).
[Try it online.](https://tio.run/##AT4Awf9vc2FiaWX//27DjUzFk861MMWhWj7CqsO8Ms61REnDt8OLacOGw6tJ4oCww7hgw4tzw4YqXcOEUM6YT///Mw)
**Explanation:**
Step 1: Generate all permutations of the list \$[1,n^2-2]\$, and prepend a leading \$0\$ and trailing \$n^2-1\$ to each:
```
n # Push the square of the (implicit) input-integer
Í # Decrease it by 2
L # Push a list in the range [1,n²-2]
œ # Pop and push all permutations of this list
ε # Map each permutation-list to:
0š # Prepend a leading 0
Z # Push the maximum (without popping the list)
> # Increase it by 1
ª # And append it as trailing item
```
[Try just the first step.](https://tio.run/##yy9OTMpM/f8/73Cvz9HJ57YaHF0YZXdo1f//xgA)
Step 2: Check for each list whether it's a valid path:
```
ü2 # Create overlapping pairs of the current list
ε # Inner map the list of pairs to:
D # Duplicate the current pair
I÷ # Integer-divide both integers in this copy by the input-integer
Ëi # If both are the same (they're in the same row of the grid):
Æ # Reduce the current pair by subtracting
ë # Else:
I‰ # Divmod both integers in the current pair by the input-integer
ø # Zip/transpose; swapping rows/columns
` # Pop and push both pairs separated to the stack
Ë # Check if the top pair (the [a%input,b%input]) are both the same
s # Swap to get the other pair (the [a//input,b//input])
Æ # Reduce it by subtracting
* # Multiply it to the a%input==b%input check
] # Close the if-else statement and nested maps
Ä # Take the absolute value of each innermost integer
P # Taking the product of each inner list
Θ # Check for each if it's equal to 1 (1 if 1; 0 if not)
```
The `I÷Ë` checks if the integers in the current pair are in the same row of the grid, and with `Æ` + `Ä` it checks if their absolute difference is 1.
For any remaining pair that are not in the same row, the `I‰ø`ËsÆ*` + `Ä` checks if the two integers are in the same column and their absolute (vertical) difference is also 1.
The `P` after the map then checks if this was truthy for all of the pairs in the list.
[Try the first two steps.](https://tio.run/##AT0Awv9vc2FiaWX//27DjUzFk861MMWhWj7CqsO8Ms61REnDt8OLacOGw6tJ4oCww7hgw4tzw4YqXcOEUM6Y//8z)
Step 3: Check how many valid paths were valid after the map, and output it as result:
```
O # Pop and sum to get the amount of valid paths
# (which is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 82 bytes
```
NθUOθ#J⊖θ⊖θP0⊞υ⌕AKV#≔⁰ηWυ«≔⊟υι¿ι«⊞υι≔⊟ιιM✳⁻χ⊗ιPIι⊞υ⌕AKV#»«≧⁺¬∨∨ⅈⅉ№KA#η✳⁻⁶⊗KK#»»⎚Iη
```
[Try it online!](https://tio.run/##hVFNS8NAED0nv2Kpl1mIUBG89FRSBIW0QUT0mKZjM7jZTfejHqS/Pc4mllQvwrIw897Me2@3bipbm0r1/YPugl@HdosWDnKRbrbK6D0cMjG7mnH9GNru2cAKa4stao87pmXid828IihPnSXtYTaPg2VwDYRM3JPeLZWCEvHjxeg1hrbSGuQowMSlc7TXMM9Ew9VnQwoFBCm@0uQHKk3HjUwQ4wm9C6ABTc4SQ/@STGdyUpgjwoos1p6MhoJ0cHDDWisTtorNk5RyZE4B8sr5CCwuNP6NkZzSBJXDwVlRdaOdJ9o3HkoVXCbWxsPGxvMa595A8p2bwIpxa9x@XifHx2D5wdDfAHeT/zgJcpgYP4x9nNJcYWUh/sIUqGGXfX/bXx/VNw "Charcoal – Try It Online") Link is to verbose version of code. Will do `n=5` on TIO but larger numbers are probably too slow. Explanation: Works by counting the paths from the bottom right corner back to the top left corner of an `n×n` square drawn on the canvas.
```
Nθ
```
Input `n`.
```
UOθ#
```
Draw an `n×n` square of `#`s.
```
J⊖θ⊖θP0
```
Start at the bottom right corner. (Any digit works here, it's just a placeholder showing that the square has been visited.)
```
⊞υ⌕AKV#
```
Start with the possible moves from the corner. (This is empty for `n=1` of course.)
```
≔⁰η
```
Start with `0` paths found.
```
Wυ«
```
Repeat until all paths have been attempted.
```
≔⊟υι
```
Pop the remaining moves to try from the current cell from the stack.
```
¿ι«
```
If there are any moves left, then:
```
⊞υι
```
Push the moves back to the stack again.
```
≔⊟ιι
```
Pop the next move to try.
```
M✳⁻χ⊗ι
```
Move in that direction.
```
PIι
```
Overwrite the current cell with the direction, so that we can find our way back, and also so that we don't try to re-enter the cell.
```
⊞υ⌕AKV#
```
Push the available moves from this cell to the stack.
```
»«
```
Otherwise:
```
≧⁺¬∨∨ⅈⅉ№KA#η
```
If the current cell is at the top left and there are no `#`s left indicating that we've covered all of the squares, then increment the count of paths found.
```
✳⁻⁶⊗KK#
```
Overwrite the current cell with a `#` and move back to the previous cell.
```
»»⎚Iη
```
Clear the canvas and output the number of paths found.
[Answer]
# [Python 3](https://docs.python.org/3/), 138 bytes
```
f=lambda n,a={0},x=0,y=0:n==len(a)/n<x+2<y+3or sum(f(n,a|{(x,y)},i,j)for i in range(n)for j in range(n)if(x-i)**2+(y-j)**2==1and{(i,j)}-a)
```
[Try it online!](https://tio.run/##XYzLDoIwEEX3fkXDagaGyCNxQRj/pQaqJTAQxKQN8u0VXBl3N@eenMkvj1HKEAz3erg1WglpXrONHGfkOauEuW8FNJ6ldklR@6QcZ/V8DWBgd98rOPK4kaUOzf5YZUXNWu4tyBd0v8AacKnFOC4S8Gl3DOZcS7PCEdhSjeGvktMFq5OaZivLLqmIrxEpAxYxfAA "Python 3 – Try It Online")
returns `True` for `f(1)`
## How it works :
take as input :
* `n` the size of the grid
* `a={0}` the set of all visited positions initialized with a `0` to avoid typing `set()`
* `x=0,y=0` the current position in the grid
then :
* `n==len(a)/n<x+2<y+3` verify if we visited all positions and if we are in the bottom right of the grid
* `f(n,a|{(x,y)},i,j)for i in range(n)for j in range(n) if` recursively call `f` with all the position verifying
+ `(x-i)**2+(y-j)**2==1` the position is at distance `1` of `(x,y)`
+ `{(i,j)}-a` the position is unvisited
] |
[Question]
[
You have a bunch of cities on a grid which you wish to link up. Roads can be placed on any tile that doesn't contain a city, and connect to all roads or cities adjacent to them, vertically, horizontally or diagonally.
Roads can link up via cities, for example
```
C
\
C-C
```
is fully linked up.
However, there are some mountains in your way. Roads can't pass through mountains, and have to go around them. In my examples/testcases, these will be be marked as M.
With
```
M
C M C
M
```
Something like
```
^
/M\
C M C
M
```
Will have to be done.
Roads can go through mountain passes diagonally, for example
```
C M
\M
MM\
C
```
is valid.
# Your challenge
Given an arrangement of cities and mountains, output the minimum number of roads needed to connect them all.
# Rules
Input can be taken however you like, as ascii-art, a matrix, the positions of the cities and mountains, etc.
You may assume that no adjacent cities (like `CC`) will ever be inputted.
# Testcases
Note: These are formatted as ASCII-art.
```
C C
=> 1
C C
C
=> 1 (in the centre)
C M C
=> 3
MMC
M
C M
=> 1
MMMMMMMMM
MCMCM M
M M M M M
M M M M
M MMMMM M
M M
MMMMMMMMM
=> 15
C C
C
C
C C
=> 5
MMM
CMC
MMM
=> 5
C
MMMMMMMMMM
C C
=> 11
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~63~~ ~~54~~ 52 bytes
Quite slow, but after some optimisation, this can now run some testcases!
```
2Føðδ.ø}©˜„ CSδQƶø0δK<®øg‰`Uæé.ΔX«Dδ-nO3‹DvDδ*O}ßĀ}g
```
[Try it online!](https://tio.run/##yy9OTMpM/V9WqW59aKGek8uh3TqPmtYE/zdyO7zj8IZzW/QO76g9tPL0nEcN8xScg89tCTy27fAOg3NbvG0OrTu8I/1Rw4aE0MPLDq/UOzcl4tBql3NbdPP8jR817HQpA7K1/GsPzz/SUJv@X8nWTuHwfi4lnf/RSs4Kzko6CkDKF8Lw9XW2VlDwtQYKQLhAJlAISCvF/tfVzcvXzUmsqgQA "05AB1E – Try It Online")
The algorithm used has complexity \$\mathcal{O}\left(2^{(n+2)^2} (n+2)^6\right)\$ (for a grid of size \$n \times n\$) and uses matrix multiplication (`øδ*O`), which is often incredibly slow in 05AB1E.
### How?
A slightly different interpretation of the tasks helps explaining the approach: Instead of placing roads, we can also place additional cities into the grid until all cities are connected.
The program tries all combinations of new cities in increasing order of new cities until it finds a valid solution.
To validate a given attempt we consider a graph where the vertices are cities and two cities are connected with an edge if they are vertically, horizontally or diagonally adjacent. Two cities are adjacent, iff their squared Euclidean distance is less than \$3\$.
This property can be used to calculate an adjacency matrix from a list of city coordinates. An undirected graph of \$n\$ vertices with adjacency matrix \$A\$ is connected, iff \$A^n\$ has no zeros. Example:
```
map
C
C C
city coordinates
[0,1], [1,0], [1,2]
pairwise squared Euclidean distances
0 2 2
2 0 4
2 4 0
adjacency matrix A
1 1 1
1 1 0
1 0 1
A^3
7 5 5
5 4 3
5 3 4
min(A^3) = 3 > 0 => connected
```
[Try your own example!](https://tio.run/##yy9OTMpM/f//0LJDK1y4lHITC7gO7@dS0uHiOrTt0EI9p0dNa4JdDq08PUfdOfBIo5aBt82hdYd3pD9q2OASyqWUnFlSqZCcn1@UkpmXWJJaDNRnqwTS7HJui26eP9DAgsTMovLM4lSF4sLSxKLUFAXX0uSczJTUxDyFlMziksS8ZLCuqPTiQ8uzDu3WAes2ftSwE6g3MSUrMTk1L7lSITexpCizQsERKAlTc2hlRLqN26F157Zo@de6cEWkKznGHd6PYVQ40E@ZeRqOcXmaCrYKIAX//yspKXE5OysoOHMpKEBIZ2cuoOB/Xd28fN2cxKpKAA "05AB1E – Try It Online")
**Commented Code**:
```
# pad with spaces
2F } # execute two times:
ø # transpose the grid
ðδ.ø # and surround every row with spaces
# get coordinates of cities and spaces
© # store the padded grid in the register
˜ # flatten the grid
„ CS # push [" ", "C"]
δQ # equality table (== [[char==" ", char=="C"] for char in flat_grid])
ƶ # multiply each pair by its 1-based index
ø # tranpose
0δK # remove all zeros
< # decrement by 1
# Now we have a two list of coordinates of spaces and cities in the flattened grid
® # get the grid from the register
øg # get the height (length of the tranpose)
‰ # divmod each flat index with this
# this results into the 2d-indices
` # push cities and spaces seperately on the stack
U # store coordinates of cities in variable X
# coordinates of spaces are now on top of the stack
# try subsets of the spaces until we get a connected graph
æ # push the powerset (all subsets) of space coordinates
é # sort by length
.Δ } # find the first value for which the following is truthy
X« # append the existing cities to the current subset of spaces
D # duplicate
δ- # subtraction table
n # square each difference
O # sum each pair of squared differences
3‹ # for each number: is it less than 3?
# this is the adjacency matrix A
D # make a copy of the matrix
v } # for each row in A:
D # duplicate current matrix
δ*O # matrix multiplication (for symmetric matrices)
ßĀ # is the minimum not 0?
g # take the length of the result
```
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 31 bytes
Takes input as lists of 1-indexed coordinates of cities and mountains. Even less efficient if the input is not square.
```
«Z>ÝãsKæé.Δ¹«Dδ-nO3‹DvDδ*O}ßĀ}g
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0Ooou8NzDy8u9j687PBKvXNTDu08tNrl3BbdPH/jRw07XcqAbC3/2sPzjzTUpv//Hx1tpKNgGKujAKKNY2O5oqMNoQJA2ghKG0MVgPnGUHljBB@o8b@ubl6@bk5iVSUA "05AB1E – Try It Online")
```
« # concatenate cities and mountains
Z> # maximum integer in the list + 1 (0 and +1 for padding)
Ý # push range from 0 to this value
ã # cartesian square: all 2d coordinates with values in that range
sK # remove all cities and mountains, this leaves the coordinates of spaces
... # same as above
```
[Answer]
# [Kotlin](https://kotlinlang.org) with [JGraphT](https://jgrapht.org), ~~3009~~ 2984 (thanks to ophact) bytes (plus header/footer)
```
import org.jgrapht.Graph
import org.jgrapht.GraphPath
import org.jgrapht.alg.connectivity.ConnectivityInspector
import org.jgrapht.alg.shortestpath.AllDirectedPaths
import org.jgrapht.alg.shortestpath.DijkstraManyToManyShortestPaths
import org.jgrapht.graph.DefaultDirectedGraph
import org.jgrapht.graph.DefaultEdge
import org.jgrapht.graph.DefaultUndirectedGraph
import org.jgrapht.graph.builder.GraphBuilder
import kotlin.streams.asStream
sealed class P
object C:P()
object M:P()
object E:P()
object R:P()
typealias D=Pair<Int,Int>
typealias L<T> =List<T>
typealias A<T> =Array<T>
typealias F=DefaultEdge
typealias G=BooleanArray
object H:ThreadLocal<G>(){override fun initialValue()=G(1 shl(B*2)){false}}
const val B=4
fun GraphPath<D,F>.v():A<D>{val r=arrayOfNulls<D>(edgeList.size+1)
r[0]=graph.getEdgeSource(edgeList.first())
edgeList.forEachIndexed{i,e->r[i+1]=graph.getEdgeTarget(e)}
return r as A<D>}
fun A<GraphPath<D,F>>.d()=sumOf{val table=if(B<=3){G(1 shl(B*2)){false}}else{H.get().also{for(i in it.indices){it[i]=false}}}
it.v().sumOf{val hash=(it.first+1)or(it.second+1).shl(B)
if(table[hash]){0}else{table[hash]=true
1}.toInt()}}
fun j(b:GraphBuilder<D,*,*>,x:Int,y:Int){val others=(x-1..x+1).flatMap{z->(y-1..y+1).map{z to it}}
others.forEach{b.addEdge(x to y,it)}}
fun g(g:L<L<P>>):Pair<Set<D>,Graph<D,F>>{val b=DefaultDirectedGraph.createBuilder<D,F>(::DefaultEdge)
val c=mutableSetOf<D>()
g.forEachIndexed{y,r->r.forEachIndexed{x,p->when(p){C->{c+=x to y
j(b,x,y)}
E->j(b,x,y)
R->error("")}}}
val width=g[0].size
g.indices.forEach{y->if (g[y][0]==M)j(b,-1,y)
if (g[y].last()==M)j(b,width,y)}
(0 until width).forEach{x->if (g[0][x]==M)j(b,x,-1)
if (g.last()[x]==M)j(b,x,g.size)}
return c to b.buildAsUnmodifiable()}
fun t(c: Set<D>, g:Graph<D,F>):Set<D>{val d=DijkstraManyToManyShortestPaths(g).getManyToManyPaths(c,c)
val h=c.flatMap{o->c.map{o to it}}.filter{if(it.first.first==it.second.first)it.first.second>it.second.second else it.first.first>it.second.first}.associateWith{d.getPath(it.first,it.second)}.map{it.key to AllDirectedPaths(g).getAllPaths(it.key.first,it.key.second,true,it.value.length)}
val j=h.map{it.first}
val k=h.map{it.second}
val l=k.s{val m=DefaultUndirectedGraph.createBuilder<D,F>(::DefaultEdge)
m.addVertices(*c.toTypedArray())
it.mapIndexed{i,b->if(b)j[i]else null}.filterNotNull().forEach{m.addEdge(it.first,it.second)}
ConnectivityInspector(m.buildAsUnmodifiable()).isConnected}
return HashSet(l.asStream().parallel().map{it to it.d()}.min{n,o->n.second-o.second}.get().first.flatMap{it.v().asList()})}
fun a(a:String)=a.lines().map{it.map{when(it){'M'->M
'.',' '->E
'C'->C
'R'->R
else->null}}.filterNotNull()}.filter{it.isNotEmpty()}
fun l(data:L<L<P>>, route:Set<D>)=route.sumOf{if(it.second<0||it.second>data.lastIndex)return@sumOf 1
val row=data[it.second]
if(it.first<0||it.first>row.lastIndex)return@sumOf 1
if(row[it.first]==E)1.toInt()else 0}
inline fun<reified T>L<L<T>>.s(noinline test:(A<Boolean>)->Boolean)=List(size){listOf(false,true)}.c().filter(test).let{sequence{for(selection in it){yieldAll(filterIndexed { i, _->selection[i]}.c())}}}
inline fun <reified T>L<L<T>>.c()=sequence{if(isEmpty())return@sequence
val j=map{it.iterator()}.toTypedArray()
val v=j.map{it.next()}.toTypedArray()
yield(v.clone())
while(true){var i=0
while(!j[i].hasNext()){j[i]=get(i).iterator()
v[i]=j[i].next()
if(++i>lastIndex)return@sequence}
v[i]=j[i].next()
yield(v.clone())}}
fun main() {
val art = System.`in`.bufferedReader().readText()
val data = a(art)
val (cities, graph) = g(data)
val route = t(cities, graph)
println("Length: ${l(data, route)}")
}
```
Here is the original, prior to golfing:
```
import org.jgrapht.Graph
import org.jgrapht.GraphPath
import org.jgrapht.alg.connectivity.ConnectivityInspector
import org.jgrapht.alg.shortestpath.AllDirectedPaths
import org.jgrapht.alg.shortestpath.DijkstraManyToManyShortestPaths
import org.jgrapht.graph.DefaultDirectedGraph
import org.jgrapht.graph.DefaultEdge
import org.jgrapht.graph.DefaultUndirectedGraph
import org.jgrapht.graph.builder.GraphBuilder
import java.util.concurrent.atomic.AtomicLong
import kotlin.concurrent.thread
import kotlin.streams.asStream
sealed class Place
object City : Place()
object Mountain : Place()
object Empty : Place()
object Road : Place()
typealias Coord = Pair<Int, Int>
operator fun Coord.compareTo(other: Coord): Int {
return first.compareTo(other.first).let {
if (it == 0)
second.compareTo(other.second)
else
it
}
}
fun <T> Collection<T>.toHashSet() = HashSet(this)
object HashTable : ThreadLocal<BooleanArray>() {
override fun initialValue(): BooleanArray {
return BooleanArray(1 shl (MAX_DIMEN_BITS * 2)) { false }
}
}
const val MAX_DIMEN_BITS = 4
inline fun <reified V, E> GraphPath<V, E>.getVertexListFast(): Array<V> {
val ret = Array<V?>(edgeList.size + 1) { null }
ret[0] = graph.getEdgeSource(edgeList.first())
edgeList.forEachIndexed { i, edge ->
ret[i + 1] = graph.getEdgeTarget(edge)
}
@Suppress("UNCHECKED_CAST")
return ret as Array<V>
}
fun Array<GraphPath<Coord, DefaultEdge>>.distinctSize() = sumOf { path ->
val table = if (MAX_DIMEN_BITS <= 3) {
BooleanArray(1 shl (MAX_DIMEN_BITS * 2)) { false }
} else {
HashTable.get().also {
for (i in it.indices) {
it[i] = false
}
}
}
path.getVertexListFast().sumOf {
val hash = (it.first + 1) or (it.second + 1).shl(MAX_DIMEN_BITS)
if (table[hash]) {
0
} else {
table[hash] = true
1
}.toInt() /* stupid overload resolution */
}
}
fun joinUp(builder: GraphBuilder<Coord, *, *>, x: Int, y: Int) {
val others = (x - 1 .. x + 1).flatMap { otherX -> (y - 1 .. y + 1).map { otherY -> otherX to otherY } }
others.forEach {
builder.addEdge(x to y, it)
}
}
fun createGraph(grid: List<List<Place>>): Pair<Set<Coord>, Graph<Coord, DefaultEdge>> {
val builder = DefaultDirectedGraph.createBuilder<Coord, DefaultEdge> { DefaultEdge() }
val cities = mutableSetOf<Coord>()
grid.forEachIndexed { y, row ->
row.forEachIndexed { x, place ->
when (place) {
City -> {
cities += x to y
joinUp(builder, x, y)
}
Mountain -> {
}
Empty -> joinUp(builder, x, y)
Road -> error("Cannot pre-supply Roads")
}
}
}
val width = grid.first().size
grid.indices.forEach { y ->
if (grid[y].first() == Mountain)
joinUp(builder, -1, y)
if (grid[y].last() == Mountain)
joinUp(builder, width, y)
}
(0 until width).forEach { x ->
if (grid.first()[x] == Mountain)
joinUp(builder, x, -1)
if (grid.last()[x] == Mountain)
joinUp(builder, x, grid.size)
}
return cities to builder.buildAsUnmodifiable()
}
fun joinCities(cities: Set<Coord>, graph: Graph<Coord, DefaultEdge>): Set<Coord> {
val allPathsAlgo = AllDirectedPaths(graph)
val dijkstraAlgo = DijkstraManyToManyShortestPaths(graph)
val shortestPaths = dijkstraAlgo.getManyToManyPaths(cities, cities)
val sourceTargets = cities.flatMap { outer -> cities.map { outer to it } }.filter { it.first > it.second }
val shortestLengths = sourceTargets.associateWith {
shortestPaths.getPath(it.first, it.second)
}
val allShortestPathsWithKey = shortestLengths.map {
it.key to allPathsAlgo.getAllPaths(it.key.first, it.key.second, true, it.value.length)
}
val allShortestPathsKeys = allShortestPathsWithKey.map { it.first }
val allShortestPaths = allShortestPathsWithKey.map { it.second }
val i = AtomicLong()
val (total, allPathsProduct) = allShortestPaths.selectiveCartesianProduct { selection ->
val builder = DefaultUndirectedGraph.createBuilder<Coord, DefaultEdge> { DefaultEdge() }
builder.addVertices(*cities.toTypedArray())
selection.mapIndexed { i, bool -> if (bool) allShortestPathsKeys[i] else null }.filterNotNull().forEach { builder.addEdge(it.first, it.second) }
val selectionGraph = builder.buildAsUnmodifiable()
ConnectivityInspector(selectionGraph).isConnected
}
val startTime = System.currentTimeMillis()
val counterThread = thread(true) {
try {
while (true) {
Thread.sleep(1000)
val progress = i.getOpaque()
val percent = (progress.toDouble() / total.toDouble()) * 100f
print("Progress: $progress\t/ $total\t($percent%)\t(${System.currentTimeMillis() - startTime} ms)\r")
}
} catch (e: InterruptedException) {
println()
}
}
val ret = allPathsProduct
.asStream()
.parallel()
.map { (it to it.distinctSize()).also { i.incrementAndGet() } }
.min { left, right -> left.second - right.second }.get().first.flatMap { it.getVertexListFast().asIterable() }.toHashSet()
counterThread.interrupt()
counterThread.join()
return ret
}
fun artToData(art: String) = art.lines().map {
it.map { char ->
when (char) {
'M' -> Mountain
'.', ' ' -> Empty
'C' -> City
'R' -> Road
else -> null
}
}.filterNotNull()
}.filter { it.isNotEmpty() }
fun plotRoute(data: List<List<Place>>, route: Set<Coord>): List<List<Place>> {
val width = data[0].size
val emptyLine = List<Place>(width + 2) { Empty }
val newData = mutableListOf(emptyLine.toMutableList(), *data.map { mutableListOf(Empty, *it.toTypedArray(), Empty) }.toTypedArray(), emptyLine.toMutableList())
for (point in route) {
if (newData[point.second + 1][point.first + 1] == Empty) {
newData[point.second + 1][point.first + 1] = Road
}
}
return newData
}
fun routeLength(data: List<List<Place>>, route: Set<Coord>): Int = route.sumOf { point ->
if (point.second < 0 || point.second > data.lastIndex) return@sumOf 1
val row = data[point.second]
if (point.first < 0 || point.first > row.lastIndex) return@sumOf 1
if (row[point.first] == Empty) 1.toInt() /* needed due to overload ambiguity */ else 0
}
fun dataToArt(data: List<List<Place>>) = buildString {
data.forEach { row ->
row.forEach { place ->
append(
when (place) {
City -> 'C'
Empty -> '.'
Mountain -> 'M'
Road -> 'R'
}
)
}
append('\n')
}
}
inline fun <reified T> List<Collection<T>>.selectiveCartesianProduct(noinline test: (Array<Boolean>) -> Boolean): Pair<Long, Sequence<Array<T>>> {
val selections = List(size) { listOf(false, true) }.cartesianProduct().filter(test)
val total = selections.sumOf { selection ->
val selected = filterIndexed { i, _ -> selection[i] }
if (selected.isEmpty()) 0 else selected.fold(1L) { acc, value -> acc * value.size }
}
return total to sequence {
for (selection in selections) {
yieldAll(filterIndexed { i, _ -> selection[i] }.cartesianProduct())
}
}
}
inline fun <reified T> List<Iterable<T>>.cartesianProduct() = sequence {
if (isEmpty()) return@sequence
val iterators = map { it.iterator() }.toTypedArray()
val values = iterators.map { it.next() }.toTypedArray()
yield(values.clone())
while (true) {
var i = 0
while (!iterators[i].hasNext()) {
// reset current iterator, move on to check next one
iterators[i] = get(i).iterator()
values[i] = iterators[i].next()
if (++i > lastIndex)
return@sequence
}
values[i] = iterators[i].next()
yield(values.clone())
}
}
fun main() {
val art = System.`in`.bufferedReader().readText()
val data = artToData(art)
val (cities, graph) = createGraph(data)
val route = joinCities(cities, graph)
println("Length: ${routeLength(data, route)}")
val newData = plotRoute(data, route)
println(dataToArt(newData))
}
```
The algorithm is very intractable: with the sample with 6 cities, it takes ~300 minutes of CPU time on my high-end desktop
Note that if your input data is longer than 14 on any dimension, you have to increase MAX\_DIMEN\_BITS.
Input is sent to stdin followed by EOF (^D) as ASCII art.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes
```
;_þ`²§<3æ*L$Ȧ
FṀ‘Żṗ2ḟẎŒPçƇḢḢL
```
[Try it online!](https://tio.run/##AV0Aov9qZWxsef//O1/DvmDCssKnPDPDpipMJMimCkbhuYDigJjFu@G5lzLhuJ/huo7FklDDp8aH4bii4biiTP/hu7Tigb5DTWnisa7isa7Fk@G6ueKxrjEsMsOH//9DTUM "Jelly – Try It Online")
Uses [ovs' method](https://codegolf.stackexchange.com/a/229197/66833), be sure to give them an upvote!
Takes the input as a pair `[a, b]` where `a` is a list of 1 indexed co-ordinates of cities and `b` a list of 1 indexed co-ordinates of mountains
This is *stupidly* slow. For an \$n \times m\$ matrix with \$x\$ spaces, this has a lower bound of \$O(2^{\max(n,m)^2-x})\$, and that doesn't factor in the speed of Jelly's matrix power, which isn't fast. This doesn't finish on TIO for any valid input
# [Jelly](https://github.com/DennisMitchell/jelly), 36 bytes
```
;’_þ`²§<3æ*L$Ȧ
Ż€ZUƊ4¡µœẹ0ŒPçƇœẹ1$ḢL
```
[Try it online!](https://tio.run/##y0rNyan8/9/6UcPM@MP7Eg5tOrTcxvjwMi0flRPLuI7uftS0Jir0WJfJoYWHth6d/HDXToOjkwIOLz/WDuYYqjzcscjn/8PdWx417nP2zXy0cR0QHW7//9/Z1xkA "Jelly – Try It Online")
Also *incredibly* slow. For an input of size \$n\times m\$ with \$x\$ spaces, this has an absolute lower bound of \$O(2^{2(n+m)+x})\$, and that doesn't factor in the speed of Jelly's matrix power, or the fact that it has to calculate \$2^{2(n+m)+x}\$ Cartesian products with the number of cities in the input.
There are various optimisations you can do if you know the input before hand. For example, [this](https://tio.run/##y0rNyan8/9/6UcPM@MP7Eg5tOrTcxvjwMi0flRPLuI7uftS0Jir0WJfRoYUPd047tPXo5Ie7dhocnRTwcEfX4eXH2sF8Q5WHOxb5/H@4e8ujxn3OvpmPNq4DosPt//8rgACXs4KvgjMA) is a much faster version that works for inputs that can be constructed as going over the "top" of the mountains.
# [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes
```
;’_þ`²§<3æ*L$Ȧ
Ż€ZUƊ4¡µœẹ0ŒPçƇŒṪḢL
```
[Try it online!](https://tio.run/##AVAAr/9qZWxsef//O@KAmV/DvmDCssKnPDPDpipMJMimCsW74oKsWlXGijTCocK1xZPhurkwxZJQw6fGh8WS4bmq4biiTP///1tbMSwgW10sIDFdXQ "Jelly – Try It Online")
Exactly the same as the 36 byte version, but takes input as a matrix where `0` is a space, `1` is a city and `[]` is a mountain. For example, `C M C` is `[[1, 0, [], 0, 1]]`
## How they work
```
;_þ`²§<3æ*L$Ȧ - Helper link. Takes S (indices of spaces) and C (indices of cities)
; - Concatenate
_þ` - Create a subtraction table
² - Square each
§ - Sums of each
<3 - Less than 3?
$ - To this square matrix M:
L - Get its length
æ* - Raise it to that power
Ȧ - Are all elements of the matrix non-zero?
FṀ‘Żṗ2ḟẎŒPçƇḢḢL - Main link. Takes [a, b] on the left
F - Flatten
Ṁ - Maximum
‘ - Increment
Ż - Range from zero
ṗ2 - Cartesian square
This gets all possible coordinates, including an outer border
Ẏ - Flatten the argument into a list of coords
ḟ - Remove the mountain + city coords from the list
ŒP - Powerset
Ḣ - Extract the list of city coords
çƇ - Keep the powerset elements that are truthy under the helper link
ḢL - Take the shortest one and return its length
```
```
;’_þ`²§<3æ*L$Ȧ - Helper link. Takes S (indices of spaces) and C (indices of cities)
; - Concatenate
’ - Decrement to zero index
_þ` - Create a subtraction table
² - Square each
§ - Sums of each
<3 - Less than 3?
$ - To this square matrix M:
L - Get its length
æ* - Raise it to that power
Ȧ - Are all elements of the matrix non-zero?
Ż€ZUƊ4¡µœẹ0ŒPçƇœẹ1$ḢL - Main link. Takes matrix M on the left
Ɗ4¡ - Do the following 4 times:
Ż€ - Prepend a zero to each row
Z - Transpose
U - Reverse
µ - Begin a new link with this bordered matrix M' as the argument
œẹ0 - Get the indices of zeros
ŒP - Powerset
$ - To M':
œẹ1 - Get the indices of ones
çƇ - Keep the powerset elements that are truthy under the helper link
ḢL - Take the shortest one and return its length
```
The third one takes advantage of the fact `[]` is both falsey and non-zero, and replaces `œẹ1$` with `ŒṪ` which gets the indices of all truthy elements in `M'`
[Answer]
# [Python 3](https://docs.python.org/3/) + [numpy](https://numpy.org/doc/stable/), 325 bytes
A (slightly faster) port of my 05AB1E solution. The computational complexity is still the same, but especially the matrix operations are faster.
```
from itertools import*
from numpy import*
def f(G):
E=enumerate;k=[' '];p,c,*s=[k*len(G[0])],[]
for y,r in E([k+r+k for r in p+G+p]):
for x,v in E(r):[s,p,p,c][ord(v)%4]+=[y,x],
for i in count():
for N in combinations(s,i):
v=array(c+[*N]);A=sum((v-v[:,None])**2,axis=2)<3
for _ in v:A=A@A
if A.min():return i
```
[Try it online!](https://tio.run/##PZDRboMgFIbvfYpzswiKTdPtyo5kxjS9si9AyeIUN6ICATT16Z3YpOEC@M7//4eDWfyfVu/r2lk9gvTCeq0HB3I02vok2rGaRrO8UCs66NAV5xFcqNhqwtZenHvKYoj52ZCGJI6yPhmEQld25JgTxiPotIWFWJAKLoj1qU37ne3EpNfU8JC5sweZnzqLc@aI2VbDmbYtmvHbB08pW8iDk2eoDNJGT8qjV8DtycYfqWovtXLIEblXYaa1tfWCmpQlN47PBXXTiNCczSwnN60Ex0lyIvVDOnrCn@/BEyK/Q@ScF7T4KgKTHRSHUaqtqRV@sgrkGnReOB@k2mzzH/HBirpF@ODMID2K7yrLsruK97f8WtkCBTZI59EglcB7p3AKCSHp6QvEIbz9Ihgrt0E7FLwYryWU0ZYYVVUVlVW57@FeQvWqlJutCuQf "Python 3 – Try It Online")
Ungolfed full program:
```
import itertools, sys
import numpy as np
grid = [list(line) for line in sys.stdin.read().splitlines()]
print(grid)
width = len(grid[0])
# pad with spaces on all sides
padding = [[' '] * width]
grid = [[' ', *row, ' '] for row in padding + grid + padding]
# get the coordinates of cities and empty spaces
cities = [[y, x] for y, row in enumerate(grid) for x, v in enumerate(row) if 'C' == v]
spaces = [[y, x] for y, row in enumerate(grid) for x, v in enumerate(row) if ' ' == v]
for i in range(len(spaces)):
# Iterate over all combinations of i new cities
for new_cities in itertools.combinations(spaces, i):
vertices = np.array([*cities, *new_cities])
adjacency = (np.sum((vertices - vertices[:, None])**2, axis=-1)<3)
if (np.linalg.matrix_power(adjacency, adjacency.shape[0]) > 0).all():
print(i)
exit()
```
[Try it online!](https://tio.run/##rZJNbtswEIX3PMUDsjDpKELa7II6G6@ycC9gCAFr0fIUEkmQjG2d3h1KtNLuuxI5P98bPo0f08nZl9uNBu9CAiUTknN9rBDHKErUfg5@hI6wXoguUIsN9j3FJHuyRuHoAvIJZHNbHVNLtg5Gt1LV0feUcjZK1QgfyCaZGUpcqE0nRvXGTpH9c6OEeIDXLS7Eqej1wUQ4C933iNSaKDjJ8C5PsF9h1WCNidMsg@VwhXVwlwpTRR6Pb3m6e/cjpurHe6DJup1JSCeDg3OBgzpl7SMOlIhP2rYwg09jGUuUeFYcK1xnHT4VKcOumcCQ@bVT9lrh/G@OixXoiNV2hc0G50aUR/8nLO5YkQspVwVtOyOz6bOUUq8CeMB7mnrhziZMhh/c8CvbQM5ORhCsuRQ7uCMDOfBRfGDysj31361FpgJNQgDzE81vtL7WIehR7tczhn/cF5PXIdfr9jcD7GHkBskd8XOQcoE8Lbz9a4WfzppGrdffK@grxc3TN/XjZcawHbmbV1H3XT3oFOj64d3FBLkoVF9idTxpb/JO4g3PqmZHZHkAMK8xqXI1V0pS3W673U5sd1vB3z8 "Python 3 – Try It Online")
] |
[Question]
[
Imagine a text file where each csv record may have different numbers of fields. The task is to write code to output how many fields there are in each record of the file. You can assume there is no header line in the file and can read in from a file or standard input, as you choose.
You can assume a version of [rfc4180](https://www.rfc-editor.org/rfc/rfc4180) for the csv rules which I will explain below for the definition of each line of the file. Here is a lightly edited version of the relevant part of the spec:
**Definition of the CSV Format**
1. Each record is located on a separate line, delimited by a line
break (CRLF). For example:
```
aaa,bbb,ccc CRLF
```
zzz,yyy,xxx CRLF
2. The last record in the file may or may not have an ending line
break. For example:
```
aaa,bbb,ccc CRLF
```
zzz,yyy,xxx
(Rule 3. does not apply in this challenge)
4. Within each record, there may be one or more
fields, separated by commas. Spaces are considered part
of a field and should not be ignored.
5. Each field may or may not be enclosed in double quotes. If fields are not enclosed with double quotes, then double quotes may not appear inside the fields. For example:
```
"aaa","bbb","ccc" CRLF
```
zzz,yyy,xxx
6. Fields containing line breaks (CRLF), double quotes, and commas
should be enclosed in double-quotes. For example:
```
"aaa","b CRLF
```
bb","ccc" CRLF
zzz,yyy,xxx
7. If double-quotes are used to enclose fields, then a double-quote
appearing inside a field must be escaped by preceding it with
another double quote. For example:
```
"aaa","b""bb","ccc"
```
## Example
Input:
```
,"Hello, World!"
"aaa","b""bb","ccc"
zzz,yyy,
"aaa","b
bb","ccc","fish",""
```
Should give the output:
```
2, 3, 3, 5
```
Your can give the output values in any way you find most convenient.
## Libraries
You can use any library you like.
---
Awesome answers so far but we are missing a command line/bash answer which would be particularly cool.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~19~~ 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
èJ§3‼}vAà○L>
```
[Run and debug it](https://staxlang.xyz/#p=8a4a1533137d764185094c3e&i=,%22Hello,+World%21%22%0A%22aaa%22,%22b%22%22bb%22,%22ccc%22%0Azzz,yyy,%0A%22aaa%22,%22b+%0Abb%22,%22ccc%22,%22fish%22,%22%22&a=1&m=1)
Unpacked, ungolfed, and commented, it looks like this.
```
_'"/ split *all* of standard input by double quote characters
2:: keep only the even numbered elements
|j split on newlines (implicitly concatenates array of "strings")
m for each line, execute the rest of the program and output
',#^ count the number of commas occurring as substrings, and increment
```
[Run this one](https://staxlang.xyz/#c=_%27%22%2F++%09split+*all*+of+standard+input+by+double+quote+characters%0A2%3A%3A+++%09keep+only+the+even+numbered+elements%0A%7Cj++++%09split+on+newlines+%28implicitly+concatenates+array+of+%22strings%22%29%0Am+++++%09for+each+line,+execute+the+rest+of+the+program+and+output%0A++%27,%23%5E%09count+the+number+of+commas+occurring+as+substrings,+and+increment&i=,%22Hello,+World%21%22%0A%22aaa%22,%22b%22%22bb%22,%22ccc%22%0Azzz,yyy,%0A%22aaa%22,%22b+%0Abb%22,%22ccc%22,%22fish%22,%22%22&a=1&m=1)
[Answer]
# [R](https://www.r-project.org/), 40 bytes
```
(x=count.fields(stdin(),","))[!is.na(x)]
```
[Try it online!](https://tio.run/##Pcq9CoAgGEbh3auwd1L48A7au4OGaPAnSRCFLEhv3pyazvCcq3fxzjY/6VY@HNEVUW4XkpAEgpTbFIpKWrxy74TliDETX/MV3QQGrfW4DGDMqLUWrLVGtVb6kbMfCT6UcwT9Aw "R – Try It Online")
Per the [documentation](https://stat.ethz.ch/R-manual/R-devel/library/utils/html/count.fields.html) of `count.fields`, fields with line breaks get a field count of NA for the initial line, so we filter them out.
[Answer]
# JavaScript (ES2018), ~~42~~ 59 bytes
```
s=>s.replace(/".+?"/sg).split`\n`.map(c=>c.split`,`.length)
```
```
f=
s=>s.replace(/".+?"/sg).split`\n`.map(c=>c.split`,`.length)
console.log(f(
`,"Hello, World!"
"aaa","b""bb","ccc"
zzz,yyy,
"aaa","b
bb","ccc","fish",""`))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṣ”"m2FỴ=”,§‘
```
A port of [recursive's Stax answer](https://codegolf.stackexchange.com/a/166582/53748) - go give credit!
**[Try it online!](https://tio.run/##y0rNyan8///hzsWPGuYq5Rq5Pdy9xRbI1Dm0/FHDjP///6urq@soeQBV5esohOcX5aQoKnEpJSYmKukoJekoKenoAImkJCAvOTlZiauqqkqnsrJSB65EgQsuqaOUllmcAaSUgGYCAA "Jelly – Try It Online")**
### How?
```
ṣ”"m2FỴ=”,§‘ - Link: list of characters, V
”" - a double quote character = '"'
ṣ - split (V) at ('"')
m2 - modulo slice with two (1st, 3rd, 5th, ... elements of that)
F - flatten list of lists to a list
Ỵ - split at newlines
”, - comma character = ','
= - equal? (vectorises)
§ - sum each
‘ - increment (vectorises)
- (as a full program implicit print)
```
---
Maybe you prefer [`ṣ”"m2ẎỴċ€”,‘`](https://tio.run/##y0rNyan8///hzsWPGuYq5Ro93NX3cPeWI92PmtYABXQeNcz4//@/urq6jpIHUGW@jkJ4flFOiqISl1JiYqKSjlKSjpKSjg6QSEoC8pKTk5W4qqqqdCorK3XgShS44JI6SmmZxRlASgloJgA) - `Ẏ` is tighten and `ċ€` counts the commas in each.
[Answer]
# Python, 63 bytes
```
import csv
def f(s):return map(len,csv.reader(s.split("\n"))
```
Returns the output in an iterable `map` object.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
Length/@ImportString[#,"CSV"]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98nNS@9JEPfwTO3IL@oJLikKDMvPVpZR8k5OEwpVu1/AJBf4pDmoKQTo@SRmpOTr6MQnl@Uk6IYo8QVo5SYmBgDkkmKUQISSWB2cnIyUK6qqkqnsrJSB1mRAheyEiCdllmcAWbEKCn9BwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/).10.0, ~~55~~ 53 bytes
```
$_=shift;s/"(""|[^"])*"//g;s/^.*$/1+$&=~y:,::/gem;say
```
[Try it online!](https://tio.run/##PcmxDoIwGEXhnafAm8YI/lIYWCDsLs4ORkzBAk2qJZSlxPjoViamLzlnlJPOvWePyg6qm0vLcQA@txr3KAbn/VrqJGY8O7J99XUFFQXv5au0wnnvCWeptaHwaib93CGAEAKEBmia1bZtESzLQs452mYYbJPQKTus4GfGWZm39adLnmRpkv4B "Perl 5 – Try It Online")
Explanation:
```
$_=shift; # first command-line arg
s/"(""|[^"])*"//g; # remove quoted fields
s/^.*$/ # replace each line
1+$&=~y:,:: # by the number of commas plus 1
/gem;
say # print
```
[Answer]
# Java 10, 101 bytes
```
s->{for(var p:s.replaceAll("\"[^\"]*\"","x").split("\n"))System.out.println(p.split(",",-1).length);}
```
[Try it online.](https://tio.run/##VVBNT8MwDL3zK4xPDUojcaUCiRsXdtmBwzKkNG23jCyNkqyinfrbi9sVJCRb/nrye/ZJdSo/VV@TtipGeFfGXe8AjEt1aJSuYTOXAF1rKtDZNgXjDhBZQd2RnCwmlYyGDTh4hinmL9emDVmnAvinKELtLe15tTZDibtPifsHicjxG5mI3ppEfYeMbfuY6rNoL0l4IknWZf4XwJHnj0zY2h3SkRXjVNyo/aW0RL0qWDSe6YJV5m4Pit3kO6Fpi8S32tqWw0cbbHUviViiUkrOo5JKLMsl13qeDcPA@77n/1HuD6OX2Jh4XBK6an3LOP0A)
**Explanation:**
```
s->{ // Method with String parameter and no return-type
for(var p:s.replaceAll("\"[^\"]*\"","x")
// Replace all words within quotes with an "x"
.split("\n")) // Then split by new-line and loop over them:
System.out.println(p.split(",",-1) // Split the item by comma's
.length);} // And print the length of this array
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
=”"ÄḂżṣ⁷ݤṣ€0,”,Ẉ
```
[Try it online!](https://tio.run/##y0rNyan8/9/2UcNcpcMtD3c0Hd3zcOfiR43bj@4@tATEalpjoAOU1Hm4q@P/4fajkx7unPH/v46SB1Bfvo5CeH5RToqiEpdSYmKiko5SkpJSUhKQTk5OVuKqqqrSqays1IFLKnDBJXWU0jKLM4CUEgA "Jelly – Try It Online")
-1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). *duh duh duh...*
[Answer]
# POSIX shell ([ShellShoccar-jpn/Parsrs](https://github.com/ShellShoccar-jpn/Parsrs) + [usp-engineers-community/Open-usp-tukubai](https://github.com/usp-engineers-community/Open-usp-Tukubai)), 19 bytes
Dependencies are
* [parsrc.sh `Version : 2017-07-18 02:39:39 JST`](https://github.com/ShellShoccar-jpn/Parsrs/blob/ac17529b4951333921ac14a7f201ddc2ecda1fd9/parsrc.sh)
* [count `Version : Fri Oct 21 11:26:06 JST 2011`](https://github.com/usp-engineers-community/Open-usp-Tukubai/blob/25f30c5fb0c315ae8de8c42608a56f68cd99ab6c/COMMANDS/count)
```
parsrc.sh|count 1 1
```
## Output format
For each line, the following line is output:
```
<row number> <number of columns>
```
## How it works
`parsrc.sh` is a parser for CSV who converts such text into list of cells and their value.
Open-usp-tukubai's `count` takes a range of field number from parameters and space-separated values to count in such range to summarize.
Here are some comments:
```
# raw CSV
parsrc.sh |
# 1: row number 2: column number 3: value where LFs are represented as "\n" while real backslashes as "\\"
count 1 1
# 1: row number 2: number of columns in the row
```
## Example run on Termux
Because Termux is not a completely POSIX-compatible so `command -p getconf PATH` fails, I am dropping the boilerplate to set PATH environment variable so the shell calls completely POSIX-compatible utilities first. Also because I am lazy to prepare Python 2, I am doing with COMMANDS.SH/count.
[](https://i.stack.imgur.com/WYmRQ.png)
] |
[Question]
[
In case you missed [Encode Factor Trees](https://codegolf.stackexchange.com/q/150144/62402), here is the definition of a Factor Tree:
>
> * The empty string is 1.
> * Concatenation represents multiplication.
> * A number *n* enclosed in parentheses (or any paired characters) represents the *n*th prime number, with 2 being the first prime number.
> + Note that this is done recursively: the *n*th prime is the factor tree for *n* in parentheses.
> * The factors of a number should be ordered from smallest to largest.
>
>
> For example, here are the factor trees for 2 through 10:
>
>
>
> ```
> ()
> (())
> ()()
> ((()))
> ()(())
> (()())
> ()()()
> (())(())
> ()((()))
>
> ```
>
>
This challenge uses a similar format; however, this challenge is to *decode* these structures.
# Test Cases
Shamelessly ~~stolen~~ *repurposed* from the last challenge.
In addition to the 9 above…
```
()()((()))((())) => 100
(()(()(()))) => 101
(()())(((())))(()(())) => 1001
(((((((()))))))) => 5381
(()())((((()))))(()()(())(())) => 32767
()()()()()()()()()()()()()()() => 32768
```
# Rules
* The paired characters in the input are your choice of parentheses, brackets, braces, or angle brackets. I may allow other formats (e.g. XML tags) if asked.
* You should be able to handle Factor Trees for any number from 2 to 215 or 32768.
* Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins.
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~52~~ 45 bytes
```
ToExpression@*StringReplace[{"["->"Prime[1"}]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVei4KCloPE/JN@1oqAotbg4Mz/PQSu4BCiTHpRakJOYnBpdrRStpGunBFSdmxptqFQb@19TQd9BoZpLQUEpOlZJB0hGx0LoWBgfKAATgcmBJOGqEPqQ9MJ0QQyGCaAKgw0EiyALgVWBBWGycEkIiIUCDD0QmWiIdbGxGE7ACZW4av8DAA "Wolfram Language (Mathematica) – Try It Online")
Input uses brackets.
Transforms the input into a Mathematica expression that computes the result. We do this simply by replacing `[` with `Prime[1`. This works because concatenation *is* multiplication in Mathematica.
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~134~~ ~~128~~ ~~127~~ 124 bytes
*This answer is part of a collaboration between myself and 0'. We both worked on this together, the only reason I'm posting it is because I won Rock, Paper, Scissors.*
```
\Q-->{Q=1};"(",\N,")",\B,{findnsols(N,I,(between(2,inf,I),\+ (between(3,I,U),0=:=I mod(U-1))),L)->append(_,[Y],L),Q is Y*B}.
```
[Try it online!](https://tio.run/##PY3BCoJAFEX3fsXg6r16I1m7YlxIGyEEFy5EJasZY8BmpAlciN9uA0Gbe@FwLnd828E@uZv0ujYF58lciHg5hRBSk1OIvlKae22kcXZwkFNGcFefSSkDe9Kmpwyp2bI/PHijRNqJo8jYy0ooeYyIdEGe3MZRGQlXqqvWAyqYdqzapEvk3@GsHlYq6gABwE9@2VHdYhQEXw "Prolog (SWI) – Try It Online")
## Explanation
This answer is a perfect exemplar of what makes golfing in prolog fun.
---
This answer uses Prologs powerful system for definite clause grammars. Here is our grammar ungolfed a bit.
```
head(1)-->[].
head(Q)-->"(",head(N),")",head(B),{prime(N,Y),Q is Y*B}.
isprime(I):- \+ (between(3,I,U),0 =:= I mod(U-1)).
prime(N,Y):-
findnsols(N,I,(
between(2,inf,I),
isprime(I)
),L),
append(_,[Y],L),!.
```
The first construction rule is:
```
head(1)-->[].
```
This tells Prolog that the empty string corresponds to 1.
Our second rule of construction is a tiny bit more complex.
```
head(Q)-->"(",head(N),")",head(B),{prime(N,Y),Q is Y*B}.
```
This tells us that any non empty string contains parentheses around a clause with these same rules, to the right of a clause with these same rules.
It also tells us that the value of this clause (`Q`) follows the rule:
```
{prime(N,Y),Q is Y*B}
```
Breaking this down, `Q` is the product of 2 numbers `Y` and `B`. `B` is just the value of the clause to the left and `Y` is the `N`th prime where `N` is the value of the clause inside the parentheses.
This rule covers both of the formation rules of the factor tree
* Concatenation multiplies
* Enclosure takes the nth prime
---
Now for the predicate definitions. In the ungolfed version there are two predicates at play (in my actual code I've forward chained the predicates away).
The two relevant predicates here are `isprime/1`, which matches a prime number, and `prime/2`, which, given `N` and `Y`, matches iff `Y` is the `N`th prime. First we have
```
isprime(I):- \+ (between(3,I,U),0 =:= I mod(U-1)).
```
This works of a pretty standard definition of primality, we insist that there is no number between 2 and `I`, including 2 but not `I` that divides `I`.
The next predicate is also pretty simple
```
prime(N,Y):-
findnsols(N,I,(
between(2,inf,I),
isprime(I)
),L),
append(_,[Y],L),!.
```
We use `findnsols` to find the first `N` numbers that are prime, we then return the last one. The trick here is that while `findnsols` is not guaranteed to find the *smallest* `N` primes, because of the way SWI handles `between` it will always find smaller primes sooner. This however means we have to cut to prevent it from finding more primes.
---
### The golfs
We can forward reason in our code twice. Since `isprime` is only used once its definition can be moved inside of `prime`. The next one is to move `prime` directly inside of the DCG, however since we use a cut in `prime` to prevent `findnsols` from producing too many primes we have a bit of an issue. The cut, cuts the entire DCG instead of just the bit we want. After a bit of documentation digging we found that `once/1` could be used to cut just this portion but not the entire DCG. However more documentation digging revealed that the `->` operator could also be used to perform a similar task. The `->` operator is roughly equivalent to `,!,` so we moved our cut to the other side of `append/3` and replaced it with `->`.
In SWI-Prolog predicates (and rules) can be give operators as names which allows us to drop the parentheses normally required. Thereby we can save 6 bytes by calling the rule `\`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~125~~ 110 bytes
```
lambda s:eval(s.replace("]","1]*").replace("[","p[1*")+"1")
p=2,
k=P=1
while k<1e4:
if P%k:p+=k,
P*=k*k;k+=1
```
[Try it online!](https://tio.run/##fY7LCsIwEEX3@YohIOkjCFFX1fgN3cdZVE1pSG1DUxS/vsa2vjbOhYF77gwz7t5XbbMeSnkY6uJyPBfgM30t6sgvO@3q4qQjipRTgQmNP0gF5JQILKWCxsTJFSdW5lKQW2VqDXYn9CYjYErIFzZzqbScQJ5Im9itTaUYyrYDD6YBxRQGKYU4d8aBqSfC0b79mI/kFU3JVDjX7/SE1XQCv7bwnxiG311nmj7yHKjcUw5l5ON4eAA "Python 3 – Try It Online")
Uses [xnor's implementation](https://codegolf.stackexchange.com/a/27022) of the Wilson Theorem method to generate primes. Substitutes `()` with `[]`.
[Answer]
# JavaScript (ES6), 98 bytes
Inspired by [notjagan's Python answer](https://codegolf.stackexchange.com/a/150499/58563). Turns the input expression into a huge and ugly executable string.
```
s=>eval(s.split`)(`.join`)*(`.split`(`.join`(g=(n,k)=>(C=d=>n%--d?C(d):k-=d<2)(++n)?g(n,k):n)(1,`)
```
Merging the `C` and `g` functions into a single one may save some bytes, but it would require even more recursion.
### Test cases
```
let f =
s=>eval(s.split`)(`.join`)*(`.split`(`.join`(g=(n,k)=>(C=d=>n%--d?C(d):k-=d<2)(++n)?g(n,k):n)(1,`)
;[
"()", // 2
"(())", // 3
"()()", // 4
"((()))", // 5
"()(())", // 6
"(()())", // 7
"()()()", // 8
"(())(())", // 9
"()((()))", // 10
"()()((()))((()))", // 100
"(()(()(())))", // 101
"(()())(((())))(()(()))", // 1001
"(((((((())))))))", // 5381
"(()())((((()))))(()()(())(()))", // 32767
"()()()()()()()()()()()()()()()" // 32768
]
.forEach(s => console.log(s, '-->', f(s)))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
OḂ;ṪÆN×ṪƲ1ṛ?¥ƒ1
```
[Try it online!](https://tio.run/##y0rNyan8/9//4Y4m64c7Vx1u8zs8HUgf22T4cOds@0NLj00y/P9w95bD7Y@a1kT@/6@hyaWhoQkkNMEsIBPMBguBxCAyUFUwlXBlUCZMAKwRzIbp1oBIwcVBVmjABNHUQcQ0IMZqaiJZghMCAA "Jelly – Try It Online")
```
OḂ Codepoints odd or even? ('(' -> 0, ')' -> 1)
ƒ Reduce starting from
1 one (implicitly treated as a singleton list):
; ¥ append:
Ʋ ṛ? if right argument (is parenthesis closing?):
Ṫ pop last element from left argument,
ÆN get nth prime,
Ṫ pop the next last element
× and multiply.
Else:
1 1.
```
Essentially interprets a stack language where `(` means "push 1" and `)` means "pop n, multiply top of stack by n-th prime", starting with a stack containing a single 1, outputting the single remaining stack item at the end.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~12~~ 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ÄKWα╛⌠ï_☻!■
```
[Run and debug it](https://staxlang.xyz/#p=8e4b57e0bef48b5f0221fe&i=%28%29%0A%28%28%29%29%0A%28%29%28%29%0A%28%28%28%29%29%29%0A%28%29%28%28%29%29%0A%28%28%29%28%29%29%0A%28%29%28%29%28%29%0A%28%28%29%29%28%28%29%29%0A%28%29%28%28%28%29%29%29%0A%28%29%28%29%28%28%28%29%29%29%28%28%28%29%29%29%0A%28%28%29%28%28%29%28%28%29%29%29%29%0A%28%28%29%28%29%29%28%28%28%28%29%29%29%29%28%28%29%28%28%29%29%29%0A%28%28%28%28%28%28%28%28%29%29%29%29%29%29%29%29%0A%28%28%29%28%29%29%28%28%28%28%28%29%29%29%29%29%28%28%29%28%29%28%28%29%29%28%28%29%29%29%0A%28%29%28%29%28%29%28%29%28%29%28%29%28%29%28%29%28%29%28%29%28%29%28%29%28%29%28%29%28%29&m=2)
-1 thanks to Razetime
Translation of my Jelly answer. I felt I ought to try this in a stack-based language. First choice was 05AB1E, but I couldn't quite figure out `i`...
```
O+k|e1{v|6*}? Unpacked representation
O+ Prepend 1 to the input. (strings = codepoint lists, mostly)
k Reduce that array by the rest of the program:
|e Even? ('(' -> 0, ')' -> 1)
? If so,
1 push 1, else
{ } perform:
v decrement,
|6 0-indexed nth prime,
* multiply.
```
The way Stax's reduce operates on the stack is by pushing the first element of the top of the stack, then for each remaining element pushing that and evaluating the block it closes (which is the entire program if there is no block to close). Unfortunately, there doesn't seem to be any alternative which skips the special treatment for the first element--preferably after performing `s`--but there is a builtin for "tuck 1 under top of stack", so it works out anyways.
] |
[Question]
[
[\*What is a transmogrifier?](http://calvinandhobbes.wikia.com/wiki/Transmogrifier)
In the [C programming language](https://en.wikipedia.org/wiki/C_(programming_language)), there are formations called [digraphs and trigraphs](https://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C) that are two and three characters sequences that evaluate to less common characters. For example, you can use `??-` if your keyboard doesn't have `~`.
Given text, replace all instances of the following digraphs and trigraphs (left side) with the correct, shorter, golfed character (right side).
```
??= #
??/ \
??' ^
??( [
??) ]
??! |
??< {
??> }
??- ~
<: [
:> ]
<% {
%> }
%: #
```
[Source](https://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C)
# Input
Input is ASCII text. Trailing newline allowed. Does not need to be valid C code.
# Output
Output is the same text, with all instances of the above digraphs and trigraphs replaced with the shortened version, evaluated left to right. Trailing newline allowed. Does not need to be valid C code.
# Test Cases
`=>` separates input and output.
```
if (true ??!??! false) { => if (true || false) {
??-arr.indexOf(n) => ~arr.indexOf(n)
function f(??) { console.log('test??'); } => function f(] { console.log('test^); }
/* comment :> :) *??/ => /* comment ] :) *\
%:What am I doing??!!??` => `#What am I doing|!??
??(??)??(??) <:-- not a palindrome => [][] [-- not a palindrome
?????????? => ??????????
int f(int??(??) a) ??< return a??(0??)??'a??(1??) + "??/n"; ??> => int f(int[] a) { return a[0]^a[1] + "\n"; }
??<:>??<% => {]{%
<:> => [>
<::> => []
:>> => ]>
#\^[]|{}~ => #\^[]|{}~
: > => : >
??=%: => ##
```
[Answer]
# C, ~~206~~ 205 bytes
(-1 thanks to ceilingcat)
The newlines are just here for readability.
```
c,d,q;f(char*s){for(char*S,*T,*t=s;c-63?q=0:q++,d=c<<8|*s,*s?
q>1&&(T=index(S="=/'()!<>-",*s))?t-=2,*s="#\\^[]|{}~"[T-S]:
d>*s&&(T=strstr(S=">:<>%<:%",&d))&&(c="][ }{ # "[T-S])&1?--t,*s=c:0:
0,*t++=c=*s++;);}
```
Modifies `s` in place. Tested with GCC and clang on Fedora Workstation, x86, in 32-bit and 64-bit mode.
C is not exactly the best language for golfing here.
[Answer]
# [Retina](https://github.com/m-ender/retina), 65 bytes
```
T`-=/'()!<>?`~#\\^[]|{}_`\?\?[-=/'()!<>]
<:
[
:>
]
<%
{
>%
}
%:
#
```
[Try it online!](https://tio.run/nexus/retina#PZBBb4MwDIXv/hVuEYJ0oqzXlMXnnXaZtEPpRtSGDgmSKQRpEqN/nZmtW5Q8WfHL@yLPz1X2kCepWBWKqmtUlq@H49c4vVUllXT47x2hkHAAqYCrGEZQMUwQS4jmuakxDX4wSLTijbVueyNwBKJMe79t7Nl8PtWpFVAP9hQaZ7FOidiCJ2d715pt6y5pEkwfiBKxxwnyDfe6ztiAUqEUuCHKGfjyrgPqDh/x7Bp7YR4zmbTk/SoWMsvQOrbhh26Z7l1n2PK3oOHQOmW9PdCCv16gN2HwFjXf3v@kJUu5Wxx3uGa8Xe/ZqDiqkIol5qEoPixSKYhus7uCRPUN "Retina – TIO Nexus") `T` is a little awkward to use but still saves me 14 bytes.
[Answer]
## JavaScript (ES6), 106 bytes
```
s=>[...'#\\^[]|{}~[]{}#'].map((c,i)=>s=s.split('<:<%%'[i-9]+':>%>:'[i-9]||'??'+"=/'()!<>-"[i]).join(c))&&s
```
### How?
This is pretty straightforward.
We should note however that:
* When **i** is less than **9**, the expression `'<:<%%'[i-9] + ':>%>:'[i-9]` evaluates to `undefined + undefined` which equals `NaN` (falsy as expected).
* When **i** is greater than or equal to **9**, the expression `'??' + "=/'()!<>-"[i]` evaluates to `"??" + undefined` which is coerced to the string `"??undefined"` (truthy when we expect a falsy result).
That's why we must process the test in this order.
### Test cases
```
let f =
s=>[...'#\\^[]|{}~[]{}#'].map((c,i)=>s=s.split('<:<%%'[i-9]+':>%>:'[i-9]||'??'+"=/'()!<>-"[i]).join(c))&&s
console.log(f(`if (true ??!??! false) {`)) // `if (true || false) {`
console.log(f(`??-arr.indexOf(n)`)) // `~arr.indexOf(n)`
console.log(f(`function f(??) { console.log('test??'); }`)) // `function f(] { console.log('test^); }`
console.log(f(`/* comment :> :) *??/`)) // `/* comment ] :) *\`
console.log(f(`%:What am I doing??!!??`)) // `#What am I doing|!??`
console.log(f(`??(??)??(??) <:-- not a palindrome`)) // `[][] [-- not a palindrome`
console.log(f(`??????????`)) // `??????????`
console.log(f(`int f(int??(??) a) ??< return a??(0??)??'a??(1??) + "??/n"; ??>`)) // `int f(int[] a) { return a[0]^a[1] + "\n"; }`
console.log(f(`??<:>??<%`)) // `{]{%`
console.log(f(`<:>`)) // `[>`
console.log(f(`<::>`)) // `[]`
console.log(f(`:>>`)) // `]>`
console.log(f(`#\^[]|{}~`)) // `#\^[]|{}~`
console.log(f(`: >`)) // `: >`
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 104+1 = 105 bytes
Uses the `-p` flag for +1 byte.
```
"=#/\\'^([)]!|<{>}-~".scan(/(.)(.)/){|k,v|gsub'??'+k,v}
"<:[:>]<%{%>}%:#".scan(/(..)(.)/){|k,v|gsub k,v}
```
[Try it online!](https://tio.run/nexus/ruby#ZU5Lc4MgEL7zKzY6jpBUba/EwrmnHnswyQwxaJ0qZBA77aj56@nax@RQZvmA5XtsuHLD8ROS8zV4DLPdLj7Qgu1XUz6KObkEaV8qQzOaMqyMjdPb3ftU98MxljLe4GMmQc4LLvZ5NEZijnh40/wTwSK4XpsKqHeDBilXWFCpttcMRiJlopxLG3PSH88VNYxUgyl9Yw1UVEqkQGlNb1udtramsde9xznYFmaSrfGv67TxwAVwBmspMxLxl1flQXXwBCfbmBrzMBOTFr8fhJwnCRiLNDirFtOd7TRS/hZp0LSiiL8CxXD0HJz2gzOgsHv/7RYv14eFsYEA402wRaJAq5wLhIjgiRuBC0HC3aHYT@N8IRzEFw "Ruby – TIO Nexus")
[Answer]
# Javascript (ES6), 131 123 bytes
```
f=
s=>"#??= \\??/ ^??' [??( ]??) |??! {??< {??> ~??- [<: ]:> {<% }%> #%:".split` `.map(x=>s=s.split(x.slice(1)).join(x[0]))&&s
```
```
<input oninput=console.log(f(this.value))>
```
[Answer]
# PHP , 112 Bytes
```
<?=str_replace(explode(_,strtr("<:_:>_<%_%>_%:0=0/0'0(0)0!0<0>0-",["_??"])),str_split("[]{}##\\^[]|{}~"),$argn);
```
[Try it online!](https://tio.run/nexus/php#Hc5LCoMwFEbheXdhbDABxTtOb/IvRO1FWmkL0obooGDt1u1jeuCDw4jXuNv36XL3CvBADRSAASyQAQwEoGLnAmsdtFMHhI3hpzlJGuLYnwYzPOP4OA9Gym@dk1HsxAVhLTqIduSppoIMWcqIKVClykYJoDprf0SmON5mo5puWfO8bY9N91rWt7Ll/8wetu0D "PHP – TIO Nexus")
## PHP , 115 Bytes
```
<?=str_replace(explode(_,"??=_??/_??'_??(_??)_??!_??<_??>_??-_<:_:>_<%_%>_%:"),str_split("#\\^[]|{}~[]{}#"),$argn);
```
[Try it online!](https://tio.run/nexus/php#Hc7BCoJAFIXhfW@hNjgDSvvxes@DqF2khgqkBnURmL26XVt8qwM/hxDv8XDsx9uzToEaOAE5YAEHJAABDJTkPZMxbHxagTdCPc2jjCEO/SXY8I7D6xqsFHtDNKJyZZVTiSLFqhTy4lnIiGHRoCv21hSHx2zTrG3PTfdZ1m/TLWum4/@cq7btBw "PHP – TIO Nexus")
## PHP , 124 Bytes
Regex solution
```
foreach(explode(_,"=|%:_/_'_\(|<:_\)|:>_!_<|<%_>|%>_-")as$v)$a=preg_replace("#\?\?$v#","#\\^[]|{}~"[$k++],$a=&$argn);echo$a;
```
[Try it online!](https://tio.run/nexus/php#Hc7RDoIgGIbh8@5CgoRp6xyB70LE/jEj3XLJbGttUbdurrP34Dl4DdKYdjwsw90ywAInoAQkoIACMIADjkZrZ4RwQrNmvc5LDP0o4ytN8yVKqpnNQtOJSvIyG01eZe2oIJONIJeFoyNT4cGfigebljjQEtMU@ijZ3sODP/es3tKf2y6/P1/W8ltVdfWmD/851cR@nHlo1vUH "PHP – TIO Nexus")
[Answer]
## JavaScript (ES6), 113 bytes
```
s=>s.replace(/\?\?[^:%?]|[<:%]./g,c=>"#\\^[]|{}~"["=/'()!<>-".indexOf(c[2])]||"[] {} #"["<:><%>%:".indexOf(c)]||c)
```
Not the shortest, but I wanted to try a different approach.
] |
[Question]
[
**This question already has answers here**:
[Case Permutation](/questions/80995/case-permutation)
(24 answers)
Closed 6 years ago.
Here's a scenario:
A grandmother and grandfather forget what their GMail password is. They know the word, but can't remember which letters are capitals.
The challenge is to take a word given and print(stdout) every combination of capital letters possible, essentially "brute-forcing" but only on a given string.
## Example:
`and` would output
```
and
anD
aNd
aND
And
AnD
ANd
AND
```
## Example:
`ea!` would output
```
ea!
Ea!
EA!
eA!
```
## Rules
* ASCII characters only
* Input doesn't have to be lowercase
* The order is not important
* Non-alphabetic chars are left alone
* [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* Any form of input is allowed
* Repetition is ***NOT*** allowed
## Leaderboard Snippet:
```
function answersUrl(a){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(a,b){return"https://api.stackexchange.com/2.2/answers/"+b.join(";")+"/comments?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(a){answers.push.apply(answers,a.items),answers_hash=[],answer_ids=[],a.items.forEach(function(a){a.comments=[];var b=+a.share_link.match(/\d+/);answer_ids.push(b),answers_hash[b]=a}),a.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(a){a.items.forEach(function(a){a.owner.user_id===OVERRIDE_USER&&answers_hash[a.post_id].comments.push(a)}),a.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(a){return a.owner.display_name}function process(){var a=[];answers.forEach(function(b){var c=b.body;b.comments.forEach(function(a){OVERRIDE_REG.test(a.body)&&(c="<h1>"+a.body.replace(OVERRIDE_REG,"")+"</h1>")});var d=c.match(SCORE_REG);d&&a.push({user:getAuthorName(b),size:+d[2],language:d[1],link:b.share_link})}),a.sort(function(a,b){var c=a.size,d=b.size;return c-d});var b={},c=1,d=null,e=1;a.forEach(function(a){a.size!=d&&(e=c),d=a.size,++c;var f=jQuery("#answer-template").html();f=f.replace("{{PLACE}}",e+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link),f=jQuery(f),jQuery("#answers").append(f);var g=a.language;/<a/.test(g)&&(g=jQuery(g).text()),b[g]=b[g]||{lang:a.language,user:a.user,size:a.size,link:a.link}});var f=[];for(var g in b)b.hasOwnProperty(g)&&f.push(b[g]);f.sort(function(a,b){return a.lang>b.lang?1:a.lang<b.lang?-1:0});for(var h=0;h<f.length;++h){var i=jQuery("#language-template").html(),g=f[h];i=i.replace("{{LANGUAGE}}",g.lang).replace("{{NAME}}",g.user).replace("{{SIZE}}",g.size).replace("{{LINK}}",g.link),i=jQuery(i),jQuery("#languages").append(i)}}var QUESTION_ID=110455,OVERRIDE_USER=8478,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align: left!important; font-family: sans-serif}#answer-list,#language-list{padding: 10px; width: 290px; float: left}table thead{font-weight: 700}table td{padding: 5px; margin: 0}table tr:nth-child(even){background: #eee}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr> <td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr> <td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr> <td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr> <td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
żŒsŒpQY
```
[Try it online!](https://tio.run/nexus/jelly#@390z9FJxUcnFQRG/v//Xz0xr7g8tcjWxEgdAA "Jelly – TIO Nexus")
### How it works
```
żŒsŒpQY Main link. Argument: s (string)
Œs Yield s with swapped case.
ż Zip s with the result, creating an array of character pairs.
Œp Take the Cartesian product.
Y Join, separating by linefeeds.
Q Unique; deduplicate the result.
```
[Answer]
# Bash + GNU utils, 38
```
eval echo `sed 's/[a-z]/{\l&,\u&}/gi'`
```
[Try it online](https://tio.run/nexus/bash#S8svUihJLS5JTixOVcjMU1BPzEtRV1BPTVRUt1ZIyedSAILU5Ix8BSUVmDIlhRqFmP@pZYk5EJmE4tQUBfVi/ehE3apY/eqYHDWdmFK1Wv30TPWE/yn5ean/AQ).
The sed expression replaces every letter with `{<LOWER>,<UPPER>}`, where `<LOWER>` and `<UPPER>` are respectively the lower- and upper- case versions of that letter. These are bash brace expansions which are then expanded - the `eval` ensures this is the last expansion to happen.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes
```
!tYohZ}&Z*Xu
```
[Try it online!](https://tio.run/nexus/matl#@69YEpmfEVWrFqUVUfr/v7proqI6AA "MATL – TIO Nexus")
Same idea as Dennis, only less neat, with Luis Mendo's suggestion.
[Answer]
## JavaScript (ES6), ~~99~~ 97 bytes
Returns a space-separated list of words.
```
f=(s,i)=>--i<1?'':s.replace(/[a-z]/gi,c=>c[`to${i&n?'Upp':'Low'}erCase`](n*=2),n=1)+' '+f(s,i||n)
```
### Test cases
```
f=(s,i)=>--i<1?'':s.replace(/[a-z]/gi,c=>c[`to${i&n?'Upp':'Low'}erCase`](n*=2),n=1)+' '+f(s,i||n)
console.log(f("and"))
console.log(f("ea!"))
```
[Answer]
# PHP, ~~115~~ ~~101~~ ~~99~~ ~~102~~ 101 bytes
saved 14 bytes thanks @user63956.
```
function f($b,$a="
"){$b&a?f($c=substr($b,1),$a.$d=$b[0])|ctype_alpha($d^=" ")&&f($c,$a.$d):print$a;}
```
recursive function, prints the results with a leading newline
**breadown**
```
function f($b,$a="\n") // $b=remaining input, $a= prepared output
{
// while $b is not empty
$b&a # this is not a typo!
// recurse with $d(=first char of $b) appended to $a
?f($c=substr($b,1),$a.$d=$b[0])
// if $d is letter, recurse with $d (case toggled) appended to $a
|ctype_alpha($d)&&f($c,$a.$d^=" ")
// if $b is empty, print $a
:print$a;
}
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 95 bytes (non-recursive)
```
s=${1,,}$'
'
s[1]=${s^^}
for((n=${#s};z<n*2**n;)){ echo -n "${s[z/n>>z%n&1]:z++%n:1}";}|sort -u
```
[Try it online!](https://tio.run/nexus/bash#DcpLDkAwEADQfU/R@KuK1FJxESFBiNU0MWxac/bq8iXP45A4JSUlOcsZTmoOxmUhdpq7KCAoRtK2B9EKAbosHT/2y/AaeBTmZBsYR5tCpubOVlUKnaJI04fmfnj9eu/dKjf6AQ "Bash – TIO Nexus")
*Note: This solution and the recursive solution below both require bash 4; the ${x,,} and ${x^^} constructs weren't available in bash 3.*
This is quite a bit longer than @DigitalTrauma's solution, but I think it works on all strings, even if they have special characters in them. For example, with input
```
{a,b}
```
this program outputs
```
{A,B}
{A,b}
{a,B}
{a,b}
```
as it should. (@DigitalTrauma's solution, although very ingenious, doesn't work for this input and other similar inputs.)
---
---
# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 88 bytes (recursive)
```
[ "$1" ]&&(c=${1:0:1};sed "h;s/^/${c,,}/;p;g;s/^/${c^^}/"<<<`$0 "${1:1}"`|sort -u)||echo
```
This recursive solution works on input `{a,b}` but it has problems with other special characters, for example, input `a/b`.
[Answer]
## C ~~247~~ 229 bytes
```
i,n,j,k,l;f(char *s){l=strlen(s);for(i=0;i<l;i++)s[i]=tolower(s[i]);int v[l];for(i=0;i<pow(2,l);i++){n=i,k=0;for(;n;k++){v[k]=n;n/=2;}for(j=0;j<l;j++){v[j]%=2;if(v[j])s[j]=toupper(s[j]);else s[j]=tolower(s[j]);}printf("%s ",s);}}
```
Ungolfed version:
```
void f(char *s)
{
int i,num,k,l=strlen(s);
for(int i=0;i<l;i++)
s[i]=tolower(s[i]);
int v[l];
for(i=0;i<pow(2,l);i++)
{
num=i,k=0;
for(;num;k++)
{
v[k]=num;
num/=2;
}
for(int j=0;j<l;j++)
{
v[j]%=2;
if(v[j])
s[j]=toupper(s[j]);
else
s[j]=tolower(s[j]);
}
printf("%s \n",s);
}
}
```
Explanation:
* Accept the character string, convert the string to lowercase.
* Declare integer array of length equal to that of the string.
* Store the numbers from 0 to `2^strlen(s)`in binary form in an `int` array.( For a 3 byte string: 000,001,010...111)
* Depending on if a bit at a position is set or, toggle the case.
* Output the string for every possible combination.
[Answer]
## JavaScript (Firefox 30-57), 92 bytes
```
f=([c,...a])=>c?[for(l of new Set([c.toLowerCase(),c.toUpperCase()]))for(r of f(a))l+r]:['']
```
Accepts a string or array of characters and returns an array of strings.
] |
[Question]
[
## Background
The [metallic means](https://en.wikipedia.org/wiki/Metallic_mean), starting with the famous [golden mean](https://en.wikipedia.org/wiki/Golden_ratio), are defined for every natural number (positive integer), and each one is an irrational constant (it has an infinite non-recurring decimal expansion).
For a natural number , the  metallic mean is the root of a quadratic equation 
The roots are always

but the metallic mean is usually given as the positive root. So for this question it will be defined by:

For  the result is the famous golden ratio:

---
## Challenge
Your code should take 2 inputs: n and p *(the order is not important as long as it is consistent)*
* n is a natural number indicating which metallic mean
* p is a natural number indicating how many decimal places of precision
Your code should output the nth metallic mean to p decimal places precision.
### Validity
Your code is valid if it works for values of n and p from 1 to 65,535.
You must output a decimal in the form
digit(s).digit(s) (without spaces)
For example, the golden mean to 9 decimal places is
1.618033988
Display the last digit without rounding, as it would appear in a longer decimal expansion. The next digit in the golden mean is a 7, but the final 8 in the example should not be rounded up to a 9.
The number of decimal digits must be p, which means any trailing zeroes must also be included.
Answers of the form

are not valid - you must use a decimal expansion.
You may output up to 1 leading newline and up to 1 trailing newline. You may not output any spaces, or any other characters besides digits and the single point/full stop/period.
## Score
This is standard code golf: your score is the number of bytes in your code.
---
# Leaderboard
*(Using [Martin's leaderboard snippet](http://meta.codegolf.stackexchange.com/questions/5139/leaderboard-snippet))*
```
var QUESTION_ID=52493;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>
```
[Answer]
# dc, 12
```
?kdd*4+v+2/p
```
* `?` Push n and p onto the stack
* `k` set precision to p
* `dd` duplicate n twice (total three copies)
* `*` multiply n\*n
* `4+` add 4
* `v` take square root
* `+` add n (last copy on stack)
* `2/` divide by 2
* `p` print
### Testcase:
```
$ dc -f metalmean.dc <<< "1 9"
1.618033988
$
```
[Answer]
# R, 116 bytes
```
library(Rmpfr);s=scan();n=mpfr(s[1],1e6);r=(n+(4+n^2)^.5)/2;t=toString(format(r,s[2]+2));cat(substr(t,1,nchar(t)-1))
```
This reads two integers from STDIN and prints the result to STDOUT. You can [try it online](http://www.r-fiddle.org/#/fiddle?id=nDZLCRyq).
Ungolfed + explanation:
```
# Import the Rmpfr library for arbitrary precision floating point arithmetic
library(Rmpfr)
# Read two integers from STDIN
s <- scan()
# Set n equal to the first input as an mpfr object with 1e6 bits of precision
n <- mpfr(s[1], 1e6)
# Compute the result using the basic formula
r <- (n + sqrt(4 + n^2)) / 2
# Get the rounded string representation of r with 1 more digit than necessary
t <- toString(format(r, s[2] + 2))
# Print the result with p unrounded digits
cat(substr(t, 1, nchar(t) - 1))
```
If you don't have the `Rmpfr` library installed, you can `install.packages("Rmpfr")` and all of your dreams will come true.
[Answer]
# Mathematica, 50 bytes
```
SetAccuracy[Floor[(#+Sqrt[4+#^2])/2,10^-#2],#2+1]&
```
Defines an anonymous function that takes `n` and `p` in order. I use `Floor` to prevent rounding with `SetAccuracy`, which I need in order to get decimal output.
[Answer]
# CJam, 35 bytes
```
1'el+~1$*_2#2$2#4*+mQ+2/1$md@+s0'.t
```
Reads **p** first, then **n**.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=1'el%2B~1%24*_2%232%242%234*%2BmQ%2B2%2F1%24md%40%2Bs0'.t&input=19%201).
### How it works
We simply compute the formula from the question for **n × 10p**, get the integer and fractional part of the result divided by **10p**, pad the fractional part with leading zeroes to obtain **p** digits and print the parts separated by a dot.
```
1'e e# Push 1 and 'e'.
l+ e# Read a line from STDIN and prepend the 'e'.
~ e# Evaluate. This pushes 10**p (e.g., 1e3 -> 1000) and n.
1$* e# Copy 10**p and multiply it with n.
_2# e# Copy n * 10**p and square it.
2$ e# Copy 10**p.
2#4* e# Square and multiply by 4.
+ e# Add (n * 10**p)**2 and 4 * 10**2p.
mQ e# Push the integer part of the square root.
+2/ e# Add to n * 10**p and divide by 2.
1$md e# Perform modular division by 10**p.
@+s e# Add 10**p to the fractional part and convert to string.
0'.t e# Replace the first character ('1') by a dot.
```
[Answer]
# Python 2, 92 Bytes
As I am now looking at the answers, it looks like the CJam answer uses the same basic method as this. It calculates the answer for `n*10**p` and then adds in the decimal point. It is incredibly inefficient due to the way it calculates the integer part of the square root (just adding 1 until it gets there).
```
n,p=input()
e=10**p;r=0
while(n*n+4)*e*e>r*r:r+=1
s=str((n*e+r-1)/2);print s[:-p]+'.'+s[-p:]
```
[Answer]
# PHP, 85 78 bytes
```
echo bcdiv(bcadd($n=$argv[bcscale($argv[2])],bcsqrt(bcadd(4,bcpow($n,2)))),2);
```
It uses the [BC Math](http://php.net/manual/en/book.bc.php) mathematical extension which, on some systems, could not be available. It needs to be included on the [compilation time](http://php.net/manual/en/bc.installation.php) by specifying the `--enable-bcmath` command line option. It is always available on Windows and it seems it is included in the PHP version bundled with OSX too.
**Update**:
I applied all the hacks suggested by @blackhole in their comments (thank you!) then I squeezed the initialization of `$n` into its first use (3 more bytes saved) and now the code fits in a single line in the code box above.
[Answer]
# J, 27 Bytes
```
4 :'}:":!.(2+x)-:y+%:4+*:y'
```
### Explanation:
```
4 :' ' | Define an explicit dyad
*:y | Square y
4+ | Add 4
%: | Square root
y+ | Add y
-: | Half
":!.(2+x) | Set print precision to 2+x
}: | Remove last digit, to fix rounding
```
Call it like this:
```
9 (4 :'}:":!.(2+x)-:y+%:4+*:y') 1
1.618033988
```
Another, slightly cooler solution:
```
4 :'}:":!.(2+x){.>{:p._1,1,~-y'
```
Which calculates the roots of the polynomial x^2 - nx - 1. Unfortunately, the way J formats the result makes retreving the desired root slightly longer.
] |
[Question]
[
Ok, my first golf question. Please be gentle :) I know there's way too many ascii puzzles :P but here we go.
The task is simple, use your favorite programming language to print a triangle ripple. The input should be the size of the ripple.
Each triangle is evenly spaced out. Basically, you keep adding the triangles until there is not enough space for the smallest triangle.
You are allowed white spaces anywhere you want as long as the ripples are the same as the example with the correct size.
# Example
```
q)g 1
__
\/
q)g 2
____
\ /
\/
q)g 3
______
\ /
\ /
\/
q)g 4
________
\ __ /
\ \/ /
\ /
\/
q)g 5
__________
\ ____ /
\ \ / /
\ \/ /
\ /
\/
q)g 6
____________
\ ______ /
\ \ / /
\ \ / /
\ \/ /
\ /
\/
q)g 7
______________
\ ________ /
\ \ __ / /
\ \ \/ / /
\ \ / /
\ \/ /
\ /
\/
q)g 8
________________
\ __________ /
\ \ ____ / /
\ \ \ / / /
\ \ \/ / /
\ \ / /
\ \/ /
\ /
\/
```
As usual, shortest code wins :)
[Answer]
# GNU sed -nr, 210
A start:
```
s/1/__/g
p
s#_(.*)_#\\\1/#
s#\\__#\\ #
s#__/# /#
ta
:a
p
s#(.*) _{6}(_*) # \1\\ \2 /#;ta
s#(.*) ( )# \1\2#;
s#(.*) _(_*)_ # \1\\\2/#
y/_/ /
Tc
:b
p
:c
s#(.*)((\\) ( *)(/)|()()()\\/)# \1\3\4\5#;tb
```
Input is a positive unary integer via STDIN, as per [this meta-question](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary).
### Output:
```
$ for i in 1 11 111 1111 11111 111111 1111111; do sed -rnf triripple.sed <<< $i; done
__
\/
____
\ /
\/
______
\ /
\ /
\/
________
\ __ /
\ \/ /
\ /
\/
__________
\ ____ /
\ \ / /
\ \/ /
\ /
\/
____________
\ ______ /
\ \ / /
\ \ / /
\ \/ /
\ /
\/
______________
\ ________ /
\ \ __ / /
\ \ \/ / /
\ \ / /
\ \/ /
\ /
\/
$
```
[Answer]
# Pyth, 31 bytes
```
VhQ+J<t+++*Nd*N"\ "d*Q\_Q_XJ"\/
```
[Demonstration.](https://pyth.herokuapp.com/?code=VhQ%2BJ%3Ct%2B%2B%2B*Nd*N%22%5C%20%22d*Q%5C_Q_XJ%22%5C%2F&input=9&debug=0)
Explanation:
```
VhQ+J<t+++*Nd*N"\ "d*Q\_Q_XJ"\/
Implicit: Q = eval(input()), d = ' '
VhQ for N in range(Q + 1):
Concatenate:
*Nd N spaces
+ *N"\ " N of the string "\ "
+ d another space
+ *Q\_ Q of the string "_"
If N = 2 and Q = 7, the string so far is:
" \ \ _______" and we want
" \ \ _" as the left half.
t Remove the first character.
< Q Take the first Q characters remaining.
This is the left half of the triangle ripple.
J Store it in J.
XJ"\/ Translate \ to / in J.
_ Reverse it.
+ Concatenate the left and right halves and print.
```
[Answer]
# C, 165 bytes
```
n,x,y,b,c;main(c,v)char**v;{for(n=atoi(v[1]);y<=n;++y){for(x=-n;x<n;++x){b=2*n-abs(2*x+1);c=b-2*y+2;b-=6*y;putchar(b>0?95:b<-4&c>0&c%4==1?"/\\"[x<0]:32);}puts("");}}
```
Before the golfing steps that destroy readability:
```
#include <stdio.h>
#include <stdlib.h>
int main(int c, char** v) {
int n = atoi(v[1]);
for (int y = 0; y <= n; ++y) {
for (int x = -n; x < n; ++x) {
int b = 2 * n - abs(2 * x + 1);
int c = b - 2 * y + 2;
b -= 6 * y;
putchar(b > 0 ? 95 :
b < -4 && c > 0 && c % 4 == 1 ? "/\\"[x<0] : 32);
}
puts("");
}
}
```
This loops over all characters in the rectangle containing the figure, and evaluates the line equations that separate the inside of the triangle from the outside, as well as the ones that separate the different parts of the triangle.
[Answer]
# [Retina](https://github.com/mbuettner/retina), 182 bytes
```
1
_
^
#$_
((`#([^#]*?)( ?)_(_*)_( ?)([^#]*?)$
$0# $1\$3/$5
+)`\\( ?)_(_*)_( ?)/(?=[^#]*$)
\ $1$2$3 /
#( *(\\ )*\\ *) ( *(/ )*/)$
$0# $1$3
)`#( *(\\ )*)\\/(( /)*)$
$0# $1$3
#
#
^#
<empty line>
```
Takes input as unary.
Each line should go to its own file and `#` should be changed to newline in the files. This is impractical but you can run the code as is as one file with the `-s` flag, keeping the `#` markers. You can change the `#`'s to newlines in the output for readability if you wish. E.g.:
```
> echo -n 1111|retina -s triangle|tr # '\n'
________
\ __ /
\ \/ /
\ /
\/
```
The code isn't too well golfed (yet).
[Answer]
**C — 206 bytes**
`i,j,m,k,a,b;main(i,v)char**v;{m=atoi(v[1])*2;while(k<m*(m/2+1)){i=k/m;j=k%m;a=i*3,b=(i+j)%2;putchar("_\\/ "[j>=a&&j<m-a?0:j>i-2&&b&&j<i*3-1&&j<m/2?1:j<=m-i&&!b&&j>m-a&&j>=m/2?2:3]);if(j==m-1)puts("");k++;};}`
```
x,m,i,j,a,b;
int main(x,v)char**v;{
m=atoi(v[1])*2;
for(i=0;i<m/2+1;i++){
for(j=0;j<m;j++){
a=i*3,b=(i+j)%2;
j>=a&&j<m-a?a=0:j>=i-1&&b&&j<i*3-1&&j<m/2?a=1:j<=m-i&&!b&&j>m-a&&j>=m/2?a=2:(a=3);putchar("_\\/ \n"[a]);
}
puts("");
}
}
```
**Example output**
```
Pauls-iMac:ppcg pvons$ for i in $(seq 1 7); do ./a.out $i; done
__
\/
____
\ /
\/
______
\ /
\ /
\/
________
\ __ /
\ \/ /
\ /
\/
__________
\ ____ /
\ \ / /
\ \/ /
\ /
\/
____________
\ ______ /
\ \ / /
\ \ / /
\ \/ /
\ /
\/
______________
\ ________ /
\ \ __ / /
\ \ \/ / /
\ \ / /
\ \/ /
\ /
\/
```
[Answer]
# JavaScript (*ES6*) 165 ~~180 204~~
Run snippet in Firefox to test. If returning the string is not enough, using alert for output is 2 chars more.
```
// 165 - return the string
F=n=>
(i=>{
for(r='__'[R='repeat'](m=n);i<n;)
r+=`\n`+' '[R](i)
+('\\ '[R](t=-~(m>3?i:~-n/3))+' ').slice(0,n-i)
+'__'[R](m>3?m-=3:0)
+(' '+' /'[R](t)).slice(i++-n)
})(0)||r
// 167 - output the string
A=n=>{
for(i=0,r='__'[R='repeat'](m=n);i<n;)
r+=`\n`+' '[R](i)
+('\\ '[R](t=-~(m>3?i:~-n/3))+' ').slice(0,n-i)
+'__'[R](m>3?m-=3:0)
+(' '+' /'[R](t)).slice(i++-n);
alert(r)
}
// TEST
out=x=>O.innerHTML += x+'\n'
for(k=1;k<13;k++)out(k+'\n'+F(k))
```
```
<pre id=O></pre>
```
] |
[Question]
[
As you know, the World Cup group stage is over, and from tomorrow the best 16 teams will commence the knockout stage:
* Brazil (BRA)
* Mexico (MEX)
* Netherlands (NED)
* Chile (CHI)
* Colombia (COL)
* Greece (GRE)
* Costa Rica (CRC)
* Uruguay (URU)
* France (FRA)
* Switzerland (SUI)
* Argentina (ARG)
* Nigeria (NGA)
* Germany (GER)
* United States (USA)
* Belgium (BEL)
* Algeria (ALG)
In the knockout stage, after each match the winner gets through to the next round, and the loser goes home (there are no draws). [Click here](http://en.wikipedia.org/wiki/2014_FIFA_World_Cup_knockout_stage) to see more about the knockout stage.
You have been hired by golfbet.com, a new betting website because you are known to be good at both programming and sports betting. Your task is to write a program or function which can guess the winner of a match. Of course, everybody makes different guesses, it doesn't matter as long as your guesses are consistent.
If you don't want to guess, you can use the following guesses:
```
BRA
BRA
CHI
BRA
COL
COL
URU
GER
FRA
FRA
NGA
GER
GER
GER
ALG
GER
NED
NED
MEX
NED
CRC
CRC
GRE
ARG
ARG
ARG
SUI
ARG
BEL
BEL
USA
```
1. The program has to output the same winner regardless the order of the to teams (the winner of the BRA-CHI match has to be the same as of the CHI-BRA match)
2. If a team loses, it cannot play any more matches. This means for matches that don't take place, you have to indicate so. For example if your program guesses Brazil to win the BRA-CHI match, then CHI-GER has to return "no result", because Chile won't play against Germany. See the link above for schedule.
For the sake of simplicity you don't have to deal with the bronze match (but you can of course).
Your program or function takes two strings as input: the 3-letter country code of the two teams and returns the country code of the winning team (you can use standard input/output, or two function parameters/return value). If the given two teams will not play according to your guesses, you must return something else (this can be anything but the country codes, eg empty string, null, error message). You can assume the input is correct (two different country codes which are in the list).
This is primarily a code-golf, so shortest program in bytes wins. However, nice and tricky solutions are also valuable.
**Example (of course, you can make your own guesses):**
input:
BRA
CHI
output:
BRA
input:
CHI
BRA
output:
BRA
input:
CHI
GER
output: no result
[Answer]
# Python 2.x - ~~368~~ 283
Interesting challenge. Of course we need to get present rankings from the [FIFA](http://www.fifa.com/worldranking/rankingtable/).
Brazil have the so-called "12th man" as they have home advantage therefore the weighting 12/11.
```
a='BRA CHI COL URU FRA NGA ALG GER MEX NED CRC GRE ARG SUI BEL USA'.split()
d=[1242*12/11,1026,1137,1147,913,640,858,1300,882,981,762,1064,1175,1149,1074,1035]
m={}
for n in[16,8,4,2]:
j=0
for k in range(0,n,2):
s=a[k] if d[k]>d[k+1] else a[k+1]
m[a[k]+' '+a[k+1]]=s
a[j]=s
j+=1
def f(s):
try: print m[s]
except: print 'no result'
```
Tips to shorten the above are welcome :-).
Improvements thanks to @TheRare and @MrLemon
```
a='BRA CHI COL URU FRA NGA ALG GER MEX NED CRC GRE ARG SUI BEL USA'.split()
d=15,6,10,11,4,0,2,14,3,5,1,8,13,12,9,7
m={}
for n in 16,8,4,2:
j=0
for k in range(0,n,2):s=a[k]if d[k]>d[k+1]else a[k+1];m[a[k]+' '+a[k+1]]=s;a[j]=s;j+=1
def f(s):print s in m and m[s]or'no result'
```
This leads to the following results:
```
BRA CHI: BRA
COL URU: URU
FRA NGA: FRA
ALG GER: GER
MEX NED: NED
CRC GRE: GRE
ARG SUI: ARG
BEL USA: BEL
------------
BRA URU: BRA
FRA GER: GER
NED GRE: GRE
ARG BEL: ARG
------------
BRA GER: BRA
GRE ARG: ARG
------------
BRA ARG: BRA
```
Example calls:
```
f('BRA MEX')
no result
f('BRA CHI')
BRA
```
[Answer]
# C, ~~182 178~~ 133 (or 126)
**Not the shortest program here, but it is the shortest in which the prediction can be changed easily. Now that all the semifinalists are known, I'm updating.**
There's some changes to the code, too. Apart from Dennis's suggestions in the comments, the program has been converted to a function (as on re-reading this is allowed by the rules) and the hashing has been shortened.
**Code,133**
```
f(char*a,char*b){
char*p,*t=" HIAEAIH N?=R=?N ;@4S4@; 5BDGDB5 B@?I?@B",h[3]={*a-a[1]%16,*b-b[1]%16};
(p=strstr(t,h))&&puts(p-t&2?a:b);
}
```
**How it works**
the inputs `a` and `b` are hashed by the expression `*a-a[1]%16` to a single character (`*a` is a shorter equivalent to `a[0]`). The hash results for teams `a` and `b` are stored in `h`. For example BRA CHI becomes `@;`. Hashed values are as follows (the confirmed semifinalists and my predicted champion are marked with `*`.)
```
GRE E CRC A *NED I MEX H
USA R BEL = *ARG ? SUI N
URU S COL 4 **BRA @ CHI ;
NGA G FRA D *GER B ALG 5
```
`t[]` stores my predictions. The results of the round of 16 and quarter finals are now known. Each group of 4 teams is ordered such that the 1st and 4th were eliminated, and the 3rd is the semifinalist. Similarly of the semifinalists, I'm predicting that the 1st and 4th will be eliminated and the 3rd semifinalist will be the overall winner. If you disagree with my predictions, simply reorder the table.
The predictions are stored in palindromic blocks to accommodate the possibility of the user entering the teams in either possible order. The ordering puts the winning teams of each set of 4 together to play a third match. Thus in the first group GRE`E` lost to CRC and MEX`H` lost to NED. This sets up CRC`A` to play NED`I` in the quarter final without having to repeat the typing. The string is padded with a space between each group of 4 teams / 7 characters to help ensure there is no output for teams that will not play each other.
The winner of each possible match in each group of 8 characters is as follows: `invalid,b,a,a,b,b,a,invalid`. Thus the correct choice of winner can be made by taking the position of `h` in `t` *AND 2*. Unfortunately the `strstr` function is not the most straighforward as it returns a pointer `p`, so we must subtract `p` from `t` to get the actual position in `t.` If the match is invalid (cannot be found in `t`), `p` is zero and the phrase `no result` is printed.
**Some dubious improvements, 126**
2 characters saved by an improved hash expression. Unfortunately, this requires the case of the teams to be as shown in the test program below the function (eg `Bra` instead of `BRA` as used in the program above.) I've satisfied myself that there is no way of doing this with a single operator, so 2 operators and a single-character constant is as good as it gets. Note also that `Uru` maps to `space` so an alternate character `|` is needed to separate the groups of teamcodes.
5 characters saved by eliminating `t` and treating the prediction string as a literal. This means it is impossible to know the address where the string is stored. However, provided it is not stored at zero, we are only interested in `p&2` so the code will work if the address is divisible by 4. (Note that it is not allowed to treat pointer `p` directly as an integer, it must be subtracted from another pointer. I use the pointer `a` so `a` must also be divisible by 4.) One can be fairly confident on a 32 or 64 bit compiler/architecture strings will be stored in this way. This has been working fine for me on GCC/cygwin, though it refuses to compile on visual studio / windows.
```
g(char*a,char*b){
char*p,h[3]={*a^a[1]+3,*b^b[1]+3};
(p=strstr("|%&626&%|+4*#*4+|(71 17(|./3$3/.|/74&47/",h))&&puts(p-a&2?a:b);
}
main(){
char team[16][4]={"Gre","Crc","Ned","Mex", "Usa","Bel","Arg","Sui", "Uru","Col","Bra","Chi", "Nga","Fra","Ger","Alg"};
int i;
for(i=1;i<16;i++){printf("%s %s \n",team[i-1],team[i]);g(team[i],team[i-1]);g(team[i-1],team[i]);}
}
```
[Answer]
## JavaScript 215 206 120 116
A lot of room for improvement:
**ES5 - 215**
```
a=prompt().split(' ');("BRACHI0COLURU0FRANGA0GERALG0NEDMEX0CRCGRE0ARGSUI0BELUSA0BRACOL0FRAGER0NEDCRC0ARGBEL0BRAGER0NEDARG0BRANED".split(0).filter(function(x){return x.match(a[0])&&x.match(a[1])})[0]||"").substr(0,3)
```
**ES6 - 206**
```
a=prompt().split(' ');("BRACHI0COLURU0FRANGA0GERALG0NEDMEX0CRCGRE0ARGSUI0BELUSA0BRACOL0FRAGER0NEDCRC0ARGBEL0BRAGER0NEDARG0BRANED".split(0).filter((x)=>{return x.match(a[0])&&x.match(a[1])})[0]||"").substr(0,3)
```
**Regex Approach - 116**
Thanks to [ɐɔıʇǝɥʇuʎs](https://codegolf.stackexchange.com/users/18638/%C9%90%C9%94%C4%B1%CA%87%C7%9D%C9%A5%CA%87u%CA%8Es) for posting [this link](http://nbviewer.ipython.org/url/norvig.com/ipython/xkcd1313.ipynb), it helped me making the regex
```
a=prompt().split(' ').sort();a.join('').match(/LG(.R(A|G)|GE)|RG(S|BE|CR)|ELUS|AC(H|O)|OLUR|CGR|CM|FRANG|XNE/)&&a[0]
```
[Answer]
# Python (~~179~~ ~~148~~ 139 c.q. way too long)
```
f=lambda *l:sorted(l)[0]if"".join(sorted(l))in"BRACHI COLURU FRANGA ALGGER MEXNED CRCGRE ARGSUI BELUSA BRACOL ALGFRA CRCMEX ARGBEL BRAFRA CRCMEX ARGBEL BRAFRA ARGCRC ARGBRA"else 0
```
Everybody knows the country with the name that comes first in the alphabet is going to win. (This answer just exists to get things started)
Thanks to the charity of the guy(s) over [here](http://nbviewer.ipython.org/url/norvig.com/ipython/xkcd1313.ipynb), I could shorten my answer by a bit:
```
import re;f=lambda *l:sorted(l)[0]if re.match('RGB|CM|RGS|CGR|L.F|XNE|EL.S|O.UR|RGCR|B.AF|L.GE|^BRACHI$|^FRANGA$|^BRACOL$',"".join(sorted(l)))else 0
```
This does assume valid teams, but doesn't need a valid line-up (`f('BRA','NED')` would return 0 (invalid match), but `f('XNE')` would return `'XNE'`. I don't get from your question that this is a problem though. Feel free to re-abuse this regex as you see fit.
Thanks @Ventero, I know nothing about regexes.
```
import re;f=lambda*l:sorted(l)[0]if re.match('RGB|CM|RGS|CGR|L.F|XNE|EL.S|O.UR|RGCR|B.AF|L.GE|BRACHI|FRANGA|BRACOL',"".join(sorted(l)))else 0
```
[Answer]
# Scala (150)
```
type s=String;var m=Map[s,s]();def f(x:(s,s))={var a=x._1;var b=x._2;if(b<a){b=a;a=x._1};if(m.getOrElse(a,a)=="")m.getOrElse(b,b)else{m=m+(b->"");a}}
```
Here are matches between "foo" and "bar" possible, also teams wich won't play in real against each other in the first rounds will have a result.(for example starting with BRA,ARG)
It's just recording loosing teams.
```
type s=String //just aliasing for saving characters
var m=Map[s,s]() //map for storing loosing teams, a set would do too
def f(x:(s,s))={
var a=x._1 var b=x._2
if(b<a){b=a;a=x._1};//swap if b<a lexographically
if(m.getOrElse(a,a)=="")//if a has loosed previously
m.getOrElse(b,b)// return b if b was not in the map else return ""
else{
m=m+(b->"") //add b to the map, because a will definitly win this amazing match
a //and return a
}
}
```
Called with:
```
f(("GER","BRA"))
```
[Answer]
# PowerShell (261 221)
```
$a=Read-Host;$b=Read-Host;$x="CHIBRA","URUCOL","FRANGA","ALGGER","MEXNED","CRCGRE","SUIARG","BELUSA";0..($x.Length-2)|%{$x+=$x[2*$_].Substring(3)+$x[2*$_+1].Substring(3)};$x|?{"$a$b","$b$a"-eq$_}|%{$_.Substring(3);exit};0
```
As a relatively new PowerShell user, I find the pipeline absolutely amazing. I think next up might be to try and fiddle with the array to hopefully eliminate all these substring calls. (I had to add a call at the end or else it outputted both teams)
>
> New member, first attempt at code golf!
>
>
> Could have hard-coded the quarterfinal, semis, and finals to save a few characters, but >that wouldn't be quite as fun.
>
>
> Should be simple enough to decipher, but it fulfills both conditions: gives same winner >regardless of order entered, and only returns a winner for matches that actually take >place!
>
>
> Any advice for improvement would be greatly appreciated, thanks!
>
>
>
### Original
```
$a=Read-Host;$b=Read-Host;$x=("CHIBRA","URUCOL","FRANGA","ALGGER","MEXNED","CRCGRE","SUIARG","BELUSA");for($c=0;$c-lt$x.length-1;$c+=2){$x+=$x[$c].Substring(3)+$x[$c+1].Substring(3)}foreach($i in $x){if($i-match$a-and$i-match$b){return $i.Substring(3)}}return 0
```
[Answer]
# CJam, ~~64~~ 58 bytes
```
lS/$_0=\:+4b256b1>:ca"oM-YtM-mM-^@}gM-^VM-^U8tM-=nM-^MfM-]oM-xgM-)tM-|m@gim{g_"2/&,*
```
The above uses caret and M- notation, since the code contains unprintable characters.
At the cost of six additional bytes, those characters can be avoided:
```
lS/$_0=\:+4b95b1>32f+:c"I8Vyv)2~N{VIEh1$IW32W)B82QBs2G"2/N*\#W>*
```
[Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### Test run
```
$ base64 -d > worldcup.cjam <<< \
> bFMvJF8wPVw6KzRiMjU2YjE+OmNhIm/ZdO2AfWeWlTh0vW6NZt1v+GepdPxtQGdpbXtnXyIyLyYsKg==
$ wc -c worldcup.cjam
58 worldcup.cjam
$ for A in ALG ARG BEL BRA CHI COL CRC FRA GER GRE MEX NED NGA SUI URU USA; do
> for B in ALG ARG BEL BRA CHI COL CRC FRA GER GRE MEX NED NGA SUI URU USA; do
> [[ $A < $B ]] && echo $A - $B : $(LANG=en_US cjam worldcup.cjam <<< "$A $B")
> done; done | grep ': .'
ALG - ARG : ALG
ALG - BRA : ALG
ALG - FRA : ALG
ALG - GER : ALG
ARG - BEL : ARG
ARG - CRC : ARG
ARG - SUI : ARG
BEL - USA : BEL
BRA - CHI : BRA
BRA - COL : BRA
COL - URU : COL
CRC - GRE : CRC
CRC - MEX : CRC
FRA - NGA : FRA
MEX - NED : MEX
```
### How it works
```
lS/$ " Read one line from STDIN, split at spaces and sort the resulting array. ";
_0=\ " Extract the first element of a copy of the array and swap it with the array. ";
:+ " Concatenate the strings. ";
4b " Convert the resulting string into an integer by considering it a base 4 number. ";
256b " Convert the integer into an array by considering it a base 256 number. ";
1>:ca " Drop the first element, convert into a string and create a singleton array. ";
"…" " Push a string of all matches encoded as explained above. ";
2/ " Split the string into an array of two-character strings. ";
& " Intersect the two arrays. If the array is non-empty, the teams play. ";
,* " Multiply the string on the stack by the length of the array. ";
```
[Answer]
# CJam, ~~49~~ 48 bytes
```
lS/$_0="^\16@&^^/+(^]^W^Y,>O?"{_2%+}3*@{2b91%c}%#1&!*
```
The above uses caret notation, since the code contains unprintable characters.
At the cost of two additional bytes, those characters can be avoided:
```
lS/$_0="(=BL2*;74)#%8J[K"{_2%+}3*@{2b91%C+c}%#1&!*
```
[Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### Test run
```
$ base64 -d > wc.cjam <<< bFMvJF8wPSIcMTZAJh4vKygdFxksPk8/IntfMiUrfTMqQHsyYjkxJWN9JSMxJiEq
$ wc -c wc.cjam
48 wc.cjam
$ for A in ALG ARG BEL BRA CHI COL CRC FRA GER GRE MEX NED NGA SUI URU USA; do
> for B in ALG ARG BEL BRA CHI COL CRC FRA GER GRE MEX NED NGA SUI URU USA; do
> [[ $A < $B ]] && echo $A - $B : $(cjam wc.cjam <<< "$A $B"); done; done | grep ': .'
ALG - ARG : ALG
ALG - BRA : ALG
ALG - FRA : ALG
ALG - GER : ALG
ARG - BEL : ARG
ARG - CRC : ARG
ARG - SUI : ARG
BEL - USA : BEL
BRA - CHI : BRA
BRA - COL : BRA
COL - URU : COL
CRC - GRE : CRC
CRC - MEX : CRC
FRA - NGA : FRA
MEX - NED : MEX
```
### Background
We start by assigning and ASCII character to each team by considering its name a base 2 number, taking the resulting integer modulo 91, adding 12 (to avoid unprintable characters) and selecting the character corresponding to the resulting ASCII code. In CJam code, this is achieved by `2b91%c`.
For example, the character codes of `ALG` are `65 76 71`. Since `(4 × 65 + 2 × 76 + 71) = 483`, `483 % 91 + 12 = 40` and 40 if the character code of `(`.
This gives the following mapping:
```
ALG ( ARG 4 BEL # BRA 2 CHI * COL ; CRC 8 FRA B
GER = GRE J MEX [ NED K NGA L SUI ) URU 7 USA %
```
Now, we can encode the matches of the round of 16 as follows:
```
(=BL2*;74)#%8J[K
```
If we assume that the first team in alphabetical order always wins, the matches of the quarter-finals are as follows:
```
(B2;4#8[
```
Note that this string can be obtained from the first by selecting every second character, starting with the first. In CJam code, this is achieved by `2%`.
Using the same idea, the matches of the semi-finals and the final match are as follows:
```
(248
(4
```
The code
```
"(=BL2*;74)#%8J[K"{_2%+}3*
```
pushes the string containing the matches of the round of 16, then does the following thrice: duplicate the string, extract every second character of the copy, concatenate. The result is the string
```
(=BL2*;74)#%8J[K(B2;4#8[(B2;4#8[(248(B2;4#8[(248(248(4
```
which contains all matches (some of them more than once).
### How it works
```
lS/$ " Read one line from STDIN, split at spaces and sort the resulting array. ";
_0= " Extract the first element of a copy of the array. ";
"…" " Push the string containing the matches of the round of 16. ";
{_2%+}3* " Push the remaining matches. ";
@ " Rotate the input array on top of the stack. ";
{2b91%C+c}% " Perform the mapping for each team in the input array. ";
# " Push the index of the match in the array of all matches (-1 for not found). ";
1&! " Push 1 if the index is even (valid match) and 0 if it is odd. ";
,* " Repeat the string on the stack that many times. ";
```
[Answer]
# JavaScript 271
```
t=prompt('Match?').split('-')
x=t[0],y=t[1],T='BRACHICOLURUFRANGAGERALGNEDMEXCRCGREARGSUIBELUSA'
v='\n',R='',W='No Game'
for(z=1;T!='USA';++z,T=n){R+=v+z+v,n='',r=/(...)(...)/g
while(m=r.exec(T))a=m[1],n+=b=m[2],R+=a+'-'+b+v,W=a==x&&b==y||a==y&&b==x?b:W
}
alert(W+'\n'+R)
```
] |
[Question]
[
plorcly borglar is a "mod" created by jan Misali for the constructed language toki pona that makes words sound funny.
It involves substituting the 14 toki pona letters for funnier versions plus 2 extra rules. The substitutions are:
| toki pona letter | plorcly borglar letter |
| --- | --- |
| m | bl |
| n | gl |
| p | b |
| t | pl |
| k | cl |
| s | scr |
| w | spw |
| l | scl |
| j | shl |
| i | ee |
| u | oo |
| e | o |
| o | or |
| a | ar |
The two extra rules are:
* When an "n" in a toki pona is followed by a consonant or ends a word it is replaced with "ng" instead of "gl", so *nasin* becomes *glarscreeng* not \**glarscreegl*
* When an *i* is the final letter of a word containing another vowel it becomes "y" instead of "ee", so *poki* becomes *borcly* not \**borclee*, but *ni* becomes *glee* not *gly*.
*(The vowels here are "a", "e", "i", "o" and "u", "y" does not exist in toki pona at all)*
And that's it.
The challenge here is to take a sequence of space separated words that are valid in toki pona's phonotactics and convert it to plorcly borglar. If you know what that means you can get going, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. Otherwise I will explain it.
Toki pona has 14 letters / phonemes, 9 consonants "m", "n", "p", "t", "k", "s", "w", "l", and "j" and 5 vowels "a", "e", "i", "o", "u". All words are built out of these characters (No upper case), but not every sequence of these characters is a valid word.
That's probably all you *need* to complete this challenge. But there are more rules that might be helpful for optimizing.
Words in toki pona consist of syllables. A syllable in toki pona is consists of a consonant, then a vowel, then an optional "n". The first syllable in a word can skip the initial consonant. For example "olin" is a valid syllable consisting of "o" + "lin". Additionally "nn" and "nm" are not legal sequences so you can't end a syllable in "n" if the next one starts with "n" or "m".
Finally the following syllables are illegal:
* *ti(n)*
* *ji(n)*
* *wu(n)*
* *wo(n)*
So they will not appear in input words.
## Test cases
```
toki pona -> plorcly borglar
nasin -> glarscreeng
poki -> borcly
ni -> glee
mi olin e sina -> blee orscleeng o screeglar
soweli lawa li ike tawa mi -> scrorspwoscly sclarspwar sclee eeclo plarspwar blee
lon sike lon ma la jan lili li tomo -> sclorng screeclo sclorng blar sclar shlarng scleescly sclee plorblor
sinpin -> screengbeeng
tenpo -> plongbor
linja -> scleengshlar
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~73~~ ~~68~~ ~~66~~ ~~63~~ ~~62~~ 60 bytes
```
‛ngkvvẊ÷V⌈ƛṪAa[ṫ‛iy*J;C«ƛẋ8›ŀ+λ¢Żƛvτ"Ŀ¨z`B†⁋ɽ†g<¹⌊}+.+«⌈$İṠṄ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigJtuZ2t2duG6isO3VuKMiMab4bmqQWFb4bmr4oCbaXkqSjtDwqvGm+G6izjigLrFgCvOu8KixbvGm3bPhFwixL/CqHpgQuKAoOKBi8m94oCgZzzCueKMin0rLivCq+KMiCTEsOG5oOG5hCIsIiIsInRva2kgcG9uYSJd) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJBIiwiYCAtPiBg4oKsaHfCqFMiLCLigJtuZ2t2duG6isO3VuKMiMab4bmqQWFb4bmr4oCbaXkqSjtDwqvGm+G6izjigLrFgCvOu8KixbvGm3bPhFwixL/CqHpgQuKAoOKBi8m94oCgZzzCueKMin0rLivCq+KMiCTEsOG5oOG5hCIsIiIsInRva2kgcG9uYSAtPiBwbG9yY2x5IGJvcmdsYXJcbm5hc2luIC0+IGdsYXJzY3JlZW5nXG5wb2tpIC0+IGJvcmNseVxubmkgLT4gZ2xlZVxubWkgb2xpbiBlIHNpbmEgLT4gYmxlZSBvcnNjbGVlbmcgbyBzY3JlZWdsYXJcbnNvd2VsaSBsYXdhIGxpIGlrZSB0YXdhIG1pIC0+IHNjcm9yc3B3b3NjbHkgc2NsYXJzcHdhciBzY2xlZSBlZWNsbyBwbGFyc3B3YXIgYmxlZVxubG9uIHNpa2UgbG9uIG1hIGxhIGphbiBsaWxpIGxpIHRvbW8gLT4gc2Nsb3JuZyBzY3JlZWNsbyBzY2xvcm5nIGJsYXIgc2NsYXIgc2hsYXJuZyBzY2xlZXNjbHkgc2NsZWUgcGxvcmJsb3IiXQ==).
*-3 bytes* by emanresu A
*-3 bytes* by slightly modifying emanresu A's 64 byte solution
*-1 byte* by adapting mod 17 indexing from [*@Arnauld's* JavaScript answer](https://codegolf.stackexchange.com/a/257740/116074)
*-2 bytes* by emanresu A
Start by handling the `n` special case by replacing every occurrence of `n` where special rules don't apply with `g`.
```
‛ng # push the string "ng"
kv # push all vowels "aeiou"
vẊ # vectorize cartesian product [["na", "ne", ... ], [ga, ge, ...]]
÷ # push each to stack
V # replace
```
Process each word individually, optionally replacing a `i` at the end with `y`.
```
⌈ # split on spaces
ƛ # map:
Ṫ # remove last item
A # is vowel?
a[ # if any is true:
ṫ # tail extract
‛iy # push "ib"
* # ring translate
J # concatenate
; # end map
```
Now comes the main part where most of the replacements happen.
```
C # convert to a list of char codes
«...« # push the string "spw gl y ee shl cl scl bl ng or b ar scr pl oo o"
⌈ # split on spaces
$ # swap top two items on the stack
İ # index into (Vyxal indexing wraps around)
Ṡ # vectorizing sum
Ṅ # join by spaces
```
[Answer]
# [Lexurgy](https://www.lexurgy.com/sc), 134 bytes
```
a:
i=>y/{a,e,i,o,u} []* _ $
n=>ng/_ {m,n,p,t,k,s,w,l,j,$}
{m,n,p,t,k,s,w,l,j,u,e,o,a,i}=>{bl,gl,b,pl,cl,scr,spw,scl,shl,oo,o,or,ar,ee}
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 103 bytes
```
a
ar
o
or
e
o
u
oo
s
scr
l
scl
j
shl
p
b
w
spw
k
cl
t
pl
n([aio])
gl$1
n
ng
m
bl
([aio]\w*)i\b
$1y
i
ee
```
[Try it online!](https://tio.run/##JY6xDsMwCET3@wqGDE23fE/TgVRWSoLBil1Z/fqUqAt3PE4njtTE@DwZfMDhB1LIB@6oqK8DGlOxob4VBQs6aunYEbChKOz2YPHniFWHCQZbkbEo/nju91HmBcP0hSCl82y@CxU3hnEVQ4kdJshCrmKUKCijek8qpNyZQmVP1C6fBeoWmQCXyXFm2tgideWFmuf4XaxEeRRu/AM "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Mainly just a series of replacements. The primary ordering is that no replacement string contains letters yet to be translated. Additionally the rules that depend on vowels come after `e` and `u` are translated but before `i` is translated to reduce the number of relevant vowels to check.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 86 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ð¡ε.•3₁‹uŒœÈĆ•S.•1и<Uº•2ô«.•3r"Δü¾n₂¸}#rö₆!õé¯à1#ry‚H¦±x¦7ke•#.:Âć'eQs¦žMÃĀ*i¨¨'y«]ðý
```
[Try it online](https://tio.run/##yy9OTMpM/f//8IZDC89t1XvUsMj4UVPjo4adpUcnHZ18uONIG1AoGCRueGGHTeihXUCW0eEth1aDlRYpnZtyeM@hfXmPmpoO7ahVLjq87VFTm@LhrYdXHlp/eIGhclHl4aZHDbM8Di07tLHi0DLz7FSgNmU9q8NNR9rVUwOLDy07us/3cPORBq3MQysOrVCvPLQ69vCGw3v//y/Jz85UKMjPSwQA) or [verify all test cases](https://tio.run/##HYyxSsRAEIb7fYo1KQ5EDk4LQYRrbSxEfIAVtthLshuS6BkwECNE69PKSi3CyRWe4MkpesVM0h4@w75InFjNP99885tYnCrZXp6nQ4fbcsKdYdriHJ7Wi77Nn3dscWXzz7Nm0tzhbV0SOu744He5fwJflLbxHWb/auSs7/EbVtoWBSwzN8IPW5QbuMAXeMXHgRulWNj84QAqeLuAateT9Ob297Cob3ryKIaqWR3idZ1vKpjCtJfCLMtwjj/tVpsYT/HQaMG0iJVmIe1MKxYobnylueREBYvNWPqK@2IsOE3lSZ50OVDMN5ocAl0I6Cz4SGiyOl/xxASGUUdI5VQ4En8).
**Explanation:**
*General explanation:*
1. Split on spaces, and map over the toki pona words.
2. Do the following replacements (in order): a→ar; o→or; e→o; u→oo; s→scr; l→scl; j→shl; p→b; w→spw; k→cl; t→pl; m→bl; na→gla; no→glo; ni→gli; i→ee.
3. Replace a trailing 'ee' with 'y' if there are three or more vowels.
4. Join the plorcly borglar words back with space delimiter, and output the result.
*Code explanation:*
```
ð¡ # Split the (implicit) input-list on spaces
# (note: cannot be builtin `#`, since it fails for inputs without spaces)
ε # Map over each toki pona word:
.•3₁‹uŒœÈĆ• # Push compressed string "aoeusljpwktmi"
S # Convert it to a list of characters
.•1и<Uº• # Push compressed string "nanonin"
2ô # Split it into parts of size 2: ["na","no","ni","n"]
« # Merge the two lists together
.•3r"Δü¾n₂¸}#rö₆!õé¯à1#ry‚H¦±x¦7ke•
"# Push compressed string "ar or o oo scr scl shl b spw cl pl bl ee gla gli glo ng"
# # Split it on spaces
.: # Do all replacement one by one in the current toki pona word
Âć'eQs¦žMÃĀ*i¨¨'y« # Handle special case trailing 'i':
 # Bifurcate the current word; short for Duplicate & Reverse copy
ć # Extract head; pop and push remainder-string and first char
'eQ '# Check if this character is an "e"
s # Swap so the remainder-string is at the top
¦ # Remove the first character
žMÃ # Only keep all vowels
Ā # Check whether what remains is NOT an empty string
*i # If both are truthy:
¨¨ # Remove the trailing "ee"
'y« '# And append an "y" instead
] # Close both the if-statement and map
ðý # Join the plorcly borglar words back together with space delimiter
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•3₁‹uŒœÈĆ•` is `"aoeusljpwktmi"`; `.•1и<Uº•` is `"nanonin"`; and `.•3r"Δü¾n₂¸}#rö₆!õé¯à1#ry‚H¦±x¦7ke•` is `"ar or o oo scr scl shl b spw cl pl bl ee gla gli glo ng"`.
[Answer]
# JavaScript, 260 bytes
```
s=>s.replace(/[^ ]*/g,w=>[...w].map((l,i,a)=>a.some((l,i)=>i!=(v={i:'ee',u:'oo',e:'o',o:'or',a:'ar'},b=a.length-1)&&v[l])&&l=='i'&&i==b?'y':((c={m:'bl',n:'gl',p:'b',t:'pl',k:'cl',s:'scr',w:'spw',l:'scl',j:'shl'})[a[i+1]]||i==b)&&l=='n'?'ng':c[l]||v[l]).join``) // 260
// Without map and join
s=>s.replace(/[^ ]*/g,w=>w.replace(/./g,(l,i)=>[...w].some((l,i)=>i!=(v={i:'ee',u:'oo',e:'o',o:'or',a:'ar'},b=w.length-1)&&v[l])&&l=='i'&&i==b?'y':((c={m:'bl',n:'gl',p:'b',t:'pl',k:'cl',s:'scr',w:'spw',l:'scl',j:'shl'})[w[i+1]]||i==b)&&l=='n'?'ng':c[l]||v[l])) // 260
```
Try it:
```
f=s=>s.replace(/[^ ]*/g,w=>[...w].map((l,i,a)=>a.some((l,i)=>i!=(v={i:'ee',u:'oo',e:'o',o:'or',a:'ar'},b=a.length-1)&&v[l])&&l=='i'&&i==b?'y':((c={m:'bl',n:'gl',p:'b',t:'pl',k:'cl',s:'scr',w:'spw',l:'scl',j:'shl'})[a[i+1]]||i==b)&&l=='n'?'ng':c[l]||v[l]).join``)
;[
['o', 'or'],
['toki pona', 'plorcly borglar'],
['nasin', 'glarscreeng'],
['poki', 'borcly'],
['ni', 'glee'],
['tonki', 'plorngcly'],
['mi olin e sina', 'blee orscleeng o screeglar'],
['soweli lawa li ike tawa mi', 'scrorspwoscly sclarspwar sclee eeclo plarspwar blee'],
['lon sike lon ma la jan lili li tomo', 'sclorng screeclo sclorng blar sclar shlarng scleescly sclee plorblor'],
['sinpin', 'screengbeeng'],
['linja', 'scleengshlar'],
].map(s=>console.log(f(s[0]), f(s[0])===s[1]));
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 155 bytes
```
s=>s[R='replace'](/\S/g,c=>'spw///ee/shl/cl/scl/bl/gl/or/b//ar/scr/pl/oo/o'.split`/`[Buffer(c)[0]%17])[R](/gl(?![aeo])/g,'ng')[R](/(?<=[aeo]\S*)ee\b/g,'y')
```
[Try it online!](https://tio.run/##jVLNTsMwDL7zFGYSaosAw4kLZRKPAMduEknxugwvjpLCxNMPp9sObANWKWni1t@P7YX5NKmNLvTXXt5oPavXqX5MzXNdRApsWiqmJU5esLtq68cihRUiEmGaM7aMSZdl7BglokU0UUMRg94FpbhJgV3/iq/N08dsRrFsq@Z2enF3P62aZ8XtuByfN4ZkWilB4btiEy/HD/UQnrxcVkQTm79@FdW6FZ@E6YalK2flqJd3B0G8GVUV/P4gQmCJLX@BldixiWd7QN4k5/8G2QLlbLVI5Lt9kKBq/sfIIHYQcyDilOytCKL97KUDYeeBQK38XpDMrtkg6oKzCxAY/BwrS5IVsQM2KwP6du8EfT4vfypVTIVQxLCSlKusm8k3E2FgAaKWRZuwi9ojBli8SleKfFgqoYGF8cqbFTjoZSmZdSDTbqryQXcG3gUsbxjzPtd9@EepdqJUSR4Eq@vAqvPhhBHYWM11s8dGoCcf5KQ5Uh2KcahDW7gwJyFs@zcYXX8D "JavaScript (Node.js) – Try It Online")
## How?
### Step 1: main character substitution
Because the input string is guaranteed to be valid toki pona, we only need to support the 14 toki pona letters. Taking their ASCII code modulo 17 is slightly more efficient than just subtracting 97.
| character | ASCII code | mod 17 | replaced with |
| --- | --- | --- | --- |
| 'a' | 97 | 12 | 'ar' |
| 'e' | 101 | 16 | 'o' |
| 'i' | 105 | 3 | 'ee' |
| 'j' | 106 | 4 | 'shl' |
| 'k' | 107 | 5 | 'cl' |
| 'l' | 108 | 6 | 'scl' |
| 'm' | 109 | 7 | 'bl' |
| 'n' | 110 | 8 | 'gl' |
| 'o' | 111 | 9 | 'or' |
| 'p' | 112 | 10 | 'b' |
| 's' | 115 | 13 | 'scr' |
| 't' | 116 | 14 | 'pl' |
| 'u' | 117 | 15 | 'oo' |
| 'w' | 119 | 0 | 'spw' |
It is worth noting that translated vowels can be detected with just `[aeo]` because `i`'s and `u`'s are removed entirely. We use this property for the two other steps.
### Step 2: applying the *n→ng* rule
We look for ...
```
.--------> the substitution of 'n'
| .--> not followed by the substitution of a vowel
| ___|___
/gl(?![aeo])/g
```
... and replace each match with `ng`.
### Step 3: applying the *ee→y* rule
We look for ...
```
.-----------> the substitution of a vowel
| .-------> optionally followed by non-space characters
| | .----> followed by 'ee'
| | | .--> followed by a space or end-of-line
_|_ _|_ | |
/(?<=[aeo]\S*)ee\b/g
```
... and replace each match with `y`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 90 bytes
```
≔aeiouηFη≔⪫⪪θ⁺nι⁺gιθ⪫EE⪪θ ⎇∨⌕⮌ιi›²ΣEη№ιλι⁺…ι⊖Lιy⭆ι§⪪”&⌊↶k⊗3NH₂uXNSuï^Tζ ﹪﹪⮌≔↙Vs⟧;VDw”d⌕βλ
```
[Try it online!](https://tio.run/##PU9NT8QgEL3vryCcIKkXr3va1Gg0GjfWP0CZEYgssANd7a@v0O46CZlM3gfvaatIR@WX5ZCzM0FwhS5OvGNW7ndfkZiwkl2xl@iCGJJ3RZw7dvRTFjxUqpPydprbea7yI7lQNtWbSuv7V3PGK@sTKSiaxTuJRxdAfOAFKaNwFeOuMZ4IVUES9x0bptPqYTvWx6k6u4552ab@eQ3Qz9pjb2Nq4ANqwhOGgiBeMZhiq3Fj85mveyg1oWmelX0ozwHw9xqRK4KsCZKHGCFCTj9gPMyACNl60L7CHkYPwUAkGKE259Air03GLdtWVMr9spT47ViKQe2Wu4v/Aw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated string. Explanation:
```
≔aeiouη
```
Get the vowels separately as this saves a byte.
```
Fη≔⪫⪪θ⁺nι⁺gιθ
```
Loop over the vowels and change `n`s preceding a vowel to `g`s.
```
⪫EE⪪θ ...
```
With the input split into words,...
```
⎇∨⌕⮌ιi›²ΣEη№ιλι⁺…ι⊖Lιy
```
... if the word ends in an `i` and contains at least `2` vowels, then replace that `i` with a `y`, and...
```
⭆ι§⪪”...”d⌕βλ
```
... replace each letter in the word with a string from a look-up table, wrapping around after `p` to save space in the table.
The best I could do as an expression was 93 bytes:
```
⪫EE⪪S ⎇∨⌕⮌ιi›²ΣEaeiou№ιλι⁺…ι⊖Lιy⭆ι∨§⪪”&⌊∨<↨…¶№Pφ↔↖℅³⁰²¹↑|êG~3ψ⌊↓EÞ´”d⌕βλ§⪪nggl²№aeiouy§⁺ι ⊕μ
```
[Try it online!](https://tio.run/##XZDdSsQwEIXvfYqQqwTqzd56JRWlorhYXyDNDG1wmoRputqnr0l2lwUD@YFzOPOd2MmwDYb2/cjOJ/UanFfvJtbdR3JJdT6uqU9ZHpVuhBQyn1/I3vCmPlg9Ow/qE0/ICypXHK44XhhNQlaHRvTrXPOkQRdW2Yg2rHmWawTpshqRn0daF9VulrCdQiziE1rGGX1CUG/oxzTl@OKWm6z3GaokZ3cmeUydB/y9cEvDsFiGSBACBFjiD8AGiLBMBJaySDAQQGAYIFNJKNy1zlDRGvEv0Y8jZeNBXyucG23y5qw13PWbOn@rMGt9aVs0/bDvKXw7EYM3d/v9if4A "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated string. Explanation:
```
⪫EE⪪S
```
With the input split into words...
```
⎇∨⌕⮌ιi›²ΣEaeiou№ιλι⁺…ι⊖Lιy
```
... if the word ends in an `i` and contains at least `2` vowels, then replace that `i` with a `y`, ...
```
⭆ι∨§⪪”...”d⌕βλ
```
... replace each letter except `n` in the word with a string from a look-up table (wrapping around after `p` to save space in the table), ...
```
§⪪nggl²№aeiouy§⁺ι ⊕μ
```
... but replace `n` with either `ng` or `gl` depending on whether it is followed by a vowel.
[Answer]
# [Haskell](https://www.haskell.org) + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 152 bytes
```
v=cx<<zW(fpM<χ)
k=v"mnptkswlj"$Wr"bl gl b pl cl scr spw scl shl"
f=fo[pY$k,v"iuoae"$Wr"ee oo or ar o",pY'$"ng"<$χn,k<>pM"y"χi++pY f]
```
```
he<gc(mY$f++p_S)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5dSsQwFEbfu4rrJeAMU999SNzBQEFkKCKSaZM2Jk2u6Z-6gS5ChL6IO3AbfZ7dONh5Oh8cDnyfP7VsrXJuPl2ZhkLs4LWXzmijSsiicn2pkovIvvtO39yevgZRvHH-cdho2vNl2iZWDNh46mw7uhdkh4hHB5WDI5CDwkFbRGhpPPO8a4eJFjo8Us5sOqDpg1T_kVIQAoQIMkLAlPJrhr5CzpbJp5bf0R7fcZnMbkc56KekEg8jrxWvio1pM9BAz_fb9eRvI40XZUgAKAKDCrAJHlc5zyv_AA)
This is an approach using hgl's parser library, there may very well be a shorter way to write this using the regular library functions, but I wanted to put this part of the library to the test, since it needs improvement.
## Reflections
This does about how I would expect it to. However there are some holes here to be filled.
* I don't know why this keeps coming up without me fixing it: I need a function to take a parser and grab the first complete parse.
* There should be some way to split a string into substrings of a certain size. This would allow me to make `Wr"ee oo or ar o"` into `Wx2"eeoooraro"` and `Wr"bl gl pl cl scr spw scl shl b"` into `Fk"l"<"bgpc"++Wx3"scrspwsclshlb"`.
* A constant string enumerating the vowels would save bytes here, however with the above optimization, it would no longer be useful.
* There should be shortcuts for `fpM<χ` and `fpM<ʃ`, plus the bajillion variants that I could make of them.
* There should probably be a shortcut for `ʃ" "`. `p_S` works well enough in this case, but it could cost me later down the line.
* `isP` should have an infix.
* A function which combines `(<>)` an `pY` could probably be useful, since it's not uncommon to use them in tandem. If done right it could save a few bytes here.
* There should be a version of `isP` which runs both the parsers instead of dropping the separators.
* I have not implemented any sort of string compression algorithm. This would obviously be useful.
I [pushed a version](https://gitlab.com/WheatWizard/haskell-golfing-library/-/commit/09621e4a3856680eb510464e71b9a3693f19a376) with some of these improvements which in total takes of 27 bytes:
### 128 bytes
```
v=cx<<zWx
k=v"mntkswljp"$Fk"l"<"bgpc"<>Wx3"scrspwsclshlb"
f=k?<>v"iuoae"(Wx2"eeoooraro")<>?hhn"ng"<>(k<>hhi"y"++pY f)
```
```
gk$f>|+p_S
```
[Answer]
# [Python](https://www.python.org), 248 bytes
```
import re
def f(s,S=re.sub,r=''):
for w in S('gl(?![aeo])','ng',S('\S',lambda c:'spw///ee/shl/cl/scl/bl/gl/or/b//ar/scr/pl/oo/o'.split('/')[ord(c[0])%17],s)).split():r+=('ee'==w[-2:]and sum(map(w.count,'aeiou'))>2)and w[:-2]+'y 'or w+' '
return r
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBLrtsgFFWnXsXtoAIUJ7SZtIrkdBEZ5mWAbeLwHuYiwLKyii6gk0zaPbUr6bAX7AweEoj7O_ec8_O3v6cbusfj15Su229__pnRY0gQdNXrK1x5rE9N0Ls4tXVoGBOHCq4YYAbj4MTZYPn3j2el8SJYzdzAakq-nFht1dj2CroDi36WUmot483KzspIt7VysBKDbKVUgVJBeopRIttFb03iTDJxxtDz7vz5Ij59-XqpoxBrURzCpuFMa9Y083m7P1yU6yFOIx-V5_Ouw8mlmiltcGJCHPci1-fzYbu_bNgdWFawYcAqEpqm4CCs-n-s-uM9VlmnNU5nqRTvYuqN2wWter4SydXIsyd0rL6mGoIZbgmaMviUAtsjMFGafDAu8Vx8F5dRtj2ymizPkaDwxTGx0Hr8_TAlfDPg0amM5i2Gzt6hxTBYFSqnIpGkQo7ITa3dUPk8Qbm29FbOLA1aV6MBJA6ggcYKYEtpQBq1eRQQCkjBjjhra8CqWZEqMG8aUv6PBY_6aMzPGDMfelSOVIACBVp3FonuM5v3VBbJ0IyTPyOhKnhVjsDzGgMJR1ygSSWRKVQyzDPR2gU_vzd6Sw8BPynQ3mxQS7cigX6xZrWlLd4k7TyuTlKOGsmPV7WuzS0FebH_Pw)
Based off Arnauld's JS answer.
] |
[Question]
[
## Description
Your task is to implement a simple UNIX command parser and file system. Your program will have to implement a file system that can be modified via commands.
The starting directory of your file system is an empty root directory `/`, with no subdirectories or files. Your program must be capable of handling the following commands:
## Commands
`cd <dirpath>` - Change the current directory
* `<dirpath>` will be a list of directory names or "..", seperated by "/"
* e.g. `cd ../folder1/folder2` means to navigate up one directory level, then descend into `folder1`, then descend into `folder2`
* If the directory path is not valid, then the command will do nothing
`touch <filename>` - Create a new file
* e.g. `touch me.txt` creates a file called `me.txt` in the current directory
* Filenames will only contain characters a-z and "."
+ Filenames will contain "." at least once
+ "." will never be the first or last character in a file name
* If a file already exists with the same name in the current directory, nothing happens
`mkdir <dirname>` - Create a new directory
* e.g. `mkdir photos` creates a new `photos` directory in the current directory
* Directory names will only contan characters a-z
* If a directory already exists with the same name in the current directory, nothing happens
`rm [-r] <filename-or-dirname>` - Remove a file or directory
* e.g. `rm hello.mp3` removes a file named `hello.mp3` in the current directory
* e.g. `rm -r documents` removes a folder named `documents` in the current directory, and all of its contents
* If `rm` tries to delete a directory without the `-r` flag, nothing will happen
+ However `rm` will delete a file even with the `-r` flag
* If the specified directory or file cannot be found, nothing happens
## Tree output
Your program will output the following tree-like representation of the current file system using spaces as indentation. For example:
```
/
documents
document.docx
downloads
zippedfile
notavirus.exe
coolgoats.mp3
zippedfile.zip
pictures
myvacation.png
```
* ~~All directories names must end with a "/"~~ no longer necessary
* You may use any number of spaces to indent the tree (minimum 1)
* Directories must be listed before files in the same directory
* ~~Directories and files should be listed in lexographical alphabetical order~~
+ ~~The character "." lexographically comes before any alphabetical character~~
* You may output the contents of directories in any order you wish
## Challenge
Create a program that accepts a series of commands, and outputs a tree-like representation of the current file system.
**Input**
The first line of input will be an integer `N`. Following will be `N` lines, each containing a command as described above.
You may feel free to omit the number `N` from your input if it is not necessary
Slight variations are allowed (using commas to seperate commands, input as a list etc) as long as it's reasonable
**Output**
The contents of the current file system in a tree-like representation, as described above.
## Test Cases
Input 1: Simple example from earlier
```
15
mkdir documents
cd documents
touch document.docx
cd ..
mkdir downloads
cd downloads
touch coolgoats.mp3
touch zippedfile.zip
mkdir zippedfile
cd zippedfile
touch notavirus.exe
cd ../..
mkdir pictures
cd pictures
touch myvacation.png
```
Output 1:
```
/
documents
document.docx
downloads
zippedfile
notavirus.exe
coolgoats.mp3
zippedfile.zip
pictures
myvacation.png
```
Input 2:
Incorrect commands and edge cases
```
12
mkdir folder1
mkdir folder1
mkdir folder2
rm folder1
rm -r folder2
cd ..
cd ../folder1
cd folder1/folder2
touch file.txt
touch file.txt
touch file2.txt
rm -r file2.txt
```
Output 2:
```
/
folder1
file.txt
```
Input 3:
~~Alphabetical listing of directories and files~~ no longer necessary
```
8
mkdir b
mkdir c
mkdir a
touch c.txt
touch aa.txt
touch b.txt
touch a.txt
touch ab.txt
```
Output 3:
```
/
a
b
c
a.txt
aa.txt
ab.txt
b.txt
c.txt
```
Input 4:
Partially correct cd should not be parsed (Suggested by @Arnauld)
```
4
mkdir folder1
cd folder1
cd ../folder2
touch file.txt
```
Output 4:
```
/
folder1
file.txt
```
Input 5:
Partially correct cd should not be parsed (Suggested by @Abigail)
```
3
mkdir foo
cd bar/../foo
touch file.txt
```
Output 5:
```
/
foo
file.txt
```
Standard loopholes and I/O rules apply.
**This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins.**
**Edit:** output requirements have been relaxed a little bit
[Answer]
# [Python 2](https://docs.python.org/2/), ~~358~~ ... ~~280~~ 277 bytes
thanks to [randomdude999](https://codegolf.stackexchange.com/users/71803/randomdude999) for -3 bytes and a bugfix.
Input is a list of commands, where each command is represented by a 2-tuple as `(cmd, args)`. Test cases can be transformed using [this Retina program](https://tio.run/##K0otycxLNPz/X0NP215TAUhqcmmoqxiq6yioqxipa3Id2salo8CVEMcVzZWgwhX7/39udkpmkUJafj5XcopCUmKRvp6ePohXkl@anKGQlpmTqldSUQIA).
```
K=T={}
for c,a in input():
try:exec"T[a]=1|x=a<'.';if x or T[a]<2:del T[a[3*x:]]|T[a]=T.get(a,{'..':T})|E=T\nfor p in a.split('/'):E=E[p]\nT=E".split('|')[hash(c)%6]
except:1
def p(t,i):
for k in sorted(t,cmp,t.get,1):
if'..'<k:print i+k;t[k]>1!=p(t[k],i+' ')
p({'/':K},'')
```
[Try it online!](https://tio.run/##nZNNb6MwEIbPy69wK60MW5aIVOqBhr2xlx72wo1yMMYEiw9bxrRkk/z2rE1aAoSsVishMX6YeWfmBfhO5qxenzBLCfCBgBCeXvzQ3x@NjAmAbQRorS7eStPyDCDFziMdwfdhhGLfPXQ@2kAHPtMMdEAVaLxZeykpdRg9fuu8OD70yaGzJdJE9h46DvTCo3UI/PC11m24boKchpdUmnAFLS/wg4jHr3XoB/ef/ACtKEdNbmLr61NsANJhwqXnGinJADelTfWEWq/Qeg0TkqQK44rbUje3XZXwhWZ6gE3hcUFrCehD8SyjIv7h3vlKREU2fYAAWgY392oW7@VoQ2idlDOG8Z7TkoBQtER16s1QNwC0I0Bb2J96XQN8zAeCXz8DIZg4pyaCoOIUmbAqUiqgDWDKcFuRWjbQsoEJcboAJWtxPuaOCrpxgVqpP41k3@uSoXQmO4GDLGas3DIkG6fij7NnvynnJM3U4o4KZ10uD8dt5nTQqplEb1S0jaMsm46/utqAUyxbQSYLTNmgW@3eEEaSstrh9RZasTF2OGNlSoQ7k/8bXZ@pqK4Sz@i7AJPE6TsYVppUnukHWk3Khz16l2Un/x2vL/wy2oVPjUhmy@LZGc0/i4WmCC3AZClxiSVLY922adHP26bNZdm4PkFi1Wuw/6u/LlSKlx1v/IZ9VfwH "Python 2 – Try It Online")
### Explanation
```
K=T={}
```
The file system is represented by a dictionary, where `K` points to the root directory, and `T` points to the current directory. Each sub-directory contains a reference to its parent directory under the key `'..'`, which allows for easy execution of `cd ..`. Files are represented by the integer `1`.
```
for c,a in input():
try:exec"""<touch>|<rm>|<mkdir>|<cd>""".split('|')[hash(c)%4]
except:1
```
This loop executes the commands, the right code to execute is selected using the hash of the command (see table below). The execution is wrapped in `try/except` to catch exceptions that occur in invalid `cd` and `rm` calls.
```
┌───────┬──────────────────────┬─────────────┐
│ cmd │ hash(cmd) │ hash(cmd)%6 │
├───────┼──────────────────────┼─────────────┤
│ cd │ 12672076131114255 │ 3 │
│ mkdir │ -4476162622565762260 │ 2 │
│ rm │ 14592087666131641 │ 1 │
│ touch │ 7353934562497703448 │ 0 │
└───────┴──────────────────────┴─────────────┘
```
```
# touch
T[a]=1
```
Creates a new file called `a` in the current directory.
```
# rm
x=a<'.'
if x or T[a]<2:del T[a[3*x:]]
```
If `a` starts with `'-r'`, `x` is set to `True`. If `x` is True or we want to delete just a file (dicts are greater than integers in Python 2), the object can be deleted.
```
# mkdir
T[a]=T.get(a,{'..':T})
```
If the current directory already has an item called `a`, do nothing. Otherwise create a new subdirectory in the current directory with name `a` with a parent reference to the current directory.
```
# cd
E=T
for p in a.split('/'):E=E[p]
T=E
```
If p is equal to '..', `E['..']` points to the parent directory of `E`. Otherwise `E[p]` is the subdirectory `p` in `E`. The current directory is only updated if all steps have completed without error.
```
# Function that formats and prints the file system
# t - dictionary representing a part of the file system
# i - current indentation
def p(t,i):
# Iterate over the keys sorted ...
# ... on the values, where dicts (directories) ...
# ... are larger than `1` (files) ...
# ... and reverse
for k in sorted(t,cmp,t.get,1):
# if k is not 0 (a parent reference) ...
# print the name of k ...
# and, if k is a directory, call p recursively
if k:print i+k;t[k]>1!=p(t[k],i+' ')
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~133~~ 86 bytes
```
(for i;{
$i
[[ $PWD =~ , ]]||cd ->~/e
})
tree --dirsfirst|sed '$d;s#[^0-Z.]# #g;1c /'
```
*-2 bytes thanks to @Dom Hastings (removing spaces around `||`)*
*-6 bytes thanks to @Dom Hastings (removing `eval` before `$i` and using `#` as a sed delimiter)*
*-12 bytes thanks to @ilkkachu (combining the `sed`s).*
*-5 bytes thanks to @chepner (`=~`, `$PWD` and sed `c` command)*
Takes input where each argument is a command, e.g. `script 'mkdir A' 'cd A' 'touch B'`
Must be called from an empty directory with name containing `,`, such that this directory is the only directory containing `,` on the system.
The code itself is 85 bytes, +1 byte for specifying the directory name.
[Try it online!](https://tio.run/##VY7RTsQgEEXf@YpJ2GR101KNj41@iE3NIky7xBYI0N1Vq7@OaNmqyZDcOzPnMs/cH@L4IpWDgggJRbzqjANVv5ONIk0De3uSe7iHXbGDtp3ntFM@fFZIPq5JcIhQlgn2XXph9ihhu5G1p83TTfnIWgq0r289ZbSi2xjzT9KIaUQdfExp/wxj1aViMJM4rGOWxHlZWVNOejBc5pSLWTBhzNAbHjwb7V3uvSlrUXZqQJZkTvltfsf8cQujTeBH5SbP8IzrhZm1SoTJ4c8Bq1648fXIBQ/KaGZ1/wU "Bash – Try It Online").
**How it Works**
```
( # start a subshell
for i;do # for each argument
$i # run that command (rm [-r], touch, and mkdir
# behave exactly as specified)
# unfortunately cd can leave the directory, so...
if [[ $PWD != *,* ]];then # if we left the directory
# (i.e. the directory now no longer contains a comma)
cd - > ~/e # cd to the directory from before the command
# if this is successful, it outputs the new directory to stdout
# so, redirect stdout to a file we can edit
# piping to : didn't work without more bytes
# It would be nice to not have to do this, but
# redirecting the final `tree` output to a file included that file half the time
fi
done
) # end subshell, returning to the initial directory (corresponding to '/')
tree --dirsfirst # tree does most of the work for us
# outputs nearly the desired output, but it looks like
# .
# ├── A
# │ └── B.txt
# └── F
# 2 directories, 1 file
| sed '
$d; # remove the last line ("2 directories, 1 file")
s#[^0-Z.]# #g; # replace all characters that are not digits, letters, or '.' with a space
1c / # replace the initial '.' with a '/'
'
```
[Answer]
# JavaScript (ES6), ~~268 265 254~~ 248 bytes
Expects an array of strings. Returns a single linefeed-separated string.
```
a=>a.map(o=r=s=>([[c],s,e]=s.split` `,c>'m'?c>r?o[s]=1:o[e||+o[s]&&s]=0:c<'m'?o=s.split`/`.every(s=>o=o[s]-2?0:o[s],q=o)?o:q:o[s]=o[s]||{'..':o}))&(g=(o,i)=>[0,1].map(t=>{for(k in o)(v=o[k],t?v^1:v-2|k<S)||(S+=i+k,t||g(v,i+' '))}))(r,`
`,S=`/`)||S
```
[Try it online!](https://tio.run/##fVLLkpswELzzFZyMVMbyIzeywqfkBzh6nbIshFcxaLAkEztmv90RD2O2trJc1K3pnulR8ZtVzHAtSztTkIp7Ru@MxowUrERANTU0RpsN34YmFFtqiClzaXf@LuRxUARrHus1bMyWLiPYiLqeNmQycReLiL80ChhM8x0RldBX5HoCbYSz1XoRNSA8UcBriE4ta2t1fQsICSJ4x3iCDhRBKDGNN4twuW3TWRrfMtDo6EvlA0aVsx23oV1Xv5ZRNVvVx5cE1zVKplROj6Gt6wOqQjkN/ABj1xTpcOe5RRLqkjlhctfidJZaoCAzASZasPSnzEVyVRwtMLGQWC3VAeFuHxS8qlflhC7ED8bfkPFp7N883@egDOSC5HBAGTJPuRvsT30HZu4L8HfvHd@LYyq1nwI/F0JZ4/F0RCyc@dvAiQOXRkCI97D9UTmwtLc9SGfjAPkBmDWkKL/1d39lWYo0c2sRB/suz8umzYh1HgWWVVKfDREX0Y2fDwlKye1ZizbAgDtfca0YZ1aCIqU6eL0hgzwVevkFW3m6GAoOzp6FbvcuwkPhWA/nD1k3v93SXuz/6arl/YiB92H2/cn7kz2eddSEsRHZjwtjvB@3/Rz7wz6fwg82aHR7puetFr7WPQXO0dbHv42r/gM "JavaScript (Node.js) – Try It Online")
## How?
### Part 1: parse the commands and build the tree
The file tree is described by an object whose keys are the file names and whose values are:
* **0** for a deleted entry
* **1** for a file
* another object for a directory
Each directory (except the root) contains a default `..` entry pointing to the parent directory.
```
a.map( // main loop
o = // o is the current object
r = // r is the root object
s => ( // for each string s in a[]:
[[c], s, e] = // split it into c = first character of the command,
s.split` `, // s = first argument, e = second argument
c > 'm' ? // if c is greater than 'm':
c > r ? // if c is greater than 's':
o[s] = 1 // touch: create a file whose name is s
: // else:
o[ // rm:
e || // use e if it exists (meaning that -r was used)
+o[s] && s // or use s if o[s] is a file
] = 0 // mark this entry as deleted
: // else:
c < 'm' ? // if c is less than 'm':
o = // cd:
s.split`/` // split the path
.every(s => // for each string s in the path:
o = // update o:
o[s] - 2 ? // if o is a file or a deleted entry:
0 // abort
: // else:
o[s], // update o to o[s] (may be undefined)
q = o // q = backup of o
) ? // if all entries were truthy:
o // confirm the update
: // else:
q // restore o to q
: // else:
o[s] = o[s] || // mkdir: create a directory whose name is s,
{'..': o} // provided that it doesn't already exist
) //
) // end of map()
```
### Part 2: build the output string
```
( g = // g is a recursive function taking:
(o, i) => // o = current object, i = indentation string
[0, 1].map(t => { // for t = 0 and t = 1:
for(k in o) // for each key k in o:
( //
v = o[k], // v = value
t ? // if we are listing files:
v ^ 1 // abort if v is not equal to 1
: // else (listing directories):
v - 2 | // abort if v is a file or a deleted entry
k < S // or the directory name is '..'
) || ( // if the above test was falsy:
S += // append to S:
i + k, // indentation + key
t || // if we are listing directories:
g(v, i + ' ') // do a recursive call
) // implicit end of for()
}) // end of map()
)(r, `\n `, S = `/`) // initial call to g
```
] |
[Question]
[
Consider the following list:
```
expected = [
'A',
'B',
'AB',
'C',
'D',
'CD',
'ABCD',
'E',
'F',
'EF',
'G',
'H',
'GH',
'EFGH',
'ABCDEFGH',
'I',
'J',
'IJ',
'K',
'L',
'KL',
'IJKL',
'M',
'N',
'MN',
'O',
'P',
'OP',
'MNOP',
'IJKLMNOP',
'ABCDEFGHIJKLMNOP',
...
]
```
Here's one way to look at it - you're learning how to write Chinese characters and want to learn increasingly big chunks of them, rehearsing them as you go. You start with A, then go with B, then there's already a sequence that is a pair of two so you combine it. Then you go with C and D, make another pair, practice it. Then you rehearse: ABCD. Then the same goes with E up to H, then rehearse: ABCDEFGH. The list is infinite.
The goal is to generate and print out an n-th element of this list, indexes going up from zero. Assume that after 'Z', you get 'A' again.
The winning criteria is source code length.
[Answer]
# Python 2, 53 bytes
```
x,y=0,1
exec"x^=y-x;y+=x/y;"*input()
print range(x,y)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v0Kn0tZAx5ArtSI1WakizrZSt8K6Utu2Qr/SWkkrM6@gtERDk6ugKDOvRKEoMS89VQOoQfP/fyNLAA)
Similar to [this](https://codegolf.stackexchange.com/a/168966/15858) construction with the transformation `x = u-v`, `y = u`
[Answer]
# JavaScript (ES6), 59 bytes
We can save 2 bytes by making the sequence 1-indexed and using a simplification similar to the one [used by KSab](https://codegolf.stackexchange.com/a/168985/58563):
```
n=>(x=g=y=>n?g(y+=y==(x^=y-x),n--):x<y?[x++,...g(y)]:[])(1)
```
[Try it online!](https://tio.run/##DcpLCoMwEADQvaeY5Qz5UHFnHT2IWBBrgkUmoqUklJ49ze4t3mv@zNdybsfbSHiu2XEW7jGy58S9DB6TKmKMD04mkhZjqI1dGsaolLbWlkFTO06ENWUXThRgqO8g0DE0twKlCL4VwBLkCvtq9@BRNDgUouqX/w "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 61 bytes
Returns a list of non-wrapping integers.
```
n=>(g=v=>n?g(u&-u^v?v*2:!!u++,n--):v?[u-v,...g(v-1)]:[])(u=1)
```
[Try it online!](https://tio.run/##FcVBDoIwEADAO69YLmbX0kb0Vi19CMGEIG0kZGvA7sX49hrnMsso4z5tz9dbc3rMJbjCrsPoxHXsI@aDznfxcjzbus5KNaw1WfF91tIYYyKKbmmw/UCYXUslpA0ZHJyuwHCDy3@lCD4VwJR4T@ts1hSRGwjIRNW3/AA "JavaScript (Node.js) – Try It Online")
Based upon a construction by Donald Knuth. Related OEIS entry: [A182105](https://oeis.org/A182105).
### How?
This is a two-stage recursive function.
We first build the sequence \$(u\_n,v\_n)\$ defined as \$(u\_1,v\_1)=(1,1)\$ and:
$$(u\_{n+1},v\_{n+1})=\begin{cases}(u\_{n}+1,1),&\text{if }(u\_{n}\operatorname{AND}-u\_{n})=v\_{n}\\(u\_{n},2v\_{n}),&\text{otherwise}\end{cases}$$
During the second pass, we build the list \$[u\_n-v\_n,u\_n-v\_n+1,\dots,u\_n]\$ and eventually return it.
---
# JavaScript (ES6), 97 bytes
Returns wrapping uppercase letters.
```
n=>(s=i='',g=v=>(s+=String.fromCharCode(65+i++%26),n--)?g(u&-u^v?v*2:!!u++):s.substr(u-v,v))(u=1)
```
[Try it online!](https://tio.run/##FcqxDoIwFEDRna94DkprW6IYGdDKwCe4myDSWoOvpqVdjN9eYbq5yXl1sfO9M59JoH0MScmE8kK8NDLPuZZxGSavkzOoC@Xsu312rp0pqY7MMLYuK8pRCNpoEjYi3GITt2W9WgXGaO0LH@5@ciSIyCOlJMg9Tco6giBhdwKEMxyWzhq@GUBv0dtxKEarCXJQBCnNfukP "JavaScript (Node.js) – Try It Online")
Or [**91 bytes**](https://tio.run/##FcrLDoIwEEDRPV8xLJQZSwmPhAVa@Qj3JojQYMjU0MfG@O1VVjcnua8hDHbclreTbJ5TnFVkdUWrFpVluVZhh1BYlWIR4lC3VDhzc9vCGpuWcpaSeo3@KP099OFUd2nqhaDOFtY/rNvQy5AHIvSqojibDRkUlGdguECz93/DJwEYDVuzTsVqNHIOMzJR8o0/) in lowercase.
[Answer]
# [Python 2](https://docs.python.org/2/), 60 bytes
```
u=v=1
exec"v=u/v%2or 2*v;u+=1/v;"*input()
print range(u-v,u)
```
[Try it online!](https://tio.run/##FcxbCsIwEEbh938VoSBpq1Inbb2VLEYk2EBJQ8iMuvpoH8/3cOI3z2sw5T37xSm6u497aq0LW7GErSqx3MnOrEmZVibeW@pkqlofIue6QUw@ZJUe4eVqPsqBm7INTiAY9Bgw4owLrriB/kggA@pBA2j8AQ "Python 2 – Try It Online")
Based on [Arnauld's use of Knuth's construction](https://codegolf.stackexchange.com/a/168966/20260). The condition `u&-u==v` can be replaced with a simpler condition `u/v%2>0`, or alternatively `u&v>0`, since `v` is always a power of 2 that `u` is divisible by.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~80~~ 71 bytes
```
Range@#2+#-#2&@@Nest[If[#~BitAnd~-#==#2,{#+1,1},{#,2#2}]&@@#&,{1,1},#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8T8oMS891UHZSFtZV9lIzcHBL7W4JNozLVq5zimzxDEvpU5X2dZW2UinWlnbUMewFkjrGCkb1cYClSqr6VSDxZRj1f5rWnMFFGXmlUQrK@jaKaQ5AMUU9B0UwMZHG@gomBrE/gcA "Wolfram Language (Mathematica) – Try It Online")
Returns a list of integers instead of a wrapping string of alphabet. 0-indexed.
Uses [OEIS A182105](https://oeis.org/A182105), thanks to @Arnauld.
### Printing the list indefinitely, 54 bytes
```
Do[j=Range@i;#∣i&&Print@j[[-#;;]]&/@(2^j/2),{i,∞}]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n5OZa2tqYGD93yU/Oss2KDEvPdUh01r5UcfiTDW1gKLMvBKHrOhoXWVr69hYNX0HDaO4LH0jTZ3qTB2gztrY//8B "Wolfram Language (Mathematica) – Try It Online")
1-indexed. The TIO version has `lim` instead of `∞` to prevent crashes.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~93~~ ~~89~~ 82 bytes
```
def f(n):r=[];C=1;exec"p=C%2or 2*p;r+=[p];C=r.count(p);"*n;return range(C*p-p,C*p)
```
[Try it online!](https://tio.run/##NYxBCsIwEAC/shSEbKrS5GjIKc8IPUjdaC6bZUlBXx/rwctcZhj59FdjP8aDChTDeNOY15CiC/SmbZKYTr4peCtB55jl5/S6tZ27EQyT5aDUd2XQOz/JJCsXOR/EIVq5Qy6mzg6hHJcK9d@5ZcF1fAE "Python 2 – Try It Online")
Returns a list of integers. Similar to [Arnauld's Javascript approach](https://codegolf.stackexchange.com/a/168966/69880).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
1;ẎṀ+ƊẎQṭƊƊ¡ị@‘Ṿ
```
[Try it online!](https://tio.run/##y0rNyan8/9/Q@uGuvoc7G7SPdQEZgQ93rj3Wdazr0MKHu7sdHjXMeLhz33@gImMA "Jelly – Try It Online") TIO link works well up to and including \$13\$.
Full program. Prints `,`-separated list of integers.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~45~~ ~~42~~ 35 bytes
```
FN⊞υ⎇∧›Lυ¹⁼L§υ±¹L§υ±²⁺⊟υ⊟υ§αL⭆υκ⮌⊟υ
```
[Try it online!](https://tio.run/##dY0xD4JADIV3f8WNbYKJGDcmBmNMFIm4GYcTKhDhwHJH9NefB4qbQ/Oafu@9poXktJGVtbeGBWxVa3Rk6isxIIrYdAUYT5yIleQXhCqDDZPUDu9I5dpR9ITvZv0wsuqma6i3KqPnkI0od37wEZ3rL14ijoa4Mh3ETTv2ftQt58TUcGDYy3bIfFvuA1ogXhCDWcyl0pBoJ/lgO1JP3BH8Oqaf0hOlexVY66/svK/e "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. I couldn't find a simple formula to generate the result so I simply followed the procedure given in the question. Explanation:
```
FN
```
Repeat the given number `n` times.
```
⊞υ
```
Push the next element to the predefined empty array `u`, calculated as...
```
⎇∧›Lυ¹⁼L§υ±¹L§υ±²
```
... if there is more than one element in `u` and the last two elements have the same length...
```
⁺⊟υ⊟υ
```
... then append the penultimate element to the last element (which builds up the result in reverse order)...
```
§αL⭆υκ
```
... otherwise the next letter can be found by counting how many letters we've added so far and cyclically indexing into the predefined uppercase alphabet. (Taking either the sum of length or length of sum fails when the list is empty, and mapping the list into a string saves two bytes over special-casing an empty list.)
```
⮌⊟υ
```
Take the last element of `u`, which is the reversed `n`th element of the desired list, and implicitly print the reverse.
] |
[Question]
[
Given an array of non-negative integers, your task is to only keep certain elements of it, as described below.
* Let's say the array is `[1, 3, 2, 4, 11, 5, 2, 0, 13, 10, 1]`.
* First get the first element of the array, `n`. Keep the first `n` elements and discard the next one (discard the `n+1`th). The new array is `[1, 2, 4, 11, 5, 2, 0, 13, 10, 1]`.
* Then, you grab the element following the one removed and do the exact same thing. Reapplying the process, we get `[1, 2, 11, 5, 2, 0, 13, 10, 1]`
* You repeat the process until you arrive outside the array's bounds / there are no elements left in the array. We stop because `11` is higher than the length of the array.
* Now you should output the result.
Input / output may be taken / provided in any standard form. The array will never be empty, and will only contain non-negative integers. All standard loopholes are forbidden.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins!
---
# Test Cases
```
Input --> Output
[1, 2, 3, 4, 5] --> [1, 3, 4]
[6, 1, 0, 5, 6] --> [6, 1, 0, 5, 6]
[1, 3, 2, 4, 11, 5, 2, 0, 13, 10, 1] --> [1, 2, 11, 5, 2, 0, 13, 10, 1]
[2, 2, 2, 2, 2, 2] --> [2, 2]
[1, 2, 3, 1, 2, 3, 1, 2, 3] -> [1, 2]
[3, 1, 2, 4, 0] --> []*
```
\* The last test case involves `0`, so I decided to post the process such that it is clearer:
```
[3, 1, 2, 4, 0] --> [3, 1, 2, 0] --> [1, 2, 0] --> [1, 0] --> [0] --> [] )
```
([Inspired by this challenge](https://codegolf.stackexchange.com/q/136372) by [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer))
[Answer]
# JavaScript (ES6), 45 bytes
```
f=(a,k=0,x=a[k])=>1/x?f(a.splice(x,1)&&a,x):a
```
### Test cases
```
f=(a,k=0,x=a[k])=>1/x?f(a.splice(x,1)&&a,x):a
console.log(JSON.stringify(f([1, 2, 3, 4, 5]))) // --> [1, 3, 4]
console.log(JSON.stringify(f([6, 1, 0, 5, 6]))) // --> [6, 1, 0, 5, 6]
console.log(JSON.stringify(f([1, 3, 2, 4, 11, 5, 2, 0, 13, 10, 1]))) // --> [1, 2, 11, 5, 2, 0, 13, 10, 1]
console.log(JSON.stringify(f([2, 2, 2, 2, 2, 2]))) // --> [2, 2]
console.log(JSON.stringify(f([1, 2, 3, 1, 2, 3, 1, 2, 3]))) // -> [1, 2]
console.log(JSON.stringify(f([3, 1, 2, 4, 0]))) // --> []
```
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
`g.pure.(0:)` is an anonymous function taking and returning a list of `Int`s, use as `(g.pure.(0:))[1,2,3,4,5]`.
```
g.pure.(0:)
g(a,_:b:c)=g$splitAt b$a++b:c
g(a,_)=a
```
[Try it online!](https://tio.run/##XYxNC4JAEIbv@ysG8uDiurhWHgQPEuElwksnk1ht/aDVxA86RL/dthUKgoGZ93lmpuLDTUg5P@0VHMJjdAqjPeziGFb2C6GG121Qt6PoeT4aUyvrVgy04Z05VPcHLWgv@BVTjREqgvNc0m7qBTUdH6PS5OTiZ36Og9IYOlmP4QiZwS1LscXigM9zwgi4BNYENgS2KUo8Ago5KhDwVGZautozprGrPVOYfbpacjX81XK3/P0flPsG9dNJ0Rs "Haskell – Try It Online")
# How it works
* The function `g` takes a tuple argument representing a split list. `a` is the list of initial elements kept at the previous step, `_` is the element to be discarded, `b` is the next element to be used as a length, and `c` is the remaining elements.
+ If there are enough elements in the second part of the tuple to select a `b`, then a new split is performed and `g` recurses. Otherwise, it halts with `a` as the result.
* The anonymous function `g.pure.(0:)` starts it all by calling `g` with the tuple `([],0:l)`, where `l` is the input and `0` gets immediately discarded by `g`.
+ `pure` here uses the `Applicative` instance for (binary) tuples, and with the result type `([Int],[Int])` conveniently puts its argument as the second element in a tuple with `[]` as first element.
[Answer]
# [Python 3](https://docs.python.org/3/), 59 bytes
```
f=lambda a,i=0:f(a[:a[i]]+a[a[i]+1:],a[i])if i<len(a)else a
```
[Try it online!](https://tio.run/##VY3BDgIhDETvfkWPkO1hC7oH4n4J4VAjRBLEje7Fr0fAREPSZJp5M@323m@PrEsJa@L75crAGNfZBMHWsI3OTWybTmQctkXGAPGcfBYsfXp54LI9Y95FEJYQFIJGOCKcnJSHH1kQKpyrjbAMhHpB9Q5RD6iepGpT0yGuOv7PAHX/8r01V1I@ "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 51 bytes
```
f s=s%s
s%(n:_)|(x,_:z)<-splitAt n s=(x++z)%z
s%_=s
```
[Try it online!](https://tio.run/##dY7BCoMwEETvfsVcBMUtmNh6kObQ75AQPFQqtUEaDyL99zQmrWKhsLCbmbeTvTXmfu17a1sYYWITmTjRlUpfyUSqmtPzwQx9N15GaAckU5bNaTw7SgljH02nITA8Oz2ijtCiZgROKAhHwklCCC8tb0keKAlOyJ1LKAOwl@ibU/gol8OYt7hnmJPZ0tdw/pcIUdwbW4VFP9H@5t9h@@JDrpa7Kg@uhLRv "Haskell – Try It Online") Example usage: `f [1,2,3,4,5]`.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 32 bytes
```
1∘{n∇⍣(n≤≢w)⊢w←⍵/⍨(n←1+⍺⊃⍵)≠⍳≢⍵}
```
## Explanation
```
1∘{ } bind 1 as starting left argument (⍺)
⍳≢⍵ generate indexes for right argument (⍵)
(n←1+⍺⊃⍵) n is 1+item at position ⍺
w←⍵/⍨ ≠ w is ⍵ with item at n removed
n∇⍣(n≤≢w)⊢ recurse with n as left and w as right arg if n <= length of w
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v/f8FHHjOq8Rx3tj3oXa@Q96lzyqHNRueajrkXlj9omPOrdqv@odwVQvG2Cofaj3l2PupqBYpqPOhc86t0MVAnk1FLDDEMFIwVjBSQSAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# Java 8, 68 bytes
This lambda accepts a mutable `List<Integer>` (supports `remove(int)`, e.g. `ArrayList`). Output is mutated input. Assign to `Consumer<List<Integer>>`.
```
l->{for(int i=0,f=0;i<l.size();f^=1)i=f>0?l.remove(i)*0+i:l.get(i);}
```
[Try It Online](https://tio.run/##dZJfa4MwFMWf7ae4j7rZoG7rQ62O0afB9tTH0kFmo9w2Rkmioyt@dhf/tG6FQUD9nRNzjtcDrem8KJk47I9tWX1yTCDhVCl4pyjgPLNKiTXVDJSm2ogpCsrhYLaRSiMnaSUSjYUg60KoKmdyNWlvqPTqVWiWMRnHkMoi2xyxhKjl8/icFtJGoQEjz00jL8QVJwq/me2E6UfkOxilsffMiWR5UTMbnTvvHpecZEybh7BprXBm4g2Zx3R1gXvITXJ7oyWKbLsDKjPldEWsMcl2Z2hCFVMQgWBf8Jt3PuvsuxC48ODCowtPjduzhQsGewa4sBiZ35uC3uf7vRT0Ht9gv7uOxqAXpjXtH865vRn1KzDv93rWdJ0t8@nAvsYGujZtYDmUGrpa/0wBzFCH1pPhRUp6@uOyb0RFqOoMdn@S44TdCZdxEpokrDQzEQPfnJRmOSkqTcy/IzQXF6mZmdW0Pw)
The control flow for this problem is very annoying. Each iteration we have to remove an element and get the element at the next position, and both of these operations require a range check (and either may trigger program completion). One strategy is to carry out both operations in a single loop iteration, with the index update guarded by its own range check. Another strategy, which turned out to be shorter, is to alternate between the operations each loop iteration, which is what this solution does.
[Answer]
# Pyth, 18 bytes
```
#IgZlQB .(Q=Z@QZ)Q
```
[Try it here.](http://pyth.herokuapp.com/?code=%23IgZlQB+.%28Q%3DZ%40QZ%29Q&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%2C+4%2C+5%5D%0A%5B6%2C+1%2C+0%2C+5%2C+6%5D%0A%5B1%2C+3%2C+2%2C+4%2C+11%2C+5%2C+2%2C+0%2C+13%2C+10%2C+1%5D%0A%5B2%2C+2%2C+2%2C+2%2C+2%2C+2%5D%0A%5B1%2C+2%2C+3%2C+1%2C+2%2C+3%2C+1%2C+2%2C+3%5D%0A%5B3%2C+1%2C+2%2C+4%2C+0%5D&debug=0)
[Answer]
# [Perl 5](https://www.perl.org/), 38 + 1 (-a) = 39 bytes
```
splice@F,$p=$F[$p],1while$p<@F;say"@F"
```
[Try it online!](https://tio.run/##K0gtyjH9/7@4ICczOdXBTUelwFbFLVqlIFbHsDwjMydVpcDGwc26OLFSycFN6f9/IwUU@C@/oCQzP6/4v66vqZ6BocF/3UQA "Perl 5 – Try It Online")
[Answer]
**Haskell, 99 bytes (88 without indentation)**
```
f x y
|y>=l=f x$l-1
|e>=l=x
|True=f (take e x ++ drop (1+e) x) e
where e=x!!y
l=length x
```
[Answer]
# VI, 31 25 bytes
```
O@0kdd<C-v><C-a>Y<C-v><C-x>gg@a<Esc>"add<C-a>Y<C-x>@a
```
`<C-?>` corresponds to `Control + ?`, and `<Esc>` to `Escape` obviously. Each of these count for 1 byte (see [meta](https://codegolf.meta.stackexchange.com/questions/8995/how-should-vim-answers-be-scored)).
## Input
The input file should contain 1 integer per line + 1 blank line at the end, example :
```
1
2
3
4
5
```
We can see each line of the input file as an array element, such as `1 :: 2 :: 3 :: 4 :: 5 :: []`, like in some languages (caml for example).
## Launch
You can start vi with the following command, and type the solution stroke by stroke :
```
vi -u NONE input
```
You can also use this one-liner :
```
vi -u NONE -c ':exec "norm O@0kdd\<C-v>\<C-a>Y\<C-v>\<C-x>gg@a\<Esc>\"add\<C-a>Y\<C-x>@a"' -c ":w output" -c ':q' input
```
This should produce a file `output` with the correct result from an input file `input`.
## Explanations
To introduce the solution, I will first present a 19-bytes solution working only for arrays without 0. This solution uses a recursive macro, used with little modification in the final solution :
```
Yqa@0ddYgg@aquggY@a
```
### Explanation of a partial solution
```
Y # yank first line (first integer + line break) to "0 register
qa # start recording a macro ("a register)
@0 # jump n lines, where n is the content of the "0 register
dd # delete the current line (n+1th line)
Y # yank current line (integer after the previously deleted line)
gg # go back to the first line
@a # recurse on macro "a"
q # finish recording the macro
u # cancel modifications done by the execution of the macro
gg # go back to the first line
Y@a # apply the recorded macro with first parameter equal to the first integer
```
The trick here is to use the `"0` register to store the current integer (and the line break, very important). Therefore, the command `@0` allows to jump `n` lines (call `n` the value of `"0`). If the jump exceeds the number of lines in the file, the macro will fail, so the program will stop (outside of the array bounds, as required).
But this solution does not work if the input contains `0`. Indeed, if `"0` register value equals `0`, then `@0` will jump one line (due to the line break), not `0` as we liked. So the next command (`dd`) won't delete the 0th integer, but the 1st (not correct).
A valid solution to handle the `0` is to always increment the integer before yanking it, and decrement it just after. Thus, the `@0` command will jump `n+1` lines (`n` is the current integer that have been incremented). A `k` command is then necessary to go to line `n` (previous line). Using this trick, a blank line is needed at the end of the input file, to avoid jumping outside of the array (thus, terminating the program), since we now always jump `n+1` lines, before jumping to the previous line.
### Explanation of the final solution
```
O # insert a new line at the beginning of the file, enter insert mode to write the macro content
@0 # jump n lines
k # go to the previous line
dd # delete this line
<C-v><C-a> # type Control+A (C-v is needed because we are in insert mode) to increment the current integer
Y # yank the incremented integer
<C-v><C-x> # decrement the current integer
gg # go to the first line
@a # recurse on macro "a"
<Esc> # exit insert mode : at this step, the first line of the file contains the macro content @0kdd^AY^Xgg@a
"add # copy @0kdd^AY^Xgg@a line to the register "a and delete the line
<C-a> # increment the first integer
Y # yank it (into "0)
<C-x> # decrement the first integer
@a # apply macro in a" (initial @0 will jump n+1 lines, since we incremented the first integer before calling the macro)
```
Writing the macro content inside the file before registering it allows to save a few bytes :
* avoids to write `qa...q` and undo all changes after registering
* avoids `:let @a="..."`)
## Edits
**#1**
* write the macro content on the first line (instead of last line)
* change input (1 blank line at the end)
* add one-liner to test in command-line
[Answer]
# Pyth, 32 bytes
```
VlQIgNlQBK@QNI!K=QYBIgKlQB.(QK;Q
```
[Try it online](http://pyth.herokuapp.com/?code=VlQIgNlQBK%40QNI%21K%3DQYBIgKlQB.%28QK%3BQ&input=%5B1%2C+2%2C+3%2C+4%2C+5%5D&debug=0)
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 74 bytes
```
n=>{for(int i=n[0];i<n.Count;){n.RemoveAt(i);i=i<n.Count?n[i]:n.Count+1;}}
```
[Try it online!](https://tio.run/##jVCxTsMwEJ3jrzh1ctQQUdhwkqrq0AUGYGCoOjjmCCelZ8l2g6LI3x7cFiFG3nCnu3fv6emMvzHW4XzyxB28jj7gUQlheu09PItJQIIPOpCBwdI7PGlimcOVOGNjAlmurtJya/seLxtf7pDRkSkfyYeKODQNdFDDzHUzfVgn0wqo5v3tQVHFSXrioPKJyxc82gE3QVKuqP7l1rynw8PPsFypGGclskE7aGvGL/hPhGlV3BX3xZ8ak0cn2zy1FAq1@ZRnyxGIoc1Flm2Tke2xfHMUUI7LBSzScUzM5Qcizt8 "C# (.NET Core) – Try It Online")
This takes in a list of ints and modifies it. I have seen some Java answers that skirt around imports by using the fully qualified name in the Lambda argument definition. If this is not allowed, I can remove this answer.
[Answer]
# [R](https://www.r-project.org/), ~~64~~ 53 bytes
```
f=function(a,i=1,d=a[i]+1)"if"(is.na(d),a,f(a[-d],d))
```
Recursive function. Has one mandatory input, `a`, the list to skip over. `i` is the index of the number of things to jump over (defaults to `1`), and `d` is the index of the next item after the required value has been removed, which is also the index of the item to be removed. Returns `numeric(0)`, an empty vector, for empty output.
[Try it online!](https://tio.run/##PYzNCsMwDIPve4rQk820UqftMU9SejANBl8y2M/zZ2nXDR3EJyQ9arVk77K9/F5I4UmQky6@XoU7t4782RelzFAY6XLLKzJzNdpIEEaEiDAhSIP5gKFBi2V35su3GDFiwnxyxF9nsg9@V0O7/wA "R – Try It Online")
Ungolfed:
```
f <- function(a, i = 1, d = a[i] + 1) {
if(is.na(d)) { # d is NA if and only if a[i] is out of bounds
a
} else {
f( a[-d], d, a[d] + 1 ) # a[-d] is a with the item at index d removed
}
}
```
] |
[Question]
[
A simple FizzBuzz using strings.
**Given**
* 1 word or phrase (string)
* 2 unique characters
**Output**
The word or phrase with each occurrence of the first character replaced with fizz and each of the second character replaced with buzz
**Rules**
* The first letter in both Fizz and Buzz must remain capitalized
* For the rest of the words fizz and buzz, you must match the case of the replaced character (if no case then keep lowercase)
* If given characters are not in the phrase, output the original phrase
**Test Cases**
```
Given: Hello, h, l
Output: FIZZeBuzzBuzzo
Given: test, a, b
Output: test
Given: PCG rocks!, , !
PCGFizzrocksBuzz
Given: This
Is
SPARTA!,
, S
Output: ThiBuzzFizzIBuzzFizzBUZZPARTA!
Given: FizzBuzz, a, b
Output: FizzBUZZuzz
```
This is code-golf so the shortest code, in bytes, wins!
**Note**
Technically handling the newline case (This Is SPARTA!) is a part of the challenge. However, I will not void an answer for not including it, as it is very challenging or even impossible in some languages.
[Answer]
## [Python 3](https://docs.python.org/3.6/), ~~180~~ ~~174~~ ~~168~~ ~~160~~ 152 bytes
```
from sys import*
J=''.join
L=str.lower
s,a,b=J(stdin).split(', ')
print(J('FBFBiuIUzzZZzzZZ'[L(k)==L(b)::2][k!=L(k)::2]*(L(k)in L(a+b))or k for k in s))
```
This is just a more golfed version of [Stephen](https://codegolf.stackexchange.com/a/113295/39211)'s answer, in Python 3. This chips away 42% of his bytes. Python 2 would save one byte on the print, but such is the price of progress. This handles newlines properly.
Thanks to Blckknight for saving 8 bytes on input.
[Answer]
# Python, 109 bytes
```
lambda s,w:"".join([c,"Fizz","Buzz","BUZZ","FIZZ"][-~w.lower().find(c.lower())*-~(-2*c.isupper())]for c in s)
```
[Try it online!](https://tio.run/nexus/python3#PY47D4JAEIT7@xXLVnvkoLA0sVATlcSC@GhECjwhniJHOAyJhX8dj/NR7E5mstlvismxL7P76ZyBEd0YMbxqVVEiBS7U84kCZ4@P7A8HK4vISpoEry4sdZc3xMNCVWeSP8v94EXByJehMo@6dlFa6AYkqAoM79vctAYmkBCu8rLU9ulljVwQxvMlNFrejIcCEDwbArka3w7Zyd0h7i7KsMiwbTzd7KaeTYQdtrWLp2ygDZQB6GhjBnWjqpYGx3@mIN/5f8D7Nw "Python 3 – TIO Nexus")
---
Takes the two characters as a single string
*Edit:
Added testcase to TIO link, newline works too*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œl=€⁹Œl¤ȧ€"“¡Ṭ4“Ụp»o"/ȯ"Œu⁹Œln$T¤¦
```
**[Try it online!](https://tio.run/nexus/jelly#@390Uo7to6Y1jxp3AlmHlpxYDuQoPWqYc2jhw51rTICMh7uXFBzana@kf2K90tFJpRCFeSohh5YcWvb//3@u4P8hGZnFXJ7FXMEBjkEhjooA "Jelly – TIO Nexus")**
### How?
```
Œl=€⁹Œl¤ȧ€"“¡Ṭ4“Ụp»o"/ȯ"Œu⁹Œln$T¤¦ - Main link: characters, string
Œl - lowercase the characters
¤ - nilad followed by link(s) as a nilad:
⁹ - right argument, the string
Œl - lowercase
=€ - equals (vectorises) for €ach (a list of 2 lists that identify the indexes of the string matching the characters regardless of case)
“¡Ṭ4“Ụp» - dictionary strings ["Fizz", "Buzz"]
" - zip with
ȧ€ - logical and (non-vectorising) for €ach (replace the 1s with the words)
/ - reduce with:
" - zip with:
o - logical or (vectorises) (make one list of zeros and the words)
- implicit right argument, string
" - zip with:
ȯ - logical or (non-vectorising) (replace the zeros with the original characters from the string)
¦ - apply...
Œu - uppercase
- ...to the indexes (the words at indexes):
¤ - nilad followed by link(s) as a nilad:
⁹ - right argument, the string
$ - last two links as a monad (i.e. the string on both sides):
Œl - lowercase
n - not equals (vectorises)
T - truthy indexes (the indexes of the capital letters in the string)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 271, 261 bytes
```
import fileinput as f
a=''
for m in f.input():a+=m
a=a.split(', ')
l=L=list(a[0])
for i in range(0,len(a[0])):
j,k=l[i].lower(),l[i].istitle()
if j==a[1].lower():
L[i]='FIZZ'if k else'Fizz'
elif j==a[2].lower():
L[i]='BUZZ'if k else'Buzz'
print''.join(L)
```
[Try it online!](https://tio.run/nexus/python2#bcwxC8IwEIbhPb/itkswlOooZHEQhK4uLQ4RErl6TUuaIvjna1pRENxyvN@Tmbqhjwk8saMwTAnsCF5Ygyh8H6EDCuCLNUm1txvT5WiLcWBKEjWgEmwqwzQmaZvyolZGC4s23JwsNbvwTmovoNV3ww1dCu4fLkql1yNrSuykEkAeWmNss/1OsoIqrwweT3WNeXAHx6PDIz2fKPL7Y3Z/zOH8Yw7TYoZIISEWbU9BVmqel6@WpMFquL4A "Python 2 – TIO Nexus")
Wow this one was a doozie! It turns out python won't accept multi-line inputs so `fileinput` must be used.
edit: should pass all cases now :)
[Answer]
# MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~106~~ ~~102~~ 111 bytes
```
@(a,b,c)regexprep(a,num2cell([lower([b c]) upper([b c]) '1234']),{'2','4','1','3','FIZZ','Fizz','BUZZ','Buzz'})
```
This could probably be optimised further.
It uses a simple Regex replacement. However an intermediate step is required by replacing the input characters with numbers first. This is so that if the second input replace letter was contained in `Fizz` that the `Fizz` doesn't then get replaced when the next regex is performed.
This of course assumes there are no numbers in the input. However given the question says the input is a word or phrase I feel that this is an acceptable assumption.
The code will handle new lines in the input correctly.
You can [Try it online!](https://tio.run/nexus/octave#RY2xCsIwFEV/5W0vgQwm7QdIB1FwdWnIkMaHFmIbUoJS8dvjq4vD4XKGe2/dC68GFWSmG71SpsQ@lYcJFKOwcX5SFnaA4CSUlP6C2jQtOqneaFBhy2imYQ6nvt9iXFeO7vKzrrB9ZPXTIiweeX1G0DvA8zjRAj4T@LjdXdEpvHMjoqxf "Octave – TIO Nexus")
[Answer]
# Bash 4.4 + GNU sed, ~~70~~ ~~228~~ ~~222~~ 227 bytes
```
IFS=;alias e=echo;K=`sed $([[ $2 != '
' ]]&&e "s/${2,}/Fizz/g;s/${2^}/FIZZ/g"||:)$([[ $3 != '
' ]]&&e ";s/${3,}/Buzz/g;s/${3^}/BUZZ/g"||:)<<<"$1"`;[[ $2 = '
'||$3 = '
' ]]&&e ${K//$'\n'/`[[ $2 = '
' ]]&&e Fizz||e Buzz`}||e "$K"
```
Apparently `alias e=echo` throws an error if referenced in Bash 4.3 or below, the version TIO is apparently using. Therefore, the longer and equivalent Bash 4.3 code is given in the below TIO test suite for the sake of testing. This passes all of the test cases, so that is nice.
[Try it online!](https://tio.run/nexus/bash#Zc69CoMwFAXgPU8RQzAttITqqA46COJSql20SooVddEhdNH42J3TqP3DjgfO/c6VgR85VugwXt4g3qQpxAbUHEgAgVmm62VRdxBxigdjN1K/6XtaWXPMVQyShFZIiKWFtgtg/gPziakE7/4RTCV455Vg2zbCB8Ss5ZPZEUKRKxEPIaWYXFpC2U/1W5hefbHTJhvfGzhEUsq4bjgIOIiO7il2NQlk9Gi7fXEt6vIJ "Bash – TIO Nexus")
[Answer]
## JavaScript (ES6), 92 bytes
Takes input as a string and an array of two characters. Supports newlines.
```
f=(s,[a,b],r='Fizz')=>a?f(s.replace(RegExp(a,'gi'),m=>m<'a'?r.toUpperCase():r),[b],'Buzz'):s
```
### Test cases
```
f=(s,[a,b],r='Fizz')=>a?f(s.replace(RegExp(a,'gi'),m=>m<'a'?r.toUpperCase():r),[b],'Buzz'):s
console.log(f("Hello", ['h', 'l']))
console.log(f("test", ['a', 'b']))
console.log(f("PCG rocks!", [' ', '!']))
console.log(f(`This
Is
SPARTA!`, [`
`, 'S']))
console.log(f("FizzBuzz", ['a', 'b']))
```
[Answer]
## [GNU sed](https://www.gnu.org/software/sed/), 135 + 1(r flag) = 136 bytes
By default, a sed script is executed as many times as there are input lines. To handle multi-line input, I use a loop to append all possible remaining lines to the first, without starting a new cycle.
```
:r
$!N
$!br
s:, (.), (.):;\u\1FIZZ;\l\1Fizz;\u\2BUZZ;\l\2Buzz:
s:^:,:
:
s:,(.)(.*;\1)(...)(.):\3,\4\2\3\4:
s:,(.):\1,:
/,;.F/!t
s:,.*::
```
**[Try it online!](https://tio.run/nexus/sed#NYuxCoMwEED3fEWEDirXSKLTZdJBcCml2kWODp0MlFoSXfLxTZOWDnf3eNwLaNkhO8W5W@YQeC6K70JNO8l@mGdNjwjG@2RUd/0Z1e3eY0xuCMgSQKxyUWqS8YjEBVIN1JCimpr/C5KMQQVa9FW2JSlKxBCmxTg2ODae28vUZsAZ8PG9vjazPl042g8)**
The replacement table used on line 4, needs to be in that exact order, i.e. 'Fizz' and 'Buzz' after their upper-case forms. This is because the sed regex `.*`, used during the table lookup, is greedy. If the current char needed to be replaced is not a letter (no case), then the lowercase string is needed (matched last).
Since sed has no data types, I use a character delimiter to iterate a string. It will mark my current position and in a loop I shift it from left to right. Fortunately, I can use `,` for this, since it is the input data delimiter.
**Explanation:**
```
:r # reading loop
$!N # append next input line
$!br # repeat till EOF
s:, (.), (.):;\u\1FIZZ;\l\1Fizz;\u\2BUZZ;\l\2Buzz: # create replacement table
s:^:,: # append my string delimiter
: # main loop
s:,(.)(.*;\1)(...)(.):\3,\4\2\3\4: # apply char replacement, if any
s:,(.):\1,: # shift delimiter to right
/,;.F/!t # repeat till end of string
s:,.*:: # print only the final string
```
[Answer]
# Pyth - 25 bytes
```
sXzsrBQ1scL2rB"FizzBuzz"1
```
[Test Suite](http://pyth.herokuapp.com/?code=sXzsrBQ1scL2rB%22FizzBuzz%221&test_suite=1&test_suite_input=%22hl%22%0AHello%0A%22ab%22%0Atest%0A%22+%21%22%0APCG+rocks%21%0A%22ab%22%0AFizzBuzz&debug=0&input_size=2).
[Answer]
# Haskell, 114 bytes
```
u=Data.Char.toUpper
p[f,b]x|f==u x="Fizz"|b==u x="Buzz"|2>1=[x]
q x y|u y<y=x|2>1=u<$>x
r x=concatMap$q=<<p(u<$>x)
```
`r` takes the fizz and buzz characters as a 2 element list as the first argument, and the input string as the second argument. Newlines and unicode should be handled appropriately, although the function is unfortunately not total (allowing for invalid inputs saved 5 bytes).
[Answer]
# Mathematica, 94 bytes
```
a=ToLowerCase;b=ToUpperCase;StringReplace@{a@#->"Fizz",b@#->"FIZZ",a@#2->"Buzz",b@#2->"BUZZ"}&
```
Anonymous function. Takes two strings as input and returns a function which takes a string as input and returns a string as output as output. It must be called in the format `prog["c1", "c2"]["s"]`, where `"s"` is the target string and `"c1"` and `"c2"` are the two characters. Could probably be golfed further.
] |
[Question]
[
## Interpret loose ranges
[ListSharp](https://github.com/timopomer/ListSharp) is an interpreted programming language that has many features, one of those features is a 1 index based range creator that works like this:
You define a range as `(INT) TO (INT)` or just `(INT)` where both or the single int can go from min to [max int32 value](https://en.wikipedia.org/wiki/2147483647_(number))
Then you can use those ranges to extract elements of an array without fearing to overstep it's boundaries
---
**therefore:**
`1 TO 5` generates: `{1,2,3,4,5}`
`3` generates: `{3}`
Ranges can be added up using the `AND` operator
`1 TO 5 AND 3 TO 6` generates: `{1,2,3,4,5,3,4,5,6}`
remember this works with negative numbers as well
`3 TO -3` generates: `{3,2,1,0,-1,-2,-3}`
---
# The challenge is the following:
## Input
A character array and the previously defined range clause as a string
## Output
The elements at the 1 index based locations of the range (non existing/negative indexes translate to an empty character)
---
# How to win
As a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge you are supposed to create the program with the shortest byte count to win
---
### It has been pointed out empty characters do not exist, therefore you should be ignoring them (I only showed them here to make it easier to understand yet it confused people)
## Test cases:
```
input array is:
{'H','e','l','l','o',' ','W','o','r','l','d'}
range clause:
"1 TO 3" => "Hel"
"5" => "o"
"-10 TO 10" => "Hello Worl"
"0 AND 2 AND 4" => "el"
"8 TO 3" => "oW oll"
"-300 AND 300" => ""
"1 TO 3 AND 3 TO 1" => "HelleH"
"-20 TO 0 AND 1 AND 4" => "Hl"
```
[Answer]
# Python 2 - 239 211 210 bytes
Thanks to [@mbomb007](https://codegolf.stackexchange.com/users/34718/mbomb007) and [@Cyoce](https://codegolf.stackexchange.com/users/41042/cyoce) for further golfing this solution!
```
def r(s):
t=[]
for x in s.split("AND"):
if"T"in x:a=map(int,x.split("TO"));b=2*(a[0]<a[1])-1;t+=range(a[0],a[1]+b,b)
else:t+=int(x),
return t
lambda p,v:[(['']+p+['']*max(map(abs,r(v))))[x]for x in r(v)]
```
Straight-forward approach. Tried generators and a recursive version, but they couldn't beat the simple for each loop. I'm a golfing noob, so this can most likely be improved quite a bit. Also, the major flaw of this snippet is that the range as a list object is computed again each time an element is retrieved from the character array (see last line, list comprehension). This means `r(s)` is executed `len(r(s)) + 1` times.
### Ungolfed code:
```
def find_range(string):
result = []
# Split at each AND and look at each element separately
for element in string.split("AND"):
# Element is just a number, so add that number to the result list
if "TO" not in string:
result += [int(string)]
# Generate a list with all the values in between the boundaries
# (and the boundaries themselves, of course) and append it to the result list
else:
boundaries = map(int, string.split("TO"))
ascending = boundaries[0] < boundaries[1]
# range(start, stop, step) returns [start, ..., stop - 1], so extend the stop value accordingly
# range(8, 3, 1) returns just [], so choose respective step (negative for a descending sequence)
result += range(boundaries[0], boundaries[1] + (1 if ascending else -1), 1 if ascending else -1)
# Make the char array 1-indexed by appending an empty char in 0th position
# Add enough empty chars at the end so too large and negative values won't wrap around
interpret = lambda chars, range_expr: [(['']+chars+['']*max(map(abs, find_range(range_expr))))[x] for x in find_range(range_expr)]
```
### Test cases:
```
c = list("Hello World")
print interpret(c, "1 TO 3")
print interpret(c, "5")
print interpret(c, "-10 TO 10")
print interpret(c, "0 AND 2 AND 4")
print interpret(c, "8 TO 3")
print interpret(c, "-300 AND 300")
```
### Output:
```
['H', 'e', 'l']
['o']
['', '', '', '', '', '', '', '', '', '', '', 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l']
['', 'e', 'l']
['o', 'W', ' ', 'o', 'l', 'l']
['', '']
```
[Answer]
# Scala, 165 bytes
```
(s:String,r:String)=>r split "AND"map(_ split "TO"map(_.trim.toInt))flatMap{case Array(a,b)=>if(a<b)a to b else a to(b,-1)
case x=>x}map(i=>s lift(i-1)getOrElse "")
```
Explanation:
```
(s:String,r:String)=> //define a function
r split "AND" //split the range expression at every occurance of "AND"
map( //map each part...
_ split "TO" //split at to
map( //for each of these splitted parts, map them to...
_.trim.toInt //trim all whitespace and parse as an int
)
) //now we have an Array[Array[Int]]
flatMap{ //map each inner Array...
case Array(a,b)=>if(a<b)a to b else a to(b,-1) //if it has two elements, create a Range
case x=>x //otherwise just return it
} //and flatten, so we get an Array[Int]
map(i=> //for each int
s lift(i-1) //try to get the char with index i-1, since Scala is zero-based
getOrElse "" //otherwise return ""
)
```
[Answer]
# Groovy (~~99~~ 97 Bytes)
```
{n,v->Eval.me("[${n.replaceAll(" TO ","..").replaceAll(" AND ",",")}]").flatten().collect{v[it]}}
```
Try it here: <https://groovyconsole.appspot.com/edit/5155820207603712>
Explanation:
* `.replaceAll(" TO ","..")` - Replace the to with a traditional range.
* `.replaceAll(" AND ", ",")` - Replace all ands with a comma.
* `"[${...}]"` - Surround it with the "list" notation in Groovy.
* `Eval.me(...)` - Evaluate string as Groovy code.
* `.flatten()` - Flatten the mixture of 2D array and 1D array into a 1D array.
* `.collect{v[it]}` - Collect the indices from the array into a single structure.
Here's a ~~115~~ 113 byte solution removing nulls from the output:
<https://groovyconsole.appspot.com/edit/5185924841340928>
Here's a 117 byte solution if you say it MUST be indexed at 1 instead of 0:
<https://groovyconsole.appspot.com/edit/5205468955803648>
If you want me to swap out the original for the 113/117 byte one, let me know.
[Answer]
# C#, 342 bytes
```
a=>r=>{var s=r.Replace(" AND","").Replace(" TO ","|").Split();int b=a.Length,i=0,n,m,j,o;var c=new List<char>();for(;i<s.Length;){var d=s[i++].Split('|');if(d.Length<2)c.Add(b<(n=int.Parse(d[0]))||n<1?' ':a[n-1]);else{o=(m=int.Parse(d[0]))<(n=int.Parse(d[1]))?1:-1;for(j=m;o>0?j<=n:j>=n;j+=o)c.Add(b<j||j<1?' ':a[j-1]);}}return c.ToArray();};
```
Ungolfed method:
```
static char[] f(char[] a, string r)
{
var s=r.Replace(" AND","").Replace(" TO ","|").Split();
int b=a.Length,i=0,n,m,j,o;
var c=new List<char>();
for(;i<s.Length;)
{
var d=s[i++].Split('|');
if(d.Length<2)
c.Add(b<(n=int.Parse(d[0]))||n<1?' ':a[n-1]);
else
{
o=(m=int.Parse(d[0]))<(n=int.Parse(d[1]))?1:-1;
for(j=m;o>0?j<=n:j>=n;j+=o)
c.Add(b<j||j<1?' ':a[j-1]);
}
}
return c.ToArray();
}
```
Full program with test cases:
```
using System;
using System.Collections.Generic;
namespace InterpretLooseRanges
{
class Program
{
static void PrintCharArray(char[] a)
{
for (int i=0; i<a.Length; i++)
Console.Write(a[i]);
Console.WriteLine();
}
static void Main(string[] args)
{
Func<char[],Func<string,char[]>>f= a=>r=>{var s=r.Replace(" AND","").Replace(" TO ","|").Split();int b=a.Length,i=0,n,m,j,o;var c=new List<char>();for(;i<s.Length;){var d=s[i++].Split('|');if(d.Length<2)c.Add(b<(n=int.Parse(d[0]))||n<1?' ':a[n-1]);else{o=(m=int.Parse(d[0]))<(n=int.Parse(d[1]))?1:-1;for(j=m;o>0?j<=n:j>=n;j+=o)c.Add(b<j||j<1?' ':a[j-1]);}}return c.ToArray();};
char[] ar = {'H','e','l','l','o',' ','W','o','r','l','d'};
PrintCharArray(f(ar)("1 TO 3"));
PrintCharArray(f(ar)("5"));
PrintCharArray(f(ar)("-10 TO 10"));
PrintCharArray(f(ar)("0 AND 2 AND 4"));
PrintCharArray(f(ar)("8 TO 3"));
PrintCharArray(f(ar)("-300 AND 300"));
}
}
}
```
A naive solution, using a char list, which uses `' '` as an empty character and gets the job done. Hoping to improve soon.
[Answer]
# Python 2, ~~156~~ 155 bytes
My answer has some similar ideas as 1Darco1's [answer](https://codegolf.stackexchange.com/a/94959/34718), but by using a different approach from the start (string slicing rather than lists), it ended up quite a bit shorter. It would be four bytes shorter if 0-indexing was allowed.
```
s,r=input()
o=""
for x in r.split("AND"):
i=map(int,x.split("TO"));d=2*(i[0]<i[-1])-1
for _ in-1,0:i[_]-=11**9*(i[_]<0)
o+=s[i[0]-1:i[-1]+d-1:d]
print o
```
[**Try it online**](http://ideone.com/Kstubh)
Fortunately, I can parse strings containing spaces into integers. Negative indexing in Python indexes from the end of the string, so I use `i[-1]` to either be the same as `i[0]` or the second value, if there is one. Then I have to adjust any negative range values to *more* negative, so they won't mess with the slicing. Multiplying negative values by `11**9` (`2357947691`) will account for ranges using integer min value. Then, simply slice the string, using reverse slice if the range is reversed.
### With zero-indexing (151 bytes):
```
s,r=input()
o=""
for x in r.split("AND"):
i=map(int,x.split("TO"));d=2*(i[0]<i[-1])-1
for _ in-1,0:i[_]-=11**9*(i[_]<0)
o+=s[i[0]:i[-1]+d:d]
print o
```
[Answer]
# R, 142 bytes
Assuming I understood the challenge correctly, here I am assuming that `r` is the pre-defined range clause in string format, and that the input array ("Hello world", in the examples) is read from stdin.
```
r=eval(parse(t=paste("c(",gsub("AND",",",gsub("TO",":",r)),")")))
o=strsplit(readline(),e<-"")[[1]][r[r>0]]
o[is.na(o)]=e
c(rep(e,sum(r<1)),o)
```
Some test cases:
```
r="1 TO 3"
[1] "H" "e" "l"
r="5"
[1] "o"
r="-10 TO 10"
[1] "" "" "" "" "" "" "" "" "" "" "" "H" "e" "l" "l" "o" " " "w" "o" "r" "l"
r="0 AND 2 AND 4"
[1] "" "e" "l"
r="8 TO 3"
[1] "o" "w" " " "o" "l" "l"
r="-300 AND 300"
[1] "" ""
```
## Ungolfed/explained
### Line 1
```
r=eval(parse(t=paste("c(",gsub("AND",",",gsub("TO",":",r)),")")))
```
R has a nice infix operator `:` which generates sequences. `1:5` gives `[1, 2, 3, 4, 5]`, and `0:-2` gives `[0, -1, -2]`. So, we replace the `TO` in the loose range clause with `:`.
```
gsub("TO",":",r)
```
Interpreting `AND` is just concatenation. We can use the function `c` for that, which handily is able to take an arbitrary number of arguments, comma-separated. So we replace `AND` with `,`
```
gsub("AND",",", ... )
```
and then wrap the whole thing in `c(`, `)`.
```
paste("c(", ... ,")")
```
This yields a character string that could look like `c( 1 : 5 , 7 )`. We call `parse` to convert to type "expression" and then `eval` to evaluate the expression. The resulting sequence of numbers is then re-assigned to the variable `r`.
```
r=eval(parse(t= ... ))
```
### Line 2
```
o=strsplit(readline(),e<-"")[[1]][r[r>0]]
```
Now for the ugly part - dealing with strings in R, which gets messy quickly. First we define `e` to be an empty string (we will need this later).
```
e<-""
```
We read from stdin and convert the character string to an array of individual characters by splitting at the empty string. (E.g. we go from "Hi" to ["H", "i"].) This returns a list of length 1, so we have to ask for the first element `[[1]]` to get an array that we can work with. Ugh, I warned you this was messy.
```
strsplit(readline(), ... )[[1]]
```
R indexes beginning at 1, and has a nice feature with negative numbers. Suppose `x` is `['a', 'b', 'c']`. Calling `x[1]` unsurprisingly returns `'a'`. Calling `x[-1]` returns all of `x` *except* index `1`, i.e. `['b', 'c']`. This is a cool feature, but means that we have to be careful with our negative indices for this problem. So for now, we just return the elements of the input array with index `>0`, and assign the result to `o`.
```
o= ... [r[r>0]]
```
### Line 3
However, there's a problem! For indices that are greater than the length of the array, R just returns `NA` values. We need it to return empty strings. So we redefine the elements of `o` for which `is.na(o)` is `TRUE` to be the empty string.
```
o[is.na(o)]=e
```
### Line 4
```
c(rep(e,sum(r<1)),o)
```
Finally, how do we deal with the negative (and zero) indices? They all need to return the empty string, so we repeat the empty string N times, where N is the number of indices that are `<1`.
```
rep(e,sum(r<1))
```
Finally, we concatenate the previously-defined `o` to this (potentially empty) list.
```
c( ... ,o)
```
[Answer]
# JavaScript (ES6), 141
Unnamed function with 2 parameters, the first being the character array (can be a string either), the second the string containing the range definition.
The return value is an array where each element can either be a single character or the js value `undefined`. When stringified, this result in a sequence of comma separated chars having undefined shown as the "empty" char - as the test cases in the first version of the question.
Using `.join` you can get a string result similar to the test case output in the current version of the question.
```
(l,r,u,z=[])=>(r+' E').replace(/\S+/g,x=>x>'T'?u=t:x>'A'?[...Array((t-(w=(u=u||t)-(d=+u<t?1:-1)-1)-1)*d)].map(_=>z.push(l[w+=d]),u=0):t=x)&&z
```
*Less golfed*
```
(
l, r, // input paramaters, array/string and string
u, // local variable start at 'undefined'
z=[] // local variable, will contain the ouput
) =>
(r+' E') // add an end marker
.replace( /\S+/g, x=> // execute for each nonspace substring
x > 'T' // check if 'TO'
? u = t // if 'TO' save first value in u (it's a string so even 0 is a truthy value)
: x > 'A' // check if 'AND' or 'E'
? (
u = u||t, // if u is falsy, it's a single value range t -> t
d = +u < t ? 1 :-1, // direction of range up or down,comparison has to be numeric, so the leading +
w = u - d - 1, // starting value (decrement by 1 as js array are 0 based)
u = 0, // set u to falsy again for next round
[...Array((t - w - 1) * d)] // build the array of required number of elements
.map(_ => z.push(l[w+=d])) // iterate adding elements of l to z
)
: t = x // if not a keyword, save value in t
) && z // return output in z
```
**Test**
```
f=
(l,r,u,z=[])=>(r+' E').replace(/\S+/g,x=>x>'T'?u=t:x>'A'?[...Array((t-(w=(u=u||t)-(d=+u<t?1:-1)-1)-1)*d)].map(_=>z.push(l[w+=d]),u=0):t=x)&&z
function run(x)
{
R.value=x;
O.textContent=f(L.value,x)
}
run("10 TO 5 AND 5 TO 10")
```
```
<table>
<tr><td>Base string</td><td><input id=L value="Hello World"></td></tr>
<tr><td>Custom range</td><td><input id=R ><button onclick='run(R.value)'>-></button></td></tr>
<tr><td>Output</td><td><pre id=O></pre></td></tr>
<tr><td>Test case ranges</td><td>
<select id=T onchange='run(this.value)'>
<option/>
<option value="1 TO 3">1 TO 3 => {'H','e','l'}</option>
<option value="5">5 => {'o'}</option>
<option value="-10 TO 10">-10 TO 10 => {'','','','','','','','','','','','H','e','l','l','o',' ','W','o','r','l'}</option>
<option value="0 AND 2 AND 4">0 AND 2 AND 4 => {'','e','l'}
"8 TO 3" => {'o','W',' ','o','l','l'}</option>
<option value="-300 AND 300">-300 AND 300 => {'',''}</option>
<option value="1 TO 3 AND 3 TO 1">1 TO 3 AND 3 TO 1 => "HelleH"</option>
<option value="-20 TO 0 AND 1 AND 4">-20 TO 0 AND 1 AND 4 => "Hl"</option>
</select>
</td></tr>
</table>
```
[Answer]
# Perl - 110 bytes
Calling the script in the command line with the string as the first argument, and the range as the second.
```
for(split AND,pop@ARGV){$_>0?print+(split//,"@ARGV")[$_-1]:0for(/(.+)TO(.+)/?($1>$2?reverse$2..$1:$1..$2):$_)}
```
De-obfuscated :
```
for $subrange (split 'AND', $ARGV[1]) {
for $index ($subrange =~ /(.+)TO(.+)/
? ($1 > $2 ? reverse $2..$1 : $1..$2) # All indices of that range
: $subrange) # Otherwise, an index only
{
if ($index > 0) {
# Here, 'split' returns an array of all characters
print((split //, $ARGV[0])[$index - 1]);
}
}
}
```
[Answer]
# Python 2, 146 bytes
```
lambda s,a:[a[i]for x in[map(int,c.split('TO'))for c in s.split('AND')]for i in range(x[0]-1,x[-1]-2*(x[-1]<x[0]),1-2*(x[-1]<x[0]))if 0<=i<len(a)]
```
All tests are at **[ideone](http://ideone.com/lfqbBP)**
Splits the clause, `s`, on "AND", splits each of the resulting sub-clauses on "TO", converts the resulting strings to `int` using `map`. The results will each have either 1 or 2 items (1 if no "TO" was present in the sub-clause).
Constructs 0-based ranges for each of these using the step parameter of range as 1 or -1 by inspection of the values at indexes 0 and -1 (a list with one entry has that entry at both indexes).
Runs through these ranges and constructs a list of the output, if the indexes provided are in-range (`if 0<=i<len(a)`).
[Answer]
**Clojure ~~232~~ ~~230~~ 229 bytes**
Oh what a monster I have created... But actually this was 260 when I was about to submit it.
Edit: removed a space from `#(get r %_"")`, `(if_(< f t)` and `(take-nth 2_%)` (indicated as `_`).
```
(let[S clojure.string/split](fn[r s](apply str(map #(get r %"")(mapcat #(apply(fn([f][(dec f)])([f t](if(< f t)(range(dec f)t)(reverse(range(dec t)f)))))%)(map #(mapv read-string(take-nth 2%))(map #(S % #" ")(S s #" AND "))))))))
```
Less golfed:
```
(def f (let[S clojure.string/split]
(fn[r s] (->> (map #(S % #" ") (S s #" AND "))
(map #(mapv read-string (take-nth 2 %)))
(mapcat #(apply(fn
([f][(dec f)])
([f t](if (< f t)
(range (dec f) t)
(reverse (range (dec t) f))))) %))
(map #(get r % ""))
(apply str)))))
```
Uses `clojure.string/split` to split by " AND " and " ", `take-nth` drops "TO" between integers, function argument matching handles the case of 1 or 2 arguments and that is about it.
Calling convention: `(f "Hello World" "1 TO 3 AND 2 AND 8 TO 2")`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~28 27 25~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-3 Thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)
```
ḟØẎṣ”Aṣ€”OVr/€FfJ}ị
```
A dyadic Link accepting the range clause on the left and the array on the right (both as lists of characters) that yields the resulting list of characters.
**[TryItOnline](https://tio.run/##y0rNyan8///hjvmHZzzc1fdw5@JHDXMdQVTTGiDLP6xIH8hyS/Oqfbi7@//h5UBO5P//SoYKIf4Kxko6CkqmIELX0AAkYGgA4hgoOPq5KBiBSROQgAVcsa6xAUQWSIP4EGMgImADwIqMwIZBFBpCjfmv5AF0ab5CeH5RTooSAA "Jelly – Try It Online")**
How?
```
ḟØẎṣ”Aṣ€”OVr/€FfJ}ị - Link: range-clause, C; array, W
ØẎ - upper-case consonants ['B','C','D','F',...,'Z']
ḟ - filter remove (from C) (i.e. TO->O, AND->A)
ṣ”A - split at 'A's
ṣ€”O - split each at 'O's e.g. [["-1","2"],["7"]]
V - evaluate as Jelly code [[-1,2],[7]]
/€ - rescue each by:
r - inclusive range [[-1,0,1,2],[7]]
F - flatten [-1,0,1,2,7]
J} - range of length (of W)
f - filter keep (those of F that are in bounds of W)
ị - index into (W)
```
[Answer]
# Scala, 151 bytes
```
_.split(" AND ").flatMap{case s"$a TO $b"=>a.toInt-1 to(b.toInt-1,(b.toInt-a.toInt).sign);case x=>Seq(x.toInt-1)}flatMap _.map("".+).orElse{case _=>""}
```
[Try it in Scastie!](https://scastie.scala-lang.org/tIFCQNV4R8eDkwoeAFs7Bg)
] |
[Question]
[
Given a list of paths, output the correct path.
Example of path:
```
/\
----+/
|
```
* `-` and `|` are horizontal and vertical paths.
* `/` and `\` are 90° turns.
* `+` is treated as a `-` or a `|` depending of the current direction.
Paths may go in any direction and a character may be used in multiple paths.
Input will be like this:
```
/--\
A------+--+--#
B------/ \--:
C------------#
D------------#
```
* `A`, `B`, `C` and `D` are path starts
* `#` is a wall (the path is bad)
* `:` is the end (the path is correct)
So here the output will be `B`.
You can assume:
* `:` and `#` will always be reached from the left.
* The character at the right of the start of a path will always be `-`.
* Paths will always be well formed.
* `#` and `:` will always be in the same column.
* There will always be only one `:` and 4 paths.
## Test cases
```
A------#
B------#
C------#
D------:
=>
D
```
```
A-\ /---:
B-+-/ /-#
C-+---+-#
D-+---/
\-----#
=>
B
```
```
/-\
A-+\\---#
B-/\-\/-#
C----++-#
D----+/
\--:
=>
A
```
```
A-\
B-+\
C-++\/----#
D-+++//---:
\++-//--#
\+--//-#
\---/
=>
A
```
```
/-\
A-+-/-\
B-+-+-\--#
C-+-/ |/-#
D-\---++-#
\---+/
\--:
=>
B
```
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer win.
[Answer]
## [Slip](https://github.com/Sp3000/Slip/wiki), 47 bytes
```
`a(?,[`-+]*((`/<|`\>)[`|+]*(`/>|`\<)[`-+]*)*`:)
```
[Test it here.](https://slip-online.herokuapp.com/?code=%60a%28%3F%2C%5B%60-%2B%5D%2a%28%28%60%2F%3C%7C%60%5C%3E%29%5B%60%7C%2B%5D%2a%28%60%2F%3E%7C%60%5C%3C%29%5B%60-%2B%5D%2a%29%2a%60%3A%29&input=%20%20%2F-%5C%0AA-%2B-%2F-%5C%0AB-%2B-%2B-%5C--%23%0AC-%2B-%2F%20%7C%2F-%23%0AD-%5C---%2B%2B-%23%0A%20%20%5C---%2B%2F%0A%20%20%20%20%20%20%5C--%3A&config=)
Yay for undocumented features...
### Explanation
Slip is basically a two dimensional regex syntax and by default Slip programs print the subset of the input that they matched. In this case I'm simply matching a valid path. To prevent printing the entire path, I'm usng the undocumented `(?,...)` groups which simply indicate that the characters matched inside should be omitted from the output.
As for the regex, unfortunately, there's some duplication because `\` and `/` need to be treated differently depending on whether we're moving horizontally or vertically. On the plus side, since we know that the path starts and ends horizontally, we know that there's an even number of `\` or `/` in every path, so that we can match two of them at a time.
```
`a # Match a letter.
(?, # Match but don't include in output...
[`-+]* # Match a horizontal piece of path, consisting of - or +.
( # Match 0 or more vertical segments...
(`/<|`\>) # Match a / and turn left, or a \ and turn right.
[`|+]* # Match a vertical piece of path, consisting of | or +.
(`/>|`\<) # Match a / and turn right, or a \ and turn left.
[`-+]* # Match a horizontal piece of path, consisting of - or +.
)*
`: # Match a : to ensure that this is the correct path.
)
```
[Answer]
# Python, 221 bytes
```
def P(s,c=""):
l=s.split("\n")
v=[0,-1]
p=[(i,l[i].index(":"))for i in range(len(l))if":"in l[i]][0]
while c in"-:|+/\\":
p=map(sum,zip(p,v))
c=l[p[0]][p[1]]
v=v[::1-(c=="\\")*2]
if"/"==c:v=[-v[1],-v[0]]
return c
```
The first indention is just one space, in the while loop it's a tab.
[Answer]
# Javascript (ES6), ~~117~~ 104 bytes
```
p=>(r=d=>(c="\\/ABCD".indexOf(p[x+=[-1,-w,w,1][d]])+1)>2?p[x]:r(d^c))(0,w=p.indexOf`
`+1,x=p.indexOf`:`)
```
Test cases:
```
let f =
p=>(r=d=>(c="\\/ABCD".indexOf(p[x+=[-1,-w,w,1][d]])+1)>2?p[x]:r(d^c))(0,w=p.indexOf`
`+1,x=p.indexOf`:`)
var p0 = 'A------#\nB------#\nC------#\nD------:',
p1 = 'A-\\ /---:\nB-+-/ /-#\nC-+---+-#\nD-+---/ \n \\-----#',
p2 = ' /-\\ \nA-+\\\\---#\nB-/\\-\\/-#\nC----++-#\nD----+/ \n \\--:',
p3 = 'A-\\ \nB-+\\ \nC-++\\/----#\nD-+++//---:\n \\++-//--#\n \\+--//-#\n \\---/ ',
p4 = ' /-\\ \nA-+-/-\\ \nB-+-+-\\--#\nC-+-/ |/-#\nD-\\---++-#\n \\---+/ \n \\--:';
console.log(p0, '=>', f(p0));
console.log(p1, '=>', f(p1));
console.log(p2, '=>', f(p2));
console.log(p3, '=>', f(p3));
console.log(p4, '=>', f(p4));
```
[Answer]
# Ruby, 140 bytes
```
->s{(?A..?D).find{|l,c|x=h=1
v=0
y=s[/.*#{l}/m].count$/
(v,h=c==?/?[-h,-v]:c==?\\?[h,v]:[v,h]
y+=v
x+=h)until(c=s.lines[y][x])=~/(:)|#/
$1}}
```
Try it on repl.it: <https://repl.it/CyJv>
## Ungolfed
```
->s{
(?A..?D).find {|l,c|
x = h = 1
v = 0
y = s[/.*#{l}/m].count $/
( v, h = c == ?/ ? [-h,-v] : c == ?\\ ? [h,v] : [v,h]
y += v
x += h
) until (c = s.lines[y][x]) =~ /(:)|#/
$1
}
}
```
[Answer]
# Perl 211 Bytes
```
sub f{for($s=-1;++$s<~~@_;){if($_[$s][0]ne' '){$r=$s;$c=$m=0;$n=1;while($_[$r][$c]ne'#'){if($_[$r][$c]eq':'){return$_[$s][0];}($m,$n)=$_[$r][$c]eq'/'?(-$n,-$m):$_[$r][$c]eq'\\'?($n,$m):($m,$n);$r+=$m;$c+=$n;}}}}
```
Ungolfed:
```
sub q{
for($start = -1; ++$start <~~@_;) {
if($_[$start][0] ne ' ') {
$row = $start;
$col = $rowMove = 0;
$colMove = 1;
while($_[$row][$col] ne '#') {
if($_[$row][$col] eq ':') {
return $_[$start][0];
}
($rowMove, $colMove) = $_[$row][$col] eq '/' ? (-$colMove,-$rowMove) :
$_[$row][$col] eq '\\' ? ($colMove,$rowMove) :
($rowMove, $colMove);
$row += $rowMove;
$col += $colMove;
}
}
}
}
```
This is my first Perl golf, so suggestions are welcome :)
] |
[Question]
[
Executive summary: test whether an input sequence of integers is "admissible", meaning that it doesn't cover all residue classes for any modulus.
## What is an "admissible" sequence?
Given an integer m ≥ 2, the *residue classes modulo m* are just the m possible arithmetic progressions of common difference m. For example, when m=4, the 4 residue classes modulo 4 are
```
..., -8, -4, 0, 4, 8, 12, ...
..., -7, -3, 1, 5, 9, 13, ...
..., -6, -2, 2, 6, 10, 14, ...
..., -5, -1, 3, 7, 11, 15, ...
```
The kth residue class consists of all the integers whose remainder upon dividing by m equals k. (as long as one defines "remainder" correctly for negative integers)
A sequence of integers a1, a2, ..., ak is *admissible modulo m* if it fails to intersect at least one of the residue classes. For example, {0, 1, 2, 3} and {-4, 5, 14, 23} are *not* admissible modulo 4, but {0, 1, 2, 4} and {0, 1, 5, 9} and {0, 1, 2, -3} *are* admissible modulo 4. Also, {0, 1, 2, 3, 4} is *not* admissible modulo 4, while {0, 1, 2} *is* admissible modulo 4.
Finally, a sequence of integers is simply *admissible* if it is admissible modulo m for every integer m ≥ 2.
## The challenge
Write a program or function that takes a sequence of integers as input, and returns a (consistent) Truthy value if the sequence is admissible and a (consistent) Falsy value if the sequence is not admissible.
The input sequence of integers can be in any reasonable format. You may assume that the input sequence has at least two integers. (You may also assume that the input integers are distinct if you want, though it probably doesn't help.) You must be able to handle positive and negative integers (and 0).
Usual [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") scoring: the shortest answer, in bytes, wins.
### Sample input
The following input sequences should each give a Truthy value:
```
0 2
-1 1
-100 -200
0 2 6
0 2 6 8
0 2 6 8 12
0 4 6 10 12
-60 0 60 120 180
0 2 6 8 12 26
11 13 17 19 23 29 31
-11 -13 -17 -19 -23 -29 -31
```
The following input sequences should each give a Falsy value:
```
0 1
-1 4
-100 -201
0 2 4
0 2 6 10
0 2 6 8 14
7 11 13 17 19 23 29
-60 0 60 120 180 240 300
```
### Tips
* Note that any sequence of 3 or fewer integers is automatically admissible modulo 4. More generally, a sequence of length k is automatically admissible modulo m when m > k. It follows that testing for admissibility really only requires checking a finite number of m.
* Note also that 2 divides 4, and that any sequence that is admissible modulo 2 (that is, all even or all odd) is automatically admissible modulo 4. More generally, if m divides n and a sequence is admissible modulo m, then it is automatically admissible modulo n. To check admissibility, it therefore suffices to consider only prime m if you wish.
* If a1, a2, ..., ak is an admissible sequence, then a1+c, a2+c, ..., ak+c is also admissible for any integer c (positive or negative).
## Mathematical relevance (optional reading)
Let a1, a2, ..., ak be a sequence of integers. Suppose that there are infinitely many integers n such that n+a1, n+a2, ..., n+ak are all prime. Then it's easy to show that a1, a2, ..., ak must be admissible. Indeed, suppose that a1, a2, ..., ak is not admissible, and let m be a number such that a1, a2, ..., ak is not admissible modulo m. Then no matter what n we choose, one of the numbers n+a1, n+a2, ..., n+ak must be a multiple of m, hence cannot be prime.
The *prime k-tuples conjecture* is the converse of this statement, which is still a wide open problem in number theory: it asserts that if a1, a2, ..., ak is an admissible sequence (or *k-tuple*), then there should be infinitely many integers n such that n+a1, n+a2, ..., n+ak are all prime. For example, the admissible sequence 0, 2 yields the statement that there should be infinitely many integers n such that both n and n+2 are prime, this is the *twin primes conjecture* (still unproved).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~25~~ ~~24~~ 19 bytes
**5 bytes thanks to Karl Napf.**
```
~~lybb'(eM-yA,?:[M]z:%aodA)~~
~~l:2'(eM-yA,?:[M]z:%aodA)~~
l:2'(eMg:?rz:%adlM)
```
[Try it online!](http://brachylog.tryitonline.net/#code=bDoyJyhlTWc6P3J6OiVhZGxNKQ&input=WzA6Mjo2OjEwXQ)
[Verify all testcases!](http://brachylog.tryitonline.net/#code=Ons6MiZgMS47MC59YXcKbDoyJyhlTWc6P3J6OiVhZGxNKQ&input=W1swOjJdOltfMToxXTpbXzEwMDpfMjAwXTpbMDoyOjZdOlswOjI6Njo4XTpbMDoyOjY6ODoxMl06WzA6NDo2OjEwOjEyXTpbXzYwOjA6NjA6MTIwOjE4MF06WzA6Mjo2Ojg6MTI6MjZdOlsxMToxMzoxNzoxOToyMzoyOTozMV06W18xMTpfMTM6XzE3Ol8xOTpfMjM6XzI5Ol8zMV06WzA6MV06W18xOjRdOltfMTAwOl8yMDFdOlswOjI6NF06WzA6Mjo2OjEwXTpbMDoyOjY6ODoxNF06W182MDowOjYwOjEyMDoxODA6MjQwOjMwMF06Wzc6MTE6MTM6MTc6MTk6MjM6MjldXQ)
```
l:2'(eMg:?rz:%adlM)
l:2 Temp = [2:length(input)]
'( ) true if the following cannot be proven:
eM M is an element of the interval
indicated by Temp, i.e. from 2
to the length of input inclusive,
g:?rz:%adlM every element of input modulo M
de-duplicated has length M.
```
[Answer]
# Jelly, 10 bytes
```
JḊðḶḟ%@ð€Ạ
```
[Try it online!](http://jelly.tryitonline.net/#code=SuG4isOw4bi24bifJUDDsOKCrOG6oA&input=&args=LTExLC0xMywtMTcsLTE5LC0yMywtMjksLTMx) or [run all test cases](http://jelly.tryitonline.net/#code=SuG4isOw4bi24bifJUDDsOKCrOG6oArFkuG5mMK1TDQwX-KBtng7CsOHO-KAnCAtPiDigJ07w5HCteKCrFk&input=&args=W1swLDJdLFstMSwxXSxbLTEwMCwtMjAwXSxbMCwyLDZdLFswLDIsNiw4XSxbMCwyLDYsOCwxMl0sWzAsNCw2LDEwLDEyXSxbMCwyLDYsOCwxMiwyNl0sWzExLDEzLDE3LDE5LDIzLDI5LDMxXSxbLTExLC0xMywtMTcsLTE5LC0yMywtMjksLTMxXSxbMCwxXSxbLTEsNF0sWy0xMDAsLTIwMV0sWzAsMiw0XSxbMCwyLDYsMTBdLFswLDIsNiw4LDE0XSxbNywxMSwxMywxNywxOSwyMywyOV0sWy02MCwwLDYwLDEyMCwxODAsMjQwLDMwMF1d).
```
Input: L.
JḊ Range of [2..len(L)].
ð ð€ For x in [2..len(L)]:
Ḷ [0..x-1] (residue classes)
ḟ without elements from
%@ L % x.
Ạ All truthy (non-empty)?
```
[Answer]
# Python, ~~61~~ 60 bytes
```
q=lambda l,d=2:d>len(l)or q(l,d+1)&(len({v%d for v in l})<d)
```
All test cases on [**ideone**](http://ideone.com/94U8nf)
Edit: replaced logical and with bitwise & to save one byte
[Answer]
## JavaScript (ES6), 59 bytes
```
a=>a.every((_,i)=>!i++|new Set(a.map(e=>(e%i+i)%i)).size<i)
```
Uses @KarlNapf's Set of remainders trick.
[Answer]
# Python, ~~67~~ 64 bytes
As unnamed lambda:
```
lambda N:all(len({i%m for i in N})<m for m in range(2,len(N)+1))
```
* Edit1: replaced `set()` with `{}`
* Edit2: dont't need square brackets around generator in `all(...)`
* Edit3: As pointed out by Jonathan Allan, `range` must go up to `len(N)+1`
Old code as function (96 bytes):
```
def f(N):
for m in range(2,len(N)+1):
if len(set(i%m for i in N))==m:return False
return True
```
[Answer]
# Mathematica, 51 bytes
```
And@@Table[Length@Union@Mod[#,i]<i,{i,2,Length@#}]&
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
"X@QGy\un>v
```
Truthy is an array (column vector) containing all ones. Falsy is an array containing at least one zero. You can check these definitions using [this link](http://matl.tryitonline.net/#code=PyAgICAgICAgICUgaWYKJ3RydXRoeScgICUgcHVzaCBzdHJpbmcKfSAgICAgICAgICUgZWxzZQonZmFsc3knICAgJSBwdXNoIHN0cmluZw&input=WzEgMCAxXQ).
[Try it online!](http://matl.tryitonline.net/#code=IlhAUUd5XHVuPnY&input=Wy0xMSAtMTMgLTE3IC0xOSAtMjMgLTI5IC0zMV0) Or verify all test cases: [truthy](http://matl.tryitonline.net/#code=IkBnWEsKIlhAUUt5XHVuPnYKXSFE&input=e1swIDJdIFstMSAxXSBbLTEwMCAtMjAwXSBbMCAyIDZdIFswIDIgNiA4XSBbMCAyIDYgOCAxMl0gWzAgNCA2IDEwIDEyXSBbLTYwIDAgNjAgMTIwIDE4MF0gWzAgMiA2IDggMTIgMjZdIFsxMSAxMyAxNyAxOSAyMyAyOSAzMV0gWy0xMSAtMTMgLTE3IC0xOSAtMjMgLTI5IC0zMV19), [falsy](http://matl.tryitonline.net/#code=IkBnWEsKIlhAUUt5XHVuPnYKXSFE&input=e1swIDFdIFstMSA0XSBbLTEwMCAtMjAxXSBbMCAyIDRdIFswIDIgNiAxMF0gWzAgMiA2IDggMTRdIFs3IDExIDEzIDE3IDE5IDIzIDI5XSBbLTYwIDAgNjAgMTIwIDE4MCAyNDAgMzAwXX0) (slightly modified code, each case produces a horizontal vector for clarity).
### Explanation
```
" % Take input array. For each; i.e. repeat n times, where n is arrray size
X@Q % Push iteration index plus 1, say k. So k is 2 in the first iteration,
% 3 in the second, ... n+1 in the last. Actually we only need 2, ..., n;
% but the final n+1 doesn't hurt
G % Push input again
y % Duplicate k onto the top of the stack
\ % Modulo. Gives vector of remainders of input when divided by k
un % Number of distinct elements
> % True if that number is smaller than k
v % Vertically concatenate with previous results
% End for each. Implicitly display
```
] |
[Question]
[
## Background
Consider a round-robin tournament, in which each contestant plays one game against every other contestant.
There are no draws, so every game has a winner and a loser.
A contestant **A** is a *king* of the tournament, if for every other contestant **B**, either **A** beat **B**, or **A** beat another contestant **C** who in turn beat **B**.
It can be shown that every tournament has at least one king (although there may be several).
In this challenge, your task is to find the kings of a given tournament.
## Input and output
Your input is an `N × N` boolean matrix `T`, and optionally the number `N ≥ 2` of contestants.
Each entry `T[i][j]` represents the outcome of the game between contestants `i` and `j`, with value 1 representing a win for `i` and 0 a win for `j`.
Note that `T[i][j] == 1-T[j][i]` if `i != j`.
The diagonal of `T` consists of 0s.
Your output shall be the list of kings in the tournament that `T` represents, using either 0-based or 1-based indexing.
The order of the kings is irrelevant, but there should not be duplicates.
Both input and output can be taken in any reasonable format.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/) are disallowed.
## Test cases
These test cases use 0-based indexing.
For 1-based indexing, increment each output value.
```
2 [[0,0],[1,0]] -> [1]
3 [[0,1,0],[0,0,0],[1,1,0]] -> [2]
3 [[0,1,0],[0,0,1],[1,0,0]] -> [0,1,2]
4 [[0,1,1,1],[0,0,1,0],[0,0,0,0],[0,1,1,0]] -> [0]
4 [[0,1,1,0],[0,0,1,0],[0,0,0,1],[1,1,0,0]] -> [0,2,3]
5 [[0,1,0,0,1],[0,0,0,0,1],[1,1,0,0,0],[1,1,1,0,1],[0,0,1,0,0]] -> [3]
5 [[0,1,0,1,0],[0,0,1,1,1],[1,0,0,0,0],[0,0,1,0,1],[1,0,1,0,0]] -> [0,1,4]
5 [[0,0,0,0,0],[1,0,1,1,0],[1,0,0,0,1],[1,0,1,0,1],[1,1,0,0,0]] -> [1,3,4]
6 [[0,0,0,0,0,0],[1,0,1,1,0,0],[1,0,0,1,1,0],[1,0,0,0,1,1],[1,1,0,0,0,1],[1,1,1,0,0,0]] -> [1,2,3,4,5]
6 [[0,0,1,1,1,0],[1,0,0,1,1,1],[0,1,0,0,1,0],[0,0,1,0,0,1],[0,0,0,1,0,1],[1,0,1,0,0,0]] -> [0,1,2,3,5]
6 [[0,1,1,0,0,1],[0,0,0,1,0,1],[0,1,0,1,1,0],[1,0,0,0,1,1],[1,1,0,0,0,0],[0,0,1,0,1,0]] -> [0,1,2,3,4,5]
8 [[0,0,1,1,0,1,1,1],[1,0,1,0,1,1,0,0],[0,0,0,1,1,0,0,0],[0,1,0,0,0,1,0,0],[1,0,0,1,0,1,0,0],[0,0,1,0,0,0,1,0],[0,1,1,1,1,0,0,1],[0,1,1,1,1,1,0,0]] -> [0,1,4,6,7]
20 [[0,0,1,1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,0,1],[1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1],[0,0,0,1,0,0,0,1,1,0,1,0,1,0,0,0,0,0,1,1],[0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1],[1,0,1,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,0,1],[0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,1,1,0,1],[0,0,1,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,0],[1,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,1,1,1,0],[1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,1],[1,0,1,0,1,0,1,1,0,0,1,0,0,0,0,1,0,1,1,1],[1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,0],[0,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,0,1,1],[0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,1],[1,0,1,1,1,0,0,0,0,1,0,0,1,0,1,1,1,1,1,1],[0,0,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1],[0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,1,1],[0,0,1,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1],[0,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1],[1,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,1,0]] -> [0,1,3,4,5,7,8,11,15,17,18]
```
[Answer]
# Matlab, ~~36 35~~ 29 bytes
```
@(T,N)find(sum(T*T>-T,2)>N-2)
```
Let us find out if `i` is a king. Then for each `j` the value `T[i][j]==1 OR there is a k such that T[i][k] * T[k][l] == 1`. But the second condition can also be replaced by `sum_over_k(T[i][k] * T[k][l])>0`, but this is just an entry of the matrix `T*T` (if you consider `T` as a matrix). The `OR` can then be replayed by adding `T` to that result, so we just have to check if `n-1` values of the row `i` of `T*T+T` are greater than zero, to see whether `i` is king. This is exactly what my function does.
(This is MATLAB, so the indices are 1-based.)
The MATLAB matrices should be encoded with semicolons as line delimiters:
```
[[0,0,0,0,0];[1,0,1,1,0];[1,0,0,0,1];[1,0,1,0,1];[1,1,0,0,0]]
```
[Answer]
# Jelly, ~~13~~ ~~12~~ 11 bytes
```
a"€¹o/€oḅ1M
```
Output is 1-based. [Try it online!](http://jelly.tryitonline.net/#code=YSLigqzCuW8v4oKsb-G4hTFN&input=&args=W1swLDAsMSwxLDAsMSwxLDAsMCwwLDAsMSwxLDAsMSwxLDEsMSwwLDFdLFsxLDAsMSwxLDEsMCwxLDEsMSwxLDEsMCwxLDEsMSwxLDEsMSwxLDFdLFswLDAsMCwxLDAsMCwwLDEsMSwwLDEsMCwxLDAsMCwwLDAsMCwxLDFdLFswLDAsMCwwLDEsMSwxLDEsMSwxLDEsMSwwLDAsMSwwLDAsMSwxLDFdLFsxLDAsMSwwLDAsMCwwLDEsMSwwLDEsMSwxLDAsMSwxLDEsMSwwLDFdLFswLDEsMSwwLDEsMCwxLDEsMSwxLDEsMCwxLDEsMSwwLDEsMSwwLDFdLFswLDAsMSwwLDEsMCwwLDEsMSwwLDEsMCwxLDEsMSwxLDEsMCwxLDBdLFsxLDAsMCwwLDAsMCwwLDAsMSwwLDEsMSwxLDEsMCwwLDEsMSwxLDBdLFsxLDAsMCwwLDAsMCwwLDAsMCwxLDEsMSwxLDEsMSwxLDEsMCwxLDFdLFsxLDAsMSwwLDEsMCwxLDEsMCwwLDEsMCwwLDAsMCwxLDAsMSwxLDFdLFsxLDAsMCwwLDAsMCwwLDAsMCwwLDAsMSwxLDEsMCwxLDAsMCwwLDBdLFswLDEsMSwwLDAsMSwxLDAsMCwxLDAsMCwxLDEsMSwxLDEsMCwxLDFdLFswLDAsMCwxLDAsMCwwLDAsMCwxLDAsMCwwLDAsMSwxLDAsMSwxLDFdLFsxLDAsMSwxLDEsMCwwLDAsMCwxLDAsMCwxLDAsMSwxLDEsMSwxLDFdLFswLDAsMSwwLDAsMCwwLDEsMCwxLDEsMCwwLDAsMCwxLDEsMCwwLDFdLFswLDAsMSwxLDAsMSwwLDEsMCwwLDAsMCwwLDAsMCwwLDAsMSwxLDFdLFswLDAsMSwxLDAsMCwwLDAsMCwxLDEsMCwxLDAsMCwxLDAsMCwxLDFdLFswLDAsMSwwLDAsMCwxLDAsMSwwLDEsMSwwLDAsMSwwLDEsMCwxLDFdLFsxLDAsMCwwLDEsMSwwLDAsMCwwLDEsMCwwLDAsMSwwLDAsMCwwLDBdLFswLDAsMCwwLDAsMCwxLDEsMCwwLDEsMCwwLDAsMCwwLDAsMCwxLDBdXQ)
Alternatively, using bitwise operators instead of array manipulation:
```
×Ḅ|/€|ḄBS€M
```
Again, output is 1-based. [Try it online!](http://jelly.tryitonline.net/#code=w5fhuIR8L-KCrHzhuIRCU-KCrE0&input=&args=W1swLDAsMSwxLDAsMSwxLDAsMCwwLDAsMSwxLDAsMSwxLDEsMSwwLDFdLFsxLDAsMSwxLDEsMCwxLDEsMSwxLDEsMCwxLDEsMSwxLDEsMSwxLDFdLFswLDAsMCwxLDAsMCwwLDEsMSwwLDEsMCwxLDAsMCwwLDAsMCwxLDFdLFswLDAsMCwwLDEsMSwxLDEsMSwxLDEsMSwwLDAsMSwwLDAsMSwxLDFdLFsxLDAsMSwwLDAsMCwwLDEsMSwwLDEsMSwxLDAsMSwxLDEsMSwwLDFdLFswLDEsMSwwLDEsMCwxLDEsMSwxLDEsMCwxLDEsMSwwLDEsMSwwLDFdLFswLDAsMSwwLDEsMCwwLDEsMSwwLDEsMCwxLDEsMSwxLDEsMCwxLDBdLFsxLDAsMCwwLDAsMCwwLDAsMSwwLDEsMSwxLDEsMCwwLDEsMSwxLDBdLFsxLDAsMCwwLDAsMCwwLDAsMCwxLDEsMSwxLDEsMSwxLDEsMCwxLDFdLFsxLDAsMSwwLDEsMCwxLDEsMCwwLDEsMCwwLDAsMCwxLDAsMSwxLDFdLFsxLDAsMCwwLDAsMCwwLDAsMCwwLDAsMSwxLDEsMCwxLDAsMCwwLDBdLFswLDEsMSwwLDAsMSwxLDAsMCwxLDAsMCwxLDEsMSwxLDEsMCwxLDFdLFswLDAsMCwxLDAsMCwwLDAsMCwxLDAsMCwwLDAsMSwxLDAsMSwxLDFdLFsxLDAsMSwxLDEsMCwwLDAsMCwxLDAsMCwxLDAsMSwxLDEsMSwxLDFdLFswLDAsMSwwLDAsMCwwLDEsMCwxLDEsMCwwLDAsMCwxLDEsMCwwLDFdLFswLDAsMSwxLDAsMSwwLDEsMCwwLDAsMCwwLDAsMCwwLDAsMSwxLDFdLFswLDAsMSwxLDAsMCwwLDAsMCwxLDEsMCwxLDAsMCwxLDAsMCwxLDFdLFswLDAsMSwwLDAsMCwxLDAsMSwwLDEsMSwwLDAsMSwwLDEsMCwxLDFdLFsxLDAsMCwwLDEsMSwwLDAsMCwwLDEsMCwwLDAsMSwwLDAsMCwwLDBdLFswLDAsMCwwLDAsMCwxLDEsMCwwLDEsMCwwLDAsMCwwLDAsMCwxLDBdXQ)
### Background
For contestant **A**, we can find all **B** such that **A beat C beat B** by taking all rows that correspond to a **C** such that **C beat A**. Ifr the **B**th entry of the **Cth** is **1**, we have that **C beat B**.
If we compute the logical ORs of all corresponding entries of the selected columns, we get a a single vector indicating whether **A beat B** by transitivity or not. Finally, ORing the resulting vector with the corresponding row of the input matrix gives Booleans whether **A beat B**, either by transitivity or directly.
Repeating this for every row, we count the number of **1**'s in each vector, therefore computing the amount of contestants each **A** beat. Maximal counts correspond to kings of the tournament.
### How it works
```
a"€¹o/€oḅ1M Main link. Argument: M (matrix)
¹ Yield M.
€ For each row of M:
a" Take the logical AND of each entry of that row and the corr. row of M.
o/€ Reduce each resulting matrix by logical OR.
o Take the logical OR of the entries of the resulting maxtrix and the
corr. entries of M.
ḅ1 Convert each row from base 1 to integer, i.e. sum its elements.
M Get all indices of maximal sums.
```
```
×Ḅ|/€|ḄBS€M Main link. Argument: M (matrix)
Ḅ Convert each row of M from base 2 to integer. Result: R
× Multiply the entries of each column of M by the corr. integer.
|/€ Reduce each row fo the resulting matrix by bitwise OR.
|Ḅ Bitwise OR the results with R.
BS€ Convert to binary and reduce by sum.
This counts the number of set bits for each integer.
M Get all indices of maximal popcounts.
```
[Answer]
## Python using numpy, 54 bytes
```
import numpy
lambda M:(M**0+M+M*M).all(1).nonzero()[0]
```
Takes in a numpy matrix, outputs a numpy row matrix of 0-based indices.
Another way to think of a king is as a contestant for which all contestants are in the union of the king, the people the king beat, and the people those people beat. In other words, for every contestant, there is a path of length at most 2 from the king to them among the "beat" relation.
The matrix `I + M + M*M` encodes the numbers of paths of 0, 1, or 2 steps from each source to each target. A player is a king if their row of this matrix has only positive entries. Since 0 is Falsey, `all` tells us if a row is all nonzero. We apply this to each row and output the indices of the nonzero results.
[Answer]
## JavaScript (ES6), 83 bytes
```
a=>a.map((b,i)=>b.every((c,j)=>c|i==j|b.some((d,k)=>d&a[k][j]))&&r.push(i),r=[])&&r
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~12~~ ~~10~~ 9 bytes
```
Xy+HY^!Af
```
Input is: first the number of contestants, and on a separate line a matrix with rows separated by semicolons. Output is 1-based.
For example, the fifth test case has input
```
4
[0,1,1,0; 0,0,1,0; 0,0,0,1; 1,1,0,0]
```
and the last test case has input
```
20
[0,0,1,1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,0,1; 1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1; 0,0,0,1,0,0,0,1,1,0,1,0,1,0,0,0,0,0,1,1; 0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1; 1,0,1,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,0,1; 0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,1,1,0,1; 0,0,1,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,0; 1,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,1,1,1,0; 1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,1; 1,0,1,0,1,0,1,1,0,0,1,0,0,0,0,1,0,1,1,1; 1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,0; 0,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,0,1,1; 0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,1; 1,0,1,1,1,0,0,0,0,1,0,0,1,0,1,1,1,1,1,1; 0,0,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1; 0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,1,1; 0,0,1,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1; 0,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1; 1,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0; 0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,1,0]
```
[**Try it online!**](http://matl.tryitonline.net/#code=WHkrSFleIUFm&input=MjAKWzAsMCwxLDEsMCwxLDEsMCwwLDAsMCwxLDEsMCwxLDEsMSwxLDAsMTsgMSwwLDEsMSwxLDAsMSwxLDEsMSwxLDAsMSwxLDEsMSwxLDEsMSwxOyAwLDAsMCwxLDAsMCwwLDEsMSwwLDEsMCwxLDAsMCwwLDAsMCwxLDE7IDAsMCwwLDAsMSwxLDEsMSwxLDEsMSwxLDAsMCwxLDAsMCwxLDEsMTsgMSwwLDEsMCwwLDAsMCwxLDEsMCwxLDEsMSwwLDEsMSwxLDEsMCwxOyAwLDEsMSwwLDEsMCwxLDEsMSwxLDEsMCwxLDEsMSwwLDEsMSwwLDE7IDAsMCwxLDAsMSwwLDAsMSwxLDAsMSwwLDEsMSwxLDEsMSwwLDEsMDsgMSwwLDAsMCwwLDAsMCwwLDEsMCwxLDEsMSwxLDAsMCwxLDEsMSwwOyAxLDAsMCwwLDAsMCwwLDAsMCwxLDEsMSwxLDEsMSwxLDEsMCwxLDE7IDEsMCwxLDAsMSwwLDEsMSwwLDAsMSwwLDAsMCwwLDEsMCwxLDEsMTsgMSwwLDAsMCwwLDAsMCwwLDAsMCwwLDEsMSwxLDAsMSwwLDAsMCwwOyAwLDEsMSwwLDAsMSwxLDAsMCwxLDAsMCwxLDEsMSwxLDEsMCwxLDE7IDAsMCwwLDEsMCwwLDAsMCwwLDEsMCwwLDAsMCwxLDEsMCwxLDEsMTsgMSwwLDEsMSwxLDAsMCwwLDAsMSwwLDAsMSwwLDEsMSwxLDEsMSwxOyAwLDAsMSwwLDAsMCwwLDEsMCwxLDEsMCwwLDAsMCwxLDEsMCwwLDE7IDAsMCwxLDEsMCwxLDAsMSwwLDAsMCwwLDAsMCwwLDAsMCwxLDEsMTsgMCwwLDEsMSwwLDAsMCwwLDAsMSwxLDAsMSwwLDAsMSwwLDAsMSwxOyAwLDAsMSwwLDAsMCwxLDAsMSwwLDEsMSwwLDAsMSwwLDEsMCwxLDE7IDEsMCwwLDAsMSwxLDAsMCwwLDAsMSwwLDAsMCwxLDAsMCwwLDAsMDsgMCwwLDAsMCwwLDAsMSwxLDAsMCwxLDAsMCwwLDAsMCwwLDAsMSwwXQo)
### Explanation
```
Xy % Implicitly take input: number. Push identity matrix with that size
+ % Implicitly take input: matrix. Add to identity matrix
HY^ % Matrix square
! % Transpose
A % Row vector with true entries for columns that contain all nonzero values
f % Indices of nonzero values
```
[Answer]
# Javascript ~~136~~ ~~131~~ ~~121~~ 112 bytes
```
(n,m)=>m.map((a,k)=>eval(a.map((o,i)=>o||eval(a.map((p,j)=>p&&m[j][i]).join`|`)).join`+`)>n-2&&k+1).filter(a=>a)
```
---
Call using:
```
f=(n,m)=>m.map((a,k)=>eval(a.map((o,i)=>o||eval(a.map((p,j)=>p&&m[j][i]).join`|`)).join`+`)>n-2&&k+1).filter(a=>a)
f(20,[[0,0,1,1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,0,1],
[1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1],
[0,0,0,1,0,0,0,1,1,0,1,0,1,0,0,0,0,0,1,1],
[0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1],
[1,0,1,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,0,1],
[0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,1,1,0,1],
[0,0,1,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,0],
[1,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,1,1,1,0],
[1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,1],
[1,0,1,0,1,0,1,1,0,0,1,0,0,0,0,1,0,1,1,1],
[1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,0],
[0,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,0,1,1],
[0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,1],
[1,0,1,1,1,0,0,0,0,1,0,0,1,0,1,1,1,1,1,1],
[0,0,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1],
[0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,1,1],
[0,0,1,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1],
[0,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1],
[1,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,1,0]])
```
watchout because output is 1-indexed (saved a few bytes not trying to filter out 0s vs falses)
] |
[Question]
[
# Definitions
Let `m` and `n` be positive integers. We say that `m` is a *divisor twist* of `n` if there exists integers `1 < a ≤ b` such that `n = a*b` and `m = (a - 1)*(b + 1) + 1`. If `m` can be obtained from `n` by applying zero or more divisor twists to it, then `m` is a *descendant* of `n`. Note that every number is its own descendant.
For example, consider `n = 16`. We can choose `a = 2` and `b = 8`, since `2*8 = 16`. Then
```
(a - 1)*(b + 1) + 1 = 1*9 + 1 = 10
```
which shows that `10` is a divisor twist of `16`. With `a = 2` and `b = 5`, we then see that `7` is a divisor twist of `10`. Thus `7` is a descendant of `16`.
# The task
Given a positive integer `n`, compute the descendants of `n`, listed in increasing order, without duplicates.
# Rules
You are not allowed to use built-in operations that compute the divisors of a number.
Both full programs and functions are accepted, and returning a collection datatype (like a set of some kind) is allowed, as long as it is sorted and duplicate-free. The lowest byte count wins, and standard loopholes are disallowed.
# Test Cases
```
1 -> [1]
2 -> [2] (any prime number returns just itself)
4 -> [4]
16 -> [7, 10, 16]
28 -> [7, 10, 16, 25, 28]
51 -> [37, 51]
60 -> [7, 10, 11, 13, 15, 16, 17, 18, 23, 25, 28, 29, 30, 32, 43, 46, 49, 53, 55, 56, 60]
```
[Answer]
# Python 2, ~~109~~ ~~98~~ ~~85~~ 82 bytes
```
f=lambda n:sorted(set(sum(map(f,{n-x+n/x for x in range(2,n)if(n<x*x)>n%x}),[n])))
```
Since `(a-1)*(b+1)+1 == a*b-(b-a)` and `b >= a`, descendants are always less than or equal to the original number. So we can just start with the initial number and keep generating strictly smaller descendants until there are none left.
The condition `(n<x*x)>n%x` checks two things in one - that `n<x*x` and `n%x == 0`.
*(Thanks to @xnor for taking 3 bytes off the base case)*
# Pyth, 32 bytes
```
LS{s+]]bmydm+-bk/bkf><b*TT%bTr2b
```
Direct translation of the above, except for the fact that Pyth seems to choke when trying to sum (`s`) on an empty list.
This defines a function `y` which can be called by appending `y<number>` at the end, like so ([try it online](https://pyth.herokuapp.com/)):
```
LS{s+]]bmydm+-bk/bkf><b*TT%bTr2by60
```
# CJam, ~~47~~ 45 bytes
```
{{:X_,2>{__*X>X@%>},{_X\/\-X+}%{F}%~}:F~]_&$}
```
Also using the same method, with a few modifications. I wanted to try CJam for comparison, but unfortunately I'm much worse at CJam than I am at Pyth/Python, so there's probably a lot of room for improvement.
The above is a block (basically CJam's version of unnamed functions) that takes in an int and returns a list. You can test it like so ([try it online](http://cjam.aditsu.net/)):
```
{{:X_,2>{__*X>X@%>},{_X\/\-X+}%{F}%~}:F~]_&$}:G; 60 Gp
```
[Answer]
# Java, 148 146 104 bytes
Golfed version:
```
import java.util.*;Set s=new TreeSet();void f(int n){s.add(n);for(int a=1;++a*a<n;)if(n%a<1)f(n+a-n/a);}
```
Long version:
```
import java.util.*;
Set s = new TreeSet();
void f(int n) {
s.add(n);
for (int a = 1; ++a*a < n;)
if (n%a < 1)
f(n + a - n/a);
}
```
So I'm making my debut on PPCG with this program, which uses a `TreeSet` (which automatically sorts the numbers, thankfully) and recursion similar to Geobits' program, but in a different manner, checking for multiples of *n* and then using them in the next function. I'd say this is a pretty fair score for a first-timer (especially with Java, which doesn't seem to be the most ideal language for this kind of thing, and Geobits' help).
[Answer]
# Java, ~~157~~ 121
Here's a recursive function that gets descendants of each descendant of `n`. It returns a `TreeSet`, which is sorted by default.
```
import java.util.*;Set t(int n){Set o=new TreeSet();for(int i=1;++i*i<n;)o.addAll(n%i<1?t(n+i-n/i):o);o.add(n);return o;}
```
With some line breaks:
```
import java.util.*;
Set t(int n){
Set o=new TreeSet();
for(int i=1;++i*i<n;)
o.addAll(n%i<1?t(n+i-n/i):o);
o.add(n);
return o;
}
```
[Answer]
# Octave, ~~107~~ 96
```
function r=d(n)r=[n];a=find(!mod(n,2:sqrt(n-1)))+1;for(m=(a+n-n./a))r=unique([d(m) r]);end;end
```
Pretty-print:
```
function r=d(n)
r=[n]; # include N in our list
a=find(!mod(n,2:sqrt(n-1)))+1; # gets a list of factors of a, up to (not including) sqrt(N)
for(m=(a+n-n./a)) # each element of m is a twist
r=unique([d(m) r]); # recurse, sort, and find unique values
end;
end
```
[Answer]
# Haskell, 102 100 bytes
```
import Data.List
d[]=[]
d(h:t)=h:d(t++[a*b-b+a|b<-[2..h],a<-[2..b],a*b==h])
p n=sort$nub$take n$d[n]
```
Usage: `p 16` which outputs `[7,10,16]`
The function `d` recursively calculates all descendants, but does not check for duplicates, so many appear more than once, e. g. `d [4]` returns an infinite list of `4`s. The functions `p` takes the first `n` elements from this list, removes duplicates and sorts the list. Voilà.
[Answer]
# CJam - 36
```
ri_a\{_{:N,2>{NNImd!\I-z*-}fI}%|}*$p
```
[Try it online](http://cjam.aditsu.net/#code=ri_a%5C%7B_%7B%3AN%2C2%3E%7BNNImd!%5CI-z*-%7DfI%7D%25%7C%7D*%24p&input=60)
Or, different method:
```
ri_a\{_{_,2f#_2$4*f-&:mq:if-~}%|}*$p
```
I wrote them almost 2 days ago, got stuck at 36, got frustrated and went to sleep without posting.
] |
[Question]
[
Write the shortest program to forecast the weather for the next 7 days
The input (from stdin) is the *weekday* and the *season*
The output (to stdout) is seven lines *weekday* and the *temperature* in centigrade
The weekdays begin on the input weekday
The temperatures are random numbers with the range depending on the season
```
Spring 10 - 30 degrees
Summer 20 - 40 degrees
Autumn 5 - 25 degrees (Fall is a synonym for autumn)
Winter -5 - 15 degrees
```
**Sample Input**
`Thursday Winter`
**Sample Output**
```
Thursday -1
Friday 3
Saturday 8
Sunday 7
Monday 10
Tuesday 10
Wednesday -1
```
Your program must not have identical output every time it is run with the same input
[Answer]
## Ruby 1.8, 95 characters
```
#!ruby -nrdate
7.times{|i|puts (Date.parse($_)+i).strftime"%A #{"\023\004\016\016\035"[$_[-3]%5]-9+rand(21)}"}
```
The character escapes inside the string should be replaced by the character literals they represent.
* Found a shorter way to pack the data, Ruby 1.9 would be 4 characters longer now (add `.ord` after `$_[-3]`).
* 112 -> 105 by stealing Joey's idea of not splitting the input.
* 105 -> 101. Note that the first line is actually parsed by the Ruby interpreter itself, so it even works when running the solution like `echo "Thursday Winter" | ruby1.8 forecast.rb`
* 101 -> 96. Stole Joey's idea again to just embed the temperatures into a string instead of an array.
* Whoops, just noticed it should be rand(21), not rand(20).
* 96 -> 95. Removed unnecessary whitespace.
[Answer]
### Windows PowerShell, 104
```
[dayofweek]$d,$s=-split$input
(0..6*2)[+$d..(6+$d)]|%{''+[dayofweek]$_,((random 20)-5+'☼
↓'[$s[3]%5])}
```
The strings in there are a bit icky, so a hex view for your convenience:
```
000: 5B 64 61 79 6F 66 77 65 │ 65 6B 5D 24 64 2C 24 73 [dayofweek]$d,$s
010: 3D 2D 73 70 6C 69 74 24 │ 69 6E 70 75 74 0A 28 30 =-split$input◙(0
020: 2E 2E 36 2A 32 29 5B 2B │ 24 64 2E 2E 28 36 2B 24 ..6*2)[+$d..(6+$
030: 64 29 5D 7C 25 7B 27 27 │ 2B 5B 64 61 79 6F 66 77 d)]|%{''+[dayofw
040: 65 65 6B 5D 24 5F 2C 28 │ 28 72 61 6E 64 6F 6D 20 eek]$_,((random
050: 32 30 29 2D 35 2B 27 0F │ 00 0A 0A 19 27 5B 24 73 20)-5+'☼ ◙◙↓'[$s
060: 5B 33 5D 25 35 5D 29 7D │ [3]%5])}
```
History:
* 2011-02-04 00:16 **(179)** – First, straightforward attempt.
* 2011-02-04 00:20 **(155)** – Why match whole season names when you can get away with individual characters and a regex match? Won't deal nicely with invalid input but that's always to be expected in Golfing.
* 2011-02-06 13:12 **(149)** – Got rid of `$t` which only lengthened things.
* 2011-02-10 22:50 **(142)** – Day name generation made simpler. I just generate a week twice, index in the correct position and pull out seven items.
* 2011-02-10 22:52 **(138)** – Moving the initial cast to the declaration of `$d` saves a few bytes as well – and gets rid of `$x`.
* 2011-02-10 23:03 **(135)** – Moving the cast further down the pipeline to avoid an array cast (which needs additional `[]`). Also changed output to casting a list of objects to string which implicitly inserts a space (`$OFS` default).
* 2011-02-11 20:54 **(132)** – Replaced the regex match by a list of character codes and indexing into a hashmap with the third character from the season.
* 2011-02-11 21:00 **(122)** – Replaced the hash map by an array.
* 2011-02-11 21:12 **(117)** – More array-y goodness. And shorter to boot. Modulo 8 packs the array a bit shorter.
* 2011-02-11 21:16 **(116)** – Extracted a factor of five to replace `0,0,2` by `0..2` which is shorter.
* 2011-02-11 21:22 **(114)** – Used a slightly different calculation. It still maps autumn and fall to the same index and has the advantage of only requiring five values. Very nice. The negative index into the string also plays very well with »Fall« being shorter than the rest.
* 2011-02-11 21:45 **(112)** – Stolen Ventero's way of determining the season's temperature range which is two bytes shorter.
* 2011-02-12 03:16 **(105)** – Back to 105 after a different attempt just printed a single line.
* 2011-02-12 13:23 **(104)** – Back to 104 again, using a positive index into the season since I split again.
Test script (as long as it outputs nothing the result is ok):
```
foreach ($d in 'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday') {
foreach ($s in 'Winter','Summer','Spring','Autumn','Fall') {
$o=-split("$d $s"|./weather_foo.ps1)
if ($o.Count -ne 14) { "Wrong output length" }
$days = $o -notmatch '\d'
$temps = $o -match '\d'
if ($days[0]-ne$d) { "Found "+ $days[0] + " instead of $d" }
$m = $temps | measure -min -max
switch ($s) {
'Summer'{ $min = 20 }
'Spring'{ $min = 10 }
'Fall' { $min = 5 }
'Autumn'{ $min = 5 }
'Winter'{ $min = -5 }
}
if ($m.Minimum -lt $min) { "Minimum temperature $($m.Minimum) didn't match for $s" }
if ($m.Maximum -gt $min + 20) { "Maximum temperature $($m.Maximum) didn't match for $s" }
}
}
```
[Answer]
## Golfscript - 110 chars
```
' ':^/){*}*43845%7&5*:|;){*}*333121%7&:$;7,{($+'Sun Mon Tues Wednes Thurs Fri Satur'^/.+='day '+20rand|+5-+n}/
```
* Fully support all the temperature ranges, seasons and also support "Fall" as synonym for "Autumn" too.
* I think there is some rooms for improvement, but my current golfscript knowledge is limited so far.
### Here is the tests, 2 passes each to confirm randomness
```
$ echo -n Thursday Spring | gs codegolf-404.gs
Thursday 23
Friday 28
Saturday 25
Sunday 22
Monday 19
Tuesday 14
Wednesday 25
$ echo -n Thursday Spring | gs codegolf-404.gs
Thursday 27
Friday 12
Saturday 26
Sunday 12
Monday 27
Tuesday 17
Wednesday 21
$ echo -n Friday Autumn | gs codegolf-404.gs
Friday 10
Saturday 5
Sunday 17
Monday 24
Tuesday 24
Wednesday 12
Thursday 18
$ echo -n Friday Autumn | gs codegolf-404.gs
Friday 13
Saturday 7
Sunday 14
Monday 6
Tuesday 14
Wednesday 21
Thursday 5
$ echo -n Sunday Summer | gs codegolf-404.gs
Sunday 39
Monday 31
Tuesday 35
Wednesday 34
Thursday 21
Friday 36
Saturday 28
$ echo -n Sunday Summer | gs codegolf-404.gs
Sunday 34
Monday 20
Tuesday 30
Wednesday 39
Thursday 30
Friday 31
Saturday 37
$ echo -n Monday Fall | gs codegolf-404.gs
Monday 6
Tuesday 7
Wednesday 18
Thursday 13
Friday 7
Saturday 5
Sunday 14
$ echo -n Monday Fall | gs codegolf-404.gs
Monday 16
Tuesday 22
Wednesday 19
Thursday 23
Friday 21
Saturday 9
Sunday 17
$ echo -n Saturday Winter | gs codegolf-404.gs
Saturday 0
Sunday -5
Monday 10
Tuesday -3
Wednesday -5
Thursday 13
Friday -1
$ echo -n Saturday Winter | gs codegolf-404.gs
Saturday -4
Sunday 13
Monday 11
Tuesday 0
Wednesday 0
Thursday -5
Friday 9
$ echo -n Tuesday Summer | gs codegolf-404.gs
Tuesday 38
Wednesday 29
Thursday 25
Friday 29
Saturday 34
Sunday 20
Monday 39
$ echo -n Tuesday Summer | gs codegolf-404.gs
Tuesday 33
Wednesday 26
Thursday 31
Friday 37
Saturday 39
Sunday 24
Monday 28
$ echo -n Wednesday Winter | gs codegolf-404.gs
W ednesday 7
Thursday 12
Friday 0
Saturday -3
Sunday 11
Monday 14
Tuesday 8
$ echo -n Wednesday Winter | gs codegolf-404.gs
Wednesday 0
Thursday -1
Friday 7
Saturday 12
Sunday -5
Monday -3
Tuesday 2
```
[Answer]
# D: 436 Characters
```
import std.algorithm, std.random, std.range, std.stdio, std.typecons;
void main(string[] g)
{
alias canFind w;
alias tuple t;
auto s = g[2];
auto e = w(s, "g") ? t(10, 30) : w(s, "Su") ? t(20, 40) : w(s, "W") ? t(-5, 15) : t(5, 25) ;
auto r = rndGen();
int v()
{
r.popFront();
return e[0] + cast(int)(r.front % (e[1] - e[0]));
}
auto x = findSplitBefore(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], [g[1]]);
foreach(q; chain(x[1], x[0]))
writefln("%s %s", q, v());
}
```
Version with extraneous whitespace removed (which is how it comes to 436 characters):
```
import std.algorithm,std.random,std.range,std.stdio,std.typecons;void main(string[] g){alias canFind w;alias tuple t;auto s=g[2];auto e=w(s,"g")?t(10,30):w(s,"Su")?t(20,40):w(s,"W")?t(-5,15):t(5,25);auto r=rndGen();int v(){r.popFront();return e[0]+cast(int)(r.front%(e[1]-e[0]));}auto x=findSplitBefore(["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],[g[1]]);foreach(q;chain(x[1],x[0]))writefln("%s %s",q,v());}
```
[Answer]
## PHP, ~~353~~ ~~319~~ ~~305~~ ~~304~~ 288 characters
```
<?$i=split(" ",fgets(STDIN));$d=$i[0][0].$i[0][1];$s=$i[1][2];$r=json_decode('{"i":[10,30],"m":[20,40],"t":[5,25],"n":[-5,15]}',true);$n=array(Sun,Mon,Tues,Wednes,Thurs,Fri,Satur);$z=$x=0;while($z<7)if($n[++$x][0].$n[$x][1]==$d||$z){$z++;echo$n[$x%7]."day ".rand($r[$s][0],$r[$s][1])."
";}
```
**Ungolfed**
```
<?php
$input = fgets(STDIN);
$info = split(" ", $input);
$day = substr($info[0], 0, 2);
$season = $info[1][2];
$range[i][] = 10;
$range[i][] = 30;
$range[m][] = 20;
$range[m][] = 40;
$range[t][] = 5;
$range[t][] = 25;
$range[n][] = -5;
$range[n][] = 15;
$days[0] = "Sun";
$days[1] = "Mon";
$days[2] = "Tues";
$days[3] = "Wednes";
$days[4] = "Thurs";
$days[5] = "Fri";
$days[6] = "Satur";
$i = $d = 0;
while($i<7)
if(substr($days[++$d], 0, 2)==$day||$i){
$i++;
echo $days[$d%7]."day ".rand($range[$season][0], $range[$season][1])."\n";
}
?>
```
305 -> 304: Switched the newline
304 -> 288: Uses JSON arrays instead of PHP arrays
[Answer]
**C# 350 Characters**
There must be a more efficient way than this. But here's what I've got so far:
```
using System;class P{static void Main(string[]x){var r=new Random();var s=x[1][2];int l=s=='r'?10:s=='m'?20:s=='n'?-5:5,u=s=='r'?31:s=='m'?41:s=='n'?16:26,i=0,z=(int)Enum.Parse(typeof(DayOfWeek),x[0]);for(;i<7;i++){var d=z<1?"Sun":z<2?"Mon":z<3?"Tues":z<4?"Wednes":z<5?"Thurs":z<6?"Fri":"Satur";Console.WriteLine(d+"day "+r.Next(l,u));z=z>5?0:z+1;}}}
```
Or in a more readable format, with a couple of comments:
```
using System;
class P
{
static void Main(string[] x)
{
var r = new Random();
var s = x[1][2]; //3rd char of season, first where all have unique letter
// lower & upper limits for random, based on season
int l = s == 'r' ? 10 : s == 'm' ? 20 : s == 'n' ? -5 : 5,
u = s == 'r' ? 31 : s == 'm' ? 41 : s == 'n' ? 16 : 26,
i = 0,
// this line makes me cringe, but converting to an int and back seems
// the easiest way to loop through days
z = (int)Enum.Parse(typeof(DayOfWeek), x[0]);
for (; i < 7; i++)
{
var d = z < 1 ? "Sun" : z < 2 ? "Mon" : z < 3 ? "Tues" : z < 4 ? "Wednes" : z < 5 ? "Thurs" : z < 6 ? "Fri" : "Satur";
Console.WriteLine(d + "day " + r.Next(l, u));
z = z > 5 ? 0 : z + 1; // increments day, resets to 0 after saturday
}
}
}
```
[Answer]
**Javascript - 251 chars**
```
d=['Mon','Tues','Wednes','Thurs','Fri','Satur','Sun'],g=function(c){return Math.random()*21+c|0},p=prompt();for(i=0,j=7,t=true;i<j;i++){t=t&&p.indexOf(d[i])!=0;t?j++:console.log(d[i>6?i-7:i]+'day '+g(/mm/.test(p)?20:/g/.test(p)?10:/te/.test(p)?-5:5))}
```
Unfortunately the script does not meet the stdin/stdout requirement but it accepts Fall as a synonym for Autumn.
Whitespaced:
```
d = [
'Mon'
, 'Tues'
, 'Wednes'
, 'Thurs'
, 'Fri'
, 'Satur'
, 'Sun'
]
, g = function(c) {
return Math.random()*21+c|0
}
, p = prompt()
;
for(i = 0, j = 7, t = true; i < j; i++) {
t = t && p.indexOf(d[i]) != 0;
t ?
j++ :
console.log(d[i > 6 ? i - 7 : i] + 'day ' + g(/mm/.test(p) ?
20 :
/g/.test(p) ?
10 :
/te/.test(p) ?
-5 :
5
)
)
}
```
[Answer]
# PHP - 150 Characters
```
<?$t=array("m"=>15,"r"=>5,"n"=>-10);for($a=split(" ",fgets(STDIN));$i<7;$i++)echo date("l ",strtotime($a[0]."+$i day")),rand(5,25)+$t[$a[1][2]],"\n";
```
I figured I'd write my own PHP solution after the current one doesn't even fully satisfy the challenge conditions.
It relies on strtotime to parse the day, and date to echo it back. To determine the season, it follows the third letter of the season name, which is unique (as given).
To run properly, it requires notices to be disabled and short tags to be enabled.
[Answer]
# Python 2, 220 characters
A little large but (almost) readable.
```
import random
c,e=raw_input().split()
a=[d+'day'for d in'Mon Tues Wednes Thurs Fri Satur Sun'.split()]*2
x='rmtn'.index(e[2])*2
g=(10,30,20,40,5,25,-5,15)[x:x+2]
f=a.index(c)
for b in a[f:f+7]:
print b,random.randint(*g)
```
Output
```
# echo "Monday Summer" | python forecast.py
Monday 33
Tuesday 29
Wednesday 33
Thursday 28
Friday 25
Saturday 21
Sunday 30
```
[Answer]
# Mathematica 218
```
s_~g~d_ :=
Grid@RotateLeft[r = Thread@{DateString[{2012, 1, #}, {"DayName"}] & /@ Range@7,
RandomInteger[Cases[{{"Spring", {10, 30}}, {"Summer", {20, 40}}, {"Autumn", {5, 25}},
{"Winter", {-5, 15}}}, {s, _}][[1, 2]], 7]}, Position[r, d][[1, 1]] - 1]
```
**Usage**
```
g["Winter", "Sunday"]
```

] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.