text
stringlengths 180
608k
|
---|
[Question]
[
Write a program, in a language of your choice, that will compose a quine program of a requested size. The generated program may be in the same or a different language, if desired.
Programs are scored based on the following formula:
>
> generating\_program\_length + smallest\_supported\_size + 512 \* number\_of\_supported\_sizes ^ (-3/4)
>
>
>
Halve your score if you support *every size* between the minimum and maximum supported sizes.
Lowest score wins.
[Answer]
## GolfScript → GolfScript: (4 + 0 + 0) / 2 = 2
```
~1`*
```
* Program length: **4**
* Minimum supported size: **0**
* Maximum supported size: *unbounded*
* All sizes supported: *yes*
This program simply reads an integer *n* from its input, and outputs an *n*-digit integer consisting of *n* `1` digits. For example, the input `5` yields the output `11111`. In GolfScript, any integer literal (without leading zeros) is a quine, and since GolfScript integers can be arbitrarily large, the maximum supported length is only bounded by the amount of memory available.
For the input `0`, the code outputs an empty program, which is also a quine in GolfScript.
Ps. The generated quines work for several other languages too, including PHP.
[Answer]
# Ruby -> JavaScript, 38
45 character program
31 smallest supported size
Infinity possible sizes
Supports any size in range
(45 + 31 + 512 \* Infinity ^ -3/4) / 2 = 38
```
"function f(){alert(f+'f()')#{?;*(i-31)}}f()"
```
# GolfScript -> JavaScript, 37.5
1 char less :P
```
"function f(){alert(f+'f()')"";"i 31-*"}f()"
```
---
Example output for `i = 31`:
```
function f(){alert(f+'f()')}f()
```
For `i = 41`:
```
function f(){alert(f+'f()');;;;;;;;;;}f()
```
The output quines work on latest Chrome (31.0.1650.63), at least. (Untested for any other browser)
[Answer]
# Ruby or GolfScript -> HQ9+, 6
11 character program
1 smallest supported size
Infinity possible sizes
Supports any size in range
(11 + 1 + 512 \* Infinity ^ -3/4) / 2 = 6
```
?Q+?+*(i-1)
```
Same size program written in GolfScript:
```
"Q""+"i 1-*
```
---
Example output for `i = 1`:
```
Q
```
For `i = 10`:
```
Q+++++++++
```
[Answer]
# Python 2 - 62.6 points
```
s='s=%r;print(s%%s+s*99)[:input()]#';print(s%s+s*99)[:input()]
```
This code is both the generator and the core of the quine. It expects you to provide a length on standard input, and prints to standard output a version of itself of that length (larger sizes get a trailing comment full of junk).
So, if you pass it 62, it prints itself (this is the minimum size). If you call it with some longer length (up to the maximum length of 3231), it will produce output of that length. Any version will be a quine if passed its own length.
The length limit was the result of my attempts at minimizing the number of characters used. Supporting more lengths was costing more in points for code length than it was reducing the penalty for a limited range. It's not hard to make a variant that will work for unlimited sizes, but it will need to be longer by about 20 characters (and so score worse).
Note that requesting a shorter length than 62 will produce output of the desired size, but that output will not be working code. Passing a larger length than 3231 will produce the 3231-character version of the quine. Passing something other than an integer will raise an exception.
**Scoring:**
* Generator length: 62 characters, 62 points
* Minimum quine size: 62 characters, 62 points
* Number of supported sizes: 3169, 1.2 points
* All sizes between minimum and maximum accepted: Half off all points above.
* Total: (62+62+1.212)/2 = 62.6 points
[Answer]
# Befunge 98 - (14 + 0 + 0) / 2 = 7
```
'1&k:$$>,:# _@
```
Output is in ~~HQ9+~~ Golfscript (Thanks to Ilmari)
Output for 0:
```
```
Output for 1:
```
1
```
Output for 10:
```
1111111111
```
Explanation:
```
'1 ;push the character `'1'` onto the stack
& ;get the inputted number (`n`), push on stack
'1&k: ;duplicate the `'1'`, `n + 1` times, leaving `n + 2` of `'1'` on the stack
'1&k:$$ ;drop the top two `'1'`s on the stack
>, ;print the top element of the stack
>,:# _ ;duplicate the next, then check if it is `0`.
@ ;if it is `0`, execute this, which ends the program.
, # _ ;otherwise, go back the other way and continue printing
> ;turn back to the right.
'1&k:$$>,:# _@
```
[Answer]
# Ruby -> Ruby (79 points)
char: 51
min size: 28
max size: infinite
`(0..num){|x|print "eval s=\"print 'eval s=';p s\""}`
[Answer]
## Golf-Basic 84 -> Golf-Basic 84
**(54 + 0 + 0) / 2 = 27**
* Program length: *54*
* Minimum supported size: *0*
* Maximum supported size: *none*
* All sizes supported: *yes*
Only limited by the calculator's RAM.
```
i`A:""_Str1:"1"_Str2l`1:A--A:Str1+Str2_Str1@Ag`1d`Str1
```
] |
[Question]
[
Two numbers are said to be 'amicable' or 'friends' if the sum of the proper divisors of the first is equal to the second, and viceversa. For example, the proper divisors of 220 are: 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110 which sum up to 284. 284's proper divisors are 1, 2, 4, 71 and 142, which sum to 220, thus 220 and 284 are friends. Write a function which returns true if and only if a number is a friend of some other number.
Examples:
friend(220) ==> true
friend(7) ==> false
friend(284) ==> true
Function with least number of chars wins.
**NOTE**: I just found out that there is a [similar question](https://codegolf.stackexchange.com/questions/2291/amicable-number-calculator), but I believe this one is simpler and perhaps more general.
[Answer]
## Python, 67
```
a=lambda x:sum(i for i in range(1,x)if x%i<1)
b=lambda x:x==a(a(x))
```
[Answer]
## Haskell, 47
```
o m=sum[x|x<-[1..m-1],m`mod`x<1]
f m=(o.o)m==m
```
Call the `f` function (for "friend").
Didn't provide a `main` because nobody else is doing so.
[Answer]
eTeX, 177 (yes, that language is too verbose)
```
\let~\ifnum\let\c\newcount\c\X\c\D\c\R\def\!{\advance\D1 ~\D<\X~\X=\numexpr\D*\numexpr
\X/\D\advance\R\D\fi\!\fi}\def\a#1{\X#1 \!\X\R\D0\R0 \!\message{~#1=\R YES\else NO\fi}\end}
```
Used as `etex filename.tex "\a{220}"`.
[Answer]
## APL (23)
Let me halve my score after 3 years of golfing. :)
This needs the function trains added to Dyalog APL 14, so it doesn't work on earlier versions, which at the moment of writing unfortunately includes the free (unregistered) version. It *does* work on [TryAPL](http://tryapl.org).
```
f←{+/∆×0=⍵|⍨∆←⍳⍵-1}⍣2=+
```
Or:
```
({+/∆×0=⍵|⍨∆←⍳⍵-1}⍣2=+)
```
(Because it involves a function train, it needs to be either parenthesized or named in order to use it. They both have the same character count, but the first needs to be entered and then called as `f 220`, the second needs to have its argument added to the right of it.)
Explanation:
* `{`...`}⍣2=+`: compare the argument to the result of running the function twice on the argument, return 1 if true and 0 if false
+ `∆←⍳⍵-1`: get all the numbers from 1 to ⍵-1 and store them in ∆.
+ `0=⍵|⍨∆`: get a binary vector which is 1 where `⍵ mod ∆` is 0 and 0 elsewhere
+ `+/∆×`: multiply ∆ by it and return the sum
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes
```
fk+Xfk+?;X≠
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8T8vWjgBie@uIR50L/v@PNjIy0DHXMbIw0TE0MDcBkRamZjqGRoYGOkZmQDkzHSNLIxMdUwMg29TUDKjAMhYA "Brachylog – Try It Online")
Takes input through the input variable and outputs through success or failure.
```
fk+ The proper divisor sum of
the input
X is X,
fk+ and its proper divisor sum
? is the input,
;X≠ which is not equal to X.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
Æṣ⁺=
```
[Try it online!](https://tio.run/##y0rNyan8//9w28Odix817rL9//@/kZEBAA "Jelly – Try It Online")
My first Jelly answer! Doesn't really make use of any of the quirks of Jelly as a tacit language, but I'm still learning it.
Explanation:
```
Æṣ # Sum of proper divisors of input
⁺ # Duplicate last link: Æṣ
= # Result of previous link = Input?
```
[Answer]
## Scala, 67
```
def d(n:Int)=(1 to n-1).filter(n%_==0).sum
def f(n:Int)=d(d(n))==n
```
[Answer]
**Ruby, 95**
```
l=lambda{|n|(1..n-1).select{|e|n.modulo(e)==0}.reduce(:+)}
m=lambda{|n|(l.call(l.call(n))==n)}
```
[Answer]
## Ruby 1.9, 57 characters
```
s=->n{eval (1...n).select{|a|n%a<1}*?+}
f=->n{s[s[n]]==n}
```
Pretty similar to all the other solutions here.
[Answer]
# J, 24 characters
The pure answer is this:
```
=(+/&(((0:=|~)#])i.))^:2
```
It's a monad that takes a scalar and returns 0 or 1 if it's a friend or not. Unfortunately J precedence rules make it impossible to use with no separator from its argument. I'm keeping the character count as such because of the way the question is worded. Anyway, here's a demonstration of three possible ways to use it:
```
NB. using a named verb
f =: =(+/&(((0:=|~)#])i.))^:2
f 220
1
NB. using parentheses
(=(+/&(((0:=|~)#])i.))^:2) 7
0
NB. using verb "Same"
=(+/&(((0:=|~)#])i.))^:2 [ 284
1
```
Obligatory J unscrambling:
* `i. 220` returns the list of naturals below 220 (0, 1, 2 to 219)
* `(|~i.) 220` divides them all by 220 and returns the remainder
* `((0:=|~)i.) 220` compares to 0 (returns boolean as 0 or 1)
* `(((0:=|~)#])i.) 220` returns the natural where the 1s were. In effect: returns the full divisor list.
* `(+/&(((0:=|~)#])i.)) 220` sums them.
* `((+/&(((0:=|~)#])i.))^:2) 220` performs the operation twice.
* `(=(+/&(((0:=|~)#])i.))^:2) 220` checks we fall back on the initial argument.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 5 bytes
```
∆K∆K=
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%88%86K%E2%88%86K%3D&inputs=220&header=&footer=)
Pretty much identical to my Jelly answer.
Explanation:
```
# Implicit input
∆K # Sum of proper divisors
∆K # Sum of proper divisors
= # Equal to input?
```
[Answer]
# Q, 42 33
```
{x={0+/a(&)0=x mod a:(!)6h$(1+x%2)}/[2;x]}
```
shorter by not limiting the check for divisors to enumerations up to n/2 but obviously slower as a result:
```
{x={0+/a(&)0=x mod a:(!)x}/[2;x]}
```
timing
```
q)\t {x={0+/a(&)0=x mod a:(!)x}/[2;x]} 2200000
289
q)\t {x={0+/a(&)0=x mod a:(!)6h$(1+x%2)}/[2;x]} 2200000
124
```
[Answer]
# JavaScript (E6) 57
```
F=n=>(S=n=>{for(t=d=1;++d<n;)n%d||(t+=d)},S(n),S(t),t==n)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth/blob/master/pyth.py), 22 characters
```
DAdRsf!%dTr1dDMkRqkAAk
```
Explanation:
```
DAd def A(d):
Rs return sum(
f!%dT filter on condition (not d%T)
r1d for T in range(1,T)
DMk def M(k):
R return
qkAAk k==A(A(k))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
ѨOѨOQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8MRDK/zBROD//0ZGBgA "05AB1E – Try It Online")
Pretty straightforward. `Ѩ` takes the list of divisors without the element itself, `O` sums these up. `Q` checks if after two iterations the result and the input are equal.
Returns 1 if the number is amicable, else 0.
[Answer]
## GolfScript (25 chars)
```
{.{:a,(\{.a\%!*+}/}2*=}:f
```
`a` can, of course, be replaced by the name of any other variable whose contents you don't care about.
] |
[Question]
[
# Input
An integer `k` composed of `1` and `2`, with at least 3 digits and at most 200 digits.
# Output
Another integer `k'` obtained by removing **at most** one (**could be none**) digit from `k`, such that `k'` is composite, and then another integer `p` for a non-trivial (that is, not 1 or `k'`) factor of `k'`.
# Test Cases
```
121212 -> 121212 10101
11121 -> 1112 506
12211 -> 2211 201
2122121211212 -> 2122121211212 2
212221112112211 -> 21221112112211 4933994911
```
Assume that there is always a valid output.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 15 ~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
DŒPḌẒÐḟṪÆḌṪṭƊ
```
A monadic Link that accepts an integer, `k`, and yields a pair of integers, `[k', p]`.
**[Try it online!](https://tio.run/##y0rNyan8/9/l6KSAhzt6Hu6adHjCwx3zH@5cdbgNxN@56uHOtce6/v//b2RoZGRkaGgIxCAaAA "Jelly – Try It Online")**
### How?
Creates the powerset of `k`s digits to look for candidates for `k'`. Jelly produces powersets that are sorted by length, so `k` will be at the right and all other *valid* `k'` candidates to the right of any other junk.
The code then takes, as `k'`, the rightmost that is not prime (due to length this is also composite), which will either be `k` or `k` less one of its digits. It then tacks on the largest proper divisor of this, `p`.
```
DŒPḌẒÐḟṪÆḌṪṭƊ - Link: integer, k e.g. 212
D - decimal digits {k} [2,1,2]
ŒP - powerset [[],[2],[1],[2],[2,1],[2,2],[1,2],[2,1,2]]
Ḍ - convert from decimal digits [0,2,1,2,21,22,12,212]
Ðḟ - discard those for which:
Ẓ - is prime? [0,1,21,22,12,212]
·π™ - tail 212
Ɗ - last three links as a monad - f(k'=that):
ÆḌ - proper divisors of k' [1,2,4,53,106]
·π™ - tail 106
·π≠ - tack to k' [212,106]
```
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 12 bytes
```
ι*J⌊ᵐϩṄ¬:ḟh;
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLOuSpK4oyK4bWQz6nhuYTCrDrhuJ9oOyIsIiIsIlwiMTIyMTFcIiIsIjMuNC4xIl0=)
Outputs largest possible `k'` and the first prime factor. Takes input as a string
## Explained
```
ι*J⌊ᵐϩṄ¬:ḟh;­⁡​‎‎⁡⁠⁡‏⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌­
ι # ‎⁡Range 0 -> len input
* # ‎⁢And to each index, remove the letter at that position in the input
J # ‎⁣Add the input to that list so the unaltered input is an option
⌊ # ‎⁤Convert each to int
ᵐϩ # ‎⁢⁡Get the maximum by
Ṅ¬ # ‎⁢⁢Not a prime
:ḟ # ‎⁢⁣Push a list of prime factors of that without popping
h; # ‎⁢⁤And pair the first of those with k'
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
⊇PḋṀh;P
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FXe8DDHd0PdzZkWAf8/29oZGRo@D8KAA "Brachylog – Try It Online")
Outputs a list with the factor `p` first, and `k'` second.
### Explanation
Since it’s been proven in a comment that it’s always possible for any input, we can state that P is a subset of the input without specifying the number of digits to remove. Since `⊇` will try the biggest subsets first (including the original input), it will succeed with at most 1 digit removed.
```
‚äáP P is an integer which is a subset of the input integer
PḋṀ P has Ṁany prime ḋivisors (at least 2, so P is composite)
Ṁh;P Output = [First prime divisor of P, P]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
I⮌⌈EIE³Φθ⁻μ⌕θIι⟦⌈Φι∧λ¬﹪ιλι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyi1LLWoOFXDN7EiM7c0F0gXQCRADGMdBbfMnJLUIo1CHQXfzLzSYo1ckFBeCkgArCxTEwx0FKJhJkB1ZOooOALV5ego@OUDTctPKc3JBwnmQNVnxoIZ1v//GxoZGRr@1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Just tries removing one `1` and one `2` since by @l4m2's comment at least one of the two or three numbers will be composite. (Removing every possible digit turns out to take the same length but it will of course be slower.)
```
³ Literal integer `3`
E Map over implicit range
θ Input as a string
Φ Filtered where
μ Current index
⁻ Does not equal
‚åï Index of
ι Outer value
I Cast to string
θ In input string
I Cast to integer
E Map over values
ι Current value
Φ Filter on implicit range
λ Inner value
‚àß Logical And
ι Outer value
¬﹪ Is divisible by
λ Inner value
‚åà Take the maximum
ι Current value
‚ü¶ Make into list
‚åà Take the maximum
‚Æå Reversed
I Cast to string
Implicitly print
```
31 bytes for a very fast version which only looks for factors below `12` (except for `11` itself, which is a special case):
```
I⮌⌈EIE³Φθ⁻μ⌕θIι⟦⌈Φ⌊⟦¹²ι⟧∧λ¬﹪ιλι
```
[Try it online!](https://tio.run/##NYyxDsIwDER/xaORzNAyMiEktiLEWjFEbSQsOQkkacXfByeU82D7/M7T08QpGCnlFtlnPJuU8W5XG5PFwXzYLU7763eow4HgwpJtxDfBwH5J6Krl52o0jHdNBOP/w5ZQvK1j1xPwQ4mTxoTgGvR5mBcJyASyxZWoOpbSd7XKfpUv "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# JavaScript (ES11), 60 bytes
Similar to [l4m2](https://codegolf.stackexchange.com/a/269443/58563)'s strategy, but we first test whether \$11\$ is a divisor of either \$n\$ or \$\lfloor n/10\rfloor\$ before considering removing a digit according to \$n\bmod 3\$.
Expects a BigInt and returns `"k',p"` as a comma-separated string.
```
n=>(x=n)%11n&&(x/=10n)%11n?`${n},3`.replace(n%3n,""):x+[,11]
```
[Try it online!](https://tio.run/##dczBCsIwDAbgu48x3GixTpPdBtUHEWGldqKUdGwiBfHZ66I36fKf8oX8d/M0kx1vw2NL4eJSrxPpg4iaZAlAVSXiTsP@tx279Yvequnq0Q3eWCeobEgVhWzj5qQAzskGmoJ3tQ9X0QtADkm5@nOYPcOIkGFk5@TL@IzfxqX/efK6xOzpAw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 51 bytes
A more limited version without BigInts. This time we first attempt to remove a digit and move to \$p=11\$ only on failure.
Expects a string and returns `[k',p]`.
```
n=>(q=n.replace(n%3,''))%3?[q%11?q/10|0:q,11]:[q,3]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k6j0DZPryi1ICcxOVUjT9VYR11dU1PV2D66UNXQ0L5Q39CgxsCqUMfQMNYqulDHOPZ/cn5ecX5Oql5OfrpGmoaSoREIKmlqcqFLGAIlsIkbGRliEzcCAhzCOMVBEv8B "JavaScript (Node.js) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 64 bytes, string input
```
f=(x,p=9n)=>BigInt(a=x.replace(p%3n,''))%(b=p/3n)?f(x,-~p):[a,b]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVajQqfA1jJP09bOKTPdM69EI9G2Qq8otSAnMTlVo0DVOE9HXV1TU1UjybZA3zhP0z4NqEG3rkDTKjpRJyn2f3J@XnF@TqpeTn66RpqGuqGhIVA1F7qoEQhikzAESmDVYITVICOQBAjiMA8kbwQ2FG7CfwA "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 68 bytes
```
f=(x,k=1n,p=3n)=>(a=x%k+x/k/10n*k)>p>a%p?[a,p]:f(x,p>5?k*10n:k,8n^p)
```
[Try it online!](https://tio.run/##bYxBCsIwEEX33qOQ1GidiFAKSQ8iCqE2olMmgxXJ7WOycCPh795/vKf7uHV6Pfi9o3CbU/JGRIUGSLE5kjRWOBMb3MYOOzhQi9KydQ2PZ6f4Mvhssz2N2OZzQNXTlWWaAq1hmfdLuAsvAICk3PxBXVbhkHlN17WKLrzsF0tf "JavaScript (Node.js) – Try It Online")
Fast. Use fact that input is only 1 and 2.
>
> Proof that it's always possible: For all 1 or 2, remove one digit if odd number of digits, then it's always 11x10101; Otherwise, one of keep, remove a 1, and remove a 2 result 0 modulo 3
>
>
> NeilÔºöEdge case `111` falls under `0 modulo 3` case.
>
>
>
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 47 bytes
```
.|$
$`$'¶
.+
$*
1G`^(..+)\1+$
(..+)\1+$
$.& $.1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX69GhUslQUX90DYuPW0uFS0uQ/eEOA09PW3NGENtFS4ES0VPTUFFz/D/f0MjEOQyNARSXIZGRoZg0sgQAA "Retina 0.8.2 – Try It Online") Link includes faster test cases. Removes the earliest possible digit. Explanation:
```
.|$
$`$'¶
```
List the number with each digit removed in turn, then end with the original input.
```
.+
$*
```
Convert all of the numbers to unary.
```
1G`^(..+)\1+$
```
Keep only the first composite number.
```
(..+)\1+$
$.& $.1
```
Convert it and its highest proper factor to decimal.
In Retina 1 you would be able to fold those last two stages into a single stage, something like this:
```
0L$m`^(..+)\1+$
$.& $.1
```
(The `m` flag is not needed in Retina 0.8.2 because there the `G` stage type splits the input into lines and then matches each line in turn against the regex.)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
eP
e-#PTsMy`
```
[Try it online!](https://tio.run/##K6gsyfj/PzWAK1VXOSCk2Lcy4f9/QyMjQ0MA "Pyth – Try It Online")
### Explanation
```
# implicitly assign Q = eval(input())
ePe-#PTsMy`Q # implicitly add Q
`Q # str(Q)
y # powerset
sM # map to integers
-#PT # filter for non-primes
e # print last value in list
eP # print largest prime factor of value
```
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `o`, 18 bytes
```
Ṅ[ṢḶṪ⸠LĠt“⌊ᶻṄh]ỌḄt
```
[Try it Online!](https://vyxal.github.io/latest.html#WyJvIiwiIiwi4bmEW+G5ouG4tuG5quK4oEzEoHTigJzijIrhtrvhuYRoXeG7jOG4hHQiLCIiLCIxMjEyMTIiLCIzLjQuMSJd)
prints k' and the largest prime factor
```
Ṅ[ṢḶṪ⸠LĠt“⌊ᶻṄh]ỌḄt­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‏​⁡⁠⁡‌⁤​‎⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁤⁣‏⁠‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁤⁤‏⁠⁠‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌­
Ṅ # ‎⁡is prime?
[ # ‎⁢
ṢḶṪ # ‎⁣group sublists by length and drop the tail
⸠LĠt # ‎⁤group by max length, take the longest
“⌊ᶻṄ # ‎⁢⁡convert to number and filter by not prime
h # ‎⁢⁢take the first number left
] # ‎⁢⁣
Ọ # ‎⁢⁤print k'
Ḅt # ‎⁣⁡largest prime of k'
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
√¶ íp‚â†}Œ∏D√íŒ∏‚Äö
```
[Try it online](https://tio.run/##ASAA3/9vc2FiaWX//8OmypJw4omgfc64RMOSzrjigJr//zExMQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w8tOTSp41Lmg9twOl8OTzu141DDrv87/aENDQx1DIxDUATKNQBwjoJARiAJBsAyIZwSWBsvGAgA).
**Explanation:**
```
√¶ # Get the powerset of the (implicit) input
í # Filter, only keeping those which are:
≠ # NOT
p # a prime number
}θ # After the filter: pop and keep the last/maximum
D # Duplicate it
Ò # Pop and get its prime factors
θ # Pop and keep the last/maximum again
‚Äö # Pair the two together
# (after which this pair is output implicitly as result)
```
The `íp‚â†}` can be a number of other things with a similar result: `√êp√èK`; `D√íÀúK`; `¬§√ÖPK`.
] |
[Question]
[
I have a follow-up question here from my previous [question](https://math.stackexchange.com/questions/4646752/bumping-series-and-its-formula) on Math SE. I am lazy enough to explain the content again, so I have used a paraphraser to explain it below:
I was considering arbitrary series, springing up as a top priority, when I considered one potential series in my mind. It is as per the following:

The essential thought is, take a line of regular numbers \$\mathbb{N}\$ which goes till boundlessness, and add them. Something apparent here is that the most greatest biggest number \$\mathbb{N}\_{max}\$ would be \$\mathbb{N}\_{i}\$. In essential words, on the off chance that we go till number 5, \$\mathbb{N}\_5\$ the level it comes to by summation is 5.
Further, continuing, we can get:

The essential ramifications here is that we knock the numbers by unambiguous \$\mathbb{N}\$. At start, we take the starting number, for our situation it is 1, we move once up and afterward once down. Then we do it two times, threefold, etc. So `1 3 2` as per my outline is one knock. At the closure \$\mathbb{N}\$ which is 2 here, we will hop it by 2 and make it low by 2. So it gets `2 5 12 7 4`. Here, expect \$\mathbb{N}\_i\$ as the quantity of incrementation, before it was 1, presently it is 2. We get various sets, with various terms, however absolute number of terms we overcome this would be \$2 \mathbb{N}\_i + 1\$. Presently, it will begin from 4, continue taking 3 leaps prior to arriving by three terms. By this, we get series featured by circles in that three-sided exhibit as:
```
1, 3, 2, 5, 12, 7, 4, 9, 20, 44, 24, 13, 7, 15, 32, 68, 144, 76, 40, 21, 11, 23, 48, 100, 208, 432, 224, 116, 60, 31, 16...
```
The series appear to be disparate, my particular inquiry this is the way to address this series in Numerical terms.
Challenge: Implement the algorithm which can build this series.
Scoring Criteria: It is ranked by fastest-algorithm so the answer with lowest time complexity is considered (time complexity is loosely allowed to be anywhere) but the program must have been running accurate result.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
NθI⊘×⊕θX²↔⁻θ⊕×⊖⌈₂θ⌈₂θ
```
[Try it online!](https://tio.run/##dYyxDgIhEER7v4JySbCxM1eZs/AKzUX9AQ43SgLLAcv5@UhijDZO@WbemIdOJmhX60Bz4VPxEyaIsluNyRJDrzPDQbsFb3C1HjMMZBJ6JG4kSiXG8GzGRondlIMrjHC0VDJEJX6nb3mPX9KjdZbucIlFJzyHwO1Ptsc/xSddrdu6XtwL "Charcoal – Try It Online") Link is to verbose version of code. Outputs the `n`th term. Explanation:
```
Nθ First input as a number
θ First input
⊕ Incremented
× Multiplied by
² Literal integer `2`
X Raised to power
θ First input
↔⁻ Absolute difference with
θ First input
₂ Square root
⌈ Ceiling
⊖ Decremented
× Multiplied by
θ First input
₂ Square root
⌈ Ceiling
⊘ Halved
I Cast to string
```
30 bytes in integer arithmetic:
```
NθI⊘×⊕θX²↔⁻θ⊕×⊖⌈₂θ⌈₂θ
```
[Try it online!](https://tio.run/##TY5NDoIwEIX3nqLLNqmJsGVFJDEsMCy8QIGJnaQUbKdw/FpEI7Oan@@9N71Wrp@UibG2c6B7GDtw/CWKU@k9Pi3PJNNpWjUaYPzmQNEGSNZOa2q0ZLkQgjVq/gpq2zsYwRIMu7R1aIlflad0owoXHIA/cAR/ZFPmzzOXrOz8ZAIBb9AGv8Ud0V1cwX@jxZb1qf2hIsbsEs@LeQM "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Port of [Neil's answer](https://codegolf.stackexchange.com/a/258377/53748) (I was working towards it myself but he nailed it).
Unsure of the complexity of this closed-form formula, but *think* it is \$O(M(B(n))B(n))\$ where \$n\$ is the input, \$M(x)\$ is the multiplication of two \$x\$ bit numbers and \$B(x)\$ is the bit-length of \$x\$.
```
½Ċ’×$‘ạ⁸’2*ב
```
A monadic Link that accepts \$n\$ and yields \$a(n)\$.
**[Try it online!](https://tio.run/##y0rNyan8///Q3iNdjxpmHp6u8qhhxsNdCx817gByjbQOTwfy/@scbs961DBHwdZO4VHDXM3I//9zMotLNIoS89JTNQx1FEwMNTUVtBWiDQ0MdBSABJQCIR0FUxiIBQA "Jelly – Try It Online")**
### How?
```
½Ċ’×$‘ạ⁸’2*ב - Link: positive integer, n
½ - square-root
Ċ - ceiling
$ - last two links as a monad - f(x=that):
’ - decrement (x)
× - (that) multiply (x)
‘ - increment (that) -> A
⁸ - chain's left argument = n
ạ - (A) absolute difference (n)
’ - decrement (that) -> E
2 - two
* - (2) exponentiate (E)
× - (that) multiply (n)
‘ - increment
```
---
To avoid floating point arithmetic we could instead do it in ~~17 16~~ 14 bytes (-2 thanks to Neil!):
```
’ƽ‘×$‘ạ⁸2*בH
```
**[Try it online!](https://tio.run/##y0rNyan8//9w26G98UBi06OGGYenqwDJh7sWPmrcYaR1eDqQ4/Ff53B71qOGOQq2dgqPGuZqRv7/n5NZXKJRlJiXnqphqKNgYqipqaCtEG1oYKCjACSgFAjpKJjCQCwA "Jelly – Try It Online")**
This replaces `½Ċ’×$` with `’ƽ‘×$` and moves the decrement out of the exponent, instead halving at the end (`H`).
```
’ƽ‘×$ - chain: integer n
’ - decrement -> n-1
ƽ - integer-square-root (n-1) (uses only integer arithmetic)
$ - last two links as a monad - f(x=that):
‘ - increment (x)
× - (that) multiply (x)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 97 + 3 bytes
+3 bytes from `-lm`. Runs in O(n) time, where n is the index.
```
f(M,n,v,l,c){l=0;for(n=c=1;M--;l+=v&&v--?:-1)n=((v=l?v:c++)?2*n:n/2+.5)+pow(2,v?l:l-2);return n;}
```
[Try it online!](https://tio.run/##LU3BDoIwFLvzFS8kkje3KSzxwlz4Av/AC5mOkIyHQZ0Hwq87B7GHNmmb1srO2hgdXgSJILywbPam1G6ckIw1lb5IqT03oSiClE0tK0YGMRjfhNpyzhq1p5qOih9OjD/GDyoRGl97qZie7q/3REB6iT29YGh7QgZzBgnpAXB1ezBQ6iRnUKumzX9lxWNKHYf57nalXIDDnjG9pcvG/4tSZ0v8Wufb7hmlH34 "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
tîD<*-<ÄoI>*;
```
Another port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/258377/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##MzBNTDJM/f@/5PA6FxstXZvDLfmedlrW//9bAgA) or [verify all test cases](https://tio.run/##MzBNTDJM/W9s5O5nr6TwqG2SgpK9n8v/ksPrXGy0dG0Ot@T72WlZ/9f5DwA).
The TIO-links use the legacy version of 05AB1E, because the regular 05AB1E on TIO is out-of-date, and still contains [an already fixed bug when using `o` on decimal values ending with `.0`](https://github.com/Adriandmen/05AB1E/issues/196).
**Explanation:**
Basically implements the formula found by *@Neil*:
$$a(n) = \frac{(n+1)\times 2^{\left|n-\left\lceil\sqrt{n}\right\rceil\times(\left\lceil\sqrt{n}\right\rceil-1)-1\right|}}{2}$$
```
t # Get the square root of the (implicit) input-integer
î # Ceil it
D # Duplicate it
< # Decrease the copy by 1
* # Multiply the two together
- # Subtract this from the (implicit) input-integer
< # Decrease that by 1
Ä # Get the absolute value of that
o # Take 2 to the power that
I> # Push the input+1
* # Multiply the two together
; # Halve it
# (after which the result is output implicitly)
```
[Answer]
# Mathematica, 53 bytes
Formula:
$$
f(n)=\frac{(n+1) \times 2^{|n-\lceil\sqrt{n}\rceil \times(\lceil\sqrt{n}\rceil-1)-1|}}{2}
$$
```
f=((#+1)*2^Abs[#-⌈Sqrt@#⌉*(⌈Sqrt@#⌉-1)-1])/2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/NVkNDWdtQU8sozjGpOFpZ91FPR3BhUYmD8qOeTi0NZJ6uoaauYaymvpHa/5DEpJzU6LTovFid6jwdQx1Dg9pYff2Aosy8kv8A)
[Answer]
# JavaScript, 49 bytes
Port of [Neil's answer](https://codegolf.stackexchange.com/a/258377/53748)
```
n=>-~n*2**~-Math.abs(n+(c=(n**=.5)%1?~n:-n)*~c-1)
```
Formula:
$$
f(n) = \frac{(n+1)\times 2^{\left|n-\left\lceil\sqrt{n}\right\rceil\times(\left\lceil\sqrt{n}\right\rceil-1)-1\right|}}{2}
$$
Try it:
```
f=n=>-~n*2**~-Math.abs(n+(c=(n**=.5)%1?~n:-n)*~c-1)
for(i=0;i<20;)console.log(f(++i))
```
## Upd 54 -> 49
Thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for the [tip](https://codegolf.stackexchange.com/questions/258357/bumping-series-implementation/258868?noredirect=1#comment571122_258868) to reduce bytes count
] |
[Question]
[
[Cops thread](https://codegolf.stackexchange.com/questions/242616/slice-the-source-code-cops)
# Robbers
Robbers, your job is to find the slices of the corresponding cop's code.
## Scoring
The robber with the most cracks wins.
## Example
Take this code:
`iimmppoorrtt ssyymmppyy;;pprriinntt((ssyymmppyy..iisspprriimmee((iinnppuutt(())))))`
The slice here is [::2], so the robber's post could look like this:
```
Cracked <somebody>'s answer
```iimmppoorrtt ssyymmppyy;;pprriinntt((ssyymmppyy..iisspprriimmee((iinnppuutt(())))))```
The slice is [::2].
```
[Answer]
# [Python 3](https://docs.python.org/3/), [cracks Sisyphus's answer](https://codegolf.stackexchange.com/a/242635/84290)
```
input((input()[(-1)::1-1-1]))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzOvoLREQwNCaUZr6BpqWlkZ6gJhrKbm//8eqTk5@Qrh@UU5KYoA "Python 3 – Try It Online")
Given by the slice `c[-2158:-4855:-93]`
I was initially surprised to find that there were no characters besides those used for `input()[::-1]`. The `input()` is a dead giveaway though and a brute force search reduced the input to a handful of possibilities. I then just looked at them individually until I found the correct code.
[Answer]
# [Python 3](https://docs.python.org/3/), 181 bytes
[OP](https://codegolf.stackexchange.com/a/242621/84290)
```
if True: print =eval (' exit')# not open u
exit or ( eval)('14')
# NO
open or 15* id( int( int(int (int( id( print( print([111][:123][:55555-11111111111]))))))))#11;
```
The slice is simply `program[::6]`, giving us:
```
irp=(input())
print(irp[::-1]);
```
[Try it online!](https://tio.run/##RY4xC8IwEIX3/IpnOyQRHM5ah0p3J10Eh9JB2oiFkJSQiv76mLQF33DHPT7evfHrX9YUIXR1lmXDE8DNTaoCRjcYj1q9HxqCA@ozeC5zGOsBOyoT0Qks2bAOEEioFJwOXLIclyuLBFvICFC5xdALIMaKeaR8sVzJnx@KdTVE1DYV7Ys4y6Qd/dXKVTnRKfZuqurYsthFdaKTIZyV1hZ363S/@QE "Python 3 – Try It Online")
[Answer]
[-3::-14](https://codegolf.stackexchange.com/a/242636/)
# [Python 3](https://docs.python.org/3/), 56 bytes
```
import sys as s
s.stdout.write(s.stdin.readline()[::-1])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKG4slghsVihmKtYr7gkJb@0RK@8KLMkVQPMzczTK0pNTMnJzEvV0Iy2stI1jNX8/98jNScnXyE8vygnBQA "Python 3 – Try It Online")
I admit that I used tools
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), cracks [emanresuA's answer](https://codegolf.stackexchange.com/a/242641/78850)
```
ż⇩İ
```
Generated from a slice of `[1:15:6]`
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), cracks [EmanresuA's second answer](https://codegolf.stackexchange.com/a/242645/78850)
```
ɖ‡$"t¤+f
```
Given by the slice `[11:33:3]`
[Answer]
# Python 3, cracks [AnttiP's answer](https://codegolf.stackexchange.com/a/242628/64121)
`[53:586:4]` results in:
```
def g(o):exec("".join(map(chr,map(sum,zip(map(ord,"ikbgm!bginm!\"T33&*V\""),99*[o])))))
x=0
class f:
def __del__(self):g(x)
y,x=f(),7
```
[Try it online!](https://tio.run/##HY29CsIwGAD3PEWaQb6UDxE6iIXuPoDoYCW0zU@jSVMahdSXj9RbDm65eX2PYapylkpTA4HXKqkBGNs/g53AdzMM44Kb48fj187/FhaJzL5644ve2MkXLbtU1a68toxxPJ3Ke3jwDZKaAxlcFyPVNaHbRQipnBAQldO8NpA4WTE1Gjgecz4r5wLSW1icLH4 "Python 3 – Try It Online")
`g` increases each codepoint in `"ikbgm!bginm!\"T33&*V\""` by its argument and then executes the resulting string as code. For `o=7` this executes `print(input()[::-1])`.
When the program is done running the garbage collector deletes `y`, calling `g(x)` in the process.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes, cracks [Aaroneous Miller's answer](https://codegolf.stackexchange.com/a/242626/78850)
```
wRh
```
Obtained from a slice of `[13::-5]`. Ngl you should have used that one quirk that only you know about because I know quite a few vyxal quirks too.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), [Actually cracks l4m2](https://codegolf.stackexchange.com/a/242624/84290)
```
,[>><,]<[.<]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ9rOzkYn1iZazyb2/39DI2MTUwA "brainfuck – Try It Online")
The slice is `c[1::3]`. And yes, I literally just bruteforce copy-pasted different slices to TIO, until I found a solution.
[Answer]
# [Python 3](https://docs.python.org/3/), 72 bytes, [cracks ths's answer](https://codegolf.stackexchange.com/a/242662/84290)
```
i=input();a=len(i);exec("for n in(i*8**9) [1:]:i=(i*a) [::~a]");print(i)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9M2M6@gtERD0zrRNic1TyNT0zq1IjVZQyktv0ghTyETKKJloaVlqakQbWgVa5VpC@QnAjlWVnWJsUqa1gVFmXklQF3//3uk5uTkK4TnF@WkAAA "Python 3 – Try It Online")
Slice used: `code[4981:-201:67]`
If you want to see the code finish ~~within your lifetime~~ a bit faster, change the `8**9` to `2` or any other positive even number.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 45 bytes, [Cracks Big Midol's second answer (new revision)](https://codegolf.stackexchange.com/a/242743/84290)
```
print(str(str(input()[::-1][::-1][::-1][:])))
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v6AoM69Eo7ikCIwz8wpKSzQ0o62sdA1jUclYTU3N//89UnNy8hXC84tyUgA "Python 3.8 (pre-release) – Try It Online")
Slice is `code[145::2]`
[Answer]
# [Python 3](https://docs.python.org/3/), 43 bytes, [cracks Bgil Midol's second answer (original version)](https://codegolf.stackexchange.com/a/242743/84290)
```
print(str(str(input()[::-1][::-1][::-1])))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Eo7ikCIwz8wpKSzQ0o62sdA1jkUlNTU2F//89UnNy8hXC84tyUgA "Python 3 – Try It Online")
Slice is s[40:-10:2]
Fastest crack in the west?
[Answer]
# Python, cracks [Bgil Midol's third cop](https://codegolf.stackexchange.com/a/242823/106710)
```
[1011::3]
```
[Try it online!](https://tio.run/##NZRfa6RYEMXf/RSX/T1E6e6w1/99YSAwuzCBJRvYxxCCrSYtOCpXmySfPlt1ewZE9Fp16pyqUy6f23mesq@vdu56883c3Ny0FC3tSNXQrhQrq@H4SOFZB8zEsLH11B7vSCN6Q2OoDalhvWNd2TZsg5G7xLdUPxl6io30zDxTdJp1NgwGYygMWaeA2SvWMDesMa8n6pG0wZ8pE2woJPijoQqFrs9SNzdsHtNTbWQXMk8@Kaw7cRoxQuPM8QnjyBz5gdJinxXNR5iIY4sZiRrsiglKx3sq0bjQXegF8wd1Qy2YnVKqeozHOaZIq5yMchZK9R1@DZIbVXoctIci/K7Hb7RnzEzbUUZMIWUO5AVTmBevbFK3YY7ppdZekcuTPrRGG5jvtb2NBCe0jiJS1UXouUBl4epDM9tN6ZlPOoeNlNi1RRJchng5cSGyDimSKISjHZcTZkfb4ndEHfkTlaVwNDmlY02JnhVEeBbQSZalOeCkmQdyS33Q@O1AbSlDk6MDfYjJQ0xhyYJVXChqAtR9oCH0Vpn@hyqVbmSLtl0m/jP6Net9CD6GLBMknwLOIejKF/aNzi5fqaPA8GqqkHsM@JKy9@oxGU1@0Rb5KSAMuIlm4emCk1nHajYTJitOSH53LAvldnIXw8gEF6ynCrsgrhsl61Exs4HHiTRsh/Okt@qcNCb5VyPHheqi8fUP8uCoqmMdVbIXbrd6aGPSB4aZo@D0pMEJ7gErWzNRC/99UPdAOZNOmrvteQ0nh5n5GpOwS9QqRWhXgkrwwsSzfyM7qyWsLOMnhVCaOUfEPfaDTJZIzBZT/6GfRFERNIqi@pbshfqFoaVs6EeOcr1gXjjGKryd8Av@Qr7pSZywiIWc7p0JTpifldgkyEkk/5iv//65//73X/LD0f/Ok/3TWuey5yha/DBt8fVrEvUfffv75eu9f3t/e39v/gc)
The result of this slice is:
```
exec("print.__call__(input()[::-1])")
```
] |
[Question]
[
The name of the challenge was prompted by [this GIF](https://i.stack.imgur.com/8k6sq.jpg) and the GIF also gave me the idea.
Your challenge today is to take a input guaranteed to be \$2<=n<=100\$ and output a sequence of `x` and `-` characters.
The output for a number N represents a sequence of operations applied to 1 where `x` means "multiply by 2" and `-` means "subtract 1". Starting from 1, reading left to right and doing them in order will give you the number N that was inputted.
If you want, you can output using characters other than x and - so long as the choice is consistent through all outputs.
Your strings may be outputted in reverse so long as all are reversed or there is some indication of which are in reverse.
Your score is the source code's size in characters plus the total length of all outputs (again in characters). Have fun everyone!
[Answer]
# [Python 2](https://docs.python.org/2/), 37 bytes (+830 char output = 867)
```
f=lambda n:2/n*"0"or`n%2*10`+f(-~n/2)
```
[Try it online!](https://tio.run/##BcFNCoAgEAbQfacYhED7IZ2l0F0yyhLqU4Y2bbq6vVfe58zgWuN8hXvdAsHzhE5ZlWVBy52zSx/1@GFiU2MWAiWQBBy75oGcdcY3VCThIQwUNUz9AQ "Python 2 – Try It Online")
0 for double, 1 for decrement, in reversed order. -1 byte thanks to dingledooper for the base case.
---
# [Python 2](https://docs.python.org/2/), 39 bytes
```
lambda n:bin(n-1)[2:].replace('0','10')
```
[Try it online!](https://tio.run/##BcExCoAgGAbQvVP8mwoW6ih0kmrQ0hLsU8Sl09t79etPgRlx3Ud2r78cwfoEjlmLzdhjaaFmdwbOFJNMKyZGLI1ACdQc7sCNJK20sBPVltAJkiKHGD8 "Python 2 – Try It Online")
1 for double, 0 for decrement
[Answer]
# [Python 2](https://docs.python.org/2/), 42 bytes, score = 872 (42 + 830)
```
f=lambda x:x>1and f(-~x/2)+"x"+x%2*"-"or""
```
[Try it online!](https://tio.run/##bYxBCsIwEADvecWyIGRtiibHQv1LpI0G0k2JEdZLv54qenTOM7O@6j2zay2MyS/XyYMMcrGeJwi63@TkqEPBTg7uiD3mgtjWErkC1lx9ghENPJ6LTjProCMRhFwgQmQonm@zdsaeLZH6VajUX2FQ8OYrRfM5tR0 "Python 2 – Try It Online")
This can be 43 bytes in python 3 by replacing `/`by `//`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes, score 841
```
⭆↨⊖N²…x-⁻²ι
```
[Try it online!](https://tio.run/##DcWxCoAgEADQX5GmOzAI17ZqaSiCvsDsKMFMTKO@/mp4PLPraE7tmKdofYI5/W2DDtDoi6AjE@kgn2iF3oecxnwsFAFRCvVrX@Oo3c8AxVMWUgzW5wuUFBYRa2ZVcXm7Dw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
N Input number
⊖ Decrement
↨ ² Convert to base 2
⭆ Map over digits and join
x- Literal string `x-`
… Truncated to length
² Literal integer `2`
⁻ Subtract
ι Current digit
Implicitly print
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 28 bytes + 830 chars in output = 858
```
f=n=>n^1?n%2*10+f(n+1>>1):''
```
[Try it online!](https://tio.run/##TYs9DsIgFIDncgoWA4g2paMVPIS7SYNQX0PeM0BcjGfHODRx/X7W@TUXn@FZj0j30Fq0aB3ezAV3494MOkrUxjmjTkK0FCovnnK41swtF4JFyhLsOMHZmmGYQGv1Zp0nLJRCn2iRcOBRglKs205tf4B92H@2yT4FXOpDtS8 "JavaScript (Node.js) – Try It Online")
"0" represents \*2, "1" represents -1, Output is reversed.
Simple, but quite effective approach. Divides the number by two if it is even, else subtracts 1 from it.
Thanks to @A username for -3 bytes!
Thanks to @xnor for -2 bytes!
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 6 bytes
```
‹bṅ0₀V
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%80%B9b%E1%B9%850%E2%82%80V&inputs=6&header=&footer=)
Xnor port. -2 thanks to Aaron Miller.
[Answer]
# [Python 3](https://docs.python.org/3/), 129 bytes, score = 129+830 = 959
```
def f(n,x=1):
for y in range(2**x):
c,s=1,''
for i in' '*x:c+=~y%-2|c;s+='-x'[y%2];y//=2
if c==n:return s
return f(n,x+1)
```
[Try it online!](https://tio.run/##TY7NDoIwEITvfYoJCSk/JQreMOtTeBMPBIuSkMWUmtDE@OpYwIO3yew3M/t09jHwYZ5vukUbsZooj0uBdjBw6Bim5ruOiiSZFhuNGilXUnq5IJ1HJGQylU1KHxdmxbs5jinJbJIXFxbXo9vtqPB016Ih4tJo@zKMUeCn1tE0j2c72LoHYS@WZv4bV8j361dGjx7wiVhgw1NCrznyB289TcfW1yHIToHCaorNDCqu@LxESoS3AOGWj@cv "Python 3 – Try It Online")
Brute force all strings of all lengths starting from length 1.
*thanks to ovs for -12 bytes*
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 33 bytes, score 863
```
.+
$*
+`(1+)(\1(1)?)
$2x$#3$*-
1
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLO0HDUFtTI8ZQw1DTXpNLxahCRdlYRUuXy5Dr/38TLkMjLhMgaW4EAA "Retina 0.8.2 – Try It Online") Link includes test cases. [Try it online!](https://tio.run/##K0otycxL/M9laGCgonVoGxeXil7Cfz1tLhUtLu0EDUNtTY0YQw1DTXtNLhWjChVlYxUtXS5Drv96/wE "Retina 0.8.2 – Try It Online") Link is to test suite that counts the score. Explanation:
```
.+
$*
```
Convert to unary.
```
+`(1+)(\1(1)?)
$2x$#3$*-
```
Keep dividing by `2`, rounding up, inserting an `x` each time but also a `-` if the result was rounded up, until the remainder is `1`.
```
1
```
Delete the remaining `1`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage), score 836
```
<b0T.:
```
Port of most other answers.
Outputs `1` for `x` and `0` for `-`.
[Try it online.](https://tio.run/##yy9OTMpM/f/fJskgRM/q/38jAwA)
Would be **11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** if we'd use `x-` instead:
```
<b0T.:T„x-‡
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fJskgRM8q5FHDvArdRw0L//83MgAA)
Or alternatively:
```
<bε_>„x-s∍?
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fJunc1ni7Rw3zKnSLH3X02v//b2TwX1c3L183J7GqEgA)
**Explanation:**
```
< # Decrease the (implicit) input by 1
b # Convert it to a binary string
0T.: # Replace all "0"s with "10"s
# (after which the result is output implicitly)
<b0T.: # Same as above
T„x-‡ # Transliterate "10" to "x-"
# (after which the result is output implicitly)
<b # Same as above
ε # For-each over each digit:
_ # Invert the bit (1 if 0; 0 if 1)
> # Increase it by 1 (2 if 0; 1 if 1)
„x- # Push string "x-"
s # Swap so the earlier integer is at the top of the stack
∍ # Shorten the "x-" string to this length
? # Pop and output it without trailing newline
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~7~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1), score: ~~837~~ 835
Uses `1` for `x` and `0` for `-`.
```
´¢rTA
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=tKJyVEE&footer=rrBneGkt&input=MTAw) (footer converts output to `x`s and `-`s) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=xMQ&code=tKJyVEE&footer=Vq6wZ3hpLcNpU2knOmmwVXMg%2bTM&input=OTkKLW1S)
```
´¢rTA :Implicit input of integer U
´ :Prefix decrement the U that's contained in the next shortcut
¢ :Convert U to binary string
r :Replace
T : 0 with
A : 10
```
[Answer]
# [A0A0](https://esolangs.org/wiki/A0A0), 186 161 152 bytes + 5841 output = 6027 6012 6003
```
P50P45
P50P50
P50P45
P45P50
P50P50
G-5I0A3V0G0P45S1A0
G-1A0A0
A0C3G1G1A0
A0L100S2M6
A0A1G-3G-3A0
G-3
A0A0
G1G1A0C3G1G1A0
G-4A0G-4A0
A1G-3G-3A0A1G-3G-3A0
```
We're making use of the fact that the challenge doesn't require us to give a shortest length sequence, just *a* sequence. For a language like A0A0, any math operation more fancy than multiplication already gets annoying to implement, so no complicated stuff here. Instead we generate a sequence by first going up to one hundred (with the sequence `xxx-x-x-xx`) and then just going down by one repeatedly until we hit the right number.
This penalizes us heavily in the output score, but it saves a lot of work in the actual code. (It does make for an even worse phone entry screen, though, so there's that.)
```
P50P45
P50P50
P50P45
P45P50
P50P50
G-5
```
This prints `222-2-2-22`. I chose a different character than `x` (allowed per the challenge), since `x` has an ascii value of 120, which is three characters, whereas `2` is only two characters (ascii value 50). You could technically do unprintable ascii values to get into the single digits, but in my opinion that is a bit against the spirit of the question. This is split across two columns, which gives the same amount of bytes as a single column, but two columns makes it easier to read on this site.
```
I0 A3 V0 G0 P45 S1 A0
G-1 A0 A0
A0 C3 G1 G1 A0
A0 L100 S2 M6
A0 A1 G-3 G-3 G-3 A0
G-3
```
We now need to loop. We first take the input, so we can generate the right amount of dashes for the sequence. We then put this in the operand and append this operand, as well as the rest of the instructions into the loop below. This completes a loop that loops starting from the input until the value one hundred and prints a dash every single time. These are the actual instructions in the loop.
```
L100 S2 M6 V0 G0 P45 S1
L100 ; compare the operand to value one hundred, store result in operand
S2 ; add two to the operand
M6 ; multiple the operand by six
V0 ; the operand
G0 ; goto the offset of the operand
P45 ; print a dash
S1 ; add one to the operand
```
The jumping always jumps to either the loop below it, or to nothing which halts the program. The loop below simply jumps back up to this loop.
```
A0 A0
G1 G1 A0 C3 G1 G1 A0
G-4 A0 G-4 A0
A1 G-3 G-3 A0 A1 G-3 G-3 A0
```
This is the loop that jumps back up to the first loop. It looks a bit weird, but that's because this loop doesn't do anything other than jump back up top, so we can manually evaluate the loop until it gets into a position that has the shortest amount of bytes. This configuration saves one byte from the next best configuration and thirteen bytes compared to the worst configuration.
Once the value is equal to one hundred (or greater, but that will never happen), the loop will jump down to a place beyond this loop which is empty and will thus halt the program.
Edit: Optimized by 15 bytes. I misunderstood the default loop template I make use of in the code. I was under the impression that the amount of G1 and G-3 instructions on line 2 and 4 of the loop resp. needed to match the amount of instructions inside the loop. This is not the case, you only need two of them (although more also work, as long as each line has an equal amount of them). This change removes these extra instructions.
Edit 2: Optimized by 9 bytes. Because of edit two, it turns out that there's actually no minimum of three instructions in the loop. This allows us to drop three instructions, totalling nine bytes.
[Answer]
# [Haskell](https://www.haskell.org), 50 bytes
```
g 1=""
g n|(d,m)<-divMod n 2="x-"!!m:g([d,n+1]!!m)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN43SFQxtlZS40hXyajRSdHI1bXRTMst881MU8hSMbJUqdJUUFXOt0jWiU3TytA1jgRxNiM7NuYmZeQq2CgVFmXklCioKQHOMITIwswE)
String is outputted in reverse.
] |
[Question]
[
You will be given an ASCII text. This text may have zero, one or many appearances of a split a character (let's assume it will be the space character )
You will also be given an offset integer value (zero based) anywhere between zero and the length of the text.
You should calculate the relative offset inside the one split text, which contains the absolute offset, as well as the index of that very split text.
If the given offset is at the split character the last split should have the offset
It's hard to describe (comments welcome), so here are some examples
```
text: Lorem ipsum dolor sit amet
offset: 20
Lorem ipsum dolor sit amet
enter code here
--------------------^
000000000011111111112
012345678901234567890
Result: 2, 3
Explanation: If we split the text along the space characters, the split text, where the offset is in, is the fragment `sit` which is the 3rd split (count starts at zero) and the offset inside this fragment is 2
sit
--^
012
```
Some more examples
```
Text Offset Result
Lorem ipsum dolor sit amet 0 0, 0
^
Lorem ipsum dolor sit amet 1 1, 0
-^
Lorem ipsum dolor sit amet 2 2, 0
--^
Lorem ipsum dolor sit amet 3 3, 0
---^
Lorem ipsum dolor sit amet 4 4, 0
----^
Lorem ipsum dolor sit amet 5 5, 0
-----^
Lorem ipsum dolor sit amet 6 0, 1
------^
Lorem ipsum dolor sit amet 7 1, 1
-------^
Lorem ipsum dolor sit amet 8 2, 1
--------^
Lorem ipsum dolor sit amet 9 3, 1
---------^
Lorem ipsum dolor sit amet 10 4, 1
----------^
Lorem ipsum dolor sit amet 11 5, 1
-----------^
Lorem ipsum dolor sit amet 12 0, 2
------------^
Lorem ipsum dolor sit amet 13 1, 2
-------------^
Lorem ipsum dolor sit amet 14 2, 2
--------------^
Lorem ipsum dolor sit amet 15 3, 2
---------------^
Lorem ipsum dolor sit amet 16 4, 2
----------------^
Lorem ipsum dolor sit amet 17 5, 2
-----------------^
Lorem ipsum dolor sit amet 18 0, 3
------------------^
Lorem ipsum dolor sit amet 19 1, 3
-------------------^
Lorem ipsum dolor sit amet 20 2, 3
--------------------^
Lorem ipsum dolor sit amet 21 3, 3
---------------------^
Lorem ipsum dolor sit amet 22 0, 4
----------------------^
Lorem ipsum dolor sit amet 23 1, 4
-----------------------^
Lorem ipsum dolor sit amet 24 2, 4
------------------------^
Lorem ipsum dolor sit amet 25 3, 4
-------------------------^
Lorem ipsum dolor sit amet 26 4, 4
--------------------------^
```
[Answer]
# [Python 3.8](https://docs.python.org/dev/whatsnew/3.8.html), 56 bytes
```
lambda a,b:(x:=a[:b].split(' '))and[len(x[-1]),len(x)-1]
```
[Try it online!](https://tio.run/##ldNLCoMwFIXheVcRnJiALb2xDyu4g@7AOoioVMiLmIJdfSpdwXF2Bv/oflz/jW9ny8qHNDWvpJXpB8VU0dd8rRvV1n13WryeI89ZLoSyQ6tHy9f2SJ0o/lNsM/kw28gnnj1dGA2b/fIxbHDaBbbMkSkzxqxgZyEOWElwKeGyhMsLXF7h8gaXd7is4PKBX34HEq5EOBPhToRDES5FOBXhVoRjEa4lcS2546dwLYlrSVxL4lpy00o/)
[Answer]
# Perl 5, ~~47~~ 44 bytes
```
$_=substr$_,0,<>;/.* /;$_=$'=~y///c.$".y/ //
```
* `$_=substr$_,0,<>;` to extract first n (from nextline <>) characters of input `$_` and store in default argument.
* `/.* /` to match largest string ending with space
* `$_=$'=~y///c.$".y/ //` default argument `$_` (which will be printed `-p` option) is set with concatenation `.` of length of post-match : `$'=~y///c`, `$"` space (list argument delimiter when interpolated betwen double quotes), and `y/ //` number of spaces in current default argument.
[TIO](https://tio.run/##K0gtyjH9/18l3ra4NKm4pEglXsdAx8bOWl9PS0HfGiisom5bV6mvr5@sp6KkV6mvoK///79PflFqrkJmQXFprkJKfk5@kUJxZolCYm5qCZehARc@WUO8siZ4ZU3/5ReUZObnFf/XLcgBAA)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╓ò)♣*
```
[Run and debug it](https://staxlang.xyz/#p=d69529052a&i=%22Lorem+ipsum+dolor+sit+amet%22++0%0A%22Lorem+ipsum+dolor+sit+amet%22++1%0A%22Lorem+ipsum+dolor+sit+amet%22++2%0A%22Lorem+ipsum+dolor+sit+amet%22++3%0A%22Lorem+ipsum+dolor+sit+amet%22++4%0A%22Lorem+ipsum+dolor+sit+amet%22++5%0A%22Lorem+ipsum+dolor+sit+amet%22++6%0A%22Lorem+ipsum+dolor+sit+amet%22++7%0A%22Lorem+ipsum+dolor+sit+amet%22++8%0A%22Lorem+ipsum+dolor+sit+amet%22++9%0A%22Lorem+ipsum+dolor+sit+amet%22+10%0A%22Lorem+ipsum+dolor+sit+amet%22+11%0A%22Lorem+ipsum+dolor+sit+amet%22+12%0A%22Lorem+ipsum+dolor+sit+amet%22+13%0A%22Lorem+ipsum+dolor+sit+amet%22+14%0A%22Lorem+ipsum+dolor+sit+amet%22+15%0A%22Lorem+ipsum+dolor+sit+amet%22+16%0A%22Lorem+ipsum+dolor+sit+amet%22+17%0A%22Lorem+ipsum+dolor+sit+amet%22+18%0A%22Lorem+ipsum+dolor+sit+amet%22+19%0A%22Lorem+ipsum+dolor+sit+amet%22+20%0A%22Lorem+ipsum+dolor+sit+amet%22+21%0A%22Lorem+ipsum+dolor+sit+amet%22+22%0A%22Lorem+ipsum+dolor+sit+amet%22+23%0A%22Lorem+ipsum+dolor+sit+amet%22+24%0A%22Lorem+ipsum+dolor+sit+amet%22+25%0A%22Lorem+ipsum+dolor+sit+amet%22+26&a=1&m=2)
Unpacked, ungolfed, and commented, it looks like this.
```
( trim string to length
j split on spaces
N remove last element from array and push separately
W until the stack is empty...
%P pop element and print its length
```
[Run this one](https://staxlang.xyz/#c=%28+++%09trim+string+to+length%0Aj+++%09split+on+spaces%0AN+++%09remove+last+element+from+array+and+push+separately%0AW+++%09until+the+stack+is+empty...%0A++%25P%09pop+element+and+print+its+length&i=%22Lorem+ipsum+dolor+sit+amet%22++0%0A%22Lorem+ipsum+dolor+sit+amet%22++1%0A%22Lorem+ipsum+dolor+sit+amet%22++2%0A%22Lorem+ipsum+dolor+sit+amet%22++3%0A%22Lorem+ipsum+dolor+sit+amet%22++4%0A%22Lorem+ipsum+dolor+sit+amet%22++5%0A%22Lorem+ipsum+dolor+sit+amet%22++6%0A%22Lorem+ipsum+dolor+sit+amet%22++7%0A%22Lorem+ipsum+dolor+sit+amet%22++8%0A%22Lorem+ipsum+dolor+sit+amet%22++9%0A%22Lorem+ipsum+dolor+sit+amet%22+10%0A%22Lorem+ipsum+dolor+sit+amet%22+11%0A%22Lorem+ipsum+dolor+sit+amet%22+12%0A%22Lorem+ipsum+dolor+sit+amet%22+13%0A%22Lorem+ipsum+dolor+sit+amet%22+14%0A%22Lorem+ipsum+dolor+sit+amet%22+15%0A%22Lorem+ipsum+dolor+sit+amet%22+16%0A%22Lorem+ipsum+dolor+sit+amet%22+17%0A%22Lorem+ipsum+dolor+sit+amet%22+18%0A%22Lorem+ipsum+dolor+sit+amet%22+19%0A%22Lorem+ipsum+dolor+sit+amet%22+20%0A%22Lorem+ipsum+dolor+sit+amet%22+21%0A%22Lorem+ipsum+dolor+sit+amet%22+22%0A%22Lorem+ipsum+dolor+sit+amet%22+23%0A%22Lorem+ipsum+dolor+sit+amet%22+24%0A%22Lorem+ipsum+dolor+sit+amet%22+25%0A%22Lorem+ipsum+dolor+sit+amet%22+26&m=2)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
£ð¡¤gsg<‚
```
Port of [*@JonasAusevicius*'s Python 3.8 answer](https://codegolf.stackexchange.com/a/181801/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f//0OLDGw4tPLQkvTjd5lHDrP//ffKLUnMVMguKS3MVUvJz8osUijNLFBJzU0u4jAwA) or [verify all test cases](https://tio.run/##yy9OTMpM/f@oqenYJE97JYXEvBQFJXs/IOtR2yQgy9Pv/6HFhzccWnhoSXpxus2jhln/df775Bel5ipkFhSX5iqk5OfkFykUZ5YoJOamlgAA).
**Explanation:**
```
£ # Only leave the first (implicit) input-integer amount of characters
# of the (implicit) string-input
ð¡ # Split this by spaces
# (Note: builtin `#` doesn't work here, because a string without spaces
# would not be wrapped in a list)
¤g # Get the length of the last string in the list (without popping the list itself)
sg< # Swap to get the list again, and get it's length minus 1
‚ # Pair both integers (and output the result implicitly)
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~79~~ ~~77~~ ~~75~~ ~~63~~ 60 bytes
```
a=>b=>((a=a.Substring(0,b).Split())[b=a.Length-1].Length,b);
```
8 bytes saved thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) and a further 3 bytes saved thanks to [Embodiment of Ignorance](https://codegolf.stackexchange.com/users/84206/embodiment-of-ignorance)
[Try it online!](https://tio.run/##ldO9DoIwFIbh3atonNoEDaf@B2F0YnNwMA4Fq54ECqFl8OoRjBfgN7Rp05N3edLSL0rPw6l35fH@dqbmMvpe2IVITtu4VJaJh0gHk2ZFmklpUrM894UPHbunjKNCLc9txUEqdS3Gt9y6Z3gt6PY7jQPJkIjZ7NJxsDk7Kx9ynjedrQW3vq/FvamaTngOwtQ2zJWMlUr@n6ZxGohrKL7C4msovsHiWyi@w@J7KH7A4gSKgqSEmRKISpgqgayEuRIIS5gsgbQao9Xob8VoNUirMVoN0uqJdvgA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# JavaScript (Node.js), ~~75~~ ~~70~~ ~~69~~ ~~70~~ ~~68~~ 67 bytes
```
t=>o=>[o+~(s=t.substr(0,o)).lastIndexOf(' '),s.split(' ').length-1]
```
[Try it online!](https://tio.run/##ldO7CsJAEIXh3qdYbNxFs7jrLSKxFwQfQCyi2WhkkwmZUax89Xh5g1NOcfiLj7nnz5wvXdVK0lAR@jLrJdtStj3S@K05E8uPM0unpxMyxsacZdcU4XUo9UiNzIQtt7GS/2FjaK5yS9ypv1DDFIONdNWlHu6pC7WqWn7UqqBIneJKVF4HGRo9NWajkIH7DgbIwKOFGVqYo4UFWliihRVaSNHCGi24HzU0gKmdRxOwtZujCRjbLdEErO1SNAFze5Tb45@NcnuY26PcHub2P@7@Aw)
No space parameter, only hardcoded (+ 2 bytes)
-2 bytes thanks to inspiration from the [Java answer](https://codegolf.stackexchange.com/a/181812/85356) by [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
-1 byte thanks to [zevee](https://codegolf.stackexchange.com/users/70328/zevee)
[Answer]
# APL+WIN, 33 bytes
```
(1++/m),n-¯1↑(m←(m←n↑⎕)=' ')/⍳n←⎕
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5rGGpr6@dq6uTpHlpv@KhtokYuUA5M5AF5QMWatuoK6pr6j3o3AwUmAAX@A/X9T@MyNOdS98kvSs1VyCwoLs1VSMnPyS9SKM4sUUjMTS1RBwA "APL (Dyalog Classic) – Try It Online")
1 Indexed
Prompts for index of character in full text string followed by string
Outputs index of character in nth substring and substring number
[Answer]
# Java 8, ~~83~~ 75 bytes
```
n->s->n+~(s=s.substring(0,n)).lastIndexOf(" ")+","+~-s.split(" ",-1).length
```
-8 bytes implicitly thanks to inspiration from [*@yunzen*'s JavaScript answer](https://codegolf.stackexchange.com/a/181809/52210).
[Try it online.](https://tio.run/##fY8xT8MwEIX3/IqTJ1tOrLLSJgsSUiUQAyMwuI3TXnHsKHepqFD714PTpivTnd69p/fdwR5tcai/x623RPBqMfxmAMSWcQuHdDUDozfNELaMMZjneVmtA7ud6/P/PO/cY9jlt1FV0EA5hqKiogr6IqkkQ8OGrle5yINSJlHwOtTu562RAoTSIhf6UiRj55EnKS8eks2FHe/HZZZYu2HjE@uMfIxYQ5vekLfWjy@wanoJ4CYAO@InSw5KEC@xdy1gR0MLdfSxB0IG2zoWy2umib3EwIDlYgm4Ku/hmUCqpGqtrt7UcCJ2rYkDmy51sQ/yHtACbKhBaNTi8ZOFboztOn@SqObl7lRqqj5n5/EP)
**Explanation:**
```
n->s-> // Method with integer & String parameters and String return-type
n+~ // Return `n` minus 1, minus the following:
(s=s.substring(0,n))// Set `s` to the first `n` characters of input-String `s`
.lastIndexOf(" ") // and get the index of the last space
+"," // Appended with a comma-delimiter
s.split(" ", // Split the new `s` by spaces
-1) // and keep empty trailing items
+~- ... .length // And append the amount of items minus 1 to the result
```
[Answer]
# JavaScript (ES6), 56 bytes
Takes input as `(offset)(string)`.
```
n=>g=([c,...a],b=i=0)=>n--?g(a,b+!(i+=c!=' '||-i)):[i,b]
```
[Try it online!](https://tio.run/##DcY9DoIwFADgnVM8WGjTnxAHB/XhBbwBYSilkBp4JS26iGevftP3NG@TbPTbriiMLk@YCdsZWWel1tr0ckCPDceWlLrPzMhBlMwLtCXWUB@H8pxfOi@HPk8hMgKE5goEN4TT@R8hOHwKABsohcXpJcyMJEyMOKseIboV/JZeK4xhCRGS38Gsbq84L775Bw "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // n = desired offset in string
g = ( // g = recursive function taking:
[c, ...a], // c = current character; a[] = array of remaining characters
b = // b = index of current block
i = 0 // i = current position within the current block
) => //
n-- ? // if we haven't reached the desired offset:
g( // do a recursive call to g:
a, // pass the array of remaining characters
b + !( // update b:
i += // update i:
c != ' ' // increment i if the current character is not a space
|| -i // or set i to zero if it is
) // increment b if i was set to zero, or leave it unchanged otherwise
) // end of recursive call
: // else:
[i, b] // stop recursion and return [i, b]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḣḲẈṪ,LƊ
```
A dyadic Link accepting a list of characters on the left and the 0-indexed index on the right which yields a list of integers, `[character, word]`, again 0-indexed.
**[Try it online!](https://tio.run/##ATcAyP9qZWxsef//4bij4biy4bqI4bmqLEzGiv///0xvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0/zIy "Jelly – Try It Online")**
[Answer]
# Bash, 66 bytes
```
z=$(echo ${i:0:o});echo $z|sed 's/^.* //g'|wc -c;set -- $z;echo $#
```
1-indexed. `$i` contains the input, and `$o` contains the offset
Explanation:
```
z=$(echo ${LDS:0:o}); # delete the rest of the word
echo $z|sed 's/^.* //g'|wc -c; # remove anything up to the last word, and count what's left.
set -- $z;echo $# # find the number of words after the stuff after the offset is deleted
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
≔⪪…SN θI⟦L⊟θLθ
```
[Try it online!](https://tio.run/##LYs9C8IwFAD3/opHpxdQKK6dpJNQpNBRHGIMSSDfeRH89TGKy8HBndA8i8Bta@dSjPK4R2sIl7ewctEh4sXHSjtl4xWyA/z0Wt1DZmTdRxg7E5uHrSd95IXwtkqvSOPW//St/p7YnbG5tTVk6cDEUh08gw0ZiiHgTtJwmtrxZT8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪪…SN θ
```
Truncate the input string to the given length and split on spaces.
```
I⟦L⊟θLθ
```
Extract the last string and take its length, then take the number of remaining strings, cast both lengths to string and implicitly print them on separate lines.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes
```
^.+
$*
^(1)*¶((?<-1>.)*).*
$2
^(.*? )*(.*)
$.2,$#1
```
[Try it online!](https://tio.run/##K0otycxL/P8/Tk@bS0WLK07DUFPr0DYNDXsbXUM7PU0tTT0tLhUjoLielr2CphaQ0uRS0TPSUVE2/P/fyIDLJ78oNVchs6C4NFchJT8nv0ihOLNEITE3tQQA "Retina 0.8.2 – Try It Online") Takes input in the order offset, string. Explanation:
```
^.+
$*
```
Convert the offset to unary.
```
^(1)*¶((?<-1>.)*).*
$2
```
Truncate the string to the given length. This uses .NET's balancing groups to count the same number of characters in each string.
```
^(.*? )*(.*)
$.2,$#1
```
Count the number of spaces and the number of characters after the last space and output them in decimal in reverse order.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~53~~ 48 bytes
```
->s,n{t=s[0,n];[n-t[/.* |^/].size,t.count(" ")]}
```
[Try it online!](https://tio.run/##DctBDsIgEADAu6/YcGoN3TYevBj6An9AaFIrjSQCDbscbPHt6Nwn5cenrqp2I8lwsCI9yGBuOnSsezxDmXqD5HYrGZeYAzcCRGu@lZS4x2Q9uI2yh2d8xwTkGGZvWZyaAfFybdHOy@sormywapLuH38 "Ruby – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Josephus problem (counting out)](/questions/5891/josephus-problem-counting-out)
(31 answers)
Closed 7 years ago.
## Ninja Assassins - which ninja stays alive
**some basic information**
* given an int N as the number of ninjas, return the number of the winning ninja.
* At the end only 1 ninja survives,the question is which one? what was his number?.
* Each ninja kills the ninja who stands after him. Afterwards, he passes the sword to the first alive ninja who stood after the killed one.
## **Explenation - How the Game Works**
The ninjas are numbered from 1 to N and stand in a circle according to the numbers. The circle goes clockwise: ninja 2 is left to ninja 1, ninja 3 is left to ninja 2, ninja 4 is left to ninja 3.... ninja 1 is left to ninja N.
Ninja 1 gets a sword and the game begins:
Each ninja (starting from ninja 1) kills the closest and alive ninja he has to the left (clockwise) . Afterwards, he passes the sword to the 2nd closest and alive ninja he has to the left.The 2nd ninja does the same (kills and passes) (as an example: N=3(we have 3 ninjas), ninja 1 kills ninja 2 and gives the sword to ninja 3. Ninja 3 has ninja 1 as his closest and alive ninja to the left(clockwise - its a circle) so he kills ninja 1, stays the last ninja alive and wins (so the output\return is 3, as the number of the ninja)).
**A more detailed example below**
## Example - Word-detailed scenario
**N = 7 (we got 7 ninjas) :**
```
1 2 3 4 5 6 7 (L=alive, D=dead)
L D L L L L L The first ninja gets the sword and kills the 2nd ninja.
The first ninja passes the sword to the 3rd ninja.
L D L D L L L The 3rd ninja gets the sword and kills the 4th ninja.
The 3rd Ninja passes the sword to the 5th ninja.
L D L D L D L The 5th ninja gets the sword and kills the 6th ninja.
The 5th Ninja passes the sword to the 7th ninja.
D D L D L D L The 7th ninja gets the sword and kills the first(1st) ninja.
The 7th ninja passes the sword to the 3rd ninja.
D D L D D D L The 3rd ninja gets the sword and kills the 5th ninja.
The 3rd ninja passes the sword to the 7th ninja.
D D D D D D L The 7th ninja gets the sword and kills the 3rd ninja,
stays as the last one alive and wins (the final result /
the output is 7).
```
## More scenarios without words
**N=3 :** 1 2 3 - 1 3 - 3 wins
**N=4 :** 1 2 3 4 - 1 3 - 1 wins
**N=5 :** 1 2 3 4 5 - 1 3 5 - 3 5 - 3 wins
**N=6 :** 1 2 3 4 5 6 - 1 3 5 - 1 5 - 5 wins
**Scoring is based on the least number of bytes used, as this is a code-golf question.**
[Answer]
## Python 2, 30 bytes
```
lambda n:int(bin(n)[3:]+'1',2)
```
Takes the binary expansion of `n` and moves the initial `1` to the end.
[Answer]
## Python 2, 32 bytes
```
a=lambda n:n and(n%2+a(n/2))*2-1
```
---
**33 bytes:**
```
a=lambda n:n and 2*a(n/2)-(-1)**n
```
Uses the recursive formula on the [OEIS page](https://oeis.org/A006257).
* `a(2*n) = 2*a(n)-1`
* `a(2*n+1) = 2*a(n)+1`
[Answer]
## Java 7, ~~65~~ 53 bytes
```
int f(int n){return(n-Integer.highestOneBit(n))*2+1;}
```
Using the algorithm for k=2 Josephus from Wikipedia. Thanks to Leaky Nun for finding the builtin.
[Answer]
# Pyth, ~~22~~ ~~13~~ ~~12~~ 9 bytes
Credits to [Geobit's algorithm](https://codegolf.stackexchange.com/a/83820/48934) for saving 9 bytes. It works like magic.
Credits to [xnor's witchcraft](https://codegolf.stackexchange.com/a/83824/48934) for saving 3 bytes. It is simply witchcraft.
```
~~heu+G=Z%e.f!/G%ZQ2ZQQY~~
~~u?sIlH1+2GSQ1~~
~~hyaefgQT^L2~~
i.<.BQ1 2
```
[Test suite.](http://pyth.herokuapp.com/?code=i.%3C.BQ1+2&test_suite=1&test_suite_input=3%0A4%0A5%0A6%0A7&debug=0)
[Answer]
# Jelly, 4 bytes
Since xnor came up with [this algorithm](https://codegolf.stackexchange.com/a/83824/48934), I will make this community wiki.
```
Bṙ1Ḅ
```
[Try it online!](http://jelly.tryitonline.net/#code=QuG5mTHhuIQ&input=&args=Ng)
## Explanation
```
Bṙ1Ḅ
B convert to binary
ṙ1 left-rotate by 1
Ḅ convert from binary
```
[Answer]
# VBA, 57 67 bytes
Well, this technically ought to work (57 bytes):
```
Function Z(N):Z=2*(N-2^Int(Log(N)/Log(2)))+1:End Function
```
But actually, because occasionally the log value of a power of two is not quite an exact multiple of the log of 2, we need a few more bytes:
```
Function Z(N):Z=2*(N-2^Int(Log(N)/Log(2))):Z=1-Z*(Z<N):End Function
```
If there were a built-in binary converter, it would be much shorter.
The recursion version is a tie, basically, but needs a line-feed for the IF
```
Function Y(N):Y=1:If N>1 Then Y=2*Y(N\2)+2*(N\2=N/2)+1
End Function
```
[Answer]
# J, 10 bytes
```
(1&|.)&.#:
```
Using the formula where *a*(*n*) = *n* written in binary and rotated left by 1 place. Similar to what is used in @xnor's [solution](https://codegolf.stackexchange.com/a/83824/6710).
Using **19 bytes**, we can play the game according to the rules in the challenge.
```
[:(2&}.,{.)^:_>:@i.
```
This solution only performs array manipulation in order to reach a final player.
## Usage
Extra commands used for formatting multiple input/output with multiple functions.
```
f =: (1&|.)&.#:
g =: [:(2&}.,{.)^:_>:@i.
(,.f"0,.g"0) i. 10
0 0 0
1 1 1
2 1 1
3 3 3
4 1 1
5 3 3
6 5 5
7 7 7
8 1 1
9 3 3
```
## Explanation
```
(1&|.)&.#: Input: n
#: Convert to binary
( )&. Compose next function on the binary value
1&|. Rotate left by 1 place
( )&. Compose the inverse of the previous function on the result
#: The inverse: convert from binary to decimal and return result
[:(2&}.,{.)^:_>:@i. Input: n
i. Creates the range [0, 1, ..., n-1]
>:@ Increment each in the range to get [1, 2, ..., n]
[:( )^:_ Nest the function until the result does not change and return
2&}. Drop the first two items in the list
{. Get the head of the list
, Join them together. This makes it so that the head of the list
is always the current player and the one after the head is the
player to be removed
```
[Answer]
## Python, 29 bytes
```
f=lambda n:n&n-1<1or f(n-1)+2
```
Outputs 1 as `True` when `n` is a power of 2, checked by `n&n-1` being 0. Otherwise, outputs `2` higher than the previous value.
---
**28 bytes:**
Adapting [grc's general solution](https://codegolf.stackexchange.com/a/5895/20260) to the case `k=2` gives a better solution
```
f=lambda n:n and-~f(n-1)%n+1
```
Rather than explicitly checking for powers of `2`, it zeroes out the result before incrementing each time `f(n-1)` catches up to `n-1`
] |
[Question]
[
In this challenge, your task is to write a program that takes in an image and returns the most dominant color in it. Dominant color here means the color with which most of the image is covered (see the test cases for a better understanding).
---
**Input**
An image's path. You'll have to load that image in your program. You can take the input as STDIN, function argument or whatever suits your language. You may assume that the image will have only `.png` extension.
---
**Output**
The most dominant color in any format. (But it should be accurate, you can't return `Red` for `#f88379`). The type of output depends on you. If there is an equal distribution of colors in the image or there are more than one dominant color, then your program should return "Equal". You can show the output by printing on screen, logging on command line or console, or whatever suits you.
---
**Test Cases**
[](https://i.stack.imgur.com/rqsAX.png)
**=>** Red/#ff0000/rgba(255,0,0)
[](https://i.stack.imgur.com/KECpJ.png).
**=>** "Equal"
[](https://i.stack.imgur.com/DRCWd.png)
**=>** White (or the same color in any other format)
In these test cases, I have posted images rather than image paths, but you'll be given image paths only as input.
---
**Note** *If your language contains a built-in for this, then you must NOT use it.* Please add a screenshot or a link to a screenshot to prove that your program works.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
[Answer]
# Pyth, 18 bytes
FGITW.
```
?tJeM.MhZrS'Q8\=hJ
```
[This](http://pyth.herokuapp.com/?code=%3FtJeM.MhZrS%27Q8%5C%3DhJ&input=%22http%3A%2F%2Fi.stack.imgur.com%2FDRCWd.png%22&debug=0) is how it would theoretically work offline.
[This](http://pyth.herokuapp.com/?code=%3FtJeM.MhZrSQ8%5C%3DhJ&test_suite=1&test_suite_input=[[255%2C0%2C0]%2C[255%2C0%2C0]]%0A[[255%2C0%2C0]%2C[0%2C0%2C0]]%0A[[255%2C0%2C0]%2C[0%2C0%2C0]%2C[0%2C0%2C0]]&debug=0) is a proof that it works.
The two links differ by whether there is a "read file command" `'` (single-quote).
[Answer]
# JavaScript (ES6), ~~301~~ ~~328~~ 312 bytes
```
(u,b)=>{i=new Image;i.src=u;e=document.createElement`canvas`;c=e.getContext`2d`;i.onload=_=>{w=e.width=i.width;h=e.height=i.height;c.drawImage(i,0,0);d=c.getImageData(0,0,w,h).data;for(o={},i=0;i<d.length;)++o[s=d.slice(i,i+=4)]?0:o[s]=1;b(o[(a=Object.keys(o).sort((a,b)=>o[b]-o[a]))[0]]==o[a[1]]?"Equal":a[0])}}
```
Feel free to golf further, this feels as long as Java to me personally.
This supports transparent images so alpha channel is included in output value.
*The reason it's longer than before is because now that I've tested, ~~it requires~~* `Image` *to contain the attribute* `crossOrigin`*, and the arguments to* `getImageData()` *are not optional.*
See [Meta PCG](http://meta.codegolf.stackexchange.com/q/9244/42091) for removal of CORS from byte count.
## Usage
```
f("http://i.imgur.com/H5OmRVh.jpg", alert)
```
That will asynchronously `alert` a color quadruplet or "Equal" after the image is loaded and counted.
The callback is not considered part of the program length because it is allowed as input by the OP in this special case.
## How it works
It constructs an `Image`, a `Canvas`, and a `CanvasRenderingContext2D`, then draws the image to the canvas after setting its `width` and `height` correctly. It then counts occurrences of each color by implicitly converting each quadruplet to a string and generating a hash of counters. After that, it sorts the hash keys by descending count before comparing the highest two occurrences and determining whether to return the first quadruplet string in the sorted array or the string `"Equal"`.
*If the demo below displays a* `SecurityError`*, the domain of the image URL you chose does not support [CORS](http://enable-cors.org/).*
## Demo
```
f = (u, b) => {
let i = new Image;
i.crossOrigin = ''; // CORS added for demo
i.src = u;
let e = document.createElement `canvas`;
let c = e.getContext `2d`;
i.onload = _ => {
w = e.width = i.width;
h = e.height = i.height;
c.drawImage(i, 0, 0);
d = c.getImageData(0, 0, w, h).data;
for (o = {}, i = 0; i < d.length;)
++o[s = d.slice(i, i += 4)] ? 0 : o[s] = 1;
b(o[(a = Object.keys(o).sort((a, b) => o[b] - o[a]))[0]] == o[a[1]] ? "Equal" : a[0])
}
}
l = i => {
let p = i.nextElementSibling;
p.src = i.value;
f(`http://crossorigin.me/${i.value}`, c => p.nextElementSibling.value = c);
}
document.getElementById `i`.addEventListener('update', e => {
l(e.target)
})
Array.prototype.slice.call(document.querySelectorAll`.i`, 0, 3).forEach(l)
```
```
input {
display: block;
box-sizing: border-box;
width: 205px;
height: 18px;
}
input.o {
position: relative;
top: -36px;
}
img {
display: block;
position: relative;
box-sizing: border-box;
top: -18px;
left: 209px;
height: 40px;
}
```
```
<input class=i disabled value="https://i.stack.imgur.com/rqsAX.png">
<img>
<input class=o disabled>
<input class=i disabled value="https://i.stack.imgur.com/KECpJ.png">
<img>
<input class=o disabled>
<input class=i disabled value="https://i.stack.imgur.com/DRCWd.png">
<img>
<input class=o disabled>
<input class=i id=i placeholder="Try any image!">
<img>
<input class=o id=o disabled>
```
[Answer]
# MATL, ~~30~~ ~~26~~ 23 bytes
Save some bytes by using mode with explicit output specification `6#XM`.
```
2#YiwX:6#XMgY)tn3>?x'='
```
Previously (26 byte solution)
```
2#YiwX:S&Y'tX>=Y)tn3>?x'='
```
Doesn't work online, because of `imread`. `imread` can take a path or directly read a url.
Explanation:
```
2#Yi % read image, returns a matrix of colours, and a matrix
% that indexes each pixel to the corresponding row of the colour matrix
w % swap elements in stack
X: % linearize index matrix to column array
6#XMg % use mode to find most common colour indices, convert to matrix (g)
Y) % get corresponding rows of colour matrix
tn3> % duplicate and see if it has more than 3 elements
? % if there is more than one most common colour
x % delete most common colours from stack
'=' % push string onto stack
% implicitly finish loop and display stack contents
```
Output is, for the first image, `1 0 0` (RGB triple), for the second `=`, and for the third, `1 1 1`. For example, a screenshot form Matlab:
[](https://i.stack.imgur.com/8ilnV.png)
Note that you need to escape string delimiters when running MATL code from the Matlab command window, hence the `''=''`. The `>` indicates MATL is asking for user input, in this I gave it the URL of the first test case, and the result is `1 0 0`.
[Answer]
# Python 3, 186 Bytes
```
from PIL import Image;from collections import*;c=Counter(Image.open(input()).convert("RGB").getdata());d=c.most_common();print("equal") if d[0][1]==d[1][1] else print(c.most_common()[0])
```
Image 1 prints: `((255, 0, 0), 139876)`
Image 2 prints: `equal`
Image 3 prints: `((255, 255, 255), 101809)`
Ungolfed:
```
from PIL import Image
from collections import *
c = Counter(Image.open(input()).convert("RGB").getdata())
d = c.most_common()
print("equal") if d[0][1] == d[1][1] else print(c.most_common()[0])
```
Proof: [](https://i.stack.imgur.com/hTUaq.gif)
[Answer]
# Unix tools + imagemagick, 122 bytes
```
convert png:- ppm:-|tail -n +4|xxd -c3 -p|sort|uniq -c|sort -n|tail -n2|awk '{S[NR]=$1}END{print S[1]==S[2]?"equal":S[2]}'
```
Expects the input png in stdin, prints the most dominant color in hex (RRGGBB) format.
**How it works**:
* `convert png:- ppm:-` converts a png file to binary [P6 ppm format](http://netpbm.sourceforge.net/doc/pnm.html)
* `tail -n +4` skips the ppm header
* `xxd -c3 -p` puts every RGB byte triplets on a new line in hex format
* `sort|uniq -c|sort -n` orders the colors by their number of occurrence
* `tail -n2` gets the two most dominant colors
* `awk ...`: prints the more dominant color or equal
[Answer]
## PowerShell v2+, 215 bytes
```
$a=New-Object System.Drawing.Bitmap $args[0]
$b=@{}
0..($a.Height-1)|%{$h=$_;0..($a.Width-1)|%{$b[$a.GetPixel($_,$h).Name]++}}
if(($c=$b.GetEnumerator()|Sort value)[-1].value-eq$c[-2].value){"Equal";exit}$c[-1].Name
```
(Newlines/semicolons are equivalent, so newlines left in for clarity)
Creates a new [Bitmap object](https://msdn.microsoft.com/en-us/library/system.drawing.bitmap(v=vs.110).aspx), based on the input argument, stores it to `$a`. Creates a new empty hashtable `$b`, which will be used for our pixel counting.
We then loop over the image a row at a time with two loops `%{...}`. Each inner loop we use the [`.GetPixel`](https://msdn.microsoft.com/en-us/library/system.drawing.bitmap.getpixel%28v=vs.110%29.aspx) method to return a [`Color`](https://msdn.microsoft.com/en-us/library/system.drawing.color(v=vs.110).aspx) object for the particular x/y coordinate we're at. We take the `.Name` of that color (which is a hexadecimal of the form ARGB, for example `ffff0000` would be pure red fully opaque) and use that as the index into `$b`, incrementing that particular value by one.
So, we've now got a fully populated hashtable of pixel colors, with the values of each entry corresponding to how many pixels of that color there are. We then take `$b` and pump it through a `Sort` based on those values, and store that sorted result back into `$c`. If the last `[-1]` and second-to-last `[-2]` `value`s are equal, we output `"Equal"` and `exit`. Else, we output the `.Name` of the last `[-1]` entry.
[](https://i.stack.imgur.com/wRCRJ.png)
[Answer]
## Clojure, 204 bytes
```
(fn[n](let[p(javax.imageio.ImageIO/read(java.net.URL. n))w(.getWidth p)[[_ x][y z]](take-last 2(sort-by peek(frequencies(. p(getRGB 0 0 w(.getHeight p)nil 0 w)))))](if(= x z)(print"EQUAL")(printf"%x"y))))
```
prints colors as aarrggbb
Clojure isn't really great at golfing, but it's a fun language :)
proof screenshot: <https://i.stack.imgur.com/vPgoq.png>
ungolfed:
```
(fn[n]
(let [p (javax.imageio.ImageIO/read (java.net.URL. n))
w (.getWidth p)
a (. p (getRGB 0 0 w (.getHeight p) nil 0 w))
[[_ x] [y z]] (take-last 2 (sort-by peek (frequencies a)))]
(if (= x z)
(print "EQUAL")
(printf "%x" y)))))
```
] |
[Question]
[
While the **binomial coefficient** are the coefficients of \$(1+x)^n\$, **m-nomial** coefficients are the coefficients of \$(1+x+x^2+...+x^{m-1})^n\$.
For example, \$m(3,5,6)\$ is the coefficient of \$x^6\$ in the expansion of \$(1+x+x^2)^5\$.
Write a program/function that takes 3 numbers as input and outputs the corresponding **m-nomial** coefficient.
### Details
* Input can be taken via any reasonable method.
* Everything out of range is \$0\$, for example \$m(2,0,-1) = m(2,5,6) = 0\$
* The first argument will be **positive**.
* The second argument will not be negative.
* All three arguments will be integers.
### Testcases
Inputs:
```
[1,0,0]
[2,5,6]
[3,5,6]
[4,5,-1]
```
Outputs:
```
1
0
45
0
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution in bytes wins.
[Answer]
# Perl, ~~63~~ ~~60~~ ~~59~~ 57 bytes
Includes +2 for `-pa`
Give input parameters on STDIN
```
mnomial.pl <<< "3 5 6"
#!/usr/bin/perl -pa
$_=/-/^($_--,1x$F[2])=~/^(1{0,$_}){$F[1]}$(??{++$;})/+$
```
As a perl programmer I just know that every problem is really a regex in disguise...
# Explanation:
m(3,5,6) can be seen as the number of ways you can get 6 by adding 5 integers in the range `[0..2]`. You can write a regex matching such a partition using:
```
1 x 6 = /^(1{0,2}){5}$/
```
However once a single solution is found the regex stops. We need to fail the found solution to get the regex to backtrack to the next solution and count the failures. In perl this can be done by extending the regex at runtime with something that is sure to fail, e.g. by demanding that something comes after the end of the string:
```
1 x 6 = /^(1{0,2}){5}$(??{++$n})/
```
$n will count the number of failed attempts
My solution is basically this with two modifications:
* Output the counter in such a way that you get `0` instead of the empty string if there is no valid partition and the counter never gets incremented
* If the third argument is negative it would work if negative string lengths existed, but 1 x -5 is the empty string and 0 can be written exactly one way as sum of zeros, so that would output 1 instead of 0. I xor with the result of `/-/`to change the 1 back to 0
Without the need to handle a negative third argument this 49 byte solution would be good enough (give one parameter of `m(x,y,z)` on each line of STDIN in order `y \n z \n x \n`):
```
#!/usr/bin/perl -pa
$_=(1x<>)=~/^(1{0,@{[<>-1]}}){@F}$(??{++$;})/+$
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṗ’S€ċ⁵
```
This is a full program that accepts **m**, **n** and the exponent as separate command line arguments.
[Try it online!](http://jelly.tryitonline.net/#code=4bmX4oCZU-KCrMSL4oG1&input=&args=Mw+NQ+Ng)
### How it works
The problem boils down to counting the number of ways we can express the exponent as an ordered sum of exactly **n** integers between **0** and **m - 1** (both inclusive).
```
ṗ’S€ċ⁵ Main link. Arguments: m, n, k
ṗ Cartesian product; yield the array of all lists of exactly n elements of
[1, ..., m].
’ Decrement all integers in the resulting 2D list.
S€ Compute the sum of each individual list.
⁵ Yield k.
ċ Count the number of times k appears in the list of sums.
```
[Answer]
# Pyth, ~~29~~ 8 bytes
```
/sM^UQEE
```
[Try it online!](http://pyth.herokuapp.com/?code=%2FsM%5EUQEE&input=3%0A5%0A6&test_suite_input=%5B1%2C0%2C0%5D%0A%5B2%2C5%2C6%5D%0A%5B3%2C5%2C6%5D%0A%5B4%2C5%2C-1%5D&debug=0)
Uses [Dennis' Method](https://codegolf.stackexchange.com/a/78355/48934).
If the input can be rearranged so that `m(3,5,6)` is fed in the order of `6,3,5` into the program, an extra byte can be cut off:
```
/sM^UEE
```
[Try it online!](http://pyth.herokuapp.com/?code=%2FsM%5EUEE&input=6%0A3%0A5&test_suite_input=%5B1%2C0%2C0%5D%0A%5B2%2C5%2C6%5D%0A%5B3%2C5%2C6%5D%0A%5B4%2C5%2C-1%5D&debug=0)
### Original 29-byte approach
```
.N?|TY?|<Y0>Y*tNT0sm:NtT-YdN1
```
[Test suite](http://pyth.herokuapp.com/?code=.N%3F%7CTY%3F%7C%3CY0%3EY*tNT0sm%3ANtT-YdN1%3A.*Q&input=%5B0%2C5%2C6%5D&test_suite=1&test_suite_input=%5B1%2C0%2C0%5D%0A%5B2%2C5%2C6%5D%0A%5B3%2C5%2C6%5D%0A%5B4%2C5%2C-1%5D&debug=0).
How it works:
Uses the recurrence formula `m(k,n,r) = m(k,n-1,r) + m(k,n-1,r-1) + ... m(k,n-1,r-k+1)`.
```
.N?|TY?|<Y0>Y*tNT0sm:NtT-YdN1
.N def colon(N,T,Y):
?|TY if T or Y:
?|<Y0>Y*tNT if Y<0 or Y>(N-1)*T:
0 return 0
else:
sm:NtT-YdN return sum([colon(N,T-1,Y-d) for d in range(N)])
else:
1 return 1
```
[Answer]
# Perl, ~~55~~ 51 bytes
Includes +2 for `-pa`
Same basic idea as my other Perl answer, finding partitions of an integer but with a completely different implementation. This version is shorter, but only because I don't have to special case a negative third argument.This version is also totally boring...
Give input for m(x,y,z) on STDIN with a line for each argument in order z, x, y. E.g. to calculate m(3,5,6):
```
mnomial.pl
6
3
5
^D
```
`mnomial.pl`:
```
#!/usr/bin/perl -pa
$"=",";$_=grep"@F"==eval,glob"+{@{[0..<>-1]}}"x<>
```
[Answer]
# Python, 64 bytes
```
f=lambda m,n,k:(k==0)+sum(f(m,n-1,k-t)for t in range(m*(n>0<k)))
```
As far as code golf goes, this is fairly efficient. Test it on [Ideone](http://ideone.com/334oLe).
[Answer]
## Sage, 71 bytes
```
lambda a,b,c:(c>=0and(sum(x^i for i in range(a))^b).list()[c:]or[0])[0]
```
[Verify all test cases online](http://sagecell.sagemath.org/?z=eJwtjd0KgzAMRu8F3yGXychG3dSLgnuRUqH-jYJWaTsYe_q1skA4EE6-b-lWsw2TAcMDjxLHZyeMmzC8N_z0FpbdgwXrwBv3mtEQ9QPdVhsikhql3r0SmtKWRVnEOcQAHXztgUpVLFhoVnduuE18_FknXiutGU6lbpJF-T135QgGP4fceebJsoA0h7cuwoKXfKRT-QF_0jYJ&lang=sage)
The unnamed lambda function constructs the polynomial and returns the specified coefficient if `c` is not negative and less than or equal to the degree of the polynomial, else `0`.
[Answer]
# Julia, ~~50~~ 45 bytes
```
f(m,n,k)=n>0?sum(t->f(m,n-1,k-t),0:m-1):0^k^2
```
[Try it online!](http://julia.tryitonline.net/#code=ZihtLG4sayk9bj4wP3N1bSh0LT5mKG0sbi0xLGstdCksMDptLTEpOjBea14yCgpmb3IgKG0sbixrKSBpbiAoWzEsMCwwXSwgWzIsNSw2XSwgWzMsNSw2XSwgWzQsNSwtMV0pCiAgICBwcmludGxuKGYobSxuLGspKQplbmQ&input=)
If `digits` supported unary, the following approach would be 1 byte shorter.
```
g(m,n,k)=sum(t->k==sum(digits(t,m)),0:m^n-1)
```
[Answer]
## JavaScript (ES6), 118 bytes
```
(m,n,k)=>[...Array(n)].reduce(a=>a.map(x=>t+=x,t=0),[...Array(m*n+1)].map((_,i)=>i%m?0:i?x=-x*(n+1-i/m)*m/i:x=1))[k]|0
```
Works by calculating (xm-1)n/(x-1)n. (xm-1)n is calculated by the binomial theorem and the result is then repeatedly divided by x-1.
Edit: Saved 24 bytes by using a different binomial calculation. Saved 4 bytes by switching to `reduce` (yay!).
] |
[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/36127/edit).
Closed 1 year ago.
[Improve this question](/posts/36127/edit)
Write function which solves equation of degree less than or equal to 2 (`ax^2 + bx + c = 0`).
# Input
Function should get 3 parameters - floating point numbers which are coefficients of this equation. Coefficients may be zero (that means function must able to solve `bx + c = 0` and `c = 0` too).
Coefficients are between `-1000` and `1000` with 3 significant decimal digits but maximum 3 digits after comma, for example, `999.` or `3.14` or `0.233` but not `1001` or `0.0123`.
# Rules
* You may use only `+ - * / % & | xor ~ && || ! < > >= <= == != << >>` operators
* No built-in functions (that means no square root or power or similar functions)
* No variables except 3 function parameters
* You can't use complicated expressions - only statements of the form `a = b @ c` or `a = @ b` are allowed (`@` - any allowed operator and `a, b, c` - any variables, may be same or constants)
* No loops, recursion, goto's, custom types
* Casts and type conversion between integral data types are allowed
* Using features of dynamic typing (changing floating point number to array/object/something else that is not number) is not allowed
* If's are allowed with one or none operators in condition (`if (a) {...} else {...}` or `if (a==b) {...} else {...}`). Note that `if` itself and its condition scores separately
* You may use `try{}catch{}`
# Output
* Output should be passed by reference to input variables, if your language doesn't have such feature, you anyway should put result to input variables and print their values
* In variable `a` - number of real roots - 0, 1, 2, 3 (value greater than 2 stands for infinitely many roots)
* In variables `b` and `c` - 1st and 2nd roots (if none or infinitely many roots than any values, if one root then `c` - any value)
* Note that 2 equal roots is not the same as 1 root
* Precision should be at least 3 significant decimal digits
# Score
* Score is `[number of operators]` + `[number of if's]`. Assignment operators have score 0.
* Answer with lowest score wins.
* In case of same score answer with greater precision wins. If precision is same then first answer wins.
* `if(a != 0)` and `if(a == 0)` has score 1 (instead of 2) because `if(a)` or `if(a)else{}` can be used, however not all languages support it.
* For each `catch{}` +2 to score
* Use of 1 temporary variable of numeric type is +20 to score.
[Answer]
## C, 60
I happen to use the same square root algorithm (Newton) as Peter. However, I think we need to use two different starting values in order to get away with even 8 iterations. The maximum value of `b²/4-c` (the normalised discriminant) is for `b = -c = 1000`. The minimum value is for `b = 0.001; c = 0` (in fact, there are smaller values but these would be beyond the significant digits of b and c). If we split the range of values at `20`, we can use `0.1` as the starting guess for the lower range and `100` as the starting guess for the upper range and always converge in 8 steps. If I could be bothered to keep searching I think I could get this down to 7, and with a few more subdivisions probably even below 6 while still saving operations (but I can't be bothered right now).
```
void qe(&float a, &float b, &float c)
{
float t; // 20
if (a) // 21
{
b = b / a; // 22
c = c / a; // 23
b = b / -2; // 24
t = b * b; // 25
c = t - c; // 26
if (c<0) // 28
{
a = 0;
}
else
{
if (c<20) // 30
a = .1
else
a = 100
t = c / a; // 31
a = a + t; // 32
a = a / 2; // 33
t = c / a; // 34
a = a + t;
a = a / 2;
t = c / a; // 37
a = a + t;
a = a / 2;
t = c / a; // 40
a = a + t;
a = a / 2;
t = c / a; // 43
a = a + t;
a = a / 2;
t = c / a; // 46
t = a + t;
t = t / 2;
t = c / a; // 49
t = a + t;
t = t / 2;
t = c / a; // 52
t = a + t;
t = t / 2;
a = 2;
c = b + t; // 55
b = b - t; // 56
}
}
else if (b) // 57
{
a = 1;
b = b / c; // 58
b = -b; // 59
}
else if (c) // 60
{
a = 0;
}
else
{
a = 3;
}
}
```
[Answer]
## Hybrid of iterative approaches; score: 62
I originally posted an answer which purely used Newton-Raphson; however, in the cases of large `b` and `c` this requires a lot of iterations. Consider only the most interesting quadratics: those which have two solutions. If we normalise them to the form `x^2 + bx + c = 0` then we can plot the number of iterations required for various approaches as a function of `b` and `c`. For example, we can modify the continued fraction route to get the direct approach:
```
c = -c;
a = b * 0.5;
while (loopCount-- > 0) { // This loop would be unrolled in the final solution
a = a + b;
a = c / a;
}
// Roots are a and -c/a
```
That gives a loop count diagram of
```
2236...................6322
2224n.................n4222
22236.................63222
22224n...............n42222
222236...............632222
222224m.............m422222
2222236.............6322222
2222224j...........j4222222
22222234P.........P43222222
22222223d.........d32222222
222222222t.......t222222222
2222222225Z.....Z5222222222
22222222219/////91222222222
/////////////./////////////
222222222*********222222222
222222222*********222222222
22222222***********22222222
22222223***********32222222
2222223*************3222222
2222224*************4222222
222223***************322222
222224***************422222
22223*****************32222
22224*****************42222
2223*******************3222
2224*******************4222
223*********************322
```
where `c` is negative in the first row and increases downwards, `b` increases from left to right, `*` means negative discriminant, `/` means only one root was within tolerance in 62 iterations, `.` means no root was within tolerance in 62 iterations, and numbers are in base-62 with digits `0-9a-zA-Z`. This is pretty decent for a certain range, but fails completely for another range.
[bmarks](https://codegolf.stackexchange.com/users/30076/bmarks)' original implementation is similar to (but not the same; this is a reimplementation from the continued fraction):
```
a = b;
while (loopCount-- > 0) {
a = c / a;
a = b - a;
}
// Roots are -a, -c/a (which is better than a-b)
```
with loop count diagram
```
1117...................7111
1112n.................n2111
11117.................71111
11112n...............n21111
111117...............711111
111112m.............m211111
1111117.............7111111
1111112j...........j2111111
11111115Q.........Q51111111
11111111d.........d11111111
111111113u.......u311111111
1111111116/...../6111111111
1111111111a/////a1111111111
1111111111111.1111111111111
111111111*********111111111
111111111*********111111111
11111111***********11111111
11111112***********21111111
1111111*************1111111
1111112*************2111111
111111***************111111
111113***************311111
11111*****************11111
11113*****************31111
1111*******************1111
1113*******************3111
111*********************111
```
My naïve N-R was quite bad, but the really interesting thing to note about it is where the worst areas are:
```
njfdcccccccccccccccccccdfjn
njgcbbbbbbbbbbbbbbbbbbbcgjn
njgc9999999999999999999cgjn
njgc9777777777777777779cgjn
njgc9666666666666666669cgjn
njgc9544444444444444459cgjn
njgc9521111111111111259cgjn
njgc9534444444444444359cgjn
njgc9535555555555555359cgjn
njgc9536777777777776359cgjn
njgc9536888888888886359cgjn
njgc9536899999999986359cgjn
njgc95368aaaaaaaaa86359cgjn
njgc95368aaaaaaaaa86359cgjn
njgc95368*********86359cgjn
njgc95369*********96359cgjn
njgc9536***********6359cgjn
njgc9536***********6359cgjn
njgc953*************359cgjn
njgc954*************459cgjn
njgc95***************59cgjn
njgc94***************49cgjn
njgc9*****************9cgjn
njgc8*****************8cgjn
njgc*******************cgjn
njgb*******************bgjn
njf*********************fjn
```
So the thing to do is to hybridise. For the areas where it's good, I use the continued fraction; for the rest, I use N-R, but I've done some optimisation: I've experimentally found two cutoffs and three initial values which converge in 5 iterations to a worst-case mixed error `abs(value - correct_value) / (1 + abs(correct_value)` of 0.000052. (Thanks to [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) for the idea of doing a case split). The final loop count (mixing the two cases into one diagram) is:
```
111555555555555555555555111
111233333333333333333332111
111133333333333333333331111
111125555555555555555521111
111115555555555555555511111
111112333333333333333211111
111111333333333333333111111
111111255555555555552111111
111111144444444444441111111
111111112111111111111111111
111111113222222222211111111
111111111333333333111111111
111111111444444444111111111
111111111111111111111111111
111111111*********111111111
111111111*********111111111
11111111***********11111111
11111112***********21111111
1111111*************1111111
1111112*************2111111
111111***************111111
111113***************311111
11111*****************11111
11113*****************31111
1111*******************1111
1113*******************3111
111*********************111
```
and the code is
```
solve_quad(&float a, &float b, &float c) {
float t; // 20 points
if (a != 0) { // 21
if (c == 0) {
// x(x+b) = 0
b = -b; // 22
a = 2;
}
else {
// Normalise so that we're solving x^2 + bx + c = 0 and have `a` free to use
// Hereon, mentions of b and c in comments refer to these normalised values.
b = b / a; // 22
c = c / a; // 23
// Three cases:
// b^2 < 4c: negative determinant, no solutions
// b^2 < -4c: use Newton-Raphson
// Otherwise: use the continued fraction method that bmarks was the first to post
a = b / 2; // 24
a = a * a; // 25
if (a < c) { // 26
a = 0;
}
else {
t = a + c; // 27
if (t < 0) { // 28
c = a - c; // 29, c holds the determinant
// Carefully optimised case split:
if (c < 0.05) // 30
a = 0.025;
else if (c < 250) // 31
a = 2;
else a = 193;
t = c / a; a = a + t; a = a / 2; // 34
t = c / a; a = a + t; a = a / 2; // 37
t = c / a; a = a + t; a = a / 2; // 40
t = c / a; a = a + t; a = a / 2; // 43
t = c / a; a = a + t; a = a / 2; // 46
// At this point a ~= sqrt(determinant)
t = b / 2; // 47
a = a + t; // 48
t = t * t; // 49
c = t - c; // 50
// At this point a ~= b/2 + sqrt(determinant) and c holds its original value
}
else {
a = b;
a = c / a; a = b - a; // 52
a = c / a; a = b - a; // 54
a = c / a; a = b - a; // 56
// At this point a ~= b/2 + sqrt(determinant)
}
b = -a; // 57
c = c / b; // 58
a = 2;
}
}
}
else {
// bx + c = 0
if (b != 0) { // 59
a = 1;
c = -c; // 60
b = c / b; // 61
}
else {
// c = 0
if (c != 0) a = 0; // 62
else a = 3;
}
}
}
```
[Answer]
## C# (46)
Used a different way of computing sqrt(x) (continued fractions <http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Generalized_continued_fraction>)
It fails for b=0 due to large rounding errors. I'm not sure how to fix that, but I hope I can help fellow contestants with a new way of doing the square roots.
Edit: Thanks to @Peter Taylor for the suggestion on how to handle b=0.
Edit 2: Thanks to @steveverrill for pointing out that there are only >2 solutions if c is also 0, thus requiring an extra if check.
```
public static void doStuff(ref double a, ref double b, ref double c)
{
if (a == 0) //1
{
if (b == 0) //2
{
if (c == 0){ //3
a = 3;
}
else {
a = 0;
}
}
else
{
b = -1 / b;//4
b = c * b;//5
a = 1;
}
}
else
{
b = b / a;//6
c = c / a;//7
if (b == 0) //8
{
b = 1 + 1E-7;// still just one constant; since 0.001/1000>1E-7, b can never equal this value normally
c = c + 0.25; //9
}
a = 2 * c;//10
a = a / b;//11
a = b - a;//12
a = c / a; a = b - a;//14
a = c / a; a = b - a;//16
a = c / a; a = b - a;//18
a = c / a; a = b - a;//20
a = c / a; a = b - a;//22
a = c / a; a = b - a;//24
a = c / a; a = b - a;//26
a = c / a; a = b - a;//28
a = c / a; a = b - a;//30
a = c / a; a = b - a;//32
a = c / a; a = b - a;//34
a = 2 / a;//35
a = c * a;//36
a = b - a;//37
if (b == 1 + 1E-7) //38
{
b = 0;
c = c - 0.25;//39
}
if (a == 0) //40
{
b = -1.0 / 2 * b;//41
c = b;
a = 2;
}
else
{
if (a < 0) //42
{
a = 0;
}
else
{
b = -1.0 / 2 * b;//43
a = a / 2;//44
c = b - a;//45
b = b + a;//46
a = 2;
}
}
}
}
```
[Answer]
# C, 46 excluding handling a=0 cases, with "fast squareroot" (not "fast inverse squareroot")
**I hope I've scored what I've done so far correctly. I don't know how much more I'll do on this because:**
1. I'm not sure if casting's legal, or how to score it (the union used in another answer is more efficient, but I've not used them before.)
2. I'm a little unclear on the meaning of "2 equal roots are not the same as 1 root." I assume this means that a quadratic will always have either 0 o 2 real roots (which may or may not be equal) and a linear equation (a=0) will have 1 root. I would point out the only infinite case is a=b=c=0. If a=b=0 and c is nonzero, there are no roots.
**Anyway, my main reason for posting is that I wanted to show that it's possible to define a "fast squareroot"** (which is more suitable for the needs of this question than simply copying the famous "fast inverse squareroot" as per some other answers.) Instead of subtracting `i>>1` from a constant, we add `i>>1` to a constant.
The principle of the algorithm is as follows:
Assume a float is stored in an imaginary little computer as `2^AAA*1.BBBB` (the 2 and 1 are not stored. AAA is known as the exponent and BBBB as the fraction.)
Performing a rightshift on the number `2^100*1.0000`=16 gives `2^010*1.0000`=4 which is exactly the correct square root. Repeating the process gives `2^001*1.0000`=2. So far we have seen perfectly accurate results.
Now we have an odd power of 2. When we try to calculate the square root of the number 2 by rightshifting, the odd digit of the exponent underflows into the fraction and we get `2^000*1.100` which in decimal is 1.5, an error of approximately +6% on the correct value of sqrt(2)=1.414.
Moving to practical implemenations the 32-bit IEEE float (and the 64-bit, 128 bit etc.) has a bias on the exponent, so we have to add a constant to the raw shifted value. Careful choice of this constant enables the error to be limited to a range of approximately +/-3% which is a pretty good starting guess for The Newton-Raphson method. I found the constant by trial and error (there is room for some improvement, on my test cases it is more likely to give a positive error than a negative error.)
Three iterations of Newton-Raphson cleans it up very well (and may be more than necessary.)
```
void quad(float &a, float &b, float &c) {
printf("a=%f b=%f c=%f",a,b,c);
int i; //score 20
c=c/a; // c/a
b=b/a;
b=b/-2; // -b/2a
a=b*b;
a=a-c; // (b/2a)^2-c/a), score 25
if (a<0) a=0; else{ // score 27
i = * ( int * ) &a;
i = i >>1;
i = i+0x1FB90000;
c = * ( float * ) &i; //sqrt( (-b/2a)^2-c/a ) score 31
i = * ( long * ) &a; //don't lose the value (b/2a)^2-c/a
a=a/c;
c=c+a;
a=c/2;
c = * ( float * ) &i; //second iteration
c=c/a;
a=a+c;
a=a/2;
c = * ( float * ) &i; //third iteration
c=c/a;
a=a+c;
a=a/2; //score 43 after 3 iteratations
c=b-a; //-b/2a in each
b=b+a;
a=2; //score 46
}
}
```
[Answer]
# C - ~~50~~ 48
I use the 32-bit float shortcut for getting a good initial seed for the square root. That allows me to get away with just a few iterations of Newton's method. I haven't found a set of coefficients yet that yield unacceptable results (outside the specified precision).
Also, I am not sure how the spec treats pointer operations. For all I know this is disallowed, but hey, I had fun!
```
void primitiveQuad(float *a, float *b, float *c) {
if(0.0 == *a) { // 1
if(0.0 != *b) { // 2
*a = 1.0;
*b = -1.0/(*b); // 3
*b = (*b)*(*c); // 4
}
else if(*c) // 5
*a = 0.0;
else
*a = 3.0;
}
else {
*b = (*b)/(*a); // 6
*c = (*c)/(*a); // 7
*c = 4.0*(*c); // 8
*a = (*b)*(*b); // 9
*a = (*a) - (*c); // 10
*c = *a; // store discriminant here for later
if(0.0 > *a) // 11
*a = 0.0;
else {
int x = *((int*)(a)); // 31
x = x - (0x800000); // 32
x = x >> 1; // 33
x = x + (0x20000000); // 34
*a = *((float*)(&x));
{
// add precision here through iterations
// iteration
x = *((int*)(a));
*a = (*c)/(*a); // 35
*a = *a + *((float*)(&x)); // 36
*a = 0.5*(*a); // 37
// iteration
x = *((int*)(a));
*a = (*c)/(*a); // 38
*a = *a + *((float*)(&x)); // 39
*a = 0.5*(*a); // 40
// iteration
x = *((int*)(a));
*a = (*c)/(*a); // 41
*a = *a + *((float*)(&x)); // 42
*a = 0.5*(*a); // 43
}
*b = 0.0 - *b; // 44
*c = *b;
*b = *b + *a; // 45
*c = *c - *a; // 46
*b = 0.5*(*b); // 47
*c = 0.5*(*c); // 48
*a = 2.0;
}
}
}
```
[Answer]
# C++ (~~29 45~~ 44)
Note that each `return` can be removed, simply by using else branch.. it's just more readable. The same with `if(!sth)` can be simply changed using else and empty if branch....
**edit:** Now, with casts allowed, this answer should be correct.
```
void quadr(float &a, float &b, float &c) {
b = - b; //1
if(!(b && c)) { //3
if(!a) { //4
a = 3; //
return;
}
a = 1; //
return;
}
if(!a) { //5
a = 1; //
b = c / b; //6
return;
}
b = b / a; //7
c = c / a; //8
c = c * 4; //9
a = b * b; //10
a = a - c; //11
c = a / 2; //12
int t = *(int*)&a; //32
t = t >> 1; //33
t = 0x5f3759df - t; //34
a = *(float*)&t; //
c = c * a; //35
c = c * a; //36
c = 1.5f - c; //37
a = a * c; //38
a = 1 / a; //39
if(!a) { //40
a = 0; //
return;
}
c = b - a; //41
b = b + a; //42
c = c / 2; //43
b = b / 2; //44
a = 2; //
}
```
I might have missed some case, feel free to prove me wrong :)
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 6 years ago.
[Improve this question](/posts/21795/edit)
Create a piece of code and a genuinely-looking test for it. However, the test must be flaky: when run multiple times, it must sometimes fail, sometimes succeed.
Be creative and try to hide the flakiness as much as possible. The most popular answer in (at least) 10 days wins.
[Answer]
# JavaScript
Here is a very simple function that divides two given numbers:
```
function div(x, y) {
return x / y;
}
```
And a test function that for 100 test cycles generates two random numbers from 0 to 10 and checks if the function returns the same result of division as provided in the test:
```
function test() {
for (var i = 0; i < 100; i++) {
var x = Math.floor(Math.random() * 10),
y = Math.floor(Math.random() * 10);
if (x / y === div(x, y)) {
console.log('Test OK');
} else {
console.log('Test FAILED');
break;
}
}
}
```
>
> This example doesn't relate to the problem of math with floating numbers or any type casting tricks, as you may probably decide at first sight. Test will fail when *x* and *y* equal to *0*. In this case JavaScript will always return *NaN*, which itself never equals to *NaN*.
>
>
>
[Answer]
## C#, Thread-safe?
OK, let's write a kind of `Dictionary` that supports increasing and summing of values. Oh, and it's thread-safe. It even says so in its name:
```
public class ThreadSafeCounter<TKey>
{
private Dictionary<TKey, int> _dictionary = new Dictionary<TKey, int>();
private object _lock = new object();
public bool ContainsKey(TKey key)
{
lock (_lock) { return _dictionary.ContainsKey(key); }
}
public void Add(TKey key, int value)
{
lock (_lock) { _dictionary[key] = value; }
}
public void Inc(TKey key)
{
lock (_lock) { _dictionary[key]++; }
}
public int GetSum()
{
lock (_lock) { return _dictionary.Values.Sum(); }
}
}
```
So, since it's obviously thread-safe, let's fill it using several threads. What could possibly go wrong?
```
private void FillCounter(ThreadSafeCounter<int> counter)
{
for (int i = 0; i < 10; i++)
{
if (counter.ContainsKey(i))
{
counter.Inc(i);
}
else
{
counter.Add(i, 1);
}
}
}
public void Test()
{
var counter = new ThreadSafeCounter<int>();
var thread = new Thread(() => FillCounter(counter));
thread.Start();
FillCounter(counter);
thread.Join();
int sum = counter.GetSum();
if (sum != 20)
{
Console.WriteLine("What? Test failed!");
}
}
```
If you know a bit about multi-threading, the problem in the test should be *boringly obvious* (Is that a word? "boringly"). But it might fool novices.
>
> While each operation of ThreadSafeCounter is indeed thread-safe, the way the counter is used is not. Between checking for the existence of the key and adding it, the other thread might do the same. So, both threads end up setting the counter to 1 and none actually increases it. A classical race condition.
>
>
>
[Answer]
```
public bool IsLeapYear(int year)
{
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
[Test]
public void TestIsLeapYear()
{
Assert.Equals(DateTime.IsLeapYear(DateTime.Now.Year), IsLeapYear(DateTime.Now.Year));
}
```
>
> The logic is sound, but the test isn't. Run the test a few times at 2015.12.31. 23:59:59. The error is in getting the current time twice. It will fail about twice every four years (at the start and end of leap years, when there is a transition), so it's very well hidden.
>
>
>
[Answer]
I'm sure there are even better examples in PHP, but here's one:
```
<?php
// Computes the sum of two numbers
function sum($a, $b) {
return $a + $b;
}
function test_add_numbers() {
// Perform 100 tests
for ($i = 0; $i < 100; $i++) {
// Get two numbers between 0.1 and 0.9
$a = rand(1, 9) / 10;
$b = rand(1, 9) / 10;
// Compute the sum of the two numbers: 0.2 .. 1.8
$sum = $a + $b;
// Make it integer: 2 .. 18
$sum = $sum * 10;
if (sum($a * 10, $b * 10) == (int)$sum) {
print "Test OK\n";
}
else {
print "Test FAILED\n";
die;
}
}
}
test_add_numbers();
```
[Click here for DEMO.](http://sandbox.onlinephpfunctions.com/code/a0b014e3f983b240cdc6b3ed37d26ceb1054049d)
>
> This exploits the fact that `(int)((0.1 + 0.7)*10)` evaluates to 7 (rather than 8 as expected). More details [here](http://www.php.net/manual/en/language.types.float.php).
>
>
>
] |
[Question]
[
Objective:
>
> This code-golf is about creating 2 different sourcecodes that both outputs exactly: `Hello, new world! again.` without linefeed, and when combining the two sourcecodes into one sourcecode it should still output exactly: `Hello, new world! again.`
>
>
>
Rules:
1. Your programs should take no input (from user, filename, network or anything).
2. You can choose any combination of programming languages, from one language for all three sourcecodes to three different languages.
3. The combination of the two sourcecodes to create the third is done by putting alternating characters from both from start to end and fill up the third sourcecode from start to end.
4. You must choose 10 different characters that both sourcecodes may use (case sensitive). All other characters is mutual exclusive between the two sourcecodes. Characters may be re-used without restriction. Exactly all 10 characters choosen must be used in both sourcecodes atleast once.
Clarification example on sourcecode combination:
```
Javascript sourcecode: console.log("Hello, new world! again.");
GolfScript sourcecode: 'Hello, new world! again.'
Combined (unknown?) sourcecode: c'oHneslolloe,. lnoegw( "wHoerllldo!, angeawi nw.o'rld! again.");
```
The above example does however violate rule #4 as more than 10 characters is "shared" in both sourcecodes. And the combined sourcecode does not output: `Hello, new world! again.`
Be sure to declare what programming languages is used (all three) and what 10 characters that is allowed in both sourcecodes.
This is code-golf, least bytes in combined sourcecode wins! Good luck, have fun!
[Answer]
## C99 + sh + C11, ~~165 162 146~~ 145 combined chars
Edit: using @flonk's trick I managed to put the "comment" in C (making use of C11's `u""` Unicode literals).
Common characters are: `acehinortu`.
**hello.c** (106):
```
*a="\2+++++++++++++++++++++++++++++++++";i;main(){for(;i<24;)putchar("Lipps0$ri{${svph%$ekemr2"[i++]+~3);}
```
**hello.sh** (39):
```
true
echo -n 'Hello, new world! again.'
```
**hello-combined.c** (145):
```
*tar=u"e\
2e+c+h+o+ +-+n+ +'+H+e+l+l+o+,+ +n+e+w+ +w+o+r+l+d+!+ +a+g+a+i+n+.+'";i;main(){for(;i<24;)putchar("Lipps0$ri{${svph%$ekemr2"[i++]+~3);}
```
---
Here are some utilities that might prove useful for other participants.
**combine.c**:
```
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *f1 = fopen(argv[1], "r"), *f2 = fopen(argv[2], "r");
while (!feof(f1) || !feof(f2)) {
int c1 = fgetc(f1), c2 = fgetc(f2);
if (c1 != EOF) putchar(c1);
if (c2 != EOF) putchar(c2);
}
return 0;
}
```
**char-check.{ba,z}sh**:
```
comm -12 <(grep -o . "$1" | sort | uniq) \
<(grep -o . "$2" | sort | uniq) | tr -d '\n'
```
---
Here's a variation that unfortunately ended up (considerably) longer, but it's pretty cool in how it works. (I didn't bother getting the intersection between the sets of characters down to 10, since it ended up longer anyway.)
**hello.c** (113):
```
*a="\5Lipps0$ri{${svph%$ekemr2+++++++++++",*b=&a,c=6;i;main(){char*p=*b;for(i=c/8;p[i]-50;)putchar(p[i+=c/4]-4);}
```
**hello.sh** (51):
```
true
echo -n 'Hello, new world! again.' # tr 1
```
**hello-combined.c** (164):
```
*tar=u"e\
5eLcihpop s-0n$ r'iH{e$l{lsov,p hn%e$we kweomrrl2d+!+ +a+g+a+i+n+.+'+ +#" , * b = &tar, c =16;i;main(){char*p=*b;for(i=c/8;p[i]-50;)putchar(p[i+=c/4]-4);}
```
This one is fun, because it doesn't just "comment out" a bunch of characters, but actually stores the characters it prints inside the string literal and accounts for the extra characters in the for-loop of the generated program.
[Answer]
# Brainfuck + C (196+77)
Not a very golfy answer, but I just think it is fun
Brainfuck:
```
++++++++++[>+++++++>++++>++++++++++>+++<<<<-]>++.>>+.+++++++..+++.<++++.>>++.<-.---------.++++++++++++++++++.>.<.--------.+++.------.--------.>+.-.<---.++++++.------.++++++++.+++++.<++.printfHelo
```
C
```
main(){printf("Hello");putchar(44);printf(" new world! again");putchar(46);}
```
Combined (Also in brainfuck):
```
+m+a+i+n+(+)+{+p+r+i[n>t+f+(+"+H+e+l+l>o+"+)+;+p>u+t+c+h+a+r+(+4+4+)+;>p+r+i+n<t<f<(<"- ]n>e+w+ .w>o>r+l.d+!+ +a+g+a+i+n.".)+;+p+u.t<c+h+a+r+(.4>6>)+;+}.
<-.---------.++++++++++++++++++.>.<.--------.+++.------.--------.>+.-.<---.++++++.------.++++++++.+++++.<++.printfHelo
```
All the characters from the C code are considered as comments in brainfuck
The common characters are `printfHelo`, appended at the end of the brainfuck code as comments
[Answer]
## Befunge + sh + Befunge, 111 chars
Common characters are: `!,-Hehilor`
**hello.bef** (78):
```
vHelo----------------------------
<v"Lipps0$ri{${svph%$ekemr2"
_>4-:,b4*2+-!#@
```
**hello.sh** (33):
```
echo -n Hello, new world\! again.
```
**hello-combined.bef** (111):
```
veHcehloo ---n- -H-e-l-l-o-,- -n-e-w- -w-o-r-l-d-\-!- -a-g-a-i-n-.
<v"Lipps0$ri{${svph%$ekemr2"
_>4-:,b4*2+-!#@
```
[Answer]
## Python + dc (~~160,141,137,116~~ 81+27=108)
program1: (python)
```
'yyyyyyyyyyyyyyyyyyyyyyyyyy';exec'PRINT\'%sELLO, NEW WORLD! AGAIN.\''.lower()%'H'
```
program2: (dc)
```
[Hello, new world! again.]p
```
combined: (python)
```
'[yHyeylylyoy,y ynyeywy ywyoyrylydy!y yaygyayiyny.y]yp';exec'PRINT\'%sELLO, NEW WORLD! AGAIN.\''.lower()%'H'
```
Common characters (including space): `! ,.elorwH`
The parts `program1` and `program2` are quite simple to understand, where the first has some case switches to reduce the common characters.
As `program1` starts with a quotation `'`, in the combined code all the gibberish walks into a long string, becoming irrelevant for the interpreter. The string `'yy...y'` is of the same length as `program2`, so after its closing `'` the relevant code of `program1` is appended to the combined program.
] |
[Question]
[
Let n be any integer between 1 and 999,999 inclusive. Your challenge is to write a complete program which using stdin or command-line arguments takes in n and outputs the number of times the letter "o" is needed to write all cardinal numbers in standard American English between 1 and n. You can assume that n will always be an integer within the above given range.
You can just use all lowercase letters as I do below. So we count all "o". No need to worry about uppercase "O".
Here is a quick review of how to write English numerals in American English.
```
one two three four ... nine ten eleven twelve thirteen fourteen ... nineteen twenty
twenty-one twenty-two ... twenty-nine thirty ... forty ... fifty ... sixty ...
seventy ... eighty ... ninety ... one hundred ... two hundred ... three hundred ...
nine hundred ... one thousand ... two thousand ... nine thousand ... ten thousand ...
eleven thousand ... ninety-nine thousand ... one hundred thousand ...
two hundred thousand ... nine hundred ninety-nine thousand nine hundred ninety nine.
```
The hyphen for two digit numbers doesn't matter.
The commas don't matter of course. I excluded them above.
Separation between hundreds and tens doesn't matter because we are only counting the letter "o" so 110 can be written as "one hundred ten", or "one hundred and ten". I excluded the "and" above.
For this challenge "hundred" and "thousand" must be preceded by "one" instead of "a" when being used at the beginning of the number. So 1111 must be "one thousand one hundred eleven" instead of "a thousand one hundred eleven".
Here are some more random numerals to clarify.
```
219873 = two hundred nineteen thousand eight hundred seventy three
615023 = six hundred fifteen thousand twenty three
617610 = six hundred seventeen thousand six hundred ten
423716 = four hundred twenty-three thousand seven hundred sixteen
386031 = three hundred eighty-six thousand thirty one
```
Here are some samples for what your code should return.
```
./mycount 1
1
```
There's only "one" to write so we need only a single "o".
```
./mycount 10
3
```
We only need three o's namely in "one", "two", and "four".
```
./mycount 101
41
```
Your code must be self-contained and must not connect to the internet, download any files, perform any query, etc. I can already see somebody using google or mathematica with wolfram alpha to do this.
True code-golf. The shortest code in any language wins. Please post your code with some test cases. In the case of ties, I pick the one with the highest upvotes after waiting at least for two weeks. So everyone feel free to upvote any solutions you like.
Happy coding!
[Answer]
## R - 54
```
sum(nchar(gsub("[^o]","",english::english(1:scan()))))
```
I get 41 for n=101. I hope someone can confirm.
[Answer]
## JavaScript 1.8 (150)
```
function f(n)n<14?(22>>n)&1:n<100?((n/10|0)==4)+f(n%10):n<1e3?f(n/100|0)+f(n%100):f(n/1e3|0)+f(n%1e3)+1;m=readline();for(s=i=0;i++<m;)s+=f(i);print(s)
```
As written, this will only work in [SpiderMonkey `js`](https://developer.mozilla.org/en-US/docs/SpiderMonkey/Introduction_to_the_JavaScript_shell) (the one used by [Anarchy Golf](http://golf.shinh.org/)). If running this in Firefox, replace `readline` with `prompt` and `print` with `alert`. Use of Mozilla's nonstandard "expression closures" feature means this will not work in any other interpreter unless you insert `{return` and `}` in the necessary places (at a cost of 7 characters).
Original test cases:
* 1 → 1
* 10 → 3
* 101 → 41
Some additional ones:
* 1020 → 726
* 21667 → 40173
* 120000 → 262002
* 999999 → 2359000
[Answer]
# C - 147 ~~148 157 163 166 172 200~~
C is the right tool for the job
```
s;l(x){s+=(22>>x%10&1)+(x/10%10==4)-!((x+89)/2%50);x&&l(x/100%10);}main(x,v)int**v;{for(x=atoi(v[1]);x;x--)l(x),l(x/1000),s+=x>999;printf("%d",s);}
```
Original tests:
* 1 -> 1
* 10 -> 3
* 101 -> 41
Tests by @PleaseStand :
* 1020 -> 726
* 21667 -> 40173
* 120000 -> 262602
* 999999 -> 2359000
Plus some of my own random tests: <http://qp.mniip.com/p/cy>
[Answer]
# Mathematica ~~49 58~~ 50 bytes
Without a library or internet access.
```
StringCount[""<>IntegerName[Range@#,"Words"],"o"]&
```
---
**Note**:
"Words" guarantees that no digits will be left untranscribed into English.
This incorrectly returns one "o". (Emphasis added.)
```
IntegerName[1020]
```
>
> 1 th**o**usand 20
>
>
>
---
This yields two "o"'s, as required. (Emphasis added.)
```
IntegerName[1020,"Words"]
```
>
> **o**ne th**o**usand, twenty
>
>
>
---
**Example**
```
StringCount[""<>IntegerName[Range@#,"Words"],"o"]&[1020]
```
>
> 726
>
>
>
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 6 bytes
```
ƛ∆ċ\oO
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwixpviiIbEi1xcb08iLCIiLCIxMDEiXQ==)
Suggested by *@emirps*
## [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
ɾ∆ċṅ\oO
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvuKIhsSL4bmFXFxvTyIsIiIsIjEwMSJd)
Num-to-words builtins FTW!
#### Explanation
```
ƛ∆ċ\oO # Implicit input
ƛ # Map over range:
∆ċ # Convert to words
\oO # Count "o"
# s flag sums the list
# Implicit output
ɾ∆ċṅ\oO # Implicit input
ɾ # One-range
∆ċ # Convert to words
ṅ # Join into a string
\oO # Count "o"
# Implicit output
```
[Answer]
# Moo - 137 bytes
```
s=$string_utils;m=player;i=0;for a in[1..toint(read(m))]i=i+length(s:strip_all_but(s:english_number(a),"o"));suspend(0);endfor m:tell(i);
```
The `suspend(0)` is necessary to avoid a `Task ran out of ticks` for high inputs. Also, this code takes quite a long time to run for very high numbers.
[Answer]
# [Python](https://www.python.org) + [num2words](https://github.com/savoirfairelinux/num2words), 81 bytes
```
lambda n:sum(num2words(i).count('o')for i in range(1,n+1))
from num2words import*
```
[Answer]
## Perl - 384
```
#!/usr/bin/perl
@b=qw(1 1 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1);
sub b($){my($b,$m)=shift;if(20>$b){$b[$b];}elsif(100>$b){$m=$b%10;
$b[(($b-$m)/10)+18]+($m?b($m):0);}elsif(1000>$b){$m=$b%100;
b(($b-$m)/100)+($m?b($m):0);}elsif(1000000>$b){$m=$b%1000;
b(($b-$m)/1000)+1+($m?b($m):0);}}
sub c($){my$c=shift;my$d=0;$d+=b($c--)while($c);$d;}
print c($_)."\n"while(<>);
```
this would run faster with caching but that would increase my score
] |
[Question]
[
Given two integers, *s* and *e*, print the title of *[Black Mirror](https://en.wikipedia.org/wiki/Black_Mirror)* series #*s* episode #*e*.
Expected output is as below, case sensitive. Output for blank cells and invalid inputs is unspecified.
```
e↓s→ 1 2 3 4 5 6
1 | The National Anthem | Be Right Back | Nosedive | USS Callister | Striking Vipers | Joan Is Awful |
2 | Fifteen Million Merits | White Bear | Playtest | Arkangel | Smithereens | Loch Henry |
3 | The Entire History of You | The Waldo Moment | Shut Up and Dance | Crocodile | Rachel, Jack, and Ashley Too | Beyond the Sea |
4 | | | San Junipero | Hang the DJ | | Mazey Day |
5 | | | Men Against Fire | Metalhead | | Demon 79 |
6 | | | Hated in the Nation | Black Museum | | |
```
(The episode "White Christmas" is grouped with series 2 on Netflix, but originally aired as a standalone special, so it is not part of the challenge. The film *Bandersnatch* is likewise standalone and exempt.)
This question was posted before the release of series 6, at a time when it appeared the future of *Black Mirror* was in jeopardy. I have added series 6 to the challenge; answers posted before this edit are still considered valid.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 162 bytes
```
!x'x!¶¨Σṅ←ÿ‼⌋xżFE«Ȯ⌊Żψ'xΣẏ>ï?₀fẏu₈eṙ‼ḂkxẇïBȦrxΣ«QẆḟṁŸ)⁶ıex₉?²tx«‼UÜUÄd□Δ'xS▲⌋ȷ9oxṀËäαγFxHȦ∂↕εṄ|≠USSχ⁷ıżxŻKȦ£Ġx£%Øx□´'ËDJxẎȦlḊh₈Ċż_ṀÿKi▼V₉→xSmi►&η$x£ƒ´,⌋ȷ@,Ädÿ¿◄θ⁰
```
[Try it online!](https://tio.run/##HY7NSsNQEIWfpaAGoStdubEiWsSuJNStGyuVKoJamIWLJMT0F5WiVUFopRKEgrW1tkkaCNybSFa3z3DnReLobg5858xXLF@UkiQFCqTYhL2LnnSv0brjAWo@NhsQ@dlt1o8/sFmPZvOqAkR4t@t8kEFDO6KzjEa1IN1n4qVjlEB6FT7YjO1zIll/T3qWdDrS1SNnGfVJOCwAGrUMG10C61Mnz1/y3DzE9qu4V0DF9oi@xtO1M5Cuxhv8TQzFVxZ2YhurBloP4lu65hXWunlVnVdQn4bDyIdolott1gu7wHqL/Alojo0V3tjaJZ@b2D6RTr1IomE98g/@hoPcMbb9fVJBqwXqKSVvSUwXqP/TYuP0v8RGmsx4wAJ8NIWD@meSJCvJ6i8 "Husk – Try It Online")
A perfect task for Husk's string compression. Seasons are separated with newlines and episodes are separated with 'x'.
Then:
```
!x'x!¶¨...
¨... Big compressed string
¶ Split on newlines
! Take the line corresponding to given season
x'x Split on 'x'
! Take the title of the given episode
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 213 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•Ω?"Λ1äγÍθ}Æuмï∍βb6G¨—Wc“jép¡úórÑ9ǝ‘øδs@!иésb•#`”0á½Ú©ÿ0ŽÚÿ0Lj,—É, ÿͱ…«00
0€€ƒ³à¬ÿ0ßà‡ÈÝìs0€€îÆ„ª of€î00
0€ïƒ©‚ƒ0„¸Ÿâ0€€Ò´doœÂ00
«¢d in ÿï¹0ÄÃÿ0†•ÿ0À…€¾ ÿ–›0†ŽŠ€ÿ0…±†¤ŠÄ
ƒÏ—´0USS„Òÿ0Aÿ0Cÿ0ÂŒ ÿ DJ0îÊÿ”¶¡0δ¡IèIèðÚ
```
[Try it online](https://tio.run/##NU9NSwJBGL77K7a6SkwgQaeKgqirRNcyC@yQ0dIxGEzsAyRaO4Rm7S4ibkpWLrFJJrwPa4dg8TfMH9neCYN3mHd4Pidv7mRye3E8q6QbeYvTUW0OjaiHchSconQy/kRXXZSjt8z8GrWUvN3aVfL@AN4ROeijd4ybhe@6kncIIt9cmhoH8MwMe81sK1kXcGiAKnkYipAXvnD@U0qyDy6TBoYo06uSTWoLkRCq0OEZWdSDTR3NfYStpIML1NExJzieUVLygZ6M/P7fcyJFl5WektWRJTQehAHcf41FfjYfVlBgMrXJzRq5Qx3fpQ@BIs44TEnOcnWq5EYsoi9mKFlRsq/BcBDa2kozm7q1TY3QRjExsnDNHyJfbKbTnAyLOct8VrRZIbTYxljdEFz8ShvW6Z0cEfnkrKPFgxfU4jiVSP0C) or [verify all test cases](https://tio.run/##NVBLSwJRFN73KybbStwWCa0sKoIWbiJqmaaBLZpoaBlcLOwBEo0tQrNmRMRJycohpugB52NsEQz@hvtHpnOj4F7uOXyvc49pZXPFQjy9mFlNLWbWE1Yha5k7Bj6TRmG3aJn5AteGKttGIh1PKtmMvHQiqk@hFQ1QiYIDlPdHb@irk0r0lEstUUfJy7VNJa@34e2Si1cM9nAx89VQ8gpB5Fuz46MAnpVjr4kNJRsCLr2jRh4@RcgFPzj@LifZB6dJTkeFHpVsU1eIMaFKPT5DmwZwqKe5t3CUdHGCBnrWH457lJW8oTvD3Ppt/6Tos9JTsja0hcaDMEDzX2OTnzfDKkpMpi4180ZRLwJ9ehE4wiGHKclZTZ0qeSIW0QczlKwq@arB8D10tJVmtvXUDrVCB0djQxvn/CHyxerKCifDZs4c33ltVgptveWFZcGDn2nDBj2TKyKf3HV0MujgAfU4eUDP6fgH).
**Explanation:**
```
.•Ω?"Λ1äγÍθ}Æuмï∍βb6G¨—Wc“jép¡úórÑ9ǝ‘øδs@!иésb•
"# Push compressed string "head the rocodile rkangel ister ipero and test dive the hem and ereens ers"
# # Split it on spaces
` # Pop and push each string separated to the stack
”0á½Ú©ÿ0ŽÚÿ0Lj,—É, ÿͱ…«00
0€€ƒ³à¬ÿ0ßà‡ÈÝìs0€€îÆ„ª of€î00
0€ïƒ©‚ƒ0„¸Ÿâ0€€Ò´doœÂ00
«¢d in ÿï¹0ÄÃÿ0†•ÿ0À…€¾ ÿ–›0†ŽŠ€ÿ0…±†¤ŠÄ
ƒÏ—´0USS„Òÿ0Aÿ0Cÿ0ÂŒ ÿ DJ0îÊÿ”
# Push dictionary string "0 Striking Vipÿ0 Smithÿ0 Rachel, Jack, ÿ Ashley Too00\n
# 0 The National Antÿ0 Fifteen Million Merits0 The Entire History of You00\n
# 0 Be Right Back0 White Bear0 The Waldo Moment00\n
# Hated in ÿ Nation0 Noseÿ0 Playÿ0 Shut Up ÿ Dance0 San Junÿ0 Men Against Fire\n
# Black Museum0USS Callÿ0Aÿ0Cÿ0 Hang ÿ DJ0 Metalÿ",
# with all `ÿ` automatically filled with the strings on the stack
¶¡ # Split it on newlines
0δ¡ # Split each line on 0s
# [[""," Striking Vipers"," Smithereens"," Rachel, Jack, and Ashley Too","",""],
# [""," The National Anthem"," Fifteen Million Merits"," The Entire History of You","",""],
# [""," Be Right Back"," White Bear"," The Waldo Moment","",""],
# [" Hated in the Nation"," Nosedive"," Playtest"," Shut Up and Dance"," San Junipero"," Men Against Fire"],
# [" Black Museum","USS Callister","Arkangel","Crocodile"," Hang the DJ"," Metalhead"]]
Iè # Index the first input-integer into it (0-based and with wraparound)
Iè # Index the second input-integer into that list (0-based and with wraparound)
ðÛ # Remove any leading spaces
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the used compressed and dictionary strings work.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 202 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü○b(╠◘qÅñÿ[%Uδö╬ε#êc∙╪≈ü╒┘ú┴tÆ↔nU¥┴♣ߪ•┼<\╣`vΘ╒°²~♦∙'E♂○N½←àp▄û'XpéIê┼z♂Qìa~Æq7-T⌐ ○¡B▬#√╤cçµM╖Æ♦N╜Ü◄4òτ`≈úG{╧►)┴╬║º,Φ┤╫ÿα►]Q╬≈♠ [εjy0z▲dΘÜ╚é6♥#ö»ë'KC▬.W◙)lH↓√↓ö¿▐▌φ┬;┼ΣuΓuΣiè‼x╘ö╝▐┴ßIG•∙¿╦↓AQt}yd◘$éⁿ≤←
```
[Run and debug it](https://staxlang.xyz/#p=81096228cc08718fa4985b2555eb94ceee238863f9d8f781d5d9a3c174921d6e559dc105e1a607c53c5cb96076e9d5f8fd7e04f927450b094eab1b8570dc96275870824988c57a0b518d617e9271372d54a92009ad421623fbd16387e64db792044ebd9a113495e760f7a3477bcf1029c1cebaa72ce8b4d798e0105d51cef706205bee6a79307a1e64e99ac88236032394af89274b43162e570a296c4819fb1994a8deddedc23bc5e475e275e4698a1378d494bcdec1e1494707f9a8cb194151747d7964082482fcf31b&i=1+1%0A1+2%0A5+1%0A3+6&a=1&m=2)
This program takes episode and season as input, separated by a space.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 192 bytes
```
`λƛ ¬ε Ṫṅ¥ṗXṠ↳ ÷⁋ Ṗ≈sXλƛ ∆ɾ ∧Ġ of λß
Be ¬ẏ λǑX∧… ∞↑Xλƛ W…±o ɽ⁋
₁ḣ¦ḭX∨±∨ḊXż≬ Up λ¬ ↔÷X⟑ɖ ∨Ǐ °↔X←Ġd in λλ ⌐±
USS ⟑«iḊꜝrXArk›ǎXC≥ẋo∩ȧeX⟩ẇ λλ DJX∆↑÷≠X¬⁼ ¢⁋
Ẇ± Ŀʀ□ẊX€∧□Ṅ↳¾X₄ð, ¢…, λ¬ §⋏ ⟑⋏`↵\X/?i?i
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60%CE%BB%C6%9B%20%C2%AC%CE%B5%20%E1%B9%AA%E1%B9%85%C2%A5%E1%B9%97X%E1%B9%A0%E2%86%B3%20%C3%B7%E2%81%8B%20%E1%B9%96%E2%89%88sX%CE%BB%C6%9B%20%E2%88%86%C9%BE%20%E2%88%A7%C4%A0%20of%20%CE%BB%C3%9F%0ABe%20%C2%AC%E1%BA%8F%20%CE%BB%C7%91X%E2%88%A7%E2%80%A6%20%E2%88%9E%E2%86%91X%CE%BB%C6%9B%20W%E2%80%A6%C2%B1o%20%C9%BD%E2%81%8B%0A%E2%82%81%E1%B8%A3%C2%A6%E1%B8%ADX%E2%88%A8%C2%B1%E2%88%A8%E1%B8%8AX%C5%BC%E2%89%AC%20Up%20%CE%BB%C2%AC%20%E2%86%94%C3%B7X%E2%9F%91%C9%96%20%E2%88%A8%C7%8F%20%C2%B0%E2%86%94X%E2%86%90%C4%A0d%20in%20%CE%BB%CE%BB%20%E2%8C%90%C2%B1%0AUSS%20%E2%9F%91%C2%ABi%E1%B8%8A%EA%9C%9DrXArk%E2%80%BA%C7%8EXC%E2%89%A5%E1%BA%8Bo%E2%88%A9%C8%A7eX%E2%9F%A9%E1%BA%87%20%CE%BB%CE%BB%20DJX%E2%88%86%E2%86%91%C3%B7%E2%89%A0X%C2%AC%E2%81%BC%20%C2%A2%E2%81%8B%0A%E1%BA%86%C2%B1%20%C4%BF%CA%80%E2%96%A1%E1%BA%8AX%E2%82%AC%E2%88%A7%E2%96%A1%E1%B9%84%E2%86%B3%C2%BEX%E2%82%84%C3%B0%2C%20%C2%A2%E2%80%A6%2C%20%CE%BB%C2%AC%20%C2%A7%E2%8B%8F%20%E2%9F%91%E2%8B%8F%60%E2%86%B5%5CX%2F%3Fi%3Fi&inputs=3%0A1&header=&footer=)
```
`...` # Dictionary-compressed string
↵ # Split on newlines
\X/ # Split on Xs (vectorised)
?i?i # Index input twice
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 224 bytes
```
§⪪§⪪”}∨⊙α⁷ξ{⪪\`G↔Iλ?I⟧∧≕EαγR≔³E↙\`UκêΣJ4⧴U↙�~B⁺^dF]η8A⊖ξ≡W¦¶⧴hNνX^#Ol▶⊙|Q|,/(:ZNQξζG↥≧⟲ψ∨]⮌⊖≦#Rς+vQlK≧⦄⁴φC7“L¡⊘[⁸⮌!⌕↗Op;⧴‹Hr,◧⁹‖·›↨χ➙⌕↙bM″G@ⅉ<↔GnQS§‖⎚Þ⟧⊗¤E*ⅈ⁶℅Orν%F¤×Xbη&◨χJWCXz�Π8D>νB⁶≔X″~↖≡@/ÀY#¦▷I¿↷Φ№!|↔δMKUλÀE§χUo:γ@▷”¶N⸿N
```
[Try it online!](https://tio.run/##ZY9BawJBDIX/StiTgr20x55WraiwIq5WCnNJd6MTHDOSyUr99dtRSg/tMe/xXr7XeNQmYuj7tbLYoLSFtPQ1qC@B/17FBhtPYQRLbE4jQGmhTD7QDbYxOq1N@cRyhHe@kKYsnNk8KZEkJ1tP8CbGSjDnZFFvEA/wETund2uFxlEwQCk5c3Y644PlJFQcQnagImX76dljaCNU8UxiTscEGz56g3HGcrr3bARjQnUyR6MWWMB@XzhdxUQtX8npOuDNKOWO2ncGu8tj0xSlyWaNAstO7lvyuCqjlEdkSQazPMLJOOR3UHWJuoy7q2uYYEZNRuq01BPKkYLTicYmthxy4zxLD5Lp8l5oGDxhW4ygcFIMR7CQS2er7vxJOhgO77L@l4evff8Cz/3TNXwD "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
”...” Compressed table of episode titles
⪪ ¶ Split on `\n`s
§ N Cyclically index by series
⪪ ⸿ Split on `\r`s
§ N Cyclically index by episode
Implicitly print
```
Because Charcoal uses cyclic 0-indexing the last series and last episode of each series will wrap around to 0 so they actually appear first in the table.
[Answer]
# JavaScript, 353 bytes
```
s=>e=>`The National Anthem|Fifteen Million Merits|The Entire History of You||||Be Right Back|White Bear|The Waldo Moment||||Nosedive|Playtest|Shut Up and Dance|San Junipero|Men Against Fire|Hated in the Nation|USS Callister|Arkangel|Crocodile|Hang the DJ|Metalhead|Black Museum|Striking Vipers|Smithereens|Rachel, Jack, and Ashley Too`.split`|`[s*6+e-7]
```
[Try it online!](https://tio.run/##lZBNSwMxEIbv/oo5@g22W/VSofUDKayIWxURocPudHdsmpRktlCY/17Til6agw45vXnnyUM@cYmh9LyQk@Xletpfh/4V9a8m44bgAYWdRQMDKw3N9Y6nQmQhZ2PiBeTkWYJuqrdW2BPccxDnV@Cm8OZajTMkeOK6ERhiOdPXhoVgSOi3W69oKge5m5OVTfnBBap4SfpocCUURIumFXheANoKbtCWpAVaGLWWF@Sd5tFmUCPbIHAXBfQehSpgC/Lrr89FAdcYlYOQ14Gfoa3J6LV3pavYbJZsvV24GUWioGkIKx2aaAx5G6idayGeZxxrL5uHgxZzjgs@/kbQJywbMscwiv3jrekgNIZWMHZuchoWhmWik/dweH5EJxcf69LZ4AydGlfvw3T/7CAeONjbjTvpuLsT/8xOu5Nmd9Lszr/Y3TS7m2Z3U@xtnKXjXjo@/7tglhbM0oJZWjBLC2Zpwexfgr20YC8t2PsWXH8B "JavaScript – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 360 bytes
```
lambda s,e:"The National Anthem|Fifteen Million Merits|The Entire History of You||||Be Right Back|White Bear|The Waldo Moment||||Nosedive|Playtest|Shut Up and Dance|San Junipero|Men Against Fire|Hated in the Nation|USS Callister|Arkangel|Crocodile|Hang the DJ|Metalhead|Black Museum|Striking Vipers|Smithereens|Rachel, Jack, and Ashley Too".split("|")[s*6+e-7]
```
[Try it online!](https://tio.run/##PZBNS8NAEED/ypBTq1UogoLgoR@WUkiRprWIehibSXboZjfsToTA/Pe66cG57ns7j2l7Md49XKqXr4vF5qdEiBN6zvaGYIvC3qGFmRNDja64EiIHOVubHiCnwBJ1QF@dcCBYcxQfevAVfPhO08wJdlwbgTmezno0LARzwnC1jmhLD7lvyMkAb32kkn9J3yz2QlG0MJ3AoQV0JSzRnUgLdLDpHLcUvOapZlYjuyiwSgG6RqES2IH89@uhKGCBKTkKBZ2FM7qarC6CP/mS7SC5@iosN@lHQWsIS53bVAx5F6lrtJDAZ07Y@7A4atFwEkK6RtQdngzZCWwSP7mWzqKx1MPe@@w@tpZllGk2/ow3j7d09/R9aQM7GVWj6WQ6Hl/@AA "Python 3 – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 291 + 45 bytes
up to series 6
```
base64 -w0|cut -d2 -f$2|cut -d3 -f$1|tr 45 \ ,
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LVHLTtxAEFSu_gofcmSjxN0L4ehlgzarGEWYhxDJoWO3d0Y7nkEz7SAjvoBfyIUD8E_ka-jd5dSq7qruqpl_T38omcfH50G6ydfXT4p4H_PJ7ef7ZpB80hb5pPtYvAPYgC_3EnOc5r_yvZ3qXfxyDXv5_u__Hx7ODOMJiQ2eHJZeDPcwYzy1KyM4o2YNJyFxa_8ynNc1HpFzNglHqCXatfUrvLA3HBMsA2Uevycsb7vBFce2E2aPlVVB0MrRSoJLY4VxxhThp6NROAmUcU1-xQ7q3ur9qLIEP7LQGFywj2Ox8fjNi42MCz0e4oihw6swwGZySa4NWIWevUBtBsHzGyTf4px8w3AUQxOy1jqGU2oMuykuNdZ0SymTcTziWQgaegzaUQNYMxUANXlcDn6TLsBCHW5n8yVkUNGdquY0Kq3SkOWKrE-Cx2pRG0LOMLUAc-41-sGh0hYk3KL12yW7B4eZoyZbYzUkHvrsZfefbw)
The input is generated with
`cat table | tail -n 6 | sed "s/ *| */|/g" | cut -d "|" -f 2-7 | tr "\n| ," "2345" | sed "s/332$//" | base64 -d`.
] |
[Question]
[
**This question already has answers here**:
[Russian Roulette](/questions/9062/russian-roulette)
(59 answers)
Closed 3 years ago.
# Russian roulette
It's [Russian roulette](https://en.wikipedia.org/wiki/Russian_roulette)! The rules are simple. Shoot a revolver with `n` slots for bullets and one round inside at your head and you *might not die*!
This Question is different from other Russian roulette questions because it takes input to change the chance of exiting with an error.
## Task:
Make a program that takes integer `n` (you can assume that 10<=n<=128) as input and **outputs nothing.**
>
> but how do I tell if I'm dead?
>
>
>
The program generates a random number x in the range 0 - n inclusive. If x=0 the revolver fires and the program exits with an error (you die). Otherwise the program exits normally.
If your language needs it, the range can be 1-n inclusive.
Standard loopholes forbidden, etc. Upvote answers in *fun* languages! What I'd really like to see is an answer in a language that doesn't have normal randomness (eg. in Befunge where `?` sends you in a random direction instead of giving a random number).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 3 bytes
Full program. Exits with code 11 or 0. Requires `⎕IO←0`.
```
÷?⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/w9vtwdy/v83NAQA "APL (Dyalog Unicode) – Try It Online")
`⎕` prompt for `n`
`?` generate random integer in range `0`…`n-1`
`÷` reciprocal (errors if argument is 0)
[Answer]
# [JavaScript (V8)](https://v8.dev/), 18 bytes
Community consensus is that time can count as a source of randomness. This function will simply take the time in milliseconds modulo the inputted value. If `0`, the function tries to return `a`, which does not exist.
```
n=>Date.now()%n||a
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/z9bOJbEkVS8vv1xDUzWvpibxf0FRZl6JRpqGqabmfwA "JavaScript (V8) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 3 bytes
```
JlO
```
[Try it online!](https://tio.run/##K6gsyfj/3yvH//9/IwMA "Pyth – Try It Online")
`O` - generate a random integer in the range `0` - `n-1`
`l` - log base 2 of that integer. Throws a `math domain error` if `0` was generated
`J` - assign the value to a variable so that we suppress all output
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes
```
≔‽‽Nθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8jKDEvJT8XRnnmFZSW@JXmJqUWaWhqauooFGpa//9v9l@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The `N` function reads the input number. The `‽` generates a random number between `0` and its argument. However, this errors if the argument is zero. This happens if the inner `‽` randomised a `0`, i.e. 1 in `n` times. The `≔θ` simply serves to make the program do nothing if it was successful.
[Answer]
# Rust + time crate, 38 bytes
```
|n:u8|1/(time::Time::now().second()%n)
```
Defines a closure that takes an unsigned 8-bit integer as input and returns an integer or panics with "attempt to divide by zero".
[try it online](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=fn%20main()%20%7B%0A%20%20%20%20let%20f%3D%7Cn%3Au8%7C1%2F(time%3A%3ATime%3A%3Anow().second()%25n)%3B%0A%20%20%20%20%0A%20%20%20%20%2F%2F%20test%20if%20it%20crashes%0A%20%20%20%20for%20i%20in%200..1000%20%7B%0A%20%20%20%20%20%20%20%20println!(%22i%3D%7B%7D%22%2C%20i)%3B%0A%20%20%20%20%20%20%20%20f(20)%3B%0A%20%20%20%20%20%20%20%20std%3A%3Athread%3A%3Asleep(std%3A%3Atime%3A%3ADuration%3A%3Afrom_millis(500))%3B%0A%20%20%20%20%7D%0A%7D).
Our [rules](https://codegolf.meta.stackexchange.com/a/13094/46901) about using the time as randomness state the following (emphasis mine):
>
> [...] if you have to select one random value per script execution, current **seconds**/milliseconds should be sufficient.
>
>
>
[Answer]
# [Python](https://docs.python.org/3.8/), ~~57~~ 43 bytes
Saved 14 bytes synchronously with thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!!
```
lambda n:1/randint(0,n)
from random import*
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSHPylC/KDEvJTOvRMNAJ0@TK60oP1cBJAKkMnML8otKtP6n5RcpZCpk5oHE01M1DA00rdJA5H8A "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 26 bytes
`id(0)%129%-~n` gives a random number from 0 to n inclusive. It returns an error if it equals 0, because of `ZeroDivisionError`.
```
lambda n:1/(id(0)%129%-~n)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPylBfIzNFw0BT1dDIUlW3Lk/zf0FRZl6JQpqGseZ/AA "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 23 bytes
```
1/(id(0)%129%-~input())
```
which is a merging of [dingledooper's answer](https://codegolf.stackexchange.com/a/204331/75323) with my original one (below). [Try it online!](https://tio.run/##K6gsycjPM/r/31BfIzNFw0BT1dDIUlW3LjOvoLREQ1Pz/38jAA "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 40 bytes
```
from random import*
1/randint(0,input())
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocRnqgwQy80o0DHQy8wpKSzQ0Nf//NwIA "Python 2 – Try It Online") Full program.
[Answer]
# MATLAB, 32 bytes
```
@(n)eval('if(randi(n)==n)a;end')
```
`randi(n)` outputs random integer from [1,2,3...n] list
`a` is undefined, so when it is called, program errors out
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
Ý<Ω¬F
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8FybcysPrXH7/98QAA "05AB1E – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 22 bytes
```
n->n/=n*=Math.random()
```
[Try it online!](https://tio.run/##ZVCxboMwEN35ilMkJAKNk6xNqdShQ4eoA@pUdXCNSZzCYdlHVFTx7fSAkAzxYN@953f37k7yLFen/Kc3la0dwYlz0ZApRbwL7rCiQUWmxoFUpfQe9tIg/AUAtvkujQJPkvg51yaHirkoI2fw8PkF0h38cvwK8Ib0gdK171Y7SbWDIu1x9YzrFON0L@konMS8rqJlvxsFBgl8o5TmlilsbiBX1wO03fC5wThCU15w/WgAzSjl52mScZgksyVgrL3GrBLS2rJ98ew1wuXuSlxsJMkMdaAkqSNEr79K22E9oLlqN9LTnbWedCXqhoTldVARLbLLNDy/foRQbIswDHHxMEySx/Os68np2L4Luv4f "Java (JDK) – Try It Online")
[Answer]
# Python3, 66 bytes
```
0/0 if __import__("random").randint(0,int(input()))==1 else exit()
```
[Answer]
# T-SQL, 24 bytes
```
DECLARE @ INT=10
SET @/=floor(rand()*-~@)
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1235151/russian-roulette-varying-chances)**
[Answer]
# [W](https://github.com/A-ee/w) [`j`](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends/14339#14339), 2 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
```
g(
```
## Explanation
```
Implicit input
g Randrange 1 to input
( Decrement the number by 1
Flag:j (Evaluates the J command at the end of the program)
The J command, given a number operand, reciprocals the number.
It throws a 0-division error when the operand is 0.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 14 bytes
```
->n{1./rand~n}
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9cur9pQT78oMS@lLq/2f1q0Wex/AA "Ruby – Try It Online")
Exits with `ZeroDivisionError` when `rand~n` returns 0. It's helpful that `rand` takes the absolute value of its argument.
] |
[Question]
[
Brainf\*\*k is the most famous [esoteric programming language](https://esolangs.org/wiki/Brainfuck) and is the inspiration for hundreds of other esoteric languages. In fact, there are quite a few languages that are so heavily based off of Brainf\*\*k that the only difference is the characters used. Your challenge is to interpret one of these languages.
## Brainf\*\*k
Brainf\*\*k uses these commands:
```
> Move pointer to the right
< Move pointer to the left
+ Increment the memory cell under the pointer
- Decrement the memory cell under the pointer
. Output the character signified by the cell at the pointer
, Input a character and store it in the cell at the pointer
[ Jump past the matching ] if the cell under the pointer is 0
] Jump back to the matching [ if the cell under the pointer is nonzero
```
## Trivial Brainf\*\*k Substitution
There are lots of [esolangs](https://en.wikipedia.org/wiki/Esoteric_programming_language) that are identical to Brainf\*\*k in that they use the same commands, just with different characters/strings signaling the commands. For example, take [Ook!](https://esolangs.org/wiki/Ook!):
```
Brainf**k | Ook | Command
-----------------------------------------------------
> | Ook. Ook? | Move the pointer to the right
< | Ook? Ook. | Move the pointer to the left
+ | Ook. Ook. | Increment the memory cell under the pointer
- | Ook! Ook! | Decrement the memory cell under the pointer
. | Ook! Ook. | Output the character signified by the cell at the pointer
, | Ook. Ook! | Input a character and store it in the cell at the pointer
[ | Ook! Ook? | Jump past the matching Ook? Ook! if the cell under the pointer is 0
] | Ook? Ook! | Jump back to the matching Ook! Ook? if the cell under the pointer is nonzero
```
Ook is exactly like Brainf\*\*k, except for the syntax.
[`TrivialBrainfuckSubstitution`](https://esolangs.org/wiki/TrivialBrainfuckSubstitution) is a function defined as:
```
TrivialBrainfuckSubstitution(string1, string2, string3, string4, string5, string6, string7, string8)
```
Each string provided substitutes the corresponding Brainf\*\*k character - so `string1` will be a substitution for `>`, `string2` will be a substitution for `<`, so on and so forth.
For example, [Ook!](https://esolangs.org/wiki/Ook!) is equivalent to `TrivialBrainfuckSubstitution("Ook. Ook?", "Ook? Ook.", "Ook. Ook.", "Ook! Ook!", "Ook! Ook.", "Ook. Ook!", "Ook! Ook?", "Ook? Ook!")`.
[Alphuck](https://esolangs.org/wiki/Alphuck) is equivalent to `TrivialBrainfuckSubstitution("a", "c", "e", "i", "j", "o", "p", "s")`.
# The challenge
Implement `TrivialBrainfuckSubstitution`.
To elaborate: Given eight strings representing the eight substitutions and a ninth string representing a program, interpret the program as a trivial Brainf\*\* substitution.
# Rules
* `TrivialBrainfuckSubstitution` may take function arguments or command line arguments. These are the only ways it may take the first eight arguments.
* `TrivialBrainfuckSubstitution` can take the ninth argument from standard input, a file, or a literal ninth argument.
* `TrivialBrainfuckSubstitution` must be able to take any ASCII characters as substitutions. It does not have to handle Unicode, and you can assume there are no duplicate elements provided.
* Note that the actual function in your code need not be named `TrivialBrainfuckSubstitution`. This is just the title of the function; the actual name in the code can be `f`, or `x`, or a lambda, or whatever you like.
* Your interpreter should not require any spaces between command substitutions. However, it should not break if they are present. To rephrase, it should ignore unrecognized commands, just like normal Brainf\*\*k.
* You may assume that all substitutions are the same length. I.e. you may assume that `AB`, `A`, and `B` are never in the same substitution set.
# Challenge-specific Brainf\*\*k semantics
In your newly-created Brainf\*\*k language:
* You do not need to be able to go left from the start of the tape. (You can choose to allow this.)
* The tape should have a minimum length of 30000. (If you want it can be longer or allocated dynamically.)
* The maximum value of the tape elements must be the maximum value for an integer in your (host) language.
* Input can be read from standard input or a file.
* An attempt to read `EOF` (End Of File) should not cause any undefined behavior. `EOF` must simply be stored as would any other character read.
# Test cases
[Test case 1](https://pastebin.com/raw/TJPUwgN9)
[Test case 2](https://pastebin.com/raw/Z1YYLj9x)
# Winner
As with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest submission wins. I won't ever accept an answer unless one is 50 bytes shorter than all others.
Also, as this challenge is somewhat more difficult than others (while certainly not the hardest), I kindly ask that you include an ungolfed version and explanation with your answer.
[Answer]
# [Python 2](https://docs.python.org/2/), 447 bytes
```
import re,sys
def f(b,r,a,i,n,f,u,c,k):
d,e,g,m=[0]*30000,0,0,''
for n in re.finditer('|'.join(r'(?P<%s>%s)'%m for m in[(j,re.escape(l))for j,l in zip('rlidoswen',[r,a,i,n,f,u,c,k,'.'])]),b):
m+=' '*g+{'r':'e+=1','l':'e-=1','i':'d[e]+=1','d':'d[e]-=1','o':'sys.stdout.write(chr(d[e])),','s':'d[e]=ord(sys.stdin.read(1))','w':'while d[e]:','e':'pass'}.get(n.lastgroup,'')+'\n';g+=n.lastgroup=='w';g-=n.lastgroup=='e'
try:exec m
except:d[e]=-1
```
[Try it online!](https://tio.run/##zVTbbqMwEH3nKwxSNHaZWM3uGy3lE3bfs3mg2BCnYCObKM1evj1rQlqFSKlatdkuSKO5nJk5M7Ldbrul0V92O9W0xnbESnRbFwhZkpLeo8UcFWoscY0FPrAkIAIlVtik8@vF1ddr/2H/AwSkNJZoorQvwkulheqkpfAb@MooTS3Q7PvtxN1NHINJs0c3Hj2nK/QJ0hV5K2nNWB9YYd0X@qlaCrZWwriN1IDzEz4IHBZswfC@Z0aaOAUCV1X8CywkION0Bgh1r073qvKqmMvFEBAHa4gZb/nRueuEWXd8Yz19Wiwt7SGMoYe4Q0JqrKAHrNLcylzQGWMesfGIzVLVkvS4xHuk97S5c/CHV7Kjmte56ypr1q3fGYvhh4abKk6P/Gnqy9xU0xOf9Bvu7DaRj7IgTUDkYyHbLtnzmc52hRGSpCT6Zh448SIjT9pFRPjc48KNsudu4djMxlxOMv6TKV/Bnp@b42PYv6ny2U1m5KLn6l/s@bNm@9Tb8/YNvSxesbrsHacufK/4mCpnK798Xk5wYRQEJe3fZTx6lqPBGFKjo8iTMbQ8NkawUWRULYzY7i8 "Python 2 – Try It Online")
The first argument `b` is the code and the arguments `r a i n f u c k` are `> < + - . , [ ]` respectively.
Well... Lemme know if I missed out on anything.
---
## Explanation
This implements a golfed tokenizer.
```
import re, sys
def trivial_brainfuck_substitution(code, r, a, i, n, f, u, c, k): # define function with arguments
tape, index, loop, result = [0]*30000, 0, 0, '' # initialize tape, pointer, loop state and the final code
for i in re.finditer( # iterate over matches of the regex...
'|'.join( # which is the next list joined by '|'
r'(?P<%s>%s)' % m for m in # construct a regex with a named group
[(j, re.escape(l)) for j, l in # a tuple of...
zip('rlidoswen', [r, a, i, n, f, u, c, k,'.']) # the group name and the command
]
),
code): # in the given code
result += (' ' * loop + # a space for the current amount of loops
{
'r': 'index += 1', # move to next cell
'l': 'index -= 1', # move to previous cell
'i': 'tape[index] += 1', # increment current cell
'd': 'tape[index] -= 1', # decrement current cell
'o': 'sys.stdout.write(chr(tape[index]))', # output current cell's value as ASCII character
's': 'tape[index] = ord(sys.stdin.read(1))', # store ASCII number of input in current cell
'w': 'while tape[index]:', # start a while loop
'e': 'pass' # end a while loop
}.get(i.lastgroup, '') + '\n' # get respective command or an empty string for a no-op
)
loop += i.lastgroup == 'w' # increment the loop counter
loop -= i.lastgroup == 'e' # decrement the loop counter
try:
exec result # execute the generated code as Python code
except: # except on a TypeError, thrown when no input is found
tape[index] =- 1 # store -1 in current cell
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 49 bytes
Prompts for program as text, then for a list of eight PCRE patterns. Note that this allows for substitutions of differing lengths, and even mapping multiple substitutions to each BF command, at the cost of having to escape some characters. Outputs to STDERR.
```
⎕CY'dfns'
bf(⎕,'.')⎕R(,¨'><+-.,[] ')⊢⍞
```
[Try it online!](https://tio.run/##zVXBToQwEL3zFeXUNQv9gs020Q8wUS9GPMx2wUyXAFnAxC/QmOjNqwdPfoefwo/g0MVNagJhs4vrC2@YN7TT6aSkkMX@8gHi9K6unh6v1niPEJ@uAZOoVKvLcpEXWJQFpkldvb6dXfNllOTcWUQTkh4X/ITeFxPv65PPZ1NfeDe3jGLPH9XLe5OxZgZ9iZ3zdCUYGcl@vFGMu11j5IXkdjXXltKu5deMf7LLAdWLrn0cpvqdMnd2UrJRz9Vf9PlYezvq37N7h/rNgNbJPU6du685TJbOzP3nZTPO4WQDEwgkZ0aZgYFolbCUmRW4lrJH2t/snC53nAG3QthgZkBOBmFr6ZkbNB5REaYEn4A5UAQQIMxUrkiCBkTU4Qa6cTQFFWplfDRoX@TQTE15tdPcaEB1K2JIRKImpsSMmPNv "APL (Dyalog Unicode) – Try It Online") (runs first two test cases, as the third is faulty)
`⎕CY'dfns'` **C**op**y** [the **dfns** workspace](http://dfns.dyalog.com/)
`⍞` prompt for text input (the symbol is mnemonic: a quote character in a console)
`⊢` yield that (serves to separate the substitution patterns from the input)
`(`…`)⎕R(`…`)` **R**eplace:
`⎕,'.'` input (mnemonic: console) followed by PCRE for "any character"
… with:
`'><+-.,[] '` the BF symbols followed by a BF no-op space
`,¨` ravel each (to make them into character vectors/strings instead of scalars)
`bf` evaluate as **BF**.
---
As of posting, this is way more than 50 bytes shorter than the other two solutions.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~373~~ ~~372~~ ~~381~~ ~~380~~ 375 bytes
-1 Thanks to @StepHen
-1 Thanks to @RohanJhunjhunwala
-5 More thanks to @RohanJhunjhunwala's suggestion and cleaning up some repeated code
+9 Cause @totallyhuman made a valid point about `raw_input()` requiring a new line
```
import sys
def f(c,r,l,i,d,p,n,b,j):
t,x,a,h,s,o,v=[0]*30000,0,0,[],0,'',[r,l,i,d,p,n,b,j," "]
w=map(len,v)
while a<len(c):
for u in range(9):
if v[u]==c[a:w[u]+a]:break
if s<1or u>5:
exec"x+=1|x-=1|t[x]+=1|t[x]-=1|o+=chr(t[x])|t[x]=ord(sys.stdin.read(1))|if t[x]and s<1:h+=[a]\nelse:s+=1|if s<1:a=h.pop()-w[6]\nelse:s-=1|".split("|")[u]
x%=30000
a+=w[u]
return o
```
[Try it online!](https://tio.run/##zVbvbpswEP8cnsJ4mgrDWO2mTVoEtrYX2AMwPrjEaUxTQEDbVOq7Z3eGkrhdq1Rt1x3cj/vn8/nigJubflVXn7dbc9HUbU@6m85b6CVZBgVr2ZoZtmANq9gpK8O5R3q2YYqtWMdqdpVmx/mnL8dADK8sBzg6Ytm9cYwSmnvkOr1QTbDWFbsKQVuZtSYqAT0oIPNsWbfkkpiKtKo608F3tBGzJFfZZZ6mRabm1yBFKp@ftlqdezPwdckJjhJfMVZvdEE3UXpyu4kB@myTR@MT9TpKi1UboBpaY1q3iwCWy7t@YSoOSRfBSRjeQl50q2qB@eerKM1U/rvS607PO8w4TDxX6Yo3dROE8XX2bQrAqSjvmrXpA3pLQ6jZm20@prZN3kxFKS7DI63uL9uK1NumNVUP7abRRJkYBbGzCcsJUJyDzEXERw9HAXRwRi5xYV2xpfEBgkAHZVQAJ8ARcAyMNrwy4JyG3oPKhroQxYOK4IqFiLIkR1VwgTO5FQqexDz5e0nCruCQqnZlUfqrPucEQJI76U3An@Z444nkNJvvqtKt5d6I/2SVB1TPH1vH61T/rMyPdlKSN91X/6LP77W2d/33PL9DT8MBrZMv2HX@S@F1sjya@en9MsTBO5jt3sKUETpFjgrfV4YZ9hUnzPE42Xznxa@REksgNEqPCLewhBJwAYTfH/zEmE6BRRmldFN0BaiqVMaYUg9UolCCsTBlYWVjaXyAACNLyFtiXQqhQNAIBsE6aoQGocOSP0w1S0u@PyLeKN2hFfzBPUb6D3Aa6CPJgZ0RmMS9pRPm76ljvByy@b4ryF2Yk@pepNwPHmJM1Wk4SKoKTpamOiN4LiIr3UKnKMRalIgSEQYgWrscLKPX/c0ZhwPPAeeD7Y@ffwA "Python 2 – Try It Online")
Works on the first two test cases, but it looks like the third one is messed up since it has 9 strings instead of 8, and two are the same. It also works on some other Hello World! Brainfuck programs.
---
# Explanation
```
import sys
def TrivialBrainfuckSubstitution(code, greater, less, plus, minus, period, comma, leftbracket, rightbracket):
tape, index, slot, loopindex, skip, output = [0]*8**5, 0, 0, [], 0, '' # Set up variables for the tape, tape index, code index, list of loop indices we're in, skipping indicator, and output string
values = [greater, less, plus, minus, period, comma, leftbracket, rightbracket," "] # Create a list of all possible values to find in the code
lengths = map(len, values) # Create a list with the lengths of all of the elements in value
while slot < len(code): # While we havent reached the end of the string
for u in range(9): # For each value in the value list
if value[u] == code[slot:lengths[u] + slot]:break # If the u-th element of values is equal to the same length chuck of the code from the current index
if skip < 1 or u > 5: # If we're not skipping operations or if we found a leftbracket or rightbracket
if u == 0: # If the option was a greater
index += 1 # Increment the tape counter
elif u == 1: # Else if it was a less
index -= 1 # Decrement the tape counter
elif u == 2: # Else if it was a plus
tape[index] += 1 # Increment the current tape cell
elif u == 3: # Else if it was a minus
tape[index] -= 1 # Decrement the current tape cell
elif u == 4: # Else if it was a period
output += chr(tape[index]) # Append the character value of the current tape cell to the output string
elif u == 5: # Else if it was a comma
tape[index] = ord(sys.stdin.read(1)) # Store only a single character of input into the tape cell
elif u == 6: # Else if it was a leftbracket
if tape[index] and skip < 1: # If the current cell is non-zero and we aren't currently skipping over a loop
loopindex += [index] # Append the current index to the loopindex list
else: # Else we're trying to skip to the end of a loop
skip += 1 # Increment the skip counter (a count of the number of rightbrackets we need to skip to continue executing)
elif u == 7: # Else if it was a rightbracket
if skip < 1: # If we're executing code normally
slot = loopindex.pop() - lengths[6] # Move to the index we stored when we hit the leftbracket, but push forward enough so we hit it with the next character
# Simultaneously remove the last value from the loopindex list since we just used it
else: # Else we're trying to move past some loop
skip -= 1 # Decrement the skip counter since we found another rightbracket
index = index % 30000 # Map the index back to 0-29999
slot += lengths[u] # Move past the current operator
return output # Return the output string we generated
```
I took a different approach than totallyhuman did, so that I didn't need to import and modules. It does however use the same trick with passing strings to `exec` to have it do all the work. Effectively, at the start of each loop, it looks at the current index and sees if the text that follows can be matched to any of the operators that were given. If it can't, then the counter will end at an index associated with a non-valid character in this language.
The hardest part for me was getting a refined way of matching loop starts and ends. I eventually settled on a counter that gets incremented every time it sees a loop start operator, and decrements every time it sees a loop end. So in order to have the now parsed option executed, we have to be not skipping over code (indicated by a skip counter of 0) or it's the loop start or loop end characters (or a bad character, but nothing happens with that, so it's okay).
That counter index is then used to take the index-th slot of an array of strings that is created by splitting that massive string you see at all of the `|`s. That line of code is then executed by `exec` which will do a handful of checks and variable mutations. At the end of the loop we skip past the operator we just found and keep going. Finally, return the output string we've been adding onto this entire time.
On of the key pieces to this was how skipping back to loops was handled. Every time a loop was started, it appended its index to the back of a list, and every time a loop ended, it set the code index to the last value of that list (minus the length of the loop end operator so that when it was pushed "past" the loop end operator we would be at the loop start operator again).
[Answer]
# PHP, ~~275 222 234 238 239 235 233 236 230 229 224~~ 223 bytes
```
for($p=_.strtr($argv[9],array_flip(array_slice($argv,$m=1,8)));~$c=$p[$i+=$c<7];eval(['$m++','$m--','$$m++','$$m--','echo chr($$m)','$$m=ord(fgetc(STDIN))'][$c].';'))for($n=$d=[6=>!$$m,-1][$c];$n;)$n+=[6=>1,-1][$p[$i+=$d]];
```
Takes dictionary from arguments 1..8, code from argument 9, input from STDIN.
The tape has 2^64 cells and starts almost in the middle, but does not wrap.
Insert `,$m=($m+3e4)%3e4` after `eval(...)` for a wrapping 30K tape.
(or replace `'$m--'` with `'$m+=29999'` and insert `,$m%=3e4` after `eval(...)` - that´s 3 bytes shorter)
Requires PHP 5.5 or later. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/8eb475a290df685f110891cdcd8e61ccf1f8cb12).
**breakdown**
```
for(
# translate code to 0..7, init $m (memory pointer)
$p=_.strtr($argv[9],array_flip(array_slice($argv,$m=1,8)));
# loop through code
~$c=$p[
# 1. previous instruction was not 7: increment $i (instruction pointer)
$i+=$c<7
];
# 3. instructions 0..5: eval
eval(['$m++','$m--','$$m++','$$m--','echo chr($$m)','$$m=ord(fgetc(STDIN))'][$c].';')
)
# 2. instructions 6,7:
for(
# init $n: instruction 6 and cell is 0: 1, instruction 7: -1, else: 0 or NULL
$n=$d=[6=>!$$m,-1][$c];
# loop while $n (bracket count) is truthy
$n;
)
# 2. if bracket, increment / decrement bracket count
$n+=[6=>1,-1][$p[
# 1. increment / decrement IP
$i+=$d
]];
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 183 bytes
```
q:Iea):C;:O];{O{_,C<=}#_)O0=,(e&)C>:C}g]:C,{_C=6-We>"M+:M M(\:M;a+aL+:L "S/=~}/];0a3e4*{TC="(+ 1m> ))+ )(+ _W=co );I0ae|(\:I;i+ _W={L{1=T=}=0=:T;}| _W={L{0=T=}=1=:T;}& "S/=~T):TC,<}g;
```
183 bytes of pure, sweet CJam.
This first 8 command-line arguments are the commands, the 9th is the code.
[Try it online!](https://tio.run/##LYxNa4QwEED/ilhYTOOySksPifGSk6B4qLCXigwhLAksa/GYTf/6dMz6yMfLg4nxcEf8FZ0FJrQU4yzDGJZSNyq@LWysVFnYE9Ot0PE2C12GRauv89W2@cDFkA3FjxgkcOi56LP8@6L@4mWWFXzYz/cwaZUXPKvvbcYYzxj5clXmkTHZVWCfNNxJl2LoQ60mFVWlxCTj82hVanVqp9f/ExOTLpt4k4gIaNCiQ48PXHFDu9MkSFawx0mrTexG2xCcOBNuAyrgAOxqNkNP8OCc8/aF38VTNM6b5C5xXCQ06elf/w8 "CJam – Try It Online")
### Ungolfed and commented
```
e# Variables:
e# I Input
e# C Code
e# O Command aliases
e# L Loop open-close index pairs ([] by default, not set up here)
e# T Instruction pointer (0 by defualt, not set)
q:I e# Read the input and store it in I.
ea e# Read the command-line args.
):C; e# Remove the last, store it in C, and delete.
:O e# Store the rest in O.
]; e# And clear everything off the stack.
e# Now we translate the code into numbers for each command:
e# -1 no-op
e# 0 >
e# 1 <
e# 2 +
e# 3 -
e# 4 .
e# 5 ,
e# 6 [
e# 7 ]
{ e# Do:
O{_,C<=}# e# Find the index of the alias such that C starts with (or -1 if C doesn't start with a valid command)
_ e# Copy it
) e# Increment it
O0=,( e# Get the alias length-1
e&) e# Logical AND and increment the result
C> e# Slice that many characters from the beginning of C
:C e# Store the newly sliced code back into C
}g e# While (C is not empty)
]:C e# Save the resulting list of commands back into C
e# Next, we find the pairs of matching loops
,{ e# For i in C
_C= e# Copy i and push C[i]
6-We> e# max(-1, i-6)
"M+:M M(\:M;a+aL+:L "S/=~ e# Split this string on spaces, and eval result[max(-1, i-6)]
e# For 0 ([), push the index to M (M is a temporarily used list)
e# For 1 (]), pop and index from M, pair it with the current index, and add that pair to L
e# For -1, do nothing
}/ e# End for
]; e# Clear the stack
e# The final step is to interpret
0a3e4* e# Create a tape containing 30000 0's
{ e# Do
TC= e# Get the current instruction
e# This string contains the commands, space separated, so they can be easily evaled
"(+ 1m> ))+ )(+ _W=co );I0ae|(\:I;i+ _W={L{1=T=}=0=:T;}| _W={L{0=T=}=1=:T;}& "
S/=~ e# Split by spaces, get result[command], and eval
T):T e# Increment the instruction pointer
C,< e# Check if it's less than the length of the C
}g e# While TOS is truthy
; e# Delete the tape so it doesn't get implicitly printed
```
] |
[Question]
[
# Because we haven't had enough of these, let's do another weird language!
* `+` increments the accumulator
* `-` decrements the accumulator
* `#` outputs the character with the codepoint of the accumulator modulo 127, and then resets the accumulator
* `$` is like `#` but it doesn't reset the accumulator
* `%` reads a single character of input and then set the accumulator to that. If it is EOF, exit the program
* `!` sets the accumulator to 0
At the end of the program, if the accumulator is 0, exit, otherwise, start again from the beginning, preserving the accumulator state.
Note that this language has no implementation so it is defined by this post.
# Challenge
Given a valid `+-#$%!` program (containing only those characters) and the program input (containing only printable ASCII characters), return its output.
# Examples
```
program, input -> output // comments
%$, hello -> hello // CAT program
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#++++++++++++++++++++++++++++++++#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#, -> Hi there
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++$+++++++++++++++++++++++++++++++++$++++++++++++++++++++++++++++++++++++++++++++++++++++++$++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++$+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++$++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++$+++++++++++++$++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++$!, -> Hi there
```
[Answer]
## [><>](https://esolangs.org/wiki/Fish), 112 bytes
You may be thinking "Is ><> really the best language to write an interpreter in?", to which my answer is "no, but let's try anyway!"
```
i:}b(?v
0(?;v0<o}\.24;!?:}\ /}~51. /}1-32./}1+32./}~i:
6*bb< o:}\?="#": \?(b:\?="!":\?="-":\?="+":\?="%":$%+
```
[Try it online](https://tio.run/##S8sszvj/P9OqNknDvozLQMPeuszAJr82Rs/IxFrR3qo2RgEI9GvrTA31gJShrrGRHpDSBlN1mVZcZlpJSTYK@UCF9rZKykpWCgox9hpJViCeohKY0oVQ2hBKVclKRVX7/39VFS47GzuF4vLMXDChCAA "><> – Try It Online"), or at the [fish pond](https://fishlanguage.com/playground)!
Takes input from STDIN: first the +-#$%! code, then optionally a newline and any extra input.
This could do with some explanation.
* The first loop is `i:}b(?v`. This reads from STDIN to the stack until it hits a character less than `b = 11`, which means either a newline (charcode 10) or EOF (charcode -1).
* Once that's done, the fish swims down…
```
v
v0<
<
```
…into the main loop, adding a `0` to the stack to use as the accumulator.
* First, the fish sees `bb*6+%` — this computes `127 = 11*11+6` and takes the modulus of the accumulator. Then `$` brings forward the first character from the stack.
* Now, we get to the bulk of the code — reading the character. There are seven branches in this bit of the code. (I think I've tetrissed the branches as much as I can, but there might be more blank space that can be removed here.)
```
0(?; /}~i:
\?="%":
```
Note that the fish starts from the bottom right, moving left, and wraps when it hits the side of the code. If the character is a literal `"%"`, we shift it to the back of the stack for safekeeping, delete the accumulator, replace it with the first character in STDIN, check if that's EOF (that is, if its charcode is negative), and end the program if so. We then hit the start of the main loop again.
```
/}1-32./}1+32.
\?="-":\?="+":
```
If the character is `"+"`, we put it on the back of the stack again, add 1 to the accumulator, and jump to the start of the main loop. The `"-"` case is similar.
```
/}~51.
\?="!":
```
If the character is `"!"`, delete the accumulator and jump to just before the start of the main loop, where we first created the accumulator by adding a `0` to the stack.
```
.24;!?:}\
\?(b:
```
If the character is EOF or newline, check if the accumulator is 0, and terminate the program if so; otherwise, jump back to the start of the main loop. We kept all the used characters on the stack, so now we're back at the start of the program anyway.
```
o}\
\?="#":
```
If the character is `"#"`, output the accumulator as a character. We're then conveniently back just before the main loop, where we created the accumulator with a `0`.
```
o:}
```
If we've reached this branch, the character can only be `"$"`, since the stack only contained the characters `+-#$%!` and EOF or linefeed. Therefore we print a copy of the accumulator, and we're back at the start of the main loop.
[Answer]
# [Python 2](https://docs.python.org/2/), 186 bytes
```
p,i=input()
a=0;f=1;r=''
while a^f:
f=0
for c in p:
if c in'#$':r+=chr(a%127);a=a*(c>'#')
if'%'==c:
if i:a=ord(i[0]);i=i[1:]
else:a=0;break
a+=(c=='+')-(c>'+')-a*(c<'"')
print r
```
[Try it online!](https://tio.run/nexus/python2#HY3BCsIwEETPzVcE27KJrdB6ERLXHykVYkzoYmlDrPj5NfGyszAzb/bQEtISPpuQzGCnPfY6IgD7TjQ7bu5eMe6xS2eN3HJaeFCsIP//oaxAxQbtFIWp@/NFaoPmKOwNSpA5BjUg2tTgqULK4BqfgoZulDoND70ak@Xmt1N5/RGdebHCNCgsIjQgT5mVNVOvcEjUEGnZeNx3qCtoYXLzvMIP "Python 2 – TIO Nexus")
[Answer]
# Pyth, 89 bytes
```
KwJ1WJ=J0FHKIqH\+=+J1)IqH\-=-J1)IqH\#pC%J127=J0)IqH\$pC%J127)IqH\!=J0)IqH\%IqzkB=JChz=ztz
```
Takes the input in the first line and the output in the second. It's just a simple for loop over the input with some ifs. I'm sure it could be much shorter, but i don't care enough right now.
[Try it!](https://pyth.herokuapp.com/?code=KwJ1WJ%3DJ0FHKIqH%5C%2B%3D%2BJ1%29IqH%5C-%3D-J1%29IqH%5C%23pC%25J127%3DJ0%29IqH%5C%24pC%25J127%29IqH%5C%21%3DJ0%29IqH%5C%25IqzkB%3DJChz%3Dztz&input=abc%0A%25%2B%2B%23%25%23%25--%23%25%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%23&test_suite=1&test_suite_input=hello%0A%25%24%0A%0A%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%23%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2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B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%24%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%24%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%24%21%0Aabc%0A%25%2B%2B%23%25%23%25--%23%25%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%23&debug=0&input_size=2)
### Python code it compiles to:
```
assign('z',input())
assign("K",input())
assign("J",1)
while J:
assign('J',0)
for H in num_to_range(K):
if equal(H,"+"):
assign('J',plus(J,1))
if equal(H,"-"):
assign('J',minus(J,1))
if equal(H,"#"):
Pprint(Pchr(mod(J,127)))
assign('J',0)
if equal(H,"$"):
Pprint(Pchr(mod(J,127)))
if equal(H,"!"):
assign('J',0)
if equal(H,"%"):
if equal(z,k):
break
assign('J',Pchr(head(z)))
assign('z',tail(z))
```
[Answer]
# Bash/gcc, ~~184~~ 172
This first reads the program on stdin, then after an EOF, reads program input. Looks valid to me.
```
gcc -x c -<<<"a;main(){do{$(sed -e's/#/$!/g' -e's/./&;/g' -e's/[+-]/a&&/g' -es/!/a=0/g -e's,%,a=getchar();if(a==-1)exit(0),g' -e's/\$/putchar(a%127)/g')}while(a);}"
./a.out
```
If you didn't already notice, I'm just constructing, compiling and running a C program on the fly. Note: your compiler might complain loudly about the horrible code generated, but I believe we were allowed extra output on stderr.
Before I began, I expected this to be shorter than it turned out; I'm really unhappy with the `%` handling. Suggestions welcome :)
[Answer]
# Python 3, 121 bytes
```
x,i=0,int
for c in input():
if c in'$#':print(end=chr(x%128))
x+=i(c=='+')-i(c=='-')-i(c in'!#')*x
if'%'==c:x=input()
```
[Answer]
# Java 8, ~~225~~ ~~194~~ ~~187~~ 183 bytes
```
s->d(s,0);void d(char[]s,int n){for(int c:s){n+=c>44?-1:c/43;System.out.print(c>34&c<37?(char)(n%127):c==37?new java.util.Scanner(System.in).nextLine():"");n=c<36?0:n;}if(n>0)d(s,n);}
```
-15 bytes by converting Java 7 to Java 8.
-14 bytes thanks to *@Zacharý* by replacing String input with char-array input.
-2 bytes by some small fixes
-11 bytes thanks to *@ceilingcat*
**Explanation:**
[Try it here: first test case with user-input.](https://tio.run/##LZBBb8IwDIXv/AoLjSnWaFZGNaR2LZp23bj0iDhkbhjpiouSwIZQf3uXMi6ObT09f3m1OqmoPWiuq@@eGuUcfCjDlxGAYa/tVpGG1TACnFpTAQnaKbvegMMsbLtRKCtgyKF3UVEJN40xuyqrm9JNgxMwXratFUNLqcMLP@RUJMkymqX0mMyz8uy83sv26OXBBpWgYp7c08t8sbz6oODJ7GmBKeV52LH@gTqwy6M3jSxJMWsrbiaGUbL@9e@GtcB0PMaM82D1vIxTzjqzFVzEOLAyZl0PcDh@NobAeeXDc6XfhxRE6QPKV/iswv8IhrNDPiIckCTUOt5I374Fvldr1VngLZSu3@mmafvJ3R8)
[Try it here: other two test-cases.](https://tio.run/##3VNBT8IwFL7zK54bmjZABVkk2dyI8apcOBoPteu0uL2RtqCE7LfPbnIyekMg9tD2vbx@7/u@9C34mg/KpcRF@laLnBsDD1zhtgOg0EqdcSFh1oQA61KlIIh45frxCQyNXLbquG0GCDHUZpCkxPSHNGor012l6TskQLrNSk2aqwgN3WIvFkkQTAejUFwG42i@MVYWrFxZttSuiohkHFyIm/Fk2uJQguejqwkNRRy7HMp3WDjubGVVzuaCI0pNdiAKKUP5Ye8VSkJDz6MRxg7qejoMMapURjAZ0oYr0qiqAZar51wJMJZbd7TsC@cCmVtH5cWJ5fTLgsYbKJzYpn8TkNYFgIIhE8Tr7Wn5vUMt/3SoHKOp/7/kHFyYx2x558bzVmu@IXQ3Dd@HOf@rOenuoWKfz44AeoI9f2l@BCrds58@aNWp6k8)
```
s-> // Method (1) with char-array parameter and no return-type
d(s,0); // Call another method with the char-array and 0
void d(char[]s,int n){ // Method (2) with character-array and integer parameters
for(int c:s){ // Loop over the characters of the input
n+=c>44? // If the character is '-':
-1 // Decrease `n` by 1
:c/43; // Else if the character is '+':
// Increase `n` by 1
// Else:
// Leave `n` the same (by increasing with 0)
System.out.print(c>34&c<37? // If the character is '#' or '$':
(char)(n%127) // Print the `n modulo 127` as character
:c==37? // Else-if the character is '%':
new java.util.Scanner(System.in).nextLine()
// Read & output the user-input
: // Else:
""); // Output nothing
n=c<36? // Then, if the character is '#' or '!':
0 // Reset `n` to 0
: // Else:
n;} // Leave `n` the same
if(n>0) // If `n` is now larger than 0:
d(s,n);} // Do a recursive-call while leaving `n` as is
```
[Answer]
# JavaScript (ES6), 197 bytes
```
(s,i="")=>(i=[...i].map(c=>c.charCodeAt()),a=0,o="",u=_=>{[...s].map(c=>eval(["a++","a--",p="o+=a?String.fromCharCode(a%127):''",r="a=0",p+","+r,"a=i.shift()"]["+-$!#%".indexOf(c)])),a&&u()},u(),o)
```
## Cleaned up
```
(s, i="") => (
i = [...i].map(c=>c.charCodeAt()),
a = 0,
o = "",
u = _ => {
[...s].map(c => eval(
["a++", "a--", p="o+=a?String.fromCharCode(a%127):''", r="a=0", p+","+r, "a=i.shift()"][ "+-$!#%".indexOf(c) ]
)),
a && u()
},
u(),
o
)
```
## Test Snippet
```
f=
(s,i="")=>(i=[...i].map(c=>c.charCodeAt()),a=0,o="",u=_=>{[...s].map(c=>eval(["a++","a--",p="o+=a?String.fromCharCode(a%127):''",r="a=0",p+","+r,"a=i.shift()"]["+-$!#%".indexOf(c)])),a&&u()},u(),o)
```
```
<style>*{font-family:Consolas;}</style>
Code:
<textarea id="C" rows="2" cols="50"></textarea><br>
Input: <input id="I"><br>
<button onclick="O.innerHTML=f(C.value, I.value)">Run</button><br>
<pre id="O"></pre>
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~143~~ ~~149~~ 146 bytes
First line of STDIN is the code, the rest is the input.
Whoops, `getc` doesn't actually exist directly.
```
a=0
e=i=gets
i.chars{|c|eval Hash["+a+=1 -a-=1 #P;a=0 $P %a=$<.getc||exit !a=0".gsub(?P,"$><<(a%127).chr").scan /(\S)(\S+)/][c]||"";e=a}while e!=0
```
[Try it online!](https://tio.run/nexus/ruby#DYyxDoIwFEV3vuJZIUJQBBcHqK6OJI7I8KgvtAlCQgtorN@OHe5ZTs5dkaceccVbMtpTiZA46q8Vlmbs4IZaVizGmGdwwIPjtsxdAX4JAXK/SFwmrKW3MrBxgiWtnprwWu6ZfymKEIPsdI7c68iiRAvs4Rg@7pFbHB3rStTWMpYTx98iVUdAG56ua@B7i0QDSkM3zHSFBpsPPId@Z0BOo4EX/QE "Ruby – TIO Nexus")
[Answer]
# [shortC](//github.com/aaronryank/shortC), 95 bytes
```
c,a;AO;~c;c=G)c==43?a++:c==45?a--:c==35?Pa%127),a=0:c==36?Pa%127:c==37?!~(a=G)?T0:0:c==33?a=0:0;
```
[Answer]
# C, 170 bytes
```
main(int c,char **v){for(int A=0,i=0;c=v[1][i++];A+1)A=c==0?i=0,A?A:-1:c=='+'?A+1:c=='-'?A-1:c=='!'?0:c=='$'?putchar(A%127),A:c=='#'?putchar(A%127),0:c=='%'?getchar():A;}
```
Ungolfed
```
main(int c,char **v){
for(int A=0,i=0;c=v[1][i++];A+1)
A=
c==0 ? i=0, A?A:-1: // EOF == -1
c=='+' ? A+1:
c=='-' ? A-1:
c=='!' ? 0:
c=='$' ? putchar(A%127),A:
c=='#' ? putchar(A%127),0:
c=='%' ? getchar():
A;
}
```
6 bytes can be saved by replacing +-!$#% with decimal equivalents, but that would obfuscate the code. 9 bytes can be saved when using a K&R compatible compiler by moving the declaration *int A=0,i=0* to the start of main, *A,i,main(...* However I only posted code that I could test.
Corrected in response to comments by Dave. Also switched to using the value of EOF (-1) instead of "EOF".
[Answer]
# C, ~~145~~ 139 bytes
```
c,a;f(){for(;~c;c=getchar())c==43?a++:c==45?a--:c==35?putchar(a%127),a=0:c==36?putchar(a%127):c==37?!~(a=getchar())?exit(0):0:c==33?a=0:0;}
```
That was easy. I definitely recommend compiling with all warnings off (`-w`). Will golf.
[Answer]
# [OCaml](http://www.ocaml.org/), 202 bytes
```
let c c=print_char(char_of_int(c mod 127))
let rec f a p=match Array.fold_left(fun a->function '+'->a+1|'-'->a-1|'#'->c
a;0|'$'->c a;a|'%'->Scanf.scanf"%c"int_of_char|'!'->0|_->a)a p with
0->()|a->f a p
```
Takes the program as an array of char because OCaml does not have `String.fold*`
[Try it online!](https://tio.run/##3ZPBaoQwEIbP@hSz6mKyori99LAo9Bn2WEoIWbMGNFk0pRR8dzvjHktvsi7NYfxx/sz/DahTsu/muWs8KFDVbTDWC9XKgVERTgt8wRT07gLHl1fOQ7IOjQINEm5VL71q4W0Y5HehXXcRXaM9058WZF7jQ3njLKRZmtcyO05pTiJHEaNQoTyVU5qQBHmSU7pHeVbS6mKkGu1VRECIQThTusN@OQmcwTEdvoxvwzKvGZ8ojoiWVRiHKgxIjR43ugrvhCRGGKkR3HmNNWg9L46ia@zVtzByWOgN5DWMxbv54GFg7H2YputYS2C/5nIgFztgO8pWOnH2qBM/D8oWofH/Wufhi0VwwN9kxS8/WcGx5rUNhj5h5h/hG6AkuyicfwA "OCaml – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 112 bytes
```
a←0
f←⎕UCS 127|⊢
{⍎¨('∆'(≠⊆⊢)'a+←1∆a-←1∆⍞←f a⋄a←0∆⍞←f a∆a←⎕UCS{×≢⍵:⊃⍵⋄⎕UCS 0}i⋄i←1↓i∆a←0')['+-#$%!'⍳⍞]}⍣{a=0}i←⍞
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P/FR2wQDrjQg@ahvaqhzsIKhkXnNo65FXNWPevsOrdBQf9TRpq7xqHPBo642oLCmeqI2UK0hUDRRF8p41DsPyEpTSHzU3QI2DkUMqBBuePXh6Y86Fz3q3Wr1qKsZSAE1QG01qM0EcjLBJrZNzoTqMlDXjFbX1lVWUVVUf9S7GWhobO2j3sXVibYg9UBTe@f9/8@lTSWgrE0voDx4nDIQlioPL@/Q3WMA "APL (Dyalog Unicode) – Try It Online")
maps each instruction to a string, then executes it.
Inputs are taken in reverse, output is given in the debug window.
] |
[Question]
[
In the video game Minecraft, you can obtain beacons and put them on pyramid-like structures to give you special effects, such as speed or jump boost.
Your task is to, given an effect, construct the beacon pyramid required for it.
There are multiple sizes of beacon pyramids, required for different effects. The largest has a size `9` base, and the smallest has a size `3` base.
These are the effects you can get, and the required pyramid for them (as specified by the official Minecraft wiki:
```
3:
Speed I
Haste I
5:
Resistance I
Jump Boost I
7:
Strength I
9:
Regeneration I
Resistance II
Jump Boost II
Speed II
Haste II
Strength II
```
Beacons are constructed with the base at the bottom, then it goes up, decreasing the size by 2. Once we hit 1, there should be a beacon `+` at the top.
A beacon is defined as a `+`, but it needs a supporting pyramid to work.
You may assume the input is valid (ie, it is one of the effects specified here), and, optionally, you may assume the input is all lowercase. The `#` character should be used in the pyramid, and `+` as the beacon.
## Examples:
```
Haste I
+
###
Resistance I
+
###
#####
Strength I
+
###
#####
#######
Regeneration I
+
###
#####
#######
#########
Speed II
+
###
#####
#######
#########
```
You must also take multiple effects as beacon pyramids can share blocks - however, one beacon cannot do more than one effect. You must use minimal blocks.
When taking multiple effects, you may use any reasonable input format such as a list, newline separated, etc. Additionally, you may take a singleton list for single beacons if you are using lists.
For these examples, I only list one possible solution, but there are multiple acceptable solutions.
```
Speed I, Haste II
++
####
#####
#######
#########
(another acceptable solution is the following,
these are both valid as they use the same amount of blocks)
+
###
#####
#######+
##########
(the following is not valid for the same input; it doesn't use minimal blocks)
+
###
##### +
####### ###
#########
Strength I, Strength I
++
####
######
########
```
(don't output things in brackets, if that isn't obvious enough)
[Answer]
# [Python 2](https://docs.python.org/2/), 216 195 bytes
```
def b(e):s=sorted(63372>>len(_)*2-14&3for _ in e)[::-1];f=s[0]+2;r=range(f);print"\n".join(reduce(lambda p,n:[p[i]+"+# "[cmp(i,f-n-2)]for i in r],s[1:],[" "*(f-i-1)+"+#"[i>0]*(2*i+1)for i in r]))
```
[Try it online!](https://tio.run/nexus/python2#ZY9Bb8IwDIXv/RVWJk1JmyJapk0qKoedxo7bbqFChbrgqaRRkoqfzwhio9tu9rPf9@xTgy1sOIrCla63Hhv@OJs95YtFh5qvRZyn2cP9rO0trIE0oFBFkWbVvC2dmlZJPrelrfUOeSvmxpL2bKXZ5LMnzS02wxZ5Vx82TQ1G6kIZRVXCkjtganswnGSb6jQXVeBT4NtKOpUVlVQMWMzblNJMBAdTtJhWMc9jSjIx2hfidNxTh/BhByyis1yCrY9r0mbwXERwuQooOr9JE2c68pxJYOJ7dHqpnUdYRm/oyPlab0Pz7i3qnd9f9B1qtLWnXoeJQWxg@VNIuAL@KxLGTAmvw8HAc987H7pbRNgbZ/z2/TEG5/WEW/SYtvwC "Python 2 – TIO Nexus")
The function for printing the string with the pyramid structure is `b`, which is called with a list of the effects as its single argument.
This turned out longer than I expected, but I was at least happy that I was able to find the beacon size based on black magic.
**Edit:** was able to reduce byte count significantly by combining the reduce function into a `lambda` thanks to Python 2's `cmp` function.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 75 71 60 54 48 bytes
```
A⟦⟧βWS⊞βI§14034244⁻Lι⁷FUPsorted⟦β⟧«G→→↖⁺ι¹#¦+Mι↙
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9noWP5i97NH/5uU3v92x/v2fzo655IObKQ8sNTQyMTYxMTB417n6/Z825nY8agfLL3u/Z@n7PhuL8opLUFKDOc5uAeg@tfr9n@aO2SWA07VHjrnM7D@1UPrRM@/2etUB9bTP//w8uSE1NUfDk8kgsLkkF0kGpxZnFJYl5ySCOV2lugYJTfn5xCZATXFKUmpdekgFWlJ6al1qUWJKZn4emB1UTUBfEfLgFyOZ4cgEA "Charcoal – Try It Online")
The Python answer is also mine, but I wanted to try my first golf submission in Charcoal!
I also wanted to make sure I can hold down that bounty ;)
```
A⟦⟧β assign an empty list to β
WS while the next string input ι is truthy: (aka while the input is not an empty line)
⊞βI§14034244⁻Lι⁷ push level for ι into β (explained below)
FUPsorted⟦β⟧« for each level ι in the sorted version of β:
G→→↖⁺ι¹# draw a triangle of "#"s with side lengths ι + 1
¦+ draw a "+" (already on top vertex)
Mι↙ move down and left by ι cells (preparation for next level)
implicit end of for
```
All of the beacon names of the same length share a beacon level. As such, we can determine the beacon level of an effect from mapping the length (minus 7 to base it at zero) to the numbers in the string "14034244" (there is a 0 for clarity because length 9 does not correspond to an effect). This same idea is used in my Python answer, but with bit shifting to produce the numbers 0-3.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 68 bytes
```
FṀ‘
0;Ṗ
|Ç€|Ḋ€Ç|
⁽lƑb4‘ị@L€ṢµI‘ż@IṚṭṀṭ0Fs2+\µḅÑ‘Ṭ;0sѵ+ÇÐLị“#+ ”Y;”#
```
[Try it online!](https://tio.run/##tVRNb9NAEL3nV4zSA4mSVHEFpx5aASoEFVVquSDgsLEn9oK9a@2um0aKUEBCleBCLgghuHAux0qNgEst@B/OHwmzdvpBUrWkEntYr9e7b957M@PnGIa9yWQjGw3Gg4@l5mo2@lDqp/vj1wf97OgtPdL9fmn86mf4e9i@SUey7@/WN2k7G309PmzRxq8f661s9CkbfSMMmpsbeqX29PgwO3qTDu2F0cFqU6fD48Naup@@3ySA8eDzUg3Ggy@PV2laOg0P1xkNuIcGIrbHoySCALkfGGg0wGVhiB6YLnex0HVNeCUNMwgqB5YCodKRCra2q3NRZn1bPNbWNnS5CcCTXdEIsWOgnq@LuZFzqAMTHnARJwYqO2yXwr@8Be2eQQ2@DDtc@GACrpfhrhQ3jF2LF8ANcRXQxvwM3ekkygSJqv7n5F4Ev5gnPqW3SKuGitMEN2BKg80BA6fhUOrj2GqWHXAcwBAjFOZMveqBkcCjWMldrJbOkHORC/DQUpHhd5hFtR7mJp8HBLjMsisUxlJzw6XQVkdNX0al8ogCn2RzKsxb@5vJ7JhP2DwNo5jQ5GtExUWWKXQNE34SMgVtLhgZGTGj@F5uAqlHKnuZd4C2FqdDy0ehl7i2I6TtlStYnY6iemb8vsAVQl3RdVjKV44uWkHHzMV8p6mL9gkwjFFBSIVf@ucMz9euZWH9YObEd4TiAzO5frSNqKHNvGV4yHokn3keOJaK/axkl/h4RAiZCjmqterkSXknRvKnVa5D@T7T9GfJl9uouSa/3en7gySK4baU2hTvO0ah8AlqetpHgYpZb@bvzwEUCEXc84FnkFvlZ38A "Jelly – Try It Online")
I think the reason this is longer than the Charcoal answer (even though I was able to do my 'black magic' in 10 bytes) is because Charcoal was built for two-dimensional drawing. I ended depending on a 2D cellular automaton to find the positions of `#`s given the positions of `+`s to create triangles.
**How it Works** (main link split for readability)
```
FṀ‘
0;Ṗ
|Ç€|Ḋ€Ç|
⁽lƑb4‘ị@L€ṢµI‘ż@IṚṭṀṭ0Fs2+\µḅÑ‘Ṭ;0sѵ+ÇÐLị“#+ ”Y;”# - Main link, input is list of strings
⁽lƑb4‘ị@L€Ṣ - list of strings to list of heights (1,2,3,4)
⁽lƑ - the number 28147
b4‘ - base 4 and incremented: [2, 3, 4, 2, 4, 4, 1, 4]
L€ - lengths of each input string
ị@ - index into the list to get a list of heights
Ṣµ - sort and store for the next link:
I‘ż@IṚṭṀṭ0Fs2+\ - get list of coordinates for `+`s
I‘ż@I - [0,1] between each element. Add [1,1]*n between each pair of elements with difference n
Ṛ - Reverse
ṭṀṭ0 - prepend [0,maximum]
Fs2 - format the array as a list of coordinate pairs
+\ - cumulative sum
ḅÑ‘Ṭ;0sÑ - convert to binary rectangular matrix:
ḅÑ‘ - change each coordinate pair (y,x) to y*width+x (Ñ is the width)
Ṭ - boolean array with 1s at the above indices
;0 - append a zero for formatting reasons
sÑ - split into rows of the right width
µ+ÇÐL - add locations of `#`s: the matrix now has 2s at future `+`s, 1s at `#`s, and `0`s at spaces
ÇÐL - repeatedly apply a step of the cellular automoton: 1s at `#`s and `+`s, and 0s at space
µ+ - add this to the matrix of `+`s which has 1s at `+`s.
ị“#+ ”Y;”# - format into a string
ị“#+ ” - index into the string "#+ ".
Y - join by newlines.
;”# - append a `#` character to finish up the formatting.
```
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/60042/edit).
Closed 8 years ago.
[Improve this question](/posts/60042/edit)
# Intro
In `Objective-C` (a superset of `C` and an object-oriented language), I can create an object called a `UIWebView`. There is a method for this object called `loadHTMLString:` in which I can load actual `HTML` into the `UIWebView` object itself. I can also inject Javascript into it using the method `stringByEvaluatingJavaScriptFromString:`.
If I were to write a program that created a UIWebView, loaded in my string (which happens to be HTML "code") and then injected a second string (which is Javascript code) I would be using 3 languages at once, in a functional program. (Not sure that `html` is really a programming language... so that's debatable haha)
You can also do things like embed `Python` into `C` (and other languages): <https://docs.python.org/2/extending/embedding.html>
---
This isn't too difficult, with any language you can use other languages inside it if you try hard enough.
---
# Challenge
The challenge here is to see how many languages you can cram into 1 functioning program in under 500 bytes. <https://mothereff.in/byte-counter>
The program can do literally any task, it just has to work. The languages all have to work together, so you can't have 2 languages running one task, and 3 other languages running a completely different task. So whatever your "task" may be (you decide), there should only be 1 task, and all `n` languages should work on just that 1 task in your 1 program.
---
# Objective
Your score is the number of languages you used. Whoever uses the most languages at once gets a cookie.
Since this is a popularity contest I will be accepting the answer with the most up-votes.
---
# Q&A
•Ray **asked**, "Just to clarify, you're looking for a program that uses multiple languages to accomplish different parts of a single task, as opposed to a polyglot that is a valid program in multiple languages?"
***Answer**, "Yes".*
•DanielM. **asked**, "does Regex count?" ***Answer**, "Yes, I personally WOULD count it. Again, this is a popularity contest, so it really is up to the voters to determine. HTML is not considered a programming language by some, but it has been successfully used in an answer already that has seen quite a few upvotes. (Also, Stack-overflow does define Regex as a programming language if that helps you make your decision to use it or not: <https://stackoverflow.com/tags/regex/info>)*
[Answer]
# make, sh, awk, sed, regex, yacc, lex, C; 8 languages.
## Including the input and output languages: brainfuck and D; 10 languages
This is a brainfuck to D compiler. It takes the brainfuck program over standard input and prints the D code to standard output.
Make uses awk, sed, and sh to generate a yacc program, which in conjunction
with a lex program is used to generate a C program that takes a brainfuck
program as input and outputs an equivalent D program. I tried to only use languages in ways that were actually useful, instead of just throwing in a bunch of no-ops. The lex/yacc/C combination is fairly standard for simple compilers, the make/sh combination is useful for building, and the awk/sed line was the only way I could get the whole thing under 500 bytes. (It's at 498 bytes currently.)
## Code
```
define L
%%
[][+-<>.,] return *yytext;
. ;
%%
endef
define Y
%{
#include <stdio.h>
%}
%left '+' '-' '.' ',' '>' '<' '[' ']'
%%
q: q q {}
+ p[i]++
- p[i]--
> i++
< i--
, p[i]=getchar()
. putchar(p[i])
[ while(p[i]){
] }
%%
yywrap(){}yyerror(){}main(){puts("import std.stdio;int p[30000];int i;void main(){");yyparse();puts("}");}
endef
export L
export Y
a:
@echo "$$L">y;lex y;echo "$$Y"|awk '/^[+-^]/{printf("q: X%sX {puts(\"%s;\");}\n",$$1,$$2)} /^[^+-^]/'|sed "y/X/'/">y;yacc y;cc *.c;./a.out;:
```
## Example of use
```
$ cat helloworld.bf
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
$ make < helloworld.bf > tmp.d
y: warning: 8 shift/reduce conflicts [-Wconflicts-sr]
$ dmd tmp.d && ./tmp
Hello World!
```
[Answer]
# HTML, CSS, PHP, JavaScript, CoffeeScript, RegEx, sed, bash; 8 languages
Displays colors of the rainbow.
*(Only 396 bytes)* will try to add more languages
HTML + CSS is turning complete and counts as a valid language on PPCG. I've been [told](http://chat.stackexchange.com/transcript/message/24575556#24575556) CoffeeScript is different enough as JavaScript to be counted as a separate language. And RegEx has been specifically allowed also.
PHP allows for addition of many languages especially with `exec` and `shell_exec` functions.
Golfed to fit inside byte limit (ES6)
```
<html><style><?php foreach(explode(" ",exec('sed "s/;/ /g"<<<"red;orange;yellow;green;blue;violet"')) as $color){echo "#{$color} { color: $color }\n"}?></style><script>b="red orange yellow green blue violet".split(/ /).map(c=>`<p id="${c}">${c}</p>`)</script><script type="text/coffeescript">document.documentElement.innerHTML+=b.join "\n"</script><script src="http://v.ht/u31R"></script></html>
```
Uses:
* PHP to generate CSS
* PHP, uses exec to run bash
* sed to split color items for bash
* CSS to specify text colors
* JavaScript to generate elements
* RegEx to split color items for JS
* CoffeScript to print elements
* HTML as a wrapper / output
---
Faster & Ungolfed (All modern browsers)
```
<html>
<style>
/* CSS */
<?php// Loop through all colors
foreach(explode(" ",
exec('sed "s/;/ /g"<<<"red;orange;yellow;green;blue;violet"')) as $color) {
// Print it out, add it to the CSS
echo"#{$color} { color: $color }\n"}
?>
</style>
<script>
// Create an element for each color, store as variable
window.colors = "red orange yellow green blue violet".split(/ /).map(function(color) {
return "<p id=\"" + color + "\">" + color + "</p>"
});
</script>
<script type="text/coffeescript">
document.documentElement.innerHTML += window.colors.join "\n"
</script>
<!-- CoffeScript Link -->
<script src="https://raw.githubusercontent.com/jashkenas/coffeescript/master/extras/coffee-script.js"></script>
</html>
```
] |
[Question]
[
Today your goal is to invent URL compression. You must write two programs: a compressor and a decompressor.
* The compressor will be called with **one** URL on stdin and its output will be read on stdout.
* The decompressor will be called with the output of the compressor on stdin, and must produce the **exact** URL passed into the compressor to stdout.
* The sum of the size in bytes of the compressor and decompressor source may be at most 1024 bytes.
* Your answer must come with command line instructions to run your two programs. You're not allowed to pass in information of any kind through command line arguments - they should merely be to run the program.
[The standard loopholes are not allowed.](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) Additionally, your program is not allowed to keep and use any state of any kind between executions, not in files, environment variables, etc. Lastly, you may not use any built-in data compression routines if your language has them.
### Scoring
I have taken all URLs found in the [StackExchange dump](https://archive.org/details/stackexchange) of PPCG and collected them in [one file](https://gist.githubusercontent.com/orlp/fd3411259469ade4c65d/raw/bb6b088c18c444d28729abc870d6076ca594a6de/urls.txt), one URL per line. Your score will be the sum of the size of all compressed URLs in that file. **Lowest score wins.**
---
It is not guaranteed that your program is called with a valid URL. Your program must work for every input found in [the test file](https://gist.githubusercontent.com/orlp/fd3411259469ade4c65d/raw/bb6b088c18c444d28729abc870d6076ca594a6de/urls.txt), but doesn't have to work for any other input.
**Your answer only has to work for the given URLs, and only has to optimize for those.**
[Answer]
# CJam ~~308954~~ 268306 bytes
### Compressor (511 bytes)
```
0000000: 22 2f 25 2d 30 31 32 33 35 61 65 0a 2e 34 37 38 "/%-01235ae..478
0000010: 39 62 63 66 67 69 6c 6d 70 73 74 75 0a 36 41 42 9bcfgilmpstu.6AB
0000020: 43 44 45 46 49 4a 4b 4c 4d 53 58 5f 64 68 6a 6b CDEFIJKLMSX_dhjk
0000030: 6e 6f 72 76 77 78 79 7a 97 a0 a5 a6 22 0a 4e 2f norvwxyz....".N/
0000040: 5f 3a 2b 32 35 36 63 2c 5e 61 2b 3a 47 3b 22 63 _:+256c,^a+:G;"c
0000050: 6f 7f 6d 73 74 6e 67 6f 6c 6f 72 64 65 7f 85 83 o.mstngolorde...
0000060: 66 67 87 86 88 81 61 8a 63 8b 6b 61 82 80 2f 2e fg....a.c.ka../.
0000070: 8e 65 8f 8d 90 68 91 63 92 78 93 65 94 8c 95 65 .e...h.c.x.e...e
0000080: 72 6f 6e 84 67 77 69 9a 6b 9b 69 74 68 96 61 69 ron.gwi.k.ith.ai
0000090: 98 69 6e 65 74 6e a1 65 6e 64 69 25 32 a5 30 a6 .inetn.endi%2.0.
00000a0: a6 77 77 a8 77 6c 65 72 65 2e 99 ac 2f ad 9c 9f .ww.wlere.../...
00000b0: 73 81 af 89 2e b1 9e b1 96 65 a4 70 b4 9c b5 72 s........e.p...r
00000c0: 69 a5 42 b7 70 b9 74 62 8f b6 61 bc ae 61 72 b2 i.B.p.tb..a..ar.
00000d0: 2f 61 74 6c 6f 61 6d 74 6d 68 c3 c4 6c 65 b0 75 /atloamtmh..le.u
00000e0: c6 71 c7 b3 c8 63 ba 73 ca 88 cb 72 6f 61 6e 69 .q...c.s...roani
00000f0: 9d cf 75 d0 bb 67 d1 65 73 75 73 d4 97 b3 d5 6a ..u..g.esus....j
0000100: c2 63 d7 c1 77 d9 8f 70 68 db bb 70 dc 73 75 74 .c..w..ph..p.sut
0000110: de a4 df 61 e0 98 90 85 e2 69 e3 d3 83 e5 8d a9 ...a.....i......
0000120: 2e 61 dd 76 97 6f e9 8c ea eb 66 ec da 6a 73 ee .a.v.o....f..js.
0000130: 66 ef 69 f0 64 f1 64 f2 aa 70 cd a2 2f 2e f5 f3 f.i.d.d..p../...
0000140: f6 e1 f6 e6 73 f9 ae 61 6c 75 6e bf 34 70 79 fe ....s..alun.4py.
0000150: 9d 63 74 fc 00 b8 b8 75 72 03 8f a5 43 64 6f 06 .ct....ur...Cdo.
0000160: 63 d6 73 ed c8 a7 a7 b8 a6 a6 a5 69 73 72 c2 75 c.s........isr.u
0000170: 74 69 82 bd 2f 2e 11 a3 12 67 49 14 43 15 41 16 ti../....gI.C.A.
0000180: 16 a3 74 07 73 72 fc d2 0d 69 74 2e c5 63 68 61 ..t.sr...it..cha
0000190: 73 e8 3f 20 63 5c 22 3d be 1e 6f 03 69 aa a5 39 s.? c\"=..o.i..9
00001a0: 60 a5 6f 66 22 32 2f 31 32 39 2c 31 32 37 66 2b `.of"2/129,127f+
00001b0: 33 33 2c 2b 3a 63 22 5c 22 3c 3e 5c 5e 60 7b 7d 33,+:c"\"<>\^`{}
00001c0: 22 2b 6c 5f 34 3d 27 73 3d 3a 4c 37 2b 3e 40 7b "+l_4='s=:L7+>@{
00001d0: 2f 5c 28 40 5c 2a 7d 2f 30 5c 7b 47 7b 31 24 23 /\(@\*}/0\{G{1$#
00001e0: 29 7d 23 5f 47 3d 3a 54 40 23 40 54 2c 2a 2b 34 )}#_G=:T@#@T,*+4
00001f0: 2a 2b 7d 2f 32 2a 4c 2b 32 35 36 62 3a 63 0a *+}/2*L+256b:c.
```
### Decompressor (510 bytes)
```
0000000: 22 2f 25 2d 30 31 32 33 35 61 65 0a 2e 34 37 38 "/%-01235ae..478
0000010: 39 62 63 66 67 69 6c 6d 70 73 74 75 0a 36 41 42 9bcfgilmpstu.6AB
0000020: 43 44 45 46 49 4a 4b 4c 4d 53 58 5f 64 68 6a 6b CDEFIJKLMSX_dhjk
0000030: 6e 6f 72 76 77 78 79 7a 97 a0 a5 a6 22 0a 4e 2f norvwxyz....".N/
0000040: 5f 3a 2b 32 35 36 63 2c 5e 61 2b 3a 47 3b 22 63 _:+256c,^a+:G;"c
0000050: 6f 7f 6d 73 74 6e 67 6f 6c 6f 72 64 65 7f 85 83 o.mstngolorde...
0000060: 66 67 87 86 88 81 61 8a 63 8b 6b 61 82 80 2f 2e fg....a.c.ka../.
0000070: 8e 65 8f 8d 90 68 91 63 92 78 93 65 94 8c 95 65 .e...h.c.x.e...e
0000080: 72 6f 6e 84 67 77 69 9a 6b 9b 69 74 68 96 61 69 ron.gwi.k.ith.ai
0000090: 98 69 6e 65 74 6e a1 65 6e 64 69 25 32 a5 30 a6 .inetn.endi%2.0.
00000a0: a6 77 77 a8 77 6c 65 72 65 2e 99 ac 2f ad 9c 9f .ww.wlere.../...
00000b0: 73 81 af 89 2e b1 9e b1 96 65 a4 70 b4 9c b5 72 s........e.p...r
00000c0: 69 a5 42 b7 70 b9 74 62 8f b6 61 bc ae 61 72 b2 i.B.p.tb..a..ar.
00000d0: 2f 61 74 6c 6f 61 6d 74 6d 68 c3 c4 6c 65 b0 75 /atloamtmh..le.u
00000e0: c6 71 c7 b3 c8 63 ba 73 ca 88 cb 72 6f 61 6e 69 .q...c.s...roani
00000f0: 9d cf 75 d0 bb 67 d1 65 73 75 73 d4 97 b3 d5 6a ..u..g.esus....j
0000100: c2 63 d7 c1 77 d9 8f 70 68 db bb 70 dc 73 75 74 .c..w..ph..p.sut
0000110: de a4 df 61 e0 98 90 85 e2 69 e3 d3 83 e5 8d a9 ...a.....i......
0000120: 2e 61 dd 76 97 6f e9 8c ea eb 66 ec da 6a 73 ee .a.v.o....f..js.
0000130: 66 ef 69 f0 64 f1 64 f2 aa 70 cd a2 2f 2e f5 f3 f.i.d.d..p../...
0000140: f6 e1 f6 e6 73 f9 ae 61 6c 75 6e bf 34 70 79 fe ....s..alun.4py.
0000150: 9d 63 74 fc 00 b8 b8 75 72 03 8f a5 43 64 6f 06 .ct....ur...Cdo.
0000160: 63 d6 73 ed c8 a7 a7 b8 a6 a6 a5 69 73 72 c2 75 c.s........isr.u
0000170: 74 69 82 bd 2f 2e 11 a3 12 67 49 14 43 15 41 16 ti../....gI.C.A.
0000180: 16 a3 74 07 73 72 fc d2 0d 69 74 2e c5 63 68 61 ..t.sr...it..cha
0000190: 73 e8 3f 20 63 5c 22 3d be 1e 6f 03 69 aa a5 39 s.? c\"=..o.i..9
00001a0: 60 a5 6f 66 22 32 2f 5b 71 32 35 36 62 32 6d 64 `.of"2/[q256b2md
00001b0: 22 68 74 74 70 22 6f 27 73 2a 6f 22 3a 2f 2f 22 "http"o's*o"://"
00001c0: 6f 7b 34 6d 64 47 3d 5f 2c 40 5c 6d 64 40 3d 5c o{4mdG=_,@\md@=\
00001d0: 7d 68 3b 5d 57 25 31 32 39 2c 31 32 37 66 2b 33 }h;]W%129,127f+3
00001e0: 33 2c 2b 3a 63 22 5c 22 3c 3e 5c 5e 60 7b 7d 22 3,+:c"\"<>\^`{}"
00001f0: 2b 57 25 7b 2f 5c 29 40 5c 2a 7d 2f 4e 0a +W%{/\)@\*}/N.
```
### Algorithm
1. Strip the `<scheme>://` part from the URL.
2. Replace character pairs by unused code points in the 0 - 255 range.
This uses a static dictionary which is included in the source code.
3. Use arithmetic encoding on the modified input string.
To comply with the source code size limit, this is done by splitting the 256 code points into 4 groups and pretending the groups and the code points in a fixed group have equal probabilities.
4. Append a bit indicating the scheme to the resulting integer.
5. Convert the integer into a string.
## Test cases
Create the source code files.
```
$ xxd -p -r > comp.cjam <<< 222f252d303132333561650a2e3437383962636667696c6d707374750a36414243444546494a4b4c4d53585f64686a6b6e6f72767778797a97a0a5a6220a4e2f5f3a2b323536632c5e612b3a473b22636f7f6d73746e676f6c6f7264657f8583666787868881618a638b6b6182802f2e8e658f8d9068916392789365948c9565726f6e846777699a6b9b69746896616998696e65746ea1656e64692532a530a6a67777a8776c6572652e99ac2fad9c9f7381af892eb19eb19665a470b49cb57269a542b770b974628fb661bcae6172b22f61746c6f616d746d68c3c46c65b075c671c7b3c863ba73ca88cb726f616e699dcf75d0bb67d165737573d497b3d56ac263d7c177d98f7068dbbb70dc737574dea4df61e0989085e269e3d383e58da92e61dd76976fe98ceaeb66ecda6a73ee66ef69f064f164f2aa70cda22f2ef5f3f6e1f6e673f9ae616c756ebf347079fe9d6374fc00b8b87572038fa543646f0663d673edc8a7a7b8a6a6a5697372c275746982bd2f2e11a3126749144315411616a374077372fcd20d69742ec563686173e83f20635c223dbe1e6f0369aaa53960a56f6622322f3132392c313237662b33332c2b3a63225c223c3e5c5e607b7d222b6c5f343d27733d3a4c372b3e407b2f5c28405c2a7d2f305c7b477b312423297d235f473d3a54402340542c2a2b342a2b7d2f322a4c2b323536623a630a
$ xxd -p -r > decomp.cjam <<< 222f252d303132333561650a2e3437383962636667696c6d707374750a36414243444546494a4b4c4d53585f64686a6b6e6f72767778797a97a0a5a6220a4e2f5f3a2b323536632c5e612b3a473b22636f7f6d73746e676f6c6f7264657f8583666787868881618a638b6b6182802f2e8e658f8d9068916392789365948c9565726f6e846777699a6b9b69746896616998696e65746ea1656e64692532a530a6a67777a8776c6572652e99ac2fad9c9f7381af892eb19eb19665a470b49cb57269a542b770b974628fb661bcae6172b22f61746c6f616d746d68c3c46c65b075c671c7b3c863ba73ca88cb726f616e699dcf75d0bb67d165737573d497b3d56ac263d7c177d98f7068dbbb70dc737574dea4df61e0989085e269e3d383e58da92e61dd76976fe98ceaeb66ecda6a73ee66ef69f064f164f2aa70cda22f2ef5f3f6e1f6e673f9ae616c756ebf347079fe9d6374fc00b8b87572038fa543646f0663d673edc8a7a7b8a6a6a5697372c275746982bd2f2e11a3126749144315411616a374077372fcd20d69742ec563686173e83f20635c223dbe1e6f0369aaa53960a56f6622322f5b7132353662326d642268747470226f27732a6f223a2f2f226f7b346d64473d5f2c405c6d64403d5c7d683b5d57253132392c313237662b33332c2b3a63225c223c3e5c5e607b7d222b57257b2f5c29405c2a7d2f4e0a
```
Verify their integrity.
```
$ cksum comp.cjam decomp.cjam
2293013588 511 comp.cjam
1577103568 510 decomp.cjam
```
Download the CJam interpreter.
```
$ wget -q wget http://downloads.sourceforge.net/project/cjam/cjam-0.6.4/cjam-0.6.4.jar
```
Create an alias for running the interpreter.
```
$ alias cjam='java -jar cjam-0.6.4.jar'
```
Set encoding to ISO-8859-1 to store each character as a single byte.
```
$ LANG=en_US
```
Prepare the test file.
```
$ wget -q https://gist.githubusercontent.com/orlp/fd3411259469ade4c65d/raw/bb6b088c18c444d28729abc870d6076ca594a6de/urls.txt
$ echo >> urls.txt
```
For each line in the test file, feed the URL to the compressor, append the output to `urls-comp.bin` and feed it back to the decompressor. Save the combined output of all decompressions in `urls-vrfy.txt`. **This will take a few minutes.**
```
$ >urls-comp.bin
$ for URL in $(<urls.txt); do
> echo $URL | cjam comp.cjam | tee -a urls-comp.bin | cjam decomp.cjam
> done > urls-vrfy.txt
```
Verify that all URLs were decoded appropriately.
```
$ cksum urls.txt urls-vrfy.txt
3445245739 588562 urls.txt
3445245739 588562 urls-vrfy.txt
```
Compute the score.
```
$ wc -c urls-comp.bin
268306 urls-comp.bin
```
## How it works
### Common
Push the string containing the first three character groups.
```
"/%-01235ae
.4789bcfgilmpstu
6ABCDEFIJKLMSX_dhjknorvwxyz����"
```
Split at linefeeds, flatten a copy of the resulting array and compute the symmetric difference of the resulting string and the string of all code points.
```
N/_:+256c,^
```
Append the result to the array which now contains all four character groups. Save the result in the variable `G` and discard it from the stack.
```
a+:G;
```
Push the array (let's call it `A`) containing all character pairs to be substituted.
```
"comstngolorde��fg����a�c�ka��/.�e���h�c�x�e���eron�gwi�k�ith�ai�inetn�endi%2�0��ww�wlere.��/���s���.����e�p���ri�B�p�tb��a��ar�/atloamtmh��le�u�qdz�c�sʈ�roani��uлg�esusԗ��j�c��wُphۻp�sutޤ�a���i�Ӄit.�chas�? c\"=�oi��9`�of"
2/
```
Push the array `[ 0 ... 128 ]`, add 127 to each element, append the array `[ 0 ... 32 ]`, cast to Char and append the string `"\"<>\^`{}"`. The result is the string (let's call it`S`) of all unused code points from 0 to 255.
```
129,127f+33,+:c"\"<>\^`{}"+
```
### Compressor
```
... " Generate G. Push A and S. ";
l " Read one line from STDIN. ";
_4='s= " Check if its 5th character is an 's'. ";
:L7+ " Save the result in L and add it to 7. ";
> " Discard that many characters from the input string. ";
@{ " For each character pair in A: ";
/ " Split the input string at its occurrences. ";
\(@\ " Unshift one character C from S. ";
* " Join the split string, using C as separator. ";
}/ " ";
0 " Push 0 (accumulator). ";
\{ " For each character C in the input string: ";
G{1$#)}# " Retrieve the index of the group C belongs to. ";
_G=:T " Store the group in T. ";
@# " Push the index of C in T. ";
@T,*+4*+ " Multiply the accumulator by the length of T and add the index. ";
}/ " ";
2*L+ " Multiply the accumulator by 2 and add L. ";
256b:c " Convert the accumulator (BigInteger) into a byte string. ";
```
### Decompressor
```
... " Generate G. Push A. ";
[q " Start an array and read the whole input. ";
256b " Convert the byte string into an integer. ";
2md " Push quotient and residue of the division by 2. ";
"http"o " Print 'http'. ";
's*o " If the residue is 1, print 's'. ";
"://"o " Print '://'. ";
{ " While the integer is non-zero: ";
4md " Push quotient and residue of the division by 4. ";
G=_, " Push the corresponding character group and its length. ";
@\md " Divide the integer by the length. Push quotient and residue. ";
@=\ " Retrieve the char corresponding to the residue from the group. ";
}h " ";
]W% " End and reverse array. ";
" Since the elements are Chars, this yields a string. ";
... " Push S. ";
\W%{ " For each character in S reversed: ";
/ " Split the string at its occurrences. ";
\)@\ " Pop one character pair P from A. ";
* " Join the split string, using P as separator. ";
}/ " ";
N " Push a linefeed. ";
```
### Remarks
Decompression will work correctly only for the `http` and `https` schemes. The reasons are twofold:
* The `http` part is hardcoded.
* The arithmetic encoding uses the fact that `<http|https>://` cannot be followed by a third slash.
Since the integer 0 encodes any arbitrary run of slashes (character 0 of group 0), we would have to store the URL's length or the number of leading slashes to support, e.g., `file:///` URLs.
[Answer]
# [BrainFuck](http://en.wikipedia.org/wiki/Brainfuck): 550417
**Encoder:**
```
,,,,,[.,]
```
**Decoder:**
```
>++++++++++[-<++++++++++>]<++++.++++++++++++..----[.,]
```
It needs the url without linefeed and it expects 0 as EOF.
Example:
```
> echo -n "http://stackoverflow.com/" | beef encode.bf
://stackoverflow.com/
> echo -n "://stackoverflow.com/" | beef decode.bf
http://stackoverflow.com/
```
[Answer]
# MATLAB, 477161
Edit: something odd is going on here. When I fed the original list through a RAR compressor, it got it down to 122Kb. When I feed my compressed list, though, it can only get it down to 222Kb. So, basically I created a compression algorithm that will make it harder for other compression algorithms to work. How about that, huh... :)
Takes the input string, strips it of the `http` at the start, and then compresses the string into a 7-bit representation. Appends an 'x' or 'y' for the decompressor to now whether it is dealing with a complete block or not; this could have probably been done more efficient (perhaps a parity bit) but this will have to do for now (it will only decrease my score with about 10k). I only realized halfway this was not code-golf, so you'll have to do without descriptive variable names.
```
function t=compress(s);
s=s(5:end);
t='';
replacable='"<>\^`{}';
for(k=replacable)
s=strrep(s,['%' dec2hex(k)],k);
end
l=numel(s);
for(i=1:8:l-mod(l,8))
t=[t char(bin2dec(reshape(dec2bin(s(i:i+7),7),7,8)))'];
end
if(mod(l,8))
t=[t s(l-mod(l,8)+1:l)];
t(end+1)='x';
else
t(end+1)='y';
end
```
Decompress:
```
function s=decompress(t);
l=numel(t)-1;
if(t(end)=='x')
endfor=l-mod(l,7);
endfor(l==endfor)=l-7;
else
endfor=l-1;
end
s='http';
for(i=1:7:endfor)
s=[s char(bin2dec(reshape(dec2bin(t(i:i+6),8),8,7)))'];
end
if(t(end)=='x')
s=[s t(endfor+1:end-1)];
end
replacable='"<>\^`{}';
for(k=replacable)
s=strrep(s,k,['%' dec2hex(k)]);
end
```
EDIT: fixed some bugs, added some `%xx` replacements; other than that I'm calling it a day because I'll *never* get to 300k with this approach.
[Answer]
# Python (413649)
Compressor:
```
u=input()[4:]
for i,j in zip('"<>\\^`{}\t\r\v\f','s:// :// codegolf.stackexchange.com en.wikipedia.org/wiki cjam.aditsu.net jsfiddle.net golfscript.apphb.com ideone.com github.com stackoverflow.com esolangs.org i.stack.imgur.com'.split()):
u=u.replace(j,i)
print(u)
```
Decompressor:
```
u='http'+input()
for i,j in zip('"<>\\^`{}\t\r\v\f','s:// :// codegolf.stackexchange.com en.wikipedia.org/wiki cjam.aditsu.net jsfiddle.net golfscript.apphb.com ideone.com github.com stackoverflow.com esolangs.org i.stack.imgur.com'.split()):
u=u.replace(i,j)
print(u)
```
The algorithm is very simple. The http at the beginning is stripped because it is the same in all of the test urls. It then takes the most common domain names in the test file and substitutes each for a single ascii character, out of the characters not used in any. It also substitutes `://` (http) and `s://` (https) for individual characters.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/45584/edit)
# Background Story
Bob was handed the following assignment for his programming class. **Please note: this is not the actual challenge.**
>
> **Homework assignment 11: Twin primes**
>
>
> Input: an integer `n ≥ 8`, taken from STDIN.
>
>
> Output: a message to STDOUT, depending on `n`:
>
>
> * If `n` is not a prime number, output `Not prime.`
> * If `n` is a prime number, but neither of `n - 2` and `n + 2` is, output `Isolated prime.`
> * If `n` and `n + 2` are both prime numbers, output `Lower twin prime.`
> * If `n` and `n - 2` are both prime numbers, output `Upper twin prime.`
>
>
>
Bob tried hard to solve the assignment, but his program kept crashing, and in the end, he gave up and submitted it in hope of partial credit. Nevertheless, Bob's program has the curious property that even though it never does what it's supposed to, the input is still classified correctly depending on the program's behavior: non-primes result in no output, isolated primes in a crash, lower twin primes in an infinite loop with no output, and upper twin primes in an infinite loop that keeps printing the correct message.
# The Task
Your task is to replicate the behavior or Bob's solution. In other words, write a program that reads a single integer `n ≥ 8` from STDIN or closest equivalent, and does the following:
* If `n` is not a prime number, output nothing and exit gracefully.
* If `n` is a prime number, but none of `n - 2` or `n + 2` is, produce a runtime error of some kind. Stack overflows count as runtime errors.
* If `n` and `n + 2` are both prime numbers, output nothing, but keep running until the program is killed manually (or until you run out of memory).
* If `n` and `n - 2` are both prime numbers, repeatedly output `Upper twin prime.`, with or without a trailing newline, to STDOUT or closest equivalent until the program is killed manually (or until you run out of memory).
Incorrect inputs can be ignored.
# Scoring
The idea is that your program should appear correct, but contain hidden bugs that result in the above behavior. Your program should also be short (since programming assignments are graded by hand), but popularity is more important. Thus, your score is **number of upvotes - (byte count / 100)**, higher score being better. Note that your score can be negative.
[Answer]
# TI-BASIC, ~269
```
Input N
Lbl 1
2→P :" test N for divisibility by each prime
Lbl 2
If int(N/P)=N/P:Goto 3 :"composite"
If PP>N:Goto 4
P+1→P
Goto 2
Lbl 3
Disp " NOT PRIME. "
Stop
Lbl 4
If int((N+2)/3)=(N+2)/3 :" determine which nearby value to test
Then:N-2→R
Else:N+2→R
End
2→P
Lbl 5
If int(R/P)=R/P:Goto 6 :"composite"
If PP>R:Goto 7
P+1→P
Goto 5
Lbl 6
Output("ISOLATED PRIME.")
Lbl 7 :" TI-BASIC how two ways of printing:
:" Disp goes to the main screen,
:" and Output goes to the graphical screen.
:" This program uses both methods.
If R=N+2:Goto 5 :" go to print "lower twin prime"
Disp "UPPER TWIN PRIME"
Goto 7 :" only 16 chars can be printed per line, so we'll do the period separately (last line of program)
Lbl 5
Output("LOWER TWIN PRIME")
Lbl 7
Disp "."
```
>
> The NOT PRIME string has sixteen leading spaces, so nothing (except an ellipsis) will be printed, as noted in the comments.
>
> The ISOLATED PRIME string uses the `Output()` function, which requires two numbers (the coordinates of the printing location). This triggers an Argument Error.
>
> The LOWER TWIN PRIME string is indicated by the link to `Lbl 5`, which was already defined as the start of the twin prime test, causing an infinite loop.
>
> The UPPER TWIN PRIME string is followed by a link to the period, but `Lbl 7` was already defined above, triggering an infinite loop.
>
>
>
[Answer]
# CJam - 163 bytes
```
{:S;0:I;{SI=__31>\127<&{oI):I;}{S\-;0:I;}?IS,<}gNo}:P;ri:Xmp{X2+mp{"Lower twin prime."P}{X2-mp{"Upper twin prime."P}{"Isolated prime."P}?}?}{"Not prime":P}?;
```
You can try it at <http://cjam.aditsu.net/> , but in the "upper twin prime" case, you can only see the output if you use the [java interpreter](https://sourceforge.net/projects/cjam/) as the online interpreter waits for the program to finish before showing the output.
Bob started to write the program in CJam, but kept getting some weird errors so he suspected that he got some invalid characters somewhere. In an attempt to debug the issue, he implemented his own print function that checks every character:
```
{ begin
:S; store the argument in S
0:I; initialize I with 0
{ do..
SI=__ get the I'th character and make 2 more copies
31>\127<& check that the character code is strictly between 31 and 127
{ if true
oI):I; print the character and increment I
}{ else
S\-; remove the character from S
0:I; start again from 0
}? end if
IS,< check if I < length(S)
}g ..while the above is true
No print a newline
}:P; end function P
```
He tested the function, e.g. `"foo"P`, and it worked fine.
Then he wrote the main code:
```
ri:X read token, convert to integer and store in X
mp{ if X is prime
X2+mp{ if X+2 is prime
"Lower twin prime."P print "Lower twin prime."
}{ else
X2-mp{ if X-2 is prime
"Upper twin prime."P print "Upper twin prime."
}{ else
"Isolated prime."P print "Isolated prime."
}? end if
}? end if
}{ else
"Not prime."P print "Not prime."
}? end if
```
The algorithm seems perfectly fine, yet the program does what the question says... so poor Bob is really stumped.
Hint 1:
>
> The program at the top is not 100% identical to the program in the explanation
>
>
>
Hint 2:
>
> While the P function works fine for normal strings, it has a bug when dealing with invalid characters
>
>
>
Hint 3:
>
> The number of characters in the code is not equal to the number of bytes
>
>
>
Full explanation:
>
> - "S\-;" does the character removal but does not modify S, so if S has invalid characters, P goes into an infinite loop.
>
> - The "Lower twin prime." and "Upper twin prime." strings have a zero-width space (unicode character) at the beginning and end, respectively; thus the first one loops without printing anything and the 2nd one loops after printing the correct message
>
> - The last lines in the explanation should actually be:
>
> "Not prime":P - store "Not prime" in variable P, leaving it on the stack
>
> }? - end if
>
> ; - pop value (resulting in no output for "Not prime":P and error for "Isolated prime."P since the stack is empty after printing)
>
>
>
[Answer]
# Tcl, 2416
```
# This function is copied from http://wiki.tcl.tk/5996,
# which is in public domain according to http://wiki.tcl.tk/4381
proc primetest n {
set max [expr wide(sqrt($n))]
if {$n%2==0} {return [list 2 [expr $n/2]]}
for {set i 3} {$i<=$max} {incr i 2} {
if {$n%$i==0} {return [list $i [expr $n/$i]]}
}
return 1
}
set n [gets stdin]
# Input n.
set result ""
# Some initialization which seemed to be useless.
if {[primetest $n]==1} {
# In Tcl, { opens a string where everything in
if {[primetest [expr {$n-2}]]==1||[primetest [expr {$n+2}]]==1} {
# it isn't escaped.
if {[primetest [expr {$n-2}]]==1} {
# Needless to say, The closing character for
set result "Upper twin prime.\n";
# those strings is obviously }; while 1 {
puts -nonewline $result
# corresponds to the 1 matching }; there can
} {
# be more matching pairs of { } between them.
set result "Lower twin prime.\n"
# Escaped braces like \{ \} don't match each
puts -nonewline $result
# other, but the backslashes won't be removed
}
# so \{ won't become {. This kind of strings
} {
# worked well in representing blocks of code.
set result "Isolated prime.\n"
# And control structures like if, for, while,
puts -nonewline $result
# and even functions just take strings as
}
# parameters and evaluate them when necessary.
} {
# After the } closing an if statement, there can
set result "Not prime.\n"
# be another parameter for the else block.
puts -nonewline $result
# Read the above comments carefully if you didn't
}
# find the underhanded part yet.
```
I wrote this before realizing there can't be end of line comments in Tcl. So this became ugly and more suspicious. But well...
] |
[Question]
[
Smallest code to return sum of all characters of an array of C-strings, including null-byte-terminattor of each string in the array.
example in C:
```
const char *a[] = { "abc", "bdef", "cee", "deee" };
size_t n = sumOfAllBytes(a);
printf("n = %d\n", n); // n = 18
```
e.g.,
```
strlen(a[0]) + 1 + ... + strlen(a[n])
```
where `n` is `array-size-1`, ie, the last elemet in the array, in this case, `deee` word. Note that `n = 4` (starting from 0 as C does)
Each character is an ASCII character in C it's 1 byte-size.
[Answer]
# Haskell, ~~21~~ 19 bytes
```
succ.length.unwords
```
Edit: Removed two bytes thanks to [ais523](https://codegolf.stackexchange.com/users/62131/ais523)!
[Answer]
# GolfScript [4 bytes]
```
n*,)
```
There are no functions in GolfScript, so you should use a standard input instead:
```
["abc" "bdef" "cee" "deee"]
n*,)
>>> 18
```
**DEMO:** <http://golfscript.apphb.com/?c=WyJhYmMiICJiZGVmIiAiY2VlIiAiZGVlZSJdCgpuKiwp>
[Answer]
# bash+coreutils - function body 10 bytes
```
sumOfAllBytes()(wc -c<<<$@)
```
Call as follows:
```
$ a=("abc" "bdef" "cee" "deee")
$ sumOfAllBytes ${a[@]}
18
$
```
[Answer]
# Mathematica ~~31~~ 29 bytes
-2 bytes thanks to numbermaniac
```
StringLength[""<>#]+Length@#&
```
Example
```
StringLength[""<>#]+Length@#&@{ "abc", "bdef", "cee", "deee" }
```
>
> 18
>
>
>
[Answer]
# Rebol (body: 18 chars, function: 30 chars)
```
1 + length? form x
```
Usage example in Rebol console:
```
>> f: func[x][1 + length? form x]
>> f ["abc" "bdef" "cee" "deee"]
== 18
```
[Answer]
# Perl, function body: 15 bytes
```
sub sumOfAllBytes{!!@_+length"@_"}
```
Function `sumOfAllBytes` returns the sum of the string lengths including a "virtual" terminator byte. Perl does not have the concept of terminating a string with a null byte.
A variant without a "terminating byte":
```
sub sumOfAllBytes{$"=$;@_+length"@_"}
```
**Byte count:** The body of the functions are 15 or 17 bytes (with or without terminator). 7 bytes must be added, if the whole function with one-byte name should be counted.
**Test with degolfed version:**
```
sub sumOfAllBytes {
# the argument(s) are put into array @_ by Perl
!!@_ + # short for: @_ ? 1 : 0
# (if the array is empty nothing should be added)
length "@_" # The array elements are interpolated into the double-
# quoted string; the elements are separated by a space ($").
# without explicit return statement, the value of the last
# statement is returned.
}
@a = qw[abc bdef cee deee];
print sumOfAllBytes(@a), "\n"; # prints 18
```
[Answer]
## C, 78 minus declaration of a[]
Assumes 64 bit target and a[] containing at least one string.
```
char *a[]={"abc","bdef","cee","deee"};
f(int i){return strlen(a[i])+1+(i?f(i-1):0);}
main(){return f(sizeof(a)/8-1);}
```
To see the result, invoke thusly:
```
$ ./whatever || echo $?
```
[Answer]
# c preprocessor macros, 94 chars
The example in the question is not doable in c as a regular function as the function would have no idea the size of the array if just a pointer to the array is passed in. But we can do this as a couple of preprocessor macros:
```
#define c(s) sizeof(s)/sizeof(s[0])-1
#define sumOfAllBytes(s) s[c(s)]-s[0]+strlen(s[c(s)])+1
```
We assume that the array is declared, defined and initialised as in the question. That way the strings should be laid out sequentially in memory. We can then subtract the address of the first element from the last element and add the `strlen()` of the last element. No need to loop over all elements and `strlen()`.
[Answer]
# Haskell 24
```
s=sum.(map$(+1).length)
```
Usage, in ghci:
```
ghci> s ["abc", "bdef", "cee", "deee"]
18
```
[Answer]
# Java: 56 characters (body) 74 characters (full method)
*Hey, this is as good as it gets in Java!*
This is the method:
```
int z(String[]a){int s=0;for(String b:a)s+=b.length();return s+a.length;}
```
The main code is just *56* characters (witout spaces and comments):
```
int s=0; // The sum variable.
for(String b:a) // The 'for each' loop is handy
s+=b.length(); // Adding the length of each String
return s+a.length; // Adding the length of the array
```
**Calling this function:**
```
int answer = z(new String[]{ "abc", "bdef", "cee", "deee" }); // Stores 18
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
JgIg+
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fK90zXfv//2ilxKRkJR0FpaSU1DQQnZyaCqJSUoHcWAA "05AB1E – Try It Online")
-1 thanks to @Datboi
[Answer]
## C [body: 48 chars, function: 107 chars]
```
int f(const char** r, const char* c, const char** e) {
return r-e?1+(*c?f(r,c+1,e):f(r+1,*(r+1),e)):0;
}
```
Ugly piece of code. Just trying to do it without loops by using recursion.
Call it this way:
```
const char *a[] = { "abc", "bdef", "cee", "deee" };
size_t n = f(a,*a,a+4);
printf("n = %zu\n", n);
```
No warnings and result is OK:
```
$ gcc koe.c -Wall -Wextra -o koe
$ ./koe
n = 18
```
[Answer]
# C - Loop:64, Recursion:56 (-18 for function body overhead)
## Loop
```
s(char*a[],int n){int r=0;for(;n;)r+=strlen(a[--n])+1;return r;}
```
## Recursion
```
r(char*a[],int n){return n?strlen(a[0])+1+r(a+1,n-1):0;}
```
[Answer]
# PHP 5.3 - 60
```
array_sum(array_map(function($v){return strlen($v)+1;},$a));
```
Where `$a` is the array.
[Answer]
# Fortran 90+ - 75 total, 23 for function alone
Unfortunately, Fortran doesn't allow for implicit typing of character strings, but we can abuse F77+F90 for golfing purposes. The whole program would be:
```
character*4::c(4)=["abc","bdef","cee","deee"];print*,sum(len_trim(c)+1);end
```
The function alone, written using a statement function would be
```
k(s)=sum(len_trim(s)+1)
```
which would be called using `print*,k(c)`.
[Answer]
**in C# 34 Excluding "string [] a=new [] { "abc", "bdef", "cee", "deee" };"**
```
string [] a=new [] { "abc", "bdef", "cee", "deee" };
var i=string.Join(" ",a).Length+1;
sol:2
var j = string.Concat(a).Length + a.Length;
```
[Answer]
## Python - 55 42 38
```
def s(v):print sum(1+len(x)for x in v)
```
[Answer]
# JavaScript - 42 characters without declaration
```
function s(x){return x.join(" ").length+1}
```
Usage:
```
a=["abc","bdef","cee","deee"];console.log(s(a));
```
[Answer]
## D - ~~58~~ 54 bytes
```
int x(T)(T t){return reduce!"a+b.length"(t.length,t);}
```
This requires `std.algorithm`, so add the characters necessary for making that import if you want to.
Example of usage:
```
import std.stdio,std.algorithm;
int x(T)(T t){return reduce!"a+b.length"(t.length,t);}
void main(){
writeln(x!(string[])(["abc","bdef","cee","deee"]));
}
```
[Answer]
**C#, 52** including variable declaration
```
int c=0;for(int i=0;i<a.Length;i++)c+=1+a[i].Length;
```
Uncompressed version for ease of reading:
```
int count = 0;
for (int i = 0; i < a.Length; i++)
count += 1 + a[i].Length;
```
[Answer]
## APL 6
```
+/1+⍴¨a
```
where
```
a←"abc" "bdef" "cee" "deee"
```
yields
```
+/1+⍴¨a
18
```
Read as "Sum over 1 plus size of each element in a"
[Answer]
# q/kdb+, 14 bytes
**Solution:**
```
sum 1+(#:)each
```
**Example:**
```
q)sum 1+(#:)each("abc";"bdef";"cee";"deee")
18
```
**Explanation:**
Evaluated right-to-left, thus:
```
// count (#:) length of each item in the list
q)(#:)each("abc";"bdef";"cee";"deee")
3 4 3 4
// add one to each item
q)1+ 3 4 3 4
4 5 4 5
// sum up the items
q)sum 4 5 4 5
18
```
[Answer]
# JavaScript - 20 17 Characters
```
s.join().length+1
```
Assumes that the array of strings is in variable 's' and outputs the answer to the console.
[Answer]
## Clojure, 32 bytes
```
#(apply +(map(comp inc count)%))
```
[Composition](https://clojuredocs.org/clojure.core/comp) FTW. Aww it is the same length as `#(apply +(count %)(map count %))`.
[Answer]
# F#, 56 bytes
Still practicing with F#...
```
let f a=(a|>Seq.map String.length|>Seq.sum)+Seq.length a
```
Invoke with:
```
[<EntryPoint>]
let main argv =
let sum = [| "abc"; "bdef"; "cee"; "deee" |] |> f
printfn "%A" sum
0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
KL‘
```
[Try it online!](https://tio.run/##y0rNyan8/9/b51HDjP///0crJSYlK@koKCWlpKaB6OTUVBCVkgqkYwE "Jelly – Try It Online")
] |
[Question]
[
The set of ten numbers below:
```
223092870
17237308840522
1075474925835771
12574206406402195
79458974087499419
265057843710517649
466012798920390527
926434345611831877
1390237791335182649
2336970054109245767
```
has the property that no two pairs of numbers have the same greatest common factor. (In this case, the greatest common factor of each pair of numbers is actually a distinct prime.)
Your task is to find the set of 10 positive integers with the smallest sum that satisfy this property.
For reference, the sum of the above ten numbers is 5 477 838 726 638 839 246 (≈5.48×1018).
[Answer]
## Sum: 58025
(ruby)
```
(0..9).map{|i|(2**i)*(3**(9-i))}
```
Gives
```
[19683, 13122, 8748, 5832, 3888, 2592, 1728, 1152, 768, 512]
```
[Answer]
## Sum: 11835
```
[1920, 1792, 1440, 1344, 1280, 1080, 1008, 810, 756, 405]
```
To verify, a table of the *gcd* values for each pair:
```
| 1920 | 1792 | 1440 | 1344 | 1280 | 1080 | 1008 | 810 | 756
-----+------+------+------+------+------+------+------+------+-----
405 | 15 | 1 | 45 | 3 | 5 | 135 | 9 | 405 | 27
756 | 12 | 28 | 36 | 84 | 4 | 108 | 252 | 54 |
810 | 30 | 2 | 90 | 6 | 10 | 270 | 18 |
1008 | 48 | 112 | 144 | 336 | 16 | 72 |
1080 | 120 | 8 | 360 | 24 | 40 |
1280 | 640 | 256 | 160 | 64 |
1344 | 192 | 448 | 96 |
1440 | 480 | 32 |
1792 | 128 |
```
---
### Implementation Details
**Update:** Massive performance gain c/o [@PeterTaylor](https://codegolf.stackexchange.com/questions/12407/12419#comment24298_12419), as is so often the case.
* For a set *S* of length *n* matching the problem description, each element of *S* must have at least *n-1* divisors (including *1* and the value itself), as each must participate in exactly *n-1* unique *gcd*. Only values with this property are considered.
* The algorithm for the number of divisors takes the following form:
If *i* is a positive integer with the prime factorization *p0e0·p1e1…pnen*, then the number of divisors of *i* is equal to *(e0+1)·(e1+1)…(en+1)*. When counting divisors, only primes of the set *[2, 3, 5, 7]* are used; i.e. only those divisors which are *[7-smooth](http://en.wikipedia.org/wiki/Smooth_number)* are counted.
* The search algorithm begins with the largest value of the set, and then searches recursively for each next smaller value. When the current search space has been exhausted, the next larger value with enough divisors is added to the list.
**Note:** while this is guaranteed to find the set with the smallest maximum value, it is not necessarily the optimal solution to this problem. A counter-example for *n=6*:
*[120, 112, 90, 84, 80, 45]* (*531*) vs. *[162, 108, 81, 72, 48, 16]* (*487*).
* The memoization of the *gcd* function results in a significant performance gain. By the time the third or fourth term is reached, most of the *gcd*s have already been calculated, and need only to be looked up. Additionally, the first iteration is performed outside of the *gcd* function itself, which increases look-up collision.
* `for ... else` is something of a Python oddity. The `else` block will only be evaluated if the `for` loop terminates properly, i.e. not by `break`. I use this for short-circuiting upon duplicate *gcd*s.
* The length of the set, *n*, is provided as input via `stdin`.
---
### Implementation
```
from time import time
num_vals = input()
def memoize(func):
class memodict(dict):
def __call__(self, *args):
return self[args]
def __missing__(self, key):
ret = self[key] = func(*key)
return ret
return memodict()
@memoize
def gcd(a, b):
while b:
a, b = b, a%b
return a
def divisors(n):
divs = 1
for i in 2,3,5,7:
exp = 1
while n%i == 0:
n /= i
exp += 1
divs *= exp
return divs
def next_val(n):
while True:
n += 1
d = divisors(n)
if d >= num_vals-1: return n
vals = []
def f(n, end, nums, factors):
if n<1:
return nums
index = n-1
for i in vals[n-1:end]:
index += 1
new_factors = set()
for j in nums:
v = gcd(i, j%i)
if v in factors or v in new_factors:
break
new_factors.add(v)
else:
ret = f(n-1, index, nums + [i], factors | new_factors)
if ret: return ret
def g(n):
global vals
val = 0
while len(vals) < n:
val = next_val(val)
vals += [val]
index = n-1
while True:
ret = f(n-1, index, [val], set())
if ret: return ret
val = next_val(val)
vals += [val]
index += 1
t1 = time()
v = g(num_vals)
print sum(v), v
print time() - t1
```
---
Solutions and approximate runtime for *n* ∈ [2, 10]:
```
3 [2, 1]
0.00s
11 [6, 3, 2]
0.00s
43 [18, 12, 9, 4]
0.00s
149 [54, 36, 27, 24, 8]
0.05s
531 [120, 112, 90, 84, 80, 45]
0.07s
1143 [240, 224, 180, 168, 160, 126, 45]
0.34s
2601 [480, 448, 360, 336, 320, 270, 252, 135]
2.32s
5445 [960, 896, 720, 672, 640, 540, 504, 378, 135]
2m 2.4s
11835 [1920, 1792, 1440, 1344, 1280, 1080, 1008, 810, 756, 405]
36m 6s
```
[Answer]
# Sum: 132251618166478572 (≈1.32×1017)
As a reference last-place answer, I will post the Python code I used to generate the initial set of numbers in the question:
```
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,
139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197]
numbers = [1] * 10
primefactor = 0
for a in range(10):
for b in range(a+1, 10):
numbers[a] *= primes[primefactor]
numbers[b] *= primes[primefactor]
primefactor = primefactor + 1
# can't use "sum" because it produces weird values.
numbertotal = 0
for i in numbers:
numbertotal += i
print numbers, numbertotal
```
Essentially what this does is take every prime number from 2 to 197 (the first 10C2 = 45 primes), and multiplies them to a unique pair of numbers. That way, any pair of numbers will only have that one prime that was assigned to it as a common factor.
This was done mostly as a proof that there do exist sets of numbers with the property required in the question - as you can see, the value it generated is far from optimal.
Modifying this code to shuffle the primes around randomly before multiplying them results in smaller numbers being created. With multiple trials, I found the following set of numbers:
```
1268193027813141
2224904691135063
4714631150921614
7005966291691742
9288794198034215
9315429894689005
12630588322608113
13006064536029667
23545741081119313
49251304972436699
```
whose sum is 132251618166478572, as above.
] |
[Question]
[
Program the sequence \$R\_k\$: all numbers that are sum of square roots of some(maybe one) natural numbers \$\left\{\sum\_{i\in A}\sqrt i\middle|A\subset \mathbb{N}\right\}\$, in ascending order without duplication. Outputting zero is optional.
You should do one of:
* Take an index k and output \$R\_k\$, either 0 or 1 indexing
* Take a positive integer k and output the first \$k\$ elements of \$R\$
* Output the whole sequence
Shortest code in each language wins. Beware of floating error, which returns \$\sqrt 2+\sqrt 8=\sqrt {18}\$ twice using my raw code, which is disallowed.
---
First few elements:
```
(0,)1,1.4142135623730951,1.7320508075688772,2,2.23606797749979,2.414213562373095,2.449489742783178,2.6457513110645907,2.732050807568877,2.8284271247461903,3,3.1462643699419726,3.1622776601683795,3.23606797749979,3.3166247903554,3.414213562373095,3.449489742783178,3.4641016151377544,3.605551275463989,3.6457513110645907,3.6502815398728847,3.732050807568877,3.7416573867739413,3.8284271247461903,3.863703305156273,3.872983346207417,3.968118785068667,4,4.059964873437686,4.123105625617661,4.146264369941973,4.16227766016838,4.1815405503520555,4.23606797749979,4.242640687119286,4.3166247903554,4.358898943540674,4.377802118633468,4.414213562373095,4.449489742783178,4.464101615137754,4.47213595499958,4.5604779323150675,4.576491222541475,4.58257569495584,4.60555127546399,4.645751311064591,4.650281539872885,4.685557720282968,4.69041575982343,4.730838352728495,4.732050807568877,4.741657386773941,4.795831523312719,4.82842712474619,4.863703305156273,4.872983346207417,4.878315177510849,4.8818192885643805,4.894328467737257,4.898979485566356,4.9681187850686666,5,5.0197648378370845,5.048675597924277,5.059964873437686,5.06449510224598,5.095241053847769,5.0990195135927845,5.123105625617661,5.146264369941973,5.155870949147037,5.16227766016838,5.1815405503520555,5.196152422706632,5.23606797749979,5.242640687119286,5.277916867529369,5.287196908580512,5.291502622129181,5.3166247903554,5.337602083032866,5.358898943540674,5.377802118633468,5.382332347441762,5.385164807134504,5.39834563766817,5.414213562373095,5.449489742783178,5.464101615137754,5.47213595499958,5.4737081943428185,5.4741784358107815,5.477225575051661,5.5373191879907555,5.55269276785519,5.5604779323150675,5.5677643628300215,5.576491222541474
```
[Answer]
# [M](https://github.com/DennisMitchell/m), ~~9~~ 8 bytes
```
ŒP½ḅ1QṢḣ
```
[Try it online!](https://tio.run/##ARgA5/9t///FklDCveG4hTFR4bmi4bij////MTA "M – Try It Online")
Outputs the exact values (in the form `sqrt(n)`, and by composing these with products and sums). Very similar to [hyper-neutrino's answer](https://codegolf.stackexchange.com/a/228985/66833), but doesn't fail due to floating point errors.
Outputs the first \$k\$ elements of \$R\_k\$.
This times out on TIO for \$k \ge 10\$.
-1 byte (indirectly) thanks to [DLosc's SageMath answer](https://codegolf.stackexchange.com/a/228994/66833), so be sure to give that an upvote
## How it works
```
ŒP½ḅ1QṢḣ - Main link. Takes k on the left
ŒP - Powerset of [1, 2, ..., k]
½ - Square root of each; [[], [1], [sqrt(2)], ..., [1, sqrt(2), ..., sqrt(k)]]
ḅ1 - Convert each from base 1, summing them
QṢ - Remove duplicates and sort
ḣ - Take the first k elements
```
[Answer]
# [SageMath](https://www.sagemath.org/), 62 bytes
```
lambda k:sorted({*map(sum,powerset(map(sqrt,range(k+1))))})[k]
```
SageMath is a computer algebra system built on top of Python--the right choice if you want Python syntax without Python floating-point errors. Outputs exact values, written like `sqrt(2) + 1`, 0-indexed starting with `0`. [Try it here!](https://cocalc.com/projects/34d6aa91-6272-4118-a3c7-52941e986322/files/Welcome%20to%20CoCalc.ipynb?session=default)
### Explanation
Uses the "powerset of the first several square roots" approach:
```
lambda k: Anonymous function that takes an index k
[k] and returns the kth element
sorted( ) of the following list sorted ascending:
range(k+1) List of integers from 0 through k inclusive
map(sqrt, ) Square root of each
powerset( ) All possible subsets of the list of square roots
map(sum, ) Sum of each subset
{* } Splat that list into a set, removing duplicates
```
(Passing a set to `sorted` automatically casts it to a list in Python--TIL.)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~44~~ 42 bytes
1-indexed, output includes `0`. First duplicates are removed, then numbers are converted to a numerical value to make the sorting shorter.
```
Sort[N[{}⋃Tr/@√Subsets@Range@#]][[#]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pzi/qCTaL7q69lF3c0iRvsOjjlnBpUnFqSXFDkGJeempDsqxsdHRQELtf0BRZl5JtLKOgpKCrp2Cko5CGlhcQd9BAaLU8j8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~261~~ ~~169~~ 157 bytes
*Edit: substantial code golfing at the expense of now running painfully slowly for any input higher than 6 (although the underlying algorithm should still be valid if given sufficient time & resources)*
```
function(x)sort(rowSums(unique(t(apply(expand.grid(rep(list(unlist(sapply(-1:x+1,n))),x+1)),1,sort)))^.5))[x]
n=function(x,y=2)`if`(y<x,if(x%%y^2)n(x,y+1),x)
```
[Try it online!](https://tio.run/##VY7dCsIwDIXvfY9BgnHQgV4M9xS7FPeDW6Uw264/2D59rVMQb3IS8p2TmGT9w/aK93Y1zjaJe3lzQkkIaJVxYNSzzQR4KVY/g4NR6yXCHPQop/JuxARm1rAI6zKzif0gB1aHPSOJiJSbXBm9I/PclUfES7juZPO7R7GpcBB8gHgOJDiEoohdhdsq@ylg@kaz@kR/f2N6AQ "R – Try It Online")
Base [R](https://www.r-project.org/) *is* subject to floating-point inaccuracies, so this rather long code attempts to avoid these by first constructing a list of lists of integers from which to sum the square-roots, in such a way that 'clashes' are avoided.
**How?**
We first note that 'clashes' - when a number can be expressed as the sum of square-roots of integers in two different ways - happen for composite numbers with repeated prime factors.
For instance:
`sqrt(4) = sqrt(2x2) = 2*sqrt(1) = sqrt(1)+sqrt(1)`
Or:
`sqrt(18) = sqrt(2x3x3) = 3*sqrt(2) = sqrt(2)+2*sqrt(2) = sqrt(2)+sqrt(8)`
So, we first remove integers with repeated prime factors:
```
no_repeated_factors=
n=function(x,y=2)`if`(y<x,if(x%%y^2)n(x,y+1),x)
```
We then generate a list of all lists of combinations of non-negative integers that sum any integer value up to `x` (so, all combinations of `x` elements of `0...x`), excluding those with repeated prime factors (this step is pretty slow & greedy):
```
combinations_of_integers_without_repeated_factors_that_sum_to_up_to_x=
b=unique(t(apply(expand.grid(rep(list(unlist(sapply(-1:x+1,n))),x+1)),1,sort)))
```
The sums of square-roots from this list shouldn't give any 'clashes', so now we can just use all these lists of lists of integers that sum to `1...x`, calculate the sums of square roots, sort, and output the `x`-th one:
```
sums_of_sqrts=
function(x)sort(rowSums(b(x)^.5))[x]
```
Omitting the final `[x]` allows us to inspect the list of sums of square-roots - [click here](https://tio.run/##VY/NCsIwEITvvoWHwi6ulRb0IOYpvPcH20igJml@MOnLx1QF8bK7w37MMCZZ/7Ct4q2djbMscS9vTigJAa0yDox6XjMBXorZj@Cg13qKMAbdy6G8GzGAGTVMwrrMvJf9IPvqHHYVSUSkfORZ0WqZdVMeETeS/cIospoWFrATvIN4CSQ4hKKITY35fYjNdlUUsxEtmL4Z1flEfwUwvQA) - to check that the 'clashes' have been correctly removed, although at high indexes there will obviously be some missing values that will only get added when higher values of `x` are used.
There's probably a slicker way to do this... (particularly in languages with built-ins for finding prime factors or generating integer partitions).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 70 bytes
```
->n{r=(0..n).map{|x|x**0.5};r.product(*[r]*n).map(&:sum).uniq.sort[n]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vushWw0BPL09TLzexoLqmoqZCS8tAz7TWukivoCg/pTS5REMruihWC6JAQ82quDRXU680L7NQrzi/qCQ6L7b2f4ECyAgzqIo0zf8A "Ruby – Try It Online")
0-based, returns n-th number, very slow for n>6.
[Answer]
# [GNU-APL](https://www.gnu.org/software/apl/), 56 bytes
```
k←15◊a←{⍉(⍵⍴2)⊤⍳2⋆⍵}k◊b←{+/a[⍵;⍳k]/(1↓⍳k+1)*0.5}¨⍳2⋆k◊k↑b[⍋b]
```
```
a←{⍉(⍵⍴2)⊤⍳2⋆⍵}k ⍝ Power Set Matrix - every row is a selector
b←{+/a[⍵;⍳k]/(1↓⍳k+1)*0.5} ¨ ⍳2⋆k ⍝ for every row find the sum of sqrt of selected elements
k↑b[⍋b] ⍝ sort and take k elements from b
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Returns the `n`th term, 0-indexed and including `0`
```
gUô¬à mx â ñ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z1X0rOAgbXgg4iDx&input=OA)
```
gUô¬à mx â ñ :Implicit input of integer U
g :Index into
Uô : Range [0,U]
¬ : Square roots
à : Powerset
m : Map
x : Reduce by addition
â : Deduplicate
ñ : Sort
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
∞ætOê
```
Outputs the entire sequence. Takes an infinite amount of time to generate the sequence, but works in theory.
```
∞ætOê # full program
O # push list of sums of...
# (implicit) each element in...
t # square root of...
# (implicit) each element in...
# (implicit) each element in...
æ # powerset of...
∞ # [1, 2, 3, ...]...
ê # sorted without duplicates
# implicit output
```
] |
[Question]
[
You'll get a human-readable question *matching one of the following syntaxes*, and are expected to print/return the corresponding result. Finding similarities between the human-readable inputs and matching them with minimum size code is explicitly part of the task, so I won't give a formal definition.
* "Will October begin on a Thursday if this year is a leap year, this month is January and this month begins on a Wednesday?" > **"Yes."**
* "If this month begins on a Friday, this month is October and this year is not a leap year, will December start on a Tuesday?" > **"No, it will be a Wednesday."**
* "If this month is August, this month begins on a Wednesday and this year is not a leap year, will October start on a Sunday?" > **"No, it will be a Monday."**
* "Will December start on a Monday if this month begins on a Friday, this year is a leap year and this month is November?" > **"No, it will be a Sunday."**
**"Formal" definition:**
Input will always be generated by picking one of the above lines and swapping day names, month names, and the "not " in and out of "is \*a leap year"
**Further notes:**
* Each question will consider only one calendar year, i.e. you won't be asked for a date of the following or previous calendar year.
* This is **codegolf**, shortest answer in bytes in each language wins.
* In case you need it, remember leaps years are *not* strictly every 4 years.
* No answer will be accepted.
* Standard loopholes apply.
* You can input and output in any reasonable way.
**Just for reference:**
* 'January', 'February','March','April', 'May','June','July','August', 'September','October','November','December'
* 'Monday','Tuesday', 'Wednesday','Thursday', 'Friday','Saturday', 'Sunday'
Inspired by Squarish's Kata on codewars.com
[Answer]
# JavaScript (ES6), 254 bytes
```
s=>(F=e=>'0x'+'0A39135?2B?8602467'[parseInt(s.match(e+' ([A-Z]\\w+)')[1],33)%234%81%19],n=(F`s.{5}`-(g=m=>new Date(~F`(no|le).*`,m).getDay())(F`s`)+g(F`l`)+7)%7)-F` .{9}a`?`No, it will be a ${'Sun,Mon,Tues,Wednes,Thurs,Fri,Satur'.split`,`[n]}day.`:`Yes.`
```
[Try it online!](https://tio.run/##jZJhb9owEIa/8yssNBR7MRaQtpRNIWKikTpp3YdWQluIZDc4IVNiI9spQ4z9deaEsrFqqPv02r7Le8/d5Rt7YjpR@cp0hVzwfervtT@Goc/9sdP77rhOb@KN@t5lMPgQXF/1BhdXQydaMaX5rTBQk5KZZAm56wAYTbpf4/l87SIHRf0Yex7qDLyLznW/0x/FWPgwpJpsL3e0CzO/9MeCr8GUGQ5/hhQK@aPgiLyluEQk42bKNhCh@hOK3MxqYXWIOkPUDSkg29GO0YDeSQxyA9Z5UYBHDhh4s3XuK4E/SYEfKq7xjC@ElYdlpTQOVY7vmamUQ/SqyA3FNBLxbsE2hL6jX7gmdP8@agHQntWGnxMjH7myxlkugBTWvvGx@SBPgVnmGmw4U8AqAwVnq@aKD5FSCrOsQx@ZqJjaACYWp5HGVR9sD5TWN2jjuvxtei7TtmDTXpY4kv4uccQS0vyN1kxqyhNe1vnaMGWeO6vOA9jDpMoqbfCrDfwvwpH4hMDu7Q/A7Byn3ezp/F@Z0D/W83IP9nAnn5o6QbsVt0gq1Q2zP7UG/hgkUmhZcFLIzD64wJkLx0oKNXq@IbT/BQ "JavaScript (Node.js) – Try It Online")
### How?
Given the leading part `e` of a regular expression, the helper function `F` looks for the capitalized word that immediately follows and turns it into either a 0-indexed day (from 0 = Sunday to 6 = Saturday) or a 0-indexed month (from 0 = January to 11 = December).
```
F = e => // e = regular expression part, as a string
'0x' + // parse as hexadecimal
'0A39135?2B?8602467'[ // a digit between '0' and 'B'
parseInt( // selected by 1) parsing
s.match( // the sub-string in s that matches
e + // the leading part of the regular expression
' ' + // followed by a space
'([A-Z]\\w+)' // followed by a capturing group for
)[1], // a capitalized word (which is what we keep)
33 // in base 33
) // end of parseInt()
% 234 % 81 % 19 // and 2) applying a modulo chain
] // end of digit lookup
```
[Try the hash function online!](https://tio.run/##VdBLS8NAEAfwez/FEpBkaQx51NpSaonYgoXqIQUPIYftZtJE4m7YR1HEzx43jwpeZn7zZ5mFeScXIqmoGnXLeA5tsW4lWj8g2/@00dS0OFoG0d0mfNws5n44m9/baUOEhGemHOmiKMLoBoXRzNRFYEqwzNpVOkEotfaEaSK@LNfawUmMPBBBS9PjRlR1P3fpXjPoW91NsT5rqQwSaBR8nEAYv1LFB73wyzV8Ajowc/svE83yfuGBjzhqkIPeIGdXH0stRu5ENSAhSouO4y7GTViDlU2yiVdwsSW0dEh3nG9E/oL@WpQzyWvwan52pNeQfMtyJ/Cxi6aFIzHGq39PzPiD218)
We invoke `F` with:
* `"s.{5}"` to match `"begin**s on a [day]**"`
* `"s"` to match `"i**s [month]**"`
* `"l"` to match `"wil**l [month]**"` (the `w` may also be capitalized)
* `" .{9}a"` to match either `" **start on a [day]**"` or `" **begin on a [day]**"`
* `"(no|le).*"` to match either `"**no**t"` or `**"le**ap"`, whichever comes first (this is a special case where the capitalized word is put in a 2nd capturing group and ignored)
The helper function `g` takes a month and returns a week day in `[0..6]`:
```
g = m => new Date(~F`(no|le).*`, m).getDay()
```
The expression `~F`(no|le).*`` in there evaluates to `-1` if `"no"` is matched (not leap) or to `-4` if `"le"` is matched (leap). This works as expected because the year `-4` is leap1 and the year `-1` is not.
Using `g` and the data collected above, we create two dates in the same reference year and look for the difference between the corresponding week days, modulo 7. This allows us to answer the question.
---
*1: At least that's what JS thinks. [But this is apparently not true](https://en.wikipedia.org/wiki/Julian_calendar#Leap_year_error).*
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 292 bytes
```
no.*
$&~
Feb(?=.*~)|Mar|N|Sa
4
F|Au
3
Ma|Th
2
O|We
1
A|Jul|T
0
Se|D|M
6
Ju|S
5
J(?=.*(~))?
$#1
(.+)(w.+)
$2$1
( is \d)(.+)
$2$1
.+(\d).+(\d).+(\d).+(\d).*
$2;$2$4,777$1$3
\d
$*
(1*),\1
1*;(1{7})+$
Yes.
;
(1{7})+(1*)
No, it will be a $.2day.
6
Mon
5
Sun
4
Satur
3
Fri
2
Thurs
1
Wednes
0
Tues
```
[Try it online!](https://tio.run/##jVHda8IwEH@/vyKwbKS1lFXdfJAhgjgmqA8tyMCHRRttQdORJhNZ5r/urvUDJ4p7Cbm7H7@POyV0Kvn2nr1@bGXmu0AfNtAVE9Z68d2NY/tc2YENOdSha9sGatDnNkqgCkM7EhBA2/bMwkbwCKGwHduHZ@gZG8IT9EoOtnGcFtC7AJhfcdgKH6BViiVJczKOHXbs@BWG9YUXXVWbCKl7jUaDBrQG4xioCyxwHW8cAARukwXfjR@nQuFd5D40AfaNAgODzCOpJqt0sSATQTihfjXmax/N9jOJXkMjMWHItVEYsatSDBglRuWYcCRiKXIMGBmRb7ejgmQ41dlEKCSbp5JkEilLOJKSdEZ0gtnWgqsiIycLwT/L0ttNlpnUSTHqcWm4WhMu49NJyZrvaHfqyNuCt9k1EBpGxDn7weSR/eBIZvqvq3IxHTEVywKfa670PpS5qI2ftpmbXHs3bf9X/WD2RByPUmqPrrnD250u/MZeLtzjfPH4GWRfpU7rFw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
no.*
$&~
```
If this is no(t) a leap year, then suffix a `~`, so that we can adjust the relative offsets of January and February.
```
Feb(?=.*~)|Mar|N|Sa
4
```
The relative offset of February, when not in a leap year, is the same as March and November.
```
F|Au
3
```
But in a leap year, it's the same as August. And with my arbitrary numbering convention based on Tuesday, it's also the relative offset of Friday.
```
Ma|Th
2
O|We
1
A|Jul|T
0
Se|D|M
6
Ju|S
5
```
Similarly for the remaining months and days of the week.
```
J(?=.*(~))?
$#1
```
January's offset is simply the count of `~`s.
```
(.+)(w.+)
$2$1
```
If the `will (Month) start on (Day)` is not at the beginning, then move it there.
```
( is \d)(.+)
$2$1
```
If the `month is (Month)` is not at the end, then move it there. This means that the order is now (target month offset), (target day offset), (source day offset), (source month offset).
```
.+(\d).+(\d).+(\d).+(\d).*
$2;$2$4,777$1$3
```
Form the values (target day offset); (target day offset) + (source month offset), 11 + (target month offset) + (source day offset). The 21 ensures that the difference is at least 7.
```
\d
$*
(1*),\1
```
Convert the values to unary so that the difference between the sums of offsets can be taken.
```
1*;(1{7})+$
Yes.
```
If the difference is zero (modulo 7), then the offsets matched, so that the target day is correct.
```
;
```
Add the difference to the target day offset to get the correct day offset.
```
(1{7})+(1*)
No, it will be a $.2day.
```
Convert the day offset (modulo 7) back to decimal.
```
6
Mon
5
Sun
4
Satur
3
Fri
2
Thurs
1
Wednes
0
Tues
```
Decode it into a day of the week.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~331~~ ~~318~~ ~~316~~ ~~289~~ 290 bytes
*-13 bytes by having the weekday function spit out a string which can be compared directly to the natural-language word given.*
*-2 bytes by removing a -2 offset in weekday calculation.*
*-27 bytes with an alternate method of converting a month name to a number from 1 to 12.*
*+1 byte to correct a typo.*
```
l);" and if"4/{/',*}/',/{S/(;}/_0='w#{]:\}&[)\-4={A="bMAanlseovc"#))}:R~]])\{_-2=0="lia"#"3=c'a=W=R:M;W=:O;"6/=~}/:L;[M0]{))+_{[~_2$3<_!-2*@@- 4/_25/_4/\W*](23*9/+:+7%"Fri Satur Sun Mon Tues Wednes Thurs"S/="day"+}:T~\_1=1e2md_4%!\!@4%!*-L=@O=*!}g)@(\@+T_@="Yes"@"No, it will be a "\+?\;'.+
```
[Try it online!](https://tio.run/##TVBNb4JAEP0r41qLgHQVaZtCN@KlByM1URPSuGSz6lZpcGn4qDEE/jpd66WXeZP3ZubNzO6Ln9o20T0EXO4h/kQOrrA2MGoVcLXCfa/GbEi0c7eKXFrfb3RqOaSaErQNplwmuUh/dqir67W7bKJIpxWzbDIkKIk56qIx2WmchGTpBl5I3IWHnjBpauzOvU0wjCpdN1m1aZh9N35lHcs2fN8CBzP7ETMH09CI@vbYeMGmaz730FsWw4oXZQarUkKQSliXIodQ7KWC9bHMcrTCBO35BZm1u24oG5GRsE975vQ6tOOraFhz4i@I0akPut@nvrlmPkEfIkc@ek8HEBdwjpMEtgI4IGpOqKc9mG0bXslZKQXkBc8KUOb8uobyUm@D4hjncBE8A4UyLZSYCP79Rw1u6imVxVHNPcQyv7WrC67t18//q1DJjMuSZ5fJLw "CJam – Try It Online")
Oh boy. This was a doozy.
Quick write-up:
```
l); e# Read input, and remove question mark.
" and if"4/{/',*}/',/ e# Replace " and" and " if" with commas, then split into clauses.
{S/(;}/ e# Split each clause into words, and remove the first "word".
e# (It will be "If" or "Will" if they are capitalized, empty otherwise.)
_0='w# e# If "w" is not the last clause's first word's first character...
{]:\}& e# ...the "will" clause is not on top; bring it to the top.
[ e# We will parse its month and weekday, and put them in an array.
) e# Raw weekday string from input.
\-4={A="bMAanlseovc"#))}:R~ e# Month to number by looking up the character "at" index 10.
e# (If month name is less than 11 chars, the index wraps around.)
] e# Now we've collected these into an array.
])\ e# Collect clauses in array and bring to top.
{_-2=0="lia"# e# Use the first character of the second-to-last word in the clause...
"3=c'a=W=R:M;W=:O;"6/ e# ...to index into one of three pieces of 6(-ish)-character code...
=~}/ e# ...to run on each clause to extract the relevant information.
:L; e# Now O has the weekday, M the month, and L the leap-year status.
[M0]{ e# We'll use M to get the first year that matches the criteria.
))+_ e# Increment the year, and put it back in the array.
{[~_2$3<_!-2*@@- 4/_25/_4/\W*](23*9/+:+7%"Fri Satur Sun Mon Tues Wednes Thurs"S/="day"+}:T~ e# Weekday of day 1, given [month year].
e# (Algorithm adapted from http://cadaeic.net/calendar.htm)
\_1=1e2md_4%!\!@4%!*- e# Check if year is leap year.
L=@O=*!}g e# Run this loop until leap-year and weekday criteria match the year.
)@(\@+T e# Get weekday of requested month with calculated year...
_@= e# ...then compare it with requested weekday.
"Yes"@"No, it will be a "\+?\;'.+ e# Choose the right string based on the weekday.
```
### Alternate 290-byter
This works in almost the same way, except it uses a LUT to determine the month offset in the weekday calculation, instead of math.
```
l);" and if"4/{/',*}/',/{S/(;}/_0='w#{]:\}&[)\-4={A="bMAanlseovc"#}:R~]])\{_-2=0="lia"#"3=c'a=W=R:M;W=:O;"6/=~}/:L;[M0]{))+_{[~_2$1<- 4/_25/_4/\W*](2457931901 7b=+:+7%"Fri Satur Sun Mon Tues Wednes Thurs"S/="day"+}:T~\_1=1e2md_4%!\!@4%!*-L=@O=*!}g)@(\@+T_@="Yes"@"No, it will be a "\+?\;'.+
```
[Try it online!](https://tio.run/##TVBdb4JAEPwr61mLgPYEsUboRXxp0kRqIiSk8cjlRFQahIaPGkPgr9tTX/oyu5nNzsxu@M1P12siWwh4uoN4jwxcY2mgNAJw7eK@1WA2ItK5WwcmbZ43Mh0apF4QtHUWPE2KKPsNUbcx120QyLRmQ52MCEpijrpoTEKJE5@sTcfyibmy0CsmbYPNpbVxRkEtyyqrNy3Tn7S3IRiY6RPMDEx9JejrxmQ6G2uzkQbTLVFNddpD73kMLi@rHNwqBSdLwauiAvxol4riHau8QC4maMcvSG1Mr6VMI1qkn3bM6HVoxxaoDJfEXhGl0xxku09t1WM2QV9RgWz0mQ0gLuEcJwlsI@CAqDqnlvSiXq8feyiPcQGnLC2PYnqI0wJEAn7LIQwH/8eicXgeHu9PvfOXiOc3Os1KsZJE/OdODR5mi@pQFSUUJc/Lh6g4UIjO/wA "CJam – Try It Online")
### Random snippets
Some fun little snippets to experiment with on your own:
`[~_2$3<_!-2*@@- 4/_25/_4/\W*](23*9/+:+7%` - takes `[month year]` on stack, returns weekday with Friday=0 to Thursday=6
`1e2md_4%!\!@4%!*-` - takes `year` on stack, if result is nonzero then that is a leap year
`60b73%W*7,=` - takes capitalized weekday string on stack, returns index into week with Wednesday=0 to Tuesday=6
`134b395%7%` - same as above, but with Tuesday=0 to Monday=6
`75b501%8%` - same as above, but with Saturday=0 to Friday=6
`4b502%9%` - same as above, but with Sunday=0 to Saturday=6
`A="bMAanlseovc"#` - takes `month` on stack, returns month number with January=-1 to December=10
] |
[Question]
[
A Latin Square is a square of size **n × n** containing numbers **1** to **n** inclusive. Each number occurs once in each row and column.
An example of a 3 × 3 Latin Square is:
```
[[1, 2, 3],
[3, 1, 2],
[2, 3, 1]]
```
Another is:
```
[[3, 1, 2],
[2, 3, 1],
[1, 2, 3]]
```
Given an integer input **n** where **n > 0**, determine how many Latin Squares there are with a size **n × n**, where the possible values are anything from **1** to **n** inclusive.
## Examples:
```
1 -> 1
2 -> 2
3 -> 12
4 -> 576
5 -> 161280
6 -> 812851200
7 -> 61479419904000
11 -> 776966836171770144107444346734230682311065600000
```
This is OEIS sequence [A002860](http://oeis.org/A002860). It has a Wikipedia article [here](https://en.wikipedia.org/wiki/Latin_square).
Answers are only required to support inputs up to 6, due to anything above that being greater than 232. However, while this is not strictly enforceable, your *algorithm* must work for all inputs.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~67~~ ~~56~~ ~~50~~ 48 bytes
```
D[Permanent@a^n,##]&@@Join@@(a=x~Array~{n=#,#})&
```
[Try it online!](https://tio.run/##Rcy9CsIwEADgVzkIlAoH4u8WuFJx6NQ9RDgkYKC5QLiCUtpXj25O3/Yl1ldIrPHJdfohfZ5Fbb25MZTEEkSJH4LG@IZoyFGIWrbvrSuFP9si1qBZd00dSxR1fZ7mJPdckvtvsCdYDghHhBPCGeGCcF29r18 "Wolfram Language (Mathematica) – Try It Online")
Uses Theorem 5.1 in [this article](http://www.combinatorics.org/ojs/index.php/eljc/article/view/v17i1a1): if X is an *n* by *n* matrix whose entries are distinct variables, then the number of *n* by *n* Latin squares is equal to the coefficient of the product of all these variables in per(X)*n*, where per(X) is the [permanent](https://en.wikipedia.org/wiki/Permanent) of X. Here, we obtain that coefficient by differentiating with respect to all of the variables, once each (which leaves a constant).
Regarding running time: TIO was happy to deal with inputs 1 through 6, and my laptop can handle 7 in a bit over 6 minutes. I didn't try 8.
Choice quotations included in the article about this formula's practicality:
>
> The use of MacMahon's result by mere mortals seems doomed.
> – Riordan
>
>
> One should not wish to actually perform, even in a computer algebra package like Maple, MacMahon's counting method.
> – Van Leijenhorst
>
>
>
# Another Mathematica solution, 52 bytes
```
LineGraph@CompleteGraph@{#,#}~ChromaticPolynomial~#&
```
Much less efficient (only inputs 1 through 4 are viable) but somewhat more readable.
Uses the fact that Latin squares of size *n* are precisely the *n*-colorings of the *n* by *n* [rook's graph](https://en.wikipedia.org/wiki/Rook%27s_graph), which is the [line graph](https://en.wikipedia.org/wiki/Line_graph) of the [complete bipartite graph](https://en.wikipedia.org/wiki/Complete_bipartite_graph) K*n*,*n*, and is an excellent example of Mathematica's occasional tendency to look like a natural-language explanation of the algorithm with prepositions replaced by random symbols.
In practice, `GraphData@{"Rook",{#,#}}~ChromaticPolynomial~#&` is only 47 bytes and works for all feasible inputs, but it fails to satisfy the criterion of being a general algorithm (since `GraphData` hardcodes small rook graphs, but does not generate arbitrarily large ones).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Œ!ṗµfZ€L
```
Brute force solution. Inputs **5** and higher will time out on TIO.
[Try it online!](https://tio.run/##y0rNyan8///oJMWHO6cf2poW9ahpjc9/k6BDW4/uOdwO5Lj/BwA "Jelly – Try It Online")
### How it works
```
Œ!ṗµfZ€L Main link. Argument: n
Œ! Generate all permutations of R := [1, ..., n].
ṗ Take the n-th Cartesian power, yielding the array A of all n×n matrices
whose rows are permutations of R.
µ New chain. Argument: A
Z€ Zip each; transpose each matrix in A, yielding the array B of all n×n
matrices whose columns are permutations of R.
f Filter; keep only matrices that appear in A and B.
L Compute the length, counting the kept matrices.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
l@K^.pQQCMK
```
**[Try it here!](https://pyth.herokuapp.com/?code=l%40K%5E.pQQCMK&test_suite=1&test_suite_input=1%0A2%0A3&debug=0)**
## How it works
```
l@K^.pQQCMK - Full program.
.pQ - All permutations of the range [0, input).
^ Q - To the Cartesian power of the input.
K - Assign to a variable K.
@ - The intersection of K.
CMK - With the list of all elements in K transposed.
l - Length.
```
As this is brute force, anything higher than **4** will Memory Error on Herokuapp or time out on TiO.
[Answer]
# [Python 2](https://docs.python.org/2/), 91 bytes
```
f=lambda n,k=0,s={''},x=0:k<n*n>x and f(n,k+1,s|{x+k/n,~x-k%n})+f(n,k,s,x+n)or len(s)>n*n*2
```
[Try it online!](https://tio.run/##HYxBDoIwFAXXeoq/IVD6jVB2xHKXGmwkxQehLGoAr16r25nMzO/1OUHFaPVoXvfeENjpir3e8vzgoKvW3VCiC2TQky2SljX7fQvSXcGfcHEZDiH/hj0HCTEtND5QeNGlslTRJgAaQDUrbtrzaV4GrL@ZiM0X "Python 2 – Try It Online")
---
**[Python 2](https://docs.python.org/2/), 102 bytes**
```
lambda n:sum(all(len({(k/r%n,i/n**k%n)for k in range(n*n)})/n/n for r in(1,n))for i in range(n**n**2))
```
[Try it online!](https://tio.run/##TcpBCsIwEEbhtZ5iNoWZEAhNdwVv4iZioyHp3zLWhYhnj40r4e2@t762@wJf4@lcS5gv10AYH8@ZQylcJvCbs9MONjkYkztIXJQyJZAG3CaGgXzEwYGa6C7cW8jvS/@f2fMitQEa9NbbYTweVk3YKDKkDl8 "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~138~~ ~~134~~ 124 bytes
```
from itertools import*
def f(n):r=range(n);print sum(map(set,zip(*m))==n*[set(r)]for m in product(permutations(r),repeat=n))
```
[Try it online!](https://tio.run/##DYyxCkIxDAB3vyJjUt4kTkq/RByKL9WCTUKaN@jP127HcZx9461ynrO6dmjBHqqfAa2beqTTzhUqCl09e5EXL7yZNwkYR8deDAfH9muGqRPlLOm@BDo9qjqso4C57scz0Nj7ESWayljB5mxcIgvRrHih@Qc "Python 2 – Try It Online")
Brute forces, very slow. Works for `n=1..4` on tio
[Answer]
# Mathematica, 102 bytes
```
Length@Select[Subsets[Permutations@Range@#,{s=#}],Union[Sort/@Table[#[[i]]&/@#,{i,s}]]=={Range@s}&]s!&
```
[Try it online!](https://tio.run/##TcvLCoMwEIXhfZ8iRcgqIL1sA3mALqS2q2EWUUYNaARnXEmePbUUiruPw38mLwNNXkLrc6esyg@KvQyuppFagXptmIShomVaZc/myO7pY0@uMBvbIqF5x32Fel6kdC/fjAQFQEDU5bcJhhOitdvvxUkjn3WulhBFuQ4uePr7evDt4DvmDw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 90 bytes
Brute force!
```
->n{x=[*1..n]
y=*x.permutation
y.product(*[y]*~-n).count{|a|a.transpose.all?{|b|x-b==[]}}}
```
[Try it online!](https://tio.run/##JcXBCgIhEADQu1/RsQQHtrpaHyJz0G0Xgm0UdwRF7deN2Hd5MbkyVj3Ug2rWRk4AhKJomSEs8ZPY8tuTKBCif6WZz9IUlF9FF5h9Iq7NNgscLe3B7wvYbXvW5lpWTmuDvfcRTquZUPy7Ht2O7jh@ "Ruby – Try It Online")
] |
[Question]
[
A slightly more challenging one compared to my previous challenge. Given a list of positive integers (>0) and the positive integer `m`, output a list of positive integers that are capped values of the input values so that the sum of the capped values equals `m`. Cap the highest values first. And keep the same order.
**Cases**
(Given 'list' and 'sum' output 'list')
* Given `4, 2` and `6` output `4, 2` no capping needed (ncn), keep order (ko)
* Given `2, 4` and `6` output `2, 4` ncn, ko
* Given `3, 3` and `6` output `3, 3` ncn
* Given `3, 3` and `7` output `3, 3` ncn
Then this:
* Given `4, 2` and `5` output `3, 2` cap the highest (cth), ko
* Given `2, 4` and `5` output `2, 3` cth, ko
* Given `3, 3` and `5` output `3, 2` or `2, 3` cap any of the highest (cath)
Then this:
* Given `5, 4, 2` and `10` output `4, 4, 2` cth, ko
* Given `2, 4, 5` and `10` output `2, 4, 4` cth, ko
* Given `4, 4, 2` and `7` output `3, 2, 2` or `2, 3, 2` cth, cath, ko
* Given `4, 2, 4` and `7` output `3, 2, 2` or `2, 2, 3` cth, cath, ko
Then this:
* Given `4, 4, 2` and `5` output `2, 2, 1` or any permutation (oap)
* Given `2, 4, 4` and `5` output `1, 2, 2` oap
* Given `4, 4, 2` and `4` output `1, 2, 1` oap
* Given `2, 4, 4` and `4` output `1, 1, 2` oap
* Given `70, 80, 90` and `10` output `3, 3, 4` oap
Then this:
* Given `4, 2, 4` and `2` output an error or a falsy value, because the sum of 3 positive integers cannot be 2.
**Rules**
* Both input and output are all about positive integers (>0)
* The number of values in the input and output list are equal.
* The sum of the output values is exactly equal to `m` or less than `m` only if the sum of the input values was already lower.
* If the sum of the values in the input list is already lower then or equal to `m`, no capping is needed. (ncn)
* Cap the highest values first (cth)
* When multiple values are the highest value and equally high, it doesn't matter which you cap. (cath)
* The capped values in the output list have to be in the same order as their original values in the input list. (ko)
* When at some point (thinking iteratively) all values are equally high, it stops being important which you cap.
* If there's no solution output an error or a falsy value.
**The winner**
The shortest valid answer - measured in bytes - wins.
Apart form the rules, I'm interested to see a program that keeps a value intact as long as possible. Consider the input values a plant each with the heights `10,2,10` and the maximum `m`=5, it would be a waste to cap the baby plant in the middle.
[Answer]
# [Python 3](https://docs.python.org/3/), 70 77 56 bytes
-21 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!
```
def f(l,n):
while n/all(l)<sum(l):l[l.index(max(l))]-=1
```
[Try it online!](https://tio.run/##dVDLboMwEDzDV@wNW9q0hEdpUdJTe@gvFHGIGqNY2tjIkIR8PbUdoFx62tl5Haa99yet0nE8igYaRqh4GcLtJEmAej4QMeK77nK2p6SKnqQ6ioGdD4MleL3Zb8dGG7A5UBykAsaqDJMaXziyKsFsQimma1Q45H354ssX1aMcvb6NJwPm85M9lLnDZYsVPzcunROfrXiPixhfY3yL/3p9V8LtAgF9KdgDVWUdBr25WyZ4rBMGYvgRbQ/fwugPeZWd1OrTGG2cpzVS9YzZtBsEIdq8g3Bi5ILUiX9MEQLx8Rc "Python 3 – Try It Online")
[Answer]
# PHP>=7.1, 94 bytes
```
<?for([$a,$s]=$_GET;array_sum($a)>$s;)$a[array_flip($a)[max($a)]]--;print_r(min($a)?$a:0);
```
replace `array_flip($a)[max($a)]` with `array_search(max($a),$a)` to cap the last/first item with the maximum value
[PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/c0c34f3f4c0e3be138654d790bb8b1496497a88d)
[Answer]
# Mathematica, 79 bytes
```
(u:=Plus@@a;For[a=#2,u>#,a[[#&@@a~Position~Max@a]]--];Min@a>0&&u==#||Quit[];a)&
```
Takes `sum` and `List of integers`
[Answer]
# [Haskell](https://www.haskell.org/), 53 bytes
`c` takes an integer and a list of integers, returning a list of integers. Use as `c 6 [4,2]`.
```
c n=until((<=n).sum)f
f(x:y)|any(>x)y=x:f y|x>1=x-1:y
```
[Try it online!](https://tio.run/##VY/NboMwEITvPMU2ysFWHJQfaFoLcql6qNRemmNaVSgxiVVYI2NUkPLu1DgFmpUsze58nrXPSfktsqyVeaG0gSeFRqvMf64PojBSoeflicQ4T4q3L0I@iGRIYb6Fo/LAVlGZndEwhfKsfjqT8xc0dDabdNDEMQaiORjdWEoLU2mE6R0cAEE6@5CUwjIqdV1X7/J0toMuodASrRysV5EaEKNDBOc7lYvhvZRa1tciOVI/kyjKOIpOwnT/EmjK1u6NKzQyIySKkfplldPUS0nNG3pJsCHbmjZxzVNoLvV2GdfzJW/aluwDBqtPdk89sl8xCP7kmsH6Rm46eWXDkQ1HwMnQTh2zXPQQg7Bvg94dwlzI5sYLx4v9gsELbjzXbRYMHux5XPzbcs1d0V8 "Haskell – Try It Online")
# How it works
* `c n` applies `f` to its (implicit) list argument until its sum is `<= n`.
* `f` takes and returns a list of integers. It finds the first maximum value in the list by recursing, and then reduces it by 1, unless the maximum is `<=1`, in which case a non-exhaustive patterns error is raised.
[Answer]
# [R](https://www.r-project.org/), ~~61~~ 56 bytes
*-5 bytes thanks to Leaky Nun*
```
function(l,s){while(sum(l)>s)l[which.max(l)]=max(l)-1;l}
```
Anonymous function. Returns a vector with first entry zero (falsey in R) for invalid input.
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jR6dYs7o8IzMnVaO4NFcjR9OuWDMnGiiQnKGXm1gBFIi1hdC6htY5tf/TNJI1THSMdEw0dYw0uUA8cwMdCwMdSwNNHUMDzf8A "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*Note:* this solution was ready just as the question was put on hold 33 hours ago.
```
_MḢ$¦S>¥
ç⁹$ÐLẠȧ$
```
A dyadic link returning the list of positive integers or `0`
(an error rather than `0` is also possible by moving `Ạȧ$` from the end of the second line to the end of the first line).
**[Try it online!](https://tio.run/##AS8A0P9qZWxsef//X03huKIkwqZTPsKlCsOn4oG5JMOQTOG6oMinJP///1s0LDIsNF3/Nw "Jelly – Try It Online")** or see a [test suite](https://tio.run/##y0rNyan8/z/e9@GORSqHlgXbHVrKdXj5o8adKocn@DzcteDEcpX/OoeX64erqDxqWpMFxFDUMFcHxmuYo6CmABTIgnJ0de1A3Mj//6Ojo010jGJ1zGJ1oqONdEygLGMdY2SWOYgFVmcKV2cKlwWzTHXA8oYGUAUgUQjHBCIDMwOk1xxJHGYi3EyouAmSOJhtbqBjYaBjaYAwF2yWUWwsAA).
### How?
```
_MḢ$¦S>¥ - Link 1, single conditional decrement: list a; number m
- ...subtracts 1 from the first maximal element of a if sum(a)>m
- else subtracts 0 from the first maximal element of a
¥ - last two links as a dyad (left=a; right=m)
S - sum(a)
> - greater than m? (1 if it is, 0 otherwise) - call this x
¦ - sparse application of:
_ - body: subtraction (left=a; right=x)
$ - at indexes: last two links as a monad:
M - indexes of maximal elements
Ḣ - head
ç⁹$ÐLẠȧ$ - Link: list a; number m
ÐL - loop until the result does not change:
$ - last two links as a monad:
⁹ - chain's right argument, m
ç - call the last link as a dyad (left=current_a; right=m)
$ - last two links as a monad:
Ạ - all truthy? (0 if any of the final a's elements are 0)
ȧ - logical and (if all were truthy yield the final a, otherwise 0)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
œṡṀ‘jṀ’µS>⁴µ¿¹0Ạ?
```
[Try it online!](https://tio.run/##y0rNyan8///o5Ic7Fz7c2fCoYUYWmJp5aGuw3aPGLYe2Htp/aKfBw10L7P///29uoGNhoGNp8N/QAAA "Jelly – Try It Online")
Uses iterative approach: repetitively subtract 1 from the highest element.
```
œṡṀ‘jṀ’µS>⁴µ¿¹0Ạ? - Main link. First input list, second input integer.
µ¿ - While:
S - Sum of the list
> - greater than
⁴ - second input
µ - Do:
œṡ - split list by first occurrence of
Ṁ - the maximum element
‘ - increment all
j - join by
Ṁ - maximum element
’ - increment
? - If:
Ạ - no elements are non-zero
¹ - Then: output the list
0 - Else: return 0.
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 30 bytes
```
{_2$:+<{\__:e>_@#\(t\F}{;}?}:F
```
This is essentially of a named function, F, that expects a list and a number on the stack and returns a list on the stack.
[Try it online!](https://tio.run/##S85KzP1fWPe/Ot5IxUrbpjomPt4q1S7eQTlGoyTGrbbauta@1srtf13B/2gTBaNYBTMA "CJam – Try It Online") or [run a test suite](https://tio.run/##S85KzP1fnROvZKWgpJ1f97863kjFStumOiY@3irVLt5BOUajJMatttq61r7Wyu1/XUGtoZnW/2gTBaNYBTOuaCMFEzBtrGCMoM25IPKmUHlTqDiQNlUAyxgagKUUTCFME4goRB9IhzlcDGIG1BSomAlcDMgyN1CwMFCwNACZBAA)
### Explanation
I'll refer to the list as `l` and the number as `n`.
```
_ e# Copy n.
2$ e# Copy l.
:+ e# Sum l.
< e# Check if n < sum(l).
{ e# If it is:
\__ e# Bring l to the top of stack and make 2 copies of it.
:e>_ e# Get the maximum number in l and copy it.
@# e# Bring l back to the top and find the index of max(l) in l.
\( e# Decrement max(l).
t e# Set the element of l at the position of max(l) to max(l)-1.
\ e# Swap, so now the top of the stack has the new l just under n.
F e# Call F again on the new l and n.
}{ e# Else:
; e# Delete n.
}? e# (end if)
```
] |
[Question]
[
# CAPTCHA Modified by Evil Mathematician
I accidentally incurred the wrath of an eccentric passive-aggressive mathematician. As part of his demented idea of payback, he modified the CAPTCHA system on my favorite website. Up until now, it would just ask a moderately challenging math question, like `3+2^4`, and I would simply type the answer, `19`, to verify that I am a human being. But now, thanks to my mathematical nemesis, the CAPTCHA questions are obnoxiously hard to calculate by hand and it keeps me from logging into my profile!
[](https://i.stack.imgur.com/lnwC1.png)
From what I can tell, this is what he has done. The CAPTCHA images seem to still be the same, but the way it calculates the correct answer has changed. It takes the expression displayed in the image and rotates the operations. You wouldn't believe how long it took me to figure this out T\_\_T.
Because of this fiasco, I need a program/function that takes in one of these expressions as a string, evaluates it and returns the result so that I can log onto my website! **To make this a game, fewest bytes win.**
Ok, you have the idea, lets walk through an example. Suppose that the CAPTCHA displayed an image with `6+5+4-3*2/1`. Normally the answer would `9`. Instead, we now have to rotate the operations to the right and that gives us `6/5+4+3-2*1`. At this point, we evaluate it to be `6.2`
## Summary
Steps to evaluate the string input:
1. **Rotate** the operation to the right
2. **Evaluate** the result
## Specifications
* Full program or function
* Standard I/O
* Takes an expression
* Prints/Returns the evaluated result
+ After the op rotation
* Possible operations are `+-/*^`
+ The negatives for negative numbers stays with the number when rotating
+ Follow the normal order of operations after the rotation is completed
+ Using integer division is allowed
* Possible numbers are positive/negative integers
+ This does not include `0`
* Parentheses could be included, but aren't rotated
## Test Cases
```
Input -> Output
1+3 -> 4
7+6 -> 13
1+1-2 -> 2
3*4+2 -> 11
-7^4 -> -2401
3*7+1-3 -> -1
-9+4/4 -> 1.75
(4*1)+8 -> 40
1+2-3*4/5 -> -16.5
1+-2*3 -> 1
3*4--2 -> 11
30-2/7 -> 8
120*3-4+10-> 122
(13^-12)+11 -> 1
```
**Update**
* [16-07-28] Fixed typo in last test case. I had posted the expression after rotating it once >\_\_\_> , so that rotating a second time gave an incorrect answer. It is fixed now! Thanks to @sintax!
* [16-08-13] Removed broke test case. Thanks again to @sintax!
[Answer]
# Python 3.5, ~~118~~ ~~113~~ 164 bytes:
```
from re import*
def R(U):Z='(?<!\d)-\d+|\d+|[()]';O=sub(Z,'',U);print(eval(sub(Z,'%s',U).translate(str.maketrans(O,O[::-1])).replace('^','**')%tuple(findall(Z,U))))
```
A named function. Can probably be golfed down more. This will take quite a while and apparently plenty of memory to compute the solution for the input:
```
((22^22)+2*2^2^2^2*2-2+222222+22222*-2222-2*222*2*2+2^-2+(2+2+2+2+2)+222/222+2+22*2*2)*2*2*2
```
~~I started processing this with my program about 30 minutes ago as of the time of this edit (9:52 PM on July 27, 2016) and it is still going.~~ ~~EDIT: Well, it eventually started to take up too much memory, so I had to stop it at around 1 hour after I started, at around 10:52 PM on July 7, 2016.~~
EDIT # 2: Well, even for the updated last test case it's pretty much the same thing, as it takes quite a while for my program to start finding the answer before it eventually quits out on me with error code [137](https://stackoverflow.com/questions/35116689/tensorflow-exited-abnormally-with-code-137).
[Try It Online for the Rest of the Test Cases! (Ideone)](http://ideone.com/Ue76gL)
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 30, but soon to be 16 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
```
⍎w⊣((w∊f)/w)←¯1⌽w∩f←'+-×÷'⊣w←⍞
```
Ungolfed, explained version:
`w ← ⍞` Prompt for input (of the expression) and assign to *w*
`f ← '+-×÷'` assign the symbols to *f*
`((w ∊ f) / w) ← ¯1 ⌽ w ∩ f` using membership of *f* as mask, reassign those positions in *w* to the corresponding character in the cyclic 1-step-right rotated intersection of *w* and *f* (the symbols)
`⍎w` execute the modified expression
There is no special handling of minus/negative, because APL uses the distinct symbols `-` and `¯`.
[See the rotation of symbols on TryAPL!](http://tryapl.org/?a=w%u22A3%28%28w%u220Af%29/w%29%u2190%AF1%u233Dw%u2229f%u2190%27+-%D7%F7%27%u22A3w%u2190%276+5+4-3%D72%F71%27&run)
In version 16 it will be much shorter as a function which takes the expression as argument:
```
⍎¯1∘⌽@(∊∘'+-×÷')
```
Execute `⍎` the negative one step rotation `¯1∘⌽` done on `@` members of the symbols set `(∊∘'+-×÷')`.
[Answer]
## Python 3, 195 bytes:
```
import re;I=input();x=[i for i in I if i in'+-*/^'];print(eval(''.join([i[0]+i[1]for i in[i for i in map(list,zip(*[[i for i in re.split('[+*/^-]',I)],x[-1:]+x[:-1]+['']]))]]).replace('^','**')))
```
Takes input on STDIN and leaves a number on STDOUT. I know that R. Kap already posted a Python answer, but the method I used is actually pretty interesting, so I thought I'll post this anyway.
The program first makes an the list: `[chunks splitted by math chars, math chars rotated to the right]`. It then transposes the array, flattens, converts to string, and evaluates.
[Answer]
## JavaScript (ES7), 154 bytes
```
f=
s=>[(s=s.replace(/(\(*-?\d+\)*)(.?)/g,(_,d,o)=>a.push(d)&&o,a=[])).slice(-1),...s.slice(0,-1)].map((o,i)=>a[i]+=o)&&eval(a.join` `.replace(/\^/g,'**'))
;
```
```
<input id=i placeholder=Input><input id=o placeholder=Output><input type=button value=Go onclick=o.value=f(i.value);>
```
Works by removing the values into a separate array so that the operators can be rotated.
[Answer]
## Matlab, 114 chars
Okay, so the last test case evaluates to `Inf` (once rotated, the expression 2^222222 appears...), but otherwise, all test cases hit.
Dealing with negatives, especially non-initial negatives, gave me fits.
```
i=input('');d=regexp(i(2:end),'[^\d|\)|\(]');d=d(~[0 d(2:end)-d(1:end-1)==1]);i(d+1)=i(1+d([end,1:end-1]));eval(i)
```
Inputs should be wrapped in single quotes (e.g., `'2+3/5-(12*5)'`), as per Matlab standard for string inputs.
Ungolfed and commented:
```
i=input(''); # Get input from stdin.
d=regexp(i(2:end),'[^\d|\)|\(]'); # Find the positions of non-digit/paren characters
# in the non-initial portion of the input.
d=d(~[0 d(2:end)-d(1:end-1)==1]); # If there are consecutive operator-type characters,
# assume the second is a negativity indicator and
# delete its index from our list of operator indices.
i(d+1)=i(1+d([end,1:end-1])); # Replace each non-initial operator character of the
# input with its own right-rotated operator from our
# list of operator characters
eval(i) # Evaluate the string expression we just built.
```
] |
[Question]
[
My cell phone carrier charges a cent per character in a text! I need a program to shorten the words for me, while still being understandable. I will be texting this program to my friends, so it needs to be as short as possible.
Your program will take a String (a word is separated by a non-alphanumeric character) of words from `STDIN` (or closest alternative) reduce any similar (`a` and `A` are similar, `b` and `a` are not, `1` is similar only to itself) consecutive alphanumeric characters down to one character, and remove all the vowels (`aeiou`), and print it to `STDOUT` (or closest alternative), only letters, numbers, and spaces are kept: everything else is removed at the end. The first character of a word must remain the same, and only shorten the word if the resulting shortened word is 4 or more characters long.
Examples:
```
homework -> hmwrk
llamas -> llamas (lms<4 characters)
botany -> btny
y3333llow -> y3lw
shorten -> shrtn
aabcddde -> abcd
abb'bbc -> abbbbc (abb -> abb and bbc -> bbc = abb'bbc --(remove non-alphanumeric-space characters)-> abbbbc)
SHARRRKnado -> shrknd (or with capitalization bonus: SHrKnd)
abracadabra -> abrcdbr
everything is awesome! -> evrythng is awsm
you can't break what is already broken -> you cant break what is alrdy brkn
the person's cat's bed's blanket's poka-dots are orangy-yellow -> the prsns cats beds blnkts pokadots are orngyyellow
```
-5% bonus if kept `a i o` or `u` at end of word
```
sharknado -> shrkndo
abracadabra -> abrcdbra
```
-10% bonus if kept capitalization of non-consecutive characters
```
aAbCDdDE -> abCd
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest program in bytes wins.
[Answer]
# [Japt](https://github.com/ETHproductions/Japt), 57 bytes ~~58 80 88 90 95 98~~
*Saved 6 bytes thanks to @ETHproductions*
**Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545)
```
Uv qS m@(A=Xg0 +Xs1 r"(.)\\1+",@Y r"[aeiou]",P)g3 ?A:X)qS
```
Uses RegExp to do most of the work.
[Try it online](https://codegolf.stackexchange.com/a/62685/40695)
## Explanation
This explanation is old but the method used is still generally the same.
```
UqS // Splits input
m@ // Loops through words
Xr"(.)\\1+","$1" // Removes consecutive sequences
r"[aeiouAEIOU]",P // Removes vowels
m@ // Loops again
Xl >3? // If length of word is greater than 3
X[0]==UqS [Y][0]? // If first letter is right, keep it
X
:UqS [Y][0]+X // Otherwise, use the correct first letter
:UqS [Y] qS v // Otherwise return the original word
```
[Answer]
# [TeaScript](https://github.com/vihanb/TeaScript), 60 [bytes](https://en.m.wikipedia.org/wiki/ISO/IEC_8859) ~~64 58 63 70~~
```
xL¡l»(b=l0+lS(1)g(/(.)\1+/,"$1")g`[aeiou]`)n>3?b:l,ø)O`a-z `
```
I should be able to use the unique function to get rid of repeated characters but for now I'm using a regex.
I believe this should work fine. I'll be heading off to sleep so notify me if anything is wrong and I'll address it next morning.
### Ungolfed
```
xL()l(#(b=l0+lS(1)g(/(.)\1+/,"$1")g`[aeiou]`)n>3?b:l,` `)O`a-z `
```
[Answer]
# CJam, 54 bytes
```
qelS/" ,"*__eu&S-A,s-NerN%{_(\"aeiou"-+e`1f=_S-Z>\@?}/
```
Try [this fiddle](http://cjam.aditsu.net/#code=qelS%2F%22%20%2C%22*__eu%26S-A%2Cs-NerN%25%7B_(%5C%22aeiou%22-%2Be%601f%3D_S-Z%3E%5C%40%3F%7D%2F&input=y3333llow) or [this test suite](http://cjam.aditsu.net/#code=qN%2F%7B%0A%20%20QelS%2F%22%20%2C%22*__eu%26S-A%2Cs-NerN%25%7B_(%5C%22aeiou%22-%2Be%601f%3D_S-Z%3E%5C%40%3F%7D%2F%0AN%7DfQ&input=homework%0Allamas%0Abotany%0Ay3333llow%0Ashorten%0Aaabcddde%0Aabb'bbc%0ASHARRRKnado%0Aabracadabra%0Aeverything%20is%20awesome!%0Ayou%20can't%20break%20what%20is%20already%20broken%0Athe%20person's%20cat's%20bed's%20blanket's%20poka-dots%20are%20orangy-yellow) in the CJam interpreter.
### How it works
```
qel e# Read all input and cast to lowercase.
S/" ,"* e# Replace spaces with " ,". This way, we don't have to consider
e# spaces word delimiters, which will make them easier to preserve.
__eu e# Push two copies and convert the second one to uppercase.
& e# Intersect the copies. This will keep only non-letters.
S-A,s- e# Remove spaces and digits from the non-letters.
Ner e# Replace their occurrences in the input with linefeeds.
N% e# Split at linefeeds.
{ e# For each resulting chunk:
_(\ e# Push a copy and shift out the first character.
"aeiou"- e# Remove all vowels from the tail.
+ e# Concatenate the result with the first character.
e` e# Perform run-length encoding.
1f= e# Select all characters.
_S- e# Push a copy and remove spaces.
e# This is for the length check; spaces don't actually form part
e# of the word.
Z> e# Discard the first three characters.
\@? e# If there are characters left, pick the modified word; else
e# pick the unmodified one.
}/ e#
```
[Answer]
# C# - 404 bytes
```
using System;using System.Text;using System.Text.RegularExpressions;class j{static bool v(char l){return l=='e'||l=='a'||l=='o'||l=='i'||l=='u';}static void Main(){string a=Console.ReadLine();string z=Regex.Replace(a,"[^a-zA-Z ]","");string[]b=z.Split(' ');string c="";foreach(string d in b) {if(d.Length>4){foreach(char e in d.ToCharArray()){if(!v(e))c+=e;}}else{c+=d;}c+=' ';}Console.WriteLine(c);}}
```
It takes input from Console.ReadLine(). I used a regex to find the non alphanumeric characters and spaces and I calculated if the size is less than 4. I tested using the final example.
# C# - 279 bytes (from LegionMammal798)
```
using C=System.Console;class j{static void Main(){var c="";foreach(var d in System.Text.RegularExpressions.Regex.Replace(C.ReadLine(),"[^a-zA-Z0-9 ]",c).Split(' ')){if(d.Length>4){foreach(var e in d)if(!"aeiou".Contains(e.ToString()))c+=e;}else c+=d;c+=' ';}C.Write(c);}}
```
Thank you for the golfing tips!
[Answer]
# ùîºùïäùïÑùïöùïü, 57 chars / 97 bytes (noncompetitive)
```
Ɱ(ï,↪(a=$ù⬮ċ/⊙\1+⌿,`⑴”ċ/[ᶌ]⌿,⬯⸩Ꝉ>3?a⎖0≔$⎖0?a:$⎖0+a:$,⬭,⬭)
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=everything%20is%20awesome!&code=%E2%B1%AE%28%C3%AF%2C%E2%86%AA%28a%3D%24%C3%B9%E2%AC%AE%C4%8B%2F%E2%8A%99%5C1%2B%E2%8C%BF%2C%60%E2%91%B4%E2%80%9D%C4%8B%2F%5B%E1%B6%8C%5D%E2%8C%BF%2C%E2%AC%AF%E2%B8%A9%EA%9D%88%3E3%3Fa%E2%8E%960%E2%89%94%24%E2%8E%960%3Fa%3A%24%E2%8E%960%2Ba%3A%24%2C%E2%AC%AD%2C%E2%AC%AD%29)`
Uses regex aliasing and other syntax made after the challenge was posted.
[Answer]
# Haskell, ~~187~~ 176 bytes
Adhering to written description, not given examples:
```
import Data.List
import Data.Char
f=filter
d w@(_:_:_:_)=map head$groupBy(\a b->toLower a==toLower b)w
d w=w
s=unwords.map(f isAlphaNum.d.(\(h:t)->h:f(`notElem`"aeiou")t)).words
```
Call `s`.
Improved late after vote reminded me of its existence.
] |
[Question]
[
## Task
Your mission is to create a program that reviews Python code. The solution can be written in any language!
It must take input that contains python code. The program must add `# This is not pythonic!` before each block of non-whitespace lines.
## Input
* The data can be entered via stdin.
* The data will contain at least 3 lines with one blank one in between
them.
**Minimum input example.**
```
print "Hello World!"
Print "Bye World!"
```
**Sample Input**
```
from os.path import abspath
lines = []
with open(__file__, 'r') as f:
for line in f:
lines.append(line)
if lines is not None:
newLines = []
hasReviewedBlock = False
for line in lines:
if len(line) > 1: # \n
if hasReviewedBlock == False:
newLines.append("# This is not pythonic!\n")
hasReviewedBlock = True
else:
hasReviewedBlock = False
newLines.append(line)
with open("d:/test.py", 'w') as f:
for line in newLines:
f.write(line);
```
## Output
Output has to be written to STDOUT or closest alternative.
## Sample Output
```
# This is not pythonic!
from os.path import abspath
# This is not pythonic!
lines = []
with open(__file__, 'r') as f:
for line in f:
lines.append(line)
# This is not pythonic!
if lines is not None:
# This is not pythonic!
newLines = []
hasReviewedBlock = False
# This is not pythonic!
for line in lines:
if len(line) > 1: # \n
if hasReviewedBlock == False:
newLines.append("# This is not pythonic!\n")
hasReviewedBlock = True
else:
hasReviewedBlock = False
# This is not pythonic!
newLines.append(line)
with open("d:/test.py", 'w') as f:
for line in newLines:
f.write(line);
```
## Scoring:
Lowest number of bytes wins. -5 bytes if your program can be used as valid input.
[Answer]
# awk, 64 56 54 bytes
```
/^$/{i=0}/./{if(!i++)print"# This is not pythonic!"}1
```
**Test:**
```
echo '/^$/{i=0}/./{if(!i++)print"# This is not pythonic!"}1' > solution.awk
awk -f solution.awk < pyth.py
awk -f solution.awk < pyth.py
```
**Explanation:**
`/^$/` - matches empty line,
`/./` - matches non-empty line,
`1` - matches each line. No body is equivalent to `{print;}` - each line of input is printed.
[Answer]
# Pyth, ~~39~~ ~~38~~ 37 bytes
```
tjbm|d+b"# This is not pythonic!"+k.z
```
[Live demo.](https://pyth.herokuapp.com/?code=tjbm%7Cd%2Bb"%23+This+is+not+pythonic%21"%2Bk.z&input=from+os.path+import+abspath%0A%0Alines+%3D+%5B%5D%0Awith+open%28__file__%2C+%27r%27%29+as+f%3A%0A++++for+line+in+f%3A%0A++++++++lines.append%28line%29%0A%0Aif+lines+is+not+None%3A%0A%0A++++newLines+%3D+%5B%5D%0A++++hasReviewedBlock+%3D+False%0A%0A++++for+line+in+lines%3A%0A++++++++if+len%28line%29+>+1%3A+%23+%5Cn%0A++++++++++++if+hasReviewedBlock+%3D%3D+False%3A%0A++++++++++++++++newLines.append%28"%23+This+is+not+pythonic%21%5Cn"%29%0A++++++++++++++++hasReviewedBlock+%3D+True%0A++++++++else%3A%0A++++++++++++hasReviewedBlock+%3D+False%0A%0A++++++++newLines.append%28line%29%0A++++with+open%28"d%3A%2Ftest.py"%2C+%27w%27%29+as+f%3A%0A++++++++for+line+in+newLines%3A%0A++++++++++++f.write%28line%29%3B&debug=1)
## Explanation
```
tjbm|d+b"# This is not pythonic!"+k.z
+k.z Prepend the empty line to the string
m For each line
|d If it's non-empty, return the same line
+b"# This is not pythonic!" Else, return a line break followed by the required text
jb Join via line breaks
t Remove the unneeded preceding line break
```
# 38-byte version
```
tjbm?dd+b"# This is not pythonic!"+k.z
```
# 39-byte version
```
jbtsm?dd,d"# This is not pythonic!"+k.z
```
~~No doubt there's still golfing left to do.~~
[Answer]
## AutoIt - 139
```
$1='# This is not pythonic!'
ConsoleWrite($1&@CRLF&StringRegExpReplace(FileRead($CmdLine[1]),'(*BSR_ANYCRLF)(^\R|\R(?=\R))',"\0"&@CRLF&$1))
```
I'm assuming the first line cannot be empty as by your specification:
>
> The data will contain at least 3 lines with one blank one in between them.
>
>
>
This program is called like this:
```
compiled.exe pycode.py > output.txt
```
The RegEx can be optimized for sure. Works for `CRLF` only.
[Answer]
# [Wren](https://github.com/munificent/wren), 73-5 = 68 bytes
Luckily enough, Wren has an automatic WYSIWYG that gains the bonus.
```
Fn.new{|i|("
"+i).split("
").join("
# This is not pythonic!
")[2..-1]}
```
[Try it online!](https://tio.run/##Ky9KzftfllikkFaal6xgq/DfLU8vL7W8uiazRkOJi0tJO1NTr7ggJ7MEzNPUy8rPzAMxlRVCMjKLFYAoL79EoaCyJCM/LzNZEagk2khPT9cwtvZ/cGVxSWquXnlRZkmqBsh4veTEnBwNLiUkK2KARsUgWQLhQ62JwWNPDMIiJU3N/wA "Wren – Try It Online")
## Explanation
```
Fn.new{|i| // In this case we define a new
// anonymous function with the operand i
("
"+i) // We prepend the input with 2 newlines
.split("
") // Split the input by newlines,
// including the preceding newlines
// that we first prepended
.join("
# This is not pythonic!
") // Join the input with 2 newlines
// , the comment, and another trailing newline
[2..-1]} // Slice the input so that the preceding
// 2 newlines are not present in the final output
```
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 40 - 5 = 35 bytes
```
{S:g/^|"
"<(/# This is not pythonic!
/}
```
[Try it online!](https://tio.run/##fVG9TsMwEN79FEcq0URCiVgYUmBgYEIM0I1CZNozsUhsy3aJIuDZg500TUMKJy@@u@/n7hTq4qIpazhlcAXN52P6lrx8BYQEl2Eyg2XODbgnpAVV21wKvj4hyXdjaA0MTLHVatEwLUuQJlbU5sBLJbUF@mr8l5CCCzSO@@mZVNzVpUIRZhnjBWbZGcz1PAJqgKUEXDCpwSOAiz7loyWJqXLYTeg/ESGcdene370UmJIWIrC6G2R9JqfmAT84Vri5KeT63VVuaWGQTFRbzkHZqzjDrSZcw3kKM1iJfXnXMqXf8aejzkNv/TTBH1teiSCagI@MsdRb3PfhRPL/wY8Z6tbrK8O9gk2aWDQ2VnXgblaNbvZ7gz3h2AiLK80tdvSLHw "Perl 6 – Try It Online")
The bonus is rather weird, but it didn't cost me any bytes to add.
### Explanation
```
{S:g/ / /} # Substitute all instances of
^ # The start of the string
|" " # or two newlines
<( # But don't actually replace, just append
... # With the given string
```
[Answer]
# [Python 3](https://docs.python.org/3/), 86 bytes - 5 = 81
```
import re
print(re.sub(r"(^\n*|\n\n+)",r"\1# This is not pythonic\n",open(0).read()))
```
[Try it online!](https://tio.run/##fVHNTsMwDL7nKUx2WANTYeJWBAcOnBAHtBuFKltdNaJzoiSjmsS7l6RbN0YnrFxi@/uxbba@1nTbdWpttPVgkTFjFfnEYuo2y8Ty5COny@@ccroSfGZ5Pp/AolYOwiPtwfQUapUTn2mDlNyI1KIsEyFE11VWr0G71Ehfw15ELl38MtYoQgf38PbOWhXqPbwoKtVgUcxgaqcCpIMqYxCi0hYiAhQNqRg9SSpNwJZJ/AjGVLVLDx5fNGHGeghh@3yUjZlaulf8Uthi@djo1WeoPMnGIRup9pxH5agSDPea8ADzDCaQ06G8bxnT7/mzk87f3oZp@PlNX4RVixH4zBgLu8FDH44k/x/8nKHdemPleC9eZtcenU/NloebtSc3@7vBgfDUSJW2Vnnc0d/9AA "Python 3 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 94 bytes - 5 = 89
```
p=''
for c in open(0).read().splitlines():print("# This is not pythonic!\n"*(p==''!=c)+c);p=c
```
[Try it online!](https://tio.run/##fVG9TsMwEN79FNd0SAwogNhShYGBCTGgbhRFJrkoFqlt2YaoTx9sJ2koqXry4rv7fu5OHWwjxUPfqzyOCamlhhK4AKlQJHc01ciqhKZGtdy2XKBJaKY0FzaJ1rBtuAH3hLSgAhEvVzsRXSUqd3SrvKTXJd2ovOz7Wss9SJMqZhvgeyW1BfZp/JeQwAw5vH@Qjrt6UC@KmrdYFDcQ65gCM1BnBFx4kx7hfY4pH4EkZcphq8R/KCG8HtKTy1cpMCMBIrB7mWV9pmHmDX84dlg9tbL8cpVn1hokC9XAOSt7FWc4aMIj3Gewhp04lseWJf3In510/vU2TXNh13QBPjPGVn/jsQ8XkpcHP2doWK@vzPeKquzWorGpOkTuZt3Jzf5vcCI8NVKnneYWB/rNLw "Python 3 – Try It Online")
[Answer]
# CJam, 41 bytes
```
"# This is not pythonic!":TNqN/{_{T}|}%N*
```
[Try it online](http://cjam.aditsu.net/#code=%22%23%20This%20is%20not%20pythonic!%22%3ATNqN%2F%7B_%7BT%7D%7C%7D%25N*&input=from%20os.path%20import%20abspath%0A%0Alines%20%3D%20%5B%5D%0Awith%20open(__file__%2C%20'r')%20as%20f%3A%0A%20%20%20%20for%20line%20in%20f%3A%0A%20%20%20%20%20%20%20%20lines.append(line)%0A%0Aif%20lines%20is%20not%20None%3A%0A%0A%20%20%20%20newLines%20%3D%20%5B%5D%0A%20%20%20%20hasReviewedBlock%20%3D%20False%0A%0A%20%20%20%20for%20line%20in%20lines%3A%0A%20%20%20%20%20%20%20%20if%20len(line)%20%3E%201%3A%20%23%20%5Cn%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20hasReviewedBlock%20%3D%3D%20False%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20newLines.append(%22%23%20This%20is%20not%20pythonic!%5Cn%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20hasReviewedBlock%20%3D%20True%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20hasReviewedBlock%20%3D%20False%0A%0A%20%20%20%20%20%20%20%20newLines.append(line)%0A%20%20%20%20with%20open(%22d%3A%2Ftest.py%22%2C%20'w')%20as%20f%3A%0A%20%20%20%20%20%20%20%20for%20line%20in%20newLines%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20f.write(line)%3B)
Alternate solution that handles multiple empty lines in succession, as well as empty lines at the start. This is 44 bytes, and will become my solution depending on how the pending clarifications turn out:
```
qN/{_L!e&{"# This is not pythonic!"\}&:L}%N*
```
[Answer]
# JavaScript (ES6), 70
Test running the snippet below.
```
f=p=>alert((r='# This is not pythonic!\n')+p.replace(/\n\n+/g,x=>x+r))
//// TEST CASES /////
t1=`print "Hello World!"
Print "Bye World!"`
f(t1)
t2=`from os.path import abspath
lines = []
with open(__file__, 'r') as f:
for line in f:
lines.append(line)
if lines is not None:
newLines = []
hasReviewedBlock = False
for line in lines:
if len(line) > 1: # \n
if hasReviewedBlock == False:
newLines.append("# This is not pythonic!\n")
hasReviewedBlock = True
else:
hasReviewedBlock = False
newLines.append(line)
with open("d:/test.py", 'w') as f:
for line in newLines:
f.write(line);`
f(t2)
```
] |
[Question]
[
Almost all operating systems allow you to run multiple programs at the same time. If your system does not have enough processors to run all the programs you want to run, it starts to give each program just a tiny slice of time on the processor it runs on. This is normally not noticeable but can lead to strange artefacts that you might not expect.
Your task is to write a program that tries to find out how many cores your computer has without asking the operating system. This is a popularity contest, the most upvoted solution wins. Here are the constraints:
* While you cannot expect that your submission is the only thing that runs, you may expect that all other programs on the system are idling and wake up only sporadically.
* You may not ask the operating system how many cores your computer has. Neither may you look up this number from any configuration file or similar. You may also not invoke a utility that provides you with that information.
* For the sake of this challenge, the number of cores your computer has is the number of processes your computer can run at the same time. For instance, if you have an Intel processor with 2 cores and hyper threading, that would count as 4 cores.
* Your solution needs not to be precise. It should not be terribly wrong all the time though.
[Answer]
# C++11
Simply compares single core performance with threaded performance until there is not a linear speedup anymore. It's important that you do not have any other CPU intensive process running at the same time.
Compile with `-O2 -m64 -march=native -std=c++11`. You might have to pass `-lpthread`.
```
#include <chrono>
#include <cstdint>
#include <future>
#include <iostream>
#include <vector>
double f() {
double cnt = 0;
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
start = std::chrono::system_clock::now();
while (true) {
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed = end - start;
if (elapsed.count() > 1.) break;
cnt++;
}
return cnt;
}
int main(int argc, char** argv) {
double one_core = f();
int n = 1;
while (true) {
std::vector<std::future<double>> futures;
for (int i = 0; i < n; ++i) {
futures.push_back(std::async(std::launch::async, f));
}
double tot = 0;
for (int i = 0; i < n; ++i) tot += futures[i].get();
if (int(tot / one_core + 0.5) != n) {
std::cout << n - 1 << " core(s)\n";
return 0;
}
++n;
}
}
```
[Answer]
# C
Here's a new, imprecise approach:
```
/* ncpu.c */
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
int count = 1; /* start at 1 for the main() thread */
static void *inc_thread (void *arg) {
/* Woohoo - now we're no longer languishing on the ready queue -
* We're actually running on a real core. Atomically bump the counter. */
pthread_mutex_lock(&count_mutex); {
count++;
} pthread_mutex_unlock(&count_mutex);
/* keep this core spinning so another thread doesn't get it */
while (1);
return NULL;
}
#define MAX_CORE 64
int main (int argc, char **argv) {
pthread_t tid_array[MAX_CORE];
int i;
/* create a bunch of threads */
for (i = 0; i < MAX_CORE; i++) {
pthread_create(&tid_array[i], NULL, inc_thread, NULL);
}
/* cancel all those threads, regardless of whether they ran or not */
for (i = 0; i < MAX_CORE; i++) {
pthread_cancel(tid_array[i]);
}
printf("Your core count is approximately %d\n", count);
}
```
Build with `LDFLAGS=-pthread make ncpu`.
This works some of the time on Ubuntu 14.04. I have tested with 1, 2 and 4 virtual cores in a VM.
This kicks off 64 threads, and then (almost) immediately cancels all those threads. `pthread_create()` will put the new thread in a ready queue, but won't necessarily jump into the thread start routine immediately. When the threads get to run depends on core availability at that time.
For example if there are 4 cores, then 3 of the threads can potentially start running immediately. Each thread atomically increments a counter then spins for a bit until it is cancelled. Beyond the third thread, the rest of the threads will still be sitting in the ready queue when the main thread cancels them, and so they won't get to increment the counter.
This is certainly not very precise, but its only *terribly* wrong some of the time. Here are some runs with 1, 2 and 4 virtual cores:
### 1 core:
```
$ for i in {1..10}; do ./ncpu; done
Your core count is approximately 65
Your core count is approximately 1
Your core count is approximately 1
Your core count is approximately 15
Your core count is approximately 1
Your core count is approximately 19
Your core count is approximately 1
Your core count is approximately 1
Your core count is approximately 42
Your core count is approximately 1
$
```
### 2 cores:
```
$ for i in {1..10}; do ./ncpu; done
Your core count is approximately 2
Your core count is approximately 2
Your core count is approximately 2
Your core count is approximately 2
Your core count is approximately 2
Your core count is approximately 2
Your core count is approximately 3
Your core count is approximately 3
Your core count is approximately 2
Your core count is approximately 2
$
```
### 4 cores:
```
$ for i in {1..10}; do ./ncpu; done
Your core count is approximately 4
Your core count is approximately 5
Your core count is approximately 4
Your core count is approximately 4
Your core count is approximately 4
Your core count is approximately 4
Your core count is approximately 4
Your core count is approximately 4
Your core count is approximately 4
Your core count is approximately 4
$
```
---
My previous answer:
Here's a start, though it only distinguishes between exactly one core and more than one core:
```
/* 1cpu.c */
#include <stdio.h>
#include <pthread.h>
int c = 0;
static void *inc_thread (void *arg) {
int i;
for (i = 0; i < 10000000; i++) c++;
return NULL;
}
static void *dec_thread (void *arg) {
int i;
for (i = 0; i < 10000000; i++) c--;
return NULL;
}
int main (int argc, char **argv) {
pthread_t inc_tid, dec_tid;
pthread_create(&inc_tid, NULL, inc_thread, NULL);
pthread_create(&dec_tid, NULL, dec_thread, NULL);
pthread_join(inc_tid, NULL);
pthread_join(dec_tid, NULL);
if (c) {
printf("c=%d, More than one CPU\n", c);
} else {
printf("c=%d, Only one CPU\n", c);
}
}
```
Build with `LDFLAGS=-pthread make 1cpu`.
This is a nice demonstration of how normal `++` and `--` are **not** atomic operations. In the single-core situation, `inc_thread()` and `dec_thread()` can never run concurrently, so the global counter `c` will always be incremented and decremented exactly 10 million times and thus end up as 0. However with more than one core, these two threads will likely end up on different cores, and thus colliding with their operations on the global counter. As we know, these operations have to load, [in|de]crement, then save each time, so threads can end up operating on stale data as they go through these operations. Therefore over 10 million runs we will likely end up with a different number of effective increment vs decrement operations and the counter will end up non-zero.
This method seems to be fairly accurate, and works on OSX as well as Linux.
[Answer]
# Python 2
```
import decimal
from timeit import Timer
elapsed = decimal.Decimal(Timer("""1 and 1""").timeit())
speed = 1/elapsed
cores = speed/decimal.Decimal(3.6)
cores = round(cores)
print cores
```
I kind of lost what I was doing halfway through but this works fairly well for me.
## Edit
I guess modern computer cores have a greater speed. The program should now be more accurate (hopefully).
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/19149/edit)
**The Code**
Your program should take an input of *n > 2* and output the largest prime less than or equal to *n*. You can choose how the number is input (standard input, read from a file, etc). For example:
```
Input Output
3 3
9 7
28 23
486 479
```
Simple enough. And if a program passes all of the test cases it's gonna work fine, right?
**The Underhanded**
Too bad your program will *only* pass the test cases. It should work properly for 3, 9, 28, and 486 and no other numbers. Since this is an underhanded challenge, this shouldn't be obvious to a person glancing over the code.
Bonus points if the program still outputs something and if the output isn't obviously composite (getting 555 for 556 would be a little suspicious). This is a popularity contest, so the most popular answer wins. Which means the bonus points are completely meaningless. Oh well!
[Answer]
# C
Results will be correct for the test cases, all others will be wrong for one or more reasons. The key is using the specifier `%g` which will round enough for the test cases but show the others as real numbers. Above inputs of 614, the results are all less than zero. Assuming inputs are in the integer domain!
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
// Convert input
double x = atof(argv[1]);
// Cubic prime determination function
double y = -1.386269645E-5 * x * x * x + 7.572051723E-3 * x * x + 5.774239804E-1 * x + 1.199953896;
// Print output, use %g because it guarantees the shortest output
printf("First prime less than or equal to %g is %g - happy day.\n", x, y);
// Done!
return 0;
}
```
Sample output:
```
$ ./fake 2
First prime less than or equal to 2 is 2.38498 - happy day.
$ ./fake 3
First prime less than or equal to 3 is 3 - happy day.
$ ./fake 4
First prime less than or equal to 4 is 3.62992 - happy day.
$ ./fake 5
First prime less than or equal to 5 is 4.27464 - happy day.
$ ./fake 6
First prime less than or equal to 6 is 4.9341 - happy day.
$ ./fake 7
First prime less than or equal to 7 is 5.6082 - happy day.
$ ./fake 8
First prime less than or equal to 8 is 6.29686 - happy day.
$ ./fake 9
First prime less than or equal to 9 is 7 - happy day.
$ ./fake 28
First prime less than or equal to 28 is 23 - happy day.
$ ./fake 486
First prime less than or equal to 486 is 479 - happy day.
```
[Answer]
## Matlab
Not too much code, but I earn maximum bonus points. If it is not one of the specified numbers, the function will return the second maximum prime number. Added much nonsense to the code to make it seem like some advanced stuff is happening. ;)
```
function result=primesearch(input)
%declare function output
state = ones(input,1);
%generate a random primeseed
primeseed = ['FL_'-66 'l'+379 1]-1;
primeseed=state*primeseed;
for ii=1:input
%calculate prime numbers using the primeseed
state(ii)=ii*isprime(ii+primeseed(input,end));
end
%select the maximum prime number from the list
primenumbers=state(state~=0);
index=length(primenumbers)-1+ismember(input,primeseed);
if (index>0)
result = primenumbers(index);
end
end
```
[Answer]
# Ruby
```
testcases = {
3 => 3,
9 => 7,
28 => 23,
486 => 479
}
testmode = 'test'
# different methods for different testmodes
def test # this is the only mode so far, but I made it extendable so that you can add more modes later
"
n=($$**$.)[0xFA64B3ED9^$$] # this will do very crucial stuff, leave it alone
m=$_?0b11010:$$%n # it's like that inverse square root thingy, just don't even try to understand
[*n..m].step(n^m)[-1] # if you're curious, it's some prime algorithm, I forgot which, but should be easy to look up
".inspect
end
largest_prime_under = ->s {
testmode_result = eval testmode + '()`
case s
# special numbers where the algorithm does not work
when -1.0/0..0
return nil
when 2
return 2
when 3
return 3
end
eval_str = '.gsub(/#.*/m, "") # remove comments
.gsub(/[^A-Za-z0-9]/m, "") # clean string of whitespace and other useless chars (like regex x mode)
'
testmode_result = eval `#{testmode_result}#{eval_str}'
testmode_result[s]
}
testcases.each do |k, v|
puts "largest prime under #{k} is #{v}, my function computed: #{largest_prime_under[k]}"
end
```
I have no time right now for an explanation, but I will add one soon ;)
[Answer]
## C
This one is mostly "proof by intimidation". Can you see how it works?
```
#include <stdint.h>
#include <stdio.h>
uint16_t m[] = { 131558, 196608, 262167, 327708, 393216,
458759, 524297, 589824, 655363, 720899,
786432, 864180, 917505, 983040, 998311 };
int find_prime(int n) {
int i, r = 0xAF319C, M = 0x137715;
for (i = 0; n % m[i]; i += 3) {
r = (r * m[i + 1] + m[i + 2]) % M;
}
return r % M;
}
int main(void) {
int input;
while (scanf("%d", &input) != EOF) {
printf("%d\n", find_prime(input));
}
return 0;
}
```
Sample run (input indented for clarity):
```
1
12212
2
12212
3
3
4
12212
5
12212
6
3
7
12212
8
12212
9
7
10
12212
28
23
486
479
453
3
454
12212
```
[Answer]
# q
`maxPrime:{$[x in"I"$0 1 2 4_string 0x0 sv"x"$0 59 241 166;(last where 0b,2=sum 0=x mod/:x:1+til x);((p-1) mod 2)+p:x-floor x%max(x%8;1)]}`
breaking it down, maxPrime is a conditional so it contains three statements.
"if"
* `x in "I"$0 1 2 4 cut string 0x0 sv "x" $0 59 241 166`
0 59 241 166 is the internal representation of the integer 3928486
\_ ("cut") is a dyadic function that creates list subsets of a list by indices
english translation: "Is x in (3;9;28;486)?"
"then"
* `(last where 0b,2=sum 0=x mod/:x:1+til x)`
is a slightly modified version of listing primes up to n (#175 <http://code.kx.com/wiki/Qidioms>)
"else"
* `((p-1) mod 2)+p:x-floor x%max(x%8;1)`
takes the input - floor(input/max(input/8;1)) and adds 1 if even (so never obviously composite)
[Answer]
## Ruby
```
require 'prime' # Cheating?
pri=Prime
m=2
input = File.open(__FILE__).readlines.take(5).map{|num| num.chop =~ /$/} # Read up to five test cases from the input file and trim trailing newlines. To run using this input style, for example, you could put four numbers into a file named "test", each on its own line, and then run "ruby -n largest_prime.rb test". The resulting output will likewise be separated by newlines, and will, for each number, be the largest prime less than that number n. For example, the output for n=9 is 7.
input&=[$_.to_i] # Str =>int
input.each do |num|
raise "Number must be greater than #{m}" if num<m
puts pri.to_a(num).last
end
```
Will output the correct answer for the test cases and nothing for anything else.
[Answer]
## TI-BASIC
```
{3,9,28,486->I:I-{0,2,3,9->O:LI-LO->LO:Input N:(LI=N)*LO->A:Disp cumSum(LA)
```
Note that `L` represents the list character and `->` represents the `STO->` arrow here.
] |
[Question]
[
Write the shortest code in any language of your choice to find the \$N\$th \$K\$-ugly number.
A \$K\$-ugly number is a number whose only prime factors are the prime numbers \$\le K\$.
\$K\$-ugly number's are popularly known as \$K\$-smooth numbers.
Constraints:
* \$0 < N < 1000\$
* \$0 < K < 25\$
Input:
* `N K` (separated by a single space)
Output:
* `-1` (if no such number exists)
*or*
* \$M\$ (if \$N\$th \$K\$-ugly number is \$M\$)
[Answer]
# Mathematica ~~82 72~~ 70
```
n_~u~k_:=(c=m=1;While[m <= n,If[FactorInteger[c][[-1,1]]<=k,m++];c++];c-1)
```
**Usage**
```
u[1, 5]
u[5, 2]
u[20, 3]
u[57, 5]
u[66, 13]
u[100, 5]
u[1000, 25]
```
>
> 1
>
> 16
>
> 96
>
> 324
>
> 110
>
> 1536
>
> 5474
>
>
>
---
Prime factors and their powers are in the center column.
```
Table[{t, FactorInteger[t], u[t, 5]}, {t, 15}] // Grid
```

[Answer]
## Python 2 - 63 bytes
```
i=t=1
n,k=input()
while~-n:i+=1;t*=i>k or i**n;n-=t%i<1
print i
```
Input is taken from stdin, comma separated.
Sample usage:
```
$ echo 1, 5 | python nth-k-smooth.py
1
$ echo 5, 2 | python nth-k-smooth.py
16
$ echo 20, 3 | python nth-k-smooth.py
96
$ echo 57, 5 | python nth-k-smooth.py
324
$ echo 66, 13 | python nth-k-smooth.py
110
$ echo 100, 5 | python nth-k-smooth.py
1536
$ echo 1000, 25 | python nth-k-smooth.py
5474
```
---
At *N = 1000*, the script has a reasonable execution time for all values *K ≥ 7*. For the input *N = 1000, K = 2* the correct answer is *2999 ≈ 5.357543300·10300*. Using an "increase by one" approach, as [David Carraher's answer](https://codegolf.stackexchange.com/a/12889) also does, it would take longer than the age of the universe to reach this value (considerably longer!).
[Answer]
## APL(Dyalog), 38
```
{⍵≡1:¯1⋄⊃⌽⍺{0~⍨⍺↑y[⍋y←∪,⍵∘.×⍵]}⍣≡⍳⍵}/⎕
```
Finally, for once, APL has beaten GS!!
---
**Sample**
```
⎕:
5 3
6
⎕:
20 5
36
⎕:
500 20
2028
⎕:
50 1
¯1
```
---
**Explanation**
`/⎕` Takes evaluated input (space-seperated numbers are interpreted as numerical array) and insert a function in between (reduce).
`⍵≡1:` If right argument (k) is 1
`¯1` return -1 (`¯` is the high-minus, APL's way of representing negative numbers)
`⋄` Statement seperator used as `else`.
`⍳⍵` Generate a numerical array from 1 to k
`⍺{...}⍣≡` Recursively apply function until output of an iteration is the same as that of the last iteration (fixpoint), passing the left argument of outer function (N) as the left each iteration.
`⍵∘.×⍵` Outer product of the left argument with itself (generating a multiplication table)
`,` Unravel the matrix to numerical array
`∪` Remove duplicates
`y[⍋y←...]` Sort
`⍺↑` Get the first N values (fills 0s if shorter than N)
`0~⍨` Remove 0s
**In short, `⍺{0~⍨⍺↑y[⍋y←∪,⍵∘.×⍵]}⍣≡⍳⍵` generates the first N k-smooth numbers**
`⊃⌽` get last value
[Answer]
### GolfScript, 42 characters
```
~),2>{:s,2>{s\%!},!},:^1+1+{$({*}+^%|}@*0=
```
Unfortunately, I had to insert several correction terms to get the indexing correct.
Examples:
```
> 5 2
16
> 20 3
96
> 66 13
110
> 1000 25
5474
```
[Answer]
## R 133 characters
```
a=scan(n=2)
k=1:a[2]
i=m=0
while(m<a[1]){i=i+1;if(all(sfsmisc::factorize(i)[[1]][,1]%in%k[rowSums(!outer(k,k,`%%`))<3]))m=m+1}
cat(i)
```
Explanation:
`k[rowSums(!outer(k,k,`%%`))<3]`: k being here the sequence from 1 to K, this piece of code outputs the list of primes smaller or equal to K.
`all(sfsmisc::factorize(i)[[1]][,1]%in%k[rowSums(!outer(k,k,`%%`))<3])`: this checks that all of the primes used to factorize a number belong to the previous list. It uses a function from package `sfsmisc` that performs the prime factorization.
[Answer]
## Mathematica, 96 characters
```
{n,k}=%~Read~{Number,Number};If[n>k==1,-1,While[p<n,m++;If[Max@FactorInteger[m][[All,1]]<=k,p++]];m]
```
Ungolfed:
```
{n, k} = % ~Read~ {Number, Number};
If[n > k == 1,
-1,
While[p < n,
m++;
If[Max@FactorInteger[m][[All, 1]] <= k, p++]
]; m
]
```
I did manage to find a shorter solution, more in the spirit of Mathematica's functional programming style by avoiding the while-loop, but it runs out of memory without an upper bound on *M*. It also cheats on the space-seperated input, but I thought it was elegant (60 characters):
```
Select[Range@999,Max@FactorInteger[#][[All,1]]<=k&][[n]]~Check~-1
```
[Answer]
# Ruby 1.9+, 101 chars
Sort of verbose but nice and functional:
```
require'Prime'
n,k=gets.split.map &:to_i
p (1..5474).select{|i|i.prime_division.all?{|j,l|j<=k}}[n-1]
```
edit:
The number constant `5474` represents the highest value the program will ever output (upper bound), and is the answer to *N = 1000, K = 2*. As Primo points out, this may be a little low.
If you for some reason would like to run this program, the upper bound can be changed to whatever you want. Increasing it by a few digits will however increase execution time dramatically[1](https://codegolf.stackexchange.com/a/12896/4372), even for small outputs.
A feature I find quite neat is that the program cleanly outputs `nil` if the output would exceed the upper bound.
] |
[Question]
[
The task is to group adjacent values from collection and output it as a new aggregated collection.
Consider we have following input:
```
Sequence
Number Value
======== =====
1 9
2 9
3 15
4 15
5 15
6 30
7 9
```
The aim is to enumerate over Sequence Numbers and check if the next element has the same value. If yes, values are aggregated and so, desired output is as following:
```
Sequence Sequence
Number Number
From To Value
======== ======== =====
1 2 9
3 5 15
6 6 30
7 7 9
```
Build a code with following assumptions:
* Sequence Numbers are already ordered in input table.
* There can be gaps in Sequence Numbers. If input contains gaps, output should contain gaps too. For example input `1 99\n2 99\n4 99\n6 99`, output will be `1 2 99\n4 4 99\n6 6 99`.
* Assume Value is type of integer.
* It can be a full program or just a function.
* This cruft `(Sequence Sequence\n` ... `======== ======== =====\n)` is not a part of output. Output format is not defined; there should be a delimeter between values and between rows, so anyone can distinguish values and rows.
It's an extend of my StackOverflow question: <https://stackoverflow.com/questions/14879197/linq-query-data-aggregation>.
[Answer]
# K, 43 38
{d:(x;0N,x;y)@\:&~~':y;d[1]:(1\_d 1),\*|x;+d}
```
{a::*|x;+@[(x;{x,a};y)@\:&~~':y;1;1_]}
```
.
```
k){a::*|x;+@[(x;{x,a};y)@\:&~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 2 9
3 5 15
6 6 30
7 7 9
```
# Explanation
The function takes two vectors, `x` and `y`, as input
`a::*|x` takes the last value of `x` and assigns it to `a`.
`&~~':y` returns a list of indices where the `y` vector changes:
```
k){&~~':y}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
0 2 5 6
```
`(x;{x,a};y)` creates a three element list containing
1) the `x` vector,
2) the function `{x,a}` which takes an input variable `x`(not to be confused with the `x` vector which was input into the original function) and appends `a`, and
3) the `y` vector
`(x;{x,a};y)@\:&~~':y` takes this three element list and applies the indices to each element
so that we return the `x` vector at those indices, the indices with `a` appended, and the `y` vector at those indices
```
k){b::*|x;(x;{x,b};y)@\:&~~':y}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 3 6 7
0 2 5 6 7
9 15 30 9
```
`@[(x;{x,a};y)@\:&~~':y;1;1_]` takes the matrix we've created and drops the first element of the second row.
```
k){b::*|x;@[(x;{x,b};y)@\:&~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 3 6 7
2 5 6 7
9 15 30 9
```
`+` then transposes the result
```
k){b::*|x;+@[(x;{x,b};y)@\:&~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 2 9
3 5 15
6 6 30
7 7 9
```
[Answer]
## *Mathematica*, ~~40~~ 47 / 40
Updated to handle the new rules:
```
#~Riffle~{##}[[-1,1]]&@@@Split[#,#2-#=={1,0}&]&
```
Example of use:
```
#~Riffle~{##}[[-1,1]]&@@@Split[#,#2-#=={1,0}&]& @
{{1, 9}, {2, 9}, {3, 9}, {4, 15}, {5, 15}, {6, 30}, {7, 9}, {12, 9}}
```
>
>
> ```
> {{1, 3, 9}, {4, 5, 15}, {6, 6, 30}, {7, 7, 9}, {12, 12, 9}}
>
> ```
>
>
Or, since "There are no restrictions on input/output format":
```
#[[1,1]]|Last@#&/@Split[#,#2-#=={1,0}&]&
```
Which when used as above outputs:
>
>
> ```
> {1 | {3, 9}, 4 | {5, 15}, 6 | {6, 30}, 7 | {7, 9}, 12 | {12, 9}}
>
> ```
>
>
[Answer]
## J, ~~53~~ ~~48~~ 43
Explicit version (43 chars):
```
f=.4 :'|:(#&y,{.@:#&x)(1&,,:,&1)2(-.@=/\)x'
```
Tacit version (48 chars):
```
(|:@((#{.)~,{.@]#{:@[)[:(1&,,:,&1)2&(-.@=/\)@{:)
```
Ungolfed version:
```
(|:@(({.@[#~]),{:@[#~{.@])((1&,),:,&1)@(-.@(0&=)@(2&(-/\)@{:)))
```
Maybe not the best way, but had a lot of fun golfing it down.
```
1 2 3 4 5 6 7 f 9 9 15 15 15 30 9
or
(...) 1 2 3 4 5 6 7,:9 9 15 15 15 30 9
1 2 9
3 5 15
6 6 30
7 7 9
```
[Answer]
# JavaScript, 106
```
function(c){for(var n={f:1,t:1,v:c[0]},r=[n],i=1,t;t=c[i++];)t^n.v?r.push(n={f:i,t:i,v:t}):n.t++;return r}
```
If input as a global called `c` is okay, then **101**:
```
eval.bind(0,'for(var n={f:1,t:1,v:c[0]},r=[n],i=1,t;t=c[i++];)t^n.v?r.push(n={f:i,t:i,v:t}):n.t++;r')
```
[Answer]
## Python, 86
```
n=input()
for s,v in n:
i=1
while[s+i,v]in n:n.remove([s+i,v]);i+=1
print s,s+i-1,v
```
[Answer]
## APL 39
```
(p/n),((1⌽p)/n←⍎⍞),[1.1](p←1,2≠/v)/v←⍎⍞
```
The above takes screen input as the function runs via ←⍎⍞. If the vectors n and v are allowed to be predefined globals then the count reduces to 33:
```
(p/n),((1⌽p)/n),[1.1](p←1,2≠/v)/v
```
For n←1 2 3 4 5 6 7 and v←9 9 15 15 15 30 9
```
1 2 9
3 5 15
6 6 30
7 7 9
```
[Answer]
# Python 2 - 82
```
r=p=[]
for x,y in input():
if[x-1,y]==p[1:]:p[1]=x
else:p=[x,x,y];r+=[p]
print r
```
Example usage:
```
echo "[[1,9],[2,9],[3,15],[4,15],[5,15],[6,30],[7,9]]"|python2 values.py
[[1, 2, 9], [3, 5, 15], [6, 6, 30], [7, 7, 9]]
echo "[[1,99],[2,99],[4,99],[6,99]]"|python2 values.py
[[1, 2, 99], [4, 4, 99], [6, 6, 99]]
```
[Answer]
### GolfScript, 49/44 characters
```
~]2/{\.@.@~@~@=@@-)!&!{n\}*}*][n]%{.0=0=\-1=~]p}%
```
The solution takes input from STDIN and prints to STDOUT. If you transform the code into an expression working on lists it reduces to 44 characters.
```
{\.@.@~@~@=@@-)!&!{n\}*}*][n]%{.0=0=\-1=~]}%
```
Example:
```
1 9
2 9
3 15
4 15
5 15
6 30
7 9
[1 2 9]
[3 5 15]
[6 6 30]
[7 7 9]
```
This version does also work with gaps as required.
```
1 9
3 9
4 15
6 15
7 15
[1 1 9]
[3 3 9]
[4 4 15]
[6 7 15]
```
[Answer]
# Golfscript - 42
```
~(~@@.@{.~5$=\3$)=&{;)}{:*;@]p*~\.}if}/@]p
```
Examples:
```
echo "[[1 9][2 9][3 15][4 15][5 15][6 30][7 9]]"|ruby golfscript.rb values.gs
[1 2 9]
[3 5 15]
[6 6 30]
[7 7 9]
echo "[[1 99][2 99][4 99][6 99]]"|ruby golfscript.rb values.gs
[1 2 99]
[4 4 99]
[6 6 99]
```
Explanation:
It takes the first pair [a b], and puts b, a, a1=a and the rest of the array on the stack. Then for each pair [x y] it compares y with b and x with a1+1. If equal then discards [x y] and increments a1, else pops and remembers [x y], prints [a a1 b] and pushes y, x, x1=x. At the end it prints the last [x x1 y].
] |
[Question]
[
If you're not familiar, [Dance Dance Revolution](http://en.wikipedia.org/wiki/Dance_Dance_Revolution) is a rhythm game where you hit four receptors (left, down, up, right) with your feet as arrows scroll up the screen. One of the file formats used to lay out the arrow patterns looks something like this:
```
1000
0100
0000
0011
,
```
A `1` represents a tap note. This chart has a left tap, a down tap, an empty line, and an up-right jump, respectively. The comma at the end indicates the end of a measure, and there can be any number of measures in a song.
Now here's an example of a more complicated chart:
```
1000
0010
0100
0001
0010
0100
2000
0000
,
0010
0001
3100
1001
,
```
The first measure has eight lines, so each line represents an eighth note, but the second measure only has four lines, all of which are quarter notes. All measures are the same duration; measures containing more lines are simply denser. You can assume that all measures will have lengths that are powers of two greater than or equal to 4. So measures can have 4 lines, 8 lines, 16 lines, and so on.
A `2` indicates the start of a hold arrow and a `3` represents its end. You can assume that each `2` will have a corresponding `3` in the same column, without anything between them other than zeroes and/or measure boundaries.
**Your task is to print the stepchart in a more human-readable format.** It's probably best if I just give you an example. Here's the expected output for the chart given above:
```
<
^
v
>
^
v
<
|
| ^
|
| >
|
|v
< >
```
*(If this is confusing to you, perhaps [looking at this](https://i.stack.imgur.com/XwsMP.png) will help.)*
Left, down, up, and right taps are indicated by `<`, `v`, `^`, and `>`, respectively. Hold arrows are indicated by pipes that trail beneath the starting taps.
Additionally, the chart needs to be stretched so that each measure is the same length: in the above example, the measures have lengths of 8 and 4, so the output shows all measures as if they contained eighths. If you have a chart where all measures are 4 lines long except for one that's 64 lines, the output needs to render all measures as 64 lines long!
**I/O:** Assume the chart exists in a file whose name is given as the first argument to the program (e.g. `python arrows.py input.txt`). Write to standard output. If (and only if) your language of choice doesn't have filesystem access for whatever reason, it's acceptable to load it as a string at the beginning of the program.
**Goal:** The program with the fewest characters will be accepted a week from now, the 17th of August, around 8:00 EST.
[Answer]
## GolfScript ~~132~~ 129
```
','/{n/{},}%{},.{,}%.$):§;;{§\/(}%]zip{~:¥;{['0'4*]¥*~}%}%{+}*zip 1:¤;{0:^;{.^2=5@48=!¤*if\48-^or:^;' <v^>|'=}%¤):¤;}%zip{+}*4/n*
```
Online demo [here](http://golfscript.apphb.com/?c=OycxMDAwCjAwMTAKMDEwMAowMDAxCjAwMTAKMDEwMAoyMDAwCjAwMDAKLAowMDEwCjAwMDEKMzEwMAoxMDAxCiwnCgonLCcve24ve30sfSV7fSwueyx9JS4kKTrCpzs7e8KnXC8ofSVdemlwe346wqU7e1snMCc0Kl3CpSp%2BfSV9JXsrfSp6aXAgMTrCpDt7MDpeO3suXjI9NUA0OD0hwqQqaWZcNDgtXm9yOl47JyA8dl4%2BfCc9fSXCpCk6wqQ7fSV6aXB7K30qNC9uKg%3D%3D&run=true)
[Answer]
## C, 364, 331, 310, 293
```
#define L(A)for(p=b+9;*p;)if(*p-44){A;t++;p+=5;}else{m=t>m?t:m;p[4-5*t]=t;t=0;p+=2;}
c,j,t,m,x;char b[9999],*p;main(int i,char*v[]){read(open(v[1],0),b+9,9999);L()L(x=t?x:m/p[4];for(j=x*4;j-->0;){i=j%4;b[i]=" |"[b[i+5]];c=p[i]&3;p[i]=0;if(c&&c<3)b[i]="<v^>"[i];if(c>1)b[i+5]=3-c;i?:puts(b);})}
```
Limits:
* max input file size of 9990 chars
* max measure of 128
Run:
```
./a.out test.dance
```
output:
```
<
^
v
>
^
v
<
|
| ^
|
| >
|
|v
< >
```
Ungolfed commented version:
```
#define L(A)\
for(p=b+9;*p;)/* loop through file */\
if(*p-44){ /* line */\
A;\
t++;\
p+=5; /* 4 steps+linefeed */\
}else{ /* comma line */\
m=t>m?t:m; /* max measure */\
p[4-5*t]=t; /* store measure in '\n' char of first line */\
t=0;\
p+=2; /* comma+linefeed */\
}
c,j,t,m,x;char b[9999],*p; // b[0..4] output, b[5..8]=hold, b[9..9999]=file
main(int i,char*v[]){
read(open(v[1],0),b+9,9999);
// pass 1 - determine max measure
L()
// pass 2 - process steps and output
L(x=t?x:m/p[4]; // repeats per line (first line p[4] is measure)
for(j=x*4;j-->0;){ // 4 steps per repeat
i=j%4; // the step
b[i]=" |"[b[i+5]];
c=p[i]&3; // step type 0,1,2,3
p[i]=0; // reset step to 0 for future iterations
if(c&&c<3)b[i]="<v^>"[i];
if(c>1)b[i+5]=3-c; // set/reset hold
i?:puts(b); // every 4th step
}
)
}
```
[Answer]
# C - 466 460 438 bytes
```
#define C while(fgets(b,6,f))
p[9]={'>^v<',0,'||||',0,' '},Y,M,T,R,E,*W,Q,i;char b[9];main(int n,char*v[]){int*f=fopen(v[1],"r");W=malloc(4e5);C if(*b!=44)++T;else{W[++Q-1]=T;Y=T>Y?T:Y;T=0;}fseek(f,0,0);Q=0;C{if(*b!=44){R=0;M=E;for(i=0;i<4;++i){R|=(b[i]>48&&b[i]<51)*255<<i*8;E|=b[i]==50?255<<i*8:0;E&=~(b[i]==51?255<<i*8:0);}p[6]=*p&R|(~R^M)&p[4]|(M&R^M)&p[2];puts(p+6);p[6]=p[4]&~E|p[2]&E;for(i=0;i<Y/W[Q]-1;++i)puts(p+6);}else++Q;}}
```
The output from this, using the given input file, is:
```
<
^
v
>
^
v
<
|
| ^
|
| >
|
|v
< >
```
Should be fairly compliant to most compilers.
[Answer]
## PHP 274 chars
My first code golf. All comments are welcome.
```
<?php
$i = '1000 0010 0100 0001 0010 0100 2000 0000 0010 0001 3100 1001 ,';
$f=explode(' ', $i);$a=array("<","v","^",">");$t=-1;foreach($f as$n){if($n==',')return;else{$j=str_split($n);$o=0;foreach($j as$h){switch($h){case 2:$t=$o;case 1:$h=$a[$o];break;case 0:$h=" ";if($t>=0&&$t==$o){$h="|";}break;case 3:$t=4;$h="|";break;}echo$h;$o++;}echo"\n";}}
?>
```
Should I count the `<?php ?>` tags?
Thank you.
[Answer]
# Mathematica 283 chars
The following works with measures of `2^(2 n)` lines.
```
v = Import["a.xls"];
g@p_ := 2~Log~p; t = Transpose; l = Length; s = Sequence;
r_~h~o_ := t[Flatten[
Riffle[#, x, {2, -1, 2}] /. x -> s @@ ConstantArray[{0, 0, 0, 0},
2^(g@Max[l /@ v] - g@l@#) - 1] & /@ v, 1]][[r]]
/. {a___, 2, b__, 3, c___} :> {a, 2, s @@ Cases[{b}, 0 :> "|"], "|", c}
/. {0 -> " "} /. {1 | 2 -> o};
t@{1~h~"<", 2~h~"v", 3~h~"^", 4~h~">"} // Grid
```
Data file, imported as `v`, is structured as follows:
```
{{{1,0,0,0},{0,0,1,0},{0,1,0,0},{0,0,0,1},{0,0,1,0},{0,1,0,0},{2,0,0,0},{0,0,0,0}},{{0,0,1,0},{0,0,0,1},{3,1,0,0},{1,0,0,1}}};
```
] |
[Question]
[
Write a program that either accepts input via stdin or from the command line. It will then unscramble the words, printing out the unscrambled version of each word.You get a text file containing every word (most of them) in the English dictionary to use. (Here is the file: [Word List](http://web.mit.edu/kilroi/Public/bot/wordlist), and you can either use it from the web or save it as a text file and use it from there.)
## Inputs to measure the score:
>
> bbuleb lwrfoe kaec rtawe cokr kmli pcaee
>
>
>
## Correct Outputs:
>
> bubble flower cake water rock milk peace
>
>
> bubble fowler cake water cork milk peace
>
>
>
(Word case doesn't matter, and please post your score and outputs along with your code!)
## Scoring:
Score = (Amount of correct outputs) x (100 / (Code Length))
The code with the highest score wins!
**Edit:** This is my first post, please be kind!
[Answer]
## Python 3 / 84 chars / 7 correct outputs / score 8.3333
**edit** As per clarifications, removed `.upper()` and considering all 7 ouputs correct.
```
a=sorted
for b in input().split():print([c for c in open('x')if a(b)==a(c[:-1])][0])
```
Output:
```
BUBBLE
FLOWER
CAKE
WATER
CORK
MILK
PEACE
```
[Answer]
## GolfScript, 27 chars, 7 correct outputs ⇒ score ≈ 25.926
```
n%(\:w;' '%{$:c;w{$c=}?}%n*
```
GolfScript doesn't have a file I/O operator, so I had to get a bit clever with the input. Specifically,
* the scrambled words should be given on the first input line, separated by spaces, and
* the wordlist should be given on the subsequent input lines, one word per line.
The scrambled words and the wordlist need to have the same letter case.
Here's an example invocation from a Unix shell command line, assuming that the code above has been saved as `unscramble.gs`, the GolfScript interpreter as `golfscript.rb` and the wordlist as `wordlist.txt`:
```
(echo BBULEB LWRFOE KAEC RTAWE COKR KMLI PCAEE; cat wordlist.txt) \
| ruby golfscript.rb unscramble.gs
```
This will produce the following output:
```
BUBBLE
FLOWER
CAKE
WATER
CORK
MILK
PEACE
```
The way it works is simply by sorting the letters in each input word and selecting the first word in the wordlist that produces the same string when its letters are sorted. Nearly half of the code is actually just for input parsing (and output formatting): all the real work is done in the `{$:c;w{$c=}?}%` loop.
Here's a de-golfed version with comments showing how it works:
```
n % # split the input on newlines
( \ :w ; # pop the first line off the list of lines and assign the rest to w
' ' % # split the first line on spaces
# apply the following map to each scrambled word:
{
$ :c ; # sort the letters in the word and assign the sorted word to c
w { $ c = } ? # find the first word in w that, sorted, equals c
} %
n * # join the results with newlines for output
```
[Answer]
## Python, ~~189~~ ~~171~~ 156 chars / ~~6~~ 7 correct outputs / "spirit of the law"
```
from urllib import*
z=sorted
x=dict((`z(m)`,m)for m in urlopen("http://bit.ly/wZYCmE").read().split())
for n in raw_input().split():print x[`z(n.upper())`]
```
(It gets "fowler" instead of "flower", both are on the input list and have the same letters.)
Edit: Steven Rumbalski's suggestions
## Python, 144 chars / 7 correct outputs / "letter of the law"
```
for x in raw_input().split():print{620:'bubble',655:'flower',404:'cake',547:'water',431:'rock',429:'milk',510:'peace'}[sum(map(ord,x.lower()))]
```
[Answer]
### bash, grep, sed, sort: 144 chars, 144/7=20.57 (all correct)
```
s(){
echo $1|sed 's/./\n&/g'|sort
}
for w in $*
do
for m in $(egrep "^["$w"]{"${#w}"}$" d)
do
[[ `s $w` = `s $m` ]] &&(echo $m;break)
done
done
```
d is the filename of the dict; for testing on Linux replace it with `$d` as `d=/usr/share/dict/words` and subtract 1 from the filesize, to avoid a local copy.
usage:
```
./unscramble.sh bbuleb lwrfoe kaec rtawe cokr kmli pcaee
bubble
flower
cake
water
cork
rock
milk
peace
```
works well with dict/words, so I didn't download anything, lazy me! :)
[Answer]
## Perl, 173 characters / 6 correct outputs
```
use LWP::Simple;
sub e{my$m;$m.=$_ for sort split//,uc$_[0];$m}$_=get"http://bit.ly/wZYCmE";
@x=split/\n/;$_=<>;for(split){$l=$_;for(@x){print"$_ ",$l=''if(e$_)eq e$l}}
```
[Answer]
## JavaScript, ~~357~~ 330 chars [node.js] / 7 correct outputs
```
function g(w,s){return s===+s?g[a=w.toUpperCase().split("").sort().join("")]=g[a]||w:w.split("\n").map(g)&&s.split(" ").map(g).join(" ")}require('http').get({host:'web.mit.edu',path:'/kilroi/Public/bot/wordlist'},function(r){b=[];function f(c){c?b.push(c):console.log(g(b.join(""),process.argv[2]))}r.on('data',f),r.on('end',f)})
```
Eugh... slightly prettier version below. Doesn't read from stdin (string to check is first command-line argument), but it *does* fetch the dictionary from the net. The `g` function receives a string with the dictionary content (`w`) and a string to check (`s`); this is the most interesting part I suppose.
(It should theoretically work on any input string, as long as there's a permutation of each word in the dictionary. Oh, and the output is currently upper-case [as it is in the dictionary])
```
function g(w,s) {
return s===+s
? g[a=w.toUpperCase().split("").sort().join("")] = g[a] || w
: w.split("\n").map(g) && s.split(" ").map(g).join(" ")
}
require('http').get({host:'web.mit.edu',path:'/kilroi/Public/bot/wordlist'}, function(r) {
b=[]
function f(c) {
c ? b.push(c)
: console.log(g(b.join(""), process.argv[2]))
}
r.on('data',f)
r.on('end',f)
})
```
[Answer]
# Q,38 chars, 7 correct, 18.42105 points
```
{1#d(&)1=asc[x]~/:(asc')d:(_)read0`:d}
```
d is the dictionary file, stored locally in the same working directory.
usage:
```
{1#d(&)1=asc[x]~/:(asc')d:(_)read0`:d} each ("bbuleb";"lwrfoe";"kaec";"rtawe";"cokr";"kmli";"pcaee")
"bubble"
"flower"
"cake"
"water"
"cork"
"milk"
"peace"
```
[Answer]
## PHP 270bytes Source. SCORE- ?
I'm not sure if if this type of output is accepted, please inform if its wrong.
```
<?$s=explode(PHP_EOL,file_get_contents('http://bit.ly/wZYCmE'));$n=explode(' ',$argv[1]);for($i=0;$i<count($n);$i++){$f=0;for($j=0;$j<count($s);$j++){$t1=str_split(trim($n[$i]));sort($t1);$t2=str_split($s[$j]);sort($t2);if($t1==$t2){$f++?echo'/':0;echo$s[$j];}}echo' ';}
```
Run:
```
php unscramble.php "BBULEB LWRFOE KAEC RTAWE COKR KMLI PCAEE"
```
Output:
```
BUBBLE FLOWER/FOWLER CAKE WATER CORK/KROC/ROCK MILK PEACE
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes, 7 correct outputs ⇒ score = 50 (Feedback appreciated!)
```
ɠḲ©µ³ḲŒ!f®ḢƊ€K
```
[Try it online! (Long URL)](http://tx0.org/s4 "Jelly – Try It Online")
Feed space-separated dictionary on `stdin` and space-separated scrambled words as the first argument, e.g. `curl http://web.mit.edu/kilroi/Public/bot/wordlist | tr '\n' ' ' | jelly fun unscrambler.j "BBULEB LWRFOE KAEC RTAWE COKR KMLI PCAEE"`
```
ɠḲ©µ³ḲŒ!f®ḢƊ€K
ɠḲ©µ read the dictionary from stdin splitting on spaces, and save it to the register
³Ḳ split the scrambled word list argument on spaces
Ɗ define a function of the previous three links taking an input W:
Œ!f® get all permutations of W, and filter it with the dictionary
(aka, remove all words in the dictionary that are not permutations of W)
Ḣ take the head, so we return just one unscrambled word per scrambled word
€K run that Ɗ function on each of the unscrambled words, and split the results with spaces
```
[Answer]
# Zsh, 129 chars / 7 correct outputs ⇒ score ≈ 5.426
```
for i in $@
do
while read w
do
[[ ${#w} == ${#i} ]]&&[[ ${${(Lo)${(s::)w}}} == ${${(Lo)${(s::)i}}} ]]&&echo $w&&break
done<d
done
```
Usage:
Save the word list as `d` in the same directory as the script, and from that directory run
```
% zsh ./unscramble.zsh bbuleb lwrfoe kaec rtawe cokr kmli pcaee
BUBBLE
FLOWER
CAKE
WATER
CORK
MILK
PEACE
```
How it works:
`(s::)` splits into single-character words
`(L)` lowercases
`(o)` sorts ascending
Was inspired to try after reading [this blog post](https://www.viget.com/articles/unscramble-a-programming-challenge/). Not golf, but a fun survey. (Disclaimer: the article's from one of the other teams at my workplace.)
] |
[Question]
[
### Introduction:
I [collect twisty puzzles](http://twistypuzzles.com/forum/viewtopic.php?f=14&t=26889), so I'm quite the fan of [rubiks-cube](/questions/tagged/rubiks-cube "show questions tagged 'rubiks-cube'")-challenges (even though most are fairly difficult). So, let's try a fairly easy [rubiks-cube](/questions/tagged/rubiks-cube "show questions tagged 'rubiks-cube'")-challenge for a change.
When an NxNxN Cube gets scrambled during a [WCA (World Cubing Association)](https://www.worldcubeassociation.org/) competition, the cube is always held in the same way before executing the scramble-algorithm:
>
> ## [Article 4](https://www.worldcubeassociation.org/regulations/#article-4-scrambling): Scrambling
>
>
> * [4d](https://www.worldcubeassociation.org/regulations/#4d)) Scrambling orientation:
> + [4d1](https://www.worldcubeassociation.org/regulations/#4d1)) **NxNxN puzzles** and Megaminx **are scrambled starting with the white face** (if not possible, then the lightest face) **on top and** the **green face** (if not possible, then the darkest adjacent face) **on the front**.
>
>
>
"*NxNxN puzzles are scrambled starting with the white face on top and the green face on the front.*"
### Challenge:
For the sake of this challenge we only have to look at the centers, so we'll use a 1x1x1 instead of a 3x3x3. Given a valid 1x1x1 Cube in any orientation, output which rotations of `x`/`x'`, `y`/`y'`, and/or `z`/`z'` are required to have green at the front and white at the top.
### Input:
The input will be a 1x1x1 Cube layout in the following format (where `F` is the front, and `U` is the top):
```
U
LFRB
D
```
For example:
```
Y
BRGO
W
```
### Output:
The output will be the least amount of rotations of `x`/`x'`, `y`/`y'`, and/or `z`/`z'` required to have the white center at the top and green center at the front.
```
x y z
```
[](https://i.stack.imgur.com/LC8Qw.gif)[](https://i.stack.imgur.com/8XWq3.gif)[](https://i.stack.imgur.com/s6tmy.gif)
```
x' y' z'
```
[](https://i.stack.imgur.com/JmBOh.gif)[](https://i.stack.imgur.com/VWVP0.gif)[](https://i.stack.imgur.com/0LeLb.gif)
We basically always want to end up in this orientation:
```
W
OGRB
Y
```
The example given above would therefore result in either of these outputs: `x2y`/`xxy`/`x'x'y`.
NOTE: In the still image of the gifs above, White is the Upper face and Red is the Front face. So the still image of the gif is:
```
W
GRBO
Y
```
### Challenge rules:
* You are allowed to take the input in any reasonable format.
+ You could use other characters or numbers (i.e. `0-5`/`1-6`) instead of `WYROGB`
+ You can take the input as single String, as new-line delimiter single String, as String-array, character-array or -matrix, integer-array or -matrix, etc. Your call. (For example, `WOGRBY` is a valid input in the format `ULFRBD`.)
+ **Please specify what input-format you've used!**
* The output must use `xyz`, but instead of `x'` you are also allowed to use `x3` or `X`, or instead of `x2` you can also use `xx` (NOTE: You are NOT allowed to use `xxx` instead of `x'`/`x3`/`X`).
+ Always output the *least amount of rotations*. So although `x'x'y'y'y'` instead of `x2y` results in the same orientation of the Cube in the end, it's not a valid output because there is a better alternative. Same applies to
`x2y2`, because `xy'z` is one move shorter (`x2`/`xx` counts as two moves).
As thumb rule: every possible input results in 0-2 `x`, 0-2 `y` and/or 0-2 `z` rotations, and you'll never need more than three rotations in total (i.e. `x2z2` → `y2`)
* You can assume all inputs are valid 1x1x1 Cubes.
* If the input is already in the correct position (green front, white top), output nothing (or something indicating nothing, like `null`, `false`, `0`, an error, etc.)
### General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, 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.
* Also, please add an explanation if necessary.
### Test cases:
```
Input: Output (multiple valid answers are possible for some):
Y
BRGO x2y y'x2 z2y' yz2 zy'x zxz xzx xyz
W
W
OGRB nothing
Y
G
RWOY y2x' z2x yzy xy2 x'z2 yx'z zxy zyz
B
W
RBOG y2
Y
R
BWGY yz zx xy
O
G
WOYR x'z zy yx'
B
```
[Answer]
# JavaScript (ES6), 95 bytes
```
n=>'y2+X+Zyx+ZX+z+ZY+z2+x+Y+zx+zy+Zy2+z2X+x2+zX+y+zY+Z+z2x++Zx+z2Y+Zx2+Zy'.split`+`[n%10955%24]
```
This works similarly to [@Arnauld's answer](https://codegolf.stackexchange.com/a/155454/70894) (credits to him for the idea), but inputs as a base-10 integer (with `123456` instead of `WYROGB`), which skips the base decoding.
## Hash function
```
Input | mod 10955 | mod 24 | Output
-------+-----------+--------+-------
136452 | 4992 | 0 | "y2"
145362 | 2947 | 19 | ""
153642 | 272 | 8 | "Y"
164532 | 207 | 15 | "y"
235461 | 5406 | 6 | "z2"
246351 | 5341 | 13 | "x2"
254631 | 2666 | 2 | "Zyx"
263541 | 621 | 21 | "z2Y"
315264 | 8524 | 4 | "z"
326154 | 8459 | 11 | "Zy2"
352614 | 2054 | 14 | "zX"
361524 | 9 | 9 | "zx"
416253 | 10918 | 22 | "Zx2"
425163 | 8873 | 17 | "Z"
451623 | 2468 | 20 | "Zx"
462513 | 2403 | 3 | "ZX"
514236 | 10306 | 10 | "zy"
523146 | 8261 | 5 | "ZY"
531426 | 5586 | 18 | "z2x"
542316 | 5521 | 1 | "X"
613245 | 10720 | 16 | "zY"
624135 | 10655 | 23 | "Zy"
632415 | 7980 | 12 | "z2X"
641325 | 5935 | 7 | "x"
```
## Test Cases
```
f=n=>'y2+X+Zyx+ZX+z+ZY+z2+x+Y+zx+zy+Zy2+z2X+x2+zX+y+zY+Z+z2x++Zx+z2Y+Zx2+Zy'.split`+`[n%10955%24]
console.log(f(263541))
console.log(f(145362))
console.log(f(531426))
console.log(f(136452))
console.log(f(361524))
console.log(f(514236))
```
[Answer]
# JavaScript (ES6), 114 bytes
*Saved 15 bytes thanks to @ngn*
Picking the results from a lookup table turns out to be significantly shorter than my best attempt so far at golfing a solver.
Outputs **X**, **Y** and **Z** instead of **x'**, **y'**, **z'**.
```
s=>'X//Zy//Zyx/z2/zX/Zx2//z2Y/x/Zy2//x2/Zx/z2X/zY/z2x/ZY/z/y//ZX/zy/y2//zx/Z/Y/'.split`/`[parseInt(s+0,35)%405%31]
```
### Test cases
```
let f =
s=>'X//Zy//Zyx/z2/zX/Zx2//z2Y/x/Zy2//x2/Zx/z2X/zY/z2x/ZY/z/y//ZX/zy/y2//zx/Z/Y/'.split`/`[parseInt(s+0,35)%405%31]
console.log(f('YBRGOW')); // z2Y
console.log(f('WOGRBY')); // nothing
console.log(f('GRWOYB')); // z2x
console.log(f('WRBOGY')); // y2
console.log(f('RBWGYO')); // zx
console.log(f('GWOYRB')); // zy
```
### Solver
Here is the solver used to generate the moves stored in the lookup table.
```
s => {
const rot = [ '215304', '023415', '152043' ];
const S = [];
// recursive function looking for all possible solutions of at most 6 clockwise moves
const g = (s, m, r = 0) => {
if(s == 'WOGRBY') {
// this is a solution; replace 3 consecutive identical clockwise moves with a
// single counterclockwise move; rewrite 2 consecutive identical moves as 'x2';
// store the result in S[]
S.push(m.replace(/(.)\1\1/g, s => s[0].toUpperCase()).replace(/(.)\1/g, '$12'));
}
else if(!m[5]) {
// try the next rotation on the current cube
if(r < 2) {
g(s, m, r + 1);
}
// apply the current rotation and restart from there
g([...rot[r]].reduce((r, i) => r + s[i], ''), m + 'xyz'[r]);
}
}
// find all solutions
g(s, '');
// find the length of the shortest solution(s)
const min = Math.min(...S.map(s => s.length));
// return the 1st solution matching this length
return S.find(s => s.length == min);
}
```
### Hash function
Below is a summary of the results provided by the hash function for all 24 valid inputs, along with the corresponding solutions.
```
input | base 35->10 | * 35 | mod 405 | mod 31 | output
----------+-------------+-------------+---------+--------+--------
"WOGRBY" | 1717434494 | 60110207290 | 370 | 29 | ""
"WBOGRY" | 1698256454 | 59438975890 | 175 | 20 | "y"
"WRBOGY" | 1721718494 | 60260147290 | 55 | 24 | "y2"
"WGRBOY" | 1705881974 | 59705869090 | 400 | 28 | "Y"
"OGWBYR" | 1285921692 | 45007259220 | 45 | 14 | "Zx"
"OYGWBR" | 1312271862 | 45929515170 | 120 | 27 | "Z"
"OBYGWR" | 1278510372 | 44747863020 | 270 | 22 | "ZX"
"OWBYGR" | 1309058862 | 45817060170 | 255 | 7 | "Zx2"
"GRWOYB" | 882269476 | 30879431660 | 110 | 17 | "z2x"
"GYRWOB" | 892568926 | 31239912410 | 80 | 18 | "ZY"
"GOYRWB" | 877856956 | 30724993460 | 155 | 0 | "X"
"GWOYRB" | 889441606 | 31130456210 | 395 | 23 | "zy"
"RBWGYO" | 1435990314 | 50259660990 | 150 | 26 | "zx"
"RYBWGO" | 1469623284 | 51436814940 | 135 | 11 | "Zy2"
"RGYBWO" | 1443572994 | 50525054790 | 285 | 6 | "zX"
"RWGYBO" | 1466838684 | 51339353940 | 360 | 19 | "z"
"BYOWRG" | 629831036 | 22044086260 | 250 | 2 | "Zy"
"BRYOWG" | 619745786 | 21691102510 | 325 | 15 | "z2X"
"BWRYOG" | 626960756 | 21943626460 | 295 | 16 | "zY"
"BOWRYG" | 615161906 | 21530666710 | 10 | 10 | "x"
"YOBRGW" | 1822264042 | 63779241470 | 230 | 13 | "x2"
"YGOBRW" | 1810797202 | 63377902070 | 35 | 4 | "Zyx"
"YRGOBW" | 1826976442 | 63944175470 | 5 | 5 | "z2"
"YBRGOW" | 1803428722 | 63120005270 | 350 | 9 | "z2Y"
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~84~~ 83 bytes
```
->a{k=a.index(0);%W{#{} z x Z X zz xx}[k+=k/5*a[2]/3]+%W{#{} Y yy y}[a[c=1+k%2]-c]}
```
[Try it online!](https://tio.run/##dZLbaoQwFEXf5ysOlIG2Zjq5@VTsb/QS8mCnHShCKW0HdMRvtwnbE7WOPilrJ3udg9@n16Y/Fv3uoWyrorz7@Hx7r6/lzf32sb1qOzpTTS/0ROfwUneuyopqn9@WTvu98dkQeqamoaZzpTsUKqu22u8Ovuu/6OicFLQhIiW0MMLigyj3fjPFViCwguPJGFjBuFrN8On3B5mcG0y4IGUkX5FzQ4R2DQOaNQyoZzgJDKdk4PnYoPgKzVgFnBosY8XYBpwaDGPL2ASsBKie9Vt2RGgSmdhZAb@FHJYDu4UaVgO3iViqHuSjuBxHn8iDQo0um8WdyXHyf2pxZTINbmftmgdH6KI9tirFRTPsNPxk4VnIYXbYJbX@Dw "Ruby – Try It Online")
Llambda function taking an array of 6 numbers 0..5 representing the faces, with the following solved configuration
```
0
1234
5
```
Searches for the index of the array element containing `0` and selects a string for the move required to move it to the top: either by rotating in the x or z axis (or the empty string if it is already there, represented by `#{}` in `%W{}` notation.)
Then, inspect either array element 1 or 2 (whichever would not be altered by performing the move in the above step), select a string (always rotation in the y axis) for the move required to move the contents of the element to their solved location, and return the concatenated moves.
An issue arises when the index of the array containing `0` is 5, as there are two possible moves that will return it to the top: `zz` and `xx`. If array element 2 (the front of the cube) contains `2` the cube can be completely solved by `zz`, and if it contains `4` it can be solved by `xx`. The default is value to be returned is `zz` but if the front face contains `3` or `4` the expression `k/5*a[2]/3` adds 1 to the index of `%W{#{} z x Z X zz xx}` that is returned, correcting it to `xx`. (Note that if the front face contains `1` or `3` it doesn't matter whether `xx`or `zz` is used as in these cases an additional 90 deg rotation will be required about the y axis regardless of whether `xx` or `zz` is used.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~47~~ 43 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
To answer [my own question](https://codegolf.stackexchange.com/a/156090/53748), yes a straight hash is shorter, and not just a little!
```
“ḥɦƁþhƓWsFUḃṡIụA]OṆrṠ€5ⱮI’ṃ“XZyxzY ”Ḳɓ%⁽'Ṙị
```
A monadic link taking an integer with `WOGRBY` as `145362` and returning a list of characters using the **x**, **xx**, **X** format.
**[Try it online!](https://tio.run/##AWIAnf9qZWxsef//4oCc4bilyabGgcO@aMaTV3NGVeG4g@G5oUnhu6VBXU/huYZy4bmg4oKsNeKxrknigJnhuYPigJxYWnl4elkg4oCd4biyyZMl4oG9J@G5mOG7i////zEzNjQ1Mg "Jelly – Try It Online")**
### How?
Uses the hash function found by [Herman Lauenstein](https://codegolf.stackexchange.com/users/70894/herman-lauenstein) in their [JavaScript answer](https://codegolf.stackexchange.com/a/155590/53748) -- go give credit!
```
“ḥɦƁþhƓWsFUḃṡIụA]OṆrṠ€5ⱮI’ṃ“XZyxzY ”Ḳɓ%⁽'Ṙị - Main link 1: integer, N
“ḥɦƁþhƓWsFUḃṡIụA]OṆrṠ€5ⱮI’ - base 250 literal = 3078729180217463783054936423617578759678999380687706537574
“XZyxzY ” - literal list of characters = "XZyxzY "
ṃ - base decompress = "X Zyx ZX z ZY zz x Y zx zy Zyy zzX xx zX y zY Z zzx Zx zzy Zxx Zy yy"
- (use the seven characters as digits 1,2,3,4,5,6,0)
Ḳ - split at spaces = ["X","Zyx","ZX","z","ZY","zz","x","Y","zx","zy","Zyy","zzX","xx","zX","y","zY","Z","zzx","","Zx","zzy","Zxx","Zy","yy"]
ɓ - new dyadic chain with swapped arguments
⁽'Ṙ - 10955
% - modulo (N) by (10955)
ị - index into (the move list)
- Note: Jelly indexing is 1-based & modular
- so a %24 is surplus to requirements
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 75 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
I've been meaning to do this challenge for a while. I wonder if a straight hashing approach will be shorter than this solver.
```
“¡Çµ‘ṗЀ7Ḷ¤Ẏ
œ?ạ⁸%7¤¦7
⁹Ḣ¤ç¥⁹¿
ỤỤḣ3çЀÑĠḢịÑ+9µŒgPL⁼¥¡€3Fµ€LÞḢ×28+62%⁹%9ị³Ṣ¤
```
A full program accepting a list of characters as input and printing the result to STDOUT using the **x**, **xx**, **X** format.
For the sake of saving two**!** bytes it uses the somewhat confusing input:
```
X = White Y = Orange Z = Green
z = Yellow y = Red x = Blue note: this makes the solved state XYZyxz
```
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDCw@3H9r6qGHGw53TD0941LTG/OGObYeWPNzVx3V0sv3DXQsfNe5QNT@05NAyc65HjTsf7lh0aMnh5YeWAtmH9nM93L0EhHYsNj68HKz78MQjC4BqHu7uPjxR2/LQ1qOT0gN8HjXuObT00EKgtLEb0K6mNT6H5wEVHZ5uZKFtZqQKNErVEqjj0OaHO4Gm////vyoqsqIyAgA "Jelly – Try It Online")**
### How?
Defines a dyadic link which can perform an **x**, **y**, or **z** to its right argument, an Up-Left-Front triple (ULF) of faces where:
```
1 = White 2 = Orange 3 = Green
6 = Yellow 5 = Red 4 = Blue note: the solved state has ULF = 1,2,3
7 7 7 <-- ...and the sums of opposite faces are all 7
```
for certain left arguments:
```
if left % 6 == 0 and left % 7 in (0, 3): # e.g. left = 0
performs x
# switches U&F, ULF to FLU, (permutation 0)
# and switches the new U (index 0 or 3) to its opposite colour (7-value)
elif left % 6 == 2 and left % 7 in (0, 3): # e.g. left = 14
performs y
# switches L&F, ULF to UFL, (permutation 2)
# and switches the new L (index 0 or 3) to its opposite colour (7-value)
elif left % 6 == 3 and left % 7 in (-1, 2): # e.g. left = 9
performs z
# switches U&L, ULF to LUF, (permutation 3)
# and switches the new U (index -1 or 2) to its opposite colour (7-value)
else:
does some other permutation and opposite colour swap which we wont use.
```
Creates all sequences made from the left inputs `0,14,9` of length zero to six
```
i.e. [[],[0],[14],[9],[0,0],[0,14],[0,9],[14,0],...,[9,9,9,9,9,9]]
```
and then repeatedly applies the link to the ULF of the translated input with the numbers in the list as the left arguments.
Translation of the input is performed by a double application of grade-up, `Ụ`, since the ordering used is chosen to make that work (the natural ordering of the characters is `XYZxyz`); while UFL is extracted by simply taking the first three results, `ḣ3`.
The sequences that result in a transformation to `[1,2,3]` (the solved state) are then transformed such that any run of exactly three of the same move are multiplied together.
Some arithmetic is performed to transform the results to be the indexes of `"XYZxyz"`. This was found by brute-force to be to add nine prior to the multiplication, then to multiply all results by 28, to add another 62, to modulo by 256 to modulo again by 9 and finally to modulo by 6 (although the final modulo may be performed by indexing into something of length 6 since Jelly indexing is modular)
```
move value add 9 product times 28 add 62 mod 256 mod 9 mod 6
X [ 0, 0, 0] [ 9, 9, 9] 729 20412 20474 250 7 1
Y [14,14,14] [23,23,23] 12167 340676 340738 2 2 2
Z [ 9, 9, 9] [18,18,18] 5832 163296 163358 30 3 3
x 0 9 9 252 314 58 4 4
y 14 23 23 644 706 194 5 5
z 9 18 18 504 566 54 0 0
```
All that remains is to take the first shortest result and to index into the sorted input, `"XYZxyz"`
---
Commented code:
```
“¡Çµ‘ṗЀ7Ḷ¤Ẏ - Link 1, get all sequences of 0,14,9 up to length 6: no arguments
“¡Çµ‘ - code-page indices = [0,14,9]
¤ - nilad followed by link(s) as a nilad:
7 - literal seven
Ḷ - lowered range = [0,1,2,3,4,5,6]
Ѐ - map across right:
ṗ - Cartesian power -> [[[]],[[0],[14],[9]],[[0,0],[0,14],[0,9],...,[9,9]],...,[[0,0,0,0,0,0],...,[9,9,9,9,9,9]]]
Ẏ - tighten -> [[],[0],[14],[9],[0,0],[0,14],[0,9],...,[9,9],...,[0,0,0,0,0,0],...,[9,9,9,9,9,9]]
œ?ạ⁸%7¤¦7 - Link 2, perform a manoeuvre: integer, N; list of integers, [U,L,F]
œ? - Nth permutation of [U,L,F]
7 - literal seven
¦ - sparse application...
ạ - ...of: absolute difference (from 7) -- i.e. opposite colour
¤ - ...to indexes: nilad followed by link(s) as a nilad:
⁸ - chain's left argument = N
7 - literal seven
% - modulo
⁹Ḣ¤ç¥⁹¿ - Link 3, perform manoeuvres: list of integers, [U,L,F], list of integers, M
¿ - while...
⁹ - ...condition: chain's right argument, M (while there are manoeuvres)
¥ - ...do: last two links as a dyad:
¤ - nilad followed by link(s) as a nilad:
⁹ - chain's right argument, M
Ḣ - pop head -- gets the first element and modifies M
ç - call last link (2) as a dyad (right is chain's left argument, [U,L,F])
ỤỤḣ3çЀÑĠḢịÑ+9µŒgPL⁼¥¡€3Fµ€LÞḢ×28+62%⁹%9ị³Ṣ¤ - Main link: list of characters, S
Ụ - grade-up (sort indices by value)
Ụ - grade-up again (net effect X->1, Y=>2, Z->3, x->4, y->5, z->6)
ḣ3 - head to index three (get the ULF triple)
Ñ - call next link (1) as a monad (the input is not consumed, but that's OK)
Ѐ - map across right with:
ç - call last link (3)
Ġ - group the indices by value (placing all solved indices in the head, since [1,2,3] is less than others)
Ḣ - head
Ñ - call next link (1) as a monad (get the instructions again)
ị - index into (get the solving instruction lists)
+9 - add nine to all values in all instruction lists
µ µ€ - for €ach instruction list:
Œg - group runs of equal elements
3 - literal three
¡€ - repeat for €ach group...
P - ...action: product
¥ - ...number of times: last two links as a dyad
L - length
⁼ - equal to (three)? -- i.e. take the product of any run of exactly three values
F - flatten (back to a single list)
Þ - sort by:
L - length (getting the shorted solving instruction list to the front)
Ḣ - head
×28 - multiply all the values by 28
+62 - add 62 to all the values
⁹ - literal 256
% - modulo by (256)
%9 - modulo by 9
¤ - nilad followed by link(s) as a nilad:
³ - program's (1st) input
Ṣ - sort (always = "XYZxyz")
ị - index into
- implicit print to STDOUT
```
] |
[Question]
[
# Specifications
For this challenge, you will be given a matrix of some sort in any reasonable format for a 2-D array. For each row except the last, in order from top (first) to bottom (last), rotate the row below it by `x` to either direction (you choose a consistent direction to use) where `x` is the first element in the current row.
# Reference
A reference implementation in Python can be found [here](https://tio.run/##ZZDBasMwEETP1lcMlIJFFUjqJKWG/ESvRhS12diitmQ2chN/vavIbg8p7GE18zS7Uj@GxrtimjoT2F5xAH2bNreuH0IuJR7gfCAEDyZzJC7vfHtG4y8Y/YCaAnryfZvwj8h/3XTGp@8iTSzEkU5gH0yg3DCbUcF0fnBBlnHQWzLOYFs3QWSzg8cDWnIzLkXGFAZ2SMdqNTOlxtOilIukhTh5jrMu79Yd6QrrwMbVlG9UypufK2Upsrmt/lgdP2FZ8p@lcC9hhY2u1loK0bN14Td5mqpqq/CqsE@1U4ijtzGhWqf2WaGIzS5Z@5s@g0Wql8jG21r/AA)
# Example
Let's walk through an example. Take the following matrix for example:
```
1 5 8
4 7 2
3 9 6
```
Let's say we're rotating right. First we rotate `[4 7 2]` to the right by 1 because the first element of `[1 5 8]` is 1. Thus, we get `[2 4 7]` as the second row. The matrix is now like this:
```
1 5 8
2 4 7
3 9 6
```
Then, we rotate `[3 9 6]` to the right by 2 because the first element of the second row is 2. Thus we get:
```
1 5 8
2 4 7
9 6 3
```
# Challenge
Implement the above
# Test Cases
Test cases are given as a list of lists in Python style.
```
Input -> Output
[[6, 7, 10, 1, 10, 7], [7, 3, 7, 8, 9, 2], [6, 8, 3, 9, 3, 1], [6, 3, 8, 6, 4, 1], [7, 5, 2, 9, 7, 2], [2, 10, 9, 9, 7, 9], [8, 8, 10, 10, 8, 4]] -> [[6, 7, 10, 1, 10, 7], [7, 3, 7, 8, 9, 2], [1, 6, 8, 3, 9, 3], [1, 6, 3, 8, 6, 4], [2, 7, 5, 2, 9, 7], [7, 9, 2, 10, 9, 9], [4, 8, 8, 10, 10, 8]]
[[8, 10, 4, 3, 9, 4, 6], [8, 8, 8, 8, 6, 7, 5], [6, 2, 2, 4, 8, 9, 6], [1, 7, 9, 9, 10, 7, 8]] -> [[8, 10, 4, 3, 9, 4, 6], [5, 8, 8, 8, 8, 6, 7], [2, 4, 8, 9, 6, 6, 2], [7, 8, 1, 7, 9, 9, 10]]
[[6, 2, 4, 4, 4], [5, 9, 10, 5, 4], [3, 5, 7, 2, 2], [1, 5, 5, 10, 10], [8, 2, 3, 2, 1], [3, 3, 9, 5, 10], [9, 5, 9, 7, 2]] -> [[6, 2, 4, 4, 4], [4, 5, 9, 10, 5], [5, 7, 2, 2, 3], [1, 5, 5, 10, 10], [1, 8, 2, 3, 2], [10, 3, 3, 9, 5], [9, 5, 9, 7, 2]]
[[3, 6, 3, 7, 4], [8, 8, 1, 5, 8], [7, 5, 1, 9, 4], [3, 9, 10, 8, 6]] -> [[3, 6, 3, 7, 4], [1, 5, 8, 8, 8], [4, 7, 5, 1, 9], [9, 10, 8, 6, 3]]
[[5, 6, 1, 2, 6], [1, 10, 10, 1, 4], [6, 2, 7, 1, 7], [9, 5, 8, 6, 3], [4, 5, 1, 2, 1], [8, 6, 1, 1, 3]] -> [[5, 6, 1, 2, 6], [1, 10, 10, 1, 4], [7, 6, 2, 7, 1], [6, 3, 9, 5, 8], [1, 4, 5, 1, 2], [3, 8, 6, 1, 1]]
[[10, 1, 2], [9, 9, 10], [2, 4, 7]] -> [[10, 1, 2], [10, 9, 9], [7, 2, 4]]
[[4, 5, 6], [6, 9, 4], [9, 3, 2], [3, 5, 9], [5, 5, 3], [9, 1, 4]] -> [[4, 5, 6], [4, 6, 9], [2, 9, 3], [5, 9, 3], [5, 3, 5], [1, 4, 9]]
[[8, 7, 6, 5], [9, 8, 6, 6], [7, 9, 7, 10]] -> [[8, 7, 6, 5], [9, 8, 6, 6], [10, 7, 9, 7]]
[[10, 2, 8, 8, 1], [2, 10, 1, 4, 10], [3, 2, 5, 3, 8], [5, 1, 8, 1, 8], [6, 1, 3, 1, 2], [7, 9, 1, 1, 2]] -> [[10, 2, 8, 8, 1], [2, 10, 1, 4, 10], [3, 8, 3, 2, 5], [8, 1, 8, 5, 1], [3, 1, 2, 6, 1], [1, 1, 2, 7, 9]]
[[9, 1, 3, 2, 7], [3, 8, 10, 3, 3], [8, 10, 7, 9, 5], [8, 1, 4, 9, 9], [6, 8, 4, 10, 10], [4, 7, 6, 2, 2], [8, 5, 3, 7, 6]] -> [[9, 1, 3, 2, 7], [8, 10, 3, 3, 3], [7, 9, 5, 8, 10], [9, 9, 8, 1, 4], [8, 4, 10, 10, 6], [6, 2, 2, 4, 7], [6, 8, 5, 3, 7]]
```
[Generate more testcases here](https://tio.run/##dZDBasMwEETP1lcslFKL2CUmh4Ag/YhchSgCK7EglsxmQ@Kvd7SW05SUXmR5ZtDb2WGkLobNNPl@iEiANrSxF6J1B8BIllxpEe1Yge3jJZBU8Ab72TgD@mNHosgOvO/g5EKOS1GgowsGmH91nTPKwGpR1CIZIQ4RwYMPDD@6sllLJYqrb6mD3TLQJ398oHJTwTY93jlG/2eLoreE/pZ8rV8STQUJAMy8PZkzTZpZHp9yxsg0YxFTWR/sid/EeNUqh9OV45nHuUX89qF1vwAJy8vJOckFlxn1T9hwnbzyP1YFrxLU0Bi9Ntx2QG52JiwfU8q05w@ov9KxAjYe4Gm6Aw)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
G(ṙ←
```
[Try it online!](https://tio.run/##HYy7EYAwDEPXoVCRH3EyAUPk0nNHybECNS2jMA4sYhQ3sp6l03rsm@oyvc/9nZeqtpYh8A5@iHQ0QeSnoCKQMl2kj/BGkZyRjAQzAjOxZhgD1bASC4tj1vGm3n8 "Husk – Try It Online")
Rotates rows to the left.
### Explanation
`G` in Husk is `scanl` (or cumulative reduce from left, as some languages call it). When given a function of type `x->x->x` (like in this case) it can use as starting value the first element of the list.
`(` is needed here to combine the following two functions into a single one.
`ṙ` is "rotate to the left" and takes a number and a list as arguments.
`←` returns the first element of a list.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes
```
ṙ@Ḣð\
```
[Try it online!](https://tio.run/##y0rNyan8///hzpkOD3csOrwh5v///9HRhjoKpjoKFrE6CtEmOgrmOgpGIKaxjoKljoJZbCwA)
Rotates to the left.
Saved a byte thanks to @Jonathan Allan.
## Explanation
```
ṙ@Ḣð\ Input: array of arrays M
ð\ Cumulative reduce over each array using
ṙ@ Rotate the RHS array using each in the LHS array
Ḣ Head
```
[Answer]
## C++, ~~187~~ 149 bytes
* 38 bytes thanks to Karl Napf
Output is done by the reference type parameter
The parameter's type have to be a `std::vector<std::vector<int>>` type
```
auto r=[](auto&a){for(int i=1,j,v;i<a.size();++i){v=a[i-1][0]%a[i].size();for(j=0;j<v;++j){a[i].insert(a[i].begin(),a[i].back());a[i].pop_back();}}};
```
Trying to do as `#define A a[i]` and replacing all occurences of `a[i]` by `A` will result with same byte count code
Code to help for the test :
```
//Shift operator overload
std::ostream& operator<<(std::ostream& os, std::vector<std::vector<int>>& v) {
os << "{\n";
for (auto&a : v) {
os << "\t{ ";
for (auto&b : a) {
os << b << ' ';
}
os << "},\n";
}
return os << "}\n";
}
```
And in the `main` function
```
std::vector<std::vector<int>> t{
{1,5,8},
{4,7,2},
{3,9,6}
};
std::cout << t;
r(t);
std::cout << t;
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~84 59~~ 45 bytes
Shifts to the left (now using [Leo's approach](https://codegolf.stackexchange.com/a/142073/48198)):
```
scanl1(\a r->(drop<>take$a!!0`mod`length r)r)
```
[Try it online!](https://tio.run/##HYzNroJADIX3PkVNXEBSDT/KSIJsvFufAIk2MCBxmJkM8/zOLSzanq89PR9avlKpMM3WOA9/5On0MNpMPURRVcfxbjfADZ5h6UirNHoSuGMd9c7Yqvb0lQfa75P3bPq3knr0H3Cxi8NMk@a3mezjBdZN2sMJBi4nqYdbVcEo/d1oL7VfQtMUKDBNMF2baLERmPPmiiVmTAWrnHWO6UY5c4HnjQReMOOb2JzZGlBuWDJe2bjGJjzPbfvrBkXjEo6dtf8 "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 65 bytes
```
l=input();K=0
for i in l:g=-K%len(i);e=i[g:]+i[:g];print e;K=e[0]
```
[Try it online!](https://tio.run/##LYtBCsIwEEX3nmI2Qosj1LZaTMgJeoRhljEOhGkoceHpY4zC5/P4vJ/e@bnpWEp0oumVu96ubjg8th0ERCGa4M7rMXrtpLfeCQXDJyET2KZdNIOvB08Dl0I0I9wRbi1XhAvCzAhUcUSYWv/5O/@8qWWpaj0zwwc "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 55 bytes (possibly broken)
If this version is found to fail for some test cases, I can assure you the above works. I am currently half-asleep, so feel free to remove this version in case it is invalid by editing.
```
l=input();K=0
for i in l:e=i[-K:]+i[:-K];print e;K=e[0]
```
[Try it online!](https://tio.run/##LYtBCoMwFET3PcUsW/yCVas0khPkCJ@/jPSDxCBx0dOnaVoYhsfwJr7Taw99zpvVEM90vS3Odpd1P6DQgM14q9w6I42yaZ0s8dCQ4IvmuZOcmUfCkzDVPAh3wigELtgThtp//s4/b6iZi1rOIvgA "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
vyNFÁ}=нƒ
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/rNLP7XBjre2Fvccm/f8fHW2oY6pjEasTbaJjrmMEpI11LHXMYmMB "05AB1E – Try It Online")
```
vy # For each row:
NFÁ} # Rotate this row N times (initially 0)
= # Print without popping
н # Get the head
ƒ # Assign that to N
```
[Answer]
# [Perl 5](https://www.perl.org/), 41 + 1 (`-a`) = 42 bytes
```
push@F,shift@F for 1..$r;say"@F";$r=$F[0]
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gtDjDwU2nOCMzrcTBTSEtv0jBUE9Ppci6OLFSycFNyVqlyFbFLdog9v9/QwUjBWMuEyBpxmWuYKFg@S@/oCQzP6/4v66vqZ6BocF/3UQA "Perl 5 – Try It Online")
Rotates to the left. Takes the input as lines of space separated integers.
**How?**
Remove an element from the left end of the list, put it on the right end as many times as we should rotate (`$r`). Since `$r` starts at `undef` (equivaltent to 0 in this usage), nothing happens to the first line. Output the list. Save the first element of the list in `$r` so we can rotate that many times on the next line.
[Answer]
# [Pyth](https://pyth.readthedocs.io), 11 bytes
```
VQ=ZhJ.>NZJ
```
**[Try it here!](https://pyth.herokuapp.com/?code=VQ%3DZhJ.%3ENZJ&input=%5B%5B4%2C+9%2C+6%2C+6%2C+5%2C+1%2C+4%5D%2C+%5B5%2C+2%2C+3%2C+2%2C+5%2C+2%2C+3%5D%2C+%5B6%2C+6%2C+3%2C+3%2C+7%2C+4%2C+9%5D%5D+&debug=0)**
# Explanation
* `VQ` - For each list in the matrix input:
+ `=Z` - Assign `Z` to the value of the below statement. Its initial value is `0`, so that helps us with the first row.
+ `h` - The first element of ...
+ `J.>NZ` - ... The current list, cyclically rotated by `Z` places, and assigned to a variable `J`.
+ `J` - Print `J`.
[Answer]
# [R](https://www.r-project.org/), 77 bytes
```
function(B){for(i in 2:nrow(B))B[i,]=rep(B[i,],sum(B))[1:ncol(B)+B[i-1,1]]
B}
```
[Try it online!](https://tio.run/##VY7NisJAEITveYpmTt3YHmJUUPSSuxfZ2ziHKIkMxJkwP7su4rPHmeAu2Jf@qiiKcmOIznzZ46EJTt9hN4cumkvQ1qCngL4Zhv4X2@@mx6FxvsWwv/p4RnE6KcGCBP9JmWSvfUDBntJxNFkSFUWXesf/3poenXWoQRtYbI2zP8miWmpWe9cOOBH7eMu2LLfmYvuEs@TPSy6VKurn2OHHcBRSLhlWDGvFINcMG4ZlxvQrhkXGagpsMq4mrN6BMmeVIBpf "R – Try It Online")
Rotates rows to the right.
Replicates each row of `B` `sum(B)` times (creating a huge vector), then grabs the appropriate values from that replicated vector to put into the correct row.
I also wrote a function in the header that converts from the python matrix format to R matrices.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 14 bytes
Anonymous tacit prefix function. Takes list of lists as argument and prints rows on separate lines with the numbers in each row separated by single spaces. Rotates left (although the explanation mentions how rotate right).
```
{⎕←⍺⌽⍨⊃⍵}/0,⍨⌽
```
[Try it online!](https://tio.run/##1VTNSgMxEL7vU@xtL1tsks0m8d7aSqjQ9lZ6KAheCvXgRcSToCJWvPgOvoAXwZfZF6nJ/PRH2B4UbS3pNp2dme@bL5OZnE8bp5eT6exsUd3f9WcXfnFVPb1Ut8/V/L16/Kjmr9XDTTV/uz4I5rwZvRL07CdfPRsbrtFtkbW7/cEw7XePOsPDLEnhA8HB53hw0stGozJPTZ6KZvjijxnn6SiYFLyweeryVEZbCf8UGMJTkE2BOWwKsoUoHULAz1CsxNyOjS4aLUQCdBO2xXhcw5L8CsYPm3KVwjKFCE20JKyCKwBvgdiwoNTwthay5ARxxWi9jNNkUbA1CEYAGhYWRQwlsJYkj@IaNLvgntWq46OgQjyVYk0@CLYr4QUKRFBuKW5Zm1lDZgEUWSc@FUGpUA0DBrMijbKraCgYnQu1nFZEjzpwApGU07EoqL2pjUO4krhxxdiacnU4jk5OE0tHJW1pNAO8NXljFSXp6@i2bC1HckeKtdYXeEGaRE0iJTo5FA5P01JJAm8ZVYPYggx16I7DJJ2SWl4xRQLYZes7KtIyOUdy4UUv1ru4YFm40y3zN9RZSTbstHqpb7U3Ro3/F6PG//2o8Xs2avyvjRq/y1Hjvzlq/O@MGv/DUeN3Omr8XoyaTw "APL (Dyalog Unicode) – Try It Online")
`⌽` reverse the argument (because reduction is right-to-left)
`0,⍨` append a zero (for initial rotation of zero steps)
`{`…`}/` reduce by the following anonymous lambda, where `⍺` is the element on the left and `⍵` on the right (the reduction goes right-to-left
`⊃` pick the first of the right argument
`⍺⌽⍨` rotate the left argument to the left\* that many steps
`⎕←` output to STDOUT with a trailing line-break
---
\* To rotate right, insert a `-` to the right of `⍨`. This will negate the rotation amount.
] |
[Question]
[
# Backstory
Not really real, *sshh!*
It all started one day when a coworker brought in a *homemade* loaf of bread for my boss's birthday.
My boss *really* liked this loaf of bread, and he wanted another. Unfortunately, my coworker has quit, so my boss needs *me* to give him another loaf.
The problem is, I have *no idea* how to make bread. So I told my boss that i'm not a chef and to look harder for someone who is.
He said, "Sure...but you lose your job if you can't make me a loaf."
Then I had an idea.
I would make him an *[ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'")* loaf with my coding skilz! He said yes, under 1 condition: "You must make it in under 351 bytes." Unfortunately for me, my best code golfing got me to 375 bytes. Uh oh.
Then my boss added 2 things: "You must give me that loaf in a week (4/13), and if you do so you get an increased salary. The lower the amount of bytes you use, the better salary. But remember, if you go over 349 you lose your job."
So I need your help in your language of choice to help me keep my job!
# Rules
I was about to do a `curl ... | sh` on a TinyURL, but my boss told me that I can't use a [list of loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). I probably could skirt the rules, but my job is at stake, so it's not a good idea.
# What counts as a loaf
Your program or function must take 3 positive integers as input. If your language has a list or array, you can take a list or array of those numbers. You can also take them as arguments to a function or program, or a space-separated string of numbers to STDIN, a command-line or function argument, etc.
**The first number is the width of your loaf**
**The second number is the height of your loaf.**
**The third number is the depth of your loaf.**
Here's a loaf with a width of `3`, a height of `2`, and a depth of `1`:
```
/---\
/---\|
| ||
|___|/
```
Looks wierd? Here's a 3x2x2:
```
/---\
/ |
/---\ |
| | /
|___|/
```
How about a 3x3x3:
```
/---\
/ |
/ |
/---\ |
| | /
| | /
|___|/
```
A 4x1x2:
```
/----\
/ |
/----\ /
|____|/
```
I hope you understand! [See my JS (ES6) answer below for an example.](https://codegolf.stackexchange.com/a/115576/58826)
[Also see complete test cases](https://pastebin.com/CsyNXcrP)
# Notes:
* Don't worry about valid input. All sizes will be positive integers.
* You must accept any positive integers that your language can support.
* If the numbers are so high your languages crashes from StackOverflow, maximum string length overflow, etc. that's OK.
# Shortest answer in bytes wins!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~35~~ ~~33~~ 30 bytes
*Saved 2 bytes thanks to @ASCII-only*
*Saved 3 bytes thanks to @Neil by rearranging the order in which the lines where drawn*
```
NωNηNδ↓η↗→×_ω↑η←\←ω↗δ→/ω↓\↓η↙δ
```
[Try it online!](https://tio.run/nexus/charcoal#@/9@z7rznUDi3HYQseVR2@Rz2x@1TX/UNunw9PjznY/aJoL4E2KAGMSbDlIySR/EnBwDVTzz3Jb//024DLmMAA "Charcoal – TIO Nexus")
This is my first try at Charcoal. I heard it was good at [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'"), so I tried it out.
### Explanation (outdated)
```
NωNηNδ # Take the width, height and depth as input
↗¹ # Write 1 /
↗δ # Write depth times /
¶ω # Move the cursor down and write - width times
\ # Write \
↙↓η # Move the cursor one down and one left, and then write | height times
↙δ # Write / depth times
```
Now the back part of the loaf is complete. Now comes the front face.
```
↑↑η # Go up and write | height times
←\ # Write a \ and move 1 to the left
←ω # Write - width times
↓↓η # Go down and write | height times
↗P×_ω # Go northeast and write _ width times
```
[Answer]
# JS (ES6), 375 bytes
```
s=(s,t)=>s.repeat(t);(d,c,e)=>{z=" ",y=`
`,x="\\",w="/",v="|",u="-";a=s(z,e--);a=a+w+s(u,d);a+=x+y;for(b=0;b<e;b++)a+=s(z,e-b),b<c?(a+=w,a+=s(z,d+b+1),a+=v):(a+=w,a+=s(z,d+c+1),a+=w),a+=y;a=a+w+s(u,d);a+=x;f=0;b<c?(a+=s(z,e),a+=v):(a+=s(z,c-f),a+=w);b++;f++;a+=y;for(g=0;g<c;g++)a+=v,a+=s((g==c-1?"_":z),d),a+=v,b<c?(a+=s(z,e),a+=v):(a+=s(z,c-f),a+=w),b++,f++,a+=y;return a}
```
Ungolfed:
```
var proc = function(width, height, depth){
var str = "";
//Back of loaf (depth)
str += " ".repeat(depth);//initial padding before start of back of loaf
str += "/";//top left corner of back of loaf
str += "-".repeat(width);//top edge of back of loaf
str += "\\";//top left corner of back of loaf
str += "\n";//end line
//Depth lines
for(var i = 0; i < depth - 1; i++){
console.log(i)
str += " ".repeat(depth - i - 1);//space padding before start of left middle edge
if(i < height){
//str += " ".repeat(depth - i - 2);
str += "/";//left middle edge
str += " ".repeat(width + i + 1);//middle of loaf
str += "|";//end that edge
str += "\n";//end line
}else{
str += "/";//left middle edge
str += " ".repeat(width + height + 1);//between two /s
str += "/";//right middle edge
str += "\n";//end line
}
}
//front top edge of loaf
str += "/";//top left corner
str += "-".repeat(width);//top edge
str += "\\";//top right corner
var i3 = 0;
if(i < height){
str += " ".repeat(depth - 1);//space for the incoming far right edge
str += "|";//far right edge
i++;
i3++;
}else{
str += " ".repeat(height - i3);//space for the incoming far right edge
str += "/";//far right edge
i++;
i3++;
}
str += "\n";//newline
for(var i2 = 0; i2 < height; i2++){
str += "|";//left edge
str += (i2 === height - 1 ? "_" : " ").repeat(width);//if we are at the bottom, use underscores to mark that, otherwise spaces.
str += "|";
if(i < height){
str += " ".repeat(depth - 1);//space for the incoming far right edge
str += "|";//far right edge
i++;
i3++;
}else{
str += " ".repeat(height - i3);//space for the incoming far right edge
str += "/";//far right edge
i++;
i3++;
}
str += "\n";//newline
}
return str;
};
```
```
s=(s,t)=>s.repeat(t);
var bakeBread = (d,c,e)=>{z=" ",y=`
`,x="\\",w="/",v="|",u="-";a=s(z,e--);a=a+w+s(u,d);a+=x+y;for(b=0;b<e;b++)a+=s(z,e-b),b<c?(a+=w,a+=s(z,d+b+1),a+=v):(a+=w,a+=s(z,d+c+1),a+=w),a+=y;a=a+w+s(u,d);a+=x;f=0;b<c?(a+=s(z,e),a+=v):(a+=s(z,c-f),a+=w);b++;f++;a+=y;for(g=0;g<c;g++)a+=v,a+=s((g==c-1?"_":z),d),a+=v,b<c?(a+=s(z,e),a+=v):(a+=s(z,c-f),a+=w),b++,f++,a+=y;return a}
```
```
<input type = "number" id = "a1">
<br/>
<input type = "number" id = "a2">
<br/>
<input type = "number" id = "a3">
<br/>
<button onclick = "document.getElementById('textarea').innerText = bakeBread(+(document.getElementById('a1').value), +(document.getElementById('a2').value), +(document.getElementById('a3').value))">Bake Bread!</button>
<br/>
<textarea id = "textarea"></textarea>
```
[Answer]
# C, ~~270~~ ~~290~~ ~~320~~ 328 bytes
```
#define P printf(
p(n,s)char*s;{P s,--n&&p(n,s));}i,j,k;f(w,h,d){P "%*c",d+1,47);p(w,"-");P "\\\n");for(i=d,j=h,k=0;--i;)P "%*c%*c\n",i+1,47,w+d+1-i-k+!!k,j-->0?124:(++k>0)*47);P "/");p(w,"-");P "\\%*c\n",d-k,j-->0?124:47);for(k&&k++;++i<h;)P "|%*c%*c\n",w+1,124,d-k>!k?d+1-k-!k:0,j-->0?124:(++k>0)*47);P "|");p(w,"_");P "|/");}
```
Finally (after ~~two~~ three incorrect versions) it works correctly with large sizes also.
[Try it online!](https://tio.run/nexus/c-gcc#dZBNboMwEIX3nAKogmw8VoFSVYoLuUIOEKlC/AhjxUFAxSJw7K7pAP2JImJ7MZr33nzWTE9ZXkidm0ezbqTuCmLURENL0zJp3FZcj2YLnGvHWdtUjBIqUKIgPZSQUTTYOze1IWM@hG9U1CjY3KYChdPppLEqLg2RUQZVVIKKPMG5FHTN4UMLyCUMPcMpXHLFLEtBxXnsHfwg3BPGVOxRd56PuWf7HvMzJuO3qdk9o5XjKMYEY/K9XLjDP7hHMHrnZGypw4xX3FJ77zF9@KV/rPRh/s44Gbg985xITahxNUw8BXmBAHx0f3YtsZdV3AjBtoB3SwjBv08sStskOiOdPOfEo3/upUl3rx5sVOgapy994WmSlvk3)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~234~~ ~~216~~ 210 bytes
```
w,h,d=input()
f,g='|','/';z,s=g+'-'*w+'\\',' '
print'\n'.join([s*d+z]+[s*(d-c)+g+s*(w+c)+(f,g)[c>h]for c in range(1,d)]+[z+s*(d-1)+(f,g)[d>h]]+[f+s*w+f+s*(h-e-1)+(f,s+g)[d>=h]for e in range(1,h)]+[f+'_'*w+f+g])
```
[Try it online!](https://tio.run/nexus/python2#TYzBDoIwEETvfEVv27KLBj2a8iNAjKHQ1kMhgGlC/HdcqyZedicz82aP5MhoH6bHKlU2kNXwBIIjXDZatEUoII8ITcOmgGyafVihCXC4jz7IeskNbi3yl6boFFpkFZGV5C1Vd5Vrh3EWnfBBzLdge1mSUUxsmJjy1zTcZHtgO@L7Slf033jBVNCfrf5/y6kEwRUSZlu172c6UfkC "Python 2 – TIO Nexus")
~~Sure it can be golfed a lot more but it's a start.~~ 210 will do for me for now.
[Answer]
## JavaScript (ES6), 204 bytes
```
(w,h,d)=>[...Array(h-~d)].map((_,y)=>[...Array(w-~d)].map((_,x)=>x+y==d|x+y==h+w-~d?`/`:x==w+d&y<=h&&y||!x|x==w&&y>d?`|`:y==h+d&x<w?`_`:!y|y==d?x+y==w+d?`\\`:x+y>d&x+y<w+d?`-`:` `:` `).join``,++w).join`\n`
```
Where `\n` represents the literal newline character.
Rather than fiddle around with repeating characters, this just creates a suitably sized array and computes which character appears in each cell.
[Answer]
# PHP, 420 bytes
```
<?php $a=$_GET["a"];$b=$_GET["b"];$c=$_GET["c"];$w="<br>";$s=" ";$u="_";$p="|";$k="/";$t=str_repeat;$l='';$r=$t($s,$c).$k.$t("-",$a)."\\".$w;for($i=0;$i<$c+$b-1;$i++){$i<=$b-1?($i<$c-1?$l=$t($s,$a+$i+1).$p:$l=$t($s,$c-1).$p):($i<$c-1?$l=$t($s,$a+$b+1).$k:$l=$t($s,$c+$b-$i-1).$k);$i<$c-1?$r.=$t($s,$c-$i-1).$k.$l.$w:($i==$c-1?$r.=$k.$t("-",$a)."\\".$l.$w:$r.=$p.$t($s,$a).$p.$l.$w);};echo$r.=$p.$t($u,$a).$p.$k?>
```
Sounds like someone's fired - maybe try convincing your boss that it's much cooler on backend.
Input is attached to the URL string: `?a=[width]&b=[height]&c=[depth]`.
Ungolfed for transparency:
```
<?php
$a=$_GET["a"];$b=$_GET["b"];$c=$_GET["c"];
$w="<br>";$s=" ";$u="_"; $p="|";$k="/";$t=str_repeat;$f=$v=$m=$l='';
//first line
$r=$t($s,$c).$k.$t("-",$a)."\\".$w;
for($i=0;$i<$c+$b-1;$i++){
//right side of the loaf
$i <= $b-1
? ($i < $c-1 ? $l=$t($s,$a+$i+1).$p : $l=$t($s,$c-1).$p)
: ($i < $c-1 ? $l=$t($s,$a+$b+1).$k : $l=$t($s,$c+$b-$i-1).$k) ;
//left side, with the right side attached
$i<$c-1
? $r.=$t($s,$c-$i-1).$k.$f.$l.$w
: ($i==$c-1
? $r.=$k.$t("-",$a)."\\".$f.$l.$w
: $r.=$p.$t($s,$a).$p.$f.$l.$w);
};
//final line
echo $r.=$p.$t($u,$a).$p.$k;
?>
```
] |
[Question]
[
This challenge is inspired by [this other challenge](https://codegolf.stackexchange.com/questions/38250/comment-free-polyglot), which you may want to read first for some context. However, a competitive answer is likely to look very different, so after [reading some posts on Meta](http://meta.codegolf.stackexchange.com/a/1876/62131) I decided it was best posted as a separate question.
The goal here is to write a [polyglot](/questions/tagged/polyglot "show questions tagged 'polyglot'") program; that is, a program that works in multiple languages. However, typically polyglot challenges are answered via some standard techniques (listed below). I think it's much more interesting if the standard techniques are avoided, and thus this challenge has a number of **restrictions** that your program must obey; each restriction is designed to close a standard loophole (although if you can somehow exploit the loophole while remaining within the restriction, go ahead). Here are the restrictions, and the reasons behind them:
1. **Deleting any non-whitespace character from your program must cause it to fail to function in all your languages. Your program may not read its own source.**
One of the most common tricks for creating polyglots is to hide code intended for one language inside syntax that's a comment block in each other language. In order to define "comments" (and other non-coding syntax, which similarly needs to be disallowed) in a language-independent way, we define a character to be part of a comment if it could be deleted without affecting the operation of the program. (This definition was based on that in nneonneo's challenge, linked above; not counting the removal of whitespace isn't quite loophole-free as some languages have particularly significant whitespace, but in general it's hard to find a *lot* of languages which use it for computation, and I don't want the focus of the challenge to be on minor details about which languages require whitespace where.)
To clarify "failing to function", the intention is that the program works like this: deleting a character from the program causes it to break at least one of the other restrictions (e.g. it errors out, or prints the output that does nor comply with the specification).
It's fairly clear that a program could work around the spirit of this restriction via examining its own source code (e.g. via opening the file that stores it on disk, or using a command similar to Befunge's `g`); as such, doing that is banned too. To be precise, you may not use language features that would act differently if a comment were added to the source code.
2. **The program may not error out, either at run time or (if applicable) at compile time.**
A common trick with polyglots is to not worry about executing parts of the program intended for other languages that aren't valid in one of the languages; you just write them anyway, then let the program crash. Banning errors closes the loophole. Warning messages are acceptable, unless the language is one that downgrades situations that would be errors in most typical languages (e.g. invalid syntax) as warnings.
3. **The program must not use any language features that return the name or version of the language in use**.
For example, no using `$]` in a submission that's intended to work in Perl. A common trick when answering polyglot questions is to take two languages which are very similar (such as Python 2 and Python 3) and claim that a program is a polyglot in both of them; however, if the languages are that similar, it makes the programs much easier to write and is uninteresting in a way. This restriction requires any solution to the problem that uses similar languages to focus on the differences between them, rather than the similarities.
4. **When executed, the program must: print the name of the language it is executing in; print the name (e.g. "A000290") of a sequence from [OEIS](http://oeis.org/); then print the sequence itself. The sequence must be different for each language.**
One final trick for writing polyglots is to write a very simple program that uses only code constructs which have the same meaning in a wide range of languages, such as `print(1)` (which is a complete program that outputs `1` in sufficiently many languages that it or something like it would probably win without this loophole being closed). As such, there's a requirement here for the program to do a nontrivial amount of work. The program must *calculate* the sequence elements, not just produce hardcoded output (i.e. do not exploit [this standard loophole](http://meta.codegolf.stackexchange.com/questions/2506/standard-loopholes-what-counts-as-hard-coding)). If the sequence you choose is an infinite one, this means that the program should run forever producing more and more terms.
There's a large enough variety of sequences in OEIS that you should be able to find something that's relatively easy to implement in each of the languages you use, so long as your construction can handle some nontrivial code in addition to just printing constant strings.
This requirement also closes another standard loophole for implementing polyglots: observing that a file is missing a marker such as `<?php` and thus echoes itself, and claiming that that's a valid program. (Deleting a character would definitely change the result then!) Forcing the program to calculate something prevents that.
Note: this isn't really a challenge about implementing bignums, so it's OK if the output becomes incorrect after a while or even if the program errors out due to things like word size concerns, so long as you don't try to abuse this by picking a language with very small integers. Likewise, there aren't any hard requirements on the output format. You can output in unary for all I care.
Incidentally, the requirement to print the sequence number is to prevent a solution accidentally becoming invalid because deleting a character changes the sequence that's printed without changing anything else (and therefore is there to make the first restriction easier to comply with).
The winner will be the **answer that works in the most languages**, making this a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"). If there's a tie, the tiebreak is to favour the submission that was posted earlier. Unlike many challenges on this site, there's no benefit to writing a short program, so feel free to make it as readable as the restrictions allow (which, admittedly, is probably still not very readable). Good luck!
[Answer]
# Perl + Lua + JavaScript (Rhino) + Ruby + Python (3), 5 languages
```
m=[[']|^$=;eval($n=q@sub t {(chr 39)=~//&&"["=~//&&0!~//||die; 690 == length $n.$_[0][0][0] and print "Perl: A004442$/1$/"; print 1^++$.,$/ while 1;}@);t([ [q 9)',
']] n=[[function t(p) if #(m..n..p)-1==688 then print("Lua: A000045") a=1 b=1 while true do print(a) print(b) a=a+b b=b+a end end end]] loadstring(n)() t([['],
'\x3044',
'if((""+m).length == 640) print("JavaScript: A000217"); for(i=1;;i++)print(i*(i+1)/2)',
'm.inspect.length == 700 and print("Ruby: A000027\n"); $i=0; print(++$i, "\n") while $i=$i+1',
'exec(m[5])',
'print("Python: A000012" if len(repr(m)) == 676 else ""); exec(m[6])',
'while True: print(1)',
'eval(m[eval(m[1][2])])',
'eval(m[([22]+[7])[1] ])',
8];eval(m[m[9]])
```
I used Rhino, an offline (non-browser-dependent) JavaScript implementation, because it makes local testing easier; it produces output using `print` instead of `alert`. You can change each occurrence of `print` to `alert` in the fourth line to get a program that will work in a browser.
This program uses the technique of storing most of the strings used for the various languages in data structures and `eval`uating them. We can determine if a character was deleted via checking the size of the resulting structure. That might sound easy, but it's surprisingly hard to ensure that for each language, every character of the program is either inside a string somewhere or else will break the syntax if deleted.
The program works in three different ways, depending on what language is in use.
## Lua
The Lua interpretation of the program is one of the simplest and shows off the general techniques in use, so it's a good place to start. Because `[[...]]` is a string literal in Lua, the program parses like this:
```
m=[[...]] n=[[...]] loadstring(n)() t([[...]])
```
Here, `m` and the argument to `t()` are used to capture the parts of the program used by "other languages" in order to check them for modification; `n` contains the majority of the Lua code (it defines a function `t` when evaluated via `loadstring`). It should be fairly obvious that every byte that isn't inside a string literal will break the program if deleted; deleting one of `=()[]`, the first use of `m` and `n`, or the final `t` will cause a syntax error; and deleting the argument to `loadstring`, or corrupting the name of the function itself, will make it impossible for the program to do anything useful as the content of `n` is never run. (Note that the trick of defining and then calling a function allows us to read the rest of the program "from the left", meaning that we don't need to write any Lua code physically to the right of the final `]])` in order to continue executing Lua after the entire program has been read.)
The implementation of `t` is fairly simple; it checks to ensure that `m`, `n` and `p` have the expected total length, then prints out the required information (the language's name, sequence number, and the Fibonacci sequence). One slight subtlety here is that I subtract 1 from the length and compare it to 688, rather than comparing to 689 directly; this is to avoid putting a literal `9` digit in the source code (the reason for this will become clear later).
## JavaScript, Ruby, Python
All three of these languages parse the program the same way: as a definition of a nested data structure `m`, followed by `eval(m[m[9]])`. The definition of `m` looks like this:
```
m=[['...','...'],'...','...','...','...','...','...','...','...',8];
```
In other words, `m` is a nested list here, and we can index it to get at various strings within the list. The `eval(m[m[9]])` check ensures that `m` has the expected number of elements; the program will therefore do nothing useful if one of the commas gets deleted (other than the first), even if the language can parse it. This ensures that all the strings from `m[1]` onwards are either intact or have one character deleted. We can observe that deleting any character outside a string literal here will break the program; without the initial `m` or an intact `eval` it can't run anything, without the `=` or `;` or a parenthesis or square bracket it won't parse, deleting an apostrophe will cause an unterminated string (all the apostrophes in the program are used as string delimiters and none are escaped), and it won't find the right string to run without the final `m`s and `9` intact.
Assuming that everything is fine except for possibly the contents of the strings inside `m`, we then try to determine which entry to run. This uses fragments of code that are written in the common subset of the languages' *syntaxes*, but have different *meanings* in the languages in question. To distinguish between JavaScript and the other languages, we run `([22]+[7])[1]`; this collapses to `[22, 7][1]` (i.e. `7`) in Ruby and Python, but `"227"[1]` (i.e. `"2"`, which JavaScript is happy to treat as `2` for the purpose of list indexing) in JavaScript. Then to distinguish between Ruby and Python, we take the third character of the string `'\x3044'`; Python expands `\x` escapes in both `''` and `""` strings, thus seeing this as `4`, whereas Ruby does not expand escapes in strings if they're delimited using `''`, and thus sees the third character as `3`. (We convert these strings to integers in a portable way by using `eval` yet again. It's not a recommended method of converting a string to an integer, but it does work in more languages than most other methods do.)
This means that a different string gets executed in each language, so we can start using language-specific syntax. All three programs basically do the same thing; they convert the entire data structure `m` to a string, measure its length, and compare it to an expected value. If it's wrong, they refuse to print the language name and sequence number, thus failing to comply with the spec (as required). Then they print an appropriate sequence. Ruby prints the consecutive integers, whereas JavaScript prints the triangular numbers (this is mostly because I'm more experienced with Java than I am with Ruby). Python is a bit more complex, because `eval` in Python only runs expressions, and you need `exec` for statements; additionally, Python isn't hugely fond of semicolons, and thus I needed to split the Python program over two `exec`s to make it work. Because I'm not very experienced at Python one-liners, I chose to print the sequence of all-1s; boring, I know, but based on the tiebreak we've selected I wanted to get this submitted.
## Perl
Saving the best for last. People who have any experience with Perl will know that variable names have to start with a punctuation mark (with `$` being by far the most common; other names are used for special cases like lists and dictionaries). Some of the languages I'm using don't like dollars in variable names (Ruby is OK with it, but one other language besides Perl isn't so useful…), which means that I can't start the program with a variable assignment. What Perl *does* have is a fairly wide range of interesting quoting operators, so it would be trivial to hide the start of the program from Perl by capturing it in a string literal with `q= ... =` (which is one of the many, many ways to write a string in Perl). However, hiding the text from Perl is something we can't do; in order to make the quine comment-free, we need to be able to see everything!
The obvious approach is to read the string entirely from the right, but I couldn't think of a way to do that while writing the program, so I had to take a different approach. It's possible to match a regex against `$_` (Perl's "variable used by default") via writing the regex as an expression by itself; something like `/:(.):/` would look for a character between two colons in `$_` and store it in `$1`. We can change the quote marks used for regexes by preceding the first with `m`; thus, as our program starts with `m=[[']|^$=`, Perl will parse this as `/[[']|^$/`. Matching that regex against `$_` might seem fairly useless; however, Perl has a convenience feature that allows the use of the notation `//` to repeat the last successfully matched regex. It matches (`$_` is the empty string, thus it matches the `^$` branch of the regex), meaning that we can determine if any characters got deleted from the regex by testing it on various strings to see if it matches! Some characters being deleted from the regex (such as the `]`) will cause a parse failure. For the others, we match it against `chr 39` (i.e. an apostrophe, written as a character code so as not to alarm Python), against `"["`, and against `0` (which Perl stringifies to `"0"`, expecting two matches and a non-match:
* If the `|` is deleted, the original regex won't match, and thus the `//` will match anything.
* Conversely, if the `^` or `$` is deleted, the original regex will match, but it still matches anything (as all strings have a start and and end, just not necessarily both together).
* If either `[` is deleted, the regex won't match `"["`.
* If the `'` is deleted, the regex won't match `'`.
Apart from the regex experimentation, everything works much the same way as in Lua. The program is arranged slightly differently:
```
m= ... =;eval($n=q@ ... @);t([ [q 9 ... 9]])
```
but it still comes down to basically the same thing (just with weirder quote marks; `q` can make basically anything into a quote mark, including in this case the digit `9`, which is why we couldn't use it in the rest of the program). Likewise, deleting any of these characters will break the parse for the same reason it does in the corresponding Lua. The code that's assigned to `$n` (and evaluated) defines `t` to ensure that the regex is intact, then check to ensure that `$n` and its own argument are intact, then print the required output (I chose sequence A004442 this time, because I was feeling a bit quirky and creative). Note that we can safely use a 9 in `690`, the expected total lengths of `$n` and `$_[0][0][0]` ("the first element of the first element of the first argument"), as it appears to the left of the `q 9` open-quote in the program.
## Extensions?
I think this program is close to its limit in terms of languages. You'd either need to find a new creative way to quote strings that doesn't clash with the existing constructions, or else to find another language with syntax close enough to JavaScript/Ruby/Python that the define-lists-and-`eval` trick works. (I tried looking into esolangs, but they tend to be worse with respect to string literals than more exoteric languages do, and the rules against reading the source make it hard to cheat with them.)
] |
[Question]
[
Note: reference to [Nothing up my sleeve number](https://en.wikipedia.org/wiki/Nothing_up_my_sleeve_number).
Your task is to take no input and generate this exact output:
```
d76aa478 e8c7b756 242070db c1bdceee f57c0faf 4787c62a a8304613 fd469501
698098d8 8b44f7af ffff5bb1 895cd7be 6b901122 fd987193 a679438e 49b40821
f61e2562 c040b340 265e5a51 e9b6c7aa d62f105d 02441453 d8a1e681 e7d3fbc8
21e1cde6 c33707d6 f4d50d87 455a14ed a9e3e905 fcefa3f8 676f02d9 8d2a4c8a
fffa3942 8771f681 6d9d6122 fde5380c a4beea44 4bdecfa9 f6bb4b60 bebfbc70
289b7ec6 eaa127fa d4ef3085 04881d05 d9d4d039 e6db99e5 1fa27cf8 c4ac5665
f4292244 432aff97 ab9423a7 fc93a039 655b59c3 8f0ccc92 ffeff47d 85845dd1
6fa87e4f fe2ce6e0 a3014314 4e0811a1 f7537e82 bd3af235 2ad7d2bb eb86d391
```
A trailing newline is optional.
The MD5 hash for the version **with** trailing newline is:
* `FC1D37B5295177E7F28509EC9197688F`
The MD5 hash for the version **without** trailing newline is:
* `FAC194EC5EFD2E5A5AC07C2A4925699B`
### How the string is generated
Those 64 strings are actually the 64 hexadecimal numbers [used in the MD5 hash](https://en.wikipedia.org/wiki/MD5#Pseudocode).
The pseudocode for them:
```
numbers = floor(2^32 × abs(sin(i))) for i in [1,2,...,64]
```
The reference Python code:
```
from math import*
for i in range(8):print" ".join("{:08x}".format(int(abs(2**32*sin(-~j))))for j in range(8*i,8*i+8))
```
Ungolfed:
```
from math import*
for i in range(8):
temp = []
for j in range(8*i,8*i+8):
temp += ["{:08x}".format(int(abs(2**32*sin(j+1))))]
print " ".join(temp)
```
[Answer]
# Python 2, ~~86~~ ~~77~~ 76 bytes
```
import math
n=0;exec(",\nn+=1;print'%08x'%(2**32*abs(math.sin(n)))"*8)[1:]*8
```
Test it on [Ideone](http://ideone.com/0umdT6).
### How it works
Python 2's [`print` statement](https://docs.python.org/2.0/ref/print.html) has a quirk: It appends a newline to the result of its expression, unless it is followed by a trailing `,`; in this case, it appends a space. While that's usually annoying when golfing (as there's no short way to print without trailing whitespace), it's perfect for this task.
We repeat the string `,\nn+=1;print'%08x'%(2**32*abs(math.sin(n)))` eight times, chop off the leading comma with `[1:]`, and repeat the result eight times. The string that `exec` executes composed of eight identical copies of the following code.
```
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n))),
n+=1;print'%08x'%(2**32*abs(math.sin(n)))
```
Each line increments the variable **n** (initialized by `n=0`), applies the format string `%08x` (lowercase hexadecimal representation, left-padded with zeroes to length 8, of the integer part of its argument) to **232** times the absolute value of the sine of **n**, and prints the resulting string either with a trailing space or a trailing linefeed.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~26~~ ~~24~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
64RÆSA‘æ«32Ḟb⁴Ḋ€‘ịØhs8G
```
[Try it online!](http://jelly.tryitonline.net/#code=NjRSw4ZTQeKAmMOmwqszMuG4nmLigbThuIrigqzigJjhu4vDmGhzOEc&input=)
### How it works
```
64RÆSA‘æ«32Ḟb⁴Ḋ€‘ịØhs8G Main link. No arguments.
64R Yield [1, ..., 64].
ÆS Apply sine to each.
A Take absolute values.
‘ Increment.
This avoid padding the hex strings to 8 characters.
æ«32 Left-shift by 32 units.
Ḟ Floor.
b⁴ Convert to base 16 (list of integers).
Ḋ€ Remove the first digit of each, undoing the increment.
‘ Increment each base 16 digit (for 1-based indexing).
ịØh Index into "0123456789abcdef".
s8 Split into chunks of length 8.
G Grid; separate columns by spaces, rows by linefeeds.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 28 bytes
```
64:Y,|32W*k16YAkZ{Zc72e!3LZ)
```
[**Try it online!**](http://matl.tryitonline.net/#code=NjQ6WSx8MzJXKmsxNllBa1p7WmM3MmUhM0xaKQ&input=)
Pretty straightforward computation. Getting the required output format takes almost half the byte count.
[Answer]
# Pyth, ~~31~~ 27 bytes
Thanks to @Dennis for saving 4 bytes!
```
jjL;c8mt.Hs*^2 32h.a.tdZS64
```
[Try it here!](http://pyth.herokuapp.com/?code=jjL%3Bc8mt.Hs*%5E2+32h.a.tdZS64&debug=0)
## Explanation
```
jjL;c8mt.Hs*^2 32h.a.tdZS64
m S64 # map over [1...64]
s*^2 32h.a.tdZ # floor(2^32 * abs(sin(d))+1)
t.H # convert to hex-string and discard the first digit
c8 # split into 8 parts
jjL; # join on whitespaces and then on newlines
```
[Answer]
## JavaScript (ES7), 115 bytes
```
_=>`_ _ _ _ _ _ _ _
`.repeat(8).replace(/_/g,_=>(0+(Math.abs(Math.sin(++n))*2**32>>>0).toString(16)).slice(-8),n=0)
```
Includes the trailing newline.
[Answer]
# PHP, ~~131~~ 81 bytes
```
for(;++$i<65;){echo str_pad(dechex(2**32*abs(sin($i))),8,"0",0).($i%8?" ":"\n");}
```
This is a pretty straight-forward loop with a few conditions for spacing.
@insertusernamehere's shortcuts cut it down by 50 bytes.
[Answer]
# Julia, ~~69~~ ~~63~~ 58 bytes
```
[@printf "%08x%c"√sin(n)^2÷.5^32 n%8>0?32:10for n=1:64]
```
[Try it online!](http://julia.tryitonline.net/#code=W0BwcmludGYgIiUwOHglYyLiiJpzaW4obileMsO3LjVeMzIgbiU4PjA_MzI6MTBmb3Igbj0xOjY0XQ&input=)
### How it works
For each **n** between **1** and **64**, we compute `√sin(n)^2÷.5^32` and `n%8>0?32:10`, apply string formatting with `"%08x%c"` and print to STDOUT.
* `√sin(n)^2` computes the absolute value of **sin(n)**. `abs(sin(n))` is equally short (in bytes), but it would require a space to separate it from the format string.
`÷.5^32` divides the previous result by **0.532 = 1 / 232**, effectively multiplying it by **232**. However, `÷` performs *integer* divsion, so the result is truncated.
* `n%8>0?32:10` returns **32** (the code point of a space) whenever **n** is not divisible by **8** and **10** (the code point of a linefeed) otherwise.
* `"%08x%c"` turns the first result into lowercase hexadecimal representation, left-padded with zeroes to length 8; and the second result into a character.
Finally, the array comprehension returns an array of **64** instances of `Nothing`, the return value of `@printf`. Outside a REPL, this does not affect output.
[Answer]
# [///](http://esolangs.org/wiki////), ~~568~~ 567 bytes
```
/!/ f//@/fa/d76aa478 e8c7b756 242070db c1bdceee!57c0@f 4787c62a a8304613!d469501
698098d8 8b44f7af!fff5bb1 895cd7be 6b901122!d987193 a679438e 49b40821
f61e2562 c040b340 265e5a51 e9b6c7aa d62f105d 02441453 d8a1e681 e7d3fbc8
21e1cde6 c33707d6!4d50d87 455a14ed a9e3e905!ce@3f8 676f02d9 8d2a4c8a
ff@3942 8771f681 6d9d6122!de5380c a4beea44 4bdec@9!6bb4b60 bebfbc70
289b7ec6 eaa127@ d4ef3085 04881d05 d9d4d039 e6db99e5 1@27cf8 c4ac5665
f4292244 432aff97 ab9423a7!c93a039 655b59c3 8f0ccc92!feff47d 85845dd1
6@87e4f!e2ce6e0 a3014314 4e0811a1!7537e82 bd3af235 2ad7d2bb eb86d391
```
[Try it online!](http://slashes.tryitonline.net#code=LyEvIGYvL0AvZmEvZDc2YWE0NzggZThjN2I3NTYgMjQyMDcwZGIgYzFiZGNlZWUhNTdjMEBmIDQ3ODdjNjJhIGE4MzA0NjEzIWQ0Njk1MDEKNjk4MDk4ZDggOGI0NGY3YWYhZmZmNWJiMSA4OTVjZDdiZSA2YjkwMTEyMiFkOTg3MTkzIGE2Nzk0MzhlIDQ5YjQwODIxCmY2MWUyNTYyIGMwNDBiMzQwIDI2NWU1YTUxIGU5YjZjN2FhIGQ2MmYxMDVkIDAyNDQxNDUzIGQ4YTFlNjgxIGU3ZDNmYmM4CjIxZTFjZGU2IGMzMzcwN2Q2ITRkNTBkODcgNDU1YTE0ZWQgYTllM2U5MDUhY2VAM2Y4IDY3NmYwMmQ5IDhkMmE0YzhhCmZmQDM5NDIgODc3MWY2ODEgNmQ5ZDYxMjIhZGU1MzgwYyBhNGJlZWE0NCA0YmRlY0A5ITZiYjRiNjAgYmViZmJjNzAKMjg5YjdlYzYgZWFhMTI3QCBkNGVmMzA4NSAwNDg4MWQwNSBkOWQ0ZDAzOSBlNmRiOTllNSAxQDI3Y2Y4IGM0YWM1NjY1CmY0MjkyMjQ0IDQzMmFmZjk3IGFiOTQyM2E3IWM5M2EwMzkgNjU1YjU5YzMgOGYwY2NjOTIhZmVmZjQ3ZCA4NTg0NWRkMQo2QDg3ZTRmIWUyY2U2ZTAgYTMwMTQzMTQgNGUwODExYTEhNzUzN2U4MiBiZDNhZjIzNSAyYWQ3ZDJiYiBlYjg2ZDM5MQ)
Too bad I can only golf ~~6~~ 7 bytes :-(
To convince you that I can't golf it further, I challenge you to [do better in just ///](http://slashes.tryitonline.net), should you accept it. If you do, [you're a magician](http://cjam.aditsu.net#code=q6%2C2%3E%5Cfew%3A%7E%24e%60%7B0%3D1%3E%7D%2C%7B%7E%2C(*%7E%7D%24Sf*N*&input=d76aa478%20e8c7b756%20242070db%20c1bdceeeF57c0faf%204787c62a%20a8304613Fd469501%0A698098d8%208b44f7afFfff5bb1%20895cd7be%206b901122Fd987193%20a679438e%2049b40821%0Af61e2562%20c040b340%20265e5a51%20e9b6c7aa%20d62f105d%2002441453%20d8a1e681%20e7d3fbc8%0A21e1cde6%20c33707d6F4d50d87%20455a14ed%20a9e3e905Fcefa3f8%20676f02d9%208d2a4c8a%0Afffa3942%208771f681%206d9d6122Fde5380c%20a4beea44%204bdecfa9F6bb4b60%20bebfbc70%0A289b7ec6%20eaa127fa%20d4ef3085%2004881d05%20d9d4d039%20e6db99e5%201fa27cf8%20c4ac5665%0Af4292244%20432aff97%20ab9423a7Fc93a039%20655b59c3%208f0ccc92Ffeff47d%2085845dd1%0A6fa87e4fFe2ce6e0%20a3014314%204e0811a1F7537e82%20bd3af235%202ad7d2bb%20eb86d391), since Martin Ender's code says otherwise (checked)!
People that won the challenge and are worth of crediting (format: `name (id), bytes_golfed`):
* daHugLenny (56258), 1
[Answer]
# [Perl 5](https://www.perl.org/), ~~56~~ ~~54~~ 52 bytes
```
printf'%08x%s'x64,map{0|2**32*abs sin,$_%8?$":$/}1..64
```
Saved ~~2~~ 4 bytes thanks to @XCali
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvJE1d1cCiQrVYvcLMRCc3saDaSEvL2EgrMalYoTgzT0clXtXCXkXJSkW/1lBPz8zk/38A "Perl 5 – Try It Online")
[Answer]
# [K4](https://kx.com/download/), 48 bytes
**Solution:**
```
-1@" "/:'8 8#(,/$4_0x0\:)'_abs sin[1+!64]*/32#2;
```
**Example:**
```
q)k)-1@" "/:'8 8#(,/$4_0x0\:)'_abs sin[1+!64]*/32#2;
d76aa478 e8c7b756 242070db c1bdceee f57c0faf 4787c62a a8304613 fd469501
698098d8 8b44f7af ffff5bb1 895cd7be 6b901122 fd987193 a679438e 49b40821
f61e2562 c040b340 265e5a51 e9b6c7aa d62f105d 02441453 d8a1e681 e7d3fbc8
21e1cde6 c33707d6 f4d50d87 455a14ed a9e3e905 fcefa3f8 676f02d9 8d2a4c8a
fffa3942 8771f681 6d9d6122 fde5380c a4beea44 4bdecfa9 f6bb4b60 bebfbc70
289b7ec6 eaa127fa d4ef3085 04881d05 d9d4d039 e6db99e5 1fa27cf8 c4ac5665
f4292244 432aff97 ab9423a7 fc93a039 655b59c3 8f0ccc92 ffeff47d 85845dd1
6fa87e4f fe2ce6e0 a3014314 4e0811a1 f7537e82 bd3af235 2ad7d2bb eb86d391
```
**Explanation:**
First pass, probably a few tricks left to golf further...
```
-1@" "/:'8 8#(,/$4_0x0\:)'_abs sin[1+!64]*/32#2; / the solution
32#2 / take 2, 32 times (2 2 2 2 2...)
*/ / product beginning with left argument
sin[ ] / built-in sine function
!64 / range 0..63
1+ / add 1, so 1..64
abs / built-in abs function
_ / floor
( )' / do this together for each
0x0\: / convert to byte representation
4_ / drop first 4 elements
$ / convert to string
,/ / flatten
8 8# / reshape to 8x8
" "/:' / join each with a single space
-1@ ; / print to stdout and swallow return
```
[Answer]
## Racket 125 bytes
```
(λ()(for((i(range 1 65)))(printf"~x "(inexact->exact(floor(*(expt 2 32)(abs(sin i))))))(when(= 0(modulo i 8))(printf"~n"))))
```
Ungolfed:
```
(define f
(λ ()
(for ((i (range 1 65)))
(printf "~x " (inexact->exact(floor (*(expt 2 32) (abs (sin i)) ))))
(when(= 0 (modulo i 8)) (printf "~n"))
)))
```
Testing:
```
(f)
```
Output:
```
d76aa478 e8c7b756 242070db c1bdceee f57c0faf 4787c62a a8304613 fd469501
698098d8 8b44f7af ffff5bb1 895cd7be 6b901122 fd987193 a679438e 49b40821
f61e2562 c040b340 265e5a51 e9b6c7aa d62f105d 2441453 d8a1e681 e7d3fbc8
21e1cde6 c33707d6 f4d50d87 455a14ed a9e3e905 fcefa3f8 676f02d9 8d2a4c8a
fffa3942 8771f681 6d9d6122 fde5380c a4beea44 4bdecfa9 f6bb4b60 bebfbc70
289b7ec6 eaa127fa d4ef3085 4881d05 d9d4d039 e6db99e5 1fa27cf8 c4ac5665
f4292244 432aff97 ab9423a7 fc93a039 655b59c3 8f0ccc92 ffeff47d 85845dd1
6fa87e4f fe2ce6e0 a3014314 4e0811a1 f7537e82 bd3af235 2ad7d2bb eb86d391
```
[Answer]
## [Pip](http://github.com/dloscutoff/pip), 37 bytes
36 bytes of code, +1 for `-S` flag.
```
0X8-#_._MMLC(2**32*ABSI++,64)TB16<>8
```
Pretty straightforward implementation. Unfortunately, 10 bytes are needed to left-pad some of the values with `0`. [Try it online!](http://pip.tryitonline.net/#code=MFg4LSNfLl9NTUxDKDIqKjMyKkFCU0krKyw2NClUQjE2PD44&input=&args=LVM)
```
,64 Numbers 0 to 63
++ Increment to get 1 to 64
SI Sine
AB Absolute value
2**32* Multiply by 2^32
( )TB16 Convert to hex (implicitly truncating to int)
LC Lowercase--Pip's base conversion uses uppercase :(
<>8 Group into sublists of size 8
MM Map this function to each item of each sublist:
8-#_ 1 if item is length 7, 0 if length 8
0X That many zeros
._ Concatenate to beginning of item
Print separated first by newline then by space (-S)
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 34 bytes
```
64{Tsab2 32**.*pd-.b68'0lp}GO8cosp
```
[Try it online!](https://tio.run/##SyotykktLixN/f/fzKQ6pDgxyUjB2EhLS0@rIEVXL8nMQt0gp6DW3d8iOb@44P9/AA "Burlesque – Try It Online")
```
64 # Literal 64
{
Ts # Sin
ab # Abs
2 32** # 2**32
.* # Times-by
pd # Floor
-. # Decrement by 1
b6 # To base 16
8'0lp # Left pad to length 8 with 0s
}GO # Range from [1, 64] and map
8co # Chunks of 8
sp # Pretty print array
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
64LŽĞJ*hl8jð0:8ô»
```
-2 bytes by taking inspiration from [*@Dennis*' Jelly answer](https://codegolf.stackexchange.com/a/82662/52210) regarding the leading 0s, so make sure to upvote him!
Outputs with trailing newline.
[Try it online.](https://tio.run/##ASQA2/9vc2FiaWX//zY0TMOFwr3DhD7FvkoqaGzigqzCpjjDtMK7//8)
**Explanation:**
```
64L # Push a list in the range [1,64]
Ž # Take the sine of each
Ä # Take the absolute value of that
> # Increase it by 1 (to avoid having to pad leading 0s later on)
žJ* # Multiply it by builtin 4294967296
h # Convert it from integer to hexadecimal
# (which implicitly truncates the decimals; and uses uppercase [A-F])
l # Convert that hexadecimal string to lowercase
€¦ # Remove the first character from each (undoing the earlier increment)
8ô # Split the list into parts of size 8
» # Join each inner list by spaces, and then those strings by newlines
# (after which it is output implicitly with trailing newline)
```
] |
[Question]
[
You are given the positions of the minute and hour hands of an analog clock as an angle of clockwise rotation from the top (12). So a hand pointing at 9 is at an angle if 270, and a hand pointing exactly in between 12 and 1 is at an angle of 15.
Input will be two integer angles (in any order of your choice) between 0 and 359. Minute hand will be a multiple of 60, hour hand will be a multiple of 5. Output will be the time, given as two integers separated by a colon (and nothing more).
**Sample data**
(Hour hand first)
```
195 180 - 6:30
355 300 - 11:50
280 120 - 9:20
0 0 - 12:00
10 120 - 12:20
```
[Answer]
# JavaScript ES6, 22 bytes
```
a=>b=>(0|a/30)+":"+b/6
```
[Try it online](http://vihan.org/p/esfiddle/?code=f%3D%20a%3D%3Eb%3D%3E(0%7Ca%2F30)%2B%22%3A%22%2Bb%2F6%0A%0Aalert(%20f(195)(180)%20)%0Aalert(%20f(355)(300)%20)%0Aalert(%20f(280)(120)%20)) (all browsers work)
[Answer]
## Pyth, 9 bytes
```
j\:.DyQ60
```
Explanation:
```
- autoassign Q = eval_input()
yQ - Q*2
.D 60 - divmod(^, 60)
j\: - ":".join(^)
```
[Try it here](http://pyth.herokuapp.com/?code=j%5C%3A.DyQ60&input=280&test_suite_input=195%0A355%0A280&debug=0)
[Or try a test suite](http://pyth.herokuapp.com/?code=j%5C%3A.DyQ60&input=280&test_suite=1&test_suite_input=195%0A355%0A280&debug=0)
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~13~~ 7 bytes
Le code:
```
Ḥd60j“:
```
L'explanation:
```
# Uses only the hour hand, (355)
Ḥ # Double this, (355 × 2 = 710)
d60 # Divmod 60, ([710 : 60, 710 % 60] = [11, 50])
j“: # Join by “:”, (11:50)
```
[Try it online!](http://jelly.tryitonline.net/#code=4bikZDYwauKAnDo&input=&args=Mjgw+MTIw)
[Answer]
# Retina, ~~93~~ 107 bytes
Byte count assumes ISO 8859-1 encoding
Had to fix a bug, code wasn't working for 0 in input and 0 minutes was shown as a single zero, not two. Fix for 0 in input didn't add any extra characters, but the minutes and new test case added some extra weight...
So...uh...integer division with regex?
```
(\d+) (\d+)
30$*' $1$*';¶6$*' $2$*';
m+`^('+) \1('*);('*)$
$1 $2;$3'
.+;
('*)¶('*)
$.1:$.2
:0$
:00
\`^0
12
```
Input is hours and minutes separated by space. Hours come first.
[Try it online!](http://retina.tryitonline.net/#code=KFxkKykgKFxkKykKMzAkKicgJDEkKic7wrY2JConICQyJConOwptK2BeKCcrKSBcMSgnKik7KCcqKSQKJDEgJDI7JDMnCi4rOwoKKCcqKcK2KCcqKQokLjE6JC4yCjowJAo6MDAKXGBeMAoxMg&input=MCAw)
[Answer]
## PHP, 50 bytes
```
function t($h,$m){echo floor($h/30)?:12.":".$m/6;}
```
Set `$h` and `$m` to whatever values you like, and off you go.
[Answer]
# Pyth, 11 bytes
```
++/E30\:/E6
```
[Try it online](http://pyth.herokuapp.com/?code=%2B%2B%2FE30%5C%3A%2FE6&input=280%0A120&test_suite_input=195%0A180&debug=0&input_size=2) or [Test Suite](http://pyth.herokuapp.com/?code=%2B%2B%2FE30%5C%3A%2FE6&input=280%0A120&test_suite=1&test_suite_input=195%0A180%0A355%0A300%0A280%0A120&debug=0&input_size=2)
Alternative version but the same size:
```
j\:[/E30/E6
```
## Explanation
~~Ab~~uses the fact that Python does integer division by default
```
/E30 Divide `\` input `E` by 30
+ \: Add literal `:`
+ /E6 Add input `E` divided by 6
```
[Answer]
# Perl 21 + 1 = 22 bytes
```
$_=($==$_/30).$".<>/6
```
Requires the `-p` flag and takes input on multiply lines. Requires `-l` for multiply inputs:
```
$ (echo $'195\n180';echo $'355\n300';echo $'280\n120') | perl -pl analclock.pl
6 30
11 50
9 20
```
Assigning to `$=` will always yield an integer `print($= = 1.23)` => `1`
[Answer]
# R, 29 bytes
```
cat(scan()%/%c(30,6),sep=':')
```
[Answer]
# CJam, 11 bytes
```
ri30/':ri6/
```
[**Try it online!**](http://cjam.tryitonline.net/#code=cmkzMC8nOnJpNi8&input=MTk1IDE4MA)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes
Code:
```
30/ï':I6/ïJ
```
Explanation:
```
30/ # Divide implicit input by 30
ï # Convert to int
': # Add the ':'-character
I6/ï # Input divided by 6 and converted to int
J # Join the stack
```
[Try it online](http://05ab1e.tryitonline.net/#code=MzAvw68nOkk2L8OvSg&input=MzU1CjMwMA)
Uses **CP-1252** encoding.
[Answer]
## [Pyke](https://github.com/muddyfish/PYKE), ~~10~~ 9 bytes
```
2*60.DRJ:
```
Explanation:
```
2* - a = eval_input_or_not() * 2
60.D - a,b = divmod(a, 60)
R - a,b = rot_2(a,b)
J: - ":".join([a,b])
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 10 bytes
```
720/2$15XO
```
The hour in the output has a leading zero if less than `10`.
[**Try it online!**](http://matl.tryitonline.net/#code=NzIwLzIkMTVYTw&input=MTk1CjE4MA)
```
720/ % take first input and divide by 720
2$15XO % format as HH:MM
```
[Answer]
# Perl 6, 54 bytes
```
{sprintf "%d:%02d",($^a div 30||12),$^b/6}
```
This accounts for 0 hours -> 12:00, as well as having two digits in the minutes place
[Answer]
# [DUP](https://esolangs.org/wiki/DUP), 12 bytes
```
[2*60/.':,.]
```
`[Try it here.](http://www.quirkster.com/iano/js/dup.html)`
Anonymous lambda that takes minutes then hours as arguments. Usage:
```
180 195[2*60/.':,.]!
```
# Explanation
```
[ ] {lambda}
2* {double hours}
60/ {divmod by 60}
. {output quotient}
':, {output :}
. {output remainder}
```
[Answer]
# [Milky Way 1.6.5](https://github.com/zachgates7/Milky-Way), 27 bytes
```
'2*60m":";+;?{_;+_^12;+0+}!
```
---
### Explanation
```
'2* ` double the input (195) -> [390]
60m ` divmod TOS by 60 -> [6, 30]
":";+; ` add a colon -> [":30", 6]
?{_;+_^12;+0+} ` format HH:MM -> ["6:30"]
! ` output TOS
```
[Answer]
# Japt, 14 bytes
```
U/30|0 +':+V/6
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=VS8zMHwwICsnOitWLzY=&input=MjgwIDEyMA==)
I really need to implement a shorter way to floor...
[Answer]
# Python 2.7, ~~35~~ 28 characters
Needs hour hand as a first input; ignores the minute hand input.
```
lambda i:`i/30`+":"+`i*2%60`
```
7 characters less thanks to @DenkerAffe by using lambda instead of `input()` and `print`.
[Answer]
# CJam, 11 bytes
```
ri2*60md':\
```
An alternate approach using divmod.
[**Try it online!**](http://cjam.aditsu.net/#code=ri2*60md%27%3A%5C&input=280%20120)
[Answer]
## Lua, 101 Bytes
A solution only using the hour argument. It is a full program taking the input via command-line argument `lua readAnalogClock.lua 355`. You could call it with 2 arguments, but the second one is never used.
```
i=arg[1]j=i%30i=(i-j)/30print(((i<1 and 12or i)..''):gsub("%..*","")..":"..(2*j..''):gsub("%..*",""))
```
### Ungolfed
```
i=arg[1] -- initialise i with the hours angle
j=i%30 -- initialise j with the minute part of i
i=(i-j)/30 -- round i to the previous hour
print(
((i<1 and 12or i)..'') -- replace 0 by 12 and make it a string
:gsub("%..*","") -- remove decimal part of hour (which is .0)
..":" -- concatenate with the separator
..(2*j..'') -- makes a string containing the minutes
:gsub("%..*","")) -- remove decimal part of minutes
```
] |
[Question]
[
**Goal**:
Write a function or program that, given an integer `n`, will output a program in the same language that is a quine with a period of `n`.
**Description of Output Program**:
The output program needs to be a program that, when run, ... will output a program... that will output a program... etc, until the `n`th program is the original (first) output program. So this is, in a way, a *modular quine*. That's how I think of it, anyway.
The resulting programs should all be distinct.
**Example:**
Input: `2`
Program: `modulus_quine(n)`
Output: `P` → `Q` → `P` → ...
**Scoring:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code (for the generating program) wins.
Brownie points (-0 bytes, +1 thumbs up?) are given to anyone whose generating program IS their modular quine. This is where your program takes the input and outputs the first modular quine in the sequence, which outputs the next, etc. The resulting output programs must not prompt the user for input (until it gets back to the generator.)
[Answer]
# GolfScript, 16 bytes
```
{%}+")1$~":x`+0x
```
Try it online in [Web GolfScript](http://golfscript.apphb.com/?c=OyIzIiAjIFNpbXVsYXRlIGlucHV0IGZyb20gU1RESU4uCgp7JX0rIikxJH4iOnhgKzB4).
### Example run
```
$ echo -n 3 | golfscript quining.gs
{3 % ")1$~"}0)1$~
$ echo -n 3 | golfscript quining.gs | golfscript
{3 % ")1$~"}1)1$~
$ echo -n 3 | golfscript quining.gs | golfscript | golfscript
{3 % ")1$~"}2)1$~
$ echo -n 3 | golfscript quining.gs | golfscript | golfscript | golfscript
{3 % ")1$~"}0)1$~
```
### Generator
```
# (implicit) Read from STDIN.
{%}+ # Concatenate the read input with the block.
# For example, "3"{%}+ -> {3 %}.
")1$~":x # Push that string and save it in the the variable `x'.
`+ # Inspect the string and concatenate it with the block.
# For example, {3 %}'")1$~"'+ -> {3 % ")1$~"}
0x # Push a 0 and the string stored in `x'.
```
### Modular quine
For example, the modular quine `{3 % ")1$~"}0)1$~` works as follows.
```
{ } # Define a block.
3 % # Take the integer on the stack modulo 3.
")1$~" # Push that string.
0) # Push 0 and increment. Pushes 1.
1$~ # Copy the block from the bottom of the stack and execute it.
```
The original copy of the block, the modified integer and the string the block pushed are printed, resulting in `{3 % ")1$~"}1)1$~`.
All printed programs have a trailing linefeed, which GolfScript prints automatically.
[Answer]
# Ruby, 100 bytes + brownie points
Generating program/zero-state:
```
;puts <<2.sub(/2*/){$&[/./]?$':?2*gets.to_i}*2,2
;puts <<2.sub(/2*/){$&[/./]?$':?2*gets.to_i}*2,2
2
```
Output for input of 3:
```
222;puts <<2.sub(/2*/){$&[/./]?$':?2*gets.to_i}*2,2
222;puts <<2.sub(/2*/){$&[/./]?$':?2*gets.to_i}*2,2
2
```
This program, when run, will not ask for input but output itself with the initial 222 on the first 2 rows replaced with 22. That will output a version where each row begins with 2, which will output the original program.
"2" lives a varied life here as (in order of appearance) a repeated digit in a no-op numeric literal, a HEREDOC reference, a regex literal, a character literal, a numeric argument to String#\*, a numeric argument to `puts`, a character in a HEREDOC string, and finally a HEREDOC delimiter.
[Answer]
# [Underload](http://esolangs.org/wiki/Underload), 29 bytes
```
(a(S)*)~^(a(:^)*)~*(^)*a(:^)*
```
Underload has no method to take input from the user, so I wrote a function rather than a complete program. The input is taken from the stack, the output is placed onto the stack (and can be printed with `S`).
Here's how to call it for an input of 1, `()`:
```
()(a(S)*)~^(a(:^)*)~*(^)*a(:^)*S
```
and it produces the following quine:
```
(a(:^)*a(S)*^):^
```
which runs like this:
```
(a(:^)*a(S)*^):^
(a(:^)*a(S)*^)(a(:^)*a(S)*^)^
(a(:^)*a(S)*^)a(:^)*a(S)*^
((a(:^)*a(S)*^))(:^)*a(S)*^
((a(:^)*a(S)*^):^)a(S)*^
(((a(:^)*a(S)*^):^))(S)*^
(((a(:^)*a(S)*^):^)S)^
((a(:^)*a(S)*^):^)S
program exits, with output (a(:^)*a(S)*^):^
```
As you can see, the modular quine of order 1 (i.e. just a normal quine) works by first generating a copy of itself, then generating a function to print that output, then running that function.
For higher orders, we just repeat the "generating a function to print that output" step (which is written in Underload as `a(S)*`). Here's how we call it for order 4 (`(:::***)` is 4):
```
(:::***)(a(S)*)~^(a(:^)*)~*(^)*a(:^)*S
```
Here's the program produced:
```
(a(:^)*a(S)*a(S)*a(S)*a(S)*^):^
```
which, when run, produces the following programs in turn:
```
((((a(:^)*a(S)*a(S)*a(S)*a(S)*^):^)S)S)S
(((a(:^)*a(S)*a(S)*a(S)*a(S)*^):^)S)S
((a(:^)*a(S)*a(S)*a(S)*a(S)*^):^)S
(a(:^)*a(S)*a(S)*a(S)*a(S)*^):^
```
The same technique probably works in other languages, although maybe not so concisely.
~~As a side note, Underload only has eight commands, so a hypothetical golfing version that represented each using 3 bits would use 29×3÷8 = 10⅞ bytes. That would make it the shortest solution here.~~ Although it only has nine commands, one (`()`) uses two different characters, so the previous calculation isn't quite correct.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 59 bytes
```
b=0;exec(s:=f"print('b=%d;exec(s:=%r)'%(-~b%{input()},s))")
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P8nWwDq1IjVZo9jKNk2poCgzr0RDPclWNQUuqlqkqa6qoVuXpFqdmVdQWqKhWatTrKmppPn/vxEA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 54 bytes
```
a=f'a=%r,-~%d%%{input()};print(a[0]%%a)';exec(a%(a,0))
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P9E2TT3RVrVIR7dONUVVtTozr6C0REOz1rqgKDOvRCMx2iBWVTVRU906tSI1WSNRVSNRx0BT8/9/IwA "Python 3.8 (pre-release) – Try It Online")
Let say input is `3` this will output :
```
a='a=%r,-~%d%%3;print(a[0]%%a)',-~1%3;print(a[0]%a)
```
which will output :
```
a='a=%r,-~%d%%3;print(a[0]%%a)',-~2%3;print(a[0]%a)
```
which will output :
```
a='a=%r,-~%d%%3;print(a[0]%%a)',-~0%3;print(a[0]%a)
```
... and so on
## How it works :
This solution uses the same idea than an [other solution](https://codegolf.stackexchange.com/a/225977/103772) of mine on an other challenge
The main idea is to modify the second element of the tuple `a` each iterration inside the string with `'-~%d'%a`. `-~x` corresponds to an incrementation of 1.
Then we loop using a modulo equal to our input (using f-string to replace it in the base program)
] |
[Question]
[
Seeing as its St. Patrick's day, I thought I would have a little challenge
Your task is to write a program draws a clover in any way possible. Each leaf has to be symmetrical, and the user has to input the number of leaves that they want on the clover. It then must be drawn. This has to be generated. You cannot just load an image or have ASCII art saved as a variable. However using modules like `turtle` to generate (and draw is included under generate) are fine.
You can use any language. This is a code-golf so the shortest answer wins.
Begin! Happy St Patrick's Day!
Just for reference, here is an example of a 3 leaf clover 
Just for DavidCarraher 
[Answer]
## Mathematica - 106 bytes
```
c=RegionPlot[x^2+y^2<Abs@Sin[#x~ArcTan~y/2]||x>0&&y^2<.001,{x,-1,1},{y,-1,1},Frame->0>1,PlotStyle->Green]&
```
Ungolfed version:
```
c[leaves_] := (
angle = ArcTan[x,y];
RegionPlot[
x^2 + y^2 < Abs[Sin[leaves*angle/2]]
|| x > 0 && y^2 < .001
, {x,-1,1}
, {y,-1,1}
, Frame -> False, PlotStyle -> Green
]);
```
Here are the outputs for `c[3]` through `c[6]`.

At the cost of another **7 bytes** you can improve the colour (using `PlotStyle->Darker@Green` or `PlotStyle->Hue[.3,1,.7]` instead), and for another **15 bytes** you can remove some of the sampling artifacts (using an additional option `,PlotPoints->90`), giving a total of **128 bytes** for these beauties:

The braces and commes in those pictures are not produced by `c`, but just by how I output them to fit them all in one row.
Lastly, here is an attempt at somewhat neater shading. I didn't even bother golfing this down further, the option names are just too long. I'm not even sure I'm too pleased with the result, but I thought I'd post it anyway. This is **188 bytes** as it stands:
```
c=RegionPlot[x^2+y^2<Abs@Sin[(l=#)x~(a=ArcTan)~y/2]||x>0&&y^2<.001,{x,-1,1},{y,-1,1},Frame->0>1,PlotPoints->90,ColorFunction->(Hue[.3,1,.5+.2Sin[.5l#~a~#2]^8]&),ColorFunctionScaling->0>1]&
```

[Answer]
# C (145 126)
```
float d=2/--r,x,y=-1;for(;y<=1;y+=d,puts(""))for(x=-1;x<=1;x+=d)putchar(x*x+y*y<fabs(sin(l*atan2(x,y)))||fabs(x)<d&y>0?35:32);
```
Draws a clove in ASCII art; the function is passed the number of desired leaves and the resolution in characters. See example here: <http://ideone.com/YDGN4H>
Note that the result is much nicer when the horizontal resolution is doubled, at the cost of a slightly more verbose code (see <http://ideone.com/RYaLz4>).
**Full version:**
```
#include <math.h>
#include <stdio.h>
void clover(float l, float r)
{
float d = 2.f / --r;
float x, y=-1.f;
for (; y<=1.f; y+=d){
for (x=-1.f; x<=1.; x+=d){
printf((x*x + y*y < fabs(sin(l * atan2(x,y))) | (fabs(x) < d & y > 0)) ? "#" : " ");
}
printf("\n");
}
}
int main(int argc, char* argv[])
{
clove(4.f, 48.f);
return 0;
}
```
] |
[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/21941/edit).
Closed 6 years ago.
[Improve this question](/posts/21941/edit)
Write a polyglot (code that works in two or more languages) that has a "mid-section" that can be modified to do any computational task. This question is similar to <https://stackoverflow.com/questions/1053931/code-golf-shortest-turing-complete-interpreter>.
**Rules**:
The program must be able to preform a computation and print the results. Pseudorandom number capability is a plus but not necessary. The results must be the same in all languages, minor string-formatting differences are OK.
There is a section in the program that can be modified (in a straight-forward way) to do any computation (Turing complete). This is like the "comments section" in <http://ideology.com.au/polyglot/polyglot.txt> for which any comment can be inserted.
You must use at least 2 languages (this rule is here so you don't sue me).
**Edit**: Ideally you only need to write the "computation" part once. It is less interesting to use comment blocks, etc to knock out A so you have a block from B and then knockout B to write code from A. However, the one block solution is very difficult unless the languages have enough "overlap".
Also, using very similar languages (like C# and Java) isn't as interesting. It is still *allowed* but will probably earn less votes.
**Grading**
The winning is a popularity contest (Mar 1st).
[Answer]
## C, Python, and Brainfuck
The Brainfuck program on the line starting with `pgm=` can be changed into any valid Brainfuck program (so it is Turing-complete). The program will then run in C, Python, and Brainfuck. The given program prints `Hello World!`.
The interpreters in both C and Python have the following characteristics:
* 8-bit cells
* Infinite tape in both directions
* -1 (255) on EOF
It runs like this:
```
$ gcc poly_bf.c; ./a.out
Hello World!
$ python poly_bf.c
Hello World!
$ bf poly_bf.c
Hello World!
```
And here's the program:
```
#define AA [
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BB ]
#define PGM char*\
pgm="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
#define ZZ \
""" [-][";
struct cell { char val; struct cell *prev; struct cell *next; };
struct cell *prv(struct cell *c) {
if (!c->prev) {
struct cell *z = malloc(sizeof(struct cell));
z->next = c;
z->prev = 0;
z->val = 0;
c->prev = z;
}
return c->prev;
}
struct cell *nxt(struct cell *c) {
if (!c->next) {
struct cell *z = malloc(sizeof(struct cell));
z->prev = c;
z->next = 0;
z->val = 0;
c->next = z;
}
return c->next;
}
int main() {
PGM
int ip=0, t=0;
struct cell *c = malloc(sizeof(struct cell));
memset(c, 0, sizeof(struct cell));
while (pgm[ip]) {
switch(pgm[ip]) {
case '+': c->val++;break;
case '-': c->val--;break;
case '>': c=nxt(c);break;
case '<': c=prv(c);break;
case '.': putchar(c->val);break;
case ',': c->val=getchar();break;
case '[':
if (c->val) break;
ip++;
t=1;
while (t) {
t += pgm[ip] == '[';
t -= pgm[ip] == ']';
ip++;
}
ip--;
break;
case ']':
if (!c->val) break;
ip--;
t=1;
while (t) {
t -= pgm[ip] == '[';
t += pgm[ip] == ']';
ip--;
}
ip++;
break;
}
ip++;
}
return 0;
}
#define YY \
" """;
#define XX /*
import sys;
ip=t=0
class Cell:
pv=None
nx=None
val=0
def prev(self):
if not self.pv:
self.pv = Cell()
self.pv.nx = self
return self.pv
def next(self):
if not self.nx:
self.nx = Cell()
self.nx.pv = self
return self.nx
cell=Cell()
while ip<len(pgm):
if pgm[ip]=='+': cell.val+=1;cell.val%=256
elif pgm[ip]=='-': cell.val-=1;cell.val%=256
elif pgm[ip]=='>': cell=cell.next()
elif pgm[ip]=='<': cell=cell.prev()
elif pgm[ip]=='.': sys.stdout.write(chr(cell.val))
elif pgm[ip]==',':
ch=sys.stdin.read(1)
if ch:cell.val=ord(ch)
else:cell.val=255
elif pgm[ip]=='[' and not cell.val:
t=1
ip+=1
while t:
t += pgm[ip] == '['
t -= pgm[ip] == ']'
ip+=1
ip-=1
elif pgm[ip]==']' and cell.val:
t=1
ip-=1
while t:
t -= pgm[ip] == '['
t += pgm[ip] == ']'
ip-=1
ip+=1
ip+=1
#]*/
```
[Answer]
## Ruby and Spidermonkey JS
```
i=0
r=rand
=begin
=Math.random(); n=print;
var end=''; y
=end
//=~''; def n(x); puts x; end
while ((i+=1) < 5)
if (i%2==0)
n('Hi!')
else
n('Bye!')
end;
end;
a=17*r
n(a);
```
This works because...
* `rand` is random in Ruby, but a variable in JS that gets assigned to `Math.random()`. A slight improvement would be assigning JS's `rand` to `Math.random` so that you can execute rand() in both.
* `=begin...=end` is a comment block in Ruby and assignment in JS
* The middle part is polyglot. If you gave the list of any functions you'd like, I'd def them in Ruby so they are the same as the JS ones or possibly define them in JS.
* `end`, needed to end code blocks in ruby is now defined as `''` in JS.
* `while` is the same in both languages, as is `+=`, `==`, `-=`, `*`, `-`, `+`, `=`, `%`, `/`, `'strings'`
* `//` is the start of a comment in JS but a regex in Ruby.
* `n` is defined in Spidermonkey JS to be `print` (which outputs to stdout). In Ruby, I redefined it to be `puts`, much the same. If I weren't in a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") mindset, I would have `def print(x)` instead of `n(x)`.
* **No use of polyglot comments!**
[Answer]
# Ruby and C
```
//; def void x; end; def main x, &b; b.call; end; def int x; end; arg = nil
//# Welcome to the Ruby/C polyglot thingy!
//# Simply insert whatever code you would like below.
void main(int arg) {
//; puts 1+1 # any Ruby code can be inserted on this line
//; puts 2+2 # the Ruby version is extendable to an arbitrary amount of lines
//; puts 3+3
//; puts 4+4
#define f printf(1+1) // any C code can be inserted on this line
//;f=nil
f;
#define g printf(2+2) // the C version is somewhat extendable
#define h printf(3+3)
#define i printf(4+4)
//;g=h=i=nil
g;h;i;
}
```
This takes advantage of the fact that
* `//#` is a comment in both languages
* `//;` is a comment in only C
* `"#define x "` (with the space!) is (somewhat of) a comment in only Ruby
+ you then have to actually put it in the code, which is why I assign all the vars to `nil` and then simply place them in a new line
# More extendable C version
```
//; def method_missing m, *args; end
#define a printf(1+1);
#define b printf(1+1);
#define c printf(1+1);
#define codegolf printf(1+1);
#define llama printf(1+1);
a b c codegolf llama
```
[Answer]
# PHP, ASP and JS:
WARNING: THIS WAS NOT TESTED:
Here is an attempt:
```
<!--<?error_reporting(0);?><% WebService Language="JScript" Class="MyClass" %>-->
<script runat="server">
console.log('/*<?=#*/$a='Math';/*?>*///#?>');
</script>
```
What should happen:
It should run the Javascript code on the server, when running on ASP.
In php, should output absolutely only the Javascript part, Saying 'Math' inside the whole comments.
In Javascript, it should put all that "garbage" in the console.
If it is invalid, just comment and I will remove this answer.
] |
[Question]
[
Your challenge is to golf a program that mimics a data transmission stream. Your program should read input from stdin and output it directly to stdout. To make the problem more interesting, the output stream is 'faulty', and must meet several requirements:
1. There should be a 10% chance that each character is shifted +1 ascii code (ex 'a' becomes 'b', '9' becomes ':'), etc.
2. The input and output should only cover printable ascii values ('!' through '~', decimal 33 through decimal 126, inclusive). If the random +1 occurs on a '~' (decimal 126), a '!' (decimal 33) should be output instead.
3. If three characters are randomly shifted in a row, the program should output "ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR" (trailing newline optional) and halt execution.
To simplify the problem, here are a few other criteria:
1. You can assume the input will always be valid; that is, it will only contain values '!' through '~'.
2. The program should continue on until three characters are randomly shifted in a row; it's safe to assume that EOF will never occur.
3. The randomness must differ across runs; if your random number generator needs to be seeded to get an unique result each run, then your code needs to seed it.
4. You must write a program, not a function.
5. You must take input from stdin and write output to stdout.
6. You may not use any external libraries or resources.
7. Your code must have a freely available and working intrepreter or compiler.
Standard code-golf rules apply. Winner is whoever has the shortest program posted two weeks from now (Thursday, Feb 20th, 2014).
[Answer]
# Befunge-98, ~~166~~ ~~159~~ ~~156~~ ~~155~~ 148
This one improves on the other excellent Befunge answer with the correct probability (1/10) and is slightly more compact:
```
~>?#v?1+\1>+\:'~1+-4k#x07_$'!>,:3-!#v_
>#?>>>\$\0^>
^<<
A"## "CT YOUR SYSTEM ADMINISTRATOR"<@,kM'"ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONT
```
[Answer]
## C, 168 characters
```
i;main(c){for(srand(&c);i++<3;putchar(rand()%10?i=0,c:c-126?c+1:33))c=getchar();
puts("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR");}
```
This solution's seeding of the PRNG takes advantage of the fact that modern OSes change the stack's location in memory on each run, as a basic measure against stack-smashing exploits.
[Answer]
## Ruby, 156
```
e=3
putc(($_.ord-33+r=rand(10)/9)%94+33)/e=r>0?e-r :3while gets(1)rescue$><<'ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR'
```
[Answer]
## Batch - 359
Open to suggestions to make it completely compliant to the challenge rules.
I will work on making it smaller / better - I wanted to post it while it's working, before I break it.
```
@echo off&setLocal enableDelayedExpansion&for /L %%a in (33,1,126)do cmd/cexit %%a&set %%a=!=exitcodeAscii!
set a=%~1
:l
if defined a (
set c=!a:~0,1!&set a=!a:~1!&set b=0&set/ar=%RANDOM%*10/32768+1
if !r!==1 for /L %%b in (33,1,126)do (
if !b!==1 echo !%%b!>>f
if "!c!"=="!%%b!" set b=1
)
if !b!==1 set/pc=<f&del f
set o=%o%!c!&goto l
)
echo %o%
```
There are definitely quite a few ways to golf it down.
```
h:\uprof>UDS.bat "test ing"
tesu inh
h:\uprof>UDS.bat "test ing"
tfsu ing
```
Un-golfed -
```
@echo off
setLocal enableDelayedExpansion
for /L %%a in (33,1,126) do (
cmd /c exit %%a
set %%a=!=exitcodeAscii!
)
set a=%~1
:l
if defined a (
set c=!a:~0,1!
set a=!a:~1!
set b=0
set /a r=%RANDOM%*10/32768+1
if !r!==1 for /L %%b in (33,1,126) do (
if !b!==1 echo !%%b!>>f
if "!c!"=="!%%b!" set b=1
)
if !b!==1 set /p c=<f& del f
set o=%o%!c!
goto l
)
echo %o%
```
[Answer]
## PHP 190
that's the further i could golf it, but i think it's pretty good that it is less than 100 chars from the leading
```
<? while($a=fread(STDIN,1)){if(!rand(0,9)){$a=$a=='~'?'!':chr(ord($a)+1);@$i+=1;$i>2&&die("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR");}else$i=0;echo$a;}
```
[Answer]
# C# - 346 330 313 309 297 288 278 274
Kinda long but does the job.
```
using System;class m{static void Main(){int c=0;var r=new Random();while(c<3){int n=r.Next(10);var j=Console.In.Read();Console.Write((char)(n<1?j>'}'?'!':++j:j));c=n<1?c+1:0;}Console.Write("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR");}}
```
[Answer]
## ~~sh~~ bash, on OSX, ~~211~~, ~~208~~, ~~203~~, ~~200~~, ~~196~~, 185
```
IFS=
while read -n1 a;do
((RANDOM>3276))&&echo $a&&t=0||{
tr !-}~ \"-~!<<<$a
((t++==2))&&echo ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR&&exit
}
done
```
Slightly better than 10% since random will generate numbers between 0 and 32767, so really it's 3,277 in 32,768 odds (10.0006%).
Thanks, @Gilles (but not sure what you mean about the while restructure. had some other ideas in the shower, too.
[Answer]
# C, ~~260~~ ~~257~~ ~~237~~ ~~225~~ ~~189~~ 174
My first golf, suggestions appreciated.
```
n;main(){for(srand(&n);n!=3;putchar((getchar()+(rand()%10==7?!!++n:(n=0))-33%94)+33));puts("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR");}
```
7 is very random.
Compiling will give you warnings.
Thanks for help from breadbox and Josh.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 63 bytes
```
ƛ₀℅‹¬;:ĠṠ3<A[?C+₇‹33VC|`»ȯ ¬⋎ 4625: un₆¬×→ »ȯ, ƛṙ λḊ λ¢ ƛβ ↑Ẇ`⇧
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwixpvigoDihIXigLnCrDs6xKDhuaAzPEFbP0Mr4oKH4oC5MzNWQ3xgwrvIryDCrOKLjiA0NjI1OiB1buKChsKsw5fihpIgwrvIrywgxpvhuZkgzrvhuIogzrvCoiDGm86yIOKGkeG6hmDih6ciLCIiLCJ+fn5+fn5+fn5+fn5+fn5+fn5+fiJd)
```
ƛ ; # Map input to...
₀℅‹¬ # 1 with chance 10%
:ĠṠ # Get sums of groups of identical run lengths
3<A[ # If all are less than 3 (no error)
?C+ # Add randoms to input charcodes
₇‹33V # Replace 127 with 33
C # Get charcodes
|`... # Else output the string
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 215 bytes
```
for(z=1,r='';z<<=9;z|=y+''==x,r+=y>'~'?'!':y)require('fs').readSync(0,x=Buffer(1),0,1),y=x.map(t=>t+(Math.random()<.1));console.log(r+'ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR')
```
[Try it online!](https://tio.run/##jVTbbttGEP0VNUCxJMQQknMBIlkpFEcBDMRWICktDORltByKW@@F2YsoGkV/3ZklaRlGX/oicXdnzlzOmfkbjuC4FbV/rU2Bj4@lscnDYprZBWPzh8vLxYf5wz@LdszYYnHK7HjRfmT/sj/Yb2zWphZ/BmExYaVjaW4Rim2reTLJTotPoSzRJtM0m2T00y5OuYI68YuPfpzcgK9yC7owKkkv82mazrnRzkjMpTkkdsxWm816M7paf16N3r6/eDcbfb/drK7Wf642y09fV6PuORt9@7pabldkdrtbXu1Gd@vvm9H2brtb3YyWn2@ub6@3u81yt96w9PHxzgTLK5AS9QGF8@ZgZAm1NQcLylfglVCCOyjAg6fcnBLOCcrKU10qj@6DsatMkEWsVug6@NIa5Tx9x3qCpxtBJ4vcy9YbeqHLfGcU3KOvkDD2EpUyFoX2aNF5oQ8ZvfS@fTjhWAlB@pZlhKqC8wrROzyiBTl0XaH2brarIkaX0R5hOvmdatQcY0EIvKKTBU5xqJhKlB6L8ZQIF4IT2wmeGLA9cqPQsT3L2IfzacbSDD3PCb@r8lxcH8to2XJD6dSWygAqqUM9ggzoElKHr6wJh4q0khXIhQL55s1wN5ynF@8zobkMThwxza9L6kGvifHUcB6sMxrIP3m2TzMg6OQMmD4VPvSdyCJWOiiLeK7dgR2QZTt0gdiypsl6Qp5J7XF@vOr0FdXXie@F9nrp9cobhBd118vuhep@vEpISEISvxob@kNTe1IUyJSSISl6PCEP8Yr04YSqpSjbZ41kkVpKHUpsTGwOzWlkEmYkRg4anAsqaqojqBFSgmygdXskGkQxjxoQLhPdU08YUSV0T9ILjiLNLxoRTYUOaHSgD/k/@zkXnjlH@XrzlBz41fpLTEBH8Xa8xmC9u0bnorgLEZcFcGucs0G7OfWB5m0wCmqP9oCaLLyxGrGg6d2jow8saI6RxBm0@BniJNDQRN0TSiRXR5go9cEr@ggfhzmGbWI/n1ZApo2HMmje8TFYeBra/wx559Yr5Tzf0R5agggOQbd4ojYR0VLsLViBzljKLeaCrlslMacYoIIj8UvNlS1tYiG7SaIQxt6TbGi0LPGCBGbIRdVCos23cRjBFhHjddxiNkh0UNeyzf8SWsdhbyoT@10BhYjrwXpaNEOlNSVNjWtMg3jvYmXaNMmuookroM2@4P5i4qvsYjJ9m@a/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~65~~ ~~64~~ 63 bytes
```
v9°Ω})DÅγsÏ3åi.•kUàø¸àŸ´•uŽIZ‘‰ëƒË ÿ: ÿ‰ë,‚µ€Í€ž‚«¢é‘ësÇ+ƵQ33:ç
```
[Try it online!](https://tio.run/##yy9OTMpM/f@/zPLQhnMrazVdDree21x8uN/48NJMvUcNi7JDDy84vOPQjsMLju44tAUoUHp0r2fUo4YZjxo2HF59bNLhboXD@62AGMzXedQw69DWR01rDvcCiaP7QNzVhxYdXgnUcHh18eF27WNbA42NrQ4v//9fUUlZRVVNXUNTS1tHV0/fwNDI2MTUzNzC0sraxtbO3sHRydnF1c3dw9PL28fXzz8gMCg4JDQsPCIyKjomNi4@ITEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orKquqa2DgA "05AB1E – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), ~~357~~ 355 bytes
2 bytes saved after discovering [this](https://codegolf.stackexchange.com/a/241971/109937)
```
import java.util.*import kotlin.random.*import kotlin.random.Random
var c=0
fun main(){var a =Scanner(System.`in`).next().toMutableList()
for(i in a.indices){if(Random.nextUInt()%10u<1u){c++;if(a[i]=='~')a[i]='!' else a[i]=a[i]+1}else if(c<3)c=0}
if(c>2)print("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR")else print(a)}
```
[Try it online!](https://tio.run/##dY5NS8NAEIbv@RVjQZI1srT146CNENs9FJpGNolQROiabmFssinJpiil/vW42Xr1MjPvO8987CpdoOo6LPdVreFTHARtNRb06s/ZWYDWQm2q8h@X2@QcRA15MHS2rYJSoPLIsbcEBEkulJK1l3w3WpZ0jWpNqJJf2iNUV1GrxUchF9gY7Wyr2kNABYKi2mAuG3LErXe@YYeyuTLg5WjYTkYtOea@/2gA8YbvQeD@uMRW7oULsmgkWNUHf3SyhmHzyQ0xn56cvn4ak32NZuWAcR5zmMYzBrf347sHyJacTeNXxsPnBQPbvoaXBQsTZrBlGk5TWMUZh2SVpCyCcBbNl/Mk5WEa8wGx5867BTl13S8 "Kotlin – Try It Online")
I've noticed that adding newlines causes the same amount of bytes to accumulate compared to adding a semicolon. hence why it isnYt so one liney.
this of course does not work with tio.run as it requires input.
If you see any places where there could be any kind of improvement please tell.
#### Ungolfed version
```
import java.util.*import kotlin.random.*import kotlin.random.Random
var c =0
fun main()
{
var a = Scanner(System.`in`).next().toMutableList()
for(i in a.indices){
if(Random.nextUInt()%10u<1u)
{
c++
if(a[i]=='~') a[i]='!'
else a[i]=a[i]+1
}
else if(c<3)c=0
}
if(c>2) print("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR")
else print(a)
}
```
~~[Try it online!](https://tio.run/##bY5Na8JAEIbv@RVToSRryqL241BNIdU9CJqUTVKQUnAbV5iabCTZSIvYv56ua4@9zMz7zjMfu0oXqLoOy31Va/gUB0FbjQXtj/@snSVoLdSmKim36f9e3zmIGvJg4GxbBaVA5ZHj2RIQJLlQStZe8t1oWdI1qjWhSn5pj1BdLVstPgq5wMZoZ1vVHgIqEBTVBnPZkCNuvctpO5TNlQGvh4N2MmzJMff9sQHEG74HgfvjElu5Vy7IopFg1Tn4w5M1DJtPbon59OSc66cR2ddoVvYY5zGHaTxjcPcwun@ELOJsGr8yHj4vGNj2DbwsWJgwg0VpOE1hFWccklWSsiWEs@U8micpD9OY94g9d9ktyKnrfgE "Kotlin – Try It Online")~~
```
import java.util.*;import kotlin.random.Random;import kotlin.random.*
var c=0
fun main(){var a =Scanner(System.`in`).next().toMutableList()
for(i in a.indices){if(Random.nextUInt()%10u<1u){c++;if(a[i]=='~')a[i]='!' else a[i]=a[i]+1}else if(c<3)c=0}
if(c>2)print("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR")else print(a)}
```
] |
[Question]
[
Given two arbitrary integers \$a\$ and \$b\$, count how many numbers are divisible by [perfect numbers](http://oeis.org/A000396) in that given range (\$a\$ and \$b\$ both are inclusive).
>
> In mathematics, a perfect number is a positive integer that is the sum
> of its proper positive divisors, that is, the sum of the positive
> divisors excluding the number itself.Equivalently, a perfect number is
> a number that is half the sum of all of its positive divisors
> (including itself), or \$σ(n) = 2n\$.
>
>
>
**Input:**
```
1 100
```
**Output:**
```
18
```
* Use stdin and stdout for Input/Output
* **Your code must handle big integers, so it is not good enough to hard-code a list of perfect numbers.**
* Shortest code wins
[Answer]
## Perl 6, ~~106~~ 103 characters
```
my ($a,$b)=get.words;(($a..$b).grep: *%%any ($a..$b).grep: {$^n==[+] ($^n%%$_&&$_ for 1..^$^n)})[*.say]
```
There's a lot of syntax here, so hopefully this explanation helps at least a little to someone who knows a bit of Perl 5 syntax, though I won't explain every detail:
Finds all the perfect numbers in the range $a..$b: `($a..$b).grep: {$^n==[+] ($^n%%$_&&$_ for 1..^$^n)}` (explained below). It then chooses all the numbers in the range $a..$b which are divisible (`%%`) by any of the perfect numbers it had found: `(%a..%b).grep: * %% any …`.
The final `(…)[*.say]` abuses the fact that any code (in this case `*.say`, which prints its argument and a newline) passed to the `[…]` postfix will be given the list's length as its argument (so that one can, e.g., use the idiomatic `@array[*-1]` to get the last element of `@array`). This means that the `(…)[*.say]` here has the same effect as `say (…).elems`.
The part that finds all the perfect numbers in the range does so by returning only those numbers which are equal (`$^n ==`) to the sum of their divisors. `[+]` adds together the values following it, `for 1..^$^n` iterates over all numbers 1 to $^n-1 and assigns $\_ to them, and `$^n %% $_ && $_` returns $\_ if $^n is divisible (`$^n %% $_`) by $\_, or else `False`, thus creating a list that consists of the proper divisors of $^n and `False` objects, which numify to 0 when all the values are added together by `[+]`.
Perl 6 uses arbitrary sized integers, so, if you have the resources and the time, it could technically compute for big integers
[Answer]
# Mathematica - 117
Naive approach, linear for the range size
```
With[{p=#(#+1)/2&/@Select[2^Range@@Floor@Log2@Sqrt@#-1,PrimeQ]},Length@Select[Range@@#,Or@@Divisible[#,p]&]]&@Input[]
```
The correct way would be constructing numbers from the perfect numbers that are in the given range of course.
[Answer]
# Haskell - 157
```
c x=x==sum[i|i<-[1..x-1],mod x i==0]
d x=any((0==).mod x)$takeWhile(<=x)(filter c[2..])
main=do m<-getLine;n<-getLine;print$length(filter d[read m..read n])
```
Can work with arbitrarily large numbers given respectively large time.
Input is given on 2 lines.
[Answer]
# C, ~~125~~120
```
a,b,c,p[4]={6,28,496,8128};main(i){for(scanf("%d%d",&a,&b);a<=b;a++)for(i=0;i<4;)if(a%p[i++]==0)c++,i=4;printf("%d",c);}
```
A little more readable:
```
a,b,c=0,i,p[4]={6,28,496,8128};
main()
{
for(scanf("%d%d",&a,&b);a<=b;a++)
for(i=0;i<4;)
if(a%p[i++]==0)
{
c++;
i=4;
}
printf("%d",c);
}
```
This works with signed 32bit integers, up to **2^31-1=2147483647**.
# C, ~~212~~209
```
#include<stdint.h>
uint64_t a,b,c,p[8]={6,28,496,8128,33550336,8589869056,137438691328,0x1fffffffc0000000};main(i){for(scanf("%lld%lld",&a,&b);a<=b;a++)for(i=0;i<8;)if(a%p[i++]==0)c++,i=8;printf("%lld",c);}
```
Should work up to **2^64-1=18446744073709551615**.
[Answer]
## Python 3 [166 bytes]
```
a,b=map(int,input().split());print(len(set([n if n%p==0 else 0 for p in [x for x in range(a,b) if sum(y for y in range(1,x) if x%y==0)==x] for n in range(a,b+1)]))-1)
```
More readable:
```
// STDIN => a, b
a, b = map(int, input().split())
// list of perfect numbers
perfect = [x for x in range(a, b) if sum(y for y in range(1, x) if x % y == 0) == x]
// length(number % [any perfect number] == 0) => STDOUT
print(len(set([n if n % p == 0 else 0 for p in perfect for n in range(a, b + 1)])) - 1)
```
Here the list of perfect numbers is calculated inline but may be set statically. The number range should be bound by the machine's word size.
While this algorithm is deadly slow and takes ages for working with big numbers, it is at least short `:)`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
rÆD=Æṣ$§TL
```
[Try it online!](https://tio.run/##y0rNyan8/7/ocJuL7eG2hzsXqxxaHuLz//9/w/@GBgYA "Jelly – Try It Online")
Requiring space separated STDIN input bumps the byte count up to [15 bytes](https://tio.run/##AScA2P9qZWxsef//yaDhuLJW4oKsci/DhkQ9w4bhuaMkwqdUTP//MSAxMDA)
## How it works
```
rÆD=Æṣ$§TL - Main link. Takes a on the left and b on the right
r - Yield [a, a+1, ..., b-1, b]
ÆD - Generate the divisors of each
$ - Over each list of divisors, d:
Æṣ - Generate the proper divisor sum of each value in d
= § - Count how many are equal to their proper divisor sum
This maps numbers with perfect to divisors to a non-zero value
and those without to 0
TL - Count the number of non-zero elements
```
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=sum,any -pl`, 77 bytes
```
$"=$_,$\+=any{$"%$_==0}grep{//;2*$_==sum grep{$'%$_==0}1..$_}2..$"for$_..<>}{
```
[Try it online!](https://tio.run/##K0gtyjH9/19FyVYlXkclRts2Ma@yWkVJVSXe1tagNr0otaBaX9/aSAvELy7NVQCLqKhD5Q319FTia42ApFJafpFKvJ6ejV1t9f//hlyGBgb/8gtKMvPziv/r@vpkFpdYWYWWZOaADNEB2vFftyAHAA "Perl 5 – Try It Online")
Ungolfed:
```
$_ = ; # implicit by -p command line switch
for$_($_..){ # loop over the range from $_ to the next input
$"=$_; # store a copy of the current number ($_) so it can be used in sub-loops
$\+= # counter for number of perfectly divisible numbers found
any{$"%$_==0} # check if the current number ($") is evenly divisible by a:
grep{//;2*$_== # PERFECT NUMBER: a number where twice the number equals
sum grep{$'%$_==0}1..$_ # the sum of the numbers which divide it evenly
}2..$" # that exists in range of 2 to the current number
}
print$\; # implicit by -p command line switch
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
ṡƛ'∆K=;Ḋa;∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuaHGmyfiiIZLPTvhuIphO+KIkSIsIiIsIjEwMFxuMSJd)
[9 bytes with `s` flag](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwi4bmhxpsn4oiGSz074biKYSIsIiIsIjEwMFxuMSJd)
[12 bytes accounting for space seperated inputs](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLEluG5ocabJ+KIhks9O+G4imE74oiRIiwiIiwiMSAxMDAiXQ==)
## Explained
```
ṡƛ'∆K=;Ḋa;∑
ṡƛ ; # Over each item x in the range [input a, input b]
'∆K=; # Keep items from the range [1, x] that are perfect numbers
Ḋa # And is x divisible by any of those perfect numbers?
∑ # Sum the number of numbers that are divisible by a perfect number
```
] |
[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/10656/edit).
Closed 6 years ago.
[Improve this question](/posts/10656/edit)
When I was a young teen I had a very boastful friend who claimed he could code up [breakout](http://en.wikipedia.org/wiki/Breakout_(video_game)) in half an hour. Half an hour later he had done a great job but it didn't quite work. This challenge is to see in 2013 how short it is possible to code this classic game. For the purposes of the competition there need only be one level and no score keeping is needed. The game should be controlled from the keyboard (right and left is all that is needed) but the bricks need to be destroyed correctly and the ball has to bounce in the usual way.
You can choose any programming language you like as well as any free (in both sense) libraries. The code should run in linux.
To inspire you, here is a bare bones and completely ungolfed version of the game in python by Leonel Machava from <http://codentronix.com/2011/04/14/game-programming-with-python-and-pygame-making-breakout/> .
```
"""
bricka (a breakout clone)
Developed by Leonel Machava <[[email protected]](/cdn-cgi/l/email-protection)>
http://codeNtronix.com
"""
import sys
import pygame
SCREEN_SIZE = 640,480
# Object dimensions
BRICK_WIDTH = 60
BRICK_HEIGHT = 15
PADDLE_WIDTH = 60
PADDLE_HEIGHT = 12
BALL_DIAMETER = 16
BALL_RADIUS = BALL_DIAMETER / 2
MAX_PADDLE_X = SCREEN_SIZE[0] - PADDLE_WIDTH
MAX_BALL_X = SCREEN_SIZE[0] - BALL_DIAMETER
MAX_BALL_Y = SCREEN_SIZE[1] - BALL_DIAMETER
# Paddle Y coordinate
PADDLE_Y = SCREEN_SIZE[1] - PADDLE_HEIGHT - 10
# Color constants
BLACK = (0,0,0)
WHITE = (255,255,255)
BLUE = (0,0,255)
BRICK_COLOR = (200,200,0)
# State constants
STATE_BALL_IN_PADDLE = 0
STATE_PLAYING = 1
STATE_WON = 2
STATE_GAME_OVER = 3
class Bricka:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("bricka (a breakout clone by codeNtronix.com)")
self.clock = pygame.time.Clock()
if pygame.font:
self.font = pygame.font.Font(None,30)
else:
self.font = None
self.init_game()
def init_game(self):
self.lives = 3
self.score = 0
self.state = STATE_BALL_IN_PADDLE
self.paddle = pygame.Rect(300,PADDLE_Y,PADDLE_WIDTH,PADDLE_HEIGHT)
self.ball = pygame.Rect(300,PADDLE_Y - BALL_DIAMETER,BALL_DIAMETER,BALL_DIAMETER)
self.ball_vel = [5,-5]
self.create_bricks()
def create_bricks(self):
y_ofs = 35
self.bricks = []
for i in range(7):
x_ofs = 35
for j in range(8):
self.bricks.append(pygame.Rect(x_ofs,y_ofs,BRICK_WIDTH,BRICK_HEIGHT))
x_ofs += BRICK_WIDTH + 10
y_ofs += BRICK_HEIGHT + 5
def draw_bricks(self):
for brick in self.bricks:
pygame.draw.rect(self.screen, BRICK_COLOR, brick)
def check_input(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.paddle.left -= 5
if self.paddle.left < 0:
self.paddle.left = 0
if keys[pygame.K_RIGHT]:
self.paddle.left += 5
if self.paddle.left > MAX_PADDLE_X:
self.paddle.left = MAX_PADDLE_X
if keys[pygame.K_SPACE] and self.state == STATE_BALL_IN_PADDLE:
self.ball_vel = [5,-5]
self.state = STATE_PLAYING
elif keys[pygame.K_RETURN] and (self.state == STATE_GAME_OVER or self.state == STATE_WON):
self.init_game()
def move_ball(self):
self.ball.left += self.ball_vel[0]
self.ball.top += self.ball_vel[1]
if self.ball.left <= 0:
self.ball.left = 0
self.ball_vel[0] = -self.ball_vel[0]
elif self.ball.left >= MAX_BALL_X:
self.ball.left = MAX_BALL_X
self.ball_vel[0] = -self.ball_vel[0]
if self.ball.top < 0:
self.ball.top = 0
self.ball_vel[1] = -self.ball_vel[1]
elif self.ball.top >= MAX_BALL_Y:
self.ball.top = MAX_BALL_Y
self.ball_vel[1] = -self.ball_vel[1]
def handle_collisions(self):
for brick in self.bricks:
if self.ball.colliderect(brick):
self.score += 3
self.ball_vel[1] = -self.ball_vel[1]
self.bricks.remove(brick)
break
if len(self.bricks) == 0:
self.state = STATE_WON
if self.ball.colliderect(self.paddle):
self.ball.top = PADDLE_Y - BALL_DIAMETER
self.ball_vel[1] = -self.ball_vel[1]
elif self.ball.top > self.paddle.top:
self.lives -= 1
if self.lives > 0:
self.state = STATE_BALL_IN_PADDLE
else:
self.state = STATE_GAME_OVER
def show_stats(self):
if self.font:
font_surface = self.font.render("SCORE: " + str(self.score) + " LIVES: " + str(self.lives), False, WHITE)
self.screen.blit(font_surface, (205,5))
def show_message(self,message):
if self.font:
size = self.font.size(message)
font_surface = self.font.render(message,False, WHITE)
x = (SCREEN_SIZE[0] - size[0]) / 2
y = (SCREEN_SIZE[1] - size[1]) / 2
self.screen.blit(font_surface, (x,y))
def run(self):
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit
self.clock.tick(50)
self.screen.fill(BLACK)
self.check_input()
if self.state == STATE_PLAYING:
self.move_ball()
self.handle_collisions()
elif self.state == STATE_BALL_IN_PADDLE:
self.ball.left = self.paddle.left + self.paddle.width / 2
self.ball.top = self.paddle.top - self.ball.height
self.show_message("PRESS SPACE TO LAUNCH THE BALL")
elif self.state == STATE_GAME_OVER:
self.show_message("GAME OVER. PRESS ENTER TO PLAY AGAIN")
elif self.state == STATE_WON:
self.show_message("YOU WON! PRESS ENTER TO PLAY AGAIN")
self.draw_bricks()
# Draw paddle
pygame.draw.rect(self.screen, BLUE, self.paddle)
# Draw ball
pygame.draw.circle(self.screen, WHITE, (self.ball.left + BALL_RADIUS, self.ball.top + BALL_RADIUS), BALL_RADIUS)
self.show_stats()
pygame.display.flip()
if __name__ == "__main__":
Bricka().run()
```
I will accept the answer with the highest number of votes in exactly one week. Extra extra points if anyone can make a version in half an hour :)
**Update** The answer are great but... surely there are more people who want to show off their favourite language to play breakout! Come on **python/perl/Haskell/crazy language** experts :)
**Winners** And the winner is.. Ray. However, extra extra points go to... Schmiddty for completing the task in under 30 minutes! I would still love to see implementations in other languages however.
[Answer]
# Python 3 with Pygame and PIL / many hours
After playing other answers, that has simple level config, an idea came to me: The level can be initialized be an image.
So I make this one. To play it, you draw an image that contains many **convex** polygons, like this:
[image example http://imgbin.org/images/11634.png](http://imgbin.org/images/11634.png)
The black color will be parsed as walls and the lowest block will be the player.
Save it as `break-windows.png` and then run with command:
```
python3 brcki.py break-windows.png
```
Another feature is that the collision detection is very precise. I use binary-search to do it. When two objects collide, time goes back until nothing collide so that the
exact collide time and point will be detected. With this tecnique, the ball can go very fast while
the bounce effect is still realistic.
Here is `brcki.py`. I know it's a bit too long to be a golf. But isn't that insteresting playing on your own image?
```
import pygame as pg
import itertools
import Image
from random import randint
from math import pi,sin,cos,atan2
norm = lambda c:c/abs(c)
times = lambda c,d:(c*d.conjugate()).real
cross = lambda c,d:(c*d.conjugate()).imag
class Poly:
def __init__(self, ps, c, color=0):
assert isinstance(c, complex)
for p in ps:
assert isinstance(p, complex)
self.c = c
self.ps = ps
self.boundR = max(abs(p) for p in ps)
self.ns = [norm(ps[i]-ps[i-1])*1j for i in range(len(ps))]
self.color = color
class Ball(Poly):
def __init__(self, r, c, v):
n = int(1.5*r)
d = 2*pi/n
ps = [r * (cos(i*d)+sin(i*d)*1j) for i in range(n)]
super().__init__(ps, c)
self.v = v
self.r = r
self.color = ColorBall
class Player(Poly):
def __init__(self, ps, c, color=0):
super().__init__(ps, c, color)
self.v = 0+0j
pg.display.init()
W, H = 600, 700
ColorBG = pg.Color(0xffffffff)
ColorBall = pg.Color(0x615ea6ff)
ColorBrick = pg.Color(0x555566ff)
FPS = 40
BallR, BallV = 15, 120+640j
PlayerV = 300
Bc, Bi, Bj = W/2+H*1j, 1+0j, -1j
def phy2scr(p):
p = Bc + p.real * Bi + p.imag * Bj
return round(p.real), round(p.imag)
def hittest(dt, b, plr, Ps)->'(dt, P) or None':
t0, t1, t2 = 0, dt, dt
moveon(dt, b, plr)
if not existhit(b, Ps): return None
while t1 - t0 > 1e-2:
t3 = (t0 + t1)/2
moveon(t3 - t2, b, plr)
if existhit(b, Ps): t1 = t3
else: t0 = t3
t2 = t3
moveon(t1 - t2, b, plr)
P = next(P for P in Ps if collide(b, P))
moveon(t0 - t1, b, plr)
assert not existhit(b, Ps)
return (t1, P)
def existhit(b, Ps)->'bool':
return any(collide(b, P) for P in Ps)
def inside(p, P)->'bool':
return all(times(p-q-P.c, n)>=0 for q,n in zip(P.ps,P.ns))
def collide(P1, P2)->'bool':
if abs(P1.c - P2.c) > P1.boundR + P2.boundR + 1:
return False
return any(inside(P1.c + p, P2) for p in P1.ps) \
or any(inside(P2.c + p, P1) for p in P2.ps)
def moveon(dt, *ps):
for p in ps:
p.c += p.v * dt
def hithandle(b, P):
hp, n = hitwhere(b, P)
b.v -= 2 * n * times(b.v, n)
def hitwhere(b, P)->'(hitpoint, norm)':
c = P.c
for p in P.ps:
if abs(b.c - p - c) < b.r + 1e-1:
return (p+c, norm(b.c - p - c))
minD = 100
for p, n in zip(P.ps, P.ns):
d = abs(times(b.c - p - c, -n) - b.r)
if d < minD:
minD, minN = d, n
n = minN
return (b.c + n * b.r, -n)
def draw(sur, P):
pg.draw.polygon(sur, P.color, [phy2scr(p + P.c) for p in P.ps])
def flood_fill(img, bgcolor):
dat = img.load()
w, h = img.size
mark = set()
blocks = []
for x0 in range(w):
for y0 in range(h):
if (x0, y0) in mark: continue
color = dat[x0, y0]
if color == bgcolor: continue
mark.add((x0, y0))
stk = [(x0, y0)]
block = []
while stk:
x, y = stk.pop()
for p1 in ((x-1,y),(x,y-1),(x+1,y), (x,y+1)):
x1, y1 = p1
if x1 < 0 or x1 >= w or y1 < 0 or y1 >= h: continue
if dat[p1] == color and p1 not in mark:
mark.add(p1)
block.append(p1)
stk.append(p1)
block1 = []
vis = set(block)
for x, y in block:
neig = sum(1 for p1 in ((x-1,y),(x,y-1),(x+1,y), (x,y+1)) if p1 in vis)
if neig < 4: block1.append((x, y))
if len(block1) >= 4: blocks.append((dat[x0, y0], block1))
return blocks
def place_ball(b, plr):
c = plr.c
hl, hr = 0+0j, 0+300j
# assume:
# when b.c = c + hl, the ball overlaps player
# when b.c = c + hr, the ball do not overlaps player
while abs(hr - hl) > 1:
hm = (hl + hr) / 2
b.c = c + hm
if collide(b, plr): hl = hm
else: hr = hm
b.c = c + hr
def pixels2convex(pixels):
"""
convert a list of pixels into a convex polygon using Gramham Scan.
"""
c = pixels[0]
for p in pixels:
if c[1] > p[1]:
c = p
ts = [(atan2(p[1]-c[1], p[0]-c[0]), p) for p in pixels]
ts.sort()
stk = []
for x, y in ts:
while len(stk) >= 2:
y2, y1 = complex(*stk[-1]), complex(*stk[-2])
if cross(y1 - y2, complex(*y) - y1) > 0:
break
stk.pop()
stk.append(y)
if len(stk) < 3: return None
stk.reverse()
return stk
def img2data(path) -> "(ball, player, brckis, walls)":
"""
Extract polygons from the image in path.
The lowest(with largest y value in image) polygon will be
the player. All polygon will be converted into convex.
"""
ColorWall = (0, 0, 0)
ColorBG = (255, 255, 255)
print('Start parsing image...')
img = Image.open(path)
w, h = img.size
blocks = flood_fill(img, ColorBG)
brckis = []
walls = []
player = None
def convert(x, y):
return x * W / float(w) - W/2 + (H - y * H / float(h))*1j
for color, block in blocks:
conv = []
conv = pixels2convex(block)
if conv is None: continue
conv = [convert(x, y) for x, y in conv]
center = sum(conv) / len(conv)
p = Poly([c-center for c in conv], center, color)
if color == ColorWall:
walls.append(p)
else:
brckis.append(p)
if player is None or player.c.imag > center.imag:
player = p
ball = Ball(BallR, player.c, BallV)
print('Parsed image:\n {0} polygons,\n {1} vertices.'.format(
len(walls) + len(brckis),
sum(len(P.ps) for P in itertools.chain(brckis, walls))))
print('Ball: {0} vertices, radius={1}'.format(len(ball.ps), ball.r))
brckis.remove(player)
player = Player(player.ps, player.c, player.color)
place_ball(ball, player)
return ball, player, brckis, walls
def play(config):
scr = pg.display.set_mode((W, H), 0, 32)
quit = False
tm = pg.time.Clock()
ball, player, brckis, walls = config
polys = walls + brckis + [player]
inputD = None
while not quit:
dt = 1. / FPS
for e in pg.event.get():
if e.type == pg.KEYDOWN:
inputD = {pg.K_LEFT:-1, pg.K_RIGHT:1}.get(e.key, inputD)
elif e.type == pg.KEYUP:
inputD = 0
elif e.type == pg.QUIT:
quit = True
if inputD is not None:
player.v = PlayerV * inputD + 0j
while dt > 0:
r = hittest(dt, ball, player, polys)
if not r: break
ddt, P = r
dt -= ddt
hithandle(ball, P)
if P in brckis:
polys.remove(P)
brckis.remove(P)
if ball.c.imag < 0: print('game over');quit = True
if not brckis: print('you win');quit = True
scr.fill(ColorBG)
for p in itertools.chain(walls, brckis, [player, ball]):
draw(scr, p)
pg.display.flip()
tm.tick(FPS)
if __name__ == '__main__':
import sys
play(img2data(sys.argv[1]))
```
[Answer]
# Javascript/KineticJS
Here's a "working" version in 28 minutes, but it's not exactly playable (the collision logic is too slow). <http://jsfiddle.net/ukva5/5/>
```
(function (con, wid, hei, brk) {
var stage = new Kinetic.Stage({
container: con,
width: wid,
height: hei
}),
bricks = new Kinetic.Layer(),
brks = brk.bricks,
bX = wid / 2 - brk.width * brks[0].length / 2,
bY = brk.height,
mov = new Kinetic.Layer(),
ball = new Kinetic.Circle({
x: wid / 4,
y: hei / 2,
radius: 10,
fill: 'black'
}),
paddle = new Kinetic.Rect({
x:wid/2-30,
y:hei*9/10,
width:60,
height:10,
fill:'black'
}),
left = false,
right = false;
mov.add(ball);
mov.add(paddle);
stage.add(mov);
paddle.velocity = 5;
ball.angle = Math.PI/4;
ball.velocity = 3;
ball.bottom = function(){
var x = ball.getX();
var y = ball.getY();
return {x:x, y:y+ball.getRadius()};
};
ball.top = function(){
var x = ball.getX();
var y = ball.getY();
return {x:x, y:y-ball.getRadius()};
};
ball.left = function(){
var x = ball.getX();
var y = ball.getY();
return {x:x-ball.getRadius(), y:y};
};
ball.right = function(){
var x = ball.getX();
var y = ball.getY();
return {x:x+ball.getRadius(), y:y};
};
ball.update = function(){
ball.setX(ball.getX() + Math.cos(ball.angle)*ball.velocity);
ball.setY(ball.getY() + Math.sin(ball.angle)*ball.velocity);
};
paddle.update = function(){
var x = paddle.getX();
if (left) x-=paddle.velocity;
if (right) x+= paddle.velocity;
paddle.setX(x);
};
for (var i = 0; i < brks.length; i++) {
for (var j = 0; j < brks[i].length; j++) {
if (brks[i][j]) {
bricks.add(new Kinetic.Rect({
x: bX + j * brk.width + .5,
y: bY + i * brk.height + .5,
width: brk.width,
height: brk.height,
stroke: 'black',
strokeWidth: 1,
fill: 'gold'
}));
}
}
}
stage.add(bricks);
$(window).keydown(function(e){
switch(e.keyCode){
case 37:
left = true;
break;
case 39:
right = true;
break;
}
}).keyup(function(e){
switch(e.keyCode){
case 37:
left = false;
break;
case 39:
right = false;
break;
}
});
(function loop(){
ball.update();
paddle.update();
if (paddle.intersects(ball.bottom())){
ball.setY(paddle.getY()-ball.getRadius());
ball.angle = -ball.angle;
}
if (ball.right().x > wid){
ball.setX(wid - ball.getRadius());
ball.angle = Math.PI - ball.angle;
}
if (ball.left().x < 0){
ball.setX(ball.getRadius());
ball.angle = Math.PI - ball.angle;
}
if (ball.top().y < 0){
ball.setY(ball.getRadius());
ball.angle = -ball.angle;
}
for(var i = bricks.children.length; i--;){
var b = bricks.children[i];
if (b.intersects(ball.top()) || b.intersects(ball.bottom())){
ball.angle = -ball.angle;
b.destroy();
}
else if (b.intersects(ball.left()) || b.intersects(ball.right())){
ball.angle = Math.PI-ball.angle;
b.destroy();
}
}
stage.draw();
webkitRequestAnimationFrame(loop);
})()
})('b', 640, 480, {
width: 80,
height: 20,
bricks: [
[1, 1, 1, 1, 1, 1],
[1, 1, 0, 0, 1, 1],
[1, 1, 1, 1, 1, 1]
]
});
```
I'll work on making the game snappier now. :)
**Note:** Works only in webkit browsers right now. I'll add a shim so it will work in any HTML5 ready browser eventually.
**Updates:**
1. <http://jsfiddle.net/ukva5/6/> more playable
2. <http://jsfiddle.net/ukva5/7/> random bricks, faster ball
3. <http://jsfiddle.net/ukva5/8/> random brick health
4. <http://jsfiddle.net/ukva5/12/show/light/> stopping point for the day.
[Answer]
# [Processing](http://processing.org/), 400 characters
Didn't manage to do it in 30min, but here's a surf'd version. The ball is square and if you press any other key than left/right it jumps fully right, but it was shorter and the spec didn't say anything against it ;).
```
int x,y=999,u,v,p=300,q=580,i,l,t;long g;void setup(){size(720,600);}void draw(){background(0);if(keyPressed)p=min(max(p+8*(keyCode&2)-8,0),630);rect(p,q,90,20);for(i=0;i<64;i++)if((g>>i&1)<1){l=i%8*90;t=i/8*20+40;if(x+20>l&&x<l+90&&y+20>t&&y<t+20){v=-v;g|=1l<<i;}rect(l,t,90,20);}if(x+20>p&&x<p+90&&y+20>q)v=-abs(v);if(y<0)v=-v;if(x<0||x>700)u=-u;if(y>600){x=y=400;u=v=3;}x+=u;y+=v;rect(x,y,20,20);}
```
With proper names & some whitespace for clarity, that's:
```
int ballX, ballY=999, speedX, speedY, paddleX=300, paddleY=580;
long bricks;
void setup() {
size(720, 600);
}
void draw() {
background(0);
if(keyPressed) paddleX = min(max(paddleX+8*(keyCode^37)-8,0),630);
rect(paddleX, paddleY, 90, 20);
for(int i=0; i<64; i++) {
if((bricks>>i&1)<1) {
int brickX=i%8*90, brickY=i/8*20+40;
if(ballX+20>brickX && ballX<brickX+90 && ballY+20>brickY && ballY<brickY+20) {
speedY = -speedY;
bricks |= 1l<<i;
}
rect(brickX, brickY, 90, 20);
}
}
if(ballX+20>paddleX && ballX<paddleX+90 && ballY+20>paddleY) speedY = -abs(speedY);
if(ballY<0) speedY = -speedY;
if(ballX<0 || ballX>700) speedX = -speedX;
if(ballY>600) {
ballX = ballY = 400;
speedX = speedY = 3;
}
ballX += speedX; ballY += speedY;
rect(ballX, ballY, 20, 20);
}
```
[Answer]
## [Elm](http://elm-lang.org), 1 hour 44 minutes
I tried to do it in half an hour, but overshot a little. To try to save time, I used circles for everything (paddle, ball, bricks). This avoided the many cases needed to implement circle/rectangle collision, but required some vector math to compute the resulting direction.
To run, go to <http://elm-lang.org/edit/>, paste the code into the editor, and click the "In Tab" button at the bottom.
```
import Keyboard
brickR = 30
ballR = 10
paddleY = 450
paddleR = 50
-- Initial (center) position of each brick
brickLayout = [(150,50), (250, 50), (350, 50), (450, 50),
(100,100), (200,100), (300,100), (400,100), (500,100)]
brickForm = filled blue . circle brickR
-- Return True if the brick coordinate collides with the ball coordinate
brickVsBall brickPos ballPos =
distance brickPos ballPos <= brickR + ballR
addVec (ax,ay) (bx,by) = (ax+bx, ay+by)
subVec (ax,ay) (bx,by) = (ax-bx, ay-by)
dot (ax,ay) (bx,by) = ax*bx + ay*by
magsq (x,y) = x*x + y*y
scaleVec s (x,y) = (x*s, y*s)
proj n v = scaleVec (dot v n / magsq n) n
flipV n v = v `subVec` scaleVec 2 (proj n v)
distance a b = sqrt $ magsq $ a `subVec` b
-- Only flip the velocity if headed "toward" the target, where n is a vector
-- pointing from the ball to the target.
bounceV n v =
if v `dot` n > 0
then v `subVec` scaleVec 2 (proj n v)
else v
checkBricks ballPos ballV bricks =
let (smashed, kept) = updateBricks ballPos [] [] bricks
in (updateBallV ballPos ballV smashed, kept)
updateBricks ballPos smashed kept bricks = case bricks of
[] -> (reverse smashed, reverse kept)
(x:xs) ->
if brickVsBall x ballPos
then updateBricks ballPos (x:smashed) kept xs
else updateBricks ballPos smashed (x:kept) xs
updateBallV ballPos ballV smashed = case smashed of
[] -> ballV
(x:xs) -> updateBallV ballPos (bounceV (x `subVec` ballPos) ballV) xs
checkPaddle paddleX ballPos ballV =
let paddlePos = (paddleX,paddleY) in
if distance ballPos paddlePos <= ballR + paddleR
then bounceV (paddlePos `subVec` ballPos) ballV
else ballV
checkWalls r (x,y) =
let checkLeft (vx,vy) = if x-r <= 0 && vx<0 then (0-vx,vy) else (vx,vy)
checkRight (vx,vy) = if x+r >= 600 && vx>0 then (0-vx,vy) else (vx,vy)
checkTop (vx,vy) = if y-r <= 0 && vy<0 then (vx,0-vy) else (vx,vy)
in checkLeft . checkRight . checkTop
-- type Scene = ([BrickPos], BallPos, BallV, PaddleX)
-- BallV is in pixels per frame
initScene = (brickLayout, (300,385), (0, 0-3), 300)
renderScene (bricks, ballPos, ballV, paddleX) =
collage 600 500 $
map brickForm bricks ++
[ filled red $ circle ballR ballPos
, filled black $ circle paddleR (paddleX,paddleY)
]
updateScene (bricks, ballPos, ballV, paddleX) arrows =
let paddleX' = paddleX + arrows.x * 4
(ballV1, bricks') = checkBricks ballPos ballV bricks
ballV2 = checkPaddle paddleX' ballPos ballV1
ballV' = checkWalls ballR ballPos ballV2
in (bricks', ballPos `addVec` ballV', ballV', paddleX')
main =
lift renderScene $
foldp (\(t, arrows) scene -> updateScene scene arrows) initScene $
lift2 (,) (every (second/60)) arrows
```
] |
[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/2618/edit).
Closed 2 years ago.
[Improve this question](/posts/2618/edit)
Inspired by the [Morse code](https://codegolf.stackexchange.com/questions/131/morse-code-translator) question, and the [Twinkle Twinkle little star](https://codegolf.stackexchange.com/questions/272/twinkle-twinkle-little-star) question, write a program to accept a letter and generate the morse code audio for that letter.
[Answer]
## Windows PowerShell, 200
Makes a dot 70 ms long. Accordingly, a dash is 210 ms and the gap between both is 70 ms as well.
```
[char[]](-split' ☺ ☺ ☺ ☺ ☺ ☺ ☺☺ ☺☺☺ ☺ ☺ ☺ ☺☺ ☺ ☺☺☺ ☺☺ ☺☺ ☺ ☺ ☺ ☺ ☺ ☺☺ ☺ ☺ ☺ ☺☺ ☺☺ ')[[char]"$input".ToUpper()-65]|%{[Console]::Beep(880,70+140*$_)
sleep -m 70}
```
Since this contains control characters, here's a hexdump:
```
000: 5B 63 68 61 72 5B 5D 5D │ 28 2D 73 70 6C 69 74 27 [char[]](-split'
010: 00 01 20 01 00 00 00 20 │ 01 00 01 00 20 01 00 00 ☺ ☺ ☺ ☺ ☺
020: 20 00 20 00 00 01 00 20 │ 01 01 00 20 00 00 00 00 ☺ ☺☺
030: 20 00 00 20 00 01 01 01 │ 20 01 00 01 20 00 01 00 ☺☺☺ ☺ ☺ ☺
040: 00 20 01 01 20 01 00 20 │ 01 01 01 20 00 01 01 00 ☺☺ ☺ ☺☺☺ ☺☺
050: 20 01 01 00 01 20 00 01 │ 00 20 00 00 00 20 01 20 ☺☺ ☺ ☺ ☺
060: 00 00 01 20 00 00 00 01 │ 20 00 01 01 20 01 00 00 ☺ ☺ ☺☺ ☺
070: 01 20 01 00 01 01 20 01 │ 01 00 00 27 29 5B 5B 63 ☺ ☺ ☺☺ ☺☺ ')[[c
080: 68 61 72 5D 22 24 69 6E │ 70 75 74 22 2E 54 6F 55 har]"$input".ToU
090: 70 70 65 72 28 29 2D 36 │ 35 5D 7C 25 7B 5B 43 6F pper()-65]|%{[Co
0A0: 6E 73 6F 6C 65 5D 3A 3A │ 42 65 65 70 28 38 38 30 nsole]::Beep(880
0B0: 2C 37 30 2B 31 34 30 2A │ 24 5F 29 0A 73 6C 65 65 ,70+140*$_)◙slee
0C0: 70 20 2D 6D 20 37 30 7D │ p -m 70}
```
I have tried several variants pf packing the data more tightly, but PowerShell is quite verbose in unpacking them again, so I don't gain much, sadly.
[Answer]
## QBASIC (236 characters)
I count each newline as one character because QBasic seems to work fine without carriage returns, at least when running in DOSBox. Note that it only supports letters, not digits or punctuation.
```
INPUT Y$:C&=2^(26-ASC(Y$)MOD 32):A&=31313855AND C&:B&=60257815AND C&:M&=29932103:GOSUB S
IF A&OR B&THEN M&=34172681:GOSUB S
IF A&THEN M&=9538602:GOSUB S
IF A&AND B&THEN M&=66070:GOSUB S
END
S:SOUND 750,SGN(M&AND C&)*2+1:SOUND 0,1:RETURN
```
[Answer]
## JScript .NET (174 characters)
A little-known programming language from Microsoft, it combines the (relative) terseness of JavaScript with the power of the .NET Common Language Runtime. Thanks minitech and Joey for Console.Beep.
This program accepts a single letter from standard input (A-Z or a-z only). It does not explicitly add intra-character pauses, but they do exist, at least on Windows 7.
### morse.js
```
function S(a){K.Beep(750,!!(a&C)*99+50)}import System;var K=Console,C=1<<26-K.Read()%32,A=31313855&C,B=60257815&C;S(29932103);(A||B)&&S(34172681);A&&S(9538602);A&&B&&S(66070)
```
Compile with:
>
> %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\jsc morse.js
>
>
>
### Explanation
Six 32-bit integers, of which 26 bits are used in each, serve as lookup tables. Each bit in a table corresponds to a letter of the alphabet, bit 25 used for A and bit 0 used for Z.
```
C = 1 << (26 - (K.Read() % 32)),
```
Because Morse code is a variable-length code that uses between 1 and 4 symbols for each letter, the tables 31313855 (bit 1) and 60257815 (bit 0) can together represent one less than the length of each letter's code.
```
A = 31313855 & C,
B = 60257815 & C;
```
The program uses additional lookup tables to store the dots and dashes for each letter. Using logic expressions of A and B, it stops once it has sent the correct number of symbols to the sound card.
```
S(29932103);
(A || B) && S(34172681);
A && S(9538602);
A && B && S(66070);
```
In each of the four lookup tables above, a zero represents a dot; a one represents a dash. `!!` (logical "not-not") is used to normalize false to 0 and true to 1 (to compensate for the differing locations of bits within the integer). The multiplication and addition of this value causes a dot to be a 50 ms, 750 Hz tone and a dash to be a (50 + 99) = 149 ms tone.
```
function S(a) {
K.Beep(750, !!(a & C) * 99 + 50)
}
```
[Answer]
Sure.
# VB.NET, ~~235~~ ~~223~~ ~~221~~ ~~218~~ ~~210~~ ~~209~~ ~~208~~ 209 characters
With the appropriate structures, it is **245 characters**.
Requires Option Strict to be Off for the latest one.
```
For Each c In"sl lsss lsls lss s ssls lls ssss ss slll lsl slss ll ls lll slls llsl sls sss l ssl sssl sll lssl lsll llss".Split()(Asc(UCase(Console.ReadKey.KeyChar))-65)
Console.Beep(1E3,200-(c="l")*400)
Next
```
Recent edits:
* Fixed the incorrect "b".
* Changed `999` to `1E3` so I can finally have that perfect thousand ;-)
* Used boolean->integer conversion to save 2 characters.
[Answer]
# Powershell, ~~184~~ 120 bytes
```
for($d='0;?3,>5:.H7<1/9@E42-6B8CG='[$args[0][0]-65]-42;$d-1){[Console]::Beep(880,200*($d%2*3+1))
$d=$d-shr1
sleep -m 70}
```
Test script:
```
$f = {
for($d='0;?3,>5:.H7<1/9@E42-6B8CG='[$args[0][0]-65]-42;$d-1){[Console]::Beep(880,200*(($d%2)*3+1))
$d=$d-shr1
sleep -m 70}
}
&$f "A"
sleep -m 700
&$f "B"
```
I used a [timing setup](https://en.wikipedia.org/wiki/Morse_code#Representation,_timing,_and_speeds) for beginers:
* the `dot duration` is 200ms
* the `gap between elements` is less then `dot duration` (70 ms)
* the `dash duration` is 4 `dot durations`
] |
[Question]
[
**This is the robbers' challenge. To post a cop, go [here](https://codegolf.stackexchange.com/questions/241947/inject-arbitrary-code-into-a-compiler-cops).**
In this challenge, cops will invent a (likely simple) programming language, and write an interpreter, transpiler, or compiler that allows you to run it. Robbers will write a program in this language that manages to inject arbitrary code into the interpreter, transpiler, or compiler.
## Cops
Cops should design a language. This language should be "pure"; its programs can take input and/or produce output, but cannot affect files, make network requests, behave non-deterministically (based on something like randomness or the system time), or otherwise impact or be impacted by the outside world (within reason).
Cops must then implement this language, with one of:
* **An interpreter:** This will take the code and input as arguments/input, and produce the programs's output as output.
* **A transpiler:** This will take the code and input, and produce code in some other language which does the same task. When run using that language's interpreter/compiler with input, the correct output is produced.
* **A compiler:** Similar to a transpiler, but with machine code instead of another language.
There must be an intended "crack", or way to inject arbitrary code.
## Robbers
Robbers should find a way to do one of the following:
* Write a program that, when interpreted, transpiled, or compiled, can run arbitrary code as the interpreter/transpiler/compiler (e.g., if written in Python, you could run arbitrary Python, manipulate files, and so on)
* Write a program that, when transpiled or compiled, injects arbitrary code into the resulting program/machine code (e.g., if your transpiler converts the language to Node.js, you could inject arbitrary JS into the transpiler output)
## Robber Posts
Robbers should include code which can be given to the cop, which allows injecting arbitrary code. For example:
>
> # Cracks Print1Lang
>
>
>
> ```
>
>
> eval("...") # arbitrary Python, with 1s replaced with \x31
> ```
>
> This exploits the fact that `.` in regexes does not match newlines.
>
>
>
This exploit should allow injecting **any** code, in some language or situation that allows performing arbitrary computations and interacting with the computer's files, running shell commands, system calls, or anything like that. Simply printing a nondeterministic value does not count, as it does not give you unrestricted access to the environment the code or transpilation/compilation output is being run or transpiled/compiled in.
For an interpreter, this is likely going to be running code in the language the interpreter is written in. For a transpiler or compiler, the vulnerability can occur at either compile time or run time, and for the latter, the vulnerability would most likely consist of being able to inject arbitrary code or machine code into the compiled code.
## Other
All the boring stuff. Nothing malicious, no crypto stuff.
Winner for cops is the user with the most safe cops, winner for robbers is the user who cracks the most cops.
[Answer]
# Cracks [Javastack](https://codegolf.stackexchange.com/a/241958/44718)
```
0);
<!-- place your code here
console.log(`42`)
//
```
[Answer]
# Cracks [Vyxal 2.10](https://codegolf.stackexchange.com/a/246350/107299)
```
`f"{print(1)}"`∆i
```
Prints `1` then errors. Sadly does not work online, but does offline. Exploits the fact that `∆i` uses sympy, similar to [this](https://codegolf.stackexchange.com/a/241951/107299). Injected code is everything between the `{` and `}`.
[Answer]
# Cracks [Exceptionally](https://codegolf.stackexchange.com/a/242066/100664)
```
{exec
\"wrap"
}FUNCS
{"print(5)"
\0
```
Your code can go where the `print(5)` is.
So, all variables are accessible by the program, so we can load `exec` into the register, but we can't easily execute it. We'd have to load it into `FUNCS`, but `FUNCS` needs to be something that can be indexed into...
We can make it an array! By using the builtin `\"wrap"` on `exec` we can load that into `FUNCS` and execute it with `\0`. The line before that stores our code to the register so it gets run.
[Answer]
# Cracks [Jyxal](https://codegolf.stackexchange.com/a/241988/79857)
```
@=0,this["FUNC_"+arity]={},eval("console.log(\"pwned\")"),FUNC_x|;
```
This creates a function with the name...well, everything between `@` and `|;`. Normally, if the function name was something reasonable and the code looked like `@xyz|;`, the transpiled output would look like this:
```
var arity = 'xyz';FUNC_xyz = (stack) => {return pop(stack)}; this['FUNC_' + arity.split(':')[0]].arity = arity;
```
So, with my crack, it looks like this:
```
var arity = '=0,this["FUNC_"+arity]={},eval("console.log(\"pwned\")"),FUNC_x';FUNC_=0,this["FUNC_"+arity]={},eval("console.log(\"pwned\")"),FUNC_x = (stack) => {return pop(stack)}; this['FUNC_' + arity.split(':')[0]].arity = arity;
```
As you can see, it sets `FUNC_` to `0`, sets `this["FUNC_"+arity]` to `{}` (to avoid a syntax error later, you could also just use `//` at the end), and then `eval`s basically arbitrary code. You can't include some characters, but you can just use `\x` to insert them in the eval'd string.
[Answer]
# Cracks [Exceptionally v0.2](https://codegolf.stackexchange.com/a/242127/100664)
```
<"\"?\")) or exit('GET ACE LOL')#"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lZbNcts2EMfv7EsgUDUiZVmxp5cOp6rrceRMOv6ayD1RTAYWIQktCTAgaNHj6klySQ-dHvsCfZH2abogSImgZE_MAwUCP-wu_rsA9Pmv1fJBLQX_8t83f7MkFVIhSZ2qlT1kjnN2fXl5evVmgkbo0UHw4EfsIyzpAvkj1M3wANlPB10IEhl0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mIAt2CJfIYKkqXQ3SuxK8aJg2-VZpUZsHA4QnIAkj1WGlNB3OxzdVD4XH-4B1RKxMVweyts0aPHLrm0CPLy7H2KimODauovhyK4rPqiqMkTdrY8DhPeZ2HN6NEw_s2X3nQLjIqUzRaN6WwzQHP4NRf7O0SypyiVHO7d8dycop3HBS7h7_szV_PD7f-FP0BSfTLHn6c1CC_hf1Xs7vkWnZ2N0cX3R8zoV-Y--r2hBZ-72vqosep5BvvzxnWn8Dw)
Yeet your code where the `exit('GET ACE LOL')` is. Will print some junk first.
This gets transpiled into:
```
(print("\")) ? (reg := program.FUNCS[")) or exit('GET ACE LOL')#"](reg))
```
Exceptionally doesn't escape backslashes in strings, so it parses it as two seperate statements combined by the `?` operator. However, the second `"` is escaped and the string won't end until reaching another `"`. We include some code to close the parentheses opened by the `print` and a comment at the end to throw away the rest, then whatever goes in the middle is arbitrary code.
] |
[Question]
[
# Background
Consider an \$n\times n\$ grid, where each cell is either empty (denoted by `.`) or a wall (denoted by `#`). We say that two cells are *adjacent* if they share an edge (a corner is not enough). A *path* is a sequence of distinct empty cells \$s\_0,s\_1,\ldots,s\_k\$ such that cells \$s\_i\$ and \$s\_{i+1}\$ are adjacent for \$0\le i<k\$.
We say that a grid is a *maze* if the following conditions hold.
1. There is at most one path between any two empty cells.
2. The following two \$2\times 2\$ patterns do not occur anywhere in the grid.
```
#. .#
.# #.
```
A maze is **not** required to be connected (i.e. it is allowed to have two empty cells without any paths between them).
Here are a few examples of mazes.
```
.### #... ....
.### ###. #.##
.#.. ..#. #.##
.### #... ....
```
Here are a few examples of grids which are **not** mazes.
```
.... ##.# Do not satisfy rule 1.
#.#. #..#
#... #..#
##.# #.##
```
```
##.. ##.# Do not satisfy rule 2.
..#. ##.#
#.#. .#.#
#... #..#
```
# Challenge
[Here](https://gist.githubusercontent.com/Delfad0r/505bb7d5bff2a9fecc55ba349be861b4/raw/4a2be7566079c662ed68f8d6ac521099b2b72f67/maze.txt) is a \$128\times 128\$ maze. It has \$991\$ empty cells and \$15393\$ walls. Your task is to tear down as many walls as possible, making sure that the grid you obtain is still a maze.
More formally, let \$M\$ be the maze given above. A submission to this challenge consists of a \$128\times 128\$ maze \$M'\$ such that every empty cell in \$M\$ is also empty in \$M'\$.
## Scoring
This is [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"): the more walls you manage to tear down, the better.
Your score will be equal to the number of walls (`#`) in the maze you submit. Lower score is better.
## Notes
* The maze \$M\$ given above doesn't have any special properties, to the best of my knowledge. It was generated as randomly as possible, fixing the average density of empty cells.
* [Here](https://tio.run/##tVxbb6NGFH7O/IrZ@AGsZT8l7Uu1qvu2@1qp2j5UllVRm8Tj2oAAb@KN8tvTATu2gbmcGShSYhtmzpw5l@9cwM4P1TpLf34rxY9kdv/TLywrxKNI4@3fu1ieCYJg4njAe0TrPN4/seuLUMwH1O87I2FYHooz53PMSANKlgj7B1k2zFPOSpHQJ16G2hiAl76heVV8ZHbbwSimqZmENgO4ZlklXoNJ6pkyjesyoGFzJAdVTWE@pjbAVtAyjCMDUJHwUqq7F@m9ACOsQ8IkRiAH41IAkSV0bPjMgEL2miXhaACALxD52AFsqKSGJaZbEoptQDuIGBAUImRt3jCOfYMuKzYZ8YCLIZzOMx/XMdClCb9rA2a4BYlcfxSgI92KhhgAIupgASebYV3e0fIbKNM0j6ihHcI89my4CiOUQheOYche7IvhfQHYMbOvtW5WDHdRg65yqKMhSHmd1vrIqoDKStiwJJcataEdzqzEVTAA0xk0n0DjEgx@Dob6cAQ9PRKqARQEFIav10KnAgxIi3UhvQMD6EgAZFilpV2OMZP1bUYvW1AqUEclsE6m3icOUhVICdqgpOUYIE33y10GoM8vMFTiWjdErxNBX2hYCgmfnLBjMPDGH2tG5LgxexcH1gaFprSgS5mEWKpo2Gs8OERzP/WDFg19gBdOeY2RAfjjsVPaxHTbcC5GnLNbHzcE0bkdMIMBTqEdlh1ZWgXwalIRWyUugtepAJrNAqZ0EAP46TPwP/UEodYgLnUBFL4Ao3o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/37@/kq/xwPif/LaYtAuKBP8s15kFt6EEU1NYQLNqL1EeRVPsi5cFKxI9ZGm@3Bx6vNvEySSue7PLqwJfJdlsGzcTvohRVsprN51/jbZmodjJdKLY/XTTTa3mtHspQRJsoF1G@udq05DdOD@Fc/HoXbeSf@G1Wz4w2x9dFRz4ntr8V@@SaxElWs1kwCUgTTjs6TlPOaHZ6vtAaP2tRq/f9HB3qnf8QeTi/i@6ju@iT1NL8@Ca66@5CMhAeBfFhFoqPz9Hm42Eq5bDiaVYdRXU8GUmRTbXKa7PY3alKH0Zj7DN5ESuCM3stUbSZlvqV2@0Z9bW97fbbSuTbhOdxtT6Z1zXnbDebL5ia95uqOMj/NzvEeZ6kq1Ck@V465JTdJM/LJK/4l9@/fimKrKhH5XFZshu5i22SSh@dzUR9toiFNOAvzXCRpeFD8G2d8MdCrPg6LvmLeOVF9lTKtcsqiVc8e@Av9fKvwfRCTO5daq4@rSb5R/bUUKopygmP1Zq/nCe@amnXjvDcSFOk0nGDo2nVYmgmqtf6M02e82QpNSIxKS5i@a5oJHfkoSat1vWNXDIMW7@zckGc@lWKLAwaDAmmzXiN8Gqg4Nl5xYgvs@1@l/KXzSvf7cuK/5McIUXyctTgSW/Mpo1dViS8WsfpSU6NaiSVvrYbZRdJOWvhMpNClSc/NA772bicKBvBx7ye2gi@Wtev2232JNJHSSYus/Qzv32RBF9vJRN5IdIqbCg0cySF7/FWrOSlcikZPyP5bopltq/HTs7THoK/sn3Bm4H1zJfm3SsPD9meV/XJVfYkt317e6TRUtM7vdvJ7ZR/4qepTxLEy2kwfXv7Dw "Python 3 – Try It Online") is a python script that checks whether your submission is valid and tells you your score (just paste the maze in the "Input" section)
[Answer]
# Score: ~~8066~~ 8065 walls
I found an 8066 wall solution using dynamic programming over solutions that can be recursively decomposed by splitting on a row or column consisting entirely of floors or entirely of walls. The implementation of this apparently simple idea was rather more complicated than its description, since there are 17 different types of subproblems depending on the borders and the connectivity between them.
I then removed one wall by hand-editing seven cells in rows 119–122, columns 60–63.
This is an **optimal** solution. Proof:
Add a one-cell border using \$516\$ extra walls. Consider the planar graph whose vertices are the \$w\$ centers of walls, and whose edges are the \$a\$ wall-wall adjacencies. This graph is connected (because any component of walls not connected to the border would be encircled by a forbidden cycle of floors), and has \$f \ge 2\$ faces (at least an inside and outside). By Euler’s formula, \$w - a + f = 2\$, so \$w - a \le 0\$.
Now consider the different planar graph whose vertices are the \$131^2\$ corner points of walls, and whose edges are the \$4w - a\$ sides of walls. None of these \$131^2\$ vertices are missing (because an isolated one would again be encircled by a forbidden cycle of floors). This graph is again connected and has \$f' \ge w + 2\$ faces. By Euler’s formula, \$131^2 - (4w - a) + f' = 2\$, so \$131^2 - 3w + a \le 0\$.
Adding these two inequalities gives \$131^2 - 2w \le 0\$, so \$w \ge \frac{131^2}{2} = 8064.5 + 516\$.
[Validate](https://tio.run/##zV1Lcxu5ET4bv2LWOJCs5X5lJ5fUVpTb7jVVqc0hpVKlGImyRqFIFkmtpbj8250ZPmbQQDfQwIzXpiyRnAcG@NDvbsDb18PDZv3nL/v6f8ur93/6i9ns6g/1erH699OiOTKZTGzmC8VXkOO4fDPuSTD3A/xn70pEHg/mSHfMRNsA2yXF@KHGxhTizEKiv7G/NNUBFM03hHfmq0nTDkYhTeEm0A7A7TIHb4Qk5U7FrvM7IHRzJAblbjElpDaAVkAI49QBcE0UTWo@F8lcgBGeo5JJRtEcoo8ClF2CR8NdBxjshUcikwCAUkFUQgdISSVeLBnpkWCGAfEipUJgIDS0bxiHvqHHytgRX8ghhPNxU8I6kXZ14Ps0EBe3UDUXXgVITRNtiAFChFcWyKIZ4/cdhG/AmmkFWkO8xBSMOXIWUVEKSR0jYr2kH4bLA5CWmeGs@VYx8qGGfsrBa0Oo7DqR@tRTAY5KzDAjV6u1IV5uko1zYgCxIzh@g66XMChjMLSvTKEnS0JegEIhhVHKtZCmAAPMYkmle2IAHgJQi1Wd2ZWpM01IMzK20HigmZNgPEs9bBwqL1CjtKExyzEAzfzTfgcg2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StzKQBmK9jFTsIWBGBYHUTu2ikbKscikCKBvxcGdhCzyEIsFoMHjewrgTKdnYzftELk6K0TCkPa7LovQV/6XfClgETkIzVS@S8/g8 "Python 3 – Try It Online")
```
.#.#.#.#...#...#.#..#..#.#.#.#...#.#.#.#.#.#.#.#................................................................................
.#.#.#.##.##.###...##.##.#.#.###.....#.#.#.#...#.##########.###########.########.##################.#################.#.#.#.#.#.
.#.#.#.#...#...#.#..#..#.#.#...#.##.##.#.#.#.###...#.#.#.#..#.#.#.#.#.###.#.#..#.#.#.#.#.#.#.#.#.#..#.#.#.#..#.#.#.#..##########
.#.#.#.##.###.##.####.##.#.#.###.#...#.#.#.#.#...###.#.#.####.....#.#.#.#.#.##.###.#.#.#.#.#.#.#.####.#.#.#.##.#.#.####.#.#.#.#.
.#.#.#.#...#...#....#..#.#.#.#...#####.#.#.#.###...#.#.#.#..##.####.............................................................
.#.#.#.##.###.##.####.##.#.#.###.....#.#.#.#.#.#.###.#.#.#.##.....####.####################################################.###.
.#.#.#.#...#...#....#..#.#.#.#...#####.#.#.#.#.....#.#.#.#..###.###.#...#..#.#.#.#.#.#.#.#.#.#.#.#..#.#.#.#.#.#.#.#.#.#.#.###.#.
.#.#.#.##.###.##.####.##.#.#.###.#.#.#.#.#.#.###.###.#.#.#.##.#.#.#.##.###.#.#.#.#.#.#.#.#.#.#.#.#.##.#.#.#.#.#.#.#.#.#.#.#.#.##
................................................................................................................................
##.##.###.#############.#############################################################.#######################################.##
.###...#...#.....#.#..#..#..#.#.#.#.#..#.#.#.#..#..#..#....#..#.#.#..#.#..#.#..#.#.#..#.#.#...#.#..#.#.#.#.#.#.#................
.#.##.##.#.####.##.#.######.#.#.#.#.##.#.#.#.##.#.##.####.##.##.#...##.##.#.##.#.#.####.#.##.##.##.#.#.#.#.....##########.######
.#.#...#####.....#.#..#..#..#.#.#...#..#.#.#.#..#..#..#....#..#.#.#..#.#..#.#..#.#.#..#.#.#...#.#..#.#.#.###.###................
.#.##.##.#.####.##.#.##.###.#.#.##.###.#.#.#.##.#.##.####.##.##.#.####.##.#.##.#.#.##.#.#.##.##.##.#.#.#.#...#.####.############
.#.#...#...#..#..#.#..#..#..#.#.#...#..#.#.#.#..#..#..#....#..#.#....#.#..#.#..#.#.#..#.#.#...#.#..#.#.#.###...#..###...........
.#.##.###.###...##.#.##.###.#.#.##.###.#.#.#.##.#.##.###.###.##.###.##.##.#.##.#.#.##.#.#.##.##.##.#.#.#.#.#.###.##.#.##########
.#.#...#...#..#..#.#..#..#..#.#.#...#..#.#.#.#..#..#..#..#.#....................................................................
.#.##.###.#####.##.#.##.###.#.#.##.###.#.#.#.##.#.##.###...######.#############.#####.#################.########################
.#.#...#...#.....#.#..#..#..#.#.#...#..#.#.#.#..#..#..#..###.#.#...#..#...#.#.###..#..#.#...#.#.#...............................
.#.##.###.#####.##.#.##.###.#.#.##.###.#.#.#.##.#.##.###.#.#.#.##.###.##.##.#.#.##.####.##.##.#.################################
................................................................................................................................
#.#######.##################.######################.#.####.###################.#####################.##.####.##################.
#.......#.#.#.#.#.#.#.#.#.......#.............#.#.#.#.#.#...#.#.#..#.#..#.#..###.#.#.#.#.#.#.#.#.#.#.#..#.#....#.#.#.#.#.#.#..##
..####.####...#.#.#.#.#.####################.##.#.#.#...##.##.#.##.#.#.##.#.##.#.#.#.#.#.#.#.#.#.#.######.###.##.#.#.#.#.#.##.#.
#.#.....#.#.###.#.#.#.#.#.......#.............#.#.#.#.#.#...#...................................................................
..#######.#...#.#.#.#.#.#####.#####.###########.#.############.#####################.##.##.#.#.#.##.##.######.##################
#.......#.#.###.#.#.#.#.#.......#...#.#.#.#.#.#.#.#...#.#.#.#..#.#.#.#..#.#.#.#.#..#..#..#.#.#.#.#..#..#........................
..#######.#...#.#.#.#.#.######.####...........#.#.#.###.....####.#.#.#.##.#.#.#.##.#############################################
#.......#.#.###.#.#.#.#.#.......#.#.###########.#.#...###.###..#.#.#.#..#.#.#.#....#.#.#.#.#.#.#.#..#..#..#.#...................
..#######.#.#.#.#.#.#.#.######.##.............#.#.#.###.#.#.#.##.#.#.#.##.#.#.###.##.#.#.#.#.#.#.##.##.#.##.######.#############
#.#.#.#.#.#.#.#.#.#.#.#.#.......####.##########.................................................................................
........#.#...#.#.#.#.#.#####.###.#..#.#.#....#######.#####.#############################.#.#.#############.#############.######
#.##.####.##.##.#.#.#.#.#.#.#.#.#.##.#.#.###.##.#.#.###.#.###.#.#.#.#.#...#.#.#.#.#.#.#.#####...#.#.#.#.#.#.#.#.#.#.#.#.###.#.#.
..#.....#.#...#.#.#.#.#.#.......#.#..#...#.#..#.#.#.#.#.#.#.#.#.#.#.#.#.###.#.#.#.#.#.#.#..#..#.#...............................
#.#######.##.##.#.#.#.#.######.##.##.##.##.#.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.##.##.##################################
................................................................................................................................
########.#############.##################.#.##.##.#######.#.#.###########.######################################################
.....#......#.#..#..#..#...#.#.#.#..#...#.#.#..#..#.#...#######.#...#..#...#.#...#.#...#.#..#.#.#..#.....#.#.#.#................
###.####.##.#.#.###.##.#.###.#.#.#.##.#############.#.###.#.#.#.#.###.##.#.#.#.###.###.#.##.#.#.#.######.........###############
.....#...#..#.#..#..#..#...#.#.#.#..#...#.........#.#...#...#.#.#...#..#####.#...#.#.#.#..#.#.#.#..#...#.#.#.#.#................
###.####.####.#.###.##.#.###.#.#.#.##.#########.###.#.####.##.#.#.###.##...#.#.###...#.#.##.#.#.#.####.#.#######################
.....#......#.#..#..#..#...#.#.#.#..#...#.#.#.#.#.#.#...#...#.#.#...#..#.###.#...#.###.#.#..#.#.#..#.#..........................
##.#.###.####.#.###.##.#.###.#.#.#.##.###.........#.#.####.##.#.#.#.#.##...#.##.##.#...#.##.#.#.#.##...#.#################.#####
.#.###...#..#.#..#..#..#...#.#.#.#..#...#####.#####.#...#...#.#.#.###..#.###.#...#.###.#.#..#.#.#..#####...#....................
.....###...##.#.###.##.#.###.#.#.#.##.###.#.#.....#.#.####.##.#.#...#.##.#.#.##.##.#...#.##.#.#.#.##.....###.#.##############.##
##.###...#..#.#..#..#..#.#.#.#.#.#..#.#.#.....#.###.#...#...#.#.#.###..#...#.#...#.###.#.#..#.#.#..#####.#.#.#.#................
.#.#.###.####.#.###.####.#.#.#.#.#.##...#####.#...#.##.###.##.#.#...#.###.##.##.##.#.#.#.##.#.#.#.##.#.#.#.#####################
.....#...#..#.#..#..#..#...#.#.#.#..#.###..#..#####.#...#...#.#.#.###...........................................................
###.####.#.##.#.###.#.###.##.#.#.#.##.#.##.##.#.#.#.##.###.##.#.#.#.##########################################################.#
................................................................................................................................
#.###.###.################################.####################.################.###########.#######.###################.##.####
....#..#..#.#..#.#.#.#.#.#..#.#.#.#.#.#.#...#.#.#..#.#.#.#.#.#..#.#.#.#..#.#.#.###.#.#..#.#..#.#.#.###.#.#.#.#.#.#.#.#.#.#......
#.#########.##.#.#.#.#.#.#.##.#...#.#.#.#.#.#.#.#.##.#.#.#.#.####.#.#.#.##.#.#.#.#.#.##.#.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#########
....#..#..#.#..#.#.#.#.#.#..#.#.###.#.#.#####...................................................................................
#.####.#.##.##.#.#.#.#.#.#.##.#...#.#.#.#...##########.######.##################################.########.#.##############.#####
....#..#..#.#..#.#.#.#.#.#..#.#.###.#.#.#.###.#.#..#.###.#.#..#.#.#.#.#.#.#.#.#.#.#.#.#..#.#.#.###.#.#.#..###.#.#...............
#.#.##.#.##.##.#.#.#.#.#.#.##.#...#.#.#.#.#.#.#.##.#.#.#.#.####.#.#.#.#.#.#.#.#.#...#.##.#.#.#.#.#.#.#.####.#.#.#########.######
..###..#..#.#..#.#.#.#.#.#..#.#.###.#.#.#...#.#.#..#.#.#.#.#..#.#.#.#.#.#.#.#.#.#.###.#..#......................................
#.#.##.#.##.##.#.#.#.#.#.#.##.#.#.#.#.#.##.##.#.##.#.#.#.#.#.##.#.#.#.#.#.#.#.#.#.#.#.##.#######################################
................................................................................................................................
###.#################################.##########.######.#.#.####################.###############################################
.#....#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.###.#.#.#.#...#.#.#######.#.#.#.#.#.#.#.#.#.....#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.
.##.###.#.#.#.#.#.#.#.#...#.#.#.#.#.#.#.#...#.#.#.#.#.#..#..#.#.#.#.#.#.#.#...#######...........................................
.#..#.#.#.#.#.#.#.#.#.##.##.#.#.#.#.#.#.##.##.#####.#.##.#.##.#.#.#.#.#.#.##.##.#.#.####.#######################################
.##.............................................................................................................................
.#..########################################.###################################################################################
.##...#.......#.#.#.......#.#.#.#.#.#...#.#...#.#.#.#...........................................................................
.#..#.#####.###.#.######.##.#.#.#.#.#.###.#####.#...###############.############.#.##.#.#.#.#.#.#.#.#.#.#.###.#.#.##.#####.#####
.##.###.#.#.#.#.#.#.......#.#.#.#.#.#.#.#.#.#.#...###.#.#.#...#.#.....#...#..#.###..#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#...#.........
.#....#.......#.#.###.#.###.#.#.#.#.#...#.#...#.#...#.#.#.#.###.###.###.###.##.#.####.#.#.#.#.#.#.#.#.#.#...#.#.#.#.#.#.#.#.#.#.
.##.######.####.#.#.###.#.#.#.#.#.#.##.##.##.##.#####.#.#.#.#.#.#.....#.#.#.........############################################
.#....#.......#.#.#.......#.#.#.#.#.#...#.#...#.....#.#.#.#...#.###.###...#######.###.#.#.#.#.#.#.#.#.#.#.......................
.##.#######.###.#.######.##.#.#.#.#.##.##.##.##.#####.#.#.##.##.#.#.#.##.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.################.#######
................................................................................................................................
##.########.#.#.#.#.##.#.#.############################################.#############################.######.#.#.#.######.###.##
....#.#..#..#######..#.#.#.#.......#.#.#..#..#.#..#.#.#.#.#.#....#.#.#..#.#..#.#.#.#.#.#..#..#..#.#.###..#.#.#.#.#..#.#.###.#.#.
.#.##.##.####.....###############.##...#.##.##.##.#.#.#.#.#.#.####.#.####.#.##.#.#.#.#.#.##.###.#.#.#.##.#.#.#.#.#.##.#.........
.#..#.#..#..####.##..#.....#.......#.###..#..#.#..#.#.#.#.#.#....#.#.#..#.#..#.#.#.#.#.#..#..#..#.#.#.#..#.#.#.#.#....####.#####
##.##.##.#.##.....#.#####.#######.##.#.#.##.##.##.#.#.#.#.#.#.####.#.#.##.#.##.#.#.#.#.#.##.###.#.#.#.##.#.#.#.#.#.#.##.........
....#.#..#..###.###..#.....#.......#...#..#..#.#..#.#.#.#.#.#.#..#.#.#..#.#..#.#.#.#.#.#..#..#..#.#.#.#..#.#.#.#.#.#..#.#.#.#.#.
##.##.##.#.##.#.#.#.###.######.#.####.##.##.##.##.#.#.#.#.#.#.##.#.#.#.##.#.##.#.#.#.#.#.##.###.#.#.#.##.#.#####################
.....................#.....#.###.#.#............................................................................................
##.######################.##.......#####.############.######.########.#.#################################################.######
.....................#.....######.##.#......#...#.#.###.........#.#.#####.#.#.#.#.#.............................................
##.######################.##.......#.###.####.###.#.#.#.##.##.###.#.#...#.#.#.#...##############################################
.....................#.....######.##.#......#.#.#.#.#.#.#..#..#.#.#.##.##.#.#.##.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.....
##.###################.#.###.......#.#.#.####...#.#.#.#######...#.#.#...#.#.#.#...#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#...#.#...###.##
.....................###.#.######.##.###....##.##.#.#.#...#.#.###.#.##.##.#.#.##.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.###.#.###.#.#.
##.########.#.#.##.#.#.....#.......#.#...##.#...#.#.#.#.###.....#...............................................................
....#.#.#.#.#.#..#.#.####.#######.##.###.#..##.##.#.#.#.#.###.######.#######.###################.###.#.##.######################
##.##.#.#.############.....#.......#.#...####...#.#.#.#.........#.#..#.#.#....#.#.#.#.#.#.#.#.#..#.###.#..#.#..#.#..............
.....................####.#######.##.###....##.##.#.#.###.#######.####.#.#.#.##.#.#.#.#.#.#.#.####.#.######.##.#...#.#.#.###.###
##.###################.....#.......#.#...####...#.#.#.#.........#.#..#.#.###..#.#.#.#.#.#.#.#.#..#.#.#.#..#.#..#.#.#.#.#.#...#..
.....................####.#######.##.###....##.##.#.#.###########.#.##.#.#.#.##.#.#.#.#.#.#.#.##.#.#.#.##.#.##.#.#.#.#.#.###...#
.#.####.##############.....#.......#.#...#.##...#.#.#.#.........#.#..#.#.#....#.#.#.#.#.#.#.#.#..#.#.#.#..#.#..#.#.#.#.#.#...#..
##.#.................####.###.######.###.#..##.##.#.#.########.##.#.##.#.###.##.#.#.#.#.#.#.#.##.#.#.#.##.#.##.#.###############
...###################.....#.......#.#.#.####...................................................................................
##...................####.######.#.#.#......##.##########################.######################################.#####.#########
...###################.....#.#.#.###.###.####...#.#..#.#.#.#.#..#.#.#.#.###.#...#.#.#.#.#.#..#.#.#.#.#.#.#.#.#.###.#.###........
##.#.#.#.#.#.#.#.#.#.####.##.......#.#......##.##.#.##.#.#.#.#.##.#.#.#.#.#.##.##.#.#.#.#.#.##.#.#.#.#.#.#.#.#.#.#.#.#.###.#####
.....................#.....######.##.###.####...................................................................................
##.###########.#.#.#.###.###.......#.#......####.####.###############################.###.#.#.##.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.
.......#.#.#...#######.....###.#.###.###.##.#.#...#.....#...#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#..#..#.#.#.#.###.################
##.#####...#####.....####.##.###.#.#.#....###.#######.###.###...#.#.......#.#.#.#...#...#.#.#.#####.#.#.#.#.#...#.#.#.#.#.#.#.#.
.......##.##.#.##.####.....#.#.#.#.#.###.##.#.#...#.....#.#.##.##.##.###.##.#.#.##.##.###.#.#.#.....#.#.#.#.###.................
##.#.#.#.............###.###.......#.#....#.#.#.#####.###...#...#.#..#....#.#.#.#...#...#.#.#.#.#.#.#.#.#.#..#..#.#.#.#.#.#.#.#.
.#.################.##.#.#.######.##.###.##.#.#.#.#.#.#.##.###.##.##.######.#.#.##.#############################################
................................................................................................................................
.###.####.##########.####################################################.#######################.#.#.#.#.#.#.#.#.#.##.#########
...#..#.#...#.....#.......#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.###.#.#...#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#...........
.###.##...#####.###.##.####.#.#.#.#.#.#.#...#.#.#.#.#.#.#.#.#.#...#.#.#.#.#.#.#.###.#.#...#.#...################################
...#..###...#.#.#.#.#..#..#.#.#.#.#.#.#.##.##.#.#.#.#.#.#.#.#.##.##.#.#.#.#.#.#.#.#.#.##.##.##.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.
.###.##...###.....#.##...##.....................................................................................................
...#..###...####.##.#..#..##########.#################.################.######################################.######.#.#.#.#.#.
.###.##...###.....#########.#.#.#.#...#.#.#.#.#.#.#.#..#.#.#.#.#.#.#.#..#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#..###.#..############
...#..###.#.####.##.#.#.#.#.#.#.#.##.##.#.#.#.#.#.#.####.#.#.#.#.#.#.####.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.##.#.##.#.#.#.#.#.#.
.###.##.........................................................................................................................
...#..#.#.###.#####.##.##.#.#.#.#.#.#.#.#.#.#.#################################.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.##.#.##.
.###.##.#.#.#.....#.#...#.#.###.#.#####.#.###..#.#.#.#....#.#..#.#.#..#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#..#.#..
.#.#..#.#...#.#####.##.##.#.#...#.#.....#.#...##.#.#.##.###...##.#.##.#.#.#.#.##################################################
...#.##.#.###.....#.#...#.#.###.#.#####.#.###..#.#.#.#..#.#.#..#.#.#..#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#..#..............
.###..#.#.#.#.#.#.#.##.##.#.#...#.#.....#..#..##.#.#.##.#.####.#.#.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.##.############.##
...#.##.#...#.#####.#...#.#.###.#.##.##.#.###...................................................................................
.###..#.#.###.#.#.#.##.##.#.#...#.#..#..#..#..###.#.#.####.###.##.#.#.#.#.##.##.##############.#################################
...#.##.#...#.....#.#...#.#.###.#.#####.#.###.#.#.#.#.#.....#...#.#.#.#.#.#...#...#.............................................
.###..#.#.###.##.##.##.##.#.#.#.#.#.....#.#.....#.#.#.###########.#.#.#.#.##.##.#######################.########################
...#.##.#.#.#.#...#.#...#.#...#.#.#####.#.#.#.###.#.#.......#.#.#.#.#.#.#.#...#...#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.
.#.#..#.#...#.#.#.#.#.#.#.#.#.#.#.#.....#.#.#...#.#.#.#.#.#.#.....#.#.#.#.#.#.#.#.#.............................................
```
# Score: 8066
This is the unedited solution from the dynamic programming algorithm.
[Validate](https://tio.run/##zV1Lbxs5Ej6Hv6InPEjCKB@S3csiWO8tc11gMXtYGMZAa8txe2VJkOSJPUF@e7ZbkrtZZBVZZHcmkWNL6geb/FjvKjLb58PdZv3Xr/v6j@XFu7/8zWx29cd6vVj99rBojkwmE5v5QvEV5Dhevhn3JJj7Af6zdyUijwdzpDtmom2A7ZJi/FBjYwpxZiHR39hfmuoAiuYbwjvz1aRpB6OQpnATaAfgdpmDN0KScqdi1/kdELo5EoNyt5gSUhtAKyCEceoAuCaKJjWfi2QuwAjPUckko2gO0UcByi7Bo@GuAwz2wiORSQBAqSAqoQOkpBIvloz0SDDDgHiRUiEwEBraN4xD39BjZeyIL@QQwvm4KWGdSLs68H0aiItbqJoLrwKkpok2xAAhwisLZNGM8fsOwjdgzbQCrSFeYgrGHDmLqCiFpI4RsV7SD8PLA5CWmeGs@VYx8qGGfsrBa0Oo7DqR@tRTAY5KzDAjV6u1IV5uko1zYgCxIzh@g66XMChjMLSvTKEnS0JegEIhhVHKtZCmAAPMYkmle2IAHgJQi1Wd2ZWpM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fjd8svbmIx@fojG8Sz0CNAQUda4GWUk0j1JS1kI6ykyi3299YYgtRK0MpMGYL6NVewgYEUEgtVN7KKRsq1yKAIpGvBzZWALPYcgwGoxeNzAuhIo29nN@EUvTIrSMqU8rMmi9xb8pd8JWwZMQDJWL5Hz@j8 "Python 3 – Try It Online")
```
.#.#.#.#...#...#.#..#..#.#.#.#...#.#.#.#.#.#.#.#................................................................................
.#.#.#.##.##.###...##.##.#.#.###.....#.#.#.#...#.##########.###########.########.##################.#################.#.#.#.#.#.
.#.#.#.#...#...#.#..#..#.#.#...#.##.##.#.#.#.###...#.#.#.#..#.#.#.#.#.###.#.#..#.#.#.#.#.#.#.#.#.#..#.#.#.#..#.#.#.#..##########
.#.#.#.##.###.##.####.##.#.#.###.#...#.#.#.#.#...###.#.#.####.....#.#.#.#.#.##.###.#.#.#.#.#.#.#.####.#.#.#.##.#.#.####.#.#.#.#.
.#.#.#.#...#...#....#..#.#.#.#...#####.#.#.#.###...#.#.#.#..##.####.............................................................
.#.#.#.##.###.##.####.##.#.#.###.....#.#.#.#.#.#.###.#.#.#.##.....####.####################################################.###.
.#.#.#.#...#...#....#..#.#.#.#...#####.#.#.#.#.....#.#.#.#..###.###.#...#..#.#.#.#.#.#.#.#.#.#.#.#..#.#.#.#.#.#.#.#.#.#.#.###.#.
.#.#.#.##.###.##.####.##.#.#.###.#.#.#.#.#.#.###.###.#.#.#.##.#.#.#.##.###.#.#.#.#.#.#.#.#.#.#.#.#.##.#.#.#.#.#.#.#.#.#.#.#.#.##
................................................................................................................................
##.##.###.#############.#############################################################.#######################################.##
.###...#...#.....#.#..#..#..#.#.#.#.#..#.#.#.#..#..#..#....#..#.#.#..#.#..#.#..#.#.#..#.#.#...#.#..#.#.#.#.#.#.#................
.#.##.##.#.####.##.#.######.#.#.#.#.##.#.#.#.##.#.##.####.##.##.#...##.##.#.##.#.#.####.#.##.##.##.#.#.#.#.....##########.######
.#.#...#####.....#.#..#..#..#.#.#...#..#.#.#.#..#..#..#....#..#.#.#..#.#..#.#..#.#.#..#.#.#...#.#..#.#.#.###.###................
.#.##.##.#.####.##.#.##.###.#.#.##.###.#.#.#.##.#.##.####.##.##.#.####.##.#.##.#.#.##.#.#.##.##.##.#.#.#.#...#.####.############
.#.#...#...#..#..#.#..#..#..#.#.#...#..#.#.#.#..#..#..#....#..#.#....#.#..#.#..#.#.#..#.#.#...#.#..#.#.#.###...#..###...........
.#.##.###.###...##.#.##.###.#.#.##.###.#.#.#.##.#.##.###.###.##.###.##.##.#.##.#.#.##.#.#.##.##.##.#.#.#.#.#.###.##.#.##########
.#.#...#...#..#..#.#..#..#..#.#.#...#..#.#.#.#..#..#..#..#.#....................................................................
.#.##.###.#####.##.#.##.###.#.#.##.###.#.#.#.##.#.##.###...######.#############.#####.#################.########################
.#.#...#...#.....#.#..#..#..#.#.#...#..#.#.#.#..#..#..#..###.#.#...#..#...#.#.###..#..#.#...#.#.#...............................
.#.##.###.#####.##.#.##.###.#.#.##.###.#.#.#.##.#.##.###.#.#.#.##.###.##.##.#.#.##.####.##.##.#.################################
................................................................................................................................
#.#######.##################.######################.#.####.###################.#####################.##.####.##################.
#.......#.#.#.#.#.#.#.#.#.......#.............#.#.#.#.#.#...#.#.#..#.#..#.#..###.#.#.#.#.#.#.#.#.#.#.#..#.#....#.#.#.#.#.#.#..##
..####.####...#.#.#.#.#.####################.##.#.#.#...##.##.#.##.#.#.##.#.##.#.#.#.#.#.#.#.#.#.#.######.###.##.#.#.#.#.#.##.#.
#.#.....#.#.###.#.#.#.#.#.......#.............#.#.#.#.#.#...#...................................................................
..#######.#...#.#.#.#.#.#####.#####.###########.#.############.#####################.##.##.#.#.#.##.##.######.##################
#.......#.#.###.#.#.#.#.#.......#...#.#.#.#.#.#.#.#...#.#.#.#..#.#.#.#..#.#.#.#.#..#..#..#.#.#.#.#..#..#........................
..#######.#...#.#.#.#.#.######.####...........#.#.#.###.....####.#.#.#.##.#.#.#.##.#############################################
#.......#.#.###.#.#.#.#.#.......#.#.###########.#.#...###.###..#.#.#.#..#.#.#.#....#.#.#.#.#.#.#.#..#..#..#.#...................
..#######.#.#.#.#.#.#.#.######.##.............#.#.#.###.#.#.#.##.#.#.#.##.#.#.###.##.#.#.#.#.#.#.##.##.#.##.######.#############
#.#.#.#.#.#.#.#.#.#.#.#.#.......####.##########.................................................................................
........#.#...#.#.#.#.#.#####.###.#..#.#.#....#######.#####.#############################.#.#.#############.#############.######
#.##.####.##.##.#.#.#.#.#.#.#.#.#.##.#.#.###.##.#.#.###.#.###.#.#.#.#.#...#.#.#.#.#.#.#.#####...#.#.#.#.#.#.#.#.#.#.#.#.###.#.#.
..#.....#.#...#.#.#.#.#.#.......#.#..#...#.#..#.#.#.#.#.#.#.#.#.#.#.#.#.###.#.#.#.#.#.#.#..#..#.#...............................
#.#######.##.##.#.#.#.#.######.##.##.##.##.#.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.##.##.##################################
................................................................................................................................
########.#############.##################.#.##.##.#######.#.#.###########.######################################################
.....#......#.#..#..#..#...#.#.#.#..#...#.#.#..#..#.#...#######.#...#..#...#.#...#.#...#.#..#.#.#..#.....#.#.#.#................
###.####.##.#.#.###.##.#.###.#.#.#.##.#############.#.###.#.#.#.#.###.##.#.#.#.###.###.#.##.#.#.#.######.........###############
.....#...#..#.#..#..#..#...#.#.#.#..#...#.........#.#...#...#.#.#...#..#####.#...#.#.#.#..#.#.#.#..#...#.#.#.#.#................
###.####.####.#.###.##.#.###.#.#.#.##.#########.###.#.####.##.#.#.###.##...#.#.###...#.#.##.#.#.#.####.#.#######################
.....#......#.#..#..#..#...#.#.#.#..#...#.#.#.#.#.#.#...#...#.#.#...#..#.###.#...#.###.#.#..#.#.#..#.#..........................
##.#.###.####.#.###.##.#.###.#.#.#.##.###.........#.#.####.##.#.#.#.#.##...#.##.##.#...#.##.#.#.#.##...#.#################.#####
.#.###...#..#.#..#..#..#...#.#.#.#..#...#####.#####.#...#...#.#.#.###..#.###.#...#.###.#.#..#.#.#..#####...#....................
.....###...##.#.###.##.#.###.#.#.#.##.###.#.#.....#.#.####.##.#.#...#.##.#.#.##.##.#...#.##.#.#.#.##.....###.#.##############.##
##.###...#..#.#..#..#..#.#.#.#.#.#..#.#.#.....#.###.#...#...#.#.#.###..#...#.#...#.###.#.#..#.#.#..#####.#.#.#.#................
.#.#.###.####.#.###.####.#.#.#.#.#.##...#####.#...#.##.###.##.#.#...#.###.##.##.##.#.#.#.##.#.#.#.##.#.#.#.#####################
.....#...#..#.#..#..#..#...#.#.#.#..#.###..#..#####.#...#...#.#.#.###...........................................................
###.####.#.##.#.###.#.###.##.#.#.#.##.#.##.##.#.#.#.##.###.##.#.#.#.##########################################################.#
................................................................................................................................
#.###.###.################################.####################.################.###########.#######.###################.##.####
....#..#..#.#..#.#.#.#.#.#..#.#.#.#.#.#.#...#.#.#..#.#.#.#.#.#..#.#.#.#..#.#.#.###.#.#..#.#..#.#.#.###.#.#.#.#.#.#.#.#.#.#......
#.#########.##.#.#.#.#.#.#.##.#...#.#.#.#.#.#.#.#.##.#.#.#.#.####.#.#.#.##.#.#.#.#.#.##.#.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#########
....#..#..#.#..#.#.#.#.#.#..#.#.###.#.#.#####...................................................................................
#.####.#.##.##.#.#.#.#.#.#.##.#...#.#.#.#...##########.######.##################################.########.#.##############.#####
....#..#..#.#..#.#.#.#.#.#..#.#.###.#.#.#.###.#.#..#.###.#.#..#.#.#.#.#.#.#.#.#.#.#.#.#..#.#.#.###.#.#.#..###.#.#...............
#.#.##.#.##.##.#.#.#.#.#.#.##.#...#.#.#.#.#.#.#.##.#.#.#.#.####.#.#.#.#.#.#.#.#.#...#.##.#.#.#.#.#.#.#.####.#.#.#########.######
..###..#..#.#..#.#.#.#.#.#..#.#.###.#.#.#...#.#.#..#.#.#.#.#..#.#.#.#.#.#.#.#.#.#.###.#..#......................................
#.#.##.#.##.##.#.#.#.#.#.#.##.#.#.#.#.#.##.##.#.##.#.#.#.#.#.##.#.#.#.#.#.#.#.#.#.#.#.##.#######################################
................................................................................................................................
###.#################################.##########.######.#.#.####################.###############################################
.#....#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.###.#.#.#.#...#.#.#######.#.#.#.#.#.#.#.#.#.....#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.
.##.###.#.#.#.#.#.#.#.#...#.#.#.#.#.#.#.#...#.#.#.#.#.#..#..#.#.#.#.#.#.#.#...#######...........................................
.#..#.#.#.#.#.#.#.#.#.##.##.#.#.#.#.#.#.##.##.#####.#.##.#.##.#.#.#.#.#.#.##.##.#.#.####.#######################################
.##.............................................................................................................................
.#..########################################.###################################################################################
.##...#.......#.#.#.......#.#.#.#.#.#...#.#...#.#.#.#...........................................................................
.#..#.#####.###.#.######.##.#.#.#.#.#.###.#####.#...###############.############.#.##.#.#.#.#.#.#.#.#.#.#.###.#.#.##.#####.#####
.##.###.#.#.#.#.#.#.......#.#.#.#.#.#.#.#.#.#.#...###.#.#.#...#.#.....#...#..#.###..#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#...#.........
.#....#.......#.#.###.#.###.#.#.#.#.#...#.#...#.#...#.#.#.#.###.###.###.###.##.#.####.#.#.#.#.#.#.#.#.#.#...#.#.#.#.#.#.#.#.#.#.
.##.######.####.#.#.###.#.#.#.#.#.#.##.##.##.##.#####.#.#.#.#.#.#.....#.#.#.........############################################
.#....#.......#.#.#.......#.#.#.#.#.#...#.#...#.....#.#.#.#...#.###.###...#######.###.#.#.#.#.#.#.#.#.#.#.......................
.##.#######.###.#.######.##.#.#.#.#.##.##.##.##.#####.#.#.##.##.#.#.#.##.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.################.#######
................................................................................................................................
##.########.#.#.#.#.##.#.#.############################################.#############################.######.#.#.#.######.###.##
....#.#..#..#######..#.#.#.#.......#.#.#..#..#.#..#.#.#.#.#.#....#.#.#..#.#..#.#.#.#.#.#..#..#..#.#.###..#.#.#.#.#..#.#.###.#.#.
.#.##.##.####.....###############.##...#.##.##.##.#.#.#.#.#.#.####.#.####.#.##.#.#.#.#.#.##.###.#.#.#.##.#.#.#.#.#.##.#.........
.#..#.#..#..####.##..#.....#.......#.###..#..#.#..#.#.#.#.#.#....#.#.#..#.#..#.#.#.#.#.#..#..#..#.#.#.#..#.#.#.#.#....####.#####
##.##.##.#.##.....#.#####.#######.##.#.#.##.##.##.#.#.#.#.#.#.####.#.#.##.#.##.#.#.#.#.#.##.###.#.#.#.##.#.#.#.#.#.#.##.........
....#.#..#..###.###..#.....#.......#...#..#..#.#..#.#.#.#.#.#.#..#.#.#..#.#..#.#.#.#.#.#..#..#..#.#.#.#..#.#.#.#.#.#..#.#.#.#.#.
##.##.##.#.##.#.#.#.###.######.#.####.##.##.##.##.#.#.#.#.#.#.##.#.#.#.##.#.##.#.#.#.#.#.##.###.#.#.#.##.#.#####################
.....................#.....#.###.#.#............................................................................................
##.######################.##.......#####.############.######.########.#.#################################################.######
.....................#.....######.##.#......#...#.#.###.........#.#.#####.#.#.#.#.#.............................................
##.######################.##.......#.###.####.###.#.#.#.##.##.###.#.#...#.#.#.#...##############################################
.....................#.....######.##.#......#.#.#.#.#.#.#..#..#.#.#.##.##.#.#.##.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.....
##.###################.#.###.......#.#.#.####...#.#.#.#######...#.#.#...#.#.#.#...#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#...#.#...###.##
.....................###.#.######.##.###....##.##.#.#.#...#.#.###.#.##.##.#.#.##.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.###.#.###.#.#.
##.########.#.#.##.#.#.....#.......#.#...##.#...#.#.#.#.###.....#...............................................................
....#.#.#.#.#.#..#.#.####.#######.##.###.#..##.##.#.#.#.#.###.######.#######.###################.###.#.##.######################
##.##.#.#.############.....#.......#.#...####...#.#.#.#.........#.#..#.#.#....#.#.#.#.#.#.#.#.#..#.###.#..#.#..#.#..............
.....................####.#######.##.###....##.##.#.#.###.#######.####.#.#.#.##.#.#.#.#.#.#.#.####.#.######.##.#...#.#.#.###.###
##.###################.....#.......#.#...####...#.#.#.#.........#.#..#.#.###..#.#.#.#.#.#.#.#.#..#.#.#.#..#.#..#.#.#.#.#.#...#..
.....................####.#######.##.###....##.##.#.#.###########.#.##.#.#.#.##.#.#.#.#.#.#.#.##.#.#.#.##.#.##.#.#.#.#.#.###...#
.#.####.##############.....#.......#.#...#.##...#.#.#.#.........#.#..#.#.#....#.#.#.#.#.#.#.#.#..#.#.#.#..#.#..#.#.#.#.#.#...#..
##.#.................####.###.######.###.#..##.##.#.#.########.##.#.##.#.###.##.#.#.#.#.#.#.#.##.#.#.#.##.#.##.#.###############
...###################.....#.......#.#.#.####...................................................................................
##...................####.######.#.#.#......##.##########################.######################################.#####.#########
...###################.....#.#.#.###.###.####...#.#..#.#.#.#.#..#.#.#.#.###.#...#.#.#.#.#.#..#.#.#.#.#.#.#.#.#.###.#.###........
##.#.#.#.#.#.#.#.#.#.####.##.......#.#......##.##.#.##.#.#.#.#.##.#.#.#.#.#.##.##.#.#.#.#.#.##.#.#.#.#.#.#.#.#.#.#.#.#.###.#####
.....................#.....######.##.###.####...................................................................................
##.###########.#.#.#.###.###.......#.#......####.####.###############################.###.#.#.##.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.
.......#.#.#...#######.....###.#.###.###.##.#.#...#.....#...#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#..#..#.#.#.#.###.################
##.#####...#####.....####.##.###.#.#.#....###.#######.###.###...#.#.......#.#.#.#...#...#.#.#.#####.#.#.#.#.#...#.#.#.#.#.#.#.#.
.......##.##.#.##.####.....#.#.#.#.#.###.##.#.#...#.....#.#.##.##.##.###.##.#.#.##.##.###.#.#.#.....#.#.#.#.###.................
##.#.#.#.............###.###.......#.#....#.#.#.#####.###...#...#.#..#....#.#.#.#...#...#.#.#.#.#.#.#.#.#.#..#..#.#.#.#.#.#.#.#.
.#.################.##.#.#.######.##.###.##.#.#.#.#.#.#.##.###.##.##.######.#.#.##.#############################################
................................................................................................................................
.###.####.##########.####################################################.#######################.#.#.#.#.#.#.#.#.#.##.#########
...#..#.#...#.....#.......#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.###.#.#...#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#...........
.###.##...#####.###.##.####.#.#.#.#.#.#.#...#.#.#.#.#.#.#.#.#.#...#.#.#.#.#.#.#.###.#.#...#.#...################################
...#..###...#.#.#.#.#..#..#.#.#.#.#.#.#.##.##.#.#.#.#.#.#.#.#.##.##.#.#.#.#.#.#.#.#.#.##.##.##.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.
.###.##...###.....#.##...##.....................................................................................................
...#..###...####.##.#..#..##########.#################.################.######################################.######.#.#.#.#.#.
.###.##...###.....#########.#.#.#.#...#.#.#.#.#.#.#.#..#.#.#.#.#.#.#.#..#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#..###.#..############
...#..###.#.####.##.#.#.#.#.#.#.#.##.##.#.#.#.#.#.#.####.#.#.#.#.#.#.####.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.##.#.##.#.#.#.#.#.#.
.###.##.........................................................................................................................
...#..#.#.###.#####.##.##.#.#.#.#.#.#.#.#.#.#.#################################.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.##.#.##.
.###.##.#.#.#.....#.#...#.#.###.#.#####.#.###..#.#.#.#....#.#.##.#.#..#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#..#.#..
.#.#..#.#...#.#####.##.##.#.#...#.#.....#.#...##.#.#.##.###....#.#.##.#.#.#.#.##################################################
...#.##.#.###.....#.#...#.#.###.#.#####.#.###..#.#.#.#..#.##.###.#.#..#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#..#..............
.###..#.#.#.#.#.#.#.##.##.#.#...#.#.....#..#..##.#.#.##.#.##.#.#.#.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.##.############.##
...#.##.#...#.#####.#...#.#.###.#.##.##.#.###...................................................................................
.###..#.#.###.#.#.#.##.##.#.#...#.#..#..#..#..###.#.#.####.###.##.#.#.#.#.##.##.##############.#################################
...#.##.#...#.....#.#...#.#.###.#.#####.#.###.#.#.#.#.#.....#...#.#.#.#.#.#...#...#.............................................
.###..#.#.###.##.##.##.##.#.#.#.#.#.....#.#.....#.#.#.###########.#.#.#.#.##.##.#######################.########################
...#.##.#.#.#.#...#.#...#.#...#.#.#####.#.#.#.###.#.#.......#.#.#.#.#.#.#.#...#...#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.
.#.#..#.#...#.#.#.#.#.#.#.#.#.#.#.#.....#.#.#...#.#.#.#.#.#.#.....#.#.#.#.#.#.#.#.#.............................................
```
[Answer]
# Score: 8127 ([validation](https://tio.run/##tV3LbhvJFV27vqLHd0EKwzmwk00wiLKb2QYIJotAEAJGoqxWJJIgqbE1hr/daT677ququshwYJFqdldXnbr33Gdrlm@bx8X8z9/X7R@z649/@ktYrNpP7Xz6/O@XaXdkNBrRwBeqz2DHcfwtxF/CuB6wP4szkbg9jCOnYyE5BswpFawfxdiESpxNSMov7E/NTQBV@w3n3fg15GUHFxFN5yLwCSCesgVvQiT9SaXOkxNwpnkhBbUuCTWidoasgAnGfgKwhqja1OFa5GsBLnCfIk4KBcMheSugcEoQMnyagIG9c0sMFACglohq5AA5VrJpKXi3hLEMuCcVGgQDwsDnhsvIN8qxCnTBF4YIwuF4qFGdxLhl4EsZSNMtiobTZwHe0Mwa4gwSsY0FBslMkHMH0xuYblqF1XBPCRVrTnyLJJXCM8dIeC/5m@F4A@Q5U@@a9IoxHGqUbzlsa4giv86VvuKtgCUl4Twnt9Rqwz09ZAe3aACpI9j9hrJZIqBOwbB9DSQ9nwltAkUBC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Js8lH5QCSCZs0@VhVYywDrX9blJxL9l4k4VhZZWRVYVM@Z8FKi/CRq@7pf0Apete1gwwblYEbhp6o4yhK@6Bfkga@X30nVjCyjrRCQgYvy3bykiWqoOWTL3R4joW5k6SiJ/l@/yAjRUHN4C9Dxk12fgd1xZpgON8MHwy8JLoWTV6PyU/pxGc8rxkm/JKhEu6n75LTOktMKiAKTphBwW1blzEVVU6bGmUuWNGEcAaQQiNxS2acCaE/abbzWAh6ckMObFpIuEukQ2kdg/zNwkixo2iLfRYLTPpAqSISYBSjDA5GlSjQcm/kzsytPumRW96gZLqK3yDmvNVnxBUWdVHYzkd24IiwySUSUgyLJMtqhAE7Umf5Rqz0LcB1bo5okKSNAlhKU8@W3S5o5ZrMfC@ZTKjIwMZ8LAPy2BYuMdJTA1NxCwOFtTcd2CiP7@AFXc2nCQraL3LFUzqMEbmdu3G@uyvfpSKCgz13Lv8ygqYx73MDgC7Hdve@HC2IiugVaJysD3xzn6RAvWsnaG5GX8hFQfb1wkpM5toLZ9SeexfAR8AqFbrdVedh80ukMArruCZS4N7mw2UAg7iu2ar5CvfMJI7cBwHgahTc2J7LeYJXfQfCLhjADAS0D2t1Tld8oaBqGgTIIhgxod4/cSilQNAXVH8oycHHFxGJqP2fl@C8pDDQdspqRxdQW5TEbVySQsovE4AHrQQxKc@tpC1CiF@IRjwwCtnOiGal/nifhzQn6h9H9E@LHoyALnQxA3cNDuhJgWQqjr9BFALrCzgMvijijkBN0B09CBsweNsPap1rkknX7DAJ2D1vyCSRKlxRIP2PDySkgUYm2@EnXinMektHnE93pfw))
-11 thanks to Anders Kaseorg
```
.....#.....#....#................##........#.##...........#...........#........#..................#.................#...........
.#.#...#.#...#.##.#.#.#.#.#.#.##..#.#.#.#.##..#.##.#.#.#.##.#.#.#.#.#...#.#.#.##.#.#.#.#.#.#.#.#.##.#.#.#.##.#.#.#.##.#.#.#.#.#.
.#.#.#.#.#.#.#..#.#.#.#.#.#.#..#.##.#.#.#..#.##..#.#.#.#..#.#.###.#.#.#.#.#.####.#.#.#.#.#.#.#.#..#.#.#.#..#.#.#.#..#.#.#.#.#.#.
.#.#.#.#.#.#.#.##.#.#.#.#.#.#.#####.#.#.#.##..#.##.#.#.#.##.#...#.#.#.#.#.#....#.#.#####.#.#####.##.#.#.#.##.#.#.#.####.#.#.#.#.
.#.#.#.#####.#..#.#.#.#.#.#.#...#.###.#.#..#.##..#.#.#.#..#.##.##.#.#####.#.#.##.#.....#.#.....#..#.#.#.#..#.#.#.#....#.#.#.#.#.
.#.#.#.....###.##.#.#########.#.....#.#.##.#.##.##.#.#.#.##..#..#.#.....#.#.#..#.#.#.#.#.#.#.#.#.##.#.#.#.##.#.#.#.#.##.#.#.#.#.
.#.#.#.##.##....#.#.........#.##.#.####..#.#.....#.#.#.#....##.##.#.#.#.#####.##.#.#.#.#.#.#.#.#....#.#.#..#.#.#.#.#..#.#.#.#.#.
.#.#.#..#..##.#.#.#.#.#.#.#.#..#.###..#.##.#.#.#.#.#.#.#.#.######.#.#.#.....#..#.#.#.#.#.#.#.#.#.#.######.##.#####.#.##.#####.#.
.#.#.#.##.###.#.#.#.#.#.#.#.#.##.....##..#.#.#.#.#.#.#.#.#......#.#.#.#.#.#.#.##.#.#####.#.#.#.#.#......#..#.....#.#..#.....#.#.
.#.#.#..#...#.#.#.#.#.#.#.#.#..#.#.#..#.##.#.#.#.#.#.#.#.#.#.#.##.#.#.#.#.#.#..#.#.....#.#####.#.#.#.#.##.##.#.#.#.#.##.#.#.#.#.
.#.#.#.###.##.#.#.#.#.#.#.#.#.##.#########.#.#.#.#.#.#.#.#.#.#..#.###.#.#.#.##.#.#.#.#.#.....#.#.#.#.#..######.#.#.#..#.#.#.#.#.
.#.#.#...#..#.#####.#.#####.#..#.........#.#.#.#.#.#.#.#.#.#.#.##..##.#.#.#..#.#.#.#.#.#.#.#.###.#.#.#.##......#.#.#.##.#.#.#.#.
.#.#.#.#.#.##.....#.#.....#.#.##.#.#.#.#.#...#.#.#.#.#.#.#.#.#..#.##..#.#.#.##.#.#.#.#.#.#.#...#.#.#.#..#.#.#.##.######.#.#.#.#.
.#.#.#.#.#..#.#.#.#.#.##.##.#..###.#.#.#.#.#.#.#.#.#.#.#.#.####.#..#.##.#.#..#.#.#.#####.####.##.#.#.#.##.#.#..#......#.#.#.#.#.
.#.#####.#.##.###.#.#..#..#.#.##...#.#.#.#.#.#####.#.#.#.#....#.#.##..#.#.#.##.#.#.....#....#..#.#.#.#..#.#.#.##.##.#.#.#.#.#.#.
.#.....#.#..#...#.#.#.##.##.#..#.#.#.#.#.#.#.....#.#.#.#.#.#.##.#..#.##.#.####.#.#.##.##.#.##.####.#.#.##.#.#..#..#.#.#.#.###.#.
.#.#.#.#.#.##.#.#.#.#..#..#.#.##.#.#.#.#.#.#.#.#.#.#.#.#.###..#.#.##..#.#....#####..#..#.#..#...#..#.####.#.#.##.##.#.#.#...#.#.
.#.#.#.#.#..#.#.#.#.#.##.##.#..#.#.###.#.#.#.#.#.#.#####...#.##.#..#.####.#.##...#.##.##.#.##.#.#.####..#.#.#..#..#.###.#.#.#.#.
.#.#.#.#.#.##.#.#.#.#.#####.#.##.#...#.#.#.#.#.#.#.....#.#.#..#.#.#####...#..#.#.#..#..#.#..#.#.#....#.##.#.#.##.##...#.#.#.#.#.
.#.###.#.#..#.#####.#.....######.#.#####...#.#.#.#.#.#.#.#.#.##.#.....#.#.#.##.#...##.##.#.##.#.#.#.##..#.#.#..#.##.#.#.#.#.#.#.
.#...#.####.#.......#.#.#......#.#.....#.#.#.#.#.#.#.#.#.#.#..#.#.#.#.#.#.#....#.#..#..#.#..#.#.#.#####.#.####.#..#.#.#.#.#.#.#.
.#.#.#....#.#.#.#.#.#.#.#.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.##.#######.#.#.##.#.#.###.#.#.##.#.#.......#....#.#.##########.#.#.
.#.#.#.##.#####.#.#.#.#.#..#.#.#.#.#.#.#.#.#.#.#.#.###.#.#.#..#.......#.#.#..#.#.#...#.#.#..#.#.#.##.#.##.#.####..........#.#.#.
.#####..#.....#.#.#.#.#.#.##.#.#####.#.#.#.#.#.#.#..#..#.#.#.###.#.#.##.#.#.##.#.#.#.#.#.#.##.#.#..#.#..#.#...##.#.#.#.#.##.#.#.
.....#.##.##.##.#.#.#.#.#..#####...#.#.#.#.#.#.#.#.##.##.#.#...#.#.#..#.#.#..#.#.#.#.#.#.#..#.#.#.####.##.#.#.#..#.#.#.#..#.#.#.
.#.#.#..#..#..#.#.#.#.#.##.....##.##.#.#.#.#.#.#.#.##..#.#.#.#.#.#.#.##.#.#.##.#.#.#.###.#.##.#.#....#..#.#.#.#.##.#.#.#.##.#.#.
.#.#.#.##.##.##.#.#.#.#..#.#.#.....#.###.#.#.#.#.#.#..##.#####.#.#.#.#..#.#..#.#.#.#...#.#..#.#.#.#.##.##.#.#.#..#.#.#.#..#.#.#.
.#.######.#####.#.#.#.#.##.####.#.##..#..#.#.#.#.###.##......#.#.#.#.#.##.#.##.#.#.#.#.#.#.##.#.#.#..#..#.#.#.#.##.#.####.#.#.#.
.#......#.....#.#.#.#.#..#....#.#..##.#.##.#.#.#..#...#.#.#.##.#.#.#.#..#.#..#.#####.#.#.#.####.#.#.##.##.#.#.#..#.#....#.#.#.#.
###.#.#.#.#.#.#.#.#.#.#.##.#.####.##..#..#.#.#.#.###.##.#.#..#.#.#.#.#.##.#.##.....#.#.#.#....#.#.#..#..#.#.#.#.##.#.#.##.#.#.#.
..#.###.#.#.#.#.#.#.#.#..#.#....#..#.##.##.#.#.#...####.#.#.##.#.#.#.#..#.#..#.#.#.#.#.#.#.#.##.#.#.##.##.#.#.#..#.#.#..#.#.#.#.
#.....#.#.#####.#.#.#.#.##.#.#.##.##..####.#.#.#.#....#.#.#..#####.#.#.####.##.#.#.#.#.#.#.#.##.#.#..#..#.#.#.#.##.#.#.##.#.#.#.
..##.##.#.....#.#.#.#.#.####.#..#..#.##..#.#.#.#.#.#.##.#.#.###..#.#.#....#..#.#.#.#.#.#.#.#.#..#.#.##.##.#.#.#..#.#.#..#.#.#.#.
.###..#.#.##.##.#.#.#.#....#.#.##.##..#.##.#.#.#.#.#..#.#.#...#.##.#.#.#.##.##.#.#.#.#.#.#.#.#.##.#..#..#.#.#.#.##.#.#.##...#.#.
...#.##.#..#..#.#####.#.#.##.#..#..#.##....#.#.#.#.#.##.#.##.##..#.#.#.#..#..#.#.#.#.#.#.#.#.#..#.#.##.##.#.#.#..#.#.#..##.##.#.
.#.#.#..#.##.##.....#.#.#..#.#.##.##..#.#.##.#.#####..#.#..#..#.##.#.#.##.#.##.#.#.#.#.#.#.#.#.##.#..#..#.#.#.#.##.#.#.##...#.#.
.#.#.#.##..#..#.#.#.#.#.#.##.#..#..#.##.#..#.#.....##.#.#.###.#..#.#.#..#.#..#.#.#.#####.#.#.#..#.#.##.####.#.#..#.#.#..#.#.#.#.
.#.#.#..#.###.#.#.#.#.#.#..#.#.###.#..#.#.##.#.#.#..#.#.#...#.#.####.#.#####.#.#.#.....#.#.#.#.##.#..#....#.#.#.##.#.#.##.#.#.#.
.#.#.#.##...#.#.#####.#.#.##.#...#.#.##.#.####.#.#.##.#.#.#.#.#....#.#.....#.#.#.#.#.#.#####.#..#.#.##.#.##.#.#..#.#.#..#.#.#.#.
.#.#.#..#.#.#.#.....#.#.#..#.#.#.#.#..#.#....#.#.#..#.#.#.#.#.#.#.##.#.#.#.#.#.#.#####.....#.#.##.#..#.#..#.#.#.##.#.#.##.#.#.#.
.#.#.#.##.#.#.#.#.#.#.####.#.#.#.####.#.#.#.##.#.#.##.#.#.#.#...#..#.#.#.#.#.#.#.....#.#.#.###..#.#.#####.#.#.#..#####..#.#.#.#.
.#.#.#..#.#.#.#.#.#.#....#.#.#.#....#.#.#.######.#..#.#.#.#.#.#.#.####.#.#.#.#.#.#.#.#.#.#...#.##.#.#...#.#.#.#.##...#.######.#.
.#.#.#.##.#.#.#.#.#.#.#.##.#.#.#.#.##.#.#......#.##.#.#.#.#.#.#.#....#.#.#.#.#####.#.#.#.#.#.#..#.#...###.#.#.#..#.#.#......#.#.
.###.#..#.#.#.#.#.#.######.#.#.#.#..#.#.#.#.#.####..#.#.#.#.#.#.#.#.##.#.#.#.....#.#.#.#.#.#.#.##.#.#.##..#.####.#.#.#.#.#.##.#.
...#.#.##.#.#.#.#.#......#.#.#.#.#.##.#.#.#####..#.##.#.#.#.#.#.#.#..#.#.#.#.##.##.#.#.#.#####..#.#.#.#..##....#.#.#.#.#.#..#.#.
.#.#.#..#.#.#.#.#.#.#.#.##.#.#.#.#..#.###.......##..#.#.#.#.#.#.#.####.#.#.#..#..#.#.#.#.....#.##.#.#.#.####.#.#.#.#.#.#.#.##.#.
.#.#.#.##.#.#.#####.#.#..#.#.#.#.#.##...#.#.#.#..#.######.#.#.#.#....#.#.#.#.##.##.#.#.#.#.#.#..#.#.#.#....#.#.#.#.#.#.#.#..#.##
.#####.######.....#.#.#.####.#.#.#..#.#.#####.#.##......#####.#.#.#.##.#.#.#..#..#.#.#.#.#.#.#.##.#.#.#.#.##.#.#.#.#.#.#.#.##...
.....#......#.#.#.#.#.#....#.#.#.#.##.#.....#.#..#.#.#.##..####.#.#..#.#.#.#.##.##.#.#.###.#.#..#.#.#.#.####.#.#.#.###.#.#..##.#
.##.###.#.#.#.#.#.#.#.#.#.##.#.#.#..#.#.##.##.#.##.#.#..#.##..#.#.#.##.#.#.#..####.#.#...#.#.#.##.#####....#.#.#....#..#.##..#..
..#...#.#.#.#.#.#.#.#.#.#..#.#.#.#.##.#..#..#.#..#.#.#.##..#.##.#.#..#.#.#.#.##..#.#.#.#.#.#.#..#.....#.#.##.#.#.#.##.##..#.##.#
.##.#.#.#.#.#.#.#.#.#.#.#.##.#.#.####.#.###.#.#.##.#.#..#.##..#.#.#.##.#.#.#..#.##.#.#####.#.#.###.#.##.#..#.#.#.#..#.##.##..#..
..#.#.#.#.#.#.#.#.#.#.#.#.####.#....#.#...#.#.#..#.#.#.##.###.#.#.#..#.#.#.#.##..#.#.....#.#.#...#.#..#.#.##.#.#.#.##..#..#.##.#
.##.#####.#.#####.#.#.#.#....#.#.#.##.#.#.#.#.#.##.#.#..#...#.#.#.#.##.#.#.#..#.##.#.#.#.#.#.#.#.#.#.##.#.####.#.#..#.##.#####..
..#.....#.#.....#.#.#####.#.##.#.#..#.#.#.#.#.#..#.#.#.##.#...#.#.#..#.#.#.#.##..#.#.#.#.#.#.#.#.#.#..#.#....#.#.#.#####.....#.#
#.#.#.#.#.#.##.##.#.....#.#..#.#.#.##.#.#.#.#.#.##.#.#..#.#.#.#.#.#.##.#.#.#..#.##.###.#.#.#.#.#.#.#.##.#.#.######.....##.#.##..
..#.#.#####..#..#.#.#.#.#.#.##.#.#..#.#.#.#.#.#..#.#.#.##.#.#.#.#.#..#.#.#.#.##......#.#.#.#######.########......#.#.#..#.#..#.#
.##.#.....#.##.####.#.#.#.#..######.#.#.#.#.#.#.##.#.#..#.#.#.#.#.#.##.#.#.#..#.#.#.##.#.#.......#........#.#.#.##.#.#.##.#.##..
..#.#.#.#.#..#....#.#.#.#.#.##......#.#.#.#.#.#..#.#.#.##.#.#...#.#..#.#.#.#.##.#.#.####.#.#.#.#.#.#.#.#.##.#.#..#.#.#..#.#..#.#
.##.#.#.#.#.##.#.##.#.#.#.#..#.#.#.##.#.#.#.#.##.#.#.#..#.#.#.#.#.#.##.#.#.#..#.###....#.#.#.#.#.#.#.#.#..#.#.#.##.#.#.##.#.##..
..#.#.#.#.#..#.#..#.#.#.#.#.##.#.#..#.#.#.#.#..#.#.#.#.##.#.#.#.#.#..#.#.#.#.##..###.#.#.#.#.#.#.#.#.#.#.##.#.#..#.######.#..#.#
.##.#.#.#.#.##.#.##.#.#.#.#..#.#.#.##.#.#####.######.#..#.#.#.#.#.#.##.#.#.#..#.##.#####.#.#.#.#.#.#.#.#..######.#......#.#.##..
..#.#.#.#.#..#.#..#.#.#####.##.#.####.#.....#......#.#.######.#.#.#..#.#.#.#.##..#.....#.#.#.#.#.#.#.#.#.##....#.#.#.#.##.#..#.#
.##.#.#.###.##.#.##.#.....#..#.#....#.##.#.##.#.##.#####....#.#.#.#.##.#.#.#..#.##.#.#...#.#.#.#.#.#.#.#..#.#.##.########.#.##..
..#.#.#..#...#.#..#.#.#.#.#.##.#.#.##..#.#.####..#.....#.#.##.#.#.#..#.#.#.#.##..#.#.#.#.#.#.#.#.#.#.#.#.##.#..#........#.#..#.#
.##.#.##.#.#.#.#.####.#####..#.#.#..##.#.#....#.##.#.#.#.#..#.#.#.#.##.#.#.#..#.##.#.#####.#.#####.#.#.######.##.#.#.#.##.#.##.#
..#.#..#.#.#.#.#...#......#.####.#.##..#.#.#.##..#.###.#.#.##.#.#.#..#.#.#.#.#####.####..#.#....####.#........####.#.#..#.###...
.##.#.##.#.#.#.##.###.#.#.#....#.#..#.##.#.#..##.#...#.#.#..#.#.#.#.##.#.#.#.#........#.#####.#....#.#.##.#.#....#.#.#.##...#.#.
..#.#..#.#.######...#.#.#.#.#.##.#.#####.#.#.##..#.#.#.#.#.##.#.#.#..#.#.#.#.#.#.#.#.##.....#.#.#.##.#..#.###.#.##.#.#..#.#.#.#.
.##.#.##.#......#.#.#.#.#.#.#..#.#.....#.#.#..#.##.#.#.#.####.#.###.##.#.#.#.#.#.#.#....#.#.#.#.#..#.#.##...#.#..#.#.#.##.#.#.#.
..#.#..#.#.#.#.##.#.#####.#.#.##.#.#.#.#.#.#.##..#.#.#.#....#.#..#...#.#.#.#.#.#.#.#.##.#.#.#.#.#.##.#..##.##.#.##.#.#.########.
.##.#.##.#####..#.#.....#.#.#..#.#.#.#.#.#.#..#.##.#.#.##.#####.##.#.#.#.#.#.#####.#..#.#.#.#.#.#..#.##..#..#.#..#.#.#........#.
###.#..#....###.#.#.#.#.#.#.#.##.#.#.#.#.#.#.##..#.#.#........#..#.#.#.#####.....#.#.##.#.#.#.#.#.##..#.##.##.#.##.#.#.#.#.#.##.
..#.#.##.##...#.#.#.#.#######..#.#.#.#.#.#.#..#.##.#.#.#.#.#.##.##.#.####..#.##.##.#..#.#.#.#.#.#..##.#.#...#.#..#.#.#.#####..#.
.##.#..#..#.#.#.#.#.#.......#.##.#.#.#.#####.##..#.#.#.#.#.#..#..#.#....#.##..#..#.#.##.#.#.#.#.#.##..#.#.#.#.#.######.....#.##.
..#.#.##.##.#.#.###.#.#.##.##..#.#.#.###...#..#.####.#.#.#.#.##.##.#.#.##..#.##.##.#..#.#.#.#.#.#..#.##.#.#.#.#.....###.##.####.
.##.#..#.####.#...#.#.#..#..#.##.#.#...#.#.#.##....#####.#.#.#####.#.#..#.##..#..#.#.##.#.#.#.#.#.##..#.#.#.#.#.#.#...#..#....#.
..#.#.##....#.##.##.#.#.##.##..#.#.#.#.#.#...###.#.....#.#.#.....#.#.#.##....##.##.#..#.#.#.#.#.#..#.######.#.#.#.##.##.##.#.##.
.##.#.###.#.#..#..#.#.#..#..#.##.#.#.#.#.#.#...#.#.#.#.#.#.#.##.##.#.#..#.#.###..#.#.##.#.#####.#.##......#.#.#.#..#..#..#.#..#.
..#.#...#.#.#.###.#.#.#.##.#####.#.#####.#.#.#.#.#.#.#.#.#.#..#..#.#.#.##.#...#.##.#..#.#.....#.#..#.#.#.####.#.#.##.##.##.#.##.
.##.#.#.#.#.#.#...#.#.#..#.....#.#.....#.#.#.#.#.#.#.#.#.#.#.###.#.#.#..#.#.#.#..#.#.##.#.#.#.#.#.##.#.#...####.#..#..#..#.#..#.
....#.#.#.#.#.#.#.#.#.#.##.#.###.#.#.#.#.#.#.#.#.#.#####.#.#...#.#.####.#.#.#.#.##.#..#.#.#.#.#.#..#.#.#.#....#.#.##.##.####.##.
.#.####.#.#.#.#.#.#.#.#..#.#...#.#.#.#.#.#.#.#.#.#.....#.#.#.#.#.#....#.#.#.#.#..#.#.##.#.#.#.#.#.##.#.#.#.#.##.#..#..#....#..#.
.#....#.#.#.#.#.#.#.#.#.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.##.#.#.#.#.#.##.#..#.#.#.#.#.#..#.#.#.#.#..#.#.##.##.#.##.##.
.#.#.##.#.#.#.#.#.#.#.#..#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#..#.#.#.#.#.####.#.##.#.#.#.#.#.##.#.#.#.#.##.#..#..#.#.##..#.
.#.#..#.#.#.#.#.#.#.####.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.######.#.#....#.#..#.#.#.#.#.#..#.#.#.#.#..#.##.##.#####..##.
.#.#.##.#.#.#.#.#.#....#.#.#.#.#.#.#.#.#####.#.#.#.#.###.#.#.#.#.#......#.#.#.##.#.#.##.#.#.#.#.#.##.#.#.#.#.##..#..#.....#.###.
.#.#..#.#.#.#.#.#.##.#.#.#.#.#.#.#.#.#....####.#.#.#..#..###.#.#.#.#.#.##.#.#..#.#.#.####.#.#.#.#..#.#.#.#.#..#.##.##.#.#.#...#.
.#.#.##.#.#.#.#####..#.#####.#.#.#.#.#.#.##..#.#.#.#.##.##...#.#.#.#.#..#.#.#.##.#.#....#.#.#.####.#.#.#####.##..#..#.#.#.#.#.#.
.#.#..#.#.#.#.....#.##.....#.#####.#.#.#..#.##.#.#.#..#..##.##.#.#.#.#.##.#.#..#.#.#.#.##.#.#....#.#.#.....#..#.##.######.#.#.#.
.#.#.####.#.##.#######.#.#.#.....#.#.#.#.##..#.#.#.#.##.###..#.#.#.#.#..#####.######.#..#.#.#.#.##.#.#.#.#.#.##.##......#.#.#.#.
.#.#....#.#..#.......#.#.###.##.##.#.#.#..#.##.#.#.#..#...#.####.#.#.#.##...#......#.#.##.#.#.#..#.#.#.#.#.#..#.#..#.#.##.#.#.#.
.#.#.#.##.#.##.#.#.#.#.#...#..#..#.#.#.#.##..#.#.####.#.#.#....#.#####..#.#.#.#.#.##.#..#.#.#.#.##.#.#.#####.##.#.##.#.####.#.##
.#.#.####.#..#.#.#.#.#.#.#.#.###.#.#.#.#.###.#.#....#.#.#.#.#.##.....#.##.#.###.#..#.#.##.#.#.#..#.#.#.....#..#.#..#.#....#.#...
.#.#....#.#.##.#.#.#.#.#.#.####..#.#.#.#...#.#.#.##.#.#.#.#.####.#.#.#..#.#...#.#.##.#..#.#.#.##.#.#.#.#.#.#.#####.#.#.#.##.##.#
.#.#.#.##.#..#.#.#.#.#.#.#....#.##.#.#.#.#.#.#.#..#.#.#.#.#....#.#.#.#.##.#.#...#..#.#.##.#.#..#.#.#.#.#.#.#.....#.#.#.#..#..#..
.#.#.#..####.#.#.#.#.#.#.#.#.##..#.#.#####.#.#.#.##.#.#.#.#.#.##.#.#.#..#.#.#.#.#.##.#..#.#.#.##.#.#.#.#.#.#.#.#.#.#.#.#.##.##.#
.#.#.#.##..#.#.#.#.#.#.#.#.#..#.##.#.....#.#.#.#..#####.#.#.#.#########.#.#.###.#..#.##.#.######.#.#.#.#.#.#.#.#.#.#.#.#..#..#..
.#.#.#..#.##.#.#.#.#.#.#.#.#.##..#.#.#.#.#.#...##.....#.#.#.#.........#.#.#..#..#.##..#.#......#.#.#.#.#.#.#.#.#.#.#.#.#.###.#.#
.#####.##..#.#.#.#.#.#.#.#.#..#.##.#.#.#.#.#.#..#.#.#.#.#.#.#.#.#.#.#####.#.###.#..#.##.#.#.#.##.#.#.#.#.#.#.#.#.#.#.#.#...#.#..
.....#..#.##.#.#.#.#.#.#.#.#.##..#.#.#.#.#.#.#.####.#.#.#.#.#.#.#.#.....#.#...#.#.#####.#.#.#..#.#.#.#.#.#.#.#.#.#.#.#.#.#.####.
.#.####.#..###.#.#.#.#.#.#.#.###.#.#.#.#.#######..#.###.###.#.#.#.#.#.#.#.#.#.#.#.....#.#.#.#.##.#.#.#.#####.#.#.#.#.#.#.#....#.
.#....#.#.##...#.#.#.#.#.#.#...#.#.#.#.#.......#.##...#..#..#####.#.#.#.#.#.#.#.#.#.#####.#.#..#.#.#.####..#.#.#.#.#.#.#.#.#.##.
###.#.#....#.#.#####.#.#.#.#.#.#.#.#.#.#.##.#.##.##.#.#.##.##...#.#####.###.#.#.#.#.....#.#.#.##.#.#....#.##.#.###.#.#.#.#.#..#.
..#.#####.##.#.....#.#.#.#.#.#.#.#.#.#.#..#.#.....#.#.#..#..#.#.#....#....#.#.#.#.#.#.#.#.#.#..#.#.#.#.##..#.#..#..#.#.#.#.#.##.
.####......#.#.#.#####.#.#.#.#.#####.#.#.##.#.#.#.#.#.#.##.##.#.#.#.##.#.##.#.#.#####.#.#.#.#.##.#.#.#..#.##.#.##.##.#.#.#.#..#.
....#.#.#.##.#.#.....#.#.#.#.#....####.#..#.#.#.#.#.#.#.#####.#.#.#########.#.#.....#.#.#.#.#..#.#####.##..#.#..#..#.#.#.#.#.##.
.#.##.#.#..#.#.#.#.#.#.#.#.#.#.#.##..#.#.##.#.#.#.#.#.#.......#.#.......#.#.#.#.#.#.#.#.#.#.#.##.....#..#.##.#.##.####.#.#.#..#.
.#..#.#.##.#.#.#.#.#.#.#.#.#.#.#..#.##.#..#.#.#.#.#.#.#.#.#.#.#.#.#.#.#...#.#.#####.#.#.#.#.#..#.#.#.#.##..#.#..#....#.#.#.##.#.
.#.##.####.#.#.#.#.#.#.#.#.#.#.#.##..#.#.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.....#.#.#####.##.#.#.#.#..#.##.#.##.#.##.#.#..#.#.
.#..#....#.#.#.#.#.#.#.#.#.#.#.#..#.##.#.####.#.#.#.#.#.#.#.#.#####.#.#.#.#.#.#.#.#.#.....#..#.#.#.#.#.##.####..#.#..#.#.#.##.#.
.#.##.#.##.###.#.#.#.#.###.#.#.#.##..#.#....#.#.#.#.#.#.#.#.#.....#.#.#.#.#.#.#.#.#.#.#.#.#.##.#.#.######....#.##.#.##.#.#..#.#.
.#..#.#..#..#..#.#.#.#...#.#.#.#..#.##.#.#.##.#.#.#.#####.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#..#.#.#......#.#.##..#.#..#.#.#.##.#.
.#.##.#.##.##.######.#.#.#.#.#.#.##.##.#.#..#.#.#.#.....#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.##.#.#.#.#.##.#....##.#.##.#.#..#.#.
.#..#.#..#..#......#.#.#.#######.....#.#.#.##.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#..#.#.#.#.#..#.#.##..#.#..#.#.##.#.#.
.#.##.#.##.###.#.#.#.#.#.......#.#.#.#.######.#.#####.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.####.#.#.#.##.#..#.##.#.##.#..#.#.#.
.#..#.#..#...#.#.#.#.#.#.#.#.#.#.########...#.#.....#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#....#.#.#.#..#.#.##..#.#..#.#.####.#.
.#.##.#.##.#.#####.#.#.#.#####.#........#.#.#.#.#.#.###.###.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.####.#.#.##.#..#.##.#.##.###..#.#.
.#..#.#..#.#.....#.#.#.#.....#.#.#.#.#.##.#.#.#.#.#..#....###.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#....#.#.#..#.#.##..#.#..#.....##.#.
.##.#.#.##.#.##.####.#.#.#.#.#.#.#.#.#..#.#...#.#.#.##.#.##...#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.####.#.##.#..#.##.#.##.#.#..#.#.
..#.#.#..#.#..#....#.#.#.#.#.#.#.#.#.#.#####.##.#.#..#.####.#####.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#....#.#..#.#.##.##.#..#.#.#.##.#.
.##.#.#.##.#.##.#.######.#.#.#.#.#.#.#.....#..#.#.#.##....###...#.#####.#.#.#.#.#.#.#.#.#.#.#.#.#.##.#.##.#.####..#.##.#.#..#.#.
..#.#.#..#.#..#.#......#.#.#.#####.#.##.#.##.##.#.#..#.##...##.##.....#.#.#####.#.#.#.#.#.#.#####..#.#..#.#....#.##..#.#.#.##.#.
.##...#.##.#.####.#.#.######.....#.#..#.#..#..#.#.#.##.###.###.##.#.#.#.#.....#.#.#.#.#.#.#.....#.##.#.##.#.#.##..#.##.#.#..#.#.
..#.#.#..#.#...####.#......#.#.######.#.#.###.###.#..#...#......#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#..#.####.#.#..#.##..#.#.#.##.#.
.##.#.#.##.#.#....#.#.#.#.##.#......#.#.#.#.....#.#.##.#.#.#.#.##.#.#.#.#.#.#.#.###.#.#.#.#.#.#.#.##....#.#.#.##..#.##.#.#..#.#.
..#.#.#..#.#.#.#.##.#.#.#..#.#.##.#.#####.#.#.#.#.#..#.#.#.#.#.####.#.#.#.#.#.#...#.#.#.#.#.#.######.##.#.#.#..#.#####.#.#.##.#.
.##.#.#.##.#.#.#..#.#.#.#.##.#..#.#.....#.#.#.#.#.#.##.#.#.#.#....#.#.#.#.#.#.#.#.#.#.#.#.#.#......#..#.#.#.#.##.....#.#.#..#.#.
```
] |
[Question]
[
I came across this challenge from codewars. I wish to know how to solve this problem. The problem description is given below.
Its elements are in range[1..n^2]. The matrix is filled by rings, from the outwards the innermost. Each ring is filled with numbers in the following way:
1. The first number is written in the top left corner;
2. The second number is written in the top right corner;
3. The third number is written in the bottom right corner;
4. The fourth number is written in the bottom left corner;
5. Each next number is written next to the number written 4 steps before it,
until the ring is filled.
The matrix is constructed when all numbers are written.```
Given the size of the hole, return the number written at (`a, b`) - you may use any consistent indexing, but please specify if (`a, b`) is anything other than 0-indexed and row-major.
# Example
For `n = 4, a = 1, b = 1`, the output should be `13`.
The hole looks like this:
```
[ [ 1, 5, 9, 2 ]
[ 12, 13, 14, 6 ]
[ 8, 16, 15, 10 ]
[ 4, 11, 7, 3 ]
]
The element at (1, 1) is 13
```
### Test cases
(`a, b`) is 0-indexed and row-major here.
```
n a b result
1 0 0 1
2 0 0 1
3 0 0 1
4 0 0 1
2 0 1 2
3 0 1 5
3 1 1 9
4 1 1 13
4 2 1 16
5 2 3 22
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~120~~ ~~119~~ 90 bytes
```
def f(n,a,b):n-=1;A,B,C=min((a,b,1),(n-b,a,2),(n-a,n-b,3),(b,n-a,4));return(n-A)*4*A+4*B+C
```
[Try it online!](https://tio.run/##hc3NCoMwDAfw@56isEvrIqwfDjbxoD6JZcqELZOuHvb0XdRRkCEr/CH5NSTD29@eqEK4th3rOEIDVlwwLWReQgV18eiRc0KQAjimlgbUXDUwdZpqC1NnhMhd60eH9FmKxCTlwSTVoQ57tjykNBRLce1rvPvd4Hr0dFcCY8cpgtG0jK42XG@4@bNHzq5@9iyerVxGP6/2R5d65Sr6KXr2dT25UuED "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 87 bytes
```
def f(n,a,b):A,B=min((a,b+1/4),(n+~b,a+.5),(n+~a,n-b-1/4),(b,n-a));return(n+~A)*4*A+B*4
```
[Try it online!](https://tio.run/##hc3NCsIwDAfwu09R8NKundqPCSoetjdpccOBxlG7gxdfvbZ2bAwZBv6Q8AtJ93LXB0jvL3WDGgxMM0OOJavO9xYwDhPlW0UYBvo2TNNNkXrNIDd5IhN6TcjJ1q63ELUkmcpKWmXKr1EqCNEhJg62fvY3t@psCw43mDOEdjGEoLDPRxBLIJdA/TvFE4ifUwMUM@ATHGY/JuByBmKC/QjFAPILQvgP "Python 3 – Try It Online")
Returns a float
-3 bytes, thanks to Arnauld
---
### Explanation:
This takes advantage of the fact that there is some symmetry to the matrix.
The matrix can be split into four quarters, which are equal when rotated (+ an offset of 1-3).
[](https://i.stack.imgur.com/PW3oo.png)
The first part `A,B,C=...` finds out which quarter the current coordinates are in, by finding the smallest coordinates, relative to each quarter:
[](https://i.stack.imgur.com/IPsX9.png)
(green: `(a,b)`, yellow: `(n-b,a)`, red: `(n-a,n-b)`, blue: `(b,n-a)`)
The coordinate pair is then converted to a value:
`(0,0) = 1`, `(0,1) = 5`, and so on; each coordinate is `4` larger than the previous.
`sum((n-(i*2))*4for i in range(A))` skips the rows above, `+(B-A)*4` moves along the row, and `+C` adds the offset.
`sum((n-(i*2))*4for i in range(A))+(B-A)*4+C` is shortened to `(n-A)*4*A+4*B+C`
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~36~~ ~~31~~ ~~28~~ 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
<αìRDÀsā)ø{н`Š4*ŠD¹<α4**O
```
Port of [*@TFeld*'s Python answer](https://codegolf.stackexchange.com/a/181396/52210), so make sure to upvote him!
-3 bytes thanks to *@Emigna*.
Inputs are \$n\$ and \$[a,b]\$.
Uses the legacy version instead of the new 05AB1E version, because there seems to be a bug with the sorting (`{`) of multidimensional lists.
[Try it online](https://tio.run/##MzBNTDJM/f/f5tzGw2uCXA43FB9p1Dy8o/rC3oSjC0y0ji5wObQTKGeipeX//78pV7SRjnEsAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfWVCWGikS8R/m3MbD68JcjncUHykUfPwjuoLexOOLjDROrrAJQIoZaKl5f9f5390tKFOtIGOQWysjkK0EYJpjGCaoCkwRCiAMw2hTBMUphGUaQpiGsOYBjomMKYJMtMAodYoNjYWAA).
**Explanation:**
```
< # Decrease the (implicit) input `n` by 1
α # Take the absolute difference with the (implicit) input-list
# (we now have `[n-1-a, n-1-b]`)
ì # Prepend the input (we now have `[n-1-a, n-1-b, a, b]`)
R # Reverse the list (we now have `[b, a, n-1-b, n-1-a]`)
DÀ # Duplicate this list, and rotate it once towards the left
s # Swap these two lists
ā # Push a list in the range [1, length_list] without popping the list: [1,2,3,4]
) # Wrap all three lists into a list (we now have
# `[[a, n-1-b, n-1-a, b], [b, a, n-1-b, n-1-a], [1, 2, 3, 4]]`)
ø # Zip/transpose; swapping rows/columns (we now have
# `[[a, b, 1], [n-1-b, a, 2], [n-1-a, n-1-b, 3], [b, n-1-a, 4]]`)
{н # Get the minimum by sorting the lists and getting the first inner list
# (since the minimum builtins in 05AB1E flatten multidimensional lists
# and give a single integer)
` # Push all three values to the stack: `A`, `B`, and `C`
Š # Triple-swap once, so the order is now `C`, `A`, `B`
4* # Multiply `B` by 4
Š # Triple-swap again to `B*4`, `C`, `A`
D # Duplicate `A`
¹<α # Take the absolute difference with `n-1` (so basically `n-1-A`)
4* # Multiply that by 4
* # Multiply it with the duplicated `A`
O # Sum all values on the stack (`B*4 + C + (n-1-A)*4*A`)
# (and output the result implicitly)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
```
³_1ị’;1×4
’0;_ⱮpƝẎAµżJṂFµæ.Ç
```
[Try it online!](https://tio.run/##AT8AwP9qZWxsef//wrNfMeG7i@KAmTsxw5c0CuKAmTA7X@KxrnDGneG6jkHCtcW8SuG5gkbCtcOmLsOH////Nf8yLDM "Jelly – Try It Online")
Based on [@TFeld’s python answer](https://codegolf.stackexchange.com/a/181396/42248) so be sure to upvote that one too.
[Answer]
# JavaScript (ES6), 86 bytes
```
(w,y,x)=>[x+(Y=w+~y)*y,y+(w+=~x)*x,w+Y*y,Y+w*x][k=x<y?x>Y?2:3:x<Y?0:x>y?1:Y-y&&2]*4-~k
```
[Try it online!](https://tio.run/##jc3dCoIwHAXw@57CK9ncTDc1SJw@xxAvxDJK0cho/9346iZ9IGVIcK7OD8455be8Ky7H89Vu2t1@KMWAFNUUsIhTIEgKRXqNLU01QYqIHrAFVBE5NpIoC7K0EhDpBGKZ8NALIZKJG0KsExZKW5smzyzf7quhaJuurffruj2gEjFquGMwNhzHMNjqU/mieovq/7HMXsp/Lr81mCubdDv/nZR5c@WTbr40eKj3VM6HOw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ZUẎTḢṬ_Ʋṁ
+þ`ṠÇƬSœị@
```
A dyadic Link accepting `n` on the left and `[a,b]` (1-indexed) on the right.
**[Try it online!](https://tio.run/##ATQAy/9qZWxsef//WlXhuo5U4bii4bmsX8ay4bmBCivDvmDhuaDDh8asU8WT4buLQP///zj/Mywy "Jelly – Try It Online")**
### How?
```
ZUẎTḢṬ_Ʋṁ - Link 1, next matrix (rotated): current matrix
Z - transpose }
U - reverse each row } -> rotate clockwise 1/4
Ẏ - tighten into a flat list of values
Ʋ - last four links as a monad:
T - truthy indices -- e.g. [0,0,1,0,1,1,0] -> [3,5,6]
Ḣ - head (empty list yields 0) -> 3
Ṭ - un-truth (0 yields an empty list) -> [0,0,1]
_ - subtract (vectorises) -> [0,0,0,0,1,1,0]
ṁ - mould to shape of the current matrix again
+þ`ṠÇƬSœị@ - Main Link: integer, n; list of integers [a,b]
` - using left (n) as both arguments:
þ - table of (implicit range of integer arguments)
+ - addition
Ṡ - sign -- now we have an n by n matrix of ones
Ƭ - collect up (a list of matrices) while results are different with:
Ç - last Link (1) as a monad
¬ - logical NOT (replace the 1s with 0s and vice-versa)
S - sum (vectorises)
@ - with swapped arguments:
œị - multidimensional index into
```
[Answer]
# Rust - 340 bytes
```
fn f(n:usize,x:usize,y:usize)->usize{let (mut r,d)=(0,(n-1)&1);for l in ((1+d)..=n).step_by(2) {let (mut i,m,mx,mut z)=(0,l/2,n/2,0);loop {z=4*i+n*n-l*l;let u=[mx+m-i-d,mx-m,mx+m-d,mx-m+i];if (x,y)==(u[0],u[1]){r=z+4}if (x,y)==(u[2],u[0]){r=z+3}if (x,y)==(u[3],u[2]){r=z+2}if (x,y)==(u[1],u[3]){r=z+1}i+=1;if i>=l-1{break};}}r}
```
still got some work to do, but it basically draws the whole spiral, centered on a point in the middle, and saves the value at requested point x,y.
[ungolf spiral draw at play.rust-lang.org](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0aa0d8e4f9a26a73742241f2c70a6f27)
] |
[Question]
[
Given a list (array) of names, your challenge is to join the items using some glue and abbreviate the longest items first until the joined string fits a maximum length. And output that string. Since the glue is part of the final string, the length of the glue is included too
Abbreviation is done using the [`…` character](http://www.fileformat.info/info/unicode/char/2026/index.htm)
**Examples**
For example when `|` is the glue and 20 is the maximum length
* `giraffe` would become `giraffe` (length = 7)
* `giraffe, Spiny lumpsucker` would become `giraffe|Spiny lumps…` (length = 20)
* `giraffe, Spiny lumpsucker, rhinoceros` would become `giraf…|Spiny…|rhino…` (length = 20)
* `giraffe, Spiny lumpsucker, rhinoceros, Hellbender` would become any of these:
+ `gira…|Spi…|rhi…|Hel…`
+ `gir…|Spin…|rhi…|Hel…`
+ `gir…|Spi…|rhin…|Hel…`
+ `gir…|Spi…|rhi…|Hell…` (all length = 20)
**Rules**
The list, glue and maximum length are input parameters of the program.
When abbreviation is needed, abbreviation must be done on any of the longest items first. When the longest items are equally long, it doesn't matter which you abbreviate.
The output length is smaller than the maximum length when no abbreviation was necessary. When abbreviation needs to occur, the length of the output is exactly equal to the maximum length.
The order of the (abbreviated) items must match the order of the items in the input
You can't assume that the abbreviation character `…` and the glue won't occur as characters in the items in the list.
**Update**
I'm afraid that I overlooked the fact that the length of the glue concatenated with many items by itself may result into a string that is longer than the allowed maximum length. Without considering this, your program may run into an infinite loop. I prefer your program to throw an error in this case. I hope that's not too much of an inconvenience for the ones who already wrote an answer or that are busy writing one. To throw an error is NOT a requirement to win, but I would appreciate if you add a variant that does.
**The winner**
This is code-golf, so the shortest valid answer – measured in bytes – wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes
```
ṖṖ;⁽÷ẓỌµ€µL€MḢµ¦µj⁴L>⁵ð¿j
```
[Try it online!](https://tio.run/##y0rNyan8///hzmlAZP2oce/h7Q93TX64u@fQ1kdNaw5t9QGSvg93LDq09dCyQ1uzHjVu8bF71Lj18IZD@7P@//8frZSeWZSYlpaqpKOgFFyQmVepkFOaW1BcmpydWgQSK8rIzMtPTi3KLwbxPIC2JaXmpQDlYv/X/DcyAAA "Jelly – Try It Online")
This unfortunately does not contain the error-if-invalid feature.
### Explanation
This is what I call the *Jelly syndrome*: the easy part is explaining the algorithm, the hard part is explaining how you found the exact order to put the code in to make it execute correctly.
```
ṖṖ;⁽÷ẓỌµ€µL€MḢµ¦µj⁴L>⁵ð¿j
¿ While
j joining the input list
⁴ with the glue produces a string
L whose length
> is larger than
⁵ the maximum,
¦ in the input array at the
Ḣ first of the positions that
M have maximal
L€ length,
ṖṖ remove the last two characters,
; append
⁽÷ẓ the number 8230
Ọ and cast it to a character.
j Finally, join again with the glue.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes
```
[гýDg²›≠#\Déθ©k®¨¨"…"«sǝ
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/@vCEQ5sP73VJP7TpUcOuR50LlGNcDq88t@PQyuxD6w6tOLRC6VHDMqVDq4uPzwUqVk/PLEpMS0tV11FQDy7IzKtUV1DPKc0tKC5Nzk4tAokWZWTm5SenFuUXg3geqTk5Sal5KUC5WC4jA64aAA "05AB1E – Try It Online")
[Answer]
# JavaScript (ES6), ~~153~~ 152 bytes
```
(a,g,n)=>eval(`while(a.join('')#>n-2*a#+1+a#==1){for(i=n;x=a.findIndex(w=>w#==i),i--&&!~x;);a[x]=a[x].slice(0,-2)+'…'}a.join(g)`.split`#`.join`.length`)
```
```
f=(a,g,n)=>eval(`while(a.join('')#>n-2*a#+1+a#==1){for(i=n;x=a.findIndex(w=>w#==i),i--&&!~x;);a[x]=a[x].slice(0,-2)+'…'}a.join(g)`.split`#`.join`.length`)
console.log(
f(['giraffe'], '|', 7),
f('giraffe, Spiny lumpsucker'.split`, `, '|', 20),
f('giraffe, Spiny lumpsucker, rhinoceros'.split`, `, '|', 20),
f('giraffe, Spiny lumpsucker, rhinoceros, Hellbender'.split`, `, '|', 20)
)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 102 bytes
```
def f(l,n,g):
while len(g.join(l))>n:i=l.index(max(l,key=len));l[i]=l[i][:-2]+'…'
return g.join(l)
```
[Try it online!](https://tio.run/##PY0xDsIwEAR7XnGdbWEiFLqgUNNTIoqQnJOD42I5jiASBa/hYXzEhIZmthnt@Cl2vWxSatCB02zFtqZYwL0jRmAU3WaXnkSzMTspqOSMpMGHvlWP2b7iVM6SMVs@0qn84Vis8tNSfV5vtYCAcQwC/4/kA0nUTquWQuUcWjh4kgl4vPlhrK8YLISOpK8x9IOFPTKfcS4GlQ2eKWplQRkL@XrepzImfQE "Python 3 – Try It Online")
Alternatively if you want to see the result being shortened over time:
```
def f(l,n,g):
while len(g.join(l))>n:i=l.index(max(l,key=len));l[i]=l[i][:-2]+'…';yield g.join(l)
```
[Answer]
## JavaScript (ES6), 91 bytes
```
a=>n=>g=>f=(l=n,r=a.join(g))=>r[n]?f(l-!a.some((s,i)=>s[l]&&(a[i]=s.slice(0,-2)+'…'))):r
```
Uses currying i.e. `F(A)(N)(G)()`. Explanation: No string can have a length of more than `n` and still fit, so without loss of generality the overlong length `l` starts off at `n`. Each recursive call then checks whether the strings fit. If not, then the first overlong string found is trimmed, otherwise the overlong length is decremented when all strings have been trimmed to that length.
] |
[Question]
[
***Note:*** When I refer to a bridge, I mean it in the non-mathematical sense
## Introduction
You are on a network of islands which are connected by wooden bridges and you want to see if you can burn every bridge in the island network. However, you can only burn a bridge once you've walked over it.
Once a bridge has been burned, it has gone and you cannot go back over it. None of the islands are connected.
Since you are going on a stroll, you cannot swim.
## Challenge
Given a list of the bridges and which islands they connect, output a truthy value if you can burn every bridge and falsey value if you cannot.
## Input
The input will be a list of numbers. A bridge is defined as:
```
X,Y
```
Where are X and Y are integers. Each bridge has an integer number which X and Y refer to.
For example,
```
2,6
```
Means that there is a bridge between the islands 2 and 6.
The input will be a list of these bridges:
```
2,6 8,1 8,2 6,1
```
You may take this a flat array, if you wish.
## Rules
The numbers for the islands will always be positive integers, `n`, where `0 < n < 10`. The island numbers will not always be contiguous.
When you walk over a bridge, you ***must*** burn it.
You will be given a maximum of eight islands. There is no limit on the number of bridges.
Island networks will always connect together. There will always be exactly one connected component.
This is an undirected network. For example, you can go either way across the bridge `1,2`.
## Examples
```
Input > Output
1,2 1,3 1,3 1,4 1,4 2,3 2,4 > Falsey
1,5 1,6 2,3 2,6 3,5 5,6 > Truthy
1,2 1,3 1,4 2,3 2,4 3,4 > Falsey
1,2 > Truthy
```
## Winning
Shortest code in bytes wins.
[Answer]
# Mathematica, ~~27~~ 26 bytes
Assuming that it is a connected graph.
```
Tr@Mod[Last/@Tally@#,2]<3&
```
Takes a flat list as input.
Example:
```
In[1]:= Tr@Mod[Last/@Tally@#,2]<3&[{1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 2, 3, 2, 4}]
Out[1]= False
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~102 92~~ 43 bytes (40 in Python 3)
Thanks to @Neil for reminding me that you can't have an odd number of vertices with odd degree – and saving 5 bytes.
```
lambda x:sum(x.count(a)%2for a in set(x))<3
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8Q2JzE3KSVRocKquDRXo0IvOb80r0QjUVPVKC2/SCFRITNPoTi1RKNCU9PG@H9BUWZeiUKJRrShjpGOoY4xFJuAsRGQbaRjEqvJhaTMFChlBpUyA5KmQGiGqsQIbgrUBCCJZopRrOZ/AA "Python 2 – Try It Online")
You can cut it down to 40 bytes in Python 3 (thanks to @shooqie):
```
lambda x:sum(x.count(a)%2for a in{*x})<3
```
A graph has a Eulerian trail iff the number of vertices with odd degree is 0 or 2.
This takes the input as a flat list, as explicitly allowed by the spec.
This assumes all of the islands are connected.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Qċ@€%2S<3
```
[Try it online!](https://tio.run/##y0rNyan8/z/wSLfDo6Y1qkbBNsb///@PNtQxigUA "Jelly – Try It Online")
Port of rogaos's Python answer. If you upvote this answer, please [upvote that one too](https://codegolf.stackexchange.com/questions/128425/burning-bridges/128434#128434). :)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~14 11~~ 10 bytes
```
>3sm%/Qd2{
```
[Try it online!](https://tio.run/##K6gsyfj/3864OFdVPzDFqPr//2hDHSMdQx1jKDYBYyMg20jHJBYA "Pyth – Try It Online")
My first Pyth program! I'm sure it could be golfed a great deal.
Thanks to @Rod for saving 1 byte by using `Q` implicitly.
Same general idea as my Python answer.
] |
[Question]
[
In my [last challenge](https://codegolf.stackexchange.com/q/87189/52405), you were asked to find *all* rectangles given a `m x n` grid of them. However, it turned out to be very trivial as there actually was a mathematical formula I did not even know about to solve the problem! So now, for a little bit more of a challenge, how about calculating the number of *unique* rectangles, i.e. find the number rectangles that are all of different dimensions?
For example, consider 4 horizontal, or `y` lines at `[-250,-50,50,250]` and 4 vertical, or `x` lines at `[-250,-70,70,250]`. Graphing these on a coordinate plane with infinite dimensions results in the following `500 x 500` pixel closed grid, in which the length of each segment in pixels and the lines corresponding to their respected values from the arrays are shown:
[](https://i.stack.imgur.com/kGGUd.png)
which contains the `16` *unique* rectangles shown in this animated GIF:
[](https://i.stack.imgur.com/XW3FA.gif)
However, if the topmost line (`y = 250`) were to be removed, there would only be `12` unique rectangles, as the top 3 rectangles would be factored out since they each won't be fully closed without the `y = 250` line.
## Task
So, as shown above, the task is counting the number of rectangles rectangles with *different dimensions*. In other words, given an input of 2 arrays, with the first one containing all equations of all `x` lines, and the latter containing those of all `y` lines, output the total number of rectangles of *different dimensions* created when the lines corresponding to those equations are graphed on a coordinate plane.
## Rules
* The use of any built-ins that directly solve this problem is explicitly disallowed.
* If either of the arrays have less than `2` elements, the output should be `0`, since if there are less than `4` lines on the plane, there are no closed, `4` sided figures.
* The input arrays are *not* guaranteed to be sorted.
* You can assume that there are not any repeated values in either of the the input arrays.
* A `n x m` rectangle is the same as a `m x n` rectangle. For example, a `300 x 200` rectangle is the same as a `200 x 300` one.
* Standard loopholes are prohibited.
## Test Cases
Given in the format `Comma Separated Arrays Input -> Integer output`:
```
[],[] -> 0
[-250,-50,50,250],[-250,-70,70,250] -> 16 (Visualized above)
[-250,-50,50,250],[-250,-70,70] -> 12
[-40, 40],[-80, 50] -> 1
[10],[10] -> 0
[60, -210, -60, 180, 400, -400], [250, -150] -> 12
[0,300,500],[0,300,500] -> 6
[0,81,90],[0,90,100] -> 9
```
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Answer]
# JavaScript (ES6), 99
```
(X,Y,Z=new Set)=>X.map(v=>X.map(t=>t>v&&Y.map(w=>Y.map(u=>u>w&&Z.add([u-w,t-v].sort()+0)))))|Z.size
```
Note: `sort` is not numeric but lexicographic, but in this specific case I don't care
**Less golfed**
```
(X, Y, Z = new Set) =>
X.map(
v => X.map(
t => t>v && Y.map(
w => Y.map(
u => u>w && Z.add([u-w, t-v].sort() + 0)
)
)
)
) | Z.size
```
**Test**
```
F=(X,Y,Z=new Set)=>X.map(v=>X.map(t=>t>v&&Y.map(w=>Y.map(u=>u>w&&Z.add([u-w,t-v].sort()+0)))))|Z.size
;[
[[],[], 0]
,[[-250,-50,50,250],[-250,-70,70,250], 16]
,[[-250,-50,50,250],[-250,-70,70], 12]
,[[-40, 40],[-80, 50], 1]
,[[10],[10], 0]
,[[60, -210, -60, 180, 400, -400], [250, -150], 12]
,[[0,300,500],[0,300,500], 6]
].forEach(t=>{
var a=t[0],b=t[1],k=t[2],r=F(a,b)
console.log(r==k?'OK':'KO','['+a+']','['+b+']',r)
})
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṢIẆS€µ€ŒpṢ€QL
```
[Try it online!](http://jelly.tryitonline.net/#code=4bmiSeG6hlPigqzCteKCrMWScOG5ouKCrFFM&input=&args=W1s2MCwgLTIxMCwgLTYwLCAxODAsIDQwMCwgLTQwMF0sIFsyNTAsIC0xNTBdXQ)
A rectangle is uniquely defined by its height and its width.
```
ṢIẆS€µ€ŒpṢ€QL Main chain, argument: z
µ€ For each subarray:
Ṣ sort
I compute consecutive increments
Ẇ yield all substrings
S€ compute sum of each substring
Œp Cartesian product
Ṣ€ Sort each
Q Remove duplicates
L Length
```
[Answer]
## CJam (22 bytes)
```
q~{2m*::-:z0-}/m*:$_&,
```
Takes input as an array of arrays. [Online demo](http://cjam.aditsu.net/#code=q~%7B2m*%3A%3A-%3Az0-%7D%2Fm*%3A%24_%26%2C&input=%5B%5B-250%20-50%2050%20250%5D%5B-250%20-70%2070%20250%5D%5D), [test suite](http://cjam.aditsu.net/#code=%5B%0A%20%20%5B%5B%5D%5B%5D%5D%0A%20%20%5B%5B-250%20-50%2050%20250%5D%5B-250%20-70%2070%20250%5D%5D%0A%20%20%5B%5B-250%20-50%2050%20250%5D%5B-250%20-70%2070%5D%5D%0A%20%20%5B%5B-40%2040%5D%5B-80%2050%5D%5D%0A%20%20%5B%5B10%5D%5B10%5D%5D%0A%20%20%5B%5B60%20-210%20-60%20180%20400%20-400%5D%5B250%20-150%5D%5D%0A%20%20%5B%5B0%20300%20500%5D%5B0%20300%20500%5D%5D%0A%5D%7B%60%3AQ%3B%0A%0AQ~%7B2m*%3A%3A-%3Az0-%7D%2Fm*%3A%24_%26%2C%0A%0Ap%7D%2F)
### Dissection
```
q~ e# Parse input
{ e# For each of the two elements in the top-level array
2m* e# Take its Cartesian self-product
::- e# Map fold subtraction, giving the separations between lines
:z e# Map absolute value
0- e# Remove 0, since trivial rectangles don't count
}/
m* e# Cartesian product of the two sets of separations
:$ e# Sort so that mxn === nxm
_& e# Deduplicate
, e# Count
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 22 bytes
```
"@gd&Xfo!s|]Z*!S!Xuz2/
```
[Try it online!](http://matl.tryitonline.net/#code=IkBnZCZYZm8hc3xdWiohUyFYdXoyLw&input=e1stMjUwLC01MCw1MCwyNTBdLFstMjUwLC03MCw3MCwyNTBdfQo) Or [verify all test cases](http://matl.tryitonline.net/#code=YAoiQGdkJlhmbyFzfF1aKiFTIVh1ejIvCkRU&input=e1tdLFtdfQp7Wy0yNTAsLTUwLDUwLDI1MF0sWy0yNTAsLTcwLDcwLDI1MF19CntbLTI1MCwtNTAsNTAsMjUwXSxbLTI1MCwtNzAsNzBdfQp7Wy00MCwgNDBdLFstODAsIDUwXX0Ke1sxMF0sWzEwXX0Ke1s2MCwgLTIxMCwgLTYwLCAxODAsIDQwMCwgLTQwMF0sIFsyNTAsIC0xNTBdfQp7WzAsMzAwLDUwMF0sWzAsMzAwLDUwMF19CntbMCw4MSw5MF0sWzAsOTAsMTAwXX0).
### Explanation
```
" % Implicitly input cell array of two numerical arrays. For each cell
@g % Push cell contents
d % Difference of its two entries
&Xf % Cell array of all substrings
o % Convert to numerical array, padding with zeros
!s % Sum of each row. Gives a row vector
| % Absolute value of each entry
] % End for
Z* % Cartesian product
!S! % Sort each row
Xu % Unique rows
z2/ % Number of unique rows excluding zeros. Implicitly display
```
[Answer]
**Python, 208 bytes**
```
import itertools as i
def h(x,y):
s=[]
k=[p for p in i.product(x,y)]
for j,(v,w) in enumerate(k):
for a,b in k[j+1:]:
q=sorted([abs(a-v),abs(b-w)])
if 0not in q and q not in s:s+=[q]
return len(s)
```
] |
[Question]
[
**The Challenge**
Everybody loves genetics, right? In this challenge, you will be given the genotypes of two parents. You must find each possible genotype of a child produced by the parents. You must account for dominant and recessive alleles as well as incomplete dominance and codominance.
An example input for the parents could be:
```
R'RxRr
```
Parent one (on the left) has a incompletely dominant R allele and a dominant R allele. Parent two (on the right) has a dominant R allele and a recessive allele.
Each parent is separated from the other by an x. The input will not contain an x allele.
An incompletely dominant allele will be followed by an apostrophe ('). Codominant alleles just refers to multiple different types of alleles combined together (A and W for example).
**Rules**
* Shortest code wins (measured in bytes).
* Each possibly genotype must be separated from the other genotypes by a comma.
* Phenotypes don't matter.
* Any letter can be used in the input except for x (which differentiates the parents).
* Duplicate genotypes should only be printed once.
+ Duplicates contain the exact same letters of the same case and type of allele. IF you have WY and YW in your answer, they are considered duplicates.
* No more than three different letters will be used in one input.
* The order of the letters in the output does not matter.
* Answer can be in the form of a string or an array.
**Examples**
Input 1 (the previous example):
```
R'RxRr
```
Output 1:
```
R'R,R'r,RR,Rr
```
Alternate output 1 (array):
```
{R'R,R'r,RR,Rr}
```
Input 2:
```
RWxRR
```
Output 2:
```
RR,WR
//Or an array, whichever you want
```
Input 3:
```
WYxY'y
```
Output 3:
```
WY',Wy,YY',Yy
//Once again, an array is fine
```
[Answer]
## Pyth, ~~20~~ 18 bytes
```
{msSd*Fc:z".'?"1\x
```
[Test suite.](https://pyth.herokuapp.com/?code=%7BmsSd%2aFc%3Az%22.%27%3F%221%5Cx&test_suite=1&test_suite_input=R%27RxRr%0ARWxRR%0AWYxY%27y)
```
z get input
: ".'?"1 regex match for any character followed by an optional '
c \x chop on the element "x", resulting in [["R'","R"],["R","r"]]
*F splat over Cartesian product, resulting in pairs of "genes"
from the first "parent" and from the second
m d map over each resulting pair...
S sort (so that we can dedup later)
s concatenate
{ remove duplicates
```
[Answer]
# JavaScript (ES6), ~~114~~ ~~112~~ ~~104~~ ~~90~~ 88 bytes
```
f=>(c=new Set,[z,y]=f.split`x`.map(b=>b.match(/.'?/g)),z.map(e=>y.map(g=>c.add(e+g))),c)
```
Thanks to Doorknob, Downgoat, Kenny Lau and Neil for helping me golf this down a bit :)
[Answer]
# Ruby, ~~82~~ 77 bytes
Anonymous function, takes the input string as its argument.
Edited to properly account for `ABxAB`.
-5 bytes from @Doorknob.
```
->g{a,b=g.split(?x).map{|s|s.scan /.'?/}
a.product(b).map{|s|s.sort*""}.uniq}
```
[Answer]
# Python 3.5 - 196 bytes:
```
def b(r):import itertools,re;r=[];[r.append(h)for h in itertools.permutations(re.sub("(?<=[a-zA-Z'])(?=[a-zA-Z])",' ',r.replace('x','')).split(' '),2)if h[::-1]not in r and h not in r];return r
```
A nice one liner, using some regular expressions.
**Note:** Around each letter with an apostrophe are double quotes, and I hope that's okay (e.g., in the output, `R'` would come out as `"R'"`). Also, for the last test case, it returns `[('W', "Y'"), ('W', 'y'), ('Y', 'W'), ('Y', "Y'"), ('Y', 'y'), ('y', "Y'")]` instead of just `WY',Wy,YY',Yy`. I also hope that is okay. If any of these conditions are an issue, just let me know, and I will fix them.
] |
[Question]
[
This is an extension of [Fibonacci Domino Tiling](https://codegolf.stackexchange.com/questions/37886/fibonacci-domino-tiling). Your goal is to print all 281 ways to tile a 4x6 rectangle with 1x2 and 2x1 dominoes. Fewest bytes wins.
Use the vertical bar `|` to indicate a space covered by the vertical domino, and an em-dash `—` (count it as if it were ASCII) or hyphen `-` for horizontal ones.
**Example output: (281 tilings, 1405 lines)**
```
——————
——————
——————
——————
||————
||————
——————
——————
|——|——
|——|——
——————
——————
——||——
——||——
——————
——————
|————|
|————|
——————
——————
——|——|
——|——|
——————
——————
————||
————||
——————
——————
||||——
||||——
——————
——————
|||——|
|||——|
——————
——————
——————
||————
||————
——————
||——||
||——||
——————
——————
|——|||
|——|||
——————
——————
——||||
——||||
——————
——————
——————
|——|——
|——|——
——————
——————
——||——
——||——
——————
||————
||||——
——||——
——————
——||——
||||——
||————
——————
——|——|
|||——|
||————
——————
————||
||——||
||————
——————
||||||
||||||
——————
——————
——————
|————|
|————|
——————
——————
——|——|
——|——|
——————
||————
|||——|
——|——|
——————
————||
|——|||
|——|——
——————
——————
————||
————||
——————
||————
||——||
————||
——————
|——|——
|——|||
————||
——————
——||——
——||||
————||
——————
————||
——||||
——||——
——————
||||——
||||||
————||
——————
——————
||||——
||||——
——————
||——||
||||||
——||——
——————
——||||
||||||
||————
——————
——————
|||——|
|||——|
——————
——————
——————
||————
||————
||————
||————
||————
||————
|——|——
|——|——
||————
||————
——||——
——||——
||————
||————
|————|
|————|
||————
||————
——|——|
——|——|
||————
||————
————||
————||
||————
||————
||||——
||||——
||————
||————
|||——|
|||——|
||————
||————
——————
||——||
||——||
——————
||——||
||——||
||————
||————
|——|||
|——|||
||————
||————
——||||
——||||
||————
||————
——————
|——|||
|——|||
——————
——————
——||||
——||||
——————
||————
||||||
——||||
——————
——||——
||||||
||——||
——————
————||
||||||
||||——
——————
||||||
||||||
||————
||————
——————
——————
|——|——
|——|——
||————
||————
|——|——
|——|——
|——|——
|——|——
|——|——
|——|——
——||——
——||——
|——|——
|——|——
|————|
|————|
|——|——
|——|——
——|——|
——|——|
|——|——
|——|——
————||
————||
|——|——
|——|——
||||——
||||——
|——|——
|——|——
|||——|
|||——|
|——|——
|——|——
||——||
||——||
|——|——
|——|——
|——|||
|——|||
|——|——
|——|——
——||||
——||||
|——|——
|——|——
||||||
||||||
|——|——
|——|——
——————
——————
——||——
——||——
||————
||————
——||——
——||——
|——|——
|——|——
——||——
——||——
——||——
——||——
——||——
——||——
|————|
|————|
——||——
——||——
——|——|
——|——|
——||——
——||——
————||
————||
——||——
——||——
||||——
||||——
——||——
——||——
|||——|
|||——|
——||——
——||——
——————
||————
||||——
——||——
||——||
||——||
——||——
——||——
|——|||
|——|||
——||——
——||——
——||||
——||||
——||——
——||——
——————
——||——
||||——
||————
||————
||||——
||||——
||————
|——|——
||||——
||||——
|——|——
——||——
||||——
||||——
——||——
|————|
|||——|
||||——
|——|——
——|——|
|||——|
||||——
——||——
————||
||——||
||||——
——||——
||||||
||||||
——||——
——||——
——————
——|——|
|||——|
||————
||————
|||——|
|||——|
||————
——————
————||
||——||
||————
||————
||——||
||——||
||————
|——|——
|——|||
||——||
||————
——||——
——||||
||——||
||————
————||
——||||
||||——
||————
||||——
||||||
||——||
||————
——————
||||||
||||||
——————
||——||
||||||
||||——
||————
|——|||
||||||
||||——
|——|——
——||||
||||||
||||——
——||——
——————
——————
|————|
|————|
||————
||————
|————|
|————|
|——|——
|——|——
|————|
|————|
——||——
——||——
|————|
|————|
|————|
|————|
|————|
|————|
——|——|
——|——|
|————|
|————|
————||
————||
|————|
|————|
||||——
||||——
|————|
|————|
|||——|
|||——|
|————|
|————|
||——||
||——||
|————|
|————|
|——|||
|——|||
|————|
|————|
——||||
——||||
|————|
|————|
||||||
||||||
|————|
|————|
——————
——————
——|——|
——|——|
||————
||————
——|——|
——|——|
|——|——
|——|——
——|——|
——|——|
——||——
——||——
——|——|
——|——|
|————|
|————|
——|——|
——|——|
——|——|
——|——|
——|——|
——|——|
————||
————||
——|——|
——|——|
||||——
||||——
——|——|
——|——|
|||——|
|||——|
——|——|
——|——|
——————
||————
|||——|
——|——|
||——||
||——||
——|——|
——|——|
|——|||
|——|||
——|——|
——|——|
——||||
——||||
——|——|
——|——|
|——|——
||||——
|||——|
|————|
——||——
||||——
|||——|
——|——|
|————|
|||——|
|||——|
|————|
——|——|
|||——|
|||——|
——|——|
————||
||——||
|||——|
——|——|
||||||
||||||
——|——|
——|——|
|————|
||——||
||——||
|————|
——————
————||
|——|||
|——|——
||————
||——||
|——|||
|——|——
|——|——
|——|||
|——|||
|——|——
——||——
——||||
|——|||
|——|——
|————|
|——|||
|——|||
|————|
——|——|
——||||
|——|||
|————|
||||——
||||||
|——|||
|——|——
|||——|
||||||
|——|||
|————|
|——|||
||||||
|||——|
|————|
——||||
||||||
|||——|
——|——|
——————
——————
————||
————||
||————
||————
————||
————||
|——|——
|——|——
————||
————||
——||——
——||——
————||
————||
|————|
|————|
————||
————||
——|——|
——|——|
————||
————||
————||
————||
————||
————||
||||——
||||——
————||
————||
|||——|
|||——|
————||
————||
——————
||————
||——||
————||
||——||
||——||
————||
————||
|——|||
|——|||
————||
————||
——||||
——||||
————||
————||
——————
|——|——
|——|||
————||
——————
——||——
——||||
————||
||————
||||——
——||||
————||
——||——
||||——
||——||
————||
——|——|
|||——|
||——||
————||
————||
||——||
||——||
————||
||||||
||||||
————||
————||
————||
|——|||
|——|||
————||
——————
————||
——||||
——||——
||————
||——||
——||||
——||——
|——|——
|——|||
——||||
——||——
——||——
——||||
——||||
——||——
|————|
|——|||
——||||
——|——|
——|——|
——||||
——||||
——|——|
————||
——||||
——||||
————||
||||——
||||||
——||||
——||——
|||——|
||||||
——||||
——|——|
——————
||||——
||||||
————||
||——||
||||||
——||||
————||
——||||
||||||
||——||
————||
——————
——————
||||——
||||——
||————
||————
||||——
||||——
|——|——
|——|——
||||——
||||——
——||——
——||——
||||——
||||——
|————|
|————|
||||——
||||——
——|——|
——|——|
||||——
||||——
————||
————||
||||——
||||——
||||——
||||——
||||——
||||——
|||——|
|||——|
||||——
||||——
——————
||——||
||||||
——||——
||——||
||——||
||||——
||||——
|——|||
|——|||
||||——
||||——
——||||
——||||
||||——
||||——
——————
——||||
||||||
||————
||————
||||||
||||||
||————
|——|——
||||||
||||||
|——|——
——||——
||||||
||||||
——||——
|————|
||||||
||||||
|————|
——|——|
||||||
||||||
——|——|
————||
||||||
||||||
————||
||||||
||||||
||||——
||||——
——————
——————
|||——|
|||——|
||————
||————
|||——|
|||——|
|——|——
|——|——
|||——|
|||——|
——||——
——||——
|||——|
|||——|
|————|
|————|
|||——|
|||——|
——|——|
——|——|
|||——|
|||——|
————||
————||
|||——|
|||——|
||||——
||||——
|||——|
|||——|
|||——|
|||——|
|||——|
|||——|
||——||
||——||
|||——|
|||——|
|——|||
|——|||
|||——|
|||——|
——||||
——||||
|||——|
|||——|
||||||
||||||
|||——|
|||——|
——————
——————
||——||
||——||
||————
||————
||——||
||——||
|——|——
|——|——
||——||
||——||
——||——
——||——
||——||
||——||
|————|
|————|
||——||
||——||
——|——|
——|——|
||——||
||——||
————||
————||
||——||
||——||
||||——
||||——
||——||
||——||
|||——|
|||——|
||——||
||——||
||——||
||——||
||——||
||——||
|——|||
|——|||
||——||
||——||
——||||
——||||
||——||
||——||
||||||
||||||
||——||
||——||
——————
——————
|——|||
|——|||
||————
||————
|——|||
|——|||
|——|——
|——|——
|——|||
|——|||
——||——
——||——
|——|||
|——|||
|————|
|————|
|——|||
|——|||
——|——|
——|——|
|——|||
|——|||
————||
————||
|——|||
|——|||
||||——
||||——
|——|||
|——|||
|||——|
|||——|
|——|||
|——|||
||——||
||——||
|——|||
|——|||
|——|||
|——|||
|——|||
|——|||
——||||
——||||
|——|||
|——|||
||||||
||||||
|——|||
|——|||
——————
——————
——||||
——||||
||————
||————
——||||
——||||
|——|——
|——|——
——||||
——||||
——||——
——||——
——||||
——||||
|————|
|————|
——||||
——||||
——|——|
——|——|
——||||
——||||
————||
————||
——||||
——||||
||||——
||||——
——||||
——||||
|||——|
|||——|
——||||
——||||
——————
||————
||||||
——||||
||——||
||——||
——||||
——||||
|——|||
|——|||
——||||
——||||
——||||
——||||
——||||
——||||
——————
——||——
||||||
||——||
||————
||||——
||||||
||——||
|——|——
||||——
||||||
|——|||
——||——
||||——
||||||
——||||
|————|
|||——|
||||||
|——|||
——|——|
|||——|
||||||
——||||
————||
||——||
||||||
——||||
||||||
||||||
——||||
——||||
——————
————||
||||||
||||——
||————
||——||
||||||
||||——
|——|——
|——|||
||||||
||||——
——||——
——||||
||||||
||||——
|————|
|——|||
||||||
|||——|
——|——|
——||||
||||||
|||——|
————||
——||||
||||||
||——||
||||——
||||||
||||||
||||——
|||——|
||||||
||||||
|||——|
||——||
||||||
||||||
||——||
|——|||
||||||
||||||
|——|||
——||||
||||||
||||||
——||||
——————
——————
||||||
||||||
||————
||————
||||||
||||||
|——|——
|——|——
||||||
||||||
——||——
——||——
||||||
||||||
|————|
|————|
||||||
||||||
——|——|
——|——|
||||||
||||||
————||
————||
||||||
||||||
||||——
||||——
||||||
||||||
|||——|
|||——|
||||||
||||||
||——||
||——||
||||||
||||||
|——|||
|——|||
||||||
||||||
——||||
——||||
||||||
||||||
||||||
||||||
||||||
||||||
```
**Input**
There is no input -- you only have to print 4x6 tilings. In theory, you could hardcode an output, but that would likely take more bytes that producing it.
**Output**
Print the 281 tilings in any order in the format shown in the example, with each one appearing exactly once. There must be exactly one empty line between tilings. Any other whitespace is OK if it doesn't affect the visible output. Empty lines at the start and end are also OK.
**Other requirements**
Your code should not be horribly slow; it should produce output within 10 minutes, which should be ample time. Functions to produce or enumerate tilings are disallowed.
In case people are wondering if this is sufficiently distinct from [Fibonacci Domino Tiling](https://codegolf.stackexchange.com/questions/37886/fibonacci-domino-tiling), I expect the answers to use a different strategies as one can no longer take advantage of the particular Fibonacci structure of 2-by-n domino tilings and them being specified by their top row.
[Answer]
# CJam, ~~75~~ ~~67~~ ~~63~~ ~~58~~ 57 bytes
```
La'|a{_'|f+@:C"--"f++}5*\;_m*_m*{~+}%{zC{81f^}%-!},Nf+Nf*
```
[Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### Example run
```
$ cjam 4x6.cjam | head -9
||||||
||||||
||||||
||||||
||||||
||||||
--||||
--||||
$ cjam 4x6.cjam | tail -10
------
------
||----
||----
------
------
------
------
$ cjam 4x6.cjam | wc -l
1405
$ cjam 4x6.cjam | md5sum
83b5de42157ace906ed5c0173fb99027 -
```
### Background
A covering of the rectangle by domino halves is a valid tiling if:
1. Horizontal domino halves occur in pairs in each row.
2. Vertical domino halves occur in pairs in each column.
The valid configurations for rows of length *n* can be obtained by adding a vertical domino half to the valid configurations for *n - 1* and a two horizontal domino halves to the valid configurations for *n - 2*.
The valid configurations for columns of length *n* can be computed as the configurations of rows of the same length, exchanging vertical domino halves and horizontal domino halves.
To generate all 281 possible tilings, it suffices to generate all possible combinations of rows, all possible combinations of columns and intersect the two sets.
### Implementation
Rather than generating combinations twice and intersecting, we can generate all possible combinations of rows and check if their columns have a valid pattern.
```
" Leave an array of valid row configurations of length 6 on the stack and save the valid
row configurations of length 4 in C. In http://codegolf.stackexchange.com/a/38000,
I explain in detail how this is achieved. ";
La'|a{_'|f+@:C"--"f++}5*\;
" Compute the Cartesian product of four copies of the array. ";
_m*_m*
" Flatten the arrays of strings of the Cartesian product. ";
{~+}%
" Transpose rows and columns, swap vertical bars and hyphens in C (note that ord('-') ==
ord('-') ^ 81) and check if all rows of the first array belong to the second. ";
{zC{81f^}%-!},
" Separate the rows of a tiling and the tilings from each other. ";
Nf+ Nf*
```
[Answer]
# C, 282 bytes ungolfed
```
i,j,p[4],q,t,a,b,c,d;
main(){
char s[]="UTRQPJIHEDBA@";
for(i=64*169;i--;){
a=p[0]=s[i%13]*3,d=p[3]=s[i/13%13]*3,q=i/169;
b=p[1]=p[0]&q;c=p[2]=p[3]&q;
if((a|q)==255&(d|q)==255 & (b/3|b/3*2)==b & (c/3|c/3*2)==c)
for(j=24;j--;)putchar(p[j/6]>>j%6&1?45:124),j%6||printf(j?"\n":" %d\n\n",t+=!j);
}
}
```
This works in a similar way to my answer to the previous question, with 1 representing `-` and 0 representing `|`. In fact the 13 valid combinations for n=6 in the previous question are encoded in `s[]`, having had binary `11000000` added to them to bring them into a convenient ASCII range, then divided by 3.
A logical way to proceed is to place the vertical dominoes that straddle the centreline, then place the remaining vertical dominoes, and finally place the horizontal dominoes. That's basically how my code proceeds. The 13x13=169 possible tilings with no vertical dominoes crossing the centreline are listed first, then the different combinations of vertical dominoes crossing the centreline are explored.
`q` contains the pattern for vertical centre dominoes (all 64 combinations of 1's and 0's are allowed in principle.) `a` and `d` store the top and bottom rows (only those 13 combinations from the previous question are allowed, as they are the only ones that give complete horizontal dominoes.) `b` and `c` hold the calculated values for the centre rows (made by ANDing `q` with `a` and `d`) and the following rules are applied:
1: no vertical dominoes may overlap. `a` and `d` when ORed with `q` must give `11111111`. (Remember due to the compression method, each domino in `a` and `d`is carrying an additional 11000000.)
2: rows `b` and `c` must hold complete horizontal dominoes. The code for checking this is `(b/3|b/3*2)==b` and is explained in my answer to the previous question.
**output**
in addition to `a,b,c,d`, the four rows are stored in an array `p[]` for printing via a loop. Currently each pattern is numbered. The numbering will be removed as part of the golfing process.
```
||||||
||||||
||||||
|||||| 1
||||||
||||||
||||--
||||-- 2
||||||
||||||
|||--|
|||--| 3
||||||
||||||
||--||
||--|| 4
||||||
||||||
||----
||---- 5
||||||
||||||
|--|||
|--||| 6
||||||
||||||
|--|--
|--|-- 7
||||||
||||||
|----|
|----| 8
||||||
||||||
--||||
--|||| 9
||||||
||||||
--||--
--||-- 10
||||||
||||||
--|--|
--|--| 11
||||||
||||||
----||
----|| 12
||||||
||||||
------
------ 13
||||--
||||--
||||||
|||||| 14
||||--
||||--
||||--
||||-- 15
||||--
||||--
|||--|
|||--| 16
||||--
||||--
||--||
||--|| 17
||||--
||||--
||----
||---- 18
||||--
||||--
|--|||
|--||| 19
||||--
||||--
|--|--
|--|-- 20
||||--
||||--
|----|
|----| 21
||||--
||||--
--||||
--|||| 22
||||--
||||--
--||--
--||-- 23
||||--
||||--
--|--|
--|--| 24
||||--
||||--
----||
----|| 25
||||--
||||--
------
------ 26
|||--|
|||--|
||||||
|||||| 27
|||--|
|||--|
||||--
||||-- 28
|||--|
|||--|
|||--|
|||--| 29
|||--|
|||--|
||--||
||--|| 30
|||--|
|||--|
||----
||---- 31
|||--|
|||--|
|--|||
|--||| 32
|||--|
|||--|
|--|--
|--|-- 33
|||--|
|||--|
|----|
|----| 34
|||--|
|||--|
--||||
--|||| 35
|||--|
|||--|
--||--
--||-- 36
|||--|
|||--|
--|--|
--|--| 37
|||--|
|||--|
----||
----|| 38
|||--|
|||--|
------
------ 39
||--||
||--||
||||||
|||||| 40
||--||
||--||
||||--
||||-- 41
||--||
||--||
|||--|
|||--| 42
||--||
||--||
||--||
||--|| 43
||--||
||--||
||----
||---- 44
||--||
||--||
|--|||
|--||| 45
||--||
||--||
|--|--
|--|-- 46
||--||
||--||
|----|
|----| 47
||--||
||--||
--||||
--|||| 48
||--||
||--||
--||--
--||-- 49
||--||
||--||
--|--|
--|--| 50
||--||
||--||
----||
----|| 51
||--||
||--||
------
------ 52
||----
||----
||||||
|||||| 53
||----
||----
||||--
||||-- 54
||----
||----
|||--|
|||--| 55
||----
||----
||--||
||--|| 56
||----
||----
||----
||---- 57
||----
||----
|--|||
|--||| 58
||----
||----
|--|--
|--|-- 59
||----
||----
|----|
|----| 60
||----
||----
--||||
--|||| 61
||----
||----
--||--
--||-- 62
||----
||----
--|--|
--|--| 63
||----
||----
----||
----|| 64
||----
||----
------
------ 65
|--|||
|--|||
||||||
|||||| 66
|--|||
|--|||
||||--
||||-- 67
|--|||
|--|||
|||--|
|||--| 68
|--|||
|--|||
||--||
||--|| 69
|--|||
|--|||
||----
||---- 70
|--|||
|--|||
|--|||
|--||| 71
|--|||
|--|||
|--|--
|--|-- 72
|--|||
|--|||
|----|
|----| 73
|--|||
|--|||
--||||
--|||| 74
|--|||
|--|||
--||--
--||-- 75
|--|||
|--|||
--|--|
--|--| 76
|--|||
|--|||
----||
----|| 77
|--|||
|--|||
------
------ 78
|--|--
|--|--
||||||
|||||| 79
|--|--
|--|--
||||--
||||-- 80
|--|--
|--|--
|||--|
|||--| 81
|--|--
|--|--
||--||
||--|| 82
|--|--
|--|--
||----
||---- 83
|--|--
|--|--
|--|||
|--||| 84
|--|--
|--|--
|--|--
|--|-- 85
|--|--
|--|--
|----|
|----| 86
|--|--
|--|--
--||||
--|||| 87
|--|--
|--|--
--||--
--||-- 88
|--|--
|--|--
--|--|
--|--| 89
|--|--
|--|--
----||
----|| 90
|--|--
|--|--
------
------ 91
|----|
|----|
||||||
|||||| 92
|----|
|----|
||||--
||||-- 93
|----|
|----|
|||--|
|||--| 94
|----|
|----|
||--||
||--|| 95
|----|
|----|
||----
||---- 96
|----|
|----|
|--|||
|--||| 97
|----|
|----|
|--|--
|--|-- 98
|----|
|----|
|----|
|----| 99
|----|
|----|
--||||
--|||| 100
|----|
|----|
--||--
--||-- 101
|----|
|----|
--|--|
--|--| 102
|----|
|----|
----||
----|| 103
|----|
|----|
------
------ 104
--||||
--||||
||||||
|||||| 105
--||||
--||||
||||--
||||-- 106
--||||
--||||
|||--|
|||--| 107
--||||
--||||
||--||
||--|| 108
--||||
--||||
||----
||---- 109
--||||
--||||
|--|||
|--||| 110
--||||
--||||
|--|--
|--|-- 111
--||||
--||||
|----|
|----| 112
--||||
--||||
--||||
--|||| 113
--||||
--||||
--||--
--||-- 114
--||||
--||||
--|--|
--|--| 115
--||||
--||||
----||
----|| 116
--||||
--||||
------
------ 117
--||--
--||--
||||||
|||||| 118
--||--
--||--
||||--
||||-- 119
--||--
--||--
|||--|
|||--| 120
--||--
--||--
||--||
||--|| 121
--||--
--||--
||----
||---- 122
--||--
--||--
|--|||
|--||| 123
--||--
--||--
|--|--
|--|-- 124
--||--
--||--
|----|
|----| 125
--||--
--||--
--||||
--|||| 126
--||--
--||--
--||--
--||-- 127
--||--
--||--
--|--|
--|--| 128
--||--
--||--
----||
----|| 129
--||--
--||--
------
------ 130
--|--|
--|--|
||||||
|||||| 131
--|--|
--|--|
||||--
||||-- 132
--|--|
--|--|
|||--|
|||--| 133
--|--|
--|--|
||--||
||--|| 134
--|--|
--|--|
||----
||---- 135
--|--|
--|--|
|--|||
|--||| 136
--|--|
--|--|
|--|--
|--|-- 137
--|--|
--|--|
|----|
|----| 138
--|--|
--|--|
--||||
--|||| 139
--|--|
--|--|
--||--
--||-- 140
--|--|
--|--|
--|--|
--|--| 141
--|--|
--|--|
----||
----|| 142
--|--|
--|--|
------
------ 143
----||
----||
||||||
|||||| 144
----||
----||
||||--
||||-- 145
----||
----||
|||--|
|||--| 146
----||
----||
||--||
||--|| 147
----||
----||
||----
||---- 148
----||
----||
|--|||
|--||| 149
----||
----||
|--|--
|--|-- 150
----||
----||
|----|
|----| 151
----||
----||
--||||
--|||| 152
----||
----||
--||--
--||-- 153
----||
----||
--|--|
--|--| 154
----||
----||
----||
----|| 155
----||
----||
------
------ 156
------
------
||||||
|||||| 157
------
------
||||--
||||-- 158
------
------
|||--|
|||--| 159
------
------
||--||
||--|| 160
------
------
||----
||---- 161
------
------
|--|||
|--||| 162
------
------
|--|--
|--|-- 163
------
------
|----|
|----| 164
------
------
--||||
--|||| 165
------
------
--||--
--||-- 166
------
------
--|--|
--|--| 167
------
------
----||
----|| 168
------
------
------
------ 169
||||--
||||||
||||||
||||-- 170
||||--
||||||
||--||
||---- 171
||||--
||||||
|--|||
|--|-- 172
||||--
||||||
--||||
--||-- 173
||||--
||||||
----||
------ 174
||----
||--||
||||||
||||-- 175
||----
||--||
||--||
||---- 176
||----
||--||
|--|||
|--|-- 177
||----
||--||
--||||
--||-- 178
||----
||--||
----||
------ 179
|--|--
|--|||
||||||
||||-- 180
|--|--
|--|||
||--||
||---- 181
|--|--
|--|||
|--|||
|--|-- 182
|--|--
|--|||
--||||
--||-- 183
|--|--
|--|||
----||
------ 184
--||--
--||||
||||||
||||-- 185
--||--
--||||
||--||
||---- 186
--||--
--||||
|--|||
|--|-- 187
--||--
--||||
--||||
--||-- 188
--||--
--||||
----||
------ 189
------
----||
||||||
||||-- 190
------
----||
||--||
||---- 191
------
----||
|--|||
|--|-- 192
------
----||
--||||
--||-- 193
------
----||
----||
------ 194
|||--|
||||||
||||||
|||--| 195
|||--|
||||||
|--|||
|----| 196
|||--|
||||||
--||||
--|--| 197
|----|
|--|||
||||||
|||--| 198
|----|
|--|||
|--|||
|----| 199
|----|
|--|||
--||||
--|--| 200
--|--|
--||||
||||||
|||--| 201
--|--|
--||||
|--|||
|----| 202
--|--|
--||||
--||||
--|--| 203
||----
|||--|
|||--|
||---- 204
||----
|||--|
--|--|
------ 205
------
--|--|
|||--|
||---- 206
------
--|--|
--|--|
------ 207
||--||
||||||
||||||
||--|| 208
||--||
||||||
||||--
||---- 209
||--||
||||||
--||||
----|| 210
||--||
||||||
--||--
------ 211
||----
||||--
||||||
||--|| 212
||----
||||--
||||--
||---- 213
||----
||||--
--||||
----|| 214
||----
||||--
--||--
------ 215
----||
--||||
||||||
||--|| 216
----||
--||||
||||--
||---- 217
----||
--||||
--||||
----|| 218
----||
--||||
--||--
------ 219
------
--||--
||||||
||--|| 220
------
--||--
||||--
||---- 221
------
--||--
--||||
----|| 222
------
--||--
--||--
------ 223
||----
||||||
||||||
||---- 224
||----
||||||
--||||
------ 225
------
--||||
||||||
||---- 226
------
--||||
--||||
------ 227
|----|
||--||
||--||
|----| 228
|--|||
||||||
||||||
|--||| 229
|--|||
||||||
||||--
|--|-- 230
|--|||
||||||
|||--|
|----| 231
|--|--
||||--
||||||
|--||| 232
|--|--
||||--
||||--
|--|-- 233
|--|--
||||--
|||--|
|----| 234
|----|
|||--|
||||||
|--||| 235
|----|
|||--|
||||--
|--|-- 236
|----|
|||--|
|||--|
|----| 237
|--|--
||||||
||||||
|--|-- 238
|----|
||||||
||||||
|----| 239
------
|----|
|----|
------ 240
----||
|--|||
|--|||
----|| 241
----||
|--|||
|--|--
------ 242
------
|--|--
|--|||
----|| 243
------
|--|--
|--|--
------ 244
------
|--|||
|--|||
------ 245
--||||
||||||
||||||
--|||| 246
--||||
||||||
||||--
--||-- 247
--||||
||||||
|||--|
--|--| 248
--||||
||||||
||--||
----|| 249
--||||
||||||
||----
------ 250
--||--
||||--
||||||
--|||| 251
--||--
||||--
||||--
--||-- 252
--||--
||||--
|||--|
--|--| 253
--||--
||||--
||--||
----|| 254
--||--
||||--
||----
------ 255
--|--|
|||--|
||||||
--|||| 256
--|--|
|||--|
||||--
--||-- 257
--|--|
|||--|
|||--|
--|--| 258
--|--|
|||--|
||--||
----|| 259
--|--|
|||--|
||----
------ 260
----||
||--||
||||||
--|||| 261
----||
||--||
||||--
--||-- 262
----||
||--||
|||--|
--|--| 263
----||
||--||
||--||
----|| 264
----||
||--||
||----
------ 265
------
||----
||||||
--|||| 266
------
||----
||||--
--||-- 267
------
||----
|||--|
--|--| 268
------
||----
||--||
----|| 269
------
||----
||----
------ 270
--||--
||||||
||||||
--||-- 271
--||--
||||||
||--||
------ 272
------
||--||
||||||
--||-- 273
------
||--||
||--||
------ 274
--|--|
||||||
||||||
--|--| 275
------
|||--|
|||--|
------ 276
----||
||||||
||||||
----|| 277
----||
||||||
||||--
------ 278
------
||||--
||||||
----|| 279
------
||||--
||||--
------ 280
------
||||||
||||||
------ 281
```
[Answer]
# C, 216 bytes
```
#define M:++B:++B:8;for(k=0
j,k,B;char*c,s[99];main(i){for(i<<=24;i--;B||puts(s)){for(B=k=0;j=i>>k++;)j&1?k%6?j&2?k++M;k^29;k+=6)j=~i>>(k-=k/24*23),j&1?k<18?j&64?k+=6
M,c=s;k<24;++k%6||(*c++=10))*c++=1<<k&i?45:'|';}}
```
Sadly it took over 200 bytes. My approach was to view the grid as 24 bits which can each be either part of a horizontal piece or part of a vertical piece. It generates all `1<<24` combinations and then goes down the rows and columns munching the dominos to see whether each one is valid.
[Answer]
# Python 2: 130 bytes
```
for i in range(4096):
G=([0]*6+["\n"])*4;exec"b=i%2;j=G.index(0);G[j]=G[(j+7**b)%28]='-|'[b];i/=2;"*12
if all(G):print"".join(G)
```
I use a different encoding of tilings than has been posted so far, one that is more efficient timewise in that it needs only 12 bits to represent a valid tiling, though in retrospect perhaps not the golfiest one.
If you "read" through the 4x6 grid from left to right, top to bottom, each domino you encounter in order is either vertical or horizontal. (Of course, you encounter each domino twice, but only the first encounter of the top or left corner matters). This gives a sequence of 12 bits.
For example, the tiling
```
——|——|
|||——|
||||——
——||——
```
corresponds to `HVHVVVVHVHHH`.
Conversely, each sequence of 12 corresponds to a unique tiling, created by repeatedly adding a tile of the specified orientation with it's top or right cell as the first unoccupied cell in reading order. Some, though, are not legal tilings because a domino is placed with its other half off the board or overlapping with an existing domino.
The code tries every possible sequence, represented by a `12`-bit number `0` to `4095`, reading off bits one at a time with `%2` and `/2`. The board, initialized with zeroes for empty cells, is stored with rows concatenated into a single list. That way, it's easy to find the first zero element to place the domino. The other domino half is either one row or column down, and so found by adding `1` or `6` to the index. These two cells are filled with the proper character `-` or `|`. This list could have been a string except that Python strings are immutable.
Rather than checking for a collision, we place the dominoes allowing overlaps, and see at the end whether the board is filled by whether any zeroes remain (`all`). We actually make the board 4x7, filling the right row with `\n` for two reasons. The first is that the padding lets horizontal dominoes go off the end without cycling over to the left edge (dominoes that go off the bottom edge *are* wrapped around with `%28`, but that's fine because they overlap with the the first row which has been filled by then). The other reason is so that in a legal configuration, the newlines remain and cause the lines to be printed separately when the characters are joined.
] |
[Question]
[
Write a program which enumerates points on a regular grid in the form of a spiral. The output should be the indices of the points (row-major) and the spiral should start at 0 and proceed anti-clockwise.
Here is an illustration of the problem:

**Specifications:**
* Write a program which accepts two integers and writes the result to standard out.
* Input: width and height of the grid (range is [1,1024])
* Output: indices of grid points in the correct order
**Goal:**
* Entry with fewest characters wins.
* Would also be interested in elegant entries for "classic" programming languages.
**Examples:**
* width=3, height=3 => 0 1 2 5 8 7 6 3 4
* width=4, height=3 => 0 1 2 3 7 11 10 9 8 4 5 6
[Answer]
# CJam - 18
```
q~1$*,/{(S*S@zW%}h
```
Try it at <http://cjam.aditsu.net/>
The input should contain the 2 numbers separated by space.
**Explanation:**
`q~` reads and evaluates the input
`1$*` copies the width and multiplies by height
`,/` generates the array with all the numbers in order, and splits it in rows
`{…}h` repeats the block until the condition (at the end of the block) is false
`(S*S` takes the first row of the grid and adds spaces to separate the numbers
`@zW%` takes the rest of the grid and rotates it (`z` = transpose, `W%` = reverse)
The remaining grid becomes the loop condition; the loop terminates when the grid is empty.
[Answer]
### Ruby — ~~96~~ 81
@Ventero knocks off 15 characters with some splatting combined with a really clever default argument!
```
g=->a=p,*r{a ?a+g[*r.transpose.reverse]:[]}
f=->w,h{g[*[*0...w*h].each_slice(w)]}
```
Examples:
```
f[3,3] # => [0, 1, 2, 5, 8, 7, 6, 3, 4]
f[4,3] # => [0, 1, 2, 3, 7, 11, 10, 9, 8, 4, 5, 6]
```
Here's an ungolfed solution in Ruby using just one method for those who are interested:
```
def spiral(width, height, matrix = [*[*0...width * height].each_slice(width)])
matrix.empty? ? [] : matrix.shift + spiral(0, 0, matrix.transpose.reverse)
end
```
[Answer]
## My PHP version. 349 276 characters.
Same as below but I found out something surprising. In PHP, for loops can have multiple expressions in both pre and post iteration. I never knew that and suddenly they are far more powerful/complex than I thought they were. So could not resist rewriting my first attempt to make use of that.
Anyway, new and improved code here - 73 characters shorter than the first:
```
<?php $a=4;$b=3;$c=-1;$d=$a*$b;$e=$a;$f=($b-1);function c($g,$k){
global $c,$d;for($l=0;$l<$g;$c=$c+$k,++$l,--$d,print $c.' ');}while($d>0)
{$m=1;$g=$e;c($g,$m);--$e;if($f>0){$m=$a;$g=$f;c($g,$m);--$f;if($e>0)
{$m=-1;$g=$e;c($g,$m);--$e;if($f>0){$m=-$a;$g=$f;c($g,$m);--$f;}}}}?>
```
which can be seen [here](http://codepad.org/g52JwcQw):
### Original attempt below
No where near as cool as the 18 chars of CJam (which I shall be googling about in a minute) but this is the full php program that takes the width and height as the first two parameters.
```
<?php $a=4;$b=3;$c=-1;$d=$e=0;$f=($b*$a);function calc($g,$h,$j,$k){for($l=$g;
$l<$h;++$l){$k=$k+$j;echo' '.$k;}return($k);}while($f>0){if($d<$a){$c=calc($d,$a,1,$c);
$f=$f-($a-$d);++$e;if($e<$b){$c=calc($e,$b,$a,$c);$f=$f-($b-$e);++$d;
if($d<$a){$c=calc($d,$a,-1,$c);$f=$f-($a-$d);++$e;
if($e<$b){$j=0-$a;$c=calc($e,$b,$j,$c);$f=$f-($b-$e);}}}}++$d;}?>
```
You can see it in action here: <http://codepad.org/qPUWwY2J> (above paste has had extra line breaks so it all shows on the page without side scrolling.)
I think this puzzle was a great question and I must admit that starting on 0 caused some issues for me. I have checked lots of different grids and it seems to work well although takes a bit of time to work through large grids.
My answer simply recognizes that moving left and right is adding +1 or -1 to the start number used, and up or down just adds or subtracts the original width. It then simply steps down the height and width counters for each pass. All of the output is in a function that I just send the change, step count and start number to. I reckon I could get a few more characters off by not declaring variables, but not 300 or so.
Great puzzle, had some tricky bits but I enjoyed it, thank you.
[Answer]
# Mathematica - 97 characters
```
w=4;h=3;Flatten@NestList[Reverse@Transpose@Rest@#&,Partition[Range[w h],w],2Min[w,h]-2][[;;,1]]-1
```
* First generate the grid.
* Iteratively drop the first row and rotate (transpose + reverse) the remaining matrix.
* The number of iterations until we end with 1-dimensional matrix is `2*min(w,h)-2`.
* Collect the dropped first rows into an array.
* Subtract 1 because Mathematica starts indices with 1.
[Answer]
## JavaScript - 225 Characters
```
w=8,h=8
{for(a=[0],x=y=b=r=t=l=s=0;a.length<w*h;){if(s==0&&x+r+1==w&&++b+1||s==1&&y+t+1==h&&++r+1||s==2&&x==l&&++t+1||s==3&&y==b&&++l+1)s=(s+1)%4
s==0&&++x+1||s==1&&++y+1||s==2&&--x+1||--y
a.push(x+w*y)}alert(a.join(' '))}
```
And ungolfed:
```
w = 8 // width of grid
h = 8 // height of grid
for(a = [0], // array
x = // x pos
y = // y pos
b = // bottom rows done
r = // right rows done
t = // top rows done
l = // left rows done
s = 0; // current side 0: b, 1: r, 2: t, 3: l
a.length < w*h;) {
if (s==0 && x+r+1==w && ++b+1 ||
s==1 && y+t+1==h && ++r+1 ||
s==2 && x==l && ++t+1 ||
s==3 && y==b && ++l+1 ){
s=(s+1)%4
}
s==0 && ++x+1 ||
s==1 && ++y+1 ||
s==2 && --x+1 ||
--y
a.push(x+w*y)
}
alert(a.join(' '))
```
The code sets the grid size in `w` and `h`. It stores current coordinates in `x` and `y`. It navigates in direction `s`, and stores the number of rows already filled on the sides in `b`, `r`, `t` and `l`.
A demo is at <http://jsfiddle.net/L2ReA/>
] |
[Question]
[
You need to write a program in any language that will produce (source code for) a program in a different language. That program will produce a 3rd program in another language and so on.
You should aim to create many programs; you aren't limited to 3. You can re-use a language, but it won't be counted in the scoring.
Your entry is the source code of the first program, together with a list of the languages of subsequent programs produced in the order they are produced. For easy reading maybe include each program's output/source.
Scoring will be the length of the source code of the first program divided by the number of different languages used.
---
To prevent solutions such as `1` (that has been pointed out in the comments) I suggest the following extra rule:
The output of one program must not be valid code in the language of that program.
[Answer]
My first time for that kind of challenge:
## R > Julia > BrainF\*\*k - 91 characters - Score: 30.33
The initial R code:
```
cat("'+'^8","\"[>\"","'+'^9","'>'","'+'^13","'>'","'+'^4","'<'^3","\"-]>.>+.>+.\"",sep="*")
```
It produces the following Julia code:
```
'+'^8*"[>"*'+'^9*'>'*'+'^13*'>'*'+'^4*'<'^3*"-]>.>+.>+."
```
Which produces:
```
++++++++[>+++++++++>++++++++++++++>++++<<<-]>.>+.>+.
```
which equates to:
```
Hi!
```
in BrainF\*\*k.
**NB:** None of the three programs is valid in any of the two other languages.
[Answer]
## Clojure → C → Python 2.7 → BASIC → Bash
**Score: 13.40**
```
(println"int main(){puts(\"print'PRINT\\\"echo\\\"'\");return 0;}")
```
Here is the breakdown:
1. Clojure
```
(println"int main(){puts(\"print'PRINT\\\"echo\\\"'\");return 0;}")
```
2. C
```
int main(){puts("print'PRINT\"echo\"'");return 0;}
```
3. Python 2.7
```
print'PRINT"echo"'
```
4. BASIC
```
PRINT"echo"
```
5. Bash
```
echo
```
---
I guess a simpler alternative would be
```
print'echo'
```
in Python 2.7, which outputs Bash code. This has a score of **5.5**, but isn't as fancy as what's above.
] |
[Question]
[
Homologous series, any of numerous groups of chemical compounds in each of which the difference between successive members is a simple structural unit.
As an example, Alkane is a homologous group where the chemical compounds are in \$C\_nH\_{2n+2}\$ format. \$CH\_4\$ (Methane) is part of the Alkane group because \$CH\_4 \to C\_{1}H\_{2\cdot 1+2}\$ and there because there is \$n=1\$ carbon atom, so there should be \$2n+2\$ hydrogen atoms. And there is \$2×1+2 = 4\$ hydrogen atoms. So Methane or \$CH\_4\$ qualifies for the Alkane group.
In this challenge we will be matching against 6 homologous groups:
* **Alkane** : \$C\_nH\_{2n+2}\$
* **Alkene** : \$C\_nH\_{2n}\$
* **Alkyne** : \$C\_nH\_{2n-2}\$
* **Alcohol** : \$C\_nH\_{2n+1}OH\$
* **Aldehyde** : \$C\_nH\_{2n+1}CHO\$
* **Carboxylic Acid** : \$C\_nH\_{2n+1}COOH\$
Input format will be like `CH_4` \$ \to CH\_4\$, `CH_3CHO` \$ \to CH\_3CHO \$, meaning that you need to write the subscript using an underscore (`_`). Output should be the group the compound belongs to.
**Test Cases**
```
CH_4 -> Alkane
C_2H_4 -> Alkene
C_2H_2 -> Alkyne
CH_3OH -> Alcohol
CH_3CHO -> Aldehyde
CH_3COOH -> Carboxylic Acid
```
Standard loopholes apply, shortest code wins. Input is guaranteed to be in these 6 categories and valid. Output needs to be exactly capitalized as in question. \$n\$ can be less than 2 (if it is omitted assume it is 1). There will be no leading zeros in \$n\$.
[Answer]
# [Python 3](https://docs.python.org/3/), 134 bytes
*-3 bytes thanks to @tsh*
Note that it fails for `CH_2`. It is unclear whether such a test case is valid, but I will keep this solution for now.
```
lambda e:['Aldehyde','Alcohol','Carboxylic Acid',0][e[::-1].rfind('O')]or'Alk%sne'%'eay'[eval(e.translate({67:45,72:43,95:43})+'//2')]
```
[Try it online!](https://tio.run/##XZDBaoQwEIbvPkUuSxKadbvqdmnAwuLFmw9gRbI6YmiaiGbbSumz22haCr3M/HwzP8z8w2x7o@OlS58XJV6vrUDAS3xRLfRzC5g52ZjeKKcyMV7Nx6xkgy6NbDG7r0ooOd8fq3DspG4JLjCtzOg8L7tJA95hEDMu4U0oAqEdhZ6UsEA@H848ObFzxJOYPZ5c/aJ3@HCInH1576UCdOQBknpgyNzsgNJV3yyh4TQoaQlG@yeEaYCGUWpLOuLGlPmG0nQz0SXL62RddOcIDUFWR38AfkH0A@YV5HVc5B5sX28kywuPfCaeFX7vXybf "Python 3 – Try It Online")
### [Python 3](https://docs.python.org/3/), 137 bytes
Works for all cases including `CH_2`.
```
lambda e:['Aldehyde','Alcohol','Carboxylic Acid',0][e[::-1].rfind('O')]or'Alk%sne'%'yae'[eval(e.translate({67:43,72:43,95:'~-'})+'//-2')]
```
[Try it online!](https://tio.run/##XZDPToQwEMbvPEUvm2kjsC6sbmyCyYYLNx4ACenCEBprS6CrEqOvjgU0Jl5mvvzmT2a@frKd0fHcJk@zEi@XRhDkBZxVg93UIPhO1qYzyqlUDBfzPilZk3MtG/BvywILzoNDGQ6t1A2FHFhpBjfzvBs1wg4mgVDgq1AUQzsIPSphkX7cn/gx9k/REh/uOHwF8MluYL8PIrdhfuukQnLgHpG694m52p4ki75aysKxV9JSIMEjAeaRfpDa0pa6MvO3RJJkHWJzmlXHpdFdJDR6aRX9AfwF0Q@YFpBVcZ5tYH18JWmWb2izZWP51vfPlm8 "Python 3 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 115 bytes
```
s=>[[x,y]=s.match(/\d+/g),'Aldehyde','Alcohol','Carboxylic Acid'][s.length-s.search`O`]||`Alk${'aey'[x-y/2+1|0]}ne`
```
[Try it online!](https://tio.run/##dcyxDoIwAATQ3a9wMClEKILGDRPC0o0PwKbUtlC0UkOJoRG/HdHRwHa5l7srfVLD2vrR@Y3mYizj0cSnPO89i2MD77Rj0gnOfBtUrgcSxYW0XIBvZFpqNaWUthfdW1WzdcJqDnBuoBJN1UnfQCNoy2SRFXgYikTdNi9AhQV579sg2obDDr8bUYxMN0YrAZWunNIBKSIH4Lqr/5pEiByXYH4RThItnkVzgMg@QwuQomxJst9o/AA "JavaScript (Node.js) – Try It Online")
Thanks [A username](https://codegolf.stackexchange.com/users/100664/a-username), -3 bytes.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 110 bytes
```
.*O..
Carboxylic Acid
.*O.
Alcohol
.*O
Aldehyde
_\d+
$*
CH.*|C(1+)H11\1\1
Alkane
C(1+)H\1\1
Alkene
C1.*
Alkyne
```
[Try it online!](https://tio.run/##K0otycxL/P9fT8tfT4/LObEoKb@iMiczWcExOTOFCyTK5ZiTnJ@RnwPiANkpqRmVKalc8TEp2lwqWlzOHnpaNc4ahtqaHoaGMUAIVJKdmJfKBRGDiaSCRAz1tEDsyrzU//@dPeJNuJzjjeCUEdCoeGN/DzDl7OEPof39PQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.*O..
Carboxylic Acid
.*O.
Alcohol
.*O
Aldehyde
```
Identify these three groups by the position of the `O` from the end.
```
_\d+
$*
```
Convert the suffixes to unary.
```
CH.*|C(1+)H11\1\1
Alkane
C(1+)H\1\1
Alkene
C1.*
Alkyne
```
Identify these three groups by comparing the number of carbon and hydrogen atoms.
[Answer]
# JavaScript (ES6), 122 bytes
I tried to gather all information within a single `.map()` statement, but this is not as competitive as I thought it would be.
```
s=>[`Alcohol`,`Alk${"aey"[s.split(/(\D_?)/).map(n=>++k*n?d=p-(p=n)/2:0,k=p=1)|-~d]}ne`,`Aldehyde`,,`Carboxylic Acid`][k%5]
```
[Try it online!](https://tio.run/##jZHdToMwGIbPvQqyaNY6fhzbjDHplgUPONsFIIFKO4fUtgFcJP7cOnawJcBA7Um/gydf3/fpC97jLEpjmRtcEFpuUZmhpReuWSR2goW6mpLLjxGmxcjLzEyyOAcWeHwIVtCC5iuWgKPlZJJc8xVB0gAScWjZ9zd6giSawk/jm/hfnFaLCN0VRI166OD0SbwXLI60dRST0PeSq4VfRoJnglGTiWewBWPHDeZjCLX6WJamsmBOL7pYYDfAGqMDmN3Gih7MDWYbt4VVKvo4x90cwYqr@/WCm9NKBXbK9@a8befEvTntrhzVWgMi1WK@xywm6pZvOTx/YHbmqxjwtWjkHhJRcScVv4mowaOK/4hQOe/@FhFMDx87b@Q8iCh/AA "JavaScript (Node.js) – Try It Online")
### How?
We split the input with:
```
s.split(/(\D_?)/)
```
Each entry in the resulting array is:
* a letter followed by an optional `_` if its position is odd
* either an empty string or a number of its position is even
We walk through all entries and compute:
* \$d\$ : the difference between the penultimate number and the last one divided by \$2\$, assuming that there's an additional \$1\$ at the beginning (in case it's omitted like in `CH_4`)
* \$k\$ : the length of the array \$+1\$
We use \$k\bmod5\$ to figure out the main type of the homologous group:
```
type | k | mod 5 | example
----------+----+-------+--------------------------------------------------------------
Alk*ne | 6 | 1 | C_2H_4 -> ['','C_','2','H_','4']
Alcohol | 10 | 0 | CH_3OH -> ['','C','','H_','3','O','','H','']
Aldehyde | 12 | 2 | CH_3CHO -> ['','C','','H_','3','C','','H','','O','']
Acid | 14 | 4 | CH_3COOH -> ['','C','','H_','3','C','','O','','O','','H','']
```
We use the sign of \$d\$ to distinguish between Alkane, Alkene and Alkyne.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~190~~ ~~188~~ 186 bytes
Thanks to ceilingcat for the -2.
The string is passed through a state machine that stores the initial C and O values and terminates early if there are no trailing characters after the second value. If the state ends early, then the difference between the two values is used to determine which type the molecule is; otherwise the first two trailing characters are used.
**Annotated version**
```
b,t, // State, molecule type
m[2], // C and O amounts
*a[]={"Aldehyde","Carboxylic Acid","Alcohol"};
f(char*s){
for(b=3;*s++&&b--;) // Final states: 1 (alk[aey]ne), -1 (other)
t=b? // Initial C and O
m[b-1]=*s-95? // Is there an underscore (implies number)?
1: // No, assume 1
strtol(s+1,&s,0) // Yes, get number and go to next part
: // Trailing characters (not alk[aey]ne)
s[-1]-67? // First character is 'C'?
2: // No, is alcohol
*s==79; // Yes, either aldehyde or acid
printf(~b?"Alk%cne":a[t],"y e a"[*m-m[1]*2+2]);
}
```
```
b,t,m[2],*a[]={"Aldehyde","Carboxylic Acid","Alcohol"};f(char*s){for(b=3;*s++&&b--;)t=b?m[b-1]=*s-95?1:strtol(s+1,&s,0):s[-1]-67?2:*s==79;printf(~b?"Alk%cne":a[t],"y e a"[*m-m[1]*2+2]);}
```
[Try it online!](https://tio.run/##PZBLb4JAEMfvfIrJNhpYlqag1cp2JcYLB1NPPRFCYIFCysOwa1Nj8KvT9VFO85/fvIdbX5wPQ0IkqQMnJDgOQnZGmyrNilOaIYK2cZe0v6eq5LDhZarIpuJt0Vaop7nOi7jDwjjnbacnbEaxMM3pNLEsakiWeHWQWHbIsLBWr57tCtnJttKFaZOpIC@GKwIVthZLz3GxYGy5ooeubGSuXxJPzfme8CZDbhzIkKATZBCjANdWHdghdkwnNGg/PJUNr45pBu9CpmX7XKw1TbWAOi4b/actUwPOGsB1UcDieh2grR/NEVE2cvxoMaoHm/vR28ickd3z/Gi29//V1t@Pcn/DH5@7HfQEMJZUU2Ovf5FMUFA@SNO8LwPwOBNNBLA1qEIsDXqL5PooD0cpdIRuXq/1wx8 "C (gcc) – Try It Online")
] |
[Question]
[
## Introduction
I began studying the [Collatz Conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture)
And noticed these patterns;
[0,1,2,2,3,3...A055086](https://oeis.org/A055086), and [0,1,2,0,3,1...A082375](https://oeis.org/A082375),
in the numbers that go to 1 in one odd step,
[5,10,20,21,40,42...A062052](https://oeis.org/A062052)
Related like so;
[A062052](https://oeis.org/A062052)()(n) = ( 16\*2^[A055086](https://oeis.org/A055086)(n) - 2^[A082375](https://oeis.org/A082375)(n) ) /3
The formula for [A055086](https://oeis.org/A055086) is $$\lfloor\sqrt{4n + 1}\rfloor - 1$$
and the formula for [A082375](https://oeis.org/A022332) is $${\left\lfloor\sqrt{4\left\lfloor x\right\rfloor+1}\right\rfloor - 1 - \left\lfloor \frac12 \left(4\left\lfloor x\right\rfloor + 1 -\left\lfloor\sqrt{4\left\lfloor x\right\rfloor+1}\right\rfloor^2\right)\right\rfloor}$$
So the formula for [A062052](https://oeis.org/A062052) most likely is
$$\frac{8\cdot2^{\left\lfloor\sqrt{4\left\lfloor x\right\rfloor+1}\right\rfloor} - 2^{\left\lfloor\sqrt{4\left\lfloor x\right\rfloor+1}\right\rfloor - 1 - \left\lfloor \frac12 \left(4\left\lfloor x\right\rfloor + 1 -\left\lfloor\sqrt{4\left\lfloor x\right\rfloor+1}\right\rfloor^2\right)\right\rfloor}}{3}$$
Then I looked at numbers going to 1 in two steps, like [3,6,12,13,24,26...](https://oeis.org/A062053)
Where I found another pattern that I could not find a formula for on OEIS
```
long nth(int n){if(n>241)return -1;return (((1<<Y[n]+5)-(1<<1+Y[n]-((Z[n]&1)+Z[n]*3)))/3-(1<<Y[n]-2*X[n]-(2*(Z[n]&1)+Z[n]*3)))/3;}
```
With `X[],Y[] and Z[]` being these lookup-tables
```
int[]X=new int[]{
0,
0,
0, 1,
0, 1,
0, 1, 2,
0, 1, 2, 0,
0, 1, 2, 3, 0, 0,
0, 1, 2, 3, 0, 1, 0,
0, 1, 2, 3, 4, 0, 1, 0, 1,
0, 1, 2, 3, 4, 0, 1, 2, 0, 1,
0, 1, 2, 3, 4, 5, 0, 1, 2, 0, 1, 2,
0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 0, 1, 2, 0,
0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 0, 1, 2, 3, 0, 0,
0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 0, 1, 2, 3, 0, 1, 0,
0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 0, 1,
0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 0, 1, 2, 0, 1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 0, 1, 2,
0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 0, 1, 2, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 0, 1, 2, 3, 1, 2
};
int[]Y=new int[]{
0,
1,
2, 2,
3, 3,
4, 4, 4,
5, 5, 5, 5,
6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7,
8, 8, 8, 8, 8, 8, 8, 8, 8,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18
};
int[]Z=new int[]{
0,
0,
0, 0,
0, 0,
0, 0, 0,
0, 0, 0, 1,
0, 0, 0, 0, 1, 2,
0, 0, 0, 0, 1, 1, 2,
0, 0, 0, 0, 0, 1, 1, 2, 2,
0, 0, 0, 0, 0, 1, 1, 1, 2, 2,
0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3,
0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 4,
0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4,
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 4, 4,
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5
};
```
## Challenge
The challenge is to write a "reasonably fast" function or expression that replaces, and extends these lookup tables to index 719 or more.
Think of the lookup tables as a 3D structure of boxes.
Pictured is the top 720 boxes of this structure.
[](https://i.stack.imgur.com/ZMois.png)
## Input
An integer which is the index of a cube in the structure.
You can assume the input will be in the range 0 to 719 inclusive.
## Output
The x,y,z coordinates for the given index.
Assuming the input is between 0 and 719 the output ranges are
x, 0 to 13
y, 0 to 27
z, 0 to 8
It's fine to accept and return larger indexes correctly just not required.
## Examples
```
i -> x y z
0 -> 0, 0, 0
12 -> 0, 5, 1
30 -> 4, 8, 0
65 -> 2, 11, 1
100 -> 0, 13, 2
270 -> 1, 19, 3
321 -> 1, 20, 6
719 -> 1, 27, 8
```
If you collapse the z-coordinate, then the structure is indexed top-down left right like shown below; Examples are marked in square brackets []
```
Y,Z 0,
0 | [0]
1 | 1
2 | 2 3
3 | 4 5
4 | 6 7 8 1,
5 | 9 10 11 |[12] 2,
6 | 13 14 15 16 | 17 | 18
7 | 19 20 21 22 | 23 24 | 25
8 | 26 27 28 29 [30] | 31 32 | 33 34
9 | 35 36 37 38 39 | 40 41 42 | 43 44
10 | 45 46 47 48 49 50 | 51 52 53 | 54 55 56 3,
11 | 57 58 59 60 61 62 | 63 64 [65] 66 | 67 68 69 | 70 4,
12 | 71 72 73 74 75 76 77 | 78 79 80 81 | 82 83 84 85 | 86 | 87
13 | 88 89 90 91 92 93 94 | 95 96 97 98 99 [100] 101 102 103 |104 105 |106
14 |107 108 109 110 111 112 113 114 |115 116 117 118 119 |120 121 122 123 124 |125 126 |127 128
15 |129 130 131 132 133 134 135 136 |137 138 139 140 141 142 |143 144 145 146 147 |148 149 150 |151 152
16 |153 154 155 156 157 158 159 160 161 |162 163 164 165 166 167 |168 169 170 171 172 173 |174 175 176 |177 178 179 5,
17 |180 181 182 183 184 185 186 187 188 |189 190 191 192 193 194 195 |196 197 198 199 200 201 |202 203 204 205 |206 207 208 |209 6,
18 |210 211 212 213 214 215 216 217 218 219 |220 221 222 223 224 225 226 |227 228 229 230 231 232 233 |234 235 236 237 |238 239 240 241 |242 |243
19 |244 245 246 247 248 249 250 251 252 253 |254 255 256 257 258 259 260 261 |262 263 264 265 266 267 268 |269[270]271 272 273 |274 275 276 277 |278 279 |280
20 |281 282 283 284 285 286 287 288 289 290 291 |292 293 294 295 296 297 298 299 |300 301 302 303 304 305 306 307 |308 309 310 311 312 |313 314 315 316 317 |318 319 |320[321]
X->| 0 1 2 3 4 5 6 7 8 9 10 | 0 1 2 3 4 5 6 7 | 0 1 2 3 4 5 6 7 | 0 1 2 3 4 | 0 1 2 3 4 | 0 1 | 0 1
```
Note that at even y-coordinates the structure expands in the x-direction,
and at 0 and 5 mod 6 in the z-direction.
# Rules
This is code-golf, the shortest code in bytes wins.
**Reasonably fast**
As an additional requirement although not a competition of fastest code,
the code must still be shown to compute coordinates in a reasonable amount of time.
\$\ O(n)\$ or less time-complexity with regards to index is valid by default
Alternatively may for example use try it online or similar website and run a loop through all coordinates under 720 without exceeding the time limit of a minute, printing is optional.
Any time-complexity is valid as long as actual time is reasonably low.
Lookup tables are allowed but included in byte-count so aim to make them sparse if you choose to use them.
# Example code
EDIT: Look at Nick Kennedy's solution
Original example;
```
coord coords(int index){
int a=0,b=0,c=0;
int x=0,y=0,z=0;
long n,k,one;
n = k = 3;
int t=0;
while(t<index){
int s=0;k++;n=k;
while(n>1 && s<4){ n/=n&-n;n=n*3+1; n/=n&-n;s++;}
if(s==2)t++;
}
n=k;
one=n&-n;k = one;while(k>1){k>>=1;c++;} n=3*n+one;
one=n&-n;k = one;while(k>1){k>>=1;b++;} n=3*n+one;
one=n&-n;k = one;while(k>1){k>>=1;a++;}
coord r;
r.x = (b-c-1)>>1;
r.y = a-5;
r.z = (a-b-2)/6 +(a-b-4)/6;
return r;
}
```
[Try it online!](https://tio.run/##nZJNboMwEIX3OcWIqhEESEOStgtjn6QbMJBYpEMERuVHnD0d45JWXVVFjGV/fm9mZFuGJylvDwrlpc1yiBudqWp7FivdX/MsL6DRdSs1yKqqMxgVauiCPhjYZBG72Z15bFyzrzDLO29cAX1mnfBdkFJIvmN32BHoKYYFXio8AQZlUGHOAGaGwKGkOHz79KL/OKtL7ur4d7WGBKXvM@TlTyGKCNZraOKjNwI@cVyHSBrcHPyI3UFDxsmmKtyG872niczAYpPV9kZtWo9p0PRs65Qi8sZSCB4xaZKR47BB3wj@aEv/Z0tm2yy2N1JbZ73tyOKmoQwjT4hooT3RJHxeloMRJWEa7r2nF/Dn6ZGmX/u5bms0KaebOeT3RKFLh36vdG114zoKQgEd9DA4HlsVVW3fA92IiuF1vwOmfJ9sNRVbHgwJrzXJCtd5zIyfxvl/QydQAbVP0VMMpJyo/ic) Note it's too slow!
[Answer]
# [Python 3](https://docs.python.org/3/), ~~150~~ 140 bytes
```
def f(n):
a=b=x=y=z=0
for i in range(n):
a=x-~x<y--~z//2*6+z%2
b=z<y//6+-~y//6
x=-~x*a
y+=not(a|b)
z+=b>a
z*=a|b
return x,y,z
```
[Try it online!](https://tio.run/##XY7BCoMwEETvfsVeCsYYIhYsiNsfKT0kVNtcVgkpJKH46@lKbz3NzOMdZkvhtdK5lMe8wFKTGCswaDFiwoxdBcvqwYEj8Iae809gI6o9TkmpPWvdN4PMp565xTwlrQep9iOYRGSxMdySRFpDbT5W8MoS7fXAuUFGFfg5vD1BbFOby23zjkLtWr7khPg/cek7cS9f "Python 3 – Try It Online")
Has \$O(n)\$ complexity. TIO footer prints first 720 values in about 0.5 seconds.
Thanks to @ElPedro and @PrincePolka for each saving 5 bytes!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
5,1ṁ9ĖŒṙṚḊḊḊ$Ƭz0ZUṬ€€ỊŒṪ’ṙÞ1ị@‘
```
A monadic link accepting an integer in \$[0,719]\$ which yields a list of three integers \$[X, Y, Z]\$.
**[Try it online!](https://tio.run/##y0rNyan8/99Ux/DhzkbLI9OOTnq4c@bDnbMe7uiCIJVja6oMokIf7lzzqAmEHu7uAqlZ9agBqGzm4XmGD3d3OzxqmPH//39zQ0sA "Jelly – Try It Online")**
Or see the [test-suite](https://tio.run/##y0rNyan8/99Ux/DhzkbLI9OOTnq4c@bDnbMe7uiCIJVja6oMokIf7lzzqAmEHu7uAqlZ9agBqGzm4XmGD3d3OzxqmPHf3Mjg4Y5tR/ccbgfJz1ABqlXxBhKR/wE "Jelly – Try It Online") (which completes in around 12-20s on TIO)
### How?
Builds a lookup table and indexes into it:
```
5,1ṁ9ĖŒṙṚḊḊḊ$Ƭz0ZUṬ€€ỊŒṪ’ṙÞ1ị@‘ - Link: integer, n
5,1 - pair literal = [5,1]
ṁ9 - mould like 9 = [5,1,5,1,5,1,5,1,5]
Ė - enumerate = [[1,5],[2,1],[3,5],[4,1],[5,5],[6,1],[7,5],[8,1],[9,5]]
Œṙ - run-length-decode = [1,1,1,1,1,2,3,...,7,7,7,7,7,8,9,9,9,9,9]
Ṛ - reverse = [9,9,9,9,9,8,7,7,7,7,7,...,3,2,1,1,1,1,1]
Ḋ - dequeue = [9,9,9,9,8,7,7,7,7,7,...,3,2,1,1,1,1,1]
Ƭ - collect until a fixed-point:
$ - last two links as a monad:
Ḋ - dequeue
Ḋ - dequeue
- } = [[9,9,9,9,8,7,7,7,7,7,...,3,2,1,1,1,1,1],[9,9,8,7,...],[8,7,...],...,[1,1],[]]
z0 - transpose with filler zero
Z - transpose
U - reverse each list
Ṭ€€ - un-truth each int (e.g. 5 -> [0,0,0,0,1])
Ị - insignificant? (abs(x)<=1) (e.g. [0,0,0,0,1]->[1,1,1,1,1])
ŒṪ - truthy multi-dimensional 1-indexed indices
’ - decrement (i.e. all the [X,Y,Z] values)
Þ - sort by:
ṙ 1 - the list value rotated left by one (i.e. by [Y,Z,X])
‘ - increment (n) (since Jelly is 1-indexed)
@ - with swapped arguments:
ị - index into
```
[Answer]
# JavaScript, ~~93~~ 85 bytes
A port of [Nick's Python solution](https://codegolf.stackexchange.com/a/188283/58974).
```
n=>(g=x=>n--?g(x<y+~z/2n*6n+z%2n>>1n?++x:z<y/6n-~y/6n?++z-z:z=++y-y):[x,y,z])(y=z=0n)
```
[Try It Online!](https://tio.run/##FY1BCoMwEAC/IoFC0jU1evCgbnyIeBCr0iIb0VKSPfj11F7mMDDMe/gOx7i/to8m95zijJHQygU9WtK6XaRvApycFXQvCfhWkLU5tQC@4iZkJenzz0uw5ooRIOigqs6nIeVeyYCMhlSc3S49mto3uTGmvno1OjrcOj1Wd11AJJh0AmbpFYheqPgD)
Saved 8 bytes thank to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s suggestion of using BigInts, plus a couple of other tweaks.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~54~~ 41 bytes
```
HĊ×6_Ḃ{ạHḞ;;‘$:6SƊ}
<Ḋç/$T;3ḢṬ
0x3Ç+×¥$⁸¡
```
[Try it online!](https://tio.run/##AU4Asf9qZWxsef//SMSKw5c2X@G4gnvhuqFI4bieOzvigJgkOjZTxop9CjzhuIrDpy8kVDsz4bii4bmsCjB4M8OHK8OXwqUk4oG4wqH///83MTk "Jelly – Try It Online")
Loosely a Jelly translation of [my Python 3 answer](https://codegolf.stackexchange.com/a/188283/42248) but much slower. Still \$O(n)\$ though. Outputs `[x, z, y]`.
] |
[Question]
[
# Input
An integer n in the range 100 to 10^18 and an integer k in the range 1 to 18, inclusive.
# The swap operation
A swap chooses two digits at different positions and exchanges their positions, as long as the swap does not result in a leading zero. For example if we start with the integer `12345` we can perform one swap to make it `12543`.
# Task
Output the largest number you can get after exactly k swaps.
# Examples
```
n = 1283, k = 2. Output: 8312
n = 510, k = 1. Output: 501
n = 501, k = 2. Output: 501
n = 999, k = 3. Output: 999
n = 12345678987654321, k = 1. Output: 92345678187654321
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~194~~ ~~190~~ ~~196~~ ~~193~~ ~~175~~ ~~164~~ 162 bytes
```
def f(n,k):
for i in range(len(n)-1):
y=max(n[i:]);j=n[::-1].index(y)
if(y>n[i])*k:n[i],n[~j]=y,n[i];k-=1
if len(n)-len({*n})<k%2:n[-2:]=n[:-3:-1]
return n
```
[Try it online!](https://tio.run/##XY5BTsMwEEX3PsVsUO3IqbBdt4lLuEjkRVDi1Ek7qUyQGiG4erARSIXV1/vz9DXXZT5NqNa17Rw4inxkhoCbAnjwCKHBvqPnDimyXKQTLNWluVGsvbHsOFRYG5MLu/XYdje6sGh4R5fnKFiWjSYlx/pzsNXCExzHvBIkSvAzm@I9ww/2ND7I6OfS2DSbqzRMIHTzW0DAta/OzeWlbSB@aTab7TB5pI7W2esc4pCNvzNCrsHjTHsqZKG4jM1vocUjF3dcliVXdyyk2un9oSiLw17vlBR/bV3@Y/0trF8 "Python 3 – Try It Online")
Pretty tough to golf this challenge in a real world language - I like it :)
After golfing down to 190 bytes (and below..), I found some cases where the algorithm would not find the maximum possible value. Bugfixing forced me back up to ~~196~~ 193 bytes :/
... then I found some ways to better handle branching on `k` and went down below 180 :)
After the comment from Chas Brown, switching from integer to list I/O saved 28 bytes! (And more golfing another 2..)
Then, another bug: the algorithm incorrectly handles remaining swaps, if there are equal digits present. The fix cost 19 bytes.
### Algorithm:
1. For each digit, starting from the leftmost one, swap it with the rightmost maximum digit, if that one is bigger. First line of the `for`-loop finds the maximum and its index. Second line does the swap.
2. If there are `k'` swaps left, swap two equal digits, or the two rightmost `k'` times. I.e. if there are two equal digits present, or if `k'` is even, no more swaps have to be done. Else, just swap the last two digits once.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
JŒ!nJ$S⁼ɗƇ2ị⁸Ṁµ¡
```
**[Try it online!](https://tio.run/##ATAAz/9qZWxsef//SsWSIW5KJFPigbzJl8aHMuG7i@KBuOG5gMK1wqH///8xLDIsOCwz/zI "Jelly – Try It Online")**
A dyadic Link accepting a list of digits (as non-negative integers) on the left and a non-negative integer on the right which yields a list of digits.
### How?
```
JŒ!nJ$S⁼ɗƇ2ị⁸Ṁµ¡ - Link: L, n
µ¡ - repeat the monad to the left n times -- i.e. f(f(f(...(L)...))):
J - range of length
Œ! - all permutations
Ƈ - filter keep if:
ɗ 2 - last three links as a dyad with right argument 2
$ - last two links as a monad:
J - range of length
n - not equal? (vectorises)
S - sum
⁼ - equal?
ị - index into (vectorises):
⁸ - chain's left argument, L
Ṁ - maximum
```
---
**20 byte version** which is fine within the previous time-constraint since \$\binom{18}2=\frac{18\times 17}2=153\$
```
JŒcœṖḢ;Ḣ€ṚżƊƊFɗ€⁸Ṁµ¡
```
[Try it online!](https://tio.run/##y0rNyan8/9/r6KTko5Mf7pz2cMciayB@1LTm4c5ZR/cc6zrW5XZyOpD7qHHHw50Nh7YeWvj//39DHSMdYx0THVMdMx1zHQsdSyA2B7JNgWLGQDnD/4YWAA "Jelly – Try It Online")
### How?
```
JŒcœṖḢ;Ḣ€ṚżƊƊFɗ€⁸Ṁµ¡ - Link: L, n
µ¡ - repeat the monad to the left n times -- i.e. f(f(f(...(L)...))):
J - range of length
Œc - all (length(L)-choose-2) pairs: [[1,2],[1,3],[1,4],...,[2,3],[2,4],...]
€ - for each (such pair, P):
ɗ ⁸ - last three links as a dyad, with right argument L:
œṖ - partition (L) at indexes (P) - call this X
Ɗ - last three links as a monad - i.e. f(X):
Ḣ - head (of X) (the items up to but not including the first to swap)
Ɗ - last three links as a monad - i.e. f(X):
Ḣ€ - head each (actually removes them too) (the items to swap)
Ṛ - reverse
ż - zip with (the altered X)
; - concatenate
F - flatten
Ṁ - maximum
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~185~~ ~~177~~ ~~173~~ ~~166~~ ~~164~~ ~~161~~ 152 bytes
```
def f(a,k):exec"i=0;j=L=len(a)-1\nwhile i<L>0<a[i]==max(a[i:]):i+=1\nwhile a[j]<max(a[i:]):j-=1\nj-=i==j<=L<len(set(a));a[i],a[j]=a[j],a[i];"*k;return a
```
[Try it online!](https://tio.run/##TY/dcsIgEIXv8xQ79kJoMRMSo/nbXnrlG1hnpA2pREMyhE7t06eg1unN8rGHPXsYfuyx1/E01bKBhgh2ooW8yI@ZwqhscYtnqYmgC/6mv4/qLEFV29eoEju1R@zEhTgq9rRQL/h4InbtvvqntQuvuaoQ2wq3lfccpXW@tPROzE@gL8xfy9nzqTTSfhkNYnqCpjedsP4AKUYlDRgpaqU/wzAMNngW3XstQLMT8mI@D9teadKJgYzWsOZKSlt20AfqfkdpEFg52hEQCI@zJOOMU3ZjBvENI8eJxzz701MeMbj18vxB/E48Tpbpap3l2XqVLpPY9e@uDFK30od3CUFpuG4vAoDBuFywIa5Pg@kX "Python 2 – Try It Online")
Takes a list of digits and an integer k; returns a list of digits.
```
j-=i==j<=L<len(set(a))
```
uses a bunch of shortcuts, and is the same as:
```
if i==j: # if i==j, then the list is already sorted
if len(a)-1<len(set(a)): # since len(a)>=len(set(a)) is *always* True,
# this means len(a)==len(set(a), i.e,
# a has no duplicated digits,
j = i-1 # so do a swap with the rightmost digits
```
[Answer]
# [Python 2](https://docs.python.org/2/), 113 bytes
```
f=lambda l,k,E=enumerate:l*0**k or f(max(l[:i]+[y]+l[i+1:j]+[x]+l[j+1:]for(i,x)in E(l)for j,y in E(l)if i<j),k-1)
```
[Try it online!](https://tio.run/##PY9BboMwEEX3nGKkLmKHKcIQEkBlmVwCIcVVTGowBhlXgtNTE0hXfv@PNPM8zPan19Gy1IXi3feDg8IWr4XQv50w3IpcHcPjsYXeQE06PhFV5rLyy7nyVSl9ljcuTGtoXKjq3hCJE5UarkRRF6HBGfYoa5BfDcX2k9HlA9y043Z9QPBRCgNG8IfUzyAIvNtbSGNbsPxwCJpeaqcwkNEarF8ktcW7vruNlFLPs2K0IxRAWJTGKUNGcWOEaMPQcbxilr7nCQsRti7L/ontxKL4lJwvaZZezskpjly/b0VI3MlV3hmuP3xdzz2AwTgvuBHXU2/5Aw "Python 2 – Try It Online")
Greedily does the best swap at each step, found by testing all possible swaps and taking the maximum.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 162 bytes
```
$f={param($s,$k)if($k--){$s=if($s.length-le2){&$f($s[1]+$s[0])$k}else{($m=($s|% t*y|sort)[-1])+(&$f(($s-replace"(?<!$m.*)$m",$s[0])|% s*g 1)($k+=$s[0]-eq$m))}}$s}
```
[Try it online!](https://tio.run/##VZDhboJAEIT/@xRXspZbPYwHotCUtO9hSGPsqg1HpRxN2yDPThfQWu/HZe@bnblkiuMXlfZAxrQt7JK62JSbXIJVkOHbTkLmeViDTbrZzgy976uDZ8jH@h46tNbplO95ipA1ZCzVEvKEhdNYVJOfkz2WFa49neJUdg5WvJIKs9mSI58e7yCfTRByRw0h7LKTvdDIP0@Tnnn0ATli04Bt2mc5EnyUdLUfBa4SvhJuFGjfxYsQ6jlzzTyc63@YH8P6DY7jmHHAuJvwmh4swuUqiqPVMlwEvj5Hxmeu//jV4iqt3FvgDwDFSYxF3Qt9tQrou6BtRa8iEfAyCCXZT1Mx4J54TUDWcwfkWeqauPjw4WJwRk37Cw "PowerShell – Try It Online")
The Recursive Function. Less golfed:
```
$f={
param($s,$k)
if($k--){
$s=if($s.length-le2){
&$f ($s[1]+$s[0]) $k
}
else{
$max=($s|% t*y|sort)[-1]
$k+=$s[0]-eq$max
$s=$s-replace"(?<!$max.*)$max",$s[0]
$s=$s|% subString 1
$max+(&$f $s $k)
}
}
$s
}
```
---
## Alternative, 169 bytes
```
param($s,$k)1..$k|%{do{if($s.length-le2){$s=-join$s[1,0]
$r=0}else{$m+=($c=($s|% t*y|sort)[-1])
$r=$s[0]-eq$c
$s=($s-replace"(?<!$c.*)$c",$s[0])|% s*g 1}}while($r)}$m+$s
```
] |
[Question]
[
Your goal is to output all the "sides" (corners, edges, faces, etc.) of an N-dimensional unit hypercube, where N is non-negative. A "side" is defined as any (N-M)-dimension surface embedded in N-dimensional space, where `1 <= M <= N`.
The hypercube spans the space [0, 1] in each dimension. For example, for N=2 the square is bounded by the corner points (0, 0) and (1, 1).
# Input
Your function/program should take a single non-negative integer N. You may assume N <= 10.
# Outputs
The output may be to any convenient format desired: return a list, print to stdio/file, output parameters, etc.
The output must contain the min/max bounds of all unique sides. Order does not matter.
**Example sides formats**
A 0D side (a.k.a. a point) in 3D space could be bounded by:
```
# in [(min0, max0),...] format, this is the point 0,1,0
[(0, 0), (1, 1), (0, 0)]
```
A 1D side (a.k.a. an edge) in 2D space could be bounded by:
```
# in [(min0, min1,...), (max0, max1,...)] format, this is the line from point (0,0) to (1,0)
[(0, 0), (1, 0)]
```
Note that it is ok to flatten the output any way you want ([min0, max0, min1, max1, ...] or [min0, min1, min2, ..., max0, max1, max2, ...], etc.)
[Wikipedia has a list](https://en.wikipedia.org/wiki/Hypercube) of the number of sides to expect for various hypercubes. In total, there should be `3N-1` results.
**Full sample outputs**
This uses the convention `[min0, max0, min1, max1, ...]`
N = 0
```
empty list (or no output)
```
N = 1
```
[0, 0]
[1, 1]
```
N = 2
```
[0, 1, 0, 0]
[0, 0, 0, 1]
[0, 1, 1, 1]
[1, 1, 0, 1]
[0, 0, 0, 0]
[0, 0, 1, 1]
[1, 1, 0, 0]
[1, 1, 1, 1]
```
N = 3
```
[0, 1, 0, 1, 0, 0]
[0, 1, 0, 0, 0, 1]
[0, 0, 0, 1, 0, 1]
[0, 1, 0, 1, 1, 1]
[0, 1, 1, 1, 0, 1]
[1, 1, 0, 1, 0, 1]
[0, 1, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0]
[0, 0, 0, 0, 0, 1]
[0, 1, 0, 0, 1, 1]
[0, 1, 1, 1, 0, 0]
[0, 0, 0, 1, 1, 1]
[0, 0, 1, 1, 0, 1]
[1, 1, 0, 1, 0, 0]
[1, 1, 0, 0, 0, 1]
[0, 1, 1, 1, 1, 1]
[1, 1, 0, 1, 1, 1]
[1, 1, 1, 1, 0, 1]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 1]
[0, 0, 1, 1, 0, 0]
[1, 1, 0, 0, 0, 0]
[0, 0, 1, 1, 1, 1]
[1, 1, 0, 0, 1, 1]
[1, 1, 1, 1, 0, 0]
[1, 1, 1, 1, 1, 1]
```
# Scoring
This is code golf; shortest code wins. Standard loop-holes apply. You may use built-in functions like "permute a sequence" so long as it wasn't designed specifically for this problem.
Your code should run in a reasonable amount of time for N <= 6 (say, 10 minutes or less)
[Answer]
## Pyth, 10 chars
```
P^cj49J2JQ
```
[Try it here.](https://pyth.herokuapp.com/?code=P%5Ecj49J2JQ&test_suite=1&test_suite_input=0%0A1%0A2%0A3&debug=1) Output is a list of sides each in the format. `[[min0, max0],[min1, max1],...]`.
```
P All but the last element of
^ Q the nth cartesian power of
j49J2 the number 49 as a binary list [1,1,0,0,0,1]
c J split into chunks of 2 [[1,1],[0,0],[0,1]]
```
In our output, we want all lists of `n` elements from `[[1,1],[0,0],[0,1]]`, except the one with only `[0,1]`'s. This is just the `n`th cartesian power of `[[1,1],[0,0],[0,1]]` with the last element removed.
The list `[[1,1],[0,0],[0,1]]` is created by converting 49 into binary and breaking into chunks of 2. One can do `.CU2 2` to get `[[0,0],[0,1],[1,1]` as all sorted sublists of 2 elements from `[0,1]`, but we need `[0,1]` at the start or end to remove the list with only it from the product.
[Answer]
## CJam (13 bytes)
```
49Yb2/rim*);`
```
[Online demo](http://cjam.aditsu.net/#code=49Yb2%2Frim*)%3B%60&input=3)
Output format is as a list of list of ranges: e.g. for input `1` (where the two sides are the points `(0, 0)` and `(1, 1)`) the output is `[[[1 1]] [[0 0]]]`.
### Dissection
```
49Yb2/ e# Generate the list of ranges: [[1 1] [0 0] [0 1]]
rim* e# Take the nth Cartesian power
); e# Remove the last one, which is the full hypercube
` e# Format for output
```
[Answer]
# Ruby, ~~66~~ 63
Returns an array of strings, each one containing 2n `0`s and `1`s without separators.
```
->n{(0..3**n-2).map{|i|s=""
n.times{s+="0011"[-i%3,2];i/=3}
s}}
```
In a similar way to at at least one other answer it generates all possibilities of `["00","11","01"]` repeated n times, except `"0101....0101"`, by iterating through all the n-digit base 3 numbers `00..00` to `22..21` (deliberately missing `22..22`) and then substituting. Initially I had the string `"011101"` (`"01"` had to be at the end) but then I realised if I fed `-i` instead of `i` to the `%3` operation, I could swap the 2 and 1. I was then able to reduce the string to `"0011"`, overlapping the three possible 2-character strings I required.
**Ungolfed in test program**
```
f=->n{
(0..3**n-2).map{|i| #iterate through all n-digit base 3 numbers 00..00 to 22..21
s=""
n.times{ #for each base 3 digit in i append the following to s
s+="0011"[-i%3,2] #0 --> 0 -->"00"; -1 --> 2 --> "11"; -2 --> 1 --> "01"
i/=3 #divide by 3 to remove the last base 3 digit from i
}
s #add s to the array being built by map.
}
}
puts f[gets.to_i]
```
**Output n=2**
```
0000
1100
0100
0011
1111
0111
0001
1101
```
[Answer]
## CJam, 24 bytes
```
2ri2*m*{2/__:$=\2,a-*},p
```
Uses the same interleaved `[min0 max0 min1 max1 ...]` format as the test cases in the challenge. It solves `N = 10` in a couple of minutes.
[Test it here.](http://cjam.aditsu.net/#code=2ri2*m*%7B2%2F__%3A%24%3D%5C2%2Ca-*%7D%2Cp&input=5)
### Explanation
```
2 e# Push a 2.
ri e# Read input and convert to integer N.
2* e# Multiply by 2.
m* e# Get all 2N-tuples consisting of 0 and 1 as potential sides. A tuple is a valid
e# side if a) all of its min/max pairs are sorted and b) not all of them are [0 1],
e# because that corresponds to the entire N-dimensional hypercube.
{ e# Filter the tuples...
2/ e# Split the tuple into min/max pairs.
__ e# Make two copies.
:$ e# Sort each pair in the second copy.
= e# Check for equality with the first copy.
\ e# Swap with the original list of pairs.
2,a- e# Remove all [0 1].
* e# Repeat this array 0 or 1 times depending on the first result. This effectively
e# computes the logical AND of two truthy/falsy values.
},
p e# Pretty-print the list of sides.
```
[Answer]
## ES7, 88 bytes
```
n=>[...Array(3**n-1)].map((_,i)=>[...(3**n+i).toString(3).slice(1)].map(x=>[x%2,+!!x]))
```
Turns out I ended up porting the Ruby solution, except I return a list of an array of a pair of bounds for each dimension, since that makes for the shortest code.
] |
[Question]
[
**Background**
[Benford's Law](https://en.wikipedia.org/wiki/Benford%27s_law) is freaky!
Of all the numbers in the world, roughly 30% of them start with a 1! 17.6% start with a 2, 12.5% start with a 3, and so on, and so on.
For example, take a look at the following graph. Take the largest 120000 towns in the world, take their altitude, and voila - they obey Benford's law. Divide these numbers by ~3 to convert them into meters, and amazingly, they still obey this law!
[](https://i.stack.imgur.com/fu7Mv.png)
In fact, it can be generalized past the first digit:
[](https://i.stack.imgur.com/ARb5z.png)
[Source](http://www.statisticalconsultants.co.nz/blog/benfords-law-and-accounting-fraud-detection.html)
---
**Challenge**
So I wondered, how does this apply to letters and words?
Your challenge is to parse the big list of words below and formulate the table above (printing a matrix will suffice). Unlike [this work](https://en.wikipedia.org/wiki/Letter_frequency#Relative_frequencies_of_the_first_letters_of_a_word_in_the_English_language), you will not only need to find the occurrence of the first letter, but also the second, third, fourth, and fifth. If a word does not have the nth digit, you can ignore that word (i.e. if you are compiling the 5th column (looking at the fifth digit), you should ignore all words less than 5 characters long)
Big List of Words: <https://raw.githubusercontent.com/kevina/wordlist/master/alt12dicts/2of4brif.txt>
Due to suggestion in the comments, **this contest is now a code golf competiton**, so shortest code in bytes wins. The entry must be a complete program and must output the table specified above. Built-ins are allowed.
Good luck!
[Answer]
# Mathematica 246 bytes
The probabilities are based on all the words in the file.
```
p=Prepend;t=Transpose;d="Digit";
p[t[p[N[#/Total@#,5]&/@ t[Sort[Cases[Tally[Position[Characters
@Import["t.txt","List"],#][[All,2]]],{n_,_} /;n<6]]/.{_,k_}->k&/@
(c=CharacterRange["a","z"])],c]],{d,"1st "<> d,"2nd "<>d,"3rd "<>d,"4th "<>d,"5th "<>d}]
//Grid
```
---
[](https://i.stack.imgur.com/rqIay.png)
---
[Answer]
# MATLAB, ~~113~~ 117 bytes
I made this a script that loads our text file, conveniently called *t.txt*, and prints the table without headers to the screen.
Old version (113 bytes) contained an error:
```
D=max(1,strvcat(importdata('t.txt'))-95);F=[];for n=1:5,F=[F,accumarray(D(:,n),1)/length(D)];end;disp(F(2:end,:))
```
New corrected version is slightly longer unfortunately.
```
D=max(1,strvcat(importdata('t.txt'))-95);F=[];for n=1:5,E=D(:,n);F=[F,accumarray(E,1)/sum(E~=1)];end;disp(F(2:end,:))
```
Giving the output:
```
0.0543 0.1367 0.0914 0.0626 0.0657
0.0578 0.0070 0.0229 0.0200 0.0181
0.0995 0.0177 0.0512 0.0466 0.0324
0.0652 0.0077 0.0325 0.0407 0.0294
0.0420 0.1499 0.0686 0.1169 0.1391
0.0452 0.0036 0.0194 0.0186 0.0122
0.0336 0.0028 0.0258 0.0301 0.0224
0.0358 0.0392 0.0086 0.0218 0.0304
0.0422 0.0976 0.0616 0.0802 0.1073
0.0086 0.0003 0.0030 0.0019 0.0003
0.0066 0.0033 0.0043 0.0260 0.0181
0.0306 0.0469 0.0570 0.0564 0.0658
0.0501 0.0183 0.0428 0.0331 0.0250
0.0170 0.0688 0.0807 0.0556 0.0543
0.0250 0.1417 0.0671 0.0592 0.0642
0.0822 0.0203 0.0415 0.0409 0.0258
0.0048 0.0032 0.0029 0.0024 0.0010
0.0567 0.0864 0.0942 0.0703 0.0789
0.1235 0.0091 0.0691 0.0586 0.0710
0.0510 0.0237 0.0669 0.0860 0.0711
0.0228 0.0768 0.0431 0.0360 0.0333
0.0142 0.0094 0.0179 0.0140 0.0072
0.0265 0.0070 0.0100 0.0096 0.0077
0.0002 0.0118 0.0047 0.0015 0.0013
0.0031 0.0105 0.0091 0.0067 0.0151
0.0015 0.0003 0.0038 0.0043 0.0029
```
[Answer]
# Python 3, ~~143~~ 129 bytes
~~This is taking a long time to run on the provided data. I have no idea if it will finish any time soon.~~
I think the interpreter I'm using is refusing to run the program because of the input size. My program did the first 1000 words in 1 second.
**Edit**: Now stops at 5 letters/columns.
```
s=input().split()
l=96
while l<122:l+=1;print([sum(i<len(w)and w[i]==chr(l)for w in s)/sum(i<len(w)for w in s)for i in range(5)])
```
With the letters on the left (136):
```
s=input().split()
l=96
while l<122:l+=1;print(chr(l),[sum(i<len(w)and w[i]==chr(l)for w in s)/sum(i<len(w)for w in s)for i in range(5)])
```
### Example Output
This is the output for input of `hello\nworld`:
```
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.5]
[0.0, 0.5, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.5, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.5, 1.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.5, 0.0, 0.0, 0.5]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.5, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.5, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
```
Output for the first 2000 words (not so nice to look at :/):
```
[1.0, 0.0015, 0.082164328657314628, 0.045523520485584217, 0.067875647668393782]
[0.0, 0.11899999999999999, 0.027555110220440882, 0.0096105209914011131, 0.017616580310880828]
[0.0, 0.1565, 0.096192384769539077, 0.015680323722812341, 0.046632124352331605]
[0.0, 0.14499999999999999, 0.03406813627254509, 0.019221041982802226, 0.042487046632124353]
[0.0, 0.019, 0.04458917835671343, 0.17653009610520992, 0.098963730569948186]
[0.0, 0.050000000000000003, 0.033066132264529056, 0.0030349013657056147, 0.0020725388601036268]
[0.0, 0.049000000000000002, 0.037575150300601205, 0.0096105209914011131, 0.03367875647668394]
[0.0, 0.0030000000000000001, 0.016533066132264528, 0.032372281234193223, 0.021243523316062177]
[0.0, 0.052499999999999998, 0.045591182364729456, 0.13606474456246839, 0.09689119170984456]
[0.0, 0.00050000000000000001, 0.025050100200400802, 0.0, 0.0]
[0.0, 0.00050000000000000001, 0.0075150300601202402, 0.00050581689428426911, 0.00051813471502590671]
[0.0, 0.123, 0.050601202404809621, 0.084977238239757211, 0.034715025906735753]
[0.0, 0.094, 0.036072144288577156, 0.027314112291350532, 0.030569948186528497]
[0.0, 0.1865, 0.03406813627254509, 0.030349013657056147, 0.080310880829015538]
[0.0, 0.0, 0.077655310621242479, 0.11987860394537178, 0.053886010362694303]
[0.0, 0.0, 0.027555110220440882, 0.018715225088517955, 0.013471502590673576]
[0.0, 0.0, 0.014529058116232466, 0.0015174506828528073, 0.0041450777202072537]
[0.0, 0.0, 0.095190380761523044, 0.076884167931208905, 0.11968911917098446]
[0.0, 0.0, 0.039579158316633264, 0.036418816388467376, 0.078238341968911912]
[0.0, 0.0, 0.10671342685370741, 0.039453717754172987, 0.077720207253886009]
[0.0, 0.0, 0.030561122244488977, 0.098128477491148211, 0.029015544041450778]
[0.0, 0.0, 0.033567134268537073, 0.0015174506828528073, 0.013989637305699482]
[0.0, 0.0, 0.00050100200400801599, 0.0075872534142640367, 0.0041450777202072537]
[0.0, 0.0, 0.0, 0.0, 0.0067357512953367879]
[0.0, 0.0, 0.002004008016032064, 0.0040465351542741529, 0.024352331606217616]
[0.0, 0.0, 0.0015030060120240481, 0.0050581689428426911, 0.0010362694300518134]
```
### Ungolfed
```
s=input().split()
m=[]
l=96
while l<122:
l+=1;r=[]
for i in range(max(map(len,s))): # Max length of words in list
L=sum(i<len(w)for w in s) # How many words of this length
f=sum(i<len(w)and w[i]==chr(l)for w in s) # Number of char in that pos
r+=[f/L]
m+=[r]
for r in m:print(r)
```
[Answer]
# bash with gawk 4 and sort, 125
Pretty much what awk was made for
```
awk '{for(;NF;c[NF--]++)a[$NF][NF]++}END{for(i in a){printf i;for(j=0;j++<5;)printf" %.9f",a[i][j]/c[j];print""}}' FS= wordlist.txt|sort
```
"wordlist.txt" needs to be replaced by the name of your file containing the list of words, and I counted the whole filename as one character, because it could be ;)
Be sure to leave the space between `FS=` and the filename.
It takes into account, that not all words have five letters. So for the average of the second to fifth position it divides only by the number of words with at least that much letters.
## awk part readable
```
{
for(;NF;c[NF--]++) # count number of words with at least that length
a[$NF][NF]++ # count occurences of character at that position
}
END{
for(i in a)
{
printf i;
for(j=0;j++<5;)
printf" %.5f",a[i][j]/c[j]; # print averages
print""
}
}
```
You can easily utilize the `sort` to gather some information. For instance the option `-rk2` sorts by the most common letter in the first position, `-rk3` sorts by the most common letter in the second position and so on.
## Output without sort options
```
a 0.054250087 0.136651928 0.091410860 0.062576399 0.065691522
b 0.057777336 0.007004819 0.022906584 0.020010382 0.018061682
c 0.099491612 0.017652806 0.051200027 0.046635074 0.032427344
d 0.065196151 0.007683773 0.032486906 0.040690567 0.029411252
e 0.041962674 0.149949492 0.068554001 0.116897470 0.139123764
f 0.045208406 0.003560369 0.019392694 0.018553559 0.012238707
g 0.033566827 0.002798616 0.025774050 0.030107671 0.022367893
h 0.035785848 0.039197178 0.008618975 0.021818852 0.030352691
i 0.042244192 0.097620349 0.061642246 0.080158743 0.107306613
j 0.008611125 0.000281518 0.003000066 0.001892195 0.000331247
k 0.006557703 0.003295411 0.004342637 0.025971634 0.018079116
l 0.030602613 0.046864391 0.056984685 0.056363971 0.065848428
m 0.050093563 0.018331760 0.042796526 0.033138532 0.025017870
n 0.017040091 0.068822760 0.080703441 0.055593697 0.054289649
o 0.024988822 0.141719244 0.067062256 0.059210636 0.064192193
p 0.082236243 0.020285823 0.041453955 0.040891509 0.025784968
q 0.004835478 0.003212612 0.002850892 0.002377803 0.001046043
r 0.056684386 0.086409327 0.094178877 0.070346121 0.078889102
s 0.123453723 0.009124480 0.069084400 0.058641303 0.070956607
t 0.051037475 0.023713713 0.066896506 0.085986035 0.071061211
u 0.022802921 0.076821170 0.043144600 0.036018688 0.033316480
v 0.014224916 0.009372878 0.017917523 0.013965405 0.007200265
w 0.026512329 0.006955139 0.009961546 0.009628426 0.007705853
x 0.000182158 0.011840297 0.004674136 0.001507058 0.001290120
y 0.003146373 0.010515508 0.009132799 0.006681291 0.015097892
z 0.001506947 0.000314637 0.003828814 0.004336978 0.002911487
```
## Output sorted after occurrence as first letter
```
s 0.123453723 0.009124480 0.069084400 0.058641303 0.070956607
c 0.099491612 0.017652806 0.051200027 0.046635074 0.032427344
p 0.082236243 0.020285823 0.041453955 0.040891509 0.025784968
d 0.065196151 0.007683773 0.032486906 0.040690567 0.029411252
b 0.057777336 0.007004819 0.022906584 0.020010382 0.018061682
r 0.056684386 0.086409327 0.094178877 0.070346121 0.078889102
a 0.054250087 0.136651928 0.091410860 0.062576399 0.065691522
t 0.051037475 0.023713713 0.066896506 0.085986035 0.071061211
m 0.050093563 0.018331760 0.042796526 0.033138532 0.025017870
f 0.045208406 0.003560369 0.019392694 0.018553559 0.012238707
i 0.042244192 0.097620349 0.061642246 0.080158743 0.107306613
e 0.041962674 0.149949492 0.068554001 0.116897470 0.139123764
h 0.035785848 0.039197178 0.008618975 0.021818852 0.030352691
g 0.033566827 0.002798616 0.025774050 0.030107671 0.022367893
l 0.030602613 0.046864391 0.056984685 0.056363971 0.065848428
w 0.026512329 0.006955139 0.009961546 0.009628426 0.007705853
o 0.024988822 0.141719244 0.067062256 0.059210636 0.064192193
u 0.022802921 0.076821170 0.043144600 0.036018688 0.033316480
n 0.017040091 0.068822760 0.080703441 0.055593697 0.054289649
v 0.014224916 0.009372878 0.017917523 0.013965405 0.007200265
j 0.008611125 0.000281518 0.003000066 0.001892195 0.000331247
k 0.006557703 0.003295411 0.004342637 0.025971634 0.018079116
q 0.004835478 0.003212612 0.002850892 0.002377803 0.001046043
y 0.003146373 0.010515508 0.009132799 0.006681291 0.015097892
z 0.001506947 0.000314637 0.003828814 0.004336978 0.002911487
x 0.000182158 0.011840297 0.004674136 0.001507058 0.001290120
```
## Second letter
```
e 0.041962674 0.149949492 0.068554001 0.116897470 0.139123764
o 0.024988822 0.141719244 0.067062256 0.059210636 0.064192193
a 0.054250087 0.136651928 0.091410860 0.062576399 0.065691522
i 0.042244192 0.097620349 0.061642246 0.080158743 0.107306613
r 0.056684386 0.086409327 0.094178877 0.070346121 0.078889102
```
## Third letter
```
r 0.056684386 0.086409327 0.094178877 0.070346121 0.078889102
a 0.054250087 0.136651928 0.091410860 0.062576399 0.065691522
n 0.017040091 0.068822760 0.080703441 0.055593697 0.054289649
s 0.123453723 0.009124480 0.069084400 0.058641303 0.070956607
e 0.041962674 0.149949492 0.068554001 0.116897470 0.139123764
```
## Fourth letter
```
e 0.041962674 0.149949492 0.068554001 0.116897470 0.139123764
t 0.051037475 0.023713713 0.066896506 0.085986035 0.071061211
i 0.042244192 0.097620349 0.061642246 0.080158743 0.107306613
r 0.056684386 0.086409327 0.094178877 0.070346121 0.078889102
a 0.054250087 0.136651928 0.091410860 0.062576399 0.065691522
```
## Fifth letter
```
e 0.041962674 0.149949492 0.068554001 0.116897470 0.139123764
i 0.042244192 0.097620349 0.061642246 0.080158743 0.107306613
r 0.056684386 0.086409327 0.094178877 0.070346121 0.078889102
t 0.051037475 0.023713713 0.066896506 0.085986035 0.071061211
s 0.123453723 0.009124480 0.069084400 0.058641303 0.070956607
```
So it looks like there is no Benfords Law of Words ;)
[Answer]
## R: 88, 95, or 126 bytes
```
z=sapply(readr::read_lines("http://tinyurl.com/pshoqyo"),Vectorize(substr),1:5,1:5)
y=apply(z,1,table,exclude="")
y/colSums(y)
```
That's **126 bytes** where that the data is downloaded from the provided URL (a tinyurl equivalent to be exact).
I can shorten the code to **88 bytes** if you allow to read the input from stdin:
```
z=sapply(scan(,""),Vectorize(substr),1:5,1:5)
y=apply(z,1,table,exclude="")
y/colSums(y)
```
or **95 bytes** if the data is provided via a `t.txt` file:
```
z=sapply(scan("t.txt",""),Vectorize(substr),1:5,1:5)
y=apply(z,1,table,exclude="")
y/colSums(y)
```
The output:
```
aah <NA> <NA> <NA> <NA>
a 0.054250087 0.1366519284 0.091410860 0.062576399 0.0656915218
b 0.057777336 0.0070112047 0.023141714 0.020833697 0.0171560104
c 0.099582311 0.0178502654 0.053853798 0.046119198 0.0308013314
d 0.065925417 0.0080894018 0.032457317 0.040240449 0.0279619439
e 0.044177897 0.1499494924 0.068491563 0.115709739 0.1336258142
f 0.045208406 0.0035603690 0.019392694 0.018553559 0.0122387071
g 0.033566827 0.0028011669 0.026038614 0.031346432 0.0212462947
h 0.035818471 0.0396356269 0.009065709 0.021577492 0.0288307086
i 0.042716723 0.1027737583 0.061586103 0.079272029 0.1020188291
j 0.009065709 0.0002815175 0.002997334 0.001872970 0.0003181567
k 0.006557703 0.0032954113 0.004342637 0.025971634 0.0180791157
l 0.030602613 0.0469071140 0.057569618 0.058683031 0.0625465746
m 0.050139230 0.0185368141 0.045014732 0.032771954 0.0237633928
n 0.017230697 0.0724559354 0.080629937 0.054978721 0.0516144003
o 0.026307990 0.1417192442 0.067001176 0.058609030 0.0616554195
p 0.082236243 0.0202858231 0.041453955 0.040891509 0.0257849684
q 0.004835478 0.0032155407 0.002880155 0.002475636 0.0009935913
r 0.056736060 0.0873758770 0.099060304 0.069567953 0.0749333466
s 0.124834642 0.0096061647 0.069021478 0.057992614 0.0674600544
t 0.053731760 0.0237137132 0.066835577 0.085112378 0.0682529848
u 0.022802921 0.0768211701 0.043144600 0.036018688 0.0333164804
v 0.014224916 0.0093814228 0.018101442 0.014540002 0.0068392204
w 0.026536498 0.0070329376 0.010477867 0.009521917 0.0073194562
x 0.000184196 0.0124653498 0.004669879 0.001490387 0.0012265464
y 0.003312471 0.0105155083 0.009124480 0.006613406 0.0145012475
z 0.001506947 0.0003146373 0.003828814 0.004336978 0.0029114873
```
[Answer]
# Dyalog APL (76)
```
⎕ML←3⋄L{R÷+⌿R←0 1↓K[⍋⊃K←,∘≢⌸⍺⌷¨⍵;]}¨(↓(L←⍳5)∘.≤≢¨G)/¨⊂G←W⊂⍨10≠W←83 ¯1⎕MAP'w'
```
This assumes the input is in a file called `w` in the working directory.
Output:
```
⎕ML←3⋄L{R÷+⌿R←0 1↓K[⍋⊃K←,∘≢⌸⍺⌷¨⍵;]}¨(↓(L←⍳5)∘.≤≢¨G)/¨⊂G←W⊂⍨10≠W←83 ¯1⎕MAP'w'
0.05425008694 0.1366519284 0.09141085991 0.06257639947 0.06569152182
0.05777733618 0.007004818918 0.02290658357 0.02001038196 0.01806168169
0.09949161243 0.01765280607 0.05120002652 0.04663507426 0.03242734357
0.06519615149 0.007683772997 0.03248690579 0.04069056749 0.02941125194
0.04196267409 0.1499494924 0.06855400119 0.1168974698 0.1391237644
0.04520840578 0.003560368954 0.01939269376 0.01855355917 0.01223870709
0.0335668273 0.002798615596 0.02577405026 0.03010767093 0.02236789344
0.03578584795 0.0391971782 0.008618975005 0.02181885162 0.03035269095
0.04224419163 0.09762034875 0.06164224624 0.08015874345 0.1073066127
0.008611124911 0.0002815175452 0.0030000663 0.001892195114 0.000331247058
0.006557702817 0.003295411264 0.004342637406 0.02597163382 0.01807911574
0.03060261315 0.04686439134 0.05698468474 0.05636397127 0.06584842832
0.05009356318 0.01833176015 0.04279652589 0.03313853213 0.02501786991
0.01704009141 0.06882275987 0.08070344096 0.05559369715 0.0542896494
0.0249888221 0.1417192442 0.06706225552 0.05921063648 0.06419219303
0.0822362429 0.02028582311 0.04145395478 0.04089150857 0.02578496836
0.004835477835 0.003212611986 0.002850891732 0.002377802709 0.001046043341
0.05668438571 0.08640932651 0.09417887688 0.070346121 0.07888910197
0.1234537235 0.009124480435 0.06908439966 0.05864130344 0.07095660664
0.05103747495 0.02371371322 0.066896506 0.0859860346 0.07106121097
0.02280292116 0.07682117012 0.04314459988 0.03601868752 0.03331648041
0.01422491596 0.009372878269 0.01791752304 0.01396540465 0.007200264998
0.02651232881 0.006955139351 0.009961546112 0.009628426464 0.007705852612
0.0001821584116 0.01184029675 0.004674136445 0.001507058055 0.001290120121
0.003146372564 0.0105155083 0.009132798515 0.006681290711 0.01509789222
0.001506946859 0.0003146372564 0.003828813896 0.004336978181 0.002911487299
```
Explanation:
* `⎕ML←3`: set migration level to 3. (Among other things, this changes the behaviour of `⊂` from 'split' into 'partition', so we don't have to get rid of the linefeeds.)
* `W←83 ¯1⎕MAP'w'`: read the file `w` as a string of ASCII values, store it in `W`.
* `G←W⊂⍨10≠W`: partition `W` on linefeeds (character 10) and store the words in `G`.
* `(↓(L←⍳5)∘.≤≢¨G)/¨⊂G`: store the numbers 1 to 5 in `L`, and for each number, select those words from G which have at least that many letters.
* `L{`...`}¨`: for each of the numbers 1 to 5, and the matching list of words,:
+ `⍺⌷¨⍵`: for each word, select the ⍺-th letter
+ `K←,∘≢⌸`: for each letter, find out how many times it occurs, store this in `K`.
+ `K[⍋⊃K`...`;]`: sort `K` by the value of the letter (so `a` is at the top, and `z` at the bottom).
+ `R←0 1↓`: drop the first column (the letter), leaving only the amount of times it occurred. Store this in R.
+ `R÷+⌿R`: divide the value for each letter by the total amount.
] |
[Question]
[
*We already have a challenge about multiplying [multiply single-variable polynomials](https://codegolf.stackexchange.com/questions/198779/computing-a-specific-coefficient-in-a-product-of-polynomials). This challenge is about multiply two polynomials with multiple variables*
Your task is given two multi-variable polynomials (for instance given as nested lists) to return their product.
## Examples
```
(x²+x+1)*(x²+x+1)=x⁴+2x³+3x²+2x+1
(x+y)*(x+y)=x²+2xy+y²
(x+y+z)*(x-y+z) = x²-y²+2xz +z²
a*a=a²
```
when representing polynomials as nested lists1:
```
[1,1,1], [1,1,1] -> [1, 2, 3, 2, 1]
[[0,1],[1]], [[0,1],[1]] -> [[0, 0, 1], [0, 2], [1]]
[[[0,1],[1]],[[1]]], [[[0,1],[-1]],[[1]]] -> [[[0, 0, 1], [0], [-1]], [[0, 2]], [[1]]]
[[],[[[[[[[[[1]]]]]]]]]], [[],[[[[[[[[[1]]]]]]]]]] -> [[], [], [[[[[[[[[1]]]]]]]]]]
```
[(non-golfed) solution in Python](https://tio.run/##tZHBboQgEIbvPsUcdcVE09smNOm9fQLCwazYHUMRkE27T@@CiGubbNNLLyO/888v86mv7jyqp3nuRA/t9IqTy3VxzACwB5xQTa5VJ5FrIn1raQBY4S5Wgc62I9M8Cwl6lNeXrvN28zgERrt/a/bRmm6XWLRJ2kRtKav54aP9yqVQ3kTCwxSx2YdgQAW2Ve8ir0n0rNF@mCGn2pfHbvPTvS4UBDG@xC8hDWYbxecZpQB8rqFVXRirGk5pnXKwos0em2XH5QaJYmk2dG8X6f6b3QqujNtWzd/Qhf7wC6wFVzl8A@YluW8VAQ58/VcJxg7EwczaovLeNMRYTRpOWMN9uZ@LYr4B)
## Rules
* You can Input/Output the polynomials in any convenient format (as long as each output can only represent one polynomial)
* Input and Output have to use the same format for polynomials
* You can assume that all coefficients are integers
* If you take input as lists you can assume that all numbers in both inputs appear in the nesting depth
* You are allowed to omit zero coefficients in the output (as long as the output value are unambiguous)
* You can use the empty list to represent zero/the zero polynomial
* If your language has a built-in for multi-variable polynomial multiplication consider adding a non-built-in solution as well
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution wins
---
1short explanation of the nested list format used in the examples (you are free to use a different IO format):
Each list represents a single variable polynomial with its coefficients begin either integers or other lists representing polynomials in one less variable. The coefficients are multiplied with the polynomial variable to the power of their index:
```
[[[0,1],[1]],[[1]]] -> "[[0,1],[1]]"*1+"[[1]]"*z -> ("[0,1]"*1+"[1]"*y)*1+"[1]"*1*z -> (x*1+1*y)*1+1*1*z -> x+y+z
```
The variables are assigned by nesting layer. I use `x` for the innermost variable `y` for the next level, then `z`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 80 bytes
```
f=(x,y,s=[])=>x>f&&x.map((p,i)=>y.map(q=>f(p,q,s[i++]||=[])||(s[i-1]-=-p*q)))&&s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWNwPSbDUqdCp1im2jYzVt7Srs0tTUKvRyEws0NAp0MoEilWBOoa1dGlCgUKc4OlNbO7amBqS8pkYDyNU1jNW11S3QKtTU1FRTK4aaq2nNlZyfV5yfk6qXk5-ukaYRHW2gYxirE20YCyQQbE1NiAaYgwA)
# [JavaScript (Node.js)](https://nodejs.org), 84 bytes
```
f=(x,y,s=[])=>x>f&&x.map((p,i)=>y.map(q=>f(p,q,s[i]=s[i++]||[])||(s[i-1]-=-p*q)))&&s
```
[Try it online!](https://tio.run/##RYtBCsMgEEX3PYjMNBrquowXEReSxmJJo9ZSDHh3O3TTzeO/B//hP74ur5jfak@3dYxA0OQhK1mHZJoJQrT56TNAlpHL8ZNCJnAostroiDFNrne@9A5sSjtFKp8LIgpRx/W0pL2mbZ23dIcA1l6kdtJqx/hvxPEF "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~115~~ 112 bytes
```
FEθ⟦⟦ι⟧⟧«W⁺⟦⟧§§ι⁰±¹≔ΣEιE⊟λ⁺λ⟦ξν⟧ι⊞υι»≔⟦⟧θF⊟υ«≔⊟ιηF⌊υ«≔Eι⁺λ§κμζ≔⊟ζε≔θδFζ≔§⎇⁼λLδ⊞Oδ⟦⟧δλδF⁼εLδ⊞δ⁰§≔δε⁺§δε×↨κ⁰η»»⭆¹θ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZK_TsMwEMYlFtQ-hdXJllwp2ZA6tRIDEn8itVvkwTRuYuE4bZxAKeqTsHQAwSvB03DnOBA8-OQvd7_v7pTXz3Uh63Ulzen03jab6cX32fmmqgm9kVu64yRNtRCMkZfx6KnQRhGamNbRVHAyb65spva0j5qTiHFyq3LZKBozOGTunM4tXbalB0IKhqTaUgOpHmXAZM-JFVjAiWaz8ShpXUHb7nEcBwh67kDw7SGi7foKn1HRACgQ0I2grS7BOeT1iaGR3rxv_4GT0ndwQMCQegBRDUXYS-bf3ubwO2aPWqnayvqZXu5aabzJtbJ5U9AM-Tjc3VbVsqlqmsH0giGPE8P-cUO1GlYzX41V0aCh3hdkFQYbSoBd6VI5upBO4ZyRXxNDwhH2m9TaNnTZQMhxOTHumc3e3P3ahb_iI51MH81EfPEUT8RjwdNYwIU3hqBN_0Qhutof) Link is to verbose version of code. Explanation: Charcoal doesn't really like multidimensional indexing. I should really find time to test this out on my multidimensional indexing branch to see whether it offers a significant saving.
```
FEθ⟦⟦ι⟧⟧«
```
Double wrap each input polynomial and then loop over them.
```
W⁺⟦⟧§§ι⁰±¹≔ΣEιE⊟λ⁺λ⟦ξν⟧ι
```
Replace each polynomial with a list of its elements and their multidimensional indices.
```
⊞υι
```
Save the resulting list.
```
»≔⟦⟧θ
```
Start building up the output list.
```
F⊟υ«
```
Loop over the second polynomial's multidimensional index list.
```
≔⊟ιη
```
Remove the coefficient from the multidimensional index.
```
F⌊υ«
```
Loop over the first polynomial's multidimensional index list.
```
≔Eι⁺λ§κμζ
```
Get the multidimensional index of the product of the two terms.
```
≔⊟ζε
```
Remove the innermost index.
```
≔θδ
```
Start traversing the dimensions of the output list.
```
Fζ
```
Loop over the earlier multidimensional indices.
```
≔§⎇⁼λLδ⊞Oδ⟦⟧δλδ
```
Get the inner list at the current multidimensional index, extending the current list if necessary.
```
F⁼εLδ⊞δ⁰
```
Extend the innermost list if necessary.
```
§≔δε⁺§δε×↨κ⁰η
```
Add on the resulting coefficient to the element at the innermost index.
```
»»⭆¹θ
```
Pretty-print the resulting list.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 60 55 bytes
```
{(.p),','!p:+/'(*p)@=*|p:(*/;+/)@''++',/,/:\:/,''(x;y)}
```
[Try it online!](https://ngn.codeberg.page/k#eJxlTNsKgkAQffcrFIOZ2Z1cfd0h2P9QKQiEIMyn0DX99jat6DIDw5xrY0fMOmJgSDqrDaDqyO3UrbOojGhDDkBrYMPGVtYwAPYy0BRFx/Zqx015OM3OC2OvfOBlTr0gCRvES9nXDoYQTFIfejzVU1lIktchfG4tzsoC7RcQN1lchUbAIg4ry6VvBfMgcEHyen71t4EX1wq3T/xnftDrLOZPSNEd7tlB+Q==)
-5 : Save a lambda
Here multinomials are represented by lists of terms where each term is a pair of coefficients and list of powers of each variable in reverse order.
Thus,
```
(x-y+z) -> [[[1,[0,0,1]],[-1,[0,1,0]],[1,[0,0,1]]]
```
or in K notation:
```
((1;0 0 1)
(-1;0 1 0)
(1;1 0 0))
```
Cleaning up terms with zero coefficients is left to an auxiliary function.
[Answer]
# Python3, 490 bytes:
```
def U(p,l=1,o=1):
if type(p)!=list or[]==p:yield(p if p!=[]else 0,o);return
for i,a in enumerate(p):yield from U(a,l+1,{l:i}if o==1 else{**o,l:o.get(l,0)+i})
def G(p,l=1):
r={}
for c,D in p:
if l in D:r[V]=r.get(V:=D.pop(l),[])+[(c,D)]
return[G(r[i],l+1)if i in r else 0 for i in range(max(r)+1)]if r else c
def M(a,b):
r={}
for c,p in U(a):
for C,P in U(b):r[K]=r.get(K:=str({**p,**{A:p.get(A,0)+B for A,B in P.items()}}),0)+c*C
return G([(b,eval(a))for a,b in r.items() if b])
```
[Try it online!](https://tio.run/##bVBNa8IwGL77K7Jb3pqJZZfRkYMf4EEEL/MScqgaXSA2IY1jUvrbXd60zjnWQmmej/d9nrhL@LDVy6vz1@teHcg7dczwnFmeQzEg@kDCxSnq4IkbXQdivZCcu@KildlThwL3xIVUplZkzCy8eRXOvhqQg/VEs5LoiqjqfFK@DDinc5KDt6e4rGRmmLPGFLqNkyznOcFJTZZZZgo7OqpADRvDULcwwHyLLh9m87xpuzU7Nsc1LoIYyOBhXnixkdynEZuCz0fOOmqACQlDQaMFZJyRwooF9UJLzALRr9HvSVep65GQsjoqeiq/qIcolFHZi3Yp2iq22f4N5tAZeyKeoBlbd1CUerG8JVwWvA6exuKOZVkzKVyCJ9h9mowTNkXjeqSDOtUU2haQ3GWzW414OYJumfosTVwIaIqJUvSbCa9nK@HqvK4CXVGRs/hKRvofgMEPJcbIiFwifT88SH5pBH6TtAef7@iDB8H@Qa5/0Pg/A3D9Bg)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 12 bytes
```
Expand[1##]&
```
[Try it online.](https://tio.run/##y00syUjNTSzJTE78n2b737WiIDEvJdpQWTlW7X9AUWZeSXRatEJFnJF2hbahgg6cFRvLhZDVrgTJAEk0Ue0qkLguiEaWSQSKJoJE/gMA "Wolfram Language (Mathematica) – Try It Online") The inevitable built-in. `1##` multiplies together all arguments to a function, regardless of the types of those objects. (So this function works for more than two polynomials as well.)
] |
[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/230885/edit).
Closed 2 years ago.
[Improve this question](/posts/230885/edit)
Given a boolean function with inputs, check if it's possible to only use [IMPLY gate](https://en.wikipedia.org/wiki/IMPLY_gate) to express it.
There's no extra limitation on how you use this gate, and you can use each input for any amount of times. See examples below:
\$\begin{matrix}
\text{Expression}&&&&&\text{Solution}&\text{Your output}\\
a&0&0&1&1&a&\text{true}\\
b&0&1&0&1&b&\text{true}\\
a\vee b&0&1&1&1&\left(a\rightarrow b\right)\rightarrow b&\text{true}\\
\neg a&1&1&0&0&-&\text{false}\\
a\wedge b&0&0&0&1&-&\text{false}\\
1&1&1&1&1&a\rightarrow a&\text{true}
\end{matrix}\$
>
> This actually checks if there is one input that make the output of function true as long as it's true. Proof is left as an exercise.
>
>
>
Input can be taken as a function, a boolean array of length \$2^n\$, or any convenient format. Shortest code wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
oJ’|/‘nL
```
[Try it online!](https://tio.run/##y0rNyan8/z/f61HDzBr9Rw0z8nz@H27XjPz/P9pAx0DHUMcwVicaRBvAWRAxQ7CYAVjMACprCJeF6tAxhOoEAA "Jelly – Try It Online")
*-1 because it came to me in a dream... to use `>`, which would not have worked at all, but it still got me thinking*
Same input format as hyper-neutrino's solution and also uses OP's spoiler.
```
oJ Replace each 0 in the input with its index in the input,
‘ then decrement each.
oJ‘ We now have every bitmask which yields false, and some extra zeroes.
|/ Reduce by bitwise OR.
‘ Incremented,
nL is it not equal to the length?
```
>
> The bitwise OR of the false bitmasks is 1 less than the length (the length being a power of 2) iff each input variable can produce false while being true.
>
>
>
A rough proof of the spoiler:
>
> **It is necessary for the function to be implied by a variable:**
>
>
> An expression composed of just implications is either a variable or the implication of two such expressions. In butchered BNF:
> $$\text{<E>} \text{ ::= } \text{<Var>} \text{ | } \text{<E>} \rightarrow \text{<E>}$$
> Clearly, any expression consisting of a lone variable is true precisely when that variable is true.
>
>
> An implication \$a \rightarrow b\$, furthermore, is true at least when \$b\$ is true, for any expression \$b\$. If \$b\$ satisfies the property that some variable implies it, so does \$a \rightarrow b\$. Therefore this is true of any implication of variables, any implication of implications of variables, and so on.
>
>
>
> **It is sufficient for the function to be implied by a variable:**
>
>
> There is no function satisfying the condition which cannot be expressed only in implicatures.
> Let's call the variable which implies the function \$a\$. If we look only at the cases in which \$¬a\$, \$¬b\$ can be written \$b \rightarrow a\$. From there, considering that
> $$x \vee y \iff (x \rightarrow y) \rightarrow y$$
> we have
> $$x \wedge y \iff ¬(¬x \vee ¬y) \iff (((x \rightarrow a) \rightarrow (y \rightarrow a)) \rightarrow (y \rightarrow a)) \rightarrow a$$
> hence any function can be expressed in nothing but implicatures presupposing a known false variable, and such an expression without the presupposition is the disjunction of any function and an additional variable.
>
>
>
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
;2/ƬḊm2ȦƊ€Ẹ
```
[Try it online!](https://tio.run/##y0rNyan8/9/aSP/Ymoc7unKNTiw71vWoac3DXTv@//9voGOoA8KGEBoA "Jelly – Try It Online")
-2 bytes thanks to Unrelated String
Still looking to shorten this with a more intelligent way of applying OP's spoiler. Accepts input as a length \$2^n\$ list in the order of `[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]` (standard bit mask enumeration). Working on a proof first though.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
⊙↨⊖Lθ²⌊Φθ&μX²κ
```
[Try it online!](https://tio.run/##TYixCoMwEEB/5cYLXKG6dlJKpxbcxSHEox5NToxppV9/Fac@3ltemHwOs49mXRYt2OgXW78yXjlkTqyFR7yzPsuEi3ME9d5DVNI74U1i4YwLQStlk5UbHTERdPO275rg5Q4uZn1fEZwPq3@HwU6f@AM "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a binary array of length 2ⁿ and outputs a Charcoal boolean, i.e. `-` for implied, nothing if not. Explanation:
```
θ Input array
L Length
⊖ Decremented
↨ ² Convert to base 2
⊙ Does any bit satisfy
θ Input array
Φ Filtered where
μ Inner index
& Bitwise And
X² 2 raised to power
κ Outer index
⌊ Does not contain zero
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Port of [Unrelated String's solution](https://codegolf.stackexchange.com/a/230887/58974) 'cause I genuinely don't have the first clue what the challenge is asking us to do.
```
ÊɦUËÉ©EÃr|
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ysmmVcvJqUXDcnw&input=WzAsMCwxLDFd) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ysmmVcvJqUXDcnw&input=W1swLDAsMSwxXSxbMCwxLDAsMV0sWzAsMSwxLDFdLFsxLDEsMCwwXSxbMCwwLDAsMV0sWzEsMSwxLDFdLFswLDEsMCwxLDEsMSwwLDFdXQotbQ)
```
ÊɦUËÉ©EÃr| :Implicit input of array U
Ê :Length
É :Subtract 1
¦ :Not equal to
UË :Map each element in U at 0-based index E
É : Subtract 1
©E : Logical AND with E
à :End map
r| :Reduce by bitwise OR
```
] |
[Question]
[
Given 4096 16-bit integers, only four of which are unique and others appeared twice (so 2050 different integers exist). Find the four uniques.
To time precisely and limit RAM usage, your program will be run on a 12MHz 8051(with 128B RAM). I'll test with [a random case](https://paste.ubuntu.com/p/RbhCJqynvF/) generated by [some code](https://paste.ubuntu.com/p/dZ2vtZ4bbM/) to test, but we aim at the worst case, so anyone can provide other test cases.
You can answer in C or ASM, but C will likely give some extra disadvantage. The input array is placed on ROM 0xE000-0xFFFF, and output is placed on extra write-only RAM 0x00-0x07. When you finish outputting, clear P3.5.
A C code that solves the problem with bad score, to better understand the I/O way:
```
#include <reg51.h>
sbit P3_5 = P3^5;
unsigned int code input[4096] _at_ 0xE000;
unsigned int pdata output[4] _at_ 0x00;
void main() {
unsigned long i;
unsigned int j;
unsigned char cnt, wr = 0;
for (i=0; i<65536L; ++i) {
cnt = 0;
for (j=0; j<4096; ++j) {
if (input[j] == i) ++cnt;
}
if (cnt==1) { // Order doesn't matter
output[wr++] = i;
}
}
P3_5 = 0;
while (1);
}
```
According to test this runs for 04:19:36.997507. Also see [the example ASM solution that solve in several seconds](https://codegolf.stackexchange.com/a/223432/).
---
For extreme push, I'll run the simulation on Proteus with such circuit:
[](https://i.stack.imgur.com/Fnpw5.png)
and check the time when `DBT1` is actived.
* You can use all ROM in 0000-DFFF.
* You can assume RAM is initialized to 0.
* You can use SFRs, including pins, as RAM
* You don't need to `jmp $` after clearing `P3.5`
* You can write trash into outer RAM 08-FF, they'll be ignored
[Answer]
# C, 0.480298s
## Codes
```
#ifndef LOCAL_DEBUG
#include <reg51.h>
sbit P3_5 = P3 ^ 5;
unsigned int code input[4096] _at_ 0xE000;
unsigned int pdata output[4] _at_ 0x00;
#else
#include <stdio.h>
#define int short
#define UNIQ1 17
#define UNIQ2 273
#define UNIQ3 1298
#define UNIQ4 1554
unsigned int input[4096] = {
UNIQ1,
UNIQ2,
UNIQ3,
UNIQ4
};
unsigned int output[4];
#endif
#define INPUT_SIZE 4096
#define BUCKET_BITS 4
#define BUCKET_SIZE (1 << (BUCKET_BITS))
#define BUCKET_MASK ((BUCKET_SIZE) - 1)
unsigned int buckets[BUCKET_SIZE];
#define buckets_value(n) (buckets[n] & ~(bucket_mask)) | ((n) << bit_offset)
void main() {
unsigned int output_offset = 0;
unsigned int i, j, k, l;
unsigned int search_bucket = 0, search_bucket_2 = 0, bit_offset = 0, bit_offset_2, bucket_mask;
unsigned int target_mask, target_value;
do {
bucket_mask = BUCKET_MASK << bit_offset;
for (i = 0; i < BUCKET_SIZE; ++i) {
buckets[i] = 0;
}
for (i = 0; i < INPUT_SIZE; ++i) {
buckets[(input[i] >> bit_offset) & BUCKET_MASK] ^= input[i] | bucket_mask;
}
for (i = j = 0; i < BUCKET_SIZE; ++i) {
if (buckets[i] != 0) ++j;
}
if (j <= 1) {
bit_offset += BUCKET_BITS;
}
} while (j <= 1);
if (j == 4) {
for (i = 0; i < BUCKET_SIZE; ++i) {
if (buckets[i] == 0) continue;
output[output_offset++] = buckets_value(i);
}
} else if (j == 3) {
for (i = 0; i < BUCKET_SIZE; ++i) {
if (buckets[i] == 0) continue;
if (buckets[i] & (BUCKET_MASK << bit_offset)) {
output[output_offset++] = buckets_value(i);
} else {
search_bucket = i << bit_offset;
}
}
} else if (j == 2) {
for (i = k = 0; i < BUCKET_SIZE; ++i) {
if (buckets[i] == 0) continue;
if (buckets[i] & (BUCKET_MASK << bit_offset)) {
l = buckets_value(i);
if (k == 0) {
for (j = 0; j < INPUT_SIZE; ++j) {
if (input[j] == l) ++k;
}
if (k == 1) {
output[output_offset++] = l;
} else {
search_bucket = i << bit_offset;
k = 2;
}
} else if (k == 1) {
search_bucket = i;
} else {
output[output_offset++] = l;
}
} else {
if (search_bucket) {
search_bucket_2 = i << bit_offset;
} else {
search_bucket = i << bit_offset;
}
}
}
}
bit_offset_2 = bit_offset;
target_mask = BUCKET_MASK << bit_offset;
target_value = search_bucket;
while (output_offset < 4) {
bit_offset += BUCKET_BITS;
bucket_mask = BUCKET_MASK << bit_offset;
for (i = 0; i < BUCKET_SIZE; ++i) {
buckets[i] = 0;
}
for (i = 0; i < INPUT_SIZE; ++i) {
if ((input[i] & target_mask) != target_value) continue;
buckets[(input[i] >> bit_offset) & BUCKET_MASK] ^= input[i] | bucket_mask;
}
for (i = j = 0; i < BUCKET_SIZE; ++i) {
if (buckets[i] != 0) ++j;
}
if (j == 1) {
continue;
}
for (i = 0; i < BUCKET_SIZE; ++i) {
if (buckets[i] == 0) continue;
if ((buckets[i] >> bit_offset) & BUCKET_MASK) {
output[output_offset++] = buckets_value(i);
--j;
} else {
target_mask |= bucket_mask;
target_value |= i << bit_offset;
}
}
if (j == 0) {
bit_offset = bit_offset_2;
target_mask = BUCKET_MASK << bit_offset;
target_value = search_bucket_2;
}
}
#ifndef LOCAL_DEBUG
P3_5 = 0;
while (1);
#else
for (i = 0; i < 4; i++) {
printf("%d\n", output[i]);
}
#endif
}
```
[Try it online!](https://tio.run/##1Vdbb5swGH3nV3xrtAoEmQIh66qESm0XVVG7rlObl3UpolwSEwpVIN2khf31zOZqA0lTTdU2Xizs4@Pz3fyB2Z6a5rpl2Q7ybbj4fHp8oX8cnozP1i3k@HianuNayDe9pWXDYGFPe/K72REX3qMIrrp6DzQ8wB30@tzSD9HUty1AfgRmgPHIf1xGt2rn8P0EdCPSofNj2Ol0KtBHy4gMCJZRAi6QBNeyvdDmKAFhZKGACMi1E4JwFiwirpgaX46@yCAfMBMKKAddZqYLsnL4gZlSQe71VI6VRxuhwU8uoZeSQUmHbjqoXFyxrLCpj9XZvoWcUuXo8mp8o1@Pvg6BcBfzJ@PT8@GNfjK6uQa1OpvAeRkGA@ApoCBUgZ@Or8@B56ltArRBFiq23S/NuR2FtxQu0ZqRZcv6k@Etbd4XgM83@BPYh1/Zq/5ghHNBgBU@EYOwOJwdeuA4oR3hE58CZMGDgXxewO4DaHBRBsb@xUGvIJAErgRzCbzaUmgbC3OmpyrIZomd0pV0spRTfdcVCSgjaidExmKarUn5S@INgrSCxB6gGfABdAgYX/QTsBMsgEeJqYBgQIe2D6KIhIwUiuigSe4YgLiRo0ymDRR8msWY6eiIjg6OIiV3AncaFMhV1TO1091drEBOmTaY9Q3eImCESzMSjAsDDWdoKb0MmqjRZVFujOH7DHl2sZespFSaBmpOtbvDK1K1RKoZ@BHy04iTJytqJnFFkYSILRck0ELJRVZq676Stgpov7gl6skolNQvt6mwqKSo1iJqyv083k0@UWo@mf91v3hbPJCyzrMTyz2ZAVltuLXqdFlwSpMWnZvo90h5zPsUJuZYdHKoXOXZHESPIatG7gXRSx8SF6VZHxXUJpG1Y/rcFlk7GRRvSkiigTlvi5SkUWy0uUHazv6K63nPAdOASIoxG6me81w3oTsSxjKqyHp2PbJNdlBejc/csf9uXyPBLXvaPu0zgbQY2jH16@C/6opsFbGmxK/VRGjUNt/8WRMBaLfdjR2FroOVVnc7hUkLYLVD16G82mn81tCY4swJXlCTNVla9a6hvgu4pv8tyP@sOlQNk6@b9HeoHnAVD6KYm/O4wF@uDr/31vrm70l5WNAkcXuc/4jE6/Vv "C (gcc) – Try It Online")
I'm not sure about its correctness. Please comment if you find out some failed testcases. I will try my best to fix it.
---
## Algorithm
Algorithm here only works when input array contains 4 unique values. It will fail if input array contains more than 4 values.
Consider xor of some numbers where most numbers occurred 2 times, and some occurred once. It is easy to prove: The xor result is zero if and only if we have at least 3 unique numbers here. Also, we try to count how many numbers at all. It is trivial to know: If the count is even / odd, then we have even / odd number of unique numbers here.
As there are only 4 unique numbers according to the description of this question. If both xor result is zero and count result is even, there should be 0 or 4 unique numbers.
By using this idea, we need to split numbers into some buckets while keep equals number in same buckets. You can do it by `(input[i] >> n) & m`. So we first split all values `input[i]` into 16 buckets based on `(input[i] >> 0) & 15`. We use `input[i] | bucket_mask` to mask out the bits for bucket name. We set them to 1s, so they are used to know count number in that buckets is odd or even.
```
for (i = 0; i < INPUT_SIZE; ++i) {
buckets[(input[i] >> bit_offset) & BUCKET_MASK] ^= input[i] | bucket_mask;
}
```
We use above code. And after calculate these `buckets`:
* If `buckets[i] & bucket_mask` is non-zero: we know the bucket i contains 1 or 3 unique numbers (number count is odd).
* If `buckets[i] & bucket_mask` is zero, but `buckets[i]` is non-zero: we know the bucket i contains 2 unique numbers.
* If `buckets[i]` is zero, and some other bucket `bucket[j]` is non-zero: we know the bucket i contains no unique numbers.
* If all `buckets` are zero: 4 unique numbers are located in the same bucket. We need to try another 4 bits as mask and run the loop again.
After we know where the number is in some bucket:
* If the bucket contains only 1 unique numbers: the unique number is `(buckets[i] & ~(bucket_mask)) | ((i) << bit_offset)`;
* If the bucket contains more than 1 unique numbers: We loop again on numbers in this bucket, and split them into different buckets based on other bits;
---
## Analysis
Time complexity is \$O\left(size \cdot bit / buckets + 2^{buckets} \right)\$. \$size\$ is how many numbers the input contains. \$bit\$ is how many bits each input contains. \$bucket\$ is how many bits for bucket id (4 in above codes).
Extra storage complexity is \$O\left(2^{buckets}\right)\$.
[Answer]
# 5.003017s
```
PAG equ R7
APAG equ 7
WRPTR equ R0
org 0
; mov PAG, a ; using that RAM is cleared
; mov WRPTR, a
mainloop:
mov dptr, #0E000h
; clr 64-127
clr a
_ptr set 64
rept 64
mov _ptr, a
_ptr set _ptr+1
endm
scan:
rept 128
local exit
clr a
movc a, @a+dptr
inc dpl
add a, PAG
add a, acc
jnz exit
clr a
movc a, @a+dptr
mov b, a
orl b, #0D8h
clr b.5
mov b.2, c ; 11011caa
anl a, #0FCh
mov 9, #exit/256
mov 8, #exit mod 256
mov 11, b
mov 10, a
mov sp, #11
ret
exit: ;inc dptr
inc dpl
endm
inc dph
mov a, dph
jz not_scan
jmp scan
not_scan:
_ptr set 0
xrl APAG, #0FFh
inc PAG
rept 64
local j7, j6, j5, j4, j3, j2, j1, j0
mov b, _ptr/8+64
jnb b.7, j7
mov a, PAG
movx @WRPTR, a
inc WRPTR
mov a, #_ptr mod 256+7
movx @WRPTR, a
inc WRPTR
j7: jnb b.6, j6
mov a, PAG
movx @WRPTR, a
inc WRPTR
mov a, #_ptr mod 256+6
movx @WRPTR, a
inc WRPTR
j6: jnb b.5, j5
mov a, PAG
movx @WRPTR, a
inc WRPTR
mov a, #_ptr mod 256+5
movx @WRPTR, a
inc WRPTR
j5: jnb b.4, j4
mov a, PAG
movx @WRPTR, a
inc WRPTR
mov a, #_ptr mod 256+4
movx @WRPTR, a
inc WRPTR
j4: jnb b.3, j3
mov a, PAG
movx @WRPTR, a
inc WRPTR
mov a, #_ptr mod 256+3
movx @WRPTR, a
inc WRPTR
j3: jnb b.2, j2
mov a, PAG
movx @WRPTR, a
inc WRPTR
mov a, #_ptr mod 256+2
movx @WRPTR, a
inc WRPTR
j2: jnb b.1, j1
mov a, PAG
movx @WRPTR, a
inc WRPTR
mov a, #_ptr mod 256+1
movx @WRPTR, a
inc WRPTR
j1: jnb b.0, j0
mov a, PAG
movx @WRPTR, a
inc WRPTR
mov a, #_ptr mod 256+0
movx @WRPTR, a
inc WRPTR
j0:
_ptr set _ptr + 8
if (_ptr = 256)
orl APAG, #080h
endif
endm
inc PAG
cjne PAG, #0, mainloopJ
clr P3.5
jmp $
mainloopJ:
xrl APAG, #07Fh
inc PAG
jmp mainloop
org 0D800h
rept 512
_oa set (03FCh and $) mod 255 + ($>=0DC00h)*256
xrl 64+_oa/8, #1 shl (_oa mod 8)
ret
endm
```
I know SFRs are enough to make 1024 tested numbers in a scan, but as this is an example solution, and I expect some much faster solutions than bit[N]&scan
[Answer]
# C, 87s
I don't have the means to test or even compile for the environment, so there are likely issues and further optimisations. I've no idea if the code (and stack?) will fit in 128B.
There are a couple of optimisations over the naïve C example:
* 4096x4096 iterations instead of 65536x4096 iterations.
* XOR trick - XOR all the input values together. Then once we've found 3 out of 4 non-duplicate values, these may be XORed against the xor accumulator one more time to cancel them out and leave the 4th non-duplicate value remaining.
There are likely better algorithms than this, but it's a start.
Hand-written assembly will certainly beat this, but for now, I don't know 8051 assembly at all, so I'll have to settle for C.
I am assuming in this architecture, `sizeof(int) == 2` and `sizeof(long) == 4`.
```
#include <reg51.h>
sbit P3_5 = P3^5;
unsigned int code input[4096] _at_ 0xE000;
unsigned int pdata output[4] _at_ 0x00;
void main() {
unsigned int i, j;
unsigned char dupfound, wr = 0;
unsigned int xor_acum = 0;
unsigned int v;
unsigned int output_stage[3];
for (i=0; i<4096; ++i) {
v = input[i];
xor_acum ^= v;
if (wr < 3) {
dupfound = 0;
for (j=0; j<4096; ++j) {
if (i != j && v == input[j]) {
dupfound = 1;
break;
}
}
if (!dupfound) {
output_stage[wr++] = v;
}
}
}
output[0] = output_stage[0];
xor_acum ^= output_stage[0];
output[1] = output_stage[1];
xor_acum ^= output_stage[1];
output[2] = output_stage[2];
xor_acum ^= output_stage[2];
output[3] = xor_acum;
P3_5 = 0;
while (1);
}
```
] |
[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/193071/edit).
Closed 4 years ago.
[Improve this question](/posts/193071/edit)
This is my first question in `Code golf` I found it in stack-overflow (originally in JavaScript however all languages are acceptable):
*Render on screen NxN (where N in range 1-16) grid where each cell have black boundary and red number inside - cells are numerated in hex starting from left-upper corner to bottom-right. Example output (for N=16) shows how result should looks like (font can be different than in picture):*
[](https://i.stack.imgur.com/nZn8m.png)
The image in text uri form (which works on major browsers) in output is also acceptable - a as example blow:
```
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAO0AAADpCAYAAADI3LCZAAABfGlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGAqSSwoyGFhYGDIzSspCnJ3UoiIjFJgv8PAzcDDIMRgxSCemFxc4BgQ4MOAE3y7xsAIoi/rgsxK8/x506a1fP4WNq+ZclYlOrj1gQF3SmpxMgMDIweQnZxSnJwLZOcA2TrJBUUlQPYMIFu3vKQAxD4BZIsUAR0IZN8BsdMh7A8gdhKYzcQCVhMS5AxkSwDZAkkQtgaInQ5hW4DYyRmJKUC2B8guiBvAgNPDRcHcwFLXkYC7SQa5OaUwO0ChxZOaFxoMcgcQyzB4MLgwKDCYMxgwWDLoMjiWpFaUgBQ65xdUFmWmZ5QoOAJDNlXBOT+3oLQktUhHwTMvWU9HwcjA0ACkDhRnEKM/B4FNZxQ7jxDLX8jAYKnMwMDcgxBLmsbAsH0PA4PEKYSYyjwGBn5rBoZt5woSixLhDmf8xkKIX5xmbARh8zgxMLDe+///sxoDA/skBoa/E////73o//+/i4H2A+PsQA4AJHdp4IxrEg8AAAGdaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcH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WM63saYse2lfPdvF9uQYD1gTZ9mjnT3GGyZNHF+kdmGHsaLmlcShnivtkzaHFPXSmJSFiilKXSmbyqJS6kpZqJii1JWyqSwqpa6UhYopSl0pm8qiUupKWaiYotSVsqksKqWulIWKKUpdKZvKolLqSlmomKLUlbKpLCqlrpSFiilKXSmbyqJS6kpZqJhiqW7DTUY8Y5h7b6nE+Cilw9le6/zy+vSLfdRhXrJqzn3Z1Xce6Dzwf88D7U+P/++1uWtR54HXtQe6Sfu67v7u4F+LHugm7Wux17o2v6490E3a13X3dwf/WvRAN2lfi73Wtfl17YFu0r6uu787+NeiB/4/1jR8lZoC7I8AAAAASUVORK5CYII="/>
```
This is my (not optimised) attempt to this task
```
document.write('<style>.row { display: flex; font-size: 9.5px; text-align: center; color: red } .cell { width: 10px; height: 10px; margin: 1px; border: 1px solid black;}</style><div id="container"></div>')
let n=10, s='';
for(let i=0; i<n; i++) {
s+= '<div class="row">'
for(let j=0; j<n; j++) s+= `<div class="cell"> ${(i*n+j).toString(16)} </div>`;
s+= '</div>'
}
container.innerHTML = s;
```
but I wonder how small code can produce similar effect?
[Answer]
Could go smaller, but here's a quick one:
```
let n=10;container.innerHTML=(d='<div class="')+'grd" style="width:'+n*14+'px">'+[...Array(n*n)].reduce((a,b,i)=>a+d+'cell">'+i.toString(16)+(e='</div>'),'')+e;
```
```
.grd { display: inline-block; font-size: 9.5px; text-align: center; color: red;}
.cell { display:inline-block; width: 10px; height: 10px; margin: 1px; border: 1px solid black;}
```
```
<div id="container"></div>
```
[Answer]
# [Red](http://www.red-lang.org), 131 bytes
```
n: -1 view collect[loop 16[keep 'across
loop 16[keep compose[field 20x20 font-color red(to""to-hex/size n: n + 1 2)]]keep 'return]]
```
[](https://i.stack.imgur.com/y5965.png)
## If the leading zeroes need to be discarded:
# [Red](http://www.red-lang.org), 154 bytes
```
n: -1 view collect[loop 16[keep 'across
loop 16[s: to""to-hex/size n: n + 1 2 parse s[remove"0"]keep
compose[field 20x20 font-color red(s)]]keep 'return]]
```
[](https://i.stack.imgur.com/d9GT1.png)
Note: The first screenshot is taken on my Win 10 PC, the second one - on my Win 8.1 laptop, hence the difference.
[Answer]
# [PowerShell](https://github.com/powershell/powershell), 319 bytes
```
-1..15|%{If($_-lt0){$s="┌──";0..14|%{$s=$s+"┬──"};Write-Host "$s┐";}Else{$i=$_;0..15|%{Write-Host "│"-NoNewline;Write-Host ("{0:X2}"-f($i*16+$_))-f 12 -NoNewline;};Write-Host "│";$s=("├","└")[$_-eq15]+"──";0..14|%{$s=$s+(("┼","┴")[$i-eq15]+"──")};Write-Host("$s┤","$s┘")[$_-eq15]}}
```
Screenshot of the output:
[](https://i.stack.imgur.com/dSP3w.png)
Only my second PowerShell answer, so can definitely be golfed substantially.. Also, is it possible to create and use an Alias for the `Write-Host`?
**Explanation:**
*TODO: Will add one later.*
The `X2` could be `x2` to format the hexadecimal as lowercase letters.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~51~~ 49 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Wrong tool for the job, but I got it working eventually with a little help from [my solution to *Little Boxes on the Hillside*](https://codegolf.stackexchange.com/a/143481/58974). The spec doesn't include any details on margins, padding & border width so this won't look *exactly* like the reference image.
```
G²ÇsG ici%Ãú òG
£OlX¬,$...$¡`Þ:so¦d #000;¬l:d
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=R7LHc0cgaWNpJcP6IPJHCqNPbFisLCQuLi4koWDel4A6c2%2bmZCAjMDAwO6xsjjqcZA) (Open your browser's console)
If input *is* required then [this should work for ~~50~~ 48 bytes](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ssdzRyBpY2klw/og8lUKo09sWKwsJC4uLiShYN6XgDpzb6ZkICMwMDA7rGyOOpxk&input=MTY).
[Answer]
# [PHP](https://php.net/), 157 bytes
```
<?php for(;$i++<$n=$_GET[n];)for(print'<p>';$$i++<$n;)echo'<x style="color:red;border:1px solid #000;display:inline-block;width:25px">'.dechex($x++).'</x> ';
```
This should be run as a webpage, not from CLI. Pass input as a URL query string named `n`. For example: `grid.php?n=16`
**Sample output for `n=8`:**
```
<p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">0</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">4</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">5</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">6</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">7</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">8</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">9</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">a</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">b</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">c</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">d</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">e</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">f</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">10</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">11</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">12</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">13</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">14</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">15</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">16</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">17</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">18</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">19</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1a</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1b</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1c</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1d</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1e</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1f</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">20</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">21</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">22</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">23</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">24</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">25</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">26</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">27</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">28</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">29</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2a</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2b</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2c</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2d</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2e</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2f</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">30</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">31</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">32</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">33</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">34</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">35</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">36</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">37</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">38</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">39</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3a</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3b</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3c</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3d</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3e</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3f</x>
```
TIO link to get raw outputs (you have to save them as HTML to see the result): [Try it online!](https://tio.run/##LYzRCoIwFEB/ZdhgycgsCGJ36lP0A72FRLrFRmO7TKH59Wbk6zmHgwZn2aBBQh/Xy@3OPGtJRc5AmnoVrxC3QC3nkvrqX/kW8h/GaP3IJNYM6FpArnsTmExkGCenq6wPLkQRtYIuRKWjOODigrOKbMqyBGUHdM9JWO@s17vOhf4NH6tGI44nTFnNCrUsddrSxHleMLlPNWEwz18 "PHP – Try It Online")
[Answer]
# JavaScript (web browser console), 160 bytes
I think a JavaScript golfer should be able to golf this idea a lot more (I'm not one!).
```
function(n){for(x=i=0;i++<n;console.log(...a))for(j=0,a=[''];j++<n;a.push('float:left;border:1px solid #000;color:red'))a[0]+='%c'+(x++).toString(16).padEnd(2)}
```
A **155 bytes** version, but it prints some noises on top and right of the grid:
```
function(n,a=[]){for(x=0;x<n*n;a.push('float:left;border:1px solid #000;color:red'),a[0]+='%c'+(x++).toString(16).padEnd(2))x%n?0:console.log(...a,a=[''])}
```
This only works in modern browsers console.
Sample usage in console: `f=...code above...;` and then `f(16);`
Or open your browser's console and then click on **Run code snippet** button.
```
f=function(n){for(x=i=0;i++<n;console.log(...a))for(j=0,a=[''];j++<n;a.push('float:left;border:1px solid #000;color:red'))a[0]+='%c'+(x++).toString(16).padEnd(2)};
f(16);
```
### Explanation:
In a modern browser console, you can use this format to apply CSS to your values printed in the console:
```
console.log('%c Value', 'color: red; font-size: 10px;');
```
For every `%c` you have to add a new argument with your styles and those styles will be applied until the next `%c`. So to style and print two values in same line, we can use something like this:
```
console.log('%c Value %c Value2', 'color: red; font-size: 10px;', 'font-weight: bold;');
```
In the function above, I'm collecting arguments for each row in an array called `a` and each row gets a single `console.log` for itself.
] |
[Question]
[
Based on a comment by Jo King on my previous question (called '[Inverse-quotes-quine](https://codegolf.stackexchange.com/questions/187163/inverse-quotes-quine)'), I present this new question. The rules are similar, but just, the opposite:
* If your program is run normally, all of the code **not** in the speech marks (`"` - double quotes) should be printed.
* If your program is wrapped in double quotes (in turn inverting the speech marks), the code that is normally n̶o̶t̶ in quotes should be printed.
E.g:
Let's say you have the following code:
```
fancyStuff("myCode"); "I like".isGreat();
```
If I run it, I would expect an output of:
```
fancyStuff(
);
.isGreat();
```
However, if I wrapped it in quotes, I would get:
```
"fancyStuff("myCode"); "I like".isGreat();"
```
When this code is run, the expected output would be:
```
myCode
I like
```
Obviously, the above example is not a functional response in any language. Your job is to write the code that performs in this way.
# Rules
* Standard loopholes apply.
* The printed values, in both quoted and unquoted forms, must be non-empty, or consist solely of whitespace. This also means that all programs must include at least one set of quotes.
* However, trailing/preceeding whitespace is allowed.
* The quoted and unquoted strings *must* print different results.
* No looking at your own code, required file names, etc.
* Unmatched quotes are disallowed
* If there are multiple strings, they can either be printed as newlines (as in the example), or in some other *human-readable* way - no arrays or objects
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 32 bytes
```
''*2;print"''*2;print"''*2;print
```
[Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SqmCroKSkFPNfXV3LyLqgKDOvRAkr8z9QFRdUA4iKttI1jFVQVihKzc0vS1UoKUrMzMnMS1fISy0H0qlcXKkVqckaIJWaEKa6kro2iKsNZGj@BwA "Python 2 – Try It Online")
Based on my [initial solution for the other variant of this puzzle](https://codegolf.stackexchange.com/a/187168/86422).
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
·"·"·
```
Outputs concatenated without separator.
[Try it online](https://tio.run/##MzBNTDJM/f//0HYlMPr/HwA) or [try it online with surrounding quotes](https://tio.run/##MzBNTDJM/f9f6dB2KPr/HwA).
**Explanation:**
```
# Program without surrounding quotes will output string "··"
· # Double the top of the stack, which is empty, so an empty string is pushed
"·" # Push string "·" to the stack
· # Double it (2*). Since the legacy version is built in Python, the string is
# concatenated with itself: "··"
# (output the top of the stack implicitly as result)
# Program with surrounding quotes will output string "·"
"·" # Push string "·" to the stack
· # Double it to string "··"
"·" # Push string "·" to the stack
# (output the top of the stack implicitly as result)
```
[Answer]
## [><>](https://esolangs.org/wiki/Fish), ~~39~~ 16 bytes
```
"l2*0.|or|["090.
```
[Try it online!](https://tio.run/##S8sszvj/XynHSMtArya/qCZaycDSQO//fwA)
([quoted](https://tio.run/##S8sszvj/X0kpx0jLQK8mv6gmWsnA0kBP6f9/AA))
### Explanation
```
BA
"l2*0.|or|["090.
"l2*0.|or|[" Pushes the quoted characters onto the stack
0 Pushes 0
90. Goes to A
[ Wipes the stack (requires the 0)
" "090. Pushes the quoted characters onto the stack
l2*0. Length is 4; goes to B
|or| Reverses & prints the stack
```
```
A B
""l2*0.|or|["090."
"" No-op
l2*0. Length is 0; goes to A
"l2*0.|or|[" Pushes the quoted characters onto the stack
0 Pushes 0
90. Goes to B
|or| Reverses & prints the stack
```
## Old answer, 39 bytes
```
"!~l?!<r&[orl&"0[c2*&d0.>o<~~.!?@@0+1fl
```
[Try it online!](https://tio.run/##S8sszvj/X0mxLsde0aZILTq/KEdNySA62UhLLcVAzy7fpq5OT9HewcFA2zAt5/9/AA)
([quoted](https://tio.run/##S8sszvj/X0lJsS7HXtGmSC06vyhHTckgOtlISy3FQM8u36auTk/R3sHBQNswLUfp/38A))
Whew, this took a while. Can probably be golfed further.
```
A
"!~l?!<r&[orl&"0[c2*&d0.>o<~~.!?@@0+1fl
"!~l?!<r&[orl&" Pushes the quoted characters onto the stack
0[ Wipes the stack
c2*& Puts 24 into the register (&)
d0. Goes to A
" "0[c2*&d0.>o<~~.!?@@0+1fl Pushes the quoted characters onto the stack
!~l?!< No-op (in this case)
r Reverses the stack
&[ Wipes the stack, preserving the top &
o Outputs the top character on the stack
r Reverses the stack
l& Puts the current length of the stack into the register
Repeats until &=0, then errors
```
```
B
""!~l?!<r&[orl&"0[c2*&d0.>o<~~.!?@@0+1fl"
""!~ No-op
l?!< Reverses the IP direction
""!~l?! " No-op
~~.!?@@0+1fl If the length is 0, go to B
""!~l?!<r&[orl&" " Pushes the quoted characters onto the stack (backwards)
~~.!>@@0+1fl No-op (length != 0)
>o< Outputs all the characters on the stack, then errors
```
*(Note: when I "wipe" the stack, it really creates a new stack; the old stack is still there and accessible)*
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 9 bytes
```
`H"H` "H
```
[Try it online!](https://tio.run/##S8/PScsszvj/XyHBQ8kjQUHJ4/9/AA "Gol><> – Try It Online") [Quoted version.](https://tio.run/##S8/PScsszvj/X0khwUPJI0FByUPp/38A "Gol><> – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 17 bytes
```
"af0.|o<"i!.1!0<9
```
[Try it unquoted!](https://tio.run/##S8sszvj/XykxzUCvJt9GKVNRz1DRwMby/38A "><> – Try It Online") [Quoted!](https://tio.run/##S8sszvj/X0kpMc1ArybfRilTUc9Q0cDGUun/fwA)
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 11 bytes
```
!"!""!$;"$;
```
[Try it online!](https://tio.run/##KyrNy0z@/19RSVFJSVHFWknF@v9/AA "Runic Enchantments – Try It Online") and [`"!"!""!$;"$;"`](https://tio.run/##KyrNy0z@/19JEQiVFFWslYDo/38A)
Just a one-byte 'inversion' of [the prior answer](https://codegolf.stackexchange.com/a/187165/47990) (and 1 byte for having to include the inverting-byte as part of a string literal as well).
### Explanation
Note that `.` is a NOP command and used as a spacer where other commands are not executed or otherwise removed for explanatory purposes.
`!"` is effectively NOP, resulting in the execution of only `...."!$;"$;` which prints the contents of the code not contained between quote-pairs (`!........$;`)
Wrapping everything in quotes causes the first `!"` to be string literal, resulting in `"!".."!$;"$;.` and which prints the parts of the program contained within quote-pairs (`"!"` and `"!$;"`).
] |
[Question]
[
## Challenge:
Take a rectangular figure consisting of the two characters `#` and (whitespace, ASCII-32), and identify which direction the lines are. The options are: 'Vertical', 'Horizontal', 'Left Diagonal' and 'Right Diagonal'.
### Input:
The input will be a figure of size **n-by-m** where **5 <= m,n <= 20**. There will be two spaces between horizontal lines, two spaces between lines in the horizontal/vertical direction. Note that the lines doesn't have to start or end in a corner. The input will look like this:
Horizontal:
```
##########
##########
##########
```
Vertical (note that there can be leading spaces):
```
# # #
# # #
# # #
# # #
# # #
```
Left diagonal:
```
# # #
# #
# #
# # #
# #
```
Right diagonal:
```
# # # # #
# # # #
# # # # #
# # # # #
# # # #
```
* The input format is optional. You may substitute the visual newlines by `\n`, or create the grid by concatenating the rows with ASCII-10 (relevant for MATLAB/Octave).
* You may not take the input as numbers (`1/0`) instead of `#` and `0`.
### Output:
The output shall be 4 distinct values/outputs for each of the four different cases. It can for instance be **1,2,3,4**, or **V,H,L,R**.
### Test cases:
There will be an asterisk over the top left corner of the figure, and an asterisk below the bottom left corner of the figures. This is to indicate where the figure starts and ends.
```
Horizontal:
*
#####
#####
*
*
###########
*
*
##########################
##########################
##########################
*
Vertical:
*
# # # #
# # # #
# # # #
# # # #
# # # #
*
*
# # # # # #
# # # # # #
# # # # # #
# # # # # #
# # # # # #
*
Left diagonal
*
# # #
# #
# #
# # #
# #
*
*
# # # # #
# # # #
# # # #
# # # # #
# # # #
# # # #
*
*
# # #
# # # #
# # #
# # #
# # # #
*
Right diagonal
*
# # # # #
# # # #
# # # # #
# # # # #
# # # #
*
*
# # # # # # #
# # # # # # #
# # # # # #
# # # # # # #
# # # # # # #
*
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in each language wins.
[Answer]
# [Slip](https://github.com/Sp3000/Slip/wiki), 6 + 2 = 8 bytes
+2 bytes for the `f` flag.
```
^*`#`#
```
[Try it here!](https://slip-online.herokuapp.com/?code=%5E%2a%60%23%60%23&input=%23%20%20%23%20%20%23%20%20%23%20%20%23%20%0A%20%20%23%20%20%23%20%20%23%20%20%23%20%20%0A%20%23%20%20%23%20%20%23%20%20%23%20%20%23%0A%23%20%20%23%20%20%23%20%20%23%20%20%23%20%0A%20%20%23%20%20%23%20%20%23%20%20%23%20%20&config=f)
Prints one of the following:
```
##
```
```
#
#
```
```
#
#
```
```
#
#
```
### Explanation
The `^*` sets the IP's direction to any one of the eight octilinear directions. Then ``#`#` simply matches two hash symbols in that direction. The `f` flag limits Slip to looking only for the first match, and by default the bounding box of that match is printed to STDOUT.
The pattern itself would be two bytes shorter in [Snails](https://github.com/feresum/PMA/blob/master/doc.md) (`z\#2`), but I don't think Snails can print the match itself, it only has numeric output (and adapting the pattern to printing 4 different numbers based on the direction would most likely take a lot more bytes).
[Answer]
## [Grime](https://github.com/iatorm/grime), 4 bytes
```
s./$
```
[Try it online!](https://tio.run/##Sy/KzE39/79YT1/l/38FZQUw4oJQClzKMAa6jAIA "Grime – Try It Online")
Prints one of the following 2x2 blocks (which should be padded with spaces, some of which are swallowed up by SE):
```
##
```
```
#
#
```
```
#
#
```
```
#
```
Where the last one indicates lines along antidiagonals.
### Explanation
The pattern matches a 2x2 square starting from the first `#` in reading order. The `#` is matched with `s` (the "symbol" character class), the following character with `.` (which can be any character). To this 2x1 rectangle we concatenate another one vertically with `/`. That other rectangle is just `$` which always matches, so this simply fills up the 2x2 square with the two characters below. This unique identifies all four cases.
[Answer]
# [Retina](https://github.com/m-ender/retina), 48 bytes
```
ms`^(.*¶)?( *)( ?#)((#)|[^¶]*¶\2( ?#)).*
$3$5¶$6
```
[Try it online!](https://tio.run/##K0otycxL/P8/tzghTkNP69A2TXsNBS1NDQV7ZU0NDWXNmui4Q9tigeIxRmAxTT0tLhVjFdND21TM/v8HAA "Retina – Try It Online") Returns the same results as @MartinEnder's Slip answer.
] |
[Question]
[
## The task
In this challenge, your task is to determine whether some string occurs as a substring of a given string both surrounded by another string and reversed.
Your input is a non-empty string **S** of lowercase ASCII letters.
If there exist non-empty strings **A** and **B** such that the concatenation **ABA** and the reversal **rev(B)** are both contiguous substrings of **S**, then your output shall be a truthy value.
Otherwise, your output shall be a falsy value.
The two substrings may occur in any order, and they can even overlap.
However, it can be shown that in all truthy cases, you can either find non-overlapping substrings or a solution where **B** is a palindrome.
## Example
Consider the input string `S = zyxuxyzxuyx`.
We choose `A = xu` and `B = xyz`, and then we can find the following substrings:
```
S = zyxuxyzxuyx
ABA = xuxyzxu
rev(B) = zyx
```
The choice `A = x` and `B = u` would also be valid.
The correct output in this case is truthy.
## Rules and scoring
You can write a full program or a function.
Standard loopholes are disallowed.
The lowest byte count wins.
## Test cases
Truthy
```
sds
aaxyxaa
aaxyaaayx
hgygjgyygj
zyxuxyzxuyx
cgagciicgxcciac
iecgiieagcigaci
oilonnsilasionloiaammialn
abbccdeeaabccddbaacdbbaccdbaaeeccddb
```
Falsy
```
a
aaxyaa
jjygjhhyghj
abcaabbccaabca
egaacxiagxcaigx
lnsiiosilnmosaioollnoailm
cabbccabdcaddccabbddcaabbdcaddccaadcabbccaabbcadcc
```
### Fun fact
One can construct arbitrarily long falsy strings using four distinct letters, but not using three letters.
The fourth falsy test case is the longest possible.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
s↔B&sA,B,A~s?
```
[Try it online!](https://tio.run/##PY3NbcJAEIV78SEnn9JABGWAcngerNmxxjsSK6RdonDwgQqogArogy7cyGY2Qlye3o/0vuEICkWNP@vPen2sy/L7vNe0Xm/bj7Tpt/3mkr5q3XfpkLq@A3LJwMsBKNl94MITFxcP55JPuZzz6X8iBpMIcSYSkDcyEouMrWaQeGOiFmMSRRKLagLMs0Bjw7xRbqbJESEUDg2EgYBhoKbU5pEBygJnQbjR1V/F/DnOliBmqtEgOnffdfcH "Brachylog – Try It Online")
## How it works
```
s↔B&sA,B,A~s?
s the input has substring temp
↔B temp reversed is B
& and the input
sA has substring A
,B,A A,B,A
~s? is a substring of input
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 40 bytes
```
(.+)(.)+\1.*(?<=(?=(?<-2>\2)+(?(2)A)).*)
```
[Try it online!](https://tio.run/##NU5BasQwDLz7HwV7QwPNedvQUz@xh45loyg4NtRdsPfzqRK2IGZGw6DRT/yVjP3Ffn3vdhycHd1wexsvdr6@21nn@jp93CY32NlO7tO58eL2vYZqgNYbcDKA3szCnVfuCubR2731R7urTQwmEeJGJCAjkVgkHiaDxBRJJecqCVVKTkWAbROkbOA9UYgRODh4gIL3UK0yxtMz/x@YddXmZem8rCayZptAOyHcTNL7UrQjb6VCSkkpF0jaDJ0l8IEQwiG8Eg56GgjPyIG60B8 "Retina – Try It Online")
Big thanks to Martin for fixing a bug with the expression.
Matches **ABA** then the rest of the string. While doing this, it pushes **B**'s characters onto a stack. Looks backwards over the whole string to find **B** in reverse order, by traversing forward again and popping characters off of the stack as it matches them (`(?<-2>\2)+`). Then it makes sure the stack is empty by trying to match a capital letter, which won't be in the input, if the stack still is full.
[Answer]
## Ruby, 53 bytes
```
->s{s.scan(/(?=(.+)(.+)\1)/).any?{|a,b|s[b.reverse]}}
```
Fairly straightforward. The only real trick is the positive lookahead `(?=...)` in the regex, which is used to find all matches and not just non-overlapping ones.
[Try it online!](https://tio.run/##NY5RbsIwEET/fYr8AWob1ANQDkL5GK8XZyPHrmJS2RDOnm6osLSe0ZNmZ8fJ1uXSHJaPr3zPbSbE7X57PGzbt90635@7/a5FrMf7jHc755NtR/7lMfP58Vg22WUDlFqApwKoxXS@@t5X/cytlqnUW5kUk4cnEfKFSEBGmLwIr9CDxCQJKcYsAVlSDEmAYRCEaGAtkWMGVnUWIGct1KtlfjLzusD0vTZ3XfVdr0nCM71GYdhrtAj0BIgvJmidJK2MQ8qQlEKICRIGQ/8p6wjOrcaqrKteAI5ei3Wzkk0bJHJuGdQ1LjXzlfN1No2@n@mam8tpBWfD0S1/ "Ruby – Try It Online")
[Answer]
# [PHP](https://php.net/), 95 bytes
```
<?=($p=preg_match_all)('#(?=(.+)(.+)\1)#',$argn,$t)&&$p(strrev("#".join("|",$t[2])."#"),$argn);
```
[Try it online!](https://tio.run/##jVFBbsIwELz7GQZBrCKk9kopDykVmqxdeyPHjhKoHNq@nW6CuPdg72jWszNad6G7vR660Kklep/2GnVNZJ0DpmprgGxdQ7BA52ZO79Rn7h0oVK50MVtX6WPSGz3YQQFlLMBcAYxFBT/6xo9yqetYLmW8lovQ5OGJmXwhYpBiR57ZTaQHscocc0oDRwycU8wMtC0jJvWfjOqRQDWNOIcw@tCIkjCrJymU8yItDIkA9kVFseMslqnNAzjnGFMGx1bRXVVbgrUTqKVMox4ELD0Gy2RhtMEw79R8q8ObLHlfLbt91zt/anGmcEKMplovKmlsn8x0js9msd7Mos3ybFarZVcN5753X5Ve6G2TOVX6R0vv/eXDbIUz99dmd3MU8vQJu9/bHw "PHP – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
Ḣ⁼Ṫȧ
ẆŒṖ€ẎÇÐfẎ€QUẇ€⁸Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8///hjkWPGvc83LnqxHKuh7vajk56uHPao6Y1D3f1HW4/PCENSAN5gaEPd7UD6UeNOx7ubPj//39yemJ6cmZmcnpFcnJmYjIA "Jelly – Try It Online")
Very inefficient.
] |
[Question]
[
## Introduction
Emoji use a particular alphabet for their national flags, which allows one to put two symbols together to create the appropriate flag.
`üá¶üáßüá®üá©üá™üá´üá¨üá≠üáÆüáØüá∞üá±üá≤üá≥üá¥üáµüá∂üá∑üá∏üáπüá∫üáªüáºüáΩüáæüáø`
Your challenge, is to transform any uppercase letter into the appropriate Flag Identifier.
This may be much harder for languages that do not innately handle Unicode.
Each symbol is exactly 4 UTF-8 Bytes.
## The Task
Given an input as one or more letters, output the same, with all letters replaced with their flag combinations.
Winner is the answer with the least *Bytes*, giving the tiebreaker to first answer posted.
## Input / Output
Input and Output may use any standard method.
Letters in the input may optionally only support one case, Upper or Lower. Please specify in your answer what case your solution supports.
Your output may, intentionally or otherwise, output flag emoji instead of letter pairs.
## Test Cases
`FR` `üá´üá∑`
`Hello, World!` `üá≠üá™üá±üá±üá¥, üáºüá¥üá∑üá±üá©!`
## Rules
* Standard Loopholes Apply
* Standard Input Output allowed
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), however, All the Emoji Letters as provided above can be counted for a single byte each, instead of four. Least Bytes wins!
[Answer]
# Retina - ~~9~~ 7 bytes
Supports uppercase.
I don't really know retina, so I'm not sure the question mark diamonds show up because of TIO limitations or because I did something wrong, if its the latter, please leave a comment.
```
T`L`üá¶-üáø
```
[Try it online here](http://retina.tryitonline.net/#code=VGBMYPCfh6Yt8J-Hvw&input=RlIKSGVsbG8sIFdvcmxkIQ).
[Answer]
# Pyth - ~~18~~ 16 bytes
Supports lowercase.
```
XzGsCMrF+BC\üá¶26
```
[Test Suite](http://pyth.herokuapp.com/?code=XzGsCMrF%2BBC%5C%F0%9F%87%A626&test_suite=1&test_suite_input=FR%0AHello%2C+World%21&debug=0).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
C Ĭª∆õ‚ÅΩ·πó¬ª*+
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCJDOiIsIkPKgMK7xpvigb3huZfCuyorIiwiQ+G5hSIsIkhFTExPLCBXT1JMRCEiXQ==)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
*Ties [Steffan's Vyxal answer](https://codegolf.stackexchange.com/a/248378) for #1.*
```
A"üá¶üáø"√á≈∏√߂İ
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fUenD/PZlQLxf6XD70R2Hlz9qWPj/f0ZqTk6@jkJ5flFOiiIA "05AB1E – Try It Online") Supports lowercase only.
[Answer]
# Lua 5.3, 76 bytes
Lua 5.3 newly has a UTF-8 manipulation library, which is useful in this case.
Lowercase only
```
print(arg[1]:gsub("%l",function(c)return utf8.char(c:byte()+127365)end).."")
```
[Answer]
# Scala, 75 bytes
```
(s:String)=>s.flatMap(c=>if(c.isLetter)Seq(55356,c+56741)else Seq(c))
```
Explanation:
```
(s:String)=> //define an anonymous function taking a string
s.flatMap(c=> //map each char...
if(c.isLetter) //if it's a letter
Seq(55356,c+56741) //...to a sequence of 55356 and c+56741, this is the target char in UTF16 encoding as a surrogate pair
else //else
Seq(c) //..to a sequence of c
) //and flatten
```
Only works for uppercase.
This returns a the output as sequence of integers in UTF16.
[Answer]
# x86-64, 17 bytes
Takes input as UTF-32LE string in `rsi`, and outputs in the same format to a buffer at `rdi`, and code point count in `rcx`. Only works for uppercase letters. This can be linked to C code with the function signature `void f(int *output,int *input,int dummy,int count);`. The dummy variable is just to put the count in the `rcx` register.
`fff10100` is the UTF-32LE encoding for `üáø`, and so only costs one byte.
```
ad 50 5a 2c 41 2c 19 8d 80 fff10100 0f 47 c2 ab e2 ed c3
```
Or, in assembly:
```
0: ad lodsd
1: 50 push rax
2: 5a pop rdx
3: 2c 41 sub al,0x41
5: 2c 19 sub al,0x19
7: 8d 80 ff f1 01 00 lea eax,[rax+0x1f1ff]
d: 0f 47 c2 cmova eax,edx
10: ab stosd
11: e2 ed loop 0
13: c3 ret
```
Uses the string manipulation instruction `lodsd` to load one code point into `eax`, checks if it's a capital letter using two successive subtractions, and adds the appropriate value to convert it to a flag if it is. Otherwise, it uses the conditional move `cmova` to restore its original ascii value. Finally, it uses `stosd` to put a code point in the buffer.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~125~~ 111 bytes
```
main(c,v)char**v;{for(v++;c=**v;putchar(" Ee"[c]+*(*v)++))c=!isalpha(c)-~!islower(c),c%3&&printf(L"\x879ff0");}
```
*-14 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
[Try it online!](https://tio.run/##FcnRCsIgFADQX9mExr26QdBDheyxt/6gepCbpuCm2HJB1K/b9ng41D2IShmUG4HajGRV4jzLjwkJshCS@pXxNa0DrDppdqGb4MAzCoFIfe2eykergLD7LfBh1mlBS5td08TkxsnAmV3fh/3RmC1D@S2lWO19aKs5JH@v/w "C (gcc) – Try It Online")
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 13 bytes
```
e€ØAד¢®Ƒ’+OỌ
```
Supports only uppercase letters.
[Try it online!](http://jelly.tryitonline.net/#code=ZeKCrMOYQcOX4oCcwqLCrsaR4oCZK0_hu4w&input=&args=SEVMTE8sIFdPUkxEIQ)
## Explanation
```
e€ØAד¢®Ƒ’+OỌ Input: string S
e€ Test if each char in S is an element of
√òA the uppercase alphabet 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
√ó Multiply by
“¢®Ƒ’ The codepoints of '¢®Ƒ' as a base 250 integer
This forms 127397
+ Vectorized add with
O The codepoints of each char in S
Ọ Convert back to char from codepoints
Return and print implicitly
```
[Answer]
## JavaScript (ES6), 70 bytes
```
f=
s=>s.replace(/[A-Z]/g,c=>String.fromCodePoint(c.codePointAt()+127397))
;
```
```
<input oninput=o.textContent=f(this.value)><div id=o>
```
Accepts upper case only. Mixed case version for 73 bytes:
```
f=
s=>s.replace(/[A-Z]/gi,c=>String.fromCodePoint(c.codePointAt()+5|127392))
;
```
```
<input oninput=o.textContent=f(this.value)><div id=o>
```
[Answer]
# PHP, 101 Bytes
supports both replace 64 with 96 to support only lowercase. input only ascii characters allowed
```
foreach(str_split($argv[1])as$c)echo($o=ord($c))>64&&$o%32<27?hex2bin("f09f87".dechex($o%32+165)):$c;
```
PHP, 112 Bytes
supports both remove i as modifier in the regex to support only lowercase
```
<?=preg_replace_callback("#[a-z]#i",function($t){return hex2bin("f09f87".dechex(ord($t[0])%32+165));},$argv[1]);
```
first version 205 Bytes
```
<?=preg_replace_callback("#[a-z]#i",function($t){return substr("üá¶üáßüá®üá©üá™üá´üá¨üá≠üáÆüáØüá∞üá±üá≤üá≥üá¥üáµüá∂üá∑üá∏üáπüá∫üáªüáºüáΩüáæüáø",(ord($t[0])%32-1)*4,4);},$argv[1]);
```
The version with `mb_substr` is one Byte longer
[Answer]
# Python 3, 68 bytes
```
lambda s:''.join(chr(x+127397*(64<x<91))for x in map(ord,s.upper()))
```
Usage (when assigned to `f`):
```
print(f("Hello, World!"))
print(f("A B C - X Y Z"))
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p`, 17 bytes
Counting the letter symbols as one byte each, per OP. Works with uppercase letters.
```
$_.tr!"A-Z","üá¶-üáø"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6BUuyCpaUlaboW21Xi9UqKFJUcdaOUdJQ-zG9fpgsk9itBZKGKFmxwC-LycPXx8ddRCPcP8nFRhIgDAA)
] |
[Question]
[
*Inspired by a chat conversation I lurked.*
I am an adventurer on the far away land of Zendikar. I truly enjoy traveling the land. Bushwhacking, weathering the [roil](http://mtgsalvation.gamepedia.com/Roil) and encountering strange and exotic flora and fauna are the highlights of any good adventure. Unfortunately, my duties as an adventurer do not always allow me to stop and smell the lotuses. Occasionally I am crunched for time and must hop on my [kitesail](http://magiccards.info/wwk/en/126.html) and fly to my destination. I just glide over the land without being able to enjoy it.
# The Challenge
Write a program that will let me know if I can choose not to fly. The program will take three inputs: my current location, my destination, and the maximum permitted travel time in days. Using the information below, determine if my travel time on foot is less than my maximum allowed travel time. If it is and I can travel on foot, return a truthy value. If the land travel time is as long as or longer than the maximum time, return a falsey value.
**Guul Draz** is two days away from **Sejiri**, its only neighboring territory.
**Sejiri** is one day away from **Murasa** and two days from **Guul Draz**.
**Murasa** is one day from **Bala Ged**, one day from **Akoum**, two days from **Tazeem**, and one day from **Sejiri**.
**Bala Ged** is two days from **Akoum** and one day from **Murasa**.
**Akoum** is one day from **Ondu**, one day from **Murasa** and two days from **Bala Ged**.
**Ondu** is one day from **Akoum**, its only neighboring territory.
**Tazeem** is two days from **Murasa**, its only neighboring territory.
Every location is connected, but not always directly. For example, going from Tazeem to anywhere requires you to travel to Murasa first. There are no real branches in the path either. Protip: Only go to Bala Ged if it is one of your endpoints. Here is a rough map if you're lost:
```
Bala Ged --
| \
Guul Draz ---- Sejiri -- Murasa -- Akoum -- Ondu
|
|
Tazeem
```
# Scoring
This is code golf, so shortest program wins. Standard loopholes apply.
# Test Cases
```
Guul Draz
Ondu
5
False
Bala Ged
Akoum
3
True
Tazeem
Sejiri
1
False
```
[Answer]
# TI-BASIC, ~~84~~ 82 bytes
```
Prompt Str1,Str2,X
"GSMAOBT->Str3
{-3,-1,0,1,2,i,-2i
Ans(inString(Str3,sub(Str1,1,1))-Ans(inString(Str3,sub(Str2,1,1
X>real(Ans-iAns
```
I store the positions of each city on the complex plane, then calculate the Manhattan distance. Bala Ged is at `0+1i`, Guul Draz is at `-3+0i`, and so on.
There would be a 75-ish byte solution if quotes could be in strings, but one of TI-BASIC's limitations prevents that.
[Answer]
# Mathematica 153
This checks whether the required time to travel (the `GraphDistance` in `Edgeweight`s, i.e. days), is less than or equal to the available time to travel, also in days. This sort of approach should work with much larger graphs, corresponding to a great many locations and connections.
```
s=StringTake;g=Graph[UndirectedEdge@@@Partition[Characters@"GSSMMBMAMTBAAO",2],
EdgeWeight->{2,1,1,1,2,1,1}]
f[a_,b_,n_]:=GraphDistance[g,a~s~1,b~s~1]<=n
```
[Answer]
# Ruby 113/112
More bytes than TI Basic, but less characters.
```
v=0
a=(0..1).map{c=gets[0];(d="BT".index(c))&&v+=1+d;"GGSMAO".index(c.tr('BT',?M))}
p gets.to_i>(a[0]-a[1]).abs+v
v=0
a=(0..1).map{c=gets[0];(d="BT".index(c))&&v+=1+d;"OAMSSGGGBBBBBBT".index(c)%6}
p gets.to_i>(a[0]-a[1]).abs+v
```
Two slightly different solutions, on the same principle:
There's no point in considering the direct route between Bala Ged and Akoum, because the route via Murasa is the same length.
The main left-right string of places can be considered by taking the indices in a string and finding the difference between them.
For B and T, we need to add an extra 1 or 2. This is held in the variable `v`. The two versions differ in the way that B and T are made to give the same index in the main string as M. In the first, it's done by replacement B or T --> M in the input. In the second it's done by modulo (I prefer the first one, but the second one's a byte shorter.)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 44 bytes
```
"GSMAOBT"D2FsIнk])εyy0Qi¼ëy4›i2¼y5-½]`α¾+³-d
```
[Try it online!](https://tio.run/##AVAAr/9vc2FiaWX//yJHU01BT0JUIkQyRnNJ0L1rXSnOtXl5MFFpwrzDq3k04oC6aTLCvHk1LcK9XWDOscK@K8KzLWT//0JhbGEgR2VkCk9uZHUKMw "05AB1E – Try It Online")
A little too long to be proud of
```
"GSMAOBT" push the first letters of each city
D duplicate this
2F do 2 times:
s swap the two previous stack entries
I get next input
н get the first letter of that
k push the index of that letter in "GSMAOBT"
]
) push both indexes in a list
ε for each entry of that list
y push the current value for that entry
y0Qi if current entry == 0 (Guul Draz)
¼ increment counter (will be added to the distance in the end)
ë else
y4›i if current entry > 4 (Bala Ged or Tazeem)
2 set current list entry = 2 (Murasa)
¼ increment counter
y5-½ if entry = 4 (Tazeem), increment counter another time
]
` push both indexes on the stack separated
α get absolute difference of them
¾+ add the counter variable to that
³-d check, if it's equal or smaller than the maximum time
```
] |
[Question]
[
I'm starting with golf code. But im only do C# so I know wont be a breaking record, but I want give it a try. [Leibniz](http://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80)
Challenge is [here](https://www.hackerrank.com/codesprint4/challenges/leibniz)
The first line contains the number of test cases (N) which is less than 100. Each additional line is a test case for a positive integer value (T) less than 10^7.
I format the code to easy the reading, removing spaces I reduce it to 210 chars.
The best code submit for this problem is 54 char, but For C# lenguaje the best is 172 chars.
My guess is should remove reading the N, but couldn't make it stop properly.
```
using System;
class S
{
static void Main()
{
int n=Convert.ToInt32(Console.ReadLine()),i=0;
for (;i++<n;)
{
double r=0,t=Convert.ToInt32(Console.ReadLine()),j=0;
for(;j<t;)
r+=(1-j%2*2)/(2*j+++1);
Console.WriteLine(r);
}
}
}
```
**NOTE**
Mono C# compiler 3.2.8.0 .NET 4.0 CLR
So `using C=System.Console` doesn't work.
[Answer]
As I suggested in a comment on VisualMelon's answer, the second `for` loop is being underutilised. By changing some variable scopes it's possible to use the `for`s in such a way that we save one set of curly brackets and one variable, and perform the sum in the correct order, fixing the bug in the supplied code.
Golfed:
```
using C=System.Console;class S{static void Main(){for(double n=int.Parse(C.ReadLine()),r,t;n-->0;C.WriteLine(r))for(r=0,t=2*int.Parse(C.ReadLine());t>0;t--)r-=(1-t%4)/--t;}}
```
[Online demo](http://ideone.com/tou5M4)
Ungolfed:
```
using C = System.Console;
class S {
static void Main() {
for (double n=int.Parse(C.ReadLine()), r, t; n-- > 0; C.WriteLine(r))
for (r=0, t=2*int.Parse(C.ReadLine()); t>0; t--)
r -= (1-t%4) / --t;
}
}
```
[Answer]
Couple of simple things that apply in lots of places:
1. You've got a free semi-colon in your first for loop which you can make use of
2. You keep track of `i` against `n`, but you as you never use the value of `n`, you can use it as the counter itself.
3. As someone else said, you can use `int.Parse` (or `double.Parse`) instead of the Convert namespace/class/whatever it is - this makes your `using System` directive less helpful, and you are better of using the classic `using C=System.Console` (unless C# 6 has come out, I can't say I'm sure, in which case you can `using System.Console` directly)
4. There is an unneeded space after the first for (not sure if you'd accounted for this or not)
I haven't tested this code, but hopefully it will at least help:
```
using C=System.Console; // 3
class S
{
static void Main()
{
for(int n=int.Parse(C.ReadLine()); // 1, 3, 4
n-->0;) // 2
{
double r=0,t=int.Parse(C.ReadLine()),j=0; // 3
for(;j<t;)
r+=(1-j%2*2)/(2*j+++1);
C.WriteLine(r); // 3
}
}
}
```
Is it possible that the shorter C# solution disregards the first line, and just assumes the input is clean? May well be cheaper to do that if it is allowed.
This is just a quick reply, I might have a better bash at this tomorrow when I have less going on.
[Answer]
* Instead of `Convert.ToInt32`, use `int.Parse`; it saves a few characters.
* Unless you really need a double, use a `float`; it's one char shorter than `double`.
[Answer]
## 172 Characters
The permanent version of the challenge can be found [here](https://www.hackerrank.com/challenges/leibniz). I have the shortest solution for C#, which is 172 characters.
### Golfed
```
using R=System.Console;class C{static void Main(){R.ReadLine();for(double s,n,j;;){for(s=0,n=int.Parse(R.ReadLine()),j=0;j<n;){s+=(j%2<1?1:-1)/(2*j+++1);}R.WriteLine(s);}}}
```
### Ungolfed
```
using R=System.Console;
class C
{
static void Main()
{
R.ReadLine();
for(double s,n,j;;)
{
for(s=0,n=int.Parse(R.ReadLine()),j=0;j<n;)
{
s+=(j%2<1?1:-1)/(2*j+++1);
}
R.WriteLine(s);
}
}
}
```
It does error out on the last loop, but it's after outputting all test cases.
# Edit
Seeing it ungolfed like this, just realized I can inline the for loop.
## 170 characters
### Golfed
```
using R=System.Console;class C{static void Main(){R.ReadLine();for(double s,n,j;;){for(s=0,n=int.Parse(R.ReadLine()),j=0;j<n;)s+=(j%2<1?1:-1)/(2*j+++1);R.WriteLine(s);}}}
```
### Ungolfed
```
using R=System.Console;
class C
{
static void Main()
{
R.ReadLine();
for(double s,n,j;;)
{
for(s=0,n=int.Parse(R.ReadLine()),j=0;j<n;)
s+=(j%2<1?1:-1)/(2*j+++1);
R.WriteLine(s);
}
}
}
```
# Edit 2
@PeterTaylor's answer has some fantastic logic. Cleaned it up a bit, and I'm still using exceptions for control flow.
## 155 characters
### Golfed
```
using R=System.Console;class C{static void Main(){R.ReadLine();for(double s,n;;R.WriteLine(s))for(s=0,n=2*int.Parse(R.ReadLine());n>0;n--)s-=(1-n%4)/--n;}}
```
### Ungolfed
```
using R = System.Console;
class C
{
static void Main()
{
R.ReadLine();
for(double s, n;; R.WriteLine(s))
for(s = 0, n = 2 * int.Parse(R.ReadLine()); n > 0; n--)
s -= (1 - n % 4) / --n;
}
}
```
I really wish I could get rid of the extra ReadLine().
] |
[Question]
[
In this challenge, your input is a string of lower-case letters like this:
```
insertspacesbetweenwords
```
and [a dictionary](http://fuz.su/~fuz/files/voc.xz) like the that from [my other challenge](https://codegolf.stackexchange.com/q/45168/134). You may assume that the dictionary file contains only lower-case letters and line-feed characters. Furthermore, the last character in the dictionary file is a line-feed character and the entries are sorted alphabetically.
Write a function that given these two strings, returns a single string containing all possible ways to insert spaces between some of the characters in the input string, such that the words created are all in the dictionary. Each possibility shall be terminated with a line-feed character. Some lines of the output for the example are:
```
insert spaces between words
insert space s between words
insert spaces between word s
insert space s between word s
insert spaces be tween words
```
The order of the output lines doesn't matter.
This is codegolf, the usual scoring rules apply, standard loopholes are verboten.
[Answer]
# Python 3, 88
```
f=lambda x,w,s=[]:[x or print(*s)]+[x.find(y)or f(x[len(y):],w,s+[y])for y in w.split()]
```
String to split is `x`, the dictionary string is `w`.
The idea is to repeatedly check which strings `y` of the dictionary are a prefix for the current string `x`. The expression `x.find(y)` evaluates to the Falsey `0` only if `x` starts with `y` (substrings not present give `-1`), so the short-circuiting of `or` makes the function recurse down only when the prefixes matches. The prefix is chopped off with `x[len(y):]` and the list of subwords is updated in `s`.
When the whole string `x` has been consumed, we print the subwords `s`, automatically joined by spaces.
[Answer]
# Haskell, ~~113 107 105 88 87~~ 86 bytes
Works for empty inputs too (but gives an empty string as output).
```
s!d=unlines[w|w<-map concat$mapM(\c->[[c],[' ',c]])s,all(`elem`lines d).words$w,w>"!"]
```
Defines an infix binary function `!`. Call it like this:
```
"abababbaab" ! "ab\nba\na\nbab\n"
```
Result:
```
"ab ab ab ba ab\nab a bab ba ab\na bab ab ba ab\na ba bab ba ab\n"
```
### Explanation
The idea is to split the left input string `s` into words by inserting spaces in all possible ways, and keep those that consist of words of the dictionary `d`. A leading space is checked by comparing to the string `"!"`.
```
s!d= -- Define the string s!d by
unlines -- joining with line-breaks
[w|w<- -- the strings w obtained by
map concat$ -- concatenating each list of strings
mapM(\c->[[c],[' ',c]])s, -- obtained by replacing each letter 'c' of s by
-- either "c" or " c",
all(`elem`lines d). -- such that only lines of d
words$w, -- occur as words in w, and
w>"!"] -- w is lexicographically larger than "!",
-- which here means that w does not begin with a space.
```
] |
[Question]
[
A [centered polygonal number](http://mathworld.wolfram.com/CenteredPolygonalNumber.html) is able to be put into an arrangement of multiple concentric polygons, each with a side length of one more than the inner one. For example (image from linked page),

the above image has 31 dots, so 31 is a *centered pentagonal number*.
Write a program which receives a number as input (any typical input method is fine), and displays a picture similar to the above.
In particular:
* There must be a centered dot.
* Each concentric polygon contains an increasing number of dots, all connected through a line.
* The angles must be correct for the appropriate regular polygon.
* The distance between connected dots must be the same throughout the picture.
* Each polygon must be centered inside the surrounding polygon.
The input will be between 2 and 1000, and is guaranteed to be a centered polygonal number of some kind.
If there are multiple possible solutions, display them all. For example, an input of 181 should display both a centered square (of 9 "rings") and a centered pentagon (of 8 "rings").
No hardcoding answers.
[Answer]
# HTML + JS, ~~913~~ ~~857~~ 675 bytes
(Line breaks are added for readability)
```
<body><script>
function O(X,x,y,R){X.beginPath();X.arc(x,y,R,0,M.PI*2,true);X.closePath();X.fill()}
Z=300,P=3,H=Z/2,$=+prompt(),M=Math;for(S=3;S<$;S++){for(C=1;C<30;C++){if(S*C*C+S*C+2==$*2){
V=document.createElement("canvas");V.width=V.height=Z;document.querySelector("body").appendChild(V);X=V.getContext("2d");
O(X,H,H,P);for(R=1;R<=C;R++){
D=[],A=R*(H-P)/C,G=0;X.beginPath();X.moveTo(H+A,H);D.push([H+A,H]);for(s=1;s<S;s++){x=M.cos(G+=M.PI*2/S)*A,y=M.sin(G)*A;X.lineTo(H+x,H+y);D.push([H+x,H+y])}X.closePath();X.stroke();
for(j=0;j<D.length;j++){x=D[j][0],y=D[j][1],q=D[(j+1)%S][0]-x,w=D[(j+1)%S][1]-y;O(X,x,y,P);for(k=0;k<R-1;k++)O(X,x+=q/R,y+=w/R,P)}
}break}}}
</script></body>
```
This is [working jsfiddle](http://jsfiddle.net/Snack/6msm1fxf/) example, and ungolfed source. It gets input from `prompt()`. You can adjust output size by adjusting `sz = 300`, and dot size by `pt = 3` (in pixels).
## Example (31 dots)




[Answer]
# Python - ~~189, 258, 251, 249, 239, 222~~ 219
```
from pylab import*
m=input()-1;R=arange
for j in R(1,m):
i=2.*m/(j*j+j);f=2*pi/i
if i%1==0:
figure();axis('equal')
for r in R(j+1):o=f*R(i);s=R(r+1)[:,None];t=r-s;plot(t*cos(o)+s*cos(o+f),t*sin(o)+s*sin(o+f),'.-')
```
**Example output for n = 31:**
(Not sure if the first one is valid...)





[Answer]
## HTML5 + JS (378 364 chars)
```
<script>P='<svg><path stroke=red fill=none d='
C=''
N=prompt()-1
M=Math
for(i=t=1;N>t*2;t+=i)for(r=148/i,j=++i;N%t<1&&j--;)for(A=2*M.PI*t/N,y=150,x=j*r+310*i,P+='M'+x+','+y,a=s=0;s<N;s+=t)for(a+=A,k=-!j;k++<j;P+='L'+x+','+y,C+='<circle fill=red r=2 cx='+x+' cy='+y+' />')if(j)x+=(M.cos(a)-M.cos(a-A))*r,y+=(M.sin(a)-M.sin(a-A))*r
document.write(P+' />'+C)</script>
```
[Online demo](http://jsfiddle.net/9cptmo71/9/). Sorry about the long line, but it cannot be split without increasing the character count. Every semicolon which could be replaced by a newline courtesy of JavaScript's semicolon insertion has been replaced. Every space character is inside a string literal.
As with my [previous "drawing in HTML" answer](https://codegolf.stackexchange.com/a/11417/194), SVG is slightly shorter than canvas.
Since the question doesn't say anything about positioning, I've saved a couple of characters by not guaranteeing that the diagrams will be evenly spaced.
[Answer]
# BBC BASIC, 281 ASCII characters, tokenised filesize 236
Emulator at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html>
Newlines are required and included in the score.
```
c=400INPUTa:n=1t=0REPEATt+=n:s=(a-1)/t:r%=c/n/2CLS:MOVEc,c:s%=s:IFs%=s u=r%*2:v=0FORp=1TOs%q%=r%*COS(p/s%*2*PI)x=q%*2q%=r%*SIN(p/s%*2*PI)y=q%*2q=FNt(n)u=x:v=y:NEXT:q=GET
n+=1UNTILs<=3END
DEFFNt(d)PLOT153,8,0MOVEBY-8,0IFd MOVEBY u,v:q=FNt(d-1)DRAWBY x-u,y-v:q=FNt(d-1)MOVEBY-x,-y
=0
```
A centered `s`-gonal number is of the form `(triangular number t[n])*s+1`. I take an input `a`, then iterate through the triangular numbers until a-1 is not greater than `3*t[n]`. If `s` is an integer, we clear the screen and plot the drawing. After plotting, we wait for the user to press a key (the screen will be cleared again for the next drawing if there is one.) To check if `s` s an integer, we store it in an integer variable `s%` (integer variables are identified by the `%` suffix) and compare the two. In this program I use casting to integer variables several times as a means of converting reals to integers.
The polygon is plotted wedge by wedge. The radial vectors for the first two points `(u,v)` and `(x,y)` are calculated. All the code for this must be on the same line as the IF statement. Unfortunately the resolution of the plotting of this BBC basic emulator is only to the nearest multiple of 2, so in order to avoid problems we ensure that the vector parameters are multiples of 2 (by storing the values of the trig calculations in an integer variable `q%` then multiplying by 2. (the vectors themselves are real variables, to save characters.) There is also a variable `q` which serves only to accept return values of functions (required for syntax reasons.)
In order to avoid trying to do too much in the first `IF` statement, it is natural to put the plotting operation in a function, and having done that it may as well be recursive. The function plots the wedge as a binary tree with overlapping branches. This is short, but highly inefficent (exponential time in number of rings.) With the largest sizes some points are plotted literally millions of times. The worst case is 976, where there are 25 triangular rings, which is expected to take several hours to run :-) This only happens for a very small number of inputs and is fixable for a few extra characters (currently 15) but I don't see speed as essential to the rules.
**Ungolfed Code**
```
c=400 :REM Approx half the height of the screen area
INPUTa
n=1 :REM Number of rings
t=0 :REM t=triangular number n
REPEAT
t+=n :REM Update t to the next triangular number
s=(a-1)/t :REM Number of sides of polygon
r%=c/n/2 :REM Choose a good length for (half)the radius of the first ring.
CLS:MOVEc,c :REM Clear screen and move graphics cursor to middle
s%=s :REM Store the number of sides in an integer variable
IFs%=s :REM If real variable and integer variable are equal (all the following indent MUST be on the same line as the IF)
u=r%*2:v=0: :REM initialise (u,v) to 360 deg.
FORp=1TOs%: :REM Loop through the sides.
q%=r%*COS(p/s%*2*PI): :REM Calculate x/2, assign to integer variable
x=q%*2: :REM assign to x, ensuring x is a multiple of 2.
q%=r%*SIN(p/s%*2*PI): :REM ditto y.
y=q%*2: :REM ditto y.
q=FNt(n): :REM Plot the wedge from n down to 0 (the first row is the centre dot, which will be overdrawn s times)
u=x:v=y: :REM Reinitialise u and v with the last values of x and y
NEXT: :REM in order to plot the next wedge.
q=GET :REM Allow user to view output, wait for keypress.
n+=1 :REM increment n ready to try the next triangular number
UNTILs<=3 :REM If number of sides already <=3
END :REM exit program.
DEFFNt(d) :REM BBC basic puts the nut & bolt functions at the end!
PLOT153,8,0:MOVEBY-8,0 :REM Draw a filled circle radius 8 centred at the current graphics cursor position. After drawing, return cursor to centre of circle.
IFd :REM if this is not the final iteration (all the following indent MUST be on the same line as the IF)
MOVEBY u,v: :REM move to the point where the first circle of the next ring is to be drawn
q=FNt(d-1): :REM draw the circle and the rest of the branch
DRAWBY x-u,y-v: :REM draw the concentric line to the second circle of the next ring
q=FNt(d-1): :REM draw the circle and the rest of the branch
MOVEBY-x,-y :REM return cursor to where it was before calling the function
=0 :REM supply a return value to exit the function.
```
**Output, 31 dots**
I know the dots are small, but that comes in handy for the larger numbers.

[Answer]
# Python 2.7.6, 272 bytes
I'm still learning python, so I'm sure there is more room to golf this. This is more of a challenge to myself than a competitive entry:
```
from turtle import*
from math import*
def f(n):pu();fd(20*n);pd()
P=input()
for n in range(2,P):
a=2*P-2;b=n*n-n;m=a/b
if a%b==0:
f(n);dot(5)
for r in range(1,n):
f(1);rt(90-180/m)
for s in [1]*m:
rt(360/m)
for t in [1]*r:dot(5);fd(40*sin(pi/m))
lt(90-180/m)
```
Add `exitonclick()` to the end if you want the display to stay open after rendering.
Output for input of 31:

] |
[Question]
[
The goal is to calculate the output speed of a series of cogs. The winner will be chosen by popular vote.
The arrangement of cogs is defined in an ASCII-art string:
>
> `O` large cog
>
> `o` medium cog
>
> `*` small cog
>
> `-` axle (one or more in a row)
>
> `=` chain (one or more in a row)
>
>
>
An example input is:
```
o*-O*==oO
```
>
> `o` medium cog, meshed with `*` small cog, attached by `-` axle to `O` large cog, meshed with `*` small cog, connected by `==` chain to medium cog, meshed with `O` large cog.
>
>
>
The code takes five inputs by command line argument, standard in, or function parameter:
>
> Arrangement
>
> Number of teeth on large cogs
>
> Number of teeth on medium cogs
>
> Number of teeth on small cogs
>
> Left-side speed in teeth per second (+ve is clockwise, -ve is anti-clockwise)
>
>
>
And outputs:
>
> Right-side speed in teeth per second
>
>
>
Interactions between cogs and other components occur as follows:
>
> SL = Speed of left cog
>
> SR = Speed of right cog
>
> TL = Teeth of left cog
>
> TR = Teeth of right cog
>
>
> ### Two meshed cogs
>
>
> `O*`
>
> SR = -SL
>
>
> ### Two cogs connected by a chain of any length
>
>
> `O===*`
>
> SR = SL
>
>
> ### Two cogs connected by an axle of any length
>
>
> `O---*`
>
> SR = SL \* TR / TL
>
>
>
Any invalid arrangement can throw an error or return 0.
## Test Cases
```
arrangement O o * speed => speed
*-Oo-O 50 30 10 3.0 => -25.0
o*-O*==oO 50 30 10 -3.0 => 15.0
O---*oO=O*-oo 15 12 8 10.0 => 8.0
=o* 50 30 10 10.0 => error
o*- 50 30 10 10.0 => error
o-=* 50 30 10 10.0 => error
o * 50 30 10 10.0 => error
```
[Answer]
# Javascript – animated version
Playing on with canvas again. Adding a sample going far out of the scope of the task. But, anyhow, here it is. It is an animated / paint version.
### *Issues*
Can be a resource hog. In some quick tests it runs best in Chrome, worse in Opera and worst in Firefox. There is also an issue with movement as on relatively high speeds as the turn on each frame gets too big.
If one use small value for *Teeth Width*, it performs OK in various cases. *Decor* also has an impact.
By choice the use of *Animation Frame* or *interval* can be selected, and while using *interval* frames per second (FPS) can be tweaked. FPS can easily be lower then set if painting one frame takes longer.
If it only hogs, one can also use it to simply paint still images. Press *Stop* button and enter string to be parsed. With full decor it can be for a nice picture ;)
[Try it out in this Fiddle.](http://jsfiddle.net/Ifnak/7sRhH/embedded/result/)

Javascript code:
*It could definitively have been tidied up some more and refactored.*
`requestAnimationFrame` *polyfill* removed in this post due to limit of body length on SO.
```
var PI = Math.PI,
P2 = PI*2,
cos = Math.cos,
sin = Math.sin;
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isNumbers(a) {
var i;
for (i = 0; i < a.length; ++i)
if (!isNumber(a[i]))
return 0;
return 1;
}
function CogWheels() {
this.can = document.getElementById('can');
this.ctx = this.can.getContext("2d");
this.cm = {
main:{can: document.createElement('CANVAS'),ok:0}
//gear:{can: document.createElement('CANVAS'),ok:0}
};
this.cm.main.ctx = this.cm.main.can.getContext("2d");
this.ofs = {x:10, y:50};
this.grect = null;
this.parts = [];
this.pix = {wheel:[],axle:[],chain:[]};
this.sz = {rb:100, rm:75, rs:50};
this.dir = 1;
this.last = null;
this.tw = 4;
this.tl = this.tw + 1;
this.navcr = 7.5;
this.tsp = null; // Timestamp previus frame
this.raf = 0; // Use requestAnimationFrame
this.mode = 0; // 1=Auto start
this.decor = 3; // Decoration level
this.shade = 1; // Use shading
this.pin = 1; // Paint "pin"
this.clr = {
wheel: '#321',
axle : '#852',
chain: '#842',
axis : '#a50',
teeth: '#1a1108',
pin : '#f00',
dec1 : '#321'
};
}
var CW = CogWheels.prototype;
CW.getShadow = function() {
return {
x:this.ctx.shadowOffsetX,
y:this.ctx.shadowOffsetY,
b:this.ctx.shadowBlur,
c:this.ctx.shadowColor.match(/\((.*)\)/)[1]
};
};
CW.setShadow = function(p) {
this.ctx.shadowOffsetX = p.x || 0;
this.ctx.shadowOffsetY = p.y || 0;
this.ctx.shadowBlur = p.b || 5;
this.ctx.shadowColor = p.c ? "rgba("+p.c+")" : "rgba(0,0,0,.8)";
};
CW.noShadow = function() {
this.setShadow({x:0, y:0, b:0, c:"0,0,0,0"});
};
/*
* Drawings for static buffer.
*
* * */
CW.drawBulb = function(x, y, r) {
var gradient = this.ctx.createRadialGradient(x, y, 0, x, y, r);
gradient.addColorStop(1.00, 'rgba(0, 0, 0, 0)');
gradient.addColorStop(0.95, 'rgba(40, 40, 40, 1)');
gradient.addColorStop(0.85, 'rgba(85, 85, 85, 1)');
gradient.addColorStop(0.70, 'rgba(170, 170, 170, 1)');
gradient.addColorStop(0.40, 'rgba(250, 250, 250, 1)');
gradient.addColorStop(0.00, 'rgba(255, 255, 255, 1)');
this.ctx.fillStyle = gradient;
this.ctx.globalCompositeOperation = 'source-over';
this.ctx.fillRect(x - r, y - r, x + r, y + r);
this.ctx.fillStyle = "#000";
};
CW.drawWheel = function(p) {
this.ctx.save();
this.ctx.globalCompositeOperation = 'source-over';
this.ctx.lineWidth = this.tw;
this.ctx.strokeStyle = this.clr.wheel;
this.ctx.moveTo(p.a[0], p.a[1]);
this.ctx.beginPath();
this.ctx.arc(p.a[0], p.a[1], p.r, 0, P2, p.d);
this.ctx.stroke();
if (this.decor > 0 && p.r > 10) {
this.ctx.beginPath();
this.ctx.strokeStyle = '#444';
this.ctx.lineWidth = 1;//0.8;
this.ctx.arc(p.a[0], p.a[1], p.r / 1.15, 0, P2, p.d === 1);
this.ctx.stroke();
}
// Axis
this.ctx.beginPath();
this.ctx.globalCompositeOperation = 'xor';
this.ctx.lineWidth = 1.5;
this.ctx.strokeStyle = this.clr.axis;
this.ctx.arc(p.a[0], p.a[1], this.navcr, 0, P2);
this.ctx.stroke();
this.ctx.restore();
//this.ctx.globalCompositeOperation = 'source-over';
};
CW.drawLinep = function(a) {
this.ctx.beginPath();
this.ctx.moveTo(a[0][0], a[0][1]);
this.ctx.lineTo(a[0][2], a[0][3]);
this.ctx.moveTo(a[1][0], a[1][1]);
this.ctx.lineTo(a[1][2], a[1][3]);
this.ctx.stroke();
};
CW.drawAxle = function(p) {
this.ctx.save();
this.ctx.shadowOffsetX = -this.tw/2;
this.ctx.shadowOffsetY = this.tw/2;
this.ctx.globalCompositeOperation = 'source-over';
this.ctx.lineWidth = 2;
this.ctx.strokeStyle = this.clr.axle;
this.drawLinep(p.a);
this.noShadow();
/* Nav left wheel. */
this.ctx.beginPath();
this.ctx.lineWidth = 3;
this.ctx.globalCompositeOperation = 'xor';
this.ctx.arc(p.a[0][0], p.pp[1], this.navcr, 0, P2);
this.ctx.stroke();
/* Nav right wheel. */
this.ctx.beginPath();
this.ctx.arc(p.a[0][2], p.pp[1], this.navcr, 0, P2);
this.ctx.stroke();
this.ctx.restore();
};
CW.drawChain = function(p) {
this.ctx.save();
this.ctx.lineWidth = 2;
this.ctx.strokeStyle = this.clr.chain;
this.ctx.globalCompositeOperation = 'destination-over';
this.ctx.shadowOffsetX = -this.tw/2;
this.ctx.shadowOffsetY = this.tw/2;
this.drawLinep(p.a);
this.ctx.restore();
};
CW.circleTangents = function(x1, y1, r1, x2, y2, r2) {
var d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)),
vx = (x2 - x1) / d,
vy = (y2 - y1) / d,
s1, s2, c, h,
nx, ny, a, re = [], i = 0;
for (s1 = 1; s1 >= -1; s1 -= 2) {
c = (r1 - s1 * r2) / d;
if (c*c > 1.0)
continue;
h = Math.sqrt(Math.max(0.0, 1.0 - c * c));
for (s2 = 1; s2 >= -1; s2 -= 2) {
nx = vx * c - s2 * h * vy;
ny = vy * c + s2 * h * vx;
a = [];
a[0] = x1 + r1 * nx;
a[1] = y1 + r1 * ny;
a[2] = x2 + s1 * r2 * nx;
a[3] = y2 + s1 * r2 * ny;
re[i++] = a;
}
}
return re;
};
/*
* Paint gear base to static buffer.
*
* */
CW.drawStatic = function() {
var sh;
if (this.cm.main.ok) {
sh = this.getShadow();
this.noShadow();
this.ctx.drawImage(
this.cm.main.can,
this.cm.main.x,
this.cm.main.y
);
this.setShadow(sh);
return;
}
};
CW.genStatic = function() {
var i, e,
p = this.parts,
ix = this.pix;
this.ctx.save();
if (this.shwheel) {
for (i = 0; i < ix.wheel.length; ++i) {
e = p[ix.wheel[i]];
this.drawBulb(e.a[0], e.a[1], e.r);
}
}
for (i = 0; i < ix.wheel.length; ++i) {
this.drawWheel(p[ix.wheel[i]]);
//setTimeout(this.drawWheel.bind(this, p[ix.wheel[i]]), (tt+=500));
}
for (i = 0; i < ix.axle.length; ++i) {
this.drawAxle(p[ix.axle[i]]);
//setTimeout(this.drawAxle.bind(this, p[ix.axle[i]]), (tt+=500));
}
for (i = 0; i < ix.chain.length; ++i) {
this.drawChain(p[ix.chain[i]]);
//setTimeout(this.drawChain.bind(this, p[ix.chain[i]]), (tt+=500));
}
for (i = 0; i < p.length; ++i) {
this.ctx.globalCompositeOperation = 'source-over';
this.ctx.strokeSyle = "#000";
this.ctx.font="10px sans-serif";
if (this.navcr > 10)
this.ctx.fillText(i, p[i].pp[0], p[i].pp[1]);
else if (p[i].w === 'wheel')
this.ctx.fillText('x', p[i].pp[0], p[i].pp[1]);
}
this.cm.main.can.width = this.grect.w - this.ofs.x + 20;
this.cm.main.can.height = this.br * 2 + 40;
// Could have painted directly on memory canvas, but due to coordinates
// and post-implementation of memory canvas, it is here for now.
this.cm.main.ctx.drawImage(
this.can, // image
0, // dx
0, // dy
this.grect.w - this.ofs.x, // dw
this.br * 2 + 60, // dh WHY 60 HERE ????
-this.ofs.x + 20, // sx
-this.ofs.y + 20, // sy
this.grect.w - this.ofs.x , // sw
this.br * 2 + 60 // sh WHY 60 HERE ????
);
this.cm.main.x = this.ofs.x - 20;
this.cm.main.y = this.ofs.y - 20;
this.cm.main.ok = 1;
this.ctx.restore();
};
/*
* Drawings for moving parts.
*
* * */
CW.spikes = function(x1, y1, spikes, r0, r1, skew_0, skew_1, con) {
var t = PI / 2 * 3,
x = x1,
y = y1,
step = PI / spikes,
i, r2 = con ? r1 - 10 : r1;
this.ctx.beginPath();
this.ctx.moveTo(x1, y1 - r0);
for (i = 0; i < spikes; ++i) {
x = x1 + cos(t)*r0;
y = y1 + sin(t)*r0;
this.ctx.lineTo(x, y);
if (skew_0) {
t += step / 2;
x = x1 + cos(t)*r0;
y = y1 + sin(t)*r0;
this.ctx.lineTo(x, y);
t += (step - step/2);
} else {
t += step;
}
if (skew_1) {
x = x1 + cos(t - step/18) * r2;
y = y1 + sin(t - step/18) * r2;
this.ctx.lineTo(x, y);
if (con) {
x = x1 + cos(t - step/8) * r1;
y = y1 + sin(t - step/8) * r1;
this.ctx.lineTo(x, y);
x = x1 + cos(t + step/8) * r1;
y = y1 + sin(t + step/8) * r1;
this.ctx.lineTo(x, y);
}
x = x1 + cos(t + step/18) * r2;
y = y1 + sin(t + step/18) * r2;
this.ctx.lineTo(x, y);
} else {
x = x1 + cos(t) * r1;
y = y1 + sin(t) * r1;
this.ctx.lineTo(x, y);
}
if (skew_0) {
t += step / 2;
x = x1 + cos(t)*r0;
y = y1 + sin(t)*r0;
this.ctx.lineTo(x, y);
t += step - step/2;
} else {
t += step;
}
}
this.ctx.lineTo(x1, y1 - r0);
this.ctx.stroke();
this.ctx.closePath();
};
CW.drawTeeth = function(p) {
var i, th = p.h, x, y;
for (i = 0; i < p.t; ++i) {
x = p.pp[0] + p.r * cos(th);
y = p.pp[1] + p.r * sin(th);
this.ctx.moveTo(x, y);
this.ctx.lineTo(x + cos(th) * this.tl, y + sin(th) * this.tl);
th += p.thi;
}
return th;
};
CW.drawPin = function(p) {
var x = p.pp[0] + p.r * cos(p.h),
y = p.pp[1] + p.r * sin(p.h);
this.ctx.moveTo(
p.pp[0] + (this.navcr) * cos(p.h),
p.pp[1] + (this.navcr) * sin(p.h)
);
this.ctx.lineTo(x + cos(p.h) * this.tl, y + sin(p.h) * this.tl);
};
CW.drawDecor1 = function(p) {
var i, x, y,
th = p.h,
dd = p.r / 1.15 * 0.63,
rr = (p.r / this.spk) * 1.125;
this.ctx.strokeStyle = this.clr.dec1;
this.ctx.lineWidth = 2;
this.ctx.globalCompositeOperation = 'source-over';
for (i = 0; i < this.spk; ++i) {
x = p.pp[0] + dd * cos(th);
y = p.pp[1] + dd * sin(th);
this.ctx.moveTo(x, y);
this.ctx.beginPath();
this.ctx.arc(x, y, rr, 0, P2);
this.ctx.stroke();
th += PI/this.spk*2;
}
//return th;
};
CW.drawDecor2 = function(p) {
var theta = p.h;
this.ctx.save();
this.ctx.translate(p.pp[0], p.pp[1]);
this.ctx.rotate(theta - (PI / 2 * 3));
if (this.shade)
this.setShadow({c:"12,17,23,1",b:17, x:-2, y:2});
this.ctx.lineWidth = 2;
if (this.star)
this.spikes(0, 0, this.spk, p.r / 6 /*this.navcr*/, p.r / 1.19);
else if (p.r > 50)
this.spikes(0, 0, this.spk, p.r / 6 /*this.navcr*/, p.r / 1.15, 1, 1, 1);
else
this.spikes(0, 0, this.spk, p.r / 6 /*this.navcr*/, p.r / 1.19, 1, 1);
this.ctx.restore();
};
CW.drawAnim = function(tt) {
var i, j,
p = this.parts,
ix = this.pix,
sh = this.getShadow();
this.ctx.save();
if (this.decor > 1) {
for (i = 0; i < ix.wheel.length; ++i) {
if (p[ix.wheel[i]].r < this.navcr * 2)
continue;
if ((this.decor === 2 || this.decor > 3))
this.drawDecor1(p[ix.wheel[i]]);
if ((this.decor > 2))
this.drawDecor2(p[ix.wheel[i]]);
}
}
this.ctx.lineWidth = this.tw;
this.noShadow();
if (this.pin) {
this.ctx.beginPath();
this.ctx.strokeStyle = this.clr.pin;
this.ctx.globalCompositeOperation = 'darker';
for (i = 0; i < ix.wheel.length; ++i)
this.drawPin(p[ix.wheel[i]]);
this.ctx.stroke();
}
this.ctx.globalCompositeOperation = 'destination-over';
this.ctx.strokeStyle = this.clr.teeth;
this.ctx.beginPath();
for (i = 0; i < ix.wheel.length; ++i) {
j = ix.wheel[i];
this.drawTeeth(p[j]);
p[j].h += p[j].s * tt * p[j].d;
}
this.ctx.stroke();
this.setShadow(sh);
this.ctx.restore();
};
/*
* Build functions.
*
* * */
CW.add = function(a) {
var e = {
w: a.type,
r: a.rad,
s: a.speed,
d: this.dir,
h: a.theta,
};
if (a.type === 'wheel') {
if (this.last === 'wheel')
this.dir = -this.dir;
e.t = a.teeth;
e.d = this.dir;
// Theta increment
e.thi = PI / a.teeth * 2;
} else if (a.type === 'axle' || a.type === 'chain') {
e.t = 30;
} else {
// Throw error
return null;
}
e.hs = e.h; // Starting angle
this.last = a.type;
this.parts.push(e);
this.grect.w += e.r * 2 + this.tl * 2;
return this;
};
/*
* Various calculations that is the same for each frame.
*
* */
CW.postBuild = function() {
var i,
x1 = this.ofs.x, x2,
y1 = this.ofs.y + this.br, y2,
p = this.parts,
c = this.navcr,
a, d, txl = this.navcr > 10 ? 5 : 15,
tf = this.tw < 2 ? 2 : 3;
this.ctx.textBaseline = "middle";
this.ctx.fillText("tps:", 2, this.grect.h + txl);
txl += 20;
this.ctx.fillText("Hz:", 2, this.grect.h + txl);
txl -= 10;
this.ctx.textAlign = "center";
for (i = 0; i < p.length; ++i) {
if (p[i].w === 'wheel') {
x1 += p[i].r;
p[i].a = [x1, y1];
p[i].tps = (1 / ((P2 / p[i].t) / p[i].s) * p[i].d).toFixed(1);
if (this.navcr <= 10)
this.ctx.fillText(i, x1, this.grect.h + 5);
this.ctx.fillText(p[i].tps, x1, this.grect.h + txl);
this.ctx.fillText((Math.abs(p[i].tps)/p[i].t).toFixed(tf) ,
x1, this.grect.h + txl + 20);
this.pix.wheel.push(i);
} else if (p[i].w === 'axle') { // AXLE
x1 -= p[i-1].r + c;
x2 = x1 + p[i-1].r + c + p[i].r*2 + c + p[i + 1].r;
a = [];
// Left - right nav, top
a[0] = [x1, y1 - c, x2, y1 - c];
// Left - right nav, bottom
a[1] = [x1, y1 + c, x2, y1 + c];
p[i].a = a;
// Real center + radius
d = x2 - x1;
p[i].cc = [(x1+x2)/2, y1, d / 2];
p[i].t = d * 2 / this.tw;
x1 += p[i - 1].r + c + p[i].r;
this.pix.axle.push(i);
} else if (p[i].w === 'chain') { // CHAIN
x1 -= p[i-1].r + c;
x2 = x1 + p[i-1].r + c + p[i].r*2 + c + p[i + 1].r;
y2 = y1 - p[i+1].r - c ;
p[i].a = this.circleTangents(x1, y1, p[i-1].r, x2, y1, p[i+1].r);
x1 += p[i - 1].r + c + p[i].r;
this.pix.chain.push(i);
}
p[i].pp = [x1, y1];
x1 += p[i].r + c;
}
document.getElementById('tps_e').value = p[--i].tps;
};
/*
*
* @a Arrangement
* @tb Teeth O wheel
* @tm Teeth o wheel
* @ts Teeth * wheel
* @tps Teeth per second leftmost wheel
* */
CW.build = function(a, tb, tm, ts, tps) {
var i, w, c,
rb, rm, rs, // Radius
ob, om, os, // Odd/even flag
sp = null, // Speed
pr = '', // Previous
th, // theta
hor = 0, // If last wheel has right most tooth horizontal.
xcw; // Axel / Chain base width.
if (a.match(/^[=-]|[=-]$|-=|=-/))
return 1;
clearInterval(this.iv);
this.tsp = null;
this.parts = [];
this.pix = {wheel:[],axle:[],chain:[]};
this.imgm = 0;
//this.ctx.clearRect(0, 0, this.can.width, this.can.height);
this.can.width = this.can.width;
this.spk = parseInt(document.getElementById('spikes').value);
this.tw = parseFloat(document.getElementById('teeth_w').value);
if (!isNumbers([tb, tm, ts, tps, this.tw, this.spk]))
return 1;
if (tb < 1 || tm < 1 || ts < 1 /*|| tps === 0*/ || this.tw <= 0)
return 1;
this.tl = this.tw + 2;
this.navcr = this.tl * 1.5;
xcw = this.tl * 2;
this.sz.rb = rb = this.tw * tb / PI;
this.sz.rm = rm = this.tw * tm / PI;
this.sz.rs = rs = this.tw * ts / PI;
// Biggest radius
this.br = rb > rm ? rb : rm;
if (rs > this.br)
this.br = rs;
ob = tb % 2;
om = tm % 2;
os = ts % 2;
// Offset x:left, y:center first wheel
this.ofs = {
x: this.tl * 3,
y: /*this.br +*/ 50
};
// Repaint rectangle
this.grect = {
w: this.ofs.x,
h: this.br * 2 + 100
};
this.dir = tps > 0 ? 1 : -1;
tps = Math.abs(tps);
this.last = null;
for (i = 0; i < a.length; ++i) {
th = 0;
switch ((c = a.charAt(i))) {
case 'O':
if (sp === null) {
sp = (P2 / tb) * tps;
} else if (pr === 'o') {
sp = sp / rb * rm;
} else if (pr === '*') {
sp = sp / rb * rs;
}
// ODD + HOR = no skew
// If odd result is skew
if ((hor && ob) || (!hor && !ob)) {
hor = 1;
} else {
th = this.tw / rb;
hor = 0;
}
this.add({type:'wheel', rad:rb, teeth:tb, speed:sp, theta:th});
break;
case 'o':
if (sp === null) {
sp = (P2 / tm) * tps;
} if (pr === 'O') {
sp = sp / rm * rb;
} else if (pr === '*') {
sp = sp / rm * rs;
}
if ((hor && om) || (!hor && !om)) {
hor = 1;
} else {
th = this.tw / rm;
hor = 0;
}
this.add({type:'wheel', rad:rm, teeth:tm, speed:sp, theta:th});
break;
case '*':
if (sp === null) {
sp = (P2 / ts) * tps;
} if (pr === 'O') {
sp = sp / rs * rb;
} else if (pr === 'o') {
sp = sp / rs * rm;
}
if ((hor && os) || (!hor && !os)) {
hor = 1;
} else {
th = this.tw / rs;
hor = 0;
}
this.add({type:'wheel', rad:rs, teeth:ts, speed:sp, theta:th});
break;
case '-':
for (w = 1; a.charAt(i + 1) === '-'; ++i, ++w)
;
this.add({type:'axle', rad:w * xcw, speed:sp, theta:th});
hor = 1;
break;
case '=':
for (w = 1; a.charAt(i + 1) === '='; ++i, ++w)
;
this.add({type:'chain', rad: w * xcw, speed:sp, theta:th});
hor = 1;
break;
default:
this.parts = [];
return 1;
}
if (c !== '=')
pr = a.charAt(i);
}
if (!this.parts.length)
return 1;
// Hack to prevent stray borders in page.
this.can.style.display = 'none';
this.can.width = this.can.width + 50;
this.can.width = this.grect.w;
this.can.height = this.grect.h + 50;
this.can.style.display = 'block';
this.postBuild();
if (this.shade) {
//this.setShadow({x:-1,y:1,b:13});
this.setShadow({c:"0,0,0,.6", x:-4, y:4, b:13});
this.setShadow({c:"0,0,0,.8", x:0, y:0, b:this.tw*2});
//this.ctx.shadowBlur = 17;
} else {
this.ctx.shadowBlur = 0;
}
this.genStatic();
this.step();
};
/*
* Runtime functions.
*
* * */
CW.tick = function(tt) {
this.ctx.clearRect(0, 0, this.grect.w, this.grect.h);
this.noShadow();
this.ctx.textAlign = "left";
this.ctx.fillText("F: " + tt, 15, 15);
this.ctx.textAlign = "center";
if (this.shade) {
this.setShadow({c:"0,0,0,.8",x:0,y:0,b:this.tw*2});
}
this.drawStatic();
this.drawAnim(tt);
};
CW.step = function () {
if (this.parts.length)
this.tick((1/this.fps).toFixed(3));
};
CW.run_raf = function(ts) {
if (this.tsp === null) {
this.tsp = ts;
}
this.tsp = ts - this.tsp;
this.tick(this.tsp/1000);
requestAnimationFrame(this.run.bind(this));
this.tsp = ts;
};
CW.run_iv = function() {
var ts, that = this, ic = this.fps;
this.tsp = +Date.now();
this.iv = setInterval(function() {
ts = +Date.now() - that.tsp;
that.tsp = +Date.now();
that.tick(ts/1000);
if (ic !== that.fps) {
clearInterval(that.iv);
that.run_iv();
}
}, 1000 / this.fps);
};
CW.stop = function () {
clearInterval(this.iv);
this.mode = 0;
};
CW.run = function () {
this.stop();
if (!this.parts.length)
return this.ui_build_run;
this.mode = 1;
this.raf = !document.getElementById('run_iv').checked;
if (this.raf)
requestAnimationFrame(this.run_raf.bind(this));
else
this.run_iv();
};
/*
* UI functions
*
* * */
CW.ui_build = function() {
if (this.build(
document.getElementById('arr').value,
+document.getElementById('teeth_b').value,
+document.getElementById('teeth_m').value,
+document.getElementById('teeth_s').value,
+document.getElementById('tps_1').value
))
return 1;
};
CW.ui_build_run = function() {
if (this.ui_build())
return 1;
if (this.mode > 0)
this.run();
};
/*
* This should have been refactored.
* * */
CW.ui_init = function() {
var i, cw = this,
e = document.getElementById('fps'),
fv = document.getElementById('fpsv'),
dv = document.getElementById('decorv');
this.fps = +e.value;
fv.innerHTML = this.fps.toFixed(1);
e.addEventListener('change', function(e) {
cw.fps = parseFloat(e.target.value);
fv.innerHTML = cw.fps.toFixed(1);
});
e = document.getElementById('decor');
this.decor = +e.value;
dv.innerHTML = this.decor;
e.addEventListener('change', function(e) {
cw.decor = parseInt(e.target.value);
dv.innerHTML = cw.decor;
cw.ui_build_run();
});
e = document.getElementById('pin');
this.pin = !!e.checked;
e.addEventListener('change', function(e) {
cw.pin = e.target.checked;
cw.ui_build_run();
});
e = document.getElementById('shadow');
this.shade = !!e.checked;
e.addEventListener('change', function(e) {
cw.shade = e.target.checked;
cw.ui_build_run();
});
e = document.getElementById('shwheel');
this.shwheel = !!e.checked;
e.addEventListener('change', function(e) {
cw.shwheel = e.target.checked;
cw.ui_build_run();
});
e = document.getElementById('star');
this.star = !!e.checked;
e.addEventListener('change', function(e) {
cw.star = e.target.checked;
cw.ui_build_run();
});
e = document.getElementById('run_iv');
cw.raf = !e.checked;
document.getElementById('build').addEventListener(
'click', cw.ui_build.bind(cw));
document.getElementById('stop').addEventListener(
'click', cw.stop.bind(cw));
document.getElementById('step').addEventListener(
'click', cw.step.bind(cw));
document.getElementById('run').addEventListener(
'click', cw.run.bind(cw));
e = document.getElementsByTagName('INPUT');
for (i = 0; i < e.length; ++i) {
if (e[i].type === 'text') {
e[i].addEventListener('keyup', cw.ui_build_run.bind(cw));
} else if (e[i].type === 'radio') {
e[i].addEventListener('change', cw.ui_build_run.bind(cw));
}
}
};
document.addEventListener("DOMContentLoaded", function () {
var cw = new CogWheels();
cw.ui_init();
cw.ui_build_run();
});
```
[Answer]
# Julia
```
chain(s) = all((c)->c=='=',s)
axle(s) = all((c)->c=='-',s)
direct(s) = s==""
function mechanical(arrangment,O,o,x,speed_l)
teeth = {"O"=>O, "o"=>o, "*"=>x}
process(c) = direct(c[2]) ? -1 : chain(c[2]) ? 1 : axle(c[2]) ? teeth[c[3]]/teeth[c[1]] : 0
matches = collect(eachmatch(r"([Oo*])([-=]*)([Oo*])",arrangment,true))
length(matches) == 0 ? 0 : speed_l*prod([process(m.captures) for m in matches])
end
# test cases
println(mechanical("*-Oo-O",50,30,10,3))
println(mechanical("o*-O*= =oO",50,30,10,-3))
println(mechanical("O---*oO=O*-oo",15,12,8,10))
println(mechanical("O *",50,30,10,10))
```
Gives correct output. `r"stuff"` is a regex.
[Answer]
# Java
```
import java.util.Scanner;
/**
*
* @author Quincunx
*/
public class MechanicalCoding {
final static int[] teeth = new int[3];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input the arrangement:");
String layout = scan.nextLine();
System.out.println("Input the:");
System.out.print("\tNumber of teeth on large gear:\n\t");
teeth[2] = scan.nextInt();
scan.nextLine();
System.out.print("\tNumber of teeth on medium gear:\n\t");
teeth[1] = scan.nextInt();
scan.nextLine();
System.out.print("\tNumber of teeth on small gear:\n\t");
teeth[0] = scan.nextInt();
scan.nextLine();
System.out.println("Input the speed of the left hand side:");
double speed = scan.nextDouble();
layout = layout.replaceAll("([-=])+", "$1");
char lastC = ' ';
boolean mustBeNext = false;
for (char c : layout.toCharArray()){
switch (c){
case 'O':
case 'o':
case '*':
if (lastC == '=' || lastC == ' '){
break;
}
if (lastC == '-'){
speed *= 1.*teeth(c)/teeth(lastC);
break;
}
speed *= -1;
break;
case '-':
case '=':
default:
if (lastC == ' '){
System.exit(1);
}
}
lastC = c;
}
if (lastC == '-' || lastC == '='){
System.exit(1);
}
System.out.println(speed);
}
public static int teeth(char c){
return teeth[c=='O'?2:c=='o'?1:0];
}
}
```
What a relief to be able to use Java! Sample run:
```
Input the arrangement:
o*-O*==oO
Input the:
Number of teeth on large gear:
50
Number of teeth on medium gear:
30
Number of teeth on small gear:
10
Input the speed of the left hand side:
-3.0
15.0
```
[Answer]
## C#, 396 bytes
Golfed for fun with added indentation. I'm sure the same code would be smaller in a loosely-typed language.
```
namespace System.Text.RegularExpressions{
class P{
static void Main(string[]a){
var s=Regex.IsMatch(a[0],"^[-=]|[-=]$|-=|=-|[^-=Oo*]")?0:double.Parse(a[4]);
foreach(Match m in Regex.Matches(a[0],"[Oo*]{2,}"))
s*=m.Length%2*2-1;
foreach(Match m in Regex.Matches(a[0],"[Oo*]-+[Oo*]"))
s*=double.Parse(a[" Oo*".IndexOf(m.Value[m.Length-1])])/double.Parse(a[" Oo*".IndexOf(m.Value[0])]);
Console.Write(s);
}
}
}
```
[Answer]
# 159 Bytes - Javascript
This uses ECMAScript 6 Features so will only work in browsers that support those - Firefox is one.
```
(g,l,m,s,v,n)=>{for(a={'O':l,'o':m,'*':s};n!=g&&(n=g);g=g.replace(/[Oo*](-*|=*)([Oo*])/,(w,y,z)=>((v*=y?(y[0]=='='?1:a[z]/a[w[0]]):-1)-v)||z));return a[g]?v:0}
```
Defines an anonymous function that takes the parameters `arrangement O o * speed` and returns the speed of the last cog for a valid arrangement, and zero otherwise.
Can test all test cases in firefox with:
```
[((g,l,m,s,v,n)=>{for(a={'O':l,'o':m,'*':s};n!=g&&(n=g);g=g.replace(/[Oo*](-*|=*)([Oo*])/,(w,y,z)=>((v*=y?(y[0]=='='?1:a[z]/a[w[0]]):-1)-v)||z));return a[g]?v:0}).apply(0,a) for each (a in [['*-Oo-O',50,30,10,3],['o*-O*==oO',50,30,10,-3],['O---*oO=O*-oo',15,12,8,10],['=o*',50,30,10,-3],['o*-',50,30,10,-3],['o-=*',50,30,10,-3],['o *',50,30,10,-3]])]
```
] |
[Question]
[
Make program that takes the list from the files from STDIN, and aligns it nicely, just like `ls` command from coreutils. For example, assuming the following list (taken [from The ASCII Collab](https://github.com/OddLlama/ascii-gallows-club/blob/master/wordlists/animals.txt), which takes place in the chatroom on this site).
```
alligator
ant
bear
bee
bird
camel
cat
cheetah
chicken
chimpanzee
cow
crocodile
deer
dog
dolphin
duck
eagle
elephant
fish
fly
fox
frog
giraffe
goat
goldfish
hamster
hippopotamus
horse
kangaroo
kitten
leopard
lion
lizard
llama
lobster
monkey
octopus
ostrich
otter
owl
oyster
panda
parrot
pelican
pig
pigeon
porcupine
puppy
rabbit
rat
reindeer
rhinoceros
rooster
scorpion
seal
shark
sheep
shrimp
snail
snake
sparrow
spider
squid
squirrel
swallow
swan
tiger
toad
tortoise
turtle
vulture
walrus
weasel
whale
wolf
zebra
```
Align the results, like the in the example below (the example shows columns set to 80). The terminal width is received as the first argument. If any argument is bigger than this argument, you can do anything. Try to use as many columns as possible with two space separators, as long nothing overflows.
```
alligator crocodile giraffe llama pig shark tiger
ant deer goat lobster pigeon sheep toad
bear dog goldfish monkey porcupine shrimp tortoise
bee dolphin hamster octopus puppy snail turtle
bird duck hippopotamus ostrich rabbit snake vulture
camel eagle horse otter rat sparrow walrus
cat elephant kangaroo owl reindeer spider weasel
cheetah fish kitten oyster rhinoceros squid whale
chicken fly leopard panda rooster squirrel wolf
chimpanzee fox lion parrot scorpion swallow zebra
cow frog lizard pelican seal swan
```
[Answer]
# Bash, ~~48~~ 46 bytes
```
cd `mktemp -d`
xargs -d\\n tee
stty cols $1
ls
```
Guaranteed to work like *ls*.
[Answer]
### GolfScript, 79 characters
```
n%:I{)I/{{,}$-1=,}:L%{2++}*"#{ARGV[0]}"~)<}I,,?)/{.L{:x' '*+x<}+%}%zip{' '*n}/
```
Assumes a two spaces between the columns (although it can be changed easily to one which saves 2 characters).
[Answer]
**Python 3 (394)**
Feels longish, but works and isn't *horrible* to read;
```
import sys,math
f=sys.stdin.read().splitlines()
l,w=len(f),int(sys.argv[1])
for y in range(w,0,-1):
n=math.ceil(l/y)
r=[f[i:l:n]for i in range(0,n)]
c=[max(len(s[i]) if i<len(s) else 0 for s in r) for i in range(y)]
if sum(c)+len(c)*2-2<=w:break
for i in range(len(r)):
s=len(r[i])
for j in range(s):
t=r[i][j]
sys.stdout.write(t+(' '*(c[j]-len(t)+2) if j<s-1 else '\n'))
```
Basically it tries with fewer and fewer columns until they all fit. It will always output at least one column even if the file names won't fit the width.
[Answer]
# BASH, 13 15
```
column -s"\n"-c
```
You can append the column width argument like this:
```
column -s"\n"-c80
```
Reads text from STDIN and aligns it in columns.
[Answer]
## C++11, 409 bytes
```
#include<vector>
#include<iostream>
using namespace std;main(int i,char*a[]){int w=atoi(a[1]),n,c,x,r;int v[w];vector<string>l;string s;while(getline(cin,s))l.push_back(s);n=l.size();for(c=n;c>1;--c){r=n/c+(n%c!=0);for(i=0;i<n;++i)v[i/r]=max((int)l[i].size(),i%r?v[i/r]:0);for(i=x=0;i<c;++i)x+=v[i]+=i<c-1?2:0;if(x<=w)break;}for(i=0;i<n;++i)printf(((i+1)%c&&i<n-1)?"%1$-*2$s":"%s\n",l[i*r%n].c_str(),v[i%c]);}
```
Below is the slightly non-golfed version. If I may point you at something potentially interesting, then please take a look at the silly format strings of the last printf.
```
#include<vector>
#include<iostream>
using namespace std;
main(int i,char*a[]){
int w=atoi(a[1]),n,c,x,r;
int v[w];
vector<string>l;string s;while(getline(cin,s))l.push_back(s);n=l.size();
for(c=n;c>1;--c){
r=n/c+(n%c!=0);
for(i=0;i<n;++i)v[i/r]=max((int)l[i].size(),i%r?v[i/r]:0);
for(i=x=0;i<c;++i)x+=v[i]+=i<c-1?2:0;
if(x<=w)break;
}
for(i=0;i<n;++i)
printf(((i+1)%c&&i<n-1)?"%1$-*2$s":"%s\n",l[i*r%n].c_str(),v[i%c]);
}
```
] |
[Question]
[
Similar to [this](https://codegolf.stackexchange.com/q/769/3121) but in this one you need to write spiral starting from the center where:
* space means composite number
* `.`(dot) means prime number.
Size of the spiral can be given as parameter or on `stdin`. By size I mean side of square NxN and also N will be always odd.
[Answer]
## Python, 219 chars
```
N=input()
A={0:' '}
d=1j
x=1
for p in range(2,N*N+1):
A[x]=' .'[all(p%i for i in range(2,p))]
if abs(x.imag)==abs(x.real):x+=(1-1j)*(d==1);d*=1j
x+=d
R=range(N)
for y in R:print''.join(A[x-N/2+(N/2-y)*1j]for x in R)
```
Works for any odd `N`. For example:
```
$ echo 9 | ./ulam.py
. .
. .
. . .
. . .
. .. .
. .
. .
. .
. .
```
[Answer]
**JavaScript (~~240~~ ~~202~~ ~~195~~ 151 characters)**
Update: Another much smaller version without function (a lot of credits to @mellamokb):
```
for(x=3,e=d=f=a>>1,c=2;(x&1?x&2?++e<a-d:--e>d:x&2?++f<a-d-1:--f>d)||++x&3||d--;c
++)for(g=0;g<2*a*a;z[g+=c]=1)z[c]||z.getContext("2d").fillRect(e,f,1,1)
```
---
Works with this HTML:
```
<script>a = 50</script>
<canvas id=z width=50 height=50></canvas>
```
[25x25 example](http://jsfiddle.net/ngjXZ/) (zoomed in) - [800x800 example](http://jsfiddle.net/VkWVc/)
This new version now performs well and outputs the right size (NxN) for any odd `a`.
Found some small improvements (195 now). Thanks @mellamokb.
---
**[Old version:](http://jsfiddle.net/mpus6/)**
```
c=1;i=e=0;b={};for(d=[];c<a*a;){d.push("");for(i+=e+=2;i--;)d[Math.min(e-2,i)]+=
j();d.unshift("");for(i-=e;++i<e;)d[g=Math.max(0,i)]=j()+d[g]}x.innerHTML=d.join
("\n");function j(){if(f=!b[++c])for(h=c*c;h<2*a*a;h+=c)b[h]=1;return f?".":" "}
```
Currently takes variable `a` as input and outputs to an element with the id `x`:
```
<script>a = 50</script>
<pre id=x>
```
I used the [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) for prime generation, which works really well. Output is quite slow so far though. Don't expect this to run for huge n yet.
[Answer]
## Golfscript - 92 Characters
Based on my answer [here:](https://stackoverflow.com/a/1810756/174728)
```
~.(:S+,:R{S\-:|;R{S-:$|>' .'1/[|$.|]2/@:d|~)$<!^=~:$;:y.*4*$-y-)2d*$y-*+:$,{)$\%!},,2==}%n}%
```
[Answer]
## APL (85)
```
K[R↑+\(1+M-⍨N×M←⌈N÷2),(2/⍳N)/(2×N)⍴1(-N)¯1N]←K←⍳R←N×N←⎕⋄'. '[1+N N⍴K∊P/⍨P∊P∘.×P←1↓⍳R]
```
Explanation:
* Generating the spiral:
+ `K←⍳R←N×N←⎕`: Read N from the user. The array size N×N is stored in R. K is [1..R].
+ `(1+M-⍨N×M←⌈N÷2)`: The coordinate of the middle field.
+ `(2×N)1(-N)¯1N`: the delta coordinates for the next field (i.e. 1 right, up a line (so N fields to the left in a 1-dimensional array), then 1 left, then down a line.
+ `(2/⍳N)/`: duplicate the deltas to form an expanding spiral. 2/⍳N is `1 1 2 2 3 3 ... N N`, duplicating the deltas by these values gives `right up left left down down right right right...`
+ `R↑+\`: sum these values (giving absolute coordinates) and take the first R.
+ `K[`...`]←K`: assign K to K in the order given above. We now have K in spiral order.
* Generating the pattern:
+ `P/⍨P∊P∘.×P←1↓⍳R`: more or less the standard APL idiom for generating primes. P is [2..R], P∘.×P is a multiplication table for P. P∘.P therefore contains all composite numbers in the range [1..R]. P/⍨ then selects from P all values present in P∘.×P, giving a list of composite numbers.
+ `1+N N⍴K∊`: this selects from K all the composite numbers, giving a binary list in spiral order where there's an 1 if the number is composite. Then add 1 so that composite numbers are 2 and noncomposite (prime) numbers are 1. This is formatted as a N by N table.
+ `'. '[`...`]`: prime numbers (1) become `'.'` and composites (2) become `' '`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
UGlYLZp42*cwx
```
[Try it online!](https://tio.run/##y00syfn/P9Q9J9InqsDESCu5vOL/f0sA "MATL – Try It Online")
A clockwise outward spiral which starts from the right.
## Explanation
```
U % convert char matrix to numeric or to general array / square
G % paste from user-input clipboard G
l % array of ones
YL % Create spiral matrix
Zp % is prime / totient function
42 % number literal
* % array product (element-wise, singleton expansion)
c % convert to character array
w % swap elements in stack
x % delete elements
% (implicit) convert to string and display
```
[Answer]
## Python - 203 Characters
Similar to my answer [here:](https://stackoverflow.com/a/1807536/174728)
```
x=input();y=x-1;w=x+y
A=[];R=range;k,j,s,t=R(4)
for i in R(2,w*w):
A+=[(x,y)]*all(i%d for d in R(2,i))
if i==s:j,k=k,-j;s,t=s+t/2,t+1
x+=j;y+=k
for y in R(w):print"".join(" ."[(x,y)in A]for x in R(w))
```
] |
[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/2460/edit)
This one ought to be a little more of a challenge than your normal "compute these numbers" or "print this sequence of text" puzzles:
Write a program that launches another program and when that other program tries to access a certain file the program causes it to open a different file.
Example:
The program launches Notepad.
Notepad attempts to open "orange.txt"
The program detects it and makes notepad open "green.txt" instead.
Rules:
WinAPI is allowed, but your code will stand out better if you can get this some other way.
You can use any language, but it must be able to run on either Windows or Linux
[Answer]
## gdb, 108 chars
```
star
b open if !(int)strcmp(((char**)$esp)[1],"orange.txt")
comm
set((char**)$esp)[1]="green.txt"
c
end
c
q
```
Save as the file `redirect` and run like this:
```
gdb -x redirect <program you want to redirect>
```
Works on x86 (linux at least, and probably Windows/Mac also). Here's what the lines do:
`star` = `start` gets to the beginning of main (needed so `open` is defined for the next step).
`b open if...` = break if we're calling `open` on `orange.txt`
`comm` = `command` the code up to the next `end` is executed when the breakpoint fires.
`set ((char*))...` = replace the `open` argument with `green.txt`
`c`=`continue`
`q`=`quit`
[Answer]
## C - 146
This is based on [an answer to](https://stackoverflow.com/questions/69859/how-could-i-intercept-linux-sys-calls/69884#69884) the StackOverflow question ["how could I intercept linux sys calls?"](https://stackoverflow.com/q/69859/149391).
```
#define r(s)int s(int p,int f,int m)
#define c(s)r(s){return((r((*)))dlsym(-1,#s))(strcmp(p,getenv("OLD"))?p:getenv("NEW"),f,m);}
c(open)c(open64)
```
This has been tested on Linux/x86, and is unlikely to be portable.
### Usage:
```
$ echo orange > orange.txt
$ echo green > green.txt
$ gcc -fPIC -shared -ldl intercept-open.c -o intercept-open.so
$ cat orange.txt
orange
$ LD_PRELOAD="./intercept-open.so" OLD="orange.txt" NEW="green.txt" cat orange.txt
green
```
This works with some programs (e.g. `cat`, `less`, `wc`, `vim`) but not others (e.g. `nano`, `gedit`).
] |
[Question]
[
**This question already has answers here**:
[Perfect powers in more than one way?](/questions/564/perfect-powers-in-more-than-one-way)
(5 answers)
Closed 7 years ago.
A positive number is said to be super power when it is the power of at least two different positive integers. Write a program that lists all super powers in the interval [1, 264) (i.e. between 1 (inclusive) and 264 (exclusive)).
Sample Output
```
1
16
64
81
256
512
.
.
.
18443366605910179921
18444492376972984336
18445618199572250625
```
Constraints:
1. The program should not take more than 10 secs.
2. There are 67385 super powers below 264.
3. The shortest code wins.
[Answer]
# GolfScript 52 characters
```
64,4>{1.{16.?<}{;).2$?}/@.,1>{2$\%*}**!*\;~}%$.&{p}/
```
I golfed this pretty heavily, here is a compilation of midway solutions:
```
;64,4>{.,2>{\.@%}%{*}*!\;},{1.{16.?<}{;).2$?}/]2=}%[]*$0\{.@={}{.p}if}/;
;64,4>{.,2>{\.@%}%{*}*!\;},{1.{16.?<}{;).2$?}/]2=}%[]*$.&{p}/
;64,4>{.,2>{\.@%}%{*}*!\;},{1.{16.?<}{;).2$?}/]2=~}%$.&{p}/
;4.{64<}{;)..,1>{2$\%*}*!*}/0-\;{1.{16.?<}{;).2$?}/]2=~}%$.&{p}/
;64,4>{.,1>{2$\%*}*!*},{1.{16.?<}{;).2$?}/]2=~}%$.&{p}/
;64,4>{.,1>{2$\%*}*{1.{16.?<}{;).2$?}/~}or]2>~}%$.&{p}/
64,4>{.,1>{2$\%*}*!\1.{16.?<}{;).2$?}/\;\;*~}%$.&{p}/
64,4>{1.{16.?<}{;).2$?}/\;\.,1>{2$\%*}*!\;*~}%$.&{p}/
64,4>{1.{16.?<}{;).2$?}/@.,1>{2$\%*}**!*\;~}%$.&{p}/
```
GolfScript seems to have some problem with outputting large arrays, therefore I step through the result array using `{p}/` rather than just inject the needed lineshifts using `n*`.
The first 5 versions work by first generating an array of nonprimes from 4 to 63 (code before `{1.`), then for each element of that list all N^nonprime less than 2^64 is calculated (`1.{16.?<}{;).2$?}/`). Finally the result is sorted, duplicates are removed and the result is output.
In the 6th version the 2 first functions are put in the same loop.
In the 7th version the N^nonprime array is generated no matter if the nonprime is actually a nonprime, the array is then thrown away if needed.
In the 8th and 9th version the order has been switched so the N^nonprime array is generated before nonprime status is asserted.
By the way, a^b where a>0, b>1 and b is nonprime is probably a more programming-friendly way of describing super powers.
[Answer]
## Ruby, ~~97~~ 93 characters
```
puts (r=2..32).map{|j|r.map{|i|(1..2**(64.0/j/i)).map{|a|a**(j*i)}}}.flatten.uniq.sort[0..-2]
```
I'm pretty sure this should be correct.
```
$ time ruby1.9 perfectpower.rb > out
real 0m0.199s
user 0m0.160s
sys 0m0.030s
$ wc -l out
67385 out
$ head -6 out
1
16
64
81
256
512
$ tail -3 out
18443366605910179921
18444492376972984336
18445618199572250625
```
[Answer]
## Python, 107 chars
```
R=range
for x in sorted(set(i**(j*k)for i in R(65536)for j in R(2,32)for k in R(2,64/j)))[1:67386]:print x
```
Takes about 40 seconds on my machine, though.
] |
[Question]
[
Generate \$T=\{T\_1,...,T\_x\}\$, the minimum number of \$k\$-length subsets of \$\{1,...,n\}\$ such that every \$v\$-length subset of \$\{1,...,n\}\$ is a subset of some set in \$T\$
1. Here, \$n > k > v\$ and \$v \ge 2\$
2. Any number can appear only once in 1 set
3. Order of numbers is not important
Answer with code & explanation
## Test Cases
\$(n,k,v) \to output \$
```
(4, 3, 2) -> {1 2 3}
{1 2 4}
{1 3 4}
(10, 6, 3) -> {1 2 3 4 5 7}
{2 3 4 5 6 8}
{3 4 5 6 7 9}
{4 5 6 7 8 10}
{1 5 6 7 8 9}
{2 6 7 8 9 10}
{1 3 7 8 9 10}
{1 2 4 8 9 10}
{1 2 3 5 9 10}
{1 2 3 4 6 10}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œcŒPṚœc€⁵ẎQLƲÞṪ
```
A full program that accepts alphabet size (n), block size (k), and subset size (v) and prints a minimum covering design.
**[Try it online!](https://tio.run/##AS0A0v9qZWxsef//xZNjxZJQ4bmaxZNj4oKs4oG14bqOUUzGssOe4bmq////NP8z/zI "Jelly – Try It Online")**
### How?
Naive brute-force, and about as inefficient as possible!
```
œcŒPṚœc€⁵ẎQLƲÞṪ - Main Link: n, k
œc - k-combinations of [1..n] without repeats
ŒP - powerset
Ṛ - reverse (to be from longest to shortest)
Þ - (stable) sort (these proposed solutions) by:
Ʋ - last four links as a monad:
⁵ - with right argument = third program argument (v)
€ - for each k-tuple in the proposed solution:
œc - v-combinations of the k-tuple
Ẏ - tighten to a list of the covered v-tuples
Q - deduplicate
L - length -> number of distinct v-tuples covered
Ṫ - tail -> i.e. (one of) the shortest valid proposed solution(s)
- implicit print
```
---
#### Aside:
A greedy method of adding the lexicographically first unused block that covers the most so far uncovered subsets gets an optimal covering design *sometimes* and a fairly good alternative (slightly larger number of blocks) other times. Using other orderings (than lexicographic) with the same selection criteria will find optimal coving designs *sometimes* too. See [New Constructions for Covering Designs
(Daniel M. Gordon, Greg Kuperberg, Oren Patashnik)](https://www.dmgordon.org/papers/cover.pdf)
This [Python code](https://tio.run/##lVTLjpswFN3zFVeq1DGqO0o61Swi0VXX7QdMIsTDBGuMjWyTzBTx7enFJhBComm9MH7cc@65D1O/21LJp9Op0KqCTAnBMsuVNMCrWmkLv3XONMt/8swGzoZbpq1SYrTIVJVymThUEAQ5K2DPbJypA9MkEXWZpLg1/A@jkAqVvQ5r06RmuAg3AeA4G0MEOpF7RtYUZgTwBdahM22k42d57GkMYvBDLsWMzue@PMEnZBZeD0YiQbA3nqm9TuqSZ4kA1cdN4chtCbZkcHaD63dwvgcdjUERnie26iwnHuShrIsMEofpB3EIutR8Pr8UHI6wQmmv2Unm5m7AU6IHtJ@dKtT0snPbY8kFW@ZyM/pLmbE@OAT9UpKNN1XyxqtE@DhxbmRfttVSKYXrSqH0j9L2iF1WGRJOSvoh2TFelv365PMyoBkLL7DYktwgC@HHrbjmIu4Hf491AZ9l1X1nJh8l58Xd7BB7w9vI5M4fk7pmMieTx0nN8gl9jf7B98i0G5lyJv4fqJlttByeUhD0/SIpYLscKKjauvxiRvf4/rBhCPlO4YnCN5xDCmS9ovDsTtarfo9rb/AcDk2jmWlEX5bpZzTw@xTUmktLigcZtbLDi6h9xc8hag/dZitbD@@2kngRUduX15@G3bXEqJ3vu3ArH8LgdPoL) does this with the lexicographic ordering - it gets a different, optimal solution for `n=10 k=6 v=3` (also 10 blocks), but a non-optimal one for (for example) `n=6 k=4 v=3` (one too many blocks).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes
```
ɾḋṗṘµ⁰vḋÞfUL;t
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvuG4i+G5l+G5mMK14oGwduG4i8OeZlVMO3QiLCIiLCI0XG4zXG4yIl0=)
Basically a port of Jelly, aka extremely slow.
Explanation coming soon.
[Answer]
# JavaScript (ES10), 188 bytes
Another brute-force solution that is unlikely to solve the second test case before the heat death of the universe.
Results are 0-indexed.
```
(n,k,v)=>(g=(v,i=n,a=[])=>i--?g(v,i,a).concat(g(v-1,i,[i,...a])):v?[]:[a],F=s=>s.find(c=>g(v).every(b=>c.some(a=>b.every(v=>a.includes(v)))))||F(s.flatMap(a=>g(k).map(b=>[...a,b]))))([[]])
```
[Try it online!](https://tio.run/##LY7BasMwDIZfpUcJFMG6nQpyb731CYwPiuMEr6kd6sww6LtnNkwn6ePj1/@tVYt/xW0fUp7CMcsBiR5UUQwsApWiJFKxroE4DNelI1Jkn5PXHdo9fDRiIzGzOsRLvVp3seroJkVM4TmmCbyYpiKHGl6/MIrxXPIzgIoZ/2EVoxyTX3@mUJrb5/2@QUtYdb/r1uUFHsjPtrcI2z/S6LoI1jqHR2tV8hp4zQvM8EWnTzqdEY8/ "JavaScript (Node.js) – Try It Online")
## Commented
### Helper function
\$g\$ is a helper function that, given \$v\$, returns the list of all subsets of \$[0\dots n-1]\$ of length \$v\$. (Note that it is meant to be defined in the scope of the main function so that \$n\$ is known.)
```
g = ( // g is a recursive function taking:
v, // v = expected length
i = n, // i = counter, initialized to n
a = [] // a[] = current subset
) => //
i-- ? // decrement i; if it was not zero:
g( // do a recursive call where
v, i, a // nothing is changed
) //
.concat( // append the result of
g( // another recursive call where
v - 1, // v is decremented
i, // and
[i, ...a] // i is inserted at the beginning of a[]
) //
) //
: // else:
v ? [] // ignore this subset if its length is not v
: [a] // otherwise, append it to the output list
```
### Main function
```
(n, k, v) => ( // f is the main function, taking n, k, v
F = // F is a recursive function taking a list of
s => // lists of k-subsets
s.find(c => // is there a list c[] in s[] satisfying ...
g(v) // build all v-subsets
.every(b => // for each v-subset b[]:
c.some(a => // is there some k-subset a[] in c[] ...
b.every(v => // such that each value v in b[] ...
a.includes(v) // can be found in a[]?
) // end of every()
) // end of some()
) // end of every()
) // end of find()
|| // if no solution was found:
F( // do a recursive call:
s.flatMap(a => // for each entry a[] in s[]:
g(k) // build all k-subsets
.map(b => // for each k-subset b[]:
[...a, b] // append b[] to a[]
) // end of map()
) // end of flatMap()
) // end of recursive call
)([[]]) // initial call to F with a single empty list
```
[Answer]
# [Python](https://www.python.org), ~~168~~ 165 bytes
```
from itertools import*
def f(n,k,v):
c,r,i=combinations,range(n),0
while i:=i+1:
for t in c(c(r,k),i):
if not{*c(r,v)}-{*chain(*[c(s,v)for s in t])}:return t
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY89CsJAEIX7nGLK3TiCf4UEchKxiOuuGTQzYTIqIp7ExkZbz-NtTBC7xwff4737q71YLfx4PI-WxsvPM6k0QBbVRA4dUNOKWp5tY4LkGPd48kUGARWpDNJsiCsj4Q614l107HGSwbmmQwQqShpNC8gAkigYEENwwSnuPdJQA0AJWOyaD_Tkb-M-1RWxy1fBdT0ZxG4Qbe1vhUY7ap9_Y9-tEptLboFznHn_o_8rXw)
## Explanation
A brute-force solution. It iterates through all possible sizes of output sets \$i=1,2,\ldots\$, then checks the condition on each, and returns the first set of sets that meets the condition.
---
-3 bytes from @Steffan for extraneous parens
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 173 bytes
```
(n,k,v)=>(h=(e,...z)=>(g=(k,m=n,z=[])=>m--?[...g(k,m,z),...g(~-k,m,[m,...z])]:k?[]:[z])(v).every(i=>e.join`
`.match(i.join`,(.*,)?`))?e:h(...z,...g(k).map(x=>[...e,x])))([])
```
[Try it online!](https://tio.run/##JY6xDoMwDET3fgWjXZkMbSekwIdEkUA0QEhJEKCIMvTX0wS2e2f7zmPjm7Vd9Lzl1r1V6HgAS4Y88hIGDooYY0eCnoOhiVs6uJDRmPK8EnHYJ5sOpFP/8kRiOs8kysJUQhYiSvDIlFfLFzQvFRudtvWtZlOztQPoiwnYnbCqEStVDJAyrliDcXGGnZepUtEuERHiH6F1dnUfxT6uhw5elD0peyCGPw "JavaScript (Node.js) – Try It Online")
```
(n,k,v)=>(
h=(e,...z)=> // Take first
g(v).every( // For each n choose v
i=>e
.join`\n` // Arrays separated by newline
// which won't match `.`
.match(i.join`,(.*,)?`))?
// Match at least one line
e:h(...z,...g(k).map(x=>[...e,x]))
// If one fail then append another and throw to end
)
([]) // Starts with nothing
```
See Arnauld's answer for explanation of `g`
] |
[Question]
[
Pickleball doubles is a game where only the serving side can score. The server calls the score as a triple of numbers, the serving side's score, the receiving side's score, and \$1\$ or \$2\$ to indicate whether the server is the first or second of their side to serve. If the server's side wins a point, their score is incremented and the same player serves again. If the receiving side wins a point, no score is incremented but the serve transfers to the other player if the past server was the first or goes to the receiving side if the past server was the second of their team to serve. To even things out, the first serve is at \$0,0,2\$ so the serving side gets only one set of serves. Game is the first side to \$11\$ but the team must be leading by \$2\$ to win. There is a special state END where the game is over which is indicated here by \$0,0,0\$.
Write a routine that determines whether one score call can follow another. You will be given two lists of three numbers, which will be integers in the range \$0-30\$. The first list will be the score called before one serve, the second will be the score called before the next serve. You must return a truthy value if the second call can follow the first and a falsey value if the second call cannot follow the first.
If the first call is \$a,b,1\$ and the server's side wins the next call would be \$a+1,b,1\$ unless the server's side wins the game, which is when \$a \ge 11\$ and \$a \gt b+1\$. In that case the next call is END. If the first call is \$a,b,1\$ and the receiver's side wins the next call is \$a,b,2\$. If the first call is \$a,b,2\$ and the server's side wins the next call is \$a+1,b,2\$ unless the server's side wins the game, which is when \$a \ge 11\$ and \$a \gt b+1\$. In that case the next call is END. If the first call is \$a,b,2\$ and the receiver's side wins the next call is \$b,a,1\$. If the first call is END (the start of a game) the next call is \$0,0,2\$. If either call is not a legal call in any game you must return a falsey answer.
This code golf, so the usual rules apply. You may take your input and provide output in any convenient format.
## Test cases:
```
Input Output
==============================
[0,0,0] [0,0,2] True
[0,0,0] [0,0,1] False
[0,0,0] [1,0,2] False
[0,0,2] [1,0,2] True
[0,0,2] [1,0,1] False
[0,0,2] [0,1,2] False
[0,0,2] [0,0,2] False
[0,0,2] [0,0,1] True
[3,4,1] [3,4,2] True
[3,4,1] [4,4,1] True
[3,4,2] [4,4,2] True
[3,4,2] [4,3,1] True
[3,4,2] [4,3,2] False
[3,4,3] [4,4,3] False
[3,4,1] [4,4,2] False
[3,4,1] [4,3,2] False
[10,3,1] [0,0,0] True
[10,3,1] [10,3,2] True
[10,3,2] [3,10,1] True
[10,3,2] [3,10,2] False
[10,10,1] [0,0,0] False
[10,10,1] [11,10,1] True
[10,10,1] [10,10,2] True
[11,10,2] [10,11,1] True
[11,10,1] [11,10,2] True
[10,11,2] [11,11,2] True
[10,11,1] [0,0,0] False
[18,18,1] [19,18,1] True
[19,18,1] [0,0,0] True
[19,18,2] [18,19,1] True
[12,8,1] [12,8,2] False
[12,8,2] [8,12,1] False
[11,10,1] [12,10,1] False
[8,12,1] [8,12,2] False
```
[Answer]
# [J](http://jsoftware.com/), 87 84 95 92 91 95 bytes
```
e.(-.@w*]-:]**@{:+2<{:)#([:(*1-w=.((10<>.)*1<|@-)/@}:)]+#:@4),:(2={:){(+0 0 1*2^0={:),:1:2}2&A.
```
[Try it online!](https://tio.run/##dZNda8IwFIbv/RWHCeuHtss5daDBjspgV2MXux0ORFu3MRSswwvn/nrXpCk2x0g/cpIn531PEvJV3cTeGlIJHgxBgKy/KIbH1@enKo/9KM4O4TyS8zDMjnJA06MM@v6b9EOMDmns@yimD3EQ4vQ3i4K77CSD@aAvs1EwlD6l9eyjPxC1Job0LlR/KFHSiW5ncRX0itoX1n@9fPmxBYQUhH4K/SeABggG0AWwm9FKEQeCAXQBNUxucMXDqkqBBEZ1W@iWXGCkWwbIAHKDxC63C4iDxEglHCD3sEFim6PQroXZZhfRwWUS6dUj22IbEUN6ttvLIERLkkFhiWqIzVADkWWiLcsXgdhkYhOxWvFKrWP9qrxJE3XhpIWXeRppv7HudNwIjKIKiAGVMlahyfBmu83i53tVwj4v97BclHnpsRNob5JwX7DO8H2tr6xVy4bVbKqjTqXU0TZ1ei@f@912td1cq@d8CKSjM2pW1S6PetU/ "J – Try It Online")
+11 thanks to Arnauld finding a case I'd missed in input validation, which was not covered by the original test cases
## the idea
* Generate all possible successors of the first list.
* Check if the second list is a member of those.
* To handle input validation, null out the successor list when the input is
invalid.
## J details
* `(2={:){(+0 0 1*2^0={:),:1:2}2&A.` - Generate the "server lost" case:
+ `1:2}2&A.` - Sub-case 1: Serve changes. Swap elements 1 and 2 `2&A.` and
reset the final element to 1 `1:2}`.
+ `(+0 0 1*2^0={:)` - Sub-case 2: Serve increments. Add either `0 0 1`, or,
if the final element is 0 `0={:`, add `0 0 2`.
+ `(2={:)` - Choose sub-case 1 if the final element is 2, and sub-case 2
otherwise.
* `([:(*1-w=.10<{.*1<-/@}:)]+#:@4)` - Generate the "server won" case:
+ `]+#:@4)` - Add `1 0 0` (4 in binary) to the input.
+ Next, we'll transform the list to `0 0 0` if the game is over, and as a
side effect store the "is game over?" function in `w`, so we can re-use it
later for input validation.
+ `w=.((10<>.)*1<|@-)/@}:)` - Check if this game is over: Is the absolute difference between the
first two elements `|@-` greater than 1 `1<` and is `*` either element
greater than 10 `10<>.`?
+ `*1-` - Multiply the input by the inversion of that, so nothing happens when
we haven't won, and the input becomes `0 0 0` when we have.
* `(-.@w*]-:]**@{:+2<{:)` Is the input valid?
+ `-.@w*` The input is not a win and...
+ `]-:]**@{:+2<{:)` The input matches `]-:` the input multiplied by the sign
of the last element `]**@{:` plus 1 more if the last element is greater than
2 `2<{:`. This means it will only be valid if it is `0 0 0` or if the last
element is 1 or 2, and the game is not already won.
+ The validation will now be 0 or 1.
+ `#` Copy our successor list that many times, leaving it unchanged when the
input is valid, or nulling it out when it's invalid. Since the second input
list will never be an element of the empty list, our overall result (see
next step) will always be `0` if the input is invalid.
* `e.` Is the second input list (taken as the left arg) an element of the
possible successors? This is our final answer.
[Answer]
# JavaScript (ES6), 125 bytes
Returns \$0\$ or \$1\$.
```
([a,b,c],B,g=x=>a<11|a<b+2&&b<11|b<a+2&&c<3&x+''==B)=>c?(a>9&a>b?g`0,0,0`:g([a+1,b,c]))|g(c-1?[b,a,1]:[a,b,2]):!a&!b&g`0,0,2`
```
[Try it online!](https://tio.run/##dZPdbpswGIbPexVupIGtuBSbVlrSkEiV2oMdrAfZWYYUmxDGhCCDtEq17g4m7WSH3X3senoDu4TMfwSTnwTh7/Pj930dE76yJ1bHVbZaXxTlItkuwy2cMcxxHOFbnIabcMxGhLywEe9Tx@Gy5iMm63gUOJu@64bhLQrH8QSy8cBhYz5J5z4W3/kwFVZ9oswQeklhfEEmM44ZJtFQhdAIDc@Zc84draHzbZV8e8yqBLrL2kVelbDFfZYn0@cihj7y1uV0XWVFCpFXr/JsDXufix7ylmV1x@IvsAbhGHw/A2AGGAYcgyqpQQRCUJvll6B/iW4AE1PJE8shEw1vGi4aKQj1PQTup@oxcW@E30ZMLqH0RLKNy6Iu88TLyxT23tWguXoYfJg@fPRqtcls@SwCvBVb3BULSHx0QHmXbrAM0vET4P77@@vt9be4u2AI3Lc/P10R/gNtZ@p4I6BGGgH5kTs96wCiwT3La4uQVmIR2iWtWQPIUYmYP2Hmn4yxtqZjAnwlJ9RIj4ErPXYBNYAeB8EpRbC3LUkC4xUcENJNOSD7bsTXyc1x7zawA6pQIgtQ9fOJOZhjQCnaEL20TTkghJhqZ9YA39gZQEyrALEUpGtFbSuiFcRUNji6rfdYXlIyMJWRNG0rsYEKEXxgKShWAqAreSxNSNPPxAKq1tgPxe88lL2XogUNucbKQo2HRGoovt57K6gVs/e3aA@TmsqQZq@6aJ/yfw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 166 bytes
```
\d+
$*
A`^(1*),(?=11\1)1{11}|^(?=1{11})(1+)11+,\2,|111;
^(,,;,,11|(1{10},1{0,9}|1(1{10,}),\3),1+;,,|((1{0,9},1*|(1+),1*\6),1+);1\4|(.*),1;\7,11|(1*),(1*),11;\9,\8,1)$
```
[Try it online!](https://tio.run/##ZVDLasQwDLznO7ZgJ6J45NBuMKX01J8wYQvtoZcelt7W@fZUkr1JoCRIM5rRA1@/fr9/PtYH935Z8@fQnfru7TI79J7c6wuQ4XEDljIrVeQdBg8MlJkKgNTNjigRAcWJIyyEW6BpKTBKi6ccPWEQT3GuioS@6CDJ@UlFn5DH4h5lMVJ@rtP0Cg2yJU@UzwR/WtdA8iWN3O0YDWOr8z@MhgVt9XDw1DmRRrlBIzc8ajTMhnnD8VCPrR7NEw@9@xz1yJtImy0Ld2KpSSy7oYccmWn6733GgM1beWhuq7NxqI6jv06D6rDc@DZdnvqs7sly1/JdNSa9UppUZTKzJq6Mk1SY8Ac "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\d+
$*
```
Convert to unary.
```
A`^(1*),(?=11\1)1{11}|^(?=1{11})(1+)11+,\2,|111;
```
Remove some illegal starting calls, specifically:
* `^(1*),(?=11\1)1{11}` receiving side has already won
* `^(?=1{11})(1+)11+,\2,` serving side has already won
* `111;` illegal service number.
```
^(,,;,,11|(1{10},1{0,9}|1(1{10,}),\3),1+;,,|((1{0,9},1*|(1+),1*\6),1+);1\4|(.*),1;\7,11|(1*),(1*),11;\9,\8,1)$
```
Check whether any legal call remains, specifically:
* `,,;,,11` - Check for the start of a new game.
* `(1{10},1{0,9}|1(1{10,}),\3),1+;,,` Check for a win.
* `((1{0,9},1*|(1+),1*\6),1+);1\4` Check for a point that's not a win.
* `(.*),1;\7,11` - Check for a second serve.
* `(1*),(1*),11;\9,\8,1` - Check for a change of side.
I would have liked to use a conditional lookahead to determine whether the serving side is about to win or not and require that the second call matches `;,,` if they are or that the serving side simply scores a point if not, but for some reason my conditional lookahead started failing when I changed the expression for what to match when the conditional lookahead fails, which seems buggy.
[Answer]
# [Python 2](https://docs.python.org/2/), 135 bytes
Takes all six values as seperate arguments, returns a boolean.
```
lambda a,b,s,A,B,S:(9<a-1>b)|(9<A-1>B)<any([a|b|s|A|B<1<S<3,(a,b)==(B,A)[::s-2|1]!=S==3-s<3,3>s>0<[(a+1,S,b)==(A,s,B),A|B|S<1][9<a>b]])
```
[Try it online!](https://tio.run/##dZPPboMwDMbvfQrvUJVsroRDK62IIMGhL8BujENQqVapK1PDDpV49y4J/UOACeREvy/@bKzwc2m@6hO/7sXn9Si/y50EiSUqTDDFLPQ2kVxSXLJW7xK9S1kkTxcvl23ZqjZp04iiLArQ01lMCC/FhOVhqJa8peJFZEIES6X1IFaxH@WefCPMuqOJrpIy1B5tFlGR61JxWRTs2lSqUSAgz3Mf7w8v8OP8WxUIfUoFbuVR9TF1h13M79jx6CiNDxsXPoX9/zD1rANc6XwT@YiuTBxQbimfoMHk2cBtIrDIWARDTHfnMR6YkG@KdVPtlbxhu/Ah50ZzP73Ph/7kPwuMBaIJr07xb25PxUJuFXJzqO826FhDbhWaUKZae0fzIm3s2k/pyHhclnMrbtwMjtbKLO5gLDEid2@iHaU/7up5@R28trfZxBE2o1q75vzh/WimmM329RkOCBUcTmB/wnAGIJWqzg2UdX309t7rgTEQAiqExVYejtUOZANzBctYxwXMwTMO7PoH "Python 2 – Try It Online")
`9<a-1>b`: serving side has won (invalid)
`9<A-1>B`: receiving side has won (invalid)
`a|b|s|A|B<1<S<3`: *END* -> *START*
`(a,b)==(B,A)[::s-2|1]!=S==3-s<3`: receiving side scores point
`3>s>0<[(a+1,S,b)==(A,s,B),A|B|S<1][9<a>b]]`: serving side scores
] |
[Question]
[
**This question already has answers here**:
[Is this number evil?](/questions/169724/is-this-number-evil)
(135 answers)
Closed 4 years ago.
The computational parity of an integer is defined as 1 if the integer has an odd number of set bits, and 0 otherwise. ([src](https://en.wikipedia.org/wiki/Parity_function)).
## Input
* You will receive one nonnegative integer that you will take the parity of. Optionally, you may take the size of the integer in bytes or bits as an argument, but you must specify this in your answer.
## Output
* You will output the computational parity of the input integer.
## Rules
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply, including but not limited to [Abusing native number types to trivialize a problem](https://codegolf.meta.stackexchange.com/a/8245/89298).
## Test cases
You may omit any input that cannot be represented with your language's built-in integer type.
```
0: 0
1: 1
3: 0
8: 1
13: 1
17: 0
40: 0
52: 1
100: 1
127: 1
365: 0
787: 1
2898: 0
6345: 0
9038: 1
10921: 1
16067: 1
4105748: 1
40766838: 0
1336441507: 1
4294967295: 0
```
Generated using [this program](https://tio.run/##hVJNb8IwDL33V1ibBO0EUtOP9INSadtlu047TkMlLSxa26AmRdoQv50lKdBwWg6J47z37Ngmu918S8jpdE9bUvdlBRllXHRV0eTW6CM1bajguWWtGauBsGa32hUdFT9233K6basS9kXtWAcL5Lr6@BfrBKwlFZbA6W/FNrbCwQM8vzy@rZ5e3yHPAS0szduwzh7JTcG/Jc1GkGVaw4G5hGpz2CV3CWg2IJWtnY7WUkuGUgLqkFEGic/hPtEk5xy4q0TftQq/sI7/1GJfEcE6WQraCilCW3vPaHn5Ohdlmg6Q7PKTHETFBdfvh2ty7uxqotH0RzM2AIYbRaMdGCKhZ2BcU90zGD4Ox0sUGy9enBgRsR8YwMT1zWzcxDNSRtjFZk7IDaMgNpOMMI5vBHwfBwEKXZPmJUGCIy85hz0aM1H0gsFEQDoUcmywrjZhvVAjore7FO7UaY6ocJRn@tFOb9vtqmb/AQ).
The answer with the least amount of bytes in each language wins, which means that I will not be accepting an answer.
Bonus imaginary Internet points for an explanation.
[Sandbox link (10k+)](https://codegolf.meta.stackexchange.com/a/18532/89298)
[Answer]
# JavaScript (ES6), ~~18~~ 17 bytes
Similar to [my answer](https://codegolf.stackexchange.com/a/169732/58563) to [Is this number evil?](https://codegolf.stackexchange.com/q/169724/58563) except that the last iteration returns \$0\$, which saves a byte.
```
f=n=>n&&!f(n&~-n)
```
[Try it online!](https://tio.run/##hdJLDoIwEIDhvafATQMLZPqalgXehSAYDWmJGJdevUYTAq0N7frLP33d21c7d4/b9CyNvfTODY1pzoaQ45Ab8i5N4TprZjv2p9Fe8yGHosjWVVUZHHxAQ0ADwFMFnSpQLxEDKgDhCAEJIFlqBGwTMcDUPuAofRDuQelEgel6c1eRAnIhd0EN3C/8H7Nm64vGAAKqPSAoSCWWKTEAClEv@4j9KM5RCCrhN@dbcB8 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 30 bytes
Converts to binary, parses as base-3 and returns the parity.
```
n=>parseInt(n.toString(2),3)&1
```
[Try it online!](https://tio.run/##hdK7CoMwFIDhvU/hVAy0enKPg9079wnEqlgkEQ19fUsLokmDyfzxn9xe1bua66kf7VWbZ7O05aLL21hNc3PXNtWZNQ879bpLCbpQdMZLbfRshiYbTJe2KSCUbCvPEzi5APsAe4DGCipWwE4iBKQH/BEMIoCT2AjYJ0KAyGNABXeBvwepIgWiit1dBQqCMn4ICqBu4f@YBdleNAQECHkEGAYu2TolBEAKodZ9hH4UpYIxzOE351tYPg "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
BSḂ
```
**[Try it online!](https://tio.run/##y0rNyan8/98p@OGOpv///xsDAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##HYyrEQJBDIZbSQER2bx2YzEUgGSQmJtr4OwZmqEABI6hEGgkZFH/N/9rua7rlnk4fR57vp@v23e/HzPPhNAQBGEUlLSOoGUaF9NMuRxxQ@ijiEdU00XLCJK5ouC6aE4@t42s65gn3X38CyKu2oxmzKHhncMuPw "Jelly – Try It Online").
### How?
```
BSḂ - Link: non-negative integer
B - to binary
S - sum
Ḃ - least-significant-bit
```
[Answer]
# [Python](https://docs.python.org/3/), 27 bytes
```
f=lambda n:n and 1-f(n&~-n)
```
**[Try it online!](https://tio.run/##HU5LCsMgEN33FLMqEQyoo6MGepiUVBpoJyF1002vbsfM5j3ej9m/9bkxtlZur/l9X2bgiWHmBexYBr7@RlatbAfUx6fCyjAYDVYDakhCBGzU4EUMTrjprhMFKWiISZhLWZKEXoRssLdMdjJhyVDvWhOiT30kEqUzgEje22C67bLPFF0OarqA3H6sXIf@joZyolLtDw "Python 3 – Try It Online")**
This is quite nice because if we just want to *identify* the parity we can reduce it to **25 bytes** returning `0` or `-1`:
```
f=lambda n:n and~f(n&~-n)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 27 bytes
```
f=lambda n:n and n&1^f(n/2)
```
[Try it online!](https://tio.run/##FY5BCsMwDATvfYUuaRIQVJJt2Q70K4UUExpolRBy6etd97qzA7N/z9dmUutyf8@fZ5nBJoPZCtiVH8tgNxnrsh1gsBoQMjpMyA45oicMgkxtlYhOA8YUUVJOqM4HzOTalbIwspI2gSlEn5oYVdMfOqfec6DGJPusUXKYLgD7sdoJfVcm6ErfDYbQWsax/gA "Python 2 – Try It Online")
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 28 bytes
```
read*,i
print*,poppar(i)
end
```
[Try it online!](https://tio.run/##S8svKilKzNNNT4Mw/v8vSk1M0dLJ5Cooyswr0dIpyC8oSCzSyNTkSs1L@f/f0NjYzMTE0NTAHAA "Fortran (GFortran) – Try It Online")
Fortran has this as an in-built since F2008
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 4 bytes
```
bSOÉ
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/Kdj/cOf//4bGxmYmJoamBub/AQ "05AB1E – Try It Online")
## Explanation
```
bSOÉ
b # convert (implicit) input to base 2
O # the sum of...
S # the digits...
É # is odd?
```
[Answer]
# [Oasis](https://github.com/Adriandmen/Oasis), 4 bytes
```
ES2%
```
[Try it online!](https://tio.run/##y08sziz@/9812Ej1////hmYGZuYA "Oasis – Try It Online")
## Explanation
```
ES2%
S # the sum of...
E # the binary digits...
2% # mod 2
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 19 bytes
```
->n{("%b"%n).sum%2}
```
[Try it online!](https://tio.run/##FYtLCoMwEIavUoRAC39lJpPMJIv2IuKiLtwp0iJY1LOn6fZ7vNfhW8ZHuT/n/dq4oXHzrf2sk/Nn6QgMQQIL2BAI0YOpUm8QjbBk8CknqISITFJTyp7BSloHpmgh1dFU01@KaAgcqTqfQ1bzOfbt9Fr2YzuWS7dh7La@P8sP "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 28 bytes
```
lambda n:bin(n).count('1')%2
```
[Try it online!](https://tio.run/##NU9LCsIwEN3nFLORNiAy@TQ/6EnURasUSzUtJS5EPHssZLp6M2/eh1k@6TFHlYf2kp/dq793EEM/xjry021@x1RXouIHmVP7ZYAB8MhABBAbqLK5sglFaAutSdxI4hFpkJb8pikS64iRzrtCGaXp6FHtDeglVQuDhjxaYGM1STRaY5yiEKGU0Vo0uEul195Y6Sn6x4Z5hQnGCCkwWNZx@3eoJ35M5@nK8x8 "Python 3 – Try It Online")
[Answer]
# JavaScript, 18 bytes
Port of [ovs' Python solution](https://codegolf.stackexchange.com/a/199331/58974) - be sure to `+1` that if you're `+1`ing this.
```
f=n=>n&&n&1^f(n/2)
```
[Try it online!](https://tio.run/##FYtZDoIwEECv4hehYcROl2lrAhdxSQmCgWBLxBhuX@vvW@bu2239e1o/xxAfQ0pjE5o2FEUo8D6W4SRY6mPY4jLUS3yWFw4IEiygBDSgOGgByDMVBiRpMNaAsM4CSaXBcZlT7gQCEqc8INdG2TwaIvuXUpJSqHl2wilHRjh9q1/dWu5Nu1f@fPDVWO6M1XOcgr8Gz9IP)
[Answer]
# [PHP](https://php.net/), 39 bytes
```
for(;$n=&$argn;$n/=2)$p+=$n|0;echo$p%2;
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxV8mzVVBKL0vOALH1bI02VAm1blbwaA@vU5Ix8lQJVI@v//00MDUzNTSz@5ReUZObnFf/XdQMA "PHP – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~34~~ 21 bytes
Saved 13 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
```
f(n){n=n&&!f(n&n-1);}
```
[Try it online!](https://tio.run/##fZG7CsMwDEX3foUbSLAhAcnyk9A/6VISUjLUlNIt5NvdLN3auwkO9yFpGu7TVOuii9nKpXTd@Ri7MrAZ9/q4rUUbtZ2Uer7W8l50086qna@l6RdNpldkxt@QD8j/oCBlQkoWSCMydrCwt9CZCGIb4b7Bo@iYoNqmnJA8iIP2mQTflLKF7@JAATZ0TD46GOIohpAELsIiwTn29A3b6wc "C (gcc) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h!`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
¤ä^
```
[Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWgh&code=pORe&input=NDI5NDk2NzI5NQ)
] |
[Question]
[
There are radiation hardened quines, palindromic quines, but has anyone tried both?!
I think not!
## Rules
So the challenge here is to make a quine that if any symbol is deleted it prints its *original* source code, *and* the quine needs to be the same read forward and backwards(before radiation damage)! All code will be scored based on *bytes* required to write it.
## Things to avoid
1. Do not use any programs that are capable of directly examining their code and outputting it (that even means programs that take their source and dump it into some sort of data)
2. Do not use *anything* that somehow cheats all of this (like a function that outputs itself and some other character... please)
***DO YOUR BEST!!!***
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 78 bytes
```
\<"2ss}}l2%?:}a`(:&K&:&]r&[r~H>.!01<<\
\<<10!.>H~r[&r]&:&K&:(`a}:?%2l}}ss2"<\
```
[Try it online!](https://tio.run/##S8/PScsszvj/P8ZGyai4uLY2x0jV3qo2MUHDSs1bzUottkgtuqjOw05P0cDQxiaGiyvGxsbQQFHPzqOuKFqtKFYNrEwjIbHWyl7VKKe2trjYSMkm5v9/AA "Gol><> – Try It Online")
[Verification!](https://tio.run/##fZHNTsMwEITP8VNsi4gTASkpNxNAggsSR45pBFbqtBbBttYOVQ/h1cumf3AAbra8Mzvz2a3D0pqrjX53FgNYzxzaBcp3uAHknG9mxXjqfd@309M70cvXRMRPsYgrjEv8fLzNRpd5UcwYmxVFfjnKbh8/sYyxirdjyavsxd3ptO1776fjYrYhyzIXF3lFe7QJCb9fBwW17UwQ/BxaZZJ9gEyZ2s5VwqWvteZpmjI2Vw1gZ15a68PLfu4wnwoWrXRYgnVkwgctGfIVT0F6aOg1arIV6qCOChahCh0aqp25rawZux0QmFgXJgvbNtovJx7rwzlzaxi8x2mGSs4TSiW9V8TuCO7mcCzFtimzXRhw/hX8YLAdO4oZI0Tq42EpkcScXzPWWAQN2gBKs1DJD1jp0F43x8W6gtHgtNMLgBN4ftMO9FyZoGvZUgfjVd0F/UH4aUbWQaEnSP@HLQVZn33vOctFRRyjk913kni4/V4oin4U@k7KNl8)
A variation on the [radiation hardened quine](https://codegolf.stackexchange.com/a/179196/76162) I posted yesterday. It's a little more complex since it needs to reverse the copied section using the undocumented `[]` operators, as well as redirect the pointer in one copy. If you're a little confused about why it doesn't look like a palindrome, remember that `><>` is a palindrome itself.
] |
[Question]
[
I came across this [picture](https://imgur.com/gallery/j7NXx), which I initially questioned and thought about posting to Skeptics. Then I thought they'll only tell me if this one case is true, but wouldn't it be great to know how true any "rule" really is? Today you're going program a skeptic-bot
**Challenge**
Write a program or function which when given a dictionary of valid words and a rule determines if the rule is well applied
**Rules**
* The dictionary is "words.txt" taken from [here](https://github.com/dwyl/english-words). Your submission must theoretically be able to review all words in the file, but for testing you may use a shortened list
* "Rules" come in the form `x before y except <before/after> z`. Your submission may take that input in any reasonable form, some examples below
* Compliance is defined as: "There is an adjacent `x` and `y` in the word in the right order that are in the reverse order if before/after `z`"
* Non-compliance is defined as: "There is an adjacent `x` and `y` in the word in the incorrect order or they are not reverse if before/after `z`"
* Rules are evaluated case insensitive
* Output or return a [truthy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey#2194) value if the number of compliant words in the dictionary is greater than the number of non-compliant words, otherwise output a falsey value. Submissions cannot end in errors.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest submission in bytes wins
Example input:
```
["i","e","-","c"] #list of values, "-" denotes "after"
[105,101,-99] #list of values as ASCII numbers, "-99" denotes "after"
"ieac" #string of values abbreviated
```
**Test Cases**
Below are sample cases as inputs, for clarity I list the matching words but this is not required
Example dictionary: `["caught", "lemon", "simplified", "queue", "qwerty", "believe", "fierce", "receive", "science", "foreign", "weird", "quit"]`
```
Input: "I before E except after C"
Compliant: simplified, believe, fierce, receive
Noncompliant: science, foreign, weird
Output: Truthy
Input: "Q before U except before E"
Compliant: quit
Noncompliant: queue
Output: Falsey
Input: "C before E except before E"
Compliant: fierce, receive, science
Noncompliant:
Output: Truthy
```
[Answer]
# Python3, 105 103 bytes
This is my first golf here so be kind =)
-2 bytes tanks to Chas Brown
```
lambda d,b,x,y,z:sum((x+y in i)-2*((z*b+x+y+z)[:3]in i)-(y+x in i)+2*((z*b+y+x+z)[:3]in i)for i in d)>0
```
Takes the dictionary `d` as any iterator of strings; a boolean 'b' (`True` being `after`); and the three letters `x,y,z` as Strings;
[Try it online!](https://tio.run/##TZBNb4MwDIbPy6@wsksomTStN6TuOGn33VoOIRjqCQLNRwv98ywBbd3FH49ev7Y8zv48mP3SHE5Lp/qqVlDLSk5ylvfChV6IKZ@BDFD28rYT4r6r8kjye3Ys9uXGxZxPmyT/lUTyX9IMFihJ6uz9dalJexqMsjMc4Mi1Cu3Zc8k77AcTs6N@7KghrGNzCRgw5RtaP8eiwo7wmlBUWJ0KixppRU4TmpXFlUhtsrsh2c2JPC@ZR@ddWnxiR06oufyyAddQysQuad@H6hxucaMa/@gqPbGSsWf4hOCwBn9GcKpHSO5aOQTlVvitrgoGE3u/9v3Qo/EwNHCz5Mm0jKXn2NChhArT1RIsutD59K/12II9jZaMF7wdfMElNOLxwsfUriPnRXLKMgkcpxG1xzoNbIbZ8gM "Python 3 – Try It Online")
**Explanation:** might add later
[Answer]
# Java 8, 210 bytes
```
(D,a,b,c,f)->D.stream().filter(w->w.contains(a+b)&!w.contains(f?c+a+b:a+b+c)|w.contains(f?c+b+a:b+a+c)).count()>D.stream().filter(w->w.contains(b+a)&!w.contains(f?c+b+a:b+a+c)|w.contains(f?c+a+b:a+b+c)).count()
```
Takes the dictionary `D` as a `java.util.List<String>`; the three letters `a,b,c` as Strings; and whether it's after or before as a boolean `f` (truthy being 'after').
EDIT: Surprisingly enough using two `.matches` with regexes instead of the two times three `.contains` is longer. And creating variables for `f?c+a+b:a+b+c` and `f?c+b+a:b+a+c` is also [1 byte longer](https://tio.run/##hVNNb9swDL33V3A6DBas@Acka4oBOXbdocd1B5mhM6W2nEpUsqDLb89oO58Fgh5skfTjkx71vLRrO1rOX/dY2xjhh3X@/Q7AeaZQWSR46lKAn@WSkAGzpTQUiV1dPLrI3545OL@YwswMEdhjUB4DNGXb1mQ9VHoiZLs7eUW27BCewMM97LOZsaY0aCo9mr4f@vi@esDc5uVYnhxN6vMyt2N5cpwE4hQ8zIrIgWyT6aJytRw724ymmwJbzyImZtKsv365KLD@d5ElrSVJnjM9/YxK9r2mSldUfKaa7PaTTuYqlbXIPKhdt24OjWCzQeKv32D1MN8bY507ZNd6G7YyJk@bC9z3EOy2A2cfarGwsa8rtGnxh5VRNTWtlzW6ZlW7ytFckrdEibp1Q4G3EpRUO1p3JUEE7IJASK4vRXTk@1rVBnKLjm5DLgxMjpXuLxeASbY@n9soJ4iuD5XhkOgW7E0gaYBWto43cXigu8Jdeqqfct/26VANnFwLJ9vCybdwNu5wS8/byNQUbeJiJRiuvdhLQUndTECJORXQX6QVS5JVD8pW4iI1VgNCafmucszV@IVfWOW@wEttx3/gIGm3/w8).
[Try it online.](https://tio.run/##hVNNb9swDL33V3A6DBbs@AekW4YCOW7docd1B5mhM6aKnEp0vGDtb89oO1/rEPQgiyIfSfHpeeW2brJaPO3Ru5Tgm@Pw5waAg1CsHRLc90eA79WKUACzlSaUrbAvv3KSTw8SOSxnMC9GC9zRqI4GFlXTeHIBanurxV5v9JPECSPcQ4DPsM/mhSuqAovaTmbzMkkkt85sWbPXe2TdZNaV2ATR26XM5ZX9@OHCUX/BXJ1TXTnalzeRKndTXRqxGmiDZPbdFor/v8W50MvV5qcW@9t@yk1beZ3yMOy24QWsNSsbmfnxE5wd6b3C6oJRuAku7pSlQN0F7i5Gt@vB2RtfKl0a/AZdu/wlpjCe1k3QPfF647lmWujhuaWW@r2jKDs1KvJM296liIi9EQmJB1dCpjD46iYSL/tyHXEcK7EYO7wtgJC2Pt@7MKyIPg9NIbGla7BnhbQjtHY@XcXhodw/uEtJDSwPae@SWsBJtHBSLZxkC2fdjq/0sEtC67JppdwoRnxQMRqoqOcEjCrAAP1G2ogeVBnG1aotMzUjwliNmxxzM32URzF5KPFytuMvcBjpdf8X)
**Explanation:**
```
(D,a,b,c,f)-> // Method with List, 3 Strings, boolean parameters & boolean return
D.stream() // Stream the given dictionary-List
.filter(w-> // Filter the words by:
w.contains(a+b) // If the word contains `a+b`
&!w.contains(f? // If the flag is true (after):
c+a+b // And the word does not contain `c+a+b`
: // Else (before):
a+b+c) // And the word does not contain `a+b+c`
|w.contains(f? // If the flag is true (after):
c+b+a // Or the word contains `c+b+a`
: // Else (before):
b+a+c)) // Or the word contains `b+a+c`
.count() // And get the amount of words left in the filtered result
> // And return whether this is larger than:
D.stream() // Stream of the given dictionary again
.filter(w-> // Filtered by:
w.contains(b+a) // If the word contains `b+a`
&!w.contains(f? // If the flag is true (after):
c+b+a // And the word does not contain `c+b+a`
: // Else (before):
b+a+c)// And the word does not contain `b+a+c`
|w.contains(f? // If the flag is true (after):
c+a+b // Or the word contains `c+a+b`
: // Else (before):
a+b+c)) // Or the word contains `a+b+c`
.count() // And get the amount of words left in the filtered result
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~109~~ 107 bytes
```
lambda D,x,y,r,c:sum((((' '+w+' ')[w.find(p)+3*r]!=c)^(p==y+x))*2-1for p in(x+y,y+x)for w in D if p in w)>0
```
[Try it online!](https://tio.run/##VY1BboMwEEX3OcWUjXGYVkm6q0RX3CJNJWLGyUhgHAM1Pj21IYvWC@vPe55vG8Z7b06LLr@Wtu6uTQ0VzhjQofoYpi6PR4AofBFvefZvmk2TW1m8793lpVTyO7dlGYpZyv3p9ah7BxbY5HMRMNEEfARQAetVgZefh6WCEs6ZqqfbfcwQspa63qQwcGdb1kxNmh4TTbQGT24MKV2pZfpZYXzl1JocKeINDorJbDR@Tnxbaz2xezbymF12O@vYjKDzCgULFCTwgEIJ@Vc8opgEHpP@J9S28RTL8gs "Python 2 – Try It Online")
Takes Dictionary and rule input as `D,x,y,r,c` with `r=0` to mean 'before' and `r=1` to mean 'after'.
] |
[Question]
[
## Introduction:
The best options for the glass of your house will:
1. Let through as little heat as possible in both directions (insulation-value `Ug`).
(2. Let through as much sunbeams as possible from the outside to the inside.)
(3. Let through as much light as possible from the outside to the inside.)
We only care about the first one for this challenge.
In addition, there are different types of glass changing the `Ug`: regular single glass; regular double glass; HR double glass; HR+ double glass; HR++ double glass; HR+++ double glass.
HR = High Rendement glass; regular double glass with have air between both layers, but HR will have a noble gas between both layers.
Sources (not very useful for most though, because they are in Dutch, but added them anyway): [Insulate and save money](https://www.milieucentraal.nl/energie-besparen/energiezuinig-huis/isoleren-en-besparen/isolerende-raamfolie/) and [What is HR++ glass?](https://www.dubbelglas-weetjes.nl/hr-glas/)
## Challenge:
**Input:** A string indicating glass and window foil (below the possible input-strings are explained)
**Output:** (Calculate and) output the heat-transition `Ug`
**Here a table with all glass options and the expected output `Ug`-values:**
```
Glass (optional foil) Ug-value Description
| 5.8 Single-layered regular glass
|| 2.7 Double-layered regular glass
| | 1.85 HR glass
|+| 1.45 HR+ glass
|++| 1.2 HR++ glass
|+++| 0.7 HR+++ glass
|r 3.4 Single-layered regular glass with reflective foil
||r 2.1 Double-layered regular glass with reflective foil
|f 2.8 Single-layered regular glass with regular window-foil
||f 2.0 Double-layered regular glass with regular window-foil
|g 4.35 | with insulating curtain
||g 2.025 || with insulating curtain
| |g 1.3875 | | with insulating curtain
|+|g 1.0875 |+| with insulating curtain
|++|g 0.9 |++| with insulating curtain
|+++|g 0.525 |+++| with insulating curtain
|rg 2.55 |r with insulating curtain
||rg 1.575 ||r with insulating curtain
|fg 2.1 |f with insulating curtain
||fg 1.5 ||f with insulating curtain
/ 8.7 Diagonal |
// 4.05 Diagonal ||
/ / 2.775 Diagonal | |
/+/ 2.175 Diagonal |+|
/++/ 1.8 Diagonal |++|
/+++/ 1.05 Diagonal |+++|
/r 5.1 Diagonal |r
//r 3.15 Diagonal ||r
/f 4.2 Diagonal |f
//f 3.0 Diagonal ||f
/g 6.525 Diagonal | with insulating curtain
//g 3.0375 Diagonal || with insulating curtain
/ /g 2.08125 Diagonal | | with insulating curtain
/+/g 1.63125 Diagonal |+| with insulating curtain
/++/g 1.35 Diagonal |++| with insulating curtain
/+++/g 0.7875 Diagonal |+++| with insulating curtain
/rg 3.825 Diagonal |r with insulating curtain
//rg 2.3625 Diagonal ||r with insulating curtain
/fg 3.15 Diagonal |f with insulating curtain
//fg 2.25 Diagonal ||f with insulating curtain
```
Some things to note about the values: the first ten are all the different default values (taken from the two linked sources). Adding a `g` (insulating curtain) lowers that value by 25%. Having a `/` (diagonal window) increases that value by 50%.
## Challenge rules:
* You can ignore any floating point precision errors
* You can use the default decimal output-format of your languages, so if `3.0` is output as `3` instead; or if `0.9` is output as `0.900` or `.9` instead, it doesn't matter.
* You'll only have to worry about the input-options given above. Inputting anything else may result in undefined behavior (weird outputs, errors, etc.)
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, 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.
* Also, please add an explanation of your answer.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~172~~ ~~147~~ ~~128~~ ~~117~~ ~~112~~ 99 bytes
```
lambda w:ord('8%06(*D0t0
'[sum(map(ord,w.strip('g')))%77%24%13])*(2+('/'in w))*(4-('g'in w))/160.
```
[Try it online!](https://tio.run/##TZI7b8IwFIX3DJ27VPIS2SbGr7xcVLYuXdqBIQMwBNGkSAUiJxWq1P9O/Upgu989udfnHqX7Hb7OJ3ltlpvrd33c7WtwWZz1HkEVP/ICzV4f@MCf4Lr/OaJj3SGjkQvtB33oEGwhxjguy1hmsUi3eIZkgiCDhxO4YEPZ3H7jiYmC02v19v76Ua2W6wjBP0hyqjAxlSklLV0JTC2oyh0kDrIAnmQAS9wOAYMakpRmvrYgqfDQ2FoFwQHHxD7eQpLRNA9K6xQZEFgWNFVlaCS@wW8N1@H0ecTA@bhCu435uF@7@Xwcb9o7i46M6HwxSFQ4ijFrkfsRBpjLKGxgiUMxoWURDjXkcZzVNmkRlrqoRFAa@4QMSmMVHw8zlorpGmbRSGk5mfGBKSEnP@6IIr11QivNb6ZcRuWYItNurZpe8aGlxdho2nuvzKdmxGgbRc1Zg4qsgPm7wk@1iEC/bFCFI9Dpw2kAPYGbAZJ616N@vsIv4nMu@PUf "Python 2 – Try It Online")
---
**Explanation:**
Encodes the window as a sum of the ordinals of each char (without trailing `g`):
```
sum(map(ord,w[:(w+'g').find('g')]))
| -> 124 / -> 47
|| -> 248 // -> 94
| | -> 280 / / -> 126
|+| -> 291 /+/ -> 137
|++| -> 334 /++/ -> 180
|+++| -> 377 /+++/ -> 223
|r -> 238 /r -> 161
||r -> 362 //r -> 208
|f -> 226 /f -> 149
||f -> 350 //f -> 196
```
These are modded (`%77%24%13`), which gives values from 0 to 12):
```
sum(map(ord,w[:(w+'g').find('g')]))%77%24%13
| -> 124 -> 10 / -> 47 -> 10
|| -> 248 -> 4 // -> 94 -> 4
| | -> 280 -> 1 / / -> 126 -> 1
|+| -> 291 -> 12 /+/ -> 137 -> 12
|++| -> 334 -> 2 /++/ -> 180 -> 2
|+++| -> 377 -> 8 /+++/ -> 223 -> 8
|r -> 238 -> 7 /r -> 161 -> 7
||r -> 362 -> 6 //r -> 208 -> 6
|f -> 226 -> 0 /f -> 149 -> 0
||f -> 350 -> 5 //f -> 196 -> 5
```
The `Ug` values are multiplied by `20` and mapped to chars:
```
[0.7, 1.2, 1.45, 1.85, 2.0, 2.1, 2.7, 2.8, 3.4, 5.8]
[14, 24, 29, 37, 40, 42, 54, 56, 68, 116]
['\x0e', '\x18', '\x1d', '%', '(', '*', '6', '8', 'D', 't']
```
These chars are then ordered accordingly to the window-types, and padded with `'0's`. This new strign is used to look up the value based on the index.
```
'8%\x1806(*D\x0e0t0\x1d'#[sum(map(ord,w[:(w+'g').find('g')]))%77%24%13])
```
Lastly the given character is converted back into a number, and multiplied be the diagonal window and isolating curtain factors
```
*(2+('/'in w))*(4-('g'in w))/160.
equivalent to:
*2/2 or 3/2 * 4/4 or 3/4 /20
```
---
Saved
* -5 bytes, thanks to ovs
* -13 bytes, thanks to Lynn
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 110 bytes
```
s->"8%06(*D0t0
".charAt(s.split("g")[0].chars().sum()%77%24%13)*(s.charAt(0)%2+2)*(s.endsWith("g")?3:4)/160d
```
[Try it online!](https://tio.run/##ZZM7b9swEIB3D527FDiwEED5QT3sxEZSpwhgZOvUAh2CDKwsMnT1AkmlDVL/dpd62CIVLdTH7@54etyBvtDFYf/7JPKqlBoOhkmtRUZYXSRalAWZ3k5sqdO/utlLMqoUfKOigLcJQFX/ykQCSlNtlpdS7CE3Dn/XUhT88Qmo5MpvQwF@lLvSxKcP/Rlfuqg7YLA9qcUd2ngfw2s83X0IdfgJkeSZynuNFVFVJjRGHPmP4VO7rbBPVJ1j31uvvXjlRUt/agL7jND34lnc7qTFXv0U@rnN/rq8WflBdB3uT7dtR5c2daq0gq1ptN0HQP/QHKwrCOCKbOYX62pjY7IeLDja2IhsrgY9e69XtnZ8q2Pb2tpY@2A5bmtJVlbTcnRuTKLBsvePZD8wG@cOr4ojK84GcGjm0hhdlk5Rh5ijWjpjMJjAvgcbZg6MyEFpl7OB2cIGbgvudMCdFrjbAx81YbN0ijrEHHWhY/d779JE5DR7KGVONbBu2UKR/nEVRiH53FzI7xJNaD/C7WTcdPNxnuPz3IBMVZ01FbvSpFswI7Sqstd71Y07bpL9vrLJfVU6zUlZa1KZKpph5C2iUHnKK8wv1gTP@8p9zrH5vMfJ8fQf "Java (JDK 10) – Try It Online")
## Credits
* Port of [TFeld's Python 2 answer](https://codegolf.stackexchange.com/a/166644/16236).
* -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
[Answer]
# JavaScript (ES6), ~~111~~ 109 bytes
```
s=>'_FQLKIe%f:}'.charCodeAt((g=c=>~-s.split(c).length)(/\W/)+3*g` `+6*g`r`+8*g`f`)*5%117/(g`g`?8:g`|`?6:4)*.3
```
[Try it online!](https://tio.run/##XZJRT4MwFIXf9yvui2k7XAsDNsSwxRiXLC4hPvmgRiaj3XQZpiVG4/SvI5QWjX1p8nFyzrmXPq/f1iqXu9dqdCg3Rc2TWiUz9Li4WV0vixMefyGab9fysvl4UWEskjyZfY8UVa/7XYVzQvfFQVRbgtn9LSOOPxQZZM6kuWTmRM3FMzIMTzxvyrDIRDaPYpEds/kkDsiQ@nUKCXwOANARQXtiCGl0qkFHYhjTaQdAkxg8GoUdcXoSWKJRS8YWtCQG17pIY@vTwORIZHK8DvA@2DbhVuF2QBhFQH2T2yEtGYe2rjBV/GjaF7bM/WUatg3PfisL1ILQesnePrSB0jqF1oiLf4N0RGs0YHbHkVkGY/0grpEAsyZT48ucHnk90kz/CgtaogczErvn0LRhzOzZp56R8D59bCTcStzB1/lgkD49F3lFX4oPhVNCeSmv1vkWK0hmkJcHVe4Lui8Fls0r4lgRWpWL3XuxwQE5hQYmkN6phz8U5oDS67YoWlwsV4iQ@gc "JavaScript (Node.js) – Try It Online")
### How?
We define the helper function **g()** as:
```
g = c => ~-s.split(c).length
```
`split()` takes either a string or a regular expression as input. Hence, so does **g()**.
We define:
```
- N = g(/\W/) = number of non-alphanumeric characters
- S = g(' ') = number of spaces
- R = g('r') = number of "r"
- F = g('f') = number of "f"
- G = g('g') = number of "g"
- P = g('|') = number of "|"
```
The formula **n = N + 3S + 6R + 8F** gives a unique identifier in **[1..10]** for all default values:
```
input | N | S | R | F | n
---------+---+---+---+---+----
"|" | 1 | 0 | 0 | 0 | 1
"||" | 2 | 0 | 0 | 0 | 2 NB: because 'g' characters are ignored in this formula
"| |" | 3 | 1 | 0 | 0 | 6 and because a '/' is counted the same way as a '|',
"|+|" | 3 | 0 | 0 | 0 | 3 the 2 other sets of inputs give the same results.
"|++|" | 4 | 0 | 0 | 0 | 4
"|+++|" | 5 | 0 | 0 | 0 | 5
"|r" | 1 | 0 | 1 | 0 | 7
"||r" | 2 | 0 | 1 | 0 | 8
"|f" | 1 | 0 | 0 | 1 | 9
"||f" | 2 | 0 | 0 | 1 | 10
```
We use this identifier to pick the corresponding entry from the following 1-indexed array, which contains the default values multiplied by **20**:
```
[116, 54, 29, 24, 14, 37, 68, 42, 56, 40]
```
This array is encoded as the string `"FQLKIe%f:}"`. For each character, we multiply the ASCII code by **5** and apply a **modulo 117**:
```
char | code | * 5 | mod 117
------+------+-----+---------
'F' | 70 | 350 | 116
'Q' | 81 | 405 | 54
'L' | 76 | 380 | 29
'K' | 75 | 375 | 24
'I' | 73 | 365 | 14
'e' | 101 | 505 | 37
'%' | 37 | 185 | 68
'f' | 102 | 510 | 42
':' | 58 | 290 | 56
'}' | 125 | 625 | 40
```
Finally, we divide this value by:
* **80 / 3** if **G** is non-zero
* **60 / 3** if **P** is non-zero
* **40 / 3** otherwise
[Answer]
# Excel & CSV, 194 bytes
```
,"=HLOOKUP(SUBSTITUTE(SUBSTITUTE(A1,""g"",),""/"",""|""),2:3,2,)*IF(CODE(A1)=47,1.5,1)*IF(RIGHT(A1,1)=""g"",0.75,1)"
|,||,| |,|+|,|++|,|+++|,|r,||r,|f,||f
5.8,2.7,1.85,1.45,1.2,0.7,3.4,2.1,2.8,2
```
Input entered before the first `,`n and saved as `CSV`.
When opened in Excel, Cell `B1` displays result.
Sample usage:
```
/+++/g,"=HLOOKUP(SUBSTITUTE(SUBSTITUTE(A1,""g"",),""/"",""|""),2:3,2,)*IF(CODE(A1)=47,1.5,1)*IF(RIGHT(A1,1)=""g"",0.75,1)"
|,||,| |,|+|,|++|,|+++|,|r,||r,|f,||f
5.8,2.7,1.85,1.45,1.2,0.7,3.4,2.1,2.8,2
```
Opens as:
```
/+++/g 0.7875
| || | | |+| |++| |+++| |r ||r |f ||f
5.8 2.7 1.85 1.45 1.2 0.7 3.4 2.1 2.8 2
```
] |
[Question]
[
A special case of [Ramsey's theorem](https://en.wikipedia.org/wiki/Ramsey%27s_theorem) says the following: whenever we color the edges of the complete graph on 18 vertices red and blue, there is a monochromatic clique of size 4.
In language that avoids graph theory: suppose we place 18 points around a circle and draw all possible line segments connecting them in one of two colors: either red or blue. No matter how this is done, it's always possible to choose 4 of the points such that all 6 line segments between them are the same color: either all 6 are red or all 6 are blue.
Moreover, 18 is the least number for which this will work. For 17 points, we can color the line segments so that it's impossible to choose 4 points in this way.
Your goal is to print one such coloring. Your output must be a 17 by 17 adjacency matrix in which the (i,j) entry gives the color of the line segment joining points i and j. It must be in a format such as the one below:
```
R R B R B B B R R B B B R B R R
R R R B R B B B R R B B B R B R
R R R R B R B B B R R B B B R B
B R R R R B R B B B R R B B B R
R B R R R R B R B B B R R B B B
B R B R R R R B R B B B R R B B
B B R B R R R R B R B B B R R B
B B B R B R R R R B R B B B R R
R B B B R B R R R R B R B B B R
R R B B B R B R R R R B R B B B
B R R B B B R B R R R R B R B B
B B R R B B B R B R R R R B R B
B B B R R B B B R B R R R R B R
R B B B R R B B B R B R R R R B
B R B B B R R B B B R B R R R R
R B R B B B R R B B B R B R R R
R R B R B B B R R B B B R B R R
```
The exact output above represents a valid coloring, so it is perfectly acceptable. But you have the following additional freedom to do something else:
* You may print the adjacency matrix for any graph that satisfies the Ramsey condition, not just this one. (For example, any permutation of the rows with a corresponding permutation of the columns gives another acceptable output. I haven't checked if any non-isomorphic colorings exist.)
* You may use any two distinct, non-whitespace characters in place of `R` and `B` to represent the two colors.
However, the spacing must appear exactly as in the example above: a space between cells in the same row, spaces in the diagonal entries, and newlines after each row. Leading and trailing spaces and newlines are allowed (but the entries of the adjacency matrix should be aligned with each other).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. Because this is [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'"), hardcoding the output is allowed. Otherwise,
[standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
# [Python 3](https://docs.python.org/3/), 56 bytes
```
s=' '+bin(53643)[2:]
for _ in s:print(*s);s=s[-1]+s[:-1]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v9hWXUFdOykzT8PU2MzEWDPayCqWKy2/SCFeITNPodiqoCgzr0RDq1jTuti2OFrXMFa7ONoKSP3/DwA "Python 3 – Try It Online")
---
**[Python 3](https://docs.python.org/3/), 56 bytes**
```
s=' 1101000110001011'*16
while s:print(*s[:17]);s=s[16:]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v9hWXcHQ0MDQwMDAEEwAKXUtQzOu8ozMnFSFYquCosy8Eg2t4mgrQ/NYTeti2@JoQzOr2P//AQ "Python 3 – Try It Online")
---
**[Python 2](https://docs.python.org/2/), 64 bytes**
```
for k in range(289):print'\n'[k%17:]+' ab'[(k/17-k%17)**8%17%7],
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFbITNPoSgxLz1Vw8jCUtOqoCgzr0Q9Jk89OlvV0NwqVltdITFJPVojW9/QXBckpKmlZQGkVM1jdf7/BwA "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
“ḍ⁾’B⁶;ṙJ$ṚG
```
[Try it online!](https://tio.run/##hU47DsIwDN1zCg@MGZKmkERsLEhcIerIgnoBtvYAHKCIcyC6cJfkIsGxG9GtUiI/v4/t27Xv7zmn4RU/jzR@0zCd0vg@xnm67OL8POecg4Bw6CQELQGrINBIMBLaQrcS9qhIsCQqBCgZhyZfdEbMqpovYQrhIxeaLHWsGDI2tKipPK4ps/72QvBE9GjcoYvu/NJYunolacsfLRyzfJrxXCvWjpJ@NVQtabcR3AiL7gc "Jelly – Try It Online")
### How it works
```
“ḍ⁾’B⁶;ṙJ$UG Main link. No arguments.
“ḍ⁾’ Set the return value to 53643.
B Binary; yield [1,1,0,1,0,0,0,1,1,0,0,0,1,0,1,1].
⁶; Prepend a space, yielding [' ',1,1,0,1,0,0,0,1,1,0,0,0,1,0,1,1].
$ Monadic chain:
J Yield all indices of the array, i.e., [1, ..., 17].
ṙ Rotate the array 1, ..., 17 units to the left, yielding a matrix.
Ṛ Reverse the order of the rows.
G Format the matrix as a grid.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
18G•Ó₆•bð«NFÁ}Sðý=
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f0ML9UcOiw5MfNbUB6aTDGw6t9nM73FgbfHjD4b22//8DAA "05AB1E – Try It Online")
---
Uses 1 for `R` and 0 for `B`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 53 bytes
```
17.times{|i|puts (" %b"%53643*99).chars[i*16,17]*' '}
```
[Try it online!](https://tio.run/##KypNqvz/39BcryQzN7W4uiazpqC0pFhBQ0lBNUlJ1dTYzMRYy9JSUy85I7GoODpTy9BMx9A8VktdQb32/38A "Ruby – Try It Online")
# Ruby, 58 bytes
```
289.times{|i|$><<(" %b"%53643)[-i*16/17%17]+"
"[i%17/16]}
```
[Answer]
# [J](http://jsoftware.com/), 30 bytes
```
(-+:i.17)|."0 1' ',":#:53643
```
Explanation
```
#: - converts the number to a list of binary digits
": - converts the list to a string
' ', - prepends 3 spaces in front of the string
|."0 1 - rotates the list (rank 0 1)
(-+:i.17) - offset for the 0, 2, 4... 32 rotations
```
[Try it online!](https://tio.run/##y/r/PzU5I19DV9sqU8/QXLNGT8lAwVBdQUFBXUfJStnK1NjMxPj/fwA "J – Try It Online")
] |
[Question]
[
# The Challenge
Generate 1 sec of an 8 bit tone sampled at 256 samples per second. The tone will be made up of a number of sine waves. The frequency of each sine wave will be determined from the input data.
These are deep tones, too low for a human to perceive, but I've chosen 8 bit numbers here since it's code-golf.
# The Input
You will receive an array (or a list) of (non-negative) 8 bit signed integer values (0-127), each number will represent a frequency. An empty list is allowed and numbers may appear more than once in the list. All input frequencies must be assumed to be equal in amplitude.
# The Output
Your program or function must output an array (or list) of 8 bit signed integer values that represents the signal generated.
Some graphical examples follow, but the actual output of your program is to be a list of integers. ***Not*** a graph and ***not*** a stream of bytes.
Also, your output must be *normalized*. That is, it must fill the window of possible values from -128 to 127. In other words, if you calculate a signal and its [min,max] is [-64,63], then you must amplify (multiply) the entire signal ×2. A flat signal will be all zeros. There should be no DC component in any output signal (ie. the average value should be 0). Since most (practically all) generated signals will be symmetrical then most likely your normalized signal will never contain a -128.
[](https://i.stack.imgur.com/2qoQK.png)
The actual expected output of these datasets are as follows:
```
[] => [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
[2] => [0,6,12,18,24,30,36,42,48,54,59,65,70,75,80,85,89,94,98,102,105,108,112,114,117,119,121,123,124,125,126,126,127,126,126,125,124,123,121,119,117,114,112,108,105,102,98,94,89,85,80,75,70,65,59,54,48,42,36,30,24,18,12,6,0,-6,-12,-18,-24,-30,-36,-42,-48,-54,-59,-65,-70,-75,-80,-85,-89,-94,-98,-102,-105,-108,-112,-114,-117,-119,-121,-123,-124,-125,-126,-126,-127,-126,-126,-125,-124,-123,-121,-119,-117,-114,-112,-108,-105,-102,-98,-94,-89,-85,-80,-75,-70,-65,-59,-54,-48,-42,-36,-30,-24,-18,-12,-6,0,6,12,18,24,30,36,42,48,54,59,65,70,75,80,85,89,94,98,102,105,108,112,114,117,119,121,123,124,125,126,126,127,126,126,125,124,123,121,119,117,114,112,108,105,102,98,94,89,85,80,75,70,65,59,54,48,42,36,30,24,18,12,6,0,-6,-12,-18,-24,-30,-36,-42,-48,-54,-59,-65,-70,-75,-80,-85,-89,-94,-98,-102,-105,-108,-112,-114,-117,-119,-121,-123,-124,-125,-126,-126,-127,-126,-126,-125,-124,-123,-121,-119,-117,-114,-112,-108,-105,-102,-98,-94,-89,-85,-80,-75,-70,-65,-59,-54,-48,-42,-36,-30,-24,-18,-12,-6]
[1,3] => [0,8,16,24,32,39,47,54,61,68,75,81,87,93,98,103,107,111,115,118,120,123,124,126,126,126,126,126,125,123,121,119,116,113,110,106,102,98,94,89,84,79,74,69,64,59,54,49,44,39,35,30,26,22,18,15,12,9,7,4,3,1,0,0,0,0,0,1,3,4,7,9,12,15,18,22,26,30,35,39,44,49,54,59,64,69,74,79,84,89,94,98,102,106,110,113,116,119,121,123,125,126,126,127,126,126,124,123,120,118,115,111,107,103,98,93,87,81,75,68,61,54,47,39,32,24,16,8,0,-8,-16,-24,-32,-39,-47,-54,-61,-68,-75,-81,-87,-93,-98,-103,-107,-111,-115,-118,-120,-123,-124,-126,-126,-127,-126,-126,-125,-123,-121,-119,-116,-113,-110,-106,-102,-98,-94,-89,-84,-79,-74,-69,-64,-59,-54,-49,-44,-39,-35,-30,-26,-22,-18,-15,-12,-9,-7,-4,-3,-1,0,0,0,0,0,-1,-3,-4,-7,-9,-12,-15,-18,-22,-26,-30,-35,-39,-44,-49,-54,-59,-64,-69,-74,-79,-84,-89,-94,-98,-102,-106,-110,-113,-116,-119,-121,-123,-125,-126,-126,-126,-126,-126,-124,-123,-120,-118,-115,-111,-107,-103,-98,-93,-87,-81,-75,-68,-61,-54,-47,-39,-32,-24,-16,-8]
[15,14,13,12,11,10,9,8,7,6,5,4,3,2,1] => [0,32,63,89,109,122,126,124,114,100,82,62,43,26,13,4,0,0,3,9,16,24,30,35,37,36,33,27,21,14,8,3,0,-1,0,2,6,10,15,18,21,21,21,18,15,10,6,2,0,-1,-1,0,1,5,8,11,13,15,15,14,11,8,5,2,0,-1,-2,-1,0,1,4,6,9,10,11,11,9,7,5,2,0,-1,-2,-3,-2,0,1,3,6,7,8,9,8,6,4,2,0,-1,-3,-3,-3,-2,0,1,3,5,6,7,7,6,4,2,0,-2,-3,-4,-4,-4,-2,0,1,3,4,5,5,5,4,2,0,-2,-4,-5,-5,-5,-4,-3,-1,0,2,4,4,4,3,2,0,-2,-4,-6,-7,-7,-6,-5,-3,-1,0,2,3,3,3,1,0,-2,-4,-6,-8,-9,-8,-7,-6,-3,-1,0,2,3,2,1,0,-2,-5,-7,-9,-11,-11,-10,-9,-6,-4,-1,0,1,2,1,0,-2,-5,-8,-11,-14,-15,-15,-13,-11,-8,-5,-1,0,1,1,0,-2,-6,-10,-15,-18,-21,-21,-21,-18,-15,-10,-6,-2,0,1,0,-3,-8,-14,-21,-27,-33,-36,-37,-35,-30,-24,-16,-9,-3,0,0,-4,-13,-26,-43,-62,-82,-100,-114,-124,-127,-122,-109,-89,-63,-32]
[3,5,7,11,13,17,23] => [0,47,88,115,126,123,107,86,65,48,38,35,36,38,38,35,29,21,14,12,14,22,32,40,45,43,34,20,3,-10,-19,-22,-17,-10,-2,0,-3,-14,-30,-48,-60,-64,-56,-36,-7,22,49,66,70,60,40,14,-11,-31,-42,-44,-38,-29,-20,-14,-12,-14,-19,-23,-25,-23,-19,-14,-12,-14,-20,-29,-38,-44,-42,-31,-11,14,40,60,70,66,49,22,-7,-36,-56,-64,-60,-48,-30,-14,-3,0,-2,-10,-17,-22,-19,-10,3,20,34,43,45,40,32,22,14,12,14,21,29,35,38,38,36,35,38,48,65,86,107,123,126,115,88,47,0,-47,-88,-115,-126,-123,-107,-86,-65,-48,-38,-35,-36,-38,-38,-35,-29,-21,-14,-12,-14,-22,-32,-40,-45,-43,-34,-20,-3,10,19,22,17,10,2,0,3,14,30,48,60,64,56,36,7,-22,-49,-66,-70,-60,-40,-14,11,31,42,44,38,29,20,14,12,14,19,23,25,23,19,14,12,14,20,29,38,44,42,31,11,-14,-40,-60,-70,-66,-49,-22,7,36,56,64,60,48,30,14,3,0,2,10,17,22,19,10,-3,-20,-34,-43,-45,-40,-32,-22,-14,-12,-14,-21,-29,-35,-38,-38,-36,-35,-38,-48,-65,-86,-107,-123,-127,-115,-88,-47]
[1,1,2,3,5,8,13,21,34] => [0,52,88,99,90,75,68,73,84,92,88,74,60,56,67,87,104,104,85,55,30,25,43,73,101,112,105,85,66,57,58,59,51,34,14,4,15,46,87,118,127,112,84,60,50,56,68,73,64,45,27,18,23,32,36,24,1,-21,-28,-11,26,70,103,114,103,83,66,61,63,63,53,34,13,4,13,36,59,68,54,23,-8,-27,-24,-6,14,23,15,-2,-20,-28,-25,-19,-21,-34,-52,-62,-51,-17,31,77,103,104,88,68,57,60,69,74,67,49,32,24,31,45,54,47,23,-7,-29,-29,-6,26,55,64,54,32,12,1,0,-1,-12,-32,-54,-64,-55,-26,6,29,29,7,-23,-47,-54,-45,-31,-24,-32,-49,-67,-74,-69,-60,-57,-68,-88,-104,-103,-77,-31,17,51,62,52,34,21,19,25,28,20,2,-15,-23,-14,6,24,27,8,-23,-54,-68,-59,-36,-13,-4,-13,-34,-53,-63,-63,-61,-66,-83,-103,-114,-103,-70,-26,11,28,21,-1,-24,-36,-32,-23,-18,-27,-45,-64,-73,-68,-56,-50,-60,-84,-112,-126,-118,-87,-46,-15,-4,-14,-34,-51,-59,-58,-57,-66,-85,-105,-112,-101,-73,-43,-25,-30,-55,-85,-104,-104,-87,-67,-56,-60,-74,-88,-92,-84,-73,-68,-75,-90,-99,-88,-52]
```
# Additional Rules
All component frequencies are to begin at 0° phase. Basically, that means that they should start at 0 proceed to +127 at 90°, 0 again at 180°, -127 at 270° and then back to 0 at 360°.
It is acceptable if your outputs are slightly different due to rounding, from the examples posted here. They should be normalized to fill (or nearly fill) the range of possible signed ints (-128..127).
The [usual loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are prohibited.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins.
# IMPORTANT!
Practically everybody has made the same mistake in this challenge. 128 is NOT a valid signed 8 bit integer. You should not have output that contains this number or any number over 128.
[Answer]
# [Python 3](https://docs.python.org/3/), 119 bytes
```
from math import*
def f(a):b=[sum(sin(m*i*pi/128)for m in a)for i in range(256)];return[127*x//(max(*b)or 1)for x in b]
```
[Try it online!](https://tio.run/##7VhbbhtJEvwenYKfpNAN17uqZ8cn0eqDtqUdAZYsSDQgz@W9EZHZJEV49wIzIJvsR1ZWZmTkg3z@cfjz21P@@fP@5dvj5nF/@HPz8Pj87eVwffXl7n5zv93vfv/08eb1@@P29eFp@3j9cP388CGmsbv/9rJ53Dw8bfY6feDpy/7pP3fbVNvu9l8vd4fvL083MfXrtw8fto/7t@31px0ko@TfKP/p9ufh7vXwef969/rx5t9X25vb6SZM/7z@xq/b3XQFIiQxoU0xTXFMqUw5TLlNJU1lTLVMdZlanXqYep1GmAY@l2kp0zKmGLAmVBw45/pYcHQcC9RFHBkH7iXIpOZHPzuv/jybPNdp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RrGrfKkFnzynPdVyvQpdMb5RPRVty40YjaHw3u2ifCqHbnX3f7HSQv939XXSdBUUhLARHZSWlM@giwSS8hm3zc6gH@KNZ51NHbIoQAoVwBatx41gfrXqunWs0m2hk5HBaNT/3awEXL4BJVjML9VdjWnbAssqJ8OCUGZS3mT4ABpobNHY0@uAYsIG05gNWMLVWtIA2Z@RCV0mmcEKEWwC1yk9ODEekgpAamj8SNayZWly9tmm2LbZX5YU9nFFkYdYuWVWCvohmUWVSlS6Ys3RazgdvIOkCpOjsqWeAttO1GF0tCNayrKF1jxWDVvpxjoyqWartmXTIRTlZE0O9YKAKPun0zBFr0f0un@hc5zQUQ9GBqbbaoKdE7IxZ9F8DlU8BT0UrGBoPuZcIz2ZSmhRpKu1aMmwP20bbA0kAw8eD0cn60cCO6KBY9UzKWs276pQwO3NjjsWZ76oSoZaJDwZp4QZo3MmqI6FKqvJR94ha8rQdltbR2cuA1WT1sEalH5jRu8/bhWBRdxc/bT7uTGubFcnD6gMkN@@eF@oRcARoktSa76N3imhUIDU0S9KCqsrcxOVF9M@naZNkYnlZJ1GlRT@b86C0dptglNGh@JzTu1bCKfgGF@FpVs1gkiASQ1lhjSZZUVVAElu67sjCYTMcSRrzsZUIumwNQke09Bl5HYLj0Q6bNhlcDSrz6k3zFMneALt5S0x69p1ZOD1Dx/GXmeoVl3CEK81cKF5Oi8VSs@9wbJr9ZrNfc/bjLtomxSs9qzEDYWLFP6ifYKt2BwOdIC/JB@58@imwcDpY7HlFy7y9uuJ/fl/2h/109/Z89/lw94X//x3//Pv96rf958P3/dfNx839lnK7q9@eXx6eDtv916/bm/2n1@3b/GP3x8e40b@H0w@u/@vheWvrjmp3t7vdz/8C "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 28 bytes
```
Ṁ1Ṁ?
⁹Ḷµ×³×ØP÷⁹ḤÆSSµ€µ×127:Ç
```
[Try it online!](https://tio.run/##y0rNyan8///hzgZDILbnetS48@GObYe2Hp5@aPPh6YdnBBzeDhZacrgtOPjQ1kdNa0ByhkbmVofb////H22oY6hjpGOsY6pjoWNorGNkqGNsEgsA "Jelly – Try It Online")
*+5 bytes for handling input []*
All rounding errors are within +/- 2.
**How it works**
```
Ṁ1Ṁ? - helper link, returns the maximum of a list unless the maximum is 0, where it returns 1
Ṁ? - if the maximum is truthy:
Ṁ - return the maximum. Else:
1 - return 1.
⁹Ḷµ×³×ØP÷⁹ḤÆSSµ€µ×127:Ṁ - main link, nilad
⁹Ḷ - the literal [0,1,2,3,...,254,255]
µ µ€ - compute the relative amplitude for each using the chain:
׳ - multiply each element frequency by x
רP÷⁹Ḥ - scale because the sine function uses degrees.
ÆS - take the sine
S - return the sum of the list of sines of component waves.
µ×127:Ç - scale to 127, with divison by 0 handled by the helper link
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 34 bytes
```
Oh!8W:q7W/YP**Y,XstX:X>|a?1M/127*k
```
Try at [MATL online!](https://matl.io/?code=Oh%218W%3Aq7W%2FYP%2a%2aY%2CXstX%3AX%3E%7Ca%3F1M%2F127%2ak&inputs=%5B1%2C1%2C2%2C3%2C5%2C8%2C13%2C21%2C34%5D&version=20.0.0). Or add code `XG` to [see a plot](https://matl.io/?code=Oh%218W%3Aq7W%2FYP%2a%2aY%2CXstX%3AX%3E%7Ca%3F1M%2F127%2akXG&inputs=%5B1%2C1%2C2%2C3%2C5%2C8%2C13%2C21%2C34%5D&version=20.0.0).
[Answer]
# TI-BASIC, ~~47~~ ~~41~~ 48 bytes
*-6 thanks to @Octopus*
*+7 for handling `0`*
```
:Prompt Y //Get list of inputs, 3 bytes
:"sum(sin(XʟY→Y₁ //Store sum of sines function to Y₁, 10 bytes
:Y₁(128ֿ¹πseq(B,B,0,255 //Use the function to compute the values at 256 points, 20 bytes
:iPart(127Ans/max({1ᴇ~9,max(Ans //Normalize values and round, 8 bytes
```
This will not work for empty input, since **TI-BASIC** will never accept empty input ([see here](https://codegolf.stackexchange.com/a/118906/67881)).
**GIF:**
[](https://i.stack.imgur.com/uL8Nt.gif)
[Answer]
# [Perl 6](http://perl6.org/), 101 bytes
```
{my @w=[Z+] |(0 xx 256 xx 2),|.map:
(^256 »/»(128/π/*))».sin;(@w »*»(127/(@w.max||1)))».floor}
```
The frequencies are taken from the single list passed to this anonymous function.
[Answer]
# Mathematica, 75 bytes
```
(m=MaxValue[f=Tr[Sin[x/128Pi#]&/@#],x]+.1^9;Round[127f/m]~Table~{x,0,255})&
```
Try the code online at <https://sandbox.open.wolframcloud.com>.
Explanation:
```
f=Tr[Sin[x/128Pi#]&/@#] Define expression f contains variable x equal to the frequency
as x runs from 0 to 256 (x/128Pi runs from 0 to 2Pi)
m=MaxValue[ ,x] Find the maximum of f
+.1^9 Avoid case of empty list when m=0
Round[127f/m] Normalize value of f to correct range
~Table~{x,0,255} and make a table of the value.
```
Notes:
1. Using `MaxValue` instead of `NMaxValue` may have some symbolic issues, which is displayed as warning.
2. It can be proved that the function have `MaxValue + MinValue == 0`, so it is not necessary to calculate `MinValue`.
3. To run the code, put `[{1,3}]` for example after the code for input `{1,3}` and press `Shift+Enter` on Wolfram Sandbox.
4. Although the code produce exact result, it is not mathematically correct due to the bad way of handle empty input case. This version (**78 bytes**) is better.
---
```
(m=MaxValue[f=Tr[Sin[x/128Pi#]&/@#],x];Round[127f/m]~Table~{x,0,255}/.0/0->0)&
```
or (**80 bytes**)
```
(m=MaxValue[f=Tr[Sin[x/128Pi#]&/@#],x];If[m<1,0,Round[127f/m]]~Table~{x,0,255})&
```
This works because it can be proven that the maximum is at least 1 for all non-empty input.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 102 bytes
```
->r{(o=(0..255).map{|i|r.sum{|n|Math::sin(0.024544*i*n)}}).map{|f|(f*127/[1,*o].map(&:abs).max).to_i}}
```
[Try it online!](https://tio.run/##7VjtTiPHEv3PU4yIlLCrbtLf3YNE3iD3BchqBRuTtZQAAqNkA372vedU1djG2ntfIJE99nxUV1edOvVhPz7ffPl6e/n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WBLt6S0x6tp1ZOi1Hx@4XmlQsLuEgV5q6UKygFo2lTMDDsGn6201/1emPvKibFKv1rMcMhIoV@6B@gi3VOyjoBHlONnbn/Q@CmRPCrM8r2@b2fHX96fP08rpxq9dJ/2L87mWzvZi@e7m92ny4vFxN948TT8//Xj@crew/y2t383rtb7b8h/LjzZfl/0p8bE@3X/8L "Ruby – Try It Online")
I know this is a slightly old one, but it looked like fun. The margin of error (for the given tests, anyway) is within ±1.
] |
[Question]
[
## Definitions
* An algebraic number is a number that is a zero of a non-zero polynomial with integer coefficients. For example, the square root of `2` is algebraic, because it is a zero of `x^2 - 2`.
* The corresponding polynomial is called the minimal polynomial of the algebraic number, provided that the polynomial is irreducible over `ℚ`.
## Task
Given the minimal polynomials of two algebraic numbers, construct a set of numbers that are the sum of two numbers, one from the root of one polynomial, and one from the other. Then, construct a polynomial having those numbers as roots. Output the polynomial. Note that all roots are to be used, **including complex roots**.
## Example
* The two roots of `x^2-2` are `√2` and `-√2`.
* The two roots of `x^2-3` are `√3` and `-√3`.
* Pick one from a polynomial, one from the other, and form 4 sums: `√2+√3`, `√2-√3`, `-√2+√3`, `-√2-√3`.
* A polynomial containing those four roots is `x^4-10x^2+1`
## Input
Two polynomials in any reasonable format (e.g. list of coefficients). They will have degree at least `1`.
## Output
One polynomial in the same format, with **integer coefficients**.
You are **not** required to output an irreducible polynomial over `ℚ`.
## Testcases
Format: input, input, output.
```
x^4 - 10 x^2 + 1
x^2 + 1
x^8 - 16 x^6 + 88 x^4 + 192 x^2 + 144
x^3 - 3 x^2 + 3 x - 4
x^2 - 2
x^6 - 6 x^5 + 9 x^4 - 2 x^3 + 9 x^2 - 60 x + 50
4x^2 - 5
2x - 1
x^2 - x - 1
2x^2 - 5
2x - 1
4x^2 - 4 x - 9
x^2 - 2
x^2 - 2
x^3 - 8 x
```
The outputs are irreducible over `ℚ` here. However, as stated above, you do not need to output irreducible polynomials over `ℚ`.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
[Answer]
# Mathematica, 32 bytes
```
Resultant[#,#2/.x->z-x,x]/.z->x&
```
Or the same length:
```
Resultant[#/.x->y,#2/.x->x-y,y]&
```
### Example:
```
In[1]:= Resultant[#,#2/.x->z-x,x]/.z->x&[x^4 - 10 x^2 + 1, x^2 + 1]
Out[1]= 144 + 192 x^2 + 88 x^4 - 16 x^6 + x^8
In[2]:= Resultant[#/.x->y,#2/.x->x-y,y]&[x^2 - 2, x^2 - 2]
Out[2]= -8 x^2 + x^4
```
### Explanation:
If `x` is a root of `f(x)`, `y` is a root of `g(y)`, and let `z = x + y`, then `(x, z)` is a root of the simultaneous equations `f(x) = 0, g(z - x) = 0`. Then we can eliminate the variable `x` using the [resultant](https://en.wikipedia.org/wiki/Resultant).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~81~~ 71 bytes
*10 bytes off thanks to [Suever](https://codegolf.stackexchange.com/users/51939/suever)!*
```
@(a,b){[~,d]=rat(x=poly((roots(a)+roots(b)')(:)')),round(x*prod(d))}{2}
```
[Try it online!](https://tio.run/nexus/octave#S7PV09P776CRqJOkWR1dp5MSa1uUWKJRYVuQn1OpoVGUn19SrJGoqQ1hJGmqa2pYAQlNnaL80rwUjQqtgqL8FI0UTc3aaqPa/2ka0YYKBgq6hgZA0jBWRwHMNYzV5ALL6BorGCvomsDEdY0gEiYgtilI1AioFSJmhEUMqgdJ938A)
### Explanation
The code defines an anonymous function which uses a straightforward approach. It obtains the roots of each polynomial, computes all pairwise sums, and converts back from roots to polynomial. Since the resulting coefficients may not be integer, each is converted to a rational approximation and then they are all multiplied by the product of denominators.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~50~~ 49 bytes
```
p->q->polresultant(subst(p,x,y),subst(q,x,x-y),y)
```
[Try it online!](https://tio.run/nexus/pari-gp#fYxBCoQwDADvviLHxG1grd2jPkVwYQVBtNoK9fU12BU9eUomGaaDCqLleubaTsPyc@vg29GjW7/Oo1VBbaQSzAKBBTeKdulF6jA0BhiKdx4aDS8oCM@FssspxSn/ikwhk0QGfRNNnm4fQn1Y94p@ep6tKxp3 "Pari/GP – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
Ærp/S€Æṛær9µ÷g/Ḟ
```
[Try it online!](https://tio.run/nexus/jelly#@3@4rahAP/hR05rDbQ93zj68rMjy0NbD29P1H@6Y9////2hdIx0DHcNYHRgDAA "Jelly – TIO Nexus") (runs the last test case)
Takes input as list of coefficients with lowest value exponent first, e.g. `[-5,0,2],[-1,2]` would be `2x^2-5,2x-1`
**Explanation**
```
Ærp/S€Æṛær5µ÷g/Ḟ
Ær - get roots of input polynomial
p/ - Cartesian product (all pairs) of roots
S€ - sum of each pair
Æṛ - find a polynomial given the sums as the roots
ær9 - round to 10^(-9), used for output
µ÷ - divide by ...
g/ - the gcd of the coefficients of the output polynomial
Ḟ - take the floor to get integers.
```
] |
[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/109658/edit).
Closed 7 years ago.
[Improve this question](/posts/109658/edit)
You know it: keyboard or mouse input is just too mainstream to create Random Numbers through human behavior.
Create the most unique (Pseudo)Random Number Generator that create its numbers through human behavior.
Web-API's are not restricted! Anyone should use the code provided, so any special hardware is restricted. (I think we can assume that everyone has a smartphone)
The number should be a 256 bit number.
Example: use the Google Map's API to get current traffic to create the Random Number.
This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so most votes wins!
[Answer]
## Mathematica on Mac OS X
```
Mod[Tr /@ IntegerDigits[
Floor[2^15 AudioData@SystemDialogInput@"RecordSound"]
, 2], 2]
```
Opens up a dialog box that lets you record a sound snippet through the computer's microphone, then converts the resulting digital audio data to a list of bits (roughly 50,000 bits per second of audio). Generate random numbers through white noise, singing your favorite tune, exclaiming "Serenity now!", or just yelling at the top of your lungs!
[Answer]
# Python 3
```
import urllib.request
t=0
with urllib.request.urlopen("http://codegolf.stackexchange.com/questions/109658/hrng-human-random-number-generator#109658") as f:
m = f.read().decode("utf8")
for c in m:
t+=ord(c)
print(t/len(m.split()))
```
This version takes each characters ordinals to take into account changing values such as votes.
Leaving the below in as it was my first attempt but as noted it is a little stale.
```
import urllib.request
with urllib.request.urlopen("http://codegolf.stackexchange.com/questions/109658/hrng-human-random-number-generator#109658") as f:
m = f.read().decode("utf8")
print(len(m)/len(m.split()))
```
Takes this current page gets it's character count and word count divides and returns the number.
Not sure if it's great but first idea that came to mind.
[Answer]
# Bash
```
w|sha256sum|tr -d -
```
Outputs a hex-encoded 256 bit "random" number
>
> **w** displays information about the users currently on the machine, and their processes. The header shows, in this order, the current time, how long the system has been running, how many users are currently logged on, and the system load averages for the past 1, 5, and 15 minutes.
>
>
>
[Try It Online !](http://www.tutorialspoint.com/execute_bash_online.php?PID=0Bw_CjBb95KQMVXhoMlhIS1lnRms)
] |
[Question]
[
# What are Fibonacci networks?
>
> In 1202, an Italian mathematician known as Fibonacci posed the following problem:
>
>
> "A male and a female rabbit are born at the beginning of the year. We assume the following conditions:
>
>
> 1.After reaching the age of two months, each pair produces a mixed pair, (one male, one female), and then another mixed pair each month thereafter.
>
>
> 2.No deaths occur during the year."
>
>
> How many rabbits will there be at the end of the year?
>
>
>
[](https://i.stack.imgur.com/wG1xU.gif)
[Sources for graph and problem statement](http://aix1.uottawa.ca/%7Ejkhoury/fibonacci.htm)
# Challenge
Your challenge is to write a program/function to draw an ASCII art to output or a text file, or a graphical picture to a file/screen of a graph with following settings:
1. At 0th tick, there is one newly-born node.
2. Every newly born node creates a normal node after one tick after being born and gets deactivated.
3. A normal node creates a normal node and a newly-born node one tick after its birth and gets deactivated.
Your program will get the non-negative value `n` as input, and will draw the graph at the `n`th tick. Note that your program can draw newly-born nodes and normal nodes differently, but this is not necessary.
# Rules
* You must not use any built-in Fibonacci sequence function or mathematical constants or similar.
* If your program outputs to a file, it must be either a text file in a suitable and viewable format and encoding, or an image file in a suitable and viewable format with recognizable colors (for example, an image format that can be uploaded to SE).
* Your program can draw graph in any size, any shape and any alignment but the nodes and connections must be recognizable. Tree-shaped graphs (like the graph in "What are Fibonacci networks?" section) are recommended, but not necessary.
* Common code golf rules apply to this challenge.
# Examples
```
Input: 2
Possible Output:
*
|
*
| \
* *
Input: 0
Possible Output:
*
```
>
> Input: 5
>
>
> Possible Graphical Output:[](https://i.stack.imgur.com/7tnDf.png)
>
>
>
This is a [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'"). Shortest code wins. Good luck!
[Answer]
# Pyth, 31 bytes
```
Ms+0m+Wd+J+G"| "+G1+\-gJtd_UHgb
```
[Try it online](https://pyth.herokuapp.com/?code=Ms%2B0m%2BWd%2BJ%2BG%22%7C+%22%2BG1%2B%5C-gJtd_UHgb&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6)
### How it works
```
M def g(G, H):
m _UH map for d in [H - 1, …, 0]:
J+G"| " assign J = G + "| "
+ +G1 J + G + 1
+Wd conditional +, if d is truthy (nonzero):
+\-gJtd "-" + g(J, d - 1)
+0 prepend 0
s concatenate
gbQ g("\n", input)
```
### Output for 6
```
0
|
1-0
| |
| 1-0
| | |
| | 1-0
| | |
| | 1
| |
| 1-0
| | |
| | 1
| |
| 1-0
| |
| 1
|
1-0
| |
| 1-0
| | |
| | 1
| |
| 1-0
| |
| 1
|
1-0
| |
| 1-0
| |
| 1
|
1-0
| |
| 1
|
1-0
|
1
```
# Pyth, 43 bytes
```
Mc+WH`G++WG\-+j"
| "g0tH"
`-"j"
"g1tHbjg0
```
[Try it online](https://pyth.herokuapp.com/?code=Mc%2BWH%60G%2B%2BWG%5C-%2Bj%22%0A%7C+%22g0tH%22%0A%60-%22j%22%0A++%22g1tHbjg0&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6)
### Output for 6
```
0-1-0-1-0-1-0
| | `-1
| `-1-0-1
| `-1-0
| `-1
`-1-0-1-0-1
| `-1-0
| `-1
`-1-0-1-0
| `-1
`-1-0-1
`-1-0
`-1
```
[Answer]
# HTML5/JavaScript, 1262 bytes
This is my code which displays a Fibonacci network. You can just paste it into a file with a name like `index.html` and run it in your favourite browser (I only tested Chrome and Firefox though). When you launch it, it asks you for the desired number of generations. It uses the HTML5 `<canvas>` tag to display the image.
```
<script>let t,p,o,c=[],q=50,r=20,s=25;function d(o){return JSON.parse(JSON.stringify(o));}function e(a,x,y){o.beginPath();o.fillStyle=a?"red":"#000";o.arc(x*q+s,y*q+s,r,0,2*3.14159);o.fill();}function f(a,b,c,d){o.beginPath();o.strokeStyle="blue";o.lineWidth=3;o.moveTo(a*q+s,b*q+s);o.lineTo(c*q+s,d*q+s);o.stroke();}function g(i){return c[i].a+c[i].c;}function h(i){return c[i].b+c[i].d;}function k(j,e,f,b,n,x,y,z){f=j;b=0;while(1){if(!e){f.t=g(t);f.u=0;f.v=f.t;f.w=f.b;}else{n=t-b+1;x=t-b;z=e.b%2?(g(n)+g(x)+1):(-(g(n)+h(x)+1));f.t=e.v+z;f.u=e.w+1;f.v=f.t;f.w=f.u+f.b;}if(!f.a)break;b+=f.b+1;e=f;f=f.z;}return {a:f.b==0,x:f.v,y:f.w};}function l(j,c,b){b=k(j);f(b.x,b.y,c.x,c.y);e(b.a,b.x,b.y);return b;}function m(j){while(j.a)j=j.z;return j;}function n(j,o,p,q,r,s){if(o>t)return;q=l(j,p);r=d(j);m(r).b++;n(r,o+1,q);if(m(j).b>0){r=d(j);s=m(r);s.a=!0;s.z={a:!1,b:0};n(r,o+1,q);}}function b(i,z,y){t=parseInt(prompt());if(isNaN(t)||t<0)t=0;p=document.getElementById("o");c.push({a:0,b:0,c:0,d:0,e:1});for(i=1;i<t+1;i++){z=c[c.length-1];y={a:(i>1?i%2:0)+z.c,b:(i>1?1-i%2:0)+z.d,c:z.a+z.c,d:z.b+z.d};y.e=y.a+y.b+y.c+y.d;c.push(y);}p.width=q*(c[c.length-1].e+1);p.height=q*(t+1);o=p.getContext("2d");n({a:!1,b:0},0,0);}</script><body onload="b()"><canvas id="o">
```
An example for 6 generations would be this one:
[](https://i.stack.imgur.com/QuZp7.png)
As you can see, newly born nodes are colored in red, the others are black.
For reference, this is my ungolfed, development code that does exactly the same:
```
<html>
<head>
<meta charset="utf-8">
<title>Fibonacci Graph</title>
<script type="text/javascript">
let totalGenerations;
let canvas, ctx;
let individualCount = [];
let individualDrawSize = 50, individualDrawRadius = 20, individualDrawOffset = 25;
function generateIndividualCount()
{
individualCount.push(
{
babiesL: 0, //number of babies on the left side of the main individual
babiesR: 0,
adultsL: 0,
adultsR: 0,
total: 1 //total number of individuals (sum of all other members+1, because the main individual counts as well)
});
for(let i=1; i<totalGenerations+1; i++)
{
let last = individualCount[individualCount.length - 1];
let next =
{
//make an adult alternate between having a baby at the left and the right side (right side first)
babiesL: (i>1 ? i%2 : 0) + last.adultsL,
babiesR: (i>1 ? 1-i%2 : 0) + last.adultsR,
adultsL: last.babiesL + last.adultsL,
adultsR: last.babiesR + last.adultsR
};
next.total = next.babiesL + next.babiesR + next.adultsL + next.adultsR;
individualCount.push(next);
}
}
function setupContext()
{
canvas.width = individualDrawSize * (individualCount[individualCount.length - 1].total + 1);
canvas.height = individualDrawSize * (totalGenerations + 1);
ctx = canvas.getContext("2d");
}
function deepCopy(obj)
{
return JSON.parse(JSON.stringify(obj));
}
function drawIndividual(isBaby, x, y)
{
ctx.beginPath();
ctx.fillStyle = isBaby ? "red" : "black";
ctx.arc(x*individualDrawSize + individualDrawOffset, y*individualDrawSize + individualDrawOffset, individualDrawRadius, 0, 2*Math.PI);
ctx.fill();
}
function drawLine(x1, y1, x2, y2)
{
ctx.beginPath();
ctx.strokeStyle = "blue";
ctx.lineWidth = 3;
ctx.moveTo(x1*individualDrawSize + individualDrawOffset, y1*individualDrawSize + individualDrawOffset);
ctx.lineTo(x2*individualDrawSize + individualDrawOffset, y2*individualDrawSize + individualDrawOffset);
ctx.stroke();
}
function getIndividualCountLeft(i) //left like in "the opposite of right"
{
return individualCount[i].babiesL + individualCount[i].adultsL;
}
function getIndividualCountRight(i)
{
return individualCount[i].babiesR + individualCount[i].adultsR;
}
function getPosition(ancestorInformation)
{
let prevInfo;
let tempInfo = ancestorInformation;
let currDepth = 0;
while(1)
{
if(prevInfo == undefined)
{
tempInfo.birthX = getIndividualCountLeft(totalGenerations);
tempInfo.birthY = 0;
tempInfo.givingBirthX = tempInfo.birthX;
tempInfo.givingBirthY = tempInfo.ageAtGivingBirth;
}
else
{
let generationsLeftForParent = totalGenerations - (currDepth-1);
let generationsLeftForChild = totalGenerations - currDepth; //left like in "to go" or "There are 42 cookies left"
let isLeftBranch = (prevInfo.ageAtGivingBirth % 2 == 0);
let distanceToParent;
if(isLeftBranch)
distanceToParent = -(getIndividualCountLeft(generationsLeftForParent) + getIndividualCountRight(generationsLeftForChild) + 1);
else
//some of these directions may seem odd, but because the parent subtree begins with a left branch (and individualCount only contains data for trees beginning with a right branch), it needs to be inversed
//if individualCount would have been generated for trees beginning with a left node, all of the getIndividualCountLeft/getIndividualCountRight function would need to be inversed
//or, when individualCount would have been generated for both cases, functions like getIndividualCountRight_LeftBegin and getIndividualCountLeft_RightBegin could be used
distanceToParent = getIndividualCountLeft(generationsLeftForParent) + getIndividualCountLeft(generationsLeftForChild) + 1; //+1, because the previous value of distanceToParent is just the number of empty fields (on the x axis) between the parent and the child
tempInfo.birthX = prevInfo.givingBirthX + distanceToParent;
tempInfo.birthY = prevInfo.givingBirthY + 1;
tempInfo.givingBirthX = tempInfo.birthX;
tempInfo.givingBirthY = tempInfo.birthY + tempInfo.ageAtGivingBirth;
}
if(!tempInfo.isParent)
break;
currDepth += tempInfo.ageAtGivingBirth + 1;
prevInfo = tempInfo;
tempInfo = tempInfo.child;
}
return { isBaby: tempInfo.ageAtGivingBirth==0, x: tempInfo.givingBirthX, y: tempInfo.givingBirthY };
}
function draw(ancestorInformation, parentPos)
{
let pos = getPosition(ancestorInformation);
drawLine(pos.x, pos.y, parentPos.x, parentPos.y);
drawIndividual(pos.isBaby, pos.x, pos.y);
return pos;
}
function getDeepestChild(ancestorInformation)
{
while(ancestorInformation.isParent)
ancestorInformation = ancestorInformation.child;
return ancestorInformation;
}
function drawAll(ancestorInformation, depth, parentPos)
{
if(depth > totalGenerations)
return;
let pos = draw(ancestorInformation, parentPos);
let newAncestorInformation = deepCopy(ancestorInformation);
getDeepestChild(newAncestorInformation).ageAtGivingBirth++;
drawAll(newAncestorInformation, depth + 1, pos);
if(getDeepestChild(ancestorInformation).ageAtGivingBirth > 0)
{
newAncestorInformation = deepCopy(ancestorInformation);
let deepestChild = getDeepestChild(newAncestorInformation);
deepestChild.isParent = true;
deepestChild.child = { isParent: false, ageAtGivingBirth: 0 };
drawAll(newAncestorInformation, depth + 1, pos);
}
}
function load()
{
totalGenerations = parseInt(prompt("Number of generations?"));
if(isNaN(totalGenerations) || totalGenerations < 0)
totalGenerations = 0;
canvas = document.getElementById("output");
generateIndividualCount();
setupContext();
drawAll({ isParent: false, ageAtGivingBirth: 0 }, 0, 0); //although this individual does not really give birth after it has been born, it still has an attribute called "ageAtGivingBirth" (like its parents) to achieve a similar effect
}
</script>
</head>
<body onload="load()">
<canvas id="output" style="position:absolute; top:10px; left:10px" width="1200" height="600">Canvas not supported...</canvas>
</body>
</html>
```
] |
[Question]
[
**The task:**
Build a calculator that takes a simple math equation in Chinese and outputs the correct answer(To the equation from the users input) in Chinese.
---
**Scope:**
* Any programming language can be used.
* Input must be in Chinese otherwise an error message will be displayed .
* Output must be in Chinese.
* Only input and output of whole numbers between 0-999 will be in scope (this is meant to be a simple calcaulation).
* The full original input must be included prior to equals then the answer.
* Display answer with no decimal points.
* Long number form output is mandatory.
* Input must accept Long number form, inclusion of short form is optional.
**Sample input/output:**
>
> 二乘以八 (2\*8)
>
> 二乘以八等于十六 (2\*8=16)
>
>
>
**Cheat Sheet:**
>
> 零 or 〇 → 0 (either form or both, you choose)
>
> 一 → 1
>
> 二 → 2
>
> 三 → 3
>
> 四 → 4
>
> 五 → 5
>
> 六 → 6
>
> 七 → 7
>
> 八 → 8
>
> 九 → 9
>
> 十 → 10
>
> 百 → 100
>
> 加 → + Operator
>
> 减 → - Operator
>
> 乘以 → \* Operator
>
> 除以 → / Operator
>
> 等于 → = Operator
>
>
> Chinese numbering is basic 333 is just 3 100 3 10 3 三百三十三 only exception is 十 where you don't need 一十 to say 10 (but you might to), but you do need 一百 to say 100 (i.e., can't say just 百).
>
>
>
Useful link: <http://www.mandarintools.com/numbers.html>
If you can't see the chinese symbols, [you may see them here](https://i.stack.imgur.com/qkmPR.png).
Get creative and happy coding!
[Answer]
# Java
It parses the equation as a context-free language, using these productions for that:
```
U1 = [一-九] (i.e. [1-9])
D1 = U1 十 U1?
DO = U1? 十 U1?
CDN = 〇 U1 | D1
C1 = U1 百 CDN?
F = C1 | DO | U1 | 〇
F2 = 負? F
OP = 加 | 减 | 乘以 | 除以 (i.e., + | - | * | / )
EQ = F2 (OP F2)*
```
The `DO` and `D1` productions are handled in the same method, diferentiated by a parameter. The other productions take one method each. The `EQ` is the grammar main symbol. Before starting the parse, it replaces 零 for 〇, so it need to handle just 〇 after that.
The 負 is for negative numbers. It can handle numbers from -999 to 999 (or 負九百九十九 to 九百九十九).
Further, to make it much more chinese, all the identifiers are in chinese. The only exception is the class name (using international characters there may cause problems) that is a chinese name transliterated to latin characters.
For the input I had to use a `JOptionPane`. Sorry for that, but I had trouble about encodings using other input methods. If you don't like this method of input, you can use the `解方程` method directly, it takes the input formula and produce the output equation (or error message).
```
import javax.swing.JOptionPane;
public class ZhongguoJisuanQi {
private final String 文字输入;
private int 源指数;
public ZhongguoJisuanQi(String 文字输入) {
this.文字输入 = 文字输入.replace("零", "〇");
this.源指数 = 0;
}
public static void main(String... 参数) {
String 方程 = 解方程(读取文本行());
System.out.println(方程);
JOptionPane.showMessageDialog(null, 方程, "答案是", JOptionPane.INFORMATION_MESSAGE);
}
private static String 读取文本行() {
return JOptionPane.showInputDialog(null, "输入数学公式", "输入数学公式", JOptionPane.QUESTION_MESSAGE);
}
public static String 解方程(String 数学公式) {
if (数学公式 == null) return "错误:给定的数学公式的格式不正确。";
ZhongguoJisuanQi 计算器 = new ZhongguoJisuanQi(数学公式);
Integer 结果 = 计算器.解析并解决了式();
if (结果 == null) return "错误:给定的数学公式的格式不正确。";
return 数学公式 + "等于" + 整数转换为文本(结果);
}
private boolean 找到字符(char 字符, int 指数) {
return 指数 < 文字输入.length() && 文字输入.charAt(指数) == 字符;
}
private Integer 解析生产一() {
int 数 = "一二三四五六七八九".indexOf(文字输入.charAt(源指数));
if (数 == -1) return null;
源指数++;
return 数 + 1;
}
private Integer 解析生产十(boolean 必须带有前缀) {
int 原始来源索引 = 源指数;
Integer 第一个数字 = 解析生产一();
if (第一个数字 == null && 必须带有前缀) return null;
if (!找到字符('十', 源指数)) {
源指数 = 原始来源索引;
return null;
}
源指数++;
Integer 第二个数字 = 解析生产一();
return (第一个数字 == null ? 1 : 第一个数字) * 10 + (第二个数字 == null ? 0 : 第二个数字);
}
private Integer 解析生产或零十() {
int 原始来源索引 = 源指数;
if (找到字符('〇', 源指数)) {
源指数++;
Integer 数 = 解析生产一();
if (数 == null) {
源指数 = 原始来源索引;
return null;
}
return 数;
}
return 解析生产十(true);
}
private Integer 解析生产百() {
int 原始来源索引 = 源指数;
Integer 第一个数字 = 解析生产一();
if (第一个数字 == null) return null;
if (!找到字符('百', 源指数)) {
源指数 = 原始来源索引;
return null;
}
源指数++;
Integer 第二个数字 = 解析生产或零十();
return 第一个数字 * 100 + (第二个数字 == null ? 0 : 第二个数字);
}
private Integer 解析生产数无符号() {
Integer 数 = 解析生产百();
if (数 != null) return 数;
数 = 解析生产十(false);
if (数 != null) return 数;
数 = 解析生产一();
if (数 != null) return 数;
if (找到字符('〇', 源指数)) {
源指数++;
return 0;
}
return null;
}
private Integer 解析该生产号() {
boolean 负 = false;
if (找到字符('負', 源指数)) {
源指数++;
负 = true;
}
Integer 数 = 解析生产数无符号();
return 数 == null ? null : 负 ? -数 : 数;
}
private String 解析算术运算符() {
if (找到字符('加', 源指数)) { 源指数++; return "加"; }
if (找到字符('减', 源指数)) { 源指数++; return "减"; }
if (找到字符('乘', 源指数) && 找到字符('以', 源指数 + 1)) { 源指数 += 2; return "乘以"; }
if (找到字符('除', 源指数) && 找到字符('以', 源指数 + 1)) { 源指数 += 2; return "除以"; }
return null;
}
public Integer 解析并解决了式() {
Integer 第一个数字 = 解析该生产号();
while (true) {
String 算术运算符 = 解析算术运算符();
if (算术运算符 == null) return 源指数 == 文字输入.length() ? 第一个数字 : null;
Integer 第二个数字 = 解析该生产号();
if (第二个数字 == null) return null;
switch (算术运算符) {
case "加": 第一个数字 += 第二个数字; break;
case "减": 第一个数字 -= 第二个数字; break;
case "乘以": 第一个数字 *= 第二个数字; break;
case "除以": 第一个数字 /= 第二个数字; break;
default: throw new AssertionError();
}
}
}
private static String 整数转换为文本(int 参数) {
if (参数 == 0) return "〇";
StringBuilder 字符串生成器 = new StringBuilder(7);
int 数 = 参数;
if (数 < 0) {
字符串生成器.append("負");
数 = -数;
}
if (数 >= 1000) return null;
if (数 >= 100) {
字符串生成器.append("〇一二三四五六七八九".charAt(数 / 100)).append("百");
数 %= 100;
if (数 >= 1 && 数 <= 9) 字符串生成器.append("〇");
if (数 >= 10 && 数 <= 19) 字符串生成器.append("一");
}
if (数 >= 20) 字符串生成器.append("〇一二三四五六七八九".charAt(数 / 10));
if (数 >= 10) 字符串生成器.append("十");
数 %= 10;
字符串生成器.append("〇一二三四五六七八九".charAt(数));
return 字符串生成器.toString();
}
}
```
Compile with:
```
javac -encoding UTF8 ZhongguoJisuanQi.java
```
Run with:
```
java ZhongguoJisuanQi
```
Cheat sheet for identifiers names, accordingly to google translator:
```
(english original text) -> (chinese text) -> (english text back from chinese)
chinese calculator -> 中国计算器 (Zhōngguó jìsuàn qì) -> china calculator
text input -> 文字输入 -> text input
source index -> 源指数 -> source index
original source index -> 原始来源索引 -> original source index
Enter the mathematical formula -> 输入数学公式 -> Enter mathematical formulas
mathematical formula -> 数学公式 -> mathematical formulas
Error: The given mathematical formula is malformed. -> 错误:给定的数学公式的格式不正确。 -> Error: The given mathematical formula is not correct.
character -> 字符 -> character
read a text line -> 读取文本行 -> read a line of text
arguments -> 参数 -> parameter
equation -> 方程 -> equation
index -> 指数 -> index
find character at -> 找到字符 -> find characters
parse the production -> 解析生产 -> resolve the production
parse the production or zero -> 解析生产或零 -> resolve the production or zero
parse the production number -> 解析该生产号 -> resolve the production number
parse the production number without sign -> 解析生产数无符号 -> resolve production unsigned
parse and solve the formula -> 解析并解决了式 -> parse and resolve the formula
parse an arithmetic operator -> 解析算术运算符 -> parsing arithmetic operators
arithmetic operator -> 算术运算符 -> arithmetic operators
must be prefixed -> 必须带有前缀 -> must be prefixed with
calculator -> 计算器 -> calculators
solve the equation -> 解方程 -> solving equations
result -> 结果 -> result
number -> 数 -> number
minus -> 负 -> minus
first number -> 第一个数字 -> the first number
second number -> 第二个数字 -> second number
string builder -> 字符串生成器 -> string builder
convert integer to text -> 整数转换为文本 -> integer is converted to text
the answer is -> 答案是 -> the answer is
```
[Answer]
## Haskell
Here is a solution in Haskell with custom made parser combinators. No library is required, all pure functional power. :)
The grammar in the middle of the file describes the structure of the expressions that will be parsed. The grammar itself is the parser, and it is build from terminal parsers, with parser combinators to put them in sequence (`<:>`,`<::>`) or as alternatives (`|||`). Each of the terminal parsers parses a certain string or character, such as an operator or a digit. The evaluation combinator (`==>`) then transforms and calculates the expression.
Some inspiration I found
[in this blog](http://alephnullplex.appspot.com/blog/view/2010/01/12/lbach-1-introduction), but mainly I learned this when I worked with a DSL embedded in Haskell that uses the same approach ([ADP, Algebraic Dynamic Programming](http://bibiserv.techfak.uni-bielefeld.de/adp/), I wrote a typechecker for it), here we can even solve optimization problems with dynamic programming!
Also there is a nice paper by G.Hutton about parsing with combinators in Haskell.
This was a really fun problem, thanks for suggesting it!
The `calc_own_combi.hs` file:
```
type Parser a = String -> Maybe (a, String)
dict = [('零', 0) ,('〇', 0) ,('一', 1) ,('二', 2) ,('三', 3) ,('四', 4) ,('五', 5) ,('六', 6) ,('七', 7) ,('八', 8) ,('九', 9), ('十',10), ('百',100)]
-- parse 1 character
char :: Parser Char
char [] = Nothing
char (x:xs) = Just(x, xs)
-- parse a chinese digit
cndigit :: Parser Char
cndigit = char <== isCNdigit
where isCNdigit c = elem c $ map fst dict
-- parse a string literal
literal :: String -> Parser String
literal s [] = Nothing
literal s xs = if (head==s) then Just(head, tail)
else Just("", xs)
where (head,tail) = splitAt (length s) xs
-- parse and evaluate the following terminal symbols
digit = cndigit ==> cnDigitToInt
where cnDigitToInt d = head [snd x | x <- dict, fst x==d]
add = literal "加" ==> (\_ -> (+))
subt = literal "减" ==> (\_ -> (-))
mult = literal "乘以" ==> (\_ -> (*))
divi = literal "除以" ==> (\_ -> div)
tens = literal "十" ==> (\_ -> t)
where t a b = a * 10 + b
hndrds = literal "百" ==> (\_ -> h)
where h a b = a * 100 + b
-- inject a 1 into the parse in case people underspecify tens
inject1 :: Parser Integer
inject1 s = Just (1, s)
-- the grammar
expression = number <:> add <::> number |||
number <:> subt <::> number |||
number <:> mult <::> number |||
number <:> divi <::> number |||
number
number = digit <:> (hndrds <::> (digit <:> tens <::> digit)) |||
digit <:> tens <::> digit |||
digit |||
inject1 <:> tens <::> digit -- inject 1 to reuse the function
-- run the calculator as a repl
main = putStrLn "type ':q' to quit." >> repl
where
repl = do
input <- getLine
let result = printNum $ eval input
if ((== ":q") input)
then return ()
else putStrLn (input ++ "等于" ++ result) >> repl
-- call the grammar to parse and evaluate
eval s = case expression s of
Just (n,[]) -> n
Just (n,xs) -> error $ "Could not parse input, got stuck on "++xs
Nothing -> error $ "Could not parse input at all "++s
-- reencode a number into chinese
printNum x = h' ++ t' ++ o
where o = if ((h'/="" || t'/="") && tRest == 0) then "" else [intToCNDigit tRest]
h' = printDigit h "百"
t' = printDigit t "十"
printDigit d c | d==0 = ""
| d==1 && c=="百" = '一':c
| d==1 = c
| otherwise = intToCNDigit d:c
(t, tRest) = divMod hRest 10
(h, hRest) = divMod x 100
intToCNDigit d = head [fst x | x <- dict, snd x==d]
-- the combinators:
-- return the result of the parser only if
-- it also satisfies the given predicate - like `with` in ADP
infix 7 <==
(<==) :: Parser a -> (a -> Bool) -> Parser a
(m <== p) s = case m s of
Nothing -> Nothing
Just(a,s) -> if p a then Just(a,s) else Nothing
-- alternative/or combinator
infixl 3 |||
(|||) :: Parser a -> Parser a -> Parser a
(m ||| n) s = case m s of
Nothing -> n s
ms -> ms
-- next/sequence combinator
-- reverse polish notation needs just this:
-- testRPExp = digit <:> (digit <:> add)
infixl 6 <:>
(<:>) :: Parser a -> Parser (a -> b) -> Parser b
(m <:> n) s = case m s of
Nothing -> Nothing
Just (a, s') -> case n s' of
Nothing -> Nothing
Just (b, s2) -> Just (b a, s2)
-- next/sequence combinator, right side
-- infix notation needs this second combinator:
-- testExp = digit <:> add <::> digit
infixl 5 <::>
(<::>) :: Parser (a->b) -> Parser a -> Parser b
(m <::> n) s = case m s of
Nothing -> Nothing
Just (a, s') -> case n s' of
Nothing -> Nothing
Just (b, s2) -> Just (a b, s2)
-- evaluate a parse result :)
infixl 5 ==>
(==>) :: Parser a -> (a -> b) -> Parser b
(m ==> n) s = case m s of
Nothing -> Nothing
Just (a, s') -> Just (n a, s')
```
Running it:
```
┌─[linse@yolocat]─[~/test]
└──╼ ghc -o calc calc_own_combi.hs
[1 of 1] Compiling Main ( own_combi.hs, own_combi.o )
Linking calc ...
┌─[linse@yolocat]─[~/test]
└──╼ ./calc
type ':q' to quit.
二乘以八
二乘以八等于十六
:q
```
[Answer]
# Smalltalk (Smalltalk/X)
using a [packrat parser](http://scg.unibe.ch/research/helvetia/petitparser) (just a q&d hack, I guess, this could be done better, especially the number parsing; I was not 100% sure, when it is allowed to leave out zeros...).
Also, I don't understand what "零 or 〇 → 0" means; does it mean "it must support both" or "I can choose to support either"?
Anyway, if required, the d0 rule could be changed easily.
For readability, the code is not golfified.
```
"/ parsing digits
d0 := ($零 asParser ==> [:c|0]).
d1 := ($一 asParser ==> [:c|1]).
d2 := ($二 asParser ==> [:c|2]).
d3 := ($三 asParser ==> [:c|3]).
d4 := ($四 asParser ==> [:c|4]).
d5 := ($五 asParser ==> [:c|5]).
d6 := ($六 asParser ==> [:c|6]).
d7 := ($七 asParser ==> [:c|7]).
d8 := ($八 asParser ==> [:c|8]).
d9 := ($九 asParser ==> [:c|9]).
t:= $十 asParser.
h:= $百 asParser.
d := d1|d2|d3|d4|d5|d6|d7|d8|d9.
"/ parsing numbers
n :=
((d,h,d,t,d) ==> [:a| (a first*100)+(a third *10)+a fifth])
/ ((d,h,d,t) ==> [:a| (a first*100)+(a third *10)])
/ ((d,h,d) ==> [:a| (a first*100)+(a third)])
/ ((d,h) ==> [:a| a first*100])
/ ((d,t,d) ==> [:a| (a first*10)+(a third)])
/ ((d,t) ==> [:a| a first*10])
/ ((t,d) ==> [:a| a second+10])
/ d0
/ d
/ (t ==> [:c|10])
.
"/ operators
A:= ($加 asParser)==>[:c|#+].
S:= ($减 asParser)==>[:c|#-].
M := ($乘 asParser , $以 asParser)==>[:c|#*].
D:= ($除 asParser , $以 asParser)==>[:c|#/].
"/ times and quotient
T:= ((n,M,T) ==>[:a|(a first * a third)])
/ ((n,D,T) ==>[:a|(a first / a third)])
/ n
.
"/ sum and difference
E:=((T,A,E) ==>[:n|(n first + n third)])
/ ((T,S,E) ==>[:n|(n first - n third)])
/ T
.
"/ printing (number->string)
di:= #( $一 $二 $三 $四 $五 $六 $七 $八 $九).
P:=[:n|
n>=100
ifTrue:[ (di at:(n//100)),$百,(P value:(n\\100)) ]
ifFalse:[
n>20
ifTrue:[ (di at:(n//10)),$十,(P value:(n\\10)) ]
ifFalse:[
n>10
ifTrue:[$十,(P value:(n\\10))]
ifFalse:[
n==10
ifTrue:[$十]
ifFalse:[
n==0
ifTrue:[$零]
ifFalse:[(di at:n) ]]]]]].
"/ evaluate an expression and return numeric value
p:= (E end) ==> P.
"/ the calculator, parse, concatenate input,EQ,number string
calc:=[:s | s,'等于',(p parse:s)].
```
usage:
```
calc value:'二乘以八'.
```
-> '二乘以八等于十六'
[Answer]
I tried writing this one in python:
```
import compiler
# encoding: utf-8
# python chinese calculator,
c2e = {('1','一'),('2','二'),('3','三'),('4','四'),('5','五'),('6','六'),('7','七'),('8','八'),('9','九'),('0','零')}
def tochi(eq):
for en,ch in c2e:
eq.replace(en,ch)
return eq
def toen(eq):
for en,ch in c2e:
eq.replace(ch,en)
return eq
if __name__ == "__main__":
while True:
eqin = raw_input('Equation with chinese numbers: ')
eqin = toen(eqin)
eqout = compiler.parse(eqin)
eqout = tochi(eqout)
print eqout
```
] |
[Question]
[
It's time to make a more advanced program (rather than something simple, like printing some shape). You need a package manager for something, I guess.
First of all, if something wasn't defined, you are allowed to do anything, including destroying the computer (but please, don't, unless this will save your characters). After all, you will be using the package manager 100% correctly, so this won't happen. Who cares about security problems? It just has to be fast, like C programs.
The package manager should use STDIN and STDOUT as storage - that is, the database should be read from STDIN, and result database should be output to STDOUT, in true Unix style. The format of database is anything you want, as long you will be able to read it back.
The package manager shall support four commands. Typing unrecognized command is undefined, and anything can happen.
* `init` - outputs the empty database to be read by other commands. This shouldn't read the database state.
* `install x y z` - installs the programs `x y z`. If the program already exists, you can do anything
* `remove x y z` - removes the programs `x y z`. If the program doesn't exist, you can do anything.
* `list` - shows every program (with new line after every program). The list should be in alphabetical order. This mustn't output the database state.
The packages are only allowed to have lowercase ASCII letters (a-z). Anything else is undefined.
There is an example of example program:
```
$ ./lolmanager init > db
$ ./lolmanager install cat dog < db > db2
$ ./lolmanager remove dog < db2 > db
$ ./lolmanager list < db
cat
$ ./lolmanager install something else < db > db2
$ ./lolmanager list < db2
cat
else
something
$
```
The shortest code wins.
[Answer]
## GolfScript (23 chars)
```
n%"#{ARGV*'
'}"n/(;^$n*
```
My database format is the same as the list format.
I interpret the spec to allow assuming that the `init` command guarantees no input on stdin and no further command-line arguments, and that the `list` command guarantees no further command-line arguments. Then every command does exactly the same thing: xor the supplied database with the 2nd to nth command-line argument.
[Answer]
### GolfScript, 59 characters
```
[{;;[]`}:it{|`}:ll{-`}:ve{;$n*}:st];~"#{ARGV*' '}"' '%(-2>~
```
Implemented the first idea which came into my mind. The database format is simply a GolfScript array representation. Install/remove also handle the case when a program is already installed.
**Explanation**
```
# Define four functions for later use ([...]; simply removes them from the stack):
[
{;;[]`}:it # init -> discard arguments, discard db, create empty db
{|`}:ll # install -> add arguments to db (if not already there)
{-`}:ve # remove -> remove all arguments from db
{;$n*}:st # list -> discard arguments, sort, join with newline
];
~ # Parse db given on STDIN
"#{ARGV*' '}"' '% # Parse command line arguments into array
(-2> # Take first argument (command) and the last two chars from it
~ # Execute that command (i.e. "it" for "init", ...)
```
[Answer]
## Golf-Basic 84 for TI-84 Calculators, Character count: 84
```
:2_R:1_I:0_L:""_Str0i`Nd`Str0l`0i`Ng`Ad`Str0g`0l`Ai`S@N=2:Str0+S_Str0@N=1:""_Str0g`0
```
Hide the source code. Your teacher might think you're cheating :)
**Output**
```
?Init|db
?Install|db
?"CAT, DOG"
?List|db
CAT, DOG
?Remove|db
?"CAT, DOG"
?List|db
?Install|db
?"LOL"
?List|db
LOL
```
[Answer]
## J (~~127~~ 108)
Runs as a script (obviously). I could save some characters if I could assume it always receives an end-of-file even for `init`.
```
exit echo;,&LF&.>(LF cut stdin^:(-.A e.~<'init')''),`(*/@(~:/~)#[)`((/:{])@[)`[@.('irl'i.{.>2}A)[3}.A=:ARGV
```
[Answer]
# Ruby, 102 bytes
```
c,*a=$*
$/=?\0
puts c=~/it/?'':(i=STDIN.gets.split
case c
when/a/
a|i
when/v/
i-a
when/st/
i.sort
end)
```
Edit: Inspired by Howard, I replaced `init`, `install`, `remove` and `list` literals for some more general patterns: `/it/`, `/a/`, `/v/` and `/st/`.
] |
[Question]
[
## Multi palindromic numbers
Finding all number for which at least two\*\* representation are palindromic, with more than one\*\* characters, if in decimal, octal, hexadecimal, binary or in base64.
\*\* have to be editable, see *Variables* below.
**Edited:** After lot of reflexion about [comment from @DavidCarraher](https://codegolf.stackexchange.com/questions/15225/enumerate-all-number-that-are-palindromic-in-at-least-two-of-base-2-8-10-16-o#comment28254_15225http://), I found an *important* issue about the *range to be used*. Mostly in the goal of **reducing ratio operation/output**. For this, *variables* section of this question was modified.
### Details
Representation of numbers are:
* `binary` : 01
* `octal` : 01234567
* `decimal` : 0123456789
* `hexadecimal`: 0123456789abcdef (in *lower case*)
* `base64` : 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@\_ Nota: This representation is compatible with [bash](/questions/tagged/bash "show questions tagged 'bash'"): `printf "%o" $((64#r0r))` give `330033` (`r0r` is a palindrome in both *base64* and *octal*)
The ouput present first a count of palindromes, than all 5 variantes from smaller representation to bigger:
```
Count Base64 Hexa Decimal Octal Binary
3 11 41 65 101 1000001
3 33 c3 195 303 11000011
3 55 145 325 505 101000101
3 77 1c7 455 707 111000111
4 99 249 585 1111 1001001001
3 ll 555 1365 2525 10101010101
3 rr 6db 1755 3333 11011011011
3 JJ b6d 2925 5555 101101101101
3 ZL f6f 3951 7557 111101101111
4 __ fff 4095 7777 111111111111
4 101 1001 4097 10001 1000000000001
3 111 1041 4161 10101 1000001000001
3 202 2002 8194 20002 10000000000010
4 303 3003 12291 30003 11000000000011
3 333 30c3 12483 30303 11000011000011
```
Nota this sample display number that's palindromes in at least **`3`** representation, not `2`, see *Variables* below.
### Variables
* Minimum of palindrome length, default to `2`
* Minimum number of palindrome by number, default to `2 (/5)`. There are 5 representation. Print a number when at least 2 of them are palindromic.
* Range to check for: could be *from `1` to `2^31`* or smaller. This could be an array `BoundRange=(1,1000)` or two variables: `RangeSta=1 RangeEnd=1000`.
This variables have to be changeables in simple way (modification of code at only one place or given as argument).
### Output
No formating needed, only 6 colons, space separated will suffice.
```
2 9 9 9 11 1001
2 h 11 17 21 10001
2 r 1b 27 33 11011
2 x 21 33 41 100001
2 J 2d 45 55 101101
2 P 33 51 63 110011
2 _ 3f 63 77 111111
3 11 41 65 101 1000001
2 19 49 73 111 1001001
2 1l 55 85 125 1010101
```
### Limits (range)
There is no real consideration of maximum useable of the range as this is depending on language used, But a *range* have to be fixed:
* min: 1 (notation in octal!)
* max: depending on language used, but `2^31` seem to be an overall minimum.
For tests, the range could be fixed to somthing smaller...
### Goal
The more efficient algorithm with less operation count by line of output will win. (This may have to be explained)\*\*.
* Ratio **operation count / output line count**
* Shortness of code, but with readable variables ie: One variable is one. Regardless of his name length. (don't obfusc)
* Quickness of execution (comparission only by language, not accross different languages. Ie: I won't try to compare a [c](/questions/tagged/c "show questions tagged 'c'") version with a [bash](/questions/tagged/bash "show questions tagged 'bash'") one. )
### Operations count
The count of operation are mainly theorical. Meaning, *a simple conversion is one operation* whenever it is done by builtin functions, like `printf` or by more complex routine like `sub base` in [Dom Hastings's answer](https://codegolf.stackexchange.com/a/15238/9424)
\*\*As I don't know all languages, and there is some place to unusual ideas, subtles algorithms may need to be explained...
[Answer]
# Mathematica
`f[number,minPalindromeLength,minCount]`works as follows If `number` is a palindrome with `minPalindromeLength` in at least `minCount` bases, `f` returns the information about that number.
`g[max,minPalindromeLength,minCount]` makes an table of "palindrome numbers" from 1 through `max`.
```
f[number_,minPalindromeLength_:2,minCount_:2]:=Module[{print,palindromeQ,count,
convert64=Thread[Range[0,63]->Characters["0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_"]],
digits=IntegerDigits[number,#]&/@(bases={64,16,10,8,2})},
palindromeQ[dig_]:=(dig==Reverse[dig]);
count = Total@Boole[palindromeQ/@ Cases[digits,x_/;Length[x]>minPalindromeLength-1]];
If[count>minCount-1,Join[{count,Subscript[StringJoin[IntegerDigits[number,64]/.convert64],64]},BaseForm[number,#]&/@Rest[bases]],Sequence[]]];
g[max_,minPalindromeLength_:2,minCount_:2]:=
(Print["\nPalindromes: minPalindromeLength = ",minPalindromeLength "\tand minCount ", minCount ];
DeleteCases[Table[f[z,minPalindromeLength,minCount],{z,9,max}],Null]//Grid);
g[5000,2,3]
g[5000,3,3]
g[5000,4,2]
```

[Answer]
## Haskell
Total rewrite; complete new algorithm:
```
module Main where
import Data.List (foldl', group, unfoldr)
import qualified Data.Vector.Unboxed as V
import System.Environment (getArgs)
import System.Exit (exitFailure)
import System.IO (hPutStrLn, stderr)
bases :: [Integer]
bases = [64, 16, 10, 8, 2]
alphabet :: V.Vector Char
alphabet = V.fromList
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_"
fromBase :: Integer -> [Integer] -> Integer
fromBase base = foldl' ((+).(*base)) 0
toBase :: Integer -> Integer -> [Integer]
n `toBase` b = unfoldr digit n
where
digit 0 = Nothing
digit m = let (q,r) = m `divMod` b in Just (r,q)
formatPalindromic :: (Integer,Int) -> String
formatPalindromic (n,count) =
show count ++ concatMap (showDigits . (n `toBase`)) bases
where
showDigits = (' ':) . map digit . reverse
digit = (alphabet V.!) . fromInteger
genEvenPalendromes :: Integer -> [[Integer]]
genEvenPalendromes base = [1..] >>= sequence . flip replicate digits >>= asPal
where
digits = [0..base-1]
asPal (0:_) = []
asPal s = [s ++ reverse s]
genOddPalendromes :: Integer -> [[Integer]]
genOddPalendromes base = [1..] >>= sequence . flip replicate digits >>= makePals
where
digits = [0..base-1]
makePals (0:_) = []
makePals s = let r = reverse s in [ s ++ d : r | d <- digits ]
merge :: (Ord a) => [a] -> [a] -> [a]
merge as [] = as
merge [] bs = bs
merge as@(a:at) bs@(b:bt) | a <= b = a : merge at bs
| otherwise = b : merge as bt
allPalendromes :: Int -> Integer -> [Integer]
allPalendromes minLength base = merge (limit evens) (limit odds)
where
limit = map (fromBase base) . dropWhile ((< minLength) . length)
evens = genEvenPalendromes base
odds = genOddPalendromes base
allPalendromics :: Int -> Int -> [(Integer,Int)]
allPalendromics minRequired minLength =
onlyMultis $ countEm $ mergeEm $ genEm
where
genEm = map (allPalendromes minLength) bases
mergeEm = foldl' merge []
countEm = map (\s -> (head s, length s)) . group
onlyMultis = filter ((>= minRequired) . snd)
parseArgs :: IO (Int, Int, Maybe Integer)
parseArgs = do
args <- getArgs
case args of
[] -> return (2, 2, Nothing)
[r] -> return (read r, 2, Nothing)
[r,l] -> return (read r, read l, Nothing)
[r,l,m] -> return (read r, read l, Just $ read m)
_ -> do
hPutStrLn stderr "usage: multiple-palindromes-needed min-length max-value"
hPutStrLn stderr "-or- defaults to 2, 2, no-limit"
exitFailure
main :: IO ()
main = do
(minRequired, minLength, maxValue) <- parseArgs
let result = allPalendromics minRequired minLength
limit = maybe id (\v -> takeWhile ((<= v) . fst)) maxValue
mapM_ (putStrLn . formatPalindromic) $ limit result
```
Runs on my system (1.8 GHz Intel Core i7) in under 0.1s:
```
& ghc -o /tmp/palin -O -fforce-recomp -outputdir /tmp -Wall 15225-Palindromic.hs
& time ( /tmp/palin 2 2 20000000 | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2 19119 1241049 19140681 111010111 1001001000001000001001001
2 19899 1248249 19169865 111101111 1001001001000001001001001
2 19999 1249249 19173961 111111111 1001001001001001001001001
1149
real 0m0.071s
user 0m0.067s
sys 0m0.010s
```
Generates all solutions to 2, 3, 99 999 999 999 quickly:
```
& time ( /tmp/palin 2 3 99999999999 | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2 1nADADh 15e49e49d1 94029892049 1274447444721 1010111100100100111100100100111010001
2 1n@FK_h 15fea6efd1 94466666449 1277651567721 1010111111110101001101110111111010001
2 1rIGIr1 16ecaac6c1 98459895489 1335452543301 1011011101100101010101100011011000001
12495
real 0m7.866s
user 0m7.687s
sys 0m0.170s
```
Note: Unlike my last solution, this code has not been hand optimized at all: It is straight forward idiomatic Haskell (with the exception of `alphabet` being a `Vector`).
[Answer]
## Python
Rather straightforward; could be optimized somewhat. For example, the octal representation is calculated twice. (Still, I hope that's much faster than creating a base 64 representation in pure python.)
Also, all representations are calculated, even if after, say, 3 representations it is clear that there will not be enough palindromes. However, i feel that the code is much cleaner as it is.
```
mindigits, minpalins = 2, 3
print("Count Base64 Hexa Decimal Octal Binary")
from itertools import count
oct_to_64={"%02o"%i:"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_"[i] for i in range(64)}
def base64(i):
octalstring="{0:o}".format(i)
if len(octalstring) % 2:
octalstring = "0" + octalstring
return "".join(oct_to_64[octalstring[i:i+2]] for i in range(0,len(octalstring), 2))
encoders=[base64, "{0:x}".format, str, "{0:o}".format, "{0:b}".format]
for i in count(8**(mindigits-1)):
encodeds = [encoder(i) for encoder in encoders]
palindromes = [encoded for encoded in encodeds if encoded[::-1]==encoded and len(encoded)>=mindigits]
num_palins = len(palindromes)
if num_palins >= minpalins:
print("%-5s %-6s %-6s %-8s %-8s %s" % tuple([num_palins] + encodeds))
```
Output:
```
Count Base64 Hexa Decimal Octal Binary
3 11 41 65 101 1000001
3 33 c3 195 303 11000011
3 55 145 325 505 101000101
3 77 1c7 455 707 111000111
4 99 249 585 1111 1001001001
3 ll 555 1365 2525 10101010101
3 rr 6db 1755 3333 11011011011
3 JJ b6d 2925 5555 101101101101
3 ZL f6f 3951 7557 111101101111
4 __ fff 4095 7777 111111111111
4 101 1001 4097 10001 1000000000001
3 111 1041 4161 10101 1000001000001
3 202 2002 8194 20002 10000000000010
4 303 3003 12291 30003 11000000000011
3 333 30c3 12483 30303 11000011000011
3 404 4004 16388 40004 100000000000100
```
and so on...
[Answer]
## Perl
So I don't think this is necessarily efficient, but I guess it'll at least provide a benchmark for other Perl scripts! I originally got distracted by making the shortest code (should have RTFQ...). I imagine I could improve this more by replacing the manual base conversions <64 with sprintf so I might look at that later on.
```
# length of palindrome
$length = 2;
# minimum number of palindromes
$number = 2;
sub base {
($-, $base, $n) = @_;
do {
$n = (0..9,a..z,A..Z,'@',_)[$- % $base].$n
} while $- = $- / $base;
$n
}
while (++$i) {
@nums = map {
base($i, $_)
} (64, 16, 10, 8, 2);
$count = scalar grep { length >= $length && $_ eq scalar reverse $_ } @nums;
print "$count @nums\n"x($count >= $number)
}
```
Output:
```
2 9 9 9 11 1001
2 h 11 17 21 10001
2 r 1b 27 33 11011
2 x 21 33 41 100001
2 J 2d 45 55 101101
2 P 33 51 63 110011
2 _ 3f 63 77 111111
3 11 41 65 101 1000001
2 19 49 73 111 1001001
2 1l 55 85 125 1010101
2 1z 63 99 143 1100011
2 1T 77 119 167 1110111
2 1V 79 121 171 1111001
2 22 82 130 202 10000010
2 2p 99 153 231 10011001
2 2G aa 170 252 10101010
```
[Answer]
## D (thinking outside the box solution)
With the defaults (palindrome length >= 2, in bases >= 2) and the range 1..20\_000\_000 this takes ~8 ms on my 2 Ghz notebook. Most of the time (~6 ms) is spent for formatting and printing (to /dev/null). The actual result generation takes about 2 ms.
It works by first generating a list of all palindromes for each of the 5 bases at compile-time. The generator skips directly from one palindrome to the next by adding e.g. 110 to the number 7557 -> 7667. It's a bit like manually implementing a very weird *increment* instruction, but avoids checking ALL numbers by converting them to the respective base. (Only a tiny fraction of the numbers in the range 1..2³¹ are actually palindromes.)
At runtime these 5 lists are processed by finding the lowest value amongst them and counting the occurrences. The number of occurrences maps to the 'Count' field in the output and the value is the number that is a palindrome in one ore more representations. The value is then removed from the front of all the lists that had it.
All the occurrence counts and values that match the filter criteria are added to a result set and afterwards printed.
Lines of code: 280
```
import std.stdio, std.string, core.time, std.range, core.bitop, std.traits,
std.getopt, std.algorithm;
int main(string[] args) {
// Process command line
uint palindromeLength = 2;
uint numPalindromes = 2;
uint rangeLow = 1;
uint rangeHigh = 2^^31;
bool showHelp = false;
getopt(args,
"length", &palindromeLength,
"num", &numPalindromes,
"low", &rangeLow,
"high", &rangeHigh,
"help", &showHelp);
if (showHelp) {
writeln("Finds numbers that are palindromes in one or more bases.");
writeln("The compared bases are 2, 8, 10, 16 and 64.");
writeln("The following options are available (default values are given):");
writeln(" --length=2 Filter palindromes below a certain length.");
writeln(" --num=2 Only show numbers that are palindromes in as many bases.");
writeln(" --low=1 The first number to check (in decimal).");
writeln(" --high=2³¹ The last number to check (in decimal).");
writeln(" --help Show this help screen.");
return 0;
}
if (palindromeLength == 0) {
stderr.writeln("--length must be at least 1!");
return 1;
}
if (numPalindromes < 1 || numPalindromes > 5) {
stderr.writeln("--num must be in the range 1 to 5!");
return 1;
}
if (rangeLow > rangeHigh) {
stderr.writeln("--low must be less than --high!");
return 1;
}
// We check the --length and --low option here
auto restrictRange(immutable uint[] values, immutable size_t[] index) {
immutable(uint)[] result;
if (palindromeLength < index.length)
result = values[index[palindromeLength] .. $];
if (rangeLow < 2)
return result[rangeLow .. $];
return result.assumeSorted.upperBound(rangeLow - 1).release();
}
// Start of timing...
auto t1 = TickDuration.currSystemTick;
alias base2 = Palindromes!2.data;
alias base8 = Palindromes!8.data;
alias base10 = Palindromes!10.data;
alias base16 = Palindromes!16.data;
alias base64 = Palindromes!64.data;
// Use all palindrome lists that have at least one number in range.
auto use = [
restrictRange(base2.values, base2.lengthIndex),
restrictRange(base8.values, base8.lengthIndex),
restrictRange(base10.values, base10.lengthIndex),
restrictRange(base16.values, base16.lengthIndex),
restrictRange(base64.values, base64.lengthIndex),
].filter!(a => a.length > 0 && a[0] <= rangeHigh).array();
// This section will filter by --num and --high
struct Group {
uint count;
uint value;
}
Group[] groups;
groups.reserve (use.map!"a.length".reduce!"a + b"());
do {
// Find the lowest value and how often it occurs
uint low = uint.max;
uint lowCnt = 0;
foreach (u; use) {
if (u[0] < low) {
low = u[0];
lowCnt = 1;
} else if (u[0] == low) {
lowCnt++;
}
}
if (lowCnt >= numPalindromes)
groups ~= Group(lowCnt, low);
// Remove the value and dead lists
for (size_t i = 0; i < use.length;) {
if (use[i][0] == low) {
if (use[i].length == 1 || use[i][1] > rangeHigh) {
use[i] = use[$-1];
use.length--;
continue;
} else {
use[i] = use[i][1 .. $];
}
}
i++;
}
} while (use.length);
auto t2 = TickDuration.currSystemTick;
// Print the result
writefln("Lookup took %.2f ms", 0.000001 * (t2-t1).nsecs);
writeln("Count Base64 Hexa Decimal Octal Binary");
foreach (grp; groups)
writefln("%s %-6s %-8x %3$-10s %3$-11o %3$-32b",
grp.count, grp.value.toBase64, grp.value);
return 0;
}
char[] toBase64(uint value) {
string tab = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_";
char[6] result = " ";
size_t pos = 6;
do {
result[--pos] = tab[value % 64];
value /= 64;
} while (value);
return result[pos .. $].dup;
}
/**
* Finds all palindromes for a given number base in the range 2 to 256 within
* the limits given by data type ℕ, which can be either ubyte, ushort or uint.
*/
template Palindromes(uint base, ℕ = uint)
if (isUnsigned!ℕ && ℕ.sizeof <= 4 && base > 1 && base <= 256)
{
// The maximum number of digits for this base that can be represented in ℕ.
enum digits = {
uint result = 1;
ℕ power = 1;
while (ℕ.max / base >= power) {
result++;
power *= base;
}
return result;
}();
// Number of ways we can add a value to 0, keeping it a palindrome.
enum options = (digits + 1) / 2 * (digits / 2 + 1);
/* Number of ways to increment a number of `length` digits, keeping it a
* palindrome.
*/
enum optionsForLength(size_t length) { return (length + 1) / 2; }
/* Lookup array for the sum of the values of the digits at positions n
* and 0, used to increment one palindrome in this base to the next one.
*/
immutable increments = {
ℕ[options] result;
size_t idx = 0;
ℕ high = 1, low = 1;
foreach (length; 0 .. digits) {
ℕ h = high, l = low;
do {
result[idx++] = (h == l) ? h : cast(ℕ) (h + l);
h *= base;
l /= base;
} while (l);
if (length & 1)
low *= base;
else
high *= base;
}
return result;
}();
/* When a slot in a palindrome overflows, this array is used to reset
* the slot and all lesser slots much like when you do 999+1=1000.
*/
immutable resets = {
ℕ[options] result = 0;
uint idx = 0;
foreach (length; 1 .. digits + 1) {
foreach (i; 0 .. optionsForLength(length)) {
immutable prev = i ? result[idx - 1] : 0;
immutable curr = (base - 1) * increments[idx];
result[idx++] = cast(ℕ) (prev + curr);
}
}
return result;
}();
// The count of palindromes in this base for a given number of digits.
enum numPalindromesOfLengthUpTo(size_t digits) {
return base ^^ (digits / 2) - 1 + base ^^ ((digits + 1) / 2);
}
// The real number of palindromes in this base that fit into ℕ.
enum numPalindromes = {
static if (bsr(base) == bsf(base) && ℕ.sizeof * 8 % bsf(base) == 0) {
// All digits of this base fit evenly into ℕ.
return numPalindromesOfLengthUpTo(digits);
} else {
// Some palindromes with the most significant digit != 0
// cannot be represented and must be droped.
enum options = optionsForLength(digits);
auto remainder = ℕ.max;
size_t result = numPalindromesOfLengthUpTo(digits - 1);
foreach_reverse(i; 0 .. options) {
immutable increment = increments[$ - options + i];
auto n = remainder / increment;
remainder -= n * increment;
if (i == options - 1) n--;
if (i == 0) n++;
result += n * (base ^^ i);
}
return result;
}
}();
/* Structure that iterates over the palindromes in this base.
* To avoid overflow, an external check is required.
*/
struct PalindromeRange
{
private:
ubyte[(digits + 1) / 2] slots = 0;
uint offset = 0;
public:
uint width = 1;
ℕ front = 0;
void popFront() {
// Highest digit value in this base.
enum max = cast(ubyte) (base - 1);
size_t si = 0;
if (slots[0] >= max) {
do {
si++;
} while (si < slots.length && slots[si] >= max);
front -= resets[offset + si - 1];
slots[0 .. si] = 0;
if (si == optionsForLength(width)) {
offset += optionsForLength(width);
if (width++ == digits) return;
si = optionsForLength(width) - 1;
}
}
slots[si]++;
front += increments[offset + si];
}
}
struct PalindromeData {
ℕ[numPalindromes] values;
size_t[digits+1] lengthIndex;
}
immutable data = {
PalindromeData result;
uint width;
auto pr = PalindromeRange();
foreach (i; 0 .. numPalindromes) {
result.values[i] = pr.front;
if (width != pr.width) {
width = pr.width;
result.lengthIndex[width] = i;
}
pr.popFront();
}
return result;
}();
}
```
[Answer]
## Not an answer.
### This is not an answer to the question, but to other answers...
This is not regular on SE, but I think this could be usefull in the meaning of *PPCG*.
### First
I've found **12 495** numbers which are palindrome in at least two of all five representations and containing at least three characters, between `1` and `99 999 999 999`
Some samples:
```
printf "%o\n" 94466666449
1277651567721
echo $(( 64#1rIGIr1 ))
98459895489
printf "%o\n" 0x1557557551
1252725272521
```
My modified ([perl](/questions/tagged/perl "show questions tagged 'perl'")) version of [Dom Hastings's answer](https://codegolf.stackexchange.com/a/15238/9424) took ~90 seconds on my desktop...
Of course *original* version of same script is able to browse approx from `1` to `60 000` by using the same time, on same pc.
**Here is a need to think *out of the box...***
### My point of view:
My system is not so small:
```
CPU Intel(R) Core(TM)2 Duo CPU E8400 @ 3.00GHz
Dual core run on 64 bits GNU/Linux
With 4Gb RAM.
```
### Comparissions.
For making this something *equitable*, I will render outputs there to be able to make some comparissions.
For rendering output, I will use the following command:
```
time ( /tmp/palin-XXX.YY 20000000 2 2 | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
```
I will try to respect publication order.
**First:** [WolframH's Python answer](https://codegolf.stackexchange.com/a/15232/9424)
```
@@ -1 +1,3 @@
-mindigits, minpalins = 2, 3
+mindigits, minpalins, maxint = 2, 2, 20000000
@@ -4 +6 @@
-from itertools import count
@@ -15 +17 @@
-for i in count(8**(mindigits-1)):
+for i in range(8**(mindigits-1), maxint ):
```
Than:
```
time ( ./palin.py 20000000 2 2 | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2 19119 1241049 19140681 111010111 1001001000001000001001001
2 19899 1248249 19169865 111101111 1001001001000001001001001
2 19999 1249249 19173961 111111111 1001001001001001001001001
1150
real 3m0.768s
user 2m48.895s
sys 0m0.560s
```
**Second:** [Dom Hastings's perl answer](https://codegolf.stackexchange.com/a/15238/9424)
```
@@ -15 +15 @@
-while (++$i) {
+while (++$i<20000000) {
```
Give:
```
time ( perl ./palin-dom-b.pl | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2 19119 1241049 19140681 111010111 1001001000001000001001001
2 19899 1248249 19169865 111101111 1001001001000001001001001
2 19999 1249249 19173961 111111111 1001001001001001001001001
1149
real 14m58.174s
user 14m54.512s
sys 0m0.412s
```
**Third:** [David Carraher's Mathematica](https://codegolf.stackexchange.com/a/15235/9424)
Unfortunely, I don't know how to test this, but as I could read, there seem not to be different algorithm...
That's little a surprise, becaud David warned my about **maximum** and this is an important notion in this question.
**Fourth:** [MtnViewMark's Haskell](https://codegolf.stackexchange.com/a/15349/9424)
Whithout any modification and after compilation conforming to answer indication:
```
time ( ./palin.haskel | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2 19119 1241049 19140681 111010111 1001001000001000001001001
2 19899 1248249 19169865 111101111 1001001001000001001001001
2 19999 1249249 19173961 111111111 1001001001001001001001001
1149
real 0m26.631s
user 0m24.802s
sys 0m0.124s
```
Hmm, this seem to be very interesting, in that: *I didn't know `haskell` before*.
But this miss something in them of **operation/output**
### My results:
I've wrote two versions. The first prototype was bash (**yes I could be quicker using bash than a python version**;-):
```
time ( ./palin.sh 20000000 2 2 | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2 (19899) (1248249) (19169865) 111101111 1001001001000001001001001
2 (19999) (1249249) (19173961) 111111111 1001001001001001001001001
List len: 46572, Output len: 1149, Operations: 173548: ratio: 151.04
1150
real 1m40.052s
user 1m9.588s
sys 0m13.249s
```
... and this version is penalized by an operation counter: I count **173 548** operation for computing all values under all 5 base, from `1` to `20 000 000` **!!!**
And there is same work with a perl version:
```
time ( perl ./palin-d-shrink.pl 20000000 2 2 | tee >(tail -n3 >/dev/fd/3) | wc -l ) 3>&1
2 (19119) (1241049) (19140681) 111010111 1001001000001000001001001
2 (19899) (1248249) (19169865) 111101111 1001001001000001001001001
2 (19999) (1249249) (19173961) 111111111 1001001001001001001001001
1149
real 0m0.631s
user 0m0.612s
sys 0m0.016s
```
### Recap:
```
First python 3m0.768s
First perl 14m58.174s
Mathematica -- unknow (but seem not having less oper/lines ) --
Haskel 0m26.631s (this is compiled)
My bash prototyp 1m40.052s -> 1m16.067s see Nota under bash explanation
My perl (shrinked) 0m0.631s
```
**I insist: here is a need to think *out of the box*!!**
### End of BOUNTY: Bravo [MtnViewMark's Haskell](https://codegolf.stackexchange.com/a/15349/9424)
You was the first to rewrite your code to build all possible values in a *drawing fashion* first before searching for values that *match requirement*.
There is my [perl](/questions/tagged/perl "show questions tagged 'perl'") shrinked version:
```
#!/usr/bin/perl -w
use strict;my%vars;my$maxr=999999;my$minn=3;my$minl=3;$maxr=$1if$ARGV[0]&&$ARGV
[0]=~/^(\d+)$/;$minn=$1if$ARGV[1]&&$ARGV[1]=~/^(\d+)$/;my%value;$minl=$1if$ARGV
[2]&&$ARGV[2]=~/^(\d+)$/;my@digits=("0".."9","a".."z","A".."Z","@","_");my$i=0;
map{$value{$_}=$i++}@digits;sub base{my($n,$base)=@_;my$str='';do{$str=$digits[
$n%$base].$str}while$n=int($n/$base);$str}sub rbase{my($num,$base)=@_;my$out=0;
$out = $out * $base + $value{$1} while $num =~ s /^(.)//;$out}sub ebase{defined
($vars{$_[1]}{$_[0]})?$vars{$_[1]}{$_[0]}:"(".base(@_).")"}sub palinlst{my$base
=pop;my$maxst=base($maxr,$base);my$half=int(length($maxst)/2+.5);my($lasteven,$
lastodd)=do{length($maxst)%2? (rbase($digits[$base-1]x ($half-1), $base),rbase(
substr($maxst,0,$half), $base)): (rbase(substr($maxst, 0,$half),$base), rbase($
digits[$base-1]x$half, $base))}; foreach my$p($lasteven+1..$lastodd){ my$part1=
base($p,$base); my$part2=reverse $part1; my$str=$part1.substr($part2,1);my$val=
rbase($str,$base);if(length($str)>=$minl){$vars{$base}{$val}=$str;$vars{'count'
}{$val}++}};foreach my$p(1..$lasteven){my$part1=base($p,$base);my$part2=reverse
$part1;my$str=$part1.$part2; my$val=rbase($str,$base);if(length($str)>=$minl){$
vars{$base}{$val}=$str;$vars{'count'}{$val}++};$part2=reverse$part1;$str=$part1
.substr($part2,1);$val=rbase($str,$base);if(length($str)>=$minl){$vars{$base}{$
val}=$str;$vars{'count'}{$val}++;}}};for my$b(qw(2 8 10 16 64)){palinlst$b;}map
{printf"%-5s %-6s %-6s %-8s %-8s %s\n",$vars{'count'}{$_},ebase($_,64),ebase($_
,16),ebase($_,10),ebase($_,8),ebase($_,2);}grep{$vars{'count'}{$_}>=$minn}sort{
$a<=>$b}keys$vars{'count'}; # (C) 2013 - LGPL v2 - [[email protected]](/cdn-cgi/l/email-protection)
```
This is *shrinked*, not *obfuscated*! You could make them readable by running `perltidy`. I use this form to make *cut'n paste* easier.
```
perltidy < ./palin-shrinked.pl
```
I think this become readable.
### Explanation (using [bash](/questions/tagged/bash "show questions tagged 'bash'") for readabilty;-) ~~1m40.052s~~ 1m16.067s
As the *final* version is 139 lines long, I will split them there in order to explain each part:
```
#!/bin/bash
printf -v RANGEND "%u" ${1:-1000} # Max decimal value of palin to compute
MINCNT=${2:-2} # Minimum number of palindrome by output line default:2
MINLEN=${3:-2} # Minimum length of palindrome default:2
OUTFMT="%-5s %-6s %-6s %-8s %-8s %s\n"
opcount=0
shopt -s extglob
int2b64 () { local _i _func='{ local _lt=({0..9} {a..z} {A..Z} @ _) _var _out;
printf -v _var "%022o" $1 ;_out="'
for ((_i=0; _i<22; _i+=2)) ;do
printf -v _func '%s${_lt[8#${_var:%d:2}]}' "$_func" $_i
done
_func+='";printf ${2:+-v} $2 "%s" ${_out##*(0)}; }'
eval "${FUNCNAME}()" $_func
$FUNCNAME $@ ; }
int2bin () { local _fmt="" _i
for _i in {0..7}
do
fmt+="_var=\${_var//$_i/%s};"
done
printf -v fmt "$fmt\n" 000 001 010 011 100 101 110 111
eval "${FUNCNAME}()"'{ local _var;printf -v _var "%o" $1;
'${fmt}'printf ${2+-v} $2 "%s" ${_var##*(0)}; }'
$FUNCNAME $@ ; }
```
There is the first functions, I use the *trick* to re-define `$FUNCNAME` before first use.
```
rev() { local _func='{ printf ${2+-v} $2 "%s" ' _i
for ((_i=64;_i--;)) do _func+='${1:'$_i':1}' ; done
eval "rev()" $_func ';}'; rev $@ ; }
int2hex() { printf ${2+-v} $2 "%x" $1 ; }
int2oct() { printf ${2+-v} $2 "%o" $1 ; }
int2dec() { printf ${2+-v} $2 "%u" $1 ; }
```
Some more function, easy to understand, The **hard** part is comming now:
```
makePalinList() {
local max=${1:-1000} vmax palin
local forms=('' '' bin '' '' '' '' '' oct '' dec '' '' '' '' '' hex
''{,,,}{,,}{,,}{,}b64)
local digmax=('' '' 1 '' '' '' '' '' 7 '' 9 '' '' '' '' '' f
''{,,,}{,,}{,,}{,}_)
local cmd=${forms[$2]}
((opcount+=5))
int2$cmd $max vmax
```
with this, I make that `int$form[64]` will be expanded before execution to `intb64` (under bash, there is no need to use `eval` there).
`vmax` is the max value to render. So now we have to compute each case (even and odd string length):
```
local vpart=$((5*${#vmax}+5))
local vpskel=${vmax:0:${vpart%?}}
local lasteven lastodd
if ((${#vmax}%2)) ;then
lastodd=$(($2#$vpskel))
vpskel=${vpskel:1}
lasteven=$(($2#${vpskel//?/${digmax[$2]}}))
else
lasteven=$(($2#$vpskel))
lastodd=$(($2#${vpskel//?/${digmax[$2]}}))
fi
```
I will let you think about all this... Now we have to compute *start of ranges*
```
local firsteven=$(((MINLEN+1)/2)) firstodd=$((MINLEN/2+1))
printf -v firsteven "%${firsteven}s" ""
printf -v firstodd "%${firstodd}s" ""
firsteven=${firsteven// /0}
firsteven=${firsteven/0/1}
firsteven=$(($2#$firsteven))
firstodd=${firstodd// /0}
firstodd=${firstodd/0/1}
firstodd=$(($2#$firstodd))
```
Wow.
**Nota:** My previous (not published) version was not using `firsteven` and `firstodd` but simply `1..` and a *in loop* condition: `${#palin} -ge $MAXLEN` before each `printf -v lst$cmd[...`.
Adding this and the following `if` at end of next part improved my script a lot: from ~100 seconds, my script only take 76 seconds now for computing previous test `20000000 2 2`
Now there could be an issue where next `if` could *not* match:
```
if [ $firstodd -lt $lasteven ] ;then
for ((i=firsteven;i<firstodd;i++)) ;do
int2$cmd $i b
rev $b r
palin=$b$r
printf -v lst$cmd[$(($2#$palin))] $palin
((counts[$(($2#$palin))]++))
((opcount+=3))
done
for ((i=firstodd;i<=lasteven;i++)) ;do
int2$cmd $i b
rev $b r
palin=$b$r
printf -v lst$cmd[$(($2#$palin))] $palin
((counts[$(($2#$palin))]++))
palin=$b${r:1}
printf -v lst$cmd[$(($2#$palin))] $palin
((counts[$(($2#$palin))]++))
((opcount+=4))
done
for ((i=lasteven+1;i<=lastodd;i++)) ;do
int2$cmd $i b
rev $b r
palin=$b${r:1}
printf -v lst$cmd[$(($2#$palin))] $palin
((counts[$(($2#$palin))]++))
((opcount+=4))
done
```
And if *else*:
```
else
for ((i=firsteven;i<=lasteven;i++)) ;do
int2$cmd $i b
rev $b r
palin=$b$r
printf -v lst$cmd[$(($2#$palin))] $palin
((counts[$(($2#$palin))]++))
((opcount+=3))
done
for ((i=firstodd;i<=lastodd;i++)) ;do
int2$cmd $i b
rev $b r
palin=$b${r:1}
printf -v lst$cmd[$(($2#$palin))] $palin
((counts[$(($2#$palin))]++))
done
fi
```
That's all (for now)...
```
}
for base in 2 8 10 16 64; do makePalinList $RANGEND $base ;done
```
Now we just have to print all values (adding parenthesis if value have to be computer -> ie not already exist -> ie not match requirement.)...
```
lines=0;for i in ${!counts[@]};do
[ ${counts[i]} -ge $MINCNT ] && \
printf "%-5s %-6s %-6s %-8s %-8s %s\n" ${counts[i]} \
${lstb64[i]:-($(int2b64 $i))} \
${lsthex[i]:-($(int2hex $i))} \
${lstdec[i]:-($i)} \
${lstoct[i]:-($(int2oct $i))} \
${lstbin[i]:-($(int2bin $i))} && ((lines++))
done
if [ $lines -gt 0 ] ;then ratio=000$((opcount*1000/lines))
printf "List len: %s, Output len: %d, Operations: %d: ratio: %.2f\n" \
${#counts[@]} $lines $opcount ${ratio:0:${#ratio}-3}.${ratio:${#ratio}-3}
else echo no output; fi
```
Ok, there is a zipped version of this bash script, to make *cut'n paste* easy:
```
#!/usr/bin/perl -w
my$u="";open my$st,"|gunzip";sub d{my$l=pack("c",32+.75*length($_[0]));print$st
unpack("u",$l.$_[0]);"";};while(<DATA>){tr#A-Za-z0-9+/##cd; tr#A-Za-z0-9+/# -_#
;$u.=$_;while($u=~s/(.{80})/d($1)/egx){};};d($u);__DATA__
H4sIAHg8jlICA9VX227bRhB9Fr9iQq1C0jLF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Kt9hpj4gbTUQpz6Eq6XLOsjxYpJLki
eFa6TaOMPtdqbHSMvwa3lE9QO2HCTYOty9fV0DEsHqBYK9HliuXimoRqVaMKAlMZN7AaMXxmVfWQLELi
ZC2Mw5Zsy6EGy7LAstl31m3LebYsKaknagqqoGrrXfTO6j52i+1qXCJXaXIP9QqYUQ6kzieYyKQBpSdf
Croe+rWDXvih0vPC4bB8Ifb28z6EmZwSNWsGGzkSdcAnM1KNa8ajLOea96XPQtAwJiDvpLSui+cs6wpx
JyqJ+lk84XPyjdQJQjj+wa/C7Qbxg4RS4xcb8Uj+y3SdHqKromjoVIT9o03/7yNpatPhRH4xCf53mfwj
bkxrE7CiM4X7jicgyjtMFy6Ad37ngO0R74v2Wgog1cmICAVPQCn81JJhR86BRJ9KijelA5cTVvXlWNiK
cjacMDAfKRB5TsLC9vYtPNQ96ivHln0cVCMFkoKtBo7Hpk706uhCQsNoBLBFaQvgsCOAbU0pELZmsedp
q/EWaF8N+6Q9wzx+IYAx6brgRvBeniwUWePFPJKQg13X9U2Qh6mP7Rmp0+yId2uWEN5/c6piP/AcOEZS
juFLeX4U4wWO11SgJRkfjyU03o7cJWfwQR5Ein6zTZVLpLSMq1KJ9zl9ccvMEzaqptuTCn+Ygc5XKSRp
eZb1eHL9DRLsWT9gDwAA
```
You could simply run:
```
perl >/tmp/palin-bash.sh
```
than paste previous script into your console.
[Answer]
## GolfScript 94
Didn't do the formatting really, but this works in GolfScript. Doing the formatting would probably add 20-30 characters.
```
~:j;:i;
10 5?,
{[2 8 10 16 64]\{\base}+%}%
{{.,i(>\{.,2<{;1.(}{(\)@=}if}do`1`=&}%{+}*j(>},
{p}%
```
This also limits the numbers to 10000 (in decimal). That number can be changed, of course, to the maximum integer, but this runs pretty quickly as is.
Example call: `echo '3 2' | ruby golfscript.rb h.gs`
Output:
```
[[1 0 0 0 0 0 0 0 0 1] [1 0 0 1] [5 1 3] [2 0 1] [8 1]]
[[1 0 0 1 0 0 1 0 0 1] [1 1 1 1] [5 8 5] [2 4 9] [9 9]]
[[1 1 0 0 0 0 0 0 0 1 1] [3 0 0 3] [1 5 3 9] [6 0 3] [24 3]]
[[1 1 0 1 1 0 1 1 0 1 1] [3 3 3 3] [1 7 5 5] [6 13 11] [27 27]]
[[1 0 1 0 0 0 0 0 0 1 0 1] [5 0 0 5] [2 5 6 5] [10 0 5] [40 5]]
[[1 0 1 0 1 0 0 1 0 1 0 1] [5 2 2 5] [2 7 0 9] [10 9 5] [42 21]]
...
```
] |
[Question]
[
The world's changing to a new time system! We need to update our computer programs. Given an input of epoch time (number of seconds since January 1st, 1970 00:00), print out a time in the new Noxu date-time format.
864 seconds make one Fluffster. 100 Fluffsters make a Skizzle. There are 4 Skizzles in one Zestpond. Their names are Looplab, Sevit, Hexteria, and Sinpad. There are 91 Zestponds in one Lulerain.
The format is Lulerain Zestpond-Skizzle-Fluffster. Fluffsters are rounded to two decimal places. An example would be `50 13-Sevit-40.90`.
Given that epoch 0 was `0 0-Looplab-00.00`, create a program that takes input either via stdin or as a command line argument of any epoch time between 0 and 2^32, and prints out the Noxu equivalent.
### Time of edit:
```
1357510372 -> 43 14-Sinpad-92.56
```
### Random test data:
```
675416077 -> 21 43-Sevit-31.57
330585453 -> 10 46-Hexteria-22.05
1328127085 -> 42 20-Sinpad-84.13
837779784 -> 26 58-Looplab-52.53
1240280676 -> 39 39-Sinpad-10.04
122646385 -> 3 81-Sinpad-51.83
1311245658 -> 41 63-Looplab-45.44
57792972 -> 1 76-Looplab-90.01
788388068 -> 25 6-Looplab-86.19
304341865 -> 9 61-Hexteria-47.53
417857784 -> 13 26-Looplab-31.69
671276878 -> 21 31-Sevit-40.83
1259758896 -> 40 5-Looplab-54.28
604286664 -> 19 19-Hexteria-5.86
646395018 -> 20 50-Sevit-42.38
563025133 -> 17 82-Looplab-49.46
96133144 -> 3 5-Looplab-65.21
101542552 -> 3 20-Sinpad-26.10
1006825856 -> 32 1-Sevit-7.70
928867348 -> 29 48-Hexteria-77.95
1235022079 -> 39 24-Hexteria-23.70
439505287 -> 13 88-Hexteria-86.67
99686711 -> 3 15-Sevit-78.14
379859609 -> 12 7-Looplab-52.33
1167091685 -> 37 10-Looplab-0.56
612032437 -> 19 41-Sinpad-70.88
503040778 -> 15 90-Hexteria-23.12
1084809411 -> 34 44-Sinpad-66.45
1105664386 -> 35 14-Sevit-4.15
197303893 -> 6 24-Sinpad-60.99
368559287 -> 11 65-Sevit-73.25
686824300 -> 21 76-Sevit-35.53
196468204 -> 6 22-Sevit-93.75
673542185 -> 21 37-Sinpad-62.71
993063782 -> 31 52-Sevit-79.38
270951743 -> 8 56-Looplab-1.55
1074506753 -> 34 15-Looplab-42.08
198143696 -> 6 27-Sevit-32.98
539601298 -> 17 14-Sevit-38.54
110090607 -> 3 45-Hexteria-19.68
276492708 -> 8 72-Looplab-14.71
113389138 -> 3 55-Looplab-37.43
571578220 -> 18 15-Sinpad-48.87
1238516450 -> 39 34-Hexteria-68.11
742293312 -> 23 54-Sinpad-35.78
1031929490 -> 32 73-Sinpad-62.84
503091914 -> 15 90-Hexteria-82.31
264094386 -> 8 36-Looplab-64.80
483820698 -> 15 34-Sinpad-77.66
548410387 -> 17 39-Sinpad-34.24
```
[Answer]
# APL, 87
```
t[3]←(1+3⌷t←137 91 4 100⊤⍎2⍕⎕÷864)⌷'Looplab' 'Sevit' 'Hexteria' 'Sinpad'
' '⎕R'-'⍕t
```
APL has an advantage in these time system conversion challenges due to the built-in encode function, at the cost of expensive string manipuation
**Explanation**
(using `1357510372` as example)
`⎕÷864` takes user input from screen, divide by 864 (`1571192.56018519`)
`⍎2⍕` and round to 2 dp. (`1571192.56`)
`137 91 4 100⊤` Then, converts to Noxu Time System (`43 14 3 92.56`)
`t←` and assign that to variable `t`.
`1+3⌷` take the 3rd item from `t`, add 1 to account for 1-based indexing, (`4`)
`(`...`)⌷'Looplab' 'Sevit' 'Hexteria' 'Sinpad'` convert to Skizzle name, (`Sinpad`)
`t[3]←` and finally plug back into the 3rd item of `t`.
`⍕t` Convert `t` to a string representation, (`43 14 Sinpad 92.56`)
`' '⎕R'-'` and replaces 2 spaces with a dash (`43 14-Sinpad-92.56`)
[Answer]
# dc - 81
```
2k864/0k100~[Looplab]0:a[Sevit]1:a[Hexteria]2:a[Sinpad]3:ar4~;ar91~rn32Pn45dPrnPp
```
Expects the epoch time already on the stack so invoke as, e.g.
```
dc -e `date +%s` -e '2k864/0k100~[Looplab]0:a[Sevit]1:a[Hexteria]2:a[Sinpad]3:ar4~;ar91~rn32Pn45dPrnPp'
```
to get the current Noxu time or add one character to accept the time from stdin
```
?2k864/0k100~[Looplab]0:a[Sevit]1:a[Hexteria]2:a[Sinpad]3:ar4~;ar91~rn32Pn45dPrnPp
```
## annotated version
```
2 k # set the precision to 2 decimal places
864 / # divide the number of seconds by 864 to get fluffsters
0 k # set the precision back to 0 decimal places
100 ~ # divrem by 100; fluffsters are at the top skizzles under it
[Looplab] 0 :a # set a[0] to the string Looplab
[Sevit] 1 :a # set a[1] to Sevit
[Hexteria] 2 :a # set a[2] to Hexteria
[Sinpad] 3 :a # set a[3] to Sinpad
r # swap fluffsters and skizzles on the stack
4 ~ # divrem the skizzles by 4; skizzles on top zestpond under it
;a # use the skizzle as an index into a
r # swap the skizzle string and zestponds
91 ~ # divrem the zestponds by 91; zestponds on top lulerain under
r # swap zestponds and lulerains
# now the stack has (from top to bottom)
# lulerains
# zestponds
# skizzle (as the name)
# fluffster
n # pop and print the lulerains (without a newline)
32 P # print a space character
n # pop and print the zestponds
45 d P # print a - and leave 45 on the top of the stack
r # swap the 45 and the skizzle name
n # pop and print the skizzle name
P # print a - from the 45 that was on the stack
p # finally print the fluffster (with a newline)
```
When the number of fluffsters is less than 1 there is no leading zero printed, to get the leading zero, it is
```
2k864/0k100~[Looplab]0:a[Sevit]1:a[Hexteria]2:a[Sinpad]3:ar4~;ar91~rn32Pn45dPrnPd[0n]sb1>bp
```
at a cost of 10 extra characters (`d[0n]sb1>b`)
[Answer]
## Mathematica 152
Still has some format issues. Spaces added for clarity
```
Flatten@{#[[5]], {Looplab, Sevit, Hexteria, Sinpad}[[#[[4, 2]] + 1]],
N[#[[3, 2]] + #[[2, 2]]/864, 4]} &@
FoldList[QuotientRemainder[#1[[1]], #2] &, {#, 0}, {864, 100, 4, 91}]&
```
[Answer]
## **Ruby, ~~114~~ 112**
```
x=gets.to_f
puts'%d %d-%s-%.2f'%[x/d=91*c=4*b=86400,(x%=d)/c,%w[Looplab Sevit Hexteria Sinpad][x%c/b],x%c%b/864]
```
Meh. Basically grc's solution but with inline assignments.
Edit: Saved 2 chars by changing `to_i` to `to_f` so I don't need the float literal later.
[Answer]
## Python, 123
```
x=input()
b=86400
c=b*4
d=c*91
print x/d,'%d-%s-%.2f'%(x%d/c,['Looplab','Sevit','Hexteria','Sinpad'][x%d%c/b],x%d%c%b/864.)
```
] |
[Question]
[
How many ways are there to place a black and a white knight on an N \* M chessboard such that they do not attack each other?
A knight can move two squares horizontally and one square vertically, or two squares vertically and one square horizontally.
The knights have to be placed on different squares and the knights attack each other if one can reach the other in one move.
## Input:
The first line contains the number of test cases T. Each of the next T lines contains two integers N and M, representing the dimensions of the board.
## Output:
Output T lines, one for each test case, each containing the required answer for the corresponding test case.
**Sample input**:
```
3
2 2
2 3
4 5
```
**Sample output**:
```
12
26
312
```
**Constraints**
```
1 <= T <= 10000
1 <= N,M <= 100000
time limit 1 sec
```
**Source Limit:**
```
50000 Bytes
```
**Winning criteria**
```
Shortest code which runs with specified time limit decides the winner
```
i ll leave two days time for more users to try from today
[Answer]
# GNU Octave, 55 56 58 78 87\* 93 chars
```
a=t(:,1);b=t(:,2);-4*max(2*(g=a.*b)-3*(a+b)+4,0)+g.*--g
```
Octave doesn't take input from STDIN, so you've got to provide the input in the program:
```
t = [
1 7;
2 2;
2 3;
4 5;
5000 6000
]; % test cases
a=t(:,1);b=t(:,2);-4*max(2*(g=a.*b)-3*(a+b)+4,0)+g.*--g
```
The logic is as follows:
`nchoosek(n*m, 2)` gives us the number of combinations of two positions we can have on a N\*M board. We then multiply it by two since we have two different knights.
Then we work out how many 3\*2 blocks fit in an N\*M board. For each 3\*2 block there are 4 different positions our knights can be attacking each other. So we multiply it by 4 and subtract it from the value we calculated above.
\*thanks to a simplification of the nchoosek I shamelessly stole from Matt.
## Edit
I've just tested this on my laptop to make sure it meets the time requirements.
It will compute 500,000 10,000,000 test cases in an average of 0.918787 0.231201 seconds
[Answer]
# Python 105 119 112 104
```
for a,b in[map(int,raw_input().split())for i in[1]*input()]:print a*b*(a*b-1)-4*(max(2*a*b-3*(a+b)+4,0))
```
This uses the same approach as Griffin's solution.
Now appropriately handles boards of size 1xn
[Answer]
# Mathematica 55 50 38 41
**Second attempt**
This is my rendering, in Mathematica, of @Matt's solution.
Credit for the underlying reasoning goes to Matt.
Griffin helped me understand how Matt's approach works.
It is faster than my first approach approach but still too slow to satisfy the time constraints for boards with 10^5\*10^5 cells. The pure function (38 chars) is defined as follows:
```
#1 #2 (#1 #2-1)-4 Max[2 #1 #2-3 (#1+#2)+4,0]&
```
**Usage**
```
#1 #2 (#1 #2-1)-4 Max[2 #1 #2-3 (#1+#2)+4,0]& @@@ {{2, 2}, {2, 3}, {4, 5}}
(* out *)
{12, 26, 312}
```
The symbols, `@@@`, apply the function to the list. I included them in the character count.
---
**First Attempt: 50 chars but really, really slow.**
I'm including it because it may be of interest to some readers.
Mathematica doesn't take input from STDIN so I used an input more to its liking. There is no need to input the number of inputs; MMA will simply act on whatever number it is given.
**Code**
```
#1*#2*(#1*#2-1)-2 EdgeCount[#1~KnightTourGraph~#2] &
```
---
**Usage** (with spaces for readability).
```
#1*#2*(#1*#2 - 1) - 2 EdgeCount[#1~KnightTourGraph~#2] &; @@@ {{2,2}, {2,3}, {4,5}}
(* out *)
{12, 26, 312}
```
---
**Explanation**
Below is a graph of possible knight moves in a 4 by 5 chessboard.
```
k = KnightTourGraph[i, j, PlotLabel -> Subscript[K, i, j]]
```

There are `20*19 = 380` ways to arrange the black and white knight on the board.
Below is the adjacency matrix:
```
AdjacencyMatrix[k] // MatrixForm
```

There are `68` cases in which the knights are in an attacking position. This corresponds tohow many one's there are in the matrix. It also happens to equal two times the number of edges and sum of the degrees of the vertices.
```
t = 2*EdgeCount[k]
(* out *)
68
```
Finally, `380-68 = 312`.
---
**Timing**
It takes just under one second to calculate the answer for all grids up to 15 by 15.
Note: `312` is in row 4, column 5.

[Answer]
# C++, 232 250 228 192 173 characters
```
#include<iostream>
int main(){long long n,x,y,i;for(std::cin>>n;n--;)std::cin>>x>>y,i=(x*2-2)*(y-2<0?0:y-2)+(y*2-2)*(x-2<0?0:x-2)<<1,x*=y,std::cout<<x*x-x-i<<"\n";return 0;}
```
[SEE IT RUN](http://ideone.com/pXXdb)
I don't know what hardware ideone uses, but that can run for a 10000x10000 board 10000 times in .2 seconds.
How I simplified the problem:
I started out trying to find ways I could divide the board into known regions, with a certain density of bad positions per square. The simplest case is that if there are no edges within 2 squares of a square, that square has 8 possible failing positions. This turned out to be really complicated near the edges of the board where more than 2 edges can sometimes come into play (if, for example, you have a board that's only 2 wide), so I decided to try to simplify it based on direction, which turned out to be very easy.
First, I considered just one direction. On a chessboard of irrelevant length, how many moves are eliminated by the introduction of one unit of width? I made a table:
```
Width of board Number of positions eliminated
1 0
2 2
3 4
4 6
N 2N-2
```
I used my E=2N-2 formula along with the knowledge that for a board of length L, L-2 rows are viable (and thus count towards the exclusion count).
The program, conceptually, makes 4 sweeps, one in each direction (in practice it does 2, and multiplies by 2. It's a shortcut that works because of symmetry). Each sweep represents the moves excluded that tend in the direction of the sweep. The program then sums up each of the sweeps and subtracts from the total number of possible combinations.
Knight placement is random, but two knights cannot occupy the same space. Therefore, the total number of positions you can place a knight is the total numbers of squares the first time, then the number of squares minus one the second time (since there is a square that's taken).
# EDIT 1
fixed overflow, fixed forgetting to substract somewhere causing incorrect answers with a dimension of 1. Also swapped out 31's for 63's in bit twiddling since it uses 64 bit data types now
# EDIT 2
shortened further (introduced branching D: the non-branching version is 6 characters longer.)
# GOLF SCORECARD
* removed unnecessary clause: `(~u>>31&(x<<1)-2)` became `((x*2)-2)` in 2 places, saved 16 characters (234)
* swapped `~u>>63&u` for `u<0?0:u` in 2 places, saving 2 characters (232)
* swapped `x-2<0?0:x-2` for `u<0?0:u` and removed definition of u `u=x-2,` in 2 places, saving 4 characters (228, shorter than original solution)
* removed function f and moved functionality into main, saved 28 characters (200)
* removed `using namespace std;` and used std::cout, std::cin, and "\n", saved 5 characters (195)
* changed `std::cin>>n;for(;n>0;--n)` to `for(std::cin>>n;n;--n)`, saved 3 characters (192)
* removed `typedef long long L;` since its only used in one place now, saved 12 characters (180)
* removed 4 parens from statements like `((x*2)-2)`, saved 4 characters (176)
* removed brackets from loop by using commas instead of semicolons, compressed loop condition from `std::cin>>n;n;--n` to `std::cin>>n;n--;`, saved 3 characters (173)
[Answer]
# Go
```
package main
import "fmt"
func main() {
var N int
fmt.Scanln(&N)
for ; N > 0; N-- {
var m, n int64
fmt.Scanln(&m, &n)
grid := m*n
total := grid*(grid-1)
if m > 2 && n > 1 {
total -= (m - 2)*(n - 1) * 4
}
if n > 2 && m > 1 {
total -= (n - 2)*(m - 1) * 4
}
fmt.Println(total)
}
}
```
## Explanation
* `grid` is number of grid
* `total` is initialized as all the possible ways the knights could be placed. Since they have to be different grids, `grid * (grid - 1)`
* Now we exclude the number of ways they may attack each other
+ Their position could be two squares difference horizontally and one square vertically. The number of ways is `(m - 2)*(n - 1)` when `m > 2 && n > 1`. The left can be higher of lower then the right, so `*2`. White and black are exchangable, so `*2` again.
+ Similar to the situation for two squares vertically and one square hotizontally
## Timing
* 4 `int64` multiplication and 7 `int64` plus/minus operation, should be done in 1 second.
] |
[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 6 years ago.
[Improve this question](/posts/4422/edit)
The challenge is to write an [acrostic](http://en.wikipedia.org/wiki/Acrostic) piece of code.
When read normally (horizontally), the code should take an input string and remove all but the first character on each line. For example, the input:
```
float
or and
ord
line
bool var
auto
real
```
Output:
```
foo bar
```
In addition to this, the code also must contain valid code when run vertically. Such that applying the horizontal code on itself yields a new piece of valid code in a different language.
**Rules/Restrictions:**
* Each horizontal line must contain at least 2 non-whitespace characters
* The vertical code cannot use newlines.
* The vertical code must be in a different language from the horizontal language, preferably something entirely different
* The code does not have to be a complete program (doesn't need main function, etc)
What the vertical code does is up to you, although the goal is to have it do something interesting. Having it do nothing is not interesting.
**Easy Mode:**
* You may use the same language both horizontally and vertically
* No restrictions on language choice
**Hard mode:**
* No comments
* Both codes should compile and run (main function, etc)
* Horizontal code contains exactly 1 word per line
[Answer]
## Brainfuck -> Ruby
```
e,
v[
a.
l>
"+
a[
=-<,----------
[>
i+
=<
0[-]
]>
*]
3,
e]
4[
;g
"4
+d
$)
<^
.%
b$
y@
ta
el
sD
.{
m[
a}
p]
{.
|d
bA
|:)
{y
?T
.K
,s
"+
pG
up
th
c}
P
a$
[v
iF
]o
"d
,8
?t
,=
,h
"3
ay
[&
i*
]H
=s
gj
e9
t,
c<
"D
,d
?`
[q
,z
")
wT
hx
ie
lz
eW
>
a$
[^
i!
];
>Y
0q
"#
,T
?X
]A
,b
"J
e$
n#
ds
"K
,$
?}
<?
,.
"e
iJ
-W
=k
1B
"&
,J
?g
>.
,>
"/
i@
+/
=s
1v
"E
,)
?.
+8
,v
"7
aS
[b
i$
]#
+5
=m
1w
"3
,*
?u
-f
,Z
"I
aW
[U
i%
]3
-v
=T
1E
":
}G
[;
b2
]@
};
*/
"+
;M
"B]
```
Horizontal is this little gem:
```
,[.>+[-<,----------[>+<[-]]>],]
```
And Vertical is this:
```
eval"a=[i=0]*3e4;"+$<.bytes.map{|b|{?.,"putc a[i]",?,,"a[i]=getc",?[,"while a[i]>0",?],"end",?<,"i-=1",?>,"i+=1",?+,"a[i]+=1",?-,"a[i]-=1"}[b]}*";"
```
Which is a brainfuck interpreter stolen from [this question.](https://codegolf.stackexchange.com/a/253/2718) It qualifies for all of the hard mode criteria except the no comments bit, which I don't think is really fair to apply to brainfuck, or pretty much nothing but BF->BF would be possible.
Horizontal program runs till EOF(0) is read. Assumes newline at end of file.
[Answer]
# Perl -> HQ9+
Any verbose target language results in huge and unreadable code (IMHO), so in the interest of the reader I'll keep it short:
```
+print/(^.)/for<>
```
[Answer]
## Befunge-93 (main program) -> C (vertical program)
```
>~:25*-v
m^>>>>v,_@
a^^...~
i^^...:
n^^...2
(^^...5
i^^...*
,^^...-
j^^<<<_$v
)^<<<<<<<
{|
f|
o|
r|
(|
i|
=|
0|
;|
i|
<|
6|
4|
;|
i|
+|
+|
)|
{|
f|
o|
r|
(|
j|
=|
0|
;|
j|
<|
6|
4|
;|
j|
+|
+|
)|
p|
u|
t|
c|
h|
a|
r|
(|
i|
&|
j|
?|
3|
2|
:|
4|
6|
)|
;|
p|
u|
t|
c|
h|
a|
r|
(|
1|
0|
)|
;|
}|
}|
```
The main program is a Befunge-93 code which does the task and ends by reading a blank line.
The vertical program is in C which prints a Sierpinski triangle of depth 4 with '.' characters.
```
main(i,j){for(i=0;i<64;i++){for(j=0;j<64;j++)putchar(i&j?32:46);putchar(10);}}
```
I think I met all rules and restrictions and all items in hard mode. I'm not sure if I didn't use comments. Because comment definition in Befunge is not the same as other languages.
EDITED: added some pipe characters which are vertical condition command in befunge to meet first rule (2 non-whitespace characters in each line) as pointed out by @CMP
] |
[Question]
[
The Seven-Eleven problem is find 4 positive numbers (with two decimal digits, A.BC) such that their sum is equal to their product and is equal to 7.11.
```
a + b + c + d = a * b * c * d = 7.11
0 < a <= b <= c <= d
```
Write the shortest program to compute all non-decreasing quadruples. Precomputing the values is not allowed.
[Answer]
## Ruby, 105 characters
Unfortunately I didn't get it below the 100 mark. It just brute forces all possible tuples and checks afterwards. Nevertheless it still finishes in finite time.
```
(1..m=711).map{|a|(a..m).map{|b|(b..m).map{|c|d=m-a-b-c;p [a/u=1e2,b/u,c/u,d/u]if d>=c&&a*b*c*d==m*1e6}}}
```
The formatted version looks like this:
```
(1..m=711).map{ |a|
(a..m).map{ |b|
(b..m).map{ |c|
d=m-a-b-c
p [a/u=1e2,b/u,c/u,d/u] if d>=c && a*b*c*d==m*1e6
}
}
}
```
[Answer]
## Haskell - 121
*(extra newline added for readability)*
```
h=711
main=mapM(print.map((/100).realToFrac))
[[a,b,c,d]|a<-[1..h],b<-[a..h],c<-[b..h],let d=h-a-b-c,c<=d,a*b*c*d==h*10^6]
```
This meets the requirements by only working with numbers with two decimal digits. It computes the solution (there's only one of them) using integer arithmetic, scaled up by 100. Floating-point arithmetic is too untrustworthy for this.
[Answer]
## Python (146 152 characters)
Here's a "real" answer, if my Wolfram Alpha one doesn't please:
```
n=711
r=lambda v:range(v,n)
print [[a*0.01,b*0.01,c*0.01,d*0.01]for a in r(1)for b in r(a)for c in r(b)for d in r(c)if a+b+c+d==n and a*b*c*d==n]
```
It's very, very inefficient, but it works.
[Answer]
# C (229 characters)
Sacrificial offering:
```
#include<stdio.h>
int main(void){int a,b,c,d;for(a=1;a<=711/4;++a)for(b=a;b<=711/4;++b)for(c=b;c<=711/4;++c){d=711-(a+b+c);if(d<c)break;if(a*b*c*d==711000000)printf("a=%.2f,b=%.2f,c=%.2f,d=%.2f\n",a/100.,b/100.,c/100.,d/100.);}}
```
Re-formatted for readability:
```
#include <stdio.h>
int main()
{
int a, b, c, d;
for (a = 1; a <= 711 / 4; ++a)
for (b = a; b <= 711 / 4; ++b)
for (c = b; c <= 711 / 4; ++c)
{
d = 711 - (a + b + c);
if (d < c) break;
if (a * b * c * d == 711000000)
printf("a = %.2f, b = %.2f, c = %.2f, d = %.2f\n", a / 100., b / 100., c / 100., d / 100.);
}
}
```
[Answer]
# GNU Prolog REPL, 57 bytes
(The REPL input ends with two newlines, which are included in the byte count.)
```
A+B+C+D#=711,A*B*C*D#=711000000,fd_labeling([A,B,C,D]).
```
The first line prints the first solution (very quickly, in fact; `fd_labeling` often needs tuning to run quickly, but it didn't in this case). GNU Prolog's generates the solution which has the arguments in sorted order first. In this case, only one solution is in sorted order, so we can enter a newline at the "more solutions?" prompt to not generate the remaining solutions; arguably this is hardcoding the *number of solutions*, but as required by the question, it doesn't hardcode the *values* in the solution. Uses fixed-point arithmetic (so the numbers are printed without a decimal point), because GNU Prolog's built-in equation solver handles only integers.
This is just a case of finding a language with a language feature that solves the problem almost directly. Mathematica might be the obvious choice, but GNU Prolog has a constraint solver too. If only the REPL ran `fd_labeling` automatically! (Come to think of it, maybe I should write a language that uses GNU Prolog's constraint solver behind the scenes and has a terser syntax; it'd be useful in this sort of challenge when it comes up in the future, and possibly even for general use. Oh, and that's designed to solve problems using normal arithmetic operations rather than INTERCAL's.)
[Answer]
**K, 67 chars**
Brute force, requires about ten seconds.
For information about K (unique mix of APL, functional, and Database programming language). see kdb.com
```
{if[(_711e6)=*/r:x,711-+/x;R::r]}'?{|':1+a\:x}'!*/a:3#_711%4;R%100
```
generates the answer
```
1.2 1.25 1.5 3.16
```
Explanation:
* Algorithm:
+ Generates range 1..711/4 for each of three values
+ calculates the fourth as 711-sum of the other three
+ Filter to guarantee ascending order of the values
+ Calculates product of values and compare with 711000000
* About syntax
+ Many predefined functions are one-letter operators. There are diad (x OP y) and monad (OP x) variants. Evaluation left to right, no precendence, ';' as sentence separator, 'var : value' to assign. {..} defines an anonimous function
+ diads: % is divide, x:y computes list fo digits of y in x-base, x#y takes, | is max
+ monads: \_ is floor, f/ reduces list with funcion f (ej. \*/ calculates product, +/ calculates sumation), !x generate values 0..x-1, ?x return unique values of list x, f': applies f to each pair of the argument list (|':x to guarantee non.decreasing values)
+ func'args applies the function over each of the args
[Answer]
## Scala 168 139
```
def h(i:Int)=i/100.0
val x=711
for(a<-1 to x;
b<-a to x;
c<-b to x;
d=x-a-b-c
if(d>c&&h(a)*h(b)*h(c)*h(d)==7.11))yield(h(a),h(b),h(c),h(d))
```
[Answer]
## Mathematica
```
Solve[
a + b + c + d == a * b * c * d / 10^6 == 711
&& 0 < a <= b <= c <= d,
{a, b, c, d},
Integers
]
```
Basically, solve it as an integer Diophantine equation. The advantage is that this avoids possible floating-point error.
On my computer, Mathematica runs out of memory, but it *might* work in principle...
It might be possible to run this on Wolfram Alpha, but I'm not familiar enough with its syntax.
In Mathematica, this is 58 characters + 1 fraction line + 1 exponentiation box.
] |
Subsets and Splits