text
stringlengths 180
608k
|
---|
[Question]
[
The following puzzle was invented by Eric Angelini in September 2007.
As mentioned in [A131744](https://oeis.org/A131744) :
>
> the sequence is defined by the property that if one writes the English
> names for the entries, replaces each letter with its rank in the
> alphabet and calculates the absolute values of the differences, one
> recovers the sequence.
>
>
>
To be precise, the alphabet starts at 1, so a is 1, b is 2, etc.
Also, 15 is supposed to be treated as fifteen and 21 as twentyone (not twenty-one).
## Example :
Begin with 1 :
```
1 -> "one" -> 15,14,5 -> absolute(15-14),absolute(14-5) -> 1,9
1,9 -> "one,nine" -> 15,14,5,14,9,14,5 -> 1,9,9,5,5,9
1,9,9,5,5,9 -> "one,nine,nine,five,five,nine" -> 15,14,5,14,9,14,5,14,9,14,5,6,9,22,5,6,9,22,5,14,9,14,5 -> 1,9,9,5,5,9,9,5,5,9,1,3,13,17,1,3,13,17,9,5,5,9
1,9,9,5,5,9,9,5,5,9,1,3,13,17,1,3,13,17,9,5,5,9 -> ...
```
So the first 22 terms are : `1,9,9,5,5,9,9,5,5,9,1,3,13,17,1,3,13,17,9,5,5,9`
You can find the 40000 first terms here : [b131744](https://oeis.org/A131744/b131744.txt)
## Challenge
Sequence I/O methods apply. You may use one of the following I/O methods:
* Take no input and output the sequence indefinitely,
* Take a (0- or 1-based) index i and output the i-th term,
* Take a non-negative integer i and output the first i terms.
The shortest code in bytes wins.
[Answer]
# [Python 3](https://docs.python.org/3/), 119 bytes
Outputs the sequence indefinitely.
```
from unicodedata import*
p,*a=b'5NE'
for x in a:
if x>45:n=abs(p-x);a+=name(chr(13144+n))[38:print(n%24)].encode();p=x
```
[Try it online!](https://tio.run/##Fc0xDsIgFADQnVP8xRRaNanQxNDg5uoFjMNvCykDH4KY4Okxvgu89C17JNmayzHAh/waN7thQfAhxVx6lo49mqWbHveOuZihgidAzcA7qDc1aTK4vHk6VTHjYAiD5eue@ShHpQYS4imvOmVPhdPhosTrbOmfcDEnU1v7AQ "Python 3 – Try It Online")
Python's `unicodedata.name` allows us to access the name of a unicode character. It happens that the characters with codepoints in the range `0x3358..0x336D` partially contain all of the required words (as can be seen in [this](https://unicode.org/Public/UNIDATA/NamesList.txt) list). The only nuance is at `twentyone`, of which `name()` gives us `twenty-one` instead. This is fixed with a simple `if x>45`, which ignores any existing `-`. This allows us to save over 70 bytes in total. Other than the sneaky `unicodedata.name`, it is essentially the same as the answer below.
# [Python 3](https://docs.python.org/3/), 196 bytes
```
p,*a=b'Wne'
for x in a:n=abs(x-p);print(n%22);p=x;a+=b'zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,four,fif,,seven,eigh,,,twentyone,,'.split(b',')[n]+b'teen'*(12<n<20)
```
[Try it online!](https://tio.run/##TY3BCsIwEETvfkUvkrRdRePNtt/hQTwksLWBsgnJ2qb@fGwFwdvM8B7jFx4cXXL2UOnOiBuh2PUuFKmwVOgrddpEmQ6@bHywxJL2Sq25S42uV/6NwYEjBJ4d8BAQoXevAL2dEKJNEHFCArTPgYHsBm51/K4847hiPNjws3r4MwA2hHjZDkAcox8tSyNAlHd61EYwIolKnlVLrTqVOX8A "Python 3 – Try It Online")
### Explanation
We start off with `a = b'ne'`, which will keep track of all the English words.
Note that `ne` are the last two letters of `one` (the first number in the sequence). In the following for loop, we iterate over `a`, and in each iteration we add a word to the sequence based on the value of `abs(x-p)`, where `x` and `p` are the current and previous letters in `a`, respectively.
The illustration below, while not an exact model, roughly describes the algorithm I am using to construct the sequence:
```
'one', n = abs(s[2]-s[1]) = abs('e'-'n') = 9 ->
'onenine', n = abs(s[3]-s[2]) = abs('n'-'e') = 9 ->
'oneninenine', n = abs(s[4]-s[3]) = abs('i'-'n') = 5 ->
'onenineninefive', n = abs(s[5]-s[4]) = abs('n'-'i') = 5 ->
...
```
One last thing to mention is the peculiar `W` in the initialization of `a`, or the strange `%22` within the `print` statement. These are both needed to print the initial `1`. We may get rid of them for **[190 bytes](https://tio.run/##TY3BCsIwEETvfkVvSdtVtN5s@yXiIYGNDZRNSNY29edjKgjeZob3GL/x5Oias4dGjVoQioNxoUqVpUrdaFQ6ynT0de@DJZZUwph61Rb2jcGBIwReHfAUEMG4VwBjF4RoE0RckADtc2Igu4N7nb8rrzgXjCcbfpaBPwNgR4i3ciBO0c@WpRYg6js9Wi0YkUQjL91AQ3euc/4A "Python 3 – Try It Online")**, but the `1` at the beginning would be omitted:
```
p,*a=b'ne'
for x in a:n=abs(x-p);print(n);p=x;a+=b'zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,four,fif,,seven,eigh,,,twentyone'.split(b',')[n]+b'teen'*(12<n<20)
```
This is currently the shortest fix I could find for eliminating this edge case, though there's likely a shorter approach (I'll exclude an explanation for it as an exercise to the reader).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~240~~ 228 bytes
*Thanks to @ovs for pointing out that 16, 19 and 20 are never used*
A naive implementation. Returns the \$n\$th term, 0-indexed.
```
f=(n,a=[1])=>1/a[n]?a[n]:f(n,[...Buffer(a.map(x=>`ZeroOneTwoThreeFourFiveSixSevenEightNineTenElevenTwelveThirteenFourteenFifteenXSeventeenEighteenXXTwentyone`.match(/.[a-z]*/g)[x]).join``)].map(x=>Math.abs(a-(a=x&31))).slice(1))
```
[Try it online!](https://tio.run/##NZDBasMwEETv@QodQpGaWo7JralSKDS3tof4EGoMUt2VreCuguw4bo2/3ZUMuew8hhl22ZPqVFM4c24jtN8wTVpQfFAiS3ImdkmsMsyfw3jU3s845y8XrcFRxX/UmfZiJz/B2Q@E9GrTygHs7cXtTQcH0x@gA3w1ZdW@Gx/wXAcnvULdQVoZ1wJgyM9qdJDjXAo0F4Nz9AVsfy2C9EvboqIxz1T0l9/HJcv6nPGTNSgly283vam24uqroSqiSvR3m4QxxpvaFEA9Tto6ikSQ9ZYgeSKbdYDVipFhQUhhsbE18NqWVCq6HHBkPrsc/AfYKNl2MU7/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~69~~ 64 bytes
```
ị“£3ṃ×ʋƁṘFqœ<ɦẎĠ_NɗṾDæ¢$⁽ċ¶Ọɦµ⁽ƭẈġȥ⁶J§GaĊƙ-ƬėƓjḢƥ4¶;»Ḳ¤FOạƝ
1Ç¡ḣ
```
[Try it online!](https://tio.run/##AYcAeP9qZWxsef//4buL4oCcwqMz4bmDw5fKi8aB4bmYRnHFkzzJpuG6jsSgX07Jl@G5vkTDpsKiJOKBvcSLwrbhu4zJpsK14oG9xq3huojEocil4oG2SsKnR2HEisaZLcasxJfGk2rhuKLGpTTCtjvCu@G4ssKkRk/huqHGnQoxw4fCoeG4o////zc "Jelly – Try It Online")
A pair of links that is called as a monad with an integer input \$n\$ and returns the first \$n\$ terms. Slow for larger n (since it actually generates far more terms than needed before truncating the list). At a cost of a byte, [this](https://tio.run/##AYsAdP9qZWxsef//4buL4oCcwqMz4bmDw5fKi8aB4bmYRnHFkzzJpuG6jsSgX07Jl@G5vkTDpsKiJOKBvcSLwrbhu4zJpsK14oG9xq3huojEocil4oG2SsKnR2HEisaZLcasxJfGk2rhuKLGpTTCtjvCu@G4ssKkRk/huqHGneG4owoxw6fGrOG5qv///zMw) is much more efficient.
Thanks to @JonathanAllan for saving 5 bytes!
## Explanation
### Helper link
```
ị | Index into:
“£…;»Ḳ¤ | - "one two three four … twentyone zero", split on spaces
F | Flatten
ØaiⱮ | Index of each character in the lowercase alphabet
ạƝ | Absolute differences of neighbouring pairs
```
### Main link
```
1 | Starting with 1:
Ç¡ | Call the helper link n times
ḣ | First n values
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 117 bytes
outputs the first i terms
```
(s=#;NestWhile[Abs@Differences@Flatten[LetterNumber[Characters@IntegerName@#/."-"->""]&/@#]&,{1},Tr[1^#]<s&][[;;s]])&
```
[Try it online!](https://tio.run/##DcnRCoIwFIDhd9lgFGjqtRmTIghCCoIuxgmmHHXgdrFzvIqefXn18/F7yzN6y26waWqeq0PWaUeNrDskfs9uQdP2pC9uHDFiGJD0dbHMGMwdt8Ru9T1Gc55ttMNm0rfAOG3DetSyOIhc5CchQBVagsq@1S97RVN9JBxJgTF1TQB7lR7RBdaTqcoSUvoD "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 83 bytes
```
1 9"£{`λḭ ƛ» ∧ḭ ⟇¯ ײ ß• ⌐≤ ƈḞ ∵‹ ¢Ṗ Ẇ„ ⟨ǐ t¥ẏ⟑⌈ ⟇¯⟑⌈ Ṡ□ ⌐≤⟑⌈ e⋏ṫ⟑⌈ ←⊍λḭ`⌈¥‹İṅC¯ȧ…£
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=1%209%22%C2%A3%7B%60%CE%BB%E1%B8%AD%20%C6%9B%C2%BB%20%E2%88%A7%E1%B8%AD%20%E2%9F%87%C2%AF%20%C3%97%C2%B2%20%C3%9F%E2%80%A2%20%E2%8C%90%E2%89%A4%20%C6%88%E1%B8%9E%20%E2%88%B5%E2%80%B9%20%C2%A2%E1%B9%96%20%E1%BA%86%E2%80%9E%20%E2%9F%A8%C7%90%20t%C2%A5%E1%BA%8F%E2%9F%91%E2%8C%88%20%E2%9F%87%C2%AF%E2%9F%91%E2%8C%88%20%E1%B9%A0%E2%96%A1%20%E2%8C%90%E2%89%A4%E2%9F%91%E2%8C%88%20e%E2%8B%8F%E1%B9%AB%E2%9F%91%E2%8C%88%20%E2%86%90%E2%8A%8D%CE%BB%E1%B8%AD%60%E2%8C%88%C2%A5%E2%80%B9%C4%B0%E1%B9%85C%C2%AF%C8%A7%E2%80%A6%C2%A3&inputs=&header=&footer=)
Outputs the values infinitely
[Answer]
# [Factor](https://factorcode.org/) + `math.text.english`, ~~109~~ 98 bytes
```
[ { 1 } [ [ number>text R/ \sand|,|-| / ""re-replace >array ] map-flat differences vabs ] repeat ]
```
[Try it online!](https://tio.run/##LU67TsNAEOzzFaPU2BGiAyktoqEAUYUUm8vYWXE@n/Y2UQLm280F0HTz7iT4aPPb69Pz4z3ETC4Fg/ihdZ69ZeqjlsMfU1xci2v4d5x4zRYYe54zstH9kk2T44OWGNEz0STqZw2OqSCMQ9ZIa4@uUV1Z8LBY3M0bfOEW39hUpOOwo62v83hZ4b1I2k83UzNhheXS2BhzlECsf99iW8/kpovi2GvX0ZhC7T3JrlStmlmV7RwkRrTzDw "Factor – Try It Online")
Takes a 0-based index and outputs the i-th term.
* `{ 1 } [ ... ] repeat` Call a quotation a given number of times, transforming our starting sequence `{ 1 }` that many times.
* `[ ... ] map-flat` Apply a quotation to each element of a sequence, collecting each result into a flat sequence.
* `number>text` Convert a number to a string, like `2222 -> "two thousand, two hundred and twenty-two"`.
* `R/ \sand|,|-| / ""re-replace` Since number>text produces commas, spaces, hyphens and `" and"`, strip them out with a regular expression.
* `>array` Convert the string to an array (e.g. `"hi" -> { 104 105 }`). This is necessary for `differences` to work properly.
* `differences` Take the first-order forward difference.
* `vabs` Take the absolute value of a sequence. (Like `[ abs ] map`, but shorter).
] |
[Question]
[
The primorial \$p\_n\#\$ is the product of the first \$n\$ primes. The sequence begins \$2, 6, 30, 210, 2310\$.
A [Fortunate number](https://en.wikipedia.org/wiki/Fortunate_number), \$F\_n\$, is the smallest integer \$m > 1\$ such that \$p\_n\# + m\$ is prime. For example \$F\_7 = 19\$ as:
$$p\_7\# = 2\times3\times5\times7\times11\times13\times17 = 510510$$
Adding each number between \$2\$ and \$18\$ to \$510510\$ all yield composite numbers. However, \$510510 + 19 = 510529\$ which is prime.
The Fortunate numbers below \$200\$ are
$$3, 5, 7, 13, 17, 19, 23, 37, 47, 59, 61, 67, 71, 79, 89, 101, 103, 107, 109, 127, 151, 157, 163, 167, 191, 197, 199$$
We'll say an integer \$n\$ is a "Fortunate sum" if it can be expressed as the sum of two distinct Fortunate numbers. For example, \$22 = 3 + 19 = 5 + 17\$, so \$22\$ can be expressed as the sum of two Fortunate numbers, and so is a "Fortunate sum"
You are to take an integer \$n\$ as input and output a truthy value if \$n\$ is a Fortunate sum and a falsey value otherwise. You may swap the order (falsey indicates it is a Fortunate sum) if you wish. You may take input and output in any [convenient format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
## Test cases
The first line is the Fortunate sums less than 100 (truthy values) and the second are the integers less than or equal to 100 that aren't Fortunate sums
```
8 10 12 16 18 20 22 24 26 28 30 32 36 40 42 44 50 52 54 56 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98
1 2 3 4 5 6 7 9 11 13 14 15 17 19 21 23 25 27 29 31 33 34 35 37 38 39 41 43 45 46 47 48 49 51 53 55 57 58 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 100
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~130~~ 128 bytes
```
a n=or[f x&&f(n-x)|x<-[2..n],2*x<n]
f m=or[and[p(x+y)/=(y<m)|y<-[2..m]]|x<-scanl1(*)$filter p[2..m]]
p n=all((>0).mod n)[2..n-1]
```
[Try it online!](https://tio.run/##NY1LDoIwFAD3nKILQ1q0VTBxBV7BAzRdvABVwuujARYl4exW8bOemcwDpr5FjBEYVcOoLQtpajnJINZQSl0oReZQZKEkk1jmNgeo0Z6H/SKOFV9KJ9blazpjtmiqgTDnmdjZDud2ZP4HE/@eACLn15NQbmgYic9B5iY66KjyY0fzPwOmc6XOFxOftUW4T1Heihc "Haskell – Try It Online")
This solution is based on the following observation.
**Fact.** An integer \$m>1\$ is Fortunate if and only if, for some prime number \$p\_n<m\$, \$m\$ is the smallest integer \$>1\$ such that
\$
p\_1 p\_2\cdots p\_n+m
\$
is prime.
*Proof.* The claim follows easily from the fact that if \$p\_n\ge m\$ then there is some \$p\_i\$ with \$i\le n\$ such that \$p\_i\mid m\$, and therefore \$p\_i\mid p\_1 p\_2\cdots p\_n+m\$.
At this point, checking if a number \$m\$ is Fortunate is trivial: we just have to check the condition for all the prime numbers up to \$m\$.
## Explanation of the code
```
p n=all((>0).mod n)[2..n-1]
```
The standard prime-checking function. Only works for `n>1`, but that's ok.
---
```
f m=or[and[p(x+y)/=(y<m)|y<-[2..m]]|x<-scanl1(*)$filter p[2..m]]
```
A function to check whether a number `m` is Fortunate. As explained above, it calculates the primorials \$\texttt{x}=p\_1p\_2\cdots p\_n\$ until \$p\_n\le\texttt{m}\$ and tests whether `m` is the smallest integer \$\texttt{y}>1\$ such that \$\texttt{x}+\texttt{y}\$ is prime.
---
```
a n=or[f x&&f(n-x)|x<-[2..n],2*x<n]
```
The final function, to check whether `n` is a Fortunate sum. Pretty straightforward, the only thing to be careful of is that `x` and `n-x` must be different: this is the reason why we only iterate over values of `x` such that `2*x<n`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 106 bytes
```
Check[Tr[1^Union[#&@@IntegerPartitions[#,{2},Array[NextPrime[a=Times@@Array[Prime,#]+1]-a+1&,#]]]]>1,1>2]&
```
[Try it online!](https://tio.run/##TY5NSxxREEX3@RWBgdl4gq/qfdVbKC1ZZRMMmFXTQiPN2MiM0LaQIPPb20KzSG3upaq49xzH9XE6juv8MG6Hq@374/Tw1N8tvdz/Ps3Pp36377ofp3U6TMvtuKzz6suXfsebnrlZlvFv/3P6s94u83Hqx6s7l5eu@zx8LNkNFzJ8Gy9k79bnWpBrHfabn0/r18vu1@s8rf3hsnszJCCKFMTQgCqa0IIaMRCVWEiBpKREDmQluymUQFFKorg3aqAqNVEL1bCAKZawghkt0JSWaIVm5@HLB0r/T/8nErwSb8BzaIjDRyQhGalIQ/0lohmtaCMKMRITMRMr0bkbSUiekklOX0lGamQhR3ImV7KRG0UokeJdldKoQo3UTK3UhgkWsYxVrNGEFmmZ5lwOFsJ52LZ3 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to ChartZBelatedly! (use the built-in for choose-2.)
Thanks to [Delfad0r](https://codegolf.stackexchange.com/users/82619/delfad0r) for the simple explanation in their [Haskell answer](https://codegolf.stackexchange.com/a/220745/53748) proving that this works, I probably would not have posted it otherwise!
```
ÆRPƤ‘Æn_ƊŒc§ċ
```
A monadic Link accepting an integer \$n\$ that yields a positive integer if \$n\$ is a Fortunate Sum, or zero if not.
**[Try it online!](https://tio.run/##ASIA3f9qZWxsef//w4ZSUMak4oCYw4ZuX8aKxZJjwqfEi////zE4 "Jelly – Try It Online")** Or see [A split of \$n\leq 100\$ into non-Fortunate and Fortunate Sums](https://tio.run/##AS0A0v9qZWxsef//w4ZSUMak4oCYw4ZuX8aKxZJjwqfEi//Dh@KCrOG5oMSg//8xMDA).
### How?
```
ÆRPƤ‘Æn_ƊŒc§ċ - Link: integer, n e.g. 18
ÆR - primes between 2 and n inclusive [2,3, 5, 7, 11, 13, 17]
Ƥ - for prefixes:
P - product [2,6 ,30,210,2310,30030,510510]
Ɗ - last three links as a monad, f(x=that):
‘ - increment (x) [3,7 ,31,211,2311,30031,510511]
Æn - next, strictly greater, prime [5,11,37,223,2333,30047,510529]
_ - subtract (x) [3,5, 7, 13, 23, 17, 19]
Œc - choose-2 [[3,5],[3,7],[3,13],[3,23],[3,17],[3,19],[5,7],[5,13],[5,23],[5,17],[5,19],[7,13],[7,23],[7,17],[7,19],[13,23],[13,17],[13,19],[23,17],[23,19],[17,19]]
§ - sums [8,10,16,26,20,22,12,18,28,22,24,20,30,24,26,36,30,32,40,42,36]
ċ - count occurrences (of n) 1 (truthy)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~35~~ ~~31~~ ~~29~~ 28 bytes
```
Lʒ©ÅPηPε2®Ÿ+pJΘ}à}ãʒË_}OI¢Íd
```
[Try it online!](https://tio.run/##ATYAyf9vc2FiaWX//0zKksKpw4VQzrdQzrUywq7FuCtwSs6YfcOgfcOjypLDi199T0nCosONZP//MTg "05AB1E – Try It Online")
-4 bytes thanks to ovs
A port of [Delfad0r](https://codegolf.stackexchange.com/users/82619/delfad0r)'s [Haskell answer](https://codegolf.stackexchange.com/a/220745).
] |
[Question]
[
The usual [correlation coefficient](https://en.wikipedia.org/wiki/Correlation_coefficient) (in 2d) measures how well a set of points can be described by a line, and if yes, its sign tells us whether we have a positive or negative correlation. But this assumes that coordinates of the points can actually interpreted quantitatively for instance as measurements.
If you cannot do that but you can still *order* the coordinates, there is the *rank correlation coefficient*: It measures how well the points can be described by a *monotonic* function.
### Challenge
Given a list of 2d points, determine their *rank correlation coefficient*.
### Details
* You can assume the input to be positive integers (but you don't have to), or any other "sortable" values.
* The points can be taken as a list of points, or two lists for the x- and y-coordinates or a matrix or 2d array etc.
* The output must be a floating point or rational type, as it should represent a real number between 0 and 1.
### Definitions
**Rank:** Given a list of numbers `X=[x(1),...,x(n)]` we can assign a positive number `rx(i)` called *rank* to each entry `x(i)`. We do so by sorting the list and assigning the index of `x(i)` in the sorted list `rx(i)`. If two or more `x(i)` have the same value, then we just use the arithmetic mean of all the corresponding indices as rank. Example:
```
List: [21, 10, 10, 25, 3]
Indices sorted: [4, 2, 3, 5, 1]
```
The number `10` appears twice here. In the sorted list it would occupy the indices `2` and `3`. The arithmetic mean of those is `2.5` so the ranks are
```
Ranks: [4, 2.5, 2.5, 5, 1]
```
**Rank Correlation Coefficient**: Let `[(x(1),y(1)),(x(2),y(2)),...,(x(n),y(n))]` be the given points where each `x(i)` and `y(i)` is a real number (wlog. you can assume it is an integer)
For each `i=1,...,n` we compute the *rank* `rx(i)` and `ry(i)` of `x(i)` and `y(i)` respectively.
Let `d(i) = rx(i)-ry(i)` be the *rank difference* and let `S` be the sum `S = d(1)^2 + d(2)^2 + ... + d(n)^2`. Then the *rank correlation coefficient* `rho` is given by
```
rho = 1 - 6 * S / (n * (n^2-1))
```
### Example
```
x y rx ry d d^2
21 15 4 5 -1 1
10 6 2&3 -> 2.5 2 0.5 0.25
10 7 2&3 -> 2.5 3 -0.5 0.25
25 11 5 4 1 1
3 5 1 1 0 0
rho = 1 - 6 * (1+0.25+0.25+1)/(5*(5^2-1)) = 0.875
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 33 bytes
```
,it7#utb,&S]2XQw)]-Us6*1GntUq*/_Q
```
[Try it online!](https://tio.run/##y00syfn/XyezxFy5tCRJRy041igisFwzVje02EzL0D2vJLRQSz8@8P//aCNDawVDAwg2MrVWMI7lijYE0mbWCuZAUaCsaSwA "MATL – Try It Online")
### Explanation
```
, % Do...twice
it % Input a numeric vector. Duplicate
7#u % Replace each element by a unique integer label (1, 2, ...)
t % Duplicate
b % Bubble up: moves original numeric vector to top
, % Do...twice
&S % Sort and push the indices of the sorting
] % End
% The above do...twice loop gives the sorted indices (as
% explained in the challenge text) for the current input
2XQ % Compute average for entries with the same integer label
w % Swap: move vector of integer labels to top
) % Index. This gives the rank vector for the current input
] % End
- % Subtract the two results. Gives d
Us % Square each entry, sum of vector. S
6* % Times 6. Gives 6*S
1G % Push first input vector again
n % Number of entries. Gives n
t % Duplicate
Uq % Square, minus 1. Gives n^2-1
* % Times. Gives n*(n^2-1)
/ % Divide. Gives 6*S/(n*(n^2-1))
_Q % Negate, plus 1. Gives 1-6*S/(n*(n^2-1))
```
[Answer]
# [R](https://www.r-project.org/), ~~64~~ 60 bytes
```
function(x,y)1-6*sum((rank(x)-rank(y))^2)/((n=sum(x|1))^3-n)
```
[Try it online!](https://tio.run/##HYlZCoQwEAWv85500I5Ev7zKgAQCIrbgAhHm7nGBgoKqraShpNPiMa2GLBfVddV@LsA22oxM9/kif541YMM781@f0DpjSYjwKtq8@CAtJUKDdNKLqgSy3A "R – Try It Online")
[`rank`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/rank.html) in R is the builtin that computes the desired rank; the rest is just the math to do the rest of the job.
*Thanks to [CriminallyVulgar](https://codegolf.stackexchange.com/users/72784/criminallyvulgar) for saving 4 bytes*
As mentioned [in the comments](https://codegolf.stackexchange.com/questions/138305/rank-correlation-coefficient#comment339175_138305), the stated definition of rank correlation coefficient doesn't correspond precisely to the Spearman correlation coefficient, else a valid answer would be 26 bytes:
```
function(x,y)cor(x,y,,"s")
```
[Answer]
# [Python 3](https://docs.python.org/3/), 141 bytes
```
lambda X,Y,Q=lambda U,S=sorted:[S(U).index(y)+S(U).count(y)/2+.5for y in U]:1-6*sum((i[1]-i[0])**2for i in zip(Q(X),Q(Y)))/(len(X)**3-len(X))
```
This defines an anonymous function which takes input as two lists corresponding to the `x` and `y` values. Output is returned as a floating-point value.
[Try it online!](https://tio.run/##LczLCoMwEIXhV8lyEsdLIrEg@BAigppmYaulAY3iBWpf3mpbmMX54GfGbXkONtyr5Lp3dX9ralJgiWnyR45ZMg/T0jaxyiCnnrFN@4KNOl/dh9Uuh3zhePIxTGQjxpJcx9yN2Lz2AEZx7RoVaMqYOAtzFm8zQgoFxRRKSqkPXWsPMha6v0X3cTLH6wqU4MiD84TEUCNRXGKEF@QcpT7CDw "Python 3 – Try It Online")
[Answer]
# Mathematica, 89 bytes
```
(F[x_]:=Min@N@Mean@Position[Sort@x,#]&;1-6Tr[(F@#/@#-F@#2/@#2)^2]/((y=Length@#)(y^2-1)))&
```
[Try it online!](https://tio.run/##JYnRCoMgGEZfRRBCQWk6arAh/FddrRFsd2IjRi1hUygviujZnbCLwzl837cLo33NcVCRVHp5mrOqrYMb1H3noPGzDdY7ffdTgIVhk10ELx8@dB9NKsA5YJ4kkyVtpckJWdW1d@8wAqZkbSUXlNIsNpN1AcGgNykYEoc/smDouDO0iRQlQ6c0p7vYTfwB "Mathics – Try It Online") (in order to work on mathics, "Tr" is replaced with "Total")
] |
[Question]
[
An [arborally satisfied point set](https://en.wikipedia.org/wiki/Geometry_of_binary_search_trees#Arborally_satisfied_point_sets) is a 2D set of points such that, for any axis-aligned rectangle that can be formed using two points in the set as opposite corners, that rectangle contains or touches at least one other point. Here is an equivalent definition from Wikipedia:
>
> A point set is said to be arborally satisfied if the following property holds: for any pair of points that do not both lie on the same horizontal or vertical line, there exists a third point which lies in the rectangle spanned by the first two points (either inside or on the boundary).
>
>
>
The following image illustrates how the rectangles are formed. This point set is NOT arborally satisfied because this rectangle needs to contain at least one more point.
[](https://i.stack.imgur.com/PbO0R.jpg)
In ASCII art, this point set can be represented as:
```
......
....O.
......
.O....
......
```
A slight modification can make this arborally satisfied:
```
......
....O.
......
.O..O.
......
```
Above, you can see that all rectangles (of which there is only one) contain at least three points.
Here is another example of a more complex point set that is arborally satisfied:
[](https://i.stack.imgur.com/wDknh.jpg)
For any rectangle that can be drawn spanning two points, that rectangle contains at least one other point.
## The Challenge
Given a rectangular grid of points (which I represent with `O`) and empty space (which I represent with `.`), output a *truthy* value if it is arborally satisfied, or a *falsey* value if it is not. This is code-golf.
Additional rules:
* You can choose to have the characters `O` and `.` swapped out with any other pair of printable ASCII characters. Simply specify which character mapping your program uses.
* The grid will always be rectangular. A trailing newline is allowable.
## More Examples
**Arborally satisfied:**
```
.OOO.
OO...
.O.OO
.O..O
....O
..O..
OOOO.
...O.
.O.O.
...OO
O.O.
..O.
OOOO
.O.O
OO..
...
...
...
...
..O
...
O.....
O.O..O
.....O
OOO.OO
```
**Not Arborally Satisfied:**
```
..O..
O....
...O.
.O...
....O
..O..
O.OO.
...O.
.O.O.
...OO
O.....
..O...
.....O
```
[Answer]
# [Snails](https://github.com/feresum/PMA), 29 ~~30 39~~ bytes
```
!{t\Oo\.+c\.,\O!{t\O{w!(.,~}2
```
It works by tracing out 2 sides of the rectangle, and then checking whether there is some square containing an O such that traveling in a straight line from the square in 2 of the cardinal directions would result in hitting a side of the rectangle.
Prints the maximum of 1 and the grid's area if the input is "arborally satisfied"; otherwise 0.
[Answer]
# Oracle SQL 11.2, ~~364~~ 344 bytes
```
WITH v AS(SELECT MOD(LEVEL-1,:w)x,FLOOR((LEVEL-1)/:w)y FROM DUAL WHERE'O'=SUBSTR(:g,LEVEL,1)CONNECT BY LEVEL<=LENGTH(:g))SELECT a.*,b.*FROM v a,v b WHERE b.x>a.x AND b.y>a.y MINUS SELECT a.*,b.*FROM v a,v b,v c WHERE((c.x IN(a.x,b.x)AND c.y>=a.y AND c.y<=b.y)OR(c.y IN(a.y,b.y)AND c.x>=a.x AND c.x<=b.x))AND(c.x,c.y)NOT IN((a.x,a.y),(b.x,b.y));
```
:g is the grid as a string
:w is the width of the grid
Returns no line as truthy, return the rectangles that do not match the criteria as falsy
Un-golfed
```
WITH v AS
(
SELECT MOD(LEVEL-1,:w)x,FLOOR((LEVEL-1)/:w)y,SUBSTR(:g,LEVEL,1)p
FROM DUAL
WHERE 'O'=SUBSTR(:g,LEVEL,1)
CONNECT BY LEVEL<=LENGTH(:g)
)
SELECT a.*,b.*FROM v a,v b
WHERE b.x>a.x AND b.y>a.y
MINUS
SELECT a.*,b.*FROM v a,v b,v c
WHERE((c.x IN(a.x,b.x) AND c.y>=a.y AND c.y<=b.y) OR (c.y IN(a.y,b.y) AND c.x>=a.x AND c.x<=b.x))
AND(c.x,c.y)NOT IN((a.x,a.y),(b.x,b.y));
```
The view v compute the coordinates of each O point.
The first part of the minus return all rectangles, the where clause insures that a point can not be paired with itself.
The second part search for a third point in each rectangle. That point needs to have one coordinate,x or y, equals to that coordinate for one of the two points defining the rectangle. The other coordinate of that third point needs to be in the range bounded by that coordinate for each of the points defining the rectangle.
The last part of the where clause insures that the third point is not one of the two points defining the rectangle.
If all the rectangles have at least a third point then the first part of the minus is equal to the second part and the query returns nothing.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 38 bytes
```
Ti2\2#fh!XJ"J@-XKtAZ)"@K-@/Eq|1>~As2>*
```
This uses a 2D char array as input, with rows separated by `;`. So the first example is
```
['......';'....O.';'......';'.O..O.';'......']
```
The rest of the test cases in this format are as follows.
* Arborally satisfied:
```
['.OOO.';'OO...';'.O.OO';'.O..O';'....O']
['..O..';'OOOO.';'...O.';'.O.O.';'...OO']
['O.O.';'..O.';'OOOO';'.O.O';'OO..']
['...';'...';'...']
['...';'..O';'...']
['O.....';'O.O..O';'.....O']
['OOO.OO']
```
* Not arborally satisfied:
```
['..O..';'O....','...O.';'.O...';'....O']
['..O..';'O.OO.';'...O.';'.O.O.';'...OO']
['O.....';'..O...';'.....O']
```
[**Try it online!**](http://matl.tryitonline.net/#code=VGkyXDIjZmghWEoiSkAtWEt0QVopIkBLLUAvRXF8MT5-QXMyPio&input=WycuT09PLic7J09PLi4uJzsnLk8uT08nOycuTy4uTyc7Jy4uLi5PJ10) You can also [**verify all test cases at once**](http://matl.tryitonline.net/#code=YApUaTJcMiNmaCFYSiJKQC1YS3RBWikiQEstQC9FcXwxPn5BczI-KgpdXURU&input=WycuT09PLic7J09PLi4uJzsnLk8uT08nOycuTy4uTyc7Jy4uLi5PJ10KWycuLk8uLic7J09PT08uJzsnLi4uTy4nOycuTy5PLic7Jy4uLk9PJ10KWydPLk8uJzsnLi5PLic7J09PT08nOycuTy5PJzsnT08uLiddClsnLi4uJzsnLi4uJzsnLi4uJ10KWycuLi4nOycuLk8nOycuLi4nXQpbJ08uLi4uLic7J08uTy4uTyc7Jy4uLi4uTyddClsnT09PLk9PJ10KWycuLk8uLic7J08uLi4uJywnLi4uTy4nOycuTy4uLic7Jy4uLi5PJ10KWycuLk8uLic7J08uT08uJzsnLi4uTy4nOycuTy5PLic7Jy4uLk9PJ10KWydPLi4uLi4nOycuLk8uLi4nOycuLi4uLk8nXQ).
### Explanation
The code first gets the coordinates of characters `O` in the input. It then uses two nested loops. The outer loop picks each point P (2-tuple of its coordinates), compares with all points, and keeps points that differ from P in the two coordinates. Those are the points than can form a rectangle with P. Call them set R.
The inner loop picks each point T from R, and checks if the rectangle defined by P and T includes at least 3 points. To do that, it subtracts P from all points; that is, moves the origin of coordinates to P. A point is in the rectangle if each of its coordinates divided by the corresponding coordinate of T is in the closed interval [0, 1].
```
T % push "true"
i % take input 2D array
2\ % modulo 2: gives 1 for 'O', 0 for '.'
2#f % row and column coordinates of ones. Gives two column arrays
h! % concatenate horizontally. Transpose. Each point is a column
XJ % copy to clipboard J
" % for each column
J % push all points
@- % subtract current point (move to origin)
XK % copy to clipboard K
tA % logical index of points whose two coordinates are non-zero
Z) % keep only those points. Each is a column
" % for each column (point)
@K- % push that point. Subtract all others
@/ % divide by current point
Eq|1>~ % true if in the interval [0,1]
A % true if that happens for the two coordinates
s % sum: find out how many points fulfill that
2> % true if that number is at least 3
* % multiply (logical and). (There's an initial true value at the bottom)
% end
% end
% implicit display
```
[Answer]
# PHP, 1123 bytes, 851 bytes, 657 bytes
(newbie php)
```
<?php
$B=array_map("str_split",array_map("trim",file('F')));$a=[];$b=-1;foreach($B as $c=>$C){foreach($C as $d=>$Z){if($Z=='O'){$a[++$b][]=$c;$a[$b][]=$d;}}}$e=array();foreach($a as $f=>$l){foreach($a as $g=>$m){$h=$l[0];$i=$l[1];$j=$m[0];$k=$m[1];if($h!=$j&&$i!=$k&&!(in_array([$g,$f],$e,1)))$e[]=[$f,$g];}}$A=array();foreach($e as $E){$n=$E[0];$o=$E[1];$q=$a[$n][0];$s=$a[$n][1];$r=$a[$o][0];$t=$a[$o][1];$u=($q<$r)?$q:$r;$v=($s<$t)?$s:$t;$w=($q>$r)?$q:$r;$X=($s>$t)?$s:$t;$Y=0;foreach($a as $p){$x=$p[0];$y=$p[1];if($x>=$u&&$x<=$w&&$y>=$v&&$y<=$X){$Y=($x==$q&&$y==$s)||($x==$r&&$y==$t)?0:1;}if($Y==1)break;}if($Y==1)$A[]=1;}echo count($A)==count($e)?1:0;
```
explaination (commented code) :
```
<?php
//read the file
$lines=array_map("str_split",array_map("trim",file('F'))); // grid in file 'F'
//saving coords
$coords=[]; // new array
$iCoord=-1;
foreach($lines as $rowIndex=>$line) {
foreach($line as $colIndex=>$value) {
if ($value=='O'){
$coords[++$iCoord][]=$rowIndex;//0 is x
$coords[$iCoord][]=$colIndex; //1 is y
}
}
}
/* for each point, draw as many rectangles as other points
* without creating 'mirror' rectangles
*/
$rectangles=array();
foreach ($coords as $point1Index=>$point1) {
//draw
foreach ($coords as $point2Index=>$point2) {
$point1X=$point1[0];
$point1Y=$point1[1];
$point2X=$point2[0];
$point2Y=$point2[1];
//if not on the same line or on the same column, ...
if ($point1X!=$point2X && // same line
$point1Y!=$point2Y && // same column
!(in_array([$point2Index,$point1Index],$rectangles,true)) //... and if no 'mirror one' already
) $rectangles[]=[$point1Index,$point2Index]; //create a new rectangle
}
}
//now that we have rectangles and coords
//try and put a third point into each
$tests=array();
foreach ($rectangles as $rectangle) {
$pointA=$rectangle[0]; // points of the rectangle
$pointB=$rectangle[1]; // __________"____________
$xA=$coords[$pointA][0];
$yA=$coords[$pointA][1];
$xB=$coords[$pointB][0];
$yB=$coords[$pointB][1];
$minX=($xA<$xB)?$xA:$xB;
$minY=($yA<$yB)?$yA:$yB;
$maxX=($xA>$xB)?$xA:$xB;
$maxY=($yA>$yB)?$yA:$yB;
$arborally=false;
foreach ($coords as $point) {
$x=$point[0];
$y=$point[1];
if ($x>=$minX &&
$x<=$maxX &&
$y>=$minY &&
$y<=$maxY) {
$arborally=($x==$xA&&$y==$yA) || ($x==$xB&&$y==$yB)?0:1; //same point (pointA or pointB)
}
if ($arborally==true) break;//1 found, check next rectangle
}
if ($arborally==true) $tests[]=1;//array of successes
}
echo count($tests)==count($rectangles)?1:0; //if as many successes than rectangles...
?>
```
[Answer]
# C, 289 bytes
```
a[99][99],x,X,y,Y,z,Z,i,c;main(k){for(;x=getchar(),x+1;x-10||(y=0,i++))a[y++][i]=x;for(;X<i;X++)for(x=0;a[x][X]-10;x++)for(Y=X+1;Y<i;Y++)for(y=0;a[y][Y]-10;y++)if(x-y&&!(a[x][X]-79||a[y][Y]-79)){c=0;for(Z=X;Z<=Y;Z++)for(z=x<y?x:y;z<=(x>y?x:y);)a[z++][Z]-79||c++;c-2||(k=0);}putchar(k+48);}
```
Requires trailing newline, which is permitted (without the newline, the code would be two bytes larger). Outputs 0 (not arborally satisfied) or 1 (arborally satisfied).
] |
[Question]
[
A [connected](http://mathworld.wolfram.com/ConnectedGraph.html) graph is a graph that contains a path between any two vertices.
### Challenge
Build a [2-input NAND-gate] circuit that determines whether a 4-vertex graph is connected.
(A gate's 2 inputs *can* be the same input bit or other gate.)
Output True if the graph is connected, and False otherwise.
### Input
The six possible edges of a [simple graph](http://mathworld.wolfram.com/SimpleGraph.html) with 4 vertices:
[ 0e1 , 0e2 , 1e2 , 0e3 , 1e3 , 2e3 ]
where aeb represents whether there is an edge between vertices ***a*** and ***b***
Connectedness is equivalent to the following conditions:
* If less than 3 inputs are True then output False.
* If more than 3 inputs are True then output True.
* If exactly 3 inputs are True and they form a [triangle](http://mathworld.wolfram.com/TriangleGraph.html) then output False.
* Otherwise, output True.
The answer that uses the fewest gates wins. Ties will be broken by
the lowest circuit depth (length of longest path(s) from input to output).
[Answer]
# 19 NANDs
There is no simpler circuit than this.
There is code for testing it below the picture.
As for understanding it, that's difficult.
There are a couple of IF gates there, and the inputs are kinda grouped into a triangle with the free corner lines added for analysis one by one, but not in a simple way. If anyone manages to understand it, I will be impressed.
[](https://i.stack.imgur.com/V4fuT.jpg)
Verilog code with testing:
```
// 4-vertex Connectedness Tester
// Minimal at 19 NANDs
//
// By Kim Øyhus 2018 (c) into (CC BY-SA 3.0)
// This work is licensed under the Creative Commons Attribution 3.0
// Unported License. To view a copy of this license, visit
// https://creativecommons.org/licenses/by-sa/3.0/
//
// This is my entry to win this Programming Puzzle & Code Golf
// at Stack Exchange:
// https://codegolf.stackexchange.com/questions/69912/build-a-4-vertex-connectedness-tester-using-nand-gates/
//
// I am sure there are no simpler solutions to this problem.
// It has a logical depth of 11, which is deeper than
// circuits using a few more NANDs.
module counting6 ( in_000, in_001, in_002, in_003, in_004, in_005, in_006, out000 );
input in_000, in_001, in_002, in_003, in_004, in_005, in_006;
output out000;
wire wir000, wir001, wir002, wir003, wir004, wir005, wir006, wir007, wir008, wir009, wir010, wir011, wir012, wir013, wir014, wir015, wir016, wir017;
nand gate000 ( wir000, in_000, in_000 );
nand gate001 ( wir001, in_001, in_003 );
nand gate002 ( wir002, wir001, wir000 );
nand gate003 ( wir003, in_002, wir002 );
nand gate004 ( wir004, wir002, wir002 );
nand gate005 ( wir005, wir004, in_002 );
nand gate006 ( wir006, wir005, wir004 );
nand gate007 ( wir007, in_005, wir006 );
nand gate008 ( wir008, in_003, wir006 );
nand gate009 ( wir009, in_004, wir003 );
nand gate010 ( wir010, wir003, wir009 );
nand gate011 ( wir011, wir009, wir000 );
nand gate012 ( wir012, wir011, in_001 );
nand gate013 ( wir013, wir008, wir012 );
nand gate014 ( wir014, wir013, in_005 );
nand gate015 ( wir015, wir006, wir013 );
nand gate016 ( wir016, wir015, wir007 );
nand gate017 ( wir017, wir016, wir010 );
nand gate018 ( out000, wir014, wir017 );
endmodule
module connecting6_test;
reg [5:0] X;
wire a;
counting6 U1 (
.in_000 (X[0]),
.in_001 (X[1]),
.in_002 (X[2]),
.in_003 (X[3]),
.in_004 (X[4]),
.in_005 (X[5]),
.in_006 (X[6]),
.out000 (a )
);
initial begin
X = 0;
end
always
#10 X = X+1;
initial begin
$display("\t\t \t_");
$display("\t\ttime,\t \\db/_,\tconnected");
$monitor("%d,\t%b,\t%d",$time, X, a );
end
initial
#630 $finish;
endmodule
// iverilog -o hello hello.v
// vvp hello
```
Kim Øyhus
[Answer]
# 30 NANDS
Instead of asking when do we get a 1, I asked the question when do we get a 0. It's better to ask it this way round because there are less 0's than 1's.
Here's the distribution according to number of edges (6th row of pascal's triangle)
```
Edges 0 1 2 3 4 5 6
Frequency 1 6 15 20 15 6 1 (total 64)
Output 0 0 0 * 1 1 1
* = 0 if triangle (4 possibilities) 1 if claw (4 possibilities)
1 if two opposite edges and one other (12 possibilities)
```
Asking the question this way round, we get the following diagram and expression
```
___D___
|\ /|
| E F |
| \ / |
A X C
| / \ |
| / \ |
|/__B__\|
(A|C|D|B)&(A|D|E)&(D|B|E|F)&(C|B|E)&(A|C|E|F)&(D|F|C)&(A|F|B)
```
We assume the output will default to 1, but will change to 0 under any of the following conditions
1.A 0 for three adjacent edges (test 3 inputs)
2.A 0 for two opposing pairs of edges (test 4 inputs)
The terms above are already ordered in the manner that will enable them to be grouped as below. (Incidentally, this version of the expression is rotationally symmetrical abouth the AFB vertex.)
```
((A|D)|((C|B)&E))&((B|E)|((D|F)&C))&((C|F)|((A|E)&D))&(A|F|B) =6 inverters
1 1 1 1 1 1 1 1 1 1 =10 (7 OR with both inputs inverted, 3 NAND)
2 2 2 2 =8 (4 OR with one input inverted)
2 2 2 =6 (3 AND)
Total =30
```
The score for each `&` or `|` is placed below the symbol and justified as follows:
Level 0: We invest in an inverter for each input: 6 NANDS
Level 1: We can build an OR from a NAND gate by putting an inverter at the input (total 3 NANDS) but as we already invested in 6 NANDS in the previous step we can make 7 OR gates from 7 NAND gates. We also need 3 AND gates. For these, we will just use NANDs and leave the output inverted. 10 NANDS
Level 2: Again we build 4 OR gates from NAND gates. In each case we have 1 input from an OR gate, so we have to invert that. But the other input is already inverted (coming from one of the NANDs in the previous step that corresponds to a `&` symbol in three cases, and from an inverter in the last one) so we only need 2 gates for each OR functionality. 4 \* 2 =8
Level 3: We now need to AND the four outputs together. This requires 3 AND gates, each built from 2 NANDs, 3 \* 2 = 6
That's a total of 30 NAND gates, with a max depth of 2+2+4=8 NANDs for branches with an `|` at level 1 or 3+1+4=8 NANDs for branches with an `&` at level 1.
The following Ruby script confirms visually that the above expression is valid.
```
64.times{|i|
a=i%2
b=i/2%2
c=i/4%2
d=i/8%2
e=i/16%2
f=i/32%2
puts i, ((a|d)|((c|b)&e))&((b|e)|((d|f)&c))&((c|f)|((a|e)&d))&(a|f|b)
puts " ___#{d}___
|\\ /|
| #{e} #{f} |
| \\ / |
#{a} X #{c}
| / \\ |
| / \\ |
|/__#{b}__\\|
"
}
```
[Answer]
# Mathematica, 17 gates
We simply enumerate all of the rules, construct the boolean function, and minimize it in `NAND` form.
```
#->If[Total@#<3||
MemberQ[{{1,1,1,0,0,0},{1,0,0,1,1,0},{0,1,0,1,0,1},{0,0,1,0,1,1}},#]
,0,1] /.{1->True,0->False}& /@
Tuples[{0,1},6];
BooleanMinimize[BooleanFunction[rule], "NAND"]
```
---
**Result**:
```
(#1⊼#2⊼#4)⊼(#1⊼#2⊼#5)⊼(#1⊼#2⊼#6)⊼(#1⊼#3⊼#4)⊼ \
(#1⊼#3⊼#5)⊼(#1⊼#3⊼#6)⊼(#1⊼#4⊼#6)⊼(#1⊼#5⊼#6)⊼ \
(#2⊼#3⊼#4)⊼(#2⊼#3⊼#5)⊼(#2⊼#3⊼#6)⊼(#2⊼#4⊼#5)⊼ \
(#2⊼#5⊼#6)⊼(#3⊼#4⊼#5)⊼(#3⊼#4⊼#6)⊼(#4⊼#5⊼#6)&
```
, where `#1...#6` are 6 slots for arguments.
---
**Test cases**:
```
f=%; (* assign the function to symbol f *)
f[True, True, True, True, False, False]
(* True *)
f[True, True, False, True, False, False]
(* True *) (*, three Trues do not form a triangle *)
f[True, True, True, False, False, False]
(* False *) (*, three Trues form a triangle *)
```
[Answer]
# 64 NANDs
The six edges can be split up into three pairs of opposite edges. For a graph to be connected, there must either be two opposite edges as well as a third edge, or three edges connected to the same vertex.
```
•
U
Z • Y
V W
• X •
```
The opposite pairs are UX, VY, WZ, so:
```
A = U+V ;3 gates
B = W+X
C = Y+Z
D = UV(B+C) ;2+2+3=7 gates
E = WX(A+C)
F = YZ(C+A)
Result = D+E+F+UVW+UYZ+XVZ+XWY ; 18 + 16 = 34 gates
```
Building AND and OR gates in the usual way, the total number of gates used is `3*3+7*3+34` = 64.
] |
[Question]
[
We all love horoscopes, *don't we*? But I have a serious problem in this *Horoscope App* installed on my *Smart Phone* that it only displays the icon of the Zodiac Sign for each day's horoscope. Now, I do remember my horoscope, but its hard to remember others' whose horoscope I am interested in.
# Challenge
So here is your challenge for an another addition to the ASCII Art of the Day series. Given a date and month input, output the corresponding Zodiac sign in ASCII format as shown below. Each Zodiac Sign is followed after the name and date range (`DD MM` format) for the zodiac sign.
```
Aries - 21 03 - 20 04
.-. .-.
(_ \ / _)
|
|
Taurus - 21 04 - 20 05
. .
'.___.'
.' '.
: :
: :
'.___.'
Gemini - 21 05 - 20 06
._____.
| |
| |
_|_|_
' '
Cancer - 21 06 - 20 07
.--.
/ _'.
(_) ( )
'. /
'--'
Leo - 21 07 - 20 08
.--.
( )
(_) /
(_.
Virgo - 21 08 - 20 09
_
' ':--.--.
| | |_
| | | )
| | |/
(J
Libra - 21 09 - 20 10
__
___.' '.___
____________
Scorpio - 21 10 - 20 11
_
' ':--.--.
| | |
| | |
| | | ...
'---':
Sagittarius - 21 11 - 20 12
...
.':
.'
'..'
.''.
Capricorn - 21 12 - 20 01
_
\ /_)
\ /'.
\ / :
\/ __.'
Aquarius - 21 01 - 20 02
.-"-._.-"-._.-
.-"-._.-"-._.-
Pisces - 21 02 - 20 03
'-. .-'
: :
--:--:--
: :
.-' '-.
```
# Input
* You would be provided two integers corresponding to the date of month and
month of year (in that order) of the birthday.
* The date and month will be `1` indexed like in normal calendars.
* You can take input form STDIN/ARGV/function arguments or the closest equivalent
# Output
* Based on what date range the input date falls in, output to STDOUT, the corresponding Zodiac Sign.
* You can have upto 4 trailing spaces in each line but no leading spaces that are not part of the output.
* You can either write a full program or a named function.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins!
---
# Leaderboard
**[The first post of the series generates a leaderboard.](https://codegolf.stackexchange.com/q/50484/31414)**
To make sure that your answers show up, please start every answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
[Answer]
# CJam, ~~296~~ ~~284~~ ~~272~~ ~~265~~ 264 bytes
```
"03½åÙªWË#å¥ÜZ2ò'ýðDc}¦Ð£RÞ5ä<Üå§ÖÞYÏuäOe¤¶è2²|ZëßB«ô¬cm"257b2bSf*Qa/"®=&ðS¢Òpût£Ð`ç«^º,[öÄ©3¸YÝæ[%$>\D£(´õÓÆeUØRHáÄ¡ããîùK½ÊÆÇ:UBÍm¥·fèäBÓEwWOkQq×tÌVfè£g8·¨ q©ñäp-ÁgUÚ´Éõ'>r Ê#"256bDb"
.\"'()-/:\_|J"f=.+sSN+/l~\K>+=
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%220%C2%913%C2%BD%C3%A5%C3%99%C2%AA%1AW%C3%8B%23%C3%A5%C2%A5%C3%9CZ2%C3%B2'%C3%BD%C3%B0D%C2%95c%7D%C2%A6%1E%C3%90%C2%8E%C2%A3R%C3%9E5%C2%88%C3%A4%3C%C3%9C%C3%A5%C2%A7%0F%10%C3%96%C3%9E%C2%98Y%C3%8F%01%7Fu%C3%A4Oe%C2%A4%C2%B6%C3%A82%7F%C2%B2%7CZ%C3%AB%C3%9FB%C2%AB%C3%B4%C2%ACc%C2%9Bm%22257b2bSf*Qa%2F%22%01%C2%AE%3D%26%C2%84%10%C3%B0S%C2%A2%C3%92p%C3%BBt%C2%A3%C3%90%60%C3%A7%C2%AB%5E%C2%BA%2C%5B%C3%B6%16%C3%84%C2%A9%C2%86%0E3%C2%B8Y%C3%9D%C3%A6%5B%10%25%24%3E%5CD%C2%A3(%C2%B4%C3%B5%C3%93%C3%86eU%C3%98RH%C3%A1%C3%84%C2%A1%C3%A3%C2%82%C2%9A%C2%9A%C2%9B%1B%C3%A3%C3%AE%05%C3%B9K%C2%BD%C3%8A%C3%86%C3%87%3AUB%06%C3%8Dm%C2%A5%14%C2%B7f%C2%99%C3%A8%03%C3%A4%1CB%C3%93EwWOkQq%C2%9E%C3%97%C2%87t%C2%8F%C3%8CVf%0F%C3%A8%C2%A3%C2%9Ag8%C2%91%C2%94%C2%B7%C2%A8%09%C2%9Cq%C2%84%C2%A9%10%1C%C3%B1%11%C3%A4p-%C3%81gU%C3%9A%18%C2%80%C2%B4%C3%89%04%C3%B5'%04%06%3Er%09%C3%8A%23%1C%22256bDb%22%0A.%5C%22'()-%2F%3A%5C_%7CJ%22f%3D.%2BsSN%2B%2Fl~%5CK%3E%2B%3D&input=21%2011).
### Idea
We start by joining all twelve signs using the string `<SP><LF>` as separator. We opt for the zodiac signs not to contain trailing spaces, so this allows to separate them easily.
The joined string is 542 bytes long. 236 of these bytes are spaces, which is almost half of them. We build an array that contains a 1 for every space and a 0 for every non-space. This way, encoding a space will only cost 1 bit.
Removing all spaces from the joined string, we are left with the characters `<LF>."'()-/:J\_|`. Assigning each of them a value (e.g., the index in this string) between 0 and 12
Finally, we decode the above base 2 and base 13 arrays as byte arrays.
In the final program, for a given input `DD MM`, we compute `(int(MM) + (int(DD) > 20)) % 12`, reverse the above process to obtain the array of all zodiac signs and select the proper one.
### Code
```
"03½åÙªWË#å¥ÜZ2ò'ýðDc}¦Ð£RÞ5ä<Üå§ÖÞYÏuäOe¤¶è2²|ZëßB«ô¬cm"
e# Push the encoded space positions.
257b2b e# Convert from base 257 to base 2.
Sf* e# Replace 1's with spaces and 0's with empty strings.
Qa/ e# Split at empty strings.
"®=&ðS¢Òpût£Ð`ç«^º,[öÄ©3¸YÝæ[%$>\D£(´õÓÆeUØRHáÄ¡ããîùK½ÊÆÇ:UBÍm¥·fèäBÓEwWOkQq×tÌVfè£g8·¨ q©ñäp-ÁgUÚ´Éõ'>r Ê#"
e# Push the encoded non-space characters.
256bDb e# Convert from base 256 to base 13.
"
.\"'()-/:\_|J"f=
e# Replace each digit in base 13 by the corresponding character.
.+s e# Interleave both arrays to create a string.
SN+/ e# Split at trailing spaces.
l~ e# Evaluate the input from STDIN.
\K>+ e# Add 1 to the month if the day is larger than 20.
= e# Retrieve the corresponding element from the array.
```
[Answer]
# CJam, 324 bytes
```
"%[hÿìs5!zaÆT=ªñ=Û]ÌUMàûÓ»¦f¼³ëµ1þÈUÑyéC4¬u1T9KÍü!+Úøöà&J~âZ®uRtkRÿ+*ÐFeÜPý¤SÙËU7óÎ?LXÝ2D@0¶ÆÀ¡kÚçaçªñܧ#iµ3L®ó&Ë'iºyè½?JS÷SjS`ösÓò»zjRoaÃIYrµ&M>ÍKaaúcg®Ð\p¨²:LqÜݶo¯ÆkµúÒ4Ezú©æ¼xP»¸¯gd^ßg±>ï úDÎŧ@3Bßt\<GÒcû)ËûwíUÑdØoiTv>¤&ý°mÊ13ÛUÿØjª¬Ì±(¦¿çÍX4tõãÜÑ*ÃmÜ9ãSÁ3IþÜìÙ,"{_'~>33*32+-}%191bEb428Et"
\"'()-./:\_a|J"f='a/q~\K>+=
```
My first attempt. [Try it online](http://cjam.aditsu.net/#code=%22%25%5Bh%C3%BF%C3%ACs5!za%C3%86T%3D%C2%AA%C3%B1%3D%C3%9B%5D%C3%8CUM%C3%A0%C3%BB%C3%93%C2%BB%C2%A6f%C2%BC%C2%B3%C3%AB%C2%B51%C3%BE%C3%88U%C3%91y%C3%A9C4%C2%ACu1T9K%C3%8D%C3%BC!%2B%C3%9A%C3%B8%C3%B6%C3%A0%26J~%C3%A2Z%C2%AEuRtkR%C3%BF%2B*%C3%90Fe%C3%9CP%C3%BD%C2%A4S%C3%99%C3%8BU7%C3%B3%C3%8E%3FLX%C3%9D2D%400%C2%B6%C3%86%C3%80%C2%A1k%C3%9A%C3%A7a%C2%AD%C3%A7%C2%AA%C3%B1%C3%9C%C2%A7%23i%C2%B53L%C2%AE%C3%B3%26%C3%8B'i%C2%BAy%C3%A8%C2%BD%3FJS%C3%B7SjS%60%C3%B6s%C3%93%C3%B2%C2%BBzjRoa%C3%83IYr%C2%B5%26M%3E%C3%8DKaa%C3%BAcg%C2%AE%C3%90%5Cp%C2%A8%C2%B2%3ALq%C3%9C%C3%9D%C2%B6o%C2%AF%C3%86k%C2%B5%C3%BA%C3%924Ez%C3%BA%C2%A9%C3%A6%C2%BCxP%C2%BB%C2%B8%C2%AFgd%5E%C3%9Fg%C2%B1%3E%C3%AF%C2%A0%C3%83%C2%BAD%C3%8E%C3%85%C2%A7%403B%C3%9Ft%5C%3CG%C3%92c%C3%BB)%C3%8B%C3%BBw%C3%ADU%C3%91d%C3%98oiTv%3E%C2%A4%26%C3%BD%C2%B0m%C3%8A13%C3%9BU%C3%BF%C3%98j%C2%AA%C2%AC%C3%8C%C2%B1(%C2%A6%C2%BF%C3%A7%C3%8DX4t%C3%B5%C3%A3%C3%9C%C3%91*%C3%83m%C3%9C9%C3%A3S%C3%813I%C3%BE%C3%9C%C3%AC%C3%99%2C%22%7B_'~%3E33*32%2B-%7D%25191bEb428Et%22%0A%20%5C%22'()-.%2F%3A%5C_a%7CJ%22f%3D'a%2Fq~%5CK%3E%2B%3D&input=2%206)
[Answer]
# Python 2, ~~961~~ ~~698~~ ~~692~~ 687 Bytes
Definitely still going to golf further, just wanted to put an idea down. Now using a dictionary.
```
a,b=raw_input().split()
b=int(b)
c='.-"-._.-"-._.-'
print{0:c+'\n'+c,1:"'-. .-'\n : :\n --:--:--\n : :\n.-' '-.",2:" .-. .-.\n(_ \ / _)\n |\n |",3:" . .\n '.___.'\n .' '.\n: :\n: :\n '.___.'",4:"._____.\n | |\n | |\n _|_|_\n' '",5:" .--.\n / _'.\n (_) ( )\n'. /\n '--'",6:" .--.\n ( )\n(_) /\n (_.",7:" _\n' ':--.--.\n | | |_\n | | | )\n | | |/\n (J",8:" __\n___.' '.___\n"+'_'*12,9:" _\n' ':--.--.\n | | |\n | | |\n | | | ...\n '---':",10:" ...\n .':\n .'\n'..'\n.''.",11:" _\n\ /_)\n \ /'.\n \ / :\n \/ __.'"}[[[b-2,11][b<2],b-1][int(a)>20]]
```
Old method, using interleaving.
```
d,m=raw_input().split()
m=int(m)
print'.\' . --.._ _ _ ".- _ .\n \n - . _.-\' \' . _-- _ _-.\'_\' . ..\n:_:. -...\n\n -\n-. "--\n (-_-._-\'. ._.\n\n.\n\n\'|/ -_- \\_ (. -.- . __| .\'. - _\n )\n \n \n: _ _\n . \\. \'( \' - \'|._ . . ":/\n \n)|_|\'/-\n | _ :_. .\n( _ \n)_-_\' _/|\n| \n.-) _)\n _ -:\n | _ \\"- _( |_| -- \'| __\n. .: ._) \n_ \' _- \n\n\n( _ \n .- :\'\'_ _ \'/-\n| .. _|.\' \n |_ .. _ \'\n _|\n : |_ . \'/ \'\\ \n |\' :|: | \n. \n \n / . : \' ) - - \n \' - | \' : \n | | \' - : | | \\ . \n / \' | . _ . / . _ _ \n . . _ \n \' _ . \' ( J \' - - - \' : '[[m-2,m-1][int(d)>21]::12].rstrip()
```
[Answer]
# Python 2, ~~565~~ ~~568~~ 553 bytes
```
def z(d,m):b="\n "+" |"*3;c=" _\n' ':--.--.";a=" ...\n ";print["\ /_)\n \ /'.\n \ / :\n \/ __.'",'.-"-._.-"-._.-\n'*2,"'-. .-'\n : :\n --:--:--\n : :\n.-' '-.",' .-. .-.\n(_ \ / _)'+'\n |'*2," . .\n '.___.'\n .' '.\n: :\n: :\n '.___.'","._____.\n | |\n | |\n _|_|_\n' '"," .--.\n / _'.\n (_) ( )\n'. /\n '--'",' .--.\n ( )\n(_) /\n (_.',c+b+"_"+b+" )"+b+"/\n (J"," __\n___.' '.___\n"+"_"*12,c+b*3+a+" '---':"," "+a+".':\n .'\n'..'\n.''."][m%12-(d<21)]
```
So I was a bit lazy and decided not to golf this AAotD.
Instead, I decided to let python golf itself.
The above solution was created using the code below:
```
full_string = """
\ /_)
\ /'.
\ / :
\/ __.'
*
.-"-._.-"-._.-
.-"-._.-"-._.-
*
... # The others in this list as well
*
...
.':
.'
'..'
.''.
"""
# Golf the input string
string_list = full_string.split('*')
# Remove begin and end \n
string_list = [s[1:-1] for s in string_list]
# Remove unnescessary repr characters
golf = repr(string_list).replace(r'\\ ', r'\ ').replace(r'\\/', r'\/').replace(', ', ',')
# Special case for the Aquarius as it's a full duplicate
middle = golf.find('\\n', 50)
end = golf.find(',', middle)
golf = golf[0:middle+2] + "'*2" + golf[end:]
# Special case for the 12 underscores
golf = golf.replace('____________"', '"+"_"*12')
# Replace the three bars and their whitespace
golf = golf.replace('\\n | | |', '"+b+"')
# Replace the bar-cover
cover = '" _\\n\' \':--.--."'
golf = golf.replace(cover, 'c')
# Replaces aries' foot
golf = golf.replace("\\n |\\n |'", "'+'\\n |'*2")
# Replace dots
golf = golf.replace(' ...\\n ', '"+a+"')
# Remove empty strings and optimize b's
golf = golf.replace('""+', '').replace('b+b+b', 'b*3')
# Surround the lookup table with the function that that prints the correct zodiac sign for the day/month
golf = 'def z(d,m):a=" ...\\n ";b="\\n "+" |"*3;c=" _\\n\' \':--.--.";print' + golf + '[m%12-(d<21)]'
```
[Answer]
# Perl, 414
Not a lot to do here, just applied dictionary compression:
```
#!perl -p
/ /;$i=$'%12-($`<21);
$_="cc_
\\ct_s \\c/'ga\\thlh\\/ __ijkee
keej'-.ck'n q:q:qnk'c'-gA k.hkg(_a\\ /a_sm|
m|j .mg oi
ih'g:chl:chl oij.d__grr _|_|_
'm'jhk-gth_'g (_) ( s'.c/
a'q'jak-g (cs(_)t
c(_.f_b )b/
cc(Jjm__
diao
ddddfbbpm'q-':jcpailci
'.i
i'g";
1while s![a-t]!(split z," z
a |a|a|zaaz___z\"-._.-z
A _
' ':--.--.bz.
za z.'z
Az.-z:
zc z
h:alz'.dza..gcz--za| |
z)
za/")[(ord$&)%97]!e;$_=(split A)[$i]
```
Test [me](http://ideone.com/s7lxk0).
] |
[Question]
[
Before reading this I suggest reading this little puzzle: <https://puzzling.stackexchange.com/questions/11408/longest-word-with-adjacent-letters-on-a-keyboard>
I want you to make a program that takes one argument, a word (only lowercase letters), and outputs "Yes" if the word can be typed with adjacent keys on the keyboard (see the article) and "No" if the word can't be typed with adjacent letters.
Here's the keyboard layout used in this challenge:
```
┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | W | E | R | T | Y | U | I | O | P |
└─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┘
| A | S | D | F | G | H | J | K | L |
└─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴───┘
| Z | X | C | V | B | N | M |
└───┴───┴───┴───┴───┴───┴───┘
```
Remember: this is codegolf so the the shortest answer wins!
[Answer]
# Pyth, 66
```
?"Yes".Am>2sm^-.uk2Cm.Dx"qwertyuiopasdfghjkl*zxcvbnm"b9.5dC,ztz"No
```
[Try it here.](https://pyth.herokuapp.com/?code=%3F%22Yes%22.Am%3E2sm%5E-.uk2Cm.Dx%22qwertyuiopasdfghjkl*zxcvbnm%22b9.5dC%2Cztz%22No&input=qaswedcvbhuikmnhytgbgtghy&debug=0)
I was surprised to learn Pyth doesn't have a hypotenuse function, so this will likely be beat by a different language. I'll propose a hypotenuse function to Pyth, so this atrocity won't happen in the future.
### Explanation
I transform the keyboard into this:
```
┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | W | E | R | T | Y | U | I | O | P |
└─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┐
| A | S | D | F | G | H | J | K | L | * |
└─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴───┴───┘
| Z | X | C | V | B | N | M |
└───┴───┴───┴───┴───┴───┴───┘
```
Which I then encode as `"qwertyuiopasdfghjkl*zxcvbnm"`. **Then I used divmod with modulo 9.5 to figure out the 2D coordinates of every key.** Then I compute distances between consecutive keys, and check if the squared distance < 2.
[Answer]
# CJam, ~~83~~ ~~75~~ 74 bytes
```
l_1>]z["qwertyuiop asdfghjkl zxcvbnm "[__B>]z+s_W%+_]zsf{\#)}:*"Yes""No"?
```
[Try it online.](http://cjam.aditsu.net/#code=l_1%3E%5Dz%5B%22qwertyuiop%20asdfghjkl%20%20zxcvbnm%20%22%5B__B%3E%5Dz%2Bs_W%25%2B_%5Dzsf%7B%5C%23)%7D%3A*%22Yes%22%22No%22%3F&input=redressed)
### Explanation
The general approach is to produce a big adjacency string containing every pair of adjacent keyboard characters and then check that every pair of adjacent input characters is contained in that string.
I'm quite happy with how I managed to build the adjacency string, which uses very simple and compact logic.
```
l_1>]z "Read a line of input and create a list of every pair of
adjacent input characters. There will be a trailing element
of just the final character, but that's okay since any single
lowercase letter can be found in the adjacency string.";
["qwertyuiop asdfghjkl zxcvbnm "
"^ Create the in-row forward adjacency string.";
[__B>]z "Create the alternating-row forward adjacency string by
interleaving the in-row string with a substring of itself
starting with the middle row letters:
'q w e r t y u i o p a s d f g h j k l zxcvbnm '
+ ' a s d f g h j k l z x c v b n m '[no interleave here]
-----------------------------------------------------
'qawsedrftgyhujikolp azsxdcfvgbhnjmk l zxcvbnm '";
+s "Append the alternating-row forward adjacency string to the
in-row forward adjacency string.";
_W%+ "Append the reverse of the forward adjacency string (the
backward adjacency string) to the forward adjacency string.";
_]zs "Double every character in the adjacency string so every
character is adjacent to itself.";
f{\#)} "Map each pair of input characters to its 1-indexed location in
the adjacency string (0 if not found).";
:* "Calculate the product of each pair's location in the adjacency
string. This will be nonzero if and only if every pair of
input characters are in fact adjacent.";
"Yes""No"? "If the product is nonzero, produce 'Yes'; otherwise, produce
'No'.";
"Implicitly print the result.";
```
[Answer]
# J, 77 bytes
```
No`Yes{::~[:*/2>+/"1@(2|@-/\3(|,.<.@%~+-:@|)'qazwsxedcrfvtgbyhnujmikXolX'i.])
```
Usage:
```
f=.No`Yes{::~[:*/2>+/"1@(2|@-/\3(|,.<.@%~+-:@|)'qazwsxedcrfvtgbyhnujmikXolX'i.])
f 'redresser'
Yes
f 'qwergy'
No
f 'ppcg'
No
```
Method:
For every input letter I generate it's 2D coordinate (similar to the image in the question) based on it's index in the string `'qazwsxedcrfvtgbyhnujmikXolX'`. For every pair of letters in the input I check if their coordinates' Manhattan-distance is smaller than 2. If all are, I output `Yes`, `No` otherwise (by abusing the ` operator).
[Try it online here.](http://tryj.tk/)
[Answer]
# CJam, 75
```
r(1$+]z[1AB]"qwertyuiop asdfghjkl zxcvbnm"f/:zSff+s_W%+f{\_|#}W&"No""Yes"?
```
[Try it here](http://cjam.aditsu.net/#code=r%281%24%2B%5Dz%5B1AB%5D%22qwertyuiop%20asdfghjkl%20%20zxcvbnm%22f%2F%3AzSff%2Bs_W%25%2Bf%7B%5C_%7C%23%7DW%26%22No%22%22Yes%22%3F&input=redresser) ([Firefox here](http://cjam.aditsu.net/#code=r%281%24%2B%5Dz%5B1AB%5D%22qwertyuiop%20asdfghjkl%20%20zxcvbnm%22f%2F%3AzSff%2Bs_W%2525%2Bf%7B%5C_%7C%23%7DW%26%22No%22%22Yes%22%3F&input=redresser)).
Overlooked the Yes/No part... Fixed.
] |
[Question]
[
# Background
You have just learned what [combinatory logic](https://en.wikipedia.org/wiki/Combinatory_logic) is. Intrigued by the various combinators you spend quite a bit of time learning about them. You finally stumble upon this particular expression:
```
(S I I (S I I))
```
You notice that when trying to reduce it to its normal form, it reduces to itself after three steps:
```
(S I I (S I I))
= (I (S I I) (I (S I I))) (1)
= (S I I (I (S I I))) (2)
= (S I I (S I I)) (3)
```
You are determined to find other expressions which share this trait and begin to work on this immediately.
# Rules
* You may use any combination of the following combinators:
```
B f g x = f (g x)
C f x y = f y x
I x = x
K x y = x
S f g x = f x (g x)
W f x = f x x
```
* Application is left associative, which means that `(S K K)` is actually `((S K) K)`.
* A reduction is **minimal** there is no other order of reduction steps which uses fewer steps. Example: if `x` has reduction `y`, then the correct minimal reduction of `(W f x)` is:
```
(W f x)
= (W f y) (1)
= f y y (2)
```
and not
```
(W f x)
= f x x (1)
= f y x (2)
= f y y (3)
```
* Standard loopholes apply.
# Task
We define the **cycle** of an expression to be the minimal number of reductions in between two same expressions.
Your task is to find the expression, with the number of combinators used < 100, which produces the longest cycle.
# Scoring
Your score will be determined by the length of the cycle of your expression. If two people's expression have the same cycle, the answer which uses fewer combinators wins. If they both use the same number of combinators, the earlier answer wins.
Good luck and have fun!
[Answer]
# Cycle: \$f\_{\omega^{\omega^{\omega^{\omega^\omega}}}}(65536)\$, combinators: 98
```
W (B (S I)) (W (B (S I))) (C (C (S (C I W) (C (C (C I K))))) (C (C (C (C (C (C (S (B (S (B (S (B (S (B (S (B (B (B (B (B (B (B W)))))) (B (B (B (B (B C)))))) (B (B (B (B (B W)))))) (B (B (B (B C))))) (B (B (B (B W))))) (B (B (B C)))) (B (B (B W)))) (B (B C))) (B (B W))) (B C)) (B W))) (C I))) (S B))) (C (C (C (C (W B) (W B)) (W B))) (W B))))
```
This expression is similar to `Y I`, that has this reduction:
```
0: Y I
1: I (Y I)
2: Y I
```
After the first reduction there were two possible reductions: `I (Y I) -> Y I` and `I (Y I) -> I (I (Y I))`. This is not a problem since the second will clearly take longer to finish.
We will replace the `I` with `j`, `j` does the same thing `I` does, but it needs `n` reductions. `n` is an arbitrarily large [Church numeral](https://en.wikipedia.org/wiki/Church_encoding) that cannot be reduced without an argument.
```
j = C (C (S (C I W) (C (C (C I K))))) n
y = Y j <- This is just to make it easier to read later.
```
To make sure that there is no reduction of `y` that takes less than `n` steps, most of the time there will be only one possible reduction.
Imagine we have an expression `a b` that can be reduced to `c`, we can change it to `C (C a) b`. This new expression cannot be reduced, but if we give it another argument it can:
```
C (C a) b d
C a d b
a b d
c d
```
This way we can lock an expression to be reduced later. This can be seen in `j`, it can only be reduced with an argument.
In these first reductions only the leftmost combinator can be reduced.
```
0: Y (C (C (S (C I W) (C (C (C I K))))) n)
1: C (C (S (C I W) (C (C (C I K))))) n y <- From now on y can always be reduced,
2: C (S (C I W) (C (C (C I K)))) y n but as we have seen before this makes
3: S (C I W) (C (C (C I K))) n y the cycle longer, so we can imagine
4: C I W n (C (C (C I K)) n) y it cannot be reduced.
5: I n W (C (C (C I K)) n) y
6: n W (C (C (C I K)) n) y
```
Now n received an argument, it can be reduced and it is the only possible reduction.
For now let's reduce `n` completely before reducing anything else.
```
?: W (W (W (...(W (W (C (C (C I K)) n) ))...))) y
^ ^ ^ ^^^ ^ ^ there are n 'W's here
```
`C (C (C I K)) n` needs an argument and each `W` needs two, so the first `W` is the only reduction allowed.
```
?: W (W (W (...(W (W (C (C (C I K)) n)))...))) y
?: W (W (...(W (W (C (C (C I K)) n)))...)) y y
?: W (...(W (W (C (C (C I K)) n)))...) y y y
?: ...(W (W (C (C (C I K)) n)))... y y y y
...
?: W (W (C (C (C I K)) n)) y ... y y y
?: W (C (C (C I K)) n) y y ... y y y
?: C (C (C I K)) n y y y ... y y y <- Let's call this line L
^ ^ ^^^ ^ ^ ^ there are n 'y's after the first 'y'
```
Now `C (C (C I K)) n` has an argument, the only way this can happen is if `n` has been fully reduced and there are no `W`s left. Here we assume `n` has not been designed to avoid line `L`, when defining `n` later I will show how this can be done.
After reduction 6 we reduced `n` completely, this was not necessary, the only other thing we could reduce besides `n` was the `W`s. It doesn't matter what order we reduce it, it will always eventually reach line `L`. When `n` is reduced it makes `n` copies of `W`, this can be done in many ways and maybe even in less than `n` reductions, but the `W`s make `n` copies of `y` one by one, this takes `n` reductions independently of when it happens or if the `W`s were copied efficiently. From line 6 to line `L` the reductions can be made in many possible orders, but it will take at least `n` reductions to make all the copies of `y`.
Continuing from line `L`:
```
>n : C (C (C I K)) n y y y ... y y y
>n+1: C (C I K) y n y y ... y y y
>n+2: C I K n y y y ... y y y
>n+3: I n K y y y ... y y y
>n+4: n K y y y ... y y y
```
The only thing we can do now is reduce the `n` and the `K`s. For the same reason as before this also takes at least `n` reductions.
Each one of the `n` `K`s deletes one of the `(n+1)` `y`s, resulting in just one `y`. Reducing `n` completely before reducing the `K`s would look like this:
```
>n+5: K (K (K (...(K (K y))...))) y y y ... y y
>n+6: K (K (...(K (K y))...)) y y ... y y
>n+7: K (...(K (K y))...) y ... y y
...
>2n-2: K (K y) y y
>2n-1: K y y
>2n : y
```
Here is one complete example of this with `n = 3 = S B (W B)`, which should take more than 6 reductions:
`^` represents the possible reductions and `(^)` represents the reduction that will be done. If there is more than one option, one of them will be chosen at random.
```
0: Y (C (C (S (C I W) (C (C (C I K))))) (S B (W B)))
(^)
1: C (C (S (C I W) (C (C (C I K))))) (S B (W B)) y
(^)
2: C (S (C I W) (C (C (C I K)))) y (S B (W B))
(^)
3: S (C I W) (C (C (C I K))) (S B (W B)) y
(^)
4: C I W (S B (W B)) (C (C (C I K)) (S B (W B))) y
(^)
5: I (S B (W B)) W (C (C (C I K)) (S B (W B))) y
(^)
6: S B (W B) W (C (C (C I K)) (S B (W B))) y <- beginning of the reduction of n
(^)
7: B W (W B W) (C (C (C I K)) (S B (W B))) y
^ (^)
8: B W (B W W) (C (C (C I K)) (S B (W B))) y
(^)
9: W (B W W (C (C (C I K)) (S B (W B)))) y
(^) ^
10: B W W (C (C (C I K)) (S B (W B))) y y <- 1st copy of y
(^)
11: W (W (C (C (C I K)) (S B (W B)))) y y <- end of the reduction of n
(^)
12: W (C (C (C I K)) (S B (W B))) y y y <- 2nd copy of y
(^)
13: C (C (C I K)) (S B (W B)) y y y y <- 3rd copy of y
(^)
14: C (C I K) y (S B (W B)) y y y
(^)
15: C I K (S B (W B)) y y y y
(^)
16: I (S B (W B)) K y y y y
(^)
17: S B (W B) K y y y y <- beginning of the second reduction of n
(^)
18: B K (W B K) y y y y
(^) ^
19: K (W B K y) y y y
^ (^)
20: K (B K K y) y y y
(^) ^
21: B K K y y y <- 1st y deleted
(^)
22: K (K y) y y <- end of the second reduction of n
(^)
23: K y y <- 2nd y deleted
(^)
24: y <- 3rd y deleted
```
We can see that indeed it took more than 6 reductions.
`Y` is not allowed in this challenge, but we can replace it with `W (B (S I)) (W (B (S I)))`:
```
0: W (B (S I)) (W (B (S I))) j
1: B (S I) (W (B (S I))) (W (B (S I))) j
2: S I (W (B (S I)) (W (B (S I)))) j <- Here we don't reduce the W for the
3: I j (W (B (S I)) (W (B (S I))) j) same reason we don't reduce Y twice
4: j (W (B (S I)) (W (B (S I))) j) before the end of the cycle.
5: W (B (S I)) (W (B (S I))) j
```
Now we just need to choose some `n` to put in the expression:
```
W (B (S I)) (W (B (S I))) (C (C (S (C I W) (C (C (C I K))))) n)
```
Using this strategy we can guarantee that for a number `n` this expression will need at least `2n` reductions, but `n` has three restrictions:
* `n` must need an argument to be reduced
* `n` must have 80 combinators or less (so far we used 19 of the 99)
* `n` must not avoid line `L`
`n` could be designed to avoid line `L`:
```
n = 1 = C B (B I)
C B (B I) W (C (C (C I K)) n) y
B W (B I) (C (C (C I K)) n) y
W (B I (C (C (C I K)) n)) y
B I (C (C (C I K)) n) y y
I (C (C (C I K)) n y) y
```
In the last line if we reduce the `I` it becomes line `L`, but we can also reduce `C (C (C I K)) n y`. The way we will define `n` avoids this because we will add 1 many times to a number that doesn't skip line `L`. It would have been harder to find a definition that does run into this problem, almost anything we can do is naturally forced to reach line `L`.
Let `[a]` be a function that represents \$f\_a\$ in the [fast-growing hierarchy](https://en.wikipedia.org/wiki/Fast-growing_hierarchy). We will also need some other functions that will be implemented later, here are their definitions:
```
d1 f x = x f x
d2 f g x = x f g x
d3 f g h x = x f g h x
d4 f g h i x = x f g h i x
...
```
By definition, applying `[a]` `x` times to `x` is equivalent to `[a+1] x`:
```
x [a] x = d1 [a] x = [a+1] x
```
Applying `d1` to `[a]` increases `a` by 1, doing this `x` times gives:
```
x d1 [a] x = d2 d1 [a] x = [a+x] x = [a+w] x
```
Now that we can add \$\omega\$, we can do this `x` times:
```
x (d2 d1) [a] x = d2 (d2 d1) [a] x = [a+wx] x = [a+w^2] x
```
Here we have a pattern:
```
d1 [a] x = [a+1 ] x
d2 d1 [a] = [a+w ] x
d2 (d2 d1) [a] x = [a+w^2] x <- we stopped here
d2 (d2 (d2 d1)) [a] x = [a+w^3] x
...
k d2 d1 [a] x = [a+w^k] x
d3 d2 d1 [a] x = [a+w^w] x
```
And here another:
```
d1 [a] x = [a+1] x
d2 d1 [a] x = [a+w] x
d3 d2 d1 [a] x = [a+w^w] x <- we stopped here
d4 d3 d2 d1 [a] x = [a+w^w^w] x
d5 d4 d3 d2 d1 [a] x = [a+w^w^w^w] x
d6 d5 d4 d3 d2 d1 [a] x = [a+w^w^w^w^w] x
```
I won't prove these patterns are correct, it would take many lines and would be very repetitive, this is left as an exercise to the reader.
We will use that last function, with `[a] = [0] = S B`.
These are the definitions of the `d`s:
```
d1 = B W (C I)
d2 = B (B W) (B C (C I))
d3 = B (B (B W)) (B (B C) (B C (C I)))
d4 = B (B (B (B W))) (B (B (B C)) (B (B C) (B C (C I))))
d5 = B (B (B (B (B W)))) (B (B (B (B C))) (B (B (B C)) (B (B C) (B C (C I)))))
d6 = B (B (B (B (B (B W))))) (B (B (B (B (B C)))) (B (B (B (B C))) (B (B (B C)) (B (B C) (B C (C I))))))
```
Each function uses part of the previous, this can be used to reduce the number of combinators to this expression:
```
S (B (S (B (S (B (S (B (S (B (B (B (B (B (B (B W)))))) (B (B (B (B (B C)))))) (B (B (B (B (B W)))))) (B (B (B (B C))))) (B (B (B (B W))))) (B (B (B C)))) (B (B (B W)))) (B (B C))) (B (B W))) (B C)) (B W) (C I) (S B) x
```
This expression is reducible, we can use the `C (C a) b` trick to solve this problem:
```
C (C (C (C (C (C (S (B (S (B (S (B (S (B (S (B (B (B (B (B (B (B W)))))) (B (B (B (B (B C)))))) (B (B (B (B (B W)))))) (B (B (B (B C))))) (B (B (B (B W))))) (B (B (B C)))) (B (B (B W)))) (B (B C))) (B (B W))) (B C)) (B W))) (C I))) (S B))) x
```
The only thing missing is the input, we can use 13 combinators to reach some big number that cannot be reduced without an argument.
The largest number I found was 65536 using 12 combinators:
```
C (C (C (C (W B) (W B)) (W B))) (W B)
```
Putting everything together gives an expression with 98 combinators and a cycle of at least \$2 f\_{\omega^{\omega^{\omega^{\omega^\omega}}}}(65536)\$ reductions.
```
W (B (S I)) (W (B (S I))) (C (C (S (C I W) (C (C (C I K))))) (C (C (C (C (C (C (S (B (S (B (S (B (S (B (S (B (B (B (B (B (B (B W)))))) (B (B (B (B (B C)))))) (B (B (B (B (B W)))))) (B (B (B (B C))))) (B (B (B (B W))))) (B (B (B C)))) (B (B (B W)))) (B (B C))) (B (B W))) (B C)) (B W))) (C I))) (S B))) (C (C (C (C (W B) (W B)) (W B))) (W B))))
'-----------.-----------' '----------------------------------------------------------------------------------------------------------------------.----------------------------------------------------------------------------------------------------------------------' '-----------------.-----------------'
Y f_w^w^w^w^w 65536
'------------------------------------------------------------------------------------------------------------------------------------------------------------.------------------------------------------------------------------------------------------------------------------------------------------------------------'
j
```
[Answer]
Gotta start with something
```
1:(((C (C I) (W I)) (C (C I) (W I)) I I) (W I) (W (C I) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
2:(((C I (C (C I) (W I))) (W I) I I) (W I) ((C I) (W (C I)) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
3:(((I (W I)) (C (C I) (W I)) I I) (W I) (I (W (C I)) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
4:(((W I) (C (C I) (W I)) I I) (W I) (W (C I) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
5:(((I (C (C I) (W I))) (C (C I) (W I)) I I) (W I) ((C I) (W (C I)) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
6:(((C (C I) (W I)) (C (C I) (W I)) I I) (W I) (I (W (C I)) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
7:(((C I (C (C I) (W I))) (W I) I I) (W I) (W (C I) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
8:(((I (W I)) (C (C I) (W I)) I I) (W I) ((C I) (W (C I)) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
9:(((W I) (C (C I) (W I)) I I) (W I) (I (W (C I)) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
10:(((I (C (C I) (W I))) (C (C I) (W I)) I I) (W I) (W (C I) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
11:(((C (C I) (W I)) (C (C I) (W I)) I I) (W I) ((C I) (W (C I)) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
12:(((C I (C (C I) (W I))) (W I) I I) (W I) (I (W (C I)) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
13:(((I (W I)) (C (C I) (W I)) I I) (W I) (W (C I) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
14:(((W I) (C (C I) (W I)) I I) (W I) ((C I) (W (C I)) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
15:(((I (C (C I) (W I))) (C (C I) (W I)) I I) (W I) (I (W (C I)) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
16:(((C (C I) (W I)) (C (C I) (W I)) I I) (W I) (W (C I) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
17:(((C I (C (C I) (W I))) (W I) I I) (W I) ((C I) (W (C I)) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
18:(((I (W I)) (C (C I) (W I)) I I) (W I) (I (W (C I)) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
19:(((W I) (C (C I) (W I)) I I) (W I) (W (C I) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
20:(((I (C (C I) (W I))) (C (C I) (W I)) I I) (W I) ((C I) (W (C I)) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
21:(((C (C I) (W I)) (C (C I) (W I)) I I) (W I) (I (W (C I)) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
22:(((C I (C (C I) (W I))) (W I) I I) (W I) (W (C I) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
23:(((I (W I)) (C (C I) (W I)) I I) (W I) ((C I) (W (C I)) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
24:(((W I) (C (C I) (W I)) I I) (W I) (I (W (C I)) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
25:(((I (C (C I) (W I))) (C (C I) (W I)) I I) (W I) (W (C I) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
26:(((C (C I) (W I)) (C (C I) (W I)) I I) (W I) ((C I) (W (C I)) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
27:(((C I (C (C I) (W I))) (W I) I I) (W I) (I (W (C I)) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
28:(((I (W I)) (C (C I) (W I)) I I) (W I) (W (C I) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
29:(((W I) (C (C I) (W I)) I I) (W I) ((C I) (W (C I)) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
30:(((I (C (C I) (W I))) (C (C I) (W I)) I I) (W I) (I (W (C I)) (W (C I)) (W (C I))) ((W I) (W I) (W I) I))
31:(((C (C I) (W I)) (C (C I) (W I)) I I) (W I) (W (C I) (W (C I)) (W (C I))) ((I (W I)) (W I) (W I) I))
```
] |
[Question]
[
[UTF-1](https://en.wikipedia.org/wiki/UTF-1) is one of the methods to transform ISO/IEC 10646 and Unicode into a sequence of bytes. It was originally for ISO 10646.
The UTF-1 encodes every character with variable length of byte sequence, just like UTF-8 does. It was designed to avoid control codes. But it was not designed to avoid duplication of a slash character ('/'), which is path delimiter for many operating systems. Additionally it takes a bit long to process the algorithm, because it is based on modulo 190, which is not power of two. Eventually UTF-8 was better than that.
In this challenge we are reviving UTF-1.
# How it works
Every constant value in tables on this section is represented in hexadecimal value.
The symbol / is the integer division operator, % is the integer modulo operator, and ^ means power. The precedence of operators is ^ first, / second, % third, and others last.
Here is how to convert each codepoint to UTF-1 (sorry for typo last time):
| codepoint x | UTF-1 |
| --- | --- |
| U+0000 to U+009F | (x) |
| U+00A0 to U+00FF | (A0,x) |
| U+0100 to U+4015 | y=x-100 in (A1+y/BE,T(y%BE)) |
| U+4016 to U+38E2D | y=x-4016 in (F6+y/BE^2,T(y/BE%BE),T(y%BE)) |
| U+38E2E to U+7FFFFFFF | y=x-38E2E in (FC+y/BE^4,T(y/BE^3%BE),T(y/BE^2%BE),T(y/BE%BE),T(y%BE)) |
T(z) is a function such that:
| z | T(z) |
| --- | --- |
| 0 to 5D | z+21 |
| 5E to BD | z+42 |
| BE to DE | z-BE |
| DF to FF | z-60 |
# Challenge
Your task is to implement a program or a function or a subroutine that takes one integer, who represents the codepoint of a character, to return a sequence of integers that represents its corresponding UTF-1 value.
# Constraints
Input shall be an nonnegative integer up to 0x7FFFFFFF.
# Rules
* Standard loopholes apply.
* Standard I/O rules apply.
* Shortest code wins.
# Test cases
Taken from the Wikipedia article.
```
U+007F 7F
U+0080 80
U+009F 9F
U+00A0 A0 A0
U+00BF A0 BF
U+00C0 A0 C0
U+00FF A0 FF
U+0100 A1 21
U+015D A1 7E
U+015E A1 A0
U+01BD A1 FF
U+01BE A2 21
U+07FF AA 72
U+0800 AA 73
U+0FFF B5 48
U+1000 B5 49
U+4015 F5 FF
U+4016 F6 21 21
U+D7FF F7 2F C3
U+E000 F7 3A 79
U+F8FF F7 5C 3C
U+FDD0 F7 62 BA
U+FDEF F7 62 D9
U+FEFF F7 64 4C
U+FFFD F7 65 AD
U+FFFE F7 65 AE
U+FFFF F7 65 AF
U+10000 F7 65 B0
U+38E2D FB FF FF
U+38E2E FC 21 21 21 21
U+FFFFF FC 21 37 B2 7A
U+100000 FC 21 37 B2 7B
U+10FFFF FC 21 39 6E 6C
U+7FFFFFFF FD BD 2B B9 40
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~289~~ ~~262~~ ~~241~~ ~~240~~ ~~232~~ 230 bytes
```
lambda n:[p(*[[n-d,4,252],[n-16406,2,246],[n-256,1,161]][(n<16406)+(n<d)]),[160]*(n>159)+[n]][n<256]
c=190
d=233006
t=lambda n:n+[-96,-c,66,33][(n<94)+(n<c)+(n<223)]
p=lambda y,x,z:[z+y//c**x]+[t(y//c**i%c)for i in range(x)][::-1]
```
[Try it online!](https://tio.run/##VU7dboIwFL4eT9GYEFo4aFvaKkT2FrvqesEAJ2arBDBBX55R1GW7Oec7P99Pex2OZ5tMh/x9@iq@P6oC2Uy3ONTaxhUI4JIbmDFTgirgwIVaZi4VMGCKGaOx3S9nEs2oIoaAZoqaENtXJlMSaTs/2f1MMV6Zs5R6Vc6ThFLlDfmvq410nCqIS1AKkmSRTcWiWS6V84QYr30yrjDCLdO36LrZlGE4mkgP@I4bvySHc4ca1FjUFfazxiMxOstiZqah7oey6Ose5UgzQHPEuSgKiEvpinKjoPLe5mnJKh/dXanYya18AvfBxFbsEiW2xvOcszNw5r9mmffSdo0d8MrvUYb8foV8hHHwFgXRsR6xeyKaZ2bdnS79gAUENCDrS9vWHSbksWWUAApQsD6dG4u1I45/WfwfC7kko4txuOsbQsj0Aw "Python 3 – Try It Online")
*-27 bytes cos my implementation of T was wrong*
*-21 bytes thanks to @wasif's implementation of f, which works on t too*
*-1 byte thanks to storing 233006 in a variable*
*-8 bytes thanks to @pxeger in TNB*
*-2 bytes thanks to unneeded parens*
It's a naive approach, and I'm sure there's lots of room for golfing, but it works!
# [Python 3.8](https://docs.python.org/3.8/), 210 bytes
```
lambda n:[[(y:=n-[d:=233006,e:=16406,256][j:=(n<e)+(n<d)])//c**(x:=[4,2,1][j])+(z:=[252,246,161][j])]+[(g:=y//c**i%c)+[-96,-c,66,33][(g<94)+(g<c)+(g<223)]for i in range(x)][::-1],[160]*(n>159)+[n]][n<256]
c=190
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBBTsMwEDzTV1iVotiN09qO7bZWzS84GR9CmrapwI2SVEr5CpdKCB7EjdeA3RQEl1nv7szurF_e61O3O7jz60bfvx27Tbr4_HjMnx7WOXDKGHhS2qVmrTTLMkIkLpWmkvsHE9KavdLQrUqUeFwji2azYjKBvdKGY4apJ1jfe_Y5EwwzLjGVQ9UmBm6VPl0UVVSgxKRLidMCS4mzzPruasm9eLsqLshYhuzm0IAKVA40uduWsEfWKJVSiw2VxE6gu6Vi6Uc5a41bBYujQtMluV721ZVtV-Rt2QINDMXAsz1IggETIoAMKSdiCD67nC2uMXQJX4i5-HkEBuVzvsgkn9vRKBgMC4LH32VqdFM3levgOGqBAlE7BhGAML5L4mRX9jCQkGHKTpv9se0gxzGJ0fRY12UDEbpWKUEYxCCe7g-VgyYI-78q9k8FgpM-2NgM8y1CaPiG83mI3w)
Same as the Python 3 answer, but uses 3.8's `:=` operator to cram it all into 1 lambda
## Explanation
The lambda `t` is equivalent to the `T()` defined in the challenge.
The lambda `p` takes 3 integers, `y`, `x`, and `z`, and creates:
```
[z+y/190^x, t(y/190^(x-1)%190), t(y/190^(x-2)%190)...t(y/190^0%190)]
```
We only use `x` as `1`, `2`, or `4`, depending on which formula we're handling:
```
(y = n-256, x = 1, z = 161):
[161+y/190, t(y%190)]
(y = n-16406, x = 2, z = 246):
[246+y/190^2, t(y/190%190), t(y%190)]
(y = n-233006, x = 4, z = 252):
[252+y/190^4, t(y/190^3%190), t(y/190^2%190), t(y/190%190), t(y%190)]
```
Finally the lambda `f` handles the 5 formulas and their ranges for input `n`:
```
def f(n):
if n < 160: return [n]
if n < 256: return [160, n]
if n < 16406: return p(n-256, 1, 161) #first formula
if n < 233006: return p(n-16406, 2, 246) #second formula
return p(n-233006, 4, 252) #third formula
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 270 bytes
```
190s1256s216406s7233006s8{g1./}s9%t={g1.%J{{33.+}{66.+}{g1.-}{g6.-}}{94g1223g2}(.<)bcz[{}Z]cne!}J{qbx{40960.+bx}{g2.-{{g9e!161.+}q%t!}M-}{g7.-{{g92E!246.+}{g9e!%t!}q%t!}M-}{g8.-{{g94E!252.+}{g93E!%t!}{g92E!%t!}{g9e!%t!}q%t!}M-}}{160g2g7g82147483648}(.<)bcz[{}Z]cne!qb6\m
```
[Try it online!](https://tio.run/##ZY7PTgMhEIfv@xZ7aKJpug4DBTbRYy9NfAGrB1n@XNrqum3SSHj2daY0MUYOHx8zvwHc@WsfpvEc5v0xOz2LHiaBaz2h0Ar0ZFBKoN3mJLqHMvWL0xPrYpuzlN2yZK2ZVFoRNbHkXiWBKBOWu@7x3g3fu1xe3oZjaMs2j@6SFfQauqW70Ah2q5xTH1qhBd00Lk5teea7TG3gpkVV36AQd38jtkYURdZYI3JzzdTBm/0dK1loSJhMsiiUUVZqZf/9dHT69TDj8FEOu@mzmQFMbAAsEHq2dzbHNrBFMgFkYu0ZgeDYHJnhruVuJKMYNIoyDN147gauRUsWvSfzgSzwMUbPCIw6C420Af2VtXyrA23Xk4l1/QA "Burlesque – Try It Online")
Pretty sure this can be golfed further/better, but this is already pretty terrifying. Main changes vs. ungolfed are using zips to build the conditional blocks.
```
190s1 # Store 190
256s2 # Store 256
16406s7 # Store 16406
233006s8 # Store 233006
{g1./}s9 # Store divide by 190
%t={ # Assign T
g1.% # Mod 190
J # Duplicate (conditional is destructive)
{
{94.<}{33.+} # <94 add 33 (0x21)
{g1.<}{66.+} # <190 add 66 (0x42)
{223.<}{g1.-} # <223 sub 190 (0xBE)
{g2.<}{96.-} # <256 sub 96 (0x60)
}
cne!} # Conditional evualuate resulting block
# END T
J # Duplicate (conditional is destructive)
{{160.<} qbx # <160 Put in box
{g2.<} {40960.+bx} # <256 add 40960 (0xA000) and box
{g7.<} { # <16406 (0x4016)
g2.- # Sub 256
{
{
g9e! # Divide by 190
161.+ # Add 161
}
q%t! # Apply T
}M-} # Cool map (create copy for each block and
{g8.<} { # eval and return list of each result)
g7.- # Sub 16406
{
{
g92E! # Divide by 190 twice
246.+ # Add 246
}
{
g9e!%t! # Divide by 190 apply T
}
q%t! # Apply T
}M-}
{2147483648.<} { # < 2147483648
g8.- # Sub 233006
{
{
g94E! # Divide by 190 4x
252.+ # Add 252
}
{
g93E!%t! # Divide by 190 3x
} #2x 1x 0x
{g92E!%t!}{g9e!%t!}q%t!}
M-}
}
}cne! # Evaluate the conditional
qb6\m # Map to hex and concatenate
```
[Answer]
# JavaScript (ES6), 175 bytes
Expects the input as a string. Returns a comma-separated string of bytes.
```
x=>(v=190,p=16406,q=233006,g=(o,n,d,k=1,y=(x-o)/k%v|0)=>--n?g(o,n,d,k*v)+[,y+=y<94?33:y<v?66:y<223?-v:-96]:160-~d+y,x<160?x:x>>8?x<p?g(256,2):x<q?g(p,3,85):g(q,5,91):160+[,x])
```
[Try it online!](https://tio.run/##XZHLbptAFIb3eYqjSBUz9ZgMYG6usWUuI3VtZZVkgWzskjhAgCKsXp6gUjddtu/R58kL9BHcGa5uLdlmvvOf/z9neAyrsNjmcVZOk3QXnffOuXaWqHIUm5LMUYwZNciLo2oa5Q8HB6UkITvy5Cjk5KB6muKbpzfVZ4qd5XSarA59/W2FJ3fkNHFOC3u20rT5aVGtDIP/qaq2mlbzqW08zBWDTr/uJidSL/jjqp7Xy6W1qhcZN1J1g6h4Xi9e@CEjGrF0PD@gF6ITW8GilQfUD/icRy8f4zxC0r6QsJxH4Y7Fx2hzSraIYrlMN2UeJweE5SI7xiW6vk@usbxP8yDcfkAFOEv4dAVwjEq4g4RAVGfRtox28AAOFDJvfh56b9Bq4dxvMMANJrxJfCouy8K8iN4nJUrk4hhvI6RiAopxmd7L84hHwh5VAznGRckRL3QpEuF7PIcZqsRwaFJd@AjTLNxtyjAvkUpAopKo3mZZlHthESGM5cc0TpAEEn7HE7ZpUqTHSD6mBz4dbw2SHVLEfCLw4nb6ksVLYiTSDeaMN7IC6c/v768/f/BfCeYgvf76JlK@4LNY5HZCqckATHbVHy0KYNHhaPOqPVbXvMq/61Hgsoa4o8ZrNd6oYa2GDRqFCo0CqjIQ3W@IGYwkaMiYpbit5sLHFRr1wsdsstZgqj2xmixOtJ4woXF1mFkd4ePQltgdmfF4AKaPWZwYnBg8a4zzmzhmgsrA6/2Dxo1DjYf2hszqlLoHmtdD32@VhgrueoAB66E/tAdduzGD2dDOmN9CHdb@CIMBBiNkA2w2apemPXRpCzUrUIWnyxfvdm@h8PTa3ccbaI1ZX9JMcFUwxSKdPf2v5Half7psMAIwvKvbiclYb@gDf9mqC64NM/oX "JavaScript (Node.js) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 138 bytes
```
f=x=>x<160?[x]:x>>8?(g=y=>++l<5?[...g(y/190|0),(y%=190)-33*~(y>93)]:[f(n)[0]-~y])(x+~[233005,,16405,255].find((m,j)=>(l=j,n=m)<x)):[160,x]
```
[Try it online!](https://tio.run/##7ZPbbptAEIbv/RRzU3m3YLKAOSWByBxW6k1volxRpFAHu7ZsQLCtsNrm1d3hnPYNKgXJYvebf/5/x/Ye0x9pva0OpVjlxUt2ve7cxvWae9VkD3GT3DaeZz@QvXtxPUk63RsPsaIoe3K5UR32i1GZXD64uKQrXf/4Si6eo9PkNt6RnMYsWb1eEkoa6TXWdJ0xQ5ZVc40vzTASZXfIXwg5y0fqeuTkHuXcPdP7htLbGMPlJrmKrBbbtM5qcOF5Afg8SYxZHMDi09ZmADabtg5Wnbm6wSp@NrPA5x3xZ03Qa4JZw3sNnzQqazUqaOpEjLAjVjSTqCNzlur3mjc@fqvR3vhYXdYGLG0kdpeFRB8JbzW@AWt7IHgc1hNnIGuMB@DGnIXERGJi1hwXdnHcAo1DMPpHnRtCHUNHQ24PSiMAPRhhGPZKUwN/M8GIjzCc2qOh3VzDemrnPOyhAZtwhtEEoxnyCXYT9UOzEfqsh7odaa2nj4MPs/ew9Qz62edvoDfmY0m3wNfAagcZ7Nk/JX8o/dXlgBmBGSyeJIvz0TAE/LE1H3wH1mzxrIjqcCZUqcvTQZDll3xJlXNakgZcDxpciu03chOzlZOudpsVT6SbPaV3i@kvr@yKKkpRJNqOn3iObZHXAorvCGBHPn8/f80qpUyrOvuUCyLwusmgmq3JqK1FhVrseBstikc8W74nqMXNU1lmVYCJeNgyfXkUaSWIJgObjYpTppyKPensXBBKfTpsM6JSkGC5lNsY5VgccrKEZdv1m95d3y/r@2X9Ty7rHw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 99 bytes
```
I⎇›¹⁶⁰θθ⎇›²⁵⁶θ⟦¹⁶⁰θ⟧E↨⁺θ⎇›¹⁶⁴⁰⁶θ¹²⁴⎇›²³³⁰⁰⁶θ³¹²⁴²⁹⁴I”)¶∧‴+νO﹪”¹⁹⁰⁺ι⎇κ⎇‹¹⁸⁹ι⎇‹²²²ι±⁹⁶±¹⁹⁰׳³⊕‹⁹³ι¹⁵⁹
```
[Try it online!](https://tio.run/##bY5Pa8MwDMW/islJAQ/8J/EqeuugpdCNHHorPZhMrKFJ1tpp2T6969QbgdIHNkL6vSfVB@vqb9uGULmmH@DN@gG25HrrfmHlyA7kQBrB2TmPj7PHmSpNmu0Stefs3Z5gYT1B1V48PPFIU4g/l1TFk0ytxT@gI6EwQvfLMqmkxJlCg1hkeVSMQBH/@65myjpO5Ya8BzlDzpr8oauUSt0P@oqrAc1Uj7kj33TkQWvO1n3tqKN@oM/kRj2a0xEl5knzEHbi53WZtA8v1/YG "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
¹⁶⁰ Literal integer 160
› Is greater than
θ Input integer
⎇ If true then
θ Input integer
⎇ Else
²⁵⁶ Literal 256
› Is greater than
θ Input integer
⎇ If true then
⟦ ⟧ List of
¹⁶⁰ Literal integer 160
θ Input integer
⎇ Else
θ Input integer
⁺ Plus
¹⁶⁴⁰⁶ Literal integer 16406
› Is greater than
θ Input integer
⎇ If true then
¹²⁴ Literal integer 124
⎇ Else
²³³⁰⁰⁶ Literal integer 233006
› Is greater than
θ Input integer
⎇ If true then
³¹²⁴²⁹⁴ Literal integer 3124294
⎇ Else
”)¶∧‴+νO﹪” Compressed string "121198296994"
I Cast to integer
↨ Convert to base
¹⁹⁰ Literal integer 190
E Map over base 190 digits
ι Current value
⁺ Plus
κ Current index
⎇ If not first digit then
¹⁸⁹ Literal integer 189
‹ Is less than
ι Current value
⎇ If true then
²²² Literal integer 222
‹ Is less than
ι Current value
⎇ If true then
⁹⁶ Literal integer 96
⎇ Else
± Negated
¹⁹⁰ Literal integer 190
± Negated
⎇ Else
³³ Literal 33
× Times
⁹³ Literal 93
‹ Is less than
ι Current value
⊕ Incremented
⎇ If first digit then
¹⁵⁹ Literal integer 159
I Cast to string
Implicitly print
```
[Answer]
# [Haskell](https://www.haskell.org/), 234 bytes
```
t z|z<94=33+z|z<130=z+66|z<223=z-190|0<1=z-96
u x|x<256=[160|x>159]++[x]|1>0=let[b,c,d]=head$dropWhile((x<).head)[[233005,5,252],[16406,3,246],[256,2,161]];w=reverse.take c.map(`mod`190).iterate(`div`190)$x-b in d+head w:map t(tail w)
```
[Try it online!](https://tio.run/##HY7NioMwFIX38xRZuFBMJT8acMb0NWYhAdPmgqHRik1rkLy7E@esvnO4nHtG/XqAc8fh0R73rq0l5@VJlBO5l0IkZIzL/UJbEklHE7Xi641CDB1rhOypIDFcadOqsuyDivRKpAPf3/AdGyVH0CYz63P5Ha2DPA9dUZ1Z0feMc0Ia3GDWMIVTUU0E5pjVIrnUjRmmgir1s8kVPrC@oPL6AeheTXrJh@lphjSqqKyHVXvIB2M//0kWLjdkZ2TK8xPavtM98rnX1qGtOCZtZ7msdvbZG5FASdLxBw "Haskell – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), 250 bytes
```
|n|{let t=|i,b,z|if i<2{b+z}else{z%190+33+(z%190>93)as i32*33};let g=|b,y,p|(1..=p).map(|i|t(i,b,y/190i32.pow(p-i))).collect();match n{0..=159=>vec![n],0..=255=>vec![160,n],0..=16405=>g(161,n-256,2),0..=233005=>g(246,n-16406,3),_=>g(252,n-233006,5)}}
```
[Try it online!](https://tio.run/##bZL7jppAFMb/9ymOm9QOlaVcBBRXG1HmAZps02SzMa47bkkRKYzuRXj27ZkZLm5TjQK/853vXIb8WPD3Y8Gg4I9BEB@CIDzuvrPN47S3S2G/iVOiwRkSxmE3ey/T8ixu@ayM9Qf9rYx3EN/Y54fhW8WSgp3fPlkTc@g4QyLv5hNH2xQQO/YXx6mmIvVpVj7or3pWEsswZplm7DcZKeOSE@H4@hWzUG5kh2eSXceaphnbQ5KwLSfadL/h21@Qnk3MtNzJbH5i2/5deq8LYLtuDSzP1GtoeSMT8ROxPEtPr23X021NyR3HVCF75GFIKD3d0fS1ZK4t5ELj6a5WVe@4j0MOSZwyiNNuW3gjVmQkh@1vccF4ITbWA7kzkurAXjJsnz1qMINskxdsHafZkZOBEBvH9DnHDWjatE7JWXFMOGp3JJUwy@OUJ2mfXN0Oz8HPCq7ncA5evlVXOqC90kvlpihYztfsT58oelF82qvwKw71sgfRQgCDgueasCW4ev0H297gda6mUE3tj1zk8SIAEV7PsT/ZPs/jPc5dZEnMyWf4fHlcMltmGTnj4lUqT@WpPxtcXdVBIv/FBwsGwS4/7NfYyzrfPMYvZCBz78z7O9sw7nXL09pt6W2i0uC7dG/EnOWkfqFO5f8cTx9MLnpVflqvehfX26Fp@hTAp73mcWwCjM32cYLRSRddYBR/i04QUknCTrNUmmWnoUpDW41lCo0FttUSdyWJH3UkkqSrZYVKc@ETCo194ePLWgvw7YaMZS0kTkOo0IQujMY1wXZMRSY1GWF5AOp2tZB4SDys1ZVbyXLUB5vCsvGPpBtCB4s2hnRcK90lOMsGrlZK6dkQLloY0Qau2vSoTvdGMGrTKV0p6MJi1cGohVEHaQvlRGpos4GhqaAzjmzhGeLg9ewKCs@lmr3bgDKmTcjxIbTBF4PU9uY/obAOfciagBeBt@zdDn1KG8MV4GHbIYQTGJm9vw "Rust – Try It Online")
### Ungolfed
```
|n| {
// Modified T: Returns T(Z%0xBE) if i > 1 else B+Z
let t = |i, b, z|
if i < 2 {
b+z
} else {
z % 0xBE + 0x21 + if (z % 0xBE) > 0x5D { 0x21 } else { 0 }
};
// Helper: Generates the p UTF-1 bytes for codepoints > U+FF
let g = |b, y, p|
(1..=p).map(
|i| t(i, b, y / 190_i32.pow(p-i))
).collect();
// Select encoding variant
match n{
0..=159 => vec![n],
0..=255 => vec![0xA0, n],
0..=16405 => g(0xA1, n - 0x100, 2),
0..=233005 => g(0xF6, n - 0x4016, 3),
_ => g(0xFC, n - 0x38E2E, 5)
}
}
```
] |
[Question]
[
## Challenge
Imagine a hexagonal grid as shown below. Let's call such a grid has size \$n\$ if it has \$n\$ dots on one side. The following is one of size 3:
```
- - -
- - - -
- - - - -
- - - -
- - -
```
Then, pick as many dots as possible on the grid so that no two dots are adjacent. For size 3, the maximum is 7 dots:
```
- * - * - *
* - - * - - - -
- - * - - or * - * - *
* - - * - - - -
- * - * - *
```
Your task is to output such a grid. For a size-\$n\$ hexagon, the output must contain exactly [A002061(n)](https://oeis.org/A002061) = \$n^2-n+1\$ non-adjacent dots. The corresponding maximal pattern can be found [in this image linked on the OEIS sequence](https://oeis.org/A002061/a002061.png) (imagine this: dissect all the hexagons there into triangles, remove one outermost layer of triangles, and pick the centers of original hexagons). The corresponding ASCII-art output must look like the following, modulo rotation/reflection:
```
n = 1
*
n = 2
* -
- - *
* -
n = 3 (following or alternative shown above)
* - *
- - - -
* - * - *
- - - -
* - *
n = 4
* - - *
- - * - -
- * - - * -
* - - * - - *
- * - - * -
- - * - -
* - - *
n = 5
- * - - *
* - - * - -
- - * - - * -
- * - - * - - *
* - - * - - * - -
- * - - * - - *
- - * - - * -
* - - * - -
- * - - *
n = 6
- * - - * -
* - - * - - *
- - * - - * - -
- * - - * - - * -
* - - * - - * - - *
- - * - - * - - * - -
* - - * - - * - - *
- * - - * - - * -
- - * - - * - -
* - - * - - *
- * - - * -
n = 7
* - - * - - *
- - * - - * - -
- * - - * - - * -
* - - * - - * - - *
- - * - - * - - * - -
- * - - * - - * - - * -
* - - * - - * - - * - - *
- * - - * - - * - - * -
- - * - - * - - * - -
* - - * - - * - - *
- * - - * - - * -
- - * - - * - -
* - - * - - *
n = 8
- * - - * - - *
* - - * - - * - -
- - * - - * - - * -
- * - - * - - * - - *
* - - * - - * - - * - -
- - * - - * - - * - - * -
- * - - * - - * - - * - - *
* - - * - - * - - * - - * - -
- * - - * - - * - - * - - *
- - * - - * - - * - - * -
* - - * - - * - - * - -
- * - - * - - * - - *
- - * - - * - - * -
* - - * - - * - -
- * - - * - - *
n = 9
- * - - * - - * -
* - - * - - * - - *
- - * - - * - - * - -
- * - - * - - * - - * -
* - - * - - * - - * - - *
- - * - - * - - * - - * - -
- * - - * - - * - - * - - * -
* - - * - - * - - * - - * - - *
- - * - - * - - * - - * - - * - -
* - - * - - * - - * - - * - - *
- * - - * - - * - - * - - * -
- - * - - * - - * - - * - -
* - - * - - * - - * - - *
- * - - * - - * - - * -
- - * - - * - - * - -
* - - * - - * - - *
- * - - * - - * -
n = 10
* - - * - - * - - *
- - * - - * - - * - -
- * - - * - - * - - * -
* - - * - - * - - * - - *
- - * - - * - - * - - * - -
- * - - * - - * - - * - - * -
* - - * - - * - - * - - * - - *
- - * - - * - - * - - * - - * - -
- * - - * - - * - - * - - * - - * -
* - - * - - * - - * - - * - - * - - *
- * - - * - - * - - * - - * - - * -
- - * - - * - - * - - * - - * - -
* - - * - - * - - * - - * - - *
- * - - * - - * - - * - - * -
- - * - - * - - * - - * - -
* - - * - - * - - * - - *
- * - - * - - * - - * -
- - * - - * - - * - -
* - - * - - * - - *
```
## I/O and rules
You can use any two distinct non-whitespace chars for marked and unmarked dots respectively. Trailing spaces on each line and leading/trailing whitespaces are allowed. Outputting a list of lines, and outputting integer charcodes instead of the corresponding chars are also allowed.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
NθG↙↘→→↗↖θ⎇﹪賓⟲∧LVoIG;”“⟲∧⦄≧Σ¶ζ;
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orID@nMj0/T8PKJb88zyc1rURHAcwMykzPALHR6dACBAuivFBHISS1KC@xqFLDNz@lNCdfAyhirKmjoKSloKugG5MHJIEsJaAAmAEWALKUNDWt//83@69blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: After reading in `n`, the code simply draws a hexagon using one of two fill patterns depending on whether `n` is a multiple of 3; if it is, the fill pattern has the `*` one `-` in from the corner, otherwise it has the `*` in the top left corner.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 92 bytes
```
f=lambda n,i=0:[l:=' '*(n-i)+('- * - '*n)[n%3%2+i<<1:][:n+i<<1]]+(n>i+1and[*f(n,i+1),l]or[])
```
[Try it online!](https://tio.run/##HcxBDoIwEEDRq8yGdIaCobIxDXiR2kUNVseUKWnYePqK7v7b/O2zv7KMl63UGucU1vsSQDqeB@uSnRWoFqVn0qh6aKE/LOSkGZuz5mky1jsr//Jeo1xZmyCLayMeE22oSz4X56nGXICBBUqQ5wPNQBa2wrKjuok6vTMLRmQi/TPVLw "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 84 bytes
```
f n=[[" * - -"!!mod(i+gcd 3n)6|i<-[1,3..2*y]++[4*y..2*y+4*n-4]]|y<-abs<$>[1-n..n-1]]
```
[Try it online!](https://tio.run/##HcaxDoIwFAXQX7kQBm19TSqEqfgFOjk2HaqINNInERya8O818Uxn9MvrMU05D@DO2hICBCqLIr77XZDPe4@a9@0WDFl9qJU6iuSktI1I/8tGMDXObcmQvy2mOllNrBSTdi5HHxgdop8vmL/rdf2cGRUGtPkH "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
3ḍ6_BṙN€ṁ"Ḥ’rƊK€ṭ"Ḷ⁶ẋƊṚŒḄY
```
A full program that accepts a positive integer and prints using `0` as `*` and `1` as `-`.
**[Try it online!](https://tio.run/##y0rNyan8/9/44Y5es3inhztn@j1qWvNwZ6PSwx1LHjXMLDrW5Q0WWAsU2PaocdvDXd3Huh7unHV00sMdLZH/gToB "Jelly – Try It Online")** Or see [a few](https://tio.run/##y0rNyan8/9/44Y5es3inhztn@j1qWvNwZ6PSwx1LHjXMLDrW5Q0WWAsU2PaocdvDXd3Huh7unHV00sMdLZH/D7e7Pdy52CDrUcNcLSDDEMTQ1cx61LiPi@v/f0MDAA "Jelly – Try It Online") with `*` and `-` in place of `0` and `1`.
### How?
```
3ḍ6_BṙN€ṁ"Ḥ’rƊK€ṭ"Ḷ⁶ẋƊṚŒḄY - Main Link: positive integer, n
3ḍ - three divides (n)? -> 1 if n is a multiple of three else 0
6 - six
_ - subtract -> 5 if n is a multiple of three else 6
B - to binary -> 101 (i.e. "-*-") ...else 110 (i.e. "--*")
N€ - negate each (of implicit [1..n]) -> [-1,-2,...,-n]
ṙ - rotate (110 or 101) left by (each of those) -> Patterns (one for each row of bottom half of a hexagon)
Ɗ - last three links as a monad, f(n):
Ḥ - double -> 2n
’ - decrement -> 2n-1
r - (2n-1) inclusive range (n) -> [2n-1..n]
" - zip (Patterns) and (range) applying, f(Pattern, i):
ṁ - mould like -> resized rows using repetition
K€ - join each with space characters -> Rows
Ɗ - last three links as a monad, f(n):
Ḷ - lowered range -> [0..n-1]
⁶ - space character
ẋ - repeat -> leading spaces for bottom half
" - zip (Rows) and (leading spaces) applying, f(row, spaces):
ṭ - tack (row) to (spaces)
Ṛ - reverse -> top of the hexagon
ŒḄ - bounce -> whole hexagon
Y - join with newline characters
- implicit, smashing print
```
] |
[Question]
[
## Task
For a given base \$n \ge 3\$, find the smallest positive integer \$m\$, when written in base \$n\$ and rotated right once, equals \$2m\$. The base-\$n\$ representation of \$m\$ cannot have leading zeroes.
The corresponding OEIS sequence is [A087502](http://oeis.org/A087502), and its base-\$n\$ representation is [A158877](http://oeis.org/A158877) (this one stops at \$n=11\$ because the answer for \$n=12\$ has a digit higher than 9). The OEIS page has some information about how to calculate the number:
>
> `a(n)` is the smallest integer of the form `x*(n^d-1)/(2n-1)` for integer `x` and `d`, where `1 < x < n` and `d > 1`. `x` is the last digit and `d` is the number of digits of `a(n)` in base `n`.
>
>
> Maple code:
>
>
>
> ```
> A087502 := proc(n) local d, a; d := 1; a := n; while a>=n do
> d := d+1; a := denom((2^d-1)/(2*n-1)); od;
> return(max(2, a)*(n^d-1)/(2*n-1)); end proc;
>
> ```
>
>
You may output the result as a single integer or a list of base-10 or base-\$n\$ digits.
## Examples and test cases
For \$ n = 3 \$, the answer is \$ m = 32 \$. \$ n = 4 \$ should give \$ m = 18 \$.
$$
m = 32\_{10} = 1012\_3 \rightarrow 2m = 64\_{10} = 2101\_3 \\
m = 18\_{10} = 102\_4 \rightarrow 2m = 36\_{10} = 210\_4
$$
```
n = 3
m = 32
m (base n) = 1012 or [1,0,1,2]
------------------------------
n = 4
m = 18
m (base n) = 102 or [1,0,2]
------------------------------
n = 10
m = 105263157894736842
m (base n) = 105263157894736842 or [1,0,5,2,6,3,1,5,7,8,9,4,7,3,6,8,4,2]
------------------------------
n = 33
m = 237184
m (base n) = 6jqd or [6,19,26,13]
------------------------------
n = 72
m = 340355112965862493
m (base n) = [6,39,19,45,58,65,32,52,26,13]
```
More I/O examples can be found [on OEIS](http://oeis.org/A087502/b087502.txt).
## Scoring and winning criterion
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest solution in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~77~~ ~~76~~ 70 bytes
```
f=lambda n,m=1,i=1:i<m and f(n,m,i*n)or(m+m%n*i)/n-m*2and f(n,m+1)or m
```
[Try it online!](https://tio.run/##TVLfa9swEH73X3FkDGxH2aSTJUthLpSyh7Ctg7VvIQzPVTaxSs4k56H957OLQ0tBiLvvvu90P3R4mv6MEU/vwMchuT47yFM//IXsnx308QGSG44p@zHCow9@Knw4jGkiOI/HNDgG@SkXL96H7KY088pX6MfXzbfN/c@7@@ubLwxKrGu0bCWqqiDlLHh54SIUvK51ddp3j3349dBDZKETzHdi7T@FuaR9SRjzdazGVIZleB9rX32Mq1Dja3gpKAiBGrsZD94RmsYA3z9v7uCam1ZxLLL7Bx1sb8dIXby9JTIQhgEdwa2VRnEGKNA2aAyfbQaK60YiP1MUailUa2zTSm0aUjeE60ZzUkglKY9qBcFakWXatsFWcLQoteJCa24ajkQ3KGZWq88PWk0VSHlWEENIpXRrheRaCCuVULYxaGWLaJRGa4ywnKqjeqTcFcU8S2pPOVUUexpFpA1D6uNvV8pzB9W6APB7oCls4w6uLutdwzDGycejo2gfM2WgcVbkHJKPEy0DFqurBZtRsrcLWNKPSSVxu@6SqyJosVuc/gM "Python 2 – Try It Online")
**Input**: base `n`
**Output**: The smallest integer `m` satisfies the requirement.
*Saved 6 bytes thanks to @Bubbler!*
This is a brute-force search that starts at `m = 1` and works its way up. Will run out of recursion limit if the actual solution is too large.
For each `m`, `i` keeps track of the current power of `n`, which is increased until `i>m`.
[Answer]
# JavaScript (ES7), ~~90 88 86~~ 85 bytes
A recursive port of the Maple function.
```
n=>(d=1,x=n,g=(a=2**++d-1,b=q=n+~-n)=>b?g(b,a%b):(x=q/a)<n?(x+!~-x)*(n**d-1)/q:g())()
```
[Try it online!](https://tio.run/##DctNDoIwEEDhPaeoCSYzLYjoDhi4Ci0/jYZMBYxpQuDqldXbfO@tf3rtltfnm7LrhzBSYKqhpzzxxIkl0PSQUqk@zRNDM7E6UkaqTWPBJPpqsABPc6ax4ga8uhypRwks5XlgNhcWEAHD6BZgQeJZChaVyO9nlUKxRUJ0jlc3DbfJWWg1xBvveNJ4G4Fxb7GM9vAH "JavaScript (Node.js) – Try It Online") (\$a(3)\$ to \$a(9)\$)
Or, for +5 bytes, a BigInt version:
```
n=>(d=1n,x=n,g=(a=2n**++d-1n,b=q=n+~-n)=>b?g(b,a%b):(x=q/a)<n?(~-x?x:2n)*~-(n**d)/q:g())()
```
[Try it online!](https://tio.run/##FYtBDoIwEADvvKIHTXYpFcV4ARa@QkuBaMhWwJgmBL5e8TaZzLz0Vy/t/Hx/FDvbhZ4CUwWWbpx44mQg0JRxHEtp1eEMTcRyV4xUmXoAk@izwRw8TanGkmvYla99njHGu4JjtJhO@QCIgKF3M7AgcedCsChJPK5/khLFGgnROl7c2F1GN0Cj4bTyhkd9Wntg3Bosoi38AA "JavaScript (Node.js) – Try It Online") (\$a(3)\$ to \$a(50)\$)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 11 bytes
```
∞.ΔxsIвÁIβQ
```
-4 thanks to @Grimmy
[Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vXNTKoo9L2w63Oh5blPg///GxgA "05AB1E – Try It Online")
explanation:
```
∞ get all positive numbers
.Δ find the first number for which:
xs the number doubled and itself (e.g. 64, 32)
Iв convert to base input (e.g. [1, 0, 1, 2])
Á rotate right (e.g. [2, 1, 0, 1])
Iβ convert back from base input to a number (e.g. 64)
Q compare to the number doubled (that's in the stack from xs)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
_ѶZsU'é}a1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X9G2WnNVJ%2bl9YTE&input=NA)
```
_ѶZsU'é}a1 :Implicit input of integer U
_ :Function taking an integer Z as an argument
Ñ : Multiply by 2
¶ : Check for equality with
ZsU : Convert Z to a string in base U
'é : Rotate right (string is converted back to decimal afterwards)
} :End function
a1 :Starting with 1, return the first integer that returns true when passed through that function
```
The `'` trick prevents the `é` method from being applied to U (sidenote: there *is* no `é` method for numbers in Japt), instead applying it to the base-U string, and saves 2 bytes over the alternative `ZsU,_éÃ`.
[Answer]
# [Python 2](https://docs.python.org/2/), 78 bytes
Simple direct solution. Increments `x` and `d` until we obtain the appropriate answer.
```
n=input()
j=x=d=2;k=2*n-1
while j%k:j=x*n**d-x;x=[2,x+1][x<n];d+=x<3
print j/k
```
[Try it online!](https://tio.run/##LY2xDoIwFAD39xVdDFAk0tZELXTE1Q8gDkqbADWlaWp8fH3FxPlyd36N4@J4GhZtVJZlyanJ@XfMC5gVKq14YxWnrmLwGaeXIfPOyo1QR6musEHV8z2W7N5j6@6NLhW2AnyYXCTzwaYt@ReZBBLDKg2aIf/tCiAGB@Mj6W7XLoQlyGcwD5sEHIHVwM7ALsBrEAJO/As "Python 2 – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + bc, 103 bytes
```
for((m=1;2*m!=p;));do((m++));t=$(bc<<<"obase=$1;$m");p=$(bc<<<"ibase=$1;${t: -1}${t::-1}");done;echo $m
```
[Try it online!](https://tio.run/##PYwxDoAgEAR7X4GEAiQWqJUHjwGFaIEYsTO8HaGh2MxmijE6HtlRhr7swkOpVwKmwffqBsZgD8VwXt6rCDWblBIHo6NVRADxmMHd/Nn8965oFKlyLcS1c1mw2xEQ8Tl1Ds1lS/4B "Bash – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 30 bytes
```
Fdr2Kt*2QVr2hQI!%J*Nt^QdK/JK.q
```
[Try it online!](https://tio.run/##K6gsyfj/3y2lyMi7RMsoMKzIKCPQU1HVS8uvJC4wxVvfy1uv8P9/QwMuQwsuQ0suIwMuY2MucyMuYy4TAA "Pyth – Try It Online")
Uses a similar approach to my [Python 2 answer](https://codegolf.stackexchange.com/a/203151/65425). **Note:** I also used the upper bound of 2n-2 on `d` that @Bubbler mentioned in a comment.
```
(Q)
```
Implicitly initialize Q to be the input
```
Kt*2Q
```
Initialize K to be 2Q-1
```
Fdr2K
```
For d in range(2, 2Q-1):
```
Vr2hQ
```
- For N in range(2, Q+1):
```
J*Nt^Qd
```
--> Set J to N \* (Q^d - 1)
```
I!%JK/JK.q
```
--> If J%K==0, print J/K and exit the program
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes
```
Nθ≔⊖⊗θηI÷⌊ΦE×θη∨‹ι⊗θ∨‹﹪ιθ²×﹪ιθ⊖Xθ÷ιθ¬﹪ιηη
```
[Try it online!](https://tio.run/##VY7NCsIwEITvPkWOW4gXD156EotQsLUHXyBtg13IT/NXHz8mFrFdWBa@nRlmmJgdNBMx1moOvg2y5xZMUR4uzuFLQcUHyyVXno9Q6dCLdE1RUDIlTWdRebgy56FWvsIFRw4NKpRBwg2FT1kNm@GJkjsw2UTJw8KdOwdIyS7wxxs9BqHz2yR6Srva93zbq9PvXJqSf4mvah1KWu037mmF@ZQxnuNxER8 "Charcoal – Try It Online") Link is to verbose version of code. Uses the OEIS quote plus the additional information provided by @Bubbler in a comment whereby `d < 2n-1`. Explanation:
```
Nθ
```
Input `n`.
```
≔⊖⊗θη
```
Calculate `2n-1`.
```
E×θη
```
Loop `nd + x` from `0` to `n(2n-1)`.
```
∨‹ι⊗θ
```
Ensure `d > 1` by returning `1` if it is not, which is never divisible by `2n-1`.
```
∨‹﹪ιθ²
```
Ensure `x > 1` in the same way.
```
×﹪ιθ⊖Xθ÷ιθ
```
Calculate `x(nᵈ-1)`.
```
Φ...¬﹪ιη
```
Keep only those values that are multiples of `2n-1`.
```
I÷⌊...η
```
Divide the minimum of those values by `2n-1` and output the result.
[Answer]
# Scala, 80 bytes
```
n=>Stream.iterate(1)(n*_)map(p=>p to p*n-1 find(x=>2*x==x%n*p+x/n))find(_!=None)
```
[Try it online!](https://scastie.scala-lang.org/atBLANI8RXiRNPAPZSDIcA)
Takes an integer n, returns an `Option[Option[Int]]` (really a `Some[Some[Int]]`).
] |
[Question]
[
**Introduction**
A popular word puzzle is to convert one word into another via a series of steps which replace only one letter and which always result in a valid word. For example, BAG can be converted to DOG via a path of five steps:
BAG -> BAT -> CAT -> COT -> COG -> DOG
Shorter paths also exist in this case; for example:
BAG -> BOG -> DOG
If one drew a graph whose vertices were labelled by words, with an edge between any pair of words that differ by one letter, then the shortest path from "BAG" to "DOG" would consist of two edges.
**Challenge**
You are to write a program which receives as input a "dictionary" of words which all have the same length, representing all allowable words that can appear as steps along a path. It should output at least one "longest shortest path", that is, a path between two of the words which is:
* no longer than any other path between those two words;
* at least as long as the shortest possible path between any other pair of words in the list.
In the context of the graph described above, the length of such a path is the *diameter* of the graph.
In the degenerate case where none of the input words can be transformed into any of the others, output at least one path of length zero, that is, a single word.
**Examples**
* The input ["bag", "bat", "cat", "cot", "dot", "dog"] should yield a path traversing all six words in that order (or reverse order), since the shortest path from "bag" to "dog" within this dictionary is the longest achievable, five steps.
* The input ["bag", "bat", "bot" , "cat", "cot", "dot", "dog"] should yield the path "bag, bat, bot, dot, dog" and/or its reversal.
* The input ["code","golf","male","buzz","mole","role","mold","cold","gold","mode"] should yield a path between "code and "golf".
* The input ["one", "two", "six", "ten"] corresponds to a graph with no edges, so output one or more single-word (zero-length) paths.
* If the input contains any two words of unequal length, the output is undefined.
**Rules**
* Standard code golf rules apply
* There will be multiple "shortest" paths. You must output at least one, but are free to output as many as you wish.
* You are free to decide how the input dictionary is passed into your program.
* Shortest code in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
ŒPŒ!€ẎnƝ§ỊẠƲƇ.ịⱮḢƙƊṪ
```
[Try it online!](https://tio.run/##y0rNyan8///opICjkxQfNa15uKsv79jcQ8sf7u56uGvBsU3H2vUe7u5@tHHdwx2Ljs081vVw56r/h9u19YFKj056uHPG///R6kmJ6eo6CkCqBEzlg6lkCC8ZwkuBUenqsQA "Jelly – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~84 80 77 76 74 66~~ 61 bytes
```
{⍵⌷⍨{⍵,⍨⊃⍋(1≠a⌷⍨⊃⍵),⍪⍺⌷a}⍣d/⊃⍸a=d←⌈/512|,a←⌊.+⍨⍣≡9*⍨2⌊⍵+.≠⍉⍵}
```
[Try it online!](https://tio.run/##nVC7TsNAEOz5CrpLyIsEUYDEx5x9sbE455BtBARcgSKc5CIo6IE0KA2VBaLkU/ZHzNzZICQjEeFiZnbXO7M2P5Ydcc6l8juu5HEcuAUt7gNFk9vt4oJ0TvNX0s9GtcE0vSI9a/Qpe@DlxHbyJoYr0u/o8ZT0UvRs/40fCDjR/Ka32x9ctrktpt2WWdRLyh73tiAH6MGk1YUt6QwyLTzzql7A5uNlhyZ3uCqOXGByGMRFgqm9LnuKID1E7zOPB5KZI3Qe0eyaqSOWbjSwyxzus01gAnRLVAZFhZj@@TST9ZzqiY76X2490fk1y1ViiIavpAcKuTSVczIem0rZKioJlbBHWPJLCs16mVU5hV/0c8n/Jq/KVSMzTk4VMA7OjB6O1viT9W80Tp8 "APL (Dyalog Classic) – Try It Online")
input and output are character matrices
`⍵+.≠⍉⍵` matrix of hamming-like distances between words
`9*⍨2⌊` leave 0s and 1s intact, turn 2+ into some large number (512=29, used as "∞")
`⌊.+⍨⍣≡` [floyd&warshall](https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm)'s shortest path algorithm
* `⌊.+` like matrix multiplication but using `min` (`⌊`) and `+` instead of `+` and `×` respectively
* `⍨` use the same matrix on the left and right
* `⍣≡` repeat until convergence
`d←⌈/512|,` length of longest (not "∞") path, assigned to `d`
`⊃⍸a=` which two nodes does it connect, let's call them *i* and *j*
`{⍵,⍨⊃⍋(1≠a⌷⍨⊃⍵),⍪⍺⌷a}⍣d/` reconstruct the path
* `{` `}⍣d/` evaluate the `{` `}` function `d` times. the left arg `⍺` is always *i*. the right arg `⍵` starts as *j* and gradually accumulates the internal nodes of the path
* `(1≠a⌷⍨⊃⍵),⍪⍺⌷a` build a 2-column matrix of these two vectors:
+ `1≠a⌷⍨⊃⍵` booleans (0 or 1) indicating which nodes are at distance 1 to the first of `⍵`
+ `⍺⌷a` distances of all graph nodes to `⍺`
* `⊃⍋` index of the lexicographically smallest row
* `⍵,⍨` prepend to `⍵`
`⍵⌷⍨` index the original words with the path
[Answer]
# [Python 3](https://docs.python.org/3/), 225 bytes
```
from itertools import*
def f(a):b=[((p[0],p[-1]),(len(p),p))for i in range(len(a))for p in permutations(a,i+1)if all(sum(q!=r for q,r in zip(*x))<2for x in zip(p,p[1:]))];return max(min(r for q,r in b if x==q)for x,y in b)[1]
```
[Try it online!](https://tio.run/##VY1BTsQwDEX3nMJ0ZZcgUdgN9CRRFimTlEhN4rqp1OHypSnMgtWTnv/351v5yult373kCKE4KTlPC4TIWUr7cHUePFq6DL1GZP1iFOvnzpDCySVkUkzks0CAkEBsGt15sL@Wq2UncS22hJwWtCo8dRQ82GnCZY04P/YCNTsrqenvwNhuRB@vVW53xcdudzFE5l1cWSVBtBvGkPBfe4Dj9db38zm/qdspSXdmZwmpYOtRN4MdGwUHSsXnH/KJ6x1jc6ztPw "Python 3 – Try It Online")
Basically, take all possible paths, only keep the ones that are valid, then go through each start-end combination, find the minimum path distance, and find the maximum of that.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 105 bytes
```
f@x_:=MaximalBy[AdjacencyGraph[x,UnitStep[1-DistanceMatrix@x]]~FindShortestPath~##&@@@Tuples[x,2],Length]
```
[Try it online!](https://tio.run/##NczBCoJAEIDhVwmFTnaoYxBMEXVJEKyTLDGt6@6ErrJOsBL56ptFnb7T/zfIRjXIJDGECvx1vUnRU4P1bii25R2lsnI4OuxM4ZOLJc5ZdcVysaee0UqVIjvy4IUYD2TL3LSOVc/Z9B3jeA4A50dXq36qVyI5KavZiJA5sgwVPKMb6iiZTfAH@aP9Uv7R0SuENw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Python 3, 228 bytes.
```
def G(w):
D={A+B:[A,B]if sum(a!=b for a,b in zip(A,B))<2else[0,0]*len(w)for A in w for B in w}
for k in w:
for i in w:
for j in w:
p=D[i+k]+D[k+j][1:]
if len(p)<len(D[i+j]):D[i+j]=p
return max(D.values(),key=len)
```
Implements the Floyd-Warshall algorithm for all-pairs shortest-paths, then takes the maximum over the found paths.
16 of the characters in this implementation are tabs, which is unfortunate :(
[Answer]
# JavaScript (ES6), ~~195~~ 194 bytes
Returns `[optimal_length, [optimal_path]]`.
```
f=(a,p=[],w=o=[],l=0)=>Object.values(o,o[k=[w,p[0]]]=(o[k]||0)[0]<l?o[k]:[l,p],a.map((v,i)=>w+w&&[...v].map((c,i)=>s-=c!=w[i],s=1)|s||f(a.filter(_=>i--),[...p,v],v,l+1))).sort(([a],[b])=>b-a)[0]
```
[Try it online!](https://tio.run/##lZBBbsMgEEX3PUXrRQTKGDnbqqRH6AEQqjDBlhPsQYbYVeS7u4DdXVWpq6c38P8grmpSXo@dC@WAF7OuDScKHBcSZo4JlleUnz/qq9GBTcrejScIKG5czOBEJaXkJKpclopGfbPvyV6FBSdBsV45QiboYsl8nA8HwRib5DbWeexLrl/4LDoJnp/o4pelIYo1nQ1mJJ/83JUlhZRzMEmYwB5PlFLmcQyECCVB1DL21KVKD1g1Dh6tYRZb0hBR1Kot4DkiJOgdmHH5QVtISp/@jtb4/wYdfzWdt2ibxF7Z7PX98ciOm487o1@29o3tzj71/LYAh5wLMyb47iubGdLl9Rs "JavaScript (Node.js) – Try It Online")
### How?
We use a recursive function \$f\$ which builds an object \$o\$ whose keys consist of a pair of words \$w\_0\$ and \$w\_1\$ separated by a comma and whose values are defined as \$[l, p]\$, where \$p\$ is the shortest path between \$w\_0\$ and \$w\_1\$ and \$l\$ is the length of this path.
Given a path \$p\$ of length \$l\$ and the last word \$w\$ added to \$p\$, \$o\$ is updated with:
```
o[k = [w, p[0]]] = (o[k] || 0)[0] < l ? o[k] : [l, p]
```
We eventually return the longest path stored in \$o\$:
```
Object.values(o).sort(([a], [b]) => b - a)[0]
```
(this code is executed at each recursion depth, but only the root level really matters)
We use the following test to know whether a word \$v\$ differs by exactly one letter with the last word \$w\$:
```
[...v].map((c, i) => s -= c != w[i], s = 1) | s
```
For each word \$v\$ that can be added to the path, we process a recursive call as follows:
```
f( //
a.filter(_ => i--), // remove the i-th word from a[]
[...p, v], // append v to p[]
v, // pass v as the last word
l + 1 // increment the length of the path
) //
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 92 bytes
```
MaximalBy[Select[Rule@@@a,EditDistance@@#<2&]~FindShortestPath~##&@@@(a=#~Tuples~2),Length]&
```
[Try it online!](https://tio.run/##hc/BSsQwEAbg@z7FkkBRiAh7diWIelJYXG@lhzSZpoE0kXaK6y7tq8dJqycPnj7@ZOaH6RS20Cl0WqVmn17VyXXKP3yVR/CgsXwbPUgplXgyDh/dgCpoeuB3u6Kan10wxzb2CAMeqGjmvKDhK7Xn8/v44WGYd9fiBYLFtirSoXcBS35z30heFbfysrmwWlkmtgRm9A9xwfxi2ST@zNb0u/13R0cDTDAbfUPQaTnV4/mcU1xSv0LJEHrFrnR5fSmKAXIxfsbM4E5LgsCmzZTSNw "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
*Inspired by [this post](https://puzzling.stackexchange.com/q/69117) over on Puzzling. Spoilers for that puzzle are below.*
Given three positive integers as input, `(x, y, z)`, construct the inclusive range `[x, y]`, concatenate that range together, then remove `z` not-necessarily-consecutive digits to produce the largest and smallest positive integers possible. Leading zeros are not permitted (i.e., the numbers must start with `[1-9]`). Output those two numbers in either order.
For the example from the Puzzling post, for input `(1, 100, 100)`, the largest number possible is `99999785960616263646566676869707172737475767778798081828384858687888990919293949596979899100`,
and the smallest number is `10000012340616263646566676869707172737475767778798081828384858687888990919293949596979899100`,
following the below logic from [jafe's](https://puzzling.stackexchange.com/users/41973/jafe) answer posted there:
* We can't influence the number's length (there's a fixed number of digits), so to maximize the value we take the maximal first digit, then second digit etc.
* Remove the 84 first non-nines (16 digits left to remove):
`999995051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100`
* The largest number within the next 17 digits is 7, so from here, the next digit in the answer can be at most 7 (we can't remove more than 16 digits). So remove 15 non-7's... (1 digit left to remove): `999997585960616263646566676869707172737475767778798081828384858687888990919293949596979899100`
* From here, the next digit can be at most 8 so remove one non-8 from the middle: `99999785960616263646566676869707172737475767778798081828384858687888990919293949596979899100`
* Similar logic, but reversed (i.e., we want leading `1`s instead of leading `9`s) for the smallest number.
Here's a smaller example: `(1, 10, 5)`.
We construct the range `12345678910` and determine which `5` digits we can remove leaving the largest possible number. Obviously, that means we want to maximize the leading digit, since we can't influence the length of the output. So, if we remove `12345`, we're left with `678910`, and that's the largest we can make. Making the smallest is a little bit trickier, since we can pluck out numbers from the middle instead, leaving `123410` as the smallest possible.
For `(20, 25, 11)`, the result is rather boring, as `5` and `1`.
Finally, to rule out answers that try leading zeros, `(9, 11, 3)` gives `91011` which in turn yields `91` and `10` as the largest and smallest.
## I/O and Rules
* If it's easier/shorter, you can code two programs/functions -- one for the largest and one for the smallest -- in which case your score is the sum of both parts.
* The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* The input can be assumed to fit in your language's native number type, ***however***, neither the concatenated number nor the output can be assumed to do so.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* [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]
# [Haskell](https://www.haskell.org/), 162 bytes
```
l=length
((m,f)%n)s|n>=l s=[]|n>0,(p,c:r)<-span(/=m(f$take(n+1)s))s=c:((m,id)%(n-l p)$r)|1>0=s
(x#y)z=[p%z$show=<<[x..y]|p<-[(maximum,id),(minimum,filter(>'0'))]]
```
[Try it online!](https://tio.run/##tU7RjoIwEHz3KwzW2ObQawvtbg31RwgPRFGJUAnlcmr8d67wdMk93ySb7GRmd@Za@lvVNOPY2KZyl@G6oLSNz2ztmH@7g22W3uZF2HhMu/i471m29V3p6Kdt6ZkM5a2i7kMwz5i3x/10XJ/Ymrpts@wY6dlbHLj1C/pYPdnL5t36Rfz1/m2zLH/sds/i3WXbnLblo26/5tuYtrWbybluhqqnhw3fMFYUY1vWzp7ui2VA19duIFTylVRECGZtHqkojkRU/NbFSnCiZlUDGsEni0zSsPzxcRJmtpoJgMporoWWOtGpVlpr0KgNcBAgIYEUFGgAQDDIUaDEBFNUqBEQ0RhuhJEmMakJj0wwmZAfCsy5E6JAA6Y@/5BTjD8 "Haskell – Try It Online")
Uses the algorithm described by jafe. Might be shorter to use a less efficient method, but this was more fun to write :)
The `%` operation takes 4 arguments (actually 3, but whatever): `m` which is a function that selects the "optimal" member from a list (either `maximum` or `minimum` depending on what we want); `f` which is a "filter" function; `n` the number of digits left to drop; and `s` the string. First we check whether n is equal to the number of digits left in the string (I used `>=` for safety) and drop the rest of `s` if so. Otherwise we check if we still need to drop digits (`n>0`), then we use `span` to break our string into three pieces: `p` the digits to drop, `c` the optimal reachable digit, and `r` the remaining string. We do this by passing span a predicate that checks for equality against our optimal digit. To find that digit we take the first `n+1` digits of the string, filter it, then pass it to our "chooser" function. Now we just yield our optimal digit and recur, subtracting the length of `p` (the number of digits dropped) from `n`. Notice that we do not pass our filtering function to the recursive call, and, instead, we replace it with `id`. That's because the filter is only there to avoid selecting leading 0s in the `minimum` case which is only relevant on the first iteration. After that we no longer need any filter.
`%` is really only a helper function for `#` which is our "real" function, taking `x`, `y`, and `z`. We use a list comprehension just to avoid a bit of repetition, iterating over our function tuples and passing them to `%` along with `z` and the concatenated string. That string is created using the magic monad operator `(=<<)` which, in this context, works like `concatMap`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
r/VDœcL_¥¥ḷ/ƇVṢ.ị
```
[Try it online!](https://tio.run/##ASsA1P9qZWxsef//ci9WRMWTY0xfwqXCpeG4ty/Gh1bhuaIu4buL////OSwxMf8z "Jelly – Try It Online")
Calculates all possibilities then keeps the largest and smallest.
Left argument: `x,y` to construct the range.
Right argument: `z` digits to be removed.
```
r/VDœcL_¥¥ḷ/ƇVṢ.ị
r/ Inclusive range from x to y
V Concatenate the digits together
D Get the resulting digits
¥ Dyad:
¥ Dyad:
L Length of the list of digits in the concatenated number.
_ Subtract the number of digits to be removed.
œc Combinations without replacement. (remove z digits)
Ƈ Keep lists of digits that:
ḷ/ have a positive first element (no leading zeros).
V Combine digits into integers. (vectorizes to ldepth 1)
Ṣ Sort the numbers
.ị Indexes at value 0.5 which yields the first and last elements.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 143 bytes
```
import itertools
s,e,r=input()
l=''.join(map(str,range(s,e+1)))
L=[i for i in itertools.combinations(l,len(l)-r)if'0'<i[0]]
print min(L),max(L)
```
[Try it online!](https://tio.run/##RcwxDsIwDEDRPafIlliEqkViozfoDaoOAQUwSuzIMRKcPnRj@svXq199Mp16x1JZ1KImUebcTAspyIxU3@rB5Nm54cVIvsTqm0qQSI/k9@swAYBZ5hXtncWiRfozw43LFSkqMjWfQ07kMxwF8O5Gd8F13DZTBUlt2fEFQomfPb37KdhpDPYMPw "Python 2 – Try It Online")
This works by calculating all combinations of the target size (the element order is preserved) and getting the smallest / biggest numbers from it
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes or 21 + ~~46~~ 35 = ~~67~~ 56 bytes
```
≔⪫…·NNωθFN≔⌈EθΦθ⁻λνθθ
```
[Try it online!](https://tio.run/##VYzNCsIwEITvfYocdyFCe/bkRVCoiG8QQ6wLyabNT/Xt4wq99DDMfMww9m2Sjca3dsqZJoZrJIYLW18zre5heHKCcy23Gp4uAWq1Q@GPaMFj94pJ7beottfRfCnUID7DotWZfJFe0khcM3itGBG3n3siLiCptaEb@v6vdlj9Dw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪫…·NNωθ
```
Input `x` and `y`, create an inclusive range and join the numbers into a string.
```
FN
```
Loop once for each digit to be removed.
```
≔⌈EθΦθ⁻λνθ
```
Create a list of strings formed by removing each possible character from the current string and take the maximum.
```
θ
```
Print the result.
```
≔⪫…·NNωθF⊕N⊞υωΦθ∧⁼ι⌊Φ✂θκLυ¹∨κIλ⊞Oυω
```
[Try it online!](https://tio.run/##VU7LCsJADLz3K/aYhQr23JOIguIL/YK1jW1wm7b70M9fs4gHA3OYzEwmTW9cMxqb0sp76hj2IzHsuLHR0wuvhjsUOsVwisMdHehS/VHhb8Gs6@IxOpWjDgfkgO1/TqtL9D3E7K@LiyMOsCUbRJtLteIWNnM01gOV6khMQxx@@s1Sg9n1LNUBuQtyRjorwdmBLNfGB7Ba529yy3lCZ8Lovm0ydUpVUS2XGWnxsh8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪫…·NNωθ
```
Input `x` and `y`, create an inclusive range and join the numbers into a string.
```
F⊕N⊞υω
```
Input `z` and increment it. I then create a list of that length: I need to be able to increment `z` inside the following filter, but only commands are allowed to increment variables; there is a loophole in that `PushOperator` increments the length of the list.
```
θ String of digits
Φ Filter over characters
κ Current index
Lυ Length of list i.e. current `z` value
¹ Literal 1
✂θ Slice string of digits
Φ Filter over characters
κ Outer index
Iλ Cast inner character to number
∨ Logical OR
⌊ Minimum
⁼ι Equals the outer character
∧ ⊞Oυω And also push to list i.e. increment `z`
Implicitly print
```
Filter on the characters that are wanted by checking that there are no lower characters in the sliceable region. The region starts with the first `z+1` characters (since it's possible to slice the first `z` away if necessary) and the end point increments for each character that is kept. Care is taken not to choose a zero for the first character.
The faster algorithm is 30 bytes when used to compute the largest possible number:
```
≔⪫…·NNωθF⊕N⊞υωΦθ∧⁼ι⌈✂θκLυ¹⊞Oυω
```
[Try it online!](https://tio.run/##VY3NDsIgEITvfQqOkGDSnnvqQRONP40@AdK1JcLS8lN9e4R46iZzmMx@M3ISTlqhU@q8VyPSk1VIjyh19GqFu8ARsp1juEbzBEcZJxub/SdrYW31so4U1IEBDDBsOUb66Ccay39b9U5hoAelQ84WTjoc6H6JQnuqOLmIrzLR0IdWEkr85uQMOIbM57GGldlSd5vBiWDdvzZfm1JTNXVdlHar/gE "Charcoal – Try It Online") Link is to verbose version of code. Edit: I've since been able to combine the above two into a second 56 byte solution which generates both results:
```
≔⪫…·NNωθF⊕N⊞υω≔⮌υη⟦Φθ∧⁼ι⌈✂θκLυ¹⊞OυωΦθ∧⁼ι⌊Φ✂θκLη¹∨κIλ⊞Oηω
```
[Try it online!](https://tio.run/##dY4xb8IwEIX3/AqPZ8mVyJwJoVZqRQuiI2JwwzW26lzI2Q78e2MHFtR2uOG9u/e9a43mdtAupaX3tiN4GyzBK7UuejvhTlOHWZ5i@Ij9FzJIJR5k1uc8o2yq74FFiTL2SAGPjzkpttEbiOW@qe5tO5yQPULMCJPtLVsKsH@xLuTMqMSSjvA8Ru08WCXe9cX2sYdPZ1ss6x8l1khdMDOhluWdUrM5Iesw8K2uuP8iLc3I@/4PspnJSmwYsrnSPoCTv5vMrekgm5Tqql4syqSnyV0B "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪫…·NNωθ
```
Generate the initial string.
```
F⊕N⊞υω
```
Represent `z+1` as the length of the list.
```
≔⮌υη
```
Reverse the list thus cloning it and save the result.
```
⟦
```
Print the two results on separate lines. (Another way of doing this is to separate the results with a literal `\r` character.)
```
Φθ∧⁼ι⌈✂θκLυ¹⊞Oυω
```
Generate the largest possible number.
```
Φθ∧⁼ι⌊Φ✂θκLη¹∨κIλ⊞Oηω
```
Generate the smallest possible number using the cloned list to keep track of `z`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
rDẎœcL_⁵Ɗ$ị@Ƈ1ḌṢ.ị
```
**[Try it online!](https://tio.run/##y0rNyan8/7/I5eGuvqOTk33iHzVuPdal8nB3t8OxdsOHO3oe7lykB@T9///fyOC/kel/Q0MA "Jelly – Try It Online")**
Very inefficient, definately no point going for `1, 100, 100` as \$\binom{192}{92}=305812874887035355118559193163641366325011573739619723360\$
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŸSDg³-.Æʒ¬Ā}{Ć`‚
```
[Try it online!](https://tio.run/##ASkA1v9vc2FiaWX//8W4U0RnwrMtLsOGypLCrMSAfXvEhmDigJr//zEwCjEKNQ "05AB1E – Try It Online")
Full program, reading inputs in this order: **y, x, z**. Outputs a list of two lists of characters.
### Explanation
```
ŸSDg³-.Æʒ¬Ā}{Ć`‚ Full program. Inputs: y, x, z.
Ÿ Inclusive binary range from x to y. Push [x ... y].
S Dump the digits separately in a list.
Dg Duplicate, and use the second copy to get its length.
³- Subtract z from the length.
.Æ Retrieve all combinations of length - z elements from the digits.
ʒ } Keep only those that...
¬Ā Don't start with a 0 (head, then Python-style boolean).
{ Sort the remaining elements.
Ć Enclose. Pushes list + list[0] (appends its tail to itself)
` Dump all elements separately on the stack.
, Pair, to get the last two, min and max (after enclosing)
```
[Answer]
## Matlab, 95 bytes
```
function[m]=f(s,e,c),a=sprintf('%d',s:e);x=str2num(combnk(a,length(a)-c));m=[min(x),max(x)];end
```
[Try it Online!](https://tio.run/##DcXBCsIwDADQX9lFlkCETfBi6ZeMHWLXatGksmbSv6@@yyvB@Bt7T4cGy0UXWX2CSpECEvv62bNagvG0jVRvEV3z1faLHgKhyF1fwPSO@rAnMJ4DohO/SFZoSMLt3@qibj3BTMM80XDF/gM)
Returns an 1x2 matrix with min and max.
**How it works**
```
% Full code
function[m]=f(s,e,c),a=sprintf('%d',s:e);x=str2num(combnk(a,length(a)-c));m=[min(x),max(x)];end
% The function
function[m]=f(s,e,c), end
% Creates the range in a single string
a=sprintf('%d',s:e);
% Gets all the combinations
combnk(a,length(a)-c)
% Converts the string combinations to integers
x=str2num( );
% Finds min and max
m=[min(x),max(x)];
```
] |
[Question]
[
There is currently a meme on the internet that consist of taking a sentence, reverse the meaning and adding `n't` at the end. For example, `I am small` becomes `I am talln't`
## Challenge
For the sake of the challenge, we'll simplify this : Your task will be to detect whenever there is a negation in a sentence, and replace it with the 'positive' one with `n't` added at the end. There will be some tricky parts that will be explained in the rules.
## Rules
* You have to take a *String* as *input*, and return a *String* as *output*.
* Input will be a sentence **in lowercase**, with only `.` and `,` as punctuation marks.
* You have to replace any `no <any_word>` or `not <any_word>` with `<any_word>n't`.
* `no`/`not` have to be a word and **not** a substring : you don't have to change anything in `none of those`
* If the word already finish with a `n`, you have to replace `n't` with `'t` : `no plan` become `plan't` and **not** `plann't`
* When `no` or `not` isn't followed by any word, a punctuation mark or another `no`/`not`, you have to replace it with **`yesn't`**.
* compound words count as one word. so even if `no-op` contain the substring `no`, it doesn't contain the **word** no. So the result will be `no-op` and **not** `-opn't`.
* You do not have to worry about grammar errors. For example, `there is no way` will result to `there is wayn't`.
* No standard loopholes allowed.
* This is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'"), so the shortest code wins.
There are some examples, even if this challenge looks clearn't for now.
## Examples
>
> **Input :** i love codegolfing, but i do not like short programs.
> does this sentence makes sense ... of course no.
>
> **Output :** i love codegolfing, but i do liken't short programs.
> does this sentence makes sense ... of course yesn't.
>
>
> **Input** : you are not invited. get out.
>
> **Output** : you are invitedn't. get out.
>
>
> **Input** : i am not ok, i have no plan and i have no gunn
>
> **Output** : i am okn't, i have plan't and i have gunn't
>
>
> **Input** : oh no no no i refuse.
>
> **Output** : oh yesn't yesn't in't refuse.
>
>
> **Input** : oh no no no, i refuse.
>
> **Output** : oh yesn't yesn't yesn't, i refuse.
>
>
> **Input** : i cannot believe this, you can't codegolf.
>
> **Output** : i cannot believe this, you can't codegolf.
>
>
> **Input** : oh no ... he did it again.
>
> **Output** : oh yesn't ... he did it again.
>
>
> **Input** : nn't is not a word, kevin. so this is not nn't.
>
> **Output** : nn't is an't word, kevin. so this is nn'tn't.
>
>
> **Input** : is it not clearn't for everyone
>
> **Output** : is this clearn'tn't for everyone
>
>
> **Input** : this is non't sense ...
>
> **Output** : this is non't sense ...
>
>
>
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~86~~ ~~70~~ 65 bytes
```
T`-'`L
\bnot?\s+(?!not?\b)(\w+?)n?\b
$1n't
\bnot?\b
yesn't
T`L`-'
```
-16 bytes thanks to *@Neil*.
-5 bytes thanks to *@ovs*.
[Try it online.](https://tio.run/##XVFBisMwDLz7FVpYaJcmgb6gH@ixxx7qJEpi4krBdlLy@qzkbnfLgsHSSDMa2QGTI3vctsut3N3O5loTp9M1HvanjxzVX/vr43D6IgnN55F26dVTmxWj5pfbWcjbRgwxWWptaMEzTwN7jGC95we2lXECLggNt9iz7xz1BdRzAgctgyiCdyNCHDgkmAL3wd5jJTXRSIOLEJESUoNwtyPmNCJUVQXciegcJCOuzMoz2IBZ0dHiksyGHhPwnNSEvecSj4VMHuyinTB5SyDW36B@JgLDg8bP4yBgN0es3tHiDXbQWFLxGr1DkVHfBagjKezS7@4vBXU/ILROBiewvXVUGdI3zRvLIVaelbvkKZeeqGIPDm0BIy7Cgsjwx0mgnWIoqq7mjUcblN1xALEWVib8N@X5onmSOjO6n3rJe5L5sSCJfnwpwd2uNZaRvwE)
**Explanation:**
```
T`-'`L # Replace all "-" with "A" and all "'" with "B" to store them
\bnot? # Then replace the word "no" or "not",
\s+ # followed by 1 or more whitespaces,
(?!not?\b)(\w+?) # followed by a word/letter that is not "not" or "no"
n?\b # minus a single trailing "n" if there are any
$1 # with: the word/letter
n't # appended with "n't"
\bnot?\b # Then replace any remaining loose "no" or "not"
yesn't # with "yesn't"
T`L`-' # And finally replace all "A" with "-" and all "B" with "'" again
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~208~~ ~~123~~ ~~113~~ 146 bytes
```
lambda s:re.sub(r"\bnot?\b(?!['-])(\s(?!not?(\b)(?!['-]))([\w'-]+))?",lambda m:(m.group(3)or"yes")+"n't"[(m.group(3)or'')[-1:]=='n':],s)
import re
```
[Try it online!](https://tio.run/##fVFNb8IwDL3vV3i5pBEl0rYbEuJP7NZySKnbRrR2laQgfj1LCkNU@5AiJbbfe352xkvomN6vzba89maoagN@41D7qcqcKCvisCurbPdayPVeZaWPz5TLykp9Z1VWlOf4WCm1E/ldZdhkg24dT2P2odiJC3qhVoJkEMWiIqUq1m@b/XYrSW72uVcvdhjZBXB4HZ2lAE0mLfR8QjhwjS33jaU2h2oKYKFmiIagt0cE3yXe6Lh1ZvA61tBD6KwHjxSQDgiDOeIcegStNXATRScXI2It1cuj44UnMA5ncUsnG7DW0GIAnsICaMEMM4qPefTTmVMiwdgbAkP1U6qdiJ6Z3KXs7dg4bjN51H8A8l8RwsLBUGpeYW8xtknT5pDMx4IMj41p8cS66abxO4TaRo8BTGssLVCfaXHxECchE@81j/8DfmAksVxEC/eUeLNAop/Z1Tkc8RR9gOfbx92rCbkwl0phLh16NC4JNewgrsBdmPAZGhY2H18v1PUL "Python 2 – Try It Online")
Lost a bunch of bytes because of words ending in `n't` or `n`. Either or is shorter, but handling both was longer.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 95 bytes
```
s=>s.replace(/\bnot?\b( (?!not?\b)(['\w-]*(\w)))?/g,(a,b,s,t)=>(s||'yes')+(t=='n'?'':'n')+"'t")
```
[Try it online!](https://tio.run/##pVTBbuIwEL3zFbO9xKaue@8q5VZpT/sBpVKdZEi8BBvZDgip/86OHbKQUCSkRVEcM2/e8zyP/UftlC@d3oYnYys8vuVHn7966XDbqhLZ87IwNiyWBQO2@NF/cvaeLfdPH3O23HPOF8@1YEoUwovA81fmv76yA/qMP7KQ55nJFln2QgN/fMjCAz/@nH3OZkC/X2bbBXgBDa3dIZSkX9t2pU0toKCIhsoCSUKr1wi@sS7A1tnaqY2XFEMPodEePJqApkTYqDWmqUeQUoJdEWnnaGasTJK/u3CHZtQzWfg/SbKAOOS41IPtQDlMVWmz0wErCTUGsF2YrHCAnmCR64yc@Kc2idGuBU0atYsCQBtoQJnq4q@6M2bqA@XaNbH/S415VPxFZkzLwljUNpGwfzQ4XHUeJxUQpDdhGHR8DdBbbOJuun64xE9sKZWJthTYaqQy4s6J5GuZKhw2/6o17s77pobYBA1Cpck9MrFW2tys41vsiNMk23zaXQV76yoBa9wRDrztW/EUNanZRkJDclr0zVwKXvdpjIXEW7aoXCRYWQfkhjtYgxPDTodigF6hR9TnRacjNpycMeUt0Of5Yhr4mJzzpZHz/ovuImBe0HVEV1FpjbctytbW7F3RARfwxhTv33lefHB@/As "JavaScript (Node.js) – Try It Online")
Thank Rick Hitchcock for 2 bytes
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~75~~ ~~73~~ 50 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ä§▀t9lJ₧5M#|+4╖¼├n▌ ·=┌«∙£╣▀K╖¥y▐▲·(■◄╙→á╣ó•ô╓╢Θ₧○
```
[Run and debug it](https://staxlang.xyz/#p=8415df74396c4a9e354d237c2b34b7acc36edd20fa3ddaaef99cb9df4bb79d79de1efa28fe11d31aa0b9a20793d6b6e99e09&i=oh+no+...+he+did+it+again.%0Ai+love+codegolfing,+but+i+do+not+like+short+programs.+does+this+sentence+makes+sense+...+of+course+no.%0Ayou+are+not+invited.+get+out.%0Ai+am+not+ok,+i+have+no+plan+and+i+have+no+gunn%0Aoh+no+no+no+i+refuse.%0Aoh+no+no+no,+i+refuse.%0Ai+cannot+believe+this,+you+can%27t+codegolf.%0Aoh+no+...+he+did+it+again.%0Ann%27t+is+not+a+word,+kevin.+so+this+is+not+nn%27t.%0Ais+it+not+clearn%27t+for+everyone%0Athis+is+non%27t+sense+...%0Ayes-no+maybe-so%0Aop-no+no-op%0Atrailing+space+no+%0Ano+non&a=1&m=2)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 72 bytes
```
F=_r"%bnot?%s+(?!not?%b)(%w+?)n?%b|%bnot?%b(?!['-])",@Y=Y||"yes"Y+"n't"}
```
[Try it online!](https://tio.run/##dU/BaoQwEL33K6ahokGbHyiLPe21ZymlRB11dt2MJLFlwX67TUSWHrYwhzfzHm/eO@nJr@vx8GlFUhv2ZeLyrHzcUC2z5DsvpQlw2dk6kO/p84cUxWt1qJZFXNGJKhcm9eJnfXpTU3bMBMHIXwgNt9jz2JHpC6hnDwQtQzCCkc4IbmDrYbLcW31xKnDowA/kwKHxaBqEiz7jtjoEpRRwF0xnGzbDSkj58rB/5CFc9iGw2M0O/xMU9xUEjTYxXI0jYYgfoxRw5TkSqb/VueMbsw0ILbVAHnSvyfwVbaXCGI4@tzpRsv4C "Japt – Try It Online")
[Answer]
# Java 8, ~~163~~ 136 bytes
```
s->s.replaceAll("(^|[ ,.])not?(?= *([,.]|$|not?(?=$|[ ,.])))","$1yesn't").replaceAll("(^|[ ,.])not? ([\\w'-]+?)n?(?=$|[ ,.])","$1$2n't")
```
-27 bytes by creating a port of [*@recursive*'s Stax' answer](https://codegolf.stackexchange.com/a/165773/52210).
[Try it online.](https://tio.run/##pVVRb9owEH7frzhZSE1KiLQ9turQfsD60kdgkkmO4GJ8me3QodHfzs5O0tJAu0mTAol9332@@@5sP8qdnFCN5rHcHAstnYPvUpnfnwCU8WhXskC4D0OAB2@VqaBIug@X3vL8M//4cV56VcA9GLiDo5t8dbnFWrP7N60Tkfw4zCDLF6khP02md3CdzHh4GB26iVFnT1ORidHnPTpz5UX6Pgkks/n86WqyGE9Tc8oQ/Udfovvxto2ubpaao@uC3JEqYctpdpnMFiDTNkePzifCUICaUtoSNFG9Jo0OpNb0hGUuMhC9mVe5hIjK9GyKETuEgkqsSK94wQyWjQcFJQGnAlptENyarIfaUmXl1uVsY0K/Vg4cciUM12ErNxiHDiHPc6AVkzaWR4ZiVB@uFFYJ4f7XQm1dBgnuqQFpMeaizE55lgAq9ECNj3H1gM4YGF7tA63kNvLQJuOw13IXaIF7wAArfjJVNca0ObMHbZjzxSGgOdETfACHfjhditaBpn0UWFw1DmO0bGjT7F8q/PWA9ziyv5C0r1PUIPFCmpD4ErVCDjlUJIOgXBGz6YvaFfqf0RfiDSVdI5S8CxTLVPFOGMR8EfGGKerJPue6xlbix1AsAr/5gAnQy4Yz1hYSAE9kyww2uOPVwRG8EngwsQ27AMJkTPtdDzae922w@chWaJQ2EKzIAutp92QwCh0hvfkM8UHi7e6JOQY5zwUYAt4KQXCq8JnIseVi/0eyobFT/JLC7Hi5blz6CVu3cr/EiaO4bwdT3YH/etzHkzS6d3dC@M76mwJ/1Vjwfk/f3B8WXaM93xImL5KA76J42DuP2zycCTUDvTbRCmMQc5OIcdI65vizkdolL@RT4ZqiQCyxFDdiJZXG8gbEuIWnY5HOTR/58/EP)
] |
[Question]
[
# My wires are all tangled!
Isn't it annoying when wires get all tangled up? Well, that just happened to me, so I'd like to to help me untangle them! For your convenience, I've disconnected them all from the device, but they're all still connected to the outlet. Your challenge is to figure out how to untangle them!
# Input
The input will consist of spaces, pipes, and Xs (both cases). The input will look something like this:
```
| | | |
X | |
| | x
| X |
| | | |
```
A capital X means that the left wire crosses over the right wire, and a lowercase x means the opposite. The first and last lines will always be `| | | |...`. You may take the input as a comma separated string, an array of strings, etc. The format is not strict, as long as it makes sense and doesn't contain any extra information.
# Output
For this challenge, not only do I need to know how long I will take, I need to know exactly what to do. So, output a list of integer pairs with the character R or L, case insensitive, representing which two wires to untangle and which way (R means right over left, and vice versa for L). You need to tell me which way to uncross them; I can't figure that out myself. Output is pretty flexible too, as long as you output all of the integer pairs + character in the correct order and you don't output any extra nonsense text (brackets, commas, etc. are fine). The wires can be zero or one indexed, but the index must start from the left. Note that you must untangle from the bottom, not the top. Output style must be consistent, and please specify how you are outputting if it is not obvious. The case of the character doesn't have be consistent, if that helps at all.
# Sample Output
For the example input above, the output would be something like:
```
2 3 R
3 4 L
1 2 R
```
The output format here is a newline separated list of space separated values. This is 1-indexed.
# Further specifications
It is valid to have X and x stacked vertically over each other in either order. Since I'm lazy, I don't want to switch wires around unnecessarily, so don't output anything for these cases; if I find that, I'll just pull the wires gently to get them straight.
It is also valid to have multiple X and x stacked vertically, and as long as neither wire is involved in other crossings, I don't want any extra moves (because I'm lazy). Thus, if the characters `X X x X x x` show up in a column without any other crossings, the output should still be blank!
In case this isn't clear, R eliminates X and L eliminates x.
There could be two wire crossings in the same row, in which case the order of these two swaps does not matter. You will never get something like `| X X |` (this does not make sense because it implies that the middle wire is being crossed over the wires on both its left and its right).
There aren't always crossings...
The input could be a single pipe. However, the input will never be blank.
Shortest valid solution wins on December 20th!
# More Examples
As I promised:
### Example 1
**Input**
```
| | | | | |
| | X x
X | x |
| x | X
X X | |
| | | | | |
```
**Output**
```
1 2 R
3 4 R
2 3 L
5 6 R
1 2 R
4 5 L
3 4 R
5 6 L
```
### Example 2
**Input**
```
| | |
X |
| x
| | |
| X
| x
| | |
```
**Output**
```
2 3 L
1 2 R
```
### Example 3
**Input**
```
|
```
**Output** is blank. Yes, you have to deal with this case.
### Example 4
**Input**
```
| |
X
x
X
x
X
x
X
x
X
x
| |
```
**Output** is blank. Just for fun :).
### Example 5
**Input**
```
| |
X
X
x
X
x
x
| |
```
**Output** is still blank...
[Answer]
# Pyth - ~~26~~ 25 bytes
Very straightforward, maybe I can golf the filtering.
```
fhhT_m+hB/xrdZ\x2@"RL"}\x
```
[Try it online here](http://pyth.herokuapp.com/?code=fhhT_m%2BhB%2FxrdZ%5Cx2%40%22RL%22%7D%5Cx&input=%5B%27%7C+%7C+%7C+%7C%27%2C+%27+X++%7C+%7C%27%2C+%27%7C+%7C++x+%27%2C+%27%7C++X++%7C%27%2C+%27%7C+%7C+%7C+%7C%27%5D&debug=0).
[Answer]
## JavaScript (ES6), 178 bytes
```
f=([t,...a],r=[])=>a[0]?t.replace(/x/gi,(c,i)=>(c=c<'x'?'R':'L',i=++i/2,r.reduce((f,[j,,d],n)=>f||i<j+2&&j<i+2&&(j-i|c==d||r.splice(n,1)&&2),0)<2?r=[[i,i+1,c],...r]:r))&&f(a,r):r
```
Takes input as an array of strings representing lines and returns an array of arrays of values e.g. `[[2, 3, "R"], [3, 4, "L"], [1, 2, "R"]]`. The reverse ordering helps with the eliminations.
[Answer]
## Python 2, ~~244~~ 241 bytes
```
m=[]
for l in input():
for i in range(len(l)):
c=l[i];a=i/2+1;L,R=[a,a+1,'LR'[c>'v']],[a,a+1,'RL'[c>'v']];x=m.index(L)if L in m else-1;M=zip(*m[:x+1])
if c in'xX':
if x>=0and(a in M[1]or a+1in M[0])<1:del m[x]
else:m=[R]+m
print m
```
Takes input as list of strings
**Example:**
Input: `['| | | |', ' X | |', '| | x ', '| X |', ' x | |']`
Output: `[[1, 2, 'L'], [2, 3, 'R'], [3, 4, 'L'], [1, 2, 'R']]`
Edit:
Fixed for case:
Input: `['| | |', ' X |', ' X |', ' x |', '| X', ' X |', ' x |', ' x |', '| | |']`
Output: `[[1, 2, 'L'], [2, 3, 'R'], [1, 2, 'R']]`
[Answer]
# Befunge, 173 bytes
Input is read from stdin in the exact format given in the challenge description, although it's crucial that every line be the correct length and the final line must include a newline (i.e. not just EOF at the end of that line).
```
$1>>05p~$~:55+-#v_
$_^#`"N":+1g50$<>:2+3%1-05g6g+0v>!#:v#
vg50-1*2p51:-1_^#:<*2!!-*84p6g5<
+#,.#$"R"\#\-#+5<^g51$_:0`6*\25g\v@_:#!.#:1#,
>+::25p6g\48*\6p48 *-:!^!:--1*2`0:<
```
[Try it online!](http://befunge.tryitonline.net/#code=JDE-PjA1cH4kfjo1NSstI3ZfCiRfXiNgIk4iOisxZzUwJDw-OjIrMyUxLTA1ZzZnKzB2PiEjOnYjCnZnNTAtMSoycDUxOi0xX14jOjwqMiEhLSo4NHA2ZzU8CiArIywuIyQiUiJcI1wtIys1PF5nNTEkXzowYDYqXDI1Z1x2QF86IyEuIzoxIywKPis6OjI1cDZnXDQ4Klw2cDQ4ICotOiFeITotLTEqMmAwOjw&input=fCB8IHwKIFggIHwKfCAgeCAKfCB8IHwKfCAgWCAKfCAgeCAKfCB8IHwK)
The basic idea for this solution is that we have an "array" keeping track of the twist counts for each wire. So every time we encounter a twist in one direction we increment the count for the associated wire, while a twist in the other direction will decrement the count.
At the same time as we process the twist for a particular wire, we also look at the twist count for the wires to the left and right of it. If either of them are non-zero, we need to "flush" those twists onto the stack, since it will no longer be possible for them to be unravelled by later twists in the opposite direction.
After the last line of input, the input stream returns EOF repeatedly, and these EOF characters are interpreted as twists in every wire, at least for the purposes of flushing. This forces the program to flush any outstanding counts in the array, but it will not generate any new twist counts.
Once we've finished processing the input, all the commands for untangling the wires will now be on the stack. This means we can simply pop them off in reverse order to output the instructions needed to untangle the wires from the bottom up.
] |
[Question]
[
In a far-off kingdom, a chess queen takes a daily walk across a spiral path, numbered from 1 to `n`, not caring to follow the spiral itself, but simply making queen's moves as she would on a chessboard. The queen is beloved by her subjects, and they make a note of every square she visits on her path. Given that the queen can start her walk on any square and ends it on any square, what is the shortest queen's walk that she can take?
**The challenge**
Given a spiral of integers on a rectangular grid, write a function that returns one of the **shortest** possible paths (counted by number of cells travelled) between two numbers on this spiral grid using a chess queen's moves.
For example, from `16` to `25`:
```
25 10 11 12 13
24 9 2 3 14
23 8 1 4 15
22 7 6 5 16
21 20 19 18 17
```
Some possible paths include `16, 4, 2, 10, 25` and `16, 5, 1, 9, 25`.
**Rules**
* The input will be any two positive integers.
* The output will be a path of integers (including both endpoints) across the spiral using only orthogonal and diagonal moves.
* The length of a path is counted by the number of cells travelled.
* Your answer may be a program or a function.
* This is code golf, so the smallest number of bytes wins.
As always, if the problem is unclear, please let me know. Good luck and good golfing!
**Test cases**
```
>>> queen_spiral(4, 5)
4, 5
>>> queen_spiral(13, 20)
13, 3, 1, 7, 20
>>> queen_spiral(14, 14)
14
>>> queen_spiral(10, 3)
10, 11, 3
>>> queen_spiral(16, 25)
16, 4, 2, 10, 25
>>> queen_spiral(80, 1)
80, 48, 24, 8, 1
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~59~~ 57 bytesSBCS
```
{v⍳+\v[⍺],↓⍉↑(|⍴¨×)⊃⍵⍺-.⊃⊂v←9 11∘○¨+\0,0j1*{⍵/⍨⌈⍵÷2}⍳⍺⌈⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v7rsUe9m7Ziy6Ee9u2J1HrVNftTb@ahtokbNo94th1Ycnq75qKv5Ue9WoKyuHojZ1VT2qG2CpYKh4aOOGY@mdx9aoR1joGOQZahVDVSm/6h3xaOeDiDr8HajWqDJQH0Qfu3/NKC@R719j/qmevoDTTq03hhoD5AXHOQMJEM8PIP/myikKZhyGRoDKSMDLkMQ19CEy9AASBtzGZqBhE25LEBcQwA "APL (Dyalog Unicode) – Try It Online")
-2 bytes thanks to @ngn.
Anonymous function that accepts two endpoints as left and right arguments.
### Ungolfed & how it works
The queen moves diagonally first, so it is sufficient to pre-compute the coordinates of each number up to `max(start,end)`.
The coordinate-generating algorithm is inspired from several answers on the [related challenge](https://codegolf.stackexchange.com/q/87178/78410), but is slightly different from any of the existing answers:
* Given the necessary bound of 10
* Generate the 1-based range `r=1 2 3 4 5 6 7 8 9 10`
* Take the ceiling of half of each number `n=1 1 2 2 3 3 4 4 5 5`
* Replicate each item of `r` by `n`. `1 2 3 3 4 4 5 5 5 6 6 6 7 7 7 7 8 8 8 8 9 9 9 9 9 10 10 10 10 10`
* Take the cumulative sum of power of imaginary unit, with starting point of 0. (this part is common to various Python solutions to the linked challenge)
Then, once the vector of coordinates `v` is ready, we can easily convert between the spiral index and coordinates using `v[i]` and `v⍳coord` (finding the first index of `coord` in `v`).
```
⍝ Define a function; ⍺=start, ⍵=end
f←{
⍝ Construct a vector of spiral coordinates v
v←9 11∘○¨+\0,0j1*{⍵/⍨⌈⍵÷2}⍳⍺⌈⍵
⍺⌈⍵ ⍝ max of start, end
⍳ ⍝ range of 1 to that number
{⍵/⍨⌈⍵÷2} ⍝ for each number n of above, copy itself ceil(n/2) times
0j1* ⍝ raise imaginary unit to the power of above
+\0, ⍝ prepend 0 and cumulative sum
⍝ (gives vector of coordinates as complex numbers)
9 11∘○¨ ⍝ convert each complex number into (real, imag) pair
v← ⍝ assign it to v
⍝ Extract start and end coordinates
a w←(⍺⊃v)(⍵⊃v)
⍝ Compute the path the Queen will take
v⍳+\(⊂a),↓⍉↑(|⍴¨×)w-a
w-a ⍝ coordinate difference (end-start)
(|⍴¨×) ⍝ generate abs(x) copies of signum(x) for both x- and y-coords
⍝ e.g. 4 -> (1 1 1 1), ¯3 -> (¯1 ¯1 ¯1)
↓⍉↑ ⍝ promote to matrix (with 0 padding), transpose and split again
⍝ (gives list of steps the Queen will take)
+\(⊂a), ⍝ prepend the starting point and cumulative sum
⍝ (gives the path as coordinates)
v⍳ ⍝ index into the spiral vector (gives the spiral numbers at those coordinates)
}
```
[Answer]
# Mathematica ~~615~~ 530 bytes
This constructs a number grid, converts it into a graph, and then finds a shortest path between the two numbers that were input.
---
## UnGolfed
`numberSpiral` is from Mathworld [Prime Spiral](http://mathworld.wolfram.com/PrimeSpiral.html). It creates an n by n [Ulam Spiral](https://en.wikipedia.org/wiki/Ulam_spiral) (without highlighting the primes).
`findPath` converts the number grid into a graph. Edges are valid queen moves on the number grid.
---
```
numberSpiral[n_Integer?OddQ]:=
Module[{a,i=(n+1)/2,j=(n+1)/2,cnt=1,dir=0,len,parity,vec={{1,0},{0,-1},{-1,0},{0,1}}},a=Table[j+n(i-1),{i,n},{j,n}];Do[Do[Do[a[[j,i]]=cnt++;{i,j}+=vec[[dir+1]],{k,len}];dir=Mod[dir+1,4],{parity,0,1}],{len,n-1}];a];
findPath[v1_, v2_] :=
Module[{f, z, k},
(*f creates edges between each number and its neighboring squares *)
f[sp_,n_]:=n<->#&/@(sp[[Sequence@@#]]&/@(Position[sp,n][[1]]/.{r_,c_}:>Cases[{{r-1,c},{r+1,c},{r,c-1},{r,c+1},{r-1,c-1},{r-1,c+1},{r+1,c+1}, {r+1,c-1}},{x_,y_}/; 0<x<k&&0<y<k]));k=If[EvenQ[
z=\[LeftCeiling]Sqrt[Sort[{v1, v2}][[-1]]]\[RightCeiling]],z+1,z];
FindShortestPath[Graph[Sort/@Flatten[f[ns=numberSpiral[k],#]&/@Range[k^2]] //Union],v1,v2]]
```
---
## Examples
```
findPath[4,5]
findPath[13,22]
findPath[16,25]
numberSpiral[5]//Grid
```
{4,5}
{13,3,1,7,22}
{16,4,1,9,25}
[](https://i.stack.imgur.com/fMIkz.png)
---
The shortest path from 80 to 1 contains 5, not 6, vertices.
```
findPath[80,1]
numberSpiral[9]//Grid
```
{80, 48, 24, 8, 1}
[](https://i.stack.imgur.com/UA81Z.png)
---
## Golfed
```
u=Module;
w@n_:=u[{a,i=(n+1)/2,j=(n+1)/2,c=1,d=0,l,p,v={{1,0},{0,-1},{-1,0},{0,1}}},
a=Table[j+n(i-1),{i,n},{j,n}];
Do[Do[Do[a[[j,i]]=c++;{i,j}+=v[[d+1]],{k,l}];d=Mod[d+1,4],{p,0,1}],{l,n-1}];a];
h[v1_,v2_]:=u[{f,z},
s_~f~n_:=n<->#&/@(s[[Sequence@@#]]&/@(Position[s,n][[1]]/.{r_,c_}:>
Cases[{{r-1,c},{r+1,c},{r,c-1},{r,c+1},{r-1,c-1},{r-1,c+1},{r+1,c+1},{r+1,c-1}},{x_,y_}/;0<x<k&&0<y<k]));
k=If[EvenQ[z=\[LeftCeiling]Sqrt[Sort[{v1,v2}][[-1]]]\[RightCeiling]],z+1,z];
FindShortestPath[g=Graph[Sort/@Flatten[f[ns=w@k,#]&/@Union@Range[k^2]]],v1,v2]]
```
[Answer]
# Scala (830 bytes)
Builds the spiral in a square 2D array using four mutually recursive functions. Another recursive search to build the path list.
```
def P(s:Int,e:Int):List[Int]={
import scala.math._
type G=Array[Array[Int]]
type I=Int
type T=(I,I)
def S(z:I)={def U(g:G,x:I,y:I,c:I,r:I):Unit={for(i<-0 to r.min(y)){g(y-i)(x)=c+i}
if(r<=y)R(g,x,y-r,c+r,r)}
def R(g:G,x:I,y:I,c:I,r:I)={for(i<-0 to r){g(y)(x+i)=c+i}
D(g,x+r,y,c+r,r+1)}
def D(g:G,x:I,y:I,c:I,r:I)={for(i<-0 to r){g(y+i)(x)=c+i}
L(g,x,y+r,c+r,r)}
def L(g:G,x:I,y:I,c:I,r:I)={for(i<-0 to r){g(y)(x-i)=c+i}
U(g,x-r,y,c+r,r+1)}
val g=Array.ofDim[I](z,z)
U(g,z/2,z/2,1,1)
g}
def C(n:I,g:G):T={var(x,y)=(0,0)
for(i<-g.indices){val j=g(i).indexOf(n)
if(j>=0){x=j
y=i}}
(x,y)}
def N(n:Int)=if(n==0)0 else if(n<0)-1 else 1
def Q(a:T,b:T):List[T]={val u=N(b._1-a._1)
val v=N(b._2-a._2)
if(u==0&&v==0)b::Nil else a::Q((a._1+u,a._2+v),b)}
val z=ceil(sqrt(max(s,e))).toInt|1
val p=S(z)
Q(C(s,p),C(e,p)).map{case(x,y)=>p(y)(x)}}
```
## Ungolfed
```
import scala.math._
type Grid=Array[Array[Int]]
def spiral(size: Int) = {
def up(grid:Grid, x: Int, y: Int, c: Int, r: Int): Unit = {
for (i <- 0 to r.min(y)) {
grid(y-i)(x) = c + i
}
if (r <= y)
right(grid,x,y-r,c+r,r)
}
def right(grid:Grid, x: Int, y: Int, c: Int, r: Int) = {
for (i <- 0 to r) {
grid(y)(x+i) = c + i
}
down(grid,x+r,y,c+r,r+1)
}
def down(grid:Grid, x: Int, y: Int, c: Int, r: Int) = {
for (i <- 0 to r) {
grid(y+i)(x) = c + i
}
left(grid,x,y+r,c+r,r)
}
def left(grid:Grid, x: Int, y: Int, c: Int, r: Int) = {
for (i <- 0 to r) {
grid(y)(x-i) = c + i
}
up(grid,x-r,y,c+r,r+1)
}
val grid = Array.ofDim[Int](size,size)
up(grid,size/2,size/2,1,1)
grid
}
def findPath(start: Int, end: Int): List[Int] = {
def findCoords(n: Int, grid: Grid): (Int, Int) = {
var (x,y)=(0,0)
for (i <- grid.indices) {
val j = grid(i).indexOf(n)
if (j >= 0) {
x = j
y = i
}
}
(x,y)
}
def sign(n: Int) = if (n == 0) 0 else if (n < 0) -1 else 1
def path(stc: (Int, Int), enc: (Int, Int)) : List[(Int, Int)] = {
val dx = sign(enc._1 - stc._1)
val dy = sign(enc._2 - stc._2)
if (dx == 0 && dy == 0) {
enc :: Nil
} else {
stc :: path((stc._1 + dx, stc._2 + dy), enc)
}
}
val size = ceil(sqrt(max(start, end))).toInt | 1
val spir = spiral(size)
path(findCoords(start, spir),findCoords(end, spir)).
map { case (x, y) => spir(y)(x) }
}
```
[Answer]
# Ruby, ~~262~~ ~~218~~ 216 bytes
This is a port of [my Python answer](https://codegolf.stackexchange.com/a/88833/47581). Golfing suggestions welcome.
**Edit:** 45 bytes thanks to Jordan and their suggestions of `d=[0]*n=m*m;*e=c=0;*t=a`, `.rect`, `0<=>x` and `x,y=(e[a]-g=e[b]).rect; t<<d[(g.real+x)*m+g.imag+y]`. Another byte from `(x+y*1i)` to `(x+y.i)`.
```
->a,b{m=([a,b].max**0.5).to_i+1;d=[0]*n=m*m;*e=c=0;*t=a
n.times{|k|d[c.real*m+c.imag]=k+1;e<<c;c+=1i**((4*k+1)**0.5-1).to_i}
x,y=(e[a]-g=e[b]).rect
(x+=0<=>x;y+=0<=>y;t<<d[(g.real+x)*m+g.imag+y])while(x+y.i).abs>0
t}
```
Ungolfed:
```
def q(a,b)
m = ([a,b].max**0.5).to_i+1
n = m*m
d = [0]*n
c = 0
*e = c # same as e=[0]
*t = a # same as t=[a]
(1..n).each do |k|
d[c.real * m + c.imag] = k+1
e << c
c += 1i**((4*k+1)**0.5-1).to_i
end
x, y = (e[a] - g=e[b]).rect
while (x+y.i).abs > 0 do
if x<0
x += 1
elsif x>0
x += -1
end
if y<0
y += 1
elsif y>0
y -= 1
end
t << d[(g.real+x)*m+g.imag+y]
end
return t
end
```
[Answer]
# Python 3, 316 bytes
This answer looks at the coordinates of `a` and `b` on the spiral (using complex numbers) and adds the diagonal moves first, then the orthogonal moves.
```
def q(a,b):
m=int(max(a,b)**.5)+1;d=[];c=0;e=[c];t=[a]
for i in range(m):d+=[[0]*m]
for k in range(m*m):d[int(c.real)][int(c.imag)]=k+1;e+=[c];c+=1j**int((4*k+1)**.5-1)
z=e[a]-e[b];x,y=int(z.real),int(z.imag)
while abs(x+y*1j):x+=(x<0)^-(x>0);y+=(y<0)^-(y>0);t+=[d[int(e[b].real)+x][int(e[b].imag)+y]]
return t
```
**Ungolfed:**
```
def queen_spiral(a,b):
square_size = int(max(a,b)**.5)+1
complex_to_spiral = []
complex = 0
spiral_to_complex = [c] # add 0 first, so that it's 1-indexed later
result = [a]
for i in range(square_size):
complex_to_spiral.append([0]*square_size) # the rows of the spiral
for k in range(square_size**2):
row = int(complex.real)
column = int(complex.imag)
complex_to_spiral[row][column] = k+1 # 1-indexing
spiral_to_complex.append(complex)
quarter_turns = int((4*k+1)**.5-1)
complex += 1j**quarter_turns
z = spiral_to_complex[a] - spiral_to_complex[b]
v = spiral_to_complex[b]
x, y = int(z.real), int(z.imag)
r, s = int(v.real), int(v.imag)
while abs(x+y*1j):
if x < 0:
x += 1
elif x > 0:
x += -1
# else x == 0, do nothing
if y < 0:
y += 1
elif y > 0:
y += -1
vertex = complex_to_spiral[r+x][s+y]
result.append(vertex)
return result
```
] |
[Question]
[
A nonogram is a Japanese puzzle game in which the goal is to draw a black-and-white picture according to a list of contiguous regions, like so:
[](https://i.stack.imgur.com/2Xtt8.png)
Define the *nonographic magnitude* of a row or column to be the number of contiguous black regions in that row or column. For example, the top row has a nonographic magnitude of 1, because there is one region of 2 squares in that row. The 8th row has a nonographic magnitude of 3 because it has 2, 2, 1.
An empty row or column has a nonographic magnitude of 0.
---
Your task is to write a program that takes a solution grid for a nonogram, and produces a solution grid with *as few filled-in squares as possible* where every row and column has the same nonographic magnutide as the given solution grid.
For example, a nonogram grid with all the squares filled in has a nonographic magnitude of 1 on every row or column:

The same nonographic magnitude could be achieved just by having a diagonal stripe through the grid, reducing the number of filled-in squares dramatically:

---
Your program will receive an input consisting of 50,000 lines from [this file](https://github.com/joezeng/pcg-se-files/raw/master/nonograms.tar.gz) (1.32 MB tar.gz text file; 2.15 MB unzipped), each representing a single 16×16 nonogram solution grid with randomly (80% black) filled-in squares, and output another 50,000 lines, each containing the optimized solution grid for the corresponding input grid.
Each grid is represented as a base64 string with 43 characters (encoding squares from left to right, then top to bottom), and your program will need to return its output in the same format. For example, the first grid in the file is `E/lu/+7/f/3rp//f799xn/9//2mv//nvj/bt/yc9/40=`, and renders as:

The grid starts with `E` which maps to `000100`, so the first six cells in the top row are all white except the fourth one. The next character is `/` which maps to `111111`, so the next 6 cells are all black — and so on.
---
Your program must actually return a solution grid with the correct nonographic magnitudes for each of the 50,000 test cases. It is allowed to return the same grid as the input if nothing better was found.
The program to return the fewest total filled-in squares (in any language) is the winner, with shorter code being the tiebreaker.
---
Current scoreboard:
1. [3,637,260](https://codegolf.stackexchange.com/a/69532/7110) — Sleafar, Java
2. [7,270,894](https://codegolf.stackexchange.com/a/69531/7110) — flawr, Matlab
3. [10,239,288](https://codegolf.stackexchange.com/a/69484/7110) — Joe Z., Bash
[Answer]
## Python 2 & PuLP — 2,644,688 squares (optimally minimized); 10,753,553 squares (optimally maximized)
## Minimally golfed to 1152 bytes
```
from pulp import*
x=0
f=open("c","r")
g=open("s","w")
for k,m in enumerate(f):
if k%2:
b=map(int,m.split())
p=LpProblem("Nn",LpMinimize)
q=map(str,range(18))
ir=q[1:18]
e=LpVariable.dicts("c",(q,q),0,1,LpInteger)
rs=LpVariable.dicts("rs",(ir,ir),0,1,LpInteger)
cs=LpVariable.dicts("cs",(ir,ir),0,1,LpInteger)
p+=sum(e[r][c] for r in q for c in q),""
for i in q:p+=e["0"][i]==0,"";p+=e[i]["0"]==0,"";p+=e["17"][i]==0,"";p+=e[i]["17"]==0,""
for o in range(289):i=o/17+1;j=o%17+1;si=str(i);sj=str(j);l=e[si][str(j-1)];ls=rs[si][sj];p+=e[si][sj]<=l+ls,"";p+=e[si][sj]>=l-ls,"";p+=e[si][sj]>=ls-l,"";p+=e[si][sj]<=2-ls-l,"";l=e[str(i-1)][sj];ls=cs[si][sj];p+=e[si][sj]<=l+ls,"";p+=e[si][sj]>=l-ls,"";p+=e[si][sj]>=ls-l,"";p+=e[si][sj]<=2-ls-l,""
for r,z in enumerate(a):p+=lpSum([rs[str(r+1)][c] for c in ir])==2*z,""
for c,z in enumerate(b):p+=lpSum([cs[r][str(c+1)] for r in ir])==2*z,""
p.solve()
for r in ir:
for c in ir:g.write(str(int(e[r][c].value()))+" ")
g.write('\n')
g.write('%d:%d\n\n'%(-~k/2,value(p.objective)))
x+=value(p.objective)
else:a=map(int,m.split())
print x
```
(NB: the heavily indented lines start with tabs, not spaces.)
Example output: <https://drive.google.com/file/d/0B-0NVE9E8UJiX3IyQkJZVk82Vkk/view?usp=sharing>
It turns out that problems like are readily convertible to Integer Linear Programs, and I needed a basic problem to learn how to use PuLP—a python interface for a variety of LP solvers—for a project of my own. It also turns out that PuLP is extremely easy to use, and the ungolfed LP builder worked perfectly the first time I tried it.
The two nice things about employing a branch-and-bound IP solver to do the hard work of solving this for me (other than not having to implement a branch and bound solver) are that
* Purpose-built solvers are really fast. This program solves all 50000 problems in about 17 hours on my relatively low-end home PC. Each instance took from 1-1.5 seconds to solve.
* They produce guaranteed optimal solutions (or tell you that they failed to do so). Thus, I can be confident that no one will beat my score in squares (although someone might tie it and beat me on the golfing part).
## How to use this program
First, you'll need to install PuLP. `pip install pulp` should do the trick if you have pip installed.
Then, you'll need to put the following in a file called "c": <https://drive.google.com/file/d/0B-0NVE9E8UJiNFdmYlk1aV9aYzQ/view?usp=sharing>
Then, run this program in any late Python 2 build from the same directory. In less than a day, you'll have a file called "s" which contains 50,000 solved nonogram grids (in readable format), each with the total number of filled squares listed below it.
If you'd like to maximize the number of filled squares instead, change the `LpMinimize` on line 8 to `LpMaximize` instead. You will get output very much like this: <https://drive.google.com/file/d/0B-0NVE9E8UJiYjJ2bzlvZ0RXcUU/view?usp=sharing>
## Input format
This program uses a modified input format, since Joe Z. said that we would be allowed to re-encode the input format if we like in a comment on the OP. Click the link above to see what it looks like. It consists of 10000 lines, each containing 16 numbers. The even numbered lines are the magnitudes for the rows of a given instance, while the odd numbered lines are the magnitudes for the columns of the same instance as the line above them. This file was generated by the following program:
```
from bitqueue import *
with open("nonograms_b64.txt","r") as f:
with open("nonogram_clues.txt","w") as g:
for line in f:
q = BitQueue(line.decode('base64'))
nonogram = []
for i in range(256):
if not i%16: row = []
row.append(q.nextBit())
if not -~i%16: nonogram.append(row)
s=""
for row in nonogram:
blocks=0 #magnitude counter
for i in range(16):
if row[i]==1 and (i==0 or row[i-1]==0): blocks+=1
s+=str(blocks)+" "
print >>g, s
nonogram = map(list, zip(*nonogram)) #transpose the array to make columns rows
s=""
for row in nonogram:
blocks=0
for i in range(16):
if row[i]==1 and (i==0 or row[i-1]==0): blocks+=1
s+=str(blocks)+" "
print >>g, s
```
(This re-encoding program also gave me an extra opportunity to test my custom BitQueue class I created for the same project mentioned above. It is simply a queue to which data can be pushed as sequences of bits OR bytes, and from which data can be popped either a bit or a byte at a time. In this instance, it worked perfectly.)
I re-encoded the input for the specific reason that to build an ILP, the extra information about the grids that were used to generate the magnitudes is perfectly useless. The magnitudes are the only constraints, and so the magnitudes are all I needed access to.
## Ungolfed ILP builder
```
from pulp import *
total = 0
with open("nonogram_clues.txt","r") as f:
with open("solutions.txt","w") as g:
for k,line in enumerate(f):
if k%2:
colclues=map(int,line.split())
prob = LpProblem("Nonogram",LpMinimize)
seq = map(str,range(18))
rows = seq
cols = seq
irows = seq[1:18]
icols = seq[1:18]
cells = LpVariable.dicts("cell",(rows,cols),0,1,LpInteger)
rowseps = LpVariable.dicts("rowsep",(irows,icols),0,1,LpInteger)
colseps = LpVariable.dicts("colsep",(irows,icols),0,1,LpInteger)
prob += sum(cells[r][c] for r in rows for c in cols),""
for i in rows:
prob += cells["0"][i] == 0,""
prob += cells[i]["0"] == 0,""
prob += cells["17"][i] == 0,""
prob += cells[i]["17"] == 0,""
for i in range(1,18):
for j in range(1,18):
si = str(i); sj = str(j)
l = cells[si][str(j-1)]; ls = rowseps[si][sj]
prob += cells[si][sj] <= l + ls,""
prob += cells[si][sj] >= l - ls,""
prob += cells[si][sj] >= ls - l,""
prob += cells[si][sj] <= 2 - ls - l,""
l = cells[str(i-1)][sj]; ls = colseps[si][sj]
prob += cells[si][sj] <= l + ls,""
prob += cells[si][sj] >= l - ls,""
prob += cells[si][sj] >= ls - l,""
prob += cells[si][sj] <= 2 - ls - l,""
for r,clue in enumerate(rowclues):
prob += lpSum([rowseps[str(r+1)][c] for c in icols]) == 2 * clue,""
for c,clue in enumerate(colclues):
prob += lpSum([colseps[r][str(c+1)] for r in irows]) == 2 * clue,""
prob.solve()
print "Status for problem %d: "%(-~k/2),LpStatus[prob.status]
for r in rows[1:18]:
for c in cols[1:18]:
g.write(str(int(cells[r][c].value()))+" ")
g.write('\n')
g.write('Filled squares for %d: %d\n\n'%(-~k/2,value(prob.objective)))
total += value(prob.objective)
else:
rowclues=map(int,line.split())
print "Total number of filled squares: %d"%total
```
This is the program that actually produced the "example output" linked above. Hence the extra long strings at the end of each grid, which I truncated when golfing it. (The golfed version should produce identical output, minus the words `"Filled squares for "`)
## How it Works
```
cells = LpVariable.dicts("cell",(rows,cols),0,1,LpInteger)
rowseps = LpVariable.dicts("rowsep",(irows,icols),0,1,LpInteger)
colseps = LpVariable.dicts("colsep",(irows,icols),0,1,LpInteger)
```
I use an 18x18 grid, with the center 16x16 part being the actual puzzle solution. `cells` is this grid. The first line creates 324 binary variables: "cell\_0\_0", "cell\_0\_1", and so on. I also create grids of the "spaces" between and around the cells in the solution part of the grid. `rowseps` points to the 289 variables which symbolize the spaces that separate cells horizontally, while `colseps` similarly points to variables that mark the spaces that separate cells vertically. Here's a unicode diagram:
```
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|□|0
- - - - - - - - - - - - - - - -
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
```
The `0`s and `□`s are the binary values tracked by the `cell` variables, the `|`s are the binary values tracked by the `rowsep` variables, and the `-`s are the binary values tracked by the `colsep` variables.
```
prob += sum(cells[r][c] for r in rows for c in cols),""
```
This is the objective function. Just the sum of all the `cell` variables. Since these are binary variables, this is just exactly the number of filled squares in the solution.
```
for i in rows:
prob += cells["0"][i] == 0,""
prob += cells[i]["0"] == 0,""
prob += cells["17"][i] == 0,""
prob += cells[i]["17"] == 0,""
```
This just sets the cells around the outer edge of the grid to zero (which is why I represented them as zeroes above). This is the most expedient way to track how many "blocks" of cells are filled, since it ensures that every change from unfilled to filled (moving across a column or row) is matched by a corresponding change from filled to unfilled (and vice versa), even if the first or last cell in the row is filled. This is the sole reason for using an 18x18 grid in the first place. It's not the only way to count blocks, but I think it is the simplest.
```
for i in range(1,18):
for j in range(1,18):
si = str(i); sj = str(j)
l = cells[si][str(j-1)]; ls = rowseps[si][sj]
prob += cells[si][sj] <= l + ls,""
prob += cells[si][sj] >= l - ls,""
prob += cells[si][sj] >= ls - l,""
prob += cells[si][sj] <= 2 - ls - l,""
l = cells[str(i-1)][sj]; ls = colseps[si][sj]
prob += cells[si][sj] <= l + ls,""
prob += cells[si][sj] >= l - ls,""
prob += cells[si][sj] >= ls - l,""
prob += cells[si][sj] <= 2 - ls - l,""
```
This is the real meat of the logic of the ILP. Basically it requires that each cell (other than those in the first row and column) be the logical xor of the cell and separator directly to its left in its row and directly above it in its column. I got the constraints that simulate an xor within a {0,1} integer program from this wonderful answer: <https://cs.stackexchange.com/a/12118/44289>
To explain a bit more: this xor constraint makes it so that the separators can be 1 if and only if they lie between cells which are 0 and 1 (marking a change from unfilled to filled or vice versa). Thus, there will be exactly twice as many 1-valued separators in a row or column as the number of blocks in that row or column. In other words, the sum of the separators on a given row or column is exactly twice the magnitude of that row/column. Hence the following constraints:
```
for r,clue in enumerate(rowclues):
prob += lpSum([rowseps[str(r+1)][c] for c in icols]) == 2 * clue,""
for c,clue in enumerate(colclues):
prob += lpSum([colseps[r][str(c+1)] for r in irows]) == 2 * clue,""
```
And that's pretty much it. The rest just asks the default solver to solve the ILP, then formats the resulting solution as it writes it to the file.
[Answer]
# Java, ~~6,093,092~~ ~~4,332,656~~ 3,637,260 squares (minimized), ~~10,567,550~~ ~~10,567,691~~ 10,568,746 squares (maximized)
Both variants of the program repeatedly perform operations on the source grid, without changing the magnitude.
## Minimizer
### shrink()
[](https://i.stack.imgur.com/tqlir.png)
If a black square has 2 white neighbors and 2 black neighbors in a 90° angle, it can be replaced by a white square.
### moveLine()
[](https://i.stack.imgur.com/fvQBY.png) [](https://i.stack.imgur.com/X6wmy.png)
In configurations like above the black line can be moved to the right. This is done repeatedly for all 4 line directions clockwise and counterclockwise, to open up new shrink possibilities.
## Maximizer
Uncomment the line in `main()` and comment out the line above it for this version.
### grow()
[](https://i.stack.imgur.com/Og0dp.png)
If a white square has 2 white neighbors and 2 black neighbors in a 90° angle, it can be replaced by a black square.
### moveLine()
Same as in Minimizer.
## Source
```
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Arrays;
import java.util.Base64;
import java.util.function.Function;
public class Main {
private static final int SIZE = 16;
private static final int SIZE_4 = SIZE + 4;
private static final int E = 0;
private static final int N = 1;
private static final int W = 2;
private static final int S = 3;
private static final Base64.Decoder decoder = Base64.getMimeDecoder();
private static final Base64.Encoder encoder = Base64.getMimeEncoder();
private static int sourceBlack = 0;
private static int targetBlack = 0;
private static class Nonogram {
private final boolean[] cells = new boolean[SIZE_4 * SIZE_4];
private final int[] magnitudes;
public Nonogram(String encoded) {
super();
byte[] decoded = decoder.decode(encoded);
for (int i = 0; i < decoded.length; ++ i) {
for (int j = 0; j < 8; ++ j) {
if ((decoded[i] & (1 << (7 - j))) != 0) {
int k = i * 8 + j;
cells[getPos(k / SIZE, k % SIZE)] = true;
++ sourceBlack;
}
}
}
magnitudes = calcMagnitudes();
}
private int getPos(int row, int col) {
return (row + 2) * SIZE_4 + col + 2;
}
private int move(int pos, int dir, int count) {
switch (dir) {
case E: return pos + count;
case N: return pos - count * SIZE_4;
case W: return pos - count;
case S: return pos + count * SIZE_4;
default: return pos;
}
}
private int move(int pos, int dir) {
return move(pos, dir, 1);
}
private int[] calcMagnitudes() {
int[] result = new int[SIZE * 2];
for (int row = 0; row < SIZE; ++ row) {
for (int col = 0; col < SIZE; ++ col) {
int pos = getPos(row, col);
if (cells[pos]) {
if (!cells[move(pos, W)]) {
++ result[row + SIZE];
}
if (!cells[move(pos, N)]) {
++ result[col];
}
}
}
}
return result;
}
private boolean isBlack(int pos) {
return cells[pos];
}
private boolean isWhite(int pos) {
return !cells[pos];
}
private boolean allBlack(int pos, int dir, int count) {
int p = pos;
for (int i = 0; i < count; ++ i) {
if (isWhite(p)) {
return false;
}
p = move(p, dir);
}
return true;
}
private boolean allWhite(int pos, int dir, int count) {
int p = pos;
for (int i = 0; i < count; ++ i) {
if (isBlack(p)) {
return false;
}
p = move(p, dir);
}
return true;
}
private int findWhite(int pos, int dir) {
int count = 0;
int p = pos;
while (cells[p]) {
++ count;
p = move(p, dir);
}
return count;
}
@SafeVarargs
private final void forEach(Function<Integer, Boolean>... processors) {
outer:
for (;;) {
for (Function<Integer, Boolean> processor : processors) {
for (int row = 0; row < SIZE; ++ row) {
for (int col = 0; col < SIZE; ++ col) {
if (processor.apply(getPos(row, col))) {
continue outer;
}
}
}
}
return;
}
}
private boolean shrink(int pos) {
if (cells[pos] && cells[move(pos, W)] != cells[move(pos, E)] &&
cells[move(pos, N)] != cells[move(pos, S)]) {
cells[pos] = false;
return true;
}
return false;
}
private boolean grow(int pos) {
if (!cells[pos] && cells[move(pos, W)] != cells[move(pos, E)] &&
cells[move(pos, N)] != cells[move(pos, S)]) {
cells[pos] = true;
return true;
}
return false;
}
private boolean moveLine(boolean clockwise, int dir, int sourcePos) {
int from = (dir + (clockwise ? 1 : 3)) % 4;
int to = (dir + (clockwise ? 3 : 1)) % 4;
int opp = (dir + 2) % 4;
if (isBlack(sourcePos) && isWhite(move(sourcePos, from)) && isWhite(move(sourcePos, dir))) {
int toCount = findWhite(move(move(sourcePos, dir), to), to) + 1;
if (allWhite(move(sourcePos, to), to, toCount + 1)) {
int lineCount = 1;
int tmpPos = move(sourcePos, opp);
while (isBlack(tmpPos) && isWhite(move(tmpPos, from)) && allWhite(move(tmpPos, to), to, toCount + 1)) {
++ lineCount;
tmpPos = move(tmpPos, opp);
}
if (allBlack(tmpPos, to, toCount + 1)) {
tmpPos = sourcePos;
for (int j = 0; j < lineCount; ++ j) {
cells[tmpPos] = false;
cells[move(tmpPos, to, toCount)] = true;
tmpPos = move(tmpPos, opp);
}
return true;
}
}
}
return false;
}
public Nonogram minimize() {
for (int i = 0; i < 5; ++ i) {
forEach(pos -> shrink(pos), pos -> moveLine(true, E, pos), pos -> moveLine(true, N, pos),
pos -> moveLine(true, W, pos), pos -> moveLine(true, S, pos));
forEach(pos -> shrink(pos), pos -> moveLine(false, E, pos), pos -> moveLine(false, N, pos),
pos -> moveLine(false, W, pos), pos -> moveLine(false, S, pos));
}
return this;
}
public Nonogram maximize() {
for (int i = 0; i < 5; ++ i) {
forEach(pos -> grow(pos), pos -> moveLine(true, E, pos), pos -> moveLine(true, N, pos),
pos -> moveLine(true, W, pos), pos -> moveLine(true, S, pos));
forEach(pos -> grow(pos), pos -> moveLine(false, E, pos), pos -> moveLine(false, N, pos),
pos -> moveLine(false, W, pos), pos -> moveLine(false, S, pos));
}
return this;
}
public String toBase64() {
if (!Arrays.equals(magnitudes, calcMagnitudes())) {
throw new RuntimeException("Something went wrong!");
}
byte[] decoded = new byte[SIZE * SIZE / 8];
for (int i = 0; i < decoded.length; ++ i) {
for (int j = 0; j < 8; ++ j) {
int k = i * 8 + j;
if (cells[getPos(k / SIZE, k % SIZE)]) {
decoded[i] |= 1 << (7 - j);
++ targetBlack;
}
}
}
return encoder.encodeToString(decoded);
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
for (int row = 0; row < SIZE; ++ row) {
for (int col = 0; col < SIZE; ++ col) {
b.append(cells[getPos(row, col)] ? '#' : ' ');
}
b.append('\n');
}
return b.toString();
}
}
public static void main(String[] args) throws Exception {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("solutions_b64.txt"));
BufferedReader reader = new BufferedReader(new FileReader("nonograms_b64.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(new Nonogram(line).minimize().toBase64() + "\n");
//writer.write(new Nonogram(line).maximize().toBase64() + "\n");
}
}
System.out.printf("%d -> %d", sourceBlack, targetBlack);
}
}
```
[Answer]
# Bash — 10,239,288 squares
As a last-place reference solution:
```
cp nonograms_b64.txt solutions_b64.txt
```
Since your program is allowed to return the same grid if it can't find a better solution, printing out the whole file verbatim is also valid.
There are a total of 10,239,288 black squares in the test file, which is pretty close to the 10,240,000 you'd expect from 80% of squares filled in out of 50,000 grids with 256 squares each. As usual with my test-battery questions, I've selected the number of test cases with the expectation that the optimal scores will be around the 2-million range, although I suspect the scores will be closer to 4 or 5 million this time around.
---
If anyone can create a solution that *maximizes* the black squares rather than minimizing them and manages to get over 10,240,000, I might consider giving it a bounty.
[Answer]
# Matlab, 7,270,894 squares (~71% of original)
Idea is a simple repeated greedy search: For every black square, try if you can set it to white without changing the nonographic magnitudes. Repeat this twice. (You could achieve way better results with more repetitions, but not for free: It results in an correspondingly longer runtime. Now it was about 80 minutes. I would do that, if we would not have to compute all 50k testcases...)
Here the code (each function in a separate file, as usual.)
```
function D = b64decode(E)
% accepts a string of base 64 encoded data, and returns a array of zeros
% and ones
F = E;
assert( mod(numel(E),4)==0 && 0 <= sum(E=='=') && sum(E=='=') <= 2,'flawed base 64 code')
F('A' <= E & E<= 'Z') = F('A' <= E & E<= 'Z') -'A'; %upper case
F('a' <= E & E<= 'z') = F('a' <= E & E<= 'z') -'a' + 26; %lower case
F('0'<= E & E <= '9') = F('0'<= E & E <= '9') -'0' + 52; %digits
F( E == '+') = 62;
F( E == '/') = 63;
F( E == '=') = 0;
D=zeros(1,numel(E)*3*8/4);
for k=1:numel(E);
D(6*(k-1)+1 + (0:5)) = dec2bin(F(k),6)-'0';
end
if E(end) == '=';
D(end-7:end) = [];
if E(end-1) == '=';
D(end-7:end) = [];
end
end
end
function E = b64encode(D)
assert(mod(numel(D),8)==0,'flawed byte code');
N=0;
while mod(numel(D),6) ~= 0;
D = [D,zeros(1,8)];
N = N+1;
end
dict = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
E=zeros(1,numel(D)/6)+'=';
for k=0:numel(E)-N-1;
E(k+1) = dict(bin2dec( [D(6*k+(1:6))+'0',''] ) + 1);
end
E = [E,''];
end
function [B,T,O] = reduce_greedy(N)
% reduce greedily
NM = nomographic_magnitude(N);
B = N; %current best
M = N;
T = nnz(N); %current number of filled squares
O = T;
for r=1:2; %how many repetitions
I = find(B);
for k=1:numel(I);
M = B;
M( I(k) ) = 0;
%check whether we have a valid solution
if all(NM == nomographic_magnitude(M))
if T > nnz(M); %did we actually reduce the number of filled squares?
B = M;
T = nnz(M);
end
end
end
end
%% main file
string_in = fileread('nonograms_b64.txt');
string_out = string_in;
tic
total_new = 0; %total number of black squares
total_old = 0;
M = 50000;
for k=1:M;
disp(k/M); %display the progress
line = string_in(45*(k-1)+(1:44));
decoded = b64decode(line);
nonogram = reshape(decoded,16,[]) ;%store nonogram as a matrix
[B,T,O] = reduce_greedy(nonogram);
disp([nnz(B),nnz(nonogram)])
total_new = total_new + T;
total_old = total_old + O;
string_in(45*(k-1)+(1:44)) = b64encode(B(:).');
end
toc
F = fopen('nonograms_b64_out.txt','w');
fprintf(F,string_out);
%%
disp([total_new,total_old])
```
] |
[Question]
[
Your task is to write a program that takes an input image and run it through edge-detection to become an output image.
The edge-detection works as follows (if unclear, see [sobel edge detection](https://en.wikipedia.org/wiki/Sobel_operator#Formulation)):
* The value for a pixel is the total brightness of a pixel, so if it is in color, you will need to convert it to grayscale first (to keep things simple and golf-able, you can take the average value for R, G and B).
* The formulae for Gx and Gy for pixel p(i,j) are:
+ Gx = -1 \* p(i-1, j-1) - 2 \* p(i-1, j) - 1 \* p(i-1, j+1) + 1 \* p(i+1, j-1) + 2 \* p(i+1, j) + 1 \* p(i+1, j+1)
+ Gy = -1 \* p(i-1, j-1) - 2 \* p(i, j-1) - 1 \* p(i+1, j-1) + 1 \* p(i-1, j+1) + 2 \* p(i, j+1) + 1 \* p(i+1, j+1)
* The value for the size of the edge at that pixel is then: √(Gx2 + Gy2)
The output image is for each pixel the size of the edge √(Gx2 + Gy2) as greyscale.
Bonuses:
* Perform a gaussian blur to smooth out the image before edge-detection kicks in, to omit any smaller edges. This gives a bonus of -30% on the end result.
* Take the angle of the edge in account. You give the output pixel some color, by taking the same greyscale value and adding color from a color wheel using the angle obtained from the formula arctan(Gy/Gx). This gives another bonus of -30% on the end result.
Rules:
* You may omit the value for the edgepixels, and set them to black, or you may use 0 for any pixel outside the image.
* Your ouput image must be in an image format that can be opened on most computers.
* Output must be written to disk or be pipeable to a file.
* Input is given as a commandline argument, in the form of a relative path to the image, or piped in from the commandline.
* This is code golf, so shortest code in bytes wins!
[Answer]
# J, ~~166 164 161 154 150 144~~ 143 bytes.
Not golfed too much; I mostly collapsed my longer implementation (see below), so there's probably lots of room for improvement. Uses BMP library. Saves result in file `o`. I handled edgepixels by only using full 3x3 cells, so the final image has width and height smaller by 2 pixels.
```
load'bmp'
S=:s,.0,.-s=:1 2 1
p=:([:*:[:+/[:,*)"2
'o'writebmp~256#.3#"0<.255<.%:(S&p+(|:S)&p)3 3,.;._3(3%~])+/"1(3#256)#:readbmp}:stdin''
exit''
```
Usage:
```
echo 'image.bmp' | jconsole golf.ijs
```
Expanded:
```
load 'bmp'
sobel1 =: 3 3 $ 1 0 _1 2 0 _2 1 0 _1
NB. transposed
sobel2 =: |: sobel1
NB. read image
image =: readbmp }: stdin''
NB. convert default representation to R,G,B arrays
rgbimage =: (3 # 256) #: image
NB. convert to grayscale
greyimage =: 3 %~ (+/"1) rgbimage
NB. 3x3 cells around each pixel
cells =: 3 3 ,.;._3 greyimage
NB. multiply 3x3 cell by 3x3 sobel, then sum all values in it
partial =: 4 : '+/"1 +/"1 x *"2 y'
NB. square partial (vertical and horizontal) results, sum and root
combine =: [: %: *:@[ + *:@]
NB. limit RGB values to 255
limit =: 255 <. ]
newimage =: limit (sobel1&partial combine sobel2&partial) cells
NB. convert back to J-friendly representation
to_save =: 256 #. 3 #"0 <. newimage
to_save writebmp 'out.bmp'
NB. jconsole stays open by default
exit''
```
Sample input and output:
[](https://i.stack.imgur.com/2XyVH.png)
[](https://i.stack.imgur.com/dh4yX.png)
[Answer]
# Python, 161\*0.7=112.7 bytes
With the Gaussian Blur bonus.
As you did not explicitly forbid built-in methods, here is OpenCV:
```
from cv2 import*
from numpy import*
g=GaussianBlur(cvtColor(imread(raw_input()),6),(3,3),sigmaX=1)
x,y=Sobel(g,5,1,0),Sobel(g,5,0,1)
imwrite('s.png',sqrt(x*x+y*y))
```
### Without bonus, 136 bytes
```
from cv2 import*
from numpy import*
g=cvtColor(imread(raw_input()),6)
x,y=Sobel(g,5,1,0),Sobel(g,5,0,1)
imwrite('s.png',sqrt(x*x+y*y))
```
* Edit1: Replaced the named constans by their values.
* Edit2: Uploaded samples
[](https://i.stack.imgur.com/dCWIs.jpg)
[](https://i.stack.imgur.com/Ukb64.png)
[Answer]
# MATLAB, 212\*0.4=84.8 bytes
Using the filter toolbox and the HSV colorspace
```
function f(x);f=@(i,x)imfilter(i,x);s=@(x)fspecial(x);S=s('sobel');A=f(double(rgb2gray(imread(x)))/255,s('gaussian'));X=f(A,S);Y=f(A,S');imwrite(hsv2rgb(cat(3,atan2(Y,X)/pi/2+0.5,0*A+1,sqrt(X.^2+Y.^2))),'t.png')
```
or ungolfed
```
function f(x)
f=@(i,x)imfilter(i,x);
s=@(x)fspecial(x);
S=s('sobel');
A=f(double(rgb2gray(imread(x)))/255,s('gaussian'));
X=f(A,S);
Y=f(A,S');
imwrite(hsv2rgb(cat(3,atan2(Y,X)/pi/2+0.5,0*A+1,sqrt(X.^2+Y.^2))),'t.png')
```
[Answer]
# Love2D Lua, 466 Bytes
```
A=arg[2]i=love.image.newImageData q=math t=i(A)g=i(t:getWidth()-2,t:getHeight()-2)m={{-1,-2,-1},{0,0,0},{1,2,1}}M={{-1,0,1},{-2,0,2},{-1,0,1}}t:mapPixel(function(_,_,r,g,b)a=(r+g+b)/3 return a,a,a end)g:mapPixel(function(x,y)v=0 for Y=0,2 do for X=0,2 do v=v+(t:getPixel(x+X,y+Y)*m[Y+1][X+1])end end V=0 for Y=0,2 do for X=0,2 do V=V+(t:getPixel(x+X,y+Y)*M[Y+1][X+1])end end v=q.max(q.min(q.sqrt(V^2+v^2),255),0)return v,v,v end)g:encode('png',"o")love.event.quit()
```
Takes command line input, outputs to a file called "o" under your Love2D appsdata folder. Love2D Wont let you save files anywhere else.
Just about as golfed as I could get it, probably could be golfed further.
## Explained
```
-- Assign the Input to A
A=arg[2]
-- Assign some macros to save FUTURE BYTES™
i=love.image.newImageData
q=math
-- t is the original image, g is the new output image. g is two pixels smaller, which is easier and better looking than a border.
t = i(A)
g = i(t:getWidth()-2,t:getHeight()-2)
-- m and M are our two sobel kernals. Fairly self explanitary.
m = {{-1,-2,-1}
,{0,0,0}
,{1,2,1}}
M = {{-1,0,1}
,{-2,0,2}
,{-1,0,1}}
-- Convert t to grayscale, to save doing this math later.
t:mapPixel(function(_,_,r,g,b)a=(r+g+b)/3 return a,a,a end)
-- Execute our kernals
g:mapPixel(function(x,y)
-- v refers to the VERTICAL output of the Kernel m.
v=0
for Y=0,2 do
for X=0,2 do
v=v+(t:getPixel(x+X,y+Y)*m[Y+1][X+1])
end
end
-- V is the HORIZONTAL of M
V=0
for Y=0,2 do
for X=0,2 do
V=V+(t:getPixel(x+X,y+Y)*M[Y+1][X+1])
end
end
-- Clamp the values and sum them.
v = q.max(q.min(q.sqrt(V^2 + v^2),255),0)
-- Return the grayscale.
return v,v,v
end)
-- Save, renaming the file. The golfed version just outputs as 'o'
g:encode('png',"S_".. A:gsub("(.*)%....","%1.png"))
-- Quit. Not needed, but I'm a sucker for self contained LOVE2D
love.event.quit()
```
## Test
[](https://i.stack.imgur.com/Yf4Yf.png)
[](https://i.stack.imgur.com/WpAXl.png)
## And...
Although it doesn't actually improve my score (Makes it worse infact), here is the version with the colour wheel implemented.
900 - 270 = 630 Bytes
```
A=arg[2]i=love.image.newImageData q=math t=i(A)g=i(t:getWidth()-2,t:getHeight()-2)m={{-1,-2,-1},{0,0,0},{1,2,1}}M={{-1,0,1},{-2,0,2},{-1,0,1}}function T(h,s,v)if s <=0 then return v,v,v end h,s,v=h*6,s,v/255 local c=v*s local x=(1-q.abs((h%2)-1))*c local m,r,g,b=(v-c),0,0,0 if h < 1 then r,g,b=c,x,0 elseif h < 2 then r,g,b=x,c,0 elseif h < 3 then r,g,b=0,c,x elseif h < 4 then r,g,b=0,x,c elseif h < 5 then r,g,b=x,0,c else r,g,b=c,0,x end return(r+m)*255,(g+m)*255,(b+m)*255 end t:mapPixel(function(_,_,r,g,b)a=(r+g+b)/3 return a,a,a end)g:mapPixel(function(x,y)v=0 for Y=0,2 do for X=0,2 do v=v+(t:getPixel(x+X,y+Y)*m[Y+1][X+1])end end V=0 for Y=0,2 do for X=0,2 do V=V+(t:getPixel(x+X,y+Y)*M[Y+1][X+1])end end h=v H=V v=q.max(q.min(q.sqrt(V^2+v^2),255),0)h=q.atan2(H,h)/q.pi*2 return T(h,1,v,255)end)g:encode('png',"S_".. A:gsub("(.*)%....","%1.png"))G=love.graphics.newImage(g)love.event.quit()
```
[](https://i.stack.imgur.com/h2zir.png)
] |
[Question]
[
# The Challenge
Consider the following diagram of the Fifteen Puzzle in its solved state:
```
_____________________
| | | | |
| 1 | 2 | 3 | 4 |
|____|____|____|____|
| | | | |
| 5 | 6 | 7 | 8 |
|____|____|____|____|
| | | | |
| 9 | 10 | 11 | 12 |
|____|____|____|____|
| | | | |
| 13 | 14 | 15 | |
|____|____|____|____|
```
At every move, an excited puzzler has the opportunity to move one piece adjacent to the blank space into the blank space. For example, after `1` move, we have `2` possible scenarios (let `0` be a blank space):
```
1 2 3 4 1 2 3 4
5 6 7 8 5 6 7 8
9 10 11 12 and 9 10 11 0
13 14 0 15 13 14 15 12
```
After `2` moves, the puzzle has `5` different outcomes (Note that the two cases above are excluded, since they cannot be reached in 2 moves). One of these situations is the original solved state, and can be reached in two different ways.
Your task in this challenge is to produce the *number* of different outcomes that a certain number of moves can lead to. As input, take a number `N >= 0`, and output the number of **unique** situations that may appear after `N` moves.
# Rules
* This is code-golf. Shortest code wins!
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/31054) are disallowed.
* Your code should be able to compute the case for `N = 10` within a few minutes. I will likely not test this rule unless an obvious abuse of time exists in an answer.
# Test Cases
(Results generated from summations of [OEIS A089484](https://oeis.org/A089484) (As Geobits described in [chat](http://chat.stackexchange.com/transcript/message/21843954#21843954)), automated by Martin Büttner's [script](http://goo.gl/enPcI6). Thanks for all the help!)
```
0 moves: 1
1 moves: 2
2 moves: 5
3 moves: 12
4 moves: 29
5 moves: 66
6 moves: 136
7 moves: 278
8 moves: 582
9 moves: 1224
10 moves: 2530
11 moves: 5162
12 moves: 10338
13 moves: 20706
14 moves: 41159
15 moves: 81548
16 moves: 160159
17 moves: 313392
18 moves: 607501
19 moves: 1173136
20 moves: 2244884
21 moves: 4271406
22 moves: 8047295
23 moves: 15055186
24 moves: 27873613
25 moves: 51197332
26 moves: 93009236
27 moves: 167435388
28 moves: 297909255
29 moves: 524507316
30 moves: 911835416
31 moves: 1566529356
```
[Answer]
# Pyth, 36 bytes
```
lu{smmXd,0@dk)fq1.a.DR4,Txd0UdGQ]U16
```
[Demonstration](https://pyth.herokuapp.com/?code=lu%7BsmmXd%2C0%40dk)fq1.a.DR4%2CTxd0UdGQ%5DU16&input=10&debug=0). [Test harness.](https://pyth.herokuapp.com/?code=FQ11%2B%2BQ%22%20moves%3A%20%22lu%7BsmmXd%2C0%40dk)fq1.a.DR4%2CTxd0UdGQ%5DU16&input=10&debug=0)
```
lu{smmXd,0@dk)fq1.a.DR4,Txd0UdGQ]U16
.a.DR4,Txd0 Find the Euclidean distance between the
present location of 0 and a given location.
fq1 Ud Filter over all locations on that distance
equaling 1.
mXd,0@dk) Map each such location to the grid with 0
and the value at that location swapped.
{sm G Map all unique grids possible after n-1
steps to all unique grids after n steps.
u Q]U16 Repeat <input> times, starting with the
initial grid.
l Print the length of the resulting set.
```
[Answer]
# CJam, ~~54~~ ~~52~~ ~~51~~ ~~50~~ ~~49~~ ~~47~~ 45 bytes
```
G,ari{{:S0#S{4md2$4md@-@@-mh1=},f{Se\}}%:|}*,
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=G%2Cari%7B%7B%3AS0%23S%7B4md2%244md%40-%40%40-mh1%3D%7D%2Cf%7BSe%5C%7D%7D%25%3A%7C%7D*%2C&input=10) (should take less than 10 seconds).
### How it works
```
G,a e# Push R := [[0 1 ... 15]].
ri{ e# Do int(input()) times:
{:S e# For each S in R:
0# e# Push the index of 0 in S (I).
S{ e# Filter S; for each J in in S:
4md e# Push J/4 and J%4.
2$ e# Copy I.
4md e# Push I/4 and I%4.
@- e# Compute (I%4)-(J%4).
@@- e# Compute (J%4)-(I%4).
mh e# 2-norm distance: a b -> sqrt(aa + bb)
1= e# Check if the distance is 1.
}, e# Keep all values of J with distance 1 from I.
f{ e# For each J:
S e# Push S.
e\ e# Swap S at indexes I and J.
} e# This pushes an array of all valid modifications of S.
}% e# Collect the results for all S in R in an array.
:| e# Reduce the outmost array using set union (removes duplicates).
}* e#
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~289~~ 276 bytes
```
^
,abcd%efgh%ijkl%mnox,
(`(,[^,]*)x([^,%])([^,y]*),
$0$1$2x$3y,
(,[^,]*)([^,%])x([^,y]*),
$0$1x$2$3y,
(,[^,]*)x([^,]{4})([^,])([^,y]*),
$0$1$3$2x$4y,
(,[^,]*)([^,])([^,]{4})x([^,y]*),
$0$1x$3$2$4y,
,.{19},(?=.*1)|,[^,]{20},(?=[^1]*$)|y|1$
+)`([^,]{19})(.*),\1,
$1$2
[^a]
a
1
```
Takes input and prints output in unary.
You can put each line in a single file or run the code as is with the `-s` flag. E.g.:
```
> echo -n 111|retina -s fifteen_puzzle
111111111111
```
The core of the method is that we keep track of all possible positions (without repetition) which can occur after exactly `k` steps. We start form `k = 0` and repeat the substitution steps (using the `(` and )` modifiers`) until we reach the input number of steps.
During this computation our string always has the form of
```
(,[puzzle_state]y?,)+1*
```
where `puzzle_state` is `abcd%efgh%ijkl%mnox` with some permutation of the letters. `x` stands for the empty place, the rest of the letters are the tiles. `%`'s are row delimiters.
`y` marks that the state is generated in the current step (`k`) so it shouldn't be used to generate other states in this step.
`1`'s mark the number of steps left.
The basic mechanic of the Retina code is that every match of an odd line is changed to the next (even) line.
The code with added explanation:
```
initialize string
^
,abcd%efgh%ijkl%mnox,
while string changes
(`
for every old (y-less) state concatenate a new state with moving the empty tile to r/l/d/u if possible
right
(,[^,]*)x([^,%])([^,y]*),
$0$1$2x$3y,
left
(,[^,]*)([^,%])x([^,y]*),
$0$1x$2$3y,
down
(,[^,]*)x([^,]{4})([^,])([^,y]*),
$0$1$3$2x$4y,
up
(,[^,]*)([^,])([^,]{4})x([^,y]*),
$0$1x$3$2$4y,
if we should have made this step (there are 1's left) remove old states
,.{19},(?=.*1)
if we should not have made this step (no more 1's left) remove new states
,[^,]{20},(?=[^1]*$)
remove y markers
y
remove one 1 (decrease remaining step count)
1$
remove duplicates until string changes (with + modifier)
+`([^,]{19})(.*),\1,
$1$2
end while
)`
remove non-a's, 1 a stays from each state
[^a]
change a's to 1's
a
1
```
10 bytes saved thanks to @MartinButtner.
[Answer]
# Python, ~~310~~ ~~253~~ ~~243~~ 229 bytes
Latest version with improvement suggested by @randomra:
```
s=set()
s.add(tuple(range(16)))
def e(a,b):s.add(t[:a]+(t[b],)+t[a+1:b]+(t[a],)+t[b+1:])
for k in range(input()):
p,s=s,set()
for t in p:j=t.index(0);j%4and e(j-1,j);j%4>2or e(j,j+1);j<4or e(j-4,j);j>11or e(j,j+4)
print len(s)
```
My own version, which was longer (243 bytes), but easier to read:
```
s=set()
s.add(tuple(range(16)))
def e(a,b):s.add(t[:a]+(t[b],)+t[a+1:b]+(t[a],)+t[b+1:])
for k in range(input()):
p,s=s,set()
for t in p:
j=t.index(0)
if j%4:e(j-1,j)
if j%4<3:e(j,j+1)
if j>3:e(j-4,j)
if j<12:e(j,j+4)
print len(s)
```
Simple breadth first search, encoding the states as tuples, and storing them in a set to keep them unique.
Takes about 0.03 seconds on my laptop for N=10. Running time does increase substantially for larger numbers, for example about 12 seconds for N=20.
[Answer]
# Perl, 148
```
#!perl -p
$s{"abcd.efgh.ijkl.mno#"}=1;for(1..$_){$x=$_,map{$r{$_}=1if
s/($x)/$3$2$1/}keys%s for
qw!\w)(# #)(\w \w)(.{4})(# #)(.{4})(\w!;%s=%r;%r=()}$_=keys%s
```
Example:
```
$ time perl 15.pl <<<20
2244884
real 0m39.660s
user 0m38.822s
sys 0m0.336s
```
] |
[Question]
[
Write a program or function that takes in a single string containing only lowercase a-z, and prints or returns a **[truthy](http://meta.codegolf.stackexchange.com/a/2194/26997)** value if the word is the **feminine** version of the thing it represents and a **[falsy](http://meta.codegolf.stackexchange.com/a/2194/26997)** value if it is the **masculine** version. For example, `hen` is the feminine version for chicken and `rooster` is the masculine version, so `hen` might produce `1` and `rooster` might produce `0`.
Doing this for *all* English words that reflect gender would of course be way too unwieldy. Your program/function only needs to support 20 masculine/feminine pairs. Below are five sets of 10 masculine/feminine pairs, categorized by topic. **Choose any two of the sets; the 20 total pairs in these two sets are the 40 words your program/function must work for.**
(format is `masculine_version feminine_version`)
1. General
```
he she
him her
man woman
boy girl
male female
masculine feminine
guy gal
lad lass
mister miss
sir madam
```
2. Familial
```
father mother
dad mom
pa ma
son daughter
brother sister
husband wife
grandfather grandmother
grandpa grandma
uncle aunt
nephew niece
```
3. Animal
```
lion lioness
rooster hen
stallion mare
bull cow
drake duck
boar sow
buck doe
ram ewe
gander goose
billy nanny
```
4. Royal
```
king queen
prince princess
emperor empress
duke duchess
marquess marchioness
earl countess
baron baroness
baronet baronetess
lord lady
knight dame
```
5. Fantastical
```
wizard witch
giant giantess
incubus succubus
nidorino nidorina
nidoking nidoqueen
ents entwives
hanuvoite inimeite
centaur centaurides
merman mermaid
khal khaleesi
```
So, for example, you might choose the General and Familial categories. Then any input from `he` to `sir` or `father` to `nephew` would produce a falsy value, and any input from `she` to `madam` or `mother` to `niece` would produce a truthy value.
The values don't all have to be the same truthy/falsy type, e.g. `he` might produce `0` but `sir` might produce `false`. You may assume only the 40 specific lowercase a-z words from your two selected categories are ever input.
**The shortest answer in bytes wins. Tiebreaker is earlier post.**
(This challenge is not meant to correlate with or make statements about any [current gender-based social issues](https://www.google.com/search?q=gender%20neutrality&tbm=nws).)
[Answer]
# [Retina](https://github.com/mbuettner/retina), 26 bytes (sets 4, 5)
```
[^u]es|ee|m.i|y|^...c|d.*a
```
Retina is @MartinBüttner's regex language. I haven't used anything specific to .NET regexes, so you can test the regex at Regex101 [here](https://regex101.com/r/rN4nZ3/1). Alternatively you can use Retina's grep `G` mode like so:
```
G`[^u]es|ee|m.i|y|^...c|d.*a
```
and pipe in a file with one word per line for batch testing.
Retina outputs the number of matches by default, giving us our truthy/falsy value. The rule "the values don't all have to be the same truthy/falsy type" is pretty important though since `marchioness` matches twice, giving an output of 2.
(Using the mod-chaining method from the [previous](https://codegolf.stackexchange.com/questions/42206/distinguish-between-masculine-and-feminine-nouns-in-french-within-100-characters) male/female question seems to be shorter in CJam, but I'll let someone else do that)
[Answer]
# Retina, ~~39~~ 32 bytes (sets 2, 4)
Accounting for `marquess` was annoying, since using `ma` was the best way to get some of the feminines.
```
[^u]es|ma$|mo|y|[mie]e|wi|ter|au
```
[Try it here](https://regex101.com/r/rN4nZ3/3)
Thanks to Sp3000 for his golf suggestion.
[Answer]
# Retina, 28 bytes (sets 3,4)
```
w|[mhorse]e|[^u]es|duc|[dn]y
```
Retina uses .NET regex, but any flavor should work. [Test it at Regex101](https://regex101.com/r/vK4wB0/1).
] |
[Question]
[
Here's an interesting problem I thought of the other day, which involves bits of code competing against other bits of code not just in a property that the code has, but by playing a game against those other bits of code.
Your task is to build a program that takes the current state of a Go board, and determines what move to make or to pass.
Your program will accept the following as input:
* 19 lines, each with 19 characters, representing the pieces currently on the Go board. A character of `0` represents an empty square, `1` is black, and `2` is white.
* Two numbers representing the number of prisoner pieces each player has (black, then white).
* One number representing whose turn it is to move (black or white). As above, `1` is black, and `2` is white.
and output one of the following:
* A pair of coordinates `a b` representing the coordinates at which to move. `1 1` is the top-left square, and the first and second numbers represent moving down and to the right respectively.
* The string `pass`, which represents a move to pass.
For example, the program may receive the following input:
```
0000000000000000000
0000000000000000000
0000000000000000000
0001000000000002000
0000000000000000000
0000000000000000000
0001210000000000000
0000100000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0002000000000001000
0000000000000000000
0000000000000000000
0000000000000000000
0 0 1
```
which represents a game where only a few moves have been played.
Then the program might output `6 5`, which means "put a black stone on the point 6th from the top and 5th from the left". This would capture the white stone at `7 5`. The state of the board would then change to:
```
0000000000000000000
0000000000000000000
0000000000000000000
0001000000000002000
0000000000000000000
0000100000000000000
0001010000000000000
0000100000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0002000000000001000
0000000000000000000
0000000000000000000
0000000000000000000
1 0 2
```
(Note that although a white stone was captured, it counts as a prisoner for black.)
Your code must additionally satisfy the following properties:
* If your program is given the same input state, it must always produce the same output. This is the determinism of the Go AI. It must not have a random component.
* Your program must not take more than approximately 60 seconds to determine what move to make. This rule will not be strictly applied due to variations in computing power, but it must make a move in a reasonable amount of time.
* Your program's source code must not exceed a total of 1 megabyte (1,048,576 bytes).
* Your program must always make legal moves. Your program cannot make a move where a stone already exists, and cannot place a piece that would result in a group of its own stones being captured. (One exception to the rules for the purposes of this challenge is that a program is allowed to create a position that was originally there - because it is only given the current position of a board, it cannot be expected to store which moves had been made before.)
Your submission will then play in an all-play-all tournament against all the other submissions, in a game of Go where the state of the board begins as empty, and each program takes turns being fed the position of the board and making a move.
Each pair of submissions will play two rounds - one round with each player being black. Because the AIs in this problem are completely deterministic, two of the same AIs playing together will always result in exactly the same game being played.
Conditions for a win are as such:
* If your program plays to the end of the game, the Chinese scoring rules of Go will be used to determine the winner. No komi will be applied.
* If your program plays to the point that an earlier state is reached, thus causing an infinite loop, the two programs will be declared to have tied.
Your submission will be scored by how many points it scores against other submissions. A win is worth 1 point, and a tie is worth half a point. The submission with the most points is the overall winner.
---
This is a king-of-the-hill challenge, in which anybody can post a new entry at any time, and the standings will be re-evaluated periodically when this happens.
[Answer]
Here is my entry to get this challenge off the ground. Python code:
```
print "pass"
```
According to your rules always playing "pass" is a valid (albeit bad) strategy.
[Answer]
# Java : Pick a spot, any spot
Simply chooses spots on the board to test for validity. It uses the PRNG, but with a set seed so that's it's deterministic. It uses different chunks of the PRNG cycle depending on how many turns have passed.
For each candidate position, it checks to see that it's a valid move (but not that it's a *smart* move). If it isn't, it moves on to the next candidate. If it cannot find a valid move after 1000 tries, it passes.
```
import java.util.Random;
import java.util.Scanner;
public class GoNaive {
int[][] board;
boolean[] checked;
int me;
public static void main(String[] args) {
new GoNaive().run();
}
void run(){
int turns = init();
Random rand = new Random(seed);
for(int i=0;i<turns*tries;i++)
rand.nextInt(size*size);
for(int i=0;i<tries;i++){
int pos = rand.nextInt(size*size);
for(int c=0;c<size*size;c++)
checked[c]=false;
if(board[pos%size][pos/size] == 0)
if(hasLiberties(pos, me)){
System.out.print((pos%size+1) + " " + (pos/size+1));
System.exit(0);
}
}
System.out.print("pass");
}
boolean hasLiberties(int pos, int color){
if(checked[pos])
return false;
checked[pos] = true;
int x = pos%size, y=pos/size, n;
if(x>0){
n = board[x-1][y];
if(n==0 || (n==me && hasLiberties(y*size+x-1, color)))
return true;
}
if(size-x>1){
n = board[x+1][y];
if(n==0 || (n==me && hasLiberties(y*size+x+1, color)))
return true;
}
if(y>0){
n = board[x][y-1];
if(n==0 || (n==me && hasLiberties((y-1)*size+x, color)))
return true;
}
if(size-y>1){
n = board[x][y+1];
if(n==0 || (n==me && hasLiberties((y+1)*size+x, color)))
return true;
}
return false;
}
int init(){
int turns = 0;
board = new int[size][size];
checked = new boolean[size*size];
turns = 0;
Scanner s = new Scanner(System.in);
String line;
for(int i=0;i<size;i++){
line = s.nextLine();
for(int j=0;j<size;j++){
board[j][i] = line.charAt(j)-48;
if(board[j][i] > 0)
turns++;
}
}
String[] tokens = s.nextLine().split(" ");
turns += Integer.valueOf(tokens[0]);
turns += Integer.valueOf(tokens[1]);
me = Integer.valueOf(tokens[2]);
s.close();
return turns;
}
final static int size = 19;
final static int seed = 0xdeadface;
final static int tries = 1000;
}
```
[Answer]
Some Scala:
```
package go;
class Go {
def main(args : Array[String]) {
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
System.out.printLn("1 1")
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
readLine()
System.out.printLn("pass")
}
}
```
From reading Wikipedia, I think this will beat the current solution.
[Answer]
# Java
```
public class Go {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < 361;) {
char c = s.nextChar();
if (c != '\n') {
if (c == '0') {
System.out.println((i % 19 + 1) + " " + (i / 19 + 1));
System.exit(0);
}
i++;
}
}
}
}
```
Chooses the first empty space. Wins against any of the AIs as of time of posting.
] |
[Question]
[
# Summary
Code golf is good. [Pie is good](http://pieisgood.org). When you put the two together, only good stuff can happen.
# Specifications
In this challenge you will manage a pie shop. The user will be able to input five different commands: `list`, `count`, `buy`, `sell`, and `exit`. Here are the specifications for each:
* `list`
+ Print a list of all the pies owned, and how many. Separate with `|` and pad with a space on either side. `|`s must be aligned. Pie amount may be negative (that means you owe pie to someone `:(`). For example:
```
| apple | 500 |
| blueberry | 2 |
| cherry | -30 |
```
* `count [type]`
+ Print how many `{{type}}` pies there are. Print "There is no `{{type}}` pie!" if there is none. `{{type}}` will always match the regex `\w+` (i.e, it will always be a single word). For example, if I had the amount of pies shown in the above example list, then
```
> count apple
500
> count peach
There is no peach pie!
```
* `buy [n] [type]`
+ Add `{{n}}` to the count of `{{type}}` pie, and print it. Create `{{type}}` pie if it does not exist. `{{n}}` will always match the regex `[0-9]+` (i.e, it will always be a number). Here's another example (with the same pie inventory as the previous examples):
```
> count blueberry
2
> buy 8 blueberry
10
```
* `sell [n] [type]`
+ Subtract `{{n}}` from the count of `{{type}}` pie, and print it. Create `{{type}}` pie if it does not exist. Pie can be negative (oh no, that would mean you owe someone pie!).
```
> sell 15 blueberry
-5
> buy 5 blueberry
0
```
* `exit`
+ Print "The pie store has closed!" and exit the program.
```
> exit
The pie store has closed!
```
# Further clarifications
* If a non-existing function is called (the first word), then print "That's not a valid command."
* If an existing function is called with invalid arguments (the words after the first word), how your program behaves doesn't matter. "Invalid arguments" includes too many arguments, too little arguments, `{{n}}` not being a number, etc.
* Pie is good.
* Your input must be distinguished from your output. If you are running the program on the command line/terminal/shell/other text-based thing, you must prefix input with "`> "` (a "greater than" sign and a space) or some other shell input prefix thing.
* Pie is good.
* If all of these clarifications are not good enough, here's some sample output:
```
> list
> buy 10 apple
10
> sell 10 blueberry
-10
> list
| apple | 10 |
| blueberry | -10 |
> count apple
10
> count peach
There is no peach pie!
> exit
The pie store has closed!
```
* If you buy/sell pie and the net count becomes `0`, you can **either** keep it in the `list` or not, and you can **either** return `0` or `There is no {{type}} pie!` when you `count` it.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest code wins.
* Did I mention that pie is good?
[Answer]
### Ruby, ~~335~~ 330
```
h=Hash.new 0
loop{$><<"> "
puts case gets when/^list/
h.map{|x|?|+" %%%ds |"%h.flatten.map{|e|e.to_s.size}.max*2%x}when/^count (.*)/
h[$1]!=0?h[$1]:"There is no #{$1} pie!"when/^buy#{m=" (.*)"*2}/
h[$2]+=$1.to_i when/^sell#{m}/
h[$2]-=$1.to_i when/^exit/
puts"The pie store has closed!"
break else"That's not a valid command."end}
```
Some tricks here:
```
?|+" %%%ds |"%[*h].flatten.map{|e|e.to_s.size}.max*2%x
```
Doorknob's idea to use a formatter is taken a step further here, literally. First, the longest string in the hash among all keys and values is formatted using `" %%%ds |"` to produce a string like `" %6s |"`. Yep, no shrinkwrapping each column separately. There was never the requirement to. One size fits all. Then this string is duplicated and used as a formatting string for the two-element array containing the current row. Finally, the `+` near the start gets its word and prepends a single leading pipe. Oh, and `puts` has a nice handling of arrays.
Ruby has interpolation in regex literals. It's a tight save, but it does save a little.
Ruby requires semicolons after the `when` expression, but not before the keyword. This leads to a weird rendering artifact when the semicolon is replaced with a newline.
And, of course, perlism known as magic globals and automatic matching of regex literals against them.
Also, most statements including `case` are expressions.
[Answer]
# Ruby, ~~427~~ 384 characters
```
alias x puts
p={}
loop{
print'> '
case(u=gets.chop.split)[0]when'exit'
x'The pie store has closed!'
exit
when'list'
p.each{|k,v|printf"| %-#{p.keys.map(&:size).max}s | %-#{p.map{|e,a|a.to_s.size}.max}s |\n",k,v}
when'count'
x p[t=u[1]]||"There is no #{t} pie!"
when/sell|buy/
m=(u[0]<?s?1:-1)*u[1].to_i
if p[t=u[2]]
x p[t]+=m
else
x p[t]=m
end
else x"That's not a valid command."
end}
```
Thanks to Jan Dvorak of huge improvement from 427 to 384 (!)
[Answer]
# ~~Python~~ *Pie*-thon 437
I'm sure there is some slack on the second last line, but the requirement to align the bars for both the pie type and number is a doozy.
```
p,C,l={},"count",len
while 1:
a=raw_input("> ").split();c=a.pop(0)
if"exit"==c:print"The pie store has closed!";break
if"sell"==c:a[0]=int(a[0])*-1
if c in[C,"buy","sell"]:
y=a[-1]
if c!=C:p[y]=p.get(y,0)+int(a[0])
print p.get(y,"There is no %s pie!"%y)
elif"list"==c:
for i in p:print"| %s | %s |"%(i.ljust(l(max(p.keys(),l))),str(p[i]).rjust(max([l(str(x)) for x in p.values()])))
else:print"That's not a valid command."
```
As per Igby Largeman's comment the rules are unclear around what to do if there **was** a pie of a specific type, but there are `0` now. So I've interpreted it in my favour.
Sample output:
```
> buy 10 apple
10
> sell 1 blueberry
-1
> buy 1 keylime
1
> sell 3 apple
7
> buy 5 blueberry
4
> list
| keylime | 1 |
| apple | 7 |
| blueberry | 4 |
> sell 1 keylime
0
> count keylime
0
```
[Answer]
## C# - 571 568 559
Bringing up the rear as usual with the hopelessly verbose C#.
```
using C=System.Console;class Z{static void Main(){var P=new
System.Collections.Generic.Dictionary<string,int>();int i=0,n;a:C.Write
("> ");var I=C.ReadLine().Split(' ');var c=I[0];object s=c=="exit"?
"The pie store has closed!":"That's not a valid command.";if(c==
"count")try{s=P[c=I[1]];}catch{s="There is no "+c+" pie!";}if(c==
"buy"||c=="sell"){n=int.Parse(I[1]);n=c=="sell"?-n:n;try{n+=P[c=
I[2]];}catch{}s=P[c]=n;i=(n=c.Length)>i?n:i;}if(c=="list")foreach(
var p in P.Keys)C.Write("| {0,"+-i+"} | {1,11} |\n",p,P[p]);else C.
WriteLine(s);if(c!="exit")goto a;}}
```

I took some liberty with the rule about list output. To save some characters I hardcoded the width of the count column to the maximum width of an integer value. (The rules didn't say extra spaces weren't allowed.)
Formatted:
```
using C = System.Console;
class Z
{
static void Main()
{
var P = new System.Collections.Generic.Dictionary<string, int>();
int i = 0, n;
a:
C.Write("> ");
var I = C.ReadLine().Split(' ');
var c = I[0];
object s = c == "exit" ? "The pie store has closed!"
: "That's not a valid command.";
// allow Dictionary to throw exceptions; cheaper than using ContainsKey()
if (c == "count")
try { s = P[c = I[1]]; }
catch { s = "There is no " + c + " pie!"; }
if (c == "buy" || c == "sell")
{
n = int.Parse(I[1]);
n = c == "sell" ? -n : n;
try { n += P[c = I[2]]; }
catch { }
s = P[c] = n;
i = (n = c.Length) > i ? n : i;
}
if (c == "list")
foreach (var p in P.Keys)
C.Write("| {0," + -i + "} | {1,11} |\n", p, P[p]);
else
C.WriteLine(s);
if (c != "exit") goto a; // goto is cheaper than a loop
}
}
```
[Answer]
# Java - ~~772~~ ~~751~~ ~~739~~ ~~713~~ ~~666~~ 619
I know it's not winning the contest, but just for fun!
```
import java.util.*;class a{static<T>void p(T p){System.out.print(p);}public static
void main(String[]s){z:for(Map<String,Long>m=new HashMap();;){p("> ");s=new
Scanner(System.in).nextLine().split(" ");switch(s[0]){case"list":for(Map.Entry
e:m.entrySet())System.out.printf("|%12s|%6s|\n",e.getKey(),e.getValue());break;
case"count":p(m.get(s[1])!=null?m.get(s[1]):"There is no "+s[1]+" pie!\n");break;
case"buy":case"sell":long r=(s[0].length()==3?1:-1)*new Long(s[1])+(m.get(s[2])!=null?
m.get(s[2]):0);p(r+"\n");m.put(s[2],r);break;case"exit":p("The pie store has
closed!");break z;default:p("That's not a valid command.\n");}}}}
```
With line breaks and tabs:
```
import java.util.*;
class a{
static<T>void p(T p){
System.out.print(p);
}
public static void main(String[]s){
z:for(Map<String,Long>m=new HashMap();;){
p("\n> ");
s=new Scanner(System.in).nextLine().split(" ");
switch(s[0]){
case"list":
for(Map.Entry e:m.entrySet())
System.out.printf("|%12s|%6s|\n",e.getKey(),e.getValue());
break;
case"count":
p(m.get(s[1])!=null?m.get(s[1]):"There is no "+s[1]+" pie!");
break;
case"buy":
case"sell":
long r=(s[0].length()==3?1:-1)*new Long(s[1])+(m.get(s[2])!=null?m.get(s[2]):0);
p(r);
m.put(s[2],r);
break;
case"exit":
p("The pie store has closed!");
break z;
default:
p("That's not a valid command.");
}
}
}
}
```
[Answer]
## Python 3, 310
```
p={}
c=G=p.get
while c:
l=("exit list buy count sell "+input("> ")).split();c=l.index(l[5]);*_,n=l
if~-c%2*c:p[n]=(3-c)*int(l[6])+G(n,0)
print(["The pie store has closed!","\n".join("| %*s | %9s |"%(max(map(len,p)),k,p[k])for k in p),G(n),G(n,"There is no %s pie!"%n),G(n),"That's not a valid command."][c])
```
] |
[Question]
[
Create a program with the lowest amount of characters to reverse each word in a string while keeping the order of the words, as well as punctuation and capital letters, in their initial place.
By "Order of the words," I mean that each word is split by a empty space (" "), so contractions and such will be treated as one word. The apostrophe in contractions should stay in the same place. ("Don't" => "Tno'd").
(Punctuation means any characters that are not a-z, A-Z or whitespace\*).
* Numbers were removed from this list due to the fact that you cannot have capital numbers. Numbers are now treated as punctuation.
For example, for the input:
```
Hello, I am a fish.
```
it should output:
```
Olleh, I ma a hsif.
```
Notice that O, which is the first letter in the first word, is now capital, since H was capital before in the same location.
The comma and the period are also in the same place.
More examples:
```
This; Is Some Text!
```
would output
```
Siht; Si Emos Txet!
```
Any language can be used. The program with the lowest amount of characters wins.
[Answer]
### GolfScript, 58 54 48 characters
```
" "/{.{65- 223&26<}:A,\{.A{96&\)31&@+}*}%+}%" "*
```
This is a GolfScript solution which became rather long. Lots of the code is actually finding out if a character is in a-zA-Z. Maybe someone can find an even shorter way of testing it.
You can try the code [online](http://golfscript.apphb.com/?c=OyJIZWxsbywgSSBhbSBmaXNoLiIKCiIgIi97Lns2NS0gMjIzJjI2PH06QSxcey5Bezk2JlwpMzEmQCt9Kn0lK30lIiAiKg%3D%3D). Examples:
```
> Hello, I am fish.
Olleh, I ma hsif.
> This; Is Some Text!
Siht; Si Emos Txet!
> Don't try this at home.
Tno'd yrt siht ta emoh.
```
[Answer]
## APL 69
Takes screen input via: t←⍞
```
⎕av[1↓∊(↑¨v),¨((¯1×⌽¨z)+z←¯32×~1↓¨v>97)+¨⌽¨1↓¨v←(+\v<66)⊂v←0,⎕av⍳t←⍞]
```
[Answer]
### Coffeescript, ~~134~~ 133 characters
```
alert prompt().replace /\S+/g,(x)->c=x.match r=/[a-z]/gi;return x.replace r,(y)->return c.pop()[`(y<"a"?"toUpp":"toLow")`+"erCase"]()
```
Coffeescript is (for the purposes of code golf) a slightly denser version of javascript. It doesn't have the ternary operator, but it has an escape to javascript.
Here's the javascript version:
### Javascript, ~~152~~ 151 characters
```
alert(prompt().replace(/\S+/g,function(x){c=x.match(r=/[a-z]/gi);return x.replace(r,function(y){return c.pop()[(y<"a"?"toUpp":"toLow")+"erCase"]()})}))
```
Indented:
```
alert(prompt().replace(/\S+/g,function(x){
c=x.match(r=/[a-z]/gi);
return x.replace(r, function(y){
return c.pop()[(y<"a"?"toUpp":"toLow")+"erCase"]()
})
}))
```
[Answer]
# Ruby: 89 characters (including 1 for the `-p` switch)
Not copied [Jan Dvorak](https://codegolf.stackexchange.com/users/7209/jan-dvorak)'s [CoffeeScript solution](https://codegolf.stackexchange.com/a/11144), but after many attempts my code ended looking like an exact copy. A subconscious voice probably kept whispering “follow ~~the white rabbit~~ Jan Dvorak”. So upvotes for the algorithm should go to his answer.
```
$_.gsub!(/\S+/){|m|l=m.scan r=/[a-z]/i;m.gsub(r){|c|l.pop.send c<?a?:upcase: :downcase}}
```
Sample run:
```
bash-4.2$ ruby -p reverse-word.rb <<< "Hello, I am a fish.
This; Is Some Text!
Don't touch that!
S'm00ch1e"
Olleh, I ma a hsif.
Siht; Si Emos Txet!
Tno'd hcuot taht!
E'h00cm1s
```
[Answer]
# Lua, 143
```
print(((io.read"*l"):gsub("%w+",function(s)local r=""for i=1,#s do r=("")[s:byte(-i)>96 and"lower"or"upper"](s:sub(i,i))..r end return r end)))
```
[Answer]
# EcmaScript 6 (112 characters)
The input is provided in `s`.
```
alert(s.replace(/\S+/g,x=>(_=x.match(X=/[a-z]/gi),x.replace(X,a=>_.pop()[(a<"a"?"toUpp":"toLow")+"erCase"]()))))
```
*Based on @Jan Dorvak's answer.*
[Answer]
**C# (375)**
```
public static string rev(string s)
{
var r = new Regex("[^A-za-z]");
var result = "";
var token = "";
foreach (var c in s)
{
if (!r.IsMatch(c + ""))
{
token += c;
}
else
{
result += new string(token.Reverse().ToArray());
result += c;
token = "";
}
}
var arr = result.ToArray();
int i = 0;
foreach (var c in s)
{
arr[i] = char.IsUpper(c) ? char.ToUpper(arr[i]) : char.ToLower(arr[i]);
i++;
}
result = new string(arr);
return result;
}
```
Minified
```
public static string rev(string s){var r=new Regex("[^A-za-z]");var result="";var token="";foreach(var c in s){if(!r.IsMatch(c+"")){token+=c;}else{result+=new string(token.Reverse().ToArray());result+=c;token="";}}var arr=result.ToArray();int i=0;foreach(var c in s){arr[i]=char.IsUpper(c)?char.ToUpper(arr[i]):char.ToLower(arr[i]);i++;}result=new string(arr);return result;}
```
] |
[Question]
[
## Background
[**Conway's Soldiers**](https://en.wikipedia.org/wiki/Conway%27s_Soldiers) is a version of peg solitaire played on an infinite checkerboard. The board is initially full of pegs below an infinite horizontal line, and empty above it. Following the ordinary peg solitaire rules (move a peg by jumping over another one horizontally or vertically, removing the one that was jumped over), the objective is to move a peg as far above the horizontal line as possible.
Wikipedia page has the solutions for 1 to 4 units above the line: (A and B denote two possible alternatives.)
[](https://i.stack.imgur.com/WJPzi.png)
In ASCII notation (using alternative B):
```
X
X .
X . .
_X_ __._ __.__ ____.____
O OOO OOOOO OOOOOOOOO
O O OOO OOOO
OOOOO
OO
```
Conway proved that it is impossible to reach 5 units above the line with finite number of moves. To prove it, he assigned a value to each peg: if a peg is \$n\$ units away from the target position in terms of Manhattan distance, it is assigned the value of \$\varphi^n\$, where
$$
\varphi = \frac{\sqrt5 - 1}{2}
$$
(The value is the [golden ratio](https://en.wikipedia.org/wiki/Golden_ratio) minus 1.)
This value was carefully chosen to ensure that every possible move keeps the total value constant when a move is towards `X`, and decreasing when a move is away from it. Also, the final state must have a peg precisely at the target position, giving the value of \$\varphi^0 = 1\$, so the target position is unreachable if the initial configuration has the value sum less than 1.
For the target position at 5 units above the line, the configuration looks like this:
```
X
.
.
.
_____._____
OOOCBABCOOO
OOOOCBCOOOO
OOOOOCOOOOO
...
```
The peg at the position `A` is given \$\varphi^5\$, the ones at `B` are \$\varphi^6\$ each, and so on. Then he showed that the sum for the infinite number of pegs is exactly 1, and therefore the value sum of any *finite* subset is less than 1, concluding the proof of non-reachability.
## Task
Now, let's apply this measure to an arbitrary configuration, not just for the original problem, e.g. the pegs may surround the target position:
```
OOOOO
O...O
O.X.O
O...O
OOOOO
```
Given such a configuration, calculate Conway's measure on it and **output truthy if the measure is at least 1, falsey otherwise**. (Note that the truthy output does not *guarantee* that the target is actually reachable, while the falsey output *does* say that the target is too far away from the pegs to reach it.)
The calculated measure should be within `1e-6` margin. A program that produces wrong answers when the computed one falls within \$\pm10^{-6}\$ from the true measure is acceptable. You can use `(sqrt(5)-1)/2` or `0.618034`, but not `0.61803` or `0.61804`.
You can choose any three distinct symbols (characters, numbers, or any other kind of values) to indicate a peg, an empty space, and the target position respectively. You can take the grid as a matrix, a list of strings (or lists of symbols), or a single string (or a list of symbols) with a delimiter of your choice. You can assume that the input has exactly one target position, and it is not already occupied by a peg.
## Test cases
In the test cases below, `O` is a peg, `X` is the target position, and `.` is a blank.
### True
```
measure = 1 (0.61803 will fail all of the measure=1 cases)
OOX
--------------
measure = 1
OO.X
.O..
.O..
--------------
measure = 1
..X..
.....
.....
OOOOO
..OOO
--------------
measure = 1
....X....
.........
.........
.........
OOOOOOOOO
..OOOO...
.OOOOO...
...OO....
--------------
measure = 4
OOOOO
O...O
O.X.O
O...O
OOOOO
--------------
measure ~ 1.00813
X....OOOO
....OOOO.
...OOOO..
..OOOO...
.OOOO....
```
### False
```
measure ~ 0.618
OO.X
--------------
measure ~ 0.999975 (0.61804 will fail)
OOOOOOOOOOOOOOOOOOOOOO.X
--------------
measure ~ 0.9868
X....OOO
....OOOO
...OOOO.
..OOOO..
.OOOO...
--------------
measure = 0
.....
.....
..X..
.....
.....
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 109 bytes
```
lambda s,i=-1:sum(c%2*.618034**(abs((i:=i+1)//(n:=(h:=s.index)(0)+1)-(x:=h(2))//n)+abs(i%n-x%n))for c in s)>1
```
[Try it online!](https://tio.run/##hVNNj9owEL37V4xSIdlAvAnQbRope9tec@kBieYQgmmszZdsI0CI/et0nA@2VNp0DpOnmfdm3lhKczZ5XS2DRt32EP26FWm53aWg5zJy/VAfSppNFlP@7AfecjWd0nSrKZVhJGc@e3qiVRjRPIw0l9VOnBj1GNZdegqjnC4YMio2sxI5qdzTpGJsXyvIQFag2Yt/0@dyWxcaIrgQACd2QvDnFq0RLVrEEa3m5ErIMZeFgJ/qIEJsfAEl0h1Oag5mDkallcbZJZgaCqkN1HvsGfFbKI1so85WBFCKVB@UwI37ok4NbfWUcd0UEr@bRcKQJ06ZaAy8xj9elapVCFtc9oYNa3WTIOjMVLUBWshKhBH0k3CUSZXRR2ly6rgO6/ZqmKGyv3eTJXB/CCtPYAYbz85tL8tykb0BXnQUCgsIrF@qrbWsVkpkBgvDKS8R@NhoFN5L984F6VfYXHriNXHY7eNqn8TxmrgPQR7bfE14zHmXRpicry3LRp9jG4htHhW20kH2KYqH6EbGbTe@I1tseZ@uWvWOLM3mNb/jeMTjO/jc8wJ/SVqXvYPeAxkA/9fVmJd38Ow/1L3uCOc7xrevH5c/xH@kwXNwN0z@Nj74HmwPrh@H/QE "Python 3.8 (pre-release) – Try It Online")
Input is a list of integers, created by concatenating all rows of the grid. Each row is terminated by the number `0`. Use the numbers `1, 2, 4` to represents `"O", "X", "."`.
---
### [Python 3.8](https://docs.python.org/3.8/), 108 bytes
```
lambda s,i=-1:sum(c%2*.618034**(abs((i:=i+1)//(n:=s.find(0)+1)-(x:=s.find(2))//n)+abs(i%n-x%n))for c in s)>1
```
[Try it online!](https://tio.run/##hVJNb6MwEL3zK0auItlJcCFpuywSvXWvvuwBqenBIUaxlhhkGzVR1f71rM1H2qxUdg7DeN57M88Wzcnua7VOGn0uIducK37Y7jiYpczCODXtARez1Zw@xEm0vpvPMd8ajGWayUVMbm@xSjNDS6l2OCKuE@LjpbEijqDIwivkTIXHmSKkrDUUIBUY8hifX/eyEvBbtyINAG5AC75zYNNad7T65LsAB8FNqwVkUFY1t7gjYEJNU0n3fV69EMcTx0I0Fp7Yryeta53C1k374wDjhAi5ot@magu4kkqkGQyT3CjLtTWv0u4xChHp9xpYZOCZsAC0idAwy1AtmooXAqMcLdFmhciAbE9WGGyWgFpbhknX58ojJTb@UNRai8K6xninxwxiBzRaKotL9Obo7/D8NhDfXxA5f14/DhjLg/AqgmuY5gFllPZpgklp7lk@hsx8uNrnSWEnHWXfVmyMfiTrUHapfLPjfbvqbnDkaT7n9FKzCY8fENMoSuJ10LkcHAwegrGg/7qa8vIBkf//@9ed4Px08eP@8@ZX8R9p8pBcDAdfjY@@R9uj6@thfwE "Python 3.8 (pre-release) – Try It Online")
Pushing the input format a little bit here by using unprintable characters. Input is a single byte string of concatenated rows, where each row is terminated by a `NULL` character (code point `0`).
Replace `X` with the character `SOT` (code point `2`).
Byte string is essentially an integer list of code points. The reason I'm not using list of integer is because list doesn't have `find` method. The code points of the row terminator and `X` are chosen to be single digit.
---
**How**:
The length of each row (including the terminator) can be simply calculated as:
```
n:=s.find(0)+1 # terminator is represented as 0
```
Similarly, the target position is
```
x:=s.find(2) # X is represented as 2
```
We can then do some modular tricks to figure out the Manhattan distance between a position `i` and the target `x`:
```
abs(i//n + x//n) + abs(i%n + x%n)
```
All of these are shoved into a single expression by abusing walrus operator.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~111~~ 110 bytes
Thanks to @xnor for suggesting to use numbers as input, rather than a list of strings
```
g=input()
f=g.index;l=f(5)+1
c=i=0
for r in g:c+=r/9*.618034**(abs(f(2)/l-i/l)+abs(f(2)%l-i%l));i+=1
print c>1
```
[Try it online!](https://tio.run/##rVLRboMgFH3nK3hpBGX14sYy2rAfWfqwUbUkRo1zWff1zrarRYWmy5bckHu4F849B@qvdleVSaerbaqCIOhyZcr6oyUUZSpfmnKb7teFyoigEUdaGQUoqxrcYFPifKUj1cQyXD7yJ7h/CEPy@vZOMpLQuLgzcUGjM170eFFQujaR4qhuTNli/cy7nhKhz50pUsxX6T7V5DAJ7V4kw30kDIsN@gFwwsfkBGEO@244t9oddjh35DiGnsvOcRDJgCVM9OshAzsbqCcD@Ej/sSr9MRciZzfLq1X7@Ih3eBmbTI7PCOvp4GqPnHg98c@pyalM@Evwez/cimHyN/8Sl7t8ksVtVvh88JngdmDzDQ "Python 2 – Try It Online")
Input is a single list of numbers. Uses `9` for pegs, `0` for blanks, `2` for the target, and `5` as a line terminator.
---
### Python 2, 118 bytes
Solution provided by @Surculose Sputum
```
g=input()
f=g.find;l=f(',')+1;m=f('X')
c=i=0
for r in g:c+=(r<',')*.618034**(abs(m/l-i/l)+abs(m%l-i%l));i+=1
print c>1
```
[Try it online!](https://tio.run/##rY/dTsQgEIXveQrSZAMUnF3UGLMVn4Nb7bZdEpY2tUZ9@spPqY0mXu1cMGdmTr4Zhq/p3Lvbue5PjSKEzJ0ybnifKEOt6qA17lRZ1VIiCOOyugSpCUO1MuqA2n7EIzYOd8eaKzo@BVsJD/LxcHdflvTl9Y1e9vbG7C3jsdj5YmcZqwxXEg2jcROun@XsVyP0cTa2wfKIMG4@mxqHo@YCcoj/Fc/heyHFKV9VaIL2qkAF5zol0N4SfWkA0bEhiw0xGaLlKsdA3nl1ZLKFMrwaVs2Xb8R9C2uhiSzgN/@HCnql/4k0y2CxXZD5GZ/pxTc "Python 2 – Try It Online")
Uses `+` instead of `O` to represent a peg. Input is a single string where rows are terminated by commas (`,`).
---
### Original solution, 128 bytes
```
g=input();l=len(g[0]);g=''.join(g)
m=g.find('X')
c=i=0
for r in g:c+=(r<'-')*.618034**(abs(m/l-i/l)+abs(m%l-i%l));i+=1
print c>1
```
[Try it online!](https://tio.run/##hY7RTsMwDEXf8xVRpSlJs3ktoAmthO@INPUBuqzLlKVVKQK@vtRZu0WAhB9iX187x@1Xf2z83VA1e6MYY0OtrG/fey4Kp5zxvN5lpSjq0YNTY0ctyFnVcLB@z5lmglTKqowcmo521HpabyupePfEVkyksMkfs/uHNOUvr2/8vHYru3ZCBrEYxcIJUVipctJ21ve0es6H8QhCPo7WGZpvzaepON4mhl0ipU5Kghl0skxAAswJ2wD60sCIssQIGvM4ydDQ@LAlDQL@F3KOi4PVPCZjgVbYQdB1AVtToeFHJ8zgdDjphpgg11/x37/hEQ/0DfwrJnPmxJiYEkNiBiu/AQ "Python 2 – Try It Online")
Uses `+` instead of `O` to represent a peg. Input is a list of strings representing the rows
[Answer]
# [J](http://jsoftware.com/), 46 bytes
```
$(1<:1#.0.618034^1&#.)@(|@-"1{.)/@(#:I.)1 2=/,
```
[Try it online!](https://tio.run/##dZBBa8JAEIXv@ysGI24WkmfWipS1gaUFoVA60FNAWpGitFLoQS@l/e9pZs2KJvhgh8fsY@ZjdvUAekulI00ZFeSal4MeXp4W9TC1d84mKDCzt8XN9M2OEhif/vl8YH9hxj5N3COMpUk5zmqjnu9Bw8Qtm2Y5sj5Th83@UIKWjjbvH99@S6kGV/oTr2aO1USFgGwtFDMqBQaOxZx9AZW0RW1lUeOlXiZDNuauOo46zuDwyycnzZAzF4CSl77UCifPXYpA0E5v56to0N3Y7lFyINK5iBbrr/0PBa97N@ox9dQJRRx1jhWpIlRkMvU/ "J – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~86~~ 84 bytes
```
WS⊞υι≔⌕Eυ№ιX¹θ≔⟦⟧ζFLυF⁻⌕A§υιO⌕§υθX⊞ζ⁺↔⁻ιθ↔κ≔E²ιδF⌈ζ⊞δ↨…⮌δ²±¹I⊘⁺ΣEζ⁺§δ⊖ι§δ⊕ι×₂⁵ΣEζ§δι
```
[Try it online!](https://tio.run/##VZDLasMwEEX3@QqR1QhcQwJddeW6lBrqJiRdBEoXij21RWXJsaQ0zc@7I8d5VKBBmse5Vypq0RVGqL7/qaVCBpluvVu7TuoKOGdLb2vwEZP8YZJYKysNz1KXkIs2pFPjtQMZselmynnEZrR319aPz4gd6fplOgavqCtHMKIO91xqbwdaohQkLtMlHk5axFtMKQ5SN5UdH5VGY8eILRVBkq01yjscmTJ0Uusl/U0TF1PB@vykUp695eIgG9/A8UwuI/YoLEL6WyhMa9PCCvfYUaakuTntN6wEoWcDekn/5SAV1sGLUHssYfC1JmSQu/gcn0L0Jyw6bFA76pWD2Wst0/9qPJTfZYME3HnR4coYB/eUvOHfjJ9Ggq@@j@NNHE/isMa4CIvOIfZ3e/UH "Charcoal – Try It Online") Link is to verbose version of code. Uses exact surd arithmetic, and then converts the final surd to floating-point using \$ \sqrt 5 \$. Explanation:
```
WS⊞υι
```
Input the configuration.
```
≔⌕Eυ№ιX¹θ
```
Find the row that contains the `X`.
```
≔⟦⟧ζ
```
Start a list of `O` distances.
```
FLυ
```
Loop through each row.
```
F⁻⌕A§υιO⌕§υθX
```
Loop through each column that contains an `O`, and calculate the relative column offset from the `X`.
```
⊞ζ⁺↔⁻ιθ↔κ
```
For each relative column offset, add its absolute value to the absolute value of the relative row offset, and push that to the list of `O` distances.
(I would prefer to write the above as `F⁺↔⁻ιθ↔⁻⌕A§υιO⌕§υθX⊞ζκ` which is slightly more efficient but Charcoal can't take the absolute value of an empty list.)
```
≔E²ιδ
```
Now start generating negative Fibonacci numbers starting with \$ F\_0, F\_{-1} \$ and working down.
```
F⌈ζ⊞δ↨…⮌δ²±¹
```
Get the maximum distance and add that many more negative Fibonacci numbers.
```
I⊘⁺ΣEζ⁺§δ⊖ι§δ⊕ι×₂⁵ΣEζ§δι
```
Calculate the total distance using the formula \$ \sum \phi^{-n} = \frac 1 2 \left ( \sum L\_{-n} + \sqrt 5 \sum F\_{-n} \right ) \$ where \$ L\_n = F\_{n-1} + F\_{n+1} \$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes
```
ŒĠḊạ€Ɲ§µ5½’H*SS<1¬
SS>3aÇ
```
[Try it Online!](https://tio.run/##y0rNyan8///opCMLHu7oerhr4aOmNcfmHlp@aKvpob2PGmZ6aAUf2hpsY3hoDVdwsJ1x4uH2////RxvqGOoY6BjF6nBFG4CZBshMAA)
[All testcases](https://tio.run/##y0rNyan8///opCMLHu7oerhr4aOmNcfmHlp@aKvpob2PGmZ6aAUf2hpsY3hoDVdwsJ1x4uH2/4fbgWoi//@PjjbUMdQxio3VgbAMgGydaAMwywCJBZI3AMnCxaEQjQ0yAwyh4hA2TDfcBHSdZIjBbcJmI8TVcB9gisFUwsyD@R9mEkwGxjZCYiPEDZH8B/cXmntQ3IRityFSKONzN7obDZDii1gI04PmSkw3YroQ032YroO6B2pHbCwA "Jelly – Try It Online") This should yield 6 truthy then 5 falsey outputs (I added the extra cases `OX` and `X`, which cause special problems with this algorithm). See the [calculated value sums](https://tio.run/##y0rNyan8///opCMLHu7oerhr4aOmNcfmHlp@aKvpob2PGmZ6aAUf2hr8/3A7UDzy///oaEMdQx2j2FgdCMsAyNaJNgCzDJBYIHkDkCxcHArR2CAzwBAqDmHDdMNNQNdJhhjcJmw2QlwN9wGmGEwlzDyY/2EmwWRgbCMkNkLcEMl/cH@huQfFTSh2GyKFMj53o7vRACm@iIUwPWiuxHQjpgsx3YfpOqh7oHbExgIA "Jelly – Try It Online") if interested.
Takes input as a rectangular array, where `.OX` corresponds to `012` (empty, peg, target).
## How it works
```
ŒĠḊạ€Ɲ§µ5½’H*SS<1¬ # Is the value sum at least 1?
ŒĠ # Get an tuple of (coords of all 0 entries, coords of all 1 entries, coords of all 2 entries)
# If the matrix does not contain one of these, then that element of the tuple is left out, necessitating the SS>3 check
Ḋ # Dequeue: remove the irrelevant coords of all 0 entries
ạ€Ɲ # Get the absolute (x,y) offset of all 1 entries from the 2 entry
§ # Sum for Manhattan distance
µ # We are left with the Manhattan distances of each 1 from the 2
5½’H # (sqrt(5)-1)/2
* # to the power of
S # Each distance (S is sum, why is this an identity?)
S # Sum these powers to get the value sum
<1¬ # Is this not less than 1? (Jelly has no <= operator)
# As a side note, ‘ÆC counts the number of primes <= z+1
# This is the same number of bytes as <1¬ and also returns a nonnegative value iff z is at least 1
SS>3aÇ # Main link
SS>3 # Is the sum of all entries > 3? (this is necessary to deal with having no pegs or no blanks, which messes with ŒĠ)
a # and
Ç # the value sum is at least one
```
## Extras
Another 25-byte solution:
```
;0ŒĠḊạ€Ɲ§µ5½’H*SS<1¬
ḢLaÇ
```
21 bytes if `[[2]]` (target but no pegs) is not included as a testcase;
```
;0ŒĠḊạ€Ɲ§µ5½’H*SS
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 37 bytes
```
!>1s.e*/b9^t.n3+a/KxQ2JhxQ5/kJa%KJ%kJ
```
[Try it online!](https://tio.run/##K6gsyfj/X9HOsFgvVUs/yTKuRC/PWDtR37si0MgroyLQVD/bK1HV20s12@v//2hLHUsdAx0jHVMgCWIZILNiAQ "Pyth – Try It Online") (You can copy-paste formatted test cases from my Python answer)
Port of my Python answer. Input is a single list of numbers. Uses `9` for pegs, `0` for blanks, `2` for the target, and `5` as a line terminator.
```
!>1s.e*/b9^t.n3+a/KxQ2JhxQ5/kJa%KJ%kJ
KxQ2 Initialize K to be the index of 2 in the input
JhxQ5 Initialize J to be the index of 5, plus 1
.e Enumerated Map over the input, with b as the value, k as the index
.n3 pre-initialized constant: phi (~1.6180339)
t minus 1
^ raised to the exponent:
a/KJ/kJ absolute difference between K/J and (index)/J
+ plus
a%KJ%kJ absolute difference between K%J and (index)%J
(this gives us the manhattan distance between the current point and the target)
* Multiply by
/b9 divide b by 9, yields 1 if b is a peg, 0 otherwise
s Sum the mapped values
!>1 Return true if greater than or equal to 1, false otherwise
(We can't use "less than" because the first test case yields 1.0 exactly)
```
] |
[Question]
[
# Rules
In this challenge, I'm going to redefine the definition of "quotes" a bit.
* **Quotation marks** (AKA **quotes**) are *any identical characters* used in pairs in various writing systems to set off direct speech, a quotation, or a phrase. The pair consists of an opening quotation mark and a closing quotation mark, *which is the same character(case-sensitive).*
* If there are quote-pairs overlapping each other,
+ If a pair nesting another, both pairs are still valid.
+ If a pair not nesting another, the first starting pair remains valid. The other is no longer considered as a pair.
* When counting quoted characters(length of a pair of quotes),
+ The quotes themselves don't count.
+ Each pair's length is counted independently. Overlapping doesn't affect another.
# Goal
Your goal is to print the total length of all valid quotes. This is code golf, therefore the code with the fewest bytes wins.
# Examples
```
Legend:
<foo>: Valid quotes
^ : Cannot be paired character
Input : ABCDDCBA
`A` (6): <BCDDCB>
`B` (4): <CDDC>
`C` (2): <DD>
`D` (0): <>
Output : 12
Input : ABCDABCD
`A` (3): <BCD>
`B` (0): ^ ^
`C` (0): ^ ^
`D` (0): ^ ^
Output : 3
Input : AABBBBAAAABA
`A` (0): <> <><> ^
`B` (0): <><> ^
Output : 0
Input : ABCDE
Output : 0
Input : Print the total length of all "quoted" characters
`r` (40): <int the total length of all "quoted" cha>
`n` (14): <t the total le>
`t` (15): < > <o> <h of all "quo>
` ` (7): ^ <total> <of> ^ ^
`h` (0): ^ ^ ^
`e` (8): < total l> ^ ^
`o` (0): ^ ^ ^
`a` (0): ^ ^ ^ ^
`l` (0): ^ ^ <>
`"` (0): ^ ^
`c` (0): ^ ^
Output : 84
Input : Peter Piper picked a peck of pickled peppers
`P` (5): <eter >
`e` (9): <t> ^ <d a p> <d p> ^
`r` (0): ^ ^
` ` (3): ^ ^ <a> <of> ^
`i` (5): <per p>
`p` (3): <er > ^ ^ ^ <>
`c` (8): <ked a pe> ^
`k` (7): ^ < of pic>
`d` (0): ^ ^
Output : 40
Input : https://www.youtube.com/watch?v=dQw4w9WgXcQ
`h` (27): <ttps://www.youtube.com/watc>
`t` (0): <> ^ ^
`/` (0): <> ^
`w` (14): <><.youtube.com/> <4>
`.` (7): <youtube>
`o` (0): ^ ^
`u` (1): <t>
`c` (0): ^ ^ ^
`Q` (8): <w4w9WgXc>
Output : 57
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 36 [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")
Full program. Prompts for input from stdin.
```
≢∊t⊣{t,←'(.)(.*?)\1'⎕S'\2'⊢⍵}⍣≡⍞⊣t←⍬
```
[Try it online!](https://tio.run/##XYxBS8NAEIXv/RVDL2lFExQvClKS1nuLBz30sm62SejaHdOJSxGv2gYiXrwWbK9e@4fmj8SNB1t8MAPv470nUJ/EC6FNUvPyDWtebXhZEpfbZzrm1w@v43c7/lGvOz71@P3zxhufeVxuuNq9cLXl1RdXaxcmF@Xqu9mo4VfYCqP@YNCPwtYhaG4PwsgpdPqXuv5zwzybEVCqgAwJDVrNEkrBTEBoDe3HwpCK2yBTkQtJKp/vm8pZGGboPmZyqmIQgEpOm3IDtCOoEA9LKRHOL4PAWusvTEHFvfKleQisIJn2nq7ikT23F7fJnRz9AA "APL (Dyalog Unicode) – Try It Online")
`t←⍬` set up an accumulator `t` (for **t**otal)
`⍞⊣` discard that in favour of string input from stdin (symbol: quote in console)
`{`…`}⍣≡` apply the following anonymous lambda until stable (fix-point; previous ≡ next)
`⊢⍵` on the argument
…`⎕S'\2'` PCRE **S**earch for the following, returning group 2 for each match:
`(.)` any character (we'll call this group 1)
`(.*?)` as few characters as possible (we'll call this group 2)
`\1` the group 1 character
`t,←` update `t` by append that to `t`'s current value
`t⊣` discard that (the final list of no matches) in favour of `t`
`≢` count the number of characters in that
[Answer]
# JavaScript (ES6), 64 bytes
```
f=([c,...a],i=a.indexOf(c))=>c?(~i&&i+f(a.splice(0,i+1)))+f(a):0
```
[Try it online!](https://tio.run/##dY5BT4NAEIXv/opND@1uigtVjNoEG2g92540MR7WYYC1K7vCUPTiX0dIGj1QXzJzeO/ly3tTB1VDpR2dlzbFrssi/gyelFK9eDpSUpcpfj5kHISI7mDFv/V0qucZV7J2RgPywNPzhRBi8MQy6MCWtTUojc15xmdxst5s1kk8E4L5PltcnJ0oDHcsXI7yOOkV9/qFBKcY9/@F20qXxKhARpaUYQbLnApmM6aMYZOPxhKmEwaFqhQQVvURdBOOSNjHbKtd/52GPaZMMYewH2CDYXrHoXN/kHA0pyBy9dL327aVX7ah5hUl2He/VQTF6hCluzZsbx/zJ9gdGVfX3Q8 "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking either the input string
// or an array of characters, split into
[c, ...a], // c = next character and a[] = all remaining characters
i = a.indexOf(c) // i = index of the 1st occurrence of c in a[] (-1 if not found)
) => //
c ? // if c is defined:
( ~i && // if i is not equal to -1:
i + // add i to the final result
f(a.splice(0, i + 1)) // remove the left part of a[] up to i (included) and
) // do a recursive call on it
+ f(a) // add the result of a recursive call on a[]
: // else:
0 // stop recursion
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 49 bytes
Recursive solution. Find quote groups, count their lengths, and then recursively look for sub-group lengths and sum everything together.
```
f=->s{s.scan(/(.)(.*?)\1/).sum{|a,b|b.size+f[b]}}
```
[Try it online!](https://tio.run/##FYtBbsIwEEX3OcUIsUhasFWpmyJRrhBWrUQRsp1JbGFikxnXosDZ02TzvvT035D0bRzb7fqT7iTIqL6UpahK8bKrft5kJShd7g@10g8tyP3ha3vQx@dzzNZ5hA6ZCoiJCZanFbSH5elYYN@M9eB6BrYIHFh58Nh3bCG0oLyHxTUFxmYBxqpBGcaBihqngdrFidGZMzagIKI5z9Es/GQixjifLXOkjZQ5Z3ELiZNGYcJFZsXG7n63zT6/54@v7tvs/wE "Ruby – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 100 bytes
```
({{<({}<>)<>(({<>(({}({})<>[({}<>)]))(){[{}()](<>)}{}}{}){(<>)})<>{}>{<>({}<<>({}<>)>)<>}<>[{}]}{}})
```
[Try it online!](https://tio.run/##JUxBCsMwDPuK6ck@9Aclb9i95OB16VIWEpZ5J5O3p04LQraEpGflI8974k/vqLqgtsXR4hD1omYwud6@J0LS1VzyaLppM5Bev8W0uVGz7M2OxpZdq/gRpt4f9cgCEgNIEU6QQn5LhLIDpwTT918kvCbYIlfeJNRfn/kE "Brain-Flak – Try It Online")
### Commented
```
# Loop over each character in input and sum iterations:
({{
# Evaluate matching quote search as zero
<
# Move opening "quote" to right stack
({}<>)<>
# Until match or end of search string found:
# Note that the character to search for is stored as the sum of the top two entries in the right stack.
(
({
<>((
# Character to search for
{}({})
# Subtract and move next character
<>[({}<>)]
# Push difference twice
))
# Add 1 to evaluation of this loop
()
# If no match, cancel out both 1 and pushed difference to evaluate iteration as zero (keep one copy of difference for next iteration)
# (compare to the standard "not" snippet, ((){[()](<{}>)}{}) )
# Then move to other stack
{[{}()](<>)}{}
# If a match was found, this will instead pop a single zero and leave a zero to terminate the loop, evaluating this iteration as 0+1=1.
# Push 1 if match found, 0 otherwise
}{})
# If match found, move to left stack and push 0 denote end of "quoted" area.
{(<>)}
# Push the same 1 or 0 as before
)
# Remove representation of opening "quote" searched for
# The closing quote is *not* removed if there is a match, but this is not a problem because it will never match anything.
<>{}
>
# Move searched text back to left stack, evaluating each iteration as either the 1 or 0 from before.
# This counts characters enclosed in "quotes" if a match is found, and evaluates as 0 otherwise.
{<>({}<<>({}<>)>)<>}
# Remove 0/1 from stack; if 1, cancel out the 1 added by the closing "quote"
<>[{}]
# Repeat until two consecutive zeroes show up, denoting the end of the stack.
# (Because closing quotes are not removed, it can be shown that all other zeroes are isolated on the stack.)
}{}})
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
œṡ¹¡ḢṖẈ;߀ƲS
```
[Try it online!](https://tio.run/##AV0Aov9qZWxsef//xZPhuaHCucKh4bii4bmW4bqIO8Of4oKsxrJT/8OHxZLhuZj//1ByaW50IHRoZSB0b3RhbCBsZW5ndGggb2YgYWxsICJxdW90ZWQiIGNoYXJhY3RlcnM "Jelly – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~65~~ ~~64~~ 62 bytes
```
f=s=>(s=/(.)(.*?)\1(.*)/.exec(s))?f(s[3])+f(s=s[2])+s.length:0
```
[Try it online!](https://tio.run/##lU7LTsMwELzzFVZPNgi7vA4UmShpkSpOLRwAFaQaZ/OgJjbxpoavD444Eg6MtDurGc1o39Reed3WDo8bm0PfF9LLa@qloJxRfpiw55NITHD4BE09Y0lB/ebshR1Fln5zGi/PDTQlVrNpf6Vt460BbmxJi22azReLeZZu2cGIM8yIk2YRacRfuZvf8qqtGyRYAUGLypCfh4gtiDKGTD46i5BPiK5UqzRC60cqIOpkVbu4Xa13kBNFHOjd0DIIJioOnBtNV4jOz4QIIfAv22H3ClzbdxEU6irZy3wdzsPlQ/mo1/8P22V5cX/7dLdMpzHcfwM "JavaScript (Node.js) – Try It Online")
Original approach (64 bytes):
```
f=(s,r=/(.)(.*?)\1/g,t=r.exec(s))=>t?f(t=t[2])+t.length+f(s,r):0
```
[Try it online!](https://tio.run/##lY49T8MwEIZ3foXVyabFKQgGikyUtkgVU1sGQIBU41w@qImNfanh1wdHjISBV7obnlfP6d7kQXrlaosnjcmh6wpB/cSJhHJG@XHKnk@TcoLCcfgERT1j4hrTgqLAp7MXNkauoSmxGhe9xmbT7kqZxhsNXJuSFrtsvlguF/Nsx44Gmn4Gmmwek8X85d38xmtXN0iwAoIGpSY/fxFTEKk1GX20BiEfEVVJJxWC8wMnIHKyrm3ctlZ7yIkkFtS@v9IDHYkFawftCtH6WZKEEPiXabF9Ba7MexIkqio9iHwTzsPlffmgNv@Xzaq8uLt93K6yaZS7bw "JavaScript (Node.js) – Try It Online")
```
f=s=> // Main function:
(s=/(.)(.*?)\1(.*)/.exec(s))? // If a "quoted" segment can be found:
f(s[3]) // Return the recursive result outside this segment,
+f(s=s[2]) // plus the recursive result of this segment,
+s.length // plus the length of this segment
:0 // If not: no quoted segment, return 0.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
œṡḢẈṖ$Ḣ+ɼṛƲ)Ẏ$F¿®
```
[Try it online!](https://tio.run/##y0rNyan8///o5Ic7Fz7csejhro6HO6epAFnaJ/c83Dn72CbNh7v6VNwO7T@07r/BoZVAITfrRw1zFHTtFB41zLU@3M51uP1R05rI//@juaLVHZ2cXVycnRzVY3WgPBCG8hydgMARCJDlXSHMgKLMvBKFkoxUhZL8ksQchZzUvPSSDIX8NIXEnBwFpcLS/JLUFCWF5IzEosTkktSiYqi2VCBbISCzAEgWZCZnp6YoJCoUpCZng3SCBHKAIgWpBQVwHRklJQXFVvr65eXlepX5pSWlSal6yfm5@uWJJckZ9mW2KYHlJuWW4ekRyYHqsVyxAA "Jelly – Try It Online")
A full program that takes a single argument, the input string wrapped in a list, and returns the number of quotes characters as an integer.
] |
[Question]
[
## Challenge
Given two strings in any default I/O format, do the following:
**NOTE: The challenge will refer to the first string as the "data" and the second referred to as the "program".**
1. Change the program to an infinite string which is just the program repeated infinitely (e.g. `10` --> `1010101010...`). The challenge will refer to this as the "infinite program"
2. While the data is non-empty, do the following while looping over the infinite program:
a. If the current command is "0", delete the left-most bit in the data. If the data is empty, "0" does not do anything.
b. If the current command is "1", append the next character in the program to the data if the left-most bit in the data is a one.
c. If the data is not empty now, output the data.
## Test Cases
Data is the left side of the input and the program is the right side.
```
100, 0 --> 00, 0
1111, 1 --> 11111, 111111, 1111111, ...
10, 011 --> 0, 0, 0
1110, 011 --> 110, 1101, 11010, 1010...
```
## Notes
* The data and program will consist of only 0s and 1s
* For data/programs that do not halt, your program does not need to halt.
* The data and program will not be empty in the input.
* You may have multiple trailing and leading newlines
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden
* You can use [any convenient I/O format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
As always with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), **shortest code wins**!
[Answer]
## Haskell, ~~77~~ ~~71~~ 62 bytes
```
f@(d:e)#(p:q)=f:[e,f++take d q]!!p#q
_#_=[]
a!b=tail$a#cycle b
```
[Try it online!](https://tio.run/##hY2xCsMgGIR3n@IXMyQkg106CELfQ37Cn2ioxKbaZunTW5FQOrV3yx183F3puboQcl4urVWuE21UqdOLMm5Y@n6n1YGFhJxHkdgoRm2QEZ/0Tj40JObXHBxM@UZ@Aw32zgDiw287NPBRyzswp0EOEkszEr@g@nAu4YCqsST8tYS1GVnhP2sFPsD8Bg "Haskell – Try It Online")
Edit: -9 bytes thanks to @xnor.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 82 bytes
```
m=>n=>{for(int i=0;m!="";Print(m=n[i++]<49?m.Substring(1):m[0]>48?m+n[i]:m))n+=n;}
```
[Try it online!](https://tio.run/##LYuxCsIwFAB3v0IzJaRKCh206UtxcRYcSxYDkTe8V2jSSfrtaUCXg4O7kM4hYXmsHIaUF@RPcw8ZZ/6bcxEKgWNw3zgvEjkfEYylEwhhnzXJkoAn1NoP3W2ky2t9/1bZqp4m4113HUnXxPekFGtguxV7iFK0xgglRYUtOw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~24~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[¹Nèi¬i¹N>è«}ë¦}DõQ#=
```
Takes the program as first input and data as second input.input.
[Try it online.](https://tio.run/##yy9OTMpM/f8/@tBOv8MrMg@tyQQy7A6vOLS69vDqQ8tqXQ5vDVS2/f/fwNCQy9AAAA)
**Explanation:**
```
[ # Start an infinite loop:
¹Nè # Get the N'th digit of the first (program) input
# (NOTES: N is the index of the infinite loop;
# indexing in 05AB1E automatically wraps around)
i # If this digit is 1:
¬ # Push the head of the current data (without popping it)
# (will take the second (data) input implicitly if it's the first iteration)
i } # If this head is 1:
¹N>è # Get the (N+1)'th digit of the first (program) input
« # And append it to the current data
ë } # Else (the digit is a 0 instead):
¦ # Remove the first digit from the current data
# (will take the second input (data) implicitly if it's the first iteration)
DõQ # If the current data is an empty string:
# # Stop the infinite loop
= # Print the current data with trailing newline (without popping it)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~62~~ 59 bytes
```
->c,d{p(d)while(a,*c=c;b,*d=d;c<<a;[]!=d=[b]*a+d+c[0,a*b])}
```
[Try it online!](https://tio.run/##ZcrLCsIwFATQfb@iIphHb0uyNU1/JAS5SewDKoaqiJR@e2wLrpzdmZnp5T6p1alsPIQ50sDe/TBeKQL32isHPOigfF2jMvaggzbOcixC4Y0A5M6yJXW6bBDcHPPWuMr3OD2qG0Z6Oj/vl4EB/nd2yTpDpBAEiCA2O25aQyAncvU@bhDyRyn38@b0BQ "Ruby – Try It Online")
### How
* Get the first bit from code `c` and data `d`, call them `a` and `b`. Put `a` back at the end of `c`.
* Put back `b` at the beginning of `d` if `a==1`. This can be shortened to `[b]*a`
* Put the first byte of `c` at the end of `d` if `a==1 and b==1`. This can be shortened to `c[0,a*b]`.
* If we have more data, print and repeat.
[Answer]
# [J](http://jsoftware.com/), 65 bytes
```
(([:(][echo)(}.@[)`([,{.@[#1{],])@.({.@]));1|.])&>/^:(0<0#@{>)^:5
```
[Try it online!](https://tio.run/##XUw7CgIxFOxzisEF8x7EmBQ2iS4BwcrKNrxFEJfFxgNEzx6z24gyDMyPedSV1SMOARoGDqFxY3G8nE@VKAeSfL9NT6a3TZmvlE1povNFjHCy1JwwR/@ywut@OwRye9el0vMQdpWVGuHbpUOEU/MTtF6yhgj/Ey2jufgffpv6AQ "J – Try It Online")
I may golf this further later. Note the `5` at the end would be infinity `_` in the actual program, but I've left it there to make running the non-halting examples easier.
[Answer]
# [Python 3](https://docs.python.org/3/), 74 bytes
```
def f(d,p):
while d:c,*p=p+p[:1];d=(d[1:],d+p[:1]*d[0])[c];d and print(d)
```
[Try it online!](https://tio.run/##JYmxCoQwEAX7@4otE2@LBLuIX7JsIXkGBYmLCMd9fVRkmmHG/uey1741zIWKA5tPH/ot6zYTUubORvuapKgDRgeJSRlv6CBBveT70FRBdqz1dPCtOIn8EJQlPKa@XQ "Python 3 – Try It Online")
Arguments: `d`: data, `p`: program.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 178 bytes
```
void a(std::string s,std::string d){while(!s.empty())for(int i=0;i<d.size();i++){if(d[i]=='0')s.erase(0,1);else if(s[0]=='1')s.push_back(d[(i+1)>=d.size()?0:i+1]);std::cout<<s;}}
```
[Try it online!](https://tio.run/##hY7NboMwEITP4Skc9xBb0MS@YkMeJIkq13aSVcEgbFq1iGenhqh/UqTObWe@nV3dto8XracHcLrqjUXShw7cpUx@HGiiZ1VdTq8NGKSIDybPbxzy2e/J0OHtCpUla7@1dRveCaXnpiPgAoKCCZBm6@HDEiogTekAZ2IOcCqKDdvQuNIpbwnLOBW28hbF2B/YHPM5bnt/fXpW@iUuEUg5LYuvuj3Lo3GiYvlGN32Q0otxnObLtQJH6JCsFMGcMZwhzDAVKOobR1IifHRHh0Wy2u1mMmpG@Q29Ty6NSyH/l@N/yPtcZ0PfOcREMk6f "C++ (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~96~~ 82 bytes
```
def g(d,p):
while d:
c=p[0];p=p[1:]+[c];d=[d[1:],d+[p[0]]*d[0]][c]
if d:yield d
```
[Try it online!](https://tio.run/##VU/BbsMgDD2Hr7DaA8mKUuhuqbJjf6DaCeVAC0lZm8AI0dqvz0xaTZoP2M/Pfs/4R7y4YTfP2rTQ5Zr5oiLwc7E3A7oi2bn2kjd7j0lUzUaem72upU6A6Y1MZPOm04sUyWyLWw9rbhr0vIYOptGMoEJQjxFcC4IiGjRwzK0LYAc/xRG24KaIFVnDaYoQHfTqaiBezHNi@6TBqNGakPhglC7LkqSzD6@zMwU1SLxiUWZ33AUzTL0JKpq8y3vlcztEdrNjzHVRsH8NX2CgSKY2tbyjSvqM/RC8Sg2KZrTZn9D3SjIfcA0kpeWXs8MiPMbA7kWRrBdj1RByyKngnDLKabEADMqAihfkCXAh/thlNuF5dXS9gWNEo25FpGA79t6Qpfk5fE8uGv1ifwE "Python 2 – Try It Online")
Stealing a bit from [Emodiment of Ignorance's answer](https://codegolf.stackexchange.com/a/182793/69880)...
A generator which uses lists of 1's and 0's for input / output.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 40 bytes
```
;€Ø2œịxØ1œị$Ʋ$Ḋ€2,1œị$?1¦ṙ€1$2¦µ⁺1ịGṄƲ¿Ḣ
```
[Try it online!](https://tio.run/##y0rNyan8/9/6UdOawzOMjk5@uLu74vAMQzBD5dgmlYc7uoBSRjpQEXvDQ8se7pwJFDJUMTq07NDWR427DIES7g93thzbdGj/wx2L/v@PNtQBQYNYnWgDECuWiysalYtsnYrKoZ1wG@3JsA/DOgA "Jelly – Try It Online")
I’ve assumed trailing newlines are ok. I’ve also gone with a list of two lists of zeros and ones as input, and output to stdout.
[Answer]
# [Python 1](https://www.python.org/download/releases/1.6.1/), 75 bytes
```
a,b=input()
while a:b=b[1:]+b[:1];a=[a[1:],a+b[:1]*a[0]][b[0]];print a or''
```
[Try it online!](https://tio.run/##K6gsycjPM/z/P1EnyTYzr6C0REOTqzwjMydVIdEqyTYp2tAqVjsp2sow1jrRNjoRxNVJhAhoJUYbxMZGJ4FI64KizLwShUSF/CJ19f//ow11wDBWBygJAA "Python 1 – Try It Online")
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~294~~ ~~289~~ 272 bytes
-22 bytes thanks to @ceilingcat
```
#import<cstdio>
#import<queue>
void a(char*e,char*p){std::queue<char>d;for(;*e;)d.push(*e++);for(char*c=p;d.size();c=*++c?c:p){*c-49?d.pop():d.front()-48?d.push(c[1]?c[1]:*p):a("","");if(d.size()){for(int i=0;i++<d.size();d.pop())d.push(putchar(d.front()));putchar(32);}}}
```
[Try it online!](https://tio.run/##PY5NboQwDEbXwylQuokJINLOok34OUjVBXJCJ4shaQhdFHF2GtAwG1v@ZL9ndK74Rty2F3N31ocap6CMbZNz/pn1rNvk1xqV9hRvvc90fjQHS9wV4tio96hVcrCeykxLUKWbpxvNNGNwpMcNNk6qcjJ/moLEJmMMOxSRlGFx/ejikXUUhCoHb8dAobi@dw8SfvKvbi8imkVPCckJAWkGegJh2T1mDKlpKmkYq5@qB/j8ys1hf4c@PQDyzN5eQa7ruu2ce29GCumSXKKPc16RPCUV59GbXLwOsx/TSibr9g8 "C++ (gcc) – Try It Online")
Fairly straightforward algorithm. Copies the data into a queue, and repeatedly loops through the program. On a "0", it removes the first element in the queue (the first "bit"). On a 1, it adds the next "bit" of the program to the data if the first "bit" of the data is 1. Then it loops through the data, printing it "bit" by "bit", and finally prints a space to separate successive data entries.
] |
[Question]
[
[Scratch](https://scratch.mit.edu) is a visual programming language. For the sake of counting bytes, Scratch is usually written in scratchblocks2 syntax.
Post tips that specifically apply to Scratch or scratchblocks2.
[Answer]
## Abuse the bool type
In Scratch the true and false values are equivalent to 0 and 1, so you can perform arithmetic operations over them. A practical example would be finding the sign of a number:
```
define f(n
set[r v]to(<(n)>(0)>-<(n)<(0
```
[Answer]
# Use a Function if Possible
Where possible, if the challenge says functions are allowed, use them! The syntax for defining a function is almost always shorter than the usual `when gf clicked`.
For example:
```
define f(n
say((n)+(1
```
Over:
```
when gf clicked
ask()and wait
say((answer)+(1
```
This also means one doesn't have to use the `answer` variable, which is quite longer than `n`.
[Answer]
# Alternatives to Ternary "if...else" operators
As of the time this answer is posted, Scratch lacks a ternary operator. If we had one, it'd have looked like this:
[](https://i.stack.imgur.com/L4WAD.png)
However, we can use a workaround with this:
[](https://i.stack.imgur.com/Ll8XZ.png)
In sb syntax (22 bytes):
```
((x)*<>)+((y)*<not<>>)
```
Make sure to replace `x` and `y` with the values for when the boolean is true and when it's false. The booleans may be empty here, but when using it should have the same conditions.
~~Besides, this only works when `x` and `y` are numbers. Currently this fails with strings.~~ See edit.
This also works because of <https://codegolf.stackexchange.com/a/198744/110681>
**EDIT:** you could use our invented ternary operator with a `(item()of[ v])` to index a number into the list, depending on the truth value of the boolean.
**EDIT:** To get single character results, Jacob has commented on his version, which is 20 bytes (replace `<>` with your boolean):
```
letter((1)+<>)of[ab]
```
However, notice that this doesn't work for emojis or Unicode characters, and they will return `�` if you try using them.
[Answer]
## Brackets auto-complete
In the scratchblocks3 visual syntax (backwards-compatible with scratckblocks2 syntax), you can auto-complete the brackets.
E.g. The hello, world program:
```
when gf clicked
say[hello, world]
```
Can be golfed into:
```
when gf clicked
say[hello, world
```
In addition, the end statement of switching structures is auto-completed at the end. So instead of
```
define f(n
set[i v]to(1
set[o v]to(
repeat(length of(n
repeat((2)-((i)mod(2
set[o v]to(join(o)(letter(i)of(n
end
change[i v]by(1
```
You could do (-4 bytes)
```
define f(n
set[i v]to(0
set[o v]to(
repeat(length of(n
change[i v]by(1
repeat((2)-((i)mod(2
set[o v]to(join(o)(letter(i)of(n
```
[Answer]
# Output via a variable or list, not `say`
The previous consensus for output in Scratch was that you had to `say` the output. However, this doesn't really make sense, since variables are automatically displayed in Scratch if not unchecked in the interface, just as `say` is automatically displayed if the sprite is not checked as hidden.
Now, per [this consensus](https://codegolf.meta.stackexchange.com/a/25520/108687), it's allowed to just output by writing a global variable, which can in some cases save many bytes.
For example, this (meaningless) code:
```
repeat(10
change[i v]by(1
if<(i)>5>then
set[a v]to((i)*(2
end
end
say(a
```
Can become just:
```
repeat(10
change[i v]by(1
if<(i)>5>then
set[a v]to((i)*(2
```
] |
[Question]
[
A maze is given as a matrix of 0s (walls) and 1s (walkable space) in any convenient format. Each cell is considered connected to its 4 (or fewer) orthogonal neighbours. A *connected component* is a set of walkable cells all transitively connected to each other. Your task is to identify the *cutpoints* - walkable cells which, if turned into walls, would change the number of connected components. Output a boolean matrix with 1-s only at those locations. The goal is to do it in the fewest bytes of code.
The input matrix will consist of at least 3 rows and 3 columns. At least one of its cells will be a wall and at least one will be walkable. Your function or program must be able to process any of the examples below in under a minute on [TIO](https://tio.run/) (or on your own computer, if the language is not supported by TIO).
```
in:
11101001
11011101
00000001
11101111
11110101
00011111
10110001
11111111
out:
01000000
00001001
00000001
00000101
00110000
00010000
00000000
11100000
in:
1111111111111111
1000000000000001
1111111111111101
0000000000000101
1111111111110101
1000000000010101
1011111111010101
1010000001010101
1010111101010101
1010101111010101
1010100000010101
1010111111110101
1010000000000101
1011111111111101
1000000000000001
1111111111111111
out:
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
in:
1011010001111010
1111111011101101
1110010101001011
1111001110010010
1111010000101001
0111101001000101
0011100111110010
1001110011111110
0101000011100011
1110110101001110
0010100111000110
1000110111011010
0100101000100101
0001010101100011
1001010000111101
1000111011000010
out:
0000000000111010
1011110001001000
0000000000000011
0000000100010000
0000010000101000
0000001000000100
0000000011000000
1001100000011110
0000000001000010
0110100001000110
0000100101000010
1000100000000000
0100001000000100
0000000100100001
0000010000111000
0000010000000010
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 40 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Çóê↓â.Φ}╞│*w<(♦◙¼ñ£º█¢,D`ì♥W4·☺╛gÇÜ♠╗4D┬
```
[Run and debug test cases](https://staxlang.xyz/#p=80a28819832ee87dc6b32a773c28040aaca49ca7db9b2c44608d035734fa01be67809a06bb3444c2&i=%2211101001+11011101+00000001+11101111+11110101+00011111+10110001+11111111%22%0A%221111111111111111+1000000000000001+1111111111111101+0000000000000101+1111111111110101+1000000000010101+1011111111010101+1010000001010101+1010111101010101+1010101111010101+1010100000010101+1010111111110101+1010000000000101+1011111111111101+1000000000000001+1111111111111111%22%0A%221011010001111010+1111111011101101+1110010101001011+1111001110010010+1111010000101001+0111101001000101+0011100111110010+1001110011111110+0101000011100011+1110110101001110+0010100111000110+1000110111011010+0100101000100101+0001010101100011+1001010000111101+1000111011000010%22%0A&a=1&m=2)
This program takes input as a space separated string containing rows. The output is in the same format. Here's the unpacked ascii representation.
```
{2%{_xi48&GxG=-}_?m}{'1'2|e{"12|21".22RjMJguHgu%
```
The fundamental operation for counting an island works like this.
1. Replace the first `'1'` with a `'2'`.
2. Regex replace `'12|21'` with `'22'`.
3. Split on spaces.
4. Transpose matrix.
5. Repeat from 2. until a string is repeated.
6. Repeat from 1. until there is no longer a `'1'` in the string. The number of repetitions is the number of islands.
.
```
{ start map block over input string, composed of [ 01]
2% mod by 2. space and 0 yield 0. 1 yields 1. (a)
{ start conditional block for the 1s.
_ original char from string (b)
xi48& make copy of input with current character replaced with 0
G jump to unbalanced }, then return; counts islands (c)
xG counts islands in original input (d)
= are (c) and (d) equal? 0 or 1 (e)
- b - e; this is 1 iff this character is a bridge
} end conditional block
_? execute block if (a) is 1, otherwise use original char from string
m close block and perform map over input
} goto target - count islands and return
{ start generator block
'1'2|e replace the first 1 with a 2
{ start generator block
"12|21".22R replace "12" and "21" with "22"
jMJ split into rows, transpose, and rejoin with spaces
gu generate values until any duplicate is encountered
H keep the last value
gu generate values until any duplicate is encountered
% count number of iterations it took
```
[Bonus 44 byte program](https://staxlang.xyz/#p=8124d11dcf6f6f00efaa77e1ac76c461606012a97a3bae4f55e4efce7d9d9683fe1aad5ae63003c59f5a6955&i=11101001%0A11011101%0A00000001%0A11101111%0A11110101%0A00011111%0A10110001%0A11111111%0A%0A1111111111111111%0A1000000000000001%0A1111111111111101%0A0000000000000101%0A1111111111110101%0A1000000000010101%0A1011111111010101%0A1010000001010101%0A1010111101010101%0A1010101111010101%0A1010100000010101%0A1010111111110101%0A1010000000000101%0A1011111111111101%0A1000000000000001%0A1111111111111111%0A%0A1011010001111010%0A1111111011101101%0A1110010101001011%0A1111001110010010%0A1111010000101001%0A0111101001000101%0A0011100111110010%0A1001110011111110%0A0101000011100011%0A1110110101001110%0A0010100111000110%0A1000110111011010%0A0100101000100101%0A0001010101100011%0A1001010000111101%0A1000111011000010&a=1&m=1) - this version inputs and outputs using the grid format.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 26 bytes
```
n:"GG0@(,w4&1ZIuz]=~]vGZye
```
The input is a numerical matrix, using `;` as row separator.
[Try it online!](https://tio.run/##y00syfn/P89Kyd3dwEFDp9xEzTDKs7Qq1rYutsw9qjL1//9oQwUQNABjIGkN50Jpa7A4AkJVINTABWCmwLUYIqswgKpAMQMOYwE) Or [verify all test cases](https://tio.run/##pVO7DsIwDNz5iooBMTDYEhMWEgMLmRmqVpFAiA2YeAgGfj1A1bq2k2ZBVh@J7s6xcz7vr6ewK124LMbOwWo6e8wnWG1uL798@7urnscAh3K9DTUWv4Dm@b6Jl@2Xmv0@WkSP4Y1OhSkoEdAilAaHH9VYZIOYnY5YU0WiEsXOKwjAILsHDLAlIMnWgATbAiCfAvOHhHyZmG8U5Fv912V1hgDlTVMtJQ6PwmjCqGBa0oKkccGATQrZDjUtEEFQd8pK65RAieyqKoouE@Uk2XnUZbJCYpv/gfQy1iPTOdBtkhOvrakOCQOVGMfo7KzrPw).
### Explanation
```
n % Implicit input: matrix. Push number of elements, N
: % Range: gives [1 2 ... N]
" % For each k in [1 2 ... N]
GG % Push input matrix twice
0@( % Write 0 at position k (in column-major order: down, then across).
% The stack now contains the original matrix and a modified matrix
% with 0 at position k
, % Do twice
w % Swap
4 % Push 4. This specifies 4-element neighbourhood
&1ZI % Label each connected component, using the specified
% neighbourhood. This replaces each 1 in the matrix by a
% positive integer according to the connected component it
% belongs to
u % Unique: gives a vector of deduplicate elements
z % Number of nonzeros. This is the number of connected components
] % End
=~ % Are they different? Gives true of false
] % End
v % Concatenate stack into a column vector
GZye % Reshape (in column-major order) according to size of input matrix.
% Implicit display
```
[Answer]
# [Perl 5](https://www.perl.org/), `-p0` ~~105~~ ~~101~~ ~~96~~ ~~93~~ ~~90~~ 89 bytes
Uses `b` instead of `1` in the input.
Make sure the matrix on STDIN is terminated with a newline
```
#!/usr/bin/perl -p0
s%b%$_="$`z$'";s:|.:/
/>s#(\pL)(.{@{-}}|)(?!\1)(\pL)#$&|a.$2.a#se&&y/{c/z />0:seg&/\B/%eg
```
[Try it online!](https://tio.run/##TU/LDoIwELz3K1QKwoF2MPGC8RHP@gck6hpiTIwS60XBX7dCH0of283s7sy0Ku@XqdYqpJDv5iO@f/HxaKbyRuSSyYUK4qLaJLGoV3X6fjdJvBwWWWLAgEfNQfCJOASqjKKnrI/yNZAL5Ko8RbJYy7A8aU2g9gDtYxJGdsFeUAe0VbO7YAAy/bAQc6OAa2KezBJ3APwMuZE@0iYMnoGsGeb14VoZ/nkXDQd6Rg2HoyEv64z/SNHTMZ9zkuTss8@tepxvV6XTCjrdTkUGgS8 "Perl 5 – Try It Online")
Uses 3 levels of substitution!
This 87 byte version is both in input and output format easier to interpret, but is not competing since it uses 3 different characters in the output:
```
#!/usr/bin/perl -0p
s%b%$_="$`z$'";s:|.:/
/>s#(\w)(.{@{-}}|)(?!\1)(\w)#$&|a.$2.a#se&&y/{c/z />0:seg&/\B/%eg
```
[Try it online!](https://tio.run/##TU/LDoIwELz3K1YpCAdaMPGCEY13/4BEXdMQEyPEmhgFf91KX0of283s7sy0FbfLQikZYkj3qyk9vOhsupRFzwpOeCmDuHokMes2Xfp@90m8nlR5orGARv2R0Tk7BlJE0ZN3J/4CXmaFFHXEqy0PRa0UAg4HYHhMQtAusBdQA0PVbB0MgKYfLETcKIBrIp7MEmsA/Ay6kTEyJAQ8A1ozxOuDayXwz3U0HDAyajgcDXpZZ/xHCiMd8zknic7@p2nv5@YqVdpmKt0tWJ6x7As "Perl 5 – Try It Online")
It's easy to save another byte (the regex `s` modifier) in both versions by using some different (non-alphanumeric) character as row terminator (instead of newline), but that makes the input quite unreadable again.
# How it works
Consider the substitution
```
s#(\w)(.{columns}|)(?!1)(\w)#c$2c#s
```
This will find two letters that are different and next to each other horizontally or vertically and replace them by `c`. In a maze whose paths consist of entirely the letter `b` nothing will happen since the letters are the same, but as soon as one of the letters is replaced by another one (e.g. `z`) that letter and a neighbor will be replaced by `c` and repeated application is a flood-fill of the connected component with `c` from seed `z`.
In this case I however don't want a complete flood-fill. I want to fill only one of the arms neighboring `z`, so after the first step I want the `z` gone. That already works with the `c$2c` replacement, but I later want to restart a flood-fill along another arm starting from the same point and I don't know which of the `c`s was originally `z` anymore. So instead I use
```
s#(\w)(.{columns}|)(?!\1)(\w)#$&|a.$2.a#se
```
`b | a` is `c`, `b | c` is `c` and `z | a` is `{`. So in a maze with paths made up of `b` and a seed `z` in the first step `b` will get replaced by `c` and `z` will get replaced by `{` which is not a letter and does not match `\w` and so will not cause further fills. The `c` however will keep a further flood-fill going and one neighbor arm of the seed gets filled. E.g. starting from
```
b c
b c
bbzbb becomes bb{bb
b b
b b
```
I can then replace all c by some non letter (e.g. `-`) and replace `{` by `z` again to restart the flood-fill:
```
- -
- -
bbzbb becomes cc{bb
b b
b b
```
and repeat this process until all neighbors of the seed have been converted. If I then once more replace `{` by `z` and flood-fill:
```
- -
- -
--z-- stays --z--
- -
- -
```
The `z` remains behind at the end because there is no neighbor to do a transformation with.
That makes clear what happens in the following code fragment:
```
/\n/ >
```
Find the first newline. The starting offset is now in `@-`
```
s#(\w)(.{@{-}}|)(?!\1)(\w)#$&|a.$2.a#se
```
The regex discussed above with `@{-}` as number of columns (since plain `@-` confuses the perl parser and doesn't properly substitute)
```
&&
```
The `/\n/` always succeeds and the substitution is true as long as we can still flood-fill. So the part after `&&` is executed if the flood-fill of one arm is done. If not the left side evaluates to an empty string
```
y/{c/z / > 0
```
Restart the flood-fill and return 1 if the previous flood-fill did anything. Else return the empty string. This whole piece of code is wrapped inside
```
s:|.: code :seg
```
So if this is executed on a starting string `$_` with a `z` at the seed position the piece of code inside will be executed many times mostly returning nothing but a `1` every time a neighbor arm gets flood-filled. Effectively `$_` gets destroyed and replaced by as many `1`s as there are connected components attached to `z`. Notice that the loop needs to be executed up to sum of component sizes + number of arms times but that is OK since it will "number of characters including newlines \* 2 + 1" times.
The maze gets disconnected if there are no `1`'s (empty string, an isolated vertex) or if there are more than 1 arms (more than 2 `1`s). This can be checked using the regex `/\B/` (this gives `0` instead of `1` on older perl versions. It's arguable which one is wrong). Unfortunately if it doesn't match this will give an empty string instead of `0`. However the `s:|.: code :seg` was designed to always return an odd number so by doing an `&` with `/\B/` this will give `0` or `1`.
All that is left is walking the whole input array and at each walkable position seed with `z` and count connected arms. That is easily done with:
```
s%b%$_="$`z$'"; code %eg
```
The only problem is that in the non-walkable positions the old value is retained. Since we need `0`s there that means the original input array must have `0` in the non walkable positions and `0` matches `\w` in the original substitution and would trigger flood-fills. That's why I use `\pL` instead (only match letters).
[Answer]
# Java 8, ~~503~~ ~~489~~ ~~459~~ ~~455~~ 407 bytes
```
int R,C,v[][];m->{int r[][]=new int[R=m.length][C=m[0].length],i=R*C,a=i(m),x,y,q;for(;i-->0;m[y][x]=0,r[y][x]=i(m)!=a?1:0,m[y][x]=q)q=m[y=i/C][x=i%C];return r;}int i(int[][]m){int r=0,i=R*C,x,y;for(v=new int[R][C];i-->0;)if(m[y=i/C][x=i%C]>v[y][x]){d(m,x,y);r++;}return r;}void d(int[][]m,int c,int r){v[r][c]=1;for(int k=-3,x,y;k<4;k+=2)if((x=c+k%2-k/2)>=0&x<C&(y=r+k/2)>=0&y<R&&m[y][x]>v[y][x])d(m,x,y);}
```
-66 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##rVbNk5owFL/vX5HuzDqhBA12TxtjD5566LbjHhkOLOJuVNDFaGUc/nY3gYAgScuhE@Uj7@P3ey/vkayCY@Bsd1GyWqwv4SbY78HPgCXnOwBYwqN0GYQReJavxYTnez4IYfUUW0RI8rtSG8zRDB2lgEj10QjY7iN4zXi0B3wL@HtUvDjh9pBwafMMEkDBJXamZ2meSlOaRH8KpDmNh5soeePvvjejsYf96hUxOv86QwFlMLbQCWXogyy3KSTMcaaYxF7meyefYpSqJ6n3hQbf3SeMKumH9SGcZpSNZuKdsoeZT9KIH9IEpCQnkg@r4oytkp9wWUILzALxeGUrSPqKgMWW8Mb19FjCWucFjKW5RVLbJvkV8bhlC7CoEZEEDItrap2PXup7oU/dAlVOrqnzraCxnjyStU3HEhSeaGivH8bOejS2phQPTpPZAGY0tauJbDIfDFQKak41pfwCwO7wumEh2POAi1vBKhYFAV94ypI3zw@sshjEonJYRS8Yl7MAnF0kBy7@4pqjpgCjWnwVYNQcNxZXm46gQum4cnUWWFloMa4WeVHS/4zPONqQ5mGm0Bp/SVTLWz@PGkWjt66iwZtOUetNr6jxZlLE/aDdfsHgfulx@yUc91vC/1IUPesUtzrxJnkmJNy6a9uxvVJ1KnXtiVHbyADdzLL223G78s2gOi1yC@7qoU2qblsRd/i5zYzqv1bt9HQ8asT1M@4Wi3ZduhzxzWpj8/ex3VHaYDDSR24o6Da7GkfVaS7@4tfcVYrCrQ4SLNkduNpZXrI9j@Lh9sCHO7Hn8E0C739I@RO4V0W/E/smz35LKSxNidH014EbbWXfyOMOtIbJMFSuzL6up51mIG0y6mAUiO3ypAISezaAS5YEm7JJQbSJ4khs4k@VHqi6ttreVxST1UTpqXMPWdm2pfS69KBS9la@CsAcQrke@V1@@QQ)
**Explanation:**
```
int R,C, // Amount of rows/columns on class-level
v[][]; // Visited-matrix on class-level
m->{ // Method with int-matrix as both parameter and return-type
int r[][]=new int[R=m.length][C=m[0].length],
// Create the result-matrix, and set `R` and `C`
i=R*C, // Index-integer
a=i(m), // The current amount of islands
x,y, // Temp integers for the coordinates
q; // Temp integer for the value
for(;i-->0 // Loop `i` over each cell:
; // After each iteration:
m[y][x]=0, // Temporarily change the current value to 0
r[y][x]=i(m)!a? // If the current and initial amount of islands are not
// the same anymore:
1 // Set the result-value at this coordinate to 1
: // Else:
0, // Set the result-value at this coordinate to 0
m[y][x]=q) // Then change the current value back to what it was
q=m[y=i/C][x=i%C]; // Save the current value at this coordinate
return r;} // Return the result-matrix
// Separated method to determine the amount of islands in a matrix
int i(int[][]m){
int r=0, // Result-count, starting at 0
i=R*C, // Index integer
x,y; // Temp integers for the coordinates
for(v=new int[R][C]; // Reset the visited array
i-->0;) // Loop over the cells:
if(m[y=i/C][x=i%C] // If the current cell is a 1,
>v[y][x]){ // and we haven't visited it yet:
d(m,x,y); // Check every direction around this cell
r++;} // And raise the result-counter by 1
return r;} // Return the result-counter
// Separated method to check each direction around a cell
void d(int[][]m,int c,int r){
v[r][c]=1; // Flag this cell as visited
for(int k=-3,x,y;k<4;k+=2)// Loop over the four directions:
if((x=c+k%2-k/2)>=0&x<C&(y=r+k/2)>=0&y<R
// If the cell in the direction is within bounds,
&&m[y][x] // and it's a path we can walk,
>v[y][x]) // and we haven't visited it yet:
d(m,x,y);} // Do a recursive call for this cell
```
[Answer]
# [Python 2](https://docs.python.org/2/), 290 bytes
```
lambda m:[[b([[C and(I,J)!=(i,j)for J,C in e(R)]for I,R in e(m)])!=b(eval(`m`))for j,c in e(r)]for i,r in e(m)]
def F(m,i,j):
if len(m)>i>=0<=j<len(m[i])>0<m[i][j]:m[i][j]=0;F(m,i,j+1);F(m,i,j-1);F(m,i+1,j);F(m,i-1,j)
b=lambda m:sum(F(m,i,j)or c for i,r in e(m)for j,c in e(r))
e=enumerate
```
[Try it online!](https://tio.run/##XVBNb8MgDD0vv4L1BKo7kR3TkEulSe2xV4ZU0hCNKJCIppv26zPIV7PKAj/7PRvj9rf7aux7X7LPvpYmLyQyCec55vyApC3wEU7klWENFSkbh05wQNoihc9EhPgI5zE2RHhdjtW3rPHFXMggr@A60m6Ua3CLPCpUiT6wgdA7iV50iWplPZPpjNGUVekQci1IRtPgeSWSyTO6n0q3MZnhbobb2Lcc4S7AKGfL5253g@dX/URX9DTX09gkUkzZu1FOdqoPpGt@Aln6FcUQjA7H3wIiPicmH1IU1raoHrpVau62Koz/q@ikeur1UImwzNZp26EN2rxVjfZblC2@dQ5QAJ6B8AtCSP8H "Python 2 – Try It Online")
-11 bytes thanks to Rod
-11 bytes thanks to Lynn
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 118 bytes
```
(r=ReplacePart)[0#,Cases[#~Position~1,p_/;(c=Max@MorphologicalComponents[#,CornerNeighbors->1<0]&)@r[#,p->0]>c@#]->1]&
```
[Try it online!](https://tio.run/##bY3BCoMwEER/RRBEIdJ4bpWAZ4v0KqGkEjWg2RBzKIj@eqoUaSzCsgwz@2YHZjo@MCNqZhsvtaFOH1z1rOYl0yaqsI9yNvKx8pcSRmEEyCVB6nm5hnVasDcpQKsOemjXhj6HQYHk0qz3KActub5z0XYv0GOcJTdMg4joNVNxhmlWE5@uNg1sqYU0pCHTlCDvO3jfm5iRN7n2T28J3u/ccZg/7Ji4r45tyQmDHebsz5GZ7Qc "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Javascript 122 bytes
Input/output as a multiline string.
```
m=>m.replace(/./g,(v,p,m,n=[...m],f=p=>n[p]==1&&(n[p]=0,v=f(p-1)+f(p+1)+f(p-w)+f(p+w)-1?1:0,1))=>(f(p),v),w=~m.search`\n`)
```
For each walkable cell, put a block and try to fill the 4 neighbor cells. If the current cell is not a cut point, then starting from any open neighbor will fill all of them. Else, I will need more than one fill operation to reach all neighbor cells.
*Less golfed*
```
m=>{
w = m.search('\n') + 1; // offset to the next row
result = [...m].map( // for each cell
( v, // current value
p // current position
) => {
n = [...m]; // work on a copy of the input
// recursive fill function from position p
// returns 1 if managed to fill at least 1 cell
fill = (p) => {
if (n[p] == 1)
{
n[p] = 0;
// flag will be > 1 if the fill from the current point found disjointed areas
// flag will be 0 if no area could be filled (isolated cell)
var flag = fill(p+1) + fill(p-1) + fill(p+w) + fill(p-w);
// v is modified repeatedly, during recursion
// but I need the value at top level, when fill returns to original caller
v = flag != 1 ? 1 : 0;
return 1; // at least 1 cell filled
}
else
return 0; // no fill
}
fill(p)
return v // orginal value or modified by fill function
})
}
```
**Test**
```
var F=
m=>m.replace(/./g,(v,p,m,n=[...m],f=p=>n[p]==1&&(n[p]=0,v=f(p-1)+f(p+1)+f(p-w)+f(p+w)-1?1:0,1))=>(f(p),v),w=~m.search`\n`)
var test=`in:
11101001
11011101
00000001
11101111
11110101
00011111
10110001
11111111
out:
01000000
00001001
00000001
00000101
00110000
00010000
00000000
11100000
in:
1111111111111111
1000000000000001
1111111111111101
0000000000000101
1111111111110101
1000000000010101
1011111111010101
1010000001010101
1010111101010101
1010101111010101
1010100000010101
1010111111110101
1010000000000101
1011111111111101
1000000000000001
1111111111111111
out:
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
0000000000000000
in:
1011010001111010
1111111011101101
1110010101001011
1111001110010010
1111010000101001
0111101001000101
0011100111110010
1001110011111110
0101000011100011
1110110101001110
0010100111000110
1000110111011010
0100101000100101
0001010101100011
1001010000111101
1000111011000010
out:
0000000000111010
1011110001001000
0000000000000011
0000000100010000
0000010000101000
0000001000000100
0000000011000000
1001100000011110
0000000001000010
0110100001000110
0000100101000010
1000100000000000
0100001000000100
0000000100100001
0000010000111000
0000010000000010
`.match(/\d[10\n]+\d/g);
for(i = 0; test[2*i]; ++i)
{
input = test[2*i]
check = test[2*i+1]
result = F(input)
ok = check == result
console.log('Test '+ i + ' ' + (ok?'OK':'FAIL'),
'\n'+input, '\n'+result)
}
```
] |
[Question]
[
**This question already has answers here**:
[Encode an integer](/questions/139034/encode-an-integer)
(11 answers)
Closed 6 years ago.
I once saw on the xkcd fora a format for expressing numbers in an odd way. In this "factor tree" format:
* 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:
```
()
(())
()()
((()))
()(())
(()())
()()()
(())(())
()((()))
```
Your task is to take in a positive integer, and output the factor tree for it.
# Test Cases
In addition to the 9 above…
```
100 => ()()((()))((()))
101 => (()(()(())))
1001 => (()())(((())))(()(()))
5381 => (((((((())))))))
32767 => (()())((((()))))(()()(())(()))
32768 => ()()()()()()()()()()()()()()()
```
# Rules
* Characters other than `()[]{}<>` are allowed in the output, but ignored.
* You should be able to handle any input from 2 to 215 inclusive.
* The winner is the shortest answer in bytes.
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~84~~ ~~81~~ ~~80~~ 64 bytes
*Byte count assumes Windows ANSI encoding.*
*Thanks to Misha Lavrov for saving 16 bytes.*
```
±1=""
±x_:=Table[{"(",±PrimePi@#,")"},#2]&@@@FactorInteger@x<>""
```
[Try it online!](https://tio.run/##JcrPCoJAGATwe08xfIIUfFCr@afI2FPQzUO3iNhkKSENZA@C@FD7Cvtim9lhfjOHaZR56UaZulLeOysKooWz/X1fXNTjra8DLYmdLbu60WUtA6YVjRxEt1BKeVKV@XTn1uin7mR/OBL56dkaSDgbIMRaYhCMiBEztoyEkTIyRs7YMcTmlxkxr8kkzifjKEuzf@Wj/wI "Wolfram Language (Mathematica) – Try It Online")
### Explanation
Quite a literal implementation of the spec. We're defining a unary operator `±` via two separate definitions.
```
±1=""
```
This is just the base case, the empty string for `1`.
```
±x_:=Table[±#,#2]&@@@FactorInteger@x<>""
```
For all other `x`, we factor the integer (this gives a list of prime-exponent pairs, `{p, k}`), generate a table of `k` copies of the representation of `p`.
For each `p`, we figure out the prime's index via `PrimePi` (i.e. the number of primes less than or equal to it), recursively pass it to `±` and wrap the result in parentheses. Then flatten and join the result into a single string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ÆfÆC$ÐLŒṘ€
```
[Try it online!](https://tio.run/##y0rNyan8//9wW9rhNmeVwxN8jk56uHPGo6Y1/w@3A8nI//@NdBSMdRRMdBRMdRTMdBTMdRQsdBQsdRQMDUAYTBiCWUDS1NgCSBobmZuZQygLAA "Jelly – Try It Online")
-7 bytes thanks to user202729
# Explanation
```
ÆfÆC$ÐLŒṘ€ Main Link
ÐL While the results have not yet repeated
ÆfÆC$ Prime factorize the number (vectorizes) and turn each prime to its prime index
ŒṘ€ Since none of the lists actually contain anything, turn it to a Python string or else it won't print. Call on each because otherwise there will be an extra set of brackets around the output.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~15~~ 7 bytes
```
ṁös;₁ṗp
```
[Try it online!](https://tio.run/##yygtzv6f9qhpjVJ0rNKjpsb/D3c2Ht5WbA1kPtw5veD////GRuZm5gA "Husk – Try It Online")
-8 bytes thanks to @Zgarb!
### Explanation
Note that the header `f€"[]"₁` just filters out all `[` & `]` characters, it's just so that the output is more readable, if you want to see the original output, [here](https://tio.run/##yygtzv7//@HOxsPbiq0fNTU83Dm94P///8ZG5mbmAA) you go.
```
ṁ(s;₁ṗ)p -- define function ₁; example input: 6
p -- prime factorization: [2,3]
ṁ( ) -- map and flatten the following (example with 3): "[""]["[\"\"]"]"
ṗ -- get prime index: 2
₁ -- recurse: "[\"\"]"
; -- create singleton: ["[\"\"]"]
s -- show: "[\"[\\\"\\\"]\"]"
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~113~~ 110 bytes
```
f=lambda n,d=2,p=1:n>2and(n%d and f(n,d+1,p+all(-~d%i for i in range(2,d)))or'(%s)'%f(p)+f(n/d,d,p))or'()'*~-n
```
[Try it online!](https://tio.run/##PYvBTsMwGIPvewpfqib0HywpW8uk8iKIQyANRGr/REk47LJXL2GTsOTPlizHS/kOrDe/xpAK8iXvqh/zXNL8@ZOyD7z41RehDlVyc9Ni1g9rwGQnTXFSZ37Vhq3gxqImnKhTpyh2ZlnE/mobDxcSPDwjGf6ahSYrpQypFU2WbeNElF29PVmyFO@DbB@ue97@j2@a0BOeCUfCiTAQRsILQR3@fIO6tcpjP1b2ejgN9xjfzzsgJs8FnpzwcvsF "Python 2 – Try It Online")
---
**ungolfed**
```
def f(num, div=2, prime=1):
if num > 2:
if num % div:
# if div does not divide num
# try next divisor, add 1 to prime if the next divisor is prime
return f(num, div + 1, prime + all((div + 1) % i for i in range(2, div)))
else:
# if div divides num add div as a factor, continue with num / div
return '(%s)' % f(prime) + f(num / div, div, prime)
else:
# if num <= 1: return ''
# if num == 2: return '()'
return '()' * (num - 1)
```
[Try it online!](https://tio.run/##dVHbTsMwDH3fVxxpmpZAgLVjFybKjyAeqjVlltpkSlJgX19yGd3GwFKcxD52znH2B7fTKu@p3WvjYA925Ne9lc7IbWcsadVQS45lM2@8r2SNmqmuFajoo8gF9oZaWWR8M4I3quGTeEGe7mexSag4RYONQ85HUWlpobQLF6pkwP8COnOAkl8JYbURKKsKGZxODEInt5MXGJBNyYteRrrOqDMVuEV21OGPZdMwdoxyT5pQh04gBVOqd8nyWMQ5H7rKxsr/hEU9Ng4gEA6x0qJEXW5dULHVypHqJD7J7SLsIYD@YjxlE8unnlLNIlnuKUYVqUQkl1Kja17jn494LpBthqbTa0BR@O87vcpPkLMYbhDfvvNj6ocRvfrpzAUeBRYCS4GVwFrgSSCbhRVdFk/eL@Zr7@f5arlK2/ot0PUKlAOJmhHvvwE "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 93 bytes
Uses the same approach as [ovs' Python answer](https://codegolf.stackexchange.com/a/150149/58563).
```
f=(n,d=2,k=1)=>n>2?n%d?f(n,++d,k+(P=n=>n%--d?P(n):d<2)(d)):`(${f(k)})`+f(n/d,d,k):n-2?'':'()'
```
### Test cases
```
f=(n,d=2,k=1)=>n>2?n%d?f(n,++d,k+(P=n=>n%--d?P(n):d<2)(d)):`(${f(k)})`+f(n/d,d,k):n-2?'':'()'
;[2,3,4,5,6,7,8,9,10,100,101,1001,5381,32767,32768].forEach(
n => console.log(n, '->', f(n))
)
```
[Answer]
# [R](https://www.r-project.org/) + [numbers](https://cran.r-project.org/web/packages/numbers/numbers.pdf), 113 bytes
```
f=function(n)"if"(n<2,"",paste0("(",sapply(match(primeFactors(n),Primes(n)),f),")",collapse=""))
library(numbers)
```
[Try it online!](https://tio.run/##dY7NCoMwDIDvPoXklEAP/rDpYb3uvFeoxbJCraXVg0/vrHabDJZASfp9CfHrqriarZz0aNESaAVobxUDYE6EqS8QEFgQzpkFBzHJJzqvh/4u5DT6sI2wR@xjRUwRAwImR2OECz0HIMqM7rzwC9p56HofaFVYFgXlnOeAtCUiUXohi7BMMDLa/xM4k31kZ28pOpe6/ThHUIpI66q5Nr8rDgOPU@i7Ksrt6cy/CesL "R – Try It Online")
Recursive function. Returns a string.
```
function(n)
if(n < 2) # 1 is empty string
"" #
else #
paste0("(", # wrap in parens
sapply( # for each
match(primeFactors(n),Primes(n))), # prime index of factors of n
f), # apply f
")", #
collapse="") # collapse into a single string
```
[Answer]
# [Swift](https://swift.org), 155 bytes
```
func f(_ n:Int)->String{var d=0;return n<2 ?"":(d=(2...n).first{n%$0<1}!,n==d).1 ?"(\(f((2...n).filter{m in(2...m).first{m%$0<1}==m}.count)))":f(d)+f(n/d)}
```
## Explanation (Ungolfed)
```
func f(_ n:Int) -> String { // Declare recursive function f(n)
var d = 0; // Temporary variable d
return n < 2 ? // If n < 2:
"" // Return empty string
: (d = (2...n).first{n % $0 < 1}!, n == d).1 ? // If the lowest number divisible by n
// is equal to n (n is prime):
"(\(f((2...n).filter{m in (2...m).first{ // Return prime index of n (length of
m % $0 < 1} == m}.count)))" // list of all primes ≤ n)
: // Else:
f(d) + f(n / d) // Return f(d) + f(n / d) where d is
} // the smallest number divisible by n
```
] |
[Question]
[
A curve is a set of points on a square grid such that each point has exactly two neighbors in the four-neighbor neighborhood and the points form a single connected component. That is, the graph induced by the points on a grid graph is isomorphic to a single cycle. "Induced" means that two points cannot touch in the input without being neighbors in the cycle.
An antipode of a vertex V in a graph is a vertex furthest away from V. The antipode is always unique on an even-length cycle (and every cycle on a grid graph is even-length). The distance shall be measured as induced by the cycle itself without respect for the underlying square grid.
Your input shall be an image of a curve. The curve will be marked out with a sequence of number sign characters (`#`) on a background out of space characters (). One of the points on the curve will be marked with the `P` character ("pode"). Your output shall be the same as the input except one curve point shall be replaced with `A` ("antipode").
You may assume the characters will be padded to a rectangular shape. You may assume the first and last row and column of input will be composed entirely of spaces (input is padded with background). Alternatively you may assume that the first and last row and column will each contain a curve point (input has minimum padding).
You may input and output this grid as a single newline-separated string, as an array of rows, or as a 2D array of individual characters. This choice shall be the same for the input and output. If your language allows this, you may output by modifying the input in place instead of returning the modified string or array.
Possible inputs:
```
P# P## #P# ##### #####P# ####### #####P######### #####P#########
## # # # # # # # # # # # # # #
### ### ## ## # ### # # ### # # ### ### ### # # #
### # # ### # # # # # # # # # # # # # # # # # #
# P# ### ### # ### # # # ### ### # # # # ### ### # # # #
## # # ### # # # # # # # # # # # # #
# # P # ##### P # ########### # # ##### ##### # # #
### ####### ### # # # # # # # #
############### ####### ####### ###############
```
Corresponding outputs:
```
P# P## #P# #A### #####P# #A##### #####P######### #####P#########
#A # # # # # # # # # # # # # #
##A #A# ## ## # ### # # ### # # ### ### ### # # #
### # # ### # # # # # # # # # # # # A # # # # #
# P# ### ##A # ### # # # ### ### # # # # ### ### # # # #
## # # ### # # # # # # # # # # # # #
A # P # ##### P # ########### # # ##### ##### # # #
### ####### ### # # # # # # # #
############### ####### ####### #########A#####
```
Vertex distances from the podes (modulo 10) (do not output these):
```
P1 P12 1P1 5A543 54321P1 9A98765 54321P123456789 54321P123456789
1A 1 3 2 2 4 2 6 2 8 4 6 0 6 0
23A 3A3 32 01 7 109 3 7 109 3 7 901 789 543 1 7 1
321 1 9 543 8 2 8 4 6 2 8 2 8 8 2 6 A 6 2 2 8 2
4 P1 234 89A 0 876 2 9 3 765 543 7 1 9 7 345 987 1 3 9 3
56 2 1 567 9 9 1 0 4 6 0 0 6 0 4 0 4
A 3 P 8 87654 P 1 56789012345 9 1 54321 56789 5 1 5
654 1234567 321 2 8 2 0 4 6 2 6
345678901234567 3456789 3210987 345678901A10987
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~333~~ ~~221~~ 215 bytes
*-17 bytes thanks to @JanDvorak*
```
g=input()
y=map(max,g).index('P')
x=g[y].index('P')
m=[k[:]for k in g]
v=x;w=y
while'#'in sum(m,[]):x,y,(v,w)=v,w,[(x+a,y+b)for a,b in((1,0),(-1,0),(0,1),(0,-1))if'#'==m[y+b][x+a]][0];m[w][v]='_'
g[w][v]='A'
print g
```
[Try it online!](https://tio.run/##pZLBbsIwDIbveYpKOSQRBrU7gnLgDbhb1lQ0CBFLqFhpk6cv2RgTYwU6cbD/yJY/W7GrWG92/qXrjLa@OtRSsahdWUlXBjBqYv3bKkixEIoFbTDSZcRp3OKU1rt9ts2szwyxRodZqyNrN/Z9JbhI0Y@Dkw6Q1DRABNlAq3RygDKMSoijpfoElLBMCCkLyBXI8UlyKL78uFDKrhNOa4epgjCVEmFOM4ctYUNavApmzu@5YNXe@jozXYcoMgFPGsGJwnts8a238vwnf0np68OvtD9/Tfndo1//5vso/9d7FD54xluUR8YH/wt/uJuhOxo20717GT7TmfLk7dIR "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), ~~402~~ ~~288~~ 282 bytes, String IO
```
g=[[*k]for k in open(0).read().split('\n')]
y=[max(k)for k in g].index('P')
x=g[y].index('P')
m=[k[:]for k in g]
v=x;w=y
while'#'in sum(m,[]):x,y,(v,w)=v,w,[(x+a,y+b)for a,b in((1,0),(-1,0),(0,1),(0,-1))if'#'==m[y+b][x+a]][0];m[w][v]='_'
g[w][v]='A'
print('\n'.join(map(''.join,g)))
```
[Try it online!](https://tio.run/##XU/LboMwELz7Kyz5YG/jIFBviXzoH@S@tSqiEEKJDSIp2F9PDZRHM5Y8q9nZWbv2z1tl3/s@V4hvpb5WDS1pYWlVZ1bEEDVZehEQPep78RT803LQxCs0qRMlLO5cR4W9ZE7wEwfiVI7@n2IUlnjQGz9plTt2ypPuVtwzznhQHz9GGIkaDk56KVrZgQqXROF2qfS787gwlecQIUQiY5BiP1Esk/HeJwDFNcQpZTBMaAyjWmOsjwY7ja1W/IuTfK4/OKmbwk5fi76rEGzSWvCpljkA9D19BaFswIlNzNigjB228KAMHbYwoezlkLXLtsoMtubMoOuu1UW2jr/3vOIX "Python 3 – Try It Online")
---
Animation of the code running:
[](https://i.stack.imgur.com/hhVTT.gif)
[Answer]
## JavaScript (ES6), ~~193~~ 181 bytes
```
f=s=>s==(`P#1P#21#12#221A`[r=`replace`](/.../g,([n,f,t])=>s=s[r](eval(`/([${n+=f}])([^]{${s.search`\n`}})?(?!\\1)[${n}]/`),m=>m[r](eval(`/^${f}|${f}$/`),t))),s)?s[r](/\d/g,`#`):f(s)
```
Version that provides a looping animation:
```
f=s=>s==(`#A#1#12#221AP#1P#2`[r=`replace`](/.../g,([n,f,t])=>s=s[r](eval(`/([${n+=f}])([^]{${s.search`\n`}})?(?!\\1)[${n}]/`),m=>m[r](eval(`/^${f}|${f}$/`),t))),s)?s[r](/\d/g,`#`):s
;setInterval(_=>i.value=f(i.value),1e3)
```
```
<textarea rows=10 cols=20 id=i style="font-family:monospace"></textarea>
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~43~~ 42 bytes
```
32-I#fbbJ*+!w3>y"&)yy-|&X<]vJQ2/)G65b&Zj&(
```
The code accepts an arbitrary amount of space padding in the first and last rows and columns. Input is a rectangular array of chars, using `;` as row separator. For example, the input
```
#####
# #
## ##
# # ###
# ### #
# #
##### P
###
```
is represented as
```
['##### ';
'# # ';
'## ## ';
' # # ###';
' # ### #';
' # #';
' ##### P';
' ###']
```
or, in one line (so it can be entered through STDIN),
```
['##### '; '# # '; '## ## '; ' # # ###'; ' # ### #'; ' # #'; ' ##### P'; ' ###']
```
[**Try it online!**](https://tio.run/##y00syfn/39hI11M5LSnJS0tbsdzYrlJJTbOyUrdGLcImtswr0Ehf093MNEktKktN4///aHVlEFBQUFC3VlAH0XC2sgJcHCgI4inD2CA5KBsEoGywQQFgNlgUqD4WAA) Or verify the last four cases: [**1**](https://tio.run/##y00syfn/39hI11M5LSnJS0tbsdzYrlJJTbOyUrdGLcImtswr0Ehf093MNEktKktN4///aHVlEFBQUFC3VlAH0XC2sgJcHCgI4inD2CA5KBsEoGywQQFgNlgUqD4WAA), [**2**](https://tio.run/##y00syfn/39hI11M5LSnJS0tbsdzYrlJJTbOyUrdGLcImtswr0Ehf093MNEktKktN4///aHVlEAhQVlCGAHVrBXVlBRAACkFoiBBQDiwEpqFCyBAupAxXCxOCAWUks2BAAclGuDqwECpQjwUA), [**3**](https://tio.run/##y00syfn/39hI11M5LSnJS0tbsdzYrlJJTbOyUrdGLcImtswr0Ehf093MNEktKktN4///aHVlEAhQhgF1awV1ZQVkABUCyiEwVAgZwoVgahBCcJOQzFKGkwgbYWohQspIqkDuigUA), [**4**](https://tio.run/##y00syfn/39hI11M5LSnJS0tbsdzYrlJJTbOyUrdGLcImtswr0Ehf093MNEktKktN4///aHUFDKBurQASVQaBAGUYgImiKB1UoqhAPRYA) (these have been chosen because they have the most complicated curves; the last one has some space padding).
### Explanation
TL;WR: Complex numbers, lots of indexing, no convolution.
```
32- % Implicitly input char matrix. Subtract 32. Space becomes zero
I#f % 3-output find: pushes nonzero values, their row indices,
% and their column indices, as column vectors
bb % Bubble up twice, so row and column indices are on top
J*+ % Times 1j, add. This transforms row and column indices into
% complex numbers, where real is row and imaginary is column
! % Transpose into a row vector
w % Swap, so vector of nonzero values is on top
3> % Logical index of elements exceeding 3. ASCII codes of space,
% '#' and 'P0 are 32, 35 and 80 respectively. Since 32 was
% subtracted these became 0, 3 and 48. So the only entry with
% value exceeding 3 is that corresponding to the original 'P'.
y" % Do this as many times as the number of complex positions
% The stack now contains the vector of complex positions and an
% index into that vector. The index points to the complex position
% to be processed next.
&) % Two-output reference indexing: pushes the indexed entry and
% a vector with the remaining entries. This pulls off the
% current complex position, which is initially that of 'P'
yy % Duplicate top two elements, i.e. current position and vector
% of remaining positions
-| % Absolute differences
&X< % Index of minimum. Gives the index of the complex position
% that is closest to the current one. In case of tie (which
% only happens in the first iteration) it picks the first. The
% result is the index of the complex position to be processed in
% the next iteration. This index will be empty if this is the last
% iteration.
] % End
% The stack now contains the complex positions as individual
% values, starting from 'P' and sorted as per the curve; plus two
% empty arrays. These empty arrays have been produced by the last
% iteration as the index for the "next" iteration and the array of
% "remaining" complex positions
v % Concatenate into a column vector. The empty arrays have no effect.
% The resulting vector contains the sorted complex positions
JQ % Push 1j and add 1
2/ % Divide by 2. This gives (1+1j)/2. When used as an index this is
% interpreted as (1+end)/2. Since the length of the curve is even
% this gives a non-integer number, which will be implicitly
% rounded up (because of .5 fracctional part). As an example, for
% length 32 this gives 16.5, which rounded becomes 17. Position 17
% along the curve is the antipode of position 1
) % Reference indexing. Gives the complex position of the antipode
G % Push input char matrix again
65 % Push 65 (ASCII for 'A')
b % Bubble up, so complex position is on top
&Zj % Separate into real and imagimary parts, corresponding to row and
% column indices
&( % 4-input assignment indexing. This writes 'A' at the specified row
% and column of the char matrix. Implicitly display
```
[Answer]
# [Python 3](https://docs.python.org/3/), 421 bytes
```
l,e=len,enumerate
r=open(0).read()
n=lambda x:[(x[0]-1,x[1]),(x[0]+1,x[1]),(x[0],x[1]-1),(x[0],x[1]+1)]
p=a={(i,j):y for i,x in e(r.split('\n'))for j,y in e(x)}
t=l(r.split('\n'));s=l(r.split('\n')[0])
for i in a:p=[p,i][a[i]=='P']
w=[p]
while l(w)!=r.count('#')+1:
for x in a:
if x in n(w[-1])and a[x]!=' 'and x not in w:w+=[x]
a[w[(l(w)+1)//2]]='A';print('\n'.join(''.join(a[j,i]for i in range(s))for j in range(t)))
```
[Try it online!](https://tio.run/##vVBBbsMgELzzCiIfYGXixO3NEYf@IHfKgTakwSJrizgyUdW3u9hO2yQP6ByAmV2GWdpLd2jweRi8sNJbFBbPRxtMZ0mQTWuRr6EI1uw4EJTeHN92hsZK8ajWelmKqEoNYmL5HZvOy/KW5SVo0kojP7kTNVQXum8CdSJSh9TyUJxa7zrOXpEBjKVaXOZShC/SSf/Qsjk9SuklIJPpeM9UrVStcFoZ5bSUbMs06ZOU1oPzlnrew0KG4r05Y3LIGORlRaZUcTYglLr9TJD3apnGM7ijRkW9kIyykUSKTTd29FWfy1QhRvWKj@Zp4tXqSWvJXtimDQ7nnEXdOOTsuhtVp4y/qYPBD8tP1x/4UzoAGIZsxDb7AcnoLf6B3@Mb "Python 3 – Try It Online")
[Answer]
# Mathematica, ~~234~~ 223 bytes
```
(p=Position;v=p[#,"#"|"P"];n=Length@v;q=v[[#]]&;h=FindCycle[Graph[v,Join@@Table[If[Norm[q@i-q@j]==1,q@i<->q@j,Nothing],{i,n},{j,i-1}]]][[1,#,1]]&;ReplacePart[#,h@Mod[p[Table[h@x,{x,n}],p[#,"P"][[1]]][[1,1]]+n/2,n,1]->"A"])&
```
This code makes `v` be the vertex list for the graph: the indices of the `"#"` and `"P"`s. Then `n` is the length (necessarily even) and `q` extracts the input-th vertex (so ignoring the shape of the loop).
Then `h` is a function that builds the graph with vertices in `v` and undirected edges between vertices when the length of the difference of their index pairs is exactly 1 (so their difference is something like `{-1,0}` or `{0,1}`) and then finds a list of all cycles and provides the first (only) cycle (as a list of edges) and then takes the input-th edge and takes the first vertex making up that edge.
Using `h`, we can find the index of the `"P"` in the cycle, and go halfway around (using Mod to wrap around if we go past the bounds of the cycle list) to find the antipode, and then we can replace the corresponding entry of the original input `m` with `"A"`
You can **try it online** with by pasting the following at [the Wolfram Cloud Sandbox](http://sandbox.open.wolframcloud.com) and clicking "evaluate cell" or hitting Shift+Enter or Numpad Enter:
```
(p=Position;v=p[#,"#"|"P"];n=Length@v;q=v[[#]]&;h=FindCycle[Graph[v,Join@@Table[If[Norm[q@i-q@j]==1,q@i<->q@j,Nothing],{i,n},{j,i-1}]]][[1,#,1]]&;ReplacePart[#,h@Mod[p[Table[h@x,{x,n}],p[#,"P"][[1]]][[1,1]]+n/2,n,1]->"A"])&@{{"#","#","#","#","#"," "," "," "},{"#"," "," "," ","#"," "," "," "},{"#","#"," ","#","#"," "," "," "},{" ","#"," ","#"," ","#","#","#"},{" ","#"," ","#","#","#"," ","#"},{" ","#"," "," "," "," "," ","#"},{" ","#","#","#","#","#"," ","P"},{" "," "," "," "," ","#","#","#"}}//MatrixForm
```
## Alternative idea, 258 bytes
Slightly inspired by [ovs's Python solutions](https://codegolf.stackexchange.com/a/135016/41105), I tried to write code that would not use any graph theory features of Mathematica and just blindly calculate the distances. I couldn't get it as short, but suspect someone could improve it:
```
f[m_]:=(x="#";t=ReplacePart;p=Position;l=t[m,p[m,"P"][[1]]->0];v=p[l,x|0];n=Length[v];q=v[[#]]&;r=l[[q[#][[1]],q[#][[2]]]]&;y=t[l,q@#->(r@#2+1)]&;Do[If[Norm[q@i-q@j]==1&&Xor[r@i==x,r@j==x],If[r@i==x,l=y[i,j],l=y[j,i]]],n,{i,n},{j,n}];t[m,p[l,n/2][[1]]->"A"])`
```
This code is very inefficient. Basically, it replaces `"P"` with `0` and then looks for a `"#"` next to something that's not a `"#"` by looping through the entire thing twice and replaces them with numbers representing the distance from `"P"`, and to make sure it finishes, it does that process `n` times. This actually doesn't even calculate distances correctly since one branch could go past the antipode, but only one location will be numbered with `n/2` no matter what.
] |
[Question]
[
To simulate a zombie invasion, start with a grid of `#` and representing the map:
```
## ##
### #
## ##
# ###
# ####
```
* `#` represents land.
* represents water.
The zombies start at a point on the map...
```
## ##
### #
## %#
# ###
# ####
```
...and spread. `%` denotes land infected by zombies.
However, **zombies cannot swim**. They can move across land in the same way a king moves in chess - one square in any diagonal or orthogonal direction:
```
!!!
!%!
!!!
```
At the end of the simulation, some land will be infected with zombies:
```
%% ##
%%% #
%% %%
% %%%
# %%%%
```
Your task is to simulate the zombie invasion. Write a program (or function) that takes as input a string representing the initial state of the grid, and two numbers representing the coordinates of the initial zombie. The program should output (or return) the final state of the invasion.
# Specifications
* Your program may print an optional trailing newline.
* You can assume the input will be in the correct format (padded with spaces), with an optional trailing newline.
* You can assume the initial zombie will start on land and will not die immediately.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins.
* -100% bonus if your code can also solve the [Halting Problem](https://en.wikipedia.org/wiki/Halting_problem) for arbitrary Turing machines.
* Your program should handle board widths of up to 50 chars.
[Answer]
## Kotlin, 283 218 bytes
Unnamed lambda (with a nested function, heh).
**Golfed**
```
{i:String,x:Int,y:Int->val m=i.lines().map{it.toCharArray()};fun v(x:Int,y:Int){try{if(m[y][x]=='#'){m[y][x]='%';for(c in-1..1)for(d in-1..1)if(!(c==0&&d==0))v(x+c,y+d)}}catch(e:Exception){}};v(x, y);m.map(::println)}
```
**Ungolfed**
```
fun zombies(input: String, startX: Int, startY: Int) {
val m = input.lines().map(String::toCharArray) // build game map
fun invade(x: Int, y: Int) { // nested functions, woo!
try {
if (m[y][x] == '#') { // if land
m[y][x] = '%' // mark as invaded
for (dx in -1..1) { // generate neighbour tiles
for (dy in -1..1) {
if (!(dx == 0 && dy == 0)) {
invade(x + dx, y + dy) // attempt to invade neighbours
}
}
}
}
} catch(e: Exception) {} // catches ArrayIndexOutOfBounds
}
invade(startX, startY) // start the invasion
m.map(::println) // print final state
}
```
Saved quite a few bytes by switching to a recursive solution.
[Answer]
## JavaScript (ES6), 144 bytes
```
(s,x,y,l=s.search`\n`,g=s=>s==(s=s.replace(eval(`/(#|%)(.?[^]{${l-1}}.?)?(?!\\1)[#%]/`),`%$2%`))?s:g(s))=>g(s.slice(0,x+=y*l)+`%`+s.slice(x+1))
```
Where `\n` represents the literal newline character. Takes 0-indexed coordinates.
[Answer]
# Befunge, ~~324~~ 323 bytes
```
&00p&10p20p~$v<p02+g02*!g02:+1$$$$<
#<%>\"P"/8+p>1+:::~:0`!#v_:85+`!#^_2%\2%3*1+*\2/:"P"%\"P"/8+g+\2/:"P"
:+**73"="+g00*g02g010$$$$<v
02:\-<v/"P"\%"P":/2::_|#:$<:+1+g02\+g02:\-1+g02:\+1:\-1:\+1-g
\:20g^>g:30p\2%3*1+/4%1->#^_::2%6*2+30g+\2/:"P"%\"P"/p:20g-1-
0<v2\g+8/"P"\%"P":/2::<\_@#`0:-g
2^>%3*1+/4%1g,1+:20g%#^_1+55+,\
```
[Try it online!](http://befunge.tryitonline.net/#code=JjAwcCYxMHAyMHB-JHY8cDAyK2cwMiohZzAyOisxJCQkJDwKICM8JT5cIlAiLzgrcD4xKzo6On46MGAhI3ZfOjg1K2AhI15fMiVcMiUzKjErKlwyLzoiUCIlXCJQIi84K2crXDIvOiJQIgo6KyoqNzMiPSIrZzAwKmcwMmcwMTAkJCQkPHYKMDI6XC08di8iUCJcJSJQIjovMjo6X3wjOiQ8OisxK2cwMlwrZzAyOlwtMStnMDI6XCsxOlwtMTpcKzEtZwpcOjIwZ14-ZzozMHBcMiUzKjErLzQlMS0-I15fOjoyJTYqMiszMGcrXDIvOiJQIiVcIlAiL3A6MjBnLTEtCjA8djJcZys4LyJQIlwlIlAiOi8yOjo8XF9AI2AwOi1nCjJePiUzKjErLzQlMWcsMSs6MjBnJSNeXzErNTUrLFw&input=MyAyCiMjICAgIyMKIyMjICAgIwojIyAjIyAgCiAgIyAjIyMKIyAgIyMjIw)
**Explanation**
Implementing this in Befunge was a little bit complicated because we're limited to 80x25 characters of "memory" which has to be shared with the source code itself. The trick to fitting a 50x50 map into that area was to flatten the 2D map into a 1D array with two map locations per byte. This 1D array is then wrapped into a 2D array again so that it can fit in the 80 character width of the Befunge playfield.
The infection algorithm starts by converting the initial coordinates into an offset in the 1D array which it pushes onto the stack. The main loop takes a value from the stack and looks up the map state for that offset. If it's uninfected land, it gets marked as infected, and eight new offsets are pushed onto the stack (representing the land all around the current position). This process continues until the stack is empty.
To avoid having to check for out of range values, the map is stored with a one character water border around all the edges.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 44 [bytes](https://github.com/abrudz/SBCS)
```
{{c'%'[⌊⌿'%#'∊¨⍵(c←4⊃⍵)]}∘,⌺3 3⍣≡'%'@(⊂⍺)⊢⍵}
```
[Try it online!](https://tio.run/##rZPNitRAEMfveYqCYUkC2UEdRfAkKAsLfiF7Exl6ks6k2U537I/NDMteFGQ3zIgXwYsH3YsHj7uXvQg@Sr/IWN0Zx3HBg@AcMpVK1b9@XVVNGr5bzAmX05V792H/qXv7/sbq@DiPd@IXbtG5xfd4ZxC70@7HV7e8THL8ftt1b9BOX56404@ZW1yNYOSW5@7sMybdT1z32i2vUtd9waCT1cotP8EzTommIKShYCpi4GEoCYWk2ntB26aRyoCgLWcCnUyANoqJKXBmqCJcZzCxBpiJvKC0prFGQ14RRXIMgJpgeI6ZmjboM7SAyRxyohQjUwqKGquEhuTB89R/KGhJLDdDOJAQFGtySIFcF5xlMJcWKnKE4BKs9vwUSsm5bD2dngtDZve8RJBJlGwRS3JbYzW3vAiKeszEWAo69odDO@e2wOyxUYRxb@iGIHu6kTmoGKoQARPqi5aWAysDSkuE8SiBFx0KZCvAUG0wXlM9hD2pgM5I3XCaedoguHb4vvoDvLKYwKQALFOTAk@OjbN59fsgd@Au0seDAQAM/K//h2DAAHqXf8abnP01orS8wLkd@p71DfRHwRnKzXQCRT/qlpkKO1bXyJBk6d8Q4ixeUwQrgKC1ZvG@6zhPcN0yqGRLj6jK@sVbw8TmD5K6h1hvXz8ySB7tpcMoKD0m2LfSijz0LNF2UjOt0U6jqAS8E/Afr0xf8gAHhFv4q2gUhRGHUm75zXXneF3xDfNKTNq8JzdDqQtfzZPsxluhl9tpW3X6zYmiWzDqN@kfhv8T "APL (Dyalog Unicode) – Try It Online")
Assumes `⎕IO←0`.
Left argument: 0-indexed row `r` of %, 0-indexed column `c` of %: `r c`
Right argument: Character matrix
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 59 bytes
```
{(ac+b+b*Ya@?n):'%L2*#aa:RVaR.`#(.?.?.{`.y-1.`})?%`'%.@>_a}
```
A function that takes a multiline string, the row of the initial zombie (0-indexed), and the column of the initial zombie (0-indexed). [Try it online!](https://tio.run/##K8gs@J9m9b9aIzFZO0k7SSsy0cE@T9NKXdXHSEs5MdEqKCwxSC9BWUPPHgirE/QqdQ31Emo17VUT1FX1HOziE2v/a6RxKSkrKygoKCtzKUMYQFoBxOICsoEMIB8kq6ysxGWkYKz5HwA "Pip – Try It Online")
### How?
Because Pip has cyclical indexing (usually a good thing, but bad for this problem because we don't want the map edges to wrap), I went for a regex-replacement solution.
`Ya@?n` finds the index of the first newline (i.e. the width of the grid) and yanks it into `y`.
`(ac+b+b*Ya@?n):'%` after doing the above, computes `(width + 1) * row + col`, i.e. `c+b+b*y`, and sets the character at that index to `%`.
`L2*#a` loops `2*len(a)` times, which gives us enough iterations for the flood fill to fully propagate and makes sure the iteration count is even (that's important).
`.`#(.?.?.{`.y-1.`})?%`` constructs a regex that matches a `#` followed by a `%`, with either 0, width-1, width, or width+1 characters in between. (The `.` at the beginning makes `.` in the regex match newlines.) This regex matches any of the following configurations:
```
#
%
#
%
#
%
#%
```
`aR ... '%.@>_` replaces matches of this regex with the character `%` prepended to `.` all but the first character `@>` of the match `_`; in short, replacing the `#` with `%`.
`a:RV ...` reverses that and assigns it back to `a`. We reverse because the regex only matches `#` *before* `%` in the string, not after; but when the string is reversed, after becomes before and we can match it on the next iteration. This is also why the number of iterations has to be even.
After the loop is complete, we simply return the modified value of `a`.
[Answer]
# TSQL, 267 bytes
**Golfed:**
```
USE master
DECLARE @ varchar(max)=
'## ##
### #
## %#
# ###
# ####'
WHILE @@rowcount>0WITH C as(SELECT x+1i,substring(@,x+1,1)v,x/z r,x%z c
FROM spt_values CROSS APPLY(SELECT number x,charindex(char(10),@)z)z
WHERE type='P'and x<len(@))SELECT @=stuff(@,d.i,1,'%')FROM C,C D
WHERE'#%'=d.v+c.v and abs(c.r-d.r)<2and abs(c.c-d.c)<2PRINT @
```
**Ungolfed:**
```
USE master-- the script needs to be executed on the default master database
DECLARE @ varchar(max)=
'## ##
### #
## %#
# ###
# ####'
WHILE @@rowcount>0
WITH C as
(
SELECT x+1i,substring(@,x+1,1)v,x/z r,x%z c
FROM
spt_values
CROSS APPLY(SELECT number x,charindex(char(10),@)z)z
WHERE type='P'and x<len(@)
)
SELECT @=stuff(@,d.i,1,'%')FROM C,C D
WHERE'#%'=d.v+c.v and abs(c.r-d.r)<2and abs(c.c-d.c)<2
PRINT @
```
**[Try it out](https://data.stackexchange.com/stackoverflow/query/592795/ascii-art-zombie-invasion-simulation)**
[Answer]
# PHP, ~~209~~ ~~189~~ ~~188~~ 183 bytes
may be golfable
```
for($w=strpos($s=($a=$argv)[1],10),$s[$a[2]*++$w+$a[3]]="%";$t<$s;)for($t=$s,$i=0;""<$c=$s[$i++];)if($c>"$")for($y=-2;++$y<2;)for($x=3;$x--;)$s[$p=$i+$y*$w-$x]>"!"?$s[$p]="%":0;echo$s;
```
Run with `php -r '<code>' '<grid>' <y> <x>`
[Answer]
# J, 152 Bytes
Not very well golfed, I'm sure there's a way to remove those last few control structures.
```
f=:4 :0
c=.(' '"_)`({~&<y)@.((*./y<$x)*.*./y>:0 0)x if.c='#' do.x=.'%'(<y)}x[i=.0 while.i<9 do.i=.>:i[x=.x f y+i<:@(|~,<.@%)3 end.end.x
)
g=:>@cutLF@[f]
```
Implements a flood fill algorithm. The function g formats input into a character array before applying f.
Note that coordinates are a bit weird:
```
0, 0
```
is the top left corner. Increasing the first coordinate:
```
1, 0
```
Moves the position down in the y direction.
Other than that coordinates are normal.
### Example:
```
land =: 0 : 0 NB. Define a multi-line string
## ##
### #
## ##
# ###
# ####
)
] l =. >@cutLF land NB. Cut 'land' on new lines, and form into an array. Assign to 'l'
## ##
### #
## ##
# ###
# ####
NB. Looks the same, but it isn't.
'%' (<2 3)} l NB. 'Infect' the land at 2, 3
## ##
### #
## %#
# ###
# ####
l f 2 3 NB. Flood fill on l (already formatted), starting at 2 3
%% ##
%%% #
%% %%
% %%%
# %%%%
land g 2 3 NB. Flood fill on land, formats for us.
%% ##
%%% #
%% %%
% %%%
# %%%%
```
] |
[Question]
[
Write a program or function that given positive *n* and *m* calculates the number of valid distinct domino tilings you can fit in a *n* by *m* rectangle. This is sequence [A099390](https://oeis.org/A099390) in the *Online Encyclopedia of Integer Sequences*. You may take input in as function argument(s), CLA or on stdin, in any reasonable format. You must return or print a single integer as output.
Each tiling must not leave any gaps, and every distinct tiling is counted, including rotations, reflections, etc. For example, the tilings for 2x3 are:
```
|-- ||| --|
|-- ||| --|
```
Example inputs/outputs:
```
1, 9 -> 0
2, 2 -> 2
2, 3 -> 3
4, 4 -> 36
4, 6 -> 281
6, 6 -> 6728
7, 10 -> 53175517
```
Your program should theoretically work for any *n* and *m*, but if your program requires too much memory or your data type overflows it's excused. Your program must work correctly for any *n, m* <= 8 however.
---
Shortest code in bytes wins.
[Answer]
# Pyth, ~~30~~ 29 bytes
```
L?bsmy-tb]dfq1.a-VThbb1y*FUMQ
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=L%3Fbsmy-tb%5Ddfq1.a-VThbb1y*FUMQ&input=4%2C+6&test_suite_input=1%2C+9%0A2%2C+2%0A2%2C+3%0A4%2C+4%0A4%2C+6%0A6%2C+6%0A7%2C+10&debug=0) / [Test Suite](http://pyth.herokuapp.com/?code=L%3Fbsmy-tb%5Ddfq1.a-VThbb1y*FUMQ&input=4%2C+6&test_suite=1&test_suite_input=1%2C+9%0A2%2C+2%0A2%2C+3%0A4%2C+4%0A4%2C+6%0A6%2C+6%0A7%2C+10&debug=0)
All example inputs run in the online compiler. The last one takes a few seconds though.
### Explanation:
In my code I'll define a recursive function `y`. The function `y` takes a list of 2D-coordinates and returns the number of different domino tilings using these coordinates. E.g. `y([[0,0], [0,1]]) = 1` (one horizontal domino), `y([[0,0], [1,1]]) = 0` (coordinates are not adjacent) and `y([[0,0], [0,1], [1,0], [1,1]]) = 2` (either two horizontal or two vertical dominoes). After defining the function I'll call it with all coordinates `[x,y]` with `x in [0, 1, m-1], y in [0, 1, n-1]`.
How does the recursive function work? It's quite simple. If the list of coords is empty, there is exactly one valid tiling and `y` returns `1`.
Otherwise I take the first coordinate in the list `b[0]`, and search the remaining coordinates for a neighbors. If there is no neighbor to `b[0]`, then there is no tiling possible, therefore I return 0. If there is one or more neighbors, then the number of tilings is (the number of tilings where I connect `b[0]` with the first neighbor via a domina, plus the number of tilings where I connect `b[0]` with the second neighbor, plus ...) So I call the function recursively for each neighbor with the shortened list (by removing the two coords `b[0]` and neighbor). Afterwards I sum up all results and return them.
Because of the order of the coords there are always only two neighbors possible, the one on the right side and the one below. But my algorithm doesn't care about that.
```
UMQ convert the input numbers into ranges
*F Cartesian product (coords of each square)
L define a function y(b):
?b if len(b) > 0:
f b filter b for squares T, which satisfy:
.a-VThb Euclidean distance between T and b[0]
q1 is equal to 1 (direct neighbors)
m map each neighbor d to:
-tb]d remove d from b[1]
y and call recursively y with the rest
s sum all those values and return them
else:
1 return 1 (valid domino tiling found)
y*FUMQ Call y with all coords and print the result
```
[Answer]
# Matlab, 292
I am sure this can be shortened a lot just by porting it into another language.
The basic idea is bruteforcing: I came up with kind of an enumeration of all ways how to place `m*n/2` domino bricks on an `m*n` board. But this enumeration also includes many invalid tilings (bricks that overlap or go outside of the board.) So the program constructs all those tilings, and only counts the valid ones. The runtime complexity is about `O(2^(m*n/2) * m*n)`. Memory is not a problem for the `8x8` as it only needs `O(m*n)` memory. But the time needed for `8x8` is about 20 days.
Here the fully commented version that explains what is going on.
PS: If anyone knows how to make the Matlab syntax highlighting work, please include the corresponding tag in this answer!
```
function C=f(m,n)
d = ceil(m*n/2);%number of dominoes
%enumeration: %the nth bit in the enumeration says whether the nth
% domino pice is upright or not. we enumerate like this:
% firt piece goes top left:
% next piece goes to the left most column that has an empty spot, in the
% top most empty spot of that column
C=0;%counter of all valid tilings
for e=0:2^d-1 %go throu all enumerations
%check whether each enumeration is valid
A = ones(m,n);
%empty spots are filled with 1
%filled spots are 0 (or if overlapping <0)
v=1;%flag for the validity. hte grid is assumed to be valid until proven otherwise
for i=1:d %go throu all pieces, place them in A
%find the column where to place:
c=find(sum(A)>0,1);
%find the row where to place:
r=find(A(:,c)>0,1);
%find direction of piece:
b=de2bi(e,d);
if b(i)
x=0;y=1;
else
x=1;y=0;
end
%fill in the piece:
try
A(r:r+y,c:c+x)=A(r:r+y,c:c+x)-1;
catch z
v=0;break;
end
%check whether A has no overlapping pieces
if any(A(:)<0)
v=0;break;
end
end
%if valid, count it as valid
if v && ~norm(A(:))
disp(A)
C=C+1;
end
end
```
Here the fully golfed one:
```
function C=f(m,n);m=4;n=6;d=ceil(m*n/2);C=0;for e=0:2^d-1;A=ones(m,n);v=1;for i=1:d;c=find(sum(A)>0,1);r=find(A(:,c)>0,1);b=de2bi(e,d);if b(i);x=0;y=1;else;x=1;y=0;end;try;A(r:r+y,c:c+x)=A(r:r+y,c:c+x)-1;catch z;v=0;break;end;if any(A(:)<0);v=0;break;end;end;if v && ~norm(A(:));C=C+1;end;end
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 26 bytes
```
{⍎0⍕√|×/⌾/¨2×2○○,⍵}⍳÷∘⊂1∘+
```
[Try it online!](https://tio.run/##hY6xagJBEED7/YopFbN4u@ftmdomdqL@gHB304hapEgwaRIQUVeSQk4C6dNZiNhZeH8yP3KOU0eE5U0z7@0MJkOdvA6GY9Tpy3M6StKkpPWm06HZl3EKeUxp/vNW5HVanernP1vklvIlvwfyh3fy@@JI8y0tPgyPmpqSXwfkN7ekChssVtlipXZtlPec/z4qMz6NPVp8nnchzb756l63xew/tXtlBgYeVQYWrDBkNqAhdEwnjMEEivwvBNcVCB3YpgEX2yZEoYmjyMRKa61Qaig1lBpKDaWGUkOpXQA "APL (Dyalog Extended) – Try It Online")
A monadic tacit function that takes a 2-element vector `n m` as its sole argument.
A port of [fireflame241's Python answer](https://codegolf.stackexchange.com/a/209206/78410), and in turn an implementation of the formula:
$$
T(n,k)^2 = \left| \prod^n\_{a=1}{\prod^k\_{b=1}{2 \cos \frac{a\pi}{n+1}+2i \cos \frac{b\pi}{k+1}}} \right|
$$
Turns out that the results before rounding are pretty accurate (under `1e-14` relative error for the test cases), except when the result is expected to be zero.
### How it works
```
{⍎0⍕√|×/⌾/¨2×2○○,⍵}⍳÷∘⊂1∘+ ⍝ input←n m
⍳ ⍝ 2D array of all pairs of 1..n , 1..m
÷∘⊂ ⍝ divided by wrapped pair of
1∘+ ⍝ (n+1)(m+1)
{ ,⍵} ⍝ Ravel the 2D array, giving a vector of pairs
2×2○○ ⍝ 2×cos(pi × each number)
⌾/¨ ⍝ Convert each pair x,y to x + yi
×/ ⍝ Product of all complex numbers
| ⍝ Abs
√ ⍝ Sqrt
⍎0⍕ ⍝ Round the number by converting to string with
⍝ zero digits under decimal point, then evaling it back
```
[Answer]
# C89, 230 bytes
```
f(n,m,b)int*b;{int s,i;s=i=0;
while(b[i])if(++i==n*m)return 1;
if(i/n<m-1){b[i]=b[i+n]=1;s+=f(n,m,b);b[i]=b[i+n]=0;}
if(i%n<n-1&&!(b[i]|b[i+1])){b[i]=b[i+1]=1;s+=f(n,m,b);b[i]=b[i+1]=0;}
return s;}
g(n,m){int b[99]={};return f(n,m,b);}
```
For readability I handwrapped this answer - all newlines can safely be removed to get to 230 bytes.
Defines a function `int g(int n, int m)` that returns the number of tilings. It uses a helper function `f` that iterates over all valid tilings by placing one domino, recursing, and then removing the domino on a shared board.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~133~~ ~~121~~ 115 bytes
```
lambda m,n:round(abs(prod(2*cos((i//n+1)*pi/-~m)+2j*cos((i%n+1)*pi/-~n)for i in range(m*n)))**.5)
from math import*
```
[Try it online!](https://tio.run/##TctLCsIwEADQvacYECETo20S@1HwJm5Sa23ETEJaF268eoWqtdsHLzz71pMuQxya42m4G1fVBpygQ/QPqpmpOhair5niZ98xZpOE1hJ5sMnm5XCtbl9f/Zmw8REsWIJo6HphjhMicr7NcNFE78CZvgXrgo89H0K01LOGSQF7RFhCuviREqBGUnPSI@mJdgJ2H8rnln9mKSfMf5gXqpy0ECDTkTMtiyyTxfAG "Python 3.8 (pre-release) – Try It Online")
(Python 3.8 adds `math.prod` for product)
*-12 bytes thanks to @Bubbler*
Implements the following formula (from [OEIS A187596](http://oeis.org/A187596#:%7E:text=absolute%20value%20of)):
```
T(n,k)^2 = absolute value of Prod(Prod( 2*cos(a*Pi/(n+1)) + 2*i*cos(b*Pi/(k+1)), a = 1..n), b = 1..k), where i = sqrt(-1)
```
Since this multiplies (floating-point) complex numbers together, this loses precision for sufficiently large `n`, which is permitted by the challenge rules (effectively, data type overflows).
[Answer]
# JavaScript (ES7), ~~149 ... 145~~ 142 bytes
Expects `(n)(m)`.
```
m=>g=(n,a=[...Array(N=2**m-1).fill(0),1])=>n?g(n-1,a.map((_,i)=>a.reduce((p,c,k)=>p+c*!(h=(x,y)=>y&~x|(x?h(x>>1,x&!y):~k&~i&N))(k&i),0))):a[N]
```
[Try it online!](https://tio.run/##bczRaoMwGIbh812FPZH/tzE1sWpXiGU34A2UMkKqNlOj2G0oDG/dBSyMSQ@/94HvQ37Lu@p19@mb9prPhZgbkZYCDJHiTCl963s5Qia45zU@Q1rouoYACbugSM2pBOMzImkjO4B3om2UtM@vXyoH6IgilS3dVnkbuAkYyGjn6E7DDwynGwxpysjgbkY8TpU7aTdDhMrVSAJEPMpzdplVa@5tndO6LaEAhuC8Ijq7nRO8/CduiS/En1C4ULiivaX9g@InFj8eD2yF8R/GCT@sNEFgwaJRyJIoYsn8Cw "JavaScript (Node.js) – Try It Online")
### How?
I've described the algorithm in [my Python answer to *Domino Recurrence Generator*](https://codegolf.stackexchange.com/a/209203/58563).
The main difference is that it's shorter in JS to combine both state compatibility tests into the following recursive function than to use a regular expression.
```
( h = (x, y) =>
y & ~x | (
x ?
h(x >> 1, x & !y)
:
~k & ~i & N
)
)(k & i)
```
[Answer]
# Python 243
I opted for a brute force approach:
* generate m\*n/2 directions;
* try and fit the domino on the m\*n board.
If they all fit and no spaces are left we have a valid entry.
Here is the code:
```
import itertools as t
m,n=input()
c,u=0,m*n
for a in t.product([0,1],repeat=u/2):
l,k,r,h=[' ',]*u,0,'-|',[1,m]
for t in a:
l[k]=r[t]
k+=h[t]
if k%m<m and k/m<n and l[k]==' ':l[k]=r[t]
k=''.join(l).find(' ',1)
if k<0:c+=1
print c
```
] |
[Question]
[
The goal of this challenge is to write a program able to guess a word in the smallest possible number of attempts.
It is based on the concept of the Lingo TV show ([http://en.wikipedia.org/wiki/Lingo\_(U.S.\_game\_show)](http://en.wikipedia.org/wiki/Lingo_%28U.S._game_show%29)).
## Rules
Given a word length passed as the first argument on its command line, the player program disposes of **five** attempts to guess the word by writing a guess on its standard output followed by a single `\n` character.
After a guess is made, the program receives a string on its standard input, also followed by a single `\n` character.
The string has the same length as the word to guess and is comprised of a sequence of the following characters:
* `X`: which means that the given letter is not present in the word to guess
* `?`: which means that the given letter is present in the word to guess, but at another location
* `O`: which means that the letter at this location has been correctly guessed
For example, if the word to guess is `dents`, and the program sends the word `dozes`, it will receive `OXX?O` because `d` and `s` are correct, `e` is misplaced, and `o` and `z` are not present.
Be careful that if a letter is present more times in the guessing attempt than in the word to guess, it will **not** be marked as `?` and `O` more times than the number of occurences of the letter in the word to guess.
For example, if the word to guess is `cozies` and the program sends `tosses`, it will receive `XOXXOO` because there is only one `s` to locate.
Words are chosen from an english word list. If the word sent by the program is not a valid word of the correct length, the attempt is considered as an automatic failure and only `X`'s are returned.
The player program should assume that a file named `wordlist.txt` and containing one word per line is present in the current working directory, and can be read as necessary.
Guesses should only be comprised of alphabetic low-case characters (`[a-z]`).
No other network or file operations are allowed for the program.
The game ends when a string only comprised of `O` is returned or after the program has made 5 attempts and was not able to guess the word.
## Scoring
The score of a game is given by the given formula:
```
score = 100 * (6 - number_of_attempts)
```
So if the word is correctly guessed on the first try, 500 points are given. The last try is worth 100 points.
Failure to guess the word grants zero points.
## The pit
Player programs will be evaluated by trying to have them guess **100** random words for each word length between 4 and 13 characters inclusively.
Random word selection will be done by advance so all entries will have to guess the same words.
The winning program, and accepted answer, will be the one to reach the highest score.
Programs will be run in an Ubuntu virtual machine, using the code at <https://github.com/noirotm/lingo>. Implementations in any language are accepted as long as reasonable instructions to compile and/or run them are provided.
I'm providing a few test implementations in ruby in the git repository, feel free to take inspiration from them.
This question will be periodically updated with rankings for published answers so challengers can improve their entries.
The official final evaluation will take place on the **1st of July**.
## Update
Entries can now assume the presence of `wordlistN.txt` files to speed up reading the word list for the current word length for N between 4 and 13 inclusively.
For example, there is a `wordlist4.txt` file containing all four letter words, and `wordlist10.txt` containing all ten letter words, and so on.
## First round results
At the date of 2014-07-01, three entries have been submitted, with the following results:
```
4 5 6 7 8 9 10 11 12 13 Total
./chinese-perl-goth.pl 8100 12400 15700 19100 22100 25800 27900 30600 31300 33600 226600
java Lingo 10600 14600 19500 22200 25500 28100 29000 31600 32700 33500 247300
./edc65 10900 15800 22300 24300 27200 29600 31300 33900 33400 33900 262600
** Rankings **
1: ./edc65 (262600)
2: java Lingo (247300)
3: ./chinese-perl-goth.pl (226600)
```
All entries performed consistently, with a clear winner, being @edc65's C++'s entry.
All contestants are pretty awesome. I have been unable so far to even beat @chinese-perl-goth.
If more entries are submitted, another evaluation will take place. Current entries can also be improved if you feel like you can do better.
[Answer]
# C++ 267700 Points
A porting from an old MasterMind engine.
Differences from MasterMind:
* More slots
* More symbols
* Bigger solution space (but non so much, because not all symbols combination allowed)
* The response is much informative, so we have more information after each guess
* The response is slower to generate and that's a pity because my algorithm have to do it a lot.
The basic idea is choosing the word that minimize the solution space. The algorithm is really slow for the first guess (I mean 'days'), but the best first guess depends only on the word len, so it's hardcoded in the source. The other guesses are done in matter of seconds.
**The Code**
(Compile with g++ -O3)
```
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
class LRTimer
{
private:
time_t start;
public:
void startTimer(void)
{
time(&start);
}
double stopTimer(void)
{
return difftime(time(NULL),start);
}
};
#define MAX_WORD_LEN 15
#define BIT_QM 0x8000
LRTimer timer;
int size, valid, wordLen;
string firstGuess[] = { "", "a", "as", "iao", "ares",
"raise", "sailer", "saltier", "costlier", "clarities",
"anthelices", "petulancies", "incarcerates", "allergenicity" };
class Pattern
{
public:
char letters[MAX_WORD_LEN];
char flag;
int mask;
Pattern()
: letters(), mask(), flag()
{
}
Pattern(string word)
: letters(), mask(), flag()
{
init(word);
}
void init(string word)
{
const char *wdata = word.data();
for(int i = 0; i < wordLen; i++) {
letters[i] = wdata[i];
mask |= 1 << (wdata[i]-'a');
}
}
string dump()
{
return string(letters);
}
int check(Pattern &secret)
{
if ((mask & secret.mask) == 0)
return 0;
char g[MAX_WORD_LEN], s[MAX_WORD_LEN];
int r = 0, q = 0, i, j, k=99;
for (i = 0; i < wordLen; i++)
{
g[i] = (letters[i] ^ secret.letters[i]);
if (g[i])
{
r += r;
k = 0;
g[i] ^= s[i] = secret.letters[i];
}
else
{
r += r + 1;
s[i] = 0;
}
}
for (; k < wordLen; k++)
{
q += q;
if (g[k])
{
for (j = 0; j < wordLen; j++)
if (g[k] == s[j])
{
q |= BIT_QM;
s[j] = 0;
break;
}
}
}
return r|q;
}
int count(int ck, int limit);
int propcheck(int limit);
void filter(int ck);
};
string dumpScore(int ck)
{
string result(wordLen, 'X');
for (int i = wordLen; i--;)
{
result[i] = ck & 1 ? 'O' : ck & BIT_QM ? '?' : 'X';
ck >>= 1;
}
return result;
}
int parseScore(string ck)
{
int result = 0;
for (int i = 0; i < wordLen; i++)
{
result += result + (
ck[i] == 'O' ? 1 : ck[i] == '?' ? BIT_QM: 0
);
}
return result;
}
Pattern space[100000];
void Pattern::filter(int ck)
{
int limit = valid, i = limit;
// cerr << "Filter IN Valid " << setbase(10) << valid << " This " << dump() << "\n";
while (i--)
{
int cck = check(space[i]);
// cerr << setbase(10) << setw(8) << i << ' ' << space[i].dump()
// << setbase(16) << setw(8) << cck << " (" << Pattern::dumpScore(cck) << ") ";
if ( ck != cck )
{
// cerr << " FAIL\r" ;
--limit;
if (i != limit)
{
Pattern t = space[i];
space[i] = space[limit];
space[limit] = t;
}
}
else
{
// cerr << " PASS\n" ;
}
}
valid = limit;
// cerr << "\nFilter EX Valid " << setbase(10) << valid << "\n";
};
int Pattern::count(int ck, int limit)
{
int i, num=0;
for (i = 0; i < valid; ++i)
{
if (ck == check(space[i]))
if (++num >= limit) return num;
}
return num;
}
int Pattern::propcheck(int limit)
{
int k, mv, nv;
for (k = mv = 0; k < valid; ++k)
{
int ck = check(space[k]);
nv = count(ck, limit);
if (nv >= limit)
{
return 99999;
}
if (nv > mv) mv = nv;
}
return mv;
}
int proposal(bool last)
{
int i, minnv = 999999, mv, result;
for (i = 0; i < valid; i++)
{
Pattern& guess = space[i];
// cerr << '\r' << setw(6) << i << ' ' << guess.dump();
if ((mv = guess.propcheck(minnv)) < minnv)
{
// cerr << setw(6) << mv << ' ' << setw(7) << setiosflags(ios::fixed) << setprecision(0) << timer.stopTimer() << " s\n";
minnv = mv;
result = i;
}
}
if (last)
return result;
minnv *= 0.75;
for (; i<size; i++)
{
Pattern& guess = space[i];
// cerr << '\r' << setw(6) << i << ' ' << guess.dump();
if ((mv = guess.propcheck(minnv)) < minnv)
{
// cerr << setw(6) << mv << ' ' << setw(7) << setiosflags(ios::fixed) << setprecision(0) << timer.stopTimer() << " s\n";
minnv = mv;
result = i;
}
}
return result;
}
void setup(string wordfile)
{
int i = 0;
string word;
ifstream infile(wordfile.data());
while(infile >> word)
{
if (word.length() == wordLen) {
space[i++].init(word);
}
}
infile.close();
size = valid = i;
}
int main(int argc, char* argv[])
{
if (argc < 2)
{
cerr << "Specify word length";
return 1;
}
wordLen = atoi(argv[1]);
timer.startTimer();
setup("wordlist.txt");
//cerr << "Words " << size
// << setiosflags(ios::fixed) << setprecision(2)
// << " " << timer.stopTimer() << " s\n";
valid = size;
Pattern Guess = firstGuess[wordLen];
for (int t = 0; t < 5; t++)
{
cout << Guess.dump() << '\n' << flush;
string score;
cin >> score;
int ck = parseScore(score);
//cerr << "\nV" << setw(8) << valid << " #"
// << setw(3) << t << " : " << Guess.dump()
// << " : " << score << "\n";
if (ck == ~(-1 << wordLen))
{
break;
}
Guess.filter(ck);
Guess = space[proposal(t == 3)];
}
// cerr << "\n";
double time = timer.stopTimer();
//cerr << setiosflags(ios::fixed) << setprecision(2)
// << timer.stopTimer() << " s\n";
return 0;
}
```
**My scores**
Evaluation with lingo, 100 rounds:
```
4 9000
5 17700
6 22000
7 25900
8 28600
9 29700
10 31000
11 32800
12 33500
13 34900
```
Total 265'100
**Self evalueted scores**
Here are my average points, scored on the whole wordlist. Not completely relyable because some detail of algorithm has changed during the tests.
```
4 # words 6728 PT AVG 100.98 87170.41 s
5 # words 14847 PT AVG 164.44 42295.38 s
6 # words 28127 PT AVG 212.27 46550.00 s
7 # words 39694 PT AVG 246.16 61505.54 s
8 # words 49004 PT AVG 273.23 63567.45 s
9 # words 50655 PT AVG 289.00 45438.70 s
10 # words 43420 PT AVG 302.13 2952.23 s
11 # words 35612 PT AVG 323.62 3835.00 s
12 # words 27669 PT AVG 330.19 5882.98 s
13 # words 19971 PT AVG 339.60 2712.98 s
```
According to these numbers, my average score should be near 257'800
**PIT SCORE**
At last I installed Ruby, so now I have an 'official' score:
```
4 5 6 7 8 9 10 11 12 13 TOTAL
10700 16300 22000 25700 27400 30300 32000 33800 34700 34800 267700
```
[Answer]
## Java, 249700 points (beats Chinese Perl Goth in my test)
Updated ranklist:
```
4 5 6 7 8 9 10 11 12 13 Total
perl chinese_perl_goth.pl 6700 12300 16900 19200 23000 26100 28500 29600 32100 33900 228300
java Lingo 9400 14700 18900 21000 26300 28700 30300 32400 33800 34200 249700
```
Here is the **old** ranklist using `pit.rb`:
```
4 5 6 7 8 9 10 11 12 13 Total
ruby player-example.rb 200 400 400 500 1800 1400 1700 1600 3200 4400 15600
ruby player-example2.rb 2700 3200 2500 4300 7300 6300 8200 10400 13300 15000 73200
ruby player-example3.rb 4500 7400 9900 13700 15400 19000 19600 22300 24600 27300 163700
perl chinese_perl_goth.pl 6400 14600 16500 21000 22500 26000 27200 30600 32500 33800 231100
java Lingo 4800 13100 16500 21400 27200 29200 30600 32400 33700 36100 245000
** Rankings **
1: java Lingo (245000)
2: perl chinese_perl_goth.pl (231100)
3: ruby player-example3.rb (163700)
4: ruby player-example2.rb (73200)
5: ruby player-example.rb (15600)
```
~~Compared to @chineseperlgoth, I lose in shorter words (< 6 chars) but I win in longer words (>= 6 chars).~~
The idea is similar to @chineseperlgoth, it's just that my main idea is about finding the guess (can be any word of the same length, not necessarily one of the remaining possibilities) which gives the most information for the next guess.
~~Currently I'm still playing with the formula, but for the scoreboard above, I choose the word which will yield the minimum for:~~
```
-num_confusion * entropy
```
The latest version uses different scoring to find next best guess, which is maximizing the number of "single possibility" after the current guess. This is done by trying all words in pruned wordlist (to save time) on all possible candidates, and see which guess is more probable to produce "single possibility" (that is, after this guess there will only be one possible answer) for the next guess.
So for example this run:
```
Starting new round, word is boons
Got: seora
Sent: ?XOXX
Got: topsl
Sent: XOX?X
Got: monks
Sent: XO?XO
Got: bewig
Sent: OXXXX
Got: boons
Sent: OOOOO
Round won with score 100
```
From the first three guesses, we already got "\*oo\*s" with an "n" somewhere and we still need to figure out one more letter. Now the beauty of this algorithm is that instead of guessing words which are similar to that form, it instead guesses the word which has no relation to previous guesses at all, trying to give more letters, hopefully revealing the missing letter. In this case it happens to also get the position for the missing "b" correctly, and concludes with the correct final guess "boons".
Here is the code:
```
import java.util.*;
import java.io.*;
class Lingo{
public static String[] guessBestList = new String[]{
"",
"a",
"sa",
"tea",
"orae",
"seora", // 5
"ariose",
"erasion",
"serotina",
"tensorial",
"psalterion", // 10
"ulcerations",
"culteranismo",
"persecutional"};
public static HashMap<Integer, ArrayList<String>> wordlist = new HashMap<Integer, ArrayList<String>>();
public static void main(String[] args){
readWordlist("wordlist.txt");
Scanner scanner = new Scanner(System.in);
int wordlen = Integer.parseInt(args[0]);
int roundNum = 5;
ArrayList<String> candidates = new ArrayList<String>();
candidates.addAll(wordlist.get(wordlen));
String guess = "";
while(roundNum-- > 0){
guess = guessBest(candidates, roundNum==4, roundNum==0);
System.out.println(guess);
String response = scanner.nextLine();
if(isAllO(response)){
break;
}
updateCandidates(candidates, guess, response);
//print(candidates);
}
}
public static void print(ArrayList<String> candidates){
for(String str: candidates){
System.err.println(str);
}
System.err.println();
}
public static void readWordlist(String path){
try{
BufferedReader reader = new BufferedReader(new FileReader(path));
while(reader.ready()){
String word = reader.readLine();
if(!wordlist.containsKey(word.length())){
wordlist.put(word.length(), new ArrayList<String>());
}
wordlist.get(word.length()).add(word);
}
} catch (Exception e){
System.exit(1);
}
}
public static boolean isAllO(String response){
for(int i=0; i<response.length(); i++){
if(response.charAt(i) != 'O') return false;
}
return true;
}
public static String getResponse(String word, String guess){
char[] wordChar = word.toCharArray();
char[] result = new char[word.length()];
Arrays.fill(result, 'X');
for(int i=0; i<guess.length(); i++){
if(guess.charAt(i) == wordChar[i]){
result[i] = 'O';
wordChar[i] = '_';
}
}
for(int i=0; i<guess.length(); i++){
if(result[i] == 'O') continue;
for(int j=0; j<wordChar.length; j++){
if(result[j] == 'O') continue;
if(wordChar[j] == guess.charAt(i)){
result[i] = '?';
wordChar[j] = '_';
break;
}
}
}
return String.valueOf(result);
}
public static void updateCandidates(ArrayList<String> candidates, String guess, String response){
for(int i=candidates.size()-1; i>=0; i--){
String candidate = candidates.get(i);
if(!response.equals(getResponse(candidate, guess))){
candidates.remove(i);
}
}
}
public static int countMatchingCandidates(ArrayList<String> candidates, String guess, String response){
int result = 0;
for(String candidate: candidates){
if(response.equals(getResponse(candidate, guess))){
result++;
}
}
return result;
}
public static String[] getSample(ArrayList<String> words, int size){
String[] result = new String[size];
int[] indices = new int[words.size()];
for(int i=0; i<words.size(); i++){
indices[i] = i;
}
Random rand = new Random(System.currentTimeMillis());
for(int i=0; i<size; i++){
int take = rand.nextInt(indices.length-i);
result[i] = words.get(indices[take]);
indices[take] = indices[indices.length-i-1];
}
return result;
}
public static String guessBest(ArrayList<String> candidates, boolean firstGuess, boolean lastGuess){
if(candidates.size() == 1){
return candidates.get(0);
}
String minGuess = candidates.get(0);
int wordlen = minGuess.length();
if(firstGuess && guessBestList[wordlen].length()==wordlen){
return guessBestList[wordlen];
}
int minMatches = Integer.MAX_VALUE;
String[] words;
if(lastGuess){
words = candidates.toArray(new String[0]);
} else if (candidates.size()>10){
words = bestWords(wordlist.get(wordlen), candidates, 25);
} else {
words = wordlist.get(wordlen).toArray(new String[0]);
}
for(String guess: words){
double sumMatches = 0;
for(String word: candidates){
int matches = countMatchingCandidates(candidates, guess, getResponse(word, guess));
if(matches == 0) matches = candidates.size();
sumMatches += (matches-1)*(matches-1);
}
if(sumMatches < minMatches){
minGuess = guess;
minMatches = sumMatches;
}
}
return minGuess;
}
public static String[] bestWords(ArrayList<String> words, ArrayList<String> candidates, int size){
int[] charCount = new int[123];
for(String candidate: candidates){
for(int i=0; i<candidate.length(); i++){
charCount[(int)candidate.charAt(i)]++;
}
}
String[] tmp = (String[])words.toArray(new String[0]);
Arrays.sort(tmp, new WordComparator(charCount));
String[] result = new String[size+Math.min(size, candidates.size())];
String[] sampled = getSample(candidates, Math.min(size, candidates.size()));
for(int i=0; i<size; i++){
result[i] = tmp[tmp.length-i-1];
if(i < sampled.length){
result[size+i] = sampled[i];
}
}
return result;
}
static class WordComparator implements Comparator<String>{
int[] charCount = null;
public WordComparator(int[] charCount){
this.charCount = charCount;
}
public Integer count(String word){
int result = 0;
int[] multiplier = new int[charCount.length];
Arrays.fill(multiplier, 1);
for(char chr: word.toCharArray()){
result += multiplier[(int)chr]*this.charCount[(int)chr];
multiplier[(int)chr] = 0;
}
return Integer.valueOf(result);
}
public int compare(String s1, String s2){
return count(s1).compareTo(count(s2));
}
}
}
```
[Answer]
# Perl
There's still some room for improvement but at least it beats the included example players :)
Assumes write access to current directory for caching wordlists (to make it run a bit faster); will create `wordlist.lenN.stor` files using `Storable`. If this is an issue, remove `read_cached_wordlist` and change the code to use just `read_wordlist`.
## Explanation
First, I build a histogram of letter frequencies in all the words in the current wordlist (`build_histogram`). Then I need to choose my next guess - which is done by `find_best_word`. The scoring algorithm is just adding the histogram values together, skipping letters already seen. This gives me a word containing the most frequent letters in the wordlist. If there is more than one word with a given score, I choose one randomly.
Having found a word, I send it to the game engine, read the reply then try and do something useful with it :)
I maintain a set of conditions, that is, letters that can occur at a given position in a word. On start, this is just simple `(['a'..'z'] x $len)`, but it is updated basing on the hints given in reply (see `update_conds`). I build a regex out of those conditions then and filter the wordlist through it.
During tests I have found out then that the aforementioned filtering doesn't handle `?`s too well, hence the second filter (`filter_wordlist_by_reply`). This takes advantage of the fact that a letter marked as `?` occurs in the word on a different position, and filters the wordlist accordingly.
These steps are repeated for every iteration of the main loop, unless the solution is found (or it is not possible to read from stdin anymore, which means a failure).
## Code
```
#!perl
use strict;
use warnings;
use v5.10;
use Storable;
$|=1;
sub read_wordlist ($) {
my ($len) = @_;
open my $w, '<', 'wordlist.txt' or die $!;
my @wordlist = grep { chomp; length $_ == $len } <$w>;
close $w;
\@wordlist
}
sub read_cached_wordlist ($) {
my ($len) = @_;
my $stor = "./wordlist.len$len.stor";
if (-e $stor) {
retrieve $stor
} else {
my $wl = read_wordlist $len;
store $wl, $stor;
$wl
}
}
sub build_histogram ($) {
my ($wl) = @_;
my %histo = ();
for my $word (@$wl) {
$histo{$_}++ for ($word =~ /./g);
}
\%histo
}
sub score_word ($$) {
my ($word, $histo) = @_;
my $score = 0;
my %seen = ();
for my $l ($word =~ /./g) {
if (not exists $seen{$l}) {
$score += $histo->{$l};
$seen{$l} = 1;
}
}
$score
}
sub find_best_word ($$) {
my ($wl, $histo) = @_;
my @found = (sort { $b->[0] <=> $a->[0] }
map [ score_word($_, $histo), $_ ], @$wl);
return undef unless @found;
my $maxscore = $found[0]->[0];
my @max;
for (@found) {
last if $_->[0] < $maxscore;
push @max, $_->[1];
}
$max[rand @max]
}
sub build_conds ($) {
my ($len) = @_;
my @c;
push @c, ['a'..'z'] for 1..$len;
\@c
}
sub get_regex ($) {
my ($cond) = @_;
local $" = '';
my $r = join "", map { "[@$_]" } @$cond;
qr/^$r$/
}
sub remove_cond ($$$) {
my ($conds, $pos, $ch) = @_;
return if (scalar @{$conds->[$pos]} == 1);
return unless grep { $_ eq $ch } @{$conds->[$pos]};
$conds->[$pos] = [ grep { $_ ne $ch } @{$conds->[$pos]} ]
}
sub add_cond ($$$) {
my ($conds, $pos, $ch) = @_;
return if (scalar @{$conds->[$pos]} == 1);
return if grep { $_ eq $ch } @{$conds->[$pos]};
push @{$conds->[$pos]}, $ch
}
sub update_conds ($$$$) {
my ($word, $reply, $conds, $len) = @_;
my %Xes;
%Xes = ();
for my $pos (reverse 0..$len-1) {
my $r = substr $reply, $pos, 1;
my $ch = substr $word, $pos, 1;
if ($r eq 'O') {
$conds->[$pos] = [$ch]
}
elsif ($r eq '?') {
for my $a (0..$len-1) {
if ($a == $pos) {
remove_cond $conds, $a, $ch
} else {
unless (exists $Xes{$a} and $Xes{$a} eq $ch) {
add_cond($conds, $a, $ch);
}
}
}
}
elsif ($r eq 'X') {
$Xes{$pos} = $ch;
for my $a (0..$len-1) {
remove_cond $conds, $a, $ch
}
}
}
}
sub uniq ($) {
my ($data) = @_;
my %seen;
[ grep { !$seen{$_}++ } @$data ]
}
sub filter_wordlist_by_reply ($$$) {
my ($wl, $word, $reply) = @_;
return $wl unless $reply =~ /\?/;
my $newwl = [];
my $len = length $reply;
for my $pos (0..$len-1) {
my $r = substr $reply, $pos, 1;
my $ch = substr $word, $pos, 1;
next unless $r eq '?';
for my $a (0..$len-1) {
if ($a != $pos) {
if ('O' ne substr $reply, $a, 1) {
push @$newwl, grep { $ch eq substr $_, $a, 1 } @$wl
}
}
}
}
uniq $newwl
}
my $len = $ARGV[0] or die "no length";
my $wl = read_cached_wordlist $len;
my $conds = build_conds $len;
my $c=0;
do {
my $histo = build_histogram $wl;
my $word = find_best_word $wl, $histo;
die "no candidates" unless defined $word;
say $word;
my $reply = <STDIN>;
chomp $reply;
exit 1 unless length $reply;
exit 0 if $reply =~ /^O+$/;
update_conds $word, $reply, $conds, $len;
$wl = filter_wordlist_by_reply $wl, $word, $reply;
$wl = [ grep { $_ =~ get_regex $conds } @$wl ]
} while 1
```
] |
[Question]
[
A problem I sometimes encounter is that when writing comments using LaTeX, the comment is too long. Today you will solve this, by writing code which, given a LaTeX math expression, will produce the shortest equivalent expression.
To define equivalent expressions, we will need to specify a (simplified) parser for LaTeX:
## Tokenizer
Given an expression, it is first processed by tokenizing it. To tokenize an expression, it is processed from left to right. Most characters are a token by themselves, except whitespaces which are ignored, and `\` which has special behavior - if it's followed by a non-letter character, then it and the character become a token. Otherwise, it and all following letters become a token.
For example, `\sum_{n \leq r^2} {\frac{v(n)}{n}} + \frac1n \in \{1,2,3\}` is tokenized as `\sum _ { n \leq r ^ 2 } { \frac { v ( n ) } { n } } + \frac 1 n \in \{ 1 , 2 , 3 \}` (with tokens seperated by a space).
## Parsing
If the `{` and `}` aren't validly matched, this is an invalid LaTeX equation. You can assume this won't be the case in the input.
Now, to parse the LaTeX, we will look at the arity of each token. Most tokens have an arity of 0, and we will only have the following exceptions: `_`, `^`, and `\sqrt` (*note*: this isn't fully accurate for `_` and `^`, since they expect a subformula and not an argument, but we'll ignore this for simplicity's sake) have an arity of 1, and `\frac` has an arity of 2. Each token will bind a number of tokens as its arity, but tokens surrounded by `{` `}` are considered a single token for this purpose. For example, the above equation will bind as
`\sum _({ n \leq r ^ 2 }) { \frac({ v ( n ) }, { n }) } + \frac(1, n) \in \{ 1 , 2 , 3 \}`.
Finally, all `{` and `}` are removed, so our parsed equation will become `\sum _(n \leq r ^ 2) \frac(v ( n ), n) + \frac(1, n) \in \{ 1 , 2 , 3 \}`.
We will say two expressions are equivalent if their parsed version is the same.
# Input
A valid LaTeX math expression (the braces are matched, and each token has enough tokens to bind to). You may assume it only contains ASCII characters. You can use any reasonable string I/O, but you can't take it pre-parsed. You can assume there are no empty braces, and the only whitespace is a space.
# Output
The shortest equivalent LaTeX math expression. You can use any reasonable string I/O (not necessarily the same as the input), but you can't output a parse tree or something similar.
# Testcases
```
\sum_{n \leq r^2} {\frac{v(n)}{n}} + \frac1n \in \{1,2,3\} -> \sum_{n\leq r^2}\frac{v(n)}n+\frac1n\in\{1,2,3\}
\a{b c}d -> \a bcd
\sqrt{b c}d -> \sqrt{bc}d
\sqrt{2 2}d -> \sqrt{22}d
\sqrt{a}d -> \sqrt ad
\sqrt{2}d -> \sqrt2d
\frac{1}{2} -> \frac12
\frac{12}{3} -> \frac{12}3
\frac{2}{n} -> \frac2n
\frac{a}{n} -> \frac an
\frac{a+1}{n} -> \frac{a+1}n
\frac{\frac12}3 -> \frac{\frac12}3
\frac{\sqrt2}3 -> \frac{\sqrt2}3
\frac {1} {23} -> \frac1{23}
\a b -> \a b
^{a b} -> ^{ab}
{ab}_{\log} -> ab_\log
{\sqrt{2}}^2 -> \sqrt2^2
\frac{\frac{\frac{1}{\sqrt{x_{1}}}+1}{\sqrt{x_{2}+1}}+2}{\sqrt{x_{3}+2}}+3 -> \frac{\frac{\frac1{\sqrt{x_1}}+1}{\sqrt{x_2+1}}+2}{\sqrt{x_3+2}}+3
\sqrt{\{} -> \sqrt\{
```
Note that `{ab}_{\log} -> ab_\log`, for example, isn't correct in real LaTeX.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 202 bytes
```
M!`\\[A-Za-z]+|\\?.
A`^
+`(?<!\\)\{¶(.+)¶}
$1
+`(?<!\\|(?<!\\)[_^]¶|\\sqrt¶|\\frac¶(\{¶(((\{)|(?<-4>})|[^{}])+)¶}(?(4)^)¶|.+¶)?)\{¶(((\{)|(?<-7>})|[^{}])+)¶}(?(7)^)
$5
(\\[A-Za-z]+¶)([A-Za-z])
$1 $2
¶
```
[Try it online!](https://tio.run/##ZY9BTsMwEEX3PoUrBcmW20pxirpBRF2x4gLUdeKWgiqVoKYFISZzrRwgFwtjt0kDLJK8P/7z/VNuT7vCtTfiIW8fR7kxy8XkyU2@V6oyJp2yRW45U7lI70bGSANNLaZKNjWyKO7n1eV4mdlVU9Pi8VCeAryUbkMrYU/QR3rrZHaPslpawJUMWSIVM2mJqqlqapnKP/75f/@c/Cy6ZWLQmFZFJ@gw5pFmTc3a1hw/3jIouNlvD7y0GjmEZvApColQIHLFwyQm044eiMd6nBhkxsGab/CZhX/6xZrrnt116imEx0iiY42QdEL7Ky/shqzigTr30Zh02sf3klM8B@0zHV8zC/RGBm6NGZj9@ytx1wetHkZC3@5s@MqIEdVwoL1EpQejxEtUyQ8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
M!`\\[A-Za-z]+|\\?.
```
Tokenise the input.
```
A`^
```
Delete unquoted spaces.
```
+`(?<!\\)\{¶(.+)¶}
$1
```
Remove `{}`s surrounding a single token.
```
+`(?<!\\|(?<!\\)[_^]¶|\\sqrt¶|\\frac¶(\{¶(((\{)|(?<-4>})|[^{}])+)¶}(?(4)^)¶|.+¶)?)\{¶(((\{)|(?<-7>})|[^{}])+)¶}(?(7)^)
$5
```
Remove matched `{}`s that don't follow `\`, `_`, `^`, `\sqrt`, `\frac`, or aren't the second argument to `frac`.
```
(\\[A-Za-z]+¶)([A-Za-z])
$1 $2
```
If a quoted word is followed by a bare letter, insert a space.
```
¶
```
Join everything together.
[Answer]
# Python3, 442 bytes:
```
lambda s:R(f(re.findall(r'\\\W|\\[a-z]+|\S',s)))
import re
def R(I):
r=[]
for i in I:r+=[' '*(r!=[]and r[-1][0]=='\\'and[]!=re.findall('^[a-z]',i))+i]
return''.join(r)
def f(s,p=0):
v={'\\sqrt':1,'^':1,'_':1,'\\frac':2}
if[]==s:return
if(t:=s.pop(0))in v:k=f(s,1);yield from[t,*[next(k)for _ in range(v[t])]]
if'{'==t:T=[t,*f(s),'}'];yield R([T[1:-1],T][p and len(T)>3])
if'}'!=t:
if t not in v and'{'!=t:yield t
yield from f(s,p)
```
[Try it online!](https://tio.run/##dVHBbuMgFLz7K15OQO1GMb6svGKPlXrNRtoDOBGp7a63DnYJjdqlfHsWnGibtPYF8WYeM@8N/Zv53ansW6@Pd0wcW7nblhL2@RLXWFfzulGlbFuskRDi17sQXN7@LeJ38RMle0JI1Oz6ThvQVVRWNSzxPckj0IwXEdSdhgYaBfe5jhlHgG6wnnlKqhI0v00LvigY88rII7yYsQtDtB6cUNIQEjdeTVfmRSuE5n@6RmFNBr8a75OeLYLngVmvtH/WBuVpgtbDuRlOIWotH1BOXQRNzb3nPj/JhRqbnO3nfdfjBSF@2kP@xIJuSr6/NVVbQq27HTfJDVfVq8FPJOy1CXtpqR4rfOCmIEURpJBFjJl8xUK71yAJcqg4yywxX/E092snq4L3EFJoK4VX5EdWkOG5QzP/PAJ/BwOqM8HlEDq9cqBOSsZ3fIx2CoEce90og@9wSOFlt7EKhGirZ9Br6sCeMrAHrIizyjmI4QSloc/bCJsmNMmEQ/5XL7Sk3cKDKz@hIedpggIdJ@RE/xd4GDZ1nhklqLPZKEPDcmOEnCTidIo6B0RdNs6G2cdJ8LODpV9mlLC9QtbWI9dNVm7dxou33eMn4n9Ybk2nx7Uf4Z0fvG584Vx8hdBQu5heYlmoXZyNfZGwbuKLrl180/Ef)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 178 bytes
```
F⪫_}⪫{_S¿⌕⮌υ\¿⁼ι W⌊υ⊞υω≡ι}«≔⟦⟧θF⌕⮌υ{F∧∨⌊υ⊟υ∧№α↥§§⊞Oθ⊟υ±¹¦⁰⬤§υ±¹⎇μ№α↥λ⁼λ\⊞θ ≔⊟υη¿∧⊖Lθ∨№⪪“7§⪪◧⌊q⦄NYL?⦄”¶§υ±¹⁼\frac§υ±²⊞υ⪫{}⪫⮌θωWθ⊞υ⊟θ⊞υω»⊞υ⁺⎇∨№υω∧№α↥ι⬤§υ±¹⎇λ№α↥κ⁼κ\⊟υωι⊞υ⁺⊟υι✂⌈υ¹±²
```
[Try it online!](https://tio.run/##jVNLi9swED5vfsWg05iq0KS3zSn0AVu63dBtT3U3CEeJxcqyrUeyxfi3u5IcOw6bQgPBYuaTv8eMs5zprGSy63alBvxSCoVk0xIK/bHZ@OOdqpx9tFqoPSb@B2IH@FmoLX7nB64NR5dQIGlKTr1PtWPSoPBFCLVjLiQHvBdKFK7w6ATWzuToKByT5YxLw8Echc1yQJFAM8uYr5CW3PrzzcoYsVf46zeF2qNvotLX9E1gir2Vbz3oCR2FdVkFWgqh96F0yiKj8LOquA5cuLJ3astfxmeQ9@CbzJYa68n9b3zPLMd5OL@LL5RyvOUu@z@4Vkz/wYLCFUoZIKek5BBfjDdmU/fhLUf/vQQKeaiFlIOVjzzTvODK8i1@5Wpv/cXwXm@/p3yspLBInlK1SVWamlrb8NxplpFAqkjwcE3/WR0Z8a@Bi6lmN67NuEHDiOokzDpJlhCnfdqI@nwx2PPSvbfparSzLd8xJ@3tGSidwSHa0WfE/3O84j8nJa9O6nmSxfNkUsNa9NQiyo3uLqQOGBHMrf1H5IciRcbxnr2M@zm/CHTZdalxxaZRkEpeg35atNDEITQHVEnbqLaFNxArcw8S/t/M6YK@T9tZ9/Yg/wI "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⪫_}⪫{_S
```
Wrap the input in `_{` and `_}` as the code will automatically join the tokens back together this way, and then loop over the characters.
```
¿⌕⮌υ\
```
If the last character was not a new escape, then:
```
¿⁼ι
```
If the current character is a space, then...
```
W⌊υ⊞υω
```
... push an empty string to the predefined empty list if there is not one already, preventing subsequent letters from being joined to a preceding command. Otherwise:
```
≡ι}«
```
If current character is a `}`, then:
```
≔⟦⟧θ
```
Start collecting tokens in reverse between the `}` and the previous `{`.
```
F⌕⮌υ{
```
Loop over the number of tokens.
```
F∧∨⌊υ⊟υ∧№α↥§§⊞Oθ⊟υ±¹¦⁰⬤§υ±¹⎇μ№α↥λ⁼λ\
```
Unless the current token is empty, if the current token starts with a letter and the next (previous) token is a command, then...
```
⊞θ
```
Insert a space after pushing the current token.
```
≔⊟υη
```
Remove the `{`.
```
¿∧⊖Lθ∨№⪪“7§⪪◧⌊q⦄NYL?⦄”¶§υ±¹⁼\frac§υ±²
```
If there was more than one token and the previous token(s) were `^`, `_`, `\sqrt` or `\frac`, then...
```
⊞υ⪫{}⪫⮌θω
```
... join the reversed tokens and wrap them in `{}`s, else...
```
Wθ⊞υ⊟θ
```
... push the tokens back. Note that this might also insert extra spaces but there's no point removing them as they would just get reinserted later.
```
⊞υω
```
Push an empty string in case the last original token was a command, so that a following letter does not get concatenated to it.
```
»⊞υ⁺⎇∨№υω∧№α↥ι⬤§υ±¹⎇λ№α↥κ⁼κ\⊟υωι
```
But if the current character was not a `}` then if the previous token was a space or current character is a letter and the previous token is a command then append the current character to it otherwise push it to the predefined empty list as a new token.
```
⊞υ⁺⊟υι
```
But if the last character was an escape, then append the current character to it.
```
✂⌈υ¹±²
```
Output the final result.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 416 410 394 bytes
```
a:~"a{"'
t:{,/(((,:';,:)"\\"=*:')t)@'t:(0,&~(-1_0,"\\"=x)|a@x)_x}
kw:"|"\"\\frac |\\sqrt |_|^"
ar:1+~!4
k:{$[1<#x;(,/x)/"{}";*x]}
r:*(,,)/(,()),
f:{*{$[^*y;x;"}"~*y;(,()),x
"{"~*y;r(x 0;x 1;2_x)
~^i:kw?y;r(y;ar[i]#*x;ar[i]_*x;1_x)
r(y;*x;1_x)]}/[,();|u,'("\\"=*'u:t x)#\:" "]}
g:{r@(!#r)^w@&~a@r@1+w:&^r:{$[`C~@x;x
|/kw~\:*x;x[0],,/{$[y;x;k@x]}[;2 1~#'(x;x 1)]'o'1_x
1=#x;o@*x
,/o'x]}f@x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxdU8FuozAQvfsrXGdVbHBF7OzJbLdIe+Laaxyo026jKt1EpWnjyphv3zEQQnoAzbz3ZvxmwEa1xDgSoYNyPKWUchVlXDGiNbmNVcQOLI8Ois75dUtvRDXnHWNZY3LLKuvR9qhIQzTAz7V5xI3W72/1ATdVUxJkaiWS9uon2ir3Yyl+zWxGeWpZSpwnWWxXHtUqppyzlHLKGEfPysUgLeOvzGbEkxaCnrIIE9flNbV4nlksMllZhnBbvqjt8S4QX5mply+rWWz7oIJAdKLADcnKp0tomTUfPKL9pNGHOmDLZloRTMDVRrk6p1ezmpXH/Lo1eZ2L5KiuyzoM8vCnzW0Ghpp0e2y1gr52OV9xngIZjG9zGG2ZSSzaWURt8MpW0T6C0xEWt7CGfR5DyNN9BMrnHBaJUqTfP/5Vbof16983XJfSY9dt1X3SHfNu5z1OcIcIEL3A4wSXfKE9vvmNh+qxeFK6S4YqKBprkDZujR/9U1ds8PrxCXUfb4L2KWQDI7GcMlKOjJng2Iz6CSoB7CwJD3gHd6bkCZbeLc54yBcDJcPwIyN3A2wuYGxGPBEXTAecyOFQvzjTI3SSdHYvFAPSCzCMgJ2cmBUhQ2GJp2Wi0sG7U0C09ii8Kqdf95sONOsqxMidFuVLeV5VKadu3bi3XmwriL1PpoAMqU/kBFqE1CffBx3GHXXispP83mfRdxm+qHZ+tKkd0ggVSlQFXBJa3PGIpHCfWARXp1Bz9WDqzSf8+4gW2T1TCQmlREcFQm1aK3qfbaKCoaRGEqH/Lxputw==)
shift/reduce parser (no regexes). Probably plenty of golfing left.
`t` tokenizes, `f` parses into an AST and `g` renders. I couldn't roll rendering into parsing because I couldn't distinguish deep structures which render as a single string from single tokens and failed on the ones mentioned in the problem comments.
] |
[Question]
[
## Challenge
In this challenge, you have to fill an \$M\$ x \$N\$ rectangle grid with the most \$A\$ x \$B\$ rectangle pieces possible.
Requirements:
* The sizes of the \$M\$ x \$N\$ rectangle grid is always bigger than the sizes of the \$A\$ x \$B\$ rectangle pieces. In other words, \$min(M, N) ≥ max(A, B)\$
* You can freely rotate the \$A\$ x \$B\$ rectangle pieces.
* Those \$A\$ x \$B\$ rectangle pieces can touch each other on the edge, but it cannot overlap each other.
* Those \$A\$ x \$B\$ rectangle pieces, or part of it, cannot be outside of the \$M\$ x \$N\$ rectangle grid.
* You don't have to fill the whole \$M\$ x \$N\$ rectangle grid, because sometimes that is impossible.
## Example
Given a \$5\$ x \$5\$ rectangle grid (or square) like below:
[](https://i.stack.imgur.com/3kXMl.png)
And you have to fill it with \$2\$ x \$2\$ rectangle (or square) pieces. The best you can do is \$4\$, like below:
[](https://i.stack.imgur.com/hlRqk.png)
## Input/Output
Input can be taken in any resonable format, containing the size of the \$M\$ x \$N\$ rectangle grid and the \$A\$ x \$B\$ rectangle pieces.
Output can also be taken in any resonable format, containing the most number of pieces possible.
Example Input/Output:
```
Input -> Output
[5, 5] [2, 2] -> 4
[5, 6] [2, 3] -> 5
[3, 5] [1, 2] -> 7
[4, 6] [1, 2] -> 12
[10, 10] [1, 4] -> 24
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) wins!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 175 bytes
Expects `(m,n,[a,b])` with all values passed as BigInts.
```
(m,n,a,M,g=(p,y,i)=>q=i--&&p>>y*~m|g(p,~-y,i))=>(h=(k,N,x,y)=>{for(y=n;--y;)for(x=m;x--;)a.map((v,i)=>k&g(2n**v-1n<<x,y,a[i^1])?M>N?0:M=N:h(k|q,N+1))})(g(1n<<m,n,++n)|~-q,0)|M
```
[Try it online!](https://tio.run/##bY7RaoNAEEXf@xU@yYzOJtnYpBCz5gv0BySFJY3GGldNirjU@ut2tyC0oQ8zcDlnLvMuO3k/3Yrmg6n67TxlYoKKFEmKKRfQkKYCRdSKgjHXbaJIe2M15AaMzCLD4CKgpIR60iZ9ZvUNtFAhYzpEG3pRhT1jIcpFJRuA7qexdHNYK8/rGFf7vbklmRav/IiHOEoOq10skt0FyqGlxOeIXwg5WNM@5/sKh5G1tMIhnk61utfX8@Ja55CZTnICMyk3i6sjorNcOtunv9bGQDup1dez9fyPtZ2tYLY2D1Ywd/HfXS/TNw "JavaScript (Node.js) – Try It Online")
### How?
This is a (slow) brute-force search over a single BigInt bitmask representing the entire board with left and bottom borders.
For instance, a \$2\times3\$ board is initialized to \$2343\$, which is \$100100100111\$ in binary. Once re-arranged in 2D, this gives:
$$\begin{matrix}1&0&0\\1&0&0\\1&0&0\\1&1&1\end{matrix}$$
We use the helper function \$g\$ to create the bitmask \$q\$ of a rectangle:
```
g = ( // g is a recursive function taking:
p, // p = row pattern
y, // y = starting row
i // i = remaining number of rows
) => //
q = // save the final result in q
i-- && // decrement i; stop if it was 0
p // insert the pattern
>> y * ~m | // shifted to the left by y * (m+1) positions
// (we actually do a shift to the right by
// y * (-m-1), which doesn't work as expected
// with Numbers but works fine with BigInts)
g(p, ~-y, i) // do a recursive call with y - 1
```
We use `g(1n << m, n, ++n) | ~-q` to initialize the board: the call to \$g\$ creates the left border and the bitwise OR with \$q-1\$ appends the bottom border.
We use \$g\$ again to create the smaller rectangles of size \$A\times B\$ and \$B\times A\$. We test collisions with bitwise ANDs and add them to the board with bitwise ORs.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~95~~ 92 bytes
```
NθNη≔E²Nζ⊞υ×⊖X²θ÷⊖X²×η⊕θ⊖X²⊕θF×η⊕θF×X²ιEX²⟦ζ⮌ζ⟧×⊖⊟κ÷⊖X⊟κ⊕θ⊖X²⊕θFυF⁼κ&λκ⊞υ⁻λκUMυΣ⍘ι²I÷⁻⌈υ⌊υΠζ
```
[Try it online!](https://tio.run/##jZE7T8MwFIX3/gqP15IZqAQIdeqDoUNQRNkQg0lMYyV2Ej9SlD8frpu0jdRUMNnX9zvH99hJxk1S8qLrtrry7tWrL2GgpovZuM6wXlor9xoiXsGckXGXUkZaJGJvM/CMvEslLGxEYoQS2okU4vKAHMrqwG6128hGpmKa6eVZ4C5dFAbppOCKozjMd2kI3LQio/bZR@IFId754KNl5E00wlgBLf2k09EqyP9K1UPXY/w/0GlkP6wvteeFhZyRlXQHacVSp1Awkgfy9BGR1N4Op4sZRluXSnEEsbfzClbcip0zUu9BMjI/vluMpYM1tw4uiXqjiP9IhTJPj9bDHovYlKlPHL5RsOi6@0fyTJ7IQ3fXFL8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Brute-force breadth-first search, so very slow.
```
NθNη
```
Input the dimensions of the grid to be filled.
```
≔E²Nζ
```
Input the dimensions of the rectangle.
```
⊞υ×⊖X²θ÷⊖X²×η⊕θ⊖X²⊕θ
```
Start a breadth-first search with a bitmask representing an empty grid.
```
F×η⊕θ
```
Loop over all the possible top left corners of the rectangle, and some impossible ones too.
```
F×X²ιEX²⟦ζ⮌ζ⟧×⊖⊟κ÷⊖X⊟κ⊕θ⊖X²⊕θ
```
Calculate and loop over the bitmasks for both orientations of the rectangle at this position.
```
Fυ
```
Loop over the grid layouts found so far.
```
F⁼κ&λκ
```
If the rectangle can be placed at this position...
```
⊞υ⁻λκ
```
... then add a new layout with the updated grid.
```
UMυΣ⍘ι²
```
Calculate the number of squares left on each grid.
```
I÷⁻⌈υ⌊υΠζ
```
Divide the difference between the maximum (i.e. the original area of the grid) and minimum by the area of the rectangle.
[Answer]
# Python3, 460 bytes:
```
R=range
S=lambda x,y:[(X,Y)for X in R(x)for Y in R(y)]
def L(m,X,Y,w,h):
m=eval(str(m))
for x,y in S(X,Y):
if 0==m[y][x]and Y-y>=h and X-x>=w:
for j,k in S(h,w):
if m[y+j][x+k]:return
m[y+j][x+k]=1
return m
def f(a,b):
m=[[0 for _ in R(a[0])]for _ in R(a[1])]
q,s,l=[(m,0)],[],[]
while q:
m,c=q.pop(0);l+=[c]
if(t:=L(m,*a,*b))and t not in s:q+=[(t,c+1)];s+=[t]
if(t:=L(m,*a,*b[::-1]))and t not in s:q+=[(t,c+1)];s+=[t]
return max(l)
```
[Try it online!](https://tio.run/##jZDNboMwEITvPMUe7bCpID9VReQ8QU/JJZFlVU4ChYR/3AJPT21DpaTtoRIHdme/0YzLXsVFvnwp62HYsVrm76GzZ6nMThcJHfYBJwc80qio4QBJDjvS2eE4Dj0VziWM4JVkqO@wxZgGDmQs/JQpaVRNMkodMIQ2M8ze@ukbSCLwGMt4L3gnZH6B47zfshjM72HebVlrrix7xdvIxtha1tIada8adm8iqEP1UedWuVsz32xGDTKbNCIST2NGzj3r/jZ2kdwTVDwsfL1woMIGU8Z1RY8K5OZzoI2TNITKhMnwzKqnsiiJRzepy/hZ2HpEBcw8zEzi7ESp6aUgL5Rxb4JKHxKFZ9enYtPoQf1B8SCY6xD/Yr9ryo6kdCjrJFckInyNsBYIfIGw0E7OvfA8CcsHYTkR/k9iNRG/BN9D8L1JWmlp@AI)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Rṡ"p/⁺€ɗⱮṚƬ}ẎŒPẎQƑ$ƇṪL
```
A dyadic Link that accepts the large rectangle dimensions, `[M, N]`, on the left and the small rectangle dimensions, `[A, B]`, on the right and yields the maximal count.
**[Try it online!](https://tio.run/##AUIAvf9qZWxsef//UuG5oSJwL@KBuuKCrMmX4rGu4bmaxqx94bqOxZJQ4bqOUcaRJMaH4bmqTP///1s1LCA1Xf9bMiwgMl0 "Jelly – Try It Online")** Too slow to complete on TIO for any other test case.
### How?
Dumb brute-force...
Creates all possible sub-rectangles where each one is a list of the cell coordinates it covers in the \$M\$ by \$N\$ rectangle. Then filters the collection of every possible set of distinct sub-rectangles keeping only those with no overlap (repeated coordinate) and outputs the length of (one of) the longest one(s).
```
Rṡ"p/⁺€ɗⱮṚƬ}ẎŒPẎQƑ$ƇṪL - Link: [M, N]; [A, B]
R - range -> [[1..M], [1..N]]
} - use right argument, [A, B], with:
Ƭ - collect up until no change applying:
Ṛ - reverse
-> [[A, B], [B, A]] ...or [[A, B]] if A==B
Ɱ - map - i.e. for [i,j] in those apply:
ɗ - last three links as a dyad - f([[1..M], [1..N]], [i,j]):
" - zip with - i.e. [f(l=[1..M], r=i), f(l=[1..N], r=j)]:
ṡ - all sublists of l of length r
/ - reduce by:
p - Cartesian product
€ - for each:
⁺ - repeat (reduce by Cartesian product)
Ẏ - tighten -> all possible A by B or B by A sub-rectangles
as 1-indexed coordinates
ŒP - powerset (Note: elements cardinality is non-decreasing)
Ƈ - filter keep those for which:
$ - last two links as a monad:
Ẏ - tighten
Ƒ - is invariant under?:
Q - deduplicate (i.e. we keep those with no overlap)
Ṫ - tail (the/one way to maximise small rectangles)
L - length
```
] |
[Question]
[
Giving a challenge involving a Star Trek reference just after May the 4th may be frowned upon, but here goes.
You, Luke, Anakin, Palpatine, Yoda and Han Solo are involved in an insane tournament of Rock, Paper, Scissor, Lizard, Spock.
The catch here is that you are only allowed to use a fixed order of moves. If your order is "R", Then you have to use Rock, until you lose or win against everyone. If your order is RRV, then you have to use 2 Rocks followed by a Spock and keep repeating until you have won or lost.
Luke, Anakin, Palpatine, Yoda and Han Solo have submitted their respective orderings and you being an expert hacker got your hands on each of their orderings!
With this knowledge, you are to design your ordering for the tournament. Since everyone wants to win, you want to create an ordering such that you win the tournament by beating everyone.
But this may not be possible under all circumstances.
Incase there is a possible winning order, print that out. If there is no possible way for you to win, print out -1 (or 0 or False or "impossible")
**Input**: a list of 5 orders
**Output**: a single order or -1
**Sample Input 1**
```
R
P
S
L
V
```
**Sample Output 1**
```
-1
```
**Explanation 1**
>
> No matter what you play in your first move, there will be at least one
> person who beats you, hence it is not possible for you to win.
>
>
>
**Sample Input 2**
```
RPS
RPP
R
SRR
L
```
**Sample Output 2**
```
RPSP
```
**Explanation 2**
>
> Once you play Rock in your first move, you end up beating "L" and "SRR" and
> tie against the rest. This is because Lizard and Scissors lose to Rock.
> When you play Paper next, you will beat "R" and tie against the remaining
> 2. This is because Rock loses to Paper.
> When you play Scissors next, you will win against "RPP" as Scissor beats
> Paper.
>
>
> Finally, you will beat "RPS" with your Paper as Paper beats Rock.
>
>
>
Here are a list of notations (you may use any 5 literals, but please specify in your answer):
```
R : Rock
P : Paper
S : Scissor
L : Lizard
V : Spock
```
Here is a list of all possible outcomes:
```
winner('S', 'P') -> 'S'
winner('S', 'R') -> 'R'
winner('S', 'V') -> 'V'
winner('S', 'L') -> 'S'
winner('S', 'S') -> Tie
winner('P', 'R') -> 'P'
winner('P', 'V') -> 'P'
winner('P', 'L') -> 'L'
winner('P', 'S') -> 'S'
winner('P', 'P') -> Tie
winner('R', 'V') -> 'V'
winner('R', 'L') -> 'R'
winner('R', 'S') -> 'R'
winner('R', 'P') -> 'P'
winner('R', 'R') -> Tie
winner('L', 'R') -> 'R'
winner('L', 'V') -> 'L'
winner('L', 'S') -> 'S'
winner('L', 'P') -> 'L'
winner('L', 'L') -> Tie
winner('V', 'R') -> 'V'
winner('V', 'L') -> 'L'
winner('V', 'S') -> 'V'
winner('V', 'P') -> 'P'
winner('V', 'V') -> Tie
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes win.
P.S: Let me know if you need more test cases.
[Answer]
# JavaScript (ES6), ~~122 115~~ 112 bytes
Takes input as an array of strings of digits, with:
* \$0\$ = Scissors (S)
* \$1\$ = Paper (P)
* \$2\$ = Rock (R)
* \$3\$ = Lizard (L)
* \$4\$ = Spock (V)
Returns either a string in the same format or \$false\$ if there's no solution.
```
f=(a,m='',x=0,o,b=a.filter(a=>(y=a[m.length%a.length])-x?o|=y-x&1^x<y:1))=>b+b?x<4&&f(a,m,x+1)||!o&&f(b,m+x):m+x
```
[Try it online!](https://tio.run/##dY1Ra4MwFIXf@yuyh5kEr@mEPXWN/QOFiUJfxEFMo3OoEZWSgv/dJd3G7EPzEL57zrnnfomLGOVQ91PQ6bNalpITAS3HGAx/AQ0FF6ysm0kNRPCIXLnIWtaorpo@n8Uv5DQwBz3za2C88MPsr7uQUh4VfnEw@1fPK10lGD@k8/yk3VxA6xu6s9/S6otCHOE0To4n/LaZ1DjZWSAeIam7UTeKNboiZLCqbWKt6Mno3JENqm@EVGTLthUg6URXx@rurMx7SSR1D3keGh5lM5lTurldJRlOcU7/OF5xsuLjik93GbA7YDvAZuDei52axM53uTRJbqn1tf/tH87p8g0 "JavaScript (Node.js) – Try It Online")
### How?
This is a breadth-first search: we first try all moves at a given step to see if we can win the game. If we can't win right now, we try to add another move to each non-losing move.
The move identifiers were chosen in such a way that a move \$A\$ wins against a move \$B\$ if and only if \$(B-A)\bmod 5\$ is odd.
With \$A\$ on the left and \$B\$ on the top:
$$
\begin{array}{cc|ccccc}
& & \text{(S)} & \text{(P)} & \text{(R)} & \text{(L)} & \text{(V)}\\
& & 0 & 1 & 2 & 3 & 4\\
\hline
\text{(S) }&0 & - & \color{green}1 & \color{red}2 & \color{green}3 & \color{red}4\\
\text{(P) }&1 & \color{red}4 & - & \color{green}1 & \color{red}2 & \color{green}3\\
\text{(R) }&2 & \color{green}3 & \color{red}4 & - & \color{green}1 & \color{red}2\\
\text{(L) }&3 & \color{red}2 & \color{green}3 & \color{red}4 & - & \color{green}1\\
\text{(V) }&4 & \color{green}1 & \color{red}2 & \color{green}3 & \color{red}4 & -
\end{array}
$$
From there, we can deduce another way of testing if \$A\$ wins against \$B\$ for \$A\neq B\$:
```
((A - B) and 1) xor (B < A)
```
where `and` and `xor` are bitwise operators.
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = input
m = '', // m = string representing the list of moves
x = 0, // x = next move to try (0 to 4)
o, // o = flag set if we lose, initially undefined
b = // b[] = array of remaining opponents after the move x
a.filter(s => // for each entry s in a[]:
( y = // define y as ...
s[m.length % s.length] // ... the next move of the current opponent
) - x // subtract x from y
? // if the difference is not equal to 0:
o |= // update o using the formula described above:
y - x & 1 ^ x < y // set it to 1 if we lose; opponents are removed
// while o = 0, and kept as soon as o = 1
: // else (this is a draw):
1 // keep this opponent, but leave o unchanged
) // end of filter()
) => //
b + b ? // if b[] is not empty:
x < 4 && // if x is less than 4:
f(a, m, x + 1) // do a recursive call with x + 1 (going breadth-first)
|| // if this fails:
!o && // if o is not set:
f(b, m + x) // keep this move and do a recursive call with b[]
: // else (success):
m + x // return m + x
```
[Answer]
# [R](https://www.r-project.org/), ~~213~~ 190 bytes
-23 bytes thanks to Giuseppe.
```
function(L){m=matrix(rep(0:2,1:3),5,5)
m[1,4]=m[2,5]=1
v=combn(rep(1:5,n),n<-sum(lengths(L)))
v[,which(apply(v,2,function(z)all(sapply(L,function(x,y,r=m[cbind(x,y)])r[r>0][1]<2,z)))>0)[1]]}
```
[Try it online!](https://tio.run/##RU/LbsIwELz7S3alrRQ78SXCfAF/YPkQXNJYsk3khDRQ8e1hWxC9zeyO5lG2eMpf8zCZ/pL9HM4ZVmxEb7Y3P@BPMqmbS1ihnEaoWkWyrZE0aRTJSmqcSVaRdkaKxfhzOuY/pWw1ZaS8@5guCV5B7IcoFkvfQ/ADdOMYr7CQonfgDbsYYXp@Dv/3la5UOMkfQ/78Zeiw2LKvnJVup@jGxvsKmbj71kMM0wweuB4ppCdokCRDHkASqeYi4iWU3KBmhUbcHg "R – Try It Online")
If a solution exists, it outputs one. If there is no solution, it outputs a row of `NA`. If this output format is not acceptable, I can change it at a cost of a few bytes.
Moves are coded as 1=R, 2=S, 3=P, 4=L, 5=V, so that the matrix of outcomes is
```
[,1] [,2] [,3] [,4] [,5]
[1,] 0 2 2 1 1
[2,] 1 0 2 2 1
[3,] 1 1 0 2 2
[4,] 2 1 1 0 2
[5,] 2 2 1 1 0
```
(0=no winner; 1=player 1 wins; 2=player 2 wins)
An upper bound on the length of the solution if it exists is `n=sum(lengths(L))` where `L` is the list of opponents' moves. The code creates all possible strategies of length `n` (stored in matrix `v`), tries all of them, and displays all winning strategies.
Note that this value of `n` makes the code very slow on TIO, so I have hardcoded in the TIO `n=4` which is enough for the test cases.
For the first test case, the output is
```
1 4 2 4
```
corresponding to the solution RLSL.
For the second test case, the output is
```
NA NA NA NA
```
meaning that there is no solution.
Explanation of a previous version (will update when I can):
```
function(L){
m = matrix(rep(0:2,1:3),5,5);
m[1,4]=m[2,5]=1 # create matrix of outcomes
v=as.matrix(expand.grid(replicate( # all possible strategies of length n
n<-sum(lengths(L)) # where n is the upper bound on solution length
,1:5,F)))
v[which(
apply(v,1, # for each strategy
function(z) # check whether it wins
all( # against all opponents
sapply(L,function(x,y){ # function to simulate one game
r=m[cbind(x,y)]; # vector of pair-wise outcomes
r[r>0][1]<2 # keep the first non-draw outcome, and verify that it is a win
}
,z)))
>0),] # keep only winning strategies
}
```
The `which` is necessary to get rid of NAs which occur when the two players draw forever.
I am not convinced this is the most efficient strategy. Even if it is, I am sure that the code for `m` could be golfed quite a bit.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
_%5ḟ0ḢḂ¬
ṁ€ZLḤƊçþ`Ạ€Tị;‘%5Ɗ$€
```
A monadic Link that accepts a list of lists of integers (each of which is an opponent's strategy) which yields a list of lists of integers - each of which is a winning strategy (so an empty list if none are possible).
(Just add `Ḣ` to only yield a single strategy list or `0` if impossible.)
**[Try it online!](https://tio.run/##y0rNyan8/z9e1fThjvkGD3cserij6dAaroc7Gx81rYnyebhjybGuw8sP70t4uGsBUCTk4e5u60cNM1RNj3WpAPn/D7cfnfRw54z//6OjDXQMdYxidcC0IYgGYiMdAx0QbRIbCwA "Jelly – Try It Online")** (the footer formats to always show the lists)
```
Rock Paper Scissors Spock Lizard
0 1 2 3 4
```
Or [try a letter mapped version](https://tio.run/##y0rNyan8/z9e1fThjvkGD3cserij6dAaroc7Gx81rYnyebhjybGuw8sP70t4uGsBUCTk4e5u60cNM1RNj3WpAPn/HzXMCQgO8wl61DD38IbMRxvXAdHD3VtqD7cDVT5q3BH5/39QQDBXUEAAVxBXcFAQlw8A "Jelly – Try It Online") (where strategies are taken and shown on their own lines using `RPSVL` notation).
### How?
The numbers are chosen such that any which are an odd number greater than another modulo five win (i.e. they are numbered going around the edge of an inscribed pentagon of the throws).
The code plays each strategy off against every strategy (including themselves) for twice as many throws as the longest strategy so as to ensure finding any losers keeping those which are not defeated. The resulting list of strategies will contain a single strategy if there is an outright winner; no strategies if there was no winner; or multiple strategies if there are drawing players. After this a winning set of moves is appended to each of these strategies.
```
_%5ḟ0ḢḂ¬ - Link 1, does B survive?: list A, list B (A & B of equal lengths)
e.g. RPSR vs RPVL -> [0,1,2,0], [0,1,3,4]
_ - subtract (vectorises) [0,0,-1,-4]
%5 - modulo five (vectorises) [0,0,4,1] ...if all zeros:
ḟ0 - filter discard zeros (ties) [4,1] []
Ḣ - head (zero if an empty list) 4 0
Ḃ - modulo two 0 0
¬ - logical NOT 1 1
ṁ€ZLḤƊçþ`Ạ€Tị;‘%5Ɗ$€ - Main Link: list of lists of integers
ṁ€ - mould each list like:
Ɗ - last three links as a monad
Z - transpose
L - length
Ḥ - double (i.e. 2 * throws in longest strategy)
` - use left as both arguments of:
þ - table using:
ç - last Link (1) as a dyad
Ạ€ - all for each (1 if survives against all others, else 0)
T - truthy indices
ị - index into the input strategies
$€ - last two links as a monad for each:
; - concatenate with:
Ɗ - last three links as a monad:
‘ - increment (vectorises)
%5 - modulo five (vectorises)
```
[Answer]
# Emacs Lisp, 730 bytes
```
(require 'cl-extra)
(require 'seq)
(defun N (g) (length (nth 1 g)))
(defun M (g) (mapcar (lambda (o) (nth (% (N g) (length o)) o)) (car g)))
(defun B (x y) (or (eq (% (1+ x) 5) y) (eq (% (+ y 2) 5) x)))
(defun S (g) (seq-filter (lambda (m) (not (seq-some (lambda (v) (B v m)) (M g)))) '(0 1 2 3 4)))
(defun F (g) (cond ((null (car g)) (reverse (nth 1 g))) ((null (S g)) nil) ((>= (nth 3 g) (seq-reduce (lambda (x y) (calc-eval "lcm($,$$)" 'raw x y)) (mapcar 'length (car g)) 1)) nil) (t (cl-some (lambda (m) (F (let ((r (seq-filter 'identity (mapcar* (lambda (v o) (and (not (B m v)) o)) (M g) (car g))))) (list r (cons m (nth 1 g)) (1+ (N g)) (if (eq (car g) r) (1+ (nth 3 g)) 0))))) (S g)))))
(defun Z (s) (F (list s () 0 0)))
```
I didn't find an online interpreter of Emacs Lisp :( If you have Emacs installed, you can copy code into a `.el` file, copy some testing lines below
```
;; 0 = rock, 1 = lizard; 2 = spock;
;; 3 = scissors; 4 = paper
(print (Z '((0) (1) (2) (3) (4))))
; output: nil
(print (Z '((0) (4) (3) (1))))
; output: nil
(print (Z '((0 4 3) (0 4 4) (0) (3 0 0) (1))))
; output: (0 4 3 0 1)
(print (Z '((4) (4) (3) (4) (4))))
; output: (3 0)
(print (Z '((4 3 2 1 0) (2 1 0 4 3))))
; output: (1)
(print (Z '((2) (2) (3) (0) (2) (3) (0) (0))))
; output: (2 1)
(print (Z '((2) (2 0) (3) (0) (2 1) (3) (0) (0))))
; output: nil
```
and run it `$ emacs --script filename.el`.
## How it works
My program does depth first search with sometimes figuring out that it's impossible to win and terminating the branch it's on.
You can see full explanation in the unshortened version of the code:
```
(require 'seq)
(require 'cl-extra)
;; This program does depth first search with sometimes figuring out
;; that it's impossible to win and terminating the branch it's on.
;;
;; A move is a number from 0 to 4.
;; https://d3qdvvkm3r2z1i.cloudfront.net/media/catalog/product/cache/1/image/1800x/6b9ffbf72458f4fd2d3cb995d92e8889/r/o/rockpaperscissorslizardspock_newthumb.png
;; this is a nice visualization of what beats what.
;; Rock = 0, lizard = 1, spock = 2, scissors = 3, paper = 4.
(defun beats (x y) "Calculates whether move x beats move y"
(or (eq (% (1+ x) 5) y)
(eq (% (+ y 2) 5) x)))
;; A gamestate is a list with the following elements:
(defun get-orders (gamestate)
"A list of orders of players who haven't lost yet. Each order is a list of moves.
For example, ((2) (2 0) (3) (0) (2 1) (3) (0) (0)) is a valid orders list.
This function gets orders from the gamestate."
(car gamestate))
;; At index 1 of the gamestate lies a list of all moves we have made so far in reverse order
;; (because lists are singly linked, we can't push back quickly)
(defun get-num-moves-done (gamestate)
"Returns the number of moves the player has done so far"
(length (nth 1 gamestate)))
(defun get-rounds-since-last-elim (gamestate)
"The last element of a gamestate is the number of rounds passed since an opponent
was eliminated. We use this to determine if it's possible to win from current
gamestate (more about it later)."
(nth 2 gamestate))
;; next go some utility functions
;; you can skip their descriptions, they are not very interesting
;; I suggest you skip until the next ;; comment
(defun get-next-move (order num-rounds-done)
"Arguments: an order (e.g. (1 0 1)); how many rounds have passed total.
Returns the move this opponent will make next"
(nth (% num-rounds-done (length order)) order))
(defun moves-of-opponents-this-round (gamestate)
"Returns a list of moves the opponents will make next"
(mapcar (lambda (order) (get-next-move order (get-num-moves-done gamestate)))
(get-orders gamestate)))
(defun is-non-losing (move opponents-moves)
"Calculates if we lose right away by playing move against opponents-moves"
(not (seq-some (lambda (opponent-move) (beats opponent-move move))
opponents-moves)))
(defun non-losing-moves (gamestate)
"Returns a list of moves which we can play without losing right away."
(seq-filter
(lambda (move) (is-non-losing move (moves-of-opponents-this-round gamestate)))
'(0 1 2 3 4)))
(defun advance-gamestate (gamestate move)
"If this move in this gamestate is non-losing, returns the next game state"
(let ((new-orders (seq-filter
'identity (mapcar* (lambda (opp-move order)
(and (not (beats move opp-move)) order))
(moves-of-opponents-this-round gamestate)
(get-orders gamestate)))))
(list new-orders
(cons move (nth 1 gamestate))
(if (eq (get-orders gamestate) new-orders) (1+ (get-rounds-since-last-elim gamestate)) 0))))
;; How do we prevent our depth first search from continuing without halting?
;; Suppose 3 players (except us) are still in the game and they have orders of lengths a, b, c
;; In this situation, if least_common_multiple(a, b, c) rounds pass without an elimination
;; we will be in the same situation (because they will be playing the same moves they played
;; lcm(a, b, c) rounds ago)
;; Therefore, if it's possible to win from this gamestate,
;; then it's possible to win from that earlier game state,
;; hence we can stop exploring this branch
(defun get-cycle-len (gamestate)
"Returns a number of rounds which is enough for the situation to become the same
if the game goes this long without an elimination."
(seq-reduce (lambda (x y) (calc-eval "lcm($,$$)" 'raw x y))
(mapcar 'length (get-orders gamestate)) 1))
(defun unwinnable-cycle (gamestate)
"Using the aforementioned information, returns t if we are in such a
suboptimal course of play."
(>= (get-rounds-since-last-elim gamestate) (get-cycle-len gamestate)))
(defun find-good-moves (gamestate)
"Given gamestate, if it's possible to win
returns a list of moves, containing all moves already done + additional moves which lead to win.
Otherwise returns nil"
(cond ((null (get-orders gamestate)) ; if no opponents left, we won, return the list of moves
(reverse (nth 1 gamestate)))
((null (non-losing-moves gamestate)) ; if no non-losing moves available, this gamestate
nil) ; doesn't lead to a win, return nil
((unwinnable-cycle gamestate) ; either it's impossible to win, or
nil) ; it's possible to win from an earlier position, return nil
(t (cl-some (lambda (move) ; otherwise return the first non-losing move which leads
(find-good-moves (advance-gamestate gamestate move))) ; to a non-nil result
(non-losing-moves gamestate)))))
(defun make-initial-gamestate (orders)
"Given an orders list, create initial gamestate"
(list orders () 0))
```
] |
[Question]
[
You are a Computer Science professor teaching the C programming language. One principle you seek to impart to the students is *modularity*. Unfortunately, past classes have tended not to get the message, submitting assignments with the entire program inside `main()`. Therefore, for this semester you have issued strict modularity guidelines upon which students will be graded.
A subset of C grammar and rules for "well-formed" translation unit are defined below. Code that follows these rules should be valid C89, UNLESS an identifier that is a keyword is used.
### Task
You will receive as input a string purportedly containing C code. You may assume that this string contains only spaces, newlines, and the characters `abcdefghijklmnopqrstuvwxyz123456789(){},+-*/%;=`.
Your code must output the number of points the student's assignment should receive according to the following rubric:
* Input is not a valid `translation-unit` according to the grammar: 0 points
* Input follows the grammar but is not "well-formed" according to the rules below: 1 point
* Input is a well-formed translation unit but not fully modular: 2 points
* Input is a fully modular well-formed translation unit: 3 points
### Token definitions
* `identifier`: Any sequence of 1 or more lowercase English letters. If an identifier is a C89 reserved word1, you may optionally return 0 instead of whatever the result would have been ignoring reserved words. You do not have to be consistent about detecting the use of reserved words as identifiers; you may flag them in some instances and let them pass in others.
* `integer-literal`: A sequence of 1 or more of the digits 1-9 (recall that the character `0` is guaranteed not to appear in the input)
* Other valid tokens are defined literally in the grammar.
* A character must belong to a token if and only if it is not whitespace.
* Two consecutive alphanumeric characters must be part of the same token.
### EBNF grammar
```
var-expr = identifier
literal-expr = integer-literal
binary-op = "+" | "-" | "*" | "/" | "%"
binary-expr = expr binary-op expr
paren-expr = "(" expr ")"
call-expr = identifier "(" [ expr ( "," expr )* ] ")"
expr = var-expr | literal-expr | binary-expr | paren-expr | call-expr
assign-stmt = var-expr "=" expr ";"
if-stmt = "if" "(" expr ")" assign-stmt
return-stmt = "return" expr ";"
function-body = ( assign-stmt | if-stmt )* return-stmt
argument-list = [ identifier ( "," identifier )* ]
function-definition = identifier "(" argument-list ")" "{" function-body "}"
translation-unit = function-definition*
```
### Well-formed program requirements
* No two function definitions may have the same function name.
* No two identifiers in an `argument-list` may be identical.
* No identifier in an `argument-list` may be identical to a function name (whether from a `function-definition` or a `call-expr`).
* The identifier in a `var-expr` must be included in the enclosing function's `argument-list`.
* For a given function, all `call-expr`s and the `function-definition` (if any) must agree in number of arguments.
### Fully modular
* No more than 1 binary operator per function
* No more than 1 assignment statement per function
* No more than 1 function call per function
### Examples (one per line)
**Score 0**
```
}}}}}
return 2;
f() { return -1; }
f() {}
f(x,) { return 1; }
f(x) { return 1 }
f(x) { returnx; }
f(x) { return1; }
f() { g(); return 1;}
f() { if(1) return 5; }
f(x) { if(1) if(1) x = 2; return x; }
f(x, y) { x = y = 2; return x; }
```
**Score 1**
```
f(){ return 1; } f(){ return 1; }
g(x, x) { return 1; }
g(f) { return 1; } f() { return 1; }
f(x) { x = write(); x = write(1); return 1; }
f() { return f(f); }
f() { return 1; } g() { return f(234567); }
f() { return(x); }
f() { j = 7; return 5; }
```
**Score 2**
```
f(x,y,zzzzz) { return x + y + zzzzz; }
f(x,a,b) { if(a) x = foo(); if(b) x = bar(); return x; }
f(j) { return g(h( i() / j, i() ), 1) ; }
```
**Score 3**
```
mod(x, y) { return ((x % y)); }
f() { return f(); }
f(c) { if(c) c = g(c) + 2; return c; }
fib(i){return bb(i,0,1);}aa(i,a,b){return bb(i,b,a+b);}bb(i,a,b){if(i)a=aa(i-1,a,b);return a;}
```
**Score 0 or 1**
```
h(auto, auto) { return 1; }
```
**Score 0 or 3**
```
if() { return 1; }
```
---
1 Reserved word list: `auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while`
[Answer]
# JavaScript (ES6), ~~599~~ ~~598~~ ~~593~~ ~~581~~ ~~580~~ ~~576~~ ~~574~~ ~~593~~ ~~591~~ ~~579~~ ~~565~~ ~~563~~ ~~562~~ ~~524~~ ~~521~~ ~~515~~ ~~513~~ ~~511~~ ~~506~~ ~~503~~ 502 bytes
*After over 3 years I finally noticed "some" further golfs. I also found an edge case while re-golfing… +19 bytes. ~~Sigh.~~ That helped me notice a 38 byte golf. :P*
```
M=p=>(P=I[i++])==p&&7
J=_=>/^[a-z]+$/.test(R=P)*7
O=(Z,a,n=R)=>M`)`?(L[n]|=2)&1|U[n]-(U[n]=a)?1:7:(a++?P==",":i--)&&Z()&O(Z,a,n)
E=_=>(M`(`?E()&M`)`:P-~P?7:J()&(M`(`?O(E,!++z):A[i--,R]|1))&(/[+*/%-]/.test(I[i])?E(++y+i++):7)
S=_=>M`return`?E()&M`;`&M`}`&((x|y|z)>1?3:7):P&&(P=="if"?M`(`&E()&M`)`+M():7)&J()&(A[R]|1)&M`=`&E()&M`;`&S(++x)
Q=_=>M()||J(A={})&(L[F=R]&5?1:7)&M`(`&O(_=>J(M())&(A[R]|(L[R]|=1)&6?1:A[R]=7),x=y=z=0)&M`{`&S()&Q(L[F]=6)
f=c=>Math.log2(Q(U={},L={},i=0,I=c.match(/\w+|\S/g)||[])+1)
```
[Try it online!](https://tio.run/##1VZdd9pGEH3Xr9hwEnk3WkCCOJyDuuY4rdPatQu2636YqNFKlrBcLFFJ2IChf92dEYIIhHvy0ofysNq9c/fO7MxoxZ18kIkbB6O06kjHG1bD6MZ7fj4TI3FAe@K4H2iaxYQYqWpLORGfxUH9j76sziztdb2WeklKL0SPvW0pXUGvueShuGDi4Mxmdoee9kNrLhpMNeZXMK1SHIVkHaPdalOpaZ2eEBVeaQfVKlPVa8rU7lKEKUfoip7Z1O4cAY6C7V71716n1T6B9dLSpUf8labNWPuwDxr8wpobDIz1vva2/qZq5RHCISwGMpo21eA4rN1iyiXqn9mxl47jcOXDtGFY2Cqlk/l0PmMHRqcJ5HZPVSmGGviVDjpWVyFpZxTV1Cykw37mHwxixQDBS3A7Ycp55o@y@fyEHoqnBfBP@x/FhaXuYzqQDLpdCqwTCryVHrBgFCD7HngIiRbjEzEVM6Hjrid0wdRzlLPEe6b4wgVPMr2tDaNBg57TK3DHT3EIhM6PhVu7l6l7S@ufHrX5p8v6AILqW0wz2PON54wHgvpQQlqr1SQ@3ShMoqGHatSvhfLe42jix7VkGLgeDRjjnz/Hwl/u4Dv4lepBBTkZkSn1eldknmiXmUf59IiZ5/n0nCmKq994MyKIrS/wp@jLSpGGqeg@ZeSJ5EDVMMkix7LnhBesK@OkiJWgSZlVUCUDyswvgms48KnBVvh@UWJpWY4TOERjvX3tiZMpMtE6LTFSRTc3Q8620R3Y0w7M2IU1mmXUgINsIGQbUIwBxlreCbXdwshGWdb6W6TyPmRNVrl4jIPUw3R/WRjF5JdEfdB70dUGr9F8t/@@VSaD868TMDJeA4s35TP8FcwTokEhNZLha57kTt4PctkJfhTh6QBwloAj40J3TbZ3IsUwdzURsO4K/gf0lpIAAq6TO55NGCfQfkht3kc3647L@dBL5A0g2ZmaWyldgW4ePDxdiGCAE60QiLub1wAScrd5gQOXxVOOObDgOoekLqSEKR54w@ZwqTlgzRaZFTwETAqkV40MMvMNEt5K45bKcRpxguN2jzWDF7szie69BxlD3PvrgPW8x8v1h2demiK1@RJ1m/iSZom3AcmsIpDTsp7c3rqTVcbIDgc7eXJXbH4pAXYtGQ2D1P4U2ooy9FLixXECOdUVxY9iQhHqJy5c4xyvdotEPsnuePgYjagnDvqaV0vGTpLGQTig2Bi8CBjMYuBUIQSVpJuO3w3xfaIowgCu1zM/@PVJCdQTPzzopCId98bzB7fB3Z/D@zAa/RUn6fjhcTKdHX749rujj9//cHzy4@nZT93e@cXlz1e//Prb79cVvL0JTacjDyQGw8iRw34uapFXQpCKPw7dNIhCoN54EJO3TTMhKBRZxQqbsvPDO1L4Qi5Tkh@Ik9VpvGHirXmQyijeyeRZmjVNWSyT7htOBFnZ@29ftT3zS02D5QX1Kiu3qsL6myyK2tALB@mtif@3srJhKtDQD0iVGBbkg@wt9rJkpEE49sy8tHguLCxqFPuBBMz8f1df36y8/lVV1/@l4qiPK7a1x379hPCCZMvEZsqGcBD6Ed0Lo9y8x57/AQ "JavaScript (Babel Node) – Try It Online") (comes with test cases)
Defines a function `f` that takes the code as argument.
### Explanation
This monstrosity is essentially a huge recursive bitwise AND, which somehow happens to work as a parser for this C subset. Scores are stored as `0137` for `0123` respectively and converted in the end as `log2(score+1)`; if any phase detects a problem in the code, it returns a score lower than 7, which in turn unsets bits from the final output and results in a lower score. All functions return a score.
If the code runs out of input, it will just continue happily reading `undefined`s from the token array. This is fine, since the only function that matches `undefined` is `J`, and anything will eventually finish recursing and return 0 due to not matching a closing `}`. (Except for `S` and `Q` which have explicit checks for end of input.)
```
// Globals:
// I = input tokens
// i = input position
// P = last token consumed
// R = last identifier consumed
// x,y,z = number of assignments, binary ops, func calls
// A = current function args
// F = current function name
// L = used identifiers as bitfields: 1=argument, 2=call, 4=definition
// U = function arg counts
// M(p): Consume a token, store it in P, return 7 if P == p, otherwise false (0).
M = p => (P = I[i++]) == p && 7
// J(): Copy P to R, return 7 if valid identifier, otherwise 0.
J = _ => /^[a-z]+$/.test(R = P) * 7
// O(Z, 0): Parse args for R() using the function Z.
O = (Z, a, n = R) => // a = arg count, n = name of function (for nested calls)
M`)` ? // consume token, is it ")"?
(L[n] |= 2) // if yes, mark n() as a called function
& 1 // and see if n has been used as an arg
| U[n] - (U[n] = a) // see if n() already has a different arg count, store new count
? 1 : 7 // if yes to either, cap score at 1
: // token wasn't ")"
(a++ // increment arg count, is this first arg?
? P == "," // if not, truthy only if token was ","
: i--) // else, push token back & be truthy
&& Z() // if truthy, parse the actual arg
& O(Z,a,n) // and recurse
// E(): Parse expression.
E = _ =>
// first, parse a primary expression:
(M`(` // consume token, is it "("?
? E() & M`)` // if yes, parse expr + ")"
: P-~P ? // else, is it numeric?
7 // if yes, it's a valid primary expr
: // else,
J() & // parse identifier into R
(M`(` // consume token, is it "("?
? O(E, !++z) // if yes, parse args for R()
: A[i--, R] | 1) // else, push token back and see if R is a valid variable
) & ( // now, handle infix operators:
/[+*/%-]/.test(I[i]) // is the next token an operator?
? E(++y + i++) // if yes, consume & parse another expr
: 7) // else, we're done
// S(): Parse statement.
S = _ =>
M`return` ? // consume token, is it "return"?
E() & M`;` & M`}` // if yes, parse expr + expect ";}"
& ((x | y | z) > 1 ? 3 : 7) // and check modularity
: P && // else, if EOF, return undefined
(P == "if" // else, is it "if"?
? M`(` & E() & M`)` // if yes, parse "(" + expr + ")"
+ M() // and consume another token to P
: // else,
7) // just a normal assignment
& J() // parse identifier into R
& (A[R] | 1) // check if R is a valid variable
& M`=` & E() & M`;` // parse "=" + expr + ";"
& S(++x) // parse next statement
// Q(): Parse function.
Q = _ =>
M() || // consume token, return undefined if EOF
J(A = {}) // parse identifier into R
& (L[F = R] & 5 ? 1 : 7) // see if it's been used as arg or defined
& M`(` // expect "("
& O(_ => // parse arg list with O(), name parsing func:
J(M()) & // consume & parse identifier into R
(A[R] | // see if R is already in this func's args
(L[R] |= 1) // mark R as a used arg name
& 6 // see if R() is a called or defined func
? 1 // if yes to either, cap score to 1
: A[R] = 7), // else, add R to this func's args
x = y = z = 0) // reset modularity counters
& M`{` & S() // parse "{" + statement(s)
& Q(L[F] = 6) // parse next function, mark F() as defined
// f(c): Parse & score code c.
f = c =>
Math.log2(Q(
U = {}, L = {}, i = 0,
I = c.match(/\w+|\S/g) || []) // C lexer (:D)
+ 1)
```
Some of my favorites:
* `(L[n]|=2)&1|U[n]-(U[n]=a)?1:7` simultaneously exploits `undefined`, `NaN` and left-to-right evaluation order
* There turned out to be a shorter "is numeric" check than `x==+x`, when used only as truthy/falsy: `x-~x`.
] |
[Question]
[
# Convert a number to a sum of digits
**Not any sum:** we need the **shortest** sum
**Not any digits:** you can use only **digits of the number**
***Example***
You will be given as **input** an integer `n>0`
Let's say `n=27`. You have to express `27` as a **sum**, using **only the digits** `[2,7]`, in the **shortest** way possible. **You don't have to use all the digits of the given number!**
So `27=2+2+2+7+7+7`. We then **take those digits and count them**: `[2,2,2,7,7,7]`.
Final answer for `n=27` is `6`
One more example for `n=195` in order to get the **shortest sum** we have to use the following digits:
`[5,5,5,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9]` and the **answer** is `23`
# The challenge
Given an integer `n>0`, output the **minimum number of digits** (contained in the number) that **sum up to this number**
# Test Cases
`Input->Output`
```
1->1
2->1
10->10
58->8
874->110
1259->142
12347->1765
123456->20576
3456789->384088
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").Shortest answer in bytes wins!
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
Lḟo=⁰ΣṁΠḣ∞d⁰
```
Handles two-digit numbers pretty fast.
[Try it online!](https://tio.run/##yygtzv7/3@fhjvn5to8aN5xb/HBn47kFD3csftQxLwUo8P//f1MLAA "Husk – Try It Online")
## Explanation
```
Lḟo=⁰ΣṁΠḣ∞d⁰ Input is n, say n = 13.
d⁰ Digits of n: [1,3]
∞ Repeat infinitely: [[1,3],[1,3],[1,3],[1,3]...
ḣ Prefixes: [[],[[1,3]],[[1,3],[1,3]],[[1,3],[1,3],[1,3]],...
ṁ Map and concatenate
Π Cartesian product: [[],[1],[3],[1,1],[3,1],[1,3],[3,3],[1,1,1],[3,1,1],...
ḟo Find the first element
Σ whose sum
=⁰ equals n: [3,3,3,3,1]
L Return its length: 5
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
lef!-TsM`Q./
```
[Try it online!](https://tio.run/##K6gsyfj/Pyc1TVE3pNg3IVBP//9/I3MA "Pyth – Try It Online")
Unfortunately it memory errors on inputs as large as `58`.
### Explanation
```
lef!-TsM`Q./
./ All lists of integers that sum to [the input]
f Filter for:
-TsM`Q Remove all occurrences of the digits in the input
! Check if falsey (i.e. an empty list)
le Length of the last occurrence, which is the shortest because all the
filtered partitions share the same digit pool
```
[Answer]
# Mathematica, 78 bytes
```
(t=1;While[(s=IntegerPartitions[x=#,t,IntegerDigits@x])=={},t++];Tr[1^#&@@s])&
```
finds last test case in 5 sec
[Answer]
# [R](https://www.r-project.org/), 78 bytes
```
function(n){while(all(F-n)){F=outer(F,n%/%10^(0:nchar(n))%%10,"+")
T=T+1}
T-1}
```
[Try it online! (golfed version)](https://tio.run/##FYzRCoMgFEDf/QophHupmDYGbeBrX@DzQERJKAVLxoi@3bmX83A4nFScLC4Hc/gYIOD5WfxqQa8rzENAPGcZ82ETzH1gNyb4G/grmEWnGiOrom@6BomSqhMXUYO4ioPHhMTBeP9zeiJpqQMxcqQtNTrvdqeb3WL60sNvtv7LDw "R – Try It Online")
Pure brute force algorithm, so it doesn't actually solve all the test cases, and I think it tried to allocate 40,000 GB for the last test case...
`T` in R defaults to `1` so we get an off-by-one error which we correct at the return step, but we also get `F` which defaults to `0` which pays off.
ungolfed explanation:
```
function(n){
d <- n%/%10^(0:nchar(n))%%10 # digit list with a 0 appended at end
d <- unique(d[d>0]) # filter zeros (not technically necessary)
# and get unique digits
x <- 0 # storage for sums
i <- 0 # counter for number of sums done
while(!any(x==n)){ # until we find a combination
x <- outer(x,d,"+") # take all sums of x and d, store as x
i <- i + 1} # increment counter
i} # return counter
```
[Try it online! (less golfy version)](https://tio.run/##DcrBCoQgEADQ@/zFBsJIQXYNpqM/EbsQjUtCTCRJRvTt5vXxQs7/KPPhN0HRN5OoVnXmh6aXeZlCQa0KAFMUv0eHPPJgvhoSGTgXvzr8THJhIir1TrTFwwVMDTdVXWmwZOvuAfvk/AI "R – Try It Online")
[Answer]
# Python 2, ~~168~~ ~~155~~ 144 bytes
It isn't the *shortest* it could be, but it's best-first and not *real* bad, runtime wise.
```
n=input()
g=sorted(set(n)-{0})[::-1]
def h(k):
if k<0:return
if`k`in g:return 1
for d in g:
f=h(k-int(d))
if f:return 1+f
print h(int(n))
```
~~The `filter(None...` is to remove 0 as a digit, which I learned I could do while making this.~~
The biggest problem is python stack frames, which realistically don't allow me to run this on the largest inputs. So, it is not a valid solution, really, I played around with increasing the recursion limit which just led to seg-faults. This has to either be done with a loop and a stack or with a lot more cleverness to work in python.
edit: Thanks to caird and Chas Brown for 13 bytes!
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
Pretty inefficient
```
VVo=⁰ΣMṖNṘ⁰d⁰
```
[Try it online!](https://tio.run/##yygtzv7/Pyws3/ZR44Zzi30f7pzm93DnDCAnBYj///9vaAwA "Husk – Try It Online")
[Answer]
## JavaScript (ES6), 82 bytes
```
f=(n,l=0,a=n,[c,...b]=a)=>n?1/c?Math.min(!+c|+c>n?1/0:f(n-c,l+1,a),f(n,l,b)):1/0:l
```
```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```
Takes input as a string.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 70 bytes
```
->n{w,s=n.digits,0;s+=1while !w.product(*[w]*s).find{|x|x.sum==n};s+1}
```
Very slow, try all the possible combinations increasing the size until we get to a solution.
Thanks Dennis for Ruby 2.4 on TIO.
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vulyn2DZPLyUzPbOkWMfAuljb1rA8IzMnVUGxXK@gKD@lNLlEQyu6PFarWFMvLTMvpbqmoqZCr7g019Y2rxao3LD2f4FCWrShQSwXiDa1iP0PAA "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
D;0ṗµḟ€0
ÇS€=µT
Çị1ĿL€Ṃ
```
[Try it online!](https://tio.run/##y0rNyan8/9/F2uDhzumHtj7cMf9R0xoDrsPtwUDa9tDWECDz4e5uwyP7fYACD3c2/f//39AAAA "Jelly – Try It Online")
This is so inefficient, that it does not run for the test cases after the third one on TIO due to a time limit >\_<
Any golfing tips are welcome!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~183~~ ~~176~~ ~~172~~ ~~166~~ 161 bytes
```
def f(n,D=0,p=0,b=0):
D=D or set(map(int,`n`))-{0}
d=min(D);c=0;D=D-{d}
q=[p+n/d,b][n%d>0]
while c<min(D or{0}):q=b=f(n-c*d,D,p+c,b);c+=1
return[q,b][q>b>0]
```
[Try it online!](https://tio.run/##NU7LboMwEDzjr@BSxS5GNQQCIV1O/gsUKTUmCVKzMZSqqqJ@O1276mFnRvuYHfe9XO@Yr6sdzvGZo9SgpKMyoETDIg06vs/xx7Dw25vjIy7yhCch0of6YZGF24hci0MP6kCr6cNSd4LOJfhipTl2@GRbdWTR13V8H@L@NeyTI52LZgID9DPtn63U0iW9NGSVQMaieVg@Z@wm7zG1hjxCwgtH0biZYsQoN9BuJN0LduGZhzwo5bGsPdZVEVp5uf/jbVH9i3LnleeqDtN9Xe3KYptnYv0F "Python 2 – Try It Online")
Longer than the other Python answer, but performs all test cases combined plus `987654321` in under a second on TIO.
Takes advantage of the fact that if `d1<d2` are digits, then there need be at most `d2-1` `d1`'s in the sum (since `d2` instances of `d1` can be replaced with `d1` instances of `d2` for a shorter sum). Thus, sorting the digits in ascending order, there are "only" at most `9! = 362880` possible sums to consider; and a maximum recursion depth of `9` (regardless of the value of `n`).
[Answer]
# [Haskell](https://www.haskell.org/), 91 bytes
```
f n=[read[c]|c<-show n,c>'0']#n!!0
s#n|n>0,x:m<-(s#).(n-)=<<s=[1+minimum(x:m)]|1<3=[0|n==0]
```
[Try it online!](https://tio.run/##DcnRCsIgFADQ977iDoMpzXBEEMO7HxEfxDYm7d5iLurBf7fO61lCfkzrWusMjG6bwt1FX6LVeXl@gLs4tqb1gpvGHLLgwqPpvgNZLbNQZ8laobUZXX@ixIneJP@rfOntBZ0pjGh8pZAYEF5b4h2OMMP1Vn8 "Haskell – Try It Online") Example usage: `f 58` yields `8`. Quick for two-digit numbers, horrendously slow for larger inputs.
The function `f` converts the input number `n` into a list of digits while filtering out zeros. Then this list and `n` itself are handed to the `(#)` function, which returns a singleton list. `!!0` returns the element of this singleton list.
`(#)` uses singleton and empty lists as option type. Given an input of `n=58` and `s=[5,8]`, the idea is to subtract all digits in `s` from `n`, then recursively apply `(#)` and check which digit resulted in the minimum number of steps and return one plus this minimum as result. The first part is computed by `(s#).(n-)=<<s`, which is the same as `concat(map(s#)(map(n-)s))`. So in our example first `[58-5,58-8]` is computed, followed by `[[5,8]#53,[5,8]#50]` which results in `[[7],[7]]` or `[7,7]` after `concat`. The result is matched on the pattern `x:m` to make sure the list has at least one element (`minimum` fails otherwise), then the singleton list of 1 plus the minimum of the result is retuned. If `n` was smaller zero or the recursive call returned an empty list, we are in a failing branch of the search and an empty list is returned. If `n==0` the branch was succeeding and `[0]` is returned.
---
# [Haskell](https://www.haskell.org/), 101 bytes
```
f n=[d|d<-[9,8..1],show d!!0`elem`show n]#n!!0
s@(d:r)#n|n>=d,[x]<-s#(n-d)=[x+1]|1<3=r#n
s#n=[0|n==0]
```
[Try it online!](https://tio.run/##RY3LboMwEEX3/oqJ6CJRTGTeTsVU/Q9kKRQbgQKTCtM2kfh3aqCP3bln5s40pb2arpvnGggLPencL85cnk6B4ra5fYHe7cTFdKa/rJGUR84w@7rXz8PBo4leUPPirnLfenvy9QGL@zFQU5BHOHjErOcOi4kQhZr7siVA0Ddg4PtQNaa6QkkPoI/@zQwM3oeWRniCGoIwijO2rn2aoa0fUHYdjMaOUJXW2P/dkjQUDJYOYsBXCheCTQrHYtOJRJQbyix2/ncQhMnZxTjk8NNa3juTpQn/E0mKGIokSze1iEy6XiRjIaWavwE "Haskell – Try It Online") A way more efficient approach, checks all test cases in under one second.
This time, the list of digits of the input is computed to be in descending order, which allows `(#)` to try to use the largest digit as often as possible, then the second largest, and so until a solution is found. The first solution found this way is also guaranteed to be the smallest one.
] |
[Question]
[
[Underload](http://esolangs.org/wiki/Underload) is a stack-based semi-functional tarpit created by [ais523](https://codegolf.stackexchange.com/users/62131/ais523). I've recently been trying to golf in it, as it's a surprisingly elegant language.
What tips do you have for golfing in Underload? (One tip per answer)
[Answer]
## Use `*` for output
Because [you can output by leaving a string on the stack](https://codegolf.meta.stackexchange.com/a/8507/61384), it might be useful to accumulate the string by using `*` rather than outputting with `S`. Say your challenge was "take a string and append a space", the way to do it with output would be:
```
S( )S
```
The way to do it with `*`, on the other hand is one byte shorter:
```
( )*
```
The problem is that if your output has a lot of accumulation, it might cost bytes to deal with the output element on the stack.
[Answer]
## "Dirty" Decrement
The functionally-pure way to decrement a Church numeral is to use the lambda calculus predecessor function:
```
\n.n(\p.\z.z($(pT))(pT))(\z.z0[whatever you define the predecessor of 0 to be])
```
Where 0 = \x.\y.y, T = \x.\y.x, and $ is the successor.
Rewritten in Underload, this is 28 bytes:
```
(!())~(!())~(!:(:)~*(*)*~)~^!
```
This is alright, but we can exploit some of Underload's useful properties, namely that `:!` and `()*` do are no-ops. This means that, for a number `n`, `:ⁿ!!()()*ⁿ` (where `cⁿ` is `c` repeated `n` times) yields n-1. For example doing this for the Church numeral 3 yields this:
```
:::!!()()***
```
Removing no-op pairs, we get:
```
:*
```
Which is 2.
So this is the new and shorter predecessor operation:
```
:(:)~^(!!()())*~(*)~^*
```
This is 7 bytes shorter.
[Answer]
# Use a dictionary of repeatedly reused functions
If you need to use a piece of code a lot, it makes sense to store that code on the stack and duplicate-and-eval it every now and then. So far, that's just normal Underload programming. Unfortunately, keeping a value around on the stack for a long time is difficult and tends to cause your code to become verbose, and that's true even if the value is a function rather than data. This gets a lot worse if you have multiple functions that need to be reused repeatedly.
In the sort of larger program that might benefit from several reused functions, a solution you can use is to instead make one large function that can fulfil any of their purposes depending on the way it's called (either based on what's underneath it on the stack, or via using longer calling sequences than just `^`; a carefully written function can distinguish `^^` from `^:^` from `^*^` from `^~^`, giving you four distinct, fairly short sequences). You can also store other useful things, such as strings that you use multiple times, in this "dictionary". Note that if you use the dictionary heavily, it may make sense to make it a kind of quine, pushing a copy of itself back onto the stack, so that you don't need to manually copy it with `:` to be able to use it without losing the ability to use it in the future.
[Answer]
# Choose data formats specialized to the operations the problem needs
As a simple example, the most commonly seen implementation of booleans are `!()` for false (i.e. integer 0), and the null string for true (i.e. integer 1), but if you have a problem that's heavily based around logical XOR, it might make more sense to use the null string for false, and `~` for true (this data format can be converted into any other boolean format using `(false)~(true)~^!`, and allows the very terse implementation `*` for XOR.
It's possible to take this general principle even further and use functions that your program will need later as part of your data values; that saves having to store the functions and data separately on the stack. This can make the control flow rather more confusing, but when golfing, maintainability often has to take a back seat, and it's not like Underload is all that usable anyway.
[Answer]
# Put Unneeded Stack Values into the Program Space
Underload actually has two stacks—the stack of strings, and the stack of commands that make up the source code. Underload's `^` instruction lets us move strings from the former stack to the latter. By doing this, we can save a lot of unnecessary stack manipulation.
For example, say we have `(a)(b)(c)` on the main stack and we'd like to concatenate the bottom two elements, ignoring `(c)`, to get `(ab)(c)`. The naïve way to do this is to rotate the stack to get `(c)(a)(b)` and then concantenate and swap back:
```
a~a~*~a*^*~
```
This is bad. Using `a~a~*~a*^` to rotate the stack like this is extremely costly, and should be avoided when possible. By putting `(c)` into the program space instead, this can be made four bytes shorter:
```
a(*)~*^
```
The idea is to take the instructions you'd like to execute and then add an instruction to push `(c)` back at the end, and then evaluate the result. This means that we don't have to worry about `(c)` until it's pushed back after we've finished.
] |
[Question]
[
Given a non empty finite sequence of integers, return an arithmetic subsequence of maximal length.
If there are multiple of the same maximal length, any of them can be returned.
### Definitions:
An *arithmetic* sequence is a sequence \$a(1),a(2),a(3),a(4),...\$ such that there is a constant \$c\$ such that \$a(m+1)-a(m) = c\$ for all \$m\$. In other words: The difference between two subsequent terms is constant.
Given a sequence \$b(1),b(2),b(3),b(4),...\$ a *subsequence* is a sequence \$b(s(1)),b(s(2)),b(s(3)),b(s(4)),...\$ where \$1 <= s(1)\$ and \$s(m) < s(m+1)\$ for all \$m\$. In other words: Take the original sequence and remove as many entries as you want.
### Examples
```
Input Output
[4,1,2,3,6,5] [1,3,5] or [1,2,3]
[5,4,2,-1,-2,-4,-4] [5,2,-1,-4]
[1,2,1,3,1,4,1,5,1] [1,1,1,1,1] or [1,2,3,4,5]
[1] [1]
```
Some longer test cases:
```
Length: 25
Input: [-9,0,5,15,-1,4,17,-3,20,13,15,9,0,-6,11,17,17,9,26,11,5,11,3,16,25]
Output: [15,13,11,9] or [17,13,9,5]
Length: 50
Input: [35,7,37,6,6,33,17,33,38,30,38,12,37,49,44,5,19,19,35,30,40,19,11,5,39,11,20,28,12,33,25,8,40,6,15,12,27,5,21,6,6,40,15,31,49,22,35,38,22,33]
Output: [6,6,6,6,6] or [39,33,27,21,15]
Length: 100
Input: [6,69,5,8,53,10,82,82,73,15,66,52,98,65,81,46,44,83,9,14,18,40,84,81,7,40,53,42,66,63,30,44,2,99,17,11,38,20,49,34,96,93,6,74,27,43,55,95,42,99,31,71,67,54,70,67,18,13,100,18,4,57,89,67,20,37,47,99,16,86,65,38,20,43,49,13,59,23,39,59,26,30,62,27,83,99,74,35,59,11,91,88,82,27,60,3,43,32,17,18]
Output: [6,18,30,42,54] or [8,14,20,26,32] or [46,42,38,34,30] or [83,63,43,23,3] or [14,17,20,23,26] or [7,17,27,37,47] or [71,54,37,20,3]
```
### Background
I got this idea when I recalled the Green-Tao-Theorem from 2004, which states that the sequence of primes contains finite arithmetic sequences of arbitrary length.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒPIE$ÐfṪ
```
[Try it online!](http://jelly.tryitonline.net/#code=xZJQSUUkw5Bm4bmq&input=&args=WzQsMSwyLDMsNiw1XQ) or [verify all test cases](http://jelly.tryitonline.net/#code=xZJQSUUkw5Bm4bmqCsOH4oKsRw&input=&args=WzQsMSwyLDMsNiw1XSwgWzUsNCwyLC0xLC0yLC00LC00XSwgWzEsMiwxLDMsMSw0LDEsNSwxXSwgWzFd).
### How it works
```
ŒPIE$ÐfṪ Main link. Argument: A (list of integers)
ŒP Powerset; generate all sublists of A, sorted by length.
Ðf Filter the powerset by the link to the left:
$ Combine the two atoms to the left into a monadic link.
I Compute all increments.
E Test whether they're all equal.
This returns all arithmetic subsequences, sorted by length.
Ṫ Tail; extract the last sequence.
```
[Answer]
## Pyth, ~~12~~ 11 bytes
```
ef!P{-VTtTy
```
[Test suite.](https://pyth.herokuapp.com/?code=ef%21P%7B-VTtTy&test_suite=1&test_suite_input=%5B4%2C1%2C2%2C3%2C6%2C5%5D%0A%5B5%2C4%2C2%2C-1%2C-2%2C-4%2C-4%5D%0A%5B1%2C2%2C1%2C3%2C1%2C4%2C1%2C5%2C1%5D%0A%5B1%5D&debug=0)
```
y powerset of implicit input, generate all subsequences
ef T find the last subsequence (sorted increasing in length) where...
Tt bifurcate over tail, giving [1,2,3,4,5] [2,3,4,5]
-V vectorize over -, giving differences of each consecutive pair
{ dedup (remove duplicate elements)
P pop, resulting in [] if all differences were equal
! boolean not, resulting in True if all differences were equal
```
Thanks to [@LeakyNun](https://codegolf.stackexchange.com/users/48934/leaky-nun) for a byte!
[Answer]
# MATL, ~~19~~ ~~18~~ ~~17~~ ~~16~~ 18 bytes
*1 byte saved (and 2 bytes added back) thanks to Luis!*
```
"GX@XN!"@dun2<?vx@
```
A fairly naive approach which brute force checks all ordered permutations of the input. Obviously this can take a while for longer sequences. To save a byte, I have started with the smallest sub-sequences (length = 1) and worked up to the larger sequences (length = N).
[**Try it Online!**](http://matl.tryitonline.net/#code=IkdYQFhOISJAZHVuMjw_dnhA&input=WzQsMSwyLDMsNiw1XQ)
**Explanation**
```
% Impilicitly grab input array (N)
" % For each value in this array
G % Explicitly grab the input
X@ % Loop index, will be [1, 2, ... length(N)] as we iterate
XN % Determine all permutations of k elements (nchoosek). The output is
% each k-length permutation of the input as a different row. Order doesn't
% matter so the result is always ordered the same as the input
! % Take the transpose so each k-length permutation is a column
" % For each column
d % Compute the difference between successive elements
un % Determine the number of unique differences
2<? % If there are fewer than 2 unique values
vx % Vertically concatenate everything on the stack so far and delete it
@ % Push the current permuatation to the stack
% Implicit end of if statement
% Implicit end of for loop
% Implicit end of for loop
% Implicitly display the stack
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
►oEẊ-Ṗ
```
[Try it online!](https://tio.run/##yygtzv7//9G0XfmuD3d16T7cOe3////RpjomOkY6uoY6ukDSBIhiAQ "Husk – Try It Online")
## Explanation
The return value of `E` is useful here for getting the longest list that satisfies a condition.
```
►oEẊ-Ṗ Implicit argument: a list.
Ṗ List of all its subsequences.
► Find one that maximizes:
o Composition of two functions:
Ẋ 1. Apply to adjacent elements:
- Subtraction.
E 2. Are all elements equal?
Returns length+1 if they are, 0 if not.
```
[Answer]
# Python 2, ~~124~~ ~~115~~ ~~98~~ 97 bytes
```
p=[[]]
for n in input():p+=[x+[n][:2>len(x)or n-x[-1]==x[1]-x[0]]for x in p]
print max(p,key=len)
```
Very slow and memory intensive. Test it on [Ideone](http://ideone.com/BjAtUE).
### Alternate version, 98 bytes
```
p={()}
for n in input():p|={x+(n,)[:2>len(x)or n-x[-1]==x[1]-x[0]]for x in p}
print max(p,key=len)
```
This completes all test cases instantly. Test it on [Ideone](http://ideone.com/gQwG9c).
[Answer]
# Pyth [checkout 8593c76, March 24th](https://github.com/isaacg1/pyth/commit/8593c7647dad748d523ebdc3d7c625c30fe9a9f3), 10 bytes
```
efq-VTtT)y
```
This is exactly the same as Doorknob's answer, except that back in march, there was a 2 byte function (`q ... )`) which checked whether all of the elements of a list were the same, which is the same as `!P{`, which is the best you can do currently.
[Answer]
## JavaScript (ES6), 157 bytes
```
a=>{for(m=i=0,l=a.length;i<l;i++)for(j=i;++j<l;)for(t=n=a[k=i],c=0;k<l;k++)a[k]==t&&(t+=a[j]-n,++c>m)?q=a[m=c,p=n,j]-n:q;return a.slice(-m).map(_=>(p+=q)-q)}
```
Almost 20 times longer than the Jelly answer... Ungolfed:
```
function subsequence(a) {
var max = 0;
for (var i = 0; i < a.length; i++) {
for (var j = i + 1; j < a.length; j++) {
var target = a[i];
var count = 0;
for (var k = i; k < a.length; k++) {
if (a[k] == target) {
count++;
target += a[j] - a[i];
if (count > max) {
max = count;
start = a[i];
step = a[j] - a[i];
}
}
}
}
}
var result = new Array(max);
for (var i = 0; i < max; i++) {
result[i] = start + step * i;
}
return result;
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
à ñÊkÈän än d
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4CDxymvI5G4g5G4gZA&input=WzQsMSwyLDMsNiw1XQotUQ)
] |
[Question]
[
Sometimes it is useful to run a math problem with multiple inputs. The goal of this challenge is to make a program that eases this task.
## Number-generating expressions
You must support 3 types of expression:
* Single number generator: Very simple, just a literal number
* Multi-number generator: A tad more complicated. Thees are surrounded by square brackets (`[]`). Numbers are comma (`,`) separated in the expression. Example `[-1,2,3.26]`.
* Range generator: This one is surrounded by curly braces (`{}`). It will have 3 numbers separated by a comma. The format of this expression is `{start,stop,step}`. `start` and `stop` are inclusive.
## Rules for evaluation
* You must support the order of operations. (<https://en.wikipedia.org/wiki/Order_of_operations#Definition>)
* You don't need to support parenthesis.
* Any number of spaces may occur in the expression.
* You must support floating point numbers (whatever precision your language defaults to is fine).
* Division by `0` results in `NaN` (not a number).
Your program must support multiplication (`*`), division (`/`), addition (`+`) and subtraction (`-`).
## Output
Each line of output is one of the combinations of the generators. The format is the expression (with the real numbers substituted into it) followed by a equals sign (`=`) and the result of evaluation. All combinations of the generators must be represented in the output.
## Examples
(`>>>` denotes input)
```
>>>3 * [3,2]
3 * 3 = 9
3 * 2 = 6
>>>{1,2,3}
1 = 1 <-- this is because 1 + 3 > the end
>>>{0,2,1} + {0,1,1}
0 + 0 = 0
1 + 0 = 1
2 + 0 = 2
0 + 1 = 1
1 + 1 = 2
2 + 1 = 3
>>>6/[2,3]
6/2 = 3
6/3 = 2
>>>{1.5,2.5,0.5}
1.5 = 1.5
2 = 2
2.5 = 2.5
>>>3-{6,5,-1}
3-6 = -3
3-5 = -2
>>>5/{-1,1,1}
5/-1 = -5
5/0 = NaN
5/1 = 5
>>>4.4 / [1,2.2] + {0,2,1}
4.4 / 1 + 0 = 4.4
4.4 / 1 + 1 = 5.4
4.4 / 1 + 2 = 6.4
4.4 / 2.2 + 0 = 2
4.4 / 2.2 + 1 = 3
4.4 / 2.2 + 2 = 4
>>> [1,2] / 0 + 5
1 / 0 + 5 = NaN
2 / 0 + 5 = NaN
```
The program needs to be short so I can memorizes it and use it anywhere.
Thanks to @PeterTaylor and @geokavel for helping me with this post in the sandbox
[Answer]
# JavaScript (ES6), ~~213~~ 211 bytes
```
f=x=>(a=0,x=x.replace(/\[.+?]|{.+?}/,r=>([i,l,n]=a=r.slice(1,-1).split`,`,r[0]>"]"&&eval(`for(a=[];n>0?i<=+l:i>=+l;i-=-n)a.push(i)`),"x")),a?a.map(n=>f(x.replace("x",n))).join``:x+` = ${r=eval(x),r<1/0?r:NaN}
`)
```
## Explanation
A recursive function that executes the expression if it does not contain any multi-number or range generators, or if it does contain one of these generators, calls itself with the generator replaced with each number produced by it.
Dividing by `0` in JavaScript produces `Infinity`, so `Infinity` can simply be replaced with `NaN`.
Using this method the multi-generators are parsed from back-to-front instead of front-to-back like in the test cases. This just means the order of the output expressions is different sometimes.
```
f=x=>(
a=0, // initialise a to false
x=x.replace(/\[.+?]|{.+?}/,r=>( // find the first multi-generator
[i,l,n]= // i = start, l = stop, n = step
a=r.slice(1,-1).split`,`, // a = each number of generator
r[0]>"]"&& // if a range generator was found
eval(` // use eval to enable for loop here
for(a=[];n>0?i<=+l:i>=+l;i-=-n)a.push(i) // add each number of the range to a
`),
"x" // replace the generator with "x"
)),
a? // if a multi-generator was found
a.map(n=> // for each number n in a
f(x.replace("x",n)) // call itself with n inserted
)
.join`` // combine the output of each result
:x+` = ${r=eval(x), // evaluate the expression
r<1/0?r:NaN}
` // replace Infinity with NaN
)
```
## Test
Test does not use destructuring assignments for browser compatibility.
```
f=x=>(a=0,x=x.replace(/\[.+?]|{.+?}/,r=>(a=r.slice(1,-1).split`,`,r[0]>"]"&&eval(`i=a[0],l=a[1],n=a[2];for(a=[];n>0?i<=+l:i>=+l;i-=-n)a.push(i)`),"x")),a?a.map(n=>f(x.replace("x",n))).join``:x+` = ${r=eval(x),r<1/0?r:NaN}
`)
```
```
<input type="text" id="input" value="4.4 / [1,2.2] + {0,2,1}" />
<button onclick="result.textContent=f(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# Haskell, ~~474~~ 362 bytes
The function f takes a string as input and prints the results
```
g '+'=(+);g '-'=(-);g '*'=(*);g '/'=(\a b->a*b/b/b)
p[]=[]
p(o:x:y)=[(flip(g o)$n,' ':o:' ':show n)|n<-v]:p r where
[f,e,s]=z;(z,h)=reads('[':y)!!0;(w,m)=reads(x:y)!!0;(v,r)|x=='['=(z,h)|x=='{'=([f,f+s..e],h)|True=([w],m)
h '}'=']';h x=x
d(a,b)=putStrLn.drop 3$foldl(++)""b++" = "++show(foldl(flip($))0a)
f t=mapM_(d.unzip)$sequence$p(filter(/=' ')$'+':map h t)
```
tests :
```
main=do
f "4.4 / [1,2.2] + {0,2,1}"
putStrLn""
f "[1,2] / 0 + 5"
putStrLn""
f "{0,2,1} + {0,1,1}"
```
output:
```
4.4 / 1.0 + 0.0 = 4.4
4.4 / 1.0 + 1.0 = 5.4
4.4 / 1.0 + 2.0 = 6.4
4.4 / 2.2 + 0.0 = 2.0
4.4 / 2.2 + 1.0 = 3.0
4.4 / 2.2 + 2.0 = 4.0
1.0 / 0.0 + 5.0 = NaN
2.0 / 0.0 + 5.0 = NaN
0.0 + 0.0 = 0.0
0.0 + 1.0 = 1.0
1.0 + 0.0 = 1.0
1.0 + 1.0 = 2.0
2.0 + 0.0 = 2.0
2.0 + 1.0 = 3.0
```
[Answer]
# Python 3, 387 Bytes
```
def a(q,d=-1,f='',g=float,h=print):
if any((c in q)for c in'[]{}'):
for i,b in enumerate(q):
if d!=-1:
if b in'}]':
e=f.split(",")
if b=='}':
r=g(e[0]);s=[]
while r<=g(e[1]):s.append(str(r));r+=g(e[2])
e[:]=s[:]
[a(q[:d]+n+q[i+1:])for n in e];return
f+=b
if b in'[{':d=i
else:
h(q+" = ",end='')
try:h(str(eval(q)))
except:h("NaN")
```
You can test it with the following code:
```
tests=['3 * [3,2]', '{1,2,3}', '{0,2,1} + {0,1,1}',
'6/[2,3]', '{1.5,2.5,0.5}', '3-{6,5,-1}',
'5/{-1,1,1}', '4.4 / [1,2.2] + {0,2,1}',
'[1,2] / 0 + 5']
for n in tests:
print(n)
a(n)
print()
```
Here is the code ungolfed:
```
def eval_statement(query):
left_bracket_index = -1
inside_bracket_content = ''
if any((bracket in query) for bracket in '[]{}'):
for i, character in enumerate(query):
if left_bracket_index != -1:
if character in '}]':
params = inside_bracket_content.split(",")
if character == '}':
value = float(params[0])
values = []
while value <= float(params[1]):
values.append(str(value))
value += float(params[2])
params[:] = values[:]
for param in params:
new_query = query[:left_bracket_index] + param + query[i + 1:]
eval_statement(new_query)
return
inside_bracket_content += character
if character in '[{':
left_bracket_index = i
else:
print(query + " = ", end='')
try:
print(str(eval(query)))
except:
print("NaN")
```
It works by finding the first set of brackets of any type, and then looping through all the values inside it, by replacing the brackets and its contents with the value and running the method recursively. It uses `eval` once there are no brackets in the line. It returns `NaN` if there is an exception running `eval`.
[Answer]
# Java, 874 bytes
```
void E(String s)throws Exception{int i=0;String t;List<String[]>z=new ArrayList<>();List<String>x=new ArrayList<>(),y=new ArrayList<>();for(String k:s.split(" "))t+=" "+(k.matches("[0-9]+")?"["+k+"]":k);for(String k:t.split(" "))s+=" "+(k.matches("\\{[^\\}]+\\}")?"["+R(k)+"]":k);for(String k:s.split(" "))t+=" "+(k.matches("\\[[^\\]]+\\]")?"$"+(i+=z.add(k.replaceAll("[\\[\\]]","").split(","))):k);x.add(t.substring(1));while (i-->0){y.clear();for(String e:x)for(String l:z.get(i))y.add(e.replace("$"+i,l));x.clear();x.addAll(y);}for(String e:x)System.out.println(e+"="+new javax.script.ScriptEngineManager().getEngineByName("JavaScript").eval(e).replace("Infinity","NaN"));}
String R(String t){String y="",[]s=t.replaceAll("[\\{\\}]","").split(",");int i=I(s[0]);y+="["+i;while ((i+=I(s[2]))<=I(s[1]))y+=","+i;y+="]";return y;}
int I(String t){return Integer.parseInt(t);}
```
---
**Detailed** [Try Here](http://ideone.com/aL45yp)
```
import java.util.*;
import java.lang.*;
import java.io.*;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
class Ideone
{
// single : x -> [x]
public static String expandSingle (String input)
{
String out = "";
for (String str : input.split(" "))
{
out += " ";
if(str.matches("[0-9]+"))
{
out += "["+str+"]";
}
else
{
out += str;
}
}
return out.substring(1);
}
// range : {start,end,step} -> [x,..,y]
public static String expandRange (String input)
{
String out = "";
int a,b,c;
int i=0;
for (String str : input.split(" "))
{
out += " ";
if(str.matches("\\{[0-9]+,[0-9]+,[0-9]+\\}"))
{
str = str.replaceAll("[\\{\\}]","");
a = Integer.parseInt(str.split(",")[0]);
b = Integer.parseInt(str.split(",")[1]);
c = Integer.parseInt(str.split(",")[2]);
out += "["+a;
while ((a+=c) <= b) out += ","+a;
out += "]";
}
else
{
out += str;
}
}
return out.substring(1);
}
public static void main (String[] args) throws java.lang.Exception
{
String input = "3 * [3,2] + {0,2,1}";
System.out.println(" input = "+input);
input = expandSingle(input);
input = expandRange(input);
System.out.println(" expand = "+input);
evaluate(input);
}
public static void evaluate (String input) throws java.lang.Exception
{
int i = 0;
String t = "";
ArrayList<String[]> set = new ArrayList<String[]>();
ArrayList<String> in = new ArrayList<String>();
ArrayList<String> out = new ArrayList<String>();
// map sets
for (String str : input.split(" "))
{
t += " ";
if(str.matches("\\[.+\\]"))
{
str = str.replaceAll("[\\[\\]]","");
set.add(str.split(","));
t+= "$"+i;
i++;
}
else t+=str;
}
in.add(t.substring(1));
// generate expressions
while (i-->0)
{
out.clear();
for (String exp : in)
{
for (String sub : set.get(i))
{
out.add(exp.replace("$"+i,sub));
}
}
in.clear();
in.addAll(out);
}
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
// print expressions
for (String exp : in)
{
System.out.println(" "+exp+" = "+engine.eval(exp).replace("Infinity","NaN"));
}
}
}
```
[Answer]
# ~~[Dyalog APL](http://goo.gl/9KrKoM), 164 bytes~~
This answer does not follow the updated requirements, and is therefore non-competing:
```
{n←⊂'NaN'
R←{+\b,s/⍨⌊((2⊃⍵)-b←⊃⍵)÷s←⊃⌽⍵}
D←{0::n⋄⍺×÷⍵}
↑(∊¨(,⍎'[-+×D]'⎕R','⊢e),¨¨⊂('[-+×÷]'⎕S'\0'⊢⍵),⊂'='),¨,⍎e←'{' '}' '\[' ']' '÷' '[-+×]'⎕R'(R ' ')' '(' ')' '∘.D ' '∘.{0::n⋄⍺\0⍵}'⊢⍵}
```
It uses regexes to change the given expression into the corresponding APL (and all operators are modified to implement `NaN`) and to extract the operators. It substitutes all operators with catenation and executes the expression to obtain the final input numbers. It then weaves it all together to get the final output.
Preserves the order of evaluation of APL (strict right-to-left).
Handles parentheses correctly.
Test cases (with added parentheses to force math-like order of execution):
```
f '3 × [3,2]'
3 × 3 = 9
3 × 2 = 6
f '{1,2,3}'
1 = 1
f '{0,2,1} + {0,1,1}'
0 + 0 = 0
0 + 1 = 1
1 + 0 = 1
1 + 1 = 2
2 + 0 = 2
2 + 1 = 3
f '6÷[2,3]'
6 ÷ 2 = 3
6 ÷ 3 = 2
f '{1.5,2.5,0.5}'
1.5 = 1.5
2 = 2
2.5 = 2.5
f '3-{6,5,¯1}'
3 - 6 = ¯3
3 - 5 = ¯2
f '5÷{¯1,1,1}'
5 ÷ ¯1 = ¯5
5 ÷ 0 = NaN
5 ÷ 1 = 5
f '(4.4 ÷ [1,2.2]) + {0,2,1}'
4.4 ÷ 1 + 0 = 4.4
4.4 ÷ 1 + 1 = 5.4
4.4 ÷ 1 + 2 = 6.4
4.4 ÷ 2.2 + 0 = 2
4.4 ÷ 2.2 + 1 = 3
4.4 ÷ 2.2 + 2 = 4
f '([1,2] ÷ 0) + 5'
1 ÷ 0 + 5 = NaN
2 ÷ 0 + 5 = NaN
```
] |
[Question]
[
You're designing a new esoteric programming language and
one feature you've decided to add is a dynamic memory allocator. Your language specifies a special dedicated virtual address space for the user's program space. This is separate from the address space used by the memory allocator for any internal state.
To help reduce the cost of distributing your implementation the size of the code must be as small as possible.
# Interface
You must provide three functions: initialization, allocate, and deallocate.
### Initialization
This function takes a single positive integer parameter `N`. This means a user's program has `N` bytes in its address space from which there are `N-1` bytes to allocate memory from. The address `0` is reserved for "null".
It is guaranteed that this function will be called exactly once before any allocate/deallocate calls.
Note that this function does not need to allocate any physical memory for the user program's virtual address space; you're basically creating the "look and feel" of a hollow memory allocator.
### Allocate
The allocate function must take a request of the number of bytes of memory to allocate. The input is guaranteed to be positive.
Your function must return an integer address to the start of the allocated block, or `0` to denote that there is no contiguous block of the requested size available. If a contiguous block of the available size is available anywhere in the address space you must allocate!
You must ensure that no two allocated blocks overlap.
### Deallocate
The deallocate function must take an address of the start of an allocated block, and optionally may also take the size of the given block.
Memory that has been deallocated is available again for allocation. It is assumed that the input address is a valid address.
# Example Python implementation
Note that you may choose any method for keeping track of internal state; in this example the class instance keeps track of it.
```
class myallocator:
def __init__(self, N):
# address 0 is special, it's always reserved for null
# address N is technically outside the address space, so use that as a
# marker
self.addrs = [0, N]
self.sizes = [1, 0]
def allocate(self, size):
for i,a1,s1,a2 in zip(range(len(self.addrs)),
self.addrs[:-1], self.sizes[:-1],
self.addrs[1:]):
if(a2 - (a1+s1) >= size):
# enough available space, take it
self.addrs.insert(i+1, a1+s1)
self.sizes.insert(i+1, size)
return a1+s1
# no contiguous spaces large enough to take our block
return 0
def deallocate(self, addr, size=0):
# your implementation has the option of taking in a size parameter
# in this implementation it's not used
i = self.addrs.index(addr)
del self.addrs[i]
del self.sizes[i]
```
# Scoring
This is code golf; shortest code in bytes wins. You need not worry about running out of memory for any internal state required by your allocator.
Standard loop holes apply.
# Leaderboard
```
var QUESTION_ID=67895,OVERRIDE_USER=31729;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 commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&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(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.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(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var 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}#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]
# Ruby, 80
```
i,a,d=->n{$m=?o*n},->n{$m.sub!(/\B#{?o*n}/,?f*n);"#$`".size},->n,s{$m[n,s]=?o*s}
```
Like MegaTom's answer, but uses a *string* instead of an array to store state. The "o" character denotes an open cell, while an "f" denotes a filled one. This lets us use Ruby's relatively terse string manipulation functions:
`?o*n` initializes a string of n "o"s.
`/\B#{?o*n}/` is a regular expression matching n consecutive "o"s that doesn't include the first character.
`sub!` replaces the first match with n "f"s.
`"#$`"` gives the string to the left of the match, or an empty string if there was no match, so the size is either the allocated index or 0.
Deallocate just sets the designated section of the string back to "o"s.
[Answer]
# JavaScript (ES6), 88
Using a global variable `_` (a *very* sparse array) to keep track.
Now how could I test it?
```
I=n=>(_=[1],_[n]=0)
A=n=>_.some((x,i)=>i-p<n?(p=i+x,0):_[p]=n,p=1)?p:0
D=p=>delete _[p]
```
[Answer]
# Ruby, 135
Has a global array keep track of whether each cell is allocated or not.
```
i=->n{$a=[!0]*n;$a[0]=0}
a=->n{s=$a.each_cons(n).to_a.index{|a|a.none?};n.times{|i|$a[s+i]=0}if s;s||0}
d=->s,n{n.times{|i|$a[s+i]=!0}}
```
[Answer]
# Mathematica, 152
```
i=(n=#;l={{0,1},{#,#}};)&
a=If[#=={},0,l=l~Join~#;#[[1,1]]]&@Cases[l,{Except@n,e_}:>{e,e+#}/;Count[l,{a_,_}/;e<=a<e+#]<1,1,1]&
d=(l=l~DeleteCases~{#,_};)&
```
`n` store the total size, `l` stores the internal state. The allocator will try to allocate right behind another section of allocated memory.
] |
[Question]
[
Or else he will huff and puff and blow your house down!
That was completely irrelevant. This challenge is actually about [Huffman coding](https://en.wikipedia.org/wiki/Huffman_coding#Compression). The gist of it is the frequency of characters in a given text is utilized to make its representation shorter. In other words, let's say that our alphabet is `a` through `z` and space. That's 27 characters. Each of them can be uniquely encoded in just 5 bits because 5 bits have enough room for 32 characters. However, in many situations (like English, or languages in general), some characters are more frequent than others. We can use *fewer* bits for the more frequent characters and (perhaps) more bits for the less frequent characters. Done right, there is an overall savings in the number of bits and the original text can still be uniquely reconstructed.
Let's take "this question is about huffman coding" as an example. This text is 37 characters long, which would be 37\*8 = 296 bits normally, though only 37\*5 = **185 bits** if we only use 5 bits for each character. Keep that in mind.
Here is a (sorta) table of each character and their frequencies in the text, sorted from most to least frequent (where \_ stands in for a space):
```
_ 5
i 4
n 3
o 3
s 3
t 3
u 3
a 2
f 2
h 2
b 1
c 1
d 1
e 1
g 1
m 1
q 1
```
An associated optimal coding could be:
```
_ 101
i 011
n 1100
o 1101
s 1110
t 1111
u 001
a 10011
f 0001
h 0101
b 00000
c 00001
d 01000
e 01001
g 10000
m 10001
q 10010
```
It should be immediately clear that this will be a better encoding than just using 5 bits for every character. Let's find out just how much better, though!
**145 bits**, compared with 185! That's a savings of 40 bits, or just over 20%! (This is, of course, assuming that information about the structure is available for decoding.) This coding is optimal because no more bits can be dropped by changing any character's representation.
## The task
* Write a program or function with one parameter that...
* Takes input from STDIN (or equivalent) or as a single argument.
* Output an optimal Huffman coding as above with the characters sorted by frequency (order within a frequency class doesn't matter).
* You may assume that the characters in the input are restricted to the ASCII range `32..126` plus a newline.
* You may assume the input is no longer than 10,000 characters (ideally, in theory, input should be unbounded).
* Your code should finish reasonably fast. The given example above should take no more than a minute or so at worst. (This is intended to rule out brute force.)
* Scoring is in bytes.
## Examples
```
x
---
x 0
xxxxxxxxx
---
x 0
xxxxxxxxy
---
x 0
y 1 (these may be swapped)
xxxxxyyyz
---
x 0
y 10
z 11
uuvvwwxxyyzz
--- (or)
u 000 000
v 001 001
w 100 010
x 101 011
y 01 10
z 11 11
this question is about huffman coding
---
101
i 011
n 1100
o 1101
s 1110
t 1111
u 001
a 10011
f 0001
h 0101
b 00000
c 00001
d 01000
e 01001
g 10000
m 10001
q 10010
```
Happy coding!
---
Note that [this similar question](https://codegolf.stackexchange.com/questions/996/huffman-golfing) is closely related, even to the point that this one is a duplicate. However, the [consensus so far](https://codegolf.meta.stackexchange.com/a/7326/12914) on Meta is that the older one should be considered a duplicate of this one.
[Answer]
# Python 2, 299 bytes
Here's my attempt at an answer.
The Huffman codes are different from the examples given, but should still be optimal.
```
i=raw_input();m=n=[(c,i.count(c))for c in set(i)]
while n[1:]:n.sort(key=lambda x:(x[1]));(a,b),(c,d)=n[:2];n=[((a,c),b+d)]+n[2:]
n=n[0][0]
r=[]
def a(b,s):
if b[1:]:a(b[0],s+'0');a(b[1],s+'1')
else:r.append(b+(s if s[1:]else s+'0'))
a(n,' ')
for y in sorted(r,key=lambda x:-dict(m)[x[0]]):print y
```
[Answer]
# Pyth, 53 bytes
```
jo_/zhNee.WtHa>JohNZ2+shKC<J2]s.b+RYNeKU2m,/zd]+d\ {z
```
[Demonstration](https://pyth.herokuapp.com/?code=jo_%2FzhNee.WtHa%3EJohNZ2%2BshKC%3CJ2%5Ds.b%2BRYNeKU2m%2C%2Fzd%5D%2Bd%5C+%7Bz&input=this+question+is+about+huffman+coding&debug=0)
Here's a version that shows the internal state, so you can see the encoding being built:
```
jo_/zhNee.WtHvp+`a>JohNZ2+shKC<J2]s.b+RYNeKU2bm,/zd]+d\ {z
```
[Demonstration](https://pyth.herokuapp.com/?code=jo_%2FzhNee.WtHvp%2B%60a%3EJohNZ2%2BshKC%3CJ2%5Ds.b%2BRYNeKU2bm%2C%2Fzd%5D%2Bd%5C+%7Bz&input=this+question+is+about+huffman+coding&debug=0)
Copy the output to an environment with wider lines for a clearer picture.
[Answer]
# Matlab, 116 bytes
`tabulate` makes a frequency table. `huffmandict` takes a list of symbols and probabilities for each symbol, and calculates the code.
```
t=tabulate(input('')');
d=huffmandict(t(:,1),cell2mat(t(:,3))/100);
for i=1:size(d,1);disp([d{i,1},' ',d{i,2}+48]);end
```
[Answer]
# Ruby, ~~189~~ 180 bytes
Work in progress.
```
->s{m=s.chars.uniq.map{|c|[c,s.count(c)]}
while m[1]
(a,x),(b,y),*m=m.sort_by &:last
m<<[[a,b],x+y]
end
h={}
f=->q="",c{Array===c&&f[q+?0,c[0]]&&f[q+?1,c[1]]||h[c]=q}
f[m[0][0]]
h}
```
It's an anonymous function; assign it to something, for example `f`, and call it with
```
f["some test string"]`
```
which returns a hash like this:
```
{"t"=>"00", "g"=>"0100", "o"=>"0101", " "=>"011", "e"=>"100", "n"=>"1010", "i"=>"1011", "m"=>"1100", "r"=>"1101", "s"=>"111"}
```
[Answer]
## Haskell, 227 bytes
```
import Data.List
s=sortOn.(length.)
f x|[c]<-nub x=[(c,"0")]|1<2=g[(a,[(a!!0,"")])|a<-group$sort x]
g=h.s fst
h[x]=snd x
h((a,b):(c,d):e)=g$(a++c,map('0'#)b++map('1'#)d):e
n#(a,b)=(a,n:b)
p=unlines.map(\(a,b)->a:" "++b).s snd.f
```
Usage example:
```
*Main> putStr $ p "this question is about huffman coding"
u 000
i 011
101
a 0010
f 0011
h 1000
s 1100
t 1101
n 1110
o 1111
d 01000
e 01001
b 01010
c 01011
q 10010
g 100110
m 100111
```
How it works:
`p` calls `f` which builds the Huffman table in the form of a list of (character,encoding)-pairs, e.g. `[ ('a',"0"), ('b',"1") ]`, sorts the table by length of encodings, formats each pair for output and joins with newlines in-between.
`f` first checks the single letter case and returns the corresponding table. Otherwise it sorts the input string and groups sequences of equal characters (e.g. `"ababa"` -> `["aaa","bb"]`) and maps them to pairs `(sequence , [(char, "")])`, (-> `[ ("aaa", [('a',"")]), ("bb", [('b', "")])]`. The first element is used to keep track of the frequency, the second element is a list of pairs of a character and it's encoding (which is initially empty). These are all single element Huffman tables as expected by `p` and are combined by `g` and `h`.
`g` sorts the list of pairs on the length of the first element, i.e. the frequency and calls `h`. `h` combines the Huffman tables of the first two elements, by concatenating the frequencies and putting a `0` (`1`) in front of every element of the first (second) table. Concatenate both tables. Call `g` again, stop when there's a single element left, throw away the frequency part and return the full Huffman table.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 78 bytes
```
{h::0#'x;(#1_){{h[x],:!2;y,,,/x}.0 2_x@<#'x}/.=x;(?,/'x,'" ",'|'$h)(?x)?>#'=x}
```
[Try it online!](https://tio.run/##DcpLDoIwEADQq4ytydBkBGRZxHoPYxA/pY2xxECTMcjZK7u3eK9d6ENKVs9O61Ii15nct2qe3ZkvpDdV/SWigpe8hKrl02EtS5E36zNUIBMKEIQ/3DqVGVbmKLHhJV1LbcXk/Aif@BwnPwRY3d2GOIGL1r67APfh4UMv6vQH "K (ngn/k) – Try It Online")
returns a list of strings for printing
`h::0#'x` creates an empty list for each character (technically, it reshapes each character to length 0). we will store the reversed huffman codes there. we use `::` instead of `:` for assignment to make `h` global so it's visible in sub-functions.
`.=x` is a list of lists - the indices of the string grouped by character value
`(#1_)` is a function that returns truthy iff the length of the argument is >1 (technically "length of 1 drop of ...")
`(#1_){`...`}/` means: while the argument has length >1, keep applying the curly-brace function
`x@<#'x` sort the argument by length
`0 2_` cut it into a 2-element head and a tail
`{h[x],:!2;y,,,/x}` update `h` by appending 0 and 1 to the indices contained in the head; return the tail with the head as a single element
`(?,/'x,'" ",'|'$h)(?x)?>#'=x` reverse each of `h`, sort, unique, prepend corresponding characters, and format nicely
[Answer]
# JavaScript (ES6) 279
Essentially, the basic algorithm from Wikipedia. I probably can do better.
```
f=s=>{for(n=[...new Set(s)].map(c=>({c:c,f:[...s].filter(x=>x==c).length}));n[1];n.push({l:a=n.pop(),r:b=n.pop(),f:a.f+b.f,c:a.c+b.c}))n.sort((a,b)=>b.f-a.f);t=(n,b)=>(n.b=b,n.r)?(t(n.l,b+0),t(n.r,b+1)):o.push(n);t(n[0],'',o=[]);return o.sort((a,b)=>b.f-a.f).map(x=>x.c+' '+x.b)}
```
More readable inside the snippet below
```
f=s=>{
for(n=[...new Set(s)].map(c=>({c:c,f:[...s].filter(x=>x==c).length}));
n[1];
n.push({l:a=n.pop(),r:b=n.pop(),f:a.f+b.f,c:a.c+b.c}))
n.sort((a,b)=>b.f-a.f);
t=(n,b)=>(n.b=b,n.r)?(t(n.l,b+0),t(n.r,b+1)):o.push(n);
t(n[0],'',o=[]);
return o.sort((a,b)=>b.f-a.f).map(x=>x.c+' '+x.b)
}
//TEST
console.log=x=>O.innerHTML+=x+'\n'
test=['xxxxxxxxy','uuvvwwxxyyzz','this question is about huffman coding']
.forEach(t=>console.log(t+'\n'+f(t).join`\n`+'\n'))
```
```
<pre id=O></pre>
```
] |
[Question]
[
# The Challenge
Implement [the Sundaram sieve](https://en.wikipedia.org/wiki/Sieve_of_Sundaram) for finding prime numbers below `n`. Take an input integer, `n`, and output the prime numbers below `n`. You can assume that `n` will always be less than or equal to one million.
---
# Sieve
1. Start with a list of the integers from `1` to `n`.
2. Remove all numbers that are in the form `i + j + 2ij` where:
* `i` and `j` are less than `n`. `j` is always greater than or equal to `i`, which is greater than or equal to `1`.

* `i + j + 2ij` is less than or equal to `n`

3. Multiply the remaining numbers by `2`, and add `1`.
This will yield all the prime numbers (except `2`, which should be included in your output) less than `2n + 2`.
---
Here is an animation of the sieve being used to find primes below `202`.

---
# Output
Your output should be every prime integer `≤ n` (in ascending order) followed by a newline:
```
2
3
5
```
Where `n` is `5`.
---
# Examples
```
> 10
2
3
5
7
> 30
2
3
5
7
11
13
17
19
23
29
```
Inputs are denoted by `>`.
[Answer]
# Pyth, 23 bytes
```
2j@JSQmhyd-Jm+sdy*Fd^J2
```
[Demonstration](https://pyth.herokuapp.com/?code=2j%40JSQmhyd-Jm%2Bsdy%2aFd%5EJ2&input=30&debug=0)
Really just implements the algorithm as given.
[Answer]
# Haskell, ~~93~~ 90 bytes
```
import Data.List
g n=unlines[show$2*x+1|r<-[[1..n]],x<-2:(r\\[i+j+2*i*j|j<-r,i<-r]),2*x<n]
```
How it works: `[i+j+2*i*j|j<-r,i<-r]` are all `i+j+2ij` which are removed (`\\`) from `[1..n]`. Scale to `2x+1` and turn them into a string (`show`). Join with NL (`unlines`).
[Answer]
# Scala, ~~115 124 122 115~~ 114 bytes
```
n=>{println(2);for{m<-1 to n;if !(for{j<-1 to n;i<-1 to j}yield i+j+2*i*j).contains(m);o=2*m+1;if o<=n}println(o)}
```
An anonymous function; takes n as an argument and prints the result to stdout.
[Answer]
# JavaScript (ES7), ~~107~~ 105 bytes
Array comprehensions are awesome! But I wonder why JS has no range syntax (e.g. `[1..n]`)...
```
n=>{for(a=[i=1];i<n;a[i++]=i);for(i=0;i++<n;)for(j=0;j<n;a[i+j+++2*i*j]=0);return[for(i of a)if(i)i*2+1]}
```
This was tested successfully in Firefox 40. Breakdown:
```
n=>{
for(a=[i=1];i<n;a[i++]=i); // fill a list with 1..n
for(i=0;i++<n;) // for each integer i in 0..n
for(j=0;j<n;) // for each integer j in 0..n
a[i+j+++2*i*j-1]=0; // set the corresponding item of the list to 0
return[for(i of a) // filter the list by:
if(i) // item != 0 AND item != undefined
i*2+1] // and return each result * 2 + 1
}
```
Alternative, ES6-friendly solution (111 bytes):
```
n=>{for(a=[i=1];i<n;a[i++]=i);for(i=0;i++<n;)for(j=0;j<n;a[i+j+++2*i*j]=0);return a.filter(x=>x).map(x=>x*2+1)}
```
Suggestions welcome!
[Answer]
# MATLAB, 98
```
n=1:input('');m=n;for p=m for i=1:p j=i:p;for k=i+j+2*i*j n(n==k)=[];end;end;end;disp(2*n'+1);
```
And in a readable form
```
n=1:input(''); %Ask for the input number (e.g. 100) and form a range
m=n; %Back up the range as we will be editing 'n', but need 'm' as a loop list
for p=m %For each number between 1 and n inclusive
for i=1:p %'i' is all numbers greater than or equal to 1 up to p
j=i:p; %'j' is all numbers greater than or equal to i up to p
for k=i+j+2*i*j %Calculate the numbers to remove, and loop through them
n(n==k)=[]; %Remove that value from the 'n' array
end
end
end
disp([2;2*n'+1]); %An display the list including the number 2 seperated by a new line.
```
[Answer]
# Java8 : ~~168~~ 165 bytes
```
N->{int[]A=new int[N*N];int i=1,j;N=N/2;for(;i<N;i++)for(j=i;j<N;)A[i+j+2*i*j++]=1;System.out.println(N>1?2:\"\");for(i=1;i<N;i++)if(A[i]<1)System.out.println(2*i+1);}
```
For more bigger number data type with wide range can be used. We do not need to iterate for whole `N` indexes `N/2` is sufficient.
To understand properly following is the equivalent method.
```
static void findPrimeSundar(int N){
int[] A = new int[N*N];
int i=1,j;
N=N/2;
for(;i<N;i++)
for(j=i;j<N;)
A[i+j+2*i*j++]=1;
System.out.println(N>1?2:"");
for(i=1;i<N;i++)
if(A[i]<1)System.out.println(2*i+ 1);
}
```
[Answer]
# CJam, 35 bytes
```
2li:V,:)__2m*{_:+\:*2*+}%m2f*:)&+N*
```
[Try it online](http://cjam.aditsu.net/#code=2li%3AV%2C%3A)__2m*%7B_%3A%2B%5C%3A*2*%2B%7D%25m2f*%3A)%26%2BN*&input=30)
This seems somewhat lengthy relative to isaacg's Pyth solution, but it's... what I have.
Explanation:
```
2 Push a 2, will be part of final output.
li Get input and convert to integer n.
:V Save in variable V for later use.
, Generate list [0 ... n-1].
:) Increment list elements to get list [1 ... n].
__ Create two copies, one for sieve, and for clamping results.
2m* Cartesian power, generating all i,k pairs.
{ Loop over all i,j pairs.
_ Copy pair.
:+ Calculate sum i + j.
\ Swap copy of pair to top.
:* Calculate product i * j.
2* Multiply by 2, to get 2 * i * j.
+ Add both values, to get i + j + 2 * i * j.
}% End loop over all i,j pairs.
m Sieve operation, remove the calculated values from the list of all values.
2f* Multiply the remaining values by 2...
:) ... and add 1 to the. We now have the list of all primes up to 2 * n + 2.
& Intersect with [1 ... n] list, because output is only values <= n.
+ Concatenate with the 2 we pushed at the start.
N* Join with newlines.
```
[Answer]
## [Perl 6](http://perl6.org), 96 bytes
If I strictly follow the description the shortest I managed to get is 96 bytes.
```
->\n {$_=@=1..n;for 1..n {for $^i..n {.[$i+$^j+2*$i*$j-1]=0}};2,|.[0..n].map(* *2+1).grep(3..n)}
```
```
->\n {
$_=@=1..n; # initialize array
for 1..n { # $i
for $^i..n { # $j
.[$i+$^j+2*$i*$j-1]=0 # remove value
}
};
2,|.[0..n].map(* *2+1).grep(3..n)
}
```
---
If I could do the `2n + 1` on initialization of the array, pre-inserting `2`, and limiting that to only the values less than or equal to `n`; it can be reduced to 84 bytes.
```
->\n {$_=@=2,{++$*2+1}...^*>n;for 1..n {for $^i..n {.[$i+$^j+2*$i*$j]=$}};.grep(?*)}
```
If I also ignore that `j` is supposed to be at least `i`, I can reduce it to 82 bytes.
```
->\n {$_=@=2,{++$*2+1}...^*>n;for 1..n X 1..n ->(\i,\j){.[i+j+2*i*j]=$};.grep(?*)}
```
---
Example usage:
```
my $code = ->\n {...} # insert one of the lambdas from above
say $code(30).join(',');
# 2,3,5,7,11,13,17,19,23,29
my &code = $code;
say code 11;
# (2 3 5 7 11)
```
[Answer]
# PHP, 126 Bytes
```
$r=range(1,$n=$argn/2-1);for(;++$i**2<=$n;)for($j=$i;$n>=$d=$j+$i+2*$i*$j++;)unset($r[$d-1]);foreach($r as$v)echo 1+2*$v."\n";
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/909649282e811fabbb67640541d829efe447bbb4)
[Answer]
# [Julia 0.6](http://julialang.org/), 65 bytes
```
n->[2;(p=setdiff(1:n,[i+j+2i*j for i=1:n for j=i:n])*2+1)[p.<=n]]
```
[Try it online!](https://tio.run/##Hck9DsIwDEDhPafwaDcBNUEwFMxFogxIrSVHlYlKOX/42Z6@V9@rPi5dgKHb4Z7TFRu/ln1WEYyThay@@qRDBXluoPy1f1XWyQoNyUfK7XhjK6X/hoEa4DlAHAOcRnIAbVPbV0NBI3KLza5/AA "Julia 0.6 – Try It Online")
Not a great challenge in terms of golfing, but I just had to do it for the name. :)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 24 bytes
```
¶↑≤¹:2m+1mDṠ-om§+oDΠΣπ2ḣ
```
[Try it online!](https://tio.run/##ATEAzv9odXNr///CtuKGkeKJpMK5OjJtKzFtROG5oC1vbcKnK29EzqDOo8@AMuG4o////zMw "Husk – Try It Online")
Ok, I'm not sure why increment `→` isn't working properly here. Once that works, this will be 23 (tied with Pyth).
] |
[Question]
[
## Background
A binary [Hankel matrix](http://en.wikipedia.org/wiki/Hankel_matrix) is a matrix with constant skew-diagonals (positive sloping diagonals) containing only `0`s and `1`s. E.g. a 5x5 binary Hankel matrix looks like
```
a b c d e
b c d e f
c d e f g
d e f g h
e f g h i
```
where `a, b, c, d, e, f, g, h, i` are either `0` or `1`.
Let's define a matrix **M** as **Hankelable** if there is a permutation of the order of rows and columns of **M** so that **M** is a Hankel matrix. This means one can apply one permutation to the order of the rows and a possibly different one to the columns.
## The Challenge
The challenge is to count how many *Hankelable* `n` by `n` matrices there are for all `n` up to as large a value as possible.
### Output
For each integer n from 1 upwards, output the number of *Hankelable* `n` by `n` matrices with entries which are `0` or `1`.
For `n = 1,2,3,4,5` the answers should be `2,12,230,12076,1446672`. (Thanks to orlp for the code to produce these.)
### Time limit
I will run your code on my machine and stop it after 1 minute. The code that outputs the correct answers up to the largest value of n wins. The time limit is for everything from `n = 1` to the biggest value of `n` for which you give an answer.
The winner will be the best answer by the end of Saturday 18 April.
### Tie Breaker
In the case of a tie for some maximum `n` I will time how long it takes to give the outputs up to `n+1` and the quickest one wins. In the case that they run in the same time to within a second up to `n+1`, the first submission wins.
### Languages and libraries
You can use any language which has a freely available compiler/interpreter/etc. for Linux and any libraries which are also freely available for Linux.
### My machine
The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor on an Asus M5A78L-M/USB3 Motherboard (Socket AM3+, 8GB DDR3). This also means I need to be able to run your code. As a consequence, only use easily available free software and please include full instructions how to compile and run your code.
### Notes
I recommend against iterating over all n by n matrices and trying to detect if each one has the property I describe. First, there are too many and second, there seems to be [no quick way to do this detection](https://stackoverflow.com/questions/29484864/an-algorithm-to-detect-permutations-of-hankel-matrices).
**Leading entries so far**
* n = 8 by Peter Taylor. **Java**
* n = 5 by orlp. **Python**
[Answer]
## Java (n=8)
```
import java.util.*;
import java.util.concurrent.*;
public class HankelCombinatorics {
public static final int NUM_THREADS = 8;
private static final int[] FACT = new int[13];
static {
FACT[0] = 1;
for (int i = 1; i < FACT.length; i++) FACT[i] = i * FACT[i-1];
}
public static void main(String[] args) {
long prevElapsed = 0, start = System.nanoTime();
for (int i = 1; i < 12; i++) {
long count = count(i), elapsed = System.nanoTime() - start;
System.out.format("%d in %dms, total elapsed %dms\n", count, (elapsed - prevElapsed) / 1000000, elapsed / 1000000);
prevElapsed = elapsed;
}
}
@SuppressWarnings("unchecked")
private static long count(int n) {
int[][] perms = new int[FACT[n]][];
genPermsInner(0, 0, new int[n], perms, 0);
// We partition by canonical representation of the row sum multiset, discarding any with a density > 50%.
Map<CanonicalMatrix, Map<CanonicalMatrix, Integer>> part = new HashMap<CanonicalMatrix, Map<CanonicalMatrix, Integer>>();
for (int m = 0; m < 1 << (2*n-1); m++) {
int density = 0;
int[] key = new int[n];
for (int i = 0; i < n; i++) {
key[i] = Integer.bitCount((m >> i) & ((1 << n) - 1));
density += key[i];
}
if (2 * density <= n * n) {
CanonicalMatrix _key = new CanonicalMatrix(key);
Map<CanonicalMatrix, Integer> map = part.get(_key);
if (map == null) part.put(_key, map = new HashMap<CanonicalMatrix, Integer>());
map.put(new CanonicalMatrix(m, perms[0]), m);
}
}
List<Job> jobs = new ArrayList<Job>();
ExecutorService pool = Executors.newFixedThreadPool(NUM_THREADS);
for (Map.Entry<CanonicalMatrix, Map<CanonicalMatrix, Integer>> e : part.entrySet()) {
Job job = new Job(n, perms, e.getKey().sum() << 1 == n * n ? 0 : 1, e.getValue());
jobs.add(job);
pool.execute(job);
}
pool.shutdown();
try {
pool.awaitTermination(1, TimeUnit.DAYS); // i.e. until it's finished - inaccurate results are useless
}
catch (InterruptedException ie) {
throw new IllegalStateException(ie);
}
long total = 0;
for (Job job : jobs) total += job.subtotal;
return total;
}
private static int genPermsInner(int idx, int usedMask, int[] a, int[][] perms, int off) {
if (idx == a.length) perms[off++] = a.clone();
else for (int i = 0; i < a.length; i++) {
int m = 1 << (a[idx] = i);
if ((usedMask & m) == 0) off = genPermsInner(idx+1, usedMask | m, a, perms, off);
}
return off;
}
static class Job implements Runnable {
private volatile long subtotal = 0;
private final int n;
private final int[][] perms;
private final int shift;
private final Map<CanonicalMatrix, Integer> unseen;
public Job(int n, int[][] perms, int shift, Map<CanonicalMatrix, Integer> unseen) {
this.n = n;
this.perms = perms;
this.shift = shift;
this.unseen = unseen;
}
public void run() {
long result = 0;
int[][] perms = this.perms;
Map<CanonicalMatrix, Integer> unseen = this.unseen;
while (!unseen.isEmpty()) {
int m = unseen.values().iterator().next();
Set<CanonicalMatrix> equiv = new HashSet<CanonicalMatrix>();
for (int[] perm : perms) {
CanonicalMatrix canonical = new CanonicalMatrix(m, perm);
if (equiv.add(canonical)) {
result += canonical.weight() << shift;
unseen.remove(canonical);
}
}
}
subtotal = result;
}
}
static class CanonicalMatrix {
private final int[] a;
private final int hash;
public CanonicalMatrix(int m, int[] r) {
this(permuteRows(m, r));
}
public CanonicalMatrix(int[] a) {
this.a = a;
Arrays.sort(a);
int h = 0;
for (int i : a) h = h * 37 + i;
hash = h;
}
private static int[] permuteRows(int m, int[] perm) {
int[] cols = new int[perm.length];
for (int i = 0; i < perm.length; i++) {
for (int j = 0; j < cols.length; j++) cols[j] |= ((m >> (perm[i] + j)) & 1L) << i;
}
return cols;
}
public int sum() {
int sum = 0;
for (int i : a) sum += i;
return sum;
}
public int weight() {
int prev = -1, count = 0, weight = FACT[a.length];
for (int col : a) {
if (col == prev) weight /= ++count;
else {
prev = col;
count = 1;
}
}
return weight;
}
@Override public boolean equals(Object obj) {
// Deliberately unsuitable for general-purpose use, but helps catch bugs faster.
CanonicalMatrix that = (CanonicalMatrix)obj;
for (int i = 0; i < a.length; i++) {
if (a[i] != that.a[i]) return false;
}
return true;
}
@Override public int hashCode() {
return hash;
}
}
}
```
Save as `HankelCombinatorics.java`, compile as `javac HankelCombinatorics.java`, run as `java -Xmx2G HankelCombinatorics`.
With `NUM_THREADS = 4` on my quad-core machine it gets `20420819767436` for `n=8` in 50 to 55 seconds elapsed, with a fair amount of variability between runs; I expect that it should easily manage the same on your octa-core machine but will take an hour or more to get `n=9`.
### How it works
Given `n`, there are `2^(2n-1)` binary `n`x`n` Hankel matrices. The rows can be permuted in `n!` ways, and the columns in `n!` ways. All we need to do is to avoid double-counting...
If you calculate the sum of each row, then neither permuting the rows nor permuting the columns changes the multiset of sums. E.g.
```
0 1 1 0 1
1 1 0 1 0
1 0 1 0 0
0 1 0 0 1
1 0 0 1 0
```
has row sum multiset `{3, 3, 2, 2, 2}`, and so do all Hankelable matrices derived from it. This means that we can group the Hankel matrices by these row sum multisets and then handle each group independently, exploiting multiple processor cores.
There's also an exploitable symmetry: the matrices with more zeroes than ones are in bijection with the matrices with more ones than zeroes.
Double-counting occurs when Hankel matrix `M_1` with row permutation `r_1` and column permutation `c_1` matches Hankel matrix `M_2` with row permutation `r_2` and column permutation `c_2` (with up to two but not all three of `M_1 = M_2`, `r_1 = r_2`, `c_1 = c_2`). The row and column permutations are independent, so if we apply row permutation `r_1` to `M_1` and row permutation `r_2` to `M_2`, the columns *as multisets* must be equal. So for each group, I calculate all of the column multisets obtained by applying a row permutation to a matrix in the group. The easy way to get a canonical representation of the multisets is to sort the columns, and that is also useful in the next step.
Having obtained the distinct column multisets, we need to find how many of the `n!` permutations of each are unique. At this point, double-counting can only occur if a given column multiset has duplicate columns: what we need to do is to count the number of occurrences of each distinct column in the multiset and then calculate the corresponding multinomial coefficient. Since the columns are sorted, it's easy to do the count.
Finally we add them all up.
The asymptotic complexity isn't trivial to calculate to full precision, because we need to make some assumptions about the sets. We evaluate on the order of `2^(2n-2) n!` column multisets, taking `n^2 ln n` time for each (including the sorting); if grouping doesn't take more than a `ln n` factor, we have time complexity `Theta(4^n n! n^2 ln n)`. But since the exponential factors completely dominate the polynomial ones, it's `Theta(4^n n!) = Theta((4n/e)^n)`.
[Answer]
# Python2/3
Pretty naive approach, in a slow language:
```
import itertools
def permute_rows(m):
for perm in itertools.permutations(m):
yield perm
def permute_columns(m):
T = zip(*m)
for perm in itertools.permutations(T):
yield zip(*perm)
N = 1
while True:
base_template = ["abcdefghijklmnopqrstuvwxyz"[i:i+N] for i in range(N)]
templates = set()
for c in permute_rows(base_template):
for m in permute_columns(c):
templates.add("".join("".join(row) for row in m))
def possibs(free, templates):
if free == 2*N - 1:
return set(int(t, 2) for t in templates)
s = set()
for b in "01":
new_templates = set(t.replace("abcdefghijklmnopqrstuvwxyz"[free], b) for t in templates)
s |= possibs(free + 1, new_templates)
return s
print(len(possibs(0, templates)))
N += 1
```
Run by typing `python script.py`.
[Answer]
# Haskell
```
import Data.List
import Data.Hashable
import Control.Parallel.Strategies
import Control.Parallel
import qualified Data.HashSet as S
main = mapM putStrLn $ map (show.countHankellable) [1..]
a§b=[a!!i|i<-b]
hashNub :: (Hashable a, Eq a) => [a] -> [a]
hashNub l = go S.empty l
where
go _ [] = []
go s (x:xs) = if x `S.member` s then go s xs
else x : go (S.insert x s) xs
pmap = parMap rseq
makeMatrix :: Int->[Bool]->[[Bool]]
makeMatrix n vars = [vars§[i..i+n-1]|i<-[0..n-1]]
countHankellable :: Int -> Int
countHankellable n = let
s = permutations [0..n-1]
conjugates m = concat[permutations[r§q|r<-m]|q<-s]
variableSets = sequence [[True,False]|x<-[0..2*(n-1)]]
in
length.hashNub.concat.pmap (conjugates.makeMatrix n ) $ variableSets
```
Nowhere near as fast as Peter's - that's a pretty impressive setup he's got there! Now with much more code copied from the internet. Usage:
```
$ ghc -threaded hankell.hs
$ ./hankell
```
] |
[Question]
[
# Courier Ception
The program must accept any string as input and output an pixel image that shows the input string in Courier. All the letters that contain a 'hole' (like `abdegopqABDPQR` etc) that is surrounded by black pixels must be also filled black.
## Input
The Program must be able to accept any ASCII string as input. The input can be any way you want, as long as the program code itself does not have to change in order to accept a different input. (Except for e.g. the filename of the file that is to be read.) No standard loopholes. You can assume that each input contains at least one printable letter.
## Output
The output must be a black and white (no gray) pixel graphic that shows the string written in Courier (in black, background white), with the specified 'holes' filled. The fontsize of the whole string must be constant (that means no different scaling for each different letters) so that the full sized letters (e.g. `ABCDEFGHIJKLMNOPRSTUVWXYZ` but j and Q are bigger) must be at least 10px in height. (You do not have to write it to a file, any kind of display is ok as long as it is generated as pixelgraphics, as e.g. canvas in JavaScript.) Please post this graphic with your answer.
Access to courier.ttf / font libraries is allowed.
The program must as well count the number of black pixels and write it to console or what ever output method prefered in the end.
## Score
The score is evaluated as follows: The full program code must be used as input string to your program. The number of black pixels will be your score. **Program code that contains non-printable or non-ASCII letters is not allowed.** (As well as standard loopholes.) The lower the score the better.
[Answer]
## Mathematica, 4864 pixels
```
l = ImageData[Binarize[Rasterize[Style[j, FontSize -> 15]], .71]]
i = {{1, 1}}
While[Length[i] > 1 - 1,
{r, c} = j = i[[1]]; l[[r, c]] = 2; i = i[[2 ;; -1]];
If[FreeQ[i, {r, c} = J = j + #] && l[[r, c]] == 1,
i = i~Join~{J}] & /@
{{1, 1 - 1}, {1 - 1, 1}, {-1, 1 - 1}, {1 - 1, -1}}
]
Image[l = l /. 1 -> 1 - 1 /. 2 -> 1]
Count[l, 1 - 1, {2}]
```
Here is the picture:

In Mathematica when you write a "program" you just write a snippet. So this expects the input stored in `j` and the last thing it returns is the image and the count. This also spits out a bunch of errors, because I don't do bounds checking on `l`, but it produces the desired result anyway.
where `%` refers to said last output.
Thanks to Geobits for the idea for the algorithm. I'm flood-filling the image from the top-left corner with an invalid intensity, then I replace all remaining white pixels with black pixels, and the invalid ones with white ones.
Note that the `FreeQ` check isn't actually necessary for the program to work correctly, but for it to finish in a reasonable amount of time. If I'd leave it out, I'd actually score about 300 pixels less.
] |
[Question]
[
## Challenge:
A Frog List is defined by certain rules:
1. Each frog within a Frog List has an unique positive digit `[1-9]` as id (any `0` in a list is basically an empty spot, which can mostly be ignored).
2. A Frog List will always have *exactly one* Lazy Frog. A Lazy Frog will remain at its position.
3. Every other frog in a Frog List will jump at least once, and will always jump towards the right from its starting position.
4. When a frog jumps, the distance of its jump is always the same.
5. When a frog jumps, it will continue jumping until it's outside the list's right bound.
6. 0-1 jumping frogs can stand on top of a Lazy Frog, as long as their summed ids is still a single digit. (Jumping frogs cannot stand on top of one another! Which implicitly also means there cannot be two jumping frogs on a Lazy Frog simultaneously.)
Note that the frog-ids within a Frog List describe how a frog has already jumped *(past sense)*. Focusing on an individual frog-id within a Frog List shows how it has jumped, and at what positions within the Frog List it has landed, and jumped onward from - with the exception of the Lazy Frog, which hasn't moved.
Worked out explanation of the Frog List `[1,2,1,0,8,2]`:
1. The Lazy Frog has id \$\color{green}{7}\$ at position `~~~~7~`:
[](https://i.stack.imgur.com/kkyRi.png)
2. The first jumping frog has id \$\color{red}{1}\$ at positions `1~1~1~` with jump distance 2:
[](https://i.stack.imgur.com/L24I6.png)
3. The second jumping frog has id \$\color{blue}{2}\$ at positions `~2~~~2` with jump distance 4:
[](https://i.stack.imgur.com/DCxIp.png)
All three frogs summed gives the Frog List `[1,2,1,0,8,2]`, so `[1,2,1,0,8,2]` would be truthy:
[](https://i.stack.imgur.com/pmDQP.png)
### All Test cases including explanation:
```
Input Explanation:
```
**Truthy:**
```
[1,2,1,0,8,2] Lazy Frog 7 doesn't jump ~~~~7~
frog 1 jumps (with jumping distance 2) 1~1~1~
frog 2 jumps (with jumping distance 4) ~2~~~2
[1,0,0,0,0,1,2,7,2,2] Lazy Frog 5 doesn't jump ~~~~~~~5~~
frog 1 jumps (with jumping distance 5) 1~~~~1~~~~
frog 2 jumps (with jumping distance 1) ~~~~~~2222
[9,8,9,1] Lazy Frog 7 doesn't jump ~7~~
frog 1 jumps (with jumping distance 2) ~1~1
frog 9 jumps (with jumping distance 2) 9~9~
[1,0,1,3,3,3,1] Lazy Frog 2 doesn't jump ~~~~2~~
frog 1 jumps (with jumping distance 2) 1~1~1~1
frog 3 jumps (with jumping distance 2) ~~~3~3~
(Note that the 3 at ~~~~3~~ is Lazy Frog 2 and jumping frog 1 on top of one another,
and not jumping frog 3!)
[7] A single Lazy Frog 7
[7,0,0,0] A single Lazy Frog 7~~~
[8,1,1] Lazy Frog 8 doesn't jump 8~~
frog 1 jumps (with jumping distance 1) ~11
OR alternatively:
Lazy Frog 7 doesn't jump 7~~
frog 1 jumps (with jumping distance 1) 111
```
**Falsey:**
```
[1,2,3,0,2,1,3] (rule 2) there is no Lazy Frog: 1~~~~1~
~2~~2~~
~~3~~~3
[1,6,1,8,6,1] (rule 4) frog 1 jumps irregular 1~1~~1 / 1~11~1
~6~~6~ / ~6~~6~
~~~8~~ / ~~~7~~
[2,8,2,8,0,9] (rule 5) frog 2 stopped jumping 2~2~~~
~~~~~1
~8~8~8
[1,2,3,2,7] (rule 6) two jumping frogs at the last position with: 1~~~1
~2~2~
~~3~3
(Lazy)~~~~4
^
OR two jumping frogs at the third and last positions with: 1~1~1
~2222
(Lazy)~~~~4
^ ^
[2,1] (rule 2+3) There are two Lazy Frogs without jumping frogs: ~1
2~
OR (rule 1) The Lazy and jumping frog would both have id=1: 11
1~
```
Here are all Frog Lists (as integers) of 3 or less digits:
```
[1,2,3,4,5,6,7,8,9,10,13,14,15,16,17,18,19,20,23,25,26,27,28,29,30,31,32,34,35,37,38,39,40,41,43,45,46,47,49,50,51,52,53,54,56,57,58,59,60,61,62,64,65,67,68,69,70,71,72,73,74,75,76,78,79,80,81,82,83,85,86,87,89,90,91,92,93,94,95,96,97,98,100,103,104,105,106,107,108,109,113,114,115,116,117,118,119,121,122,131,133,141,144,151,155,161,166,171,177,181,188,191,199,200,203,205,206,207,208,209,211,212,223,225,226,227,228,229,232,233,242,244,252,255,262,266,272,277,282,288,292,299,300,301,302,304,305,307,308,309,311,313,322,323,334,335,337,338,339,343,344,353,355,363,366,373,377,383,388,393,399,400,401,403,405,406,407,409,411,414,422,424,433,434,445,446,447,449,454,455,464,466,474,477,484,488,494,499,500,501,502,503,504,506,507,508,509,511,515,522,525,533,535,544,545,556,557,558,559,565,566,575,577,585,588,595,599,600,601,602,604,605,607,608,609,611,616,622,626,633,636,644,646,655,656,667,668,669,676,677,686,688,696,699,700,701,702,703,704,705,706,708,709,711,717,722,727,733,737,744,747,755,757,766,767,778,779,787,788,797,799,800,801,802,803,805,806,807,809,811,818,822,828,833,838,844,848,855,858,866,868,877,878,889,898,899,900,901,902,903,904,905,906,907,908,911,919,922,929,933,939,944,949,955,959,966,969,977,979,988,989]
```
## Challenge rules:
* The integers in the input-list are guaranteed to be \$0\leq n\leq9\$ (aka single digits).
* Any single-value inputs are Frog List, since they'll contain a single Lazy Frog and no jumping frogs.
* I/O is flexible. You may take the input as a list/array/stream of digits,
an integer, a string, etc. You may output any two values or type of values (not necessarily distinct) to indicate truthy/falsey respectively.
* You can assume a Frog List will never start with a `0` (doesn't matter too much for list I/O, but can be for integer I/O).
## 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.
[Answer]
# Python3, 498 bytes:
```
E=enumerate
def V(x,l):r=len(K:=set({x[i+1]-a for i,a in E(x)if i+1<len(x)}));return r==1and max(x)+max(K)>=len(l)
T=lambda x:[*filter(None,x)]
P=sorted
def f(l):
if len(T(l))==1:return 1
q=[(l,T({*l[:i]+l[i+1:]}),i,a,[])for i,a in E(l)if a>1]
while q:
L,s,I,o,C=q.pop(0)
if[]==s and o-sum(C)not in l and o-sum(C)and C:return 1
if[]==s:continue
S,*s=s
U=[i for i,a in E(l)if a==S and i!=I]
if len(U)>1and V(P(U),l):q+=[(L,s,I,o,C)]
if V(P(U+[I]),l)and len(C)<1:q+=[(L,s,I,o,C+[S])]
```
[Try it online!](https://tio.run/##bVFBbtswELzrFewpXGtdSDLQ2Groi5GDkaIIYCcXgge1phACNCVTNKoiyNvdpeoWlhMQlJazM8NZqf0dXho3m7f@dLoX2h332ldBJztds2feo4XSC6sdfyhFpwN/7aVJczWtWN14ZrBixrF73oOpGTXuIrWHN4CvXoejd8wLkVdux/ZVT400vh5gOVhaSLbCVvsfu4r1pZzUxgbt@ffGaexBJY@ia3zQuyFMTfQyYXRNlG7pBORcnm/JE3YQklvc8teJlaVRqY1BS/UGSClRKhgFtjFwtcxVwn69GKvZgczZN@xwjQ2uxOFz27Q8AwJNLZUQHYtTNNPuuOcrcE2IPnYExnp1keifsvzZuGDcURO0wUknOiqehDTsg0hCbAZT80ms1eAxDPwEy@EzPvNHquNvOaQ08P/AcOYO/VSuVeREQRSv4C6/4qdyo0CdWm9c4DWXORaYY4ZzLBRAcoFn5xUZt7TH/QUpFpi/0@Q4G9a4czs@/XUeYXNSXmhupjeTIht5F@SaDWlnV7d@IWwenyO8iDPRznBxxY9ONNMVO6pPfwA)
[Answer]
# [Haskell](https://www.haskell.org) + [hgl](https://www.gitlab.com/WheatWizard/haskell-golfing-library), 141 bytes
```
g k(x:y)=lq x<>mL1 x<>k?<fo y
f x=or[fo[ay(g k<tx<fue(dW(k/=)y)<sA)$dpH y|k<-y,k>0]|y<-[i++q:k|(i,j:k)<-fsA**<dph$x,q<-e0$j-1,(j-q)?<x||1>q]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZK_asMwEMaho5_iBkOlRGptpzSpkROytdAhWwfjwWCpceTEf2KDBX6FPkGXLKXPlD5N5bpDGlDKcSe43-m7D6T3z3W8lzzLDsebdFvkVQ1lE2epSHkCq4pnTcKtX7CyRMMhAHENTcM_mlrQ2fHtFSRqfYWDrISWzbfPbn_IBRM5KEtAG-RVKPIwVkiPsrplWgUlL0jeBlhhtl9iOykeQXWSUUXk3Ik6xWiYjselLzuUko0vMaNivxyNWFKs7ZaUjHLH3lCXoA0t8YK1XefOyygaTH1dkW2c7rTVJLcAigpsEIDCaQS-D-HTro7wad819KfE6cN0a6A6XOKRqU7PMOmRO00nRuqQyV_6d41J1mzMOxc8p0YrP2YuULNuz8zKgydHV_fCzL2ms74ad8xInw55uLhHP8c__PT-8GkOh-H8Bg)
*Euch*, this seems *long*. There's probably a better way to do this, and there's probably a lot of little things here I could tweak to improve it. But the spec turned out to be a lot more intricate and have a lot more edge cases than I had thought and I'm just glad to be done.
# Explanation
First we find all the ways to split the list into two chunks
```
(i,j:k)<-fsA**<dph$x
```
We filter out cases where the element we are splitting is `0`
```
j>0
```
Then we get all number strictly less than `j`. This will give us the id number for the lazy frog.
```
q<-e0$j-1
```
Now we replace the lazy frog with `q`.
```
i++q:k
```
Now we confirm that one of the possible combinations of lazy frog and replacement yields a solution. To check solutions we are going to check that every frog in the list can jump to the right.
So we enumerate every frog in the list:
```
k<-y,k>0
```
This has duplicates, but I don't care. For each frog we drop everything off the front of the list until that frog is at the front itself.
```
dW(k/=)y
```
Then for each number \$n\$ from one to the length of the list, we split the trimmed list into chunks of size \$n\$.
```
fue(dW(k/=)y)<sA)$dpH y
```
Now we transpose the list with `tx`. With the transposed list we want to check the following conditions:
* The first piece contains only one type of element (must be the frog we are looking at since it is the first element of the trimmed list) `lq x`
* The first piece contains at least two elements (so the frog jumps at least twice) `mL1 x`
* The frog cannot occur in other pieces `k?<fo y`
If the split list satisfies these conditions for any way to divide it, then that frog is good. If all frogs in the modified list satisfy this then the substitution is good. If any substitution of the lazy frog for a non-lazy frog is good, then the whole list is valid.
# Reflection
There are a lot of things here that could be improved. A few come to mind immediately but I will probably add to this list as I ruminate on this.
* I shouldn't have to do `ic[j]`. I really thought I had already made a function which intercalates elements with lists. But it seems either I didn't or I can't find it.
* There should be a way to replace every instance of one element with another element.
* I could swear there used to be a "is x a prefix of y" function. But I cannot find it. It would be useful here
* There should be a way to get all partitions of a specific size. *And* there should be a function which gives all ways to split a list in two (as tuples).
* `tx` could be a pattern here. It would be one of the rare times in which a pattern would actually save bytes
* There should be a built in for breaking a list into chunks of a certain size. `uue<sA` is short, but it could be much shorter.
* I discovered `eL` is broken. I didn't need to use it but it should be fixed. Also there should be some pre-composed functions here with `eL2`, `eL3` etc.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~39~~ 35 bytes
```
Ḷ⁹¦Ẏ€ŒpɗⱮTẎḟƑ_ƒ¥ƇSẹⱮ¹ƇfƑJmÐƤ`ẎIƇƲƲƇ
```
[Try it online!](https://tio.run/##RU2xDgFBEP0VxZVT3K6Eu15DSyMXoaGQk2iVNNsJ19BpUCGh4PbKu5jwGXs/smZ3ibzM5M17b2bGwzieaa3SezmX@VFly3JxeibT96a8Xjo0qnSH6z4m@QFFW2WS5FyiGOG6NSlWuB9QpokCbwShXw@61CiEh@KZKLlV8lw45tHdrtYRAw4MfAiA96ASGepgjDqVlUPyQ2C/BIOqhRXqtrktQwOyv0lOGd8@qDqhRjQw3YzcPKXyIfzH6anzWO8D "Jelly – Try It Online")
Takes an integer list as input, and outputs a list of all valid ways to ignore the Lazy Frog--falsy if empty.
Generate every candidate:
```
Ḷ⁹¦Ẏ€ŒpɗⱮTẎḟƑ_ƒ¥ƇS
ɗⱮT For every index with any frogs:
Ḷ⁹¦ Replace the frog(s) at that index with [0 .. id),
Ẏ€ wrap all other elements in singleton lists,
Œp and compute the Cartesian product of all of them.
Ẏ Join the results into a single list of candidates.
Ƈ Filter the candidates to those which
ḟƑ do not contain
_Ĵ the difference between their sum and
S the input's sum
_Ĵ S (i.e., the Lazy Frog's ID).
```
Filter (`ƲƇ`) to those with valid jumping frogs:
```
ẹⱮ¹ƇfƑJmÐƤ`ẎIƇƲ
J ÐƤ For every suffix of [1 .. len(input)],
m drop all but every n'th element, where n is
J ` each of [1 .. len(input)].
Ẏ Join the results,
IƇ and filter to those with multiple elements.
Ɱ¹Ƈ For every frog in the candidate,
ẹ get the list of all of its indices in the candidate.
fƑ Ʋ Is every element of that list an element of the other list?
```
This took me an hour and a half to write on my phone and it didn't even work lmao
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~68~~ 67 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εLã€êDOyQÏ}JŻ‘}θ€€SʒU9LεXQ€à0ÛDVεYNÅ0«Ćƶ0K¥Ë}à}þ`y˜0KD¢ΘOy€g2¢!P
```
Twice as long as the Jelly answer, but figured I'd post my own (now mostly golfed) reference implementation. A different approach is likely much shorter, though.
-1 byte by including duplicates in the truthy outputs.
Input as an integer; output as a list of list of ids for truthy cases (may contain duplicates) and an empty list for falsey cases.
[Try it online](https://tio.run/##yy9OTMpM/f//3Fafw4sfNa05vMrFvzLwcH@t1@HWQ7sPLwIKnZ5Te24HkAai4FOTDq08vMDn3NZD6wJBqhcYHJ7tEnZua6Tf4VaDQ6uPtB3bZuB9aOnh7trDC2oP70uoPD3HwNvl0KJzM/wrgerTjQ4tUgz4/9/QyNDAwggA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1t9Di9@1LTm8CoX/8rAw/21XodbD@0@vAgodHpO7bkdQBqIgk9NOrTy8AKfc1sPrQsEqV5gcHi2S9i5rZF@h1sNDq0@0nZsm4H3oaWHu2sPL6g9vC@h8vQcA2@XQ4vOzfCvBKpPNzq0SDHgf@3h9Tr/ow2NDA0sjHQMDYDA0MjcyEjH0sLSEMg3NDY2NtQx1zEHSuhYGBrqKBgaGRsYGRrrGJoZWpgZ6hhZGFkYWOoARY3MdYwMYwE).
**Explanation:**
Step 1: Convert each digit of the input to a list of potential 1 or 2 frogs:
```
ε # Map over each digit of the (implicit) input-integer:
L # Convert it to a list in the range [1,digit]
ã # Get the cartesian power of itself to create pairs
€ # Inner map over each pair:
ê # Uniquify and sort each pair
D # Duplicate this list
O # Sum each inner list
yQ # Check which are equal to the current digit
D Ï # Keep the singulars/pairs which sum to the digit
} # Close the map
```
[Try just the first step.](https://tio.run/##yy9OTMpM/f//3Fafw4sfNa05vMrFvzLwcH/t//@GRoYGFkYA)
Step 2: Reduce it by the cartesian product to create all possible result-lists (for which 05AB1E unfortunately lacks a builtin):
```
J # Join each inner singular/pair together
Å» # Left-reduce it by (unfortunately keeping all intermediate results)
â # Take the cartesian product of the current two lists to create pairs
€˜ # Flatten each inner list
}θ # After the reduce (with intermediate results), keep the last
€ # Map over each inner list:
€ # Inner map over each integer:
S # Convert it back to a singular digit/pair of digits
```
[Try the first two steps.](https://tio.run/##yy9OTMpM/f//3Fafw4sfNa05vMrFvzLwcH@t1@HWQ7sPLwIKnZ5Te24HkAai4P//DY0MDSyMAA)
Step 3: Filter and output the result:
```
ʒ # Start filtering this list by:
```
Step 3a: Verify rules 4 (the jump distance of jumping frogs is always the same) and 5 (will go outside the list's right bound):
```
U # Pop and store the current list in variable `X`
9L # Push a list in the range [1,9]
ε # Map over this list of potential frog-ids:
X # Push list `X`
Q # Check which inner digits are equal to the current potential frog-id
ۈ # Any on each (for the pairs)
0Û # Trim all leading 0s
DVεY # Duplicate this list its length amount of times as list
ε # Inner map over each of these lists:
NÅ0 # Push a list with the 0-based index amount of 0s
« # Append it to the list
Ć # Enclose; append its own head
ƶ # Multiply each inner 0/1 by its 1-based index
0K # Remove all 0s
¥ # Get the deltas/forward-differences
Ë # Check if all of them are equal
}à # After the inner map: check if any was truthy
}þ # After the outer map: remove all empty strings (for the non-occurring frog-ids)
` # Pop and push all checks to the stack
```
Step 3b: Verify rule 2 (there is exactly one Lazy Frog):
```
y # Push the current list we're filtering again
˜ # Flatten it to a single list of digits
0K # Remove all 0s
D¢ # For each digit, count how many times it occurs
Θ # Check for each count whether it's equal to 1
O # Sum them together to get the amount of Lazy Frogs
```
Step 3c: Verify rule 6 (there cannot be two jumping frogs on top of one another):
```
y # Push the current list we're filtering for a third time
€g # Get the length of each inner list
2¢ # Count the amount of 2s (amount of pairs of frog-ids)
! # Faculty to check it's either 0 or 1
```
Step 3d: Combine all checks, and output the result:
```
P # Get the product of all values on the stack
# (note: only 1 is truthy in 05AB1E)
# (output the filtered result)
```
] |
[Question]
[
This is a Cops and Robbers challenge. For the Robbers' thread, go [here](https://codegolf.stackexchange.com/q/166340/42963).
The Cops have three tasks.
1) Pick a sequence from the [OEIS](https://oeis.org).
2) Pick a language (this is suggested to be a golflang, but doesn't have to be) that, when given input `n`, outputs `A(n)` (where `A(n)` is the sequence chosen) using all usual [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules.
Call this language **LA** and code **CA**.
For example, *Jelly* and *Jelly\_code*.
3) Then, pick a different language (this is suggested to be a non-golflang, but doesn't have to be) and write code that takes no input and outputs code **CA**, again following all usual [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules. (Note: this can be obfuscated code and doesn't necessarily need to be golfed, but the longer this code is the easier it will be for the robbers to crack your submission.)
Call this language **LB** and code **CB**.
For example, *Python* and *Python\_code*.
**The Cop's submission to this challenge** is the sequence (specified whether 0- or 1-indexed), the name of the two languages **LA** and **LB** (and which one solves which part), and the byte-count of **CB** only. Keep the actual code of both parts, and the length of **CA**, secret.
For the Cop, links to documentation for **LA** and **LB**, or an interpreter (or a TIO link, since that includes both), are appreciated but not required.
The Robber's challenge is to select a Cops' entry and write code **CC** in the same **LB** language that outputs *some* code in the same **LA** language that solves the original OEIS task. The length of **CC** can be no longer than the length of **CB** as revealed by the cop (though may be shorter). Note: The code produced by **CC** does *not* have to match **CA**.
For our example, this means that the Robber has to write *Python* code that outputs *Jelly* code that solves the original OEIS sequence, and that *Python* code has to be no longer than the length revealed by the Cop.
### Winning conditions
Answers that have not been cracked in a week can have their solutions revealed, at which point they are considered *Safe*. Note that if you don't reveal your solution after a week, it can still be cracked. The Cop with the shortest *Safe* answer wins.
[Answer]
# [OEIS A000041](https://oeis.org/A000041), [cracked](https://codegolf.stackexchange.com/a/166384/58563) by [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)
Let's try it the other way around: golflang generates non-golflang.
>
> ***a(n)** = number of partitions of **n** (the partition numbers).*
>
>
>
* **a(n)** (0-indexed) is returned by a **JavaScript** function (ES6)
* The program that outputs the JS function is written in [**Jelly**](https://github.com/DennisMitchell/jelly)
* The length of the Jelly program is **35 bytes**
## Intended solution
>
> Jelly: `“¦ṚoIwƭ- ḊFæSḂ¥¶Ẉ|ḊJƓƝʋnrB⁾’b28+40Ọ`
>
>
>
>
> which outputs
>
>
>
>
> JS: `C=(A,B=A)=>A<0?0:A?B?C(A,B-1)+C(A-B,B):0:1`
>
>
>
[Answer]
# [OEIS A048272](https://oeis.org/A048272), [cracked](https://codegolf.stackexchange.com/a/166362/31716) by [DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem)
>
> Number of odd divisors of **n** minus number of even divisors of **n** (1-indexed).
>
>
>
* The program that outputs **a(n)** is written in **[05AB1E](https://github.com/Adriandmen/05AB1E)**.
* The program that outputs the 05AB1E program is written in **[Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak)** + the `-A` flag.
* The length of the Brain-Flak program is **198 bytes** (the byte count does *not* include the flag).
Note that I could probably easily golf the Brain-Flak program by using stack-manipluation tricks and other kolmogorov-complexity tricks I am aware of, but I wanted to keep this simple as my first submission. ~~Good luck, robbers!~~
### What I had in mind
>
> 05AB1E: `ÑÈD<)O(O`
>
>
> Brain-Flak: `(((((((((((()()()){}){}){({}[()])}{}())[((((()()()){}){}())){}{}])((((()()()){}){}())){}{})[((((()()()){}){})()){}{}])(((()()()){})){}{}())(()()()()){})(((((()()()()){}){}){}()){}){})((()()())){}{})`
>
>
>
[Answer]
# [OEIS 000035](http://oeis.org/A000035), [cracked](https://codegolf.stackexchange.com/a/166355/68942) by [betseg](https://codegolf.stackexchange.com/users/56721/betseg)
The problem is solved in **Proton**.
The Proton code is output by **Python**.
The length of the Python program is **13 bytes**.
Really easy one for starters (if you know Proton :D). Zero-indexed.
# Intended Solution
>
> Python: `print("(2%)")`
>
> Proton: `(2%)`
>
> Though I decided to let `n=>n%2` be short enough because dyadic/monadic function shortcuts are not documented.
>
>
>
[Answer]
# [OEIS A000034](https://oeis.org/A000034) ([cracked](https://codegolf.stackexchange.com/a/166975/3852) by H.PWiz)
>
> **1, 2, 1, 2, 1, 2, 1, 2, …**
>
>
> *Period 2: repeat [1, 2]; a(n) = 1 + (n mod 2).*
>
>
>
**a(n)** is the output of a [**Haskell**](https://tio.run/#haskell) answer, which is the output of a 32-byte [**Malbolge**](https://tio.run/#malbolge) answer.
[Answer]
# [OEIS A055642](https://oeis.org/A055642), [cracked](https://codegolf.stackexchange.com/a/166965/80897) by [Lynn](https://codegolf.stackexchange.com/users/3852/lynn)
>
> Number of digits in decimal expansion of n
>
>
>
This is probably too easy, but it took me a while so I hope someone out there will be just as disappointed as I was when I finally figured it out :D
* The program that writes out **a(n)** is written in **[05AB1E](https://github.com/Adriandmen/05AB1E)**
* The program that prints the 05AB1E program is written in **[TeX](https://en.wikibooks.org/wiki/TeX)**
* The TeX program is **6 bytes** long
What I had in mind:
>
> `Sg` as 05AB1E code
>
> `Sg\bye` as TeX code
>
>
>
[Answer]
# [OEIS A000668](https://oeis.org/A000668), [cracked](https://codegolf.stackexchange.com/a/166968/3852) by [Lynn](https://codegolf.stackexchange.com/users/3852/lynn)
>
> Mersenne primes (of form **2p-1** where **p** is a prime)
>
>
>
* **a(n)** is outputted by a **[Jelly](https://github.com/DennisMitchell/jelly)** full program.
* **n** is 1-indexed.
* The Jelly program is printed by a **[Triangularity](https://github.com/Mr-Xcoder/Triangularity)** program, whose length is **38 bytes**.
Different strategy: solve the sequence in a golflang and output the program in an esolang.
### Intended solution
>
> * **[Jelly code](https://tio.run/##y0rNyan8/1/tUcMMm4e7Jh3bpPxw56r//00B)**
> * **[Triangularity code](https://tio.run/##KynKTMxLL81JLMosqfz/X09PTwGIufT0lB7uXKUEYik93DXp2CZlJT0uJbVHDTNslLS1//8HAA)**
>
>
>
>
] |
[Question]
[
There is a site called ["Return True to Win"](https://alf.nu/ReturnTrue) with interesting tasks for Javascript programmers. The goal is to find arguments to a given function that force it to return true.
The following is one of the tasks:
```
function total(x) {
return (x < x) && (x == x) && (x > x);
}
```
The users must find snippets for the value of `x` that cause the function to return true. To test snippets, you call the function with your snippet as the parameter (i.e. `total(<snippet>)`).
I found a 22-character solution:
```
{valueOf:_=>n++%3},n=0
```
Some people found the solution in 21 chars. I can't find out this solution. What is the solution in 21 chars?
[Answer]
# 21 chars
```
{valueOf:n=_=>n=2<<n}
```
---
My original joke, which got downvoted and proposed for deletion:
# 11 chars :)
```
total=_=>!0
```
Test:
```
function total(x) {
return (x < x) && (x == x) && (x > x);
}
var arg = total=_=>!0
console.log(total(arg))
```
[Answer]
# Cheaty answer
I've already mentioned it in the comments, but it was not tested. It is now. You'll have to keep submitting it until it works.
```
{valueOf:Math.random}
```
### Demo
```
function total(x) {
return (x < x) && (x == x) && (x > x);
}
for(i = 1; !total({valueOf:Math.random}); i++);
console.log('Returned true after ' + i + ' iteration(s)')
```
] |
[Question]
[
**Goal:** This goal to take a string and output how many contributions should be made on which days in order to display a message.
[](https://i.stack.imgur.com/nqlB5.png)
## Specification
* Input
+ Support letters plus space (i.e. `[A-Za-z ]` )
+ Space is a blank `3X7`
+ The letters are defined in this [5x7 DOT Matrix](https://fontstruct.com/fontstructions/show/847768/5x7_dot_matrix) font provided below
+ The size of each letter is the minimum bounding rectangle (e.g. `l = 3x7`, `e = 5x5`)
* Coloring
+ There are 5 colors `C0, C1, C2, C3, C4`
+ `CX` requires `Y` contributions with `3X <= y < 3(X+1)`
+ Letters should alternate between `C1` and `C2`
+ Spaces have no color
+ Each letter size should overlap exactly 1 column with adjacent letters
+ If a cell has more than 1 color then use `C3`
* Dot Matrix
+ The dot matrix is Github's contribution history graph
+ If today is Monday, May 1st, 2017:
```
4-30 5-07 5-15
[5-01] 5-08 5-16
5-02 5-09 .
5-03 5-10 .
5-04 5-12 .
5-05 5-13
5-06 5-14
```
* Output
+ Flexible on how this is given
+ `(x, y)` pairs
+ `x` is a date greater than or equal to the current date
+ `y` is the number of contributions to be made on the date, `x`
+ Should be in chronological order (so I can fill in my calendar)
+ If for each date, `x`, the given `y` contributions are made, the input message should show up on the Github graph (with correct coloring)
+ The first date should the earliest possible
* Scoring
+ Shortest program/function in bytes wins
---
# Alphabet
Created by sylvan.black under [CC](https://creativecommons.org/licenses/by-sa/3.0/)
[](https://i.stack.imgur.com/Dsbpz.png)
[](https://i.stack.imgur.com/1N2D6.png)
---
# Test Cases
For these test cases, assume the current date is May 25th, 2017.
```
Input -> Output
----- ------
l 5-28-17, 3
6-3-17, 3
6-4-17, 3
6-5-17, 3
6-6-17, 3
6-7-17, 3
6-8-17, 3
6-9-17, 3
6-10-17, 3
6-17-17, 3
He 5-28-17, 3
5-29-17, 3
5-30-17, 3
5-31-17, 3
6-1-17, 3
6-2-17, 3
6-3-17, 3
6-7-17, 3
6-14-17, 3
6-21-17, 3
6-25-17, 3
6-26-17, 3
6-27-17, 3
6-28-17, 9
6-29-17, 9
6-30-17, 9
7-1-17, 3
7-4-17, 6
7-6-17, 6
7-8-17, 6
7-11-17, 6
7-13-17, 6
7-15-17, 6
7-18-17, 6
7-20-17, 6
7-22-17, 6
7-26-17, 6
7-27-17, 6
o W 5-31-17, 3
6-1-17, 3
6-2-17, 3
6-6-17, 3
6-10-17, 3
6-13-17, 3
6-17-17, 3
6-20-17, 3
6-24-17, 3
6-28-17, 3
6-29-17, 3
6-30-17, 3
7-9-17, 6
7-10-17, 6
7-11-17, 6
7-12-17, 6
7-13-17, 6
7-14-17, 6
7-22-17, 6
7-26-17, 6
7-27-17, 6
7-28-17, 6
8-5-17, 6
8-6-17, 6
8-7-17, 6
8-8-17, 6
8-9-17, 6
8-10-17, 6
8-11-17, 6
```
[Answer]
# JavaScript (ES6), 743 bytes
```
s=>(n=y=>d.setDate(d.getDate()+y),d=new Date,(h=d.getDay())&&n(7-h),r={},i=0,[...s].map(c=>{c<"!"?n(14):([...parseInt("jn4x733nx8gjw6nhricv6nx8dpz2vilui81vikl7b4nhridnzvgc1svznx8dji8g16fkg0vgc6341vg38oe9vh669ofvgm1dvjnhricvyvikl7aonhrjrjxvikmm29m0rqqp2nqmi6o0vbnf6dav2t14e4vbnjqpqs0g34o3tlqqwdso43oixtg1uyt8vvgddxn2hizrn2ahizrmdbhj4suq4gtytq8wgshvtzyvgc4mq7gzhwhz4g15ymf4vg72q9snx7r2f4jmffjm7jm5gavjhizrn2mjmkh3wogsgmianjm5gavcgwxpc3mhvni2kijhgqujjj8mcsgsjhgslnihw2cx75iqyv1cuhwdrh5d".substr((c.charCodeAt()-(c>"`"?71:65))*7,7),36).toString(2).slice(1).replace(/(0{7})+$/,"")].map(b=>(+b&&(r[+d]=r[+d]?9:i%2?6:3),n(1))),i++,n(-7))}),Object.keys(r).map(k=>[k,r[k]]).sort((i,j)=>i[0]-j[0]>0?1:-1).map(i=>[(new Date(+i[0])+"").slice(4,15),i[1]]))
```
Output is an array of 2-item arrays in the form `[dateString, contribs]`. The snippet below shows how that can be formatted into being more readable.
## Un-Golfed
```
s=>(
n=y=>d.setDate(d.getDate()+y),
d=new Date,
(h=d.getDay()) && n(7-h),
r={},
i=0,
[...s].map(c=>{
c<"!" ? n(14) : (
[...parseInt("<...>".substr((c.charCodeAt()-(c>"`"?71:65))*7,7),36).toString(2).slice(1).replace(/(0{7})+$/,"")].map(b=>(
+b && (r[+d] = r[+d] ? 9 : i%2?6:3),
n(1)
)),
i++,
n(-7)
)
}),
Object.keys(r)
.map(k=>[k,r[k]])
.sort((i,j)=>i[0]-j[0] > 0 ? 1 : -1)
.map(i => [ (new Date(+i[0])+"").slice(4,15), i[1] ])
)
```
Where `<...>` represents the 364-byte string of characters that I created to encode each letter's dot matrix form.
## Explanation
The encoded string:
```
jn4x733nx8gjw6nhricv6nx8dpz2vilui81vikl7b4nhridnzvgc1svznx8dji8g16fkg0vgc6341vg38oe9vh669ofvgm1dvjnhricvyvikl7aonhrjrjxvikmm29m0rqqp2nqmi6o0vbnf6dav2t14e4vbnjqpqs0g34o3tlqqwdso43oixtg1uyt8vvgddxn2hizrn2ahizrmdbhj4suq4gtytq8wgshvtzyvgc4mq7gzhwhz4g15ymf4vg72q9snx7r2f4jmffjm7jm5gavjhizrn2mjmkh3wogsgmianjm5gavcgwxpc3mhvni2kijhgqujjj8mcsgsjhgslnihw2cx75iqyv1cuhwdrh5d
```
Each 7 characters is a base-36 encoded binary number that contains the mapping for the character at that index. The binary form always has a leading `1` in order to preserve the leading `0`s. For example, an uppercase `T` maps to `nqmi6o0`, which converts to `1100 00001000 00011111 11100000 01000000`. Skipping the leading 1, each bit is one day. Most numbers have 5 columns/weeks, so the numbers with less than 5 columns have one or two sets of 7 trailing zeros that are later removed before parsing (`.replace(/(0{7})+$/,"")`). This keeps all encoded strings the same length, removing the need for delimiters.
There's probably still more ways to improve upon this, especially with compressing the letter mappings further, so feel free to share any ideas.
Binary format of the letter mappings (JS syntax, prefixed with `0b`), can be found [here](https://gist.github.com/jmariner/7caa282497af3e0821e06874237342c9).
## Basic Snippet
```
f=
s=>(n=y=>d.setDate(d.getDate()+y),d=new Date,(h=d.getDay())&&n(7-h),r={},i=0,[...s].map(c=>{c<"!"?n(14):([...parseInt("jn4x733nx8gjw6nhricv6nx8dpz2vilui81vikl7b4nhridnzvgc1svznx8dji8g16fkg0vgc6341vg38oe9vh669ofvgm1dvjnhricvyvikl7aonhrjrjxvikmm29m0rqqp2nqmi6o0vbnf6dav2t14e4vbnjqpqs0g34o3tlqqwdso43oixtg1uyt8vvgddxn2hizrn2ahizrmdbhj4suq4gtytq8wgshvtzyvgc4mq7gzhwhz4g15ymf4vg72q9snx7r2f4jmffjm7jm5gavjhizrn2mjmkh3wogsgmianjm5gavcgwxpc3mhvni2kijhgqujjj8mcsgsjhgslnihw2cx75iqyv1cuhwdrh5d".substr((c.charCodeAt()-(c>"`"?71:65))*7,7),36).toString(2).slice(1).replace(/(0{7})+$/,"")].map(b=>(+b&&(r[+d]=r[+d]?9:i%2?6:3),n(1))),i++,n(-7))}),Object.keys(r).map(k=>[k,r[k]]).sort((i,j)=>i[0]-j[0]>0?1:-1).map(i=>[(new Date(+i[0])+"").slice(4,15),i[1]]))
I.value="Hello World";
(I.oninput=_=>O.innerHTML = f(I.value).map(e=>e.join(": ")).join("\n"))();
```
```
<input id="I">
<pre id="O">
```
## [Interactive example](https://codepen.io/justinm53/full/vZNZEL/)
Using the library [cal-heatmap](http://cal-heatmap.com/), I created an interactive heatmap of the dates that are output. This was used to test everything while working, and it just looks plain neat.
] |
[Question]
[
Given a string, first square it as follows:
First, write the string.
```
abcde
```
Next, write the string rotated one left.
```
abcde
bcdea
```
Keep doing this until you have written *len(string)* lines.
```
abcde
bcdea
cdeab
deabc
eabcd
```
Now, read from the string like this:
```
----+
+--+|
|+>||
|+-+|
+---+
```
Which gives:
```
abcdeabcdcbaedcbcdeabaede
```
Print this string.
### Test cases
```
abcdef -> abcdefabcdedcbafedcbcdefabcbafedefaf
cena! -> cena!cenanec!anena!cec!a!
ppcg -> ppcgppcppgcpcgpg
abc -> abcabacbc
ab -> abab
a -> a
->
```
Please comment if a test case is incorrect.
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins.
[Answer]
# JavaScript (ES7), ~~83~~ ~~80~~ ~~78~~ 77 bytes
```
s=>s.repeat(l=s.length).replace(/./g,_=>s[(c-=--i**.5-l&1||-1)%l],c=-1,i=l*l)
```
Bonus ES3-compliant program:
```
for(s=prompt(r=""),c=-1,l=s.length,i=l*l;i;)r+=s[(c-=l-Math.sqrt(i--)&1||-1)%l];alert(r)
```
---
## Explanation
This takes advantage of the fact that the output for e.g. a length 5 string can be represented as:
```
abcdeabcd cbaedcb cdeab aed e
012345678 7654321 23456 543 4
```
where each digit represents an index in the string (starting at 0), modulo the length of the string. In other words, if **n** is the length of the string, we increment the index **2n - 1** times, then decrement it **2(n - 1) - 1** times, then increment it **2(n - 2) - 1** times, etc. This can be simplified to the following algorithm:
* Start the index **i** at **-1**.
* For each integer **x** in the range **[n2..1]**:
+ If **floor(sqrt(x))** is of the same parity (even/odd) as **n**, increment **i**.
+ Otherwise, decrement **i**.
+ Add the character at index **i mod n** to the output.
This works because **floor(sqrt(x))** switches parities after **2n - 1** iterations, then **2(n - 1) - 1** iterations, etc.
[Answer]
# [Pyth](http://github.com/isaacg1/pyth), 15 bytes
```
.Wp.(H0_CZ.<LQU
```
A program that takes input of a `"quoted string"` and prints the result.
[Try it online!](http://pyth.tryitonline.net/#code=LldwLihIMF9DWi48TFFV&input=ImFiY2RlZiI) or [verify all test cases](http://pyth.tryitonline.net/#code=Vm0tZFwiLnpwIklucHV0OiAgIk5wIk91dHB1dDogIiMuV3AuKEgwX0NaLjxMTlVOKWI&input=ImFiY2RlZiIKImNlbmEhIgoicHBjZyIKImFiYyIKImFiIgoiYSIKIiI) (modified for multiple input).
**How it works**
```
.Wp.(H0_CZ.<LQU Program. Input: Q
L U Map over [0, 1, 2, 3, ..., Q-1] (implicit input):
.< Q Q left-shifted by that many characters
Call this X
.W While
.(H0 popping the first element of X (mutates X in-place)
p and printing it with no trailing newline is truthy:
Z X =
C X transposed
_ reversed
```
[Answer]
# Python 2.7 (in CMD.EXE), 91 bytes
This requires a terminal with a working backspace(`\b`), and will not work on [repl.it](https://repl.it/languages/python) or [ideone.com](http://ideone.com/). A print statement ending in a comma separates further output with space instead of a newline or return. The backspace allows us to overwrite the separating space.
```
s=input();r=s[::-1];n=len(s)-1;i=0
while i<=n:print'\b'+s[i:]+s[:n-i]+r[i+2:]+r[:n-i],;i+=2
```
# Python 2.7, 96 bytes
Try it on [ideone.com](http://ideone.com/8w6MIg) or [repl.it](https://repl.it/EOEZ) (thanks to Oliver). Input must be a python string, e.g.`'cena!'`.
```
s=input();r=s[::-1];n=len(s)-1;i=0;S=''
while i<=n:S+=s[i:]+s[:n-i]+r[i+2:]+r[:n-i];i+=2
print S
```
---
The four slices appended by the loop (`s[i:]`,`s[:n-i]`,`r[i+2:]`,`r[:n-i]`) are taken from four edges of the spiral. For instance with `01234` the square is:
```
01234
12340
23401
34012
40123
```
So we take `01234`,`0123`,`210`,`4321`. The variable `i` is the index of the top-left value in each step of the process. In the final spiral several of the slices may be empty.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ẋ2µṖȮṖUµÐL
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=4bqLMsK14bmWyK7huZZVwrXDkEw&input=&args=Y2VuYSE)**, or [all tests](http://jelly.tryitonline.net/#code=4bqLMsK14bmWyK7huZZVwrXDkEwKw4fhuYQk4oKs&input=&args=WyJhYmNkZWYiLCJjZW5hISIsInBwY2ciLCJhYmMiLCJhYiIsImEiLCAiIl0)
### How?
The unspiralled square is a series of "top-edge plus right-edge" and "bottom-edge plus left-edge" runs, each of which is the reverse of the previous run without the first and last letter, and the first of which is the input plus the input without the last letter (e.g. input `"abcde"` has an output of `"abcdeabcd" + "cbaedcb" + "cdeab" + "aed" + "e"`).
```
ẋ2µṖȮṖUµÐL - Main link: s e.g. abcde
ẋ2 - repeat s twice e.g. abcdeabcde
µ µ - monadic chain separation
ÐL - repeat until results are no longer unique:
Ṗ - remove the last character abcdeabcd / cbaedcb / cdeab / aed / e / ""
Ȯ - print z (with no linefeed) and return z
Ṗ - remove the last character abcdeabc / cbaedc / cdea / ae / "" / ""
U - reverse cbaedcba / cdeabc / aedc / ea / "" / "" <- no longer unique.
```
[Answer]
# 05AB1E, 12 bytes
```
2×[DõQ#¨D?¨R
```
[Try it online!](http://05ab1e.tryitonline.net/#code=MsOXW0TDtVEjwqhEP8KoUg&input=Y2VuYSE)
Explanation:
```
2×[DõQ#¨D?¨R
# Implicit input
2× # Repeat twice
[ # Begin infinite loop
┏> DõQ# # If empty string, break
┃ ¨ # Remove last character
┃ D # Duplicate
┃ ? # Print with no newline and pop
┃ ¨ # Remove last character
┃ R # Reverse
┗━━━━━━━━━━━━┛ # Implicit end infinite loop
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 27 bytes
```
"GX@q_YS]vGn1YL_GnoQ&Ple&S)
```
The empty input exits with an error (producing the correct output).
[Try it online!](http://matl.tryitonline.net/#code=IkdYQHFfWVNddkduMVlMX0dub1EmUGxlJlMp&input=J2FiY2RlZic) Or [verify all test cases](http://matl.tryitonline.net/#code=YFhLCiJLWEBxX1lTXXZLbjFZTF9Lbm9RJlBsZSZTKQpEVA&input=J2FiY2RlZicKJ2NlbmEhJwoncHBjZycKJ2FiYycKJ2FiJwonYScKJyc).
[Answer]
# C, ~~95~~ 94 Bytes
```
i,j,k,l;f(char*s){for(k=-1,l=i=strlen(s);i--;)for(j=i*2;~j--;putchar(s[(k+=(l-i)%2*2-1)%l]));}
```
Inspired by @ETHproductions answer.
[Answer]
# Perl, 99 bytes
```
$_=<>;
chop;
@a=split//;
print(@a[$%,(@f=1-($b=@a-$%)..$b-3),$b-1?$b-2:(),reverse@f]),$%+=2 until$%>@a
```
Whitespace is not part of the program and is provided for readability.
Not extremely efficient code. I should be able to shorten the first three lines somehow, but everything I tried to do failed. That ternary operator also needs to be fixed somehow, but having it this way made it possible to shorten my code by like, 10 bytes because I could cut out so much.
The code works by compiling a list of palindromes, separated by even numbers, which represent the place values of the string to be pulled.
[Answer]
# [Actually](http://github.com/Mego/Seriously), ~~21~~ 13 bytes
This algorithm is largely based on [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/98612/47581). There are two ways to go about printing the result as one string. The approach used here duplicates an intermediate step and then adds it to a running total in register 1 (an empty string by default); `;╕` in the function, then `╛` at the end. The other approach is to duplicate an intermediate step, leave those duplicate steps on the stack, and sum them into one string at the end; `;` in the function, then `kΣ` at the end.
Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=MipgZFg74pWVZFhSYFnilZs&input=ImFiY2RlIg)
```
2*`dX;╕dXR`Y╛
```
**Ungolfing**
```
Implicit input s.
2* Push a string that repeats s two times.
`...`Y Call the following function until there is no change from the last call
dX Discard the last element. Call this new string m.
;╕ Duplicate m and add it to the running total in register 1.
dXR Discard the last element again and reverse the string.
╛ Push the unspiralled string from register 1 to the stack.
Implicit return.
```
[Answer]
# Python 3, 59 bytes
```
x=input()*2
while x:x=x[:-1];print(x,end='');x=x[:-1][::-1]
```
**[repl.it](https://repl.it/ESJe)**
A direct port of [my Jelly answer](https://codegolf.stackexchange.com/a/98612/53748); only a full program taking input (rather than a function).
The `print(x,end='')` is a print statement which will not print the default newline.
[Answer]
# Python 3, 93 bytes
```
s=input();r,n,i=s[::-1],len(s)-1,0
while n-i:print(s[i:]+s[:n-i]+r[i+2:]+r[:n-i],end='');i+=2
```
[Try it online!](https://repl.it/EPNs)
] |
[Question]
[
**Input:**
A string only containing the following characters:
`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?!` (space at the end) and two special characters (`_` and `|`)
**Output:**
Mirror the text based on the position(s) of the `_` and `|`.
`_` mirrors horizontally and `|` mirrors vertically.
**Mirroring process**
* The first `_` indicates the start of the mirroring of that substring, the second `_` the end.
* If just one `_` is present, you can continue on until the end of the string.
* If more then two `_` are present, the same process repeats.
* There can only be one `|` in the string, and this reversed the first substring and removes the second substring.
---
`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?!` (space at the end) will be converted to [`…êq…îp«ù…ü…ì…•ƒ±…æ ûl…Øuodb…πs án å çx éz‚àÄêêí∆Ü·ó°∆é‚Ñ≤‚ÖÅHI≈ø‚ãä‚ÖÇWNO‘Č工öS‚䕂ੌõMX‚ÖÑZ0‚áÇ·òî∆êflàœõ9„Ñ•86Àô¬ø¬°`](https://en.wikipedia.org/wiki/Transformation_of_text#Upside-down_text) (space at the end) when it is mirrored by `_` (click the link for the unicode values - requires unicode v8.0+).
*Example input 1:* `_Will I be mirrored?!`
*Output 1:* `Mıll I qǝ ɯıɹɹoɹǝp¿¡`
*Example input 2:* `Wi_ll I be mi_rrored?!`
*Output 2:* `Will I qǝ ɯırrored?!`
---
When it is mirrored by `|` we simply reverse the substring from 0 to index-of-`|`.
*Example input 1:* `Will I be mirror|ed?!`
*Output 1:* `Will I be mirrorrorrim eb I lliW`
Both mirrors (`_` and `|`) can be present in the string.
---
**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](http://meta.codegolf.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* [Default Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
**Test cases:**
```
_Will I be mirrored?! -> Mıll I qǝ ɯıɹɹoɹǝp¿¡
Wi_ll I be mi_rrored?! -> Will I qǝ ɯırrored?!
Will I be mirror|ed?! -> Will I be mirrorrorrim eb I lliW
This_ is a test_ cont_aining bo|t_h mirrors. -> This ƒ±s …ê á«ùs á cont…ꃱuƒ±u…ì qooq …ìuƒ±uƒ±…êtnoc ás«ù á …ê sƒ± sihT
0_1_2_3_4_5|_6_7_8_9 -> 0⇂2Ɛ4ϛϛ4Ɛ2⇂0
```
[Answer]
# Pyth - 174 bytes
Can prolly save with base compression or something cuz of unicode(this is only 119 chars)
```
u?qH\_&=hZG+G@@c2K+s+rB;1UT".?! …êq…îp«ù…ü…ì…•ƒ±…æ ûl…Øuodb…πs án å çx éz‚àÄêêí∆Ü·ó°∆é‚Ñ≤‚ÖÅHI≈ø‚ãä‚ÖÇWNO‘Č工öS‚䕂ੌõMX‚ÖÑZ0‚áÇ·òî∆êflàœõ9„Ñ•86Àô¬ø¬° "ZxKH?}\|zs_Bhcz\|zk
```
[Test Suite](http://pyth.herokuapp.com/?code=u%3FqH%5C_%26%3DhZG%2BG%40%40c2K%2Bs%2BrB%3B1UT%22.%3F%21+%C9%90q%C9%94p%C7%9D%C9%9F%C9%93%C9%A5%C4%B1%C9%BE%CA%9El%C9%AFuodb%C9%B9s%CA%87n%CA%8C%CA%8Dx%CA%8Ez%E2%88%80%F0%90%90%92%C6%86%E1%97%A1%C6%8E%E2%84%B2%E2%85%81HI%C5%BF%E2%8B%8A%E2%85%82WNO%D4%80%CE%8C%E1%B4%9AS%E2%8A%A5%E2%88%A9%CE%9BMX%E2%85%84Z0%E2%87%82%E1%98%94%C6%90%DF%88%CF%9B9%E3%84%A586%CB%99%C2%BF%C2%A1+%22ZxKH%3F%7D%5C%7Czs_Bhcz%5C%7Czk&test_suite=1&test_suite_input=_Will+I+be+mirrored%3F%21%0AWi_ll+I+be+mi_rrored%3F%21%0AWill+I+be+mirror%7Ced%3F%21%0AThis_+is+a+test_+cont_aining+bo%7Ct_h+mirrors.%0A0_1_2_3_4_5%7C_6_7_8_9&debug=0).
[Answer]
# JavaScript (ES6), 308 bytes
```
s=>s[r='replace'](/_.*?(_|$)/g,m=>m[r](/./g,c=>'| …êq…îp«ù…ü…ì…•ƒ±…æ ûl…Øuodb…πs án å çx éz‚àÄ∆Ü·ó°∆é‚Ñ≤‚ÖÅHI≈ø‚ãä‚ÖÇWNO‘Č工öS‚䕂ੌõMX‚ÖÑZ0‚áÇ·òî∆êflàœõ9„Ñ•86Àô¬ø¬°êêí'['| abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?!B'.indexOf(c)]||''))[r](/(.*)\|.*/,(m,t)=>t+[...t].reverse().join``)
```
## Test
```
var solution =
s=>
s[r='replace'](/_.*?(_|$)/g,m=>
m[r](/./g,c=>
'| …êq…îp«ù…ü…ì…•ƒ±…æ ûl…Øuodb…πs án å çx éz‚àÄ∆Ü·ó°∆é‚Ñ≤‚ÖÅHI≈ø‚ãä‚ÖÇWNO‘Č工öS‚䕂ੌõMX‚ÖÑZ0‚áÇ·òî∆êflàœõ9„Ñ•86Àô¬ø¬°êêí'
['| abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?!B'
.indexOf(c)]||''
)
)
[r](/(.*)\|.*/,(m,t)=>t+[...t].reverse().join``)
var testCases = [
'_Will I be mirrored?!',
'Wi_ll I be mi_rrored?!',
'Will I be mirror|ed?!',
'This_ is a test_ cont_aining bo|t_h mirrors.',
'0_1_2_3_4_5|_6_7_8_9'
];
tests.textContent = testCases.map((c) => c + ' => ' + solution(c)).join('\n');
```
```
<input type="text" oninput="result.textContent=solution(this.value)" value="This_ is a test_ cont_aining bo|t_h mirrors." /><pre id="result"></pre><pre id="tests"></pre>
```
[Answer]
# PERL 243
242 + 1 for -p
```
$h=(split'\|',$_)[0];$_=$h.reverse$h if($_=~/\|/);for$b(split'_',$_){$b=~y/A-Za-z0-9.?!/…êq…îp«ù…ü…ì…•ƒ±…æ ûl…Øuodb…πs án å çx éz‚àÄêêí∆Ü·ó°∆é‚Ñ≤‚ÖÅHI≈ø‚ãä‚ÖÇWNO‘Č工öS‚䕂ੌõMX‚ÖÑZ0‚áÇ·òî∆êflàœõ9„Ñ•86Àô¬ø¬°/ if($f);$\.=$b;$f=!$f;}$_='';
```
Ungolfed:
```
$reverse = (split('\|', $_))[0];
$_ = $reverse . reverse($reverse) if($_=~/\|/);
for $block (split '_', $_) {
$block =~ y/A-Za-z0-9.?!/…êq…îp«ù…ü…ì…•ƒ±…æ ûl…Øuodb…πs án å çx éz‚àÄêêí∆Ü·ó°∆é‚Ñ≤‚ÖÅHI≈ø‚ãä‚ÖÇWNO‘Č工öS‚䕂ੌõMX‚ÖÑZ0‚áÇ·òî∆êflàœõ9„Ñ•86Àô¬ø¬°/ if($flip);
$\.=$block;
$flip=!$flip;
}
$_='';
```
Example:
```
$ perl -p mirror.pl <<<'Will I be mirror|ed?!'
Will I be mirrorrorrim eb I lliW
```
I'm 99% sure this works, but most of the upsidedown characters don't display correctly on my system. I tested it by using a different range of character, e.g. `.?! -> %^&` instead of `.?! -> Àô¬ø¬°`.
[Answer]
# R, 362 362 342 339 bytes
Edit 1: I found a bug in my original (failed if there were no `_` in input), fixed it, golfed some more, and I'm back at 362 where I started!
Edit 2: Golfed away 20 byes by replacing `"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! "` with `paste(c(letters,LETTERS,0:9,".?! "),collapse="")`
Edit 3: Removing some extra whitespace shaves off another 3 bytes.
```
p=strsplit
l=length
i=p(readline(),"_")[[1]]
if(l(i)-1)i[v]=chartr(paste(c(letters,LETTERS,0:9,".?! "),collapse=""),"…êq…îp«ù…ü…ì…•ƒ±…æ ûl…Øuodb…πs án å çx éz‚àÄêêí∆Ü·ó°∆é‚Ñ≤‚ÖÅHI≈ø‚ãä‚ÖÇWNO‘Č工öS‚䕂ੌõMX‚ÖÑZ0‚áÇ·òî∆êflàœõ9„Ñ•86Àô¬ø¬° ",i[v<-seq(2,l(i),2)])
i=unlist(p(i,""))
if(l(b<-which(i=="|")-1))i[1:b+b]=rev(i[1:b])
cat(i,sep="")
```
Explained:
```
p=strsplit # Aliases for common functions
l=length
i=p(readline(),"_")[[1]] # Read input, split by _s. Now every even-indexed substring is one that we must
# mirror vertically. (R indexes from 1.)
if(l(i)-1) # If there are any _s,
i[v]=chartr("paste(c(letters,LETTERS,0:9,".?! "),collapse=""),
"…êq…îp«ù…ü…ì…•ƒ±…æ ûl…Øuodb…πs án å çx éz‚àÄêêí∆Ü·ó°∆é‚Ñ≤‚ÖÅHI≈ø‚ãä‚ÖÇWNO‘Č工öS‚䕂ੌõMX‚ÖÑZ0‚áÇ·òî∆êflàœõ9„Ñ•86Àô¬ø¬° ",
i[v<-seq(2, l(i), 2)]
) # Flip the characters in the vertically-mirrored substrings
i=unlist(p(i,"")) # Split each substring into a single character object
if(l(b<-which(i=="|")-1)) # If there is a |,
i[1:b+b]=rev(i[1:b]) # insert the reversed characters at the end of the list
cat(i,sep="") # Print output
```
[Answer]
# Javascript (ES5), 344 340 bytes
```
function mirror(a){d=[];~a.indexOf("|")&&(a=a.split("|")[0]+a.split("|")[0].split("").reverse().join(""));for(var c=!1,b=0;b<a.length;++b)"_"==a[b]&&(c=!c),d[b]=c?"z éx ç ån ás…πbdou…Øl û…淥⅕…ì…ü«ùp…îq…êZ‚ÖÑXMŒõ‚à©‚ä•S·¥öŒå‘ÄONW‚ÖÇ‚ãä≈øIH‚ÖÅ‚Ñ≤∆é·ó°∆Ü·ó∫‚±Ø068„Ñ•95flà∆ê·òî‚áÇÀô¬ø¬° "["zyxwvutsrqponmlkijhgfedcbaZYXWVUTSRQPNOMLKIJHGFEDCBA0987654321.?! ".indexOf(a[b])]:a[b];return d.join("")}
```
Ungolfed:
```
function mirror_u(s){return "z éx ç ån ás…πbdou…Øl û…淥⅕…ì…ü«ùp…îq…êZ‚ÖÑXMŒõ‚à©‚ä•S·¥öŒå‘ÄONW‚ÖÇ‚ãä≈øIH‚ÖÅ‚Ñ≤∆é·ó°∆Ü·ó∫‚±Ø068„Ñ•95flà∆ê·òî‚áÇÀô¬ø¬° "["zyxwvutsrqponmlkijhgfedcbaZYXWVUTSRQPNOMLKIJHGFEDCBA0987654321.?! ".indexOf(s)]};
function mirror(str){var b=[];
if(~str.indexOf("|"))str=str.split("|")[0]+str.split("|")[0].split("").reverse().join("");
var is_mirrored=false;
for(var i=0;i<str.length;++i){
if(str[i]=="_")is_mirrored=!is_mirrored;
if(is_mirrored){b[i]=mirror_u(str[i])}else{b[i]=str[i]};
}
return b.join("");
}
```
EDIT: Longer working code, that is mirrored | by character 341.
```
function mirror(a){d=[];~a.indexOf("|")&&(a=a.split("|")[0]+a.split("|")[0].split("").reverse().join(""));for(var c=!1,b=0;b<a.length;++b)"_"==a[b]&&(c=!c),d[b]=c?"z éx ç ån ás…πbdou…Øl û…淥⅕…ì…ü«ùp…îq…êZ‚ÖÑXMŒõ‚à©‚ä•S·¥öŒå‘ÄONW‚ÖÇ‚ãä≈øIH‚ÖÅ‚Ñ≤∆é·ó°∆Ü·ó∫‚±Ø068„Ñ•95flà∆ê·òî‚áÇÀô¬ø¬° "["zyxwvutsrqponmlkijhgfedcbaZYXWVUTSRQPNOMLKIJHGFEDCBA0987654321.?! ".indexOf(a[b])]:a[b];return d.join("")}//})""(nioj.d nruter;]b[a:])]b[a(fOxedni." !?.1234567890ABCDEFGHJIKLMONPQRSTUVWXYZabcdefghjiklmnopqrstuvwxyz"[" ¬°¬øÀô‚áÇ·òî∆êflà59„Ñ•860‚±Ø·ó∫∆Ü·ó°∆é‚Ñ≤‚ÖÅHI≈ø‚ãä‚ÖÇWNO‘Č工öS‚䕂ੌõMX‚ÖÑZ…êq…îp«ù…ü…ì…•·¥â…æ ûl…Øuodb…πs án å çx éz"?c=]b[d,)c!=c(&&]b[a=="_")b++;htgnel.a<b;0=b,1!=c rav(rof;))""(nioj.)(esrever.)""(tilps.]0[)"|"(tilps.a+]0[)"|"(tilps.a=a(&&)"|"(fOxedni.a~;][=d{)a(rorrim noitcnuf
```
[Answer]
# [Retina](http://github.com/mbuettner/retina), 176 bytes
```
\|.+
:$`
O$^`:|(?!^)\G.
:
T`w.?!`_0‚áÇ·òî∆êflàœõ9„Ñ•86‚àÄ:∆Ü·ó°∆é‚Ñ≤‚ÖÅ\HI≈ø‚ãä‚ÖÇWN\O‘Č工öS‚䕂ੌõMX‚ÖÑZ…êq…î\p«ù…ü…ì…•ƒ±…æ û\l…Øu\o\db…πs án å çx ézÀô¬ø¬°`_[^_]*_?
:
êêí
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYApcfC4rCjokYApPJF5gOnwoPyFeKVxHLgoKOgoKVGB3Lj8hYF8w4oeC4ZiUxpDfiM-bOeOEpTg24oiAOsaG4Zehxo7ihLLihYFcSEnFv-KLiuKFgldOXE_UgM6M4bSaU-KKpeKIqc6bTVjihYRayZBxyZRccMedyZ_Jk8mlxLHJvsqeXGzJr3Vcb1xkYsm5c8qHbsqMyo14yo56y5nCv8KhYF9bXl9dKl8_CjoK8JCQkg&input=X1dpbGwgSSBiZSBtaXJyb3JlZD8hCldpX2xsIEkgYmUgbWlfcnJvcmVkPyEKV2lsbCBJIGJlIG1pcnJvcnxlZD8hClRoaXNfIGlzIGEgdGVzdF8gY29udF9haW5pbmcgYm98dF9oIG1pcnJvcnMuCjBfMV8yXzNfNF81fF82XzdfOF85) (The first line enables a linefeed-separated test suite.)
[Answer]
# Java 7, ~~504~~ 502 bytes
```
import java.util.*;String c(String s){Map m=new HashMap();int i=0,j;while(i<67)m.put("abcdefghijklmnopqrstuvwxyzABBCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! ".charAt(i),"…êq…îp«ù…ü…ì…•ƒ±…æ ûl…Øuodb…πs án å çx éz‚àÄêêí∆Ü·ó°∆é‚Ñ≤‚ÖÅHI≈ø‚ãä‚ÖÇWNO‘Č工öS‚䕂ੌõMX‚ÖÑZ0‚áÇ·òî∆êflàœõ9„Ñ•86Àô¬ø¬° ".charAt(i++));String q=s.split("\\|")[0],z[]=(q+(s.equals(q)?"":new StringBuffer(q).reverse()+"")).split("_"),r="";for(i=-1;++i<z.length;){q="";for(char c:z[i].toCharArray())q+=m.get(c);r+=i%2<1?z[i]:q;}return r;}
```
Of course I'll have to answer my own challenge again. And.. it's long.. xD
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/RdF4se)
```
import java.util.*;
class M{
static String c(String s){
Map m = new HashMap();
int i = 0,
j;
while(i < 67){
m.put("abcdefghijklmnopqrstuvwxyzABBCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?! ".charAt(i),
"…êq…îp«ù…ü…ì…•ƒ±…æ ûl…Øuodb…πs án å çx éz‚àÄêêí∆Ü·ó°∆é‚Ñ≤‚ÖÅHI≈ø‚ãä‚ÖÇWNO‘Č工öS‚䕂ੌõMX‚ÖÑZ0‚áÇ·òî∆êflàœõ9„Ñ•86Àô¬ø¬° ".charAt(i++));
}
String q = s.split("\\|")[0],
z[] = (q + (s.equals(q)
? ""
: new StringBuffer(q).reverse() + "")
).split("_"),
r = "";
for(i = -1; ++i < z.length;){
q = "";
for(char c : z[i].toCharArray()){
q += m.get(c);
}
r += i%2 < 1
? z[i]
: q;
}
return r;
}
public static void main(String[] a){
System.out.println(c("_Will I be mirrored?!"));
System.out.println(c("Wi_ll I be mi_rrored?!"));
System.out.println(c("Will I be mirror|ed?!"));
System.out.println(c("This_ is a test_ cont_aining bo|t_h mirrors."));
System.out.println(c("0_1_2_3_4_5|_6_7_8_9"));
}
}
```
**Output:**
```
Mıll I qǝ ɯıɹɹoɹǝp¿¡
Will I qǝ ɯırrored?!
Will I be mirrorrorrim eb I lliW
This ƒ±s …ê á«ùs á cont…ꃱuƒ±u…ì qooq …ìuƒ±uƒ±…êtnoc ás«ù á …ê sƒ± sihT
0⇂2Ɛ4ϛϛ4Ɛ2⇂0
```
] |
[Question]
[
This is somewhat similar to [The centers of a triangle](https://codegolf.stackexchange.com/questions/11767/the-centers-of-a-triangle), but with a different point. The [Fermat Point](https://en.wikipedia.org/wiki/Fermat_point) is the point P in triangle ABC such that the value of AP + BP + CP is minimized. There are two cases:
If there is an angle greater than 120 degrees, that vertex is the fermat point. Otherwise, draw equilateral triangles on each of the sides of ABC. Connect the far vertex of each equilateral triangle to the opposite vertex of triangle ABC. Doing this for each of the three equilateral triangles results in a single common point of intersection for all three lines, which is the Fermat Point.
It should run within 5 seconds on a reasonable machine.
**Input**: A set of 3 points, not necessarily integers. This can be taken as a nested array, string, list of tuples, etc. (whatever suits your language).
**Output**: The coordinates of the Fermat point, again, however your language best handles points. Floating point inaccuracies will not be counted against you.
**Test Cases**:
```
[[1, 1], [2, 2], [1, 2]] --> [1.2113248654051871, 1.788675134594813]
[[-1, -1], [-2, -1], [0, 0]] --> [-1, -1]
[[-1, -1], [1, -1], [0, 1]] --> [0, -0.42264973081037427]
[[0, 0], [0.5, 0.8660254037844386], [-5, 0]] --> [0, 0]
[[0, 0], [0, -5], [-0.8660254037844386, 0.5]] --> [0, 0]
```
This is code golf so shortest code wins!
[Answer]
# Mathematica, 39 bytes
```
Sum[Norm[p-{x,y}],{p,#}]~NArgMin~{x,y}&
```
Constructs an equation based on the distances between the vertices and a point `{x,y}`. Then uses the `NArgMin` function to find a global minimum for that equation, which will be the Fermat Point by definition.
[](https://i.stack.imgur.com/yfTHI.png)
[Answer]
# Haskell, ~~346~~ ~~291~~ 295 bytes
```
infixl 5£
z=zipWith
(?)=z(-)
t[a,b]=[-b,a]
a¤b=sum$z(*)a b
a%b=t a¤b
r a b c=[c%b/a%b,c%a/a%b]
x£y=2*x¤y<= -sqrt(x¤x*y¤y)
f[a,b,c]|a?b£c?b=b|a?c£b?c=c|b?a£c?a=a|[n,m,p,o]<-c?k a b c++a?k b c a=r[m,o][n,p][c%[n,m],a%[p,o]]
k a b c=map(/2)$z(+)a b?map(signum((b?a)%(c?a))*sqrt 3*)(t$b?a)
```
The same code with some explanations
```
infixl 5£
z=zipWith
-- operator ? : difference of two vectors
(?)=z(-)
-- function t : rotate a vector by +90 degrees
t[a,b]=[-b,a]
-- operator ¤ : scalar product of two vectors ( a¤b = a0 * b0 + a1 * b1 )
a¤b=sum$z(*)a b
-- operator % : "cross product" of two vectors ( a%b = a0 * b1 - a1 * b0 )
-- this returns actually the z coordinate of the 3d cross vector
-- other coordinates are nul since a and b are in the xy plan
a%b=t a¤b
-- function r : solves the system of two linear equations with two variables x0,x1 :
-- a0*x0 - b0*x1 = c0
-- a1*x0 - b1*x1 = c1
r a b c=[c%b/a%b,c%a/a%b]
-- operator £ : returns true if the angle between two vectors is >= 120 degrees
-- x¤y = ||x|| * ||y|| * cos(xyAngle)
-- so xyAngle>=120° is equivalent to : x¤y / (||x|| * ||y||) <= -0.5
x£y=2*x¤y<= -sqrt(x¤x*y¤y)
-- function k : takes 3 points A B C of a triangle and constructs the point C'
-- of the equilateral triangle ABC' which is opposite to C:
-- C' = (A+B)/2 - ((+/-) sqrt(3)/2 * t(AB))
--
-- the sign +/- is given by the sign of the cross vector of AB an AC ((b?a)%(c?a))
-- which is >0 if the angle between AB and AC is positive
-- and <0 otherwise.
k a b c=map(/2)$z(+)a b?map(signum((b?a)%(c?a))*sqrt 3*)(t$b?a)
-- function f : returns the fermat point of a triangle
f[a,b,c]
|a?b£c?b=b -- return B if angle ABC >= 120°
|a?c£b?c=c -- return C if angle BCA >= 120°
|b?a£c?a=a -- return A if angle CAB >= 120°
|[n,m,p,o]<-c?k a b c++a?k b c a= -- calculate the two segments C'C and A'A
r[m,o][n,p][c%[n,m],a%[p,o]] -- return their intersection
```
Tests:
```
main = do
print $ f [[1, 1], [2, 2], [1, 2]]
print $ f [[-1, -1], [-2, -1], [0, 0]]
print $ f [[-1, -1], [1, -1], [0, 1]]
print $ f [[0, 0], [0.5, 0.8660254037844386], [-5, 0]]
print $ f [[0, 0], [0, -5], [-0.8660254037844386, 0.5]]
```
Output:
```
[1.2113248654051871,1.7886751345948126]
[-1.0,-1.0]
[0.0,-0.42264973081037427]
[0.0,0.0]
[0.0,0.0]
```
[Answer]
# Python, ~~475~~ ~~448~~ 440 bytes
Any help to golf further is appreciated.
```
from math import *
d=lambda x,y:((x[0]-y[0])**2+(x[1]-y[1])**2)**0.5
s=lambda A,B,C:(d(B,C), d(C,A), d(A,B))
j=lambda a,b,c:acos((b*b+c*c-a*a)/(2*b*c))
t=lambda a,b,c:1/cos(j(a,b,c)-pi/6)
b=lambda A,B,C,p,q,r:[(p*A[i]+q*B[i]+r*C[i])/(p+q+r) for i in [0,1]]
f=lambda A,B,C:A if j(*s(A,B,C)) >= 2*pi/3 else B if j(*s(B,C,A)) >= 2*pi/3 else C if j(*s(C,A,B)) >= 2*pi/3 else b(A,B,C,d(B,C)*t(*s(A,B,C)),d(C,A)*t(*s(B,C,A)),d(A,B)*t(*s(C,A,B)))
```
Ungolfed:
```
from math import *
#distance between two points
d = lambda x,y: ((x[0]-y[0])**2+(x[1]-y[1])**2)**0.5
#given the points, returns the sides
s = lambda A,B,C : (d(B,C), d(C,A), d(A,B))
#given the sides, returns the angle
j = lambda a,b,c : acos((b*b+c*c-a*a)/(2*b*c))
#given the sides, returns secant of that angle
t = lambda a,b,c: 1/cos(j(a,b,c)-pi/6)
#given the sides and the Trilinear co-ordinates, returns the Cartesian co-ordinates
b = lambda A,B,C,p,q,r: [(p*A[i]+q*B[i]+r*C[i])/(p+q+r) for i in [0,1]]
#this one checks if any of the angle is >= 2π/3 returns that point else computes the point
f = lambda A,B,C: A if j(*s(A,B,C)) >= 2*pi/3 else B if j(*s(B,C,A)) >= 2*pi/3 else C if j(*s(C,A,B)) >= 2*pi/3 else b(A,B,C,d(B,C)*t(*s(A,B,C)),d(C,A)*t(*s(B,C,A)),d(A,B)*t(*s(C,A,B)))
```
Input:
```
print('{}'.format(f([1, 1], [2, 2], [1, 2])))
print('{}'.format(f([-1, -1], [-2, -1], [0, 0])))
print('{}'.format(f([-1, -1], [1, -1], [0, 1])))
print('{}'.format(f([0, 0], [0.5, 0.8660254037844386], [-5, 0])))
print('{}'.format(f([0, 0], [0, -5], [-0.8660254037844386, 0.5])))
```
Output:
```
[1.2113248652983113, 1.7886751347016887]
[-1, -1]
[0.0, -0.42264973086764884]
[0, 0]
[0, 0]
```
[Answer]
# Python 3.5, ~~1019~~ ~~1016~~ ~~998~~ ~~982~~ ~~969~~ 953 bytes:
```
from math import*
def H(z,a,b):c=complex;T=lambda A,B:abs(c(*A)-c(*B));d=T(z,a);e=T(z,b);f=T(a,b);g=[d,e,f];h=max(g);g.remove(h);i=acos((sum(i*i for i in g)-(h*h))/(2*g[0]*g[-1]));_=[[z,a],[z,b],[a,b]];j,s,t=cos,sin,atan;N=[[b,a]for a,b in zip([b,a,z],[max(i,key=i.get)if i!=''else''for i in[{(g[0]+(h*j(t(l))),g[1]+(h*s(t(l)))):T(k,(g[0]+(h*j(t(l))),g[1]+(h*s(t(l))))),(g[0]-(h*j(t(l))),g[1]-(h*s(t(l)))):T(k,(g[0]-(h*j(t(l))),g[1]-(h*s(t(l)))))}if l else{(g[0]+h,g[1]):T(k,(g[0]+h,g[1])),(g[0]-h,g[1]):T(k,(g[0]-h,g[1]))}if l==0else''for g,h,l,k in zip([((a[0]+b[0])/2,(a[1]+b[1])/2)for a,b in _],[(3**0.5)*(i/2)for i in[d,e,f]],[-1/p if p else''if p==0else 0for p in[((a[1]-b[1])/(a[0]-b[0]))if a[0]-b[0]else''for a,b in _]],[b,a,z])]])if b!=''];I=N[0][0][1];J=N[0][0][0];K=N[1][0][1];G=N[1][0][0];A=(N[0][1][1]-I)/(N[0][1][0]-J);B=I-(A*J);C=(K-N[1][1][1])/(G-N[1][1][0]);D=K-(C*G);X=(D-B)/(A-C);Y=(A*X)+B;return[[X,Y],[[a,b][h==d],z][h==f]][i>2.0943]
```
**Incredibly** long compared to other answers, but hey, at least it works! I could not be happier with the result I got as this has got to be one of the hardest challenges I have ever done. I am just so ***happy*** that it actually works! :D Now, onto the more technical notes:
* This function takes each ordered pair in as a list or a tuple. For instance, `H((1,1),(2,2),(1,2))` will work, but so will `H([1,1],[2,2],[1,2])`.
* Outputs the coordinates of the points in either a list of integers or floating points depending on whether or not one angle more than or equal to 120º exists.
* This may output `-0.0` in place of `0.0` for some inputs. For instance, the output for the input `[-1, -1], [1, -1], [0, 1]` is `[-0.0, -0.4226497308103744]`. ~~I hope this is okay, although if it isn't, I will change it, though it will cost me a few more bytes.~~ This is okay, as [confirmed by OP](https://codegolf.stackexchange.com/questions/79691/calculate-the-fermat-point-of-a-triangle/79933#comment196389_79691).
* Should be accurate up to at least `13` to `14` significant figures.
I will try and golf this more over time. An explanation, possibly very long, coming soon.
[Try It Online! (Ideone)](http://ideone.com/0QrGjv)
] |
[Question]
[
**Welcome back!** I'm excited to present the 3rd CodeBots challenge. This one has been a long time in the making. This challenge will be split up in 3 sections: the short version, the long version, and additional details.
# The Short Version
Each competitor will write a 24-command program. These bots will move around the world and copy their code into other bots, while trying to prevent other bots to do the same. One of the possible commands is the no-op `Flag`. If a bot has more of your `Flag` than any other bot's `Flag`, you get a point. You win by having the most points.
All of the above was true for the past two challenges. This time around, bots will be able to run multiple lines of code at the same time.
# The Long Version
## The API
Every bot will have exactly 24 lines, where each line is in the following format:
```
$label command parameters //comments
```
Labels and comments are optional, and each command has a different number of parameters. Everything is case-insensitive.
### Parameters
Parameters are typed, and can be in the following formats:
1. A value from 0 to 23.
2. A variable: `A`, `B`, `C`, `D`
3. A value using addition: `A+3` or `2+C`
4. A line of code, which is designated using the `#` sign (`#4` would represent the 5th line, while `#C+2` would represent the line calculated by `C+2`).
5. You can use a `$label` instead of designating a line of code.
6. Your opponent's variable or line of code, designated by `*`. Your opponent is the bot in the square that you are facing. (`*B` represents your opponent's `B` value, while `*#9` represents your opponent's 10th line). If there is nobody in that square, the command is not executed.
### Commands
**Move V**
Moves the bot `North+(V*90 degrees clockwise)`. Movement does not change direction.
**Turn V**
Turns the bot `V*90 degrees` clockwise.
**Copy V W**
Copies whatever is in `V` into `W`. If `V` is a line number, then `W` has to be a line number. If `V` is a variable or value, then `W` must be a variable.
**Flag**
Does nothing.
**Start V**
Starts a new thread attached to the variable `V`. Immediately, and on each future turn, the thread will execute the command on line `V`.
If `V` is already attached to a thread, then this command is a no-op. If `V` is an opponent's variable, then the opponent will start a thread attached to that variable.
**Stop V**
Stops the thread attached to the variable `V` at the end of this turn.
**Lock V**
Prevent the line or variable `V` from being used in *any way* except by the thread that called `Lock`. A subsequent call to `Lock` by the same thread unlocks `V`. Locks cannot be called on opponent's variables or lines.
**If Cond V W**
This will test `Cond`. If the condition is true, then it will move the thread pointer to the line number `V`, otherwise to the line number `W`. That line will then be immediately executed.
Conditionals can be `X=Y`, `X<Y`, `!X`, or `?X`:
1. `X=Y` tests whether two lines are of the same type and from the same bot, or you test whether two values equal the same amount.
2. `X<Y` tests whether the value of `X` is less than `Y`.
3. `!X` tests whether the variable or line `X` is locked (returns true if locked)
4. `?X` tests whether a given variable has a thread attached to it
# Additional Details
## Multi-threaded interactions
Actions of the same type are executed at the same time. Actions are executed in the following order:
1. Lock. If several threads attempt to lock a variable, they will all fail. If a thread is unlocking a variable while another is attempting to lock it, the variable will remain unlocked.
2. Start. If several threads attempt to start a thread on a variable, it will count as a single start.
3. Copy. If two threads both copy to the same variable, the variable will end up as a random value. If they both copy to the same line, neither will work. If a thread copies to the same variable another thread is copying from, then the latter thread will copy a random value. If two threads are both copying from the same variable, they will both work fine.
4. If. All conditionals will be tested simultaneously, and then the thread variables will be updated after. Executing an `If` can cause an action with a higher priority to be added. Actions with higher priority will be executed before moving on past the `If`, while actions with a lower priority will execute after the `If`.
5. Move. Multiple moves on the same bot will move the bot the sum of all of the moves. If multiple bots would end up in the same spot, they will be returned to their starting spot.
6. Turn. Multiple turns on the same bot will sum.
7. Stop. Multiple stop commands on the same variable will count as a single stop.
## Other details
Your initial thread starts attached to the `D` variable
Recursing with an `If` (having an `If` statement pointed to itself) will cause your bot to do nothing
If a thread is stopped after locking, those locks will be unlocked
Actions to use a locked variable or line will do nothing.
If a bot is shorter than 24 lines, remaining lines will be filled with `Flag`
Performing a write on a variable that is also attached to a starting thread will actually have the thread start its execution on the new value as the thread starts the following turn.
Bots are placed in a toroidal world in the following pattern:
```
B...B...B...
..B...B...B.
B...B...B...
```
I have added [several](https://codegolf.stackexchange.com/a/51617/20198) [sample](https://codegolf.stackexchange.com/a/51619/20198) [bots](https://codegolf.stackexchange.com/a/51618/20198) that are commented as a language reference.
The controller is [located here](https://github.com/nathanmerrill/CodeBots3). I've worked a long time on it, but it probably still has bugs. When the spec and the controller contradict, the spec is correct.
## Scoreboard
```
1. 771 LockedScannerBot
2. 297 CopyAndSelfFlag
3. 289 DoubleTapBot
4. 197 ThreadCutterBot
5. 191 TripleThread
6. 180 ThickShelled
7. 155 Attacker
8. 99 RandomMover
9. 90 BananaBot
10. 56 LockedStationaryDoubleTap
```
[Answer]
# Locked Scanner Bot
Scans the enemy as fast as possible and replaces the lines with flags.
```
Lock D
Copy $a A
Start A
Copy $b B
Start B
$d Lock $d0
Lock $d1
$d0 Copy $flag *#C+1
$d1 If 1=1 $d0 $d0
$a Lock A
Lock $a0
Lock $a1
Lock $a2
$a0 Copy $flag *#C
$a1 Copy C+2 C
$a2 If !*#C $a1 $a0
$b Lock B
Lock $b0
Lock $b1
Lock $b2
$b0 Move C
$b1 Turn 1
$b2 If 1=1 $b0 $b0
$flag Flag
```
[Answer]
## DoubleTapBot
This bot has 3 threads :
One for moving (A),
The two others for flagging (B and D).
B flag 1/2 turn, D flag 1/3 turn. So some turn, he will double flag the opponent :).
I assume that C will return to 0 if it exceed 23.
It shoudl be pretty safe if it have some turn to prepare itself (8 turn), as he will always keep at least 2 threads (A & B) running normally.
I can't try it at the moment, so I'll do the test when I'll be back Home :)
```
Lock D //Thread D locks itself
Copy 6 A //Thread A will start line 6
Start A
Copy 13 B //Thread B will start line 13
Start B
Copy 20 D //Moving Thread D to an other part of the program
Lock A //Thread A locks itself and the line it will be using
Lock #10
Lock #11
Lock #12
Move C //Move in a pseudo random direction
Turn 1 //always turn to the right
If 1=1 #10 #10 //return to Move C
Lock B //Thread B locks itself and the line it will be using
Lock #13
Lock #14
Copy #18 *#C //Copy a flag to the Cth line of the opponent
If 1=1 #16 #16 //jump back to the copy
Flag
Flag
Copy C+1 C //Increment C
Copy #19 *#C+1 //Copy a flag to the Cth+1 line of the opponent
If 1=1 #20 #20 //jump back to the increment
Flag
```
[Answer]
# Locked Stationary Double Tap
Inspired by @Katenkyo's DoubleTapBot, this one gives up a couple of flags and any hope of movement in return for completely locking down its own threads so it can't ever be reprogrammed. It is, however, still succeptible to having enemy flags written to non-looping code areas.
```
Lock $flag // lock the only flag line, super important!
Lock D // lock thread D
Copy 10 A
Start A // start thread A at $Astart
Copy 17 B
Start B // start thread B at $Bstart
Lock $D1 // lock thread D lines
Lock $D2 // thread D should be safe on turn 8
$D1 Turn C // Spin in place, once every 2 turns
$D2 If 0=0 $D1 $D1 // thread D loop
$Astart Lock A // thread A starts here, locks itself
Lock $A1 // lock thread A lines
Lock $A2
Lock $A3 // thread A should be safe on turn 7
$A1 Copy $flag *#C // ATTACK! once every 3 turns
$A2 Copy C+1 C // increment C, used for attacks and turning
$A3 If 0=0 $A1 $A1 // thread A loop
$Bstart Lock B // thread B starts here, locks itself
Lock $B1 // lock thread B lines
Lock $B2 // thread B should be safe on turn 8
$B1 Copy $flag *#C+12 // ATTACK! once every 2 turns
$B2 If 0=0 $B1 $B1 // thread B loop
$flag Flag
```
[Answer]
# Random Mover
Moves in a psuedorandom direction
```
Copy 5 C
Copy 8 B
Start C
Move A // If you can't catch me, you can't modify me
If 1=1 #3 #3 //Continue to execute the above line
Start B
Copy 4 A
If 1=1 #6 #6 //Continue to execute the above line
Flag
Copy 5 A
If 1=1 #9 #9 //Continue to execute the above line
```
[Answer]
# Thick Shelled
Locks his stuff as much as he can
```
Copy 5 B //Designating that the B thread will start on line 5
Start B //Starting the B thread
Lock C //Preventing C from being used
Copy A+1 A //The two threads are offset, meaning that the two threads shouldn't access this at the same time
Lock #A
Copy 2 B
```
[Answer]
# Attacker Bot
Copies flags into various locations
```
Copy A+1 A // Increment A
Move A //Move in the Ath direction
Turn A //Rotate A times
Copy #8 *#A //Copy my flag over
Copy 23 D //Loop back to the beginning. (I use 23 here as threads auto-increment)
```
[Answer]
# Triple Thread
This simple bot runs three threads all with the same code. Each thread attacks 1/3 turns, moves 1/6, turns 1/6, and does bookkeeping 1/3.
```
Move 0
Start A
Start B
$loop Copy #A+9 *#C
Move C
Copy #A+9 *#C
Turn C
Copy C+1 C
If 0=0 $loop $loop
```
[Answer]
# Banana Bot
Attempts to throw bananas in the enemies wheel before the enemy can do anything. Prone to being squished.
```
$d If !*D $d1 $d0
$d0 Copy 24 *D
$d1 If !D $d2 $start
$d2 If !*B $d5 $d3
$d3 Copy 24 *B
$d4 Copy $d D
$start Lock D //Banana's like to split.
Copy $a A
Start A
Copy $b B
Start B
Lock $flag
$d5 Copy $start *C //It's okay if enemy messes up our start.
Copy $d d
$a Lock A
$a1 Move C
Turn 1
Copy $a1 A
$b Lock B
$b0 Copy C+1 C
If !*#C $b0 $b1 //Banana's are good at slipping.
$b1 Copy $flag *#C
$b2 Copy $b0 B
$flag Flag
```
[Answer]
# Thread Cutter Bot
```
Lock D
Lock $f
Copy 16 C
$S If ?*D $1 $2
Move 1
Copy $S D
$f Flag
$1 Stop *D
$2 If ?*A $3 $4
$3 Stop *A
$4 If ?*B $5 $6
$5 Stop *B
$6 Copy $f *#C
Copy C+1 C
If *#C=#C $E $6
Copy 2 D
$E Start *D
```
Stop all enemy threads before filling with your code.
[Answer]
# Copy and Self Flag
This bot runs three threads. The D thread moves until it runs into an enemy, then tries to copy a flag into them, then moves a random direction. The A thread copies its own flag over non-essential lines of the bot's code. The B thread is just a counter.
The variable, flag, and lines of code used by each thread are fully locked in the first 15 turns, and the bot overwrites almost all of its startup code with its own flags. I don't think it's possible to convert this bot to another team's banner after turn 15 without a dedicated attack bot doing nothing but writing flags to it.
```
Lock D // Lock D thread
Copy $AS A
Start A // Start A thread at $AS
Start B // B is just a counter
Copy $DL D // Jump to D thread startup code
$DC Start B // Don't let B thread get stopped
$D0 If !*#B $D1 $D2
$D1 Copy $DF *#B
$D2 If !*#B+6 $D3 $DM
$D3 Copy $DF *#B
$DM Move B // Move some direction after attacking
$DA Move 0 // Move north ...
If ?*D $DC $DA // until we hit a live target
$DF Flag // Flag to copy
$DL Lock #B+3 // Lock the D thread's lines
If B<12 $DL $DA // jump to `Move 0` when D thread is safe
$AS Lock A
$AL Lock #B+20
If B<4 $AL $AD
Copy 23 B // reset B so A doesn't overwrite its own code
$AF Flag
Flag
$AD Copy $AF #B+1 // Copy a safe flag over every unused line of code
If B<18 $AD $AF
```
] |
[Question]
[
You are sick of all of the codegolf challenges. Hence you decide to write a program that will automatically golf some Python code for you. There are 3 test cases:
```
print quickSort([0,7,3,-1,8,10,57,2])
def quickSort(arr):
less = []
pivotList = []
more = []
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
for i in arr:
if i < pivot:
less.append(i)
elif i > pivot:
more.append(i)
else:
pivotList.append(i)
less = quickSort(less)
more = quickSort(more)
return less + pivotList + more
```
---
```
for i in xrange(1, 101):
if i % 15 == 0:
print "FizzBuzz"
elif i % 3 == 0:
print "Fizz"
elif i % 5 == 0:
print "Buzz"
else:
print i
```
---
```
from sys import argv
def randomGenerator(seed=1):
max_int32 = (1 << 31) - 1
seed = seed & max_int32
while True:
seed = (seed * 214013 + 2531011) & max_int32
yield seed >> 16
def deal(seed):
nc = 52
cards = range(nc - 1, -1, -1)
rnd = randomGenerator(seed)
for i, r in zip(range(nc), rnd):
j = (nc - 1) - r % (nc - i)
cards[i], cards[j] = cards[j], cards[i]
return cards
def show(cards):
l = ["A23456789TJQK"[c / 4] + "CDHS"[c % 4] for c in cards]
for i in range(0, len(cards), 8):
print " ", " ".join(l[i : i+8])
if __name__ == '__main__':
seed = int(argv[1]) if len(argv) == 2 else 11982
print "Hand", seed
deck = deal(seed)
show(deck)
```
Rules:
1. Your program must not target the code I posted specifically, and should work with any Python 2 code. I reserve the right to change the source code being codegolfed. You may assume that there are no multi-line strings (so you don't have build a full-blown parser), and that locals() is not called.
2. The output of your program should run in an identical manner as the original source code. (Namely, it must produce the same output. Variable names and language constructs can be changed, as long as the output remains the same)
3. You may use STDIO or a File to do your input/output of the source code.
Your score will be the sum of the bytes of your program's output.
(The code listed above has been taken from <http://rosettacode.org/> under the [GNU Free Documentation License 1.2](http://www.gnu.org/licenses/fdl-1.2.html))
[Answer]
# Python 2.7, 794
I have been meaning to build a minifier for Python for a while, so this is a good opportunity to investigate the problem.
The program uses a mix of regular expression analysis, and Python parser operations. White space is minimised. Variable that are defined by the user are replaced by a single letter variable (which is not in use!). Finally the `while True` statement is put on a diet.
The three test cases all verify as running correctly. I could imagine some pathological examples which could result in errors in the generated code but the algorithm should be robust under most circumstances.
## Results
```
228 t1.py
128 t2.py
438 t3.py
794 total
```
## Output
```
def c(a):
b=[]
d=[]
f=[]
if len(a)<=1:
return a
else:
e=a[0]
for i in a:
if i<e:
b.append(i)
elif i>e:
f.append(i)
else:
d.append(i)
b=c(b)
f=c(f)
return b+d+f
print c([0,7,3,-1,8,10,57,2])
for i in xrange(1,101):
if i%15==0:
print"FizzBuzz"
elif i%3==0:
print"Fizz"
elif i%5==0:
print"Buzz"
else:
print i
from sys import argv
def a(k=1):
b=(1<<31)-1
k=k&b
while 1:
k=(k*214013+2531011)&b
yield k>>16
def d(k):
f=52
h=range(f-1,-1,-1)
g=a(k)
for i,r in zip(range(f),g):
j=(f-1)-r%(f-i)
h[i],h[j]=h[j],h[i]
return h
def m(h):
l=["A23456789TJQK"[c/4]+"CDHS"[c%4]for c in h]
for i in range(0,len(h),8):
print" "," ".join(l[i:i+8])
if __name__=='__main__':
k=int(argv[1])if len(argv)==2 else 11982
print"Hand",k
e=d(k)
m(e)
```
## Code
```
import sys
import re
from tokenize import generate_tokens
from token import tok_name
from keyword import iskeyword
wr = sys.stdout.write
def pyparse(text):
'Return [TYPE,TOKEN] pair list'
# Use KEYWORD,NAME,NUMBER,OP,STRING,NL,NEWLINE,COMMENT,INDENT,DEDENT
rawtokens = generate_tokens(text.readline)
tokens = [[tok_name[n], t] for n,t,p1,p2,dx in rawtokens]
for tpair in tokens:
if tpair[0] == 'NAME' and iskeyword(tpair[1]):
tpair[0] = 'KEYWORD'
return tokens
def finduservars(filename):
'Return a set of user variables that we can replace with a-zA-Z'
varset = set()
for line in open(filename):
line = line.strip()
match = re.match(r'def\s+(\w+)\s*\((.*)\)\s*:', line)
if match:
func, args = match.groups()
varset.add(func)
arglist = re.findall(r'(\w+|=)', args)
for a in arglist:
if a == '=':
break # keyword args follow - too hard to parse
varset.add(a)
continue
match = re.match(r'(\w+)\s*=.+', line)
if match:
assigned = match.group(1)
varset.add(assigned)
continue
return set(v for v in list(varset) if len(v) > 1)
filename = sys.argv[1]
tokenlist = pyparse(open(filename))
# Build map for var->char conversion:
varset = finduservars(filename)
singles = [text for tok,text in tokenlist if tok=='NAME' and len(text)==1]
allvar = [chr(n) for n in range(97,123)+range(65,91)]
charvar = [c for c in allvar if c not in singles]
varreplaced = list(varset)[:len(charvar)]
varmap = dict((v, charvar.pop(0)) for v in varreplaced)
prev = 'NONE'
indent = ['']
output = []
add = output.append
for tok, text in tokenlist:
if tok == 'NL':
continue
elif tok == 'INDENT':
indent.append( text.replace(' ', ' ') )
output[-1] = indent[-1]
elif tok == 'DEDENT':
indent.pop(-1)
output[-1] = indent[-1]
elif tok == 'NEWLINE':
add(text)
add(indent[-1])
elif tok in 'KEYWORD,NAME,NUMBER':
if prev in 'KEYWORD,NAME,NUMBER':
add(' ')
if tok == 'NAME':
if output[-2] == 'while' and text == 'True':
add('1') # common verbose idiom
else:
add(varmap.get(text, text))
else:
add(text)
else:
add(text)
prev = tok
wr(''.join(output))
```
[Answer]
# sed, 1074 (down from 1390)
Very mild, low-hanging-fruit type of answer, to get the ball rolling:
```
/^$/d # Remove empty lines
/^[ <--TAB-->]*#/d # Remove whole-line comments
s/ /<--TAB-->/g # Replace 4 spaces with tabs
/^[^'"]*$/s/ *([|&:,<>=*/%+-]) */\1/g # Remove spaces before/after operators
```
Replace `<--TAB-->` with real `TAB` characters
Obvious shortcoming:
* Indents assumed to be exactly 4 spaces in input code.
Since we can assume no multi-line strings, then we only strip leading/trailing spaces from operators if there are no `'` or `"` on the given line. This could be improved, but <mumbles something about sed regex always being greedy>.
### Test as follows:
```
$ cat qs.py fizzbuzz.py cards.py | wc -c
1390
$ sed -rf pygolf.sed qs.py fizzbuzz.py cards.py | wc -c
1074
$ sed -rf pygolf.sed qs.py fizzbuzz.py cards.py | python
[-1, 0, 2, 3, 7, 8, 10, 57]
1
2
Fizz
...
98
Fizz
Buzz
Hand 11982
AH AS 4H AC 2D 6S TS JS
3D 3H QS QC 8S 7H AD KS
KD 6H 5S 4D 9H JH 9S 3C
JC 5D 5C 8C 9D TD KH 7C
6C 2C TH QH 6D TC 4S 7S
JD 7D 8H 9C 2H QD 4C 5H
KC 8D 2S 3S
$
```
[Answer]
# Python 3.4, 1134
This program should work alright for most programs. Strangely, Sp3000 test case is much easier to optimize for my program than your programs. Input is accepted through the file specified in the first argument. The actual file is modified.
```
import subprocess
from sys import argv
progamtext = open(argv[1]).read()
if 'argv' in progamtext or 'input' in progamtext or 'open' in programtext:#Make sure the program always produces the same results.
exit(0)
program = subprocess.Popen(['C:\Python27\python', argv[1]], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
program.wait()
erroroutput1 = str(program.stderr.read())
output1 = str(program.stdout.read())
program = subprocess.Popen(['C:\Python27\python', argv[1]], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
program.wait()
erroroutput2 = str(program.stderr.read())
output2 = str(program.stdout.read())
if erroroutput1 != erroroutput2 or output1 != output2:#Make sure the program always produces the same results.
exit(0)
newprog = ''
if erroroutput1:
newprog += "import sys\n" + "sys.stderr.write("+ erroroutput1 + ')'
if output1:
newprog += "\n"
if output1:
newprog += 'print ' + output1
if len(newprog) > len(progamtext):
exit(0)
open(argv[1],mode='w').write(newprog)
```
# How it works:
First, this program checks to see if your program interacts with the user at all or uses random. If it does, the program is unmodified.
Next, the program is ran. The program is then replaced with `print "output"`. Finally, if the program is shorter than its output, it is unmodified.
Sp3000's program, optimized:
```
import sys
sys.stderr.write(b'')
print b'0.540377721372\r\n3\r\n1\r\n7\r\n99\r\nf\r\n[5, 5]\r\n53\r\n53\r\n53\r\n'
```
Sp3000's super bonus program, optimized:
The optimized version is only off .001% of the time.
```
import sys
sys.stderr.write(b'')
print b'B\r\n'
```
] |
[Question]
[
## Background
[Manufactoria](http://pleasingfungus.com/Manufactoria) is a game about programming. The player must use a form of two-dimensional programming language to complete tasks. If you've never heard of it, the easiest way to learn is to try out the first few levels of the game.
## Challenge
Your challenge is to create a program which tests the primality of a number.
The input will be a series of N blue markers in the queue. If N is prime, then your program should accept it (move the robot to the finish). If N is composite, then your program should reject it (drop it on the floor somewhere).
## Submission Options
Since this is a more complex challenge than the typical Manufactoria challenge, I have decided to allow more ways to submit your answers.
**Vanilla**
I have created a 13x13 custom level to build and test submissions. The custom testing level is as follows.
>
> [13x13 custom level](http://pleasingfungus.com/Manufactoria/?ctm=Prime?;Input_is_a_series_of_N_blues.__Accept_iff_N_is_prime.;b:x|bb:*|bbbb:x|bbbbb:*|bbbbbbb:*|bbbbbbbbb:x|bbbbbbbbbbb:*|bbbbbbbbbbbbbbb:x;13;3;0;)
>
>
>
The game only allows 8 test cases on a custom level, but *your creation should be theoretically able to handle any natural number N, limited only by the available memory.* For informational purposes, the test cases provided in the custom level are as follows:
```
1 -> reject
2 -> accept
4 -> reject
5 -> accept
7 -> accept
9 -> reject
11-> accept
15-> reject
```
**Expanded Grid**
Some users may want more room than a 13x13 grid. Here is a link to an in-game 15x15 custom level, created by changing a number in the URL:
>
> [15x15 custom level](http://pleasingfungus.com/Manufactoria/?ctm=Prime?;Input_is_a_series_of_N_blues.__Accept_iff_N_is_prime.;b:x|bb:*|bbbb:x|bbbbb:*|bbbbbbb:*|bbbbbbbbb:x|bbbbbbbbbbb:*|bbbbbbbbbbbbbbb:x;15;3;0;)
>
>
>
Sadly, larger custom levels don't work, as the additional cells are inaccessible.
**The Manufactoria Esolang**
There has been an adaption of Manufactoria into an ASCII-based language. If you want a different way to design/test your creation, or if you are unable to fit your final solution onto the game board, you can use this esolang. You can find information on this esolang here:
>
> [Manufactoria esolang](http://esolangs.org/wiki/Manufactoria)
>
>
>
There are a few discrepancies between the esolang and the actual game. For example, conveyor crossings are handled differently. Try to avoid taking advantage of these discrepancies.
## A Faster Way to Test
The game is very slow when it comes to programs which take several thousands of steps to complete. My proof-of-concept solution took 28042 steps to reject 15. Even at the 50x speedup in-game, that simply takes too long.
I found this very helpful [website](http://www.xanthir.com/manufactoria/). Simply copy-paste the link to your answer, and you can test your answer with specific inputs. The 28042-step process took under a second.
One thing to note is that it will often say something like "incorrectly accepted" even if your machine worked properly. This is because the webpage only knows the test cases. For example, it would say that my solution "incorrectly accepted" the number 3, even though my machine was actually correct.
## How to Win
The scoring criteria is the number of parts (cells occupied). This is code golf, so the submission with the fewest parts wins.
For those interested, my benchmark solution has 96 parts and fits on the 13x13 grid. Finding a better algorithm could lead to colossal improvements, since I know I used a sub-optimal algorithm.
[Answer]
# 53 parts - 11x11 grid
I just learned to play Manufactoria 2 days ago, so it is probably not very golf-optimized, but at least it solves the problem. It implements trial division of course, via repeated subtraction. All divisors from 2 to N-1 are checked. The time complexity should be O(N^3), I believe.

[Solution Link](http://pleasingfungus.com/Manufactoria/?lvl=33&code=p12:11f7;p11:10f6;b11:9f3;g12:3f0;p11:3f4;p11:4f4;b11:5f3;r11:6f3;p12:7f3;b11:7f2;g12:8f3;q12:9f1;p11:11f7;p14:9f7;g13:10f1;q14:10f1;b13:8f3;p13:9f0;q15:12f3;g16:11f2;g16:12f1;p17:11f2;b17:12f1;r13:11f2;r17:10f0;g16:10f1;p16:3f2;b16:4f2;q16:5f7;p16:6f1;g16:7f1;q16:8f2;p16:9f1;p17:4f3;g17:5f0;b17:9f0;b13:4f2;b13:7f2;q14:3f5;p14:4f5;g14:6f3;p14:7f3;q14:8f6;g15:3f2;r15:4f0;p15:5f4;b15:6f0;r15:7f0;b14:11f3;p14:12f6;b17:6f0;b15:9f3;c15:10f2;&ctm=feersum11x11primes;;:x%7Cb:x%7Cbb:*%7Cbbb:*%7Cbbbbbbb:*%7Cbbbbbbbb:x%7Cbbbbbbbbb:x%7Cbbbbbbbbbb:x;11;3;0;)
I was very disappointed to have to use a conveyor belt :)
] |
[Question]
[
This question is similar to [Write a word equation solver](https://codegolf.stackexchange.com/questions/32475/write-a-word-equation-solver) by David Frank **but different in three important ways:** (1) David asked for just the first solution found, and I am asking for all the solutions. (2) I am asking to output the time required to solve the puzzle. And (3), it is a completely different undertaking to write a program designed to be fast compared with one designed to be short. A brute force method is probably best for code golf, but will not beat my ?amazing? time of 0.15 seconds. -I say "amazing" only to encourage other to try it out. I'm sure mine won't be the fastest.
(I'm going to copy a lot of the text from that question.)
**Introduction**
Consider the following example:
```
CODE
+ GOLF
——————
GREAT
```
This is an equation where each letter represents a decimal digit and the words represent natural numbers (similar letters represent similar digits and different letters represent different digits). The task is to match each letter with its digit value so that the equation is correct. **One of the four** solutions for the equation above is:
```
9265
+ 1278
——————
10543
```
**Your task**
Your task is to write a program or function to **find ALL of the answers** to such a word equation. Your program should output all the answers and the time it took to find them in seconds.
**Input**
The input will be something like this, two words added together to make a third word.
Example:
1. CODE+GOLF=GREAT
2. AA+BB=CC
Spaces are omitted and only letters between capital A and Z will be used (no special or small letters). This string can be read from the standard input, from a file, or as a function parameter.
**Output**
The output should look something like this. To take luck out of the competition, your program must list all the solutions.
```
time = XX.XXX seconds
(1) 9265+1278=10543
(2) 9275+1268=10543
(3) 9428+1437=10865
(4) 9438+1427=10865
```
**Rules**
1. **Similar letters represent similar digits and different letters represent different digits**
2. To make things easier, you can assume that numbers can or don't start with a leading zero, it's up to you. The four answers I got for the sample problem assume numbers do not start with leading zeros.
3. You can use any language and the standard library of the chosen language (no external libs)
4. You cannot connect to any resources on the internet (why would you anyways?)
5. So the goal here is speed, but of coarse that depends on what computer you use. In order to account for the different speed of different computers, you could run my example on your computer and then report how many times faster or slower yours is than my sample answer.
6. **Please explain how your code works.**
**Example in JavaScript**
<http://goo.gl/TdQczX>


[Answer]
# Python3, 0.03 seconds:
```
def f(a, b, r, c = {}, s = [], k = 0, l = [], A = [], B = []):
if not a and not b:
yield f"{''.join(map(str, A))}+{''.join(map(str, B))}={''.join(map(str, l))}"
return
for x in c.get(a[-1], range(10)):
if a[-1] in c or x not in s:
_c, _s = {**c, a[-1]:[x]}, s+[x]
for y in _c.get(b[-1], range(10)):
if b[-1] in _c or y not in _s:
n_c, v = {**_c, b[-1]:[y]}, k+x+y
n_s = _s+[y]
if a[:-1] and b[:-1]:
_v, _k = v%10, v//10
if [_v] == n_c.get(r[-1], [_v])and (r[-1] in n_c or _v not in n_s):
yield from f(a[:-1], b[:-1], r[:-1], {**n_c, r[-1]:[_v]}, n_s+[_v], _k, [_v]+l, [x]+A, [y]+B)
else:
if len(str(v)) == len(r):
F = 1
for J, K in zip(r[::-1], str(v)[::-1]):
if n_c.get(J, [int(K)]) == [int(K)] and (J in n_c or int(K) not in n_s):
n_c[J] = [int(K)]
n_s = n_s + [int(K)]
else:
F = 0
break
if F: yield from f(a[:-1], b[:-1], '', n_c, n_s, 0, [v]+l, [x]+A, [y]+B)
t = time.time()
result = [*f('CODE', 'GOLF', 'GREAT')]
print(time.time() - t)
print(result)
```
[Try it online!](https://tio.run/##jVRNb5tAEL3zK0aRKlhDHFu9REg@2I1dyWljKe0lQgiBvaTUeEELQaZWfrs7swu1G39yYHZnZ@a9eTuQ1@WvTHy@z@V2m6zyTJZQJituLHgMsRU6EDkgHZjDADbvDhRoPd@BJdqeA2mzHTZ2pCxzDQBIYhBZCSGEYqFWkXLjUyc8XUB8szHN7u8sEdYqzK2iRJghY@/2oXuE7sGhO0X3TVNT8vJNCtrEmYQ1JALm3VdeWqF320dmMhSv3Or3GGtZID91pkJBJRFL3BVtCD7B3IGAut50OrhUGa639kkLG@0uknBrSg80cHQKGP7hRy1@oAjULYGg@BCLjyAmlSZCy0gzqYnJ0l7b9ZEM4h0gzdo/OFTduwRP1xOp5SGoUqBCBei@q099vPLq7q7fOxqIJb2g8mEwILJKA6k1IDcjHO2gFoVuOajanpEtO05gb2RktqKpVGydhjVK3FhURqkktTQIitoIEgCX1IRmYqdo1749RFP79ogdoPK04O6pHlMuaPysijFqlbbyDPMJKtc/eUpDM3XgkRT4k@Soj6t70Qh6d6Z6w6nVG0t5iSitR@Yrcu1GXbI13RNeH1wn/m4CvakPu6qXE2gA6W1fl3Na9w@C9i4FRZKHS@OMYhP3/EyZpqM/OaTv0K/OOzI4/1c1jBKp0d@zSy@LGZIXbyk5vU5smV9mD2Osan6dfZso@zwe/jRRklySOHuJcAsla9y6BrtQ@8f46YFqfp89j7V9Gr9cW3u7/Qs)
[Answer]
# C++, 10000× faster (~20 µs)
```
#include <stdio.h>
#include <time.h>
#include <algorithm>
// digits
typedef int digit_t;
const digit_t BASE = 10;
typedef unsigned digit_mask_t;
inline char format_digit(digit_t d) { return '0' + d; }
// letters
typedef int letter_t;
const letter_t ALPHABETSIZE = 26;
typedef unsigned letter_mask_t;
inline bool is_letter(char c) { return unsigned(c - 'A') < 26u; }
inline letter_t parse_letter(char c) { return letter_t(c - 'A'); }
// terms
typedef int term_t;
inline term_t term_abs(term_t x) { return x < 0 ? -x : x; }
bool parse_formula(const char* formula, term_t coeffs[ALPHABETSIZE], letter_mask_t* ppresent, letter_mask_t* pleading) {
// Convert BA+BB=CCC into A + 21*B - 111*C = 0.
letter_mask_t present = 0, leading = 0;
const char* p = formula;
term_t side = +1, place = +1;
for (;;) {
const char* r;
for (r = p; is_letter(*r); ++r) {}
if (p < r)
leading |= letter_mask_t(1) << parse_letter(*p);
for (const char* q = r; q != p; --q) {
letter_t l = parse_letter(q[-1]);
coeffs[l] += place;
present |= letter_mask_t(1) << l;
place *= BASE;
}
p = r;
switch (*p++) {
case 0:
*ppresent = present; *pleading = leading; return true;
case '+':
place = +side; break;
case '-':
place = -side; break;
case '=':
if (side < 0)
return false;
place = side = -1;
break;
default:
return false;
}
}
}
struct Var {
digit_t value;
term_t coeff;
digit_t minval; // 0 or 1
letter_t name;
};
class Solver {
const char* formula;
letter_t num_vars;
Var vars[BASE];
void solve2(Var*, digit_mask_t, term_t, term_t);
public:
bool solve(const char* formula);
};
bool Solver::solve(const char* formula) {
this->formula = formula;
term_t coeffs[ALPHABETSIZE] = {0};
letter_mask_t present, leading;
if (!parse_formula(formula, coeffs, &present, &leading))
return false;
// sort the used letters by magnitude of their coefficient
letter_t letters[BASE];
letter_t num_vars = 0;
for (letter_t i = 0; i < ALPHABETSIZE; ++i) {
if (present & (letter_mask_t(1) << i)) {
if (num_vars == BASE)
return false;
letters[num_vars++] = i;
}
}
if (num_vars == 0)
return false;
this->num_vars = num_vars;
std::sort(letters, letters + num_vars, [&](letter_t a, letter_t b) { return term_abs(coeffs[a]) < term_abs(coeffs[b]); });
// initialize tables
term_t bounds[2] = {0};
for (letter_t i = 0; i < num_vars; ++i) {
vars[i].name = letters[i];
vars[i].minval = digit_t((leading >> letters[i]) & 1);
term_t coeff = vars[i].coeff = coeffs[letters[i]];
bounds[coeff > 0] += coeff * (BASE - 1);
}
// call the recursive solver
solve2(vars + num_vars - 1, 0, bounds[0], bounds[1]);
return true;
}
void Solver::solve2(Var* pos, digit_mask_t digits_used, term_t lower_bound, term_t upper_bound) {
term_t coeff = pos->coeff;
digit_t d = BASE - 1, e = pos->minval;
// adjust bounds to reflect a digit equal to BASE-1, instead of anything in [0,BASE)
if (coeff < 0)
upper_bound += coeff * d;
else
lower_bound += coeff * d;
do {
if (lower_bound <= 0 && upper_bound >= 0 && !(digits_used & (digit_mask_t(1) << d))) {
pos->value = d;
if (pos == vars) {
// print the solution
char digit_chars[ALPHABETSIZE];
for (letter_t i = 0; i < num_vars; ++i)
digit_chars[vars[i].name] = format_digit(vars[i].value);
for (const char* p = formula; *p; ++p)
putchar(is_letter(*p) ? digit_chars[parse_letter(*p)] : *p);
putchar('\n');
} else {
solve2(pos - 1, digits_used | (digit_mask_t(1) << d), lower_bound, upper_bound);
}
}
lower_bound -= coeff;
upper_bound -= coeff;
} while (--d >= e);
}
int main(int argc, char **argv) {
int code = 0;
for (int i = 1; i < argc; ++i) {
puts(argv[i]);
clock_t t = clock();
code |= !Solver().solve(argv[i]);
t = clock() - t;
printf("%f\n", double(t) / CLOCKS_PER_SEC);
}
return code;
}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVfBbttGED1Ll_7C2EUtUhQdyYeiMC0VtuqmRQ04iIMeqggCRa6kbSiS5pKO00Rf0ksuPfbUv-nXdGZ3uVwqEtCDIHJ2dnZm3szb4Z9_R3lSCfot1lH0-fNfVbnyv_v3K-9rnkZJFTO4EmXMs_PNpNuISr5lbUmYrLOCl5vtpNt98QJivual6JYfchazFfC0VKJFGXSjLBXmFW6uH25hDKNhYLSrVPB1ymKtsw3FO9rH04SnDKJNWMAqK7ZhuZAKTm0qduEjFKysihR6wx54EAewk_4krCxZ0XZIyRqP6ne4vnv10_XN7ZuHn38j1y6-PeCaVt7zbZllCXCxUKuOdDWyvKq3OxH40LvuuXCF5ivyUlswTuRhIdhRQ7WaMVQHitJtO0ySWC6qV_UXLoWj358t48_o1RC-B_8ZLuFZWu7KyJRPlPsqCR2VNXKtD1o2qM1HGVutxMzO5HzQTlof8rxggqXllwsJC2OertGnbgeDmmbpEyuoVrybm_F0OqXAMrhGhC9G_RtMwWg06k8Rq-F5t9MyBvoMWqNzpF16CbodO4AcZToIXNFRCI6lPQZvNECXwkg94zIqghME0r2WlQIX1WqBunlg1UK_QIw8r8BNO1TiK3ByzHPh4kun9uvTuJ0KZ4QVctWuhX7umlPssx_xxCLAvxN5su8_Kv86pqQS8sk29TjzR3NpraMBS-bgjVWwUlxn74hjiVKSuemPZS-ThALMpTv4IN7zMtoA-u152qMoFAyGl_TY6ecNQvopgH7eIKWfgro6y6JSvkkrPa-n7BiACLQAlgUL31lq_p6af1htrNUIHok-doJEqNPRx6_CRKjzjS1dJv5IiRub2IJhlZTK5P5-TNKui60lMKCohF-xwzE5NZc9hYkM0-6noFne8hQ1AgDsjiFgKYy6Dc5puMWtu6DbjZJQCHjIEmwfsn6gZQN7Y7VdPGGBoIzcoccZYTpHwVPGYxBk6cLBxf6gxc5149f_WFR5tUx4hLFL6pA7D1GGqzyVSsrRy8vjyhREueHCn2jJobY9RD6o93G4C46wg2EGVCDoT9pMZ9hNWR7Amdl3VlMVVckexIiNyJC2yg2DSphLQ8DyA2zDdcpLujqzFSnwQhnnEUe7FiZ6j8HhC7A0mUk-MItcSvHvqnWbEQNx1YSSgHTnnZmdre7mru5X0m2OU33uHizqTu1ure55lHpuCv4LW8MDiVMIWwFahYnTCBVIUWqXxcCk1TN6A5idzZtshIPmXl1aF525BHXFhHO6kPelyzndrq4ClCNqPEz4H3iThsuECVN1y6xKYzG7aErtKCQmnAYO2Wt8fk69C2ODOifIzaLqelzWNOA4NU1OJtYWFwEdSVq3GwK31Xbq95r0zU55mg5EKU1gKK8E9dYHR85rvrK_kymJwiSRNV6wqCoEf2Kq2wsES_GFRLFBh7YP6DrWJw3n5lFdRy2mR4qU3NMiB8VBkGeizUN68FxQu5lhJMneIwLyBCOr8ryWKVJpZwoN-5N90o1Blb7yn9VqmotlLsL490rUtQA4oxRslTCk91B5BuyxQgRxgQz5aIYjySGIRANh-gErH9HkKcyGA91l1DDKLX0XWa7byMToAcP-QQ0r4H2NODPdb2tdYW3C2ZmdFpho2YljJZW4wk64porYrblCpkTeXlSnQU0fKKZuJ_i1IqUrL-SEupEVU5U8S-WKHHfVKfS4R-Xqlv2fzaXubtuW3WlzfX2YT4l6UQbgWicdmxVxVKGDcn1QXpWk41hzX-7iKG07sD_NzXHK1kNdY6D3Nu0p0Q4IVZ0zXfyUTVmENjKfjiAzaDeAXfnqAD2x2fXgj83I0ao3S76D9xueMHB8X9YKpYu-FAjRbchThx7CYh0N1Cdbv48vTxJ8WokyOTSZq4tkhOJIoUgbLXrEtAiH9hO9kVNRkkXU7zQ2ymdHickqDqsnii0c91zNEvZWawsmsSSRrMOVc_rN6m16ilnNcHZhTukCfnvc3U9_eVi8un29eLidatbTBEWnYdDqm1l_Ov8zO53e_3Drvby_-3H88vXt9ZvTuV76Dw)
This is roughly 10,000 times faster than JeffSB's solver and 2,500 times faster than Ajax1234's solver on my machine on the problem `CODE+GOLF=GREAT`. The speed ratio varies widely with the problem. For `FIFTY+STATES=AMERICA`, the JeffSB/me ratio is 25,000, while for `CORRECTS+REJECTED=MATTRESS` it's about 25.
The algorithm is quite different. Neither JeffSB nor Ajax1234 explained theirs, but it appears they both do digitwise addition from right to left. This program converts a problem like `TO+GO=OUT` into a formula like \$-98 O + 10 G - 10 U + 9 T = 0\$, with the terms sorted by absolute value. For each term from left to right, for each possible value of that digit, it computes upper and lower bounds for the sum by assuming that every later digit is 0 or 9. If the bounds include 0 then it recurses.
Since it doesn't cost any time, this program supports a more general set of alphametics with arbitrarily many terms on both sides of the `=`, and subtraction as well as addition. It can very quickly solve problems like `NINETEEN+NINETEEN+TEN+TEN+TEN+TEN+NINE+NINE+NINE+NINE+NINE+ONE+ONE+ONE+...=THOUSAND` where there are 877 `ONE`s.
I tried computing slightly more sophisticated bounds, and rewriting the recursive function as an iterative one, but both changes only improved performance by 1-2%, and complicated the code, so I reverted them.
(Sources for example problems: [Mike Keith](http://www.cadaeic.net/alphas.htm), [Michael Hartley](https://www.dr-mikes-math-games-for-kids.com/cryptarithms.html))
[Answer]
# Python 3, <5ms
```
def solver(eqn, soln_format = "eqn"):
#get weights
weight = -1
weights = {}
for char in reversed(eqn):
if char=='=':
weight=1
continue
if char=='+':
if weight>0:
weight=1
else:
weight=-1
continue
if char not in weights:
weights[char] = 0
weights[char]+= weight
weight*=10
assert len(weights) <= 10
weights_sorted = list(weights.values()) + [0]*(10-len(weights.values()))
weights_sorted.sort()
_, order = zip(*sorted(zip(weights_sorted, range(10)), key=lambda x: abs(x[0]), reverse=True)) #abs sorted order
order_list = [num - sum(i<num for i in order[:idx]) for idx, num in enumerate(order)] #because indexes change
order_list = order_list[:len(weights.values())] #to ignore zeros
order_list.reverse() #to pop and append like a stack
for soln in backtrack(0, weights_sorted.copy(), order_list, list(reversed(range(10))), []):
weights_copy = weights.copy()
weight_soln_pair = [(weights_sorted[i],num) for i,num in zip(order, soln)]
assert sum(i*j for i,j in weight_soln_pair) == 0, "Major error"
final_soln = {}
for weight_val, soln_val in weight_soln_pair:
for char, weight in weights_copy.items():
if weight == weight_val:
final_soln[char] = soln_val
del weights_copy[char]
break
if soln_format == "eqn":
#CONVERT TO EQN
eqn_copy = eqn
for k, v in final_soln.items():
eqn_copy = eqn_copy.replace(k, str(v))
yield eqn_copy
elif soln_format == "dict":
yield final_soln
def backtrack(val, weights, test_order, remaining, soln):
#Check if end
if len(test_order)==0:
if val==0:
yield soln
return False
#Check if possible
if sum([i*j for i,j in zip(remaining, reversed(weights))]) + val < 0: #max
return False
if sum([i*j for i,j in zip(remaining, weights)]) + val > 0: #min
return False
#Backtrack for each digit
order = test_order.pop()
weight = weights.pop(order)
for i, num in enumerate(remaining):
del remaining[i]
yield from backtrack(val+num*weight, weights, test_order, remaining, soln + [num])
remaining.insert(i, num)
weights.insert(order, weight)
test_order.append(order)
return False
```
does pretty much the same as benrg's answer, but in python and does not remove the solutions with leading zeros
```
%%timeit -n 1 -r 1
print([*solver('CODE+GOLF=GREAT')])
```
---
```
['9428+1437=10865', '9438+1427=10865', '9265+1278=10543', '9275+1268=10543', '8653+0671=09324', '8673+0651=09324', '8643+0672=09315', '8673+0642=09315', '8612+0635=09247', '8632+0615=09247', '7642+0651=08293', '7652+0641=08293', '6918+0934=07852', '6938+0914=07852', '6918+0925=07843', '6928+0915=07843', '5928+0943=06871', '5948+0923=06871', '3857+0862=04719', '3867+0852=04719', '3612+0685=04297', '3682+0615=04297', '2918+0956=03874', '2958+0916=03874', '2918+0947=03865', '2948+0917=03865', '2846+0851=03697', '2856+0841=03697']
4.63 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
```
notebook [link](https://github.com/arrmansa/fast-word-equation-solver/blob/main/fast-word-equation-solver.ipynb)
] |
[Question]
[
The goal is to write a full program that emulates the Universal Machine from ICFP 2006 with the shortest code. The Universal Machine has a very simple instruction set explained [here](http://www.boundvariable.org/um-spec.txt). The emulator has to read a filename from command-line argument, and run the file as the program, so your language has to support command-line arguments and stdin/out in some way. The emulator has to complete the [sandmark](http://www.boundvariable.org/sandmark.umz) within a reasonable time (not decades).
Here's a short explanation of the instruction set:
>
> The machine has eight registers each holding an 32-bit unsigned integer.
>
> The machine holds an indexed set of arrays of 32-bit unsigned integer cells.
>
> Shortly speaking, the allocation instruction returns an opaque 32-bit uint which is the handle to the created array, which has a static size, and holds 32-bit uint elements.
>
> The 0'th array denotes the program. It is loaded from a big-endian file on startup.
>
> There is also an Instruction Pointer which points to a cell in the 0 array.
>
> On each step, an instruction is read from the cell the Pointer points to, and the Pointer is inceremented before anything is done.
>
> The 4 most significant bits represent the opcode.
>
> If the opcode is 13, then the next 3 bits represent the register, and the other 25 represent the number that is written into the said register.
>
> Otherwise the 9 least significant bits represent three registers, say, A, B, and C, where C is represented by the 3 least significant bits.
>
> Then depending on the opcode, the following happens:
>
> 0. A = B unless C == 0
>
> 1. A = B[C]
>
> 2. A[B] = C
>
> 3. A = B + C
>
> 4. A = B \* C
>
> 5. A = B / C
>
> 6. A = ~(B & C)
>
> 7. The emulator exits
>
> 8. B = allocate(C)
>
> 9. deallocate(C)
>
> 10. output a character from C to stdout
>
> 11. input a character from stdin into C
>
> 12. copy the array B into the 0 array and set the Pointer to C
>
>
>
I have written a needlessly complex but totally fast implementation (ab)using x86\_64 jitted assembly [(the fun starts in emit())](http://qp.mniip.com/p/ci), which would for sure help you if you misunderstand some of the Machine's aspects.
[Answer]
## PHP: 443 416 384 bytes
```
<?php @eval(ereg_replace('[U-Z]','$\0',strtr('for(Y=[unpack("N*",join(file($argv[1])))];;A|=0){{W=Y[V=0][++U]
C&&A=B
A=Y[B][C+1]
Y[A][B+1]=C
A=B+C
A=B*C
A=bcdiv(PB),PC))*1
A=~B|~C
die
B=++Z
unset(Y[C])
echo chr(C)
C=fgetc(STDIN);C=ord(C)-(C=="")
Y[0]=Y[B|0];U=C
X[W>>25&7]=W&33554431;}}',['
'=>';}if((W>>28&15)==V++){',A=>'X[W>>6&7]',B=>'X[W>>3&7]',C=>'X[W&7]',P=>'sprintf("%u",'])));
```
\*Revamped again\*. It's as small as I can possibly get it now. I kept some variables down the far end of the alphabet so that the regex that inserts the $ signs doesn't mangle the STDIN constant, so here's a little glossary:
* U: instruction pointer
* V: index of opcode that's currently being tested
* W: current instruction word
* X: the 8 general purpose registers
* Y: main memory (each block is 1-based, since that's how `unpack()` returns arrays)
* Z: id of next free memory block (will eventually overflow, but the sandmark only uses ~92 million)
* A,B,C are the registers of the current instruction as in the spec
Unsigned division is a subtle nuisance (the `*1` is needed to ensure that large numbers cast back to the correct int) but the rest of the arithmetic is easy to keep 32-bit by ORing the arithmetic register with 0 (`A|=0`) after each instruction.
---
I found this project really interesting but striving to minimize the character count made it slow and inelegant, so I also made a simple (not golfed) Java version, that can complete the sandmark in a few minutes instead of taking all day:
```
import java.io.*;
import java.util.HashMap;
public class UniversalMachine {
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("Program not specified.");
System.exit(1);
}
int[] program;
try (RandomAccessFile raf = new RandomAccessFile(args[0], "r")) {
program = new int[(int)(raf.length() / 4)];
for (int i = 0; i < program.length; i++) {
program[i] = raf.readInt();
}
}
HashMap<Integer,int[]> memory = new HashMap<>();
memory.put(0, program);
int nextMemKey = 1;
int[] R = new int[8]; // Registers
int IP = 0; // Execution Finger (Instruction Pointer)
loop: for (;;) {
int ins = program[IP++];
int op = ins >>> 28;
if (op == 13) { // Orthography
int A = (ins >> 25) & 7;
int num = ins & 0x01FF_FFFF;
R[A] = num;
} else {
final int A = (ins >> 6) & 7;
final int B = (ins >> 3) & 7;
final int C = (ins >> 0) & 7;
switch (op) {
case 0: // Conditional Move
if (R[C] != 0) R[A] = R[B];
break;
case 1: // Array Index
R[A] = memory.get(R[B])[R[C]];
break;
case 2: // Array Amendment
memory.get(R[A])[R[B]] = R[C];
break;
case 3: // Addition
R[A] = R[B] + R[C];
break;
case 4: // Multiplication
R[A] = R[B] * R[C];
break;
case 5: // Division
R[A] = (int)((R[B] & 0xFFFF_FFFFL) / (R[C] & 0xFFFF_FFFFL));
break;
case 6: // Not-And
R[A] = ~(R[B] & R[C]);
break;
case 7: // Halt
break loop;
case 8: // Allocation
// note: must use C before setting B, as they may be the same reg
memory.put(nextMemKey, new int[R[C]]);
R[B] = nextMemKey++;
break;
case 9: // Abandonment
memory.remove(R[C]);
break;
case 10: // Output
System.out.print((char)R[C]);
break;
case 11: // Input
R[C] = System.in.read();
break;
case 12: // Load Program
IP = R[C];
if (R[B] != 0) {
memory.put(0, program = memory.get(R[B]).clone());
}
break;
}
}
}
}
}
```
[Answer]
# Perl, 407
It looks like the question might seem too complex, actually it's very simple.
I'm still very new to perl though, anyway here it is
```
open$f,shift;binmode$f;push@{$m[0]},unpack'N',$b while read$f,$b,4;$z=2**32;while(){$o=$m[0][$p++];$a=\$r[$o>>6&7];$b=\$r[$o>>3&7];$c=\$r[$o&7];eval qw,$$a=($$b)if$$c $$a=$m[$$b][$$c] $m[$$a][$$b]=$$c $$a=($$b+$$c)%$z $$a=$$b*$$c%$z $$a=$==$$b/$$c $$a=$$b&$$c^($z-1) exit $$b=scalar@m;$m[$$b]=[] undef$m[$$c] print(chr$$c) $$c=ord(getc) $m[0]=[@{$m[$$b]}]if$$b;$p=$$c $r[$o>>25&7]=$o&33554431,[$o>>28].";";}
```
It runs really slow, probably 800x slower than the JITed x86\_64 one.
Also, a friend of mine made a [reference C implementation](http://bpaste.net/show/lL7B9rauFqeVNB0Df84V/)
[Answer]
# C, ~~924~~ ~~838~~ ~~825~~ ~~696~~ ~~646~~ 623
I store a "pointer" (byte-offset) in the register designated `b` in the instruction, and use whatever register designates an array in the pseudocode in the same manner (or reverse, rather, to reconstitute a pointer) to access that array later. Still need to try the test program...
*Edit:* added comments.
*Edit:* fixed instruction 12. change the pointer, not the instruction in memory. Count is with all comments, indents, and newlines removed.
*Edit:* It appears to be running now, assuming I'm interpreting the results correctly. :) The final realization was that the *0 array* is indeed referenced by the *handle* 0, which may be found in an uninitialized register. A very twisted little machine! :)
*Edit:* rewrote debugging apparatus to use `write` instead of `printf`.... The idea here is to *remove* bugs. :) *Edit:* `putchar()` and `getchar()` are also no-nos with `sbrk`. It now works, and appears quite fast.
```
#define O(_)*a=*b _*c;B
#define B break;case
#define U unsigned
U*m,r[8],*p,*z,f,x,*a,*b,*c;main(int n,char**v){U char
u[4];z=m=p=sbrk(4);f=n>1?open(v[1],0):0;\
while(read(f,u,4)){*m++=(((((*u<<8)|u[1])<<8)|u[2])<<8)|u[3];sbrk(4);}sbrk(4);\
for(;x=*p++,1;){c=r+(x&7);b=r+((x>>3)&7);a=r+((x>>6)&7);switch(x>>28){case
0:*c?*a=*b:0;B
1:*a=(*b?m+*b:z)[*c];B
2:(*a?m+*a:z)[*b]=*c;B
3:O(+)4:O(*)5:O(/)6:*a=~(*b&*c);B
7:return 0;case
8:*b=1+(U*)sbrk(4*(1+*c))-m;(m+*b)[-1]=*c;B
9:B
10:*u=*c;write(1,u,1);B
11:read(0,u,1);*c=*u;B
12:*b?memcpy(z=sbrk(4*(m+*b)[-1]),m+*b,4*(m+*b)[-1]):0;p=&z[*c];B
13:a=r+((x>>25)&7);*a=x&0x1ffffff;}}}
```
For little-endian only, there's a **611** character version.
```
#define O(_)*a=*b _*c;B
#define B break;case
#define U unsigned
U*m,r[8],*p,*z,f,x,*a,*b,*c;main(int n,char**v){U char
u[4];z=m=p=sbrk(4);f=n>1?open(v[1],0):0;while(read(f,u,4)){*m++=(((((*u<<8)|u[1])<<8)|u[2])<<8)|u[3];sbrk(4);}sbrk(4);for(;x=*p++,1;){c=r+(x&7);b=r+((x>>3)&7);a=r+((x>>6)&7);switch(x>>28){case
0:*c?*a=*b:0;B
1:*a=(*b?m+*b:z)[*c];B
2:(*a?m+*a:z)[*b]=*c;B
3:O(+)4:O(*)5:O(/)6:*a=~(*b&*c);B
7:return 0;case
8:*b=1+(U*)sbrk(4*(1+*c))-m;(m+*b)[-1]=*c;B
9:B
//10:*u=*c;write(1,u,1);B //generic
10:write(1,c,1);B //little-endian
//11:read(0,u,1);*c=*u;B //generic
11:read(0,c,1);B //little-endian
12:*b?memcpy(z=sbrk(4*(m+*b)[-1]),m+*b,4*(m+*b)[-1]):0;p=&z[*c];B
13:a=r+((x>>25)&7);*a=x&0x1ffffff;}}}
```
Indented and commented, with (extended) commented debugging apparatus.
```
//#define DEBUG 1
#include <fcntl.h> // open
#include <signal.h> // signal
#include <stdio.h> // putchar getchar
#include <string.h> // memcpy
#include <sys/types.h> // open
#include <sys/stat.h> // open
#include <unistd.h> // sbrk read
unsigned long r[8],*m,*p,*z,f,x,o,*a,*b,*c; // registers memory pointer zero file working opcode A B C
char alpha[] = "0123456789ABCDEF";
//void S(int x){signal(SIGSEGV,S);sbrk(9);} // autogrow memory while reading program
void writeword(int fd, unsigned long word){
char buf[8];
unsigned long m=0xF0000000;
int off;
for (off = 28; off >= 0; m>>=4, off-=4) {
buf[7-(off/4)]=alpha[(word&m)>>off];
}
write(fd, buf, 8);
write(fd, " ", 1);
}
int main(int n,char**v){
#ifdef DEBUG
int fdlog;
#endif
unsigned char u[4]; // 4-byte buffer for reading big-endian 32bit words portably
int cnt;
#ifdef DEBUG
fdlog = open("sandlog",O_WRONLY|O_CREAT|O_TRUNC, 0777);
#endif
z=m=p=sbrk(4); // initialize memory and pointer
//signal(SIGSEGV,S); // invoke autogrowing memory -- no longer needed
f=n>1?open(v[1],O_RDONLY):0; // open program
while(read(f,u,4)){ // read 4 bytes
*m++=(((((*u<<8)|u[1])<<8)|u[2])<<8)|u[3]; // pack 4 bytes into 32bit unsigned in mem
sbrk(4); // don't snip the end of the program
}
sbrk(4);
for(cnt=0;x=*p++,1;cnt++){ // working = *ptr; ptr+=1
c=r+(x&7); // interpret C register field
b=r+((x>>3)&7); // interpret B register field
a=r+((x>>6)&7); // interpret A register field
#ifdef DEBUG
{int i;write(fdlog,"{",1);for(i=0;i<8;i++)writeword(fdlog, r[i]);
write(fdlog,"} ",2);
}
write(fdlog, alpha+(x), 1);
write(fdlog, alpha+(x>>28), 1);
#endif
switch(o=x>>28){ // interpret opcode
case 0:
#ifdef DEBUG
write(fdlog, "if(rX)rX=rX\n", 12);
#endif
*c?*a=*b:0;
break; // Conditional Move A=B unless C==0
case 1:
#ifdef DEBUG
write(fdlog, "rX=rX[rX]\n", 10);
#endif
*a=(*b?m+*b:z)[*c];
break; // Array Index A=B[C]
case 2:
#ifdef DEBUG
write(fdlog, "rX[rX]=rX\n", 10);
#endif
(*a?m+*a:z)[*b]=*c;
break; // Array Amendment A[B] = C
case 3:
#ifdef DEBUG
write(fdlog, "rX=rX+rX\n", 9);
#endif
*a=*b+*c;
break; // Addition A = B + C
case 4:
#ifdef DEBUG
write(fdlog, "rX=rX*rX\n", 9);
#endif
*a=*b**c;
break; // Multiplication A = B * C
case 5:
#ifdef DEBUG
write(fdlog, "rX=rX/rX\n", 9);
#endif
*a=*b/ *c;
break; // Division A = B / C
case 6:
#ifdef DEBUG
write(fdlog, "rX=~(rX&rX)\n", 12);
#endif
*a=~(*b&*c);
break; // Not-And A = ~(B & C)
case 7:
#ifdef DEBUG
write(fdlog, "halt\n", 5);
#endif
return 0; // Halt
case 8:
#ifdef DEBUG
write(fdlog, "rX=alloc(rX)\n", 13);
#endif
*b=1+(unsigned long*)sbrk(4*(1+*c))-m;
(m+*b)[-1]=*c;
break; // Allocation B = allocate(C)
case 9:
#ifdef DEBUG
write(fdlog, "free(rX)\n", 9);
#endif
break; // Abandonment deallocate(C)
case 10:
#ifdef DEBUG
write(fdlog, "output(rX)\n", 11);
#endif
//putchar(*c);
//*u=u[1]=u[2]=' ';
u[3]=(char)*c;
write(fileno(stdout), u+3, 1);
break; // Output char from C to stdout
case 11:
#ifdef DEBUG
write(fdlog, "rX=input()\n", 11);
#endif
//x=getchar();*c=x;
read(fileno(stdin), u+3, 1);
*c=u[3];
break; // Input char from stdin into C
case 12:
#ifdef DEBUG
write(fdlog, "load(rX)[rX]\n", 13);
#endif
*b?memcpy(z=sbrk(4*(m+*b)[-1]),m+*b,4*(m+*b)[-1]):0;
p=&z[*c];
break; // Load Program copy the array B into the 0 array, Ptr=C
case 13:
#ifdef DEBUG
write(fdlog, "rX=X\n", 5);
#endif
a=r+((x>>25)&7);*a=x&0x1ffffff; // Orthography REG=immediate-25bit
}
}
}
```
] |
[Question]
[
It's me. Cave Johnson.
It's May 21st. You are working at Aperture Science, finest company on Earth, and tomorrow we're releasing Version 3.0 of our flagship windowing system (or *WindowS*): CavOS. Unfortunately, tomorrow morning, our chief competitor is releasing Version 3.0 of their *WindowS* too!
It's been leaked to me, Cave Johnson, CEO that the competing *WindowS* has one feature that CavOS lacks: A game of Klondike Solitaire. I, Cave Johnson, am concerned that this omission will lead to drastically lower sales. As such, I, Cave Johnson, have devised a competition between the programming interns to create a game of Solitaire. The programmer whose entry is chosen will get the opportunity to join the exciting GlaDOS AI project.
I, Cave Johnson, has a few requirements:
* Due to the fact that the Software must ship tomorrow, the **shortest program will be chosen** such that it can fit in the spare sectors of the already printed, imaged floppies.
* Don't worry about the gameplay. Our customers have printers don't they? All I need is for your program to **produce a list showing: The order of the cards in the deck, and the contents of each of the 7 piles. The deck will be dealt from the top. The piles will be visible from the bottom. Use the abbreviations H, D, C, S for Hearts, Diamonds, Clubs and Spades. Use the abbreviations K, Q, J, A for King, Queen, Jack, and Ace. Each card should be separated by a space. The first line should show the deck, the second the card of the first and smallest pile, the third the cards of the second pile and so on.** You are welcome to use T instead of 10 if you wish.
* We're making lemonade here - not sucking lemons. I, Cave Johnson, don't like losing, and neither do our customers. **Every game must be winnable**
* **The game must be randomised.** No attempting to encode a single game. There are 7000 trillion possible Klondike hands, and about 90% of them are winnable. I'd be happy with a program that can produce 256 or more different hands. If your language lacks a manner to get random numbers (from a timer or the like), then assume that you can get a seed in a manner appropriate for your language.
* Our customers are reasonably clever. **Assume for winnability that they're playing Draw 3, with no limits on times through the deck**
On behalf of everybody (and everything) at Aperture, I wish you all good luck. We're counting on you.
"*Caroline? How do I shut this damn thing off?*"
---
Out of character: assume the rules of Windows, Draw 3, Not-vegas solitaire. I've attempted to cross every t and dot every i, but ask if you've any questions. Good luck.
Example output:
```
5H AS 7C 8S QH ...
AH
JS 10S
JC JH 7C
9D AC 8D 7C
.
.
.
```
[Answer]
# Brainfuck - 1575 1365
I am horribly abusing the minimum number of unique deals. This will produce exactly 256 distinct outputs. It accepts one byte of input as its random seed.
```
,>++++[>++++++<-]<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>>[<+<<+>>>-]>[-]<
<-[>+<-]<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-]>[-]>[<<<+>>>-]>[-]+[>+<
+++++]>+++++[>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>
>+>>+>>+>>+>>+[<<]>-]>>>>>>>>>+>>+>>+>>+>++++++[>++++>>++++>>++++>>+++
+>>+++>>+++>>+++>>+++>>++++>>++++>>++++>>++++>>+++>>+++>>+++>>+++<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<-]>++++>>++++>>++++>>++++>>>>>>>>>>+>>+>>+>>
+>>+>>+>>+>>+[<<]>>[>+<-<+>]>[<+>-]<<+++++++++++[>>+>>+>>+>>+>>+>>+>>+
>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+>>+[<<]>>-]>>>>+>>++++
+>>++++++++++++++++>>>>+>>+++++>>++++++++++++++++>>>>+>>+++++>>+++++++
+++++++++>>>>+>>+++++>>++++++++++++++++>>>>+>>+++++>>++++++++++++++++>
>>>+>>+++++>>++++++++++++++++[<<]<<<<<<[>>>>>>+<<<<<<-]>>>>>>[>[<<+>>-
]<[>+<-]>>[<<+>>-]<-[>+<-]>]>.[-]>.[-]>[[<<<<+>>>>-]>]<<<<<[<<]<++++[>
++++++++<-]>.[-]<<<[>>>+<<<-]>>>[>[<<+>>-]<[>+<-]>>[<<+>>-]<-[>+<-]>]>
.[-]>.[-]>[[<<<<+>>>>-]>]<<++++[>++++++++<-]>.[<<<+>>>-]<<<<<[.[-]>.[-
]>.[<<+>>-]<<<<]>>[>+>++>++<<<-]++++++++++.>>+>+++<.>.<<<.>>----------
-----.+>.<<.>.+>.<<<.>>.+>.<<.>.+>.<<.>.+>.<<<.>>.>.<<.>++++++++++.>+.
<<.>---------------.+>.<<.>.+>.<<<.>>.+>.<<.>.+>.<<.>.+>.<<.>.+>.<<.>+
++++++++.>++++.<<<.>>---------------.+>.<<.>.+>.<<.>.+>.<<.>.+>.<<.>.+
>.<<.>.+>.<<<.>>+++++++++.>+++++++++++.<<.>---------------.+>.<<.>.+>.
<<.>.+>.<<.>.+>.<<.>.+>.<<.>.+>.<<.
```
Could definitely be condensed more, but that is kinda the nature of the language. This is quick and dirty, and it works.
Example output (input = 98):
```
8H 9S KS KH KD KC QS QH QD QC JS JH JD JC TS TH TD TC 9H 9D 9C 8S 8D 8C
AC
2C 3C
4C 5C 6C
7C AD 2D 3D
4D 5D 6D 7D AH
2H 3H 4H 5H 6H 7H
AS 2S 3S 4S 5S 6S 7S
```
It is fairly intuitive that all decks of this format are winnable.
] |
[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 7 years ago.
[Improve this question](/posts/8791/edit)
I'm very lazy so I try to always **program my microwave with the fewest possible button presses**. My microwave has the following buttons:
* A "minute plus" button which may only be pressed first and implies "start". It may be pressed multiple times for multiple minutes, but it will *not* add a minute to a manually entered time. **Output `+`**
* A set of 0-9 buttons. Time entry is MMSS (i.e. "130" means 1 minute 30 seconds). Seconds may range from 0..99. So "130" and "90" are equivalent entries. Obviously each minute is 60 seconds even if the seconds part of the entry exceeds 59. **Output `0`..`9`**
* A "start" button which must be pressed to start the microwave if the time is entered manually. **Output `S`**
My food packages **specify time in MM:SS** and so the program must accept that input.
### Examples
* 1:00 is `+` (remember "minute plus" implies start)
* 1:01 is `61S` (seconds can exceed 59, but "minute plus" does not work in conjunction with digits -- I think this is a design flaw in my microwave)
* 9:00 is `900S` (shorter than `+++++++++`)
[Answer]
## JavaScript
```
var x = /(\d+):(\d\d)/.exec('<time here>');
x[1] === '0' ? +x[2] + 'S' :
x[1] < 4 && x[2] === '00' ? (
x[1] === '1' ? '+' :
x[1] === '2' ? '++' : '+++') :
x[2] < 40 ?
(x[1] - 1 ? x[1] - 1 : '') + '' + (6 + +x[2][0]) + x[2][1] + 'S' :
x[1] + x[2] + 'S'
```
[Answer]
## APL
APL has a bad reputation that it's unreadable, which is totally not the case if it's not golfed.
The rules:
* Whole minutes <= 4 get +, ++, +++, and ++++
* 960-999 is preferred above 1000-1039. 9960-9999 is preferred above 10000-10039, etc.
* If the time can be rewritten such that the seconds are 66, 77, 88, or 99 then this is done. (This never gives a worse solution and usually gives a better one, i.e. 888 instead of 928.)
```
∇ Microwave;time;secs;mins;fmt;⎕ML
⎕ML←3
⎕←'Enter the time (m+:ss)'
time←⍞
mins secs←⍎¨(time≠':')⊂time
⍝ 'minute plus' can only be used on whole minutes ≤ 4
:If (secs=0)∧(mins≤4)
⎕←mins⍴'+'
:Return
:EndIf
⍝ If possible, save a keypress by using seconds > 60
⍝ if mins is a power of ten
:If (mins>0)
:If ((⌈10⍟mins)=(⌊10⍟mins))∧(secs<40)
⎕←('BI2'⎕FMT mins-1),(⎕FMT secs+60),'S'
:Return
:EndIf
:EndIf
⍝ For the 'finger movement' requirement we want as many
⍝ of the keypresses as possible to be of the same key.
⍝ So 888S i.p.v. 928S.
:If secs∊66 77 88 99-60
⎕←('BI2'⎕FMT mins-1),(⎕FMT secs+60),'S'
:Return
:EndIf
⍝ Otherwise, just output mmssS, there was no better alternative.
:If mins>0
⍝ output seconds with leading zero
⎕←('BI2'⎕FMT mins),('G⊂99⊃'⎕FMT secs),'S'
:Else
⍝ only output seconds, not with leading zero
⎕←('BI2'⎕FMT secs),'S'
:EndIf
∇
```
[Answer]
## Perl
meets the requirements, but it isn't how I would enter the buttons (e.g. "860S" vs "900S") handles exactly 60 seconds as a special case
```
use strict;
use warnings;
sub cook
{
my ($mins, $secs) = @_;
my $plus = $secs =~ /00/ ? $mins : undef;
my $secs_total = $mins * 60 + $secs;
my $mins_total = 0;
while ($secs_total > 99)
{
++$mins_total;
$secs_total -= 60;
}
$plus = "+" x $plus if defined $plus;
my $nums = "";
my $even = ($mins_total > 0 and $secs_total == 60);
$secs_total *= not $even;
$mins_total += $even;
if ($mins_total > 0)
{
$nums = sprintf "%s%02dS", $mins_total, $secs_total;
}
else
{
$nums = sprintf "%2dS", $secs_total;
}
return ($nums, $plus)
[defined $plus and length $plus < length $nums];
}
die "usage:$/\tperl $0 <MINUTES>:<SECONDS>$/"
unless @ARGV > 0 and shift =~ /([0-9]{1,2}):([0-9]{1,2})/;
print cook($1, $2), $/;
```
## Output
```
andrew@gidget:~$ perl mic.pl 9:00
900S
andrew@gidget:~$ perl mic.pl 1:00
+
andrew@gidget:~$ perl mic.pl 1:01
61S
andrew@gidget:~$ perl mic.pl 1:30
90S
andrew@gidget:~$ perl mic.pl 0:07
7S
andrew@gidget:~$ perl mic.pl 4:00
400S
```
[Answer]
## ruby
```
#Build a string for the microwave
def build_result(minutes, seconds)
duration = minutes * 60 + seconds
if duration < 99
result = "%iS" % [ duration] #shortcut '90S' instead '130S'
else
result = "%i%02iS" % [ minutes, seconds]
end
result
end
#Call microwave optimizer
def microwave( input )
minutes = input.split(/:/).first.to_i
seconds = input.split(/:/).last.to_i
#build result
result = build_result(minutes, seconds)
#try a shorter result, make 999S out of '10:39':
if seconds < 40 and minutes > 0
result2 = build_result(minutes - 1, seconds + 60) #try a
result = ( result.size <= result2.size ? result : result2 )
end
#Check if a version with only '+' is shorter
if seconds == 0 and minutes <= result.size
result = '+' * minutes
end
result
end
#Test if called with an argument
if ARGV.empty?
require 'test/unit' #Exceute a test
class MicrowaveTest < Test::Unit::TestCase
def test_007
assert_equal('7S', microwave('0:07'))
end
def test_100
assert_equal('+', microwave('1:00'))
end
def test_101
assert_equal('61S', microwave('1:01'))
end
def test_130
assert_equal('90S', microwave('1:30'))
end
def test_400
#~ assert_equal('400S', microwave('4:00'))
assert_equal('++++', microwave('4:00'))
end
def test_500
assert_equal('500S', microwave('5:00'))
end
def test_900
assert_equal('900S', microwave('9:00'))
end
def test_1000
#~ assert_equal('1000S', microwave('10:00'))
assert_equal('960S', microwave('10:00'))
end
def test_1015
#~ assert_equal('1015S', microwave('10:15'))
assert_equal('975S', microwave('10:15'))
end
def test_1039
#~ assert_equal('1039S', microwave('10:39'))
assert_equal('999S', microwave('10:39'))
end
end
else #started via shell, evaluate input
puts microwave(ARGV.first)
end
```
Remarks:
* Start it with `ruby program-my-microwave-oven.rb` and a unit test is evaluated.
* Start it with `ruby program-my-microwave-oven.rb 10:00` and it writes `960S`
Some remarks on the rules (and my interpretation):
* The shortest for `10:00` is `960S` (9 minutes and 60 seconds -> 10 minutes).
* The shortest for `10:39` is `999S` (9 minutes and 99 seconds -> 10 minutes and 39 seconds).
* for `4:00` it prefers `++++` (less finger movements)
] |
[Question]
[
It is easy to generate a fair coin using a unfair coin, but the reverse is harder to accomplish.
Your program will receive one number *X* (between 0 and 1, inclusive) as input. The input must not simply be hard-coded as a number in the middle of the source code. It must then return a single digit: a `1` with a probability of *X* and a `0` otherwise.
Your program is only allowed to use one form of random number generator in the source code: `int(rand(2))` (or an equivalent), which returns either a zero or a one with equal probability. You can include or access this function as many times as you wish in your code. You also have to provide the function yourself as part of the code.
Your program is not allowed to use any other random number generating functions or external sources (such as time and date functions) that could function as a random number generating function. It also cannot access any external files or pass the job along to external programs.
This is code golf, the shortest answer wins.
[Answer]
# Perl, 37 42 char
```
($d/=2)+=rand>.5for%!;print$d/2<pop|0
```
Takes arbitrary probability as a command line argument. Builds a uniform random number in `$d` and compares it to the input.
Earlier, 52 char solution
```
$p=<>;do{$p*=2;$p-=($-=$p)}while$--(.5<rand);print$-
```
[Answer]
## Python, 81 chars
```
import random
print(sum(random.randint(0,1)*2**-i for i in range(9))<input()*2)+0
```
Can be off by a bit, but never more than 1%.
[Answer]
# Mathematica 165
Not streamlined, but some may find the algorithm of interest:
```
d = RealDigits; r = RandomInteger;
f@n_ := If[(c = Cases[Transpose@{a = Join[ConstantArray[0, Abs[d[n, 2][[2]]]], d[n, 2][[1]]],
RandomInteger[1, {Length@a}]}, {x_, x_}]) == {}, r, c[[1, 1]]]
```
**Usage**
```
f[.53]
```
>
> 1
>
>
>
**Check**
Let's see if `f[.53]` really produces the value `1` around 53% of the time.
Each test calculates the % for samples of 10^4.
50 such tests are run and averaged.
```
Table[Count[Table[f[.53], {10^4}], 1]/10^4 // N, {50}]
Mean[%]
```
>
> {0.5292, 0.5256, 0.5307, 0.5266, 0.5245, 0.5212, 0.5316, 0.5345,
> 0.5297, 0.5334, 0.5306, 0.5288, 0.528, 0.5379, 0.5293, 0.5263, 0.539,
> 0.5322, 0.5195, 0.5208, 0.5382, 0.543, 0.5336, 0.5305, 0.5303,
> 0.5297, 0.5318, 0.5243, 0.5281, 0.5361, 0.5349, 0.5308, 0.5265,
> 0.5309, 0.5233, 0.5345, 0.5316, 0.5376, 0.5264, 0.5269, 0.5295,
> 0.523, 0.5294, 0.5326, 0.5316, 0.5334, 0.5165, 0.5296, 0.5266, 0.5293}
>
>
> 0.529798
>
>
>
**Histogram of results**

**Explanation** (spoiler alert!)
The base 2 representation of .53 is
>
> .10000111101011100001010001111010111000010100011110110
>
>
>
Proceeding from left to right, one digit at a time:
If RandomInteger[] returns 1, then answer = 1,
Else If second RandomInteger[] returns 0, then answer = 0,
Else If third RandomInteger[] returns 0, the answer = 0,
Else....
If, when all digits have been tested, there is still no answer,
then answer = RandomInteger[].
[Answer]
# Haskell, 107 chars:
```
import System.Random
g p|p>1=print 1|p<0=print 0|1>0=randomIO>>=g.(p*2-).f
f x|x=1|1>0=0.0
main=readLn>>=g
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
RandomInteger[]/.⌈1-2#⌉:>#0@Mod[2#,1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n1aap2D7PygxLyU/1zOvJDU9tSg6Vl/vUU@Hoa6R8qOeTis7ZQMH3/yUaCNlHcNYtf8BRZl5JdHO@aVAMiQxKSc1GmhEtIGeuWmsjqGBAZCIjf0PAA "Wolfram Language (Mathematica) – Try It Online")
This is a recursive approach. Ungolfed, the algorithm is:
* If the input probability `p` is less than 1/2, then when the coinflip comes up 0, return 0. Otherwise, recurse on `2p`; assuming correctness, the overall probability of getting 1 is half of `2p` or `p`.
* If the input probability `p` is greater than 1/2, then when the coinflip comes up 1, return 1. Otherwise, recurse on `2p-1`; assuming correctness, the overall probability of getting 0 is half of `1-(2p-1)` or `1-p`.
To make it shorter, we start with the random coinflip, which, in either branch, gets returned half the time. If the coinflip does not match the case when we're supposed to return it, replace it by the result of recursing on `2p` modulo 1. (That is, when `p` is less than 1/2, replace 1; when `p` is greater than 1/2, replace 0. This is equivalent to replacing `⌈1-2p⌉`.)
] |
[Question]
[
## Background
An **interval graph** ([Wikipedia](https://en.wikipedia.org/wiki/Interval_graph), [MathWorld](https://mathworld.wolfram.com/IntervalGraph.html), [GraphClasses](https://www.graphclasses.org/classes/gc_234.html)) is an undirected graph derived from a set of intervals on a line. Each vertex represents an interval, and an edge is present between two vertices if the corresponding intervals overlap. The following is an example interval graph with corresponding intervals.

Multiple linear-time algorithms exist that can determine whether a given graph is an interval graph or not. Many other graph-theoretical problems are also solvable in linear time for these graphs. Refer to the Wikipedia and GraphClasses links for details.
Note that you don't need to meet linear time complexity in this challenge.
## Challenge
Given an undirected, connected, loop-free, nonempty graph as input, determine if it is an interval graph. ("loop-free" means that the graph does not contain any edge that goes from a vertex to itself.)
A graph can be taken as input using any standardized structures for an undirected graph, which include
* an adjacency matrix / adjacency list / incidence matrix, and
* an edge list (a list of `(vi, vj)` pairs).
If you use adjacency list or edge list, you may assume that the vertices are numbered consecutively (0- or 1-based). For all input methods, you can optionally take the number of vertices as the second input.
For output, you can choose to
* output truthy/falsy using your language's convention (swapping is allowed), or
* use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
The test cases are given as edge lists with 1-based vertex numbering.
### Truthy
```
[(1,2)]
[(1,2), (1,3), (2,3)]
[(1,2), (1,3)]
[(1,2), (1,3), (2,3), (3,4), (4,5), (4,6), (5,6)]
[(1,2), (1,3), (2,3), (2,4), (3,4)]
[(1,2), (1,3), (1,4), (1,5), (1,6), (2,3), (3,4), (4,5), (5,6)]
```
### Falsy
```
// contains a 4-cycle without chord
[(1,2), (1,3), (2,4), (3,4)]
[(1,2), (1,3), (2,3), (2,4), (3,5), (4,5)]
// contains an asteroidal triple (1, 4, 6)
[(1,2), (1,3), (2,3), (2,4), (2,5), (3,5), (3,6), (4,5), (5,6)]
```
[Answer]
# [Sage](https://www.sagemath.org/), 17 bytes
```
Graph.is_interval
```
[Try it on Sage Cell](https://sagecell.sagemath.org/?z=eJxzL0osyNDLLI7PzCtJLSpLzNFwB4loRGsY6hhp6igAKWMIZQKhTCGUGYgygsgZQ-RMIHKmQLlYTU0ANLYUaw==&lang=sage&interacts=eJyLjgUAARUAuQ==); [documentation](https://doc.sagemath.org/html/en/reference/graphs/sage/graphs/generic_graph.html#sage.graphs.generic_graph.GenericGraph.is_interval)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 17 bytes
```
Œ!⁹ịⱮ;ⱮrḊɗ/€ẎḟƊ€Ạ
```
[Try it online!](https://tio.run/##y0rNyan8///oJMVHjTsf7u5@tHGdNRAXPdzRdXK6/qOmNQ939T3cMf9YF5i54L/Ow537rB81zFHQtVN41DDX@vByoMChpVxuD3c2HF7O9XD3lqOTwg63qwCVR/7/r6SkFK1hqGOkGcsFoXUUgJQxiDICUmii2BUBKWMdExBlomMKocxAlCmQwqnDCKIDpBFTjSFE0hBinCHEOKxW4bIDj@HoDjCFGUdIqRFEqTGMMkN3BzAw/xNvGwA "Jelly – Try It Online")
A dyadic link which takes the number of vertices as the left argument and the adjacency list as the right argument and returns 0 for an interval graph and 1 for not. This tests every possible ordering of vertices.
Uses the fact that iff the graph is an interval graph, there exists an ordering of vertices where if \$v\_i\$ and \$v\_k\$ are adjacent then all \$v\_j\$ where \$i<j<k\$ must also be adjacent to \$v\_i\$, as per the [Mathworld article](https://mathworld.wolfram.com/IntervalGraph.html).
Full explanation to follow.
---
# Original solution that assumes vertices are appropriately ordered
## [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
;ⱮrḊɗ/€Ẏḟ
```
[Try it online!](https://tio.run/##y0rNyan8/9/60cZ1RQ93dJ2crv@oac3DXX0Pd8z//3DnPutHDXMUdO0UHjXMtT7cDhRQ4Xq4e8vRSWGH21WACiP//1dSUorWMNQx0ozlgtA6CkDKGEQZASk0UeyKgJSxjgmIMtExhVBmIMoUSOHUYQTRAdKIqcYQImkIMc4QYhxWq3DZgcdwdAeYwowjpNQIotQYRpmhuwMYmP@Jtw0A "Jelly – Try It Online")
A monadic link taking an ordered adjacency list as its argument and returning an empty list (falsy) if the argument represents an interval graph and a non-empty list (truthy) if not.
## Explanation
```
ɗ/€ | For each edge do the following as a dyad with the first vertex as the left argument and the second as the right:
;Ɱ | - Concatenate the first edge to each of:
r | - The range of integers from first vertex to second vertex inclusive
Ḋ | - Remove the first item (which will be [first vertex, first vertex])
Ẏ | Join outer lists together
ḟ | Remove all edges found in the original list
```
] |
[Question]
[
## Input
A string S of length between 2 and 30. The only letters in the string will be `a` or `b`.
## Output
All strings within [Levenshtein](https://en.wikipedia.org/wiki/Levenshtein_distance#:%7E:text=Informally%2C%20the%20Levenshtein%20distance%20between,considered%20this%20distance%20in%201965.) distance 2 of S. You must output all the strings without duplicates but in any order you like.
## Example
If `S = aaa` then the output would be (in any order):
```
aa
abab
ab
aabba
aaaa
abaa
bbaaa
aba
bbaa
babaa
bba
abaaa
abaab
baaa
baab
baaaa
baba
aabaa
ba
abba
aaba
aabb
abbaa
abb
aabab
aaaaa
aaaab
baaba
a
aaaba
aaabb
aaa
aab
ababa
aaab
bab
baa
baaab
```
## Constraints
Your code must be fast enough that it would run to completion on TIO when S is of length 30. This is only to stop brute force solutions.
[Answer]
# [Haskell](https://www.haskell.org/), ~~115~~ 109 bytes
* -6 thanks to Unrelated String
```
import Data.List
f=nub.(=<<)g.g
g=(=<<)h.(zip.inits<*>tails)
h(x,y)=[x++b++c|b<-["a","b",""],c<-[y,drop 1 y]]
```
[Try it online!](https://tio.run/##PU7LboMwELz7K1YoUqA81KpXk0t77B9EHHbBASsOIOyoUPXfqb1uItnWzHhmdge0V2XMvuvbPC0OPtFh9aWtE5d6vFOV1lJmfdWLvmY4VOmPnis9amfly8mhNjYTQ7oWW1af1zynPG9/SZbnBJMiIX@Tpmg934pumWZ4g61p9hvqEWroJgGg1lm1TnUgS0itX6L6npbOZvJw6pX7mEanRme90SgH2Lo7Gh8NRjjABRJETKAsFzUb3aJT8P4KRzz6wLzoMZgeofo5a0cUSEgiHCTyDKOEwrMIGQl6iPwbXxIMnyi6QhND8d8YH2LKImvEs@JEjgdbYHELdnGQN4xa6Bex3LM/ "Haskell – Try It Online")
Explanation:
```
f :: String -> [String]
f=nub -- delete duplicates
.(=<<)g -- apply g to every result (get all words with distance <= 2)
.g -- apply g once to the input (get all words with distance <= 1)
g :: String -> [String]
g=(=<<)h -- apply h to every split and flatten the resulting list
.(zip.inits<*>tails) -- split the string at every possible position
{- |
h takes a pair of Strings (x,y the input split at some point) and returns all
combinations of x, one of a, b or nothing, and y with the first letter present
or removed
("he","llo") -> ["heallo","healo","hebllo","heblo","hello","helo"]
drop 1 is basically the same as tail with the difference that drop 1 [] returns
[] instead of throwing an error
-}
h :: (String,String) -> [String]
h(x,y)=[x++b++c|b<-["a","b",""],c<-[y,drop 1 y]]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 66 bytes
```
⊞υθ≔⟦θ⟧ηFη«≔⟦⟧ζFLιFabF³⊞ζ⭆ι⎇⁻ξκν…⁺λνμFab⊞ζ⁺ικFζ¿¬№υκ«⊞υκ¿⁼ιθ⊞ηκ»»υ
```
[Try it online!](https://tio.run/##PY8xbsMwDEVn@xREJhJQp4yZAqNbUxhotqIDYziWEFWKZatoHOTsCq3a1STqfT2SjebQeLYp1XHQGBX0tCv3w2A6h5/9lwIt9dkHQE1wL4sVCZmEFBm9ta4bNRoiyPWGT5vluiXI5knBxxiM6w58RaPg2AbH4YYH4@KAvwoupMApqG6NbSvtr1hbAVYeBXyTnLXbn3215piZ//8HJgJzBnz3I1Y@unFeS3Cev1j3vMzxYs699pFtdvS0ePXCH@WjrGVqUdAuJWZOLz/2CQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υθ
```
Push the input to the predefined empty list as the first result.
```
≔⟦θ⟧ηFη«
```
Start a breadth-first search using the input.
```
≔⟦⟧ζ
```
Start collecting potential new results.
```
FLιFabF³
```
Loop over each index, each potential insert/edit, and each operation (0=delete, 1=edit, 2=insert).
```
⊞ζ⭆ι⎇⁻ξκν…⁺λνμ
```
Apply the specified operation to the appropriate index of the current string.
```
Fab⊞ζ⁺ικ
```
Also consider appending either of `a` and `b` to the current string.
```
Fζ¿¬№υκ«
```
For each string that has not been seen before, ...
```
⊞υκ
```
... push it to the result string, ...
```
¿⁼ιθ⊞ηκ
```
... and if we're modifying the original input then also push it to the search space.
```
»»υ
```
Finally print all the results.
[Answer]
# [Python 2](https://docs.python.org/2/), 113 bytes
Takes input as a singleton list containing the string.
```
s="{k[:i]+c+k[i+w:]for k in %sfor i in range(len(k)+1)for c in['','a','b']for w in(0,1)}"
print eval(s%s%input())
```
[Try it online!](https://tio.run/##HctBCsMgEIXhfU8hARnFLJouAz2JuJgG2w6GiahpKKVnt9rFg58PXnyX58aXWvN1@AQ7kzOLCZbMMbv7lkQQxELmntQzIT@8Wj2roM2kuy/NLcAI2HaD/@1ops7jpL/DKSbiIvwLV5VllsRxL0rrWi0gIrgf "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 114 bytes
```
f=lambda s,d=2,i=0:d*s[i-1:]and{k[:i]+c+k[i+w:]for k in f(s,d-1)for c in['','a','b']for w in(0,1)}|f(s,d,i+1)or{s}
```
[Try it online!](https://tio.run/##LY5BjoMwDEX3nMLqxjEEqTC7SOlFEIu0IR2LTqgSpKpiODtjmC4sW9/v2//5nr@n@LVtwT7cz9U7yNrbVrM9G1/mjuvG9C76ZewM99WtGjuuXqYPU4IROEJQYqgb2oWbCB2iRid1xQN6iabOuqH190A1Vw1NacnrlsECOofFM3GcZQlYX1BDntI8ePVpQQnjkEjDOLztY4hExcciw/6D9yDJxfugWg1tQ6YA@CfCaWHT@rWUTFBfYBH/cRJLJlohz4Ld84m2Pw "Python 3 – Try It Online")
**Commented**:
```
f=lambda s,d=2,i=0: # a recursive function with arguments:
# - s, the input string
# - d, the maximal Levensthein distance to s
# - i, the index of the current operation
d*s[i-1:]and ... or{s} # if d==0 or i>len(s) return a set containing s
# otherwise:
{k[:i]+c+k[i+w:] # apply an operation
for k in f(s,d-1) # on every string with maximal Levensthein distance d-1
for c in['','a','b'] # insert / replace with any of '', 'a', 'b'
for w in(0,1)} # w==0: c=='': no operation, c!='': insertion
# w==1: c=='': deletion, c!='': replacement
| f(s,d,i+1) # union this to the result of applying an operation at a larger index
```
[Answer]
# JavaScript (ES6), ~~137 134 131~~ 123 bytes
Expects a string with `0`/`1` instead of `a`/`b`. Returns an Object whose keys (and values) are the output strings.
```
f=(s,k=2,o={},p='')=>[...o[s]=s].map((c,i)=>k&&[p+(q=s.slice(i+1)),p+(C=c^1)+q,(p+=c)+0+q,p+1+q,C+s].map(s=>f(s,k-1,o)))&&o
```
[Try it online!](https://tio.run/##XZBta4MwEMff91McMjQh11TtnkuEUfZusA/gHE2zaG1dYo0MRvGzu1g2GH1xD/z5c7@728sv6VRXt/3c2A89jqUgDg8iRStOA7YiiqjIcs65zV0hXME/ZUuIwtrLhzDMW0aOwnHX1EqTmiWUopfWQr0nlB2RtEwoymLftizxec1@ZziRlRNqnqCllIahHVc5pAhLhGuEG4RbhDuEe4QHhCRGSH0sYyh4abtnqXbEgMjgNANQ1jjbaN7YimxetKn6HVydzADzzNfX7V6rnh/0tyMlCeKAd7rVsifGc3lztg/g@q42ldvQ1Wzw8X9k8GaemubPAR4PkZQyegwujJekOA484XzttKqbwI30j1rwRYWgJjGS2yhXhV9lNf4A "JavaScript (Node.js) – Try It Online")
### Commented
This is a naive and rather lengthy implementation that just builds all the strings recursively.
```
f = ( // f is a recursive function taking:
s, // s = input string
k = 2, // k = counter
o = {}, // o = an object used to store the results
p = '' // p = current prefix
) => //
[...o[s] = s] // save s into o and split s
.map((c, i) => // for each character c at position i in s:
k && // abort if k = 0
[ // otherwise, build an array:
p + // remove c by concatenating the prefix p
(q = s.slice(i + 1)), // with the suffix q
p + (C = c ^ 1) + q, // modify c
(p += c) + 0 + q, // insert '0' after c (and update p)
p + 1 + q, // insert '1' after c
C + s // prepend the modified c at the beginning
// (this case is not covered by the insertions)
] // end of array
.map(s => f(s, k - 1, o)) // do a recursive call for each string in there
) // end of map()
&& o // return o
```
[Answer]
# [Ruby 2.7](https://www.ruby-lang.org/), ~~115~~ 109 bytes
*Port of [ovs](https://codegolf.stackexchange.com/users/64121/ovs)'s answer in [Python](https://codegolf.stackexchange.com/a/216310/83605)!*
```
f=->s,d=2,i=0{d>0&&s[i-1]?['',?a,?b].product(f[s,d-1],[0,1]).map{_2[...i]+_1+"#{_2[i+_3..]}"}|f[s,d,i+1]:[s]}
```
[Try it online!](https://tio.run/##HYtBDoIwEEX3nGICiVUYJoWlCXABb9B0UUF0QlRCIUbbnh3RzX@L9/60nN/r2ld5bbGrSuRKuq6Wu51VnBe6UUJgY7A5axqnZ7e0875XW7o5VBILfaC7GZ1vccCXH5QkItZZm8WJGxRnL6ItDXHw/xtyVuijsjqsJS3j/NyX8gAOPPsIxmW2EJ8uj@t8g8RxgLze2CthRMqaLH8uIY5CFP3K/8BPGiM0pCAQxPoF "Ruby – Try It Online")
TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves 3 bytes, and we've begin-less `...i` and end-less `i+_3..` ranges, which saves 3 more bytes!
[Answer]
# [Haskell](https://www.haskell.org/), 89 bytes
```
import Data.List
nub.(g=<<).g
g(h:t)=t:((:)<$>"ab"<*>[h:t,t])++map(h:)(g t)
g _=["a","b"]
```
[Try it online!](https://tio.run/##DcpBDoMgEADAO6/YbDxAtTyAgKce@wNjmsVUJBUksv1@qdfJbFQ/731vLaZynAwPYtLPWFmsLn@9lsFZq3QQQW6GlWMjpVG2G5E82ts4XTrwrPo@UbmKkgFYiQAvNyHhgB7nlihmcFDOmBk6WAGJCNtvWXcKtd2XUv4 "Haskell – Try It Online")
The helper function `g` recursively generates all strings at Levenshtein distance 1.
[Answer]
# [K (ngn/k)](https://git.sr.ht/%7Engn/k), 78 bytes
```
{?"ab"@?,/e'e"b"=x}
e:{?,/(~+x==#x;{y,x,z}.',/0 1,/:\:(0,'!1+#x)_\:x;x_/:!#x)}
```
[Try it online!](https://ngn.bitbucket.io/k#eJw9T0EKgzAQvPsKuxaMGBq9ZhH7DxVNQKG0UBAPa0Xf3mA2XjKZ3cnMZNJbDcbCs5ZqTEewUNEejW4qlThyqqqEcFslyd/+SKUq4lIq3WpRyPRW5gllfasJqVf65sgeRYve7s16zHqKCYfvG8UwmdcHCVecs26PlgaMMYDCA1h7nq4EuiZ+dG14xcNT4u+n2PNAPLDPuWFgnbm8WemRM00wup5dHUKJ0CLYWI+cHuKDOf+HG4QobsSBDiUYyLo/+slwsQ==)
] |
[Question]
[
First, a mathematical interlude, short, and worth your while:
If `0 < a < 4`, the *logistic function* `f(x) = ax(1-x)` maps the interval [0,1] inside itself. This means that one can play the iteration game; for instance, if a=2, the initial value 0.3 becomes 0.42, then 0.4872, etc.
As the parameter `a` increases, the quadratic function `f` becomes more complicated in the following sense:
* `0 < a < 1` all initial values iterate toward 0.
* `1 < a < 3` 0 becomes repelling, but there is a new fixed point (a-1)/a that attracts all iterations.
* `3 < a < 1+sqrt(6)` the new fixed point becomes repelling, but a cycle of 2 attracting points appears.
* `3.44949... < a < 3.54409...` the 2-cycle becomes repelling, but a cycle of 4 attracting points appears.
* etc.
Feigenbaum noticed that the lengths of these parameter intervals decrease at a rate that gets closer and closer to `4.6692...`, the **Feigenbaum constant**. The wonderful discovery is that this period 2 *bifurcation* sequence is a general phenomenon shared by any function that (like the quadratic parabola) is increasing, then decreasing. This was one of the first reports on the *universality of chaos*.
Now for the challenge! Write the shortest possible code that *computes* the Feigenbaum constant to an accuracy of your choice. The point here is **not** to cheat the system by encoding a number that you googled, but to actually have the computer find the value. For reference, here is the constant to 30 digits:
**4.669201609102990671853203821578**
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 79 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410)
```
⊃⊃{⌽u,a,c÷u←b-⍨a←⍺{⍵-÷/⍵{(⍺-×⍨⊃⍵),1-2××/⍵}⍣⍺⊢0}⍣≡b+c÷⊃e b c←⍵}/(⌽2*1+⍳17),⊂*3↑1
```
[Try it online!](https://tio.run/##XU47SwNBEO7zK67M49bszN7u3Ba21sF/cBeNTUCbFHKkUYjmcEULuUrw0djLERCs9p/MH7nMpREchnnwPWaKq6U6uy6WlxcdP76cnEqZzXjzBJhTYrIB398tOq5vJSt@@F2lRTqPu5UwSsXhq5CBw0/FoVVxN5VWDWVXsRGwl4V2lILC2MSmR9ccPgXn@kMfxu17ORE/YZ4nZTI/uLXr6VBO4RgmHL6BRinXN2PDm2fo5J1uMeDwmh0551GD0x40eq8dQW4NapMjWMp7zvFf8Pbtn0pTllm0zpIoDBFajx7I7QE "APL (Dyalog Unicode) – Try It Online")
Outputs **4.669201609**074452565738237725929176 (10 digits). You can increase the number 17 near the end to get more correct digits; the largest number that fits within 1 minute of TIO is 22, which gives **4.6692016091029**76931847851885076037 (14 digits).
Dyalog APL has 128-bit floating point numbers, which gives more precision needed to get closer to the constant. Otherwise, the number simply diverges after certain number of iterations.
The algorithm itself is the same as [this Python sample code](http://code.activestate.com/recipes/577464-feigenbaum-constant-calculation/), which was already referenced in [Thomas W's JS answer](https://codegolf.stackexchange.com/a/126570/78410) and others.
### Ungolfed with comments
```
func←{
i←⍺ ⍝ Input: ⍺ ← iterations of inner-inner loop
e b c←⍵ ⍝ Input: ⍵ ← d, a_1, a_1-a_2
a←b+c÷e ⍝ Initial value of a ← a_1+(a_1-a_2)÷d
g←{ ⍝ One iteration of a:
x y←0 ⍝ Initialize x, y to 0
h←{ ⍝ One iteration of x,y:
x y←⍵ ⍝ Extract x,y
y←1-2×x×y ⍝ Next value of y
x←⍺-x×x ⍝ Next value of x (here ⍺ is outer a)
x,y ⍝ Return x,y
}
x y←⍵ h⍣⍺⊢x y ⍝ Iterate h ⍺ times (here ⍺ is outer i)
⍵-x÷y ⍝ Return next value of a
}
a←i g⍣≡ a ⍝ Iterate g until a does not significantly change
(c÷a-b),a,a-b ⍝ Return next value of d, a_1, a_1-a_2
}
⍝ Reduce from right over iteration counts starting with (2.7,1,1) and
⍝ extract the value of d
⊃⊃ func/ (⌽2*1+⍳17),⊂*3↑1
```
[Answer]
## Javascript, ~~141~~ ~~138~~ ~~135~~ 131 bytes, 8 digits
It's something I guess. It should be improveable quite a bit. If anyone needs a start: [how to calculate Feigenbaum](http://keithbriggs.info/documents/how-to-calc.pdf). And if you rather want to know how to do it code-wise, check out [this](http://code.activestate.com/recipes/577464-feigenbaum-constant-calculation/).
Copy paste the following code in your console. Calculates **4.6692016***68823243* (so not really precise).
```
b=1;c=0;e=3.2;for(i=2;i<13;i++){z=b-c;a=b+z/e;j=4;while(j--){x=y=0;k=2**i;while(k--){y=1-2*y*x;x=a-x*x;}a-=x/y}e=z/(a-b);c=b;b=a;e}
```
```
b=1;c=0;e=3.2;for(i=2;i<13;i++){z=b-c;a=b+z/e;j=4;while(j--){x=y=0;k=2**i;while(k--){y=1-2*y*x;x=a-x*x;}a-=x/y}e=z/(a-b);c=b;b=a;e}
console.log(e)
```
[Answer]
# Python, 127 bytes
```
c,b,e=0,1,2
for i in range(2,13):a=b+(b-c)/e;exec(("x=y=0;"+"y,x=1-2*y*x,a-x*x;"*2**i+"a=a-x/y;")*17);d,c,b=(b-c)/(a-b),b,a;e=d
```
Credit goes for @ThomasW with his javascript answer.
Add `print(d)` to output **4.669201673141983**. Takes a few seconds, due to the long strings being calculated before execution.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 84 bytes
```
A¹βA⁰εA³·²δF…²¦¹³«A⁺β∕⁻βεδαFχ«A⁰ξA⁰ψFX²ι«A⁻¹××ψ²ξψA⁻α×ξξξ»A⁻α∕ξψα»A∕⁻βε⁻αβδAβεAαβ»Iδ
```
[Try it online!](https://tio.run/##bVHLCoMwELz7FTnupknxcfRU2ktvpX@QqLWBoqAiSvHb00QtrmAOgRlmJruT7K2arFYfay9ta8oKIsE0psGKQsGKDSXnWLDc4VfdMHiqqizAMVGCyL4Bc2cVnkALdq@6m@lNXoD0sEDvdZdyAV47h0Th30rs7tVhFe3ZkbCznXM/gEEaQizSr8OBwyhYjD4V9yE7rfLaYVXRAabgSLvtN/hQstlEuzioYbZrxKVMotVL3YRRy3dMwaMxVQdX1XbgWkyttbK3sv38AA "Charcoal – Try It Online") Link to verbose code for explanation.
Uses algorithm from [here](http://code.activestate.com/recipes/577464-feigenbaum-constant-calculation/).
Prints **4.66920**0975097843 (6 digits)
] |
[Question]
[
Thanks to [MD XF's recent challenge](https://codegolf.stackexchange.com/questions/125635/read-a-password), we can now read passwords in many different languages! The problem is, now we need to port our applications to mobile devices, and they do password entry a little differently.
# Challenge
* Read a string from the keyboard.
* Each time a character`k` is entered, display it for a short time interval.
* After the time interval has passed OR the user has entered another character, replace `k` with some character `c`.
# Rules
* `c` must be constant; it must be the same character.
* `c` can be any visible character (i.e. it cannot be a newline, space, tab, or unprintable).
* `c` can't be based on any inputted `k`; `c` must be defined/constant
before the first `k` is read.
* `c` must be the same every time the program is run.
* `c` can be one of the values given as `k` if by accident, as long as all other rules are followed.
* You must print `k` in realtime. As soon as the user enters a new `k`, you must display it immediately.
* `k` should be visible to the end user before being changed to `c`; the time interval shall not be less than 0.5 seconds.
* `k` should be replaced by `c` within a reasonable time; the time interval shall not exceed 5 seconds.
* As soon as a new character is entered, whether or not the time interval has expired, you should replace `k` with `c` and use the entered key as the new `k` immediately.
* It is acceptable to clear and redraw the screen each time you need to change a character.
* You may use any reasonable methods of input and output as long as all other rules are followed.
* You may assume that the number of characters inputted is never longer than the terminal/graphical window width.
* If using a terminal, your program should terminate after a newline is entered or EOF is reached.
* Your program should function as outlined here on both mobile and other environments.
* Your program may assume that the input will only contain printable characters (letters, numbers, symbols) and possibly a terminating newline (no backspace, arrow keys, delete, etc).
* Your program may terminate when Ctrl+C is pressed.
* You may terminate your program by closing a window, if your program launches one.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins!
# Example
Here is an example of what it should look like. Note this is recorded on a mobile platform, but should also work on a desktop platform.
[](https://i.stack.imgur.com/o6Zr2.gif)
[Answer]
# HTML + JavaScript, 20+105 = 125 bytes
```
<input id=I oninput=v=I.value;s='*'.repeat(l=v.length-1);I.value=s+v[l];clearTimeout(I.t);I.t=setTimeout(`I.value=s+'*'`,1e3)
```
The delay between the entry of `k` and the letter becoming `*` is one second.
## JavaScript `oninput`, Formatted
```
v=I.value;
s='*'.repeat(l=v.length-1);
I.value=s+v[l];
clearTimeout(I.t);
I.t=setTimeout(`I.value=s+'*'`,1e3)
```
## Test Snippet
Added the ending bracket (`>`) for better compatibility.
```
<input id=I oninput=v=I.value;s='*'.repeat(l=v.length-1);I.value=s+v[l];clearTimeout(I.t);I.t=setTimeout(`I.value=s+'*'`,1e3)>
```
[Answer]
# [Python 3](https://docs.python.org/3/), 186 224 bytes
Works only in windows.
```
import os,time,msvcrt as m
i=s=x=0;t=time.clock
def v():os.system("cls")
v()
while 1:
if m.kbhit():
k=str(m.getch())
if"\\r"in k:break
i+=1;x=1;v();print("*"*(i-1)+k[2]);s=t()
if (t()-s>.6and x):x=0;v();print("*"*i)
```
Older version(186 bytes): The sleep was mandatory regardless of the speed at which key was pressed.
```
import os,time,msvcrt
a=k=[];i=0;o=os.system
while 1:
o("cls")
if i:print("*"*(i-1)+a[i-1]);time.sleep(.6);o("cls");print("*"*i)
k=str(msvcrt.getch())
if"\\r"in k:break
a+=k[2];i+=1
```
[Answer]
# [Python 2](https://docs.python.org/2/), 133 bytes
Based on @officialaimm [answer](https://codegolf.stackexchange.com/a/125910/38183).
```
import time,msvcrt as m
k=T=0
s=p='\r'
while'\r'!=k:
t=time.time();print s,
if m.kbhit():k=m.getch();s=p+k;T=t;p+='*'
if t-T>1:s=p
```
[Answer]
# HTML + JavaScript, 115 bytes
```
<input id=I oninput="setTimeout(g=>g==I.value?I.value=0+g.slice(0,-1):0,1e3,I.value=I.value.replace(/.(?=.)/g,0))">
```
] |
[Question]
[
The challenge is simplistic, given an input time ***as a string*** in any one of the following formats:
`hh`, `hh:mm` or `hh:mm:ss` with `0 ‚â§ hh ‚â§ 23`, `0 ‚â§ mm ‚â§ 59` and `0 ‚â§ ss ‚â§ 59`.
Output what time it currently is using the following symbols:
```
AA LABEL FOR CHARACTER CODE POINT HEXADECIMAL
== ==================== ========== ===========
üïê Clock Face 01 Oclock 128336 0x1F550
üïë Clock Face 02 Oclock 128337 0x1F551
üïí Clock Face 03 Oclock 128338 0x1F552
üïì Clock Face 04 Oclock 128339 0x1F553
üïî Clock Face 05 Oclock 128340 0x1F554
üïï Clock Face 06 Oclock 128341 0x1F555
üïñ Clock Face 07 Oclock 128342 0x1F556
üïó Clock Face 08 Oclock 128343 0x1F557
üïò Clock Face 09 Oclock 128344 0x1F558
üïô Clock Face 10 Oclock 128345 0x1F559
üïö Clock Face 11 Oclock 128346 0x1F55A
üïõ Clock Face 12 Oclock 128347 0x1F55B
```
In the following format:
```
It is currently {Clock Face 1} with {mm} minutes and {ss} seconds until {Clock Face 2}.
```
---
**Examples (Including all fringe cases):**
Case with only hours...
```
f("12") = "It is currently üïõ."
```
---
Case with hours and minutes...
```
f("12:30") = "It is currently üïõ with 30 minutes until üïê."
```
---
Case with only hours, but has minutes included as 00...
```
f("12:00") = "It is currently üïõ."
```
---
Case with hours, minutes and seconds...
```
f("12:30:30") = "It is currently üïõ with 29 minutes and 30 seconds until üïê."
```
---
Case with hours and minutes, but has seconds included as 00...
```
f("12:30:00") = "It is currently üïõ with 30 minutes until üïê."
```
---
Case with hours and minutes, with less than a minute until the next hour...
```
f("12:59:59") = "It is currently üïõ with 1 seconds until üïê."
```
**You do not have to change from plural to singular.**
---
Case with hours and minutes, with 1 minute to the next hour...
```
f("12:59") = "It is currently üïõ with 1 minutes until üïê."
```
**You do not have to change from plural to singular.**
---
Case using military time (yes you must handle this)...
```
f("23:30:30") = "It is currently üïö with 29 minutes and 30 seconds until üïõ."
```
---
Invalid cases...
```
f("PPCG") = This cannot occur, you are guaranteed a valid format by the definition of the problem.
f(66:66:66) = This cannot occur, you are guaranteed valid numbers by the definition of the problem.
f(24:60:60) = This cannot occur, you are guaranteed valid numbers by the definition of the problem.
```
You do not have to conform to any style of output for invalid cases, errors are fine.
---
Overall the challenge is rather simplistic, but seemed to be dynamic enough to be fun in my opinion. The shortest code here is the winner as there isn't much variable aspect to the code other than length.
[Answer]
# Befunge, ~~256~~ 250 bytes
```
>&~85+`v
8~-&"<"_00v`+5
0v%\-&"<<"_
v>:00p!!-"<"%10p65++:66+%0" yltnerruc si tI">:#,_$"Hu 5x"2*,3*,+,2*+,10g00g+
_".",@,".",+*2,+,*3,*2"x5 uH"%+66+1$_,#!>#:<v0
" litnu htiw ",,,,,,10g:>#v_$"sdnoces"00g.^>
_>,,,,,,,>" dna ">,,,,,00^ >."setunim"00g!#^
```
[Try it online!](http://befunge.tryitonline.net/#code=PiZ+ODUrYHYKOH4tJiI8Il8wMHZgKzUKMHYlXC0mIjw8Il8Kdj46MDBwISEtIjwiJTEwcDY1Kys6NjYrJTAiIHlsdG5lcnJ1YyBzaSB0SSI+OiMsXyQiSHUgNXgiMiosMyosKywyKissMTBnMDBnKwpfIi4iLEAsIi4iLCsqMiwrLCozLCoyIng1IHVIIiUrNjYrMSRfLCMhPiM6PHYwCiIgbGl0bnUgIGh0aXcgIiwsLCwsLDEwZzo+I3ZfJCJzZG5vY2VzIjAwZy5ePgpfPiwsLCwsLCw+IiBkbmEgIj4sLCwsLDAwXiA+LiJzZXR1bmltIjAwZyEjXg&input=MTI6MzA6MzA)
The results are encoded as utf-8, since that works best with TIO, but if you're testing locally, you may need to adjust your system's default code page to see the clock faces correctly. Otherwise just redirect the output to a file and open that in a utf-8 compatible editor.
**Explanation**
The first three lines read the hours minutes and seconds from stdin, checking for EOF or a linefeed after each value, and substituting zeros for the componenents that are missing from the input. On line four, we adjust the minute value if the seconds are non-zero, convert the hour value into the range 0 to 11 (to match the appropriate unicode character for each hour), and write out the initial part of the output, including the the first clock face.
It's at this point that we need to follow different branches depending on what components are non-zero. The first test, at the start of line five, just checks if both minutes and seconds are zero. If so, we write out a final `.` and exit. Otherwise lines six and seven deal with the remaining cases - writing out the appropriate text and values, before the paths all combine again on line five to write out the final clock face (executing right to left).
[Answer]
# JavaScript (ES6), 201
```
t=>(T=h=>String.fromCodePoint(128336+h%12),[h,m,s]=t.match(/\d+/g),'It is currently '+T(h-=~10)+((m-=-!!-s)?` with ${60-m?60-m+' minutes'+(-s?' and ':''):''}${-s?60-s+' seconds':''} until `+T(-~h):''))
```
*Less golfed*
```
t=>(
T=h=>String.fromCodePoint(128336+h%12),
[h,m,s]=t.match(/\d+/g),
'It is currently '+T(h-=~10)
+(
// if seconds is not 0, increment m else just convert to number
// have to use '- -' to force conversion to number
(m -= - !!-s)
-s?++m:m)
? ` with ${60-m ? 60-m+' minutes'+(-s?' and ':''):''}${-s?60-s+' seconds':''} until `+T(-~h)
: ''
)
)
```
**Test**
```
F=
t=>(T=h=>String.fromCodePoint(128336+h%12),[h,m,s]=t.match(/\d+/g),'It is currently '+T(h-=~10)+((m-=-!!-s)?` with ${60-m?60-m+' minutes'+(-s?' and ':''):''}${-s?60-s+' seconds':''} until `+T(-~h):'')
)
var tid=0
function getTime(t)
{
var a=t.match(/\d+/g)
if (a) {
var [h,m,s]=a
h|=0, s|=0, m|=0
if(h>=0 & h<24 & m>=0 & m<60 & s>=0 & s<60)
return [h,m,s]
}
return null
}
function update()
{
clearTimeout(tid)
var t=I.value, a=getTime(t)
if (a) {
O.textContent = F(t)
tid = setTimeout(again,5000)
}
else {
O.textContent = 'invalid ' + t
}
}
function again()
{
var t=I.value, a=getTime(t)
if (a) {
var [h,m,s]=a
++s>59?(s=0,++m>59?(m=0,++h):0):0
h%=24
s<10?s='0'+s:0
m<10?m='0'+m:0
t = h+(-m-s?':'+m+(-s?':'+s:''):'')
I.value = t
O.textContent=F(t)
tid = setTimeout(again, 1000)
}
}
update()
```
```
#O { font-size:16px }
```
```
Time <input id=I value='12' oninput='update()' onkeydown='update()'>
(modify current time as you wish - but use valid values)
<pre id=O></pre>
```
[Answer]
## JavaScript (ES6), 201 bytes
```
(i,[h,m,s]=i.split`:`,c=n=>String.fromCodePoint(128336+(n+11)%12))=>`It is currently ${c(+h)}${m|s?` with ${(m=59+!+s-m)?m+` minutes`:``}${+s&&m?` and `:``}${+s?60-s+` seconds`:``} until `+c(-~h):``}.`
```
226 bytes if you take plurals into account:
```
f=
(i,[h,m,s]=i.split`:`,c=n=>String.fromCodePoint(128336+(n+11)%12))=>`It is currently ${c(+h)}${m|s?` with ${(m=59+!+s-m)?m+` minute`+(m-1?`s`:``):``}${+s&&m?` and `:``}${+s?60-s+` second`+(59-s?`s`:``):``} until `+c(-~h):``}.`
```
```
<input oninput=o.textContent=f(this.value)><div id=o>
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~250~~ 243 bytes
```
$h,$m,$s=$args-split':'
$f={[char]::ConvertFromUtf32(128336+(11+$args[0])%12)}
$u=(60-$s)%60
$v=(59-$m+!$u)%60
"It is currently $(&$f $h;"with $(("$v minutes"|?{$v}),("$u seconds"|?{$u})-match'.'-join' and ') until $(&$f (1+$h))"|?{$u-or$v})."
```
[Try it online!](https://tio.run/nexus/powershell#LY7NSsQwGEX3fYoYvjEJbYYmxaKV4kIQfABXwyxKpzWRJpH8VGTss9c64/IeOIe7girAFBBa6Px74OFz0pE0JIOxPR961flj0zw7Ow8@vnhn3uJYSSrkfVXVORUiv2iH8sh2QrIlg9TSuuQQ2K4uM5hbevfAweQ3kC4Ev0akA@qT94ON0zcCegsjAvWIv3RU26QYZmS0TXEI@OfpDPPCig0mFIbe2dMVpoVx08VekT3hH05bgjp7QoShZKOe/rN0@6cYuxrc@b/WHq/rKqtGiEbKXw "PowerShell – TIO Nexus")
[Answer]
## C, 241 bytes
Writes UTF-8 to stdout.
```
#define p printf(
c(v,h){p"%s \xf0\x9f\x95%c",v,144+h%12);}f(t){int h=0,m=0,s=0;sscanf(t,"%d:%d:%d",&h,&m,&s);m=(59-m+!s)%60;c("It is currently",h-1);m&&p" with %d minutes",m);s&&p" %s %d seconds",m?"and":"with",60-s);m|s&&c(" to",h);p".");}
```
[Try it online!](https://tio.run/nexus/c-gcc#ZU/RbsIwDHxev8Lz1CoZYUqhRaMR2vP@gZcqbZVKS6iawJgY386cahpMSPaD73xn3@WpabvetTDAMPYudCzR7CAMPw2YetgeO7k9rjvqMtUoDiIviplJ8wVX544FfiINmI0UltpvpPJe144YgWlTTYUiMyKzIvNc2Q0r13M7e/Q8XUmlGb4H6D3o/Ti2Lnx8oTDznPaybED47IOBtAHbu31oPQrLlZ8Yeo1w3@qdayL@hrVrsMKoQLGS83jrm3bpAoQduXI14AvS15f4MbkFpk09wnPgcEoefsNT5gpQQOAqeYj51JXaOpIn5ySJBrbuHZuUkxXmi0j@DZWUVP@h5d18B5VrqluorGRRFa830GJ5FZ4vPw)
Code with whitespace:
```
#define p printf(
c(v, h) {
p"%s \xf0\x9f\x95%c", v, 144 + h % 12);
}
f(t) {
int h = 0, m = 0, s = 0;
sscanf(t, "%d:%d:%d", &h, &m, &s);
c("It is currently", h - 1);
m = (59 - m + !s) % 60;
m && p" with %d minutes", m);
s && p" %s %d seconds", m ? "and" : "with", 60 - s);
m | s && c(" to", h);
p".");
}
```
] |
[Question]
[
### Challenge
You are given an ASCII-art representation of characters on a plane as input by any reasonable method. This will only contain:
* `[a-z]` representing moveable characters. Every letter will appear on the board at most once.
* `#` representing immovable walls
* `.` representing empty space
For example:
```
abcdef.gh#..
.......ij.#.
#..#.......#
...#.#...###
.#.......#q#
.........###
```
You are also given a string representing the changes in gravity. This will only contain:
* `>` representing a change to rightward gravity
* `<` representing a change to leftward gravity
* `^` representing a change to upward gravity
* `v` representing a change to downward gravity
For example:
```
v>^
```
Your program must simulate the each change in gravity sequentially until all characters stop moving (they hit a wall, or another character). Characters that "fall off the edge of the map" are permanently removed, and characters can "stack" on top of each other.
In this example, at the start there is downward gravity (`v`), so `c`, `e`, `g`, `h`, `i`, and `j` fall off the bottom of the map. All other characters slide downwards until hitting a wall, leaving the map like this:
```
.........#..
a..d......#.
#..#.f.....#
.b.#.#...###
.#.......#q#
.........###
```
Then, we move on to rightward gravity (`>`), which leaves us with this:
Note how the `a` stacks next to the `d`.
```
.........#..
........ad#.
#..#......f#
..b#.#...###
.#.......#q#
.........###
```
Finally, we simulate upward gravity (`^`), during which the `a` and the `b` fall off the map.
```
.........#..
.........d#.
#..#......f#
...#.#...###
.#.......#q#
.........###
```
Your task is to output the remaining characters after the gravitational shifts. They can be given in any order. For this example, you could output any permutation of `dfq`.
### Testcases
For the following map:
```
abcde
.....
##.##
```
```
v = abde
v> = <nothing>
```
For the following map:
```
######
#....#
abcdef
#.gh..
######
```
```
> = <nothing>
< = gh
^> = bcde
v< = bghef
```
[Answer]
## JavaScript (ES6), ~~251~~ 233 bytes
```
(m,d,r=`replace`)=>[...d].map(c=>[...`<^>v`].map(d=>m=[...(m=(c==d?m[r](/[.\w]+/g,s=>s[r](/\./g,``)+s[r](/\w/g,``))[r](/^\w+/gm,s=>s[r](/./g,`.`)):m).split`
`)[0]].map((_,i)=>m.map(s=>s[i]).join``).reverse().join`
`))&&m[r](/\W/g,``)
```
Edit: Saved 18 bytes thanks to @WashingtonGuedes.
Works by rotating the input grid four times for each directional character, but on the direction where the directional character matches the loop character we do the left gravity thing. Pseudocode:
```
function slideleft(map) {
map = map.replace(/[.\w+]/g, match=>movedotstoend(match));
map = map.replace(/^\w+/gm, match=>changetodots(match));
}
function rotate(map) {
return joinrows(reverse([for each (column of rows(map)[0])
joinrow([for each (row of rows(map)) row[column]])
]));
}
function gravity(map, directions) {
for each (direction of directions) {
for each (angle of '<^>v') {
if (direction == angle) map = slideleft(map);
map = rotate(map);
}
}
return letters(map);
}
```
[Answer]
# JavaScript (ES6), 199
Same algortihm of @Neil's answer. The grid is rotated four times for each directional character, when in the right position the gravity shift to left is applied to each row.
```
x=>y=>(x=>{for(d of y){R='';for(e of'^>v<')x=[...x[0]].map((c,i)=>e!=d?x.map(r=>r[i]).join``:x.map(r=>(c=r[i])<'.'?(q+=p+c,p=''):c>'.'&&q?(q+=c,R+=c):p+='.',q=p='')&&q+p).reverse();}})(x.split`
`)||R
```
```
F=x=>y=>(x=>{for(d of y){R='';for(e of'^>v<')x=[...x[0]].map((c,i)=>e!=d?x.map(r=>r[i]).join``:x.map(r=>(c=r[i])<'.'?(q+=p+c,p=''):c>'.'&&q?(q+=c,R+=c):p+='.',q=p='')&&q+p).reverse();}})(x.split`
`)||R
// Less golfed
U=(x,y)=>
{
x = x.split`\n`;
for(d of y)
{
R = '';
for(e of '^>v<')
x = [...x[0]].map(
(c,i) => e != d
? x.map( r => r[i] ).join`` // basic rotation
: x.map( // rotation with gravity shift
r=> (c=r[i])<'.' ? (q+=p+c,p='') : c>'.'&&q?(q+=c,R+=c) : p+='.', q=p=''
) && q+p
).reverse();
}
return R
}
console.log=x=>O.textContent+=x+'\n'
;[
['abcdef.gh#..\n.......ij.#.\n#..#.......#\n...#.#...###\n.#.......#q#\n.........###',
[['v>^','dfq']]
],
['abcde\n.....\n##.##',[['v','abde'],['v>','']]],
['######\n#....#\nabcdef\n#.gh..\n######',[['>',''],['<','gh'],['^>','bcde'],['v<','befgh']]]
].forEach(t => {
var i=t[0]
console.log(i)
t[1].forEach(([d,k])=>{
var r=F(i)(d),ok=[...r].sort().join``==k
console.log((ok?'OK ':'KO ')+d+' : '+r+(ok?'':' (expected '+k+')'))
})
console.log('')
})
```
```
<pre id=O></pre>
```
[Answer]
# Pyth, 143 bytes
(Do we really need that much bytes?)
```
JhQKeQMe.u:N+"\."H+H"."G;DybVkI}NG=gkN;D'bVlJ=k@JNykVkI}HG=:kH\.).?B)=XJNk;VKIqN\<'J)IqN\v=C_J'J=_CJ)IqN\>=C_CJ'J=C_CJ)IqN\^=CJ'J=CJ;VJVNI}HGpH
```
[Try it online!](http://pyth.herokuapp.com/?code=JhQKeQMe.u%3AN%2B%22%5C.%22H%2BH%22.%22G%3BDybVkI%7DNG%3DgkN%3BD%27bVlJ%3Dk%40JNykVkI%7DHG%3D%3AkH%5C.%29.%3FB%29%3DXJNk%3BVKIqN%5C%3C%27J%29IqN%5Cv%3DC_J%27J%3D_CJ%29IqN%5C%3E%3DC_CJ%27J%3DC_CJ%29IqN%5C%5E%3DCJ%27J%3DCJ%3BVJVNI%7DHGpH&input=[[%22%23%23%23%23%23%23%22%2C%22%23....%23%22%2C%22abcdef%22%2C%22%23.gh..%22%2C%22%23%23%23%23%23%23%22]%2C%22%5E%3E%22]&debug=0)
## How it works
We define a function `left` which does the leftward gravity thing.
Then, the other directions are implemented by messing with the array so that the desired direction is leftwards, then do `left`.
The algorithm of `left` is here:
* Do the following until idempotent:
* Replace `".X"` with `"X."`, where `X` represents a letter.
The whole program is divided into the following 6 sections:
```
JhQKeQ
Me.u:N+"\."H+H"."G;
DybVkI}NG=gkN;
D'bVlJ=k@JNykVkI}HG=:kH\.).?B)=XJNk;
VKIqN\<'J)IqN\v=C_J'J=_CJ)IqN\>=C_CJ'J=C_CJ)IqN\^=CJ'J=CJ;
VJVNI}HGpH
```
### First section
```
JhQKeQ Q auto-initialized to evaluate(input())
JhQ J = Q[0]
KeQ K = Q[len(Q)-1]
```
### Second section
```
Me.u:N+"\."H+H"."G; @memoized
M ; def g(G,H):
.u G repeat_until_idempotent(start:G, as N):
:Nxxxxxxyyyyy return N.replace(xxxxxx,yyyyy)
+"\."H "\."+H
+H"." H+"."
```
### Third section
```
DybVkI}NG=gkN; @memoized
Dyb ; def y(b):
Vk for N in k: --TAKES GLOBAL VARIABLE k
I}NG if N in G: --G pre-initialized to "abcde...z"
=gkN k = g(k,N)
```
### Fourth section
```
D'bVlJ=k@JNykVkI}HG=:kH\.).?B)=XJNk; @memoized
D'b ; def single_quote(b):
VlJ ) for N in range(len(J)): --TAKES GLOBAL VARIABLE J
=k@JN k = J[N] --SETS GLOBAL VARIABLE k
yk y(k) --returns nothing, but MODIFIES GLOBAL VARIABLE k
Vk for H in k:
I}HG ) if H in G:
=:kH\. k = k.replace(H,".")
.? else:
B break
=XJNk J[N] = k --MODIFIES GLOBAL VARIABLE J
```
### Fifth section
```
VKIqN\<'J)IqN\v=C_J'J=_CJ)IqN\>=C_CJ'J=C_CJ)IqN\^=CJ'J=CJ;
VK ; for N in K:
IqN\< ) if N == '<':
'J single-quote(J)
IqN\v ) if N == 'v':
=C_J J = transpose(reverse(J))
'J single-quote(J)
=_CJ J = reverse(transpose(J))
IqN\> ) if N == '>':
=C_CJ J = transpose(reverse(transpose(J)))
'J single-quote(J)
=C_CJ J = transpose(reverse(transpose(J)))
IqN\^ if N == '^':
=CJ J = transpose(J)
'J single-quote(J)
=CJ J = transpose(J)
```
### Sixth section
```
VJVNI}HGpH
VJ for N in J:
VN for H in N:
I}HG if H in G: --G = "abc...z"
pH print(H)
```
[Answer]
# Ruby, 306 bytes
Anonymous function. Pretty circuitous technique that could probably be optimized.
```
->s,d{w=[];x=y=0;m={}
s.chars.map{|c|c>?!?(c<?A?c<?.?w<<[x,y]:0:m[c]=[x,y]
x+=1):(x=0;y+=1)}
d.chars.map{|c|q=[c<?=?-1:c<?A?1:0,c>?a?1:c>?A?-1:0];e=1
(n=m.clone.each{|k,v|z=[v[0]+q[0],v[1]+q[1]]
w.index(z)||m.value?(z)?0:m[k]=z}
m.reject!{|k,v|i,j=v;i<0||i>=x||j<0||j>y}
e=(m!=n ?1:p))while e}
m.keys.join}
```
] |
[Question]
[
[This challenge](https://codegolf.stackexchange.com/q/75057/40695) but with a better spec.
## Spec
Your program will take a linear equation containing a single variable `x` and output the value of `x`.
### Input / Parsing
* The input will only contain numbers, operators, parenthesis (`()`), `x`, and an `=` sign (this means no whitespace).
* Parenthesis will always be balanced.
* There will always be at least 1 `x`. An `x` may be preceded by a number.
* All equations will exactly have one result.
---
A **number** can be defined by following these steps. A number can be defined by the regex: `-?(\d+(\.\d+)?|\.\d+)`.
---
If you don't speak regex: A digit is defined as `0-9`
1. It may have a `-` at the beginning of it signifying negative
2. Then there *may* be some digits. If they aren't any digits there will be a decimal point
3. If a decimal point exists, at least one digit will follow it
The biggest a number / value will be is defined by your language's capabilities.
---
An **operator** is any of: `+-*/`, they will always appear between numbers, and or parenthesis
this means `(5)(5)` is not a valid input for the sake of simplicity.
---
Parenthesis will always contain a valid expression (a valid combination of numbers and/or operators) inside them. "Balanced" parenthesis is defined as every `(` will have an associated closing `)`
### Evaluation
* Order of operations should be followed and the precedences are (highest to lowest):
+ Parenthesis (most deeply nested first)
+ Multiplication & Division
+ Addition & Subtraction
* If two operators with the same precedence are occurred you should prefer going left -> right
### Output
You should output the result in some way. If you don't output just number result, clarify in your answer how the output is outputted. Your output format should be consistent. Output may be a decimal, but it will always be rational, the precision is limited to your language's precision. **Only** if your language does not support floating point arithmetic, you do not need to support it.
## Rules
* Built-ins trivializing this task are allowed **but**, you must clearly add `[uses built-in]` clearly to the header of the answer. This exempts your answer from winning
* A "Built-ins trivializing this task" is any of:
+ Something which takes in an equation and outputs the value for a/the variable
+ Something which will completely simplify an equation
+ Using `eval` or a related function to do a significant amount of the parsing. Use of `eval` and related functions are disallowed if they are used to (with minimal modification to the input) solve linear equations.
+ If you're in doubt, just ask in a comment.
* Built-ins which parse the equation are allowed
## Examples
```
3+4=x
7
4+x=5
1
3+3*3=x
12
3x-4=7+2x
11
3--1=x
4
3*(2+4x)=7x-4
-2
1.2+2.3x=5.8
2
10=4x
2.5
```
**INVALID** Inputs:
```
(5)(4)=x no operator between (5) and (4)
5(x+3)=2 no operator 5 and (...)
x=y the only variable is x
4=3 there is no x
x+3=x-7 no solution
x=x infinite solutions
+5=x + is not an unary operator. -5=x would be valid though
1/(x-3)=5 Nonlinear
3/x Nonlinear
```
[Answer]
# JavaScript ES6, 246 bytes
Still some golfing to be done, but at least it's a solution!
```
C=a=>new Function("x","return "+a.replace(/(\d)x/g,"$1*x"));n=>{n=n.split("=");t=Math.abs,r=C(n[0]),c=C(n[1]),a=0,i=r(a)-c(a);a++;v=r(a)-c(a);o=t(i)<t(v)?-1:1;for(u=1/0;r(a)!==c(a);)a+=o,e=t(r(a)-c(a)),e>u&&(u=1/0,o/=10),u=Math.min(e,u);return a}
```
Name the function `n=>{n=n.split("=")...` to use it.
Hyper-ungolfed:
```
function solveLinear(equation){
equation = equation.split("=");
var abs = Math.abs;
var LHS = convertToFunction(equation[0]), RHS = convertToFunction(equation[1]);
var pivot = 0;
var dir;
var dir1 = LHS(pivot) - RHS(pivot);
pivot++;
var dir2 = LHS(pivot) - RHS(pivot);
if(abs(dir1)<abs(dir2)) dir = -1;
else dir = 1;
var dif, minDif = Infinity;
while(LHS(pivot) !== RHS(pivot)){
pivot += dir;
dif = abs(LHS(pivot) - RHS(pivot));
if(dif > minDif){
minDif = Infinity;
dir /= 10;
}
minDif = Math.min(dif, minDif);
console.log(pivot,dir,dif,minDif);
}
return {
x: pivot,
LHS: LHS,
RHS: RHS
};
}
```
This uses a pivot approach. (I'm not sure if this is what the algorithm is called, just a name I invented.) It first gathers which direction to search for from zero (i.e., which way the slopes of the two sides of the equations will intersect) and looks for the value. Once it finds a point of minimal difference, it goes to that point and decreases the search increment. This eventually yields as precise of a solution we need.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~106~~ 93 bytes
```
a=>eval(`f=x=>${a[R='replace'](/(\d)x/g,"$1*x")[R]("=","-(")[R](/-/g,"+-")})`)(0)/(f(0)-f(1))
```
[Try it online!](https://tio.run/##NY3baoRAEETf8xXLIGy343gbwwZM70fsqxEc3PESRBcVGRC/3YwueenqqkNRv2pRUzm2r1n0w1PvDe2K7npRHRQVGbo7q8oedB31q1OlvuYQwM8TTVB7zIlcwzB75MCIeUzA2wTigFww3LBACDGAyl5RQYS4L2q8zHqaJ8qY5AkZ20y4oU@rkktXnok0IqEbj89fiOgduhDzxCDdLLU@8mMe@9J2/a/DhpQYlqcf1TDCMdNSmLbf55jf6b6em7TlHMuhn4ZO@91QQ@GsJ8/afPMuhpy1gf8AtwLT/Q8 "JavaScript (Node.js) – Try It Online")
-13 bytes thanks to @tsh
Ungolfed:
```
var h=a=>{
a=a.replace(/(\d)x/g,"$1*x").replace("=","-(").replace("--","- -"); //get into an eval-able form
var f=x=>eval(a+")");
var df=(f(1)-f(0))/(1-0) //derivative or slope of the function
var x=0;
return x-(f(x)/df); //newton's method
}
```
Explaination:
This solution works by [Newton's method](https://en.m.wikipedia.org/wiki/Newton's_method) for finding roots. The code subtracts the right hand side of the equation from the left hand side, such that when `f(x)=0`, `x` will equal the value we are solving for. Therefore, when we find the root of this new function, it will be our desired `x` value. Then it finds the derivative `f'(x)` by finding the slope between two points on the function. Then, the values are simply inserted into Newton's method which states for an approximation of the root `x`, `x=x-(f(x)/f'(x))` (in the code, we use 0 as an initial `x` value). Since this finds the roots, it finds our `x` value. And since the equation is guaranteed to be linear, the approximation will be exact.
[Answer]
# Mathcad, [uses built-in]
[](https://i.stack.imgur.com/XUHVC.jpg)
Mathcad has two built-in methods of solving such equations:
* Symbolic solver (uses the keyword solve)
* Solve Block (which works in both numeric and symbolic modes). A Solve Block starts with the keyword Given, followed a set of expressions defining the conditions of interest, and closed by one of the solving keywords, such as Find (which finds an exact solution) or MinErr (which minimizes the error between the target and any solution).
The symbolic solver is quite happy with y=x and returns the solution x = y.
For those unfamiliar with Mathcad, the image below is taken directly from the WYSIWYGish Mathcad 15 workbook. Changing any of the expressions where they are written will cause Mathcad to reevaluate its answer and update the display accordingly.
[Answer]
# Axiom, 214 bytes [uses built-in]
```
q(t:EQ POLY FLOAT):Any==(a:=[variables(lhs t),variables(rhs t)];a.1~=[x]and a.1~=[]=>%i;a.2~=[x]and a.2~=[]=>%i;a.1=[]and a.2=[]=>%i;a.1=[x]and degree(lhs t,x)>1=>%i;a.2=[x]and degree(rhs t,x)>1=>%i;rhs solve(t).1)
```
For some error would return %i, for other type of errors the function is stopped from the system, something else as 1--2 seems out of language... test:
```
(72) -> q(x+3=9)
(72) 6.0
Type: Complex Fraction Polynomial Float
(73) -> q(3+4=x)
(73) 7.0
Type: Complex Fraction Polynomial Float
(74) -> q(4+x=5)
(74) 1.0
Type: Complex Fraction Polynomial Float
(75) -> q(3+3*3=x)
(75) 12.0
Type: Complex Fraction Polynomial Float
(76) -> q(3*x-4=7+2*x)
(76) 11.0
Type: Complex Fraction Polynomial Float
(77) -> q(3--1=x)
Line 1: q(3--1=x)
.AB
Error A: Missing mate.
Error B: syntax error at top level
Error B: Possibly missing a )
3 error(s) parsing
(77) -> q(3*(2+4*x)=7*x-4)
(77) - 2.0
Type: Complex Fraction Polynomial Float
(78) -> q(1.2+2.3*x=5.8)
(78) 2.0
Type: Complex Fraction Polynomial Float
(79) -> q(10=4*x)
(79) 2.5
Type: Complex Fraction Polynomial Float
(80) -> q((5)(4)=x)
Cannot find a definition or applicable library operation named 5
with argument type(s)
PositiveInteger
Perhaps you should use "@" to indicate the required return type,
or "$" to specify which version of the function you need.
(80) -> q(5(x+3)=2 )
(80) %i
Type: Complex Integer
(81) -> q(x=y)
(81) %i
Type: Complex Integer
(82) -> q(4=3)
(82) %i
Type: Complex Integer
(83) -> q(x+3=x-7)
>> Error detected within library code:
inconsistent equation
protected-symbol-warn called with (NIL)
(83) -> q(x=x)
>> Error detected within library code:
equation is always satisfied
protected-symbol-warn called with (NIL)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes [uses built-in]
```
\=/÷∆q
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiXFw9L8O34oiGcSIsIiIsIjMrND14XG4zeC00PTcrMnhcbjMtLTE9eFxuMyszKjM9eFxuNCt4PTVcbjEuMisyLjN4PTUuOFxuMTA9NHhcbjEvKHgtMyk9NVxuNSh4KzMpPTIiXQ==)
As a bonus, it can even handle some of the invalid input cases.
## Explained
```
\=/÷∆q
\=/÷ # Split the input on "=" and dump to the stack
∆q # Pop two items a and b and solve x in a = b
```
[Answer]
# [Python](https://www.python.org), 134 bytes [uses built-in]
```
import re
def f(e):
l,r=re.sub(r"(?<=\d)x","*x",e).split("=")
a,b=[eval(f"{l}-({r})",{"x":x})for x in[0,1]]
return a/(a-b)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZA9boQwEEZ7n8KaygM2WX5WrFaxchBCAVqjWCKAjIkcIdpcIs02yX1S5jYxu5sQF1M8vfHMN--fw6t96rvz-WOyjTh8v-nnoTeWGkVOqqENU3gk1L-WG2lUNE41M8Ae7uXjCR1wCHxRGI1Dqy0DCXixK17LQr1ULWtgbhfBZrMg8BkcHN2CTW-oo7ordjwuy0uHUXYyHa3uWCVqvG3zZdVoqaTFRWGQhpn083LkN5CFTu6Bx38gDdMgXZ042ZgTmczDZKX_TCHiVcw2ErAkzBzK3DcAF9sPcZSESZT6WdEB-MYzJ-OdB9EeSUnIGkvz3gej6-LXww1Gd5b1vGEakVyD_Z77Bw)
This preprocesses the string, turns it into an expression where \$x\$ is the root, then uses `eval` to find two points plus basic algebra to find the root.
] |
[Question]
[
Based on [Chunky vs. Smooth Strings](https://codegolf.stackexchange.com/questions/53075/chunky-vs-smooth-strings).
Squiggles `/\_/\/\__/\/\/\/\_/\_/\` are fun to make on a keyboard when you are really bored. But not all squiggles are created equal. Some squiggles are smooth, like `\___/`, and some are chunky, like `/\/\/\/\`. Others are just downright broken, like `////_\\\`
Inside every squiggle of `N` characters, there are `N-1` squiggle-junctions. Each squiggle-junction is classified into one of three types:
* Smooth (angle > "90 degrees"):
`\_ __ _/`
* Chunky (angle = "90 degrees")
`/\ \/`
* Broken (anything that doesn't connect)
`// \\ /_ _\`
Let's define the *smoothness* to be the proportion of junctions that are smooth, with *chunkiness* and *brokenness* defined similarly. Each value ranges between `0` and `1`. The sum of a squiggle's smoothness, chunkiness, and brokenness is always equal to 1.
For example, the squiggle `/\/\\_//\_` has 3 smooth junctions, 4 chunky junctions, and 2 broken junctions. It is thus `0.3333` smooth, `0.4444` chunky, and `0.2222` broken.
**Empty strings and strings with only one character have undefined values, all input will be at least 2 characters long.**
## Challenge
Write a program that takes in a squiggle of arbitrary length and outputs any two of its smoothness, chunkiness, and brokenness values.
* You may write a program or function, with input via STDIN, command line, or as a string argument.
* You may assume the input is at least of **length >= 2** and consists only of the characters `/\_` with an optional trailing newline.
* Print (or return if a function) the two floats to a precision of at least 4 decimals, rounded or truncated. If the true value is `2/3`, acceptable values include any value between `0.6666` and `0.6667`, even things like `0.666637104`. If the exact value is `1/3`, any answer containing `0.3333` is valid. You may leave off trailing zeros, or the leading zero if the value is less than one.
* Output any pair of the three values as you prefer, just be sure to state which two and in what order.
**The shortest code in bytes wins.**
## Examples
`/\/\\/\//\\` → Smoothness `0`, Chunkiness `0.7`, Brokenness `0.3`
`_/\\_/\\/__/\\\//_` → Smoothness `0.29411764705`, Chunkiness `0.29411764705`, Brokenness `0.41176470588`
`//\\__/_\/` → Smoothness `0.3333333`, Chunkiness `0.2222222`, Brokenness `0.4444444`
*Bonus question: Which do you prefer, smooth or chunky or broken squiggles?*
[Answer]
# Pyth, 25 bytes
```
mcl@.:d2.:z2tlzc2"\__//\/
```
[Test suite](https://pyth.herokuapp.com/?code=mcl%40.%3Ad2.%3Az2tlzc2%22%5C__%2F%2F%5C%2F&input=_%2F%5C%5C_%2F%5C%5C%2F__%2F%5C%5C%5C%2F%2F_&test_suite=1&test_suite_input=%2F%5C%2F%5C%5C%2F%5C%2F%2F%5C%5C%0A_%2F%5C%5C_%2F%5C%5C%2F__%2F%5C%5C%5C%2F%2F_%0A%2F%2F%5C%5C__%2F_%5C%2F%0A___&debug=0)
Outputs smoothness, chunkiness. Basically, it takes the hard coded string and cuts it in half. Each half is decomposed into its 2 character substrings, and the same is done for the input. We take the intersection, resulting in the south and chunky pairs. Then, we take the the length, divide by the number of pairs, and print.
[Answer]
# Japt, 42 bytes
```
U=U¬ä@2+"\\/\\__/"bX+Y)f2};[T2]£U¬fX l /Ul
```
Outputs brokenness, chunkyness. [Try it online!](http://ethproductions.github.io/japt?v=master&code=VT1VrORAMisiXFwvXFxfXy8iYlgrWSlmMn07W1QyXaNVrGZYIGwgL1Vs&input=Il8vXFxfL1xcL19fL1xcXC8vXyI=)
### How it works
```
// Implicit: U = input string
U=UŠ@ } // Set U to U split into chars, with each pair mapped by this function:
"..."bX+Y) // Take the index in this string of the two chars concatenated.
// This is 0-1 for chunky, 2-4 for smooth, and -1 for broken.
2+ f2 // Add two and floor to the nearest multiple of 2.
// This is now 2 for chunky, 4 or 6 for smooth, and 0 for broken.
[T2]£ // Map each item X in [0,2] through this function:
U¬fX l // Count the occurances of X in U.
/Ul // Divide by U.length.
// Implicit: output last expression
```
### Non-competing version, 36 bytes
```
U=Uä@2+"\\/\\__/"bZ)f2};[T2]£UèX /Ul
```
Works in basically the same way as the other, with a few minor changes:
* `ä` now works on strings. The chars are passed into the function in order `(X, Y, X+Y)`.
* `è` counts the number of occurrences of the argument in the string/array.
[Answer]
# Ruby, 71
Outputs smoothness, chunkiness.
Takes the minimal smooth and chunky strings and searches them for every two-character string in the initial string.
Thanks to [Kevin Lau](https://codegolf.stackexchange.com/users/52194/kevin-lau) for EIGHT bytes!
```
->x{%w{\\__/ /\\/}.map{|t|(0..n=x.size-2).count{|i|t[x[i,2]]}/(n+1.0)}}
```
[Answer]
# Python 3, 149 bytes
This outputs smoothness and chunkyness.
```
def f(s):
for i in"012":s=s.replace("\_/"[int(i)],i)
a=len(s)-1;t=["bscbssbbc"[int(s[i:i+2],3)]for i in range(a)]
for x in"sc":print(t.count(x)/a)
```
**Ungolfed:**
```
def f(s):
for i in "012":
s = s.replace("\_/"[int(i)], i)
a = len(s) - 1
t = []
for i in range(a):
t.append("bscbssbbc"[int(s[i:i+2],3)])
for x in "sc":
print(t.count(x) / a)
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~82~~ 79 bytes
```
lambda x:[sum(a+b in s for a,b in zip(x,x[1:]))/~-len(x)for s in["\__/","/\/"]]
```
[Try it online!](https://tio.run/##HcpBCsMgEEDRq4irGWoZQjcl0JM4IoZWKiRG1IDpolc3aZef99Ne32u83VPu/sF9dsv0dKKNumwLuMskQhRF@DULp/7xCQmaanoYDSJ9r/MrQsPfUE7Wkq0lqSQxSWN6yiFW8BBi2iogYj@B2RKxPQA "Python 3.8 (pre-release) – Try It Online")
---
-3 from @xnor by not using index `i` into array
---
# [Python](https://www.python.org), 90 bytes
```
f=lambda x,s=0,c=0,n=0:x[1:]and f(x[1:],s+(x[:2]in"\__/"),c+(x[:2]in"/\/"),n+1)or(s/n,c/n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3o9JscxJzk1ISFSp0im0NdJKBOM_WwKoi2tAqNjEvRSFNA8zUKdYGMqyMYjPzlGLi4_WVNHWSESL6MSCBPG1DzfwijWL9PJ1k_TxNiA3bC4oy80o00jSKQKpiYuL19WPilTShsjB3AAA)
Recursive solution -- longer, but I think it's more elegant.
] |
[Question]
[
I love ><>, ><> is life! 2D langages are amazing!
In this challenge, you will have to say if a "fishy" road has an end,
while code-golfing.
## Definition
A fishy road is constructed with tiles, including the following ones:
```
v (go down)
> (go right)
^ (go up)
< (go left)
/ (mirror)
\ (mirror)
```
Any other character (except `-|+`) may be considered as a distraction, like some flowers (or fish heads) on the border of the road.
A road always start on the upper-left corner of a rectangular grid, delimited by `-|+`symbols. The road has an end if, by following it, you end up on a border, else, you'll be trapped in an infinite path.
Finding your way on the road is accomplished by following directions given by `v>^<`and mirrors. A mirror will reflect by 90° depending on where you came from. Here's how it works (using `v>^<`to show directions):
```
^ ^
>/< >\<
v v
</> <\>
^ ^
```
A road might be looking like this if it ends:
```
+--------------------+
|>\/ this way >\/> | this one ends here
| v^ \/ |
| v^ ^.^ |
| \/\ >v |
| /\/ ^< |
+--------------------+
```
An infinite loop :
```
+--------+
|>>\ This|
|\\ is |
| \\ a |
| \ /trap|
+--------+
```
## Specifics
A road doesn't necessarily consist only of instructions. Spaces or letters can be used to complete it. This means you have to continue moving in the same direction except if you cross a character in `<v^>-|`.
There will always be one of `v>^<` in the upper-left corner, `<` or `^` implies this road ends.
You may submit a function taking a string as parameter, or a standalone program using STDIN/whatever is the closest alternative in your language.
Your submission must return or print on STDOUT truthy/falsy values when it's done. Truthy values meaning the road has an end, while falsy means it is an infinite loop.
## Test cases
```
+--------------------+
|>\/ this way >\/> | this one ends here
| v^ \/ |
| v^ ^.^ |
| \/\ >v |
| /\/ ><> ^< |
+--------------------+
True
+--------+
|>>\ This|
|\\ is |
| \\ a |
| \ /trap|
+--------+
False
+--+
|<v|
|^<|
+--+
True
+--+
|>v|
|^<|
+--+
False
+----------+
|v Hello \ |
|\\/\/ / |
| \/\\ \ |
|/ // >\ |
| ^/\>\\/ |
|\ /\/\/ |
+----------+
False
+-----+
|>\/\\|
|//\\/|
|\/\\\|
|//\//|
|\/\/ |
+-----+
True
2 test cases added as suggested by @MartinBüttner
+----+
|v |
|\\ |
|//\ |
|\\v |
| \/ |
+----+
False
+----+
|v |
|\\ |
|//\ |
|\\^ |
| \/ |
+----+
False
Test case inspired by @ETHproductions
+-------------------------+
|><> |
|something smells fishy...|
+-------------------------+
False
```
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden (as always).
The winner will be the one with the shortest code in bytes.
(it would be amazing to see a ><> answer :))
[Answer]
# Non-compliant ><> answer
You wanted ><>, I give you ><> !
I believe the only sane way to do this in ><> is by copying the input in the codespace and letting the interpreter decide by itself if the input leads somewhere. Since ><> doesn't implement threading anymore, that leaves us with a big problem : if the input has a loop, we'll get stuck into it.
These considerations taken into account, I decided to make a solution compatible with [><> online interpreter](http://fishlanguage.com/playground) so that it would be possible to assert if the interpreter is stuck in the input or just taking ages to do everything. I also had to add trailing lines to the code so the online interpreter shows the added code and doesn't crash when trying to write to it.
Oh and since I'm clearly disqualified by now, I didn't bother with golfing the code.
Without further ado, the code in all its glory :
```
50i:0(?v :"^"=?v:"v"=?v:">"=?v:"<"=?v:"/"=?v:"\"=?v:"|"=?v:"-"=?va=?v1+10.
>.!603f< v"."~ < < >~1+010.
>.!01+1p}:$}:}v! < < < < < <
;oooo"true" <<
^
```
To use it, copy it in the online interpreter, add enough trailing lines to handle your input, submit the code, give it the input as `;`-separated lines and enjoy the ride.
A few tests :
>
> With
>
>
>
> ```
> +--------------------+
> |>\/ this way >\/> | this one ends here
> | v^ \/ |
> | v^ ^.^ |
> | \/\ >v |
> | /\/ ^< |
> +--------------------+`
>
> ```
>
> Final codespace :
>
>
>
> ```
> 50i:0(?v :"^"=?v:"v"=?v:">"=?v:"<"=?v:"/"=?v:"\"=?v:"|"=?v:"-"=?va=?v1+10.
> >.!603f< v"."~ < < >~1+010.
> >.!01+1p}:$}:}v! < < < < < <
> ;oooo"true" <<
> ^
> ....................
> .>\/ >\/> .
> . v^ \/ .
> . v^ ^ ^ .
> . \/\ >v .
> . /\/ ^< .
> ....................
>
> ```
>
> Outputs "true" and stops.
>
>
>
---
>
> With
>
>
>
> ```
> +--------+
> |>>\ This|
> |\\ is |
> | \\ a |
> | \ /trap|
> +--------+
>
> ```
>
> Final codespace :
>
>
>
> ```
> 50i:0(?v :"^"=?v:"v"=?v:">"=?v:"<"=?v:"/"=?v:"\"=?v:"|"=?v:"-"=?va=?v1+10.
> >.!603f< v"."~ < < >~1+010.
> >.!01+1p}:$}:}v! < < < < < <
> ;oooo"true" <<
> ^
> ........
> .>>\ .
> .\\ .
> . \\ .
> . \ / .
> ........
>
> ```
>
> Loops forever.
>
>
>
[Answer]
# JavaScript, ES6, ~~177~~ ~~161~~ 145 bytes
```
f=(s,i=1,M=[],D)=>D==5||!~M[O="indexOf"](D+i)&&f(s,i-[M.push(D+i),L=s[O]('|'),-L,1,-1][D=`431255${5-D+'X3412'[D]}`['><^v-|/\\'[O](s[i+L])]||D],M,D)
```
We can detect a cycle by traversing the path and detecting a repeat of the tuple
* location
* coming-from direction
That is, if we are entering some position `(x,y)` coming from some direction `D` for the second time, we know that this cycle will repeat forever. Therefore, the code keeps track of all locations that were visited, and from what direction, and checks against that record each time a new space is visited.
The directions up, down, left, and right are assigned the numbers `1`, `2`, `3`, and `4`. The code considers the current symbol being visited (`s[i+L]`) and changes the current direction (`D`), then the new direction is used to recursively call the function and evaluate the next space. `5` as a direction indicates a wall, and a `true` termination of the program.
Here is an explanation of less-golfed code:
```
f=
(s, // input string
i=1, // current location as offset string index
M=[], // record of previously visited spaces
D // current direction
)=>(
L=s[O="indexOf"]('|'), // find arena width `L` by index of first `|`
// if D is 5, return true, or...
D==5 ||
// if direction + position is not new, return false
!~M[O](D+i) &&
// otherwise, save this direction + position
M.push(D+i) &&
// recursively call `f` with new direction and position
f(s,
i-[,L,-L,1,-1][D= // modify position based on active direction
`431255${5-D+'X3412'[D]}` // from these possible directions...
[ // chose the one at the index...
'><^v-|/\\'[O]( // based on the index of the symbol
s[i+L] // of the current character
)
]
||D // or preserve old D if symbol is not directional
],
M,D)
```
The template string ``431255${5-D+'X3412'[D]}`` has a nested expression that handles the mirrors: because the directions are numbers, they can also be used as indexes. The expression `'X3412'[D]`, evaluates to the 8th character in the possible-direction string, and so corresponds to `\`, the 8th character in the symbol string `'><^v-|/\\'`). The expression says,
* If current direction `D` is `1` (up), then the new direction on hitting a `\` mirror will be `3` (left)
* If current direction `D` is `2` (down), then the new direction on hitting a `\` mirror will be `4` (right)
* etc.
The other mirror `/` would use the expression `'X4321'[D]`, but since that's simply an ordered count-down from `4`, we can express it more simply as `5-D`.
] |
[Question]
[
Write a program that takes two integers as an input; the first can be any integer and the second is less than or equal to the number of digits in the first number. Let these numbers be `a` and `b` respectively.
The program will do the following
* Concatenate a minimal number of `1`s to the end of `a` so the number of digits in `a` is divisible by `b`.
* Split `a` along every `b` digits.
* Multiply the digits in each section together.
* Concatenate the products together (if one of the numbers is zero, then concatenate `0`).
* Repeat this process until a number with strictly fewer than `b` digits is formed. Print this as the output, as well as the number of the process is repeated. Units are not necessary, but some form of separation between the final number and number of iterations is.
In the following test cases, the individual steps are shown for the purpose of understanding. It is not necessary for your program to display the steps.
**Test case 1**
`1883915502469, 3`
*Steps*
```
1883915502469 //Iteration 1
188391550246911
188 391 550 246 911
64 27 0 48 9
64270489 //Iteration 2
642704891
642 704 891
48 0 72
48072 //Iteration 3
480721
480 721
0 14
014 //Iteration 4
0
```
*Sample Output*: `0, 4`
**Test case 2**
`792624998126442, 4`
*Steps*
```
792624998126442 //Iteration 1
7926249981264421
7926 2499 8126 4421
756 648 96 32
7566489632 //Iteration 2
756648963211
7566 4896 3211
1260 1728 6
126017286 //Iteration 3
126017286111
1260 1728 6111
0 112 6
01126 //Iteration 4
01126111
0112 6111
0 6
06
```
*Sample Output*: `06, 4`
---
The program must return an error (or just not print anything) if `b>len(a)`. Also, `b` cannot equal 1 or the program will result in an infinite loop.
---
This is code golf, so standard rules apply. Shortest code in bytes wins.
[Answer]
# [Python](https://www.python.org), 156 bytes
```
g=lambda a,d,c=0,k=-1,j=''.join:d>(l:=len(a))and(a,c/c*c)or g(j([str(-[k:=k*x for x in map(int,j((a+l%d*"1")[i:i+d]))][k:=-1])for i in range(0,l,d)]),d,-~c)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZBBTsMwEEX3nMKyhDqT2hC7bkgimYMQZWHsNjhxnSgEqWy4CCy6gTtxGxK1SF3Of08zX_P5M7xPL308nb7fpj3Pf78aHczh2RlimGNWp6zTXLBWr1Z3be9j6R4hlDrsIhhEEx0YZu9tYrEfSQMtVK_TCLzqSt0lR7Kf0yPxkRzMAD5OrAUw63DrEiooVr70a1cj1ovPRY2L7xd_NLHZQcoCc1jjXIV_WLx0fBrGeRVQzjnFm_PQABV5vinEdptKlRWUkQ1ewYdCZlIVRS5kppScsbrG4pKcL_x_4w8)
Takes in a string and an integer, causes a DivideByZero error if the input is invalid.
---
# [Python 3 + `functools` + `operator`](https://www.python.org), 137 bytes
```
g=lambda a,d,c=0,j=''.join:d>(l:=len(a))and(a,c/c*c)or g(j([str(reduce(mul,map(int,j((a+l%d*"1")[i:i+d]))))for i in range(0,l,d)]),d,-~c)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY5NTsMwEEb3PYVlCXWcOpC4aYgjhYNQdWHsJDjyT-Q6CzbsOQObbOBOvQ2BFKmzGc33pO_N5_f4Fl-9my-0C96ibnIyem_OSNvRh5hs_mI_tkFEH_7Tryl2aXX56Bsj7IsSSFBFZZPRodlu7wevXa2ewNSNaR0IQoRTIKh8kIkkS0sPAxzPMUBo1SRbsJOhVoygXaQDgNiZO5XgHJOjrvVOncgy3a8daYeCcH0LGTVUkRNZvOm7JNeHnsewdABO0xSTzXr0gPOq2vP8cMhYUXJM0Z7cwEfOSlZwXuWsLAq24OIW59dkNczzun8A)
[Answer]
## Perl 6, 116 bytes
```
my ($a,$b)=@*ARGS;for 0..* {if $b>$a.chars {$_&&say "$a,$_";last};$a=map({[*] @_},($a~1 x$b-1).comb.rotor($b)).join}
```
```
my ($a,$b)=@*ARGS;
for 0..* {
if $b>$a.chars {$_&&say "$a,$_";last}; # you need a 「;」 if you remove the newline
$a=map(
{[*] @_},
($a~1 x$b-1).comb.rotor($b)
).join
}
```
[Answer]
# Python 3 + `functools` + `operator`, ~~242~~ ~~241~~ 205 bytes
Shorter version (thanks 97.100.97.109!)
```
def g(a,b):
c,d,j=0,int(b),''.join
while len(a)>=d:a=j(map(str,[reduce(mul,map(int,[*j(u)]))for u in zip(*[iter([a+"1"*n for n in range(d)if not len(a+"1"*n)%d][0//(d<=len(a))])]*d)]));c+=1
return (a,c)
```
Original explained version:
```
def g(a,b):
c=0
while len(a)>=int(b):a="".join(map(str,[reduce(mul,map(int,u))for u in map(list,map(''.join,zip(*[iter([a+"1"*n for n in range(int(b))if not len(a+"1"*n)%int(b)][0])]*int(b))))]));c+=1
return None if int(b)>len(a)else(a,c)
```
This was a fun one! I wish I could've made it a one-liner but there was no real way to do that without massively increasing the length. Takes input as two strings, returns a 2-tuple of a string and an int (or `None` if `b>len(a)`)
## Explanation
```
def challenge(a,b):
c=0
while len(a) >= int(b):
a="".join(
map(str,[
reduce(mul,map(int,u)) # Multiply the digits together. Uses reduce from functools and mul from operator, works similarly to sum() but for multiplication
for u in map(list,map(''.join,
zip(*[iter(
[a+"1"*n for n in range(int(b)) if not len(a+"1"*n)%int(b)][0] # Do the 1 concatenation
)]*int(b))
) # Split a along every b digits
) # Split those strings into lists
]) # Convert to a list of strings
) # Concatenate the products together
c+=1
return None if int(b)>len(a) else(a,c) # I don't really like the "return None if invalid input" requirement, but ah well
```
[Answer]
# CJam, 42 bytes
```
q~:N;Ab{_N(>}{_N/)N1e]a+::*s:~}w])S@,_])g*
```
[Test it here.](http://cjam.aditsu.net/#code=q~%3AN%3BAb%7B_N(%3E%7D%7B_N%2F)N1e%5Da%2B%3A%3A*s%3A~%7Dw%5D)S%40%2C_%5D)g*&input=1883915502469%203)
[Answer]
# Pyth, 32 bytes
```
IglzQf<l=zjk*MsMMc+z*\1%_lzQQQ)z
```
[Demonstration](https://pyth.herokuapp.com/?code=IglzQf%3Cl%3Dzjk%2aMsMMc%2Bz%2a%5C1%25_lzQQQ%29z&input=0&test_suite=1&test_suite_input=1883915502469%0A3%0A792624998126442%0A4%0A12%0A3&debug=0&input_size=2)
Takes input on two lines, `a` followed by `b`. Gives output on two lines, operations followed by result.
Pad: `+z*\1%_lzQ`
Chop: `c ... Q`
Convert to list of ints: `sMM`
Take products: `*M`
Convert back to str: `jk`
Assign back: `=z`
Check for termination: `<l ... Q`
Print iterations taken: `f ... )`
Print result: `z`
Initial check of whether to print anything at all: `IglzQ`
[Answer]
# [Ruby](https://www.ruby-lang.org/), 139 bytes
```
f=->n,b,i=1{c=[*n.scan(/.{#{b=b.to_i}}/),*$'[0]&&$'.ljust(b,?1)].map{_1.chars.map(&:to_i).reduce:*}*""
c.size<b ?[c,i]:f[c,b,i+1]}
p f[*$*]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN7vTbHXt8nSSdDJtDauTbaO18vSKkxPzNPT1qpWrk2yT9Ery4zNra_U1dbRU1KMNYtXUVNT1crJKi0s0knTsDTVj9XITC6rjDfWSMxKLikEcDTUrkB5NvaLUlNLkVCutWi0lJa5kveLMqlSbJAX76GSdzFirNCAFtFTbMLaWq0AhLVpLRSsW4iSoyzZFG1pYGFsampoaGJmYWeooGMdCZQA)
## Explanation
```
f = ->n,b,i=1{ # Recursive lambda definition; n is the number, b is the target length, i is the number of iterations
c = [ # Make an array of...
*n.scan(/.{#{b=b.to_i}}/), # the whole sections of length b
*$'[0] && $'.ljust(b, ?1) # plus, if there’s stray letters, the final section padded to length b
].map{
_1.chars.map(&:to_i).reduce :* # Multiply each section’s digits
} * "" # Join back together
c.size < b ? # If we’re under the target length...
[c, i] : # return the remaining string and iteration count
f[c, b, i+1] # otherwise call itself recursively, incrementing the iteration count
}
p f[*$*] # $* is ARGV; splat it into f's arguments
```
] |
[Question]
[
Write a program that takes in (via stdin or command line) a string with the recursive form
```
PREFIX[SUFFIXES]
```
where
* `PREFIX` may be any string of lowercase letters (a-z), including the empty string, and
* `SUFFIXES` may be any sequence of strings with the recursive form `PREFIX[SUFFIXES]` concatenated together, including the empty sequence.
Generate a list of lowercase lettered strings from the input by recursively evaluating the list of strings in each of the suffixes and appending them to the prefix. Output to stdout the strings in this list in any order, one per line (plus an optional trailing newline).
>
> ### Example
>
>
> If the input is
>
>
>
> ```
> cat[s[up[][]][]ch[e[r[]s[]]]a[maran[]comb[]pult[[]ing[]]]]
>
> ```
>
> then the prefix is `cat` and and the suffixes are `s[up[][]]`, `[]`,
> `ch[e[r[]s[]]]`, and `a[maran[]comb[]pult[[]ing[]]]`. Each suffix has
> its own prefix and suffixes in turn.
>
>
> The output would be these 9 words in any order
>
>
>
> ```
> catsup
> cats
> cat
> catcher
> catches
> catamaran
> catacomb
> catapult
> catapulting
>
> ```
>
> because the input encodes this tree
>
>
> [](https://i.stack.imgur.com/T9Z4f.png)
>
>
> and each of the 9 output words can be formed by traversing the tree
> from root to leaf.
>
>
>
### Notes
* Remember that the prefix may be the empty string, so something like
```
[donut[][]cruller[]]
```
is valid input whose output would be (in any order)
```
donut
cruller
```
where the empty line is for the empty string that the second suffix matches.
* The suffix sequence can also be empty, so the trivial input case
```
[]
```
has a single empty line as its output:
```
```
* You may assume that the input will only produce unique output words.
+ e.g. `hat[s[]ter[]s[]]` would be invalid input because `hats` is encoded twice.
+ Similarly, `[[][]]` is invalid because the empty string is encoded twice.
* You may *not* assume that the input is as short or compressed as possible.
+ e.g. the `'e'` node in the main example above could be combined with the `'ch'` node, but that's doesn't mean the input is invalid.
+ Similarly, `[[[[[]]]]]` is valid, despite only encoding the empty string in a sub-optimal way.
* Instead of a program you may write a function that takes the input string as an argument and prints the output normally or returns it as a string or list.
**The shortest code in bytes wins.**
[Answer]
## Haskell, 125 bytes
```
t=tail.p
p=g.break(=='[')
g(a,(_:t))=(:)&(map(a++).z)$t#[]
z[]=[""];z x=x
(']':u)#a=u:a
s#a=(#)&(a++)$p s
(g&f)(x:y)=g x$f y
```
The function is `t` (for traversal):
```
λ: t "cat[s[up[][]][]ch[e[r[]s[]]]a[maran[]comb[]pult[[]ing[]]]]"
["catsup","cats","cat","catcher","catches","catamaran","catacomb","catapult","catapulting"]
λ: t "[donut[][]cruller[]]"
["donut","","cruller"]
λ: t "[[[[[]]]]]"
[""]
```
[Answer]
# Ruby, ~~119~~ 115
```
t=['']
l=[0]
gets.chars{|c|c<?]?t<<''&&(l<<0)[-2]+=1:c<?^?(x=l.pop;t.pop==''&&(puts t*''if x<1;t[-1]='')):t[-1]<<c}
```
### Example
Try it: <http://ideone.com/NW0CNB>
### Description
The program gets the input from stdin and outputs the result to stdout.
It traverses the tree keeping the current branch in a stack. There's also a different stack, called `weights` which keeps track of the number of children of each node. This is needed in order to determine if a node is really a leaf, or it had children in the past.
The readable program:
```
stack = ['']
weights = [0]
gets.chars do |c|
case c
when '['
weights[-1] += 1
stack << ''
weights << 0
when ']'
last_weight = weights.pop
if stack.pop == ''
puts stack.join if last_weight < 1
stack[-1] = ''
end
else
stack[-1] << c
end
end
```
[Answer]
# Java, 206 bytes
Defines a function that accepts a string as an argument and returns a list of strings. For an added bonus it returns strings in the same order as the question does.
```
int c,i;List a(String a){String b=a.substring(c,c=a.indexOf(91,c));List d=new ArrayList();for(;a.charAt(++c)!=93;)d.addAll(a(a));if(d.isEmpty())d.add("");for(i=0;i<d.size();)d.set(i,b+d.get(i++));return d;}
```
### Example usage:
```
class A{
public static void main(String[] args){
System.out.println(new A.a("cat[s[up[][]][]ch[e[r[]s[]]]a[maran[]comb[]pult[[]ing[]]]]"));
}
int c,i;List a(String a){String b=a.substring(c,c=a.indexOf(91,c));List d=new ArrayList();for(;a.charAt(++c)!=93;)d.addAll(a(a));if(d.isEmpty())d.add("");for(i=0;i<d.size();)d.set(i,b+d.get(i++));return d;}
}
```
### Expanded:
```
int c, i;
List a(String a){
String b = a.substring(c, c = a.indexOf(91, c));
List d = new ArrayList();
for(; a.charAt(++c) != 93 ;)
d.addAll(a(a));
if (d.isEmpty())
d.add("");
for (i = 0; i < d.size();)
d.set(i, b + d.get(i++));
return d;
}
```
I will add an explanation tomorrow.
[Answer]
# Python, 212 chars
```
def p(t,f="",o="",d=0):
if[]==t:return
b=[""]
for c in t:d+=c=="[";b[-1]+=c;d-=c=="]";b+=[""]*(d==0)*(c=="]")
for r in b[:-1]:i=r.index("[");w,s=f+r[:i],r[i:][1:-1];p(s,w);o+= ["",w+"\n"][""==s]
if o:print o,
```
I was hoping to get under 200, but still I am pretty happy with this.
[Answer]
# Javascript ES6, 142 bytes
```
s=>(o=[],x=_=>s[0]==']'?s=s.slice(1):0,(g=d=>{while(s&&!x())[o[d],s]=s.split(/\[(.*)/).concat``,x()?console.log(o.join``):g(d+1),o.pop()})(0))
```
[Answer]
## Q: 70 Bytes
```
f:{,/'$({(z_x),y}\[();{`$x@&~x="]"}'w;-b])@-1+&0<b:(+/"]"=)'w:"["\:x}
```
defines a function f that accepts a string and return a list of strings (words)
As a lambda (anonymous function) we drop the first 2 chars f:, so length is 68 Bytes
**Test**
```
f "cat[s[up[][]][]ch[e[r[]s[]]]a[maran[]comb[]pult[[]ing[]]]]"
```
("catsup";"cats";"cat";"catcher";"catches";"catamaran";"catacomb";"catapult";"catapulting")
```
f "[donut[][]cruller[]]"
```
("donut";"";"cruller")
```
f "[[[[[]]]]]"
```
,""
**Notes**
,"" indicates a list of strings that contains only has an empty string
Symbols are atomic. Push/pop a symbol on the stack is a simple operation not affected by the lenght of the symbol (see explanation)
**Explanation**
Q is a cousin of APL (kx.com)
Pseudocode:
* Splits string (arg x) at "[" char. Result (list of strings) in w
* Counts "]" chars in each elem. of w. Result in b
* Modifies each item in w to filter out character "]" and converts each string to a symbol
* Generates a logical sequence (bitmap) to mark items >0 in b
* Iterates over partial results with a stack: if item marked we must drop one of more symbols (according to value in b). Always append actual symbol to stack
* After iterating we have all intermediate states of stack. We select previously marked states
* finally for each result we convert symbols to strings and concatenate them
[Answer]
# Cobra - 181
```
def f(s='')as String*
for m in RegularExpressions.Regex.matches(s,r'(\w*)\[((?:(?<B>\[)|\w|(?<-B>]))*)](?(B)(?!))'),for r in.f('[(u=m.groups)[2]]'),yield'[u[1]]'+r
if''==s,yield''
```
] |
[Question]
[
The species of geese known as *Alex A* are known for residing in triangular grids consisting of 64 cells:

(Picture taken from this [unrelated Project Euler problem](https://projecteuler.net/problem=189).)
We'll label each cell with the numbers `0` to `63` starting from the top row and then moving from left to right on each row below that. So the top cell is `0` and the bottom-right cell is `63`.
Each cell has three borders. We can label each border in the form `a,b` where `a` and `b` are the numbers of the cells that share that border. For instance, the border between cell `0` and `2` would be called `0,2` or `2,0` (it doesn't matter what order you put them in).
The labeling system for borders on the very edge of the grid are different, since the cells on the edge of the grid have a border that they don't share with other cells. If a border is only part of one cell, we will use the letter `X`. For instance, the three borders of cell `0` are `0,2`, `0,X`, and `0,X`.
Some of the cells contain *geese*. However, these geese will be killed by evil foxes (that come from outside the borders of the grid) if you don't protect them. And if all the geese die then BrainSteel will be sad. Therefore we will write a program that builds fences around the geese to protect them from the foxes. The geese should exist in a **single** fully enclosed polygon of fences. Our fence budget is quite low so use the least number of fences possible.
**Input Description**
A list of numbers, comma separated, from `0` to `63`, representing the cells that contain geese. Example:
```
6,12
```
**Output Description**
A list of borders that need to have fences built on them to protect the geese successfully. This should be the smallest number of fences possible. Example:
```
5,6 6,7 11,12 12,13
```
[Answer]
# C#, 530 bytes
Complete C# program, takes input as a single line from STDIN, and outputs a single line to STDOUT, with a trailing " ".
This is rather long... and has way too much x/y/z repetition, but I've not been able to reduce it to anything sensible thus far, and have an exam in 2 hours, might come back to this tomorrow.
```
using Q=System.Console;class P{static void Main(){int q=9,w=0,e=9,r=0,t=9,u=0,i=0,x=0,y=0,z=0,p=0;System.Action V=()=>{z=(int)System.Math.Sqrt(i);p=(x=i-z*z)%2;x/=2;y=(++z*z--+~i)/2;},W=()=>{Q.Write(i+","+(x<0|y++<0|z>7?"X":""+(z*z+2*x+1-p))+" ");};foreach(var g in Q.ReadLine().Split(',')){i=int.Parse(g);V();q=q>x?x:q;w=w<x?x:w;e=e>y?y:e;r=r<y?y:r;t=t>z?z:t;u=u<z?z:u;}for(i=64;i-->0;){V();if(!(x<q|x>w|y<e|y>r|z<t|z>u))if(p>0){if(y==r)W();if(x++==w)W();x--;if(z--==t)W();}else{if(y--==e)W();if(x--==q)W();x++;if(z++==u)W();}}}}
```
This diagram explains most of what is going on.

Recognize that because we can't have 0-width sections, a "hexagon" is always going to be the cheapest shape (and has the benefit of giving the geese the maximum of space to move in).
The program works by first translating all the input cell indices into x/y/z coords, and finding the min/max of each of x/y/z.
```
z = floor(root(i))
x = floor((i - z^2) / 2)
y = floor((z+1)^2 - i - 1) / 2)
p = (i - z^2) % 2
```
Next, it goes through each cell index, and checking if it fits in the 'hexagon' bound we have described. If it is then it checks if it's on any of the extreme edges of the bounds (i.e. x = xmin, or y = ymax) and adds corresponding edges if it is. It has to work out the index of the edge it's next to. For x and z, we just increment/decrement them however we want, and then use the following formula:
```
i = z^2 + 2*x + (1-p)
```
Notice that the "parity" always changes, and that y is not involved. For y, we don't have to change anything, but the code is a bit of a mess because it has to perform "triangle" bounds checking to detect whether the cell next door should be an "X" or not.
Example solution (Cells with geese just in from the three corners):
```
Input
2,50,62
Output
62,63 61,X 59,X 57,X 55,X 53,X 51,X 50,49 48,X 36,X 35,X 25,X 24,X 16,X 15,X 9,X 8,X 4,X 3,X 2,0 1,X
```
Tidier code with comments:
```
using Q=System.Console;
class P
{
static void Main()
{
int q=9,w=0,e=9,r=0,t=9,u=0, // min/max x/y/z/ (init min high, and max low)
i=0, // index of cell we are looking at
x=0,y=0,z=0,p=0; // x,y,z dimension
System.Action V=()=>
{ // translates the index into x/y/z/p
z=(int)System.Math.Sqrt(i);
p=(x=i-z*z)%2; // 'parity'
x/=2; // see p assignment
y=(++z*z--+~i)/2; // ~i == -i - 1
},
W=()=>
{ // writes out the edge of i, and the cell described by x/z/inverse of p (the inversion of p handles y +/-)
Q.Write(i+","+ // write out the edge
(x<0|y++<0|z>7?"X":""+(z*z+2*x+1-p)) // either X (if we go out of 'trianlge' bounds), or we translate x/z/inverse of p into an index
+" "); // leaves a trailing space (as shown in example output)
};
foreach(var g in Q.ReadLine().Split(',')) // for each cell with geese
{
i=int.Parse(g); // grab index of cell
V(); // compute x/y/z/p
q=q>x?x:q; // sort out mins/maxes
w=w<x?x:w;
e=e>y?y:e;
r=r<y?y:r;
t=t>z?z:t;
u=u<z?z:u;
// code like the above suggests a solution with a couple of arrays would be better...
// I've not had success with that yet, but maybe in a couple of days I will try again
}
for(i=64;i-->0;) // for each cell
{
V(); // compute x/y/z/p
if(!(x<q|x>w|y<e|y>r|z<t|z>u)) // if we are inside the 'hex' bounds
if(p>0)
{ // x max, y max, z min
// these checks check that we are on the extremes of the 'hex' bounds,
// and set up the appropriate vars for W calls to put the edges in
// must do y first, because W modifies it for us (saves 2 bytes in the next block)
if(y==r) // don't need the ++ (can't go out of 'trianlge' bounds)
W();
if(x++==w)
W();
x--;
if(z--==t)
W();
//z++; not used again
}
else
{ // x min, y min, z max
if(y--==e) // do need the -- (used for 'trianlge' bounds checking)
W();
// y is reset in W, as such
if(x--==q)
W();
x++;
if(z++==u)
W();
//z--; not used again
}
}
}
}
```
] |
[Question]
[
A [Friedman Number](https://en.wikipedia.org/wiki/Friedman_number) is a positive integer that is equal to a non-trivial expression which uses its own digits in combination with the operations +, -, \*, /, ^, parentheses and concatenation.
A Nice Friedman Number is a positive integer that is equal to a non-trivial expression which uses its own digits in combination with the same operations, with the digits in their original order.
A Very Nice Friedman Number (VNFN), which I am inventing here, is a Nice Friedman Number which can be written without the less pretty (in my opinion) parts of such an expression. Parentheses, concatenation and unary negation are disallowed.
For this challenge, there are three possible ways of writing an expression without parentheses.
**Prefix:** This is equivalent to left-associativity. This type of expression is written with all operators to the left of the digits. Each operator applies to the following two expressions. For instance:
```
*+*1234 = *(+(*(1,2),3),4) = (((1*2)+3)*4) = 20
```
A VNFN which can be written this way is 343:
```
^+343 = ^(+(3,4),3) = ((3+4)^3) = 343
```
**Postfix:** This is equivalent to right-associativity. It is just like prefix notation, except that the operation go to the right of the digits. Each operator applies to the two previous expressions. For instance:
```
1234*+* = (1,(2,(3,4)*)+)* = (1*(2+(3*4))) = 14
```
A VNFN which can be written this way is 15655:
```
15655^+** = (1,(5,(6,(5,5)^)+)*)* = (1*(5*(6+(5^5)))) = 15655
```
**Infix:** Infix notation uses the standard order of operations for the five operations. For the purposes of the challenge, that order of operations will be defined as follows: Parenthesize `^` first, right associatively. Then, parenthesize `*` and `/` simultaneously, left associatively. Finally, parenthesize `+` and `-` simultaneously, left associatively.
```
1-2-3 = (1-2)-3 = -4
2/3*2 = (2/3)*2 = 4/3
2^2^3 = 2^(2^3) = 256
1^2*3+4 = (1^2)*3+4 = 7
```
A VNFN which can be written this way is 11664:
```
1*1*6^6/4 = (((1*1)*(6^6))/4) = 11664
```
**Challenge:** Given a positive integer, if it can be expressed as a non-trivial expression of its own digits in either prefix, infix or postfix notation, output that expression. If not, output nothing.
**Clarifications:** If multiple representations are possible, you may output any non-empty subset of them. For instance, 736 is a VNFN:
```
+^736 = 736
7+3^6 = 736
```
`+^736`, `7+3^6` or both would all be acceptable outputs.
A "Trivial" expression means one that does not use any operators. This only is relevant for one digit numbers, and means that one digit numbers cannot be VNFNs. This is inherited from the definition of a Friedman Number.
Answers should run in seconds or minutes on inputs under a million.
[Related.](https://codegolf.stackexchange.com/questions/6673/generate-friedman-numbers)
**IO:** Standard IO rules. Full program, function, verb or similar. STDIN, command line, function argument or similar. For outputing "Nothing", the empty string, a blank line, `null` or similar, and an empty collection are all fine. Output may be a string delimited with a character that cannot be in a representation, or may be a collection of strings.
**Examples:**
```
127
None
343
^+343
736
736^+
7+3^6
2502
None
15655
15655^+**
11664
1*1*6^6/4
1^1*6^6/4
5
None
```
**Scoring:** This is code golf. Fewest bytes wins.
Also, if you find one, please give a new Very Nice Friedman Number in your answer.
[Answer]
# Perl, ~~345~~ ~~334~~ ~~318~~ ~~293~~ ~~263~~ 245B
```
$_='$_=$i=pop;$c=y///c-1;sub f{say if$c&&$i==eval pop=~s/\^/**/gr}A$m)$1$4"})};f"("x$c.$m}globOx$c.$i;A$1$4($m"})};f$m.")"x$c}glob$i.Ox$c;map{f$_}glob joinO,/./g';s!O!"{+,-,*,/,^}"!g;s!A!'map{m{(\d)((?R)|(\d)(?{$m=$3}))(.)(?{$m="'!ge;s!d!D!;eval
```
Call with `perl -M5.10.0 scratch.pl 736`
---
## Results
The first few results that I found are:
```
^+343
736^+
7+3^6
^+/3125
^+^3125
/^+-11664
/^--11664
1-1+6^6/4
/^++14641
^^++14641
1+5^6/1-8
1+5^6^1-8
1+5^6-2-2
1+5^6-2^2
1+5^6+2-4
1+5^6+4^2
-^+^16377
-^-+16377
/^+^16384
/^-+16384
```
---
## Explanation
### Fully ungolfed
I tried to repeat myself as much as possible to make the later golfing easier.
```
#!perl
use 5.10.0;
$_ = $input = pop;
# y///c counts characters in $_
$count = y///c - 1;
sub f {
say if $count && $input == eval pop =~ s/\^/**/gr
}
# PREFIX
map {
m{ # Parses *^+1234
(\D) # $1 = first symbol
(
(?R) # RECURSE
|
(\d)(?{ # $3 = first digit
$match=$3
})
)
(.)(?{ # $4 = last digit
$match="$match)$1$4"
})
}x;
f "(" x $count . $match
}
# glob expands '{0,1}{0,1}' into 00,01,10,11
glob "{+,-,*,/,^}" x $count . $input;
# POSTFIX
map {
m{(\d)((?R)|(\d)(?{$match=$3}))(.)(?{$match="$1$4($match"})};
f $match. ")" x $count
}
glob $input . "{+,-,*,/,^}" x $count;
# INFIX
# /./g splits $_ into characters
map { f $_} glob join "{+,-,*,/,^}", /./g
```
### How it's golfed
* Remove whitespace & comments and replace all vars with 1-character version
* Wrap program in `$_=q! ... !;eval`
* Extract strings and substitute them in afterwards.
This gives something like this, from which you can remove the line breaks for the result:
```
$_='
$_=$i=pop;
$c=y///c-1;
sub f{say if$c&&$i==eval pop=~s/\^/**/gr}
A$m)$1$4"})};f"("x$c.$m}globOx$c.$i;
A$1$4($m"})};f$m.")"x$c}glob$i.Ox$c;
map{f$_}glob joinO,/./g
';
s!O!"{+,-,*,/,^}"!g;
s!A!'map{m{(\d)((?R)|(\d)(?{$m=$3}))(.)(?{$m="'!ge;
s!d!D!;
eval
```
[Answer]
## Ruby 2.1.5 only - 213 220 238 + 9 = 247
Not sure how Ruby beats Perl, but here you go...
Run this with a -rtimeout flag (and either -W0 or send your stderr elsewhere).
To make this *slightly* more robust, replace `send([].methods[81],z-1)` with `repeated_permutation(z-1)` and score an extra character (so, **248**).
```
g=$*[0].split //
exit if 2>z=g.size
d=->a,s{$><<a*''&&exit if$*[0].to_i==timeout(2){eval"#{(s*'').gsub(?^,'**')}"}rescue p}
l,r=[?(]*z,[?)]*z
%w{* / + - ^}.send([].methods[81],z-1){|o|d[m=g.zip(o),m]
d[g+o,l.zip(m)+r]
d[o+g,l+g.zip(r,o)]}
```
Basically, go through all permutations of operators and try infix, postfix, and prefix in that order. The `d` method uses `eval` on the second parameter to perform the calculations, catching any DivideByZero or Overflow exceptions.
You need to send stderr to /dev/null, though, or else `eval` will sometimes print warnings like `(eval):1: warning: in a**b, b may be too big`.
While I came up with this ungolfing, I found a way to save three chars!
### Ungolfed (outdated but similar principles):
```
input = $*[0]
digits = input.split //
num_digits = digits.size
exit if 2 > num_digits # one-digit numbers should fail
def print_if_eval print_array, eval_array
# concatenate the array and replace ^ with **
eval_string = (eval_array * '').gsub(?^, '**')
val = eval(eval_string)
if input.to_i == val
$><<print_array*''
exit
end
rescue
# this catches any DivideByZero or Overflow errors in eval.
end
# technically, this should be * (num_digits - 1), but as long as we
# have AT LEAST (num_digits - 1) copies of the operators, this works
operators = %w{* / + - ^} * num_digits
left_parens = ['('] * num_digits
right_parens = [')'] * num_digits
operators.permutation(num_digits-1) { |op_set|
# infix
# just uses the native order of operations, so just zip it all together
# 1+2-3*4/5^6
print_if_eval(digits.zip(op_set),
digits.zip(op_set))
# postfix
# leftparen-digit-operator, repeat; then add right_parens
# (1+(2-(3*(4/(5^(6))))))
#
print_if_eval(digits+op_set,
(left_parens.zip(digits, op_set) + right_parens))
# prefix
# leftparens; then add digit-rightparen-operator, repeat
# ((((((1)+2)-3)*4)/5)^6)
print_if_eval(op_set+digits,
left_parens + digits.zip(right_parens, op_set))
}
```
### Changelog
**247** made this work for larger numbers instead of timing out.
**220** shaved off three chars by declaring paren arrays, and fixed a bug where one-digit numbers were considered VNFNs
**213** initial commit
[Answer]
MATLAB (435 b)
```
n=input('');b=str2num(fliplr(num2str(n)));l=floor(log(b)/log(10));a=unique(nchoosek(repmat('*+-/^', 1,5), l), 'rows');for k=1:numel(a(:,1)),for j=0:2,c=strcat((j>1)*ones(l)*'(',mod(b,10)+48);for i=1:l,c=strcat(c,a(k,i),(j<1)*'(',mod(floor(b/10^i),10)+48,(j>1)*')'); end,c=strcat(c,(j<1)*ones(l)*')');if eval(c(1,:))==n,fprintf('%s%s%s%s\n',c(1,1:(j==1)*numel(c(1,:))),fliplr(a(k,1:(j>1)*l)),(j~=1)*num2str(n),a(k,1:(j<1)*l));end,end,end
```
---
try it here
<http://octave-online.net/>
[Answer]
## Python 2, 303 bytes
[Try it online](https://tio.run/nexus/python2#VYxBTsMwEEXX@BRWNzO2k6JIqAtLXkXd9QYIVOO6kpEzthwXJSy4eggtCJjVn6/3/nIuaeCh@lJTiiMPQ06lSkYmUL5UFCya6AlJtB3bG/9mIzunwh0PxHNJp4urCKqV98/QFJ@9rSYKzfjBRDu8nCyfmllP29cUCAebcb7G5j1kpMYpBGjEetvVjdZ5hHUHpATBeG8AbqJbv1pmze7C@bjHw5cFIMTRGNK5BKr8p/tGAEG2H1HdavGf7R@1brsnRb97eJXVSsr4FyXVM@4n53PV2Y7jsmy6brd72HwC)
```
from itertools import*
n=input()
l=len(n)-1
E=eval
for c in product('+-*/^',repeat=l):
L=lambda x,y:x.join(map(y.join,zip(n,c+('',)))).replace('^','**')
C=''.join(c)
try:
if`E(L('',''))`==n:print L('','')
if`E('('*-~l+L('',')'))`==n:print C[::-1]+n
if`E(L('(','')+')'*l)`==n:print n+C
except:pass
```
Infix output will contain `**` instead of `^`. If this is not allowed, `.replace('**','^')` will occure and add another 18 bytes
Explanation:
```
# get all possible combinations of operators (with repetitions)
product('+-*/^',repeat=l)
# create string from input and operators like
# if passed '(' and '' will return (a+(b+(c
# if passed '' and ')' will return a)+b)+c)
# if passed '' and '' will return a+b+c
lambda x,y:x.join(map(y.join,zip(n,c+('',)))).replace('^','**')
# evaluate infix
E(L('',''))
# evaluate prefix
E('('*-~l+L('',')'))
# evaluate postfix
E(L('(','')+')'*l)
# all evals need to be inside try-except to handle possible 0 division
# prefix output is need to be swapped (which IMO is not needed)
n:print C[::-1]+n
```
] |
[Question]
[
This is a simple encryption method that uses PI digits to encode a message, the method is simple:
The key is just a positive integer that indicates where the window starts then:
Given a string to encrypt, containing only lowercase letters, no spaces, you take its length, then you find the Nth digit of PI and then proceeds to shift every letter to the right for the amount indicated by the digit.
For example, if the key is `2` and I want to encode `house`, I take a window of 5 digits from the second one: `14159` and then it becomes:
```
h -> i
o -> s
u -> v
s -> x
e -> n
```
a.- Your program/function/algorithm will receive two parameters, an string composed only of lowercase letters with no spaces and the key, which will be just a positive integer between 1 (1 refers to 3) and 1000, which could be more or less as I'm not quite sure how long does it take to compute PI with said accuracy because:
b.- You must compute PI yourself in your code, here is a neat webpage to compare with: [Pi Day](http://www.piday.org/million/). The input should never have you calculate PI beyond the 1000 digit, meaning that length(message)+key <= 1000.
By computing Pi, I mean not harcode it in your code (silly for a code golf) nor use any embedded constant in your code nor any trigonometric identity (2\*acos(0)) nor any web reference.
c.- The output will be just the encrypted string.
This is a code golf question, shorter code wins!
I'll be accepting the winning answer at July 14th, 2014.
[Answer]
# Python - 370
Ok, nice one, finally got the pi thing working with thanks to [link1](http://www.math.hmc.edu/funfacts) and [link2](http://thelivingpearl.com/2013/05/28/computing-pi-with-python/).
```
from decimal import *
def f(s,n):
j=len(s)
getcontext().prec=j+n+5
d=Decimal
e=d(0)
for k in range(0,j+n+5):
e+=(d(16)**(-k)*(d(4)/(8*k+1)-d(2)/(8*k+4)-d(1)/(8*k+5)-d(1)/(8*k+6)))
c=`e`.split("'")[1].replace('.','')
t=''
for i,l in enumerate(s):
o=ord(l)
for v in[0,32]:
if 64+v<o<91+v:
l=chr(((o-65-v)+int(c[i+n-1]))%26+65+v)
t+=l
print t
```
Example output:
```
>>> f('house',2)
isvxn
```
and another:
```
Wimt fcy d dnyh uhkvkv qhvadil
```
>
> >>> f('This was a very secret message',1)
>
>
>
[Answer]
# CJam - 51
```
l_,li(2e4,-2%{2+_2/@*\/2e2000+}*Ab><]z{~+_'z>26*-}%
```
Example input:
```
zebra
20
```
Output:
```
dkdxe
```
This works for (string length) + key <= 2000, but is quite slow for the online interpreter (still fast with the java interpreter).
Here's a version that works up to 200 and you can try at <http://cjam.aditsu.net/> without waiting too long:
```
l_,li(2e3,-2%{2+_2/@*\/2e200+}*Ab><]z{~+_'z>26*-}%
```
[Answer]
# JavaScript - 167 ~~173~~ ~~176~~
Thanks to **Michael** for the clever representation of powers of 16.
This can calculate PI up to the 16-th digit.
```
function e(s,o){for(p=i=n=r='',m=1;s[+i];m<<=4,n>o?r+=String.fromCharCode(s.charCodeAt(i)-+-(1e15*p+'')[o+i++]):0)p-=(4/((d=8*n++)+1)-2/(d+=4)-1/++d-1/++d)/m;return r}
```
The test case:
```
> e("house",2)
"isvxn"
```
[Answer]
## Python - 321 304 288 285
```
from decimal import*
d=Decimal
s,n=raw_input(),input()
l=len(s)
getcontext().prec=n+l
print''.join([chr((v-97)%26+97)for v in map(sum,zip(map(ord,s),map(int,str(sum([(d(4)/(8*k+1)-d(2)/(8*k+4)-d(1)/(8*k+5)-d(1)/(8*k+6))/16**k for k in range(0,l+n)])).replace('.','')[n-1:n+l])))])
```
Most of the golfed version is easy to read and understand. The final line is ungolfed below:
```
# Calculate PI using the BBP formula.
pi = 0
for k in range(0,l+n):
pi += (d(1)/(16**k))*((d(4)/(8*k+1))-(d(2)/(8*k+4))-(d(1)/(8*k+5))-(d(1)/(8*k+6)))
# Remove the decimal point in PI.
pi = str(pi).replace('.','')
result = []
# For the ASCII sum of each pair of letters in `s` and its digit in PI
for v in sum(zip(map(ord, s), map(int, pi))):
result.append((v-97)%26+97)
# Convert all the ordinal values to characters
print ''.join(map(chr, result))
```
EDIT #1: simplified my module arithmetic.
EDIT #2: refactored the BBP formula.
[Answer]
# Haskell - 265 ~~267~~ bytes (no IO)
```
p=g(1,0,1,1,3,3)where g(q,r,t,k,n,l)=if 4*q+r-t<n*t then n:g(10*q,10*(r-n*t),t,k,div(10*(3*q+r))t-10*n,l) else g(q*k,(2*q+r)*l,t*l,k+1,div(q*(7*k+2)+r*l)(t*l),l+2)
e i s=zipWith(\k c->toEnum$fromIntegral k+fromEnum c::Char)(take(length s)$drop(fromIntegral$i-1)p)s
```
`p` is a golfed version of the algorithm that can be found at <http://rosettacode.org/wiki/Pi#Haskell>
`e` is the encoding function :
```
λ> e 2 "house"
"isvxn"
```
It does not loop around if an index is outside of the lowercase alphabet. This means that some other characters can slip in the encoded string :
```
"Sfufv#Kork(mq}nns j{i&sv&xitmujtu&vey|h{xljej|35.)(\"%(\"\"&\" %\"\"$()$ ''\"&'!)$'(\"&($(\"& !$'&)]hrs\"ow olih7$Tdkhnsj ns&qpdlw}oplwmxbipn#o{ur!vhbp\"mitj/"
```
Unfortunately, it takes several seconds with offsets greater than `10 000` to compute the output. Fortunately, when using the same offset multiple times, the digits only have to be computed the first time.
# Bonus - Decoding
```
d i s=zipWith(\k c->toEnum$fromEnum c-fromIntegral k::Char)(take(length s)$drop(i-1)p)s
```
Again if we test with `isvxn` :
```
λ> d 2 "isvxn"
"house"
```
[Answer]
# CoffeeScript - 148 Chars/Bytes
*My first ever Code Golf*
*Unfortunately It does not support wrapping (So a z would end up being punctuation)*
>
> e=(m,k)->(m.split('').map (v,i)->String.fromCharCode v.charCodeAt()+parseInt Math.PI.toString().replace('.','').slice(k-1,m.length+k-1)[i]).join('')
>
>
>
Demo on [CSSDeck](http://cssdeck.com/labs/eon3dz3e)
Called with:
>
> alert e 'house', 2
>
>
>
> >
> > isvxn
> >
> >
> >
>
>
>
] |
[Question]
[
Given a list of strings, sort the list as numbers without knowing what base is used. The values of the digits are also unknown (it is possible that `'1'` > `'2'`).
Since the values of digits are unknown, use [Benford's Law](http://wikipedia.org/wiki/Benford%27s_law) (or First Digit's Law) to determine the relative value of the digits. For distributions that follow Benford's Law, lower valued digits appear as a leading digit more frequently than higher valued digits.
**Rules**
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
* The list of strings can come from a source of your choosing (stdin, variable, file, user, etc.)
* Strings are limited to ASCII characters.
* Characters that do not appear as a leading character have the highest values. (assume there are no zeros, and sort strictly by leading frequency.)
* Characters that appear as leading digits the same number of times as other characters are weighted equally.
**Example**
*Unsorted*
```
['c','ca','ac','cc','a','ccc','cx','cz','cy']
```
*Sorted*
```
['c','a','cc','ca','cz','cy','cx','ac','ccc']
```
*Note:* In the example, `'cz'`,`'cy'` and `'cx'` can appear as the 5th, 6th and 7th elements in any order since the digits `'x'`,`'y'` and `'z'` are equally weighted.
[Answer]
# Python, 59 ~~108~~ ~~112~~
```
sorted(a,None,lambda x:(-len(x),map(zip(*a)[0].count,x)),1)
```
Input is provided as the list `a`, and this expression produces the sorted list (+2 characters to assign to a variable). This sorts the list *in reverse* by negated length and then by frequency.
[Answer]
# Ruby, 65
```
f=->a{a.sort_by{|s|[s.size,s.chars.map{|c|a.count{|t|t[0]!=c}}]}}
```
Sorts lexicographically on the string's size, then each character's frequency as not the leading digit.
[Answer]
## Java (261)
```
void s(String[]s){int[]a=new int[128];for(String t:s)a[t.charAt(0)]++;java.util.Arrays.sort(s,(o,p)->{int j=o.length()-p.length();if(j!=0)return j;for(int i=0;i<Math.min(o.length(),p.length());i++){j=a[p.charAt(i)]-a[o.charAt(i)];if(j!=0)return j;}return 0;});}
void s(String[] s) {
int[] a = new int[128];
for (String t : s) {
a[t.charAt(0)]++;
}
java.util.Arrays.sort(s, (o, p) -> {
int j = o.length() - p.length();
if (j != 0) {
return j;
}
for (int i = 0; i < Math.min(o.length(), p.length()); i++) {
j = a[p.charAt(i)] - a[o.charAt(i)];
if (j != 0) {
return j;
}
}
return 0;
});
}
```
The methods takes an array of strings, and sorts the array in place. Nothing fancy about the implementation, but it does make use of the lambda expressions added to Java 8.
[Answer]
# Javascript (E6) 147
```
F=i=>(f={},i.map(x=>(f[x[0]]=-~f[x[0]])),i.map(x=>[x,[...x].map(y=>1e9-~f[y]+'')]).sort((a,b,d=a[0].length-b[0].length)=>d||a[1]<b[1]).map(x=>x[0]))
```
**Limit**
Frequency values up to 1000000000: for sorting, the frequency values are merged in a big padded string
**Ungolfed**
```
F=i=>(
f={}, //init frequency map
i.map(x => (f[x[0]]=-~f[x[0]])), // build frequency map
i.map(x => [x, [...x].map(y=>1e9-~f[y]+'')]) // add frequency info to each element of input list
.sort((a,b,d=a[0].length-b[0].length)=>d || a[1]<b[1]) // then sort by lenght and frequency
.map( x => x[0]) // throw away frequency info
)
```
*Sidenote* `X-~` increment by 1 even if the original number X is undefined or NaN
**Usage**
```
F(['c','ca','ac','cc','a','ccc','cx','cz','cy'])
```
Output: `["c", "a", "cc", "ca", "cx", "cz", "cy", "ac", "ccc"]`
] |
[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/24603/edit).
Closed 2 years ago.
[Improve this question](/posts/24603/edit)
Write a quine with 1 or more rhyme scheme from <http://en.wikipedia.org/wiki/Rhyme_scheme> when read. The following characters are spoken aloud:
* any alphanumeric words or characters not in a comment;
* comparison and arithmetic characters (+ plus; - minus; \* times, / divided by, | or, || or, & and, && and, ! not, = equals, == equals, === equals).
The following is not accounted for (is not spoken aloud):
* any characters which signify the beginning or end of string literals ("');
* any characters which signify the beginning or end of logical blocks ((){}[]);
* any characters which signify the delineation of a variable, function or line of code (.,;).
* any characters in comments;
The "spoken aloud" rules always apply. the "not spoken aloud" rules apply to all languages, except Brainfuck, K, J, APL, Befunge and Sclipting. In the case of APL, Brainfuck, Befunge, K and J, any character not mentioned in "spoken aloud rules" are subject to the "choose consistently" rule outlined above. Sclipting characters are pronounced like they would be if they were that Chinese character, with free choice of which pronounciation you use.
Any characters which are not explicitly allowed or denied pronounciation are free to be pronounced or kept silent. However, a specific character is either always pronounced or always kept silent. You may not pronounce # as hashtag in one line and keep # silent in the next.
Words may be pronounced in any dialect or language, but it needs to be consistent within the same stanza (no having the first word be pronounced in a Scottish way and the second in a Welsh way).
Contest type is popularity contest. The deadline is April 23rd in honor of one of the most well known bards, William Shakespeare, who was born and allegedly died on that day. Winner is he who gets the most votes.
Edit: because I don't think there will be any more submissions, I've decided to end the contest early. I'll mark the winner momentarily.
[Answer]
# Batch AABBA (Limerick)
This is my best try, but I have never been any good at poems.
Code:
```
@Echo off || cd \.
If "this"=="a largeish" pot
Type %0 || chef
Color 7f
Goto :eof || shallot
```
In english:
>
> Echo off else CD slash dot
>
> If this equals a largeish pot
>
> Type zero else chef
>
> Color seven f
>
> Go to EOF else shallot
>
>
>
[Answer]
# Fortran 95 (McCarron Couplet)
>
> McCarron Couplet: "AABBABCCDDCDEEFFEF" a contemporary take on a
> classic rhyming pattern, introduced by the academic James McCarron.
>
>
>
My code (which should be saved as `all.f95` in order for it to work):
```
character (LEN=100) :: &
bend; logical :: wondered
inquire(file="superstar &
&car",exist=wondered,number=i_r)
open(unit=100, &
file="superstar car")
if (.NOT.(.NOT.(wondered))) then
i_sum = 1; read(100,*) n
i_sum = n + i_sum
rewind(100); else; i_sum = 1
endif; write(100,*) i_sum, 10
codingThis = fun
write(bend,"(I5)") n; call &
SYSTEM ("copy all.f95 all"//&
TRIM(TRIM(ADJUSTL(bend)))//&
".f95"); open(access="append", &
unit=10,file="waterfall")
write(10,*) "foo bar"; end
```
It will copy itself to numbered files, starting with `all0.f95`, then `all1.f95`, `all2.f95`, and so on...
It reads:
```
character len equals hundred
bend logical wondered
inquire file superstar
car exist wondered, number equals IR
open unit equals hundred
file equals superstar car
if not not wondered then
I sum equals one, read hundred N
I sum equals N plus I sum
rewind hundred else I sum equals one
endif write hundred I sum ten
conding this equals fun
write bend I five N call
system copy all F point ninety five all
trim trim adjust L bend
point ninety five access append
open unit ten file waterfall
write ten foo bar end
```
] |
[Question]
[
Inspired by [xkcd](http://xkcd.com/1344/).
Your challenge is to determine whether a number would make a good combination in [the game 2048](http://git.io/2048). Your input will be a number, such as:
```
8224
```
And the output will be whether that number would make a good 2048 combo, which for this input would be `true` or `yes` or `1` or any other way of indicating a positive result.
For those not familiar with the game, here's a simple explanation: powers of two are arranged on a grid, like this: `[2] [2]`. Tiles can be moved in any direction, and if two identical tiles meet, they become the next power of two (so `[2] [2]` when moved left or right becomes `[4]`). Or, you could just [try the game here](http://git.io/2048).
What does "a good 2048 combination" mean? It means any number that, if it was in the game "2048", it could be combined into one single number. (A zero means an **empty space**, and can be ignored if needed.) Note that numbers could possibly be multiple digits! However, the numbers must **not** change between moves. Here are some examples/test cases (with "Good" indicating a good combination, and "Bad" meaning not good):
* Good: 8224 (8224 -> 844 -> 88 -> 16)
* Good: 2222 (2222 -> 44 -> 8)
* Good: 22048 (22048 -> 448 -> 88 -> 16)
* Bad: 20482 (cannot combine the outer 2's, nor can you combine a 2048 and a 2)
* Good: 20482048 (20482048 -> 4096)
* Bad: 210241024 (210241024 -> 22048, but this is now [2] [2048] and cannot be combined since numbers cannot change between moves)
* Good: 2048 (it's already one number)
* Bad: 2047 (it's not a power of 2)
* Bad: 11 (there are no 1's in the game)
* Good: 000040000000 (zeroes are empty spaces)
Miscellaneous rules:
* Input can be from anywhere reasonable, i.e. STDIN, function argument, file, etc.
* Output can also be anywhere reasonable, i.e. STDOUT, function return value, file, etc.
* Ignore the grid size - `22222222` should still output true.
* The is no maximum to what s number could be, as long as it's a power of two. Therefore the possible numbers are any power of two greater than 0.
* For those worried about zeroes causing ambiguity, that is not the case. For example, `22048` can be parsed as either `[2] [2048]` or `[2] [2] [0] [4] [8]`. The first one doesn't work, but the second one does, so it should output true.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win!
[Answer]
# Python: ~~457~~ 422 characters
```
z=range
def c(n):
for x in z(1,12):
if int(n)==2**x:return 1
return 0
def p(s):
if s=='':return[]
for i in z(len(s),0,-1):
if c(s[:i])>0and p(s[i:])!=1:return [int(s[:i])]+p(s[i:])
return 1
def r(a):
if len(a)==1:return 1
i,t=1,a[:1]
while i<len(a):
if a[i]==t[-1]:t[-1]*=2
else:t+=[a[i]]
i+=1
if len(t)==len(a):return 0
return r(t)
def f(s):
if p(s)==1or r(p(s))==0:print('bad')
else:print('good')
```
The function f(s) gets a string of digits and outputs 'good' or 'bad' accordingly.
I chose not to use 0 as spaces because spaces are meaningless in the game and they create ambiguity when parsing strings (is 22048 good or bad?). This only uses numbers up to 2048, but that can be changed without adding characters.
At the cost of 10 characters or so I can also print all the steps of combining the numbers.
And I realize that this code isn't golfed enough yet; don't worry, edits are coming.
[Answer]
# Haskell: ~~285 254 253 237 230~~ 227
usage - just load it into ghci, and pass the string to h.
```
*Main> h "210241024"
False
*Main> h (replicate 1024 '2') -- very long string
True
*Main> h (replicate 1023 '2') -- odd one out
False
```
Code:
```
t=i 0
i n=mod n 2<1&&(n<3||i(div n 2))
a%[]|i a=[[a]]|t=[];a%(b:c)=[a:d|d<-b%c,i a]++(a*10+b)%c
c(0:a)=c a;c(a:b:d)|a==b=(a+a):c d|t=a:c(b:d);c a=a
l a=c a/=a&&(g.c)a
g[a]=t;g a=l a||(l.reverse)a
h b=any g$0%(map(read.(:[]))b)
```
Commentary: `i` is the check if a number is a power of 2, this will be outplayed by languages with bit twiddling. `%` recursively generates all parses that are lists of powers of 2 or 0. `c` collapses tiles. `l` recursively tests if tiles are collapsible left or good. `g` tests if tiles are collapsible left or right. There is no limit to the numbers on the tiles - eg `h ((show (2^200))++(show (2^200)))` returns true for 2 tiles marked "1606938044258990275541962092341162602522202993782792835301376".
Edited to fix a bug that it didn't correctly collapse "88222288888" to the right, but also found more golfing opportunities.
[Answer]
# Perl, 175-336 bytes
```
while(<>){chomp;$n="nothing";$\=("."x(1+/^[2048]+$/+/^((\d+)0*\2)+$/+((sprintf"%b",
$_)!~/1.*1/)))."\n";($o=$\)=~y/.\n/oh/;print$o;$m=length;for$i(1..$m){$a=$_;$r=
qr((\d*[2468])0*\2)0*/;($b=substr$a,0,$i,"")=~s/$r/$2+$2/ge;@n=$"="$b$a";push@n,$"while$"
=~s/$r/$2+$2/ge;($"%2&&next)||($">>=1)while$">1;$n="nice";(print)for@n;last}print$n}
```
Keeping just the essentials intact:
```
$_=shift;$m=length;for$i(1..$m){$a=$_;$r=qr/((\d*[2468])0*\2)0*/;($b=substr$a,0,$i,"")=~
s/$r/$2*2/ge;$"="$b$a";1while$"=~s/$r/$2*2/ge;($"%2&&next)||($">>=1)while$">1;exit}die;
```
>
> 1
>
>
>
> >
> > ooh..
> > 1..
> > nice..
> >
> >
> >
>
>
> 2
>
>
>
> >
> > oooh...
> > 2...
> > nice...
> >
> >
> >
>
>
> 22
>
>
>
> >
> > oooh...
> > 22...
> > 4...
> > nice...
> >
> >
> >
>
>
> 42
>
>
>
> >
> > ooh..
> > nothing..
> >
> >
> >
>
>
> 422
>
>
>
> >
> > ooh..
> > 422..
> > 44..
> > 8..
> > nice..
> >
> >
> >
>
>
> 322
>
>
>
> >
> > oh.
> > nothing.
> >
> >
> >
>
>
> 336
>
>
>
> >
> > oh.
> > nothing.
> >
> >
> >
>
>
> 4224
>
>
>
> >
> > ooh..
> > nothing..
> >
> >
> >
>
>
> 4228
>
>
>
> >
> > ooh..
> > 4228..
> > 448..
> > 88..
> > 16..
> > nice..
> >
> >
> >
>
>
> 16022481602248
>
>
>
> >
> > ooh..
> > 1604481602248..
> > 16088160448..
> > 1601616088..
> > 3216016..
> > 3232..
> > 64..
> > nice..
> >
> >
> >
>
>
>
[*64 and 256 lead to some poorly resolvable ambiguities that greedy matching can't cope with... but these are* nice *byte counts.*]
>
> 2048
>
>
>
> >
> > oooh...
> > 2048...
> > nice...
> >
> >
> >
>
>
>
[Answer]
# Delphi 572582 characters
Edited code, limit is set to 2^30 so it wont exceed the MaxInt value in Delphi.
### Golfed
```
uses SysUtils,Classes;var t,j,c:integer;s,n:string;L:TStringList;function p(x:string):boolean;var r,i:int64;begin if x='0'then exit(1>0);i:=2;r:=StrToInt(x);while i<r do i:=i*2;p:=i=r;end;begin read(s);t:=0;L:=TStringList.Create;j:=1;while j<=Length(s)do begin for c:=9downto 1do begin n:=copy(s,j,c);if p(n)then break;end;if n>'0'then L.Add(n);j:=j+Length(n);end;for j:=0to L.Count-1do t:=t+StrToInt(L[j]);j:=0;repeat if j=L.Count-1then break;if L[j]=L[j+1]then begin L[j]:=IntToStr(StrToInt(L[j])*2);L.Delete(j+1);j:=0;end else inc(j);until L.Count=1;write(strtoint(L[0])=t);end.
```
### Ungolfed
```
uses
SysUtils,
Classes;
var
t,j,c:integer;
s,n:string;
L:TStringList;
function p(x:string):boolean;
var
r,i:int64;
begin
if x='0'then exit(1>0);
i:=2;r:=StrToInt(x);
while i<r do
i:=i*2;
p:=i=r;
end;
begin
read(s);
t:=0;L:=TStringList.Create;
j:=1;
while j<=Length(s)do
begin
for c:=9downto 1do
begin
n:=copy(s,j,c);
if p(n)then break;
end;
if n>'0'then L.Add(n);
j:=j+Length(n);
end;
for j:=0to L.Count-1do
t:=t+StrToInt(L[j]);
j:=0;
repeat
if j=L.Count-1then break;
if L[j]=L[j+1]then
begin
L[j]:=IntToStr(StrToInt(L[j])*2);
L.Delete(j+1);j:=0
end
else
inc(j);
until L.Count=1;
write(strtoint(L[0])=t);
end.
```
### EDIT
So I got curious and wondered how many of these combinations would fit the puzzle and ran a test one it.
For others that are also curious, make a test too ;)
But ok here are the results:
`20736 combinations were tested and 1166 were great combinations`
I must say combinations with 3 or more zeroes were skipped (makes sense right?)
Combinations are almost unique, meaning the combinations `2248`,`8224`,`8422` and `4228` were all counted as a great combination.
[Answer]
## Mathematica - 218 bytes
```
f=MemberQ[DeleteCases[Map[FromDigits,l~Internal`PartitionRagged~#&/@Join@@Permutations/@IntegerPartitions@Length[l=IntegerDigits@#],{2}],{___,x_,___}/;!IntegerQ[2~Log~x]||x<2]//.{a___,x_,x_,b___}:>{a,2x,b},{_Integer}]&
```
Ungolfed version:
```
f[n_] := MemberQ[
DeleteCases[
Map[
FromDigits,
Internal`PartitionRagged[l, #] & /@
Join @@ Permutations /@ IntegerPartitions[Length[l = IntegerDigits[n]]],
{2}
],
{___, x_, ___} /; x < 2 || ! IntegerQ[2~Log~x]
]
] //. {a___, x_, x_, b___} :> {a, 2 x, b},
{_Integer}
]
```
The `Internal\`PartitionRagged` magic is taken from [this question](https://mathematica.stackexchange.com/questions/8528/finding-all-partitions-of-a-set).
This solution handles arbitrary grid sizes and arbitrarily large numbers.
Here is a **195 byte** version that works like the actual game with up to 4 tiles only (so `f[22222222]` is `False`):
```
f=MemberQ[(d=DeleteCases)[d[ReplaceList[IntegerDigits@#,{a__,b___,c___,d___}:>FromDigits/@{{a},{b},{c},{d}}],0,2],{___,x_,___}/;!IntegerQ[2~Log~x]||x<2]//.{a___,x_,x_,b___}:>{a,2x,b},{_Integer}]&
```
where I've replaced
```
Map[
FromDigits,
Internal`PartitionRagged[l, #] & /@
Apply[
Join,
Permutations /@ IntegerPartitions[Length[l = IntegerDigits@#]]
],
{2}
]
```
with
```
ReplaceList[
IntegerDigits[n],
{a__, b___, c___, d___} :> FromDigits /@ {{a}, {b}, {c}, {d}}
]
```
[Answer]
# Haskell - 260 ~~263~~
```
import Data.Bits
p[x]=[[[x]]]
p(x:s)=do r@(h:t)<-p s;[[x]:r,(x:h):t]
q=filter(and.map(\n->(n::Integer)/=1&&n.&.(-n)==n)).map(filter(/=0)).map(map read).p
c(x:y:s)
|x==y=2*x:c s
|True=x:(c$y:s)
c x=x
r[x]=True
r l=c l/=l&&(r(c l)||r(c$reverse l))
f=or.map r.q
```
`f` is the function. Examples:
```
> f"22228"
True
> f"20482044"
False
```
A little explanation:
`p` returns all ways to split a list.
`q` filters those that consist of only powers of 2 (excluding 1 but including 0).
[Answer]
### GolfScript, 137 characters
```
[0`]1$,4*,{2\)?`}%+:W;[]\]][]\{{:A;W{A 1=\?!},{[.A~@,>\@~+\].~!{0-.,/@+\0}*;}%~}%.}do+.{~}%,{{.-1%}%.&{[{.2$={+)}*}*]{1|(}%}%}*{,1=},!!
```
Input must be given on STDIN. The output is `0`/`1` for bad/good numbers. Most of the code is necessary for parsing the possible inputs.
This shorter version (113 characters) performs a simple shift test which would not work correctly for input like `224422`.
```
[0`]1$,4*,{2\)?`}%+:W;[]\]][]\{{:A;W{A 1=\?!},{[.A~@,>\@~+\].~!{0-.,/@+\0}*;}%~}%.}do+{W{~[.:S]/[S.+]*}/,1=},!!
```
All test cases can be checked [online](http://golfscript.apphb.com/?c=ewogIFswYF0xJCw0Kix7MlwpP2B9JSs6VztbXVxdXVtdXHt7OkE7V3tBIDE9XD8hfSx7Wy5BfkAsPlxAfitcXS5%2BIXswLS4sL0ArXDB9Kjt9JX59JS59ZG8rLnt%2BfSUse3suLTElfSUuJntbey4yJD17Kyl9Kn0qXXsxfCh9JX0lfSp7LDE9fSwhIQp9OlRFU1Q7Cgo7WyI4MjI0IiAiMjIyMiIgIjIyMDQ4IiAiMjA0ODIiICIyMDQ4MjA0OCIgIjIxMDI0MTAyNCIgIjIwNDgiICIyMDQ3IiAiMTEiICIwMDAwNDAwMDAwMDAiICIyMjQ0MjIiXQp7IDpJIFRFU1QgWyIgQmFkIiIgR29vZCJdPSBJXCsgcHV0cyB9Lw%3D%3D&run=true).
] |
[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/21718/edit).
Closed 1 year ago.
[Improve this question](/posts/21718/edit)
Your task - if you accept it - is to write a program which helps understanding [my proposal on meta](https://codegolf.meta.stackexchange.com/a/1050/16901) by calculating the winner of a [code-golf-reversed](/questions/tagged/code-golf-reversed "show questions tagged 'code-golf-reversed'") competition. Of course, answers to this question will be treated as proposed, so your program (if correct) can calculate whether your answer will become the accepted answer.
## Rules
* The program reads a file with multiple lines of the following format (see example below): [Language] TAB [NumberOfCharacters] TAB [LinkToAnswer]
* The file name is passed as an argument to your program or the file is redirected to standard input of your program. It's your choice, please mention the method when giving the answer
* It's expected that the input format is correct. There's no need for error handling.
* The number of characters is positive. Your program must handle lengths up to 65535. 64k should be enough for everybody :-)
* The program outputs those lines on standard output which meet the idea of the meta proposal, that is
+ the shortest code of a particular programming language wins (reduction phase)
+ the longest code among all programming languages wins (sorting phase)
+ in case of a draw, all answers with the same length shall be printed
* The order of the output is not important
* Although the longest code wins, this is not [code-bowling](/questions/tagged/code-bowling "show questions tagged 'code-bowling'"). Your code must be as short as possible for your programming language.
* Answers on seldom programming languages which are not attempting to shorten the code deserve a downvote, because they try to bypass the intention of this kind of question. If there's only one answer for a specific programming language, it would be considered as a winner candidate, so you could start blowing its code.
Example input file (separated by single tabs if there should be an issue with formatting):
```
GolfScript 34 http://short.url/answer/ags
GolfScript 42 http://short.url/answer/gsq
C# 210 http://short.url/answer/cs2
Java 208 http://short.url/answer/jav
C# 208 http://short.url/answer/poi
J 23 http://short.url/answer/jsh
Ruby 67 http://short.url/answer/rub
C# 208 http://short.url/answer/yac
GolfScript 210 http://short.url/answer/210
```
Expected output (order is not important):
```
C# 208 http://short.url/answer/poi
C# 208 http://short.url/answer/yac
Java 208 http://short.url/answer/jav
```
## Update
Some programs rely on the fact that there is a single maximum (like the C# 210 character program). Derived from reality, someone can also write a GolfScript program with 210 characters. The output would remain the same. I have added such a GolfScript to the input.
## Update 2
As suggested I have retagged (still code-golf as well) and the deadline is **2014-03-06** (which looks like an arbitrary date, but I'll be back to Germany from travelling then).
## Final results
I decided to vote like the following:
* Answers where the number of characters cannot be confirmed get a comment to explain the count.
* Answers which can easily be reduced get a comment, an edit suggestion and go into the result with the lower count value. (Hopefully I have seen that in advance).
* Answers which do not compile get a downvote. (Quite a hard task as it turns out).
* Answers which are not golfed get a downvote (as described in the rules already).
* Answers which produce expected output get an upvote. Due to some answers which do not work as expected, I use 4 different input files and check against the expected result.
Finally, the winner is determined by providing the qualifying answers table as input to my reference program (plus double checking the result manually). If my own answer would be the winning one, I'd exclude it from the list.
In case of several winners, I would have to pick only one. Therefore, some bonuses can be earned:
* answers which accept more input than expected (e.g. outside the defined ranges)
* answers which use a clever idea of making it short
I have taken a snapshot of the answers on 6th of March 2014, 19:45 UTC+1. The analysis is ongoing. Checking all the answers is harder than expected...
[Answer]
# Java - 556
```
import java.util.*;class G{public static void main(String[]x){TreeMap<?,TreeMap>m=new TreeMap();try{Scanner s=new Scanner(System.in);for(;;){String[]a=s.nextLine().split("\t");a(new Long(a[1]),a(a[0],m)).put(a[2],a);}}catch(Exception e){}TreeMap<?,Map<?,String[]>>n=new TreeMap();for(TreeMap o:m.values())a(o.firstEntry().getKey(),n).putAll((Map)o.firstEntry().getValue());for(String[]o:n.lastEntry().getValue().values())System.out.println(o[0]+"\t"+o[1]+"\t"+o[2]);}static<T>Map a(T t,Map m){if(m.get(t)==null)m.put(t,new TreeMap());return(Map)m.get(t);}}
```
Program will read from STDIN.
```
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
class G {
public static void main(String[] x) {
TreeMap<?, TreeMap> m = new TreeMap();
try {
Scanner s = new Scanner(System.in);
for (; ; ) {
String[] a = s.nextLine().split("\t");
a(new Long(a[1]), a(a[0], m)).put(a[2], a);
}
} catch (Exception e) {
}
TreeMap<?, Map<?, String[]>> n = new TreeMap();
for (TreeMap o : m.values())
a(o.firstEntry().getKey(), n).putAll((Map) o.firstEntry().getValue());
for (String[] o : n.lastEntry().getValue().values())
System.out.println(o[0] + "\t" + o[1] + "\t" + o[2]);
}
static <T> Map a(T t, Map m) {
if (m.get(t) == null)
m.put(t, new TreeMap());
return (Map) m.get(t);
}
}
```
1. Programm will read line by line until an exception occours (either `ArrayIndexOutOfBoundsException` when a blank line is encountered or `NoSuchElementException` if input ends without trailing new line). Each line read is added to the `TreeMap m`, which could have been defined as `TreeMap<String, TreeMap<Long, TreeMap<String,String[]>>>` (left-to-right: language, code-size, URL, input).
2. Then a result-`TreeSet<Long, TreeSet<String, String[]>> n` (left-to-right: code-size, URL, input) is build where the contents of every languages `firstEntry()` are aggregated.
3. `lastEntry()` of the aggregated `TreeMap` contains our result - we only need to print it.
Try on [ideone.com](http://ideone.com/6XcJXP) (switched last two lines of input to show that all lines are read)
[Answer]
## Perl, 195 bytes
```
while(<>){/(\S+)\t(\d+)\t(.+)/;push@{$a{$1}},$3if$2==$l{$1};$l{$1}=$2,$a{$1}=[$3]if $2<($l{$1}//65536)}$m=(sort{$b<=>$a}values%l)[0];map{$l=$_;map{print"$l\t$m\t$_\n"if$l{$l}==$m}@{$a{$l}}}keys%l
```
Input is expected in STDIN, result is written to STDOUT:
```
C# 208 http://short.url/answer/poi
C# 208 http://short.url/answer/yac
Java 208 http://short.url/answer/jav
```
## Ungolfed version
```
#!/usr/bin/env perl
use strict;
$^W=1;
# hash %language remembers the minimum count for a language
# %language: <language> => <minimum count>
my %language;
# hash %array remembers the URLs for the minimum count of the language
# %array: <language> => [<url>, <url>, ....]
my %array;
while(<>){
# parse input line (no error checking)
/(\S+)\t(\d+)\t(.+)/;
my ($lang, $count, $url) = ($1, $2, $3);
# add URL, if the count is the current minimum for the language
if ($count == ($language{$lang}//0)) {
# better, but longer version:
# if (defined $language{$lang} and $count == $language{$lang}) {
push @{$array{$lang}}, $url;
}
# create a new entry for the language, if there is a new minimum
if ($count < ($language{$lang}//65536)) {
# better, but longer version:
# if (not defined $language{$lang} or $count < $language{$lang}) {
$language{$lang} = $count;
$array{$lang} = [$url];
}
}
# Sort the minimal values in numerical descending order and
# get the first entry as maximum.
my $maximum = (sort { $b <=> $a } values %language)[0];
# Loop over all URLs of minimal answers for the language,
# but print only the entries for the languages with the largest
# minima.
foreach my $lang (keys %language) {
foreach my $url (@{$array{$lang}}) {
if ($language{$lang} == $maximum) {
print "$lang\t$maximum\t$url\n";
}
}
}
__END__
```
[Answer]
# dg - 286 281 260 251 218 bytes
```
import '/sys'
d=dict!
for(a,b,c)in(map str.split$(sys.stdin.read!).splitlines!)=>d!!a=(d.get a list!)+(list'(int b,c))
for(i,l)in(d.items!)=>for(s,u)in l=>s==(max$map(i->fst$min i)d.values!)=>print$i+' '+(str s)+' '+u
```
Example:
```
$ cat langs.txt | dg langs.dg
C# 208 http://short.url/answer/poi
C# 208 http://short.url/answer/yac
Java 208 http://short.url/answer/jav
```
**Ungolfed** version:
```
import '/sys'
s = sys.stdin.read!
d = dict!
# convert the string into a list of tuples (name, score, url)
u = map str.split $ s.splitlines!
# add all the values to the dict (converting the score to an integer)
for (a, b, c) in u =>
d!!a = (d.get a list!) + (list' (int b, c))
# computes the maximum value amongst the mins
m = max $ map (i -> fst $ min i) d.values!
for (i, l) in (d.items!) =>
for (s, u) in l =>
# if the score equals the maximum then print all the line
s == m => print $ i + ' ' + (str s) + ' ' + u # actually here .format()
# would be better
```
**Q: What the heck is dg?**
**A:** A programming language that compiles to CPython bytecode, much like Scala compiles to JVM's. That essentially means that dg is an alternative syntax for Python 3. It allows you to use all of the existing libraries, too.
More info here (even a tutorial!): <https://pyos.github.io/dg>
[Answer]
## Python ~~378~~ ~~377~~ 372
```
import sys
d=__import__("collections").defaultdict(list)
o={}
x=int
n="\n"
for i,l,u in[a.split()for a in sys.stdin.read().strip().split(n)]:d[i]+=[(l,u)]
for e,b in d.items():o[e]=[i for i in b if i[0]==str(min([x(i[0])for i in b]))]
print("".join(n.join("\t".join([u,s[0],s[1]])for s in y if x(s[0])==max(x(i[0][0])for i in o.values()))+n for u,y in o.items()).strip())
```
Input on the stdin:
```
C:\Users\gcq\Documents\python>type m.txt | python test.py
C# 208 http://short.url/answer/poi
C# 208 http://short.url/answer/yac
Java 208 http://short.url/answer/jav
```
And this is what i had before starting to compress it down, at 551 chars:
```
from collections import defaultdict
import sys
d = defaultdict(list)
for language, length, url in [a.split() for a in sys.stdin.read().strip().split("\n")]:
d[language].append((length, url))
o = {}
for language, data in d.items():
winval = data[0][0]
for i in data:
if int(i[0]) < int(winval):
winval = i[0]
o[language] = [i for i in data if i[0] == winval]
maxlen = max(int(i[0][0]) for i in o.values())
for language, dataa in o.items():
for data in dataa:
if int(data[0]) == maxlen:
print("\t".join([language, data[0], data[1]]))
```
[Answer]
# C# - 628
Here's a longer alternative of yours that uses `DataTable`:
```
using Microsoft.VisualBasic.FileIO;namespace System{using T=Data.DataTable;using R=Data.DataRow;using V=Data.DataView;using C=Data.DataColumn;class p{static void Main(string[] a){var I=typeof(Int32);T t=new T();t.Columns.AddRange(new[]{new C("a"),new C("b",I),new C("c"),new C("d",I)});var f=new TextFieldParser(a[0]);f.SetDelimiters("\t");while(!f.EndOfData){var r=t.NewRow();r.ItemArray=f.ReadFields();t.Rows.Add(r);}foreach(R r in t.Rows){r[3]=t.Compute("min(b)","a='"+r[0]+"'");}V v=new V(t);T s=v.ToTable();foreach(R r in s.Select("b='"+t.Compute("max(d)","")+"'")){Console.WriteLine(String.Join("\t",r[0],r[1],r[2]));}}}}
```
I originally thought I may have gained slight code reduction from using max/min with `DataTable`, but the types required to build the `DataTable` (rows/columns/view) add a lot of length, unfortunately. I'm new to code golfing so maybe somebody would be able to reduce it further. Still a fun challenge.
[Answer]
# Rebol - 314
```
d: map[]foreach r read/lines to-file system/script/args[r: split r tab p: take r r/1: to-integer r/1 r/2: reduce[r/2]either none? d/:p[repend d[p r]][case[d/:p/1 > r/1[d/:p: r]d/:p/1 = r/1[append d/:p/2 r/2]]]]l: 0 foreach[k v]d[l: max l v/1]foreach[k v]d[if l = v/1[foreach n v/2[print rejoin[k tab v/1 tab n]]]]
```
## un-golfed
```
d: map []
foreach r read/lines to-file system/script/args [
r: split r tab
p: take r
r/1: to-integer r/1
r/2: reduce [r/2]
either none? d/:p [repend d [p r]] [
case [
d/:p/1 > r/1 [d/:p: r]
d/:p/1 = r/1 [append d/:p/2 r/2]
]
]
]
l: 0 foreach [k v] d [l: max l v/1]
foreach [k v] d [
if l = v/1 [
foreach n v/2 [print rejoin [k tab v/1 tab n]]
]
]
```
Usage example:
```
$ rebol script.reb data.txt
C# 208 http://short.url/answer/poi
C# 208 http://short.url/answer/yac
Java 208 http://short.url/answer/jav
```
[Answer]
## C# - 515
Expects a file name as argument
```
using System.Collections.Generic;namespace N{using S=SortedList<int,T>;class T:List<string>{static void Main(string[]a){var d=new Dictionary<string,S>();int n,m=0;T w=new T();foreach(var l in System.IO.File.ReadAllLines(a[0])){var p=(a=l.Split('\t'))[0];n=int.Parse(a[1]);if(!d.ContainsKey(p))d.Add(p,new S());if(!d[p].ContainsKey(n))d[p].Add(n,new T());d[p][n].Add(l);}foreach(var e in d){n=e.Value.Keys[0];if(n==m)w.AddRange(e.Value[n]);if(n>m)w=e.Value[m=n];}foreach(var e in w)System.Console.WriteLine(e);}}}
```
First I designed my C# program to be straight forward, because I wanted to have a kind of reference program. But then I decided to also jump into contest myself and golfed it. This is one of the earlier versions of the code + some comments:
```
// N: namespace
// P: Program
// S: type definition: sorted dictionary
// a: arguments
// d: data container
// r: lines read from text file
// l: single line from r
// t: tabbed part of l after splitting
// p: programming language name
// n: character count
// m: maximum character count
// w: list of winners
// e: entry in data container
// c: winner candidate
using System.Collections.Generic;
namespace N
{
using S = SortedList<int, P>;
public class P : List<string>
{
public static void Main(string[] a)
{
var r = System.IO.File.ReadAllLines(a[0]);
// Make it a data structure
var d = new Dictionary<string, S>();
foreach (var l in r)
{
var t = l.Split('\t');
var p = t[0];
var n = int.Parse(t[1]);
if (!d.ContainsKey(p)) d.Add(p, new S());
if (!d[p].ContainsKey(n)) d[p].Add(n, new P());
d[p][n].Add(l);
}
// Get the maximum values
var m = 0;
P w = null;
foreach (var e in d)
{
foreach (var s in e.Value.Keys)
{
if (s > m)
{
w = e.Value[s];
m = s;
}
else if (s == m)
{
w.AddRange(e.Value[s]);
}
break; // Break here to get the shortest solution per language
}
}
// Print everything on console
foreach (var e in w)
{
System.Console.WriteLine(e);
}
}
}
}
```
[Answer]
# C# - ~~460~~ 359
After realizing how bulky my `DataTable` solution was, I created the following example using Linq. It uses the same methodology as my previous solution.
## Golfed
```
namespace System{using Linq;using IO;class p{static void Main(string[]i){var l=(from f in File.ReadAllLines(i[0])let s=f.Split('\t')select new Tuple<string,int,string>(s[0],Convert.ToInt16(s[1]),f)).ToList();foreach(var f in l.Where(a=>a.Item2==l.Where(b=>b.Item1==l.Single(c=>c.Item2==l.Max(d=>d.Item2)).Item1).Min(e=>e.Item2)))Console.WriteLine(f.Item3);}}}
```
## Ungolfed
```
namespace System
{
using Linq;
using IO;
class p
{
static void Main(string[]i)
{
var l=(from f in File.ReadAllLines(i[0])
let s=f.Split('\t')
select new Tuple<string, int, string>(s[0],Convert.ToInt16(s[1]),f)).ToList();
foreach(var f in l.
Where(a=>a.Item2==l.
Where(b=>b.Item1==l.
Single(c=>c.Item2==l.
Max(d=>d.Item2)).Item1).
Min(e=>e.Item2)))
Console.WriteLine(f.Item3);
}
}
}
```
I'm still fairly new to Linq so I'm almost positive those expressions can be reduced further.
From your question, it's not clear if there is a single maximum length solution. For my answers I've used the assumption that there is a single maximum point (ie. if there was a GolfScript maximum of 210 as well, it may fail based on the Single maximum record returned). Heiko's solution would have the same issue. To fix this, we would have to add another step that contained a list of tied maxima to check minima for each language.
[Answer]
# C++ - 535
Will only output the answers tied for longest position after selecting only the shortest answers of each language as potential winners.
```
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){
string s;
vector<string>l;
vector<int>v;
vector<string>u;
cin>>s;
ifstream i(s.c_str());
do{
int n;
i>>s;
if(i.eof())break;
l.push_back(s);
i>>n;
v.push_back(n);
i>>s;
u.push_back(s);
}while(1);
for(int i=0;i<l.size();i++){
for(int j=0;j<l.size();j++){
if(l[j]==l[i]){
if(v[i]>v[j])l[i]="";
else if(v[i]<v[j])l[j]="";
}
}
}
int n=0;
for(int i=0;i<v.size();i++)
if(n<v[i]&l[i]!="")n=v[i];
for(int i=0;i<v.size();i++)
if(v[i]==n)cout<<l[i]<<'\t'<<v[i]<<'\t'<<u[i]<<endl;
}
```
Golfed (not as unreadable as some languages):
```
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){string s;vector<string>l;vector<int>v;vector<string>u;cin>>s;ifstream i(s.c_str());do{int n;i>>s;if(i.eof())break;l.push_back(s);i>>n;v.push_back(n);i>>s;u.push_back(s);}while(1);for(int i=0;i<l.size();i++)for(int j=0;j<l.size();j++)if(l[j]==l[i]){if(v[i]>v[j])l[i]="";else if(v[i]<v[j])l[j]="";}int n=0;for(int i=0;i<v.size();i++)if(n<v[i]&l[i]!="")n=v[i];for(int i=0;i<v.size();i++)if(v[i]==n)cout<<l[i]<<'\t'<<v[i]<<'\t'<<u[i]<<endl;}
```
] |
[Question]
[
Your challenge is to interpret a circuit diagram, complete with logic gates.
[Logic gates](http://en.wikipedia.org/wiki/Logic_gate) (you don't actually need to know what these do / are to complete this challenge):
* and gate: `a`
* or gate: `o`
* nand gate: `A`
* nor gate: `O`
* xor gate: `x`
* xnor gate: `X`
* not gate: `~`
Each gate but the last one takes two inputs. Inputs are from a `.` in the top left and bottom left corners of the 3 by 3 square centered on the gate. For not, the input is directly to its left. Output is to a `.` directly to the right.
Wires are represented by `-|\/.=`
* `-` contacts two wires, one to the right, and one to the left: `c-c`
* `|` contacts two wires, one above, and one below:
```
c
|
c
```
* `/` and `\` work as follows:
```
c c
\ /
c c
```
* `.` contacts every surrounding wire:
```
ccc
c.c
ccc
```
* `=` is special; it connects adjacent wires across it:
```
-=-
```
connects the two wires. In the following
```
\|/
-=-
/|\
```
each opposite wire is connected with each other, but not the others (this is where it differs from `.`).
* In order for current to flow, two wires must both be connected to the other one, so in `|-`, current does **not** flow.
Example of wiring:
```
.-.
= \
.--. .---=---
-. = .--
.--. .-------
```
the input is split into two wires and then split into three. In this split, the bottom wire moves to the middle, and the downwards split of the top wire appears on the bottom. Next, the top of the three wires is moved to the middle.
Sample wiring with gates:
```
--.
o..~..
--. o.---
a.---.
--.
```
Input format:
* each input wire will be labeled with a digit. At the end (right before newline), each output will be labeled with `:` (and the wire will always go **right** into it, ie `-:` or `.:` or `=:`)
* the input will always be valid; there will be no loops or wires joining together without a gate. Note that there can be wires with loose ends.
* `=` will be used only when necessary.
Output format:
* each input is referenced with the corresponding number.
* an expression is outputted. For example, if the wires compute input 1 and input 2, the output is `1a2`.
* whatever functions outputted must correspond to the logic gates at the beginning.
* to show not, put the `~` before the correct place.
* for multiple functions, use parentheses to show the order of execution. Parentheses can also be used when there is only a single function. For example,
```
1-.~.-.
A.~.-:
.
2-. /
x.
3-.
```
has one possible output of `~((2x3)A(~1))`
* multiple outputs must be separated by a newline (or equivalent)
Sample input:
```
1--.---.
x. \
2--. x.-=---------.
. .~. X.--.
3---. . a.----. /
O.~.-. \ /
. =
4-. / / .-:
X. .----:
5-.
```
One possible corresponding output:
```
(~1)a(~(3O(4X5))
((1x2)x3)X((~1)a(~(3O(4X5))))
```
[Answer]
# Java: ~~1523~~ 1512 chars
```
import java.util.*;class W{int v=99;Map<Integer,String>t;boolean k;public static void main(String[]y){new W().d();}W(){try{java.io.InputStream i=new java.io.File("r").toURL().openStream();t=new HashMap<>();int a=0,x=0,y=0;while((a=i.read())>-1){if(a==10){y++;x=0;continue;}q(x,y,(a>47&a<58?"!":"")+(char)a);x++;}}catch(Exception e){}}void d(){while(!k){k=!k;for(Map.Entry<Integer,String>g:t.entrySet())e(g.getKey(),g.getValue());}for(String b:t.values())if(b.startsWith("$"))System.out.println(b.substring(1));}void e(int a,String s){if(s==null||!s.startsWith("!"))return;int x=a/v,y=a%v;s=s.substring(1);b(s,x,y,x-1,y+1);b(s,x,y,x,y+1);b(s,x,y,x+1,y+1);b(s,x,y,x-1,y);b(s,x,y,x+1,y);b(s,x,y,x-1,y-1);b(s,x,y,x,y-1);b(s,x,y,x+1,y-1);}void b(String p,int m,int n,int x,int y){String s=t.get(x*v+y);if(s==null)return;boolean g=y==n+1;boolean h=y==n-1;boolean i=x==m+1;boolean j=x==m-1;if(z(s,"-=")&n==y){if(i)b(p,x,y,x+1,y);if(j)b(p,x,y,x-1,y);}if(z(s,"|=")&m==x){if(g)b(p,x,y,x,y+1);if(h)b(p,x,y,x,y-1);}if(z(s,"/=")){if(j&g)b(p,x,y,x-1,y+1);if(i&h)b(p,x,y,x+1,y-1);}if(z(s,"\\=")){if(i&g)b(p,x,y,x+1,y+1);if(j&h)b(p,x,y,x-1,y-1);}if(z(s,".")){q(x,y,"!"+p);u();}if(z(s,"~")){q(x,y,"!~("+p+")");u();}if((s.charAt(0)=='%'&n==y-1)|(s.charAt(0)=='&'&n==y+1)){q(x,y,"!("+p+")"+s.charAt(1)+"("+s.substring(2)+")");u();}if(z(s,"OoAaXx")){q(x,y,(n==y+1?"%":"&")+s+p);u();}if(z(s,":")){q(x,y,"$"+p);u();}}void q(int x,int y,String z){t.put(x*v+y,z);}void u(){k=false;}boolean z(String s,String c){return c.indexOf(s)>-1;}}
```
It gives this output for the sample input:
```
(~(((5)X(4))O(3)))a(~(1))
((~(((5)X(4))O(3)))a(~(1)))X(((2)x(1))x(3))
```
In order to squeeze its size:
* It does not do any error checking, error handling or input validation, assuming that the input is always valid.
* Is limited to 99 lines of input.
* Its input file must be called just `r`, without any file extension in the name.
* It does not makes any effort to detect if the parenthesis are or aren't necessary. It assumes that they always are necessary, and since this assumption is false, there is a lot more parenthesis than needed, but since this does not makes it fail the spec anyway, it is no problem.
* The order of the parameters to each binary operator is in general unpredictable, as it depends on the velocity that the values are propagated and from cell scanning order. But since all the binary operators are commutative, this should be no problem.
I am sure that it should be possible to reduce it more, but just a bit.
The interpreter is implemented in the form of some sort of cellular automata. It scans the entire field setting values, repeating it as many times as needed until no changes are detected.
Here is an ungolfed version:
```
import java.util.*;
class Wiring {
int maxLines = 99;
Map<Integer, String> circuitState;
boolean finished;
public static void main(String[] args) {
new Wiring().interpret();
}
Wiring() {
try {
// Always read the input from the "r" file, and do not check if it even
// exists. BTW, the toURL() method is deprecated, but we don't care about
// this in code-golfing.
java.io.InputStream stream = new java.io.File("r").toURL().openStream();
circuitState = new HashMap<>();
int byteRead = 0, cellX = 0, cellY = 0;
while ((byteRead = stream.read()) > -1) {
// Check for line break;
if (byteRead == 10) {
cellY++;
cellX = 0;
continue;
}
// Populate the circuit cell. Precede numbers with an exclamation mark.
setCircuitCell(cellX, cellY, (byteRead >= '0' & byteRead <= '9' ? "!" : "") + (char) byteRead);
cellX++;
} catch (Exception e) {
}
}
void interpret() {
while (!finished) {
finished = !finished; // i.e. finished = false;
for (Map.Entry<Integer, String> entry : circuitState.entrySet()) {
analyzeCell(entry.getKey(), entry.getValue());
}
}
// Now print the output. To do that scan for cells marked with "$".
for (String cell : circuitState.values()) {
if (cell.startsWith("$")) System.out.println(cell.substring(1));
}
}
void analyzeCell(int cellIndex, String cellValue) {
// Only the cells with a value marked with "!" are worth to analyze.
if (cellValue == null || !cellValue.startsWith("!")) return;
// Convert the cellIndex to a bidimensional coordinate.
int x = cellIndex / maxLines, y = cellIndex % maxLines;
// Remove the "!".
cellValue = cellValue.substring(1);
// Propagate the cell value to neighbouring cells.
propagateCellData(cellValue, x, y, x - 1, y + 1);
propagateCellData(cellValue, x, y, x, y + 1);
propagateCellData(cellValue, x, y, x + 1, y + 1);
propagateCellData(cellValue, x, y, x - 1, y);
propagateCellData(cellValue, x, y, x + 1, y);
propagateCellData(cellValue, x, y, x - 1, y - 1);
propagateCellData(cellValue, x, y, x, y - 1);
propagateCellData(cellValue, x, y, x + 1, y - 1);
}
void propagateCellData(String cellValue, int sourceX, int sourceY, int targetX, int targetY) {
String targetContent = circuitState.get(targetX * maxLines + targetY);
// If the target cell does not exist, just ignore.
if (targetContent == null) return;
boolean targetBelowSource = targetY == sourceY + 1;
boolean targetAboveSource = targetY == sourceY - 1;
boolean targetRightToSource = targetX == sourceX + 1;
boolean targetLeftToSource = targetX == sourceX - 1;
// Propagate horizontally through wires.
if (isStringContained(targetContent, "-=") & sourceY == targetY) {
if (targetRightToSource) propagateCellData(cellValue, targetX, targetY, targetX + 1, targetY);
if (targetLeftToSource) propagateCellData(cellValue, targetX, targetY, targetX - 1, targetY);
}
// Propagate vertically.
if (isStringContained(targetContent, "|=") & sourceX == targetX) {
if (targetBelowSource) propagateCellData(cellValue, targetX, targetY, targetX, targetY + 1);
if (targetAboveSource) propagateCellData(cellValue, targetX, targetY, targetX, targetY - 1);
}
// Propagate in the diagonal x=-y.
if (isStringContained(targetContent, "/=")) {
if (targetLeftToSource & targetBelowSource) {
propagateCellData(cellValue, targetX, targetY, targetX - 1, targetY + 1);
}
if (targetRightToSource & targetAboveSource) {
propagateCellData(cellValue, targetX, targetY, targetX + 1, targetY - 1);
}
}
// Propagate in the diagonal x=y.
if (isStringContained(targetContent, "\\=")) {
if (targetRightToSource & targetBelowSource) {
propagateCellData(cellValue, targetX, targetY, targetX + 1, targetY + 1);
}
if (targetLeftToSource & targetAboveSource) {
propagateCellData(cellValue, targetX, targetY, targetX - 1, targetY - 1);
}
}
// If we got a dot, store the value there.
// Do not forget to mark it with "!", so we can rescan it later.
if (isStringContained(targetContent, ".")) {
setCircuitCell(targetX, targetY, "!" + cellValue);
markThatStateChanged();
}
// If we got a "~", store the inverted value there.
// Do not forget to mark it with "!", so we can rescan it later.
if (isStringContained(targetContent, "~")) {
setCircuitCell(targetX, targetY, "!~(" + cellValue + ")");
markThatStateChanged();
}
// If we found a binary logical port with one of the values set and
// we can set the another value, do it. Use "%" and "&" to know which
// one was already defined.
// BTW, do not forget to mark it with "!", so we can rescan it later.
if ((targetContent.charAt(0) == '%' & sourceY == targetY - 1)
| (targetContent.charAt(0) == '&' & sourceY == targetY + 1))
{
setCircuitCell(targetX, targetY,
"!(" + cellValue + ")"
+ targetContent.charAt(1)
+ "(" + targetContent.substring(2) + ")");
markThatStateChanged();
}
// Found a binary logical port without any value setted, so set it.
// Use "%" and "&" to mark which one was setted.
if (isStringContained(targetContent, "OoAaXx")) {
setCircuitCell(targetX, targetY, (sourceY == targetY + 1 ? "%" : "&") + targetContent + cellValue);
markThatStateChanged();
}
// If we found an output, store the value there.
// Mark it with "$", so we will print it in the future.
if (isStringContained(targetContent, ":")) {
setCircuitCell(targetX, targetY, "$" + cellValue);
markThatStateChanged();
}
}
void setCircuitCell(int cellX, int cellY, String cellContents) {
circuitState.put(cellX * maxLines + cellY, cellContents);
}
void markThatStateChanged() {
finished = false;
}
boolean isStringContained(String searchingString, String searchTarget) {
return searchTarget.indexOf(searchingString) > -1;
}
}
```
[Answer]
# Python ~~2488~~ ~~1567~~ ~~806~~ ~~706~~ ~~697~~ ~~657~~ 653
Yay for gzip + exec!
```
import zlib,base64;exec zlib.decompress(base64.b64decode('eNp1U8FuqzAQvPMV7sm2gBSuuFupX9BLD5UoBxNMMAkEgQmJVPXb364Daiu9ntaznt2dWYzthvPo2HSbgsrU7E3so0FmAWtgnyeFshjSImC2Zs1Tws4js/fQPMPJ9KKTlFrPeVPIbDRuHnvOA3YByuS2UCNwrloYqOMRQ1ooDY0qwaoKRJxGSZRKP+QCwBn/0YRyzPYcYq77irUATVbGcIytGkN4E7mOyiLayx/MT888AthMx9DGDTLj/zIfPz44emUGqC/Zoio1UdFzohzFp0TNNA7xQhFxDWJiNGNG98L54yLVYUsv3+kZx9G8/uyEoQFk8NELrDeIIggf5Cb3b3/I3nnFNdZe0QOrCHl4+4ZsgVyH16gMb4XHq4IrwA0gkV7kAwyZH7Fs7f0S/O7IbnZX7jelzy+v13f8LsAFD0kVfrQyTklZyCUPL+F2Ef66WHug7i9f/bWyfnOIsrNTZQ/WCXxCcAnY/QmwMeggLwIyeCKD+FB3k6tsj/K6nR4G01fiZCcnTlIGBkw/d2bUzvgSG2kqMvhOkU+ZNirvGS1XgyWKy/xS2TDa3uE/kNuoJX0UC/kP8j/kmA=='))
```
---
### Limitations and assumptions
As it is, only up to 9 inputs are supported - multiple digits are not handled correctly. As the spec indicates that inputs are labelled with a *digit*, not a *number*, this is allowed.
---
### Input and output
Input is taken via standard in, and output is via standard out.
---
### Testing
Sample input and output:
```
1--.---.
x. \
2--. x.-=---------.
. .~. X.--.
3---. . a.----. /
O.~.-. \ /
. =
4-. / / .-:
X. .----:
5-.
```
```
(~(1))a(~((3)O((4)X(5))))
(((1)x(2))x(3))X((~(1))a(~((3)O((4)X(5)))))
```
Tested here: <http://ideone.com/gP4CIq>
---
### The algorithm
It's basically a rather naive DFS from the outputs. For each output, it starts from the character one to its left and traces the wire, branching (and adding to the expression) at every gate. When it reaches an input, it adds it to the expression and backtracks to the last point it branched, since we can be sure that branching is *not* possible without a gate. And of course any invalid cases are discarded. Nothing really special to it - and therefore it's likely longer than it could have been.
---
### Notes
Size could probably be reduced a fair bit with some restructuring, but I've spent enough time on this for today. The manually golfed version was the one compressed.
The gzip compression makes golfing interesting, because certain caching (e.g. `d=(-1,0,1)`) actually takes more space than letting the compression algorithm take care of it. However, I opted to golf the manual version as far as possible rather than optimising for compression.
---
### Manually golfed (~~909~~ ~~895~~ ~~840~~ 803):
```
import sys
def T(c,p):
h=c[0];i=c[1]
if h<0 or i<0 or h>=len(m)or i>=len(m[h]):return''
v=m[h][i];r='';j=p[0];k=p[1];a=h;b=i;d=(-1,0,1)
if v==' ':return''
if v in'=-'and j==h:b-=k-i;r+=T([a,b],c)
if v in'=|'and k==i:a-=j-h;r+-T([a,b],c)
if v in'=/\\':
e=j==h or k==i;s=j-h>0;t=j-h<0;u=k-i>0;w=k-i<0;f=(s and u)or(t and w);g=(s and w)or(t and u)
if not(e or v=='/'and f or v=='\\'and g):a-=j-h;b-=k-i;r+=T([a,b],c)
if v=='.':
for x in d:
for y in d:
w=[a+x,b+y]
if not(x==y==0)and w!=p:r+=T(w,c)
if j==h and k-i>0:
if v in'aoAOxX':r='('+T([a-1,b-1],c)+')'+v+'('+T([a+1,b-1],c)+')'
if v=='~':r='~('+T([a,b-1],c)+')'
if v.isdigit():r=v
return r
m=[]
for l in sys.stdin:
m.append(list(l))
e=enumerate
for i,a in e(m):
for j,b in e(a):
if b==':':
print T([i,j-1],[i,j])
```
### Full ungolfed (2488):
```
import sys
def findOuts(c):
for i, iVal in enumerate(c):
for j, jVal in enumerate(iVal):
if jVal == ':':
yield [i, j]
def trace(pos, prev):
if pos[0] < 0 or pos[1] < 0 or pos[0] >= len(circuit) or pos[1] >= len(circuit[pos[0]]):
return ''
val = circuit[pos[0]][pos[1]]
if val == ' ':
return ''
next = pos[:]
ret = ''
if val in '=-':
if prev[0] == pos[0]:
next[1] -= prev[1] - pos[1]
ret += trace(next, pos)
if val in '=|':
if prev[1] == pos[1]:
next[0] -= prev[0] - pos[0]
ret += trace(next, pos)
if val in '=/\\':
# top-bottom, left-right
tblr = prev[0] == pos[0] or prev[1] == pos[1]
# top-left, bottom-right
tlbr = (prev[0] - pos[0] == 1 and prev[1] - pos[1] == 1) or (prev[0] - pos[0] == -1 and prev[1] - pos[1] == -1)
# top-right, bottom-left
trbl = (prev[0] - pos[0] == 1 and prev[1] - pos[1] == -1) or (prev[0] - pos[0] == -1 and prev[1] - pos[1] == 1)
if not ((val == '/' and (tlbr or tblr)) or (val == '\\' and (trbl or tblr)) or (val == '=' and tblr)):
next[0] -= prev[0] - pos[0]
next[1] -= prev[1] - pos[1]
ret += trace(next, pos)
if val == '.':
for x in (-1,0,1):
for y in (-1,0,1):
if x == y == 0:
continue
w = [next[0] + x, next[1] + y]
if w == prev:
continue
# only one of them should return anything
ret += trace(w, pos)
# assumption that a logic gate always has a . on its connections, as according to spec
if val in 'aoAOxX':
# only from the right/output
if not (prev[0] == pos[0] and prev[1] == pos[1] + 1):
return ret
ret = '(' + trace([next[0] - 1, next[1] - 1], pos) + ')' + val + '(' + trace([next[0] + 1, next[1] - 1], pos) + ')'
if val == '~':
# only from the right/output
if not (prev[0] == pos[0] and prev[1] == pos[1] + 1):
return ret
ret = '~(' + trace([next[0], next[1] - 1], pos) + ')'
if val in '123456789':
ret = val
return ret
circuit = []
for line in sys.stdin.readlines():
# padding added to prevent index out of bounds later
circuit.append(list(line))
for out in findOuts(circuit):
next = out[:]
next[1] -= 1
print trace(next, out)
```
] |
[Question]
[
The idea is this: Write a function to print the length of time from now/today's date (at the time the function is called) until a date supplied as an argument.
**Assumptions:**
* Input date will always be tomorrow or later, in the future.
* Input date will never be more than 10 years in the future.
**Rules:**
* Output must be in this format: "[z year(s)], [x month(s)], y day(s) until -Input Date-"
* Output time frame (day/month/year) must be pluralized correctly. i.e. `1 month`, not `1 months`
* Input can be in whichever date format *you* prefer (3/15/12 - March 15, 2012 - 2012.03.15).
**Example:**
Assuming program is run on March 15, 2012:
* Input date of `3/20/12` = `5 days until 3/20/12`
* *NOT* Input date of `4/16/12` = `1 month, 1 days until 3/20/12`
* Input date of `2012.04.20` = `1 month, 5 days until 2012.04.20`
* *NOT* Input date of `2012.04.20` = `36 days until 2012.04.20`
* Input date of `10/31/17` = `5 years, 7 months, 16 days until 10/31/17`
* Input date of `3/15/13` = `1 year until 3/15/13`
This is code golf, so shortest length code wins.
I suppose for the sake of having a deadline, I will be selecting an answer on:
## March 23, 2012!
(This is my first CG question, so I'll be happy to correct any question errors on my part!)
[Answer]
## R, 99 characters
I know it is sort of cheating, but R is all about its packages and [lubridate](http://cran.r-project.org/web/packages/lubridate/index.html) is so convenient for this kind of tasks!
```
f=function(x){library(lubridate);cat(show(as.period(interval(mdy("3/15/2012"),mdy(x)))),"until",x)}
```
# Usage:
```
f("10/31/2017")
[1] 5 years, 7 months and 16 days
5 years, 7 months and 16 days until 10/31/2017
```
[Answer]
# [Python](https://docs.python.org/) + [`dateutil`](https://dateutil.readthedocs.io/en/stable/), 331 bytes
```
from dateutil import*
from datetime import*
def f(s):
if'/'in s:m,y,d=map(int,s.split('/'))
else:y,m,d=map(int,s.split('.'))
x=relativedelta.relativedelta(datetime(y,m,d),datetime.now())
D,M,Y=x.days,x.months,x.years
return f"{Y} year{'s'*(Y>1)}, "*(Y>0)+f"{M} month{'s'*(M>1)}, "*(M>0)+f"{D} day{'s'*(D>1)} "*(D>0)+"until "+s
```
[Answer]
## PHP, 315 characters
```
function p($z)
{
list($d,$m,$y)=explode("/",$z);
$d=$d-date("d");
$n=$m-1;
$m=$m-date("m")-($d<0);
$d=$d+($d<0)*($n>7^$n&1)+27+($n-2?3:($y%4?1:($y%100?2:($y%400?1:2))));
$y=$y-date("Y")-($m<0);
$s="s ";
echo ($y?$y." year".$s[$y<2]:"")." ".($m?$m." month".$s[$m<2]:"")." ".($d?$d." day".$s[$d<2]:"")." until ".$z;
}
```
Usage:
```
p("11/03/2006");
```
Takes dates in a `dd/mm/yyyy` format. I've used Griffin's month length calculation([again](https://codegolf.stackexchange.com/a/3412/737)), though I had to stick extra brackets in it to make the precedence work properly. I've also left some line-breaks in to make it a little easier to read.
[Answer]
# Ruby (213)
takes dates in any format `Date.parse` accepts. Tried just with `yyyy-mm-dd`
```
def u s
t=Date.today
f=Date.parse s
[[0,'year'],[0,'month'],[0,'day']].map{|c,n| while t<f
c+=1
t=t.send"next_#{n}"
end
c,t=c-1,t.send("prev_#{n}")if t>f
[c,n+(c>1??s:'')]*' 'if c>0}.compact*', '+' until '+s
end
```
to also get weeks, add:
```
['prev_','next_'].each{|n|Date.send(:define_method,n+'week'){send n+'day',7}}
```
and `[0,'week'],` (between month and day). days will then always be `< 7`
[Answer]
## VBA: 766 631 Chars
Thanks to [mellamokb](https://codegolf.stackexchange.com/users/879/mellamokb) for helping shorten up the string creation and `IIf`.
```
Function k(i)
e=" month"
g="s"
n=Now()
r=Month(n)
s=Month(i)
t=DateSerial(Year(i),s,1)
u=DateSerial(Year(i),s-1,1)
v=Day(n)
w=Day(i)
x=DateSerial(Year(n),r,1)
d=t-u-v+w
For y=0 To 10
If Year(DateAdd("yyyy",-1*y,i))=Year(n) Then Exit For
Next
y=IIf(s=1,y-1,y)
z=s-r
z=IIf(z<0,z+12,z)
For m=0 To z
If Month(DateAdd("m",-1*m,i))=r Then Exit For
Next
d=IIf(v<=w,w-v,d)
m=IIf(v>w,m-1,m)
If y Then a=y & " year" & Left(g,y-1)
a=IIf((m Or d) And y,a & ",",a)
If m Then b=IIf(d,m & e & Left(g,m-1) & ",",m & e & Left(g,m-1))
If d Then c=IIf(d>1,d & " days",d & " day")
k=Trim(Trim(a & " " & b) & " " & c) & " until " & i & "."
End Function
```
I know `VBA` definitely does not lend itself to code golfing as well as some other languages, but it's what I'm good (not expert) at. :-)
This has been a fun exercise for me!
[Answer]
## JavaScript (ES6), 125 bytes
Since [the answer by Paolo](https://codegolf.stackexchange.com/a/5227/22867) used an external library, I shall do the same. Node.js is all about NPM packages and [moment](http://momentjs.com/) + [HumanizeDuration](https://github.com/EvanHahn/HumanizeDuration.js) is so convenient for this task!
### Node environments
```
m=require('moment'),f=d=>console.log(require('humanize-duration')(m(d).diff(m()),{units:['y','mo','d'],round:1})+' until '+d)
```
### Browser environment
Since the libraries declare global variables, it's actually a bit shorter (102 bytes). It's not clear whether I need to include the script tags required to load in the third-party JavaScript, so I will count the Node one officially.
```
f=d=>console.log(humanizeDuration((m=moment)(d).diff(m()),{units:['y','mo','d'],round:1})+' until '+d)
```
---
## CoffeeScript, also 125 bytes
```
f=(d)->console.log require('humanize-duration')((m=require 'moment')(d).diff(m()),{units:['y','mo','d'],round:1})+' until '+d
```
[Answer]
# PHP, 151 chars
```
function p($z){$n=date_create(date('Y-m-d'));$d=date_create($z);$i=date_diff($n,$d);print($i->format('%R%y years, %m months, and %a days until '.$z));}
```
] |
[Question]
[
## Task
>
> Write a function/program which takes \$n\$ as a parameter/input and prints/returns the number of topologies (which is demonstrated below) on the set \$\{1,2,...,n\}\$.
>
>
>
## Definition of Topology
Let \$X\$ be any finite set, and assume that \$T\$, which is subset of the [power set](http://en.wikipedia.org/wiki/Power_set) of \$X\$ (i.e. a set containing subsets of \$X\$), satisfy [these conditions](http://en.wikipedia.org/wiki/Finite_topological_space#Topologies_on_a_finite_set):
1. \$X\$ and [\$\emptyset\$](http://en.wikipedia.org/wiki/Empty_set) are in \$T\$.
2. If \$U, V\$ are in \$T\$, then the [union](http://en.wikipedia.org/wiki/Union_(set_theory)) of those two sets is in \$T\$.
3. If \$U, V\$ are in \$T\$, then the [intersection](http://en.wikipedia.org/wiki/Intersection_(set_theory)) of those two sets is in \$T\$.
...then \$T\$ is called the topology on \$X\$.
## Specifications
1. Your program is either:
* a function which takes \$n\$ as a parameter
* or a program which inputs \$n\$
and prints or returns the number of (distinct) topologies on the set \$\{1,2,...,n\}\$.
2. \$n\$ is any non-negative integer which is less than \$11\$ (of course there's no problem if your program handles n bigger than \$11\$), and the output is a positive integer.
3. Your program should not use any kinds of library functions or native functions which calculates the number of topology directly.
Example input (value of n) : `7`
Example output/return : `9535241`
You may check your return value at [here](http://oeis.org/A000798) or [here](http://en.wikipedia.org/wiki/Finite_topological_space#Number_of_topologies_on_a_finite_set).
Of course, shortest code wins.
---
The winner is decided, however, I may change the winner if shorter code appears..
[Answer]
## Python, 147 chars
```
N=input()
S=lambda i,K:1+sum(0if len(set(j&k for k in K)-K)-1 else S(j+1,K|set(j|k for k in K))for j in range(i,2**N))
print S(1,set([0,2**N-1]))
```
Quick for N<=6, slow for N=7, unlikely N>=8 will ever complete.
Individual sets are represented by integer bitmasks, and topologies by sets of bitmasks. `S(i,K)` computes the number of distinct topologies you can form by starting with `K` and adding sets with bitmasks >= `i`.
[Answer]
# Haskell, 144 characters
```
import List
import Monad
p=filterM$const[True,False]
f n=sum[1|t<-p$p[1..n],let e=(`elem`t).sort,e[],e[1..n],all e$[union,intersect]`ap`t`ap`t]
```
Almost a direct implementation of the specification, modulo some monad magic.
Extremely slow for `n > 4`.
[Answer]
# Python, 131 chars
```
lambda n:sum(x&(x>>2**n-1)&all((~(x>>i&x>>j)|x>>(i|j)&x>>(i&j))&1 for i in range(2**n)for j in range(2**n))for x in range(2**2**n))
```
Expanded version:
```
def f(n):
count = 0
for x in range(2**2**n): # for every set x of subsets of [n] = {1,...,n}
try:
assert x & 1 # {} is in x
assert (x >> 2 ** n - 1) & 1 # [n] is in x
for i in range(2**n): # for every subset i of [n]...
if x >> i & 1: # ...in x
for j in range(2**n): # for every subset j of [n]...
if x >> j & 1: # ...in x
assert (x >> (i | j)) & 1 # their union is in x
assert (x >> (i & j)) & 1 # their intersection is in x
count += 1
except AssertionError:
pass
return count
```
For example, suppose n = 3. The possible subsets of [n] are
```
0b000
0b001
0b010
0b011
0b100
0b101
0b110
0b111
```
where the ith bit indicates whether i is in the subset. To encode *sets* of subsets, we notice that each of these subsets either belongs or does not belong to the set in question. Thus, for example,
```
x = 0b10100001
0b000 # 1
0b001 # 0
0b010 # 1
0b011 # 0
0b100 # 0
0b101 # 0
0b110 # 0
0b111 # 1
```
indicates that x contains {}, {2}, and {1,2,3}.
[Answer]
## Zsh, 83 characters
This solution matches the letter of your requirements (but not, of course, the spirit). There's undoubtedly a way to compress the numbers even more.
```
a=(0 3 S 9U 5CT 4HO6 5ODFS AMOZQ1 T27JJPQ 36K023FKI HW0NJPW01R);echo $[1+36#$a[$1]]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
```
ŒP⁺f,œ|ɗþ`ẎẎṢe¥€Ʋ;ẠCaiʋẠʋ€RS
```
[Try it online!](https://tio.run/##y0rNyan8///opIBHjbvSdI5Orjk5/fC@hIe7@kBo56LUQ0sfNa05tsn64a4FzomZp7qB9KluoFBQ8P@ju3UOt6sA2e7//xsDAA "Jelly – Try It Online")
*So, incredibly,* slow. Times out on TIO for all \$n \ge 4\$, and running it locally with \$n = 4\$ still didn't produce an output after 15 minutes. That is because this answer has a time complexity of \$O(2^{2^n})\$, as we calculate \$\mathcal P(\mathcal P(\{1, 2, ..., n\}))\$ and filter on topologies.
## How it works
```
ŒP⁺f,œ|ɗþ`ẎẎṢe¥€Ʋ;ẠCaiʋẠʋ€RS - Main link. Takes n on the left
ŒP - Powerset of X = [1, 2, ..., n]
⁺ - Powerset of that
ʋ - Last 4 links as a dyad f(T, X):
Ʋ - Last 4 links as a monad g(T):
ɗ - Last 3 links as a dyad h(U, V):
f - U ∩ V
œ| - U ∪ V
, - [U ∩ V, U ∪ V]
þ` - For all U ∈ T, V ∈ T, calculate h(U, V)
ẎẎ - Flatten into a list of unions and intersections
¥ - Last 2 links as a dyad k(Z, T):
Ṣ - Sort Z
e - Is Z ∈ T?
€ - For each Z in the list of unions and intersections, find k(Z, T)
ʋ - Last 4 links as a dyad l(T, X):
Ạ - Are all elements of T truthy?
C - Complement; are any falsey?
i - Index of X in T, or 0 if not present
a - And; are both true?
; - Concatenate the list of k(Z, T)s with l(T, X)
Ạ - Are all true?
R - X = [1, 2, ..., n]
€ - Over each T ∈ P(P(X)), calculate f(T, X)
S - Count the truthy elements
```
[Answer]
# [Scala](https://www.scala-lang.org/), ~~450~~ 343 bytes
Thanks to the comment, saved 107 bytes using some trivial tricks.
---
rewrite [@user76284's solution](https://codegolf.stackexchange.com/a/204039/110802) into scala.
Using scala for calculation is so slow! On TIO, I only use one case `f(4)=355`
---
Golfed version. [Try it online!](https://tio.run/##jZExT8MwEIX3/oqjqipb0CpBTAmO1IGBgQkxIYSMSVpH6bk6u6WVyW8PdqpEgBi4yb53n9/T2SrZyM681aVy8CA1gu/eywoqhtk9Oi78QRIokeSVIXa8XSSwR6cb2Eq3We7MB7u@@nZEzpfORNA7OnlpbUmOseM85Rci4fnYKArGfnCLdCCH2Wio/zTE0URXrH9MD5SPVP1Pqh6pIVcfTH/WnP9OfFbmgwJBakPloC5FmrdKOrXxStoSXrNVz2iDd0SGRBEmc9V2AHGz27BkJmltM1gRydPzoyON6xeewRNqBwL8BEIdZAMI4ma8UGn3TdTD3/C@uwuga5DZacVmyIM0Ow9No95O2u4L)
```
def f(n:Int)={var c=0;for(x<-0 until math.pow(2,math.pow(2,n)).toInt){try{assert((x&1)!=0);assert((x>>((math.pow(2,n)-1).toInt)&1)!=0);for(i<-0 until math.pow(2,n).toInt){if(((x>>i)&1)!=0){for(j<-0 until math.pow(2,n).toInt){if(((x>>j)&1)!=0){assert(((x>>(i|j))&1)!=0);assert(((x>>(i&j))&1)!= 0);}}}}; c+=1;}catch{case _:AssertionError=>;}};c}
```
Ungoled version. [Try it online!](https://tio.run/##lZIxT8MwEIX3/IpHVVWOoFWLmCoSiYGBgQkxIYSMSVpHqV3ZLlBBfnu4OGmbQlKJDNb57t7nu@hZwXNelvo1S4TDPZcKXwHwlqRImZrjTrnQn4h8AXjnBkJvfGbqM6k2YJ@4HmMKysscK@6Wk7X@YJcXR7EKw4nTFbOBAc5s9zHArU2MY0QbYRbijJ4IO4pxDMaOwRiTYAfvEPshZd@Q6s9c1SdTMDTvyTb1qKthZ/9j/@ZnJ/it5XfttMo3aTpX7ZeMTkuKoO92iA9RbYLzCLMmVUBwJ5at4QW3CV7muPGTSK1ujaF/FcVBG1afHhdUt8Z/KzIj42ZhSW8M3z49OCPV4pn8@Khk25A5FKKr/cUkdpNXdXJwveKahC5XzA5SNiSvRBjWTYPQv1gEZfkD)
```
object Main {
def f(n: Int): Int = {
var count = 0
for (x <- 0 until math.pow(2, math.pow(2, n)).toInt) {
try {
assert((x & 1) != 0)
assert((x >> ((math.pow(2, n) - 1).toInt) & 1) != 0)
for (i <- 0 until math.pow(2, n).toInt) {
if ( ((x >> i) & 1) != 0) {
for (j <- 0 until math.pow(2, n).toInt) {
if ( ((x >> j) & 1) != 0) {
assert( ((x >> (i | j)) & 1) != 0)
assert( ((x >> (i & j)) & 1) != 0)
}
}
}
}
count += 1
} catch {
case _: AssertionError =>
}
}
count
}
def main(args: Array[String]): Unit = {
val n =4
val result = f(n)
println(s"f($n) = $result")
}
}
```
] |
[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 3 years ago.
[Improve this question](/posts/1118/edit)
>
> **Note:** After trying this myself, I soon realized what a mistake this was. Therfore, I am modifying the rules a bit.
>
>
>
The minimum required functionality:
* Character classes (`.`, `\w`, `\W`, etc.)
* Multipliers (`+`, `*`, and `?`)
* Simple capture groups
---
Your challenge is to implement [PCRE](http://www.pcre.org/) in the language of your choice subject to the following conditions:
* You **may not** use your language's native RegEx facilities in *any way*. You may not use a 3rd party RegEx library either.
* Your entry should implement as much of the PCRE spec. as possible.
* Your program should accept as input, 2 lines:
>
>
> + the regular expression
> + the string input to match against
>
* Your program should indicate in its output:
>
>
> + Whether the RegEx matched anywhere in the input string
> + The results of any capturing groups
>
* The winner shall be the entry that implements as much of the spec. as possible. In case of a tie, the winner shall be the most creative entry, as judged by me.
---
**Edit:** to clarify a few things, here are some examples of input and expected output:
---
* **Input:**
```
^\s*(\w+)$
hello
```
* **Output:**
```
Matches: yes
Group 1: 'hello'
```
---
* **Input:**
```
(\w+)@(\w+)(?:\.com|\.net)
[[email protected]](/cdn-cgi/l/email-protection)
```
* **Output:**
```
Matches: yes
Group 1: 'sam'
Group 2: 'test'
```
---
[Answer]
## Python
Since implementing full PCRE is too much I implemented only an essential subset of it.
Supports `|.\.\w\W\s+*()`. Input regexp must be correct.
## Examples:
```
$ python regexp.py
^\s*(\w+)$
hello
Matches: hello
Group 1 hello
$ python regexp.py
(a*)+
infinite loop
$ python regexp.py
(\w+)@(\w+)(\.com|\.net)
[[email protected]](/cdn-cgi/l/email-protection)
Matches: [[email protected]](/cdn-cgi/l/email-protection)
Group 1 sam
Group 2 test
Group 3 .net
```
## How it works:
For detailed theory read this [Introduction to Automata Theory, Languages, and Computation](http://infolab.stanford.edu/~ullman/ialc.html).
The idea is to convert the original regular expression into a nondeterminist finite automata (NFA). Actually, PCRE regular expressions are at least context free grammars for which we need push-down automata, but we'll limit ourselves to a subset of PCRE.
Finite automatas are directed graphs in which nodes are states, edges are transitions and each transition has a matching input. Initially you start from a start node, predefined. Whenever you receive an input that matches one of the transition you take that transition to a new state. If you reached a terminal node it is called that automata accepted input. In our case input is a matching function that returns true.
They are called nondeterminist automata because sometimes there are more matching transitions that you can take from the same state. In my implementation all transition to the same state must match the same thing, so I stored the matching function together with the destination state (`states[dest][0]`).
We transform our regexp to a finite automata using building blocks. A building block has a start node (`first`) and an end node (`last`) and matches something from the text (possible empty string).
The simplest examples include
* matching nothing: `True` (`first == last`)
* matching a character: `c == txt[pos]` (`first == last`)
* matching end of string: pos == len(txt)`(`first == last`)
You will also need the new position in text where to match next token.
More complicated examples are (capital letters stand for blocks).
* matching B+:
+ create nodes: u, v (matching nothing)
+ create transitions: u -> B.first, B.last -> v, v -> u
+ when you get to node v you already matched B. Then you have two options: go further, or try to match B again.
* matching A|B|C:
+ create nodes: u, v (matching nothing)
+ create transitions: u -> A.first, u -> C.first, u -> C.first,
+ create transitions: A->last -> v, B->last -> v, C->last -> v,
+ from u you can go to any block
All regexp operators can be transformed like this. Just give a try for `*`.
The last part is to parse the regexp which requires a very simple grammar:
```
or: seq ('|' seq)*
seq: empty
seq: atom seq
seq: paran seq
paran: '(' or ')'
```
Hopefully implementing a simple grammar (I think is LL(1), but correct me if I'm wrong) is much easier than building an NFA.
Once you have the NFA you need to backtrack until you reach terminal node.
## Source code (or [here](http://pastebin.com/3RhFn58y)):
```
from functools import *
WORDCHAR = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_'
def match_nothing(txt, pos):
return True, pos
def match_character(c, txt, pos):
return pos < len(txt) and txt[pos] == c, pos + 1
def match_space(txt, pos):
return pos < len(txt) and txt[pos].isspace(), pos + 1
def match_word(txt, pos):
return pos < len(txt) and txt[pos] in WORDCHAR, pos + 1
def match_nonword(txt, pos):
return pos < len(txt) and txt[pos] not in WORDCHAR, pos + 1
def match_dot(txt, pos):
return pos < len(txt), pos + 1
def match_start(txt, pos):
return pos == 0, pos
def match_end(txt, pos):
return pos == len(txt), pos
def create_state(states, match=None, last=None, next=None, name=None):
if next is None: next = []
if match is None: match = match_nothing
state = len(states)
states[state] = (match, next, name)
if last is not None:
states[last][1].append(state)
return state
def compile_or(states, last, regexp, pos):
mfirst = create_state(states, last=last, name='or_first')
mlast = create_state(states, name='or_last')
while True:
pos, first, last = compile_seq(states, mfirst, regexp, pos)
states[last][1].append(mlast)
if pos != len(regexp) and regexp[pos] == '|':
pos += 1
else:
assert pos == len(regexp) or regexp[pos] == ')'
break
return pos, mfirst, mlast
def compile_paren(states, last, regexp, pos):
states.setdefault(-2, []) # stores indexes
states.setdefault(-1, []) # stores text
group = len(states[-1])
states[-2].append(None)
states[-1].append(None)
def match_pfirst(txt, pos):
states[-2][group] = pos
return True, pos
def match_plast(txt, pos):
old = states[-2][group]
states[-1][group] = txt[old:pos]
return True, pos
mfirst = create_state(states, match=match_pfirst, last=last, name='paren_first')
mlast = create_state(states, match=match_plast, name='paren_last')
pos, first, last = compile_or(states, mfirst, regexp, pos)
assert regexp[pos] == ')'
states[last][1].append(mlast)
return pos + 1, mfirst, mlast
def compile_seq(states, last, regexp, pos):
first = create_state(states, last=last, name='seq')
last = first
while pos < len(regexp):
p = regexp[pos]
if p == '\\':
pos += 1
p += regexp[pos]
if p in '|)':
break
elif p == '(':
pos, first, last = compile_paren(states, last, regexp, pos + 1)
elif p in '+*':
# first -> u ->...-> last -> v -> t
# v -> first (matches at least once)
# first -> t (skip on *)
# u becomes new first
# first is inserted before u
u = create_state(states)
v = create_state(states, next=[first])
t = create_state(states, last=v)
states[last][1].append(v)
states[u] = states[first]
states[first] = (match_nothing, [[u], [u, t]][p == '*'])
last = t
pos += 1
else: # simple states
if p == '^':
state = create_state(states, match=match_start, last=last, name='begin')
elif p == '$':
state = create_state(states, match=match_end, last=last, name='end')
elif p == '.':
state = create_state(states, match=match_dot, last=last, name='dot')
elif p == '\\.':
state = create_state(states, match=partial(match_character, '.'), last=last, name='dot')
elif p == '\\s':
state = create_state(states, match=match_space, last=last, name='space')
elif p == '\\w':
state = create_state(states, match=match_word, last=last, name='word')
elif p == '\\W':
state = create_state(states, match=match_nonword, last=last, name='nonword')
elif p.isalnum() or p in '_@':
state = create_state(states, match=partial(match_character, p), last=last, name='char_' + p)
else:
assert False
first, last = state, state
pos += 1
return pos, first, last
def compile(regexp):
states = {}
pos, first, last = compile_or(states, create_state(states, name='root'), regexp, 0)
assert pos == len(regexp)
return states, last
def backtrack(states, last, string, start=None):
if start is None:
for i in range(len(string)):
if backtrack(states, last, string, i):
return True
return False
stack = [[0, 0, start]] # state, pos in next, pos in text
while stack:
state = stack[-1][0]
pos = stack[-1][2]
#print 'in state', state, states[state]
if state == last:
print 'Matches: ', string[start:pos]
for i in xrange(len(states[-1])):
print 'Group', i + 1, states[-1][i]
return True
while stack[-1][1] < len(states[state][1]):
nstate = states[state][1][stack[-1][1]]
stack[-1][1] += 1
ok, npos = states[nstate][0](string, pos)
if ok:
stack.append([nstate, 0, npos])
break
else:
pass
#print 'not matched', states[nstate][2]
else:
stack.pop()
return False
# regexp = '(\\w+)@(\\w+)(\\.com|\\.net)'
# string = '[[email protected]](/cdn-cgi/l/email-protection)'
regexp = raw_input()
string = raw_input()
states, last = compile(regexp)
backtrack(states, last, string)
```
] |
[Question]
[
# Background
Here on CGCC, a commonly seen subgenre is [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") – writing a program that works even if one character is deleted. A similar problem is studied in the field of coding theory: finding an encoding that can be decoded even if one symbol is deleted from the encoded string. In this challenge, we're looking at the "binary" variant of the problem: the codes are strings of bits, and the deletions that we're trying to harden against happen at the bit level.
Although the problem of finding the optimal code for handling a single deletion from a string of bits is still not entirely solved, one commonly used code for the purpose is the Varshamov–Tenengolts code (typically called the "VT code" for short); this code has the property that for every encoded codeword, the sum of the 1-based indexes of the 1 bits is divisible by the length of the codeword plus 1. The full version of this code is conjectured to be an optimal solution to the problem (and is known to at least be close to optimal).
This challenge is about implementing an encoder for a variant of the VT code, known as the "systematic VT code". The systematic variant occasionally wastes a bit in order to make the encoding and decoding algorithms more efficient (and is used here because I think it makes for a more interesting golfing challenge than the original version of the code).
# The task
Given a string of bits as input, output a string of bits that represents the input string encoded with the systematic binary VT code.
The following algorithm is one possible definition of the code in question: following the algorithm will let you know the systematic VT encoding of any string of bits. The task is to implement something that produces the same results as this algorithm would; your solution doesn't necessarily need to use this algorithm itself, but it does have to produce the same results.
1. Imagine an infinite array of positions into which bits can be placed. Mark those positions whose 1-based indexes are powers of 2:
```
_* _* _ _* _ _ _ _* _ _ _ _ _ _ _ _* _ _ …
```
2. Fill the input bits into the unmarked positions of the array, in order from left to right, until no input bits are left. For example, suppose we were encoding the string `01101001100`:
```
_* _* 0 _* 1 1 0 _* 1 0 0 1 1 0 0 _* _ _ …
```
3. Cut off the array after the last filled bit: anything beyond that point is deleted, whether marked or unmarked:
```
_* _* 0 _* 1 1 0 _* 1 0 0 1 1 0 0
```
4. Add together the 1-based indexes of all the 1 bits in the array so far.
```
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
_* _* 0 _* 1 1 0 _* 1 0 0 1 1 0 0
5+6 +9 +12+13 = 45
```
5. Calculate minus this sum, wrapping-modulo the length of the array plus 1. In this case, we're calculating \$-45\mod (15+1)\$, which is \$3\$ (because \$-45=(16\times-3)+3\$, i.e. \$-45\$ has remainder \$3\$ upon dividing by \$16\$).
6. Express the resulting value as a sum of distinct powers of 2; in this case, we have \$3=2^1+2^0=2+1\$. (In other words, we're writing the sum in binary, and then looking at the place-value of the resulting 1s.)
7. Fill in the marked positions of the array, placing a 1 into those positions whose indexes were part of the sum in the previous step, and a 0 into those positions that weren't:
```
1 2 4 8
1* 1* 0 0* 1 1 0 0* 1 0 0 1 1 0 0
```
The result of the process is the bit string we want to create as output, e.g. for our input string `01101001100`, the output is `110011001001100`.
# Clarifications
* As usual, your submission can either be [a full program or a function](https://codegolf.meta.stackexchange.com/a/6912), and can take input and produce output via any of the [usually permitted I/O methods](https://codegolf.meta.stackexchange.com/q/2447).
* The algorithm is defined in terms of 1-based indexes, because this is necessary for the resulting code to be able to handle deletions in every position. Even if your language uses 0-based indexes, you still have to produce the same result as the algorithm above does using its 1-based indexes (e.g. the first bit of the input string has to appear as the third bit of the output string, not the first or fourth).
* You can represent the "string of bits" in the input or output as a string/list of Booleans (i.e. using the truthiness or falsiness of each element); a string/list of numbers that are each 0 or 1 (or, in output, other values that are numerically 0 or 1); or a string/list of characters that are each "0" or "1" or each have a codepoint of 0 or 1. You can't represent it as the digits of a binary or decimal number, because that would cause leading zeroes to be lost.
* In I/O, you must use the same representation consistently, e.g. if "1" has a codepoint of 0 in some encoding, you can't output a string of "1"s and say that the 0s are being output by codepoint and the 1s as characters; but you may use different encodings for the input and the output if you wish.
* Although an empty input is meaningful (and, in theory, should encode to itself), your solution doesn't need to be able to handle this particular case.
# Test cases
```
0 -> 000
1 -> 101
10 -> 11100
01 -> 10001
111 -> 001011
1101 -> 1010101
1010 -> 1111010
01101001100 -> 110011001001100
```
# Victory condition
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge: as usual for code golf, the fewer bytes there are in your answer, the better. Your submission should contain a header listing the language in which the answer is written, and the number of bytes it contains.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~29~~ ~~27~~ 26 bytes
```
gÝo<£õÜD»SÐƶ«þO(sgÌ%bRs0ζS
```
[Try it online](https://tio.run/##yy9OTMpM/f8//fDcfJtDiw9vPTzH5dDu4MMTjm07tPrwPn@N4vTDPapJQcUG57YF//9vYGhoYGgAIg0A), or [try all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRf6fI//fDcfJtDiw9vPTzH5dDu4MMTjm07tPrwPn@N4vTDPapJQcUG57YF//fS@R9toKNgCERASsnAUAnIMgRxDQ3AglBhEANEGijFAgA).
I'm quite sure this can be golfed
# Explanation
```
g push the input's length
Ý push the range [0,...,length]
o take 2^<each value>
< remove 1 from each value
£ split the input string into subsequences of those sizes
(e.g. ["", "0", "110", "1001100", "", "", "", "", "", "", "", ""])
õ push the empty string
Ü remove all of its occurrences at the end of the list
(e.g. ["", "0", "110", "1001100"])
D duplicate the result
» join it by newlines
S convert it to a list of characters
(e.g. ["\n", "0", "\n", "1", "1", "0", "\n", "1", "0", "0", "1", "1", "0", "0"])
Ð triplicate that list, pushing 2 new copies
ƶ lift the first copy, multiplying each number by its 1-based index
(and not changing the newlines)
(e.g. ["\n", 0, "\n", 4, 5, 0, "\n", 8, 0, 0, 11, 12, 0, 0])
« merge it with the second copy
þ keep only the numbers from that list
O take the sum
( negate it
s swap that with the third copy
g find that list's length (e.g. 14)
Ì add 2 to it (e.g. 16)
% calculate (-sum) % (length+2) (e.g. 3)
b convert it to binary (e.g. "11")
R reverse it (e.g. "11")
s swap, to make the copy without newlines on top
(e.g. ["", "0", "110", "1001100"])
0ζ zip it with the reversed binary string, using 0 as a filler
(e.g. [["1", ""], ["1", "0"], ["0", "110"], ["0", "1001100"]])
S convert it to a list of characters
(e.g. ["1", "1", "0", "0", "1", "1", "0", "0", "1", "0", "0", "1", "1", "0", "0"])
```
[Answer]
# JavaScript (ES6), ~~89~~ 83 bytes
A rather literal implementation of the algorithm described in the challenge.
```
s=>(g=(q,i=j=t=0)=>s[i]?(j&++j?s[t+=j*s[i],i++]:(q/=2)*2&1)+g(q,i):"")(g()&&j*t%~j)
```
[Try it online!](https://tio.run/##bY7LCoMwEEX3/QoJVDLG1olLYfRDxIVYFUMxtZEu@@vWUB@lMYuEuZzcOap8laZ6do/x0utbPTU0GUp5S3wIO1I0EgKlJu@KjCtfCJWZfBSkAhuFnRBFwoeIYghiX4Jo7TdIGAPecvB9FYznt4Kp0r3R9/p61y1vOEPmbQfAiyIPEU9/kHQgidKBfqoWSEq3C6WDzRvdNrlzq9e89IDbCzc1PNTbBTc9G7qCNrU3shX8jsszfQA "JavaScript (Node.js) – Try It Online")
### Commented
```
s => ( // main function taking the input string
g = ( // g is a recursive function taking:
q, // q = result of the 5th step of the algorithm
// as described in the challenge,
// or undefined during the first pass
i = // i = pointer in s[]
// and also using:
j = // j = pointer in the output string
t = 0 // t = sum of the indices of 1 bits
) => //
s[i] ? // if s[i] is defined:
( //
j & ++j ? // increment j; if j is not a power of 2:
s[ //
t += j * s[i], // add j to t if s[i] is "1"
i++ // yield s[i] and increment i afterwards
] //
: // else:
(q /= 2) * 2 & 1 // yield the least significant bit of q
// and divide q by 2
) + g(q, i) // append the result of a recursive call
: // else:
"" // stop the recursion
)( //
g() && // do a first call to g so that j and t are set
j * t % ~j // then compute the correct value of q and use
) // it for the second call
```
[Answer]
# [R](https://www.r-project.org), 126 bytes
```
\(x){v=!(l=seq(3*sum(x|1)))
v[p<--2^l/2]=seq(!x)
v=v[l<-1:(m=which.max(v))]
v[p]=x
v[-l[p]]=-sum(which(v>0))%%(m+1)%/%-p%%2
v}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY_bisIwEIbv-xQVCcxoopl6I2J8CvFGu7BURaHFQ20MeHgRb7oXyz7TPse-wKath0ZCmOH_v8k_uX3t85_JONrMF-o7OyxF__c6A4MnrRoQq3Sxg14rzRIwZ0JET0-3QyGCj7gbhKXbMFZUehoPBQ0gUcfVOlp1kk8DGjEs-FAZW0Rsu1CJ4q2SAT2SiIxB0iZkXSa2jAWevty3-KuWgggs5Td9MfKllN5TpYdKkmoqf9JEVOclr01Id4ZennUkvZnOaHmcQO6GFoATy-8Mf_Q12sYVtype9fU8r-o_)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
FS«W¬&Lυ⊖Lυ⊞υω⊞υι»⭆υ⎇ιι⎇κ﹪÷﹪±↨⌕Aυ1¹Lυκ²ω
```
[Try it online!](https://tio.run/##TU7RqsIwDH12X1F8SmEXVl99UkQQriLoD5QtbsHaSpc5Lhe/vaaoaCCHnJOQc@rOxjpYl9IpRAUbfx34wJF8C1qr/2IyduRQwS4wLIlH6nHhG/hF33IHgy7VCuuIF/SMX3IutR96mUs16nkxeRMSci/24sDwNNraa14cMXob/4Dk5sPOpdqGZnBBovGKbtQgvIQdtpYRlrZHWJNvFs7lP1MzlVRGC3zilOosPdM5jNQ8pcqYylQZq/Rzcw8 "Charcoal – Try It Online") Link is to verbose version of code. I/O is as digit strings. Explanation:
```
FS«
```
Loop over the input bits.
```
W¬&Lυ⊖Lυ⊞υω
```
Skip over powers of `2`. (`0` also gets skipped over, which adjusts for 0-indexing.)
```
⊞υι
```
Push the next bit in the position where it is to be output.
```
»⭆υ⎇ιι⎇κ﹪÷﹪±↨⌕Aυ1¹Lυκ²ω
```
Fill in the skipped bits with the base `2` of the shortfall.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~27~~ 26 bytes
```
0i"NB?0]@]vtfs_ynQ\BfqW1w(
```
[Try it online!](https://tio.run/##y00syfn/3yBTyc/J3iDWIbasJK04vjIvMMYprTDcsFzj//9oAwVDIDQAYxjbIBYA) Or [verify all test cases](https://tio.run/##y00syfmf8N8gU8nPyd4g1iG2rCStOL4yLzDGKa0w3LBc47@6rq56hEvI/2iDWK5oQxBWALEMFCBsQzgNEzFQgKtQgPIUYGyDWAA).
### How it works
```
0 % Push 0 (first "marked" position)
i % Push input: numerical vector
" % For each digit in the input
N % Push current number of elements in the stack
B? % Does its binary expansion contain only ones? If so,
0 % Push a 0 ("marked position")
] % End
@ % Push current input digit
] % End
v % Concatenate all digits into a column vector
tf % Duplicate, find: push 1-based positions of non-zeros
s_ % Sum, negate
y % Duplicate from below: pushes copy of column vector
nQ % Length plus 1
\ % Modulo
Bf % 1-based indices of binary expansion
qW % Subtract 1, then compute 2 raised to that, element-wise
1w( % Write 1 at those positions. Implicitly display
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 29 bytes
```
ΣSżż+öm;↔ḋ§%o→Lȯ_ΣWIΣmΘCΘm←İ2
```
[Try it online!](https://tio.run/##yygtzv7//9zi4KN7ju7RPrwt1/pR25SHO7oPLVfNf9Q2yefE@vhzi8M9zy3OPTfD@dyM3EdtE45sMPr//3@0gY4hEBqAMYxtEAsA "Husk – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 250 bytes
```
g(a)=2^a2-a-2
L=l.length
C=ceil(log_2L)-1
c=\{L<3:L,g(C)<L:C+1,C\}
K=2^c+L-g(c-1)
B=[1...K]
A=-0^{mod(log_2B,1)}
D=\{A=0:l[B+\sum_{n=1}^BA[n]],A\}
E=2^{[0...c]}
F=(i-mod(floor(mod(-B[D=1].total,K+1)/E),2)E)^2.min
f(l)=[\{D[i]>=0:D[i],F=0,0\}\for i=B]
```
The function \$f(l)\$ takes in a list of bits and returns the encoded list of bits. Pretty much follows the exact algorithm specified in the challenge.
Holy crap it's long. 100% can be golfable, but I'm too lazy to do that.
[Try It On Desmos!](https://www.desmos.com/calculator/zitg6gsdms)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/vpiz9ehitp)
] |
[Question]
[
## Challenge Statement
The goal of this challenge is to build the 5 state *Infinite Time Turing Machine* that takes the longest to halt. Since Infinite Time Turing Machines can run for infinite time your score will be a "transfinite ordinal".
That's the challenge statement, but if you don't what all this means or want to dig into the details the rest of this challenge is some definitions and an example to help you. If there is something you don't understand or that isn't explained feel free to leave a comment.
## Turing Machines
For clarity we will define the Turing machines as used for this problem. This is going to be rather formal. If you are familiar with Turing machines this is a *single-tape*, *binary* Turing machine, without an explicit halt state, and with the possibility of a *no shift* move. But for the sake of absolute clarity here is how we will define a classical Turing machine and its execution:
A Turing machine consists of a \$3\$-Tuple containing the following:
* \$Q\$: A finite non-empty set of states.
* \$q\_s : Q\$: The initial state.
* \$\delta : Q\times \{0,1\} \nrightarrow Q\times \{0,1\}\times\{1, 0, -1\}\$: A partial transition function, which maps a state and a binary symbol, to a state, a binary symbol and a direction (left, right or no movement).
During execution of a specific Turing machine the machine has a *condition* which is a \$3\$-Tuple of the following:
* \$\xi\_\alpha : \mathbb{Z}\rightarrow \{0,1\}\$: The *tape* represented by a function from an integer to a binary symbol.
* \$k\_\alpha :\mathbb{Z}\$: The location of the read head.
* \$q\_\alpha : Q\$: The current state.
For a Turing machine the *transition* function takes the condition of a machine at step \$\alpha\$ and tells us the state of the machine at step \$\alpha + 1\$. This is done using the transition function \$\delta\$. We call the function \$\delta\$ with the current state and the symbol under the read head:
\$
\delta\left(q\_\alpha, \xi\_\alpha\left(k\_\alpha\right)\right)
\$
If this does not yield a result, then we consider the machine to have *halted* at step \$\alpha\$, and the condition remains the same. If it does yield a result \$\left(q\_\delta, s\_\delta, m\_\delta\right)\$ then the new state at \$\alpha+1\$ is as follows:
* \$\xi\_{\alpha+1}(k) = \begin{cases}s\_\delta & k = k\_\alpha \\ \xi\_\alpha(k) & k \neq k\_\alpha\end{cases}\$ (That is the tape replaces the symbol at the read head with the symbol given by \$\delta\$)
* \$k\_{\alpha+1} = k\_\alpha+m\_\delta\$ (That is the read head moves left right or not at all)
* \$q\_{\alpha+1} = q\_\delta\$ (That is the new state is the state given by \$\delta\$)
Additionally we define the condition of the machine at time \$0\$.
* \$\xi\_0(k)=0\$ (Tape is all zeros to start)
* \$k\_0=0\$ (Read head starts a zero)
* \$q\_0=q\_s\$ (Start in the initial state)
And thus by induction the state of a Turing machine is defined for all steps corresponding to a natural number.
## Infinite Ordinals
In this section I will introduce the concept of transfinite ordinals in a somewhat informal context. If you would like to look up a more formal definition this explanation is based of of the Von Neumann definition of ordinals.
In most contexts when talking about the order of events we use natural numbers. We can assign numbers to events such that events with smaller numbers happen earlier. However in this challenge we will care about events that happen after an infinite number of prior events, and for this natural numbers fail. So we will introduce *infinite ordinals*.
To do this we will use a special function \$g\$. The \$g\$ function takes a set of numbers and gives us the smallest number greater than all the numbers in that set. For a finite set of natural numbers this is just the maximum plus 1. However this function is not defined on natural numbers alone. For example what is \$g(\mathbb{N})\$, or the smallest number greater than all naturals. To create our ordinals we say
* \$0\$ exists and is an ordinal.
* If \$X\$ is a set of ordinals then \$g(X)\$ exists and is an ordinal.
This gives us the natural numbers (e.g. \$1 = g(\{0\})\$, \$2 = g(\{1\})\$ etc.) but also gives us numbers beyond that. For example \$g(\mathbb{N})\$, this is the smallest infinite ordinal, and we will call it \$\omega\$ for short. And there are ordinals after it, for example \$g(\{\omega\})\$ which we will call \$\omega + 1\$.
We will in general use some math symbols \$+\$, \$\times\$ etc. in ways that are not defined explicitly. There are precise rules about these operators, but we will just use them as special notation without definition. Hopefully their use should be clear though. Here are a few specific ordinals to help you out:
\$
\begin{eqnarray}
\omega\times 2 &=& \omega+\omega &=& g(\{\omega + x : x\in \mathbb{N}\})\\
\omega^2 &=& \omega\times\omega &=& g(\{\omega \times x + y : x\in \mathbb{N}, y\in \mathbb{N}\})\\
\omega^3 &=& \omega\times\omega\times\omega &=& g(\{\omega^2\times x+\omega\times y + z : x\in \mathbb{N}, y\in \mathbb{N}, z\in \mathbb{N}\})\\
\omega^\omega &=& & & g(\{\omega^x\times y + z : x\in \mathbb{N}, y\in \mathbb{N}, z < \omega^x\})\\
\end{eqnarray}
\$
If an ordinal is not the successor of another ordinal, meaning there is not a next smaller ordinal, we call that ordinal a *limit ordinal*. For example \$\omega\$, \$\omega\times3\$, and \$\omega^{\omega\times 2}+\omega^6\times 4\$ are all limit ordinals. \$3\$, \$\omega\times 5 + 12\$ and \$\omega^{\omega^\omega}+1\$ are not. Some authors will specify further that 0 is not a limit ordinal, we will be explicit about 0 when we talk about limit ordinals to avoid confusion.
## Infinite Time Turing Machines
A classical Turing machine is equipped with a start status, and a way to get from one status to another. This allows you to determine the status of the machine at any finite step.
Infinite time Turing machines extend classical Turing machines to have a defined status non-zero *limit ordinals* as well. That is ordinals as defined above which are not the successor of any previous ordinal. This addition makes the condition of the machine defined at transfinite time as well.
### Formal definition
For this we add an additional object to the machine's definition
* \$q\_l : Q\$: The limit state
And we define the condition of the machine at some limit ordinal \$\lambda\$ to be
* \$\xi\_\lambda(k) = \limsup\_{n\rightarrow \lambda} \xi\_n(k)\$
* \$k\_n = 0\$
* \$q\_n = q\_l\$
\$\$
# Example
Here we have a diagram of a long running 2-state machine:
[](https://i.stack.imgur.com/SVeFg.png)
If we want to calculate how long this takes to halt we can't just throw it into a computer and run it, rather we have to determine it by hand.
To start we follow the machine through it's normal execution. It starts at \$q\_1\$ and we can see that from there it *always* moves to \$q\_2\$ flipping the cell under the read-write head. So here it turns the
cell on.
Then since the cell is on it will transition back to \$q\_1\$, turning the cell off and moving to the right. This puts us in the exact same condition as the start, except the read-write head has advanced by 1.
So it will continue in this loop of flipping on bit on and off and moving to the right endlessly.
[](https://i.stack.imgur.com/2Rp68.gif)
Now that we have determined the behavior of the machine for all finite steps we can figure out the state at step \$\omega\$.
Each cell is on for at most 1 step, before being turned off, and then it is never on again.
So the limit supremum of each cell is \$0\$, and at step \$\omega\$ the tape is entirely empty.
So this means that after \$\omega\$ the machine just repeats its exact behavior, the condition at step \$\omega+n\$ is the same as the condition at step \$n\$.
And this persists even after we hit another limit ordinal, \$\omega+\omega\$, the tape remains blank and just repeats the same behavior over and over.
[](https://i.stack.imgur.com/E9D96.gif)
So we now have an accurate description of the machine for states of the form \$\omega\times n + m\$, and it doesn't halt for any of those steps.
It just repeats the same infinite pattern an infinite number of times.
So now we can look at the step after all the steps we have described.
We take the next limit ordinal:
\$
g(\{\omega\times n + m : n\in \mathbb{N}, m \in \mathbb{N}\}) = \omega\times\omega = \omega^2
\$
Your first instinct might be that the tape will be completely empty again, since it was empty at every step \$\omega\times n\$.
However with infinities instincts can be misleading, so we should look at the definitions carefully instead.
In order for a cell to be zero it must converge to zero.
Since the only possibilities are zero and one, this means that for each cell there must be some step \$x\$ after which that cell is always zero.
Previously since each cell was only turned on once that step was just the step after it was turned off.
Now if such a step were to exist for a cell \$k\$ it would be of the form \$\omega\times n + m\$, however we know that the cell will be turned on again some time during the \$\omega\times(n+1)\$ iteration.
In fact it will be turned on at exactly step \$\omega\times(n+1) + 2k + 1\$.
So no cell (with a non-negative index) will converge to a stable value.
Meaning that by the limit supremum all non-negative cells will be on at time \$\omega^2\$.
So here we finally get some new behavior.
With cell 0 on, the machine transitions to \$q\_2\$ turning the cell off, and since \$q\_2\$ doesn't have a transition for off cells the machine halts.
This gives us a total of \$\omega^2+1\$ steps until halting.
[Answer]
# 5 states, \$\omega^{\omega\cdot2}+\omega\cdot2+1\$
| State | Tape | Next State | Write | Move |
| --- | --- | --- | --- | --- |
| Init | 0 | Lseek | 1 | Left |
| Init | 1 | Rtest | 0 | Left |
| Lseek | 0 | Rseek | 1 | No |
| Lseek | 1 | Lseek | 1 | Left |
| Rtest | 0 | Halt | - | - |
| Rtest | 1 | Rseek | 0 | Right |
| Rseek | 0 | Lclear | 1 | No |
| Rseek | 1 | Rseek | 0 | Right |
| Lclear | - | Lclear | 0 | Left |
# Visualization
```
# 0
|
...00000000...
▲ Init
...00010000...
▲ Lseek
...00110000...
▲ Rseek
...00010000...
▲ Rseek
...00000000...
▲ Rseek
...00001000...
▲ Lclear
...00000000...
▲ Lclear
.
.
.
# omega
|
...00000000...
▲ Init
.
.
.
# omega*2
|
...00000000...
▲ Init
.
.
.
# omega^2
|
...00111000...
▲ Init
...00101000...
▲ Rtest
...00100000...
▲ Rseek
...00100100...
▲ Lclear
...00100000...
▲ Lclear
...00100000...
▲ Lclear
...00100000...
▲ Lclear
...00000000...
▲ Lclear
.
.
.
# omega^3
|
...00111100...
▲ Init
.
.
.
# omega^4
|
...00111110...
▲ Init
.
.
.
# omega^omega
|
...00111111...
▲ Init
...00101111...
▲ Rtest
...00100111...
▲ Rseek
.
.
.
# omega^omega+omega
|
...00100000...
▲ Init
...00110000...
▲ Lseek
...00110000...
▲ Lseek
...01110000...
▲ Rseek
...00110000...
▲ Rseek
...00010000...
▲ Rseek
...00000000...
▲ Rseek
...00001000...
▲ Lclear
...00000000...
▲ Lclear
.
.
.
# omega^omega*omega == omega^(omega+1)
|
...001111111...
▲ Init
...001101111...
▲ Rtest
.
.
.
# omega^(omega+1) + omega
|
...001100000...
▲ Init
.
.
.
# omega^(omega*2)
|
...111111111...
▲ Init
.
.
.
# omega^(omega*2) + omega
|
...111100000...
▲ Init
...111110000...
▲ Lseek
...111110000...
▲ Lseek
.
.
.
# omega^(omega*2)+ omega*2
|
...111110000...
▲ Init
...111100000...
▲ Rtest
HALT
```
# 4 states, \$\omega^\omega+\omega+1\$
| State | Tape | Next State | Write | Move |
| --- | --- | --- | --- | --- |
| Init | 0 | Ltest | 1 | Left |
| Init | 1 | Rseek | 0 | Left |
| Ltest | 0 | Rseek | 1 | Right |
| Ltest | 1 | Halt | - | - |
| Rseek | 0 | Lclear | 1 | No |
| Rseek | 1 | Rseek | 0 | Right |
| Lclear | - | Lclear | 0 | Left |
## Visualization
```
|
...00000000...
▲ Init
...00010000...
▲ Ltest
...00110000...
▲ Rseek
...00100000...
▲ Rseek
...00101000...
▲ Lclear
...00100000...
▲ Lclear
...00100000...
▲ Lclear
...00000000...
▲ Lclear
.
.
.
# Omega
|
...00000000...
▲ Init
.
.
.
# Omega*2
|
...00000000...
▲ Init
.
.
.
# Omega*Omega
|
...00111000...
▲ Init
...00101000...
▲ Rseek
...00100000...
▲ Rseek
...00100100...
▲ Lclear
...00100000...
▲ Lclear
...00100000...
▲ Lclear
...00100000...
▲ Lclear
...00000000...
▲ Lclear
.
.
.
# Omega*Omega + Omega
|
...00000000...
▲ Init
.
.
.
# Omega*Omega*2
|
...00111000...
▲ Init
.
.
.
# Omega*Omega*3
|
...00111000...
▲ Init
.
.
.
# Omega*Omega*Omega
|
...00111100...
▲ Init
...00101100...
▲ Rseek
...00100100...
▲ Rseek
...00100000...
▲ Rseek
...00100010...
▲ Lclear
...00100000...
▲ Lclear
...00100000...
▲ Lclear
...00100000...
▲ Lclear
...00100000...
▲ Lclear
...00000000...
▲ Lclear
.
.
.
# Omega^Omega
|
...00111111...
▲ Init
...00101111...
▲ Rseek
...00100111...
▲ Rseek
...00100011...
▲ Rseek
...00100001...
▲ Rseek
.
.
.
# Omega^Omega + Omega
|
...00100000...
▲ Init
...00100000...
▲ Ltest
HALT
```
] |
[Question]
[
[Sandbox](https://codegolf.meta.stackexchange.com/a/22278/80214)
Given a boolean matrix representing my grass field, sheep length \$n\$ and wool thickness \$k\$, you will have to count my sheep.
A sheep is a single independent unbroken line of sheep length \$n\$ and thickness \$k\$.
```
#|##|# | #
#| | #|#
```
are all valid sheep for \$n=2,k=1.\$
```
##|###|## | ##
##|###| ## | ##
##| | ##|##
```
are all valid sheep for \$n=3,k=2.\$
The diagonal sheep must be composed of horizontal lines of length k.
you are to count occurrences of valid sheep across a given grid.
Sheep will not intersect.
You will be guaranteed that \$n,k≥1\$ and \$n ≠ k.\$
so for \$n=2,k=1\$:
```
##
#
## #
```
should give 3.
Sheep may be right next to each other, and smaller animals may be present in the grid. You should get the max number of sheep that can be recognized from the grid.
Since the grass becomes really short after the sheep graze, your code must be short as well ([code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")).
## I/O
You may take the field in any way you like (2D array, string, boolean matrix, so on)
Output must be a single integer ≥ 0.
## Test Cases
`n=3, k=1`
```
# #
# ### #
#
#
#
#
```
`Output: 3`
---
`n=1,k=4`
```
####
####
#
#
####
```
`Output: 3`
---
`n=3, k=1`
```
# #
##
###
#
#
```
`Output: 2`
---
`n=2, k=5`
```
###
###
###
###
###
###
```
`Output: 1`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~66~~ 55 bytes
```
ZQ€Ƒȧ)Ẏ+€4ḶB¤fƑƇƊṆ)Ạ
ḶŒp,U;Ä,_@\€ƊƲ+þẎfƑƇŒPŒcÇaẎQƑ$ƲƇẈṀ
```
[Try it online!](https://tio.run/##dZLPSsNAEMbveYqgvUgDuskmWotQfAHtwYPGIOI/rEWKtAdvVcRIBaE5eVDwIBSkXnIIpkIPCVl8jc2LxN1kNoSSXPY3O/vtfJnJds663dskOWjH91My/pus0NlLncWY/njbwec5GRObjKj/yA4@JJaMnJ6y1wwflKPWIb8zIm49nLNbqTRydiPnJLSPWaJNxjXiEpvOnqg/TKj/3VqNHOq/smt8w@NpGn/R3@f4br4s7xOXn4STTFiLh2/XW2xR5KsMFzeXpzwKvHTZGfR7g/6mHA/fm0tSaLNqHVYo8AIvSUzJNDVFRpYimyaCgHGDU1VkFYiBOtAApjpWQOPEoNOBBqdlKVJaGi96qEANiBdqrxc9GBvgoYOHDh5a7pVR5A3wLusPL/SnQR9qsR8NdBj2Oj/PaopRVPajQr7EA5V5YchjyBc8Ue6dUfSLgGo@h7xfterbMFAHGsX/jWDG/J4QIKOim6oX0RD6NREIZVazZACZlAfiBOWz4g9Isv4B "Jelly – Try It Online")
A pair of links that takes a left argument of `[n,k]` and a right argument of the 1-indexed coordinates of the cells containing the hashes. Returns an integer with the maximal number of sheep that can be found.
The intersecting diagonals as seen in the third example make this quite a bit harder. Removing this requirement [saves 26 bytes](https://tio.run/##dZIxS8NAGIb3/Iqg3TzQu1yitQj9B@rgIDG4VMVapEg7uEURIgpCMznoLEhdOgRToUNC7n9c/ki8y30XQkmWPN/dvfnevF9ueDEa3RcF/42ycIxOeukTOu@f5Y9z9sIWW@mKL98u2YwFWXgkymM267CAL5957Bc8/ulvZyGP34VcLmQ9L@tv/veaP6w2zVO2kCfplxJ2cv/j9kA8kHmjcHV3PZBVEpWPw@lkPJ3sm7n/2dsw0kB0G4pGSZREReEarmshE3vIdF0MheCeJEEmAVKgDXSApU40sCQp6GygI@l5yChb03UPArSAdK33bt1DsAseNnjY4GFVXop63wHvpnx0LZ8FOUg9jwU6CmtbnqueehSteQjsN3jgJi8K@xT2a5648lbUeTGQVHOo8pK2b6NAG@jU/zeGGcv3tAA7LWnabkRX63d0oZWqZ8MAlFQW@gRXs5IXyPD@AQ).
## Explanation (outdated)
### Helper link
Takes a pair of sheep and checks whether they intersect
```
.ịⱮ | Last and first list member of each sheep
Ẏ | Tighten (merge outer lists)
œc3 | Combinations of length 3
Ʋ€ | For each combination:
_Ṫ | - Subtract the last one from each of the first two
¥/ | - Reduce using the following:
U× | - Reverse x and y for left hand item and then multiply by right
>/ | - Reduce using greater than
s2 | Split into lists of length 2
I | Increments (vectorises)
Ȧ | Any and all
```
## Main link
```
Ḷ | [0..n-1], [0..k-1]
Œp | Cartesian product of these
Ʋ | Following as a monad f(z)
,U | - Pair z with reversed pairs of z
; Ɗ | - Concatenate to the following applied to z:
Ä | - Cumulative sum of each member of z
,_@\€ | - Paired with cumulative subtraction of each member of z with reversed arguments
+þ | Outer sum with right hand argument (grid of sheep coordinates)
Ẏ | Tighten -> list of all potential sheep
fƑƇ | Keep those where all coordinates are in the original list
ŒP | Power set
ƒ€“” | Reduce each list starting with an empty list on the left:
ʋ? | - If:
¥€ | - For each current sheep in list:
, | - Pair with potential new sheep
Ç | - Call helper link to check if they intersect
o | - Or:
fƇ | - Filter any current sheep that contain an overlapping coordinate
Ẹ | - Any of the above
¹ | - Then: identity function (i.e. don’t append new sheep)
ṭ@ | - Else: tag new sheep to end of list
Ẉ | Lengths of lists of sheep
Ṁ | Max
```
[Answer]
# Python3, 629 bytes:
```
lambda b,n,k:max(map(len,F({r for x,R in E(b)for y,_ in E(R)for r in S(b,x,y,n,k)})))
E=enumerate
def S(b,x,y,n,k):
q=[(x,y,[],r,w,h)for r,w,h in[(0,n,k),(0,k,n),(1,k,n),(-1,k,n)]]
while q:
x,y,C,r,w,h=q.pop(0)
if h==0:yield tuple(C);continue
if x<len(b)and 0<=y and y+w<=len(b[0])and all(b[x][y:y+w]):q+=[(x+1,y+r,C+[(x,y+i)for i in range(w)],r,w,h-1)]
O=lambda x,y:any(t[0]==T[0]and t[1]>T[1]for t in x for T in y)and any(t[0]==T[0]and t[1]>T[1]for t in x for T in y)
def F(s,c=[]):
if[]==(o:=[i for i in s if all({*j}&{*i}==set()for j in c)and 0==any(O(j,i)for j in c)]):yield c
for i in o:yield from F(s-{i},c+[i])
```
[Try it online!](https://tio.run/##lVNNb@IwED2vf8WoSIvduBWBfqyy9V6q9thKXW5pVCXgLKbBCcYIIsRvZz02W1qVHjZS7Jl5855nxknT2kmtBz8asyvF867KZ8U4h4Jr/prM8jWd5Q2tpOb3dGOgrA2s@RMoDXe0YOi2/CW4T9416PymBV/zFjXYljFG7oTUy5k0uZVkLMsPCQmBuUgpumnGDV/xSVBCy6mltOfzuNtfuXZ7vN/PgpFlBFYTVUmYOy1AodugI@bnTd3QHnNhVcJEiF7SKlmNwS6bStJb9nNUa6v0UoaM9Y1r1TWW6zH0bkQLaLTR6kb4eNrLPJRXlXPWWdomDsxYMo@wgyjmbWT4beS7iZRvQ@FATK7/SLpi@/7OYpaRR7GftctNct1S6@SFGLoVz7BpnP0augVFLIqs/fiHaLahjP8lgR/@PV3wkUgznLwqU0endSJSBW/lLnAW2OTmdLr9vjlVWyEW0lLf0BQzRmFEQmANj3TK1XvMSYcxj8hBtN7HSlPPsIazjdryUZSqjO2KGAScnJyQjnsAOsQtgBYQjBb9d7DPQDR4Ps29JIQh4IE2eKOhEoIhrRPgi38wBCYBVOugASEWOMcNL3H5oe49HooIVgh0PlkHgte5EvtCXIW@I@IrCYUQOEzi@u28oy9ieMe2finq3Izdt5yQb0bapdGQpkpbOhWi2@kerktlhzsqVWWloQ@1lhyK80VTKUu7z7rL3AdLGoP8kh7EY8b7PHY/@Geoz/iA949Cg69ZF8g6Dl0yHvOLo9DV16xrPOuSsd1f)
] |
[Question]
[
You will be given a point `(x,y)` relative to the center of the [Ulam spiral](https://en.wikipedia.org/wiki/Ulam_spiral) (the center being the point which represents one), and length `z`. The task is to check whether there exists a path from `(0,0)` to `(x,y)` of length `z`, assuming prime numbers are obstacles and each turn in path has an angle of 90 degrees. Path may not overlap with itself. `(x,y)` may not be a prime.
Examples of valid paths:
```
XXXX
XX
X
X
XXXXXXXX
```
```
XXXXXX
XXXXX
```
```
XXXXXXXXXXXXXX
X
X
X
XXXXXXX
```
Examples of invalid paths:
```
XXXXXXXXXXXX
XXXXX
```
```
XXXXX XXXXXX
X X
X
```
```
XXX
X
X
XXXXXXXXXXX
```
```
X
X
XXXXXXX!XXX
X X
XXXX
The path above overlaps in a place marked with !.
```
For the record, this is a fragment of a Ulam spiral with `1 (0,0)` marked:
```
............#...#.......#...#
.#...#...........#.#.....#...
#.#.....#.#.....#.....#......
.........#...........#...#...
....#...#.......#.....#......
...#.........#...#.#...#.#.#.
......#.....#.........#.#...#
.#.....#...#.#...............
..............#.#.....#...#..
...#...#.#...#.......#...#.#.
..............#.#...#........
.....#...#.#.....#.#.#.....#.
#.#.#.#.#.#.#...#.......#....
.............#.#.#...........
........#...#.1##.#.#.#...#.#
.#.......#.#.#...............
..........#...#..............
...#.#...#.#...#...#.#...#...
..#...#...#.....#.....#.#...#
...........#...........#.....
......#.#.....#...#...#......
...#...#...........#.......#.
....#.....#...#.#............
.........#.#...#.....#...#...
#.#.#.........#.#.....#.....#
.#...#...........#.#.........
#.#.....#.....#...#.#........
.......#.........#.......#...
........#.#...#.#.........#..
```
## I/O examples
```
Input: (5, -1), 7 - true
Suggested path:
1##.#.#.#...#.#
XXXXXX.........
#..............
Input: (3, 0), 6 - true
Suggested path:
.#.#.#...........
#.1##X#.#.#...#.#
.#XXXX...........
Input: (-2, -1), 18 - true
Suggested path:
...#...#.#...#.......#...#.#.
..............#.#...#........
.....#...#.#.....#.#.#.....#.
#.#.#.#.#.#.#...#.......#....
.............#.#.#...........
........#...#.1##.#.#.#...#.#
.#.......#.#X#XX............
..........#.XX#XX............
...#.#...#.#.XX#XX.#.#...#...
..#...#...#...XX#X....#.#...#
...........#...XXX.....#.....
Input: (2, 1), 6 - false
Input: (-5, 2), 20 - true
Input: (-1, 0), 5 - false
```
## Additional considerations
`abs(x) <= 20` and `abs(y) <= 20` cases have to be resolved within the TIO time limit (soft bound; 60s) to verify validity of the answers.
The answers have to (theoretically and ideally) work on any reasonable input.
[Answer]
# JavaScript (ES6), 169 bytes
*Saved 1 byte thanks to @att*
Expects `(z)(x,y)`. Returns *false* if there's a solution or *true* otherwise.
```
z=>F=(X,Y,i=z,k)=>--i?[-1,0,1,2].every(d=>(g=d=>n%--d?g(d):d==1)(n=(k=2*Math.max(x=X+d%2,-x,y=Y+~-d%2,-y))*k-~(-y<x?y-k-x:k+x-y))|F[k=[x,y]]||F(x,y,i,F[k]=1)|--F[k]):X|Y
```
This is fast enough for all existing test cases, but I guess it's likely to time out on some other ones.
[Try it online!](https://tio.run/##hY5Ba4NAEIXv/RV7CczGGaNbbIt09Oatd0U8SFat1WrRNGiQ/HW7CaWHQOhleO/x8TEf@TEf90P9daCu18Va8nriIGKIMcGaT9hIDojqMCUXHXRRZXZxLIYZNAdQsbndhkiHFWjpa2ZXQsfQsNq@5Yd3@zOfYOLY0huFNOHMiXWma5ml3DZ0Bppfp3Cmhia/sabLvERpw6mBs2xZIjABazRbZuQL0SVJP16Sdd93Y98WdttXUIJ4liA8JFdKsduJw/BdPNwQT4Z4ROHcJdwXCaT@dSgUv0SZt@Mtohwj8VCo@xLPEO7fI1fJ@gM "JavaScript (Node.js) – Try It Online")
### Commented
NB: the spiral formula is similar to the one I used [in my answer](https://codegolf.stackexchange.com/a/168960/58563) to [Spiral neighbourhoods](https://codegolf.stackexchange.com/q/168949/58563).
```
z => // outer function taking z
F = ( // main recursive function taking:
X, Y, // (X, Y) = current position
i = z, // i = move counter initialized to z
k // k = local variable whose initial value is ignored
) => //
--i ? // decrement i; if it's not equal to 0:
[-1, 0, 1, 2].every(d => // for each direction d:
( g = d => n % --d ? g(d) // g is a recursive primality test function
: d == 1 // which is invoked ...
)( //
n = // ... on the 1-indexed square ID n defined as:
( k = 2 * Math.max( // k² + (k + x - y) * s + 1
x = X + d % 2, -x, // with:
y = Y + ~-d % 2, -y // x = X + dx
) // y = Y + dy
) * k - // k = 2 * max(|x|,|y|) = 2 * max(x,-x,y,-y)
~(-y < x ? y - k - x // s = -1 if -y < x or 1 otherwise
: k + x - y) //
) // abort if n is prime
| F[k = [x, y]] // or (x, y) was already visited
|| F(x, y, i, F[k] = 1) // otherwise mark (x, y) as visited and do a
// recursive call with the new position
| --F[k] // clear the mark afterwards
) // end of every()
: // else:
X | Y // falsy if and only if X = Y = 0
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 117 bytes
```
(a=0;Do[g@a=b;a-=I^⌈2√b⌉,{b,8#^2}];1!=##2&&!PrimeQ@g@#2&&If[#<2,0==#2,Or@@#0[#-1,#2+I^i,##2]~Table~{i,4}]&@##)&
```
[Try it online!](https://tio.run/##NYzBisIwGITvfYvyQ3DxDyT/WhVqJIe99OQu6620kEqrBatQegvp2QWfwMfri3RTxdPMfMxMY7pT2ZiuPpixUuPMKBF/XdOjNqqIDVdJPtxvNNwexXD/Q1vgGnJyWSxDBUCMhd9t3ZQ/@qinlFQpbAiFUkC4a7UGkQKXCDRP8hr9Iuv3pjiXva1x4TKmAT7Y6D8unS9uK7/IWP97MJfeBnaFEU8cBnaJn5PINXJ6E385GRLIozk9fYRcPhm@ShKFC9z4Dw "Wolfram Language (Mathematica) – Try It Online")
Input \$z\$ and a complex number \$x+iy\$.
```
1!=##2&&!PrimeQ@g@#2 (* check if the current path is valid *)
&&If[#<2,0==#2 (* if the length is reached, check if the endpoint is the origin *)
Or@@#0[#-1,#2+I^i,##2]~Table~{i,4}]& (* otherwise, check if any child paths succeed *)
(a=0;Do[g@a=b;a-=I^⌈2√b⌉,{b,8#^2}]; % &@##)& (* cache indices of a sufficiently large spiral first. *)
```
---
### 110 bytes
```
1!=##2&&!PrimeQ[b=1;0//.a_/;a!=#2:>a-I^⌈2√b++⌉;b]&&If[#<2,0==#2,Or@@#0[#-1,#2+I^i,##2]~Table~{i,4}]&@##&
```
[Try it online!](https://tio.run/##NY3BCoJAFEX3fkUyMFS@yZlXVmSKW1cVtROLMZSEbBHuBl0b@AV9nj9iI9XqwT33nlfI8pYWssyvss@8XpgeIUipuX/mRXqIEk@43LZn8mK7UjPc@JKF565tsGveiWV17ctNYkrDLCJbBO7pDuyeQUB4RJgAglZ4zkFL4/okk3taqxwWVUwDQmivvzxK3fMzPYhpfbzKR60MtQKHhRUYaglzfcbTkRJrYDiEo@lkyLX3R5ADcyz8IweYGKYIX4UAXhlV/wE "Wolfram Language (Mathematica) – Try It Online")
Same principle, but takes much longer without cached spiral indices.
] |
[Question]
[
Create three programs, which we'll call Rock, Paper, and Scissors.
Each program must be unique, and accept input.
If a program gets any input which is not one of the programs Rock, Paper or Scissors, it must print itself.
[RPS](https://en.wikipedia.org/wiki/Rock_paper_scissors) style, the programs will each print one of the following four outputs:
1. "win" if the running program beats the program that is being input
2. "lose" if the running program loses against the program that is being input
3. "tie" if the input is equal to the source code of the running program
4. The source code of the running program itself for any other input (including an empty input)
General rules:
* The three programs can be in any language. Rock can be in a different language from Paper: same for any other pair.
* They are not restricted by size.
* They must print through STDOUT or closest equivalent, and must print strings or closest equivalent. They must not print to STDERR.
* They need not be full programs. They can be functions, if you wish to get rid of the stuff needed in a program, like C's #includes.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, where your score is determined by the sum of the programs' sizes. The person with the lowest score wins.
If two people have the same score, the person whose largest program by bytes out of the set Rock, Paper, Scissors is smaller wins.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~273, 489,~~ 429 bytes
Rock:
```
r=['tie', 'lose', 'win'];s="i=input();t=[f'r={r[n:]+r[:n]};s={s!r};exec(s)'for n in[0,1,2]];print(i in t and r[i.find('t')//7]or t[0])";exec(s)
```
[Try it online against itself!](https://tio.run/##zY5BCsJADEWvMnaTGSy26kLoMCcJWYhtMSBpyaSolJ69FsE7uPrwef/xx7fdBzmvqyYE4w5KB48hf/PJAhRzKjixjJP5EC1hD5pmRWlor9gILRsx550usXt1N58D9IM6cSxYl8fyRBRHZTHPW@XMXaV1inzoWVoPBqGqLrQtDGsKxU/yd4c@ "Python 3 – Try It Online")
[Try it online against Paper!](https://tio.run/##xc5BCsIwEAXQq8RuJsFiqy6EhpxkyEJsiwMyLZMRldKz16gI3sDVwGf@540PPQ@8XxYJCEodlAYuQ3rfGzFEn0JBgXi8qnVeA/YgYRLkJq4FG45z/pjSSmbf3buTTQ76QQwbYqzLbbmL0Y9CrJZyZNQcuTWCtOmJWwsKrqoOMTcU6@iK78gH9BJkyK/rX6An "Python 3 – Try It Online")
[Try it online against Scissors!](https://tio.run/##xY5BCsIwEEWvEruZBIutuhAacpIhC7EtDsi0TEZUSs9eoyJ4A1cPPv9/3vjQ88D7ZZGAoNRBaeAypDdvxBB9CgUF4vGq1nkN2IOESZCbuBZsOM65MaWVzL67dyebHPSDGDbEWJfbchejH4VYLeXIqDlyawRp0xO3FhRcVR1iXijW0RXfk4/Qr0nGy@9fQk8 "Python 3 – Try It Online")
[Try it online against rubbish!](https://tio.run/##NY7BCsIwEER/JfayCRZb9SA05EvCHqxt6YJsy2aLSum31yB4GhjePGb@6Djxdd8lRFDqoTTwnNIvX8SAPoWCAvG8qHVeQxxAwiqRGzxKbBi3TKzpIJvv3/3DJgfDJIYNcazLc3lB9LMQq6VcGTV37oxEOg3EnQUFV1U3zAuNNbriL8mHlralNH4B "Python 3 – Try It Online")
Paper:
```
r=['win', 'tie', 'lose'];s="i=input();t=[f'r={r[n:]+r[:n]};s={s!r};exec(s)'for n in[0,1,2]];print(i in t and r[i.find('t')//7]or t[0])";exec(s)
```
[Try it online against itself!](https://tio.run/##zY5BCsIwEEWvEt1MgsVWXQgNOckwC7EpDsi0TEZUSs9e68I7uPrwef/xx7fdBjktiyaEJwtUDozzN@5DyUCxpC0nlvFhPkRL2IOmSVFa2im2QvNKTGWjc8yvfPUlQD@oE8eCTXWojkRxVBbzvFbO3EU6p8j7nqXzYBDq@kzrwrChsP1J/u7QBw "Python 3 – Try It Online")
[Try it online against Scissors!](https://tio.run/##xc5BCsIwEAXQq8RuJsFgqy6EhpwkZCE2xQGZlsmISunZa1QEb@Bq4DP/88aHnAfaLwv7ADcksAoE0@tchpwguuwr9EjjVbRx4kMP7CcO1MY1h5biXD6mvOLZpXs66WygH1iRQgqN3dpdjG5kJNFYIiXqSJ3igJseqdMgYOr6EEtDQhNN9R35gN6EQvmB/Qv0BA "Python 3 – Try It Online")
[Try it online against Rock!](https://tio.run/##xY5BCsIwEEWvEruZBIOtuhAacpKQhdgUB2RaJiMqpWevKSJ4A1cPPv9/3viS60DHZWEf4IEEVoFgWnEbcoLosq/QI4130caJDz2wnzhQG7ccWopzaUx5w7NLz3TR2UA/sCKFFBq7t4cY3chIorFEStSZOsUBdz1Sp0HA1PUploWEJprqe/IR@jUpXP3@JfQG "Python 3 – Try It Online")
[Try it online against garbage!](https://tio.run/##NYxBCsIwEEWvEruZBIOtuhAacpKQRbVpHZBpmYyolJ491oWrD4/3/vyR@0TnUtgHeCGBVSCYfvOYcoLosq/QI81P0caJDwOwXzhQG/ccWorrZix5x6tL73TT2cAwsSKFFBp7tKcY3cxIonFDSlRHveKAhwGp1yBg6voSt0JCE031Pyll7PjajekL "Python 3 – Try It Online")
Scissors:
```
r=['lose', 'win', 'tie'];s="i=input();t=[f'r={r[n:]+r[:n]};s={s!r};exec(s)'for n in[0,1,2]];print(i in t and r[i.find('t')//7]or t[0])";exec(s)
```
[Try it online against itself!](https://tio.run/##zY5BCsIwEEWvEt1MgsVWXQgNOckwC7EpDsi0TEZUSs9e68I7uPrwef/xx7fdBjktiyaE@1AyVA6eLN8wzkCxpC0nlvFhPkRL2IOmSVFa2im2QvNKTGWjc8yvfPUlQD@oE8eCTXWojkRxVBbzvFbO3EU6p8j7nqXzYBDq@kzrwrChsP1J/u7QBw "Python 3 – Try It Online")
[Try it online against Rock!](https://tio.run/##xc5BCsIwEAXQq8RuJsFgqy6EhpwkZCE2xQGZlsmISunZa4oI3sDVwGf@540vuQ50XBb2AW5DTmAVPJDWI5gguuwr9EjjXbRx4kMP7CcO1MYth5biXD6mvOHZpWe66GygH1iRQgqN3dtDjG5kJNFYIiXqTJ3igLseqdMgYOr6FEtDQhNN9R35gFZBgfy6/gV6Aw "Python 3 – Try It Online")
[Try it online against Paper!](https://tio.run/##xY5BCsIwEEWvEruZBIOtuhAacpKQhdgUB2RaJiMqpWevURG8gasHn/8/b3zIeaD9srAPcBlyAqvghvSCYILosq/QI41X0caJDz2wnzhQG9ccWopzaUx5xbNL93TS2UA/sCKFFBq7tbsY3chIorFEStSROsUBNz1Sp0HA1PUhloWEJprqe/IR@hEpeOv9S@gJ "Python 3 – Try It Online")
[Try it online against trash!](https://tio.run/##NYxBCsIwEEWvEruZBIutuhAacpIwi2JTOiDTMhlRKT17rAtXHx7v/eWj08zXUiREeMw5QW3gRfwbpQToc6goEC9Ptc5riCNIWCVyh0eJHeO2G2s@yObTO91tdjDOYtgQx7Y@1xdEvwixWtqRUdPzYCTSaSQeLCi4prnhXmhs0VX/k1JU@jx9AQ "Python 3 – Try It Online")
The same as the previous version, but check that the input exactly matches the source code of one of the programs.
[Try it online (together)!](https://tio.run/##7ZRNbsIwEIX3PoULC8dqCgQWlRL5FF26XqTBUAsYW7b7J8TZ6TgBGrrpkiIhRYr9MvPN81gZ9xVfLcz2TjDG9l5IFo1mOWVrG9r3hwGmqiAGRhhwbzHjVRRywbzYegmluveyBLXDiG2487tKf@omC5wtrKdADchJXuRTpSrnDcTMoEQjrWFOvTSjhYF5xiLj4/GjwowoJ4oPjhCS/CQD6KNv66J@@o05@LqUnz3emSzKh0KNglubmLFnYOjSNivhMJK42mmPy0KR0JgQrA@4mypCumrsqbFeU0HxJBsD2aZ22VpD7mQ5U5xzQob0PdAEJG3NtOJ0SPHUndBWSAq2o1OOhZKYenVgtIHnkPbrOeXE7VMSuoMc1XPOqfQJ80PucxIcOWBpe1M9SD/9V96//Cdufq5rZtz8XM1Mvfn5yw/G2Q1OUQgaH7KoV/owUJe1f6mXmnwD "Python 3 – Try It Online")
# Old (invalid) version
Rock:
```
s="print(['tie','lose','win','s='+repr(s)+';exec(s)',''][input().find('ti')//7-1])";exec(s)
```
Paper:
```
s="print(['win','tie','lose','s='+repr(s)+';exec(s)',''][input().find('ti')//7-1])";exec(s)
```
Scissors:
```
s="print(['lose','win','tie','s='+repr(s)+';exec(s)',''][input().find('ti')//7-1])";exec(s)
```
[Try it online!](https://tio.run/##5dPNcoMgEAfwO0/BJIeFiU1qe@hMMz5Fj9ZDxtIpUwM7YPrx9HaRaKE91kumHhT/wm8RET/7F2tuB6wAYPDVCp02vaih1woK6KwPl3dt6Owr2DiFTni5gb36UC21KIem1gZPvZDbZ22eBI0FudvdXZWNXE39WGJHLquwmJ3NOJb4kz3QutTlPWVbj53uBTwakMzZ9rXC@rpheEDlqFk2zLfae@s83d00jMUpwUNrneIVh4IftRHHA4pOmQKllIyt@ZvnAWNjvdCSfM1p4jEY9ZDQC8VkKhLC8LJnY@yYI@PTXJndVAl0RKY0d@bSM/Mtp07AyTGWj8uajvnROfF/77n46ZbeF5dqn720xL@3s5Ve4B@/WJuOLw "Python 3 – Try It Online")
Three almost identical programs (all with 91 bytes), the only difference is the order of the win/tie/lose, which each program uses the position of the `'tie'` to determine the result from it's own ordering.
As pointed out, these programs are invalid, as they will only print out themselves if the input doesn't contain 'ti' (or the 'ti' is in a certain place).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~67~~ 59 bytes × 3 = score of 177
```
“3ṛṾ;Ṫ,ɠ;µḣ2O_/2ị%3+1×ḣ2a2¦Ɱ3Ṿ€¤ċɗ/$ịṚ“win“lose“tie“1ịv”1ịv
```
[Try it online!](https://tio.run/##y0rNyan8//9RwxzjhztnP9y5z/rhzlU6JxdYH9r6cMdiI/94faOHu7tVjbUND08HCSQaHVr2aOM6oOJ9j5rWHFpypPvkdH0VoJKHO2cBDSnPzAOSOfnFqUCqJBNEGgIlyx41zAXTYJsM6WETAA "Jelly – Try It Online")
A full program that reads a line from STDIN and returns `tie` if given the same program, `win` if given a program against which it can win and `lose` if a program against which it loses. If provided with anything except one of the rock, paper or scissors programs it prints itself.
The digit in second position in the program indicates which it is:
1. Rock
2. Scissors
3. Paper
[Answer]
# Java 10, 1716 (three time 572) bytes
Rock program:
```
interface R{static void main(String[]a){var s="interface R{static void main(String[]a){var s=%c%s%1$c;System.out.print((s=s.format(s,34,s)).equals(a[0])?%1$ctie%1$c:t(s).equals(a[0])?%1$close%1$c:t(t(s)).equals(a[0])?%1$cwin%1$c:s);}static String t(String s){var r=%1$c%1$c;for(int b:s.getBytes())r+=(char)(b==82?80:b==80?90:b==90?82:b);return r;}}";System.out.print((s=s.format(s,34,s)).equals(a[0])?"tie":t(s).equals(a[0])?"lose":t(t(s)).equals(a[0])?"win":s);}static String t(String s){var r="";for(int b:s.getBytes())r+=(char)(b==82?80:b==80?90:b==90?82:b);return r;}}
```
The Paper program is similar, except with both `R` replaced with `P`.
The Scissor program is similar, except with both `R` replaced with `Z` (since `S` is already used in `String`).
*Rock program:*
- [Try it online with itself as input.](https://tio.run/##7ZKxasMwEEB/RYgaJJoaN@3g2AhDP6EZQ4azoqRKY7vVnV1C8Le7kpNuHtrQMZMO7gneg9tDBw/7zfsw2JqM24I27PWEBGQ16xq7YRXYWizJ2Xq3WoM8deAYKv43PNIRRo93Ol8ekUwVNy3FH54hIVBhvG1cBSRw9vQ8Qylj89nCAQWskrUswj@yJjyZZya2hwZ/1gGYIL5sPQIo8/5ie3ZkdJFleHZ1KoCjq7cSXpGVGcY7Qy9HMiikdPdK6DdwUpRKpfMiTbIwJMViHBZJkc6zUubOUOtq5vK@59d0cx/NJ4p5yOXTrdyH8l9Vcv6PfcPtfG7nc33fNw)
- [Try it online with the Paper program as input.](https://tio.run/##7ZLBSsNAEEB/ZVkM7GINsXpIE5aAX1DssfQwSbd1a5PoziRSSr497qYVPOTQijc97cC8hfdgdtDC3W792vemIm03UGj2fEQCMgVra7NmJZhKLMiaartcgTy2YBkqfh0eFAEG9zdFujgg6TKsGwrfHENCoMJwU9sSSODk4XGCUob6vYE9ClhGK5n5f2S0fxLHjGz3NX6tPTBCfJhqAFCm3dn25MjoLMvw5GqVBwdXZyWcIssTDLeang6kUUhpb5UoXsBKkSsVT7M4SvwQZbNhmEVZPE1ymVpNja2YTbuO/6Sbu2g@Usx9Lh9v5S6UX1TJ@S/29d/PZ37d@cz/z@evn88n)
- [Try it online with the Scissor program as input.](https://tio.run/##7ZLBSsNAEEB/ZVkM7GINsXpIE5aAn2BvLT1M0m3d2iS6M4mUkm@Pu2kFDzm04k1POzBv4T2YHbRwt1u/9r2pSNsNFJo9H5GATMHa2qxZCaYSc7Km2i5XII8tWIaKX4cHRYDB/U2Rzg9IugzrhsI3x5AQqDDc1LYEEjh5eJyglKF@b2CPApbRSmb@Hxntn8QxI9t9jV9rD4wQH6YaAJRpd7Y9OTI6yzI8uVrlwcHVWQmnyPIEw62mpwNpFFLaWyWKF7BS5ErF0yyOEj9E2WwYZlEWT5NcplZTYytm067jP@nmLpqPFHOfy8dbuQvlF1Vy/ot9/ffzWVx3Pov/8/nr5/MJ)
- [Try it online with rubbish input.](https://tio.run/##rY/LasMwEAB/RYgaJJoaN@3BsRGGfkJzDDmsFSVV6kerXbuE4G93JSe9@dCGnnZhZ2HmCD08HHfv42gbMm4P2rDXMxKQ1axv7Y7VYBuxJmebw2YL8tyDY6j43/BIRxg93ul8fUIyddx2FH94hoRAhfG@dTWQwMXT8wKljM1nBxUK2CRbWYQ/siaMzDMz16rFn3MAZogv20wAyny42l4cGV1lGV5cnQrg5OqthFdkZYbxwdDLiQwKKd29EvoNnBSlUumySJMsLEmxmpZVUqTLrJS5M9S5hrl8GPgt3dxH85liHnL5fCv3ofxXlZz/Y984jmUF3w)
*Paper program:*
- [Try it online with itself as input.](https://tio.run/##7ZKxasMwEEB/RYgaJJoaN@3g2AhDv6CQMWQ4K0qqNLZb3dklBH@7Kznp5qENHTPp4J7gPbg9dPCw37wPg63JuC1ow15PSEBWs66xG1aBrcWSnK13qzXIUweOoeJ/wyMdYfR4p/PlEclUcdNS/OEZEgIVxtvGVUACZ0/PM5QyNp8tHFDAKlnLIvwja8KTeWZie2jwZx2ACeLL1iOAMu8vtmdHRhdZhmdXpwI4unor4RVZmWG8M/RyJINCSnevhH4DJ0WpVDov0iQLQ1IsxmGRFOk8K2XuDLWuZi7ve35NN/fRfKKYh1w@3cp9KP9VJef/2Dfczud2Ptf3fQM)
- [Try it online with the Scissor program as input.](https://tio.run/##7ZLBSsNAEEB/ZVkM7GINsXpIE5aAXyD01tLDJN3WrU2iO5NIKfn2uJtW8JBDK970tAPzFt6D2UELd7v1a9@birTdQKHZ8xEJyBSsrc2alWAqMSdrqu1yBfLYgmWo@HV4UAQY3N8U6fyApMuwbih8cwwJgQrDTW1LIIGTh8cJShnq9wb2KGAZrWTm/5HR/kkcM7Ld1/i19sAI8WGqAUCZdmfbkyOjsyzDk6tVHhxcnZVwiixPMNxqejqQRiGlvVWieAErRa5UPM3iKPFDlM2GYRZl8TTJZWo1NbZiNu06/pNu7qL5SDH3uXy8lbtQflEl57/Y138/n8V157P4P5@/fj6f)
- [Try it online with the Rock program as input.](https://tio.run/##7ZLBSsNAEEB/ZVkM7GINsXpIE5aAXyDtsfQwSbd1a5PoziRSSr497qYVPOTQijc97cC8hfdgdtDC3W792vemIm03UGj2fEQCMgVra7NmJZhKLMiaartcgTy2YBkqfh0eFAEG9zdFujgg6TKsGwrfHENCoMJwU9sSSODk4XGCUob6vYE9ClhGK5n5f2S0fxLHjGz3NX6tPTBCfJhqAFCm3dn25MjoLMvw5GqVBwdXZyWcIssTDLeang6kUUhpb5UoXsBKkSsVT7M4SvwQZbNhmEVZPE1ymVpNja2YTbuO/6Sbu2g@Usx9Lh9v5S6UX1TJ@S/29d/PZ37d@cz/z@evn88n)
- [Try it online with rubbish input.](https://tio.run/##rY/LasMwEAB/RYgaJJoaN@3BsRGGfkEhx5DDWlFSpX602rVLCP52V3LSmw9t6GkXdhZmjtDDw3H3Po62IeP2oA17PSMBWc361u5YDbYRa3K2OWy2IM89OIaK/w2PdITR453O1yckU8dtR/GHZ0gIVBjvW1cDCVw8PS9Qyth8dlChgE2ylUX4I2vCyDwzc61a/DkHYIb4ss0EoMyHq@3FkdFVluHF1akATq7eSnhFVmYYHwy9nMigkNLdK6HfwElRKpUuizTJwpIUq2lZJUW6zEqZO0Oda5jLh4Hf0s19NJ8p5iGXz7dyH8p/Vcn5P/aN41hW8A0)
*Scizzor program:*
- [Try it online with itself as input.](https://tio.run/##7ZKxasMwEEB/RYgaJJoaN@3g2AhDfyFbQ4azoqRKY7vVnV1C8Le7kpNuHtrQMZMO7gneg9tDBw/7zfsw2JqM24I27PWEBGQ16xq7YRXYWizJ2Xq3WoM8deAYKv43PNIRRo93Ol8ekUwVNy3FH54hIVBhvG1cBSRw9vQ8Qylj89nCAQWskrUswj@yJjyZZya2hwZ/1gGYIL5sPQIo8/5ie3ZkdJFleHZ1KoCjq7cSXpGVGcY7Qy9HMiikdPdK6DdwUpRKpfMiTbIwJMViHBZJkc6zUubOUOtq5vK@59d0cx/NJ4p5yOXTrdyH8l9Vcv6PfcPtfG7nc33fNw)
- [Try it online with the Rock program as input.](https://tio.run/##7ZLBSsNAEEB/ZVkM7GINsXpIE5aAn9DeLD1M0m3d2iS6M4mUkm@Pu2kFDzm04k1POzBv4T2YHbRwt1u/9r2pSNsNFJo9H5GATMHa2qxZCaYSC7Km2i5XII8tWIaKX4cHRYDB/U2RLg5IugzrhsI3x5AQqDDc1LYEEjh5eJyglKF@b2CPApbRSmb@Hxntn8QxI9t9jV9rD4wQH6YaAJRpd7Y9OTI6yzI8uVrlwcHVWQmnyPIEw62mpwNpFFLaWyWKF7BS5ErF0yyOEj9E2WwYZlEWT5NcplZTYytm067jP@nmLpqPFHOfy8dbuQvlF1Vy/ot9/ffzmV93PvP/8/nr5/MJ)
- [Try it online with the Paper program as input.](https://tio.run/##7ZLBSsNAEEB/ZVkM7GINsXpIE5aAX1DozdLDJN3WrU2iO5NIKfn2uJtW8JBDK970tAPzFt6D2UELd7v1a9@birTdQKHZ8xEJyBSsrc2alWAqsSBrqu1yBfLYgmWo@HV4UAQY3N8U6eKApMuwbih8cwwJgQrDTW1LIIGTh8cJShnq9wb2KGAZrWTm/5HR/kkcM7Ld1/i19sAI8WGqAUCZdmfbkyOjsyzDk6tVHhxcnZVwiixPMNxqejqQRiGlvVWieAErRa5UPM3iKPFDlM2GYRZl8TTJZWo1NbZiNu06/pNu7qL5SDH3uXy8lbtQflEl57/Y138/n/l15zP/P5@/fj6f)
- [Try it online with rubbish input.](https://tio.run/##rY/LasMwEAB/RYgaJJoaN@3BsRGG/kJuDTmsHSVV6kerXbuE4G9XJSe9@dCGnnZhZ2HmCAM8HHfvzpmWtN1DpdnrGQnIVGzozI41YFqxJmvaw2YL8jyAZaj43/CoijB6vKvy9QlJN3HXU/zhGRICFcb7zjZAAhdPzwuUMtafPdQoYJNsZRH@yOgwMs/MXOsOf84BmCG@TDsBKPPxantxZHSVZXhxtSqAk6u3El6RlRnGB00vJ9IopLT3SlRvYKUolUqXRZpkYUmK1bSskiJdZqXMrabetszm48hv6eY@ms8U85DL51u5D@W/quT8H/ucc2UN3w)
## Explanation:
**General [quine](/questions/tagged/quine "show questions tagged 'quine'") explanation:**
* The `var s` contains the unformatted source code
* `%s` is used to put this String into itself with `s.format(...)`
* `%c`, `%1$c`, and `34` are used to format the double-quotes
* `s.format(s,34,s)` puts it all together
**Challenge part:**
I've added a separated method `t` which will transliterate the characters `RPZ` once clockwise in all three programs:
```
static String t(String s){ // Method with String as both parameter and return-type:
var r=""; // Result-String, starting empty
for(int b:s.getBytes()) // Loop over the characters of the input-String:
r+= // Append to the result-String:
(char)( // A character with codepoint:
b==82? // If the character is 'R':
80 // Change it to 'P' (codepoint 80)
:b==80? // Else-if the character is 'P':
90 // Change it to 'Z' (codepoint 90)
:b==90? // Else-if the character is 'Z':
82 // Change it to 'R' (codepoint 82)
: // Else:
b); // Leave the character unchanged
return r;} // Return the resulting String
```
When we're printing, it will do the following checks:
```
s.equals(a[0])? // If the program equals the input:
"tie" // Print "tie"
:t(s).equals(a[0])? // Else-if the program transliterated once equals the input:
"lose" // Print "lose"
:t(t(s)).equals(a[0])? // Else-if the program transliterated twice equals the input:
"win" // Print "win"
: // Else:
s // Print the source code-String itself
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~219~~ ~~207~~ 201 (three times ~~73~~ ~~69~~ 67) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Rock program:
```
2"D34çý…·‡§Íް#sª¤¸YF¤₁DÀ‡ª}IQZ_ªÏ"D34çý…·‡§Íް#sª¤¸YF¤₁DÀ‡ª}IQZ_ªÏ
```
Paper program is similar, but with leading `5` instead of `2`.
Scissor program is similar, but with leading `6` instead of `2`.
Similar transliterate approach as [my Java answer](https://codegolf.stackexchange.com/a/196436/52210).
*Rock program:*
- [Try it online with itself as input.](https://tio.run/##yy9OTMpM/f/fSMnF2OTw8sN7HzUsO7T9UcPCQ8sP9x7de2iDcvGhVYeWHNoR6XZoyaOmRpfDDSDJVbWegVHxh1Yd7idX3wBYCQA)
- [Try it online with the Paper program as input.](https://tio.run/##yy9OTMpM/f/fSMnF2OTw8sN7HzUsO7T9UcPCQ8sP9x7de2iDcvGhVYeWHNoR6XZoyaOmRpfDDSDJVbWegVHxh1Yd7idX3///pvS2EgA)
- [Try it online with the Scissor program as input.](https://tio.run/##yy9OTMpM/f/fSMnF2OTw8sN7HzUsO7T9UcPCQ8sP9x7de2iDcvGhVYeWHNoR6XZoyaOmRpfDDSDJVbWegVHxh1Yd7idX3///ZvS2EgA)
- [Try it online with rubbish input.](https://tio.run/##yy9OTMpM/f/fSMnF2OTw8sN7HzUsO7T9UcPCQ8sP9x7de2iDcvGhVYeWHNoR6XZoyaOmRpfDDSDJVbWegVHxh1Yd7idXH9BKUzMA)
*Paper program:*
- [Try it online with itself as input.](https://tio.run/##yy9OTMpM/f/fVMnF2OTw8sN7HzUsO7T9UcPCQ8sP9x7de2iDcvGhVYeWHNoR6XZoyaOmRpfDDSDJVbWegVHxh1Yd7idX3wBYCQA)
- [Try it online with the Scissor program as input.](https://tio.run/##yy9OTMpM/f/fVMnF2OTw8sN7HzUsO7T9UcPCQ8sP9x7de2iDcvGhVYeWHNoR6XZoyaOmRpfDDSDJVbWegVHxh1Yd7idX3///ZvS2EgA)
- [Try it online with the Rock program as input.](https://tio.run/##yy9OTMpM/f/fVMnF2OTw8sN7HzUsO7T9UcPCQ8sP9x7de2iDcvGhVYeWHNoR6XZoyaOmRpfDDSDJVbWegVHxh1Yd7idX3///RvS2EgA)
- [Try it online with rubbish input.](https://tio.run/##yy9OTMpM/f/fVMnF2OTw8sN7HzUsO7T9UcPCQ8sP9x7de2iDcvGhVYeWHNoR6XZoyaOmRpfDDSDJVbWegVHxh1Yd7idX3///RqZmAA)
*Scizzor program:*
- [Try it online with itself as input.](https://tio.run/##yy9OTMpM/f/fTMnF2OTw8sN7HzUsO7T9UcPCQ8sP9x7de2iDcvGhVYeWHNoR6XZoyaOmRpfDDSDJVbWegVHxh1Yd7idX3wBYCQA)
- [Try it online with the Rock program as input.](https://tio.run/##yy9OTMpM/f/fTMnF2OTw8sN7HzUsO7T9UcPCQ8sP9x7de2iDcvGhVYeWHNoR6XZoyaOmRpfDDSDJVbWegVHxh1Yd7idX3///RvS2EgA)
- [Try it online with the Paper program as input.](https://tio.run/##yy9OTMpM/f/fTMnF2OTw8sN7HzUsO7T9UcPCQ8sP9x7de2iDcvGhVYeWHNoR6XZoyaOmRpfDDSDJVbWegVHxh1Yd7idX3///pvS2EgA)
- [Try it online with rubbish input.](https://tio.run/##yy9OTMpM/f/fTMnF2OTw8sN7HzUsO7T9UcPCQ8sP9x7de2iDcvGhVYeWHNoR6XZoyaOmRpfDDSDJVbWegVHxh1Yd7idX3///RqZmAA)
## Explanation:
**General [quine](/questions/tagged/quine "show questions tagged 'quine'") explanation:**
Uses [the default 14 bytes quine program of *@OliverNi*](https://codegolf.stackexchange.com/a/97899/52210), since it's easy to modify (even though there is a [shorter 05AB1E quine](https://codegolf.stackexchange.com/a/186809/52210)).
This quine will:
```
2 # Push a 2 (or 5 or 6 depending on the program used)
"D34çý" # Push the trailing part of the source-code as string
D # Duplicate this string on the stack
34ç # Push a 34 as ASCII character (a double quote '"')
ý # Join the three values on the stack by this
# (and output the result implicitly)
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fSMnF2OTw8sN7YfT//wA)
**Challenge part:**
I've combined this with the following if-else construction:
```
…·‡§Íް # Push dictionary string "tie lose win"
# # Split it on spaces: ["tie","lose","win"]
sª # Swap, and append the quine-string we created
¤ # Get the last item (the quine we added) of the list (without popping)
¸ # Wrap it into a list
YF # Loop 2 times (the default value of variable `Y` is 2):
¤ # Get the last item of the list (without popping)
₁D # Push builtin 256 twice
À # Rotate the digits once towards the left: 562
‡ # Transliterate the 256 to 562 in the string
ª # And append it to the list
}IQ # After the loop: check for each value if it's equal to the input
Z # Get the maximum (without popping) to check if any are truthy
_ # Inverse this boolean (0 becomes 1; 1 becomes 0)
ª # Append it to the list of truthy/falsey values
Ï # Leave the strings of the earlier created list at the truthy positions
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `…·‡§Íް` is `"tie lose win"`.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 127 \* 3 = 381 bytes
## Rock :
```
x=0;exec(s:="a=';exec(s:=%r)'%s;i=input();print(a==i[3:]and'x=/'<i[:3]<'x=3'and['tie','win','lose'][x-int(i[2])]or'x=%d'%x+a)")
```
[Try it online!](https://tio.run/##xZFNasMwEIX3PoUQmLFoQ@t4U@zMJboVWii2IEOLJDR2op7elVMotItsvZk/Ps17aOLXfAm@e4tpHcPkBAop5ZrxdXDZjQ33KC3Cb1MnBTUPhOTjMjdqiIn83FhE0l1vrJ8g4wucSPedOZW6gzLTMJODZ7iRL/EzsAOj82F7SfpolAmpoPUEdX6ySqq1eNBtf2hN9bNfpjB@iCuLLUtV3e1sftV/INro0kOCR2IOiR9CaTkTX/4ge39KlbHdWf@4q/77ct6OIu4q3w "Python 3.8 (pre-release) – Try It Online")
## Paper :
```
x=1;exec(s:="a=';exec(s:=%r)'%s;i=input();print(a==i[3:]and'x=/'<i[:3]<'x=3'and['tie','win','lose'][x-int(i[2])]or'x=%d'%x+a)")
```
[Try it online!](https://tio.run/##xZHBasMwDIbveQpjCIppy5rmUpL6JXY1PriJoWLFNlbSek@fORkMyqDXXIQkPun/kcL3ePOuOYc4936wTDLO@Zxk3dlk@4payY2Ev6KMAkrqUKIL01iJLkR0Y2WkRNW02rgBkvyAC6q20ZecN5B7Cka0sIcnuhzvnixolQ7LJKqTFtrHjJYDlGlnBBdz9qDq9lDr4nc/DybYyB7Eou@/uChWP4th8Y9Yk/cI9UjkI72n4nRFur0w@TDHLQ9TbPyYrH/aVP9zui5PYavKDw "Python 3.8 (pre-release) – Try It Online")
## Scissors :
```
x=2;exec(s:="a=';exec(s:=%r)'%s;i=input();print(a==i[3:]and'x=/'<i[:3]<'x=3'and['tie','win','lose'][x-int(i[2])]or'x=%d'%x+a)")
```
[Try it online!](https://tio.run/##xZLBasMwDIbveQpjCIrZypbmMpLqJXY1PriJoWLFNlayeU@fOR0bDAY95iIk8Un6kRQ/50vw3UtM6xgmJ1BIKdeMx8FlNzbco7QIv0GdFNQ8EJKPy9yoISbyc2MRSXe9sX6CjE9wIt135lT8DkpOw0wOHuGDfLHXwA6MzoetkvTRKBNSQesJ6vxglVRr0aDb/tCa6ru/5JGYQ2LxziKF8U2q6iZp06z@g6KNLt2lfvy7YFrOxJc/WFnS855LqjK2O8/f9Umq1@W8HUXcpnwB "Python 3.8 (pre-release) – Try It Online")
## How it works :
The structre of this quine is a variation of `exec(s:="print('exec(s:=%r)'%s)")`
* `x=0`, `x=1`, `x=2` defines the type of the program (rock, paper or scissors)
* `a=';exec(s:=%r)'%s` stores the quine in `a`
* `i=input()` stores the input in `i`
* `a==i[3:]and'x=/'<i[:3]<'x=3'` verify that the input is any of `rock`, `paper` or `scissors`.
* `and['tie','win','lose'][x-int(i[2])]` If the above is true, prints the corresponding result using as index the difference of the type of each code
* `or'x=%d'%x+a` otherwise, prints the quine
] |
[Question]
[
**Background and Motivation:**
[IOC Country Codes](https://simple.wikipedia.org/wiki/List_of_IOC_country_codes) are three letter abbreviations that are commonly used when broadcasting the Olympic Games. The last two letters of some codes overlap with the first two letters of other codes (RUS -> USA, JPN -> PNG), etc. Clearly, you can transform the first country code into the second by removing the first letter, and adding a new letter at the end. Sometimes, you can chain these transformations into a longer path (RUS -> USA -> SAM).
I want to find determine whether a path exists between 2 given country codes (using a provided list like the IOC list or the FIFA list) in order to impress party guests, and in the event that multiple paths exist, I'd like to output the longest one. To keep the output small enough to sneak into a commercial break, paths are compressed by not repeating common substrings between adjacent country codes: RUS -> USA -> SAM would be written as RUSAMfor example.
If multiple equal length paths are possible, you can select any result (previously asked for a deterministic tiebreaking rule that "I could explain to a partygoer." I would still appreciate answers that include this, but it's probably not a good objective rule that constrains whether an answer is correct.)
**The Technical Challenge**
*Inputs:*
* initial 3 letter country code
* terminal 3 letter country code
* set of valid 3 letter country codes
*Outputs*:
Determine whether a string exists such that:
* the first three letters are identical to the initial 3 letter country code
* The last three letters are identical to the terminal 3 letter country code
* each 3-letter substring corresponds to a valid country code from the input set
* the same country code cannot appear twice in the string (with the exception that the first 3 characters and the last 3 characters can be the same)
If one such string exists, print that string as the output. If multiple such strings exist, print the longest such string. If no such string exists, any of the following are acceptable:
* no output
* falsey output
* error
Other ways of indicating that no such path exists are also allowed as long as they can't be confused for a valid path.
*Valid Assumptions*:
\*The initial 3 letter country code and the terminal 3 letter country code are both contained in the provided set of valid 3 letter country codes.
*Invalid Assumptions*:
\*The input set cannot be assumed to be ordered for purposes of producing a deterministic output.
\*The initial 3 letter country code cannot be assumed to be different from the terminal country code (cyclic requests are allowed)
*Extra Style Points (Not Necessary for Submission to be Valid):*
If your answer includes a description of a deterministic tie-breaking rule you are using to determine which string to output when multiple identical length strings exist that meet all the above criteria, then you'll make this internet stranger very happy. Preferably something easy enough to explain to a random Olympics viewer, which is too fuzzy to be a good requirement for a valid submission.
*Scoring:*
This is code golf, so the shortest answer (in bytes) wins. Standard Loopholes apply.
**Test Cases**
*Input 1*: "AAA", "ZZZ", ["AAA", "AAZ", "AZZ", "ZZZ"]
*Output 1*: "AAAZZZ" (Find valid path if it exists)
*Input 2*: "AAA", "ZZZ", ["AAA", "AAZ", "AZZ", "ZZZ", "AAB", "ABB", "BBB", "BBZ", "BZZ", "ZZZ"]
*Output 2*: "AAABBBZZZ" (Find longest path if short and long paths both exist)
*Input 3*: "AAA", "ZZZ", ["AAA", "ZZZ"]
*Output 3*: Crash, falsey message, or no output (just don't output "AAAZZZ" or something that could be confused for a path)
*Input 4*: "AAA", "ZZZ", ["AAA", "AAB", "ABZ", "BZZ", "AAY", "AYZ", "YZZ", "ZZZ"],
*Output 4*: "AAABZZZ" OR "AAAYZZZ", but you must explain what rule decided which one to output (consistent behavior that follows your chosen rule)
*Input 5*: "AAA", "AAA", ["AAA", "ABA", "AAB", "BAA"],
*Output 5*: "AAABAAA" (Test case where initial code == terminal code, but other codes should be included in result)
*Input 6*: "AAA", "AAA", ["AAA", "ABA"],
*Output 6*: "AAA" ("AAABAAA" is not valid because "AAB" and "BAA" are 3 letter substrings contained in the answer which are not part of the valid set of country codes)
*Input 7*: "ISL", "ERI",
```
["AFG", "AHO", "AIA", "ALB", "ALG", "AND", "ANG", "ANT", "ARG", "ARM", "ARU", "ASA", "AUS", "AUT", "AZE", "BAH", "BAN", "BAR", "BDI", "BEL", "BEN", "BER", "BHU", "BIH", "BIZ", "BLR", "BOL", "BOT", "BRA", "BRN", "BRU", "BUL", "BUR", "CAF", "CAM", "CAN", "CAY", "CGO", "CHA", "CHI", "CHN", "CIV", "CMR", "COD", "COK", "COL", "COM", "CPV", "CRC", "CRO", "CUB", "CYP", "CZE", "DEN", "DJI", "DMA", "DOM", "ECU", "EGY", "ERI", "ESA", "ESP", "EST", "ETH", "FAR", "FGU", "FIJ", "FIN", "FLK", "FPO", "FRA", "FSM", "GAB", "GAM", "GBR", "GBS", "GEO", "GEQ", "GER", "GHA", "GIB", "GRE", "GRL", "GRN", "GUA", "GUD", "GUI", "GUM", "GUY", "HAI", "HEL", "HKG", "HON", "HUN", "INA", "IND", "IRI", "IRL", "IRQ", "ISL", "ISR", "ISV", "ITA", "IVB", "JAM", "JOR", "JPN", "KAZ", "KEN", "KGZ", "KIR", "KOR", "KSA", "KUW", "LAO", "LAT", "LBA", "LBR", "LCA", "LES", "LIB", "LIE", "LTU", "LUX", "MAC", "MAD", "MAR", "MAS", "MAW", "MAY", "MDA", "MDV", "MEX", "MGL", "MGO", "MKD", "MLI", "MLT", "MNT", "MON", "MOZ", "MRI", "MRT", "MSH", "MTN", "MYA", "NAM", "NCA", "NCD", "NED", "NEP", "NFI", "NGR", "NIG", "NIU", "NMA", "NOR", "NRU", "NZL", "OMA", "PAK", "PAN", "PAR", "PER", "PHI", "PLE", "PLW", "PNG", "POL", "POR", "PRK", "PUR", "QAT", "REU", "ROU", "RSA", "RUS", "RWA", "SAM", "SEN", "SEY", "SIN", "SKN", "SLE", "SLO", "SMR", "SOL", "SOM", "SPM", "SRB", "SRI", "STP", "SUD", "SUI", "SUR", "SVK", "SWE", "SWZ", "SYR", "TAN", "TGA", "THA", "TJK", "TKM", "TKS", "TLS", "TOG", "TPE", "TTO", "TUN", "TUR", "TUV", "UAE", "UGA", "UKR", "URU", "USA", "UZB", "VAN", "VEN", "VIE", "VIN", "WAF", "YEM", "ZAM", "ZIM"]
```
*Output 7*: ISLESTPERI (real world test case: IOC codes ISL -> SLE -> LES -> EST -> STP -> TPE -> PER -> ERI corresponding to Iceland -> Sierra Leone -> Lesotho -> Estonia -> Sao Tome and Principe -> Republic of China -> Peru -> Eritrea)
*Input 8*: USA, USA,
```
["ABW", "AFG", "AGO", "AIA", "ALA", "ALB", "AND", "ARE", "ARG", "ARM", "ASM", "ATA", "ATF", "ATG", "AUS", "AUT", "AZE", "BDI", "BEL", "BEN", "BES", "BFA", "BGD", "BGR", "BHR", "BHS", "BIH", "BLM", "BLR", "BLZ", "BMU", "BOL", "BRA", "BRB", "BRN", "BTN", "BVT", "BWA", "CAF", "CAN", "CCK", "CHE", "CHL", "CHN", "CIV", "CMR", "COD", "COG", "COK", "COL", "COM", "CPV", "CRI", "CUB", "CUW", "CXR", "CYM", "CYP", "CZE", "DEU", "DJI", "DMA", "DNK", "DOM", "DZA", "ECU", "EGY", "ERI", "ESH", "ESP", "EST", "ETH", "FIN", "FJI", "FLK", "FRA", "FRO", "FSM", "GAB", "GBR", "GEO", "GGY", "GHA", "GIB", "GIN", "GLP", "GMB", "GNB", "GNQ", "GRC", "GRD", "GRL", "GTM", "GUF", "GUM", "GUY", "HKG", "HMD", "HND", "HRV", "HTI", "HUN", "IDN", "IMN", "IND", "IOT", "IRL", "IRN", "IRQ", "ISL", "ISR", "ITA", "JAM", "JEY", "JOR", "JPN", "KAZ", "KEN", "KGZ", "KHM", "KIR", "KNA", "KOR", "KWT", "LAO", "LBN", "LBR", "LBY", "LCA", "LIE", "LKA", "LSO", "LTU", "LUX", "LVA", "MAC", "MAF", "MAR", "MCO", "MDA", "MDG", "MDV", "MEX", "MHL", "MKD", "MLI", "MLT", "MMR", "MNE", "MNG", "MNP", "MOZ", "MRT", "MSR", "MTQ", "MUS", "MWI", "MYS", "MYT", "NAM", "NCL", "NER", "NFK", "NGA", "NIC", "NIU", "NLD", "NOR", "NPL", "NRU", "NZL", "OMN", "PAK", "PAN", "PCN", "PER", "PHL", "PLW", "PNG", "POL", "PRI", "PRK", "PRT", "PRY", "PSE", "PYF", "QAT", "REU", "ROU", "RUS", "RWA", "SAU", "SDN", "SEN", "SGP", "SGS", "SHN", "SJM", "SLB", "SLE", "SLV", "SMR", "SOM", "SPM", "SRB", "SSD", "STP", "SUR", "SVK", "SVN", "SWE", "SWZ", "SXM", "SYC", "SYR", "TCA", "TCD", "TGO", "THA", "TJK", "TKL", "TKM", "TLS", "TON", "TTO", "TUN", "TUR", "TUV", "TWN", "TZA", "UGA", "UKR", "UMI", "URY", "USA", "UZB", "VAT", "VCT", "VEN", "VGB", "VIR", "VNM", "VUT", "WLF", "WSM", "YEM", "ZAF", "ZMB", "ZWE"]
```
*Output 8*: "USAUSA" (real world test case: ISO3166-Alpha-3 codes representing the path USA -> SAU -> AUS -> USA corresponding to United States -> Saudi Arabia -> Australia -> United States)
**Data:**
All country codes for the real world examples was taken from <https://datahub.io/core/country-codes#data> if you want to play with it more. The paths were a lot shorter and less interesting than I thought they'd be when I started this question (I guess the country codes don't populate the space of 3 letter strings densely enough), but someone else may find something interesting to do with them.
**Reference Code:**
In case you prefer code you can play with over written test cases (or simply want to play with various paths but don't want to solve the challenge), here's some reference (ungolfed) code that solves all test cases quickly.
```
def pathfinder_helper(initial_code, terminal_code, valid_codes):
if initial_code != terminal_code:
if initial_code[1:] == terminal_code[:-1]:
return [initial_code, terminal_code]
if not valid_codes:
if initial_code == terminal_code:
return [initial_code]
return None
best_path = None
for intermediate_code in valid_codes:
# Pure speed optimization, can be left out and be "correct" but will be super slow on cases 7 and 8
if initial_code[1:] != intermediate_code[:-1]:
continue
initial_intermediate_path = pathfinder_helper(initial_code, intermediate_code, valid_codes - {intermediate_code})
intermediate_terminal_path = pathfinder_helper(intermediate_code, terminal_code, valid_codes - {intermediate_code})
if initial_intermediate_path and intermediate_terminal_path:
# Longer paths preferred
if (best_path is None) or len(initial_intermediate_path + intermediate_terminal_path[1:]) >= len(best_path):
if best_path and len(initial_intermediate_path + intermediate_terminal_path[1:]) == len(best_path):
# If lengths equal, use sort order (lexicographic)
if initial_intermediate_path + intermediate_terminal_path[1:] < best_path:
best_path = initial_intermediate_path + intermediate_terminal_path[1:]
else:
best_path = initial_intermediate_path + intermediate_terminal_path[1:]
return best_path
def pathfinder(initial_code, terminal_code, valid_codes):
path = pathfinder_helper(initial_code, terminal_code, valid_codes - {initial_code, terminal_code})
if path:
return ''.join([path[0]] + [code[-1] for code in path[1:]])
print("Case 0:", pathfinder("AAA", "AAA", {"AAA"}))
print("Case 1:", pathfinder("AAA", "ZZZ", {"AAA", "AAZ", "AZZ", "ZZZ"}))
print("Case 2:", pathfinder("AAA", "ZZZ", {"AAA", "AAZ", "AZZ", "ZZZ", "AAB", "ABB", "BBB", "BBZ", "BZZ", "ZZZ"}))
print("Case 3:", pathfinder("AAA", "ZZZ", {"AAA", "ZZZ"}))
print("Case 4:", pathfinder("AAA", "ZZZ", {"AAA", "AAB", "ABZ", "BZZ", "AAY", "AYZ", "YZZ", "ZZZ"}))
print("Case 5:", pathfinder("AAA", "AAA", {"AAA", "ABA", "AAB", "BAA"}))
print("Case 6:", pathfinder("AAA", "AAA", {"AAA", "ABA"}))
print("Case 7:", pathfinder("ISL", "ERI", {"AFG", "AHO", "AIA", "ALB", "ALG", "AND", "ANG", "ANT", "ARG", "ARM", "ARU", "ASA", "AUS", "AUT", "AZE", "BAH", "BAN", "BAR", "BDI", "BEL", "BEN", "BER", "BHU", "BIH", "BIZ", "BLR", "BOL", "BOT", "BRA", "BRN", "BRU", "BUL", "BUR", "CAF", "CAM", "CAN", "CAY", "CGO", "CHA", "CHI", "CHN", "CIV", "CMR", "COD", "COK", "COL", "COM", "CPV", "CRC", "CRO", "CUB", "CYP", "CZE", "DEN", "DJI", "DMA", "DOM", "ECU", "EGY", "ERI", "ESA", "ESP", "EST", "ETH", "FAR", "FGU", "FIJ", "FIN", "FLK", "FPO", "FRA", "FSM", "GAB", "GAM", "GBR", "GBS", "GEO", "GEQ", "GER", "GHA", "GIB", "GRE", "GRL", "GRN", "GUA", "GUD", "GUI", "GUM", "GUY", "HAI", "HEL", "HKG", "HON", "HUN", "INA", "IND", "IRI", "IRL", "IRQ", "ISL", "ISR", "ISV", "ITA", "IVB", "JAM", "JOR", "JPN", "KAZ", "KEN", "KGZ", "KIR", "KOR", "KSA", "KUW", "LAO", "LAT", "LBA", "LBR", "LCA", "LES", "LIB", "LIE", "LTU", "LUX", "MAC", "MAD", "MAR", "MAS", "MAW", "MAY", "MDA", "MDV", "MEX", "MGL", "MGO", "MKD", "MLI", "MLT", "MNT", "MON", "MOZ", "MRI", "MRT", "MSH", "MTN", "MYA", "NAM", "NCA", "NCD", "NED", "NEP", "NFI", "NGR", "NIG", "NIU", "NMA", "NOR", "NRU", "NZL", "OMA", "PAK", "PAN", "PAR", "PER", "PHI", "PLE", "PLW", "PNG", "POL", "POR", "PRK", "PUR", "QAT", "REU", "ROU", "RSA", "RUS", "RWA", "SAM", "SEN", "SEY", "SIN", "SKN", "SLE", "SLO", "SMR", "SOL", "SOM", "SPM", "SRB", "SRI", "STP", "SUD", "SUI", "SUR", "SVK", "SWE", "SWZ", "SYR", "TAN", "TGA", "THA", "TJK", "TKM", "TKS", "TLS", "TOG", "TPE", "TTO", "TUN", "TUR", "TUV", "UAE", "UGA", "UKR", "URU", "USA", "UZB", "VAN", "VEN", "VIE", "VIN", "WAF", "YEM", "ZAM", "ZIM"}))
print("Case 8:", pathfinder("USA", "USA", {"ABW", "AFG", "AGO", "AIA", "ALA", "ALB", "AND", "ARE", "ARG", "ARM", "ASM", "ATA", "ATF", "ATG", "AUS", "AUT", "AZE", "BDI", "BEL", "BEN", "BES", "BFA", "BGD", "BGR", "BHR", "BHS", "BIH", "BLM", "BLR", "BLZ", "BMU", "BOL", "BRA", "BRB", "BRN", "BTN", "BVT", "BWA", "CAF", "CAN", "CCK", "CHE", "CHL", "CHN", "CIV", "CMR", "COD", "COG", "COK", "COL", "COM", "CPV", "CRI", "CUB", "CUW", "CXR", "CYM", "CYP", "CZE", "DEU", "DJI", "DMA", "DNK", "DOM", "DZA", "ECU", "EGY", "ERI", "ESH", "ESP", "EST", "ETH", "FIN", "FJI", "FLK", "FRA", "FRO", "FSM", "GAB", "GBR", "GEO", "GGY", "GHA", "GIB", "GIN", "GLP", "GMB", "GNB", "GNQ", "GRC", "GRD", "GRL", "GTM", "GUF", "GUM", "GUY", "HKG", "HMD", "HND", "HRV", "HTI", "HUN", "IDN", "IMN", "IND", "IOT", "IRL", "IRN", "IRQ", "ISL", "ISR", "ITA", "JAM", "JEY", "JOR", "JPN", "KAZ", "KEN", "KGZ", "KHM", "KIR", "KNA", "KOR", "KWT", "LAO", "LBN", "LBR", "LBY", "LCA", "LIE", "LKA", "LSO", "LTU", "LUX", "LVA", "MAC", "MAF", "MAR", "MCO", "MDA", "MDG", "MDV", "MEX", "MHL", "MKD", "MLI", "MLT", "MMR", "MNE", "MNG", "MNP", "MOZ", "MRT", "MSR", "MTQ", "MUS", "MWI", "MYS", "MYT", "NAM", "NCL", "NER", "NFK", "NGA", "NIC", "NIU", "NLD", "NOR", "NPL", "NRU", "NZL", "OMN", "PAK", "PAN", "PCN", "PER", "PHL", "PLW", "PNG", "POL", "PRI", "PRK", "PRT", "PRY", "PSE", "PYF", "QAT", "REU", "ROU", "RUS", "RWA", "SAU", "SDN", "SEN", "SGP", "SGS", "SHN", "SJM", "SLB", "SLE", "SLV", "SMR", "SOM", "SPM", "SRB", "SSD", "STP", "SUR", "SVK", "SVN", "SWE", "SWZ", "SXM", "SYC", "SYR", "TCA", "TCD", "TGO", "THA", "TJK", "TKL", "TKM", "TLS", "TON", "TTO", "TUN", "TUR", "TUV", "TWN", "TZA", "UGA", "UKR", "UMI", "URY", "USA", "UZB", "VAT", "VCT", "VEN", "VGB", "VIR", "VNM", "VUT", "WLF", "WSM", "YEM", "ZAF", "ZMB", "ZWE"}))
```
[Answer]
# [Python 2](https://docs.python.org/2/), 119 bytes
```
def f(s,e,c):
r=max([s[0]+f(p,e,c-{p})for p in c-{s}if s[1:]==p[:2]]+[e]*(s==e)+['!'],key=len)
return[r,'!']['!'in r]
```
[Try it online!](https://tio.run/##jY69bsQgEIT7ewriBhMTKbnSEgXcI1xlIwqcgGJdwiFwpJwtP7vDz1lxEUupZmdW@@3Y2/B@NcdleVMa6NJjhV9RfQCOfMrvknv@LCpd2hg/TXZG@uqABb0Bwfq518Dzl1oQYnl9FKLiSjyWnhCFKg4foMAXdSMfyqBAVMOXM9zhmMdlgDixWNebIXyGUkqIARzHMcgUbBet7KKFXUrTckaH9aaglBYYFG3bBplWSylLwmJasLQMYZOkSa7JYTz8g5flzsu4QIszC8l/CuSXv0@2rZKwVbYdd@rs0M/55ryln@7Y0z59@QE "Python 2 – Try It Online")
Takes country codes as a set of strings; returns longest path or `!` if no such path exists.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes
```
ḟŒPŒ!€Ẏ;ṙ-ɗ€Ḋ⁼Ṗ}ɗƝẠ$ƇLÞṪ;Ṫ}¥/
```
[Try it online!](https://tio.run/##y0rNyan8///hjvlHJwUcnaT4qGnNw1191g93ztQ9OR3E2dH1qHHPw53Tak9OPzb34a4FKsfafQ7Pe7hzFVDNqtpDS/X///8freTo6KikowCkosBUFJiKglFOYMoJzHMCCsb@h8iBtRHQ7egI1u3oBKacYBTcLKjKWAA "Jelly – Try It Online")
Golfy, but inefficient answer that generates all combinations of all power sets of the country code set minus the start and end, and then checks which ones fit the rules. A dyadic link that takes as its left argument the set of codes and its right argument the end and start in that order. Returns 0 if no path exists. Otherwise returns the longest path, and if there is more than one, the last as determined by the order of the input set.
# [Jelly](https://github.com/DennisMitchell/jelly), ~~42~~ 43 bytes
```
ṭ@Ɱ⁵ḟṖ⁼¥Ƈ0ị$Ḋ$ƲßẎ;W)
ÇẎ0ị$Ḋ⁼⁴Ṗ¤ƲƇLÞṪṭ@;Ṫ}¥/
```
[Try it online!](https://tio.run/##NZU9b9w2HIf3forikKVAgWbPUomSKJ5ISiEpyTrDY5ciX6BDB08GEqBjx2ZplgIt0KAF4raTDfh7nL/I5fx73Ok58f/@Qt73371588PpdLz9/dvHP/94vP77@On98fbnx@v/7j483Lw8/vvuxfHT2xcPH@/fH//56dX61Rf3N@cf/wvOeo/Xf50N7n59@Phw4@9/Od7@9uTs1Zk/3n345nQ6XV7u5lztrq5O4ulyV9Xr7usvd1VnBTsKrhL8M2ohNkJqAQYpCBkUDEoHUJkzKMJB5nXjhNaDCKRZd/JS2wYkoX8GKq4XfADI/EEIszDiOuEs1YBABSxKqV6lYqoOSGbMIPQt8ACZW4SgsGZsgAXYEd2MStBMGCQVbeYaqPPmAi8bmtsk0KWmVSnNXnZNUJ5NVIQG181Bh62RZms3gUBt7sEEVG1bdNg5ldLhuvPy2dGsLmkLOoZqK6Vra@VpW8ksgWwvA@tQwaf1imcDh/EZr4VkQAPUJVsINHfg@UsR@kFt7YMMenawT@pnX5R8Pyusa0AAaLpRRTsCOcbvknJxmcOswhy7u68Ufd8q@n6UbD/Jbqi0YAPbOli@ehkMTppDlJcBu2FVdF@pZ76OIAFF8EYG3mngfuArY1A0VD9fCItkoTKgA3IWjAxCg0pjgboUWpkHVjgM6kvwDijBwCaH2ALMo8YYRpUZEpo0KxR1MHC1w4qzja9NmpFGRqOwsZVd7LRn0SrP6AxQmdErs0jr4oRdQnbQ18hsp2oAfBlAhIkyJ6/LNVHKxG2cuBZTwpyKpqQ5TFm1T5va@rqSLHH/0gioNvFc5EqHma3L7ES2E5Bm5rnIe3Ui84xm3wINJ9P5zGXOE@CxylkNyQWfM5rLAHC94mzVjPIF5psBMigsWDFyVnjgC/e27OWsDB7IvHglX0ZFKAUD7lghiTIr@bJyyBM0M9R5kMoc1OuZ7j792TzhoMIWursYQOsWi4x7tETlsvCnsXpNZeVB2lrhwA048Mwc6MTMy14ia8PE5kw/uXH1Jtl2ll19Bg "Jelly – Try It Online")
A full program that takes three arguments: the starting country in a nested list, the final country and the list of country codes. Returns a Jelly string of the longest path if one exists with the sort order determined by the reverse of the listing of the country codes. If no valid path exists, returns `0` followed by the last letter of the destination. Works recursively, and handles longer cases relatively efficiently.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 108 bytes
```
+/(?m:^.*\b((..).)(?!.*\1).*\2$)/_L$`\b(..)(.)(?!.*\1\2)(?=.*\1$)
$=$2
mL$`(...),(\w*\1)\w*$
$2
N$^`
$.&
1G`
```
[Try it online!](https://tio.run/##bZRNb@M2EEDv/hcF3MJpB1lkjwUWC@qLokVSCj@kSAi2aYEeetgeigL9@emT5XXibA7PEskhNdLM8z9//vvX37/fPf940E/Pv3w4fP7665fbnx//OBxub29ubw6ff2B0d8PPx/3Nh9/s/ok1lg6XtceP3H1a7/Y3u/2n/cfdV6KIub2Rw@N/625@9zsW/P7L025/@9Pujoc9K6VEqUXUsshyhrnd23mlClFFIcWJRYp34r/fv@7ZYpWaRc2LzO89p9hii9Me9Wb@PG60qLYXZRhbzrWMfQXrNYkKXIODLCoSkyMwv9Sc24KHIEVlpKgtMK4Zt1kKw7ohT8u4Z61PUgQFxHBekZnLQUrVgAMPs5S6l7JVYIA5M0rpiOsr6MAC8QPzoQTicyHlPEhJXhU5VEcjlVNSEVeXWWo9Sx2M1LxDHQdIUqdWGnJvdJbGHMFLYztphl4a8myiE8330@SmiwBRdN3DPTAmR21YDzVY8KIzc7kCA@zLs7TKSMu3aTstbe@lzV6MV1CJISfDXhPuxUSuMcAoJrE@FnLk2cc@yHHw0tE3He/Waa4mSMd8x/t0eRKrekhiqa0lV1tyraNY8rOmFpuy2PwgTpVQQYAIE8ziKgWjuJoYbaEX1xFnDSRx9IIjd9cv4sjZBcaxFZeYm5V48vQ805eV@HplEN8Y8TqINxqyeOrhydlTe79Y6RkPqgMPQQa@6UDNB1vDJAM9OFDrgT1DII5euecdQ50l9MC7B/oxTEoiz498m1jPEqlj7IBzou0l0juRcyK9EAcIBRiJaZBIrSK1ipwdx07ixJ5pkTgHSeSVtJJEndOxk9Q5iJIs9FrSUEtKvSTqmdif8ihZ1ZLZk7sgmffM5JiXQkbOGslvpBYj@U30/Fw7Wch7Me7Um9R/p4pJTk7qb06evVydpM8uPtKbih5RqQF97eWVi1GKBud0BauXK3Fz07rNTYujLm@OnvwsNkepbTHiLN93cxQXS/xra7DvuKnf8dNsbtKj5QNxs3vlaX7x1HcnV6tFvfG1vfZ1dZQ9J09XR3H/4unq6Ooney9uEq/tINpx71dwl/8MHarN2bQ62ry4ujrqKmn53m0YpU1m87UC5zdn@R/bnPXX3lKPk6/04LvOtm7zFvdP7k5p87bwm7PFvHm7@tpxjf3FWzuqs7vN5m7Zn53VL95SkytnqYvzNRDjh7O7q7fMp3tx9IybiJ25zunssMVdHG063MVXU27u2mpzd7Cv/PUv/pb@7K@9dpcantzluUOYZYi4PTfXHl8czhIrv3mscVNHifRYPOIsDmw@j2efX7kcq7PLZ4dH/@LxAzFzufnMt038PyXcenHabl6fnPbf@Zwm7unJi9PO4PX8yuskY5k2tzVj6jt6JyMuTraRid7cPG9koQcX8jrtjep/ "Retina – Try It Online") Link includes test suite. Takes input in the order set, terminal, initial. Explanation: Works by generating all possible paths, filtering on those that include the destination, and taking the longest. Explanation:
```
+
```
Repeat the command until it does nothing (because there are no more matches).
```
/(?m:^.*\b((..).)(?!.*\1).*\2$)/_
```
Operate only on lines whose chain can be extended.
```
L$`\b(..)(.)(?!.*\1\2)(?=.*\1$)
$=$2
```
List all of the new possible chains.
```
mL$`(...),(\w*\1)\w*$
$2
```
List all of the chains that include the terminal (cut to the length of the terminal).
```
N$^`
$.&
```
Sort in ascending order of length, then reverse the list.
```
1G`
```
Take the first. In the case of a tie-break, the last to be generated wins; if the set is in lexicographic order then this will be the last in lexicographic order.
[Answer]
# JavaScript (ES6), 106 bytes
Takes input as `(terminal)(initial,[array of codes])`. Returns \$0\$ if there's no solution.
```
(t,S=0)=>g=(s,a,r=s)=>S=a.map(w=>s[0]+w==s+w[2]&w!=s&&g(w,a.filter(s=>s!=w),r+w[2]))|s!=t||S[r.length]?S:r
```
[Try it online!](https://tio.run/##nZbNbtw2FIX3fYrGi2CMuEbQZYFJoV@KI5JSREoTycjCSB03hRsHHqPe@N3dmftpDI0rJ01WBxQvLy8Pfz79df7P@ebDzacvt798vv7j4uHj8mFxe@KXr4@Xby6Xi83J@cnNcrNt@OX56d/nXxZ3yzebs9fvX90tl5tXd2e/vn9592K5efnycnF3cn768dPV7cXNYrMNerG8Oz65kZDj4/tt8/b@3p/dnF5dfL68/fP97/63m4cP158311cXp1fXl4uPi6NhGI6OF0dRFB2d/Hw26lYGkUFkF7NN@NMPDpWPsUgsEu9F@uIfmOQ7Kxonn04XRb1IL63@qzXs8sykjafZ4@3H7xo6E5w1ehesvSE4VxJcVCKaoYbFGPpcioytINLQaizSiniGtx4hcsiovUAc0oikWiQzCH0ZfYXkjDXjNMYa@ioGVDJD3EQIw6klbglpZUAS5YhFHCLbkyhZe1JEiEYI0Z2IJUuVIiViEHLWRDYJQs5WjEz6WgQnUpaZrmSi1Mq0KVmyRIrPlFS226udYGvma0QWnQXxJcfIXMm4XK8QmSE3UmdeSy05LuVeJlKcKIUhKm4Q2TiVVchbhD7sUZpxTYYYROZTLSFtimiEGVpZURHJx4INL0o5REUlw4tWRLsIkSwaCzQT6UZK4vBupUHEeR0Y10mBKxa2qiRkVUvqkmejZANKRUtLSElkiddlu96JiSpELDdcRoNZJqGViWcGX4wWX0yQ7TDtu53YKEFSpEE8skbEHptGiKzIZgxXBpFabEkWoxGpzHIpLUbaShZmsc429Hk5LzYQ0stEDpccS3GJpHbZKHLcXC5ZnJKqnVaIrM9xdh3WOS6eG6Tcir46KhGHSGTNkaq5arXJEHGi5pmpuVw1qeuGLFzmt2xHk8l8TYWwcQ1vT7OWlmd9ng33mZjsuR2@RJjdG3HXc9E9s3supa@RJkakah/EHs9h9xx2T4G@k3L9mtRr2Q7fS1/AiaCkwMCtCisZEEqLyBqCQSoxJNSSLASpM3BXAvOFVs5LG0lIS@q2lL6WXWmxpx1kDR1FdPjScWg7fFnzVPaZ1DLg4KDtHEx2WY8XY/ItTGLZwj1T1CFTDtAyMoVn5AlMeKEi7nMUckQ9j5Z5ikhknMMGlSIjWkbxU8IYOyWMgTe2nfJmD5p4yhtuVNzBIg7eI2@gSAIwigwx3yaM@jZo9JQwvFfJO7L0dg477Qx2XDmhTzpEX4FQ8TyERt6Qeo@dkTeQ8Al2Rt6MoGGiJ4QhpzIyn7J8dKNAJlirmnTKojDyJp@hz8gbKwMKzmDRiJ9F0FMIpYh1Uxbxu/HIIvc8kji7ewjx7vwfFhV2iiRIuCfTOkyRFLspi@J@iqQRQiUtX/0XSaaLDsiUT8mUVAcsUjNI4gjPs4iTbF2GMNzVB2QakURkEActV9uuSdbT6sMBpwxkgjd5CZmAkE6mZDLplEy1mQOUmwFU4g4AZZ4nE9diTyZWVDeyD7WHaH3@PK6ecEo@@tRNcaUgjJJIz3PhV7CIZ/QRXt0BvOao5dMDah1wqnMzuHrH8D6ZwosDFvhRCDzwTxlmpijbM8x9C15hzUeeoCcMsxqU9XMoE3e7JEyJpujjHnVOaumAxtrIrqx5kB4xJx8Hnplh68SWdg//Ag "JavaScript (Node.js) – Try It Online")
### Commented
```
(t, S = 0) => // t = terminal code; S = best string, initialized to 0
g = ( // g is a recursive function taking:
s, // s = previous code (or initial code on the first call)
a, // a[] = array of codes
r = s // r = current result string, initialized to the first code
) => //
S = // this code will eventually update S
a.map(w => // for each word w in a[]:
s[0] + w == // the test w[0] + w[1] == s[1] + s[2] can also be processed
s + w[2] // as s[0] + (w[0] + w[1]) + w[2] == s[0] + (s[1] + s[2]) + w[2]
& // and therefore as s[0] + w == s + w[2]
w != s && // if the above test is true and w is not equal to s:
g( // do a recursive call to g:
w, // use w as the previous code
a.filter(s => // using a[], create a new array:
s != w // where w is removed
), // end of filter()
r + w[2] // append w[2] to r
) // end of recursive call
) | // end of map()
s != t || // if s is not equal to t
S[r.length] ? // or S is longer than r:
S // leave S unchanged
: // else:
r // update it to r
```
[Answer]
## Haskell, ~~102~~ 95 bytes
```
import Data.Lists
f l u@(s:t)e=argmax(1<$)$"":[e|e==u]++[s:f(l\\[w])w e|w<-l,t==take 2w,u/=w]
```
Returns an empty string if no path exists.
As `Data.Lists` is not installed on TIO, I'm providing a definition for `argmax`. I'm still importing `Data.List` for `\\`, so the code on TIO scores one byte less. [Try it online!][Try it online!](https://tio.run/##rZZdT9w4GIXv51dEqBeg0l11V@oF2qk2n44ntpPGToYMcDHaDgV1gIoZRC/639lwTgZlIJSuFi44iv369evjj2fO5quvi@Xy7u784tvV9dqL5uv5b@p8tR6dekvv5u/d1cF6bzGeX3@5mH/3lovLL@uzNzs7B0eLH4vx@Obk7duj1cHp7vL4@Oj2ZO/WW/y4/evdcn89Hq/nXxfeH7f7N7@Pb0/uugRt0ja3N/ZOr5afl@@93eMLb/Huo3d@2nYtvI/t/wtvfba4bD8Wy9XCu9jDiNHoYn5@2Y77fDXyvG83a7u@VpfemzbeO9rxfX9n32tlBplBZq2ctMHbf4h92nof/F8SozGABJBgI@gLXr2EV11NV3i/VN9vIA2@mte3MOjPHbSNv5y4a/1J4v@X6vzqn6eR0qqB8XEpB8avrv58/@HD0@jKDtXQtY5G7bztgW4XkggsJM0hkstS3CTFPhNRui8HKflVakoFsRxeWQojZzFdTymGUkIiCYkVhX0x@1LkDCTHSR4Yxb6cA3LMEJQ@hcNZS1AxpMKA0E8ommIoOHahwNrD1KdICkNkDdHMkkeUjKIozFkwsgwpzFnByLApIHQi4jKjCSaKNKaNmCUOUXwsUNn9jt8LbY1tQcGiYwdfEhqZCIxL5ISCGRKFOpMCtSR0KbGYSPAuCBoigpKCjRNxTvlEYR/tEZLjypiiKJhPVAypIoqkcIYKK0p9NKbc8DTDIUpzDE8riDQ@BVkkLZCcSJYo6f5@QEoKnJeO42oUOOHCJjlCJgVSZ3xKM25AJvglEZIxMqPXWTW9F@XnFFiu@IwomqVCfsXwTNEXJeGLctgOVR3ei/ZDSkQpKZYypcAeHfkUrEjHHC4UBbXojFmUpKAyzUupaaTOsTBN63TJPovzoh1DGkxk6JLhUkyI1CbuBMfNJMhiBKo2UlCwPsOza2id4cUzM5Sbs6/wM4qhILLgkSp41QoVU@BEwWem4OUqmLoomYWX@RO3o4wxX5lTuHEl355yii/L9VluuI1hsuXtsBmFs1sFdy0vuuXslpfSFpQyoKBq62CP5WG3POyWBdoa5dopU0@xHbZBn6MTTqBAx1vlJhjgMk3BGpyi5DDEFUjmHOp0vCuO87kK56XyEVIxdZWhr@KuVLSnmmENNYuo6UvNQ1vTlymfyiZGLTM6OJO6Bd2oow3JEWC/NgAR2wDZ4kgHEL4Zj8jB58jn5fVdQhHPc2QYGYgMEoJARJSOI53YPk6U7uNEES666sNlQ5WgDxden6AmeHjKHuBCZISkQxpT1Ms4ES9TRfZxwscpPGSWRg8xphpgjMl6qIlm/k@Ikz5PnA4uTL1hTAcXYu8RYzq4dFThRI9wwpxCYT6h2Wg6IYYIVlFGffC4Di7JAGo6uGgMSHkG0xJ@pk72iRNRtOmDh78tHsBjnucPz@6GOHxkfgU8qe7zh9jbYGjq@vwJTB88QdPnT0ecjF82f8ofVftbGEr6GArzLfCIAf7wCA@DhydZm5jC4abYwlDHH0Y6OKh5tfWUyRp@NW4LSooYIlySjBgicWTYx5CK@hgq1BCNzACNQrNFI/U8hngtNhjiiooS@1BY4qtJnmfTIyih0UamzyZBnAhEWj4XdkLw8Bl9IFW9RaohRNloC1FbUKrNAJsOObwJ@6TiAXP8VeD4wD8GlupzawMs8xKp3JSNfIIeAUtLcqsZ4hbcrUPXx5dgH@9RbVBLTWhMFXZlygfpgWlonPGZmbVOtGgb3f0L "Haskell – Try It Online")
] |
[Question]
[
I am a big fan of the game Creeper World, and especially the sequel. You don't need to know how this game works to answer the question, I just wanted to mention where my question originated from.
In the game, your objective is to destroy the Emitters that are spawning Creeper, using a weapon known as a nullifier.
Nullifiers can destroy any emitter in this radius:
```
eee
eeeee
eenee
eeeee
eee
```
Each nullifier CAN target multiple Emitters.
**Your objective**
Given an array simulating a 2D map consisting of *nothing* and *emitters* with whatever characters you like, could be *spaces* and *e* or numbers - just be sure they are distinguishable, output the same map with the optimal amount of nullifiers *n* (or what you would like) placed, so that the emitters are destroyed with the least amount of nullifiers.
If there are multiple optimal ways of doing it, just outputting one would be fine. If, however, the task is not solvable, say there are so many emitters that no layout will ever hit all of them, you must output a distinguishably different something, null will suffice
**Quick Rules:**
* Input: multidimensional array
* Input will contain two characters, meaning *nothing* and *emitter*, include what is what in your answer
* Output: multidimensional array
* Output will contain three characters, meaning *nothing*, *emitter* and *nullifier* OR a distinguishable output if the input is unsolvable
* You may only replace the *nothing* character with a nullifier
* A nullifier can hit multiple emitters, and will always hit all that
are in range
* A nullifier can hit in the area specified above, and will always hit all emitters that it can target
* Shortest answers in bytes win
* standard loopholes forbidden
**Examples**
Input:
```
[[ , ,e, , ],
[ , , , , ],
[e, , , ,e],
[ , , , , ],
[ , ,e, , ]]
```
Output:
```
[[ , ,e, , ],
[ , , , , ],
[e, ,n, ,e],
[ , , , , ],
[ , ,e, , ]]
```
Input:
```
[[e,e,e,e,e],
[e, , , ,e],
[e, , , ,e],
[e, , , ,e],
[e,e,e,e,e]]
```
Output:
```
[[e,e,e,e,e],
[e, ,n, ,e],
[e, , , ,e],
[e, ,n, ,e],
[e,e,e,e,e]]
```
Input:
```
[[e, , , , , , ,e, ,e, , , ,e, ,e, ,e, ,e],
[ , ,e, , ,e, , , ,e,e, , , , ,e, , , , ],
[ , ,e, , , ,e, ,e, ,e, ,e, ,e, ,e, , , ],
[e, , , ,e, ,e, , , , , , , , , , , ,e, ],
[e, , ,e, , , , , ,e, ,e, ,e, ,e, , , ,e],
[ , , ,e, ,e, ,e, , , , , , , , , ,e, , ],
[ ,e,e, ,e, , , ,e, ,e,e, ,e, ,e, ,e, , ],
[ , ,e, , , ,e, , , , , , , , ,e,e, ,e, ],
[ , , ,e, , , , ,e,e, , , , , , , , ,e, ],
[e, , , , , , ,e, , , ,e,e, ,e, , , , , ],
[ ,e,e, , ,e, , , , ,e, , , , , , ,e, , ],
[ , , ,e,e, ,e, ,e, , , ,e,e, ,e, ,e, ,e],
[e,e, , , , ,e, , , ,e, , , , , , , , , ],
[ , , ,e, , , , , ,e, , ,e, ,e, ,e, ,e, ],
[ , , , ,e, ,e, , , , , , , , , , , , , ],
[e,e, , ,e,e, , ,e, , ,e, ,e, ,e, ,e, ,e],
[e, ,e, ,e, , ,e,e,e, , ,e, , , ,e, , ,e],
[ , , , ,e, , , , , ,e, , , ,e, , , , , ],
[ , ,e, , , ,e, ,e, , , ,e, , , , ,e, , ],
[ , , ,e, ,e, ,e, , ,e,e, , ,e,e, , ,e, ]]
```
Output (This output is hand-made, and might not be the optimal output):
```
[[e, , , , , , ,e, ,e, , , ,e, ,e, ,e, ,e],
[ , ,e, , ,e, , ,n,e,e, , , ,n,e, , , , ],
[ ,n,e, , ,n,e, ,e, ,e, ,e, ,e, ,e, ,n, ],
[e, , , ,e, ,e, , , , , , , , , , , ,e, ],
[e, , ,e, , , , , ,e, ,e, ,e, ,e, , , ,e],
[ , ,n,e, ,e, ,e, , , ,n, , , , , ,e, , ],
[ ,e,e, ,e, ,n, ,e, ,e,e, ,e, ,e,n,e, , ],
[ , ,e, , , ,e, , , , , , , , ,e,e, ,e, ],
[ , , ,e, , , , ,e,e, , , , , , , , ,e, ],
[e, ,n, , , , ,e, , , ,e,e, ,e, , , , , ],
[ ,e,e, , ,e,n, , ,n,e, , , ,n, , ,e,e, ],
[ , , ,e,e, ,e, ,e, , , ,e,e, ,e, ,e, ,e],
[e,e, , , , ,e, , , ,e, , , , , , , , , ],
[ , , ,e, ,n, , , ,e, , ,e, ,e, ,e, ,e, ],
[ ,n, , ,e, ,e, , , , , , , ,n, , , ,n, ],
[e,e, , ,e,e, , ,e,n, ,e, ,e, ,e, ,e, ,e],
[e, ,e, ,e, , ,e,e,e, , ,e, , , ,e, , ,e],
[ , , , ,e, , , , , ,e, ,n, ,e, , ,n, , ],
[ , ,e, ,n, ,e, ,e, , , ,e, ,n, , ,e, , ],
[ , , ,e, ,e, ,e, ,n,e,e, , ,e,e, , ,e, ]]
```
Input:
```
[[e,e],
[e,e]]
```
Output:
```
null
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~558~~ ~~511~~ 509 bytes
```
from itertools import*
E=enumerate
L=len
def s(s):
q=[(x,y)for y,r in E(s)for x,k in E(r)if k==w]
for i in range(1,L(q)):
for c in combinations(q,i):
m=[l*1for l in s]
for p in c:
m[p[1]][p[0]]=n
for y,r in E([list(r) for r in' xxx ,xxxxx,xxnxx,xxxxx, xxx '.split(',')]):
for x,k in E(r):
o=(p[0]-x+2,p[1]-y+2)
if k==d and-1<o[0]<L(m[0])and-1<o[1]<L(m)and m[o[1]][o[0]]==e:
m[p[1]-y+2][p[0]-x+2]=d
if e not in ','.join([''.join(r)for r in m]):return(m)
print(s(m))
```
[Try it online!](https://tio.run/##jVTBTtwwEL37K0biEAcC6tIbIkcOlVDVQ29pVAUy23VJ7GCbbvbr6YwdOwFRqTnE8czzvPfGszud/MHoz697a0ZQHq03ZnCgxslYD@dCINRQYCGOvEIhNK@6ED2vcyFEj3uYOutQjt1U3giARzOdKEvbKzcNysuiKkqK742FUwXWHEFpQP0you08SsaHg/xYOtm0y4ZPPB46y3g6ljABd9VNE@pecr5cElypObVUwgoKWfQvVofootMq7X@SsKxV7Vkn1DV8NRojQUAFBG1xcEt4ZGUDnMMu6BpYFIGi1n95G98YK4qr30ZpSbAkeUx6V@bih15wY1kKwbyxwUpPL16W5ce3dS7u6kws7usBdTDtpGMRz3Uj5@pURqWhpXeU4e1cPcWtLakfT3V9JFOcUKHxnf6Fclfdy@cyuAm3wplHMz4o3XlltJPPlYpex7oZzne5RS40iLdTOLM0s5maXdvS@1Pb1nrTw0VZMyjnSVCIcqyAeZ6hmvmhtw5v/g7xYjNqber5O2/pJkwtmfZyvriuWMXl6eI6XUf030On@8vdrSHY7b0caSlTZBcivCUTJpgwwUSNeT6jO64bHTJVW/ciEiBo41kUiY333OTBKJNdGMlGHGBiE3EyHE/E69kXngMnxBnSI85oSAGqQFzRF@DyHeIRhEvig3esgbA5g8uaQHHFmOctrYixOnw/KJpAB8cDWqShBOc76x14A757Qugoo4aVAhNHJoHEAokm82AiWsGJkn6uoPEPWtgrrdwBe7iRKwukmrhh5GKwUmwgy4GsZH02qjZAzAo3wNwWjmdsJkq42MAlgviWKOnDVDrUhFV3vm3MWpLN1d2qKhPFFiAk9nc22TtC4so9qRYSTCIwzRfCW7JNP1e5my6t1Wlw4RvPM82Gxa7vHgbkf1Kx/j3HQf@Pyf0L "Python 3 – Try It Online")
It's very loopy, but I don't know enough about Python to optimize it further. I did learn some things from ovs's answer, so that was fun.
The input (modified to [make it easier to write test cases](https://codegolf.meta.stackexchange.com/questions/8047/things-to-avoid-when-writing-challenges/8077#8077)) expects ' ' or 'e', while the output uses ' ', 'n' for nullifier, and 'x' for a nullified emitter. The function takes the expected input that was described in the question.
I set the e, w, n, and d variables outside because they could be easily replaced with numbers and, if the input and output were modified to use numbers as well, it would print out the same thing. I used letters because they made it more readable while working on it.
Fun question, OP! Creeper World is great and it was a cool inspiration for the question :)
Edit: -47 bytes thanks to Erik the Outgolfer
[Answer]
# [Python 2](https://docs.python.org/2/), ~~267~~ 263 bytes
```
from itertools import*
m=input()
E=enumerate
e=[(x,y)for y,a in E(m)for x,e in E(a)if e]
for n in count():
for p in combinations(e,n):
k=[l*1for l in m]
for x,y in p:k[y][x]=2
all(e+any(8>(y-Y)**2+(x-X)**2for X,Y in p)for y,a in E(m)for x,e in E(a))>0>exit(k)
```
[Try it online!](https://tio.run/##hU5BbsMgEDybV3AEh0iJT1UkfMsfEiEOtFqryLAggiV4vWPs9tpqLjOzM6ONNX8HHNZ1SsFTmyHlENyLWh9Dyj3x0mJcMuPkLgEXD8lkICAVK6LyKSRahaEW6Z35XRYBhzTcThQ0aSY26yssuA3dCG1WPCz/adFkG/DFQOB27GapXH9tEdciXpPu2K1NxtusqlZFy4F0xjkGJ4OVfYysnp@874cTK@dHI630EM@99M@jfLyMUGxmM19XpS7iB1ps/Lrjb/6b128 "Python 2 – Try It Online")
`0` for emitter, `2` for nullifier and `1` for empty space.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~173~~ 168 bytes
```
t=ToExpression@$ScriptInputString
P=Position
p=t~P~0
q=t~P~2
Print@ReplacePart[t,Thread[p->LinearProgramming[1&/@p,(xBoole[Norm[x-#]^2<6]&/@p)/@q,1&/@q,0,Integers]]]
```
[Try it online!](https://tio.run/##ZYxNigIxEEb3uYYyKESMWbialkaYhTAMQd2FDIS2aAPmp6tLaBA9hDeYE84R2igOs3BRFO97X5W3tAdvyVW276nYxo8uIbSti6Ecbip0iVYhHWlD6ELNVKFi6yhblgq6qItgzWNLpnKByjWkg61AWSRNfLtHsDudJotPF8Ciwlij9T6/0rO3aZn4qPu9/ixjPID@iuh1NxmYb/k@N3c7npYNv/caLvgqENSArTGm708nkSOZR5w5e4D4A/kE@WL@b843 "Wolfram Language (Mathematica) – Try It Online")
Solves the largest test case [in 1 second](https://tio.run/##fVLBaoQwEL3nNyyLQsqmc@ipQij0sFCKsL2JBVlkK1QTYwqCuNceC/2DfuF@glW7u8ZkWobBkHmZefN8RapfsyLV@S7tex0@i4dGqqyuc1Hyq@1O5VJvSvmut1rl5Z5EYSTqXA9VIkN9iA6MVNMXiK/j2PNWnHtJEnoQDCfut5I@5mWWqkiJvUqLYmgS36zWXFK/OX593wvxlsVPQhVxc@0lL3B3m4zVYM0rOuIqyuim1Nk@U3XSHT8/AhINTDTXfd@2MFTngFOa5yk7Slp2Kc4QWDydYgm1@ixnjFBARtsBJhQQvgveZwJuyV71xBWQvZ3O2Fp2R5i52iBAHywUYIi2Rs3kyjDh7bWYs4h7A78EABnvSIatZTrCyBn6/4@9eAAWIgFunLNYYEDAsaTlAYwtoqvrV0Tlv5yF8O@6Hw).
Full program. As a function, it's shorter, [only 130 bytes](https://tio.run/##ZYtNCoJAAIX3XUMIhRGnWbQxY2gXRAzRTiYYbNQB58dxFoLoIbpBJ@wIplK0aPF4fHzvSeZKLpkTGRvzZPRJQnQjnNAqNok3kAHG9dIo9oYLNxXLOGHWDdfScnZPTbg/CcWZJVYXlkkpVJFu1hE2wG9fj@dB64qnZ21l2oYevaHdls42iHAN5l0NIDgqxwtuG0qD9UisUA7nuOvgpNAU2IPVAvAL6APoz/w@/fgG).
Use `0` for , `1` for `n` and `2` for `e`.
[This program](https://tio.run/##K0otycxLNPz/X8E@JpqrmiuWq5YrJCFVIcHI4P//6GgFHQWdVCBWiNXhUgDzFOC8VCgvFYscQl8sAA) can be used to convert from the input format in the challenge.
If there are no solution it will print error message `lpdim` like [this](https://tio.run/##HYzNCoJAFEb3vkYRBSOVi1YZErQIIoZ0N0ww2EUHmh@vNxBCH6I36Al7BFM331mcw2cUlWAU6Vz1PcWZOzUeoa61s8k8zVF7Olv/opRQ2yLgMXe1psEGPqaOd5ugmhgFfAgouYF/qhy4QhLEshJBPYQPDxdtQSFHV6AyZrgS28U68WzZ/D7fo3NPEFeHRjThTN6j/U6OdrVOKjZ2FduwsyUoAGspZd@/3xGLWjZt@wc), or `lpsnf` like [this](https://tio.run/##HYzNCoJAFEb3vkYRBSOZi1YZErQQIoZ0N0ww2EUHmh@vNxCkHqI36Al7BNP4FmdxDp9RVINRpEs1DJQU7th5hLbVzqbzvETtKbP@QTmhtlXAE@5aTaMNfEIv/oqC5s844GNA6QX8XZXAFZIgVtQI6iZ8uD9pCwo5ugqVMeOV2CzWqWfL7vv@HJy7gzg7NKILZ/Ia77Zysqt12rCpa1jEMktQAbZSymHo@5hNi57PHw).
Version using `Outer` (although more readable) is 2 bytes longer, despite the short name of `Outer`: [Try it online!](https://tio.run/##HYy9CsIwFEb3vobSKaLN4GSlCA6CaLDdQoRQLzVgfnpzBUHqq8fo9ME5h89quoPVZHqdEtWd378CQozGu2be9mgCHVx4Ukto3FCIWvhoKNsi1PQRn1Ux/pcXIgfUXCA8dA9CI0li3R1B32RYbI/GgUaBfkBtbb6SVblsAjs/CVDuvH@APHm0craYcXXlm7Uq2cgCqxT7lSNbsYMjGACjUiql95tnxKfpCw "Wolfram Language (Mathematica) – Try It Online")
---
Explanation.
Note that this can be reduced to an integer linear programming problem.
Each `e` cell is fixed at 2, each empty cell is an integer variable, which can be either `0` (empty) or `1` (nullifier). The list of coordinates of variables are stored in variable `p`. (the `Position`s in `t` that is `0`)
The objective is to minimize the number of nullifier used, so the sum of those integer variables must be minimized. (`1&/@p`, a vector consists of all `1` and with length equal to `p`'s length, indicates the objective function)
The constraints are, for each emitter (`2`) (their positions are stored in `q`), there must be at least a nullifier in the range around it, or to be precise, have an Euclidean distance to it of at most \$\sqrt 6\$.
This is formulated with the matrix `m` = `(xBoole[Norm[x-#]^2<6]&/@p)/@q` (for each element in `q`, create a row with elements being `1` if the squared distance (`Norm`) to the corresponding coordinate in `p` is less than `6`) and the vector `b` = `1&/@q`.
After that `ReplacePart` and `Thread` "applies" the variable values to `t` and print it.
] |
[Question]
[
AKA: Generate Clickbait From an Array.
Given an array of integers, generate some cringe-worthy clickbait based on its arrangement and length:
* If it's 20 elements or less, you can make a Top X List. *Parameters: length of the array.*
* Prime numbers are celebrities, so anytime two of them are next to each other it'll pass as gossip. *Parameters: the two adjacent primes in the order they appear in the array.*
* If any number appears twice or more in the array, then it's shocking and unbelievable and everyone needs to hear about it. If multiple numbers appear twice, make a news story for each one. Only print this once per unique number. *Parameters: occurrence of the number measured by total appearance.*
* If you see 3+ elements in ~~sorted~~ [monotonically increasing](https://en.wikipedia.org/wiki/Sequence#Increasing_and_decreasing) order, followed by a sudden decrease, then tell of how they're sorted and tease about what happens next. Only do this once per straight. *Parameters: length of the straight.*
These are the respective clickbaits you should use:
```
The Top {{N}} Array Elements
{{N1}} And {{N2}} Were Spotted Together, You Won't Believe What They Did
These {{N}} Elements Will Blow Your Mind
{{N}} Elements Sort Themselves, Find Out What Comes Next
```
Remember, you represent a cheap media company, so you'll need to milk this and print every possible title. If there are 2 identical titles, print them both.
For example, if you're given this array…
```
1,2,3,4,2,1,1,5,6
```
You should output all of these, in arbitrary order:
```
The Top 9 Array Elements
2 And 3 Were Spotted Together, You Won't Believe What They Did
These 2 Elements Will Blow Your Mind
These 3 Elements Will Blow Your Mind
4 Elements Sort Themselves, Find Out What Comes Next
```
Note the *lack* of this title:
```
3 Elements Sort Themselves, Find Out What Comes Next
```
As code golf, the shortest answer in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 142 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
I>-ṣ0ṖS€ỊÐḟ‘ɓĠL€ḟ1,ɓ¹ƝÆPẠ$ÐfW;ɓLẋ<¥21W;ż@€"“æƥu®ụ³Km&|°ẓz“ṿ$¥{d3ɓFȤSJẎVḍnṃ*¹0Ḟ¬ȤɲƝċƲạB'ɼɓ.€⁺Ƒ“¢ßUṡʠx\~⁻ḅėʠAƓḳ¶e<“½ė!Ƙ¥Ḍ3]⁷ṀƭȮþċ⁽?ṫĠƁÆȦØ⁾Ż»ṣ€⁷¤
```
A monadic link accepting a list of integers, returning a list of lists of clickbaits (each of which is a list of characters and integers). For a full program printing line-feed separated clickbaits just add `ẎY` to the end.
**[Try it online!](https://tio.run/##VU9dSwJBFP0thRTEFH6UEkpfD0HlQyAlUb5lD2G9BX0RbpFBVhgD6UPmWq4vmYRCzuyqwcw67Pov7vyRbeotDhy49x7OOXc/ncmceN7K3CTQNz/Qp4S8bIB1ywtAKjJbcrGtx39XpBJALmZUlHluHUzdxwt7yaiL42DmY8wIBpLRQXdBKUdl9pnXhXHEmmAZrL12MHbOPsHEp@oA9NvHjLPdkIuXnVpiFcyHTSD3h0CvJhj1A3lhDafmtkTZzosWmNWlcbfr4inlKzVTPCoL9sorG0CrQ/1450JqFpBruzjUFwUG0mZf6divpmcXR0SJGUDuQimpdYBmxYfT5H07L7XePNB3Wxcazzl1XpJaf2AxS/3/l9JhNY/fqGJbnrc9jUIoiAIKMyiMIoojaFZN4f9I/QA "Jelly – Try It Online")** (Footer makes a single list of clickbaits and then separates them with new-lines.)
...or see **[the example](https://tio.run/##HY9PSwJRFMU/SyEFMYWj1Ubp3yKoXARSEuUuW4S1C/pHOEUGWWE8SBfZjOW4ySQU8r0ZNXhvfMzzW9z3RaZnXLiLc36ce@5hJps9C4K1hWkgH2EgL0l53QD3nhUBmzJXFsizEiMJm7omECW8wvKb4FghVjxIxQRKgFOIUzuip2KD7pIix2XuldW5fUKb4Nq0vXE0cUm/wUHnygDyG6L2xX5UoFW/llwH52kb8OMxkJspSsKA32jDr4kWr3gF3gKnujIpugLNqFxpOPxZRdB3Zm4BqQ6t070rabiAb73S0FrmCHCb/mTiI6bnlcZ4mdqAH6JpaXSA5PiX32R9ryCN3iKQT8/iBsv7dVaWRn/gUlf9/3@lQ2sBu1PFdoJgV9ciWlSbVVtXM6fNp/8A "Jelly – Try It Online")** given in the question.
### How?
The 99 right-most bytes of this Link form a nilad (a function with zero arguments, i.e. a constant):
```
“...“...“...“...»ṣ€⁷¤
¤ - nilad followed by link(s) as a nilad:
“...“...“...“...» - list of compressed strings (the four clickbait-texts with the
- integers replaced with line-feed characters)
⁷ - literal line-feed character
ṣ€ - split-at for €ach (read to interweave with the integers)
```
Let's label these text-parts as `X`, now the Link is:
```
I>-ṣ0ṖS€ỊÐḟ‘ɓĠL€ḟ1,ɓ¹ƝÆPẠ$ÐfW;ɓLẋ<¥21W;ż@€"X - Link: list of integers Z
- # get the monotonically increasing runs:
I - incremental differences of Z
>- - greater than -1 (vectorises)
ṣ0 - split at zeros
Ṗ - pop (discard final run)
S€ - sum each (length - 1 for all runs)
Ðḟ - filter discard if:
Ị - insignificant (discard any 0s or 1s)
‘ - increment (yielding all run-lengths >= 3)
ɓ - new dyadic chain with that on the right
- # get the multiplicities:
Ġ - group indices of Z by value
L€ - length of €ach
ḟ1 - filter discard 1s
, - pair with right (the run-lengths)
ɓ - new dyadic chain with that on the right
- # get the prime-pairs
Ɲ - for each pair in Z
¹ - identity (do nothing)
Ðf - filter keep if:
$ - last two links as a monad:
ÆP - is prime? (vectorises)
Ạ - all?
W - wrap in a list
; - concatenate with right ([multiplicities,runs])
ɓ - new dyadic chain with that on the right
- # get top count as a list
L - length
21 - literal 21
¥ - last two links as a dyad
< - less than? (1 if 20 or less, else 0)
ẋ - repeat ([length] if 20 or less, else [])
W - wrap in a list (i.e. [[length]] or [[]])
; - concatenate with right ([[prime pairs],[multiplicities],[run-lengths]])
- ...now we have [[length],[prime pairs],[multiplicities],[run-lengths]]
"X - zip with X (the text-parts)
€ - for each (item in the current list):
ż@ - interleave with swapped arguments
```
[Answer]
# Java 10, ~~467~~ ~~457~~ ~~456~~ 453 bytes
```
a->{int l=a.length,i=0,p=0,P=0,m[]=new int[999],t;String e=" Elements ",r=l<21?"The Top "+l+" Array"+e+"\n":"";for(;i<l;r+=i>0&&p(p)>1&p(t=a[i-1])>1?p+" And "+t+" Were Spotted Together, You Won't Believe What They Did\n":"",m[a[i++]]++)if(p<(p=a[i]))P++;else{r+=P>2?P+e+"Sort Themselves, Find Out What Comes Next\n":"";P=1;}for(;l-->0;r+=m[l]>1?"These "+m[l]+e+"Will Blow Your Mind\n":"");return r;}int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}
```
Assumes the input-array will contain values `0 < N < 1000` (`[1,999]`).
[Try it online.](https://tio.run/##pVRrT9swFP3Or7iKNEiIW@qkD9KQorHHN1glkNCU5UPWmmLmOJnjlqEqv51dJy2PCbp1KHUc177nnnt87Jt0kbZupj/uJyItSzhNuVzuAHCpmbpKJwzOzBDgXCsuZzCxcSZOIHVC/LvChr8zkBDBfdoaLXEWRJS2BZMzfU141CEFtjG2LE4iyW4NdBwEQUJ0uAJlkQWfBMuY1CVYREXiyKPH1sU1g4u8AMsVrgXvlUrvLJe51jdpDS0rvMqVHfIjESo34qPO7m5hF86IYqejNOYtmuDouDChcoogGr8umWJwXuRasyliz5i@ZorA13wOl7nc03DCBGcLBpfXqQYkcAcf@bRJiAUgrOsmies6/MoujuzCJEocZ@y6IRMlWyKV8cg7Hhua57mqIbKSiQUrCXzmyOPLXDfgH/KMlXDGfulVPeOIhlVdlGi1Rh1TVhaLZNQoUTIswYwN9CUXAk5EfmuYKzhF4AbECRXTcyVBhVVo9qIw@wXSWRpg88kjD0WToYzkOyzmiB53hvIhTIbVPUAx/y74BEqdauwWOZ9Chr6wm@2Kk9RpPGHMAhluvdlWM7BrVwAc7NcdwF7jgz2Y5WXJiyEE6wl9m0OhOGrwOLn0iF@tF5Ts55zJCXuc7kJMCS4h3WS9KJ9M5ko9XVYOwQebOpCi2B7YnlOv3T9oXHxXapa187luY3KphbSztmxP7LUxk@UqBb4pPj3Sr5xVVS8E/7Ve2n@9YKS67BFKK2L6numMAKSmvqR0gxgY2oPYBBOKRH1Cu0kddghxQx@JkwE5xBWbxeqC3XNIoxRZi@ZvK9ozJpi7R/5kgcW8RUevs1lHn3hGv0EtY61fjww2yVebqabXCOcbOQck@Adr1WoZ0QKw@4@iDbYVrYsSPbgMc9f5cdR//rxJN39LTh5u2nYZX9SJUqNQrYz5pJ3/MFSHbP16m8U2Xk00QGvT1Ync4jZZhb3pDglevxP7EJtz1jdnrPNwC/Qac6OZBngq/WRL0s8QyVMkbJ7xLIrdJ16f@JR0cTY4XBVY7VT3vwE)
```
a->{ // Method with integer-array parameter and String return-type
int l=a.length, // Length of the input-array
i=0, // Index-integer
p=0, // Previous item, starting at 0
P=0, // Sequence-counter, starting at 0
m[]=new int[999], // Element-counter array, starting filled with 0s
t; // Temp-integer to reduce the byte-count
String e=" Elements ", // Temp-String " Elements " to reduce byte-count
r=l<21? // If the size of the input-array is 20 or less:
"The Top "+l+" Array"+e+"\n"
// Start the result-String with 'length' gossip-line
: // Else:
""; // Start the result-String empty
for(;i<l // Loop over the input-array
; // After every iteration:
r+=i>0&& // If this is not the first item,
p(p)>1&p(t=a[i-1])>1?
// and the current and previous items are both primes:
p+" And "+t+" Were Spotted Together, You Won't Believe What They Did\n":"",
// Append the 'two primes' gossip-line
m[a[i++]]++) // Increase the counter of the current value by 1
if(p<(p=a[i]) // If the previous item is smaller than the current:
P++; // Increase the sequence-counter by 1
else{ // Else:
r+=P>2 // If the sequence-counter is 3 or larger:
P+e+"Sort Themselves, Find Out What Comes Next\n":"";
// Append the 'sequence' gossip-line
P=1;} // Reset the sequence-counter to 1
for(;l-->0; // Loop over the Element-counter array
r+=m[l]>1? // If this element occurred at least two times:
"These "+m[l]+e+"Will Blow Your Mind\n":"");
// Append the 'occurrence' gossip-line
return r;} // Return the result
// Separated method to check if the given number is a prime
// If `n` is a prime, it remains the same; if not: either 1 or 0 is returned
int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}
```
[Answer]
* still golfing but help will be much appreciated
# [JavaScript (Node.js)](https://nodejs.org), 397 bytes
```
a=>a.map(x=>(l<=x?s++:(s>2&&r.push(s+" Elements Sort Themselves, Find Out What Comes Next"),s=1),P(x)&&P(l)&&r.push(l+` And ${x} Were Spotted Together, You Won't Believe What They Did`),c[l=x]=-~c[x]),c=[s=l=r=[]])&&c.map((x,i)=>x>1&&c.indexOf(x)==i&&r.push(`These ${x} Elements Will Blow Your Mind`))&&[...r,...a[20]?[]:[`The Top ${a.length} Array Elements`]]
P=(n,i=1)=>n>1&&++i*i>n||n%i&&P(n,i)
```
[Try it online!](https://tio.run/##PZDbSgMxEIbvfYpBtCZuXGw9XIhZ8XinFhSKhMCG7bQbSZMlSWuKh1evWYUSGEjC/803865WKjRed/HIuiluZnyjeKXKhepI4hUxlzxdhaK4IKEaDQa@7JahJaHYhXuDC7QxwIvzEV5bXAQ0KwwMHrSdwvMywqRVEW7dAgM8YYq7lAU@pGxMEh0MxsTQLdAUNVzn1N5n@oYJeoSXzsWIU3h1c4wtegZvbgkTZw8i3KDRuMJ/fu68hjs9rSlrhOFJ8qOfRiSZr1wEbrjnQsrcqvkbiiSmKa9SNexfsimm51kW4lxvberMDPgvsx1zoo2BG@M@ehEPjzla04wVZVl6losSo2N5JeSF6PNZvMsEVRq089h@w7X3ar3F1VLujDmxTOeN8Mr2OkWhD3Vlv77svu73kz/ppnE2OIOlcXMyI2LIRuyEneY6zOeMnUtKdza/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~351~~ ~~350~~ ~~349~~ 347 bytes
```
a=>a.map((x,i)=>c[s=x>=l?-~s:++s>2&&(t+=s+` Elements Sort Themselves, Find Out What Comes Next
`),P(x)&P(l)&&(t+=l+` And ${x} Were Spotted Together, You Won't Believe What They Did
`),l=x]=-~c[x],t=a[20]?'':`The Top ${a.length} Array Elements
`,c=[s=l=P=(n,i=n)=>n%--i?P(n,i):1/i])+c.map(x=>x>1&&(t+=`These ${x} Elements Will Blow Your Mind
`))&&t
```
[Try it online!](https://tio.run/##PZDRasIwFIbvfYpzsWlKU7c6twtHKrrNu22CgoxSaKgHzUiT0kQXGfrqXbqCN@EEDt/5/v@bH7kpalHZSOktNgvWcJbwYckrQhwVAUuK1DCXMDmNLmYShiYZ9fvEhsyEObxJLFFZAytdW1jvsTQoj2goLITawufBwmbPLbzoEg18oLO9PKBL4oL@ksigA0kPmvntm193hg3WCKtKW4tbWOsd2j3WFL70ATZaDSzMUQo8Ysf1F0/wKrYtVTKXsehSpC6jlvF0dJ9NB4NJ7nc8qPJ4PpSodnZ/hlld89PVvpfTgvmUki0ZUVQw5WOr2ygS02X7DybxnciCsPivxbHEJXGn3sINdubXLjZCSphL/dNa1/Dum/B@PqxtngutjJY4lHpHFiSN6Yg@0LF/Y9rOj/SJjrMgaP4A "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
I got to wondering yesterday if I could write a program to comb through a given word search and output the answers. It was actually surprisingly easy. Now I wonder just how small we can get.
# Rules
* Your first input is a string or collection of n lines, each of which is n characters long
* Your second input is a list of words in any format to find in the puzzle
* All words in the search list are guaranteed to be in the puzzle
* Words can be oriented in any of the four cardinal directions, as well as diagonally both forwards and backwards
* Only uppercase A-Z characters will be present in the puzzle
* Your code must find every word in the the search string, and output the coordinate position of the starting letter, where 0,0 is the top left character.
* In the event that you locate more than one instance of the same word, you may handle it however you like. Output it multiple times, or only once, it's up to you
# Examples/Test Cases
Given the following board:
```
ABCD
EFGH
IJKL
MNOP
```
And the following search string:
```
ABCD,CGKO,POMN,NJF,AFKP,CFI,LGB,MJGD
```
Your program should output the following, in any order:
```
ABCD at 0,0
CGKO at 0,2
PONM at 3,3
NJF at 3,1
AFKP at 0,0
CFI at 0,2
LGB at 2,3
MJGD at 3,0
```
As always, shortest answer wins
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 154 152 150 141 bytes
* thanks to Arnauld for reducing by 2 bytes
returns array of locations (it was a string with new lines before)
```
(b,w)=>w.map(s=>[...b].map((_,p)=>[1,-1,r=b.search`
`,-r,~r,++r,-~r,~r].map(d=>[...s].every((c,i)=>c==b[p+d*i])?s+=" at "+[p/r|0,p%r]:0))&&s)
```
[Try it online!](https://tio.run/##PY5db4IwFIbv@ysMyUw7Dh3o3ZK6KA4GKnBPyMqXG8ZB0xLNksW/zqhku3t6@p7nPaf8kqtSNqK32q6qhyMbcAFXwlZX@pULrNgqpZQW2f2F30GMX6kDlgOSFVTVuSw/OeJgSbhJME0J1k3jtFBN6yqj9aWW3xiX0IyCkrEiFWb12GTkRZnMmOX9zDBT8SR/bBAPMnu2CZnPFRnKrlXduabn7gMfMV9v3C169fw3FIS7PTpEccLB0FNw/V0MSRwdIAo9WHu7BFwvgL2/gUPobw2qxLnpOXBCT13TjkczdvfpchtspAUTL5D2aF7CEo26CR2krf9xL/hLjx0aF2NYV01pm5PhFw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 213 bytes
```
lambda a,W:[(w,i,j)for w in W for i in R(L(a))for j in R(L(a[0]))for U in R(9)if U-4and g(i,j,U/3-1,U%3-1,a).find(w)==0]
g=lambda i,j,u,v,a,s='':L(a)>i>=0<=j<L(a[0])and g(i+u,j+v,u,v,a,s+a[i][j])or s
L=len;R=range
```
[Try it online!](https://tio.run/##PU5Nc4IwFLznV@TSSTI8rf241BpnFAtFEa2W8YAc0uGjYWxwAGX66ylR7OXNvt19u@/4W33n6rFJ@L45iJ@vSGABu2FAa5CQsSQvcI2lwjusodRwQ10q2EXK/vdgEF4p/0q9MJlgv/csVIRT2kaBf//UewD/Tk/B@olUEa0Z54MQpbyr1r4TnEFAyQkZ6p6xHPPBiGejrqQLNE6QGeeb2RCBDIMsZO0DJXL5IVavG14IlcZNFZdVXGCOCSGTqTlDb5b9jpz5wkVLb7VGH5vtZyv1y@NBVpShOi@iUtu1GUx7sYL1yluCN7dgYi3WYFoOuPYU2gRYzu0ZbD3ndk6AMHQspKow2SvSz3Kp6PWDG590O1yKWPMH "Python 2 – Try It Online")
`g` takes a starting location `i,j` and a direction `u,v` and via recursion extracts the string starting at that location in that direction.
`f` then visits each starting location `i,j` and direction `U/3-1,U%3-1` and checks each word `w` to see if the resulting string starts with `w`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~149~~ 147 bytes
```
def g(b,w):h=b.find('\n')+1;return[f'{y} at {i//h},{i%h}'for y in w for i in range(len(b))for d in(1,h+1,h,h-1,-1,~h,-h,1-h)if y==b[i::d][:len(y)]]
```
[Try it online!](https://tio.run/##HY1Bi4MwFITv@RWhsCShT4vszcVDa1e3Wqt310MlagIlSswiIu5fd@PCPBg@ZuYNsxG9et823rS4ozVMzBdB7bZScUq@FWFH70M35kersiXLvOKnwYs8ncQKi3wTK2l7jWcsFZ7wbuVu9VN1DX01itaM7ZRbSj0QR3sgHA@sfgU4AjxHMNniOQjqUvo@r0p/782sqrZOS44DTAhB50t4RZ9R/IVuSXpH2SMvkOXuaLQcKENo6jUfbfiwJyGM0xyK/JHBI4ngHKUFhNEN7vEFsiS@HtxxeElDCRBbHbRUhnZ0fwf4f4ix7Q8 "Python 3 – Try It Online")
### Ungolfed version
```
def g(b,w):
h = b.find('\n') + 1 # width of a row plus the '\n'
a = []
for y in w: # iterate over the words
for i in range(len(b)): # iterate over the game board
for d in(1,h+1,h,h-1,-1,~h,-h,1-h): # for each possible direction
if y==b[i::d][:len(y)]: # see if the word matches
a.append(f'{y} at {i//h},{i%h}')
return a
```
The main idea is that `b[i::d]` selects a slice from the game board. The slice starts as position `i` and extends in the direction `d`. For example, `d = h+1` corresponds to the southeast diagonal, whereas `d = ~h`, which is the same as `-h-1`, corresponds to the northwest diagonal. `[:len(y)]` chops the slice off at the same length as the word being searched.
] |
[Question]
[
*This challenge is from an admission test to a closed number cyber security course. Anyway it doesn't have to do with cyber security, it's just to test the students logical and coding skills.*
## Task
Write a program that removes entries from an array so that the remaining values are sorted in a strictly decreasing order and their sum is the maximized among all other possible decreasing sequences.
## Input and Output
**Input** will be an array of integer values **strictly greater** than `0` and all **different from each other**.
You are free to choose whether to read input from file, command line or stdin.
**Output** will be a **descending-sorted** subarray of the input one, whose sum is greater than any other possible descending-sorted subarray.
***Note:*** *`[5, 4, 3, 2]` is a subarray of `[5, 4, 1, 3, 2]`, even if `4` and `3` are not adjacent. Just because the `1` was popped.*
## Bruteforce solution
The simplest solution of course would be iterate among all possible combinations of the given array and search for a sorted one with the greatest sum, that would be, in **Python**:
```
import itertools
def best_sum_desc_subarray(ary):
best_sum_so_far = 0
best_subarray_so_far = []
for k in range(1, len(ary)):
for comb in itertools.combinations(ary, k):
if sum(comb) > best_sum_so_far and all(comb[j] > comb[j+1] for j in range(len(comb)-1)):
best_subarray_so_far = list(comb)
best_sum_so_far = sum(comb)
return best_subarray_so_far
```
Unfortunately, since checking if the array is sorted, and calculating the sum of it's elements is  "\Theta \left( k \right )") and since this operation will be done !%7D "\binom{n}{k} = \frac{n!}{k!(n-k)!}") times for 
!%7D&space;%5Cright)&space;=&space;%5CTheta(n&space;2%5E%7Bn-1%7D)&space;=&space;%5CTheta(n&space;2%5E%7Bn%7D) "\Theta\left(\sum_{k=1}^{n} k \frac{n!}{k! (n-k)!} \right) = \Theta(n 2^{n-1}) = \Theta(n 2^{n})")
## Challenge
Your goal is to achieve a better time complexity than the bruteforce above. The solution with the smallest asymptotic time complexity is the winner of the challenge. If two solutions have the same asymptotic time complexity, the winner will be the one with the smallest asymptotic spatial complexity.
***Note:*** *You can consider reading, writing and comparing **atomic** even on large numbers.*
***Note:*** *If there are two or more solutions return either of them.*
## Test cases
```
Input: [200, 100, 400]
Output: [400]
Input: [4, 3, 2, 1, 5]
Output: [4, 3, 2, 1]
Input: [50, 40, 30, 20, 10]
Output: [50, 40, 30, 20, 10]
Input: [389, 207, 155, 300, 299, 170, 158, 65]
Output: [389, 300, 299, 170, 158, 65]
Input: [19, 20, 2, 18, 13, 14, 8, 9, 4, 6, 16, 1, 15, 12, 3, 7, 17, 5, 10, 11]
Output: [20, 18, 16, 15, 12, 7, 5]
Input: [14, 12, 24, 21, 6, 10, 19, 1, 5, 8, 17, 7, 9, 15, 23, 20, 25, 11, 13, 4, 3, 22, 18, 2, 16]
Output: [24, 21, 19, 17, 15, 13, 4, 3, 2]
Input: [25, 15, 3, 6, 24, 30, 23, 7, 1, 10, 16, 29, 12, 13, 22, 8, 17, 14, 20, 11, 9, 18, 28, 21, 26, 27, 4, 2, 19, 5]
Output: [25, 24, 23, 22, 17, 14, 11, 9, 4, 2]
```
[Answer]
# [Haskell](https://www.haskell.org/), \$O(n \log n)\$ time, \$O(n)\$ space
```
{-# LANGUAGE MultiParamTypeClasses #-}
import qualified Data.FingerTree as F
data S = S
{ sSum :: Int
, sArr :: [Int]
} deriving (Show)
instance Monoid S where
mempty = S 0 []
mappend _ s = s
instance F.Measured S S where
measure = id
bestSubarrays :: [Int] -> F.FingerTree S S
bestSubarrays [] = F.empty
bestSubarrays (x:xs) = left F.>< sNew F.<| right'
where
(left, right) = F.split (\s -> sArr s > [x]) (bestSubarrays xs)
sLeft = F.measure left
sNew = S (x + sSum sLeft) (x : sArr sLeft)
right' = F.dropUntil (\s -> sSum s > sSum sNew) right
bestSubarray :: [Int] -> [Int]
bestSubarray = sArr . F.measure . bestSubarrays
```
### How it works
`bestSubarrays xs` is the sequence of subarrays of `xs` that are on the efficient frontier of {largest sum, smallest first element}, ordered from left to right by increasing sum and increasing first element.
To go from `bestSubarrays xs` to `bestSubarrays (x:xs)`, we
1. split the sequence into a left side with first elements less than `x`, and a right side with first elements greater than `x`,
2. find a new subarray by prepending `x` to the rightmost subarray on the left side,
3. drop the prefix of subarrays from the right side with smaller sum than the new subarray,
4. concatenate the left side, the new subarray, and the remainder of the right side.
A [finger tree](http://hackage.haskell.org/package/fingertree) supports all these operations in \$O(\log n)\$ time.
[Answer]
# Perl
This should be O(n^2) in time and O(n) in space
Give numbers separated by space on one line to STDIN
```
#!/usr/bin/perl -a
use strict;
use warnings;
# use Data::Dumper;
use constant {
INFINITY => 9**9**9,
DEBUG => 0,
};
# Recover sequence from the 'how' linked list
sub how {
my @z;
for (my $h = shift->{how}; $h; $h = $h->[1]) {
push @z, $h->[0];
}
pop @z;
return join " ", reverse @z;
}
use constant MINIMUM => {
how => [-INFINITY, [INFINITY]],
sum => -INFINITY,
next => undef,
};
# Candidates is a linked list of subsequences under consideration
# A given final element will only appear once in the list of candidates
# in combination with the best sum that can be achieved with that final element
# The list of candidates is reverse sorted by final element
my $candidates = {
# 'how' will represent the sequence that adds up to the given sum as a
# reversed lisp style list.
# so e.g. "1, 5, 8" will be represented as [8, [5, [1, INFINITY]]]
# So the final element will be at the front of 'how'
how => [INFINITY],
# The highest sum that can be reached with any subsequence with the same
# final element
sum => 0,
# 'next' points to the next candidate
next => MINIMUM, # Dummy terminator to simplify program logic
};
for my $num (@F) {
# Among the candidates on which an extension with $num is valid
# find the highest sum
my $max_sum = MINIMUM;
my $c = \$candidates;
while ($num < $$c->{how}[0]) {
if ($$c->{sum} > $max_sum->{sum}) {
$max_sum = $$c;
$c = \$$c->{next};
} else {
# Remove pointless candidate
$$c = $$c->{next};
}
}
my $new_sum = $max_sum->{sum} + $num;
if ($$c->{how}[0] != $num) {
# Insert a new candidate with a never before seen end element
# Due to the unique element rule this branch will always be taken
$$c = { next => $$c };
} elsif ($new_sum <= $$c->{sum}) {
# An already known end element but the sum is no improvement
next;
}
$$c->{sum} = $new_sum;
$$c->{how} = [$num, $max_sum->{how}];
# print(Dumper($candidates));
if (DEBUG) {
print "Adding $num\n";
for (my $c = $candidates; $c; $c = $c->{next}) {
printf "sum(%s) = %s\n", how($c), $c->{sum};
}
print "------\n";
}
}
# Find the sequence with the highest sum among the candidates
my $max_sum = MINIMUM;
for (my $c = $candidates; $c; $c = $c->{next}) {
$max_sum = $c if $c->{sum} > $max_sum->{sum};
}
# And finally print the result
print how($max_sum), "\n";
```
[Answer]
This answer expands on Ton Hospel's one.
The problem can be solved with dynamic programming using the recurence
$$
T(i) = a\_i + \max \left[ \{0\} \cup \{ T(j) | 0 \leq j < i \wedge a\_i \leq a\_j \} \right ]
$$
where \$(a\_i)\$ is the input sequence and \$T(i)\$ the maximally achievable sum of any decreasing sub-sequence ending with index \$i\$. The actual solution may then be retraced using \$T\$, as in the following rust code.
```
fn solve(arr: &[usize]) -> Vec<usize> {
let mut tbl = Vec::new();
// Compute table with maximum sums of any valid sequence ending
// with a given index i.
for i in 0..arr.len() {
let max = (0..i)
.filter(|&j| arr[j] >= arr[i])
.map(|j| tbl[j])
.max()
.unwrap_or(0);
tbl.push(max + arr[i]);
}
// Reconstruct an optimal sequence.
let mut sum = tbl.iter().max().unwrap_or(&0).clone();
let mut limit = 0;
let mut result = Vec::new();
for i in (0..arr.len()).rev() {
if tbl[i] == sum && arr[i] >= limit {
limit = arr[i];
sum -= arr[i];
result.push(arr[i]);
}
}
assert_eq!(sum, 0);
result.reverse();
result
}
fn read_input() -> Vec<usize> {
use std::io::{Read, stdin};
let mut s = String::new();
stdin().read_to_string(&mut s).unwrap();
s.split(|c: char| !c.is_numeric())
.filter(|&s| !s.is_empty())
.map(|s| s.parse().unwrap())
.collect()
}
fn main() {
println!("{:?}", solve(&read_input()));
}
```
[Try it online!](https://tio.run/##bVTbctowEH3nK5Y8eOQpcYjb9OIU@tA/SGf6wjCMYpawGVl2dAFS4NvpysYEk2iQdTlnpbNHEsZbdzgsNNhSrVBIYzKIJt7SP5zGcD2Gv5j/rIdj2PaAi0IHhXfgHhWMApxlGtcivq/Rmxv4XRaVdwhOPiqENbklFHJDhS/A@sJCuQCpX2ElFc3B4otHnSOgnpN@ateooyQ80Qo1kJ7jBiipwUVpgHgKhknCahOFWsRHaSd5csPSBDMoPgGhJAtSDo3YRc874OjJ8xTGo7pH0wtqISuxYxrnybR34EZcTHm9NrKalUYMj16EwtFJ5e1SBE2f2p0afN9m@4B5qa0zPndsDZSVo0KqkzdJx3f2kJML61JIJW60nG0fDeMkV6XG9kzaSEUFOY4ddqcNWq/cxVl2vRbnZseJwVXHc1rULtEURqNaXxQdMw3uNttuO261UhrWfQcLC1x/DDVSG0M7Vr7Z2XyltWjcDF/6gpcbQHskxwU4ATT2ZFAz29v3evwQDMr5jDRfYfHxA/AWwbp5llGZZdsHpg/CmPS@66vl/P44w7e680Jqqggm8j6unNmaIqI6pD3HEzmxlSIndnkG@VKaHfTzhOxM@wIN5XwYvfd32zLLBhYWlXvtcOpLzbhNKlkbcNrvjJSXSmHO6R8dKSS9vbGK1Tql@@Jqm/3aXw2OfxzRuW0xq9/3DodJejeAW66fB/B1AOkX7g255eE3BvjHo9uA/OA25cpIyu137gYGB6SBwtTA4Ok0VB6mIYopgcEIo3fT/w "Rust – Try It Online")
] |
[Question]
[
Your task is to, given a map as input, zoom it out or in, depending on the scale. Note that the scale given is the scale by which to zoom *out*, so a scale between 0 and 1 will actually zoom in.
For example, given the following (badly made) map:
```
..____....
../OOO\...
..\OO/\...
..........
```
And a scale factor of 2, you should first separate it into 2x2 sections:
```
.. | __ | __ | .. | ..
.. | /O | OO | \. | ..
----------------------
.. | \O | O/ | \. | ..
.. | .. | .. | .. | ..
```
And in each section find the most common character:
```
.__..
.....
```
Note that there was an ambiguous section:
```
__
OO
```
I chose to use `_` for this section, but using `O` would have been perfectly acceptable too.
If, for example, you were given the scale factor of 4, you would split it into 4x4 sections, like so:
```
..__ | __.. | ..
../O | OO\. | ..
..\O | O/\. | ..
.... | .... | ..
```
As you can tell, the map doesn't perfectly fit into 4x4 sections, but that's fine, as we can just lower the size of the section at the side.
Also, whenever we need to cut off our maps, we cut off at the bottom or on the right side.
The resulting map would look like so:
```
...
```
What an interesting map!
For scale factors below 1, such as 0.5, the process is simpler as we zoom in instead. Take this map:
```
./O\.
.\O/.
```
Zooming with a scale of 0.5:
```
..//OO\\..
..//OO\\..
..\\OO//..
..\\OO//..
```
Note that whenever your zoom factor is less than `1`, the following will always be true: `1/(zoom factor) % 2 == 0`. When it is above `1`, the only guarantee you have is that it will be a whole number. When it is `1`, the map should stay the same.
## Examples:
```
4
/OO\
|OO|
|OO|
\OO/
O
0.25
ABCD
AAAABBBBCCCCDDDD
AAAABBBBCCCCDDDD
AAAABBBBCCCCDDDD
AAAABBBBCCCCDDDD
1
My zoom
should
not change
My zoom
should
not change
```
You may also take the map as a newline-separated array.
[Answer]
# Mathematica, 105 bytes
```
If[#<1,ArrayFlatten[#2/.n_String:>Table[n,1/#,1/#]],Map[First@*Commonest,#2~Partition~UpTo@{#,#},{2,3}]]&
```
The input is (scale, array of characters). The scale must be an integer or an exact fraction.
### Explanation
```
If[#<1, ..., ... ]
```
If the first input is less than 1...
```
#2/.n_String:>Table[n,1/#,1/#]
```
Replace all Strings in the second input into a square array, with length 1/(first input)
```
ArrayFlatten[ ... ]
```
Flatten the result into a 2D array.
```
If[#<1, ..., ... ]
```
If the first input is not less than 1...
```
#2~Partition~UpTo@{#,#}
```
Partition the (second input) into partitions whose width/length are at most (first input).
```
Map[ ..., ... ,{2,3}]
```
Map onto level 2 and level 3...
```
First@*Commonest
```
The composition of the Commonest function (finds the commonest element in a list) and First (take the first element; in case there are multiple commonest elements).
[Answer]
# Python, ~~191~~ ~~182~~ 180 bytes
```
lambda m,s,j=''.join,i=int:[j((lambda p:max(p,key=p.count))(j(g[i(x*s):-i(~x*s//1)]for g in m[i(y*s):-i(~y*s//1)]))for x in range(-i(-len(m[0])//s)))for y in range(-i(-len(m)//s))]
```
Call `_(map, scale_factor)`, where map is an array of lines, and it returns an array of lines.
Though this answer has already been beaten, I want to explain it, as it doesn't special case where the scale factor is less than one.
It makes a `h` by `w` matrix, where `h = ceiling(map height / scale factor)`, and `w = ceiling(map width / scale factor)`.
For every index (x, y) in the matrix, do:
* Take a submatrix from the coordinates `int(x * scale factor), int(y * scale factor)` to `ceil((x + 1) * scale factor), ceil((y + 1) * scale factor)`.
* Put the most common character in that submatrix at (x, y).
[Try it online!](https://tio.run/nexus/python3#dZBNboQwDIX3OUV2Y1dMaLtE4gwcABBKIUGh5EdJkKCLXp2GwkhV1b7Vs79nybYsm33m@m3gVGchm8rbjU1WmUyVysSingAu7ArNV3DZu9hKx3q7mIgIE4y1gvUpYHFX8JlMnr9gK62nI1WG6kS3B90uinjw9eCem1FAgvdZGND1c4t5HvBMbH8kTtzuSjvrIw1bIGQQkn5Yq0Fz12U09HwWneR9tB4LQpO8iIs39NaY8zyQ31kW3KwiHG38NYeE/KxpSeVseQRl3BIh4WM@ddMCLMRBGeYFHwCJ8@lxIMxQ/rcS7q@EsS6JJSWbV1XVnLapqvyyD30B "Python 3 – TIO Nexus")
[Try test cases](https://tio.run/nexus/python3#lVK7bsIwFN39Fd6w25AAKkukDH3QrfLSjSBkEgccEttyHJVUqL9O7YQ3DO0Zout7Hrl@ZFG8K2i5SCksvcrLo17PzyUXHo@4MOE0R2hPq7CkG6S8NWsi5SeyFgZjlKPllKPNQ4XDPkc/tgiCIZ5lUsMl5AKWlm0ObLNnMXb8xvGaiiVDluwXTKByOpjhIKhwp2juKDp6tktZBr@lLFFJ1dyDVUILNs9oYqTGIYAWmplaC9iLRbcllLVav1IFN8i18ZUPA2B007m/Vrxg8FPXrFs7nIthZIdTtUH4SLt0257Ojp17IQ7Hv5zDxt0JdWCbhCkDJ@R9orXUt9aFZnR90eUZFNK4tL@o23OhSjGRImu52dLpDF3jRCttHwm6OMMrrg14bAOuqbPbywpJr3Jw52p9d/evaFXtRsD35xa@hS0DQkjclTEhwb48AICn/8kH/hhYUWy7MQlav7XEYEvItvs4m9ONxuD55fUNgCH4aNp3aScE1UrWReqGBe4ykpV7yr8 "Python 3 – TIO Nexus")
] |
[Question]
[
The [coin change problem](http://www.algorithmist.com/index.php/Coin_Change) is very well documented. Given an infinite supply of coins of denominations `x_1` to `x_m` you need to find the number of combinations which add up to `y`. For example, given `x = {1,2,3}` and `y = 4` we have four combinations:
1. `{1,1,1,1}`
2. `{1,1,2}`
3. `{1,3}`
4. `{2,2}`
# Introduction
There are several variations of the coin change problem. In this variation we have two additional restrictions:
1. Every denomination must be used at least once.
2. Exactly a fixed number of coins must be used in total.
For example, given `x = {1,2,3}`, `y = 36` and `n = 15` where `n` is the total number of coins that must be used, we get four combinations:
1. `{1,2,2,2,2,2,2,2,3,3,3,3,3,3,3}` (1 ones, 7 twos, 7 threes)
2. `{1,1,2,2,2,2,2,3,3,3,3,3,3,3,3}` (2 ones, 5 twos, 8 threes)
3. `{1,1,1,2,2,2,3,3,3,3,3,3,3,3,3}` (3 ones, 3 twos, 9 threes)
4. `{1,1,1,1,2,3,3,3,3,3,3,3,3,3,3}` (4 ones, 1 twos, 10 threes)
# Challenge
The challenge is to write a function `enumerate` in the language of your choice which enumerates all the combinations as described above given:
1. The list of denominations. For example `{1,5,10,25}`. You may use either lists or arrays.
2. A non-negative integer `y` that denotes the sum of every combination.
3. A non-negative integer `n` that denotes the total number of coins.
The order of the arguments doesn't matter. Pointfree functions are allowed.
The output of the `enumerate` function must be a list of combinations. Each combination must be unique and it must be a list of `n` integers which add up to `y`. Every denomination must appear at least once in each combination and no combination must be missing. The ordering of the integers and the combinations doesn't matter. You may use either lists or arrays for the output.
Keep in mind the following edge cases:
1. If both `y` and `n` are zero and the list of denominations is empty then the output is a list of one combination, the empty combination (i.e. `{{}}`).
2. Otherwise, if `y` is zero, `n` is zero or the list of denominations is empty then the output is a list of zero combinations (i.e. `{}`).
3. More generally, if `y` is less than the sum of the denominations or `n` is less than the number of denominations then the output is a list of zero combinations.
Scoring will be based on the size of the entire program in bytes. Note that this includes the `enumerate` function, helper functions, import statements, etc. It does not include test cases.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 22 bytes
```
Z^!S!Xu!tsi=Z)"1G@m?@!
```
Input order is: array of denominations, number of coins taken (`n`), desired sum (`y`).
Each combination is displayed on a different line. Empty output is displayed as an empty string (so nothing).
[**Try it online!**](http://matl.tryitonline.net/#code=Wl4hUyFYdSF0c2k9WikiMUdAbT9AIQ&input=WzEgMiAzXQo4CjE1)
The code runs out of memory in the online compiler for the example in the challenge, but works offline with a standard, reasonably modern computer:
```
>> matl
> Z^!S!Xu!tsi=Z)"1G@m?@!
>
> [1 2 3]
> 15
> 36
1 1 1 1 2 3 3 3 3 3 3 3 3 3 3
1 1 1 2 2 2 3 3 3 3 3 3 3 3 3
1 1 2 2 2 2 2 3 3 3 3 3 3 3 3
1 2 2 2 2 2 2 2 3 3 3 3 3 3 3
```
### Explanation
```
Z^ % Implicitly input array of denomminations and number of coins n. Compute
% Cartesian power. This gives 2D array with each "combination"
% on a different row
!S! % Sort each row
Xu % Deduplicate rows
! % Transpose: rows become columns. Call this array A
ts % Push a copy, compute sum of each column
i % Input y (desired sum)
= % Logical array that contains true if the "combination" has the desired sum
Z) % Keep only those columns in array A
" % For each column
1G % Push array of denominations again
@ % Push current column
m % Is each denomination present in the column?
? % If so
@! % Push current column again. Transpose into a row
% End if
% End for
% Implicitly display stack contents
```
[Answer]
# Python 3, ~~120~~ 106 bytes
```
from itertools import*
lambda d,t,l:[i+d for i in combinations_with_replacement(d,l-len(d))if sum(i+d)==t]
```
An anonymous function that takes input of a tuple of denominations of the form `(x_1, x_2, x_3 ... , x_k)`, a target value, and a number of coins via argument, and returns a list of tuples of the form `[(solution_1), (solution_2), (solution_3), ... (solution_k)]`.
**How it works**
`Itertools`'s `combinations_with_replacement` function is used to generate all `l-len(d)` combinations, with replacement, of the denominations. By appending `d` to each of these combinations, it is guaranteed that each denomination appears at least once, and that the new combination has length `l`. If the elements of a combination sum to `t`, the combination is added to the return list as a tuple.
[Try it on Ideone](https://ideone.com/1ns7os)
---
*An alternative method for 108 bytes*
```
from itertools import*
lambda d,t,l:set(tuple(sorted(i+d))for i in product(d,repeat=l-len(d))if sum(i+d)==t)
```
An anonymous function that takes input of a tuple of denominations of the form `(x_1, x_2, x_3 ... , x_k)`, a target value, and a number of coins via argument, and returns a set of tuples of the form `{(solution_1), (solution_2), (solution_3), ... (solution_k)}`.
**How it works (other version)**
This uses the `product` function from `itertools` to generate all `l-len(d)` arrangements of the denominations. By appending `d` to each of these combinations, it is guaranteed that each denomination appears at least once, and that the new combination has length `l`. If the elements of a combination sum to `t`, the combination is sorted, converted from a list to a tuple, and added to the return tuples. Finally, calling `set` removes any duplicates.
[Try it on Ideone](https://ideone.com/2Uhr5W) (other version)
[Answer]
## 05AB1E, 20 bytes
```
g-¹sã€{Ùvy¹«DO³Qiˆ}¯
```
Input is in the order: `list of values`, `nr of coins`, `sum to reach`.
**Explanation in short**
1. Get all permutations of the coin list of length: `final length - length of unique coin list`
2. Add the list of unique coins to these lists.
3. If the sum equals the sought after sum, save the list
4. Output all saved lists
[Try it online](http://05ab1e.tryitonline.net/#code=Zy3CuXPDo-KCrHvDmXZ5wrnCq0RPwrNRacuGfcKv&input=WzEsMiwzXQo4CjE1)
The online compiler can't handle large number of coins.
[Answer]
## JavaScript (ES6), 135 bytes
```
g=(a,n,y,r)=>n>0?y>0&&a.map((x,i)=>g(a.slice(i),n-1,y-x,[...r,x])):n|y||console.log(r)
(a,n,y)=>g(a,n-a.length,a.reduce((y,x)=>y-x,y),a)
```
] |
[Question]
[
You've got a set of tiles with the symbols from the periodic table. Each symbol appears once. You're thinking up words to make but you want to know if it's possible or not.
## The Challenge
Write a program in your favourite language that will take in a string as an input parameter. You may assume that input is not null, has no spaces and consists of ASCII characters.
Your program should take that string and output a truthy value if that word can made up of symbols from the periodic table of elements, and a falsey value if the word cannot.
To make this challenge more difficult, you may not use a symbol twice. So if you use Nitrogen `N` you may not use `N` again in the same word.
## Rules
Standard loopholes are not allowed. You may use symbols from elements 1-118 (Hydrogen to Ununoctium). You can find a list of all the elements [here](http://pastebin.com/DNZMWmuf). You may read the list of symbols in from a file or input arguments if you wish.
## Test Cases:
```
Laos - true (LaOs)
Amputation - true (AmPuTaTiON)
Heinous - true (HeINoUS)
Hypothalamus - true (HYPoThAlAmUS)
Singapore - true (SiNGaPoRe)
Brainfuck - true (BRaInFUCK)
Candycane - false
```
This is a code golf challenge, shortest code wins.
**BEFORE YOU CLOSE AS DUPLICATE:** While this may seem similar to [this challenge](https://codegolf.stackexchange.com/q/6284/16043), I feel it is different because it is not 'Generate a list of all words that are possible from the periodic table', it is 'Take in arbitrary input and determine if it can be made from the periodic table'
[Answer]
## 05AB1E, 16 bytes
```
œvyŒ€J})˜Ùvy²Q}O
```
**Explained**
```
œv # for each permutation of the list of elements
yŒ # get all sublist of elements
€J # join as strings to form the words possible to spell
})˜Ù # convert to list of unique spellable strings
vy²Q} # compare each word with input word
O # sum giving 1 if the word is found, else 0
```
**Warning:** Extremely slow. I recommend testing on a much smaller subset of elements in the online interpreter.
Takes list of elements as first argument.
Takes word to test as second argument.
Returns 1 for true and 0 for false.
[Try it online on a small subset of elements](http://05ab1e.tryitonline.net/#code=xZN2ecWS4oKsSn0py5zDmXZ5wrJRfU8&input=WydoJywgJ2hlJywgJ2xpJywgJ2JlJywgJ2InLCAnYyddCmJlY2xp)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
spc~@l.
```
Call with the list of symbols (all lowercase) as Input, and the word as Output, e.g. `run_from_atom('spc~@l.', ["he":"n":"o":"li"], "Nohe").` .
**Warning:** this is extremely inefficent when all symbols are in the list.
### Explanation
```
spc Create a string from a permutation of a subset of the Input
~@l. This string can unify with the lowercase version of the Output
```
[Answer]
## JavaScript (Firefox 48 or earlier), 103 bytes
```
f=(w,e=`
H
He
... (list of elements not included in the byte count) ...
Uus
Uuo
`)=>!w||e.match(/\w+/g).some(s=>!w.search(s,`i`)&&f(w.slice(s.length),e.replace(`
${s}
`,`
`)))
```
[Answer]
# Pyth - 13 bytes
Just checks if any partition of lowercased input has all parts in the periodic table.
```
sm.A}RQd./rzZ
```
On mobile, so couldn't set up an actual test suite, but try [this](http://pyth.herokuapp.com/?code=sm.A%7DRQd.%2FrzZ&input=%22la%22%2C%22c%22%2C%22os%22%0Alaos&debug=0).
[Answer]
# Pyth, 11 bytes
```
s}RySQSM./z
```
[Try it online.](http://pyth.herokuapp.com/?code=s%7DRySQSM.%2Fz&input=%22ca%22%2C%22n%22%2C%22dy%22%2C%22ne%22%0Acandycane&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=s%7DRySQSM.%2Fz&test_suite=1&test_suite_input=%22al%22%2C%22am%22%2C%22h%22%2C%22po%22%2C%22s%22%2C%22th%22%2C%22u%22%2C%22y%22%0Ahypothalamus%0A%22ca%22%2C%22n%22%2C%22dy%22%2C%22ne%22%0Acandycane&debug=0&input_size=2)
Written on my phone, but should work. **Very slow for a large number of elements or a long string.**
### Explanation
* Take all partitions (`./`) of the input (`z`).
* Sort (`S`) each partition (`M`).
* For each partition (`R`), see if it is in (`}`) the list of all subsets (`y`) of the sorted (`S`) periodic table given as input (`Q`).
* Sum (`s`) the resulting list of booleans.
] |
[Question]
[
Chess pieces (kings, queens, rooks, bishops, and knights) and pawns are on a board, but not on the [**a1**](//en.wikipedia.org/wiki/Algebraic_notation_(chess)) or **h8** square. Your task is to travel from the empty **a1** to the empty **h8** squares, passing through only empty squares. The rules of movement are as follows:
1. You can proceed from any empty square to any empty square next to it (same rank, next or preceding file; or same file, next or preceding rank).
2. You can proceed from any empty square to any empty square diagonally next to it (next or preceding rank, next or preceding file), **provided** that the catty-corner squares contain either (a) two pawns or (b) pawns/pieces of opposite color. (Two non-pawn pieces, or a non-pawn piece and a pawn, of the same color are strong enough to bar your progress across the corner, but two pawns are not; and pieces/pawns of opposite color don't work in concert to bar your way.) For example, if you're on **c4** and **d5** is empty, you can proceed to it provided **c5** and **d4** contain pawns or contain pieces/pawns of opposite color. See the "Example diagonals" section, below, for pictures.
## Input
[FEN](//en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation)'s board description. That is: The input will be a string that includes a description of rank **8**, a slash (`/`), a description of rank **7**, a slash, …, and a description of rank **1**. The description of each rank comprises numbers and letters running from file **a** to file **h**, where the letters indicate pieces and pawns (the black ones are `p`= pawn, `n`=knight, `b`=bishop, `r`=rook, `q`=queen, `k`=king, and the white ones are capitalized versions of the same) and the numbers indicate the successive number of empty squares. For example, `rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBN` is the board after one ply move (king's pawn to **e4**) in a chess game.
**a1** and **h8** will be empty in the input; i.e., the first slash has a digit before it, and the last slash has a digit after it.
## Output
Truthy or falsey, indicating whether successful passage to **h8** is possible.
If the input is not a valid FEN board description (meaning, one that matches my explanation above), or if **a1** or **h8** is occupied, then the output can be anything or nothing. (In other words: you may assume the input meets the requirements above.)
## Scoring
This is code golf: fewest bytes wins.
## Example input and output
Note that your code must work for all valid inputs, not only the examples.
Add a space and a `w` after each FEN to visualize it at [`http://www.dhtmlgoodies.com/scripts/chess-fen/chess-fen-3.html`](http://www.dhtmlgoodies.com/scripts/chess-fen/chess-fen-3.html). (Note that some other online FEN visualizers will not allow a board that's illegal in chess, e.g. with a pawn on rank **1** or **8**, so can't be used for our purposes.)
### Truthy examples
* `8/8/8/8/8/8/8/8` — the empty board
* `1p1Q4/2p1Q3/2p1Q3/2p1Q3/2p1Q3/2p1Q3/Q1p1Q3/1q3q2` — there's a path **a1**, **b2**, **b3**, **b4**, **b5**, **b6**, **b7**, **c8**, **d7**, (*not* **e8**, that's blocked off, but) **d6**, **d5**, **d4**, **d3**, **d2**, **d1**, **e1**, **f2**, **f3**, **f4**, **f5**, **f6**, **f7**, **f8**, **g8**, **h8**
* `8/8/KKKKK3/K3K3/K1K1p3/Kp1K4/K1KK4/2KK4` — an example where a square that's blocked at one point must be passed through later on (to make sure you don't set squares as impassable)
* `K1k1K1K1/1K1k1K1k/K1K1k1K1/1k1K1K1k/K1k1K1k1/1K1k1k1K/K1K1k1K1/1k1k1K1k` — there's a single path through (just follow your nose: there's only one square to move to at each step, unless take a step backward); this is also an example where a square is blocked at one point but necessary later
### Falsey examples
* `6Q1/5N2/4Q3/3N4/2Q5/1N6/2Q5/1N6` — any attempt at a path will have to pass through two diagonally situated same-color pieces
* `N1q1K1P1/1R1b1p1n/r1B1B1Q1/1p1Q1p1b/B1P1R1N1/1B1P1Q1R/k1k1K1q1/1K1R1P1r` — the only way through the **a8-h1** diagonal is at **f2-g3**, but that would require passage through **e1-d2** or **f2-e3**, which are both impossible.
* `4Q3/4q3/4Q3/5Q2/6Q1/3QqP2/2Q5/1Q6`
* `4q3/4Q3/4q3/5q2/6q1/3qQp2/2q5/1q6`
## Example diagonals
In case the prose above was unclear, here are some pictures.
### Passable diagonals



### Impassable diagonals


[Answer]
# VBA 668 666 633 622 548 510 489 435 331 322 319 315 bytes
```
Function Z(F):Dim X(7,7):While Q<64:R=R+1:V=Asc(Mid(F,R))-48:If V>9 Then X(Q\8,Q Mod 8)=(3+(V\8=V/8))*Sgn(48-V):V=1
Q=Q-V*(V>0):Wend:X(7,0)=1:For W=0 To 2E3:Q=W Mod 8:P=W\8 Mod 8:For T=Q+(Q>0) To Q-(Q<7):For S=P+(P>0) To P-(P<7):If X(S,T)=0 Then X(S,T)=(1=X(P,Q))*(6>X(P,T)*X(S,Q))
Next S,T,W:Z=X(0,7):End Function
```
Reading the input string occupies up to 'Wend'. Nice side effect - this abandons the input string once the board [X] is fully coded, so you can leave a description on the end.
In the board coding, pawns are 2, other pieces are 3, black is negative. Pawns are recognized by 'P' & 'p' having character codes divisible by 8.
'X(7,0)=1', setting **a1** accessible, is where the path checks start. This repeatedly scans the board trying to add accessible squares from squares marked as accessible (1) so far. Diagonal access and occupancy are checked in a IF + logic-calc which once lived in a function but now sits in nested neighbour loops. The diagonal access check relies on the product of the two kitty-corner squares, which is only at 6 or more if pieces there are the same colour and at least one is a piece not a pawn.
Call in spreadsheet; returns the value in X(0,7) - 1 if **h8** accessible and 0 if not - which Excel recognizes as truthy / falsy.
=IF(Z(C2), "yes","no")
[](https://i.stack.imgur.com/tvCoi.jpg)
I maybe got carried away with scrunching the code down, above, so here is a semi-ungolfed commented version:
```
Function MazeAssess(F) 'input string F (FEN)
Dim X(7, 7) 'size/clear the board; also, implicitly, Q = 0: R = 0
'Interpret string for 8 rows of chessboard
While Q < 64
R = R + 1 ' next char
V = Asc(Mid(F, R)) - 48 ' adjust so numerals are correct
If V > 9 Then X(Q \ 8, Q Mod 8) = (3 + (V \ 8 = V / 8)) * Sgn(48 - V): V = 1 ' get piece type (2/3) and colour (+/-); set for single column step
Q = Q - V * (V > 0) ' increment column (unless slash)
Wend
'Evaluate maze
X(7, 0) = 1 ' a1 is accessible
For W = 0 To 2000 ' 1920 = 30 passes x 8 rows x 8 columns, golfed to 2E3
Q = W Mod 8 ' extracting column
P = W \ 8 Mod 8 ' extracting row
For T = Q + (Q > 0) To Q - (Q < 7) ' loop on nearby columns Q-1 to Q+1 with edge awareness
For S = P + (P > 0) To P - (P < 7) ' loop on nearby rows (as above)
If X(S, T) = 0 Then X(S, T) = (1 = X(P, Q)) * (6 > X(P, T) * X(S, Q)) ' approve nearby empty squares if current square approved and access is possible
Next 'S
Next 'T
Next 'W
MazeAssess = X(0, 7) ' report result for h8
End Function
```
---
## Progress notes
***Edit***1: The code is now not as 666-devilish :-D and has lost its functions; I found a short-enough way to write them to avoid the overhead.
***Edit***2: Another biggish leap forward, effectively finishing the work of removing the inc/dec functions, sigh, and using a couple of globals. I might finally be getting the hang of this....
*The coding of pieces & squares changed. No effect on code length.*
***Edit***3: Return of (fake) functions, removing all those annoying `Call` bytes, and some other tweaks.
***Edit***4: Breaking through the big 500, woohoo - smooshed the 3 For loops into 1.
***Edit***5: Jiminy Cricket, another big drop when I smooshed the two functions together - my diagonal access check always passes for adjacent squares, so...
***Edit***6: Holy niblicks, another massive drop. Buh-bye to external functions and thus globals... I have gone to under half the original posted length....
***Edit***7: Add ungolfed version
***Edit***8: Revised the read process for a few dollars more
***Edit***9: Squeezed a couple of expressions for the last few drops of blood
***Edit***10: Compund `Next` statement sheds a few bytes
---
For interest, graphics of the boards after accessibility analysis (the code numbers are out of date but...) accessible squares are green, inaccessible squares white and other colours are pieces or pawns.
[](https://i.stack.imgur.com/pXpOF.jpg) [](https://i.stack.imgur.com/NIftA.jpg)
A couple of challenge boards: **h8** is accessible in both:
* P1Pq2p1/1P1R1R1p/1K2R1R1/1p1p1p2/p1b1b1np/1B1B1N1k/Q1P1P1N1/1r1r1n2 - 10 passes to solve
* P1P3r1/1P1R2r1/1N1R1N2/1P1P1P2/1n1p1ppp/1B1B4/1b1pppp1/1P6 - a winding path
[Answer]
## Matlab, 636 887 bytes as saved (including indentation)
This solution is not very golfed, but I wanted to go ahead and put it up.
```
function[n] = h(x)
o=[];
for i=x
b={blanks(str2num(i)),'K','k',i};o=[o b{~cellfun(@isempty,regexp(i,{'\d','[NBRQK]','[nbrqk]','p|P'}))}];
end
o=fliplr(reshape(o,8,8))
for i=1:64
b=i-[-8,8,7,-1,-9,1,9,-7];
if mod(i,8)==1
b=b(1:5);
elseif mod(i,8)==0
b=b([1,2,6:8]);
end
b=b(b<65&b>0);c=o(b);dn=b(isspace(c)&ismember(b,i-[9,7,-9,-7]));
for j=dn
g=o(b(ismember(b,j-[-8,8,7,-1,-9,1,9,-7])));
if ~isempty(regexp(g,'pk|kp|PK|KP|kk|KK'));c(b==j)='X';end;
end
Bc{i}=b(c==32);
end
n=Bc{1};
on=[];
while length(n)>length(on)
on=n;
for i=1:length(n)
n=unique([n Bc{n(i)}]);
end
end
any(n==64)
end
```
Reads a board string `x` as specified above and turns it into the more completely represented `o`, then finds all the moves (graph edges) between spaces, then figures out which moves are possible (not into filled spaces), then figures out which possible moves have "gates" of two pieces to pass between, then figures out if the gate is open (pawns, opposite colors) or closed (same color and including a non-pawn). Then, it walks through to find locations reachable by paths from the lower left square and if a path can reach space 64, it's a Yes board.
] |
[Question]
[
Write a program in any language that reads input from stdin and outputs a slightly modified output to stdout. The program should borrow some characters from the input and output as large of a prefix as possible of `*language-name* is awesome!` followed by a newline and then what's left of the input.
* The input does not contain any uppercase characters.
* If the first character of the language name is not present in the string, only the newline character should be borrowed.
* If there's no newline character in the input, output the input unmodified.
* It does not matter which of the available characters you borrow.
I'm using `\n`as the newline character (`0x0a`) to save space when writing. The real program should only care about the real newline character, not the `\n` string.
Example: python.
input: `abcdefghijklmnopqrstuvwxyz\n0123456789`
output: `python\nabcdefgijklmqrsuvwxz0123456789`
Since the input does not have any spaces, we cannot continue even though we have enough characters for the next word: `is`.
Example: C.
input: `i don't see anything!`
output: `i don't see anything!`
C was not found in the string, so no modification was possible. Also, no newline character is present.
Example: C++.
input: `i don't\nsee anything!`
output: `\ni don'tsee anything!`
C was not found in the string, so no modification was possible.
Example: Obj-C.
input: `objectively, clojure is amazing.\nq.e.d.`
output: `obj\nectively, clojure is amazing.q.e.d.`
The input contains enough characters to write `obj` but the `-` is missing.
Byte count of your source code minus the byte count of your languages' name, utf-8 encoded (if possible), is your score; lowest wins!
[Answer]
# Pyth, 37 bytes
```
.-Jjb.zpef!.-TJ+,kb+Rb._"pyth is awesome!
```
The source code is **41 bytes** long. [Try it online.](https://pyth.herokuapp.com/?code=.-Jjb.zpef%21.-TJ%2B%2Ckb%2BRb._"pyth+is+awesome%21&input=abcdefghijklmnopqrstuvwxyz%0A0+1+2+3+4+5+6+7+8+9)
### How it works
```
Jjb.z Save all user input in J.
._"pyth is awesome! Compute all prefixes that string:
["p", "py", ... ]
+Rb Append a linefeed to each prefix.
+,kb Concatenate ["", "\n"] with the result.
f Filter the resulting array; for each T:
.-TJ Perform bagwise difference between T
and J (respects multiplicities).
! Take the logical NOT.
Keep T if ! returned True, i.e., if J
contains all of T's characters.
e Retrieve the last, longest match.
p Print it.
.-J Remove its characters from J.
(implicit) Print the result.
```
[Answer]
## Python, 186 - 6 = 180
```
import sys
a=sys.stdin.read()
s="python is awesome!"
r=''
if'\n'not in a:print a;exit()
a=a.replace('\n','',1)
for c in s:
if c in a:a,r=a.replace(c,'',1),r+c
else:break
print r+'\n'+a
```
[Try it online](http://ideone.com/XL5yI8)
[Answer]
## Python, 146 bytes
```
import sys
r=sys.stdin.read();y='\npython is awesome!';a=''
for i in y:
if i in r:a+=i
else:break
print a[1:]+'\n'+''.join(b for b in r if not b in a)
```
[Answer]
# Ceylon, 235 - 6 = 229
`void a(){variable value i="";variable value r="\nceylon is awesome!";while(exists l=process.readLine()){i=i+"\n"+l;}i=i.rest;for(j->c in r.indexed){if(c in i){i=i.replaceLast(c.string,"");}else{r=r[0:j];break;}}print(r.rest+r[0:1]+i);}`
Here is a formatted and commented version:
```
void a() {
// our target string, with the \n shuffled to the start.
variable value r = "\nceylon is awesome!";
// read the whole input line by line
// (there doesn't seem a way to do this shorter :-/)
variable value i = "";
while (exists l = process.readLine()) {
i = i + "\n" + l;
}
// remove first \n:
i = i.rest;
for (j->c in r.indexed) {
if (c in i) {
// remove some occurence of c
i = i.replaceLast(c.string, "");
} else {
// stop the loop, and take the part of `r` processed so far.
r = r[0:j];
break;
}
}
// reshuffle first \n in r to its end.
// This will result in the empty string if r is empty, i.e. no \n was found.
print(r.rest + r[0:1] + i);
}
```
It uses `replaceLast` instead of `replaceFirst` because it is shorter.
Some example inputs and outputs in the same format as in the question:
* `abcdefghijklmnopqrstuvwxyz\n0123456789` → `ceylon\nabdfghijkmpqrstuvwxz0123456789`
* `i don't see anything!` → `i don't see anything!`
* `i don't\nsee anything!` → `\ni don't see anything!`
* `objectively, closure is amazing.\nq.e.d.` → `ceylon is a\nobjectivel, sureiamzng.\q..d.`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 - 5 = 18 bytes
```
“£İþ¬Ɠ¥ỊḊ»
¢œ-ƤṆ€×¢Ṅœ-@
```
[Try it online!](https://tio.run/##AW0Akv9qZWxsef//4oCcwqPEsMO@wqzGk8Kl4buK4biKwrsKwqLFky3GpOG5huKCrMOXwqLhuYTFky1A/8OH//9hYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5egowMTIzNDU2Nzg5Cmx5IGlzIGF3ZSst "Jelly – Try It Online")
This uses the [Jelly encoding](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page). Insisting on UTf-8 encoding has the same byte count, it just means I need to make a hexdump of the bytes.
## How it works
```
“£İþ¬Ɠ¥ỊḊ» - Helper link. Compressed string "jelly is awesome"
¢œ-ƤṆ€×¢Ṅœ-@ - Main link. Takes S on the left
¢ - Yield "jelly is awesome"
Ƥ - Over each prefix of "jelly is awesome":
œ- - For each character in the prefix, remove it exactly once
if it is in the input
This results in an empty list if the entire prefix is in
the input else a non-empty list
€ - Over each:
Ṇ - Logical NOT. This yields 1 for an empty list, else 0
¢ - Yield "jelly is awesome"
× - For each character, keep it if the left argument is 1
Ṅ - Print the kept characters with a trailing newline
œ-@ - Remove exactly one occurrence of each of the kept characters
from the input and output that
```
[Answer]
# JavaScript (ES6) 90 (100-10)
As a function returning the requested ouput. It's difficult to implement with I/O, as the usual substitute for STDIN is `prompt()`, that does not accept a newline inside the input string.
As a function with real output (using `alert`) the byte count is 107
```
f=s=>alert(([...`
javascript is awesome`].every(c=>(z=s.replace(c,''))!=s&&(s=z,q?o+=c:q=c),q=o=''),o+q+z))
```
Test running the snippet below in an EcmaScript 6 compliant browser (implementing spread operator and arrow function - I use FireFox)
```
f=s=>([...`
javascript is awesome`].every(c=>(z=s.replace(c,''))!=s&&(s=z,q?o+=c:q=c),q=o=''),o+q+z)
function test()
{
O.innerHTML=f(I.value)
}
test()
```
```
#I {width: 80%}
```
```
<textarea id=I>
objectively, clojure is amazing.
q.e.d.</textarea><button onclick="test()">-></button>
<pre id=O></pre>
```
[Answer]
# Perl, 72 - 4 = 68 bytes
Includes 2 switches.
```
perl -0pe 'for$c("\nperl is awesome!"=~/./gs){s/$c//?$p.=$c:last}s/^/$p\n/;s/\n//'
```
*Explanation*: For every character in the string `"\nperl is awesome"`, remove the corresponding character from the input string (`$_`) till we find a character not present in `$_`. The matching characters are stored in `$p` which is prefixed to `$_` which is then printed.
The `-0` switch reads in the complete input rather than line-by-line and the `-p` switch makes reading input and print the output implicit.
[Answer]
# JavaScript (ES7), ~~101~~ 107 - 10 = 97
It was shorter before, and even worked on all four test cases, but apparently I missed a rule, so....
```
x=>(i=r=q='',[for(c of`
javascript is awesome`)(y=x.replace(c,''),i||y==x?i=1:(c<' '?q=c:r+=c,x=y))],r+q+x)
```
Works properly in Firefox 42. This originally started out at 119 bytes, but a trick from [@edc65's answer](https://codegolf.stackexchange.com/a/61757/42545) helped to shorten it a great deal. I think there's still some room for improvement. As always, suggestions welcome!
] |
[Question]
[
To conjugate a verb in *l'imparfait*, one needs to perform the following steps:
1. Find the "stem" of the word; this is achieved by omitting the `-ons` from the nous-conjugated form of the word. For example, *vivre* is *nous vivons*; removing `-ons` from *vivons* yields `viv-`.
2. Take the stem and add an appropriate ending, according to the subject. Here are the endings:
```
je -ais
tu -ais
il/elle -ait
nous -ions
vous -iez
ils/elles -aient
```
**Objective** Given a verb and a subject, output the imperfect form of that verb with respect to the subject. The input format can be in any format convenient to your language. Your submission can either be a program, snippet, or function. (Note that the verb does not have to be a real verb.)
You can assume that the verb is a regular verb, i.e, items like *avoir* would be treated as an `-ir` verb, not an irregular one. The only verb you have to quantify as irregular is *être*; it is conjugated as such:
```
j'étais
tu étais
il/elle était
nous étions
vous étiez
ils/elles étaient
```
Here are the conjugations for `-er`, `-re`, and `-ir` verbs in the nous forms
```
-ER => (e)ons ; e is added after a 'g'
-RE => ons
-IR => issons
```
Anything that does not end with such does not have to be handled.
(Note that *je* merges with the next vowel, if there is one. E.g., `je acheter -> j'achetais`. `h` will be considered a vowel for our purposes.)
# Example IOs
```
input: tu vivre
output: tu vivais
input: elles nager
output: elles nageaient
input: je morter
output: je mortais ; incorrect in real life, but correct for our purposes
input: vous finir
output: vous finissiez
input: il croire
output: il croiait
input: nous jouer
output: nous jouions
```
# Bonuses
* -5N bytes for all `N` extra irregular verb handled.
* -10% if you *also* output every conjugation of the verb in the imperfect tense.
---
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins.
[Answer]
# Haskell, ~~366~~ ~~362~~ 352 bytes
```
s#v=m++g++d++t
where
m|v=="être"="ét"|i/="rio"&&i/="erd"&&i/="eri"=r 2 v|otherwise=r 3 v
g=if(last m=='g'&&head t/='i')then"e"else""
d|init i=="ri"="iss"|i=="eri"="y"|otherwise=""
t|s=="je"||s=="tu"="ais"|elem s["il","elle","on"]="ait"|s=="nous"="ions"|s=="vous"="iez"|s=="ils"||s=="elles"="aient"
r i=reverse.drop i.reverse
i=take 3$reverse v
```
You can compile this in ghci and use it like so `"je"#"choisir"` to get `"choisissais"`.
This code works with some irregular verbs. It can conjugate *croire* (*je croyais*, *tu croyais*…) or *prendre* as well as all its derivatives (*apprendre*, *comprendre*, etc.).
I couldn't find a short way to conjugate other verbs ending in -ire (such as *lire*, *rire*, *dire*, etc.) or in -dre (such as *craindre*, *soudre*, etc.).
[Answer]
# Processing, 342-10%(bonus) = 307.8
I have created a function. To call the function, include the pronoun as the first parameter and the verb as the second. For example, `a("je","habiter")`
Please note that my program conjugates the verb for all the pronouns, so that is how I got the 10% bonus.
```
void a(String a,String b){String[]e={"ais","ais","ait","ait","ions","iez","aient","aient"},p={"je","tu","il","elle","nous","vous","ils","elles"};if("aehiou".contains(b.charAt(0)+""))p[0]="j'";for(String i:p)println(i+" "+b.substring(0,b.length()-2)+(b.endsWith("ger")?"e":b.endsWith("ir")?"iss":"")+e[java.util.Arrays.asList(p).indexOf(i)]);}
```
Readable form:
```
void a(String a,String b){
String[]e={"ais","ais","ait","ait","ions","iez","aient","aient"},p={"je","tu","il","elle","nous","vous","ils","elles"};
if("aehiou".contains(b.charAt(0)+""))p[0]="j'";
for(String i:p)
println(i+" "+b.substring(0,b.length()-2)+(b.endsWith("ger")?"e":b.endsWith("ir")?"iss":"")+e[java.util.Arrays.asList(p).indexOf(i)]);
}
```
Output (for `a("je", "habiter")`)
```
j' habitais
tu habitais
il habitait
elle habitait
nous habitions
vous habitiez
ils habitaient
elles habitaient
```
[Answer]
# [Java](http://www.tutorialspoint.com/compile_java_online.php), ~~389~~ ~~385~~ ~~383~~ ~~382~~ ~~352.7~~ 443-10%(bonus) = 398.7 bytes
Byte count reduced thanks to @PeterTaylor and @Fatalize
Please note that my program conjugates the verb for all the pronouns, so that is how I got the 10% bonus.
```
class A{public static void main(String[]a){String[]e={"ais","ais","ait","ait","ions","iez","aient","aient"},p={"je","tu","il","elle","nous","vous","ils","elles"},w=new java.util.Scanner(System.in).nextLine().split(" ");if("aehiou".contains(w[1].charAt(0)+""))p[0]="j'";for(String i:p)System.out.println(i+" "+w[1].substring(0,w[1].length()-2)+(w[1].endsWith("ger")?"e":w[1].endsWith("ir")?"iss":"")+e[java.util.Arrays.asList(p).indexOf(i)]);}}
```
Readable form (still quite messy):
```
1| class A{
2| public static void main(String[]a){
3| String[]e={"ais","ais","ait","ait","ions","iez","aient","aient"};
4| String[]p={"je","tu","il","elle","nous","vous","ils","elles"};
5| String[]w=new java.util.Scanner(System.in).nextLine().split(" ");
6| if("aehiou".contains(w[1].charAt(0)+""))p[0]="j'";
7| for(String i: p) {
8| System.out.print(i+" "+w[1].substring(0,w[1].length()-2)+(w[1].endsWith("ger")?"e":w[1].endsWith("ir")?"iss":"")+e[java.util.Arrays.asList(p).indexOf(i)]);
9| }
10| }
11| }
```
Explanation:
```
Lines 3-4: Initialisation of arrays.
Line 5: Read a line as input and split it into words
Line 6: Shorten the `je` to `j'` in presence of a succeeding vowel or a `h`.
Line 7: Create a for-loop iterating through all of the pronouns .
Line 8: Conjugate the verb(remove the ending from the infinite form of the verb and add ending accordingly) and print the result, along with the pronoun.
```
## (Old Version) 393-10% = 352.7 bytes
Please note also that my old program does not obey with the new rule about the `je` merging into `j'`.
```
class A{public static void main(String[]a){String[]e={"ais","ais","ait","ait","ions","iez","aient","aient"},p={"je","tu","il","elle","nous","vous","ils","elles"},w=new java.util.Scanner(System.in).nextLine().split(" ");for(String i:p)System.out.println(i+" "+w[1].substring(0,w[1].length()-2)+(w[1].endsWith("ger")?"e":w[1].endsWith("ir")?"iss":"")+e[java.util.Arrays.asList(p).indexOf(i)]);}}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 258-10% = 232.2 223-10% = 200.7
Huge thanks to @WW for saving me 35 bytes!
```
def t(x,y):
z=y[-2:];y=y[:-2];y+='e'*(y[-1]=='g');y+='iss'*(z=='ir')
return[('j'+"e'"[y[0]in'aeiouh']+' tu il elle nous vous ils elles').split()[i]+' '+y+'ais ais ait ait ions iez aient aient'.split()[i]for i in range(8)]
```
[Try it online!](https://tio.run/##bY7BboMwDIbvPIXVi5PRTlt3mZh4kigHppriKXVQEqqGl2cBLpPWgy37@/3r95jT4OVjWS7UQ1KPY9ZNBXObzenc2K9chuZ0LkPdIuGLKvzdti1eUW@MYyx0LoQD6goCpSmIUfiD9YHwYLJ5syzYEftpQFsjpAnYATlHIH6KcF8bu7ihiPo1jo6T0obXa6xzjR1H2CttxV6KheaykKS94x9f7wMwsEDo5ErqU9tlDCxJJYV7yhF7lvVlXf1Thu6bEz3XRpJLoKfSbc1aXcsv "Python 3 – Try It Online")
] |
[Question]
[
Rod is moderating a card game between two players: George and Tim. Currently, Tim is shuffling the cards. Rod suspects that Tim is trying to cheat, so he needs your help to check that the shuffle is fair.
Tim is doing the overhanded shuffle: he cuts a pile of cards from the bottom of the deck, then cuts various parts from the top of the pile onto the top of the deck, and repeats the process a few times.
Rod is eagle-eyed and can see exactly how many cards Tim is cutting each time, however he can't calculate and keep track of the cards as fast as Tim is shuffling. This is where you come in: Rod would like you to write a program or function that gets the detailed shuffling information and determines whether the shuffle is fair, weak or a trick.
* If after shuffling, less than 25 pairs of adjacent cards remain adjacent (in the same order), then the shuffle is fair and the game can go on.
* If at least 25 (but not all) pairs of adjacent cards remain adjacent, then the shuffle is weak and Rod will bonk Tim over the head and ask him to shuffle some more.
* If all the cards remain in the same position at the end, then Tim is obviously cheating and Rod will whack him with a large trout.
This is code golf, so the shortest code wins.
**Input:**
You will get a series of numbers between 0 and 52 (both exclusive) separated by space, on several lines, where each line represents a round of shuffling that begins and ends with all the cards piled together.
On each line, the first number is the number of cards Tim cuts from the bottom of the deck, and each subsequent number is a number of cards he drops from his hand onto the top of the deck. If any cards remain after the last number on a line, you should assume that Tim puts them on top of the deck.
The input is guaranteed to be valid. There is at least one line of numbers, and each line contains at least 2 numbers. The first number on each line is not smaller than the sum of all the other numbers on the same line. A trailing newline is optional, you may assume that the input has one or that it doesn't have one.
**Output:**
Your program should print/return "fair" if the shuffle is fair, "weak" if the shuffle is weak and "trick" if Tim is keeping all the cards in the same order. A trailing newline is optional.
**Example:**
The deck is assumed to have 52 cards, but for demonstration purposes, I'll use a smaller deck of 10 cards.
Input:
```
5 3 1
4 2 2
```
Initial deck, viewed from the top: `0 1 2 3 4 5 6 7 8 9`
`5` ➜ `0 1 2 3 4` (`5 6 7 8 9` in hand)
`3` ➜ `5 6 7 0 1 2 3 4` (`8 9` in hand)
`1` ➜ `8 5 6 7 0 1 2 3 4` (`9` in hand)
end of line ➜ `9 8 5 6 7 0 1 2 3 4`
`4` ➜ `9 8 5 6 7 0` (`1 2 3 4` in hand)
`2` ➜ `1 2 9 8 5 6 7 0` (`3 4` in hand)
`2` ➜ `3 4 1 2 9 8 5 6 7 0`
4 pairs remain adjacent: `(3 4) (1 2) (5 6) (6 7)`
**Test cases:**
```
43 5 5 5 5 5 5 5 5
43 5 5 5 5 5 5 5 5
43 5 5 5 5 5 5 5 5
```
Output: `fair`
---
```
43 5 5 5 5 5 5 5 5
43 5 5 5 5 5 5 5 5
43 5 5 5 5 5 5 5
```
Output: `weak`
---
```
29 24
19 18
38 2 1 8 13 6 4
47 15 16 5 2 1 7
34 22 9 3
44 9 10 11 3 1 7
33 18 4 2 3 3
```
Output: `fair`
---
```
24 6 12 4
25 3 19
36 4 25 2
19 11 1 3
15 9 3
37 5 27
```
Output: `weak`
---
```
26 13
26 13
26 13
26 13
```
Output: `trick`
---
```
50 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
```
Output: `weak`
---
```
50 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
50 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
```
Output: `trick`
---
```
50 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
49 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
```
Output: `fair`
**Requirements:**
* If you write a function, it can either read from the standard input or receive the input as a single string parameter. Also, the function can either print out the output or return it.
* The program must be runnable in Linux using freely available software.
* The source code must use only ASCII characters.
* No standard loopholes.
[Answer]
# CJam, ~~76~~ 75 bytes
```
52,qN/{[~](52\-@/(\e_@{/(@+\e_}/\+}/2ew::m2f/0-,_!\26>-"weak trick fair"S/=
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=52%2CqN%2F%7B%5B~%5D(52%5C-%40%2F(%5Ce_%40%7B%2F(%40%2B%5Ce_%7D%2F%5C%2B%7D%2F2ew%3A%3Am2f%2F0-%2C_!%5C26%3E-%22weak%20trout%20fair%22S%2F%3D&input=26%2013%0A26%2013%0A26%2013%0A26%2013).
[Answer]
# Pyth, 62 bytes
```
@c"weak trick fair"d-!JlfhT-M.:us_cG.u+NYtKrH7-52hK.zU52 2>J26
```
[Demonstration.](https://pyth.herokuapp.com/?code=%40c%22weak%20trick%20fair%22d-!JlfhT-M.%3Aus_cG.u%2BNYtKrH7-52hK.zU52%202%3EJ26&input=29%2024%0A19%2018%0A38%202%201%208%2013%206%204%0A47%2015%2016%205%202%201%207%0A34%2022%209%203%0A44%209%2010%2011%203%201%207%0A33%2018%204%202%203%203&debug=0)
[Answer]
## JavaScript, ~~292~~ 289 bytes
This could probably get some more bytes squeezed out of it, but it's a quick first pass for now:
```
d=[];for(i=0;i<52;i+=1)d[i]=i
s=prompt().split('\n')
s.forEach(function(e,i){s[i]=e.split(' ')
h=d.splice(-s[i][0],99)
for(j=1;j<s[i].length;j+=1)d.unshift.apply(d,h.splice(0,s[i][j]))
d.unshift.apply(d,h)})
for(c=0;i>1;i-=1)if(d[i-2]==d[i-1]-1)c+=1
alert(c<25?"fair":c<51?"weak":"trick")
```
EDIT: Saved 3 bytes by reusing the value of `i` from the deck-building loop when counting the number of adjacent cards.
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.