text
stringlengths 180
608k
|
---|
[Question]
[
For those who didn't know, **[Sigma](https://en.wikipedia.org/wiki/Sigma)** is a Greek letter which is heavily used in mathematics as the summation sign. Given a string representing an expression depending on \$k\$ that we will denote \$E(k)\$, compute the sum of the results for \$E(k)\$, for each \$k\in\{1,2,3,4,5\}\$. Concisely, you should find \$S\$ such that:
$$S=\sum^5\_{k=1}E(k)$$
An example of an expression: \$E(k)=\frac k 2 + k^2\$
---
### Specs
* You are guaranteed:
+ that the expression is valid, so it contains no errors, and that it's dependent of the syntax chosen (e.g: if you only support `2*k`, there will be no `2k`)
+ to only have defined values amongst your results, so no values like `1/0`, `inf` or `nan` will appear
* You can assume that the expression above is fitting the limits of the programming language of your choice, so it won't result in overflows or any other limit-related errors
* Any other non-whitespace ASCII Character instead of `k` can be chosen
* Your program **must** support the following operations:
+ addition (`+`, `plus()`,`add()`,`sum()`)
+ subtraction (`-`, `minus()`, `subtract()`)
+ exponentiation (`**`,`^`,`pow()` or others, should be specified), with support to negative bases and exponents
+ square root in the form of `sqrt(k)`, `k^0.5`, `k**0.5`, or however else you wish
+ multiplication and division
* The submission can either be a full program or a function, while mentioning its usage
* Any trailing / leading whitespace is allowed when outputting
* Minimum precision: 2 decimal places
### Test Cases (with `k`)
```
+---------------+--------------+
| Input = E(k) | Output |
|---------------+--------------|
|2*k | 30 |
|---------------+--------------|
|sqrt(k) | 8.38 | (* with minimum decimal precision)
|---------------+--------------|
|k+k/2+k**2 | 77.5 |
|---------------+--------------|
|k**2 | 55 |
+---------------+--------------+
```
The score will be the number of bytes (of the source + compiler flags). The lowest scoring valid submission wins, while taking note that [these loopholes](//codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are strictly forbidden. **[Here](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqjgalVcmqsRnVqWmKNRXFKk4aqpV5RakJOYnKqhnq2uAxLK1NTUVEjLL1LIVMjMUyhKzEtP1TDUMdOM1fxfUJSZV6KRBlSqpWWkrqnJhRDQBgoZ6JmiCuoaoivSN9LG1KulZYwqoG8MVGmCMPI/AA)** is a Python pseudo-code, to make things clearer.
[Answer]
## Mathematica, ~~17~~ ~~14~~ 13 bytes
*Thanks to Ian Miller for saving 3 bytes.*
*Thanks to LegionMammal978 for saving 1 byte.*
```
#~NSum~{k,5}&
```
The input should be an actual expression containing `k`, e.g.:
```
#~NSum~{k,5}&[Sqrt[k]^3+4]
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~40~~ 37 bytes
3 bytes thanks to Arnauld.
Eval scope tricks \o/
```
f=lambda s,k=5:k and eval(s)+f(s,k-1)
```
[Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqFCsk21rapWtkJiXopBalpijUaypnaYBFNU11PxfUJSZV6KRpqFkpJWtpKnJBedna2kZ6JmiCmln6xtpAyWM0FWCBP4DAA "Python 3 – TIO Nexus")
Uses `k**0.5` instead of `sqrt(k)`.
[Answer]
## JavaScript (ES7), ~~31~~ 30 bytes
Uses `k**0.5` for `sqrt(k)`.
```
f=(e,k=6)=>--k&&f(e,k)+eval(e)
console.log(f("2*k"))
console.log(f("k**0.5"))
console.log(f("k+k/2+k**2"))
console.log(f("k**2"))
```
[Try it online!](https://tio.run/nexus/javascript-node#@59mq5Gqk21rpmlrp6ubraaWBuJqaqeWJeZopGpycSXn5xXn56Tq5eSna6RpKBlpZStpaqKLZmtpGeiZYpPQztY30gZKG2HXBRL@/x8A)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
vЀ5S
```
[Try it online!](https://tio.run/nexus/jelly#@192eMKjpjWmwf8PtwPp/4b/o7k4lR7uWKKkA6QP7QVT2h7ahzZBBDYpccUCAA "Jelly – TIO Nexus")
Input a valid Jelly monadic chain (I golfed them down in my link).
## How it works
```
vЀ5S
Ѐ for each of ...
5 5 (implicitly converted to [1,2,3,4,5]), ...
v evaluate the input with the above as argument
S and find the sum
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ ~~7~~ 6 bytes
```
6G¹.VO
```
[Try it online!](https://tio.run/nexus/05ab1e#@2/mfminXpj///9@Cn5G@tp@RrnaAA)
Input is in postfix notation, and **uses the variable N**. 05AB1E is a stack-based language, so only postfix notation works.
Format of `E(N)`: write the number(s) you want to do the operation with, and then write the sign of the operation. For example, `3+4` would be `3 4+`, `3*4+2*3` would be `3 4* 2 3* +`. Also note that this uses `t` instead of `sqrt`, and `m` instead of `**`, so `sqrt(N)` would be `Nt`.
**Explanation:**
```
6G¹.VO
6G For N in range(1,6). This includes [1,2,3,4,5].
¹.V Read and eval input.
O Sum results.
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~50~~ ~~46~~ ~~31~~ 29 bytes
```
@(d)eval(["k=1:5;sum(" d 41])
```
[Try it online!](https://tio.run/nexus/octave#S7ON@e@gkaKZWpaYoxGtlG1raGVqXVyaq6GkkKJgYhir@T9NQ8lITytbSZMLyCouLCrRyNaEcLK1s/WNtLP14oygfDDrPwA "Octave – TIO Nexus")
Exponentiation is denoted with the caret `.^` and multiplication is denoted with `.*`.
This declares an anonymous function that takes in argument `d`. It sets `k` to be equal to the range `1:5` and sums the evaluated `d` and returns it.
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 10 bytes
```
6ÆK=XOxUÃx
```
Input string should have variable as an uppercase `K`. `sqrt(K)` should be inputted as `K**0.5`.
[Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=NsZLPVhPeFXDeA==&input=IksrSy8yK0sqKjIi)
## Explanation
`eval` scope didn't work in my favor; had to redefine the counting variable `X` as a global `K`.
```
6ÆK=XOxUÃx // implicit: U = input string
6oXYZ{K=XOxU} x // expanded
6oXYZ{ } // create array [0, 6) and map to function:
K=X // redefine the array value to global K
OxU // eval the input string
x // sum the resulting array
```
[Answer]
# Octave, ~~25~~ 23 bytes
```
@(f)sum(inline(f)(1:5))
```
[Try it online!](https://tio.run/nexus/octave#@@@gkaZZXJqrkZmXk5mXCuRoGFqZamr@LyjKzCtJ01BSzYzJU9JRSMwr1lA30spW19S05sImV1xYVKKRrYlTPls7W99IO1svzgi3EqjkfwA)
Exponentiation is denoted as `.^`
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 9 bytes
```
+/⍎⎕⊣k←⍳5
```
[Try it online!](https://tio.run/nexus/apl-dyalog#e9TRnvZfW/9Rb9@jvqmPuhZnP2qb8Kh3s@n/Rx3t/9O41I0OT89W5wIysrX0TCEMbY3sw9uNNLWztYygMkbqAA "APL (Dyalog Unicode) – TIO Nexus")
Addition is `+`, subtraction is `-`, multiplication is `×`, division is `÷` exponentiation is `*` and execution is right to left, so use `()` to group expressions.
Input is in terms of `k`.
### Explanation
```
k←⍳5 Set k to be equal to the vector 1 2 3 4 5
⊣ The left argument:
+/ Sum of
⍎⎕ The evaluated input (the eval returns an array because k is an array)
```
---
And here's a solution that takes trains as input (like the Jelly answer): [`+/(⍎⎕)¨⍳5`](https://tio.run/nexus/apl-dyalog#e9TRnvZfW1/jUW/fo76pmodWPOrdbPr/UUf7/zQudaPD0x91LVLnAjL1TLUe9a6A8YC0tobR4e0QIU1tI2RJOAcA "APL (Dyalog Unicode) – TIO Nexus").
[Answer]
# Common Lisp, 55 bytes
```
(defun f(x)#.(read))(print(+(f 1)(f 2)(f 3)(f 4)(f 5)))
```
[Try it online](https://tio.run/nexus/clisp#@6@RkppWmqeQplGhqaynUZSamKKpqVFQlJlXoqGtkaZgqAkkjECEMYgwARGmmpqa//9raClUAGUA)
```
Example input - output:
(* x 2) - 30
(sqrt x) - 8.382333
(+ (/ x 2) x (expt x 2)) - 155/2
(expt x 2) - 55
```
different, longer (58 bytes) version - starts getting shorter if you do sumation from 1 to 7.
```
(print #.`(+,@(mapcar #'(lambda(x)#.(read))'(1 2 3 4 5))))
```
yet another and longer method (~~65~~ 64 bytes) - doesn't define function - just inserts your expression into a loop. Should get shorter for bigger sums.
```
(setf a(read)b 0)(loop as x from 1 to 5 do(incf b #.a))(print b)
```
[Answer]
# Swift, ~~202~~ 184 bytes
```
import Foundation;func s(i:String){print([1,2,3,4,5].map{NSExpression(format:i.replacingOccurrences(of:"k",with:"\($0).0")).expressionValue(with:nil,context:nil)as!Float}.reduce(0,+))}
```
For some reason this will only run locally :(.
Here is an explanation of what I am doing:
```
import Foundation // Import the Foundation module
func s(i:String){ // Create a function that takes in a String and returns a Float
print( // Print the result of the follow algorithm to strdout
[1,2,3,4,5].map{ //Conduct the follow code on numbers 1 - 5
NSExpression(format: // Create an expression with the following String and return it
i.replacingOccurrences(of:"k",with:"\($0).0")) // Create a string replacing all ocurrances of 'k' in `i` with the current Float from the map
.expressionValue(with:nil,context:nil)as!Float // Get the resulting value of the expression
}.reduce(0,+) // Add the result of all the expressions together
)
}
```
Thanks to @Mr. Xcoder for saving 15 bytes!
[Answer]
# TI-Basic, 12 bytes
```
Σ(expr(Ans),K,1,5
```
Call with `"string":prgmNAME`, where `string` is any valid TI-Basic expression of `K`.
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 16 bytes
```
5~>[@k#~]2/"!sum
```
[Try it online!](https://tio.run/nexus/stacked#q1bM@29aZxftkK1cF2ukr6RYXJr7P08hRkFHQaUotaBIITexQEFdwdYOSGTlZ@Yp5JeWKNRycWlwKahnKxgpaKmDGcWFRSUQFkhQH0zGKWgraKtD1cWpc2kCTQWa9h8A "Stacked – TIO Nexus")
`5~>` is a range from 1 to 5 incluive. `2/` makes a func dyadic, `"` is pair-wise, and `!` is execute. This thus maps the range `[1, 5]` with the input, which is then evaluated after defining the range member to be `k`. Then, the results are summed.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~31~~ 24 bytes
```
?sa1k[lax+Kd1+k5>p]dspxp
```
The input must be given in reverse-Polish notation (also known as postfix notation) and enclosed in square brackets (`[]`) with:
* `K` replacing `k` as the parameter;
* `+` representing addition;
* `-` representing subtraction and `_` followed by any number representing a negative number;
* `*` representing multiplication;
* `/` representing division;
* `^` representing exponentiation;
* `v` representing the square-root.
For example, `-2*k+k+3*k**2+k**0.5-k/2` would be input as `[_2K*K+K2^3*+Kv+K2/-]`. This takes due advantage of the fact that `K` is a `dc` command which returns the current precision (initially set to `1`). Therefore, by the end, this returns the output with a precision of `6`.
[Try it online!](https://tio.run/nexus/dc#@29fnGiYHZ2TWKHtnWKonW1qVxCbUlxQUfD/f7S3kVbs17x83eTE5IxUAA "dc – TIO Nexus")
[Answer]
# [R](https://www.r-project.org/), 35 bytes
```
k=1:5;sum(eval(parse(t=scan(,""))))
```
[Try it online!](https://tio.run/##K/qvnFaal1ySmZ@nUaGTbWtoZapZXJqrkVqWmKNRkFhUnKpRYluhqanJpZymoWSkla0EYRUXFpVoZGtCedna2fpG2tlaWkYwAQjzP9hAawwDi5MT8zR0lJSA5mr@B6nl@g8A "R – Try It Online")
TIO link includes a function solution as well (38 bytes)
[Answer]
# [Tcl](http://tcl.tk/), 58 bytes
```
proc S {f s\ 0} {time {incr k
set s [expr $s+$f]} 5
set s}
```
[Try it online!](https://tio.run/##JczBCsIwEIThe55iDnvQFLQEfJIe1YOEBMq2GrNbEEKePQ31Mj/M4VO/tJbyx2NCiZAHxoqi8xpQ5rfPYCNBIbiHX8ogGSg@K27/t7ZlfSVEFGeJId@sJ@IziAfiq7uMPdY6HNtdkzbt1ISOmNp2 "Tcl – Try It Online")
If it only worked with integers, I could golf it more!
]
|
[Question]
[
Your task is to take a list of arguments that are either integers or operators, and parse them like so:
1. There is a current operator, which starts as +.
2. Each time an operator is found, the current operator will change to it.
3. The possible operators are: "+", "-", "\*", "/", and "%", which correspond to their meanings in C and most languages.
4. There is a running solution kept, which starts at 0.
5. Each time an integer is found, the solution is modified by the number depending on the operator; e.g. if the operator is "/" then the solution is divided by the number.
6. If an operation would result in a mixed number (i.e. with a decimal) then it must be floored back to an integer (i.e. the decimal must be chopped off).
7. Output the final solution.
For example:
The arguments `5 8 25 * 9 6 2 - 104 / 4 7 + 6 % 14` would result in:
```
5 8 25 * 9 6 2 - 104 / 4 7 + 6 % 14
0 5 13 38 342 2052 4104 4000 1000 142 148 8 -> 8
```
The inputs will be as command-line or function arguments, or an equivalent for your language.
Shortest code wins!
[Answer]
# JavaScript (ES6) 53
A function taking an array as input.
Run the snippet in Firefox to test.
```
f=a=>a.map(t=>t<'0'?o=t:v=eval(v+o+t)|0,v=0,o='+')&&v
// TEST
out=x=>O.innerHTML=x;
input = [5,8,25,"*",9,6,2,"-",104,"/",4,7,"+",6,"%",14];
out(input.join(' ')+' -> '+f(input));
function go() {
i=I.value.split(/ +/),out(I.value+' -> '+f(i))
}
```
```
<pre id=O></pre>
Your test:<input id=I><button onclick='go()'>GO</button>
```
[Answer]
# Pyth - ~~24~~ ~~23~~ ~~22~~ 20 bytes
*2 bytes saved thanks to @issacg and 1 thanks to @orlp!*
Uses reduce with base case of `0` and checks for `'` being in repr to detect string vs. int.
```
u.xsv++GbH&=bHG+\+QZ
```
Does not work online because I use full eval which is disabled online for security reasons. Takes input from stdin in a list as such: `5, 8, 25, "*", 9, 6, 2, "-", 104, "/", 4, 7, "+", 6`.
[Answer]
# Julia, ~~85~~ 83 bytes
```
s->(o=0;p="+";for i=split(s) isdigit(i)?o=eval(parse("ifloor($o$p$i)")):(p=i)end;o)
```
This creates an unnamed function that accepts a string as input and returns an integer.
Ungolfed:
```
function f(s::String)
# Assign the starting output value o and operator p
o = 0
p = "+"
# Split the input string into an array on spaces
for i = split(s)
if isdigit(i)
# Assign o using string interpolation
o = eval(parse("ifloor($o $p $i)"))
else
# Assign p to the new operator
p = i
end
end
end
```
Fixed issue and saved 2 bytes thanks to Glen O.
[Answer]
# elisp, 101 bytes
With the arguments passed as a quoted list: e.g. `(c '(5 5 * 10))`
```
(defun c(a)(let((f 0)(o '+))(dolist(x a)(if(not(integerp x))(setf o x)(setq f (eval(list o f x)))))f))
```
Version with new lines:
```
(defun c (a)
(let ((f 0)
(o '+))
(dolist (x a)
(if (not (integerp x))
(setf o x)
(setq f (eval (list o f x)))))
f))
```
[Answer]
# CJam, 24 bytes
```
0'+ea+{_A,s&O{:O;}?S}%s~
```
This is a full program that reads the input as command-line arguments.
To try the code online in the [CJam interpreter](http://cjam.aditsu.net/#code=0'%2BlS%2F%2B%7B_A%2Cs%26O%7B%3AO%3B%7D%3FS%7D%25s~&input=5%208%2025%20*%209%206%202%20-%20104%20%2F%204%207%20%2B%206%20%25%2014) (which doesn't support command-line arguments), replace `ea` with `lS/` to read from simulated STDIN.
### How it works
```
0'+ Push a 0 and the character '+'.
ea Push the array of command-line arguments.
+ Prepend the character to the array.
{ }% For each element:
_ Push a copy.
A,s Push "0123456789".
& Intersect the copy with the string of digits.
{ }? If the intersection is non-empty:
O The element is a number. Push O.
:O; The element is an operator. Save it in O.
S Push a space.
s~ Flatten the array of strings and evaluate it.
```
[Answer]
# JavaScript, 85 bytes
```
r=0;o="+";prompt().split(" ").forEach(t=>+t+1?r=parseInt(eval(r+o+ +t)):o=t);alert(r)
```
[Answer]
# Lua, 142 bytes
```
function f(s)o="+"r=0 for c in s:gmatch"%S+" do if tonumber(c)~=nil then loadstring("r=r"..o..c)() else o=c end r=math.floor(r)end print(r)end
```
Ungolfed:
```
function f(s)
o="+" --original operator
r=0 --return value
for c in s:gmatch"%S+" do --split by spaces
if tonumber(c)~=nil then --check if the current character is a number
loadstring("r=r"..o..c)() --appends the current operator and current character ex "r=r+5" and then evaluates as another Lua script
else
o=c --if the character is not a number, it is the new operator
end
r=math.floor(r) --floor after each operation
end
print(r) --print the result
end
```
[Answer]
# Powershell, 57 bytes
```
$o="+"
$args|%{$r=iex "$r$o$_"
if(!$?){$o=$_}$r-=$r%1}
$r
```
ungolfed;
```
$operator="+"
$args | ForEach-Object
{
$result = Invoke-Expression "$result $operator $_"
if(!$?)
{
$operator=$_
}
$result -= $result % 1
}
$result
```
If the implicit variable in the for-each is an operator rather than number, Invoke-Expression (POSH's `eval()`) will fail and the execution status `$?` will be false.
Floor in POSH is unwieldy - `$foo=[math]::floor($foo)` and `$foo-=$foo%1` was the golfiest alternative I could think of.
[Answer]
# GNU Sed (with the eval extension, + dc), 102
(Score includes +1 for the -r option to sed.)
```
s/.*/0 + &p/
s/([-+/*%]) ([0-9]+)/\2 \1/g
:
s/([-+/*%] )([0-9]+ )([0-9]+)/\1\2\1\3/
t
s/.*/dc<<<'&'/e
```
Transforms the input expression to reverse polish notation, and then uses `dc` to evaluate it.
### Test output:
```
$ sed -rf calclist.sed <<< '5 8 25 * 9 6 2 - 104 / 4 7 + 6 % 14'
8
$
```
[Answer]
# CJam, 34 bytes
```
'+0lS/{"+-*/%"1$#){@;\}{i2$~}?}/\;
```
[Try it online](http://cjam.aditsu.net/#code='%2B0lS%2F%7B%22%2B-*%2F%25%221%24%23)%7B%40%3B%5C%7D%7Bi2%24~%7D%3F%7D%2F%5C%3B&input=5%208%2025%20*%209%206%202%20-%20104%20%2F%204%207%20%2B%206%20%25%2014)
I thought this was going to be fairly reasonable. But I wasn't fast enough posting it to be the shortest CJam answer at least for a moment. :(
[Answer]
## Python 3 - ~~131 bytes~~ ~~129 bytes~~ ~~121 bytes~~ 116 Bytes
Thanks to Maltysen for shaving off two bytes, Beta Decay for shaving off 8, and Steven Rumbalski for shaving off 5.
```
def f(x):
a,b="+",0
for i in x:
if i in"+-*/%":a=i
else:b=int(eval(str(b)+a+i))
return b
```
I'm trying to figure out a way to reduce the length of the if statement, but for now this seems about as golfed as I can get it. Takes input as a list.
[Answer]
# Bash, 69
```
set -f
for t in $*
do
((1${t}1>2))&&((r${o-+}=$t))||o=$t
done
echo $r
```
This only works with non-negative integers - its not clear in the question if this is ok or not.
[Answer]
# Groovy, 79 bytes
```
def f(x,a=0,b='+'){x.each{z->a=z=~/\d/?Eval.me(a+b+z)as int:a;b=z=~/\d/?b:z};a}
```
Demo:
```
groovy> f([5,8,25,'*',9,6,2,'-',104,'/',4,7,'+',6,'%', 14])
Result: 8
```
Ungolfed:
```
def f(x, a=0, b='+') {
x.each {z->
a = z =~ /\d/ ? Eval.me(a+b+z) as int : a
b = z =~ /\d/ ? b : z
}
a
}
```
[Answer]
# Perl 5.10+, 52 bytes
```
perl -E '$o="+";/\D/?$o=$_:eval"\$x=int\$x$o$_"for@ARGV;say$x'
```
Demo:
```
$ perl -E '$o="+";/\D/?$o=$_:eval"\x=int\$x$o$_"for@ARGV;say$x' 5 8 25 \* 9 6 2 - 104 / 4 7 + 6 % 14
8
```
(Note that `*` has to be escaped in my shell so it's not interpreted as a glob pattern.)
## Ungolfed:
```
$o="+"; # Start with addition
/\D/ ? $o=$_ # If not a number, update the current operator
: eval"\$x=int\$x$o$_" # Otherwise, make a string like '$x=int$x+1' and eval it
for@ARGV; # Repeat for each item in the argument list
say$x # Print the result
```
[Answer]
# C#, 132 ~~165 168~~ bytes
This function assumes the input is valid. This is tough for C# given there's no `eval` equivalent.
Thanks [edc65](https://codegolf.stackexchange.com/users/21348/edc65) for saving 33 bytes!
Indented for clarity.
```
int C(string[]a){
int o=1,r=0,n;
foreach(var b in a)
n=int.TryParse(b,out n)
?r=o<0?r%n
:o<1?r*n
:o<2?r+n
:o<4?r-n
:r/n
:o=b[0]-42;
return r;
}
```
[Answer]
# Ruby, 59 bytes
```
a=0
o=?+
gets.split.map{|s|s=~/\d/?a=eval([a,s]*o):o=s}
p a
```
Test run:
```
$ ruby calc.rb <<< "5 8 25 * 9 6 2 - 104 / 4 7 + 6 % 14"
8
```
[Answer]
# C 122
**Thanks to @ceilingcat for finding a much better (and shorter) version**
```
#define A atoi(*a):s
o,s;main(z,a)char**a;{for(;*++a;)**a<48?o=**a-43:(1?s=o+6?o-4?~o?o-2?o?:s+A-A*A/A%A);printf("%d",s);}
```
[Try it online!](https://tio.run/##DYjbDoIgAIbvewpnc@MgMw3NJMd4FIZaXCRNvKrVq/9x9R2cuDsHHKd58eucmczuwRNm6RAPoYzqaf1K3qWl7mE3xqz6LGEjinFuFU19k70OYxIhzwOpdRwD73QQUv9CQqODHiI3wjBTmcJQ9dr8ui8kL6a8jFR9AbTo0bRguKJDA4H6JFFB4gKeToFa/gE "C (gcc) – Try It Online")
But if you are compiling it with mingw32 you need to turn off globbing (see <https://www.cygwin.com/ml/cygwin/1999-11/msg00052.html>) by compiling like this:
```
gcc x.c C:\Applications\mingw32\i686-w64-mingw32\lib\CRT_noglob.o
```
]
|
[Question]
[
# Article Spinning with Spintax
[Article spinning](https://www.google.ca/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=0CCQQFjAB&url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FArticle_spinning&ei=-C2EVYfsLoj1-QHrq7zwAQ&usg=AFQjCNGREvbaE6Y8WeFsVc73xXEWAndlkA&sig2=j5rz3g_FG9bqHZ8YeEAqAg) is a search engine optimization technique by which search engine optimizers post a unique version of relevant content on article directories, web 2.0 sites, or other sources for backlinks.
It is occasionally used by website authors on their own sites but usually avoided because the quality of spun content will be lower than hand written content. Spinning works by rewriting existing articles, or parts of articles, and replacing specific words, phrases, sentences, or even entire paragraphs with any number of alternate versions to provide a slightly different variation with each spin.
This process can be completely automated or rewritten manually. Your job today will be to create a program or function which interprets a string containing **Spintax**, the syntax by which a program would read the different options available. Below is an example string that uses Spintax:
```
{Hello|Hi there|Bonjour}, user! {What's up?|How are you?|Feeling alright?|I caught a fish!}
```
As you can see, sections of the string that are to be 'spun' are enclosed in curly braces, where individual options are split by the `|` character. Here are some example sentences this could produce.
```
Hi there, user! What's up?
Hello, user! How are you?
Bonjour, user! Feeling alright?
Hello, user! What's up?
Hi there, user! I caught a fish!
```
# Your Job
Your mission, should you choose to accept it, is to create a program or function which takes an input string that may or may not contain **Spintax**, then print 5 versions of the string, [randomly](http://meta.codegolf.stackexchange.com/questions/1324/standard-definitions-of-terms-within-specifications/1325#1325) selecting one of the choices from each block of options. You can make a few assumptions:
1. You will not need to handle nested Spintax (`{This|is {an|one}|example}`).
2. The `|`,`{` and `}` characters will not occur anywhere else other than within a Spintax block.
3. You do not need to check if the 5 output sentences are distinct, as long as the code selects options using your language's random number function.
4. You may assume the input ends with a newline.
# Rules
1. [No standard loopholes.](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
# Tests
```
1. {A|The|One} {quick|magnificent|charming|lucky|fast|super|cool} {gold|tan|yellow|white|brown|silver} {beaver|packrat|cat|lion|tiger|fox|dog|wolf} {consumed|ate|pilfered} my {pastry|strudel|cake}.
-------------------------------------------
One cool brown wolf consumed my pastry.
...(3 more here)...
The charming yellow beaver ate my cake.
-------------------------------------------
2. This sentence is valid, and happens to have no Spintax!
-------------------------------------------
This sentence is valid, and happens to have no Spintax!
...(3 more here)...
This sentence is valid, and happens to have no Spintax!
-------------------------------------------
3. {beg|get|ton|sun|bun|can|top|big}{2|3|4|5}{A|B|C|D|E|F|G}{2|3|4|5|6|7}{at|as|be|ex|hi|}{!|#|%}
-------------------------------------------
top2F2hi%
...(3 more here)...
big3E4ex#
```
A fourth test can be found [here.](https://gist.github.com/anonymous/2fb5f68817a67e0ca6dd)
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest number of bytes wins.
[Answer]
# Pyth, 18
```
V5sOMcR\|scR\{cz\}
```
[Try it online here](https://pyth.herokuapp.com/?code=V5sOMcR%5C%7CscR%5C%7Bcz%5C%7D&input=%7BA%7CThe%7COne%7D+%7Bquick%7Cmagnificent%7Ccharming%7Clucky%7Cfast%7Csuper%7Ccool%7D+%7Bgold%7Ctan%7Cyellow%7Cwhite%7Cbrown%7Csilver%7D+%7Bbeaver%7Cpackrat%7Ccat%7Clion%7Ctiger%7Cfox%7Cdog%7Cwolf%7D+%7Bconsumed%7Cate%7Cpilfered%7D+my+%7Bpastry%7Cstrudel%7Ccake%7D.&debug=0)
### Explanation:
```
V5sOMcR\|scR\{cz\} : z = input()
V5 : do this 5 times
cz\} : split z on the } character
cR\{ : split each element of the resulting list on {
s : join the list of lists back into a list of strings
cR\| : split these strings on the | character
OM : Choose a random element from each inner list
s : join those choices, and print them
```
[Answer]
# Ruby, 46
With command-line flag `-p`, run
```
($_*=5).gsub!(/{(.+?)}/){$1.split(?|).sample}
```
Read in a string with a trailing newline. Concatenate it to itself 5 times, mutate it in place, and output the result. `/{(.+?)}/` is a regular expression with a lazy quantifier: without the `?`, it would match the leftmost `{` to the rightmost `}` instead of the nearest one. `$1` is a magic variable referring to the first capture group in each match, while the `?|` literal refers to the `|` character. `sample` is an array method returning a random element.
[Answer]
# CJam, ~~25~~ ~~22~~ ~~19~~ 18 bytes
```
q5*'}/{'{/~'|/mR}/
```
This code requires the input to contain a trailing newline.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q5*'%7D%2F%7B'%7B%2F~'%7C%2FmR%7D%2F&input=%7BA%7CThe%7COne%7D%20%7Bquick%7Cmagnificent%7Ccharming%7Clucky%7Cfast%7Csuper%7Ccool%7D%20%7Bgold%7Ctan%7Cyellow%7Cwhite%7Cbrown%7Csilver%7D%20%7Bbeaver%7Cpackrat%7Ccat%7Clion%7Ctiger%7Cfox%7Cdog%7Cwolf%7D%20%7Bconsumed%7Cate%7Cpilfered%7D%20my%20%7Bpastry%7Cstrudel%7Ccake%7D.%0A).
### How it works
```
q e# Read from STDIN.
5* e# Repeat the input five times.
'}/ e# Split at right curly brackets.
{ e# For each chunk:
'{/ e# Split at left curly brackets.
~ e# Dump both chunks on the stack.
'|/ e# Split the right chunk at vertical bars.
mR e# Select a chunk, pseudo-randomly.
}/ e#
```
In each iteration, two chunks (one constant, one variable) are left on the stack and will be printed when the program exits.
[Answer]
# Python 3, 110 bytes
```
import re,random
exec('print("".join(random.choice(s.split("|"))for s in re.split("{(.*?)}",%r)));'%input()*5)
```
Regex splitting, like the others.
# Python 3, ~~121~~ ~~116~~ 114 bytes
```
from random import*
exec(("print(%r[:-1]);"%(input()+'"')).translate({123:"'+choice(['",124:"','",125:"'])+'"})*5)
```
This one performs the appropriate replacements then evaluates it. If it wasn't for escaping backslashes and apostrophes, this would have turned out shorter.
For example, suppose we have the Spintax
```
I {like|hate} {Python|C}.
```
The `.translate` performs a few conversions to give:
```
print('I '+choice(['like','hate'])+' '+choice(['Python','C'])+'.')
```
[Answer]
# Perl, 50
```
$_=$_ x5;s/{(.*?)}/@r=split"\\|",$1;$r[rand@r]/ge
```
`49` characters `+1` for `-p`.
It works by first setting `$_` to the 5 sentences. Then it does a global search and replace, where we search for each `{ | | }` group. It splits the group on `|`, and the picks a random element for the replacement.
Run with:
```
echo '{A|The|One} {quick|magnificent|charming|lucky|fast|super|cool} {gold|tan|yellow|white|brown|silver} {beaver|packrat|cat|lion|tiger|fox|dog|wolf} {consumed|ate|pilfered} my {pastry|strudel|cake}.' | perl -pe'$_=$_ x5;s/{(.*?)}/@r=split"\\|",$1;$r[rand@r]/ge'
```
[Answer]
# [Ostrich v0.7.0](https://github.com/KeyboardFire/ostrich-lang/releases/tag/v0.7.0-alpha), 27 characters
```
{`{.*?}`{);(;"|/.,R*F=}X}5*
```
Explanation:
```
{...}5* repeat 5 times
`{.*?}` regex to match "spintax" sections
{...}X replace with...
);(; remove first and last characters (the curly brackets)
"|/ split on |
.,R* multiply length of that array by a random number
F= take the floor of that and get the nth element of the array
```
(note: the 0.7.0 release was made after this question was posted, but the answer is still valid as all the commits that made up that release were all pushed before this questions was posted.)
[Answer]
# Pip, ~~25~~ ~~22~~ 20 bytes
Late to the party, but here's mine. Takes input as a command-line argument, which may need to be quoted.
```
L5P_@RR#_Ma^`}|{`^'|
```
Explanation:
```
L5 Loop 5 times:
a^`}|{` Split cmdline arg on curly braces using regex
^'| Split each item of the result on pipe (if there isn't one,
the result is a single-item list)
M Map this function to each item a in the result:
_@RR#_ Calculate a random number between 0 and len(item)-1; use it to
index into item
P Print the resulting list, concatenating elements together
```
## 17 bytes (but not a valid submission)
```
L5PRC_Ma^`}|{`^'|
```
Requires the latest version of Pip, updated after this question was posted. The RC (random choice) operator was planned for some time, but I never got around to implementing it until just now. :^(
[Learn more about Pip](http://github.com/dloscutoff/pip)
[Answer]
# JavaScript ES6, ~~86~~ 84 bytes
```
f=s=>s.repeat(5).replace(/{(.+?)}/g,(_,e)=>(p=e.split`|`)[Math.random()*p.length|0])
```
This expects the input to have a trailing newline. It starts by repeating the input 5 times, and then replacing each Spintax string with a random word from it, which is obtained by splitting out the `|` characters and then choosing a random number between 0 and the length of the resulting array minus 1. In this case, `|0` is just a shorter way of doing `Math.floor`. Thanks to vihan1086 for reminding me about tagged template strings.
The Stack Snippet below contains ungolfed and easily testable code.
```
f=function(s){
return s.repeat(5).replace(/{(.+?)}/g,function(_,e){
return (p=e.split('|'))[Math.random()*p.length|0]
})
}
run=function(){document.getElementById('output').innerHTML=f(document.getElementById('input').value+'\n')};document.getElementById('run').onclick=run;run()
```
```
<input type="text" id="input" value="{A|The|One} {quick|magnificent|charming|lucky|fast|super|cool} {gold|tan|yellow|white|brown|silver} {beaver|packrat|cat|lion|tiger|fox|dog|wolf} {consumed|ate|pilfered} my {pastry|strudel|cake}." style="width: 400px;" /><button id="run">Run</button><br />
<pre id="output"></pre>
```
[Answer]
# Perl, 82 bytes
```
while($o=<>){for(0..4){$_=$o;s/{(.*?)}/@x=split\/\|\/,$1 and$x[rand@x]/ge;print;}}
```
[Answer]
# Python 2, 139 bytes
Added two bytes for quotes around input string. If these are not needed let me know.
[**Try it here**](http://ideone.com/vj3MLk)
```
import re,random
s=input()
exec"print''.join(t*(t!=''and(t[0]!='{'))or random.choice(t[1:].split('|'))for t in re.split('({.*?)}',s));"*5
```
[Answer]
# Java, 243 215 242 234 bytes
```
int i,k;void f(String s){String a,b[],c=s;for(;k++<5;System.out.println(c),c=s)while((i=c.indexOf("{"))>=0){a=c.substring(i,c.indexOf("}")+1);b=a.replaceAll("\\{|\\}","").split("\\|");c=c.replace(a,b[(int)(Math.random()*b.length)]);}}
```
Finds strings within braces `{}` and replaces them with a random element from the array of strings created by splitting by the pipe character. (I realized a little too late that five sentences had to be printed :P)
[Answer]
# Bash: ~~144~~ 138 characters
```
IFS={} read -ap
w()(for o in "${p[@]}";{
[[ $o =~ \| ]]&&{
IFS=\| read -aa<<<"$o"
o=${a[RANDOM%${#a[@]}]}
}
echo -n "$o"
}
echo)
w
w
w
w
w
```
Sample run:
```
bash-4.3$ bash spintax.sh <<< "Look {ma'|daddy|mr. president}! No {bin|core|doc|find|mail}utils tools nor {Awk|Sed|jq|XML Starlet}!"
Look ma'! No docutils tools nor Awk!
Look daddy! No binutils tools nor XML Starlet!
Look mr. president! No docutils tools nor XML Starlet!
Look ma'! No docutils tools nor Awk!
Look mr. president! No binutils tools nor Sed!
```
[Answer]
# Javascript, ~~143~~ 142 bytes
```
a=prompt(b=5);for(c=[];b--;c.push(a.replace(/{(.+?)}/g,function(_,j){return (d=j.split("|"))[d.length*Math.random()|0]})));alert(c.join("\n"))
```
[Answer]
# Python 3, 97 bytes
Using a lambda function in regex substitution. This is somewhat similar to how I did it in my Spintax module <https://github.com/AceLewis/spintax> however it does not deal with nested Spintax or escaping the characters.
```
import re,random
print(re.sub("{(.*?)}",lambda x:random.choice(x.group(1).split('|')),input()*5))
```
If you do not assume the input ends with a newline then it will be 104 bytes.
```
import re,random
print(re.sub("{(.*?)}",lambda x:random.choice(x.group(1).split('|')),(input()+'\n')*5))
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
5Ær"\{(.+?)}"Ïq| ö
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=NcZyIlx7KC4rPyl9Is9xfCD2&input=IntBfFRoZXxPbmV9IHtxdWlja3xtYWduaWZpY2VudHxjaGFybWluZ3xsdWNreXxmYXN0fHN1cGVyfGNvb2x9IHtnb2xkfHRhbnx5ZWxsb3d8d2hpdGV8YnJvd258c2lsdmVyfSB7YmVhdmVyfHBhY2tyYXR8Y2F0fGxpb258dGlnZXJ8Zm94fGRvZ3x3b2xmfSB7Y29uc3VtZWR8YXRlfHBpbGZlcmVkfSBteSB7cGFzdHJ5fHN0cnVkZWx8Y2FrZX0i)
]
|
[Question]
[
I got an email from Hugo Pfoertner, an Editor-in-Chief at the On-Line Encyclopedia of Integer Sequences, with a terrific idea for a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge, which will also help verify or expand the boundary of an open mathematical question in optimization.
Here's the idea: we want to confirm and extend OEIS sequences [A063984](http://oeis.org/A063984) and [A070911](http://oeis.org/A070911), which are about finding convex polygons on the grid \$\mathbb Z \times \mathbb Z\$ that have \$n\$ vertices and minimal area. (See an example below.) These sequences had been computed up to \$n=25\$, but unfortunately, some of the programs that were used to compute these sequences have been lost, and it would be useful to have new programs that we could use to confirm the sequence.
If you are able to extend the sequence or correct any erroneous terms, Hugo or I will update the OEIS to give you credit for that—plus, you'll get lots of brownie points from me. :)
### Challenge
Your program should take a positive integer `n` (\$n \geq 3\$) and output a set of \$n\$ vertices of an area-minimal convex \$n\$-gon with vertices in the square grid. It should also output *twice*1 the area of the corresponding polygon, which should be equal to (or less than!) \$A070911(n)\$.
This is a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge, and the score will be based on the largest \$n\$ that you can compute on my machine2 in under \$10\$ minutes. In case of a tie, whichever program computes the next value fastest will win.
It would be helpful for me if you would post the runtimes and results from running your program on your machine, so that I can get an order-of-magnitude estimate for how quickly your program runs.
### Examples
The OEIS sequence [A070911](http://oeis.org/A070911) begins (starting at the index \$n=3\$): $$1, 2, 5, 6, 13, 14, 21, 28, 43, 48, 65, 80, 103, 118, 151, 174, 213, 242, 289, 328, 387, 420, 497, \dots$$
Hugo Pfoertner posted a [PDF on the OEIS containing the best known examples](https://oeis.org/A321693/a321693_1.pdf). I have included the example for \$n=13\$ here, which shows that the minimum (known) area for a convex lattice \$13\$-gon is \$\displaystyle \frac{65}{2}\$.
[](https://i.stack.imgur.com/zOxaK.png)
If you want to play around with some examples, Markus Sigg wrote a [visualizer in Javascript](http://antiton.de/PolygonalAreas/index.html?(8,1),(9,1),(12,2),(14,3),(15,4),(16,6),(16,7),(15,9),(14,10),(12,11),(9,12),(8,12),(5,11),(3,10),(2,9),(1,7),(1,6),(2,4),(3,3),(5,2)) (unfortunately, no HTTPS for this one).
---
1 Why twice the area? So that all of the solutions are whole numbers.
2 I'll be running this on my 2021 MacBook Pro on an Apple M1 Pro chip and with 16 GB of RAM.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), \$n=19\$
This is a very early attempt. Given 10 minutes, it is only able to compute up to \$n=19\$ on my laptop and finds the same values as the ones listed in A070911.
It assumes \$n\ge7\$ in order to avoid some edge cases. Although the code could be updated to support \$n<7\$, I'm not sure it's worth the effort.
A few assumptions are made about the shape of the \$n\$-gon and the size of its enclosing rectangle. The later one should probably be relaxed to make sure that no shorter solution is missed.
Each solution comes with an [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") representation.
### Code
```
const MAX_N = 13;
const MAX_TIME = 600;
let pathCache = {},
ts = Date.now(),
min = 4, max = 4;
for(let n = 7; n <= MAX_N; n++) {
console.log(`n = ${n}`);
let [ score, solution ] = solve(n, min, max),
w = solution.w - 1,
h = solution.h - 1;
console.log(`Area * 2 = ${score}`);
console.log(`Enclosing rectangle: ${w} x ${h}`);
displaySolution(solution);
let time = Math.round((Date.now() - ts) / 1000);
console.log(`Total time: ${time}s\n`);
if(time >= MAX_TIME) {
break;
}
min = solution.h;
max = solution.w + 2;
}
function solve(n, min, max) {
let part = partitionsInFour(n),
rect = [],
best = Infinity,
solution;
for(let w = min; w <= max; w++) {
for(let h = min; h <= w; h++) {
rect.push([ w, h ]);
}
}
for(let [ w, h ] of rect) {
for(let y0 = 0; y0 < h - 1; y0++) {
for(let x0 = 0; x0 < w - 1; x0++) {
for(let y1 = 1; y1 < h; y1++) {
for(let x1 = 1; x1 < w; x1++) {
let [ score, res ] = solveRectangle(part, w, h, y0, x0, y1, x1);
if(score < best) {
best = score;
solution = { w: w, h: h, y0: y0, res: res };
}
}
}
}
}
}
return [ best, solution ]
}
function solveRectangle(part, w, h, y0, x0, y1, x1) {
let best = Infinity,
solution;
for(let p of part) {
let p0, p1, p2, p3;
if(
(p0 = getPaths(x0, h - y0 - 2)[p[0] - 1]) &&
(p1 = getPaths(w - x0 - 2, h - y1 - 1)[p[1] - 1]) &&
(p2 = getPaths(w - x1 - 1, y1 - 1 )[p[2] - 1]) &&
(p3 = getPaths(x1 - 1, y0 )[p[3] - 1])
) {
let outerArea = p0.area + p1.area + p2.area + p3.area,
score = (w - 1) * (h - 1) * 2 - outerArea;
if(score < best) {
best = score;
solution = [
p0.path,
[...p1.path].reverse(),
p2.path,
[...p3.path].reverse()
];
}
}
}
return [ best, solution ];
}
function getPaths(w, h) {
if(pathCache[[ w, h ]]) {
return pathCache[[ w, h ]];
}
let set = new Set(), list = [];
function search(x = 0, y = 0, pw = 0, ph = 1, area = 0, path = []) {
if(x == w && y == h) {
let len = path.length,
outerArea = w * h * 2 - area;
if(!set.has(len) || outerArea > list[len].area) {
set.add(len);
list[len] = {
area: outerArea,
path: path
}
}
}
for(let w0 = 1; w0 <= w - x; w0++) {
for(let h0 = 1; h0 <= h - y; h0++) {
if(h0 * pw < w0 * ph) {
search(
x + w0, y + h0, w0, h0,
area + ((w - x) * 2 - w0) * h0, [ ...path, [ w0, h0 ]]
);
}
}
}
}
search();
pathCache[[ w, h ]] = list;
pathCache[[ h, w ]] = list.map(o => ({
area: o.area,
path: [...o.path].reverse().map(([ dx, dy ]) => [ dy, dx ])
}));
return list;
}
function partitionsInFour(n) {
let list = [];
(function search(n, i = 1, l = []) {
if(n) {
if(i <= n && l.length != 4) {
search(n - i, 1, [i, ...l]);
search(n, i + 1, l);
}
}
else if(l.length == 4) {
list.push(l);
}
})(n);
return list;
}
function displaySolution(solution) {
let m = [...Array(solution.h)].map(_ => [...Array(solution.w)].fill('--')),
x, y, i = 1;
function mark(x, y) {
if(m[y][x] == '--') {
m[y][x] = i.toString().padStart(2, '0');
}
i++;
}
mark(x = 0, y = solution.y0);
mark(x, ++y);
solution.res[0].forEach(([ dx, dy ]) => mark(x += dx, y += dy));
mark(++x, y);
solution.res[1].forEach(([ dx, dy ]) => mark(x += dx, y -= dy));
mark(x, --y);
solution.res[2].forEach(([ dx, dy ]) => mark(x -= dx, y -= dy));
mark(--x, y);
solution.res[3].forEach(([ dx, dy ]) => mark(x -= dx, y += dy));
console.log(m.map(r => r.join(' ')).join('\n'));
}
```
[Try it online!](https://tio.run/##lVdtj5tGEP7uX7GVqtwSMMV21Up2HClqUykfUlW9fKhEUEJs7iDBiwU42Er826/PzMKyYOfNUrLD7rzPM7N77@OPcbUps309VcU2eXjYFKqqxctn/735W@C3FrPFatJvvnrx8jk2fwuC1WSSJ7XYx3X6R7xJE@x@OnsTEqorfPwZ14mvikY6enOXKez@6oldfCQC8ndFKUkHHfy@wvJkrS2Ddl1HfIIgmS7yxM@Le/mWGH/@pM5vHUgLQbKhqDZFmXgCXIc6K5SIwISPj4lUHllli60TQjT6lFn9RkzFrDtJ7ZOUTtjIwIFnZRKLx2LOfrBh9mXE9Vxt8qLK1L0ok00dq/s8WYK/OYsjlrQV2WbVPo9Pt61J2dnuY6uzHaX1JVLsl8VBbaXsswoH68oRv4hZEATOpauvijrOWQXZpvVcvVZt5rI7ycqfrk1VdbqFeIcQP5B/50lXtD4rtK/rZ@XQFfPV5IxyHtSGK3CZfdat4VLWkKYlI97qhfqrOJRSmQJRysARRt3Gu6SijRfqLlNZfeq2Owc4ng5JVF0YXYEAlmAZVIeknivtuFLiarD2PNoBf3@oUhmKxgNPxOXSCTnb1rpzUdyx1NjOKYChYEXrE6ERBdq21XEeW84jcTaa8zjgtLTOqCtXtEIrrUM@S2vLeSTOhtYx56iHyqTq2@ffDruSquVxrB789@AZ1hnWmUZT/wOuWBXsUdnGxkwxmWk1OjMdjEkimiUbXGqbS7YL95bs43koep5cozvqbBWPqlsfSoWQyRN7alwi@LsSYJD9IzDdE2JIaZcg3oTSPZTu5/i3aBOLhLaK5J4wcp/U/2AcVJJc6H4ELWBsKuZOuA@DiPATOeLRIyM6s0UJX0dm97TojARIdHZFdH4hyuxeK0ZMJDq/IroYONyK0Q/Otj8SXbSiLNdDhnJSHOqk5KGLmRH4MVEusmSouaEWTHkWFDQS14K9RqUeC5l21ByEUW5A/BX4XgeuBdnQsgxX6V60nQl934fftB35ZfIxKatEOjYHYrkqtBgLGYZo9WMQH07pvqiAgQ4V8Zv7POymW9SlodV7hWPVTUaqWZVQolTSiNukRogizyo90XUPmB5L4nKTSrpMqJ30sm/alWY00BLr2tMOzLKWzh04C1nMb0COxNddFB148kTxVYPbE@T9MLU2shoAIm1BEY/w8BPC8dO4Qt8qR3z@bAk@5chCHESMPRsuJBVvtyxlzUgjQDPO8obEl73qASzg/5L//@JkG1w6TaCHPla63Khh6eParZO2rCmz8iigj@ElgRzg/DFV5gkpBZUO53pbyMFIPqIlGy6rC40e01gHPG3nSj1Vuq5sAqJIJhQEf2oJumlZAbBmqXBWXx32E@MaM17BLcKnioxPYbDpT/1dvJeFWD8VUkfdFsuaN7pG1K3FuFlZGi@J7dET2xPeEqQInyd8HgUPvbOjIdL2l/bI7tQrryVz7QybS467C@@vTHdSPm4e1VcRXxlBQFEr5W23iJ/wSh9iWqtEkTKPVIZYEHMeWYWw7bps17mcUkIkeZWQWWNsPTDGeec3WG4/vhypvpGqLz6qTcJ2lAd4/aws45Psn7ZOxKV6w/W5PG9wfpflubyZTm8cM7hR1VOb4uF028XlB0mnVsZ34SkKjxHFylpMuOZAZH5d3NYl/nYAdPbx9rZG7SUu6pvgxsoE1LmumbraVj9HjdOnwFmZc0@47om/zTneUngu@JgHzwH9C5i2et01b5@YODm9StflAC9Uzr5f5XSkEpvT6RWV82@qnH5J5XR63cvF96s0gY/@yNoxZEoSKf33RabkjQA4WvK1uiGZ88PD/w "JavaScript (Node.js) – Try It Online") (up to \$n=13\$)
### Output
```
n = 7
Area * 2 = 13
Enclosing rectangle: 3 x 3
01 07 -- --
02 -- -- 06
-- -- -- 05
-- 03 04 --
Total time: 0s
n = 8
Area * 2 = 14
Enclosing rectangle: 3 x 3
-- 08 07 --
01 -- -- 06
02 -- -- 05
-- 03 04 --
Total time: 0s
n = 9
Area * 2 = 21
Enclosing rectangle: 4 x 4
01 09 -- -- --
02 -- -- 08 --
-- -- -- -- 07
-- 03 -- -- 06
-- -- 04 05 --
Total time: 0s
n = 10
Area * 2 = 28
Enclosing rectangle: 5 x 4
-- 10 09 -- -- --
01 -- -- -- 08 --
02 -- -- -- -- 07
-- 03 -- -- -- 06
-- -- -- 04 05 --
Total time: 0s
n = 11
Area * 2 = 43
Enclosing rectangle: 6 x 5
-- 11 10 -- -- -- --
01 -- -- -- -- 09 --
02 -- -- -- -- -- 08
-- -- -- -- -- -- 07
-- 03 -- -- -- 06 --
-- -- 04 05 -- -- --
Total time: 1s
n = 12
Area * 2 = 48
Enclosing rectangle: 6 x 6
-- 12 11 -- -- -- --
01 -- -- -- 10 -- --
02 -- -- -- -- 09 --
-- -- -- -- -- -- --
-- 03 -- -- -- -- 08
-- -- 04 -- -- -- 07
-- -- -- -- 05 06 --
Total time: 4s
n = 13
Area * 2 = 65
Enclosing rectangle: 8 x 6
-- 13 12 -- -- -- -- -- --
01 -- -- -- -- 11 -- -- --
02 -- -- -- -- -- -- 10 --
-- -- -- -- -- -- -- -- 09
-- 03 -- -- -- -- -- -- 08
-- -- 04 -- -- -- -- 07 --
-- -- -- -- 05 06 -- -- --
Total time: 7s
n = 14
Area * 2 = 80
Enclosing rectangle: 8 x 7
-- -- -- 13 12 -- -- -- --
-- 14 -- -- -- -- 11 -- --
01 -- -- -- -- -- -- 10 --
02 -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- 09
-- 03 -- -- -- -- -- -- 08
-- -- 04 -- -- -- -- 07 --
-- -- -- -- 05 06 -- -- --
Total time: 22s
n = 15
Area * 2 = 103
Enclosing rectangle: 9 x 8
-- -- 14 13 -- -- -- -- -- --
-- 15 -- -- -- -- 12 -- -- --
-- -- -- -- -- -- -- -- 11 --
01 -- -- -- -- -- -- -- -- 10
02 -- -- -- -- -- -- -- -- 09
-- -- -- -- -- -- -- -- -- --
-- 03 -- -- -- -- -- -- 08 --
-- -- 04 -- -- -- -- 07 -- --
-- -- -- -- 05 06 -- -- -- --
Total time: 38s
n = 16
Area * 2 = 118
Enclosing rectangle: 9 x 9
-- -- -- -- 14 13 -- -- -- --
-- -- 15 -- -- -- -- 12 -- --
-- 16 -- -- -- -- -- -- 11 --
-- -- -- -- -- -- -- -- -- --
01 -- -- -- -- -- -- -- -- 10
02 -- -- -- -- -- -- -- -- 09
-- -- -- -- -- -- -- -- -- --
-- 03 -- -- -- -- -- -- 08 --
-- -- 04 -- -- -- -- 07 -- --
-- -- -- -- 05 06 -- -- -- --
Total time: 70s
n = 17
Area * 2 = 151
Enclosing rectangle: 11 x 10
-- -- -- 16 15 -- -- -- -- -- -- --
-- 17 -- -- -- -- -- 14 -- -- -- --
01 -- -- -- -- -- -- -- -- 13 -- --
02 -- -- -- -- -- -- -- -- -- 12 --
-- -- -- -- -- -- -- -- -- -- -- --
-- 03 -- -- -- -- -- -- -- -- -- 11
-- -- -- -- -- -- -- -- -- -- -- 10
-- -- -- -- -- -- -- -- -- -- -- --
-- -- -- 04 -- -- -- -- -- -- 09 --
-- -- -- -- 05 -- -- -- -- 08 -- --
-- -- -- -- -- -- 06 07 -- -- -- --
Total time: 98s
n = 18
Area * 2 = 174
Enclosing rectangle: 12 x 10
-- -- -- -- 16 15 -- -- -- -- -- -- --
-- -- 17 -- -- -- -- -- 14 -- -- -- --
-- 18 -- -- -- -- -- -- -- -- 13 -- --
-- -- -- -- -- -- -- -- -- -- -- 12 --
01 -- -- -- -- -- -- -- -- -- -- -- --
02 -- -- -- -- -- -- -- -- -- -- -- 11
-- -- -- -- -- -- -- -- -- -- -- -- 10
-- 03 -- -- -- -- -- -- -- -- -- -- --
-- -- 04 -- -- -- -- -- -- -- -- 09 --
-- -- -- -- 05 -- -- -- -- -- 08 -- --
-- -- -- -- -- -- -- 06 07 -- -- -- --
Total time: 202s
n = 19
Area * 2 = 213
Enclosing rectangle: 13 x 12
-- -- 18 17 -- -- -- -- -- -- -- -- -- --
-- 19 -- -- -- -- 16 -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- 15 -- -- -- -- --
01 -- -- -- -- -- -- -- -- -- -- -- -- --
02 -- -- -- -- -- -- -- -- -- -- 14 -- --
-- -- -- -- -- -- -- -- -- -- -- -- 13 --
-- -- -- -- -- -- -- -- -- -- -- -- -- --
-- 03 -- -- -- -- -- -- -- -- -- -- -- 12
-- -- -- -- -- -- -- -- -- -- -- -- -- 11
-- -- 04 -- -- -- -- -- -- -- -- -- -- --
-- -- -- 05 -- -- -- -- -- -- -- -- 10 --
-- -- -- -- -- 06 -- -- -- -- -- 09 -- --
-- -- -- -- -- -- -- -- 07 08 -- -- -- --
Total time: 436s
```
[Answer]
# Fortran n=17, 323 s
```
C Find strictly convex polygons of minimum area on square grid
C Author: Hugo Pfoertner, 2018
implicit integer (A-Z)
parameter (vlarge=2147483647)
C Number of vertices
parameter (n=17)
C Number of coordinate pairs to be used as polygon edges,
C read from external list
parameter (ms=2048)
C Length of lists for segments, coordinates, areas
C Must be extended for n>nm
parameter (nm=25)
dimension xd(ms), yd(ms), x(nm), y(nm), a(nm), as(nm), nn(nm)
equivalence
& (n1,nn(1)),(n2,nn(2)),(n3,nn(3)),(n4,nn(4)),(n5,nn(5)),
& (n6,nn(6)),(n7,nn(7)),(n8,nn(8)),(n9,nn(9)),(n10,nn(10)),
& (n11,nn(11)),(n12,nn(12)),(n13,nn(13)),(n14,nn(14)),
& (n15,nn(15)),(n16,nn(16)),(n17,nn(17)),(n18,nn(18)),
& (n19,nn(19)),(n20,nn(20)),(n21,nn(21)),(n22,nn(22)),
& (n23,nn(23)),(n24,nn(24)),(n25,nn(25))
C Number of polygons with minimal area found
integer*8 count
C File names of external files, command argument
character*15 bspirx, bspiry, carg
C Progress indicator line
character pline*150
C CPU time
real cptime
C function to calculate d^2 of enclosing circle,
C to be replaced by function encirc
C if exact enclosing circle is needed
integer diamet
external diamet
C variables needed in diameter calculation
doubleprecision xc, yc, rc, d, diamin, diamax
C Some choices for OEIS files describing spirals
C Square spiral
C data bspirx, bspiry /'b174344.txt', 'b274923.txt' /
C Circular rings (Sloane)
C data bspirx, bspiry /'b283307.txt', 'b283308.txt' /
C Circular rings
data bspirx, bspiry /'../b305575.txt', '../b305576.txt' /
C Statement function: Double area of triangle
triar(x1,y1, x2,y2, x3,y3) =
& x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2)
C Progress indicator
pline = '....+....1....+....2....+....3....+....4....+....5' //
& '....+....6....+....7....+....8....+....9....+....A' //
& '....+....B....+....C....+....D....+....E....+....F'
C
C read external files with coordinates of points in spiral
C X
open ( unit=10, file=bspirx, status='old',
& form='formatted', iostat=ios)
if ( ios .ne. 0 ) stop 'Error opening bfile spiral x'
do 1 i = 1, ms
read (10,*,end=999) k, xd(i)
1 continue
close (unit=10)
C Y
open ( unit=10, file=bspiry, status='old',
& form='formatted', iostat=ios)
if ( ios .ne. 0 ) stop 'Error opening bfile spiral y'
do 2 i = 1, ms
read (10,*,end=999) k, yd(i)
2 continue
close (unit=10)
C
C For convenience: write first nonnegative (x,y) pairs to terminal
do 3 i = 2, 120
if (xd(i) .ge. 0 .and. yd(i) .ge. 0 ) write (*,1003)i,xd(i),yd(i)
1003 format ( 3 i3 )
3 continue
C
C preset minimum area
ami = vlarge
C if an upper bound is known: least area + 1
C ami = 183
C preset diameter extreme values
diamin = 1.0D20
diamax = 0.0D0
C Total number of polygons with same minimum area
count = 0
C get number of list items from first parameter of program call
CALL get_command_argument(1, carg)
read (carg, *) m
if ( m .gt. ms ) stop 'm exceeds length of segment list'
write (*,*) 'Segments used:', m
C get index of
CALL get_command_argument(2, carg)
read (carg, *) n2first
if ( xd(n2first) .lt. 0 .or. yd(n2first) .lt. 0 )
& stop 'illegal negative start step'
C limit range, assuming first coordinate pair on files is (0,0)
n2first = max(2,min (m,n2first))
write (*,*) 'First start step:', xd(n2first), yd(n2first)
C
C Start building the polygon
C
C Freeze first point
x(1) = 0
y(1) = 0
n1 = 0
C
C loop over second point
do 20 n2 = n2first, m
L = 2
x(L) = xd(nn(L))
y(L) = yd(nn(L))
C
C Limit to angle 0 <= Pi/2
if ( x(L) .lt. 0 .or. y(L) .lt. 0 .or. y(L) .gt. x(L) ) goto 20
C
C optional: Exclusion of extremely long segments
C if (dble(x(L)**2 + y(L)**2) .gt. diamin) goto 20
write (*,1006) count, n2, xd(nn(L)), yd(nn(L))
1006 format (/,'Min area polygons found so far: ', i0,
& ', next n2 = ', i0, ' (',i0,',',i0,')')
C if wanted: progress indicator
WRITE(*, 1004, ADVANCE='NO') pline(1:1)
1004 format (A1)
C loop over third point
do 30 n3 = 2, m
C Progress indicator
WRITE(*, 1004, ADVANCE='NO') pline(n3:n3)
L = 3
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
as(L) = a(L)
if ( a(L) .le. 0 ) goto 30
if ( a(L) .gt. ami-n+L ) goto 30
C The following blocks are repeated in code with adaptation for
C current segment number (code easily generated by a small script
C or preprocessor)
do 40 n4 = 2, m
L = 4
C try extension by segment from list
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
C area contribution
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 40
C left turn?
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0) goto 40
C start point still left of straight line through endpoints of segment?
if ( triar(x(1),y(1), x(2),y(2), x(L),y(L)) .le. 0 ) goto 40
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 40
C
do 50 n5 = 2, m
L = 5
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar ( x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 50
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0) goto 50
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 50
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 50
C
do 60 n6 = 2, m
L = 6
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 60
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0) goto 60
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 60
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 60
C
do 70 n7 = 2, m
L = 7
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 70
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0) goto 70
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 70
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 70
C
do 80 n8 = 2, m
L = 8
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 80
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0) goto 80
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 80
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 80
C
do 90 n9 = 2, m
L = 9
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 90
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0) goto 90
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 90
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 90
C
do 100 n10 = 2, m
L = 10
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 100
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0)goto 100
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 100
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 100
C
do 110 n11 = 2, m
L = 11
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 110
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0)goto 110
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 110
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 110
C
do 120 n12 = 2, m
L = 12
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 120
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0)goto 120
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 120
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 120
C
do 130 n13 = 2, m
L = 13
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 130
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0)goto 130
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 130
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 130
C
do 140 n14 = 2, m
L = 14
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 140
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0)goto 140
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 140
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 140
C
do 150 n15 = 2, m
L = 15
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 150
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0)goto 150
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 150
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 150
C
do 160 n16 = 2, m
L = 16
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 160
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0)goto 160
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 160
as(L) = as(L-1) + a(L)
if ( as(L) .gt. ami-n+L ) goto 160
C
do 170 n17 = 2, m
L = 17
x(L) = x(L-1) + xd(nn(L))
y(L) = y(L-1) + yd(nn(L))
a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
if ( a(L) .le. 0 ) goto 170
if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0)goto 170
if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 170
as(L) = as(L-1) + a(L)
C in last line of repeated code part n=L
c if ( as(L) .gt. ami-n+L ) goto 170
C example how to continue for n>17
c do 180 n18 = 2, m
c L = 18
c x(L) = x(L-1) + xd(nn(L))
c y(L) = y(L-1) + yd(nn(L))
c a(L) = triar (x(1),y(1), x(L-1),y(L-1), x(L),y(L))
c if ( a(L) .le. 0 ) goto 180
c if (triar(x(L-2),y(L-2), x(L-1),y(L-1), x(L),y(L)) .le. 0)goto 180
c if ( triar (x(L),y(L), x(1),y(1), x(2),y(2)) .le. 0 ) goto 180
c as(L) = as(L-1) + a(L)
c if ( as(L) .gt. ami-n+L ) goto 180
C ...
C ...
C
C Update minimum
if ( as(L) .lt. ami ) then
count = 0
ami = as(L)
C
C alternative with exact enclosing circle
C call encirc ( 1, n, x, y, xc, yc, rc )
C diamin = 4*rc**2
call cpu_time (cptime)
C type cast assumed to work diamin (real*8) = diamet (integer)
diamin = diamet (n,x,y)
write (*,1000) n, as(L), diamin, (x(k),y(k),k=1,n)
1000 format (/,i2, 1X, i0, f14.6, 2x, 25('(',i0,',',i0,')',:,',') )
write (*,1001) cptime, nn(2:n)
1001 format ( F12.4,' s: ',i0, 25(1X,i0,:) )
endif
C
C check for multiple solutions with same mimimum area
if ( as(L) .eq. ami ) then
call cpu_time (cptime)
d = diamet(n,x,y)
C call encirc ( 1, n, x, y, xc, yc, rc )
C d = 4*rc**2
count = count + 1
if ( d .lt. diamin ) then
diamin = d
write (*,1000) n, as(L), diamin, (x(k),y(k),k=1,n)
write (*,1001) cptime, nn(2:n)
endif
if ( d .gt. diamax ) then
diamax = d
write (*,1000) n, as(L), -diamax, (x(k),y(k),k=1,n)
write (*,1001) cptime, nn(2:n)
endif
endif
250 continue
240 continue
230 continue
220 continue
210 continue
200 continue
190 continue
180 continue
170 continue
160 continue
150 continue
140 continue
130 continue
120 continue
110 continue
100 continue
90 continue
80 continue
70 continue
60 continue
50 continue
40 continue
30 continue
20 continue
C
call cpu_time ( cptime )
write (*,1007) cptime, count
1007 format (/,'CPU time: ', f12.4, ' s',/,
& 'Number of polygons with minimum area: ', i0)
999 continue
end
C
C Maximum of mutual point distance sufficient as an estimate.
C Exact enclosing circle needs a more sophisticated method,
C e.g., Welz's algorithm
integer function diamet (n, x, y)
integer n, x(*), y(*)
id = 0
do 10 i = 1, n-1
do 20 j = i+1, n
jd = (x(i)-x(j))**2 + (y(i)-y(j))**2
id = max (id,jd)
20 continue
10 continue
diamet = id
end
```
This is essentially the first version of the program I started with in 2018 just for illustration with no tweaks. It's more to have a place to make some general notes on pitfalls of this problem that I think are important. When those are scattered in comments on individual answers, it's hard to keep track of.
The program only handles the case n=17, which I chose because it is the smallest n without a proof of optimality. In order to run the program, 2 external files are required, namely the b-files of the OEIS sequences [A305575](https://oeis.org/A305575) and [A305576](https://oeis.org/A305576), which should be one directory above the program.
A typical output looks like this:
```
.\17.exe 56 1
2 1 0
3 0 1
...
114 6 1
115 1 6
Segments used: 56
First start step: 1 0
Min area polygons found so far: 0, next n2 = 2 (1,0)
...
17 185 373.000000 (0,0),(1,0),(1,1),(0,3),(-1,4),(-4,6),(-6,7),(-9,8),(-13,9),(-14,9),(-16,8),(-17,7),(-17,6),(-16,5),(-13,3),(-11,2),(-8,1)
0.0469 s: 2 3 16 7 41 17 33 53 4 18 8 5 9 45 21 37
17 185 -373.000000 (0,0),(1,0),(1,1),(0,3),(-1,4),(-4,6),(-6,7),(-9,8),(-13,9),(-14,9),(-16,8),(-17,7),(-17,6),(-16,5),(-13,3),(-11,2),(-8,1)
0.0469 s: 2 3 16 7 41 17 33 53 4 18 8 5 9 45 21 37
17 178 370.000000 (0,0),(1,0),(1,1),(0,3),(-2,5),(-5,7),(-7,8),(-10,9),(-14,10),(-15,10),(-16,9),(-16,8),(-15,6),(-14,5),(-11,3),(-9,2),(-6,1)
0.0938 s: 2 3 16 23 41 17 33 53 4 8 5 20 9 45 21 37
17 159 306.000000 (0,0),(1,0),(1,1),(0,3),(-2,6),(-3,7),(-5,8),(-8,9),(-12,10),(-13,10),(-14,9),(-14,8),(-13,6),(-12,5),(-9,3),(-7,2),(-4,1)
0.1094 s: 2 3 16 40 7 17 33 53 4 8 5 20 9 45 21 37
17 159 296.000000 (0,0),(1,0),(1,1),(0,3),(-2,6),(-3,7),(-6,9),(-8,10),(-11,11),(-12,11),(-13,10),(-13,9),(-12,7),(-10,4),(-9,3),(-7,2),(-4,1)
0.1094 s: 2 3 16 40 7 41 17 33 4 8 5 20 44 9 21 37
17 157 265.000000 (0,0),(1,0),(1,1),(0,4),(-1,6),(-3,9),(-4,10),(-6,11),(-9,12),(-10,12),(-11,11),(-11,10),(-10,7),(-9,5),(-8,4),(-5,2),(-3,1)
0.2969 s: 2 3 32 16 40 7 17 33 4 8 5 36 20 9 45 21
.+.
17 157 232.000000 (0,0),(1,0),(2,1),(2,2),(1,4),(0,5),(-3,7),(-5,8),(-8,9),(-9,9),(-11,8),(-12,7),(-12,6),(-11,4),(-10,3),(-8,2),(-5,1)
0.9844 s: 2 6 3 16 7 41 17 33 4 18 8 5 20 9 21 37
17 151 202.000000 (0,0),(1,0),(2,1),(2,2),(1,4),(-1,7),(-2,8),(-5,10),(-7,11),(-8,11),(-9,10),(-10,8),(-10,7),(-9,5),(-8,4),(-5,2),(-3,1)
1.0469 s: 2 6 3 16 40 7 41 17 4 8 19 5 20 9 45 21
17 151 193.000000 (0,0),(1,0),(2,1),(2,2),(1,5),(0,7),(-1,8),(-3,9),(-6,10),(-7,10),(-9,9),(-10,8),(-10,7),(-9,5),(-8,4),(-5,2),(-3,1)
1.1406 s: 2 6 3 32 16 7 17 33 4 18 8 5 20 9 45 21
17 151 137.000000 (0,0),(1,0),(2,1),(3,3),(3,4),(2,7),(1,9),(0,10),(-2,11),(-3,11),(-5,10),(-6,9),(-7,7),(-7,6),(-6,4),(-5,3),(-2,1)
2.1562 s: 2 6 15 3 32 16 7 17 4 18 8 19 5 20 9 45
...1....+....2....+....3....+....4....+....5....+.
Min area polygons found so far: 24, next n2 = 6 (1,1)
....+....1....+....2....+....3....+....4....+....5....+.
Min area polygons found so far: 48, next n2 = 10 (2,0)
....+....1....+....2....+....3....+....4....+....5....+.
Min area polygons found so far: 48, next n2 = 14 (2,1)
....+....1....+....2....+....3....+....4....+....5....+.
Min area polygons found so far: 65, next n2 = 22 (2,2)
....+....1....+....2....+....3....+....4....+....5....+.
Min area polygons found so far: 65, next n2 = 26 (3,0)
....+....1....+....2....+....3....+....4....+....5....+.
Min area polygons found so far: 65, next n2 = 30 (3,1)
....+....1....+....2....+....3....+....4....+....5....+.
Min area polygons found so far: 70, next n2 = 38 (3,2)
....+....1....+....2....+....3....+....4....+....5....+.
Min area polygons found so far: 76, next n2 = 46 (4,0)
....+....1....+....2....+....3....+....4....+....5....+.
Min area polygons found so far: 76, next n2 = 50 (4,1)
....+....1....+....2....+....3....+....4....+....5....+.
CPU time: 323.0781 s
Number of polygons with minimum area: 76
```
For n=17 there is not only the [compact solution](http://antiton.de/PolygonalAreas/index.html?(8,1),(9,1),(10,2),(11,4),(11,5),(10,8),(9,10),(8,11),(6,12),(5,12),(3,11),(2,10),(1,8),(1,7),(2,5),(3,4),(6,2)) found by everyone, but also exotic needle-shaped solutions, like [Squared diameter 1361](http://antiton.de/PolygonalAreas/index.html?(31,1),(32,1),(32,2),(31,3),(27,6),(24,8),(16,13),(11,16),(4,20),(2,21),(1,21),(2,20),(6,17),(13,12),(16,10),(24,5),(29,2)).
[](https://i.stack.imgur.com/7reqI.png)
This is the one I've known so far with the largest diameter. As far as I know, it has not been proven that no extreme solutions of this kind with a smaller area exist. If one could show that there are no other solutions with even greater stretching, then that would be an important step towards a proof of optimality for this n.
## Heavily stretched polygons
I don't want to spoil anyone's good mood, but if you all only find the solutions that I gave 4 years ago, the doubts remain whether we are making things too easy for ourselves when searching. I have already pointed out the existence of very strongly stretched polygons with likewise minimal areas. As a test case for your programs, you can try to find at least one even slimmer solution than the following at n=19:
[n=19, 2\*Area=213, Diameter^2=1105](http://antiton.de/PolygonalAreas/index.html?(31,1),(32,1),(32,2),(31,3),(29,4),(24,6),(16,9),(13,10),(6,12),(2,13),(1,13),(1,12),(2,11),(5,9),(7,8),(12,6),(15,5),(22,3),(26,2))
My program finds the shown and -intentionally undisclosed- slimmer solutions (squared diameters = 5\*prime number, prime, ..) after about 200 s (17700 s for the prime squared diameter) using 1000 points from the spiral files.
If other programs also find these solutions, then that would increase my confidence considerably.
### Update
In the meantime I have found that all of the strongly distorted and needle-shaped polygons found by my programs can be reduced to the already known slightly deformed shapes by applying shear transformations. So far I haven't found any exceptions to this observation. Apparently, allowing longer polygon sides does not bring any advantage in terms of further reducing the area. In a way, this contradicts the asymptotic elliptical shape described in the work of [Bárány, I., Tokushige, N. (2004)](https://doi.org/10.1007%2Fs00493-004-0012-0) or [version without paywall](http://www.renyi.hu/%7Ebarany/cikkek/94.pdf) with semi-axes \$a=0.003573 n^2\$ and \$b=1.656 n\$, which at \$n=27\$ gives an axis ratio of about \$1/15\$. The observed ratio of the solution with \$2\*A(27)=625\$, which has meanwhile also been found by my own program, is only about \$1/2\$.
# Fortran revised, n=17, 8.8 s
See [Lattice-Polygons](https://github.com/HugoPfoertner/Lattice-Polygons) on GitHub. Another faster version exists (approx. 70% of run time), with explicit expansion of the inner loops, similar to code shown above, but the GitHub version is cleaner.
[Answer]
# Python, *n*=44 in under 2 minutes
This can go up to 44-gons in under 2 minutes, using pypy on my laptop.
CPython is slightly slower (2'45'').
The approach is rigorous. It uses the
dynamic programming
algorithm in the following paper:
* David Eppstein, Mark Overmars, Günter Rote und Gerhard Woeginger,
Finding minimum area k-gons.
*Discrete and Computational Geometry* **7** (1992), 45-58.
<https://doi.org/10.1007/BF02187823>
* see also:
Joseph S. B. Mitchell, Günter Rote, Gopalakrishnan Sundaram,
and Gerhard Woeginger,
Counting convex polygons in planar point sets.
*Information Processing Letters* **56** (1995), 45-49.
<http://page.mi.fu-berlin.de/rote/Papers/abstract/Counting+k-subsets+and+convex+k-gons+in+the+plane.html>
The algorithm is also explained in the comments of the code.
Here are some smallest polygons:
* 20-gon, area=242/2: [(0,0),(3,1),(5,2),(6,3),(7,5),(7,6),(6,8),(5,9),(3,10),(0,11),(-1,11),(-4,10),(-6,9),(-7,8),(-8,6),(-8,5),(-7,3),(-6,2),(-4,1),(-1,0)]
* 21-gon, area=289/2: [(0,0),(2,1),(5,3),(6,4),(8,7),(9,9),(10,12),(10,13),(9,14),(7,15),(6,15),(3,14),(1,13),(-2,11),(-3,10),(-4,8),(-5,5),(-5,4),(-4,2),(-3,1),(-1,0)]
* 22-gon, area=328/2: [(0,0),(3,1),(5,2),(8,4),(9,5),(10,7),(10,8),(9,10),(8,11),(6,12),(3,13),(2,13),(-1,12),(-3,11),(-6,9),(-7,8),(-8,6),(-8,5),(-7,3),(-6,2),(-4,1),(-1,0)]
* 23-gon, area=387/2: [(0,0),(3,1),(5,2),(6,3),(7,5),(8,8),(8,9),(7,11),(6,12),(4,13),(1,14),(0,14),(-4,13),(-7,12),(-9,11),(-10,10),(-11,8),(-11,7),(-10,5),(-9,4),(-6,2),(-4,1),(-1,0)]
* 24-gon, area=420/2: [(0,0),(3,1),(5,2),(8,4),(9,5),(11,8),(12,10),(13,13),(13,14),(12,16),(11,17),(9,18),(8,18),(5,17),(3,16),(0,14),(-1,13),(-3,10),(-4,8),(-5,5),(-5,4),(-4,2),(-3,1),(-1,0)]
* 25-gon, area=497/2: [(0,0),(3,1),(5,2),(8,4),(9,5),(10,7),(11,10),(11,11),(10,13),(9,14),(7,15),(4,16),(3,16),(-1,15),(-4,14),(-6,13),(-9,11),(-10,10),(-11,8),(-11,7),(-10,5),(-9,4),(-6,2),(-4,1),(-1,0)]
* 26-gon, area=548/2: [(0,0),(3,1),(5,2),(8,4),(9,5),(11,8),(12,10),(13,13),(13,14),(12,16),(11,17),(9,18),(6,19),(5,19),(2,18),(0,17),(-3,15),(-4,14),(-6,11),(-7,9),(-8,6),(-8,5),(-7,3),(-6,2),(-4,1),(-1,0)]
* 27-gon, area=625/2: [(0,0),(3,1),(5,2),(8,4),(9,5),(11,8),(12,10),(13,13),(14,17),(14,18),(13,20),(12,21),(10,22),(9,22),(6,21),(4,20),(1,18),(-3,15),(-4,14),(-6,11),(-7,9),(-8,6),(-8,5),(-7,3),(-6,2),(-4,1),(-1,0)]
* 28-gon, area=690/2: [(0,0),(4,1),(7,2),(9,3),(12,5),(13,6),(15,9),(16,11),(17,14),(17,15),(16,17),(15,18),(13,19),(10,20),(9,20),(5,19),(2,18),(0,17),(-3,15),(-4,14),(-6,11),(-7,9),(-8,6),(-8,5),(-7,3),(-6,2),(-4,1),(-1,0)]
* 29-gon, area=783/2: [(0,0),(3,1),(5,2),(8,4),(9,5),(12,9),(14,12),(15,14),(16,17),(16,18),(15,20),(14,21),(12,22),(9,23),(8,23),(4,22),(1,21),(-1,20),(-4,18),(-5,17),(-7,14),(-8,12),(-9,9),(-9,8),(-8,5),(-7,3),(-6,2),(-4,1),(-1,0)]
* 30-gon, area=860/2: [(0,0),(4,1),(7,2),(9,3),(12,5),(13,6),(15,9),(16,11),(17,14),(17,15),(16,18),(15,20),(14,21),(12,22),(9,23),(8,23),(4,22),(1,21),(-1,20),(-4,18),(-5,17),(-7,14),(-8,12),(-9,9),(-9,8),(-8,5),(-7,3),(-6,2),(-4,1),(-1,0)]
* 31-gon, area=967/2: [(0,0),(4,1),(7,2),(9,3),(12,5),(13,6),(15,9),(16,11),(17,14),(18,18),(18,19),(17,22),(16,24),(15,25),(13,26),(12,26),(8,25),(5,24),(3,23),(0,21),(-4,18),(-5,17),(-7,14),(-8,12),(-9,9),(-9,8),(-8,5),(-7,3),(-6,2),(-4,1),(-1,0)]
* 32-gon, area=1046/2: [(0,0),(3,1),(5,2),(8,4),(9,5),(11,8),(12,10),(13,13),(13,14),(12,17),(11,19),(9,22),(8,23),(5,25),(3,26),(0,27),(-1,27),(-4,26),(-6,25),(-9,23),(-10,22),(-12,19),(-13,17),(-14,14),(-14,13),(-13,10),(-12,8),(-10,5),(-9,4),(-6,2),(-4,1),(-1,0)]
* 33-gon, area=1177/2: [(0,0),(3,1),(5,2),(8,4),(12,7),(13,8),(16,12),(18,15),(19,17),(20,20),(21,24),(21,25),(20,27),(19,28),(17,29),(14,30),(13,30),(9,29),(6,28),(4,27),(1,25),(-3,22),(-4,21),(-6,18),(-7,16),(-8,13),(-9,9),(-9,8),(-8,5),(-7,3),(-6,2),(-4,1),(-1,0)]
* 34-gon, area=1264/2: [(0,0),(4,1),(7,2),(9,3),(12,5),(13,6),(15,9),(16,11),(17,14),(17,15),(16,18),(15,20),(13,23),(12,24),(9,26),(7,27),(4,28),(3,28),(-1,27),(-4,26),(-6,25),(-9,23),(-10,22),(-12,19),(-13,17),(-14,14),(-14,13),(-13,10),(-12,8),(-10,5),(-9,4),(-6,2),(-4,1),(-1,0)]
* 35-gon, area=1409/2: [(0,0),(4,1),(7,2),(9,3),(12,5),(13,6),(15,9),(16,11),(17,14),(17,15),(16,18),(15,20),(13,23),(12,24),(10,25),(7,26),(3,27),(2,27),(-3,26),(-7,25),(-10,24),(-12,23),(-15,21),(-16,20),(-17,18),(-18,15),(-18,14),(-17,11),(-16,9),(-14,6),(-13,5),(-10,3),(-8,2),(-5,1),(-1,0)]
* 36-gon, area=1498/2: [(0,0),(4,1),(7,2),(9,3),(12,5),(13,6),(15,9),(16,11),(17,14),(17,15),(16,18),(15,20),(13,23),(12,24),(9,26),(7,27),(4,28),(0,29),(-1,29),(-5,28),(-8,27),(-10,26),(-13,24),(-14,23),(-16,20),(-17,18),(-18,15),(-18,14),(-17,11),(-16,9),(-14,6),(-13,5),(-10,3),(-8,2),(-5,1),(-1,0)]
* 37-gon, area=1671/2: [(0,0),(4,1),(7,2),(9,3),(12,5),(13,6),(16,10),(18,13),(19,15),(20,18),(20,19),(19,22),(18,24),(17,25),(14,27),(12,28),(9,29),(5,30),(4,30),(-1,29),(-5,28),(-8,27),(-10,26),(-13,24),(-14,23),(-16,20),(-17,18),(-18,15),(-18,14),(-17,11),(-16,9),(-14,6),(-13,5),(-10,3),(-8,2),(-5,1),(-1,0)]
* 38-gon, area=1780/2: [(0,0),(4,1),(7,2),(9,3),(12,5),(13,6),(15,9),(16,11),(17,14),(18,18),(18,19),(17,22),(16,24),(14,27),(13,28),(10,30),(8,31),(5,32),(1,33),(0,33),(-4,32),(-7,31),(-9,30),(-12,28),(-13,27),(-15,24),(-16,22),(-17,19),(-18,15),(-18,14),(-17,11),(-16,9),(-14,6),(-13,5),(-10,3),(-8,2),(-5,1),(-1,0)]
* 39-gon, area=1955/2: [(0,0),(4,1),(7,2),(9,3),(12,5),(13,6),(15,9),(16,11),(17,14),(18,18),(18,19),(17,22),(16,24),(14,27),(13,28),(10,30),(8,31),(5,32),(1,33),(0,33),(-5,32),(-9,31),(-12,30),(-14,29),(-17,27),(-18,26),(-20,23),(-21,21),(-22,18),(-22,17),(-21,14),(-20,12),(-18,9),(-17,8),(-13,5),(-10,3),(-8,2),(-5,1),(-1,0)]
* 40-gon, area=2078/2: [(0,0),(4,1),(7,2),(9,3),(12,5),(13,6),(15,9),(16,11),(17,14),(18,18),(18,19),(17,23),(16,26),(15,28),(13,31),(12,32),(9,34),(7,35),(4,36),(0,37),(-1,37),(-5,36),(-8,35),(-10,34),(-13,32),(-14,31),(-16,28),(-17,26),(-18,23),(-19,19),(-19,18),(-18,14),(-17,11),(-16,9),(-14,6),(-13,5),(-10,3),(-8,2),(-5,1),(-1,0)]
The target value of N can be given on the command line.
## The minimum area of a convex polygon of given lattice width
The correctness of the program (knowing when one can stop) depends crucially on two lemmas that relate area to *lattice width*. The first lemma is about centrally symmetric polygons (arising when *n* is even), and the second lemma about arbitrary polygons.
**Definition:**
The *lattice width* of a lattice polygon P *in a given lattice direction*
(a,b) in Z² is one less than the number of lattice lines orthogonal to (a,b)
intersecting P.
The *lattice width* of P is the smallest number lattice width over
all lattice directions.
### Lemma 3:
>
> A centrally symmetric convex polygon P of lattice width w has area
> at least w²/2.
>
>
>
Proof:
[ A weaker bound of w²/4 is given in the following paper
(p.175, before remark 2):
* Imre Bárány and Norihide Tokushige, The minimum area of convex lattice n-gons.
*Combinatorica* **24** (No. 2, 2004), 171-185.
[https://www.renyi.hu/~barany/cikkek/94.pdf](https://www.renyi.hu/%7Ebarany/cikkek/94.pdf).
Our proof uses the same setup but refines the argument in the end.
The improvement to w²/2 speeds up the computations by a factor 5-6. ]
1. We assume that the lattice width direction is vertical.
Thus P touches two horizontal lines H+: y=b and H-: y=-b, with b=w/2.
Let (a,0) be the intersection of P with the positive x-axis.
2. If a>=b, then the area is at least 2b²=w²/2, and we are done.
Thus, let us assume a<b.
3. By horizontal shearing, we assume that the tangent at (a,0)
(or some supporting line) is not vertical and has slope s at least +1.
(Since horizontal lattice-preserving shearing changes the "inverse
slope" 1/s in increments of 1, the inverse slope can always be brought into
the interval (0,1].)
4. The lattice width in direction (1,0) is b'>=b. Thus
P touches two vertical lines V+: x=b' and V-: x=-b'
5. The lattice width in direction (1,-1) is b">=b. Thus
P touches two diagonal lines D+: y-x=b" and D-: y-x=-b"
(Draw a picture!)
6. If (a,0) had tangent of slope 1, P could not touch D-, since a<b".
Thus the slope s is strictly larger than 1, and P must touch V+
in the upper half-plane, and P must touch D- in the lower half-plane.
7. If the intersection of V+ and D- is below the x-axis,
we swap the roles of V+ and D- by a horizontal shearing transformation
combined with a vertical reflection: Each point (x,y) is mapped to (x-y,-y).
This turns V+ into a line of slope 1 and makes D- vertical.
Point on the x-axis are fixed.
Thus we can assume that the intersection of V+ and D- is above or
on the x-axis, at (b',c) with c>=0.
8. Pick a point where P touches each of the six lines, in a symmetric way.
Denote them by B,BR,R (Bottom, Bottom-Right, and Right) and the reflected
points by T,TL,L. (Draw a picture!)
Replace P by the convex hull of these points (making the area smaller).
9. Holding L,B,R, and T fixed, we can move the points BR and TL on their
respective lines D- and D+, keeping them symmetric.
The area depends linearly on the movement.
If the are would decrease when BR is moved towards R and towards V+,
we can stop this movement at the point (b",0) where D- intersects
the x-axis. The convex hull of (b",0),(-b",0),T,B has area 2b"b>w²/2.
10. Thus we are left with the case that we can decrease the area by
moving BR towards H-, reaching the point B'=(d,-b) with d := b"-1>=0.
Then we consider the convex hull of B', R, and their two
symmetric points. R has coordinates R=(b',e) with e>=c>=0.
The determinant of (d,-b) and (b',e) is bb'+de>=bb'>=b², and we are done.
QED.
### Lemma 4:
>
> A (not necessarily symmetric) convex polygon P of lattice width w
> has area at least w²/3.
> The inequality is strict except when P is a triangle.
>
>
>
Proof:
The polygon P and the symmetrized version Q = 1/2 \* (P-P)
(which is half the "difference body" P-P={ a-b | a,b in P }),
have the same width in every direction, and Q is centrally
symmetric. We can apply Lemma 3 to Q.
The area of Q is at most 3/2 times the area of P, and
equality holds only when P is a triangle.
See any of the following papers. QED
* Hans Rademacher, Über den Vektorenbereich eines konvexen ebenen Bereiches.
*Jahresbericht d. Deutschen Math.-Verein.* **34** (1926): 64-78. <http://eudml.org/doc/145705>
* Theodor Estermann. Zwei neue Beweise eines Satzes von Blaschke und Rademacher.
*Jahresbericht d. Deutschen Math.-Verein.* **36** (1927): 197-200. <http://eudml.org/doc/145763>
* Theodor Estermann. Über den Vektorenbereich eines konvexen Körpers.
*Math Z.* **28** (1928), 471-475. <https://doi.org/10.1007/BF01181177>
* C. A. Rogers and G. C. Shephard, The difference body of a convex body.
*Arch. Math.* **8** (1957), 220-233. <https://doi.org/10.1007/BF01899997>
I believe the true factor for Lemma 4 might be 3/8, and it is sharp for
the triangle (-w/2,-w/2),(w/2,0),(0,w/2), for the case of even w.
(By analogy with the ordinary width, *not* lattice width:
"It is well-known that of all convex sets of a given width, the
equilaterial triangle has the smallest area.")
In the proof, we would consider the 8-gon formed as the
intersection of a horizontal slab of width w, a vertical slab
of width w1>=1, and two slabs of directions 45° and -45° of
*vertical* widths w3>=w and w4>=w, respectively. (Their Euclidean
widths are >=w/sqrt(2).)
Some sides of the 8-gon may degenerate into
a point, in case several lines are concurrent.
The body must touch each of these edges (even if they are degenerated to a point).
# Possible further improvements
### Lemma 5.
A) For three successive vertices v,v',v" of P, the triangle vv'v" contains
no interior point.
B) If n is even, then there cannot even be points on the diagonal vv".
Proof:
A) Otherwise v' could be replaced by that point, reducing the area.
B) Bárány and Tokushige proved that the set E of edge vectors is
convex in the following sense: Every vector e in the convex hull of E
that is a primitive vector, must belong to E.
Let e=v->v' and e'=v'->v". If vv"=e+e' would have gcd d>2 the vector
(e+e')/d, which is in the convex hull of e,e',-e,-e', is missing
from E, a contradiction.
QED
This Lemma could be used to shortcut the propagation process.
Property B is really strong. It seems that it holds also
in the odd case, but I cannot prove it.
Property B means the following. Consider a pair (q,f). Then the
outgoing edges q->p that need to be considered end on the next
lattice line parallel to f. The points q form an arithmetic progression
p0, p0+f, p0+2f, ....
When considering a range of diameter D (roughly the maximum height),
then these are about D/|f| successor points altogether (on all levels py).
Under Property A, we have to consider in addition all multiples of the vectors
(q-f)->(p0+t*f).
I.e.,
p = (q-f) + s*(p0+t*f-(q-f))
= s*p0 - (s-1)*q + (s*t-s-1)*f
This would be D/|f| log(D*|f|) ~ D log D/|f| points.
Typically, the average length of the lists (the number of
vectors f for a point q) is very small,
(about 4 for height py=100), and |f| is usually not very short.
(By contrast, currently, every point p gets O(D²) inputs, one from every other
point q (looking at the propagation from the incoming side).)
Some further possible improvements are mentioned in
the comments in the program.
Now here comes finally the program:
```
N_target = 44
"""
Lemma 1: Every edge is a primitive vector.
Lemma 2: If n is even, then P can be assumed to be centrally symmetric.
Lemma 3: A centrally symmetric convex polygon P of lattice width w has area
at least w²/2.
Lemma 4: A (not necessarily symmetric) convex polygon P of lattice width w
has area at least w²/3.
The inequality is strict except when P is a triangle.
"""
# Since we use "volume", which is TWICE the area, the following constants
# are twice as big as the constants in the lemmas.
lattice_width_factor_even = 1
lattice_width_factor_odd = 2/3 + 0.00001
# +0.00001 is because of the strict inequality (except for triangles, but
# those are found in the first iteration.)
def lower_bound(k,w):
"lower bound on vol (=2*area) for k-gon of lattice width w "
if k%2:
lattice_width_factor = lattice_width_factor_odd
else:
lattice_width_factor = lattice_width_factor_even
LB = ceil( w**2 * lattice_width_factor )
if k%2 != LB%2:
LB +=1 # vol must be odd for odd k and even for even k
return LB
"""
===================================================
Also in the algorithm, we make the assumption
that the lattice width direction is vertical.
(The smallest number of parallel lattice lines intersecting P
are the horizontal lines.)
We assume that the lowest point (or one of the two lowest points)
is the origin O=(0,0).
=====================================================
For each pair of points p and q and every k, we remember the smallest
counterclockwise k-gon (0,0), .... , q, p
Restriction:
* The successive points move strictly upwards.
(Thus, p is the top point, and there is a "long edge" from O to p.)
Polygons with one or two horizontal edges will be treated specially.
By horizontal lattice-preserving shearing transformations, it suffices to
store results only for the range 0 <= px < py
(The answer for any point p in the plane can then be figured out
by an appropriate shearing transformation.)
The area is roughly n^3, and by Lemma 4 the maximum height H=py can be bounded by
H=n^1.5 (omitting all constant factors). Thus the number of points p is n^3.
The points q can be bounded only very loosely in the horizontal
direction, by n^2, however, in practice, it turns out they go only up to
(1+alpha)n, where alpha grows very slowly (less than 4 for height 120.)
Thus, the number of points q that are considered is also roughly of the order n^3.
This gives an estimated runtime of O(n^3*n^3*n)=O(n^7) for all triples (p,q,k).
One could say O(n^6) for each new value of n.
===========================
In the end we put together a counterclockwise k-gon ending in p
with a counterclockwise k'-gon starting in O or in (-1,0) and
ending in p or in p-(1,0).
Main data structure:
====================
min_gon is a dictionary
min_gon[(px,py)] is a dictionary
min_gon[(px,py)][k] is a list of pairs (f,vol)=((fx,fy),vol), where
the incoming edge f=(fx,fy)=q-p is a primitive vector (pointing upwards, fy>0)
and vol = 2 * min-area of a k-gon ((0,0), .... ,q,p).
In the list, the vectors f are sorted clockwise by direction,
and the corresponding values "vol" are strictly increasing.
(If pairs don't fit this order, we can eliminate one of them, as DOMINATED.)
We fill this dictionary row by row, increasing py.
[ If we want to enumerate ALL optimal solutions, we should allow
the "vol" values to be weakly increasing. We should then use the
weaker lower bound also for even k, in case we are interested in solutions
that are not centrally symmetric.
Another possibility is COUNTING the number of solutions. (For each height
separately. Every solution has up to 2k representations with at least
one flat edge, and infinitely many without flat edge.)
We should consider all solutions of height up until the value is confirmed. ]
[ We should have proceeded from left to right, swapping x and y.
Then the notion of slope could have been used more naturally. ]
"vol" is TWICE the area.
https://oeis.org/A070911
1,2,5,6,13,14,21,28,43,48,65,80,103,118, / 151,174,213,242,289,328,387,420,497
The odd values after the slash were unconfirmed according to OEIS.
"""
known_value = {i+3:v for i,v in enumerate((
1,2,5,6,13,14,21,28,43,48,65,80,103,118,151,174,213,242,289,
328,387,420,497,548,625,690,783,860,967,1046,1177,1264,1409,
))} # just for guidance; not used by the algorithm
from math import tan,pi,gcd,sqrt,ceil
import itertools
import sys
if len(sys.argv)>1:
N_target = int(sys.argv[1])
min_gon = dict()
record_vol = [n**3 for n in range(N_target+1)] # loose upper bound as start value
min_height = [0 for n in range(N_target+1)] # smallest height of a min-area polygon
max_height = [0 for n in range(N_target+1)]
# largest height of a min-area polygon with at least one horizontal edge,
# AS FOUND BY THE PROGRAM, not definite
confirmed = [True]*2 + [False]*(N_target+1-2) # checks which entries are confirmed.
how_achieved = [None]*(N_target+1)
# Auxiliary procedures to construct the solution, once the optimal
# area has been determined
def find_polygon(px,py,k,alpha0=0):
# find the smallest k-gon ending in (px,py) by backtracing
# 0<px<py. The two points (0,0),(1,0) are not produced.
alphaT = alpha0
result = [(px+alphaT*py,py)]
(fx,fy),vol = min_gon[px,py][k][0]
for k in range (k-1,1,-1):
qx,qy = px-fx,py-fy
vol -= qx*py-qy*px
alpha = qx//qy
px,py = qx-alpha*qy,qy
alphaT += alpha # alpha is accumulated
result.append((px+alphaT*py,py))
for (fx,fy),vol2 in min_gon[px,py][k]:
if vol2==vol: # this must be the right entry, recognition by vol is easiest
break
else:
error("not found",k,px,py)
return result
def print_solution(k,how_achieved,vol):
how,px,py,k1,k2 = how_achieved
#print(f"{(k,how,px,py,k1,k2)=}")
p1 = find_polygon(px,py,k1)
p1.reverse()
if how=="1 FLAT":
top_point = px-1
else:
top_point = px
ppx = (-top_point)%py
alpha0 = (-top_point - ppx) // py # usually, alpha0==-1
leftshift = 1 if how=="2 FLAT" else 0
p2 = [(-x-leftshift,y) for x,y in find_polygon(ppx,py,k2,alpha0)]
#print(f"-- {how=} {alpha0=}, {p2[0][0]=},{top_point=},{ppx=},{px=},{py=},{k=}")
assert p2[0][0]==top_point-leftshift
if how=="DIAGONAL":
p2 = p2[1:] #eliminate the common point
last = [(-1,0)] if how=="2 FLAT" else []
print ("--- a smallest %d-gon,"%k, "area = %d/2:"%vol,
[(0,0)]+p1+p2+last) # counterclockwise
## Start the computation
for py in itertools.count(1): # for py = 1,2,...
# proceed row by row
for px in range(py): # 2-gons are the base case.
min_gon[px,py]={2:[((px,py),0)]}
# or perhaps rather start 2-gons?
work = num_work = 0
sum_alpha = num_alpha = 0
visited_p = visited_q = 0
for k in range(2,N_target):
collect=[[] for px in range(py)]
# We will first *collect* the contributions to row py
# for k+1 before sorting and processing them.
for qy in range(1,py):
# Generate all contributions from point q on row qy to points p on row py.
# We look at each starting point (qx0,qy) with 0<=qx0<qy<py, for which we
# have min_gon[qx0,qy] stored.
# Then we consider the series of affine images
# (qx0,qy), (qx0+qy,qy), (qx0+2*qy,qy), ..., (qx0+alpha*qy,qy), ...
# until we are sure that there are no more contributions to row py
# to be expected.
#
# These are two crucial pieces of the algorithm:
# 1. The simultaneous clockwise sweep around each point (qx,qy)
# with the incoming directions (fx,fy) and with the outgoing edges
# to the points on row py.
# 2. The logic to determine when no more progress can be expected from
# advancing alpha.
#
Delta_y = py-qy # >0
for qx0 in range(qy):
if k not in min_gon[qx0,qy]:
continue
sides = min_gon[qx0,qy][k]
assert(sides)
for alpha in itertools.count(0): # for alpha = 0,1,2,...
qx = qx0+alpha*qy # apply shearing by alpha
visited_q += 1 # statistics
px = 0
row_py_finished = False # for exit from nested loops
exhausted = True
for (fx0,fy),vol in sides:
# sweep clockwise around q; vol is increasing.
# simultaneously sweep the point p on
# row py from left to right, clockwise around q.
fx = fx0+alpha*fy # apply the reverse shearing by -alpha
while (# vector q->p is counterclockwise from (fx,fy):
# Delta_x/Delta_y < fx/fy
(px-qx) * fy < fx * Delta_y ):
# store this:
Delta_x = px-qx
if gcd(Delta_x,Delta_y)==1:
collect[px].append(
(vol + qx*py-qy*px, Delta_x,Delta_y))
if px>=py-1: # py-1 is largest value of px
row_py_finished = True
break
px += 1
if row_py_finished: break
# Not all points on row py could be reached
# from the first incoming vector in q:
exhausted = False
if exhausted:
# All points up to the maximum px have been reached
# by extending the FIRST incoming edge in "sides".
# Further increase of alpha would only produce a larger
# area of Opq, and could not lead to an improvement.
sum_alpha += alpha # statistics
num_alpha += 1
break
# [ There might be additional possibilities of shortcutting:
# For example, the volume of Opq is too big in
# order to be useful for anything. Indeed the lists in "collect"
# accumulate thousands of elements (from every point q),
# of which only 2-3 remain on average. ]
# Now, consolidate the lists
for px,triples in enumerate(collect):
if not triples:
continue
visited_p += 1
work += len(triples)
num_work += 1 # statistics
# This is one more crucial piece of the program:
# We should keep only those incoming edges that are not DOMINATED.
# If (fx',fy') enters clockwise from (fx,fy) and has larger volume,
# then it cannot be part of a minimum-area solution.
# If it has equal volume, it could be useful, but in any situation it
# could always be replaced by (fx,fy).
#
# We solve this but looking at the entries sorted by slope.
#
result = []
prev_fx, prev_fy = -1,0 # ensure that test is true at the first iteration
prev_vol = -1
for vol,fx,fy in (sorted(triples)):
# smallest area first <==> result should be ordered clockwise.
if (# this is the first time OR (fx,fy) is clockwise from prev:
# fx/fy > prev_fx/prev_fy
fx*prev_fy > prev_fx*fy):
if vol!=prev_vol:
result.append(((fx,fy),vol))
else: # replace the last entry:
result[-1] = ((fx,fy),vol)
# adjust this treatment when generating ALL solutions:
# Then multiple vol-entries should be kept, but SORTED BY SLOPE.
prev_fx,prev_fy,prev_vol = fx,fy,vol
min_gon[px,py][k+1]=result
if 0:
#print(f"p=({px},{py}) {k=}")
for t in result: print(" ",t)
# compute new record areas
improved = [False]*(N_target+1)
def check_record(k, vol, how, text=""):
if k>N_target:
return
if vol<record_vol[k]:
#if text: print(text)
assert not confirmed[k]
if k in known_value and vol<known_value[k]:
# then something must be wrong:
print("BETTER THAN KNOWN VALUE",100*"!!")
print_solution(k,how,vol)
exit()
record_vol[k] = vol
how_achieved[k] = how
min_height[k] = py
improved[k] = True
if vol==record_vol[k] and how[0] != "DIAGONAL":
# DIAGONAL case not counted: Without a flat edge, height is unbounded.
max_height[k] = py
# Combine "right" k1-gons with "left" k2-gons
for px in range(py):
ppx0 = (-px)%py # A) exact match along long edge (0,0)-(px,py)
ppx1 = (1-px)%py # B) horizontal edge of length 1 at the top
for k1,best1 in min_gon[px,py].items():
_,vol1 = best1[0]
for k2,best2 in min_gon[ppx0,py].items():
_,vol2 = best2[0]
check_record(k1+k2-2,
vol1+vol2, ("DIAGONAL",px,py,k1,k2))
check_record(k1+k2,
vol1+vol2+2*py, ("2 FLAT",px,py,k1,k2))
#f"DIAG k={k1+k2-3} {k1=} {k2=} {vol1=} {vol2=} p=({px},{py})")
for k2,best2 in min_gon[ppx1,py].items():
_,vol2 = best2[0]
check_record(k1+k2-1, vol1+vol2+py, ("1 FLAT",px,py,k1,k2))
#f"EDGE k={k1+k2-2} {k1=} {k2=} {vol1=} {vol2=} p=({px},{py})")
target_height = 0 # how high we still have to go
for k in range(2,N_target+1):
if not confirmed[k]:
if lower_bound(k,py+1)>=record_vol[k]:
# evaluated for increased py in the next iteration
#print("LB",k,py+1,LB)
confirmed[k] = True
print_solution(k,how_achieved[k],record_vol[k])
else:
# find necessary target height to confirm the current record:
t_k = py+2
while lower_bound(k,t_k)<record_vol[k]: t_k += 1
target_height = max(target_height,t_k-1)
print("N=%d, height %d"%(N_target,py) +
(".\nRESULT:" if target_height==0 else "->%d:"%target_height),
",".join(("*" if improved[k] else "")+
str(record_vol[k])+
("-" if k in known_value and record_vol[k]>known_value[k]
else "" if confirmed[k] else "?")
for k in range(3,N_target+1)),
#
# Meaning of the signs:
# - if there is a smaller known value
# ? if still unconfirmed
# * if has just been improved
#
"work=%d"%work, # work done in this step, total items in "collect"
"" if num_work==0 else "avg=%.2f"%(work/num_work), # average list size in "collect"
"" if num_alpha==0 else ("av_alpha=%.2f"% (sum_alpha/num_alpha)),
flush=True)
if py%10==0:
print("smallest heights:",*("%2d"%x for x in min_height[3:]))
print("largest heights: ",*("%2d"%x for x in max_height[3:]))
print("2n-gons:", ",".join(str(record_vol[k]//2)
+("" if confirmed[k] else "?")
for k in range(4,N_target+1,2)))
if all(confirmed):
break
print("smallest heights:",*("%2d"%x for x in min_height[3:]))
print("largest heights: ",*("%2d"%x for x in max_height[3:]))
# "largest heights" are preliminary, since the algorithm stops
# too early to find the largest heights.
# There is quite a large variation of heights, in line with the
# result of Bárány and Tukushige that, in the limit,
# the shapes resemble ellipses that are more and more oblong.
print("2n-gons:", ",".join(str(record_vol[k]//2)
for k in range(4,N_target+1,2)))
```
[Answer]
# Rust + itertools + fasthash, n = 26 in ~423s
This is a rust port of [Arnauld's answer](https://codegolf.stackexchange.com/a/253655), with a few iterations of performance improvement.
I use `Vec<Option<_>>` for sparse arrays and reference counting for the cache. I also use `128 * w + h` as a hash for coordinate pairs, and use SeaHash from the [fasthash crate](https://crates.io/crates/fasthash)
Obviously needs to be build with `--release`.
It is around 40 times faster for n=16, taking only 2.5s instead of 100s in Javascript.
```
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::iter::once;
use std::rc::Rc;
use std::time::{Duration, Instant};
use fasthash::sea::Hash64;
use itertools::Itertools;
struct Solution {
w: i32,
h: i32,
y0: i32,
res: [Vec<(i32, i32)>; 4],
}
#[derive(Clone, Debug)]
struct AreaPath {
area: i32,
path: Vec<(i32, i32)>,
}
#[derive(Eq, PartialEq)]
struct Coord(i32, i32);
#[allow(clippy::derive_hash_xor_eq)]
impl Hash for Coord {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_i32(128 * self.0 + self.1);
}
}
type PathCache = HashMap<Coord, Rc<Vec<Option<AreaPath>>>, Hash64>;
fn main() {
const MAX_N: i32 = 99;
const MAX_TIME: Duration = Duration::from_secs(600);
let mut pathCache: PathCache = HashMap::with_hasher(Hash64);
let mut getPaths = |w: i32, h: i32| -> Rc<Vec<Option<AreaPath>>> {
let cached: Option<&Rc<Vec<Option<AreaPath>>>> = pathCache.get(&Coord(w, h));
return match cached {
Some(p) => Rc::clone(p),
None => {
let mut set: HashSet<usize> = HashSet::new();
let mut list = vec![None; 11];
fn search(
x: i32,
y: i32,
pw: i32,
ph: i32,
area: i32,
path: Vec<(i32, i32)>,
w: i32,
h: i32,
set: &mut HashSet<usize>,
list: &mut Vec<Option<AreaPath>>,
) {
let len: usize = path.len();
if x == w && y == h {
let outerArea = w * h * 2 - area;
if !set.contains(&len) || outerArea > list[len].as_ref().unwrap().area {
set.insert(len);
list[len] = Some(AreaPath {
area: outerArea,
path: path.clone(),
});
}
}
for w0 in 1..=(w - x) {
for h0 in 1..=(h - y) {
if h0 * pw < w0 * ph {
let mut path_clone = Vec::with_capacity(len + 1);
path_clone.extend(path.clone());
path_clone.push((w0, h0));
search(
x + w0,
y + h0,
w0,
h0,
area + ((w - x) * 2 - w0) * h0,
path_clone,
w,
h,
set,
list,
);
}
}
}
}
search(0, 0, 0, 1, 0, vec![], w, h, &mut set, &mut list);
let list = Rc::new(list);
pathCache.insert(Coord(w, h), Rc::clone(&list));
pathCache.insert(
Coord(h, w),
Rc::new(
list.iter()
.map(|o| {
o.as_ref().map(|a| AreaPath {
area: a.area,
path: a.path.iter().rev().map(|&(dx, dy)| (dy, dx)).collect(),
})
})
.collect(),
),
);
list
}
};
};
let mut solveRectangle = |part: &[[i32; 4]],
w: i32,
h: i32,
y0: i32,
x0: i32,
y1: i32,
x1: i32|
-> (f32, Option<[Vec<(i32, i32)>; 4]>) {
let mut best = f32::INFINITY;
let mut solution = None;
for p in part {
if let Some(Some(p0)) = getPaths(x0, h - y0 - 2).get((p[0] - 1) as usize) {
if let Some(Some(p1)) = getPaths(w - x0 - 2, h - y1 - 1)
.get((p[1] - 1) as usize)
{
if let Some(Some(p2)) = getPaths(w - x1 - 1, y1 - 1)
.get((p[2] - 1) as usize)
{
if let Some(Some(p3)) =
getPaths(x1 - 1, y0).get((p[3] - 1) as usize)
{
let outerArea = p0.area + p1.area + p2.area + p3.area;
let score = (w - 1) * (h - 1) * 2 - outerArea;
let score = score as f32;
if score < best {
best = score;
solution = Some([
p0.path.clone(),
p1.path.iter().rev().copied().collect(),
p2.path.clone(),
p3.path.iter().rev().copied().collect(),
]);
}
}
}
}
}
}
return (best, solution);
};
let mut solve = |n: i32, min: i32, max: i32| -> (f32, Solution) {
let part: Vec<[i32; 4]> = partitionsInFour(n);
let mut rect = vec![];
let mut best = f32::INFINITY;
let mut solution = None;
for w in min..=max {
for h in min..=w {
rect.push((w, h));
}
}
for (w, h) in rect {
for y0 in 0..(h - 1) {
for x0 in 0..(w - 1) {
for y1 in 1..h {
for x1 in 1..w {
let (score, res) = solveRectangle(&part, w, h, y0, x0, y1, x1);
if score < best {
best = score;
solution = Some(Solution {
w: w,
h: h,
y0: y0,
res: res.unwrap(),
});
}
}
}
}
}
}
return (best, solution.unwrap());
};
let ts = Instant::now();
let mut min = 4;
let mut max = 4;
for n in 7..=MAX_N {
println!("n = {n}");
let (score, solution) = solve(n, min, max);
let w = solution.w - 1;
let h = solution.h - 1;
println!("Area * 2 = {score}");
println!("Enclosing rectangle: {w} x {h}");
displaySolution(&solution);
let time = ts.elapsed();
println!("Total time: {time:?}");
if time >= MAX_TIME {
break;
}
min = solution.h;
max = solution.w + 2;
}
fn partitionsInFour(n: i32) -> Vec<[i32; 4]> {
let mut list = vec![];
fn search(n: i32, i: i32, l: Vec<i32>, list: &mut Vec<[i32; 4]>) {
if n != 0 {
if i <= n && l.len() != 4 {
search(n - i, 1, once(i).chain(l.iter().copied()).collect(), list);
search(n, i + 1, l, list);
}
} else if let Ok(a) = l.try_into() {
list.push(a);
}
}
search(n, 1, vec![], &mut list);
return list;
}
fn displaySolution(solution: &Solution) {
let mut m = vec![vec!["--".to_owned(); solution.w as usize]; solution.h as usize];
let mut x = 0;
let mut y;
let mut i = 1;
let mut mark = |x: i32, y: i32| {
let x = x as usize;
let y = y as usize;
if m[y][x] == "--" {
m[y][x] = format!("{:>02}", i);
}
i += 1;
};
y = solution.y0;
mark(0, y);
y += 1;
mark(x, y);
for (dx, dy) in &solution.res[0] {
x += dx;
y += dy;
mark(x, y)
}
x += 1;
mark(x, y);
for (dx, dy) in &solution.res[1] {
x += dx;
y -= dy;
mark(x, y)
}
y -= 1;
mark(x, y);
for (dx, dy) in &solution.res[2] {
x -= dx;
y -= dy;
mark(x, y)
}
x -= 1;
mark(x, y);
for (dx, dy) in &solution.res[3] {
x -= dx;
y += dy;
mark(x, y)
}
println!("{}", m.into_iter().map(|r| r.join(" ")).join("\n"));
}
}
```
[Answer]
# Python (with restricted conditions) n=26, 10 seconds
Uses backtracking.
Numba for speed.
notebook [link](https://github.com/arrmansa/smallest-area-of-a-convex-grid-polygon/blob/main/Attempt%2019%20-%20one%20half%20is%20bigger.ipynb)
```
10.49 seconds, 548 area
points: [[0, 0], [0, 1], [1, 3], [2, 4], [4, 5], [7, 6], [8, 6], [11, 5], [13, 4], [16, 2], [17, 1], [19, -2], [20, -4], [21, -7], [21, -8], [20, -10], [19, -11], [17, -12], [14, -13], [13, -13], [10, -12], [8, -11], [5, -9], [4, -8], [2, -5], [1, -3]]
```
# Fast O(n^2) upper bounds for high n (<10% error for n<=36, slightly better than n^3/27 when n<1e5, sometimes better for n>1e5)
Assuming the solution to be close to circular. We can make circle-like shapes where sides made of the smallest n vectors where i and j are coprime. This gives a polygon of size n\*4. I think this should have the optimal minimum perimeter as well. [github notebook link](https://github.com/arrmansa/smallest-area-of-a-convex-grid-polygon/blob/main/choose%20small%20vectors.ipynb)
The calculated upper bound is (slightly) better than n^3/27 for n upto 10000.
[](https://i.stack.imgur.com/crL8G.png)
[](https://i.stack.imgur.com/v95UI.png)
(Old extra method - best solution found in 15s for n upto 44 [link](https://github.com/arrmansa/smallest-area-of-a-convex-grid-polygon/blob/main/Attempt%2020%20-%20half_bigger-round-opt.ipynb) . At these high numbers, it's basically just oneshot generations but still somewhat interesting)
## Old code links n = 14, 80s
---
```
88.12 seconds, 80 area, points: [[0, 0], [0, 1], [1, 2], [3, 3], [4, 3], [6, 2], [7, 1], [8, -1], [8, -2], [7, -3], [5, -4], [4, -4], [2, -3], [1, -2]]
```
notebook [link](https://github.com/arrmansa/smallest-area-of-a-convex-grid-polygon/blob/main/Attempt%203.ipynb)
---
another way to get it to generate 1 valid, pretty optimal output very early is to sort the points in order of distance to previous point, but it doesn't help in overall speed. [link](https://github.com/arrmansa/smallest-area-of-a-convex-grid-polygon/blob/main/Attempt%202.ipynb)
---
if we assume point n+1 must be in a 7x7 grid centered at point n, the max manhattan distance between points is <6 and that the angle between formed by n-1, n and n+1 is >= 90, we get the output for n=18, gridsize=14 in 360 seconds
```
362.6 seconds, 174 area, points: [[0, 0], [0, 1], [1, 3], [2, 4], [4, 5], [5, 5], [7, 4], [8, 3], [9, 1], [10, -2], [10, -3], [9, -5], [8, -6], [6, -7], [5, -7], [3, -6], [2, -5], [1, -3]]
```
notebook [link](https://github.com/arrmansa/smallest-area-of-a-convex-grid-polygon/blob/main/Attempt%204.ipynb)
---
reducing the number of wasted calculations and function calls since cross product is the area of a triangle and taking into account that p0 = 0,0 we get:
```
from numba import jit
import numpy as np
@jit
def create_polygon_jit(points, n, target_n, gridsize, curr_area, min_area, soln):
if n >= 3:
if points[1,0]==0 and points[n-1,0]==0:
return False
if (points[n-3][0]-points[n-2][0])*(points[n-1][1]-points[n-2][1])<=\
(points[n-3][1]-points[n-2][1])*(points[n-1][0]-points[n-2][0]):
return False
add_area = points[n-1][0]*points[n-2][1]-points[n-1][1]*points[n-2][0]
if add_area <= 0:
return False
curr_area += add_area
if curr_area >= min_area[0]:
return False
if n == target_n:
min_area[0] = curr_area
soln[:] = points.copy()
return False
for i in range(gridsize):
for j in range(-gridsize//2, gridsize//2):
points[n] = (i,j)
result = create_polygon_jit(points, n+1, target_n, gridsize, curr_area, min_area, soln)
points[n] = (0,0)
return False
```
which only does 4 seconds better at 84.4 sec
notebook [link](https://github.com/arrmansa/smallest-area-of-a-convex-grid-polygon/blob/main/Attempt%205.ipynb)
---
pypy 3 tio [link](https://tio.run/##lVRNc5wwDL3zKzQ5GWISYC@dTOixf2LLMAS8G@@A7bFhpvTPb2WD@dhtk5STZUnvSXoyauzfpTjEalTj9Ro07AS1ZlXPSiXb8SxFeeE9UZKL3lAQFPpKn1lf4umseWP4b0ahHrQuK0yj0HExn4xsRfgSAH78BAK@53CYzPlqAj2mxTEp8jyBSjT@TsT@ds2wn2b9oAX8qFrDtlBkyTvYvHgxM2uGEdnipnt/WoSv@c8FbQd1H7qHuqf6Qr1V07gRQX7TbrTnivdFR3umbfsL4msOX5nYohc85kvyFnANQNW8pEj6CbbTOc@XHVnDNxjY9gK/@O2yTL6py6daqpGEwT@pTlIDBy5AV@LMiN/FzfxtxGWNiH3I83O27i4aN5L5KdtaCKeX8KZlM7S9beGDR/KY/u8zCe6YE5pMt7vOA94pqXvoeYfG9FilMUrLZqixgtQiNxSU7@pXR2HswIrY4HydG3dpi0wwzY4@xmC73hn60Ri7MLYebziPDwsddyOHt5a5PubmZ9YZuXozxAwd2dc4dWlrmY8c93s1ivBWW5SrZcIz4BfgkkGaBdMNno9uXEUkAj9svPwWTGK5gCKwc7YnfDkGxbEa2ik@KaZPZS0H0TONC1d@rG3q/oGrpAmFo7eiKCu8nua9UrYIawVKYzLRyNGQv3DGrh4KWUjhwbBaisbQB7obr0NF97QzUzUvGON4wuv1Dw)
---
restricted conditions with quadrant/octant optimization suggested by @HugoPfoertner, n=19 works, and n=18 is done in 180 seconds
```
438.59 seconds, 213 area, points: [[0, 0], [0, 1], [1, 3], [2, 4], [4, 5], [5, 5], [8, 4], [10, 3], [11, 2], [12, 0], [13, -3], [13, -4], [12, -6], [11, -7], [10, -7], [7, -6], [5, -5], [2, -3], [1, -2]]
```
notebook [link](https://github.com/arrmansa/smallest-area-of-a-convex-grid-polygon/blob/main/Attempt%206.ipynb)
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), n=16 ~2 seconds
C++ port of @arrmansa's optimized version.
```
#include <array>
#include <chrono>
#include <iostream>
struct point {
int x;
int y;
};
template<std::size_t N>
bool create_polygon_jit(std::array<point, N>& points, int n, int target_n, int gridsize, int curr_area, int& min_area, std::array<point, N>& soln)
{
if (n >= 3)
{
int x1 = points[n - 3].x - points[n - 2].x, y1 = points[n - 3].y - points[n - 2].y;
int x2 = points[n - 1].x - points[n - 2].x, y2 = points[n - 1].y - points[n - 2].y;
if (x1 * y2 - x2 * y1 <= 0) // Angle > 180
return false;
if (x1 * x2 + y1 * y2 > 0) // Angle >= 90
return false;
if (points[1].x == 0 and points[n - 1].x == 0)
return true;
int add_area = points[n - 1].x * points[n - 2].y - points[n - 1].y * points[n - 2].x;
if (add_area <= 0)
return true;
curr_area += add_area;
if (curr_area >= min_area)
return true;
if (n == target_n)
{
min_area = curr_area;
soln = points;
return true;
}
int min_i = std::max(0, points[n - 1].x - 3);
int max_i = std::min(gridsize, points[n - 1].x + 4);
int min_j = std::max(-gridsize / 2, points[n - 1].y - 3);
int max_j = std::min(gridsize / 2 + 1, points[n - 1].y + 4);
if (x2 > 0)
{
if (y2 > 0)
{
if (x2 > y2)
{
for (int j = min_j; j < max_j; j++) {
for (int i = max_i - 1; i > min_i - 1; i--) {
points[n].x = i;
points[n].y = j;
if (!create_polygon_jit(points, n + 1, target_n, gridsize, curr_area, min_area, soln))
break;
}
if (points[n].x == max_i - 1)
break;
}
}
else
{
for (int j = max_j - 1; j > min_j - 1; j--)
{
for (int i = max_i - 1; i > min_i - 1; i--)
{
points[n].x = i;
points[n].y = j;
if (!create_polygon_jit(points, n + 1, target_n, gridsize, curr_area, min_area, soln))
break;
}
if (points[n].x == max_i - 1)
break;
}
}
}
else
{
if (x2 > -y2)
{
for (int i = max_i - 1; i > min_i - 1; i--)
{
for (int j = min_j; j < max_j; j++)
{
points[n].x = i;
points[n].y = j;
if (!create_polygon_jit(points, n + 1, target_n, gridsize, curr_area, min_area, soln))
break;
}
if (points[n].y == min_j)
break;
}
}
else
{
for (int i = min_i; i < max_i; i++)
{
for (int j = min_j; j < max_j; j++)
{
points[n].x = i;
points[n].y = j;
;
if (!create_polygon_jit(points, n + 1, target_n, gridsize, curr_area, min_area, soln))
break;
}
if (points[n].y == min_j)
break;
}
}
}
}
else
{
if (y2 > 0)
{
if (-x2 > y2)
{
for (int i = min_i; i < max_i; i++)
{
for (int j = max_j - 1; j > min_j - 1; j--)
{
points[n].x = i;
points[n].y = j;
if (!create_polygon_jit(points, n + 1, target_n, gridsize, curr_area, min_area, soln))
break;
}
if (points[n].y == max_j - 1)
break;
}
}
else
{
for (int i = max_i - 1; i > min_i - 1; i--)
{
for (int j = max_j - 1; j > min_j - 1; j--)
{
points[n].x = i;
points[n].y = j;
if (!create_polygon_jit(points, n + 1, target_n, gridsize, curr_area, min_area, soln))
break;
}
if (points[n].y == max_j - 1)
break;
}
}
}
else
{
if (-x2 > -y2)
{
for (int j = max_j - 1; j > min_j - 1; j--)
{
for (int i = min_i; i < max_i; i++)
{
points[n].x = i;
points[n].y = j;
if (!create_polygon_jit(points, n + 1, target_n, gridsize, curr_area, min_area, soln))
break;
}
if (points[n].x == min_i)
break;
}
}
else
{
for (int j = min_j; j < max_j; j++)
{
for (int i = min_i; i < max_i; i++)
{
points[n].x = i;
points[n].y = j;
if (!create_polygon_jit(points, n + 1, target_n, gridsize, curr_area, min_area, soln))
break;
}
if (points[n].x == min_i)
break;
}
}
}
}
}
else
{
int min_i = std::max(0, points[n - 1].x - 3);
int max_i = std::min(gridsize, points[n - 1].x + 4);
int min_j = std::max(-gridsize / 2, points[n - 1].y - 3);
int max_j = std::min(gridsize / 2, points[n - 1].y + 4);
for (int i = min_i; i < max_i; i++)
{
for (int j = min_j; j < max_j; j++)
{
points[n].x = i;
points[n].y = j;
create_polygon_jit(points, n + 1, target_n, gridsize, curr_area, min_area, soln);
}
}
}
points[n].x = 0;
points[n].y = 0;
return true;
}
int main() {
using namespace std::chrono;
auto t1 = steady_clock::now();
const int n = 16;
std::array<point, n> points = { 0 };
int gridSize = 11;
int minArea = gridSize * gridSize;
std::array<point, n> result;
create_polygon_jit(points, 1, n, gridSize, 0, minArea, result);
std::cout << "Result: ";
for (point& p : result)
std::cout << "(" << p.x << ", " << p.y << ") ";
std::cout << "\nArea: " << minArea << "\n";
auto t2 = steady_clock::now();
auto time_span = duration_cast<duration<double>>(t2 - t1);
std::cout << "Time:" << time_span.count() << " seconds.\n";
}
```
[Try it online!](https://tio.run/##7Vnbbts4EH3XV8xmgcCKrcR2iqJryQL6A11gs29tYTAS48qRKUOi0GiD/Hq9Q1I3Wpc4TgKkgfVgc6iZM8OZQ4oSvc3GWnredvtnwLww9Sk4JI5J5hpVh/cjjlhU7wmihMeUrF3DwEbqcdhEAeNwbwBeonVnl83MNh5sw@B0vQkJp07C/dksCf6jCw5fXOM6ikLwEI3TxSYKs2XEFquAD6SajMWR4CNUPlV@kpEEZuqPk3hJ@SKXlnHgC3AleWkcLwiCS/EU1gHLxXb4JAqZaeTDuIEBA3cOl6aUVW85wAnM82i@MrDg8vv5Hf7VeqbYM4KsqZc19DJbx57qNpMu7KZePzaOCOM@E4aW8HImwnPmMDbh4gI@s2VIwYXJp3FpIq6Y8jRmcEPChLaAIc5Q4EhYV2DVwObw175gedhysHOMCQjzG1kQN8w2QKQh4mlpJL4vi92SzLPdJOlpk4nc1bnTwy3RnT1DKrkIw3kZm45ZqWDiCq7uNVzJVUxOMRkqo3vNvADFnJTObE1DTIEyY3a376LzQU@6cBCgvZxfa3I3GI9aqHxp6oxHxZpVwAbVNN41HsIH0276XNV9WoU5XMB01DJF2vyv2vwLAHQ5aYLsxiGmg@J/R@qFRraj0dTSsLKp2bjZVBfXTRTDQIxEjELmw8amowaGzeHQ7LDUrEUNVC1wlDaKbl5QJVpWH4q4iizJuQqBvadyhsqrfmWRlD9anhPFE4GpMlVPg4pCtadA7QEglnqz16W4rlH5tjuyB6MvXi0btcz2u@1x2XTX7KG4sh7EGjkHZKFXed0LEeveav8ijOrEeE2mHan2XKrpUoN0PauadcCydiCN9iBo94J5JObLEjOTxBSpfnPrX5CTIBDUUiQQzS4S/H606lO2j5x7mYWwamkcfM420Dp0H/hKjH76HuG4YD6TvEXK3@ai@XrP5CPV3h/VDto0WgfvGl/5tWb/5fXIzGe@zohUv8235v33eEdavX9a9e4M1W/JtPv3/uH00Y@mT@G9zvOnzsHmLHl0Zjz6DvXS3Lf3II8e9dg2mpHmndrHeiSmqhZWqPiEmyYBWwIja5psiEdVCdVZn0IgKY@AT2R1KfGzhRdG3u1sxqKfg6KKXsQSrk7jUG/yUVk2D9eYm0eJWvcwhofcvjiyuxKUQYBJdW6I2fmsTipKhbOymZu3OoppkoYcNYxHqoQVyktzJUszHhVORzmIWffjRSkHx4GTf@S9GZyoYCUXJeYpbGBWmJb1040HJ@Jvg/UT0ghyMZOiWWDqNt9kUDOlW@RF3TjJI1TFmnYVq1IJ1nSBBRfl8tOY8ACT4pGEO4Xk@FF6HVLXHXBxTMgnZltI/yLOTMZTIp7jTcaRX@I@JBS54SfnMkTk33b7y7sJyTLZWn9f/g8 "C++ (gcc) – Try It Online")
[Answer]
# Rust, *n*=44 in ~7 seconds
This is merely an abridged port of [Günter Rote's solution](https://codegolf.stackexchange.com/a/265224), no original contribution.
```
const LWF_EVEN: f64 = 1.0;
const LWF_ODD: f64 = 2.0/3.0 + 0.00001;
fn lower_bound(k: usize, w: usize) -> usize {
let lattice_width_factor = if k%2 == 1 {
LWF_ODD
} else {
LWF_EVEN
};
let mut lb = ( (w*w) as f64 * lattice_width_factor ) as usize;
if k%2 != lb%2 {
lb += 1;
};
lb
}
fn gcd(mut x: isize, mut y: isize) -> isize {
while y != 0 {
let t = y;
y = x % y;
x = t;
}
x
}
fn check_record(k: usize, vol: usize, py: usize, n_target: usize,
record_vol: &mut [usize], min_height: &mut [usize], max_height: &mut [usize], improved: &mut [bool], diagonal: bool) {
if k > n_target {
return
}
if vol < record_vol[k] {
record_vol[k] = vol;
min_height[k] = py;
improved[k] = true;
}
if vol==record_vol[k] && !diagonal {
max_height[k] = py;
}
}
use std::collections::HashMap;
fn main() {
#[allow(non_snake_case)]
let mut N_target = 44;
if let Some(s) = std::env::args().skip(1).next() {
if let Ok(x) = s.parse() {
N_target = x;
}
};
let mut min_gon = HashMap::new();
let mut record_vol = Vec::new();
for n in 0..=N_target {
record_vol.push(n*n*n);
};
let mut min_height = vec![0; N_target+1];
let mut max_height = vec![0; N_target+1];
let mut confirmed = vec![false; N_target+1];
confirmed[0] = true; confirmed[1] = true;
for py in 1usize.. {
for px in 0usize..py {
min_gon.insert((px, py), HashMap::from([(2, vec![((px as isize, py as isize), 0)])]));
};
let mut _work = 0;
let mut _num_work = 0;
let mut _sum_alpha = 0;
let mut _num_alpha = 0;
let mut _visited_p = 0;
let mut _visited_q = 0;
for k in 2usize..N_target {
let mut collect = Vec::new();
for _px in 0..py {
collect.push(Vec::new());
};
for qy in 1..py {
let delta_y = (py-qy) as isize;
for qx0 in 0..qy {
let sides = match min_gon[&(qx0,qy)].get(&k) {
Some(x) => x,
None => continue
};
for alpha in 0.. {
let qx = qx0+alpha*qy;
_visited_q += 1;
let mut px = 0usize;
let mut exhausted = true;
'a: for ((fx0,fy),vol) in sides {
let fx = fx0+alpha as isize*fy;
while (px as isize - qx as isize) * fy < fx * delta_y {
let delta_x = px as isize - qx as isize;
if gcd(delta_x.abs(), delta_y) == 1 {
collect[px].push(
(vol + qx*py-qy*px, delta_x, delta_y));
};
if px>=py-1 {
break 'a
}
px += 1;
}
exhausted = false;
}
if exhausted {
_sum_alpha += alpha;
_num_alpha += 1;
break
}
}
}
}
for (px, mut triples) in collect.into_iter().enumerate() {
if triples.is_empty() {
continue
};
_visited_p += 1;
_work += triples.len();
_num_work += 1;
let mut result = Vec::new();
let mut first_time = true;
let (mut prev_fx, mut prev_fy) = (0, 0);
let mut prev_vol = 0;
triples.sort();
for (vol,fx,fy) in triples.into_iter() {
if first_time || fx*prev_fy > prev_fx*fy {
if first_time || vol != prev_vol {
result.push(((fx,fy),vol));
first_time = false;
} else {
let i = result.len()-1;
result[i] = ((fx,fy),vol);
};
prev_fx = fx; prev_fy = fy; prev_vol = vol;
}
};
min_gon.get_mut(&(px,py)).expect("min_gon[px,py] has to be initialized").insert(k+1, result);
}
}
let mut improved = vec![false; N_target+1];
for px in 0..py {
let ppx0 = (py - px) % py;
let ppx1 = (py + 1 - px) % py;
for (k1,best1) in min_gon[&(px,py)].iter() {
let vol1 = best1[0].1;
for (k2,best2) in min_gon[&(ppx0,py)].iter() {
let vol2 = best2[0].1;
check_record(k1+k2-2, vol1+vol2, py, N_target, &mut record_vol, &mut min_height, &mut max_height, &mut improved, true);
check_record(k1+k2, vol1+vol2+2*py, py, N_target, &mut record_vol, &mut min_height, &mut max_height, &mut improved, false);
}
for (k2,best2) in min_gon[&(ppx1,py)].iter() {
let vol2 = best2[0].1;
check_record(k1+k2-1, vol1+vol2+py, py, N_target, &mut record_vol, &mut min_height, &mut max_height, &mut improved, false);
}
}
}
let mut target_height = 0;
for k in 2..=N_target {
if !confirmed[k] {
if lower_bound(k,py+1) >= record_vol[k] {
confirmed[k] = true;
} else {
let mut t_k = py+2;
while lower_bound(k,t_k) < record_vol[k] { t_k += 1 };
target_height = std::cmp::max(target_height, t_k-1);
}
}
}
if confirmed.iter().all(|x| *x) {
break
}
};
println!("{:?}", &record_vol[3..]);
}
```
]
|
[Question]
[
This is code golf. For this challenge, I will accept a method (you don't need a full program), but the method signature does count towards the byte count and I want to see the full signature (not a lamdba). The input for the method is an integer array with 81 elements. The output/return value from the method is a string that represents the array as an ascii sudoku board.
If you're using an esoteric language or something that absolutely doesn't have methods, you can adapt, but if the language supports this at all I want to see something might actually be plugged into a "real" ungolfed program, even if the method body itself is a pain to work with. The requirement is not meant to block languages like Jelly or 05AB1E, but to make it easier for languages like Java to build something that makes sense for that platform.
For the input, integer values 1-9 should have obvious meanings. A 0 should always be interpreted as a blank cell. You may also interpret anything else outside the 1-9 range as a blank cell, but this is not required. Positioning from the array to the puzzle starts at the top left and fills each row from left to right before moving to the next row.
For the boxes, I want double lines around the outside and between each 3x3 region, and single lines between other cells. These should be drawn with line drawing characters (if your I/O format represents strings as a sequence of bytes rather than a sequence of characters, you should represent them in a well-known encoding such as UTF-8 or codepage 347).
For this challenge, I am **NOT** asking you to generate the sudoku puzzle. That is the input for the function. I am **NOT** asking you to solve the puzzle. I'm just asking you to produce a string to "draw" what you're given (in as few bytes as possible).
### Example Input:
Values for the array:
```
{ 8, 5, 0, 0, 0, 2, 4, 0, 0, 7, 2, 0, 0, 0, 0, 0, 0, 9, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 7, 0, 0, 2, 3, 0, 5, 0, 0, 0, 9, 0, 0 ,0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 7, 0, 0, 1, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 6, 0, 4, 0}
```
The values can use whatever mechanism is natural for your language: int[], ArrayList, sequence, tuple, string of digits, whatever, as long as you have a value in the input for every cell (no maps for only populated cells to positions). Remember that the input is supplied... it is not part of your byte count. But the input might represent *any* sudoku puzzle, and the puzzle *might not even have a valid solution*. You do get to assume that puzzle *is* printable. You won't get something with 82 elements, for example.
You also get to assume a reasonable fixed-width font.
### Corresponding Output:
```
╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗
║ 8 │ 5 │ ║ │ │ 2 ║ 4 │ │ ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ 7 │ 2 │ ║ │ │ ║ │ │ 9 ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ │ │ 4 ║ │ │ ║ │ │ ║
╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣
║ │ │ ║ 1 │ │ 7 ║ │ │ 2 ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ 3 │ │ 5 ║ │ │ ║ 9 │ │ ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ │ 4 │ ║ │ │ ║ │ │ ║
╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣
║ │ │ ║ │ 8 │ ║ │ 7 │ ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ │ 1 │ 7 ║ │ │ ║ │ │ ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ │ │ ║ │ 3 │ 6 ║ │ 4 │ ║
╚═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╝
```
[Answer]
# [Python 3](https://docs.python.org/3/), 232 bytes
Thanks to those who helped to golf this down.
Encryption within encryption...
```
q=lambda x,y:x+y+x+y+x
r=lambda a,b,c,d,e:a+q(q(b*3,c),d)+e+"\n"
print(((r(*"╔═╤╦╗")+q(q("║ %d │ %d │ %d "*3+"║\n",r(*"╟─┼╫╢")),r(*"╠═╪╬╣"))+r(*"╚═╧╩╝"))%eval(input())).replace(*"0 "))
```
[Try it online!](https://tio.run/##hY5fSsQwEMbf9xQhsJA0g1S7664L3sSXtA240K1tqbJ9E0@g0EEQRFFR/HMETzMXqTE1ZWGFhS/ky28y30zR1KdnedR15XGmV3Gq2RqaxVo1yp1R5bGGGBJIwSy0KkUp4iCCREIqlVH8JOejolrmtRCiEgEnbAmvCV8IXwlvuXQtFt@wccqovdq4eBCp34rNgL73gdpLar8JPwmfuJR/@NFFfhB@ET5brHp85/Ab4TvhvcVjc6EzscyL81pIKfcqU2Q6MfZvyGy568Qc2BRY6HUAbOL9zD3DLR15M/mvOmjfhwzJkTPT7SgGO9N6zTd2G6bMdnXZuYfDwvIH "Python 3 – Try It Online")
To be golfed.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~398~~ ~~395~~ 291 bytes
Saved 3 bytes by working through the string reversed, and 104 (!) bytes thanks to Leaky Nun.
```
#include<locale.h>
#define q(x,y) x y x y x
#define D L"╝"q(q("═══","╧"),"╩")"╚"q(q("\n║"q(q(" & ","│"),"║")"║","\n╢"q(q("───","┼"),"╫")"╟"),"\n╣"q(q("═══","╪"),"╬")"╠")"\n╗"q(q("═══","╤"),"╦")"╔"
i;f(int*t){setlocale(LC_ALL,"");for(i=721;i--;)wprintf(L"%lc",D[i]%19?D[i]:*t++?48+t[-1]:32);}
```
[Try it online!](https://tio.run/##hZBrSgMxFIX/zyouKZWkzUinD/uItYj9OTuoRcp0RgPj1NaILaUgrsBCiyCIoqL4WIKr6UbGPJxBaEE4SU5yv5wb4tnHnhfHGR554UXf3w0HXi/0t0/2rEzfD3jkwxCP6YTAGCZmpIU2uGi1vEdDPMTS3BghKv0bImp5R0TOd4Y4jFbLubGwBQpbXBtsrrG5PFLM02/g4spIk9@G/NTkg9oo9HlT7w@Dfmn0Uc6KvN1EvhjyVZMLZHEWYB6JnCDTc1@Yn8DuwdG@61KECAsGI8yb1aLDuG0zcnk2knSAXZQNPUTbHd7NOvWWWhs5kc@3yrW86NhOt1EqEjaLJQynPR5hMrWUF50uNGEKNQoVCoVERQrlxFf1trCmemLKm6qpnCQkTS5pU1mPAvpvmlHtz9vSLtX/bsm@O@mDYcasAAvCrFn8Aw "C (gcc) – Try It Online")
## [C (gcc)](https://gcc.gnu.org/), 395 bytes
I'll keep this here so its more evident as to how the program works.
```
#include<locale.h>
#define A L"\n╢───┼───┼───╫───┼───┼───╫───┼───┼───╟"
#define B L"\n║ & │ & │ & ║ & │ & │ & ║ & │ & │ & ║"
#define C L"\n╣═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╠"
#define E B A B A B
#define D L"╝═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╚"E C E C E L"\n╗═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╔"
i;f(int*t){setlocale(LC_ALL,"");for(i=721;i--;)wprintf(L"%lc",D[i]%19?D[i]:*t++?48+t[-1]:32);}
```
[Try it online!](https://tio.run/##S9ZNT07@/185My85pzQl1SYnPzkxJ1Uvw45LOSU1LTMvVcFRwUcpJu/R1EWPpjTA0B7s7KmrqaRmvhLceieo9RMV1BQeTWlCkMSJIAxyhhq0@NHUCTC0Cgd7DZXULEBY7wr0iSMEw8VcgE56NHUukoblONgrqaRmlpIrMCAgGBIc05Fkl@BgL6OSmilKXJnWaRqZeSVaJZrVxaklkNSm4eMc7@jjo6OkpGmdll@kkWlrbmRonamra61ZXlAEVJ2m4aOkmpOspOMSnRmramhpD6KttEq0te1NLLRLonUNY62MjTSta/8DFSvkJmbmaWhWc4HYJdGxCrYK1QoWOgqmOgoGMGSko2ACY5uDuQYYyBLGMMEmC0eGMEPgJhuDGaaYRinoEDQNgiyQ3Aa3xZyQLqC9ZnAHK9Rac6VplGhac9X@BwA "C (gcc) – Try It Online")
Working with unicode in C is... costly. Takes input as an `int*` as shown in the link and in the specification.
I'm going to see if I can save bytes using some number magic instead of hardcoding the string.
[Answer]
# [PHP](https://php.net/), 297 bytes
```
<?for(;$l<19;$l++)echo$l&1?strtr(vsprintf(str_pad("",67,"║ %d │ %d │ %d "),array_slice($_GET,9*($l/2^0)-9,9)),0," "):str_pad([╔,╟,╠,╚][$b=$l?$l<18?$l%6<1?2:1:3:0],108,strtr("11101110111".[╦,╫,╬,╩][$b],[[╤,═],[┼,─],[╪,═],[╧,═]][$b])).[╗,╢,╣,╝][$b],"
";
```
[Try it online!](https://tio.run/##hZDbSsNAEIbv@xRhSWXXjppN25xLrsQX8C7EEHsghWBDEgTvxCdQSBAEsagoHh7Bp8mLxEliQqFCYf7df2Z3v53dKIhKy46CqCd6J8enE0cDYQyC1IYMwqj1ap1KW6G3ZvTfahe8hXTkYW3G2ygBdtKa0DZ6625Rd53Ce5WuYdcsF6uYmmJocR3HwYDNp8FKDPe4naRxGtPLJIqXF@mCYupF/owSAooKpMjvhP5MKLKbjYkw8OPYv/KScDmd0/pXQd@nYngkn0nsQAedMXwewZ1GC3SKPIMif0KtUQ@uI55PxNCuetJw7CsWt2WDG0NDcoFLGjSdEc659CdyiJQ3PP2F@kZ9VBQXHCy/YnqLtsh@oMiuK5d/trX8vXb1bsYqyj0WnlEvqMeGQnrELMtf "PHP – Try It Online")
Expanded
```
for(;$l<19;$l++) # loop thrpugh lines
echo$l&1 # Output
?strtr(
vsprintf(str_pad("",67,"║ %d │ %d │ %d ") # formated string for lines with numbers
,array_slice($_GET,9*($l/2^0)-9,9)) # nine items of the input array
,0," ") #replace zeros with space
:str_pad([╔,╟,╠,╚][$b=$l?$l<18?$l%6<1?2:1:3:0] # start character non number lines and switch number four cases
,108 # fill too 108 bytes
,strtr("11101110111".[╦,╫,╬,╩][$b] # with string
,[[╤,═],[┼,─],[╪,═],[╧,═]][$b])) #replace ones and zero with the two character in array chosed
.[╗,╢,╣,╝][$b] # end row with chosen character
,"
"; # end line with new line
```
used functions for both versions
[vsprintf](http://php.net/manual/en/function.vsprintf.php) , [strtr](http://php.net/manual/en/function.strtr.php) , [str\_pad](http://php.net/manual/en/function.str-pad.php) , [array\_slice](http://php.net/manual/en/function.array-slice.php) , [array\_chunk](http://php.net/manual/en/function.array-chunk.php)
# [PHP](https://php.net/), 313 bytes
```
<?$r=($s=str_pad)(╔,108,($t=strtr)(($p=11101110111).╦,[╤,═])).╗;foreach(array_chunk($_GET,9)as$v)$r.=$t(vsprintf($s("
",68,"║ %d │ %d │ %d "),$v),0," ").(++$k%9?$k%3?$s("
╟",109,$t($p.╫,[┼,─])).╢:$s("
╠",109,$t($p.╬,[╪,═])).╣:"");echo$r.$s("
╚",109,$t($p.╩,[╧,═])).╝;
```
[Try it online!](https://tio.run/##hZDdSsMwFMfv9xQhZJCww2jdV7taeiW@gHdjlNJtVAZbSOvAO/EJFBoEQRQVhx@P4NPkRWratd3GhMFJck5y/v/zIzzi2anHI94g/vnZhTuyAPUAGVWcAOpW@aAojYOwq6T732sdZmVSO3eKpHdoheCo2yasHbZ6yuCYSs/t18BjJyPCpSR240T4PJgwqmQKpmEBJUl@mQhGKeGuaZpGuVhbyQ8YKfkOSt6NWV4/OLOlmAZhRAMhgms/jK4Wc1p8K9gsiMmKEdF2SUJXMReXi2Smh1LcwNC3ACt5j5oTpNLbnQMz0Cr9GVinbdpqkXnT9vTW8Qqpks9Yk9qgTQnXDN@aKf0Fld5smF6HZd/Lft9Pzv61ZX8bYsycaRgtNWIpedyXfOaS9Vby5GTZHw "PHP – Try It Online")
[Answer]
# T-SQL, ~~445~~ 437 bytes (in 381 characters)
```
DECLARE @r INT=0,@ NVARCHAR(999)=N'╔=╤=╤=╦=╤=╤=╦=╤=╤=╗P'p:SELECT @+=FORMAT(CAST(SUBSTRING(a,@r*9+1,9)AS INT),N'║ 0 │ 0 │ 0 ║ 0 │ 0 │ 0 ║ 0 │ 0 │ 0 ║P')FROM t
SET @r+=1IF @r=9SET @+=N'╚=╧=╧=╩=╧=╧=╩=╧=╧=╝P'ELSE IF @r%3=0SET @+=N'╠=╪=╪=╬=╪=╪=╬=╪=╪=╣P'ELSE SET @+=N'╟-┼-┼-╫-┼-┼-╫-┼-┼-╢P'IF @r<9GOTO p
PRINT REPLACE(REPLACE(REPLACE(REPLACE(@,'=',N'═══'),'-',N'───'),'0',' '),'P',CHAR(13))
```
Input is via a string of digits stored in column *a* of pre-existing table *t*, [per approved methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341).
**Format and Explanation**:
```
DECLARE @r INT=0, @ NVARCHAR(999)= N'╔=╤=╤=╦=╤=╤=╦=╤=╤=╗P'
p:
SELECT @+= FORMAT(CAST(SUBSTRING(a, @r*9+1, 9) AS INT),
N'║ 0 │ 0 │ 0 ║ 0 │ 0 │ 0 ║ 0 │ 0 │ 0 ║P') FROM t
SET @r+=1
IF @r=9 SET @+= N'╚=╧=╧=╩=╧=╧=╩=╧=╧=╝P'
ELSE IF @r%3=0 SET @+= N'╠=╪=╪=╬=╪=╪=╬=╪=╪=╣P'
ELSE SET @+= N'╟-┼-┼-╫-┼-┼-╫-┼-┼-╢P'
IF @r<9 GOTO p
PRINT REPLACE(REPLACE(REPLACE(REPLACE(@, '=',N'═══'), '-',N'───'), '0',' '), 'P',CHAR(13))
```
In the top line of the loop I'm getting the next 9 digits of the input string from column *a* of pre-existing table *t*.
I convert that string of digits to an integer, and use the .Net `FORMAT` function to display them using a custom text template `'║ 0 │ 0 │ 0 ║ 0 │ 0 │ 0 ║ 0 │ 0 │ 0 ║P'`.
After that I just append the appropriate divider line, and make some byte-saving replacements before output.
Output is displayed in the results pane:
```
╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗
║ 8 │ 5 │ ║ │ │ 2 ║ 4 │ │ ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ 7 │ 2 │ ║ │ │ ║ │ │ 9 ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ │ │ 4 ║ │ │ ║ │ │ ║
╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣
║ │ │ ║ 1 │ │ 7 ║ │ │ 2 ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ 3 │ │ 5 ║ │ │ ║ 9 │ │ ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ │ 4 │ ║ │ │ ║ │ │ ║
╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣
║ │ │ ║ │ 8 │ ║ │ 7 │ ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ │ 1 │ 7 ║ │ │ ║ │ │ ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ │ │ ║ │ 3 │ 6 ║ │ 4 │ ║
╚═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╝
```
I previously had some additional replacements for some of the other drawing characters, but they ultimately didn't save me bytes.
**EDIT 1**: Saved 8 bytes by starting `@r` at zero instead of 1, and removing some unneeded spaces.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~196~~ 167 bytes
```
.{27}
¶N#=XZ#Q¶|$&
\d{9}\B
$&¶M#─┼Y#P¶|
\d{3}
$& |
\B\d
│ $&
^¶.*
B#=RT#E
$
¶H#=UW#K
+`#([^#¶]+)([^#¶])#
#$1#$2#$1#$2#$1#
#(.)#
$1$1$1
T`0=|#L` ═-╬
```
[Try it online!](https://tio.run/##TYy5CsJQEEX7@YrAPIILhsmiMUWagCC4oKK4RYkQCxsLsYsB8Qss4l9Yv8rqfcr7kfjigt6B4c49lzlsj7v9Js@NxHJTELyP/myBQ8FPTIcwTrw0DIDpgvdQZmeZPeY4ULBAdgoa0zXlgzAGTWYXdcJacKMCAfqjMbaAqZdt9CdT7EA1wtJyjYKvquWPKSMgM5FZvw1YMlTMzGJgHJF/wm6kydu1Jm/3PG/WichyiFyLXvKIHPrKJFdRm@pv8EeImlRA0/0ldkMVng "Retina – Try It Online") Takes input as a string of length 81. Explanation: Because the box drawing characters cost three bytes, the unicode code points `═-╬` are represented in the code using `=|#A-Z` (not all the characters are used but sticking to ranges saves bytes). Additionally the rows are compressed using `#` signs: `a#bcd#e` expands to `abbbcbbbcbbbdbbbcbbbcbbbdbbbcbbbcbbbe`.
```
.{27}
¶N#=XZ#Q¶|$&
```
Inserts `╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣` for every third row, plus a `║` at the start of every group of 27.
```
\d{9}\B
$&¶M#─┼Y#P¶|
```
Inserts `╟───┼───┼───╫───┼───┼───╫───┼───┼───╢` between the other rows, plus `║`s at the start of those rows.
```
\d{3}
$& |
```
Inserts `║`s after every three digits. All the `║`s have now been inserted.
```
\B\d
│ $&
```
Inserts `|`s between all the remaining pairs of digits. (This one is the actual box drawing character rather than a pipe. Unfortunately the characters `─│┼` have codes too far apart from each other and the double box characters to make it worth while using placeholders.)
```
^¶.*
B#=RT#E
```
Changes the first row to `╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗` (this saves 1 byte over not adding the first row in the first place).
```
$
¶H#=UW#K
```
Adds `╚═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╝` after the last row.
```
+`#([^#¶]+)([^#¶])#
#$1#$2#$1#$2#$1#
```
Expands `a#bcd#e`, first to `a#bc#d#bc#d#bc#e`, then to `a#b#c#b#c#b#d#b#c#b#c#b#d#b#c#b#c#b#e`.
```
#(.)#
$1$1$1
```
Changes `#b#` to `bbb`. This completes the decompression.
```
T`0=|#L` ═-╬
```
Deletes all the zero entries, and replaces the placeholders with the box drawing characters.
[Answer]
# JavaScript (ES6), 246 bytes / 198 chars
```
(n,r=(x,y)=>x+y+x+y+x,q=s=>([u,w,x,y,z]=[...s[0]],u+r(r(w+w+w,x),y)+z+`
`))=>q`╔═╤╦╗`+n.reduce((o,v,i)=>o+"║││"[i++%3]+` ${v||" "} `+(i%9?e:`║
`+(i-27&&i-54?i<81?q`╟─┼╫╢`:e:q`╠═╪╬╣`)),e="")+q`╚═╧╩╝`
```
Input is an array of integers. Ended up using the same two helper functions as [Leaky Nun's Python answer](https://codegolf.stackexchange.com/a/126934/69583), so credit goes there.
### If `function` is required, 263 bytes / 215 chars
```
function g(n,r=(x,y)=>x+y+x+y+x,q=s=>([u,w,x,y,z]=[...s[0]],u+r(r(w+w+w,x),y)+z+`
`)){return q`╔═╤╦╗`+n.reduce((o,v,i)=>o+"║││"[i++%3]+` ${v||" "} `+(i%9?e:`║
`+(i-27&&i-54?i<81?q`╟─┼╫╢`:e:q`╠═╪╬╣`)),e="")+q`╚═╧╩╝`}
```
## Test Snippet
Any input of 81 numbers is supported (`1234`, `1, 2, 3, 4`. `[1 2 3 4]`, etc). Best viewed as full page.
```
f=
(n,r=(x,y)=>x+y+x+y+x,q=s=>([u,w,x,y,z]=[...s[0]],u+r(r(w+w+w,x),y)+z+`
`))=>q`╔═╤╦╗`+n.reduce((o,v,i)=>o+"║││"[i++%3]+` ${v||" "} `+(i%9?e:`║
`+(i-27&&i-54?i<81?q`╟─┼╫╢`:e:q`╠═╪╬╣`)),e="")+q`╚═╧╩╝`
onload=I.oninput=_=>O.innerHTML=(m=I.value.match(/\d/g))&&m.length==81?f(m.map(x=>+x)):''
```
```
<textarea id=I rows=3 style="width:95%">8, 5, 0, 0, 0, 2, 4, 0, 0, 7, 2, 0, 0, 0, 0, 0, 0, 9, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 7, 0, 0, 2, 3, 0, 5, 0, 0, 0, 9, 0, 0 ,0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 7, 0, 0, 1, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 6, 0, 4, 0</textarea>
<pre id=O>
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~174~~ ~~172~~ ~~164~~ ~~160~~ 158 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
«ž#>]Wž²6√±_ΕΨ╥╬]v←ē⅓ZΗ⌡z∫◄‽q §↑╗∑Ολ[Μ↕z↓/∆Yn⁄:Ο║χ≥¾▓g*≈]═+π℮─6⁽SE/⁷,0+►Ƨ⌡u\^⁄-▼0cΦ“╤─┼╬│║═╔╗╚╝”Φ⅜nΡ¡ΞΨīŗ(`½│uģ“ ╬ζ─{ζ} 6Δ¹∑A'⁄─{IaW}¹∑#¶ŗ3 ¶ŗ ”+Ƨøp+!!┌d0@ŗčŗ
```
Overly long explanation:
```
...“ push a big base-43 encoded number; will be used later. It's pushed here to save a byte on a quote
...” push "╤─┼╬│║═╔╗╚╝" - the chars in SOGLs encoding
...“ push 679301851737965572513837476350078477
╬ push "╬"
ζ convert it to its codepoint (9580)
─ convert that number to an array of base-9580 numbers
{ζ} convert each number to a character (pushing each on the stack)
6Δ push all ascii chars up to 6 (" !"#$%&'()*+,-./0123456")
¹∑ join all the strings on the stack together ("╤─┼╬│║═╔╗╚╝╦╟╫╢╠╪╣╧╩ !"#$%&'()*+,-./0123456")
A save on variable `A`. Now ontop of the stack is the 1st big number
'⁄─ onvert from base 43
{ } for each number do
I increase
aW get its position in the variable A
¹∑ join all the strings ontop of the stack (the loop above pushed each char separately)
#¶ŗ replace quote (") characters with newlines
3 ¶ŗ replace 3s with "¶"
”+ append "”"
Ƨøp+ append "øp"
!! execute the created code as SOGL
┌ push "-"
d push variable d - defaults to string input. In a full program could be set as an input
0@ŗ replace zeroes with spaces
č chop into an array
ŗ replace ["-" with input chopped - so each iteratively]
```
The program that's executed:
```
───!#
- $
¶%&¶'(
)╪)╪)+
)╤)╤),
)╧)╧).
┼#
+╬+/
0!╫0!1
,╦,2
.╩.4
5│$║&
#0
═══)
$│$5
║&&%
╠/╬+╣6'*
╟1╫0!╢(
(6
╔2╦,╗6'**╚4╩.╝”øp
```
where all but last line are just `in the entire program replace occurrences of the last char of this line with the rest of this line`. This is the reason it was possible to make half of the chars just random ascii (but getting so that spaces, dashes, and quotes are usefully used took a while to figure out)
```
...” push the whole sudoku grid
øp print nothing (prevents bug that this code would already print and pop the result)
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JUFCJXUwMTdFJTIzJTNFJTVEVyV1MDE3RSVCMjYldTIyMUElQjFfJXUwMzk1JXUwM0E4JXUyNTY1JXUyNTZDJTVEdiV1MjE5MCV1MDExMyV1MjE1M1oldTAzOTcldTIzMjF6JXUyMjJCJXUyNUM0JXUyMDNEcSUwOSVBNyV1MjE5MSV1MjU1NyV1MjIxMSV1MDM5RiV1MDNCQiU1QiV1MDM5QyV1MjE5NXoldTIxOTMvJXUyMjA2WW4ldTIwNDQlM0EldTAzOUYldTI1NTEldTAzQzcldTIyNjUlQkUldTI1OTNnKiV1MjI0OCU1RCV1MjU1MCsldTAzQzAldTIxMkUldTI1MDA2JXUyMDdEU0UvJXUyMDc3JTJDMCsldTI1QkEldTAxQTcldTIzMjF1JTVDJTVFJXUyMDQ0LSV1MjVCQzBjJXUwM0E2JXUyMDFDJXUyNTY0JXUyNTAwJXUyNTNDJXUyNTZDJXUyNTAyJXUyNTUxJXUyNTUwJXUyNTU0JXUyNTU3JXUyNTVBJXUyNTVEJXUyMDFEJXUwM0E2JXUyMTVDbiV1MDNBMSVBMSV1MDM5RSV1MDNBOCV1MDEyQiV1MDE1NyUyOCU2MCVCRCV1MjUwMnUldTAxMjMldTIwMUMlMjAldTI1NkMldTAzQjYldTI1MDAlN0IldTAzQjYlN0QlMjA2JXUwMzk0JUI5JXUyMjExQSUyNyV1MjA0NCV1MjUwMCU3QklhVyU3RCVCOSV1MjIxMSUyMyVCNiV1MDE1NzMlMjAlQjYldTAxNTclMjAldTIwMUQrJXUwMUE3JUY4cCslMjElMjEldTI1MEMlMkMwQCV1MDE1NyV1MDEwRCV1MDE1Nw__,inputs=ODUwMDAyNDAwNzIwMDAwMDA5MDA0MDAwMDAwMDAwMTA3MDAyMzA1MDAwOTAwMDQwMDAwMDAwMDAwMDgwMDcwMDE3MDAwMDAwMDAwMDM2MDQw)
The online interpreter code is more correct because tabs don't work with SE
-8 bytes: brute force replacement compressing the entire board, then replacing foreign chars (to the codepage) with their codepoints. Doing this took an hour less than the old program...
-4 bytes: compressing the compressed string...
-2 bytes: using a variable+string instead of array
[Answer]
## Batch, 332 bytes
```
@echo off
set/ps=
set s=%s:0= %
call:l É Í Ñ Ë »
set t="Ç Ä Å × ¶"
for %%i in (%t% %t% "Ì Í Ø Î ¹" %t% %t% "Ì Í Ø Î ¹" %t% %t% "È Í Ï Ê ¼")do call:c %%~i
exit/b
:c
set t=º
for %%j in (³ ³ º ³ ³ º ³ ³ º)do call set t=%%t%% %%s:~,1%% %%j&call set s=%%s:~1%%
echo %t%
:l
set t=%2%2%2%3%2%2%2%3%2%2%2
echo %1%t%%4%t%%4%t%%5
```
Needs the console to be in CP437. If that's not your default, then you can change it using the `CHCP 437` command if your console is set to TrueType fonts. (It will only work with raster fonts if CP437 is already your default code page.) This is what the code looks like in CP437:
```
@echo off
set/ps=
set s=%s:0= %
call:l ╔ ═ ╤ ╦ ╗
set t="╟ ─ ┼ ╫ ╢"
for %%i in (%t% %t% "╠ ═ ╪ ╬ ╣" %t% %t% "╠ ═ ╪ ╬ ╣" %t% %t% "╚ ═ ╧ ╩ ╝")do call:c %%~i
exit/b
:c
set t=║
for %%j in (│ │ ║ │ │ ║ │ │ ║)do call set t=%%t%% %%s:~,1%% %%j&call set s=%%s:~1%%
echo %t%
:l
set t=%2%2%2%3%2%2%2%3%2%2%2
echo %1%t%%4%t%%4%t%%5
```
[Answer]
# With ideas harvested from other answers:
## [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 401 bytes, 349 Chars
```
string s(string x){Func<string,string,string>q=(m,n)=>m+n+m+n+m;var a="╔"+q(q("=","╤"),"╦")+"╗";for(var i=0;i<9;) {a+=int.Parse(x.Substring(i*9,9)).ToString("\n║"+q(q(" 0 ","│"),"║")+"║\n")+(i++<8?(i%3>0?"╟"+q(q("-","┼"),"╫")+"╢":"╠"+q(q("=","╪"),"╬")+"╣"):"╚"+q(q("=","╧"),"╩")+"╝");}return a.Replace("=","═══").Replace("-","───").Replace("0"," ");}
```
### Ungolfed:
```
static public string s(string x)
{
Func<string,string,string>q=(m,n)=>m+n+m+n+m;
var a="╔"+q(q("=","╤"),"╦")+"╗";
for (var i=0;i<9;) //once per row
{
//parse that row to an int, then spit out a formatted string
a += int.Parse(x.Substring(i*9,9)).ToString("\n║"+q(q(" 0 ","│"),"║")+"║\n")
// as well as a trailing row for the box
+ (i++<8?(i%3>0?"╟"+q(q("-","┼"),"╫")+"╢":"╠"+q(q("=","╪"),"╬")+"╣"):"╚"+q(q("=","╧"),"╩")+"╝");
}
//expand placeholder characters before returning
return a.Replace("=","═══").Replace("-","───").Replace("0"," ");
}
```
[Try it online!](https://tio.run/##VY7bSgMxEIbv9ylCQEjcuoy2ta3brRTBO0Gs4E1v0jVKoJu1SaqVUhCfwIIiCKKoKB4ewafxRWrS1EPDJJPM/03@SfVSmis@6WshD1HrVBuexUEQpF2mNWoOg0AbZkSKtFGOMFybTs7UPkoQrpYBYKUEUFmB6aoBlOBnLUPFqkUoe@GfAlAFJy5X/irFVQvg@NfvOBf7aIsJSWgwDBBCx0yhjFtbyU9Qk9DYFTdyqfMuj/aUMJxkPNLkd0JqkVEwmQ2uyewyoMPNvkzr/lmYS41eQrKCpEkjC2U43bHzZQn@urrEYY/0CE5wwb6eMHXpGdPQpmscH@SKOFYkEIt6LaZDFiZCmmibKc3JIGr1O96FiMVaoUZptJu3fAG35dfVePY/AuQcLs@9w9g7jNvSXogIw3p1nYiFYgPWbflu1rQ0bfn0Le@@5QGv2fN@buw3T3x44hFTh9zMIS8eefXILabxSHHTVxKxaIcfdVnKf9ALH5j@CX6QMx//BbACcp9NRpNv "C# (.NET Core) – Try It Online")
# My Answer:
## [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 509 430 418 bytes, 328 chars
```
string b(string x){var a="╔=╤=╤=╦=╤=╤=╦=╤=╤=╗\n║";for(int i=0,j=0,k,l,m;j<3;j++)for(k=0;k<3;k++){for(l=0;l<3;l++)for(m=0;m<3;)a+=" "+x[i++]+(m++<2?" │":" ║");a+=i<80?(k<2?"\n╟-┼-┼-╫-┼-┼-╫-┼-┼-╢\n║":"\n╠=╪=╪=╬=╪=╪=╬=╪=╪=╣\n║"):"\n╚=╧=╧=╩=╧=╧=╩=╧=╧=╝";}return a.Replace("=","═══").Replace("-","───").Replace("0"," ");}
```
### Ungolfed:
```
public string s(string x)
{
var a = "╔=╤=╤=╦=╤=╤=╦=╤=╤=╗\n║";
for (int i=0,j=0,k,l,m;j<3;j++)
{
for (k = 0; k < 3;k++)
{
for (l = 0; l < 3; l++)
{
for (m = 0; m < 3;)
a += " " + x[i++] + (m++ < 2 ? " │" : " ║");
}
a += i < 80 ? (k < 2 ? "\n╟-┼-┼-╫-┼-┼-╫-┼-┼-╢\n║": "\n╠=╪=╪=╬=╪=╪=╬=╪=╪=╣\n║")
: "\n╚=╧=╧=╩=╧=╧=╩=╧=╧=╝";
}
}
return a.Replace("=", "═══").Replace("-","───").Replace("0"," ");
}
I also looked at using a lambda for the `for` loops here, but it actually cost me one byte (saved 10 bytes per loop, with 41 bytes of overhead).
```
[Try it online!](https://tio.run/##dVDLThsxFN3PV1he2XISXfJoUpwRQqy7KYsuoAtncJEzr2psQqooUsUXFCkRUqUKBIiqwCfwNfMj4TozDWxi@WjOPefeuWcmss0oL/TqzJrslBz@sE6nMgiCKFHWkv1ZEFinnImIdYXvcNq6Ua6KExISOugBQLsL0G/D@nwE6ML/swN9dDvQq4x3DsAAvLnTf1M6H7CBys2@SW5OyCdlMsaDWUAImaiCpBrXZvqc7DMuvXiQZzZPdOtLYZxmqW6N2CYhx5Z5sKqDj1hNpnzmX6VCWi4XYbm8r/GwhV8dZ@XykspvecFM5ogJoTFGxI2kkcrxsCPHQnDvxiHIGOsY65kXEhQSFJK6IcU6xZorEVJCxfTICPFVsFSIYXuPknJxQXfxgeu4xB4zHMAei73nQ1w3y8VLheXTFn5bpd1dD9xg/Mcaz1v4XTXAq4nfqPyt8W8L/0PlvNDurMiIan3W3xMVaUZD2sAf@qu6lL8ZTW8sflb3vQFoEPzQ@Wq@egU "C# (.NET Core) – Try It Online")
[Answer]
# [Chip](https://github.com/Phlarx/chip), 3645 bytes
...that's not a typo...
```
ooooooZZ-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-).
|`xxxx-x--(x---x---x---x---x-v-x---x---x---x---x---x-.`K-)-K-)-K-)-K-).
|b|`xx-x--(x-v-x---x-v-x---x-x-x---x-v-x---x-v-x---x-x-x---x-v-x---x-.`K-).
|>xd`x-x(v-x-x-x-v-x-x-x-v-x-x-x-v-x-x-x-v-x-x-x-v-x-x-x-v-x-x-x-v-x-x-x-.|
||`--x-x-x(x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x/.
|`--z',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\','
`-. |,< >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.|
*-x-/xZ/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ'
Z~' |`'|`' |`' |`' |`' |`' |`' |`' |`' |`' |`' |`' |`' |`' |`' |`' |`','`'
`)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)'
=
oooooo).h
`)))--^M^Zh
=
oooooo
| `(--------------------------------------------------------------------------------------------------------va
KZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ^cg
)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx-xKZvvZ
xxxxxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxxx-Kxxxx}e
)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)x))xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)x))xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)x)b`feac
c
=
oooooo
,' `(--------------------------------------------------------------------------------------------------------.cba
KZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ^x^^)v--.
xx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxxx-xK-'f e`.
)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx-x-K-+Z+Z}e
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxK^}b gac
xxxxxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxxx-K^d
=
oooooo
,-'
KZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZtabgfv------.
)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx-xK^^x-Zv-vZ}e
xxxxxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxxxK^---^}cade,]b
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)-K----^-^^~'
,v'
db
=
oooooo
,--' `(--------------------------------------------------------------------------------------------------------v-.,-v-ZZZZZZZZZZZZf
KZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'a{x.df
)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xxKx-xxv+Zc
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)x-KZx+bge
xx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxxx---K\--^c
a^b
=
oooooo
,---'`(--------------------------------------------------.
KZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'gf
)xxxxx)xxxxx)xxxxx)xxxxx)xxxxx)xxxxx)xxxxx)xxxxx)xxxxx)xx-^KZc
)xxxxx)x)xxx)x)xxx)xxxxx)x)xxx)x)xxx)xxxxx)x)xxx)x)xxx)xxbahKZ\ZZZ
x))xxxxxxxxxxxxxxxx))xxxxxxxxxxxxxxxx))xxxxxxxxxxxxxxxx))-K-eh|fff
,--K-v-v-K--v-vK-v---K-----K-----K-----K-----K-----K `--Z-Z--'
A/ab/B/e/C/cd/D/-e/A
*}s
```
[Try it online!](https://tio.run/##xZdtb9sgEIC/36/wN0LjA/q2tNJWqdu@of0BlCH8GvfTJq1CaHP617Ozk6Z5WaU0btiZw/ZBgHDPHUnRPPxcLH70Ygxy1IergNYFEgyII1LcVo/7tk6F2x8n70ZajeN3Ph923l@z9@PSWHehdNQ28qs@x95FC23rVjONAg66ZLdZiL9ZKqfDlYFDkbTpx@ROtEMVzmiBMhgqdqAyME8saR2jkgzQlDkGCYl7E5D/UgafYIk3Fw04zjmi/WZNs7ZD2880wkjiM9AmqthiBjyEmAWDNt4bCFvCT/wcUHf1vDrw6/L36pO7usoKQrZYY5U8Qsp6sGwksESRx0crWMs9zQ2n9@62p4NGVieVE/HRprwyNmNDmIWDhL9Tn6DtPE9mBFr0sLLlS75MkcXG7DHLZ7VfYf4fcpm1AY1Hv@/zk@@97tKHnRdZWaXf88jEdUdoNz1a@8Qg9QzKfBMEZDEPThQpVZtc1LFBZNmfIMo6NoKaIAx@bAqI636KfBPG@ayKnt4R9ZTAozM1s9vIITsGOXE8KWzW@3u9xDfVaDV57fmVb9QHWfKs0WZKi4D@h8iOew6yUAhXTVvXNSS0e5oiyHdRTbfuGZcR/nqd0N8WQxcl/XuZ5fKzrOQXWZTyq8RK3sPZ/NdicXOtlLq4UmpyoXq5VepKPcu5mlDrpbpeNmy0KHWjusbzyYvl8gN1gL8 "Chip – Try It Online"), sort of. The TIO version contains a cutoff about a third of the way in (the `t` after the 4th `oooooo`), so that it should terminate in less than 60 seconds. The full version takes about 1m25s on my machine, and TIO seems about half as quick. This also means the TIO only shows the first 7 lines of output.
My first draft weighed in at a massive 19758 bytes, and took me about 8m30s to run. The final solution, pre-golfing, was a spry 5980 bytes, taking only 2m07s.
### So, how's it work, then?
This takes a string of 82 bytes, 81 digits, followed by a terminator. `\0` or `\n` or even another number will do. (This implementation actually only looks at the first 81, but requires at least one more, since Chip will terminate if it has exhausted its input. If this is unacceptable, the flag `-z` may be used, which effectively appends an infinite number of `\0` bytes to the end of the input.) The shortened TIO code doesn't actually get to all 81 bytes, so the point is moot there.
The way I've implemented this, it only looks at the low 4 bits of the input, so anything, really, can be a sudoku 'puzzle', from raw binary data, to the lesser-known works of Shakespeare. Any character whose low 4 bits are all zero will appear as a space (a special case), all other characters map into `123456789:;<=>?`. (So, the last few aren't digits, but neither is 10 a valid number in normal sudoku).
For the box-drawing characters, it produces UTF-8, equating to 3 bytes each.
### What about the actual implementation?
Chip is a 3D language that is inspired by integrated circuits. It has wires, logic gates, and memory cells. Most stuff is done on 2D planes, but these planes may be stacked atop one another. That is how this program is built.
The lines that start with `=` are the layer separators. Then, the layers are stacked, with the top and left sides aligned. The `o`'s serve as pins, allowing signals to pass from one layer to another.
Each layer here has a purpose, you could think of them as functions. The first layer controls everything; it 'calls' each of the other layers in turn. There is a repeating left-to-right pattern here. That pattern keeps track of which of the 19 lines of output we are currently printing.
The second layer is rather tiny, and it has a very tiny job. It sets the `0x80` bit for all the lines of output except the lines that contain numbers. `h` is the Chip element that corresponds to the `0x80` bit. (The low end of the alphabet `h` through `a` define all eight output bits.)
Layer three is where we really get into the meat of printing. This layer is in charge of line one. The ungolfed version has eight rows of `x`'s and `)`'s, mapping to 0's and 1's for each of the eight bits of each byte. However, we can take advantage of the patterns in the bits to accomplish the same task in fewer rows.
Layer four is much like the third. It handles the horizontal double lines.
Layer five handles the last line. Note that it is missing the wire along the top that the other layers have. This is because we don't need to return control to the sequencer. Instead, we can just terminate execution here with `t`.
Layer six handles the horizontal single lines.
Layer seven is where the numbers are printed. It is 'called' for each the nine numeric lines. It consumes 9 bytes of input as part of its execution.
[Answer]
# JavaScript (ES6), 222 bytes
Using short syntax for ES6 functions - 174 chars encoded in utf8, 222 bytes (<https://mothereff.in/byte-counter>). Using `function ...` requires 16 more bytes.
```
F=v=>[1,...v].map((x,i)=>'│║│'[i%3]+` ${x||' '} `+(i%9?'':`║
${[h,r,s,u,t]=i%27?'─╟╫┼╢':i>80?'═╚╩╧╝':i?'═╠╬╪╣':'═╔╦╤╗',r+(s=(u=(h+=h+h)+u+h+u+h)+s)+s+u+t}
`)).join``.slice(6)
```
*Less golfed*
```
F=v=>{
// horizontal lines are appended after each 9th element
// so I need to prepend a dummy first element to draw the top horizontal line
v = [1, ...v];
return v.map( (x,i) =>
'│║│'[i % 3] + ` ${x||' '} ` // left bar and cell value
+ ( i % 9 ? '' // add horizontal line after each 9th element
// the line drawing characters are chosen according to the value of i
: `║\n${ [h, r, s, u, t] =
i % 27 != 0
? '─╟╫┼╢'
: i > 80
? '═╚╩╧╝' // i==81, bottom row
: i != 0
? '═╠╬╪╣'
: '═╔╦╤╗', // i==0, top row
r + (s = (u = (h += h + h) + u + h + u + h) + s) + s + u + t
}\n`
)
).join``
.slice(6) // cut the first cell (the dummy element)
}
```
```
F=v=>[1,...v].map((x,i)=>'│║│'[i%3]+` ${x||' '} `+(i%9?'':`║
${[h,r,s,u,t]=i%27?'─╟╫┼╢':i>80?'═╚╩╧╝':i?'═╠╬╪╣':'═╔╦╤╗',r+(s=(u=(h+=h+h)+u+h+u+h)+s)+s+u+t}
`)).join``.slice(6)
function go() {
var i=I.value
i = i.match(/\d+/g).map(x => +x); // convert strings to numbers
O.textContent = F(i)
}
```
```
#I { width: 90% }
```
```
<input id=I value='8 5 0 0 0 2 4 0 0 7 2 0 0 0 0 0 0 9 0 0 4 0 0 0 0 0 0 0 0 0 1 0 7 0 0 2 3 0 5 0 0 0 9 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 8 0 0 7 0 0 1 7 0 0 0 0 0 0 0 0 0 0 3 6 0 4 0'>
<button onclick='go()'>go</button>
<pre id=O></pre>
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 279 bytes
```
String f(int[]a){String P="0121213121213121214",R[]={"╔═╤╦╗","║ │║║x","╟─┼╫╢","╠═╪╬╣","╚═╧╩╝"},r="";for(int X:P.getBytes()){for(int x:P.replace("1",R[X-=48].length()>5?"151":"111").getBytes())r+=R[X].charAt(x-48);r+="\n";}for(int i:a)r=r.replaceFirst("x",i>0?""+i:" ");return r;}
```
[Try it online!](https://tio.run/##hVHNattAEL77KYY57RJZWIncuBZKaA@5BUJyCbg6bJ21s6myNqt14iAEpU/QgpdCoTQkoaU/j9Cn2RdxVxvLGFKINGhmv5n5ZvTtBbti7cmUy4uzd8vp7G0uhjDMWVHAIRMSyuWJVkKOYUSE1IOM0XIFHKXYibbdu7PxjTE4HmRpidYsrPlozYM13635jIFDPoFdfHDO2dwD3@zivV38tea3NXceufVNv6z5Y829R7545Ic1P635ilWgUsRkNFH1OnDaPwrHXL@@0bwglJYNPne44tOcDTnBqN7ptJ3GvSzMuRzrc0L3uvsYdSPsYxRFSDdJ1FbqyrNweM7UK03m7bhHEwfiG4lJ1UwQfUZVqpopB0IVmqD7LbHX2UfcEn0EdH1cz5QElVRLgJW6hWbauauJOINLpzF5FHSQAVPjgkLZAvd49es0pCD5tT8TmvjcyU2h@WU4melw6lp1LkldGY5IXenvqYReAN0AOo1tBxA38a4/dp7YyyaI/5ddW9SQrJl3fNB9SgXBs2yP1tvYbT1l97kuN/fFeuGKruQBcK5qVa3lPw "Java (OpenJDK 8) – Try It Online")
For the byte count, use CP-437, [which is natively supported by Java](https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html) as `IBM437` (recent APIs) or `Cp437` (older APIs); so use a system that has this charset has this charset as default charset.
This code is compatible from Java 5 onwards, but was tested on Java 8 only.
### Explanation
```
String f(int[]a){
String P="0121213121213121214", // Both lines and rows are repeated according to this pattern.
R[]={"╔═╤╦╗","║ │║║x","╟─┼╫╢","╠═╪╬╣","╚═╧╩╝"}, // Characters found on each line.
// (note the 'x')
r=""; // The string under construction
for (int X: P.getBytes()) { // For each line,
for (int x: // For each character in the pattern,
P.replace("1",R[X-=48].length()>5?"151":"111") // *but* with a cell width of 3,
// and with an optional character ('x')
.getBytes())
r+=R[X].charAt(x-48); // append the real mapped character
r+="\n"; // then append a new line
}
for(int i:a) // For each number in the input
r = r.replaceFirst("x",i>0?""+i:" "); // replace the first 'x' with that number.
// (or space if zero)
return r; // Return the constructed string.
}
```
[Answer]
# [Tcl](http://tcl.tk/), 373 bytes (273 chars)
Very naïve approach, but I just had to do it even it not being a winner by any measure:
```
puts ╔[set D ═══]╤$D╤$D╦$D╤$D╤$D╦$D╤$D╤$D╗
set r ║
lmap x $L {set r $r\ [expr $x?$x:{ }]\ [expr [incr i]%3?"│":"║"]
if ![expr $i%9] {puts $r\n[expr $i%27?"╟[set S ───]┼$S┼$S╫$S┼$S┼$S╫$S┼$S┼$S╢":$i<72?"╠$D╪$D╪$D╬$D╪$D╪$D╬$D╪$D╪$D╣":"╚$D╧$D╧$D╩$D╧$D╧$D╩$D╧$D╧$D╝"]
set r ║}}
```
[Try it online!](https://tio.run/##K0nO@V@cWqLgo1BtoWCqYACGRgomYNocyDJAgpZg0gRFDAINwaoheo2BpCmKDux6QNACag/EDHOsaowVzCAm1P4vKC0pVng0dUo0yMkuQNYECIp9NHWJiguUWAZnYeNO5wLpLQLqnajAlZObWKBQoaAC9D1EVKUoRiE6taIAyKqwV6mwqlaojYWJRGfmJRcpZMaqGtsrPZrSpGSlBDRDKZYrM01BEaonU9UyVqEa7EqgSXlwUSNzoJap88HODlZ4NKUBgmIfTdmjEgwhpq6GsbByFylZqWTamBuBzFkA8scqOLEGL3cx2J2zQMzlcGIlXu5coKfggVRb@/8/AA "Tcl – Try It Online")
---
Same chars expense but more bytes:
# [Tcl](http://tcl.tk/), 421 bytes (273 chars)
```
puts ╔[set D ═══]╤$D╤$D╦$D╤$D╤$D╦$D╤$D╤$D╗
set r ║
lmap x $L {set r $r\ [expr $x?$x:{ }]\ [expr [incr i]%3?"│":"║"]
if ![expr $i%9] {puts $r\n[expr $i%27?"╟───┼───┼───╫───┼───┼───╫───┼───┼───╢":$i<72?"╠$D╪$D╪$D╬$D╪$D╪$D╬$D╪$D╪$D╣":"╚$D╧$D╧$D╩$D╧$D╧$D╩$D╧$D╧$D╝"]
set r ║}}
```
[Try it online!](https://tio.run/##K0nO@V@cWqLgo1BtoWCqYACGRgomYNocyDJAgpZg0gRFDAINwaoheo2BpCmKDux6QNACag/EDHOsaowVzCAm1P4vKC0pVng0dUo0yMkuQNYECIp9NHWJiguUWAZnYeNO5wLpLQLqnajAlZObWKBQoaAC9D1EVKUoRiE6taIAyKqwV6mwqlaojYWJRGfmJRcpZMaqGtsrPZrSpGSlBDRDKZYrM01BEaonU9UyVqEa7EqgSXlwUSNzoJap8x9NaYChPdjZU1dTSc0iJSuVTBtzI5C9C0D@XgUn1uDlLgb7axaIuRxOrMTLnQsMBHig1tb@/w8A "Tcl – Try It Online")
[Answer]
# [SlimSharp](https://github.com/jcoehoorn/SlimSharp), 284 characters (bytes not counted)
```
S b(S x){S a="╔=╤=╤=╦=╤=╤=╦=╤=╤=╗\n║";for(I i=0,j=0,k,l,m;j<3;j++)for(k=0;k<3;k++){for(l=0;l<3;l++)for(m=0;m<3;)a+=" "+x[i++]+(m++<2?" │":" ║");a+=i<80?(k<2?"\n╟-┼-┼-╫-┼-┼-╫-┼-┼-╢\n║":"\n╠=╪=╪=╬=╪=╪=╬=╪=╪=╣\n║"):"\n╚=╧=╧=╩=╧=╧=╩=╧=╧=╝";}return a.R("=","═══").R("-","───").R("0"," ");}
```
This is a simple adaption of my C# answer.
]
|
[Question]
[
A hill number is a number that has **the same digit in the first & the last**, but that's not all. In a hill number the first digits are **strictly increasing** until the largest digit, and after the largest digit, the last digits are **strictly decreasing. The largest digit can be repeated but consecutively only**, meaning no gaps by smaller numbers.
Here is an example of a hill number:
```
12377731 | 1237... | ...731
^ same ^ | strictly increasing | strictly decreasing
---------+---------------------+---------------------
12377731
^^^ okay because largest digit can be repeated
```
This is **not**:
```
4588774 | ...8774
| ^^ not the largest digit
| so this has to be strictly decreasing
| but it's not, so not a hill number
```
### Challenge
Given a positive integer, write a full program or a function that returns truthy for hill numbers but falsy on other values.
**Notes:**
* Input & output can be in **any reasonable format**.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in each language wins!
### Test Cases
```
12321 -> Truthy
1233321 -> Truthy
99 -> Truthy
3 -> Truthy
234567992 -> Truthy
5555555 -> Truthy
1232 -> Falsy
778896 -> Falsy
23232 -> Falsy
45566554 -> Falsy
5645 -> Falsy
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
_ƝṠÞ+SƊƑ
```
[Try it online!](https://tio.run/##y0rNyan8/z/@2NyHOxccnqcdfKzr2MT/h9sfNa0BIgX3//@jDY2MjQx1FICUMZhhaamjYKyjYGRsYmpmbmlpFKujAFajo2BubmFhaQaSAnNNTE3NzExNTXQUTM1MTGMB "Jelly – Try It Online")
### How it works
```
_ƝṠÞ+SƊƑ Main link. Argument: n (integer)
_Ɲ Take the differences of neighboring digits.
This maps n = abcd to [a-b, b-c, c-d].
Ƒ Fixed; apply the link to the left and return 1 if the result is equal to
its argument, 0 if not.
Ɗ Drei; combine the three links to the left into a monadic chain.
ṠÞ Sort the differences by their signs (negative, zero, positive).
S Take the sum of the differences, yielding 0 if and only if the
first digit is equal to the last.
+ Add the sum to each difference.
```
[Answer]
# JavaScript (ES6), ~~62~~ 54 bytes
Takes input as a string. Returns a Boolean value.
```
s=>s[-[...s].some(p=q=n=>q>(q=Math.sign(p-(p=n))))]==p
```
[Try it online!](https://tio.run/##fc69DoIwFIbh3atgowyU0NJChzK6ubkRBoL8GWwLRROvvoJRNCHlW8@TN@daPApdjp2afCEvlam50TzVmZ9BCHUOtbxVQPGBC54OKRj4qZhaqLtGAOXPB@HNyzlXppRCy76CvWxADdwQYRS6nucsCwLnPN6n9nnYKrw6q2LsG9pT@A/ZFcIRoTFjaNF7f6E1N6tj0esNiuMkYfTDbGgO/VI2FBFCKSHR29kQoRHZ/GRe "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // s = input string
s[ // we will eventually access either s[0] or s[-1]
-[...s].some( // depending on the result of this some()
p = q = // initialize p and q to non-numeric values
n => // for each digit n:
q > ( // compare q with
q = // the new value of q,
Math.sign( // defined as the sign of
p - (p = n) // the difference between the current digit and the previous one
)) // yield true if the previous q is greater than the new q
) // s[-1] being undefined, a truhty some() will force the test to fail
] == p // otherwise: test if the 1st digit s[0] is equal to the last digit p
```
---
# JavaScript (ES6), 65 bytes
A solution using a regular expression. Takes input as a string. Returns \$0\$ or \$1\$.
```
s=>/N(,-\d+)*(,0)*[^0-]*$/.test([...s].map(p=v=>p-(p=v)))&p==s[0]
```
[Try it online!](https://tio.run/##fc67DoIwGIbh3atgMNIiFCi02KGOjk5uiEnDwUNQGoskXj2CUTQh5V/@5cmb7yIaodL7WdbOrcrytuCt4mt3C2xnny2hBWwPWvHBcxJr7qI6VzWIEUIqQVchgeQNX0un/xDCheRcxV7SptVNVWWOyuoICmD6OMC@CaHRn@sau/ujPj1nYxUMTqsY@4amVPCH9AoHIaERY7jXU7vwkOvURpRqhKJotWL0w3SoC/1SOhQSQikh4dvpEKEhGW1qXw "JavaScript (Node.js) – Try It Online")
### How?
We first convert the number to a list of pairwise digit differences in \$[-9,9]\$:
```
[...s].map(p = v => p - (p = v))
```
*Example:*
```
"234567992" --> [ NaN, -1, -1, -1, -1, -1, -2, 0, 7 ]
```
This array is coerced to a string, which gives:
```
"NaN,-1,-1,-1,-1,-1,-2,0,7"
```
We apply the following regular expression:
```
+-----------------------> the second 'N' of 'NaN'
| +------------------> a sequence of negative numbers
| | +------------> a sequence of zeros
| | | +------> a sequence of positive numbers
| | | | +---> end of string
| | | | |
|/¨¨¨¨¨¨\/¨¨¨\/¨¨¨¨\|
/N(,-\d+)*(,0)*[^0-]*$/
```
Finally, we also test if the last digit `p` is equal to the first digit `s[0]`.
[Answer]
# Pyth, 16 bytes
```
&SI_._MJ.+jQT!sJ
```
[Try the test suite](http://pyth.herokuapp.com/?code=%26SI_._MJ.%2BjQT%21sJ&input=12377731&test_suite=1&test_suite_input=12321%0A1233321%0A99%0A3%0A234567992%0A1232%0A778896%0A23232%0A45566554%0A5645&debug=0).
```
jQT input in base 10
J.+ J = differences: [3,1,4,1] -> [-2,3,-3]
._M Signs of each element of J
_ Reverse the list
SI and check if it is Invariant under Sorting.
If this is true, J consists of some positive numbers,
followed by some 0s, followed by some negative numbers,
which is what we want.
!sJ Now we check the other hill condition by ensuring
sum(differences) = 0; i.e. the first and last digit are equal.
& We take the logical AND of both conditions.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
DIµṠNṢƑaS¬$
```
Explanation:
```
D Convert to a list of Digits.
I Increments; compute differences between successive elements.
µ Start new µonadic link.
Ṡ Find Ṡign of each increment
N then negate;
ṢƑ is the result invariant under Ṣorting?
If so, the increments consist of some positive numbers,
followed by some 0s, followed by some negative numbers,
which is what we want.
a Logical AND this result with
S¬$ logical NOT of the Sum of the increments.
If the sum of the increments is zero, first and last digits are equal.
```
[Try it online!](https://tio.run/##ASQA2/9qZWxsef//REnCteG5oE7huaLGkWFTwqwk////MTIzNzc3MzI "Jelly – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 39 bytes
```
{.[0]==.tail&&[<=] $_ Z<=>.skip}o*.comb
```
[Try it online!](https://tio.run/##VczBCoJAFAXQdfMVbxGiYUOOzuiQ47IvaJVIWClJmuIoIea32xCRunvnXu6rkjpnY9GBloIYexzuIiFwE2e5poW@iGB9hpMvAiwfWTWUG3wti8u4R2lZg55nz0Qa0KNV1Tagpzp@lfVNqh@GCe8fiKmIhtEiNrFgG8Cxbpt7h5TtZcL5DPbsJrZDmcs5Wc6/PMS57JDreh5nk1U5rx1KGaPUmRLKHPrXBw "Perl 6 – Try It Online")
### Explanation
```
{ ... }o.comb # Split into digits and feed into block
.[0]==.tail # First element equals last
&& # and
$_ Z<=>.skip # Pairwise application of three-way comparator
[<=] # Results never decrease
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~114~~ 112 bytes
```
lambda n:all((n[0]==n[-1])*sorted(set(x))==list(x)[::d]for x,d in zip(n.split(max(n)*n.count(max(n)),1),[1,-1]))
```
[Try it online!](https://tio.run/##fc2xDoIwFAXQ3a9o4mBr0NhCiyWpo1/ghgxVIDSpD0Jrgv486qDBoWzv5uTe1z180wIba3Uerb5dSo0g09ZiDPmuUAryDS3I2rW9r0rsKo8HQpSyxn2uPMvKom57NEQlMoCepsOwdZ01Ht/0gIGsYXtt7/CNJKIkymn0GSVj1xvwqMYrymJGVwQt0eaATv3dN4/FFOMZljIkcQhYnHCRSslmXv7sqK2bUJru91IE8F0LFhPOheA8CTAXCf@j8QU "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 65 bytes
Takes strings. Took the idea for checking sort invariance from the Pyth answer.
```
function(a)!sum(d<-diff(utf8ToInt(a)))&all(sort(k<-sign(d),T)==k)
```
[Try it online!](https://tio.run/##bc7LCoMwEAXQfb/CWigz0CzMSwPaZaF7f0AqaUWNYJJFvz6VvhbGWZ57ucwcdFKSoL25uW4y0ODe@hHakrSd1uCdLurpatwSIB6bYQA7zQ76ktjubqDFU41V1WPQkGaU0SzFQ0LOST1793juPsq2XKmIWCSUcSFzpejW7A8vzWDfludFoeRal2Jc5UJIKQRfu5BcRAPfW/z/QngB "R – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ ~~17~~ ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¥D.±Â{RQsO_*
```
-5 bytes by creating a port of [*@lirtosiast*'s Pyth answer](https://codegolf.stackexchange.com/a/176228/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//0FIXvUMbDzdVBwUW@8dr/f9vYmphYW5uAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/0NLXfQObTzcVB0UWOwfr/Vf57@hkbG5ubmxIReQYQQmjUG0pSWXMZeRsYmpmbmlpRGXiamFhbm5CVgRl7m5hYWlGVAWxDExNTUzMzU14TI1MzEFAA).
**Explanation:**
```
¥ # Push the deltas of the digits of the (implicit) input
# i.e. 4588774 → [1,3,0,-1,0,-3]
D # Duplicate this list
.± # Get the sign of each
# [1,3,0,-1,0,-3] → [1,1,0,-1,0,-1]
 # Bifurcate (short for DR: Duplicate and Reverse copy)
# i.e. [1,1,0,-1,0,-1] → [-1,0,-1,0,1,1]
{ # Sort the copy
# i.e. [-1,0,-1,0,1,1] → [-1,-1,0,0,1,1]
R # Reverse it
# i.e. [1,1,0,0,-1,-1]
Q # And check if they are equal
# i.e. [1,1,0,-1,0,-1] and [1,1,0,0,-1,-1] → 0 (falsey)
s # Swap to get the list of deltas again
O # Take the sum
# i.e. [1,3,0,-1,0,-3] → 0
_ # And check if it's exactly 0
# 0 → 1 (truthy)
* # Check if both are truthy (and output implicitly)
# i.e. 0 and 1 → 0 (falsey)
```
`Â{RQ` can alternatively be `(Â{Q` for the same byte-count, where `(` negates each sign: [Try it online](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/0NLXfQObdQ43FQdWOwfr/Vf57@hkbG5ubmxIReQYQQmjUG0pSWXMZeRsYmpmbmlpRGXiamFhbm5CVgRl7m5hYWlGVAWxDExNTUzMzU14TI1MzEFAA).
[Answer]
# J, 23 bytes
```
[:((0=+/)**-:*/:*)2-/\]
```
Idea stolen from the Jelly answers. Just wanted to see how short I could make it in J.
[Try it online!](https://tio.run/##bU67DsIwDNzzFSeWNoE0aVIKjZQJiYmJFZgqKsTC/0/BLgwJRSfb8t358UyrppoQAypsYBEodIPD@XRMl1DXNq6NVEoHZYKSTpvrLUkh7uPjhRYRE2UHj90Mj3YpOapL1v9RBkLe@6LjqQ5b9HSIne77hi1u5Ry/tCcMNJPzH@evm3fz9n6uXaExz7qASG8 "J – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 53 bytes
```
def f(s):x=map(cmp,s,s[1:]);s[:sorted(x)==x]!=s[-1]>_
```
Takes input as a string. Output is via [presence or absence of an exception](https://codegolf.meta.stackexchange.com/a/11908/12012 "Functions may return a boolean value via the presence or absence of an error/exception").
[Try it online!](https://tio.run/##RY5Bi8IwEIXP9VfM3hKIh6ZNarJ0b3r05K0UKZqiYNswk4X662tSEU9vvjePN@Of4TaNclmuroeeEbdzPXSeXQYvSFCT25b/UmNpwuCubOZ1Pbc/NTXbvP07L/2EEBwFgvsILJeFzAVEKdbBGAGFAFmUSlfGSC7eGQFVtdsZnVYrlkpprVQpQOlScbvJPsWpdz0QvSzgM0kW/wzIks15Yo/3McAJ/10kN1@cD3DsBrdHnNB@E4fuQTGywvIC "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 62 bytes
```
lambda s:s[:eval('<='.join(map(str,map(cmp,s,s[1:]))))]==s[-1]
```
Takes input as a string and returns a Boolean.
[Try it online!](https://tio.run/##NY7RDoIwDEWf5Sv6xpZUkw022CJfgjygQsTAWOhi4tcjg9iX23va3NZ/w2t2cu2hgts6ttP92QJZqm33aUeWXqv08p4Hx6bWMwoLRn1MHgmpFrbhWzVVRfVZNGs/LxA6CgSDAyZkJgXCJtneGIOQIcgsV7owRnI8dhCKoiyNjqPd5kpprVSOoHSuuE1O/@CYux/Y2MkvgwvQx69YhJwnB1t/ "Python 2 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
dZSd1<AGds~*
```
[Try it online!](https://tio.run/##y00syfmf8D8lKjjF0MbRPaW4Tuu/S1RFyH91QyNjI0N1LhBtDGFZWgIJYyA2MjYxNTO3tDSCSIMoc3MLC0szdQWQJETExNTUzMzU1ATINDUzMQVpgwJ1AA "MATL – Try It Online")
### Explanation
Input is a string of digits. Output is a `1` or `0`. The number `222222` is a hill number according to this program. Saved 2 bytes by copying Dennis' method for checking equality of the first and last digits.
```
d % Takes the difference between digits
ZS % Calculate the sign.
d % Take the difference again.
1< % A number is a hill number if these differences are < 1.
A % Truthy iff above is all true OR if array is empty (necessary for short inputs)
Gds % Push the input, and sum all the differences.
~ % Negate
* % Multiply the two tests (=logical AND).
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 47 bytes
```
->n{(r=n.each_cons(2).map{|a,b|a<=>b})==r.sort}
```
[Try it online!](https://tio.run/##JYzRCoMgGEZfZZcJTkj9LSF7kYihzbYuZqJtNLJnd8VuvsM5F194m28eVb62biuCcsTq4XkbZhcLishL@y1pbJJuVGt2pFQgcQ7LnruSMlriY9lJKTHDlHEQlZT0zBRXVV1LcdRTOIAQAByD4ND/j9fkL2Pni5Xcp8e0RBLsx4ZoUb/nHw "Ruby – Try It Online")
Input as array of digits, output is boolean.
[Answer]
# Mathematica/Wolfram Language, 69 64 bytes
Pure function. Takes input as an integer, returns `True` or `False`.
```
Sort[x=Sign@-Differences[y=IntegerDigits@#]]==x&&y[[1]]==Last@y&
```
### Explanation:
The first clause checks the "hilliness":
* `IntegerDigits`: Get digits from integer. Store in `y`.
* `-Differences`: Take successive differences and flip signs.
* `Sign`: Replace each entry with +1 if positive, 0 if zero, and -1 if negative. Store in `x`.
* `Sort`: Sort list of +1, 0, -1 from smallest to largest. Compare to original list in `x`.
The second clause checks whether the first and last digits are equal.
A tip of the hat to @IanMiller for tips on refining this code.
[Answer]
# Japt, 11 bytes
Takes input as a digit array.
```
ä-
eUñg)«Ux
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=5C0KZVXxZymrVXg=&input=WzEsMiwzLDIsMV0=) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=5C0KZVXxZymrVXg=&input=WwpbMSwyLDMsMiwxXQpbMSwyLDMsMywzLDIsMV0KWzksOV0KWzNdClsyLDMsNCw1LDYsNyw5LDksMl0KWzEsMiwzLDJdCls3LDcsOCw4LDksNl0KWzIsMywyLDMsMl0KWzQsNSw1LDYsNiw1LDUsNF0KWzUsNiw0LDVdCl0KLW1S)
```
:Implicit input of digit array U
ä- :Deltas
\n :Reassign to U
Uñ :Sort U
g : By signs
e ) :Check for equality with U
« :Logical AND with the negation of
Ux :U reduced by addition
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 115 bytes
```
s=>!s.Where((c,i)=>i<1?c!=s[^1]:i>s.LastIndexOf(s.Max())?c>=s[i-1]:i>s.IndexOf(s.Max())?s.Max()!=c:c<=s[i-1]).Any()
```
[Try it online!](https://tio.run/##fc7NCoJAFAXgfU@hrmYgDX9mbMoZaSMERS2CFlFgk@aAKHgN8unNhUQR0@7Cdw7nSrAlqD55VDKCtlHVfXqt61IYucF74MIE51hkTYaQnCrMhYrcWJocThf3vFACnE0K7bq6Zc9djsDZpk@EcSzFkFD2GPnh8TC5XMhoTGJnVXUI98vJZD@80aIcWa7ne66F8dKYzYxD82iL7gv9P8yYTnwdeH5AaMiY92fybUlawgeF4XzOqAaHmrYYEEIpIYGGCQ3IF/Uv "C# (Visual C# Interactive Compiler) – Try It Online")
Here is an overview of how this works...
1. Input is in the form of a `string`
2. Find the largest digit
3. Ensure the first and last digits are the same
4. Ensure digits after the last occurrence of the largest digit are decreasing
5. Ensure digits between the first and last occurrence of the largest digit are equal to the largest digit
6. Ensure digits before the first occurrence of the largest digit are increasing
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 22 bytes
```
XXJl_-]==j2COqcm^mso&&
```
[Try it online!](https://tio.run/##SyotykktLixN/f8/IsIrJ1431tY2y8jZvzA5Ny63OF9N7f9/QyNjIDAyBAA "Burlesque – Try It Online")
```
XX # Explode into digits
J # Duplicate
l_-] # Head & Tail
== # Are equal
j # Reorder stack
2CO # 2-grams
qcm^m # Compare with UFO operator
so # If sorted
&& # If going up then down AND head-tail is equal
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 52 bytes
```
.
$*1;$&$*1,
(1+),\1
,
^(1+);(,1+;)*(,;)*(1+,;)*\1,$
```
[Try it online!](https://tio.run/##FYgxDoMwDEV3nyNFgVhIdmIHKwfgEgjB0KFLh6r3D/Hy3v/v9/5/vnd/xf3qK4SFWpgGESKlGQ8ChNNni0ipzUtEByXXQRh6J85MMJjdZpCBcxGtZuyZodZtMx3VTxFRFSkgWuQB "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.
$*1;$&$*1,
```
Convert each digit to unary twice, separated by `;`s and terminated by `,`s. However, you can then think of the result as the first digit, a `;`, then all the pairs of adjacent digits, the digits of each pair separated by `,` and the pairs separated by `;`s, then another `;`, then the last digit, then a final `,`.
```
(1+),\1
,
```
Subtract the pairs of adjacent digits. This leaves `;,;` for equal digits and `1`s on the greater side for unequal digits. (This could be done as part of the following regex but obviously that wouldn't be so golfy.)
```
^(1+);(,1+;)*(,;)*(1+,;)*\1,$
```
Match the first digit, then any number of pairs of ascending digits, then any number of pairs of equal digits, then any number of pairs of descending digits, then match the first digit again at the very end.
[Answer]
# [Red](http://www.red-lang.org), 181 bytes
```
func[n][m: last sort copy t: s: form n
parse t[opt[copy a to m(a: sort unique a)]copy b thru any m
opt[copy c to end(c: sort/reverse unique c)]](s = rejoin[a b c])and(s/1 = last s)]
```
[Try it online!](https://tio.run/##TY7LDoMgEEX3fsVd6qrxgQpJf6JbwoIipjYVLGCTfr21tVF2986ZMxmnu@WiOy6Sni39bBQ3go8MD@kDvHUByk5vBAbP0Fs3wiSTdF4jcDsF/qMSwWJMJduM2QzPWUNm4kevCDc3Q5o3xmR31NfRpkvVZp2cfunv3b@tMiFSjzOcvtvBcLneUSKTq@FP@TrfPszEMrnBBPTIi7LIk6iVcad0j@WeirIidUNpEWtHaZq2pXW0HcOKkPpgpK7I8gE "Red – Try It Online")
## More readable:
```
f: func[n][
t: s: form n
m: last sort copy t
parse t [ opt [ copy a to m (a: sort unique a) ]
copy b thru any m
opt [ copy c to end (c: sort/reverse unique c) ]
]
(s = rejoin [ a b c ]) and (s/1 = last s)
]
```
[Answer]
# Powershell, 77 bytes
```
($x=-join("$($args|%{"-$_;$_"})"|iex))-match'^(-\d)+0*\d+$'-and$x[1]-eq$x[-1]
```
Less golfed test script:
```
$f = {
# $args = 1,2,3,3,3,2,1
$a=$args|%{"-$_;$_"} # "-1;1","-2;2","-3;3","-3;3","-3;3","-2;2","-1;1"
$d="$a" # "-1;1 -2;2 -3;3 -3;3 -3;3 -2;2 -1;1"
$x=-join($d|Invoke-Expression) # "-1-1-100111"
$x-match'^(-\d)+0*\d+$'-and$x[1]-eq$x[-1] # $true or $false
}
@(
,($True , 1,2,3,2,1 )
,($True , 1,2,3,3,3,2,1 )
,($True , 9,9 )
,($True , 3 )
,($True , 2,3,4,5,6,7,9,9,2 )
,($False, 1,2,3,2 )
,($False, 7,7,8,8,9,6 )
,($False, 2,3,2,3,2 )
,($False, 4,5,5,6,6,5,5,4 )
,($False, 5,6,4,5 )
) | % {
$expected,$a = $_
$result = &$f @a
"$($result-eq$expected): $result"
}
```
Output:
```
True: True
True: True
True: True
True: True
True: True
True: False
True: False
True: False
True: False
True: False
```
[Answer]
# [Python 3](https://docs.python.org/3/), 114 bytes
```
def f(r):
l=[*r]
for i in-1,0:
while 1<len(l)and l[i]<l[(1,-2)[i]]:l.pop(i)
return 2>len({*l})and r[0]==r[-1]
```
[Try it online!](https://tio.run/##ZZDRaoMwFIbvfYpDQUhKLE00WqXZ5Z5gd@KFq5EGQgxJyjbGnt2lsgm2d/m/fP@Bc@xXuE4mn@dBjjAih5sEtGj3rktgnBwoUCaj5BgxfFyVlkDPWhqkcW8G0K3qzrpFlGQMx3fX6IOdLFI4ASfDzRlgL3f9e69/loZrj50Qrs1oNwfpw6X30oMAFOcDIMpyRgm8uZvEZEX5E6zrbc63keUFL6u6Zk@jInnttV9RVZ1OdfkAo/YkFpyXJefFA@Zlwck/wUmy3MxYAvLTykuQQ0ywLtosJeuUCWiX@gZSv4MU0KaB8WK55S4j8sHd//9o7710Ad6nSaNoYBBiLc6/ "Python 3 – Try It Online")
Way longer than some Python 2 solutions, but this one is def-based and I like it.
]
|
[Question]
[
Given a list of indices and zero or more lists of integers, output the lists of integers, sorted in ascending order, with the key priority from the first input.
## Example
Let the keys input be `[1, 0, 2]`, and the lists input be `[[5, 3, 4], [6, 2, 1], [5, 2, 1]]`. Those lists need to be sorted by their second element, then first element, then third element, in ascending order:
1. First, we sort by the values at index `1`: `[[6, 2, 1], [5, 2, 1], [5, 3, 4]]`
2. Next, we break any ties from the first sort using the values at index `0`: `[[5, 2, 1], [6, 2, 1], [5, 3, 4]]`
3. Finally, we break any remaining ties with the vlues at index `2` (this doesn't actually change anything, because there are no ties remaining).
## Details
* Sorting is stable: if two elements compare equal with respect to the given sort keys, they must remain in the same relative order in the output. For example, if `A` and `B` are equal under the given sort keys, and the input was `[..., A, ..., B, ...]`, `A` must be placed before `B` in the output.
* A sort key will never reference a non-existant element in one of the input lists.
* No sort key will be repeated. Thus, `[1, 2, 1]` is not a valid list of sort keys.
* Any elements not referenced by the sort keys do not factor into the sorting order. Only the initial relative order and the values of the elements referenced by the sort keys determine the output order.
* You may choose whether the sort keys are zero-indexed or one-indexed.
* There will be no negative values in the sort keys. If you choose to use one-indexing, there will be no zeroes in the sort keys either.
* Integer values will not exceed your language's natively-representable range. If your chosen language is natively capable of arbitrary-precision integers (like Python), then any integer value can be present in the input, subject to memory constraints.
## Reference Implementation (Python 2)
```
#!/usr/bin/env python
keys = input()
lists = input()
print sorted(lists, key=lambda l:[l[x] for x in keys])
```
[Try it online](http://ideone.com/fork/xfxYbP)
## Test Cases
Format: `keys lists -> output`. All sort keys are zero-indexed.
```
[1, 0, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[5, 2, 1], [6, 2, 1], [5, 3, 4]]
[1, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[6, 2, 1], [5, 2, 1], [5, 3, 4]]
[0, 1] [[1, 2], [2, 1]] -> [[1, 2], [2, 1]]
[1, 0] [[1, 2], [2, 1]] -> [[2, 1], [1, 2]]
[0] [[4], [10, 11, -88], [-2, 7]] -> [[-2, 7], [4], [10, 11, -88]]
[2] [[-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6]] -> [[-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2]]
[2, 1] [[9, 2, -2, -10, -6], [3, -4, -2]] -> [[3, -4, -2], [9, 2, -2, -10, -6]]
[2, 4, 8] [[5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5], [-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3]] -> [[-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3], [5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5]]
[1, 2, 3, 4, 5] [[-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [5, 3, -6, -5, -4, -4, -8, 2], [9, -4, 1, -1, -3, -2], [-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [1, -5, -3, -10, -7, 9, -8, -5, -1], [-9, 4, -1, -1, 2, 4]] -> [[-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -5, -3, -10, -7, 9, -8, -5, -1], [9, -4, 1, -1, -3, -2], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [5, 3, -6, -5, -4, -4, -8, 2], [-9, 4, -1, -1, 2, 4]]
[8, 7, 3, 2, 4, 9, 1] [[8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9]] -> [[10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5]]
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 4 bytes
```
⁴ị$Þ
```
[Try it online!](http://jelly.tryitonline.net/#code=4oG04buLJMOe&input=&args=W1s4LCAtNSwgMSwgLTYsIC0xLCAtNCwgNiwgMTAsIDEwLCA2LCA5LCA1XSwgWzQsIC04LCA2LCAtMTAsIC0yLCAtMywgMiwgLTYsIDksIDUsIDQsIDEwLCAyLCAzXSwgWzEwLCAtMSwgMywgMCwgLTQsIDEsIC01LCAtNCwgLTEsIC03LCA5LCAtOSwgLTEsIC01LCA3LCA4LCA5LCA2LCAtM10sIFswLCAtOSwgLTcsIC0yLCAyLCAtNSwgNywgNCwgNiwgLTQsIDEsIDgsIC03LCAxMF0sIFs1LCA2LCAtOSwgMCwgLTEsIDUsIDQsIDcsIDUsIDEwLCAyLCA1LCA3LCAtOV1d+WzksIDgsIDQsIDMsIDUsIDEwLCAyXQ)
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), 13 bytes
```
{W%{{X=}$}fX}
```
An unnamed block which expects the list of lists and the list of priorities on top of the stack and replaces them with the sorted list of lists.
[Try it online!](http://cjam.tryitonline.net/#code=cU4ve35cCgp7VyV7e1g9fSR9Zlh9Cgp-cH0v&input=WzEgMCAyXSBbWzUgMyA0XSBbNiAyIDFdIFs1IDIgMV1dClsxIDJdIFtbNSAzIDRdIFs2IDIgMV0gWzUgMiAxXV0KWzBdIFtbNF0gWzEwIDExIC04OF0gWy0yIDddXQpbMCAxXSBbWzEgMl0gWzIgMV1dClsxIDBdIFtbMSAyXSBbMiAxXV0gClsyXSBbWy0xIC01IDggLTEgLTQgLTEwIC01IDQgNCA2IC04IDQgMl0gWy03IDYgMiAtOCAtNyA3IC0zIDMgMCAtNiAxXSBbLTkgOCAtNSAtMSAtNyAtOCAtNSAtNiA1IC02IDZdXQpbMiAxXSBbWzkgMiAtMiAtMTAgLTZdIFszIC00IC0yXV0KWzIgNCA4XSBbWzUgLTMgNCAtNiAtMSAtMiAtMiAtNCA1XSBbLTIgLTMgNiAtNCAtMSAtNCAtNCAtNSA4IDkgOSAtMyAzIC05IC0zXSBbMiAwIDEwIC0xMCAtMSAyIC0xIDUgLTEgMTAgLTVdIFstNyAtOCAtNiA3IDMgOCA2IC03IC0yIDAgLTYgLTQgNCAtMyAyIC0zXV0KWzEgMiAzIDQgNV0gW1stNyAzIC04IDMgNSAtMSA2IC02IDkgOF0gWy05IC0xIC03IC05IC0xMCAtMiAtOCAtMTAgLTEwIC0zXSBbNSAzIC02IC01IC00IC00IC04IDJdIFs5IC00IDEgLTEgLTMgLTJdIFstNiAtMTAgNCAtMTAgNiA2IC0xIDMgMCAwXSBbMSAtMiAtNyAtNiAtNyAtNyAtMSAwIC00IDMgM10gWzcgLTEgLTcgMiAtMiA5IDcgNSAtNiAtOF0gWzEgLTUgLTMgLTEwIC03IDkgLTggLTUgLTFdIFstOSA0IC0xIC0xIDIgNF1dCls4IDcgMyAyIDQgOSAxXSBbWzggLTUgMSAtNiAtMSAtNCA2IDEwIDEwIDYgOSA1XSBbNCAtOCA2IC0xMCAtMiAtMyAyIC02IDkgNSA0IDEwIDIgM10gWzEwIC0xIDMgMCAtNCAxIC01IC00IC0xIC03IDkgLTkgLTEgLTUgNyA4IDkgNiAtM10gWzAgLTkgLTcgLTIgMiAtNSA3IDQgNiAtNCAxIDggLTcgMTBdIFs1IDYgLTkgMCAtMSA1IDQgNyA1IDEwIDIgNSA3IC05XV0) (As a test suite.)
### Explanation
Sorting with tie breakers can be implemented by repeatedly sorting the entire list stably going from the lowest-priority key to the highest-priority key.
```
W% e# Reverse priority list.
{ e# For each priority X...
{ e# Sort the lists by the result of this block...
X= e# Extract the Xth element from the current list.
}$
}fX
```
[Answer]
# Ruby, 35 bytes
```
->k,a{a.sort_by{|e|e.values_at *k}}
```
See it on eval.in: <https://eval.in/652574>
[Answer]
## Haskell, 38 bytes
```
import Data.List
sortOn.flip(map.(!!))
```
Usage example: `( sortOn.flip(map.(!!)) ) [2,1] [[9,2,-2,-10,-6], [3,-4,-2]]` -> `[[3,-4,-2],[9,2,-2,-10,-6]]`.
Non-pointfree: `f k v=sortOn(\x->map(\y->x!!y)k)v`.
[Answer]
## Mathematica, ~~22~~ 19 bytes
```
SortBy[Extract/@#]&
```
Uses 1-based indices. This unnamed function is [curried](https://codegolf.meta.stackexchange.com/a/8427/8478), so the calling convention is:
```
SortBy[Extract/@#]&[{2, 1, 3}][{{5, 3, 4}, {6, 2, 1}, {5, 2, 1}}]
```
Mathematica's `SortBy` can take a list of functions in which case the individual functions are used as successive tie-breakers, so that's just what we want. All we need to do is create a list of functions which return the corresponding list element. This can be done with `Extract`. `Extract` is normally a binary function `Extract[list, index]` which returns a list element. However if used unarily, then `Extract[index]` returns a function which retrieves the element at `index` from a list passed to it. In other words, the `index` parameter of `Extract` can be curried. We make use of this by mapping `Extract` over the list of indices we're given, which creates the list of functions we need.
[Answer]
## Python, 50 bytes
```
lambda l,k:sorted(l,key=lambda x:[x[y]for y in k])
```
This is a trivially-golfed version of the reference implementation. `l` is the lists parameter, and `k` is the sort keys parameter. `l` can be any iterable, so long as its elements are subscriptable by integers (like lists, tuples, or int-keyed dicts). `k` can be any iterable.
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 29 bytes
```
tT,?hg:Tz:{:2f}o:ta
heI,?t:Im
```
[Try it online!](http://brachylog.tryitonline.net/#code=dFQsP2hnOlR6Ons6MmZ9bzp0YQpoZUksP3Q6SW0&input=W1s4Ojc6MzoyOjQ6OToxXTpbWzg6XzU6MTpfNjpfMTpfNDo2OjEwOjEwOjY6OTo1XTpbNDpfODo2Ol8xMDpfMjpfMzoyOl82Ojk6NTo0OjEwOjI6M106WzEwOl8xOjM6MDpfNDoxOl81Ol80Ol8xOl83Ojk6Xzk6XzE6XzU6Nzo4Ojk6NjpfM106WzA6Xzk6Xzc6XzI6MjpfNTo3OjQ6NjpfNDoxOjg6Xzc6MTBdOls1OjY6Xzk6MDpfMTo1OjQ6Nzo1OjEwOjI6NTo3Ol85XV1d&args=Wg)
### Explanation
We use the fact that `o - Order` can be used with an additionnal predicate as input: we order the lists by using for each `[Keys, a list]` the list of the elements of `a list` which are at index `a key` in the order that they appear in `Keys`.
```
Input = [Keys, List of lists]
tT, Call the Keys T
?hg:T Create the list [[T], List of lists]
z Zip [T] with the list of lists
:{ }o Order by the output of this predicate
:ta Keep only the last element of each sublist in the Output
:2f Find all outputs of the predicate below
heI, Take a key I
?t:Im Output is the Ith element of the sublist
```
[Answer]
## CJam (12 bytes)
```
{{1$\f=}$\;}
```
[Online demo](http://cjam.aditsu.net/#code=qN%2F%7B~%0A%0A%7B%7B1%24%5Cf%3D%7D%24%5C%3B%7D%0A%0A~p%7D%2F&input=%5B1%200%202%5D%20%5B%5B5%203%204%5D%20%5B6%202%201%5D%20%5B5%202%201%5D%5D%0A%5B1%202%5D%20%5B%5B5%203%204%5D%20%5B6%202%201%5D%20%5B5%202%201%5D%5D%0A%5B0%201%5D%20%5B%5B1%202%5D%20%5B2%201%5D%5D%0A%5B1%200%5D%20%5B%5B1%202%5D%20%5B2%201%5D%5D%0A%5B0%5D%20%5B%5B4%5D%20%5B10%2011%20-88%5D%20%5B-2%207%5D%5D%0A%5B2%5D%20%5B%5B-1%20-5%208%20-1%20-4%20-10%20-5%204%204%206%20-8%204%202%5D%20%5B-7%206%202%20-8%20-7%207%20-3%203%200%20-6%201%5D%20%5B-9%208%20-5%20-1%20-7%20-8%20-5%20-6%205%20-6%206%5D%5D%0A%5B2%201%5D%20%5B%5B9%202%20-2%20-10%20-6%5D%20%5B3%20-4%20-2%5D%5D%0A%5B2%204%208%5D%20%5B%5B5%20-3%204%20-6%20-1%20-2%20-2%20-4%205%5D%20%5B-2%20-3%206%20-4%20-1%20-4%20-4%20-5%208%209%209%20-3%203%20-9%20-3%5D%20%5B2%200%2010%20-10%20-1%202%20-1%205%20-1%2010%20-5%5D%20%5B-7%20-8%20-6%207%203%208%206%20-7%20-2%200%20-6%20-4%204%20-3%202%20-3%5D%5D%0A%5B1%202%203%204%205%5D%20%5B%5B-7%203%20-8%203%205%20-1%206%20-6%209%208%5D%20%5B-9%20-1%20-7%20-9%20-10%20-2%20-8%20-10%20-10%20-3%5D%20%5B5%203%20-6%20-5%20-4%20-4%20-8%202%5D%20%5B9%20-4%201%20-1%20-3%20-2%5D%20%5B-6%20-10%204%20-10%206%206%20-1%203%200%200%5D%20%5B1%20-2%20-7%20-6%20-7%20-7%20-1%200%20-4%203%203%5D%20%5B7%20-1%20-7%202%20-2%209%207%205%20-6%20-8%5D%20%5B1%20-5%20-3%20-10%20-7%209%20-8%20-5%20-1%5D%20%5B-9%204%20-1%20-1%202%204%5D%5D%0A%5B8%207%203%202%204%209%201%5D%20%5B%5B8%20-5%201%20-6%20-1%20-4%206%2010%2010%206%209%205%5D%20%5B4%20-8%206%20-10%20-2%20-3%202%20-6%209%205%204%2010%202%203%5D%20%5B10%20-1%203%200%20-4%201%20-5%20-4%20-1%20-7%209%20-9%20-1%20-5%207%208%209%206%20-3%5D%20%5B0%20-9%20-7%20-2%202%20-5%207%204%206%20-4%201%208%20-7%2010%5D%20%5B5%206%20-9%200%20-1%205%204%207%205%2010%202%205%207%20-9%5D%5D). This is an anonymous block (function) which takes the arguments in the order given for the test cases and leaves the sorted value on the stack. It relies on the built-in sort `$` being stable, but the official interpreter guarantees that.
### Dissection
```
{ e# Define a block. Stack: orders values-to-sort
{ e# Sort by...
1$\f= e# Copy orders from the stack, and map array lookup
}$
\; e# Pop the orders to leave just sorted-values
}
```
[Answer]
# J, 6 bytes
```
]/:{&>
```
Keys are zero-indexed. The LHS is the list of keys and the RHS is an array of values. Since J doesn't support ragged arrays, each array must be boxed.
## Usage
```
f =: ]/:{&>
< 1 0 2
┌─────┐
│1 0 2│
└─────┘
5 3 4 ; 6 2 1 ; 5 2 1
┌─────┬─────┬─────┐
│5 3 4│6 2 1│5 2 1│
└─────┴─────┴─────┘
(< 1 0 2) f 5 3 4 ; 6 2 1 ; 5 2 1
┌─────┬─────┬─────┐
│5 2 1│6 2 1│5 3 4│
└─────┴─────┴─────┘
(< 1 2) f 5 3 4 ; 6 2 1 ; 5 2 1
┌─────┬─────┬─────┐
│6 2 1│5 2 1│5 3 4│
└─────┴─────┴─────┘
(< 0) f 4 ; 10 11 _88 ; _2 7
┌────┬─┬─────────┐
│_2 7│4│10 11 _88│
└────┴─┴─────────┘
```
## Explanation
```
]/:{&> Input: keys (LHS), values (RHS)
{&> Select from values at each index in keys
] Get the values
/: Sort up the values using the ones selected with the keys
```
[Answer]
## JavaScript (ES6), 55 bytes
```
(k,l)=>k.reduceRight((l,i)=>l.sort((a,b)=>a[i]-b[i]),l)
```
The ECMAscript standard doesn't guarantee that the underlying sort is stable, so the following 68-byte code doesn't make that assumption:
```
(k,l)=>l.sort(g=(a,b,i=0)=>i<k.length?a[k[i]]-b[k[i]]||g(a,b,i+1):0)
```
[Answer]
# Pyth, ~~5~~ 4 bytes
```
@LDF
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%40LDF&input=%5B1%2C+0%2C+2%5D%2C+%5B%5B5%2C+3%2C+4%5D%2C+%5B6%2C+2%2C+1%5D%2C+%5B5%2C+2%2C+1%5D%5D&test_suite_input=%5B1%2C+0%2C+2%5D%2C+%5B%5B5%2C+3%2C+4%5D%2C+%5B6%2C+2%2C+1%5D%2C+%5B5%2C+2%2C+1%5D%5D%0A%5B1%2C+2%5D%2C+%5B%5B5%2C+3%2C+4%5D%2C+%5B6%2C+2%2C+1%5D%2C+%5B5%2C+2%2C+1%5D%5D%0A%5B0%2C+1%5D%2C+%5B%5B1%2C+2%5D%2C+%5B2%2C+1%5D%5D%0A%5B1%2C+0%5D%2C+%5B%5B1%2C+2%5D%2C+%5B2%2C+1%5D%5D%0A%5B0%5D%2C+%5B%5B4%5D%2C+%5B10%2C+11%2C+-88%5D%2C+%5B-2%2C+7%5D%5D%0A%5B2%5D%2C+%5B%5B-1%2C+-5%2C+8%2C+-1%2C+-4%2C+-10%2C+-5%2C+4%2C+4%2C+6%2C+-8%2C+4%2C+2%5D%2C+%5B-7%2C+6%2C+2%2C+-8%2C+-7%2C+7%2C+-3%2C+3%2C+0%2C+-6%2C+1%5D%2C+%5B-9%2C+8%2C+-5%2C+-1%2C+-7%2C+-8%2C+-5%2C+-6%2C+5%2C+-6%2C+6%5D%5D%0A%5B2%2C+1%5D%2C+%5B%5B9%2C+2%2C+-2%2C+-10%2C+-6%5D%2C+%5B3%2C+-4%2C+-2%5D%5D%0A%5B2%2C+4%2C+8%5D%2C+%5B%5B5%2C+-3%2C+4%2C+-6%2C+-1%2C+-2%2C+-2%2C+-4%2C+5%5D%2C+%5B-2%2C+-3%2C+6%2C+-4%2C+-1%2C+-4%2C+-4%2C+-5%2C+8%2C+9%2C+9%2C+-3%2C+3%2C+-9%2C+-3%5D%2C+%5B2%2C+0%2C+10%2C+-10%2C+-1%2C+2%2C+-1%2C+5%2C+-1%2C+10%2C+-5%5D%2C+%5B-7%2C+-8%2C+-6%2C+7%2C+3%2C+8%2C+6%2C+-7%2C+-2%2C+0%2C+-6%2C+-4%2C+4%2C+-3%2C+2%2C+-3%5D%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%5D%2C+%5B%5B-7%2C+3%2C+-8%2C+3%2C+5%2C+-1%2C+6%2C+-6%2C+9%2C+8%5D%2C+%5B-9%2C+-1%2C+-7%2C+-9%2C+-10%2C+-2%2C+-8%2C+-10%2C+-10%2C+-3%5D%2C+%5B5%2C+3%2C+-6%2C+-5%2C+-4%2C+-4%2C+-8%2C+2%5D%2C+%5B9%2C+-4%2C+1%2C+-1%2C+-3%2C+-2%5D%2C+%5B-6%2C+-10%2C+4%2C+-10%2C+6%2C+6%2C+-1%2C+3%2C+0%2C+0%5D%2C+%5B1%2C+-2%2C+-7%2C+-6%2C+-7%2C+-7%2C+-1%2C+0%2C+-4%2C+3%2C+3%5D%2C+%5B7%2C+-1%2C+-7%2C+2%2C+-2%2C+9%2C+7%2C+5%2C+-6%2C+-8%5D%2C+%5B1%2C+-5%2C+-3%2C+-10%2C+-7%2C+9%2C+-8%2C+-5%2C+-1%5D%2C+%5B-9%2C+4%2C+-1%2C+-1%2C+2%2C+4%5D%5D%0A%5B8%2C+7%2C+3%2C+2%2C+4%2C+9%2C+1%5D%2C+%5B%5B8%2C+-5%2C+1%2C+-6%2C+-1%2C+-4%2C+6%2C+10%2C+10%2C+6%2C+9%2C+5%5D%2C+%5B4%2C+-8%2C+6%2C+-10%2C+-2%2C+-3%2C+2%2C+-6%2C+9%2C+5%2C+4%2C+10%2C+2%2C+3%5D%2C+%5B10%2C+-1%2C+3%2C+0%2C+-4%2C+1%2C+-5%2C+-4%2C+-1%2C+-7%2C+9%2C+-9%2C+-1%2C+-5%2C+7%2C+8%2C+9%2C+6%2C+-3%5D%2C+%5B0%2C+-9%2C+-7%2C+-2%2C+2%2C+-5%2C+7%2C+4%2C+6%2C+-4%2C+1%2C+8%2C+-7%2C+10%5D%2C+%5B5%2C+6%2C+-9%2C+0%2C+-1%2C+5%2C+4%2C+7%2C+5%2C+10%2C+2%2C+5%2C+7%2C+-9%5D%5D&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=%40LDF&input=%5B1%2C+0%2C+2%5D%2C+%5B%5B5%2C+3%2C+4%5D%2C+%5B6%2C+2%2C+1%5D%2C+%5B5%2C+2%2C+1%5D%5D&test_suite=1&test_suite_input=%5B1%2C+0%2C+2%5D%2C+%5B%5B5%2C+3%2C+4%5D%2C+%5B6%2C+2%2C+1%5D%2C+%5B5%2C+2%2C+1%5D%5D%0A%5B1%2C+2%5D%2C+%5B%5B5%2C+3%2C+4%5D%2C+%5B6%2C+2%2C+1%5D%2C+%5B5%2C+2%2C+1%5D%5D%0A%5B0%2C+1%5D%2C+%5B%5B1%2C+2%5D%2C+%5B2%2C+1%5D%5D%0A%5B1%2C+0%5D%2C+%5B%5B1%2C+2%5D%2C+%5B2%2C+1%5D%5D%0A%5B0%5D%2C+%5B%5B4%5D%2C+%5B10%2C+11%2C+-88%5D%2C+%5B-2%2C+7%5D%5D%0A%5B2%5D%2C+%5B%5B-1%2C+-5%2C+8%2C+-1%2C+-4%2C+-10%2C+-5%2C+4%2C+4%2C+6%2C+-8%2C+4%2C+2%5D%2C+%5B-7%2C+6%2C+2%2C+-8%2C+-7%2C+7%2C+-3%2C+3%2C+0%2C+-6%2C+1%5D%2C+%5B-9%2C+8%2C+-5%2C+-1%2C+-7%2C+-8%2C+-5%2C+-6%2C+5%2C+-6%2C+6%5D%5D%0A%5B2%2C+1%5D%2C+%5B%5B9%2C+2%2C+-2%2C+-10%2C+-6%5D%2C+%5B3%2C+-4%2C+-2%5D%5D%0A%5B2%2C+4%2C+8%5D%2C+%5B%5B5%2C+-3%2C+4%2C+-6%2C+-1%2C+-2%2C+-2%2C+-4%2C+5%5D%2C+%5B-2%2C+-3%2C+6%2C+-4%2C+-1%2C+-4%2C+-4%2C+-5%2C+8%2C+9%2C+9%2C+-3%2C+3%2C+-9%2C+-3%5D%2C+%5B2%2C+0%2C+10%2C+-10%2C+-1%2C+2%2C+-1%2C+5%2C+-1%2C+10%2C+-5%5D%2C+%5B-7%2C+-8%2C+-6%2C+7%2C+3%2C+8%2C+6%2C+-7%2C+-2%2C+0%2C+-6%2C+-4%2C+4%2C+-3%2C+2%2C+-3%5D%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%5D%2C+%5B%5B-7%2C+3%2C+-8%2C+3%2C+5%2C+-1%2C+6%2C+-6%2C+9%2C+8%5D%2C+%5B-9%2C+-1%2C+-7%2C+-9%2C+-10%2C+-2%2C+-8%2C+-10%2C+-10%2C+-3%5D%2C+%5B5%2C+3%2C+-6%2C+-5%2C+-4%2C+-4%2C+-8%2C+2%5D%2C+%5B9%2C+-4%2C+1%2C+-1%2C+-3%2C+-2%5D%2C+%5B-6%2C+-10%2C+4%2C+-10%2C+6%2C+6%2C+-1%2C+3%2C+0%2C+0%5D%2C+%5B1%2C+-2%2C+-7%2C+-6%2C+-7%2C+-7%2C+-1%2C+0%2C+-4%2C+3%2C+3%5D%2C+%5B7%2C+-1%2C+-7%2C+2%2C+-2%2C+9%2C+7%2C+5%2C+-6%2C+-8%5D%2C+%5B1%2C+-5%2C+-3%2C+-10%2C+-7%2C+9%2C+-8%2C+-5%2C+-1%5D%2C+%5B-9%2C+4%2C+-1%2C+-1%2C+2%2C+4%5D%5D%0A%5B8%2C+7%2C+3%2C+2%2C+4%2C+9%2C+1%5D%2C+%5B%5B8%2C+-5%2C+1%2C+-6%2C+-1%2C+-4%2C+6%2C+10%2C+10%2C+6%2C+9%2C+5%5D%2C+%5B4%2C+-8%2C+6%2C+-10%2C+-2%2C+-3%2C+2%2C+-6%2C+9%2C+5%2C+4%2C+10%2C+2%2C+3%5D%2C+%5B10%2C+-1%2C+3%2C+0%2C+-4%2C+1%2C+-5%2C+-4%2C+-1%2C+-7%2C+9%2C+-9%2C+-1%2C+-5%2C+7%2C+8%2C+9%2C+6%2C+-3%5D%2C+%5B0%2C+-9%2C+-7%2C+-2%2C+2%2C+-5%2C+7%2C+4%2C+6%2C+-4%2C+1%2C+8%2C+-7%2C+10%5D%2C+%5B5%2C+6%2C+-9%2C+0%2C+-1%2C+5%2C+4%2C+7%2C+5%2C+10%2C+2%2C+5%2C+7%2C+-9%5D%5D&debug=0)
Thanks to @Maltysen for one byte.
# Explanation:
```
@LDFQ Q (=input) added implicitly.
D sort a list of lists by
@L the sublists generated by some indices
FQ executes ^ with the the input as parameter
```
I was really surprised that this worked. It's a really strange syntax.
[Answer]
# JavaScript (ES6) 46
```
k=>l=>l.sort((a,b)=>k.some(i=>v=a[i]-b[i])&&v)
```
At each comparison during the sort, scan the key indices to find the right order
**Test**
```
f=k=>l=>l.sort((a,b)=>k.some(i=>v=a[i]-b[i])&&v)
;`[1, 0, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[5, 2, 1], [6, 2, 1], [5, 3, 4]]
[1, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[6, 2, 1], [5, 2, 1], [5, 3, 4]]
[0, 1] [[1, 2], [2, 1]] -> [[1, 2], [2, 1]]
[1, 0] [[1, 2], [2, 1]] -> [[2, 1], [1, 2]]
[0] [[4], [10, 11, -88], [-2, 7]] -> [[-2, 7], [4], [10, 11, -88]]
[2] [[-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6]] -> [[-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2]]
[2, 1] [[9, 2, -2, -10, -6], [3, -4, -2]] -> [[3, -4, -2], [9, 2, -2, -10, -6]]
[2, 4, 8] [[5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5], [-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3]] -> [[-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3], [5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5]]
[1, 2, 3, 4, 5] [[-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [5, 3, -6, -5, -4, -4, -8, 2], [9, -4, 1, -1, -3, -2], [-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [1, -5, -3, -10, -7, 9, -8, -5, -1], [-9, 4, -1, -1, 2, 4]] -> [[-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -5, -3, -10, -7, 9, -8, -5, -1], [9, -4, 1, -1, -3, -2], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [5, 3, -6, -5, -4, -4, -8, 2], [-9, 4, -1, -1, 2, 4]]
[8, 7, 3, 2, 4, 9, 1] [[8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9]] -> [[10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5]]`
.split('\n').map(row=>{
var [keys,list,expected]=row.split(/] -?>? ?\[/)
keys=eval(keys+']');
list=eval('['+list+']');
expected=eval('['+expected);
var result=f(keys)(list);
var ok=result.join`|`==expected.join`|`;
console.log(ok?'OK':'KO',keys+' '+list.join`|`+' -> ' +expected.join`|`,ok?'':result.join`|`)
})
```
[Answer]
# [Perl 6](http://perl6.org) ~~23 20~~ 19 bytes
```
->\a,\b{b.sort:{.[|a]}}
{$^a;$^b.sort:{.[|$a]}}
{$^b.sort: *.[|$^a]}
```
```
{$^b.sort: *[|$^a]}
```
[Answer]
## PHP, ~~212~~ 170 bytes
```
function m(&$i,$k){foreach($i as$a=>$y)for($b=-1;++$b<$a;){for($p=0;$p<count($k)&!$r=$i[$b][$x=$k[$p++]]-$i[$b+1][$x];);if($r>0){$s=$i[$b+1];$i[$b+1]=$i[$b];$i[$b]=$s;}}}
```
PHP has [no stable sort built in anymore](https://bugs.php.net/bug.php?id=53341); picking an older version there is no way to do a recursive callback with the required specification. But nevermind: using the [recursive callback iterator](http://php.net/manual/class.recursivecallbackfilteriterator) would cost tons; so I didn´t even check if that could do it.
The inner loop could be replaced with another `foreach`; that would save some bytes on the swapping. But without a check for `$b<$a` (or `$b<count($i)`), that will result in an infinite loop. And with that check, The `foreach` costs as much as the swapping wins.
I first did the comparison recursively; but iteration saves tons of bytes:
**breakdown**
```
// bubble sort
function m(&$i,$k)
{
foreach($i as$a=>$y)
for($b=-1;++$b<$a;)
{
// comparison:
for($p=0;$p<count($k) // loop through keys
&
!$r=$i[$b][$x=$k[$p++]]-$i[$b+1][$x] // while element equals its successor
;);
// if element is larger than its successor, swap them
if($r>0)
{
$s=$i[$b+1];$i[$b+1]=$i[$b];$i[$b]=$s;
}
}
}
```
[Answer]
## R 40 bytes
```
for(i in rev(il)){dd=dd[order(dd[,i]),]}
```
Explanation:
List of lists is best represented as a data.frame in R:
```
ll2 = list(c(5,3,4), c(5,3,7), c(6,2,1), c(6,1,3), c(5,2,1))
dd = data.frame(do.call(rbind, ll2))
dd
X1 X2 X3
1 5 3 4
2 5 3 7
3 6 2 1
4 6 1 3
5 5 2 1
```
If index list is il (indexing is from 1):
```
il = list(1, 2, 3)
```
Sorting can be done with following code:
```
for(i in rev(il)){dd = dd[order(dd[,i]),]}
```
Output:
```
dd
X1 X2 X3
5 5 2 1
1 5 3 4
2 5 3 7
4 6 1 3
3 6 2 1
```
[Answer]
## Racket 218 bytes
```
(λ(il ll)(define qsl(λ(l i)(if(null? l)l(let*((h(first l))(t(rest l))(g(λ(ff)(filter(λ(x)(ff(list-ref x i)
(list-ref h i)))t))))(append(qsl(g <)i)(list h)(qsl(g >=)i))))))(for((i(reverse il)))(set! ll(qsl ll i)))ll)
```
Ungolfed (il=index list; ll=list of lists; qsl= quicksort for list of lists; h=head (first element); t=tail (rest or remaining elements); g=modifiable filter fn):
```
(define qsl
(λ(l i)
(if (null? l)
l
(let* ((h (first l))
(t (rest l))
(g (λ(ff) (filter (λ(x) (ff (list-ref x i) (list-ref h i))) t))))
(append (qsl (g <) i)
(list h)
(qsl (g >=) i)
)))))
(define f
(λ(il ll)
(for ((i (reverse il)))
(set! ll (qsl ll i)))
ll))
```
Testing:
```
(f (list 0 1 2) (list (list 5 3 4) (list 5 3 7) (list 6 2 1) (list 6 1 3) (list 5 2 1)))
(f [list 1 2] [list [list 5 3 4] [list 6 2 1] [list 5 2 3]])
```
Output:
```
'((5 2 1) (5 3 4) (5 3 7) (6 1 3) (6 2 1))
'((6 2 1) (5 2 3) (5 3 4))
```
[Answer]
# PHP, 139 Bytes
use the new [spaceship operator](http://php.net/manual/en/language.operators.comparison.php) and [usort](http://php.net/manual/en/function.usort.php)
```
<?$a=$_GET[a];function c($x,$y,$i=0){$k=$_GET[k];return$x[$k[$i]]-$y[$k[$i]]?:($k[++$i]?c($x,$y,$i):0);}usort($a,c);echo json_encode($a);
```
Instead of `$x[$k[$i]]<=>$y[$k[$i]]` you can use `$x[$k[$i]]-$y[$k[$i]]` under a PHP Version greater 7 - 2 Bytes
version with create an own index 197 Bytes like in a real library
```
<?$m=min(array_map(min,$a=$_GET[a]));foreach($a as$p=>$v){$k="";foreach($s=$_GET[s]as$f){$k.=str_pad($v[$f]-$m,5,0,0);}$k.=str_pad($p,5,0,0);$r[$k]=$v;}ksort($r);echo json_encode(array_values($r));
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 10 bytes
```
{y@<y[;x]}
```
[Try it online!](https://ngn.bitbucket.io/k#eJy1VMtuAjEMvPMVPoLUSJvHJpumh/4H4so3FFXtt9czTpBKyy49VAvLrj0e22OH8/P75fXlcmxvp4/dbj9LEN8y77NESYfP89HLJKHJnoYm5hVCD6fdfqBvYlYi4MSj4iY4aBhOQPW9J75xuiClPaXmNc6LWxZyKEhtcjU2AY74Kou4WZzai7r4nIW33GBDbbAXUX/Ueif4tCiEzIjW36T3Ca9Jrwx8sgrR5CZwI89aieghklZZKiiCZcjMTvG+mZt0OLs3vqwpoybJTBAss0OFWogGRoxGHxPtnmQBgJlCqidbZ7wn67bqxT5cJQNoUQG/YPXCniiHFZtk4U78a6omj3ZNhTJpbGxZWBNGoyvFqSqUaQpK6GPCIJTHs8rIyVgjhRkKPzgzCtKqOeE+3GpstgmjBUWUDqAaVV85fbewmQh0tBYz7BU64mgBMw+lFi5aFVMPuoyDiEMIgfd3ybYr/D3dDyHW9VzR6L4CK3O46Rb/LNPIaIXNY5sYWPuhLlyq3BvLcEy2RYmZlSUIYK42eGpfoWDByZbUC4+z196oR75Kx/2CtCAkmSZi1X7sPTg815g4TGrhwuKYVJ7r1YDHcv5djke63ZDscPoCdPEd+Q==)
[Answer]
**Clojure, 29 bytes**
```
#(sort-by(fn[c](mapv c %))%2)
```
Nicely `sort-by` is stable and knows how to sort vectors, and vectors can operate as functions. `([4 6 9 7] 2)` is `9` (0-based indexing).
]
|
[Question]
[
## The challenge
Write a program or function that prints stars! The program will receive two parameters by standar input: Size of the star and number of points of the star. A star can be any size between 0 and 10 and have 3, 4 or 5 points. The input parameters are separated by a comma, for example: `5,3` means a size 5 star with 3 points. The stars are composed by asterisks `*`
Consider the program will only receive valid inputs.
The prints must be correctly spaced so we can see pretty stars in the output!
## Parameters explanations
## Points
Is the number of arms counting from the central asterisk.
**3 points stars**:
```
*
*
*
* *
* *
```
They are composed by a vertical arms and two diagonal arms. The separation between diagonal arms is `2*size-1`
**4 points stars**
```
* *
* *
*
* *
* *
```
They have the form of a X and composed by two diagonal lines. The separation between lines is `2*(size-1)+1`
**5 points stars**
```
*
*
* * * * *
* *
* *
```
They are composed by a vertical line and a horizontal line. Each asterisk in the horizontal line is separated by one space. Also they have two diagonal lines, with a separation between themselves of `2*(size-2)+1`
## Size
Size is the number of asterisks that has each arm of the star counting from the central asterisk (inclusive).
**Size 1 stars are composed by a single asterisk**
```
*
```
**Size 2 stars examples**
**3 points**
```
*
*
* *
```
**4 points stars**
```
* *
*
* *
```
**5 points stars**
```
*
* * *
* *
```
You have examples of the size 3 stars in the Points parameter explanation.
## Winning criteria
Shortest code wins. Code have to be checked with the following input parameters: `3,2` `3,3` `4,2` `4,3` `5,2` `5,3`
## Bonus
**-25% characters count** for creating a size 6 pointed with the criteria explained before (6 arms and the size is the number of asterisks counting from the central asterisk). It can be any form you want while it respect the specifications. A example of a size 6 star with size 3:
```
*
*
* * * * *
* * *
* * *
```
6 points stars must be checked with the following inputs `6,2` `6,3`.
[Answer]
# Mathematica 80 76 67 chars
Some would question whether this is ASCII art, but I couldn't resist.
```
Graphics@Table[Text["*", r {Cos@t, Sin@t}], {t,0,2π,2π/#1}, {r,0,#2-1}]&
```
**Usage** (setting the font size at 24 to make the stars appear large.)
```
Graphics@Table[Text["*"~Style~24, r {Cos@t, Sin@t}], {t,0,2π,2π/#1}, {r,0,#2-1}] &[6,4]
```

---
**Output** for the following cases:
{{3, 2}, {3, 3}, {4, 2}, {4, 3},
{5, 2}, {5, 3}, {6, 2}, {6, 3},
{7, 4}, {8, 3}, {9, 2}, {12, 4}}

---
**How it works**
(a) The first star is at the origin of a coordinate space. Let's display it.
(b) Afterwards, we'll display a point at {1,0}.
(c) Then 5 points at once. We applied a pure function onto each pair of coordinates that follows it.
(d) Use Cos and Sin to determine the coordinates
(e) Coordinates work only on unit circle; 6 is the number of light beams.
(f) Draw radii from 0 to 4 unit.
```
options = Sequence[Axes -> True, ImageSize -> 225, BaseStyle -> 14];
a = Graphics[Text["*"~Style~{28, Blue}, {0, 0}], PlotLabel -> Style["a", 20], options];
b = Graphics[Text["*"~Style~{28, Blue}, {1, 0}], PlotLabel -> Style["b", 20], options];
c = Graphics[Text["*"~Style~{28, Blue}, {#1, #2}] & @@@ {{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}}, PlotLabel -> Style["c", 20], options];
d = Graphics[Text["*"~Style~{28, Blue}, {Cos@#, Sin@#}] & /@ {0, \[Pi]/3, 2 \[Pi]/3, \[Pi], 4 \[Pi]/3, 5 \[Pi]/3}, PlotLabel -> Style["d", 20], options];
e = Graphics@Table[Text["*"~Style~24, {Cos@t, Sin@t}], {t, 0, 2 \[Pi], 2 \[Pi]/#1}] &[6];
f = Graphics@Table[Text["*"~Style~24, r {Cos@t, Sin@t}], {t, 0, 2 \[Pi], 2 \[Pi]/#1}, {r, 0, #2 - 1}] &[6, 4];
GraphicsGrid[{{a, b, c}, {d, e, f}}, Dividers -> All]
```

[Answer]
# Ruby, ASCII, ~~193~~ score 142 (189 chars - 25 % bonus)
```
def s r,d
f=->a,n{[n*Math.sin(a),n*Math.cos(a)]}
s=d*6
p=[]
s.times{|k|p<<" "*s}
c=s/2
p[c][c]=?*
r.times{|a|d.times{|l|x,y=f[6.28/r*a,d*l]
p[c+x.round][c+y.round]=?*}}
p.map{|j|puts j}
end
```
[Test it online](http://ideone.com/RzAUT)
I think it qualifies for the 6-rays star bonus.
```
* *
* *
* * * * *
* *
* *
* *
* * *
* *
* *
* *
* *
* * * * * * *
* *
* *
* *
```
[Answer]
## *Mathematica*, ~~65~~ 64
My take on David's method:
```
f@p_=Graphics@Array[Text["*",{Cos@#,Sin@#}&[2π/p[[1]]#]#2]&,p,0]
```
Use:
```
f @ {6,4}
```

Errors are produced because of the use of `=` rather than `:=`, and it isn't the proper way to make a definition, but it does work here.
If one were allowed to use dots instead of asterisks this could be written (52 chars):
```
f@p_:=Most@ListPolarPlot@Array[{2π/p[[1]]#,#2}&,p,0]
f @ {6, 4}
```

[Answer]
```
use subs qw /N W E S NW NE SE SW Circler Printer/;
($size,$points)=split(/\,/,$ARGV[0]);
my $arrsize = $size>$points ? $size : $points;
for $my (0...2*$arrsize-2) {
$starArray[$my]=();
}
if($size == 3) {
@armlist=('N','SW','SE');
}
elsif($size == 4) {
@armlist=('NE','NW','SW','SE');
}
elsif($size == 5) {
@armlist=('E','N','W','SW','SE');
}
elsif($size == 6) {
@armlist=('E','N','W','SW','S','SE');
}
elsif($size == 7) {
@armlist=('E','N','W','SW','S','SE','NE');
}
elsif($size == 8) {
@armlist=('E','N','W','SW','S','SE','NE','NW');
}
Circler;
Printer;
sub Circler{
for (@armlist) {
&{$_};
}
}
sub Printer{
for $my1 (0...2*$arrsize-2) {
for $my2 (0...2*$arrsize-2) {
print "$starArray[$my1]->[$my2]"."\t";
}
print "\n\n";
}
}
sub N {
for $my (0...$points-1) {
$starArray[$arrsize-1-$my]->[$arrsize-1]="*";
}
}
sub E {
for $my (0...$points-1) {
$starArray[$arrsize-1]->[$arrsize-1+$my]="*";
}
}
sub W {
for $my (0...$points-1) {
$starArray[$arrsize-1]->[$arrsize-1-$my]="*";
}
}
sub S {
for $my (0...$points-1) {
$starArray[$arrsize-1+$my]->[$arrsize-1]="*";
}
}
sub NW {
for $my (0...$points-1) {
$starArray[$arrsize-1-$my]->[$arrsize-1-$my]="*";
}
}
sub NE {
for $my (0...$points-1) {
$starArray[$arrsize-1-$my]->[$arrsize-1+$my]="*";
}
}
sub SE {
for $my (0...$points-1) {
$starArray[$arrsize-1+$my]->[$arrsize-1+$my]="*";
}
}
sub SW {
for $my (0...$points-1) {
$starArray[$arrsize-1+$my]->[$arrsize-1-$my]="*";
}
}
__END__;
```
]
|
[Question]
[
If the agent is at the origin it always moves right when you choose it.
The goal is to get one agent to 10.
The cost is the sum of the square of the total number of moves (left or right) taken by each individual agent until the first agent gets to 10. You want to minimise the expected cost
Once you have fixed a strategy you should run your code ten thousand times (each time up to the point where the first agent gets to 10) and report the average cost.
# Input and output
There is no input to this challenge. Your code need only output the mean cost over ~~10000~~ 100,000 runs as specified. However please do include an explanation of your strategy for choosing which agent to move when.
In short, the cost of moving a particular agent effectively increases each time you move it. This is a result of the scoring system. As another example, if you move agent 1 twice for your first two moves and it ends up back at the origin, it is now cheaper to move any other agent.
If two answers have the same strategy then the first answer wins. If two different strategies give similar mean costs then they should be rerun with ~~100,000~~ a million (or even more) iterations to see which is better.
A very simple strategy gives a mean cost of 6369. So the first hurdle is to do better than that.
# Winners
This question was first brilliantly solved optimally by Anders Kaseorg.
[Answer]
# [Ruby](https://www.ruby-lang.org/), modified minimum product, average cost ~4950
```
f=->a,b{(0..3).min_by{|q|(9-a[q])**3*b[q]}}
```
[Try it online!](https://tio.run/##RY7NCoQgHMTvPcVeFtSt/1qdIuxFRBalgg5JZeGG@uxuH4edgeF3mIFZNrXH6ZHTQ7AOY2fAbKPz2ieScZpeFon6c@xZ1shUOUQBSgzjoD9qd372qMoknwUmpCTqgBAiBbN2E/SDbp1lPT92opbcCobOfKFF6hYVmBRZjgnSz@IiDFKZWp0NltcSRvltqpCo@5v1ltgQ3vdpGn8 "Ruby – Try It Online")
Always select the agent that minimizes `(9-position)^3*(number of moves)`:
* On the first round, every agent makes a move.
* By using `9-a` instead of `10-a`, any agent in position 9 will try to move on the next iteration.
* Position seems to be more important than the cost projection, so after trying out different values, I found out that the third power is the best way to represent it.
The easiest strategy (round-robin) has a cost of about 7000.
If I let it run in a continuous loop, after a while the average stabilizes around 4950.
[Answer]
# Rust, cost = 4928.296960314256
Computed exactly (modulo floating point imprecision) with a non-random algorithm, but also measured as \$4923.8 ± 2.6\$ (\$1σ\$ confidence) with \$10^7\$ random runs of the actual game as a check.
### Strategy
Consider the following equivalent but wetter version of the game. There’s a tower of cells \$(p, m)\$ with eleven columns \$0 ≤ p ≤ 10\$ and infinitely many rows \$m ≥ 0\$ going downwards. We’ll call the first ten columns \$p = 0, \dotsc, 9\$ “live” and the last column \$p = 10\$ “dead”. Each live cell has a plugged drain in the floor, connected by equal-width pipes to its diagonal neighbors below. We start with \$1\$ liter of water in \$(0, 0)\$, with \$4\$ grains of sand floating in the water. Our goal is to control the plugs until one of the grains ends up in the dead column, while minimizing the expected sum of the squared row numbers of the grains at that time.
The reason to formulate the game like this is that our strategy does not need to look at the grains. Instead, we’re going to open the plugs in some fixed order, letting the grains float where they may, until 100% of the water flows into the dead column in the limit as all of the plugs are open. (We’re very good at opening plugs.)
I’ll explain in a moment how to decide which order we’ll use, but to motivate that, I first need to explain how to evaluate our expected score. Define “time \$t\$” to be the time when \$t\$ liters of water have flowed into the dead column. Then, because the grains of sand flow equivalently to water molecules, the distribution of time quadruples \$(t\_1, \dotsc, t\_4)\$ when the four grains enter the dead column is just the uniform distribution over \$[0, 1]^4\$. Therefore, the time \$t\_\min = \min \{t\_1, \dotsc, t\_4\}\$ when the score should be evaluated has a [beta distribution](https://en.wikipedia.org/wiki/Beta_distribution) \$t\_\min \sim \mathrm{Beta}(1, 4)\$, whose [PDF](https://en.wikipedia.org/wiki/Probability_density_function) is \$4(1 - t)^3\$.
Let \$q\_{(p, m)}(t)\$ be the amount of water in cell \$(p, m)\$ at time \$t\$; let \$c\_{(p, m)}(t) = m^2q\_{(p, m)}(t)\$ be its weighted cost, and \$c\_{\textrm{live}}(t)\$ (resp. \$c\_{\textrm{dead}}(t)\$) the sum over all live (resp. dead) cells. Then we can write our expected score as
\begin{split}
&\int\_0^1 4(1 - t)^3 \left(3\frac{c\_{\textrm{live}}(t)}{1 - t} + c'\_{\textrm{dead}}(t)\right)\,dt \\
&= \int\_0^1 12(1 - t)^2 c\_{\textrm{live}}(t)\,dt + \int\_0^1 4(1 - t)^3 c'\_{\textrm{dead}}(t)\,dt \\
&= \Bigl[-4(1 - t)^3 c\_{\textrm{live}}(t)\Bigr]\_0^1 - \int\_0^1 -4(1 - t)^3 c'\_{\textrm{live}}(t)\,dt + \int\_0^1 4(1 - t)^3 c'\_{\textrm{dead}}(t)\,dt \\
&= \int\_0^1 4(1 - t)^3 (c'\_{\textrm{live}}(t) + c'\_{\textrm{dead}}(t))\,dt.
\end{split}
Therefore, we see that our goal at each step is to minimize the total growth rate of the weighted cost of *all* cells (\$c'\_{\textrm{live}}(t) + c'\_{\textrm{dead}}(t)\$), relative to the rate of flow into the dead column (i.e. growth of \$t\$ itself). \$4(1 - t)^3\$ is decreasing, so we prefer to have smaller ratios earlier. This makes our strategy obvious: at each step, we’ll open the plug that minimizes this ratio, wait until all water has flowed out of that cell, and leave it open while proceeding to the following cells.
Since \$c'\_{\textrm{live}}(t) + c'\_{\textrm{dead}}(t)\$ is piecewise constant, the integral evaluates to an (infinite) sum, one that converges much more quickly than the Monte Carlo simulation. That’s how I determined the precise answer above.
### Code
Build and run with `cargo run --release`.
**`Cargo.toml`**
```
[package]
name = "wandering"
version = "0.1.0"
edition = "2021"
[dependencies]
rand = "0.8.5"
```
**`src/main.rs`**
```
use rand::prelude::*;
use rand::rngs::StdRng;
use std::collections::HashMap;
#[derive(Default, Debug)]
struct Rate {
dead: f64,
cost: f64,
live: HashMap<(u32, u32), f64>,
}
fn add(map: &mut HashMap<(u32, u32), f64>, state: (u32, u32), value: f64) {
if value != 0.0 {
*map.entry(state).or_insert(0.0) += value;
}
}
struct SortingHat {
distribution: HashMap<(u32, u32), f64>,
moves_frontier: [u32; 10],
rates: HashMap<(u32, u32), Rate>,
orders: HashMap<(u32, u32), usize>,
}
impl Default for SortingHat {
fn default() -> SortingHat {
let mut distribution = HashMap::new();
distribution.insert((0, 0), 1.0);
SortingHat {
distribution,
moves_frontier: [0_u32, 1, 2, 3, 4, 5, 6, 7, 8, 9],
rates: HashMap::new(),
orders: HashMap::new(),
}
}
}
impl SortingHat {
fn get_order(&mut self, query_position: u32, query_moves: u32) -> usize {
if let Some(&order) = self.orders.get(&(query_position, query_moves)) {
return order;
}
loop {
let (_, position, moves) = (0_u32..10)
.zip(&self.moves_frontier)
.filter(|&(position, &moves)| {
position + 1 == 10 || self.moves_frontier[position as usize + 1] > moves + 1
})
.map(|(position, &moves)| {
let mut cost = 0.0;
let mut dead = 0.0;
for new_position in [position.abs_diff(1), position + 1] {
cost += moves as f64 + 1. / 2.;
if new_position == 10 {
dead += 1. / 2.;
} else if let Some(new_rate) = self.rates.get(&(new_position, moves + 1)) {
dead += new_rate.dead / 2.;
cost += new_rate.cost / 2.;
}
}
(cost / dead, position, moves)
})
.min_by(|a, b| a.partial_cmp(&b).unwrap())
.unwrap();
self.orders.insert((position, moves), self.orders.len());
let mut rate = Rate::default();
for new_position in [position.abs_diff(1), position + 1] {
rate.cost += moves as f64 + 1. / 2.;
if new_position == 10 {
rate.dead += 1. / 2.;
} else if let Some(new_rate) = self.rates.get(&(new_position, moves + 1)) {
rate.dead += new_rate.dead / 2.;
rate.cost += new_rate.cost / 2.;
for (&newer_state, live_rate) in &new_rate.live {
add(&mut rate.live, newer_state, live_rate / 2.);
}
} else {
add(&mut rate.live, (new_position, moves + 1), 1. / 2.);
}
}
if let Some(mass) = self.distribution.remove(&(position, moves)) {
for (&new_state, live_rate) in &rate.live {
add(&mut self.distribution, new_state, live_rate * mass);
}
}
for old_rate in self.rates.values_mut() {
if let Some(live_rate) = old_rate.live.remove(&(position, moves)) {
old_rate.dead += rate.dead * live_rate;
old_rate.cost += rate.cost * live_rate;
for (&new_state, new_live_rate) in &rate.live {
*old_rate.live.entry(new_state).or_insert(0.0) += new_live_rate * live_rate;
}
}
}
self.rates.remove(&(position + 1, moves + 1));
self.rates.insert((position, moves), rate);
self.moves_frontier[position as usize] += 2;
if (position, moves) == (query_position, query_moves) {
return self.orders.len() - 1;
}
}
}
fn strategy(&mut self, positions: &[u32; 4], num_moves: &[u32; 4]) -> usize {
(0..4)
.min_by_key(|&agent| self.get_order(positions[agent], num_moves[agent]))
.unwrap()
}
}
fn test(mut rng: impl Rng, mut strategy: impl FnMut(&[u32; 4], &[u32; 4]) -> usize, runs: u32) {
let mut count = 0;
let mut mean = 0.0;
let mut m2 = 0.0;
let mut mean_stdev = f64::NAN;
for _ in 0..runs {
let mut positions = [0; 4];
let mut num_moves = [0; 4];
loop {
let agent = strategy(&positions, &num_moves);
if positions[agent] == 0 || rng.gen() {
positions[agent] += 1;
} else {
positions[agent] -= 1;
}
num_moves[agent] += 1;
if positions[agent] == 10 {
break;
}
}
let sample: f64 = num_moves.into_iter().map(|m| (m as f64).powi(2)).sum();
count += 1;
let delta = sample - mean;
mean += delta / count as f64;
m2 += delta * delta * (1. - 1. / count as f64);
mean_stdev = (m2 / (count as f64 * (count - 1) as f64)).sqrt();
if count % 100 == 0 {
eprint!("\r\x1b[K{count}: {mean} ± {mean_stdev}");
}
}
eprint!("\r\x1b[K");
println!("{count}: {mean} ± {mean_stdev}");
}
fn main() {
let rng = StdRng::seed_from_u64(0);
let mut sorting_hat = SortingHat::default();
test(
rng,
|positions, num_moves| sorting_hat.strategy(positions, num_moves),
10000000,
)
}
```
[Answer]
# [Python 3 (PyPy)](http://pypy.org/), 4957.6 +/- 2.6 (10M trials)
```
def expco(positions, num_moves,depth=0) -> float:
if depth==0:
return min((10**2 - positions[i] ** 2)
* (5 * 10**2 - positions[i] ** 2 + 6 * num_moves[i] - 2)/3 for i in range(4))
return (10 not in positions)and min(
expco([abs(p-(i==j)) for j,p in enumerate(positions)],
[m+(i==j) for j,m in enumerate(num_moves)],depth-1)/2 +
expco([p+(i==j) for j,p in enumerate(positions)],
[m+(i==j) for j,m in enumerate(num_moves)],depth-1)/2 +
num_moves[i]*2+1 for i in range(4))
def strategy(positions, num_moves, depth=1) -> int:
return min(range(4), key = lambda i:
expco([abs(p-(i==j)) for j,p in enumerate(positions)],
[m+(i==j) for j,m in enumerate(num_moves)],depth)/2 +
expco([p+(i==j) for j,p in enumerate(positions)],
[m+(i==j) for j,m in enumerate(num_moves)],depth)/2 +
num_moves[i]*2+1)
```
[Try it online!](https://tio.run/##xVTNjpswEL7zFKM9GQIJsNseItGn6C2KIic4iXfjn4LZJlrlofoKfbF0jMGEbLbqqeuDBZ6Zb2a@@Wx9MnslHxN90qfLpWRbYEe9UUSrmhuuZB2DbMRKqFdWxyXTZl@kISTfYHtQ1MwDwMW34CxF6g7sqphpKgmCS0KyNIpySMCDLvgSogjy0LvbFQH5gtuH3jCBr2j39djzBEFmj7BVFXDgEioqd4w8hQ65KwILAKmMtXvQkMqyra4vwfW9oOua6ITwongOwxb3OdY2kmFeVlHDBm7CZTxqABZi4iK7QDEO9JVjYMtYkoUzbOumBD0G@V/Zr3mN8kl2j1QrkNpYuN3pvkY6KWStSLjsJHKlhh4shhd2ggIOVKxLCnz@mYP4zDH8dQhhEFy40KoyIKjZB903klgqEbTzMKw2pB9KDFUjr6bgWN2oRpoYBKMS9xxZT2NIp24LWpebYVuUcLjNvlsMXaR4HeHJ23zJd2w/9/zA4HvVsPmIJLpj0qD/v2gJZTqKHd6FFmUJkwIy@wi9MxTYJ7BDzTq@ppu94htGFlkMSbYcww7MX8GOPD5IkaXj3uxaV4y@@NOaCo00YLuNIEf7ulm2j5btQQ2Bd2@nNU5fsoOhFsAhJe0ovdX@WH/nNXMAgzX3NpsaX9kMAbLer0tsMVa1KdkrprFSm9Y/KkMweAbEVRT1Hxgddi@srvCOk@3DWz/J6WolqWCr1RneLOYZfv9yXw79/IAJgxvNZmmKWszDyx8 "Python 3 (PyPy) – Try It Online")
This is a simple brute force search on top of @Anders Kaseorg's formula (and code).
The score given was obtained with search depth 1, i.e. for each agent compute the expected cost if we can switch agents once immediately after the first move and take the best.
Apologies for the messy code.
[Answer]
# Python 3, cost ≈ 5034.3 ± 2.7
\$1σ\$ confidence, evaluated with \$10^7\$ runs.
```
def strategy(positions, num_moves):
return min(
range(4),
key=lambda i: (10**2 - positions[i] ** 2)
* (5 * 10**2 - positions[i] ** 2 + 6 * num_moves[i] - 2),
)
```
[Try it online!](https://tio.run/##fVJBbuMwDLz7FURPsmsndrbbQ4H8orcgMNSYSYRGkivJbYwij9ov7MeylBUrcXe7PAgSORxySLW922v1o2j7tj@fG9yCdYY73PWs1VY4oZXNQXWylvodbfqUAJlB1xkFUig2vAcfVztkD2kePa/YLw9cvjQcxBOwqsyyBRQQeVdiDVkGizRmZMB@0vEtEu7hkeKxHe8viCDUTM9Ctto4kNztk8ud2mq0TBIvzaF1bNSXg@nUKGijO@VykMgVnQtYQplDOQtHMkC22oAAoS5Cb5K9xVYpdVVSt/AQY7Hdf8Q@9uKA8Gw6vHJ54ztUjvD/38Yk5TqtIXkN90uoQGz/DixJHuDB4mU6s81eiw2yVZVDUa2ntNdh39BOEN@UqMqpJG8vBvlr9FouW1JPKjvJjn7nfshHP@QbjRE@LGlavsGD454gMBXDBmPUPzw@oOaB4BpdxJgvTX@vIoJqxF0Ke47augbfqYz/WDP7Zhyj5Dmw0FE2Xig7TcP0WiOUY9u7z3GBs7pWXGJdn@DTc57g969wC@ynOyqYfPmhVektPf8B "Python 3 (PyPy) – Try It Online") (\$10^5\$ runs)
### How it works
If we were to pick one agent at position \$p\$ that’s previously moved \$m\$ times, and use it for the rest of the game, the expected additional cost would be exactly
$$f(p, m) = \frac13(10^2 - p^2)(5⋅10^2 - p^2 + 6m - 2).$$
(You can verify that
$$m^2 + f(p, m) = (m + 1)^2 + \frac12(f(\lvert p - 1\rvert, m + 1) + f(p + 1, m + 1))$$
and \$f(10, m) = 0\$.)
At each step, we pick the agent that minimizes this quantity. (We don’t restrict ourselves to using it for the rest of the game.)
[Answer]
# 5050? ± 26.64
```
def strategy(positions, num_moves):
E = [100, 99, 96, 91, 84, 75, 64, 51, 36, 19]
_, n = min(((E[p] + m) ** 2 - m ** 2, i) for p, m, i in zip(positions, num_moves, range(4)))
return n
```
[Try it online!](https://tio.run/##fVPbctowEH33V5zJk@waYhOSls7wmD/oG8N4VBCgKbpUltPQDB/VX@iP0ZUFCk7TakaypD17ds@ubA9@Z/TdyB7s4XRaiw1a77gX2wOzppVeGt2W0J1qlHkSbf45Ax4xx6KuqhKzGc0HmnWJT9MSH@9LPND3ns53dF/PloRviIBclNSMsceFXeIDVI6iwAQjqH5TQubYGAdbQtEBUuOntO8mUcJxvRVsmuc50TvhO6ehT1JZ4zwU97vsvCfg2qgsC8K8aD27qCOOTkc5wMp02lNcwTWtE8qVtFXjuGQ9JKTWJxVDXzmHkbIMlamWKDBNtpT2O7YfO7kX@OI68coVBt8K7Qn//14MXBJi0TtTjeeoITd/G@YkD2LfinN1xqudkSvBFtS0Ub0c0qZo17QDxD9C1NVQUhhfneDf0m3LlSX1pLJT7LkoJn2Rn0ORrzQmeN@kYfi12HseCCLTqO9gsoZDwEfUbSR4tU6SLYQuwGoiqC@4c@DA0bR@LZ7CA6aHNW6/O8/I@RYsZlRcNuQdHyQ1w0nt2ebm5dLAcdNorkTTHPESOI/4/SvuIvvxhgJmb14o/WI08tMf "Python 3 (PyPy) – Try It Online")
Use minimal \$\left(E(P\_i)+M\_i\right)^2-M\_i^2\$, where \$E(X)\$ is a pre-calculated array $$\left[E(0),\dots,E(9)\right]=\left[100, 99, 96, 91, 84, 75, 64, 51, 36, 19\right]$$
generated by following codes
```
syms E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA
solve([E0-E1-1, E1-(E0+E2)/2-1, E2-(E1+E3)/2-1, E3-(E2+E4)/2-1, E4-(E3+E5)/2-1, E5-(E4+E6)/2-1, E6-(E5+E7)/2-1, E7-(E6+E8)/2-1, E8-(E7+E9)/2-1, E9-(E8+EA)/2-1, EA])
```
[Try it online!](https://tio.run/##Ncq7CsJAEEbh3qeYMmEMZu@bMsX/FGIRYxAxskIk4NOvgzDd@eCU@TPtS30/77SW6Ubb93Ut62OuEhuhJxiCJTiCJwRCJCRCJgyE8bCVdV@aM/oOpjNHubsGPcO2J/u3FRuGUzuxZXi1FztGUAexZ0R1FAdGUidxZGR1FifGoB7EmTGqx0tb6w8 "Octave – Try It Online")
The driver code is used from other posts.
[Answer]
# Python 3, cost ≈ 4928.4 ± 1
I believe this is essentially optimal. Thank you to @usul for the inspiration.
```
import functools
f = lambda p, m: (1. / 3) * (100 - p * p) * (500 - p * p + 6 * m - 2)
@functools.lru_cache(None)
def gittins_value(p, m, l):
if m >= 400:
return f(p, m)
if p == 0:
v_next = gittins_value(p + 1, m + 1, l)
else:
v_next = 0.5 * gittins_value(p - 1, m + 1, l)
if p != 9:
v_next += 0.5 * gittins_value(p + 1, m + 1, l)
return min((2 * m + 1) + v_next, l)
@functools.lru_cache(None)
def gittins_index(p, m):
low = 2 * m + 1
high = f(p, m)
while True:
mid = 0.5 * (low + high)
v = gittins_value(p, m, mid)
if v < mid:
high = mid
else:
low = mid
if abs(high - low) <= 1e-6:
break
return 0.5 * (low + high)
def strategy(p, m):
indices = [gittins_index(p_i, m_i) for p_i, m_i in zip(p, m)]
return indices.index(min(indices))
```
[Answer]
# R / Rcpp: 5006 ± 7.31, or 4932 ± 3.63
Score computed by taking the average of 20 million simulated games. Bounds are a 95% bootstrap confidence interval with 10,000 iterations.
Thanks to Anders Kaseorg for pointing out a typo in my code that caused the solution to accidentally be optimal. Reader, may all your future bugs behave thusly. The following description explains the 5006 solution with a note for how to get the 4932 solution.
## Strategy:
Let's consider a simplified version of the environment in order to construct a risk heuristic. We'd like to be able to treat `n` consecutive movements of an agent as independent, but that won't be true if the agent ever reaches position 0 or 10 during those movements.
Suppose instead that each of the number lines is infinite in both directions, and that the probability of moving right is always 0.5 (even at position 0). In this simplified case, if we move a single agent `n` consecutive times, we may treat the resulting `k` number of movements to the right as binomially distributed.
At each step, let `n = 10 - x`, where `x` is the agent's position on the number line. Since the agent's movements are independent in the simplified environment, we can calculate the probability that the agent has moved backwards given `k` moves to the right as
$$Prob = 1 - \sum\_{k=\lceil \frac{n}{2} \rceil}^n \dbinom n k \cdot 0.5^k \cdot (1-0.5)^{n-k}$$
Note: If you incorrectly move the one-minus inside the sum, the solution becomes near optimal for reasons that are unclear.
Let the cost function be the increase in cost accrued by moving the agent `n` times:
$$ Cost = (x + n)^2 - (x)^2 $$
Then define the risk of moving an agent as
$$ Risk = Prob \cdot Cost $$
and at each step move the agent with the lowest risk.
## Intuition:
The idea is to calculate the risk that over the minimum number of steps an agent would need to reach the goal, the agent ends up moving backwards instead of forwards, i.e. We try to maximize the chance that the chosen agent will move closer to the goal. Minimizing this risk heuristic appears to perform fairly well even though the method does not take into account the effect of the order of the movements, nor the effect of reaching the zero position.
```
#include <Rcpp.h>
using namespace Rcpp;
//* Initialize Environment
// [[Rcpp::export]]
NumericMatrix initEnv() {
return(NumericMatrix (4, 2));
}
//* Update Environment
// [[Rcpp::export]]
NumericMatrix updateEnv(NumericMatrix x, int a) {
//Update move counter
x(a, 1) = x(a, 1) + 1;
//Update position
if(x(a, 0) == 0){
x(a, 0) = 1;
} else {
RNGScope scope;
NumericVector r = Rcpp::runif(1, 0.0, 1.0);
if(r[0] <= 0.5){
x(a, 0) = x(a, 0) - 1;
} else {
x(a, 0) = x(a, 0) + 1;
}
}
//Return
return(x);
}
//* Calculate Loss
// [[Rcpp::export]]
double envCost(NumericMatrix x) {
double lambda = 0;
for(int i = 0; i < 4; i++){
lambda = lambda + pow(x(i, 1), 2);
}
return(lambda);
}
//* Calculate Risk
// [[Rcpp::export]]
double agentRisk(NumericMatrix x, int a) {
//Parameters
int pos = x(a, 0);
int n = 10 - pos;
//Calculate risk correctly
double prob = 0;
double cost = pow(x(a, 1) + n, 2) - pow(x(a, 1), 2);
for(int k = ceil(n / 2); k <= n; k++){
prob = prob + (Rf_choose(n, k) * pow(0.5, k) * pow(0.5, n - k));
}
prob = 1 - prob;
//Calculate risk with typo
//double prob = 0;
//double cost = pow(x(a, 1) + n, 2) - pow(x(a, 1), 2);
//for(int k = ceil(n / 2); k <= n; k++){
// prob = prob + (1 - Rf_choose(n, k) * pow(0.5, k) * pow(0.5, n - k));
//}
//Return
return(prob * cost);
}
//* Simulate Game
// [[Rcpp::export]]
List simGame() {
//Generate environment
NumericMatrix en = initEnv();
//Complete game
bool done = false;
while(!done){
//Parameters
int a = 0;
double lambda = agentRisk(en, 0);
//Calculate risks and choose action
for(int i = 1; i < 4; i++){
double lambda_new = agentRisk(en, i);
if(lambda_new < lambda){
a = i;
lambda = lambda_new;
}
}
//Update game
en = updateEnv(en, a);
//Check victory conditions
for(int i = 0; i < 4; i++){
if(en(i, 0) >= 10){
done = true;
break;
}
}
}
//Return
return(
List::create(
Named("state") = en,
Named("cost") = envCost(en)
)
);
}
```
[Answer]
# Rust, cost = ~5032 (1M iterations)
```
const depth: usize = 1200;
const iterations: usize = 1_000_000;
lazy_static! {
static ref EXPECTED_SCORES: [[usize; 10]; depth] = {
let mut expected_scores = [[1_000_000usize; 10]; depth];
for i in (0..depth-1).rev() {
for j in 0..10 {
if j == 0 {
expected_scores[i][j] = expected_scores[i + 1][j + 1].saturating_add(2 * i + 1);
} else if j == 9 {
expected_scores[i][j] =
(expected_scores[i + 1][j - 1] / 2).saturating_add(2 * i + 1);
} else {
expected_scores[i][j] = (expected_scores[i + 1][j + 1]/ 2)
.saturating_add(expected_scores[i + 1][j - 1] / 2)
.saturating_add(2 * i + 1);
}
}
}
expected_scores
};
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
struct Agent {
position: u8,
actions: u32,
}
fn strategy(agents: [Agent; 4]) -> usize {
return (0..4)
.min_by_key(|i| EXPECTED_SCORES[(agents[*i].actions as usize).min(depth - 1)][agents[*i].position as usize])
.unwrap();
}
```
Basically pre-computes a table of expected scores then uses that.
[Playground link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=31b9f5b089615a963e41b679395e1d1a) Need to reduce iterations if you don't want it to time out.
[Answer]
# [Python 3 (PyPy)](http://pypy.org/), 5027.1 ± 8.3
```
def strategy(positions, num_moves) -> int:
return min(
range(4),
key=lambda i: (10 - positions[i] + 2*num_moves[i]) * (10 - positions[i]),
)
```
[Try it online!](https://tio.run/##fVPBbtswDL37K4ieZM9O7aynAOkn7LRbEBhqzCRCI8mV5K5GkY/aL@zHMkpylHrrxoMhkY@PfKTcj@6o1deqH/vxculwD9YZ7vAwsl5b4YRWtgQ1yFbqV7Q5VI8glFtlQGbQDUaBFIqFe/BxdUD2kJfJ84zj@sTlU8dBrIA1NVSQuDdiC19gWaQK5Mih@AQ2MeYXIXttHEjujtl0pqKdllnm@3doHbuKKMEMKnb9TSuMbe/0oFwJErmi7xLWUJdQL@InC5C9NiBI6CQnkKySotQWpW7qLbX7kGJJyCexH0dxQvhuBrxxeeMHVI7w/x/9LOU2mZBMQ1xDA2L/d2BN8gBPFqcpLXZHLXbINk0JVbOd097W8IF2hvhHiaaeS/L2ZJA/J6/lsif1pHKQ7K0olmHIb37IHzQmeFjSvHyHJ8c9QWSqwgZT1F88PqLuI8EtukwxX9o/MCJorripsOdorevwlcr4B7awL8YxSr4HFjsqrgfKzvM4vd7QL8H2d@/XBS7aVnGJbXuGd895hl8/4ymyn@@oYPbHS23qYPnlNw "Python 3 (PyPy) – Try It Online")
Copies the function/testing template from [Anders Keorg's answer](https://codegolf.stackexchange.com/a/250837).
Chooses the agent with the minimal best-case cost \$(10-\mathit{position}+\mathit{moves})^2-\mathit{moves}^2=(10-\mathit{position}+2\mathit{moves})(10-\mathit{position})\$.
[Answer]
# C++: ~4953 (100 million iterations)
```
#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int rand(int a, int b) { return uniform_int_distribution<int>(a, b)(rng);}
int main() {
const int NRIT = 100'000'000;
auto go = [&] {
int l[4] = { 10,10,10,10 }, t[4] = {}, sol = 0;
auto cost = [&](int nr) {return l[nr] * (4 * t[nr] * l[nr] + 6); };
while (1) {
pair<int, int> best = { INT_MAX, -1 };
for (int i = 0; i < 4; ++i)
best = min(best, { cost(i), i });
int opt = best.second;
sol += 2 * t[opt]++ + 1;
if (l[opt] == 10)
--l[opt];
else {
if (rand(0,1))
--l[opt];
else
++l[opt];
}
if (!l[opt])
return sol;
}
};
long long total = 0;
for (int i = 0; i < NRIT; ++i)
total += go();
cout << (double)(total) / NRIT;
}
```
I misread the question at first and thought it had a 1/2 chance to move backwards or stay still. This chooses the agent with the least expected cost to finish, according to my calculations and the (wrong) assumption it can't go backwards.
\$ \text{cost} = (10-p)(4 \cdot (10-p) \cdot m+6)\$
I want to add 10 000 iterations is definitely not enough, I could cherrypick 10k iterations to get 4790, which is far from the real average. Standardised testing also encounters the issue of different number generators, which can actually make a small difference (it did from my testing).
[Answer]
# Python: ~4973
**TL;DR** By Gittins theory, there is an optimal solution of the following form, but it has some complicated replacement for `approx_grades` and this is a heuristic.
```
import random,numpy
def approx_grade(x,n):
if x <= 0:
return 2*n+1 + approx_grade(1, n+1)
else:
return 2**(10-x) * (9 - x) + (2**(11-x) -2)*(2*n + 1)
def sim(num_players):
xs = [0]*num_players
ns = [0]*num_players
grades = [approx_grade(0,0)]*num_players
while True:
i = numpy.argmin(grades) # STRATEGY HERE
ns[i] += 1
if xs[i] == 0:
xs[i] = 1
elif random.random() <= 0.5:
xs[i] += 1
if xs[i] == 10:
return sum([n*n for n in ns])
else:
xs[i] -= 1
grades[i] = approx_grade(xs[i], ns[i])
T = 100000
scores = [sim(4) for t in range(T)]
print(numpy.mean(scores))
```
This is a special case of the Gittins index theorem, and there is a very nice exposition of essentially this game in the 2003 paper *On Playing Golf with Two Balls*[1]
[1] <https://epubs.siam.org/doi/abs/10.1137/S0895480102408341>
Notice we can rephrase the cost as: when we move an agent that has taken n steps so far, we pay 2n+1 immediately, and the total cost at the end is the sum of all payments made along the way. Note 2n+1 = (n+1)^2 - n^2.
The key point is that for any given agent i and state of the agent (i.e. location x[i] and number of steps so far n[i]), there is an **index** or "grade" we can give the agent that perfectly captures how desirable it is to choose that agent next. The optimal strategy is to pick the agent with the best grade. **One agent's grade does not depend on the others' states!**
The grade is the following number. Imagine we had a fifth agent with the ability to magically teleport to the end for a cost g. And imagine we are playing the game with only agent i and the magic agent. If g is very small, we will just choose the magic agent. But if g is large, we will take a risk and play agent i, see what happens, and then decide whether to use the magic agent or play agent i again.
There is some magic number g(x[i],n[i]) where we are indifferent between the magic agent and i. That number is the grade.
---
Now, in theory the grade is polynomial-time computable, but it's pretty complex. So I used the following approximation: suppose the optimal strategy in the magic game is to keep trying agent i as long as they move right, but as soon as they move left, pay g to stop. Then the index for step 9 would satisfy
$$ g(9,n) = 2n + 1 + \frac{1}{2}g(9,n) . $$
The left side is if we pay g(9,n) for the magic agent to halt immediately, and the right side is if we pay 2n+1 to advance agent i: with probability half we terminate and pay nothing, and with probability half we go left, at which point we pay g(9,n) to stop.
This solves to g(9,n) = 4n+2.
Similarly, at location 8, we should be indifferent between paying g(8,n) to stop, or paying 2n+1 to get a half chance to go left -- when we pay g(8,n) to stop -- and a half chance to go right -- when we repeat the game at step 9.
$$ g(8,n) = 2n+1 + \frac{1}{2} g(8,n) + \frac{1}{2}\left(2(n+1)+1 + \frac{1}{2}g(8,n)\right) . $$
If we repeat this logic, we get an approximation to the grade which is
$$ g(x,n) = 2^{10-x}(9-x) + (2^{11-x}-2)(2n+1) . $$
After dealing with the special case of x=0, I get this code. Apparently it's still pretty suboptimal as another answer gets ~4927.
---
Note: I used multiprocessing to run 8 million total reps in 36min on a laptop, and got an average of just under 4973. I also reimplemented in C++ with probably hundreds of millions of reps and it seemed to converge to about 4974.5. But the quality of the RNG and precision arithmetic matters! C's built in rand() gave basically nonsense.
[Answer]
# R / Rcpp: 4937 ± 4.22
Average of 15 million simulated games. Bounds are a 95% bootstrap confidence interval with 15,000 iterations.
As a supplement to the wonderful Gittins index answers, I wanted to show an empirical method that produces the same result. This solution predicts which robot to move using a neural net that's been trained by a genetic algorithm.
## Strategy:
In order to optimally move our robots across the number lines, we need to determine a function that maps each robot's state information to a value that represents our decision to move it. This is called an action-value function. For simplicity, let's choose to always move the robot with the highest action-value.
At this point we could use the Gittins index as our action-value, but let's empirically estimate an action-value function instead.
### Estimating the Action-Value Function
I decided to use a neural net (NN) to approximate the action-value function. The NN is fully connected with two hidden layers, each having ten neurons. Weights are initialized using the He method, and biases are initialized uniformly on \$[-1,1]\$. The activation functions are all rectified linear units (ReLU), except the activation function for the output, which is a ReLU clamped to \$[0, 1]\$.
Neural nets often have better performance when the inputs are symmetrically distributed and on the interval \$[-1, 1]\$, but in this problem the input state information of a robot is its current position on the interval \$[0 .. 9]\$ and the number of times it has been moved on the interval \$[0 .. \infty)\$.
I transformed the position of the robot to the \$[-1, 1]\$ interval by shifting and scaling.
To transform the total number of moves I first simulated 10 million games in which I always moved the same robot. This gave a distribution for the total number of moves, which I used to estimate an upper bound. The distribution of the total number of moves is heavily right skewed, so I applied a log transform to reduce skew, and then normalized the result using the log of my estimated upper bound in order to arrive at the \$[-1, 1]\$ interval for total number of moves. Note: Because the total number of moves can be zero, I added one to the total number of moves before taking the log.
### Training the Neural Net
In reinforcement learning there are a number of well-established methods for training neural nets that predict action-values, but I have decided to completely ignore them because I've been having a lot of fun with genetic algorithms recently. There's no fun like gradient-free fun.
The genetic algorithm that I used updated NN weights and biases, but not the NN architecture itself. The initial population was 225 chromosomes, and fitness for each chromosome was calculated by evaluating its corresponding action-value function over 7500 games.
It is often desirable for neural net weights and biases to be relatively small and for the model's learned representation to be distributed across the neurons. To achieve this, I added batch normalization to the hidden layers of the neural nets. Regularizing the models in this way greatly improved performance and helped to ensure that the mutation function continued to be effective late in training by keeping the weights and biases close to the mutation function's generating distributions.
The batch normalization's \$\gamma\$ and \$\beta\$ parameters were also updated by the genetic algorithm.
## Learned Action-Values:
This graph shows the final neural net's predicted action-values for robots in the most commonly traversed subset of the state space. Note: Because these estimated action-values are not with reference to any rewards, they only have meaning with respect to each other. I have arbitrarily scaled them to be between zero and one.
[](https://i.stack.imgur.com/pGKVv.jpg)
## Code:
**R Code to Generate Policy**
```
# Parameters
iters <- 100
popNum <- 225
layers <- c(10, 10)
neval <- 7500
mutRate <- 0.001
# Evolve
population <- generatePopulation(popNum, layers, neval)
out <- rep(NA, iters)
for(i in 1:iters){
# Evaluate population fitness
fitness = evaluatePopulation(population, neval)
out[i] = mean(fitness)
# Keep track of best policy so far
minFit = fitness[length(fitness)]
if(min(fitness) <= minFit){
minFit = min(fitness)
minPolicy = population[[which.min(fitness)]]
}
# Selection
cutoff = quantile(fitness, 0.5)
population = population[fitness <= cutoff]
# Crossover
offspringNum = (popNum - length(population))
offspring = lapply(1:offspringNum, function(i){
inds = sample(1:length(population), 2, FALSE)
crossover(population[[ inds[1] ]], population[[ inds[2] ]])
})
population = c(population, offspring)
# Mutate
population = lapply(1:length(population), function(i){
mutate(population[[i]], rate = mutRate)
})
# Elitism
eliteInds = c(round(0.99 * popNum):popNum)
population[eliteInds] = lapply(eliteInds, function(i){minPolicy})
}
```
**R Code Helper Functions**
```
#' Evaluate Population
#' @export
evaluatePopulation <- function(population, neval){
sapply(population, function(x){
return(mean(evaluatePolicy(x, neval)))
})
}
#' Generate Random Population
#' @export
generatePopulation <- function(size, layers, neval, maxCost = Inf){
# Population
population = list()
# Increase yield
while(TRUE){
# Generate seed population
out = lapply(1:size, function(i){
generateChromosome(layers)
})
# Calculate fitness
fitness = evaluatePopulation(out, neval)
fitness[fitness > maxCost] = NA
inds = order(fitness)
out = out[inds]
fitness = fitness[inds]
# Seed population
population = c(population, out[!is.na(fitness)])
# Report
if(length(population) >= size){
population = population[1:size]
break
} else {
message(paste0("Found: ", length(population)))
}
}
# Return
return(population)
}
```
**Rcpp Code for Genetic Algorithm**
```
#include <Rcpp.h>
using namespace Rcpp;
//* Initialize Environment
// [[Rcpp::export]]
NumericMatrix initEnv() {
return(NumericMatrix (4, 2));
}
//* Update Environment
// [[Rcpp::export]]
NumericMatrix updateEnv(
NumericMatrix env,
int a
) {
//Increase movement count
env(a, 1) += 1;
//Move robot
if(env(a, 0) == 0){
env(a, 0) = 1;
} else {
NumericVector r = Rcpp::runif(1, 0.0, 1.0);
if(r[0] >= 0.5){
env(a, 0) += 1;
} else {
env(a, 0) -= 1;
}
}
//Return
return(env);
}
//* Calculate Total Cost
// [[Rcpp::export]]
double envCost(NumericMatrix env) {
double lambda = 0;
for(int i = 0; i < env.nrow(); i++){
lambda += pow(env(i, 1), 2);
}
return(lambda);
}
//* Generate Chromosome
// [[Rcpp::export]]
List generateChromosome(
IntegerVector layers
) {
//Create container for the NN matrices
List chrom;
//Create weight and bias matrices for each layer
for(int i = 0; i < layers.length() + 1; i++){
//Determine matrix dimensions
int inputNum;
int outputNum;
if(i == 0){
inputNum = 2;
outputNum = layers[i];
} else if(i == layers.length()){
inputNum = layers[i - 1];
outputNum = 1;
} else {
inputNum = layers[i - 1];
outputNum = layers[i];
}
//Initialize weights and biases
NumericVector wtList = Rcpp::rnorm(outputNum * inputNum, 0.0, sqrt(0.5 * inputNum));
NumericVector biList = Rcpp::runif(outputNum, -1.0, 1.0);
NumericMatrix wt (outputNum, inputNum, wtList.begin());
NumericMatrix bi (outputNum, 1, biList.begin());
//Record
List chLayer = List::create(
Named("wt") = wt,
Named("bi") = bi
);
chrom.push_back(chLayer);
}
//Initialize batch normalization matrix
NumericMatrix batch (layers.length(), 2);
NumericVector batchVals = Rcpp::rnorm(batch.size(), 0.0, 1.0);
for(int i = 0; i < batch.size(); i++){
batch[i] = batchVals[i];
}
//Return
List out = List::create(
Named("layers") = layers,
Named("chrom") = chrom,
Named("batch") = batch
);
return(out);
}
//* Crossover
// [[Rcpp::export]]
List crossover(
List x,
List y,
double rate = -1,
double scale = -1
) {
//Set parameters
NumericVector probs = Rcpp::runif(2, 0.0, 1.0);
if(rate >= 0){
probs[0] = rate;
}
if(scale >= 0){
probs[1] = scale;
}
//Crossover the NN
List out = clone(x);
//Access the components
List chrom = out["chrom"];
List xChrom = x["chrom"];
List yChrom = y["chrom"];
//Crossover weights and biases
for(int i = 0; i < chrom.length(); i++){
//Reference the layer
List chLayer = chrom[i];
List xLayer = xChrom[i];
List yLayer = yChrom[i];
//Access the matrices
NumericMatrix wt = chLayer["wt"];
NumericMatrix bi = chLayer["bi"];
NumericMatrix xWt = xLayer["wt"];
NumericMatrix xBi = xLayer["bi"];
NumericMatrix yWt = yLayer["wt"];
NumericMatrix yBi = yLayer["bi"];
//Crossover
LogicalVector doCross_wt = (Rcpp::runif(wt.size(), 0.0, 1.0) < probs[0]);
LogicalVector doCross_bi = (Rcpp::runif(bi.size(), 0.0, 1.0) < probs[0]);
for(int j = 0; j < wt.size(); j++){
if(doCross_wt[j]){
wt[j] = probs[1] * (xWt[j] - yWt[j]) + xWt[j];
}
}
for(int j = 0; j < bi.size(); j++){
if(doCross_bi[j]){
bi[j] = probs[1] * (xBi[j] - yBi[j]) + xBi[j];
}
}
}
//Crossover gamma and beta
NumericMatrix batch = out["batch"];
NumericMatrix xBatch = x["batch"];
NumericMatrix yBatch = y["batch"];
LogicalVector doCross_yb = (Rcpp::runif(batch.size(), 0.0, 1.0) < probs[0]);
for(int i = 0; i < batch.size(); i++){
if(doCross_yb[i]){
batch[i] = probs[1] * (xBatch[i] - yBatch[i]) + xBatch[i];
}
}
//Return
return(out);
}
//* Mutate
// [[Rcpp::export]]
List mutate(
List x,
double rate = -1
) {
//Set parameters
NumericVector probs = Rcpp::runif(1, 0.0, 1.0);
if(rate >= 0){
probs[0] = rate;
}
//Access components
List out = clone(x);
List chrom = out["chrom"];
//Mutate weights and biases
for(int i = 0; i < chrom.length(); i++){
//Access the weights and biases
List chLayer = chrom[i];
NumericMatrix wt = chLayer["wt"];
NumericMatrix bi = chLayer["bi"];
//Mutate
int numInputs = wt.ncol();
LogicalVector doMut_wt = (Rcpp::runif(wt.size(), 0.0, 1.0) <= probs[0]);
LogicalVector doMut_bi = (Rcpp::runif(bi.size(), 0.0, 1.0) <= probs[0]);
for(int j = 0; j < wt.size(); j++){
if(doMut_wt[j]){
wt[j] = Rcpp::rnorm(1, 0.0, sqrt(0.5 * numInputs))[0];
}
}
for(int j = 0; j < bi.size(); j++){
if(doMut_bi[j]){
bi[j] = Rcpp::runif(1, -1.0, 1.0)[0];
}
}
}
//Mutate gamma and beta
NumericMatrix batch = out["batch"];
LogicalVector doMut_yb = (Rcpp::runif(batch.size(), 0.0, 1.0) <= probs[0]);
for(int i = 0; i < batch.size(); i++){
if(doMut_yb[i]){
batch[i] = Rcpp::rnorm(1, 0.0, 1.0)[0];
}
}
//Return
return(out);
}
//* Neural Net Prediction
//*
//* Environment:
//* env[0] = Position
//* env[1] = Total moves
//*
// [[Rcpp::export]]
NumericVector predictNN(
NumericVector env,
List chromosome
) {
//Initialize the output
NumericVector pred (1);
//Process environment
//Normalizing to be in [-1, 1]
NumericVector vIn (2);
vIn[0] = (env[0] / 5 - 1);
vIn[1] = 2 * (log(env[1] + 1) / log(2000)) - 1;
//Compute NN outputs
List chrom = chromosome["chrom"];
NumericMatrix batch = chromosome["batch"];
for(int i = 0; i < chrom.length(); i++){
//Access the layer
List chLayer = chrom[i];
NumericMatrix wt = chLayer["wt"];
NumericMatrix bi = chLayer["bi"];
//Calculate activation
NumericVector vOut (wt.nrow());
for(int j = 0; j < wt.nrow(); j++){
NumericVector wtVec = wt(j, _);
NumericVector biVec = bi(j, _);
NumericVector act = {sum(wtVec * vIn) + biVec};
vOut[j] = act[0];
}
//Apply batch normalization
if(vOut.size() > 1){
vOut = (vOut - mean(vOut)) / sd(vOut);
vOut = batch(i, 0) * vOut + batch(i, 1);
}
//Apply ReLU
for(int j = 0; j < vOut.length(); j++){
NumericVector relu = {0.0, vOut[j]};
vOut[j] = max(relu);
}
//Copy
vIn = clone(vOut);
}
//Record
pred[0] = vIn[0];
//Return
return(Rcpp::clamp(0.0, pred, 1.0));
}
//* NN Prediction to Action
// [[Rcpp::export]]
int predToResponse(NumericVector pred){
//Calculate response
double maxPred = max(pred);
IntegerVector response;
for(int i = 0; i < 4; i++){
if(pred[i] >= maxPred){
response.push_back(i);
}
}
int action = Rcpp::sample(response, 1)[0];
//Return
return(action);
}
//* Evaluate Chromosome
// [[Rcpp::export]]
NumericVector evaluatePolicy(
List chromosome,
int iters
) {
//Initialize parameters
NumericVector out (iters);
NumericVector pred (4);
//Run episodes
for(int i = 0; i < iters; i++){
//Episode parameters
NumericMatrix env = initEnv();
//Complete episode
bool done = false;
while(!done){
//Update state
for(int j = 0; j < 4; j++){
NumericVector state = env(j, _);
pred[j] = predictNN(state, chromosome)[0];
}
int a = predToResponse(pred);
env = updateEnv(env, a);
//Check victory condition
for(int j = 0; j < 4; j++){
if(env(j, 0) >= 10){
out[i] = envCost(env);
done = true;
break;
}
}
}
}
//Return
return(out);
}
```
]
|
[Question]
[
Let a counting tree be a rooted tree in which every node is labeled with the number of descendants it has.
We can represent such trees as ragged lists with each node being represented by a list containing its label followed by its children. For example the following is a counting tree:
```
[5,[2,[0],[0]],[0],[0]]
```
However the brackets themselves are redundant since the labels fully capture the structure of the counting tree. So we can represent them simply as lists of integers. The example above is:
```
[5,2,0,0,0,0]
```
However not all lists of integers represent a counting tree. For example:
```
[5,1,2,0,0,0]
```
This can't work because `2` must be a child of `1`, but it needs more descendants.
## Challenge
Take as input a non-empty list of non-negative integers and determine if it represents a counting tree as described above. Output one of two distinct consistent values, one if the input is a valid counting tree the other if it is not.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes.
## Test cases
## Valid
```
[5,2,0,0,0,0]
[5,2,1,0,0,0]
[5,2,1,0,1,0]
[5,3,1,0,0,0]
[6,5,4,3,2,1,0]
[0]
```
## Invalid
```
[0,0,0,0,0,0]
[5,2,1,1,0,0]
[5,2,0,1,0,0]
[5,3,1,0,1,0]
[6,2,1,0,0,0]
[5,3,1,0,0,1]
[5,2,3,0,0,0]
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 13 bytes
```
qCᵉLR↔<a*$h→L
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6FpsLnR9u7fQJetQ2xSZRSyXjUdsknyXFScnFUPkFN9dGm-oY6RhAYCwXmGeIwTOE8oyR5Mx0THVMgCJGUFkw1jHAMMsQiWeAxDNGMtkMzVaYPYZQfcZQOYirAQ)
---
Here is the original answer in an old version of Nekomata:
## [Nekomata](https://github.com/AlephAlpha/Nekomata/tree/07c871a41fe7a47b78da21b9fe1f06b1e5ded2c1) + `-e`, 16 bytes
```
qCᵉLR↔$-ᵐP∀*$h→L
```
This is a new golfing language I'm working on. It's still in a very early stage of development.
I haven't made the first release, so the link above is to the latest commit.
This is a non-deterministic language inspired by [Curry](https://curry.pages.ps.informatik.uni-kiel.de/curry-lang.org/), [Brachylog](https://github.com/JCumin/Brachylog) and other language. Functions in Nekomata may have multiple possible results, and the interpreter will choose the result via backtracking.
## Explanation
A port of [@Neil's Charcoal answer](https://codegolf.stackexchange.com/a/258011/9288).
```
qCᵉLR↔$-ᵐP∀*$h→L
# Take [5,2,0,0,0,0] as an example
# The stack is initialized with an infinite cycle of the input
q # Non-deterministically choose a contiguous subsequence of the input
# Take [2,0,0] as an example
# The stack is now ..., [5,2,0,0,0,0], [2,0,0]
C # Uncons; pop a list and push the tail and the head
# The stack is now ..., [5,2,0,0,0,0], [0,0], 2
ᵉL # Check if the length of the tail is equal to the head
# The stack is still ..., [5,2,0,0,0,0], [0,0], 2 since the check passes
R # Range from 1 to n
# The stack is now ..., [5,2,0,0,0,0], [0,0], [1,2]
↔ # Reverse
# The stack is now ..., [5,2,0,0,0,0], [0,0], [2,1]
$ # Swap
# The stack is now ..., [5,2,0,0,0,0], [2,1], [0,0]
- # Subtract
# The stack is now ..., [5,2,0,0,0,0], [2,1]
ᵐP # Check if all elements of the list are positive
# The stack is still ..., [5,2,0,0,0,0], [2,1] since the check passes
∀ # Find all possible results of a non-deterministic computation
# The stack is now ..., [5,2,0,0,0,0], [[3,4,3,2,1],[2,1],[],[],[],[]]
* # Multiply; this will fail if the two lists has different lengths
# The stack is now ..., [[15,20,15,10,5],[4,2],[],[],[],[]]
$ # Swap
# Note that there are infinite many copies of the input on the stack
# The stack is now ..., [[15,20,15,10,5],[4,2],[],[],[],[]], [5,2,0,0,0,0]
h # Head of a list
# The stack is now ..., [[15,20,15,10,5],[4,2],[],[],[],[]], 5
→ # Increment
# The stack is now ..., [[15,20,15,10,5],[4,2],[],[],[],[]], 6
L # Check if the length of the list is equal to the number
# The check passes, so there is a result
```
The flag `-e` set the interpreter to `CheckExistence` mode, which prints `True` if the computation has any result, and `False` otherwise. We don't care what the result really is.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes
```
ʀėṠ:Ẋ'ɖ↔ꜝnF;?ḣL≠∨
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiyoDEl+G5oDrhuoonyZbihpTqnJ1uRjs/4bijTOKJoOKIqCIsIiIsIls1LDIsMCwwLDAsMF1cbls1LDIsMSwwLDAsMF1cbls1LDIsMSwwLDEsMF1cbls1LDMsMSwwLDAsMF1cbls2LDUsNCwzLDIsMSwwXVxuWzBdXG5bMCwwLDAsMCwwLDBdXG5bNSwyLDEsMSwwLDBdXG5bNSwyLDAsMSwwLDBdXG5bNSwzLDEsMCwxLDBdXG5bNiwyLDEsMCwwLDBdXG5bNSwzLDEsMCwwLDFdXG5bNCwzLDEsMCwwLDBdIl0=)
Outputs a falsy value if it is a counting tree and a truthy if it's not.
Uses the fact that it is a counting tree iff
1. the first number is equal to the length of the rest of the list
2. for each pair of values `a`, `b` at indices `i`, `j` respectively the inclusive ranges `[i, i+a]` and `[j, j+b]` are either disjoint or one is a subset of the other
Get all inclusive ranges.
```
ʀ # elementwise inclusive range from 0
ė # enumerate
Ṡ # elementwise sum
```
Get all pairs and keep only those that don't satisfy 2.
```
: # duplicate
Ẋ # cartesian product
' ; # filter by:
# [[1,2,3],[3,4]]
ɖ↔ # scan by intersection [[1,2,3],[3]]
ꜝ # keep truthy [[1,2,3],[3]]
n # push argument [[1,2,3],[3]], [[1,2,3],[3,4]]
F # set difference [[3]]
# empty are falsy, non-emtpy are truthy
```
Check if 1. is not satisfied and combine the two.
```
? # push input
ḣ # head extract
L # length
≠ # not equal
∨ # or
```
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/index.html), 36 bytes
```
f[0]=1
f(a:b++c)=f b*f(a-length b:c)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m706ubSoqDK-IDE7uXjBgqWlJWm6FjdV0qINYm0NudI0Eq2StLWTNW3TFJK0gDzdnNS89JIMhSSrZE2I2m25iZl5CrYKaQrRpjpGOgYQGAuRhBkIAA)
[Answer]
# [Python](https://www.python.org), 63 bytes
```
f=lambda T,*t:T!=len(t)or T>0<f(T-(x:=t[0]+1),*t[x:])|f(*t[:x])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY37dNscxJzk1ISFUJ0tEqsQhRtc1LzNEo084sUQuwMbNI0QnQ1KqxsS6INYrUNNYFKoiusYjVr0jSALKuKWE2oMappQA05Cpl5CvkFQP0GmlZcCgVFmXklGkCVqWWJORo5mppQxQtuLog21THSMYDAWC4wzxCDZwjlGSPJmemY6pgARYygsmCsY4BhliESzwCJZ4xkshmarTB7DGO5IA4FAA)
Returns False for trees and True for fakes.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~28~~ 23 bytes
```
∧⁼§θ⁰⊖Lθ⬤θ⬤✂θ⁺ικκ±¹¬›λμ
```
[Try it online!](https://tio.run/##HYrBCsIwEER/JccNrNAKnjwFFBGkFDyWHkKytKHblKSp@PcxcWAYHm/MrKPZNOfcR@cTKG/hHg7NO6j09Ja@EFA0EsWNTKSVfCILL/JTmiFIWYRirp86b3aGKvR87OBQLMUvKDqadCJo673bEjwiFY7AKFb5zzXnYbjgGVtsascxnz78Aw "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a counting tree, nothing if not. Explanation: Based on @AndrovT's approach, the first element must be one less than the length, then given any element `e`, the next `e` elements must all be less than the sequence from `e` down to `1`, although the code actually extracts the elements in reverse so that within their slice they must not exceed their 0-based index.
```
θ Input array
§ ⁰ First element
⁼ Equals
θ Input array
L Length
⊖ Decremented
∧ Logical And
θ Input array
⬤ All elements satisfy
θ Input array
✂ Sliced from
ι Current value
⁺ Plus
κ Current index
κ To current index
±¹ In reverse
⬤ All elements satisfy
λ Inner value
¬› Is not greater than
μ Inner index
Implicitly print
```
Example: For the input `[5,2,1,0,1,0]`, the length is `6` so the first element must be `5`, then the subsequent `5` elements must be less than `5,4,3,2,1`; the `2` elements after the `2` must be less than `2,1` and the `1` element after each `1` must be less than `1`. (Trivially the `0` elements after each `0` satisfy the property as well.)
Previous 28-byte approach:
```
Fθ«⊞υιW∧υ¬↨υ⁰≧⁻¬⊟υυ¬υ»¿∨υ⊖ⅈ⎚
```
[Try it online!](https://tio.run/##JYw9C8IwFEXn5ldkfIEIVXDqVO1aLU5C6RDatHkQk5oPHcTfHhu8cOFyuJxRCTdaoVOaraPwZPRDii56BZFTZBUp3gq1pFCbKaOLDXASXuZdsi20FWvtPS7mhosK0KKJ/v/r7AqRMU5j9nQOTYDMN1aRL8GZwtVlUSNHJx/SBDnBHbL0rKVwwKqU@v7ID3zPy9xhSLuX/gE "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a counting tree, nothing if not. Explanation:
```
Fθ«
```
Loop over the input integers.
```
⊞υι
```
Push them to the predefined empty list.
```
W∧υ¬↨υ⁰
```
While the list ends in `0`...
```
≧⁻¬⊟υυ
```
... remove the trailing `0` and decrement the remaining elements.
```
¬υ
```
Count the number of counting trees found.
```
»¿∨υ⊖ⅈ⎚
```
Check that there was exactly one counting tree and that it ended with the last element.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 61 bytes
```
\d+
$*
+%`^((1)*)1(1*),(\1(?!1)(?<-2>,1*)*)(?(2)^)
$4¶$3
^¶*$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFi0tbNSFOQ8NQU0vTUMNQS1NHI8ZQw17RUFPD3kbXyE4HKKQFZGsYacZpcqmYHNqmYswVd2iblsr//6Y6RjoGEMgFYhuisQ3BbGO4uJmOqY4JkA@W5QJCHQM0/YZwtgGcbQw3ywzFDpi5hgA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Port of @alephalpha's Curry answer.
```
\d+
$*
```
Convert to unary.
```
+%`^((1)*)1(1*),(\1(?!1)(?<-2>,1*)*)(?(2)^)
$4¶$3
```
Repeatedly split each rooted tree into its first branch and remaining branches.
```
^¶*$
```
Check that there are only twigs left.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒʒćsgQ}εāR‹}˜P*ćsgQ
```
Inspired by [*@Neil*'s top Charcoal](https://codegolf.stackexchange.com/a/258011/52210), which is a port of [*@AndrovT*'s Vyxal answer](https://codegolf.stackexchange.com/a/258020/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//6KRTk460F6cH1p7beqQx6FHDztrTcwK0wEL//0eb6RjpGOoYgGAsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/6OTTk060l6cHlh7buuRxqBHDTtrT88J0AIL/df5Hx1tqmOkYwCBsTpgniEGzxDKM0aSM9Mx1TEBihhBZYFYIdpAxwDDMEMkngESzxjJaDM0a2EWGUL1GUPlYgE).
**Explanation:**
```
Œ # Get all sublists of the (implicit) input-list
ʒ # Filter it by:
ć # Extract head; pop and push remainder-list and first item seperately
s # Swap so the remainder-list is at the top of the stack
g # Pop and push its length
Q # Check if the length of the remainder-list and first item are equal
}ε # After the filter: map over each remaining sublist:
ā # Push a list in the range [1,length] (without popping the list)
R # Reverse it to [length,1]
‹ # Element-wise less-than check: [a<length,b<length-1,...,y<2,z<1]
}˜ # After the map: flatten the list of checks
P # Product to check if all were truthy
* # Multiply this 1/0 to each value in the (implicit) input-list
ćsgQ # Do a similar check as before within the filter on the input-list itself
# (after which the result is output implicitly)
```
I've been unable to find anything shorter for `*ćsgQ` which works for both the `[0,0,0,0,0,0]` and `[6,2,1,0,0,0]` test cases. Checking whether the input-list is in the filtered list of sublists is an equal-bytes alternative:
```
ŒéʒćsgQ}¤IʪεāR‹}˜P
```
[Try it online](https://tio.run/##yy9OTMpM/f//6KTDK09NOtJenB5Ye2iJ5@GuQ6vObT3SGPSoYWft6TkB//9Hm@kY6RjqGIBgLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/6OTDq88NelIe3F6YO2hJZWHuw6tOrf1SGPQo4adtafnBPzX@R8dbapjpGMAgbE6YJ4hBs8QyjNGkjPTMdUxAYoYQWWBWCHaQMcAwzBDJJ4BEs8YyWgzNGthFhlC9RlD5WIB).
**Additional explanation:**
```
é # Sort the sublists by length (shortest to longest)
¤ # Push the last sublist after the filter (without popping the list of lists)
IÊ # Check that it's NOT equals to the input-list
ª # Append this 0 or 1 to the list of sublists
# (`āR‹` will succeed for 0 and fail for 1)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 64 bytes
```
T=t=>t.shift()!=t.length|C(t)
C=$=>$>C&&C($.splice($[0]+1))|T($)
```
[Try it online!](https://tio.run/##hY@9CoMwFIV336IQJJemIdHqFpe8gps4iI0/JSTShE6@e1oo7VKN3PE7H@eee/fsXP@YF38x9qbCIEItvKg8ddM8eAwn4alWZvTTKrGHRAokKlTJNJUYUbfouVcYNaw9c4C1xghCb42zWlFtRzzgpiAZYZ9rAZINyg8p36F5xC1JQa7vRLZl/6UZYYdf8ghlEZpHNpQH@78L@U5v/nPDCw "JavaScript (Node.js) – Try It Online")
Code with comments:
```
isTree = tree =>
tree[0] + 1 === tree.length &&
isChildren(tree.slice(1))
isChildren = children =>
children.length === 0 ||
isTree(children.slice(0, children[0] + 1)) &&
isChildren(children.slice(children[0] + 1))
```
Changing `!=` into `-` makes it 64 bytes by returning truthy vs. falsy.
~~-1~~-2 byte by l4m2.
[Answer]
# [Haskell](https://www.haskell.org), ~~85~~ 65 bytes
*-20 bytes thanks to [@Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)*
```
h(n:w)=f(n:take n w)&&h(drop n w)
h _=1>0
f(n:w)=h w&&n==length w
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jZG_CsIwEMZxzVPcIKWFKI3VIkIEFzc3wUGkBE1NscbSRAruPoWLi_hM-jQG459SKkjgjvvxcffl7nQVTG14mp7Pl72OW_3bSLhyUHg0NkmzDQcJhec4wl3lu-xZIAERJUMfxVYpoHAcSWnK5Vqbwja6N46aKx0tmeIKKAKYw7yHO9i3b2EItoTUElIiQUUT4h7uGtopqT4Z-7UzSIX4FRJUpoY1zt4-SKlP8NUsEGJSFTx_fXia7zn-GcYsVX9F03bLEgkUtiybRJDlidTQhEOSzRKzcdel1IM2xB6UVv5yYq_xPu8D)
[Answer]
# [tinylisp 2](https://github.com/dloscutoff/tinylisp2), 88 bytes
```
(d F(\(L)(? L(*(<(h L)(# L))(F(](h L)(t L)))(F([(h L)(t L))))1
(\(L)(*(F L)(=(h L)(#(t L
```
The submission is the anonymous function in the second line.
You can try it at [Replit](https://replit.com/@dloscutoff/tinylisp2). Example session:
```
tl2> (d F(\(L)(? L(*(<(h L)(# L))(F(](h L)(t L)))(F([(h L)(t L))))1
F
tl2> (\(L)(*(F L)(=(h L)(#(t L
(() (L) (* (F L) (= (h L) (# (t L)))))
tl2> (d G _)
G
tl2> (G (list 5 2 1 0 1 0))
1
```
### Explanation
Our recursive helper function, `F`, analyzes a list as follows:
* Is it empty? Return `1` (truthy).
* Otherwise, split the list, conceptually, into head (first element) and tail (remaining elements).
+ Is the head greater than or equal to the list's total length? (This means the root of this subtree doesn't have enough children.) Return `0` (falsey).
+ Split the tail at the index given by the head. Recurse over each of these sublists. Return `1` if both results are `1`; otherwise return `0`.
```
(d F(\(L)(? L ... 1)))
(d F ) ; Define F as
(\(L) ) ; Lambda function taking list L
(? L ) ; If L is nonempty
... ; (see below)
1 ; Else, return 1
(*(<(h L)(# L))(F(](h L)(t L)))(F([(h L)(t L))))
(* ) ; Multiply these (logical AND):
(<(h L)(# L)) ; 1. Head of L < length of L
(F ) ; 2. Recursive call on:
(] ) ; Take
(h L) ; (head of L) elements
(t L) ; from tail of L
(F ) ; 3. Recursive call on:
([ ) ; Drop
(h L) ; (head of L) elements
(t L) ; from tail of L
```
`F` verifies that a list represents a "forest" of zero or more counting trees concatenated. Our main function also needs to verify that we have exactly one counting tree. To do so, we first call `F` on the list, and then check whether the head is exactly equal to the length of the tail.
```
(\(L)(*(F L)(=(h L)(#(t L)))))
(\(L) ) ; Lambda function taking list L
(* ) ; Multiply these (logical AND):
(F L) ; 1. Call F on L
(= ) ; 2. These are equal:
(h L) ; Head of L
(#(t L)) ; Length of tail of L
```
[Answer]
# JavaScript (ES6), 75 bytes
Returns \$0\$ for valid, or \$1\$ for invalid.
```
f=([v,...a],s=v)=>v+1&&a.length!=s|f(a.slice(v=a[0]),s-++v)|f(a.slice(0,v))
```
[Try it online!](https://tio.run/##hZCxDoIwGIR338IF2vDTtCBsdfcFXGqHBgpimmIs6eS7V6PRYGIh/3bfXf7cXZRXrrkN1ym3Y6tD6DgSHgghSoLjHvO9z1iSKGK07afzlrt7hxRxZmg08lwJKjG4PMs8ngEKHuPQjNaNRhMz9igVR2WGVqZ4M5c7JCoogL5P4r@UrVIWoeVCtoYKdk9HEUm/tB8xPVlxsD7SgwJd7cEWKF2g5ULLemWhzwYs8rf8ZsMD "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 147 bytes
```
(a=#;l=Length@a;And@@(IntervalMemberQ[#1,#2]||Length@IntervalIntersection[#1,#2]==0&@@@Subsets[Interval@{#,#+a[[#]]}&/@Range@l,{2}])&&a[[1]]==l-1)&
```
[Try it online!](https://tio.run/##PYvLCoMwFET3/Y1AUHpLE/vYSOB2WWihj2XIItpgBE1B0240325FtMxiYM6ZWntrau3LXA9WDJEWJK3ExbjCW9Tpyb0Qo7Pzpvnq6mrqzDR3STiQRPX9rC146tbkvny72RGCUUR8frLW@FYuJnYEyFpLSZQKdIsP7QqDFXRJUDGlI@Bq/FYbHtPh1pTOo8XuAAnwMQxYWP3XIxxgD7uJsTD8AA "Wolfram Language (Mathematica) – Try It Online")
I was looking at the problem in terms of interval arithmetic, and it seems got the same algorithm as @AndrovT. Unfortunately, Mathematica has almost no shorthands for cool functions, so code looks huge (
Explained:
```
(*Total logic And*)
And @@
(*In True case intervals must be disjointed or nested*)
(IntervalMemberQ[#1, #2] ||
Length@IntervalIntersection[#1, #2] == 0 & @@@
(*All subsets length 2*)
Subsets[
(*All intervals i + array[i]*)
Interval@{#, # + a[[#]]} & /@ Range@l
, {2}])
(*Is first element equal length of the rest*)
&& a[[1]] == l - 1 &
```
]
|
[Question]
[
[proposed by @Adám in chat](https://chat.stackexchange.com/transcript/message/62831208#62831208)
Given an even number of finite points return a line \$y=mx+b\$ that evenly splits the points on both sides.
## Specs
* Take a list of distinct points \$(x,y)\$ (or a list of x-coordinates and a list of y-coordinates), output a possible \$(m,b)\$ pair
* Half of the points should be true for \$y>mx+b\$, the other half should be true for \$y<mx+b\$
* All \$x, y\$ pairs are integers
* There will always exist a line \$y=mx+b\$ which divides the points, in which \$m\$ and \$b\$ are integers, but you can output rationals
## Test cases
```
[(1, 1), (-1, -1)] -> -1, 0
[(0, 0), (2, -3)] -> 1, -3
[(3, 4), (0, 0), (-2, -6), (4, -5), (-2, 1), (-23, -18)] -> (-2, -1)]
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~22~~ 21 bytes
```
Þn:Ẋλ⁰∩YṘ÷*+-±₌A∑¬∧;c
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnm464bqKzrvigbDiiKlZ4bmYw7cqKy3CseKCjEHiiJHCrOKIpztjIiwiIiwiWyg1LCAyKSwgKDQsIDMpXSJd)
*-1 byte:* Fixed a bug and saved a byte thanks to *@KevinCruijssen*
Simply tries all integer pairs until one works.
```
Þn # all integers
: # duplicate
Ẋ # cartesian product
λ ;c # find first pair [m,b] such that:
⁰∩ # transposed input [x-coords, y-coords]
Y # interleave [m, x-coords, b, y-coords]
Ṙ # reverse [y-coords, b, x-coords, m]
÷ # push each to stack
* # multiply
+ # add
- # subtract
± # sign
₌A∑¬∧ # are all non zero and is the sum 0?
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~39~~ 38 bytes
```
`,Xrk]XJxXIx0G"1@g0Jh-lIh&v0&|ZS/+]]IJ
```
Input is a cell array of 1×2 vectors. Output is `m`, then `b`.
This produces a random output among all valid outputs, possibly different in each run. Running time is also random, but the code ends in finite time with probability 1.
[**Try it online!**](https://tio.run/##y00syfn/P0Enoig7NsKrIsKzwsBdydAh3cArQzfHM0OtzECtJipYXzs21tPr///qaGMdBZNYHYVoAx0FAxCta6SjoGsGYpkAGaYwIUMIA6ha19AithYA "MATL – Try It Online")
Or try at [**MATL Online**](https://matl.io/?code=%60%2CXrk%5DXJxXIx0G%221%40g0Jh-lIh%26v0%26%7CZS%2F%2B%5D%5DIJ+++++++++%25+required+code%0AG%21gt1Z%29XKw2Z%291j%2a%2B%27%2a%27%26XG1%241%231ZG2%3A%29tI%2aJ%2Bl3ZG%26XG++%25+plot+points+and+line&inputs=%7B%5B3%2C+4%5D%2C+%5B0%2C+0%5D%2C+%5B-2%2C+-6%5D%2C+%5B4%2C+-5%5D%2C+%5B-2%2C+1%5D%2C+%5B-23%2C+-18%5D%7D&version=22.7.4) including a plot with the points and the solution line.
### How it works
The code randomly picks integer values for `m` and `b` until a solution is found. The choice of each of those two values follows a *normalized Gaussian distribution* rounded down. This ensures that each integer pair has a non-zero probability, and will eventually be tried with probability 1.
For each `m` and `b`, the value `b` is first subtracted from the *y*-coordinate of all points. This has the effect of shifting the line vertically so now it passes through the origin with direction given by the vector `[1, m]`.
To test which side of the line a point `[x, y]` is in, the *vector product* of `[1, m]` and `[x, y]` is computed. This is equivalent to the *determinant* of the 2×2 matrix formed by those vectors. The *sign* of the result indicates the side, with a 0 meaning that the point is exactly on the line. Thus, a line is valid if and only if the sum of all signs is 0 and no sign was 0. This is tested by computing the sum of the *inverses* of the signs and checking if it is 0 (if a sign is 0 the sum will give an infinite result).
[Answer]
# [Python](https://www.python.org), 54 bytes
```
lambda L:[m:=1+L.ptp(),sorted(L@[-m,1])[len(L)//2]-.5]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NVBBasMwELz7FXvcTVaO7CYhGAx9gE65qiIkJE4NkSxkB-J-pZdAaf_Ut_RSqW4OywzDzDLM-5cfh9fO3T-a-uXzOjRi872-7O3huAdVaVvVxVzlfvBI3HdhOB1RPWthuTCkLyeHihaL0oh8Zf7TP03oLLir9SO01scMhB2HvTt2lvv27LKmC6CgdYAZaHxiWBIDSgaZUJQMYp3YMpLVQyomEt2i2JDhDKaXeYLWDSgKKTkdlpJLoujQWrIoDEeQJkWoysDyAWpoMOy0MpSBDykd1ci3tcbbX0m0s9v8IEYiSHVvPKbCyjz8_dWinr21HmdbMjquUdeSpgnu9wl_AQ)
Takes an Nx2 NumPy array.
Slightly longer but more readable version:
# [Python](https://www.python.org), 58 bytes
```
lambda L:[m:=1+ptp(L),median(L@[-m,1])]
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVDBSsQwFLz3K94x6b5IUldZCgE_IKe9xrC01K4Bk4ZsC62_4qUg-k9-ixcT6548PGZ4b-YxzNtnWMbnwa_vvXz8mMaeHb7ql8a1XQOq1q6WYhfGQBRF99TZxhP1oJlDYagp-jg48JMLC1gXhjiWfx--_10gnjA2vhscXuzZF_0QQYH1QArQ5BZhTxEIR-AZWYXA7jPbJ3J3XYmNJDUTB2qwgO3lTQbrR8IE55iHVBwrSpNCa45MGEzATbbQugCHLUjoSTxpZWgBIWZ32iZ-lJrMvyGJK-ddyxZKIcedccmBlbnqL5Mjuny1gZRHanSqREpOtwrWdcMf)
### How?
This chooses a slope larger than the "diameter" of the given point cloud to avoid any ties.
[Answer]
# [Python](https://www.python.org), 169 bytes
```
def g(P,*p):
a,b,c=p or[0]*3
for i,(x,y)in enumerate(P):l=2*(i<len(P)/2)-1;q=a*x+b*y+c;v=(q*l<=0)*(l-q);a+=v*x;b+=v*y;c+=v;z=a,b,c
return z!=p and g(sorted(P),*z)or z
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc49DoIwHAXwnVPUrf1TIuJiKL0Du3EoUJQEC9RCaK_iwqKJR_I21q_p5S3v_a733ppTp5blNpo62j0flazREecUepIGSNCClrxHnd7HB9gGqO40aiieqSWNQlKNZ6mFkTgnacsTwE3WSuXbOiHRhg1cwBwWYMOSTRwP0GY8JoDbaCBMhHyCmRXvsKz0wRz_HAZISzNqhdzKfwtVedGl00ZWfpmCIx7hvuCf--9_AQ)
Sort of cheating, since it outputs the values \$(a,b,c)\$ defining the line \$ax+by+c=0 \Rightarrow y = (-ax-c)/b = -\frac{a}{b}x - \frac{c}{b}\$.
Explanation to be added later, but in brief:
* Sorts the points, then says that the first half of the list is in one group and the second half is in another (I believe this always produces two sets which are separable, but I haven't proved it).
* Uses a perceptron algorithm to find the line which classifies those points.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
A lot of bytes, and extra computation, to effectively break on the first found solution :(
```
×Ṛ_+⁸ṪṠ
ŒRṗ2çⱮS¬ȧẠƲ¥Ƈ
1ç1#Ṫç⁸Ḣ
```
A monadic Link that accepts a list of the coordinates that yields a pair of integers, \$[m, b]\$.
**[Try it online!](https://tio.run/##y0rNyan8///w9Ic7Z8VrP2rc8XDnqoc7F3AdnRT0cOd0o8PLH21cF3xozYnlD3ctOLbp0NJj7VyGh5cbKgOVAeWAyncs@v//f7SGgY6Bpo6GIZCMBQA "Jelly – Try It Online")**
### How?
```
×Ṛ_+⁸ṪṠ - Link 1 side of the line: L=[m, b]; P=[x, y]
× - (L) multiply (P) -> [mx, by]
Ṛ - reverse (that) -> [by, mx]
_ - subtract (P) -> [by-x, mx-y]
⁸ - chain's left argument = L
+ - add -> [by-x+m, mx-y+b]
Ṫ - tail -> mx-y+b = (mx+b)-y
Ṡ - sign -> 1 (below), 0 (on), or -1 (above)
ŒRṗ2çⱮS¬ȧẠƲ¥Ƈ - Link 2 find solutions: integer k, coordinates C
ŒR - span-range -> [-abs(k)..abs(k)]
ṗ2 - second Cartesian power -> all [m,b] using values from -k to k
Ƈ - filter keep those for which:
¥ - last two links as a dyad - f(L=[m,b], C)
Ɱ - map (across each coordinate pair, P, in C) with:
ç - call Link 1 - f(L, P) -> side of the line
Ʋ - last four links as a monad - f(A=that):
S - sum (A)
¬ - logical NOT (that)
Ạ - all (A)?
ȧ - logical AND
1ç1#Ṫç⁸Ḣ - Link: coordinates C
1 - set the left argument to one
1# - find the first one integers, k (incrementing), for which:
ç - call Link 2 - f(k, C) -> empty lists are falsey
Ṫ - tail -> get the k value found
⁸ - chain's left argument = C
ç - call Link 2 - f(found k, C)
Ḣ - head (that)
```
[Answer]
# Python3, 268 bytes:
```
import math as M,statistics as S
K=lambda p,x,y:(m:=M.tan(S.median([M.atan2(Y-y,X-x)for X,Y in p])),y-m*x)
def v(p,x,y):
t=[0,0]
for X,Y in p:t[Y<(x*X+y)]+=1
return t[0]==t[1]
f=lambda p:[R for t in p for T in p-{t} if v(p,*(R:=K(p,(t[0]+T[0])/2,(t[1]+T[1])/2)))][0]
```
[Try it online!](https://tio.run/##XY7NboMwEITvfoo9esFOMaRVhOoniLgkOSRCHNwSFEvlR7CtQFGendpEaaterG9mdmfdTXRpm2TT9fNs667tCWpDFzADZGIgQ3Yg@z54vWdb/WHqt9JAJ0YxpbxOdbYi0/D9qj6X1kGerYwzYn6SkzjKEau2h6M4gW2gKxDFJOtgRFaeK/jiSw2mDEjnkYgKBn/HU8pPr3wMjuGERagVg/5Mn30DlEeF1pSrglU/P0rz3bJNy@6ChwXllW5g7@cCvkv11gH3HeHBPfgUe6W8Ul4hYuH8uettQ7ziV64EKBTApQOp8IbIfsNIQOTD2GXJvywRsPbZY0b6oRdPawfPD@teHie@feMr5m8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes
```
≔Eθ↨ι⁰η≔⊕⁻⌈η⌊ηηW⁻Eθ↨κ±ηυ⊞υ⌊ιI⟦η⁻§υ⊘Lυ·⁵
```
[Try it online!](https://tio.run/##RY@xDoIwEIZ3n6LjNSmGaJyc0EUSMeyEocELbSxVaYu8fT0Iyna5//u/3DVK9s1Tmhgz53RroZAveAt2kg5BC5ZyLpjix80S57bpsUPr8Q6FtsFRYdRd6EARSJtl/tU@Shtkf3R1PwS7YSs9LnDgnJXBKQirRnMylL22Hs7SeajUnJEp87m94zjBF2kGOuaKtvXUnmXp9sBrKsdYVZBOXwgGO8GSPa/rmAzmCw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Inspired by @loopywalt's NumPy answer.
```
≔Eθ↨ι⁰η≔⊕⁻⌈η⌊ηη
```
Calculate `m` as the incremented maximum `y` extent between any two points.
```
W⁻Eθ↨κ±ηυ⊞υ⌊ι
```
Calculate and sort what the `y`-intercepts would be for lines of gradient `m` that pass through each point. (These must all be different due to the size of `m` calculated above.)
```
I⟦η⁻§υ⊘Lυ·⁵
```
Output `m` and a `y`-intercept that divides the set of points into two.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞<D(.ιæ2ù.ΔIø.ιR`*+-DĀPs.±O_*
```
Port of [*@AndrovT*'s Vyxal answer](https://codegolf.stackexchange.com/a/257880/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//Ucc8GxcNvXM7Dy8zOrxT79wUz8M7gLygBC1tXZcjDQHFeoc2@sdr/f8fHW2sYxKrE22gYwAkdY10dM2AtImOrimEawimjHV0DS1iYwE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeWilvZLCo7ZJCkr2/x91zLNx0dA7t/PwMqPDO/XOTTm07vAOIDcoQUtb1@VIQ0Cx3qGN/vFa/2t1/kdHRxvqGMbqROsa6ugaxsbqKERHG@gYAAWMdHSNIXxjHRMgHyKqCxQ2A9ImOrqmEC5Ys5ExULdFbGwsAA).
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
< # Decrease it to a non-negative list: [0,1,2,...]
D( # Push a negative copy: [0,-1,-2,...]
.ι # Interleave the lists together: [0,0,1,-1,2,-2,...]
æ # Get the powerset of this list
2ù # Only keep all pairs: [[0,0],[0,1],[0,1],[0,-1],[0,-1],[1,-1],[0,2],...]
.Δ # Pop and keep the first pair [m,b] that's truthy for:
Iø # Push the transposed/zipped input-list, swapping its rows/columns
.ι # Interleave it with the current pair: [m,x-coords,b,y-coords]
R` # Push it in reversed order to the stack
* # Multiply m to the x-coords
+ # Add b to each
- # Subtract each from the y-coords
DĀPs.±O_* # Check that there is an equal amount of positive/negative values and no 0s:
D # Duplicate the list
Ā # != 0 check on each
P # Product to check all are truthy
s # Swap so the list is at the top again
.± # Signs of each integer
O # Sum them together
_ # ==0 check
* # Check if both are truthy
# (after which the found [m,b]-pair is output implicitly)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 162 bytes
```
Catch[n=0;While[True,m=(-1)^n⌊(n+1)/2⌋;a=#[[2]]-m#[[1]]&/@#1;Do[If[Values@CountsBy[b-a,Sign]=={#2,#2},Throw[{m,b}]],{b,Range@@MinMax@a}];n++]]&[#,Length@#/2]&
```
[Try it online!](https://tio.run/##NYzRSsMwGEZfpRAYG/1DmzhFKIHgvBEciA69CBHSkTaB9S90KSohL6B7yr1I7RCvzuHj8HUmONuZ4PdmasS0MWHvFIqyenP@YNVuGC10YknZ6h3Pp@8l5mxV8PPppzKCKMW1pt1MpvWikIRV9716aNSrOYz2KDf9iOF496VqauDFt6iFiIQD4Ql2bug/VOygTlpDrOHZYGul3Hrcmk9pkq4wz@dbReDRYhucJAXXi@lp8BhkI2O8gmydIIslZOWFlENGby62nuX6f2J/MteU3aY0/QI "Wolfram Language (Mathematica) – Try It Online")
Start from \$m = 0\$. Going through \$0, -1, 1, -2, 2, …\$ ([OEIS A130472](https://oeis.org/A130472))
Find \$b\_{min}\$ and \$b\_{max}\$ that bounded array of points with given \$m\$ (here \$m = -2\$):
[](https://i.stack.imgur.com/8ngJK.jpg)
Scan from \$b\_{min}\$ to \$b\_{max}\$. If the test line halves the array and does not pass through any point then throw-catch `{m,b}`. Else test the next \$m\$.
Fast and reliable algorithm, find \$m\$ closest to \$0\$, so solution for the last test case is `{0, -4}` (but we can start from any other value).
Ungolfed version:
```
halfline[pts_] := With[{h = Length@pts/2},
n = 0;
Catch[
While[True,
m = (-1)^n ⌊(n + 1)/2⌋;
arr = #[[2]] - m #[[1]] & /@ pts;
Do[
If[Values@CountsBy[b - arr, Sign] == {h, h},
Throw[{m, b}]
]
, {b, Range @@ MinMax@arr}];
n++
]
]
] /; MatrixQ[pts, IntegerQ];
```
]
|
[Question]
[
A [band matrix](https://en.wikipedia.org/wiki/Band_matrix) is a matrix whose non-zero entries fall within a diagonal *band*, consisting of the main diagonal and zero or more diagonals on either side of it. (The [main diagonal](https://en.wikipedia.org/wiki/Main_diagonal) of a matrix consists of all entries \$a\_{i,j}\$ for which \$i=j\$.) For this challenge, we will only be considering square matrices.
For example, given this matrix:
```
1 2 0 0
3 4 5 0
0 6 0 7
0 0 8 9
```
this is the band:
```
1 2
3 4 5
6 0 7
8 9
```
The main diagonal (`1 4 0 9`) and the diagonals above it (`2 5 7`) and below it (`3 6 8`) are the only places non-zero elements are found; all other elements are zero. (Some of the elements in the band may also be zero.)
The *bandwidth* of the matrix is the smallest number \$k\$ such that all non-zero elements are contained within a band consisting of the main diagonal, \$k\$ diagonals above it, and \$k\$ diagonals below it. The bandwidth of the above matrix is 1: all non-zero elements fall within the main diagonal, the one diagonal above it, or the one diagonal below it. For another example:
```
1 1 0 0
1 1 1 0
1 1 1 1
0 1 1 1
```
The bandwidth of this matrix is 2, because it takes two diagonals above and below the main diagonal to catch all non-zero elements:
```
1 1 0
1 1 1 0
1 1 1 1
1 1 1
```
Note that for the purposes of this challenge, the band must extend the same distance on either side of the main diagonal, which is why the diagonal `0 0` is included above.
Mathematically, the bandwidth is the smallest number \$k\$ such that for every entry \$a\_{i,j}\$ in the matrix, \$a\_{i,j} = 0\$ if \$|i-j|>k\$.
## Challenge
Given a square matrix containing nonnegative integers, output its bandwidth.
The matrix will always have at least one nonzero entry.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): make your code (measured in bytes) as short as possible.
## Test cases
```
1
=>
0
1 0 0
0 1 0
0 0 1
=>
0
1 2 0 0
3 4 5 0
0 6 0 7
0 0 8 9
=>
1
1 1 0 0
1 1 1 0
1 1 1 1
0 1 1 1
=>
2
16 18 8
6 14 22
20 10 12
=>
2
0 0 0 1 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
=>
3
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ŒṪIAṀ
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7V3k6PtzZ8P9w@6OmNf//R3NFRxvGxupwgWgdAx0DIFMh2kDHEM4CsuHyRnAVxjomOqZwNWZAcXO4egsdS7gOhJkgtiEK2xBulyHCDjMdQwsdC7AMkGmiY2QEZEcbAVUBkRFUFcgWVDcaILmdGF4sVywA "Jelly – Try It Online")
```
ŒṪ -- indices of non-zero values
I -- reduce each index by subtraction
A -- get the absolute values
Ṁ -- select the maximum
```
[Answer]
# [R](https://www.r-project.org/), 38 bytes
```
function(A)max(abs(row(A)-col(A))*!!A)
```
[Try it online!](https://tio.run/##lU7LDsIgELzzFdsbazBhqfVx8NBPwRpME9smtMb@PS4UTUy9mCxhZlhmxgcHZwju0TdTO/Syxs7O0l5G6Ycns20z3PnCTVHUGJzs7OTbWZIiRCGcvLb2xqxcWH5tWAGjQMcRpYKdgiphVvZJPyTMc1RwQt5YG9DbYMH0jSkZZPzLgHOIzTlAxEziDsYoYeKveAyuWuucmLM@VP9LuU@FGF4 "R – Try It Online")
Test harness taken from [Robin Ryder's answer](https://codegolf.stackexchange.com/a/243456/67312).
R has [some weird built-ins](https://codegolf.stackexchange.com/a/219617/67312). Given a matrix `M`, `row` will return a matrix of the same size with each entry equal to its row number, and `col` likewise, but with columns. That is, \$row(M)\_{ij}=i\$ and \$col(M)\_{ij}=j\$. So `abs(row(A)-col(A))` gives us a matrix of possible bandwidths like so for a \$5\times 5\$ matrix:
```
[,1] [,2] [,3] [,4] [,5]
[1,] 0 1 2 3 4
[2,] 1 0 1 2 3
[3,] 2 1 0 1 2
[4,] 3 2 1 0 1
[5,] 4 3 2 1 0
```
Then we "filter" the entries where `A` is nonzero and take the maximum to obtain the bandwidth.
[Answer]
# [R](https://www.r-project.org/), ~~41~~ 40 bytes
-1 byte thanks to Giuseppe
```
function(A)max(diff(t(which(t(A)|A,T))))
```
[Try it online!](https://tio.run/##lVC7DsIwDNzzFR5jyUOdUh4DQ/@BH6iKQjO0SFURHfj3ckkDEoKFyFHuHOfulHHxdKTF34Z2CtfB1tw3sz0H7@1k711oO5w1P2o5Mdbibd9MY5itijIb4zHbXMDKleXbFh1yQkUsUwpthKqE0dmm/i5h1F7owJj4FtCXwIr1E2sSyPiXAHwU4jAw0VORwTkxLr6K2/FX6iI7Zq83Lf6lyFPhu54 "R – Try It Online")
Note that the matrix \$A|A^T\$ has the same bandwidth as the matrix \$A\$, but is symmetrical. We can therefore consider only its lower-triangular part, for which row index is greater than column index.
The formula given in the question is \$\max(|i-j|)\$ such that \$A\_{ij}\neq 0\$; this is equivalent to \$\max(i-j)\$ such that \$(A|A^T)\_{ij}\neq 0\$ (without the absolute value). The call `which(x,T)` returns a 2-column matrix listing the row and column indices of all `TRUE` values in `x`; we need to transpose the output since `diff` acts column-wise.
This saves 3 bytes compared to the more obvious strategy:
```
function(A)max(abs(which(!!A,T)%*%c(1,-1)))
```
Edit: [Outgolfed](https://codegolf.stackexchange.com/a/243509/86301) by Giuseppe's 38 byte answer.
[Answer]
# Python 3, 68 bytes
```
lambda a,e=enumerate:max(abs(i-j)for i,r in e(a)for j,c in e(r)if c)
```
[Try it online!](https://tio.run/##fY5BbsMgEEX3nGJ2gYpGgNPUjeRepK4q4mCFyMYIiNqe3mWwk@wqYcb/z5s/@N90nlxV@zD3TTsPejyeNGhuGuOuowk6mcOof6g@RmqfL6yfAliePweG6iIvvFtkYLaHjs1odjoadCdvHBVsG4w@UbaNfrCJblrXug07EICnMH1HDl8cgonXIUFTRh/ghmUKodz5GGxMdNSeWpc4uivHGAPcmh1civgnjt0iM04XgWk@oO4pYuy2mM2SNO9EECJBgCACZLlzvfuqdCrYwUvp7bN@LUwNb0hJpJZ5rPJeZcmTS5bK1B5kDVCTnCF3oBRRGchHrQCGPp4g1if995fnqj8 "Python 3.8 (pre-release) – Try It Online")
Finds the largest \$|i-j|\$ among all entries \$a\_{ij} \neq 0\$.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
I⌈EA⌈Eι∧λ↔⁻μκ
```
[Try it online!](https://tio.run/##TYnLCsIwFET3fsUsb@EKvh@4Kl25KLgPWcQqGEzS0iTi31@DYHE4cJiZ7mHGrjdO5DLakKgxMVFr3tZnXzzQOQw5UcX4Hy2jDjdyRdfYu5zu1NqQI3nGs/rlJKKUWjJWjEVB8wxQa8aGsZ16eXbffz/1woFx1FrL/OU@ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
A Input array
E Map over rows
ι Current row
E Map over elements
λ Current element
∧ Logical And
μ Column index
⁻ Subtract
κ Row index
↔ Absolute value
⌈ Take the maximum
⌈ Take the maximum
I Cast to string
Implicitly print
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~10~~ 6 bytes
```
&f-|X>
```
[Try it online!](https://tio.run/##y00syfmfoJCpUBLlp2CvoKcQq/BfLU23JsLuv0KEi0JUhUJI7H9DrmhDBQMFA2sgYQihgAxrhViQuBFExljBRMEUImcGxOYQRRYKllBlUAMMwRDOMIQYaYhkmrGCNdgoMyBtDjIAKG4AsRFmtQHMMXiZsVwG@gZcXFwA "MATL – Try It Online")
Port of @ovs's Jelly solution.
*(-4 bytes thanks to @LuisMendo)*
---
*Older*
### [MATL](https://github.com/lmendo/MATL), 16 bytes
```
&+t"tX@&Rs~?X@q.
```
[Try it out!](https://matl.suever.net/?code=%26%2Bt%22tX%40%26Rs%7E%3FX%40q.&inputs=%5B0+0+0+1+0%3B+0+0+0+0+0%3B+0+0+0+0+0%3B+0+0+0+0+0%3B+0+0+0+0+0%5D&version=22.4.0) [Check all cases](https://tio.run/##y00syfmfoJCpUBLlp2CvoKcQq/BfTbtEqSTCQS2ouM4@wqFQ739srEJ5hUKEi0JUhUJI7H9DrmhDBQMFA2sgYQihgAxrhViQuBFExljBRMEUImcGxOYQRRYKllBlUAMMwRDOMIQYaYhkmrGCNdgoMyBtDjIAKG4AsRFmtQHMMXiZsVwG@gZcXFwA "MATL – Try It Online")
Outputs a transformed version of the input (input + input's transpose) and then the bandwidth. Not sure if extraneous output like this is usually allowed; if not, the "cleaner" version is just 1 byte longer: `&+XH"HX@&Rs~?X@q.` [Try it out](https://matl.suever.net/?code=%26%2BXH%22HX%40%26Rs%7E%3FX%40q.&inputs=%5B0+0+0+1+0%3B+0+0+0+0+0%3B+0+0+0+0+0%3B+0+0+0+0+0%3B+0+0+0+0+0%5D&version=22.4.0)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 50 bytes
```
a->m=0;matrix(#a,,i,j,a[i,j]&&m=max(m,abs(i-j)));m
```
[Try it online!](https://tio.run/##fU5RCsMgDL2KdFAUIqjrOoe0N9gJih/ZR4dlDun60Z3eqS3b3yDkveQlLwk4O34PcSRdRN77ThiPy@xWekAABxPgkLKta995XKkHvL2o4xNjzPiIITzeFAnvSZjdc0m0ykVFRoqMARmuuFCZiQQBwgiQJSe0palK@wgNnIrQpvpcBjRctpFtM6P8oixOcndpQWrQJkEDShmVtBQqa9npd1TsT/xh1rL4AQ "Pari/GP – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~38~~ ~~31~~ 23 bytes
```
>./@,@(~:&0*|@-/~@i.@#)
```
-7 bytes by removing some useless parentheses
-8 bytes, thanks @ovs (see comment below)
[Try it online!](https://tio.run/##jU7LCsJADLzvVwxarJV222wf1oKyKHgqHsQfkNKiXjzUo/TX17haoT1JEjLJDJPczES6DdYFXPiIUHAFErtjuTcbGWpfz7tiFi2eOgg7fZV66hlPiMNW4lS3D1Tntm6FqKvLHQ0I5FA/xIgd3kQ2fr1nEyRvVtltzGNqUca1tCjHaqSlr9MH0RANr2agHGzBfpRAKSiWcapeliJ1Rq/9EeYF "J – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 63 bytes
```
x=>x.map((r,i)=>r.map((c,j)=>v=c?Math.max(i-j,j-i,v):v),v=0)&&v
```
[Try it online!](https://tio.run/##LY1LCsMgFEXnXcUbBQUV@/@A6Qq6gw4UmzSKjcHII7u30vRODudMrjdoZpvclPkYX13pVVlUu4iPmQhJzFHVplUs81VQ2fvD5KG2hTjumeeOIb0hZagkbRosNo5zDJ0I8U16orewAwlys4cDHCslnKqfKyVc4KrFPAWX9XPUv5@s2vxPsJYOTaB15Qs "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript (ES7), ~~58~~ 55 bytes
```
m=>m.map(q=(r,y)=>r.map(v=>q=!v|(n=y*y--)<q?q:n))|q**.5
```
[Try it online!](https://tio.run/##fY5PU8MgEMXvfIq1l0I0NMS2xj/Ekx576bWXmJIaJ0CANDMZ62ePhKq9OcOw7G/fe8tH0ReutHXbxUrvxVjxUfJcUlm02HBsbwbCcxvanueGX/UnrPgQDXFMnsyzeVCEnEwU0dVohTnWVuB55eaEWlHsX@tGbAdV4oTQTm87W6sDJtS1Td3h2U7t1IzQStuXonzHDngOnwigER1I4OAuQi@bfhAkv3gB14sz3hzlm7CEPHpzqZXTjaCNPuAKywl@kZEhxCCBBCXAwu3rhNIAb2EJq4DXvr8L4wzuJ8HZNVX2V1lIYSFhDSwDyJB3siWkKUr9zJ8UhZTLuuRn/T@vbw "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ĀDƶsøƶøαà
```
(Or `ø‚Ā€ƶ`øαà` as minor alternative.)
[Try it online](https://tio.run/##yy9OTMpM/f//SIPLsW3Fh3cc23Z4x7mNhxf8/x8dbaADgoY6BrE6ULYBkexYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3loeVT6uS1Zh3brcCn5l5ZAhO0r/x9pcDm2rfjwjmPbDu84t/Hwgv86h7bZ/4@OjjaMjdVRAFI6BjoGsTrRBjqGUBrIgkkZQSWNdUx0TKHSZkAxc6hCCx1LmFKYOSCWIRLLEGq2IdxUMx1DCx0LoDCQYaJjZARkGQFVAJERRAXIZGTnGMCdSIgdGwsA).
**Explanation:**
```
Ā # Transform each non-0 integer in the input-matrix to a 1
D # Duplicate this matrix of 0s/1s
ƶ # Multiply each inner value by its 1-based row-index
s # Swap so the matrix of 0s/1s is at the top again
øƶø # Do the same for the columns
# (where `ø` is a zip/transpose, to swap rows/columns)
α # Take the absolute difference of the values at the same positions
à # Pop and push the flattened maximum
# (which is output implicitly as result)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 7 bytes
```
vT:ẏ-ȧf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJHIiwiIiwidlQ64bqPLcinZiIsIiIsIltbMTYsMTgsOF0sWzYsMTQsMjJdLFsyMCwxMCwxMl1dIl0=) or [Run all the test cases!](https://vyxal.pythonanywhere.com/#WyJQaiIsIsabIiwidlQ64bqPLcinZiIsIkc7WsabYCA9PiBgaiIsIltbWzFdXSxbWzEsMCwwXSxbMCwxLDBdLFswLDAsMV1dLFtbMSwyLDAsMF0sWzMsNCw1LDBdLFswLDYsMCw3XSxbMCwwLDgsOV1dLFtbMSwxLDAsMF0sWzEsMSwxLDBdLFsxLDEsMSwxXSxbMCwxLDEsMV1dLFtbMTYsMTgsOF0sWzYsMTQsMjJdLFsyMCwxMCwxMl1dLFtbMCwwLDAsMSwwXSxbMCwwLDAsMCwwXSxbMCwwLDAsMCwwXSxbMCwwLDAsMCwwXSxbMCwwLDAsMCwwXV1dIl0=)
Port of Jelly answer.
## How?
```
vT:ẏ-ȧf
vT # Get the truthy indices of each
:ẏ # Duplicate and get length range [0, length)
-ȧ # Subtract the two and get the absolute values (implicit vectorization with both)
f # Flatten
# G flag takes the maximum of the top of the stack
```
]
|
[Question]
[
The game [shapez.io](https://shapez.io) has a huge variety of shapes you can produce, such as:
[](https://i.stack.imgur.com/GbCUE.png)
Each shape has a unique *short code*, for example the above is `CrWbScRu`.
This means, going clockwise from top right, red circle (`Cr`), blue wedge (`Wb`), cyan star (`Sc`), uncolored rectangle (`Ru`).
There are four different shapes:
* Rectangle - `R`
* Wedge - `W`
* Star - `S`
* Circle - `C`
And eight different colours:
* uncolored - `u`
* red - `r`
* green - `g`
* blue - `b`
* yellow - `y`
* purple - `p`
* cyan - `c`
* white - `w`
A quadrant is made out of one of each of these - (shape)(color). A quadrant can also be *empty* with `--`. This means there are 33 possible quadrants.
Four quadrants concatenated together make a *layer*, of which there are \$33^4 - 1 = 1185920\$ possibilities. You can't have an empty layer (`--------`). These layers can be stacked on top of one another by joining with `:` - the code `CyCyCyCy:SrSrSrSr` looks like:
[](https://i.stack.imgur.com/8bQB7.png)
Shapes can be stacked up to 4. This means there are \$\left(33^{4}-1\right)+\left(33^{4}-1\right)^{2}+\left(33^{4}-1\right)^{3}+\left(33^{4}-1\right)^{4} = \$ 1.97 septillion possible shapes total.
Your challenge is to randomly generate one of these.
Your generation does not have to be uniformly random, as long as every possible shape has a nonzero chance of being chosen.
## Specs
* Each *quadrant* is one of `SWCR` followed by one of `ugbrycpw`, or `--`.
* A *layer* is four *quadrants* concatenated together.
* A *shape* is 1-4 *layers* joined by `:`
* You should generate a not-necessarily-uniformly-random *shape*.
You can view shapes at <https://viewer.shapez.io/>.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~35~~ ~~40~~ ~~38~~ 36 bytes
+5 to prevent empty output which would've occured with probability \$33^{-16}\$
-2 bytes thanks to Kevin Cruijssen!
Quite slow, generates \$33^4\$ possible layers 4 times and chooses a random one each time. Layers of all `-` are removed.
```
[₄ε‘¥„W‘’»Õpcw’â„--ª4ãΩJ}'-8×K':ýDĀ#
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/@lFTy7mtjxpmHFr6qGFeOJDxqGHmod2HpxYklwNZhxcBRXV1D60yObz43EqvWnVdi8PTvdWtDu91OdKg/P//f13dvHzdnMSqSgA "05AB1E – Try It Online")
At the cost of two bytes this can actually run fast: [Try it online!](https://tio.run/##yy9OTMpM/f8/2tDM59zWRw0zDi191DAvHMh41DDz0O7DUwuSy4Gsw4uAorq6h1adW1lrcniLl7quxeHp3upWh/e6HGlQ/v8fAA "05AB1E – Try It Online")
Because every quadrant in each layer has a \$1\$ in \$33\$ chance of being empty the resulting shapes are quite noisy:
[](https://i.stack.imgur.com/KqmFo.png)
---
```
[ ... Dg# # until the the output is not empty, do the following:
₄ # push constant 1000
ε } # for each digit in this number:
‘¥„W‘ # dictionary compressed string "SRCW"
’»Õpcw’ # dictionary compressed string "rugbypcw"
â # cartesian product of the two strings
„--ª # append "--" to this list
4ã # 4th cartesian power, all 4-element combinations from the length-2 strings
Ω # choose a random one
J # join into a single string
'-8× # string of 8 -'s
K # remove all occurences from the list
':ý # join the list by ":"
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~38~~ ~~35~~ 34 bytes
```
“SWCR”p“¬,ĖṆḷ⁸»Żṗ4XʋⱮ4ẸƇƊṆ¿o⁾--j”:
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5zgcOegRw1zC4DMQ2t0jkx7uLPt4Y7tjxp3HNp9dPfDndNNIk51P9q4zuThrh3H2o91AaUP7c9/1LhPVzcLqM3q/38A "Jelly – Try It Online")
This *just* about finishes on TIO most of the time (it has a \$1\$ in \$33^{16}\$ chance of taking longer), taking around 55 seconds. Full program, as we require Jelly's smash-printing to get the correct output
-4 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!
The first sample output I got was:
[](https://i.stack.imgur.com/jk18Ls.png)
[External link](https://viewer.shapez.io?SbSyRwWy.WwWgRyCg.RrScRuWc.WgCyRuCr)
# How it works
```
“SWCR”p“¬,ĖṆḷ⁸»Żṗ4XʋⱮ4ẸƇƊṆ¿o⁾--j”: - Main link. No arguments. Left argument = 0
Ɗ - Group the previous 3 links into a monad f(_): (ignores the argument)
“SWCR” - Set the return value to “SWCR”
ʋ - Group the previous 4 links into a dyad g(“SWCR”, i): (ignores i)
“¬,ĖṆḷ⁸» - Compressed string: “rugbypcw”
p - Cartesian product with “SWCR”
Ż - Prepend a zero (represents “--”)
ṗ4 - 4th Cartesian power
X - Choose a random list
Ɱ4 - Yield [g(“SWCR”,1), g(“SWCR”,2), g(“SWCR”,3), g(“SWCR”,4)]
ẸƇ - Remove any that are just zeros
¿ - While:
Ṇ - The left argument is falsey ([] or 0)
Ɗ - Set the left argument to f(_)
o⁾-- - Replace all zeros with “--”
j”: - Join by ”: and smash-print
```
[Answer]
# [Python 3](https://docs.python.org/3/), 129 bytes
```
from random import*
print(':'.join(''.join(sample(q,4))for q in[[i+j for i in'RWSC'for j in'urgbypcw']*4+['--']*3]*randint(1,4)))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VocRUUZeaVaKhbqetl5WfmaahD6eLE3IKcVI1CHRNNzbT8IoVChcy86OhM7SwFEC8TyFMPCg92VgfxskC80qL0pMqC5HL1WC0T7Wh1XV0gwzhWC2QbyAJDkEGa//8DAA "Python 3 – Try It Online")
For each layer, 4 items are picked from a distribution containing 3 empty quadrants and the other shape-colour combinations 4 times.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~40~~ ~~39~~ 38 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
This version has a *very* high probability of having all 4 layers, using a similar approach as [Level's Ruby solution](https://codegolf.stackexchange.com/a/233743/58974) of generating all 4 layers, removing the ones consisting entirely of empty quadrants and making a recursive call if there are none left.
```
4Æ"RWCS"ï`Õ½wbgp` p-² ö4 qÃfÈr-Ãq': ªß
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=NMYiUldDUyLvYNW9d2JncGAgcC2yIPY0IHHDZshyLcNxJzogqt8)
## Original, 39 bytes
```
Ò4ö)ÆÈr-}a@"RWCS"ï`Õ½wbgp` p-² ö4 q
q':
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0jT2KcbIci19YUAiUldDUyLvYNW9d2JncGAgcC2yIPY0IHEKcSc6)
```
Ò4ö)ÆÈr-}a@"RWCS"ï`Õ½wbgp` p-² ö4 q\nq':
Ò :Negate the bitwise not of (i.e., increment)
4ö : Random int in the range [0,4)
) :End bitwise op
Æ :Map the range [0,Ò4ö)
È : Left function taking a string as argument
r- : Remove all "-"s
} : End function
a : Return the first result of the right function that returns truthy (non-empty string) when passed through the left
@ : Right function
"RWCS"ï : Cartesian product of "RWCS" and
`Õ½wbgp` : Compressed string "ucrywbgp"
p : Push
-² : "-" duplicated
ö4 : Choose 4 random elements
q : Join
q': :Join with ":"
```
[Answer]
# C#[9.0] - ~~191, 235, 228, 204,~~ 203 Bytes (Condensed)
```
static Random r=new();static string g(){var z="";for(int j,i,l=r.Next(1,4);l-->0;z+=":")for(i=j=0;i++<4;)z+=r.Next()%8<1&&j++<3?"--":$"{"CRWS"[r.Next(0,3)]}{"rgbypcuw"[r.Next(0,7)]}";return z.Trim(':');}
```
* `+44` bytes due to a missed requirement.
* `-5` bytes by reducing `GetShape` to `g` per [@emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a)'s recommendation.
* `-24` bytes by using `var`, consolidating declarations and using constant strings per [@Johan du Toit](https://codegolf.stackexchange.com/users/41374/johan-du-toit).
* `-1` byte by swapping `==0` for `<1` per [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
#### How it Works
```
// Create a new random number generator using C# 9.0's `new` invocation.
static Random r = new();
static string g() {
// Create a variable to store the possible shapes.
string s = "CRWS",
// Create a variable to store the possible colors.
c = "rgbypcuw",
// Create a variable to store the result.
z = "";
// Create an iteration variable to iteratively create between 1 and 4 layers randomly.
// Evaluate for stop then decrement.
// Append `:` to the result.
for (int l = r.Next(1, 4); l-- > 0; z+=":")
// Create an iteration variable to iteratively create the four quadrants.
// Create a variable for tracking the number of empty quadrants.
for (int i = 0, j = 0; i++ < 4;)
// If we haven't reached the maximum number of allowed empty quadrants, a new one can still be added.
// Use a random number to determine if we should create an empty quadrant.
// Since && short circuits, the increment of J doesn't occur unless we're adding an empty quadrant.
if (r.Next() % 8 == 0 && j++ < 3)
// Add an empty quadrant.
z += "--";
// Otherwise, add a shape and color from the variables above,
// using a random index within the bounds of the variables lengths.
else
z += $"{s[r.Next(0, 3)]}{c[r.Next(0, 7)]}";
// Return the result and remove any trailing `:`.
return z.Trim(':');
}
```
#### Sample Output
I called the method in a `for` loop over 10 iterations to sample the output for this post:
```
--CyCpCb:RpCu--Rc
RpCyWbWc:RcWuWyWc
CyWy--Cr:RrWpWuWg
Wp--WuRc
RpCcCgWp
CbWuWgCu:--RcRbWg:CcCuCpCc
RgRpCyCu:CbWyWuCu
CgCuRpCu
CyRc--Ru:WuRuRbRu:--CgRbWr
WpCgCpRu
```
#### Resulting Image Sample
I ran the shape code `CbWuWgCu:--RcRbWg:CcCuCpCc` through and got this result:
[](https://i.stack.imgur.com/JUhy8.png)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 51 bytes
```
⪫EE⊕‽⁴⊕‽⊖X³³¦⁴⭆E⁴÷ιX³³λ⎇﹪λ³³⁺§RWSCλ§urgbypcw÷λ⁴--¦:
```
[Try it online!](https://tio.run/##bY49C4MwEIb/Ssh0Qpzi1E6lLhYE0ULnNAk2EBNJo9Zfn0altUOH446H9@P4gzlumQ6hcsp4uFhloGT9OoXhTnbSeCmgZkbYDrIkIegPz@WOKjtJB5QSFNXJYmh8DG8/sdmS4HM1KiFBEbTr9aq@SmeYm6G0YtAWNEGURlzp4QknXxghX4DrW3PGi4OgLxtce597PuHfAr29QRBOU7wdh7iPIYR01G8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
‽⁴ Random integer 0-3
⊕ Incremented
E Map over implicit range
X³³¦⁴ 33⁴
⊖ Decremented
‽ Random integer
⊕ Incremented
E Map over random integers
E⁴ Map over quadrants
÷ι Current random integer
÷ Integer divide by
³³ Literal integer `33`
X Raised to power
λ Current quadrant
⭆ Map over values and join
λ Current value
﹪ ³³ Modulo literal `33`
⎇ If nonzero then
§RWSCλ Cyclically indexed colour
⁺ Concatenated with
§urgbypcw Shape cyclically indexed by
λ Current value
÷ Integer divide by
⁴ Literal integer `4`
-- Else literal string `--`
⪫ : Join with literal `:`
Implicitly print
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `rR`, 37 bytes
```
\:4℅ƛ«3⟩∑ḣ`«`SWRC`Ẋ‛--J33²²‹℅τ∑₅8ε-;j
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=rR&code=%5C%3A4%E2%84%85%C6%9B%C2%AB3%E2%9F%A9%E2%88%91%E1%B8%A3%60%C2%AB%60SWRC%60%E1%BA%8A%E2%80%9B--J33%C2%B2%C2%B2%E2%80%B9%E2%84%85%CF%84%E2%88%91%E2%82%858%CE%B5-%3Bj&inputs=&header=&footer=)
This uses a quite neat custom-base-decompression-based approach to ensure there'll never be an empty layer. It basically generates a random number between 1 and \$33^4 - 1\$, decompresses it with the key as all possible quadrants (with `--` first, so 0 can never occur, so empty layers won't either).
```
4℅ƛ ; # array of length (random 1-4) filled with...
33²²‹℅ # Random integer between 1 and 33^4-1 inclusive
τ # Decompressed by...
Ẋ # Cartesian product of...
«3⟩∑ḣ`« # Compressed string `bcgpruwy`
`SWRC` # String literal `SWRC`
‛--J # Prepend a `--`
∑ # Concatenate all this
₅8ε- # Pad with `-` from the start
j # Join the whole thing by...
\: # Semicolons.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~117~~ 114 bytes
```
->{s=((0..19).map{|i|i%5<1??::"-SWCR"[(r=rand 40)/8]+"rgbpucyw-"[r<8?8:r%8]}*'').gsub ?:+?-*8,''
s>''?s[1,99]:f[]}
```
[Try it online!](https://tio.run/##HcjBCoMgAADQ@74ihFArXcEGKpWH/cF22EE8ZFvhoRGajLC@vcHe8blg1mNoDtJG3yBUUlpxTKdujpvdbHqtKymFAOTxvN2BQq5x3eeVXEp8ZjoHbjRz6NcvAcrVTDLhUqb3DEJMRx9MIkUuScYKCE@@hVB6VRWcazEovR@c08VObx/nsPjkXz8 "Ruby – Try It Online")
A function returning a string.
**Commented code (original version)**
```
->{s=
((0..19).map{|i|i%5<1? #Iterate 20 times to make an array. if i%5==0
?:: #put a colon, else...
"-SWCR"[(r=rand 40)/8]+ #Select a shape
(r<8??-:"rgbpucyw"[r%8]) #If selected shape is - then put another -, else put a colour
}*''). #Convert the 20-element array into a string
gsub(?:+?-*8,'') #Delete all instances of :--------
s<?!?f[]:s[1,99]} #If s is empty, recursively call f[] to try again. Else output s (minus the initial colon)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 137 bytes
```
#define r rand()
m;b;q(){m=r;m&30||q();}f(){for(q(b=5+r%4*5);--b;)printf(b%5?m&1<<b%5?"%c%c":"--":":"+!q(),"WRSC"[r%4],"rugbywcp"[r%8]);}
```
[Try it online!](https://tio.run/##HU5NC4IwAL37K9ZC2dKBUUI4pUP/oA4dwoObTgZt6TQk1L/eml0e7z14H5w0nFu7rWohdQ0MMKWuEPYUZbRDeFK5oSo4xPPsFF2Es8TLoA6xPAmNf9wlmBLCKG6N1INAzE/OKthn2Uqgz30OU0iIgxSGG9cRwfv1doEPly0iaN4N@4y8XfWpcANWlVIjDCYPgP7/ZZCqRjHG1DlunnqL/XLxLJvekvEH "C (gcc) – Try It Online")
-5 bytes thanks ceilingcat!
[Answer]
## [Perl 5](https://www.perl.org/), ~~95~~ 138 bytes
```
{@q=(qw(: --),map{$s=$_;map$s.$_,ugbrycpw=~/./g}C,R,W,S);@i=map$_%5?$==1+rand
33:0,1..rand 19;@i%5==4&&" @i "!~/ (1 ){4}/||redo;say@q[@i]}
```
[Try it online!](https://tio.run/##FcrdCoIwGIDh865iyRSluTV0Bzk@GnQHddBBhFiKCP3ohon4c@tLz94XnrrQL2FbU6CfoHwv7aAa8JvOT1AYBuSd1QM2gFO5FDYUp6QtH7p/1h3MjLJyOpEzuZJLIFUFq0ldccQAfKezT76JomRPOKXrIH5YkCsAYs9zkKqQs50Z8jkKhnhi46iL/CtN1qvmpqr7ZO0f "Perl 5 – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~263~~ 253 bytes
-10 thanks to ceilingcat! Forgot that `|` exists and that ternary `if`s can be written without parentheses. D'oh!
```
String f(int i){var r=new Random();var q=""+"SWCR-".charAt(r.nextInt(5));q+=q.equals("-")?'-':"ugbrycpw".charAt(r.nextInt(8));return i<1?(f(2)+f(2)+f(2)+f(3)).substring(1):i<9?i>2|r.nextInt(2)<1?(":"+f(9)+f(9)+f(9)+f(9)).replace(":--------",f(1)):"":q;}
```
[Try it online!](https://tio.run/##bZA9T8MwEIb3/IqTl/oUYqVFSDRuqBATAwztwIAY3MQpLomTOE5LVfrbg9NEAiE8vNJ9vHfnZyf2ItilH50qqtJY2LmYtVblbCV0Whbc85JcNA08CaVPHoDSVppMJBKe@xBgbY3SW0ioq4BG7pJnz0ljhVUJdGM9u9QVnvbCgIm1PMCwgSLvU3VMiE/WLw@rgLDkXZh7Sw3T8tM@aktvEHntxzWTdSvyhpKA4HISTCLSbjfmmFSHf0y3zmSkbY0GtZguaUZn6P@Wa0TWtJvmciGdYqQW86W6m339zJhh7yQRce1z/CPIjKxyx8I1BOMjV5mbhBEhUc3PHe9RVO0mdyhGIvtSpVA4nHRA8/oGAgeWkJUGBlAQQ8j7u8OQK99HGBp64MfGyoKVrWWV89tcu5@FOJI/d98 "Java (JDK) – Try It Online")
Took forever to find something promising, ow my head...
This won't win any prices, but I liked the approach so here it is anyways. It uses the same function recursively with a different parameter to build different parts of the string.
I hope I find the template for Java lambdas again, I keep forgetting how the boilerplate needs to look for them to work :(
## EDIT:
Function lamdas aren't shorter in this case, since you don't call but `apply()` them, which is WAY longer. Still, thanks for the template `Johan du Troit`!
### Explained:
```
// function is called with 0 to start
String f(int i) {
// use var because it's shorter
var r=new Random();
// build a quadrant
// decide on a type...
var q=""+"SWCR-".charAt(r.nextInt(5));
// ...and append the color. If the type is "-" then append a "-" instead
q+=q.equals("-")?'-':"ugbrycpw".charAt(r.nextInt(8));
// decide what to return
return
// shape case: build full shape
i<1?
// a shape consists of four layers
// each layer starts with a :, cut the first one off
(f(2)+f(2)+f(2)+f(3)).substring(1)
// not the starting case, check for layer case
:i<9?
// build one layer. It either doesn't exist or contains four shapes
// note: 3 overrides the random decision and always returns a layer
i>2|r.nextInt(2)<1?
// replace an empty layer with a newly generated one...
(":"+f(9)+f(9)+f(9)+f(9)).replace(":--------",f(1))
// ...or return a nonexistant layer
:""
// not the shape case nor the layer case, return the quadrant calculated above
:q;
}
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 64 bytes [SBCS](https://github.com/abrudz/SBCS)
A full program that prints the shape.
```
⊃{∊⍺':'⍵}/{∊((⊂'--'),,'RWCS'∘.,'urgbypcw')[?4⍴33]}⍣{∨/'-'≠⍺}¨⍳?4
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9TVXP2oo@tR7y51K/VHvVtr9UFcDY1HXU3qurrqmjo66kHhzsHqjzpm6OmolxalJ1UWJJera0bbmzzq3WJsHFv7qHcxUMsKfXVd9UedC4AG1R5a8ah3s70JAA&f=AwA&i=AwA&r=tryapl&l=apl-dyalog&m=tradfn&n=f)
`?4` random integer between 1 and 4
`... ¨⍳` call the function on the left this many times and collect the results in a list:
`{ ... }⍣{∨/'-'≠⍺}` until any char in the result is not `-`:
`'RWCS'∘.,'urgbypcw'` Cartesian product of the two strings
`,` flatten into a list of 2-char strings
`(⊂'--'),` prepend the empty quadrant
`( ... )[?4⍴33]` get elements at 4 random indices between 1 and 33.
`∊` flatten into a string
`{∊⍺':'⍵}/` join with `:`
`⊃` get the first element from the nested output
[Answer]
# JavaScript, ~~125~~ ~~120~~ ~~119~~ ~~115~~ ~~112~~ 118 bytes
To avoid the possibility of an empty layer, we force the 4th quadrant to be non-empty *if* all previous quadrants are already empty (+6 bytes 'cause I realised I'd screwed that up).
Need to figure out a way to shorten the selection of the characters.
```
(r=x=>Math.random(g=s=>s[7]?l--?s+`:`+g``:s:g(s+`RWSC-`[c=r(5^s==`------`)]+`urgbypcw-`[c-4?r(8):8]))*x|0,l=r(4))=>g``
```
[Try it online!](https://tio.run/##HYyxDoIwFEV/p89aUhOMpPhgcHbRwYFgWlGqplLSItbEf6/o3U5Ozr2rUfnG3fqBjVlsMRKHAYutGq6JU93ZPohGj4WvVnVpGCs9lUJSLaXwQpOJdof9hsmqQUeWR48o2X8SaiqfTp/effP6eZaWjmQgshpgFj58bqYiBcBiOoutdSQgzwOl6wXnOTS289ZcEmM1aQlA/AI)
[Answer]
# [CSASM v2.5.1](https://github.com/absoluteAquarian/CSASM/releases/tag/v2.5.1), 514 bytes
```
func a:
lda 0
sta $1
lda ""
sta $2
push 1
push 5
extern Random.Next(i32,i32)
pop $a
.lbl a
push $a
brfalse b
dec $a
push 0
pop $1
push ""
pop $3
.lbl c
push $1
push 4
sub
brfalse d
inc $1
push "RWSC-"
push 5
extern Random.Next(i32)
dup
push 1
add
substr
dup
push "-"
sub
len
brtrue f
dup
add
br e
.lbl f
push "urgbypcw"
push 8
extern Random.Next(i32)
dup
push 1
add
substr
add
.lbl e
push $3
swap
add
dup
pop $3
push "--------"
sub
len
brtrue c
push 0
pop $1
push ""
pop $3
br c
.lbl d
push $2
push $3
add
pop $2
push $a
brfalse a
push $2
push ":"
add
pop $2
br a
.lbl b
push $2
print
ret
end
```
Whew, this was one mammoth of a program to write.
This submission defines a function `a` which generates then prints the random shape string as is specified by the challenge.
---
**Explained:**
```
func a:
; $a = random value in [1, 4]
; $1 = loop counter for quadrants
; $2 = final string
; $3 = build string
lda 0
sta $1
; Initialize $2 to an empty string
lda ""
sta $2
; Initialize $a to the random value specified above
push 1
push 5
extern Random.Next(i32,i32)
pop $a
.lbl a
; Stop looping if $a == 0
push $a
brfalse b
dec $a
; Reset $1 and $3
push 0
pop $1
push ""
pop $3
.lbl c
; Stop looping if $1 == 4
push $1
push 4
sub
brfalse d
inc $1
; Get a random letter in "RWSC-"
push "RWSC-"
push 5
extern Random.Next(i32)
dup
push 1
add
substr
; Check if the letter was "-"
dup
push "-"
sub
len
brtrue f
; Letter was "-"; just add the other one
dup
add
br e
.lbl f
; Letter was not "-"; Get the color
push "urgbypcw"
push 8
extern Random.Next(i32)
dup
push 1
add
substr
; Add the two parts together
add
.lbl e
; Add the new piece to $3
push $3
swap
add
dup
pop $3
; Check $3. If it's "--------", generate another layer
push "--------"
sub
len
brtrue c
; Reset the quadrants counter and build string
push 0
pop $1
push ""
pop $3
br c
.lbl d
; Append the layer to the result
push $2
push $3
add
pop $2
; If $a == 0, don't add the ":"
push $a
brfalse a
push $2
push ":"
add
pop $2
br a
.lbl b
; Print the result
push $2
print
ret
end
```
---
The first run of this code produce the following shape:
`--Cp----:--RgSg--:CgRwWbRr:WyWpWwWw`
[](https://i.stack.imgur.com/eOHxy.png)
More examples of shapes generated by the code:
```
--ScWyRp
WuWuCbRg:--RbSwRc:CwRuWrCb
CgSgRpCb:Cu--SrRb
Wc--CcCg:----CrRu
SyCbWc--
SrCbSc--:----WrWb
Ry--CgSr:--Cp--Sw
--CwWpCc:CbCpRcSy:CpWw--Cy:--Ru----
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 49 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
{╘4{4{"CRSW"w"bcgpruwy"w+v¶╛æ;û--}Γy}Γ'-8*a-}↔':u
```
[Try it online.](https://tio.run/##y00syUjPz0n7/7/60dQZJtUm1UrOQcHhSuVKScnpBUWl5ZVK5dplh7Y9mjr78DLrw7t1dWvPTa4EYnVdC61E3dpHbVPUrUr//wcA)
The first output was: `CwRuRrRw:RpSwSbRp:RcWpRpCu:CpWwWgWc`:
[](https://i.stack.imgur.com/EnkXXs.png)
**Explanation:**
```
{ ... }↔ # Do while false without popping:
╘ # Empty the stack (in case we've encountered a fully empty result)
4{ # Loop 4 times:
4{ # Inner loop 4 times:
"CRSW"w # Push a random character from "CRSW"
"bcgpruwy"w # Push a random character from "bcgpruwy"
+ # Concat these two characters together
v # Push a random integer in the range [-2147483648,2147483647]
¶╛ # If this integer is a prime number,
æ # use the following four character as inner code-block:
; # Discard the earlier character pair
û-- # Push "--"
} # After the inner loop:
Γ # Wrap the top four items into a list
y # And join this list together to a single string
} # After the outer loop:
Γ # Wrap the top (up to) four items into a list
'-8*a- '# Remove any strings consisting of 8 "-"
}↔ # After the do-while false:
':u '# Join the list with ":" delimiter
# (after which the entire stack is output implicitly as result)
```
Compressed strings are pretty mediocre in MathGolf, so unfortunately it won't save any bytes here. `"CRSW"w` can be [`╖╖`'w+wδ`](https://tio.run/##y00syUjPz0n7///R1GlAlKBerl1@bsv//wA) which is 1 byte longer, and `"bcgpruwy"` can be [`╕█≈║☺ 'ußy`](https://tio.run/##ASEA3v9tYXRoZ29sZv//4pWV4paI4omI4pWR4pi6ICd1w595//8) which is the same byte-count.
[Answer]
# JavaScript (ES6), 117 bytes
*-2 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
Although this is not required, this solution has a uniform distribution.
```
f=(k=(R=Math.random)()*4|0,q=R(n=4)*1185920)=>n--?f(k,q/33)+'SWCR-'[((q%=33)&35)%7]+'ugbrycpw-'[q>>2]:k?f(k-1)+':':''
```
[Try it online!](https://tio.run/##LYu7DoJAFAV/ZRvkXmCRZ1R0sbC2wcLCUCAvEdyFBTUm/juiMaeZnMlck0fSp7JqB8pFlo9jwaBmELF9MlxMmfBM3BBQ896W0bEIOPNQs@2lv3IsZCGndFtAbXRz10VdPRx3EVVPAJ3CpmPm@qgsYl29l2f5Stvn5LowdOKg/lbUnpJgmjoWQkI15JIwYq3JjzbE@aOuI0kF70WTm40ooQDE8QM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 158 bytes
```
p='eval printf %s, '
s=$($p {S,W,C,R}{u,g,b,r,y,c,p,w})--
l=`$p{$s}{$s}{$s}{$s}`
$p{$l}:{$l}:{$l}:{$l}|tr , \\n|sed -E "s/-{4}(:|$)//g;/(^|:)(:|$)/d"|shuf -n1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kKbE4Y8GCpaUlaboWN-cV2KqnliXmKBQUZeaVpCmoFusoqHMV26poqBQoVAfrhOs46wTVVpfqpOsk6RTpVOok6xTolNdq6upy5dgmqBRUqxTXIuMELpBYTq0VKlFTUqSgoxATk1dTnJqioOuqoFSsr1ttUqthVaOiqa-fbq2vEVdjpQnhpijVFGeUpino5hlCXAl1LMzRAA)
[Answer]
# [FMSLogo](https://fmslogo.sourceforge.io/manual), 106 bytes
```
show bl map[word pick bf invoke[(crossmap "word ? ? ? ?)]se[--]crossmap "word[RWCS urgbycpw]":]random 1500
```
Don't try it online. The [calormen.com](https://www.calormen.com/jslogo/#) logo interpreter does not support "templates" (which is what logo calls anonymous functions) on map, only procedure names; it's error messages also leave something to be desired.
The program works in FMSLogo 8.3.2 and propably MSWLogo and UCBLogo as well, as FMSLogo is based on them.
Explaination:
* Logo is based on lisp but allows omitting parentheses around procedures that use their default arity.
* `crossmap` generates all possible combinations of the members of its inputs, which can be given in a list. The first input is a function, or "template", which is passed each combination to combine them.
* I don't know a better way to remove the empty layer yet, so the first `crossmap` generates a 1185921 element list of every possible layer and then `bf` removes the first one. That's why this program takes approximately 27 seconds to run on my laptop.
* Numbers can be coerced to strings in logo, so `map` maps the big instruction list in the middle over the characters of a random number, which has some length between one and four. `repeat 1+random 4[...]` would not output the concatenation of the results, and using `map[...]iseq random 4 4` is 4 characters longer.
* I would not be able to tell, of course, but maybe some correlation in the random number generator makes some shapes actually impossible. I am not going to investigate.
Anonymous functions can not be called the normal way, unlike in javascript for example. They must be called by `apply`, `map`, or similar, which is why I consider
```
[bl map[word pick bf invoke[(crossmap "word ? ? ? ?)]se[--]crossmap "word[RWCS urgbycpw]":]random 1500]
```
to be an invalid submission.
Alternative much faster 5 characters longer solution, which, unlike the submission, can propably produce empty output:
## FMSLogo, 111 bytes
```
show bl map[invoke[if ?="--------: ["][?]]word map[pick se[--]crossmap "word[RWCS urgbcypw]]1234 ":]random 1500
```
Sample shape: `CpCuRpSc:SwSuCcWr:Sb--RwSb` (everyone seems to do this)
[](https://i.stack.imgur.com/cvq6x.png)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 155 bytes
```
r=RandomInteger
c=RandomChoice
t=Table
StringRiffle[StringJoin/@(Nest[#/.c@#->"--"&,#,r@2]&/@t[t[#<>#2&@@c@*Characters/@{"RWSC","urgbypcw"},4],r@3+1]),":"]
```
The distribution of the non-empty quadrants is uniform, but the distribution of shapes is not, as empty quadrants are generated after the fact.
*TIO* requires two extra bytes for symbol assignment so that the output can be printed.
[Try it online!](https://tio.run/##LY1PC4IwHEDvfowJ0p/ZyDpFyg881SFCgw6yw1xThzpj/iIi@uxLqOPj8Xi9wEb1ArUUztk4E@Y29AeDqlbWk39Om0FL5WF8EWWnvDbO0WpTZ7qqOlX84Dhow2B2UiMWPltJ8MOEhCEJqE8tRDxggMWk9okfBQASFmkjrJCo7MjgTbJrnhJKHrYuX3f5JB@65VO4Wa75nJId4e48bRBa9wU "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~117 116~~ 114 bytes
```
f=(k=n=5*~R(4))=>++n?n%5?R(~k%5)?'--'+f(k+1):'SWCR'[R(4)]+'ugbrycpw'[R(8)]+f(k):':'+f(n):''
R=n=>Math.random()*n|0
```
[Try it online!](https://tio.run/##FcxBC4IwHAXwe99D9v87lAkJok0PnbusQ4fosMxZaZtMM4Pwq9uEd3g8frynHGVf2kc3BGOyKO4CDdc89mcBW0SeU6oL7cWFgLnxYixIEBCqoKERpuR42gtyXuWFknd9td@y@6xD4gaHHElXrV0hG@GO84Mc7qGV@mZegL7@sUUZCxNn2UTpLmIsw9Lo3rRV2JoaFCAufw "JavaScript (V8) – Try It Online")
If already \$k\$ empty in this layer, then there's \$\frac 1{4-k}\$ probably be not empty, aka 1 when already 3 empty
]
|
[Question]
[
Your task is to write a program or function that takes as input a list of positive integers and determines if there are any two integers in the list, that both appear the same number of times.
For example the list
```
[1, 2, 3, 2]
```
Has one 1 and one 3 so it satisfies the condition.
But the list
```
[3, 2, 2, 1, 2, 3]
```
does not satisfy the condition since every member appears a unique number of times.
Additionally your program should *not* satisfy this condition when its source code is interpreted as a list of bytes.
For example
```
abcb
```
Would not be a valid submission since both `a` and `c` appear exactly once.
[Here](https://tio.run/##XU8xDsIwENvzCg8MqQSVWCuyFBYkJAZecIHQVqRJ1FwH/sbGw0KqMhSms89n2ddSfBhrU@r64AfGgZjK@snmwkPnGlBELQCJxvDeOzaOY@ZrjC7Q9ZFhIZbWUxdZiAAFshZSKrUtUMIa13A7oWbwY8gzTpYSPYWv@K8J0VPnUFU4niGLmSncfM7UuWDEboP75K/LuUwGvy1DfoGxms8XPMyblIi01u/XBw "Haskell – Try It Online") is a verifier you can use if your source is in ASCII.
## Output
Your submission when executed should output one of two possible values, one when the input satisfies the condition, one when the input does not.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
D¢DD¢Q
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f5dAiFyAO/P8/2lBHwUhHwRhMAtmGsQA "05AB1E – Try It Online") or [validate more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/l0OLXIA48L/O/@hoJRclHaVDi4CECxSDOYFKsTrRhjpGOsY6RkAWkARCMB/IU0oEqkgC4mQwDRIB8WCiSXDRRKgoCDtB1UNwbCwA).
Outputs 1 if each item appears a unique number of times, 0 otherwise.
```
D # duplicate the input
¢ # count occurences of each item in the input
DD # triplicate the list of occurence counts
¢ # count occurences of each occurence count in the list of occurence counts
Q # check whether this is equal to the list of occurence counts
```
Without the source restriction, this could be 4 bytes: `¢Ð¢Q`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1+2+3+4 = 10 bytes
```
ĠQQẈQƑẈĠĠĠ
```
A monadic Link which accepts a list and returns an empty list, `[]`, if the input satisfies the condition, or a list with a list containing a one, `[[1]]` if the input does not satisfy the condition.
**[Try it online!](https://tio.run/##y0rNyan8///IgsDAh7s6Ao9NBJJHFoDg/8PtRyc93DkDqyQA "Jelly – Try It Online")**
### How?
Without the source code restriction we could do the four byte `ĠẈQƑ`: `Ġ`, group indices by value; `Ẉ`length of each; `Ƒ`, is invariant under; `Q` de-duplication.
So for the \$1+2+3+4=10\$:
```
ĠQQẈQƑẈĠĠĠ - Link: list, L
Ġ - group indices by value -> list of lists (which when flattened would contain the integers 1 to len(L) inclusive)
Q - de-duplicate (a no-op)
Q - de-duplicate (again a no-op)
Ẉ - length of each (group) 0> how many times each element appeared
Ƒ - is invariant under?:
Q - de-duplication -> 0 if satisfies, 1 if not
Ẉ - length of each -> [] if satisfies, [1] if not
Ġ - group indices by value -> [] if satisfies, [[1]] if not
Ġ - group indices by value (a no-op)
Ġ - group indices by value (another no-op)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~136~~ ~~126~~ 120 bytes
A slight improvement of @xnor's solution, posted with permission. Source code has 15 distinct characters.
```
n=input()
print(not
sum(())==sum(sum(r==m
for
m
in
n)==sum(u==m
for
m
in
n)for
r
in
n
for(u)in(n)if(r==u)==(r==n)))#ouu)
```
[Try it online!](https://tio.run/##hVFNb8IwDL3nV1jlQCJVSHyckHqE637AyqELRo0Ap3Mcbf31LGkQQ2jSJLfx84trv75hlN7T6mb9EaGBqqpu1DgaomijBnYkmryoEK9aG9M0OckPN81VnTyrq3Kk6M7El2pOeUpzVUfjSJNxp9weU08@yRgz8zGaWxq@CMJuSKPVDAb2FkMA7GwP00pwcYTqq3cXhOVWgfCY3oDfaHUWYFTKLQ4Cu7f9jtlzpj8Yu3P5YJID0iNMaoN0EopGqFraM35GJDuCP4HtOw5pKAQf2ZaGbaUk/aKLC6KDZ8GjDihlsDFZINjSMnFSn3FsMruwPpKYtEsZxjiwtqb@5RK6vS9rWNWwrmFzUL9glcB6Ainu1QdfrpTYPMdBzR82tvTwsaU/jWwpLd9SOh219GzmKzMhvqOJ/MfU@Q8 "Python 2 – Try It Online")
**Input**: A string representation of a list/iterable, from stdin.
**Output**: `True` if the list has 2 elements with the same frequency, `False` otherwise.
### Base solution
```
n=input() # read a list/iterable from stdin
# This is Python2, so the input string is implicitly evaluated
print(0 != sum( # return True if sum is not 0 (aka at least one of the following is True)
sum(r==m for m in n)==sum(t==m for m in n) # check if frequency of r and t are the same
for r in n for t in n if r!=t # ignore when r==t
))
```
[Try it online!](https://tio.run/##XVDBbsIwDL3nK0x3IJEqNAqnSTmy6z6AcoAuFRGLGxlXwNcXJ2EMzbLi92zHzku88XHAZuqGbwcWqqqa0HqMI2ujInlk/Q4zC@cxaAU5kLUB@oEggEdAY23K8r@sNCdGmcGDcWZCfA80s6yMmWTl4szkoyxUl6P/cbD8UMB0kxPc1XU6PU4GumvnIsPm63NDNFAqH8jtT9N2WUNTw6qG9U79kUbIKhPxR/ZZLy3F16@@U/PnD7RYviAJ/JXeoihpUaJHjeZFfq7oYEo@YSo4QS7Q92kIy60Upc289YHFaCxm5nc)
## Old solution using `exec`
### [Python 2](https://docs.python.org/2/), 158 bytes
```
e=s=110;"tt)e";exec"e=%c%x%c%x%c%x%cx:%ce%c(set(x))-%ce%c(set(%c%x%c(x%cc%c%c%ct,x)))"%(e-2,10,e-1,11,100,10,0x20,e-2,e,s-2,s,s-1,10,s--2,0x2e,s--1,120-2-1,s)
```
[Try it online!](https://tio.run/##zZBNCsIwEIX3PcVQCGYglSR1pfQk4kLiiIGaliZIPH2d1N8jSN684X1vVhnv6TIEO8/Uxc4YvatTQqp3lMnV1Akn8nfyVjgSTkZKMiM23/TsJY8Ty0uKD7AWkhqrjFbUGGVYWpeksy3IKlKRPbKXjhcnLgsuxOrG8o44@@s4TAniPVbnYYLeBwIfSl7HdPJhW0EPHdDt2MtSMp38KBErGCcfkiTZI857o8AqaNkP1b5dAutFGZk3at/a/Opz0S5h9d@/tnoA "Python 2 – Try It Online")
**Input**: a list or iterable.
**Output**: a positive number if the list has 2 elements with the same frequency. `0` otherwise.
### Base solution
```
e=lambda x:len(set(x))-len(set(map(x.count,x)))
```
[Try it online!](https://tio.run/##ZY9BbsMgEEX3PgWyhAISRIC7csRJoixcMlWRMLYMrcjpncGpnUXFn2H@@7CY@ZG/p9itK9gwjJ/3gZQ@QGQJMiucy30eh5mVs5t@YhbI@erHeVoySY/UfE0LCT4C8bH6c8p3H/uGBGIJ/A6B1ZA3ZF58zAxYwO9XLYgRpMN@a67dZlB/FJHeUbfr47@Od91mTmCL1Vpd2pSztZab9gIFHGvBUkfLu0pPHVB3rPl2r5xhObqd174tZSCN0EqA1EKjlKpOFVOREXD0moki0WEIdUJilDR4A@enJw "Python 3 – Try It Online")
My approach is inspired by [this answer](https://codegolf.stackexchange.com/a/110722/92237), which discussed how to construct any Python programs using only the characters `exc="%\n`. The idea is to convert the program into `exec"<program>"`, then use string modulo (`%x` and `%c`) to build program string from number.
[Answer]
# [Zsh](https://www.zsh.org/), \$\sum\_{i=1}^{18} i = 171\$ bytes
```
((f--))
for u (${(u)@})((n[$#-${#@:#$u}]--))
((f-(${${(@on)n}[f]})))
# rrrrrr[[[[[[]]]]]]]nnnnnnnn@@@@@@@@@#########{{{{{{{{{{}}}}}}}}}}}-----------))))))))
```
[Try it online!](https://tio.run/##1ZDBjoIwEIbvfYoJVNuGcEDjBUPCZh@D5WC0RKJO1QLJLumzs9MuanyE/RrCMPwz83d@7HFqpJKTlE2aKsUac4ceJB9lr0qnpMSKxykf4zKPee/qIPJikpCoNKjQVU3tFOVjeOMeqAL1HzhTPogfjE/ci/SFmmFsosfbPLe2A8lEBis6a38EExvYzNGashnFGWSC0c2AF6FkuQS9Pxrg4eu4s4AG0x7bW69Bn/VFY2cZ0WnbFeIfbUaQ5@@rtrqD9AMuu2swvYcWgRzZPFf@Sm47Mm9i2J0LTqKK7@uQmOOCS0n/IIGMmjrGwrY@TY9dDjz2bf3V6V0XYcAJhrCX06Ao6dTcH6uhTorIj74l6uSikL3eW@waEIuNhRwW9gvFUwF8oHm@5eA9R36NtMRoCwfzXrw6vIqlTJJWKV98MKinXw "Zsh – Try It Online")
Tricks used: We use subtraction instead of adding. We reuse characters we need from `for`, `(on)`, and `(u)` as parameter names. `((f--))` gets us `f=-1`, which saves us from using `1`.
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), ~~66~~ 57 bytes
```
*.Bag{*}.Bag{*}.all≠'l.}}}}****{{{{{{{gggggBBBBBBB'.Bag
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@19LzykxvVqrFkYl5uQ86lygnqNXCwRaQFANAekg4AQB6iDF/625ihMrFdIUog11jHSMdYxj4QLGOgpGYGQIJhEy6aklevlFKcXW5FsLAA "Perl 6 – Try It Online")
10 unique characters, `*.Bag{}l'` and the 3 byte character `≠`. This uses `.Bag{*}` to get the number of times each element appears, then repeats that to get the number of times those appear and then confirms that not all of them are equal to one.
[Answer]
# JavaScript (ES6), \$\sum\limits\_{i=1}^{16}i= 136\$ bytes
Returns \$1\$ if the condition is satisfied or \$0\$ if it's not.
```
p=>p.map(aa=m=a=>aa|=1^(p[[,a]]||(m[p.map(m=>pp+=a==m,p[[,a]]=pp=1),pp]^=1)))|aa//((((((,,...........11111===>>>>>>>>>>>[[^mmmmmppp|||||
```
[Try it online!](https://tio.run/##bY/dCsIwDEbvfYpeplg7qtcZiI9ROgx1/rFuwcmu@u4znYIgHkpKm0P4cqeJxvi48XPTD6d2jlIUquPMWLNNxECECQlrooyuAfbeUAg5Q/JvIYnJa1EwmU8XmdFpwxwaubXORFUFC8bYL66AiPUX75tUYOZcmI927G6xBWfUxunV6izx2ok6KFHlHYd@HLrWdsMFzuBF2xq1kxq0/m3ulqacj/VHkVRlcFhWiwprFW280uMgn/snyDJ6fgE "JavaScript (Node.js) – Try It Online")
### How?
To minimize the number of distinct characters, we only use `map()` loops and variable names made with ***m***, ***a*** and ***p***.
Character usage breakdown:
```
+ | / | ^ | ) | ] | , | [ | 1 | | | ( | m | a | . | > | = | p
----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
```
### Commented
In the following source, the variables have been renamed for readability.
```
a => // a[] = input array, also used to keep track of the
// values that have already been counted
a.map(r = o = v => // r = result flag
// o = object used to keep track of the character counts
// that have already been encountered
// for each value v in a[]:
r |= // set r if ...
1 ^ ( // ... the test below is false:
a[[, v]] || ( // v has already been counted, or this is ...
o[ // ... the first time this count is encountered:
a.map(V => // for each value V in a[]:
n += v == V, // increment n if V is equal to v
a[[, v]] = // mark v as counted
n = 1 // and start with n = 1
), // end of inner map()
n //
] ^= 1 // toggle o[n]
) // end of count update
) // end of test
) | r // end of outer map(); return r
```
[Answer]
# [R](https://www.r-project.org/), 78 bytes
```
all(table(table(scan()))==all(c()))#nss==bbbcccceeeeettttttaaaa(((()))))llllll
```
[Try it online!](https://tio.run/##LckxCgAxCATArwTSaJlL7WNU0kmKM//3NNwsLgu@EWwGh8XW3668ARGJ6qM1@3YnEhFNq5yLEyQsdsVsT2bkzRYf "R – Try It Online")
`table(x)` gives a table of the counts of each value in `x` (here `x` will be the input taken by `scan`); `table(table(x))` counts how many times each count occurs. We therefore want to check whether `all(table(table(x))==1)`. Adding `#` and all the necessary characters to obey the constraint would lead to a score of 91.
The trick is to avoid the character `1` by using instead `all(c())`, which is `all` of an empty vector, i.e. `TRUE`, which gets converted to `1`.
I haven't looked yet into using [octal codes](https://codegolf.stackexchange.com/a/191117/86301) for this challenge; they might lead to a better score.
[Answer]
# [Haskell](https://www.haskell.org/) (No monomorphism), 245 bytes
```
import Data.List
g1L=all o111111111LLLLLLLLLLaaaaaaaeeeeeeeegggggggghhhhhhhiiiiillllnnnnoooooppppprrrrsssstuu.map length.group.sort.map length.group.sort
o111111111LLLLLLLLLLaaaaaaaeeeeeeeegggggggghhhhhhhiiiiillllnnnnoooooppppprrrrsssstuu i=i==1
```
[Try it online!](https://tio.run/##tdCxbsMgEADQna9AKJtlS/4Ato5Oh3bJEClCqYtPhTsEZ8lfHwKNkyhRlw55Czq4O043mfQzOpcz@ECR5Zth0w2QWNh@0MY5Sf3VcGMuxpVdTRdQuQILqkIVi1TwPHfeBOlGtDx1NtIculQ@//tWvGIACRq07jNq9Yr2SixaPW90j9eVqqbBplH/2cIe16J1ciW8AdRfJKQMM39yHFAuNYiALDeyFpXj3qwEv@3ubzW9bWvK9nCre8hZ8un47YxNud2905aQPMUwQfIfY@IIRwbCMw "Haskell – Try It Online")
---
Here is a work in progress towards a better answer, it solves the problem using 9 distinct characters. However currently there are some characters that appear the same number of times (e.g. `(` and `)`). I'm going to take a break from this, if anyone wants to use this to make a more complete answer go ahead.
```
s+|(ss:sss)|s==ss=1+s+|sss|1==1=s+|sss
s+|ss=1
s|+(ss:sss)|s==ss=s|+sss|1==1=ss:s|+sss
s|+ss=ss
s(ss:sss)=ss+|sss:s(ss|+sss)
s(ss)=ss
ss(1:s)=ss(s)
ss(s:ss)=1==11
ss(s)=1==1
sss(sss)=ss(s(s(sss)))
```
[Try it online!](https://tio.run/##XYw9DsIwDIV3n4MhVtrBZYvkkyCGDkhUlArx2AhnD7YDQmKx389nn2dcTuvaniMhFdYslWh8NeSagAKAK1QBlWyZ@Sqqol1TLBVCzX@4JT/YmrAUS118cTPxqngSEEfJQSFJCZk8tlm88acStmuTfvIBU9fM7Tovm97uy/bYWXKQYRpk2Nucju0N "Haskell – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL) (unreleased master), 10 bytes
```
&u&uqaaaa&
```
[Try it on MATL Online](https://matl.io/?code=%26u%26uqaaaa%26&inputs=%5B%27%26%27%2C+%27u%27%2C+%27%26%27%2C+%27u%27%2C+%27q%27%2C+%27a%27%2C+%27a%27%2C+%27a%27%2C+%27a%27%2C+%27%26%27%5D&version=ee8bd433)
[Multiple test cases](https://matl.io/?code=%60+i+tZN+%3F+x.+%5D+XH%0A%26u%26uqaaaa%26%0AXD+Zx+T%5D&inputs=%5B%27%26%27%2C+%27u%27%2C+%27%26%27%2C+%27u%27%2C+%27q%27%2C+%27a%27%2C+%27a%27%2C+%27a%27%2C+%27a%27%2C+%27%26%27%5D%0A%5B1%2C+2%2C+3%2C+2%5D%0A%5B3%2C+2%2C+2%2C+1%2C+2%2C+3%5D%0A%5B%27a%27%2C+%27b%27%2C+%27c%27%2C+%27b%27%5D%0A%5B%27b%27%2C+%27a%27%2C+%27b%27%2C+%27b%27%2C+%27b%27%5D%0A%5B%27a%27%2C+%27a%27%2C+%27a%27%2C+%27B%27%2C+%27c%27%2C+%27c%27%2C+%27c%27%5D%0A0%2F0&version=ee8bd433)
~~[Try it online!](https://tio.run/##y00syfmfoJCpUBLlp2CvUKGnEKsQ4fHfRLkUiAoTgUDtf4SLQlSFQkjs/2h1NXUdBfVSEIFgFYKIRCyEmnosV7ShjoKRjoIxkARyjMEcIIKKAoUgSpNARDKEBRJMghuShETAlSMIJ7hGKBHLZaBvwAUA "MATL – Try It Online"), but not really - link is to an equivalent 12 byte (non-conforming) version that works on TIO, since `&u` isn't available in it yet.~~
0 = input satisfies the condition, 1 = does not.
Actual code is `&u&uqa&` - take the counts of unique values in the input, take the counts of unique values in *that*, decrement that by one, and see if any of it is non-zero (which would mean the count was greater than 1, hence condition not satisfied). Repeating the non-zeroness check doesn't change anything, but takes `a`'s count to 4 and so makes it occur a unique number of times.
A conforming version that can run on TIO is `888#8#u8#uqaaaa` [Try it online!](https://tio.run/##y00syfmfoJCpUBLlp2CvUKGnEKsQ4fHfwsJC2UK5FIgKE4Hgf4SLQlSFQkjs/2h1NXUdBfVSEIFgFYKIRCyEmnosV7ShjoKRjoIxkARyjMEcIIKKAoUgSpNARDKEBRJMghuShETAlSMIJ7hGKBHLZaBvwAUA "MATL – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 253 bytes
```
(*!!!!!!!!!!!!!!!!!!!!!o*=L=L=L=L*Ln*n*n*nUUU))))))))))))))))))UUUUUUTTTTTTTTTTSSSSSSSSSSSrrnnrrrrrrrrrrLLLLLLLLiiiiiiiiiiiiii//ss&&########*#######@#####&&&&&&&&&&&&&&&&s/ss/ss/s/ss/ss/ss/ss//////((((((((((((((((a*aaaa*)Union@(l=Last/@Tally@#)!=Sort@l&
```
[Try it online!](https://tio.run/##bcrBCsIwDAbgu0/hGJQtDIbzXOgD9CBsPckOQWQWagdtLyJ79lri3HD6/aEhSe8Ybtc7Bn3BOPBYQPbPCFy@A9ICRSlV/lCkW7Qr56x1CznTX@rae8byGcxd0Ms2fPpL9elUpNhAwARKZfVoRWG4RB9q0aExD5GXGW9HF4Rh8eS0DXsxnJ@HqqmOVTP1u3WX5hS6TH2MLw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~406~~ \$\sum\limits\_{i=1}^{26}i= 351\$ bytes
Saved \$27+28=55\$ bytes thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!!
```
lambda l:all(l.count(a)^l.count(p)for a,p in itertools.combinations(set(l),2))
import itertools##22:::^^^^dddddffffff,,,,,,bbbbbbbuuuuuuuu........ccccccccceeeeeeeeeemmmmmmmmmmmpppppppppppprrrrrrrrrrrrsssssssssssss (((((((((((((()))))))))))))))nnnnnnnnnnnnnnnnaaaaaaaaaaaaaaaaiiiiiiiiiiiiiiiiilllllllllllllllttttttttttttttttoooooooooooooooo
```
[Try it online!](https://tio.run/##7dHNisMgEAfwu08x2IuybmDTWyB9kW4LNmpXalQSC7uUPnt2TPqR5r63/RGCmpkJ/I0/6Sv49RBrSqmT7UFJcJV0jrmiCWefmOT7@zJyEzqQIoL1YJPuUgiux4/twXqZbPA963VijouSc2LbGLr0LFytyrKqqj1SmRmJ0WFyvilumjv90D7FmW6mn4M59oK/8gtywS65V2khLGDCRH/rhlFT07fIiak/h//M/zTzQWkDR0ynIqDqy5VAjrPJYU6p4TmoAtdYKM8uPe6g4QK2O17IGLVXuJ1aT7lV5a7YWSw7CbU97ThJuk891MAIbD8ElALW@N4J3K7HLT6383wYBcH7x3kpzxubceY00tBLusL7Bi6GJX6l@OfVEVfDLw "Python 3 – Try It Online")
A veritable ~~triple~~ double super-sized whopper!!!
Returns `False` if the input (any sequence) satisfies the condition, `True` otherwise.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~40~~ 23 bytes
```
⁼№θEθι⁼Eθ№θιEθ№Eθ№θλ№θι
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R18xDWx61TEMmzu1Gw3vRMVDXuR0QomHno8Y953YDxRr3AHWf23FuN4TaS1PDAQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` only if the condition is satisfied. Port of @Grimmy's 05AB1E answer. Explanation: The leading `⁼№θEθι` exists to consume characters to meet the source layout restrictions and also happens to complement the result. The rest of the code is as follows:
```
Eθ№ ι List of counts of elements
θ In list
⁼ Equals
Eθ№ №θι List of counts of counts
Eθ№θλ In list of counts
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~66~~ 55 bytes
```
####>Count@s@@o@uuunnnntttttssssss@s&@@Counts@Counts@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XxkI7JzzS/NKHIodHPIdSktL84CgBASKwcChWM3BAayiGEYpq/0PKMrMK4lW1rVLc1COVasLTk7Mq6vmqjbUMdIx1jGq1eGqBlJACBYAckPynTMSixKTS1KLnPNTUh2UyLRYSQdkCchUsCVgBtBGYx0TVC5QAAJruWr/AwA "Wolfram Language (Mathematica) – Try It Online")
Returns `True` if occurrence counts are not unique, and `False` otherwise.
```
Counts@# occurrence counts
Counts@ count of counts
#### &@@ squared product
>Count@s@@o@uuunnnntttttssssss@s >1
```
`Count@s@@o@uuunnnntttttssssss@s` simplifies to `(Count@s)@uuunnnntttttssssss@s` = `Count[...[s],s]` = 1. The product of positive integers can only be \$\not>1\$ if they are all 1.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 253 bytes
```
n=>new(Set)(n).size>new(Set)(n.map(e=>n.filter(r=>r==e).length)).size//(======ghgmmmmmmmaaaaaaaapppppppppppwwwwwwwwwwwllllllllllllhhhhhhhhhhhhhrrrrrrrrrrrrrggggggggggggggzzzzzzzzzzzzzzzzSSSSSSSSSSSSSSSSSttttttttttttttttnnnnnnnnnnnnnnssssssssssssssssssss
```
[Try it online!](https://tio.run/##dZDBbsIwDIbvPEWPiZQFwc7uS3CsKjDFTVuFtEqjgnj5YsI2Qrd9OUTyb8fR1@GEY@XbIXy4/kRzDTShFR3MBwe5o4vYUZDCST22N0oK@oyDIG7RdWsDeeEh9wAktSVnQiOfE@u1gIhpzPkJfjG8uLywCU2KTzFv3BbsloQF7o3xDw6zXFW9G3tL2vZG1KLYqK36VNtS/kq4yifmj3Q1oc/2dQYZK0xbEdhfxv7YpzpCobXG8ltkQeo/l6VU1c/oMQ5cIb8WG96mMHpWVbx4@Z4/xA93pZzv "JavaScript (Node.js) – Try It Online")
unavoidable new Set size length map filter
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), 36 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ü mÊ
e UUâââmÊmÊmÊmÊÊ
eUâ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=/CBtygplICAgICAgIFVV4uLibcptym3KbcrKCgoKCgoKZVXi&input=WzMsIDIsIDIsIDEsIDIsIDNdCg)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 91 bytes
```
p=>"">p[")||]m",mp="","map"](m=>[p["map"](pa=>a-=m==pa,a=[]),mp|=p[a]>m|m>p[a],p[a]=m])==mp
```
[Try it online!](https://tio.run/##bVDRasMgFH3PV4hPyoxtt8dwhaTtVzgh4pLVEqMkXWlYtl/PNOtgjImce/UcztF71lc9msGGS977l2YxERCgegkgMBZBYjrPymHmAmDMsNMBK@JAyEh9H4IGoXNwAEEzDVLRKJ4hSK2Em51IDUsATlEAF5aaj501DdkxlO9ottmgck0rZYw4wt23iiHlT8gexCGHCmDPDmvEcYZSHpSo5kqkhiWASlEBx@wG7x/FFHVF6wdikW9R@hi9Sasg/0zlztge3ejEw9t4InK33T4kjllFi4mPfrgQWhjfj75reOdfycTP3vb1c1/TImvjoJqr7sjqnWW/hW10Y@iRoaeIitK/5NNKxn1X/SPhnCdjxeMEiEEgkOHmpId9vCzjw@JavgA "JavaScript (Node.js) – Try It Online")
Optimized from
```
A=>"">A["",E="map"](B=>[A["map"](C=>D-=B==C,D=[]),E|=A[D]>B|B>A[D],A[D]=B])>=E
```
Only 5 bytes of direct waste!
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 28 bytes
```
gNUM_NMQUQNUUgg:_NgMUQgUQgQg
```
Takes the list as command-line arguments; or, with the `-r` flag, takes the list of lines of stdin. Outputs 1 if every item's count is unique, 0 if some items have identical counts.
[Try it online!](https://tio.run/##K8gs@P8/3S/UN97PNzA00C80ND3dKt4v3Tc0MB2IAtP//zfmMgJCQyA2/q9bBAA "Pip – Try It Online")
[Self-verify it online!](https://tio.run/##JYmxCcBADAN775IFfgcJXKj@UqR7sj84CgHrTsjnPjOmsIlWU7LXpqF2rj2jUu1yMUaI6jSHDFd@n5Gt45/JXM8L "Pip – Try It Online")
### Explanation
```
gNUM_NMQUQNUUg
```
No-ops to get the character counts right.
```
g:_NgMUQgUQgQg
g ; List of arguments
UQ ; Uniquify (remove duplicates)
M ; Map this function to each:
N ; Count of
_ ; function argument in
g ; original list
g: ; Assign the result back to g
UQg ; g with duplicates removed
Q ; is equal (using string comparison) to
g ; g
```
]
|
[Question]
[
Given a number as input, print out its **collective sum**
What is a collective sum?
Consider the number `13214`, the input
Looping through each of the digits starting from the left, we will be able to obtain its collective sum.
`1` means look at the first digit, and add it to the sum, sum = 1
`3` means look at the "first 3 digits" and add it to the sum, sum = 1 + 132
`2` means look at the "first 2 digits" and add it to the sum, sum = 1 + 132 + 13
`1` means look at the first digit, and add it to the sum, sum = 1 + 132 + 13 + 1
`4` means look at the "first 4 digits" and add it to the sum, sum = 1 + 132 + 13 + 1 + 1321
Total sum = `1468` and this is your output
---
>
> Special cases:
>
>
>
If we encounter a `0`, then clearly we keep the sum the same
```
The number 1301 would have a sum = 1 + 130 + 1 = 132
```
If we encounter a number that is larger then the length of the input, we add it all
```
The number 251 would have a sum = 25 + 251 + 2 = 278
```
---
>
> Test cases:
>
>
>
```
collectiveSum(0) = 0
collectiveSum(2) = 2
collectiveSum(2315) = 23 + 231 + 2 + 2315 = 2571
```
---
Shortest amount of bytes wins. Happy golfing!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~4~~ 3 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
-1 thanks to Kevin Cruijssen (use of `€` avoiding a `}`)
```
€£O
```
**[Try it online!](https://tio.run/##MzBNTDJM/f//UdOaQ4v9//83MjY0BQA "05AB1E – Try It Online")**
### How?
```
€£O - implicit input e.g. 2315
€ - map with:
£ - head to 23, 231, 2, 2315
O - sum 2571
```
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
lambda n:sum(int('0'+n[:int(x)])for x in n)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPqrg0VyMzr0RD3UBdOy/aCsSs0IzVTMsvUqhQyMxTyNP8X1AEFFVI0yhKLI/PzCsoLdHQ1PxvaGxgCAA "Python 2 – Try It Online")
[Answer]
# Python 2, 72 bytes
First submission! Thanks to @DestructibleLemon for the help!
```
import sys;d=sys.argv[1];s=0;for e in d:s+=int(d[:int(e)]);print str(s)
```
[Answer]
## Haskell, ~~43~~ 37 bytes
```
f l=sum[read$'0':take(read[d])l|d<-l]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hx7a4NDe6KDUxRUXdQN2qJDE7VQPEi06J1cypSbHRzYn9n5uYmadgq5CbWOAbr6BRUJSZV6KXpqkQzaWgoGRobGRooqQDYhpAKCMoZWxoqhT7HwA "Haskell – Try It Online")
The input number is taken as a string.
```
[ |d<-l] -- for every digit d in the input string
read[d] -- convert to a number
take l -- and take that many digits from l
0: -- prepend a 0 (to handle 0s)
read -- convert to a number
sum -- sum all numbers
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 36 bytes
```
->n{n.sum{|x|n[0,x.to_i].join.to_i}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk@vuDS3uqaiJi/aQKdCryQ/PjNWLys/Mw/MrK39X6CQFp2eWlKsl5yRWFQc@9/Q2MjQBAA "Ruby – Try It Online")
[Answer]
# JavaScript, ~~42~~ 40 bytes
Thanks @Shaggy for golfing off 2 bytes
```
f=
x=>[...x].map(y=>a+=+x.slice(0,y),a=0)|a
console.log(f("2315"))
console.log(f("0100"))
console.log(f("2"))
console.log(f("01025"))
```
Receives input as a string and returns an integer. As currently written, this code leaves leading zeroes on any integers.
[Answer]
# R, 57 bytes
saved one more thanks to @Vlo
```
sum(strtoi(substring(i<-scan(,""),1,el(strsplit(i,"")))))
```
was:
Saved 4 bytes thanks to @Robert Hacken's suggestion.
```
i=scan(,"");sum(strtoi(substring(i,1,el(strsplit(i,"")))))
```
A simple string approach.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 106 bytes
```
j,k,c,t;f(char*S){for(t=j=0;S[j];j++)c=S[k=S[j]-48<(c=strlen(S))?S[j]-48:c],S[k]=0,t+=atoi(S),S[k]=c;S=t;}
```
[Try it online!](https://tio.run/##LY3NCsIwEIRfpQQKuzaF@gdiXKTPkGPNoaxGk2oqaW7FZ68tepxvvmG4vDNPk5edZJmUBX60caVxtH2ERJ4qpRtvlC8KZNJNR0ssd4cTMA0pPm8BNOL5T49s5CwZqmQqqE29m9sfYaUpqc/0al0AHJefrG4Mic12vRfqHV1IFoSFfMCMsvx6CULW0kKNOM@@ "C (gcc) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
IΣIEθ✂θ⁰Iι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0F8LwTSzQKNRRCM7JTE4FMQx0FMDimZoQYP3/v5Gxoel/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Eθ Map over input string
Iι Cast current character to integer
✂θ⁰ Slice input string to that length
ΣI Cast slices to integer and take the sum
I Cast result to string and implicitly print
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 56 bytes
```
@(n)sum(str2num(['' 32+char(n.*(find(n)<=(n'-48))-32)]))
```
Anonymous function that takes a string as input argument and returns a number as output.
[**Try it online!**](https://tio.run/##LcpBDkAwEIXhvVPYzQzR6JTEgsQ9xELQsDASxfVL6Or/XvL28Rzu2dtGKeVbFHLXhu48WN52ALHhdFyGA0UlaFeZ3kvdoEBWVESZYeqJvEXQhnUBFH3M9S8uA/KwQ4wugfwD "Octave – Try It Online")
The shorter version
```
@(n)sum(str2num(['' char(n.*(find(n)<=(n'-48)))]))
```
works in Matlab, because `char(0)` is treated as a space.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 thanks to Dennis (head vectorises >.<)
4 if we may take lists of digits\*
```
Dḣ`ḌS
```
**[Try it online!](https://tio.run/##y0rNyan8/9/l4Y7FCQ939AT////fyNjQFAA "Jelly – Try It Online")**
\* `ḣ`ḌS`
### How?
```
Dḣ`ḌS - Link: integer, n e.g. 2315
D - to decimal list [2,3,1,5]
` - repeat left as right [2,3,1,5]
ḣ - head [2,3], [2,3,1], [2], [2,3,1,5]
Ḍ - from decimal lists 23, 231, 2, 2315
S - sum 2571
```
[Answer]
# [Perl 6](https://perl6.org), 27 bytes
```
{sum $_ X[&substr]^«.comb}
```
[Test it](https://tio.run/##RZDRaoMwGIXv8xQHJkWpFZNWWyqWPcQuBmMbrc2GTKuYWFZKn2hvsRdz/x9lvTlJvnP4k5NWd1U69EbjnEZFJkR9waxojhr5cDV9De8dzy8z0x@M7V7ffn@ioqkPt4Fij1Ybixy@AORSyRXyHeQq3YR4gMScoVOW8SgpSmssOcrgHo1Z2YZKRlut3SSVkMOM1PlA7HxayZ@QmpCb6HJqKROGKllLB/kdBFnHXSICKszdn6hJJtpqf8Lc1crER9NNDRc7/gQf2y998b3y1PY2CLE976te@57@bnVh9TFAgCvdWxrw992D/4kQ0WdprLgNfw "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit param 「$_」
sum
$_ # the input
X[&substr] # crossed using &substr sub as if it was an infix operator
^«\ # upto 「^」 for each of the following 「«」 (creates Range objects)
.comb # the input split into digits (implicit method call on 「$_」
}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~77~~ 75 bytes
Has to be compiled with the `-lm` switch or GCC doesn't recognize the math functions.
```
r,q,i;f(n){for(r=0,i=n;i;i/=10)q=log10(n)+1-i%10,r+=n/pow(10,q>0?q:0);n=r;}
```
[Try it online!](https://tio.run/##Nc3RCoMgFAbg6/kUEgRKRlrrZmJ7kd2EoQh1Sje2i@jV53JrV/8H/885urRaxxiYZ04aAnQ1cyBBceYUSCddpQSnXo2zFXyvC1G6XHAWCgXVMr/Ibt/xq79wKkEFucXn7AZsiYMHBopWdFrCbkOyfMCqw/lwg4xhYDi9oxJtCKXt1Dsg370l@60U9RGNaH8STS3Of3Jx1G3CFt/ajL29x3KcPg "C (gcc) – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 55 bytes
```
[0*]sq?dsfZ1-se[lfddZrIle^/I%-d0>qIr^/+led1-se0<a]dsaxp
```
No strings nor arrays! Indeed, the required digits are acquired solely through mathematical manipulation.
[Try it online!](https://tio.run/##S0n@/z/aQCu2uNA@pTgtylC3ODU6Jy0lJarIMyc1Tt9TVTfFwK7QsyhOXzsnNQUkbWCTGJtSnFhR8P@/obGRoQkA "dc – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
ṁd´M↑d
```
[Try it online!](https://tio.run/##yygtzv7//@HOxpRDW3wftU1M@f//v5GxoSkA "Husk – Try It Online")
### Explanation
```
ṁd´M↑d -- example input: 1301
d -- decimal digits: [1,3,0,1]
´M -- map over it using it as argument (example with 3):
↑ -- | take: [1,3,0]
-- : [[1],[1,3,0],[],[1]]
ṁ -- map and then sum the result (example on [1,3,0]):
d -- | as decimal: 130
-- : 1 + 130 + 0 + 1 = 132
```
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
[:+/"."0".@{."0 1]
```
## Explanation
Takes a string as input
```
{."0 1 - take
"."0 - current char as int items
] - from the argument
". - and convert them to an integer
[:+/ - add them up
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6209ZX0lAyU9ByqgZSCYex/TS4FrtTkjHyFNAV1Q2MjQxN1JK6BIYJnZIrEMUASR2IaG5qqc/0HAA "J – Try It Online")
[Answer]
# Japt, 5 bytes
Takes input as a string.
```
¬x@¯X
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=rHhAr1g=&input=IjEzMjE0Ig==)
---
## Explanation
```
:Implicit input of integer string U
¬ :Split to an array of characters/digits
@ :Pass each X through a function
¯X :Slice U from the first to the Xth character
x :Reduce by addition
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ç╫&º±å
```
[Run and debug it online](https://staxlang.xyz/#c=%C3%A7%E2%95%AB%26%C2%BA%C2%B1%C3%A5&i=13214%0A1301%0A251%0A2%0A0%0A2315&a=1&m=2)
The corresponding ascii representation of the same program is this.
```
EZFy(e+
E get array of digits
Z push 0 under array of digits
F for each digit, run the rest of the program
y input as a string
( get start of string for specified number of characters
e evaluate substring as integer
+ add
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 10 bytes
```
╝ß⌠≈╛H≈⌡MΣ
```
[Try it online!](https://tio.run/##S0wuKU3Myan8///R1LmH5z/qWfCos@PR1NkeIKpnoe@5xf//KxkaGxmaKAEA "Actually – Try It Online")
# Explanation
```
╝ Push input to register 1
ß Push n-th input (0 by default)
M Map
⌠ ⌡ Function
≈ Cast current character of input to int
╛ Get value of register 1 (input)
H Push input[:current character]
≈ Cast to int
Σ Sum
```
[Answer]
# JavaScript, 43 bytes
It's well after 3 in the morning, why am I still golfing?!
Takes input as a string.
```
s=>(g=x=>s[x]?+s.slice(0,s[x])+g(++x):0)(0)
```
[Try it online](https://tio.run/##bco9CoQwEEDh3mNYzRCViT@NED2IbCExBiUYcZYlt49ubcr38fb5N7O@tvNbHn4xcVWR1QBWBTXwFD6j4Irdpg1Q8W8UFoQI2BMCYdT@YO9M5byFFXLZ1LLNEbOXk0xw3aWUUmfKGtk9HG8)
[Answer]
# Perl 5, 26 bytes
Includes `+1` for `p`
```
perl -pE 's%.%/.{0,$&}/;$\+=$&%eg}{' <<< 2315; echo
```
[Answer]
# [K4](http://kx.com/download/), 22 bytes
**Solution:**
```
+/10/:'(x&#x)#\:x:10\:
```
**Examples:**
```
q)k)+/10/:'(x&#x)#\:x:10\:13214
1468
q)k)+/10/:'(x&#x)#\:x:10\:1301
132
q)k)+/10/:'(x&#x)#\:x:10\:251
278
q)k)+/10/:'(x&#x)#\:x:10\:2315
2571
```
**Explanation:**
Break into base-10, take min of each number and the length of list from this. Convert back and sum up.
```
+/10/:'(x&#x)#\:x:10\: / the solution
10\: / to base 10, 123 => 1 2 3
x: / save as x
#\: / take (#) each left
( ) / the left
#x / count (#) length of x
x& / min of x and the length
10/:' / from base 10 each
+/ / sum up the results
```
[Answer]
# Java 8, 92 bytes
```
n->n.chars().map(c->(c-=48)>0?new Integer(n.substring(0,c<n.length()?c:n.length())):0).sum()
```
**Explanation:**
[Try it online.](https://tio.run/##hY8/b8JADMV3PoXFdJaaUwJUqvgTZgZYGKsO5jjCQeJEuQsIVfnsqRsidaqQ7MHPP/k9X@hGUVlZvhyvncnJe9iS4@8RgONg6xMZC7vfsRfAqH2oHWfAuBCxlZbygYIzsAOGFXQcpazNmWqvUBdUKROl0qvZB6bxmu0dNnI6s7Vi7ZuD7w@q@M0sWeeWs3BWuDbzvwFxHqOghcJu8XSsmkMujoPxrXRHKCT3kO7zi/CZef/wwRa6bIKuZBNyFlOjxvEY@wf@JyaviWny/hJKppNkNlDtqO1@AA)
```
n-> // Method with String parameter and int return-type
n.chars() // Loop over the characters
.map(c->(c-=48) // Convert character to digit
>0? // And if it's larger than 0
new Integer(n.substring(0, // Take the first `x` digits, where `x` is:
c<n.length()? // If the digit higher than the total a.o. digits
c // Take the first `c` digits
: // Else:
n.length())) // Take all digits
: // Else:
0) // Take 0
.sum() // And sum everything
```
[Answer]
**REXX 118 bytes**
```
pull n
l=length(n)
a=0
j=1
do while (j<=l)
if substr(n,j,1)==0 then m=0;
else m=substr(n,1,substr(n,j,1));
a=a+m
j=j+1
end
say a
```
[Try it here](http://tpcg.io/Qm71Pi)
Provide Input value in the STDIN tab.
[Answer]
# [Python 3](https://docs.python.org/3/), 66 bytes
```
lambda n:sum([int(str(n)[:int(i)])if i!='0'else 0for i in str(n)])
```
[Try it online!](https://tio.run/##TcqxCoAgEIDhvae4Jr1Ns5agJ6kGo6SDukJt6OmNiMDt@@E/77gebJLrhrTZfZotcBuuXfbEUYboJWPfviYckRxQ2Qklli0soNzhgYAYvm/EdPp3dVKbSteIxd8qc5Xb6AYxPQ "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
DµḣµVS
```
[Try it online!](https://tio.run/##y0rNyan8/9/l0NaHOxYf2hoW/P//f0NjI0MTAA "Jelly – Try It Online")
Get the `D`igits of the input, then get the first [each digit] elements of the input (`ḣ`ead), then e`V`al each sum to make it a number again and `S`um.
]
|
[Question]
[
Grouping takes a list and splits it into new lists of equal adjacent elements. For example
```
[1,1,2,1,1] -> [[1,1],[2],[1,1]]
```
If you then take the length of these groups you get a new list of integers
```
[1,1,2,1,1] -> [2,1,2]
```
Your task is to write a program that takes a list of positive integers and find the number of times you can group and length it before the resulting list has a single element. For example the list `[1,2,3,3,2,1]` can be regrouped 4 times
```
[1,2,3,3,2,1]
[1,1,2,1,1]
[2,1,2]
[1,1,1]
[3]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
# Test cases
```
[1,2,3,3,2,1] -> 4
[1,2,3,4,5,6,7] -> 2
[1,1,1,1,1,1] -> 1
[2] -> 0
[1,2,4] -> 2
[1,2,2,1,1,2] -> 4
[1,2,2,1,1,2,1,2,2] -> 5
[1] -> 0
```
[Answer]
## Haskell, 49 bytes
```
import Data.List
f[_]=0
f c=1+f(length<$>group c)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrLTo@1taAK00h2dZQO00jJzUvvSTDRsUuvSi/tEAhWfN/bmJmnoKtQm5igW@8gkZBUWZeiV6apkI0l4JCtKGOkY4xEBrpGMbqIARMdEx1zHTMYUJwCBEwQig1QTCNwEqMMATA2Cg29j8A "Haskell – Try It Online")
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 18 bytes
```
q~_,{_e`0f=}*]:,1#
```
[Try it online!](https://tio.run/##S85KzP3/v7AuXqc6PjXBIM22VivWSsdQ@f//aEMFIyA0VDAEk0B2LAA "CJam – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
;.{ḅlᵐ}ⁱ⁾l1∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/31qv@uGO1pyHWyfUPmrc@KhxX47ho47l//9HG@oYAaGhjiGYBLJj/0cBAA "Brachylog – Try It Online")
### Explanation
```
;.{ }ⁱ⁾ Iterate Output times the following predicate on the input:
ḅ Group consecutive equal elements together
lᵐ Map length
l1∧ The result of this iteration must have length 1
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 bytes
```
ÊÉ©1+ßUò¦ ml
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=ysmpMSvfVfKmIG1s&input=WzEsMiwzLDQsNSw2LDdd)
### Explanation
```
Ê É © 1+ßUò¦ ml
Ul -1&&1+ßUò!= ml Ungolfed
Implicit: U = input array
Ul -1 Take U.length - 1.
&& If this is non-zero:
Uò!= Split U between non-equal elements.
ml Take the length of each run of equal elements.
ß Run the entire program again on the resulting array.
1+ Add one to the return value.
```
Recursion is a really non-conventional approach for Japt, but it seems to be 4 bytes shorter than the next alternative...
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~20~~ 19 bytes
**Solution:**
```
#2_{#:'(&~~':x)_x}\
```
[Try it online!](https://tio.run/##y9bNz/7/X9kovlrZSl1Dra5O3apCM76iNsZQwUjBGAiNFAz//wcA "K (oK) – Try It Online")
**Examples:**
```
#2_{#:'(&~~':x)_x}\1 2 3 3 2 1
4
#2_{#:'(&~~':x)_x}\1 2 3 4 5 6 7
2
#2_{#:'(&~~':x)_x}\1 1 1 1 1 1
1
#2_{#:'(&~~':x)_x}\1#2
0
#2_{#:'(&~~':x)_x}\1 2 4
2
```
**Explanation:**
This one is pretty simple, am wondering if there is an even better approach though... Find the indices where the input differs, split at those indices and then count the length of each sub-list. Iterate until results converge to 1.
```
#2_{#:'(&~~':x)_x}\ / the solution
{ }\ / scan over lambda until results converge
x / implicit input
_ / cut at indices
( ) / do this together
~~':x / differ... not (~) match (~) each-previous (':) x)
& / indices where true
#:' / count (#:) each (')
2_ / drop first two results
# / count result
```
**Notes:**
The following **14 byte** solution works for all **except** a single-item list:
```
#1_(-':&~~':)\
```
[Try it online!](https://tio.run/##y9bNz/7/X9kwXkNX3Uqtrk7dSjPGUMFIwRgIjRQM//8HAA "K (oK) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 25 23 bytes
1 byte saved thanks to streetster
1 byte saved thanks to FrownyFrog
```
2#@}.#;.1@(0,2=/\])^:a:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jZQdavWUrfUMHTQMdIxs9WNiNeOsEq3@a3IpcKUmZ@QrpCkYKhgpGAOhkYIhqpCJgqmCmYI5QhAOYUJGyBpMkDlGYIVGWIQgbLjEfwA "J – Try It Online")
Initial solution:
```
_2+[:#(#;.1~1,2~:/\])^:a:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/4420o62UNZSt9QzrDHWM6qz0Y2I146wSrf5rcilwpSZn5CukKRgqGCkYA6GRgiGqkImCqYKZgjlCEA5hQkbIGkyQOUZghUZYhCBsuMR/AA "J – Try It Online")
## Explanation
```
( )^:a: - repeat until result stops changing, store each iteration
;.1~ - cut the input (args swapped)
1,2~:/\] - where the items are no longer the same
# - and take the length of the sublists
2+[:# - finally subtract 2 from the number of steps
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
-1 byte thanks to @Zgarb!
```
←Vε¡(mLg
```
[Try it online!](https://tio.run/##yygtzv7//1HbhLBzWw8t1Mj1Sf///3@0oY4REBrqGIJJIDsWAA "Husk – Try It Online")
### Explanation
```
←Vε¡(mLg) -- example input: [1,2,3,3,2,1]
¡( ) -- repeatedly apply the function & collect results
( g) -- | group: [[1],[2],[3,3],[2],[1]]
(mL ) -- | map length: [1,1,2,1,1]
-- : [[1,2,3,3,2,1],[1,1,2,1,1],[2,1,2],[1,1,1],[3],[1],[1],...
V -- index where
ε -- | length is <= 1: [0,0,0,0,1,1...
-- : 5
← -- decrement: 4
```
[Answer]
## JavaScript (ES6), ~~67~~ ~~65~~ 63 bytes
```
f=a=>a[1]?1+f(q=j=i=[],a.map(x=>x^a[++i]?j=!q.push(++j):++j)):0
```
Oddly enough, JavaScript and Japt seem to have the same shortest algorithm for once...
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ÆÑfá╒]`*Ä
```
[Run and debug it online](https://staxlang.xyz/#c=%C3%86%C3%91f%C3%A1%E2%95%92%5D%60*%C3%84&i=%5B1%2C2%2C3%2C3%2C2%2C1%5D%0A%5B1%2C2%2C3%2C4%2C5%2C6%2C7%5D%0A%5B1%2C1%2C1%2C1%2C1%2C1%5D%0A%5B2%5D%0A%5B1%2C2%2C4%5D%0A%5B1%2C2%2C2%2C1%2C1%2C2%5D%0A%5B1%2C2%2C2%2C1%2C1%2C2%2C1%2C2%2C2%5D%0A%5B1%5D&a=1&m=2)
The ascii representation of the same program is this.
```
{D}{|RMHgf%
```
This uses a stax feature called a [generator](https://github.com/tomtheisen/stax/blob/master/docs/generators.md#generators) that produces value according to transformation and filter blocks.
```
{ } the filter for the generator
D tail of array; this is truthy for length >= 2
{ gf generator block - termination condition is when the filter fails
|R run-length encode into pairs [element, count]
M transpose matrix
H last element
% length of final generated array
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~108~~ 103 bytes
* Saved five bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
j,k,n;f(A,l)int*A;{for(j=k=n=0;j<l;j++)n=A[j]-A[k]?A[k++]=n,A[k]=A[j],1:n+1;A=l>1?-~f(A,k,A[k++]=n):0;}
```
[Try it online!](https://tio.run/##jY9RC4IwFIWf62cEwdaO4FYpuZbsd4gPYRhOWyG92frrNqV6zDjcC@fycQ63CM5F0fcGNawsiUZDK3tfadmV15YYVSurQmn2jTSMUat0ZvJAZ3We@sVYriwGN97BE8u41Ko58DR4Dmk1PhhNQun6y7GyhHbz2a31NSVZLE@PBUpCvMty2nEIrL0EuENEqZwgN9giQuwQ/2a/mkgVDnyqdeOwnmLE2Cb@@OFNjuP53cC7/gU "C (gcc) – Try It Online")
# Explanation (108 bytes version)
```
j,k,n; // array pos, group pos, group val
f(A,l)int*A;{ // function takes array and length
for(j=k=n=0;j<l;j++) // initialize, loop through array
if(n++, // increase n (*), check if group ended
A[j]-A[k]) // group ended
A[k++]=--n, // advance group pos, decrease n, counteracting (*)
A[k]=A[j], // store new group type
n=1; // group is at least one long
A=l>1? // check if array length is larger than one
-~f(A,k,A[k++]=n) // fix last group length, enter recursion
:0;} // array length is less than two, return zero
```
[Try it online!](https://tio.run/##jVLtTp1AEP1dnmJj0oSVIQpaTUtpw3Pc8GMDA3eBzpJl0eotffXbQdCgpr1lQwLJ@ZhzZouwLorjsYEWKBFvnosLoaxVD6I3A4jamrHfft6pzqv8DDqpyZ1nyWFLrEYqnDYknGpxWHUUlaJDqt3eE5WxfpO2KaWXSfO1S5ogkDNRk3ZadfoRQXTG9MLt2a3eLxKeELryKQjg7aSaCotqQEHCP5cgij0WLYPXYZFKLJmd7Zo8zHZtLl@xX4MY1QZBnoYhwbaM8k5RgdsmSnx2ZUczkkOrODfV8xCrUp7OprC1G5yxzMH7Vcs99DijKY2S90tYMJpbdFyfGpwwhFwO1Z7I0u5b9P095yX@0vzS@qzRKVuj5VYVzTLsGv6et9jCGprkukH9k8FsttgvCsAdcUZhsRjtwPtl/pfLZPrr1dkY4zAstu7eACu40ZJ4RGuOP5QmXx68D73lq1T5Zx/LX2dQ@T7/7XJ5iCCGKz4xRBPcSJmcQF7DJ7iB2wlu/419OSdU4wmiU67XE1ydwsRPbvF/ZFiRTy/jP8/46fgH "C (gcc) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~33~~ 24 bytes
Saved 9 bytes thanks to @[Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)!
```
{1=≢⍵:0⋄1+∇2-/⍸2≠/0,⍵,0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rQ9lHnoke9W60MHnW3GGo/6mg30tV/1LvD6FHnAn0DHaCMjkHt/7RHbRMe9fY96mo@tN74UdvER31Tg4OcgWSIh2fw/zQFQzA0AkJDrjQwyxgIETwTEA1lG0HVgtkA "APL (Dyalog Unicode) – Try It Online")
```
{
1=≢⍵ ⍝If the length (≢) of the input (⍵) is 1
:0 ⍝return 0, as we can't go further
⋄1+ ⍝Otherwise, add 1 to the result of the next call:
∇2-/⍸2≠/0,⍵,0 ⍝Next step
0,⍵,0 ⍝ Put 0s on both sides (1 1 1 2 2 1 -> 0 1 1 1 2 2 1 0)
2≠/ ⍝Pairwise reduce with ≠
⍝0 1 1 1 2 2 1 0 -> 1 0 0 1 0 1 1
⍝There is now a 1 wherever a run starts
⍸ ⍝Indices of 1s (indices where runs start)
⍝1 0 0 1 0 1 1 -> 1 4 6 7
2-/ ⍝Pairwise reduce with subtraction (length of each run)
⍝1 4 6 7 -> 3 2 1
∇ ⍝Call itself with new list
}
```
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 19 bytes
```
q~{_);}{_e`0f=}w],(
```
[Try it online!](https://tio.run/##S85KzP3/v7CuOl7TurY6PjXBIM22tjxWR@P/fwA "CJam – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 20 bytes
```
l~{__,(}{e`z0=}w;;],
```
[Try it online!](https://tio.run/##S85KzP1f/T@nrjo@Xkejtjo1ocrAtrbc2jpW53@BYW36/2hDBSMFYyA0UjCM5YLyTBRMFcwUzMF8OATyjKAqTKC0EVjGCJUHxkaxAA "CJam – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), ~~53~~ ~~50~~ ~~49~~ 45 bytes
Includes `+3` for `-p`
Give the list of numbers as one line on STDIN
```
#!/usr/bin/perl -p
s%%$\+=1<s:\d+:$.++x($'-$&and$.=1):eg%eg}{
```
[Try it online!](https://tio.run/##K0gtyjH9/79YVVUlRtvW0KbYKiZF20pFT1u7QkNFXVdFLTEvRUXP1lDTKjVdNTW9tvr/f0MFIwVjIDRSMPyXX1CSmZ9X/F@3AAA "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ŒgL€$ḊпL’
```
[Try it online!](https://tio.run/##y0rNyan8///opHSfR01rVB7u6Do84dB@n0cNM/8fbgeKRP7/H82lEG2oY6RjDIRGOoaxOnC@iY6pjpmOOVQEDsF8I7g6EzjLCCxvhM4HY6gokIwFAA "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 84 bytes
```
f=lambda a:len(a)>1and-~f(eval(''.join('1'+',+'[x==y]for x,y in zip(a,a[1:]))+'1,'))
```
**[Try it online!](https://tio.run/##VY7BCoMwEETP7VfkthtcC0ltC4L@iOSwRUMtNooNRXvor9sYpFCGZXk7A7PD7G@908tii44f15oF513jkGWp2NXpx2Lz4g4BDve@dQgKEqAEqqkoZmP7UUw0i9aJdzsgE1cqN1ImoAikXFbfN0@/BrBSpOkYpEkZ2iijE53pEvmnQHpLZNvW0dH/FEcbme93w9g6H7tIQFoChUqPFtdLeOQL "Python 2 – Try It Online")**
### How?
`f` is a recursive function which, if its input, `a`, has length 2 or more (`len(a)>1`) returns `1+f(x)`\* where `x` is the group lengths of `a`; while if its input is length 1 or 0 returns `False` (equal to 0 in Python) - this is because the right hand side of the `and` does not get evaluated when the left is falsey.
\* `-~f(x)` is `-(-1 - f(x))` but can abut the `and` unlike `1+f(x)` or `f(x)+1`)
The group lengths are calculated by creating code which is then evaluated with `eval(...)`. The code created is something like `1,1,1+1+1,1,1+1,1,` which evaluates to a tuple like `(1,1,3,1,2,1)`.
The code is created by zipping through `a` and `a` without its head (`...for x, y in zip(a,a[1:])` making `x` and `y` each of the adjacent pairs in `a`. If the pair are equal `x==y` evaluates to `True` (1) otherwise `False` (0) - this result is used to index into the string `,+` yielding `+` and `,` respectively and each resulting character is preceded by a `1` (`'1'+...`) - the whole thing then has a final, trailing `1,` appended. For example if `a` were `[5,5,2,9,9,9]` then the `x,y` pairs would be `(5,5)(5,2)(2,9)(9,9)(9,9)` making the equalities `10011` then the characters would be `+,,++`, which with the preceding `1`s becomes `1+1,1,1+1+` and the final trailing `1,` making `1+1,1,1+1+1,` which evaluates to `(2,1,3)` as required.
Note that the trailing `,` ensures that an input with a single group is evaluated as a tuple rather than an integer (i.e. `[3,3]` -> `1+1,` -> `(2)` rather than `[3,3]` -> `1+1` -> `2`)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
[Dg#γ€g]N
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2iVd@dzmR01r0mP9gDxDHSMgNNQxBJNAdiwA "05AB1E – Try It Online")
**Explanation**
```
[Dg# ] # loop until the length of the current value is 1
γ # split into groups of consecutive equal elements
€g # get length of each
N # push the iteration variable N
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes
Saved 2 bytes thanks to Martin Ender. Using CP-1252 encoding, where `±` is one byte.
```
±{_}=0;±x_:=1+±(Length/@Split@x)
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78///Qxur4WlsD60MbK@KtbA21D23U8EnNSy/J0HcILsjJLHGo0PwfUJSZVxKtrKOgpKBrp6Cko3Boo3KsgpqCvoNCdbWhjpGOMRAa6RjW6ihAuSY6pjpmOuYQATgEcY1gikxgDCOwpBEaF4whgrW1/wE "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~54 56 55~~ 54 bytes
```
g=->l,d=0{l[1]?g[l.chunk(&:i).map{|i,j|j.size},d+1]:d}
```
[Try it online!](https://tio.run/##VY7LCsIwEEX3/YrBglgcg4mtQqH6ISGImtIm1ge2WWiab6@xalEuszl35jA3s793XZHN1hXKbG4rTsWm4BU5lOZ8nIxTFZHT7mpbhbrVpFaP3KGcUpFK13HOKTJc@DCkAiEWGHxZjAkuceUp@9AhntGe@Qbmw038s8teRh/2Z/2wfl5N8m56iyD57lCCvID/FXQbAFxNU8MotIo0l21NKm3qBtjKwWwNoS24Eg4modUuGgX5WXZP "Ruby – Try It Online")
[Answer]
# SmileBASIC, ~~110~~ 108 bytes
```
DEF R L,J
K=LEN(L)FOR I=1TO K
N=POP(L)IF O-N THEN UNSHIFT L,0
INC L[0]O=N
NEXT
IF I<3THEN?J ELSE R L,J+1
END
```
Call function as `R list,0`; output is printed to the console.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ŒɠƬṖṖL
```
[Try it online!](https://tio.run/##y0rNyan8///opJMLjq15uHMaEPn8P9z@qGlN5P//0VwK0YY6RjrGQGikYxirA@eb6JjqmOmYQ0XgEMw3gqszgbOMwPJG6HwwhooCyVgA "Jelly – Try It Online")
I assume that `Œɠ` did not exist when Dennis wrote his solution, and it wouldn't surprise me if this challenge had even inspired him to add it, but it's worth showing that this solution is possible now.
[Answer]
# [Python 2](https://docs.python.org/2/), 85 bytes
```
from itertools import*
f=lambda a:~-len(a)and-~f([len(list(v))for k,v in groupby(a)])
```
[Try it online!](https://tio.run/##bY5BCoMwEEX3nmLqypQINdUWCi56juIiomlDYxKSVHDj1dNYpbQin1nMvD9/Rg/uoSTxnhnVAXetcUoJC7zTyrh9xEpBu7qhQC9jKlqZUERlk44suU2d4NYlPUJMGXjiHriEu1EvXQ/BWCFPrQ2JENwZJvgYRHBWIShLyKM1zHGBT/g8Y/KHv5ph9gPJPDqs4vKtGDKdDyLbLyzwU4uliLTh0kF8FQJca50FPS01u9i/AQ "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~51~~ 45 bytes
```
f=function(a)"if"(sum(a|1)>1,f(rle(a)$l)+1,0)
```
[Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jUVMpM01Jo7g0VyOxxlDTzlAnTaMoJxUorpKjqW2oY6D5P00jWcNQx0jHGAiNdAw1Nf8DAA "R – Try It Online")
Recursively take the length of the run length encoding and increment the counter.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 31 bytes
```
,.*
$&_
}`(\b\d+)(,\1)*\b
$#2
_
```
[Try it online!](https://tio.run/##K0otycxL/K@qoeGe8F9HT4tLRS2eqzZBIyYpJkVbU0MnxlBTKyaJS0XZiCv@//9oQx0jHWMgNNIxjOWC8kx0THXMdMzBfDgE8oygKkygtBFYxgiVB8ZGsQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
,.*
$&_
```
If there is a comma, we're going to make another iteration, so append a count character.
```
}`(\b\d+)(,\1)*\b
$#2
```
Replace each run with its decremented length. The above stages repeat until there are no commas left.
```
_
```
Count the number of iterations.
[Answer]
# [Perl 6](https://perl6.org), 52 bytes
```
{+($_,*.comb(/(\d+)[" "$0»]*/).map(+*.words)...^1)}
```
[Test it](https://tio.run/##XZDRboIwFIbv@xQnhiwtdNV2yBIJxofYnXOGQTVkIA0tbsb4ZLvbi7FSGcblT5Pm@8/523OUbMqoa7WEY8SyGKHqBA9ZnUtIunOAvS31WVZX73iKX/OArCcw8WY/3xt/SliVKhz47LNuck0YY2@cXDrbvzJSG0gAI4A1p4I@WQnKN5AsIaQ3GtI5jeiz42Lgoxzljgp3n42d4V2H6LOtxL/8gbpz9eZX7y6N/5k2jsSo38SL/X6MVJkeIHCzxGhXN8NYj0vwtoBh8SFPeFUcVGsIhcUxLVuJPfmlZGZkToDA2T5QaOiXeSscKyiwfaENunS/ "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
+ ( # turn the following into a Numeric (get the count)
$_, # seed the sequence with the input
*.comb( # turn into a string, and grab things that match:
/ # regex
( \d+ ) # a run of digits (number)
[
" " # a space
# (gets inserted between elements of list when stringified)
$0 # another instance of that number
» # make sure it isn't in the middle of a number
]* # get as many as possible
/
).map(
+*.words # turn each into a count of numbers
)
...^ # keep doing that until (and throw away last value)
1 # it gives a value that smart-matches with 1
# (single element list)
)
}
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 78 bytes
```
({}<>)<>({()<(<>{}<(())><>){({}[({})]<>){((<{}>))}{}((){})<>}<>{}({}<>)<>>}{})
```
[Try it online!](https://tio.run/##NUw7CoBQDLvKG5vBoc6lFxGH5yCI4uBaevYaH0hJyI9uTz/uab/6WSWR5jCXEJiY04oAzjDYLQTWYcQiHchIDpia5zf/HzgLVGmbedp0MPUL "Brain-Flak – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), 9 bytes
```
ltt.uhMr8
```
**[Test suite!](https://pyth.herokuapp.com/?code=ltt.uhMr8&input=%5B1%5D&test_suite=1&test_suite_input=%5B1%2C2%2C3%2C3%2C2%2C1%5D%0A%5B1%2C2%2C3%2C4%2C5%2C6%2C7%5D%0A%5B1%2C1%2C1%2C1%2C1%2C1%5D%0A%5B2%5D%0A%5B1%2C2%2C4%5D%0A%5B1%2C2%2C2%2C1%2C1%2C2%5D%0A%5B1%2C2%2C2%2C1%2C1%2C2%2C1%2C2%2C2%5D%0A%5B1%5D&debug=0)**
[Answer]
# [Red](http://www.red-lang.org), 140 bytes
```
func[b][n: 0 while[(length? b)> 1][l: copy[]parse split form b" "[any[copy s[set t string! thru any t](append l length? s)]]b: l n: n + 1]n]
```
[Try it online!](https://tio.run/##bY3NDoIwEITvPsXICeJFKmrCQd/B62YP/BQhqaVpSwxPj5VEI8RM9rDfZGasrKebrEGMJp@aQVdUMukcezzbTkmKldR3315RJhekTCpH1ZuR2BTWSTijOo@mtw@UESIq9EhvH46c9PBw3nb6voVv7YDgwnNcGCN1DYVPt0uYyzyAMKyxCzuaJxOCoRqUQuAQJALfrGiGI044L/hXP1SsktnqF3NC/KfzLTyeXg "Red – Try It Online")
I just wanted to give Red's Parse dialect another try.
Ungolfed
```
f: func [b] [
n: 0
while [(length? b) > 1][
l: copy []
parse split form b " " [
any [copy s [set t string! thru any t]
(append l length? s)]
]
b: l
n: n + 1
]
n
]
```
]
|
[Question]
[
Given a number \$n\$, we have its sum of divisors, \$\sigma(n)\ = \sum\_{d | n} {d}\$, that is, the sum of all numbers which divide \$n\$ (including \$1\$ and \$n\$). For example, \$\sigma(28) = 1 + 2 + 4 + 7 + 14 + 28 = 56\$. This is OEIS [A000203](https://oeis.org/A000203).
We can now define the sum of sum of divisors as \$S(n) = \sum\_{i=1}^{n}{\sigma(i)}\$, the sum of \$\sigma(i)\$ for all numbers from \$1\$ to \$n\$. This is OEIS [A024916](https://oeis.org/A024916).
Your task is to calculate \$S(n)\$, **in time sublinear in \$n\$, \$o(n)\$**.
# Test cases
```
10 -> 87
100 -> 8299
123 -> 12460
625 -> 321560
1000 -> 823081
1000000 (10^6) -> 822468118437
1000000000 (10^9) -> 822467034112360628
```
# Rules
* **Your complexity must be \$o(n)\$**. That is, if your code takes time \$T(n)\$ for input \$n\$, you must have \$\lim\_{n\to\infty}\frac{T(n)}n = 0\$. Examples of valid time complexities are \$O(\frac n{\log(n)})\$, \$O(\sqrt n)\$, \$O(n^\frac57 \log^4(n))\$, etc.
* You can use any reasonable I/O format.
* Note that due to the limited complexity you can't take the input in unary nor output in it (because then the I/O takes \$\Omega(n)\$ time), and the challenge might be impossible in some languages.
* Your algorithm should in theory be correct for all inputs, but it's fine if it fails for some of the big test cases (due to overflow or floating-point inaccuracies, for example).
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
This is code golf, so the shortest answer in each language wins.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~55~~ 52 bytes
Formula is adapted from [this math.SE question](https://math.stackexchange.com/q/3287652). Runs in \$\mathcal{O}(\sqrt{n})\$.
-3 bytes thanks to @dingledooper.
```
->x{(1..$.=x**0.5).sum{(v=x/_1)*_1-(v*~v-$.*~$.)/2}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsHiNNuYpaUlaboWN0107SqqNQz19FT0bCu0tAz0TDX1iktzqzXKbCv04w01teINdTXKtOrKdFX0tOpU9DT1jWproXqdCxTSog0NYrkgNIxhZAxhmBmZwqS0tIwRTDME0zIWYtSCBRAaAA)
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
Runs in \$ \mathcal{O}(\sqrt{n}) \$ time.
```
f=lambda n,i=1:~i*i*(n/-~i-n/i)/2+(i<n and f(n,n/(n/-~i)))
```
[Try it online!](https://tio.run/##TY3NboMwEITvfoq9xaYQvDZ/@aGvUtGGKCvBYoFRlEtenZjSVr2sZvabnXUPfxvYLNS7YfQwPabTOvZT68f2ax4nGrijnrxEHUW5Wq511/SflwY4phqPT4ookpwmT0o4JZWaN0lnhoYvcJUcc7pBpdRyv1HXAh4FELsYhtk7qKFvnCT2MYzN/SOA2Uu1n1wXXu4geYedUgLcGCKhMHC1XS6oV1qVAvWmzOEg0NhVo8kKLQqTr8YazIMLsZ@c1RV@279NiFeIVWbL3/1/VGqbYWgudGGqFw "Python 2 – Try It Online")
## Explanation
Note: [@Neil's answer](https://codegolf.stackexchange.com/a/265132/88546) seems to use a similar approach to mine.
We first take the \$ O(n) \$-time formula \$ \sum\_{i=1}^n{i \cdot \lfloor\frac{n}{i}\rfloor} \$, noticing that there can only be \$ O(\sqrt{n}) \$ unique values of \$ \lfloor\frac{n}{i}\rfloor \$. For example, if \$ n = 50 \$, the possible values of \$ i \$ for each \$ \lfloor\frac{n}{i}\rfloor \$ are:
```
n//i | i
------+-------
1 | 26-50
2 | 17-25
3 | 13-16
4 | 11-12
5 | 9-10
6 | 8-8
7 | 7-7
8 | 6-6
10 | 5-5
12 | 4-4
16 | 3-3
25 | 2-2
50 | 1-1
```
Let \$ a \$ be a sorted list of all unique values of \$ \lfloor\frac{n}{i}\rfloor \$. For this example, \$ a = [ 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 16, 25, 50 ] \$. We can then construct a new summation that solves the problem in \$ O(\sqrt{n}) \$:
$$ \sum\_{i=1}^{|a|}{\left\lfloor \frac{n}{a\_{i}} \right\rfloor \times (T(a\_{i}) - T(a\_{i-1}))} $$
where \$ T(n) \$ is the sum of the first \$ n \$ positive integers, and assuming that \$ a\_0 = 0 \$. Next, a bit of insight allows us to rearrange the summation like so:
$$ \sum\_{i=1}^{|a|}{T(a\_i) \times \left(\left\lfloor\frac{n}{a\_i}\right\rfloor - \left\lfloor\frac{n}{a\_i+1}\right\rfloor\right)} $$
To compute \$ a \$, we can apply the following recurrence:
$$ a\_i = \left\lfloor\frac{n}{\lfloor n / (1+a\_{i-1}) \rfloor}\right\rfloor $$
The proof is left as an exercise to the reader. Finally, we can compute \$ T(n) \$ using the formula \$ \frac{n(n+1)}{2} \$.
[Answer]
# [R](https://www.r-project.org), 52 bytes
```
\(x,y=1:x^.5,z=x%/%y)y%*%z+(z+1)%*%z/2-max(y)*sum(y)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMEiF9ulpSVpuhY3TWI0KnQqbQ2tKuL0THWqbCtU9VUrNStVtVSrtDWqtA01QSx9I93cxAqNSk2t4tJcIAXRu684saAgp1IjWcPQQMfQAIwhhIGmjgtU0YIFEBoA)
Golfed down version of [Dominic's answer](https://codegolf.stackexchange.com/a/265126/67312) which in turn uses the same observation as ovs. Nothing crazy here; should run in \$\mathcal{O}\left(\sqrt n\right)\$ time, but saves bytes by using `1:sqrt(x)` to truncate, and `%*%` to calculate the sumproduct.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 17 bytes (34 nibbles)
```
+:.;.,;^$-2/_$-;~$/*+$~$~$;$!$,_*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWNxW1rfSs9XSs41R0jfTjVXSt61T0tbRV6oDQWkVRRSdeC6IQqn7BTQVDAy5DAzCGEFASRhlAFAIA)
Direct port of my R answer.
This feels very clunky, with half the tokens used for control-flow (`,;,;;~`) or explicit variable names (`$_$$$$$;$$_`); I suspect that one of the stack-based languages will be able to better this...
**Bit-by-bit** (in conjunction with the Nibbles [quick reference](http://golfscript.com/nibbles/quickref.html) and [tutorial](http://golfscript.com/nibbles/tutorial_basics.html)):
y (=floor(sqrt(x)): `^$-2`
z (=floor(x/(1..y))), saving y: `.,;^$-2/_$` (y saved as `$`)
triangle(z), saving z, y & triangle function: `.;.,;^$-2/_$;~$/*+$~$~`
triangle(z)-triangle(y): `.;.,;^$-2/_$-;~$/*+$~$~$;$`
(leaves z saved as `$`, y saved as `@`, x is `_`)
So now we can easily use the saved variables to calculate D:
D = (1..y)\*z + triangle(z)-triangle(y): `+: .;.,;^$-2/_$-;~$/*+$~$~$;$ !$,_*`
[Answer]
# [R](https://www.r-project.org), ~~61~~ ~~51~~ 49 bytes
*Edit: saved ~~10~~ 12 bytes by re-arrangement, goaded (and inspired) by Giuseppe golfing-down my original version in [his answer](https://codegolf.stackexchange.com/a/265138/95126)*
```
\(x,y=1:x^.5,z=x%/%y)min((2*y+z+1)%*%z-y^3-y^2)/2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMEiF9ulpSVpuhY3DWM0KnQqbQ2tKuL0THWqbCtU9VUrNXMz8zQ0jLQqtau0DTVVtVSrdCvjjIHYSFPfCKpRoTixoCCnUiNZw9BAx9AAjCEEEGjquGhC1C1YAKEB)
Golfed calculation based on the same [Math.SE question](https://math.stackexchange.com/q/3287652) used in [ovs' Ruby answer](https://codegolf.stackexchange.com/a/265116).
**Ungolfed**
```
triangle=function(x)x*(x+1)/2
D=
function(x){
y=sqrt(x)%/%1
k=1:y
sum(k*x%/%k+triangle(x%/%k))-triangle(y)*y
}
```
[Answer]
# [Scala 3](https://www.scala-lang.org/), 75 bytes
Port of [@ovs's Ruby answer](https://codegolf.stackexchange.com/a/265116/110802) in Scala.
---
```
x=>{val d=sqrt(x);(BigInt(1) to d).map(k=>x-x%k-(x/k* ~(x/k)-d* ~d)/2).sum}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jZCxTsMwEIbVNU9xSyW7NG3TCoSCYgk2hJgQE2Jwm6SYpG5JXDCqwouwdIF3ok_DOU5SgWjE4vPd_9_n871_5jOe8sl21-kup4_RTME1FxI2DkAYxbDAhPBsnvtwnmX89e5GZULO76kPt1IoCEonwAqrKpUkJhdifikV8UaU0kNSizaeHNROxsdtzNYHR__QG0vh4PHMU4h96wiYjfjdj7WK3dOvKx2wjbGEQf6UKaLpWUOjoJYQ0sGCr0gSMO3qbuISPUx68GYCdUO8hXQ4poN8vSgsctdxnWrpluiDBdL60izbeGSkFZG11Afxl51IOAIBQ5AUGAPPKdvN2EsZod5MXAsZSCyjuM89LNjH-qAr48uDSCMgBEUX2QM-zYGZNlpNCCVHenXyC2JqxQ8UOnrGxlDeMxC_n6ZqKKGFU21tu7XxGw)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~41~~ 38 bytes
```
Nθ≔θη≔⁰ζWη«≔÷θιε≔÷θ⊕εη≧⁺×⁻ιη÷×ε⊕ε²ζ»Iζ
```
[Try it online!](https://tio.run/##bY7NCoMwEITP9Sly3IAF26un0l48WKT0BVJdzEJMNT8WLH321KClF/ewMHwzs1tLYeqnUCEUuvfu6rsHGhh4npyspVbDkDL5V1nKplm9JClkIDl7J7sVFdpdaKQGY4R4ynA2bsJC1wY71A4bQM6XA7tS9Iv5Rq10UClvU3anDi2UpL0FisaY/lUtEDcKj3HFRz9JZUg7OAvrYOI8D@GQrRP2o/oC "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses the formula \$ A024916(n) = \sum\_{i=1}^n i \lfloor n/i \rfloor \$ with the linked observation that it can be calculated more efficiently by grouping terms with the same value of \$ \lfloor n/i \rfloor \$, and then applying @dingledooper's rearrangement that \$ \sum\_{j=1} \lfloor n/a\_j \rfloor (T(a\_j) - T(a\_{j-1})) = \sum\_{j=1} T(a\_j) ( \lfloor n/a\_j \rfloor - \lfloor n/a\_{j+1} \rfloor ) \$ where \$ T(n) \$ are the triangular numbers to save 3 bytes.
```
Nθ
```
Input \$ n \$.
```
≔θη
```
Start counting \$ \lfloor n / a\_j \rfloor \$ down from \$ n \$.
```
≔⁰ζ
```
Start with no total.
```
Wη«
```
Repeat until \$ \lfloor n / a\_j \rfloor \$ is zero. This also conveniently makes a copy of the value, so I can update the original variable in the loop while still being able to access its former value.
```
≔÷θιε
```
Calculate \$ a\_j \$.
```
≔÷θ⊕εη
```
Calculate \$ \lfloor n / a\_{j+1} \rfloor = \lfloor n / ( 1 + a\_j ) \rfloor \$.
```
≧⁺×⁻ιη÷×ε⊕ε²ζ
```
Calculate \$ T(a\_j) ( \lfloor n/a\_j \rfloor - \lfloor n/a\_{j+1} \rfloor ) \$, and accumulate it to the total.
```
»Iζ
```
Output the final total.
On TIO, \$ 10^{11} \$ takes about \$ 10 \$ times as long as \$ 10^9 \$, so the time complexity appears to be \$ O(\sqrt n) \$.
[Answer]
# [Python](https://www.python.org), 74 bytes
```
lambda n,i=0,k=1:(k>=i)*i*k+(i<k and f(n,j:=i+1,l:=n//j)+i*(l*~l-k*~k)//2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RU5LboMwEN37FLO0wQTbEH6qc4AqR6ha0QbUCWAQn0U2WfYS3USq2jvlNrVLo4w00rw3b-a9z5_hNL_35vJV66fvZa6D7PrYlt3roQTDUQveaFnQZqeReeg1PsWHBkpzgJoafiw0-pK3hTZheGQ-erT1zm3QeOeGhaFi_x8X7IZ-nGE6TcT2ZqrmsXpbxgl702KHM5XCFSN1P8Ie0EA_VIYKVhBA7r3wHjTsN9PQWi1znCO6cqBoZk4tZJYdRosorSkyR6zml-uHFBDsIEuJdfmbVJ4TqSI3SxUngiRq60Ck5NYiF2bVRSKTZM0mwIZ8Tti6sFeZlFkcpbf1TZHfFamIYml9EpGojKxxfgE)
### Old [Python](https://www.python.org), 88 bytes
```
lambda n,k=0:sum(i*k*(k>i)+i*(k-~(j:=n//-~i))*(k-(k:=j))//2for i in range(int(n**.5)+1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY5NboMwEEb3nMLLGQLBY_4MEjkBB-iiakXV0DoEgwhZdJNlL9FNpKq9U25TT0mUled78_zZX7_jx_w-2PN3Wz3-HOc21JeHfdO_vDbCBl0ly8OxB-N3PnQbgyvjzvAEu7KyURSeDCID6MpqhxhFqh0mYYSxYmrs2xaMncH6_jrFFSFe-2uWapaGcWtBYukJE_jPwSAqUa8P497MgMwY9M3INQG4iI6OE5dCCwYZLJ3nyydJEW6Ezj2Sy6SKwiMV80wqyaSXqZRDrCh1yWlXL5aa_iMTIPmU4bJwtzSRTuL8tr4Zxd3IZZyQeyeTmdLe8p0_)
Probably similar to @ovs's although found independently.
The basic idea is to regroup the given double sum by divisors and then count how many numbers in the range are a multiple of the divisor.
To achieve O(n^0.5) divisors with the same multiplicity are lumped together.
[Answer]
# JavaScript (ES6), 54 bytes
Based on the formula [found by ovs](https://codegolf.stackexchange.com/a/265116/58563).
```
x=>(g=k=>++k*k>x?--k*k*~k/2:k*(q=x/k|0)-q*~q/2+g(k))``
```
[Try it online!](https://tio.run/##bY1NDoIwGAX3noJlW1LbfuWnmBSvAkEgWkKtGMPCcPUKIRqjvM1bzCRzKR/lUN3O1zvt7an2jfajzlGrjc7D0BCTj0dK5yeTYXAwBDk9MvPkmDoyOQZhiwzGReEr2w@2q/edbVGDgmWCYxwwFqh0908Ff1PIsi0OcuUCooRvCAnEqyBBxFvGXPgkJFfix1jwlzFXlBAqkql/AQ "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES11), 45 bytes
*-3 bytes thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
A port of [dingledooper's answer](https://codegolf.stackexchange.com/a/265137/58563).
Expects a BigInt.
```
f=(n,q=n)=>q&&(i=n/q)*(q-n/++i)*i/2n+f(n,n/i)
```
[Try it online!](https://tio.run/##bY7LDsIgEEX3fgWrBlorDPRBF/gvTW0NphmKNf4@oqmPGGZ7Tu6ZS3/v1@Fql1uJ7jSGMBmKe2@QmaPPMmoNcs9y6kvkRWFZbrnEYooOcsvC4HB183iY3ZlOlLwOkDHCOYFdgoLYqG4TGMQHy65LCVK912XViITRyHozlIQ6pcTIt6KE/v/zyX@VGNIAulJteAA "JavaScript (Node.js) – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~44~~ 42 bytes
```
{+/-[q*k;x@s]+x@q:_y%k:1+!s:_%y}{-2!x*1+x}
```
-2 thanks to @coltim
Same formula as [@ovs' answer](https://codegolf.stackexchange.com/a/265116).
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rW1teNLtTKtq5wKI7VrnAotIqvVM22MtRWLLaKV62srdY1UqzQMtSuqOXiSlM3NFAwNABiI2MFMyNTEBssYIBEAwEXAB0MFQw=)
[Answer]
# [C#](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~82~~ 80 bytes
-2 thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
With 2 dummy parameters (`y` and `z`).
```
(x,y,z)=>Enumerable.Range(1,y=(int)Math.Sqrt(x)).Sum(i=>2*i*(z=x/i)-z*~z+y*~y)/2
```
[Try it online!](https://tio.run/##hY2xDoIwFEV3vqLje1hAanTBshiddJHBGbFoEykRaEI7@Ou1TkxKcnOXe3JP1UdVL91Bq2or1UDJVLdWX58iJzXhDkZqqEWe75VuRFf6IT6X6i4gpYaD5/FUDo@4eHUDjIhxoRuQPGehDMHyMZG4sGH0tpHxbTBhLguCXav61j9dOjmIo1QCakiXlHyDmP3Y5wC2@g9s2HpWMTncBw "C# (Visual C# Interactive Compiler) – Try It Online")
# [C#](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~89~~ 87 bytes
Single parameter.
```
x=>{int i=0,s=0,y=(int)Math.Sqrt(x),z;for(;i++<y;)s+=i*(z=x/i)+(y*~y-z*~z)/2;return s;}
```
[Try it online!](https://tio.run/##fYy9DsIgFIV3n4IRSv@s0eWWLiZOOjk4a6XxJg1EoEnB6KsjPkAdzknO@ZKvt0VvMR4m1beoXE7uerqNsiMDEXEW3SudBEWd2xQvaJrsdHWP8vw0js4sDzBoQwE5bz0wywVmNIi5QsZpyIpPKHxqz6oGjHSTUcTCO8JqtdfK6lGWF4NOHlFJOtB1zRgskGXUbJbQrtn@Ef6M8Qs "C# (Visual C# Interactive Compiler) – Try It Online")
Both use the same formula:
$$
\begin{eqnarray\*}
D(x) &=& \Big(\sum\_{i=1}^{\lfloor\sqrt x\rfloor}i \cdot \Big\lfloor\frac x i\Big\rfloor + T(\Big\lfloor\frac x i\Big\rfloor) \ \Big) - \lfloor \sqrt x\rfloor \cdot T\big(\lfloor \sqrt x\rfloor \big)\\
&=& \Big(\sum\_{i=1}^{y}i \cdot z + T(z) \ \Big) - y \cdot T(y)\\
&=& \sum\_{i=1}^{y}i \cdot z + T(z) - T(y)\ \\
&=& \sum\_{i=1}^{y}i \cdot z + \frac{z \cdot (z-1) - y \cdot (y-1) }{2} \\
\end{eqnarray\*}
$$
where
$$
T(x) = \frac{x(x+1)}{2} \\
y = \lfloor\sqrt x\rfloor \\
z = \Big\lfloor\frac x i\Big\rfloor
$$
]
|
[Question]
[
## Challenge
Given two integer values \$a \ge 2\$ and \$0 \le b < a\$, generate a \$(2a-1) \times (2a-1)\$ matrix consisting of the integers 0, 1, and 2 as follows:
1. Create a checkerboard of 0s and 1s of the given size, corners being 0.
2. If \$b > 0\$, overwrite the checkerboard with 2s in the X shape at the center, each leg being of length \$b\$ (not counting the center).
This pattern is directly modeled from Art Puzzle event grids (where \$a\$ is fixed at 3, \$b=0,1,2\$ represent easy/normal/hard grids, and the 0, 1, 2s in the output represent easy/normal/hard minipuzzles respectively). Blame it if you don't like the edge case of \$b=0\$ :P
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
a = 2, b = 0
[[0, 1, 0],
[1, 0, 1],
[0, 1, 0]]
a = 2, b = 1
[[2, 1, 2],
[1, 2, 1],
[2, 1, 2]]
a = 3, b = 0
[[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0]]
a = 3, b = 1
[[0, 1, 0, 1, 0],
[1, 2, 1, 2, 1],
[0, 1, 2, 1, 0],
[1, 2, 1, 2, 1],
[0, 1, 0, 1, 0]]
a = 3, b = 2
[[2, 1, 0, 1, 2],
[1, 2, 1, 2, 1],
[0, 1, 2, 1, 0],
[1, 2, 1, 2, 1],
[2, 1, 0, 1, 2]]
a = 4, b = 0
[[0, 1, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 1, 0]]
a = 4, b = 1
[[0, 1, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0, 1],
[0, 1, 2, 1, 2, 1, 0],
[1, 0, 1, 2, 1, 0, 1],
[0, 1, 2, 1, 2, 1, 0],
[1, 0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 1, 0]]
a = 4, b = 2
[[0, 1, 0, 1, 0, 1, 0],
[1, 2, 1, 0, 1, 2, 1],
[0, 1, 2, 1, 2, 1, 0],
[1, 0, 1, 2, 1, 0, 1],
[0, 1, 2, 1, 2, 1, 0],
[1, 2, 1, 0, 1, 2, 1],
[0, 1, 0, 1, 0, 1, 0]]
a = 4, b = 3
[[2, 1, 0, 1, 0, 1, 2],
[1, 2, 1, 0, 1, 2, 1],
[0, 1, 2, 1, 2, 1, 0],
[1, 0, 1, 2, 1, 0, 1],
[0, 1, 2, 1, 2, 1, 0],
[1, 2, 1, 0, 1, 2, 1],
[2, 1, 0, 1, 0, 1, 2]]
```
[Answer]
# [R](https://www.r-project.org/), ~~72~~ 68 bytes
```
function(a,b)`[<-`(diag(2*a-1)*0+0:1,cbind(c(x<--b:b,-x),x)+a,2*!!b)
```
[Try it online!](https://tio.run/##BcHBCoAgDADQX8nbphuo3cI/6eKmGF4MosC/t/ee1bbEq32jvP0eIKSYz8QZapcLohUOaL3zR6CifVQoMBOzHko8kSY6oWiNUVwNdgq4fg "R – Try It Online")
Thanks to Robin Ryder for -4 bytes.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~22~~ 21 bytes
```
UO±N01¶10‖O⌈¿IηPX×2⊕η
```
[Try it online!](https://tio.run/##FcoxDoIwFADQ3VM0nX6TmgBxgtGJQUiMg4NLqR9o0n6a8uEMDp7Si1RdX56dTbKL8Tn3g19ogg4nwwgtxY27LQyYQCktZFE@qCykag5XHD1a7ndM3kSoP@/XT90o4GxWhlkpcdk8u5gcMdR3LW4u4Aqyklq0ZBMGJMbnf6om55Oo8nH3Xw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
UO±N01¶10
```
Draw a chequerboard of size `a` with `0`s on its major diagonals above and to the left of the current position.
```
‖O⌈
```
Reflect it to produce a chequerboard of size `2a-1`, leaving the current position in the middle of the chequerboard. (Note that while drawing the chequerboard below and right would save a byte, there is no single byte to reflect up and left, and Charcoal's up reflect is buggy and moves the current position incorrectly anyway.)
```
¿Iη
```
Test whether `b` is zero.
```
PX×2⊕η
```
If not then draw arms of `2`s of length `b+1` (including the centre).
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 82, 80 bytes (@ovs)
```
lambda a,b:(R:=range(1-a,a))and[[1&x+y|(x*x==y*y<=b*b>0)*2for x in R]for y in R]
```
[Try it online!](https://tio.run/##TY/LCsIwEEX3/YrQhSQ1glUEKcaP6La6mNhWA82DNIuE2m@Pra3grO7cA4cZE9xLq@PZ2NiyW@xA8hoQUF7gsmAW1LPB@Q4oEAKqrqp847fhjX3mGQtZuDCe8eueZIdWW@SRUKi8zzEsMSat1RIZY4VySEijrVu3hQjXWKd11//gQ0suFDihVZ/MJk5hdv33eLnrROiBFAma5mvEbToAG@nA2ZiSpV8Bnj4iJH4A "Python 3.8 (pre-release) – Try It Online")
[Old version](https://tio.run/##ZY9LCsIwEED3PUVwIUmNYCuCFONFqouJNhpoPqRZJNSePba2guDs5j14w9jon0bvj9YlwS6pBcXvgIDyqq6LddjEFw55YCzm8cR4zs87kpfCOBSQ1MiBfjS42AIFcp1o/KMpE84oZK2T2iOprHF@2WYjfeO8MW33lTejuNTgpdFdNkU5hSn7y/F840BoSaoMjfMpYrHqgQ2052xYkZkvAo8/EZLe "Python 3.8 (pre-release) – Try It Online")
Nothing too fancy, still learning the ropes. Should run on older python3s, too.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Dи2.ý01ŽNœSΛĀ+Y87S.Λ.º.∊
```
Can probably be shortened with a different approach, but I wanted to try and use the Canvas builtin for this challenge.
-1 byte thanks to *@ovs*.
[Try it online.](https://tio.run/##AS8A0P9vc2FiaWX//0TQuDIuw70wMcW9TsWTU86bxIArWTg3Uy7Omy7Cui7iiIr//zcKMw)
**Explanation:**
```
D # Duplicate the first (implicit) input-integer `a`
и # Create a list with `a` amount of `a`s
2.ý # Intersperse it with 2: [a,2,a,2,a,2,...,a]
01 # Push "01"
ŽNœ # Push compressed integer 6020
S # Convert it to a list of digits: [6,0,2,0]
Λ # Use the Canvas builtin with these three options:
# Length: [a,2,a,2,a,2,...,a]
# Characters to draw: "01"
# Directions: [6,0,2,0]
Ā # Check if the (implicit) second input-integer `b` is NOT 0
+ # Add this check to the (implicit) second input-integer `b`
# (b=0 will remain 0; b≥1 is now b+1)
Y # Push "2"
87S # Push list [8,7]
.Λ # Use the modifiable Canvas builtin with these three options:
# Length: b+1 (or 0 if b=0)
# Characters to draw: "2"
# Directions: [8,7]
.º # Intersected mirror the result towards the left
.∊ # Intersected mirror the result downwards
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ŽNœ` is `6020`.
The Canvas Builtin uses three arguments to draw a shape:
* Length of the lines we want to draw
* Character/string to draw
* The direction to draw in, where each digit represents a certain direction:
```
7 0 1
↖ ↑ ↗
6 ← X → 2
↙ ↓ ↘
5 4 3
```
Here a step-by-step explanation of how it draws for example inputs \$a=5,b=2\$ with these steps:
Preparation: `Dи2.ý` makes the list `[5,2,5,2,5,2,5,2,5]`.
`Dи2.ý01ŽNœSΛ` for this input will have the following Canvas arguments:
* Length: `[5,2,5,2,5,2,5,2,5]`
* Characters: `"01"`
* Directions: `[6,0,6,2]`, which translate to \$[←,↑,→,↑]\$
Step 1: Draw 5 characters (`"01010"`) in direction `6←`:
```
01010
```
Step 2: Draw 2-1 characters (`"1"`) in direction `0↑`:
```
1
01010
```
Step 3: Draw 5-1 characters (`"0101"`) in direction `2→`:
```
10101
01010
```
Step 4: Draw 2-1 characters (`"0"`) in direction `0↑`:
```
0
10101
01010
```
Step 5: Draw 5-1 characters (`"1010"`) in direction `6←`:
```
01010
10101
01010
```
Step 6: Draw 2-1 characters (`"1"`) in direction `0↑`:
```
1
01010
10101
01010
```
Step 7: Draw 5-1 characters (`"0101"`) in direction `2→`:
```
10101
01010
10101
01010
```
Step 8: Draw 2-1 characters (`"0"`) in direction `0↑`:
```
0
10101
01010
10101
01010
```
Step 9: Draw 5-1 characters (`"1010"`) in direction `6←`:
```
01010
10101
01010
10101
01010
```
We then use the Canvas builtin again with three new arguments: `Ā+Y87S.Λ`
* Length: \$b+1\$ (or \$0\$ if \$b=0\$, because with length `1`, direction `8` will draw a `"2"` at the position it was at before the reset unfortunately)
* Characters to draw: `"2"`
* Direction: `[8,7]`, where the `8` is a special direction that resets the starting position (to the bottom-left we started at) and `7` translates to \$↖\$
Draw \$3\$ (\$b=2\$) characters (`"222"`) in direction `7↖`:
```
01010
10101
01210
10121
01012
```
After which we mirror this multi-line string both horizontally and vertically, after which it is output implicitly as our result.
[See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~22~~ 21 bytes
```
_Zvt&+oy&=bitg+>&+>E+
```
Inputs are `a`, then `b`.
[**Try it online!**](https://tio.run/##y00syfn/Pz6qrERNO79SzTYpsyRd205N285V@/9/Yy5DAA)
### Explanation
This uses inputs `3`, `1` as an example. The stack contents are shown in each step. The stack is shown upside down, with the top (i.e. most recent) element down.
```
_Zvt % Implicit input: a. Symmetric range [a a-1 ... 2 1 2 ... a-1 a]. Duplicate
% STACK: [3 2 1 2 3],
[3 2 1 2 3]
&+ % Duplicate. Add to itself transposed, elementwise with broadcast
% STACK [3 2 1 2 3],
[6 5 4 5 6
5 4 3 4 5
4 3 2 3 4
5 4 3 4 5
6 5 4 5 6]
o % Modulo 2, elementwise. Gives checkered matrix
% STACK: [3 2 1 2 3],
[0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
y % Duplicate second-top element
% STACK: [3 2 1 2 3],
[0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0],
[3 2 1 2 3]
&= % Equal? to itself transposed, elementwise with broadcast. Gives "X" matrix
% STACK: [3 2 1 2 3],
[0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0],
[1 0 0 0 1]
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
1 0 0 0 1]
b % Bubble up third-top element
% STACK: [0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0],
[1 0 0 0 1]
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
1 0 0 0 1],
[3 2 1 2 3]
i % Input: b
% STACK: [0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0],
[1 0 0 0 1]
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
1 0 0 0 1],
[3 2 1 2 3],
1
tg+ % Duplicate, convert to logical, add. This converts positive b into b+1
% STACK: [0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0],
[1 0 0 0 1]
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
1 0 0 0 1],
[3 2 1 2 3],
2
> % Greater than?, elementwise
% STACK: [0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0],
[1 0 0 0 1]
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
1 0 0 0 1],
[1 0 0 0 1]
&+ % Add to itself transposed, elementwise with broadcast
% STACK: [0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0],
[1 0 0 0 1]
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
1 0 0 0 1],
[2 1 1 1 2
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
2 1 1 1 2]
> % Greater than?, elementwise. Equivalent to "and not". This trims the "X" matrix
% STACK: [0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0],
[0 0 0 0 0]
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
0 0 0 0 0],
E+ % Multiply by 2, element-wise. Add, element-wise. Implicit display
% STACK: [0 1 0 1 0
1 2 1 2 1
0 1 2 1 0
1 2 1 2 1
0 1 0 1 0]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
^þ
ÇḂ+UṚŒḄŒBɓa‘{ǬḤ
```
[Try it online!](https://tio.run/##y0rNyan8/z/u8D6uw@0PdzRphz7cOevopIc7Wo5Ocjo5OfFRw4zqw@2H1jzcseT/4eX67ppZjxr3cXH9/x9tpKNgEKujAKINQbQxlG@M4BuBaBOouAlU3AQhbhwLAA "Jelly – Try It Online")
With some inspiration from hyper-neutrino's Vyxal solution.
```
^þ Monadic helper link:
þ Table the (range from 1 to the) argument with itself by
^ XOR.
Ḃ The parities of the cells form a checkerboard,
¬ and the diagonal consists of zeroes while the rest is truthy.
ÇḂ+UṚŒḄŒBɓa‘{ǬḤ Dyadic main link:
Ǭ Generate an identity matrix of size
ɓ b
‘ + 1
a { or 0 if b is 0,
Ḥ then double it.
+ Add that to (the top left corner of)
ÇḂ an a by a checkerboard,
UṚ rotate the result 180 degrees,
ŒḄŒB and palindromize it in both dimensions.
```
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ ~~24~~ ~~23~~ ~~22~~ 21 bytes
```
^þ
ÇḂ+ŒḄŒBðÇUoḶ>¥*¬ḤU
```
[Try it online!](https://tio.run/##y0rNyan8/z/u8D6uw@0PdzRpH530cEfL0UlOhzccbg/Nf7hjm92hpVqH1jzcsST0/@Hl@u6aWY8a93Fx/f8fbaSjYBCrowCiDUG0MZRvjOAbgWgTqLgJVNwEIW4cCwA "Jelly – Try It Online")
That feels better. \$a\$ on the left, \$b\$ on the right.
```
^þ Monadic helper link:
þ Table the (range from 1 to the) argument with itself by
^ XOR.
Ḃ The parities of the cells form a checkerboard,
¬ and the diagonal consists of zeroes while the rest is truthy.
ÇḂ+ŒḄŒBðÇUoḶ>¥*¬ḤU Dyadic main link:
Ç Generate an a by a matrix of zeroes on the diagonal and nonzeroes elsewhere.
U Mirror it,
o and replace zeroes with corresponding elements from:
Ḷ ¥ for each 0 .. a-1,
> is it greater than b?
* Raise each to the bth power,
¬ logically negate,
Ḥ double,
U and mirror back.
+ ð Add that to
ÇḂ an a by a checkerboard,
ŒḄŒB then palindromize in both dimensions.
```
[Answer]
# [J](http://jsoftware.com/), 40 bytes
```
((2|+/~)@]+2**@[*=/~@]*(>:]*=/~))|@i:@<:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NTSMarT16zQdYrWNtLQcorVs9escYrU07KxiQUxNzRqHTCsHG6v/mlypyRn5QJ1pCkYQprqurq46hGkIFDXGEDUCipr8BwA "J – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
_þµṂ>Ɠa~¤×¬Ḥ+ḂŒBŒḄ
```
[Try it online!](https://tio.run/##ATEAzv9qZWxsef//X8O@wrXhuYI@xpNhfsKkw5fCrOG4pCvhuILFkkLFkuG4hP/Dh0f/Mv81 "Jelly – Try It Online")
-1 from caird, who noted that I could get rid of a backtick by reading `b` from stdin.
```
For inputs (a, b):
_þµ Make a subtraction table over [1..a], and operate on that.
Ṃ Get the minimum row: this is always [1-a, 2-a ... 0].
>Ɠa~¤ Which elements are greater than (b and ~b)?
For example for (5, 2): Ṃ → [-4, -3, -2, -1, 0]
Ṃ>-3 → [ 0, 0, 1, 1, 1]
׬ Multiply this vector by the a×a identity matrix "¬table"
Ḥ and double the result (generating the 2s)
+Ḃ then add to an a×a checkerboard of 1s "table % 2":
0 0 0 0 0 0 1 0 1 0 0 1 0 1 0
0 0 0 0 0 1 0 1 0 1 1 0 1 0 1
0 0 2 0 0 + 0 1 0 1 0 → 0 1 2 1 0
0 0 0 2 0 1 0 1 0 1 1 0 1 2 1
0 0 0 0 2 0 1 0 1 0 0 1 0 1 2
ŒBŒḄ Finally, palindromize both ways to make the full output.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 70 bytes
```
->a,b{(r=1-a...a).map{|x|r.map{|y|x*x==y*y&&x*x<=b*b&&b>0?2:(x+y)%2}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6lao8jWUDdRT08vUVMvN7GguqaipgjCqKyp0Kqwta3UqlRTA7JsbJO0ktTUkuwM7I2sNCq0KzVVjWpra/8XlJYUK6RFG@kYxIL0aahZZeYVF6Qml2hygaS4oPKmBORNdAzxypvrGGPI/wcA "Ruby – Try It Online")
[Answer]
# Zsh, ~~127~~ ~~116~~ 112 bytes
```
R=({1..$[c=2*$1-1]})
for i ($R)(for j ($R)S+=$[(i==j)|(j+i==c+1)?$2==0?0:${$((i-$1))/\-/}>$2?0:2:(i+j)%2]
<<<$S)
```
[Attempt this Online!](https://ato.pxeger.com/run?1=LY1LDoJADIb3c4pZ1KQVUaawMITKHWAJLpRIgA3Gx8bHSdyQGA7FbRzARft9bZP-n-_jWnVDXLYXbTRrVKw9W0b5lv5EVoH1wN5tGwdfEUZRdBAwq1wfBbi_30p3O5wTwadZryErhJdgXLN_kxp_1xohIRy1mTR1BDKsRRp6YeNYKRxDMbCIF3shPAGxdsEQbXJ3894B2y2HWDsNLXivbD6kNOf2p6Jq_951M38) ~~[116 bytes](https://tio.run/##RY29EoIwEAZ7nuKKcyYR@clBBRN5EKTQjBmSQhy0MubZY4jO2Oztt829HnPQjLvsquYFzhLFAS4SKSiJI@1RFGLq9bKCAeZEWaLy3G3b/vd9NbenBhyZkdLyN7N5FJULPiBJWQ91hw4ZMwUKzqtTUfkjUqzUMZNbvqOp3977sDHzmQaCOlFENsmbn1Nkm0oLAtL5piZ8AA)~~ ~~[127 bytes](https://tio.run/##TY69EoIwEAb7PMUV50xO5CeBipnIgyCFZmRICnHQBmOePYZoYbP37Vb3ekxh5OTYVU8znBWKA1wUyqAV9nKPIhcDG@cFDHAnigK1J7e5/fNVIecolaq6qkW3icgNUXnKS39EGaskYvfF3J4jYM@NUpbe3GZx6ExQt7bcZJZ2cvDpEx82Ms9GkFAlisg67fq3ZWSTSgMC0vmmOnwA)~~
I used bits of the [X without Y](https://codegolf.stackexchange.com/a/233518/15940) problem.
@pxeger saved 4 bytes!
**Description**
```
Using `a = $1` and `b = $2` as defined in the question...
R=({1..X}) define array R as a sequence from 1 to expression X
c=$2*$1-1 size of matrix
for i.. for j.. iterate rows, columns
S+=$[...] add a digit to S, per the logic in [...]
(i==j)|(j+i==c+1)?... are we on a diagonal? if so, do ...
:(i+j)%2 otherwise, fill the matrix with 1s and 0s
$2==0?0 if b is 0, then default to 0 on the diagonal
:${$((i-$1))/\-/}>$2?0:2 if abs(i-a) > b then put 0 on the diagonal, otherwise 2
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~118~~ \$\cdots\$ ~~106~~ 103 bytes
```
i;f(a,b){for(a*=2,i=--a*a;i--;)printf("%d%c",!b|b<abs(a/2-i/a)||i/a-i%a&&i/a+1+i%a-a?i%2:2,i%a?32:10);}
```
[Try it online!](https://tio.run/##ZY/BCsIwDIbvPkUcVFrXoFa82BVfxEtamRR0igoe3F7dmiJTh//hTxq@/G0D7kNIKdpakvbqUZ8ukqbO6OgQaUo2Ilp1vsTmVstC7EQo9Ni3viJ/lTQzGGek2pYdo6DJhJtyUXKLtInCrDlI0GZp1ou5sl3iGDhSbKSCxwhYfB/IPCVwYCyXysHKQllSjwwwD25u2SugDHn1Qb5wVv/iHCt2Ou9x3TaFBuKTsgM6f/5v2EdsGxyIQ37IbvT2Lj1DfaD9NeH9BQ "C (gcc) – Try It Online")
*Saved 3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 24 bytes
```
:±+ʁ:±†vǔd$ʁ:v+∷+2(ṘømÞT
```
[Try It Online!](https://vyxapedia.hyper-neutrino.xyz/tio#WyIiLCI6wrEryoE6wrHigKB2x5RkJMqBOnYr4oi3KzIo4bmYw7htw55UIiwiKSB24bmE4oGLIiwiIiwiMlxuNCJd)
-3 bytes thanks to lyxal
-1 byte thanks to Unrelated String
```
:±+ʁ:±†vǔd$ʁ:v+∷+2(ṘømÞT Full Program; take in order b, a
: duplicate b
± sign
+ add (0 if b is 0, otherwise b+1)
ʁ range (0..x-1)
: duplicate
± sign ([0, 1, 1, ..., 1] of length 0 / b+1)
† logical NOT - [1, 0, 0, ..., 0]
vǔ vectorized rotate; identity matrix of size 0 / b+1
d double; [2, 0, 0], [0, 2, 0], [0, 0, 2]
$ swap a to TOS
ʁ range; 0..a-1
: duplicate
v+ add each; addition table; [2, 3, 4], [3, 4, 5], [4, 5, 6]
∷ parity; checkerboard of size a with 0 in top-left
+ add the two matrices together
2(....) repeat twice
Ṙ reverse (flip vertical)
øm palindromize (reflect vertical; do not copy middle)
ÞT transpose
```
[Answer]
# Excel, 97 bytes
```
=LET(x,SEQUENCE(A1*2-1)-A1,y,TRANSPOSE(x),IF(MOD(x+y,2),1,IF((x-y)*(x+y)+(B1=0)+(ABS(x)>B1),,2)))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnQVfT5BM4NBPJs1G?e=8lgz25)
## Explanation
```
=LET(x,SEQUENCE(A1*2-1)-A1, # [-a..a] vertical
y,TRANSPOSE(x), # [-a..a] horizontal
IF(MOD(x+y,2),1, # if x+y mod 2 <> 0 then 1
IF((x-y)*(x+y)+(B1=0)+(ABS(x)>B1),,2)))
# else if (x<>y and x<>-y) or b = 0 or abs(x) > b then 0 else 2
```
[Answer]
# [Julia](https://www.julialang.org/), ~~336~~ ~~271~~ ~~195~~ 187 Bytes
v4, and thanks for the help!
```
function x(a,b)
s=(2*a-1)
h = zeros(Int8,(s,s))
h[2:2:s^2].=1
if b!=0;h[a,a]=2end
for i in range(1,stop=min(b,a-1))
h[a+i,a+i]=2
h[a-i,a-i]=2
h[a-i,a+i]=2
h[a+i,a-i]=2
end
return(h)
end
```
old:
```
function cross(a,b)
h = zeros(Int8,((2*a-1),(2*a-1)))
h[2:2:(2*a-1)^2] .= 1
c = (Int8((2*a-1)/2+0.5), Int8((2*a-1)/2+0.5))
h[c[1],c[2]] = 2
for i in range(1,stop=min(b,a-1))
h[c[1]+i,c[2]+i] = 2
h[c[1]-i,c[2]-i] = 2
h[c[1]-i,c[2]+i] = 2
h[c[1]+i,c[2]-i] = 2
end
return(h)
end
```
[Answer]
# JavaScript (ES6), ~~87~~ 84 bytes
Expects `(a)(b)`.
```
a=>b=>[...Array(a+--a)].map((_,y,A)=>A.map(_=>x+y&1|(x*x/b<=b&x*x--==y*y)*2,y-=x=a))
```
[Try it online!](https://tio.run/##NY7NboMwEAbveQqfwi7YTgPcmrXEoU9BrGhNID9KceREFZb67jRAc5pvZi975R9@NOFyf6reH9uxo5HJODK11roKgSNwphSj1d98BzjIKCskU816IDNkcb39hSEdNm5Hbv0aShHFNGKay6hoIEYcP@s6lx9Wihe2E4rFirflE8ollkss37GwdqU7H764OQPULIWzKMiIxvcPf2v1zZ@gA0ZwOP8VpmPQV3/pIREJ4v/c9wmKTMzE8Q8 "JavaScript (Node.js) – Try It Online")
### Note
We do `x*x/b<=b` rather than `x*x<=b*b` so that `x*x/b` evaluates to `NaN` when both \$x\$ and \$b\$ are \$0\$. This makes the condition fail as expected for this edge case without the need for an explicit test on \$b\$.
[Answer]
# TI-Basic, 80 bytes
```
Prompt A,B
identity(2A-1→[A]
For(I,1,2A-1
For(J,1,2A-1
remainder(I+J,2)+2max(abs({I,J}-A)≤B and B)max(I={J,2A-J→[A](I,J
End
End
```
+1 byte if not ran on a TI-84+/SE with the 2.53 MP OS or above by replacing `remainder(I+J,2)` with `2fPart(.5(I+J))`.
Output is stored in `[A]`.
[Answer]
# APL+WIN, 72 bytes
Prompts for a then b:
```
(s⊖(s←.5×b-a)⌽z↑(b≠1)×2×m∨⌽m←n∘.=(n←⍳b←(2×b←⎕)+1))+(z←a,(a←(2×⎕)-1))⍴0 1
```
Explanation:
```
(z←a,(a←(2×⎕)-1))⍴0 1 create the 0 1 checkerboard matrix defined by a
2×m∨⌽m←n∘.=(n←⍳b←(2×b←⎕)+1)) create the 2s diagonals defined by b
(b≠1)× filter the case where b=0
z↑ pad the diagonals matrix to the same size as the checkerboard matrix
s⊖(s←.5×b-a)⌽ centre the diagonals in the padded diagonals matrix.
The two matrices are then summed together.
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv0bxo65pQKJtgp7p4elJuomaj3r2Vj1qm6iR9KhzgaHm4elGh6fnPupYARTOBarKe9QxQ89WIw/IfNS7OQlIaQAVgGigwZrahpqa2hpA7RMSdTQSoZIgCV2gxKPeLQYKhv@B1nL9T@My4jLgUldQ5wKxDKEsY7iYMVAUwjKBi5nA1ZkgyRpzcQEA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 92 bytes
```
z,i;f(a,b){for(i*=z=i=2*a-1;i;)printf("\n%d"+!!(i--%z),i%~z&&i%~-z||(i/z-~-a)/~b|!b?i%2:2);}
```
[Try it online!](https://tio.run/##VU9JDsIwDLznFWmkIIcmLD1wII34SC8OVZElCIjlki5fL4mQEMzBssbj8fhojmcMp3mOmmwHqL3qu@sdaOmiI1ct0WwtWXW7U3h2IJogW1EWBZAxMipNcoqLRaomDgPQOprJoFpPfij8gWS1r5Qd57TLL0iBg@pZsueQGXSVxXpnyxIV41/au431NSY6ZWGcf05zEB3IVstWrRKaYH4hdE5uk/rzQ@5ur@cjB/4TNkHk4cjYOL8B "C (clang) – Try It Online")
Function printing to stdout.
Leading line can be removed at the cost of 1 Byte.
```
z : side length
i : characters counter(backwards)
f(a,b){
for(i*=z=i=2*a-1;i;) - initialize variables and itetate backwards until 0
printf("\n%d"+!!(i--%z) - prints:
> a newline if i%z == 0
> the number obtained by expression below at each iteration (decrements i)
i%~z&&i%~-z - false on diagonals
||(i/z-~-a)/~b|!b - false on horizontal window
* for example f(3,1)
01110 11111 11111
10101 00000 10101
11011 || 00000 = 11011
10101 00000 10101
01110 11111 11111
?i%2:2 - draw board on 1's
2's on zeros
```
[Answer]
# Matlab, 79 bytes
```
m=zeros(2*a-1);
m(2:2:end)=1;
for i=a-b:a+b
m(i,i)=2*(b>0);end
max(m,flipud(m))
```
Only make one diagonal of twos and generate the antidiagonal by maxing with the flipped matrix. The `2*(b>0)` was my shortest way to take care of the `b=0` edge case.
]
|
[Question]
[
## Background
The sequence in the title is [A245788](https://oeis.org/A245788) "n times the number of 1's in the binary expansion of n" ("times" here means multiplication), which starts like this:
```
1, 2, 6, 4, 10, 12, 21, 8, 18, 20,
33, 24, 39, 42, 60, 16, 34, 36, 57, 40,
63, 66, 92, 48, 75, 78, 108, 84, 116, 120,
155, 32, 66, 68, 105, 72, 111, 114, 156, 80,
123, 126, 172, 132, 180, 184, 235, 96, 147, 150,
204, 156, 212, 216, 275, 168, 228, 232, 295, 240, ...
```
Though it is not immediately obvious, this sequence has some duplicates (same number appearing at least twice). The first duplicate appears at \$a(22) = a(33) = 66\$. The next ones are \$a(39) = a(52) = 156\$, and \$a(44) = a(66) = 132\$. Note that the duplicates do not appear in ascending order.
It is easy to prove that there exist infinitely many duplicates in this sequence, and I suspect that there exist infinitely many \$k\$-plicates (the numbers that appear at least \$k\$ times in the sequence) as well. For the record, the first triplicate entry is \$a(1236) = a(1545) = a(2060) = 6180\$.
## Challenge
Produce the sequence of **unique** duplicates in A245788, **in ascending order**. For example, 156 should appear after 132, and 6180 should appear only once in the sequence. The following is the list of all 124 terms under 10000, generated using [this Python program](https://tio.run/##NY/BDoIwEETv/YpJPNAaMBJvRL34GcQDQtFNoG1KSTDGb8ct4J66u29npu4dXtac5rn1tkdtu07XgawZQL2zPuBmRxO0Fw3VuODzFc3o@FHeRWs9CGTgK/PUMk/zI5cqBFARI4Q9HmQkqUMdRWSSJ4qX1MY937FkhIEdnCcGeFBWdE9BKZIsY6fsmqRMqwXj/lA5p00j15HuBl1gu4qOYtUZOLhu5KCDnBBjTosdB2fvCWesSZUSf@ftl5IZpeb5Bw):
```
66, 132, 156, 228, 264, 300, 312, 420, 435, 456,
528, 588, 600, 624, 804, 840, 870, 912, 1056, 1100,
1164, 1176, 1200, 1220, 1248, 1545, 1572, 1608, 1635, 1680,
1740, 1824, 2050, 2100, 2112, 2196, 2200, 2244, 2316, 2328,
2340, 2352, 2400, 2440, 2496, 2580, 2628, 2820, 3090, 3108,
3140, 3144, 3216, 3270, 3325, 3360, 3480, 3535, 3648, 3690,
4025, 4098, 4100, 4200, 4224, 4260, 4392, 4400, 4488, 4620,
4632, 4656, 4680, 4704, 4800, 4880, 4914, 4992, 5160, 5256,
5640, 5880, 6125, 6180, 6195, 6216, 6280, 6288, 6432, 6510,
6540, 6650, 6660, 6720, 6960, 7070, 7296, 7380, 7608, 8040,
8050, 8196, 8200, 8220, 8292, 8400, 8448, 8490, 8520, 8580,
8784, 8800, 8976, 9228, 9240, 9264, 9312, 9360, 9408, 9600,
9732, 9760, 9828, 9984
```
Default I/O methods for [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") are allowed:
* Take no input, and output the terms infinitely.
* Take \$n\$ as input, and output the \$n\$-th term (0- or 1-indexed).
* Take \$n\$ as input, and output the first \$n\$ terms.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~72 71 70~~ 69 bytes
A full program that prints the sequence forever.
```
for(n=1;c=2;c||print(n))for(d=++n;d--;)c>>=n==(h=n=>n&&h(n&n-1)+d)(d)
```
[Try it online!](https://tio.run/##FcgxCsAgDADA30iCONipIPEvEhHtkIoVJ/@etssNd6WVHh6tT7dO1XIPEPKB6Qi8dx9NJgji/5mslZCdC8gxkhBB/YxiTAUx4jzajJBRC6C@ "JavaScript (V8) – Try It Online")
### Commented
```
for( // infinite outer loop:
n = 1; // start with n = 1
c = 2; // before each iteration: initialize c to 2
c || print(n) // after each iteration: print n if c = 0
) //
for( // inner loop:
d = ++n; // increment n and start with d = n
d--; // stop when d = 0 / decrement d
) //
c >>= // right-shift d by 1 position if ...
n == ( // ... n is equal to ...
h = n => // ... the result of the recursive function h
n && // which adds d as many times as there are
h(n & n - 1) // bits set in d, using n & n - 1 to clear
+ d // the least significant bit at each iteration
)(d) //
```
### Note
We decrement \$d\$ right away in the inner loop, which means that we never consider the case where the divisor of \$n\$ is \$n\$ itself. But that would only work if there's a single 1 in the binary representation of \$n\$, which means that \$n\$ is a power of \$2\$ and all its divisors have a single 1 in their binary representation as well. Therefore, \$n=1\times n\$ is the only possible solution and \$n\$ does not belong to the sequence.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
×BS)ċ>1µ#
```
[Try it online!](https://tio.run/##y0rNyan8///wdKdgzSPddoaHtir//29oAAA "Jelly – Try It Online")
-1 byte thanks to Jonathan Allan
## Explanation
```
×BS)ċ>1µ# Main Link
# nfind; find first (read from stdin) numbers such that
>1 there is more than one
ċ occurrence of the original number in the list of
) each number from 1 to N
×BS multiplied by its hamming weight
```
Note that `×BS` doesn't actually chain as `× (B S)`. In other words, this isn't *actually* multiplying each number by its hamming weight. However, by distribution of multiplication over addition, instead of doing \$a\times(b\_1+b\_2+\dots+b\_n)\$, it's actually doing \$ab\_1+ab\_2+\dots+ab\_n\$ because `×` vectorizes, and those happen to be literally the same thing. It chains as `(× B) S`, but that ends up giving the same result.
[Answer]
# Scala, ~~144~~ 135 bytes
Saved 9 bytes thanks to Kirill L.!
```
n=>Stream.from(1).scanLeft(0::Nil)((s,x)=>x*Integer.bitCount(x)::s).collect{case h::t if t toSet h=>h}.distinct.take(n*2).sorted take n
```
[Try it in Scastie!](https://scastie.scala-lang.org/OmFSOXakSLmRspjSApwo7Q)
Pretty naive solution. Returns the first n elements.
```
n => //How many elements you want
Stream.from(1) //Infinite list of natural numbers
.scanLeft(0::Nil) //Scan left, collecting prefixes of hamming number sequence (reversed)
((s,x) => //s is the previous sequence, x is a natural number
x * Integer.bitCount(x) //Find the next hamming number
::s) //Prepend to s
.collect{ //Keep the ones that work with this PartialFunction:
case h::t //A prefix with hamming number h at the start and initial piece t
if t toSet h => //If h is a duplicate
h //Keep h
}.distinct //Uniquify
.take(n*2) //Take the first 2n elements
.sorted //Sort them
take n //Take the first n elements
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~19~~ 15 bytes
```
.f<1lfq*TsjT2ZS
```
[Try it online!](https://tio.run/##K6gsyfj/Xy/NxjAnrVArpDgrxCgq@P9/YwA "Pyth – Try It Online")
Outputs the first \$n\$ elements of the sequence.
Explanation:
```
.f<1lfq*TsjT2ZS | Full program
.f<1lfq*TsjT2ZSZQ | with implicit variables
------------------+--------------------------------------------------
.f Q | first Q (input) numbers Z starting at 1 such that
lf SZ | the number of elements T of [1, Z] such that
*TsjT2 | T * sum of digits of T in base 2
q Z | equals Z
<1 | is greater than 1
```
[Answer]
# [Haskell](https://www.haskell.org/), 65 bytes
```
[x|x<-[1..],sum[1|n<-[1..x],n*h!!(n-1)==x]>1]
h=1:do x<-h;[x,x+1]
```
[Try it online!](https://tio.run/##JcsxDsIgFADQ3VO0iUOr0PTHzfZ7A2cHJIYUFFJAIjX5Q88umji@4VmVZ@N90XgtglYauYCukyy/g4A1/kmSxZ2t6yZyaBFJnkBuLMJRP6vfsIMgRnuQJSgXMah0vlXp5eKyXdRsLtZ504x46Pu@1eUz3b165MKnlL4 "Haskell – Try It Online")
The list defined in the first line is the infinite list of duplicates in the sequence. `h` is a helper infinite list that contains the hamming weight of \$n\$ at position \$n-1\$.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
≔⁰θFN«≦⊕θW›²LΦθ⁼θ×λΣ⍘λ²≦⊕θ»Iθ
```
[Try it online!](https://tio.run/##fY3LCsIwFETX7Vfc5Q1EqN12paJSUBHqD8R6bQNJ2rx0IX57bNG1sxqGc5i2F64dhEpp5b3sDBYcLKvy@@AAazPGcIr6Sg4Zg1eeHcX442rTOtJkAt2@RvbspSLAvSMRJqHkcCDThR53Us2D5bC1USg/t4vU5FFxaKLGtfDUBCdNNy8l@wX@vL3z88QH3Agf0DJWpbQs0uKhPg "Charcoal – Try It Online") Link is to verbose version of code. Outputs the `n`th element of the sequence. Explanation:
```
≔⁰θ
```
Start the accumulator at `0`.
```
FN«
```
Find `n` elements of the sequence.
```
≦⊕θ
```
Increment the accumulator.
```
W›²LΦθ⁼θ×λΣ⍘λ²
```
While the number of integers whose base 2 sum multiple equals the accumulator is less than 2, ...
```
≦⊕θ
```
... increment the accumulator.
```
»Iθ
```
Output the accumulator.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 66 bytes
```
for(d=o=[];;o[d]&&print(d))o[p=(h=n=>n&&h(n&n-1)+d)(++d)]=o[p]+1|0
```
[Try it online!](https://tio.run/##DckxCsAgDADA34QEEepWkPQj4iCVoh0SseLUv9sut9ydZnrOXtuwc1/r0o6ZlUP0XkOOAK1XGZiJNDTGwsKHABQUEOvIZELzE/nvaNy7rfUB "JavaScript (V8) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 55 bytes
```
loop{p$.if(1..$.+=1).count{|y|y*y.digits(2).sum==$.}>1}
```
[Try it online!](https://tio.run/##KypNqvz/Pyc/v6C6QEUvM03DUE9PRU/b1lBTLzm/NK@kuqayplKrUi8lMz2zpFjDSFOvuDTX1lZFr9bOsPb/fwA "Ruby – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), ~~140~~ 136 bytes
```
func[n][i: m: 1 until[d: 0 repeat k i: i + 1[p: k b: 0
until[b: p % 2 * k + b(p: p / 2)= 0]if b = i[d: d + 1]]if d > 1[m: m + 1]n < m]i]
```
[Try it online!](https://tio.run/##JY2xDsMgEEP3fIWXSm0zFDKiph@RFd0QCkinFoQQ@X56NNv52WfX4PsWvKUpmh6P/LaZLBskA40jN/5ab6BQQwl7wwfiMWZoW4woJ950xuQsuGDBXfgMdy0DPLDcVijiCIcVPNr8@KeBPF7SJFvpjzKeSMTUS@XcEKFV/wE "Red – Try It Online")
Returns the \$n\$th element of the sequence.
Since the above code is really slow, I decided to write a faster function:
# Faster alternative, 168 bytes
```
func[n][r:[]m: copy#()i: 0 until[p: i: i + 1 b: 0
until[b: p % 2 * i + b(p: to 1 p / 2)= 0]either m/:b[r:
union r to[]b][m/:b: 1](length? r)=(2 * n)]take/part sort r n]
```
[Try it online!](https://tio.run/##PYzLCsIwEEX3/YoLIiS66ANXAfEf3IZZNG1qg20SYrrw6@NUwc1w58yZm@xY7nbUVE2qTJsftCedlKZVYQjxfRDSKTTYfHaLjgq8OZzRwjCufphjxBEdTt@bEezlwE5EjU5e0ZB1ebYJa60M1/OfCx6JLU2G9I4VWhKL9Y8835DkVex1XlLun7aOfcp4BR4JnkpMzmdMaLtL9c9N@QA "Red – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~78~~ 76 bytes
*Edit: -2 bytes thanks to Kirill L.*
```
repeat{T=T+1;s=0;for(n in 1:T)s=s+(n*sum(n%/%2^(0:n)%%2)==T);if(s>1)show(T)}
```
[Try it online!](https://tio.run/##BcExDoAgDADAr7iQtDoIjJD6is4mDhAZLIZqHIxvx7vWe0tn2q6XiScXlWzMtYEMRQYXGJV0Ahn1PkDMbPwKNgga45GIMZYMujjUvT7A@PX@Aw "R – Try It Online")
[Answer]
# [Clojure](https://clojure.org/), ~~81~~ 78 bytes
```
#(for[i(range):when(second(for[j(range i):when(=(*(Long/bitCount j)j)i)]j))]i)
```
[Try it online!](https://tio.run/##Lck7DsJADAXAnlNYovGjIbRIVLTcAKXIx5vYIBttNsrxFwS0M8MzbM1SeZREqe45Rb4r584nwXmbxXmRIXz8hv2C9F8XPvAtfDr2Wq6xeiGDQdEa0CoqdvzK@mEu3UPo1BAnAPUN "Clojure – Try It Online")
Returns the infinite sequence.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~18~~ 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Èò_*¤è1Ãè¥X z}jU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yPJfKqToMcPopVggen1qVQ&input=MTA)
Thanks to @Galen Ivanov for spotting an error which once fixed saved me 1 Byte!
```
È ... }jU - first input U elements to return a truthy value when passed trough : f(XYZ)
ò_ > range[0..X] trough f(Z)
* * multiply Z by
¤è1à * convert to binary string an count '1's
è¥X > is number of elements == X
z > divided by 2 not 0 ?
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ʒLDb1ö*y¢2@
```
Outputs the infinite sequence.
[Try it online.](https://tio.run/##yy9OTMpM/f//Uce8U5N8XJIMD2/Tqjy0yMjh/38A)
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
ʒ # Filter each value `y` by:
L # Pop and create a list in the range [1,`y`]
D # Duplicate this list
b # Convert each inner value to a binary-String
1ö # Sum the digits of each inner binary-String (by converting it to base-1)
* # Multiply each binary-sum to its [1,`y`] value of the duplicated list
y¢ # Count how many times `y` occurs in this list
2@ # And check whether this count is larger than or equal to 2
# (after which the filtered infinite list is output implicitly as result)
```
]
|
[Question]
[
A deck of cards is the Cartesian product of `S` suits and `R` ranks.
Many, though not all, card games use `S=4` and `R∊{6,8,13}`.
A hand of `H` cards is dealt from the deck.
Its *distribution*, a.k.a. "hand pattern", is an array that describes
how many cards you got from each suit, ignoring suit order (so, it's like a multi-set).
Given a distribution `D` satisfying `len(D)=S`, `1≤sum(D)=H≤S×R`, `0≤D[i]≤R`, `D[i]≥D[i+1]`,
find the probability of it occurring.
Input: an integer `R` and an array `D`.
Output: the probability with at least 5 digits after the decimal mark;
trailing zeroes may be skipped; scientific notation is ok.
Loopholes forbidden. Shortest wins.
Tests:
```
R D probability
13 4 4 3 2 -> 0.2155117564516334148528314355068773
13 5 3 3 2 -> 0.1551684646451760586940386335649517
13 9 3 1 0 -> 0.0001004716813294328274372174524508
13 13 0 0 0 -> 0.0000000000062990780897964308603403
8 3 2 2 1 -> 0.4007096203759162602321667950144035
8 4 2 1 1 -> 0.1431105787056843786543452839337155
8 2 2 1 0 -> 0.3737486095661846496106785317018910
8 3 1 1 0 -> 0.2135706340378197997775305895439377
15 4 4 3 2 1 -> 0.1428926269185580521441708109954798
10 3 0 0 -> 0.0886699507389162561576354679802956
10 2 1 0 -> 0.6650246305418719211822660098522167
10 1 1 1 -> 0.2463054187192118226600985221674877
```
See also [Bridge hand patterns in Wikipedia](https://en.wikipedia.org/wiki/Contract_bridge_probabilities#Hand_pattern_probabilities).
EDIT: dropped unnecessary restriction `H≤R`
EDIT: added constraint `H≥1`
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 30 chars
```
×/!⍨,z,1÷((z←!∘≢⊢)⌸⊢),×∘≢!⍨1⊥⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TD0/UVH/Wu0KnSMTy8XUOjCiik@KhjxqPORY@6Fmk@6tkBonQOT4eIgZQaPupaChT8/9/QWCFNwQQIjRWMuMAcUyATzrEEMg0VDCAcIGEAglwWQA5IDRAaQjgmICaMAxZHKDOEmGCKsAio0NAAyAWbB2FCdICZIPWGAA)
Using [@orlp’s formula](https://codegolf.stackexchange.com/a/148624/74681).
[Answer]
# Python 3, 134 bytes
```
b=lambda n,k:k<1or n*b(n-1,k-1)/k
f=lambda R,D,i=1,s=1,t=0:D and b(R,D[0])*i/s*f(R,D[1:],i+1,(D[0]in D[1:])*s+1,t+D[0])or 1/b(~-i*R,t)
```
Formula is the product of `binom(R, d)` for each element `d` in `D`, times `factorial(len(D))`, divided by the product of `factorial(len(S))` for each `S` in the groupings of `D` (e.g. `[4, 4, 3, 2]` has groupings `[[4, 4], [3], [2]]`), finally divided by `binom(len(D) * R, sum(D))`.
Or in math notation, assuming **m** contains the multiplicities of the **n** unique elements in **D**:
$$
\frac{|D|!}{m\_1!\cdot m\_2!\cdots m\_n!}
\binom{|D|\cdot R}{\sum D}^{-1}
\prod\_{d\in D}\binom{R}{d}
$$
[Answer]
# [R](https://www.r-project.org/), ~~90~~ ~~85~~ 83 bytes
```
function(R,D,l=sum(D|1),K=choose)prod(K(R,D),1:l,1/gamma(1+table(D)))/K(R*l,sum(D))
```
[Try it online!](https://tio.run/##JYs7DsIwEAV7n8LlvrAorNIgRDp36biBceKA5A@Kk467mwCaYorRLNXr61FXvyW3PnOiGxsOfdkimbeAh949ci4TXkseafhmsFwCSzvbGC3JYbX3MJEB0O69CfybgeqpOJsIrP@GOivVadk51Q8 "R – Try It Online")
I observed the same thing as [orlp](https://codegolf.stackexchange.com/a/148624/67312), but I picked a nice language that has combinatorics builtins.
Explanation:
```
function(R,D, # next are optional arguments
l=sum(D|1), # alias for length of D, aka S
K=choose) # alias for choose
prod( # take the product of:
K(R,D), # "choose" is vectorized over R and D
1:l, # S!
1/gamma(1+ # gamma(n+1) = n! for integer n
table(D)) # multiplicities of unique elements of D
) / # divide by
K(R`*`l, sum(D)) # R`*`S choose H
# return last computation (which is all the computation)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 bytes using a new quick, `ʋ`, and a new monadic atom `Ẉ`
```
ĠẈ!;L×c⁸S¤ʋ
L!;c@֍P
```
A dyadic link, taking the dealt-distribution, D, on the left and the number-of-ranks, R, on the right, which returns the probability of occurrence.
**[Try it online!](https://tio.run/##y0rNyan8///Igoe7OhStfQ5PT37UuCP40JJT3Vw@itbJDoe3H14e8P//f2MdIyA0/G8BAA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##y0rNyan8///Igoe7OhStfQ5PT37UuCP40JJT3Vw@itbJDoe3H14e8P/onsPLHfQfNa05OunhzhlAGojc//@PjjY01lGIVjDRASEg0yg2VodLASpqChZCF7UECxnqKBggiYIIAwiCiCpYgNSC9IKRIbKoCUQITdQIJopugiGKbaao7oUbYmgAVY5wA0QIxVCIkCHM9lgA "Jelly – Try It Online")
### How?
```
ĠẈ!;L×c⁸S¤ʋ - Link 1, denomParts: list, distribution (D); number, ranks (R)
e.g. [3,3,3,2,2]; 8
Ġ - group indices of D by their values [[4,5],[1,2,3]]
Ẉ - length of each group [2,3]
! - factorial (vectorises) [2,6]
ʋ - last four links as a dyad
- ... i.e. totalWaysToDeal = f(list, distribution (D); number, ranks (R)):
L - length of D 5
× - multiply by R = total number of cards 40
¤ - nilad followed by link(s) as a nilad:
⁸ - chain's left argument, D [3,3,3,2,2]
S - sum = total cards dealt 13
c - binomial 40C13 = 12033222880
; - concatenate [2,6,12033222880]
L!;c@֍P - Main link: list, distribution (D); number, ranks (R)
- e.g. [3,3,3,2,2]; 8
L - length of D = number of suits 5
! - factorial 120
c@ - R binomial (vectorised across) D (8C3=56;8C2=28) [56,56,56,28,28]
; - concatenate [120,56,56,56,28,28]
ç - call the last link (1) as a dyad = denomParts(D,R) [2,6,12033222880]
÷ - divide (vectorises) [120/2,56/6,56/12033222880,56,28,28]
P - product 0.11441900924883391
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes
```
cP¹g!*¹γ€g!P¹gI*¹Oc*/
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/OeDQznRFrUM7z21@1LQmXRHE9QRy/ZO19P//jzbVMQZCo1guQ2MA "05AB1E – Try It Online")
**Explanation**
```
P # product of
c # bin(input1,input2)
* # multiplied by
! # fac of
¹g # length of input1
/ # divided by
P # product of
! # fac of each
€g # length of each
¹γ # chunk of consecutive equal elements of input1
* # multiplied by
c # bin of
¹g # length of input1
I* # times input2
¹O # and sum of input1
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 32 bytes
```
cc*.!lQ*F.cLvzQ*F.!hMr8Q.c*vzlQs
```
**[Try it here!](https://pyth.herokuapp.com/?code=cc%2a.%21lQ%2aF.cLvzQ%2aF.%21hMr8Q.c%2avzlQs&input=%5B1%2C1%2C1%5D%0A10&test_suite_input=%5B4%2C+4%2C+3%2C+2%5D%0A13%0A%0A%5B5%2C+3%2C+3%2C+2%5D%0A13%0A%0A%5B9%2C+3%2C+1%2C+0%5D%0A13%0A%0A%5B13%2C+0%2C+0%2C+0%5D%0A13%0A%0A%5B3%2C+2%2C+2%2C+1%5D%0A8%0A%0A%5B4%2C+2%2C+1%2C+1%5D%0A8%0A%0A%5B2%2C+2%2C+1%2C+0%5D%0A8%0A%0A%5B3%2C+1%2C+1%2C+0%5D%0A8%0A%0A%5B4%2C+4%2C+3%2C+2%2C+1%5D%0A15%0A%0A%5B3%2C+0%2C+0%5D%0A10%0A%0A%5B2%2C+1%2C+0%5D%0A10%0A%0A%5B1%2C+1%2C+1%5D%0A10%0A&debug=0&input_size=3)** or **[Verify all the test cases!](https://pyth.herokuapp.com/?code=cc%2a.%21lQ%2aF.cLvzQ%2aF.%21hMr8Q.c%2avzlQs&input=%5B1%2C1%2C1%5D%0A10&test_suite=1&test_suite_input=%5B4%2C+4%2C+3%2C+2%5D%0A13%0A%0A%5B5%2C+3%2C+3%2C+2%5D%0A13%0A%0A%5B9%2C+3%2C+1%2C+0%5D%0A13%0A%0A%5B13%2C+0%2C+0%2C+0%5D%0A13%0A%0A%5B3%2C+2%2C+2%2C+1%5D%0A8%0A%0A%5B4%2C+2%2C+1%2C+1%5D%0A8%0A%0A%5B2%2C+2%2C+1%2C+0%5D%0A8%0A%0A%5B3%2C+1%2C+1%2C+0%5D%0A8%0A%0A%5B4%2C+4%2C+3%2C+2%2C+1%5D%0A15%0A%0A%5B3%2C+0%2C+0%5D%0A10%0A%0A%5B2%2C+1%2C+0%5D%0A10%0A%0A%5B1%2C+1%2C+1%5D%0A10%0A&debug=0&input_size=3)**
### How this works?
```
cc*.!lQ*F.cLvzQ*F.!hMr8Q.c*vzlQs ~ Full program. D = list, R = number.
.! ~ The factorial of...
lQ ~ The length of D.
* ~ Multiplied by...
*F ~ The product of the elements of...
.c ~ The nCr between...
L Q ~ Each element of D, and...
vz ~ R.
c ~ Divided by...
*F ~ The product of the elements of...
.! ~ The factorial of each...
hM ~ Heads. Count of adjacent elements in...
r8Q ~ The run length encoding of D.
c ~ Divided by...
.c ~ The nCr between...
* ~ The product of...
vz ~ R, and...
lQ ~ The length of D.
s ~ And the sum of D.
~ Output implicitly.
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 42 bytes
```
{×/(!≢⍵),(⍵!⍺),÷((+/⍵)!⍺×≢⍵),!≢¨⍵⊂⍨1,2≠/⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Tqw9P1NRQfdS561LtVU0cDSCo@6t2lqXN4u4aGtj5IEMQ/PB2mAqT00Aog81FX06PeFYY6Ro86F4DU1f7/b2iskKZgAoTGCkZcYI4pkAnnWAKZhgoGEA6QMABBLgsgB6QGCA0hHBMQE8YBiyOUGUJMMEVYBFRoaADkgs2DMCE6wEyQekMA "APL (Dyalog Unicode) – Try It Online")
Still golfing.
[Answer]
## Clojure, 153 bytes
```
#(apply +(for[_(range 1e06):when(=(remove #{0}%)(reverse(sort(vals(frequencies(take(apply + %)(shuffle(for[i(range %2)j(range(count %))]j))))))))]1e-06))
```
Just a brute-force simulation, to get more precision increase the iteration count and the "1 / N" value at the end accordingly. First argument is the counts and 2nd argument is the number of cards in the deck per suite.
[Answer]
# J, 57 bytes
```
](#@]%~[:+/[-:"1[:\:~@(#/.~)"1+/@[{."1])i.@!@(*+/)A.(##\)
```
[Try it online!](https://tio.run/##Rc29DsIgGIXhnas4Qkz5RPmx25c0weugTEaiXRw6Grl1Sqfm5B2e6SytrJgYHr2WtYr5XBMbl24sQ@KZa9TK2UoyGBfTz8qQ6WPjKeqLcfSwWqmZGglpMZSJB1zxZ5RViNfz/cWIgrDv4L3THxz7uUfbAA "J – Try It Online")
This runs in *O(golf)* and will choke on many of the test cases (though works theoretically), which would be fine if it were golfier. But I'm stuck on trimming it down, especially with avoiding those repeated `"1`. If anyone wants to help, here's the parsed version...
The right side of the main fork is all possible deals of the *deck*, and the left side of the main fork is just the original right arg, ie, the suit mask we're matching against.
Inside, from each "shuffled" deck, we take the first *hand* elements, then group them using key `/.` and sort the result, and check if that matches the suit mask in question. We add add up the total number that do match, and divide that into the length of all possible decks.
```
┌─┬─────────────────────────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────┐
│]│┌───────┬─────┬─────────────────────────────────────────────────────────────────────────────────┐│┌──────────────────────┬──┬─────────┐│
│ ││┌─┬─┬─┐│┌─┬─┐│┌──┬─────┬──────────────────────────────────────────────────────────────────────┐│││┌────────┬─┬─────────┐│A.│┌─┬─────┐││
│ │││#│@│]│││%│~│││[:│┌─┬─┐│┌─┬────────┬─────────────────────────────────────────────────────────┐│││││┌──┬─┬─┐│@│┌─┬─────┐││ ││#│┌─┬─┐│││
│ ││└─┴─┴─┘│└─┴─┘││ ││+│/│││[│┌──┬─┬─┐│┌──┬───────────────────────────┬────────────────────────┐│││││││i.│@│!││ ││*│┌─┬─┐│││ ││ ││#│\││││
│ ││ │ ││ │└─┴─┘││ ││-:│"│1│││[:│┌─────────────────────┬─┬─┐│┌───────────┬────────┬─┐│││││││└──┴─┴─┘│ ││ ││+│/││││ ││ │└─┴─┘│││
│ ││ │ ││ │ ││ │└──┴─┴─┘││ ││┌──────┬─┬──────────┐│"│1│││┌─────┬─┬─┐│┌──┬─┬─┐│]││││││││ │ ││ │└─┴─┘│││ │└─┴─────┘││
│ ││ │ ││ │ ││ │ ││ │││┌──┬─┐│@│┌──────┬─┐││ │ ││││┌─┬─┐│@│[│││{.│"│1││ ││││││││ │ │└─┴─────┘││ │ ││
│ ││ │ ││ │ ││ │ ││ ││││\:│~││ ││┌─┬──┐│~│││ │ │││││+│/││ │ ││└──┴─┴─┘│ │││││││└────────┴─┴─────────┘│ │ ││
│ ││ │ ││ │ ││ │ ││ │││└──┴─┘│ │││#│/.││ │││ │ ││││└─┴─┘│ │ ││ │ ││││││└──────────────────────┴──┴─────────┘│
│ ││ │ ││ │ ││ │ ││ │││ │ ││└─┴──┘│ │││ │ │││└─────┴─┴─┘│ │ ││││││ │
│ ││ │ ││ │ ││ │ ││ │││ │ │└──────┴─┘││ │ ││└───────────┴────────┴─┘│││││ │
│ ││ │ ││ │ ││ │ ││ ││└──────┴─┴──────────┘│ │ ││ │││││ │
│ ││ │ ││ │ ││ │ ││ │└─────────────────────┴─┴─┘│ │││││ │
│ ││ │ ││ │ ││ │ │└──┴───────────────────────────┴────────────────────────┘││││ │
│ ││ │ ││ │ │└─┴────────┴─────────────────────────────────────────────────────────┘│││ │
│ ││ │ │└──┴─────┴──────────────────────────────────────────────────────────────────────┘││ │
│ │└───────┴─────┴─────────────────────────────────────────────────────────────────────────────────┘│ │
└─┴─────────────────────────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────┘
```
]
|
[Question]
[
Given two positive integers `a` and `b`, output two positive integers `c` and `d` such that:
* `c` divides `a`
* `d` divides `b`
* `c` and `d` are co-prime
* the [least common multiple](https://en.wikipedia.org/wiki/Least_common_multiple) of `c` and `d` equals the least common multiple of `a` and `b`.
If there are more than one possible answers, you can output only one or all of them.
Test cases:
```
a b c d
12 18 4 9
18 12 9 4
5 7 5 7
3 6 1 6 or 3 2
9 9 9 1 or 1 9
6 15 2 15 or 6 5
1 1 1 1
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 13 bytes
```
ÆEz®0iṂ$¦€ZÆẸ
```
[Try it online!](https://tio.run/##ASkA1v9qZWxsef//w4ZFesKuMGnhuYIkwqbigqxaw4bhurj///8yMjUwLDM2MA "Jelly – Try It Online")
>
> If **a = 2A · 3B · 5C · …** and **b = 2α · 3β · 5γ · …**, then we compute
>
>
> * **c = 2A>α?A:0 · 3B>β?B:0 · 5C>γ?C:0 · …**
> * **d = 2A>α?0:α · 3B>β?0:β · 5C>γ?0:γ · …**
>
>
> Now **lcm(c, d) = 2max(A>α?A:0, A>α?0:α) · … = 2max(A, α) · 3max(B, β) · … = lcm(a, b)**
>
>
> and **gcd(c, d) = 2min(A>α?A:0, A>α?0:α) · … = 20 · 30 · 50 · … = 1**.
>
>
>
In other words: start from **(c, d) = (a, b)**. Then, for each prime, divide that prime *all the way out* of the factorization of either **c** or **d**: whichever has the smallest exponent for that prime. (In this implementation, in case of a tie, **c** loses its exponent.)
So if **a = 2250 = 21 · 32 · 53** and **b = 360 = 23 · 32 · 51**,
then **c = 20 · 30 · 53 = 125** and **d = 23 · 32 · 50 = 72**.
Jonathan Allan golfed down a whopping 8 bytes! Thank you~
[Answer]
# R, ~~143~~ ~~139~~ 123 bytes
```
f=function(a,b,q=1:(a*b))for(i in 1:a)for(j in 1:b)if(!a%%i+b%%j&max(q[!i%%q+j%%q])<2&i*j==min(q[!q%%a+q%%b]))cat(i,j,"\n")
```
(Thanks to @Giuseppe for those 19 bytes off!)
With indentations, newlines and some explanations:
```
f=function(a,b,
q=1:(a*b)) #Defined as function arguments defaults to avoid having to use curly brackets
for(i in 1:a)
for(j in 1:b)
if(!a%%i + b%%j & #Is a divided by c and b divided by d
max(q[!i%%q+j%%q])<2 & #Are c and d coprimes
i*j==min(q[!q%%a+q%%b])) #Is this the same lcm
cat(i,j,"\n") #Then print
```
Test cases:
```
> f=function(a,b,q=1:(a*b))for(i in 1:a)for(j in 1:b)if(!a%%i+b%%j&max(q[!i%%q+j%%q])<2&i*j==min(q[!q%%a+q%%b]))cat(i,j,"\n")
> f(5,7)
5 7
> f(12,18)
4 9
> f(6,15)
2 15
6 5
> f(1,1)
1 1
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
→ÖF§-⌋⌉ΠmḊ
```
Brute force. Takes and returns lists, and works for more than two numbers too. [Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/j9omHZ7mdmi57qOe7kc9necW5D7c0fX///9oQyMdQ4tYrmhDCx1DIyBtqmMOJI11zICkpY4lkDTTMTQFKdAxBJJGRqYGOsZmBrEA "Husk – Try It Online")
## Explanation
```
→ÖF§-⌋⌉ΠmḊ Implicit input, say [6,15]
mḊ Map divisors: [[1,2,3,6],[1,3,5,15]]
Π Cartesian product:[[1,1],[2,1],[1,3],[2,3],[3,1],[1,5],[3,3],[6,1],[1,15],[2,5],[3,5],[6,3],[2,15],[6,5],[3,15],[6,15]]
Ö Sort by
F reduce by
⌉ lcm
-⌋ minus gcd: [[1,1],[3,3],[2,1],[1,3],[3,1],[6,3],[1,5],[2,3],[6,1],[2,5],[3,15],[1,15],[3,5],[6,15],[2,15],[6,5]]
→ Get last element: [6,5]
```
[Answer]
# Mathematica, 82 bytes
```
#&@@Select[Subsets[Flatten@Divisors[{t=#,r=#2}],{2}],GCD@@#==1&&LCM@@#==t~LCM~r&]&
```
[Answer]
# JavaScript (ES6), ~~90~~ ~~84~~ 80 bytes
Takes input in currying syntax `(a)(b)` and returns an array of 2 integers.
```
a=>g=(b,c=1)=>(G=(a,b)=>b?G(b,a%b):a)(c,d=a*b/G(a,b)/c)-1|a%c|b%d?g(b,c+1):[c,d]
```
### Test cases
```
let f =
a=>g=(b,c=1)=>(G=(a,b)=>b?G(b,a%b):a)(c,d=a*b/G(a,b)/c)-1|a%c|b%d?g(b,c+1):[c,d]
console.log(JSON.stringify(f(12)(18))) // [ 4, 9 ]
console.log(JSON.stringify(f(18)(12))) // [ 9, 4 ]
console.log(JSON.stringify(f( 5)( 7))) // [ 5, 7 ]
console.log(JSON.stringify(f( 3)( 6))) // [ 1, 6 ] or [ 3, 2 ]
console.log(JSON.stringify(f( 9)( 9))) // [ 9, 1 ] or [ 1, 9 ]
console.log(JSON.stringify(f( 6)(15))) // [ 2, 15 ] or [ 6, 5 ]
console.log(JSON.stringify(f( 1)( 1))) // [ 1, 1 ]
```
### How?
```
a => // a = first input
g = ( // g = recursive function that takes:
b, // b = second input
c = 1 // c = first output divisor, initially set to 1
) => //
(G = (a, b) => // G = function that takes a and b
b ? G(b, a % b) : a // and returns the greatest common divisor
)( // we call it with:
c, // - c
d = a * b / G(a, b) / c // - d = LCM(a, b) / c = a * b / GCD(a, b) / c
) - 1 | // if the result is not 1 (i.e. c and d are not coprime)
a % c | // or c does not divide a
b % d ? // or d does not divide b:
g(b, c + 1) // do a recursive call with c + 1
: // else:
[c, d] // return [c, d], a valid factorization of the LCM
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~17~~ 16 bytes
```
&YFt&X>2:!=*^!Xp
```
[Try it online!](https://tio.run/##y00syfn/Xy3SrUQtws7IStFWK04xouD//2hDMx0FQ7PY/wA "MATL – Try It Online")
Same method as Lynn's Jelly solution
It's been a while since I've used any MATL (or matlab for that matter) so many improvements are likely possible.
[Answer]
# [Haskell](https://www.haskell.org/), ~~50~~ ~~48~~ ~~47~~ ~~45~~ 42 bytes
```
(?)=gcd;a!b|c<-div a$a?b=(c*c?b,div b$c?b)
```
Idea: I noticed that `c*d = a*b/gcd(a,b)`. So the algorithm performs two steps:
1. Begin with `c' = a/gcd(a,b)` and `d' = b`. This fulfils all requirements except that `c'` and `d'` have to be co-prime.
2. To make them co-prime, I calculate `e = gcd(c',d')` and then set `c = c'*e` and `d = d'/e`. This keeps all properties (since the combined factors stay the same), but since I remove all shared factors from `d`, I make `c`and `d` coprime.
In my implementation, `c'` is just called `c`.
[Try it online!](https://tio.run/##y0gszk7Nyfn/X8Ne0zY9OcU6UTGpJtlGNyWzTCFRJdE@yVYjWSvZPkkHJJCkAmRp/s9NzMyzzU0s8I3XKCjKzCvRK81LLi0qqtRQ1NSM1jA00jG00NTRMLTQMTQC0qY65kDSWMcMSFrqWAJJMx1DU5ACHUPN2P8A "Haskell – Try It Online")
-3 bytes thanks to Laikoni
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
Ñ`âʒ.¿I.¿Q}н
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8MSEw4tOTdI7tN8TiANrL@z9/z/a0EjH0CIWAA "05AB1E – Try It Online")
or as a [Test suite](https://tio.run/##MzBNTDJM/V9W@f/wxITDi05N0ju0vxKIA2sv7P1fqXR4v5XC4f1KOv@jow2NdAwtYnWiDS10DI2AtKmOOZA01jEDkpY6lkDSTMfQFKRAxzA2FgA)
[Answer]
# [R](https://www.r-project.org/), 126 bytes
```
function(a,b,g=function(x,y)ifelse(o<-x%%y,g(y,o),y),l=a*b/g(a,b))matrix(c(C<-(1:l)[!l%%1:l],D<-l/C),,2)[g(C,D)<2&!a%%C+b%%D,]
```
[Try it online!](https://tio.run/##PYtBCoMwFAX3PUVd/PJ/@4LookiJq@QW4iKKCUJUsBb09KnddDczMGvyV62S/8z9Ni4zO3QI9V93HDL6Ib4HXrTaiQ4EPrDI2RFrd@/y8HtEJret4849G624eEVpskh0QgurVcyNAKU0gQ2s6PKWOSLz6Igs2uS5KFFUcjnhiUrSFw "R – Try It Online")
This takes a different (and apparently less golfy) approach to finding the values than [the other R answer](https://codegolf.stackexchange.com/a/142881/67312).
Explanation:
```
function(a,b){
G <- function(x,y)ifelse(o<-x%%y,G(y,o),y) #gcd function, vectorized for x,y
l <- a*b/g(a,b) #lcm of a,b
C <- (1:l)[!l%%1:l] #divisors of l
D <- l/C #l/C is the other half of the pair
rel_prime <- G(C, D) < 2 #pairs where C,D are relatively prime, lol, GCD
a_div <- !a%%C #divisors of a
b_div <- !b%%D #divisors of b
C <- C[rel_prime & a_div & b_div]
D <- D[rel_prime & a_div & b_div] #filter out the bad pairs
matrix(c(C,D),,ncol = 2) #matrix of pairs, returned
}
```
except I shoehorn all the definitions as default arguments and do all the calculations on one line for the golfiness.
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
(*/:"1)&.|:&.(_&q:)
```
[Try it online!](https://tio.run/##HcNNCoMwFADhfU4xuIiJSOxL8e@JNxFclAZxU4pbe/ZUZL7ZczqYlQfX2VWNFuJtONUGt9qv@uxNESjTrCU1PyUdxrxf24c14qbkFyQiwy3S0vOkY7zqkBZB8h8)
Based on @Lynn's [solution](https://codegolf.stackexchange.com/a/142892/6710).
## Explanation
```
(*/:"1)&.|:&.(_&q:) Input: [a, b]
_&q: Get exponenets of each prime
|:& Transpose
/:"1 & Grade each row
* Multiply elementwise
&.|: Transpose
&. _&q: Convert exponents back to numbers
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~91~~ 74 bytes
```
a!b=[(x,y)|x<-[1..a],y<-[1..b],rem a x+rem b y+gcd x y<2,lcm a b==lcm x y]
```
[Try it online!](https://tio.run/##JYxBCoMwFESv8t0l@BV@ilbB9AY9QZpFYqUVo4jtIoHePU3azZthZpineS2TczGawkrFPAb@8UOlqK6NxvB3VuMxrWDAl1kthPIx3sFDGAS6MTdWymxSpONq5g0krGa/AtuPeXvX7Pa7ri6@CJyDYiSQOo6MOiSRtMFz4gnbxB77xBapyQMkruMX "Haskell – Try It Online")
*Saved **17** bytes thanks to Laikoni*
[Answer]
# [Python 2](https://docs.python.org/2/), 75 bytes
```
def f(x):n=1;exec'n+=1;j=k=1\nwhile x[j]%k<1:k*=n**j;j^=1\nx[j]/=k/n;'*x[0]
```
Input is taken as a list, which the function modifies in place.
[Try it online!](https://tio.run/##fY5NDoIwEIXXcIrZkGptgq0B@bEnwbrREmjJQAjEevraegAXk@/Lm7d4y2cbZhTev3QP/cEdG5S81U4/CZ6CGWklv@N7GCcNrjMqszfeWCqRUtOaR3zGOJc2x5ZQ152V7@cVHIwIHRcMeKVYsCqYiFYwuEZeGJSRNYM6sgyF4lcNopo0WdYRNyCZ2CEcgQy2fZl0GMnSJG79V/Ff "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 129 bytes
```
lambda a,b:[[c,d]for c in range(1,-~a)for d in range(1,-~b)if((gcd(c,d)<2)*a*b/gcd(a,b)==c*d/gcd(c,d))>a%c+b%d]
from math import*
```
[Try it online!](https://tio.run/##VYw7DsIwEAV7TrFNJK8xihIahDAXCSnWXpxYwh9Zbmi4ukkKCsqZ0Xv5XdcUz83pR3tRMExAylynySqeXSpgwUcoFJenGNTpQ7hL/pcGvRNisSy2Fd5GlCRNv/P2hVpbyf2v4p06ezQdzwdXUoBAdQUfcipVtlx8rMKJYVQwXBDbFw "Python 3 – Try It Online") or [Try the test suite.](https://tio.run/##VYzLDoIwFAX3fMXdkPTWGlKID4z4I8iiDwtNbEuabtz46xUWJLicOZkzf9IUfJNN98xv4aQWIJi89b1iejAhggLrIQo/vghnx6/AVep/KdEaQkalyVLhvUYqqKxWXr6w6xTV1bbiQ5TqIEs9FCYGB06kCaybQ0w0z9H6RAzhNQN@RSw2cWJw2WHD4LzDlkG7Q77EiPkH)
Outputs all possible combinations in the form of a nested list.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19 15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-4 with pointer from [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun) (use divisor built-in)
I am almost 100% certain this is not the way to actually do this one, but here is a first attempt.
Let's see who outgolfs it with a seven or eight byter!
Yep... see [Lynn's answer](https://codegolf.stackexchange.com/a/142892/53748) with explanation!
```
g/־l/
ÆDp/ÇÐṂ
```
A monadic link taking a list of the two numbers and returning a list of lists of the possibilities.
**[Try it online!](https://tio.run/##ASQA2/9qZWxsef//Zy/Dt8OmbC8Kw4ZEcC/Dh8OQ4bmC////MTIsMTg "Jelly – Try It Online")**
### How?
```
g/־l/ - Link: gcd divided by lcm: list [x, y]
g/ - reduce by gcd = gcd(x, y)
æl/ - reduce by lcm = lcm(x,y)
÷ - divide
ÆDp/ÇÐṂ - Main link: list [a, b] e.g. [160, 90]
ÆD - divisors (vectorises) [[1,2,4,5,8,10,16,20,32,40,80,160],[1,2,3,5,6,9,10,15,18,30,45,90]]
p/ - reduce by Cartesian product [[1,1],[1,2],...,[1,90],[2,1],[2,2],...,[2,90],....,[160,90]]
ÐṂ - entries for which this is minimal:
Ç - call the last link (1) as a monad
```
[Answer]
# [Perl 6](https://perl6.org), 72 bytes
```
{([X] map {grep $_%%*,1..$_},@^a).grep:{([lcm] @a)==([lcm] $_)==[*] $_}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/WiM6IlYhN7FAoTq9KLVAQSVeVVVLx1BPTyW@VschLlFTDyRsBVSWk5wbq@CQqGlrC2WrxAPZ0VogRm3t/@JEkIkaGoZGOgqGFpqa1lxwEQugiBGyiKmOgjky31hHwQyZb6mjYInMNwMaYIpiJFAEZMd/AA "Perl 6 – Try It Online")
Takes a list (a, b). Returns a list of all possible lists (c, d).
Explanation:
```
-> @ab {
# Generate all pairs (c, d)
([X]
# where c divides a and d divides b.
map { grep $_%%*, 1..$_ }, @ab)
# Only keep pairs with lcm(a, b) = lcm(c, d) and lcm(c, d) = c * d.
# The latter implies gcd(c, d) = 1.
.grep: { ([lcm] @ab) == ([lcm] $_) == [*] $_ }
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~126~~ 121 bytes
```
def f(a,b):
c=[1,1];p=2
while p<=a*b:
t=m=1
while(a*b)%p<1:m*=p;t=b%p<1;a/=p**(a%p<1);b/=p**t
p+=1;c[t]*=m
return c
```
[Try it online!](https://tio.run/##LY9BDoMgEEXXzCnYNAFK0kBjq@JsvYRxAVajSbXE0DQ9vRXq6r/3N3/Gf8P4WvS2PfqBDsxKx0ugHTZKqtZ41EA/4/Tsqa/QClcCCTijApJatlf85CtVzgK9CeiiGHtBLwSzUbhxyQIQf0Zluia0Amegax/e60K7tFwfy8Sv0xJos1srj3sAaqa0VBk/IE@QS6UjZPIe4ypvMQpZxLj9bX@Cw/YD "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/) + [sympy](http://www.sympy.org/en/index.html), 148 bytes
```
from sympy import*
a,b=input()
c=d=z=1
while(a/c*c+b/d*d<a+b)+gcd(c,d)-1+(lcm(c,d)!=lcm(a,b)):E=c==d==z;Q=c==z;d=+E or Q+d;c=+Q or-~c;z+=E
print c,d
```
[Try it online!](https://tio.run/##HcwxDoMgFADQnVPQDfwaY5OmSfGPHsAj6KetJCKE0jQy9OoUu73p@T0ubjvn/AjO8tdu/c6N9S7Eik31jGbz7ygkI9SYsGOfxax3MbVUEcytrnQ/wSzhSVpQrWXTgVjJ/n3CQyWR8jYgYRkwqfFQUhph4C7wEbQihLG4@ZJKgAPzwWyRlyJncan5Vf4A "Python 2 – Try It Online")
-1 thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech).
This answer works in Python 2 (not Python 3), using `sympy.gcd` and `sympy.lcm` instead of `math.gcd` and `math.lcm` which are only available in Python 3. And yes, this is brute force :)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
Ụ€’×
ÆEz0ÇZÆẸ
```
[Try it online!](https://tio.run/##ASsA1P9qZWxsef//4buk4oKs4oCZw5cKw4ZFejDDh1rDhuG6uP///1sxMiwgMThd "Jelly – Try It Online") My first Jelly answer! Edit: `ÆEz0µỤ€’×µZÆẸ` also works for 13 bytes. Explanation:
```
ÆE Get prime factor exponents of both values (vectorises)
z0 Zip but fill the shorter array with 0
µ New monadic link
Ụ€ Grade up each pair (1-indexed)
’ Convert to 0-indexing (vectorises)
× Multiply each pair by its grade (vectorises)
µ New monadic link
Z Zip back into separate lists of prime factor exponents
ÆẸ Turn prime exponent lists back into values (vectorises)
```
[Answer]
# PARI/GP, 86 bytes
This just does what Lynn says in her answer:
```
f(a,b)=forprime(p=2,a*b,v=valuation(a,p);w=valuation(b,p);if(w<v,b/=p^w,a/=p^v));[a,b]
```
If I do not count the `f(a,b)=` part, it is 79 bytes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~32~~ ~~26~~ ~~24~~ ~~22~~ ~~20~~ 19 bytes
```
Ó0ζεD`›0sǝ}øεā<ØsmP
```
[Try it online!](https://tio.run/##ATIAzf8wNWFiMWX//8OTMM62zrVEYOKAujBzx519w7jOtcSBPMOYc21Q//9bNjAsIDkwXf8tZA "05AB1E – Try It Online") I still have no idea how to write in this language, but at least it's not a brute-force algorithm. Explanation:
```
Ó Get exponents of prime factors (vectorised)
0ζ Zip, filling with 0
ε } For each prime
D` Extract the pair of exponents
›0sǝ Overwrite the smaller with 0
ø Zip back into two lists of prime exponents
ε For each list (} implied)
ā<Ø Get a list of primes
sm Raise each prime to the exponent
P Take the product
```
]
|
[Question]
[
*Randomly inspired by [Numbers Increase While Letters Decrease](https://codegolf.stackexchange.com/q/138200/42963)*
Given a list of mixed letters and integers (e.g., `['a', 2, 3, 'b']`) *increase* the letters by one position in the alphabet (wrapping at `z` to `a`) and *decrease* the numbers by 1. For the above example, the output should be `['b', 1, 2, 'c']`.
* The input can be a mixed-type list, a delimited string, a list of strings, etc.
* `z` wraps to `a`, but `1` goes to `0`, and `0` goes to `-1`, etc.
* The input will only ever be `[a-z]` and integers. You can choose capital letters `[A-Z]` as input if that's easier for you.
* The input is guaranteed non-empty.
* The input may contain only numbers or only letters.
Examples:
```
Input
Output
['a', 2, 3, 'b']
['b', 1, 2, 'c']
['a', 'b', 'z']
['b', 'c', 'a']
[-1, 0, 257, 'x']
[-2, -1, 256, 'y']
[0, 3, 1, 20382876]
[-1, 2, 0, 20382875]
```
### Rules and Clarifications
* Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* You can print the result to STDOUT or return it as a function result.
* The output doesn't have to be the same format as the input (e.g., you could take input as a string and output as a list).
* Either a full program or a function are acceptable.
* If applicable, you can assume the input/output integers fit in your language's native `int` range.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
<AAÀ‡
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fxtHxcMOjhoX//0crVSnpKBjqKBjpKCglK8UCAA "05AB1E – Try It Online")
```
< # decrement the numbers
A # constant "abcdefghijklmnopqrstuvwxyz"
AÀ # same, but rotated left ("bcd...yza")
‡ # transliterate
```
[Answer]
# [Python 3](https://docs.python.org/3/), 59 bytes
```
lambda a:[i-1if''!=i*0else chr(97+(ord(i)+8)%26)for i in a]
```
[Try it online!](https://tio.run/##VY7LCoMwEEX3fsUUKZNUBY34aMEvSV3EFwasinVR@/PpqHXhLMIw595DxmVuhz40TfY0nXoVlQL1kNoLdIN4yfTNr7t3DWU7sXvisGGqmOZOyq8i5s0wgQbdg8rNOOl@Zg2TqNAF4ULoAhaYcw40tqTdhWAjWGJuWefChvF75I8CRelRp7xHFp9EUULo82/Y0iPzikQU0305VfztOyv0w1SkSbyW7M0kdtl@j3LzAw "Python 3 – Try It Online")
*-1 byte thanks to Erik the Outgolfer*
[Answer]
# [Perl 5](https://www.perl.org/) (-p), 17 bytes
```
y/a-z/b-za/or$_--
```
[Try it online!](https://tio.run/##K0gtyjH9/79SP1G3Sj9JtypRP79IJV5X9///Ki4TIy5dI67kf/kFJZn5ecX/dQtyAA "Perl 5 – Try It Online")
Bonus 19-byter:
```
$_>$_++?$_-=2:s/a//
```
[TIO](https://tio.run/##K0gtyjH9/18l3k4lXlvbXiVe19bIqlg/UV////8qLhMjLl0jruR/@QUlmfl5xf91C3IA). This one features some cool tricks, but fails to beat the straightforward solution above.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 34 bytes
For each element, attempt to return the element -1. Strings cannot do this, so they error out and are picked up by the `rescue` clause, which instead calls `succ` on it to return the next letter in the alphabet. `succ` "rolls over" on `z` and returns `aa` though, so we simply take the first character in the returned string.
```
->a{a.map{|e|e-1rescue e.succ[0]}}
```
[Try it online!](https://tio.run/##FcWxCoAgEADQX7nNRaXItX5EHE45WwpEMyj1282W92K2T/drFxsWlCeGUqmSmCMllwlIpuycnkxrPYDXdOMBO13JdM2QcWD25x2ImcM0UhwWZT4 "Ruby – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 55 bytes
```
a=>a.map(s=>1/s?s-1:B([(B(s)[0]+8)%26+97])+'',B=Buffer)
```
[Try it online!](https://tio.run/##bc5LDoIwEAbgvafoxkwbChQID03AhGuQLipSo0EgVI16eRzwtcBZNJn8803nqK7KlP2hO9tNu6sGnQ4qzZRzUh01aea5ZmNsb53TgubUsEJIK2FLP7JWsWQWAM/T/KJ11bOhbBvT1pVTt3uqaQEKOPE5CTiBLUjGCJbrkgI7TrwpgxLk4p@bZuDxYT@HAh81ZzZuFLg0jDG/veHIbPxnDP0wwuQ@l2K6cZwQQeIncTTaSb6OFN8klMMT "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 182 130 118 bytes
*-51 bytes thanks to @AdmBorkBork and @Black Owl Kai, -1 byte thanks to @Black Owl Kai, -12 bytes by replacing `.append()` with `+=[]` and replacing `n+1` with `-~n`*
```
def a(x):
b='abcdefghijklmnopqrstuvwxyz';c=[]
for d in x:
try:c+=[d-1]
except:c+=[b[(-~b.find(d)%26)]]
return c
```
[Try it online!](https://tio.run/##Vcw7DoMwEATQnlNsE9lWIOKjACLiJIgC2xCcjyGOSQxFrk5WdDRbzJvZcbb9oJN1lW0HDXWs8ICXpOECg2uvbvfHUw/jy7zt9Pm6eSEXUVa1B91gQILS4HAB1syFOJaVDCI0aJ1oR7slvKLBj586pSWV7BCnrMaGae1kNIh1NEpb2tCKNMSH2IfEB8JJzZi3JwzxLHsJIh9CnJ0zNLe3cPuFhThM8jjPUtT1Dw "Python 3 – Try It Online")
I made this while the question was in the Sandbox but didn't see it posted until just now. :P
## Ungolfed
```
def a(x):
b = 'abcdefghijklmnopqrstuvwxyz'
c = []
for d in x:
try:
c.append(d - 1)
except:
c.append(b[((b.find(d) + 1) % 26)])
return c
```
## Explanation
For each element in the inputted list `x`, it tries to subtract 1 and add it to the eventual returned list. If an error occurs (because the element is a string), the letter's index in the alphabet is added by 1 and that mod 26 is taken. The mod 26 wraps an index of 26 back to 0.
[Answer]
# [J](http://jsoftware.com/), 30 bytes
```
<: ::((26|>:)&.(_97+a.i.]))&.>
```
[Try it online!](https://tio.run/##XY67CsJAEEX7fMXFwklws2wm5OGOplCwEgtbWUIUg9rYqvjv6wpGxGKKczhc5uJHmnrMLQgKBjZcqrHcrld@ZmFtHHP5bGwy1nE7rSadPmuXBGp8Eh0Ppyt6UEdCe/pFlvxfBRR6fFWbiREuKqEbYbPQ2KWskGYKXJQKdCc3pCaMZQI2ec11VX7qdxk@VoMvXORf "J – Try It Online")
[Answer]
# [Gema](http://gema.sourceforge.net/), 55 characters
```
<N>=@sub{$1;1}
z=a
<L>=@int-char{@add{@char-int{$1};1}}
```
Dirty solution. Wrapping around on letter increment is painfully long, so got a separate rule.
Input can be quite anything, just use some separators. (You can even omit separators between numbers and letters. With the price of 1 character for changing to `<L1>` you could omit separators between letters too.)
Sample run:
```
bash-5.0$ gema '<N>=@sub{$1;1};z=a;<L>=@int-char{@add{@char-int{$1};1}}' <<< "['a', 2, 3, 'b']"
['b', 1, 2, 'c']
```
[Try it online!](https://tio.run/##S0/NTfz/38bPztahuDSpWsXQ2rCWq8o2kcvGByiUmVeim5yRWFTtkJiSUu0AYuoCxYDKaoHqav//j1ZPVNdRMNJRMNZRUE9Sj@WCCACZQKIKxNc11FEwACoxNQeKVIBEDMCqgcJGBsYWRhbmZrEA "Gema – Try It Online")
### Gema, 66 characters
```
<N>=@sub{$1;1}
<L>=@cmpi{$1;z;@int-char{@add{@char-int{$1};1}};a;}
```
Clean solution. Half relatively efficient, then half pure pain.
Sample run:
```
bash-5.0$ gema '<N>=@sub{$1;1};<L>=@cmpi{$1;z;@int-char{@add{@char-int{$1};1}};a;}' <<< "['a', 2, 3, 'b']"
['b', 1, 2, 'c']
```
[Try it online!](https://tio.run/##S0/NTfz/38bPztahuDSpWsXQ2rCWy8YHyE3OLcgE8ausHTLzSnSTMxKLqh0SU1KqHUBMXaAYULYWqLzWOtG69v//aPVEdR0FIx0FYx0F9ST1WC6IAJAJJKpAfF1DHQUDoBJTc6BIBUjEAKwaKGxkYGxhZGFuFgsA "Gema – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 77 ~~85~~ bytes
Thanks @Giuseppe for a whooping 8 bytes
```
function(l)Map(function(x)"if"(i<-match(x,L<-c(letters,"a"),0),L[i+1],x-1),l)
```
[Try it online!](https://tio.run/##TYxBCsIwFET3niJkk//xB5IUbRf1BvUE4iKGBgOxShshePkYXEg2A/MeM2vxp@Lfi0vhuUDEs33Bv2bkwXMIo3zY5O6QaRqlgzinNK8bccuRFNJ0CXt9pSw1UsTiIYYtgbCCmCHWERM3gbhreSU1Pg2Wmpiqg0NfRW6E@l1Ua1Q3mKE/IpYv "R – Try It Online")
Takes the input as a list. After a big change by @Giuseppe, this makes use of `Map` to apply a function to the list. It makes use of `match` to test for a character. During the test the extended letter list and index are saved for the return.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 14 bytes
```
▄\╧¿ò'z=¿Å'a)(
```
[Try it online!](https://tio.run/##y00syUjPz0n7///RtJaYR1OXH9p/eJN6lS2QalVP1NT4/189UZ3LkAtE6gKpMnUu9Sp1AA "MathGolf – Try It Online")
Takes letter as lowercase.
## Explanation
```
▄\╧ Is the element in the lowercase alphabet?
¿ò If so:
'z= Is it equal to z?
¿Å If so:
'a Push 'a'
) Else: Increment the string
( Else: Decrement the number
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language#transliterate-t-and-y), ~~52~~ ~~50~~ ~~48~~ ~~58~~ ~~41~~ 37 bytes
```
T`zl`l
\b0
-
\d+
*
-_*
-$.0
_(_*)
$.1
```
-4 bytes thanks to *@FryAmTheEggman* (and for mentioning I had a bug: `1 → -1` instead of `1 → 0`).
+10 bytes to fix a bug with `1` and `0`.. Such an annoying edge case which screwed me over for quite a while.. But golfed it to 41 bytes now. (Now I'm curious about the <40 bytes versions *@Neil* and *@CowsQuack* mentioned in the comments.. Thanks *@Neil* for the tip of converting the `0` to `-`, and dealing with the negative values first. Converting those right back from unary to integer helped a lot.)
Apparently I don't need the boundaries at this point, so -4 bytes.. >.>
I/O is comma-separated.
[Try it online.](https://tio.run/##Fck7CoUwFEXR/oxDwc@J3Bt56AycgKWQD1oIYiGvkEw@arF3s67tv59Bc1lNPs8@Hf7AEgUGy9qigXFvRSdwlWtqFJ3mHGjZMyIwMsEohfY38GZioEJeVFrpRwo@VPn2AA)
**Explanation:**
Transliterate all `"zabcdefghijklmnopqrstuvwxy(z)"` to `"abcdefghijklmnopqrstuvwxyz"`:
```
T`zl`l
```
Replace all standalone `0`s with a `-`:
```
\b0
-
```
Convert all numbers to unary, by replacing them with that amount of underscores:
```
\d+
*
```
For all negative values, with zero or more unary-lines behind it: keep the minus sign, and get the total length of this match (including the `-`), converted back to an integer:
```
-_*
-$.0
```
As for the positive integers: match a positive integer by matching a single unary-line, followed by zero or more unary-lines. And then replace them with the length of that capture group to remove that single unary-line and convert them back to integers simultaneously:
```
_(_*)
$.1
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 103 bytes
```
U =&UCASE 'A'
N X =INPUT :F(END)
U X @P :F(D)
U POS(P) LEN(1) . OUTPUT :(N)
D OUTPUT =X - 1 :(N)
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/nzNUwVYt1Nkx2FVB3VGdy48zQsHW0y8gNITTyk3D1c9FkwuoIkLBIQDEh/AC/IM1AjQVfFz9NAw1FfQU/ENDwOo1/DS5XDghPAXbCAVdBUOIINCY//8duQy5DLicuKIA "SNOBOL4 (CSNOBOL4) – Try It Online")
[Answer]
# [PHP](https://php.net/), 50 bytes
```
for(;''<$a=$argv[++$i];)echo$a<a?--$a:(++$a)[0],_;
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKzV1W1UEm1VEovSy6K1tVUyY601U5Mz8lUSbRLtdXVVEq00gKKJmtEGsTrx1v///0/8n/S/6r/Bf8P/Rv@NAQ "PHP – Try It Online")
[Tests](https://tio.run/##LU3tCoMwDPzfpyij0IoKzrEPVsUH6Ypko7ODTaXq2Ad7dpeqgQvJ3SXX2nbMita2hLDedH1Hc6qI4sAjniI2iDPX0UKdEZ95jdc4J9623WN/zWyy3HgxTTaH9LDfeUVLQq6NM3CxVCxJ0NFpCuiXUCwGrnpiPjgH7/JhXGWEqof7XUeLUY74Q0jOMwb5ZFdhyG5aBuZiGwYZFHHM4CiQhUAlOirl6F97ma5O9UpOSUPdmV6wWyDJb/wD "PHP – Try It Online")
Outputs letters/integers separated by `_` with a trailing separator.
In PHP you can increment letters directly, so I took advantage of it. But the `z` is incremented to `aa`, to convert it to `a`, the `(++$a)[0]` is used which only outputs the first character of the incremented value.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), ~~13~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
-1 byte thanks to Shaggy
```
;¤?UÉ:Cg8+Uc
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=O6Q/Vck6Q2c4K1Vj&input=Wy0xLCAwLCAyNTcsICJ6Il0)
## Explanation:
```
;o ?UÉ:Cg8+Uc
-m // Map U through the input:
o // Try to create a range [1...U]
? // If that creates a range (number):
UÉ // Return U-1
: // Else, return:
; C // alphabet (a...z)
g // Index:
8+Uc // 8 + char-code of U
```
**Note**: `;` turns `C` into the lowercase alphabet
[Answer]
## Haskell, ~~52~~ 51 bytes
```
map q
q"z"="a"
q x|x>"`"=succ<$>x|1<2=show$read x-1
```
As Haskell doesn't allow lists of mixed types, letters and numbers are taken and returned as strings.
[Try it online!](https://tio.run/##FctBDoIwEEDRPaeYTLq0iSUxbhguoiZMKhVixZZqGAlnt9rN@6s/cLr33mdH5/zgALGKuCIhYxVBNmmxQ0pvaxvVymaamtLwXNTc8xVEm/8zTkAQ5nF6gQIHcEJtcAe4L9SHY4kUPoUVL/lrnedbytqG8AM "Haskell – Try It Online")
Check for every list element: if the string is `"z"`, return `"a"`; if the first character of the string is > `'`'` (i.e. a letter, not a digit), return the successor of the char(s) in the string; else it must be number, so convert to an integer, subtract 1 and turn into a string again.
Edit: -1 byte thanks to @cole.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
®i‘ị®µ’e?€Øa©
```
[Try it online!](https://tio.run/##AT4Awf9qZWxsef//wq5p4oCY4buLwq7CteKAmWU/4oKsw5hhwqn/4bqOw4fFkuG5mP//WydhJywgMiwgMywgJ2InXQ "Jelly – Try It Online")
Clever fix by [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
Note: This is not a full program, the footer over TIO makes it possible to input using a command-line argument to test the function.
[Answer]
# [C++17 (gcc)](https://gcc.gnu.org/), 120 bytes
```
#define O int operator()
struct V{O(char&c){c++-90?:c=65;}O(int&i){--i;}};int f(auto&l){for(auto&x:l)std::visit(V{},x);}
```
Here `f` is the required function; `l` is both the input and output parameter, and it is expected to be a container of objects which are compatible with `std::variant<char, int>` or vice versa.
[Try it online!](https://tio.run/##fZJda4MwFIbv/RWHFvygCralH1Pr2KB3g@6qjLEbSbUL2CgxlkLIX193Eru11DEvNDkf73nPg6Sugz0h5yFlpGx3OSTHjNOMifQ83OUFZTlsgDIBVZ3zTFTc9axG8JYI2MqNSz4zbhNPktEoeAgfI7Kaz2K1cbHDpp4MAhorFev@ws1aUdmlJwsUMedTVHqN2EXRkTZUuFup/JMXqxsvJW1Eal3vtMLZeXZIrbahbA/rVdffWU60Gx@HpbF1rOgOao6XF9RwScUaAaZYaybr1IbSA2kBPiZMqlZAksBAwiC@hM2ar1pkqx1WHCQY4SsMQwAISt3JOAP9IZdzDKrXqanQXiPVpapzgKSgQwUniIxhuAF26wzZAcK7M@GDnvzHkgp3VB0kkSOfWzJXMFd@ZU8aglSLFyb1T6HzwRw9S297yChzf8TNXAnOk@PDxIepD86zA8qLe1mM4@u9lwzGPoTYPFtg@q2XDo0o1kzC6XKyXMx/C3guWs4gRF/nL1KU2b45B@h6hb/xePEN "C++ (gcc) – Try It Online")
[Answer]
# dzaima/APL, ~~21~~ 20 bytes
```
{0::⍵-1⋄⎕l(⍳⊇1⌽⊣)⍵}¨
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/qG@qp/@jtgkGXGlAUuN/tYGV1aPerbqGj7pbgHI5Go96Nz/qajd81LP3UddiTaBU7aEV/zW5gHIKQA0KaQrqieoK6knqCkYKxgrqVepIMofWGyoYKBiZmiuoV6j/BwA "APL (dzaima/APL) – Try It Online")
-1 thanks to ngn.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 27 bytes
```
{$[9+@x;`c$97+26!8+x;x-1]}'
```
[Try it online!](https://tio.run/##y9bNz/7/P82qWiXaUtuhwjohWcXSXNvITNFCu8K6Qtcwtlb9f5qGUqKStZGxtVKVkuZ/AA "K (oK) – Try It Online")
-8 thanks to ngn and dzaima :)
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 36 bytes
```
\$ka'~?*3({':+1\
R';$ >i::0Sqn=?/1-$
```
[Try it online!](https://tio.run/##KyrNy0z@/z9GJTtRvc5ey1ijWt1K2zCGK0jdWkXBLtPKyiC4MM/WXt9QV@X//0QFIwVjhSoA "Runic Enchantments – Try It Online")
General process is to read input, prepend with a 0 (coercion to string), convert back to a number (single char will always return -1), compare with input. If same, it must be a numerical value, subtract 1 and print. If not same, it must be a char, subtract 1, compare with `{`. If less than, print, otherwise replace it with `a` and print.
Repeat until program performs a stack underflow.
Output is separated by `;` in order to [save 1 byte](https://tio.run/##KyrNy0z@/z9GJTtRvc5ey1ijWt1K2zDGmitIXUFFwS7TysoguDDP1l7fUFfl//9EBSMFY4UqAA) (and has a trailing one). Input is space-separated.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
àºÇ╝'♫d▬♣ΩÜEƒ6╩╬ó
```
[Run and debug it](https://staxlang.xyz/#p=85a780bc270e641605ea9a459f36cacea2&i=[%27a%27,+2,+3,+%27b%27]%0A[%27a%27,+%27b%27,+%27z%27]%0A[-1,+0,+257,+%27x%27]%0A[0,+3,+1,+20382876]&a=1&m=2)
This feels like it should be possible to do shorter, but I can't resist the opportunity to use a new stax feature from the last release.
Treating the entire input as a string:
1. Regex replace runs of digits with `eval(match) - 1`. This is the new feature, as the regex block replacement is not a string, but an integer.
2. Regex replace runs of letters by ring-translating them around the lower-case alphabet.
[Answer]
# Python 3, 66 bytes
```
lambda X:[x-1if type(x)==int else chr(97+(ord(x)+8)%26)for x in X]
```
Edit:
I didn't see the solution of Jitse until now. The trick of if''!=i\*0 is awesome!
[Answer]
# C#, 148 bytes
```
(object[] o)=>{var l=new List<object>();foreach(var h in o){try{l.Add((int)h-1);}catch{var c=((char)h+1);if(c>122){c=97;}l.Add((char)c);}}return l;}
```
[Repl.it link](https://repl.it/repls/AshamedLightyellowCompilers)
Ungolfed:
```
var inputList = new object[] {'a', 2, 'z', 6};
var outputList = new List<object>();
foreach (var currentItem in inputList)
{
try
{
outputList.Add((int)currentItem-1);
}
catch
{
var currentItemPlusOne = ((char)currentItem + 1);
if (currentItemPlusOne > 122)
{
currentItemPlusOne = 97;
}
outputList.Add((char)currentItemPlusOne);
}
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
WS⟦⎇№βι§β⊕⌕βιI⊖ι
```
[Try it online!](https://tio.run/##RYoxC8IwEEb3@xUZL9CCdXWSipBN0E0cYnLYQLyWeG2tfz6mOLh973vPdTa53sac5y5EUmh4GOUsKfADtVanMgSvF0ps04JtPxa8VyroSu3FsKf3ioZdoiexkMdjYP9LdIla@xI80F@v903vcq4bWGADH2jAwhZyPcUv "Charcoal – Try It Online") Link is to verbose version of code. Takes input on STDIN, each line being either a single lowercase letter or an integer, and outputs on separate lines on STDOUT. Explanation:
```
WS
```
Repeatedly input from STDIN until an empty line is reached.
```
⟦
```
Make this expression output on its own line.
```
⎇№βι
```
Is this a substring of the predefined lowercase alphabet?
```
§β⊕⌕βι
```
If so then print the next letter cyclically indexed.
```
I⊖ι
```
Otherwise decrement the value and cast back to string for implicit print.
[Answer]
# [Zsh](https://www.zsh.org/), 47 bytes
```
a=({a..z} a)
for i
<<<${a[$a[(i)$i]+1]:-$[--i]}
```
[Try it online!](https://tio.run/##qyrO@F@cWqKgq6uga6hgoGCokKhQqVD1P9FWozpRT6@qViFRkystv0ghk8vGxkalOjFaJTFaI1NTJTNW2zDWSlclWlc3M7b2/38A "Zsh – Try It Online")
```
a=({a..z} a) # append extra 'a' to the end to handle 'z' case
for i # for i in "$@" arguments
<<<${a[$a[(i)$i]+1]:-$[--i]}
$a[(i)$i] # first (i)ndex of $i in list (if not found, set to after last index)
[ +1] # increment
${a[ ] } # value in array at index. if lookup fails, empty string
${ :-$[--i]} # if empty, decrement $i and substitute instead
<<< # print to stdout
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~93~~ 86 bytes
```
f(int**s){for(char**p=s,*z;z=*p++;)64&*z?*z=*z-'z'?++*z:97:sprintf(z,"%d",atoi(z)-1);}
```
[Try it online!](https://tio.run/##fZDJboMwFEXX9ldYjtJ4gBY6qnFofiBi1xVlgRiCpdYgDFLriG@ndk277OroXb1731CG57JcloZINTKm6aXpBlK2xcBYn@iAGWES1nMu6OP9FTNHZksT7szuyDkz@@enve4H622ICfC2wkExdpIYGsZUzMtGqvJ9qmp00GNV1c11@wKh7UYfhVSEogsEbhYaW6nOOsuzOMpR4mSAH3Dg8Olx5/HlEd96Rh4GQzALuLETpKpRioiWpu4a4nMpukGrwFaFroOZVP006izlcS4gsMcj9wkk7RaRsDig1IJzawBrr3QrrhtL5/rNcHr6ejq5IOJF@n/oz6Xr//BWvykc/AU76wzBUI/ToKwPzss3 "C (gcc) – Try It Online")
The input is a `NULL`-terminated array of `'\0'`-terminated strings, e.g. `{"a", "b", "c", "17", NULL}`.
-7 bytes thanks to @ceilingcat
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 31 bytes
```
*>>.&{(try $_-1)||chr ord ++$_}
```
[Try it online!](https://tio.run/##PY29DoIwFEZ3nuIOhCqUppTws0ji4ObsQhqDCNEExRQHq/js9dImLt9w7jm5j04NublpCHrYgAmrigWf1VNp8I9xsp7n9qJgVGeIIv/4NVOjge0O2z1Dvx8VDNd7N9WcpoyxUJqaNISCoJBSICcivRqXQmIZaRF4TrGYvP8G3nAaK8SocyyyAtFrUWKsFyqyHJG2FrdPFsjTUpRFLl0pXOxgJn8 "Perl 6 – Try It Online")
Anonymous Whatever lambda that maps each element to the list and attempts to subtract one from it, otherwise incrementing it and taking the first character in the case that `z` wraps over to `aa`.
[Answer]
# T-SQL 2012, 61 bytes
Capital letters needed in input.
Using table variable as input.
```
SELECT iif(x<'a',left(x-1,9),char((ascii(x)-64)%26+65))FROM @
```
**[Try it online](https://rextester.com/IBUMDE60459)**
[Answer]
# SimpleTemplate, 80 bytes
This was written on a language I've made.
Due to limitations in the compiler, I can't reduce it any more.
```
{@eachargv}{@if_ is matches"@\d+@"}{@incby-1_}{@echol_}{@else}{@inc_}{@echol_.0}
```
And now, ungolfed:
```
{@each argv as value}
{@if value is matches "@\d+@"}
{@inc by -1 value}
{@else}
{@inc by 1 value}
{@/}
{@echo value, "\n"}
{@/}
```
And the explanation:
* `{@each argv as value}` - loops through all values in `argv`. (`argv` contains all the arguments passed).
If the `as <var>` isn't present, the default `_` variable is assumed.
* `{@if value is matches "@\d+@"}` - checks that `value` matches with the regular expression `"@\d+@"`.
* `{@inc by -1 value}` - increments the value by -1 (basically, a decrement).
* `{@echo value, "\n"}` and `{@echol_}` - `echol` outputs the values passed and appends a line at the end.
* `{@else}` - self-explanatory
* `{@inc by 1 value}` - increments the value by 1. If the `by <value>` is missing, it is assumed to be 1.
* `{@echo value.0, "\n"}` and `{@echol_.0}` - `echol` outputs the values passed and appends a line at the end.
This is required because of the challenge rules: `z wraps to a`.
When an `@inc` is used on a string, it increments the chars and, once it hits `z`, it wraps to `aa`.
Outputting the first character satisfies the challenge, at the cost of 7 bytes.
* `{@/}` - closes the `{@else}` above (optional).
* `{@/}` - closes the `{@each}` above (optional).
You can try this on: <http://sandbox.onlinephpfunctions.com/code/7533641a0aa1fc8bf4699a9c758690de186b052f>
Each passed argument to `render()` will be a new value that is considered.
[Answer]
## Perl, 64 bytes
```
foreach (@ARGV){$_=~m/[a-zA-Z]/?++$_:--$_;print substr $_,0,1;}
```
]
|
[Question]
[
**Terminology**
An increasing number is one where each digit is greater than or equal to all the digits to the left of it (ex. 12239)
A decreasing number is one where each digit is less than or equal to all the digits to the left of it (ex. 95531)
A bouncy number is any number that is not increasing or decreasing. Since this requires at least 3 digits, the first bouncy number is 101
**The task**
Given an integer n greater than or equal to 1, find the sum of the first n bouncy numbers
**Rules**
* This is code golf, so the answer with the shortest amount of bytes wins
* If your language has limits on integer size (ex. 2^32-1) n will be small enough that the sum will fit in the integer
* Input can be any reasonable form (stdin, file, command line parameter, integer, string, etc)
* Output can be any reasonable form (stdout, file, graphical user element that displays the number, etc)
**Test cases**
```
1 > 101
10 > 1065
44701 > 1096472981
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 bytes
```
ṢeṚƬ¬µ#S
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//4bmiZeG5msaswqzCtSNT//80NDcwMQ "Jelly – Try It Online")
### How it works
```
ṢeṚƬ¬µ#S Main link. No arguments.
# Read an integer n from STDIN and call the chain to the left with argument
k = 0, 1, 2, ... until n of them return a truthy result.
Yield the array of successful values of k.
µ Monadic chain. Argument: k (integer)
Ṣ Sort, after promoting k to its digit array.
ṚƬ Reverse 'til the results are no longer unique and yield unique results.
Calling Ṛ on k promotes it to its digit array. If k = 14235, the
result is [14235, [5,3,2,4,1], [1,4,2,3,5]].
e Check if the result to the left appears in the result to the right.
¬ Negate the resulting Boolean.
S Take the sum.
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 10 bytes
```
s.f!SI#_B`
```
[Try it here!](https://pyth.herokuapp.com/?code=s.f%21SI%23_B%60&input=10&debug=0)
### How it works?
```
s.f!SI#_B` – Full program. Takes an integer Q from STDIN and outputs to STDOUT.
.f – Find the first Q positive integers that satisfy a certain condition.
!SI#_B – The condition. Returns true for bouncy numbers only.
_B` – Cast the number to a string and bifurcate (pair) it with its reverse.
# – Filter-keep those...
I – That are invariant under...
S – Sorting.
– To clarify, I (invariant) is a Pyth operator that takes two inputs, a
function and a value and checks whether function(value) == value, so
this is technically not a built-in.
! – Logical not. The empty list gets mapped to true, other values to false.
s – Sum.
```
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 37 bytes
```
{+/x{{(a~&\a)|a~|\a:10\x}(1+)/x+1}\0}
```
[Try it online!](https://tio.run/##FchBCsMgEADAe1/RQymKlLjFJo37lChkL5aSkkLIYYPRr5t4G2Z6zJ@5lGCjajhGQfnuSO6Ud0cWtOMkQMmGFSSnU1ltvA1bXmy4Mo7/CcUY6PtDxg0X6dNlHQBBg6/Qp9pXpTGdrt@3pnv2b/DlAA "K (ngn/k) – Try It Online")
`{` `}` is a function with argument `x`
`x{` `}\0` applies the `{}` on `0` `x` times, preserving the intermediate results
`(1+)` is the successor function
`{` `}(1+)/x+1` applies the successor function starting from `x+1` until the `{}` returns true
`10\x` are the decimal digits of `x`
`a:` assign to `a`
`|\` is the max-scan (partial maxima) of `a`
`&\` analogously, is the min-scan
`a~|\a` does `a` match its max-scan?
`|` or
`a~&\a` its min-scan?
`+/` sum
[Answer]
# [Python 2](https://docs.python.org/2/), 84 bytes
```
i=s=0
n=input()
while n:b=`i`>`sorted(`i`)`[2::5]<`i`[::-1];n-=b;s+=b*i;i+=1
print s
```
**[Try it online!](https://tio.run/##DcZBCoAgEADAu6/waEmQUQRr20ckECloITZJI3q9NaeJb95P7kohTNgKRuJ4Z1WJZ6djkwwBPfnZp/PK26r@V951AMMy/XcAjVksNxhs0hhqsqTRiHgRZ5lK6fuxNR8 "Python 2 – Try It Online")** Or see a [test-suite](https://tio.run/##JY7RDoIgGEav5Sm4AxI3MVsb9vsizg1RmmwGTmjV05PW3bk439m3fuLsXZVGPxkghCQLAUrkwLr1GSlDr9kuBjupQVnVquC3aCa6M1NdJeWlv@3cSVmIvnEF6CbkoE@2sTkItG7WRRzSHka/ICzDQ0@DjCZEdPcbPgBbh6ngFT9zUfK6vpaCSZT9x4fAMSlawlFm3makx1WWvg "Python 2 – Try It Online").
[Answer]
# JavaScript (ES6), 77 bytes
```
f=(i,n=0,k,p)=>i&&([...n+''].map(x=>k|=x<p|2*(p<(p=x)))|k>2&&i--&&n)+f(i,n+1)
```
[Try it online!](https://tio.run/##bcyxDsIgEADQ3Q@53lkgbeceP2IcSC0GqXCxxjDw76ircX3Du7mX25dHkKdO@bK25hmDSjyoqITYBgA8GWNS33Vnc3eChW2sXGap0xFlRuFCRDXaCSBoDZCo99@jH6ktOe15W82Wr@hxJDr8yPCHPtbe "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f = recursive function taking:
i, // i = number of bouncy numbers to find
n = 0, // n = current value
k, // k = bitmask to flag increasing/decreasing sequences
p // p = previous value while iterating over the digits
) => //
i && ( // if there's still at least one number to find:
[...n + ''] // turn n into a string and split it
.map(x => // for each digit x in n:
k |= // update k:
x < p | // set bit #0 if x is less than the previous digit
2 * (p < (p = x)) // set bit #1 if x is greater than the previous digit
// and update p
) // end of map()
| k > 2 // if both bits are set (n is bouncy):
&& i-- // decrement i
&& n // and add n to the total
) + f(i, n + 1) // add the result of a recursive call with n + 1
```
[Answer]
# Python 2, ~~110~~ ~~92~~ 89 bytes
```
n=input()
x=s=0
while n:b={-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]));s+=x*b;n-=b;x+=1
print s
```
[**Try it online**](https://tio.run/##Lc1NCoMwEEDhtXOK4iqpCk4RCrFzkiJo0gGlNQaT0kjp2dMfunur77ktjIs9JLNcmPI8T5Ym6@5BSIjkqYbHON14Z5WmZ4Ulvk7kOYh5cMLMruxjf1YVdr9A1UnZ@oLiXre2It3GghDcOtmw8@mj/zVUkIV1UxzZiO9ZQsbRsAtKrzxcEwLW0DTHGt8)
This function determines if a number is bouncy:
```
lambda x:{-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]))
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 93 bytes
```
K`:
"$+"{/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`:(#*).*
:$1#;$.($1#
)`\d
*_;
)`:(#+).*
$1:$1
\G#
```
[Try it online!](https://tio.run/##K0otycxLNPz/3zvBiktJRVupWl/D3lZPy1ojXkvTOsYwXhPMjYdwjaw19eOqE6w0lLU09bS4rFQMla1V9DSAFJdmQkwKl1a8NZABlNYGSasYAhVwxbgr//9vaAAA "Retina – Try It Online") Explanation:
```
K`:
```
Initialise `s=i=0`. (`s` is the number of `#`s before the `:`, `i` the number of `#`s after.)
```
"$+"{
...
)`
```
Repeat `n` times.
```
/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`
...
)`
```
Repeat while `i` is not bouncy.
```
:(#*).*
:$1#;$.($1#
```
Increment `i` and make a copy in decimal.
```
\d
*_;
```
Convert the digits of the copy to unary. The bounciness test uses the unary copy, so it only works once `i` has been incremented at least once.
```
:(#+).*
$1:$1
```
Add `i` to `s` and delete the copy of the unary digits, so that for the next pass of the inner loop the bounciness test fails and `i` gets incremented at least once.
```
\G#
```
Convert `s` to decimal.
121 byte version calculates in decimal, so might work for larger values of `n`:
```
K`0:0
"$+"{/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`:(\d+).*
:$.($1*__);$.($1*__)
)+`;\d
;$&*_;
)`\d+:(\d+).*
$.(*_$1*):$1
:.*
```
[Try it online!](https://tio.run/##PYsxCsMwDEV3HSOIYsngWBklQg7QK5jIhXTokqF0y@Ed00C2/z7vfd@/z/6S1p41a4YB43CMYZkTW3AmK@L0R79wMhrXo2ooW6TEoJgCCruT3QsoVisbGD7YDah29w66xd49UhTQfrQm@QQ "Retina – Try It Online") Explanation:
```
K`0:0
```
Initialise `s=i=0`.
```
"$+"{
...
)`
```
Repeat `n` times.
```
/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`
...
)
```
Repeat while `i` is not bouncy.
```
:(\d+).*
:$.($1*__);$.($1*__)
```
Increment `i` and make a copy.
```
+`;\d
;$&*_;
```
Convert the digits of the copy to unary. The bounciness test uses the unary copy, so it only works once `i` has been incremented at least once.
```
\d+:(\d+).*
$.(*_$1*):$1
```
Add `i` to `s` and delete the copy of the unary digits, so that for the next pass of the inner loop the bounciness test fails and `i` gets incremented at least once.
```
:.*
```
Delete `i`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
µN{‚Nå_iNO¼
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0Fa/6sNNjxpm@R1eGp/p539oz///JibmBoYA "05AB1E – Try It Online")
**Explanation**
```
µ # loop over increasing N until counter equals input
Nå_i # if N is not in
N{‚ # the pair of N sorted and N sorted and reversed
NO # sum N with the rest of the stack
¼ # and increment the counter
```
[Answer]
# Java 8, ~~114~~ 112 bytes
```
n->{int i=0,s=0;for(;n>0;++i)s+=(""+i).matches("0*1*2*3*4*5*6*7*8*9*|9*8*7*6*5*4*3*2*1*0*")?0:--n*0+i;return s;}
```
Uses a regular expression to check if the number is increasing or decreasing. Try it online [here](https://tio.run/##TVDBcoIwEL33K3Y4wSJMqFprU@xM7z15dDxEjBoLC5MEO47l22lAtO4hL3nZffP2HcVJRGUl6bj9bqt6k6sMslwYA19CEVyewJUiK/VOZBI@y5qy80APX2Dqwu@QAt7zTX8OYsYK6@BUqi0UTtJfWq1ov1qD0HsTPEgN2psrpNBStLh0uiplI5Myviu1z2nBeBiqwISp73nuEhfCZgdpfI9hgs84xglO8QVn@Ipz/J07mLnn1NFj950gQy/4YG9RRMhCxbW0tSYwvGlvTvjjes4p1cVGauM8kfwZuAskI0jYCCaTGUug@Z/pbPa2XT/jDt5vAnEuaW8PHLoF7v1dLc/GyiIuaxtXLh6bk3/NIe7CHcZXah3cI27aPw).
Ungolfed:
```
n -> { // lambda
int i = 0, // the next number to check for bounciness
s = 0; // the sum of all bouncy numbers so far
for(; n > 0; ++i) // iterate until we have summed n bouncy numbers, check a new number each iteration
s += ("" + i) // convert to a String
.matches("0*1*2*3*4*5*6*7*8*9*" // if it's not an increasing number ...
+ "|9*8*7*6*5*4*3*2*1*0*") ? 0 // ... and it's not a decreasing number ...
: --n*0 // ... we have found another bouncy number ...
+ i; // ... add it to the total.
return s; // return the sum
}
```
[Answer]
# Python 2, 250 bytes
```
n=input()
a=0
b=0
s=0
while a<n:
v=str(b)
h=len(v)
g=[int(v[f])-int(v[0]) for f in range(1,h) if v[f]>=v[f-1]]
d=[int(v[f])-int(v[0]) for f in range(1,h) if v[f]<=v[f-1]]
if len(g)!=h-1 and len(d)!=h-1:
a+=1
s+=b
b+=1
print s
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles), 9 bytes
```
+<$|,~~?`.`<;`p$\
```
(it would be 8.5 bytes if filesystems could store half bytes)
Similar to the Jelly answer.
```
+ # sum of
< # first n elements of
$ # first input integer
| ~ # filter.not
,~ # range from 1 to infinity
? # index of (begin of filter body)
`. # iterate while uniq
`< # sort
;`p$ # int to str of filter arg, also save value
\ # reverse
# implicit $ (arg of iterate while uniq)
# implicit $ (saved value from `p)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ö²àDæ▲☼Ty≡°lû↕
```
[Run and debug it](https://staxlang.xyz/#p=99fd8544911e0f5479f0f86c9612&i=1%0A10%0A44701&a=1&m=2)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
fÞȮ¬)ȯ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJmw57IrsKsKciv4oiRIiwiIiwiNSJd)
```
∑ # Sum of...
ȯ # First n integers...
----) # Where...
f # Digits
¬ # Are not
ÞȮ # Sorted
```
[Answer]
# [Red](http://www.red-lang.org), 108 bytes
```
func[n][i: s: 0 until[t: form i
if(t > u: sort copy t)and(t < reverse u)[s: s + i n: n - 1]i: i + 1
0 = n]s]
```
[Try it online!](https://tio.run/##PYzBCgIhFEX3fsVdNkSgMBBI9RFtxUWMCg/qOTyfQV9vrmZ3OJdzJafxzClEU/wonbfAMZBH87DorPQO6lGqfECGyknxQJ9zFcVW9x90eXGa@gbJ3ywtoy9h1g1nENiDcYGL85KmccbiDo4tjl2IFWWqg@yB63q1bvwB "Red – Try It Online")
## More readable:
```
f: func [ n ] [
i: s: 0
until [
t: form i
if ( t > u: sort copy t ) and ( t < reverse u ) [
s: s + i
n: n - 1
]
i: i + 1
0 = n
]
s
]
```
A good opportunity to use `form` - `form i` is 5 bytes shorter than `to-string i`
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~31~~ 30 bytes
```
l9`tVdZS&*0<a?wQtG>?.]y]QT]xvs
```
[Try it online!](https://tio.run/##y00syfn/P8cyoSQsJSpYTcvAJtG@PLDE3c5eL7YyNjAktqKs@P9/QwMA "MATL – Try It Online")
```
l % Initialize counter to 1
9 % First value to check for being bouncy
` % Start do-while loop
tV % duplicate the current number and convert to string
% (let's use the iteration where the number is 1411)
% stack: [1, 1411, '1411']
d % compute differences between the characters
% For non-bouncy numbers, this would be either all
% positive values and 0, or all negative values and 0
% stack: [1, 1411, [3 -3 0]]
ZS % keep only the signs of those differences
% stack: [1, 1411, [1 -1 0]]
&* % multiply that array by its own transpose, so that
% each value is multiplied by every other value
% for non-bouncy numbers, all products will be >=0
% since it would have had only all -1s or all 1 (other than 0s)
% stack: [1, 1411, [1 -1 0
-1 1 0
0 0 0]]
0<a? % if any value in the matrix is less than 0
wQ % switch the counter to top, increment it
% stack: [1411, 2]
tG>? % duplicate it, check if it's gotten greater than the input limit
.] % if so, break out of loop
y] % else, duplicate bouncy number from inside stack,
% keeping a copy to be used for summing later
% stack: [1411, 2, 1411]
QT % increment number, push True to continue loop
] % loop end marker
x % if we've broken out of loop, remove counter from stack
v % concatenate the bouncy numbers we've collected in stack and
s % sum them
```
[Answer]
# [R](https://www.r-project.org/), 96 bytes
```
function(n){while(n){y=diff(T%/%10^(0:log10(T))%%10);g=any(y<0)&any(y>0);F=F+T*g;n=n-g;T=T+1};F}
```
[Try it online!](https://tio.run/##HchBCsIwEEDRvfeIzFiKEywUjOMyJ8haEDUxUKZQLBKkZ49JNp/HX7Ln7Fd5fOIsIPj7vuP0qkj8jN6DU0el6QZ0nuagCRyiKgNN4LskSBfCfcO1PMu2c4dghKUPxrHr9Gbslj1o3JVQ7al1GEZqc6SK/Ac "R – Try It Online")
**Explanation :**
```
while(n){ # while n > 0
T%/%10^(0:log10(T))%%10 # split T into digits(T==TRUE==1 at the 1st loop)
y=diff( ) # compute the diff of digits i.e. digits[i] - digits[i+1]
g=any(y<0)&any(y>0) # if at least one of the diff is < 0 and
# at least one is > 0 then T is "bouncy"
F=F+T*g # if bouncy increment F (F==FALSE==0 at the 1st loop)
n=n-g # decrement n by 1 if bouncy
T=T+1} # increment T by 1 and loop
F} # return F
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 76 bytes
```
->n,s=i=0{[d=(i+=1).digits,d.reverse].index(d.sort)||(s+=i;n-=1);n<1?s:redo}
```
[Try it online!](https://tio.run/##NcpBDoIwEEDRvado4qYEaFpTQcTRg5BuzBQzm2I6aDTi2SuQ@JcvPz6u79RDKs@hYCDQnw5BUg4mU0g3GrlAFf3TR/ZOUUD/kqh4iGM2TZJzoDaU89yGk7nwMXocvuku@s44sbQVRpvNCtr9odqvYm2t522RprL1rjmY9AM "Ruby – Try It Online")
[Answer]
# C (gcc), 104 bytes
```
f(b,o,u,n,c,y){for(o=u=0;b;u+=y?0:o+0*--b,++o)for(n=o,y=3;n/10;)c=n%10,n/=10,y&=(c-=n%10)<0?:c?2:y;b=u;}
```
Try it online [here](https://tio.run/##PY3BasMwDIbPyVOIQoc1K8TpCoOoIg/S9TB7zfCh9kjngxfy7Jkzyi4Sn/5Pkms@nVvXUVmKlCiQo4zzGCcVJYlhy0lLHkwftXluGktaR9ziIJGyvHBoO8PoJOw7Q6GVUvOTKNf8TfBkht4Nhz6zlcTL6sM33N59UAhzXW0U0s1ep/v5AgIzdATlAhyPr6aDhetq@7VpvsSGSzvB3f9c46gei9g@uFjIoLXHuqq@poKj2u0/3sKO4N8@@wsi18v6Cw).
Ungolfed:
```
f(n, // function: return type and type of arguments defaults to int;
// abusing extra arguments to declare variables
i, // number currently being checked for bounciness
s, // sum of the bouncy numbers
j, // copy of i to be used for checking bounciness in a loop
p, // used for investigating the last digit of j
b) { // whether i is not bouncy; uses the two least significant bits to indicate increasing/decreasing
for(i = s = 0; // check numbers from zero up; initial sum is zero
n; // continue until we have n bouncy numbers
s += b ? 0 // not bouncy, no change to the sum
: i + 0* --n, // bouncy, add it to the sum and one less bouncy number to go
++i) // either way, move to the next number
for(j = i, b = 3; j/10; ) // make a copy of the current number, and truncate it from the right until there is just one digit left
// bounciness starts as 0b11, meaning both increasing and decreasing; a value of 0 means bouncy
p = j % 10, // get the last digit
j /= 10, // truncate one digit from the right
b &= // adjust bounciness:
(p -= j % 10) // compare current digit to the next
< 0 ? // not an increasing number, clear second to least significant bit
: p ? 2 // not a decreasing number, clear least significant bit
: b; // keep it the same
n = s; // gcc shortcut for return s
}
```
[Answer]
## Ruby (123 106 bytes)
```
o=0
x=[?0]
(z=(x=(x.join.to_i+1).to_s.chars).sort)!=x&&z!=x.reverse ? (n-=1;o+=x.join.to_i):1while n>0
p o
```
Looks pretty ugly to me. Bounciness is defined in this block `x.sort!=x&&x.sort!=x.reverse`
]
|
[Question]
[
# Challenge
The challenge is to write a code that takes a positive integer 'n' as an input and displays all the possible ways in which the numbers from 1 - n can be written, with either positive or negative sign in between, such that their sum is equal to zero. Please remember that you may only use addition or subtraction.
For example, if the input is 3, then there are 2 ways to make the sum 0:
```
1+2-3=0
-1-2+3=0
```
Note that, the numbers are in order, starting from 1 till n (which is 3 in this case). As it is evident from the example, the sign of the first number can also be negative, so be careful.
Now, 3 was pretty much simple. Let us list all the ways when we consider the number 7.
```
1+2-3+4-5-6+7=0
1+2-3-4+5+6-7=0
1-2+3+4-5+6-7=0
1-2-3-4-5+6+7=0
-1+2+3+4+5-6-7=0
-1+2-3-4+5-6+7=0
-1-2+3+4-5-6+7=0
-1-2+3-4+5+6-7=0
```
So here, we have got a total of 8 possible ways.
---
# Input And Output
As stated before, the **input would be a positive integer**. Your output should contain all the possible ways in which the numbers give a sum of zero. **In case there is no possible way** to do the same, **you can output anything** you like.
Also, **you can print the output in any format you like**. **But, it should be understandable**. For example, you may print it as in the above example. Or, you may just print the signs of the numbers in order. Otherwise, you can also print '0's and '1's in order, where '0' would display negative sign and '1' would display positive sign (or vice versa).
For example, you can represent 1+2-3=0 using:
```
1+2-3=0
1+2-3
[1,2,-3]
++-
110
001
```
However, I would recommend using any of the first three formats for simplicity.
You can assume all the inputs to be valid.
---
# Examples
```
7 ->
1+2-3+4-5-6+7=0
1+2-3-4+5+6-7=0
1-2+3+4-5+6-7=0
1-2-3-4-5+6+7=0
-1+2+3+4+5-6-7=0
-1+2-3-4+5-6+7=0
-1-2+3+4-5-6+7=0
-1-2+3-4+5+6-7=0
4 ->
1-2-3+4=0
-1+2+3-4=0
2 -> -
8 ->
1+2+3+4-5-6-7+8=0
1+2+3-4+5-6+7-8=0
1+2-3+4+5+6-7-8=0
1+2-3-4-5-6+7+8=0
1-2+3-4-5+6-7+8=0
1-2-3+4+5-6-7+8=0
1-2-3+4-5+6+7-8=0
-1+2+3-4+5-6-7+8=0
-1+2+3-4-5+6+7-8=0
-1+2-3+4+5-6+7-8=0
-1-2+3+4+5+6-7-8=0
-1-2+3-4-5-6+7+8=0
-1-2-3+4-5+6-7+8=0
-1-2-3-4+5+6+7-8=0
```
---
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins!
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
f n=[l|l<-mapM(\i->[i,-i])[1..n],0==sum l]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6pybHRjc3scBXIyZT1y46U0c3M1Yz2lBPLy9Wx8DWtrg0VyEn9n9uYmaegq1CQVFmXomCikKagsl/AA "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
1,-ṗ×RSÐḟ
```
[Try it online!](https://tio.run/##ARoA5f9qZWxsef//MSwt4bmXw5dSU8OQ4bif////NA "Jelly – Try It Online")
# Exp
```
1,-ṗ×RSÐḟ Main link. Input = **n**. Assume n=2.
1,- Literal list [1, -1].
ṗ Cartesian power **n**. Get [[1, 1], [1, -1], [-1, 1], [-1, -1]]
×R Multiply (each list) by **R**ange 1..n.
Ðḟ **ḟ**ilter out lists with truthy (nonzero)
S **S**um.
```
---
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
[Jonathan Allan](https://codegolf.stackexchange.com/users/53748)'s suggestion, output a list of signs.
```
1,-ṗæ.ÐḟR
```
[Try it online!](https://tio.run/##ARoA5f9qZWxsef//MSwt4bmXw6Yuw5DhuJ9S////Nw "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
f=lambda n,*l:f(n-1,n,*l)+f(n-1,-n,*l)if n else[l]*(sum(l)==0)
```
[Try it online!](https://tio.run/##JYxBCoAgEADP9QqPbhlktwJfEh2MtIR1C61Drzer2wwDc9zntlOXklWo/bxoRqLCwXJqpHgR6p@bT5xlxAxGM@JU8Xh5jqBUC8nuIRdHLGhaDZeih6EsjuDozMe8gPQA "Python 2 – Try It Online")
*Mr. Xcoder saved 4 bytes with a nifty use of starred arguments.*
[Answer]
# Perl, ~~37~~ 36 bytes
```
perl -E 'map eval||say,glob join"{+,-}",0..<>' <<< 7
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
®X‚¹ãʒ¹L*O_
```
[Try it online!](https://tio.run/##AR0A4v8wNWFiMWX//8KuWOKAmsK5w6PKksK5TCpPX///Mw "05AB1E – Try It Online")
The output format for e.g. input `3` is:
```
[[-1, -1, 1], [1, 1, -1]]
```
That is, `-1-2+3, 1+2-3`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes
```
Pick[p={1,-1}~Tuples~#,p.Range@#,0]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z8gMzk7usC22lBH17C2LqS0ICe1uE5Zp0AvKDEvPdVBWccgVu1/QFFmXkl0WrR5bOx/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
fo¬ΣΠmSe_ḣ
```
[Try it online!](https://tio.run/##yygtzv7/Py3/0Jpzi88tyA1OjX@4Y/H////NAQ "Husk – Try It Online")
## Explanation
Not too complicated.
```
fo¬ΣΠmSe_ḣ Implicit input, say n=4
ḣ Range: [1,2,3,4]
m Map over the range:
Se pair element with
_ its negation.
Result: [[1,-1],[2,-2],[3,-3],[4,-4]]
Π Cartesian product: [[1,2,3,4],[1,2,3,-4],..,[-1,-2,-3,-4]]
f Keep those
Σ whose sum
o¬ is falsy (equals 0): [[-1,2,3,-4],[1,-2,-3,4]]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 105 bytes
```
lambda n:[k for k in product(*[(1,-1)]*n)if sum(-~n*s for n,s in enumerate(k))==0]
from itertools import*
```
[Try it online!](https://tio.run/##Hc0xDoMwDEDRnVN4dCKQijpUQspJKENaEjWC2MgxA0uvnkL39/W3Qz9M9xrds64@v2YPNIwLRBZYIBFswvP@VrQj9m3Xm8mSSRHKnrH7ki1/SW25bKA9B/EacDHGudvUROEMSYMo83qavLGorVcjVxHxYYYGzksiRTH1Bw "Python 3 – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~69 61~~ 58 bytes
*Saved 8 bytes thanks to @Neil*
*Saved 3 bytes thanks to @l4m2*
Prints all solutions.
```
f=(n,o='')=>n?f(n-1,o+'+'+n)&f(n-1,o+-n):eval(o)||print(o)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P81WI08n31ZdXdPWLs8@TSNP11AnX1sdCPM01WBc3TxNq9SyxByNfM2amoKizLwSIOt/cn5ecX5Oql5OfrqGgoJ6tHmsuqZ1moa5JheyjHpMXrQJRMYEU8YIImOEKWMBkbHQ/A8A "JavaScript (V8) – Try It Online")
[Answer]
# [Swift](https://swift.org), 116 bytes
```
func f(n:Int){var r=[[Int]()]
for i in 1...n{r=r.flatMap{[$0+[i],$0+[-i]]}}
print(r.filter{$0.reduce(0){$0+$1}==0})}
```
[Try it online!](https://tio.run/##NY5BCsIwFET3PUUoXSQ0hlQKSiUHcOEJYhalNvCh/pZvqouQs9cUcTU8mDfM6wM@tNvmVxyY59hdMYj47omRsTaD48IVfiYGDJA1SimMZEj5qQ@3fom20rUFJ/c4gHMpFQsBBp4rMIWRYqUVjY91GLkWGeqqScboJNL2n7Un2cqjPLv4U0Fm7wnYh5m6srtjKS77N8jOFw)
## Explanation
```
func f(n:Int){
var r=[[Int]()] // Initialize r with [[]]
// (list with one empty list)
for i in 1...n{ // For i from 1 to n:
r=r.flatMap{[$0+[i],$0+[-i]]} // Replace every list in r with the list
} // prepended with i and prepended with -i
print(r.filter{$0.reduce(0){$0+$1}==0}) // Print all lists in r that sums to 0
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 91 bytes
```
lambda x:[s for s in[[~j*[1,-1][i>>j&1]for j in range(x)]for i in range(2**x)]if sum(s)==0]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCKrpYIS2/SKFYITMvOrouSyvaUEfXMDY6084uS80wFiSVBZRSKErMS0/VqNAEi2QiRIy0tICCmWkKxaW5GsWatrYGsf8LijLzShTSNMw1/wMA "Python 2 – Try It Online")
Returns a list of satisfying lists (e.g., f(3)=[[-1,-2,3], [1,2,-3]])
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 38 bytes
```
{k/⍨0=+/¨k←((,o∘.,⊢)⍣(⍵-1)⊢o←¯1 1)×⊂⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqbP1HvSsMbLX1D63IBvI1NHTyH3XM0NN51LVI81HvYo1HvVt1DTWBvHyg7KH1hgqGmoenP@pqetS7GShV@///o7aJaQrmXOq2trbqXGCOCTLHCJljAQA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), 13 bytes
```
f!sT.nM*F_BMS
```
**[Try it here!](https://pyth.herokuapp.com/?code=f%21sT.nM%2aF_BMS&input=4&debug=0)**
[Answer]
# [Clean](https://clean.cs.ru.nl), 79 bytes
```
import StdEnv
$n=[k\\k<-foldr(\i l=[[p:s]\\s<-l,p<-[~i,i]])[[]][1..n]|sum k==0]
```
[Try it online!](https://tio.run/##Jc27CsIwFIDh3afI0EGhKToJkmx2ELp1PDlD7EUOudKkgiA@urHg@C/fP9hJ@@LCuNqJOU2@kIthyazPY@ufu8pLMEoZwedgx2WviFkJEC8JlUqC2zoKDh@qCfEAgAinpvH4TqtjRsojlj7rjZOsYufyHWarH6nwW1euL68dDf/Ybh3dfw "Clean – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 73 bytes
```
.+
*
_
=_$`
+0`=
-$%"+
(-(_)+|\+(_)+)+
$&=$#2=$#3=
G`(=.+)\1=
=.*
_+
$.&
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4srnss2XiWBS9sgwZZLV0VVSZtLQ1cjXlO7JkYbRGlqc6mo2aooGwGxsS2Xe4KGrZ62ZoyhLZetnhYXVzxQWk/t/39zAA "Retina – Try It Online") Explanation:
```
.+
*
```
Convert the input to unary.
```
_
=_$`
```
Convert the number to a list of `=`-prefixed numbers.
```
+0`=
-$%"+
```
Replace each `=` in turn with both `-` and `+`, duplicating the number of lines each time.
```
(-(_)+|\+(_)+)+
$&=$#2=$#3=
```
Separately count the number of `_`s after `-`s and `+`s. This sums the negative and positive numbers.
```
G`(=.+)\1=
```
Keep only those lines where the `-`s and `+`s cancel out.
```
=.*
```
Delete the counts.
```
_+
$.&
```
Convert to decimal.
[Answer]
# Python 3 + numpy, ~~104~~ 103 bytes
```
import itertools as I,numpy as P
lambda N:[r for r in I.product(*[[-1,1]]*N)if sum(P.arange(N)*r+r)==0]
```
Output is [-1, 1] corresponding to the sign.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~171~~ 161 bytes
* Saved ten bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
k,s;f(S,n,j)int*S;{if(s=j--)S[j]=~0,f(S,n,j),S[j]=1,f(S,n,j);else{for(k=n;k;)s+=k--*S[k];if(!s)for(puts("");k<n;)printf("%d",S[k++]+1);}}F(n){int S[n];f(S,n,n);}
```
[Try it online!](https://tio.run/##PY6xDsIgEIZfBWlMOIGkzCdrB1bGymBqMS16GtGp0VevaLTb3X35v/86fey6eU4qYxRekRphoPvG4zREke2oNfh2DPZVqz9X34NZduxPuZ/i5SaSJUwIWdqk9ca3KWCxrDJ84PVxz4JzwLQlhOut1ETB1wdefEnKIA3g89kIgqkg5lsKv5eogPm8H0g4@PY4W6Pbmtqgk3JR7aiqKkbMsvWBlZErB6opmZJ@Aw "C (gcc) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~101~~ ~~100~~ 83 bytes
Represents addition as 0 and subtraction as 1, but that ultimately that does not matter since for any valid sequence, the complement of the sequence will also result in zero. Returns the permutations by appending them as 32-bit ints to a caller-provided buffer.
```
i,j,s;f(n,p)int*p;{for(i=1<<n;--i;s||(*p++=i))for(j=s=0;j<n;)s+=i>>j++&1?j:-j;n=p;}
```
[Try it online!](https://tio.run/##VVHLbsIwEDwnX7FKBeRZ4hJVFY7DrT8BqAqBgCMwURz6EOTXm64do7Y@eL07szP2uoj2RdH3PKxCSUtXhLXHRevX9FqeG5czkqaCRhGn8nZz/ToIGPc8BVVMsphWiHoSi1lWBcGYLKp5VFHBatr1D1wUx8t2B6lst/z8eMhs2eYtL6A4C9lCccgb8E2y4SJvvt4E32yOuyV5XgODq205MS4nBIeYGBOT66gJxBCIIZhcx0GBGAViFIhRIHcFQyCGYHIV7Y7ap5wL18Pb6JEIddlWMkJ1TNnLcAgCz7aQZGnGpVyqoq@2dQg4UAuhmpWuqoSIe1QVGmSXriPYiM9XAm0VrCE0A@3Gcc7AIYU6wjY8aidtpb3e8yMOSznytWr87RymiSAKmHMK@gLBzJsm9@KgNwhaf/8GYamk//2NsssySHyjOIb483VNQXcP7wHXGT36El8zcDKmPKfJQoVRMk80MDzT6tRWX1pl6U5WYqLLWO3srv8uymO@l3300Uen2dMP "C (gcc) – Try It Online")
# Explanation
```
i,j,s; // iterators i and j, sum s.
f(n,p)int*p; // declare function
{
for ( i=1<<n; --i; // iterate over all permutations of n bits (except all-0)
s||(*p++=i)) // if the permutation summed to 0, append it to the buffer
for(j=s=0;j<n;)
s+= i>>j++&1 // Determine the value of the jth bit
?j:-j; // 1=>+(j+1), 0=>-(j+1)
n=p; // return the pointer to the end of the appended values
}
```
[Answer]
# [Perl 6](https://perl6.org), 43 bytes
```
{grep *.sum==0,[X] (1..$_ X*1,-1).rotor(2)}
```
[Try it](https://tio.run/##NY7RCoIwGIXv9xTHEbWlLe0iArF6jCAq0lYY6samQYTPvpbVufu@H/5ztDTV0nVW4rEURUrqJ8aFukhk7nUzUmMqbFdnWRztdwewRIjRCbtpEs0SLoxqlWEL3jsxvpRWV@cnrsrg84CteEqI7XL8LwxbWza3SoLjRQDr3c@I@qzZx33jK9aIB9xsABqOTnSgIPD0hZ6Luyobvy63LZsfaUjn0QQT39q7Nw "Perl 6 – Try It Online")
Returns a sequence of lists
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
grep # only return the ones
*.sum == 0, # that sum to zero
[X] # reduce with cross meta operator
(
1 .. $_ # Range from 1 to the input
X* # cross multiplied by
1, -1
).rotor(2) # take 2 at a time (positive and negative)
}
```
`1..$_ X* 1,-1` ⇒ `(1, -1, 2, -2)`
`(…).rotor(2)` ⇒ `((1, -1), (2, -2))`
`[X] …` ⇒ `((1, 2), (1, -2), (-1, 2), (-1, -2))`
[Answer]
# [J](http://jsoftware.com/), 35 30 bytes
-5 bytes thanks to FrownyFrog!
```
>:@i.(]#~0=1#.*"1)_1^2#:@i.@^]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7awcMvU0YpXrDGwNlfW0lAw14w3jjJRBog5xsf81uRS4UpMz8hXSFMwhDHV1mIAJuoARuoAF138A "J – Try It Online")
## Original:
# [J](http://jsoftware.com/), 35 bytes
```
[:(#~0=+/"1)>:@i.*"1(_1^[:#:@i.2^])
```
## How it works
I multiply the list 1..n with all possible lists of coefficients 1 / -1 and find the ones that add up to zero.
```
( ) - the list of coefficients
i. - list 0 to
2^] - 2 to the power of the input
_1^[: - -1 to the power of
#:@ - each binary digit of each number in 0..n-1 to
*"1 - each row multiplied by
>:@i. - list 1..n
(#~ ) - copy those rows
0=+/"1 - that add up to 0
[: - compose
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600lOsMbLX1lQw17awcMvW0lAw14g3joq2UQTyjuFjN/5pcClypyRn5CmkK5hCGujpMwARdwAhdwILrPwA "J – Try It Online")
As an alternative I tried an explicit verb, using the approach of cartesian product of +/-:
# [J](http://jsoftware.com/), 37 bytes
```
3 :'(#~0=+/"1)(-y)]\;{(<"1@,.-)1+i.y'
```
`{(<"1@,.-)` finds the cartesian products for example:
```
{(<"1@,.-) 1 2 3
┌───────┬────────┐
│1 2 3 │1 2 _3 │
├───────┼────────┤
│1 _2 3 │1 _2 _3 │
└───────┴────────┘
┌───────┬────────┐
│_1 2 3 │_1 2 _3 │
├───────┼────────┤
│_1 _2 3│_1 _2 _3│
└───────┴────────┘
```
Too bad that it boxes the result, so I spent some bytes to unbox the values
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jRWs1DWU6wxstfWVDDU1dCs1Y2OsqzVslAwddPR0NQ21M/Uq1f9rcilwpSZn5CukKZhDGOrqMAETdAEjdAELrv8A "J – Try It Online")
[Answer]
Not the best but I tried :)
# C (Linux GCC)
## Entire program: 282 characters
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int n,x,i,s;int main(int c,char**z){n=atoi(z[1]);int a[n];for(x=0;x<n;x++)a[x]=x+1;for(i=0;i<pow(2, n)-1;i++){s=0;for(x=0;x<n;x++){printf("%c%d",i>>x&0x01?'-':'+',a[x]);s+=(i>>x&0x01?-1:1)*a[x];}printf(s!=0?"\r":"=%d \n",s);}}
```
## Just as function: 196 characters
```
void z(int n){int a[n],x,i,s;for(x=0;x<n;x++)a[x]=x+1;for(i=0;i<pow(2,n)-1;i++){s=0;for(x=0;x<n;x++){printf("%c%d",i>>x&0x01?'-':'+',a[x]);s+=(i>>x&0x01?-1:1)*a[x];}printf(s!=0?"\r":"=%d \n",s);}}
```
### Results
* n = 4:
```
+1-2-3+4=0
-1+2+3-4=0
```
* n = 7:
```
+1-2-3-4-5+6+7=0
-1+2-3-4+5-6+7=0
-1-2+3+4-5-6+7=0
+1+2-3+4-5-6+7=0
-1-2+3-4+5+6-7=0
+1+2-3-4+5+6-7=0
+1-2+3+4-5+6-7=0
-1+2+3+4+5-6-7=0
```
## Abstract Printing & Just Function: 172 characters
You could shrink the print statements down much more by simply outputting only the +/-'s which are represented by 1/-1 and abstractly representing the entire sum thing, but I still don't think it would beat the other C answers anyway.
That version is:
```
void z(int n){int a[n],x,i,j,s;for(x=0;x<n;x++)a[x]=x+1;for(i=0;i<pow(2,n)-1;i++){s=0;for(x=0;x<n;x++){j=i>>x&0x01?-1:1;printf("%d ",j);s+=j*a[x];}printf(s!=0?"\r":"\n");}}
```
## Results
* n = 4:
```
1 -1 -1 1
-1 1 1 -1
```
* n = 7:
```
1 -1 -1 -1 -1 1 1
-1 1 -1 -1 1 -1 1
-1 -1 1 1 -1 -1 1
1 1 -1 1 -1 -1 1
-1 -1 1 -1 1 1 -1 1
1 1 -1 -1 1 1 -1
1 -1 1 1 -1 1 -1 1
-1 1 1 1 1 -1 -1 -1
```
[Answer]
# T-SQL, 152 bytes
Input is a *varchar(max)*
Output format is *+1+2-3*
```
WITH C as(SELECT @*1d,@+null o,0f
UNION ALL
SELECT~-d,concat(char(44+s),d,o),f+s*d
FROM C,(values(-1),(1))x(s)WHERE d>0)SELECT
o FROM C WHERE f=0and d=0
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1255293/make-zero-from-first-n-numbers)**
[Answer]
# [R](https://www.r-project.org/), ~~82~~ 69 bytes
```
s=t(expand.grid(rep(list(c(-1,1)),n<-scan())))*1:n;t(s[,!colSums(s)])
```
[Try it online!](https://tio.run/##K/r/v9i2RCO1oiAxL0UvvSgzRaMotUAjJ7O4RCNZQ9dQx1BTUyfPRrc4OTFPQxMItAyt8qxLNIqjdRST83OCS3OLNYo1YzX/W/wHAA "R – Try It Online")
*Edit: -13 bytes by using built-in `expand.grid` function to automatically create matrix of all combinations of `+1` and `-1`.*
Selects rows of matrix of 1:n in all combinations of positive & negative which sum to zero.
Commented version:
```
s=t( # transpose matrix of:
mapply(rep, # apply the function 'rep'
list(c(-1,1)), # to the values (-1, 1)
each=2^(0:(n-1)), # repeating each by an increasing power-of-2
length=2^n) # and making the output length always 2^n
) # so: this generates a matrix of all the
# combinations of -1 and 1
t( # now transpose the matrix s
s[, # taking only the columns with a
!colSums(s*1:n)] # zero sum of multiplying the values
) # by the sequence 1:n
```
**Previous (but sadly ~~longer~~ *much* longer) recursive strategy: 118 bytes**
```
f=function(n,l=NULL,t=0)`if`(n>1,c(f(n-1,c(0,l),t-n),f(n-1,c(1,l),t+n)),`if`(t==n,list(c(0,l)),if(t==-n)list(c(1,l))))
```
[Try it online!](https://tio.run/##XY7BCoMwEER/Zxc3oLdetl8gvXnWIi4E4wbS9eLPx8S2F@cy8JgZJuXtvS7jsaQ4SoobZ2HZdTYfFZQCv4a@J@MWJy8T6LOjGQTUVW8pIJlTpD/pLtIoIl15Yy4j/mPwTSN5qbB0frQ2im434IH5BA "R – Try It Online")
Outputs `1` for `+` and `0` for `-` (or the other way around).
Commented version:
```
f=function(n,l=NULL,t=0){ # n = counts down to 1 recursively
# l = list of signs so far
# t = total so far
if(n==1){ # if n is 1...
if(t-n==0){ # ...then if t-n makes zero...
return(list(c("-",l))) } # add a '-' to the list of signs & return it
else if(t+n==0){ # ...or, if t+n makes zero...
return(list(c("+",l))) } # add a '+' to the list of signs & return it
else { # ...otherwise we can't make zero...
return(NULL) } # so return NULL
} else { # if n is greater than 1
return(c( # return the result of calling this function
f(n-1,c("-",l),t-n), # using n-1, after applying either a '-'
f(n-1,c("+",l),t+n) # or a '+' and updating the total so far
))
}
}
```
]
|
[Question]
[
I have written [a few challenges](https://codegolf.stackexchange.com/search?q=user:31516%20[matrix]%20is:question) related to matrices, and common for all are that I use a format like the one below when representing the matrices, both in examples and in test cases:
```
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
```
This is likely a cumbersome format in many languages.
---
# Challenge:
Write a program/function that can **take a matrix on the form given in the top as input (directly copy/pasted from this post), and output the same matrix on all of the three other conventional formats shown below**.
### The input format:
Numbers separated by a varying number of spaces, and newlines to represent rows (see test cases).
* The number of spaces between numbers are not guaranteed to be consistent. You may however assume that the last digit in each column align (if that helps any).
* There can be both integers and floats, and they can be positive, negative or zero. A matrix will not contain integers *and* floats at the same time.
* You may assume that no number is longer than 10 characters, including the minus and decimal point for negative floats.
* You may assume that there are the same number of entries in each row and in each column.
* There won't be any empty input matrices, but there can be single numbers, or matrices with only one row or column.
+ You may in these cases choose between the output formats shown in the test cases
Your program/function must handle the input if it's directly copied from this post and pasted into the interpreter (STDIN or as function argument or something equivalent). You may have whatever you like (brackets, quotation marks, parentheses) in front of, and/or after the matrix, but you must consider the matrix a sequence of characters that can't be altered (that includes the newlines).
**To clarify:** Assume your function/program is called `f` and the matrix is:
```
1 -2
3 5
6 7
```
then you may give the matrix as function arguments like this (and infinitely many other options):
```
f(1 -2
3 5
6 7)
f([1 -2
3 5
6 7])
f("""1 -2
3 5
6 7""")
```
If your language can't, in any way, take the copy/pasted matrix as input then I'm afraid you have to pick another language.
---
### The output format:
You should output the matrix on the following three formats (order doesn't matter):
```
[[16, 2, 3, 13], [5, 11, 10, 8], [9, 7, 6, 12], [4, 14, 15, 1]]
{{16, 2, 3, 13}, {5, 11, 10, 8}, {9, 7, 6, 12}, {4, 14, 15, 1}}
[16, 2, 3, 13; 5, 11, 10, 8; 9, 7, 6, 12; 4, 14, 15, 1]
```
* You may separate the three outputs however you want (e.g. a newline)
* You must output the numbers using the same precision as the input (for instance, you must not trim the number of decimals, nor output integers as floats).
* The spaces are mandatory
* You must use `-` for negative numbers, not `_` or similar.
### Test cases:
```
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
----
[[16, 2, 3, 13], [5, 11, 10, 8], [9, 7, 6, 12], [4, 14, 15, 1]]
{{16, 2, 3, 13}, {5, 11, 10, 8}, {9, 7, 6, 12}, {4, 14, 15, 1}}
[16, 2, 3, 13; 5, 11, 10, 8; 9, 7, 6, 12; 4, 14, 15, 1]
```
```
0.14778 0.27114 0.24415
0.45997 0.12287 0.67470
0.28945 0.37928 0.51887
----
[[0.14778, 0.27114, 0.24415], [0.45997, 0.12287, 0.6747], [0.28945, 0.37928, 0.51887]]
{{0.14778, 0.27114, 0.24415}, {0.45997, 0.12287, 0.6747}, {0.28945, 0.37928, 0.51887}}
[0.14778, 0.27114, 0.24415; 0.45997, 0.12287, 0.6747; 0.28945, 0.37928, 0.51887]
```
```
-0.0398301 0.2403455 -0.2253368 0.3565870 0.0605803 0.0830780
-0.3254422 -0.1185191 -0.2989537 0.1647319 0.3621135 0.2018815
-0.0022281 -0.3362287 -0.3568447 0.4419063 0.3801872 -0.2847033
---
[[-0.0398301, 0.2403455, -0.2253368, 0.3565870, 0.0605803, 0.0830780], [-0.3254422, -0.1185191, -0.2989537, 0.1647319, 0.3621135, 0.2018815], [-0.0022281, -0.3362287, -0.3568447, 0.4419063, 0.3801872, -0.2847033],]
{{-0.0398301, 0.2403455, -0.2253368, 0.3565870, 0.0605803, 0.0830780}, {-0.3254422, -0.1185191, -0.2989537, 0.1647319, 0.3621135, 0.2018815}, {-0.0022281, -0.3362287, -0.3568447, 0.4419063, 0.3801872, -0.2847033},}
[-0.0398301, 0.2403455, -0.2253368, 0.3565870, 0.0605803, 0.0830780; -0.3254422, -0.1185191, -0.2989537, 0.1647319, 0.3621135, 0.2018815; -0.0022281, -0.3362287, -0.3568447, 0.4419063, 0.3801872, -0.2847033]
```
```
0 4 1 0
0 0 -6 0
0 1 4 -3
2 0 0 8
0 0 0 0
----
[[0, 4, 1, 0], [0, 0, -6, 0], [0, 1, 4, -3], [2, 0, 0, 8], [0, 0, 0, 0]]
{{0, 4, 1, 0}, {0, 0, -6, 0}, {0, 1, 4, -3}, {2, 0, 0, 8}, {0, 0, 0, 0}}
[0, 4, 1, 0; 0, 0, -6, 0; 0, 1, 4, -3; 2, 0, 0, 8; 0, 0, 0, 0]
```
```
1
----
[1] (or [[1]])
{1} (or {{1}})
[1] (or 1)
```
```
1 2
----
[1, 2] (or [[1, 2]])
{1, 2} (or {{1, 2}})
[1, 2]
```
```
4
5
----
[[4], [5]]
{{4}, {5}}
[4; 5]
```
---
I'm fully aware of [this](https://codegolf.meta.stackexchange.com/a/8077/31516), but in this challenge, the cumbersome I/O format is the whole point. The challenge will be all about formatting the output in some languages, while reading the input will be the hardest part in other languages.
Please do not be discouraged if reading the input is hard, those submissions might be the most interesting ones. Short isn't necessarily the same as impressive. And as always, explanations are encouraged!
[Answer]
# [Retina](https://github.com/m-ender/retina), 52 bytes
This answer is based on my [Perl answer](https://codegolf.stackexchange.com/a/129142/55508), with the help of [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) for the golfing with Retina.
```
^ *
[
$
]
\s+
,
m):`.+
[$&]
*T`[]`{}
], .
;
^.|]$
```
[Try it online!](https://tio.run/##ZVE7UsQwDO11CheBWXY3GX38kckxlm4JEwoKCiiADrgWB@BiQbYzyyx4JnqKpPf8lLw8vD0@3y/fXzDCYR5HuNhsDJc7t4UjdDDB7esO9g6erq7nYQfH7nKC7c18nOb3T5j2boDRwd3wMXWwHOZuoejscAliDwm4UJBKwFJWcLlgKqFME4PzBWso044AcCCfktoLDpyoNi3znoL1fMg51Qoxa8ti8gmtx5p9qBVJmZtCINUE0OOAklWQVjUUH2zW6sxBJLZpCTFowppjxKAoLTdmUiwywsF75kol0kCZmkzWHGS1Fn0Syk0yMpE0W4zmxtYobpDNf6Pa9W2XvjpQ75uMrZwxNgeixk3tWlbbV8Q@lWvHr0gr4qmzYh//deic2wvwOeeE@lftFwHsh5FjAA/hBw "Retina – Try It Online")
The explanations can be found on my Perl answer. The differences are:
```
*
[
$
]
```
Instead of `s/^ *(.+)/[$1]/gm` to both remove the leading spaces and add brackets around the lines.
```
^.|]$
```
To remove the leading and trailing brackets for the third output.
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~57~~ 54 bytes
Byte count assumes ISO 8859-1 encoding.
```
m`^ +
¶
] [
+
,
:`.+
[[$&]]
*T`[]`{}
], .
;
^.|]$
```
[Try it online!](https://tio.run/##ZVFLTsQwDN37FFkMCDHTyr8kDj3GsKs6KgsWLGCB2AHX4gBcrDhNNWggUv1c2@/luX19fHt6eVi@v2CA4zwMcHXjsDzPp7AH8PIURvD0EOBu7vcwjrvraYLb@3mc5vdPmA6hhyHAqf@YdrAc591CKfjhGsQfEgixItWAtWwQSsVcQ50mhqAV11CnAwFgT5qz@Qv2nGlteqZK0XsaS8lrhZitZSlrRu@xFY1rRXLhphDJLAN02KMUE6RNDUWjz3qdOYqkNi0xRcu45pgwGkrLnZkNq4xwVGVeqUQWqVCTKVaibNaSZqHSJBMTSbPF6G58jeoG2f03ql/fdulWB6baZHzlgqk5EHNubtey@b4i/qlCO7ohbYjnzoZd@tehS24nwJecM9pftV8E8B9GgQEU4g8 "Retina – Try It Online")
The TIO link currently prints no linefeeds between the three formats but that's because it uses an unstable commit. The program does print the intermediate linefeeds in Retina 0.8.2.
### Explanation
```
m`^ +
```
Get rid of leading spaces on each line.
```
¶
] [
```
Replace linefeeds with `] [`.
```
+
,
```
Replace all runs of spaces with a comma and a space.
```
:`.+
[[$&]]
```
Wrap the entire thing in `[[...]]` which completes the first format. Print the result.
```
*T`[]`{}
```
Replace brackets with braces and print the result without actually changing the working string (i.e. the first format is restored after this is printed).
```
], .
;
```
Replace `], [` with a semicolon and a linefeed.
```
^.|]$
```
Remove the first `[` and the last `]`. This completes the third format.
[Answer]
# Scala, ~~183~~ ~~181~~ 149 bytes
[Try it online!](https://tio.run/##pVRLj9MwEL77VwzWHhJIIr8fLQXtkQMnxKn0ENrsUhTSyg1oUZTfXsZxy7LsBQUr8ozn8c3M5ySnbd3W58Pnr822h/f1voOBAOyaO/iGh6wO96cF3IZQ/1x/6MO@u9/kC/jY7XtYYSQJGaWUQyngumQlcREJoLTCJ9q4IBrAVIynGCUwK6@O4bD7vu3f9U2o@0Oo7g6hqbdfsiPW6dsuJzH2csjyx1oRXBMDYOfD/EcD85tXRM@va6Jx4llGSiUBHWWklLNodgR8lDZuJtEOkX8@bXq6idn1WcWVtQ4drBKWT5ioKcU1YZXS3tvJwoVwSTNWWYY@4bzSk0VaLxKC5s7Nv72SVUx6J6f3KTbBpNJYAu1CaClNKiK10c6ySWeGacdk0jHTOkYwXAp8SYWYUjl3mnueYLzzWl4mMspK7hOkEZzLNI1gOAROH7thAsdOqVg@UVBOHTilEgwy5ZlJHUiHuTaVFQ5pknL@xVw@PHWRl28MkPqrlkRpnnn409xSEvE057d0f6M9yn/tfDz/qFsIq@xhkX4l@erNEE271UMVmmNbb5vbts3opw5e0oIuAXH/tGdvX79Y5vAKfQX6ltmJrtc3w@4alMWUgm4KWNN83GxocaLD8DxgLGDAgHGMAeub3QYP5/H8Cw "Scala – Try It Online")
## New version, using `String` replacements and regexes:
```
(x:String)=>{val d=x.replaceAll("\n *","; ").replaceAll("(?<!;) +",", ");(s"[[${d.replace("; ","], [")}]]",s"{{${d.replace("; ","}, {")}}}",s"[$d]")}
```
The new version has the same semantics and usage as the old version using `split`, `map` and `mkString`.
## Old version, using `split`, `map` and `mkString`:
### Edit: Redundant character class for space removed
```
(x:String)=>{val d=x.split("\n").map(_.trim.split(" +").mkString(", "));(d.map(x=>s"[$x]").mkString("[",", ","]"),d.map(x=>s"{$x}").mkString("{",", ","}"),d.mkString("[","; ","]"))}
```
Lambda. Execute in REPL. Accepts input as triple-quoted `String` parameter, returns output as a 3-tuple of the required outputs. The REPL renders tuples separated by commas, bordered by parentheses.
## Explanation:
### New version:
Mostly the same logic as the other regex-based answers, except for the tricky lookbehind to handle leading spaces on lines.
### Old version:
We split the input matrix representation into a 2D `String` array, then map it to a 1D array by collapsing the inner arrays by separating the elements with `,` . Finally, we just create the different outputs by collapsing the 1D arrays by using the required newline separators and boundary markers (prefixes and suffixes). It's all implemented via `split` (reading), `map` (transforming) and `mkString` (collapsing).
Example REPL session:
```
scala> val r=(x:String)=>{val d=x.split("\n").map(_.trim.split(" +").mkString(", "));(d.map(x=>s"[$x]").mkString("[",", ","]"),d.map(x=>s"{$x}").mkString("{",", ","}"),d.mkString("[","; ","]"))}
scala> r("""16 2 3 13
| 5 11 10 8
| 9 7 6 12
| 4 14 15 1""")
res12: (String, String, String) = ([[16, 2, 3, 13], [5, 11, 10, 8], [9, 7, 6, 12], [4, 14, 15, 1]],{{16, 2, 3, 13}, {5, 11, 10, 8}, {9, 7, 6, 12}, {4, 14, 15, 1}},[16, 2, 3, 13; 5, 11, 10, 8; 9, 7, 6, 12; 4, 14, 15, 1])
```
For the few-element edge cases, this provides the desired output.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~63~~ 53 bytes
This was coming in at 44 bytes before I noticed that the spacing in the output was mandatory.
```
·®¸f
"[[{q"],["}]]
\{\{{q"},\{"}}}
[{q';}]"r",|;"_+S
```
[Test it](http://ethproductions.github.io/japt/?v=d2af30a143a0774cde9e8ff45afc3a55efee2383&code=t664ZgoiW1t7cSJdLFsifV1dClx7XHt7cSJ9LFx7In19fQpbe3EnO31dInIiLHw7Il8rUwo=&input=IjE2ICAgIDIgICAgMyAgIDEzCiA1ICAgMTEgICAxMCAgICA4CiA5ICAgIDcgICAgNiAgIDEyCiA0ICAgMTQgICAxNSAgICAxIg==)
---
## Explanation
```
:Implicit input of string U
· :Split to an array on newlines.
® :Map over the array.
¸ :Split each element to an array on spaces.
f :Filter to remove empty elements from the subarrays.
"[[ :Start building the output string. In Japt strings, anything enclosed in {}s will be evaluated before being added to the string.
{q"],["} :Join the array to a string using ],[ The sub-arrays will be cast to comma separated strings in the process.
]] :That's the first line done.
\{\{ :The start of the second line. A few bytes have to be sacrificed to esapce the {s
{q"},\{"} :Join the array to a string using },{
}} :That's the second line done.
[ :And on to the last line.
{q';} :This time we join the array with a semi-colon.
]" :And that's the string completed.
r :Except we still need to replace...
",|;" : All occurrences of a comma or a semi-colon with...
_+S : Itself and a space.
:Implicit output of resulting string.
```
[Answer]
# [Perl 5](https://www.perl.org/), 71 bytes
69 bytes of code + `-p0` flags.
```
s/^ *(.+)/[$1]/gm;s/\s+/, /g;$_="[$_]
{".y/[]/{}/r."}
".s/], \[/; /gr
```
[Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdAsM/hfrxyloaehpa@pHqxjG6qfnWhfrxxRr6@so6Kdbq8TbKkWrxMdyVSvpVepHx@pX1@oX6SnVcinpFevH6ijEROtbA9UV/f9voAABJlDaEEobcMFkoLSuGYaMIapeXWMuI1Q9cNoC3TQEDQA "Perl 5 – Try It Online")
**Explanations**
`s/^ *(.+)/[$1]/gm;` adds `[]` around each line while removing the leading spaces.
`s/\s+/, /g;` replaces runs of spaces and newlines with a comma and a space.
The first output is then obtained by surrounding with braces: `[$_]`.
The second needs to replace braces with curly bracket (`y/[]/{}/r`) and surround with curly brackets `"{" ... "}"`.
For the third, `], [` are replaces with a semicolon and a space (`s/], \[/; /gr`).
---
After writing this solution, I tried adpating Martin Ender's Retina answer, but it ended up 10 bytes longer ([TryItOnline](https://tio.run/##ZYyxDsIwDER3f4UJ3WjiFApCqvgSYzqhLiBFzYSifHuwRAAVvLzTne/Cdb7ty3oVlGiDL5EuuCGa7kMkIEGmSZVaLapqxpNhbkYRSMm4B7FQyjQ7kzOwcZGkxTPToM9qiinF4@v6yq7SwzuptIe/pFt27Q62y86Hx9@1L58)):
```
s/^ +//gm;s/
/] [/g;s/ +/, /g;$_="[[$_]]
{{".y/[]/{}/r."}}
[".s/], \[/; /gr."]"
```
For this version, see Martin's [answer](https://codegolf.stackexchange.com/a/129138/55508) for the explanations.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 60 bytes
```
`jtU&D32', 'XHYXw]xXhH&Zc91wh93htD[]&D{}&DXED&GxvUH&4$'; 'TD
```
[Try it online!](https://tio.run/##y00syfn/PyGrJFTNxdhIXUdBPcIjMqI8tiIiw0MtKtnSsDzD0jijxCU6Vs2lulbNJcLVRc29oizUQ81ERd1aQT3E5f9/QwUjLmMFEy5TBTMuLgA "MATL – Try It Online")
Thanks a lot to Luis Mendo for shaving off a quarter of my bytecount in a masterclass in chat.
Paste the input, followed by an empty line.
```
% Act I: Taking input.
`jt w] % Take input line by line until an empty line is encountered.
U % Convert string input to numerical row array
&D % Convert back to string, adding brackets and single spaces
32', 'XHYX % Add commas before the spaces. Store ', ' in clipboard H.
% Act II: Nested square brackets
x % Discard the tab character
Xh % Concatenate all strings as cell array.
H&Zc % Join all the strings together, using clipboard H as a separator
91wh93h % Wrap in square brackets (ASCII 91 and 93)
tD % Display a copy of the result.
% Act III: Nested curly brackets
[]&D{}&D % Convert empty array and cell array to string.
XE % Use to substitute square for curly brackets.
% Act IV: MATLAB-style input.
&Gxv % Get all the input again, discard the tab, and concatenate vertically.
U % Convert to numerical
&4$ TD % Convert to string, using row- and column separators
H'; ' % Namely, clipboard H and a semicolon.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~45~~ 44 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
```
|„ ð:ðδÛ˜ð¡„, ý''KD…[ÿ]=„[]„{}‡,"], ["„; :=
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/5lHDPAWFwxusDm84t@Xw7NNzDm84tBAopqNweK@6urfLo4Zl0Yf3x9oChaJjgUR17aOGhTpKsToK0UpArrWCle3//4ZmCkBgBCKMgdjQmEvBFEQbgggDkLAFl4IliDYHESDVhkZcCiYgGkyAVCsYAgA "05AB1E – Try It Online")
**First output**
```
| # push a list of the inputs
„ ð: # replace any instance of 2 spaces with 1 space
ðδÛ # remove any leading spaces
˜ # flatten to a 1D list
ð¡ # split on spaces
„, ý # merge on ", "
''K # remove all single quotes
D # duplicate for use in output 3
…[ÿ] # interpolate between square brackets
= # print without popping
```
**Second output**
```
„[]„{}‡, # translate square brackets to curly brackets and print
```
**Third output**
```
# the copy from the first output is used here
"], ["„; : # replace "], [" with "; "
= # print
```
[Answer]
# [Python 2](https://docs.python.org/2/), 143 bytes
```
import re
b=re.sub
def f(s):s='[['+b('\n','], [',b(' +',', ',b('\n +','\n',s)))+']]';print s,b('\[','{',b('\]','}',s)),b('\], \[','; ',s)[1:-1]
```
[Try it online!](https://tio.run/##JYzBDoIwDIbve4qGS1mYxoGiQniSsQsRIgcH2fBgjM8@29Gk/9@//bb1sz0XV8Y4v9bFb@BHMXR@PIb3IB7jBFMeZBM6NAaLIcfeoUKrwKCiBAUlBWnuXUoMBCllgdZiu/rZbRDSnZ7gd0ctjb/E7VFBurbAO6Obg7ZxyrMs0zVQlSwVta4EXNg1y4nXNwF39isL07oUcGZPwjTomr6S8Q8 "Python 2 – Try It Online")
[Answer]
# Javascript (ES6), ~~121~~ ~~110~~ 106 bytes
-15 bytes thanks to @Shaggy and @Justin
```
m=>`[[${(a=m.split`
`.map(x=>x.match(/\S+/g).join`, `)).join`], [`}]]
{{${a.join`}, {`}}}
[${a.join`; `}]`
```
Example code snippet:
```
f=
m=>`[[${(a=m.split`
`.map(x=>x.match(/\S+/g).join`, `)).join`], [`}]]
{{${a.join`}, {`}}}
[${a.join`; `}]`
console.log(f(
`1 -2
3 5
6 7`
))
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~163~~ ~~152~~ ~~150~~ 145 bytes
*-5 bytes thanks to Felipe Nardi Batista who suggested the use of splats (sorry, I just need an excuse to say that word :P).*
```
import re
a=str.replace
def f(s):r=a(`[re.findall('[\.\d]+',i)for i in s.split('\n')]`,"'",'');print r,a(a(r,*']}'),*'[{'),a(r[1:-1],'], [','; ')
```
[Try it online!](https://tio.run/##TY5Bb4QgFITv/IoXLw9algjCgrvZX6ImS7qaklg16KVp@tst6KWXmcc3kwnL9/Y5T2rfw9cyxw1iT/xj3aKI/TL6j568@gEGurJbfHj6bGIvhjC9/DhSbFrRvrp35IENc4QAYYJVrMsYNorthKx78gILjsjuSwxTWueeehr5G3a/yJI1P8kSaeTtIjuOHYcGOd4B2T7QoigkXBSpAAy5AtgEGCFnkN4AKkuKQVYETHaZpczYEaiz2yy5LRUBnf2Q3Ab5b7EUUlvrEi2FsvJopUtraUgptKlrexCplDuvq9W2TJlytTYHqWytzgUjnTv@u/8B "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~184 178 174 173 169 163\* 157\*~~ 153 bytes
**Input/Output Format:** Output with a space between the matrices and input with this function call (as shown on TIO):
```
g("""<paste matrix here>""")
```
This is the function :
```
def g(s,r=str.replace):a=str([[[int,float]['.'in y](y)for y in x.split()]for x in s.split('\n')]);print(a,r(r(a,*'[{'),*']}'),'['+r(a,'], [','; ')[2:-1])
```
[Try it online!](https://tio.run/##rVFBboMwELz7Fav0YNwCYg3EkKgvoRxocFIkBMhYTVDVt1MvpK3SXmPJO@tZe3ZsD5N967t4nmt9hJM3@uZ5tCY0emirgxa7ipZeURRNZ/1j21e2LHjImw6m0pvEsTcwgVtdwnFoG@uJkqgLUeOV4i8dF6XYD8ZpeJVvPOPiIy8@uHBQfjrgBX8ilpc@FNzne@CikLsASzGzk7fZbKIQE6UyAIhCqRCTNUsSTFkUJmmeq4VBKbM126pERa4mszxJFyZWuVwVUswy5VQFY6stAct4gKqudU32e1NrA7aHVlfvGjp9bptOj/Cq7VnrDqweLRyqUY9sdYhbUpAUYjcxZkBtESlERGcMckLyB7QbJQO6yHIbpN2Ad3YVrRJLm0X/iu5lvrMVgu2/Ct6eDWImb8/8YPZX7Rfv/cr31oMgdX@hCIIMAvdTAWIUOR5z6jV/AQ "Python 3 – Try It Online")
---
\**Saved a 6 bytes thanks to @officialaimm (from 169 to 163 bytes).*
\**Saved 4 bytes thanks to @FelipeNardiBatista.*
---
Explanation to come after further golfing.
[Answer]
# C, 415 bytes
```
#import<stdio.h>
#define A(a,c,o)for(l=strlen(a)-o,k=0;c[k];)a[l+k]=c[k++];
j,k,l;main(i){char s[999],a[999]="[",b[999]="{",c[999]="[",t[]=" ";for(;fgets(s,999,stdin);){A(b,"{",0)A(a,"[",0)for(i=0;s[i];++i){j=0;for(;s[i]-32&&s[i]-10&&s[i];++i){j=1;t[0]=s[i];A(c,t,0)A(b,t,0)A(a,t,0)}if(j){A(c,", ",0)A(b,", ",0)A(a,", ",0)}}A(c,"; ",2)A(b,"}, ",2)A(a,"], ",2)}A(c,"]",2)A(b,"}",2)A(a,"]",2)puts(a);puts(b);puts(c);}
```
It's a monster and waaayyyy too long, but I'm done with it. Should have gone for a different approach probably.
[Try it online!](https://tio.run/##RY/djoMgEIXvfQpikwbidCO2@2NYN@lzEC6Qaku12ih71fjsLoN2S8KcM8MHM5jd2Zh53tjbvR/c9@hOtn@7/ESbU1XbriJHqsFAz@p@oG0xuqGtOqrZroemSIWRjRJMyzZpVOGTJFEiukIDrbhp21HLHuaiBzLKPM8V6CBFLGMoV/uIwbyqTnolscBuoj5XbqQj@FPAuTom2ONIS8BLKcPJ8E4aZrN@mlFaJZLEN736LLyBpd0@226D4elinhAXTqaqCKUjNeDCs@WqOuhka3rFvgZiIPFK/Fv9tNMUEOGTbEEmWL1n1OIXRr2QF4Du/us/rJkIWq5qmJjmmX8QvzIMe7/5PiLvqBxDiuWviOSonxiQ5llEDqghIE34Hw)
[Second test case](https://tio.run/##RY/RjoIwEEXf/QqCiWnDSFqELaTLJn4H6UOpoBUEA@yT4dvZtuD6dM/cuZ2ZquNVqWXZ68ezH6bvcbroPrz97PaXqtZd5Z2RBAU9rvsBtfk4DW3VIYmPPTQ54apoBMeyaING5KYIAsF3d2ig5Q@pO6TxS93k4I1FlmUCpJPcL3woN3z5oD7uVBj1fG638fpaTSMawXTB3tVhjl9nVIJ9RLC9zL4h7jZtrhkLLXgQmKV3U7kZ1jqeosPBASUrvEOUTwURubPOSMHkxpabSqezrtHd7lXgg@dviX@Ub5xnF@GmiNbIDBubjFh5zYhP5BOw9Pw1H5aYOy03VZjPy0JCGjOWep5HwohRGq8UxzTZkTBOsow5h0ZRutIXixkxvSjN4sQ5J5ZF64SEpin7Aw)
|
[Third test case](https://tio.run/##RY/NbsIwEITvPIWVSlWsGLT@S2y5qcRzRDkYEyBASUXSE8qzU/@k5TSfNzM7G7c@Ovd8vvVf38N9@hinfT9sTp@rt3136G8d2uaWODLgw3DPr/U43a/dLbd4PZBLDcY1l9Zg21yLS1v7R1G0ZnUmF3I1X7a/5T1@uJO9o7HRWrfERqmzJiO7BR8Zca/p1HhFmQlt5nDspjEfif9Kwl03bPBjm@9ICAEOl4UMxNt6f83Y9K0pCl969q@4I4zWnL2/R6CQ4M9EzdRAW8fRNndkimt3i9qoc3/Iz6HXkYygbHH8o/3DeY4W4x8sWWaysPe0iZOnfVlehkDfP/6HLTZRd4s6bObncw0b4FpxoAgh2DABXEiJkJ8zJjkvVZxzWUpVQWQoQSrgiX2yUrDyds6kEIzFKKVKUk3TGq205FW001JUnOq0smSUcplqgSpFZVgDwBhTKerrPVeJZamESGuEoBrKdAFXPlulWqZEBZz/Ag)
|
[Fourth test case](https://tio.run/##ZY9NboMwEIX3nAIRKbLFUJmkqhq5VOIclhfGgcRAIAJ3FXF2ahsTlNab783Mmx/L5CLlPO/U7d4P@mvUZ9W/Xb@D3bmsVFeGORIgocdVP6A2G/XQlh0SOOmhyQiVrOEUC9bGDc9MEMecBjU00NKbUB1S@CGvYghHdjqdOAiHLGIRFF4@IpBbVjPDMKJ2G60upR7RCKYK9q4OU/zIUQG2iWB7me0h7jZlrhmZ4jSOzdLaRG6GTSXHw37vREoWsZpSqhnhmUvlSIJ2YwtP4TipCtV2r4QIwsg7nlKscpqchZrgsFgm8Np4@KIXD98sm8Gq@4/5sMDUsfCUmE7zTMLlvXumniRYK57Jx79K@tqbHIPDa8@Tn3@nbfwF)
|
[Fifth test case](https://tio.run/##RY/BjoMgEIbvfQpDkwbiuNHuyUzdxOcgHJBqi1pthD0Zn90FtOvp/2f4ZuZHJQ@l1vWsX@9xsjdj73r8ev6czve60UMdlVSCgpE140T7wtiprwcqWTJCV6SoeCeQSd7HnShcEccCTy100ONL6oFqNqunnCLD8zwXIIMUhBOodjsTUEfXcqcRQX8Nm0dtDTXgXsHnGhiyuaQV@KGU@WR@Jg3ZtEtjuBYYx@5o66qww7eS7@vlEkyWbuYDZWh5KorQKqkCG9ZWu8qgi25o6@8qIBCRnfi38mOXJSDoiuuGLLB7x4jNb4w4kAPw7v3rPiwZBq12VQyXdc3@AA)
| [Sixth test case](https://tio.run/##RY/BjoMgEIbvfQpDkwbiuNHuyUzdxOcgHJBqi1pthD0Zn90FtOvp/2f4ZuZHJQ@l1vWsX@9xsjdj73r8ev6czve60UMdlVSCgpE140T7wtiprwcqWTJCV6SoeCeQSd7HnShcEccCTy100ONL6oFqNqunnCLD8zwXIIMUhBOodjsTUEfXcqcRQX8Nm0dtDTXgXsHnGhiyuaQV@KGU@WR@Jg3ZtEtjuBYYx@5o66qww7eS7@vlEkyWbuYDZWh5KorQKqkCG9ZWu8qgi25o6@8qIBCRnfi38mOXJSDoiuuGLLB7x4jNb4w4kAPw7v3rPiwZBq12VQyXdc2i6x8)
| [Seventh test case](https://tio.run/##RY9BboMwEEX3OQVypMgWQ0XSdIGmVOIclhfGgcRAIMLuCnF2ahtSVv/P@M3Mt0ruSi3LUT9fw2i/jb3p4ePxczjeqlr3VVRQCQoGVg8j7XJjx67qqWTJAG2eouKtQCZ5F7cid0UcCzw00EKHT6l7qtmkHnKMDM@yTIAMkhNOoNzsREDtXcudRgT9NazvlTXUgHsFn6tnyKaCluCHUuaT@Zk0ZNMujeFaYBy7o42rwg7fSj4vp1Mw53Q1b@iMlqciD62CKrBhbbmpDDrrmjb@rgICEdmIfyvfdp4Dgq64rMgMm3eMWP3KiB3ZAe9ev@7DkmHQclPFcF6W6@HrDw)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 37 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
j€⁾, j⁾; ⁾[]j
ỴḲLÐf$€VµŒṘṄ“[]“{}”yṄȧÇ
```
A full program printing the three formats on three lines.
**[Try it online!](https://tio.run/##y0rNyan8/z/rUdOaR437dBSygKS1ApCIjs3ierh7y8Mdm3wOT0hTAcqHHdp6dNLDnTMe7mx51DAnOhZIVNc@aphbCRQ4sfxw@////w3NFIDACEQYA7GhMZeCKYg2BBEGIGELLgVLEG0OIkCqDY24FExANJgAqVYwBAA "Jelly – Try It Online")**
### How?
```
j€⁾, j⁾; ⁾[]j - Link 1, create the 3rd format (semicolon-style): list of lists
⁾, - literal [',', ' ']
j€ - join for €ach (place ", " between the elements of each row)
⁾; - literal [';', ' ']
j - join (place "; " between the rows)
⁾[] - literal ['[', ']']
j - join (surround the whole result with a pair of brackets)
ỴḲLÐf$€VµŒṘṄ“[]“{}”yṄȧÇ - Main link: list of characters
Ỵ - split at newlines
$€ - last two links as a monad for €ach row:
Ḳ - split at spaces
Ðf - filter keep those for which the following is truthy:
L - length (this removes all the empty lists "between" spaces)
V - evaluate as jelly code (yields a list of lists of numbers)
µ - monadic chain separation, call that x
ŒṘ - get a Python string representation of x
Ṅ - print that (the 1st format) plus a newline, and yield it
“[]“{}” - literal [['[', ']'],['{', '}']]
y - translate (converts all '[' to '{' and all ']' to '}')
Ṅ - print that (the 2nd format) plus a newline, and yield it
Ç - call the last link as a monad with argument x
ȧ - logical and
- implicit print of the result (the 3rd format)
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 41 bytes
```
òJé;òÓ¨ä©ó«/±,
yss]Y.pkÓ; /], [
Ùòcs]}f[
```
[Try it online!](https://tio.run/##ATwAw/92///DskrDqTvDssOTwqjDpMKpw7PCqy/CsSwgCnlzc11ZLnBrw5M7IC9dLCBbCsOZw7Jjc119Zlv//zI "V – Try It Online")
### Explanation
```
òJé;ò Join all lines with `; ` (trailing single space)
Ó¨ä©ó«/±, :s/\v(\d)\s+/\1, /g
yss] Surround everything with brackets (completes [x,x;x,x])
Y.pk (Y)ank, surround with brackets again, (p)aste. Adds [[x,x;x,x]]
Ó; /], [ :s/; /[, ]/g (transforms to [[x,x], [x,x]])
Ù Duplicate this line
ò recursively
cs]} (c)hange (s)urrounding [] with {}
f[ go to the next [ until there are none
```
[Answer]
# [R](https://www.r-project.org/), 132 bytes
```
function(x,p=paste0,g=gsub)cat(z<-p('[[',g('\n','], [',y<-g('[:blank:]',', ',x)),']]'),chartr('[]','{}',z),p('[',g('
','; ',y),']'))
```
[Try it online!](https://tio.run/##JY7NboMwEITveQrfjCUTrb3@WafhSSgHggqpWlFEiJSk6rPTBd/G45lvdl77au3vY7d8/ozFQ0/V1N6WD9BDNdzuF9W1S/E6l1Mh61rqoZDvo9Sy0YJfz3PJRn26fLfj16lhXwupH0pxoJFKd9d2XmZObF@/f1K/lN5AO@fA3hvHn1taKrX2hSzhCJgIwQgh4GgdoPNeCPat9YiBdh998BRh1xDAE2DW3IwEB46j9c5Zu1eNIW@SyZhEyWPc4ya4iCZlZLDGoM@zYIiM3zAA1lrKVZ5nHbP2gZzLGOdMgpAvQOJuzLOWXAREqdZ/ "R – Try It Online")
an anonymous function. Takes input like
```
f('1 -2
3 5
6 7')
```
It prints them in the same order as the test cases, but with spaces as the separator.
### Explanation:
It first swaps spaces with `,` and saves the result as `y`. Then it swaps newlines with `], [`, puts `[[` and `]]` on either end, and saves the result of that as `z`.
Next, `chartr` switches `[` with `{` and `]` with `}` in `z`.
Finally, it takes `y`, swaps newlines with `;` and puts `[` and `]` on either end.
Then all the results are passed in that order to `cat` which prints them out, all nicely formatted, and separated by a single space.
Mildly ungolfed:
```
function(x)
cat(
z<-paste0('[[',gsub('\n','], [',y<-gsub('[:blank:]',', ',x)),']]'),
chartr('[]','{}',z),
paste0('[',gsub('\n','; ',y),']'))
```
[Answer]
# Java 8 with Netbeans 8+, 209 bytes
Count is 208 from the code, plus 1 bytes to run it by pressing `F6`.
Cumbersome answer for cumbersome challenge :p
```
interface M{static void main(String[]a){String s="";s=s.trim().replaceAll(" +",", ").replaceAll("\n(, )?","; ");System.out.println("["+s+"]\n[["+s.replace("; ","], [")+"]]\n{{"+s.replace("; ","}, {")+"}}");}}
```
How to use?
Within Netbeans, paste this code in a file called `M.java`. Then copy the matrix you want to use. Then between the two consecutive characters `""`, press `ctrl`+`v` as required by the challenge.
Now press `F6`! This will compile the code, run it and output the expected matrix representations.
[Answer]
# Mathematica, 129 bytes
```
s=StringSplit
r=StringReplace
Print[#,n,#~r~{"{"->"[","}"->"]"},n,#~r~{"{{"->"[","}}"->"]","}, {"->"; "}]&@ToString@s@s[#,n="
"]&
```
The third and fourth lines together define a pure function taking a string as input; for example, if we set `f=Print...&`, then the last test case would be called as:
```
f@"4
5"
```
The snippet
```
ToString@s@s[#,n="
"]
```
parses the input string as a matrix (of strings—we never try to interpret the entries as numerical quantities) and converts the resulting expression back to a string; this automatically generates the output format with curly braces. Then `Print[#,n,#~r~{"{"->"[","}"->"]"},n,#~r~{"{{"->"[","}}"->"]","}, {"->"; "}]` prints that output format and the two others, separated by newlines, by using straightforward string replacement rules.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~49~~ 46 bytes
45 bytes of code, +1 for `-r` flag.
```
g|>:sYP(RPg^w)R';kPyR'['{R']'}O'[OgRwkJ"; "']
```
Takes input from stdin. [Try it online!](https://tio.run/##K8gs@P8/vcbOqjgyQCMoID2uXDNI3To7oDJIPVq9Okg9Vr3WXz3aPz2oPNtLyVpBST32/39DMwUgMAIRxkBsaMylYAqiDUGEAUjYgkvBEkSbgwiQakMjLgUTEA0mQKoVDP/rFgEA "Pip – Try It Online")
### Explanation
```
Preset variables used: s is " ", w is regex `\s+`, k is ", "
g With -r flag, g is a list of lines from stdin
|>:s Left-strip spaces from (elements of) g and assign back to g
YP(RPg^w)R';k
g^w Split (elements of) g on runs of whitespace
RP Apply Pip's built-in repr, which wraps lists in [] and separates items
with ; (e.g. [[1;2];[3;4]])
( )R';k Replace the semicolons with ", " to obtain format #1
YP Print and yank into y variable
PyR'['{R']'}
yR'['{ In y, replace [ with {
R']'} and ] with }
P and print (format #2)
O'[OgRwkJ"; "']
O'[ Output [ with no newline
O Output with no newline:
g Take g (list of lines of stdin, with leading spaces stripped)
Rwk Replace runs of whitespace with ", "
J"; " and join lines on "; "
'] Print the final ] to complete format #3
```
(This explanation format feels a bit convoluted to me, so let me know if anything didn't make sense.)
[Answer]
# SCALA, 590 bytes
Was hard, but I think I'm done with it
```
var o=s.replaceAll(" *"," ").replaceAll("\n ","\n")
var z=o.split("\n")
var h=z.length
var k=new Array[Array[String]](h)
for(i<-0 to h-1)k(i)=z(i).split(" ")
var u=k.length-1
print("{")
for(i<-0 to u){print("{")
for(j<-0 to k(i).length-2)print(k(i)(j)+", ")
print(k(i).last)
print("}")}
print("}[")
for(i<-0 to u){print("[")
for(j<-0 to k(i).length-2)print(k(i)(j)+", ")
print(k(i).last)
print("]")}
print("][")
for(i<-0 to u-1){for(j<-0 to k(i).length-2)print(k(i)(j)+", ")
print(k(i).last)
print("; ")}
for(j<-0 to k(k.length-1).length-2)print(k(u)(j)+", ")
print(k.last.last)
print("]")
```
Quick explanation : I take input surrounded by triple quotes, then take off unrequired spaces ; split the string two times (once for lines and once for columns) ; and I print with my three routines. It might be possible defining a function to mutualize, but I don't know how.
[Try it online!](https://tio.run/##rZLBcoMgEIbP5Sl2OEEbnWhMD2095AF66tF4oIZEDUUHSZvq@OwWo8aktrcwzML@C9/P7FBETLAme095pOGVJRL4UXO5KWCV5xW62/AtfDCtkiMpnt7MKne0aj6ZgswvbMVzwSK@EoJggHs8w4DplbqWYNS1xBS1l0o/s4tcJJqMWuyXtuByp@NTuvcl/4KVUuw76GJnG4YkpmibKZK8WHPQGcSWQ/ckoX5pwoCFnnrw9z3VclBuAKZW4WvAgVa/KmlfabHDdZd2h1qNpPQBz1qPUbMFK/Qg4BrT@rwP/jUMbmYYXhiGE0PTouo2Ps/QGl2zxhb/AT1MoSfi5PlNjfovhjF2wHJhGAt7YQaCUQDwlp6ZbeK4F5UlwKM9d7rEcw2Jorr5AQ)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 34 bytes
```
|εð¡õK}€ï"ÿ"Є[]„{}‡s¦¨"], ["„; :»
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/pqzy8IZDCw9v9a7VfNS05vB6pcP7lQ5PeNQwLzoWSFTXPmpYWHxo2aEVSrE6CtFKQCFrBatDu///NzRTAAIjEGEMxIbGXAqmINoQRBiAhC24FCxBtDmIAKk2NOJSMAHRYAKkWsEQAA "05AB1E – Try It Online")
`ε...}` has been replaced with `vy...})` on TIO since it hasn't been pulled there yet.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 214 bytes
```
(s)=>{var result=Regex.Replace("[["+Regex.Replace(s.Replace("\n","], [")," +(\\d)",", $0")+"]"," +"," ").Replace("[, ","[");return$"{result}]\n{result.Replace('[','{').Replace(']','}')}}}\n[{result.Replace("[","").Replace("],",";")}";};
```
[Try it online!](https://tio.run/##XVBNa8MwDL37VwhTSEy9tln3iddeygaF7bINdnB8CKnbBTKn2E7pCP7tmbyOtszg9@SnZ0modBdlY3Xfusps4O3bef0lyPlr9K73fvSqN21d2Mf91mrnqsY40Zd14RxsO@J84asSdk21gpeiMqnzFgtItWQxGWMo7AZmsJQTJchTa8qHg84PNIc1Zsl4vGhWGj611SR1bDbvdoUF7NjWfpZSKekQB9F7HGdbF6VO3TGiuaGcKg6SMk5hmOb5iqHCYZBRNqSKspNXcsAUOoXVvrVmQLtDk6By8xce3YlMeNIlp@@JQiEkLISQG/nfjmU5PW@mcAgqKAtUBEEWuLqm1qMPW3n9XBmdrlPcDWOCBBL6vs9uAM9lhCnebErgOnIWYRLlOwL3kW8jRHd2SeAq8i9EN2Q/ "C# (.NET Core) – Try It Online")
Takes the Matrix as a string, returns the three formats as a single string separated by newlines.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
≔E⪪θ¶⪫Φ⪪ι λ, θE⪪[]{}²⪫ι⪫Eθ⪫ιλ, ⪫[]⪫θ;
```
[Try it online!](https://tio.run/##XYzNCsIwEITveYqwpxQqmNZfevLiQRBEj7WHIkEXQtqmpRfx2eNuaVVcsvNBZnZuj9LfqtKGsGtbvDt1LGt1qS12qoklXB1EsTxU6NQebWf86CF5ki1LC/QiYhNl4uTRdT8lkBfPFwWSqQb/2Iw8m9741ij8FNJMfUOCquB7BNmQyULIAUCvJE3CktLqVMglU7PM@Xsj5Ja5ZuG0ToRcMAfhtNTUVIRZb98 "Charcoal – Try It Online") Note: Trailing space. Link is to verbose version of code. Charcoal has a multiline input option delimited using `["""` and `"""]`. Explanation:
```
θ Input string
⪪ ¶ Split on newlines
E Map over each line
ι Current line
⪪ Split on spaces
Φ λ Filter out empty strings
⪫ , Join with `, `
≔ θ Assign resulting array to variable
```
This takes the input and prepares it by splitting it into lines and normalising the separators.
```
⪪[]{}² Split `[]{}` into substrings of length 2
E Map over the substrings
Eθ Map over array from above
⪫ιλ Wrap each element with the substring
⪫ , Join elements with `, `
⪫ι Wrap with the substring
Implicitly print each result on a separate line
```
This handles the `[[ ... ], [ ... ]]` and `{{ ... }, { ... }}` cases.
```
θ Array from above
⪫ ; Join elements with `; `
⪫[] Wrap result with `[]`
Implicitly print
```
This handles the `[ ... ; ... ]` case.
Before I golfed a byte off the above solution I used to have two 39-byte solutions; this is the other:
```
⮌E⪪[]{}[]²⪫ι⪫EE⪪θ¶⪫Φ⪪λ ν, ⎇κ⪫ιλλ⁺§;,,κ
```
[Try it online!](https://tio.run/##RYzNCsIwEITvfYplTylEMPUfT14EBaGot9pD0YDBEGtaRRGfPe7WShdmBjJf5ngu/PFa2BBSb1wttvqhfaXFpijFrrSmFpjl70@Wo4QklrC@GidMmwx14E0CHhz@oaWxtfZtZ6kDrhyJpjCm3GvvCv8Sl27Wxiyy1N4rsahX7qSfAudS0qdL/Ftpbh5ChohqDHQJ24CkBhGMOBVbn5@nEcw4J2xMqySCIWdjTIOipTz0HvYL "Charcoal – Try It Online") Note: Trailing space. Link is to verbose version of code. Explanation:
```
⪪[]{}[]² Split `[]{}[]` into substrings of length 2
E Map over the substrings
θ Input string
⪪ ¶ Split on newlines
E Map over each line
λ Current line
⪪ Split on spaces
Φ ν Filter out empty strings
⪫ , Join with `, `
E Map over each line
⎇κ λ If outer index is zero, just use the line
⪫ιλ Otherwise wrap the line in the substring
⪫ ⁺§;,,κ Join with `; ` or `, ` per outer index
⪫ι Wrap in the substring
⮌ Reverse the order of the results
Implicitly print each result on a separate line
```
]
|
[Question]
[
The program must output the letter that is paired the most. For example, if your program was given the following string:
```
"Sally's friend Bobby searched for seashells."
```
it must output `L` because `"ll"` occurs twice, which is more frequent than the other pair `"bb"`.
Rules:
* If more than one letter has 1st place for occurrences, then output all of them in alphabetical order (e.g. `"Sally's friends Jimmy and Bobby rummaged for seashells."` should output both `L` AND `M` [or `"LM"` if you please] because they both occur more frequently than other pairs.)
* Letters which are tripled, quadrupled, etc. count as one pair (e.g. `"lll"` in `"willless"` is counted as only one pair of `L`.)
* Letter pairs must be in one word (e.g. `"Sally's sociable friends Sammy and Bobby searched for fabulous seashells."` should output `L` and not `S` because despite `"ss"` having more occurrences than `"ll"`, they are separated by spaces.)
* Count only letters from the English alphabet
* Case does not matter (e.g. `"Ss"` is the same as `"SS"` or `"ss"`, and all are counted as one pair of `S`.)
You may read your input from wherever you please. Shortest code wins.
[Answer]
# Bash + GNU coreutils, 133
```
grep -Eo '([A-Z])\1+'<<<"${1^^}"|cut -c1|sort|uniq -c|sort -rn|while read n l
do((a-n&&a-0))&&exit||echo $l&&a=$n
done|sort|tr -d \\n
```
### Testcases:
```
$ for t in "Sally's friend Bobby searched for seashells." \
> "Sally's friends Jimmy and Bobby rummaged for seashells." \
> "willless" \
> "Sally's sociable friends Sammy and Bobby searched for fabulous seashells." \
> "11ss11aa"
> do
> ./mostpaired.sh "$t"
> echo
> done
L
LM
LS
L
AS
$
```
[Answer]
# Pyth, ~~26~~ ~~25~~ ~~24~~ ~~16~~ 15 bytes
```
.M/sfthTrrz08ZG
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=.M%2FsfthTrrz08ZG&input=Sally%27s%20friends%20Jimmy%20and%20Bobby%20rummaged%20for%20seashells.&debug=0)
### Explanation:
```
.M/sfthTrrz08ZG implicit: z = input string
rz0 convert z to lower-char
r 8 run-length-encoding (into tuples [count, char])
f filter for tuples T, which satisfy:
thT T[0]-1 != 0 (count > 1)
s join to a string
.M G find the elements Z of "abcd...z", which produce the highest value:
/...........Z count of Z in ...
```
[Answer]
# CJam, ~~29~~ 27 bytes
```
leue`{2a>},s_el-$e`$z~\)-,>
```
*Thanks to @Optimizer for golfing off 2 bytes!*
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=leue%60%7B2a%3E%7D%2Cs_el-%24e%60%24z~%5C)-%2C%3E&input=Sally's%20friends%20Jimmy%20and%20Bobby%20rummaged%20for%20seashells.).
### How it works
```
leu e# Read a line from STDIN and covert to uppercase.
e` e# Perform run-length encoding.
e# Example: "AABBBC!!" -> [[2 'A] [3 'B] [1 'C] [2 '!]]
{2a>}, e# Filter out all pairs that are less of equal to [2].
s e# Stringify.
e# Example: [[2 'A] [3 'B] [2 '!]] -> "2A3B2!"
_el e# Push a copy of the string and convert to lowercase.
e# Example: "2A3B2!" -> "2a3b2!"
- e# Remove all character from the second string from the first.
e# Example: "2A3B2!" "2a3b2!" - -> "AB"
$e`$ e# Sort, perform run-length encoding and sort again.
e# Example: "ABACABDBC" -> "AAABBBCCD"
e# -> [[3 'A] [3 'B] [2 'C] [1 'D]]
-> [[1 'D] [2 'C] [3 'A] [3 'B]]
z~ e# Zip and dump.
e# Example: [[1 'D] [2 'C] [3 'A] [3 'B]] -> [1 2 3 3] ['D 'C 'A 'B]
\) e# Pop out the last element from the first array.
e# Example: [1 2 3 3] -> [1 2 3] 3
- e# Remove all occurrences of the popped element from the array.
e# Example: [1 2 3] 3 -> [1 2]
, e# Compute the length of the remainder.
> e# Skip that many elements from the character array.
```
[Answer]
# Pyth - 23 22 21 20 bytes
Uses regexp substitution to replace all of two or greater of alphabet to a temp value, and uses `.M`aximal to get all the have the highest occurrence. Thanks to @Jakube for pointing out the redundancy of sorting and saving a byte.
```
.M/:rz0+Z"{2,}"KC0KG
```
Takes input from stdin and outputs like `['l', 'm']` to stdout.
```
.M G Values which yield maximal amount over lowercase alphabet
/ Count
: Regexp substitution
rz0 Lowercased input
+Z String concatenate current loop var
"{2,}" Regexp 2 or more of previous group
KCZ Inline assign null byte to K and use value
K Count K which is null byte
```
[Try it online here](http://pyth.herokuapp.com/?code=.M%2F%3Arz0%2BZ%22%7B2%2C%7D%22KC0KG&input=Sally%27s+friends+Jimmy+and+Bobby+rummaged+for+seashells.&debug=1).
[Answer]
# C, 155
Something different, no regexps.
```
m=1,i=1,n[91];
main(c,a)char**a;
{
char*t=a[1];
for(;c=*t++;)(c&=95)>64&&c<91&&(c-(*t&95)?i=1:(c=(n[c]+=i),i=0,m=m<c?c:m));
for(c=0;++c<91;)n[c]-m||putchar(c);
}
```
[Answer]
# Python 2, ~~132~~ 143 bytes
```
def f(x):import re;x=re.findall(r'(.)\1+',x.upper());s={l:x.count(l)for l in x};print "".join(sorted([l for l in s if s[l]==max(s.values())]))
```
Example run:
```
f("Sally's friends Jimmy and Bobby rummaged for seashells.")
LM
```
[Answer]
# CJam, 37 bytes
```
leue`{~_el-\(e&},1f=$e`$_W=0=f-{,1=},
```
[Try it online](http://cjam.aditsu.net/#code=leue%60%7B~_el-%5C(e%26%7D%2C1f%3D%24e%60%24_W%3D0%3Df-%7B%2C1%3D%7D%2C&input=Sally's%20friend%20Bobby%20searched%20for%20seashells.)
Without regular expression support, I'm afraid it will be tough to compete with Pyth. This is the best I came up with on a first pass.
Explanation:
```
l Get input.
eu Convert it to upper case, since case does not matter.
e` Run length encoding, to split into groups of same characters.
{ Start of block for filtering.
~ Unpack the length/letter pair.
_ Copy the letter.
el Change copy to lower case.
- Subtract to compare. If result is non-zero, this is a letter.
\ Swap count to top.
( Decrement to get truthy value for count > 1.
e& Logical and: It's a letter, and count is > 1.
}, End of filter.
1f= Don't need the counts anymore, filter out the letters only from the RLE pairs.
$ Sort them, so that multiples of the same letter are sequential.
e` RLE again, to count how many multiples of each letter we had.
$ And sort again, to get the count/letter pairs in order of incrementing count.
_ Copy list.
W=0= Pick out count of last element, which is the highest count.
f- Remove count from pairs that have the highest count. This leaves them
as one member lists with letter only, while others still have count/letter.
{ Start block for filter.
,1= Check for list length one.
}, End filter.
```
[Answer]
# Q (66)
Relatively readable to boot:
```
{where g=max g:.Q.A#count each group y where not differ y:upper x}
```
[Answer]
# R, 105 bytes
```
cat(substr(names(b<-table(regmatches(s<-toupper(readline()),gregexpr("([A-Z])\\1+",s))))[b==max(b)],1,1))
```
This reads a line of text from STDIN and prints a space delimited list of the most common paired letters to STDOUT.
Ungolfed + explanation:
```
# Read a string from STDIN, convert to uppercase
s <- toupper(readline())
# Get each match of the regex /([A-Z])\1+/
matches <- regmatches(s, gregexpr("([A-Z])\\1+", s))
# Compute the frequency of each match
freq <- table(matches)
# Get the matches with the highest frequency
highest <- names(freq)[freq == max(freq)]
# Each element of highest is the literal pair, so take the first character
first <- substr(highest, 1, 1)
# Print to STDOUT
cat(first)
```
Examples:
```
> (code)
Sally's friends Jimmy and Bobby rummaged for seashells.
L M
> (code)
Sally's friend Bobby searched for seashells.
L
> (code)
Sally's sociable friends Sammy and Bobby searched for fabulous seashells.
L
> (code)
11ss11nn
N S
```
You can [try it online](http://www.r-fiddle.org/#/fiddle?id=gOjnCA3M)!
[Answer]
# Ruby, 60
```
f=->s{(?a..?z).group_by{|l|s.scan(/#{l*2}+/i).size}.max[1]}
p f["Sally's friends Jimmy and Bobby rummaged for seashells."]
```
`group_by` creates a hash (dictionary) structure where the keys are the output of the block and the values are lists of letters that result in each key. In this case, the keys are counts of 2+ runs of a letter, case-insensitive. `max` compares each `[key,value]` tuple lexicographically, so it just finds the maximum key. Then `[1]` returns the value list part of the tuple.
[Answer]
# Python 2, 185 159 153
```
i=input().lower()
d=sorted({l:len(i.split(l+l))for l in map(chr,range(97,123))}.items(),None,lambda x:x[1],1)
print sorted(c for c,k in d if k==d[0][1])
```
Takes input as a quoted string.
[Answer]
# C# 160 Bytes
Where `s` is the input:
```
char? d(string s){s=s.ToUpper();return s.Select((x,i)=>new{y=x,z=i==0?(char?)null:s[i-1]}).Where(x=>x.y==x.z).GroupBy(x=>x.z).OrderBy(x=>x.Count()).Last().Key;}
```
[Answer]
# rs, 146 bytes
```
[^A-Za-z]/
*(.)\1+/\1\1
*(.)(?!\1)/
$/#
+*(.)#(?!.*?\1)/#\1
+*(.)(.*)#(.*)\1/\2#\3\1\1
#/
*(.)(\1*)/\1(_)^^((^^\1\2))
([^_])(_+)(?!_)(?=.*\2_)/
_/
```
[Try it!](http://kirbyfan64.github.io/rs/index.html?script=%5B%5EA-Za-z%5D%2F%0A*(.)%5C1%2B%2F%5C1%5C1%0A*(.)(%3F!%5C1)%2F%0A%24%2F%23%0A%2B*(.)%23(%3F!.*%3F%5C1)%2F%23%5C1%0A%2B*(.)(.*)%23(.*)%5C1%2F%5C2%23%5C3%5C1%5C1%0A%23%2F%0A*(.)(%5C1*)%2F%5C1(_)%5E%5E((%5E%5E%5C1%5C2))%0A(%5B%5E_%5D)(_%2B)(%3F!_)(%3F%3D.*%5C2_)%2F%0A_%2F&input=Sally%27s%20friend%20Bobby%20Bobbb%20searched%20for%20seasheLLs.) Please! It took me forever to make the buttons even with the output box on that page...
Well, this was fairly...crazy. The logic here is kind of weird; I'll only post an explanation if someone asks. (Of course, I also said that for an INTERCAL answer whose explanation was requested...that I never explained... ;)
[Answer]
# JavaScript 156 153
```
var x=prompt(),f={},a=0,o
x.toUpperCase().replace(/([A-Z])\1+/g,function(m,s){m=f[s]=-~f[s]
if(a==m)o.push(s)
if(a<m)a=m,o=[s]})
alert(o.sort().join(""))
```
[Answer]
**Bash + textutils (grep, sed), 111 chars**
```
fold -1<<<$s|uniq -iD|sort -f|uniq -ic|sort -rn|grep -i [A-Z]|sed -n '1h;G;s/\(\s*\S\+\s\)\(.\)\n\1./\2/p'|sort
```
**Bash + awk (instead of sed), 97 chars**
```
fold -1<<<$s|uniq -iD|sort -f|uniq -ic|sort -rn|grep -i [A-Z]|awk '!n{n=$1};n==$1{print $2}'|sort
```
to test it, first assign s
```
s="Sally's friends Jimmy ää and Bobby rummaged ää for seashells."
```
[Answer]
# R, 98 bytes
Very similar to Alex's solution, but uses a substitution rather than a match to determine consecutive letters. Scan is used to get the input and also to split the substitution result on spaces.
```
cat(names(a<-table(scan(,'',t=gsub('([A-z]?)(\\1?)[^A-z]*','\\U\\2 ',scan(,''),T,T))))[a==max(a)])
```
A couple of tests
```
> cat(names(a<-table(scan(,'',t=gsub('([A-z]?)(\\1?)[^A-z]*','\\U\\2 ',scan(,''),T,T))))[a==max(a)])
1: 11 was a race horse, 22 was one too. 11 won one race and 22 one won too.
19:
Read 18 items
Read 2 items
O
> cat(names(a<-table(scan(,'',t=gsub('([A-z]?)(\\1?)[^A-z]*','\\U\\2 ',scan(,''),T,T))))[a==max(a)])
1: Sally's friends Jimmy and Bobby rummaged for seashells.
9:
Read 8 items
Read 5 items
L M
> cat(names(a<-table(scan(,'',t=gsub('([A-z]?)(\\1?)[^A-z]*','\\U\\2 ',scan(,''),T,T))))[a==max(a)])
1: 11ss11nn
2:
Read 1 item
Read 2 items
N S
>
```
]
|
[Question]
[
[F# solutions known inside 140 chars](http://trelford.com/blog/post/Sundays.aspx), and this is a [Rosetta Code](http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month) problem.
Required result on stdout or in a string variable for input year `2014`:
```
2014-01-26 2014-02-23 2014-03-30 2014-04-27 2014-05-25 2014-06-29 2014-07-27 2014-08-31 2014-09-28 2014-10-26 2014-11-30 2014-12-28
```
As it was requested, for 1900:
```
1900-01-28 1900-02-25 1900-03-25 1900-04-29 1900-05-27 1900-06-24 1900-07-29 1900-08-26 1900-09-30 1900-10-28 1900-11-25 1900-12-30
```
And 2000:
```
2000-01-30 2000-02-27 2000-03-26 2000-04-30 2000-05-28 2000-06-25 2000-07-30 2000-08-27 2000-09-24 2000-10-29 2000-11-26 2000-12-31
```
Posed because dates seem to bring out awkwardness in most languages. More than permitting date libraries, I hope to see them! But if external to the base language, declare in the name of the post (e.g. C# + Jon Skeet's NodaTime).
Clarifications:
* Year range 1900 to 3015
* Gregorian calendar
* If it otherwise matters, whatever is conventional for UK/London.
* A program taking a commandline switch or stdin is fine, producing the result to stdout
* A function taking a value for the year and returning a string is also fine.
[Standard loopholes excluded](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny/1070#1070). Looking forward to the APL, J, K solutions, and seeing some new date libraries.
[Answer]
# Ruby, 91+6=97
```
#!ruby -prdate
$_=(Date.new(y=$_.to_i)...Date.new(y+1)).select(&:sunday?).chunk(&:mon).map{|k,v|v[-1]}*' '
```
Works out pretty well. `select(&:sunday?)` is pretty, and surprisingly, `*' '` does all of the formatting by itself.
[Answer]
# Bash 4.x + ncal, 57
If newline separators are OK instead of spaces, then we can remove the `-n` switch and trailing space from the `echo` statement. And I guess it will still work without the shebang, so I removed that too:
```
for i in {01..12};{ echo "$1-$i-`ncal $i $1|tail -c-3`";}
```
Original script (73 bytes):
```
#!/bin/bash
for i in {01..12};{ echo -n "$1-$i-`ncal $i $1|tail -c-3` ";}
```
### Usage:
```
$ bash sundays.sh 2014
2014-01-26
2014-02-23
2014-03-30
2014-04-27
2014-05-25
2014-06-29
2014-07-27
2014-08-31
2014-09-28
2014-10-26
2014-11-30
2014-12-28
$
```
**Note:** Bash versions prior to 4.0 will omit the leading zeroes from the months. This can be fixed with the addition of 5 characters by changing `{01..12}` to ``seq -w 1 12)``. Also, `tail -c-3` might cause problems on some systems where the output of `ncal` includes trailing spaces, but I'm not aware of any that do.
[Answer]
# IBM DFSORT, ~~11~~ 3 lines of 71, 72 or 80 characters
```
OPTION COPY
OUTFIL REPEAT=12,OVERLAY=(5:SEQNUM,2,ZD,5,2,1,8,Y4T,LASTDAYM,TOJUL=Y4T*
,9,7,Y4T,ADDDAYS,+1,TOJUL=Y4T,1:16,7,Y4T,PREVDSUN,TOGREG=Y4T(-),12X)
```
The two answers with columnar output format have stood the test of time. That gives me a "loop", sort of, in that on OUTFIL REPEAT= copies the current record that many times.
Different technique to get to the value, which seems longer but is shorter as I can't work out any unconditional way to deal with the 12th record being in the following year, and making it conditional means including `IFTHEN=(WHEN=`, twice, and some other stuff. Gain on the swings (first of month is simplest way to do it) lose heavily on the roundabouts (particular syntax requirements).
This uses an inbuilt function (all functions in DFSORT are inbuilt) to find the last day of the month. Then adds one day (function) to get to first of following month and uses the PREVDSUN function to get the previous Sunday (which will always be the last Sunday in the previous month, as before).
When turning the year (input) into a valid date, a two-digit sequence number is used for the month, and that value is copied for the day as well, since the starting point does not matter as long as valid, as we are after the last day of the month initially: `5,2` is shorter than `C'01'`.
Here's the detail:
OPTION COPY - copy input file to output
OUTFIL - to allow multiple output files, with different selection and formatting, produce formatted reports. Used in preference to the shorter `INREC` because of the use of `REPEAT=`.
REPEAT=12 - produce 12 copies of each record. In this example, there can be only one input record (unlike the previous version) because of the SEQNUM.
5: - start at column 5 on the record.
SEQNUM,2,ZD - sequence number, defaults to start at one, two digits, "zoned decimal" (for unsigned, which they will be, same as character).
1,8 - copy bytes 1 for length 8 to current location (9). This is because the Y4T need to see that 8, else a different date format will be used.
Y4T - ccyymmdd-format date (due to the 8 immediately in front of it).
LASTDAYM - Last day of Month (also possible of Week, Quarter and Year).
TOJUL= - output date-conversion for date functions (TOJUL is one character less than TOGREG)
9,7 - now that it is 7 long, Y4T is going to be CCYYDDD.
ADDDAYS - adds a number of days, adjusting automatically if goes into following month/year (could also be ADDMONS and ADDYEARS)
PREVDSUN - the Julian date comes in, previous Sunday is located, TOGREG to get the correct output format, with the "-" seperator (could be anything you like as separator)
12X - blanks to clear up the mess which has allowed us to do it in such a short way
The output from the above, for 2014, is:
```
2014-01-26
2014-02-23
2014-03-30
2014-04-27
2014-05-25
2014-06-29
2014-07-27
2014-08-31
2014-09-28
2014-10-26
2014-11-23
2014-12-28
```
Something is required to tell the SORT what to do. There is no default. `OPTION COPY` is the shortest, `SORT FIELDS=COPY` is equivalent but longer.
The work itself it done this time in `OUTFIL` (to allow the use of REPEAT). The working code is arguably any of 160 (2 \* 80), 144 (2 \* 72), 140 (72 + 69), or 138 (70 + 68) (excluding the leading blanks, forced continuation and trailing blanks).
Given that the receiver would have to know what they are doing, I think I can say that the DFSORT code to list the last Sunday of each month for any year from 1900 (will run from year 0001, but I'm avoiding the research as well) up to 9999 (although DFSORT supports years up to 9999, previous solution would not work in year 9999 since the 12th date goes into the following year) can be Tweeted.
Why is the code so long, if there are especially apt inbuilt-functions?
Field-definitions are ephemeral. A field is only defined as a particular location within the data (which is a record) for its immediate use. To put it another way, fields are not defined as such, but are defined for each use and only for use. Date functions need to know which (of many) formats of date are used for the source, and the output must be in a date format, so that has to be specified.
Now that we have a Julian date.... TBC?
---
```
OPTION COPY
INREC OVERLAY=(1,4,C'0201',1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8*
,94:C'1',89:1,4,ZD,ADD,+1,ZD,LENGTH=4,14:C'3',22:C'4',30:C'5',38:C'6',*
46:C'7',54:C'8',62:C'9',69:C'10',77:C'11',85:C'12',127:X,89,8,Y4T,PREV*
DSUN,TOGREG=Y4T(-),116:X,81,8,Y4T,PREVDSUN,TOGREG=Y4T(-),105:X,73,8,Y4*
T,PREVDSUN,TOGREG=Y4T(-),94:X,65,8,Y4T,PREVDSUN,TOGREG=Y4T(-),83:X,57,*
8,Y4T,PREVDSUN,TOGREG=Y4T(-),72:X,49,8,Y4T,PREVDSUN,TOGREG=Y4T(-),61:X*
,41,8,Y4T,PREVDSUN,TOGREG=Y4T(-),50:X,33,8,Y4T,PREVDSUN,TOGREG=Y4T(-),*
39:X,25,8,Y4T,PREVDSUN,TOGREG=Y4T(-),28:X,17,8,Y4T,PREVDSUN,TOGREG=Y4T*
(-),17:X,09,8,Y4T,PREVDSUN,TOGREG=Y4T(-),1:1,8,Y4T,PREVDSUN,TOGREG=Y4T*
(-),11:X,18,120,6X)
```
Needs some `JCL`
```
//LASTSUNG EXEC PGM=SORT
//SYSOUT DD SYSOUT=*
//SORTOUT DD SYSOUT=*
//SYSIN DD *
```
And an input file (another line of JCL and three instream items of data):
```
//SORTIN DD *
2014
1900
2000
```
Produces:
```
2014-01-26 2014-02-23 2014-03-30 2014-04-27 2014-05-25 2014-06-29 2014-07-27 2014-08-31 2014-09-28 2014-10-26 2014-11-30 2014-12-28
1900-01-28 1900-02-25 1900-03-25 1900-04-29 1900-05-27 1900-06-24 1900-07-29 1900-08-26 1900-09-30 1900-10-28 1900-11-25 1900-12-30
2000-01-30 2000-02-27 2000-03-26 2000-04-30 2000-05-28 2000-06-25 2000-07-30 2000-08-27 2000-09-24 2000-10-29 2000-11-26 2000-12-31
```
Will actually work up to the year 9999.
DFSORT is IBM's Mainframe sorting product. Data can be manipulated, but since sorting is key and sorts are often large and long-running, the DFSORT control cards have no looping constructs, so we can't put a SORT into a loop. Makes things a bit long-winded for tasks like Golf.
Why to post the answer, is because DFSORT has a `PREVDday` function. So last Sunday in a month is easy. It is the Sunday previous (PREVDSUN) to the first day of the following month.
It was also fun to do it within one "operand" (OVERLAY), a bit like doing it all within `sprintf` or similar.
Here it is ungolfed:
```
OPTION COPY
INREC OVERLAY=(1,4,C'0201',1,8,1,8,1,8,1,8,1,8,1,8,
1,8,1,8,1,8,1,8,
1,8,94:C'1',89:1,4,ZD,ADD,+1,ZD,LENGTH=4,
14:C'3',22:C'4',30:C'5',38:C'6',46:C'7',54:C'8',
62:C'9',69:C'10',77:C'11',85:C'12',
127:X,89,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
116:X,81,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
105:X,73,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
94:X,65,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
83:X,57,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
72:X,49,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
61:X,41,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
50:X,33,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
39:X,25,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
28:X,17,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
17:X,09,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
1:1,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
11:X,18,120,6X)
```
Whilst not quite abuse, it wouldn't be usual to attempt to cram all this into one OVERLAY, and there is some seemingly unnecessary stuff which is needed to allow it all to go into one OVERLAY. There is some room for golfing, but since it would only remove one line at most, I'm not tempted.
The INREC is processed for each record.
OVERLAY allows the content of an existing record to be changed. If the record is extended beyond its length in the process, that is not a problem.
1,4 is the year coming in. It has a literal of 0201 appended to it, and then the successive 1,8s repeat it 11 times to give one long chuck of 96 bytes,
The 12th year on the extended current record gets 1 added to it, and its month made to 1 (January).
The remaining 10 months are changed to 3 through 11.
Then there are 12, in reverse order (due to OVERLAY) of these type of thing:
```
127:X,89,8,Y4T,PREVDSUN,TOGREG=Y4T(-),
```
The n: is a column-number on the record. The X inserts a blank. 89,8 takes the data from that column/length, Y4T treats it as a CCYYMMDD date, PREVDSUM works out the previous Sunday,TOGREG=Y4T(-) outputs it as a Gregorian CCYY-MM-DD date.
Because you get rubbish if the source and target of a particular part of an OVERLAY overlap destructively, the final `11:X,18,120,6X)` rearranges and masks a bit of mess.
Manuals and papers can be found at: <http://www-01.ibm.com/support/docview.wss?uid=isg3T7000080>, and includes the 900+ page DFSORT Application Programming Guide.
As with all IBM products all manuals are available for free (except an excruciatingly small amount of very expensive ones which only a very small number of people in the world would even pretend to understand).
All DFSORT Control Cards must start with a blank. Column 72 is only used for continuation (any non-blank will do, but \* is conventional). Column 72 is followed by a sequence number area which is ignored, making the each record 80 bytes.
Another couple of solutions to come, maybe.
[Answer]
# Bash, 63 bytes
```
for i in {01..12};{ date -v30d -v${i}m -v2014y -vsun +%Y-%m-%d;}
```
Output:
```
2014-01-26
2014-02-23
2014-03-30
2014-04-27
2014-05-25
2014-06-29
2014-07-27
2014-08-24
2014-09-28
2014-10-26
2014-11-30
2014-12-28
```
[Answer]
# Python 2 - 189 bytes
```
y=input()
for m in range(12):
d=[31-(1322>>m&1),28+(y%400<1or 1>y%4<y%100)][m==1];Y=y-(m<2);Z=Y%100;C=Y/100
while(d+13*((m-2)%12+4)/5+Z+Z/4+C/4-2*C)%7-1:d-=1
print"%d-%02d-%d"%(y,m+1,d),
```
Enter the date via STDIN.
Still a lot more golfing that can be done. The program goes a little overboard, just for fun:
* No imports, in particular not using any built-in date functions
* Uses [Zeller's congruence](https://en.wikipedia.org/wiki/Zeller%27s_congruence) for calculating days of the week
## Notes
* 1322 is a [magic lookup table](https://codegolf.stackexchange.com/a/41742/21487) for determining whether a non-February month has 30 or 31 days
* No `zfill` is needed for years due to the input range, nor days as they will always be over 20
---
# Python 2 - 106 bytes
The not-as-fun solution:
```
from calendar import*
y=input();m=1
while m<13:w,n=monthrange(y,m);print"%d-%02d-%d"%(y,m,n-(n+w)%7),;m+=1
```
`calendar.monthrange` returns two numbers: the weekday the month starts on (`w`) and the number of days in the month (`n`). The solution is a little counterintuitive due to a catch — the weekday returned starts at 0 for *Monday*, not Sunday! However, this is offset by the fact that `n` is 1-based.
[Answer]
# JavaScript (ES6) 155 ~~145~~
**Edit** Fixed timezone problems
Could be shorter if made recursive. Maybe.
```
F=y=>{
for(n=i=o=[];!o[11];)
d=new Date(Date.UTC(y,0,++i)),m=d.getMonth(),
d.getDay()||(m!=n&&o.push(p.toISOString().slice(0,10)),p=d,n=m);
return o.join(' ')
}
```
[Answer]
# JavaScript, ES6, ~~222 219~~ 199 bytes
I did not see any JavaScript answer in the rosetta wiki.
Here we go:
```
S=Y=>{for(l=[],p=new Date(Y,i=0);i<365+!(Y%4);)if(!(d=new Date(Y,0,++i,9)).getDay()){p.getMonth()-d.getMonth()&&l.push(p);p=new Date(d)}return[...l,p].map(x=>x.toISOString().split("T")[0]).join(" ")}
```
This creates a function `S` which returns a string with the desired output. the function also takes care of leap years.
Due to ES6, this only works in a latest Firefox.
*Thanks to apsillers for the tip which got it reduced to 200 bytes*
Find the ungolfed version below as a stack snippet which you can run here itself:
```
S=Y=>{
for(l=[],p=new Date(Y,i=0);i<365+!(Y%4);)
if(!(d=new Date(Y,0,++i,9)).getDay()){
p.getMonth()-d.getMonth()&&l.push(p);
p=new Date(d)
}
return[...l,p].map(x=>x.toISOString().split("T")[0]).join(" ")
}
alert(S(parseInt(prompt())))
```
[Answer]
# Rebol - 120 116 80 79 76
```
d: do join"1-1-"input print collect[for m 2 13 1[d/2: m keep d - d/weekday]]
```
Ungolfed + some annotations:
```
d: do join "1-1-" input ;; golfy way to create Rebol date! datatype 1-Jan-(year)
print collect [
for m 2 13 1 [ ;; loop thru months 2 to 13!
d/2: m ;; move to (1st of) next month
keep d - d/weekday ;; collect/keep last sunday of month
]
]
```
Example of the sunday calculation in Rebol console:
```
>> ; get last sunday of Jan 2014
>> d: 1-1-2014
== 1-Jan-2014
>> d/month: d/month + 1
== 2
>> d
== 1-Feb-2014
>> d/weekday
== 6
>> d - d/weekday
== 26-Jan-2014
>> ; above is last sunday of Jan 2014
>> ; and when pass end of year (ie. month 13!)
>> d/month: 13
== 13
>> d
== 1-Jan-2015
```
[Answer]
# CJam, ~~122~~ 102 bytes
```
30li:X400%){[1387Yb30f+~28I!I4%!I100%e&|g+\]W%{\_2$>7*-\7%7\m1$+}/}fI;]12/W=12,{101+s1>}%]z{X+W%'-*S}/
```
This does not use any form of date library. It can be also still be golfed a lot, I think.
[Test it here.](http://cjam.aditsu.net/)
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM) with [cal](http://dfns.dyalog.com/n_cal.htm) from [dfns](http://dfns.dyalog.com/), 19 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Better late than never!
Prompts for year, returns list of dates in *yyyy m d* format.
```
⎕{⍺⍵,2↑⊢⌿cal⍺⍵}¨⍳12
```
`⎕` prompt for numeric input and let that be the left argument to the
`{` ... `}¨` anonymous function (found below) applied to each of
`⍳12` the numbers from 1 to 12 (the months)
The above anonymous function is as follows:
`⍺⍵,` prepend the left and right arguments (i.e. year and month) to
`2↑` the first two characters of
`⊢⌿` the bottom-most row of
`cal` the calendar for
`⍺⍵` left argument and right argument (year and month)
### TryAPL online:
1. Return to this page after [clicking here](http://tryapl.org/?a=date%u2190%7B%u237A%u2190%AF53799%20%u22C4%20qr%u2190%7B%u2282%u2364%AF1%u22A2%280%2C%u237A%29%u22A4%u2375%7D%20%u22C4%20Z%20F%u21901%20qr%20%u2375+2415020%20%u22C4%20a%u2190%u230A%28Z-1867216.25%29%F736524.25%20%u22C4%20A%u2190Z+%28Z%u2265%u237A+2415021%29%D71+a-%u230Aa%F74%20%u22C4%20B%u2190A+1524%20%u22C4%20C%u2190%u230A%28B-122.1%29%F7365.25%20%u22C4%20D%u2190%u230AC%D7365.25%20%u22C4%20E%u2190%u230A%28B-D%29%F730.6001%20%u22C4%20dd%20df%u21901%20qr%28B-D%29+F-%u230A30.6001%D7E%20%u22C4%20mm%u2190E-1+12%D7E%u226514%20%u22C4%20yyyy%u2190C-4715+mm%3E2%20%u22C4%20part%u219060%2060%201000%20qr%u230A0.5+df%D786400000%20%u22C4%20%u2191%5B%u2395IO-0.5%5Dyyyy%20mm%20dd%2Cpart%7D%20%u22C4%20%20days%u2190%7B%u237A%u219017520902%20%u22C4%20yy%20mm%20dd%20h%20m%20s%20ms%u21907%u2191%u2282%5B%u2373%AF1+%u2374%u2374%u2375%5D%u2375%20%u22C4%20D%u2190dd+%280%2060%2060%201000%u22A5%u2191h%20m%20s%20ms%29%F786400000%20%u22C4%20Y%20M%u2190yy%20mm+%AF1%2012%D7%u2282mm%u22642%20%u22C4%20A%u2190%u230AY%F7100%20%u22C4%20B%u2190%28%u237A%3C0%20100%20100%u22A5%u2191yy%20mm%20dd%29%D7%282-A%29+%u230AA%F74%20%u22C4%20%AF2416544+D+B+%u2283+/%u230A365.25%2030.6%D7Y%20M+4716%201%7D%20%u22C4%20%20cal%u2190%7B%u2395IO%u21901%20%u22C4%20%u237A%u21901%20%u22C4%20cntr%u2190%7B%28%u23080.5%D7+/%u2227%5C%27%20%27%3D%u2375%29%u233D%u2375%7D%20%u22C4%201%3D%u2262%u2375%3A%u237A%20%u2207%7B%20%u22C4%2012%u2265%7C%u2375%3A%u237A%20%u237A%u237A%200%201+0%2012%u22A4%u2375+0%2012%u22A50%20%AF1+2%u2191%u2395TS%20%u22C4%20year%u21904%203%u23740%20%u237A%u237A%A8%u2375%2C%A8%u237312%20%u22C4%20join%u2190%7B%u2349%u2191%28%u2193%u2349%u237A%29%2C%27%20%20%20%27%2C%u2193%u2349%u2375%7D%20%u22C4%20head%u2190cntr%20%AF66%u2191%u2355%u2375%20%u22C4%20head%u236A%2C%5B%u23732%5D%u2191join/year%20%u22C4%20%7D%u2375%20%u22C4%20dys%u2190%27Su%27%20%27Mo%27%20%27Tu%27%20%27We%27%20%27Th%27%20%27Fr%27%20%27Sa%27%20%u22C4%20Q1%u2190%27January%27%20%27February%27%20%27March%20%20%20%20%27%7E%A8%27%20%27%20%u22C4%20Q2%u2190%27April%20%20%27%20%27May%20%20%20%20%20%27%20%27June%20%20%20%20%20%27%7E%A8%27%20%27%20%u22C4%20Q3%u2190%27July%20%20%20%27%20%27August%20%20%27%20%27September%27%7E%A8%27%20%27%20%u22C4%20Q4%u2190%27October%27%20%27November%27%20%27December%20%27%7E%A8%27%20%27%20%u22C4%20months%u2190Q1%2CQ2%2CQ3%2CQ4%20%u22C4%20yyyy%20mm%u2190%u2375%20%u22C4%20day%u2190days%20yyyy%20mm%201%20%u22C4%20mms%20dds%u21902%u21911%u2193%u2193%u2349date%20day+%AF1+%u237331%20%u22C4%20fmts%u21902%200%u2218%u2355%A8%28mm%3Dmms%29/dds%20%u22C4%20pad%u2190%287%7Cday%29%u21910%u2191fmts%20%u22C4%20dmat%u2190%u2191%7B%u237A%2C%27%20%27%2C%u2375%7D/dys%u236A6%207%u237442%u2191pad%2Cfmts%20%u22C4%20head%u2190%28mm%u2283months%29%2C%u237A/%27%20%27%2C%u2355yyyy%20%u22C4%20%u2191%28%u2282cntr%20%AF20%u2191head%29%2C%u2193%7B%28%u2228/%u2375%u2260%27%20%27%29%u233F%u2375%7Ddmat%7D&run) to import `cal` and its dependencies.
2. [Click here](http://tryapl.org/?a=2014%7B%u237A%u2375%2C2%u2191%u22A2%u233Fcal%u237A%u2375%7D%A8%u237312%20%u22C4%201900%7B%u237A%u2375%2C2%u2191%u22A2%u233Fcal%u237A%u2375%7D%A8%u237312%20%u22C4%202000%7B%u237A%u2375%2C2%u2191%u22A2%u233Fcal%u237A%u2375%7D%A8%u237312&run) to run the test cases.
[Answer]
# R, 128 chars
```
P=paste;f=format;a=strptime(P(1:366,scan()),"%j %Y");cat(sort(sapply(split(a,f(a,"%B")),function(x)P(tail(x[f(x,"%u")==7],1)))))
```
With line breaks:
```
P=paste
f=format
a=strptime(P(1:366,scan()),"%j %Y")
cat(sort(sapply(split(a,f(a,"%B")),function(x)P(tail(x[f(x,"%u")==7],1)))))
```
[Answer]
## C# 255
Ungolfed
```
static void Main(string[] a)
{
int y = Int32.Parse(Console.ReadLine());
DateTime d = new DateTime(y, 1, 1);
while (d.Year == y)
{
if (d.DayOfWeek == DayOfWeek.Sunday && d.Day>(DateTime.DaysInMonth(y,d.Month)-7))
Console.WriteLine(d.ToShortDateString());
d = d.AddDays(1);
}
Console.ReadKey();
}
```
Edit: modified to print only the **last** Sunday :)
[Answer]
# q, 67
```
{({{1<>x mod 7}-[;1]/x}')14h$1_til[13]+13h$"D"$(($)x),".01.01"}
```
[Answer]
"Oh, no, him again!"
# Java - ~~259~~ 246 bytes
```
void g(int y){for(int i=;i<12;i++){GregorianCalendar c=new GregorianCalendar(y,i,0);c.set(c.DAY_OF_WEEK,c.SUNDAY);c.set(c.DAY_OF_WEEK_IN_MONTH,-1);System.out.print(y+"-"+String.format("%02d",(c.get(c.MONTH)+1))+"-"+(c.get(c.DAY_OF_MONTH))+" ");}}
```
Ungolfed version:
```
void g(int y){
for (int i = 0; i < 12;i++) {
GregorianCalendar c = new GregorianCalendar(y, i, 0);
c.set(c.DAY_OF_WEEK, c.SUNDAY);
c.set(c.DAY_OF_WEEK_IN_MONTH, -1);
System.out.print(y+"-"+String.format("%02d",(c.get(c.MONTH)+1))+"-"+(c.get(c.DAY_OF_MONTH))+" ");
}
}
```
Usage:
```
import java.util.GregorianCalendar;
import java.util.Scanner;
public class LastSundayInYear {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Year?");
int year = scanner.nextInt();
LastSundayInYear sunday = new LastSundayInYear();
sunday.g(year);
}
void g(int y){
for (int i = -1; ++i < 12;) {
GregorianCalendar c = new GregorianCalendar(y, i, 0);
c.set(c.DAY_OF_WEEK, c.SUNDAY);
c.set(c.DAY_OF_WEEK_IN_MONTH, -1);
System.out.print(y+"-"+String.format("%02d",(c.get(c.MONTH)+1))+"-"+(c.get(c.DAY_OF_MONTH))+" ");
}
}
}
```
Output:
```
2014-01-26 2014-02-23 2014-03-30 2014-04-27 2014-05-25 2014-06-29 2014-07-27 2014-08-31 2014-09-28 2014-10-26 2014-11-30 2014-12-28
```
Yet another "let's put a Java reply just for kicks" answer. Oh well. But, at least, since you bothered to reach this point of my answer, I'll try to bore you some more and explain my reasoning.
The method `g` receives the desired year and, for each month, creates a `GregorianCalendar` object (months go from 0 to 11). Then, the first `c.set` sets the day of the week as a Sunday and the second declares that we want the *last* week of the month - as seen on the [official documentation](https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#DAY_OF_WEEK_IN_MONTH). The `System.out.println` prints out the date of that Sunday (if we were doing this right, the year would be printed as `c.get(c.YEAR)`, but using `y` again shaves off 13 characters), the month has to be formatted to add a leading zero from January to September (and the value is incremented because, well, months in here are represented 0-11) and the day of last Sunday is printed. And this procedure is repeated for the other eleven months.
[Answer]
## C#, 212, 237
```
string x(int y){var s="";var t="";var d=new DateTime(y,1,1);for(;;){if(d.Year!=y){return s;}t=(d.DayOfWeek==DayOfWeek.Sunday)?t=string.Format("{0}-{1}-{2} ",d.Year,d.Month,d.Day):t;s=(d.AddDays(1).Month!=d.Month)?s+=t:s;d=d.AddDays(1);}}
```
With line breaks
```
string x(int y)
{
var s = "";
var t = "";
var d = new DateTime(y,1,1);
for (;;)
{
if (d.Year != y) {
return s;
}
t = (d.DayOfWeek == DayOfWeek.Sunday) ? t = string.Format("{0}-{1}-{2} ", d.Year, d.Month, d.Day) : t;
s=(d.AddDays(1).Month!=d.Month)?s+=t:s;
d=d.AddDays(1);
}
}
```
Output for 2014
```
"2015-1-25 2015-2-22 2015-3-29 2015-4-26 2015-5-31 2015-6-28 2015-7-26 2015-8-30 2015-9-27 2015-10-25 2015-11-29 2015-12-27"
```
[Answer]
# C# 171
Function returning a string.
```
string S(int y){var r="";for(int m=1;m<13;++m){var d=new System.DateTime(y,1,1).AddMonths(m).AddDays(-1);r+=y+string.Format("-{0:00}-{1} ",m,d.Day-d.DayOfWeek);}return r;}
```
**Ungolfed**
```
string S(int y)
{
var r="";
for (int m=1;m<13;++m)
{
var d = new System.DateTime(y, 1, 1).AddMonths(m).AddDays(-1);
r += y + string.Format("-{0:00}-{1} ", m, d.Day - d.DayOfWeek);
}
return r;
}
```
[Answer]
# C# 194
using Linq:
```
string d(int y){return string.Join(" ",Enumerable.Range(1,12).Select(m=>new DateTime(y,m,DateTime.DaysInMonth(y,m))).Select(d=>d.AddDays(-(int)d.DayOfWeek)).Select(d=>d.ToString("yyy-MM-dd")));}
```
**Ungolfed**
```
string d(int y)
{
return string.Join(" ",Enumerable.Range(1,12)
.Select(m => new DateTime(y, m, DateTime.DaysInMonth(y, m)))
.Select(d => d.AddDays(-(int)d.DayOfWeek))
.Select(d => d.ToString("yyy-MM-dd")));
}
```
**Output**
```
2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29
```
[Answer]
# Mathematica - 171
Wrapped in an anonymous function, returns the string
```
StringJoin[Last@#~DateString~{"Year","-","Month","-","Day"," "}&/@GatherBy[Select[DateRange[DateObject[{#}],DateObject[{#+1}]],DayName@#==Sunday&],DateValue[#,"Month"]&]]&
```
First mathematica golf. I feel like it could be substantially reduced.
[Answer]
**VB-192**
```
Function z(y)
For i = 1 To 11
a = 0
s = IIf(i <> 11, DateSerial(y, i + 1, 1), DateSerial(y + 1, 1, 1))
While Weekday(s - a) <> 1
a = a + 1
Wend
r = r + Str(s - a) + " "
Next
z = r
End Function
```
Could be worse ^^
My second and last entry (don't think i can get it smaller)
**142**
```
Function z(y)
Dim m(12)
For i = 1 To 366
s = DateSerial(y, 1, 1) + i
If Weekday(s) = 1 Then m(Month(s)) = s
Next
z = Join(m, " ")
End Function
```
[Answer]
# Ruby 76
Uses a commandline parameter `ruby sundays.rb 1900`. Uses the Date library.
```
require'date';puts (1..12).map{|m|d=Date.new($*[0].to_i,m,-1);d-d.wday}*" "
```
]
|
[Question]
[
### Inspiration
The longest words that can be typed with only the left hand on a standard QWERTY keyboard are "sweaterdresses", "tesseradecades", and "aftercataracts" ([Source: Wikipedia](https://en.wikipedia.org/wiki/Longest_word_in_English#Typed_words)).
### Challenge
Given as input a "keyboard" \$K\$ and a string \$S\$ determine whether \$S\$ can be typed using only the left hand on keyboard \$K\$.
### Input
The keyboard \$K\$ will be provided as a list of 3 *rows*. You may take this input in any reasonable format (eg. a list of 3 strings, a list of 3 lists of characters, etc.), but please do not take the left-hand-side and right-hand-side of the keyboard separately, as that defeats the purpose of the challenge.
You may assume that the input contains only lowercase letters (or only uppercase letters if you wish). Each of the three rows of the keyboard may be of any non-zero size, but each letter from `a-z` will appear only once on the keyboard.
Example 1: [`qwertyuiop`, `asdfghjkl`, `zxcvbnm`]
Example 2: [`qazwsxplkm`, `edcrfv`, `tgbyhnuji`]
The string \$S\$ may also be taken as input in any reasonable format.
### Output
Output a truthy value if the string \$S\$ can be typed using the left hand on the keyboard \$K\$ and a falsey value otherwise.
**For the purposes of this challenge**: A word can be typed with the left hand if it is made up solely of letters appearing in the first half of each row of the keyboard. If a row contains an odd number of letters, the **middle letter is also included** in the first half.
Using the row `asdfghjkl` as an example, the word `gafs` can be typed with the left hand.
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Make your code as short as possible.
### Test Cases
These are formatted as \$K\$, \$S\$ `->` (expected output)
```
[qwertyuiop, asdfghjkl, zxcvbnm], qazg -> true
[qwertyuiop, asdfghjkl, zxcvbnm], qpazg -> false
[p, asdfghjklqwertyuio, zxcvbnm], sxzklkl -> true
[p, asdfghjklqwertyuio, zxcvbnm], b -> false
[qazwsxplkm, edocrfv, tgbyhnuji], bad -> true
[qazwsxplkm, edocrfv, tgbyhnuji], tex -> false
[thequick, brownfx, jmpsvlazydg], brow -> true
[thequick, brownfx, jmpsvlazydg], fox -> false
```
[Answer]
# [Python 3](https://docs.python.org/3/), 48 bytes
Takes as input \$ K \$ and \$ S \$, the keyboard and the target string. \$ K \$ is a taken as a list of lists.
```
lambda K,S:{r.pop(0)for r in K for i in r}>={*S}
```
[Try it online!](https://tio.run/##zZLPboMwDIfve4rcAhOaJu02qXuBHnukPRAghRIIhHT8qfrsrD/Sudq0Sd1l4vLJEjb@bKcebKarl0mutpOKSpFEbB1sXk/mqda19@xLbZhhecXWDGGO0JzfVqfHzXmqTV5ZT3phyBseMN4BKWAACwzAEcgBDdR8F7CQR4hbIAEksAcy4AAUgHLpI@IeiIF3QAAVUPLdJYs30bjnvv/wv2qNK71gLhxd@m9Cf@6B39w9xP27avuxUIVaqJ346Yy39Xbk19PyFVmVrlFK/jF5Sddy/m5pKkG2GYkcadL8qhQly5Oyaf9NylJFSse53SB2PnMrQQKa9Cvy6V3Swbl/ztPSydTX4Qea6/r0hdHdQtWkxtKmDw "Python 3 – Try It Online")
## Explanation
It essentially converts \$ S \$ and the *valid* keyboard characters \$ K' \$ into sets, and returns `True` iff \$ S \$ is a subset of \$ K' \$. To obtain only the first half of each row of \$ K \$, we use the `pop` trick, which is explained in [this](https://codegolf.stackexchange.com/a/204230/88546) answer of mine.
---
The previous answer, where \$ K \$ is taken as a list of strings instead.
# [Python 3](https://docs.python.org/3/), 54 bytes
```
lambda K,S:{*''.join(r[:-~len(r)//2]for r in K)}>={*S}
```
[Try it online!](https://tio.run/##nZDNDsIgEITvPgU3WuNPojcTfQGPHtUDFGhpKVBKW4rRV68lJiYaD6a32ex8M5vVvc2U3A5sfxkEKjFB4Lg47W5zCFe54jIy593yIego4vV6c2XKAAO4BMf4ftjf5qf7oA2XNmLRGVYdNbZvuNJwASCqCUuzvBBh8C5psSzhddQV8imM49lfYKWD@zf26X6HfPfVzhdiTJvC4q9Dke9qp0VRBiMliWFtUDbFfSabnL8gRKZglrpPzGa0anhSBCs2qpPMBZmXum4F8j15PSasJoFMhcLhCQ "Python 3 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 22 21 bytes
```
a:=(-.>.@-:@#$])~&.>/
```
[Try it online!](https://tio.run/##jY1Li8IwAITv/ophXYzCNrrXSEVY8ORp73tI2qSPpO9X2sP@9VpERCmIh7kM880Xjx@UKLgMBF/YgU1xKH5@z6eRM3ft0AM9Ouy4/Pzb/K/oYTtuFgvphRm@4UJhz0jRybLumyjLwStfBWGsDQbrtSJNUPAhIM8AyMPwDt@Jyg7aaHODdu9BYuaYxF1lc6MTSN8rVYs6EH2YNnEEwf3Z/at9Le3svw5l0USehiizLlUWcZJXreFD7wfXbmZ4SahsUowX "J – Try It Online")
*-1 byte thanks to FrownyFrog*
---
Takes input as boxed words, with the string to test at the end.
Reduces the list, set-subtracting `-.` the first half `-.>.@-:@#` of each row `$]` from the string to test.
Check if the result is empty: `a:=`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
-2 thanks to Kevin Cruijssen.
```
ε2ä¬}JÃQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3Fajw0sOran1Otwc@P9/tFJheWpRSWVpZn6Bko5SYnFKWnpGVnYOkF1VkVyWlJerFMtVmFiVDgA "05AB1E – Try It Online")
# Explanation
```
ε For each item of the input list:
2√§ Split into chunks of size 2
(conveniently, the middle character is included in the left half)
¬} Take the head of this list
J Join the output string
à List intersection with the input
Q is the input
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 57 bytes
```
s()(echo ${1:0:(${#1}+1)/2});grep ^[`s $1``s $2``s $3`]*$
```
[Try it online!](https://tio.run/##fY7LUsJAEEX38xW3xixAqozBHVK40q0fYGkxr2RCJg8yeQxBvj2GFCCrbM6i@/S9zZnVvWAVNkWZRyVLsV7T988P2tvZfKaEzuEdg9XzauYdH4LTIpj7y9P8NSpVgZ@vrYUXbM9cjnzZfj96/XBOiNBpLlEvHC7BhLQ6NgqlYhIMHAJxVtQVAWQ@ABjbqDdOKX7x5F9/oh6jA/gZgmIDX6rGz2pj/g@9tzEpU/2@VWV1qOO8ALMyjPQuMeicaHiWYs@6CGRaKQaH3G1u9k2xrktMYqYlToay1rrCJCmUFGXYoIr4QWf1LgZncnJfKUcqrfZ1LBLwMm@z0GGXFrYxrDvIaJxNG2HuSH81@ovR3xl/ "Bash – Try It Online")
The three keyboard rows are passed as arguments, and the input string is passed on stdin.
Output is the exit code (0 for truthy, 1 for falsey).
This can probably be improved with clever golfing.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒH€ZḢFfƑ@
```
A dyadic Link accepting a list of lists of characters on the left and a list of characters on the right which yields `1` if the right may be typed with the left hand or `0` if not.
**[Try it online!](https://tio.run/##y0rNyan8///oJI9HTWuiHu5Y5JZ2bKLD////o9ULy1OLSipLM/ML1HUU1BOLU9LSM7Kyc0CcqorksqS8XPXY/8XlqYklqUUpRanFxanFAA "Jelly – Try It Online")**
### How?
```
ŒH€ZḢFfƑ@ - Link: keys, word
ŒH€ - halve each
Z - transpose
·∏¢ - head
F - flatten
@ - with swapped arguments:
Ƒ - is invariant under?:
f - filter keep
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~42~~ 34 bytes
```
r`(?<-1>.)+(?<=(\w\w)+),
,
D`\w
,$
```
[Try it online!](https://tio.run/##fc29DoMgHATwnedoE03/bdK9H0uTvoSDIIgIIgIK8vLWdjCd3C53v@Qs80Lj5Zi9y8WW2fN2vj4u@WkN96wIRchPOSBAr7IICA7LMgRm/TyK3gB2tOZNKxWkWE1EdzDgxNG@MF/yt2x6Iy4mqaTaRwStX8FFo2QHjFa2nsBzMjd6bAUQTHd3zyLyDRtGUUkgtg@6jtB2xk0Kp5nyX7cv6j5@AA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
r`(?<-1>.)+(?<=(\w\w)+),
,
```
The `r` modifier causes the regex to be processed from right to left, so that the `,` is matched first, before the lookbehind then matches as many pairs of letters as possible. .NET captures each matching pair into a stack of values for capture group `1`. The balancing group then matches once for each value in the stack, thus deleting 1 character from the end of the row for every pair of letters.
```
D`\w
```
Remove all duplicate letters.
```
,$
```
Check that no letters of `S` remain.
[Answer]
# C (GCC) ~~114~~ ~~109~~ ~~108~~ ~~105~~ 102 bytes
-3 bytes ceilingcat
```
i,h,t,r;f(char**k,char*s){for(r=1;*s;++s)for(i=3;i--;)for(h=strlen(k[i]);t=k[i][++h/2];)r*=t!=*s;i=r;}
```
[Try it online!](https://tio.run/##lZDLbtswEEX3@gpGgAHJptE47SoEmw9xjILiQ6L1oEyO/Iy/3RFpuWi5SlYzA95z7wz5suT8dtO4woAtURmvmJ3Paxyqyy/K2MzSFZk7sli43I@a/iR6uSRhqKgD28guq9d6kxOgvq4Xi@rHy4bkdk7hiY6sppZcbyAd3BMQmB6je9tqIRr5mAoDYNrHdDBWYKQ7QNxYKzn8MQP0A@TokqBJU8tTYZgV618bRNHFO0@Wk9fzlYxib8I4DKyZPEaxyh4wDlG5F/Z2lKosnblXpJa/ZwJ9oJl471Ic8zTaCr2htGfOpegVpYrpJkZwfAZJrkniN2uZ7rL7VeGX0t1BWjgN2vSjScqcUGW1rb1jej7yfdG1vt2xcznWVVj8W2B/J5//If8H/vpEpDue6yb4rb7NFlHiuP7BHfumDq9SGG7V3rdQFqeqG7Y6UEzEN36JA3mM8qCSu0HzOrhac@iUV6Tbtnf7hp1Pony8RIFfA5WZAhFKrrdP "C (gcc) – Try It Online")
[Answer]
# Google Sheets, ~~106~~ 99 Bytes
```
=ArrayFormula(1-IsErr(Or(Find(Mid(B1,Row(Offset(A1,0,0,Len(B1))),1),Join(,Left(A:A,Round(Len(A:A)/2
```
Keyboard input is in the range `A1:A3`. The word is input in `B1`. After entering the formula, Sheets will automatically add 7 trailing parentheses.
[](https://i.stack.imgur.com/1e5S3.png)
`Join(,Left(A:A,Round(Len(A:A)/2)))` combines the left-hand side of the keyboard rows into a single string we can search later.
`Mid(B1,Row(Offset(A1,0,0,Len(B1))),1)` pulls each letter of the word, one character at a time.
`Or(Find(Mid(~),Join(~)))` searches for each character in the search string and returns the location of each (a positive integer). If it can't find the character, it returns the `#VALUE!` error. Therefore, `Or(~)` returns either `TRUE` or `#VALUE!`.
`1-IsErr(Or(~))` returns `1` for `TRUE` and `0` for `#VALUE!`.
`ArrayFormula(~)` makes all these pieces work on input and output arrays instead of individual cells. This only matters for joining the input keyboard into a string and pulling out one character at a time from the word.
---
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 51 bytes
```
k=>s=>s.every(c=>k.some(l=>l.length/l.search(c)>2))
```
[Try it online!](https://tio.run/##jZE9b8IwEIZ3fsVt2KoxKh1RsnXp0A4dIRLGcT4vsbGdD6j621MjqpKNSrZknd7nuTu5Er1w0pbGr1qdqimLpjqKXThc9cqeiYzimjvdKIJRjBxVm/tijdwpYWVBJI03lE5eOS@FUxDBYbE7Dcr6c1dqw0C4NMuLqkYGl1H2x7ZJGJzEJYdVDN526j9x85vPBLoAzHN/8Bxw46XGGu8tHhLHmT5MN7jRYN0wUKm0Wc/A58dz0XZVec2KdDb8g7BX40ztC3XqSlkHidVDm40Mqsa4HsXlnObJrXyXP4xnemY/cG/LhlDuDJaeLPftkvJGGIIQxYDh6cOPrffD0zqnlGfavopQIDt8ZoCbcF8YDNqmYZPRKOkTegW/FgBSt06j4qhzks2BhJId5/xKJZTB2@fHOzfCOkVuCkq3i2@6nX4A "JavaScript (Node.js) – Try It Online")
Input keyboard as an array of three strings. Input the word as an array of characters.
[Answer]
# x86 32-bit machine code: ~~34~~ 31 bytes
Strategy: build a bitmap of left-hand keys with bit test-and-set ([`bts`](https://www.felixcloutier.com/x86/bts)), then loop over the input string and check against that bitmap (`bt`). 386 `bt*` instructions with a register destination mask the bit-index like shifts do, so we can use ASCII characters directly as bit indices. (0x61 .. 0x7a)
Inputs:
* EDI: `const char *str` (0-terminated C string)
* ESI: points at rows serialized into 3 back-to-back explicit-length strings in a buffer. 3x { dword length, char[] }, no indirection just flat byte stream concatenated to be loaded with lodsd / lodsb. Asm wrapper to do this conversion from an array of 3x `char*` included with the test harness on TIO.
Output: AL=first non-left-hand character (non-zero=falsy), or zero=truthy (the terminator). Assembly language can just as easily jump on non-zero as on zero [so this is justified](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey#comment9441_2194). An alternate version of this took an explicit-length string and returned 0 or 1 in the CF flag.
Clobbers: all GP registers except ESP
```
1 tlh:
2 00000000 31DB xor ebx, ebx ; left hand keys bitmap
3 00000002 8D4B03 lea ecx, [ebx + 3]
4 .rows:
5 00000005 AD lodsd ; length. Upper bytes zero because each letter can appear at most once.
6 00000006 8D2C06 lea ebp, [esi + eax]
7 00000009 92 xchg edx, eax
8 .keys: ; do{
9 0000000A AC lodsb
10 0000000B 0FABC3 bts ebx, eax ; bmap |= 1<<(c & 31)
11 0000000E 4A dec edx
12 0000000F 4A dec edx
13 00000010 7FF8 jg .keys ; while(len-=2 > 0); // handles the len=0 case where --len becomes negative
14 00000012 89EE mov esi, ebp ; skip 2nd half of string
15 00000014 E2EF loop .rows
16
17 ;;; If the input string indexes any bit in EBX that isn't set, it's not left-hand typeable
18 00000016 89FE mov esi, edi
19 .chars: ; do{
20 00000018 AC lodsb
21 00000019 0FA3C3 bt ebx, eax
22 0000001C 72FA jc .chars
23 .exit:
24 ; non-zero AL means we found a non-left-hand character.
25 ; zero means we found the terminating 0. ASCII 'a' = 0x61 so our bitmap always has bit 0 = 0
26 0000001E C3 ret
```
TODO:
* A better row input format to save instructions in the input code? (When I designed this format, I forgot about having to skip over the right half of a row that I wasn't going to read. `lea ebp, [start + len]` + `mov` was a bugfix. It would be nice to at least not need that many regs.)
* Maybe start with an all-1 bitmap and clear bits for right-hand keys? But that introduces a corner case for a row of length 1 which has no right-hand keys. Otherwise it might allow efficient looping to the end of a 0-terminated string.
I used the nice C test harness from [@Noodle9's answer](https://codegolf.stackexchange.com/questions/204581/can-i-type-this-with-my-left-hand/204604#204604). This is 32-bit asm so it would be a double pain to get something runnable on TIO.run with NASM. (You can use FASM to make a 32-bit executable directly, without a separate linker invocation, but I think that doesn't link libc. You could I guess inline a simple strlen, or hard-code some data structures to at least exit with a 0 / 1 exit status...) I put the source + asm wrapper (to adapt to a normal C calling convention), and C test harness itself [on TIO](https://tio.run/##pVZtb9s2EP7OX3FI0cVpbNdvKLIoKdZl/RCgGAZsAwZkRkCJlMVYElWSiuV0/e3ZHfViOUmxZDWMRKTueHfP89zR3FqZhel2lHOb3d@7NDllgJ9KG/wrw2pIf2DvE0AqYwcJzwWs5dZCqFzGC@@XSk5@EfpdkeMxzJdsbPTG1uemWljx@Lh85ZIxwJ9FIQ2EWyct3EmjIZQRL60EyaMEzZzD1xHPgaMhN8AdZNo60Hkkx/34YUHxrcL4klfL/ivhU@PV8XTpgxtdYh1lEdDBhw4oXBUlq8YULb23TUzrPcWNMRV@Co8/AQj9hbUrKjfsVqGzHai8au1DxA7@OYfp2dkggh9gPj3qPISM6qjdzg0mVkffRdwkKpWD0QhxhPcwOQoA3r71/KQIpEskIXw@wQKxtk0ijYTaGOHVGZrkcsWdupU@SqZvKaZVRH3RxrBrVcAMkUp4GoOOwTqj8lVDqkY7zzJjQRDAZeyjqrwoXWOICyErjMXzLQkG1/Dx57/QDklUlpC30g1BuUPMRzuvsZHXmNsi2WH6ODuh2DhKuHlExI6EHQGhgx74fusGwa0PYGNZKVdLNMDw@cjL78MnyCTPLWwkxF4n3L/c5UbePEJZjhtf7/fAibBAk0zliDJCMUGpf/j94vISDvkhnMOkejcFq0GXpukl4OmGI8UJ990FE7LyEYx0jDFZ4Xk5QYs0MsZTtcph@o6tUh3yFLCNrzeGmsSw3vNpB0@odQrxINI5dg/VAG/WobiaL4fQ38Pzay0WpU1IDTsKfItJW7CgiXltHTeOBfX/075b1VtY1VsggXVzlSFxiidOZye9GEL5GG3SpUprMAV3nIovI1eimGOjM5jDRSM1u5tgewMsAG4aHQ7BZ0lkoPxiZbBk7KlQcyNaZY8JXVT2aS8hkt0VdcUxnCwf7dfzJqzeLJYseNJpOttZPMIk4mnaUNrydAlCCeqNKJHRGuVkKHF88oxnMnfYw7grvTPK6o9EkWqQbRSg07DRpnXzUvFBqVtxpvTbpcyyLb2o6XB6f0gHfuCikutJ3Ss86rWTkYXftmHnlsksKrZ1k2e@8/1s94QRkS1lQ@DilucREfLxl0t/nMoj6MQTZUXD5rxu3ZTGYMMQYw80Q2gfT2cPGSK5dkBjX8CT8xuvGZxCOHrxdL3FIfUboq0xsY1yCWhM22Cpjco8zTi4IrSBp8/Dji2xV6nlcCzQ3PvwyfsiEg7dhjxlzSl3uKxr4UI86IiGNdVb2P4Cgeqvit20qBuU7RqTEEHS6ptMoYYm1cmE1ZKlxn8D62tK7mqJY@fLweeNNG5bKl0cDOGAWxGvkpt1Sou7KroN8@zga9D3Brvnzu9WZPu5oAe0vMfLySvgp1@1xivqx0O6FSxGaQWM3wt/CeCPkgDoEnF@Gy9@hKnAkeuw6/HSG7NXKJO0FBLOrBNKj5P3@1sEO20yP/J6w/BZwy9gr4SMVY7R9oYqI9QyrvLBEdQXzc7zf6H38Ij/gNATjY3j4sHBawv@@3eOJk3oybJ7nO4eZ8uj2hUHwoAqUOeTANTZLIDjY9VWUvceXscYOh7UrsM2H9Ue8SCD0Xt4LWDwWhz5NDprfMTv@fl0pBrHr9@Aa9bUug9Th95TePWRat1tdbdOa3jDZyA160E162E1@w6wZsMupxfBNXsRXvOdNja2KtJ1RjVLoSMT39KjW4XbJC9v1JN4te4hF95YVs9Aa95Da95Da/4daM2HXUYvQmv@IrQWTbk4vT@XKlp7feAP1jyu6PEmK@xtyu@2YvUkWq07uZB9rJ8D16IH16IH1@I74FoMu5ReBNfiG3B9Zff/Ag "Assembly (nasm, x64, Linux) – Try It Online") even though you can't actually try it there.
```
$ nasm -f elf32 -l/dev/stdout type-left-hand.asm &&
gcc -Wall -fno-pie -no-pie -m32 type-left-hand.[co] &&
./a.out
qwertyuiop asdfghjkl zxcvbnm
qazg -> 1 (1)
qpazg -> 0 (1)
p asdfghjklqwertyuio zxcvbnm
sxzklkl -> 1 (1)
b -> 0 (1)
qazwsxplkm edocrfv tgbyhnuji
bad -> 1 (1)
tex -> 0 (1)
thequick brownfx jmpsvlazydg
brow -> 1 (1)
fox -> 0 (1)
```
`0 / 1 (1)` means *left-hand typeable (matches the correct result)*
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~116~~ \$\cdots\$ ~~108~~ 104 bytes
Saved 4 bytes thanks to [rtpax](https://codegolf.stackexchange.com/users/85545/rtpax)!!!
Saved 4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
c;p;l;r;i;f(char**k,char*s){for(r=1;*s;++s)for(i=3;i--;r&=l>p*2)for(l=p=0;c=k[i][l];++l)p=c-*s?p:l;c=r;}
```
[Try it online!](https://tio.run/##pZLtboIwGIX/7yoaEhdASLTwa13dhTiyYPmqVKgtKmq8dkcREDeXYWya8Jae0573SYkdE3I@E8QRQwJRFOkk8YVpplb9lcYxyoUu8BSZEo3H0lBLih1EbRuJV8xm3IT1T4Y5niCC0zn15syrxMzgmNim/OBvrNoQ6HRe@TTTDXB8AdWobwDpVxHKYu4BDI7aeheKYr@hOdcsoPkyiOJkmTK1OJRku8hW2gn1zEDeuP1DrKRrropGyAXNikjXRhLU8zOrJM2lE68rp9cSesbFWveaFYBWjQH6DhEYj2mbXg21KaurI/1itdo8tD3iRwJ7BkYB0EeBUcfo1FVZTYynNm2Mp1@IYNPlLZqO2H@MWrssDym7IF0MYAR7kGCPEnwCE7S6TA@BggNJOdf3sJMlZ@lKdRsGORHRVpVFvNgn2WZJ75Jq7Qs/qMVhOYCT0@Pk9Dg5T3ByrC7RQ5ycgZzcptEiCdcbStL6TYh8l0WlKpcrLrfMP@yD@C6n1q4sSh/lQ0C5PVBuD5T7BCjX6iI9BMr9A9Tp/A0 "C (gcc) – Try It Online")
Takes the keyboard as an array of strings and the word as a string.
Returns \$1\$ for true and \$0\$ otherwise.
[Answer]
# Haskell, 69 bytes
```
x l=take(length l`div`2)l;l k s=all(\c->elem c$foldl(++)[]$map x k)s
```
Use (in `ghci`):
```
$ let kbd = ["qwertyuiop","asdfghjkl;","zxcvbnm,./"]
$ l kbd "stewardesses"
=> True
$ l kbd "joker"
=> False
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~56~~ 63 bytes
```
k=>s=>s.All(c=>k.Any(l=>(uint)l.IndexOf(c)/(float)l.Length<.5))
```
[Try it online!](https://tio.run/##nZIxa8MwEIXn@lccpoMEjjt1SmwIpYWUQIcOHUIGWZZsRYqUWHLi2Pi3p1YSCk02g4Z7uvvuCZ6onVArzh@1prPFu663rCKZYjPrKqGLNIJL56oiyIxRaQockrNMUjuceK4Uokkq47k@IZWkqBbaYRUvdM6aL44ofkFcGeLvlkwXrpzFrxifp0FwIBU4Zp2FBDQ7rtZBFzyhSwUdhPsjq9ypFmYXRhASm/Oi3EjlRdvQQ6a3IfSD2JO2CHE0Ct09sv@Rv00PrG1aqYad4@js/sWkPdpmp@TWj7Lc0IoffOmK7FTqeiNuHMlHko41d6Qr2b4WVPrhrDJHzRtfbrY7e1CkPeXFzXPojUS5GUyDfhpwUzFCS0A@dCQjsBiEvsaPfe5vRlujWPxTCceWQjP0HK6678vHiz@N0MgbRCBxv46gsz1MUug4khhZ3Id4GvTnXw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~72~~ 71 bytes
```
function(k,s)all(t(sapply(k,function(x)match(s,x,0)))<(lengths(k)+2)/2)
```
[Try it online!](https://tio.run/##jc@xEoIwDAbgWR6jU3L21GPWZ/EKFMHWgjQq@PL111MGJodvSPO3SYfkbS3HxoTqkOpbKKXtAjkd2XhPQtH0vZ9wMPdGvhgpG4p61Dtm3pO34SRNJMfrnLc5J2enojNDtfFWxA7x4NsolK1KUlel1QMsDCAwwQ1a6KBXrD9hgyJCBTWcoIEzOPC/4BPFCCXcoYAAF8WczR@k5V76u9B7zvPz/l/xfnElvQA "R – Try It Online")
[Answer]
# JavaScript (ES6), 53 bytes
Takes input as `(keyboard)(word)`. Returns a Boolean value.
```
k=>w=>!w.match(`[${k.map(r=>r.slice(-r.length/2))}]`)
```
[Try it online!](https://tio.run/##ndHNasQgEAfwe5/CSg8Kuwn0nn2RZWGNUZNo1Kj5LH32NDZQaBc2obcRmZ//GWvSE09dZcNZm4ItPFtkdhmyy@uQNCTQEt2vbx9yrS1y2cUlXlWUobNLFNMilOk7xp@3O16o0d4oligjEEdX2A7MhamrjIUnAIkvuChrqeJhHmmf6wbeMIItmQUEAGAM0hQE17GX/0p2ozaJE@Ufqd/CD/yX8uMs1frCk1AHpTzOBp6HWlcw@NEq2cRuVlDH@1gFkU@l7uoKgm@KFBDsbOqYFNgI90KFkrVdRWVsz50ZNB9jWTfW94rMUyG2@darne87KHHzEGr5Ag "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
⬤η⊙θ№…λ⊘⊕Lλι
```
[Try it online!](https://tio.run/##FYixDsIgFEV/hTA9E/wCp6aLJg7uTQekT0BfoVCK0p9HepZ77lFGRuUl1fqI1iXoiMAI1rkCQbDeb631RRH2xi9Agl0lZZzg5lTEGV1qfkenkwE6NQSzx1xqHQYevhhT2axfuGBcrtNLm/eHjrP/VH66mY/Ng9w1H@s50x8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list and a string. Output is a Charcoal boolean, i.e. `-` for true, nothing for false. Explanation:
```
η Input S
⬤ All characters
θ Input `K`
‚äô Any row
λ Current row
… Truncated to
⊘⊕Lλ Half its length rounded up
№ ι Contains input character
Implicitly print
```
[Answer]
# [Python 3](https://docs.python.org/3/), 53 bytes
```
lambda k,w:all(max(map(r.find,w))<len(r)/2for r in k)
```
**[Try it online!](https://tio.run/##nZHdasQgEIXv@xTeRcF2ob0pS9sXaffCxJgYf2NMNHn5NLNbChsolAwI5@D5ZsTxc2ydfXn1YRXvX6tmpuQMKZrOTGtsWN6Ox@FJSMtpIuRN1xYHcnoWLqCApEWKrKAVRQksfkA/hT@LPtUhzqN0vqCoYAMXTdspDWbJ1VRaU1w23bOlKQj9J9l7iP/B3cd/u@wnDnlRemt3CC73b2VLGrLXykCy5lUQE6jYlHNrx07eKMYPcbHOOy62dT/KSkG2DC5ZkUF2xg@TZsvMb78DV8dI4e5GkvNV@iBtxLDnLfL4sYHi6ghZvwE "Python 3.8 – Try It Online")**
[Answer]
# [Python 2](https://docs.python.org/2/), ~~57~~ 55 bytes
*-2 bytes thanks to @ovs !*
```
lambda k,s:all(t.find(c)*2<len(t)for t in k for c in s)
```
[Try it online!](https://tio.run/##jZBNkoMgEIX3OUUXK52QLLJMjXMRx6qgghIRCY2JenkHYn7cZXbd9Pdev8aMru70YRbJ76xYm5cMGopHplTk9kLqMirir8O34jpysegsOJAaGghlEUqMZ9mazjrAETfhWUnN75MR9@hKqY8bAKTANN64hQRaZiJ01g@tNPTO79Eo6SKy@yFx7HFGc1pQ9HDqFi4iaQYkhlcGfGooiTMvaQJ814XutexZJECc7TnxM8uxV87PRORvDeuMldr5w0PMkIE@GN@lZHtamiRZvE5bkpE5vfjSjb3s/AkMS1HV50ZRmIbimus2o3BhUwW7HwhrN//AzYMXTKEXrLmXeC3AYWpUo94rPirylb1Pd8PBqKalwMvCiisFV@VjrfuzDCwrV@E/wI4PK2tX80svC/@due1uWgwUzq3Bq2LTWFbZ8vw2/4iL7u3@Bw "Python 2 – Try It Online")
]
|
[Question]
[
# The challenge
Given a positive integer `N`, compute the proportion of `N`-step walks on a plane that don't intersect themselves.
Each step can have any of the `4` possible directions North, East, South, West.
A walk intersects itself if it visits a previously visited point.
# Examples
* `N=1`: a single-step walk obviously doesn't intersect itself. So the result is `1`.
* `N=2`: given the first step in any direction, there are `3` possible directions that avoid intersection, and one that goes back to the origin, causing intersection. So the result is `3/4 = 0.75`.
* `N=3`: if the second step doesn't cause intersection, which happens `3/4` of the times, the third step will not cause intersection with probability again `3/4`. So the result is `(3/4)^2 = 0.5625`.
* `N=4`: things become more interesting because proper loops can be formed. A similar computation as above gives `(3/4)^3 - 8/4^4 = 0.390625`, where the second term accounts for the `8` proper loops out of the `4^4` possible paths (these are not excluded by the first term).
# Additional rules
* Output can be floating-point, fraction, or numerator and denominator.
* If floating point, the result should be accurate up to at least the fourth decimal.
* Input and output are [flexible](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) as usual. [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Shortest code in bytes wins.
# Test cases
```
1 -> 1
2 -> 0.75
3 -> 0.5625
4 -> 0.390625
5 -> 0.27734375
6 -> 0.1904296875
7 -> 0.132568359375
8 -> 0.09027099609375
9 -> 0.0620574951171875
10 -> 0.042057037353515625
11 -> 0.02867984771728515625
12 -> 0.0193674564361572265625
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~153 149 144 140 126 118~~ 92 bytes
Here we represent the 2d coordinates as a single integer: We start at `0`, and the directions `N,E,S,W` correspond to adding `+n,+1,-n,-1` where `n` is the input (we could also use any larger number). Using this we generate all possible paths, and then just check for duplicate numbers in those paths.
Thanks @H.PWiz for -26 bytes!
```
g n|a<-scanl(+)0<$>mapM(\_->[1,-1,n,-n])[1..n]=sum[1|x<-a,[b|b<-x,c<-x,b==c]==x]/sum[1|x<-a]
```
[Try it online!](https://tio.run/##RY0xDgIhEAC/QmEBEU7pLHbvB/cCJBcgehK5DRFNKPg7SmUz1WTm4crzllLvG6PmQJXgKPGjOMNh3l1e@HVVs9FSaUlSkRVGTxNZLJ/d6FZBOWl886CqDAMeMVjEak9/w/bdRWLIRnBl@RXpzfk9xcylQIBN/Gaje7GifwE "Haskell – Try It Online")
### Explanation
```
--generate all possible paths
a<-scanl(+)0<$>mapM(\_->[1,-1,n,-n])[1..n]
--count the non-self intersecting paths, compute the ratio to the total
g n|a<- ... =sum[1|x<-a,[b|b<-x,c<-x,b==c]==x]/sum[1|x<-a]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 89 bytes
```
f=lambda n,S=[0]:n>=len(S)and sum(f(n,S+[S[-1]+d])for d in[-n,-1,1,n])/4.or len(set(S))>n
```
[Try it online!](https://tio.run/##FY0xDoMwEATr8IorbXFO4oQqkvkEpeXCkbGCBAsCp8jrnaPd3ZndfuWz4lFrdnNc3ikSeHD@Hl7o3TxCDToi0fFdVFZStX7wxoY2BZ3XnRJN8AZsLFtG0LfuKunJHWMRVveo5w6yI//kjq2om8u2TyhyRSLVTf0D "Python 2 – Try It Online")
A recursive approach inspired by [flawr's lovely Haskell answer](https://codegolf.stackexchange.com/a/197382/69880). Outputs a float.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 12 bytes
```
‘ı×Ƭ¤ṗÄQƑ€Æm
```
[Try it online!](https://tio.run/##ATkAxv9qZWxsef//4oCYxLHDl8aswqThuZfDhFHGkeKCrMOGbf874oCcIC0@IOKAnTvDhwrDh@KCrFn//zg "Jelly – Try It Online")
A monadic link taking `N` as its argument and returning a float representing the proportion of non-self-intersecting walks of length `N`. Generates all walks of that length and then checks for intersections, using complex numbers to represent the 2D coordinates.
Thanks to @LuisMendo for saving a byte, and @Mr.XCoder for saving 2 more!
## Explanation
```
‘ | Increment by 1
¤ | Following as a nilad
ı | - 1i
×Ƭ | - Multiply (by 1i) until no new values, returning all intermediate values
ṗ | Cartesian power (with N+1)
Ä | Cumulative sums of innermost lists
QƑ€ | Check whether each list is invariant when uniquified
Æm | Arithmetic mean
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
Done with a lot of help from [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) in [MATL CHATL](https://chat.stackexchange.com/rooms/39466/matl-chatl).
```
QJ4:!^Z^!YsSdAYm
```
[Try it at MATL Online!](https://matl.io/?code=QJ4%3A%21%5EZ%5E%21YsSdAYm&inputs=4&version=22.1.0)
Alternative:
```
Q8BPZFZ^!YsSdAYm
```
[Try it at MATL Online!](https://matl.io/?code=Q8BPZFZ%5E%21YsSdAYm&inputs=4&version=22.1.0)
## Explanation
```
QJ4:!^Z^!YsSdAYm – Full program. Receives an integer N as input.
4: – Range 1...4.
J !^ – Raise J (imaginary unit) to those powers*. Yields j, -1, -j, 1.
Q Z^ – Cartesian power N+1.
!Ys – Transpose and take the cumulative sums.
Sd – Sort and get the deltas (consecutive differences).
A – All. For each column, if it contains 0, then 0, else 1.
Ym – Arithmetic mean.
```
(\*): `!` is needed there because [Octave is weird](https://chat.stackexchange.com/transcript/message/53024041#53024041).
[Answer]
# [R](https://www.r-project.org/) + gtools, ~~111~~ 88 bytes
```
mean(!apply(diffinv(t(expand.grid(rep(list(c(1,-1,n<-scan(),-n)),n)))),2,anyDuplicated))
```
[Try it online!](https://tio.run/##Dcs9CoAwDEDhs7glkAoKbo5eJPRHAjWEtoqevnZ43/ZK71dkhYnN8gdBUhJ9oEF8jTXMZ5EAJRpkqQ08LOQW0t1VPyYkp4g0Gq7E@h23ZfHcYkDsW/8B "R – Try It Online")
[Test suite](https://tio.run/##VY7NCsIwEITvfYo1UNjARqgnKfXmY3gJ@ZFAXUOTSoP47DHFk4cZhjl8M0v1MCnwK5scnoybhHeXjOa/Vm714TTjQcc4F7TB@8AvzOi2qNke70uwuLiIc0gZDQ6kBuJJ7SCUpFhKamp@Is3lusY5GJ2dlbJ@upYwxSVw9ih6O0KfBEHZHwzjmSD9Vgv5BkguwgXEjYWsXw)
Reads `N` from STDIN and implicitly prints the answer as a float.
Thanks to @LuisMendo for a fab challenge and saving 6 bytes! Thanks to @Mr.XCoder for saving 3 bytes (indirectly via my Jelly answer). Thanks to @Giuseppe for saving 10 bytes with an excellent suggestion partially inspired by @flawr’s Haskell answer!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
Uses [flawr's method](https://codegolf.stackexchange.com/a/197382/59487) of reducing to 1D.
```
1‚D(«Iãε.¥DÙQ}ÅA
```
[Try it online!](https://tio.run/##ASMA3P9vc2FiaWX//zHigJpEKMKrScOjzrUuwqVEw5lRfcOFQf//NQ "05AB1E – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 69 bytes
```
(%[])
-1%_=1
n%l=sum[(n-1)%map(+d)(0:l)|d<-[1,-1,pi,-pi],all(/=0)l]/4
```
[Try it online!](https://tio.run/##DctBDsIgEADAe1/RgyS7EdqSeDAG/IEvQNKQVpR0IRvRm28Xnfs8Qt1uRC3aawPhPHZKi9nqrgiy9Z0dFKVR5MCwXxGmE@FnNcppqbTkJBUnLwMRjHZC8uOh5ZBKb/v/uMw9P1N5AURKDBKtMRHN7uz0MBw9tu8SKdxrUwvzDw "Haskell – Try It Online")
Uses a similar idea to [flawr's solution](https://codegolf.stackexchange.com/a/197382/20260) of storing 2D coordinates as 1D values: \$(x,y)\$ is represented as \$x+\pi y\$. Maybe this is unfair because finite precision means that eventually two different coordinates will be represented as the same value. This will take an extremely large input though because `toRational pi` equals `884279719003555 % 281474976710656`.
Instead of updating the position after each move, we `map` the position change onto the list of previously visited coordinates. That way, we can detect a collision by seeing a 0 among the previous coordinates. Because we only check a coordinate the loop after it's added, one extra loop is done, for `n+1` total.
[Answer]
# [Python 3](https://docs.python.org/3/), 76 bytes
```
f=lambda n,p=0,*S:n<1or sum(f(n-1,q,p,*S)for q in{p-1,p+1,p-1j,p+1j}-{*S})/4
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIU@nwNZARyvYKs/GML9Iobg0VyNNI0/XUKdQpwAorJkGFCxUyMyrLgCKFWgDsa5hFoiRVatbrRVcq6lv8h@kJg@oRqEoMS89VcNQx1LTiouzoCgzr0QjT0cBaJ6m5n8A "Python 3 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~56~~ 52 bytes
```
Nθ≔⁰η⊞υ⟦⁰⟧FυFΦ⁺⟦¹θ±¹±θ⟧§ι±¹¬№ικ¿⁼Lιθ≦⊕η⊞υ⁺ι⟦κ⟧I∕ηX⁴θ
```
[Try it online!](https://tio.run/##TY5NSwMxEIbv/oo5TiBCC715KlVhQUvvyx7i7nQTmiZNMqn@@zi7qHiar2dentGaPEbjW@vCrfKxXj8oY1JPD/tS3Bxwo8HKdKrFYtXQbwaZzjEDVgVrfXWe5efka8F@qyFpONJsmHCr/tqkBg177sJEX@j@EWphIuMh1sDL5SIrcGfAl1SNL/hGYWaLTrgkl3dz@zHrwpjpSoFpWh2BfCH4FV11JK6/DGrxz07iD6YwPru7mwitMPFTxHdrsECt7drj3X8D "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `N`.
```
≔⁰η
```
Initialise the number of paths to `0`.
```
⊞υ⟦⁰⟧
```
Start off with a path with no steps.
```
Fυ
```
Perform a breadth-first search of the paths.
```
FΦ⁺⟦¹θ±¹±θ⟧§ι±¹¬№ικ
```
Take @flawr's list `1, N, -1, -N` and add the last position on the current path to each value. Filter out results that already appear in that path, and loop over the remaining self-avoiding values.
```
¿⁼Lιθ
```
If this path already has `N` steps...
```
≦⊕η
```
... then increment the count of found paths.
```
⊞υ⁺ι⟦κ⟧
```
... otherwise construct a new path and add it to the search list.
```
I∕ηX⁴θ
```
Print the proportion of self-avoiding paths.
]
|
[Question]
[
A [superabundant number](https://en.wikipedia.org/wiki/Superabundant_number) is an integer *n* that sets a new upper bound for its ratio with the [divisor sum function](https://en.wikipedia.org/wiki/Divisor_function) σ. In other words, *n* is superabundant if and only if, for all positive integers *x* that are less than *n*:
$$\frac{\sigma(n)}n>\frac{\sigma(x)}x$$
For a few of the values:
```
n σ(n) σ(n)/n superabundant
1 1 1.0000 yes
2 3 1.5000 yes
3 4 1.3333 no
4 7 1.7500 yes
5 6 1.2000 no
6 12 2.0000 yes
7 8 1.1429 no
8 15 1.8750 no
9 13 1.4444 no
```
A longer list of these (for test cases) can be found at [OEIS A004394](https://oeis.org/A004394).
One *highly recommended* negative test case (if your interpreter can handle it) is 360360, because it ties with the last superabundant number.
# Challenge
Your program should take in a single positive integer, and output a truthy or falsey value representing whether that integer is superabundant.
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Æs÷$ÞṪ=
```
[Try it online!](https://tio.run/##AS8A0P9qZWxsef//w4Zzw7ckw57huao9/zEwMMK1LMOHJGrigJwgLT4g4oCdwrXigqxZ/w "Jelly – Try It Online")
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Æs÷$ÐṀ⁼W
```
[Try it online!](https://tio.run/##y0rNyan8//9wW/Hh7SqHJzzc2fCocU/4////jUwA "Jelly – Try It Online")
[Test Suite!](https://tio.run/##ATIAzf9qZWxsef//w4Zzw7ckw5DhuYDigbxX/zEwMMK1LMOHJGrigJwgLT4g4oCdwrXigqxZ/w "Jelly – Try It Online")
### Explanation
```
Æs÷$ÐṀ⁼W ~ Full program (monadic).
ÐṀ ~ Keep the elements with maximal link value (auto-rangifies).
Æs ~ Divisor sum.
÷$ ~ Divide by the current element.
⁼W ~ Check equality with the input wrapped into a singleton.
~ (for integers like 360360)
```
[Answer]
# [Haskell](https://www.haskell.org/), 73 bytes
*-1 byte thanks to Mr. Xcoder. -7 bytes thanks to Laikoni.*
```
r=read.show
s n=sum[r i|i<-[1..n],n`mod`i<1]/r n
f n=all((s n>=).s)[1..n]
```
[Try it online!](https://tio.run/##JcqxDkAwEADQvV9xg4GEE4tJ/YhINEFctFe5Ixb/XhJvfpvTffE@JbGyuBl1i7dRYKtXGATooa4aGkQeS55CnCfqmrEWYLN@yXmf59/ubYFa/C8FRwwWDiE@IYMV2vQC "Haskell – Try It Online")
Haskell's type system isn't very golfy...
[Answer]
# [Haskell](https://www.haskell.org/), ~~64~~ ~~63~~ 61 bytes
**-1** byte thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).
**-2** bytes thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn).
```
a!x=a*sum[y|y<-[1..x],mod x y<1]
f n=and[x!n>n!x|x<-[1..n-1]]
```
[Try it online!](https://tio.run/##JcpBCoMwEAXQfU/xA11JlWRveoOeIAxlQIOhyVTUwgS8e0rpW7@F99ecc2ts1HO3f0qoZx374IZB6VbeExR1dHSJEM8yBTVyF6On/pP0jqgVTgKPwuvjiXVLcuCKmPIxb4j4PWetpfYF "Haskell – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 41 bytes
```
@(n)([~,p]=max((x=1:n)*~mod(x,x')./x))==n
```
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI09TI7pOpyDWNjexQkOjwtbQKk9Tqy43P0WjQqdCXVNPv0JT09Y2739afpFCHlDWkksBCNKA@rhS81L@AwA)
### Explanation
```
@(n) % Define anonymous function of n
x=1:n % Range from 1 to n. Call that x
mod(x,x') % n×n matrix of all pair-wise moduli
~ % Logical negate. True means it's a divisor
( )* % Matrix-multiply x times the above matrix
% (gives the dot product of vector x times
% each column of the matrix)
./x % Divide each column by each entry in x
[~,p]=max( ) % Index of first occurrence of maximum
( )==n % Does it equal n?
```
[Answer]
# [J](http://jsoftware.com/), 35 bytes
Thanks to Mr.Xcoder for finding the problem and to cole for fixing it!
```
[:([:*/{:>}:)@(%~>:@#.~/.~&.q:)1+i.
```
[Try it online!](https://tio.run/##NYc7CoAwEAX7nOKh@InKukaIsKB4D0vx24i1mKtHm8AMzJx@6wWMXz9JPklRPzK8osc8cYOMMbmaXEq36KY8yGsVEbK1pwwVXsGm1DLvF1bYEI2xjDCm6wxzuNbyj/8A "J – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/), 52 bytes
```
n->indmax(sum(x for x=1:m if m%x<1)//m for m=1:n)==n
```
[Try it online!](https://tio.run/##HchBCoMwEAXQvaf4iIWZRZFshErjXQQNjDi/ohVy@9S6fG85Vxu7kmLhczBOPmY5TpeM9NmRY@gdluCP/A7atn63X02NkeUvwojQvypg243flVI3RCNJqFprNXMqPw "Julia 0.6 – Try It Online")
This solution uses rational numbers to ensure correctness in case of equality.
(Testing 360360 took almost 10 minutes.)
Using floating point, 2 bytes can be saved with the left divide:
```
n->indmax(m\sum(x for x=1:m if m%x<1)for m=1:n)==n
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 14 bytes
([FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) saved 1 byte)
```
qh.Mcs*M{yPZZS
```
**[Try it here!](https://pyth.herokuapp.com/?code=qh.Mcs%2aM%7ByPZZS&input=20&test_suite=0&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A20%0A24&debug=0)** or **[see more test cases.](https://pyth.herokuapp.com/?code=qh.Mcs%2aM%7ByPZZS&input=20&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A20%0A24&debug=0)**
Just my mandatory Pyth submission which is most likely golfable.
### How?
```
qh.Mcs*M{yPZZS ~ Full program. Q = input.
S ~ The integers in the range [1, Q].
.M ~ Get the elements with maximal function value.
cs*M{yPZZ ~ Key function: uses a variable Z.
yPZ ~ The powerset of the prime factors of Z.
{ ~ Deduplicated.
*M ~ Product of each.
s ~ And summed.
c Z ~ Divided by Z.
h ~ First element.
q ~ Check equality with the input. Outputs either True or False.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
LÑOā/ZQ¨_P
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f5/BE/yON@lGBh1bEB/z/bwYA "05AB1E – Try It Online")
or as a [Test suite](https://tio.run/##MzBNTDJM/W/pU1b53@fwRP8jjfpRgYdWxAf8r1Q6vN9K4fB@JR3NmP8A)
**Explanation**
```
L # push range [1 ... input]
Ñ # divisors of each
O # sum of each
ā/ # divide each by its 1-based index
Z # get max
Q # compare to each
¨ # remove the last element
_ # logical negation
P # product
```
[Answer]
# [Python 3](https://docs.python.org/3/), 77 bytes
*-1 byte thanks to Rod. -3 bytes thanks to Dennis.*
```
lambda n:max(range(1,n+1),key=lambda k:sum((k%i<1)/i for i in range(1,k)))==n
```
[Try it online!](https://tio.run/##NctBCoAgEADAr@wl2CUhJOgg@ZMuRlmLuYUV5OvtUudhjnytu7TF26FsLo6TAzHRPZicLDNqJbUmFeZsPw3mvCNiqLjX1DD4PQEDC/whEJG1Uo7EcqHHjqi8 "Python 3 – Try It Online")
[Answer]
# R using `numbers`, 59 bytes
```
f=function(n)which.max(sapply(1:n,numbers::Sigma)/(1:n))==n
```
[Answer]
# Mathematica, ~~53~~ 50 bytes
```
a=Tr@Divisors@#/#&;AllTrue[a@#-Array[a,#-1],#>0&]&
```
Pure function. Takes an integer as input and returns `True` or `False` as output.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 33 bytes
```
{⍵=⊃⌽+⌿∘.≤⍨((+/⍳(/⍨)0=⍳|⊢)÷⊢)¨⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71bbR91NT/q2av9qGf/o44Zeo86lzzqXaGhoa3/qHezBpBYoWlgC2TWPOpapHl4O4g8tALIB@qs/f8/XwGkQiFN4dAKhXwFoIkKQCkLEwMA)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
εü<m§ṁ/Ḋṫ
```
[Try it online!](https://tio.run/##AUQAu/9odXNr/yBtKHPigoFyKcK2/861w7w8bcKn4bmBL@G4iuG5q////zEKMgozCjQKNQo2CjcKOAo5CjEwCjYwCjgwCjM2MA "Husk – Try It Online")
Too slow for the 360360 test case.
## Explanation
```
εü<m§ṁ/Ḋṫ Implicit input, say n=6.
ṫ Decreasing range: [6,5,4,3,2,1]
m Map this function (example argument k=4):
Ḋ Divisors of k: [1,2,4]
§ṁ Map and sum
/ division by k: 7/4
Result: [2,6/5,7/4,4/3,3/2,1]
ü Remove duplicates by
< strict comparison. This greedily extracts a non-decreasing subsequence: [2]
ε Is it a singleton list? Yes.
```
[Answer]
# Japt v2.0a0, ~~12~~ 16 bytes
Sleep deprived brain can't seem to improve on this any further!
Returns `1` for truthy or `0` for falsey.
```
Æâ x÷U >Xâ x÷XÃ×
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=xuIgePdVID5Y4iB491jD1w==&input=OA==)
Sacrificed 4 bytes to handle `360360`.
---
## Explanation
* Implicit input of integer `U`.
* `Æ Ã` creates an array of integers from `0` to `U-1` and passes each through the following function as `X`.
* `â` gets the divisors of `U`.
* `÷U` divides each of those by `U`.
* `x` sums the results.
* `Xâ` gets the divisors of `X`.
* `÷X` divides each of those by `X`.
* `x` sums the results.
* `>` checks if the first result is greater than the second.
* `×` reduces the resulting array of booleans by multiplcation.
[Answer]
# APL+WIN, 37 bytes
```
↑1=⍒⌽(+/¨((0=(⍳¨n)|¨n)×⍳¨n)~¨⊂0)÷n←⍳⎕
```
Prompts for screen input.
[Answer]
# C (gcc), 99 bytes
```
s(n,j,k){for(j=k=0;j++<n;)k+=n%j?0:j;n=k;}f(n,i,r){for(i=r=0;++i<n;)r=1.*s(n)/n<1.*s(i)/i?:r;r=!r;}
```
[Try it online!](https://tio.run/##JY7BDoJADETvfEUlIdm6q8CV0vAjXgwEs0uspnojfPtacE7NzJtJx8tjHHP@OAkpLLjOL3WJF24oed8L4eJZqjQ0XSLhhbbZyBj0T0ZWI72PO6ncXs82hLX0xxWxjkOnpHxS2nKULzzvURwWawEmWwC3u8ItgZUaAu8Fj3DXWy2dXVlNHVTTTcoAEsA@QKRiyz8)
# C, 108 bytes
```
float s(n,j,k){for(j=k=0;j++<n;)k+=n%j?0:j;return k;}f(n,i,r){for(i=r=0;++i<n;)s(n)/n<s(i)/i&&++r;return!r;}
```
[Try it online!](https://tio.run/##LY3BDoIwEETvfMVKAulma4CrS@OPeCFgTVtcTMET4duxqHOceTPTn/uxk8e@23HqFpiVaK8DrnaKyptgavZErTAGMlL4a33xHO/LOwoE3mzCnY4/3JmYcCJ34GkIK2ln5bByZUkU/7VT5G13ssCzc6IwWzNISn1QhyumYZC2qRmIBL/hoVdMqVV5MVygGG6SaxAN6R@Rs23/AA)
[Answer]
# [Swift](https://swift.org), ~~120~~ 118 bytes
```
let s={n in Float((1...n).reduce(0){n%$1>0 ?$0:$0+$1})}
{n in(1..<n).reduce(0){max($0,s($1)/Float($1))}<s(n)/Float(n)}
```
Takes some time (around 6 seconds on TIO) to compile because of the implicit type declarations in Swift.
[Try it online!](https://tio.run/##Vc3BCsIwEATQu1@xlAi7WGMCnmqtN/8jaAKBui1JRKHk26OhePA2DLyZ@PIuHUsZbYJ4Xhg8w3WcTELUUkomGez9ebOoaOGt0IOCi1CdUDuhM@VNdW51FfR/4GHeKFQbUWg6rKvfRLmPyL@CKRc3BfD1uV5qtczBc0LfOvTURjubYNIUugb2AzR0yuUD)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
RÆs©Ṫ×R>®×$Ạ
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef//UsOGc8Kp4bmqw5dSPsKuw5ck4bqg////MTIw) or [Find all superabundant numbers below 1000.](https://tio.run/##ASUA2v9qZWxsef//UsOGc8Kp4bmqw5dSPsKuw5ck4bqg/8i3w4fDkGb/ "Jelly – Try It Online")
because I hate floating points.
[Answer]
# [Funky](https://github.com/TehFlaminTaco/Funky), 79 bytes
```
d=n=>fors=i=0i<=n i++s+=i*!n%i
f=n=>{forc=1c<n c++if(d(n)/n)<=d(c)/c return0 1}
```
## Explained
This first defines the function `d` which is the `σ` function, and this is the golfed version of
```
function d(n){
var s = 0;
for(var i=0; i<n; i++){
if(n%i == 0){
s += i;
}
}
return s;
}
```
We can set i to 0, because `i*n%0` will always equal `0*...`, thus `0`.
The next half of this defines the function `f`, which is the Superabandunce function, and it is just the golfed form of
```
function f(n){
for(var c=1; c<n; c++){
if( (d(n)/n) <= (d(c)/c) ){
return 0;
}
}
return 1;
}
```
And this just checks, as the challenge spec suggests, that all integers from 1 to n-1 have a `d(n)/n` of less than the input.
[Try it online!](https://tio.run/##FcrBCsIwDADQs/2KOBBaM1h7b/wSL5JaSIUoXTeQsW@v8/xeXvT17T2R0i2/60xCXiIpCOKMJNezXsTkP2@HMwWOCowo2SarblIXKVl2E0N9tqWqh7D3o8L6qFAoQInBQ0HczOlTRZstIwz3NoyQbXHO7P0H "Funky – Try It Online")
[Answer]
# Perl 5, 84 bytes
```
say!grep$a[-1]<=$a[$_],0..(@a=map{$i=$_;my$j;map{$i%$_ or$j+=$_/$i}1..$i;$j}1..<>)-2
```
requires `-E` (free)
a straightforward implementation of the specification, golfed
[Answer]
# APL(NARS), 61 chars, 122 bytes
```
r←f w;m;k
r←m←0
r+←1⋄k←r÷⍨11πr⋄→3×⍳r≥w⋄→2×⍳∼m<k⋄m←k⋄→2
r←k>m
```
11π is the function sum of factors
```
(⍳9),¨ f¨1..9
1 1 2 1 3 0 4 1 5 0 6 1 7 0 8 0 9 0
f 360360
0
```
]
|
[Question]
[
I have a problem for a cyber club that asks you to print:
```
ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"!
```
Using Brainf\*\*k in 29 bytes or less without using the ',' character.
I have a working code:
```
++++++++++[>++++++>+++++++++<<-]>-->.<[>-.<-]
```
However my loop is too long, sending me 16 bytes over the limit.
Is there a more efficient way to set the second and third cell to 58 and 90 so I can run my second loop? Or is there a better way to do this all together that I am just not seeing?
[Answer]
## ~~27~~ 24 bytes
```
++[<++[++<]>>>+]<[-<-.>]
```
~~Spent a whole day basically writing up a brute forcer and watching the results come in. Now I can get back to doing some actual work...~~ Another day of brute forcing later...
[Try it online!](http://brainfuck.tryitonline.net/#code=KytbPCsrWysrPF0-Pj4rXTxbLTwtLj5d&input=)
The component `++[<++[++<]>>>+]` initialises the tape to
```
[130, 0, 0, 0, 91, 59, 0]
^
```
which is just perfect for what we need!
[Answer]
# 30 bytes
```
-<-[>+>-[---<]>]>++>+[---<.->]
```
[Try it online!](http://brainfuck.tryitonline.net/#code=LTwtWz4rPi1bLS0tPF0-XT4rKz4rWy0tLTwuLT5d&input=)
*85* and *171* are fairly easy to generate in brainfuck (modular inverses of *3* and *-3*). *85* is pretty close to *90*, and *171* is pretty close to *177* (*59·3*), which is used here. With a bit of hackery, I'm able to produce *88* and *176* instead.
Still one byte short of the target, though.
**Other suggestions**
In general, it's shorter to iterate over a list, multiplying by a constant, rather than the other way. This is especially true for 3 or more values. For example, this:
```
++++++++++[>++++++>+++++++++<<-]
```
can be written as:
```
+>++++[+++++[>++++++++++<-]<]>
```
There were only two inner values, so it's not much of an improvement in this case. In fact, just refactoring is one byte shorter:
```
+++++[>++++++[>++>+++<<-]<-]>
```
Multiplying *30* by *2* and *3*, rather than *10* by *6* and *9*. With Martin Büttner's suggestion, this is already down to *38* bytes, without much change to the original:
```
+++++[>++++++[>++>+++<<-]<-]>>-[>.-<-]
```
[Answer]
# 34 bytes
Saved you 11 bytes, but still 5 bytes too long...
```
+[--->++<]>++++<+[--------->.-<]>.
```
I've spent hours already, hopefully someone can improve on this.
]
|
[Question]
[
You are given a single printable ASCII string containing no newlines, and a multiline "mold", containing spaces (), and hashes (`#`).
You must go character by character in the string, and replace **hashes** using the characters from the string in left-right, top-bottom order. If the string is too short to fill the mold, you stop outputting, if the string is too long you truncate the string to exactly fill the mold.
---
Example string/mold (string too long, truncated):
```
Loremipsumdolorsitamet,consecteturadipiscingelit.Namsuscipitmagnanoneratgravidacondimentum.Vestibulumnecnisllorem.Fuscemolestieviverranibh,eueleifendnislplaceratnon.Namblanditturpislacus,vitaemolestielacusimperdietquis.Nullapulvinar,exquissollicitudinfacilisis,eratnullavolutpatlectus,etluctusenimvelitegetex.Inhachabitasseplateadictumst.Donecinterdumnullalacinia,sodalesloremin,eleifendturpis.Pellentesqueanisimi.Aeneannonlobortisdiam,quisaliquetquam.Aeneanaugueipsum,imperdietsedaliquetnon,volutpategetsapien.Nullampharetranullaquispretiumornare.Aliquamfermentumvestibulummassavitaevehicula.
###########################################################
##### ############## ###### ###### ######################
##### ## ###### # ##### ###### ######## ######
###### # # #### #### ##### ###### ####### ###### #####
###### ### ### ##### ###### ####### ####### #####
###### ##### ### ########### ###### ####### ### ######
###### ###### ### ########## ###### ##### #########
################## #### ##########################
###########################################################
```
Example output:
```
Loremipsumdolorsitamet,consecteturadipiscingelit.Namsuscipi
tmagn anoneratgravid acondi mentum .Vestibulumnecnisllore
m.Fus ce molest i evive rranib h,euelei fendni
slplac e r atno n.Na mblan dittur pislacu s,vita emole
stiela cus imp erdie tquis. Nullapu lvinar, exqui
ssolli citud inf acilisis,er atnull avolutp atl ectus,
etluct usenim vel itegetex.I nhacha bitas seplatead
ictumst.Donecinter dumn ullalacinia,sodalesloremin
,eleifendturpis.Pellentesqueanisimi.Aeneannonlobortisdiam,q
```
Example string/mold (string too short, output stopped):
```
This probably won't look good.
### ### ### ###
# # # # # #
### ### # # #
# # # # #
# # ### ###
```
Corresponding output:
```
Thi s p rob abl
y w o n '
t l ook g o
o d .
```
---
Shortest code in bytes wins.
Credit for the idea to [this website](http://jollo.org/ascii2uri.htm).
[Answer]
# LabVIEW, 37 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490)
splits the string into text and mold then transforms them into an array. Checks the mold if theres a # and puts a char from text else it does nothing. If either the text or the mold are empty exit the loop
[](https://i.stack.imgur.com/cFBDM.jpg)
[](https://i.stack.imgur.com/nUHau.gif)
[Answer]
# Haskell, 48 bytes
called like "(replace with string)#(hashmark string)":
```
[]#_=[]
(r:t)#('#':s)=r:t#s
r#(c:s)=c:r#s
_#_=[]
```
Less golfed:
```
combine replacements slots | null replacements = []
| null slots = []
| head slots == '#' = head replacements : combine (tail replacements) (tail slots)
| otherwise = head slots : combine replacements (tail slots)
```
[Answer]
## CJam, ~~16~~ 14 bytes
*Thanks to Sp3000 for saving 2 bytes.*
```
lq{s'#-\+(\}/;
```
Terminates with an error if the string is too short, but the error is printed to STDERR.
[Try it online!](http://cjam.tryitonline.net/#code=bHF7cycjLVwrKFx9Lzs&input=VGhpcyBwcm9iYWJseSB3b24ndCBsb29rIGdvb2QuCiMjIyAjIyMgIyMjICMjIwojICMgIyAjICMgICAjCiMjIyAjIyMgIyAgICMgIwojICAgIyAgICMgICAjICMKIyAgICMgICAjIyMgIyMj)
Alternatively (same byte count):
```
lq{SN+&\+(\}/;
```
### Explanation
```
l e# Read the input line.
q e# Read the grid.
{ e# For each character in the grid...
s e# Convert to string.
'#- e# Remove "#" from it.
\+ e# Prepend it to the input line (this is a no-op for "#"s in the grid).
( e# Pull off the first character from the input line. This will terminate the
e# program with an error once the input line is empty.
\ e# Swap the character with the input line.
}/
; e# Discard the remainder of the input line if there is any.
```
[Answer]
## [Retina](https://github.com/mbuettner/retina/), ~~42~~ 40 bytes
Byte count assumes ISO 8859-1 encoding.
```
T`#`×`¶.+
+`^(.)([^×]+)×
$2$1
^.*¶|×\D*
```
The trailing linefeed is significant.
[Try it online!](http://retina.tryitonline.net/#code=VGAjYMOXYMK2LisKK2BeKC4pKFtew5ddKynDlwokMiQxCl4uKsK2fMOXXEQqCg&input=VGhpcyBwcm9iYWJseSB3b24ndCBsb29rIGdvb2QuCiMjIyAjIyMgIyMjICMjIwojICMgIyAjICMgICAjCiMjIyAjIyMgIyAgICMgIwojICAgIyAgICMgICAjICMKIyAgICMgICAjIyMgIyMj)
### Explanation
```
T`#`×`¶.+
```
We first replace `#` which are part of the grid with the non-ASCII (but extended ASCII) character `×` so we don't confuse them with any `#` that might appear on the first line.
```
+`^(.)([^×]+)×
$2$1
```
Now we fill as many `×` as possible from the first line by repeatedly replacing the first `×` we can find with the first character on the first line (which is removed in the process).
```
^.*¶|×\D*
```
Finally, we get rid of anything that's left on the first line as well as anything from the first `×` to truncate the input in both directions.
[Answer]
# JavaScript (ES6), ~~57~~ ~~56~~ 55 bytes
```
(s,m)=>m.replace(x=/[^]/g,c=>c-1?x&&c:x=s[i++]||"",i=0)
```
*Saved 1 byte thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!*
## Explanation
Works with hashes in the input string and retains trailing white-space after the input string has finished.
```
var solution =
(s,m)=>
m.replace(x=/[^]/g,c=> // for each character c of the mold, initialise x to true
c-1? // if c is a space or newline:
x&&c // if x is truthy, return c
// else if the string has ended, x will equal "" (false), return x
: // else if c is a hash:
x= // set x to the character of the input string
s[i++]||"", // return the input string character (or "" if finished)
i=0 // initialise i to 0
)
```
```
<input type="text" id="input" value="This probably won't look good." /><br>
<textarea id="mold" rows="6" cols="40">### ### ### ###
# # # # # #
### ### # # #
# # # # #
# # ### ###</textarea><br>
<button onclick="result.textContent=solution(input.value,mold.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# Python 3, ~~69~~ ~~68~~ 67 bytes
```
def f(s,m):s=iter(s);return''.join(n<'#'and n or next(s)for n in m)
```
`[Ideone](http://ideone.com/WDNQ9j)`
Thanks to FryAmTheEggman, Chiel ten Brinke for the byte off. Alternatively, I could have used Python 2 for an extra one (`print` without `()`).
[Answer]
# [pb](https://esolangs.org/wiki/pb), 359 bytes
```
^w[B!0]{w[B=10]{t[T+1]b[0]}>}<w[T!0]{w[B!0]{<}>^b[T]vw[B!0]{t[B]b[0]^v[B]v<[X]w[B!0]{>}b[T]<[X]^[Y+2]w[B=0]{>}t[B]b[0]>b[T]v}^t[B-1]vw[B=0]{<}}>b[10]t[X]w[X!-2]{w[B!0]{v}<}w[X!T]{b[35]>}^[Y]^<[X]w[B!10]{t[B]b[0]w[T=35]{t[10]}v<[X]w[B!35]{w[B=0]{v<[X]<b[1]}>}b[T]^[Y]^<[X]w[B=0]{>}}<[X+2]w[B=0]{v}w[B!0]{b[0]>}w[Y!-1]{<[X]^w[B!0]{w[B=35]{b[0]}w[B=10]{b[35]}>}}
```
In pb, input is strictly one dimensional. It doesn't understand that you're drawing a shape with your input, it just sees one long line with some bytes with a value of 10 thrown in there. The first thing this program does is copy all but the first "line" of input onto Y=0, Y=1, etc, to create the shape of the mold.
Something I've noticed a lot in code golf, but *especially* when golfing esoteric languages, is that you often don't want to have two branches to deal with; you just set yourself up that you do the same thing in either case. The naive way to solve this problem would probably check the length of the string against the number of hashes in the rest of the input and do something depending on the result, because it has to behave differently depending on what gets cut off. But that's a lot of bytes.
Instead, after completing the mold, an extra line is added to the bottom. It is simply `n` hashes in a row, where `n` is the length of the string. Now the string is guaranteed to fit! After inserting all the characters of the string, that extra line that was added is unconditionally destroyed. Any leftover hashes in the mold proper are erased as well, and that's the necessary output!
Of course, it would violate the spec to simply destroy all hashes. After all, there could be a hash in the input string! To handle this, I refer to another part of the spec:
>
> You are given a single printable ASCII string **containing no newlines**
>
>
>
(Emphasis mine.) By the time we're dealing with the string, we don't really care if there are newlines in it, but we do know that there aren't any. So, all hashes are replaced with newlines before being put into the mold! After all hashes are destroyed, all newlines are replaced with hashes again. This doesn't turn the entire output into a single hash-delimited line because the nature of pb's 2D output means that it never actually put a newline at the end of each line, it just went on to the next line.
**Ungolfed:**
```
# Start by copying down the mold
^
# (B means "the character under the cursor")
w[B!0]{ # While B isn't a null byte:
w[B=10]{ # While B IS a newline:
t[T+1] # Increase T by 1
# (`T` is the only variable that can be modified directly)
b[0] # Overwrite with 0 to break out of inner loop
}
> # Move to the right
# (dodge the 0 we wrote and progress towards the end of input)
}
# Brush is now at the end of the input, T contains number of lines
< # Make sure the brush is actually /on/ the input
w[T!0]{ # While T isn't 0:
w[B!0]{<}> # Go to the first character of the last line
^b[T] # Place a flag above current character
# Also a convenient way to get the value of T back later
vw[B!0]{ # While the character under the flag isn't 0:
t[B]b[0] # Put it in T, overwrite with 0
^v[B]v # Go down by the amount written in the space above
<[X] # Go left by the amount right the brush is (i.e. go to X=0)
w[B!0]{>} # Find first empty space
b[T] # Write the value of T
<[X] # Go left by the amount right the brush is
^[Y+2] # Go up by the amount down the brush is plus 2 (above input)
w[B=0]{>} # Find flag
t[B]b[0] # Pick it up, overwrite with 0
>b[T] # Place it to the right
v}
^t[B-1]v # Collect flag - 1
w[B=0]{<} # Go to end of previous line
}
# Mold is placed, all that's left is placing the string
>b[10] # Put a newline at the end, guaranteed to not be in the string
t[X] # Save current X value in T
# Add more hashes, guaranteed to fit the input and findable later
w[X!-2]{ # While X!=-2:
w[B!0]{v} # Move down until hitting a null byte
< # Move left
}
w[X!T]{ # While not at the X value we saved earlier:
b[35]> # Travel right, leaving hashes
}
^[Y]^<[X] # Go to (0, -1)
w[B!10]{ # Until hitting the newline at the end:
t[B]b[0] # Pick up character, overwrite with 0
w[T=35]{ # If it's a hash...
t[10] # Make it a newline so we remember, deal with it later
}
v<[X] # Go to (0, 0)
w[B!35]{ # While B is not a hash:
w[B=0]{ # While B IS null:
v # Go down
<[X]< # Go to X=-1
b[1] # Print a 1 to break loop (it won't be rendered anyway)
}
> # Go right, either ignore a non hash or go to X=0
}
b[T] # Overwrite hash with picked up character
^[Y]^<[X] # Go to (0, -1)
w[B=0]{>} # Go to first character of it to restart loop
}
<[X+2] # Go to (-2, -1)
w[B=0]{v} # Go down until finding the row of added hashes
w[B!0]{b[0]>} # Wipe it out unconditionally
w[Y!-1]{ # For every remaining line on the screen:
<[X]^ # Go to the beginning
w[B!0]{ # For each character in it:
w[B=35]{ # If it's a hash:
b[0] # Destroy it
}
w[B=10]{ # If it's a newline:
b[35] # Write a hash (after the check to destroy hashes!)
}
>}
}
```
[Answer]
## ES6, 59 bytes
```
(t,m)=>m.replace(/#/g,h=>t[i++]||h,i=0).replace(/#[^]*/,'')
```
70 bytes if the text can contain hashes:
```
(t,m)=>m.replace(/#/g,(_,n)=>t[i]&&(j=++n)&&t[i++],i=0,j=0).slice(0,j)
```
[Answer]
## Perl, ~~53~~ ~~51~~ 42 + 2 = 44 bytes
```
@a=/./g;$/="";$_=<>;s/#/shift@a/ge;s/\s+$//
```
Requires `-p` to run. Explanation:
```
@a=/./g; # Split first line into an array of characters
$/=""; # Enable slurp mode (read the rest of lines in one go)
$_=<>;
s/#/shift@a/ge;
s/\s+$//
# With '-p' auto print is enabled
```
[Answer]
# Jelly, ~~10~~ 8 bytes
```
¹ƈ<”#$?€
```
[Try it here!](http://jelly.tryitonline.net/#code=wrnGiDzigJ0jJD_igqw&input=TG9yZW1pcHN1bWRvbG9yc2l0YW1ldCxjb25zZWN0ZXR1cmFkaXBpc2NpbmdlbGl0Lk5hbXN1c2NpcGl0bWFnbmFub25lcmF0Z3JhdmlkYWNvbmRpbWVudHVtLlZlc3RpYnVsdW1uZWNuaXNsbG9yZW0uRnVzY2Vtb2xlc3RpZXZpdmVycmFuaWJoLGV1ZWxlaWZlbmRuaXNscGxhY2VyYXRub24uTmFtYmxhbmRpdHR1cnBpc2xhY3VzLHZpdGFlbW9sZXN0aWVsYWN1c2ltcGVyZGlldHF1aXMuTnVsbGFwdWx2aW5hcixleHF1aXNzb2xsaWNpdHVkaW5mYWNpbGlzaXMsZXJhdG51bGxhdm9sdXRwYXRsZWN0dXMsZXRsdWN0dXNlbmltdmVsaXRlZ2V0ZXguSW5oYWNoYWJpdGFzc2VwbGF0ZWFkaWN0dW1zdC5Eb25lY2ludGVyZHVtbnVsbGFsYWNpbmlhLHNvZGFsZXNsb3JlbWluLGVsZWlmZW5kdHVycGlzLlBlbGxlbnRlc3F1ZWFuaXNpbWkuQWVuZWFubm9ubG9ib3J0aXNkaWFtLHF1aXNhbGlxdWV0cXVhbS5BZW5lYW5hdWd1ZWlwc3VtLGltcGVyZGlldHNlZGFsaXF1ZXRub24sdm9sdXRwYXRlZ2V0c2FwaWVuLk51bGxhbXBoYXJldHJhbnVsbGFxdWlzcHJldGl1bW9ybmFyZS5BbGlxdWFtZmVybWVudHVtdmVzdGlidWx1bW1hc3Nhdml0YWV2ZWhpY3VsYS4&args=IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKIyMjIyMgIyMjIyMjIyMjIyMjIyMgICAjIyMjIyMgIyMjIyMjICMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKIyMjIyMgICMjICAgIyMjIyMjICAgIyAgIyMjIyMgIyMjIyMjICMjIyMjIyMjICAgICAgICAjIyMjIyMKIyMjIyMjICMgICMgICMjIyMgICMjIyMgIyMjIyMgIyMjIyMjICMjIyMjIyMgICMjIyMjIyAgIyMjIyMKIyMjIyMjICAgIyMjICAjIyMgICAgICAgIyMjIyMgIyMjIyMjICMjIyMjIyMgIyMjIyMjIyAgIyMjIyMKIyMjIyMjICAjIyMjIyAjIyMgIyMjIyMjIyMjIyMgIyMjIyMjICMjIyMjIyMgICAjIyMgICAjIyMjIyMKIyMjIyMjICMjIyMjIyAjIyMgICMjIyMjIyMjIyMgIyMjIyMjICAgICAgIyMjIyMgICAjIyMjIyMjIyMKIyMjIyMjIyMjIyMjIyMjIyMjICAgICAgICMjIyMgICAgIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyM)
[Answer]
# [Perl 6](http://perl6.org), 72 bytes
```
my@a=get.comb;say(S:g/\#/{@a.shift//''}/~~{S/\s+$//}),@a||last for lines
```
[Answer]
# ES6, 47 bytes
Probably the most straightforward solution.
```
(S,R)=>(i=-1,S.replace(/#/g,_=>R[++i]||R[i=0]))
```
This code creates an anonymous function that receives 2 parameters and returns the final result.
The first parameter `S` is the "map" string with your `"#"`, while the second parameter `R` is the "replacement" for those `"#"`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 52 bytes
```
->a,b{i=-1
a.gsub(/(#)|./){b[i+1]?$1?b[i+=1]:$&:""}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nVTNatwwEL705KcQu6FNqOOw0EMJpCFQAoUSeii9hBzG9qx36Ehy9OMmpHmSXkJJH6p9lJ46sp2Nk02hVIvl-ftm5ht59e3WxfLy5vvxwY8Ylruvf77afQN5eUUHu4sMisbHcntve77ztdjbuSpP6eXi7HBrcZikg8XZ_tbz_dns-nrA_nr2u43Bq-PT2fz_V9bv6qFRqdHw8PUXrJoCRBjlx1g1ril23kcPtnF_Cnuf_QG2V8ftPvVj7Pxp7No5JbdRV80n5LKNIKU2sZNOJu5svrEmTatp6MZ6AvvPa5Zns_fWoabWR11bts5TAI0hr6zxWAUM0UFNLfmKTINMoTgB7aOoLQUNjQFjDToIjYOOahBcTRpNiLr4hD5QGTlqg5Uhz5xqFceCRm05ebGjDp0DQ-Uqx4iMtERTp-CWoUqJJX-qWTJI5iD9SDPiij7vpNd1ot5EukVXE4bzSL44iczQRu7IgMvxIhm9ZaaKQqzJLKEiJk8-7-uk6M5yDC0EFu5SAQPHJKAh3SX22GDAi-KdWUG1glIa8B6l04AyJYnUPhRvZSAyrSCdCPOUVXojQ5B7W4N024-BTH7HduBUfEBmGRz684gyECFDxREakWUEbEvrAvmaQOeJCDBJnBAFPUZBbCL2J5mv5-CxHgMlR37HLrHw0BKaYUa6XYHDIMeQtJS9FZWitk4mh8VRSgF6iW442W59sFr4Q38OHa6oigzF7CxLV0-WTS4gNXmy9L8efvJdZ2tPfzskr1L3z0Qf4tIn-3FFXrXOllDypfpizYug2NrPqrG2lvrDFXhzM7z_AA)
[Answer]
# [Julia 1.0](http://julialang.org/), ~~98 88~~ 77 bytes
```
!S=((a,b)=split(S,'
';limit=2);j=0;[b...].|>m->(print(m=='#' ? a[j+=1] : m)))
```
[Try it online!](https://tio.run/##nVNNb9swDL37V6jNIQnmCeuOK9yhwDBgwFAMyLDL0ANtszE7SnL14bXA/ntGOWniItkOVRBblPio9x6t@8QEF4@bzdmqWiygrJdV6JniYlXOi/klk6FYvV9e3lfvLn/WWutb/efKvL1a9J5sXJiqms/m6qOCn/dvqotb9UGZ5XK5WVXn3zsKqveuhpqf1G9n51Gxc7/U2rlWF7PZTE3@hTx3P6Vmh90c5Xh8q@N4m3deFNE/FUqdrYoGYtPJdCTIdrEs0LZFIYy@Oo@G@pBM69j5QBEMxrJxNmATMSYPLfUUGrJrFA/0DZiQJOwpGlhbsM6ih7j2MFALgmvJoI3J6B8YItWJk7HYWArM@Sz9WdBoHOddHGhA78FS3ZWYkJHuhFlO7hmaXFjq5zNrBqkchY@Qka0UykG47guNS2R69C1hfEgU9E1ihj7xQBZ8iY95MThmaiimluwdNMQUKJTjOTl7cJxiD5FFu5yAkVOeoCUzZPW4xoiP@ovtoOmgFgIhoDCNKC5JpglRfxJDxK0oTER5rircyBKUwbUgbEcbyJbParea9DdkFuMwPCQUQ0QM6Wu0MhcL2NXORwotgSmzEGCSPBEKZpcFaZ1w7GS59yFgu0uUGuWzuqwiQE9otx6ZvgOPUdqQo1y9l5CScV6cQ32dS4C5Q7/t7LBvrBH9MPZhwI6axDB@xK8dW6x6ubj9og/r6r9YNQWM9@EkVu3GFDverB1g9zyFPVR/gd3eO3WofRI7O43db07FHZ2rpm4UR0lKHWMnTCbbJ3o0Ia2mqf/w@XXjvDhbbf4C "Julia 1.0 – Try It Online")
-22 MarcMush
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 39 bytes
```
{(w@l)#@[y;l#w;:;(l:(#x)&#w:&"#"=y)#x]}
```
[Try it online!](https://ngn.codeberg.page/k#eJydVNtq20AQfddXLBIkNgilfXUIOFAKhRL6UPrSlHYkje2hs7vKXmSb0n/vrKw4cpyU0jXS3uacOWdGeLX4NdsueV4sv+6vudheL65nvJgVu/lFsV1c5EV+s58Xu2+/swwWs/yjdaip81G3lq3zFEBjKBtrPDYBQ3TQUke+IbNGplDdgfZRth0FDWsDxhp0ENYOempBcC1pNCHq6gv6QHXkqA02hjxzylW9FzRqy+kWe+rROTBUb0qMyEgrNG0K7hiaRCz8KWfNIMxB9IgYuYq+7EXrkWg4It2hawnDQyRf3UVm6CL3ZMCVuEuH3jJTQyG2ZFbQEJMnXw55UnRvOYYOAot3yYCBY1qgId0n97jGgLvqg9lAs4FaBHiPojSgVEkitQ/VOymIVCuIEnGeWEUbGYLS2xZE7VAGMuWj24On6hMyS+HQP0SUgogZqm7RyFpKwLa2LpBvCXSZjACTxIlR0GMUxHXEoZPlsQ4e2zFQOMpHd8mFh47QHGqkuw04DNKGtEvsnWwpauukcljdJgrQK3SHzvbHxmrxD0MfetxQExmqPFP5vcmv3n6/TPN9ror/H9kB/IxCqfHgdHoNrKYIWagT0iNYjeMEXAzhh8Px/RL4if4UPOzH1xP5c3DxCvh4OzV4llkVE3+ZOotS6hw80TK5zqZ5immoelyeB/wN/M8jn2dZLf9GnzfkVedsDTXv1daay6DY2p9qbW378qc1fUTD8Sdas6e7oe/DvZo804NDZBLy481itbyCNOf5uKuzP+zla0U=)
Explanation:
```
{(w@l)# / up to the final index
@[y; / replace the mold
l#w;:; / at the first l indices of hash characters
(l:(#x)&#w:&"#"=y) / where l is the min of
number of such indices and length of string
#x]} / with the first l characters of string
```
Uses the fact that one past the last index of a list is null and taking the first null characters defaults to the full list.
[Answer]
# Python 3
# ~~152~~ 127 bytes
A full program.
```
from sys import stdin as S
s=list(S.readline())
print(''.join([''if not s else(s.pop(0)if m=='#'else m)for m in S.read()]))
```
# 106 bytes
A function that takes the stream as input.
```
def f(S):s=list(S.readline());return''.join([''if not s else(s.pop(0)if m=='#'else m)for m in S.read()])
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
`'ÿ«)'#s.;'ÿ¡н
```
Also complies to the two rules in the comments, unlike some of the other answers:
1. The input-sentence can contain hashes and (potentially trailing) spaces.
2. The output does not contain trailing spaces (unless the input contained trailing spaces), only a single trailing newline.
[Try it online.](https://tio.run/##yy9OTMpM/f8/Qf3w/kOrNdWVi/WsQcyFF/b@/x@SkVmsUFCUn5SYlFOpUJ6fp16ikJOfn62Qnp@foselpKSkrKysgIS5gCQUKigAeTAZEA/EB9MKmHyIOqB5AA)
**Explanation:**
I take advantage of the fact that the input only contains printable ASCII.
```
` # Push the characters of the first (implicit) input-sentence separately
# to the stack
'ÿ« '# Append an "ÿ" to the last character
) # Wrap the entire stack into a list
'# '# Push string "#"
s # Swap so the list is at the top again
.; # Replace every first "#" in the second (implicit) multi-line string
# with the items in the list one by one
'ÿ¡ '# Split the resulting string on "ÿ"
н # Only keep the first part
# (after which the result is output implicitly with trailing newline)
```
Unfortunately [the legacy version of 05AB1E](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b) doesn't vectorize with builtin `.;`, otherwise the second `'ÿ` could have been replaced with `Z` (maximum character - based on codepoint - without popping). In the new 05AB1E version, the min/max builtins doesn't work on characters. But because it doesn't vectorize, it's 15 bytes instead: [``'ÿ«)v'#y.;}Z¡н` - try it online](https://tio.run/##MzBNTDJM/f8/Qf3w/kOrNcvUlSv1rGujDi28sPf//5CMzGKFgqL8pMSknEqF8vw89RKFnPz8bIX0/PwUPS4lJSVlZWUFJMwFJKFQQQHIg8mAeCA@mFbA5EPUAc0DAA).
[Answer]
# [Python](https://www.python.org), 64 bytes
```
f=lambda s,m:m and(z:=m[0]*(m[0]!='#')+s)and z[0]+f(z[1:],m[1:])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pVTNbtQwED5x2acwu4fu0hDRPaFKK1EJISGhigPiUvUwiSebEf6rf0LbV-HSC7wTPE3HSbqbdssFHMXx_Hzj-WYc__jlbmJrzd3dzxSb129_v2s2CnQlQYRCn2oBRi5vTzf64s3lq2WeX26OFker47Bii7hlxXGzvL04Ob0sdJ5XQ5w_L5bhRGzE_JP1qMmFpKVV1geKoDEWtTUB64gxeZDkKNRktqgoluegQ2LRUdSwNWCsQQ9x66EjCYyTpNHEpMuvGCJVSSVtsDYUlMp7lR8YjdqqbMWOOvQeDFVtgQkVUoNGZmenoM6BOX7es1LMhyLnw8mwKYWi41x3gXoVaYdeEsarRKE8T0qBS6ojA77A66wMVimqKSZJpoGaFAUKRb9P9u6sStFBVMydd8CoUl6gId1l9rjFiNflR9NC3ULFCYSAnGlErhJ76hDL91wQrlbkTJh5jsq5kSEogpXA2fZlIFM8sB04lZ9RKS4chquEXBAmQ-UZGl5zCZStrI8UJIEuMhFQxH5MFPToBWmbsO9ksatDQDk6cozigV1mEcARmqFG2rXgMXIbspSjOxYpaeu5clie5RCgG_RDZ7tdYzXzh74PHbZUJwXlfKb7gzWfzxb_PgaseKwUYlQ8_vwFK6YAXozrp1gxjil20XsPunF-DruP_gjbi-O0D_0Uu3geuzNOyR3sKxYTcrMDJyEOsZNMJuZnejRJWkxdD8Z_9Tefj1lY55PypaUgnLcVVOpGfLfmKApl7TextVbm87TenycxeWe5TcPTd2tv7-VsF2L_TuQR3-fgPP-ry4avw0Lok9Vqr1izYr0aL8yHC_ge)
]
|
[Question]
[
Write a program that takes in a string of the four characters `()[]` that satisfies these points:
* Every left parenthesis `(` has a matching right parenthesis `)`.
* Every left bracket `[` has a matching right bracket `]`.
* Matching pairs of parentheses and brackets won't overlap. e.g. `[(])` is invalid because the matching brackets are not fully contained in the matching parentheses, nor vice-versa.
* The first and last characters are a matching pair of parentheses or brackets. So `([]([]))` and `[[]([])]` are valid but `[]([])` is not.
(A [grammar](http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form) for the input format is `<input> ::= [<input>*] | (<input>*)`.)
Each pair of matching parentheses and brackets evaluates to a non-negative integer:
* The values of pairs inside matching parentheses are all *summed*. The empty match `()` has value [`0`](http://en.wikipedia.org/wiki/Empty_sum).
* The values of pairs inside matching brackets are all *multiplied*. The empty match `[]` has value [`1`](http://en.wikipedia.org/wiki/Empty_product).
(The [sum](http://www.wolframalpha.com/input/?i=sum%28x%2C%20n%3D%200%20to%200%29) or [product](http://www.wolframalpha.com/input/?i=product%28x%2C%20n%3D%200%20to%200%29) of one number is that same number.)
For example, `([](())([][])[()][([[][]][][])([][])])` can be broken down and evaluated as `9`:
```
([](())([][])[()][([[][]][][])([][])]) <input>
(1 (0 )(1 1 )[0 ][([1 1 ]1 1 )(1 1 )]) <handle empty matches>
(1 0 2 0 [(1 1 1 )2 ]) <next level of matches>
(1 0 2 0 [3 2 ]) <and the next>
(1 0 2 0 6 ) <and the next>
9 <final value to output>
```
Another example:
```
[([][][][][])([][][])([][][])(((((([][]))))))] <input>
[(1 1 1 1 1 )(1 1 1 )(1 1 1 )((((((1 1 ))))))]
[5 3 3 (((((2 )))))]
[5 3 3 ((((2 ))))]
[5 3 3 (((2 )))]
[5 3 3 ((2 ))]
[5 3 3 (2 )]
[5 3 3 2 ]
90 <output>
```
Your program needs to evaluate and print the integer represented by the entire input string. You can assume the input is valid. The shortest code in bytes wins.
Instead of a program, you may write a function that takes in a string and prints or returns the integer.
[Answer]
# CJam, 23
```
q"])(""1]:*0]:+["4/ers~
```
With BIG credits to Dennis! [Try it online](http://cjam.aditsu.net/#code=q%22%5D)(%22%221%5D%3A*0%5D%3A%2B%5B%224%2Fers~&input=%5B(%5B%5D%5B%5D%5B%5D%5B%5D%5B%5D)(%5B%5D%5B%5D%5B%5D)(%5B%5D%5B%5D%5B%5D)((((((%5B%5D%5B%5D))))))%5D)
**Explanation:**
The program converts the input to a CJam expression then evaluates it.
`[…]` becomes `[…1]:*` (append 1 and multiply)
`(…)` becomes `[…0]:+` (append 0 and add)
```
q read input
"])(" characters we want to replace
"1]:*0]:+[" replacement strings, concatenated
4/ split into strings of length 4: ["1]:*" "0]:+" "["]
er replace (transliterate) the 3 characters with the 3 strings
s convert the result (mixed characters and strings) to string
~ evaluate
```
[Answer]
# Common Lisp - 98
```
(lambda(s)(eval(read-from-string(#1=ppcre:regex-replace-all"\\["(#1#"]"(#1#"\\("s"(+")")")"(*"))))
```
1. Replace `(` by `(+`
2. Replace `[` by `(*`
3. Replace `]` by `)`
4. Read from string
5. Eval
This requires `cl-ppcre` library to be loaded in current lisp image.
### Explanation
Functions `*` and `+` are variadic and return their neutral value when given no arguments.
For your examples, the evaluated lisp form are the following ones:
```
(+ (*) (+ (+)) (+ (*) (*)) (* (+)) (* (+ (* (*) (*)) (*) (*)) (+ (*) (*))))
=> 9
```
and
```
(* (+ (*) (*) (*) (*) (*)) (+ (*) (*) (*)) (+ (*) (*) (*))
(+ (+ (+ (+ (+ (+ (*) (*))))))))
=> 90
```
### Without regexes - 183 bytes
```
(lambda(s)(do(r(x(coerce s'list))c)((not x)(eval(read-from-string(coerce(reverse r)'string))))(setq c(pop x))(push(case c(#\[ (push #\* r)#\()(#\] #\))(#\( (push #\+ r) #\()(t c))r)))
```
### C'mon, Lisp - 16 bytes (experimental)
```
+((<r*([<r)]<rRE
```
Other languages are so terse that I am tempted to make my own golfing language based on Common Lisp, for shorter string manipulations. Currently there is no spec, and the eval function is the following one:
```
(defun cmon-lisp (expr &rest args)
(apply
(lambda (s)
(let (p q)
(loop for c across expr
do (case c
(#\< (push (pop p) q))
(#\r
(let ((a1 (coerce q 'string)) (a2 (coerce p 'string)))
(setf p nil
q nil
s
(cl-ppcre:regex-replace-all
(cl-ppcre:quote-meta-chars a1) s a2))))
(#\R
(setf s
(if (string= s "")
nil
(read-from-string s))))
(#\E (setf s (eval s)))
(t (push c p))))
s))
args))
```
Tests:
```
(cmon-lisp "+((<r*([<r)]<rRE" "([] [] ([] []))")
=> 4
```
* there is an implicit argument called `s` and two stacks, `p` and `q`.
* characters in source code are pushed to `p`.
* `<` : pops from `p` and pushes to `q`.
* `r` : replaces in `s` (must be a string) from characters in `q` to charactes in `p`; result is stored in `s`; `p` and `q` are emptied.
* `R` : read from string `s`, store result in variable `s`.
* `E` : eval form `s`, store result in `s`.
[Answer]
# Pyth, ~~35~~ ~~34~~ 33 bytes
```
L?*F+1yMbqb+YbsyMbyvsXzJ"])"+R\,J
```
[Demonstration.](https://pyth.herokuapp.com/?code=L%3F*F%2B1yMbqb%2BYbsyMbyvsXzJ%22%5D)%22%2BR%5C%2CJ&input=%5B(%5B%5D%5B%5D%5B%5D%5B%5D%5B%5D)(%5B%5D%5B%5D%5B%5D)(%5B%5D%5B%5D%5B%5D)((((((%5B%5D%5B%5D))))))%5D&debug=0)
*1 byte thanks to @Jakube.*
We start by parsing the input. The input format is close to Python, but not quite. We need commas after each parenthesized or bracketed group. The comma at the end of a bracketed group is unnecessary, but harmless. To accomplish this, we use this code:
```
vsXzJ"])"+R\,J
X Translate
z in the input
"])" the characters "])"
J which we will save to J to
J J
+R\, with each character mapped to itself plus a ",".
s Combine the list to a string.
v Evaluate as a Python literal.
```
This will leave an extra `,` at the end of the string, which will wrap the whole object in a tuple, but this is harmless, because the tuple will be summed, and so have a value equal to its element.
Now that the string is parsed, we must find its value. This is done using a user defined function, `y`, which is called on the parsed object. the function is defined as follows:
```
L?*F+1yMbqb+YbsyMb
L Define a function, y(b), which returns the following:
? qb+Yb We form a ternary whose condition is whether the input, b,
equals the inputplus the empty list, Y. This is true if
and only if b is a list.
yMb If so, we start by mapping y over every element of b.
*F+1 We then take the product of these values. The +1 ensures
that the empty list will return 1.
yMb Otherwise, we start by mapping y over every element of b.
s Then, we sum the results.
```
[Answer]
# Emacs lisp, 94
The format looks very lispy, so I thought a simple transformation might work:
```
(defun e()(format-replace-strings'(("("."(+")("["."(*")("]".")")))(eval(read(buffer-string))))
```
The intermediate format looks something like (for the example in the question):
```
(+(*)(+(+))(+(*)(*))(*(+))(*(+(*(*)(*))(*)(*))(+(*)(*))))
```
We're helped by the fact that addition and multiplication already do what we want with an empty argument list.
Degolfed, and interactive, for you playing pleasure:
```
(defun paren_eval()
(interactive "*")
(format-replace-strings '(("(" . "(+")
("[" . "(*")
("]" . ")")))
(eval (read (buffer-string)))
)
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 111 bytes
```
[\([](1+x)[]\)]
$1
\[]
1x
\(\)
x
(\[a*)1(?=1*x1*x)
$1a
a(?=a*x(1*)x)
$1
(\[1*x)1*x
$1
)`(\(1*)x(?=1*x)
$1
[^1]
<empty line>
```
Gives output in unary.
Each line should go to its own file but you can run the code as one file with the `-s` flag. E.g.:
```
> retina -s brackets <input_1
111111111
```
Explanation comes later.
[Answer]
# Java, 349 characters
A simple recursive approach. Expects the string to be the first argument used to call the program.
```
import java.util.*;class K{int a=0,b;String c;public static void main(String[]a){K b=new K();b.c=a[0];System.out.print(b.a());}int a(){switch(c.charAt(a++)){case'(':b=0;for(int a:b())b+=a;break;case'[':b=1;for(int a:b())b*=a;}a++;return b;}List<Integer>b(){List d=new ArrayList();char c;while((c=this.c.charAt(a))!=']'&&c!=')')d.add(a());return d;}}
```
Expanded:
```
import java.util.*;
class K {
int a =0, b;
String c;
public static void main(String[] a){
K b = new K();
b.c = a[0];
System.out.print(b.a());
}
int a(){
switch (c.charAt(a++)){
case '(':
b =0;
for (int a : b())
b += a;
break;
case '[':
b =1;
for (int a : b())
b *= a;
}
a++;
return b;
}
List<Integer> b(){
List d = new ArrayList();
char c;
while ((c= this.c.charAt(a)) != ']' && c != ')')
d.add(a());
return d;
}
}
```
[Answer]
# Perl 5, 108
Done as an interpreter rather than rewrite-and-eval. Not a great showing, but fun to write anyway.
```
push@s,/[[(]/?[(ord$_&1)x2]:do{($x,$y,$z,$t)=(@{pop@s},@{pop@s});
[$t?$x*$z:$x+$z,$t]}for<>=~/./g;say$s[0][0]
```
Un-golfed:
```
# For each character in the first line of stdin
for (<> =~ /./g) {
if ($_ eq '[' or $_ eq '(') {
# If it's an opening...
# ord('[') = 91 is odd, ord('(') = 40 is even
push @stack, [ ( ord($_) & 1) x 2 ];
# so we will push [1, 1] on the stack for brackets and [0, 0] for parens.
# one of these is used as the flag for which operator the context is, and
# the other is used as the initial (identity) value.
} else {
# otherwise, assume it's a closing
($top_value, $top_oper) = @{ pop @stack };
($next_value, $next_oper) = @{ pop @stack };
# merge the top value with the next-to-top value according to the
# next-to-top operator. The top operator is no longer used.
$new_value = $next_oper
? $top_value * $next_value
: $top_value + $next_value
push @stack, [ $new_value, $next_oper ];
}
}
say $stack[0][0]; # print the value remaining on the stack.
```
[Answer]
# Python, 99
I tried a variety of methods but the shortest I could get was basically just a replacement and eval. I was pleasantly surprised to find that I could leave all the trailing `,`s, as Python can parse `[1,2,]` and the final trailing comma just puts the whole thing in a tuple. The only other non-straightforward part would be the `ord(c)%31%7` to seperate out the different characters (it evaluates to `2`,`3`,`1`,`0` for `(`,`)`,`[`,`]` respectively)
```
F=lambda s:eval(''.join(["],1),","reduce(int.__mul__,[","sum([","]),"][ord(c)%31%7]for c in s))[0]
```
[Answer]
# Clojure - 66 bytes
Notice that `([] (()) ([] []) [()] [([[] []] [] []) ([] [])])` is a valid Clojure form. So:
```
#(letfn[(g[x](apply(if(list? x)+ *)(map g x)))](g(read-string %)))
```
* This is an anonymous function taking a string, reading it and giving to `g`.
* The local `g` function apply `+` or `*` to the result of the invocation of `g` on sub-elements of its arguments.
* The base case of the recursion is a little subtle: it is reached when `x` in an empty sequence; `(map g x)` returns `nil`, and `apply` returns the neutral value for the operation.
[Answer]
# Java, 301
a bit of a different approach than TheNumberOne's answer, although mine is also recursive in nature. Input is taken from the command line. The void method saves a few bytes when removing the characters that are no longer needed.
```
enum E{I;String n;public static void main(String[]r){I.n=r[0];System.out.print(I.e());}int e(){int v=0;if(n.charAt(0)=='('){for(s("(");n.charAt(0)!=')';)v+=e();s(")");}else if(n.charAt(0)=='['){v=1;for(s("[");n.charAt(0)!=']';)v*=e();s("]");}return v;}void s(String c){n=n.substring(1+n.indexOf(c));}}
```
expanded:
```
enum EvaluatingParenthesesAndBrackets{
AsIntegers;
String input;
public static void main(String[]args){
AsIntegers.input=args[0];
System.out.print(AsIntegers.evaluate());
}
int evaluate(){
int value=0;
if(input.charAt(0)=='('){
for(substringAfterChar("(");input.charAt(0)!=')';)
value+=evaluate();
substringAfterChar(")");
}
else if(input.charAt(0)=='['){
value=1;
for(substringAfterChar("[");input.charAt(0)!=']';)
value*=evaluate();
substringAfterChar("]");
}
return value;
}
void substringAfterChar(String character){
input=input.substring(1+input.indexOf(character));
}
}
```
[Answer]
# Python, ~~117~~ ~~110~~ 109 bytes
```
def C(s,p=[0]):
m=r=s[p[0]]=='[';p[0]+=1
while s[p[0]]in'[(':t=C(s,p);r=r*t*m+(r+t)*(1-m)
p[0]+=1;return r
```
One aspect I was struggling with is that the function basically has two return values: the product/sum, and the new position in the string. But I need a function that returns only the result, so returning a tuple does not work. This version uses a "reference" argument (list with one element), to pass the position back from the function.
I have a shorter version (103 bytes) that uses a global variable for the position. But that will only work on the first call. And a function that only works once seems a bit fishy. Not sure if it would be acceptable for code golf.
The algorithm is straightforward recursion. I tried a number of variations for the expression that updates the product/sum. I came up with a few versions that were exactly the same length, but none of them shorter.
I sort of expected that the approach that turns this into an expression that gets evaluated would probably win. But as they say: "To iterate is human, to recurse divine."
[Answer]
## JavaScript (ES6), 116 bytes
```
s=>+[...s].reduce((t,c)=>((x=c==']')||c==')'?t[1].push(t.shift().reduce((a,b)=>x?a*b:a+b,+x)):t.unshift([]),t),[[]])
```
]
|
[Question]
[
Note: the title was misspelled intentionally.
Given a string s, swap the first vowel runs of every 2 words. For this challenge, y is considered a vowel.
For example, given an input of "great day sir":
```
1. Input: "great day sir"
2. Identify pairs of words: "[great day] [sir]" (No word for sir to pair with)
3. Identify the first vowel runs in each word: "[gr[ea]t d[ay]] [s[i]r]"
4. Swap the vowel runs in each pair: "[gr[ay]t d[ea]] [s[i]r]"
5. Return/print: "grayt dea sir"
```
When there are vowel runs of different lengths, you still swap the whole runs. When a word has more than one vowel runs, you still only swap the first one. When the first or second word of a pair of words does not have a vowel, then you do not swap the vowels for those words.
You may assume that the input only consists of one case of alphabetic letters and the literal space or another constant delimiter.
Standard methods of I/O, standard loopholes apply. Leading/trailing whatevers are okay.
**Test cases:**
```
Input -> Output
"great day sir" -> "grayt dea sir"
"ppcg is the best" -> "ppcg is the best" (When there is no vowel to swap, don't swap vowels."
"this is a test case" -> "this is e tast case"
"loooooooooooooong word" -> "long woooooooooooooord"
"great night" -> "grit neaght"
"anything goes" -> "oenything gas"
"qwrtpsdfghjklzxcvbnm aaaaaaaa hi there" -> "qwrtpsdfghjklzxcvbnm aaaaaaaa he thire"
"this is a long test case in case you could not tell" -> "this is o lang tast cese an cise ou cyould net toll"
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~42~~, 41 bytes
```
ò2Eá
òͨ[aeiouy]«©¨ƒ ƒ©¨[aeiouy]«©/³²±
Íî
```
[Try it online!](https://tio.run/##K/v///AmI9fDC7kObzrce2hFdGJqZn5pZeyh1YdWHlpxqFnhUDOIgSysf2jzoU2HNnId7j287v//xKTi/JzSktScSoXi0qJUAA "V – Try It Online")
Hexdump:
```
00000000: f232 45e1 0af2 cda8 5b61 6569 6f75 795d .2E.....[aeiouy]
00000010: aba9 a883 2083 a9a8 5b61 6569 6f75 795d .... ...[aeiouy]
00000020: aba9 2fb3 b2b1 0acd ee ../......
```
Explanation:
```
ò ò " Recursively:
2E " Move to the end of two words forward
á<cr> " And append a newline
```
This will put all groups of two words on their own line, for example:
```
this is
a long
test case
in case
you could
not tell
```
Now we run some fancy regex-magic:
```
Í " Globally substitute
¨[aeiouy]«© " A vowel (capture group 1)
¨<131> " Followed by as few characters as possible, then a space
<131>© " Followed by as few characters as possible (capture group 2)
¨[aeiouy]«© " Followed by a vowel again
/ " With:
³²± " Capture groups '3', '2', '1'
Í " Remove all:
î " Newlines
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~39~~ 37 bytes
They said it would be ugly, but I didn't listen... and it was:
```
¸ò ®efQ="%y+" ?Z£XrQZg°T fQP PÃ:ZÃc ¸
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=uPIgrmVmUT0iJXkrIiA/WqNYclFaZ7BUIGZRUCBQwzpaw2MguA==&input=IlN3YXAgdGhlIHZvd2VscyIgLVE=)
### Explanation
```
¸ ò ® efQ="%y+" ?Z£ XrQ Zg° T fQ P PÃ :ZÃ c ¸
UqS ò mZ{Zef"%y+" ?ZmXYZ{Xr"%y+"Zg++T f"%y+"P P} :Z} c qS
Implicit: U = input string, such as "abc def ghi jkl mno"
UqS Split on spaces, splitting into words. ["abc","def","ghi","jkl","mno"]
ò Group into runs of two items. [["abc","def"],["ghi","jkl"],["mno"]]
mZ{ For each pair Z:
Zef"%y+"? If not every item contains a run of vowels (%y = [AEIOUYaeiouy]),
:Z return Z. [ ["ghi","jkl"] ]
ZmXYZ{ Otherwise, for each item X in Z:
Xr"%y+" Replace each run of vowels with
Zg++T the item at the next index in Z, [["def","abc"] ["mno"]]
f"%y+"P but only the first run of vowels. [["e", "a" ] ["o" ]]
P Replace only for the first match. [["ebc","daf"] ["mno"]]
}
} [["ebc","daf"],["ghi","jkl"],"mno"]]
c Flatten back into a single array. ["ebc","def","ghi","jkl","mno"]
qS Re-join on spaces. "ebc daf ghi jkl mno"
Implicit: output result of last expression
```
[Answer]
# JavaScript (ES6), ~~62~~ ~~106~~ ~~98~~ 101 bytes
```
s=>s.match(/(\w+)( (\w+))?/g).map(m=>m.replace(/([aeiouy]+)(\w* \w*?)([aeiouy]+)/g,'$3$2$1')).join` `
```
```
f=
s=>s.match(/(\w+)( (\w+))?/g).map(m=>m.replace(/([aeiouy]+)(\w* \w*?)([aeiouy]+)/g,'$3$2$1')).join` `
;
[
"great day sir",
"ppcg is the best",
"this is a test case",
"loooooooooooooong word",
"great night",
"anything goes",
"qwrtpsdfghjklzxcvbnm aaaaaaaa hi there",
].map(f).map(s=>console.log(s))
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 65 bytes
```
((\w*?)([aeiouy]+)(\w* \w*?)([aeiouy]+)|(\w+ ))(\w*)
$2$5$4$3$6$7
```
[Try it online!](https://tio.run/##XU3LDsIgELzzFXvgUPTm8@iHqAcKCChCha21xn9Hao1RJ5NsZiY7ExVaz3Ouql032bBqy5UNbb@fssGAf/NR3CmwV8gIndElXdA5XdF1zjoqjiB5D8lG0jRCg02ARkGtEhI0RRVywCJB8KSICz/wGroQJRmbvNUGCfd9@SyJDiqRSxexSfKgzfHk7jdxrf0Z@Btg7DAX1deWG0o/g2D9ePvQggitk@ADlty5Jw "Retina – Try It Online") Includes test cases. I wanted to use a conditional group reference but I couldn't get it to work in 66 bytes let alone 65 or less.
[Answer]
# [Retina](https://github.com/m-ender/retina), 50 bytes
```
\S+ \S+
$&¶
%O$^`(?<=\b[^aeiouy]*)[aeiouy]+
$`
¶
```
[Try it online!](https://tio.run/##VU0xDsIwDNz9Cg8tKvAFECMjA2OhatqGJBCSkrhAeRgP4GMhFRWCky37dPad46QMC2m2LsNuO8ehIZm8npBukqLMVovlrsoLxpXt@v1smo/bHJIS4lUIwnFG2LAevXLQtrVA5ZEkx4p7ApKRxWJIkWLNPAdt/2AE3qxr4ONklJAEzPTxMyrCcg@Xm6PWNwchjyf9uNfXypyRjUCphjjHf7L0YPoNRGU@s7cd1rbTDRpLUdf6DQ "Retina – Try It Online")
−2 bytes thanks to Martin.
* First step is splitting each word pair to its own line (`¶` is newline). This allows us to use `.*` within a pair of words.
* Next, for each line we find the first vowel block in each word, and sort them by position in descending order.
[Answer]
# [Python 2](https://docs.python.org/2/), 148 bytes
```
from re import*
v="([aeiouy]+)"
print sub(r"(\w+)(?: (\w+))?",lambda m:sub(v+"(.* .*?)"+v,lambda g:''.join(g.groups()[::-1]),m.group()),raw_input())
```
[Try it online!](https://tio.run/##NU5LCoMwFNx7ikc2JmqFdhkoHsRKeaKNKc2HZ6Lk9DZt6azmxzA@hcXZy3E8yBmgGbTxjkJVbFfGe5y1i2moBSs8aRtgjSMnxm97LXgn4UtEx5oXmnFCMPJT2GrG2wraqhOs3v6ZkmXZPp22XLWKXPQrF72Up/MgGvNzuBAN4X7X1seQxXEomjHAhAlWTbC4HTB/TC7ClJcUjBmAGaBHhPQG "Python 2 – Try It Online")
Code Golfing is getting addictive!
>
> Sections off pairs of words, then grabs the 2 groups of vowels and the string in between, reverses the order and uses that as the [substitute](https://docs.python.org/2/library/re.html#re.sub).
>
>
>
[Answer]
## Perl, 58 bytes
**57 bytes code + 1 for `-p`.**
```
$v="([aeiouy]+)";s!\w+ \w+!$&=~s/$v(.* .*?)$v/$3$2$1/r!ge
```
-2 bytes thanks to [@Dada](https://codegolf.stackexchange.com/users/55508/dada)!
[Try it online!](https://tio.run/##VU3LbgIxDLznK7zSCvFQuyoVR8SHtBzCrklSQhxiL9vtgU9vGgSqYOSRNR55JmLyq5y5@hwWUFjVk/WFm@mHRkf9uF3Mpq/zDRTOHm5N/V4v67cmVQZzNgm1QKdHYJdUjK0BxyAWYYcsSmxRZTRIkdBqRuXpCcHAQKlTt6TgjBWlw1g@i2MIWZ2GJJG7vbFfB//z3Z534Qj6DrDuWpfwoctfQ/8LwYXbHqmHlnrfQSApvve/FMVR4PwS/wA "Perl 5 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 177 173 171 169 bytes
```
unwords.s.words
s(x:y:z)=maybe[x,y]id(do(a,b)<-k x;(c,d)<-k y;j[b c,d a])++s z
s x=x
v=(`elem`"aeiouy")
j=Just
k s=do(a,(x:y,r))<-j$span v<$>break v s;j(x:y,\n->a++n++r)
```
[Try it online!](https://tio.run/##VVBda4NAEHz3VwwmDx5qfkCSC4RSAiUtgdInI80ZD79PuT1TTelvtxf71GVhd2aYWdhcUCXrevoOFzju3w4f@8Mznk4nLMIfR/Pz1KuvVqe0otU8HfKG9bi@M96IMZHREIxxkXpp64kgYduwwrDxrkE6r@OmjBJYBBEz3yfcHcLAB@fGvYusZXNxhSzafnSZU/KXnoxTgfgc9jgTaGZzyiV1QuG2Xe4SLUWFG2hTzvpZhTvh@8r3NZsaUShwNKJ7/YTX9ebd6KPCCpohcjNrNUjFCCq0G7hdd81QEEwukUgyljK5xbYFjCVwFSQtW7f/SmV4PMIKf4mqyHLjxtMv "Haskell – Try It Online")
This is a direct shortening of the following naïve solution, so there should something much better around here:
```
swapvowels :: String -> String
swapvowels = unwords . swapPairs . words
swapPairs :: [String] -> [String]
swapPairs (word1:word2:rest) =
case (,) <$> extractVowels word1 <*> extractVowels word2 of
Just ((vowels1, rebuild1), (vowels2, rebuild2))
-> [rebuild1 vowels2, rebuild2 vowels1] ++ swapPairs rest
Nothing -> [word1,word2] ++ swapPairs rest
swapPairs rest = rest
extractVowels :: String -> Maybe (String, String -> String)
extractVowels s = do
let isVowel l = l `elem` "aeiouy"
(a,b) <- Just $ break isVowel s
(w@(_:_),r) <- Just $ span isVowel b
return (w, \n -> a ++ n ++ r)
```
[Answer]
# Ruby, 87+1 = 88 bytes
Uses the `-p` flag.
```
gsub(/(\w+) (\w+)/){_,a,b=*$~;a[r=/[aeiouy]+/]&&b[r]?a.sub(r,b[r])+' '+b.sub(r,a[r]):_}
```
[Try it online!](https://tio.run/##KypNqvyvrFgEpBR0C/6nF5cmaehrxJRrayqASX3N6nidRJ0kWy2VOuvE6CJb/ejE1Mz80spYbf1YNbWk6KJY@0Q9kK4iHRBHU1tdQV07CSqSCBKxiq/9/7@wvKikoDglLT0jKzunqiK5LCkvVyERChQyMhVKMlKLUgE "Ruby – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~363~~ 304+25 bytes
*-34 bytes thanks to @KevinCruijssen*
Golfed:
```
l->{String s[]=l.split(" "),a,b;Pattern p=Pattern.compile("[aeiouy]+");for(int i=0;i<s.length-1;i+=2){Matcher m=p.matcher(s[i]),n=p.matcher(s[i+1]);a=m.find()?m.group():null;b=n.find()?n.group():null;if(a!=null&b!=null){s[i]=s[i].replaceFirst(a,b);s[i+1]=s[i+1].replaceFirst(b,a);}}return l.join(" ",s);}
```
[Try it online!](https://tio.run/##dVPBcqMwDD03X6HlsIM3xN3usZTurbfOdKbHTA4GDJga22uLpGwm354VgWaadFbDIKEnS/KTaMVWrKyTpi3fjqpz1iO05OM9Ks29rOU7/5HC7S28CIJsBdhIyAeUq8L2BheLL4eq3hSorOFPs5EuXJ9rVUChRQjwLJSB/QJIZn9AgaS2VpXQERq/olemXm9A@DqwOXiUj5QPU0QyqUeoIIOjXj3uJweE9SbTPDitMI4gYolI8vRFIEpvwGWzxQvbOaVlHK2FVLYfNsuIpZX1sTIIKvuZqofAtTQ1Nqu7VC2zX2z/LLBopIcuc7yb7Dis1YYl5tKzvNuwVGQdr5QpY/a747W3vYvZvem1TvPMfCDmElFVLL5lo/k9nzTbjxWy8UUzcVoU8kn5gDFdi6VTrWxSl3ieCJYeDl5iTxfXvLXELhGSBHIfb9LFmdnTVGzeEpFG7k6fMSP85jwLZVyPgfA9nE@NEtVeCoRSDBCUj5JL0LmiBhWmtZEBr3FsCKRHABIKhQjyOkTbC6Hx7qwvKermU3mj6oaSX7UmzEAF6ERtZfiC/tl5dKGs6qZ903/fi21uOhCzQKPGpr38f8d67OXcNhE06cH2QD@HLsFYJFzr6Jzh8IlyWjSYV30iF@5nktl0tdchoOy47ZE7ikJt4ooL5/QQn@IYDeiUdHE4/gM "Java (OpenJDK 8) – Try It Online")
Ungolfed:
```
String swapVowels(String line) {
String[] parts = line.split(" ");
Pattern pattern = Pattern.compile("([aeiouy]+)");
for (int i = 0; i < parts.length - 1; i += 2) {
Matcher matcherL = pattern.matcher(parts[i]), matcherR = pattern.matcher(parts[i + 1]);
String vowelRunL = matcherL.find() ? matcherL.group() : null, vowelRunR = matcherR.find() ? matcherR.group() : null;
if (vowelRunL != null & vowelRunR != null) {
parts[i] = parts[i].replaceFirst(vowelRunL, vowelRunR);
parts[i + 1] = parts[i + 1].replaceFirst(vowelRunR, vowelRunL);
}
}
return String.join(" ", parts);
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 198 196 192 bytes
* Saved 6 bytes: thanks to [Zachary T](https://codegolf.stackexchange.com/users/55550/zachary-t) : `if(m and n)` to if m and n & removed unwanted r for regex string, index i starting from 1 instead of 0
```
from re import*
s=search
a=input().split()
v="[aeiouy]+"
j=1
while j<len(a):
i=j-1;m=s(v,a[j]);n=s(v,a[i])
if m and n:a[i]=sub(v,m[0],a[i],1);a[j]=sub(v,n[0],a[j],1)
j+=2
print(' '.join(a))
```
[Try it online!](https://tio.run/##LY/NbsMgEITvPMUql5jmR3V7i8uTWD5QSsoi2EWAU/nBc3ZwE2mlWX2zq9GkpTqmz3W9Zo6QLWBMnOubKKpYnY0TWiGluXbyXFLApuKmdqO2yPMyHXbCq178OQwW/Few1Gl5EYDKn/ohqtLdjnr0kxzoteMkm32FCJp@gC4bUWX@bmYc36f/i2Mvh@3rxenJ/cYF@IP6ECkj1W4P@7Nn3DLlulaHBdpoCEy/UG2pYHRpleipC89geA4tlmvzQ7gTn4w2zj4A "Python 3 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `S`, 33 bytes
```
⌈2ẇƛƛ≬k∪$cḊ:‡hAǑ";:vƒiṘ¨vJƛ÷Ȧṅ;;f
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJTIiwiIiwi4oyIMuG6h8abxpviiaxr4oiqJGPhuIo64oChaEHHkVwiOzp2xpJp4bmYwqh2Ssabw7fIpuG5hTs7ZiIsIiIsInRoaXMgaXMgYSBsb25nIHRlc3QgY2FzZSBpbiBjYXNlIHlvdSBjb3VsZCBub3QgdGVsbCJd)
Really really bad, I couldn't find a single good piece of this code
]
|
[Question]
[
## What?
Let's say I have this graph:
```
1
\
\
2 3
\ /
\ /
4
```
I can represent it in 2 ways:
1. A list of connected vertices. `[[1,3],[2,4],[3,4]]`
2. A boolean matrix which shows where edges are:
```
c |1 2 3 4
--|-------
1 |0 0 1 0
2 |0 0 0 1
3 |1 0 0 1
4 |0 1 1 0
----- or -----
[[0,0,1,0],[0,0,0,1],[1,0,0,1],[0,1,1,0]]
```
## Task
* Your code should take input in the form of 1 (as a vertex list) and output it as 2 (as an adjacency matrix)
* The graph is not directed (aka it is an undirected graph).
* You can also accept input which is 0-indexed. For example: `[[0,2],[1,3],[2,3]]`
* This is code golf, shortest answer wins.
* You can also output 2 different values instead of 1 and 0.
## Test cases
```
[[1,2],[3,4]] -> [[0,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,0]]
[[1,3],[2,4],[3,4]] -> [[0,0,1,0],[0,0,0,1],[1,0,0,1],[0,1,1,0]]
[[1,2],[2,3],[5,6]] -> [[0,1,0,0,0,0],[1,0,1,0,0,0],[0,1,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,1],[0,0,0,0,1,0]]
[[1,2]] -> [[0,1],[1,0]]
[[1,2],[4,5]] -> [[0,1,0,0,0],[1,0,0,0,0],[0,0,0,0,0],[0,0,0,0,1],[0,0,0,1,0]]
[[4,5]] -> [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,1],[0,0,0,1,0]]
[[4,5],[2,1]] -> [[0,1,0,0,0],[1,0,0,0,0],[0,0,0,0,0],[0,0,0,0,1],[0,0,0,1,0]]
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 6 bytes
```
¯⍸⊢,⌽¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//9D6R707HnUt0nnUs/fQiv9pj9omPOrte9Q31dP/UVfzofXGj9omAnnBQc5AMsTDM/h/NZABVrXmUddiCDvtUccMIMsr2N/vUe/W2kMrFNSjow11jGJ1oo11TGJj1SF8YyDfCMhHFTUCi4LkTHXMkESR5U10TKF8CAsA "APL (Dyalog Extended) – Try It Online")
When given an adjacency matrix, `⍸` gives the edge list (indices of 1's). Therefore the inverse `¯⍸` solves this challenge when we add the reverse edges to the input list.
I used Extended here for the short syntax for inverse functions and because the inverse of `⍸` doesn't require its input to be sorted.
[Answer]
# [R](https://www.r-project.org/), ~~46~~ 43 bytes
*Edit: -3 bytes thanks to pajonk*
```
function(x,m=0*diag(max(x))){m[x]=1;m|t(m)}
```
[Try it online!](https://tio.run/##hZBNCsIwEEb3nqLgZiIjJP1xI/UiIlJTrV0klRAloJ691rTQVNN2NTMJ877HqJpX8nFW@lio7HZN68tdcl1WEgyKlK7yMitAZAYMIeQp9uaQsq14aRDkPVwFdSplDhwYhgQ5RBg3K8EyWO8CAIoMKVKCYKvtbEXWdc07IYsxZPRFhg3SQ253XR5zyGyGHLZkG5Dg5t/Z8Xbd3T@K1DsxZ/JZ6M5gkNlmzRnHmPhU@wMPVVyR/lQjSr/sad4Uu/4A "R – Try It Online")
Input is 2-column matrix with each row representing 2 connected vertices; output is matrix of `TRUE` and `FALSE` to indicate pairwise connections.
We could save 2 more bytes [for 41 bytes](https://tio.run/##hZDPCsIwDIfvPsXASwIZtPvjReaLiMjsdO7QTkaVgvjsc3aDddq5U5KWfL@PNK2o1ePc6GPZ5Ldr1l7uSuiqVmBIZkWVlyBzAwYRn3JvDhnfylCDxNd0EZpTpQoQwClCEhBT0q0E6yDcBQCMODFiSGCr7WwlPnTdO@JqDhl/kFGH9JD7XZfHHTJfIEc92QaktPl1drxdd/ePEfNO3Jl8FnowmGT2WUvGCaU@1fHAUxVXZDzVjNI3@z/vH7t9Aw) by returning a matrix of falsy (zero) and truthy (either `1` or `-1`) to indicate connections.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
;UŒṬ
```
A monadic Link that accepts a list of pairs of positive integers (the vertex list) and yields a list of lists of `1`s and `0`s (the adjacency matrix).
**[Try it online!](https://tio.run/##y0rNyan8/9869OikhzvX/P//PzraUMcoVifaSMcYSJrqmMXGAgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9869OikhzvX/D/c7m79qHG7jgOIOyNSM/L//@joaEMdo1idaGMdk9hYHQUQ1xjINQJyUQSNwIIgKVMdM4QgkqyJjimEC2bEAgA "Jelly – Try It Online").
### How?
```
;UŒṬ - Link: list of pairs of positive integers, V
U - reverse each pair in V
; - V concatenate that
ŒṬ - multi-dimensional array with 1s at those coordinates and 0s elsewhere
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/index.html), ~~38~~ 16 bytes
*Edit: -22 bytes thanks to a change-of-approach provoked by ~~goading~~ clever hint from [ovs](https://codegolf.stackexchange.com/users/64121/ovs).*
*Edit2: changed `+` to `∨` (logical OR) so that if there are any vertices connected to themselves, which would appear on the output matrix diagonal, they are still represented as `1` and not `2`; thanks to Neil for spotting this*
```
+⟜⍉⊢∊˜·↕2⥊1+⌈´∘∾
```
[Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=Q2VsbHMg4oaQIOKIqOKfnOKNieKKouKIisucwrfihpUy4qWKMSvijIjCtOKImOKIvgpDZWxscyDin6ggMeKAvzMsIDLigL80LCAz4oC/NCwgMOKAvzAg4p+pCg==)
Uses zero-indexed input.
The [BQN](https://mlochbaum.github.io/BQN/index.html) `Range` (`↕`) function has the behaviour: "if its argument is list of numbers, then it returns an array of list indices" ([here](https://mlochbaum.github.io/BQN/doc/range.html)).
So we just use `↕` to construct an array filled with indices, check whether each index is present in the input, and then combine the result with its transpose (to fill-in the elements corresponding to the same connections the other-way-around).
```
∨⟜⍉⊢∊˜·↕2⥊1+⌈´∘∾ # full train:
∾ # flatten the input connections,
⌈´∘ # get the maximum,
1+ # add 1 (since 0-based indexing),
2⥊ # duplicate it,
·↕ # and construct an array of 0-based 2d-coordinates;
˜ # now, for each 2d-coordinate,
⊢∊ # check if it's in the input (1) or not (0);
∨ # finally, logical-OR the result
⟜⍉ # with the transpose of itself
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Z©LãδQ.«~®ôDø~
```
The lack of builtins to check if a list is inside another list in 05AB1E is as always pretty dang annoying.. :/
[Try it online](https://tio.run/##yy9OTMpM/f8/6tBKn8OLz20J1Du0uu7QusNbXA7vqPv/PzraUMc4VifaSMcESBoDyVgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/qEMrfQ4vPrclUO/Q6rpD6w5vcTm8o@6/zv/o6GhDHaNYnWhjHZPYWB0FENcYyDUCclEEjcCCIClTHTOEIJKsiY4phAtmxAIA).
**Explanation:**
```
Z # Push the flattened maximum of the (implicit) input
© # Store it in variable `®` (without popping)
L # Pop and push a list in the range [1,®]
ã # Cartesian product to get all pairs of this list
δ # Apply double-vectorized with the input-pairs:
Q # Check which pairs are equal
.« # Then reduce this list of lists by:
~ # Bitwise-OR on the bits at the same positions
®ô # Split this list into parts of size `®`
D # Duplicate this matrix of bits
ø # Zip/transpose; swapping rows/columns
~ # Bitwise-OR the bits at the same positions again
# (after which the result is output implicitly)
```
[Answer]
# [Python 3](https://www.python.org), ~~90~~ ~~88~~ ~~87~~ 86 bytes
*thanks to @Kevin Cruijssen for pointing out my mistake*
*thanks to @ophact for saving 2 bytes*
*thanks to @loopy walt for saving 1 byte*
*thanks to @Jonathan Allan for saving 1 byte*
```
lambda a:(r:=range(max(sum(a,[]))+1)and[[[i,j]in a or[j,i]in a for j in r]for i in r]
```
The input is a list of lists (as in the example).
# ~~85~~ ~~84~~ 83 bytes
*thanks to @loopy walt for saving 1 byte*
*thanks to @Jonathan Allan for saving 1 byte*
```
lambda a:(r:=range(max(sum(a,()))+1))and[[not{(i,j),(j,i)}&a for j in r]for i in r]
```
The input is a set of tuples.
[Answer]
# Mathematica 12, 15 bytes
```
AdjacencyMatrix
```
lol.
Mathematica can accept lists of tuples as edges in a graph, so
```
AdjacencyMatrix@{{1, 2}, {2, 3}, {3, 4}, {4, 1}}
```
produces
```
{{0, 1, 0, 1},
{1, 0, 1, 0},
{0, 1, 0, 1},
{1, 0, 1, 0}}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
≔⊕⌈Eθ⌈ιηEη⭆η∨№θ⟦ιλ⟧№θ⟦λι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DMy@5KDU3Na8kNUXDN7EiM7c0F0gXaBTqKMC4mZpAoKOQoWnNFVCUmVcCls/QUQguAfLSoRz/Ig3n/FKgJFBjdKaOQk4sUAtCJEdHITMWZI6m9f//0dHRBjpGsTrRhjrGQNIISMbG/tctywEA "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Outputs the boolean matrix as a string array of `0` and `1`s for convenience. Explanation:
```
≔⊕⌈Eθ⌈ιηEη
```
Calculate the size of the array.
```
⭆η∨№θ⟦ιλ⟧№θ⟦λι
```
For each cell of the array, check whether it or its transpose exists within the input list.
[Answer]
# [Factor](https://factorcode.org/) + `math.matrices`, 75 bytes
```
[ 1 swap dup mmax 1 + dup 0 <matrix> [ matrix-set-nths ] keep dup flip m+ ]
```
[](https://i.stack.imgur.com/sKhwC.gif)
## Explanation
* Create a square zero-matrix large enough to accommodate the maximum value in the input.
* Set the (zero-indexed) input coordinates in the matrix to one.
* Add the resulting matrix to its transpose.
```
! { { 0 1 } }
1 ! { { 0 1 } } 1
swap ! 1 { { 0 1 } }
dup ! 1 { { 0 1 } } { { 0 1 } }
mmax ! 1 { { 0 1 } } 1
1 ! 1 { { 0 1 } } 1 1
+ ! 1 { { 0 1 } } 2
dup ! 1 { { 0 1 } } 2 2
0 ! 1 { { 0 1 } } 2 2 0
<matrix> ! 1 { { 0 1 } } { { 0 0 } { 0 0 } }
[ matrix-set-nths ] keep ! { { 0 1 } { 0 0 } }
dup ! { { 0 1 } { 0 0 } } { { 0 1 } { 0 0 } }
flip ! { { 0 1 } { 0 0 } } { { 0 0 } { 1 0 } }
m+ ! { { 0 1 } { 1 0 } }
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 98 bytes
```
x=>[...Array(eval(`1+Math.max(${x})`))].map((_,i,t)=>t.map((_,j)=>x.some(v=>v==i+[,j]|v==j+[,i])))
```
[Try it online!](https://tio.run/##rZI9T8MwEIZ3fkUGBptc3bgfLMiRWJGAgTFYxG2dkihtKsdEqSi/PVySorgFwcJ0H/Y999p6M1WpcmnSnR1ti5VuEtHUIowYY7fGqD3RlcpJzP17ZV/ZRtXk8r3@oDGlEqsdIS@QgqUitF9lhkXNymKjSSXCSojUjyCTB8wyzFJJKW1uvPgiijhMJERTmEnpjUIvigLgEECAzS52WReBHzPsS9mNTrEzwdEzQH/FHeMOgDuASQdoMXO4PlPgqHCVuGcBBD9W3KncZcOCHuyomMH82/7hD075Ln145hF3Avp9@G9Q@zv8P3TFzOhdrpaajAm7oi2wjeM1eOgXBQt0zLLYlkWuWV6sidGluHt6fGClNel2nSZ7kvQ@VAPpeeUjwKLxRhwdRYcTa970IVF5qfsLfjdqKQWvJYsF@u8T "JavaScript (Node.js) – Try It Online")
:(
[Answer]
# [Haskell](https://www.haskell.org/), ~~66~~ 63 bytes
```
f x|r<-[1..maximum$id=<<x]=[[elem[i,j]x||elem[j,i]x|j<-r]|i<-r]
```
[Try it online!](https://tio.run/##rZA9D4IwEIZ3fsUNDpocpMWPCUYHBze35gaMEIsUCGrCwH/HUgi2iTEOdrhe767Pe3fX5H5Li6LvM2i7JvIFDwKVtFI91UJe4ihqKRYiLVIlJObUdp3xc5TazyO/oU4Otj9XVXGqDuUDYlBJDcvBZE2l9uVTrTxPJbIcU0dY1o3UhQG8PwWQrUB4AEJwDAnFGjdECOPxfR1nyJEh0zlzG8/cyCdPx4kmxlrHQs2YSRNjrLJ/covBHUZoGANpizuLMenPvdj92DmG7OOLWy9Xb57YnXvUcfra4PbzfuwNubq26nsDM9chOtzvrF@4wx45EfyvX@pf "Haskell – Try It Online")
Uses `True` and `False` for the output.
[Answer]
# [PDL](https://metacpan.org/pod/PDL) (Perl Data Language) 81 chars (the second paragraph)
```
use PDL;
use PDL::NiceSlice;
$_ = [[1,3],[2,4],[3,4]];
$i=pdl($_)-1;
$m=zeroes("$_",$_)for$i->max+1;
$m->indexND($i->glue(1,$i(-1:0))).=1;
print $m;
```
Explanation per line:
* construct indices ndarray, turn 1-based to 0-based
* find highest index+1; make square matrix that size; `""` is to coerce to Perl scalar not ndarray as `zeroes` with ndarray first arg copies its dimensions
* `$i(-1:0)` reverses order of indices in 0th dimension, i.e. symmetrises; `glue(1,...)` adds rows; `indexND` selects the given elements; set them to 1
]
|
[Question]
[
You are given an \$ 25 \times 25 \$ square lattice graph. You are to remove certain nodes from the graph as to *minimize* your score, based on the following scoring system:
Your score will be the \$ \text{number of nodes removed} \$ \$ + \$ the \$ \text{size of the largest connected component} \$. In the smaller \$ 4 \times 4 \$ example below, exactly \$ 5 \$ nodes have been crossed out (removed), and the size of the largest connected component is \$ 4 \$ (top and left components). Therefore the total score is \$ 9 \$.
[](https://i.stack.imgur.com/AQXtv.png)
## Notes
* You should give your score alongside a list of crossed out nodes
* If a program was written to solve this problem, please include it in your answer if possible
* [Here](https://tio.run/##bVHLTsMwELz7K0bi0ISmVls4VQSJCyeOHCJFETKJ07hqN5HjQPn6snaaIqAHv2Z2Z3bX3ZdrWlqfTjd4MaSx2uAJNBzetQUlqDS1ztAWikA48tpaU4lz8B2kZGjuswhlo6wqnbY9WoJWZYO9j7pouEaHdEQzOUPdskNb6QSzbHyVtu17XS3awQUmFoKQwpCLrPp8M9QNLopjsbWqaxJ8mJ7ZvEh4CZ9vOBRW0VZHFG8EQpxUXaepivam/y0TC68w0fmz2ve6wC2IbStdo6r7yCYovZKpYfGAJdjF4jHlbn29E1ReoGCZ2yIvC6Rp6IxR9hkxloLVbrCEpfiBuY1XO2gxccHaj9Xb8zmV4qHLG4v//GLkV0Io6lcsy8eaj@XV@Xhs9wfzrY5NmCLfjU3wZymq@EtcKDkQPhRnk4M6Rv6ahEJMgp0f7jWlbDblrTFPuc7O8u@OOvMAn073IpNSCpnJTEje/U1@Aw) is a program to check your score
This is [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), so the *minimum* score wins!
[Answer]
# 92+41=133
```
.......X.........X.......
........X.......X........
.......X.........X.......
......X.X.......X.X......
.....X...X.....X...X.....
....X.....X...X.....X....
...X.......X.X.......X...
X.X.........X.........X.X
.X.X.......X.X.......X.X.
....X.....X...X.....X....
.....X...X.....X...X.....
......X.X.......X.X......
.......X.........X.......
......X.X.......X.X......
.....X...X.....X...X.....
....X.....X...X.....X....
.X.X.......X.X.......X.X.
X.X.........X.........X.X
...X.......X.X.......X...
....X.....X...X.....X....
.....X...X.....X...X.....
......X.X.......X.X......
.......X.........X.......
........X.......X........
.......X.........X.......
```
Now with 13 regions, all of 41.
# Previous version 93+46=139
```
X...........X...........X
.X..........X..........X.
..X.........X.........X..
...X.......X.X.......X...
....X.....X...X.....X....
.....X...X.....X...X.....
......X.X.......X.X......
.......X.........X.......
......X.X.......X.X......
.....X...X.....X...X.....
....X.....X...X.....X....
...X.......X.X.......X...
XXX.........X.........XXX
...X.......X.X.......X...
....X.....X...X.....X....
.....X...X.....X...X.....
......X.X.......X.X......
.......X.........X.......
......X.X.......X.X......
.....X...X.....X...X.....
....X.....X...X.....X....
...X.......X.X.......X...
..X.........X.........X..
.X..........X..........X.
X...........X...........X
```
8 regions of 46, 4 regions of 41.
[Answer]
# Lower bound: 114
**Notation:** Add 25 points to each side of the grid to produce a 27-by-27 grid with corners missing. Call these additional 100 points \$\mathcal{E}\$. Let \$\mathcal{X}\$ denote the set of deleted points. Say the \$i\$th component has \$c\_i\$ points and is bounded by \$x\_i\$ members of \$\mathcal{X}\$ and by \$e\_i\$ members of \$\mathcal{E}\$.
**Constraints:** First, components that border \$\mathcal{E}\$ border disjoint subsets of \$\mathcal{E}\$, and so
$$\sum\_i e\_i \leq 100.$$
Next, consider the simple polygon with vertices/perimeter at the members of \$\mathcal{X}\$ and \$\mathcal{E}\$ that border the \$i\$th component. By [Pick's theorem](https://en.wikipedia.org/wiki/Pick%27s_theorem), the area of this polygon is
$$A\_i=c\_i + \frac{x\_i + e\_i}{2} - 1.$$
Meanwhile, the octagon with \$\mathcal{E}\$ as vertices/perimeter has area 674. As such,
$$\sum\_i c\_i + \sum\_i\Big( \frac{ x\_i + e\_i }{2} - 1 \Big)
= \sum\_i A\_i
\leq 674.$$
Furthermore, it is [conjectured](https://oeis.org/A261491) (!) that
$$\frac{ x\_i + e\_i }{2} - 1
\geq \frac{1}{2}\Big\lceil \sqrt{8c\_i-4}\Big\rceil.$$
**Optimization:** In our notation, we seek to minimize \$|\mathcal{X}|+\max\_i c\_i\$. It is convenient to write
$$|\mathcal{X}|
= 625 - \sum\_i c\_i.$$
We may relax our optimization to only consider the above constraints:
$$\text{minimize} \quad 625 - \sum\_i c\_i + \max\_i c\_i$$
$$\text{subject to} \quad \sum\_i e\_i \leq 100, \quad
\sum\_i c\_i + \sum\_i\Big( \frac{ x\_i + e\_i }{2} - 1 \Big) \leq 674, $$
$$\frac{ x\_i + e\_i }{2} - 1
\geq \frac{1}{2}\Big\lceil \sqrt{8c\_i-4}\Big\rceil, \quad x,c,e \geq 0.$$
The square root makes this optimization a pain, so we further relax to a sequence of linear programs. To accomplish this, we take
$$X\_k := \sum\_{i:c\_i=k} x\_i,
\quad
E\_k := \sum\_{i:c\_i=k} e\_i,
\quad
z\_k := |\{i:c\_i = k\}|,
\quad
C := \max\_i c\_i.$$
Then for each \$C\in\{1,\ldots,133\}\$, we solve the linear program
$$\text{minimize} \quad 625 - \sum\_k kz\_k + C$$
$$\text{subject to} \quad \sum\_k E\_k \leq 100, \quad
\sum\_k kz\_k + \sum\_k\Big( \frac{ X\_k + E\_k }{2} - z\_k \Big) \leq 674, $$
$$\frac{ X\_k + E\_k }{2} - z\_k
\geq \frac{1}{2}\Big\lceil \sqrt{8k-4}\Big\rceil\cdot z\_k, \quad X,E,z \geq 0.$$
Indeed, we only need to consider \$C\leq 133\$ thanks to [the best known solution](https://codegolf.stackexchange.com/a/204368/85259). Here's an implementation in MATLAB using [CVX](http://cvxr.com/cvx/):
```
vals=[];
for C=1:133;
[C min(vals)]
w = ceil(sqrt(8*(1:C)-4))/2;
cvx_begin quiet
variable X(C)
variable E(C)
variable z(C)
minimize( 625 - (1:C)*z + C )
subject to
sum(E) <= 100
(1:C)*z + sum( (X+E)/2-z ) <= 674
for ii=1:C
(X(ii)+E(ii))/2-z(ii) >= w(ii)*z(ii)
end
X >= 0
E >= 0
z >= 0
cvx_end
vals(end+1)=cvx_optval;
end
```
The minimum value of 113.32 occurs when \$C=41\$. (Curiously, this is the size of the components in [the best known solution](https://codegolf.stackexchange.com/a/204368/85259).) Here's a plot of how the minimum varies with \$C\$:

[Answer]
## Score 80 + 61 = 141
```
........X...........X....
.......X.............X...
........X...........X....
.X.......X.........X.....
X.X.......X.......X......
...X.......X.....X.......
....X.......X...X........
.....X.....X.X.X.......X.
......X...X...X.......X.X
.......X.X.....X.....X...
........X.......X...X....
.......X.........X.X.....
......X...........X......
.....X.X.........X.......
....X...X.......X........
...X.....X.....X.X.......
X.X.......X...X...X......
.X.......X.X.X.....X.....
........X...X.......X....
.......X.....X.......X...
......X.......X.......X.X
.....X.........X.......X.
....X...........X........
...X.............X.......
....X...........X........
```
Found with the help of [this program](https://tio.run/##lVFdS8MwFH1ufkWoL7dQiw6G4J4UFBzbHM5BXsvM2rCsmW0zBNlvr7drtzbNKhoaem/O/TrnruIwXalQFsVU7TncL3cTvs69EXlUXzC482l53SsXX@Y6i0H7dMKTKI9hzvnmQUrwPMTWKqUwGHr0mzhjvd29K7jxqUDEOUIvyU7nizwVSYQJVKwpPH3qUGawwfLMxbc5gjlsvBHlMuO0GudNRHE5zeHcfSoSnYE1g08Xegv6T8PUUOXMVA6v6YdIQnksV/KpYOdZYGk3KLmj948BHOeA12SATwdSTzPjUZhzuMWk2hyUaZUCCylWHMZKJGU3Fz8MGyJeFEF9WNCco00uAJVHfslhFlRZhFlQ/SfW08kj3ehzUWJEt0sTM7oBWMOHdXpZfFi/Bqds0qNAM1tXgRYfSyTS4d5kd3Rj7T4tcka2wYf175TZO7V3xMjFfZ61vqCAudOgf6eGXVzv5Q8 "Charcoal – Try It Online") which tells you the number of `X`s and the size of each area of `.`s.
## Previous score 89 + 54 = 143
```
....X...............X....
.....X.............X.....
......X...........X......
.......X.........X.......
........X...X...X........
.........XXX.XXX.........
........X.......X........
.......X.........X.......
XXXXXXX...........XXXXXXX
.......X.........X.......
.......X.........X.......
........X.......X........
.........XXXXXXX.........
........X.......X........
.......X.........X.......
.......X.........X.......
XXXXXXX...........XXXXXXX
.......X.........X.......
........X.......X........
.........XXX.XXX.........
........X...X...X........
.......X.........X.......
......X...........X......
.....X.............X.....
....X...............X....
```
[Answer]
# C++, score 147
Adding simulated annealing has changed the results *very significantly*. They are now extremely worrying.
The code:
```
//#define _GLIBCXX_DEBUG
#include <x86intrin.h>
#include <iostream>
#include <streambuf>
#include <bitset>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cmath>
#include <climits>
#include <random>
#include <set>
#include <list>
#include <map>
#include <unordered_map>
#include <deque>
#include <stack>
#include <queue>
#include <string>
#include <iomanip>
#include <unordered_set>
#include <thread>
std::mt19937_64 mt;
int N = 25;
std::vector<char> cuts(N*N);
std::vector<char> marks;
int dfs(int at)
{
char x = at % N, y = at / N;
marks[at] = true;
int sz = 1;
static const char ddx[4] {1, -1, 0, 0};
static const char ddy[4] {0, 0, 1, -1};
for(int d = 0; d < 4; d++)
{
int dx = ddx[d], dy = ddy[d];
int nx = x + dx, ny = y + dy;
if(nx < 0 || ny < 0 || ny >= N || nx >= N) continue;
if(marks[ny * N + nx]) continue;
sz += dfs(ny * N + nx);
}
return sz;
}
bool connected(int at)
{
char x = at % N, y = at / N;
static const char ddx[4] {1, -1, 0, 0};
static const char ddy[4] {0, 0, 1, -1};
for(int d = 0; d < 4; d++)
{
int dx = ddx[d], dy = ddy[d];
int nx = x + dx, ny = y + dy;
if(nx < 0 || ny < 0 || ny >= N || nx >= N) continue;
if(cuts[ny * N + nx]) return true;
}
return false;
}
int score()
{
marks = cuts; //true -> pretend it's already cut
int ans1 = 0, ans2 = 0;
for(char el : cuts) ans2 += el == true;
for(int i = 0; i < N*N; i++)
{
if(marks[i]) continue;
ans1 = std::max(ans1, dfs(i));
}
return ans1 + ans2;
}
int main()//int64_t argc, char*argv[])
{
int gs = 8;
for(int y = 0; y < N; y++)
for(int x = 0; x < N; x += gs)
cuts[y*N+x] ^= true;
for(int y = 0; y < N; y += gs)
for(int x = 0; x < N; x++)
cuts[y*N+x] ^= true;
for(int x = 0; x < N; x++)
cuts[x] ^= true,
cuts[N*x] ^= true,
cuts[N*(N-1)+x] ^= true,
cuts[N*x+N-1] ^= true;
//do random changes, minimizing score
printf("%d\n", score());
int its = 1e6;
float temp = 1;
for(int y = 0; y < N; y++)
{
for(int x = 0; x < N; x++) printf("%c", cuts[y*N+x] ? '#' : '.');
printf("\n");
}
while(its --> 0)
{
if(its % 1000 == 0) printf("i: %d\n", its);
temp -= 2e-6;
int i = 0;
do { i = mt() % (N*N); }
while(!cuts[i] && !connected(i));
//fun fact: do..while loops don't actually need braces
int sb = score();
cuts[i] ^= 1;
int sa = score();
int delta = sb - sa; //positive -> good
//printf("%d\n", delta);
if(delta <= 0 && (temp <= 0 || ldexpf(std::exp(delta / temp), 60) < mt()))
cuts[i] ^= 1;
else printf("%d\n", sa);
}
for(int y = 0; y < N; y++)
{
for(int x = 0; x < N; x++) printf("%c", cuts[y*N+x] ? '#' : '.');
printf("\n");
}
}
```
The output, with the starting condition being a 3x3 grid:
```
........#........#.......
.........#......#........
........#.......#........
.......#.......#.........
........#.......#........
........#........#.......
.......#........#........
.#....#.#......#.#...#.##
#.#.##...#...##...#.#.#..
...#......#.#....#.#.....
...........#.....#.......
..........#......#.......
.........#.......#.......
#......##........#.......
.#....#.......###........
..##.#.......#..#........
....#......##....#....#.#
.....#....#......#...#.#.
......#.##........###....
.......#.........#.......
.......#........#........
........#......#.........
.......#......#..........
.......#......#..........
.......#.....#...........
```
```
[Answer]
# Score: ~~158 145~~ 141
*-4 thanks to @LevelRiverSt !*
```
.....X.............X.....
.....X.............X.....
......X...........X......
.......X.........X.......
........X.......X........
XX.......X.....X.......XX
..X.......X.X.X.......X..
...X.......X.X.......X...
....X.....X...X.....X....
.....X...X.....X...X.....
......X.X.......X.X......
.......X.........X.......
......X...........X......
.......X.........X.......
......X.X.......X.X......
.....X...X.....X...X.....
....X.....X...X.....X....
...X.......X.X.......X...
..X.......X.X.X.......X..
XX.......X.....X.......XX
........X.......X........
.......X.........X.......
......X...........X......
.....X.............X.....
.....X.............X.....
```
[Try it online!](https://tio.run/##nVLBjpswEL37K57UQ6AhKEnVS1RW2ktPPfaAhFDlghMcZQdkTLv9@nRsAkuyoasukmX7vZn3ZsY0f2xV0/Z8/oBvmhQ2OzyCuqefyoAilIpqq@kASSA88zoYXYpL8CfEMUNLl0UoKmlkYZVpUROULCqcXNSoYSvl0xEs4gX2NTvUpYqwSPtbYeq2VeWq7qxnQiEICTTZwMjfPzQ1nQ3CUByMbKoIv3TLbJZHvITL1xwKI@mgAgp3Aj4ulk2jqAxOur2WCYVTGOjsqzy1KsdHENuWao9y3wYmQuGU9B4GX7AGuxg8JNytq3eAihHylpnJsyJHkvjOGGWfHmMpGGU7Q1iLF5jb@G46JQbOW7uxOnveh1IcNN6xes2ven4jhKR2w7K8bXlb352Pw443mGu1b0Ln2bFvgh9LUslPYn3JnnChsCztvHWEY@iAi@uTfA7cMYIN70umi90lfotlwgU3hp@5z196eIJEHjift59F7L40nn797S3mirqcRXxLDSdxC4whIr2GxlsqptHpNFPE19RLvrgWmkiKO@BNP68k3@znPTOY9Zmtbbaf2RnMze1fs557n3fP4P/@qr8)
**Number of X**: 80
**Largest component**: 61
Divide the grid into 9 rougly equal areas of size ~60.
[Answer]
# 92 + 45 = 137
```
......X.........X........
.......X........X........
........X........X.......
.......X.X.......X.......
......X..X......X.X......
.....X....X....X...X.....
....X......X..X.....X...X
X..X.......X.X.......X.X.
.XX.........X.........X..
...X.......X.X.......X...
....X.....X...X.....X....
.....X...X.....X...X.....
......X.X.....X.X.X......
.......X.....X...X.......
......X.....X.....X......
.....X......X......X.....
....X......X........X....
....X.....X.X........XXX.
XXXX.X...X...X......X...X
......X.X.....X....X.....
.......X.......X..X......
.......X........XX.......
........X.......X........
........X.......X........
........X.......X........
```
[Try it online!](https://tio.run/##jVJNj5swEL37V4zUQ6AhKEm1l6istJeeeuzBEkKVC05wlB2QMe3216djE74MkYoENu/NzJs3dv3XlBUe7/dP8F2hhMMJ3gDb919SA0ZQSKyMwgsIBIQPei9aFewR/AXimKCtzULIS6FFbqRuoEKQIi/hZqOGGqaULh2CTbyBc0UKVSEj2PDuL9dV08hiV7XGMSFjCAkoNIEWf34qrFsThCG7aFGXEfxWDbFpFtHLbL6iUNACLzLA8MTAxcWiriUWwU018zIhsxV6Ov0mbo3M4DMgyRbyDMW5CXQEua2kzqDhK@yBVDS8JuTW9ttD@QA5yVRnaZ5BkjhnhJJOh1Ep0NK0GmHPRphs/NCtZD3npO1YrTytfSsWGv5ht@R3HX9gTGBzoLK0HGnZr87HYlcPs1Y7EypLr50JOiyBBR2JcS07woZCXrVoqLzVV9E1tNhD@F18BHYbdUHhemW@OT1yjrBNqO9a02l3NbYOvt@PLyx2D4/7Z9gxH1gwS2rM4esMH5AhhI1xw4ePDPcSHc3GOjMtTjl8xYvdsXg9Z6bDZ7tJbz7N5oW472eZMZ2B953OwFvYkpj2xj075J5mwO2Xz9W7ufld@36mc@HP7gF/dg@e35D/Yf4B "Python 2 – Try It Online")
I started with a program, then I took the best output and hand-modified it to get this. Next I'm going to try restricting the program to only place Xs on one color of squares - that seems like it might work better. The program is written in rust. The key idea was to seed the map with a Vornoi diagram before running a simplified simulating annealing:
```
use rand::prelude::*;
use std::collections::{HashMap, HashSet};
fn make_neighbors(point: (usize, usize), size: usize) -> Vec<(usize, usize)> {
let (r, c) = point;
let mut neighbors = vec![];
if r > 0 {
neighbors.push((r - 1, c));
}
if c > 0 {
neighbors.push((r, c - 1));
}
if r < size - 1 {
neighbors.push((r + 1, c));
}
if c < size - 1 {
neighbors.push((r, c + 1));
}
neighbors
}
fn value_board(board: &Vec<Vec<bool>>) -> usize {
let size = board.len();
let mut color_counts = vec![];
let mut removed_count = 0;
let mut seen = HashSet::new();
for r in 0..size {
for c in 0..size {
if board[r][c] {
removed_count += 1;
} else {
let mut color_count = 0;
let mut flood_stack = vec![(r, c)];
while !flood_stack.is_empty() {
let point = flood_stack.pop().unwrap();
if !board[point.0][point.1] &&!seen.contains(&point) {
seen.insert(point);
color_count += 1;
let neighbors = make_neighbors(point, size);
flood_stack.extend(neighbors);
}
}
color_counts.push(color_count);
}
}
}
let max_color_count = color_counts.into_iter().max().unwrap_or(0);
removed_count + max_color_count
}
// TODO: make removed, neighbor_removed into VecSets.
fn simulated_annealing(input_board: &Vec<Vec<bool>>, max_steps: usize) -> Vec<Vec<bool>> {
let size = input_board.len();
let mut coloring: HashMap<(usize, usize), usize> = HashMap::new();
let mut max_color = 0;
let mut color_counts = vec![];
let mut removed: Vec<(usize, usize)> = vec![];
let mut neighbor_removed: Vec<(usize, usize)> = vec![];
let mut board = input_board.clone();
for r in 0..size {
for c in 0..size {
if board[r][c] {
removed.push((r, c));
let neighbors = make_neighbors((r, c), size);
for point in neighbors {
if !board[point.0][point.1] && !neighbor_removed.contains(&point) {
neighbor_removed.push(point);
}
}
} else {
if !coloring.contains_key(&(r, c)) {
let color = max_color;
max_color += 1;
color_counts.push(0);
let mut flood_stack = vec![(r, c)];
while !flood_stack.is_empty() {
let point = flood_stack.pop().unwrap();
if !board[point.0][point.1] && !coloring.contains_key(&point) {
coloring.insert(point, color);
color_counts[color] += 1;
let neighbors = make_neighbors(point, size);
flood_stack.extend(neighbors);
}
}
}
}
}
}
let mut rng = thread_rng();
for step in 0..max_steps {
//dbg!(&removed, &neighbor_removed, &coloring, &board);
assert_eq!(removed.len() + coloring.len(), size.pow(2));
if rng.gen::<f64>() < 0.5 && !removed.is_empty() {
let index = rng.gen_range(0, removed.len());
let &(r, c) = &removed[index];
assert!(removed.contains(&(r, c)));
assert!(!neighbor_removed.contains(&(r, c)));
assert!(!coloring.contains_key(&(r, c)));
assert!(board[r][c]);
let neighbors = make_neighbors((r, c), size);
let neighbor_colors: HashSet<usize> = neighbors
.iter()
.filter_map(|n| coloring.get(n))
.cloned()
.collect();
// Remove if only 1 color.
// This will always be a neutral or improving step
// Never remove otherwise
if neighbor_colors.len() <= 1 {
board[r][c] = false;
removed.swap_remove(index);
let neighbors = make_neighbors((r, c), size);
for neighbor in neighbors {
if board[neighbor.0][neighbor.1] {
neighbor_removed.push((r, c));
break;
}
}
let new_color = if neighbor_colors.len() == 1 {
neighbor_colors.into_iter().next().unwrap()
} else {
let new_color = max_color;
max_color += 1;
color_counts.push(0);
new_color
};
coloring.insert((r, c), new_color);
color_counts[new_color] += 1;
}
} else if !neighbor_removed.is_empty() {
let index = rng.gen_range(0, neighbor_removed.len());
let (r, c) = neighbor_removed[index];
let my_color = *coloring.get(&(r, c)).unwrap();
let is_max_color = color_counts.iter().enumerate().all(|(i, &color_count)| {
i == my_color || color_count < color_counts[my_color]
});
// Flip if either is a max color, in which case it's free,
// or temp is high enough and get lucky.
let take_action = is_max_color || {
step < max_steps / 2 && rng.gen::<f64>() < 0.1
};
if take_action {
board[r][c] = true;
neighbor_removed.swap_remove(index);
removed.push((r, c));
coloring.remove(&(r, c));
color_counts[my_color] -= 1;
let neighbors = make_neighbors((r, c), size);
for neighbor in neighbors {
if !board[neighbor.0][neighbor.1] && !neighbor_removed.contains(&neighbor) {
neighbor_removed.push(neighbor)
}
}
}
}
}
board
}
// Given starting points and a board size, make a vornoi diagram
fn vornoi(points: &Vec<(usize, usize)>, size: usize) -> Vec<Vec<bool>> {
let mut time_board: Vec<Vec<Option<usize>>> = vec![vec![None; size]; size];
let mut board = vec![vec![false; size]; size];
for (i, point) in points.iter().enumerate() {
time_board[point.0][point.1] = Some(i);
}
for _ in 0..size {
let mut new_board = time_board.clone();
for r in 0..size {
for c in 0..size {
if let Some(i) = time_board[r][c] {
let neighbors = make_neighbors((r, c), size);
for (nr, nc) in neighbors {
if let Some(j) = new_board[nr][nc] {
if i != j {
board[r][c] = true;
}
} else {
new_board[nr][nc] = Some(i);
}
}
}
}
}
time_board = new_board
}
board
}
fn random_vornoi(num_points: usize, size: usize) -> Vec<Vec<bool>> {
let mut points = vec![];
let mut rng = thread_rng();
while points.len() < num_points {
let r = rng.gen_range(0, size);
let c = rng.gen_range(0, size);
if !points.contains(&(r, c)) {
points.push((r, c))
}
}
vornoi(&points, size)
}
fn print_board(board: &Vec<Vec<bool>>) {
let string_board = board
.iter()
.map(|row| {
row.iter()
.map(|&c| if c { 'X' } else { '.' })
.collect::<String>()
})
.collect::<Vec<String>>()
.join("\n");
println!("{}", string_board);
}
fn main() {
let size: usize = 25;
let reps = 100;
let steps = 30000000;
let mut best_points = 0;
let mut best_board = None;
let mut best_value = size.pow(2);
for num_points in 8..17 {
let mut best_board_points = None;
let mut best_value_points = size.pow(2);
for _ in 0..reps {
let board = random_vornoi(num_points, size);
let better_board = simulated_annealing(&board, steps);
let value = value_board(&better_board);
if value < best_value {
best_board = Some(better_board.clone());
best_value = value;
best_points = num_points;
}
if value < best_value_points {
best_board_points = Some(better_board);
best_value_points = value;
}
}
println!("{} {}", num_points, best_value_points);
print_board(&best_board_points.unwrap());
println!();
}
println!("{} {}", best_points, best_value);
print_board(&best_board.unwrap());
println!();
}
```
To run the program, put the above file in `src/main.rs` and put `rand = "*"` in your Cargo.toml.
[Answer]
# Score: ~~314~~ 313
-1 thanks to @Level River St
```
.X.X.X.X.X.X.X.X.X.X.X.X.
X.X.X.X.X.X.X.X.X.X.X.X.X
.X.X.X.X.X.X.X.X.X.X.X.X.
X.X.X.X.X.X.X.X.X.X.X.X.X
.X.X.X.X.X.X.X.X.X.X.X.X.
X.X.X.X.X.X.X.X.X.X.X.X.X
.X.X.X.X.X.X.X.X.X.X.X.X.
X.X.X.X.X.X.X.X.X.X.X.X.X
.X.X.X.X.X.X.X.X.X.X.X.X.
X.X.X.X.X.X.X.X.X.X.X.X.X
.X.X.X.X.X.X.X.X.X.X.X.X.
X.X.X.X.X.X.X.X.X.X.X.X.X
.X.X.X.X.X.X.X.X.X.X.X.X.
X.X.X.X.X.X.X.X.X.X.X.X.X
.X.X.X.X.X.X.X.X.X.X.X.X.
X.X.X.X.X.X.X.X.X.X.X.X.X
.X.X.X.X.X.X.X.X.X.X.X.X.
X.X.X.X.X.X.X.X.X.X.X.X.X
.X.X.X.X.X.X.X.X.X.X.X.X.
X.X.X.X.X.X.X.X.X.X.X.X.X
.X.X.X.X.X.X.X.X.X.X.X.X.
X.X.X.X.X.X.X.X.X.X.X.X.X
.X.X.X.X.X.X.X.X.X.X.X.X.
X.X.X.X.X.X.X.X.X.X.X.X.X
.X.X.X.X.X.X.X.X.X.X.X.X.
```
The largest connected component is of size 1.
Verify the score here: [Try it online!](https://tio.run/##7VGxTsMwFNz9FScxNKFp1BaxVASJhYmRIVIUIZO4jav2JXIcKF8fnh1SBLQbYxVZju/e3b1nNx@2qmnZ91d40qSwWOEB1O1flQFFKBXVVtMGkkA48NoYXYqv4hvEMUNTpyIUlTSysMq0qAlKFhV2ruroYSvl5Qgm8QTrmhPqUkWYpMOpMHXbqnJWd9YzoRCEBJpsYOT7i6ams0EYio2RTRXhTbfMZnnESzi95lIYSRsVULgS8HWxbBpFZbDT7U@bUDiHkc4e5a5VOa5BHFuqNcp1G5gIhXPSaxjcYQ5OMbhPeFrX7wgVR8hHZibPihxJ4idjlHMGjK1glO0MYS6@YR7j2XRKjJyPdtfq4nkfW3HQ8YzZX3428AshJLULtuVtydv85P04bPsLc6MOQ@g82w5D8GNJKvlJrG/ZE64UXyF7eQjcb@Qb0RG27nJPOaWTUbfENOE@G8OvO/hMPdz3y1sRp2c@cY5IL5qL5v81nw "Python 2 – Try It Online")
]
|
[Question]
[
# Objective
Given a dimension of an SI unit, convert the Lorentz-Heaviside version of a Planck unit \$1\$ into SI metric.
# What is a Planck unit?
[Planck units](https://en.wikipedia.org/wiki/Planck_units) are a set of units of measurement. It defines five fundamental constants of the universe as dimensionless \$1\$.
# What is a dimension?
There are five types of fundamental dimension: `L`, `M`, `T`, `Q`, and `Θ` (U+0398; Greek Capital Letter Theta).
`L` stands for length and corresponds to SI unit m (meter).
`M` stands for mass and corresponds to SI unit kg (kilogram).
`T` stands for time and corresponds to SI unit s (second).
`Q` stands for electric charge and corresponds to SI unit C (Coulomb).
`Θ` stands for temperature and corresponds to SI unit K (Kelvin).
A dimension is a multiplicative combination of these. For example, SI unit V (volt) is same as kg·m²·C/s⁴ and thus corresponds to dimension `L²MQ/T⁴`.
# Planck to SI
\$1\$ as Planck unit can be converted to SI metric as follows:
$$
1 = 5.72938×10^{−35} \space [\text{m}] = 6.13971×10^{−9} \space [\text{kg}] = 1.91112×10^{−43} \space [\text{s}] = 5.29082×10^{−19} \space [\text{C}] = 3.99674×10^{31} \space [\text{K}]
$$
# Input and Output
A dimension is given as the input. Its type and format doesn't matter. In particular, it can be an size-5 array of signed integers, each integer representing the exponent of a fundamental dimension.
The Planck unit \$1\$ is to be converted to the SI unit that corresponds to the inputted dimension, and then outputted. The output type and format doesn't matter.
# Examples
Let's say the input format is a tuple of five integers, representing `L`, `M`, `T`, `Q`, and `Θ`, respectively.
For example, If the input is \$(2,1,-1,-2,0)\$, it corresponds to SI unit Ohm, and thus:
$$
1 = \frac{(5.72938×10^{−35})^2 × (6.13971×10^{−9})}{(1.91112×10^{−43})×(5.29082×10^{−19})^2} \space [\text{Ω}]
$$
So the output is approximately \$376.730\$.
For another example, if the input is \$(-2,-1,3,0,1)\$, it corresponds to SI unit K/W, and thus:
$$
1 = \frac{(1.91112×10^{−43})^3 × (3.99674×10^{31})}{(5.72938×10^{−35})^2 × (6.13971×10^{−9})} \space [\text{K/W}]
$$
So the output is approximately \$1.38424×10^{−20}\$.
Note that, if the input is \$(0,0,0,0,0)\$, the output must be \$1\$.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~118~~ \$\cdots\$ ~~85~~ 80 bytes
Saved a whopping 29 bytes thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!!
Saved 4 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
Saved 5 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)!!!
```
lambda a,b,c,d,e:399674e26**e/174539e29**a/162874e3**b/523253e37**c/189007e13**d
```
[Try it online!](https://tio.run/##TYkxDsIwDEV3TsHYWEaJ7aZpkLgJS9K4AgnaCnXh9CEDSOi/5b@3vffbukidL9f6SM9c0jFhxgkL6lliHEKvPACopdB7icoRIFkaeGxFALL1LOxFJQBMlsboXFBqpdTtdV/2bu4YCU8NRmfM4WfbbVLQIf1Zh98ZUz8 "Python 3 – Try It Online")
[Answer]
## [Frink](https://frinklang.org/), 76 bytes
```
f[a,b,z,d,e]:=l_P^a m_P^b(4π)^((a-b+z-e)/2)t_P^z(ℏ c epsilon0)^(d/2)T_P^e
```
Example usage:
```
f[2,1,-1,-2,0]
376.73031366686987155 m^2 s^-3 kg A^-2 (electric_resistance)
f[-2,-1,3,0,1]
1.3842382138391631282e-20 m^-2 s^3 kg^-1 K (thermal_resistance)
```
(As a bonus, it outputs a description of the unit of the result!)
Frink has the constants `plancklength`, `planckmass`, `plancktime`, and `plancktemperature` built in, with abbreviations `l_P`, `m_P`, `t_P`, and `T_P` respectively. Unfortunately, these are the Gaussian versions of the units, and the challenge specifies that we must use the Lorentz-Heaviside versions. This is a factor of \$\sqrt{4\pi}\$ conversion for each unit, which is consolidated into the `(4π)^((a-b+z-e)/2)` expression in the solution. (This expression is placed in the middle of the code to save a byte by letting us remove the space between `m_P^b` and `t_P^z`.)
Incidentally, `4π` is exactly as long as `4pi` in UTF-8, so it doesn't actually save any bytes -- it just looks fancier. :P
Finally, Frink inexplicably lacks the built-in unit `planckcharge`, so we calculate the Lorentz-Heaviside version directly ourselves as `(ℏ c epsilon0)^(1/2)` (this time, `ℏ` actually saves a byte over `hbar`!).
[Answer]
# Fortran (2008), 133 bytes
At least for this challenge there should be a Fortran solution.
Takes input as integer array.
```
real(real64)function h(I)
use iso_fortran_env
integer I(5)
h=product([572938d-40,613971d-14,191112d-48,529082d-24,399674d26]**I)
end
```
A slightly longer and less accurate function uses the logarithm (stolen from @xnor):
```
real(real64)function f(I)
use iso_fortran_env
integer I(5)
f=exp(sum([-7884487d-5,-1890850d-5,-9836347d-5,-42083140d-5,7276562d-5]*I))
end
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~35~~ 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“~VHð¡ȷ‘I⁵*ד®ƬØʋ¥4ẋİ8nCaḌ’bȷ6¤*⁸P
```
A monadic Link accepting a list of the five exponents, `[L, M, T, Q, Θ]`, which yields a floating-point number.
**[Try it online!](https://tio.run/##AVkApv9qZWxsef//4oCcflZIw7DCoci34oCYSeKBtSrDl@KAnMKuxqzDmMqLwqU04bqLxLA4bkNh4biM4oCZYsi3NsKkKuKBuFD///9bLTIsIC0xLCAzLCAwLCAxXQ "Jelly – Try It Online")**
### How?
```
“~VHð¡ȷ‘I⁵*ד®ƬØʋ¥4ẋİ8nCaḌ’bȷ6¤*⁸P - Link: list of numbers [L, M, T, Q, Θ]
“~VHð¡ȷ‘ - list of code-page indices [126, 86, 72, 24, 0, 26]
I - differences [-40,-14,-48,-24,26]
⁵ - ten 10
* - exponentiate [1e-40, 1e-14, 1e-48, 1e-24, 1e26]
¤ - nilad followed by link(s) as a nilad:
“®ƬØʋ¥4ẋİ8nCaḌ’ - base 250 number 572938613971191112529082399674
ȷ6 - 10^6 1000000
b - convert from base [572938,613971,191112,529082,399674]
× - multiply (vectorises) [5.72938e-35,6.13971e-09,1.91112e-43,5.29082e-19,3.99674e31]
⁸ - chain's left argument [L, M, T, Q, Θ]
* - exponentiate [5.72938e-35^L,6.13971e-09^M,1.91112e-43^T,5.29082e-19^Q,3.99674e31^Θ]
P - product 5.72938e-35^L×6.13971e-09^M×1.91112e-43^T×5.29082e-19^Q×3.99674e31^Θ
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~31~~ 29 bytes
```
•¿NkˆSSÀ¯j5ÄΣDt₁ñµ•8ô6°/₃-*O°
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcOiQ/v9sk@3BQcfbji0Psv0cMu5xS4lj5oaD288tBUoa3F4i9mhDfqPmpp1tfwPbfj/P9pIx1BHF4iMdAxiAQ "05AB1E – Try It Online")
-2 thanks to @Kevin Cruijssen
inspired by @xnor.
explanation:
```
•¿NkˆSSÀ¯j5ÄΣDt₁ñµ•8ô6°/₃- compressed list [-34.241893, -8.211853000000005, -42.718713, -18.276477999999997, -82.33983, -94.999995]
* multiply by the implicit input (e.g. [-68.48378600000001, -8.211852999999998, 42.718713, 36.552955999999995, 0.0])
O sum (e.g. 2.576029999999996)
° raise 10 to the power of that (e.g. 376.729821659)
```
# Old Solution, ~~36~~ ~~35~~ 34 bytes
```
"7Q/Gy"Ç₃-*O°•7“µ$₁$´*h$òE•6ôImP*
```
-1 thanks to @Expired Data
[Try it online!](https://tio.run/##yy9OTMpM/f9fyTxQ371S6XD7o6ZmXS3/QxseNSwyf9Qw59BWlUdNjSqHtmhlqBxpO7TJFShudniLZ26A1v//0UY6hjq6QGSkYxALAA "05AB1E – Try It Online")
explanation:
```
"7Q/Gy"Ç₃- compressed list [-40,-14,-48,-24,26]
* multiply (vectorize) with the implicit input - [-80, -14, 48, 48, 0]
O sum - 2
° 10^ - 100
•7“µ$₁$´*h$òE• compressed number 572938613971191112529082399674
6ô split into groups of length 6 - [572938,613971,191112,529082,399674]
I push input to the stack, to get [2, 1, -1, -2, 0] [572938,613971,191112,529082,399674] 100
m power (vectorize) - [328257951844, 613971, 5.232533802168362e-6, 3.5723502030270884e-12, 1]
P product - 3.7672911312918473
* multiply - 376.72911312918473, and then implicitly output
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, ~~84~~ 80 bytes
*@Arnauld and I both realized that you can save bytes by removing the decimal points.*
```
$\=1;map$\*=$_**$F[$i++],572938E-40,6.13971E-9,191112E-48,529082E-24,399674E26}{
```
[Try it online!](https://tio.run/##Dcg9DsIwDEDhq2TIlDoodn6tqmO4BEWoA0OlQiNgQ706JtIbPr12f21RRM8Tjo@l6dlM@maMPl/0OgxXiJnYl2qDg3RCzxmrZUBGROq3QCR2pZMCeOaUQ6V0fEVIobI9Uu63t8@6P99il7b9AQ "Perl 5 – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~85~~ ~~81~~ ~~78~~ ~~75~~ 70 bytes
```
16iFFk1F875AI15^*?^35C8BI18^*?^/9B5431E?^/3C1109I1E^*?^/1A3ADDIA^*?^/p
```
[Try it online!](https://tio.run/##HYg7DoAgEAX7PYqNPBCFyvBN9hJYaGNsvH@zIskUM3OdIljvWh9Ut9nAsG3am7HJRYb7ffbRLgalm0mA8owyPoIJOXMY8Yoo0gQ6Opo@ "dc – Try It Online")
Or try a [test suite](https://tio.run/##Tc5NCsIwEAXgfU/xFi5UEDuN0XYl6R/kDmJJk4EWxYou3Hj32EaFMjC87y2Gac2z86@uvzIebBwMWlg4cAS4YVzAkm03YGEC8EU7h53DzcErvOEsNoyTp31f1xeq04NUmuR5fTwLWaS5pnTK2yyXO0HVmERBFGeaqtCTEqostQq4@//18OCNPaFJ0BAE4ihGAprQJGP@TfQB) that shows the sample cases listed in the challenge. (This is a bash script that runs the dc program on each test data set in turn.)
---
*Saved 4 bytes by removing the decimal points, thanks to @Arnauld.*
*Had to add 1 byte also though, because I had inadvertently omitted a digit in one of the constants.*
*Saved 3 more bytes by changing constants to hexadecimal.*
*Thanks to @Noodle9 for pointing out that using division instead of multiplication can shorten this. That, plus careful attention to how many significant digits were needed throughout, yielded a savings of 5 additional bytes.*
---
**Input on stdin, one number per line, in base 16, in the following order:**
```
Θ
L
M
T
Q
```
This is the OP's order except the last one there is moved to the first position instead.
(The challenge says, "A dimension is given as the input. Its type and format doesn't matter." Also, hexadecimal input won't make a difference in practice given the problem domain, because we're not going to have a dimensional exponent outside the range -9 to 9. And this is allowed anyway by ["Yes, I/O in unary, binary, octal, decimal or hexadecimal should be acceptable by default"](https://codegolf.meta.stackexchange.com/a/5367/59825), which got the required support of at least 5 net votes, and at least twice as many upvotes as downvotes -- in this case, 20 upvotes, 8 downvotes, and 12 net votes.)
**Output on stdout, in base 10 as usual, with *lots* of decimal places :) .**
---
**If you try this out,** note that when you enter negative numbers in dc, they're written with an initial `_` character instead of `-`, since `-` is reserved for the binary subtraction operator. And don't forget to put `Θ` first, and to enter them all in hexadecimal! (Output is still in decimal.)
[Answer]
# JavaScript (ES7), ~~81~~ 76 bytes
*Saved 5 bytes thanks to @Noodle9*
Seems like the direct formula is the shortest way... ¯\\_(ツ)\_/¯
Takes input as 5 distinct arguments.
```
(a,b,c,d,e)=>399674e26**e/174539e29**a/162874e3**b/523253e37**c/189007e13**d
```
[Try it online!](https://tio.run/##VclBDsIgEEDRvSeByVRgppSyqHehMDWaphhrvD6yNfmr/57pm878frw@w1GLtG1pKuGKGQuKXm4c4xRGoQlAjAuj5ygUAZJxE81dGGA1npg8CweAbNwcrQ3iupSW63HWXa57vatNEToceoRW68u/9dmJ0aLTuv0A "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES7), 86 bytes
Using `reduce()` adds ~~5~~ 10 bytes.
Takes input as an array.
```
a=>a.reduce((p,c,i)=>p*([572938e8,613971e34,191112,529082e24,399674e74][i]/1e48)**c,1)
```
[Try it online!](https://tio.run/##XclNDoMgEEDhfU8CZvyZAQUWehHjguDY2Bgh2vb6lHWTt3rfy3/9Ha49veszrpy3Mftx8s3F6yewEAkC7HKcUiXm3pBTli0MqJxBVhrQISJBT66zxKRBOTcYzUYv8760yNrKqgqAMod43vHg5ohPsYmZAKEuEXSLlI8/Lbuggg6waP4B "JavaScript (Node.js) – Try It Online")
[Answer]
# Mathematica, 260 bytes
Using a different method than the OP's. In particular, Table 2 at <https://en.wikipedia.org/wiki/Planck_units#Definition>
Many opportunities for cleanup (e.g., shrink name to `c`, saving 6 bytes), but seems pointless. Newlines and indenting are inessential and are only present for presentation. Two spaces are required, at the end of the `BoltzmannConstant` line and at the end of the `ElectricConstant` line.
```
convert=Function[{L,M,T,Q,t},
N[UnitConvert[
Quantity["BoltzmannConstant"]^-t
Sqrt[
(4Pi)^(L-M+T-t)
Quantity["SpeedOfLight"]^(-3L+M-5T+Q+5t)
Quantity["ElectricConstant"]^Q
Quantity["GravitationalConstant"]^(L-M+T-t)
Quantity["ReducedPlanckConstant"]^(L+M+T+Q+t)
]
],6]
]
```
Checking:
```
convert[2, 1, -1, -2, 0]
(* 376.730 kg m^2/(s^3A^2) *)
(* FullForm: Quantity[376.730, ("Kilograms" ("Meters")^2)/(("Amperes")^2 ("Seconds")^3)] *)
convert[-2, -1, 3, 0, 1]
(* 1.3842\[Times]10^-20 s^3K/(kg m^2) *)
(* FullForm: Quantity[1.3842\[Times]10^-20, ("Kelvins"*"Seconds"^3)/("Kilograms"*"Meters"^2)] *)
convert[0, 0, 0, 0, 0]
(* 1.00000 *)
```
Notice that this code uses a curated source of consensus scientific values of the constants, and the output will change as those values change. Of relevance to the Challenge (and exemplified in the above samples), the gravitational constant is only 6.674 30(15) \*10^(-11) m^3 /(kg s^2), so is only known to four significant digits. This impacts the precision of length, mass, and time (except in combinations where this term cancels) in the Challenge, although the Challenge does not acknowledge this limitation of precision in those constants.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~124~~ 101 bytes
*-23 bytes thanks to mazzy*
```
$t=1
$args|%{$t/=[math]::pow((174539e29,162874e3,523253e37,189007e13, 2502039161917e-44)[$i++],$_)}
$t
```
[Try it online](https://tio.run/##NYhBCoMwEEX3niKLaVGMNDOTGCN4EpHiItaCRdGAC@vZrSDl/cX7bxpXPy@9H4YDumo7IFQYQTu/lu9tg/Co6k8b@qYsp3GNY7TasPPkJOZUWO1ZGmIy7NlKLJxS1iNLMooUO8zRofWZ1kkN7zRtJDyTPYJw7NFdQCdIoMjOkVBXOO38LJTAK6g/xw8).
[Answer]
# Java 8, 118 bytes
```
Math M=null;(a,b,c,d,e)->M.pow(399674e26,e)/M.pow(174539e29,a)/M.pow(162874e3,b)/M.pow(523253e37,c)/M.pow(189007e13,d)
```
Port of [*@Noodle9*'s Python answer](https://codegolf.stackexchange.com/a/201792/52210), so make sure to upvote him!!
[Try it online.](https://tio.run/##hZDBjoIwEIbvPsUcS3ZAaBUkhn0DvHjc7KGU2RUXCpGiMRufnR3Q9Wra/O388zXp/Ed91v6x/BlNrfsecl3Z3wVAZR2dvrQh2E0lQNkORU1gBHdA46TFrGbWclbytgzfFiy5dgfIMzvU9RaWS3iLJBRXRz24FtyB5sI37WAd0zuwkMEoNBZosETy/Pc86NqLUGkaJyuSMXvLuxUlq7VKSaaon1YsN0wpLP6dtVRyrUglaJ7QJg3DhCKFpTdup092PFNloHfa8XFuqxIaDkDs3amy3x@foL379FMs0GSWLvNVzHMC7K@9oyZoBxd0/MLVVjSBDYyQGKHPW2LovWIZYlRhiNFLNsTH8h5J38Y/)
[Answer]
# TI-83 Basic, 62 tokens
Using list operations:
```
prod({5.72938ᴇ−35,6.13971ᴇ−9,1.91112ᴇ−43,5.29082ᴇ−19,3.99674ᴇ31}^Ans
```
where
```
prod( Multiply all list elements together (1 token)
{ ... } Constants in list (59 tokens)
^ Power using 2 lists as arguments (1 token)
Ans Input list stored in answer variable (1 token)
```
Example:
```
| {2,1,-1,-2,0} | Give input
| {2 1 -1 -2 0} |
| prgmPLANCK | Run program
| 376.7291131 | Result
```
Second example unfortunately returns 0, because of insufficient precision on calculator.
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), ~~95~~ 90 bytes
```
READ*,I,J,K,L,M
PRINT*,399674D26**M/174539D29**I/162874D3**J/523253D37**K/189007D13**L
END
```
[Try it online!](https://tio.run/##Jck7CsMwDADQPafwLGRsSbEdjQVlcH6U0At0SbcWQu/vBro9eMfn/J7Pt38df7S2jzcDrDjhjAuu3X2v2wNQVHPpjTPAGqj0SdRYAWqgzMM1AjCFxMJJTArAHGjQGIvRNUs3btaaZ@fJiYuOfg "Fortran (GFortran) – Try It Online")
Input on stdin, output on stdout.
*Thanks to @Noodle9 for saving 5 bytes by pointing out that using division instead of multiplication can shorten this.*
]
|
[Question]
[
**Challenge:**
In the programming language of your choice, accept an [**integer**](https://en.wikipedia.org/wiki/Integer) as input in base 10, and output it in [**the negadecimal notation**](https://en.wikipedia.org/wiki/Negative_base), which is also known as base -10
**Example algorithm:**
[This is an algorithm taken from Wikipedia to convert base 10 to any negative base in VB.NET](https://en.wikipedia.org/wiki/Negative_base):
```
Function toNegativeBase(Number As Integer , base As Integer) As System.Collections.Generic.List(Of Integer)
Dim digits As New System.Collections.Generic.List(Of Integer)
while Number <> 0
Dim remainder As Integer= Number Mod base
Number = CInt(Number / base)
if remainder < 0 then
remainder += system.math.abs(base)
Number+=1
end if
digits.Insert(0, remainder)
end while
return digits
end function
```
*Obviously, you can use any algorithm, as long as it fulfills the challenge*
**Example inputs / outputs:**
Input:
```
12
```
Output:
```
192
```
**Another example:**
Input:
```
2048
```
Output:
```
18168
```
**Rule:**
You must not use any built-in methods that solve this problem that exist in your programming language
This is a **code-golf**, so shortest code wins!
[Answer]
## JavaScript (ES6), ~~51~~ ~~45~~ 37 bytes
```
f=n=>n&&n%10+((k=n<0)+f(k-n/10|0))*10
```
### Test cases
```
f=n=>n&&n%10+((k=n<0)+f(k-n/10|0))*10
console.log("12 -> " + f(12))
console.log("2048 -> " + f(2048))
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 bytes
```
_ì ìAn)¥U}a
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.3&code=X+wg7EFuKaVVfWE=&input=MTA=)
### Explanation
```
_ì ìAn)¥U}a // Implicit: U = input integer, A = 10
_ }a // Return the smallest non-negative integer Z that returns a truthy value
// when run through this function:
ì // Convert Z to a list of its base 10 digits.
ìAn) // Interpret this as a list of base -10 digits and convert to a base 10 integer.
¥U // Return (the result == U).
// Implicit: output result of last expression
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Dḅ-10=ð1#
```
This is a brute-force inverse of negadecimal-to-integer conversion.
[Try it online!](https://tio.run/nexus/jelly#@@/ycEerrqGB7eENhsr///83MjCxAAA "Jelly – TIO Nexus")
### How it works
```
Dḅ-10=ð1# Main link. Argument: n
ð Combine the links to the left into a chain and start a new, dyadic
chain with left and right argument n.
1# Repeatedly execute the chain with left argument k = n, n + 1, ... and
right argument n until the first match is found.
D Convert k to decimal.
ḅ-10 Convert the result from base -10 to integer.
= Compare the result with n.
```
[Answer]
## Batch, 82 bytes
```
@set/a"d=%1%%10,n=%1/-10-(a=d>>4),d-=a*10
@if %n% neq 0 %0 %n% %d%%2
@echo %d%%2
```
Batch's division truncates to zero, so if the remainder is negative I need to add 1 (and also add 10 to the remainder) to compensate. The digits are then accumulated in `%2` until the result becomes zero.
[Answer]
# Pyth - 9 bytes
Lel it has the crying emoji in it.
```
fqQijT;_;
```
[Test Suite](http://pyth.herokuapp.com/?code=fqQijT%3B_%3B&test_suite=1&test_suite_input=-10%0A12%0A2048&debug=0).
[Answer]
# Python 3, 35 bytes
```
f=lambda n:n and n%10+f(0-n//10)*10
```
Python port of [Arnauld's](https://codegolf.stackexchange.com/a/105996/61809) algorithm.
Alternatively, for 102 bytes a generic function using the algorithm of the original post:
```
def f(n,b,r=0):
if n:
r,n=n%b,n//b
if r<0:r+=abs(b);n+=1
return f(n,b,r)+str(r)
else:return ""
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
:⁵NµÐĿ%⁵ṚḌ
```
[Try it online!](https://tio.run/nexus/jelly#@2/1qHGr36Gthycc2a8KZD7cOevhjp7///8bGZhYAAA "Jelly – TIO Nexus")
### Background
Converting a list of non-negative from base **b** to integer can be achieved by left-folding by the function **x, y ↦ bx + y**. To convert and integer *to* base **b**, we must simply reverse that function, i.e., find an expression for **bx + y ↦ x, y**.
In Python (and, by extension, Jelly), the result of the modulo operator is always non-negative, so **(bx + y) % |b| = y**.
Also, integer division always rounds down, making sure that if **q = n / d** and **r = n % d**, the equality **n = qd + r** holds. If **s** is the sign of **b**, then **(sx)|b| + y = bx + y**, so **sx = (bx + y) / |b|** and, therefore, **s((bx + y) / |b|) = x.**
### How it works
```
:⁵NµÐĿ%⁵ṚḌ Main link. Argument: n
µ Combine the links to the left into a monadic chain.
ÐĿ Iteratively apply the chain until the results are no longer unique.
Collect all unique results in an array.
:⁵ Divide the previous return value (initially n) by 10.
N Negate; multiply the result by -1.
%⁵ Take all results modulo 10.
Ṛ Reverse the results.
Ḍ Convert from base 10 to integer.
```
[Answer]
# [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate), 147 bytes
This is a template language I've been working on.
By no means it is meant to be for golfing.
It even lacks complete basic math, but it allows to write tiny snippets of PHP directly.
This works around that issue.
```
{@setN argv.0}{@whileN}{@setM N}{@php$DATA[N]=($DATA[M]/-10)|0;$DATA[R]=$DATA[M]%-10}{@ifR is lower0}{@incby10 R}{@incN}{@/}{@setD R,D}{@/}{@echoD}
```
This throws a bunch of warnings.
The code is "compiled" into PHP.
Ungolfed, with trash whitespace:
```
{@set no argv.0}
{@while no}
{@set temp_no no}
{@php $DATA["no"] = ($DATA["temp_no"] / -10) | 0}
{@php $DATA["remainder"] = $DATA["temp_no"] % 10}
{@if remainder is lower than 0}
{@inc by 10 remainder}
{@inc no}
{@/}
{@set digits remainder, digits}
{@/}
{@echo digits}
```
If required, a set-by-step explanation can be added, but I believe that it is pretty straightforward.
---
**Disclaimer**:
The last commit, as of the time of writting this answer, was on 2017-01-07 20:36 UTC+00:00.
This works on commit [140e56ff38f45fa4fd40fd3ec382094e707b1bad](https://github.com/ismael-miguel/SimpleTemplate/tree/140e56ff38f45fa4fd40fd3ec382094e707b1bad) from 2017-01-06 23:27 UTC+00:00.
That is the version used to run this answer.
The PHP code is available on <https://raw.githubusercontent.com/ismael-miguel/SimpleTemplate/140e56ff38f45fa4fd40fd3ec382094e707b1bad/SimpleTemplate.php>
I do recommend running this with the last version, but that one works fine for this question.
---
**How to run?**
Create a file with the code and run it like this:
```
<?php
include 'path/to/SimpleTemplate.php';
$template = new SimpleTemplate('<code>');
$template->render(<number>);
```
The value will then be displayed on the screen.
[Answer]
# PHP, ~~71~~ 67 bytes
```
for(;$n=&$argn;$n=$g-$n/10|0)$d=($r=$n%10)+10*($g=$r<0).$d;echo+$d;
```
or 62 bytes for a port of [Arnauld´s answer](https://codegolf.stackexchange.com/a/105996#105996):
```
function n($n){return$n?$n%10+(($k=$n<0)+f($k-$n/10|0))*10:0;}
```
[Answer]
# Mathematica, 49 bytes
```
d@0="";d@n_:=d[-Floor[n/10]]<>ToString[n~Mod~10];
```
Defines a function `d` taking one integer argument, and returning a string. A recursive algorithm—looks like the same algorithm in [Arnauld's answer](https://codegolf.stackexchange.com/a/105996/56178). It does work on negative numbers as well. (It returns the empty string intsead of "0" if the input is 0.) Note for Mathematica golfers: using `±` requires one extra set of parentheses and thus seems not to be any shorter.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
T(в
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/ROPCpv//jQxMLAA "05AB1E – Try It Online") This is not a builtin. It uses builtin base conversion, but not builtin negadecimal conversion.
```
T(в # full program
в # base-10 digits of...
# implicit input...
в # in base...
( # negative...
T # 10
# implicit output
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
₀Nτṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoBOz4ThuYUiLCIiLCIyMDQ4Il0=)
Explanation:
```
τ # From base 10 to base
₀ # Ten
N # Negated
ṅ # Join by nothing
# Implicitly print
```
[Answer]
# C, 68 bytes
```
main(f,a){f&&scanf("%d",&a);f=a?a%10+((f=a<0)+main(0,f-a/10))*10:0;}
```
Instead of printing the resulting number the program just returns it. Obviously this is [Arnauld's answer](https://codegolf.stackexchange.com/a/105996#105996), the only difference is that since C isn't an interpreted language I felt like I should make it a full program as opposed to just a function.
[Answer]
# Rust, 88 bytes
```
fn g(mut n:i32)->i32{let mut r=n%10;n/=-10;if r<0{r+=10;n+=1;}if n==0{r}else{r+g(n)*10}}
```
This is just a recursive version of the algorithm provided in the question.
]
|
[Question]
[
Traveling with electronics is always fun, especially when you need an adapter to charge them. Your challenge is to make planning a trip a little easier by checking if a given plug will be compatible with a given socket.
### Challenge
Given a plug type and a socket type, return a value that indicates whether they will work together or not.
### Compatibility table
```
Socket Accepted plugs | Plug Accepting Sockets
A A | A A, B
B A, B | B B
C C | C C, D, E, F, H, J, K, L, N, O
D C, D, E, F | D D
E C, E, F | E D, E, F, H, K, O
F C, E, F | F D, E, F, H, K, O
G G | G G
H C, E, F, H | H H
I I | I I
J C, J | J J
K C, E, F, K | K K
L C, L | L L
M M | M M
N C, N | N N
O C, E, F, O | O O
```
The tables show the same information, only transposed.
[For reference](https://www.worldstandards.eu/electricity/plugs-and-sockets/).
### Input
* The input will be given as two uppercase or two lowercase letters (you choose).
* Inputs will always be `/[A-O]/` (or `/[a-o]/`), there's no need to handle invalid inputs.
* You may accept the two inputs in any order (please specify which).
* Input can be taken in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) (string, stdin, array, ...).
* If you take both inputs in a single string, they can be separated by no more than one character and there must be nothing surrounding them
* Good inputs: `"G,K"`, `"EF"`, `"a b"`, `['l', 'o']`
* Bad inputs: `"K l"`, `"f(O)(I)"`, `[1,5]`
### Output
* Output can be returned in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* Output must be either `truthy`/`falsy` or one of 2 constant values
* Good outputs: `false`/`any positive number`, `1`/`2`, `'T'`/`'F'`
* Bad outputs: `an even number`/`an odd number`, `1`/`more than 1`
### Examples
Using the format `socket`, `plug` => `true` / `false`.
```
A, A => true
I, K => false
O, C => true
C, O => false
E, F => true
F, E => true
```
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the answer with the fewest bytes in each language wins.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~30~~ 29 bytes
```
(.)\1|[DEFHKO][CEF]|[JLN]C|BA
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0NPM8awJtrF1c3D2z822tnVLbYm2svHL9a5xsnx/39HRy5Pby5/Zy5nfy5XNy43VwA "Retina 0.8.2 – Try It Online") Link includes test cases.
[Answer]
# [Python 3](https://docs.python.org/3/), 76 bytes
```
lambda s,p:any([s==p,p in"CEF"and s in"DEFHKO",s=="B"<p,s in"JLN"and"C"==p])
```
[Try it online!](https://tio.run/##VZAxb4MwEIX3/IrTTURyhyobioeUYqVNFRY2iiqXQINCjWUbVfn19Gygoh6s7@7ee/JZ3921V7ux4e9jJ78/LxIs07FU96iwnGumoVWYpAKluoD1xXMqjqcMGY3xCfeahe7r29lLMEFyldvR1HbonAUOBR4OOTJ8OQm6s8RzknlOhWeR5lhumt7A5KG0mWy8ATq2r261Y6C74YuBVPanNpQ7aYKiGVT1Mbs5NNHasQ2KP9cCHDDHMKp6Y@rK/ZutAoNGm1a5aGoU8cNjubyDraWMdm3VnEebLVQWM9G//AI "Python 3 – Try It Online")
# Credits:
* From 83 to 76 bytes by [(Better) Neil](https://codegolf.stackexchange.com/users/17602/neil)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~72 Bytes~~ ~~73 bytes~~ 70 bytes
```
lambda p,s:s in{"A":"AB","C":y+"CJLN","E":y,"F":y}.get(p,p)
y="DEFHKO"
```
[Try it online!](https://tio.run/##XZDBb4IwFMbP61/R9CRZ42G7kXBQFBEQl@y4LQRZ1WZAK5Qsxvm3s9enmbIemt/Xvve9r9VHs1f1c3/w3vsyrzafOdW8dVsq6xObMJdNpowzn7nHR@ZHSQpiDoKzAPbzeCfMSHPtkKPHZvMgjNesl5VWjaHSiMYoVbaE6LLbZUZlrSq@hKEePZGHP3PAKeCFYBDzrVEUJ@kaj2ZwNEOaW7oMsTIYygXIBVIIFCItgZZIEVCEFAPFSAlQgrQCWiGlQCnSGsg6nwkxorWpIa7NtgiXkG4F8Uihqk3r3Z46tgeyzo1UdZt9S7PPGqHLvBCVqM3I@nD65BCyVQ21v8Lp9U9kTdHMJRRWXpguL6G37Uo7@VY0/Mo3Kz@wZdvVxa3hMLp3d7ACN91ICMJe4NalpzP9oa9YchETnHu9CMDxir5qGlFgERtD9io3gwF8mJjfp@H/X@Pd3zpO/ws "Python 3 – Try It Online")
Edit: Thanks to [Chas Brown](https://codegolf.stackexchange.com/users/69880/chas-brown) for cutting some fat!
[Answer]
# [C (gcc)](https://gcc.gnu.org/) (x86 architecture), 76 60 bytes
Many thanks to Arnauld for the changes!
Arguments are given in (plug, socket) order.
```
c[15]={6,0,56696,0,35184,35184};f(a,b){a=a==b|c[a-65]>>b&1;}
```
[Try it online!](https://tio.run/##bZDfToMwFMbv9xQnNZMSihnREl0pi29gondjF6XA1oqwQPEGeXakoFtMvDn/vt93TnKkf5RyvFGVLLssh6g1marvTvEo9wE98D4kG0LD8Mnmexo8PixxYAUWJHV7wQXn6ZfcCz@khzhObwM2jKoy8CFUhT9rlbnQrwDkSTQwWdhUW1kRbctzMzUFRi9ld0zMmoZtUiGCXmv5nhvkWqSoG6y4HzAVBZQpz1sWAgiuPOfZYXNjKW0pbSl9pQBSrq/cdL0ArKKNe7m9lolBBLCehjsHnG3q/rJ52eazQf9jEH@xi9rO6vKgHXpruhxtkY9@6GGO5860GC2zYTWM3w "C (gcc) – Try It Online")
[Answer]
## Haskell, 67 bytes
```
p#s=p==s||or[elem s b|a:b<-words"AB CDEFHJKLNO EDFHKO FDEHKO",a==p]
```
Arguments to function `#` are two characters, plug first, socket second.
[Try it online!](https://tio.run/##NcfRCoIwFIDh@57ioBdzYD1AtAvTDctqDyAS04SkqWNLIvDd1yHYxc/P91Tu1WvtvYkdM4y5dZ1t3et@BAftqvbtYfuZ7cNF2RHygovyXF1uEnghykqCKDguShVjpvGjGiZgMCpzvUNi7DC9YQfL1C3WfpOYUqg3AAnJSIrR9I8KcQrIETJAIvIAgeABHCEIbfwP "Haskell – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 79 bytes
```
S=>P=>P==S|P<'B'&S<'C'|P=='C'&'JLN'[K='includes'](S)|'CEF'[K](P)&'DEFHKO'[K](S)
```
Invoked as a curried function, `f(socket)(plug)`.
[Try it online!](https://tio.run/##dZJtb6owFMff8ymOuZttEy57P8cWRZ3zOeElIRkXy4ZywbQ676J8dnfawpTkDiH@2p7zP09dRx@RjEW63f3OixU/n@/uwIuyDA7p7h0iIaJPCGQRb/jOhm22fwutuMjlDrpCgAs0sUHiAQP3ERIaKA6ZVYtEEuK9EClfATUijCoRVol4@/@ISLRhVmURKB0bkjwE1wIIlIsNvvu4VK/rn5YPpEfa/gPxyAk38K9NxtM5CSYuSfM426@4JCH12Yl4gyFuh3TJ2qQ/GI4mC730GYSdOp7KzteZzqIt5nbEoN17IN0esRF7iIY8JE@pjCfT@UJv9XGrr2mgyERQy2Fz@YzLZ00jpJGmF6QXTWOksaYJ0kTTFGmqaYY00zRHmmtaICnlsqqiyLiTFW@UAD63ktiw@LPm8c7Z8E9JGxUyZ12kubIkjHWspBBAM27aAGnebAfT3VDHojhgbwJsG8C3jxnwD14Apr/83xYzwfvgNq0CfbecemL1belcuQoe8/RDu/YKrDHKqbocNMltuL6hrOH1NxIb9LjEdS9CT0Dwh91rEeOCdTnbvXynrzdH5VjeHK@Nf2ljh5TV6WsVKU2AfgdoXQLUpZtc1FgOkcBu97r9FjHJ1qlXSqVlvsYYb@W9GaNxUEmaqemZldb5/AU "JavaScript (Node.js) – Try It Online") (includes testcases, showing a matrix of results.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Oḅ⁴_ȷe“j⁼⁽⁾ƇƑƓƘƝƤḄẸỊṂṢỴẒĊḞĿ‘o⁼/
```
A monadic link accepting a list of characters `[plug,socket]` which yields `1` if compatible or `0` if not.
**[Try it online!](https://tio.run/##AVQAq/9qZWxsef//T@G4heKBtF/It2XigJxq4oG84oG94oG@xofGkcaTxpjGncak4biE4bq44buK4bmC4bmi4bu04bqSxIrhuJ7Ev@KAmG/igbwv////RUM "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##AYEAfv9qZWxsef//T@G4heKBtF/It2XigJxq4oG84oG94oG@xofGkcaTxpjGncak4biE4bq44buK4bmC4bmi4bu04bqSxIrhuJ7Ev@KAmG/igbwv/@KAnEFCQ0RFRkdISUpLTE1OT@KAnXDCtcOHxocsw4fDkOG4n0vigqxq4oG@wrbCtv8 "Jelly – Try It Online") (which separates out the two classes).
[Answer]
# [R](https://www.r-project.org/), ~~132 129~~ 113 bytes
```
function(S,P,`!`=utf8ToInt)"[<-"(diag(15),cbind(rep(!"",!" "),!"
"),1)[-64+!P,-64+!S]
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jWCdAJ0Exwba0JM0iJN8zr0RTKdpGV0kjJTMxXcPQVFMnOSkzL0WjKLVAQ1GJkZmVTUkHSHOysSlpAhlMXDx8LKxsHNz8yCRQylAzWtfMRFsxQAdMBcf@T9NQclTSUQASmgrKCrZ2CiVFpalcQFFPkKg3TDQtMacYLOwPEnZGV@wMEvXHUOwKEnZDV@wGEnVFFv0PAA "R – Try It Online")
Builds the following matrix and extracts `m[S,P]` => 1 if TRUE, else 0.
```
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
[1,] 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
[2,] 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 1 1 1 1 0 1 0 1 1 1 0 1 1
[4,] 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 1 1 1 0 1 0 0 1 0 0 0 1
[6,] 0 0 0 1 1 1 0 1 0 0 1 0 0 0 1
[7,] 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
[9,] 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0
[10,] 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
[11,] 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
[12,] 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
[13,] 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
[14,] 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
[15,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
```
Saved 3 bytes by compressing indexes using `intToUtf8` and replacing this function with `!`. See History for more legible version.
Saved 16 bytes thanks to @Giuseppe!
[Answer]
# [PHP](http://www.php.net/), 81 bytes
```
<?list(,$s,$p)=$argv;$A=AB;$C=$E=$F=DEFHKO;$C.=JLN;echo+($p==$s||strpos($$p,$s));
```
To run it:
```
php -n -d error_reporting=0 <filename> <socket> <plug>
```
Example:
```
php -n -d error_reporting=0 socket_plug_compatibility.php F E
```
Or [Try it online!](https://tio.run/##DczBCsIwDADQX/GQQ4ubeK9B5mwRFf0EES3bQJqQFE/7duOO7/J4ZLPd/jNpdQ1oA@wRnjJ8A3TYHQL0CBEh4TGm0@W@eIPn6y3k10hrB4wIOs9ahUkdAC@H98HMksUfcZ2oqLXF2vcqi5A8JDNJncqA2z8 "PHP – Try It Online")
**Notes:**
* To save some bytes, I have used strings without single/double quotations as the string wrapper. Thus, the `error_reporting=0` option is used to not output warnings.
* Input only works with uppercase letters.
* Outputs 1 for compatibility and 0 for non-compatibility.
---
# How?
Every plug is compatible with same socket as itself. There are four special plugs (A, C, E, F) which are compatible with a few more sockets as well. Four string variables with the name of the special plugs are defined to hold list of their extra compatible sockets.
It is checked if input plug and socket are same or if the socket is in the list of compatible sockets for that plug. The latter check is done with the help of [PHP's variable variables](http://php.net/manual/en/language.variables.variable.php).
[Answer]
# Javascript ES6, ~~66~~ ~~65~~ 64 chars
```
p=>s=>p==s|{A:1,C:14172,E:8788,F:8780}[p]&(1<<parseInt(s,36)-11)
```
Takes capital letters into `p` for plug and `s` for socket, returns falsy (`0`) or truthy (`1`, `2`, `4`, ..., `8192`) value.
### Test:
```
f=p=>s=>p==s|{B:1,C:14172,E:8788,F:8780}[p]&(1<<parseInt(s,36)-11)
console.log(`A, A => true
I, K => false
O, C => true
C, O => false
E, F => true
F, E => true`
.split`
`.map(x=>x.match(/(.), (.) => (\w+)/))
.every(([m,p,s,res])=>!!f(s)(p)==eval(res)))
```
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), 113 bytes
```
var p,s:char;begin read(p,s);write((p=s)or(pos(p,'CEF')>0)and(pos(s,'DEFHKO')>0)or(pos(p+s,'AB CJ CL CN')>0))end.
```
[Try it online!](https://tio.run/##NcpBCgIxDEDRq2TXBkdx7aCgsYOo6BliW3VAOiEVPX4tBbfvf@Hs@TW/iy/lwwrS5ZV/sva3@BgTaORgq2H/1fEdrZV1xkmtTLmyITcY3CyRU2iUO7N3w@F0bfr/ZpW3O6Aj0Bno0hrGFBalkPsB "Pascal (FPC) – Try It Online")
[Test for all values](https://tio.run/##XY1BCsIwEEXX9hSzmwSruHLR0kKNLaJizxCbVAslCZmix48h6MbN8Hnv88dJGuS8Gd0Qwkt6cDkVw1P6Mrvrx2Sy1WgjLCpsEBYL2CMoC1@XJP3Lt58WzZiriFvPnCXmchRth7zecWlUQpTjse1Olz7RX28dcXMAcQZxBXFLDoo9L@OvNDubGLVRZRbPNoQP)
Following the `DEFHKO` train...
`pos(string1,string2)` checks for first occurence of `string1` in `string2` and returns its position in it or 0 if it doesn't exist.
]
|
[Question]
[
Oh no! I have a theory test soon and I don't remember the scales yet! Help me remember my major scales by printing the following:
```
7♯ - C♯ D♯ E♯ F♯ G♯ A♯ B♯ C♯
6♯ - F♯ G♯ A♯ B C♯ D♯ E♯ F♯
5♯ - B C♯ D♯ E F♯ G♯ A♯ B
4♯ - E F♯ G♯ A B C♯ D♯ E
3♯ - A B C♯ D E F♯ G♯ A
2♯ - D E F♯ G A B C♯ D
1♯ - G A B C D E F♯ G
0 - C D E F G A B C
1♭ - F G A B♭ C D E F
2♭ - B♭ C D E♭ F G A B♭
3♭ - E♭ F G A♭ B♭ C D E♭
4♭ - A♭ B♭ C D♭ E♭ F G A♭
5♭ - D♭ E♭ F G♭ A♭ B♭ C D♭
6♭ - G♭ A♭ B♭ C♭ D♭ E♭ F G♭
7♭ - C♭ D♭ E♭ F♭ G♭ A♭ B♭ C♭
```
This is code-golf, so shortest code wins. You may use `#` and `b` symbols instead of `♯` and `♭` respectively.
Edit: If you are using `♯` and `♭` signs, you only have to count them as a single byte each. This is to not give an unfair disadvantage.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~66~~ 65 bytes (if using # and b)
```
↑⮌…0¦8‖O⸿×⁷♭M→×⁷♯→⸿⸿¹⁵FE⁸﹪⊕⊗ι⁷«⸿⸿✂׳FCGDAEBι⁺¹⁵ι→⸿✂⭆♭ ♯×⁷κι⁺¹⁵ι»⟲
```
[Try it online!](https://tio.run/##bVDdSsMwFL5enyLkKoEIisjGdqXODcHiyNzdbmJ22gWzZqRpb8QH8SHEd9qLZKddKUK9yjmH7zd6r7x2ysa48qYIbLo5CiKhBl8Ck6rIgdFrKgidUM75LJGQWdDhFQFWHRleLjy69bRf3swBSjZG1un7hza01NXAptLk@/Av6rdFdRFaGJ63/q/ozR2OmfOEpWg8ESR1u8o69lxoDwcoAuzY3FXvFl/DuSBjDEw@k1Ef8KLW7WtrNHQZbtFs8bic3z89UCQaQVa2KtER57b1aJBsoLQOuORNtKY0aSoJ0lf84EPdWfKVSBdUgBfIAn5ljPGqtmc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
↑⮌…0¦8‖O
```
Print the characters `0` to `7` reversed, then reflect with overlap. Lists normally print downwards, so printing upwards actually prints rightwards; we'll rotate everything into place at the end.
```
⸿×⁷♭M→×⁷♯
```
Start a new line and print 7 flats and 7 sharps with a gap in between.
```
→⸿⸿¹⁵
```
Leave a blank line and print 15 `-`s.
```
FE⁸﹪⊕⊗ι⁷«
```
Take the numbers 0 to 7, double them, add 1, then reduce modulo 7. Loop over the result.
```
⸿⸿✂׳FCGDAEBι⁺¹⁵ι
```
Leave a blank line and then take a 15-character slice of the triplicated string of notes starting at the current value.
```
→⸿✂⭆♭ ♯×⁷κι⁺¹⁵ι
```
On the next line take a 15-character slice of flats, spaces and sharps, each repeated 7 times.
```
»⟲
```
After printing all the notes, rotate everything into place.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 113 bytes (~~131 126 108~~ 105 with # and b)
```
-7.upto(7){|i|print i.abs," ♭♯"[i<=>0]," - ",(4..11).map{|j|("FCGDAEB"*3)[k=j*2%7-i]+"♭♯ "[~k/7]}*" ",$/}
```
[Try it online!](https://tio.run/##KypNqvz/X9dcr7SgJF/DXLO6JrOmoCgzr0QhUy8xqVhHSeHRzLWPZq5Xis60sbUziAUK6Coo6WiY6OkZGmrq5SYWVNdk1WgouTm7uzi6OilpGWtGZ9tmaRmpmutmxmorQXQrKEXXZeubx9ZqKQE1q@jX/v8PAA "Ruby – Try It Online")
# [Ruby](https://www.ruby-lang.org/), 116 bytes (108 with # and b)
[Try it online!](https://tio.run/##KypNqvz/X9dcr7SgJF/DXLO6JrOmoCgzr0QhUy8xqVhHSeHRzLWPZq5Xis60sbUziAUK6CoBCdViJS0LVQ0TPT1DQ0293MSC6pqsGg0lN2d3F0dXJyUtY83obNssLSNVc93MWG0liCEKStF12frmsbU6Kvq1//8DAA "Ruby – Try It Online")
# [Ruby](https://www.ruby-lang.org/), 126 bytes (118 with # and b)
[Try it online!](https://tio.run/##KypNqvz/X9dcr7SgJF/DXLO6JrOmoCgzr0QhUy8xqVhHSeHRzLWPZq5Xis60sbUziAUK6CrpKKkWK2lZqEYb6ZjomOkY6hjrmOqY6xjF6uUmFlTXZNUoKShpayg5uTq6uDu7KWkZa0Zn6mbFaitBzFJQitYA8jX1zWNrdVT0a///BwA "Ruby – Try It Online")
# [Ruby](https://www.ruby-lang.org/), 131 bytes with # and b
[Try it online!](https://tio.run/##DcdLDoIwEADQqzSDkwBO@RS0GzXxf4imC7oriUoYWBjK2atv98bZfWOUupiH6ZPqbAk@DKN/T8IXnWMC4RIw/nA8VfYfKYBSuCLfkO/ID@Qn8hn5ggx5rTLj86Yi1Vo0ilraU00N7UiTssWrG5bQB3CJAJN62WeltlsQsNKmXGP8AQ "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 135 bytes
*counting ♯ and ♭ as 1 byte each*
thanks to [Zacharý](https://codegolf.stackexchange.com/users/55550/zachar%C3%BD) for -6 bytes.
```
for i in range(15):k=' ♯♭'[(i<7)-(i>7)]+' -';print(str(i-7)[-1]+k,*[v+k[a+8>i>a]for a,v in zip([1,3,5,0,2,4,6,1],('CDEFGAB'*8)[i*3:])])
```
[Try it online!](https://tio.run/##FczbCcIwFADQVfKXm@QGjLW2VC34HiLkIx8@LoW0xFLQTTqEuFMXifQMcLp3/2xDltK9jYwYBRZ9eNzA5KJqdpxN428av9wCbQuhgepCOMWZ5psuUujh1UcgXQirjVMNSjuoxnpV1lR7N58eh3n9UAfWYIY5LnCJK1yjcQj8eDpfrvsDl6WwJLPKCSdS@gM "Python 3 – Try It Online")
[Answer]
# [GNU sed](https://www.gnu.org/software/sed/), ~~148~~ 144 + 1 = 145 bytes
+1 byte for `-r` flag.
```
s/^/ 7# - C# D# E# F# G# A# B# \n65432101234567/
:
s/((.).(. - )((\S..){3})([^-]+)..\n)([0-7])/\1\2\7\3\6\2 \4\n/
s/ 0#/b0b/
t
s/^.//gm
s/0b/0 /
```
[Try it online!](https://tio.run/##DYu7DsIwDAD3fIUlL4lQ7DRpG4mN9wcw4naoQIiBFJFuiF8nZLs76fLtWkrmkSEiWNgh7BEOCEeEE8IGYYsgqe/a4BvX@NB2fWS1Vpm1JkOa6mS0ljOR@YSv0ZfRDitDJKmys3EwLI14iRKkFw/SSuK6g0Oe3MRqqTIS8/1ZoQYHXIr6za/lMadc7PsP "sed 4.2.2 – Try It Online")
## Explanation
First, insert a template of sorts:
```
7# - C# D# E# F# G# A# B#
65432101234567
```
Note the leading and trailing space on the first line.
In a loop, take the first number from the last line and replace it with parts of the second-to-last line like so:
```
7# - C# D# E# F# G# A# B#
│ └┬─┘└───┬───┘└───┬────┘
2 3 4 6
│ │ └────────│──┐
├──│────────────┐ │ │
│ │ ┌─────│──┘ │
│ ┌┴─┐┌───┴────┐│ ┌───┴───┐
6# - F# G# A# B C# D# E#
```
As you can see, the initial space (capture 2) is used to replace the character after the `B`.
When the `0` is reached, replace the initial space with `b`. The loop continues, but instead of replacing `#`s with spaces, on each subsequent line a space is replaced with a `b`.
Finally, do a little cleanup: Remove the leading character from each line and replace `0b` with `0`.
[Answer]
# Befunge, ~~134~~ ~~132~~ 130 bytes
```
<v:,,," - ",g2+!!\`0::,+*86*-1*2`0::p00:<75
@>4*65*+81v>55+,$$\:00g0`!\9p3+7%\1-:8+#^_
b#"A"%7:\_^#:-1,*84,g2*+1`0g00!!g9%7:\+1,+
```
[Try it online!](http://befunge.tryitonline.net/#code=PHY6LCwsIiAtICIsZzIrISFcYDA6OiwrKjg2Ki0xKjJgMDo6cDAwOjw3NQpAPjQqNjUqKzgxdj41NSssJCRcOjAwZzBgIVw5cDMrNyVcMS06OCsjXl8KIGIjIkEiJTc6XF9eIzotMSwqODQsZzIqKzFgMGcwMCEhZzklNzpcKzEsKw&input=)
**Explanation**
* We begin with an outer loop counting down from 7 to -7. We'll call this the *row* number.
* For each row, we start by writing out `'0'+abs(row)` (the scale number), and then calculate `(row>0)+(row!=0)` to lookup whether it's natural, sharp, or flat in the table `#b` (you'll see this at the start of the third line of code).
* We then calculate the scale's start note, *n*, as `30 + row*4`. This will ultimately be mod 7, so think of it as the repeating sequence 2,5,1,4,0,3,6 (i.e. CFBEADG).
* Our inner loop, *i*, then counts down from 8 to 1, for the eight notes in the scale, incrementing *n* on each iteration.
* The letter of the note is simply `'A' + n%7`. Whether it is sharp or flat is determined by looking up `i%7` in a table. The table is initially all true, since the first scale is all sharps.
* After each row is output, though, we update the table by toggling one value. On the first iteration we'll toggle the value at offset 5, but each loop the offset is adjusted by `(offset+3)%7`.
* On the first half of the output, when the *row* is greater than zero, we're toggling these table values to false. On the second half of the output, when the *row* is less than or equal to zero, we're setting them back to true.
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 107 bytes
Bubblegum threshold
```
00000000: 4dca a90d 0301 1443 41ee 2a9e f4b1 a5ec M......CA.*.....
00000010: 8d73 f7e1 fe8b 48a0 e968 aec1 3c87 d7f0 .s....H..h..<...
00000020: 1e3e c377 b80f 8ff9 a3ce c165 74d4 31b8 .>.w.......et.1.
00000030: 8c8a da07 1751 4fdb e022 ea69 1d5c 443d .....QO..".i.\D=
00000040: 2d83 8ba8 a71b b888 7a5a 828b 524f 6b70 -.......zZ..ROkp
00000050: 51fa 690b 2e4b 47ed c165 e9a8 23b8 2c1d Q.i..KG..e..#.,.
00000060: 7506 97a5 a3ae e0b2 74d4 0f u.......t..
```
[Try it online!](https://tio.run/##VZDLSgQxEEX3fsVFd6JFKo9OWlQQBQWRYVyKmzwqKioIziD4823NTIt4VyGQk3tuWZfyJk/r92kyc07gW83Io2kwzjDYewfPIrB5FHRfGDlIBe5om8sLOtwe9nYEVkZq0aFHYXRJBT5lAxmHhCyV4WqKaLEbgD43L2@InolO/xhWGSxOUF2MKMl0pN5HZFf1joeA6JuH45KUcU5fuyokK@Jfhtv0qCmjZRPBMTB8bwVirIXkYQS3UKF6TRmbLBdE@/RCj1dnM8Mrw7bkkErW8pGLlkkJMYeMZFUtWN8xlKgux3OJ7wei@8Xrx8wIygjcM4bRFFjxukeUttOQUbnWqYatrD2W@j3dXqsJ0QEd/boMyojBDBj1Z10hi2oUu1tBx/mX9dxjRTRNPw "Bubblegum – Try It Online")
[Answer]
# JavaScript (ES6), ~~130~~ 124 bytes
Or ~~128~~ [**121 bytes**](https://tio.run/##DcvtCoIwFIDh/13FouRsHlZGyGioo@@LCMGPNApxURE7VNe@/PvyvLfyXT7rx/X@kr09N963KXcppZFIM0oWseHOAAOEzXa3PxzXcOIULtGJQOUIE1YNwYVxoJDEXH2jXBej6YcSZZSkAYCmTBmSCqECDRGDH5OFwJYjumBlnB7jsGoAX9v@abtm1tkLb7kQ/g8) with a leading newline.
```
f=(y=14,x=8)=>x?f(y,x-1)+' '+'BCDEFGA'[(y*3+x)%7]+'# b'[(x*5%7+y)/7|0]:(y?f(y-1)+`
`:'')+`${y<7?7-y+'#':y>7?y-7+'b':'0 '} -`
O.innerText = f()
```
```
<pre id=O style="font-size:11px"></pre>
```
[Answer]
# C, ~~212~~ ~~189~~ ~~186~~ 185 bytes
*Thanks to @Jonathan Frech for saving a byte!*
```
#define N n>0?35:98:32);
f(i,n){for(n=8;--n+8;puts(""))for(i=-1,printf("%d%c -",abs(n),n?N++i<8;)printf(" %c%c",(n*4+65+i)%7+65,"\377\277\273\233\231\211\10\0@Ddfv\367\377"[n+7]&1<<i?N}
```
[Try it online!](https://tio.run/##NY5LCsIwGIT3PUWIRBKTQNOoqbZaF657AeOipkay8Fd8bUrPXlPBgY@BYRjGyYtzwzBpzz7AGdUItmmlF@tVvtYZKxJPgwDW@duDwiYvpASeF/f360kxZmyMw0YqcX8EeHmKSUscklg0pycFJqCqOQ9lXrB/ARFHHBYUZnO@XPDAiIkusNXG2OyHtpkeUTZTyqrUprt96z9WL83Ywgfg5jhVZRmquh/iLLo2AShLugRFeRpv98MX)
**Unrolled:**
```
#define N n>0 ? 35 : 98 : 32);
f(i, n)
{
for (n=8; --n+8; puts(""))
for (i=-1, printf("%d%c -", abs(n), n?N ++i<8;)
printf(" %c%c",
(n*4+65+i)%7 + 65,
"\377\277\273\233\231\211\10\0@Ddfv\367\377"[n+7] & 1<<i ? N
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~57 56 55~~ 54 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to [EriktheOutgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) (use `7ŒR` to replace `-7r7`)
```
_Ṃị“ b#”
=”B+\Çż
×3⁵+€ịØAḣ7¤ḊḊÇ€Z
7ŒRµṠÑżAW€żÇj€”-UK€Y
```
A full program printing the desired output (using `#`, `b`).
**[Try it online!](https://tio.run/##y0rNyan8/z/@4c6mh7u7HzXMUUhSftQwl8sWSDhpxxxuP7qH6/B040eNW7UfNa0BKjk8w/HhjsXmh5Y83NEFRIfbgcJRXOZHJwUd2vpw54LDE4/ucQwHih3dc7g9C0gDzdEN9QYyIv//BwA "Jelly – Try It Online")**
### How?
```
_Ṃị“ b#” - Link 1, getSharpsFlatsOrSpaces: list of integers
Ṃ - minimum (of the input list)
_ - subtract (from the input list) -- for our purposes this resets whatever our
- 1st value is to 0, since our inputs are always monotonically increasing
“ b#” - literal list of characters = [' ', 'b', '#']
ị - index into (1-based and modular)
=”B+\Çż - Link 2, addSharpsFlatsOrSpaces: list of characters e.g."CFBEADGCFBEADGC"
”B - literal character 'B'
= - equals? (vectorises) [0,0,1,0,0,0,0,0,0,1,0,0,0,0,0]
\ - cumulative reduce with:
+ - addition [0,0,1,1,1,1,1,1,1,2,2,2,2,2,2]
Ç - call the last link (1) as a monad "## bbbbbb"
ż - zip (with input) ["#C","#F"," B"," E",...," F","bB","bE","bA","bD","bG","bC"]
×3⁵+€ịØAḣ7¤ḊḊÇ€Z - link 3, getNoteLetters: list of integers e.g. [-7,-6,...,6,7]
×3 - multiply by three [-21,-18,-15,-12,-9,-6,-3,0,3,6,9,12,15,18,21]
⁵ - literal ten 10
+€ - add for €ach (in [1,10]) [[-20,...,22],[-19,...,23],...,[-11,...31]]
¤ - nilad followed by link(s) as a nilad:
ØA - yield uppercase alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ḣ7 - head to index seven "ABCDEFG"
ị - index into ["ADGCFBEADGCFBEA","BEADGCFBEADGCFB","CFBEADGCFBEADGC",...]
Ḋ - dequeue ["BEADGCFBEADGCFB","CFBEADGCFBEADGC","DGCFBEADGCFBEAD",...]
Ḋ - dequeue ["CFBEADGCFBEADGC","DGCFBEADGCFBEAD","EADGCFBEADGCFBE",...]
Ç€ - call the last link(2) as a monad for €ach
- [[["#C","#F"," B"," E",...," F","bB","bE","bA","bD","bG","bC"],...]
Z - transpose [["#C","#D",...,"#C"],["#F",..." B",...,"#F"],...]
7ŒRµṠÑżAW€żÇj€”-UK€Y - Main link: no arguments
7ŒR - absolute range of seven [-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7]
µ - start a new monadic chain (call that r)
Ṡ - sign (of r) [-1,-1,-1,-1,-1,-1,-1,0,1,1,1,1,1,1,1]
Ñ - call the next link (1) as a monad "####### bbbbbbb"
A - absolute value (of r) [7,6,5,4,3,2,1,0,1,2,3,4,5,6,7]
ż - zip [[7,'#'],[6,'#'],...,[0,' '],...,[7,'b']]
W€ - wrap €ach [[[7,'#']],[[6,'#']],...,[[0,' ']],...,[[7,'b']]]
Ç - call the last link (3) as a monad (with r) see link 3 example
ż - zip [[[['#',7]],["#C","#D",...,"#C"]],
[[['#',6]],["#F",...," B",..."#F"]], ...]
”- - literal character '-'
j€ - join for €ach [[['#',7],'-',"#C","#D",..."#C"],
[['#',6],'-',"#F",...," B",..."#F"],...]
U - upend (reverse each) [[[7,'#'],'-',"C#","D#",..."C#"],
[[6,'#'],'-',"F#",...,"B ",..."F#"],...]
K€ - join €ach with spaces [[7+"# - C# D# ... C#"],
[6+"# - F# ... B ... F#"], ...]
Y - join with newlines
- implicit print to STDOUT
```
[Answer]
# [CJam](http://cjam.readthedocs.io/en/latest/index.html), ~~109~~ ~~106~~ 94 bytes
```
{_0={_z/}|" b#"=a}:A;15,{X7-_zs\A+" - "+o7,0+{YX+7%65+c"2461357"Y=aiX\-_7,#){;0}&AS++o}fYNo}fX
```
[Try it online](http://cjam.aditsu.net/#code=%7B_0%3D%7B_z%2F%7D%7C%22%20b%23%22%3Da%7D%3AA%3B15%2C%7BX7-_zs%5CA%2B%22%20-%20%22%2Bo7%2C0%2B%7BYX%2B7%2565%2Bc%222461357%22Y%3DaiX%5C-_7%2C%23)%7B%3B0%7D%26AS%2B%2Bo%7DfYNo%7DfX%0A)
[Answer]
# Java 8, 255 bytes
*Counting ♯ and ♭ as 1 byte each.*
```
v->{String r="",t="GABCDEF";for(int i=-8;++i<8;r+="\n"){r+=(i<0?-i+"♯":i>0?i+"♭":"0 ")+" - ";for(String c:((t=t.substring(3)+t.substring(0,3))+t.charAt(0)).split(""))r+=c+("BEADGCF".substring(i<0?7+i:i).contains(c)?i<0?"♯":" ":i>0?"♭":" ")+" ";}return r;}
```
**Explanation:**
[Try it online.](https://tio.run/##TZBNasMwEIX3PcUwKwnFxpBFgxXH5H/VbArdtF0oitMqdWQjyYYSfJAeovROvYgrxy4EJJh50jw9fSdRi6AoM306fLQyF9bCg1D6cgegtMvMUcgMdl0L8OiM0m8gyVOhDlBT7tXGb7@sE05J2IGGBNo6mF2GyyZBHLkEt/PFcrXeID8WhnhnUEkw4Yyp6YQbluCLRnrxBVHTKA0Uw9@vH4zVLEqv9TfGGAFShhBAb/KfJibEJS601d5eFTKm7LaNRmPaKfJdmLkjEaWhLXPlCCKl/kXJCC7W89V2ucGbsS7HPVOxoqEstPNMLJE07eQ@G0Kfb0jXh0PemMxVRoPhTct7OGW1zz2cgVHdwTt7v@EHz6@CDnw/rcvOYVG5sPQnLtdEh5LoKs/pALtp/wA)
```
v->{ // Method with empty unused parameter and String return-type
String r="", // Result-String, starting empty
t="GABCDEF"; // Temp-String `t`, starting at "GABCDEF"
for(int i=-8;++i<8; // Loop from -7 to 7 (inclusive); range (-8;8) == [-7;7]
r+="\n"){ // After every iteration: append the result with a new-line
r+= // Append the result-String with:
(i<0? // If `i` is negative:
-i+"♯" // Append the absolute value of `i` + a literal "♯"
:i>0? // Else-if `i` is positive:
i+"♭" // Append `i` + a literal "♭"
: // Else (`i` is 0):
"0 ") // Append a literal "0" + space
+" - "; // And then append a literal " - "
for(String c:((t=t.substring(3)+t.substring(0,3))
// Split String `t` in the middle,
// and swap the two parts (i.e. "GABCDEF" becomes "CDEFGAB")
+t.charAt(0))
// Then append the first character
.split(""))
// And loop over each character:
r+=c+ // Append the result-String with this character, plus:
("BEADGCF".substring(i<0?
// If `i` is negative
7+i // Take the last `-i` characters of "BEAFGCF"
: // Else (`i` is 0 or positive)
i) // Take the last `7-i` characters of "BEAFGCF"
.contains(c)?// And if these last characters contain the current character:
i<0? // And `i` is negative:
"♯" // Append a literal "♯"
: // Else (`i` is 0 or positive)
" " // Append a space
:i>0? // Else-if `i` is positive
"♭" // Append a literal "♭"
: // Else:
" ") // Append a space
+" ";} // And then append a space
return r;} // Return the result-String
```
]
|
[Question]
[
A standard ruler of length *n* has distance marks at positions 0, 1, ..., *n* (in whichever units). A [sparse ruler](https://en.wikipedia.org/wiki/Sparse_ruler) has a subset of those marks. A ruler can measure the distance *k* if it has marks at positions *p* and *q* with *p*−*q*=*k*.
### The challenge
Given a positive integer *n*, output the minimum number of marks required in a sparse ruler of length *n* so that it can measure all distances 1, 2, ..., *n*.
This is [OEIS A046693](https://oeis.org/A046693).
As an example, for input 6 the output is 4. Namely, a ruler with marks at 0, 1, 4, 6 works, as 1−0=1, 6−4=2, 4−1=3, 4−0=4, 6−1=5, and 6−0=6.
### Additional rules
* The algorithm should be valid for arbitrarily large *n*. However, it is acceptable if the program is limited by memory, time or data type restrictions.
* Input/output can be taken/produced by any [reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Shortest code in bytes wins.
### Test cases
```
1 -> 2
2 -> 3
3 -> 3
4 -> 4
5 -> 4
6 -> 4
7 -> 5
8 -> 5
9 -> 5
10 -> 6
11 -> 6
12 -> 6
13 -> 6
14 -> 7
15 -> 7
16 -> 7
17 -> 7
18 -> 8
19 -> 8
20 -> 8
21 -> 8
22 -> 8
23 -> 8
24 -> 9
25 -> 9
26 -> 9
27 -> 9
28 -> 9
29 -> 9
30 -> 10
31 -> 10
32 -> 10
```
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 65 bytes
```
Tr[1^#]&@@Cases[Subsets[n=0~Range~#],k_/;Union@@Abs[k-#&/@k]==n]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVei4KCloPE/pCjaME45Vs3BwTmxOLU4Org0qTi1pDg6z9agLigxLz21TjlWJzte3zo0LzM/z8HBMak4OltXWU3fITvW1jYvVu2/poK@gwJYqYOhyX8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Mathematica, 84 bytes
```
#&@@(l=Length)/@Select[(S=Subsets)@Range[0,d=#],l@Union[Differences/@S[#,{2}]]==d&]&
```
[Try it online!](https://tio.run/##Dcu9CsIwEADghwmEFgL@4Hpwg6ODGJyODDG9tIH0Cs05ic8e/fZvjbrwGrWk2DN0YxGHCjeWWZfxgJ4rJ6XBg3@/Gmsb8RFlZjq6CUxwFZ9SNqFryZl3lsTtn8i4z/kbAsBkg@33vYhiptMl9B8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
lh.Ml{-M^Z2ySh
```
**[Try it here!](https://pyth.herokuapp.com/?code=lh.Ml%7B-M%5EZ2ySh&input=5&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0)**
# [Pyth](https://github.com/isaacg1/pyth), ~~21~~ 19 bytes
```
hlMf!-SQmaFd.cT2ySh
```
**[Try it here!](https://pyth.herokuapp.com/?code=hlMf%21-SQmaFd.cT2ySh&input=5&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0)**
## How it works
I'll update this after golfing.
```
hSlMfqSQS{maFd.cT2ySh ~ Full program. Q = input.
Sh ~ The integer range [1, Q + 1].
y ~ Powerset.
f ~ Filter (uses a variable T).
.cT2 ~ All two-element combinations of T.
m ~ Map.
aFd ~ Reduce by absolute difference.
S{ ~ Deduplicate, sort.
qSQ ~ Is equal to the integer range [1, Q]?
lM ~ Map with length.
hS ~ Minimum.
```
Thanks to [isaacg](https://codegolf.stackexchange.com/users/20080/isaacg) for saving a byte for my second approach and inspiring me to golf 3 bytes off my current approach!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~129~~ ~~128~~ 126 bytes
*thanks to [totallyhuman](https://codegolf.stackexchange.com/users/68615/totallyhuman) for -1 byte*
```
from itertools import*
r=range(1,input()+2)
[{a-b+1for a in l for b in l}>set(r)>exit(i)for i in r for l in combinations(r,i)]
```
[Try it online!](https://tio.run/##HcoxDsIwDEDRvafwmNAypAsTvQhiSKoULCV25LgSCPXsQen2pP/LV99Mc2ubcAbUKMqcKmAuLHoZ5C6eXtG4Cansauw42@Hx89cwuo0FPCBBgs5w8lhqVCN2iR9Ug7YX7EXOKXWunAOSV2SqRia0z9bc7Q8 "Python 2 – Try It Online")
output is via exit code
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~20~~ 18 bytes
```
λ▼mLfȯ≡⁰u´×≠tṖ⁰)…0
```
Thanks @H.PWiz for -2 bytes!
[Try it online!](https://tio.run/##AToAxf9odXNr/8K2bVMs4oKB4bij/8674pa8bUxmyK/iiaHigbB1wrTDl@KJoHThuZbigbAp4oCmMP///zEw "Husk – Try It Online")
### Explanation
```
λ )…0 -- lambda with argument ⁰ as [0..N]
Ṗ⁰ -- all subsets of [0..N]
t -- tail (remove empty subset)
f( ) -- filter by following function:
≠ -- absolute differences
´× -- of all pairs drawn from itself
u -- remove duplicates
≡⁰ -- "equal" to [0..N]
mL -- map length
▼ -- minimum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
‘ŒPµạþ`FQḊṫ³µÐfḢL
```
[Try it online!](https://tio.run/##ASwA0/9qZWxsef//4oCYxZJQwrXhuqHDvmBGUeG4iuG5q8KzwrXDkGbhuKJM////NQ "Jelly – Try It Online")
Saved 1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!
[Answer]
# Pyth, 15 bytes
```
lhf!-SQ-M^T2yUh
```
[Test suite](https://pyth.herokuapp.com/?code=lhf%21-SQ-M%5ET2yUh&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8&debug=0)
## How it works
```
lhf!-SQ-M^T2yUh
Uh [0, 1, ... n]
y Powerset - all possible rulers
f Filer rulers on
^T2 All pairs of marks, in both orders
-M Differences - (a)
SQ [1, ... n], the desired list of differences - (b)
- Remove (a) from (b)
! Check that there's nothing left.
h The first remaining ruler (powerset is ordered by size)
l Length
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
_þ`ẎQṢw
‘ŒPçÐfRḢL
```
[Try it online!](https://tio.run/##ASkA1v9qZWxsef//X8O@YOG6jlHhuaJ3CuKAmMWSUMOnw5BmUuG4okz///8xNA "Jelly – Try It Online")
Borrowed a trick from Mr. Xcoder's [answer](https://codegolf.stackexchange.com/a/149146/41024) for -1.
-1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒcIQL
‘ŒPÇÐṀḢL
```
A monadic link taking and returning non-negative integers.
**[Try it online!](https://tio.run/##ASQA2/9qZWxsef//xZJjSVFMCuKAmMWSUMOHw5DhuYDhuKJM////MTQ "Jelly – Try It Online")** (first 15 values [here](https://tio.run/##ASgA1/9qZWxsef//xZJjSVFMCuKAmMWSUMOHw5DhuYDhuKJM/zE1w4figqz/ "Jelly – Try It Online") - not efficient)
### How?
Finds all the rulers one could make using marks 1 through to n+1 (the power-set of [1,n+1]) ordered by their marking-count, and keeps only those which create maximal measurable distances (the length of the set of differences between all ordered pairs of marks), then returns the length of the first (i.e. [one of] the shortest one[s]).
```
ŒcIQL - Link 1: number of measurable distances: list of numbers, ruler e.g. [1,2,3,7]
Œc - all pairs [[1,2],[1,3],[1,7],[2,3],[2,7],[3,7]]
I - incremental differences [1,2,6,1,5,4]
Q - de-duplicate [1,2,6,5,4]
L - length 5
‘ŒPÇÐṀḢL - Main link: number, n e.g. 4
‘ - increment 5
ŒP - power-set (implicit range of input) [[],[1],[2],[3],[4],[5],[1,2],[1,3],[1,4],[1,5],[2,3],[2,4],[2,5],[3,4],[3,5],[4,5],[1,2,3],[1,2,4],[1,2,5],[1,3,4],[1,3,5],[1,4,5],[2,3,4],[2,3,5],[2,4,5],[3,4,5],[1,2,3,4],[1,2,3,5],[1,2,4,5],[1,3,4,5],[2,3,4,5],[1,2,3,4,5]]
ÐṀ - keep those maximal under:
Ç - call the last link (1) as a monad [[1,2,3,5],[1,2,4,5],[1,3,4,5],[1,2,3,4,5]]
Ḣ - head [1,2,3,5]
L - length 4
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 98 bytes
```
->n{(w=*0..n).find{|x|w.combination(x+1).find{|y|y.product(y).map{|a,b|(b-a).abs}.uniq.size>n}}+1}
```
[Try it online!](https://tio.run/##NcmxDoMgEADQvV/hCFov0l1/pHHgtCQMHlQlihzfTpM2nd7w1oCxmL60AyVx9HUHQBKMpTnxyQdMbkFLereOxNmof0WO4Fc3h2kXUcKifWJ9RxbYagkatwyB7Bs2e70GyrlRufjKPNV4@9L9fKixfAA "Ruby – Try It Online")
]
|
[Question]
[
A [triangular number](https://en.wikipedia.org/wiki/Triangular_number) is a number that can be expressed as the sum of consecutive positive integers, starting at 1. They can also be expressed with the formula `n(n + 1) / 2`, where `n` is some positive integer.
A number's digitangular counterpart is calculated in the following way:
1. Split a number into an array of its digits e.g. `613 => [6 1 3]`
2. For each number in the array, calculate the `n`th triangular number; `[6 1 3] => [21 1 6]`
3. Sum the resultant array; `[21 1 6] => 28`
Your task is, given an integer `n`, repeatedly calculate `n`'s digitangular counterpart, until the result is equal to 1, then output all values that were calculated. You may output the values in any order, and with an optional inclusion of the original number at the start of the array. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
## Test cases
```
23 => 9 45 25 18 37 34 16 22 6 21 4 10 1
72 => 31 7 28 39 51 16 22 6 21 4 10 1
55 => 30 6 21 4 10 1
78 => 64 31 7 28 39 51 16 22 6 21 4 10 1
613 => 28 39 51 16 22 6 21 4 10 1
8392 => 90 45 25 18 37 34 16 22 6 21 4 10 1
11111 => 5 15 16 22 6 21 4 10 1
8592025 => 117 30 6 21 4 10 1
999999999 => 405 25 18 37 34 16 22 6 21 4 10 1
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
U¡(ṁΣd
```
[Try it online!](https://tio.run/##yygtzv6vcGhbrsajpsZMzQqlQ9v@hx5aqPFwZ@O5xSn///83MuYyN@IyNeUyt@AyMzTmsjC2NOIyBAEuC1NLIwMjUy5LGAAA "Husk – Try It Online")
### Explanation
```
U¡(ṁΣd
¬°( Iterate the following function on the input:
d Split the number into digits
ṁΣ Map each digit to its triangular number, then sum the results
U Take the results of iteration until before the first repeated one
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes
```
Δ=SLO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3BTbYB////8tTC2NDIxMAQ "05AB1E – Try It Online") Edit: Saved 1 byte thanks to @Emigna. Explanation:
```
Δ Repeat until value doesn't change
= Print current value
S Split into characters
L Turn each character into range from 1 to N
O Sum
```
[Answer]
# J, ~~20~~ 19 bytes
```
(1#.2!1+,.&.":)^:a:
```
[Try it online!](https://tio.run/##jZDLCsIwEEX3fsVVQRrUkJlkmgf4K4KIRdz4/6uYVFsVtHoXAwdyuJO55Nxhp9HQUvOc1hu90ouk9umQZqfj@Yqmg2eFR7apECzBgwNshBCoBTPKIDiQAY2iyKsoAms@vvPhrSCgdX93tGTV0y30jxRsHP5UpEqIBk7AAiq6h3UTOtWoQe8JRZSpRolsuL9HbbxTUf23m8QhqgojwZkfW@Z8Aw)
Outputs the original number, too.
# Explanation
```
(1#.2!1+,.&.":)^:a:
^:a: Apply until input converges, storing all results in an array
(1#.2!1+,.&.":) Digitangular sum
,.&.": Split to digits
&.": Convert to string, apply left function, then undo conversion
,. Ravel items (make array of singleton arrays of items)
This ensures that when cast back to integers, the digits are split.
1+ Add 1 to each
2! Compute (n choose 2) on each (nth triangular number)
1#. Sum (debase 1)
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~23~~ ~~20~~ 17 bytes
*3 bytes saved thanks to @ngn*
```
{⍵∪⍨+/∊⍳¨⍎¨⍕⊃⍵}⍣≡
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71bH3WsetS7Qlv/UUfXo97Nh1Y86u0DEVMfdTUDZWsf9S5@1LkQqFzByJgrTcHcCEgYmQIJM0MQ3xIGAA)
**How?**
`⍵∪⍨` - prepend current array to the
`+/` - sum of
`‚àä` - flattened
`⍳¨` - ranges of each
`⍎¨⍕` - digit of the
`⊃⍵` - previous value
`⍣≡` until convergence. The usage of `∪` (union) makes sure after the first 1 is joined, the next will be excluded due to set uniqueness, and the array will converge.
[Answer]
## Haskell, ~~51~~ ~~47~~ 46 bytes
```
f 1=[1]
f x=x:f(sum$do d<-show x;[1..read[d]])
```
[Try it online!](https://tio.run/##NcHRCsIgFADQ977iPvSwwU26ik0rP6EvEAnBycbmNmaRf2/00DmDz1M/z7VGIGPJHSIUU66xye90DCuE@ykP6wfKzRJje@@DDc61NflxAQPJb48nNNs@Li9gsQXLBXYcpcRO4YUEKqE50g8qqfmZS9R/rn4B "Haskell – Try It Online")
```
f 1=[1] -- if x == 1, return the singleton list [1]
f x= -- else
do d<-show x -- for each char 'd' in the string representation of x
-- (using the list monad)
[1..read[d]] -- make a list of [1..d]
-- (the list monad concatenates all those lists into a single list)
sum -- sum those numbers
f -- call f on it
x: -- and put x in front of it
```
Edit: @H.PWiz saved a byte. Thanks!
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
f=lambda x:x<2and[1]or[x]+f(sum(-~int(i)*int(i)/2for i in`x`))
```
[Try it online!](https://tio.run/##NY1BCsIwFET3PcVfJhrR/FJtij1JCLRSg4E2LU2EuPHq8av0bYaZgZnlFR@zx5xtO/bTbeghNemKvR@0NPOqk9lbFp4TO7ydj8zx3V@OaOcVHDjfpY7zHO8hBmhBYyngggKqirQWcJYU1KWiSH4hUyk8IdVqwxTFtga/oaYAYlnpCyy95Q8 "Python 2 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~43~~ 41 bytes
```
Echo@#>1&�[#.(#+1)/2&@IntegerDigits@#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n1aaZ/vfNTkj30HZzlBNTdkgWllPQ1nbUFPfSM3BM68kNT21yCUzPbOk2EE5Vg2kPNrM0Dj2PwA "Wolfram Language (Mathematica) – Try It Online")
## How it works
The expression `#.(#+1)/2&@IntegerDigits@#` gives the digitangular counterpart of `#`. We `Echo` the input, use short-circuit evaluation with `&&` to stop if we've reached `1`, and otherwise recurse on the digitangular counterpart.
---
*-2 bytes thanks to Martin Ender for the `.` trick: we don't have to use `Tr` to sum the digits if we replace the multiplication `#(#+1)/2` by the dot product `#.(#+1)/2`.*
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~49~~ ~~42~~ 39 bytes
*Thanks to Misha Lavrov for saving 3 bytes.*
```
#//.x_:>(y=IntegerDigits@Echo@x).++y/2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcSHaum4KCloPFfWV9fryLeyk6j0tYzryQ1PbXIJTM9s6TYwTU5I9@hQlNPQ1u7UlPfSO2/poK@g0K1kbGOgrmRjoKpKZC20FEwMwQKWBhbAoUMQQDIMbU0MjACSlvCQO1/AA "Wolfram Language (Mathematica) – Try It Online") (TIO needs parentheses around the `++y` for some reason. In my local Mathematica installation it works without them, as it should.)
Prints each value on its own line, preceded by `>>`, and includes the starting number.
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), ~~9~~ 7 bytes
```
·Ω}#ΣΣu
```
[Try it online!](https://tio.run/##y8/INfr//9D2cytrlc8tPre49P9/cyMA "Ohm v2 – Try It Online")
**Explanation**
```
Implicit input as a string
·Ω Evaluate until the result has already been seen, pushing intermediate results
} Split digits
# Range from 0 to N
ΣΣ Sum
u Convert to string
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 21 bytes
```
;{:G`
.
$*1¶
1
$%`1
1
```
[Try it online!](https://tio.run/##K0otycxL/G@tquGe8N@62so9gUuPS0XL8NA2LkMuFdUEQy7D//@NjLnMjbhMTbnMLbjMDI25LIwtjbgMQYDLwtTSyMDIlMsSBgA "Retina – Try It Online") (The outputs of the individual cases aren't well separated, but each output ends with a `1`.)
Prints each number on its own line, in order, including the starting number.
### Explanation
```
;{:G`
```
This is just some configuration of the program. `{` makes the program loop until it fails to change the result (which happens once we get to `1`), `:` prints number before each iteration, and `;` prevents the final result from being printed twice at the end of the program. The `G` is just my usual way of creating a no-op stage.
```
.
$*1¶
```
Convert each digit to unary and put it on its own line.
```
1
$%`1
```
Compute the triangular number on each line, by replacing each `1` with its prefix. We could also use `M!&`1+` here, which gives us all suffixes of each line.
```
1
```
Count all `1`s, which sums up all the triangular numbers and converts the result back to decimal.
[Answer]
# Ruby, ~~60 47~~ 42 bytes
-13 bytes by @JustinMariner
-5 bytes by @GB
```
->x{p x=x.digits.sum{|k|k*-~k/2}while x>1}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf166iukChwrZCLyUzPbOkWK@4NLe6JrsmW0u3LlvfqLY8IzMnVaHCzrD2f1q0maFx7H8A)
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 51 bytes
```
p&>>:25*%:1+*2/v
|:/*52p00+g00<
00<vp000_@#-1.::g
```
[Try it online!](https://tio.run/##S0pNK81LT/3/v0DNzs7KyFRL1cpQW8tIv4xLQaHGSl/L1KjAwEA73cDAhguIy4Acg3gHZV1DPSur9P//LYwtjQA "Befunge-93 – Try It Online")
James Holderness cleverly reshaped my progarm into a 51-byte form. Thanks!
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), ~~24~~ ~~22~~ ~~21~~ 17 bytes
```
[sL:R{;Svc^#&1=?i
```
**[Try it online!](https://tio.run/##Kygtzqj8/z@62McqqNo6uCw5TlnN0NY@8////5YwAAA "Pushy – Try It Online")**
## Explanation
```
[sL:R{;Svc^#&1=?i
[ &1=?i \ Loop until result == 1:
s \ Split last result into digits
L: ; \ For each digit n:
R{ \ Push the range (1, n) inclusive
S \ Sum the ranges
vc^ \ Delete all stack items, except the sum
# \ Print result
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~19~~ ~~17~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Doesn't include the input as the first element.
```
Æ=ì cò xÃâ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xj3sIGPyIHjD4g&input=NjEzCi1R)
```
Æ=ì cò xÃâ :Implicit input of integer U
Æ :Map the range [0,U)
= : Reassign to U
ì : Convert to digit array
c : Flat map
ò : Range [0,digit]
x : Reduce by addition
à :End map
√¢ :Deduplicate
```
[Answer]
# [R](https://www.r-project.org/), 70 bytes
```
f=function(n)"if"(n-1,c(n,f((d=n%/%10^(nchar(n):0)%%10)%*%(d+1)/2)),n)
```
[Try it online!](https://tio.run/##DcpBCoAgEAXQuwgD88tQC1oEXiUIZcjNBFLnn9w@XjeTLJ@Wtz3KCtfEsS7JF1YvzDUrBUrxZC331cc4ImgAaCKuc0JYAa8w4T1tsB8 "R – Try It Online")
Returns the original value as well.
# [R](https://www.r-project.org/), 80 bytes
```
function(n){o={}
while(n-1){n=(d=n%/%10^(nchar(n):0)%%10)%*%(d+1)/2
o=c(o,n)}
o}
```
[Try it online!](https://tio.run/##DcpBCoAgEADAu6/osrBbiVnQIfIrQWhSELsQRQfx7dZ1mKvEatYlPuzvQxiZkriU1bsf54asLSV2GByDAdstyH5fr39NHcEPBDVgaCyZXonzKC1TVpJLxNEOVD4 "R – Try It Online")
Does not return the original value.
[Answer]
# [Lua](https://www.lua.org), 91 bytes
```
function f(n)x=0 for d in((0|n)..""):gmatch"."do x=x+d*(d+1)/2 end print(x)c=x==1or f(x)end
```
[Try it online!](https://tio.run/##DcvRCsMgDEDRXwk@JSs4KxS2QT6mmNoJWxzFQh76787Hy@F@zrX3fGpqpSpkVDIOkOsBAkURw6XkvXP02r9rS2/nnVQwtkluKNNM9wibCvyOog2NEhvzPPY8YkDP@FieMcSF@h8 "Lua – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ 12 bytes
*Saved 2 bytes thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)*
```
ΔD,þ€iLO}O}}
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3BQXncP7HjWtyfTxr/Wvrf3/38LU0sjAyBQA "05AB1E – Try It Online")
## Explanation
(old version)
```
Δþ€iD>*;}OD1›iD,}}1, Main program
Δ } Repeat until there is no changes
þ Push digits of the input number
€i } Apply for each digit
D>*; Calculate the triangular number for given digit
O Sum all numbers
D1›iD,} Print if greater than 1
1, Print 1 at the end
```
[Answer]
# JavaScript, ~~61~~ 57 bytes
```
f=a=>a-1?([...a+[]].map(b=>a+=b++*b/2,a=0),a)+' '+f(a):''
```
[Try it online!](https://tio.run/##RYzLDoIwEEX3foW7zlioUIKCSeVDkMWUh8EoJYD6@bUuoHd1cueeedCH5nrqxyUcTNNa2ylSVwrjAkohBPGyqsSLRtCu5UpzftBHGZCKMCDkbM94B4QXxuzT3BU42S3HydTtPIt5acx7Ed@pX1qAkpwXV2VUFew2MOcg14gQ4c650IFMcMWz3DBNfZtteIr9OEtyP4//8ac0l5H0H/I1iPYH "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 69 bytes
```
def f(x):
while x>1:
x=sum(-~int(z)*int(z)/2for z in`x`)
print x
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNo0LTikuhPCMzJ1Whws4QyFaosC0uzdXQrcvMK9Go0tSCUPpGaflFClUKmXkJFQmaQFUFRUAJhYr/aRoWxpZGmv8B "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
W⊖Iθ«≔IΣ⭆θΣ…·0κθθ⸿
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDJTW5KDU3Na8kNUXDObG4RKNQU1NToZqL07G4ODM9DyIWXJqrEVxSlJmX7ptYoFGoowAS8MxLziktzixLDUrMS0/VUDJQ0lHI1gQBHYVCTWsuzgCgBpB5cKZSTJESkFf7/7@FqaWRgZHpf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input
I Cast to integer
‚äñ Decrement
W « Loop while not zero
θ Current value
⭆ Map over characters and concatenate
0 Literal character 0
κ Current character
…· Inclusive range
Σ Concatenate
Σ Sum of digits
I Cast to string
≔ θ Assign back to value
θ Output latest value
‚∏ø Move to start of next line
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 62 bytes
```
?sj[0soljZ1-[dljr10r^/10%d1+*2/lo+sod1-r0<i]dsixlopdsj1<b]dsbx
```
[Try it online!](https://tio.run/##S0n@/9@@OCvaoDg/JyvKUDc6JSeryNCgKE7f0EA1xVBby0g/J1@7OD/FULfIwCYzNqU4syInvyClOMvQJgnIS6r4/9/M0BgA "dc – Try It Online")
[Answer]
# [k](https://en.wikipedia.org/wiki/K_(programming_language)), 19 bytes
```
{+/(+/1+!"I"$)'$x}\
```
Unsurprisingly works similarly to the already posted APL and J solutions
```
$x cast x (implicit var of lambda) to string
( )' apply composition (function train) to each character of string
+/1+!"I"$ cast character to number, create list from 1 to n, sum it
+/ sum triangular numbers
{ }\ iterate lambda until result converges, appending each result
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
DRFSµÐĿ
```
[Try it online!](https://tio.run/##y0rNyan8/98lyC340NbDE47s////v5ExAA "Jelly – Try It Online")
* `DRFSµÐĿ`: Full program / monadic link.
* `ÐĿ`: Loop until results are no longer unique (if something other than 1 would occur twice, then the given input does not have a defined result, since it would never reach 1).
* `D`: Convert from integer to decimal.
* `R`: Range (1-indexed). Vectorizes.
* `F`: Flatten and `S`: Sum (`µ` just creates a new monadic chain)
[Answer]
# dc, 31 bytes
```
[[I~d1+*2/rd0<m+]dsmxpd1<f]dsfx
```
The function `m` computes the digitangular function of its input; `f` repeats this until the result reaches 1.
Note that we use the input radix to extract digits - this means it will work in any base system, not only decimal.
## Demo
```
for i in 23 72 55 78 613 8392 11111 8592025 999999999
do echo $i '=>' $(dc -e $i'[[I~d1+*2/rd0<m+]dsmxpd1<f]dsfx')
done
```
```
23 => 9 45 25 18 37 34 16 22 6 21 4 10 1
72 => 31 7 28 39 51 16 22 6 21 4 10 1
55 => 30 6 21 4 10 1
78 => 64 31 7 28 39 51 16 22 6 21 4 10 1
613 => 28 39 51 16 22 6 21 4 10 1
8392 => 90 45 25 18 37 34 16 22 6 21 4 10 1
11111 => 5 15 16 22 6 21 4 10 1
8592025 => 117 30 6 21 4 10 1
999999999 => 405 25 18 37 34 16 22 6 21 4 10 1
```
[Answer]
# [Python 2](https://docs.python.org/2/), 76 bytes
```
f=lambda k,s=0:k+s<2and[1]or[k]*(s<1)+f(*[k/10,s,s+k%10*(k%10+1)/2][k<1::2])
```
[Try it online!](https://tio.run/##NYxBCoMwFET3nuJvCokGzP9iq0FPErKw2NCQNorJpqdPY6FvMcPMwOyf9NwC5Wzn1/K@rwt4EWepfBMnWsKq0WyH9qZmcULeWFZr36IUUcTGX1DW7NQGeUtG@wmVIsNzesQUYQZNnYAbCej74oOAK5Zi6MZS4UkJ/UiSyjz@MVVltwMcuAC/I1VBYT9cSGCZ4/kL "Python 2 – Try It Online")
[Answer]
# [Neim](https://github.com/okx-code/Neim), 8 bytes
```
ÕªùêÇtùïïùê¨D√∑D
```
Explanation:
```
Õª Start infinite loop
ùêÇ Split top of stack into each of its characters
t Push infinite list of triangular numbers
ùïï For each of the characters, get the nth element in the above list.
ùê¨ Sum.
D Duplicate.
√∑ If top of stack is equal to 1, break.
D Duplicate.
Implicitly print all elements in the stack, concatenated.
```
[Try it online!](https://tio.run/##y0vNzP3//@zuD3MnNJV8mDt1KpCxxuXwdpf//80MjQE "Neim – Try It Online")
[Formatted output](https://tio.run/##y0vNzP3//@zuD3MnNJV8mDt1KpCxxuXwdpf/mir/zQyNAQ "Neim – Try It Online")
[Answer]
# [D](https://dlang.org/), 140 bytes
```
import std.algorithm,std.range,std.conv,std.stdio;void f(T)(T n){n=n.text.map!(u=>u.to!T-48+(u.to!T-48).iota.sum).sum;n.writeln;if(n-1)n.f;}
```
[Try it online!](https://tio.run/##PY1LCoNAEETX8RTjrpvEhnwWgcGcwgsM0TEDTrdoawLBs0/URRZVvLepqlMKsZdBzag1ua6VIegrnjYbHLfNTk/heYc1QewsoTYeKoTKMH65ZNLmoxRdn8NUPiZSyavidj/CH5GCqKNxiriVZXqvT03HNnjg4oxM3i5pn44uMKD5ZgcPlyvabEk/ "D – Try It Online")
[Answer]
# PHP, 71+1 bytes
```
for(;1<$n="$s"?:$argn;print$s._)for($i=$s=0;$p--||~$p=$n[$i++];)$s+=$p;
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/a743695711e6a1cdcb65b6a2b1b973c59ec27d67). (requires PHP 5.3 or later for the Elvis operator)
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 32 bytes
```
D,f,@,EDBFEREss
+?
y:1
W!,$f>x,O
```
[Try it online!](https://tio.run/##S0xJKSj4/99FJ03HQcfVxcnNNci1uJhL256r0sqQK1xRRyXNrkLH/////2aGxgA "Add++ – Try It Online")
Doesn't output the first value
## How it works
```
D,f,@, - Create a monadic function, f.
- Example argument: [613]
ED - Digits; STACK = [[6 1 3]]
BF - Flatten; STACK = [6 1 3]
ER - Range; STACK = [[1 2 3 4 5 6] [1] [1 2 3]]
Es - Sum each; STACK = [21 1 6]
s - Sum; STACK = [28]
f calculates n's digitangular counterpart
+? - Take input; x = 613; y = 0
y:1 - Set y to 1; x = 613; y = 1
W!, - While x != y...
$f>x, - Call f; x = 28; y = 1
O - Print x;
```
[Answer]
# [Perl 6](http://perl6.org/), 36 bytes
```
{$_,{sum map {sum 1..$_},.comb}...1}
```
[Try it online!](https://tio.run/##NcnBCoQgFEbhV/kJaSWX8YqlzNSriA3jaqQoZhHiszsV9K0OnOWzfruadrQRQ83Cy7z9ElJYcIUiEr5Ies9pKkSkSt3CjkZ4DCNyxHEbxHnFizV6hjHoLTqlYbVjqBOscfxgA3cbn/UP "Perl 6 – Try It Online")
Includes the input number in the output list.
]
|
[Question]
[
This question is inspired by this [answer](https://codegolf.stackexchange.com/a/656/8555). Coincidentally, I used to use Ethiopian Multiplication when I was a kid, but had never known the name of the method until recently.
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
**Method:**
1. Take two numbers to be multiplied and write them down at the top of two columns.
2. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
3. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
4. Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together.
For example: 17 x 34
```
17 34
```
Halving the first column:
```
17 34
8
4
2
1
```
Doubling the second column:
```
17 34
8 68
4 136
2 272
1 544
```
Strike-out rows whose first cell is even, we'll do this by encasing those numbers on the right in square brackets:
```
17 34
8 [68]
4 [136]
2 [272]
1 544
```
Sum the remaining numbers in the right-hand column:
```
17 34
8 [68]
4 [136]
2 [272]
1 544
=====
578
```
So 17 multiplied by 34, by the Ethiopian method is 578.
**The Task:**
Golf code that takes two numbers between 1 and 1000 and perform the same layout and algorithm, displaying the product below.
Input Method: However you choose...
Example Input:
```
19 427
```
Resulting Output:
```
19 427
9 854
4 [1708]
2 [3416]
1 6832
======
8113
```
Please note the alignment of the digits. This is most important in the layout.
Also note that the double line laid out by equal signs must be two characters longer than the overall answer and must be centre justified.
**Testing**
How will you be testing this? By providing a run of your program using two numbers. These numbers can be extracted from your user ID number (this can be obtained by hovering your cursor over your avatar on the top window). Take your number and take the last three digits, this will be number B, take whatever else remains at the front, that will be number A. Then test for A times B.
Testing example:
My user ID number is 8555, so my numbers are 8 and 555. So my output should look like this:
```
8 [555]
4 [1110]
2 [2220]
1 4440
======
4440
```
**Restrictions:**
No native multiplication operators permitted save for in the use of "doubling", as per mentioned in the algorithm. In other words, if you're using an operator like \*, it can only be used for multiplying by 2 only.
Entries that do not adhere to this will not be considered and the user will be escorted off the premises with a cardboard box full of their belongings. Each entry will have code, plus the test based on your user ID number.
This is code golf. Shortest number of bytes will receive the prize, glory and admiration of their peers... (And maybe a Lamborghini... I said "maybe"!)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 91 bytes
```
≔⟦⟧τ≔⁰σNθNηWθ«⊞τ⪫ Iθ⊞υ⪫⎇﹪θ² ¦[]Iη≔⁺σ∧﹪θ²ησ≔÷θ²θ≔⁺ηηη»⊞υ…=⁺²LIσ⊞υ⪫ Iσ←E⮌τ⮌ιM⌈EυLιLυ←E⮌υ⮌ι
```
[Try it online!](https://tio.run/##fZBLSwMxFIXXzq@4zOoGUqizULC4KLpp6UgRd6WL2IlNIJOZyWNUxN8eM6@is3ARyOF85@bcnAQzp4qpENbWyrPGw5GCI6tklEsKNqqNrr178uUrN9jMtIj6XUjFIVrwlVztvRXoKGwrqTEFSCk8MOuiSyI62H60X7jRzHxiXhVeVdhQyAiFIZQejikZs6KPjqX2ylu0FNa6mAUjNhSe0I12j7KVBZ@IZj5HdKnurJLvZOqWV6rA9D6W6JmMwo7rsxPYl7GE9Kv82eTXonZwjdQO73b8Lf5Fzmp85i03lqOLz0132aNbX9aYsw9Z@hI71F8e7ICL8P/O9fO5IVzfJjfLLCzasLDqBw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⟦⟧τ≔⁰σ
```
Sets `t` to the empty list and `s` to `0`. (`u` already defaults to the empty list.)
```
NθNη
```
Inputs the two numbers.
```
Wθ«
```
Repeats while `q` is nonzero.
```
⊞τ⪫ Iθ
```
Wrap `q` in padding and append it to the list `t`.
```
⊞υ⪫⎇﹪θ² ¦[]Iη
```
Wrap `h` either in padding or `[]` depending on whether `q` is odd, and append it to the list `u`.
```
≔⁺σ∧﹪θ²ησ
```
Add `h` to `s` if `q` is odd.
```
≔÷θ²θ
```
Integer divide `q` by 2.
```
≔⁺ηηη»
```
Add `h` to itself.
```
⊞υ…=⁺²LIσ
```
Append a suitable string of `=` signs to the list `u`.
```
⊞υ⪫ Iσ
```
Append the padded sum `s` to the list `u`.
```
←E⮌τ⮌ι
```
Rotate the list `t` by 180° and print it up-side down, thus right-justifying it.
```
M⌈EυLιLυ←E⮌υ⮌ι
```
Move the cursor so that when `u` is right-justified its top left corner lines up with the top-right corner we just reached, and print `u` right-justified.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~203~~ ~~202~~ ~~187~~ 133 bytes
```
a,b=input()
s=0
while a:print'%3s%9s'%(a,'[ %%dd] '[a%2::2]%b);s+=[0,b][a%2];a/=2;b*=2
print'%10s==\n%11s'%(''.rjust(len(`s`),'='),s)
```
[Try it online!](https://tio.run/##LcxBCoMwEEDRvafIZpikDa1GClWZk9iACQoqkgYnUnr6FKHbD@/Hb5rfweTstKclxCNJVTCVxWdetkm4Nu5LSAg1Q8MI0mnsBcA4WoG9A9O2xoJXHV@pL7W3Z7Odu5Pp/IVM8edVyUSvAFV1ThBv@3pwktsU5MCD0kioNKuc66cWj8b8AA "Python 2 – Try It Online")
If I can use `*` for string multiplication (`'='*R`) and as a 'selector' (`b*(a%2)` instead of `[0,b][a%2]`), I get:
## 118 bytes
```
a,b=input()
s=0
while a:print'%3s%9s'%(a,'[ %%dd] '[a%2::2]%b);s+=a%2*b;a/=2;b*=2
print'%10s==\n%11s'%('='*len(`s`),s)
```
[Try it online!](https://tio.run/##LcvRCsIgFADQd7/Cl4u6hKYjaMr9kjWYssGEYdI1oq@3gh7Pwynvut@zbS3oiCmXZ5WKEfbstadj48GVR8pVwEAwkgAZtJg4wLrOXEwBrHN2hqg8nfCrLvpwRutjh5b9p@kJ8ZbBmN8XKLpjy3KhRWlSrQ1XzS@j/QA "Python 2 – Try It Online")
---
## Explanation:
```
a,b=input() #Get input
L=len(`a`) #Get length of first number for adjusting text
l=[] #Output list
s=0 #Sum
while a:
B=['[%d]',' %d '][a%2]%b #B is either '[b]' or ' b ' depending on if a is odd/even
l+=[(`a`,B)] #Add a,B to output list
s+=[0,b][a%2] #Add b to sum if a is odd
a/=2; #Halve a
b*=2; #Double b
R=len(B) #Length of last B for adjusting output
l+=[('',''.rjust(R,'='))] #Add double line ==== to output list
l+=[('','%d '%s)] #Add sum to output list
for x,y in l:
print x.rjust(L),y.rjust(R) #Print adjusted numbers
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~353~~ ~~316~~ ~~267~~ ~~214~~ 210 bytes
```
(a,b)->{int g=0;for(;a>0;g+=a%2*b,a/=2,b*=2)System.out.printf("%1$8d%2$10s\n",a,a%2<1?"["+b+"]":b+" ");System.out.printf("%1$19s%2$18s","".valueOf(new char[(int)Math.log10(g)+3]).replace("\0","=")+"\n",g+" ");}
```
[Try it online!](https://tio.run/##bZDBbsIwDEDv/YooAimhJWvLpMFKmbSddkA7cAQObklDWJtUSco0Ib69S7ce54Nl2X6y9S5whbluubqcPnvZtNo4dPE91jlZs6pTpZNasVkWBG1X1LJEZQ3Woi1IhW4B8mEdON9/lW9a2a7hZv2uHBfcRGgsNqhCOeoJRAWdb25SOSTyOKu0IRls4kyEOUzTWRHBQ55GxSxP6e7bOt4w3TnWGg9UBE@TyfI0TSdJbA8KRxB5Zp284D0OixAf8bPPCNPsfzRZ2YFdWhxhzK5Qd/yjIop/ofIMZk/8It2CO7NaiyQmgoaLI2WGtzWUnOBD7Lkc0xAPt8XfpXvvtQwKRjWjiauWJ9R4QWTn/ANif0RghKWjryEqBmXJW0eeFhFaxY80@x3dg3v/Aw "Java (OpenJDK 8) – Try It Online")
[Answer]
# Mathematica, 264 bytes
```
(s=#;k=(i=IntegerLength)@s;t=#2;w=0;P=Print;T=Table;While[s>0,If[OddQ@s,P[""<>T[" ",k-i@s],s," ",""<>T[" ",i[s(t)]-i@t],t];w=w+t,P[""<>T[" ",k-i@s],s,""<>T[" ",i[s(t)]-i@t]," [",t,"]"]];s=Quotient[s,2];t=2t];P[" "<>T[" ",k],""<>T["=",i@w+2]];P[" "<>T[" ",k],w])&
```
**input**
>
> [19,427]
>
>
>
**output**
```
19 427
9 854
4 [1708]
2 [3416]
1 6832
======
8113
```
[Answer]
# [Perl 5](https://www.perl.org/), 157 bytes
155 bytes of code + 2 command line flags (`-nl`)
```
$\=<>;$w=y///c;$y=2+length$\<<((log)/log 2);while($_){$s+=$\if$_%2;printf"%${w}s %${y}s\n",$_,$_%2?$\.$":"[$\]";$_>>=1;$\<<=1}say$"x++$w,'='x$y;say$"x++$w,$s
```
[Try it online!](https://tio.run/##TYzdCoIwAEbvewoZn6T4lwMTmrMn6AlaSIR/MKY4QYf46q266@Y7cA58Yz3JzFoIXpQMCzdJkrwYDKeBrFU7dxBF4XlyaP3kOw712dL1svZQ@Rt0wCH6BpVL2Tj1am6Ii23ZtfOF2bVQJEQV/voVIga5kDvEgzBUZclT9jvn6a6fBmQNAizhkR9XGPZnoK3N6SE/5@9hnPtBaRvdsviUnmwk1Qc "Perl 5 – Try It Online")
[Answer]
# JavaScript 2017, 221 bytes
Mostly a problem of output formatting
```
(a,b)=>{for(t=b,r=0,l=[],w=`${a}`.length;a;l.push([a,t]),a>>=1,t+=t)z=`${r+=a&1&&t}`.length+2;P=(s,w)=>`${s}`.padStart(w);return[...l.map(([a,b])=>P(a,w)+P(a&1?b+' ':`[${b}]`,z+1)),P('='.repeat(z),z-~w),P(r,z+w)].join`
`}
```
*Less golfed*
```
(a, b) => {
var w=`${a}`.length, r=0, l=[]
while(a) {
r += a&1 && b
l.push([a,b])
a >>= 1
b += b
}
// algo complete, result in r, now display it and the steps in l[]
var z=`${r}`.length+2
var P= (s,w) => `${s}`.padStart(w)
return [... l.map( ([a,b]) => P(a,w) + P(a&1?b+' ' : `[${b}]`, z+1) )
, P('='.repeat(z), z+w+1)
, P(r, z+w)
].join`\n`
}
```
**Test**
```
var F=
(a,b)=>{for(t=b,r=0,l=[],w=`${a}`.length;a;l.push([a,t]),a>>=1,t+=t)z=`${r+=a&1&&t}`.length+2;P=(s,w)=>`${s}`.padStart(w);return[...l.map(([a,b])=>P(a,w)+P(a&1?b+' ':`[${b}]`,z+1)),P('='.repeat(z),z-~w),P(r,z+w)].join`
`}
function update(){
var i=I.value, [a,b]=i.match(/\d+/g)
O.textContent=F(+a,+b)
}
update()
```
```
<input id=I value='21x348' oninput='update()'><pre id=O></pre>
```
[Answer]
## C, C++, ~~319~~ ~~313~~ ~~301~~ 299 bytes
-8 bytes thanks to Zacharý
Great thanks to `printf` magic i just learnt in 60 minutes between the edits
```
#include<string.h>
#include<stdio.h>
#define O printf("%*d %c%*d%c\n",5,a,a%2?32:91,9,b,a%2?32:93);
void m(int a,int b){int r=0,i=0;O while(a>1){r+=a%2*b;a/=2;b*=2;O}r+=b;char t[20],p[20];memset(t,0,20);memset(p,0,20);sprintf(t,"%d",r);memset(p,61,strlen(t)+2);printf("%*c%*s\n%*d",5,32,12,p,16,r);}
```
### C++ optimization, replace header `stdio.h` by `cstdio` and `string.h` by `cstring`, saves 2 byte
Compilation with MSVC requires to add `#pragma warning(disable:4996)` in order to use `sprintf`
Testing with my PPCG ID :
72 x 535 =>
```
72 [ 535]
36 [ 1070]
18 [ 2140]
9 4280
4 [ 8560]
2 [ 17120]
1 34240
=======
38520
```
It respects the rules, digit are aligned, and the equal signs will always be 2 char larger than the final number. Example with 17 x 34 =>
```
17 34
8 [ 68]
4 [ 136]
2 [ 272]
1 544
=====
578
```
[Answer]
# [Bash], ~~144~~ ~~142~~ ~~140~~ ~~131~~ 128 bytes
Better respect of display, note there is a trailing space character
```
read a b;for((;a;));{ ((a%2))&&((r+=b))&&x=$b\ ||x=[$b];printf %3s%9s\\n $a "$x"
((a/=2,b+=b));};printf %12s\\n =${r//?/=}= $r\
```
First answer
```
read a b;while((a));do ((a%2))&&((r+=b))&&printf "%6s %6s
" $a $b||printf "%6s [%6s]
" $a $b;((a/=2,b+=b));done;printf "%6s %7s
" \ ==== \ $r
```
[Answer]
# [Haskell](https://www.haskell.org/), 305 bytes
```
i=iterate
s=show
l=length.s
a!b=zip((takeWhile(>0).i(`div`2))a)(i(*2)b)
a?b=sum[y|(x,y)<-a!b,rem x 2>0]
a%b=l(snd.last$a!b)
a#b=unlines$[(' '<$[1..l a-l x])++s x++(' '<$[-1..a%b-l y])++if mod x 2<1then show[y]else(' ':s y)|(x,y)<-a!b]++map((++)(' '<$[-1..l a+a%b-l(a?b)]))['='<$[1..l a+1+a%b],' ':(s$a?b)]
```
[Try it online!](https://tio.run/##ZY9RT4MwFIXf@RXXgFmv3chACGro/AO@@eADIVkJVZqVbqGdgvG/Y7sscZn38Xz3nHtux81OKDXPkkkrBm5FYJjp9l@BYkroD9vFJuA3DfuWB0Is34m3TipBNmuMJdm28nObInIkktyl2GDAnxtmjn01/ZBxOWG5cublIHoYId2s64DfNkwRo9tYcWMjR50nbNhRK6mFiSqygEUZVUkcK@ArBWONlBoYKT2TlUMuxaHJI/kO/b718WViO6HBt6@mWigjvOPJwIQXZWpKe@5@oRQvAt0tegol7gGsEasF@6tBEw/rpY8jJjqtzD2XGhi0@wDcHI721Q4vGiJIivA@89o/8BhmaXGtPoR5nl@LaRJmRTH/Ag "Haskell – Try It Online")
The `!` operator creates the two lists, `?` computes the product. `%` and `#` are used for the ascii layout.
[Answer]
# C, ~~205~~ ~~201~~ ~~190~~ ~~183~~ ~~156~~ ~~150~~ 143 bytes
This will compile with warnings as C89, & I don't believe it's valid C99, but it ends up being smaller than HatsuPointerKun's version, as it saves bytes by ommitting `#include`'s, not using dynamic lengths to printf as they're unneeded, & using `log10()` to calculate the number of `=`'s needed:
```
r;m(a,b){r=0;while(a){printf(a%2?"%4d%10d\n":"%4d [%8d]\n",a,b);r+=a%2?b:0;a/=2;b<<=1;}printf("%15.*s\n%14d",(int)log10(r)+3,"==========",r);}
```
As my number is `64586`, I used this test program to calculate `64 * 586`:
```
#include <stdio.h>
int m(int a, int b);
int main(void)
{
m(64, 586);
putchar('\n');
}
```
& it outputs:
```
64 [ 586]
32 [ 1172]
16 [ 2344]
8 [ 4688]
4 [ 9376]
2 [ 18752]
1 37504
=======
37504
```
### edit
saved 4 bytes by the "implicit int" rule
### edit 2
saved 11 bytes by changing to a `do...while()` loop & moving the printf into the loop from a macro. Also should work correctly if `a=1`.
### edit 3
saved 7 bytes & made the code work right.
### edit 4
Saved 26 bytes with some printf trickery.
### edit 5
saved 6 bytes by collapsing extra padding into 1 number.
### edit 6
saved 7 bytes by printf trickery with the ternary operator & not declaring an unused variable
[Answer]
# Excel VBA, ~~183~~ 172 bytes
An anonymous VBE immediate window function that takes input from range `[A1:B1]` and outputs to the console.
```
a=[A1]:b=[B1]:k=" ":While a:c=a Mod 2:?Right(k &a,2)Right(k &IIf(c,b &" ","["&b &"]"),7):s=s+IIf(c,b,0):a=a\2:b=b*2:Wend:?Right(k &String(Len(s)+2,61),9):?Right(k &s,9)
```
## Ungolfed
```
Sub EthiopianMultiply(ByVal a As Integer, b As Integer)
Const k As String = " "
While a
Let c = a Mod 2
Debug.Print Right(k & a, 2);
Debug.Print Right(k & IIf(c, b & " ", "[" & b & "]"), 7)
Let s = s + IIf(c, b, 0)
Let a = a \ 2
Let b = Int(b * 2)
Wend
Debug.Print Right(k & String(Len(s) + 2, 61), 9)
Debug.Print Right(k & s, 9)
End Sub
```
## Output
```
61 486
30 [972]
15 1944
7 3888
3 7776
1 15552
=======
29646
```
[Answer]
# Excel, 201 Bytes
An anonymous worksheet function that takes no input and outputs as plain text to the calling cell. Output is best viewed with word wrapping, a wide column width, and a monospace font on the calling cell.
Functions for all inputs such that \$(A<10^5)\land(B\*2^{\lceil Log\_2 A\rceil}<10^7)\$.
### Golfed
```
=Let(s," ",z,2^Sequence(Log(A1,2)+1,,0),a,Int(A1/z),b,B1*z,c,Sum(IsOdd(a)*b),TextJoin("
",,Right(s&a,4)&Right(s&If(IsOdd(a),b&" ","["&b&"]"),8),Right(s&Rept("=",Len(c)+2),12),Right(s&c,11)))
```
### Commented
```
=Let(s," ", ' Define var block, hold 10 spaces in s
z,2^Sequence(Log(A1,2)+1,,0), ' z=array of powers of 2
a,Int(A1/z), ' a=⌊Input 1/z⌋ - left array
b,B1*z, ' b=B1*2^{0...⌈log2(A1)⌉} - ~right array
c,Sum(IsOdd(A)*B), ' c=∑(If a(i)Is Odd b(i)) - Sum
TextJoin("\n",, ' concat w. `\n` delimiter from below:
Right(s&a,4)& ' `a` value, padded to 4 chars concat with
If(IsOdd(a),b&" "," ["&b&"]")' `b` value, wrapped in `[]` if `a` val is even
Right(s& ...,8), ' padded to 8 chars
Right(s&Rept("=",Len(c)+2),12), ' the `=` line
Right(s&c,11))) ' the sum
```
# Output
[](https://i.stack.imgur.com/CBDLf.png)
]
|
[Question]
[
Consider the natural sequence up-to 6 *(disregard 1)*:
```
2,3,4,5,6
```
We start scanning from the left (in this case from 2), search for a number divisible by 2 (here 4) and then remove both the numbers from the list (here 2 & 4), such that the list reduces to:
```
3,5,6
```
We continue the same process, here leftmost is 3, so we search for number divisible by 3. 6 is surely that number and thus 3 and 6 are removed,
```
5
```
Now, no further such searches can be made Thus, this becomes the list of ALONED numbers for n=6.
**OBJECTIVE**
1. Given a number n greater than 1, print all the corresponding aloned numbers.
**INPUT**
```
2
6
15
20
22
```
**OUTPUT**
```
2
5
8,9,11,12,13,15
11,12,13,15,17,19,20
12,13,15,17,19,20,21
```
**YET ANOTHER WORKED OUT EXAMPLE**
*For n= 22*
```
=>2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
=>3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22 (remove 2 & 4)
=>5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22 (remove 3 & 6)
=>7,8,9,11,12,13,14,15,16,17,18,19,20,21,22 (remove 5 & 10)
=>8,9,11,12,13,15,16,17,18,19,20,21,22 (remove 7 & 14)
=>9,11,12,13,15,17,18,19,20,21,22 (remove 8 & 16)
=>11,12,13,15,17,19,20,21,22 (remove 9 & 18)
=>12,13,15,17,19,20,21 (remove 11 & 22) (OUTPUT)
```
***This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.***
[Answer]
## Python 2, ~~90~~ ~~79~~ 73 bytes
*-6 bytes thanks to xnor*
```
L=range(2,input()+1)
while L[0]*2<=L[-1]:L.remove(L[0]*2);L=L[1:]
print L
```
Takes the input number on stdin. [Ideone it!](http://ideone.com/GXFLiX)
### Explanation
We construct the initial list from the input number and store it in `L`. Next, loop while the last number is greater than or equal to 2 times the first number and remove 2 times the first number from the list. This will always be the next number divisible by `L[0]`. `L=L[1:]` takes off the first number as well. When the condition is no longer true, no further removals can be made, and the list is printed.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~22~~ ~~17~~ ~~15~~ 14 bytes
```
L¦¹F¬·©¹›_i¦®K
```
[Try it online!](http://05ab1e.tryitonline.net/#code=TMKmwrlGwqzCt8KpwrnigLpfacKmwq5L&input=MjI)
**Explanation**
```
L¦ # push the list [2..input]
¹F # input nr of times do:
i # if
¬·© # the first element in the list * 2
¹›_ # is less than or equal to input
# then
¦ # remove first element of list
®K # and remove it's multiple
```
[Answer]
## Python, 61 bytes
```
lambda n:[i+1for i in range(n/2,n)if-~i&~i&4**n/3>>(-~i&i<1)]
```
It's a bit easier to understand this less golfed code:
```
lambda n:[i for i in range(n/2+1,n+1)if((i&-i)**.5%1>0)^(i&~-i>0)]
```
This uses a direct characterization of aloned numbers:
>
> A number `i` is *aloned* if, when decomposed as `i = a * 2^b` with `b` odd, either
>
>
> * `a>1` and `b` is even, or
> * `a==1` and `b` is odd
>
>
> The aloned numbers for `n` are all aloned numbers `i` in the interval `n/2 + 1 <= i <= n`.
>
>
>
Why does this hold? When doing the process for `n`, say we remove an odd number `a` in the lower half (`1` to `n/2`). Then, `2*a` is removed no matter where in the list it is. So, `4*a` remains (if it existed). But if it's in the lower half, the deletion process will get to it and remove both `4*a` and `8*a`. So, we see that an upper-half number gets removed if it's of form `2*a`, `8*a` ... with odd `c`, but stays if it has form `a`, `4*a`, `8*a`, ...
The exception is for `a=1`, which does not start in the list and so is not removed. As a result, the removal chain starts with `a=2`, and the rule for powers of 2 is flipped.
```
lambda n:[i for i in range(n/2+1,n+1)if((i&-i)**.5%1>0)^(i&~-i>0)]
```
In the code above, `(i&-i)**.5%1>0` checks whether `i` lacks the form `i = a * 2^b` with `b` odd, by the bit-trick to extract the greatest power-of-two factor, `2^b = i&-i`, then checking if the result is not a perfect square. Then, `i&~-i>0` is another bit trick to check if `i` is not a perfect power of 2. These conditions are then xor'ed.
There's some more improvements here
```
lambda n:[i+1for i in range(n/2,n)if-~i&~i&4**n/3>>(-~i&i<1)]
```
First, we shift the range 1 index down to to shorten to `range(n/2,n)` from `range(n/2+1,n+1)`, compensating by replacing all `i` with `i+1` (or `~-i`).
Whether a power of 2 is number is a power of `4` (2^`b` with `b` even) can be checked by and-ing with `2**c/3` for some large `c`. This is because `2**c/3` has binary representation `10101...101` with ones in the even-positioned bits. Using `c=2*n` suffices. To negate result when `i` is a power of 2, we halve this number is that case, putting `1`'s in the odd positions instead.
[Answer]
# Groovy, ~~65~~ 58 Bytes
Algorithm idea from [DSLoc](https://codegolf.stackexchange.com/a/96966/59376), who noticed you need only to remove the doubles.
```
{n->a=(2..n);(2..(n/2)).each{if(it in a){a-=[it,it*2]}};a}
```
Here's a breakdown:
```
{
n->
a=(2..n); // Store [2,...,n].
(2..(n/2)).each { // From 2 to half of n.
if(it in a){ // If it's there...
a-=[it,it*2] // Remove it and its double, store in a.
}
};
a // Return a.
}
```
[Answer]
# Perl, ~~53~~ ~~49~~ ~~45~~ 44 bytes
Includes +1 for `-n`
Give input number on STDIN:
```
perl -M5.010 aloned.pl <<< 22
```
`aloned.pl`:
```
#!/usr/bin/perl -n
@F[$F[$_*2]/2,$_*2,1]=0,$_&&say for@F=0..$_
```
Directly checking the possible numbers is longer:
```
map{/$/;$_/=4until$_%4;$_%2^$_<3&&say$`}$_/2+1..$_
```
This checks all numbers in the upper half range. Keep numbers that have an even number of 2 as prime factors except if the number is a power of 2 then odd (because 1 is left out of the original series). This method should however work well for other languages.
[Answer]
# [MATL](http://github.com/lmendo/MATL), 18 bytes
*Borrowed the "multiply by 2" idea from [@Emigna's 05AB1E answer](https://codegolf.stackexchange.com/a/96971/36398)*.
```
q:Qt"t1)tEhym?6MX-
```
[Try it online!](http://matl.tryitonline.net/#code=cTpRdCJ0MSl0RWh5bT82TVgt&input=MjI)
### Explanation
```
q:Q % Input n implicitly. Push [2 3 ... n]
t" % Duplicate. For each: repeat n-1 times
t1) % Duplicate. Get first element from current array, say k
tEh % Append twice that value: gives array [k 2*k]
y % Push another copy of current array
m? % If both k and 2*k are members of the array
6M % Push [k 2*k] again
X- % Set difference: remove from current array
% End if implicitly
% End for each implicitly
% Display implicitly
```
[Answer]
## Haskell, ~~71~~ ~~69~~ ~~62~~ 56 bytes
```
g(a:b)|s<-filter(/=2*a)b=[a|s==b]++g s
g x=x
q n=g[2..n]
```
Usage example: `q 22` -> `[12,13,15,17,19,20,21]`.
If there's a multiple of the first number `a`, then it's `2*a`. Keep `a` if `2*a` is not in the list and append a recursive call with `a` and `2*a` removed from the list.
[Answer]
# Pyth - 19 bytes
Will *definitely* be refactoring.
```
u?Kf!%ThGtG-tGhKGtS
```
[Test Suite](http://pyth.herokuapp.com/?code=u%3FKf%21%25ThGtG-tGhKGtS&test_suite=1&test_suite_input=2%0A6%0A15%0A20%0A22&debug=0).
[Answer]
## Ruby, 124
Comparing scores to other answers, this is obviously the wrong approach:
```
->n{a={};b=[*2..n].each{|k|a[k]=7}
b.map{|i|g=b.select{|x|a[i]&&a[x]&&x%i<1}
a[g[0]]=a[g[1]]=!g[1]}
a.select{|k,v|v&k}.keys}
```
The somewhat clever bit here is `a[g[0]]=a[g[1]]=!g[1]` which sets the hash's values to true/false as necessary.
[Answer]
# PHP, 98 Bytes
```
foreach($r=range(2,$argv[1])as$v)$a=&$r[$v-2]&&$b=&$r[$v*2-2]?$b=$a="":(!$a?:print$x?",$a":$x=$a);
```
8 Bytes save by [@Titus](https://codegolf.stackexchange.com/users/55735/titus) Thank You
If a trailing comma is allowed then it can be shorten 9 Bytes
`(!$a?:print"$a,");` instead of `(!$a?:print$x?",$a":$x=$a);`
[Answer]
## Javascript, 149 bytes
```
function a(n){o=Array.from(Array((n+1)).keys());o.shift();o.shift();for(i=1;i<o.length;i++){if(o[i]%o[0]==0){o.splice(i,1);o.shift();i=0;}}return o;}
```
Here's a working example. All the HTML and the wrapper() function is just so it's actually interactive.
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Aloned</title>
<script>
function wrapper(){document.getElementById("o").innerHTML = a(parseInt(document.getElementById("i").value));}
function a(n){o=Array.from(Array((n+1)).keys());o.shift();o.shift();for(i=1;i<o.length;i++){if(o[i]%o[0]==0){o.splice(i,1);o.shift();i=0;}}return o;}
</script>
</head>
<body>
<p>Enter an integer:</p>
<p><input type="text" id="i" value="5" /></p>
<p><input type="button" value="Alone It!" onclick="wrapper()" /></p>
<div id="o"></div>
</body>
</html>
```
This ungolfed code snippet has some comments and lets you interactively see the steps for any given input.
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Aloned</title>
<script>
function wrapper()
{
document.getElementById("o").innerHTML = aloned(parseInt(document.getElementById("i").value));
}
function aloned(n)
{
// From nils peterson's comment on benmcdonald's answer
// http://stackoverflow.com/questions/3895478
// Creates an array from 0 to n.
o=Array.from(Array((n+1)).keys());
// Remove 0 and 1 from the start of the array.
o.shift();
o.shift();
// s and t are just used to display the output each iteration.
var s = String(o);
// Go through every item in the array (except the first).
for(i = 1; i < o.length; i++)
{
// Check for an item evenly divisible by the first item.
if (o[i]%o[0]==0)
{
var t=" (remove "+o[0]+" and "+o[i]+")";
// Splice removes the current item, shift removes the first item.
o.splice(i,1);
o.shift();
// Reset the array, so we're looping from the beginning again.
i=0;
s = s + "<br />" + String(o) + t;
}
}
return s + " (OUTPUT)";
}
</script>
</head>
<body>
<p>Enter an integer:</p>
<p><input type="text" id="i" value="5" /></p>
<p><input type="button" value="Alone It!" onclick="wrapper()" /></p>
<div id="o"></div>
</body>
</html>
```
[Answer]
# JavaScript (ES6), 92 bytes
```
f=(n,R=[...Array(n-1)].map((_,i)=>i+2),[i,...r]=R)=>~r.indexOf(i*=2)?f(n,r.filter(x=>x-i)):R
```
I thought I had posted this yesterday, but obviously not...
Here's another version:
```
f=(n,R=[...Array(n-1)].map((_,i)=>i+2),[i,...r]=R,q=r.filter(x=>x-i*2))=>q+""!=r+""?f(n,q):R
```
[Answer]
# Java 7, 210 bytes
```
import java.util.*;List c(int n){List<Integer>l=new ArrayList();int i=1;for(;i++<n;l.add(i));for(i=1;i++<n;)for(int x:l)if(i!=x&x%i<1&l.indexOf(i)>=0){l.remove((Integer)i);l.remove((Integer)x);break;}return l;}
```
Can definitely be golfed some more by using a different approach, probably by using an array with some tricks. Due to the cast, break, typed-list and if-checks it is a bit longer than expected, but it works.
**Ungolfed & test code:**
[Try it here.](https://ideone.com/EDldZq)
```
import java.util.*;
class M{
static List c(int n){
List<Integer> l = new ArrayList();
int i = 1;
for(; i++ < n; l.add(i));
for(i = 1; i++ < n;){
for(int x : l){
if(i != x & x%i < 1 & l.indexOf(i) >= 0){
l.remove((Integer)i);
l.remove((Integer)x);
break;
}
}
}
return l;
}
public static void main(String[] a){
System.out.println(Arrays.toString(c(2).toArray()));
System.out.println(Arrays.toString(c(6).toArray()));
System.out.println(Arrays.toString(c(15).toArray()));
System.out.println(Arrays.toString(c(20).toArray()));
System.out.println(Arrays.toString(c(22).toArray()));
}
}
```
**Output:**
```
[2]
[5]
[8, 9, 11, 12, 13, 15]
[11, 12, 13, 15, 17, 19, 20]
[12, 13, 15, 17, 19, 20, 21]
```
[Answer]
## Racket 191 bytes
```
(let loop((fl(range 2(add1 n)))(fg #f))(define i(first fl))(for((j(rest fl))
#:when(= 0(modulo j i))#:final(= 0(modulo j i)))
(set! fl(remove*(list i j)fl))(set! fg #t))(if fg(loop fl #f)fl))
```
Ungolfed (comments after ';'):
```
(define (f n)
(let loop ((fl (range 2 (add1 n))) ; create a full list of numbers
(fg #f)) ; flag to show if main list is modified
(define i (first fl))
(for ((j (rest fl)) #:when (= 0 (modulo j i)) ; test divisibility
#:final (= 0 (modulo j i)))
(set! fl (remove* (list i j) fl)) ; remove these from main list
(set! fg #t))
(if fg (loop fl #f) ; if main list modified, check again,
fl))) ; else print modified list.
```
Testing:
```
(f 2)
(f 6)
(f 15)
(f 20)
(f 22)
```
Output:
```
'(2)
'(5)
'(8 9 11 12 13 15)
'(11 12 13 15 17 19 20)
'(12 13 15 17 19 20 21)
```
]
|
[Question]
[
Write a function which takes a single positive integer *n* and returns the period of the decimal representation of 1/*n*.
Test cases:
```
1 -> 1 # 1/1 = 1.0000...... = 1._0
2 -> 1 # 1/2 = 0.5000...... = 0.5_0
3 -> 1 # 1/3 = 0.3333...... = 0._3
7 -> 6 # 1/7 = 0.14285714.. = 0._142857
13 -> 6
14 -> 6
123 -> 5
345 -> 22
654 -> 108
12345 -> 822
67890 -> 120
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Built-ins or libraries which return the period directly are not permitted. Numbers up to at least 100000 should work within reasonable time (at most several minutes).
[Answer]
# APL, 19 chars/bytes\*
```
{(↑⍳⍨1∘↓)⌽⍵|10x*⍳⍵}
```
[Nars2000](http://www.nars2000.org/). The previous version was wrong on some numbers, this should be right. I manually checked it on all numbers up to 50.
Again, credit goes to [Ben Reich](https://codegolf.stackexchange.com/users/11218/ben-reich) for the idea of looking at the period of `10^i (mod x)`
**Exploded view**
```
{ ⍳⍵} generate all naturals up to the argument ⍵
10x* raise 10 to each of them, with unlimited precision
⍵| compute the respective remainders mod ⍵
⌽ reverse the list
( ⍳⍨ ) (fork) find the position of the first occurrence
↑ of the fist element of the list
1∘↓ in the remainder of the list
```
**Examples**
```
{(↑⍳⍨1∘↓)⌽⍵|10x*⍳⍵}¨1 2 3 7 13 14 123 345 654 12345 67890
1 1 1 6 6 6 5 22 108 822 120
```
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.
[Answer]
## GolfScript (42 27)
```
{:x)1\[{.10*x%}*]-1%(?)}:P;
```
Benchmark time: 5 secs. Benchmarking code:
```
'"The time is #{Time.now#1
}"'~ puts
[1 2 3 7 13 14 123 345 654 12345 67890 99991]{[P]p}%
'"The time is #{Time.now#2
}"'~ puts
```
Credit to Ben Reich for the core idea of looking at the period of `10^i (mod x)`.
### Explanation
The period `p` is defined as the smallest positive integer such that for all sufficiently large `i` we have `frac(10^i * 1/x) = frac(10^(i+p) * 1/x)`. We can simplify that slightly to `frac(10^i / x) = frac(10^(i+p) / x)`. Now, `frac(a / x) = frac(b / x)` iff `a == b (mod x)`, so we're looking for the smallest positive integer such that for all sufficiently large `i`: `10^i == 10^(i+p) (mod x)`.
Suppose `10^i == 10^(i+p) (mod x)`. Then `10^(i+1) == 10 * 10^i == 10 * 10^(i+p) == 10^(i+p+1) (mod x)`; so once we get a repetition, we're in an unbreakable cycle.
There are only `x` distinct values `(mod x)`, so by the pigeonhole principle we must get a repetition in the first `x + 1` values of `10^i (mod x)`.
So what the code above does is to compute `x + 2` values of `10^i (mod x)`\*. Then the last one is guaranteed to be a repetition, and by reversing the list and searching for it I can find the most recent occurrence. Moreover, because I'm only doing the one search this is pseudolinear time.
\* The extra one is to handle the special case `x = 1`, because I don't reduce `10^0 (mod x)` and so I'd be looking for a `0` in `[1]`.
[Answer]
## Golfscript - 26 bytes
```
{:i.)+.,{;10*i%.}%i>|,}:f;
```
*Edit: updated to output `1` if the decimal terminates, rather than the length of the decimal representation.*
A fairly efficient version. The value *67890* runs in approximately 10 seconds, and *99991* around 20 seconds. It's a bit slower than it was before (roughly half as fast), because the range that is iterated has been doubled, the first half of which is ignored.
**Alternative, also 26 bytes**
```
{:i.)+.n*{*i%.}%i>)^^,}:f;
```
This one works by iterating over the string `"\n"*(2*i+1)`, where `i` is the value passed to the function. The value passed to the block each time is the ordinal value of `"\n"`, which is *10*.
The `)^^` is a bit of a work-around. When you [uncons](http://www.golfscript.com/golfscript/builtin.html#%29) a character from a string, the result is the ordinal value of the character removed, as mentioned above. However, appending that value back on will append the *string representation* of that number, rather than the character - fairly nonsymmetric behavior, and in my opinion a design flaw. If you actually wanted to do that, stringifying first would only cost one byte.
An extra copy of the final value is already on the stack, so I remove the final value again `)`, xor it with the string, and then xor it again, so that any characters which were added or removed by the first xor are restored. If `int op string` were treated as a character, rather than its string representation, `)^^` could be replaced by `|`.
Note that while strings (which in Golfscript are stored as an array of ints) will display the value of each character mod *256*, the values of each character may themselves be outside this range. When testing for uniqueness (via set operations) or containedness (via `?`), it is the actual value that is compared, rather than the display value.
A patch file for the [current Golfscript interpreter](http://www.golfscript.com/golfscript/golfscript.rb):
```
61c61
< to_gs
---
> Gstring.new([self])
```
The above will only affect the behavior of `string op int` (and vice versa), where `op` is one of
`+-|&^`. Everything else remains unaffected, including the behavior of `Gint``.
The following **24 byte** solution would then become valid:
```
{:i.)+.n*{*i%.}%i>|,}:f;
```
And this also fixes a lot of other [really ugly work-arounds](https://codegolf.stackexchange.com/a/8399/).
---
## Python - 48 bytes
```
f=lambda n:len(set(10**-~i%n for i in range(n)))
```
Not the most efficient solution, but reasonable for values less than *100000*.
FWIW, the core element is identical to my solution for [Generate cyclic numbers in decimal](https://codegolf.stackexchange.com/questions/12076/).
A more efficient version of the same code (**70 bytes**):
```
def f(n):
a=[];i=10%n
while i not in a:a+=i,;i=i*10%n
return len(a)
```
The value *99991* takes less than a second.
[Answer]
## GolfScript, ~~48~~ ~~47~~ 46
Thanks to @PeterTaylor for chopping two chars off.
```
{2{1$1$%!{.@\/\d}*}:d~;5d;9{2$%}{10*9+}/+,}:f;
```
I tried using J, but it kept giving me all sorts of strange results.
[Test online](http://golfscript.apphb.com/?c=O3syezEkMSQlIXsuQFwvXGR9Kn06ZH47NWQ7OXsyJCV9ezEwKjkrfS8rLH06ZjsKWzEgMiAzIDcgMTMgMTQgMTIzIDM0NSA2NTQgMTIzNDUgNjc4OTBdCntmfSVw)
This basically divides 2 and 5 out of the number (2 and 5 are the prime factors of 10, and their reciprocals terminate, and stuff up the algorithm), then the lowest integer n such that the resulting number divides 10^n - 1 is the period.
[Answer]
## Perl, 52 characters
```
sub f{($p,%r)=1;1until$r{$p=$p*10%$_[0]}++;~~keys%r}
```
This is an uncomplicated implementation of the direct approach. (Fortunately the direct approach is also pretty efficient: thanks to modulo arithmetic, the math never has to deal with a number more than 10 times the input value.)
Since the challenge specified a function, I felt compelled to (re-)initialize my variables, something I wouldn't bother doing for a complete program. Likewise, the `~~` in the final statement is unnecessary if the function can be certain it will be invoked in a scalar context.
[Answer]
# Clojure, ~~102, 117, 115~~, 106
unformated:
```
(defn r([n](r{}(iterate #(mod(* % 10)n)10)0))([a[f & s]i](if(a f)(- i(a f))(recur(assoc a f i)s(inc i)))))
```
formatted:
```
(defn r
([n] (r {} (iterate #(mod (* % 10) n) 10) 0))
([a [f & s] i]
(if (a f)
(- i (a f))
(recur
(assoc a f i)
s
(inc i)))))
```
Running time scales with the period. Almost instantaneous on my computer for the sample values.
Basically, this calculates the result of the subtraction after each step in long division. A cycle is detected if at any point that number is the same as one that has been calculated before it.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÌLR°I%ćk>
```
Port of [*@PeterTaylor* GolfScript answer](https://codegolf.stackexchange.com/a/18550/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f//cI9P0KENnqpH2rPt/v83NjEFAA) or [verify almost all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/wz0@QYc2VKoeac@2@6/zP9pQx0jHWMdcx9BYx9BEx9DIWMfYxFTHzBTMNjGNBQA). The last test case is omitted, which takes little over a minute.
If we want to output all test cases in less than a second, a port of [*@primo*'s Python answer](https://codegolf.stackexchange.com/a/19682/52210) could be used, which comes in at **14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** with a minor alternative of the same approach using a cumulative right-reduce:
```
>LTªÅ«T*I%}ćk>
```
[Try it online](https://tio.run/##yy9OTMpM/f/fzifk0KrDrYdWh2h5qtYeac@2@//fzNzC0gAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf/tfEIOrTrcemh1iNahdaq1R9qz7f7r/I821DHSMdYx1zE01jE00TE0MtYxNjHVMTMFs0EscwtLAx1LIDCMBQA).
**Explanation:**
Based on the input \$n\$, I first generate a list within the range \$[n+1,1]\$. And then find the first 1-based index of a value \$x\$ which is truthy for \$10^x\pmod n=10^{n+2}\pmod n\$.
```
Ì # Increase the (implicit) input-integer by 2
L # Pop and push a list in the range [1,input+2]
R # Reverse it to the range [input+2,1]
° # Map each value to 10 to the power that value
I% # Modulo the input
ć # Extract head; pop and push remainder-list and first item separately
k # Get the 0-based index of this 10**(input+2) in the list of
# [10**(input+1),10**input,...,100,10]
> # Increase this by 1 to make it a 1-based index
# (which is output implicitly as result)
```
```
>L # Push a list in the range [1,input+1]
Tª # Append a trailing 10
Å« # Cumulative right-reduce, keeping all intermediate results:
T* # Multiply the current integer by 10
I% # Modulo the input
} # After the right-reduce:
ćk> # Get the 1-based index of the extracted head, similar as above
# (which is output implicitly as result)
```
[Answer]
# Pyth, 13 bytes
```
fq.^;yTQ.^;TQ
```
Uses [turtle-and-hare algorithm](https://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare) ([more information](https://www.quora.com/How-does-Floyds-cycle-finding-algorithm-work)).
[Watch it pass every test.](http://pyth.herokuapp.com/?code=fq.%5E%3ByTQ.%5E%3BTQ&test_suite=1&test_suite_input=1%0A2%0A3%0A7%0A13%0A14%0A123%0A345%0A654%0A12345%0A67890+&debug=0)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 8 bytes
```
⇧ɾṘ↵%ḣḟ›
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwi4oenyb7huZjihrUl4bij4bif4oC6IiwiIiwiMzQ1Il0=)
Port of 05AB1E.
## How?
```
⇧ɾṘ↵%ḣḟ›
⇧ɾ # Push range [1, (implicit) input + 2]
Ṙ # Reverse to make it range [input + 2, 1]
↵ # Map each value to 10 to the power of it
% # Modulo by the (implicit) input
ḣ # Head extract, push a[0] and a[1:]
ḟ # Get the index of this a[0] in this a[1:]
› # Increment to make this a one-based index
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 33 bytes
```
n->znorder(Mod(10,n/gcd(n,10^n)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWNxXzdO2q8vKLUlKLNHzzUzQMDXTy9NOTUzTydAwN4vI0NTWhCoMTCwpyKjUSFXTtFAqKMvNKgEwlEEdJIU0jUVNTRyHaUEfBSEfBWEfBXEfBEEgZmgCxEZBhbGKqo2BmCuGC2eYWlgaxUKMXLIDQAA)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
üpßN▲╞§
```
[Run and debug it](https://staxlang.xyz/#p=8170e14e1ec615&i=1%0A2%0A3%0A7%0A13%0A14%0A123%0A345%0A654%0A12345%0A67890&a=1&m=2)
**Approach:**
1. Multiply by 10
2. Keep only fractional part
3. Repeat until a loop of values is found
4. Keep only the loop
5. Get the length
]
|
[Question]
[
**Challenge**
The challenge is to write a program that takes the coefficients of any n-degree polynomial equation as input and returns the **integral** values of x for which the equation holds true. The coefficients will be provided as input in the order of decreasing or increasing power. You can assume all the coefficients to be **integers**.
**Input And Output**
The input will be the coefficients of the equation in decreasing or increasing order of power. The degree of the equation, i.e, maximum power of x, is always 1 less than the total no of elements in the input.
For example:
```
[1,2,3,4,5] -> represents x^4 + 2x^3 + 3x^2 + 4x + 5 = 0 (degree = 4, as there are 5 elements)
[4,0,0,3] -> represents 4x^3 + 3 = 0 (degree = 3, as there are 3+1 = 4 elements)
```
Your output should be only the **distinct integral values** of x which satisfy the given equation. All the input coefficients are integers and the input polynomial **will not be a zero polynomial**. If there is no solution for the given equation, then the output is undefined.
If an equation has repeated roots, display that particular root only once. You can output the values in any order. Also, assume that the input will contain at-least 2 numbers.
**Examples**
```
[1,5,6] -> (-3,-2)
[10,-42,8] -> (4)
[1,-2,0] -> (0,2)
[1, 1, -39, -121, -10, 168] -> (-4, -3, -2, 1, 7)
[1, 0, -13, 0, 36] -> (-3, -2, 2, 3)
[1,-5] -> (5)
[1,2,3] -> -
```
Note that the equation in the second example also has the root 0.2, but it is not displayed as 0.2 is not an integer.
**Scoring**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (in bytes) wins!
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes
```
|stE:-GyZQ~)
```
[Try it online!](https://tio.run/##y00syfn/v6a4xNVK170yKrBO8///aEMdBQMdBV1DYzBtbBYLAA)
This uses the [fact](https://en.wikipedia.org/wiki/Properties_of_polynomial_roots#Bounds_on_(complex)_polynomial_roots) that, for integer coefficients, the absolute value of any root is strictly less than the sum of absolute values of the coefficients.
### Explanation
Consider input `[1 5 6]` as an example.
```
| % Implicit input. Absolute value
% STACK: [1 5 6]
s % Sum
% STACK: 12
t % Duplicate
% STACK: 12, 12
E % Multiply by 2
% STACK: 12, 24
: % Range
% STACK: 12, [1 2 ... 23 24]
- % Subtract, elemet-wise
% STACK: [11 10 ... -11 -12]
G % Push input again
% STACK: [11 10 ... -11 -12], [1 5 6]
y % Duplicate from below
% STACK: [11 10 ... -11 -12], [1 5 6], [11 10 ... -11 -12]
ZQ % Polyval: values of polynomial at specified inputs
% STACK: [11 10 ... -11 -12], [182 156 ... 72 90]
~ % Logical negation: turns nonzero into zero
% STACK: [11 10 ... -11 -12], [0 0 ... 0] (contains 1 for roots)
) % Index: uses second input as a mask for the first. Implicit display
% STACK: [-3 -2]
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~10~~ 9 bytes
-1 byte thanks to Zgarb
```
uSȯf¬`Bṁṡ
```
[Try it online!](https://tio.run/##yygtzv7/vzT4xPq0Q2sSnB7ubHy4c@H///@jDXVMdcxiAQ "Husk – Try It Online")
### Explanation
```
ṁṡ Concatenate together the symmetric ranges of each coefficient
(It is guaranteed that the integer roots lie in the range [-n..n],
where n is the coefficient with the largest magnitude)
Sȯf Find all the values in that range which
¬ are zero
`B when plugged through the polynomial
(Base conversion acts as polynomial evaluation)
u De-duplicate the roots
```
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
```
f l|t<-sum$abs<$>l=[i|i<-[-t..t],foldl1((+).(i*))l==0]
```
[Try it online!](https://tio.run/##VYxBDsIgEEX3nmIWXYACKcU2mhRv4AkIC4w2Eqe1sbjr3RG6sZ3FzPyX/Pd00@uBGGMHOIeWT9@@cLepLS6ojZ99yw0PQgTLujfeURJyoIL4PaWodWlj7/wAGno3XoGMHz8EENDRHaQxYCSDmkFjl8xSLhnwY8Xg9EeJJFCuQWbqnJas8ptbstlUskeq5apm46rXKYmVBRt/ "Haskell – Try It Online")
Brute force and synthetic division.
## Ungolfed with [UniHaskell](https://github.com/totallyhuman/unihaskell) and `-XUnicodeSyntax`
```
import UniHaskell
roots ∷ Num a ⇒ [a] → [a]
roots xs = [r | r ← -bound … bound, foldl1 ((+) ∘ (r ×)) xs ≡ 0]
where bound = sum $ abs § xs
```
## Alternate solution, 44 bytes
*Credit to nimi.*
```
f l=[i|i<-[minBound..],foldl1((+).(i*))l==0]
```
Good luck with [trying it online](https://tio.run/##VYwxD4IwFIR3f8WNrZaGUiFK7OLm4C9oOpAgsaEUorj532vLIrzhvXvf5e7ZvPuHcyF0cErbr71kerD@On58y7lh3ehaJwg5UE7snlKnVG7C0FgPhaGZ7iDTy/oZHB3dIY6GFgwlQ2VQ19A3P5vFYNHIGbJjwXD6o0giyNcgMXmOSxRJppSoNpHUI@RyZbXpKtdfLJYGJvwA "Haskell – Try It Online"), as this checks *every* number in an `Int`'s range.
[Answer]
# [Python 2](https://docs.python.org/2/) + numpy, ~~95~~ ~~93~~ ~~91~~ ~~103~~ ~~93~~ ~~91~~ 82 bytes
-2 bytes thanks to ovs
thanks Luis Mendo for the upper/lower bounds of the roots
-10 bytes thanks to Mr. Xcoder
```
from numpy import*
def f(r):s=sum(fabs(r));q=arange(-s,s);print q[polyval(r,q)==0]
```
[Try it online!](https://tio.run/##LY7LDoMgEEX3/Qp2YjMkgtW0Gr6EsLCptCbyELCJX29Bu5lzJnMzuW6LH2vYvitvNTKrdhuatLM@Xi@vUSGFfdkFHlaN1fAMaSv7hQ9@MO8RkwCh7J2fTESLcHbevsOMPSwl55Xc4xhi4EJQaKCVIGgF5MbgnhUIg@qQpPUDCGVJUoK25z1laZ1m3Z7x5gCDWsqLsh7l52gyB0N3dsjeK5zxr1UU@w8 "Python 2 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~50~~ ~~47~~ ~~42~~ ~~25~~ 27 bytes
```
{}⋃Select[x/.Solve[#~FromDigits~x==0],IntegerQ]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v7r2UXdzcGpOanJJdIW@XnB@TllqtHKdW1F@rktmemZJcV2Fra1BrI5nXklqempRYKza/4CizLyS6DSHakMDHV0TIx2L2tj/AA "Wolfram Language (Mathematica) – Try It Online")
Update: using Luis Mendo's fact, golfed off another 3 bytes
```
Pick[r=Range[s=-Tr@Abs@#,-s],#~FromDigits~r,0]&
```
Getting sloppier with the bounds, we can reduce this 5 more bytes per @Not a tree's suggestion:
```
Pick[r=Range[s=-#.#,-s],#~FromDigits~r,0]&
```
After posting this, OP commented allowing "native polynomials", so here's a 25 byte solution that accepts the polynomial as input. This works because by default Mathematica factors polynomials over the integers, and any rational roots show up in a form like `m*x+b` that fails the pattern match.
```
Cases[Factor@#,b_+x:>-b]&
```
As @alephalpha pointed out this will fail for the case where zero is a root, so to fix that we can use the `Optional` symbol `:`
```
Cases[Factor@#,b_:0+x:>-b]&
```
This parses fine Mathematica 11.0.1 but fails and requires an extra set of parentheses around `b_:0` in version 11.2. This takes up back up to 27 bytes, plus two more after version 11.0.1. It looks like a "fix" was put in [here](https://mathematica.stackexchange.com/questions/124801/pattern-matching-with-list-and-optional)
[Try it Online!](https://tio.run/##y00syUjNTSzJTE78n2b73zmxOLU42i0xuSS/yEFZRyMp3spAU7vCyk43KVbtf0BRZl5JdFq0obZRhXZFnFFsLBdMyEzbFF0IyNOuiI39DwA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~33~~ ~~26~~ 31 bytes
Fixed an error noted by Kelly Lowder in the comments.
```
x/.{}⋃Solve[#==0,x,Integers]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v0Jfr7r2UXdzcH5OWWq0sq2tgU6FjmdeSWp6alFxrNp/roCizLwSB600BX0HheqKOCNt0wptMx0FQwMgW9fEqELbQkcBxDSqANGm2hVxJrrGlhVxxrqGRoYgCaBKbUMzsCoTXUNjkBHGQAMqdE3BGrWBRhjDWYa1/wE "Wolfram Language (Mathematica) – Try It Online")
**Previous incorrect solutions:**
I just noticed that for no integer solution, the output is undefined instead of empty list; that allows to remove a few bytes.
```
x/.Solve[#==0,x,Integers]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v0JfLzg/pyw1WtnW1kCnQsczryQ1PbWoOFbtP1dAUWZeiYNWmoK@g0J1RZyRtmmFtpmOgqEBkK1rYlShbaGjAGIaVYBoU@2KOBNdY8uKOGNdQyNDkARQpbahGViVia6hMcgIY6ABFbqmYI3aQCOMa/8DAA "Wolfram Language (Mathematica) – Try It Online")
Now if no integer solution exists, the function returns `x`.
**Previously:**
```
x/.Solve[#==0,x,Integers]/.x->{}&
```
[Try it online!](https://tio.run/##HYzLCsIwFET3fkVAcGFym@ZVdBHp1p3gUgwESbVgK9QgF0q/PSZdzcCcOYOPrzD42D986mxCXl0/71@4ba2tGbLzGMMzTN87rxBO87JLm8vUj7Hdd4S3ZEYnqUHaMCLq3EFLpAdGSpVY0lB0GtQRnQIhRRkySUWzUhqEKgqVBQhmPdKsUEv6Aw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~61~~ 59 bytes
A special thanks to [@mathmandan](https://codegolf.stackexchange.com/users/36885/mathmandan) for pointing out my (incorrect) approach could be saved, and golfed!
```
function(p)(x=-(t=p[!!p][1]):t)[!outer(x,seq(p)-1,"^")%*%p]
```
[Try it online!](https://tio.run/##PYxBCsIwEEX3PcW0UpiRBIyii2JPEipImJRukpikpZ4@ZiFd/cfn8WKx8JTFrs7kxTsMhPsoMY9Bt22YtJpoyKRbv2aOuIvEn@pIJbpXR/25D1OZawCOwJcsRt7qEpzAeLexW9gZPhSwPkLmlMG8E6emmdGgEnfxIKqshhv9L3kVF6LyAw "R – Try It Online")
Takes input as a list of coefficients in *increasing* order, i.e., `c(-1,0,1)` represents `-1+0x+1x^2`.
Using the rational root theorem, the following approach very nearly works, for 47 bytes:
```
function(p)(x=-p:p)[!outer(x,seq(p)-1,"^")%*%p]
```
[Try it online!](https://tio.run/##PYtBCsIwEEX3PcVYKcxIsgiii1JPIgoyTEo3k5ikpZ4@ZtXV@zz@S9XDZKtflcsSFCPh/rBxjPQ8hbVIwt1k@TZvnenfPQ2XIb7q3CI4oh95TLI1EpyBg26iiyjLcQEfEhTJBfiTJXfdjIzO3MydqG03Xqn@AQ "R – Try It Online")
`-p:p` generates a symmetric range (with a warning) using only the first element of `p`, `a_0`. By the [Rational Root Theorem](https://en.wikipedia.org/wiki/Rational_root_theorem), all rational roots of `P` must be of the form `p/q` where `p` divides `a_0` and `q` divides `a_n` (plus or minus). Hence, using just `a_0` is sufficient for `|a_0|>0`, as for any `q`, `|p/q|<=a_0`. However, when `a_0==0`, as then *any* integer divides `0`, and thus this fails.
However, mathmandan points out that really, in this case, this means that there's a constant factor of `x^k` that can be factored out, and, assuming `k` is maximal, we see that
```
P(x) = x^k(a_k + a_{k+1}x + ... a_n x^{n-k}) = x^k * Q(x)
```
We then apply the Rational Root Theorem to `Q(x)`, and as `a_k` is guaranteed to be nonzero by the maximality of `k`, `a_k` provides a tidy bound for the integer roots of `Q`, and the roots of `P` are the roots of `Q` along with zero, so we will have all the integer roots of `P` by applying this method.
This is equivalent to finding the first nonzero coefficient of the polynomial, `t=p[!!p][1]` and using it instead of the naive `p[1]` as the bounds. Moreover, since the range `-t:t` always contains zero, applying `P` to this range would still give us zero as a root, if indeed it is.
### ungolfed:
```
function(polynom) {
bound <- polynom[polynom != 0][1] #first nonzero value of polynom
range <- -bound:bound #generates [-bound, ..., bound]
powers <- outer(range,seq_along(p) - 1, "^") #matrix where each row is [n^0,n^1,n^2,...,n^deg(p)]
polyVals <- powers %*% polynom #value of the polynomial @ each point in range
return(range[polyVals == 0]) #filter for zeros and return
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ASŒRḅ@Ðḟ
```
**[Try it online!](https://tio.run/##y0rNyan8/98x@OikoIc7Wh0OT3i4Y/7///@jDXVMdcxiAQ "Jelly – Try It Online") or [as a test-suite!](https://tio.run/##y0rNyan8/98x@OikoIc7Wh0OT3i4Y/7/w@2Pmta4//8fHW2oY6pjFqsTbWigo2tipGMBYuroGukYgBlAprGljq6hEZABVGFoBpEHqjU0BpLGZhDlpmDKSMc4NhYA)**
## How?
```
ASŒRḅ@Ðḟ || Full program (monadic link).
AS || Sum the absolute values.
ŒR || And create the symmetric inclusive range from its negative value.
Ðḟ || And discard those that yield a truthy value...
ḅ@ || When plugging them into the polynomial (uses base convertion).
```
Based off [Luis' answer](https://codegolf.stackexchange.com/a/154009/59487). [An alternative](https://tio.run/##y0rNyan8///opCC3wIc7Wh0OT3i4Y/7///@jDXVMdcxiAQ).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~59~~ 49 bytes
```
@(p)(x=-(t=p(~~p)(end)):sign(t):t)(!polyval(p,x))
```
[Try it online!](https://tio.run/##PYzNCoMwEITvfYr0tgubkJ8aWiHQ9xAP0qoIooEGsRdfPU2kCsPON8sw8ys0Sxs7J4SIT/AIq@MQnIdtS6Gd3ojlZ@gnCFgGhKufx@/SjOBpRYwdVIoKsjVeMkriN033fyKuSR7Mkrh5pKN0xtRlyp5VJvPP7G7sOVAcpMnUGH8 "Octave – Try It Online")
This is a port of my [R answer](https://codegolf.stackexchange.com/a/154013/67312). The only difference is that I have to explicitly use `sign(t)` and `end` to generate the range, and that it has `polyval` to compute the polynomial.
Takes input as a row vector of coefficients in decreasing order.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 31 bytes
```
p->[x-a|a<-factor(p)[,1],a'==1]
```
Factors the polynomial, and picks out the factors whose derivatives are 1.
[Try it online!](https://tio.run/##LY3NCsIwEIRfZenF/iTgJm1RMH2R0MIiVAqiS@ghgu8eN42XMPNlZpYpbPrBaQUHifXko6Yv3fRK9/0dam68wlnRyTmcEzE/PzWDnoDD9tpFVtlUsEqyUeDjYqCDoY3yjgrw3GaioTcHuigoXmyWg7C49ALsVZJWBBr8d3JZ/nE8WjmEti0HrGxHAUPZ66DM27lJPw "Pari/GP – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~127~~ ~~126~~ 123 bytes
* Saved one byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen); golfing `l+~j++` to `l-++j`.
* Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for saving three bytes.
```
x,X,j,m,p;f(A,l)int*A;{for(m=j=0;j<l;m+=abs(A[j++]));for(x=~m;X=x++<m;p||printf("%d,",x))for(p=j=0;j<l;X*=x)p+=A[l-++j]*X;}
```
[Try it online!](https://tio.run/##ddDbaoMwGADg6@0pRBgk5g@omdKR5sKeH0EQLzqHo2K60HYg2OzVXdRubJiGkASSL/@hoO9F0XUNpFCBBMVLlECND8eLl/C2/DghKSrh82pec0nE/vWMkqwiJMeY97eN@JI8FQ0hc8nV9apOhpbIfXoDFxqM@zfq94fUEw1WRCRZTQmpci/lupP7wxHh9vHBSCfJctEGEEGsHcsY0mOYq8/LGbku5qNaDMoH@hzCTNvUwqKWYywagq/tsZYWtRqVYyZlL2YJwv5oojtBPNNGrSCeqPVN@f1TNuzsT4lGrSGaqM0tw8jajF5tIJyo7ahCYPd6uLXUtftRlN3pxu6/0t03 "C (gcc) – Try It Online")
---
# Explanation
# [C (gcc)](https://gcc.gnu.org/), 517 bytes
```
x,X,j,m,p; // global integer variables
f(A,l)int*A;{ // define function, takes in integer array pointer and length
for(m=j=0;j<l;m+=abs(A[j++])); // loop through array, sum up absolute values
for(x=~m;X=x++<m; // loop through all values x in [-m, m], prime X
p||printf("%d,",x)) // at loop's end, print x value if polynomial value is zero
for(p=j=0;j<l;X*=x) // loop through coefficients
p+=A[l-++j]*X;} // build polynomial
```
[Try it online!](https://tio.run/##dZLbbqMwFEWfJ19xFKkaCEZNYBJ15PJA75@AFOXBAUNMfUFgRnRS5tczBtKqaQhCgC2vdfYxjt0sjg@HBkUoRwIVGEav62vIuNoSDkxqmtES/pCSkS2n1SS1QsRtMz8L8X6cTWjKJIW0lrFmSiLQ5JVWxvWpI2VJ3qBQ3diMZAKcykzvJpCq0hJBHsxxfsuxcAKyraxwnTvOxrZxZ@dKFaB3paqz3SBCUNUC6gLMWsVrTU1cXpus0Oua4J/AUdA4zq3A37Oe2jg/otB0cdeuQCA2CIqSCQqREULx/m5GUqfW9CpBU9TY9omQ6N75swIqk56U2th6LbDUNM3fpBKM8I@5Cv7SUnXuPm7x2X00Cxr7YthY0TRlMaNSVz0MhROEa@46Tr6ZRbj91um2Zjz5Uv4gCJOWvZ/86BKG602wX6AlWrVjJwJ3v923cVHryppObTxQdz01R@4vD920Y9TdCHU/1HI9NG/Ha92PUA8DBeZ2/d/msfC6T1MdFqub1lAPaHVGPR6pebfU79/@lxYN9YiWZ9TTMeFydDM66gl5Z9TzQHnIv7SHzyN9vXxQrn9hN15OqfbwHw "C (gcc) – Try It Online")
[Answer]
# Java 8, ~~141~~ 140 bytes
```
a->{int l=a.length,s=0,i,r,f,p;for(int n:a)s+=n<0?-n:n;for(r=~s;r++<s;System.out.print(p==0?r+",":""))for(p=i=0,f=1;i<l;f*=r)p+=a[l-++i]*f;}
```
Inspired by [*@Rod*'s Python 2 answer (his 82 bytes version)](https://codegolf.stackexchange.com/a/154008/52210).
Fun challenge! I certainly learned a lot of it when investigating about polynomials and seeing how some others here have done it.
**Explanation:**
[Try it online.](https://tio.run/##dVHLbsIwELz3K1Y5JWQd5VFQi3H5gnLpEXFwQ0JNg2PZhqpC6a@nS6CXtpFsy94ZjWd29/IkWWsqvd@@92UjnYNnqfT5DkBpX9lalhWsLk@AU6u2UIZUX29ARpyKHW1azkuvSliBBgG9ZE9nIkEjZNJUeuff0IkUFVqs0fC6tRcN0HMZuVjoRbpkeq6HuhVfjts4Xjj@8ul8dUjao0@MJX5ohEiXNg4wmAdBFF3oRigSrkXG1aLh9UTYyMRCrhsWx2ozqXnX86tDc3xtyOHN6JDkQDnDF0/au/VGRteMvnI@1NUHDCnPGU5x1g1R/2IpsvscH8ZgZDmmoyDBxSOyLKcLKWWzcR36JyvoLEadYI7FuI1p98@shhYM3J95XhugkzKUN6nfI2h0eFPq@m8)
```
a->{ // Method with integer-array parameter and no return-type
int l=a.length, // The length of the input-array
s=0, // Sum-integer, starting at 0
i, // Index integer
r, // Range-integer
f, // Factor-integer
p; // Polynomial-integer
for(int n:a) // Loop over the input-array
s+=n<0?-n:n; // And sum their absolute values
for(r=~s;r++<s; // Loop `r` from `-s` up to `s` (inclusive) (where `s` is the sum)
System.out.print(p==0?r+",":""))
// After every iteration: print the current `r` if `p` is 0
for(p=i=0, // Reset `p` to 0
f=1; // and `f` to 1
i<l; // Loop over the input-array again, this time with index (`i`)
f*=r) // After every iteration: multiply `f` with the current `r`
p+= // Sum the Polynomial-integer `p` with:
a[l-++i] // The value of the input at index `l-i-1`,
*f;} // multiplied with the current factor `f`
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/) with Symbolic Package, 63 bytes
```
@(p)(s=double(solve(poly2sym(p)==0)))(s==(t=real(s))&~mod(t,1))
```
[Try it online!](https://tio.run/##PYzPCsIwDIfvPkVPkkBW@scVPRR8D9lhuu7U0bHWwS6@em3FDULyJfn4hVfqV5dHyznPd5gRoh3C@@kdxOBXB3Pwm4rbVF7WCsQqWEh2cb2HiHj@TGGARBIxj/CQrGWmw1NFQc1F0fW/UaNI7MxKNfpWmlQVi8ukOVQm6k3/pjZHQLuTIt1h/gI "Octave – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
ÄOD(Ÿʒβ>
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cIu/i8bRHacmndtk9/9/tKGOqY5ZLAA "05AB1E – Try It Online")
[Answer]
## JavaScript (ES6), 97 bytes
```
a=>[...Array((n=Math.max(...a.map(Math.abs)))-~n)].map(_=>n--).filter(i=>!a.reduce((x,y)=>x*i+y))
```
Takes coefficients in decreasing order of power and outputs results in descending order.
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~110~~ 91 bytes
```
import StdEnv
?p#s=sum p
=[i\\i<-[~s..s]|i<>0&&sum[e*i^t\\t<-reverse(indexList p)&e<-p]==0]
```
[Try it online!](https://tio.run/##DcxBC4IwFADgu79iEEiFEzvUactLHQJvHrcFQ1/xwM3hm1IQ/fSW5w@@bgDrkxv7eQDmLPqELoxTZG3sr37J6rAhSbNjIZMKtUbB1ZfKkswHxbnK89UU7PEetY6CT7DARLBF38OrQYos7HIQPBgpK5PaaNdaspqpQ3EsTib9usdgn5T4rUmXt7cOO/oD "Clean – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 89 bytes
```
def f(a):s=sum(map(abs,a));return[n for n in range(-s,s)if reduce(lambda v,c:v*n+c,a)==0]
```
[Try it online!](https://tio.run/##LY5BDoIwEEXXeorZUXRICggxmHqRposRWiWRgbRA4ulRwNV7yc9L/vAZXz1ny9JYB05QXAUVpk50NAh6BKQ4vnk7Tp41g@s9MLQMnvhpRRIwxK0Db5uptuJN3aMhmLGu5hOf61@rlDTLWtFaaZ1igaVB0KnE5JLhdXNMMpS7gURI0nxjXv7XYmeGuTHV8TD4lkcgjNQ9wvXy8gU "Python 2 – Try It Online")
]
|
[Question]
[
If a positive integer \$N > 2\$ has (strictly) less prime factors (without counting multiplicities) than its successor and its predecessor, we will call it a *factor-poor number*.
In other words, \$\omega(N) < \omega(N - 1)\$ and \$\omega(N) < \omega(N + 1)\$, where \$\omega(N)\$ is the number of unique prime factors of \$N\$.
# Task
You can choose among the following I / O formats:
* Take an integer \$N\$ and output the \$N^{\text{th}}\$ factor-poor number. In case you choose this one, \$N\$ can either be 0 or 1 indexed.
* Take a positive integer \$N\$ and output the first \$N\$ factor-poor numbers.
* Print the sequence indefinitely.
---
You can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487), while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is code golf, so the shortest submission that abides to the rules wins.
I won't include separate test cases, because the methods of competing are different, but you can refer to the first 100 terms of this sequence, which is [OEIS A101934](https://oeis.org/A101934):
```
11, 13, 19, 23, 25, 27, 29, 37, 41, 43, 47, 49, 53, 59, 61, 64, 67, 71, 73, 79, 81, 83, 89, 97, 101, 103, 107, 109, 113, 121, 125, 131, 137, 139, 149, 151, 155, 157, 163, 167, 169, 173, 179, 181, 191, 193, 197, 199, 211, 221, 223, 227, 229, 233, 239, 241, 243, 251, 259, 263, 265, 269, 271, 277, 281, 283, 289, 293, 307, 309, 311, 313, 317, 331, 337, 341, 343, 347, 349, 353, 359, 361, 365, 367, 371, 373, 379, 383, 389, 397, 401, 407, 409, 419, 421, 431, 433, 439, 441, 443
```
As an example, \$25\$ occurs in this sequence because \$\omega(25) = 1\$ (5), \$\omega(26) = 2\$ (2 and 13) and \$\omega(24) = 2\$ (2 and 3), so \$\omega(25) < \omega(24)\$ and \$\omega(25) < \omega(26)\$.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 21 bytes
```
⟨+₁≡-₁⟩{ḋdl}ᵐ⌋>~↰₂?ẉ⊥
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8FdqPmhofdS7UBVHzV1Y/3NGdklP7cOuERz3ddnWP2jY8amqyf7ir81HX0v//AQ "Brachylog – Try It Online")
Prints infinitely.
### Explanation
```
⟨+₁≡-₁⟩ Fork: The output of the fork is [Input + 1, Input -1]
{ }ᵐ Map:
ḋdl (predicate 2) the output is the length of the prime decomposition
of the input with no duplicates
⌋ Take the minimum result of that map
> This minimum is bigger than…
~↰₂? …the output of predicate 2 with Input as input
?ẉ Write Input followed by a new line if that's the case
⊥ False: backtrack and try another value for Input
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes
```
Cr~ÆvÐṂN⁼Wø#
```
Prints the first **n** factor-poor numbers.
[Try it online!](https://tio.run/##y0rNyan8/9@5qO5wW9nhCQ93Nvk9atwTfniH8v//hgYGAA "Jelly – Try It Online")
### How it works
```
Cr~ÆvÐṂN⁼Wø# Main link. No arguments.
ø Wrap the links to the left into a chain and begin a new chain.
# Read an integer n from STDIN and call the chain to the left with
arguments k = 0, 1, 2, ... until n of them return a truthy value.
Return those n values of k as an array.
C Complement; yield -k+1.
~ Bitwise NOT; yield -k-1.
r Range; yield [-k+1, -k, -k-1].
ÐṂ Yield those elements of [-k+1, -k, -k-1] for which the link to
the left returns the minimal value.
Æv Count the number of unique prime factors.
Note that, for a negative argument, Æv counts -1 as well, and
0 is counted as a/the factor of 0. Negating the the arguments
eliminates the edge case 1 (no factors), which would be a
false positive otherwise.
For a factor-poor number, this yields [-k].
N Take the negatives of the resulting integers.
W Wrap; yield [k].
⁼ Test the results to both sides for equality.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~123~~ 119 bytes
```
q=lambda n:sum(n%i<all(i%j for j in range(2,i))for i in range(2,n+1))
i=2
while 1:
i+=1
if q(i-1)>q(i)<q(i+1):print i
```
[Try it online!](https://tio.run/##TYo7DoMwEAV7n2IbJK9ICru0MHdxxO8hs4ADiji9YzqaGWk023VMq9icdx/D8ukCifuei5YKTYhRo5ppWBPNBKEUZOy1fYH5bng2qQ2zgrfqNyH2ZJwi1N4UDrRrvA23RdwUlNVtCXIQcv4D "Python 2 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~26~~ ~~24~~ 22 bytes
```
`T@3:q+YFg!sdZSd0>?@QD
```
Prints the sequence indefinitely.
[Try it online!](https://tio.run/##y00syfn/PyHEwdiqUDvSLV2xOCUqOMXAzt4h0OX/fwA)
### Explanation
```
` % Do...while loop
T % Push true. Will be used as loop condition
@ % Push (1-based) iteration index, k
3:q % Push [1 2 3] minus 1, that is, [0 1 2]
+ % Add, element-wise. Gives [k k+1 k+2]
YF % Exponents of prime-factor decomposition. Gives a 3-row matrix
g % Convert to logical: non-zero numbers become 1
!s % Transpose, sum of each column. Gives a row vector of 3 elements,
% which are the number of unique prime factors of k, k+1 and k+2
d % Consecutive differences. Gives a row vector of 2 elements
ZS % Sign: replaces each number by -1, 0 or 1
d % Consecutive difference. Gives a single number
0> % Is it positive?
? % If so
@Q % Push k+1
D % Display
% End (implicit)
% End (implicit). The stack contains true, which (is consumed and)
% causes an infinite loop
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 22 bytes
```
f(ΠtSM<←ṙ1mȯLup§…←→)tN
```
Prints the sequence indefinitely, [try it online](https://tio.run/##yygtzv7/P03j3IKSYF@bR20THu6caZh7Yr1PacGh5Y8algFFHrVN0izx@/8fAA "Husk – Try It Online") or [view the first **N**!](https://tio.run/##yygtzv7//1HbxDSNcwtKgn1tHrVNeLhzpmHuifU@pQWHlj9qWAYUedQ2SbPE7////4YGBgA "Husk – Try It Online")
Alternatively `§oΛ>←t` [could be used](https://tio.run/##yygtzv7/P03j0PL8c7PtHrVNKHm4c6Zh7on1PqUFh5Y/algGFHrUNkmzxO//fwA "Husk – Try It Online") instead of `ΠtSM<←`.
### Explanation
```
f( )tN -- filter the tail of the naturals ([2,3…]) by:
ΠtSM<←ṙ1m(Lup)§…←→ -- | takes a number as argument, example 11
§… -- | range of..
← -- | | the argument decremented (10)
→ -- | | to the argument incremented (12)
-- | : [10,11,12]
m( ) -- | map the following (example on 12) ..
p -- | | prime factors: [2,2,3]
u -- | | deduplicate: [2,3]
L -- | | length: 2
-- | : [2,1,2]
ṙ1 -- | rotate by 1: [1,2,2]
SM< -- | map the function (< X) over the list where X is ..
← -- | | the first element (1)
-- | : [0,1,1]
t -- | tail: [1,1]
Π -- | product: 1
-- : [11,13,19,23,25,27,29…
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
.f!-.ml{Pb}tZh
```
**[Try it here!](https://pyth.herokuapp.com/?code=.f%21-.ml%7BPb%7DtZh&input=50&debug=0)**
It was initially a suggestion on [Dopapp's answer](https://codegolf.stackexchange.com/a/152418/59487), but they [told me](https://codegolf.stackexchange.com/questions/152402/factor-poor-numbers/152418#comment372445_152418) to post it separately.
### How it works?
```
.f!-.ml{Pb}tZh | Full program. Takes input from STDIN, outputs the first N to STDOUT.
.f | (var: Z) Output the first N values which satisfy the predicate.
}tZh | Creates the list [Z - 1, Z, Z + 1].
.m | (var: b) Take the elements with minimal function value.
Pb | Prime factors of b.
l{ | Deduplicate, get length.
| For a factor-poor number, this yields itself wrapped in a singleton.
- | Remove Z from that.
! | Logical negation.
```
[Answer]
# Haskell, ~~105~~ 86 bytes
*Thanks to @Wheat Wizard, @Bruce Forte, and @Laikoni for saving 19 bytes.*
`[n|n<-[2..],d n<d(n-1),d n<d(n+1)]
d x=[1|n<-[1..x],x`rem`n<1,all((>0).rem n)[2..n-1]]`
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~87~~ ~~83~~ 79 bytes
*Thanks to @Cows quack for saving a byte and thanks to @Luis Mendo for saving ~~three~~ six bytes!*
```
f=@(n)nnz(unique(factor(n)));n=9;while++n if[f(n-1) f(n+1)]>f(n)disp(n);end;end
```
Prints the sequence indefinitely.
[Try it online!](https://tio.run/##y08uSSxL/f8/zdZBI08zL69KozQvs7A0VSMtMbkkvwgopqlpnWdraV2ekZmTqq2dp5CZFp2mkadrqKkApLQNNWPtgLRmSmZxAZCyTs1LAeH//wE)
**73 bytes with leading `n =` before each value:**
```
f=@(n)nnz(unique(factor(n)));n=9;while++n if[f(n-1) f(n+1)]>f(n)n end;end
```
[Try it online!](https://tio.run/##y08uSSxL/f8/zdZBI08zL69KozQvs7A0VSMtMbkkvwgopqlpnWdraV2ekZmTqq2dp5CZFp2mkadrqKkApLQNNWPt0kA6FVLzUqyB@P9/AA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes
Outputs the nth factor-poor number (1-indexed)
```
µ3LN+Íf€gÀć›P
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0FZjHz/tw71pj5rWpB9uONL@qGFXwP//hgYGAA "05AB1E – Try It Online")
**Explanation**
```
µ # loop over N (1,2,3, ...) until counter equals input
3L # push the range [1,2,3]
N+ # add current N
Í # subtract 2
f # get unique prime factors of each
€g # get length of each factor list
À # rotate left
ć # extract the head
› # check if the remaining elements are strictly greater
P # product
# if 1, increment counter
# implicitly output final N
```
[Answer]
# Pyth, 30 25 bytes
```
#=hTI&>l{PhTKl{PT>l{PtTKT
```
This is my first *real* Pyth golf, so any comments are very appreciated.
A big thanks to Xcoder!
Explanation
```
# | Loop until error
=hT | Add one to T (initially 10)
I& | If both...
>l{PhTKl{PT | The number of unique prime factors of T+1 is greater than that of T (store in K)
>l{PtTK | And the number of unique prime factors of T-1 is greater than K (from before)
T | Then implicitly print T
```
[TIO](https://tio.run/##K6gsyfj/X9k2I8RTzS6nOiAjxBtIhoCYJSHeIf//AwA).
[Answer]
# JavaScript (ES6), 94 bytes
Returns the Nth factor-poor number, 0-indexed.
```
f=(i,n=9)=>(P=(n,i=k=1)=>++k>n?0:n%k?P(n,1):i+P(n/k--,0))(n)>P(++n)&P(n)<P(n+1)&&!i--?n:f(i,n)
```
[Try it online!](https://tio.run/##FYzBDoIwEETvfMV6EHazVNujQOEX@AWC1NSSrQHjxfjttVwmMy8z85w@0z5v/vVWEu9LSs6ir8XeyPY4WpTa22BNTsyhl0E3cg7DmLmhxnM216BUrYlQqB@RWajMlLosbKgsT16pQRp33FJycUMBC7oFgQ6MPgwzwbcAmKPscV0ua3xgNWEFnEsMFeXBEVz@pbb4pT8 "JavaScript (Node.js) – Try It Online")
### How?
We first define the **P()** function which returns the number of unique prime factors of a given integer.
```
P = ( // P = recursive function taking:
n, // n = input number to test
i = // i = flag to increment the number of prime factors
k = 1 // k = current divisor
) => //
++k > n ? // increment k; if k is greater than n:
0 // stop recursion
: // else:
n % k ? // if k is not a divisor of n:
P(n, 1) // do a recursive call with n unchanged and i = 1
: // else:
i + // add i and
P(n / k--, 0) // do a recursive call with n / k and i = 0; decrement k
```
The wrapping code now reads as:
```
f = ( // given:
i, // i = input index
n = 9 // n = counter
) => //
P(n) > P(++n) & // increment n; if P(n - 1) is greater than P(n)
P(n) < P(n + 1) && // and P(n) is less than P(n + 1)
!i-- ? // and we have reached the correct index:
n // return n
: // else:
f(i, n) // go on with the next value
```
[Answer]
# [Japt](https://ethproductions.github.io/japt/), ~~29~~ ~~27~~ 26 bytes
Not entirely happy with this but at least it's better than my first attempt which was over 40 bytes!
Outputs the `N`th number in the sequence, 1-indexed.
```
È=Jõ_+X k â ÊÃé)e>Xo)«´U}a
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=yD1K9V8rWCBrIOIgysPpKWU+WG8pq7RVfWE=&input=MTAwMA==)
---
## Explanation
Implicit input of integer `U`.
```
È }a
```
Return the first integer `X` that returns true when passed through the following function.
```
=Jõ )
```
Assign the array `[-1,0,1]` to `X`.
```
_+X Ã
```
Pass each element of that array through a function which firstly adds the current value of `X`.
```
k â Ê
```
Get the length (`Ê`) of the unique (`â`) prime factors (`k`) of the result.
```
é
```
Rotate the resulting array one to the right.
```
e>Xo)
```
Pop (`o`) the last element from `X` and check if all remaining elements are greater than it.
```
«´U
```
If so, decrement `U` and check if it is equal to 0.
[Answer]
# [Python 3](https://docs.python.org/3/), 97 bytes
```
n,g=9,lambda m,k=2,p=1:m//k and(m%k<p%k)+g(m,k+1,p*k*k)
while 1:n+=1;g(n-1)>g(n)<g(n+1)!=print(n)
```
In theory, this prints the sequence indefinitely. In practice, `g` eventually exceeds the recursion limit.
[Try it online!](https://tio.run/##DYlBCoMwEADvfUV6ELJmi6w9Vd3@JUWJsmZdRCh9fZrLDMzY71oPfZaimPiFe8yfObqMwj0a05C7TlzU2edGJmsEQvL1BkJrpRW4fddtXxwNGpjG5PVB8K6CqSIQ3NnOTa8aSvkD "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 126 bytes
```
j,t;o(n){for(j=t=0;j++<n;)if(n%j<1)for(t--;j>1>n%j;)n/=j;t=~t;}
m(J){for(J=3;;J++)if(o(J-1)>o(J)&o(J)<o(J+1))printf("%d,",J);}
```
[Try it online!](https://tio.run/##JYtBCgMhEATvecbChhlUEslxVh/gL4LB4IAalrktm68bJZdqupuK5h1j76yFGlQ8UtuBnbg7sVJbJcwJ6sqbxfmIMcTe@rEQ1ptjEvcVOi8Fwt8N7kEUlJpeg2As@hF4ndgGlEX87LlKgmV96UUHpLOXZ66AR4FZfg "C (gcc) – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~130~~ ~~123~~ 117 bytes
```
import StdEnv
?n=[1\\q<-[p\\p<-[2..n]|and[gcd p i<2\\i<-[2..p-1]]]|n rem q<1]
f=[n\\n<-[3..]| ?n<min(?(n-1))(?(n+1))]
```
Equates to an infinite number of terms of the sequence. Since it's all nested comprehensions, it can't take advantage of graph reduction very well and so is quite slow, even for such a bad algorithm.
[Try it online!](https://tio.run/##Jc2xDoMgFEDR3a94o6aBiF01Lu3QpJsjMBBAQypPVNqkid9eStPpDHe4erYKk1/Mc7bglcPkfFi2CEM0V3wVPXacCbG2hAchQqahFOWh0PBJGwjg2kYI9w@BMCnlgbBZD2vLZDF2HIXAnM@UygN6bL3Dsi@RsKr6ecrKNESVpx1E9bDA6hrG9NHjrKY9kds9Xd6ovNP7Fw "Clean – Try It Online")
[Answer]
# APL NARS, 124 bytes, 62 chars
```
{(⍵>1E4)∨⍵≤0:¯1⋄x←9+⍳10×⍵⋄⍵↑(∊{v←⍴∘∪∘π¨⍵+2-⍳3⋄2=+/v>2⌷v}¨x)/x}
```
It should return answer until 1E4, then return -1 error; it suppose 9..10xargument
has enought right numbers; test:
```
z←{(⍵>1E4)∨⍵≤0:¯1⋄x←9+⍳10×⍵⋄⍵↑(∊{v←⍴∘∪∘π¨⍵+2-⍳3⋄2=+/v>2⌷v}¨x)/x}
z 0
¯1
z 1
11
z 20
11 13 19 23 25 27 29 37 41 43 47 49 53 59 61 64 67 71 73 79
```
]
|
[Question]
[
Compress a sparse matrix using [Compressed sparse row (CSR, CRS or Yale format)](https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_row_.28CSR.2C_CRS_or_Yale_format.29).
These are all the same form of compression (ignore new Yale).
Input may be any 2d data structure (list of lists, etc): e.g
```
[[0 0 0 0],
[5 8 0 0],
[0 0 3 0],
[0 6 0 0]]
```
And the output should be three 1d data structures (list etc), that denote the outputs `A`, `IA` and `JA`, for example
```
[5, 8, 3, 6]
[0, 0, 2, 3, 4]
[0, 1, 2, 1,]
```
The process is described by wikipedia:
>
> * The array `A` is of length `NNZ` and holds all the nonzero entries of `M` in
> left-to-right top-to-bottom ("row-major") order.
> * The array `IA` is of length `m + 1`. It is defined by this recursive
> definition:
> * `IA[0] = 0`
>
>
> `IA[i] = IA[i − 1] + (number of nonzero elements on the (i − 1)-th row in the original matrix)`
> * Thus, the first `m` elements of `IA` store the index into `A` of the first
> nonzero element in each row of `M`, and the last element `IA[m]` stores
> `NNZ`, the number of elements in `A`, which can be also thought of as the
> index in `A` of first element of a phantom row just beyond the end of
> the matrix `M`. The values of the `i`-th row of the original matrix is
> read from the elements `A[IA[i]]` to `A[IA[i + 1] − 1]` (inclusive on both
> ends), i.e. from the start of one row to the last index just before
> the start of the next.[5]
> * The third array, `JA`, contains the column index in `M` of each element of
> `A` and hence is of length `NNZ` as well.
>
>
>
If your language doesn't support actual data structures, input and output may be text.
# Test cases
Input 1:
```
[[0 0 0 0],
[5 8 0 0],
[0 0 3 0],
[0 6 0 0]]
```
Output 1:
```
[ 5, 8, 3, 6 ]
[ 0, 0, 2, 3, 4 ]
[ 0, 1, 2, 1, ]
```
Input 2
```
[[10 20 0 0 0 0],
[0 30 0 40 0 0],
[0 0 50 60 70 0],
[0 0 0 0 0 80]]
```
Output 2:
```
[ 10 20 30 40 50 60 70 80 ]
[ 0 2 4 7 8 ]
[ 0 1 1 3 2 3 4 5 ]
```
Input 3:
```
[[0 0 0],
[0 0 0],
[0 0 0]]
```
Output 3:
```
[ ]
[ 0 0 0 0 ]
[ ]
```
Input 4:
```
[[1 1 1],
[1 1 1],
[1 1 1]]
```
Output 4:
```
[ 1 1 1 1 1 1 1 1 1 ]
[ 0 3 6 9 ]
[ 0 1 2 0 1 2 0 1 2 ]
```
Input 5:
```
[[0 0 0 0],
[5 -9 0 0],
[0 0 0.3 0],
[0 -400 0 0]]
```
Output 5:
```
[ 5, -9, 0.3, -400 ]
[ 0, 0, 2, 3, 4 ]
[ 0, 1, 2, 1, ]
```
Assume inputs may contain any real number, you need not consider mathematical symbols or exponential representation (e.g. 5,000 will never be entered as 5e3). You will not need to handle `inf`, `-inf`, `NaN` or any other 'pseudo-numbers'. You may output a different representation of the number (5,000 *may* be output as 5e3 if you so choose).
# Scoring
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 19 bytes
```
!3#f!Dx0Gg!XsYshDq!
```
Input uses `;` as row separator.
[Try it online!](https://tio.run/##y00syfn/X9FYOU3RpcLAPV0xojiyOMOlUPH//2gDBTC0VjBVsIAwQHxjCMMMxIkFAA "MATL – Try It Online") Or verify all test cases: [1](https://tio.run/##y00syfn/X9FYOU3RpcLAPV0xojiyOMOlUPH//2gDBTC0VjBVsIAwQHxjCMMMxIkFAA), [2](https://tio.run/##y00syfn/X9FYOU3RpcLAPV0xojiyOMOlUPH//2hDAwUjAwUotAYSxiCWCZxroGBqoGBmoGAO50OghUEsAA), [3](https://tio.run/##y00syfn/X9FYOU3RpcLAPV0xojiyOMOlUPH//2gDBSC0VkCmYgE), [4](https://tio.run/##y00syfn/X9FYOU3RpcLAPV0xojiyOMOlUPH//2hDBSC0VkCmYgE), [5](https://tio.run/##y00syfn/X9FYOU3RpcLAPV0xojiyOMOlUPH//2gDBTC0VjBV0LWEsMACesYQpq6JAZgfCwA).
### Explanation
```
! % Implicit input. Transpose
3#f % 3-output version of find: it takes all nonzero values and pushes
% their column indices, row indices, and values, as column vectors
! % Transpose into a row vector
D % Display (and pop) vector of values
x % Delete vector of row values
0 % Push 0
G % Push input
g % Convert to logical: nonzeros become 1
! % Transpose
Xs % Sum of columns. Gives a row vector
Ys % Cumulative sum
h % Prepend the 0 that's below on the stack
D % Display (and pop) that vector
q % Subtract 1 from the vector of row indices
! % Transpose into a row vector. Implicitly display
```
[Answer]
# Mathematica, 78 bytes
```
{a=SparseArray@#;a@"NonzeroValues",a@"RowPointers",Join@@a@"ColumnIndices"-1}&
```
See [this answer on mathematica.stackexchange.com](https://mathematica.stackexchange.com/a/83722/6652).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
n0S€0;;\S€,T€Ẏ$’$
Ẏḟ0W;Ç
```
[Try it online!](https://tio.run/##y0rNyan8/z/PIPhR0xoDa@sYEK0TAiQe7upTedQwU4ULyHi4Y75BuPXh9v///0dHG@goQFGsDpdCtKmOggUSFyJljMQ1g8rGAgA "Jelly – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~31~~ 28 chars or ~~36~~ 33 bytes\*
Requires `⎕IO←0` for zero based indexing. I/O is list of lists.
```
{(∊d)(0,+\≢¨d←⍵~¨0)(∊⍸¨⍵≠0)}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZLXGo46uFE0NAx3tmEediw6tSAEKPurdWndohYEmSO5R745DK4ACjzoXGGjW/g8qzQPpUldQf9S76lEvUKYTyNB41DYRqEZTXeFR2yR1DZBU31SvYH@/QyvSFEAStUByroJXaXGJQlp@kUJeZnKqQkpmcUFOYiXISAUNAwUw1FTQMFWwgLJAIsZQlhlYjAus1tBAwQiqHiprDGKaGCDpMwVqMVAwRwhAoAXMDGS1CBpqvgIQaqLTXBjuPLTeElm3Hsyth9abGEBUAQA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` anonymous function where the argument is represented by *⍵*
`(`…`)(`…`)(`…`)` return a list of three things:
`⍵≠0` Boolean where the argument differs from 0
`⍸¨` **ɩ**ndices of those for each sub-list
`∊` **ϵ**nlist (flatten) to combine into single list
`⍵~¨0` remove zeros from each sub-list of the argument
`d←` store that as *d*
`≢¨` tally each
`+\` cumulative sum
`0,` prepend a zero
`∊d` **ϵ**nlist (flatten) *d* to combine into single list
---
\* To run in Dyalog Classic, simply replace `⍸` with `⎕U2378`.
[Answer]
## Haskell, 87 bytes
```
f s|a<-filter(/=0)<$>s=(id=<<a,scanl(+)0$length<$>a,s>>= \t->[i|(i,e)<-zip[0..]t,e/=0])
```
[Try it online!](https://tio.run/##bYyxDsIgEIZ3n@KGDhChkhiNA/AiyEAstRcRm8Jk@u6IDYmLueG@fP/dP7n08CGUMkJaneQjhuwXclCCyk4nRXBQUjqWbi4GsqeiCz7e81TDKrVWcM1cG1wJMk8lf@NsRN/bzHztsLQ8HUZQMLx2APOCMUMHIxgj2DaWmRO7NPqaY6Pz5uy/r3b52xbKBw "Haskell – Try It Online")
How it works:
```
a<-filter(/=0)<$>s -- let a be the list of lists with all 0 removed]
-- e.g. [[1,0,0],[0,3,4]] -> [[1],[3,4]]
-- return a triple of
id=<<a -- a concatenated into a single list -> A
scanl(+)0$length<$>a -- partial sums of the length of the sublists of a
-- strating with an additional 0 -> IA
s>>= -- map the lambda over the sublists of s and concatenate
-- into a single list
\t->[i|(i,e)<-zip[0..]t,e/=0] -- the indices of the non-zero elements -> JA
```
[Answer]
# Python+SciPy, 79 bytes
i guess built-ins were not forbidden
```
from scipy.sparse import*
A=csr_matrix(input())
print A.data,A.indptr,A.indices
```
Accepts input in the format `[[0, 0, 0, 0],[5, 8, 0, 0],[0, 0, 3, 0],[0, 6, 0, 0]]`
[Answer]
# [R](https://www.r-project.org/), 70 bytes
```
function(m,M=t(m))list(M[x<-!!M],diffinv(colSums(x)),which(x,T)[,1]-1)
```
[Try it online!](https://tio.run/##NYzNCoMwEIRfRW@7sIFKf@hBHyGnehMPNiW4YDYQY02fPmpLGfjmm8uEbItaFdkuYiJ7AUe6ieAQJ54j6C7Vqix1Ty@2luUNxk@Pxc2QEGkd2YyQqMWOql5VmC24IQZOYOBEv1zpTn8/f3k7iCTBr82FZH/c6/k5ZouYNw "R – Try It Online")
This is an old, [matrix](/questions/tagged/matrix "show questions tagged 'matrix'") challenge that didn't get an R answer for 3 years! Having to do this in row-major rather than column-major order costs 8 bytes (`,M=t(m))`).
[Answer]
# [Python 3](https://docs.python.org/3/), 96 bytes
```
lambda m:list(map(list,zip(*[[e,i,j] for i,r in enumerate(m) for j,e in enumerate(r) if e!=0])))
```
[Try it online!](https://tio.run/##VY7LCsIwEEX3/Yq4S2QqYx@@oF8Ss4iYYEqThhgX@vO1L4hyGbj3MHMZ/46P3pWDbq5DJ@3tLom9dOYZqZWeTgY@xtMt5woMtILoPhAD4zii3MuqIKOils28BfXPAyNGE7VpUDDGhliQhnC@RygQVgngCOVkq5QRaoQDwjGBRScUIov1XJMKasjPP7e4K1efV7jsiMwH4yLVNBaMpVCPX30B "Python 3 – Try It Online")
[Answer]
# [PHP](https://php.net/), 107 bytes
```
<?for($y=[$c=0];$r=$_GET[+$l++];)foreach($r as$k=>$v)!$v?:[$x[]=$v,$z[]=$k,$y[$l]=++$c];var_dump($x,$y,$z);
```
[Try it online!](https://tio.run/##VY1BCsIwFET3nkLLLFqSRUEUMX67Ei/g7vMppSqFthgihtbLxyiIdjHMMG9gbGPDrrCNnaE8Hk7EnOSJ/pNoTlYxbSbNly8nzfq3EROuN5diJEZNuRg4@jywQqeUmCziS1U3Kdy8uqOlPXy2gC@2jIGF4DWeb281RkYnpBRqMb5y5fnR2xRDBHGTmRBe "PHP – Try It Online")
# [PHP](https://php.net/), 109 bytes
```
<?$y=[$c=0];foreach($_GET as$r){foreach($r as$k=>$v)if($v){$x[]=$v;$z[]=$k;$c++;}$y[]=$c;}var_dump($x,$y,$z);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKUS7@4aYhsdrWSgpIOEY3WilUyBLAsUEZi8MYqIGUJNrPV/lUrbaJVkW4NY67T8otTE5AwNsBUKicUqRZrVcLEikEC2rZ1KmWZmmgaQrFapiI61VSmzVqkC0dnWKsna2ta1KpUgXrJ1bVliUXxKaW6BhkqFjkqljkqVpvX//wA "PHP – Try It Online")
[Answer]
# JavaScript (ES6), 117 bytes
```
a=>[a.map((b,i)=>(b=b.filter((x,c)=>x&&o.push(c)),m[i+1]=m[i]+b.length,b),m=[0],o=[]).reduce((x,y)=>x.concat(y)),m,o]
```
Input is a 2D array of numbers and output is an array of `[A, IA, JA]`.
## Explained
```
a=>[
a.map((b,i) => ( // map each matrix row
b = b.filter((x,c) => x // filter to only non-zero elements
&& o.push(c) // and add this index to JA
)
m[i+1] = m[i] + b.length, // set next value of IA
b // and return filtered row
),
m=[0],o=[] // initialize IA (m) and JA (o)
).reduce((x,y) => x.concat(y)), // flatten the non-zero matrix
m,o] // append IA and JA
```
## Tests
```
let f=
a=>[a.map((b,i)=>(b=b.filter((x,c)=>x&&o.push(c)),m[i+1]=m[i]+b.length,b),m=[0],o=[]).reduce((x,y)=>x.concat(y)),m,o]
let run=x=>O.innerHTML+=f(x).map(s=>`[${s.join`, `}]`).join`\n`+"\n\n"
run([[0,0,0,0],[5,8,0,0],[0,0,3,0],[0,6,0,0]])
run([[10,20,0,0,0,0],[0,30,0,40,0,0],[0,0,50,60,70,0],[0,0,0,0,0,80]])
run([[0,0,0],[0,0,0],[0,0,0]])
run([[1,1,1],[1,1,1],[1,1,1]])
run([[0,0,0,0],[5,-9,0,0],[0,0,0.3,0],[0,-400,0,0]])
```
```
<pre id=O></pre>
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~31~~ ~~27~~ 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Hopefully this output format is OK.
```
cf pUmè iT å+ Ucð
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y2YgcFVt6CBpVCDlKyBVY/A&input=WwpbMCAwIDAgMF0KWzUgOCAwIDBdClswIDAgMyAwXQpbMCA2IDAgMF0KXS1R)
```
cf pUmè iT å+ Ucð :Implicit input of 2D array U
c :Flat map
f : Filter
p :Push the following two elements
Um : First element: Map U
è : Count the truthy elements in each
i : Prepend
T : Zero
å+ : Cumulatively reduce by addition
Uc : Second element: Flat map U
ð : 0-based indices of truthy elements
```
[Answer]
# [Python 2](https://docs.python.org/2/), 115 bytes
```
lambda m:zip(*[[v,i]for k in m for i,v in enumerate(k)if v])+[reduce(lambda a,b:a+[len(b)-b.count(0)+a[-1]],m,[0])]
```
[Try it online!](https://tio.run/##TYzLDoIwEEX3fsUsWxnIiOIr8UvqLAqU2EALIYVEfx5FSTB3c@48TvcMj9anU3W7T412eanBXV@2E1ulRrRctT3UYD04mNHiOBfjB2d6HYyopa1gZBmp3pRDYcQi0ZhfdaQa40Uu4zwp2sEHQTLSKt4xo0NFLHkKKdxAqR1hSriEPzvcz3hYO2FGeCQ8rYNfzsS8CdlXswoyjC9/v5TsF44P9LvhTddbH6ASIZUrZ3J6Aw "Python 2 – Try It Online")
Output is `[A, JA, IA]`
[Answer]
# [Perl 6](http://perl6.org/), 84 bytes
```
{.flatmap(*.grep(+*)),(0,|[\+] .map(+*.grep(+*))),.flat.kv.flatmap:{$^a%.[0]xx?$^b}}
```
[Try it online!](https://tio.run/##TYvtCoIwGIVv5fww2dwYbx9apNmFmMIC148UhkYo5rUv7APG8@fwPBxbd03i2hGhwclNyjT60WrLInXrastExLlkJF/FRZRQSxFe4vJzUPfn/3icgkqvVEHlMJyD6jrPLkWvRxjGsjVhQ/iRS2SE7bJ3niDEhISw98yXA@Wcp@4N "Perl 6 – Try It Online")
The single matrix argument is in `$_`.
* `.flatmap(*.grep(+*))` selects the nonzero elements of the entire matrix.
* `[\+] .map(+*.grep(+*))` is the triangular reduction of the number of elements in each row (which some languages call `scan`). `(0,|...)` prepends a zero to that list.
* `.flat.kv` produces an indexed list of all elements of the matrix. `.flatmap: { $^a % .[0] xx ?$^b }` flat-maps over the modulus of each index by the number of columns in the array (`.[0]`, the number of elements in the first row), replicated by the element itself, interpreted as a boolean. That is, nonzero elements are replicated once, and zero elements are replicated zero times (ie, removed).
[Answer]
# [Julia](http://julialang.org/), ~~66~~ 63 bytes
```
using SparseArrays
n*a=getfield(sparse(a'),n)
!a=5a,3a.-1,4a.-1
```
`SparseArrays` is a standard library that stores with CSC instead of CSR (column instead of row or something), that's why we need to transpose (`a'`).
-6 bytes if 1-indexing was allowed
overloads `*` with `getfield` to save a few bytes
[Try it online!](https://tio.run/##jVHLboMwELz7Kza5FFfGsmNo4MCh39Aj5WAlTuQKOYhHlXw99QMotD3Ua63WM@udtfdjqLXk93EcOm2u8NbItlOvbSsfHTLPsriq/qJVfY46z0TyCROD0U4WqSRC0piTxPnxMphTr28GetX1kTYE1L2hlGIEdt2GHgrYaeNPZ901tXzYrMA2rTZ9baL9u9lvEBrZi9scX6mAT3WikVXAWxYjZc4I@R5QWTLwViEoU8jm0GFiDl88WhFUQkogIyCIxfyZEbcPHkoWiHvI@grhRYgzOExic2Hh4oStRVMrx@C4QoJlUwOhivDXltyMBWmbBwewjcAR7FsWjPstPCk8nzoSbz9hEfwOfIXwqskCsnqVrczdhR@BzXPd/rKpmLAfmM8Hbvta@wr/PZ0433RHlwHFCWObGcU5cTwJzL8mhccv "Julia 1.0 – Try It Online")
[Answer]
# Scala, 82 bytes
```
x=>x.flatMap(_.zipWithIndex).filter(_._1!=0).unzip->x.scanLeft(0)(_+_.count(_!=0))
```
[Try it in Scastie!](https://scastie.scala-lang.org/bOf3LO1ERQSNkIt1fl43Zg)
Returns `((A, JA), IA)`
Explanation:
```
x => //The sparse matrix to be smooshed
x.flatMap( //Do the following operation to each row, then flatten the result
_.zipWithIndex //Zip each element with its column (makes tuples)
).filter( //Keep the tuples where
_._1!=0 //the first element isn't 0
).unzip //Unzip into a tuple of two lists, A and JA
-> //Make that the first element of another 2-tuple with IA:
x.scanLeft(0)( //Starting with 0
_+_.count(_!=0) //Add the number of nonzero elements in each row
) //Keep the intermediate results, giving us IA
```
]
|
[Question]
[
Your task is to take an encrypted string as input, and output the string decrypted, to reveal its hidden message.
The strings, both the input and output, will contain characters from this list of 64 ASCII-characters (note the leading space):
```
!"#$%&'()*+,-./0123456789:;=?@[\]^_abcdefghijklmnopqrstuvwxyz|~
```
These characters are assigned numbers, in the order they are listed above:
```
! " # $ % & ...
0 1 2 3 4 5 6 ...
```
So, space is number 0, `!` is number 1 and `~` is number 63. These numbers can be represented in 6-bit binary code:
```
: 0: 000000
!: 1: 000001
": 2: 000010
#: 3: 000011
.. ... ......
z: 61: 111101
|: 62: 111110
~: 63: 111111
```
---
The encryption is very simple:
I'll use `eC` for encrypted characters, and `C` for characters of the original string. `C(n)` is the n'th character of the original string, while `eC(n)` is the n'th character of the encrypted string.
**You'll use the 6-bit binary representation of the characters. The first character will be `eC(0) = not(C(0))`. From there, all characters will be `eC(n) = xor(C(n),C(n-1))`.**
**Example:**
Let's assume the input string is `code`.
* `c` is the 38th character (zero indexed), or `100110` in binary. The encrypted version has all bits flipped, so `011001 -> 25 -> '9'` (again, zero indexed).
* `o` is the 50th character, or `110010` in binary. `xor(100110, 110010) = 010100 = 20 = '4'`.
* `d` is the 39th character, or `100111` in binary. `xor(100111, 110010) = 010101 = 21 = '5'`.
* `e` is the 40th character, or `101000` in binary. `xor(101000, 100111) = 001111 = 15 = '/'`.
So, if the original string is `code`, the encrypted string will become `945/`.
---
## Test cases:
```
945/
code
,&'8[14 =?;gp+% 2'@s&&c45/eg8?&
programming puzzles & code golf
;a$5$%0r?2@12dw6# lb-eg&519nt%ot=9$@es@96+?;ga" 4*)&ta56dp[?o#t%oh/"(&?#ee![,+,/+fe4"
a $150 reward will be given to those sending account and pin# to hackers@steal_id.com
~!#!'!#!/!#!'!#![!#!'!#!/!#!'!#!~!#!'!#!/!#!'!#![!#!'!#!/!#!'!#!
!"#$%&'()*+,-./0123456789:;=?@[\]^_abcdefghijklmnopqrstuvwxyz|~
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 26 bytes
```
ØJḟ“<>`{}”ḟØAɓi@€_33^\96_ị
```
[Try it online!](https://tio.run/##y0rNyan8///wDK@HO@Y/aphjY5dQXfuoYS6Qd3iG48nJmQ6PmtbEGxvHxViaxT/c3f3/4e4th9uBYpH//1uamOpz6aipW0QbmijY2lunF2irKhipOxSrqSUDpVLTLezVuKwTVUxVVA2K7I0cDI1Sys2UFXKSdFPT1UwNLfNKVPNLbC1VHFKLHSzNtIEGJCopmGhpqpUkmpqlFETb5ysDVWToK2mo2SunpipG62jr6GunpZoocdUpKiuqA7E@lI5G4xOSBwA "Jelly – Try It Online")
### Alternate version, 22 bytes (non-competing)
Jelly finally caught up with other golfing langs and got a *printable ASCII* atom, so this works now.
```
ØṖḟ“<>`{}”ḟØAɓi@€’^\Nị
```
[Try it online!](https://tio.run/##y0rNyan8///wjIc7pz3cMf9Rwxwbu4Tq2kcNc4G8wzMcT07OdHjUtOZRw8y4GL@Hu7v/P9y95XA7UCTy/39LE1N9Lh01dYtoQxMFW3vr9AJtVQUjdYdiNbVkoFRquoW9Gpd1ooqpiqpBkb2Rg6FRSrmZskJOkm5qupqpoWVeiWp@ia2likNqsYOlmTbQgEQlBRMtTbWSRFOzlIJo@3xloIoMfSUNNXvl1FTFaB1tHX3ttFQTJa46RWVFdSDWh9LRaHxC8gA "Jelly – Try It Online")
## How it works
```
ØJḟ“<>`{}”ḟØAɓi@€_33^\96_ị Main link. Argument: s (string)
ØJ Yield Jelly's code page, i.e., 32 non-ASCII characters,
followed by all printable ASCII characters, followed by
129 non-ASCII characters.
ḟ“<>`{}” Filterfalse; remove the characters "<>`{}".
ḟØA Filterfalse; remove all uppercase ASCII letters.
Let's call the resulting alphabet a.
ɓ Begin a new, dyadic chain.
Left argument: s. Right argument: a
i@€ Find the (1-based) index of all characters of s in a.
_33 Subtract 33, so ' ' maps to 0, '~' maps to 63.
^\ Compute the cumulative bitwise XOR.
We didn't take the bitwise NOT of the first index,
which can be rectified by subtracting all results from
63. However, we must also add 33 to account for the
fact that the index of ' ' in a is 33.
96_ Subtract the results from 96.
ị Index into a.
```
[Answer]
## JavaScript (ES6), 115 bytes
```
s=>s.replace(/./g,s=>d[x^=d.indexOf(s)],x=63,d=` !"#$%&'()*+,-./0123456789:;=?@[\\]^_abcdefghijklmnopqrstuvwxyz|~`)
```
### Test cases
```
let f =
s=>s.replace(/./g,s=>d[x^=d.indexOf(s)],x=63,d=` !"#$%&'()*+,-./0123456789:;=?@[\\]^_abcdefghijklmnopqrstuvwxyz|~`)
console.log(f("945/"))
console.log(f(",&'8[14 =?;gp+% 2'@s&&c45/eg8?&"))
console.log(f(';a$5$%0r?2@12dw6# lb-eg&519nt%ot=9$@es@96+?;ga" 4*)&ta56dp[?o#t%oh/"(&?#ee![,+,/+fe4"'))
console.log(f("~!#!'!#!/!#!'!#![!#!'!#!/!#!'!#!~!#!'!#!/!#!'!#![!#!'!#!/!#!'!#!"))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~34~~ 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-3 bytes thanks to Dennis (use `ḟ` twice rather than `œ-`, `;` and `¤`; use `”~` rather than **63** )
```
32r126Ọḟ“<>`{}”ḟØAṙ1ɓ”~;i@€^\Ḋị
```
A monadic link taking and returning lists of characters.
\*Note: the input arguments to a Jelly program utilise Python string formatting, so quoting with `"`, `'`, `'''` (or if unambiguous no quoting) are all options.
**[Try it online!](https://tio.run/##y0rNyan8/9/YqMjQyOzh7p6HO@Y/aphjY5dQXfuoYS6Qd3iG48OdMw1PTgZy66wzHR41rYmLebij6@Hu7v///yvpqKlbRBuaKNjaW6cXaKsqGKk7FKupJZuY6qemW9irKQEA)**
### How?
Bitwise-xor is invertible (given "leading zeros").
Bitwise-Not is an xor with "all ones" - in this case only **6** ones are ever required, so **27-1 = 63**.
Once we have created the array or characters and looked up the indexes of the input characters, the decode itself is then simply a cumulative reduction by bitwise-xor, after which we may index back into the same array.
```
32r126Ọḟ“<>`{}”ḟØAṙ1ɓ”~;i@€^\Ḋị - Main link: string, s
32r126 - inclusive range -> [32,33,...,125,126]
Ọ - cast to ordinals -> " !...}~"
“<>`{}” - literal ['<','>','`','{','}']
ḟ - filter discard
ØA - yield "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ḟ - filter discard
ṙ1 - rotate left by one (Jelly indexing is one based)
ɓ - dyadic chain separation, swapping arguments (call that p)
”~ - literal '~'
; - concatenate with s (`~` has value 63 for the bitwise-not)
i@€ - first index* of €ach character of s in p
\ - cumulative reduce by:
^ - bitwise-xor
Ḋ - dequeue (remove the 63 from '~')
ị - index into p
```
\* *Note:* looking up a space in p will yield a 64, but that's OK since indexing back into p is modular so adding a leading `1` is like adding 64, taking the index right back around to where it needs to be).
[Answer]
# Java, 225 bytes
```
String D(String E){String A="",C=" !\"#$%&'()*+,-./0123456789:;=?@[\\]^_abcdefghijklmnopqrstuvwxyz|~";for(int i=-1,J=0;++i<E.length();J=C.indexOf(E.charAt(i)),A+=C.charAt(i<1?(1<<6)-1-J:C.indexOf(A.charAt(i-1))^J));return A;}
```
I have not golfed in Java in a very long time, so any golfing tips are appreciated.
[Try It Online!](https://tio.run/##RZBLb4JAFIXX@ivGQe2MPBSrtIgEibrQjUndNBFtRhhxLA4Uxlet/esWE9uu7rm5303OORuyJ2qcUL4J3s2rH5EsA6@TF3C@TkXKeAgG6C6G@HxXrg2h0rchKHlQKleqDwjXZEXV6g29@dhqG0/PZseynd7M8@aLN7L0A7oK12zzHm15nHykmdjtD8fT59c3tFZxihgXgNmqrozthiXLrDvUIspDsUbYGtt9jfGAHicrNNT8NUldgRjGiivnl9@9qztI73YNrOrquPP/4f4Rqo7xYoyxlVKxSzlwrcs12S0j5oNMEJGPfcwCsCWM3wPP5oDgc7Fwa2MEbMDp4dZM7qlYmJ4yQbdavBNakrMi4mikDRC0SLldrjRSp9nTm8HBkEC0VGlYbesmF5VY2Ga5R7OeaciOFRIPglYNVwVpG0Eyc2IpR9Z1D6KqI1FamimyUpdXtOVBmBsvXi7XHw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 40 bytes
```
'~«vžQAu"<>{}`"«SK©yk64+b¦S}r.gG^DJC®sè?
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fve7Q6rKj@wIdS5Vs7KprE5QOrQ72PrSyMtvMRDvp0LLg2iK9dPc4Fy/nQ@uKD6@w///fOlHFVEXVoMjeyMHQKKXcTFkhJ0k3NV3N1NAyr0Q1v8TWUsUhtdjB0kzb3jo9UUnBREtTrSTR1CylINo@XxmoIkNfSUPNXjk1VTFaR1tHXzst1UQJAA "05AB1E – Try It Online")
**Explanation**
```
'~« # append input to "~"
v # for each char y in the resulting string
žQ # push printable ascii chars
Au # push upper case alphabet
"<>{}`"« # append "<>{}`"
SK # remove those chars from printable ascii
© # store a copy in register
yk # get the index of y in that string
64+ # add 64
b # convert to binary
¦S # remove leading 1 and convert to list of bits
} # end loop
r # reverse stack
.gG # len(stack)-1 times do
^ # xor top 2 lists of bits on the stack
DJC # convert a copy to decimal
®sè # index into the char string with this
? # print
```
[Answer]
# CPU x86 instruction set, 235 bytes
```
00000750 50 push eax
00000751 8A10 mov dl,[eax]
00000753 80FA00 cmp dl,0x0
00000756 7418 jz 0x770
00000758 31DB xor ebx,ebx
0000075A EB03 jmp short 0x75f
0000075C F9 stc
0000075D EB13 jmp short 0x772
0000075F 8A83C1A14000 mov al,[ebx+0x40a1c1]
00000765 3C00 cmp al,0x0
00000767 74F3 jz 0x75c
00000769 38C2 cmp dl,al
0000076B 7404 jz 0x771
0000076D 43 inc ebx
0000076E EBEF jmp short 0x75f
00000770 42 inc edx
00000771 F8 clc
00000772 58 pop eax
00000773 C3 ret
00000774 53 push ebx
00000775 8B442408 mov eax,[esp+0x8]
00000779 31C9 xor ecx,ecx
0000077B 09C0 or eax,eax
0000077D 7505 jnz 0x784
0000077F 31C0 xor eax,eax
00000781 48 dec eax
00000782 EB2F jmp short 0x7b3
00000784 E8C7FFFFFF call 0x750
00000789 72F4 jc 0x77f
0000078B 7510 jnz 0x79d
0000078D F6D3 not bl
0000078F 80E33F and bl,0x3f
00000792 88D9 mov cl,bl
00000794 8AB3C1A14000 mov dh,[ebx+0x40a1c1]
0000079A 8830 mov [eax],dh
0000079C 40 inc eax
0000079D E8AEFFFFFF call 0x750
000007A2 72DB jc 0x77f
000007A4 750D jnz 0x7b3
000007A6 30D9 xor cl,bl
000007A8 8AB1C1A14000 mov dh,[ecx+0x40a1c1]
000007AE 8830 mov [eax],dh
000007B0 40 inc eax
000007B1 EBEA jmp short 0x79d
000007B3 5B pop ebx
000007B4 C20400 ret 0x4
000007B7 53 push ebx
000007B8 8B442408 mov eax,[esp+0x8]
000007BC 31C9 xor ecx,ecx
000007BE 09C0 or eax,eax
000007C0 7505 jnz 0x7c7
000007C2 31C0 xor eax,eax
000007C4 48 dec eax
000007C5 EB32 jmp short 0x7f9
000007C7 E884FFFFFF call 0x750
000007CC 72F4 jc 0x7c2
000007CE 750F jnz 0x7df
000007D0 30D9 xor cl,bl
000007D2 8AB1C1A14000 mov dh,[ecx+0x40a1c1]
000007D8 8830 mov [eax],dh
000007DA 88D9 mov cl,bl
000007DC 40 inc eax
000007DD EBE8 jmp short 0x7c7
000007DF 8B442408 mov eax,[esp+0x8]
000007E3 E868FFFFFF call 0x750
000007E8 72D8 jc 0x7c2
000007EA 750D jnz 0x7f9
000007EC F6D3 not bl
000007EE 80E33F and bl,0x3f
000007F1 8AB3C1A14000 mov dh,[ebx+0x40a1c1]
000007F7 8830 mov [eax],dh
000007F9 5B pop ebx
000007FA C20400 ret 0x4
```
The function find() and deCript() + the string abc: 171 bytes + 64 bytes=235
assembly with nasmw and compiler/library with Borland C compiler:
```
; nasmw -fobj this.asm
; bcc32 -v this.obj
section _DATA use32 public class=DATA
global _main
extern _printf
fmt1 db "result=%s" , 13, 10, 0, 0
fmt2 db "abc[63]=%c" , 13, 10, 0, 0
code1 db "code" , 0, 0
code2 db ",&'8[14 =?;gp+% 2'@s&&c45/eg8?&" , 0, 0
code3 db ';a$5$%0r?2@12dw6# lb-eg&519nt%ot=9$@es@96+?;ga" 4*)&ta56dp[?o#t%oh/"(&?#ee![,+,/+fe4"' , 0, 0
abc db ' !"#$%' , "&'()*+,-./0123456789:;=?@[\]^_abcdefghijklmnopqrstuvwxyz|~" , 0, 0
section _TEXT use32 public class=CODE
find:
push eax
mov dl, [eax]
cmp dl, 0
je .2
xor ebx, ebx
jmp short .1
.e: stc
jmp short .z
.1: mov al, [abc+ebx]
cmp al, 0
je .e
cmp dl, al
je .3
inc ebx
jmp short .1
.2: inc edx ; set zf=0
.3: clc
.z: pop eax
ret
deCript:
push ebx
mov eax, dword[esp+8]
xor ecx, ecx
or eax, eax
jnz .1
.e: xor eax, eax
dec eax
jmp short .z
.1: call find
jc .e
jnz .2
not bl
and bl, 03Fh
mov cl, bl
mov dh, [abc+ebx]
mov [eax], dh
inc eax
.2: call find
jc .e
jnz .z
xor cl, bl
mov dh, [abc+ecx]
mov [eax], dh
inc eax
jmp short .2
.z:
pop ebx
ret 4
cript:
push ebx
mov eax, dword[esp+8]
xor ecx, ecx
or eax, eax
jnz .1
.e: xor eax, eax
dec eax
jmp short .z
.1: call find
jc .e
jnz .2
xor cl, bl
mov dh, [abc+ecx]
mov [eax], dh
mov cl, bl
inc eax
jmp short .1
.2: mov eax, dword[esp+8]
call find
jc .e
jnz .z
not bl
and bl, 03Fh
mov dh, [abc+ebx]
mov [eax], dh
.z:
pop ebx
ret 4
_main:
pushad
push code1
call cript
push code1
push fmt1
call _printf
add esp, 8
xor eax, eax
mov al, [abc+63]
push eax
push fmt2
call _printf
add esp, 8
push code1
call deCript
push code1
push fmt1
call _printf
add esp, 8
push code2
call deCript
push code2
push fmt1
call _printf
add esp, 8
push code3
call deCript
push code3
push fmt1
call _printf
add esp, 8
popad
mov eax, 0
ret
```
results:
```
result=945/
abc[63]=~
result=code
result=programming puzzles & code golf
result=a $150 reward will be given to those sending account and pin# to hackers@steal_id.com
```
Assembly is better (for say the true I use a macro system, yes I know it is too long but as the C one +- with macro system , for say the true because the instructions are simpler it is easy write code in assembly even without make corrections as one write in English (not I) )
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 153 bytes
```
char*i=" !\"#$%&'()*+,-./0123456789:;=?@[\\]^_abcdefghijklmnopqrstuvwxyz|~";a(b){b=index(i,b)-i;}f(char*x){for(*x=i[a(*x)^63];x[1];)*x=i[a(*x)^a(*++x)];}
```
[Try it online!](https://tio.run/##tU7BVoMwELz7FWloadKAlApYjDz4j4C@AIFGLdRCFYv46zX0efB58aKH3Xk7uzszmVlm2emUbfh@IQMIJjHUpjN9jvCCGOaltbRXV47rXa/9GxqEEYvj5O6ep1kuinIjHx6ftlW9e9437eHltXs7vn9AylGK@zSQVS46JI0Um5IOBTpbdLgv6j1adIFkXAG@864S2jE7ofgbqTohHU7ocNpyWSHcX/QXAIwSgLMkgL7jWpAqqkAcn1GpyqoFMlhSedvIo6gLwE2bSkLw@AvA7tCOAogzmZx/hpFqEIRqGn4YGPp8zWwHBCEtd2QGVvOo0fVM2YpyHer/6k351J3OlvtwFdmr/NXTwFNqilJ3bb9qZ3Ub@NNINJHvERWOxxA4C6y33PXyHQtrTZ1srBgiPdSEmDCDGBYphBPDfw39MdEmc1XWF7If82/7Pw43nD4B "C (gcc) – Try It Online")
Slightly golfed less
```
char*i=" !\"#$%&'()*+,-./0123456789:;=?@[\\]^_abcdefghijklmnopqrstuvwxyz|~";
a(b){
b=index(i,b)-i;
}
f(char*x){
for(*x=i[a(*x)^63];x[1];)
*x=i[a(*x)^a(*++x)];
}
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 52 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Requires `⎕IO←0`
```
{C[2∘⊥¨≠\~@0⊢(6/2)∘⊤¨⍵⍳⍨C←(32↓⎕UCS⍳127)~⎕A,'<>{}`']}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6udo40edcx41LX00IpHnQti6hwMHnUt0jDTN9IECy8BCvdufdS7@VHvCmegDg1jo0dtk4H6Q52DgaKGRuaadUCeo466jV11bYJ6bO3/NKCyR719EDu6mg@tN37UNhHICw5yBpIhHp7B/9MU1C1NTPXVuYAMHTV1dYtoQxMFW3vr9AJtVQUjdXWHYjW1ZKCC1HQLezWwKutEFVMVVYMieyMHQ6OUcjNlhZwk3dR0NVNDy7wS1fwSW0sVh9RiB0szbaApiUoKJlqaaiWJpmYpBdH2@cpAFRn6Shpq9sqpqYrROto6@tppqSZKYJPrFJUV1dWBhD6MEY0hQowadQA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Röda](https://github.com/fergusq/roda), ~~120~~ 100 bytes
```
f a{A=[]seq 32,126|chr _|{|v|A+=v if[v=~"[^<>`{}A-Z]"]}_;l=63;a|{|c|l=indexOf(c,A) b_xor l;[A[l]]}_}
```
[Try it online!](https://tio.run/##Dc9Rj0MwAADgd7@iKxM7FodpIr2O/oK9XzmK2iQ9bia2RO2vO@/fyzf0NV/XBvCZEpY9xB0EvuP5SFW3AeRqVpOiNplA27CJvCH7@ToX80KP3xnMlhxLggLMN1YpSdquFq9LY1UOPYAyf/UDkJhRJrONLusvb7tZ4wRiboTG/nOI/cTz6yfSgSyP4mqGXtSN@34kkZGIRxIhO8ZXnkJw@jiYIw9R/cfiXt/IzU2hZca6EDvm2I5rN@KUQugWhbZVtGX9Bw "Röda – Try It Online")
I used the `l=63` trick from the JavaScript answer. ~~Right now I am working on shortening `A` so golfing in progress...~~
[Answer]
# [Python 2](https://docs.python.org/2/), 155 bytes
```
lambda s,m=' !"#$%&\'()*+,-./0123456789:;=?@[\\]^_abcdefghijklmnopqrstuvwxyz|~':''.join(m[i]for i in reduce(lambda a,b:a+[a[-1]^b],map(m.find,s),[63])[1:])
```
[Try it online!](https://tio.run/##hY/dboJAEIXv@xTL3y7IKoJABUPgPRZsFlkQKwuFtdam8dUpJHrTm04yczKZM99kups4ttwZyygdz7TJCwoG3EQISLKiajBFurEw8XJlrW1n43r@6zYId1GckDTN9m80PxSsrI716f3c8Lb76Adx@bx@3b5/7ihEaHVqa643pM7Ktgc1qDnoWXE5MP1xi@I8pCahZGln@zzDDe30ZlXWvMCDgYm/yQxih5kxzvuCDWJGEIRQ4HrWJBjMBaItsV0QxbuqMzXgoGSA8DA5WLWN4dO2o6qnaus@dhLbKa6@As75klXQswMutFZEgZqwIQl8c@JQGbgLAwrq@UVH4laZHEdL1mGsMCYRbGLLLJkrP@F3SZHQlNZDyZ/@v/mEyMIXMEXX11yAUp@/NUZ5flT@BQ "Python 2 – Try It Online")
[Answer]
# PHP, 103 Bytes
```
for($x=63;~$c=$argn[$i++];)echo($a=join(preg_grep("#[^A-Z<>`{}]#",range(" ","~"))))[$x^=strpos($a,$c)];
```
[Try it online!](https://tio.run/##hY/RToMwFIbv9xRQurZIFwSBjHQIew0L08q6gjHQFIxLlu3VsRqvvPEkJyd//u/8OUd3etmVutOr02ikaDvCcZ6kIaaYohpveZQ4RcmUDtZOXONqQqi1tlTbElmGCZjC9b0p4yqKj5@Z57y/bqRCaZQP83qcixxWcqryLLAZAjjJnY9mkWZHzcvRs0QXAoJKT0qX04CGwUkmmIKb67nYdvg7@R/9nw8aMUFh1OBfVh/DJGcCe58t9kUCz0X2wG6wLX4ADvsgaJgv224kUBRvYz8QbaR6VkZqAjx@2G@edo8vl2vjAWrEoCQBDrA3At8Wh@dDMc1Gj5Ndp7D1G7Z8h4F6AOy6fAE "PHP – Try It Online")
## PHP, 107 Bytes
```
for($x=63;~$c=$argn[$i++];)echo($a=preg_filter("#[A-Z<>`{}]#","",join(range(" ","~"))))[$x^=strpos($a,$c)];
```
[Try it online!](https://tio.run/##hY/fToMwFIfv9xRQSlukC4JARjqEvYYFtbLyxyzQFIxLlu3VsRqvvPEkJyfn/L58yVG9WveF6tWmnbQUTU84zuIkwBRTVOEdD2MrL1infNeKKlzOCDUmlt2uQIZhAibQvddFVIbR8TN1rNPbVnYoCbNxcaclz2Ap5zJLfeMQwIrvPLSIJD0qXkyOIfoAEFQ4Utqc@jTwWxljCm62Y2PTwe/kf/b/clCLGQrdjd5l8zHOciFw8NhqXiTwnKcP7Aab/AfgcPD9mnmy6ScCRa607F7a4bRITYDDD9un/ePr5Vo7gAJA36dhJFqMnSTAMpcb8ExxeH7O50WraTYKChuvZuu3EFQjYNf1Cw "PHP – Try It Online")
## PHP, 118 Bytes
```
for($x=63;~$c=$argn[$i++];)echo($a=join(array_diff(range(" ","~"),range(A,Z),str_split("<>`{}"))))[$x^=strpos($a,$c)];
```
[Try it online!](https://tio.run/##hY/bboMwEETf8xXEOL4UVzQpoCCHQn6jDk1dYi5VBJZN1VRR8uvUvTz1pSutVqM5Gs3qVk@bXLd6Vg9GyaolAqdRHGKGGdrhtVhGXpbzRgcLb7XDhUWocrZq1jlyDJcwhos7k6@K5erwnvje8eVWNShepv24GMYshYWyRZoELkMCL7qhaJRxctAiH3xHtCEgKPeVmgsWsDCoVYQZuM79OXYb/l7xR//ng1JaKE3T0/PsrbdqJLCjfHIvEnjKknt@hVX2DQjYBUHJqaragUCZvQ5dT6Qx8mN/6OqaGNk3igAPuFKAsh@5ZY@U2dHsrT52IwGbh@fzBVA3Ap6eMufowbo0Bita8ukrG@x6wC/TJw "PHP – Try It Online")
[Answer]
## Python + Numpy, 214 bytes
Can't compete with other Python solution, though uses different, pure numeric approach:
```
from numpy import *
def f(s):
r=range
A=array
S=A(r(32,60)+[61,63,64]+r(91,96)+r(97,123)+[124,126])
T=A(r(128))
T[S]=A(r(64))
W=T[fromstring(s,"b")]
W[0]=~W[0]
W=S[bitwise_xor.accumulate(W)&63]
print W.tobytes()[::4]
```
A bit of explanation:
* `S=A(r(32,60)+...)` - define alphabet as code ranges
* `T=A(r(128))` - init hash table of size 128 (largest codepoint)
* `T[S]=A(r(64))` - fill the hash table, i.e. write indices 0-63 to the elements with ASCII indices
* `W=T[fromstring(s,"b")]` - convert the input to array & translate it into new codes
* `W[0]=~W[0]` - invert 1st value
* `W=S[bitwise_xor.accumulate(W)&63]` - use Numpy's accumulate method with xor to avoid looping, reset 2 left bits and translate back to ascii
[Answer]
# [Alice](https://github.com/m-ender/alice), 46 bytes
```
/" >"{""ZNr\'?wi.h%)qXq&[.&]?oe(K
\"<~`r}A*"!/
```
[Try it online!](https://tio.run/##S8zJTE79/19fScFOqVpJKcqvKEbdvjxTL0NVszCiUC1aTy3WPj9Vw5srRsmmLqGo1lFLSVH//38dNXWLaEMTBVt76/QCbVUFI3WHYjW1ZBNT/dR0C3s1AA "Alice – Try It Online")
### Explanation
The first half of the program runs in ordinal mode and sets up the mapping from numbers to characters. The second half runs in cardinal mode and uses this mapping to decode the input.
```
" ~" Push this string
r Convert to entire range (all printable ASCII)
"AZ" Push this string
r Convert to entire range
"<>`{}" Push this string
* Append last two strings
N Remove characters from full string
! Copy entire string to tape
'? Push 63 (code point of ?) onto the stack
w Store return address (start main loop)
i Take byte of input
.h% Calculate n mod (n+1): this crashes on EOF (-1)
) Find byte on tape
q Get position on tape
X Bitwise XOR with current value
q&[ Return to tape position 0
.&] Move to tape position corresponding to result of earlier XOR
?o Get and output byte at current tape position
e( Search for -1 to left of current tape position (which will put us at position -1)
K Jump to previously pushed return address.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-P`, 33 bytes
```
;
EkB+"<>}\{`"1
¬i63 åÈ^VaYÃÅm!gV
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=OwpFa0IrIjw+fVx7YCIxCqxpNjMg5cheVmFZw8VtIWdW&input=Ijk0NS8iCi1Q)
For some reason, the test cases object to running as a suite, so here's the [second](https://ethproductions.github.io/japt/?v=1.4.6&code=OwpFa0IrIjw+fVx7YCIxCqxpNjMg5cheVmFZw8VtIWdW&input=IiwmJzhbMTQgPT87Z3ArJSAyJ0BzJiZjNDUvZWc4PyYiCi1Q), [third](https://ethproductions.github.io/japt/?v=1.4.6&code=OwpFa0IrIjw+fVx7YCIxCqxpNjMg5cheVmFZw8VtIWdW&input=JzthJDUkJTByPzJAMTJkdzYjIGxiLWVnJjUxOW50JW90PTkkQGVzQDk2Kz87Z2EiIDQqKSZ0YTU2ZHBbP28jdCVvaC8iKCY/I2VlIVssKywvK2ZlNCInCi1Q), and [fourth](https://ethproductions.github.io/japt/?v=1.4.6&code=OwpFa0IrIjw+fVx7YCIxCqxpNjMg5cheVmFZw8VtIWdW&input=In4hIyEnISMhLyEjISchIyFbISMhJyEjIS8hIyEnISMhfiEjISchIyEvISMhJyEjIVshIyEnISMhLyEjISchIyEiCi1Q) individually.
Explanation:
```
; #Set E to a string of all printable ASCII characters
Ek 1 #Set V to E with these characters removed:
B # All uppercase letters
+"<>}\{`" # and the characters "<>}{`"
¬ #Turn the input into an array
i63 #Add the number 63 to the front of that array
å Ã #Replace each character with:
È # The index of the previous decoded character in V
^ # Xor with...
VaY # The index of the current character in V
Å #Remove the extra character
m!gV #Map the indexes to the character in V
#Join to a string due to the flag
```
[Answer]
# APL(NARS), 72 chars, 144 bytes
```
{r←6⍴2⋄y←{r⊤⍵}¨¯1+⍵⍳⍨s←⎕AV[33..127]∼⎕A,'{<>}`'⋄y[1]←⊂∼↑y⋄s[1+{r⊥⍵}¨≠\y]}
```
This suppose the input is always in the array 's'... For understand how to do decipher i had to write the assembly version first... test:
```
h←{r←6⍴2⋄y←{r⊤⍵}¨¯1+⍵⍳⍨s←⎕AV[33..127]∼⎕A,'{<>}`'⋄y[1]←⊂∼↑y⋄s[1+{r⊥⍵}¨≠\y]}
h ,'6'
f
h '945/'
code
h ",&'8[14 =?;gp+% 2'@s&&c45/eg8?&"
programming puzzles & code golf
h ';a$5$%0r?2@12dw6# lb-eg&519nt%ot=9$@es@96+?;ga" 4*)&ta56dp[?o#t%oh/"(&?#ee![,+,/+fe4"'
a $150 reward will be given to those sending account and pin# to hackers@steal_id.com
h "~!#!'!#!/!#!'!#![!#!'!#!/!#!'!#!~!#!'!#!/!#!'!#![!#!'!#!/!#!'!#!"
!"#$%&'()*+,-./0123456789:;=?@[\]^_abcdefghijklmnopqrstuvwxyz|~
```
[Answer]
# 105 103 bytes, machine code (16-bit x86), 57 instructions
```
00000000: ff 01 b9 01 00 89 fa b4 3f cd 21 85 c0 75 02 cd
00000010: 20 8a 05 2c 20 3c 1d 72 1b 48 3c 1e 72 16 48 3c
00000020: 39 72 11 2c 1a 3c 25 72 0b 48 3c 3f 72 06 48 3c
00000030: 40 72 01 48 32 04 24 3f 88 04 3c 3f 72 01 40 3c
00000040: 3e 72 01 40 3c 24 72 01 40 3c 1f 72 02 04 1a 3c
00000050: 1d 72 01 40 3c 1c 72 01 40 04 20 43 89 d9 88 05
00000060: b4 40 cd 21 4b eb 9b
```
Running: save to codegolf.com, dosbox:
`codegolf.com < input.bin`
Almost forgot fun part: [](https://i.stack.imgur.com/TPEjO.png)
Howdy, this is my second entry. Previous one was [RC4](https://codegolf.stackexchange.com/questions/126244/simple-encryption-for-people-on-a-byte-budget/179324#179324).
Done using [HT hexeditor](http://hte.sourceforge.net), **without compiler**, but this time I was using Ctrl-a `assemble instruction`, I still dunno if this
counts as an entry or not.
## Why & how
In as similar manner I've started by creating file with `NOP`s, then
I reused reading in /writing out from [RC4](https://codegolf.stackexchange.com/questions/126244/simple-encryption-for-people-on-a-byte-budget/179324#179324).
I first written in python 'translation ladder' from ascii to index.
and used that in assembly, created similar ladder in reverse direction,
finally I added small trick to handle first byte
In a similar fashion to RC4 last step was getting rid of additional `nops`,
which required fixing jumps.
## Dissection
Again program relies on [initial register values](http://www.fysnet.net/yourhelp.htm).
```
00000000 ff01 inc word ptr [bx+di]
```
Dummy, will be needed later
```
00000002 b90100 mov cx, 0x1
00000005 89fa mov dx, di
00000007 b43f mov ah, 0x3f
00000009 cd21 int 0x21
```
read byte
```
0000000b 85c0 test ax, ax
0000000d 7502 jnz 0x11
0000000f cd20 int 0x20
```
quit if stdin finished
```
00000011 8a05 mov al, [di]
00000013 2c20 sub al, 0x20
00000015 3c1d cmp al, 0x1d
00000017 721b jc 0x34
00000019 48 dec ax
0000001a 3c1e cmp al, 0x1e
0000001c 7216 jc 0x34
0000001e 48 dec ax
0000001f 3c39 cmp al, 0x39
00000021 7211 jc 0x34
00000023 2c1a sub al, 0x1a
00000025 3c25 cmp al, 0x25
00000027 720b jc 0x34
00000029 48 dec ax
0000002a 3c3f cmp al, 0x3f
0000002c 7206 jc 0x34
0000002e 48 dec ax
0000002f 3c40 cmp al, 0x40
00000031 7201 jc 0x34
00000033 48 dec ax
```
ladder that translates ascii to index (mind that all jumps go to 0x134)
```
00000034 3204 xor al, [si]
```
xor byte by previous byte, `SI` points at address `0x100`,
which initially contains 0xFF from the opcode of a dummy instruction
at the top, which results in negate behavior
(reminder: COMs are loaded at 0x100)
```
00000036 243f and al, 0x3f
00000038 8804 mov [si], al
```
limit result to index, and store byte at 0x100,
```
0000003a 3c3f cmp al, 0x3f
0000003c 7201 jc 0x3f
0000003e 40 inc ax
0000003f 3c3e cmp al, 0x3e
00000041 7201 jc 0x44
00000043 40 inc ax
00000044 3c24 cmp al, 0x24
00000046 7201 jc 0x49
00000048 40 inc ax
00000049 3c1f cmp al, 0x1f
0000004b 7202 jc 0x4f
0000004d 041a add al, 0x1a
0000004f 3c1d cmp al, 0x1d
00000051 7201 jc 0x54
00000053 40 inc ax
00000054 3c1c cmp al, 0x1c
00000056 7201 jc 0x59
00000058 40 inc ax
00000059 0420 add al, 0x20
```
ladder in reverse direction
```
0000005b 43 inc bx
0000005c 89d9 mov cx, bx
0000005e 8805 mov [di], al
00000060 b440 mov ah, 0x40
00000062 cd21 int 0x21
00000064 4b dec bx
```
put byte under [di], write byte to stdout (mind that AH=40h uses DX as an
address, but it was set at the top, when reading byte)
mind that stdin -> stdout and stdout to stdin is done using inc bx / dec bx
```
00000067 eb99 jmp 0x2
```
loop ^^
## Tools and resources
* [ht editor](http://hte.sourceforge.net) - it has 16-bit disasm/assembly
* [hexplorer](https://sourceforge.net/projects/hexplorer/) - for mouse based copy/paste + insert/overwrite
* dosbox - for debugging
* [Register values at DOS .COM startup](http://www.fysnet.net/yourhelp.htm)
]
|
[Question]
[
Write a function or complete program that takes a positive number `n` and performs `n` steps of an iterative algorithm for calculating π that has quadratic convergence (i.e. it approximately doubles the number of accurate digits at every iteration) then returns or prints out 2n correct digits (including the beginning 3). One such algorithm is the [Gauss–Legendre algorithm](http://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm), but you are free to use a different algorithm if you prefer.
**Examples:**
input `1` → output `3.1`
input `2` → output `3.141`
input `5` → output `3.1415926535897932384626433832795`
**Requirements:**
* Each iteration of the algorithm must perform a constant number of basic operations such as addition, subtraction, multiplication, division, power and root (with integer exponent/degree) - each such operation on "big" integer/decimal numbers is counted as one even if it involves one or more loops internally. To be clear, trigonometric functions and powers involving complex numbers are not basic operations.
* The algorithm is expected to have an initialization step which must also have a constant number of operations.
* If the algorithm needs 1 or 2 more iterations to get to 2n correct digits, you can perform up to `n+2` iterations instead of just `n`.
* If it wasn't clear enough, after the correct 2n digits, your program must **not** print anything else (such as more correct digits, wrong digits or the complete works of Shakespeare).
* Your program must support values of `n` from 1 to at least 20.
* Your program should not take more than an hour for `n`=20 on a modern computer (not a hard rule, but try to keep it reasonable).
* The program must not obtain more than 20 accurate digits after the initialization and first iteration of the algorithm.
* The program must be runnable in Linux using freely available software.
* The source code must use only ASCII characters.
**Scoring:**
Straightforward code golf, shortest code wins.
**Winner:**
The winner is Digital Trauma, I finally finished running his code on n=20 (just kidding). Special prize goes to primo for his very fast python solution and different algorithm :)
[Answer]
# dc, 99 bytes
Golfed:
```
2?dsi1+^k1dddsa2v/sb4/stsp[lalb*vlalb+2/dla-d*lp*ltr-stsasblp2*spli1-dsi0<m]dsmxK2/1-klalb+d*4lt*/p
```
With whitespace and comments for "readability":
```
2?dsi # Push 2. push input n, duplicate and store in i
1+^k # Set calculation precision to 2^(n+1)
1dddsa # Push four 1s. Store 1st in a
2v/sb # Store 1/sqrt(2) in b
4/st # Store 1/4 in t
sp # Store 1 in p
[ # Start iteration loop macro
lalb*v # Save sqrt(a*b) on stack
lalb+2/d # Save a[i+1] = (a[i]+b[i])/2 on stack and duplicate
la-d*lp*ltr- # Save t-p(a[i]-a[i+1])^2 on the stack
st # Store t result from stack
sa # Store a result from stack
sb # Store b result from stack
lp2*sp # Store 2p in p
li1-dsi0<m] # Decrement iteration counter i; recurse into macro if < 0
dsmx # Duplicate, store and run macro
K2/1-k # Set display precision to 2^n-1
lalb+d*4lt*/ # Save (a+b)^2/4t on stack
p # Print result
```
`dc` needs to be told how many digits of precision should be used. The calculation precision needs to be higher than the final display precision, so the calculation precision is set to be `2^(n+1)` digits. I have verified the accuracy of the output with n=10 against <http://www.angio.net/pi/digits/pi1000000.txt>.
This slows down dramatically for larger n; n=12 takes 1.5 mins on my VM. Running a few different samples shows the time complexity is O(e^n) (not surprising). Extrapolating this to n=20 would have a runtime of 233 days. Oh well. Better than heat-death-of-the-universe at least.
This is moderately golfed - the stack is used to eliminate temporary variables during the calculations of each iteration, but there is possibly more use of the stack to shorten this more.
```
$ dc glpi.dc <<< 1
3.1
$ dc glpi.dc <<< 2
3.141
$ dc glpi.dc <<< 5
3.1415926535897932384626433832795
$ time dc glpi.dc <<< 7
3.1415926535897932384626433832795028841971693993751058209749445923078\
164062862089986280348253421170679821480865132823066470938446
real 0m0.048s
user 0m0.039s
sys 0m0.000s
$
```
If you don't like `dc` wrapping output at 70 chars, you can set the environment variable `DC_LINE_LENGTH` to 0:
```
$ DC_LINE_LENGTH=0 dc glpi.dc <<< 8
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648
$
```
[Answer]
# R, 156 bytes
Let's get this party started... with the absolute naivest implementation of the Gauss-Legendre algorithm ever.
```
for(i in 1:scan()){if(i<2){a=p=Rmpfr::mpfr(1,2e6);t=a/4;b=t^t}else{x=(a+b)/2;b=(a*b)^.5;t=t-p*(a-x)^2;a=x;p=2*p};o=(a+b)^2/(4*t)};cat(Rmpfr::format(o,2^i))
```
Ungolfed + explanation:
```
# Generate n approximations of pi, where n is read from stdin
for (i in 1:scan()) {
# Initial values on the first iteration
if (i < 2) {
a <- p <- Rmpfr::mpfr(1, 1e7)
t <- a/4
b <- t^t
} else {
# Compute new values
x <- (a + b) / 2
b <- (a*b)^0.5
t <- t - p*(a - x)^2
# Store values for next iteration
a <- x
p <- 2*p
}
# Approximate pi
o <- (a + b)^2 / (4*t)
}
# Print the result with 2^n digits
cat(Rmpfr::format(o, 2^i))
```
The `mpfr()` function is part of the `Rmpfr` package. It creates an `mpfr` object using the first argument as the value and the second argument as the number of bits of precision. We assign `a` and `p` to 1, and by defining `t` based on `a` (and `b` based on `t`), the `mpfr` type propogates to all four variables, thereby maintaining precision throughout.
As mentioned, this requires the R package `Rmpfr`, which is an acronym for "R Multiple Precision Floating point Reliable." The package uses GMP in the background. Unfortunately base R does not have the ability to do high-precision arithmetic, hence the package dependency.
Don't have `Rmpfr`? No sweat. `install.packages("Rmpfr")` and all of your dreams will come true.
Notice that `2e6` was specified as the precision. That means we have 2,000,000 bits of precision, which is enough to maintain precision for at least `n` = 20. (Note: `n` = 20 takes a long time but less than an hour on my computer.)
The approach here is literally just a regurgitation of the formulas on the Wikipedia page, but hey, we have to start somewhere.
Any input is welcome as always!
---
I had to rewrite a lot of this but I still have to acknowledge that Peter Taylor helped me knock *70 bytes* off of my first score. In the words of DigitalTrauma, "boom."
[Answer]
# Python 2, 214 bytes
This challenge presented a good excuse for me to learn the Decimal module. The Decimal numbers have definable precision and have square root support. I have set the precision to a conservative estimate of the accuracy depending on the loop count.
### Update
I have updated the program to improve accuracy and speed, at the expense of
golfing. By using the decimal `sqrt()` method and replacing the `x**2` usage
with `x*x`, it is now 200 times faster. This means it can now compute 20
loops giving a million digit result in 6.5 hours. The Decimal
numbers often have an error in the last digit (caused by operations on the limit
of precision), so the program now uses and discards 5 extra digits so only accurate digits are printed.
```
from decimal import*
d=Decimal
e=input()
getcontext().prec=5+(1<<e)
k=d(1)
j=d(2)
g=j*j
h=k/j
a=k
b=k/j.sqrt()
t=k/g
p=k
for i in[0]*e:f=a;a,b=(a+b)/j,(a*b).sqrt();c=f-a;t-=c*c*p;p+=p
l=a+b
print str(l*l/g/t)[:-5]
```
Sample run:
```
$ echo 1 | python min.py
3.1
$ echo 2 | python min.py
3.141
$ echo 3 | python min.py
3.1415926
$ echo 5 | python min.py
3.1415926535897932384626433832795
$ echo 12 | python min.py
3.141592653589793238462643383279502884197169399375105820974944592307816406286208
99862803482534211706798214808651328230664709384460955058223172535940812848111745
02841027019385211055596446229489549303819644288109756659334461284756482337867831
65271201909145648566923460348610454326648213393607260249141273724587006606315588
17488152092096282925409171536436789259036001133053054882046652138414695194151160
94330572703657595919530921861173819326117931051185480744623799627495673518857527
24891227938183011949129833673362440656643086021394946395224737190702179860943702
77053921717629317675238467481846766940513200056812714526356082778577134275778960
91736371787214684409012249534301465495853710507922796892589235420199561121290219
60864034418159813629774771309960518707211349999998372978049951059731732816096318
59502445945534690830264252230825334468503526193118817101000313783875288658753320
83814206171776691473035982534904287554687311595628638823537875937519577818577805
32171226806613001927876611195909216420198938095257201065485863278865936153381827
96823030195203530185296899577362259941389124972177528347913151557485724245415069
59508295331168617278558890750983817546374649393192550604009277016711390098488240
12858361603563707660104710181942955596198946767837449448255379774726847104047534
64620804668425906949129331367702898915210475216205696602405803815019351125338243
00355876402474964732639141992726042699227967823547816360093417216412199245863150
30286182974555706749838505494588586926995690927210797509302955321165344987202755
96023648066549911988183479775356636980742654252786255181841757467289097777279380
00816470600161452491921732172147723501414419735685481613611573525521334757418494
68438523323907394143334547762416862518983569485562099219222184272550254256887671
79049460165346680498862723279178608578438382796797668145410095388378636095068006
42251252051173929848960841284886269456042419652850222106611863067442786220391949
45047123713786960956364371917287467764657573962413890865832645995813390478027590
09946576407895126946839835259570982582262052248940772671947826848260147699090264
01363944374553050682034962524517493996514314298091906592509372216964615157098583
87410597885959772975498930161753928468138268683868942774155991855925245953959431
04997252468084598727364469584865383673622262609912460805124388439045124413654976
27807977156914359977001296160894416948685558484063534220722258284886481584560285
06016842739452267467678895252138522549954666727823986456596116354886230577456498
03559363456817432411251507606947945109659609402522887971089314566913686722874894
05601015033086179286809208747609178249385890097149096759852613655497818931297848
21682998948722658804857564014270477555132379641451523746234364542858444795265867
82105114135473573952311342716610213596953623144295248493718711014576540359027993
44037420073105785390621983874478084784896833214457138687519435064302184531910484
81005370614680674919278191197939952061419663428754440643745123718192179998391015
91956181467514269123974894090718649423196156794520809514655022523160388193014209
37621378559566389377870830390697920773467221825625996615014215030680384477345492
02605414665925201497442850732518666002132434088190710486331734649651453905796268
56100550810665879699816357473638405257145910289706414011097120628043903975951567
71577004203378699360072305587631763594218731251471205329281918261861258673215791
98414848829164470609575270695722091756711672291098169091528017350671274858322287
18352093539657251210835791513698820914442100675103346711031412671113699086585163
98315019701651511685171437657618351556508849099898599823873455283316355076479185
35893226185489632132933089857064204675259070915481416549859461637180270981994309
92448895757128289059232332609729971208443357326548938239119325974636673058360414
28138830320382490375898524374417029132765618093773444030707469211201913020330380
19762110110044929321516084244485963766983895228684783123552658213144957685726243
34418930396864262434107732269780280731891544110104468232527162010526522721116603
96665573092547110557853763466820653109896526918620564769312570586356620185581007
29360659876486117
```
The ungolfed code:
```
from decimal import *
d = Decimal
loops = input()
# this is a conservative estimate for precision increase with each loop:
getcontext().prec = 5 + (1<<loops)
# constants:
one = d(1)
two = d(2)
four = two*two
half = one/two
# initialise:
a = one
b = one / two.sqrt()
t = one / four
p = one
for i in [0]*loops :
temp = a;
a, b = (a+b)/two, (a*b).sqrt();
pterm = temp-a;
t -= pterm*pterm * p;
p += p
ab = a+b
print str(ab*ab / four / t)[:-5]
```
[Answer]
## Python (2.7) - 131 bytes
```
from gmpy import*
n=input()
p=a=fsqrt(mpf(8,4<<n));b=0
exec"a=fsqrt(a/2);b=1/(a-a*b+b/a+1);p*=b+a*a*b;a+=1/a;"*n
print`p`[5:2**n+6]
```
***Update:** Now using `gmpy` rather than `gmpy2`. For whatever reason, in `gmpy2` setting the precision on a single value doesn't propagate to other values. The result of any calculation reverts back to the precision of the current context. Precision does propagate in `gmpy`, which seems more intuitive to me. It's also considerably less verbose.*
Using one of the many algorithms devised by [Borwein and Borwein](http://www.pi314.net/eng/borwein.php), slightly refactored. n=20 takes about 11 seconds on my box. Not the most efficient method, but still not bad.
---
**Refactoring**
The original algorithm was the following:




Refactoring was done incrementally, but the end result is that 




The major simplification happens in *pn+1*. It's also slightly faster due to having eliminated a division.
The current implementation pushes *an* back one iteration in the calculation of *pn+1*, which allows for a different initialization of *p0* (*2√2*), but is otherwise identical.
---
**Sample Usage**
```
$ echo 1 | python pi-borwein.py
3.1
$ echo 2 | python pi-borwein.py
3.141
$ echo 5 | python pi-borwein.py
3.1415926535897932384626433832795
$ echo 10 | python pi-borwein.py
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420198938095257201065485863278
```
[Answer]
# bc and Newton's method, 43 bytes
[Newton's method](http://en.wikipedia.org/wiki/Newton%27s_method) for finding zeros of any function converges quadratically and the algorithm is way simpler than for Gauss-Legendre. It basically boils down to:

So here goes the according snippet:
```
n=20;x=3;scale=2^n;while(n--)x-=s(x)/c(x);x
```
A bit more readable:
```
/* desired number of iterations */
n = 20;
/* starting estimate for pi */
x = 3;
/* set precision to 2^n */
scale = 2^n;
/* perform n iteration steps */
while(n--)
// f:=sin, f'=cos
x -= s(x)/c(x)
```
To test this, run `bc -l` in a shell and paste the above snippet. Be prepared to wait for a while; `n=20` has been running for about 5min now and no end in sight, yet. `n=10` takes about 40s.
]
|
[Question]
[
Starting with `/\` you can create a [Sierpinski triangle](http://en.wikipedia.org/wiki/Sierpinski_triangle) like pattern by adding a line beneath such that...
1. Any loose branch `/` or `\` splits again into two branches: `/\`.
2. Any collision of branches `\/` dies with nothing (but spaces) under it.
Repeating these rules yields
```
/\
/\/\
/\ /\
/\/\/\/\
/\ /\
/\/\ /\/\
etc...
```
([Inspiration by ViHart](http://www.youtube.com/watch?v=e4MSN6IImpI&t=2m0s))
Write a program or function that takes in a positive integer N and prints the first N lines of this pattern to stdout, with no more leading or trailing spaces than necessary.
For example, if the input is `1` the output must be
```
/\
```
If the input is `2` the output must be
```
/\
/\/\
```
If the input is `8` the output must be
```
/\
/\/\
/\ /\
/\/\/\/\
/\ /\
/\/\ /\/\
/\ /\ /\ /\
/\/\/\/\/\/\/\/\
```
And so on.
The code with the fewest bytes wins.
[Answer]
## GolfScript (42 bytes)
```
~,-1%1\{' '*\.2base{' /\\'2/=}%[[email protected]](/cdn-cgi/l/email-protection)*^}/;;
```
[Online demo](http://golfscript.apphb.com/?c=Oyc3JwoKfiwtMSUxXHsnICcqXC4yYmFzZXsnICAvXFwnMi89fSVuQC4yKl59Lzs7)
This exploits a well-known relationship between Pascal's triangle and the Sierpinski triangle.
[Answer]
# CJam, ~~48~~ 46 bytes
```
li(_S*"/\\":T+\{_N@S+TW%/S2**" /"/"\ "f/:+T*}*
```
Simple recursive approach based on observations 1 and 2 in the question.
[Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### How it works
```
li( " L := int(input()) - 1 ";
_S* " A := L * ' ' ";
"/\\":T+ " A += (T := '/\') ";
\{ " do L times: ";
_N " push A, '\n' ";
@S+ " A += ' ' ";
TW%/ " B := A.split(reverse(T)) ";
S2** " A := ' '.join(B) ";
" /"/ " B := A.split(' /') ";
"\ "f/ " C := { X.split('\ ') : X ∊ B } ";
:+T* " A := T.join(sum(C, [])) ";
}* " ";
```
---
# CJam, 51 bytes
```
li__2mL,1a\{2_@##)1$f*+}/<f{2b_" /\\"2/f=@@,-S*\N}
```
I like this approach better, but it can't compete with the recursive one. Even after eliminating `2mL` (which results in at least O(2n) execution time), I'm still at 48 bytes...
This approach encodes `/\`'s as 1's and double spaces between them as 0's. Considering the resulting arrays binary numbers, we see that the configuration of the *nth* row corresponds to the *nth* integer larger than 1 that can be expressed as a product of different Fermat numbers (integers of the form **22k+1**).
### How it works
```
li__2mL,1a " push L := int(input()), L, R := range(log(L)/log(2)), A := [1] ";
\{2_@##)1$f*+}/ " for I in R: A += { a × 2**(2**I) : a ∊ A } ";
< " A := A[:L] ";
f{ " for I in R: push L, I ";
2b_" /\\"2/ " push (B := base(I, 2)), B, S := [ ' ' '/\' ] ";
f= " for J in I: J := S[J] ";
@@,-S*\N " push (L - len(B)) * ' ', J, '\n' ";
} " ";
```
[Answer]
# Python 2 - ~~140 139 127 122 121 118~~ 116
```
N=input()
b,V,m,n=' V/\\'
s=b*~-N+m+n
R=str.replace
while N:print s;N-=1;s=R(R(R(R(s+b,b+m,V),n+b,V),n+m,b+b),V,m+n)
```
Based on temporary string replacements (<https://stackoverflow.com/a/8687380/3419103>):
1. `/` > `V`
2. `\` > `V`
3. `\/` > `__` (2 spaces)
4. `V` > `/\`
[Answer]
# Javascript - 117 bytes
Minified:
```
T=n=>{S=' '.repeat(n-1);a='/\\';for(t=s=S+a+S;--n;t+='\n'+s)s=s.replace(/\\\//g,' ').replace(/ \/|\\ /g,a);return t}
```
Expanded:
```
T = n => {
S = ' '.repeat( n-1 );
a = '/\\';
for( t = s = S + a + S; --n; t += '\n' + s )
s = s.replace( /\\\//g, ' ' ).replace( / \/|\\ /g, a );
return t;
}
```
Sample Output (for `n = 20`):
```
/\
/\/\
/\ /\
/\/\/\/\
/\ /\
/\/\ /\/\
/\ /\ /\ /\
/\/\/\/\/\/\/\/\
/\ /\
/\/\ /\/\
/\ /\ /\ /\
/\/\/\/\ /\/\/\/\
/\ /\ /\ /\
/\/\ /\/\ /\/\ /\/\
/\ /\ /\ /\ /\ /\ /\ /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
/\ /\
/\/\ /\/\
/\ /\ /\ /\
/\/\/\/\ /\/\/\/\
```
Now if only the `repeat` and `replace` function names weren't so long. :P
[Answer]
# Pyth, 45 bytes
```
K"/\\"Jt+*QdKVQpbJ=JjKsmcd"\ "cj*2dc+Jd_K" /"
```
### Example run
```
$ pyth -c 'K"/\\"Jt+*QdKVQpbJ=JjKsmcd"\ "cj*2dc+Jd_K" /"' <<< 16
/\
/\/\
/\ /\
/\/\/\/\
/\ /\
/\/\ /\/\
/\ /\ /\ /\
/\/\/\/\/\/\/\/\
/\ /\
/\/\ /\/\
/\ /\ /\ /\
/\/\/\/\ /\/\/\/\
/\ /\ /\ /\
/\/\ /\/\ /\/\ /\/\
/\ /\ /\ /\ /\ /\ /\ /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
```
### How it works
```
# Q = eval(input())
K"/\\" # K = "/\\"
Jt+*QdK # J = (Q * " " + K)[1:]
VQ # for N in range(Q):
pbJ # print(J, end="\n")
#
=JjK # J = K.join(
sm # sum(list(map(lambda d:
cd"\ " # d.split("\ "),
c # .split( )
j*2d # " ".join( )
c _K # .split(K[::-1])
+Jd # (J + " ")
" /" # " /"
# ))))
```
[Answer]
# Ruby, 90
```
f=->n{a=["/\\".center(2*n)]
2.upto(n){a<<a[-1].gsub("\\/"," ").gsub(/ \/|\\ /,"/\\")}
puts a}
```
## Explanation
* Input is taken as an argument to a lambda. It is expected to be an `Integer`.
* Use `String#center` to create a `String` `"/\"` with `n - 2` spaces on each side and put it into an `Array` (`a`).
* Add to `a` the last element of `a` with every occurrence of `"\/"` replaced with `" "` and every occurrence of `" /"` or `" \"` replaced with `"/\"`.
* Use `puts` to print each element in `a` on its own line.
[Answer]
# Haskell, ~~128~~ 112
```
g n=unlines$take n$i t([1..n]>>" ")%(i(\l->l++l%i(t.t)(t l>>" ")%l)["/\\"]!!n)
t=tail
(%)=zipWith(++)
i=iterate
```
[Answer]
# JavaScript (E6) 107 ~~106~~
Edit: fixed byte count, made recursive.
Not much different from the other JS answer ... at least this one 'prints' the pattern as requested.
The core is replacing ' /' '\ ' with '/\' and all the rest with ' ' on each new line.
```
F=(n,o=t='/\\',b=' ')=>
n--&&
console.log(b.repeat(n)+o)|
F(n,(b+o+b).replace(/../g,s=>s==b+b|s=='\\/'?b+b:t))
```
**Test** In FireFox/FireBug console
```
F(15)
```
*Output*
```
/\
/\/\
/\ /\
/\/\/\/\
/\ /\
/\/\ /\/\
/\ /\ /\ /\
/\/\/\/\/\/\/\/\
/\ /\
/\/\ /\/\
/\ /\ /\ /\
/\/\/\/\ /\/\/\/\
/\ /\ /\ /\
/\/\ /\/\ /\/\ /\/\
/\ /\ /\ /\ /\ /\ /\ /\
```
[Answer]
# Perl 5 - 56 bytes
\0's can be replaced by actual null byte characters
```
#!/usr/bin/perl -l
$p="/\\";$_=$"x~$_.$p,y/\0/ /,print,$p^="\0\0$p"for-<>..-1
```
It is using the fact that if you ignore leading spaces and represent '/\' as 1 and ' ' as 0 the pattern in a given row f(n) = f(n-1) ^ (f(n-1) << 1). However the calculations in the code above are executed on strings that are close to the expected output (no leading spaces, other spaces replaced by null bytes) thanks to perl's bitwise string manipulation.
```
$p="/\\"; # initialize
$_=$"x~$_.$p, # loop start, add spaces
y/\0/ /, # replace nulls with spaces
print, # output
$p^="\0\0$p" # calculate next string
for-<>..-1 # loop from -n to -1
```
[Answer]
## Python 2, 84 bytes
```
n=i=input()
while i:print' '*i+''.join("/ \ "[j&i+1>0::2]for j in range(n-i+1));i-=1
```
[Answer]
# Mathematica, 86 bytes
```
Column[Row/@Mod[Table[Binomial[n,k],{n,0,#-1},{k,0,n}],2]/.{1->"/\\",0->" "},Center]&
```
[Answer]
## Javascript with lambdas, ~~141~~ 128
**141**
```
f=n=>{for(a="25",q=0;++q<n;a=a[r='replace'](/^|$/mg,1)[r](/(.*)$/,"$1\n$1")[r](/..(?=.*$)/g,x=>x%3?11:25));return a[r](/./g,x=>" / \\"[x])}
```
**128**
```
f=n=>(t=a=>--n?t(a[r='replace'](/^|$/mg,1)[r](/(.*)$/,"$1\n$1")[r](/..(?=.*$)/g,x=>x%3?11:25)):a)("25")[r](/./g,x=>" / \\"[x])
```
Can be tested at Firefox (n=16):
```
/\
/\/\
/\ /\
/\/\/\/\
/\ /\
/\/\ /\/\
/\ /\ /\ /\
/\/\/\/\/\/\/\/\
/\ /\
/\/\ /\/\
/\ /\ /\ /\
/\/\/\/\ /\/\/\/\
/\ /\ /\ /\
/\/\ /\/\ /\/\ /\/\
/\ /\ /\ /\ /\ /\ /\ /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
```
[Answer]
# Python 2, 97 bytes
```
i=input()
x=1
while i:i-=1;print " "*i+bin(x)[2:].replace("0"," ").replace("1", "/\\");x^=2*x
```
]
|
[Question]
[
Einstein wrote a riddle. He said that 98% of the world could not solve it.
I solved this riddle in about 25 minutes while on the train to work.
It's basically just deduction.
# The riddle
>
> There are 5 houses in 5 different colors in a row.
>
> In each house lives a person with a different nationality.
>
> The 5 owners drink a certain type of beverage, smoke a certain brand of cigar, and keep a certain pet.
>
> No owners have the same pet, smoke the same brand of cigar, or drink the same beverage.
>
> **Question:** *Who owns the fish?*
>
>
>
To solve this riddle Einstein provides 15 hints:
1. The Brit lives in the red house.
2. The Swede keeps dogs as pets.
3. The Dane drinks tea.
4. The green house is on the immediate left of the white house.
5. The green house's owner drinks coffee.
6. The owner who smokes Pall Mall rears birds.
7. The owner of the yellow house smokes Dunhill.
8. The owner living in the center house drinks milk.
9. The Norwegian lives in the first house.
10. The owner who smokes Blends lives next to the one who keeps cats.
11. The owner who keeps the horse lives next to the one who smokes Dunhill.
12. The owner who smokes Bluemasters drinks beer.
13. The German smokes Prince.
14. The Norwegian lives next to the blue house.
15. The owner who smokes Blends lives next to the one who drinks water.
With these hints you can come to a solution.
Your task:
Make a program that will solve this riddle for you.
Hard coding the solution isn't allowed (duh)
It is allowed to hardcode the hints in any format.
**Example format:**
```
//Hints in order
(Nationality:Brit)==(Color:Red)
(Nationality:Swede)==(Pet:Dogs)
(Nationality:Dane)==(Drink: Tea)
(Color:Green)/(Color:White)
(Color:Green)==(Drink:Coffee)
(Smoke:PallMall)==(Pet:Birds)
(Color:Yellow)==(Smoke:Dunhill)
(House:3)==(Drink:Milk)
(Nationality:Norwegian)==(House:1)
(Smoke:Blend)/\(Pet:Cats)
```
>
> == means equals to
>
> / means on left side of
>
> \ means on right side of
>
> /\ means left or right of
>
>
>
Like I said its allowed to either hardcode hints or have them as input.
Output:
Output should be in the following format (With the correct values, just saying for the trolls ;) )
```
_____________ _____________ _____________ _____________ _____________
| Number | | Number | | Number | | Number | | Number |
| Nationality | | Nationality | | Nationality | | Nationality | | Nationality |
| Color | | Color | | Color | | Color | | Color |
| Drink | | Drink | | Drink | | Drink | | Drink |
| Smoke | | Smoke | | Smoke | | Smoke | | Smoke |
| Pet | | Pet | | Pet | | Pet | | Pet |
--------------- --------------- --------------- --------------- ---------------
The <Nationality> in the <Color> house owns the fish!
```
Ascii art boxes can be changed by you, as long as they are boxes, doesn't matter what symbols you use.
Any knowledge on this riddle and solution can *not* be used in the program.
It should use pure logic and deduction to solve the riddle.
Tagged this as a codegolf but might be a code challenge, not sure.
Any thoughts on winning criteria for a code challenge feel free to share :)
For now this is code-golf so the program with the lowest bytecount wins.
Good luck and Happy coding :)
[Answer]
# Prolog - 954 Characters
```
m(A,Z):-member(A,Z).
e:-e(Z),w(Z).
e(Z):-Z=[[1,A,F,K,P,U],[2,B,G,L,Q,V],[3,C,H,M,R,W],[4,D,I,N,S,X],[5,E,J,O,T,Y]],m([_,b,r,_,_,_],Z),m([_,s,_,d,_,_],Z),m([_,d,_,_,t,_],Z),m([WH,_,w,_,_,_],Z),m([GH,_,g,_,_,_],Z),GH=:=WH-1,m([_,_,g,_,c,_],Z),m([_,_,_,b,_,p],Z),m([_,_,y,_,_,d],Z),m([3,_,_,_,m,_],Z),m([1,n,_,_,_,_],Z),m([BH,_,_,_,_,b],Z),m([CH,_,_,c,_,_],Z),(BH=:=CH+1;BH=:=CH-1),m([DH,_,_,_,_,d],Z),m([HH,_,_,h,_,_],Z),(HH=:=DH+1;HH=:=DH-1),m([_,_,_,_,b,l],Z),m([_,g,_,_,_,r],Z),m([NH,n,_,_,_,_],Z),m([YH,_,b,_,_,_],Z),(NH=:=YH+1;NH=:=YH-1),m([SH,_,_,_,_,b],Z),m([XH,_,_,_,w,_],Z),(SH=:=XH+1;SH=:=XH-1),p([n,d,b,g,s],[A,B,C,D,E]),p([y,b,r,g,w],[F,G,H,I,J]),p([c,h,b,f,d],[K,L,M,N,O]),p([w,t,m,c,b],[P,Q,R,S,T]),p([d,b,p,r,l],[U,V,W,X,Y]).
t(X,[X|R],R).
t(X,[F|R],[F|S]):-t(X,R,S).
p([W|X],Y):-p(X,V),t(W,Y,V).
p([],[]).
b:-write('+--+--+--+--+--+--+'),nl.
z(A):-writef('|%2L|%2L|%2L|%2L|%2L|%2L|',A),nl.
w([A,B,C,D,E]):-b,z(A),z(B),z(C),z(D),z(E),b.
```
**Output**
```
+--+--+--+--+--+--+
|1 |n |y |c |w |d |
|2 |d |b |h |t |b |
|3 |b |r |b |m |p |
|4 |g |g |f |c |r |
|5 |s |w |d |b |l |
+--+--+--+--+--+--+
```
Key:
* First column is house number;
* Second column is nationality;
* Third column is favorite color;
* Fourth column is pet;
* Fifth column is drink; and
* Sixth column is cigarette (r = prince, l = bluemaster).
[Answer]
# Ruby 322 + input 442
**Brute force** search of nearly **25 billion** possible answers.
My computer would take about **75 days** to run this program.
I never verified if this program prints a correct answer!
Run as `ruby riddle.rb < riddle.in`
*riddle.rb* (332 bytes)
```
g=readlines
v=g.shift(5).map &:split
c,*d=v.map{|a|[*a.permutation]}
c.product(*d){|a|(f=eval a.map{|b|b.each_with_index.map{|s,i|"#{s}=#{i}\n"}.join}.join+'g.map{|h|eval h}.all?&&fish')&&(r=['-----------']*5
puts [r,[*0..4],*a,r].map{|s|s.map{|t|'|%11s|'%t}.join},"The #{a[0][f]} in the #{a[1][f]} house owns the fish!")}
```
*riddle.in* (442 bytes)
```
brit dane german norwegian swede
blue green red white yellow
beer coffee milk tea water
blends bluemasters dunhill pall_mall prince
birds cats dogs fish horse
brit==red
swede==dogs
dane==tea
green==white-1
green==coffee
pall_mall==birds
yellow==dunhill
2==milk
norwegian==0
blends==cats-1||blends==cats+1
horse==dunhill-1||horse==dunhill+1
bluemasters==beer
german==prince
norwegian==blue-1||norwegian==blue+1
blends==water-1||blends==water+1
```
The input file must contain 5 lines of names, followed by lines of logical expressions. House numbers are 0 to 4. There must be a `fish`.
The program calls `Array#permutation` five times to find all ways to order the arrays of nationalities, colors, drinks, smokes and pets. The long loop is `c.product(*d){|a|...}`, calling `Array#product` to iterate nearly 25 billion possible answers. The loop body has the form `(f=eval ...)&&(...)`. The `eval ...` part evaluates the logical expressions. If all are true, then `f` is the house number of the fish and the `&&(...)` part prints the answer. House number 0 is true in Ruby.
Code golf means not adding code for speed! But I lack **75 days** to run the program!
[Answer]
## Prolog, 653 characters
```
a([],L,L).
a([H|T],L2,[H|L3]):-a(T,L2,L3).
m(X,L):-a(_,[X|_],L).
r(X,Y,L):-a(_,[X,Y|_],L).
n(X,Y,L):-r(X,Y,L);r(Y,X,L).
s:-s(S),w(S).
s(S):-length(S,5),m([b,r,_,_,_],S),m([s,_,_,_,d],S),m([d,_,t,_,_],S),r([_,g,_,_,_],[_,w,_,_,_],S),m([_,g,c,_,_],S),m([_,_,_,p,b],S),m([_,y,_,d,_],S),S=[_,_,[_,_,m,_,_],_,_],S=[[n,_,_,_,_],_,_,_,_],n([_,_,_,b,_],[_,_,_,_,c],S),n([_,_,_,d,_],[_,_,_,_,h],S),m([_,_,b,l,_],S),m([g,_,_,r,_],S),n([n,_,_,_,_],[_,b,_,_,_],S),n([_,_,_,b,_],[_,_,w,_,_],S),m([_,_,_,_,f],S).
b:-write('----------------+'),nl.
z(Y,A):-write(Y),writef('|%2L|%2L|%2L|%2L|%2L|',A),nl.
w([S1,S2,S3,S4,S5]):-b,z(1,S1),z(2,S2),z(3,S3),z(4,S4),z(5,S5),b.
```
[Answer]
# Smalltalk 1332 chars
**Using plain Smalltalk:**
```
|n c v g p t r|n:=#(Brit Swede Dane Norwegian German
Red Green White Yellow Blue
Tea Coffee Milk Beer Water
PallMall Dunhill Blends Bluemasters Prince
Dogs Birds Cats Horses Fish).
v:=Dictionary new.n do:[:n|v at:n put:nil].g:=n splitForSize:5.
c:={{[:b :r|b==r].#Brit.#Red}.{[:s :d|s==d].#Swede.#Dogs}.{[:d :t|d==t].#Dane.#Tea}.
{[:g :w|g==(w-1)].#Green.#White}.{[:g :c|g==c].#Green.#Coffee}.
{[:p :b|p==b].#PallMall.#Birds}.{[:y :d|y==d].#Yellow.#Dunhill}.
{[:m|m==3].#Milk}.{[:n|n==1].#Norwegian}.{[:b :c|(b-c)abs==1].#Blends.#Cats}.
{[:h :d|(h-d)abs==1].#Horses.#Dunhill}.{[:m :b|m==b].#Bluemasters.#Beer}.
{[:g :p|g==p].#German.#Prince}.{[:n :b|(n-b)abs==1].#Norwegian.#Blue}.
{[:b :w|(b-w)abs==1].#Blends.#Water}}.
t:=[:c|x:=(c from:2collect:[:n|v at:n]).(x includes:nil)or:[c first valueWithArguments:x]].
p:=[|f|(((''-'',* 16),'' ''),*5)printCR.g do:[:n||w|w:=n collect:[:n|v at:n].w sortWith:n.
n do:[:n|''|''print.(n centerPaddedTo:14)print.''| ''print].''''printCR.].(((''-'',* 16),'' ''),*5)printCR.
f:=v at:#Fish.(''The %1 in the %2 house owns the fish''bindWith:(g first detect:[:n|(v at:n)==f])with:((g at:2) detect:[:n|(v at:n)==f]))printCR].
r:=[:gi|gi==0ifTrue:p ifFalse:[#(1 2 3 4 5)permutationsDo:[:perm|v declareAll:(g at:gi)from:perm.
(c conform:t)ifTrue:[r value:gi-1]].v declareAll:(g at:gi)from:#(nil),*5]].
r value:g size.
```
Output:
```
---------------- ---------------- ---------------- ---------------- ----------------
| Norwegian | | Dane | | Brit | | German | | Swede |
| Yellow | | Blue | | Red | | Green | | White |
| Water | | Tea | | Milk | | Coffee | | Beer |
| Dunhill | | Blends | | PallMall | | Prince | | Bluemasters |
| Cats | | Horses | | Birds | | Fish | | Dogs |
---------------- ---------------- ---------------- ---------------- ----------------
The German in the Green house owns the fish
```
As the golfed version is almost unreadable, here is the developer's code with proper names, indentation and spaces for readability:
```
|names constraints foundSolution v groups printSolution testC test try|
names := #(Brit Swede Dane Norwegian German
Red Green White Yellow Blue
Tea Coffee Milk Beer Water
PallMall Dunhill Blends Bluemasters Prince
Dogs Birds Cats Horses Fish).
v := Dictionary new.
names do:[:n | v at:n put:nil].
groups := names splitForSize:5.
constraints := {
{[:b :r | b==r] . #Brit . #Red }. "/ The Brit lives in the red house.
{[:s :d | s==d] . #Swede . #Dogs }. "/ The Swede keeps dogs as pets.
{[:d :t | d==t] . #Dane . #Tea }. "/ The Dane drinks tea.
{[:g :w | g==(w-1)] . #Green . #White }. "/ The green house is on the immediate left of the white house.
{[:g :c | g==c] . #Green . #Coffee}. "/ The green house's owner drinks coffee.
{[:p :b | p==b] . #PallMall . #Birds}. "/ The owner who smokes Pall Mall rears birds.
{[:y :d | y==d] . #Yellow . #Dunhill}. "/ The owner of the yellow house smokes Dunhill.
{[:m | m==3] . #Milk}. "/ The owner living in the center house drinks milk.
{[:n | n==1] . #Norwegian }. "/ The Norwegian lives in the first house.
{[:b :c | (b-c)abs==1] . #Blends . #Cats}. "/ The owner who smokes Blends lives next to the one who keeps cats.
{[:h :d | (h-d)abs==1] . #Horses . #Dunhill}."/ The owner who keeps the horse lives next to the one who smokes Dunhill.
{[:m :b | m==b] . #Bluemasters . #Beer}. "/ The owner who smokes Bluemasters drinks beer.
{[:g :p | g==p] . #German . #Prince}. "/ The German smokes Prince.
{[:n :b | (n-b)abs==1] . #Norwegian . #Blue}."/ The Norwegian lives next to the blue house.
{[:b :w | (b-w)abs==1] . #Blends . #Water}. "/ The owner who smokes Blends lives next to the one who drinks water.
}.
testC := [:c | vi:=((c from:2) collect:[:n|v at:n]). (vi includes:nil) or:[c first valueWithArguments:vi]].
test := [constraints conform:testC].
printSolution :=
[ |f|
((('-',* 16),' '),*5) printCR.
groups do:[:names|
|values|
values := names collect:[:nm|v at:nm].
values sortWith:names.
names do:[:n| '|'print. (n centerPaddedTo:14)print.'| ' print].
'' printCR.
].
((('-',* 16),' '),*5) printCR.
f := v at:#Fish.
('The %1 in the %2 house owns the fish'
bindWith:((groups at:1) detect:[:n|(v at:n)==f])
with:((groups at:2) detect:[:n|(v at:n)==f]))printCR
].
try := [:gi |
gi == 0
ifTrue: printSolution
ifFalse:[
(1 to:5) asArray permutationsDo:[:perm |
v declareAll:(groups at:gi) from:perm.
test value ifTrue:[
try value:(gi-1).
].
].
v declareAll:(groups at:gi) from:#(nil nil nil nil nil).
].
].
try value:groups size.
```
**Using a constraint solver library:**
Using a constraint solver library, which is very similar to the one described in the OZ/Mozart manual.
As I expect you will complain this being not valid for the contest ;-), it is added for your amusement and inspiration only (look for a contraint package in your language), ungolfed, and not counting chars.
```
|solution|
solution := Solver
anySolutionFor:[
|Brit Swede Dane Norwegian German
Red Green White Yellow Blue
PallMall Dunhill Prince Blends Bluemasters
Tea Coffee Water Beer Milk
Dogs Birds Cats Horses Fish|
Brit := (1 %% 5) name:#Brit.
Swede := (1 %% 5) name:#Swede.
Dane := (1 %% 5) name:#Dane.
Norwegian := (1 %% 5) name:#Norwegian.
German := (1 %% 5) name:#German.
Red := (1 %% 5) name:#Red.
Green := (1 %% 5) name:#Green.
White := (1 %% 5) name:#White.
Yellow := (1 %% 5) name:#Yellow.
Blue := (1 %% 5) name:#Blue.
PallMall := (1 %% 5) name:#PallMall.
Dunhill := (1 %% 5) name:#Dunhill.
Prince := (1 %% 5) name:#Prince.
Blends := (1 %% 5) name:#Blends.
Bluemasters := (1 %% 5) name:#Bluemasters.
Tea := (1 %% 5) name:#Tea.
Coffee := (1 %% 5) name:#Coffee.
Milk := (1 %% 5) name:#Milk.
Water := (1 %% 5) name:#Water.
Beer := (1 %% 5) name:#Beer.
Dogs := (1 %% 5) name:#Dogs.
Birds := (1 %% 5) name:#Birds.
Cats := (1 %% 5) name:#Cats.
Horses := (1 %% 5) name:#Horses.
Fish := (1 %% 5) name:#Fish.
Solver allDistinct:{ Brit . Swede . Dane . Norwegian . German. }.
Solver allDistinct:{ Red. Green. White. Yellow. Blue. }.
Solver allDistinct:{ PallMall. Dunhill. Prince. Blends. Bluemasters. }.
Solver allDistinct:{ Tea. Coffee. Milk. Water. Beer }.
Solver allDistinct:{ Dogs. Birds. Cats. Horses. Fish. }.
Brit =: Red. "/ The Brit lives in the red house.
Swede =: Dogs. "/ The Swede keeps dogs as pets.
Dane =: Tea. "/ The Dane drinks tea.
Green =: (White - 1). "/ The green house is on the immediate left of the white house.
Green =: Coffee. "/ The green house's owner drinks coffee.
PallMall =: Birds. "/ The owner who smokes Pall Mall rears birds.
Yellow =: Dunhill. "/ The owner of the yellow house smokes Dunhill.
Milk =: 3. "/ The owner living in the center house drinks milk.
Norwegian =: 1. "/ The Norwegian lives in the first house.
(Blends - Cats) abs =: 1. "/ The owner who smokes Blends lives next to the one who keeps cats.
(Horses - Dunhill) abs =: 1. "/ The owner who keeps the horse lives next to the one who smokes Dunhill.
Bluemasters =: Beer. "/ The owner who smokes Bluemasters drinks beer.
German =: Prince. "/ The German smokes Prince.
(Norwegian - Blue) abs =: 1. "/ The Norwegian lives next to the blue house.
(Blends - Water) abs =: 1. "/ The owner who smokes Blends lives next to the one who drinks water.
].
solution printCR.
```
Notice the "=:" operator, which means "unify with". The solver uses a backtracking algorithm on the set of constraints defined in the problem block.
The remaining code prints the solution into boxes:
```
|pLine pSorted f |
pLine := [
(1 to:5) do:[:i | ('-' ,* 15) print] separatedBy:[' ' print].
'' printCR.
].
pSorted := [:keys |
|items t|
items := keys collect:[:k| solution at:k].
t := keys copy. items values sortWith:t.
pLine value:(t collect:[:x | '| ',(x centerPaddedTo:11),' |']).
].
pLine value.
pSorted value:#( Brit Swede Dane Norwegian German ).
pSorted value:#( Red Green White Yellow Blue ).
pSorted value:#( Tea Coffee Milk Water Beer ).
pSorted value:#( PallMall Dunhill Prince Blends Bluemasters ).
pSorted value:#( Dogs Birds Cats Horses Fish ).
pLine value.
f := solution at:'Fish'.
('The %1 in the %2 house owns the fish!'
bindWith:(#( Brit Swede Dane Norwegian German ) detect:[:n| (solution at:n) == f])
with:(#( Red Green White Yellow Blue ) detect:[:n| (solution at:n) == f])
) printCR.
```
Output:
```
Solution(Brit->3 Swede->5 Dane->2 Norwegian->1 German->4 Red->3 Green->4
White->5 Yellow->1 Blue->2 PallMall->3 Dunhill->1 Prince->4 Blends->2
Bluemasters->5 Tea->2 Coffee->4 Milk->3 Water->1 Beer->5 Dogs->5 Birds->3
Cats->1 Horses->2 Fish->4)
--------------- --------------- --------------- --------------- ---------------
| Norwegian | | Dane | | Brit | | German | | Swede |
| Yellow | | Blue | | Red | | Green | | White |
| Water | | Tea | | Milk | | Coffee | | Beer |
| Dunhill | | Blends | | PallMall | | Prince | | Bluemasters |
| Cats | | Horses | | Birds | | Fish | | Dogs |
--------------- --------------- --------------- --------------- ---------------
The German in the Green house owns the fish!
```
Edit: oops - I forgot to print the "who owns the fish" line in the plain version.
[Answer]
# Ruby 1166 characters
*Edit: Updated for correct output format*
Runs consistently in under 0.2 seconds on a MBP i5.
**Source: [View On Github](https://github.com/seanhandley/einstein)**
One-liner:
```
def q(a);a.permutation;end;def z(a,b,c,d);l(a,b,c,d)||l(c,d,a,b);end;def l(a,b,c,d);(0..4).any?{|i|a[i]==b&&c[i+1]==d};end;def i(a,b,c,d);(0..4).any?{|i|a[i]==b&&c[i]==d};end;def t(i);['White','Yellow','Blue','Red','Green','German','Swede','Brit','Norwegian','Dane','Birds','Cats','Horses','Fish','Dogs','Beer','Water','Tea','Milk','Coffee','Blends','PallMall','Prince','Bluemasters','Dunhill'][i];end;def y(s);l=13-s.length;'|'+' '*(l/2.0).floor+s+' '*(l/2.0).ceil+'|';end;def d(s);b=[' '+(0..4).map{'_'*13}.join(' '*4)];u=' ';b<<[1,2,3,4,5].map{|i|y(i.to_s)}.join(u);s.each{|i|b<<i.map{|j|y(t(j))}.join(u)};b<<(0..4).map{'-'*15}.join(u);b<<'';z=s[4].index(13);b<<"The #{t s[0][z]} in the #{t s[1][z]} house owns the fish!";b.join "\n";end;q([0,1,2,3,4]).each{|c|l(c,4,c,0)||next;q([5,6,7,8,9]).each{|n|i(n,7,c,3)||next;n[0]==8||next;z(n,8,c,2)||next;q([10,11,12,13,14]).each{|a|i(n,6,a,14)||next;q([15,16,17,18,19]).each{|d|d[2]==18||next;i(c,4,d,19)||next;i(n,9,d,17)||next;q([20,21,22,23,24]).each{|s|z(a,12,s,24)||next;i(s,21,a,10)||next;z(s,20,d,16)||next;z(s,20,a,11)||next;i(n,5,s,22)||next;i(c,1,s,24)||next;i(s,23,d,15)||next;puts d([n,c,d,s,a]);exit}}}}}
```
Padded with newlines to fit the page:
```
def q(a);a.permutation;end;def z(a,b,c,d);l(a,b,c,d)||l(c,d,a,b);end
def l(a,b,c,d);(0..4).any?{|i|a[i]==b&&c[i+1]==d};end;def i(a,b,c,d);
(0..4).any?{|i|a[i]==b&&c[i]==d};end;def t(i);['White','Yellow','Blue',
'Red','Green','German','Swede','Brit','Norwegian','Dane','Birds',
'Cats','Horses','Fish','Dogs','Beer','Water','Tea','Milk','Coffee',
'Blends','PallMall','Prince','Bluemasters','Dunhill'][i];end;def y(s);
l=13-s.length;'|'+' '*(l/2.0).floor+s+' '*(l/2.0).ceil+'|';end;
def d(s);b=[' '+(0..4).map{'_'*13}.join(' '*4)];u=' ';
b<<[1,2,3,4,5].map{|i|y(i.to_s)}.join(u);s.each{|i|b<<i.map{|j|
y(t(j))}.join(u)};b<<(0..4).map{'-'*15}.join(u);b<<'';
z=s[4].index(13);
b<<"The #{t s[0][z]} in the #{t s[1][z]} house owns the fish!";
b.join "\n";end;q([0,1,2,3,4]).each{|c|l(c,4,c,0)||next;
q([5,6,7,8,9]).each{|n|i(n,7,c,3)||next;n[0]==8||next;z(n,8,c,2)||next;
q([10,11,12,13,14]).each{|a|i(n,6,a,14)||next;
q([15,16,17,18,19]).each{|d|d[2]==18||next;i(c,4,d,19)||next;
i(n,9,d,17)||next;q([20,21,22,23,24]).each{|s|z(a,12,s,24)||next;
i(s,21,a,10)||next;z(s,20,d,16)||next;z(s,20,a,11)||next;i(n,5,s,22)||next;
i(c,1,s,24)||next;i(s,23,d,15)||next;puts d([n,c,d,s,a]);exit}}}}}
```
Outputs:
```
_____________ _____________ _____________ _____________ _____________
| 1 | | 2 | | 3 | | 4 | | 5 |
| Norwegian | | Dane | | Brit | | German | | Swede |
| Yellow | | Blue | | Red | | Green | | White |
| Water | | Tea | | Milk | | Coffee | | Beer |
| Dunhill | | Blends | | PallMall | | Prince | | Bluemasters |
| Cats | | Horses | | Birds | | Fish | | Dogs |
--------------- --------------- --------------- --------------- ---------------
The German in the Green house owns the fish!
```
## Ungolfed Code
```
@colors = [:white, :yellow, :blue, :red, :green].shuffle.permutation
@cigars = [:blends, :pall_mall, :prince, :bluemasters, :dunhill].shuffle.permutation
@nationalities = [:german, :swedish, :british, :norwegian, :danish,].shuffle.permutation
@drinks = [:beer, :water, :tea, :milk, :coffee].shuffle.permutation
@pets = [:birds, :cats, :horses, :fish, :dogs].shuffle.permutation
def next_to?(set_a, val_a, set_b, val_b)
left_of?(set_a, val_a, set_b, val_b) ||
left_of?(set_b, val_b, set_a, val_a)
end
def left_of?(set_a, val_a, set_b, val_b)
(0..4).any? do |i|
set_a[i] == val_a &&
set_b[i+1] == val_b
end
end
def implies?(set_a, val_a, set_b, val_b)
(0..4).any? do |i|
set_a[i] == val_a &&
set_b[i] == val_b
end
end
def solve
i = 0
@colors.each do |colors|
i += 1
next unless left_of?(colors, :green, colors, :white)
@nationalities.each do |nationalities|
i += 1
next unless implies?(nationalities, :british, colors, :red)
next unless nationalities[0] == :norwegian
next unless next_to?(nationalities, :norwegian, colors, :blue)
@pets.each do |pets|
i += 1
next unless implies?(nationalities, :swedish, pets, :dogs)
@drinks.each do |drinks|
i += 1
next unless drinks[2] == :milk
next unless implies?(colors, :green, drinks, :coffee)
next unless implies?(nationalities, :danish, drinks, :tea)
@cigars.each do |cigars|
i += 1
next unless next_to?(pets, :horses, cigars, :dunhill)
next unless implies?(cigars, :pall_mall, pets, :birds)
next unless next_to?(cigars, :blends, drinks, :water)
next unless next_to?(cigars, :blends, pets, :cats)
next unless implies?(nationalities , :german, cigars, :prince)
next unless implies?(colors, :yellow, cigars, :dunhill)
next unless implies?(cigars, :bluemasters, drinks, :beer)
return [colors, nationalities, pets, drinks, cigars], i
end
end
end
end
end
end
class Symbol
def humanize
result = self.to_s
result.gsub!('_', ' ')
result.split(' ').collect{|part| part.capitalize }.join(' ')
end
end
solution, attempts = solve
puts "\nSolved in #{attempts} attempts.\n\n"
for i in (0..4)
number, color, nationality, cigar, drink, pet = i+1, solution[0][i], solution[1][i].humanize, solution[4][i].humanize, solution[3][i], solution[2][i]
puts "House #{number} is #{color}. The owner is #{nationality}, smokes #{cigar}, drinks #{drink}, and keeps #{pet}."
end
puts "\n"
```
Outputs:
```
Solved in 37663 attempts.
House 1 is yellow. The owner is Norwegian, smokes Dunhill, drinks water, and keeps cats.
House 2 is blue. The owner is Danish, smokes Blends, drinks tea, and keeps horses.
House 3 is red. The owner is British, smokes Pall Mall, drinks milk, and keeps birds.
House 4 is green. The owner is German, smokes Prince, drinks coffee, and keeps fish.
House 5 is white. The owner is Swedish, smokes Bluemasters, drinks beer, and keeps dogs.
```
The use of `shuffle` in the initial setup ensures unique solution paths every time. You can see this by the number of attempts altering between runs. This mitigates the need to feed in the input separately, though altering the code to do so would be trivial.
]
|
[Question]
[
In this challenge you are asked to find in *how many ways* we can express a positive integer `n` as the sum of two positive integers `k` and the `reverse of k`.
Here is an example using `n = 1069` :
`188 + 881 = 1069`
`287 + 782 = 1069`
`386 + 683 = 1069`
`485 + 584 = 1069`
`980 + 89 = 1069`
So, the answer here would be `5`.
**rules**
As you can see we count every pair once: `{188,881}` is the same as `{881,188}`.
If a number cannot be expressed as such, your program should return `0`.
Your program should take as `input` a `positive integer` and return an `integer`.
**test cases**
```
1 -> 0
2 -> 1 (this is 1 + 1 = 2)
22 -> 2
101 -> 1 ( this is 100 + 001 = 100 + 1 = 101 )
132 -> 4
8547 -> 20
49886 -> 0
955548 -> 113
1100000 -> 450
```
This is `CodeGolf`! The shortest code in bytes, wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
rHDṚḌ+Ʋ€ċ
```
A monadic Link that accepts a positive integer and yields the number of valid pairs distinct up to reversing
**[Try it online!](https://tio.run/##AR8A4P9qZWxsef//ckhE4bma4biMK8ay4oKsxIv///8xMDY5 "Jelly – Try It Online")**
### How?
```
rHDṚḌ+Ʋ€ċ - Link: positive integer, N
H - halve {N} -> N/2
r - {N} inclusive range {that} -> [N, N-1, ..., floor(N/2)]
€ - for each such "potential larger of the pair"*, X:
∆≤ - last four links as a monad - f(X):
D - convert {X} to decimal digits
·πö - reverse
Ḍ - convert from decimal digits
+ - add {X}
ċ - count occurrences of {N}
```
\* Note: while odd \$N\$ *do* include one "potential larger of the pair" that *would not be* the larger of the pair (\$X=\lfloor \frac{N}{2} \rfloor\$), that value can *never* work. This is because \$N=\lfloor \frac{N}{2} \rfloor + \lceil \frac{N}{2} \rceil\$ and so \$\text{reverse}(X) - X = 1\$ but this isn't a multiple of \$9\$. (Thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for simplifying my explanation!)
[Answer]
# [R](https://www.r-project.org), 70 bytes
```
\(x)sum(sapply(x:(x/2),\(z)z%/%(b=10^(0:log10(z)))%%10%*%rev(b)+z)==x)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxBCsIwEABfE9jV1WZjUpNCrr6iCFaMlxZLayXmK16i4KP8jYI9DQzMPJ5DfgX_nq5hZT-7GiKOUwfjoe_bO8QKYqGQakiYRCGg8Sz3IKv2cmb5k4hCsBQLMZxu0OAyofcR55uaL0dgUqQUsWTijVqzLB1Zo7eknbUlOWOMtkhhLnP-8ws)
More or less an R translation of [@JonathanAllan’s Jelly answer](https://codegolf.stackexchange.com/a/269383/42248), so be sure to upvote that one too!
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `s`, 7 bytes
```
½⌊z-ᵛṁ=
```
[Try it Online!](https://vyxal.github.io/latest.html#WyJzIiwiIiwiwr3ijIp6LeG1m+G5gT0iLCIiLCI4NTQ3IiwiMy40LjEiXQ==)
Port of [Jelly answer](https://codegolf.stackexchange.com/a/269383/106959)
-2 bytes thanks to [@pacman256](https://codegolf.stackexchange.com/users/96266/pacman256)
```
½⌊z-ᵛṁ=­⁡​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁡​‎‏​⁢⁠⁡‌­
- ## ‎⁡n -
½⌊z ## ‎⁢[0 .. floor(N / 2)]
ᵛṁ ## ‎⁣for every element n, n + mirror(n)
= ## ‎⁤equals to itself? (vectorized)
## ‎⁢⁡The flag -s counts every Truthy values.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
/ec2m+s_`
```
[Try it online!](https://tio.run/##K6gsyfj/Xz812ShXuzg@4f9/QwMzSwA "Pyth – Try It Online")
### Explanation
```
# implicitly assign Q = eval(input())
/ec2m+s_`ddQQ # implicitly add ddQQ
m Q # map lambda d over range(Q)
_`d # reverse string(d)
s # convert back to integer
+ d # add d
c2 # chop list into 2 parts of equal length
e # take the second part
/ Q # count instances of Q
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~16~~ 15 bytes
```
NθIΣE⮌…·⊘θθ⁼κ⮌ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RCO4NFfDN7FAIyi1LLWoOFXDMy85p7Q4syw1KDEvPVXDIzGnLDUFqElHoVATSLgWlibmFGtk6yjANGRqgoH1//@GBob/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ First input as a number
…· Inclusive range from
θ Input number
‚äò Halved
θ To input number
‚Æå Reversed
E Map over values
κ Current index
⁼ Equals
ι Current value
‚Æå Reversed
Σ Take the sum
I Cast to string
Implicitly print
```
Reversing the range means the value plus index always equals the input number, so we just need to check that the latter is the reverse of the former.
[Answer]
# [Python 3](https://docs.python.org/3/), 56 bytes
```
lambda x:sum(i>=x-i==int(str(i)[::-1])for i in range(x))
```
[Try it online!](https://tio.run/##VYq9DsIgEIB3n@LGu6GJtKCUBF9EHTCKXmJpQzHBp0ddTG78fpZ3ecxpaNHDqT3DdLkGqG59TcgHXzv2nlPBtWRkOjrXqTPFOQMDJ8gh3W9YidqSfxdGVES0@VMvSaLaylkNsluj90Lo0dqdMKMxRtuvah8 "Python 3 – Try It Online")
or [53 bytes Python2 by Fmbalbuena](https://tio.run/##VYpLCsIwEED3nmKWM4uCaRNNA/EiKjSi0QGbllghPX3UjTDL95nX5TGltkYPp/oM4@UaoLjXe0Q@@NKw95wWHHg4OteoM8UpAwMnyCHdb1iI6px/C0ZURLT5UytJotrKWXWyW6P3Quje2p0wvTFG26@qHw)
# [JavaScript (Node.js)](https://nodejs.org), 59 bytes
```
x=>(g=t=>t&&g(t-1)+!([...x-t+''].reverse().join``^t))(x>>1)
```
[Try it online!](https://tio.run/##bctNCsIwEEDhvbdw085QMjj@UDfJRURpqWloKYkkQ8nto2vJ9uO9ddzHNMXlI8qHty2zLlkbcFq0kaZxIIqxO8KDiLKSrm2fFO1uY7KAtIbFD8NLECEbw1im4FPYLG3BAczAiHj4s3PNasin2s6XWnu/Xfsfly8 "JavaScript (Node.js) – Try It Online")
-1 Byte from Arnauld
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 40 35 bytes ([SBCS](https://github.com/abrudz/SBCS))
```
{+/⍵=10⊥¨(⌽+⊢)¨10⊥⍣¯1¨¯1+(⌊⍵÷2)+⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1pb/1HvVltDg0ddSw@t0HjUs1f7UdcizUMrwCKPehcfWm94aAWQ0AbKdQGVHt5upKn9qHczkFn73@1R2wSKTOB61DcVaIabgiGcZYRgIZiGBggFhsYIcQtTE3M4x8TSwsIMzrM0NTU1sUDoMjQAgf8A "APL (Dyalog Unicode) – Try It Online")
37 **32** with `‚éïIO‚Üê0`:
```
{+/⍵=10⊥¨(⌽+⊢)¨10⊥⍣¯1¨(⌊⍵÷2)+⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6u19R/1brU1NHjUtfTQCo1HPXu1H3Ut0jy0AizyqHfxofWGYPEuoLLD2400tR/1bgYya/@7AfWTrZsL6AKgfjcFQzjLCMFCMA0NEAoMjRHiFqYm5nCOiaWFhRmcZ2lqampigdBlaAAC/wE "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 19 bytes
```
/+=+⋕∵⇌°⋕.-+1⇡⌊÷2..
```
[Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAgLys9K-KLleKIteKHjMKw4ouVLi0rMeKHoeKMisO3Mi4uCgpmIDEKZiAyCmYgMjIKZiAxMDEKZiAxMzIKZiA4NTQ3CmYgNDk4ODYKIyBmIDk1NTU0OAojIGYgMTEwMDAwMCAjbWlnaHQgdGFrZSBhIGZldyBzZWNvbmRzCg==)
```
/+=+⋕∵⇌°⋕.-+1⇡⌊÷2..
.. # duplicate input twice
‚åä√∑2 # halve and floor
‚á° # range
+1 # increment
- # subtract from input
. # duplicate
°⋕ # unparse (convert to array of boxed strings)
∵⇌ # reverse each
‚ãï # convert all to integers
+ # add reversed to non-reversed
= # where is it equal to input?
/+ # sum
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
;ŸDí+QO
```
[Try it online](https://tio.run/##yy9OTMpM/f/f@ugOl8NrtQP9//83NDCzBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCf@tj@5wObxWO9D/v87/aEMdIx0jIx1DA0MdQ2MjHQtTE3MdE0sLCzMdS1NTUxMLHUNDAxCIBQA).
**Explanation:**
```
; # Halve the (implicit) input-integer
≈∏ # Pop and push a list in the range [(implicit) input, floor(input/2)]
D # Duplicate this list
í # Reverse each inner value in the copy
+ # Add the values at the same positions in the lists together
Q # Check for each whether it equals the (implicit) input
O # Sum the amount of truthy values
# (which is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 bytes
```
->x{(x/2..x).count{x==_1+_1.digits.join.to_i}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY9NCsJADIX3OUXAjUU7JmNHp4v2IiLFv-q4sGKnUCmexE0RPYYH8TaOTjUkvEDyvZDr_VQtz-0tTx6VzUP9EmFaN_16JIWoA7EqqoNt6iTJeJCxWJutsaXYF-YgbJGZy6WjnjOmSTwEHvbCFAnkVxn7dmdKdMk4cJWgDED6ocRfABP_9vEPEDmE6AP53neMAfDYW0SgVTT1bgRRrPWkux8rpSLtTXkM7BxceEgRzMVmsdo1R8xnGc-7J9rW6xs)
[Answer]
# [Zsh](https://www.zsh.org/), 48 bytes
```
for ((i=$1;i-->$1/2;c+=`rev<<<$i`+i==$1)):
<<<$c
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3DdLyixQ0NDJtVQytM3V17VQM9Y2sk7VtE4pSy2xsbFQyE7QzbYGSmppWXCB-MkQfVPvSaENjo1goBwA)
Terribly slow, because to reverse a string in Zsh you have to spawn a process!
[Answer]
# [Perl 5](https://www.perl.org/), 48 bytes (30 bytes w/o args or return)
```
($x,$n)=(0,@_);$x+=$_+reverse==$n for$n/2..$n;$x
```
[Try it online!](https://tio.run/##RY/tboIwFIb/cxVvTA0QG0aVOpQ08z62xUCoH1GraYVhjNfOWulcf73nOec8J71IfeS9aSocDrj3EekoUbGIUrpaxwXpJoKsJ1q2UhspBFHYnDVRb9MkIcq2@0cQWIIoAD4ZRfpNXZpSMJ9snA6RpeyF2czy7I/PFxR8KHKevdsN78kWeT5/WRec8yy3Djbzmyx1z5q4G4lxt/R0Q0RKvaUgsrvEEFiRdTE0iJbGAvtVN@HgRe/VdYORak6V1BjnNczu3Bxr7MpWYsxr/JQ3kyQJxuZLjdxd4N/va5sgxNP/BMAHwvMh9MUSxh8Kq7IusN23Ui2f9r0yV1nWIR2WH0H/Cw "Perl 5 – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 80 bytes
```
f(k)=‚àë_{n=.5k}^k0^{(k-n-‚àë_{d=0}^n10^{floor(logn)-d}mod(floor(n/10^d),10))^2}
```
[Try It On Desmos!](https://www.desmos.com/calculator/0fsrpn47bg)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/ewf3fokdys)
[Answer]
# [Scala 3](https://www.scala-lang.org/), 53 bytes
```
x=>(x/2 to x).count{i=>i+i.toString.reverse.toInt==x}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZU-7TsMwFN37FVedbJGGpE1ap5IjMSIBC4KlqoSbOsUotZHjlKCq_8DO0oUufFH_hpsHUy37Puxzzj3-PpWZKMTkdzEcafMhrB4uzy9m9SYzB_dCadgPANYyhy02RNhNOYcba8Xn4tFZpTdLOocnrRzwFgmwEwVkptLuWRRq_VBtV9Iih9xqx1MMFJE_lctH7BzXPCX19RicgZr6LWuveKqulO9Mp-9buUMBiReNAq8PPfnrf5juRqDsnSodCYNp4kHowRg3njDAOpxgxeJo5kGUMDb1IInjOGL4EgbNoq33XsrPjZUieyXYA0_hHY24QpOLbzUAShvuYdD7Oh67_Ac)
]
|
[Question]
[
# Objective
Generate the original scrambled list, from the movements that an [Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) would do to sort it.
The original list will have all numbers from `0` to `N-1`(inclusive) where `N` is the size of the input.
# Input
A list containing the necessary moves to sort the list. Each value represents the amount of slots displaced by the original (scrambled) number to be in his right position , keep in mind that this process is from the left to the right.
The value at (0-indexed) position `i` in the input list will be between `0` and `i` inclusive.
You don't need to handle invalid inputs, any behaviour is acceptable in this case (crash, infinite loop, etc).
# Output
The scrambled list
### Step-by-step to generate the moves
```
Scrambled List | Moves to sort
[4,0,2,1,3,5] | [0, , , , , ] #4 stay in place
[**4,**0,2,1,3,5] | [0,1, , , , ] #0 is moved 1 slot to the left
[**0,4**,2,1,3,5] | [0,1,1, , , ] #2 is moved 1 slot
[**0,2,4,**1,3,5] | [0,1,1,2, , ] #1 is moved 2 slot
[**0,1,2,4,**3,5] | [0,1,1,2,1, ] #3 is moved 1 slot
[**0,1,2,3,4,**5] | [0,1,1,2,1,0] #5 is in the right place already
[**0,1,2,3,4,5**]
```
So, for the input `[0,1,1,2,1,0]` your program need to output `[4,0,2,1,3,5]`.
Keep in mind that the movements aren't to the position in the (final) sorted list, but in the sorted segment(the bolded section)
# Test Cases
```
[0,0,0] -> [0,1,2]
[0,1,0,1] -> [1,0,3,2]
[0,0,0,0,0,5] -> [1,2,3,4,5,0]
[0,1,2,3] -> [3,2,1,0]
[0,1,1,1] -> [3,0,1,2]
[0,1,1,2,1,0] -> [4,0,2,1,3,5]
```
# Winning
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
L!_UÆ¡$œ?J’U
```
[Try it online!](https://tio.run/nexus/jelly#@@@jGB96uO3QQpWjk@29HjXMDP1/uP1R05r//6OjDXSAMFYHSBsCWYZgFgyaQsWNdIyhLEOoCkOwKFBHbCwA "Jelly – TIO Nexus")
## Explanation
We can basically see the two lists (the input and the output) as encoding an integer; the input encodes an integer in factorial base, and the output encodes an integer as a permutation. Luckily, Jelly has builtins that are already very close to both of these encodings, so it's simply a matter of writing small pieces of code to convert to an integer, then back to the other encoding.
```
L!_UÆ¡$œ?J’U
U Reverse {the input}
Æ¡ and convert from base factorial to integer;
_ $ subtract that from
L! the factorial of the length of {the input};
œ? then take the nth permutation of
J [1,2,...,l], where l is the length of {the input},
’ subtract 1 from every elevent,
U and reverse it
```
In the case of base factorial, we can observe that the first element of the list must be 0, the second can be 0 or 1, the third must be 0/1/2, and so on. Thus, we have to reverse the input in order to get its elements into the normal writing order for base conversion.
Additionally, for the relative orders of the factorial conversion and the permutation conversion to match up with the operation that insertion sort uses, we need to make two adjustments: reversing the sequence of the permutations, and reversing the order of the output list. Reversing the output list is easy enough, needing only a `U` at the end of the program. To reverse the sequence of permutations, we subtract from the factorial of the input length (this works because the base factorial produces a number in the range 0 to (length!-1), whereas the permutations are numbered by Jelly from 1 to length!, producing an implicit off-by-one that cancels out the off-by-one that you normally get when subtracting a permutation index from a factorial).
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes, in collaboration with @JonathanAllan
```
UÆ¡Nœ?J’U
```
This version of the program is very similar, but uses a different method of reversing the sequence of permutations; simply negating the input with `N` is enough to make `œ?` treat the order in reverse. Apart from that, it works identically to the previous program.
[Try it online!](https://tio.run/nexus/jelly#@x96uO3QQr@jk@29HjXMDP1/uP1R05r//6OjDXSAMFYHSBsCWYZgFgyaQsWNdIyhLEOoCkOwKFBHbCwA)
[Answer]
# Mathematica, 92 bytes
```
Permute[Range[l=Length@#]-1,(c=Cycles@{#}&)@{}©##&@@c[i-0~Range~#[[i]]]~Table~{i,l,1,-1}]&
```
Pure function taking a list of nonnegative integers as input and returning a list of nonnegative integers. The above code contains a `©`, which is incorrect: it's a placeholder for the 3-byte symbol U+F3DE, which Mathematica represents by a circle with a dot in it, and which represents composition of permutations.
`c=Cycles@{#}&` defines a function that converts a list of integers into a `Cycles` object representing a permutation; for example, `c[{3,4}]` is the transposition swapping elements 3 and 4 of a list. `c[i-0~Range~#[[i]]]~Table~{i,l,1,-1}]` takes the input list and generates the permutations necessary to undo the insertion sort. Then `c@{}©##&@@` composes all of these permutations together, starting with the identity permutation `c@{}`. Finally, `Permute[Range[l=Length@#]-1,...]` applies this permutation to the 0-indexed list of appropriate length.
[Answer]
# Python 2, 79 68 bytes
Thanks to Krazor for saving 10 bytes
Thanks to TuukkaX for saving 1 byte
```
a=input();b=range(len(a));print[b.pop(j-a[j])for j in b[::-1]][::-1]
```
Works by generating the moves in reverse
[Answer]
## JavaScript (ES6), ~~69~~ ~~65~~ 63 bytes
```
a=>a.reverse(b=[...a.keys()]).map(o=>+b.splice(~o,1)).reverse()
```
Annoyingly both input and output are in the wrong order. Edit: Saved 4 bytes thanks to @Arnauld. Saved 2 bytes thanks to @ETHproductions.
[Answer]
## JavaScript (ES6), ~~73~~ 71 bytes
*Saved 2 bytes thanks to ETHproductions*
```
m=>(a=m.map((_,i)=>j=i)).map(_=>a.splice(j,0,+a.splice(j-m[j--],1)))&&a
```
### Test cases
```
let f =
m=>(a=m.map((_,i)=>j=i)).map(_=>a.splice(j,0,+a.splice(j-m[j--],1)))&&a
console.log(JSON.stringify(f([0,0,0]))); // -> [0,1,2]
console.log(JSON.stringify(f([0,1,0,1]))); // -> [1,0,3,2]
console.log(JSON.stringify(f([0,0,0,0,0,5]))); // -> [1,2,3,4,5,0]
console.log(JSON.stringify(f([0,1,2,3]))); // -> [3,2,1,0]
console.log(JSON.stringify(f([0,1,1,1]))); // -> [3,0,1,2]
console.log(JSON.stringify(f([0,1,1,2,1,0]))); // -> [4,0,2,1,3,5]
```
[Answer]
# [Haskell](https://www.haskell.org/), 85 bytes
```
f x|n<-length x-1=reverse x#[n,n-1..0]
(n:r)#l=r#(take n l++drop(n+1)l)++[l!!n]
x#l=x
```
[Try it online!](https://tio.run/nexus/haskell#DcpBCsMgEEDRfU4xwS6UiUG7LPUk4iKQSRtqp2EqxUXvbuTzdr9tUP98t5n4UZ5QrQ9CP5IvQVWRJ7Z@nl0aNN/EqBxE6bK8CBgy4iqfQzN6kw1izOPIaah9qu297AwBDtm5wAU2iG7yvWvnUjsB "Haskell – TIO Nexus") Example usage: `f [0,1,1,2,1,0]` yields `[4,0,2,1,3,5]`.
`f x` calls the function `#` with list `x` reversed and a list `[length x - 1, length x - 2, ... , 0]`. `(n:r)#l` performs the reverse insertion sort by recursively taking the `n`th element out of `l`, where `l!!n` yields the `n`th element and `take n l++drop(n+1)l` yields the list `l` with the `n`th element removed.
[Answer]
# perl, 61 bytes
```
@o=@p=0..@ARGV-1;splice@o,$_,0,splice@o,$_-pop,1for reverse@p
```
Output ends up in array @o. Example with input array as command line arguments:
```
perl -le'@o=@p=0..@ARGV-1;splice@o,$_,0,splice@o,$_-pop,1for reverse@p;print@o' 0 1 1 2 1 0
402135
```
[Answer]
## Ruby, 49 bytes
```
->l{(w=l.size).times{l.insert(l.shift+w-=1,w)};l}
```
Performs the "reverse insertion" in place inside the list, starting with the largest number.
]
|
[Question]
[
# The Challenge
For this challenge, you are supposed to determine if a given number is in the Cantor set. So first, let's define the Cantor set.
First, start with the numbers between 0 and 1. Any numbers outside this range are not in the Cantor set. Now, let's divide the numbers into three equal parts: [0,1/3], [1/3,2/3], [2/3, 1]. Any numbers not inside the ranges of the first and last parts are not in the Cantor set. Now, you repeat this process for the segments [0,1/3] and [2/3, 1]. Then you repeat on what is leftover. You keep on doing this forever. In the end, all numbers that are remaining are in the Cantor set. Here is a diagram of the first six iterations:

---
# Input
Two integer `x` and `y`.
`0 < y < 2^15`
`0 <= x <= y`
The greatest common denominator of `x` and `y` is 1, unless `x == 0`.
---
# Output
Truthy if `x/y` is in the Cantor set.
Falsy if `x/y` is not in the Cantor set.
---
# Examples
Now, let's see some examples of numbers that are in the Cantor set.
```
1/3 -> true
```
It is on a boundary, and boundaries are never removed.
```
1/4 -> true
```
`1/4` is never in the middle third of a segment, though it is never on the boundary either. If you follow it's path, you will actually find that it alternates between being in the first and last thirds of a section.
```
1/13 -> true
```
`1/13` alternates between the first, first, and last sections.
```
1/5 -> false
```
`1/5` falls into the first empty block of the third row in the above diagram, between 1/9 and 2/9.
Other test cases:
```
0/4 -> true
3/10 -> true
3/4 -> true
10/13 -> true
1/1 -> true
12/19 -> false
5/17 -> false
3/5 -> false
1/7 -> false
1/2 -> false
```
You can try other numbers with this snippet:
```
function isCantor(t,r){var n=new Set;if(0>r)return isCantor(-t,-r);if(0==r)return!1;if(0>t||t>r)return!1;for(;;){if(t%r===0)return!0;if(1===Math.floor(t/r))return!1;if(n.has(t))return!0;n.add(t),t=t%r*3}}$("#test").click(function(){var t=parseInt($("#x").val()),r=parseInt($("#y").val());if(isNaN(t)||isNaN(r)||0==r)return void $("#result").text("Invalid input");var n=isCantor(t,r),i=(n?"I":"Not i")+"n the Cantor set.";$("#result").text(i)});
```
```
input{width:30px}button{margin-left:7px}
```
```
<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><input id=x>/<input id=y><button id=test>Test</button><p id=result>
```
---
# Objective
The person with the least bytes wins.
[Answer]
# Mathematica, 54 bytes
```
If[Last@#===1,Most@#,#]&@RealDigits[#,3][[1]]~FreeQ~1&
```
Unnamed function taking a fraction `x/y` as input, where `y > 0` and `0 ≤ x ≤ y`, and returning `True` or `False`.
A real number between 0 and 1 is in the Cantor set precisely when none of the digits in its base-3 expansion equals 1; the exception is that a fraction whose denominator is a power of 3 (whose base-3 expansion therefore terminates) is allowed to end in a 1.
`RealDigits[#,3][[1]]` gives all of the digits in the base-3 expansion of the fractional input `#`, in a form like `{1, 0, 2, {0, 1, 0, 2}}`: the last list is the periodic part of the expansion, while the integers beforehand are the digits before the periodicity starts. If the base-3 expansion is periodic right away, the output is like `{{0, 1, 0, 2}}`; if the base-3 expansion terminates, the form is like `{1, 0, 2}`.
So we want to check, using `~FreeQ~1`, whether the list is free of `1`s or not. However, because of the terminating expansion thing, we want to delete the last element of the list if it equals `1`; that's what `If[Last@#===1,Most@#,#]` accomplishes. (The `===` is needed to compare a potential list with `1`: `==` alone remains unevaluated in that situation.)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~61~~ ~~59~~ 58 bytes
```
f(x,y,i){for(i=y;i--&&x<y;)x=(y-x<x?y-x:x)*3;return x<=y;}
```
Exploits the symmetry of the Cantor set. Breaks after `y` iterations to avoid an infinite loop.
[Try it online!](https://tio.run/nexus/c-gcc#PVDtbsMgDPwdnsJqlQpasqZfmlbI9iBbf0wj0SytpEpTyTTKs2cmzSYdxj7fgWGoJOmgUXVV3UgsgsEsWyzIBqOokCEjS28cj6SWO9OU7a3xQJZ1/TBH//VzcyXYa@uwfvp@FQJ9C/R@ggI6yDXATkdsON0wtswcHgwDejPqw6TfP4RxmxQvvJ51tHDcRv1oOH@ilwo6kcQKmU14epDIx@QGECxc8V7WFRCs/9IlcWe1Gm3JpWFnJWepW6fuCKn78DPNg@NJ8zgx8r/8V0oZkfR8y/T@3IheDL8 "C (gcc) – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ ~~17~~ ~~16~~ 15 bytes
```
,ạµ%⁹×3µÐĿ:⁹Ḅ3ḟ
```
Prints **3** for truthy, nothing for falsy.
[Try it online!](https://tio.run/nexus/jelly#@6/zcNfCQ1tVHzXuPDzd@NDWwxOO7LcCch7uaDF@uGP@f2ulw8v1HzWtcf//P9pQxzhWRwFImUAoQyjXFEQZQESNdQwNIDREkQFclSGYMtIxtAQxTHUMzSHqTCHS5hDKKBYA "Jelly – TIO Nexus")
### Background
A well-known property of the Cantor set is that it contains precisely those numbers between **0** and **1** that can be written without **1**'s in their ternary expansion.
Note that some numbers – precisely the right edges of the closed intervals involved in the set's construction – can be written either with a single (trailing) **1** or with an infinite amount of trailing **2**'s. For example, **1 = 13 = 0.22222…3** and **1/3 = 0.13 = 0.022222…3**, just as **0.510 = 0.499999…10**.
To avoid special-casing the right edges, we can check for **1**'s is the shortest decimal expansion in both **x/y** and **1 - x/y = (y - x)/y**, where **x/y** is a right edge iff **(y - x)/y** is a left edge. If at least one of them contains no **1**'s, **x/y** belongs to the Cantor set.
### How it works
```
,ạµ%⁹×3µÐĿ:⁹Ḅ3ḟ Main link. Left argument: x. Right argument: y
ạ Absolute difference; yield y - x.
, Pair; yield [x, y - x].
µ Begin a new, monadic chain with argument [a, b] := [x, y - x].
µ ÐĿ Repeatedly execute the links in between until the results are no
longer unique, updating a and b after each execution. Return the
array of all unique results.
%⁹ Compute [a % y, b % y].
×3 Compute [3(a % y), 3(b % y)].
This yields all unique dividends of the long division of x by y in
base 3.
:⁹ Divide all dividends by y to get the corresponding ternary digits.
Ḅ Unbinary; turn [1, 1] into 3, other pairs into other numbers.
3ḟ Remove all occurrences of the resulting numbers from [3], leaving
an empty array if and only if one pair [a, b] is equal to [1, 1].
```
[Answer]
# JavaScript (ES6), 65 ~~67~~
**Edit** 2 bytes saved thx @Luke
```
n=>d=>(z=>{for(q=0;~-q*n*!z[n];n=n%d*3)z[n]=1,q=n/d|0})([])|q!=1|!n
```
*Less golfed*
```
n=>d=>{
z = []; // to check for repeating partial result -> periodic number
for(q = 0; q != 1 && n != 0 && !z[n]; )
z[n] = 1,
q = n / d | 0,
n = n % d * 3
return q!=1 | n==0
}
```
**Test**
```
f=
n=>d=>(z=>{for(q=0;~-q*n*!z[n=n%d*3];q=n/d|0)z[n]=1})([])|q!=1|!n
console.log(
'Truthy: 1/3 1/4 1/13 0/4 3/10 3/4 10/13 1/1\nFalsey: 1/5 12/19 5/17 3/5 1/7 1/2'.replace(/(\d+).(\d+)/g,(a,x,y)=>a+':'+f(x)(y))
)
```
[Answer]
## JavaScript (ES6), 55 bytes
```
y=>f=(x,z,n=~y,q=x/y|0)=>n?!z|!q&&f(x%y*3,z|q==1,n+1):1
```
Use by currying in the denominator first and the numerator second. The standard form is a byte longer:
```
f=(x,y,z,n=~y,q=x/y|0)=>n?!z|!q&&f(x%y*3,y,z|q==1,n+1):1
```
### Explanation
If a fraction is not in the Cantor set, it must fall into one of the middle sections at some point; therefore, its representation in base 3 must contain a 1 followed at some point by a non-zero digit. That's how this works:
* `z` keeps track of whether we've found a 1.
* `q` is the current digit in base 3.
* `!z|!q` is true if `z` is false (we have not found a 1) or `q` is false (the current digit is 0).
If `n` runs down to zero before we find a non-zero digit somewhere after a 1, the fraction is in the Cantor set and we return `1`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 62 bytes
```
dc -e3o9d$2^$1*$2/p|tr -cd 012|grep -P "1(?!(0{$2,}|2{$2,})$)"
```
[Try it online!](https://tio.run/nexus/bash#@5@SrKCbapxvmaJiFKdiqKVipF9QU1KkoJucomBgaFSTXpRaoKAboKBkqGGvqGFQrWKkU1tjBKY0VTSV/v//b/jf0BgA "Bash – TIO Nexus")
Pass it two integer arguments with arg1 <= arg2 and 0 < arg2.
The output is returned in the exit code (0 for falsy, 1 for truthy), as allowed by [PPCG I/O methods](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5330#5330).
I suspect the regex can be golfed further, maybe even eliminating the tr command in favor of using grep -z, but this is the shortest I've been able to come up with. (Unfortunately, grep -z is incompatible with grep -P, and the -P option to get perl-style regexes is required for the ?! syntax.)
Testbed program and output:
```
for x in '1 3' '1 4' '1 13' '1 5' '0 4' '3 10' '3 4' '10 13' '1 1' '12 19' '5 17' '3 5' '1 7' '1 2'
do
printf %-6s "$x "
./cantor $x >/dev/null && echo F || echo T
done
1 3 T
1 4 T
1 13 T
1 5 F
0 4 T
3 10 T
3 4 T
10 13 T
1 1 T
12 19 F
5 17 F
3 5 F
1 7 F
1 2 F
```
---
**Explanation**
dc part (the arguments are x and y):
```
3o Set output base to 3.
9 Push 9 on the stack.
d Duplicate the top of the stack. (The extra 9 on the stack isn't actually used, but I need some delimiter in the code here so that the 9 doesn't run into the number coming up next. If I used a space as a no-op, then I'd need to quote it for the shell, adding an extra character.)
$2^ Raise 9 to the y power. This number in base 3 is 1 followed by 2y 0's.
$1*$2/ Multiply the base-3 number 10....0 (with 2y 0's in it) by x and then divide by y (truncating). This computes 2y digits (after an implied ternary point) of x/y. That's enough digits so that the repeating part of the rational number is there at least twice.
p Print the result, piping it to tr.
```
tr and grep part:
A minor issue is that, although dc handles arbitrarily large integers, when dc prints a large number, it will break it up into 69-character lines, with each line except the last ending with a backslash, and with a newline after each line.
The tr command deletes any backslashes and newlines. This leaves just a single line.
The grep command then uses a perl-style regex (-P option, which is a GNU extension). The regex matches if the line contains a 1 not followed by at least y 0's or at least y 2's which then end the string.
This is exactly what's needed to identify x/y as not being in the Cantor set, because the repeating part of the base-3 representation of the rational number x/y can be viewed as starting at digit #y+1 after the ternary point, and is at most y digits long.
[Answer]
## CJam (19 bytes)
```
{_@3@#*\/3b0-W<1&!}
```
[Online test suite](http://cjam.aditsu.net/#code=q%22%2Ftf%22%22%2010%22er%22-%3Erueals%22-~%5D3%2F%7B~%40%40%0A%0A%7B_%403%40%23*%5C%2F3b0-W%3C1%26!%7D%0A%0A~%3D%7D%25&input=0%2F4%20-%3E%20true%0A3%2F10%20-%3E%20true%0A3%2F4%20-%3E%20true%0A10%2F13%20-%3E%20true%0A1%2F1%20-%3E%20true%0A12%2F19%20-%3E%20false%0A5%2F17%20-%3E%20false%0A3%2F5%20-%3E%20false%0A1%2F7%20-%3E%20false%0A1%2F2%20-%3E%20false%0A1%2F3%20-%3E%20true%0A2%2F3%20-%3E%20true)
This is an anonymous block (function) which takes two arguments on the stack and leaves `0` or `1` on the stack. It works by base converting the fraction `x/y` into `y` base `3` digits and returning true iff they contain no `1` or the only `1` is part of a suffix `1 0 0 0 ...`.
```
{ e# Begin a block
_@3@#*\/3b e# Base conversion
0-W< e# Remove all zeros and the final non-zero digit
1&! e# True iff no 1s are left
}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
gu*3hS,G-QGQE0
```
Based on my C solution. `y` on first input line, `x` on second.
```
Q = y
u QE G = x
loop y times
*3 x = 3 *
hS,G min(x,
-QG y-x)
g 0 return x >= 0
```
If `x/y` is within the Cantor set, `x` stays between `0` and `y`. Otherwise, `x` becomes greater than `y` at one point, then diverges to negative infinity in the remaining iterations.
[Try it online!](https://tio.run/nexus/pyth#@59eqmWcEazjrhvoHuhq8P@/oTGXoQEA "Pyth – TIO Nexus")
[Answer]
## Batch, 91 bytes
```
@set/ai=%3+1,n=%1*3%%%2,f=%1*3/%2%%2,f^|=j=!((%2-i)*n)
@if %f%==0 %0 %n% %2 %i%
@echo %j%
```
Tests the first `y-1` base 3 digits of `x/y`. `i` is the count of digits tested. `n` is the next value of `x`. `j` is true if `n` reaches zero (because the expansion terminates) or we have tested `y-1` digits without finding a `1`. `f` is true if `j` is true or if the next digit is a `1`, at which point we stop looping and output `j`.
]
|
[Question]
[
# Guide the Alphabet
Given an array of directions, where the directions are defined as follows:
```
NW N NE
W . E
SW S SE
```
Or as indexes (you may use these indices for directions instead of the strings above):
```
0 1 2
3 . 4
5 6 7
```
You may choose either format, supporting both is not required by the challenge. Generate the corresponding alphabet String that represents the drawn path, starting with A. The number of directions will never exceed 25, meaning that it can never go past `Z`, so you don't have to handle this scenario. No other input formats will be accepted unless you can explain why these formats do not work due to a language limitation. This is easier to explain using a verbosely worked out example.
---
So, lets look at a quick example:
```
[E,SE,N,S,S,S,NW,W,N] or [4,7,1,6,6,6,0,3,1]
```
Always start with A.
```
A
```
Go East to B.
```
A-B
```
Go South East to C.
```
A-B
\
C
```
Go North to D.
```
A-B D
\|
C
```
Go back South to E, overwriting C.
```
A-B D
\|
E
```
Continue South for 2 cycles to both F and G.
```
A-B D
\|
E
|
F
|
G
```
Go North West to H.
```
A-B D
\|
E
|
H F
\|
G
```
Go West to I.
```
A-B D
\|
E
|
I-H F
\|
G
```
End to the North at point J.
```
A-B D
\|
J E
| |
I-H F
\|
G
```
---
The final value you would return is by reading the final graph left to right, top to bottom:
```
ABD
JE
IHF
G
```
Resulting in:
```
ABDJEIHFG
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins.
[Answer]
## JavaScript (ES6), ~~108~~ ~~107~~ ~~94~~ 87 bytes
*Saved a whopping 13 bytes, thanks to Titus!*
*Saved 7 more bytes, thanks to edc65!*
```
let f =
a=>[i=9,...a].map(d=>r[p+=(d+=d>3)*9-d%3*8-28]=(++i).toString(36),r=[],p=646)&&r.join``
console.log(f([4,7,1,6,6,6,0,3,1]));
```
### How it works
The formula `(d += d > 3) * 9 - d % 3 * 8 - 28` translates the directions `0..7` into the following offsets:
```
0 1 2 -28 -27 -26
3 x 4 --> -1 x +1
5 6 7 +26 +27 +28
```
We use these offsets to move the pointer `p` into the one-dimensional array `r` and write the letters at the resulting positions.
We iterate on `[i = 9, ...a]` rather than just `a` in order to insert the starting letter 'a'. Because we initialize `i` to `9` at the same time, we introduce a special offset of 54 (the result of the above formula for `d = 9`). After the first iteration, `p` equals `646 + 54 = 700`, which leaves just enough space to support up to 25 moves to North-West: `25 * -28 = -700`. That's why `p` is initialized to `646`.
Then we just have to join the array to get our final string. Undefined values in between letters are simply ignored by `join()`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~64~~ ~~58~~ ~~57~~ ~~50~~ ~~46~~ ~~40~~ ~~37~~ ~~36~~ ~~35~~ 30 bytes
```
O'!":<TUV '59-G)hYsIH$6#u64+c!
```
Try it at [MATL Online](https://matl.io/?code=O%27%21%22%3A%3CTUV+%2759-G%29hYsIH%246%23u64%2Bc%21&inputs=%5B4%2C7%2C1%2C6%2C6%2C6%2C0%2C3%2C1%5D&version=19.7.3)
**Explanation**
```
O % Push the number 0 to the stack
'!":<TUV ' % String literal
59- % Converts this string literal into [-26 -25 -1 1 25 26 27 -27]. These
% are deltas for the linear indexes into the matrix corresponding to each
% of the directions. Note that the -27 is at the end since a 0 index wraps
% around to the end
i) % Grab the input and use it to index into the delta array
h % Horizontally concatenate this with the 0 (our starting point)
Ys % Take the cumulative sum to get the absolute linear index (location) of
% each successive letter
IH$6#u % Find the index of the last (sorted) occurrence of each location
64+ % Add 64 to this index to create ASCII codes
c! % Convert to character, transpose, and display
```
[Answer]
# Octave, ~~145~~ ~~138~~ ~~131~~ ~~123~~ ~~105~~ ~~103~~ ~~90~~ ~~87~~ 85 bytes
```
@(a){[~,k]=unique(cumsum([1 fix((z=a+(a>3))/3);1 mod(z,3)]'-1),'rows');[k'+64 '']}{2}
```
[Try It Online](https://tio.run/#Ge58i)
Thanks to [Suever](https://codegolf.stackexchange.com/users/51939/suever) 2 bytes saved!
Previous answer 103 bytes:
```
@(a)[nonzeros(accumarray(cumsum([1 fix((z=a+(a>3))/3);1 mod(z,3)]'-1)+30,65:nnz(++a)+65,[],@max)')' '']
```
[Try It Online!](https://tio.run/#cAOXa)
First try 145 byts
```
@(a){[x y]=find(~impad(1,1,1));c=cumsum([0 0;([y x]-2)(++a,:)]);c=c-min(c)+1;n=nnz(a);[nonzeros(sparse(c(:,1),c(:,2),65:n+65,'unique')')' '']}{5}
```
Some Explanations
```
@(a){
[x y]=find([1 0 1]|[1;0;1]); %generate 2d coordinates corresponding to 1d input indices
XY = [y x]-2;
c=cumsum([0 0;XY(++a,:)]); %cumulative sum of coordinates to find position of characters
c=c-min(c)+1;n=nnz(a);
[nonzeros(sparse(c(:,1),c(:,2),65:n+65,'unique')')' ''] %using sparse matrix to place characters at specified positions
}{5}
```
[Answer]
## MATLAB, ~~87~~ 85 bytes
*saved 2 bytes thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)*
```
function a=f(s);i='()*BD\]^'-67;[~,a]=unique([0 cumsum(i(s+1))],'last');a=[a'+64,''];
```
[Answer]
# PHP, 93 bytes
Operating on a single array like [Kodos Johnson´s answer](https://codegolf.stackexchange.com/a/107969#107969).
But this has so many more ideas that I posted on my own.
```
for($r=[$c=A];""<$d=$argv[++$i];)$r[$p+=($d+=$d>3)*9-$d%3*8-28]=++$c;ksort($r);echo join($r);
```
takes numbers from command line arguments. Run with `-nr`.
**moving the cursor**
initial calculation:
```
$d+=$d>3; // if $d>3, add 1
$p+= ($d/3-1|0)*26 // add/subtract 26 for line change
+$d%3-1; // add/substract 1 for column change
```
golfing:
```
$d+=$d>3;$p+=($d/3-1|0)*27+$d%3-1; // +0: multiple of 3 instead of 26
$d+=$d>3;$p+=($d/3|0)*27-27+$d%3-1; // +1: distribute `line-1`
$d+=$d>3;$p+=($d/3)*27-$d%3/3*27-27+$d%3-1; // +8: distribute `|0`
$d+=$d>3;$p+=$d*9-$d%3*9-27+$d%3-1; // -8: `/3*27` -> `*9`
$d+=$d>3;$p+=$d*9-$d%3*8-28; // -7: combine duplicates
```
merging the assignments doesn´t save anything, but kind of improves readability:
```
for(init;input loop;$p=$d...)$d+=$d>3;
for(init;input loop;)$p=($d+=$d>3)...;
```
**breakdown**
```
for($r=[$c=A]; // init result, init letter
""<$d=$argv[++$i];) // loop through command line arguments
$r[
$p+=($d+=$d>3)*9-$d%3*8-28 // move cursor
]=++$c; // increment letter, plot
ksort($r); // sort result by index
echo join($r); // print result
```
[Answer]
## Python 2, ~~180 178~~ 176 bytes
```
def f(d,a=[[""]*26 for _ in[1]*26],x=0,y=0,j=66):
a[0][0]="A"
for i in d:y+=(i>4)-(i<3);x+=(`i`in'247')-(`i`in'035');a[y][x]=chr(j);j+=1
return"".join("".join(i)for i in a)
```
[Answer]
## PHP, 121 bytes
```
$r[0]=chr(65);for(;($n=$argv[1][$i])!=null;)$r[$c+=[-27,-26,-25,-1,1,25,26,27][$n]]=chr($i+++66);ksort($r);echo join($r);
```
This runs in the command line with the `-r` flag and takes a char array (string) of indices as an argument.
[Answer]
# R, 160 bytes
```
a=scan()
e=f=26
x=matrix(0,51,51)
x[e,f]="A"
for(i in a){g=function(q)grepl(q,i)
T=T+1
f=f-g("N")+g("S")
e=e-g("W")+g("E")
x[e,f]=LETTERS[T]}
cat(x[x>0],sep="")
```
]
|
[Question]
[
**Input:** Two integers n and k given in any form that is convenient for your code
**Output** A random non-decreasing sequence of k integers, each in the range 1 to n. The sample should be chosen uniformly from all non-decreasing sequences of k integers with integers in the range 1 to n.
The output can be in any reasonable format you find convenient.
You can use whatever pseudo-random generator your favorite library/language provides.
We can assume that the integers n,k > 0.
**Example**
Say n,k = 2. The non-decreasing sequences are
```
1,1
1,2
2,2
```
Each sequence should have probability 1/3 of being outputted.
**Restriction**
Your code should run in no more than a few seconds for k = 20 and n = 100.
**What doesn't work**
If you just sample each integer randomly from the range 1 to n and then sort the list you won't get a uniform distribution.
[Answer]
## Python, 89 bytes
```
from random import*
lambda n,k:[x-i for i,x in enumerate(sorted(sample(range(1,n+k),k)))]
```
Generating an *increasing* sequence rather than a *non-decreasing* one would be straightforward: this is just a random subset of `k` numbers between `1` and `n`, sorted.
But, we can convert an increasing sequence to a non-decreasing one by shrinking each gap between consecutive numbers by 1. So, a gap of 1 becomes a gap of 0, making equal numbers. To do so, decrease the `i`'th largest value by `i`
```
r[0], r[1], ..., r[n-1] => r[0]-0, r[1]-1, ..., r[n-1]-(n-1)
```
For the result to be from `1` to `n`, the input must be from `1` to `n+k-1`. This gives a bijection between non-decreasing sequences of numbers between `1` and `n`, to increasing sequences between `1` and `n+k-1`. The same bijection is used in the [stars and bars argument](https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)) for counting such sequences.
The code uses the python function `random.sample`, which takes `k` samples without replacement from the input list. Sorting it gives the increasing sequence.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 13 bytes
```
+<L.r¹£{¹L<-Ä
```
[Try it online!](http://05ab1e.tryitonline.net/#code=KzxMLnLCucKje8K5TDwtw4Q&input=MjAKMTAw)
**Explanation**
```
+<L # range [1 ... n+k-1]
.r # scramble order
¹£ # take k numbers
{ # sort
¹L<- # subtract from their 0-based index
Ä # absolute value
```
[Answer]
## Python, 87 bytes
```
from random import*
f=lambda n,k:k>random()*(n+k-1)and f(n,k-1)+[n]or k*[7]and f(n-1,k)
```
The probability that the maximum possible value `n` is included equals `k/(n+k-1)`. To include it, put it at the end of the list, and decrement the needed numbers remaining `k`. To exclude it, decrement the upper bound `n`. Then, recurse until no more values are needed (`k==0`).
Python's `random` doesn't seem to have a built-in for a Bernoulli variable: 1 with some probability, and 0 otherwise. So, this checks if a random value between 0 and 1 generated by `random` falls below `k/(n+k-1)`. Python 2 would the ratio as float division, so we instead multiply by the denominator: `k>random()*(n+k-1)`.
[Answer]
## JavaScript (Firefox 30+), 74 bytes
```
(n,k,i=0,j=k)=>[for(_ of Array(q=k+n-1))if(Math.random(++i)<k/q--)i-j+k--]
```
### Explanation
[xnor's excellent Python answer](https://codegolf.stackexchange.com/a/100198/42545) contains a very good summary of how/why the technique used here works. The first step is to create the range **[1, 2, ..., n + k - 1]**:
```
(n,k,i=0)=>[for(_ of Array(q=k+n-1))++i]
```
Next we need to take **k** random items from this range. To do this, we need to select each item with probability **s / q**, where **s** is the number of items still needed and **q** is the number of items left in the range. Since we're using an array comprehension, this is fairly easy:
```
(n,k,i=0)=>[for(_ of Array(q=k+n-1))if(Math.random(++i)<k/q--)k--&&i]
```
This gives us a uniformly distributed *increasing* sequence of numbers. This can be fixed by subtracting the number of items **j** that we have previously found:
```
(n,k,i=0,j=0)=>[for(_ of Array(q=k+n-1))if(Math.random(++i)<k/q--)k--&&i-j++]
```
Finally, by storing **k** in **j**, we can incorporate `k--` into the expression and save a few bytes:
```
(n,k,i=0,j=k)=>[for(_ of Array(q=k+n-1))if(Math.random(++i)<k/q--)i-j+k--]
```
[Answer]
# TI-BASIC, 53 Bytes
```
Prompt N,K
K→dim(L1
While K
If rand<K/(N+K-1
Then
N→L1(K
K-1→K
Else
N-1→N
End
End
L1
```
Follow's xnor's logic, with a small caveat. We could theoretically shave a byte by doing something like this:
```
K>rand(N+K-1
```
But rand( is reserved to create a list of random numbers, so we wouldn't be able to do the desired implicit multiplication to save a byte.
This should run decently fast on an 84+ per the restriction but I'll check to make sure when I can.
[Answer]
# [Actually](http://github.com/Mego/Seriously), ~~14~~ 12 bytes
This answer is based on [Emigna's 05AB1E answer](https://codegolf.stackexchange.com/a/100197/47581) and [the answers on this Math.SE question](https://math.stackexchange.com/q/28223/295310). Golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=OztyYStEUuKVmkhT4pmALQ&input=MTAwCjIw)
```
;;ra+DR╚HS♀-
```
**Ungolfing**
```
Implicit input n, then k.
;; Duplicate k twice.
r Push range [0...k] for later.
a Invert the stack. Stack: n, k, k, [0...k]
+DR Push the range [1..n+k-1].
╚ Shuffle the range. Stack: shuffled_range, k, [0...k]
H Push the first k elements of shuffled_range. Call this increasing.
S Sort increasing so the elements are actually increasing.
♀- Subtract each element of [0...k] from each element of increasing.
This gives us our non-decreasing sequence.
Implicit return.
```
[Answer]
# PHP, ~~77~~ ~~75~~ 73 bytes
```
foreach(array_rand(range(2,$argv[1]+$k=$argv[2]),$k)as$v)echo$v+1-$i++,_;
```
Run like this:
```
php -r 'foreach(array_rand(range(2,$argv[1]+$k=$argv[2]),$k)as$v)echo$v+1-$i++,_;' -- 10 5 2>/dev/null;echo
> 1_4_6_9_9_
```
# Explanation
```
foreach( # Iterate over...
array_rand( # a (sorted) random number of items from...
range( # an array with items...
2, # from 2
$argv[1]+$k=$argv[2] # to n + k (set arg 2 to $k)
),
$k # Take k number of items (their keys)
)
as $v
)
echo $v +1 - $i++,"_"; # Print the value subtracted by the index.
# Need to add 1, because keys are 0-indexed.
```
# Tweaks
* Saved 2 bytes by removing `end()` call and set `$argv[2]` to `$k` instead to shorten access to arguments
* Saved 2 bytes by removing the index from the foreach, since it's simply an incrementing number. Just increment `$i` each iteration instead
]
|
[Question]
[
Japanese kana characters correspond to a single sound in the Japanese language. With the exception of ん (*n*), every other kana consists of a consonant part and a vowel part. There is a natural ordering to Japanese kana, a sort of "alphabetical order", which is typically arranged in a 10 by 5 table:
```
| a i u e o
-----------------------------
* | a i u e o
k | ka ki ku ke ko
s | sa si su se so
t | ta ti tu te to
n | na ni nu ne no
h | ha hi hu he ho
m | ma mi mu me mo
y | ya yu yo
r | ra ri ru re ro
w | wa wo
```
This ordering is called *[gojuuon](https://en.wikipedia.org/wiki/Goj%C5%ABon)*, or "fifty sounds", even though some of the fifty cells in the table are in fact empty.
## The challenge
Input will be any of the listed kana above, with the exception for *wo*. Your program or function should output the next kana along in left-to-right, top-to-bottom reading order, e.g:
```
Input Output
------------------
a -> i
i -> u
o -> ka
ke -> ko
so -> ta
ni -> nu
ya -> yu
yu -> yo
wa -> wo
wo -> (undefined behaviour)
```
With the exception of an optional single trailing newline, there should be no leading or trailing whitespace in the output.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the goal is to minimise program size, in bytes.
## Additional notes
* In order to keep things simple, this challenge uses [Nihon-shiki romanisation](https://en.wikipedia.org/wiki/Nihon-shiki_romanization). [Hepburn romanisation](https://en.wikipedia.org/wiki/Hepburn_romanization) is more common, but has a few kinks which make things more annoying for golf (e.g. *si* becomes *shi*, *hu* becomes *fu*).
* Kana *do* exist for the empty spots (see [Japanese SE](https://japanese.stackexchange.com/questions/643/when-did-the-wu-character-drop-out-of-use)), but they were either non-standard or are now obsolete.
[Answer]
## [Retina](https://github.com/mbuettner/retina), ~~54~~ 53 bytes
```
T`au`ie`y.
wa
we
T`\oeuia`ao
T`ko`stn\hmyr\w`.a
^a
ka
```
[Try it online.](http://retina.tryitonline.net/#code=VGBhdWBpZWB5Lgp3YQp3ZQpUYFxvZXVpYWBhbwpUYGtvYHN0blxobXlyXHdgLmEKbWBeYQprYQ&input=YQppCm8Ka2UKc28KbmkKeWEKeXUKeW8Kd2EKd28)
### Explanation
Wooo, showing off even more features from today's 0.7.2 release. :) ([The release predates this challenge](https://github.com/mbuettner/retina/releases/tag/v0.7.2) by about 7 hours.)
```
T`au`ie`y.
```
This is a transliteration which replaces `a` with `i` and `u` with `e`, but only in matches of `y.`. The purpose of that is to treat `ya` and `yu` like `yi` and `ye`, respectively, in order to skip the gaps.
```
wa
we
```
Replace `wa` with `we` to skip that gap as well.
```
T`\oeuia`ao
```
Here is the new feature. When rotating sets of characters, the "from" and "to" set in a transliteration are usually almost identical. So now we've got `o` (without a backslash) to refer to the other set, which allows us to get rid of some duplication. The `\o` just stands for a literal `o` in that case. So the two sets expand to:
```
oeuia
aoeuia
```
The extraneous `a` in the second set is ignored and the vowels are replaced cyclically as expected.
```
T`ko`stn\hmyr\w`.a
```
This does the same thing for the consonants, but using `o` in the first set (just because we can...). `h` and `w` need escaping because they are character classes. The expanded sets are:
```
kstnhmyrw
stnhmyrw
```
The `.a` restricts this operation to syllables that end in `a`, i.e. those that wrap to the next line of the table.
```
^a
ka
```
Finally, we replace a single `a` with `ka`, because that case cannot be handled by the previous transliteration.
[Answer]
# GNU sed, 65
Comments not included in score:
```
: # Define unnamed label
y/aiueo/iueoa/ # Rotate vowels
/a/y/kstnhmyr/stnhmyrw/ # If at end of row, rotate consonants
s/^a/ka/ # If at end of 1st row, prefix a "k"
/[yw][ie]\|wu/b # If one of the invalid values, jump back to label and redo
```
Oy, this is beginning to look a lot like @Martin's [Retina answer](https://codegolf.stackexchange.com/a/68717/11259) (but longer, of course).
[Answer]
## Pyth, ~~42~~ ~~40~~ 38 bytes
```
s.r]z.DrR6*" kstnhmyrw""aiueo"CM"$&./0
```
This takes the outer product between vowels and consonants, and removes elements at the ords of each number in `$&./0`. Then it outputs the element after the input.
```
@J.DrR6*" kstnhmyrw""aiueo"CM"$&./0"hxJz Implicit: z=input()
*" kstnhmyrw""aiueo" Outer product: [' a',...,' o','ka',...]
rR6 Strip each string—'a'~'o' now single letters
CM"$&./0" Map ord onto the string: [36,38,46,47,48]
.D Remove elements at those indices.
J That's the list of kana; assign it to J
xJz Find the index (x) of z in J,
h add one,
@J and access J at that index.
```
Try it [here](https://pyth.herokuapp.com/?code=s.r%5Dz.DrR6%2a%22+kstnhmyrw%22%22aiueo%22CM%22%24%26.%2F0&input=ya&debug=0).
[Answer]
# Ruby, 105
```
->n{a=['wo','wa']
'rymhntsk '.chars{|c|a+='*o *e *u *i *a'.tr(?*,c).split}
a[8..10]='yu'
a[a.index(n)-1]}
```
Commented in test program
```
f=->n{a=['wo','wa'] #initialize array to last line of table, begin to build table backwards
'rymhntsk '.chars{|c| #for each consonant,
a+='*o *e *u *i *a'.tr(?*,c).split #perform a sustitution to get that line of table in string form,
} #then split into array at spaces and append to a
a[8..10]='yu' #substitute 3 elements ye yu yi with 1 element yu
a[a.index(n)-1] #return element before argument (array is backwards.)
}
puts f[gets.chop]
```
[Answer]
# [TXR](http://nongnu.org/txr) Lisp, ~~135~~ ~~127~~ ~~124~~ 91 bytes
```
(ret[(memqual @1(diff(maprod(op trim-str`@1@2`)" kstnhmyrw""aiueo")'#"yi ye wi wu we"))1])
```
Run:
```
1> (ret[(memqual @1(diff(maprod(op trim-str`@1@2`)" kstnhmyrw""aiueo")'#"yi ye wi wu we"))1])
#<interpreted fun: lambda (#:arg-1-0208 . #:arg-rest-0207)>
2> [*1 "a"]
"i"
3> [*1 "o"]
"ka"
4> [*1 "ki"]
"ku"
5> [*1 "mu"]
"me"
6> [*1 "ya"]
"yu"
7> [*1 "yo"]
"ra"
8> [*1 "wa"]
"wo"
```
[Answer]
# Bash + sed, 83
```
echo {,k,s,t,n,h,m,y,r,w}{a,i,u,e,o}|sed -E "s/[yw][ie]|wu//g;s/.*\b$1 +//;s/ .*//"
```
* Brace expansion to create full table on one line
* sed to:
+ remove `yi`, `ye`, `wi`, `wu` and `we`
+ remove everything up to and including the input entry (but not the next entry)
+ remove everything after the next entry
[Answer]
## JavaScript, ~~145~~ ~~162~~ ~~131~~ 118 bytes
```
x=>(d=" kstnhmyrw".replace(/./g,"$&a$&i$&u$&e$&o").replace(/ |yi|ye|wiwuwe/g,"").match(/[^aiueo]?./g))[d.indexOf(x)+1]
```
~~Admit it, you couldn't imagine a more ridiculous solution to solve this problem ;)~~ ok, done this in a more interesting way.
Demo:
```
function p(x) {
return (d=" kstnhmyrw".replace(/./g,"$&a$&i$&u$&e$&o") //build the sequence of kana, regex rulez!
.replace(/ |yi|ye|wiwuwe/g,"") //remove the spaces and excess kana
.match(/[^aiueo]?./g))[d.indexOf(x)+1] //split it into array using regex and get the index of input in it
}
alert(p(prompt()))
```
[Answer]
## Japt, ~~75~~ ~~70~~ 68 bytes
```
X=" kstnhmyrw"£"aiueo"®+X w} r" |yi|ye|wiwuwe"P f"[^aiueo]?.")g1+XbU
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=WD0iIGtzdG5obXlydyKjImFpdWVvIq4rWCB3fSByIiB8eWl8eWV8d2l3dXdlIlAgZiJbXmFpdWVvXT8uIilnMStYYlU=&input=IndhIg==)
[Answer]
## Haskell, ~~114~~ 96 bytes
```
f"ya"="yu"
f"yu"="yo"
f"wa"="wo"
f x=snd(span(/=x)[words[a,b]!!0|a<-" kstnhmyrw",b<-"aiueo"])!!1
```
`[words[a,b]!!0|a<-" kstnhmyrw",b<-"aiueo"]` is a list of all kanas, including the "holes". I break up the list into the part before the input kana and from the input kana up to the end. From the 2nd part I pick the second element. The exceptions around the "holes" a caught before by separate cases.
Edit: @xnor came up with the idea of using `span`which saved 18 bytes.
[Answer]
# [Lexurgy](https://www.lexurgy.com/sc), 115 bytes
```
a:
{a,i,u,e,o}=>{i,u,e,o,'a}
b:
'=>k/$ _
{',k,s,t,n,h,m,y,r,w} '=>{k,s,t,n,h,m,y,r,w,`} *
y:
{i,e}=>{u,o}/y _
```
Explained:
```
# advance the vowel
a:
{a,i,u,e,o}=>{i,u,e,o,'a}
# advance the consonant
b:
'=>k/$ _ # o => ka case
{',k,s,t,n,h,m,y,r,w} '=>{k,s,t,n,h,m,y,r,w,`} * # everything else
# force yu yo
y:
{i,e}=>{u,o}/y _
```
[Answer]
# Perl 6, 105 bytes
```
.[.first(@*ARGS[0],:k)+1].say with (" kstnhmyrw".comb X~ <a e i o u>).grep(* !~~/[y|w][i|e]|wu/)».trim
```
This is as short as I can get it on my first go, I might have another crack at it later but I feel pretty good about this.
[Answer]
# JavaScript (ES6), 127 bytes
```
s=>s>"yt"?"yo":s=="ya"?"yu":s=="wa"?"wo":(m=[].concat(...["",..."kstnhmyrw"].map(c=>[..."aiueo"].map(v=>c+v))),m[m.indexOf(s)+1])
```
## Explanation
```
s=>
// Hardcode "yu", "ya" and "wa"
s>"yt"?"yo":
s=="ya"?"yu":
s=="wa"?"wo":
// Generate table
(m=[].concat(... // flatten the array of arrays
["", // first consonant is blank
..."kstnhmyrw"].map(c=>[..."aiueo"].map(v=>c+v)) // combine each consonant and vowel
))[m.indexOf(s)+1] // return the next sound
```
## Test
```
var solution = s=>s>"yt"?"yo":s=="ya"?"yu":s=="wa"?"wo":(m=[].concat(...["",..."kstnhmyrw"].map(c=>[..."aiueo"].map(v=>c+v))),m[m.indexOf(s)+1])
```
```
<input type="text" id="input" value="mo" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
## Perl 6, 96 bytes
```
{my @a=(" kstnhmyrw".comb X~ <a i u e o>).grep({!/[y|w][e|i]|wu/})>>.trim;@a[[[email protected]](/cdn-cgi/l/email-protection)($_,:k)]}
```
[Answer]
# Python 2, 107 bytes
```
L=[(x+y).lstrip()for x in' kstnhmyrw'for y in'aiueo'if x+y not in'yiyewiwuwe']
print L[L.index(input())+1]
```
Expects input enclosed in quotes, `'he'` for example
[Answer]
## Racket 151 bytes
```
(second(member s '(a i u e o ka ki ku ke ko sa si su se so ta ti tu te to na
ni nu ne no ha hi hu he ho ma mi mu me mo ya yu yo ra ri ru re ro wa wo)))
```
Ungolfed:
```
(define (f s)
(second
(member s
'(a i u e o ka ki ku ke ko sa si su se so ta ti tu te to na ni nu ne
no ha hi hu he ho ma mi mu me mo ya yu yo ra ri ru re ro wa wo))))
```
Testing:
```
(f 'a)
(f 'i)
(f 'o)
(f 'ke)
(f 'so)
(f 'ni)
(f 'ya)
(f 'yu)
(f 'wa)
```
Output:
```
'i
'u
'ka
'ko
'ta
'nu
'yu
'yo
'wo
```
There is an error message if 'wo is sent.
[Answer]
# C, ~~138~~ 135 bytes
```
char*s="aiueokstnhmyrw";i,j;k(*v){j=strchr(s,*v>>8)-s;i=strchr(s,*v)-s;j=i<4?i++:j<4?j-~(2520%i&3):!++i;printf("%c%c",s[i],i<5?:s[j]);}
```
[Wandbox](http://melpon.org/wandbox/permlink/ZYmhjKjp7fEBjHXn)
]
|
[Question]
[
Don't you hate it when you want to copy-paste a list of numbers (vector, array ...), from one program to another, but the format you have the numbers on doesn't match the format you need it on?
For instance, in MATLAB you may have a space separated list like this:
```
[1 2 3 4 5] (you can also have it comma separated, but that's not the point)
```
In Python you would need to insert commas to make that list a valid input, so you'd have to convert it to
```
[1, 2, 3, 4, 5]
```
to make it work. In C++ you might want something like:
```
{16,2,77,29}
```
and so on.
To simplify everyone's life, let's create a list converter, that takes a list on any format\*, and outputs a list on another specified format.
The valid brackets are:
```
[list]
{list}
(list)
<list>
list (no surrounding brackets)
```
The valid delimiters are:
```
a,b,c
a;b;c
a b c
a, b, c <-- Several spaces. Must only be supported as input.
a; b; c <-- Several spaces. Must only be supported as input.
a b c <-- Several spaces. Must only be supported as input.
```
Note, the input can have any number of spaces between the numbers, but the output can choose to have zero spaces (if `,` or `;` is used as delimiter), or a single space (if it's space-delimited).
In addition to the input list, there will be a string (or two characters) that defines the output format. The format string will first be the opening bracket type (only), `[`, `(`, `<`, `{` or (the last one is a single space used when there is no surrounding bracket). The bracket type will be followed by the delimiter type, `,`, `;` or (the last one is a single space). The two input format characters must be taken as a single argument (string or two consecutive characters) in the order described above.
Some examples of format strings:
```
[, <-- Output format: [a,b,c]
{; <-- Output format: {a;b;c}
<-- Two spaces, output list has format: a b c
```
Rules:
* The output can't have leading spaces
* The output can have trailing spaces and a newline
+ The output should *only* be the list of numbers, not `ans =` or similar
* The input will be a list of integer or decimal numbers (both positive and negative (and zero)), and a string of two characters
+ If the input consist of *only* integers, the output list should have only integers. If the input list consist of integers and decimal numbers, all output numbers can be decimal numbers. (It's optional to keep the integers as integers)
+ The maximum number of digits after the decimal point that must be supported are 3.
+ The input will be two arguments. I.e. the numbers are in one argument, and the format string is a single argument.
* The code can be a program or function
* The input can be function argument or STDIN
Some examples:
```
1 2 3 4
[,
[1,2,3,4]
<1; 2; 3>
; <-- Space + semicolon
1;2;3
not valid: 1.000;2.000;3.000 (Input is only integers => Output must be integers)
{-1.3, 3.4, 4, 5.55555555}
[,
[-1.300,3.400,4.000,5.556] (5.555 is also valid. Rounding is optional)
also valid: [-1.3,3.4,4,5.55555555]
```
The shortest code in bytes win. As always, the winner will be selected one week from the day the challenge was posted. Answers that are posted later can still win if they are shorter than the current winner.
---
## Leaderboard
The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=66345,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# JavaScript (ES6), 75 ~~82~~
As an anonymous function
Edit: 2 byte saved thx @user81655 (and 5 more just reviewing it)
```
(l,[a,b])=>a.trim()+l.match(/[-\d.]+/g).join(b)+']})> '['[{(< '.indexOf(a)]
```
Test snippet
```
F=(l,[a,b])=>a.trim()+l.match(/[-\d.]+/g).join(b)+']})> '['[{(< '.indexOf(a)]
// Test
console.log=x=>O.innerHTML+=x+'\n'
// default test suite
t=[['1 2 3 4','[,'],['<1; 2; 3>',' ;'],['{-1.3, 3.4, 4, 5.55555555}','[,']]
t.forEach(t=>console.log(t[0]+' *'+t[1]+'* '+F(t[0],t[1])))
function test() { console.log(P1.value+' *'+P2.value+'* '+F(P1.value,P2.value)) }
```
```
#P1 { width: 10em }
#P2 { width: 2em }
```
```
P1<input id=P1>
P2<input id=P2>
<button onclick="test()">-></button>
<pre id=O></pre>
```
[Answer]
## CJam, ~~35~~ 34 bytes
```
l(S-l"{[<(,}]>);":BSerS%@*1$B5/~er
```
[Test it here.](http://cjam.aditsu.net/#code=l(S-l%22%7B%5B%3C(%2C%7D%5D%3E)%3B%22%3ABSerS%25%40*1%24B5%2F~er&input=%3C%3B%0A%7B-1.3%2C%203.4%2C%20%2C4%2C%205.55555555%7D)
Expects the format on the first line and the list on the second.
### Explanation
```
l e# Read the format line.
( e# Pull off the first character, which is the opening bracket.
S- e# Set complement with a space, which leaves brackets unchanged and turns a space
e# into an empty string.
l e# Read the list.
"{[<(,}]>);":B
e# Push this string which contains all the characters in the list we want to ignore.
Ser e# Replace each occurrence of one of them with a space.
S% e# Split the string around runs of spaces, to get the numbers.
@ e# Pull up the the delimiter string.
* e# Join the numbers in the list with that character.
1$ e# Copy the opening bracket (which may be an empty string).
B5/ e# Push B again and split it into chunks of 5: ["{[<(," "}]>);"]
~ e# Unwrap the array to leave both chunks on the stack.
er e# Use them for transliteration, to turn the opening bracket into a closing one.
```
[Answer]
# Pyth, 33 bytes
```
rjjezrXwJ"<>[] {}(),;"d7@c6JChz6
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?test_suite_input=%5B%2C%0A1%202%203%204%0A%20%3B%0A%3C1%3B%20%202%3B%20%203%3E%0A%5B%2C%0A%7B-1.3%2C%203.4%2C%20%2C4%2C%205.55555555%7D&code=rjjezrXwJ%22%3C%3E%5B%5D%20%20%7B%7D%28%29%2C%3B%22d7%40c6JChz6&input=%5B%2C%0A1%202%203%204&input_size=2&test_suite=0) or [Test Suite](http://pyth.herokuapp.com/?test_suite_input=%5B%2C%0A1%202%203%204%0A%20%3B%0A%3C1%3B%20%202%3B%20%203%3E%0A%5B%2C%0A%7B-1.3%2C%203.4%2C%20%2C4%2C%205.55555555%7D&code=rjjezrXwJ%22%3C%3E%5B%5D%20%20%7B%7D%28%29%2C%3B%22d7%40c6JChz6&input=%5B%2C%0A1%202%203%204&input_size=2&test_suite=1)
# Explanation:
```
J"<>[] {}(),;" assign this string to J
rjjezrXwJd7@c6JChz6 implicit: z = first input string, e.g. "[;"
w read another string from input (the list of numbers)
X Jd replace every char of ^ that appears in J with a space
r 7 parse ^ (the string of numbers and spaces) into a list
jez put z[1] (the separator symbol) between the numbers
c6J split J into 6 pieces ["<>", "[]", " ", "{}", "()", ",;"]
Chz ASCII-value of z[0] (opening bracket symbol)
@ take the correspondent (mod 6) brackets from the list
j and put the numbers between these brackets
r 7 remove leading and trailing spaces
```
[Answer]
## PowerShell, ~~108~~ ~~100~~ ~~95~~ 85 Bytes
```
$i,$z=$args;($z[0]+($i-split'[^\d.-]+'-ne''-join$z[1])+' }) >]'[($z[0]-32)%6]).Trim()
```
(see revision history for previous versions)
Golfed another 15 bytes by removing `$b` and `$s` variables and changing parens on the inner string.
This takes input as two strings and stores them into `$i` and `$z`, then we construct a new output string. The inner parens `-split`s `$i` with a regex to select only numeric digits, then `-join`s back together with the requested delimiter. We concatenate that with the first character of the delimiter input (e.g., `[`) and close it with indexing into a string based on the ASCII value of the first character and some formulation trickery. The outer `.Trim()` removes any leading or trailing spaces.
[Answer]
# Python 2, 96 bytes
```
import re
lambda(a,(b,c)):(b+c.join(re.findall('[-\d\.]+',a))+'])>} '['[(<{ '.index(b)]).strip()
```
Call as:
```
f(('{-1.3, 3.4, ,4, 5.55555555}','[,'))
```
Output:
```
[-1.3,3.4,4,5.55555555]
```
[Answer]
# JavaScript (ES6), ~~82~~ ~~92~~ ~~116~~ 92 bytes
```
(a,b)=>(c=a.match(/-?\d+(\.\d+)?/g).join(b[1]),d=b[0],d<"'"?c:d+c+"]}>)"["[{<(".indexOf(d)])
```
An anonymous function, run it like this
```
((a,b)=>(c=a.match(/-?\d+(\.\d+)?/g).join(b[1]),d=b[0],d<"'"?c:d+c+"]}>)"["[{<(".indexOf(d)]))("{1; 2;3; 4}","<;")
```
This can probably be golfed way further..
### Ungolfed
```
(a,b)=>( // "{1; 2;3; 4}", "<;"
c=a.match(/-?\d+(\.\d+)?/g) // regex to match decimals
.join(b[1]), // c -> "1;2;3;4"
d=b[0], // d -> "<"
d<"'" ? // if d is smaller than ' then ...
c : // return just "1;2;3;4"
d + c + // "<" + "1;2;3;4" + ...
"]}>)" [ "[{<(".indexOf(d) ] // "]}>)"[2] -> ">"
)
```
[Answer]
# Mathematica, 108 bytes
Mathematica is generally clumsy with string inputs unless the string is meant to be interpreted as a text.
```
c=Characters;t_~f~p_:=({b,s}=c@p;b<>Riffle[StringCases[t,NumberString],s]<>(b/.Thread[c@"[ {<(" -> c@"] }>)"]))
```
---
**Explanation**
`StringCases[t,NumberString]`returns the list of number strings.
`Riffle`inserts the separators between the numbers.
`/.Thread[c@"[ {<(" -> c@"] }>)"])` replaces the left "bracket" with the right bracket.
`<>` is the infix form of `StringJoin`. It glues together the substrings.
[Answer]
# Bash + GNU Utilities, 90
```
b=${2:0:1}
echo $b`sed "s/[][{}()<>]//g;s/[,; ]\+/${2:1}/g"<<<"$1"``tr '[{(<' ']})>'<<<$b`
```
[Answer]
# Matlab, 85 bytes
```
@(s,x)[x(1) strjoin(regexp(s,'-?\d+\.?\d*','match'),x(2)) x(1)+(x(1)~=32)+(x(1)~=40)]
```
Example use:
```
>> @(s,x)[x(1) strjoin(regexp(s,'-?\d+\.?\d*','match'),x(2)) x(1)+(x(1)~=32)+(x(1)~=40)]
ans =
@(s,x)[x(1),strjoin(regexp(s,'-?\d+\.?\d*','match'),x(2)),x(1)+(x(1)~=32)+(x(1)~=40)]
>> ans('1 2.4 -3 -444.555 5', '[,')
ans =
[1,2.4,-3,-444.555,5]
```
[Answer]
# CJam, 27 bytes
```
l)l_5ms`-SerS%*\S-_o_'(#(f-
```
[Try it here.](http://cjam.aditsu.net/#code=l%29l_5ms%60-SerS%25*%5CS-_o_%27%28%23%28f-&input=%20%3B%0A%7B16%2C2%2C77%2C29%7D)
### Explanation
```
l e# Read the format string.
) e# Extract the separator.
l_ e# Read the list.
5ms` e# Get a string that contains -.0123456789.
- e# Get the characters in the list that are not in the string.
Ser e# Replace those characters with spaces.
S% e# Split by those characters, with duplicates removed.
* e# Join with the separator.
\S- e# Remove spaces (if any) from the left bracket.
_o e# Output a copy of that character before the stack.
_'(# e# Find '( in the left bracket string.
( e# Get -1 if '( is the first character, and -2 if it doesn't exist.
f- e# Subtract the number from every character in the left bracket string,
making a right bracket.
```
[Answer]
# Julia, 95 bytes
```
f(l,s)=(x=s[1]<33?"":s[1:1])*join(matchall(r"[\d.-]+",l),s[2])*string(x>""?s[1]+(s[1]<41?1:2):x)
```
This is a function `f` that accepts two strings and returns a string.
Ungolfed:
```
function f{T<:AbstractString}(l::T, s::T)
# Extract the numbers from the input list
n = matchall(r"[\d.-]+", l)
# Join them back into a string separated by given separator
j = join(n, s[2])
# Set the opening bracket type as the empty string unless
# the given bracket type is not a space
x = s[1] < 33 ? "" : s[1:1]
# Get the closing bracket type by adding 1 or 2 to the ASCII
# value of the opening bracket unless it's an empty string
c = string(x > "" ? s[1] + (s[1] < 41 ? 1 : 2) : x)
# Put it all together and return
return x * j * c
end
```
]
|
[Question]
[
Write a program that takes an input to STDIN and makes all of the lowercase letters (including accented letters) in the `2k-1`th word uppercase and all the uppercase letters (also including accented letters) in the `2k`th word lowercase (`k` is a positive integer). The program should not affect any other characters in any word. For example, if the string is `Ook! O0k!`, then the output should be `OOK! o0k!`.
A new word is formed when there is a nonzero amount of whitespace after a non-whitespace character. Whitespace at the beginning of an input should be ignored. If a word does not contain any changed characters, the program should still consider it as a word and continue.
*Sample inputs* (Different inputs are separated by a blank newline). **Please note the third example**, which should have leading spaces, and have the first `be` capitalised.
```
Nineteen Eighty-Four (1984)
Programming Puzzles & Code Golf -
Hooray for Code Golf Stack Exchange!
2be or not 2be, that is the ~~~QuEsTiOn~~~
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
```
*Sample outputs*
```
NINETEEN eighty-four (1984)
PROGRAMMING puzzles & code GOLF -
HOORAY for CODE golf STACK exchange!
2BE or NOT 2be, THAT is THE ~~~question~~~
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
```
---
This is code golf, fellas. Standard CG rules apply. Shortest program in bytes wins.
---
I'm pretty sure I covered all the loopholes regarding whitespace and non-letter characters, but if I've missed any, please tell me.
---
Thanks to [@Optimizer](https://codegolf.meta.stackexchange.com/users/31414/optimizer) for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet".
```
/* Configuration */
var QUESTION_ID = 59464; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 43444; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
else console.log(body);
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
lang = jQuery('<a>'+lang+'</a>').text();
languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# Vim script, ~~22~~ 21 bytes
```
nm Q vEUWvEuWQ|norm Q
```
Explanation:
The first command maps `Q` to:
`vEU` make word uppercase
`W` go to next word
`vEu` make word lowercase
`W` go to next word
`Q` repeat recursive mapping
and `|norm Q` executes the mapping
## Usage of the program
This is how you get *Vim* to read from stdin:
```
$ vim - -c 'nm Q vEUWvEuWQ|norm Q'
Vim: Reading from stdin
This is the first line!
This is the second line!
This is the third and last line I type to check if this works!
^D
```
This will open up *Vim* displaying this:
```
THIS is THE first LINE.
this IS the SECOND line.
THIS is THE third AND last LINE i TYPE to CHECK if THIS works!
~
~
~
```
[Answer]
# GNU sed, 28
Score includes +2 for `-rz` passed to GNU sed.
```
s/(\S+\s*)(\S*)/\U\1\L\2/g
```
### Test output
```
$ for t in 'Nineteen Eighty-Four (1984)' \
> 'Programming Puzzles & Code Golf -
> Hooray for Code Golf Stack Exchange!' \
> ' 2be or not 2be, that is the ~~~QuEsTiOn~~~' \
> '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'; do
> echo "$t" | sed -zrf PRINTlikeTHIS.sed
> done
NINETEEN eighty-four (1984)
PROGRAMMING puzzles & code GOLF -
HOORAY for CODE golf STACK exchange!
2BE or NOT 2be, THAT is THE ~~~question~~~
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
$
```
[Answer]
# Perl, 26 bytes
25 bytes code + 1 byte command line
```
s/\S+/++$i%2?uc$&:lc$&/eg
```
Thanks to ThisSuitIsBlackNot for fixing a couple of bugs!
Usage:
```
perl -p entry.pl
```
[Answer]
# Pyth, 23
```
jdmjbmrk=xZ!!kcdbcjb.zd
```
[Try it online](https://pyth.herokuapp.com/?code=jdmjbmrk%3DxZ%21%21kcdbcjb.zd&input=a%0Ab&debug=0) or run the [test suite](https://pyth.herokuapp.com/?code=jdmjbmrk%3DxZ%21%21kcdbcjb.zd&input=a%0Ab&test_suite=1&test_suite_input=Nineteen+Eighty-Four+%281984%29%0A%0AProgramming+Puzzles+%26+Code+Golf+++-+%0AHooray+for+Code+Golf+Stack+Exchange%21%0A+++++2be+or+not+2be%2C+that+is+the+%7E%7E%7EQuEsTiOn%7E%7E%7E%0A%0A%2B%2B%2B%2B%2B%2B%2B%2B%5B%3E%2B%2B%2B%2B%5B%3E%2B%2B%3E%2B%2B%2B%3E%2B%2B%2B%3E%2B%3C%3C%3C%3C-%5D%3E%2B%3E%2B%3E-%3E%3E%2B%5B%3C%5D%3C-%5D%3E%3E.%3E---.%2B%2B%2B%2B%2B%2B%2B..%2B%2B%2B.%3E%3E.%3C-.%3C.%2B%2B%2B.------.--------.%3E%3E%2B.%3E%2B%2B.%0A%0Aa%0Ab&debug=0&input_size=2)
Alternates between pyth's `lower` and `upper` functions, which are `r...0` or `r...1`. This will probably affect unicode characters, waiting on OP clarification to change.
I feel like something must be golfable. Particularly the XOR to change the switch on which of `upper`/`lower` should be used.
[Answer]
## Perl, 87 bytes
After screwing with both regular expressions and `map` for a while, I could not come up with an elegant solution, so this is the result:
```
@a=split(" ",lc(<>));while($i<=$#a/2){@a[$i*2]=uc(@a[$i*2]);$i++;}print(join(" ", @a));
```
[Answer]
# Ruby, 56 bytes
```
$><<gets.gsub(/\S+/){($.+=1)%2>0?$&.downcase: $&.upcase}
```
[Answer]
# JavaScript ES6, ~~74~~ 71 bytes
`.toUpperCase()` and `.toLowerCase()` absolutely slaughter the byte count (adds 32 bytes 0.o). Most work-arounds end up with more bytes though
```
s=>s.replace(/(\S+\s*)(\S*)/g,(_,a,b)=>a.toUpperCase()+b.toLowerCase())
```
[Answer]
# Delphi, 290 bytes
```
program P;uses SysUtils;var s:string;i:word;w:byte;f:boolean;begin repeat readln(s);w:=0;f:=false; for I:=1 to length(s) do begin if s[i]>' ' then begin if w=0 then f:=not f;w:=1;if f then s[i]:=uppercase(s[i])[1] else s[i]:=lowercase(s[i])[1] end else w:=0 end;writeln(s)until false;end.
```
Not really a good language to golf with ...
[Answer]
# Groovy, ~~108~~ ~~125~~ 120
```
System.in.eachLine{def b;it.split(" ").any{if(!it.empty)b=!b;print "${b?it.toUpperCase():it.toLowerCase()} "};println()}
```
Not as clean as I was hoping it would be, which seems to be a theme with my Groovy answers.
* +17 to fix behavior with leading whitespace
* -5 for removing trailing newline and switching from .isEmpty() to .empty
```
$ cat tests.txt
Nineteen Eighty-Four (1984)
Programming Puzzles & Code Golf -
Hooray for Code Golf Stack Exchange!
2be or not 2be, that is the ~~~QuEsTiOn~~~
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
$ groovy PRINTlikeTHIS.groovy < tests.txt
NINETEEN eighty-four (1984)
PROGRAMMING puzzles & code GOLF -
HOORAY for CODE golf STACK exchange!
2BE or NOT 2be, THAT is THE ~~~question~~~
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
```
[Answer]
# Lua, 96 bytes
```
i=0 print(io.read'*l':gsub('%S+',function(x)i=i+1 return i%2==1 and x:upper() or x:lower()end))
```
[Answer]
# Python 3, ~~103~~ 95 bytes
```
print(' '.join(b.lower()if a%2 else b.upper()for a,b in enumerate(input().strip().split(' '))))
```
[Answer]
## STATA, 252 bytes
```
insheet using a.b
g b=word(v,1)
gl c=0
forv x=1/`=_N'{
loc d=1
while b[`x']!=""{
if !$c replace v=subinword(v,b,upper(b),1) if `x'==_n
if $c replace v=subinword(v,b,lower(b),1) if `x'==_n
loc ++d
replace b=word(v,`d') if `x'==_n
gl c=1-$c
}
di v[`x']
}
```
Expects input as a csv file (one column) called a.b.
Explanation:
Read data in (default variable name is v1, shortenable to v). Make a new variable b equal to the first word (space separated token) of v for each line. For each line, while the next word is not empty (only occurs if no more characters on that line), replace the word in v with the upper or lower case version of that word in the current line, depending on how many (mod 2) words have already been found. Then get the next word and repeat. Print out the whole line when finished with it.
[Answer]
# Lua, 88 bytes
```
a=io.read():gsub("%g+",function(s)m=not m return m and s:upper()or s:lower()end)print(a)
```
[Answer]
# CJam, 28 bytes
```
q{C' >Sc'!<*X^:XCelCeu?:S}fC
```
I'm currently considering the first 33 ASCII/Unicode characters (and only those) whitespace. I'm awaiting clarification to know whether this is valid or not.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q%7BC'%20%3ESc'!%3C*X%5E%3AXCelCeu%3F%3AS%7DfC&input=Programming%20Puzzles%20%26%20Code%20Golf%20%20%20-%20%0AHooray%20for%20Code%20Golf%20Stack%20Exchange!).
[Answer]
## Pyth, ~~17~~ 22 bytes
```
FGcwd=+YrG=Z%+1Z2;jdY
```
[Try it here](http://pyth.herokuapp.com/)
[Answer]
# C#, 104 100 99 bytes
```
static void Main(){string.Join(" ","".Split(' ').Select((o,i)=>i++%2==0?o.ToUpper():o.ToLower()));}
```
It's 79 bytes with
```
string.Join(" ","".Split(' ').Select((o,i)=>i++%2==0?o.ToUpper():o.ToLower()));
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-040plF/^ +$/`, 17 bytes
```
$_=($|-=@F)?uc:lc
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lZDpUbX1sFN07402Son@f9/BRAwSkpVyC9SyMsvATF1FEoyEksUMouBdKpCXV1dYKlrcUimfx6Q@S@/oCQzP6/4v26BgYlBjpt@nJ62ij4A "Perl 5 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
z?a_mȯ%2Lwḣ¹
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8X@VfWJ87on1qkY@5Q93LD608////9FKfpl5qSWpqXkKrpnpGSWVum75pUUKGoaWFiaaSjpKAUX56UWJubmZeekKAaVVVTmpxQpqCs75KakK7vk5aUAVHvn5RYmVCmn5RQhhheCSxORsBdeK5IzEvPRURaAyBRAwcnJVAKrz8w9RMEpK1VEI8XAMUcgsBtKuCnV1dYWlqcUlmfl5QCZQhzYURNvBSBADgm2AQDfWDsiy07Wz0462iQVx7fTsdHV19aD69EAMPaCgja6eDZitCwZQCsgA6tQDmqenFAsA "Husk – Try It Online")
Preserves whitespace in the input, in agreement with the test cases.
```
z?a_mȯ%2Lwḣ¹
z # zip two lists together,
# using this function on each pair of elements:
? # if element from list1 is truthy
a # uppercase the element from list2
_ # otherwise lowercase the element from list2
mȯ%2Lwḣ¹ # list1:
mȯ # map this function on each element of
ḣ¹ # all the prefixes of the input string:
Lw # number of elements after splitting on whitespace
%2 # modulo 2
# list2: the input string
```
---
A different program which uppercases & lowercases in words, and does "not affect any other characters in any word" (which I wrote after reading the instructions, but before realising that the third "Sample output" should also be considered as part of the specification), could be only **10 bytes**:
```
wzom?a_ݬw
```
[Try it online!](https://tio.run/##RYzBasJAEIZfZcyhVHQXWjwohPUgaXuyFr2FULa6JotmBzYbrDkE2ufx4DOIT@KLbCea4g8z/zfDP5OVxcbnl98fv6swH8vP8/F02Hnv42CqjXJKGYh0mrk9e8HSwuPTaDjoBv1gZjG1Ms@1SWFWVtVWFfAAE1wpeMXtmhJviFbuYY32voa5k8sNRN/LTJpUdSj2/KWAIgYdEPbBZdKBLsgV1HX9UUbFQr8bQgr3WsXivzdwq5DEEkEkmBC9OEyaUXDBGOPtHW@A0zJkPLwyu6o1Arrk9I8HyR8 "Husk – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 106 bytes
```
$k=@();$i=0;$args[0].trim().split(' ')|%{if($i%2){$k+=$_.tolower()}else{$k+=$_.toupper()};$i++};$k-join" "
```
[Try it online!](https://tio.run/##RYyxCsIwFEV/5RFSmlANpWspdHEWwU1EKkT7TGxCkuJQza/H1MU73Hs4w7XmJZ0fpdYpUdX1jLcUu7qlg7v7U30WweGTceGtxsBKKPm7WPDGKBYNX6iqOnoRwej1hvGP1F7@7Wztz@bLqsqttg@DEwGSUiKwprlKMA4mE1bcQBiHAOjzSogxHuadP@J@yki@ "PowerShell – Try It Online")
Shameless port of python 3 solution, Just horrible attempt to golf ;-(
]
|
[Question]
[
# The task
Given a multiline string with ascii art operators and numbers, parse the expression!
# Possible symbols
Numbers: (3x4)
```
/
/|
|
---
___
_|
|
---
___
_|
|
---
| |
|_|
|
|
___
|_
|
---
___
|_
| |
---
___
/
/
|
___
|_|
| |
---
___
|_|
|
---
___
| |
| |
---
```
Operators: (3x3)
```
|
-+-
|
---
\ /
x
/ \
.
---
.
```
Braces: (1x4)
```
/
|
|
\
\
|
|
/
```
# Input
A multiline string with ascii art operators and numbers. Examples in the test cases.
# Output
The string of the parsed expression.
# Test cases
Input:
```
/ ___ ___ \ ___
| _| | / | . _|
| | -+- / | --- |
\ --- | | / . ---
```
Output: `(2+7)/3`
Input:
```
___ / ___
|_| /| \ / |_
| --- | x |
--- --- / \ ---
```
Output: `9-1*5`
# Rules
1. Numbers will always be single-digit
2. Since operators are one symbol shorter than numbers, they are placed one symbol lower than numbers, leaving whitespace on top.
3. All symbols have a column of whitespace between them
4. This is a code-golf challenge, so lowest byte count wins!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~46~~ 44 bytes
```
'/(80-)63+92145*7'[16|43|25⊥¨(×⊆⊢)2⊥' .\'⍳⎕]
```
[Try it online!](https://tio.run/##XVDNSgMxEL7nKeaW1pqm@9Nqn8XIEpCKUKjHCnPysMpCRQ/iXRC86xPom@RF1pnMJq0NzM6XbyfffDP@dm2u7vx6c92Hp9ebTWifZyo8Pqx6bUfnMzNeVJNlWdTzkzN9USywrrCch@7j53P0@xa6NnTv45LuGqZOh90XiVz29L5fKYKkVkNZhd23ttA0DfDh7BJC@lIgXy2nKfOIkTETwyxhYwgBOgHDAxuridFK7dsVS26XmnFRatWgMJQcN@MKzIqw5Z8onaIs1bhB3gNph@5edK0MwcFGEz6M40NSWvnTQYVfsQ0Y5scYIJaiNeFkL2KXZyX2SAVyEeaIvBUUJ6Q1xrG2MtZ/FWYOI@1EKmHPY54keiFPOq89tC/@Dw "APL (Dyalog Unicode) – Try It Online")
`⎕` evaluated input, must be a character matrix
`' .\'⍳` replace spaces with 0, `.`s with 1, `\`s with 2, and everything else with 3
`2⊥` base-2 decode the columns
`(×⊆⊢)` split on zeroes
`25⊥¨` base-25 decode each group
`16|43|` mod 43, mod 16
`'/(80-)63+92145*7'[` `]` use as indices in the given string
[Answer]
# [Python 2](https://docs.python.org/2/), ~~154~~ 139 bytes
```
s=zip(*input().split('\n'))
i=0
while s[i:]:d=3**(max((s+[' '])[i+1])>' ')+i;print'+/5(_41_7802*6__-9)3'[hash(tuple(s[i:d]))*3%67%21];i=1+d
```
[Try it online!](https://tio.run/##NYzbqsIwEEXf/Yq8SGYSYm3rXeqPtCEIFTpQYzCRc6H/XjNyTiDsxdrsCT9pePhqnmPzSwEU@fBKgKsYRkogOy8RF9SsF18DjTcRWzrZU9/USsH9@g0QdSuFtNiSLi1eMqOmc3iST1IXW3Cb0u0P60rtnDNHrGU7XOMA6RXGG/C13iKqernbL6vSnqkpdT/PshDOOcGPs@v@sfNTzvwnFgXHipuJC3ZGG/aZjckkcpHXH/5bFZ9JNvIN "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~69~~ 61 bytes
Anonymous tacit prefix function. Requires `⎕IO←0`.
```
{('+-*/()',⎕D)['∆JV⍺TgucKmre3Ha'⍳⎕AV[94|2⊥¨,⌿⍵⊆⍨∨⌿32≠⍵]]}⎕UCS
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6s11LV1tfQ1NNV1gIIumtHqjzravMIe9e4KSS9N9s4tSjX2SFR/1LsZKOsYFm1pUmP0qGvpoRU6j3r2P@rd@qir7VHvikcdK4BcY6NHnQuAYrGxtUDFoc7B/9OAVjzq7XvU1fyod82j3i2H1hs/apsIlAwOcgaSIR6eQDUKQBZQnYmCkTFQibq@Qnx8vAIIgOgYGKsGSAJxDYirD6L0QOI1NWARXW1dkCiQrasLZCnUxEAYUA36YNVAEXUuhG2GliDbYHaB1MBsiq@BiACpGJBdIBU1cAMVKkCSNRCLwKYC1YDtUwcA "APL (Dyalog Unicode) – Try It Online")
`⎕UCS` convert characters to code points
`{`…`}` "dfn"; argument is `⍵`
`('+-*/()',⎕D)` the involved symbols followed by the **D**igits
`[`…`]` index into that using the following indices:
`'∆JV⍺TgucKmre3Ha'⍳` indices in this string (missing elements get index=length) of
`⎕AV[`…`]` index into the **A**tomic **V**ector (the character set) using the following:
`94|` the division remainder when divided by 94 of
`2⊥¨` the base-2 evaluation of each of
`,⌿` the vertically joined and flattened
`⍵⊆⍨` segments of the argument, as indicated by trues in
`∨⌿` the vertical OR-reduction of
`32≠⍵` the Boolean mask indicating where the argument is different from 32 (space)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 67 bytes
```
⭆⪪⭆θ§αI⭆⟦θηζε⟧÷⊖℅§λκ³²A℅⁺⁴⁰÷⌕”$⌈O⁴εΦa↙M∕³↧FωG↙σ⎇C(|?⊞¦﹪ω←2I0C⁻sⅉ”ι³
```
[Try it online!](https://tio.run/##XU7fT4MwEH7fX3HhqcQiRn3zqQxRQsTlpombM6SBxjUiTlaXxfR/x7amE9frd7/vvqvXvK8/eDsMs152isyVMa93fEPmm1aO408KTOVdI/aEU5jy7bj4bKprCt8UxAuFvFOp3MlGkFTUvXgXnRINue8b2fGW@C0thbcwDClcnIfOBiwwemou4rUSPZm1X1tyeTbel8muIcENY8jYw/WiSArGWFE4fVvgEp@yJMVyibiYZyWmiGmSPyJiiRhQkJbNkl0NA8QAVVU5aCPeP8bxi2E1ibVxKu2gHcDBVrXPGbHfvpUlO7Whnvyl9QGuN/71fBydRBBFEcAenLWz1nrYPu/bqX81fbjV8Rr@Idq1Pw "Charcoal – Try It Online") Link is to verbose version of code. Assumes 4 input strings of equal length (space padded if necessary). Explanation:
```
θ First input
⭆ Map over characters and join
⟦θηζε⟧ All four inputs as a list
⭆ Map over strings
λ Inner string
§ Indexed by
κ Outer index
℅ Take the ASCII code
⊖ Decrement
÷ ³² Integer divide by literal `32`
I Cast to integer
§α Index into uppercase alphabet
⪪ A Split on literal `A`
⭆ Map over substrings
⌕...ι Find their indices in compressed data
÷ ³ Integer divide by 3
⁺⁴⁰ Plus literal `40`
℅ Convert to ASCII
Implicitly print
```
The compressed data represents the literal string `GAARAATEYKBKAAAKKKAAAKHKRZRXFBDRNZRRYSFNRDRRDBIURRRNRR` which contains the pattens that result from the calculation, padded with `A`s to place them at the appropriate offset to generate the desired ASCII character.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 152 bytes
```
f=(s,i=0,a=s.split`
`,c=a[n=0][i],x=1)=>c?"*3-425()6+9/7081"[c=='/'?6:c=='\\'?7:[x=3,4,5,6,9].map(c=>n+=Buffer(a[c/3|0])[i+c%3]*c)|n%47%16]+f(s,i-~x):''
```
[Try it online!](https://tio.run/##NY7dioMwEIXvfYpSkCQ1MXZt7baQCnuxL9DLKG2IScnixq6xxQXZV3eT/RkYzjfnzMC8iYdwsje3gdiuUfOsGXTYsAwL5lJ3a81wiS5YMsEty2puajyyNWJHWS5XOdk8bSEqkj3dZc/rJZeMAQrK4hCgqkC5O/CR5XiDt7jA@zp9Fzco2dEm7OWuteqh4JLmU1YjbhIZ5/VKosnGm128LupEh1fI14gOAMyys65rVdp2V6hhrz7uplcQaAdQ2ivRvJpWnT6thIA26kHd0Bjro6E7Db2xV4gQmunifD4vQgWt/imavPiewkyDpCGYvB8skpBgeybE02KKql/6O6E/@975Bg "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ỴZ⁶=ẠƊ€œp$“¢Ọ/’,“642-*+)9(8/17035”ḥⱮ
```
A monadic Link accepting a list of characters which yields a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8///h7i1Rjxq32T7cteBY16OmNUcnF6g8aphzaNHD3T36jxpm6gA5ZiZGulrampYaFvqG5gbGpo8a5j7csfTRxnX////XV4iPj1cAARAdA2Nx1QApIK4B8fVBlB5IogYoDhLS1dYFCQPZurpAlkINVwyEBdWiD1YPFAEA "Jelly – Try It Online")**
### How?
```
ỴZ⁶=ẠƊ€œp$“¢Ọ/’,“642-*+)9(8/17035”ḥⱮ - Link: list of characters, I
Ỵ - split at newline characters
Z - transpose
$ - last two links as a monad - i.e. f(X):
Ɗ€ - for each, last three links as a monad:
⁶ - the space character
= - equals? (vectorises)
Ạ - all?
œp - split (X) at truthy indices of (that)
- (...call the result A)
“¢Ọ/’ - base 250 int = 170548 (salt)
“642-*+)9(8/17035” - list of characters "642-*+)9(8/17035" (domain)
, - pair -> [salt, domain]
Ɱ - map across A with:
ḥ - Jelly's hash function with salt and domain
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~54~~ ~~40~~ 39 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"2(-1 0/ 9 6*)+"Ž´Š«|€SøJð4סJÇ2δβŽ4w%è
```
~~Can definitely be golfed some more with smarter magical integers (including changing the `ā‡` to for example `Åβ` or changing the order of the charcters in the strings), but I'm pretty bad at those kind of challenges personally, so this will do for now.~~
-14 bytes thanks to *@ovs*, because he is skilled in these kind of magic integer challenges. ^\_^
[Try it online](https://tio.run/##yy9OTMpM/f9fyUhD11DBQF/BUsFMS1Nb6ejeQ1uOLji0uuZR05rgwzu8Dm8wOTz90EKvw@1G57ac23R0r0m56uEV//8r6CsoxMfHg3ENEMLY6Bgd6CvEcOnXABnxNWBcA8YKYAySrYGJASEIgUAMyDI9ELeGCyFcA8dgtfoQFpgE6tfV1lXQ1dVVUKhQANMgvSAahkHqYGyQLhS5GrhbwfYC7QcA) or [verify all test cases](https://tio.run/##XVCxSgNBEO33K4YFIZrbrAmHYJrUSZPC9mBRsLBRwcQkMJVNPsHWdIFYiBwiSJpdrs1H5EfOmdnsiVl4N2/fzL6ZuYen65u72xrzUD7r4f3jdNIHnS38T6bH00m8Dmrda5kunFu4hIuz07autr6s3vxmsX95vwrfo/CRh1e/GoVlb1fuPqttPjsJ6zrzX4PagnMO@HAsElNIgYB8txw6nEDSWTJtwzJxY4gBqiKywxMr9aSo5M5S4@0wShQKdnegGi9OzUE8o7f4UJV0UOzDngyeJfFjHB96r7ifbEVAAQhkw6SlFSDOxnuQpv5kbCC1NjL50nv@MzL3PM6Nhz0S0p4xB/Avh82s0pf6/wI).
**Explanation:**
```
"2(-1 0/ 9 6*)+" # Push this string
Ž´Š # Push compressed integer 45783
« # Append it to the string: "2(-1 0/ 9 6*)+45783"
| # Push all input-lines as list
€S # Convert each line to a list of characters
ø # Zip/transpose; swapping rows/columns
J # Join each inner list (column) together to a string
ð4× # Push a string of 4 space characters: " "
¡ # Split the list on that
J # Join each inner list of strings to a single string
Ç # Convert each string to a list of codepoint integers
δ # For each list of integers:
2 β # Convert from a base-2 list to a base-10 integer
Ž4w% # Modulo-1078 on each value
è # And then (modulair 0-based) index them into the string
# (after which the result is output implicitly)
```
[See this 05AB1E tips of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž´Š` is `45783` and `Ž4w` is `1078`.
]
|
[Question]
[
# Introduction
My car speedometer was hacked! Instead of showing me how fast i'm driving, it just shows: "Vroooom!" Please help me know how fast i'm going.
# Challenge
Take a string as input, and check if it matches the regex `/^[Vv]ro*m!$/m`. In English that means any line of the string must start with a capital or lowercase `v`, then a lowercase `r`, then any amount (including zero) of the lowercase letter `o`, then the exact string `m!`. There may be other lines, but the Vroom string must be on it's own line.
If you find a match, then you must count the amount of `o`'s in the Vroom string and output it. If you don't find a match however, you should output any default value that can't be outputted otherwise (like `-1` or an empty string)
# Reminders
* I/O is in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are banned
* Submission may be a full program or function
* Input is guaranteed to only have 1 Vroom string
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the [shortest code](https://codegolf.meta.stackexchange.com/questions/10145/how-to-count-bytes-faq) in bytes wins. **However**, I will not mark any answer as accepted.
# Test cases
**Input**
```
Vrom!
```
**Output** `1`
**Input**
```
vrooooooom!
```
**Output** `7`
**Input**
```
Hello, Vroom!
```
**Output** `(none)`
**Input**
```
Foo bar boo baz
Vrooom!
hi
```
**Output** `3`
**Input**
```
Vrm!ooo
```
**Output** `(none)`
**Input**
```
PPCG puzzlers pie
```
**Output** `(none)`
**Input**
```
hallo
vROOOm!
```
**Output** `(none)`
[Answer]
# [sed 4.2.2](https://www.gnu.org/software/sed/), 20 bytes
`-nr` options required at the command-line.
```
s/^[Vv]r(o*)m!$/\1/p
```
This outputs the speed in [unary](https://codegolf.meta.stackexchange.com/a/5349/11259) as the number of `o`s.
[Try it online!](https://tio.run/##K05N@f@/WD8uOqwstkgjX0szV1FFP8ZQv@D/f7f8fIWkxCKFJDBdxRVWlJ@fn6vIlZH5L7@gJDM/r/i/bl4RAA "sed 4.2.2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~56~~ 53 bytes
```
lambda x:len(re.search('^[Vv]r(o*)m!$',x,8).group(1))
```
[Try it online!](https://tio.run/##HcmxCsIwEADQvV9xDULvpBR0EsHVT@giCommJtDkwjWV6s/H0ukNL32z43gsPiSWDGLLcBl1MC8Ny3m0EcV2k9XydNg8bv3nLsh7CvWuaZf2RN1beE54ICpJfMwwoFLqygxGC5jNX9ULM4e6cn5NKn8 "Python 2 – Try It Online")
Basic regex and grouping, uses re.MULTILINE flag (which has a value of 8) and re.search to ensure it works for multiline inputs. Raises an exception when no match is found. Thanks to @ovs for the -3 bytes from `(re.M == 8)` tip.
[Answer]
# [R](https://www.r-project.org/), ~~62 60 58~~ 44 bytes
```
nchar(grep("^[Vv]ro*m!$",readLines(),v=T))-4
```
[Try it online!](https://tio.run/##K/r/Py85I7FII70otUBDKS46rCy2KF8rV1FFSacoNTHFJzMvtVhDU6fMNkRTU9fkv1t@vkJSYpFCEpiu4gorys/Pz1Xkysj8DwA "R – Try It Online")
@Giuseppe with 14 bytes golfed.
Original approach with explanation:
```
function(x)attr(el(regexec("(?m)[Vv]r(o*)m!$",x,,T)),"m")[2]
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCM7GkpEgjNUejKDU9tSI1WUNJwz5XMzqsLLZII19LM1dRRUmnQkcnRFNTRylXSTPaKPZ/moZSWFE@EOQqKmlygXmJCCaM5ZGak5Ovo8AFUQpWzRWeX5STApT/DwA "R – Try It Online")
R has seven pattern matching functions. The more commonly used ones are `grep`, `grepl`, and `sub`, but here's a nice use for `regexec`.
`regexec` gives you a bunch of things, one of which is the length of any captured substring, in this case the `(o*)` part of the multiline regex.
The `attr(el .... "m")[2]` stuff is a golfy way to get the desired number.
Returns `NA` if there is no match.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 41 bytes
```
a=>(l=/[Vv]r(o*)m!/.exec(a))&&l[1].length
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1k4jx1Y/OqwstkgjX0szV1FfL7UiNVkjUVNTTS0n2jBWLyc1L70k439yfl5xfk6qXk5@ukaaRoJbfr5CUmKRQhKYruIqK8rPz89V5MrITNDUtP4PAA "JavaScript (Node.js) – Try It Online")
[Answer]
# Powershell, ~~62~~ ~~58~~ ~~53~~ 48 bytes bytes
```
"$($args|sls '(?m-i)^[Vv]ro*m!$'|% M*)".Length-4
```
returns numbers of `o` in a first `Vroom!`, or -4 if `Vroom!` not found.
Notes:
* `sls` is alias for [Select-String](https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Select-String);
* `(?m-i)` inside regexp means:
+ Use multiline mode. `^` and `$` match the beginning and end of a line, instead of the beginning and end of a string.
+ Use case-sensitive matching
* `|% M*` is [shortcut](https://codegolf.stackexchange.com/a/111526/80745) for the property `Matches`, which gives a first match because we don't use `-AllMatches` parameter.
Test script:
```
$f = {
"$($args|sls '(?m-i)^[Vv]ro*m!$'|% M*)".Length-4
}
@(
,('Vrom!',1)
,('vrooooooom!',7)
,('Hello, Vroom!',-4)
,('Foo bar boo baz
Vrooom!
hi',3)
,('Vrm!ooo',-4)
,('PPCG puzzlers pie',-4)
,('hallo
vROOOm!',-4)
,('
Vrooom!
Vrooooom!
',3) # undefined behavior.
,('vrm!',0) # :)
) | % {
$n,$expected = $_
$result = &$f $n
"$($result-eq$expected): $result"
}
```
Output:
```
True: 1
True: 7
True: -4
True: 3
True: -4
True: -4
True: -4
True: 3
True: 0
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 83 bytes
```
($args-split"`n"|%{if(($x=[regex]::Match($_,"^[Vv]ro*m!$")).success){$x}}).length-4
```
[Try it online!](https://tio.run/##HcWxDoIwEADQna@ApobWCJMTiaubKwtBLU2lTQpH7qo2It9eE9/yFngbJGu8T0lwhSNVtHgX2H1m393qHkLweOrQjCb2TXNRQVvBbwd27dpXj7CfCs6krOmptSGSK4/bJmtv5jHY6phSKs8A@aAwH/5/shYBYCoy68of "PowerShell – Try It Online")
`-split`s the input `$args` on ``n`ewlines, pipes those into a for loop. Each iteration, we check whether our `[regex]::Match` is a `.success` or not. If so, we leave `$x` (the regex results object) on the pipeline. Outside the loop, we take the `.length` property -- if it's the regex results object, this is the length of the match (e.g., "Vroom!" would be 6); if it's not a regex results object, the length is zero. We then subtract `4` to remove the counts for the `Vrm!` and leave that on the pipeline. Output is implicit. Outputs a `-4` if no match is found.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 21 bytes
```
L$m`^[Vv]r(o*)m!$
$.1
```
[Try it online!](https://tio.run/##K0otycxLNPz/30clNyEuOqwstkgjX0szV1GFS0UPKOyWn6@QlFikkASmq7jCivLz83MVuTIyAQ "Retina – Try It Online") Explanation: `L` lists matches, so if the regex fails to match then output is empty. `$` causes the result to be the substitution rather than the match. `m` makes it a multiline match (the equivalent to the trailing `m` in the question). The `.` in the substitution makes it output the length of the capture in decimal.
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~99~~ 82 bytes
```
I INPUT POS(0) ('V' | 'v') 'r' ARBNO('o') @X 'm!' RPOS(0) :F(I)
OUTPUT =X - 2
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/35PT0y8gNEQhwD9Yw0BTQUM9TF2hRkG9TF1TQb1IXcExyMnPX0M9H8h1iFBQz1VUVwiCKOW0ctPw1OTi9A8NAem3jVDQVTDicvVz@f/fLT9fISmxSCEJTFdxhRXlg0CuIldGJgA "SNOBOL4 (CSNOBOL4) – Try It Online")
Pretty direct SNOBOL translation of the spec, reads each line until it finds one that matches `^[Vv]ro*m!$`, then outputs the length of the `o*` bit.
Enters an infinite loop if no `Vroom!` can be found.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 26 bytes
```
{-!/^^[V|v]r(o)*m\!$$/+$0}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WldRPy4uOqymLLZII19TKzdGUUVFX1vFoPZ/cWKlQpqGSrymQlp@EZdSWn5@TF5ZUX5@rmJMXlJikZIOl1JZUa4iiA4DCoMBhAtUlav0HwA "Perl 6 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 188 183 bytes
Why use regexes when you can use a state machine instead? :-)
```
a,b;f(char*s){for(a=b=0;a<5;s++){!a&*s==86|*s=='v'?a++:a==1&*s=='r'?a++:a==2?*s-'o'?*s-'m'?0:a++:b++:a==3&*s==33?a++:!*s&a==4?a++:*s-10?(a=-1):a-4?(a=0):a++;if(!*s)break;}s=a<5?-1:b;}
```
[Try it online!](https://tio.run/##fVPbjtowEH33VxiqJXYuVbJsqxVZNw/V0lZCZVWpfQEekpCA1VxQ7ERaaL6djhPMpVUbgew553g8ZyaJnU0cH9/wIs7qdYKfhFzz8u32A7qGKl5s/sTWGY8AO4Z25Kck3oaVKeghLSsSsoi5fvj0zheWRQ@DcGQKxh7f/1KL0RhBaFmTkDGvw43qDNwHpnCM0uiW3AjciSKinhx36vG4Ew9MMQLsoQtA7bkBXOt4dBI6D2rrUnXW5ykBKY2qJPzpt4JBUYHjTSK/PaqKsblJZF5nkpPpl9kzNlOKDwjjnhM2jm0c1eni0V2xg9v6QPFCKigu60LaGFpz2gGWJQUTfJ@UKYGI@gjkqh@Cff0@m13ETJ@HLmESsxSKiElK6YA9z6d@XwLc1KXphaxPrymMBQNLWVbGRFwSW73K8qivZbIq4t0rEdZNpbrca12f4XTRGV9oZsWMpWto/MpBh7TohC40Y1krFitSUVdWtIV/Gug32sL/DPT5TrrFXzkuFbdqElUi66rAwkcQqinmIS9IU/L1zczZ@Y1QX0JBbWzClWYN/0bPn59HK5nwsYQpSlbT0YhAA@@pttiwvHfoWYQzQmoGNcKPQMLhslgWQ0qD2pETwKDnRFJ4bm03NgYxP6HNgl@PYQefpUzJ8E5ghu/WkM/GcCAljU6TVkkCkR5DFwoI2@OPqswHCDVV2T8q@JxAtTYGqgunZYkj6EnUrXukcEVsOYJ9PoAIoZeXj5/wrt7vs6QSeMcThLbKNGq@zefzfPAb "C (gcc) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
∞╠mQ╛3mQ->n▀÷↕┐ò
```
[Run and debug it](https://staxlang.xyz/#p=eccc6d51be336d512d3e6edff612bf95&i=Vrom%21%0A%0Avrooooooom%21%0A%0AHello,+Vroom%21%0A%0AFoo+bar+boo+baz%0AVrooom%21%0Ahi%0A%0AVrm%21ooo%0A%0APPCG+puzzlers+pie&a=1&m=1)
[Answer]
# [Haskell](https://www.haskell.org/), ~~75~~ ~~71~~ 69 bytes
```
f s=[length n-2|r<-lines s,n<-scanr(:)"m!"$'o'<$r,v<-"Vv",r==v:'r':n]
```
[Try it online!](https://tio.run/##HcWxCsMgEADQPV9xEcEWtENH0bWfkKV0MMFUqbmDUyyU/ruFvuWlUF@xlDF2qP5eIj5bAjTXLztTMsYKVaMzdQvIJ3sWxyykIuUk6@6MWLrQ7H23ipXFxzhCRvCQsUUOWwMJNdEbLrCPGxGsgWH9/5kWJqJjnlL@AQ "Haskell – Try It Online")
No regex. Instead builds all valid `Vrooom!`-strings up to a sufficient length and compares the lines of the input against them, collecting the number of `o`s in a list. Thus for invalid inputs an empty list is returned.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~104~~ 100 bytes
```
s;main(c,n){for(;gets(&s);sscanf(&s,"v%*[o]%nm%c%c",&n,&c,&c)-1||c-33?:printf("%d",n-2))s=s-768|32;}
```
[Try it online!](https://tio.run/##JYxBC4JAFITv71eswoobu4cSKpLoEFQ3pUOX6KAvLcHdlV3zYPbbba3hwcz3BgbFA3EcbSyzSoXIFXuX2oTxo2htGFgWW4uZKl3kfkdnV32jSlKk6PNA8QDdMTEfBhRRtNs0plJtGfr07nMlFozZrRWr5XqIFvFnHC9GSw@gM/qvCU5FXWtOXPXDg9YkzwzJf97D9J@KZwUuS88RQJruj6R59X1dGEuaqgB4Zm4GunOSJNL7Ag "C (gcc) – Try It Online")
Output the `n` for each valid line, exactly in the requirement(nothing if no valid line, the `n` if exactly one)
```
int s; // Use as a char[]
main(c){
while(gets(&s)) {
s=s-768|32; // byte 0: 'V'=>'v'; byte 1: 'r'=>'o', 'o'=>'l'
if (sscanf(&s,"v%[o]m%c%c",&s,&c,&c)==2 && c=='!') {
// The last '%c' get nothing if it's EndOfLine
printf("%d",strlen(&s)-1))
}
}
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 bytes
```
fè`^[Vv]*m!$` ®èo
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=ZuhgXltWdl2eKm0hJGAgruhv&input=W1siVnJvbSEiXSwKWyJ2cm9vb29vb29tISJdLApbIkhlbGxvLCBWcm9vbSEiXSwKWyJGb28gYmFyIGJvbyBiYXoiLCJWcm9vb20hIiwiaGkiXSwKWyJWcm0hb29vIl0sClsiUFBDRyBwdXp6bGVycyBwaWUiXSwKWyJoYWxsbyIsInZST09PbSEiXV0KLVFt)
Saved a byte by taking input as an array of lines.
Includes an unprintable character between `]` and `*`.
Explanation:
```
fè Get the line(s) that match
`^[Vv]*m!$` The provided RegEx with a little compression
®èo Count the number of "o" in that line if it exists
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 138 124 bytes
Here's the boring regex way.
```
#include<regex.h>
f(char*s){regmatch_t m[9];regcomp(m+2,"^[Vv]r(o*)m!$",5);s=regexec(m+2,s,2,m,0)?-1:m[1].rm_eo-m[1].rm_so;}
```
[Try it online!](https://tio.run/##fVNdb9owFH33rzBsbW0SKkCatDX1@jCVbhIa1aT1JbAKjAOW4hjZTrSB@O3sOsF8bNoiEL7nHB/f4xt4d8n5/o0seF4uBL63biH17eojOoeMLJZ/YotczgE7br03Yil@elVG@GpmOpZuAVIzx1evDqv0wzSBmmu1JioaxO0f6Us1NUR3qGq9bcfvaGJZ7SF4LbDxIFZxjz50@3cq7U9vjXoVuhuWVie7vT8Id5bCqTJ3kgy/jB5xJ6N4izBuOBtjHuN5maXve1O27e0SoGThPMR1WbgYQ77DCrBcFMzKjdAZgYomCOSZNsSyr99Ho5OYhf2sl2DCWQZNcJJR2mKP42HStAAn1TaNkDX2gcLY553luebEnoyjRhX1aRJkzhR8/YvY6KLT0O65rnE4HHTE08BM2c2kdxPwswQ1skMHNA1MFE0Z96SnzqKECP8M0CxChP8FaPwOuvQvj1PHOz8JI1xpCmwTBKWfoprJglRaLi5mzo5vhH@dCxrjDhzZKeFbhfnL42gdswl2MEXHSnp9TeACBzRErJhqEvYjIhkhJYMe4UPAsD0pJkWb0oey6@4AgzsnjsJzGbuKMYjlAa1SeT6GNfy3XEbaVxYzfLUAvxjDhoxUwSYzQkAVxlCXFsrd/sVo1UKoMrp5fPFZQLcxBqouh1rjOdzJvP7dII97YiURrFULKoSenz894XW52eTCWLyWAqGVD42qb@PxWLV@Aw "C (gcc) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 28 bytes
```
IJjb.nm:rd0"^vro*m!$"1.z/J\o
```
[Try it online!](https://tio.run/##K6gsyfj/39MrK0kvL9eqKMVAKa6sKF8rV1FFyVCvSt8rJv///@T8lFSF9PycNK6wovz8/FxFrozUnJx8AA "Pyth – Try It Online")
[Answer]
# Pyth, 20 bytes
```
/R\o:#"^Vro*m!$"1cQb
```
Outputs as a list containing only the number of 'o's, or an empty list if there's no Vroom.
[Try it here](http://pyth.herokuapp.com/?code=%2FR%5Co%3A%23%22%5EVro%2Am%21%24%221cQb&input=%22Foo%20bar%20boo%20baz%5CnVrooom%21%5Cnhi%22&debug=0)
### Explanation
```
/R\o:#"^Vro*m!$"1cQb
cQb Split on newlines.
:#"^Vro*m!$"1 Filter the ones that match the regex.
/R\o Count the `o`s in each remaining element.
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 21 bytes
```
a~,`^[Vv]r(o*)m!$`#$1
```
[Try it online!](https://tio.run/##K8gs@P8/sU4nIS46rCy2SCNfSzNXUSVBWcXw////YUW5ivn5@VxlQfn5uYpcZUVADpABAA "Pip – Try It Online")
Match regex `^[Vv]r(o*)m!$` in multiline mode; output length of capture group.
[Answer]
# [sfk](http://stahlworks.com/dev/swiss-file-knife.html), 94 bytes
```
xex -i -case "_[lstart][char of Vv]r[chars of o]m![lend]_[part 4]o_" +linelen +calc "#text-1"
```
[Try it online!](https://tio.run/##HYxBCsMgEEX3OcWPXQYXhZ6hR8hGBjF2QqQmU1SC9PLWZvV4j8/P67u1yhU6QHuXGcqamItLhYzfXIKsmE9Kl@S/Ce2jiXy8yJpP3@FBYhWmGA7uGZN30UPdCtei7wqtPUWw9Kvl4neYk@zjsIUf "sfk – Try It Online")
Gives `-1` when you're not vrooming.
[Answer]
# [Red](http://www.red-lang.org), 104 bytes
```
func[s][n:""if parse/case s[opt[thru"^/"]["V"|"v"]"r"copy n any"o""m!"opt["^/"to end]][print length? n]]
```
[Try it online!](https://tio.run/##bY0xb4MwFIR3/4rHzY2yZ@lQKc1GlIHFciUHngsS2NazQQptfzuBZkxuueG@uxNulgs32ih3WNzoa52M9gegcxStJN7XNjElHWLWuZURX3sYjQq/mGAgqEO8kSfrbwjAUGAjNyoHYt8Yo6N0PlPP/ju37@SNWRwRJgkPrRX1QLDbBOUIJ@778EaVvM5/jiHQ1Qpd/31WG7iSqu3@nscqGYo1Bj3vtHb9UdOlLMuheFE9nz8@KY7z3LMkih1DLXc "Red – Try It Online")
A straightforward solution. Red's `parse` is cool and readable, but too long compared to regex
```
Red []
f: func [ s ] [
n: ""
if parse/case s [
opt [ thru newline ]
[ "V" | "v" ]
"r"
copy n any "o"
"m!"
opt [ newline to end ]
] [ print length? n ]
]
```
[Answer]
# J, 35 bytes
```
(]{~0<{.)(1{'^[Vv]r(o*)m!'rxmatch])
```
Returns negative 1 if the pattern doesn't match.
[Answer]
## JavaScript, 90 73 61 bytes
```
_=>_.replace(/^[Vv]r(o*)m!$|[^\1]/mg,(m,a)=>a||'').length||-1
```
[Try it online!](https://tio.run/##TYzLCoMwEEX3fkWEgknxgR9gN4V2qXThxvqINj5K4ki0UiT/bq2IeDcz99yZ@6Yj7QvZdIPVwovNpTen3iW1Jes4LRh2kigcY4nhTIR@UlHydGNHVCYWJiXehSplGMTmrK2GWinLnQtoe@DM5lDhEmejhIOE/tUWIvSMmGhJw8O@X@7kBoByKlG@zkkL5ZpqdbO/C31BmwuC6x11n2niTPaoa9jGa8o5aOPD9/1/NZl/)
Replace characters that are not captured at `(o*)` with empty string, return `length` of string containing only `"o"` or `-1` if resulting string is empty.
[Answer]
# Ruby, 32 bytes
```
->n{n=~/^[Vv]r(o*)m!$/m;$1.size}
```
Matches the string to the regex, then uses Ruby's magic regex group variables to get the first group's size.
Call it like so:
```
x=->n{n=~/^[Vv]r(o*)m!$/m;$1.size}
x["Vrooooooooooooooooooooom!"] # returns 21
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~28~~ 29 bytes
```
p$_[/^[vV]r(o*)m!$/].count ?o
```
[Try it online!](https://tio.run/##KypNqvz/v0AlPlo/LrosLLZII19LM1dRRT9WLzm/NK9EwT7///@wovxcRa6yIjCRnw/ieKTm5OTrKIC4QF5YkL@v4r/8gpLM/Lzi/7p5AA "Ruby – Try It Online")
Multi-line strings require three more bytes. I'm not sure if that's a hard requirement. If so, I'll update this.
```
->l{l[/^[Vv]r(o*)m!$/].count ?o}
```
[Answer]
# [Clojure](https://clojure.org/), 90 bytes
```
#(do(def a(clojure.string/replace % #"(?ms).*^[Vv]r(o*)m!$.*""$1"))(if(= a %)-1(count a)))
```
[Try it online!](https://tio.run/##JchBCoAgEADAr2ymsCtk@IDoF12iQNSiqAy1vm@H5jj2CPsTfSk1uoDOL2DQ/qdSjtu1ttHfh7EeBNQM@zORkvM4vFPEIOmsuJKMcc2IcFuwAwOCGo02PFcGQ0SlfA "Clojure – Try It Online")
This anonymous function returns the number of "o"s in the vroom string, or -1 if there is no valid vroom string.
### Readable version
```
(fn [s]
(def a (clojure.string/replace s #"(?ms).*^[Vv]r(o*)m!$.*" "$1"))
(if (= a s) -1 (count a)))
```
### Explanation
```
#"(?ms).*^[Vv]r(o*)m!$.*" ; This regex matches any string that contains a valid vroom string. The first capturing group contains only the "o"s in the vroom string
(clojure.string/replace s #"(?ms).*^[Vv]r(o*)m!$.*" "$1") ; Replaces a match of the above regex with its first capturing group. The resulting string is stored in the variable a
(if (= a s) -1 (count a))) ; a equals s if and only if there is no valid vroom string, so if a equal s we return -1. If there is a valid vroom string, a contains only the "o"s from the vroom string, so we return the length of a
```
[Answer]
# perl -nE, 35 bytes
```
$s=length$1if/^[Vv]r(o*)m!$/}{say$s
```
This uses the *Eskimo greeting* (`}{`) which abuses the a quick on how the `-n` option is dealt with by perl.
[Answer]
# Java 8, 109 bytes
```
s->{int r=-1;for(var l:s.split("\n"))r=l.matches("[Vv]ro*m\\!")?l.replaceAll("[^o]","").length():r;return r;}
```
[Try it online.](https://tio.run/##lVA9b8IwEN35FYenuIJIXYloVVVquxRQkbIQKjnBEFPHjs4moqD89vQSGLpUpB5s@fye38deVGK833w1mRbOwbtQ5jwAUMZL3IpMwqy9dgPIgqVHZXbgeETDekCb88KrDGZgYNq48cO5BeJ0fB9tLQaVQNATF7pSKx@wxDDOcarDQvgsly5gq7hao70rkmTI@KMOUZaaVJ@0prdPu2Yjxniopdn5POATjFD6AxrAqG6iVr88pJr0rzYqqzZQUIar09UaBL8EWH47L4vQHnxY0pPXJjBhFrAYbUHaXaK/URXay@qBfZNa2xHQx33QL9ZCSjWl3XlKTMsjYmJydZMcYzEk9E3cYvH8SlWdTlqig1LJm4xcUIjEVB/z@bxHiiNBsTV97OFZ/Kfwa@udQJ8@4@p37/Wgbn4A)
**Explanation:**
```
s->{ // Method with String parameter and integer return-type
int r=-1; // Result-integer, starting at -1
for(var l:s.split("\n")) // Loop over the lines:
r=l.matches("[Vv]ro*m\\!")? // If the current line matches the regex:
l.replaceAll("[^o]","").length()
// Change `r` to the amount of "o"'s in it
: // Else:
r; // Leave the result `r` unchanged
return r;} // Return the result
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 134 122 bytes
```
for(var a="";a!=null;a=Console.ReadLine())if(new Regex(@"^[Vv]ro*m!$").Match(a).Success)Console.Write(a.Count(x=>x=='o'));
```
[Try it online!](https://tio.run/##XY3NagIxFIX3fYo7g2AiNC8QUirSnW6q2EVp4RKvNpDJbfMzRsRnn2ZTkJ7dOXC@z6ZHy5Gmklw4wfaSMg0a7ptau/Dzb9pRzeqVTsVjfKnfkVJyHJJ@sB5TgiVcIWXMzsLI7gAbdEFIuE5HjmLECGj6XmNnQvFeo1m1L3tqRDw0Gwkp3VEEOkNzUBXP/ef7fvyIvBi6WS/VBrP9EijVtljb3PIP8BZdJoFqxSVkUc1TNWbOcyn1dLtN@8j3Gbpf "C# (.NET Core) – Try It Online")
*-12 bytes: moved* `null` *check into* `for` *loop and removed brackets*
Ungolfed:
```
for(var a = ""; a != null; a = Console.ReadLine()) // initialize a, and while a isn't null, set to new line from console
if(new Regex(@"^[Vv]ro*m!$") // set regex
.Match(a).Success) // check if the line from the console matches
Console.Write(a.Count(x => x == 'o')); // write the number of 'o's to the console
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~39~~ 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
|ʒć„VvsåsÁÁD…m!rÅ?s¦¦¦Ù'oså)P}Dgi`'o¢
```
Although 05AB1E is a golfing languages, regex-based challenges are definitely not its strong suite, since it has no regex-builtins.
Outputs `[]` if no match was found.
[Try it online](https://tio.run/##yy9OTMpM/f@/5tSkI@2PGuaFlRUfXlp8uPFwo8ujhmW5ikWHW@2LDy0DwcMz1fOBkpoBtS7pmQnq@YcW/f/vlp@vkJRYpJAEpqu4yoryE0EwVxHIBOrOBzPygQDICCtKTATLBPn7KnJlZAIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/U5OOtD9qmBdWVnx4afHhxsONLo8aluUqFh1utS8@tAwED89UzwdKagbUuqRnJqjnH1r0v1bnf3S0UlhRfq6iUqyOQrRSWVE@BMAEPFJzcvJ1FIBK4EJu@fkKSYlFCklgukpJB2QAWFpHKSMToiasKFcRKAbhBAQ4uysUlFZV5aQWFSsUZKZChDMSgUYD9ZQF@fv7@8IdgNsaoOMSQRBsE0hhUT6UmQ@zP6woMREqHwQyE@EiuPrYWAA).
**Explanation:**
```
| # Get the input split by newlines
ʒ # Filter it by:
ć # Head extracted: Pop and push the remainder and head-character
# i.e. "vrm!" → "rm!" and "v"
# i.e. "Vroaom!" → "roaom!" and "V"
„Vvså # Is this head character in the string "Vv"?
# i.e. "v" → 1 (truthy)
# i.e. "V" → 1 (truthy)
s # Swap so the remainder is at the top of the stack again
ÁÁ # Rotate it twice to the right
# i.e. "rm!" → "m!r"
# i.e. "roaom!" → "m!roao"
D # Duplicate it
…m!rÅ? # Does the rotated remainder start with "m!r"?
# i.e. "m!r" → 1 (truthy)
# i.e. "m!roao" → 1 (truthy)
s¦¦¦ # Remove the first three characters from the duplicated rotated remainder
# i.e. "m!r" → ""
# i.e. "m!roao" → "oao"
Ù # Uniquify, leaving only distinct characters
# i.e. "" → ""
# i.e. "oao" → "oa"
'oså '# Is this uniquified string in the string "o"?
# i.e. "" → 1 (truthy)
# i.e. "oa" → 0 (falsey)
)P # Check if all three checks above are truthy
# i.e. [1,1,1] → 1 (truthy)
# i.e. [1,1,0] → 0 (falsey)
} # Close the filter
D # After the filter, duplicate the list
gi # If its length is 1:
# i.e. ["vrm!"] → 1 (truthy)
# i.e. [] → 0 (falsey)
` # Push the value in this list to the stack
# i.e. ["vrm!"] → "vrm!"
'o¢ '# And count the amount of "o" in it (and output implicitly)
# i.e. "vrm!" → 0
# (Implicit else:)
# (Implicitly output the duplicated empty list)
# i.e. []
```
[Answer]
## C++, MSVC, ~~164~~ 159 bytes
-5 bytes thanks to Zacharý
It compiles even with the `regex` header only
```
#include<regex>
using namespace std;int f(vector<string>i){smatch m;for(auto&e:i)if(regex_match(e,m,regex("^[Vv]ro*m!$")))return m[0].str().size()-4;return-1;}
```
Tests :
```
std::cout << "Vrom!" << " -> " << f({ "Vrom!" }) << '\n';
std::cout << "vrooooooom!" << " -> " << f({ "vrooooooom!" }) << '\n';
std::cout << "Hello, Vroom!" << " -> " << f({ "Hello, Vroom!" }) << '\n';
std::cout << "Foo bar boo baz \\n Vrooom! \\n hi" << " -> " << f({ "Foo bar boo baz", "Vrooom!", "hi" }) << '\n';
std::cout << "Vrm!ooo" << " -> " << f({ "Vrm!ooo" }) << '\n';
std::cout << "PPCG puzzlers pie" << " -> " << f({ "PPCG puzzlers pie" }) << '\n';
std::cout << "hallo \\n vROOOm!" << " -> " << f({ "hallo", "vROOOm!" }) << '\n';
```
]
|
[Question]
[
We define the function **g** as **g(n) = n XOR (n \* 2)** for any integer **n > 0**.
Given **x > 0**, find the smallest integer **y > 0** such that **gk(y) = x** for some **k > 0**.
## Example
```
x = 549
549 = 483 XOR (483 * 2) (as binary: 1000100101 = 111100011 XOR 1111000110)
483 = 161 XOR (161 * 2) (as binary: 111100011 = 10100001 XOR 101000010)
```
Which means that **g2(161) = 549**. We can't go any further, as there is no **n** such that **g(n) = 161**. So, the expected output for **x = 549** is **y = 161**.
## Rules
* You are not supposed to support invalid entries. A pair **(y, k)** is guaranteed to exist for the input value **x**.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
## Test cases
```
3 --> 1
5 --> 1
6 --> 2
9 --> 7
10 --> 2
23 --> 13
85 --> 1
549 --> 161
960 --> 64
1023 --> 341
1155 --> 213
1542 --> 2
9999 --> 2819
57308 --> 19124
57311 --> 223
983055 --> 1
```
[Answer]
# Java 8, ~~68~~ ~~57~~ ~~53~~ 52 bytes
```
n->{for(int i=0;i<n;)i-=(i*2^i)==n?n=i:-1;return n;}
```
-5 bytes thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##XZFPb4JAEMXvfoqJJ6iBsCAWXbf9BPXisX@SLWIzioOBwaQhfHa6bjmw7mGSN5n3y8vbk77p4HQ4D3mpmwbeNFIHMANA4qI@6ryAXWekXUDu3Sf50mz6mRkNa8YcdkCgYKDgpTtWtT1CFUnckvQxUB4@xV/oK0WvpHATCFkX3NYEJPtB3jnX9rs0nBF3q/AAFxPF23ON9PP@Cdr/T8FFw15iA4winYrVVKynQkRTFTuIzGGkS8e4XkUux/UKkTpukS5jx26eQ39OouxhIYTjyJJoZE47tqXYA1vv2Mf@t@HiElYth1dTFZfk4WK@@eD5gkLzXf7I6Yc/)
**Explanation:**
```
n->{ // Method with integer as both parameter and return-type
for(int i=0;i<n;) // Loop `i` in the range (1,n)
i-=(i*2^i)==n? // If `i*2` XOR-ed with `i` equals `n`
n=i // Set `n` to `i`, and set `i` to 0 to reset the loop
: // Else:
-1; // Increase `i` by 1 to go to the next iteration
return n;} // Return `n` after the entire loop
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~54~~ 53 bytes
```
f=lambda n:next((f(i)for i in range(n)if n==i^i*2),n)
```
[Try it online!](https://tio.run/##FY3NCsIwEITvPsUeE5lDfrq1KfRJRKFiowu6LaWH@vQxncPAfHwwy297zxpKycNn/D6eI2mv074Zk43YPK8kJErrqK/JqJVMOgxyl3OwUFsOQatwjWC0SPAOIaJjcJOQWldB3d4zw3MTkGrAl@i6o71H6qJjvvUnWlbRjXJ9KX8 "Python 2 – Try It Online")
[Answer]
# JavaScript, 53 bytes
```
f=x=>(i=0,y=(G=x=>x&&(i^=x&1)+2*G(x>>1))(x),i?x:f(y))
```
`G` is `g^-1`, which set `i` to `0` if success, set `i` to `1` if failed.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~13 12~~ 10 bytes
*Saved 1 byte thanks to @MrXcoder, and 2 more bytes following their suggestion*
```
fqQ.W<HQxy
```
[Try it online](https://pyth.herokuapp.com/?code=fqQ.W%3CHQxy&input=1023&debug=0)
Explanation:
```
fqQ.W<HQxyZZT Implicit: Q=eval(input()), trailing ZZT inferred
f Return the first T in [1,2,3...] where the following is truthy
.W T Functional while - loop until condition is true, starting value T
<HQ Condition: continue while iteration value (H) less than input
xyZZ Body: xor iteration value (Z) with double (y) iteration value (Z)
qQ Is the result of the above equal to input?
```
[Answer]
# [R](https://www.r-project.org/), ~~73~~ 65 bytes
```
f=function(x){for(i in 1:x)if(x==bitwXor(i,i*2)){i=f(i);break};i}
```
[Try it online!](https://tio.run/##RY3dCoMwDEbvfYpcNqMDq6tzP77H7oZKC2GuG7Yyh/jsLh0bBr4EDod8/bLYyg6uDfRwYsTJPnpBQA7UcUSyYqyqhsLrErGkTYY4UWUF4anpTX2bTzQvwfhwbWtvPJy30IocJGhOwTlwVCohyyWUEerdgWmRRhyhUlrz1ruMMQ8b@zwtv0cpZmWeao1Jb/zQhW/D4DryQXT189m9xdouwSImrr4bL346Rn81/l@WDw "R – Try It Online")
Thanks a lot [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) (-8) due to your tweaks, so simple yet very effective
[Answer]
# JavaScript, ~~38~~ 36 bytes
```
f=(n,x=n)=>x?x^x+x^n?f(n,--x):f(x):n
```
[Try it online](https://tio.run/##VY3LCoMwFER/xUUXCd4Eo6Y0hehHdNlWEnwUxd6ISgmUfnuaLjuLgTlnMZN92a1dx2Vn6Lo@hEETBK@R6srXvvGpb7AeImPM0/NAYmFoHW5u7vnsHuRagIQjKBAZ5AWcJMhSgTpmEcQthJQgZJmDirnzp12I15U5vP3H8MV2l92uOylpahLGqsSkUf1u/i3lkxvR3NDQ8AU) - Starts throwing overflow errors somewhere between `9999` & `57308`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes
Use `⁺¿` to return the last non-zero element (thanks Dennis for -1 byte)
```
^Ḥ)i$⁺¿
```
[Try it online!](https://tio.run/##y0rNyan8/z/u4Y4lmpkqjxp3Hdr//3D7o6Y1//9HG@uY6pjpWOoYGugYGetYmOqYmljqWJoZAAWAfENDU1MdQ1MTIx1LINAxNTc2sACRhoY6lhbGBqamsQA "Jelly – Try It Online")
Brute force wins again :(
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~57~~ ~~56~~ ~~55~~ 51 bytes
* Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat); `!=` ~ `-`.
* Saved ~~a byte~~ five bytes thanks to [Rogem](https://codegolf.stackexchange.com/users/77406/rogem); making use of the ternary expression and gcc quirks.
```
X(O,R){for(R=1;R;O=R?R:O)for(R=O;--R&&(R^2*R)-O;);}
```
[Try it online!](https://tio.run/##Zc7daoMwFMDx6/UpgsOSMyJ4orGmIfgIQuiFF2MgfozA5orurvTZnUu2lHW5OeHH4Z90yWvXrWtDa2bgMn7M1GhURtXaVOZYg5daJYnZ76l54U8GklqBuq6P/TDaaSAnatkM59lOnyONGhoXPRCtSSx6ois3aLzA8xQxyxpqgc1uaD1X0bldlqGPjtHY2rftAmr33tqJwmX3cKLk@2TMDYQg4p8UXvhNpJdDEEzvd7gvYxakvC@L3HWwCCIL3ynyH8HUd7L8dwdRuA4PZRQ5//u63M4mvETpRRyytGQEJfI8CKLrcN@RZZaK2w@v6xc "C (gcc) – Try It Online")
[Answer]
# [Z80Golf](https://github.com/lynn/z80golf), 22 bytes
```
00000000: 1600 1803 4216 007a b830 097a 82aa b828 ....B..z.0.z...(
00000010: f314 18f3 78c9 ....x.
```
Port of @KevinCruijssen's Java answer
[Example with input of 9-Try it online!](https://tio.run/##jcwxCsMwEATAPq/YMpVZSUY6p8xPZBmlMbgLQZ9XVrEfkIWDPbibZnwde@2dVx5g5IKycQVZIgLLpmZEii6qOQPD7IHpF2reozxvp@BkuEjd59X0Li1l88hj9VYD3CyjhmTDaBKa3u/D@FyGl1EW/Jep9y8 "Z80Golf – Try It Online")
[Example with input of 85-Try it online!](https://tio.run/##jY7BboMwEETP8BVz7CFCawjOJlIP7S0fkA8wdt1UcqAKpmr5eTK0fEBHsna8mnnaWeV9SHFZZNMJYtsWPkgHEW/RiA90KjhYY@mMQpp9DVSXihK@r9W8ln8EQ4axwrzrlHU50mkNt35rjQ3MnozYHJSMaiZhZv1pZXxvjJoMf8T/VC3Luf@c8rO25cs4vt269IM43BGn3uePoYd3KcH1AcOUGTyVY3Z3jiIFdDvWit9ELAsXAk@@bgvlKfRXl/ID "Z80Golf – Try It Online")
Assembly:
```
;d=loop counter
;b=input and output
f:
ld d,0
jr loop
begin:
ld b,d
ld d,0
loop:
ld a,d
cp b
jr nc,end ; if d==b end
ld a,d
add d ; mul by 2
xor d
cp b
jr z,begin ; if (d*2)^d==b set b to d
inc d
jr loop
end:
ld a,b
ret
```
Assembly example for calling the function and printing the result:
```
ld b,9 ; input to the function, in this case 9
call f
add 30h ; ASCII char '0'
call 8000h ; putchar
halt
```
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 78 bytes
```
int g(int n){return f(n)%2<1?g(f(n)/2):n;}int f(int x){return 1>x?0:x^f(x/2);}
```
[Try it online!](https://tio.run/##XZFfa4MwFMXf@ykuhUJCmUu0dlbH@gn21Mf9gaxVSWvTYq6dQ/zsLhFZk@UhyQnn/ALnHsVNPBwPp2FfCa3hVUjVDVIhlMTuinZ1jk2toCCKLsJnvi2JvT6GNFVZbz3F6Gz/nPyl3bK0/SxIa1xZP2SzGcC1@arkHjQKNMftIg9wNp@RHdZSlW8fIGhnbACYayQRze4idsXaFRtXcOaq0EMkHiNeecHNmvkcP8t57KV5vAq9uFke/Sliyb8Hzr1EErGJ2dtu3FJGgy1UTn3sfjTm5@DSYHA1VWGlCMjlPH3H@RJU/j3OjNDADIzCxOyHXw "Java (JDK 10) – Try It Online")
[Answer]
# JavaScript (Node.js), ~~48~~ ~~45~~ 38 bytes
```
f=(n,i=0)=>i<n?i*2^i^n?f(n,i+1):f(i):n
```
-7 bytes thanks to @Neil creating a recursive version of my iterative version below. Doesn't work for large test cases.
[Try it online.](https://tio.run/##TczBDoIwDIDhO09BOG2iZgWGgA5exJAQBDJDOiOLrz/BZMWe/i1f@@w@3dK/9cue0DwG50bF8KiV4KrWN2z0IWl1i824/cbAq5FpXqGzw2JDFaKqe4OLmYfzbCaGcVTdbRSvmvNrEGyKpWv9QvrIfZQ@QPhKiBfkZUawzMW@s1sASRpklhBfh65cUlH8PQBIFanY9t0X)
---
Iterative **45 bytes** version that works for all test cases:
```
n=>{for(i=0;i<n;)i-=i*2^i^n?-1:n=i;return n;}
```
[Port of my Java answer.](https://codegolf.stackexchange.com/a/166272/52210)
-3 bytes thanks to *@Arnauld*.
[Try it online.](https://tio.run/##TczRDoIgGIbhc6/CeYQ5G6iYStSNNDdn0GjupyF10rp20jYwjt5/ez7uw2uYR6MeNgd9FU5yB/z0ltogxTFTR2CpyrnaFb3q4ZyTDrhiRtingRjYx1kx25jHy2jUMOtJ7Cd9Q5Al3cUmmUSQpiyKVoXKpX5BfdQ@Wh8E@yoCb4KnVYBtjbfNZgmhQRNaFYEvL/xyKHHzdxASVFPide@@)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
f=->x,y=x{y<1?x:x==y^y*2?f[y]:f[x,y-1]}
```
[Try it online!](https://tio.run/##ZZBNCsIwEEb3OUXAnTTSyZ9JMe1BQgUVg0vRFhJaz17TqDTY2czwZnh8zKM/h2lyhtS@CMYP4QCNr7wx4Ri2tHE2tJWzcUegfU0Wx2K42BBSzyMGlJpYI5kh@kE6Q/uEoFxd0UwPLCG10gu@uEAmpGXmkhzN8szF@HwFIBYXTXoQnP6F0LF@iCrQCIs9K9UXgQbKEwJYXJQhrVgZ9TiL2u6up8ttGLvx3ndP7GwXn/gG "Ruby – Try It Online")
As expected for the recursive version, complains about "stack level too deep" on the latter test cases.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 bytes
```
BÄḂṛḄß$Ṫ?
```
[Try it online!](https://tio.run/##y0rNyan8/9/pcMvDHU0Pd85@uKPl8HyVhztX2f8/3P6oac3//9HGOqY6ZjqWOoYGOkbGOhamOqYmljqWZgZAASDf0NDUVMfQ1MRIxxIIdEzNjQ0sQKShoY6lhbGBqWksAA "Jelly – Try It Online")
Tips: Use recursive function instead of loops.
---
Very fast, unfortunately loses to the brute force approach.
Note that:
* For *x > 0*, *f(x) > x*.
* *popcount(f(x))* is even, where *popcount(n)* is the number of bits set in *n*.
* If *n* has even popcount, then there exists *x* such that *f(x) = n*.
* Let *B(x)* be the binary representation of *x*, and *Ṗ(l)* be the list *l* with last element removed. Then *B(x)* is the accumulated XOR of *Ṗ(B(f(x)))*.
So, we repeatedly:
* Compute its binary representation (`B`)
* then take the accumulated XOR (use `^\` or `ÄḂ`, they have the same effect).
* Check if (`?`) the tail (last element) (`Ṫ`) of the accumulated XOR is nonzero (odd popcount)
+ If so, convert the binary list back to decimal and recurse.
+ If not, returns the input (`ṛ`).
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 71 bytes
```
: f 0 begin 2dup dup 2* xor = if nip 0 else 1+ then 2dup < until drop ;
```
[Try it online!](https://tio.run/##LYzhDoIwDIT/8xQXfmpG2NyIiPowygZLyLaMkfj22KJNvja9u9bFXGYxOR77foNDi5edfIAatwRGnfCJGQ94h@ATBeyyWsgzymz/uTu2UPyCMceEgf78TjWajKYGhHjW9Nvw/s4YqgtSZYiO6AnZUlOsXlk2msW@aw/r0KU07EijFVtUSPsX "Forth (gforth) – Try It Online")
### Explanation
```
0 \ add an index variable to the top of the stack
begin \ start an indefinite loop
2dup \ duplicate the top two stack items (n and i)
dup 2* xor = \ calculate i xor 2i and check if equal to n
if nip 0 \ if equal, drop n (making i the new n) and use 0 as the new i
else 1+ \ otherwise just increment i by 1
then \ end the if-statement
2dup < \ duplicate the top two stack items and check if n < i
until \ if previous statement is true, end the loop
drop \ drop i, leaving n on top of the stack
```
[Answer]
# [Perl 6](https://perl6.org), 44 bytes
```
{({first {($^a+^2*$a)==$_},^$_}...^!*).tail}
```
[Try it](https://tio.run/##XY5daoQwFEbfs4pbkKKjkzHROKZi6SL6WCxWMyD4hzqlRVxRd9GN2SSjMvU@JHDyfeemFV0ZzNdewGeAswih6hsesyYXEM@jOV6Krh9gNI0ktRN6MFIrjo33yUnkgTFOHg4WHtKinGbZexmEDMdQFrXocZW2TzDavz84a6oP8/SW2yfLAVlESO17leEItWVag62bEbo03SI5PoNpGkXdXgfHEF@tyAaRq3Yu@syCEQEUPah/Lin1tuaWWISmGdR4cJQ@NQTpi@1BsAF6A3wDZw2Iu0vQTUo8DcKdlPmrgwQa8GBzBD5Sys3h@SpBCFsdVEsJ8@m/tVzODdCQcATs7LmhBoQT6mtAyOqgHuKh57K7j/0B "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter $_
(
# generate a sequence
# no need to seed the sequence with $_, as the following block will
# default to using the outer $_
# $_,
{ # parameter $_
first
{ # block with placeholder parameter $a
( $^a +^ 2 * $a ) # double (numeric) xor
== $_ # is it equal to the previous value
},
^$_ # Range up to and excluding the previous value ( 0..^$_ )
}
...^ # keep doing that until: (and throw away last value)
!* # it doesn't return a trueish value
).tail # return the last generated value
}
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 44 bytes
```
A-R:-between(1,A,B),A is B xor(B*2),B-R;R=A.
```
[Try it online!](https://tio.run/##bY5BCsMgEEX3PYXLWJzgaExNSwl6BI9QkCKEWEzA3t527/zlW7z3PyVv@Q1HTa05CHd4xbPGuA8onPBcOJYO5tk3l8FfFRcewiM83dhW0BAEqyWdcduHwMfLCqZHc4@WHqHsmSICliiYiRAus6QqlBPREFY0kyK0/xEPblpaEiMSDqtlV2w/ "Prolog (SWI) – Try It Online")
[Answer]
# PHP, 49 bytes
Based on Kevin Cruijssen's answers.
```
for($x=$argn;$x>$i-=$i*2^$i^$x?-1:$x=$i;);echo$x;
```
Run as pipe with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/2c3a9d770bce01dc8b29b8a2efee8420a062ab60).
[Answer]
## F#, 92 bytes
```
let rec o i=
let r=Seq.tryFind(fun x->x^^^x*2=i){1..i-1}
if r.IsNone then i else o r.Value
```
[Try it online!](https://tio.run/##LZBBS8NAEIXv@RWPQsEK2WaTpqbE5KYgiAhCL7WBkE7qQNzUzUYi6m@Pk9q5DPMxvHlv6s6vWkvj2JCDpQotOPNwnrIX@lDOft2zOVzVvcHg50NRFMN1mPHiWyvFvv71wDWseuieWkNwb2TAoKYjkbJqWzY9jbvbOyNCzy0bl@@9Sf29ZIPSHj9xOcfm1LsOGXZRijjFOsUmhQ5ShAISIfFKwGYdTHRiWsdCdbwKBUvJxk0UJOemtbAkCuJ47@GRO6fYkcV/DPi5mBvwk@NkxVJtMJvzq5vzDMPi4sRDgOVSfuJ6K04llXF0FA0a2KFqDzT@AQ)
Recursively checks through the numbers from 1 to `i-1`. If there's a match, check for a smaller for that number. If there's no match, return the input number.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 40 bytes
```
f=n=>g(n)%2?n:f(g(n)/2)
g=x=>x&&x^g(x/2)
```
[Try it online!](https://tio.run/##TczRCoMgGIbh864igoUS29SyVcN2I2MQzWIjdCwZ3r3TgX/z6FWez@fwGdbx/XiZvdJ36dwklOhnpPCOXVQ3oZBHhpNZWNHbPLe3GVn/4IxcTSpSr0etVr3Iw6I9LrLuarJi8jN8TpKgUOnrFzxGHaONQUksBrwBzyuAbU22zWYp5aAprxhwf@CXU0mavwuloJqShL37Ag "JavaScript (Node.js) – Try It Online")
Thanks Shaggy for -1 bytes.
Port of my [Jelly answer](https://codegolf.stackexchange.com/a/166281/69850).
Finally there is a language where this approach is ~~shorter~~ ([oops](https://codegolf.stackexchange.com/a/166285/69850)). (I tried Python and [Java](https://codegolf.stackexchange.com/a/166283), it doesn't work)
Can anyone explain why I can use `/2` instead of `>>1`?
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~32~~ 26 bytes
```
{$[*|a:2!+\2\x;x;2/-1_a]}/
```
[Try it online!](https://tio.run/##FYvdCoJAFITve4oTBGkh7jn7467nUVLSGyMMA/FCKXv17ezAwDDfzFhMjynGof6cbpdvX9Px2lCz8spUFnjv272MS4Lbb64HWLl7j5x1Q/98yWbjOW/3w1KeMw3IVuyAOEDFqCSQtJp96q0JgA45OAXOCBamDTKitUCyQmsofUVAHgPbSisPGJBMyohApDl4reSBefwD "K (ngn/k) – Try It Online")
`{` `}` is a function with argument `x`
`/` applies it until convergence
`$[` `;` `;` `]` if-then-else
`2\x` binary digits of `x` (this is specific to ngn/k)
`+\` partial sums
`2!` mod 2
`a:` assign to `a`
`*|` last - reverse (`|`) and get first (`*`)
if the above is 1, `x` will be returned
otherwise:
`-1_a` drop the last element of `a`
`2/` decode binary
[Answer]
# C, 62 bytes
Based on Kevin Cruijssen's Java:
`int n(int j){for(int i=0;i<j;)i-=(i*2^i)==j?j=i:-1;return j;}`
To test:
```
#include <stdio.h>
int n(int j);
#define p(i) printf("%6d --> %5d\n", i, n(i))
int main(void)
{
p(3);
p(5);
p(6);
p(9);
p(10);
p(23);
p(85);
p(549);
p(960);
p(1023);
p(1155);
p(1542);
p(9999);
p(57308);
p(57311);
p(983055);
}
```
When run, the test program outputs:
```
3 --> 1
5 --> 1
6 --> 2
9 --> 7
10 --> 2
23 --> 13
85 --> 1
549 --> 161
960 --> 64
1023 --> 341
1155 --> 213
1542 --> 2
9999 --> 2819
57308 --> 19124
57311 --> 223
983055 --> 1
```
# C, 54 bytes
Only works with C89 or K&R C:
`n(j){for(i=0;i<j;)i-=(i*2^i)==j?j=i:-1;return j;}`
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes
```
Min[{#}//.x_:>Select[Range@#,MemberQ[x,#|BitXor[#,2#]]&]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d83My@6WrlWX1@vIt7KLjg1JzW5JDooMS891UFZxzc1Nym1KDC6Qke5ximzJCK/KFpZx0g5NlYNiP7rOyhUG@somOoomOkoWOooGBroKBgBBSyAIqYmQAFLMwOQqJFxbex/AA "Wolfram Language (Mathematica) – Try It Online")
Starts with a list containing just the input. Iteratively replaces the list by all integers that are either already in it, or map into it by the double-and-xor operation. Then `//.` says to do this until reaching a fixed point. The answer is the least element of the result.
]
|
[Question]
[
## Overview
Your goal is to implement RC4 encryption. RC4 encryption, invented by Ron Rivest (of RSA fame), was designed to be secure, yet simple enough to be implemented from memory by military soldiers on the battlefield. Today, there are several attacks on RC4, but it's still used in many places today.
Your program should accept a single string with both a key and some data. It will be presented in this format.
```
\x0Dthis is a keythis is some data to encrypt
```
The first byte represents how long the key is. It can be assumed the key will no longer than 255 bytes, and no shorter than 1 byte. The data can be arbitrarily long.
Your program should process the key, then return the encrypted data. RC4 encryption and decryption are identical, so using the same key to "encrypt" the ciphertext should return the original plaintext.
## How RC4 Works
### Initialization
Initialization of RC4 is quite simple. A state array of 256 bytes is initialized to all bytes from 0 to 255.
```
S = [0, 1, 2, 3, ..., 253, 254, 255]
```
### Key processing
Values in the state are swapped around based on the key.
```
j = 0
for i from 0 to 255
j = (j + S[i] + key[i mod keylength]) mod 256
swap S[i] and S[j]
```
### Encryption
Encryption is accomplished by using the state to generate pseudo-random bytes, which are then XOR'd to the data. Values in the state are swapped around constantly.
```
i = j = 0
for each byte B in data
i = (i + 1) mod 256
j = (j + S[i]) mod 256
swap S[i] and S[j]
K = S[(S[i] + S[j]) mod 256]
output K XOR B
```
## Expected inputs and outputs
Non-printable characters will be shown in `\xAB` format.
Input: `\x01\x00\x00\x00\x00\x00\x00`
Output: `\xde\x18\x89A\xa3`
Output(hex): `de188941a3`
Input: `\x0Dthis is a keythis is some data to encrypt`
Output: `\xb5\xdb?i\x1f\x92\x96\x96e!\xf3\xae(!\xf3\xeaC\xd4\x9fS\xbd?d\x82\x84{\xcdN`
Output(hex): `b5db3f691f9296966521f3ae2821f3ea43d49f53bd3f6482847bcd4e`
Input: `\x0dthis is a key\xb5\xdb?i\x1f\x92\x96\x96e!\xf3\xae(!\xf3\xeaC\xd4\x9fS\xbd?d\x82\x84{\xcdN`
Input(hex): `0d746869732069732061206b6579b5db3f691f9296966521f3ae2821f3ea43d49f53bd3f6482847bcd4e`
Output: `this is some data to encrypt`
Input: `Sthis is a rather long key because the value of S is 83 so the key length must matchand this is the data to be encrypted`
Output: `\x96\x1f,\x8f\xa3%\x9b\xa3f[mk\xdf\xbc\xac\x8b\x8e\xfa\xfe\x96B=!\xfc;\x13`c\x16q\x04\x11\xd8\x86\xee\x07`
Output(hex): `961f2c8fa3259ba3665b6d6bdfbcac8b8efafe96423d21fc3b13606316710411d886ee07`
[Answer]
# 138 bytes, machine code (16-bit x86)
```
000000 88 9f 00 02 fe c3 75 f8 b9 01 00 89 fa b4 3f cd
000010 21 86 0d ba 00 03 b4 3f cd 21 89 dd 01 f6 02 9e
000020 00 03 8a 04 00 c3 86 87 00 02 88 04 46 45 39 cd
000030 75 02 31 ed 81 fe 00 03 75 e4 81 ee 00 01 31 db
000040 31 d2 ff c6 81 fe 00 03 75 04 81 ee 00 01 8a 04
000050 00 c3 88 c2 86 87 00 02 88 04 00 c2 89 d7 81 c7
000060 00 02 8a 15 89 d7 89 dd 31 db ba 00 03 b9 01 00
000070 b8 00 3f cd 21 87 fa 30 15 85 c0 74 0b 87 fa 43
000080 b4 40 cd 21 89 eb eb b8 cd 20
```
Running: save to codegolf.com, dosbox:
`codegolf.com < input.bin`

I don't know if this gonna count as an entry, but I've decided to do it
**manually** using hex editors. **No compilers** were used to do this.
ht editor actually has assembler, but honestly I did not know about this until
I was finished ¯\*(ツ)*/¯
## Why & how
Why: mostly cause I wanted to check if I'm able to do this.
How: I've started with creating byte filled with `NOP`s and following with
a simple part: trying to write first loop that fills `S`tate with 0..255 values.
I switched to python and quickly wrote python version, just to have something to test against.
Next I was simplifying python code into pseudo code / pseudo assembly.
Then I I was trying to write small pieces.
I decided it'll be easiest to read from stdin, so I started with something
small that will read single byte, then I added password reading and
key initialization. Figuring out what registers to pick took me some time.
I though adding de/encryption loop will be easy, but first I actually got
single byte decode and added whole loop afterwards.
Last step was getting rid of additional `nops` that I've left between
instructions when writing it (ofc that required fixing jumps as well).
You can see small gallery that I tried to make while progressing [here](https://i.stack.imgur.com/PmZrW.jpg).
## Dissection
The program relies on some initial values after startup (see resources below).
```
00000000 889f0002 mov [bx+0200], bl
00000004 fec3 inc bl
00000006 75f8 jnz 0x0
```
fill in State (at 0x200)
```
00000008 b90100 mov cx, 0x1
0000000b 89fa mov dx, di
0000000d b43f mov ah, 0x3f
0000000f cd21 int 0x21
00000011 860d xchg [di], cl
00000013 ba0003 mov dx, 0300
00000016 b43f mov ah, 0x3f
00000018 cd21 int 0x21
```
read length, read password, store password at ds:0x300
```
0000001a 89dd mov bp, bx
0000001c 01f6 add si, si
0000001e 029e0003 add bl, [bp+0300]
00000022 8a04 mov al, [si]
00000024 00c3 add bl, al
00000026 86870002 xchg [bx+0200], al
0000002a 8804 mov [si], al
0000002c 46 inc si
0000002d 45 inc bp
0000002e 39cd cmp bp, cx
00000030 7502 jnz 0x34
00000032 31ed xor bp, bp
00000034 81fe0003 cmp si, 0300
00000038 75e4 jnz 0x1e
```
initialize State with a key (`BP` is used to traverse key, `SI` is used to
traverse State)
```
0000003a 81ee0001 sub si, 0100
0000003e 31db xor bx, bx
00000040 31d2 xor dx, dx
00000042 ffc6 inc si
00000044 81fe0003 cmp si, 0300
00000048 7504 jnz 0x4e
0000004a 81ee0001 sub si, 0100
0000004e 8a04 mov al, [si]
00000050 00c3 add bl, al
00000052 88c2 mov dl, al
00000054 86870002 xchg [bx+0200], al
00000058 8804 mov [si], al
0000005a 00c2 add dl, al
0000005c 89d7 mov di, dx
0000005e 81c70002 add di, 0200
00000062 8a15 mov dl, [di]
```
generate pseudo random value (in `DL`, `DH` is 0 thx to xor at 0x140)
```
00000064 89d7 mov di, dx
00000066 89dd mov bp, bx
00000068 31db xor bx, bx
0000006a ba0003 mov dx, 0300
0000006d b90100 mov cx, 0x1
00000070 b8003f mov ax, 3f00
00000073 cd21 int 0x21
00000075 87fa xchg dx, di
00000077 3015 xor [di], dl
00000079 85c0 test ax, ax
0000007b 740b jz 0x88
0000007d 87fa xchg dx, di
0000007f 43 inc bx
00000080 b440 mov ah, 0x40
00000082 cd21 int 0x21
00000084 89eb mov bx, bp
00000086 ebb8 jmp 0x40
00000088 cd20 int 0x20
```
* store values that we need to preserve (`SI` - ints won't touch it, `BX`)
* read char from input, xor it
* quit if end of stream
* output decoded char
* restore values
* loop to 0x40 (reuse xor on `DX`)
P.S. This probably could be even shorter, but this took 4 evenings, so not sure if I want to spend another one...
## Tools and resources
* [ht editor](http://hte.sourceforge.net) - it has 16-bit disasm
* [hexplorer](https://sourceforge.net/projects/hexplorer/) - mostly for it's mouse based copy/paste + insert/overwrite
* dosbox - for debugging
* [X86 Opcode and Instruction Reference 1.12](http://ref.x86asm.net/geek.html) and invaluable [16-bit ModR/M Byte](http://ref.x86asm.net/geek.html#modrm_byte_16)
* [DOS INT 21h - DOS Function Codes](http://spike.scu.edu.au/%7Ebarry/interrupts.html)
* [80386 Instruction Set](http://css.csail.mit.edu/6.858/2012/readings/i386/c17.htm) note this is 386, but that's more than enough
* [Register values at DOS .COM startup](http://www.fysnet.net/yourhelp.htm)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~193 188 182 178 171~~ 172 bytes
```
f(x,l)int*x;{unsigned char*X=x,i=0,j=0,S[256],t;for(;S[i]=++i;);for(;t=S[i],S[i]=S[j+=t+X[1+i%*X]],S[j]=t,t=++i;);for(X+=*X;l--;S[i]-=S[t]=j)*++X^=S[S[i]+=S[t+=j=S[++i]]];}
```
[Try it online!](https://tio.run/##7VRNj5swEL3vr5girQQYpEC@RdFeeu6FC1KgkjEmcZqQCJzK2yi/PX1mm7YrVVVX6tehFqNhnt@MZ7AeIlwLcb02rgl2nmq1b5Lzqe3VupU1iQ3v/Dw1gUpHwRaWreLprAx00hw6N8lWqkwZU4n3FOvUIsEAZ6stSzXLVxFT935eWnhbpjrQ32TkLPXzZBeGQ6kQSbpMt57PWP4OgQWZBVm6hUNeWZbJ5brnqnW98935juhZr8RXZeoUZhTBRt8zJ0FO4/KgVx/loSEexqHPvQFFQ/gApFKfsyhRr79QEDDm2dOIjh04jevcj2JDToATVUlD/oWOJ927joPo8oPe3uiN6gkPp/fy8Rb0h72kmmtO@kCyFd3jUf8DzdbPmi1MNS1MXT2owkRNYZYxbFbE8Uy@KkwzLgyX7uc3yQszga8n4DQZUuuHujALpCwm58KI@u2vm0@8fLjs62Qd1xvZ0e7Qru2UVEnBT70koPSB706ScHJmuYsxLmrALW8n27Xe0P7Ua9pzjdptTbeylnS7z0rerlTWf/9SF9FvGD1/0fr/oX5yQScVpAMdVRBOA00J2NSqELEQ0Bb0NV1Cb7BGomnr51Ai9iT8EvwIwuOoMV885dqcOfQbgzvHvzICR@IcCZyDMwc@gY9Ro8F@jbrjpe3jz0j2cv0E "C (gcc) – Try It Online")
Edit: Now works with keys longer than 127 bytes.
Edit2: Added testcase with 129 byte key to TIO link.
Slightly less golfed version
```
f(x,l)int*x;{
unsigned char*X=x,i=0,j=0,S[256],t;
// initialize state
for(;S[i]=++i;);
// key processing
for(;t=S[i],S[i]=S[j+=t+X[1+i%*X]],S[j]=t,t=++i;);
// encrypt
for(X+=*X;l--;S[i]-=S[t]=j)
*++X^=S[S[i]+=S[t+=j=S[++i]]];
}
```
[Answer]
# CPU x86 instruction set, 133 bytes
```
000009F8 53 push ebx
000009F9 56 push esi
000009FA 57 push edi
000009FB 55 push ebp
000009FC 55 push ebp
000009FD BF00010000 mov edi,0x100
00000A02 29FC sub esp,edi
00000A04 8B6C3C18 mov ebp,[esp+edi+0x18]
00000A08 31DB xor ebx,ebx
00000A0A 8A5D00 mov bl,[ebp+0x0]
00000A0D 45 inc ebp
00000A0E 31C0 xor eax,eax
00000A10 880404 mov [esp+eax],al
00000A13 40 inc eax
00000A14 39F8 cmp eax,edi
00000A16 72F8 jc 0xa10
00000A18 31F6 xor esi,esi
00000A1A 31C9 xor ecx,ecx
00000A1C 89F0 mov eax,esi
00000A1E 31D2 xor edx,edx
00000A20 F7F3 div ebx
00000A22 8A0434 mov al,[esp+esi]
00000A25 02441500 add al,[ebp+edx+0x0]
00000A29 00C1 add cl,al
00000A2B 8A0434 mov al,[esp+esi]
00000A2E 8A140C mov dl,[esp+ecx]
00000A31 88040C mov [esp+ecx],al
00000A34 881434 mov [esp+esi],dl
00000A37 46 inc esi
00000A38 39FE cmp esi,edi
00000A3A 72E0 jc 0xa1c
00000A3C 8B443C1C mov eax,[esp+edi+0x1c]
00000A40 01E8 add eax,ebp
00000A42 722F jc 0xa73
00000A44 48 dec eax
00000A45 89C6 mov esi,eax
00000A47 01DD add ebp,ebx
00000A49 31C0 xor eax,eax
00000A4B 31D2 xor edx,edx
00000A4D 31C9 xor ecx,ecx
00000A4F 39F5 cmp ebp,esi
00000A51 7320 jnc 0xa73
00000A53 FEC2 inc dl
00000A55 8A0414 mov al,[esp+edx]
00000A58 00C1 add cl,al
00000A5A 8A1C0C mov bl,[esp+ecx]
00000A5D 88040C mov [esp+ecx],al
00000A60 881C14 mov [esp+edx],bl
00000A63 00D8 add al,bl
00000A65 8A1C04 mov bl,[esp+eax]
00000A68 8A4500 mov al,[ebp+0x0]
00000A6B 30D8 xor al,bl
00000A6D 884500 mov [ebp+0x0],al
00000A70 45 inc ebp
00000A71 EBDC jmp short 0xa4f
00000A73 01FC add esp,edi
00000A75 5D pop ebp
00000A76 5D pop ebp
00000A77 5F pop edi
00000A78 5E pop esi
00000A79 5B pop ebx
00000A7A C20800 ret 0x8
00000A7D
```
A7D-9F8=85h=133 bytes but i don't know if calculation is ok because the preciding number of bytes of the
same function result 130 bytes...
The first argumenti of the function that I name "cript" is the string,
the second argumenti is the string lenght (first byte+ key lenght + message lenght).
Below there is the assembly language file for obtain that cript routines:
```
; nasmw -fobj this.asm
section _DATA use32 public class=DATA
global cript
section _TEXT use32 public class=CODE
cript:
push ebx
push esi
push edi
push ebp
push ebp
mov edi, 256
sub esp, edi
mov ebp, dword[esp+ edi+24]
xor ebx, ebx
mov bl, [ebp]
inc ebp
xor eax, eax
.1: mov [esp+eax], al
inc eax
cmp eax, edi
jb .1
xor esi, esi
xor ecx, ecx
.2: mov eax, esi
xor edx, edx
div ebx
mov al, [esp+esi]
add al, [ebp+edx]
add cl, al
mov al, [esp+esi]
mov dl, [esp+ecx]
mov [esp+ecx], al
mov [esp+esi], dl
inc esi
cmp esi, edi
jb .2
mov eax, dword[esp+ edi+28]
add eax, ebp
jc .z
dec eax
mov esi, eax
add ebp, ebx
xor eax, eax
xor edx, edx
xor ecx, ecx
.3: cmp ebp, esi
jae .z
inc dl
mov al, [esp+edx]
add cl, al
mov bl, [esp+ecx]
mov [esp+ecx], al
mov [esp+edx], bl ; swap S[c] S[r]
add al, bl
mov bl, [esp+eax]
mov al, [ebp]
xor al, bl
mov [ebp], al
inc ebp
jmp short .3
.z:
add esp, edi
pop ebp
pop ebp
pop edi
pop esi
pop ebx
ret 8
```
below the C file for check results:
```
// Nasmw -fobj fileasm.asm
// bcc32 -v filec.c fileasm.obj
#include <stdio.h>
void _stdcall cript(char*,unsigned);
char es1[]="\x01\x00\x00\x00\x00\x00\x00";
char es2[]="\x0Dthis is a keythis is some data to encrypt";
char es3[]="\x0dthis is a key\xb5\xdb?i\x1f\x92\x96\226e!\xf3\xae(!\xf3\xea\x43\xd4\x9fS\xbd?d\x82\x84{\xcdN";
char es4[]="Sthis is a rather long key because the value of S is 83 so the key length must matchand this is the data to be encrypted";
void printMSGKeyC(unsigned char* a, unsigned len)
{unsigned i,j,k;
unsigned char *p,*end;
printf("keylen = %u\nKey = [", (unsigned)*a);
for(i=1, j=*a;i<=j;++i) printf("%c", a[i]);
printf("]\nMessage= [");
for(p=a+i,end=a+len-1;p<end;++p)printf("%c", *p);
printf("]\n");
}
void printMSGKeyHex(unsigned char* a, unsigned len)
{unsigned i,j,k;
unsigned char *p,*end;
printf("keylen = %u\nKey = [", (unsigned)*a);
for(i=1, j=*a;i<=j;++i) printf("%02x", a[i]);
printf("]\nMessage= [");
for(p=a+i,end=a+len-1;p<end;++p)printf("%02x", *p);
printf("]\n");
}
main()
{printf("sizeof \"%s\"= %u [so the last byte 0 is in the count]\n", "this", sizeof "this");
printf("Input:\n");
printMSGKeyHex(es1, sizeof es1);
cript(es1, (sizeof es1)-1);
printf("Afther I cript:\n");
printMSGKeyHex(es1, sizeof es1);
printf("Input:\n");
printMSGKeyC(es2, sizeof es2);
printMSGKeyHex(es2, sizeof es2);
cript(es2, (sizeof es2)-1);
printf("Afther I cript:\n");
printMSGKeyC(es2, sizeof es2);
printMSGKeyHex(es2, sizeof es2);
cript(es2, (sizeof es2)-1);
printf("Afther II cript:\n");
printMSGKeyC(es2, sizeof es2);
printMSGKeyHex(es2, sizeof es2);
printf("----------------------\n");
printf("Input:\n");
printMSGKeyHex(es3, sizeof es3);
cript(es3, (sizeof es3)-1);
printf("Afther I cript:\n");
printMSGKeyHex(es3, sizeof es3);
printf("----------------------\n");
printf("Input:\n");
printMSGKeyHex(es4, sizeof es4);
cript(es4, (sizeof es4)-1);
printf("Afther I cript:\n");
printMSGKeyHex(es4, sizeof es4);
cript(es4, (sizeof es4)-1);
printf("Afther II cript:\n");
printMSGKeyHex(es4, sizeof es4);
return 0;
}
```
the results:
```
sizeof "this"= 5 [so the last byte 0 is in the count]
Input:
keylen = 1
Key = [00]
Message= [0000000000]
Afther I cript:
keylen = 1
Key = [00]
Message= [de188941a3]
Input:
keylen = 13
Key = [this is a key]
Message= [this is some data to encrypt]
keylen = 13
Key = [746869732069732061206b6579]
Message= [7468697320697320736f6d65206461746120746f20656e6372797074]
Afther I cript:
keylen = 13
Key = [this is a key]
Message= [Á█?iÆûûe!¾«(!¾ÛCȃS¢?déä{═N]
keylen = 13
Key = [746869732069732061206b6579]
Message= [b5db3f691f9296966521f3ae2821f3ea43d49f53bd3f6482847bcd4e]
Afther II cript:
keylen = 13
Key = [this is a key]
Message= [this is some data to encrypt]
keylen = 13
Key = [746869732069732061206b6579]
Message= [7468697320697320736f6d65206461746120746f20656e6372797074]
----------------------
Input:
keylen = 13
Key = [746869732069732061206b6579]
Message= [b5db3f691f9296966521f3ae2821f3ea43d49f53bd3f6482847bcd4e]
Afther I cript:
keylen = 13
Key = [746869732069732061206b6579]
Message= [7468697320697320736f6d65206461746120746f20656e6372797074]
----------------------
Input:
keylen = 83
Key = [74686973206973206120726174686572206c6f6e67206b65792062656361757365207468652076616c7565206f66205320697320383320736f20746865206b6579206c656e677468206d757374206d61746368]
Message= [616e64207468697320697320746865206461746120746f20626520656e63727970746564]
Afther I cript:
keylen = 83
Key = [74686973206973206120726174686572206c6f6e67206b65792062656361757365207468652076616c7565206f66205320697320383320736f20746865206b6579206c656e677468206d757374206d61746368]
Message= [961f2c8fa3259ba3665b6d6bdfbcac8b8efafe96423d21fc3b13606316710411d886ee07]
Afther II cript:
keylen = 83
Key = [74686973206973206120726174686572206c6f6e67206b65792062656361757365207468652076616c7565206f66205320697320383320736f20746865206b6579206c656e677468206d757374206d61746368]
Message= [616e64207468697320697320746865206461746120746f20626520656e63727970746564]
```
[Answer]
## JavaScript (ES6), ~~169~~ 168 bytes
Takes input as an array of bytes. Returns another array of bytes.
```
([l,...s])=>s.slice(l).map(b=>b^S[(S[S[J=J+(t=S[I=I+1&m])&m,I]=x=S[J],J]=t)+x&m],[...S=[...Array(m=255).keys(),m]].map(i=>S[S[i]=S[j=j+(t=S[i])+s[i%l]&m],j]=t,I=J=j=0))
```
### How?
This is essentially a literal implementation of the spec.
We first split the input array into ***l*** (length of key) and ***s*** (payload data: key + message). Then, in order of execution:
* We initialize the state array ***S*** and define ***m = 255*** which is repeatedly used later as a bit mask.
```
S = [...Array(m = 255).keys(), m]
```
* We shuffle the state array. The indices ***I*** and ***J*** which are initialized here are actually used in the next step.
```
[...S].map(i =>
S[S[i] = S[j = j + (t = S[i]) + s[i % l] & m], j] = t,
I = J = j = 0
)
```
* We apply the encryption.
```
s.slice(l).map(b =>
b ^ S[
(S[S[J = J + (t = S[I = I + 1 & m]) & m, I] = x = S[J], J] = t) +
x & m
]
)
```
### Test cases
```
let f =
([l,...s])=>s.slice(l).map(b=>b^S[(S[S[J=J+(t=S[I=I+1&m])&m,I]=x=S[J],J]=t)+x&m],[...S=[...Array(m=255).keys(),m]].map(i=>S[S[i]=S[j=j+(t=S[i])+s[i%l]&m],j]=t,I=J=j=0))
let toArray = s => [...s].map(c => c.charCodeAt())
let toHexa = s => [...s].map(c => ('0' + c.toString(16)).slice(-2)).join` `
console.log(toHexa(f(toArray("\x01\x00\x00\x00\x00\x00\x00"))))
console.log(toHexa(f(toArray("\x0Dthis is a keythis is some data to encrypt"))))
console.log(String.fromCharCode(...f(toArray("\x0dthis is a key\xb5\xdb?i\x1f\x92\x96\x96e!\xf3\xae(!\xf3\xeaC\xd4\x9fS\xbd?d\x82\x84{\xcdN"))))
console.log(toHexa(f(toArray("Sthis is a rather long key because the value of S is 83 so the key length must matchand this is the data to be encrypted"))))
```
[Answer]
# JavaScript (ES6), 262 bytes
I considered using only chained functions, but opted to golfify the algorithm given here: <https://gist.github.com/farhadi/2185197>.
```
A=>eval(`for(C=A[c='charCodeAt']
(),K=A.slice(1,++C),T=A.slice(C),i=j=k=l=m=y=0,s=[],r=[],a=256;i<a;)s[i]=i++
for(;j<a;){t=s[k=(k+s[j]+K[c](j%K.length))%a]
s[k]=s[j]
s[j++]=t}for(;y<T.length;){r[y]=T[c](y++)^s[((t=s[m=(m+s[l=++l%a])%a])+
(s[m]=s[l]))%a]
s[l]=t}r`)
```
## Less Golfed
```
A=>{
C=A.charCodeAt()
K=A.slice(1,++C)
T=A.slice(C)
for(i=j=k=l=m=y=0,s=[],r=[];i<256;)s[i]=i++
for(;j<256;){
t=s[k=(k+s[j]+K.charCodeAt(j%K.length))%256];
s[k]=s[j];
s[j++]=t;
}
for(;y<T.length;){
t=s[m=(m+s[l=(l+1)%256])%256];
s[m]=s[l];
s[l]=t;
r[y]=T.charCodeAt(y++)^s[(s[l]+s[m])%256];
}
return r;
}
```
```
let f =
A=>eval(`for(C=A[c='charCodeAt']
(),K=A.slice(1,++C),T=A.slice(C),i=j=k=l=m=y=0,s=[],r=[],a=256;i<a;)s[i]=i++
for(;j<a;){t=s[k=(k+s[j]+K[c](j%K.length))%a]
s[k]=s[j]
s[j++]=t}for(;y<T.length;){r[y]=T[c](y++)^s[((t=s[m=(m+s[l=++l%a])%a])+
(s[m]=s[l]))%a]
s[l]=t}r`)
let test = (input, expected) => {
let output = f(input);
let chars = output.map(c=>String.fromCharCode(c)).join``;
let hex = output.map(c=>('0' + c.toString(16)).slice(-2)).join``;
let success = chars === expected;
console.log([success ? 'SUCCESS:' : 'ERROR:', output, chars, hex].join`\n`);
}
test('\x01\x00\x00\x00\x00\x00\x00','\xde\x18\x89A\xa3')
test('\x0Dthis is a keythis is some data to encrypt','\xb5\xdb?i\x1f\x92\x96\x96e!\xf3\xae(!\xf3\xeaC\xd4\x9fS\xbd?d\x82\x84{\xcdN')
test('\x0dthis is a key\xb5\xdb?i\x1f\x92\x96\x96e!\xf3\xae(!\xf3\xeaC\xd4\x9fS\xbd?d\x82\x84{\xcdN','this is some data to encrypt')
test('Sthis is a rather long key because the value of S is 83 so the key length must matchand this is the data to be encrypted',
'\x96\x1f,\x8f\xa3%\x9b\xa3f[mk\xdf\xbc\xac\x8b\x8e\xfa\xfe\x96B=!\xfc;\x13`c\x16q\x04\x11\xd8\x86\xee\x07')
```
[Answer]
# [Python 2](https://docs.python.org/2/), 203 bytes
```
def f(x):
def h():S[i],S[j]=S[j],S[i]
m=256;x=map(ord,x);S=range(m);l=x.pop(0);j=0
for i in S[:]:j=(j+S[i]+x[i%l])%m;h()
i=j=0
for b in x[l:]:i=(i+1)%m;j=(j+S[i])%m;h();yield chr(S[(S[i]+S[j])%m]^b)
```
[Try it online!](https://tio.run/##rVNNj5swED3Dr5geohgFrcJmN2WD0Kof5144At0YbAdn@SqYyml/fHYmX22lSr1UYtB4/N7zPDP0B1N17f3xKKQCxay3cR1KK@ZtklTnfpLu85hePi1dp4nvH9eRjRves24QvvWiJB54u5Os8aI6tnd917OlF@3jpeuobgANuoUk3eSbfcz2C5JZ2FTP6tybNREe5Do6vqELQtu0RriOmV4EBLoRL4zooGUtoKwGlqTspEgt4m7@tfCOuu0nM0IM6TyzywBj@beY@0D7n02lR8CHw6s8XBdj10gQ3HAwHci2HA69uRDEH4TMFo@ZFcWzzmygMvt0j7GmkO8yq1aZ5ZJdMsk/IfQBN1WCPPEsMhsiPnz4mdlSfKEDkl/qAzeVHKDu2h2dBIUs@TRKwCp85/UkoVOQEDZcYcOnOuFq2e5MBc00Gmi4KSveCrjKEujqq5BXa1LMc7ebzG8XJyQaCrG5pw/oYXU2/3@9/vuyST1QPtIUNTHDSkGJSptXlMdiUeIaI8R6iC0rjiGJ@TGmVsoIFVZbRATrb/j1sKMAR0KQMxSXCF2@R/PuaVbbFx/wGmgIf@ienSfpVKKE/o5@0K2BLSK3vusMcpxqgzc2n9/tO90yhZwXz7vhzoCt6/BxlIOBKyEmzeMb "Python 2 – Try It Online")
`f` is a generator (iterable) of strings.
Ungolfed:
```
def f(x):
def h():
S[i], S[j] = S[j], S[i] # we have to do this two times
m = 256 # used often
x = map(ord, x) # get numbers to do stuff with
S = range(m) # init State
l = x.pop(0) # get key length and remove the first byte in one go
j = 0
for i in S[:]: # shorter than range(256)
j = (j + S[i] + x[i%l]) % m
h()
i = j = 0
for b in x[l:]: # data comes after the key
i = (i+1) % m
j = (j+S[i]) % m
h()
yield chr(S[(S[i]+S[j]) % m] ^ b) # convert to str again
```
[Answer]
# [R](https://www.r-project.org), 189 bytes
```
\(s){f=256
S=1:f-1
for(i in 1:f)S[c(i,T)]=S[c(T<-(T-1+S[i]+s[(i-1)%%s[1]+2])%%f+1,i)]
i=j=1
sapply(s[0:-s-1],\(B)bitwXor(S[sum(S[c(j,i)]<<-S[c(i<<-(i)%%f+1,j<<-(j-1+S[i])%%f+1)])%%f+1],B))}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVBLasMwFNzrFMIQeA9bUKUfQrA22XVtFwqKFq5jU7mNbSyZYkrP0AN040J7jB6kt-lz7GwLgpl5aGae9PHZjV9dfqW-e1-Kze_PHhy-lmp9fcMSJbelkKxsOrDc1pwkJjoHG6Vo1MTSWEAqZJhoa0KnwQqJq5XT0oRrQ6wMZWTRMKsqJZnL2vZ5AKcvtsIJaaI97PDB-pd7aki0648whVaTJY7FqYoQ7JJUTaJa6uYZLmiiHeLb8oh3W7e9VznIy4gmm7S5rT0E_tE6TifjT8VwFq45FvyQ-Yz7hhd13g2tDxAZUUX_AqcoZIdilv9mBhiRjcy29mlzR7eAfMjmtcZxxj8)
Ungolfed code:
```
rc4=function(s){
l=s[1]
k=s[1:l+1]
d=s[-(0:l+1)]
# initialization
S=0:255
# key processing
j=0
for(i in 0:255){
j=(j+S[i+1]+k[i%%l+1])%%256
temp=S[i+1]
S[i+1]=S[j+1]
S[j+1]=temp
}
#encryption
i=j=0
ans={}
for(B in d){
i=(i+1)%%256
j=(j+S[i+1])%%256
temp=S[i+1]
S[i+1]=S[j+1]
S[j+1]=temp
K=S[(S[i+1]+S[j+1])%%256+1]
ans=c(ans,bitwXor(K,B))
}
ans
}
```
[Answer]
# Ruby, 234 bytes
Untested.
```
->s{l=s[0].ord;k=s[1..l];i=s[l+1..-1];o='';s=[*0..255];i,j,q=0;256.times{|i|j=(j+s[i]+k[i%k.size].ord)%256;s[i],s[j]=s[j],s[i]};i.size.times{|k|i=(i+1)%256;q=(q+s[i])%256;s[i],s[q]=s[q],s[i];b=s[(s[i]+s[q])%256];o<<(b^i[k].ord).chr;o}
```
[Answer]
# C, 181 bytes
```
f(a,n)char*a;{unsigned char A=*a++,i=-1,j=0,k,s[256];for(;s[i]=i;--i);for(;k=s[i],s[i]=s[j+=k+a[i%A]],s[j]=k,k=++i;);for(n-=A,a+=A;--n;*a++^=s[j+=A])j=s[++i],A=s[i]=s[k+=j],s[k]=j;}
```
thanks to ceilingcat for some bytes less:
```
f(a,n)char*a;
{unsigned char A=*a++,i=-1,j=0,k,s[256];
for(;s[i]=i;--i);
for(;k=s[i],s[i]=s[j+=k+a[i%A]],s[j]=k,k=++i;);
for(n-=A,a+=A;--n;*a++^=s[j+=A])j=s[++i],A=s[i]=s[k+=j],s[k]=j;
}
```
f(a,n) in "a" there would be the array of chars 1Byte len + key + message;
in n there is the size of the all array of "a" not count the last '\0'.
code for test and result would be as the one used for assembly function.
[Answer]
# APL(NARS), 329 chars, 658 bytes
```
xor←{⍺<0:¯1⋄⍵<0:¯1⋄⍺=0:⍵⋄⍵=0:⍺⋄k←⌈/{⌊1+2⍟⍵}¨⍺⍵⋄(2⍴⍨≢m)⊥m←↑≠/{(k⍴2)⊤⍵}¨⍺⍵}
∇r←C w;s;i;j;l;t;b;x
k←256⋄s←¯1+⍳k⋄i←j←0⋄l←¯1+⎕AV⍳↑w
t←s[1+i]⋄j←k∣¯1+j+t+⎕AV⍳w[2+l∣i]⋄s[1+i]←s[1+j]⋄s[1+j]←t⋄i+←1⋄→2×⍳i<k
i←j←0⋄b←≢w⋄l+←1
l+←1⋄→6×⍳l>b⋄i←k∣i+1⋄t←s[1+i]⋄j←k∣j+t⋄s[1+i]←s[1+j]⋄s[1+j]←t
x←s[1+k∣t+s[1+i]] xor ¯1+⎕AV⍳w[l]⋄w[l]←⎕AV[1+x]⋄→4
r←w
∇
```
as always the error check would be demanded to someone other...
This seems to be ok on input and output, test:
```
str2Hex←{∊{'0123456789ABCDEF'[1+{(2⍴16)⊤⍵}⍵]}¨{¯1+⎕AV⍳⍵}⍵}
str2Hex ⎕AV[2,1,1,1,1,1,1]
01000000000000
str2Hex C ⎕AV[2,1,1,1,1,1,1]
0100DE188941A3
str2Hex C C ⎕AV[2,1,1,1,1,1,1]
01000000000000
str2Hex C ⎕AV[14],'this is a keythis is some data to encrypt'
0D746869732069732061206B6579B5DB3F691F9296966521F3AE2821F3EA43D49F53BD3F6482847BCD4E
C C ⎕AV[14],'this is a keythis is some data to encrypt'
this is a keythis is some data to encrypt
str2Hex C 'Sthis is a rather long key because the value of S is 83 so the key length must matchand this is the data to be encrypted'
5374686973206973206120726174686572206C6F6E67206B65792062656361757365207468652076616C7565206F662053
20697320383320736F20746865206B6579206C656E677468206D757374206D61746368961F2C8FA3259BA3665B6D
6BDFBCAC8B8EFAFE96423D21FC3B13606316710411D886EE07
C C 'Sthis is a rather long key because the value of S is 83 so the key length must matchand this is the data to be encrypted'
Sthis is a rather long key because the value of S is 83 so the key length must matchand this is th
e data to be encrypted
```
Yes all can be reduced...but for example make more little the xor function could mean make it less general...
[Answer]
# Rust 348
```
fn rc4(n:Vec<u8>)->Vec<u8>{let(mut s,mut j,mut t,l)=((0..256).collect::<Vec<usize>>(),0,0,n[0] as usize);let(key,msg)=n[1..].split_at(l);(0..256).fold(0,|a,i|{j=(a+s[i]+key[i%l] as usize)%256;t=s[i];s[i]=s[j];s[j]=t;j});j=0;(1..).zip(msg.iter()).map(|(i,b)|{j=(j+s[i])%256;t=s[i];s[i]=s[j];s[j]=t;s[(s[i]+s[j])%256]as u8^b}).collect::<Vec<u8>>()}
```
This is quite terribly large, I am hoping maybe someone could provide some suggestions.
ungolfed: [on play.rust-lang.org playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=64c2430a0abe1ff8f3daa312212e53b6)
]
|
[Question]
[
## Binary trees
A binary tree is a tree with nodes of three types:
* terminal nodes, which have no children
* unary nodes, which have one child each
* binary nodes, which have two children each
We can represent them with the following grammar, given in [BNF](https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form) (Backus–Naur form):
```
<e> ::=
<terminal>
| <unary>
| <binary>
<terminal> ::=
"0"
<unary> ::=
"(1" <e> ")"
<binary> ::=
"(2" <e> " " <e> ")"
```
In this grammar the nodes are given in preorder and each node is represented by a digit which is the number of children it has.
## Motzkin numbers
Motzkin numbers ([OEIS](https://oeis.org/A001006)) ([Wikipedia](https://en.wikipedia.org/wiki/Motzkin_number)) have many interpretations, but one interpretation is that the `n`th Motzkin number is the number of distinct binary trees with `n` nodes. A table of Motzkin numbers starts
```
N Motzkin number M(N)
1 1
2 1
3 2
4 4
5 9
6 21
7 51
8 127
...
```
e.g. `M(5)` is 9, and the nine distinct binary trees with 5 nodes are
```
1 (1 (1 (1 (1 0))))
2 (1 (1 (2 0 0)))
3 (1 (2 0 (1 0)))
4 (1 (2 (1 0) 0))
5 (2 0 (1 (1 0)))
6 (2 0 (2 0 0))
7 (2 (1 0) (1 0))
8 (2 (1 (1 0)) 0)
9 (2 (2 0 0) 0)
```
## Task
Take a single positive integer `n` as input and output all of the distinct binary trees with `n` nodes.
Examples for `n` from 1 to 5 with parenthesis included for readability
```
0
(1 0)
(1 (1 0))
(2 0 0)
(1 (1 (1 0)))
(1 (2 0 0))
(2 0 (1 0))
(2 (1 0) 0)
(1 (1 (1 (1 0))))
(1 (1 (2 0 0)))
(1 (2 0 (1 0)))
(1 (2 (1 0) 0))
(2 0 (1 (1 0)))
(2 0 (2 0 0))
(2 (1 0) (1 0))
(2 (1 (1 0)) 0)
(2 (2 0 0) 0)
```
## Input
The input will be one positive integer.
## Output
The output should be an intelligible representation of the distinct binary trees with that many nodes. It is not compulsory to use the exact string given by the BNF grammar above: it is sufficient that the syntax used give an unambiguous representation of the trees. E.g. you could use `[]` instead of `()`, an extra level of brackets `[[]]` instead of `[]`, outer parenthesis are present or missing, extra commas or no commas, extra spaces, parenthesis or no parenthesis, etc.
All of these are equivalent:
```
(1 (2 (1 0) 0))
[1 [2 [1 0] 0]]
1 2 1 0 0
12100
(1 [2 (1 0) 0])
.:.--
*%*55
(- (+ (- 1) 1))
-+-11
```
Also a variation purposed by @xnor in a comment.
Since there is a way to translate this to a format that can be understood it is acceptable.
```
[[[]][]] is (2 (1 0) 0)
```
To make this easier to understand convert some of the `[]` to `()` like so
```
[([])()]
```
Now if you start with
```
[]
```
then insert a binary which needs two expressions you get
```
[()()] which is 2
```
and then for the first () insert a unary which needs one expression you get
```
[([])()] which is 21
```
but since `[]` or `()` with no inner bracketing can represent 0 which needs no more expressions you can interpret it as
```
2100
```
Note that answers should work theoretically with infinite memory, but will obviously run out of memory for an implementation-dependent finite input.
## Variations of output
```
BNF xnor Christian Ben
b(t, b(t, t)) [{}{{}{}}] (0(00)) (1, -1, 1, -1)
b(t, u(u(t))) [{}{(())}] (0((0))) (1, -1, 0, 0)
b(u(t), u(t)) [{()}{()}] ((0)(0)) (1, 0, -1, 0)
b(b(t, t), t) [{{}{}}{}] ((00)0) (1, 1, -1, -1)
b(u(u(t)), t) [{(())}{}] (((0))0) (1, 0, 0, -1)
u(b(t, u(t))) [({}{()})] ((0(0))) (0, 1, -1, 0)
u(b(u(t), t)) [({()}{})] (((0)0)) (0, 1, 0, -1)
u(u(b(t, t))) [(({}{}))] (((00))) (0, 0, 1, -1)
u(u(u(u(t)))) [(((())))] ((((0)))) (0, 0, 0, 0)
```
## A possible place to check for duplicate trees
One place to check for a duplicate is with M(5).
This one tree was generated twice for M(5) from M(4) trees
```
(2 (1 0) (1 0))
```
the first by adding a unary branch to
```
(2 (1 0) 0)
```
and second by adding a unary branch to
```
(2 0 (1 0))
```
## Understanding BNF
BNF is composed of simple rules:
```
<symbol> ::= expression
```
where on the left is a symbol name surrounded by `<>`.
On the right is the expression for constructing the symbol.
Some rules use other rules in the construction, e.g.
```
<e> ::= <terminal>
```
`e` can be a `terminal`
and some rules have characters that are used in constructing the symbol, e.g.
```
<terminal> ::= "0"
```
`terminal` is just the character zero.
Some rules have multiple ways of constructing them, e.g.
```
<e> ::=
<terminal>
| <unary>
| <binary>
```
An `e` can be a `<terminal>` or a `<unary>` or a `<binary>`.
And some rules are a sequence of parts, e.g.
```
<unary> ::= "(1" <e> ")"
```
A `unary` is the characters `(1` followed by what can be constructed for `e` followed by `)`.
You always start with the starting rule, which for this `<e>`.
Some simple examples:
The simplest sequence is just `0`. So we start with the starting rule `<e>` and see that there are three choices:
```
<terminal>
| <unary>
| <binary>
```
so take the first one `<terminal>`. Now a terminal has no choices and is `0`. So replace `<terminal>` with `0` in the `<e>` rule and you are done.
Then next one is `(1 0)`. Start with `<e>` and use rule `<unary>` which has
```
"(1" <e> ")"
```
Now this needs an `<e>` so we go back to `<e>` and make a choice of one of the three, this time choosing, `<terminal>` which gives `0`. Replacing `0` into `(1 <e> )` gives `(1 0)`, and this is replaced into `<unary>` so `<e>` is `(1 0)`.
[Answer]
## Haskell, 68 bytes
```
t 0=[""]
t 1=["0"]
t n=['(':x++y++")"|k<-[1..n-1],x<-t k,y<-t$n-k-1]
```
Terminal nodes are represented by `0`, unary and binary nodes by `(e)` resp. `(ee)`, so the two three-node trees are given as `(00)` and `((0))`.
Examples:
```
*Main> t 5
["(0(00))","(0((0)))","((0)(0))","((00)0)","(((0))0)","((0(0)))","(((0)0))","(((00)))","((((0))))"]
*Main> length $ t 8
127
*Main> length $ t 15
113634
```
[Answer]
## CJam (37 bytes)
```
0aa{_2m*2\f+1Y$f+++:e__&}qi:A*{,A=},p
```
[Online demo](http://cjam.aditsu.net/#code=0aa%7B_2m*2%5Cf%2B1Y%24f%2B%2B%2B%3Ae__%26%7Dqi%3AA*%7B%2CA%3D%7D%2Cp&input=3). Note that this is not very efficient, and you probably don't want to try calculating input `5` online.
Dissection to follow.
[Answer]
## Pyth (24 21 19 bytes)
This is based on my [Python 3 solution](https://codegolf.stackexchange.com/a/112895/39211).
```
f!|sTf<sY0._T^}1_1t
```
It's my first time using Pyth so this is likely still golfable.
**Example**, output when input is `4`:
```
[[1, 0, -1], [1, -1, 0], [0, 1, -1], [0, 0, 0]]
```
1 represents a binary node, 0 represents a unary node, and -1 represents a terminal node. There is an implied terminal node at the end of every tree.
**Explanation**:
```
f!|sTf<sY0._T^}1_1t
f filter
^ t length n-1 lists of elements
}1_1 from [1, 0, -1]
!| for when both
sT sum of list is 0, and
f ._T for each prefix of list,
<sY0 sum of prefix is non-negative.
```
[Answer]
## brainfuck, 107 bytes
```
,>++>-[-[<-[<-[>>[[>+<-]<]>+>[[<+>>>>>+<<<<-]>]>>++>,++++>]>[<+>-[+>>]>[<->[.<<<
<<]+[->+]+>>>]]]]<[[,<]<]<]
```
Formatted:
```
,>++>-
[
-
[
<-
[
<-
[
>>
[[>+<-]<]
>+>
[[<+> >>>>+<<<<-]>]
>>++>,++++>
]
>
[
<+>-
[
+>>
]
>
[
<->[.<<<<<]
+[->+]
+>>>
]
]
]
]
<
[
[,<]
<
]
<
]
```
[Try it online](https://tio.run/nexus/brainfuck#HYvBDcBACMPenSWXThBlkSj7j3GFGh6WMPcYMMPoXzsxxKrGuOAFGljXmx8M43tlplil826lIjS6jx2UHHXn3ucD)
Input is taken as a [byte](https://codegolf.meta.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values/4719#4719), and the tree `12100` is represented as `\x01\x02\x03\x02`: to convert back, translate `tr/\x01\x02\x03/012/`, reverse the string, and add a final `0`. Trees are separated by `\xfe`. (The output can be made easier to read by e.g. changing the first `-` into `-36` and the `.` into `+47.-47`, where `-36` means a string of 36 `-` characters, etc.)
This approach makes use of the property (which Ben Frankel also used): considering the possible nodes as `-1, 0, 1` and disregarding the final `-1` node, a list represents a valid tree if and only if (1) all prefixes of the list have non-negative sum, and (2) the sum of the entire list equals `0`. The first condition is maintained while generating intermediate nodes, so only the second condition needs to be checked at the end.
The tape is divided into 5-node cells,
```
i d x 0 0
```
where `i` is the index (descending from left to right), `d` is the partial sum, and `x` is the element.
Sketch of control flow:
```
take n and push initial node
while stack is non-empty:
if rightmost node can be decremented:
decrement rightmost node
if there are less than n nodes:
push new node
else if valid tree:
print
else:
backtrack (pop)
```
Note that sometimes a value is stored or initialized as one or two greater than the actual (conceptual) value and adjusted as needed.
[Answer]
## Python 3 (138 134 128 121 119 bytes)
```
from itertools import*
lambda n:[any(sum(t[:k])<0for k in range(n))|sum(t)or print(t)for t in product(*[[-1,0,1]]*~-n)]
```
Example output, for `n=5`:
```
(0, 0, 0, 0)
(0, 0, 1, -1)
(0, 1, -1, 0)
(0, 1, 0, -1)
(1, -1, 0, 0)
(1, -1, 1, -1)
(1, 0, -1, 0)
(1, 0, 0, -1)
(1, 1, -1, -1)
```
1 represents a binary node, 0 represents a unary node, and -1 represents a terminal node. There is an implied terminal node at the end of every tree.
The program starts taking too long at around `n=17`.
[Answer]
## JavaScript (Firefox 30-57), 79 bytes
```
f=(m,l=0)=>m?[for(n of[1,0,-1])if(l>n&l<=m+n)for(a of f(m-1,l-n))[...a,n]]:[[]]
```
Where `-1` represents a terminal, `0` a unary node and `1` a binary node. Starts getting slow at `m=14` on my PC. Recursively works back from the end of the tree.
* The number of unaccounted-for nodes `l` is limited by the fact that there may only be 1 node left at the end.
* The type of the next node `n` is limited by the need to have enough unaccounted-for nodes to be its children.
[Answer]
## Prolog, 149 144 138 137 131 107 bytes
```
e(L,L)-->[0].
e([_|A],L)-->
[1],
e(A,L).
e([_,_|A],L)-->
[2],
e(A,B),
e(B,L).
e(M,E):-
length([_|L],M),
e(L,[],E,[]).
?- e(5,S).
S = [1, 1, 1, 1, 0] ;
S = [1, 1, 2, 0, 0] ;
S = [1, 2, 0, 1, 0] ;
S = [1, 2, 1, 0, 0] ;
S = [2, 0, 1, 1, 0] ;
S = [2, 0, 2, 0, 0] ;
S = [2, 1, 0, 1, 0] ;
S = [2, 1, 1, 0, 0] ;
S = [2, 2, 0, 0, 0].
```
And to count the solutions
```
e_count(N,Count) :-
length([_|Ls], N),
findall(., phrase(e(Ls,[]),E), Sols),
length(Sols, Count).
?- e_count(N,Count).
N = Count, Count = 1 ;
N = 2, Count = 1 ;
N = 3, Count = 2 ;
N = Count, Count = 4 ;
N = 5, Count = 9 ;
N = 6, Count = 21 ;
N = 7, Count = 51 ;
N = 8, Count = 127 ;
N = 9, Count = 323 ;
N = 10, Count = 835 ;
N = 11, Count = 2188 ;
N = 12, Count = 5798 ;
N = 13, Count = 15511 ;
N = 14, Count = 41835 ;
N = 15, Count = 113634
```
[Answer]
## Python, 71 bytes
```
f=lambda n:{(a+b,)for k in range(n)for a in f(k)for b in f(n+~k)}or[()]
```
This represents trees as nested tuples such as `((((),), ()),)`, which can be transformed into `((())())` by removing commas, spaces, and the outermost `()`.
An earlier 76-byte version:
```
f=lambda n:{'('+a+b+')'for k in range(n)for a in f(k)for b in f(n+~k)}or['']
```
[Answer]
## CJam, 38 bytes
Uses a different approach that Peter Taylor's CJam answer.
```
3rim*{:(1\+[{1$+}*])\:(_:z#|!},
```
Output will be something like `1110120020102100`. Each tree is a group of `n` digits (where `n` is the input number).
The basic idea is that we generate each possible string of digits `0`, `1`, and `2`, and then filter only the ones that are well-formed trees.
]
|
[Question]
[
A [bag](https://en.wikipedia.org/wiki/Multiset), also called a multiset, is an unordered collection. You can call it a set that allows duplicates, or a list (or an array) that is not ordered/indexed. In this challenge, you are asked to implement bag operations: addition, difference, multiplication, division, counting and equality test.
# Operations
The specified operations may not be conventional.
* **addition** combines two bags into one, conserving the total number of each value
`[1,2,2,3] + [1,2,4] = [1,1,2,2,2,3,4]`
* **difference** removes from a bag each element of another bag, or does nothing if no such element
`[1,2,2,4] - [1,2] = [2,4]` `[1,2,3] - [2,4] = [1,3]`
* **multiplication** multiplies each element in the bag.
`[1,2,3,3,4] * 3 = [1,1,1,2,2,2,3,3,3,3,3,3,4,4,4]` `2 * [1,3] = [1,1,3,3]`
* **division** is an uncommon one: each n equal elements are put in n equal new bags, elements that cannot form an n-group remain in the bag. Return any one of the n new bags.
`[1,1,2,2,2] / 2 = [1,2]` `[1,2,2,3,3,3] / 3 = [3]`
* **counting** counts how many divisor bags can be produced from the dividend bag
`[1,1,2,2,2,2,3,3,3] c [1,2,3] = 2`
* **equality test** checks if two bags have the same numbers of each element
`[1,2,2,3] == [3,2,1,2] = truthy` `[1,2,3] == [1,2,2,3] = falsy` (can also use `=` for this)
If you are using your own symbols for the operators, please specify.
# Formats
Bags will be displayed as lists of the form `[1,1,2,3,4]`. You can use any other bracket than square ones, or even use quotes, or nothing at all. The elements will be integers(mathematically, not necessarily `int`) for the purpose of this question. Bags do not have to be sorted.
The **input format** will be two bags or a bag and an integer, with an operator. You can specify your own format as long as it contains these three.
The **output format** should be a single bag of the same format.
# Rules
* you may not use built-in functions, operations or libraries (including the standard library) that already implement these; it's ok though to use list concatenation and multiplication since they are by definition list operations, not bag operations (which happen to basically do the same thing)
* standard loopholes apply
* shortest answer wins
# Test cases
```
[1,2,2,3] + [1,2,4]
[1,1,2,2,2,3,4]
[1,2,2,4] - [1,2]
[2,4]
[1,2,3] - [2,4]
[1,3]
[1,2,3,3,4] * 3
[1,1,1,2,2,2,3,3,3,3,3,3,4,4,4]
2 * [1,3]
[1,1,3,3]
[1,1,2,2,2] / 2
[1,2]
[1,2,2,3,3,3] / 3
[3]
[1,1,2,2,2,2,3,3,3] c [1,2,3]
2
[3,2,1,2] == [1,2,2,3]
truthy
[1,2,3] == [1,2,2,3]
falsy
```
[Answer]
# APL (155)
```
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
```
This defines an operator `∆` 'bag', which defines bag operations for given functions. I.e. `+∆` would be addition. It then reads a line from the keyboard and evaluates it as an APL expression.
The functions are:
* `+∆`, addition
* `-∆`, subtraction
* `×∆`, multiplication
* `÷∆`, division
* `⊂∆`, counting
* `≡∆`, equivalence (though due to golfing any unrecognized function will do equivalence)
Explanation:
* `∆←{`...`}`: define an operator `∆`:
+ `O←⍺⍺`: store the given function in `O` (`⎕CR` won't work with `⍺⍺` directly)
+ `O←⎕CR'O'`: get the string representation of that function
+ `'+'=O`...`:`: for addition,
- `⍺,⍵`: join the two lists together
- `R[⍋R←`...`]`: and sort the result
+ `'-'=O:`: for subtraction,
- `⍺{`...`}⍵`: run the following recursive function:
* `⍵≡⍬:⍺`: if the subtrahend is empty, return the minuend
* `⍺/⍨(⍳⍴⍺)≢⍺⍳⊃⍵∇1↓⍵`: otherwise, remove the first element of the subtrahend from both the subtrahend and the minuend and try again
+ `(⍬=⍴⍵)∧K←'×'=O:` for multiplication, and if the right argument is not a bag:
- `⍵/⍺`: replicate each element in the left argument by the right argument
+ `K:`: ...and if the right argument *is* a bag:
- `⍺/⍵`: replicate each element in the right argument by the left argument (this is so that multiplication is commutative)
+ `'÷'=O:`: for division,
- `⍵≤⍺∘.+⍺`: see which elements in ⍺ occur at least ⍵ times,
- `⍺/⍨`: select those from ⍺,
- `∪`: and remove all duplicates from that list
+ `'⊂'=O:`: for counting,
- `⍵{`...`}⍺`: run the following recursive function:
* `(∪⍺)≢∪⍵:0`: if one list contains elements the other doesn't, the result is 0
* `1+⍺∇⍵-∆⍺`: otherwise, subtract the dividend from the divisor, try again, and increment the result.
+ `⋄`: if none of the above, do the equivalence test:
- `⍺[⍋⍺]≡⍵[⍋⍵]`: sort both lists and see if they are equal
* `⎕`: read an expression from the keyboard, evaluate it, and output the result.
Test cases:
```
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
1 2 2 3 +∆ 1 2 4
1 1 2 2 2 3 4
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
1 2 2 4 -∆ 1 2
2 4
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
1 2 3 -∆ 2 4
1 3
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
1 2 3 3 4 ×∆ 3
1 1 1 2 2 2 3 3 3 3 3 3 4 4 4
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
2 ×∆ 1 3
1 1 3 3
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
1 1 2 2 2 ÷∆ 2
1 2
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
1 2 2 3 3 3 ÷∆ 3
3
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
1 1 2 2 2 2 3 3 3 ⊂∆ 1 2 3
2
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
3 2 1 2 ≡∆ 1 2 2 3
1
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
1 2 3 ≡∆ 1 2 2 3
0
```
[Answer]
## JavaScript (ES6), 260 bytes
```
(x,o,y,a=a=>a.reduce((r,e,i)=>[...r,...Array(e).fill(i)],[]),b=(a,r=[])=>a.map(e=>r[e]=-~r[e])&&r)=>[z=>a(b(y,z)),z=>y.map(e=>z[e]&&z[e]--)&&a(z),z=>a(z.map(e=>e*y)),z=>a(z.map(i=>i/y|0)),z=>b(y).map((e,i)=>r=Math.min(r,z[i]/e),r=1/0)|r,z=>``+z==b(y)][o](b(x))
```
Takes 3 parameters. The first parameter is an array, the second is an operator, the third depends on the operator. Bags are required to hold non-negative integers.
```
[...] 0 [...] -> addition
[...] 1 [...] -> difference
[...] 2 <n> -> multiplication
[...] 3 <n> -> division
[...] 4 [...] -> counting
[...] 5 [...] -> equality
```
Ungolfed:
```
function do_bag_op(lhs, op, rhs) {
function bag2array(bag) {
return bag.reduce(function (result, entry, index) {
return result.concat(Array(entry).fill(index));
}, []);
}
function array2bag(array, bag) {
if (!bag) bag = [];
array.forEach(function (entry) {
if (bag[entry]) bag[entry]++;
else bag[entry] = 1;
}
return bag;
}
var bag = array2bag(lhs);
switch (o) {
case 0: // addition
return bag2array(array2bag(rhs, bag));
case 1: // difference
rhs.forEach(function(entry) {
if (bag[entry]) bag[entry]--;
});
return bag2array(bag);
case 2: // multiplication
return bag2array(bag.map(function (entry) {
return entry * rhs;
}));
case 3: // division
return bag2array(bag.map(function (entry) {
return Math.floor(entry / rhs);
}));
case 4: // counting
return Math.floor(array2bag(rhs).reduce(function (count, entry, index) {
return Math.min(count, bag[index] / entry);
}, Infinity));
case 5: // equality
return String(bag) == String(array2bag(rhs));
}
}
```
[Answer]
# Octave, ~~253~~ ~~244~~ 226 bytes
```
function r=f(a,b,o)
u=union(a,b);p=hist(a,u);q=hist(b,u);m=d=0;if(numel(b)==1)m=p.*b;d=p/b;elseif(numel(a)==1)m=a.*q;end
r={p+q,p-q,m,d,min(fix(p./q)),isequal(p,q)}{o};if(o<5)r=[arrayfun(@(x,y)repmat(y,1,x),r,u,'un',0){:}];end
```
This function must be in a file. To write the function in the command window you must use `endfunction` or `end`.
Thanks to [Luis Mendo](https://stackoverflow.com/users/2586922/luis-mendo) for saving 18 bytes.
The operations are:
```
1 = addition
2 = difference
3 = multiplication
4 = division
5 = counting
6 = equality test
```
Usage example:
```
>> f([1,2,2,3], [1,2,4], 1)
ans = 1 1 2 2 2 3 4
>> f([1,2,2,4], [1,2], 2)
ans = 2 4
>> f([1,2,3], [2,4], 2)
ans = 1 3
>> f([1,2,3,3,4], 3, 3)
ans = 1 1 1 2 2 2 3 3 3 3 3 3 4 4 4
>> f(2, [1,3], 3)
ans = 1 1 3 3
>> f([1,1,2,2,2], 2, 4)
ans = 1 2
>> f([1,2,2,3,3,3], 3, 4)
ans = 3
>> f([1,1,2,2,2,2,3,3,3], [1,2,3], 5)
ans = 2
>> f([3,2,1,2], [1,2,2,3], 6)
ans = 1
>> f([1,2,3], [1,2,2,3], 6)
ans = 0
```
Ungolfed:
```
function r = f(a,b,o)
u = union(a,b);
p = hist(a,u);
q = hist(b,u);
m = d = 0;
if (numel(b)==1)
m = p.*b;
d = p/b;
elseif (numel(a)==1)
m = a.*q;
end
r = {p+q, p-q, m, d, min(fix(p./q)), isequal(p,q)}{o};
if (o<5)
r = [arrayfun(@(x,y) repmat(y, 1, x), r, u, 'un', 0){:}];
end
end
```
[Answer]
## Mathematica, ~~387~~ ~~347~~ ~~300~~ 284 bytes
```
k=KeyValueMap[Table,#]&;j=b@@Join@@#&;l=List;q=Counts
b~SetAttributes~Orderless
a_b+c_b^:=j@{a,c}
c_b-a_b^:=j@k@Merge[q/@(l@@@{a+c,2a}),-Min[0,+##2-#]&@@#&]
a_b*n_Integer/;n>0^:=a+a*(n-1)
a_Rational c_b^:=j@k[⌊a#⌋&/@q@*l@@c]
a_b==d_b^:=l@@a==l@@d
c_b/a_b^:=If[(c-a)+a==c,1+(c-a)/a,0]
```
Slightly degolfed (a.k.a old version), didn't have full support for equality tests (returned truthy values, but left unevaluated for non-matching bags).
```
SetAttributes[b,Orderless]
b/:-a_b:=d@@a
b/:a_b+c_b:=Join[a,c]
d/:a_b+c_d:=b@@Join@@KeyValueMap[Table,Merge[Counts/@(List@@@{a+b@@c,b@@c+b@@c}),Max[0,#-(+##2)]&@@#&]]
b/:Rational[1,a_]c_b:=b@@Join@@KeyValueMap[Table,Floor[#/a]&/@Counts@*List@@c]
b/:(a_b)^-1:=c@@a
c/:a_b d_c:=Min@Merge[Counts/@(List@@@{a,d}),If[+##2==0,\[Infinity],#/+##2]&@@#&]
b/:a_b*n_Integer:=a+a*(n-1)
```
Implements the required data type with head `b`.
First `b` is defined to be `Orderless`. Any object passed to the kernel with head `b` will autosort its arguments. So even if `b[3,2,1]` is typed in, the evaluator will never see anything other than `b[1,2,3]`.
Addition is trivially defined as joining the elements.
A special rule for the difference of two bags is defined (explained below). Previous version had an auxiliary symbol for expressions of form `-bag`.
Then multiplication (as long as `n` is a positive integer) is recursively defined as `n*b[...] = b[...] + (n-1)*b[...]` which will eventually reduce to a simple sum.
The special rule for `b[...] - b[...]` counts the number of distinct elements in the sum of the bags and subtracts the bag to be subtracted twice from that result. Easier explained:
```
b[1,2,3,4,5] - b[2,3,6]
Element counts in sum of bags: <|1->1, 2->2, 3->2, 4->1, 5->1, 6->1|>
Element counts in 2x second bag: <|2->2, 3->2, 6->2|>
Subtracting the corresponding values:
<|1->1, 2->0, 3->0, 4->1, 5->1, 6->-1|>
```
Above is a list of `Keys->Values`. `KeyValueMap` with `Table` creates lists of each `Key` `Value` times. (there's also a `Max[...,0]` there to not attempt creation of negative length tables). This comes out as:
```
{{1},{},{},{4},{5},{}}
```
which is flattened and head `List` is replaced with `b`.
Division by integers is somewhat similar in functions used, it is simply the floored division of the element counts by the integer.
Division by sets or counting I've changed since the original implementation. It is now recursively done as follows. Say, we divide bag `b1` by `b2` (which in the golfed code are `c` and `a` respectively. If `(b1-b2) + b2 == b1`, then add 1 and add to that the result of dividing `(b1-b2)/b2`. If not, return 0 and exit the recursion.
If bags match, built-in `==` gives `True`. The last line forces a `False` if they don't.
Test cases:
```
Input:
b[1, 2, 2, 3] + b[1, 2, 4]
b[1, 2, 2, 4] - b[1, 2]
b[1, 2, 3] - b[2, 4]
b[1, 2, 3, 3, 4]*3
2*b[1, 3]
b[1, 1, 2, 2, 2]/2
b[1, 2, 2, 3, 3, 3]/3
b[1, 1, 2, 2, 2, 2, 3, 3, 3] /b[1, 2, 3]
b[3, 2, 1, 2] == b[1, 2, 2, 3]
b[1, 2, 3] == b[1, 2, 2, 3]
Output:
b[1, 1, 2, 2, 2, 3, 4]
b[2, 4]
b[1, 3]
b[1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4]
b[1, 1, 3, 3]
b[1, 2]
b[3]
2
True
False
```
[Answer]
## 05AB1E, ~~92~~ ~~87~~ ~~83~~ ~~82~~ 77 bytes
```
>i‚˜,}¹iи˜Qis}GD})˜,}¹<i³v²y¢O}){0è,}¹Íi{s{Q,}¹Í<iÙv²y¢O³‹_iy}}),}svy†¬yQi¦}}
```
**Split by operation**
```
>i # if 0
‚˜,} # addition
¹i # if 1
и˜Qis}GD})˜,} # multiplication
¹<i # if 2
³v²y¢O}){0è,} # count
¹Íi # if 3
{s{Q,} # equality
¹Í<i # if 4
Ùv²y¢O³÷Fy}}),} # division
# else
svy†¬yQi¦}} # difference
```
**Explanation**
*Addition*
```
‚˜,}
```
Put one bag in other and flatten them to one bag.
*Multiplication*
```
и˜Qis}
```
Make sure the number is on the top of the stack. Call this X.
```
GD})˜,}
```
Duplicate the bag X times and join to one bag.
*Count*
```
³v²y¢O}){0è,}
```
For each element in the divisor bag, count number of occurences in dividend bag.
The minimum count will be the number of bags we can make.
*Equality*
```
{s{Q,}
```
Sort both bags and check if they're equal.
*Division*
```
Ùv²y¢O³÷Fy}}),}
```
Count how many times each unique element occurs in the bag.
If it occurs at least as many times as the divisor. Keep (nr\_of\_copies\_total // divisor) copies in the bag.
*Difference*
```
svy†¬yQi¦}}
```
For each element in the subtrahend, sort it to the front of the minuend.
If the current subtrahend if equal to the first element in the minuend, remove it from the minuend.
[Answer]
## Q - 219 characters
```
a:(,)
s:{[x;y]x((!:)(#:)x)except(,/)({.[(#);x]}')flip(7h$(({(+/)x=y}[y]')(?:)y);(({where x=y}[x]')y))}
m:{(,/)$[0>(@:)x;(#[x]')y;(#[y]')x]}
d:{(?:)x(&:)({y<=(+/)x=z}[x;y]')x}
c:{min({(+/)x=y}[x]')y}
e:{(asc x)~asc y}
```
`a` for addition, `s` for difference (subtraction), `m` for multiplication, `d` for division, `c` for counting, `e` for equality.
The addition algorithm is the obvious one, just joining the bags.
The subtraction function indexes in input bag (represented as an array) with the entire index range, except for the first `n` indices of each equivalence class formed by equality to each element in `y`, where `n` is the number of copies of that representative in `y`. Handling possible duplicates in `y` makes this a real monster of a function.
The multiplication function takes `x` values from each `y`, in the case that `y` is a single value, instead of an array, it just replicates them.
The division function produces the values whose count in the array is greater than `y`, and then removes duplicates.
The counting function calculates the counts of each element in `y`, and then returns the minimum.
Two bags are equal if their sorted array representations are equal.
[Answer]
# Ruby, class definition answer, ~~323~~ 291 bytes
Mostly just wanted to make the `Bag` an actual class because of Ruby's flexibility with classes. In this case, it inherits from `Array` because it's shorter than having to initialize an internal array and dealing with the other stuff.
I'll probably do a more-serious golfing answer that uses a function to deal with the operations tomorrow. I'm very tired and I had too much fun with this ~~even though I had to wrangle with the numerics class definition to get `Number * Bag` working properly~~ PRAISE THE COERCE FUNCTION FOR MAKING IT SO I DIDN'T NEED TO MESS UP THE NUMERICS CLASS DEFINITIONS
[Try it online!](https://repl.it/C8h6) (Whitespace doesn't matter in Ruby, so the code is slightly ungolfed there.)
```
class B<Array
def == o
sort==o.sort
end
def + o
B.new super
end
def - o
r=to_a
o.map{|i|r[r.index(i)||size]=p}
B.new r-[p]
end
def * i
B.new super
end
def / i
B.new uniq.map{|o|[o]*(count(o)/i)}.flatten
end
def c o
o.map{|i|count i}.min
end
def inspect
sort
end
def coerce o
[self,o]
end
end
```
[Answer]
# Ruby, 201 bytes
As promised in my other answer, here's one that uses functions instead of building a new class. I'm so close to breaching the 200 byte mark... [Try it online](https://repl.it/C9CM)
This uses the same opcodes as @Neil in his JavaScript answer, and the same order of arguments (lhs, opcode, rhs)
```
0: Addition
1: Difference
2: Multiplication
3: Division
4: Counting
5: Equality
```
---
The code:
```
->x,o,y{[->{(x+y).sort},->r=[*x]{y.map{|i|r[r.index(i)||x.size]=p};r-[p]},->{(x==[*x]?x*y :y*x).sort},->{x.uniq.map{|i|[i]*(x.count(i)/y)}.flatten},->{y.map{|i|x.count i}.min},->{x.sort==y.sort}][o][]}
```
[Answer]
# C++, ~~555~~ 551 bytes
(line breaks added for readability - only the first newline is required and counted)
```
#include<map>
struct B:std::map<int,int>{
B(std::initializer_list<int>l){for(auto i:l)++(*this)[i];}};
B operator+(B a,B b){for(auto m:b)a[m.first]+=m.second;return a;}
B operator-(B a,B b){for(auto m:b){int&x=a[m.first];x-=x>m.second?m.second:x;if(!x)a.erase(m.first);};return a;}
B operator*(B b,int n){for(auto m:b)b[m.first]*=n;return b;}
B operator*(int n,B b){return b*n;}
B operator/(B b,int n){for(auto m:b)if(!(b[m.first]/=n))b.erase(m.first);return b;}
int operator/(B a,B b){auto r=~0u;for(auto m:b){int x=a[m.first]/m.second;r=r>x?x:r;}return r;}
```
# Explanation
We implement our bag as a map of (value, count). The basic operations can be implemented by manipulating the counts; subtraction and integer division also need to remove any elements whose count reaches zero, so that `std::map::operator==` will work as the equality test.
The following expanded code is a generic version of the above, much less golfed: we use a separate `s()` to squeeze out any zero-count values, and we implement `const` operations in terms of assignment operators in the idiomatic C++ way. We also use `s()` to make multiplication by `0` return a truly empty bag (tested by adding `(B{1}*0 != B{})` to `main()`); the original fails this test, and it's not clear whether it's a requirement.
```
template<class T>
struct Bag{
std::map<T,int>b;
Bag(const std::initializer_list<T>& l){for(auto i:l)++b[i];}
Bag&s(){for(auto i=b.begin();i!=b.end();i=i->second?++i:b.erase(i));return*this;}
Bag&operator+=(const Bag& o){for(auto m:o.b)b[m.first]+=m.second;return*this;}
Bag&operator-=(const Bag& o){for(auto m:o.b){auto&x=b[m.first];x-=x>m.second?m.second:x;}return s();}
Bag&operator*=(int n){for(auto m:b)b[m.first]*=n;return s();}
Bag&operator/=(int n){for(auto m:b)b[m.first]/=n;return s();}
auto operator/=(const Bag& o){auto r=~0u;for(auto m:o.b){int x=b[m.first]/m.second;r=r>x?x:r;}return r;}
bool operator==(const Bag& o)const{return b==o.b;}
Bag operator+(Bag o)const{return o+=*this;}
Bag operator-(const Bag& o)const{Bag t=*this;return t-=o;}
Bag operator*(int n)const{Bag t=*this;return t*=n;}
friend Bag operator*(int n,const Bag& b){return b*n;}
auto operator/(auto n)const{Bag t=*this;return t/=n;}
bool operator!=(const Bag& o)const{return b!=o.b;}
};
using B = Bag<int>;
```
## Tests
```
bool operator!=(B a,B b){return!(a==b);}
int main()
{
return 0
+ (B{1,2,2,3}+B{1,2,4} != B{1,1,2,2,2,3,4})
+ (B{1,2,2,4}-B{1,2} != B{2,4})
+ (B{1,2,3}-B{2,4} != B{1,3})
+ (B{1,2,3,3,4}*3 != B{1,1,1,2,2,2,3,3,3,3,3,3,4,4,4})
+ (2*B{1,3} != B{1,1,3,3})
+ (B{1,1,2,2,2}/2 != B{1,2})
+ (B{1,2,2,3,3,3}/3 != B{3})
+ (B{1,1,2,2,2,2,3,3,3}/B{1,2,3} != 2)
+ (B{3,2,1,2} != B{1,2,2,3})
+ (B{1,2,3} == B{1,2,2,3})
;
}
```
[Answer]
**Python 2.7 - 447B (filesize)**
This is my first try at Codegolf, I hope it satisfies. I needed 2h. (But I'm still a beginner at Python)
Edit: Thanks to "Kevin Lau - not Kenny" for pointing out these:
* pythons self argument in a class can be replaced by anything
* indentation only has to be a single space
* the builtin sorted - funktion (I **knew** I had seen it, but I thought it to be a method in lists)
* \_\_ radd \_\_ is not needed (I only support adding B-objects(Bag-type) anyways)
Edit: Additionally I saved space by replacing functions with lambdas and new lines and indentations with more semicolons.
Code:
```
class B:
def __init__(S,L=[]):S.L=sorted(list(L));S.p=lambda:[[i]*S.L.count(i)for k,i in enumerate(S.L)if i!=S.L[k-1]];S.__eq__=lambda o:S.L==o.L;S.__rmul__=S.__mul__=lambda o:B(S.L*o);S.__add__=lambda o:B(S.L+o.L);S.__sub__=lambda o:B([i for k in S.p()for i in k[:max(0,S.L.count(k[0])-o.L.count(k[0]))]]);S.__div__=lambda o:B([i for k in S.p()for i in k[::o][:[-1,None][len(k)%o==0]]]);S.c=lambda o:min([S.L.count(i)//o.L.count(i)for i in o.L])
```
checks:
```
print B([1,2,2,3]) + B([1,2,4]) == B([1,1,2,2,2,3,4]) # Add
print B([1,2,2,4]) - B([1,2]) == B([2,4]) #Substract
print B([1,2,3]) - B([2,4]) == B([1,3]) #Substract
print B([1,2,3,3,4]) * 3 == B([1,1,1,2,2,2,3,3,3,3,3,3,4,4,4])#Multiply
print 2 * B([1,3]) == B([1,1,3,3]) #
print B([1,1,2,2,2]) /2 == B([1,2]) #Divide
print B([1,2,2,3,3,3]) /3 == B([3]) #
print B([1,1,2,2,2,2,3,3,3]).c(B([1,2,3]))==2 #Contained n times
print B([3,2,1,2]) == B([1,2,2,3]) # Equal
print B([1,2,3]) == B([1,2,2,3]) # Unequal
```
Output:
```
True
True
True
True
True
True
True
True
True
False
```
I might try it an other time with set as basis some time.
Edit: Maybe I'll even try with functions only.
[Answer]
# [Go](https://go.dev), 642 bytes
```
type B struct{C map[int]int}
func N(c...int)B{b:=B{make(map[int]int)};for _,d:=range c{b.C[d]+=1};return b}
func(b B)L()(o[]int){for k,v:=range b.C{for i:=0;i<v;i++{o=append(o,k)}};return}
func(b*B)A(O B)B{for k,v:=range O.C{b.C[k]+=v};return*b}
func(b*B)S(O B)B{for k,v:=range O.C{if _,o:=b.C[k];o{b.C[k]-=v}};return*b}
func(b*B)M(n int)B{for k:=range b.C{b.C[k]*=n};return*b}
func(b*B)D(n int)B{for k:=range b.C{b.C[k]/=n;if b.C[k]==0{delete(b.C,k)}};return*b}
func(b B)O(O B)int{i:=0;for;len(b.L())>len(O.L());i++{b=b.S(O)};return i}
func(b B)E(O B)bool{for k,v:=range b.C{if V,o:=O.C[k];o{if V!=v{return 0>1}}else{return 0>1}};return 0<1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZTBbptAEIal9sZTbHPatTE2Xh8qk40UktyaUilSLxaqAEOKjBe0wZYixKWv0YtVqS_RR-nTdNgFDIYqAsvLwHzzz78DP389p6c_mRfsvOcQ7b2Ya1q8z1KRo6ton1_9PuTR7OPfdz_y1yxENnrJxSHIizt4NNvEPHfhV2rRgQfoMw4Mw4BrYhf-mtnF3tuFuPMcKa0oFeibvl0z4XGoFxS-cbfZulNmlpYI84PgyFc47CObfMIEpxuZW1SpO_3YpEKiDMVrtrDi66MVT6dFyrwsC_kWp_qOlA2yAU5scosdwNqXMAdglZIdKDk2aRO_k_j0_8Q4gpbSNVMAK61JMyCNoh4xR8olCes2pDInjI8m3r-VOGfcAjXqgrFFsQ2TMA8xBLp-TLoWO7IxwBbSSSBbScghBbwnN9XSkUvprw9NghOk3ay4Q3qQJD9Nk7G9Al1fK5ecxqUq8IEdi5q0uDHLMkxewl6gqbO4Nst6FN8LOW3VqGKCCu3oCZToSCBbm8_RxtSXcFAXTdV65dZhdQNuVaEEMZhXU0dLeVKiiU5kRTSYfeOLAFsSjhPjFgsiXeiUWLloJteqwHIEu-piL5lPAyaVxI5k2ie2KsckjuBkq2iCaOvA2YPzsaqOi0LyHJR4xPRcYglgJbGB055eOsxe9gTWWlwErEZzJ781cWDc_QWobahCqV7pcIfVOWTRMVFnYtBsjex5TF4fL_r71a_mwB6pShSYVb-IsfPIVnfg85p_f63rUIlRwyMGE9tnP7TsepQuyZEHL9f4PL1FrV-900n9_wM)
Methods `ASMDOE` are the methods described in-order in the OP. `N` is the constructor, taking a list of ints, and `L` is a utility function that turns a bag into a list of ints.
## [Go](https://go.dev), generic, 712 bytes
```
type B[T comparable]struct{C map[T]int}
func N[T comparable](c...T)B[T]{b:=B[T]{make(map[T]int)};for _,d:=range c{b.C[d]+=1};return b}
func(b B[T])L()(o[]T){for k,v:=range b.C{for i:=0;i<v;i++{o=append(o,k)}};return}
func(b*B[T])A(O B[T])B[T]{for k,v:=range O.C{b.C[k]+=v};return*b}
func(b*B[T])S(O B[T])B[T]{for k,v:=range O.C{if _,o:=b.C[k];o{b.C[k]-=v}};return*b}
func(b*B[T])M(n int)B[T]{for k:=range b.C{b.C[k]*=n};return*b}
func(b*B[T])D(n int)B[T]{for k:=range b.C{b.C[k]/=n;if b.C[k]==0{delete(b.C,k)}};return*b}
func(b B[T])O(O B[T])int{i:=0;for;len(b.L())>len(O.L());i++{b=b.S(O)};return i}
func(b B[T])E(O B[T])bool{for k,v:=range b.C{if V,o:=O.C[k];o{if V!=v{return 0>1}}else{return 0>1}};return 0<1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jZTdjppAFMeT9o6nmO7VjKKr4kUjO5ts173rliZremNIAwhbIgKZRZMN4Ul6Y5r0JfoC7TP0aXpmhkG-jA0kjgfP7_8_H_j9x3Ny_JU63tZ59tHOCWNNC3dpwjJ0Feyyq5_7LBi9__vmT_aa-ujDeoW8ZJc6zHEj337J2N7L8nvIS9crO4yzQgv2sYc-NX-HvfF4vCKQbefugorPnbP1cZVHCjNIGPqqbxaUOTFY8XJ3fL_e2EM6LUzmZ3sWI1fiscuN2OQjJjhZ2yuS89ytflC5kClC4YJOzPDmYIbDYZ5QJ039eIMTfUsKxVTEgSDeYUuihcUW1QIq97QFTweVP3CbhKdLhDCAKpMFlSQzKZEjQJ5jPuIY8R6dkPVCZf6AxufSl_-Rfk1jE5zJL5RO8o0f-ZmPIVDv1qA1AUtVC_xcdBv4ZuTHkAjTIbf8aImjmIELZUOHSDXRsMl7UDw3SaK-qYLHL7x7luoeD7yjh7zkTW6nReFHL34joNQmN9OiXOi3v8Wi8oXHBOXawWEo0hEDeajF1q6v0Xqqz-AybDSU57kKywfwiIciRGHfeRKe6mgmboNorB2eEw1eqPFnBrEoxtH4DjMiWlMTm9toJM5SanZOYN4RaNOfOnRDsGtlGD3spvM-2z1g0Qg0QEbVn1OHTtecX32S4u7oPGLjpDMDunSsFIyufaOLmDWslq5sBEDlvg2pWtzp6LJFq-rjPFl6X0erCjv2lvUKa2tVYT01ONGCs0abGp3F6-haMEGpaQCd9wBRelp3_gT-2LNvr3VFQ7DkpnUk-lQeKpVy-doagQPv6aUNvMQv3-fjUX7-Aw)
]
|
[Question]
[
# Scralphabet
A normal bag of Scrabble tiles contains the following letters (`?` is a blank tile, which can stand for any other letter):
```
AAAAAAAAABBCCDDDDEEEEEEEEEEEEFFGGGHHIIIIIIIIIJKLLLLMMNNNNNNOOOOOOOOPPQRRRRRRSSSSTTTTTTUUUUVVWWXYYZ??
```
The letters have the following value:
```
{"A": 1,"B": 3,"C": 3,"D": 2,"E": 1,"F": 4,"G": 2,"H": 4,"I": 1,"J": 8,"K": 5,"L": 1,"M": 3,"N": 1,"O": 1,"P": 3,"Q": 10,"R": 1,"S": 1,"T": 1,"U": 1,"V": 4,"W": 4,"X": 8,"Y": 4,"Z": 10,"?": 0}
```
Given a normal bag of Scrabble tiles, construct the highest-scoring set of non-intersecting words (i.e., individual words, not on a Scrabble board) given the following conditions:
* The score for each word is `sum(letter_values) * length(word)`.
* You may only include a maximum of one word starting with each letter of the alphabet (so, a maximum of 26 words).
* Only valid Scrabble words (from [this dictionary](https://raw.githubusercontent.com/jmlewis/valett/master/scrabble/sowpods.txt)) may be included. You may read the dictionary from a file, hard-code it (ugh), or scrape it from the website.
* You need not use every tile, but all unused tiles form a single word, scored the same way, which subtracts from your score.
If you wish, your code may accept two inputs: the bag contents as a string, and the letter values in some format similar to a python `dict` (as above); alternatively, you can hard-code the bag contents and letter values. It should output the words in your set, their respective scores, and your total score, in some reasonable format.
Highest scoring set of words wins, with ties going to first posted.
[Answer]
# C, 2765 (optimal)
### Edit
Now all in a single C file. This just finds all the optimal solutions. They all must have 6 words of 15 letters and one 10-letter word consisting of 8 letters of value 1 and two blanks. For that I only need to load a fraction of the dictionary and I don't have to look for 15 letter words with blanks.
The code is a simple exhaustive depth-first search.
```
#include <stdio.h>
#include <stdint.h>
#include <string.h>
struct w {
struct lc { uint64_t hi,lo; } lc;
char w[16];
} w15[6000], w10[40000];
int n15,n10;
struct lc pool = { 0x12122464612, 0x8624119232c4229 };
int pts[27] = {0,1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
int f[27],fs[26], w15c[27],w15l[27][6000];
int count(struct lc a, int l) { return (l < 16 ? a.lo << 4 : a.hi) >> 4*(l&15) & 15; }
int matches_val(uint64_t a, uint64_t b) {
uint64_t mask = 0x1111111111111111ll;
return !((a - b ^ a ^ b) & mask);
}
int matches(struct lc all, struct lc a) { return matches_val(all.hi,a.hi) && matches_val(all.lo,a.lo); }
int picks[10];
void try(struct lc cur, int used, int level) {
int c, i, must;
if (level == 6) {
for (i = 0; i<27; i++) if (count(cur, i) && pts[i]>1) return;
for (i = 0; i < n10; i++) if(!(used & (1 << (w10[i].w[0] & 31))) && matches(w10[i].lc, cur)) {
for (c = 0; c<level; c++) printf("%s ",w15[picks[c]].w);
printf("%s\n",w10[i].w);
}
return;
}
for (i = 0; i < 26;i++) if (count(cur,fs[i])) break;
must = fs[i];
for (c = 0; c < w15c[must]; c++) { i = w15l[must][c]; if(!(used & (1 << (w15[i].w[0] & 31))) && matches(cur, w15[i].lc)) {
struct lc b = { cur.hi - w15[i].lc.hi, cur.lo - w15[i].lc.lo };
picks[level] = i;
try(b, used + (1 << (w15[i].w[0] & 31)), level+1);
}}
}
int cmpfs(int *a, int *b){return f[*a]-f[*b];}
void ins(struct w*w, char *s, int c) {
int i;
strcpy(w->w,s);
for (;*s;s++)
if (*s&16) w->lc.hi += 1ll << 4*(*s&15); else w->lc.lo += 1ll << 4*(*s&15) - 4;
if (c) for (i = 0; i < 27;i++) if (count(w->lc,i)) f[i]++, w15l[i][w15c[i]++] = w-w15;
}
int main() {
int i;
char s[20];
while(scanf("%s ",s)>0) {
if (strlen(s) == 15) ins(w15 + n15++,s,1);
if (strlen(s) == 10) ins(w10 + n10++,s,0);
}
for (i = 0; i < 26;i++) fs[i] = i+1;
qsort(fs, 26, sizeof(int), cmpfs);
try(pool, 0, 0);
}
```
Usage:
```
$time ./scrab <sowpods.txt
cc -O3 scrab.c -o scrab
JUXTAPOSITIONAL DEMISEMIQUAVERS ACKNOWLEDGEABLY WEATHERPROOFING CONVEYORIZATION FEATHERBEDDINGS LAURUSTINE
JUXTAPOSITIONAL DEMISEMIQUAVERS ACKNOWLEDGEABLY WEATHERPROOFING CONVEYORIZATION FEATHERBEDDINGS LUXURIATED
JUXTAPOSITIONAL DEMISEMIQUAVERS ACKNOWLEDGEABLY WEATHERPROOFING CONVEYORIZATION FEATHERBEDDINGS LUXURIATES
JUXTAPOSITIONAL DEMISEMIQUAVERS ACKNOWLEDGEABLY WEATHERPROOFING CONVEYORIZATION FEATHERBEDDINGS ULTRAQUIET
JUXTAPOSITIONAL DEMISEMIQUAVERS ACKNOWLEDGEABLY WEATHERPROOFING CONVEYORIZATION FEATHERBEDDINGS UTRICULATE
JUXTAPOSITIONAL DEMISEMIQUAVERS WEATHERPROOFING ACKNOWLEDGEABLY CONVEYORIZATION FEATHERBEDDINGS LAURUSTINE
JUXTAPOSITIONAL DEMISEMIQUAVERS WEATHERPROOFING ACKNOWLEDGEABLY CONVEYORIZATION FEATHERBEDDINGS LUXURIATED
JUXTAPOSITIONAL DEMISEMIQUAVERS WEATHERPROOFING ACKNOWLEDGEABLY CONVEYORIZATION FEATHERBEDDINGS LUXURIATES
JUXTAPOSITIONAL DEMISEMIQUAVERS WEATHERPROOFING ACKNOWLEDGEABLY CONVEYORIZATION FEATHERBEDDINGS ULTRAQUIET
JUXTAPOSITIONAL DEMISEMIQUAVERS WEATHERPROOFING ACKNOWLEDGEABLY CONVEYORIZATION FEATHERBEDDINGS UTRICULATE
OVERADJUSTMENTS QUODLIBETARIANS ACKNOWLEDGEABLY WEATHERPROOFING EXEMPLIFICATIVE HYDROGENIZATION RUBIACEOUS
OVERADJUSTMENTS QUODLIBETARIANS WEATHERPROOFING ACKNOWLEDGEABLY EXEMPLIFICATIVE HYDROGENIZATION RUBIACEOUS
real 0m1.754s
user 0m1.753s
sys 0m0.000s
```
Note every solution is printed twice because when adding a 15-letter 'W' word 2 orders are created because there are 2 'W' tiles.
The first solution found with the point breakdown:
```
JUXTAPOSITIONAL 465
DEMISEMIQUAVERS 480
ACKNOWLEDGEABLY 465
WEATHERPROOFING 405
CONVEYORIZATION 480
FEATHERBEDDINGS 390
LAURUSTINE (LAURU?TI?E) 80
no tiles left
```
### Edit: explanation
What makes searching the entire space possible? While adding a new word I only take into account words that have the rarest remaining letter. This letter need to be in some word anyway (and a 15 letter word since this will be a non 1-value letter, though I don't check for that). So I start with words containing `J, Q, W, W, X, Z` which have counts around `50, 100, 100, 100, 200, 500`. At lower levels I get more cutoff because some words are eliminated by the lack of letters. Breadth of the search tree at each level:
```
0: 1
1: 49
2: 3046
3: 102560
4: 724040
5: 803959
6: 3469
```
Of course a lot of cutoff is gained by not checking non-optimal solutions (blanks in 15 letter words or shorter words). So it is lucky that 2765 solution can be achieved with this dictionary (but it was close, only 2 combinations of 15 letter words give a reasonable leftover). On the other hand it is easy to modify the code to find lower scoring combinations where not all the leftover 10 letters are 1-valued, though it would be harder to prove this would be an optimal solution.
Also the code shows classic case of premature optimization. This version of `matches` function makes the code only 30% slower:
```
int matches(struct lc all, struct lc a) {
int i;
for (i = 1; i < 27; i++) if (count(a, i) > count(all, i)) return 0;
return 1;
}
```
I even figured out how to make the bit magic parallel comparison even shorter than in my original code (highest nibble cannot be used in this case, but this is not a problem, as I only need 26 out of 32 nibbles):
```
int matches_val(uint64_t a, uint64_t b) {
uint64_t mask = 0x1111111111111111ll;
return !((a - b ^ a ^ b) & mask);
}
```
But it gives zero advantage.
### Edit
Writing the explanation above I realized that most of the time is spent on scanning the list of words for those containing a specific letter not in the `matches` function. Calculating the lists upfront gave 10x speedup.
[Answer]
# Python 2, score: ~~1840~~ 2162
This program first finds the best scoring word available with the given tiles (without using wildcards), then makes 10000 attempts to include random words that meet the constraints of unique first character and having available tiles. With the current constants, the program takes 27 seconds to run on my machine. Using larger constants would probably find a higher scoring combination of words.
**UPDATE:** Now uses a 2 stage selection algorithm, so it finds the best of 50 words at each select stage. The penalty score is now used in the evaluation algorithm too.
```
from random import *
tilelist = ('AAAAAAAAABBCCDDDDEEEEEEEEEEEEFFGGGHHIIIIIIIIIJKLLLLMM'
'NNNNNNOOOOOOOOPPQRRRRRRSSSSTTTTTTUUUUVVWWXYYZ??')
maintiles = dict((t, tilelist.count(t)) for t in set(tilelist))
value = {"A": 1,"B": 3,"C": 3,"D": 2,"E": 1,"F": 4,"G": 2,"H": 4,"I": 1,
"J": 8,"K": 5,"L": 1,"M": 3,"N": 1,"O": 1,"P": 3,"Q": 10,"R": 1,
"S": 1,"T": 1,"U": 1,"V": 4,"W": 4,"X": 8,"Y": 4,"Z": 10,"?": 0}
words = open('words.txt', 'rt').read().split()
def sumpoints(word):
return len(word) * sum(value[c] for c in word)
ranked = sorted((sumpoints(w),w) for w in words)[::-1]
for points,word in ranked:
if all(word.count(ch) <= maintiles[ch] for ch in word):
firstword = word
break
def findwordset(first):
tiles = maintiles.copy()
startletter = set(tilelist) - {'?'}
startletter.discard(first[0])
result = [ (first, sumpoints(first)) ]
thistotal = sumpoints(first)
for ch in first:
tiles[ch] -= 1
for i in range(30):
best = None
for word in sample(words, 50):
if word[0] in startletter:
if all(word.count(ch) <= tiles[ch] for ch in word):
points = sumpoints(word)
if best == None or points > best:
best, bestword = points, word
if best:
thistotal += best
result.append( (bestword,best) )
startletter.discard(bestword[0])
for ch in bestword:
tiles[ch] -= 1
penaltyword = ''.join(c*n for c,n in tiles.items())
penalty = sumpoints(penaltyword)
return thistotal - penalty, result, tiles
best = None
for attempt in range(10000):
wordset = findwordset(firstword)
if best == None or wordset > best:
best = wordset
total, result, tiles = best
penaltyword = ''.join(c*n for c,n in tiles.items())
penalty = sumpoints(penaltyword)
for word,points in result:
print '%20s%6s' % (word, points)
print 'Remaining word "%s" penalty = %s' % (penaltyword, -penalty)
print 'Total score = %s' % total
```
I include here the best of a few runs:
```
$ python s.py
OXYPHENBUTAZONE 615
LIQUEFACTIONS 351
DETERMINATIVES 280
FAMILIARISERS 234
JUNKETEERED 253
WOODPIGEON 170
GAYAL 45
CLAUGHT 91
BRIARWOOD 135
Remaining word "V??" penalty = -12
Total score = 2162
```
Note that I do not use the wild cards and pay a larger penalty (due to word length). A future enhancement may include wildcard use.
[Answer]
## Simulated annealing (score 2246)
```
180 ADDITIVELY
338 ERYTHROPHOBIA
345 FLAGELLOMANIACS
435 INTERSUBJECTIVE
171 KOWTOWERS
390 QUADRINGENARIES
250 WEAPONIZED
200 XENOGAMOUS
-9 for blank used as S
-9 for blank used as W
-18 FTU unused
Total score: 2246
```
Unfortunately this is non-deterministic. I'll try to fix that and find a deterministic seed which gives a better value.
```
import java.io.*;
import java.util.*;
public class PPCG50219 {
// Plus two wildcards
private static String CHAR_FREQ = "9224<232911426821646422121";
private static String CHAR_VALUE = "1332142418513113:11114484:";
private static List<List<String>> WORDS;
public static void main(String[] args) {
init();
Random rnd = new Random(1);
FeasibleSolution initial = new FeasibleSolution();
List<List<String>> shuffledByLetter = new ArrayList<List<String>>(WORDS);
Collections.shuffle(shuffledByLetter, rnd);
for (List<String> list : shuffledByLetter) {
Collections.shuffle(list, rnd);
for (String word : list) {
if (initial.canUse(word)) {
initial.use(word);
break;
}
}
}
FeasibleSolution best = anneal(initial, rnd);
System.out.println(best.toStringDetailed());
}
private static void init() {
try {
WORDS = new ArrayList<List<String>>(26);
for (int i = 0; i < 26; i++) WORDS.add(new ArrayList<String>());
// Take dictionary from stdin with fallback to hard-coded path.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "ISO-8859-1"));
if (!br.ready()) {
br.close();
br = new BufferedReader(new InputStreamReader(new FileInputStream("/home/pjt33/notes/dict/sowpods"), "ISO-8859-1"));
}
String line;
FeasibleSolution soln = new FeasibleSolution();
while ((line = br.readLine()) != null) WORDS.get(line.charAt(0) - 'A').add(line);
br.close();
}
catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
public static FeasibleSolution anneal(FeasibleSolution feasibleSolution, Random rnd)
{
//Random rnd = new Random();
FeasibleSolution best = feasibleSolution;
int bestScore = best.score();
double temperature = bestScore / 10;
FeasibleSolution current = best;
int currentScore = bestScore;
for (int i = 0; i < 1024; i++)
{
// Try out some random changes, and then adjust the temperature according to the results.
FeasibleSolution bestAtT = current;
for (int j = 0; j < 256; j++)
{
FeasibleSolution neighbour = current.randomNeighbour(rnd);
int score = neighbour.score();
// Use a simple threshold rather than a Boltzmann probability
if (score >= currentScore - temperature)
{
current = neighbour;
currentScore = score;
temperature *= 0.95;
}
if (score > bestScore)
{
best = neighbour;
bestScore = score;
}
}
if (current == bestAtT) temperature *= 1.01;
if (temperature < 1E-6 * bestScore) break;
}
return best;
}
static class FeasibleSolution {
private final String[] words;
private int blanksUsed;
private final int[] counts;
private FeasibleSolution(String[] words) {
this.words = words;
counts = new int[26];
for (String word : words) {
if (word == null) continue;
for (char ch : word.toCharArray()) counts[ch - 'A']++;
}
for (int i = 0; i < 26; i++) {
int limit = CHAR_FREQ.charAt(i) - '0';
if (counts[i] > limit) blanksUsed += counts[i] - limit;
}
if (blanksUsed > 2) throw new IllegalArgumentException("Required " + blanksUsed + " blanks");
}
public FeasibleSolution() {
this(new String[26]);
}
public FeasibleSolution(FeasibleSolution copy) {
this(copy.words.clone());
}
public boolean canUse(String word) {
int offset = word.charAt(0) - 'A';
String current = clear(offset);
boolean rv = set(offset, word);
clear(offset);
if (!set(offset, current)) throw new IllegalStateException();
return rv;
}
public void use(String word) {
int offset = word.charAt(0) - 'A';
clear(offset);
if (!set(offset, word)) throw new IllegalArgumentException();
}
private boolean set(int offset, String word) {
if (words[offset] != null) throw new IllegalStateException();
if (word != null) {
for (char ch : word.toCharArray()) {
int limit = CHAR_FREQ.charAt(ch - 'A') - '0';
counts[ch - 'A']++;
if (counts[ch - 'A'] > limit) blanksUsed++;
}
}
words[offset] = word;
return blanksUsed <= 2;
}
private String clear(int offset) {
String word = words[offset];
if (word != null) {
for (char ch : word.toCharArray()) {
int limit = CHAR_FREQ.charAt(ch - 'A') - '0';
if (counts[ch - 'A'] > limit) blanksUsed--;
counts[ch - 'A']--;
}
}
words[offset] = null;
return word;
}
public int score() {
int score = 0;
List<List<Integer>> lengths = new ArrayList<List<Integer>>();
for (int i = 0; i < 26; i++) lengths.add(new ArrayList<Integer>());
int unused = 100;
for (String word : words) {
if (word == null) continue;
for (char ch : word.toCharArray()) lengths.get(ch - 'A').add(word.length());
unused -= word.length();
}
for (int i = 0; i < 26; i++) {
int limit = CHAR_FREQ.charAt(i) - '0';
int off = 0;
List<Integer> l = lengths.get(i);
if (l.size() > limit) {
off = l.size() - limit;
Collections.sort(l);
}
else if (l.size() < limit) {
int surplus = limit - l.size();
l.add(-surplus * unused);
}
for (; off < l.size(); off++) score += l.get(off) * (CHAR_VALUE.charAt(i) - '0');
}
return score;
}
public FeasibleSolution randomNeighbour(Random rnd) {
FeasibleSolution soln = new FeasibleSolution(this);
// Shake things up.
List<Integer> used = new ArrayList<Integer>();
int totalCount = 0;
for (int i = 0; i < words.length; i++) {
if (words[i] == null) continue;
used.add(i);
totalCount += words[i].length();
}
if (totalCount > 50) {
int offset = used.get(rnd.nextInt(used.size()));
soln.clear(offset);
}
// TODO We can probably get better results by biasing the shuffle.
List<List<String>> shuffledByLetter = new ArrayList<List<String>>(WORDS);
String theBitThatMatters = Arrays.toString(counts);
Collections.shuffle(shuffledByLetter, rnd);
for (List<String> list : shuffledByLetter) {
Collections.shuffle(list, rnd);
for (String word : list) {
if (word.equals(soln.words[word.charAt(0) - 'A'])) continue;
if (soln.canUse(word)) {
soln.use(word);
if (!theBitThatMatters.equals(Arrays.toString(soln.counts))) return soln;
}
}
// To avoid getting trapped in a local oscillation.
int off = list.get(0).charAt(0) - 'A';
if (soln.words[off] != null) {
soln.clear(off);
return soln;
}
}
throw new RuntimeException("This really shouldn't be reachable");
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (String word : words) {
if (word == null) continue;
if (sb.length() > 0) sb.append(", ");
sb.append(word);
}
return sb.toString();
}
private static int wordScore(String word) {
int wordScore = 0;
for (char ch : word.toCharArray()) {
if (ch != '?') wordScore += (CHAR_VALUE.charAt(ch - 'A') - '0');
}
return wordScore * word.length();
}
public String toStringDetailed() {
int score = 0;
List<List<Integer>> lengths = new ArrayList<List<Integer>>();
for (int i = 0; i < 26; i++) lengths.add(new ArrayList<Integer>());
int unused = 100;
StringBuilder surplusChars = new StringBuilder();
int unusedBlanks = 2;
StringBuilder sb = new StringBuilder();
for (String word : words) {
if (word == null) continue;
for (char ch : word.toCharArray()) lengths.get(ch - 'A').add(word.length());
unused -= word.length();
sb.append(wordScore(word)).append("\t").append(word).append("\n");
}
for (int i = 0; i < 26; i++) {
int limit = CHAR_FREQ.charAt(i) - '0';
int off = 0;
List<Integer> l = lengths.get(i);
if (l.size() > limit) {
off = l.size() - limit;
unusedBlanks -= off;
Collections.sort(l);
}
while (l.size() < limit) {
surplusChars.append((char)('A' + i));
l.add(-unused);
}
for (int j = 0; j < off; j++) sb.append(-l.get(j)).append("\tfor blank used as ").append((char)('A' + i)).append("\n");
for (; off < l.size(); off++) score += l.get(off) * (CHAR_VALUE.charAt(i) - '0');
}
while (unusedBlanks > 0) {
surplusChars.append('?');
unusedBlanks--;
}
sb.append(-wordScore(surplusChars.toString())).append("\t").append(surplusChars).append(" unused\n");
sb.append("Total score: ").append(score());
return sb.toString();
}
}
}
```
[Answer]
# Python, score ~~2638~~ ~~2675~~ ~~2676~~ ~~2689~~ ~~2699~~ 2717
**Result:**
```
OXYPHENBUTAZONE for 615
MICROEARTHQUAKE for 525
FLAVOURDYNAMICS for 435
ADJUSTABILITIES for 375
PREINTERVIEWING for 360
WATERFLOODINGS for 308
EAGLE?OOD? for 100
Left-over word: E
2717
```
**Code:**
```
import time
from multiprocessing import Pool
start_tiles = "AAAAAAAAABBCCDDDDEEEEEEEEEEEEFFGGGHHIIIIIIIIIJKLLLLMMNNNNNNOOOOOOOOPPQRRRRRRSSSSTTTTTTUUUUVVWWXYYZ??"
start_tiles = {l: start_tiles.count(l) for l in set(start_tiles)}
values = {"A": 1,"B": 3,"C": 3,"D": 2,"E": 1,"F": 4,"G": 2,"H": 4,"I": 1,"J": 8,"K": 5,"L": 1,"M": 3,"N": 1,"O": 1,"P": 3,"Q": 10,"R": 1,"S": 1,"T": 1,"U": 1,"V": 4,"W": 4,"X": 8,"Y": 4,"Z": 10,"?": 0}
with open("sowpods.txt") as f:
full_dictionary = list(l.strip() for l in f if l.strip())
def num_wilds_needed(word, tiles):
return sum(max(0, word.count(l) - tiles[l]) for l in word)
def word_is_possible(word, tiles):
# never replace 1st letter with wild, for simplicity
if tiles[word[0]] <= 0:
return False
return num_wilds_needed(word, tiles) <= tiles['?']
def word_score(word):
return sum(values[c] for c in word) * len(word)
def final_score(words, tiles_left, print_leftover=False):
left_over_word = ""
for tile, counts in tiles_left.iteritems():
left_over_word += tile * counts
if print_leftover:
print "Left-over word: %s" % (left_over_word,)
return sum(word_score(word) for word in words) - word_score(left_over_word)
def filter_dictionary(dictionary, tiles_left, start_letters):
return [word for word in dictionary
if word[0] in start_letters and word_is_possible(word, tiles_left)]
def pick_word(next_word, start_letters, tiles_left, dictionary):
if not word_is_possible(next_word, tiles_left):
raise ValueError("Using word that is impossible: %s" % (next_word,))
next_letters = set(start_letters)
next_letters.remove(next_word[0])
next_tiles = dict(tiles_left)
for c in next_word:
next_tiles[c] -= 1
next_dictionary = filter_dictionary(dictionary, next_tiles, next_letters)
return next_letters, next_tiles, next_dictionary
class FakeResult:
def __init__(self, value):
self.value = value
def get(self, timeout=None):
return self.value
class FakePool:
def apply_async(self, f, args):
res = f(*args)
return FakeResult(res)
def proc_next_word(next_word,
start_letters, tiles_left, filtered_sorted_dictionary,
depth, picks, prefix):
score = word_score(next_word)
next_letters, next_tiles, next_dictionary = pick_word(
next_word, start_letters, tiles_left, filtered_sorted_dictionary)
if len(prefix) / 2 < 5:
print "%sDepth %d: ?, %s for %d, %d possible words left" % (
prefix, len(prefix) / 2, next_word, score, len(filtered_sorted_dictionary))
next_words, next_score = search(FakePool(), next_letters, next_tiles, next_dictionary,
depth-1, picks, prefix + " ")
if len(prefix) / 2 < 5:
print "%sDepth %d: %d, %s for %d" % (
prefix, len(prefix) / 2, score + next_score, next_word, score)
return [next_word] + next_words, score + next_score
def wildify(word, tiles_left):
# replace missing letters with wilds
while True:
for c in word:
if tiles_left[c] < word.count(c):
word = word[0] + word[1:].replace(c, '?', word.count(c) - tiles_left[c])
break
else:
break
return word
def search(pool, start_letters, tiles_left, filtered_sorted_dictionary, depth, picks, prefix=""):
if not filtered_sorted_dictionary:
# no words left - penalize for tiles left
return [], final_score([], tiles_left)
if depth == 0:
raise ValueError("Hit depth 0")
if tiles_left['?'] > 0:
# proc top few and re-calculate score based on wildcarding
best_word_candidates = [wildify(w, tiles_left) for w in filtered_sorted_dictionary[:10000]]
best_word_candidates.sort(key=word_score, reverse=True)
else:
# no wildification needed
best_word_candidates = filtered_sorted_dictionary
best_words = best_word_candidates[:picks]
if depth == 1:
# only look at 1 word since depth 0 will do nothing
best_words = [best_words[0]]
results = [pool.apply_async(proc_next_word, (next_word,
start_letters, tiles_left, filtered_sorted_dictionary,
depth, picks, prefix))
for next_word in best_words]
results = [result.get() for result in results]
return max(results, key=lambda (words, result): result)
if __name__ == "__main__":
start_letters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
tiles_left = dict(start_tiles)
print "Preparing word list..."
dictionary = filter_dictionary(full_dictionary, tiles_left, start_letters)
dictionary.sort(key=word_score, reverse=True)
print "Starting search..."
pool = Pool(8)
words, _ = search(pool, start_letters, tiles_left, dictionary, 666, 5)
for word in words:
for c in word:
if tiles_left[c] <= 0:
raise ValueError("Invalid word list")
tiles_left[c] -= 1
print
print "\n".join(("%s for %s" % (word, word_score(word)) for word in words))
print final_score(words, tiles_left, True)
```
**Explanation:**
Depth-first search which searches the entire tree, picking between the top `picks` best words at each stage.
I sort the entire word list once by score at the beginning. After picking each word, for the next iteration I filter out all the words that are now no longer possible, preserving the order, so I don't have to sort the list at each step. To deal with wildcards, if there's a possibility that a wild card is needed, I pick the top 10000 candidates, replace missing letters with wildcards if needed, and re-sort based on the new (lower) scores.
This output is for `picks=5` and took `8m01s` to run on my 8-core machine.
[Answer]
# Java 8, score ~~2641~~ 2681
The program starts by taking the 40 best words. For each word, it finds the 40 best words to go along. Of the 1600 combinations, the program takes the best 40. For each combination, the 40 best words are found, and the cycle repeats.
When just a few tiles are left, the remaining letters are combined with the two blanks for the final word.
## Update
I increased the threshold to the 50 best words. Also, each combination only adds words that are less than those already present. This prevents multiple permutations of the same group.
```
OXYPHENBUTAZONE: 615
MICROEARTHQUAKE: 525
INTERSUBJECTIVE: 435
DAFFADOWNDILLY: 406
PREINTERVIEWING: 360
AUTOALLOGAMIES: 238
GOODSIRES: 99
?A?: 3 (ZAX)
---
Total: 2681
```
The program:
```
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Scrabble {
static final int[] scores = new int[]{1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10, 0};
static final int[] freqs = new int[]{9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1, 2};
static final int MAX = 50;
public static void main(String[] args) throws IOException {
List<String> words = Files.readAllLines(new File("C:/Users/Ypnypn/scrabble.txt").toPath());
words.sort((s, t) -> score(t) - score(s));
words.removeIf(w -> !works(w));
List<List<String>> last = words.stream().map(Arrays::asList).collect(Collectors.toList()),
finalList = new ArrayList();
for (int i = 0; i < 10; i++) {
List<List<String>> next = new ArrayList();
for (int j = 0; j < MAX && j < last.size(); j++) {
List<String> group = last.get(j);
Object[] thirds = words.stream().filter(word -> workTogether(group, word) && least(word, group)).toArray();
for (int k = 0; k < MAX && k < thirds.length; k++) {
List<String> newList = new ArrayList(group);
newList.add((String) thirds[k]);
next.add(newList);
}
}
last = next;
last.sort((s, t) -> t.stream().mapToInt(Scrabble::score).sum()
- s.stream().mapToInt(Scrabble::score).sum());
for (List<String> l : last) {
if (l.stream().mapToInt(String::length).sum() > 90) {
finalList.add(l);
}
}
}
finalList.forEach(g -> {
List<Integer> chars = new ArrayList();
int[] counts = new int[26];
g.forEach(str -> str.chars().forEach(c -> counts[c - 'A']++));
for (int i = 0; i < 26; i++) {
while (counts[i] < freqs[i]) {
chars.add('A' + i);
counts[i]++;
}
}
String end = words.stream()
.filter(w -> w.length() == chars.size() + 2)
.filter(w -> g.stream().noneMatch(s -> s.charAt(0) == w.charAt(0)))
.filter(w -> {
List<Integer> copy = new ArrayList(chars);
int _1 = 0, _2 = 0;
for (char c : w.toCharArray()) {
if (copy.contains((int) c)) {
copy.remove((Integer) (int) c);
} else if (_1 == 0) {
_1 = c;
} else if (_2 == 0) {
_2 = c;
} else {
return false;
}
}
return true;
}).findAny().orElse("");
if (end.equals("")) {
return;
}
char[] arr = end.toCharArray();
for (int i = 0; i < arr.length; i++) {
if (chars.contains((int) arr[i])) {
chars.remove((Integer) (int) arr[i]);
} else {
arr[i] = '?';
}
}
g.add(new String(arr));
});
finalList.removeIf(g -> g.stream().mapToInt(String::length).sum() < 100);
finalList.sort((s, t) -> t.stream().mapToInt(Scrabble::score).sum()
- s.stream().mapToInt(Scrabble::score).sum());
List<String> answer = finalList.get(0);
for (String str : answer) {
System.out.print(str + ": " + score(str));
if (str.contains("?")) {
String actual = words.stream().filter(s -> s.matches("^" + str.replace('?', '.') + "$")).findAny().get();
System.out.print(" (" + actual + ")");
}
System.out.println();
}
System.out.println("---");
System.out.println("Total: " + answer.stream().mapToInt(Scrabble::score).sum());
}
static boolean works(String str) {
int[] counts = new int[26];
for (char c : str.toCharArray()) {
counts[c - 'A']++;
}
for (int i = 0; i < 26; i++) {
if (counts[i] > freqs[i]) {
return false;
}
}
return true;
}
static boolean workTogether(List<String> strs, String str) {
if (strs.stream().anyMatch(s -> s.charAt(0) == str.charAt(0))) {
return false;
}
int[] counts = new int[26];
strs.stream().forEach(s -> s.chars().forEach(c -> counts[c - 'A']++));
str.chars().forEach(c -> counts[c - 'A']++);
for (int i = 0; i < 26; i++) {
if (counts[i] > freqs[i]) {
return false;
}
}
return true;
}
static boolean least(String str, List<String> strs) {
int score = score(str);
return strs.stream().allMatch(s -> score(s) >= score);
}
static int score(String word) {
int score = 0;
for (char c : word.toCharArray()) {
if (c != '?') {
score += scores[c - 'A'];
}
}
return score * word.length();
}
}
```
[Answer]
# Perl, score: 2655 ~~2630~~
```
#!perl -l
%p = qw{A 1 B 3 C 3 D 2 E 1 F 4 G 2 H 4 I 1 J 8 K 5 L 1 M 3 N 1 O 1 P 3 Q 10 R 1 S 1 T 1 U 1 V 4 W 4 X 8 Y 4 Z 10 x 0};
/[A-Z]+/,push @R,$& for <>;
@R = sort{length($b)<=>length($a)}@R;
for(@R) {push@W,$_;push@W,"$`x$'" while /./g;push@O,($_)x(1+length)}
$l = "AAAAAAAAABBCCDDDDEEEEEEEEEEEEFFGGGHHIIIIIIIIIJKLLLLMMNNNNNNOOOOOOOOPPQRRRRRRSSSSTTTTTTUUUUVVWWXYYZxx";
@S = map {$r='';for$x(A..Z,'x'){$r.="${x}{".(1*s/$x//g).",}"};"^$r\$"} map{"$_"}@W;
sub score{$r=0;$r+=$p{$_}for split'',$rr=pop;$r*length$rr}
@X = map{score$_}@W;
$f = 'x';
for(;;) {
$best = -1; $besti = 0;
for ($i=0;$i<@S;$i++) {
next if $X[$i] < $best;
if ($O[$i]!~/^[$f]/ && $l=~$S[$i]) {
$best = $X[$i];
$besti = $i;
}
}
if($best < 0){
$ls = score$l;
print "left: $l (-$ls)";
$tot -= $ls;
print "total: $tot";
exit;
}
$l=~s/$_// for $W[$besti]=~/./g;
$O[$besti]=~/./; $f .= $&;
print "$W[$besti]/$O[$besti] ($X[$besti])";
$tot += $X[$besti];
}
```
Use:
```
$ perl ./scrab.pl <~/sowpods.txt
OXYPHENBUTAZONE/OXYPHENBUTAZONE (615)
MICROEARTHQUAKE/MICROEARTHQUAKE (525)
NONOBJECTIVISMS/NONOBJECTIVISMS (465)
DAFFADOWNDILLY/DAFFADOWNDILLY (406)
PREINTERVIEWIxG/PREINTERVIEWING (345)
LITURGIOLOGxSTS/LITURGIOLOGISTS (240)
URDEE/URDEE (30)
EE/EE (4)
AA/AA (4)
left: AA (-4)
total: 2630
```
Use of blanks actually does not give that much while significantly slows down the execution:
```
$ perl ./scrab.pl <~/sowpods.txt
OXYPHENBUTAZONE/OXYPHENBUTAZONE (615)
MICROEARTHQUAKE/MICROEARTHQUAKE (525)
NONOBJECTIVISMS/NONOBJECTIVISMS (465)
DAFFADOWNDILLY/DAFFADOWNDILLY (406)
PREINTERVIEWED/PREINTERVIEWED (322)
LITURGIOLOGISTS/LITURGIOLOGISTS (255)
RUGAE/RUGAE (30)
EE/EE (4)
AA/AA (4)
left: Axx (-3)
total: 2623
```
After adding some heuristics:
```
$ time perl ./scrab.pl <~/sowpods.txt
OXYPHENBUTAZONE/OXYPHENBUTAZONE (615)
MICROEARTHQUAKE/MICROEARTHQUAKE (525)
NONOBJECTIVISMS/NONOBJECTIVISMS (465)
PREFIGURATIVELY/PREFIGURATIVELY (405)
DOWNREGULATIONS/DOWNREGULATIONS (300)
FORGEAxILITIES/FORGEABILITIES (238)
ADWAxDED/ADWARDED (104)
EA/EA (4)
left: L (-1)
total: 2655
real 3m58.517s
user 3m57.832s
sys 0m0.512s
```
[Answer]
# Python 3, score 2735
*(The optimal score of 2765, "6 words of 15 letters and one 10-letter word consisting of 8 letters of value 1 and two blanks" [has been achieved by nutki](https://codegolf.stackexchange.com/a/50374/7311).)*
I used a greedy approach similar to others':
I start with one-element lists containing the top scoring words containing Q's.
At every step for every list element I create `k = 800` new lists with the best legal words for the list. From the aggregated list of lists I keep the `k` top scoring lists and repeat the process 10 times.
Note that you can get the top `k` elements of an `n`-long list in O(n + k\*log n) which is O(n) if `k<<n` as in our case (`k = 800, n ~= 250000`) with a heap queue. I guess this method isn't used in other submission s hence the smaller `k` values.
I use wildcards along the way if needed for the words.
Runtime is a couple minutes for `k = 800`. Greater values and other optimizations haven't yielded better results yet.
Result:
```
DEMISEMIQUAVERS for 480
OXYPHENBUTAZONE for 615
ACKNOWLEDGEABLY for 465
FLASHFORWARDING for 435
INTERJACULATING for 375
COOPERATIVITIES for 330
METEOROID for 108
? is C for -45
? is M for -27
Left U for -1
Total score of 2735
```
I experimented with the Descartes product of the best words containing Q,J and X as these letter barely share words. My best score with this startegy was 2723 (`DEMISEMIQUAVERS OXYPHENBUTAZONE INTERSUBJECTIVE FLASHFORWARDING KNOWLEDGABILITY RADIOPROTECTION ANALOGUE EA`).
The unnecessary complicated spaghetti-code (with traces of experimentation with other methods):
```
import sys,heapq as hq
def score(s):
r=0
for c in s:
r+=ord('1332142418513113:11114484:0'[ord(c)-65])-48
return r*len(s)
def score_wl(rwl):
ac=a[:]
ssd=0
for rwle in rwl:
ac,sd=decr(ac,rwle)
ssd+=sd
return sum([score(rw) for rw in rwl])-ssd
def decr(av,nw):
nav=av[:]
scd=0
for c in nw:
if nav[ord(c)-65]>0:
nav[ord(c)-65]-=1
else:
nav[ord('[')-65]-=1
scd+=(ord('1332142418513113:11114484:'[ord(c)-65])-48)*len(nw)
return (nav,scd)
def bestwordlist(w,ac,sw,count):
stl=[swe[0] for swe in sw]
sl=[]
for we in w:
if we[0] not in stl:
acn,sd=decr(ac,we)
if min(acn)>=0:
sl+=[(we,score(we)-sd)]
mw=hq.nlargest(count,sl,key=lambda p:p[1])
res=[mwe[0] for mwe in mw]
return res
def bestword(w,ac,sw):
ms=0
mw=''
stl=[swe[0] for swe in sw]
for we in w:
if we[0] not in stl:
acn,sd=decr(ac,we)
if min(acn)>=0 and score(we)-sd>ms:
ms=score(we)-sd
mw=we
return mw
def search(t,lev,av,sw):
if lev>=len(t) and min(av)>=0:
return [sw]
if min(av)<0:
return []
r=[]
stl=[swe[0] for swe in sw]
if av[ord(tl[lev])-65]>0:
for i in range(1,maxch):
nw=t[lev][-i][0]
if nw[0] not in stl:
nav=decr(av,nw)[0]
swn=sw[:]+[nw]
r+=search(t,lev+1,nav,swn)
else:
r+=[sw]
if len(r)<10000:
return r
else:
return hq.nlargest(10000,r,key=score_wl)
args=sys.argv
maxch=300#int(args[1])
maxch2=800#int(args[2])
w=[]
with open('scr_words.txt','r') as f:
for l in f:
w+=[l[:-1]]
a=[ord(c)-48 for c in '9224<2329114268216464221212']
#ABCDEFGHIJKLMNOPQRSTUVWXYZ?
t=[]
tl='Q'
for c in tl:
tp=[]
wl=[(x,score_wl([x])) for x in w if c in x]
wl=sorted(wl,key=lambda p:p[1])
t+=[wl]
r=search(t,0,a,[])
rt=sorted(r,key=score_wl)[-maxch2:]
ms=0
res='-'
for i in range(10-len(tl)):
rtn=[]
for sw in rt:
ac=a[:]
for swe in sw:
ac,sd=decr(ac,swe)
bwl=bestwordlist(w,ac,sw,maxch2)
if not bwl:
rtn+=[sw]
for bwle in bwl:
rtn+=[sw+[bwle]]
rt=sorted(rtn,key=score_wl)[-maxch2:]
print(rt[-1],score_wl(rt[-1]),'- left')
sys.stdout.flush()
ms=-1000000
for sw in rt:
ssd=0
ac=a[:]
for swe in sw:
ac,sd=decr(ac,swe)
ssd+=sd
sc=sum([score(swe) for swe in sw])-ssd
left=''.join([chr(i+65)*v for i,v in enumerate(ac)])
sc-=score(left)
if sc>ms:
ms=sc
res=(sw,left)
fsw,left=res
print('\n\nres =',ms,' '.join(fsw),'left',left)
v
```
]
|
[Question]
[
I want to play Dungeons and Dragons, but I don't have any dice! Your challenge is to roll some D&D dice.
The input format specification in [Backus-Naur form](http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form) is:
```
<valid-input> ::= <opt-integer> "d" <integer> <opt-modifier>
<opt-integer> ::= | <integer>
<opt-modifier> ::= | "+" <integer>
<integer> ::= "0" | "1" | "2" | "3" | "4" | "5" |
"6" | "7" | "8" | "9" | <integer> <integer>
```
The optional integer before the `d` is the number of dice to roll; it must be at least `1`, and defaults to `1` if not supplied.
The required integer immediately after the `d` is the number of sides each die has; it must be at least `1`. The sides of each die are distinct consecutive positive integers starting at `1`.
The optional modifier may be `+0`, and it defaults to `+0` if not specified.
For example, for the input `2d10+5`, you generate two random numbers from 1 to 10 inclusive, add them together, and add 5. Then you will output the result.
If you receive invalid input, such as `2d`, `d20+`, `0d4`, `2d5+1+2`, `2+2`, or anything else that doesn't fit this format, you must output "`Invalid input`". Otherwise, you must output only a single random integer, weighted according to the input. For example, [`3d6` should produce more `10`s than `4`s](http://anydice.com/program/1/).
### Test cases
```
Input Minimum possible output Maximum possible output
d1 1 1
d6 1 6
d1+3 4 4
d20+3 4 23
2d1 2 2
2d6+2 4 14
d01 1 1
d01+0 1 1
01d01+01 2 2
3d20+10 13 70
d Invalid input
d0 Invalid input
d+0 Invalid input
d0+0 Invalid input
0d1 Invalid input
0d1+1 Invalid input
d1+ Invalid input
1d Invalid input
1d1+ Invalid input
1d+1 Invalid input
2d+2d Invalid input
d2+d2 Invalid input
d2+2+2 Invalid input
d2-1 Invalid input
-d2 Invalid input
-2d2 Invalid input
4*3 Invalid input
4*d2 Invalid input
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win!
[Answer]
# Perl, ~~109~~ ~~95~~ ~~93~~ ~~96~~ 89 bytes
```
s/^d/1d/;/^(\d+)d(\d+)(\+\d+)?$/;$d+=1+rand$2|0for
1..$1;$_=$1*$2?$d+$3:'Invalid input'
```
Requires the `-p` switch, which accounts for two of the bytes. Try it online on [Ideone](http://ideone.com/gLJfhO).
### How it works
* Because of the `-p` switch, a line is read from STDIN and stored in `$_`.
* The command `s/^d/1d/` prepends a *1* to `$_` if it begins with a *d*, i. e., if the number of dice has not been specified.
* The regular expression `/^(\d+)d(\d+)(\+\d+)?/` checks if the line consists of a number, a literal *d*, another number and, optionally, a third number preceded by a *+* sign.
If there is a match, the numbers will be saved in `$1`, `$2` and `$3`.
In this case, the input will be valid if and only if `$1` and `$2` are both positive.
* `$d += 1 + rand $2 | 0` adds a pseudo-randomly chosen integer from 1 to the specified number of sides to `$d` (initially treated as zero).
* `for 1 .. $1` does the above once for every integer between 1 and the number of dice.
* The command `$_ = $1 * $2 ? $d + $3 : 'Invalid input'` does the following:
+ If `$1 * $2` is zero, it sets `$_` to *Invalid input*.
+ Otherwise, the input is valid and it sets `$_` to the sum of the dice rolls and the modifier.
* Because of the `-p` switch, Perl prints the contents of `$_`.
* Since there a no further input lines, the script exits.
[Answer]
# Fortran: 145
```
character(1)a;read(*,*)s,a,j,a,k;n=0;if(k<0.or.a=="-")then;print*,"error k<0";stop;endif;do l=1,int(s);n=n+int(s*rand(0)+1);enddo;print*,n+k;end;
```
Abuses implicit typing (`i-n` are all integers, everything else a real). Minor caveat: input must be space separated, so `2d10+5` must be entered as `2 d 10 + 5`, otherwise you'll get an `input conversion error`.
[Answer]
## Ruby, 116
Alternative Ruby version. I was trying to find a way to do it without the regular expressions, but the validation you have to do is a lot harder without them.
```
gets=~/^(\d+)?d(\d+)(\+\d+)?$/
a=$1||?1
puts$~&&a>?0?eval("r=#{$3||0};#{a}.times{r+=rand(#$2)+1};r"):'Invalid input'
```
This one is 112, using Dennis' clever Perl algorithm:
```
$p='(\d*[1-9]\d*)'
puts~/^#$p?d#$p(\+\d+)?$/?eval("r=#{$3||0};#{$1||1}.times{r+=rand(#$2)+1};r"):'Invalid input'
```
[Answer]
## GolfScript (120 106 bytes)
```
.100?!1`*\+.43?)!'+0'*+.10,'d+':^*-!*.10,''*-^=*^1/{/n*}/~].,3=*3,or:x~;*{x~\{rand)+}+@*}'Invalid input'if
```
This is not only shorter than the first version, but also more elegant. The part which actually does the die rolling is
```
\{rand)+}+@*
```
The rest is mainly input validation, and a few characters for parsing.
```
# Start by converting valid inputs into valid inputs with all optional bits.
# Prepend a '1' if the string starts with 'd'.
.100?!1`*\+
# Append '+0' if there's no '+' in the string.
.43?)!'+0'*+
# Now we start knocking out the invalid inputs.
# If it contains a character other than [0-9d+], replace the string with ''.
.10,'d+':^*-!*
# If it doesn't contain exactly one 'd', exactly one '+', and the 'd' before the '+',
# replace the string with ''.
.10,''*-^=*
# Now we either have a valid string, an empty string, or a string which is almost valid
# but has some empty substrings which should be integers, or a forbidden 0 integer value.
# Replace the 'd' and '+' with newlines, eval the result, and gather into an array.
^1/{/n*}/~]
# If we had any empty parts, we'll have fewer than 3 items on the stack.
# In that case, replace with integer values which will fail the final validation step.
.,3=*3,or
# Final validation: number of dice * number of sides per die != 0.
:x~;*
# If we pass, do the actual die rolling. Otherwise give the error message.
{x~\{rand)+}+@*}'Invalid input'if
```
[Online demo with test framework](http://golfscript.apphb.com/?c=IyMKOydkMQpkNgpkMSszCmQyMCszCjJkMQoyZDYrMgpkMDEKZDAxKzAKMDFkMDErMDEKM2QyMCsxMApkCmQwCmQrMApkMCswCjBkMQowZDErMQpkMSsKMWQKMWQxKwoxZCsxCjJkKzJkCmQyK2QyCmQyKzIrMgpkMi0xCi1kMgotMmQyCjQqMwo0KmQyCiduL3sKLnAKIyMKCi4xMDA%2FITFgKlwrLjQzPykhJyswJyorLjEwLCdkKyc6XiotISouMTAsJycqLV49Kl4xL3svbip9L35dLiwzPSozLG9yOnh%2BOyp7eH5ce3JhbmQpK30rQCp9J0ludmFsaWQgaW5wdXQnaWYKCiMjCnByaW50IG4gcHJpbnR9LwojIwo%3D)
[Answer]
# Java, 378
Just wanted to try a solution with Java far from the best solution. But hey: Java isn't a golfing language in any case!
It gets the input from command line. First parameter `args[0]` is the input value.
```
class A{public static void main(String[]s){System.out.print(s[0].matches(
"(0+\\d+|[1-9]\\d*|)d(0+\\d+|[1-9]\\d*)(\\+\\d+)?")?z(s[0]):"Invalid input");}static int
z(String s){String[]a=s.split("d");String[]b=a[1].split("\\+");int c=a[0].isEmpty()?1:Byte.
decode(a[0]);int d=b.length<2?0:Byte.decode(b[1]);while(c-->0)d+=new java.util.Random().
nextInt(Byte.decode(b[0]))+1;return d;}}
```
Did you know, that `decode` is shorter than `valueOf`?
[Answer]
# J - 130 (45?) char
This challenge seems to be a little biased towards regular expressions, especially with having to differentiate invalid input. J has a POSIX regex library, so it's not that bad, but it's not integrated as it is with Perl, so J fares no better than other languages.
```
+/@,`(1+?@#~)/`('Invalid input'"_)@.(0 e.$)0 1 1>.".>|.}.((,'?d','(\+[0-9]+)?$',~}.)'^([0-9]*[1-9][0-9]*)')(rxmatch rxfrom])1!:1]1
```
If you're just implementing the logic for valid expressions, like the Python/PHP solutions appear to, it's the more reasonable 45 chars:
```
+/,(1+[:?@#/1>.".;._2@,&'d')`".;._1'+',1!:1]1
```
Notable bits:
* `1!:1]1` is the input, and `(rxmatch rxfrom])` is the logic that returns the subexpression matches.
* Whether or not the input was legal is handled by the regex matching, so we can set the defaults for n and p with `0 1 1>.`. It looks backwards (n is 1 by default and p is 0) because we had to reverse (`|.`) the list earlier, so that the logic at the end executes in the right order.
* `@.` is the *Agenda* conjunction, essentially a J-ish switch statement. If the matches are empty (if 0 is an e.lement of the $hape: `0 e.$`), we emit the error message, else we go through with rolling the dice: `#~` to set out the dice, `1+?` to roll, and `+/@,` to add the modifier p and sum.
[Answer]
## [TinyMUSH](http://www.tinymush.net/index.php/Main_Page), 239
```
@dig/t +
@op d=+
@lo d=d
@fail d=Invalid input
@cr .
@set .=com
&d .=$*:\ifelse(regmatch(%0,^(\\\\d+)?d(\\\\d+)(\\\\+\\\\d+)?$,0 1 2 3),ifzero(and(or(not(strlen(%q1)),%q1),%q2),Invalid input,add(die(usetrue(%q1,1),%q2),%q3)),Invalid input)
```
The first four lines deal with the fact that "d" is an alias for the universal "down" exit with a built-in failure message when it doesn't exist; exits are scanned before user-defined commands. The remaining lines create an object with a user-defined command making use of the built-in die() function.
[Answer]
# PHP, 129
```
<?eval(preg_filter(~Сף›ÔÖÀ›×£›Ö×£Ô£›ÔÖÀÛÐ,~ÛžÂÝÛÎÝÀÅÎÄ™×ÄÛ–ÔÔÃÛžÄیԞ‘›×ÎÓÛÍÖÖÄšœ—ÛŒÛÌÄ,$_GET[0])?:~šœ—ݶ‘‰ž“–›ß–‘Š‹ÝÄ);
```
Uses a regex to create a expression which PHP then evaluates.
Input is fed in via url: ?0=*argument*. Make sure you urlencode the + to %2b.
Here's what it looks like in a more readable form:
```
eval(preg_filter('/^(\\d)?d(\\d)(\\+\\d)?$/','$a="$1"?:1;for(;$i++<$a;$s+=rand(1,$2));echo$s$3;',$_GET[0])?:'echo"Invalid input";');
```
Bitwise inverting the strings using `~` not only saves a character because you don't need quotes (PHP assumes they are strings) but also saves characters because you don't have to escape the backslashes in the regular expression.
The `?:` operator is a special form of the ternary operator. `$foo = $a ? $a : $b` is the same as `$foo = $a ?: $b`.
[Answer]
# Ruby, ~~167~~ 147
```
/^(\d+)?d(\d+)(\+\d+)?$/.match gets
abort'Invalid input'if !$~||$1==?0||!$2||$2==?0
p eval(([0]*($1||1).to_i).map{rand($2.to_i)+1}*?+)+($3||0).to_i
```
Uses a regexp to do all the work. Since I'm using `\d+`, the only things I need to check for invalid input are that there was a match, that neither `n` nor `m` were `0`, and that there was an `m`. If any of those are found, it aborts with a message (`'Invalid input'`). Then it just prints the result, since it would have aborted by now if the input was invalid.
The result-printing isn't that interesting, but...
```
([0]*($1||1).to_i) # create an array of n elements (1 if there is no n)
.map{rand($2.to_i)+1} # fill it up with random numbers, where the number x is 1 < x < m+1
.inject(:+) # add them all up
+($3||0).to_i # and finally add the modifier (0 if there is none)
```
I later changed `.inject(:+)` to `eval(...*?+)`, but the idea is the same.
[Answer]
# Python 3, 184 bytes
```
import random,re
try:a,b,c=re.findall("^(\d*)d(\d+)(\+\d+)?$",input())[0];t=int(c or 0)+(sum(random.randint(1,int(b))for i in range(int(a or 1)))or q)
except:t="Invalid input"
print(t)
```
Passes all tests. If zero dice were allowed, it would be 6 bytes shorter by leaving out `(or q)`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `V`, 89 bytes
```
h\d=[1p|]⁽±Ḋ→a⟨←aL5=|←a⌊±T⟨0|2|4⟩=|←a1i\d=|←a3i\+=⟩A[←a0i⌊ʁ(←a2i⌊℅⅛)¾∑←a4i⌊+,|«¢q⁰∷Ṗ-←¥«,
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQViIsIiIsImhcXGQ9WzFwfF3igb3CseG4iuKGkmHin6jihpBhTDU9fOKGkGHijIrCsVTin6gwfDJ8NOKfqT184oaQYTFpXFxkPXzihpBhM2lcXCs94p+pQVvihpBhMGnijIrKgSjihpBhMmnijIrihIXihZspwr7iiJHihpBhNGnijIorLHzCq8KiceKBsOKIt+G5li3ihpDCpcKrLCIsIiIsIjJkNSsxMiJd)
Ties Perl
```
h\d=[1p|] # Checks if the first character is a d, and prepends a 1
⁽±Ḋ→a # Splits the string on non-numeric values, so consecutive digits stay grouped, then casts the list to variable "a"
⟨←aL5=| # is it Length 5 (3 numbers, the "+" and the "d")
←a⌊±T⟨0|2|4⟩=| # convert the numbers-as-strings to numbers and check if the numbers are in positions 1 3 and 5 (0 indexed)
←a1i\d=| # is the second item in the list "d"
←a3i\+=⟩ # is the fourth item "+"
A # are all of these checks true?
[←a0i⌊ʁ # If all the checks are true, create a range from 0-a[0]
(←a2i⌊℅⅛) # for i in said range, generate a random number 0-a[2] and push to global array
¾∑←a4i⌊+, # push global array, sum the values, and add a[4]
|«¢q⁰∷Ṗ-←¥«, # If any of the checks are false, print "invalid input"
```
```
[Answer]
# Zsh, 205 ~~223~~ bytes
```
set -e;e=Invalid\ input;trap '<<<$e' ERR
echo "^0d\n+$\nd+\n+d\n+.+\n[-|*]">p;[[ `grep -cfp<<<$1`>0 ]]&&<<<$e&&exit
q=(${(s: :)${1//(#s)d/1d}//[^0-9]/ });for i ({1..$q[1]})((s+=RANDOM%q[2]+1))
<<<$[s+q[3]]
```
[Try it Online](https://tio.run/##TY9fa8IwFMXf8yku2tnGUJukQ5i1wmB72MM28DVGdCbVgvSP7caY87O7JplzCdzz495zbshXszs3ui2rFvRnqwul1XZfviGUBThATUpRX292JfQ81jNGCHWi06fiY73P1QLyonpvk/awrsCfTqee9uFxPkcusqRqURBvUSjSqeFRByL8HsrerEqEgNX2oCsIN1llwmw1oyDlYGA3DQb6M29RnQbeMWgmMMHekUVR0G@wipg6RZFY0vBORnDCSVYeIIfgyEYjrxZMnnAQNCSd3788vD7f1IJLwjBGZrFoSC1iKc8YZaCYKWNLJDbCqVU2tl1uDVyNCTdDylwltFPKLDHoODY5Ru3HjcXaTLFORV3ALusqYWCOe/WXmPqDf72rkyvClctwojhcsLsXDpmj0I4dcscd@rfD2L@y4v75Bw) (with all test cases)
Writing the validation code was a chore. Without this guff, the solution would be a [svelte 89 bytes](https://tio.run/##JYuxCsIwFEX3fEVoIyQEm7wUCpZ2EFxVcA1x0KRWEGtNB7H022Mbl3sO97379W3wbuheA3afwT2ts7dHd0GooYwiX0uUumvb4YRAEvqakpH6EpeMjCAETT2zAuwkhD7L9cYIPDHUdG98x3SELCO9BjMxSj2vT9vD7rhf9VoZDoyhqqqI9rzXuTFhXmELSxTReL5AyUgoYqvig7IFV8tRwj@5nCkhGuDZ82UHMvwA):
```
q=(${(s: :)${1//(#s)d/1d}//[^0-9]/ });for i ({1..$q[1]})((s+=RANDOM%q[2]+1))
<<<$[s+q[3]]
```
[Answer]
# Python3, 204B
Mine beats the existing Python answer by adding in the required error handling and reading `d20` as `1d20` rather than `0d20` :)
```
import random,re
try:a,b,c=re.findall('^([1-9]\d*)?d(\d+)(\+\d+)?$',input())[0];I=int;R=sum(random.randrange(I(b))+1for x in[0]*(1if a==''else I(a)))+(0if c==''else I(c))
except:R='Invalid input'
print(R)
```
edited to fix 2 typos: `I(x) => I(c)`, `Invalid Input => Invalid input`
edited to fix regex: `\+?(\d*) => (\+\d+)?`
[Answer]
# [Go](https://go.dev), unseeded, 366 bytes
```
import(."regexp";."strconv";."math/rand")
func f(s string)int{k:=MustCompile(`^(\d*)d(\d+)(\+\d+)?$`).FindAllStringSubmatch(s,-1)
if len(k)<1||k[0][2]==""{return-1}
r:=k[0]
var n,l,f,m,t int
l=len(r)
n,_=Atoi(r[1])
if n<1&&r[1]==""{n=1}else if n<1{return-1}
if l>2{f,_=Atoi(r[2])}
if f<1{return-1}
if l>3{m,_=Atoi(r[3])}
for i:=0;i<n;i++{t+=Intn(f)+1}
t+=m
return t}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVLdatswFGa3egohRidVdmbJo4wk3iiDwS42CmFXqdd6kZyK2HKQ5bTg5kl2Ewp7qO1ppp_-jK0339H50Xc-naMfd-vu8OvVtlptqrWEbaU0UO22M3aC6taiR8eqVqKfg63Tt79f6BjFE2TkWt5s0WyCemtWnd75Y1vZq9em0gIRUA96BWvcQ5dXek2UtuNmWnweevuha7eqkfjyGz4Xx0Q4pASfU2_ev7wkk49Ki9OmWYSbi-G7411d4T5JGQGqho3UeEPm7PZ2s8zKJS-LAqHRSDsYnbI9MNPCJ8CuMlAnTVInbWKhEwCawt81BOjkoji1ncJmycpAqufs6Mh7gUwXbC-bXsKY-Yvc93_Hx_qJgJckhOv_6_KxfarLfV3dGaimRTZTcz1TlI6WFp-01bgm1N1yXgsiCbT7h7G3YZh-R5jAESykFPhLd43J5KtWN5gQ4Ibcw2kBl2Uc94gEQwkSJx4Yzb3hWbA8ZLg4odxHMxaRZs5mLJx8KPf1LENR8kUS6N1u3WcJzUZw5hrZRru9-D07EfvHkJuo3lWNEv9oCq08hG4ii02DIIeURbUOmQhwf6ZRMeWBgFPBo-XxCTz1-TREUx7Mm-M8oHOeecCDuGffcD_1wyHaPw)
# [Go](https://go.dev), seeded, 393 bytes
```
import(."regexp";."strconv";."math/rand";."time")
func f(s string)int{k:=MustCompile(`^(\d*)d(\d+)(\+\d+)?$`).FindAllStringSubmatch(s,-1)
if len(k)<1||k[0][2]==""{return-1}
r:=k[0]
var n,l,f,m,t int
l=len(r)
n,_=Atoi(r[1])
if n<1&&r[1]==""{n=1}else if n<1{return-1}
if l>2{f,_=Atoi(r[2])}
if f<1{return-1}
if l>3{m,_=Atoi(r[3])}
Seed(Now().Unix())
for i:=0;i<n;i++{t+=Intn(f)+1}
t+=m
return t}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVJbbtQwFBW_WYVlocqukxA7qEIzE1CFhMQHCGnED9PQhrEztSZxRo4zrZRmAayhP6NKLIKtsBr8aCmC_pzj-8i5r9zebbrDz1213lYbAdpKqki2u06bFNatgT8GUyevfj37HpwohVpsxPUOzlPYG73u1N4928pcvtCV4s4wshUQR_Wg1qBGPbB5Um2wVGbczooPQ2_edu1ONgJdfEVn_BhziwSjM-LozfMLnL6Tip82zdJ_uRy-Wf31JerjhOJI1qARCm3xgt7cbFdZuWJlUUA4amEGrRI6RXpWuEC0rzRQcRPXcRsbYBuImsJ9q3Gk4vPi1HQS6RUtvaha0KMjZ3kxVdBJNL0AIfKXuKv_mo31owArsXfX_-flY_uYl7u8pRAcfeyuEE4_K3mNsN1Up4GcFdlcLtRcEjIaUrxXRqEaEytkrTYKusBMDxf54vfrDoYwGCO75B7MCrAqw7pHyCmMIT9xQEnuiGWemY8wfkKY82Y0IMksZ9S_nCt3-TSDk-_vPPby9sb2N_HFxuiTLWQaZe_i7mwHmf647EbVvmok_6cnX8qBr8azUNQ3ZJHQ0K1Fyj3cv0nomDAvwAhngVkYgSUunnhvwjy9PM49WuOJAR6ae3KG-xUfDoF_Aw)
]
|
[Question]
[
# Task
Given a set of `n` unique elements and a multiset `l` of positive numbers that add up to `n`, find all the ways of partitioning those unique elements into disjoint sets with sizes given by the elements of `l`.
(A multiset is a set that allows repeated elements)
The point here is that we are taking everything in the output as sets, so order doesn't matter in any place.
This may be simpler to understand if you check some test cases below.
# Input
The multiset `l` of positive integers that add up to `n`. Note that the elements in `l` may appear repeatedly. This might be given as
* a list `l = [1, 1, 2, 2, 3]`
* arguments to a function `f(1, 1, 2, 2, 3)`
* or any other sensible way of representing a multiset
You may assume the representation of `l` is ordered.
You may also take a list/set/collection of `n` distinct integers, or you may generate it depending on the sum of the elements in `l`. If you generate it, you may use *any* `n` distinct integers for the set to be partitioned but your remaining code should work for any set of `n` integers. The set you use must be specified in your answer. Suggestions include:
* a range starting in `0`: `[0, 1, ..., n-1]`
* a range starting in `1`: `[1, 2, ..., n]`
# Output
The different ways in which your collection can be split in sets with the given sizes. Your output should be unambiguous.
# Reference implementation
You can find a [vanilla python reference implementation here](https://gist.github.com/RojerGS/a2c41c4d4bd3a1fe3c5af52910a73e61) or [you can try it online](https://tio.run/##pVbbbuM2EH3XVwych0obxV0nfSgMZH9hgaJAH7yCI1vjmI1EaklqXbfYb09nOKQkO3lYtEFgXTgzPHM5h@rP/mj0w@trgwfYH41xmDv0JehinQEsFovf6xd0UEOrnAdzgEGrrwMCttih9rSiG7DoB6vpvm3BHxF645zatUgRTvXZsVuIrfQz6Mn1YE0HijarHZyQfOlK7uRlsauVbtCyK0ckTHStPcVzoI3neA71kgBmZK8OFPfxET6CsXT3CVrUnEdIAiI@2FRse0OP@8E69Q1hVzuEPf2UvItFUARWt2f6QYYO3kBjCCP5YZt2WcWo8Mgh@fYGerV/CUhjdiXgN7RUXc4ZW9rm2VAdBz04bILPgaCqMtiDoqrooUNbe5zhpj2Wdd@jbvJ8w4ZVyZXYrFV1y1d1u1pXRTHP0WYBqkOJcMS6IZhs/FGg7kxzjm/IOYvwUXH@QOBCEuxWci0bo3/yy2gk8xEMpEGhn0O3kz5d9pWteK/ge6Lw24glThmv0ZjdrYp5NXJaVXtqR4sHX1zWZQwyVmd8s1EVRc43fF/dXsSI2E@GDP4g@8@DF0jmfUA/DsdcgTFzKMkxQpqgxD5NFblNnmE5y5iJrm@VFyLuj4N@2Tr1N/5XRpKJ8o58@9p65ZXRgZH4daDVM3DoRrZxJZwCDbh5xk78I@fdsH/BGH1aVtqpRuzFQCYGutp7tMxOSonrP41JDERviUwUwOeJrD/PchW/a8ZFHm/IuqqyRMrJ7T1bIU7oaOKauEdkJ4au2gaw3h9TFspzk0ki2nMwYu86LhIHPVUSdmc4qL@YA6wWUuWxC8GLyqLhSebraVTHiTvk50SSnDeWmtrXyobm5KnczsChtuXUXZ4kliWiKhcpiFC@EWEoOCmNp22UpiwOMudsa/2MuY7jyq9ZiUj3zJZZzxZpkm/oSfl5U3law/OB8PmoYglT9OJ9w2vaWoKS5FRjyHfFQw4KRcOu0EVTYY6biBmDkVrN2ZCEg2NL/1J9pwFLmc5ZzJnGLVK@QK6WCHhO@MPlFjYppago1WgfajxK89w7SkUxnhDBdLNei/OsOYHtjL5Rbl9bKmfXe6Ij7g1RrMNRVnkseTCyaahHJof0xqcStqGR1PkgIxPhRUv42SUZ@U1ipaqFg5rmKkjPeOa@lZeAmzZJAxpGo7d4RxsqTXXj5rilHCyfZxpyoSCiHuzLmjojXkOn5CQgS4EqHHm2ZuhlgAaRMFd3eCf6NTU9JLl0xvq8EG7VdNL/ALNkqgOp0A2td@9Ta1oLBDsdVYuy6Tqbj2PaJ2RP3xWMUyzYOMqVOKaz@SbURtyDT1frczzIzWnLT8lluTcDSecYqhgjuzFq8knH/Lukl3Qm6l9/yDj57no2LNVmFMFQfk7hJXrSKtoOG0Vn4zV3yxH@hyvA7/NzHmsiqVQnzSeLyQgxQHvLfRBrroicqGmjNygERzDa2nBEBMdp83QICBvj922qRU2Pz1o@@4a@4QpclCMWeRZsJpZRbOLeVzbRM0nNbBUgT0HmXzrylz410qjOQl1K0XyY/48ghSSm@drORqt69ej8lr@yw0bktVlVH34t@eahCpf7Elbj3b3crehu/no1rtyHlQuzh/GB/n@pMpr4P43S2x0TZvFFc26LrLf8ubF4enpaFBmjZWQMdUK4jmfqTDr5OyuX49MNXc62RVGUwYkLLVEPi3/4xXe4@wSbuCG1lV5HIEu@5l3d586T7Nii@P5FV4spQpFdAHz9Fw).
# Test cases
I am using the set `0, ..., n-1` when the list adds up to `n`. In the TIO link, that list is given explicitly to my function.
After the `->`, each line represents one possible way of splitting the set.
```
[1, 1, 1, 1, 1, 1, 1, 1] -> [
[[0], [1], [2], [3], [4], [5], [6], [7]]
]
[3] -> [
[[0, 1, 2]]
]
[1, 2] -> [
[[0], [1, 2]]
[[1], [0, 2]]
[[2], [0, 1]]
]
[2, 2] -> [
[[0, 1], [2, 3]]
[[0, 2], [1, 3]]
[[0, 3], [1, 2]]
]
[1, 1, 2] -> [
[[0], [1], [2, 3]]
[[0], [2], [1, 3]]
[[0], [3], [1, 2]]
[[1], [2], [0, 3]]
[[1], [3], [0, 2]]
[[2], [3], [0, 1]]
]
[1, 2, 2] -> [
[[0], [1, 2], [3, 4]]
[[0], [1, 3], [2, 4]]
[[0], [1, 4], [2, 3]]
[[1], [0, 2], [3, 4]]
[[1], [0, 3], [2, 4]]
[[1], [0, 4], [2, 3]]
[[2], [0, 1], [3, 4]]
[[2], [0, 3], [1, 4]]
[[2], [0, 4], [1, 3]]
[[3], [0, 1], [2, 4]]
[[3], [0, 2], [1, 4]]
[[3], [0, 4], [1, 2]]
[[4], [0, 1], [2, 3]]
[[4], [0, 2], [1, 3]]
[[4], [0, 3], [1, 2]]
]
[2, 2, 2] -> [
[[0, 1], [2, 3], [4, 5]]
[[0, 1], [2, 4], [3, 5]]
[[0, 1], [2, 5], [3, 4]]
[[0, 2], [1, 3], [4, 5]]
[[0, 2], [1, 4], [3, 5]]
[[0, 2], [1, 5], [3, 4]]
[[0, 3], [1, 2], [4, 5]]
[[0, 3], [1, 4], [2, 5]]
[[0, 3], [1, 5], [2, 4]]
[[0, 4], [1, 2], [3, 5]]
[[0, 4], [1, 3], [2, 5]]
[[0, 4], [1, 5], [2, 3]]
[[0, 5], [1, 2], [3, 4]]
[[0, 5], [1, 3], [2, 4]]
[[0, 5], [1, 4], [2, 3]]
]
[1, 2, 3] -> [
[[0], [1, 2], [3, 4, 5]]
[[0], [1, 3], [2, 4, 5]]
[[0], [1, 4], [2, 3, 5]]
[[0], [1, 5], [2, 3, 4]]
[[0], [2, 3], [1, 4, 5]]
[[0], [2, 4], [1, 3, 5]]
[[0], [2, 5], [1, 3, 4]]
[[0], [3, 4], [1, 2, 5]]
[[0], [3, 5], [1, 2, 4]]
[[0], [4, 5], [1, 2, 3]]
[[1], [0, 2], [3, 4, 5]]
[[1], [0, 3], [2, 4, 5]]
[[1], [0, 4], [2, 3, 5]]
[[1], [0, 5], [2, 3, 4]]
[[1], [2, 3], [0, 4, 5]]
[[1], [2, 4], [0, 3, 5]]
[[1], [2, 5], [0, 3, 4]]
[[1], [3, 4], [0, 2, 5]]
[[1], [3, 5], [0, 2, 4]]
[[1], [4, 5], [0, 2, 3]]
[[2], [0, 1], [3, 4, 5]]
[[2], [0, 3], [1, 4, 5]]
[[2], [0, 4], [1, 3, 5]]
[[2], [0, 5], [1, 3, 4]]
[[2], [1, 3], [0, 4, 5]]
[[2], [1, 4], [0, 3, 5]]
[[2], [1, 5], [0, 3, 4]]
[[2], [3, 4], [0, 1, 5]]
[[2], [3, 5], [0, 1, 4]]
[[2], [4, 5], [0, 1, 3]]
[[3], [0, 1], [2, 4, 5]]
[[3], [0, 2], [1, 4, 5]]
[[3], [0, 4], [1, 2, 5]]
[[3], [0, 5], [1, 2, 4]]
[[3], [1, 2], [0, 4, 5]]
[[3], [1, 4], [0, 2, 5]]
[[3], [1, 5], [0, 2, 4]]
[[3], [2, 4], [0, 1, 5]]
[[3], [2, 5], [0, 1, 4]]
[[3], [4, 5], [0, 1, 2]]
[[4], [0, 1], [2, 3, 5]]
[[4], [0, 2], [1, 3, 5]]
[[4], [0, 3], [1, 2, 5]]
[[4], [0, 5], [1, 2, 3]]
[[4], [1, 2], [0, 3, 5]]
[[4], [1, 3], [0, 2, 5]]
[[4], [1, 5], [0, 2, 3]]
[[4], [2, 3], [0, 1, 5]]
[[4], [2, 5], [0, 1, 3]]
[[4], [3, 5], [0, 1, 2]]
[[5], [0, 1], [2, 3, 4]]
[[5], [0, 2], [1, 3, 4]]
[[5], [0, 3], [1, 2, 4]]
[[5], [0, 4], [1, 2, 3]]
[[5], [1, 2], [0, 3, 4]]
[[5], [1, 3], [0, 2, 4]]
[[5], [1, 4], [0, 2, 3]]
[[5], [2, 3], [0, 1, 4]]
[[5], [2, 4], [0, 1, 3]]
[[5], [3, 4], [0, 1, 2]]
]
[1, 1, 4] -> [
[[0], [1], [2, 3, 4, 5]]
[[0], [2], [1, 3, 4, 5]]
[[0], [3], [1, 2, 4, 5]]
[[0], [4], [1, 2, 3, 5]]
[[0], [5], [1, 2, 3, 4]]
[[1], [2], [0, 3, 4, 5]]
[[1], [3], [0, 2, 4, 5]]
[[1], [4], [0, 2, 3, 5]]
[[1], [5], [0, 2, 3, 4]]
[[2], [3], [0, 1, 4, 5]]
[[2], [4], [0, 1, 3, 5]]
[[2], [5], [0, 1, 3, 4]]
[[3], [4], [0, 1, 2, 5]]
[[3], [5], [0, 1, 2, 4]]
[[4], [5], [0, 1, 2, 3]]
]
```
---
This is the fifth and **final** challenge of the [RGS Golfing Showdown](https://codegolf.meta.stackexchange.com/q/18545/75323). If you want to participate in the competition, you have 96 hours to submit your eligible answers. Remember there is still 300 reputation in prizes! (See 6 of [the rules](https://codegolf.meta.stackexchange.com/q/18545/75323))
Also, as per section 4 of the rules in the [linked meta post](https://codegolf.meta.stackexchange.com/q/18545/75323), the "restricted languages" for this third challenge are *only* [Sledgehammer](https://codegolf.stackexchange.com/a/200706/75323), [J](https://codegolf.stackexchange.com/a/200834/75323) and [Mathematica](https://codegolf.stackexchange.com/a/200687/75323) so submissions in these languages are not eligible for the final prize. But *they can still be posted!!*
## Final prize
If you want to be considered for the final prize, at the end of your answer to this challenge please add a link to the eligible submissions you want to be considered for your final score, as well as the scores those answers got! This way it will be slightly easier for me to keep track of everything. Thanks!
This is still a regular [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so enjoy!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
œεI£€{{}ê
```
[Try it online!](https://tio.run/##yy9OTMpM/e/vY/P/6ORzWz0PLX7UtKa6uvbwqv//ow11jHSMYgE "05AB1E – Try It Online")
```
œ # permutations of the [0, ..., n-1] input
ε } # for each permutation:
I£ # cut it in parts of lengths given by the second input
€{ # sort each part
{ # sort the list of parts
ê # sort and uniquify the list of lists of parts
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~123~~ ~~118~~ ~~114~~ 112 bytes
Input: set `s` representing a list of `n` unique elements, and an iterable `l` representing the multiset.
Output: a set of all partitions, where each partition is a tuple of tuples of elements (aka output is a set of tuples of tuples).
```
lambda s,l:{(*sorted(p),)for p in product(*(combinations(s,i)for i in l))if{*sum(p,p)}>s}
from itertools import*
```
[Try it online!](https://tio.run/##XVFbTgMxDPzPKazlJ6kCEu0fUjkCFyhVtWWdNiIvEge1qjh7cXa7gJA2sp0Zj@PZdKZjDKurWb9eXe/3Qw9Fu6eLXJSYCQeZlFYmZkhgA6Qch/pGciHfot/b0JONocii7cixjeOUsuayKNXLpJP6ei5fwuTowRJmitEVsD6x@OI6RSjnIu6gFhygqfDxPZENB8hYqiMxoAGKO2cL8ax3PK9fYkD1JJhANfPMEZkePBH4KCVY1thceESbsz@Dw3CgowY6Ymj1Z@8qjvqNseMuefqjK5nPF/rEUu1pzgZsO/KLHwoNNjD1jl3B5k6qVAQ4WAOyrGxcxajnDWxBEhAYarY4JaC0HEnmPhxQBtWYXEM0UIP9qAjo0GNokm3GgbGbG5C51/CerNOgya8fNGUbSDoN3f0zbDqelQ03zP7N0fdpznm90bPZAjX@hlNbNHP7b2F43Zt@BwCdBjZmvth26rp51PD/24rNig@nSw7LKUzYLVv@Qn/vVttv "Python 3 – Try It Online")
## Approach
**Step 1**: For each element `i` of the multiset `l`, we find all combinations of `i` elements of `s`. We then find the Cartesian products of them. This is the list of candidate partitions.
For example: for `l = [1,2], s = ABC`, we first find all combinations
* of 1 element: `A, B, C`
* of 2 elements: `AB, AC, BC`
The candidate partitions are the Cartesian product of the above list of combinations:
```
[A,AB]
[A,AC]
[A,BC]
[B,AB]
[B,AC]
[B,BC]
[C,AB]
[C,AC]
[C,BC]
```
**Step 2**: Filter out the invalid partitions (partitions that do not add up to `s`).
For the above example, only the following partitions are kept:
```
[A,BC]
[B,AC]
[C,AB]
```
## Code breakdown
```
lambda s,l:
{
(*sorted(p),) # convert partition to a sorted tuple (of tuples)
for p in product( # for each candidate partition
*(combinations(s,i)for i in l)
)
if{*sum(p,p)}>s # keep only if partition add up to s
} # put everything in a set to filter out duplicates
```
Each partition is stored as a sorted tuple of sorted tuple. This ensure no duplicate in the final result.
`{*sum(p,p)}>s` checks if a candidate partition is valid (aka contains all element in `s`). This work by putting all elements in the partition and some extra elements into a set, then check if the set is a superset of `s`.
For example: for `s={0,1,2,3}` and valid partition `p=((0,1),(2,3))`:
`sum(p,p)` evaluates to `((0,1),(2,3),0,1,2,3)`, which when converted into set is a superset of `s`.
For `s={0,1,2,3}` and invalid partition `p=((0,1),(1,2))`:
`sum(p,p)` evaluates to `((0,1),(1,2),0,1,2)`, which when converted into set becomes `{0,1,2,(0,1),(1,2)}`, not a superset of `s`.
[Answer]
# JavaScript (ES6), ~~158 156~~ 141 bytes
Takes input as `(a)(r)`, where \$a\$ is the representation of the input set \$l\$ as an ordered array, and \$r\$ is the range \$[1,2,...,n]\$.
Prints the results.
```
a=>r=>(F=(k,m,o=[],p,s=[],n=a[k])=>n?s[n-1]?F(++k,m,[...o,s],a[k]-n?0:s[0]):r.map(i=>i<p|m>>i&1||F(k,m|1<<i,o,i,[...s,i])):console.log(o))(0)
```
[Try it online!](https://tio.run/##bVBda4UgGL7vV3g1lN6kOruqNHax/oTIkE5t7pw0dBuMtd/etGBrYyC8z/t8oT6rN@V7p@eXzNjzsI5sVYw7xnHH8AUmsExImMHHYZgSF0kYN60XJitk2@E0jS5BKbXgJURDZtq88iKXpHJ0UjPWjOtmXibO9U2xLF0sXoqm0WBBb1kPWhJS9dZ4ex3o1T5iSwjOyVqLBCFRAPrnSIjaaR@BKHdUfqPd97OUvzx/lNMxcysTmdDRunvVP2GFGEcfQT1eUJE6MA4xFF9w55x6x4q64fzaDxjPgHoSYzNKAyJy@wn8AEhvtA50sTWMoQm7DR7rA/FJ6vUL "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = ordered representation of the input set
r => ( // r[] = range [1, 2, ..., n]
F = ( // F is a recursive function taking:
k, // k = index of the current entry in a[]
m, // m = bitmask of values already assigned in the output
o = [], // o[] = output
p, // p = either 0 or a previous value (as a lower bound)
s = [], // s[] = array representing the current set
n = a[k] // n = k-th entry in a[]
) => //
n ? // if n is defined:
s[n - 1] ? // if the current set is not full:
F( // do a recursive call:
++k, // increment k
m, // pass m unchanged
[...o, s], // append s[] to o[]
a[k] - n ? 0 // set p to 0 if the next set has a different size
: s[0] // or to s[0] if it has the same size
) // end of recursive call
: // else:
r.map(i => // for each value i in the range r[]:
i < p | // abort if i is less than p
m >> i & 1 || // or the i-th bit is already set in m
F( // otherwise, do a recursive call:
k, // pass k unchanged
m | 1 << i, // set the i-th bit in m
o, // pass o unchanged
i, // set p to i
[...s, i] // append i to s[]
) // end of recursive call
) // end of map()
: // else:
console.log(o) // leaf node: print o[]
)(0) // initial call to F with k = 0
```
---
### Previous answers
* [RGS 1/5](https://codegolf.stackexchange.com/a/200002/58563) - JavaScript, 37 bytes
* [RGS 2/5](https://codegolf.stackexchange.com/a/200270/58563) -
CP-1610 machine code, 28 bytes (or 27.5)
* [RGS 3/5](https://codegolf.stackexchange.com/a/200501/58563) - JavaScript, 79 bytes
* [RGS 4/5](https://codegolf.stackexchange.com/a/200688/58563) - JavaScript, 206 bytes
Total score: **491 bytes**
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 63 bytes
Uses the range [1,2,...,n]
```
Union[Sort/@(Sort/@#~TakeList~a&/@Permutations@Range@Tr[a=#])]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277PzQvMz8vOji/qETfQQNCKdeFJGan@mQWl9Qlquk7BKQW5ZaWADXk5xU7BCXmpac6hBRFJ9oqx2rGqv0PKMrMK1HQd0iPrjbUMdQxqY39/x8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage/wiki), ~~16~~ ~~15~~ 13 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
Œ!ṁ€R}Ṣ€Ṣ¥€ṢQ
```
-2 bytes thanks to *@NickKennedy* by golfing the loose link to an inline one with `}`.
[Try it online.](https://tio.run/##y0rNyan8///oJMWHOxsfNa0Jqn24cxGQBpKHlkLowP///0cb6BjqGOkYx/6PNtJRMIoFAA)
**Explanation:**
```
Œ!ṁ€R}Ṣ€Ṣ¥€ṢQ # Main link taking two list arguments
# i.e. left=[0,1,2,3,4]; right=[1,2,2]
Œ! # Get all permutations of the (implicit) left argument
# i.e. [0,1,2,3,4] → [[0,1,2,3,4],[0,1,2,4,3],...,[4,3,2,1,0]]
} # Turn a monad into a dyad by using the right argument:
R # Create a range of each inner integers
# i.e. [1,2,2] → [1,[1,2],[1,2]]
ṁ€ # And mold each permutation based on that
# i.e. [3,0,2,4,1] and [1,[1,2],[1,2]] → [3,[0,2],[4,1]]
€ # Map,
¥ # using the previous two links as dyad:
Ṣ€ # Sort each inner-most list
# → [[0,[1,2],[3,4]],[0,[1,2],[3,4]],...,[4,[2,3],[0,1]]]
Ṣ # Then sort each inner list
# → [[0,[1,2],[3,4]],[0,[1,2],[3,4]],...,[[0,1],[2,3],4]]
Ṣ # And after the map, sort the outer list
# → [[0,[1,2],[3,4]],[0,[1,2],[3,4]],...,[[0,4],[1,3],2]]
Q # And uniquify it
# → [[0,[1,2],[3,4]],[0,[1,3],[2,4]],...,[[0,4],[1,3],2]]
# (after which the result is output implicitly)
```
---
**Original ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) answer:**
```
⁹R⁸ṁ
Œ!çṢ€Ṣɗ€ṢQ
```
First (semi-complex) Jelly answer, so can definitely be golfed.. I probably can't find the builtins I'm looking for, since I have the feeling there should be a builtin for `⁹R⁸ṁ` similar as 05AB1E's `£`.
Port of the approach used by *@Grimmy* in [his 05AB1E answer](https://codegolf.stackexchange.com/a/200879/52210).
[Try it online.](https://tio.run/##y0rNyan8//9R486gR407Hu5s5Do6SfHw8oc7Fz1qWgMkT06H0IH///@PNtAx1DHSMdYxif0fDWIZxQIA)
**Explanation:**
```
⁹R⁸ṁ # Define a link taking two list arguments
# i.e. left=[1,2,2]; right=[3,0,2,4,1]
⁹ # Use the left argument
R # And create a range of each inner integers
# i.e. [1,2,2] → [1,[1,2],[1,2]]
⁸ # Then take the right argument
ṁ # And mold it based on the earlier list
# i.e. [3,0,2,4,1] and [1,[1,2],[1,2]] → [3,[0,2],[4,1]]
Œ!çṢ€Ṣɗ€ṢQ # Main link taking two list arguments
# i.e. left=[0,1,2,3,4]; right=[1,2,2]
Œ! # Get all permutations of the (implicit) left argument
# i.e. [0,1,2,3,4] → [[0,1,2,3,4],[0,1,2,4,3],...,[4,3,2,1,0]]
€ # Map,
ɗ # using the previous three links as dyad:
ç # Apply the link we defined above,
# which uses this main-link's right as left argument for the helper-link
# → [[0,[1,2],[3,4]],[0,[1,2],[4,3]],...,[4,[3,2],[1,0]]]
Ṣ€ # Sort each inner-most list
# → [[0,[1,2],[3,4]],[0,[1,2],[3,4]],...,[4,[2,3],[0,1]]]
Ṣ # Then sort each inner list
# → [[0,[1,2],[3,4]],[0,[1,2],[3,4]],...,[[0,1],[2,3],4]]
Ṣ # And after the map, sort the outer list
# → [[0,[1,2],[3,4]],[0,[1,2],[3,4]],...,[[0,4],[1,3],2]]
Q # And uniquify it
# → [[0,[1,2],[3,4]],[0,[1,3],[2,4]],...,[[0,4],[1,3],2]]
# (after which the result is output implicitly)
```
---
And not that it matters, but my other *RGS Golfing Showdown* answers are:
* 1/5: [MathGolf](https://codegolf.stackexchange.com/a/200033/52210) or [Stax](https://codegolf.stackexchange.com/a/200037/52210), both 9 bytes (or [Java 10](https://codegolf.stackexchange.com/a/200022/52210), 58 bytes)
* 2/5: [Java 8](https://codegolf.stackexchange.com/a/200260/52210), 76 bytes (or [Whitespace](https://codegolf.stackexchange.com/a/200275/52210), 149 bytes)
* 3/5: [Java 8](https://codegolf.stackexchange.com/a/200492/52210), 107 bytes
* 4/5: [Java 8](https://codegolf.stackexchange.com/a/200786/52210), 261 bytes
Total score: **466 bytes**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
œcŒpFQƑ$ƇṢ€Q
```
[Try it online!](https://tio.run/##y0rNyan8///o5OSjkwrcAo9NVDnW/nDnokdNawL///9vqGOkY6xjomMKZhkBAA "Jelly – Try It Online")
A dyadic link taking the list of \$n\$ integers as the left argument and the list of set lengths as the right. Returns a list of lists.
Thanks to @KevinCruijssen for pointing out an omission in my original answer.
## Previous RGS submissions:
1. [Jelly 12 bytes](https://codegolf.stackexchange.com/a/200050/42248)
2. [BBC BASIC V 92 bytes](https://codegolf.stackexchange.com/a/200337/42248)
3. [Jelly 37 bytes](https://codegolf.stackexchange.com/a/200539/42248)
4. [R 128 bytes](https://codegolf.stackexchange.com/a/200700/42248)
5. Jelly 12 bytes (this post)
**Total: 281 bytes**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œcŒpṢ€FQƑ$ƇQ
```
**[Try it online!](https://tio.run/##y0rNyan8///o5OSjkwoe7lz0qGmNW@CxiSrH2gP///8fbaBjqGOkY6xjomMa@z/aUEcBiExiAQ "Jelly – Try It Online")**
---
**Overal RGS admissible competition entries:**
[RGS 1/5 - Jelly, 7](https://codegolf.stackexchange.com/a/200043/53748)
[RGS 2/5 - Husk, 22](https://codegolf.stackexchange.com/a/200376/53748)
[RGS 3/5 - Jelly, 36](https://codegolf.stackexchange.com/a/200519/53748)
[RGS 4/5 - MATL, 26](https://codegolf.stackexchange.com/a/200704/53748) \*
This: 12
**Total = 103 bytes**
\* Might be 25, but I haven't proven that the 25 would never yield multiple results
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ 17 bytes
```
œ€.œ€`€€{ʒ€gQ}€{Ù
```
[Try it online!](https://tio.run/##yy9OTMpM/e/vY/P/6ORHTWv0wGQCEANR9alJQDI9sBbEPjzz//9oQx0jHaNYAA "05AB1E – Try It Online"), or [verify some test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRfeWilv4/N/6OTHzWt0QOTCUAMRNWHZ56aBKTTD60LrIXw/@vU/o@ONtRRQKBYHRDfCEgZQ5hQHogCsWIB)
---
### Explanation
```
- Takes input of the numbers [1..N]
œ - Permutations of this list
€.œ - Partitions of each of these permutations
€` - Flatten these 1 level
€€{ - Sort the lists in each list in each partition
ʒ - Filter the partitions
€g - Where the size of the sub partitions...
Q} - Equal to the second input (l)
€{Ù - Sort and uniquify these
- Output implicitly
```
---
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-Q`](https://codegolf.meta.stackexchange.com/a/14339/), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
á £V®Xj0Z ñ
â
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=4SCjVq5YajBaIPEK4g&input=WzAsMSwyXQpbM10)
**Submissions**
(1/5) [Japt, 9 bytes](https://codegolf.stackexchange.com/a/200132/84206)
(2/5) [CJam, 23 bytes](https://codegolf.stackexchange.com/a/200333/84206)
(3/5) [Japt, 40 or 41 bytes](https://codegolf.stackexchange.com/a/200529/84206) (I don't know which one to use, I'm not sure if the 40 byte one is valid)
(4/5) [Magma, 34 bytes](https://codegolf.stackexchange.com/a/200720/84206)
**Total Score: 120 (or maybe 119)**
[Answer]
# [J](http://jsoftware.com/), 47 bytes
```
[:~.~:@I.(/:(#,])&.>)@(<@/:~;.1)"1[:(!A.&i.])+/
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63q9OqsHDz1NPStNJR1YjXV9Ow0HTRsHPSt6qz1DDWVDKOtNBQd9dQy9WI1tfX/a3KlJmfkK6QpGAKhEYJjhMxBgTBhHTNk1cb/AQ "J – Try It Online")
I entirely missed the Portuguese one, so I'm out of the final prize anyway.
And J is not so good for handling non-rectangular arrays.
### How it works
```
[:~.~:@I.(/:(#,])&.>)@(<@/:~;.1)"1[:(!A.&i.])+/
[:(!A.&i.])+/ NB. all permutations of 0..n-1
+/ NB. sum of l, i.e. the value of n
( &i.]) NB. array of 0..n-1
! &i. NB. array of 0..n!-1
A. NB. (0..n!-1)-th permutations of 0..n-1
~:@I. NB. cut vector (1 2 3 -> 1 1 0 1 0 0)
I. NB. for each number k at index i, k copies of i
NB. e.g. 1 2 3 -> 0 1 1 2 2 2
~:@ NB. nub sieve; does each item appear for the first time?
(/:(#,])&.>)@(<@/:~;.1)"1 NB. cut, sort each item, and sort each row
"1 NB. on each row...
( ;.1) NB. cut to the lengths of l
NB. e.g. 1 1 0 (f;.1) 0 1 2 -> (f 0)(f 1 2)
<@/:~ NB. sort each item and enclose
( )@ NB. then...
/: NB. sort the row by...
( )&.> NB. the result applied to each item x...
#,] NB. the length of x, followed by x itself
NB. that is, sort by lengths then content
[:~. NB. finally, remove duplicate rows to get the answer
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 [bytes](https://github.com/barbuz/Husk/wiki/Codepage)
```
u→SġÖȯLuΣmOΠMṖ
```
**[Try it online!](https://tio.run/##yygtzv7/v/RR26TgIwsPTzux3qf03OJc/3MLfB/unPb///9oQx1DHZPY/9EGQNpIx1jHRMc0FgA "Husk – Try It Online")**
...I feel like the `→SġÖȯLuΣ` (last-entry-of hook group-by sort-by compose length deduplicate concatenated) should be `XȯLuΣ` where `X` is "maximals-by-predicate", saving 3 bytes, but I can't seem to find such a high-level-function. Maybe I'm being blind?
[Answer]
# [GAP](https://www.gap-system.org/), ~~145 127~~ 105 bytes
```
f:={l,c}->(i->Orbit(SymmetricGroup(c),Set(l,n->Set([1..n],k->NextIterator(i))),OnSetsSets))(Iterator(c));
```
[Try it online!](https://tio.run/##PYzBCsIwEER/pfS0C5vSiHhQzFW8WKFHm0MNqYS2aYkrKOK3x8aDMAMDb2Zu7Rxjt92/BzIfocAJVYWrY6hf42g5OHMI02MGg1RbhoG8UClcZFF4Tb1QJ/vkI9vQ8hTAISJVfmnckxHhjwziLp6D8wzdMidJa03pZqORsrzxjc8p@6FVAiTLRaVOsy8 "GAP – Try It Online")
This is absurdly long, but I like computing the answer as an orbit of a group action. I have mixed feelings about creating the first element using an `Iterator`...
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
{SMfqQlMTSMMs./M.pUs
```
[Try it online!](https://tio.run/##K6gsyfj/vzrYN60wMMc3JNjXt1hP31evILT4//9oQx0jHeNYAA "Pyth – Try It Online")
### Explanation
```
{SMfqQlMTSMMs./M.pUsQ # full program (Q=input, last one is implicit)
UsQ # range(sum(Q))
.p # get all permutations
s./M # for each permutation, get all partitions, concatenate to one list
SMM # sort each list in each partition
f # keep only the partitions T where
qQ # Q ==
lMT # map each list in a partition T to its length
SM # now sort the filtered partitions
{ # and deduplicate
```
[Answer]
# [R](https://www.r-project.org/) (with partitions library), 86 bytes
```
function(l,n)lapply(partitions::listParts(n),function(x)if(all(lengths(x)==l))show(x))
```
[Try it online at RDRR!](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(l%2Cn)lapply(partitions%3A%3AlistParts(n)%2Cfunction(x)if(all(lengths(x)%3D%3Dl))show(x))%0Ainvisible(f(c(1%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201)%2C%208))%0Ainvisible(f(c(2%2C%201)%2C3))%0Ainvisible(f(c(2%2C2%2C1)%2C%205)))
Assumes that `l` is sorted in decreasing order. Will print a lot of fluff after the answer, so I advise to call `invisible(f(l, n))` rather than `f(l, n)`.
The function `listParts` lists all the partitions of `1:n`; they are then filtered to keep only those whose lengths match the values of `l`.
Previous submissions, all in R (not that R is a competitive language!):
1. [38 bytes](https://codegolf.stackexchange.com/a/200005/86301)
2. [73 bytes](https://codegolf.stackexchange.com/a/200283/86301) (also [SPL, 398 bytes](https://codegolf.stackexchange.com/a/200426/86301))
3. [111 bytes](https://codegolf.stackexchange.com/a/200610/86301)
4. [68 bytes](https://codegolf.stackexchange.com/a/200693/86301)
**Total: 376 bytes**
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 95 bytes
```
⊞υE⊕⌈θE№θι⟦⟧Fη«≔υζ≔⟦⟧υFζFLκF∨⊕⌕§κλ⟦⟧№θλ¿‹L§§κλμλ⊞υEκ⎇⁻ξλνEν⎇⁻ρμπ⁺π⟦ι⟧»≔⟦⟧ζFυ«≔⟦⟧εFιFκ⊞ελ⊞ζε»⪫ζ¶
```
[Try it online!](https://tio.run/##XVDLasMwEDzXX7HkJIEKfRx7CoVASk196E31wdhKLCyvE8kqrku@3V35EdyAQBrN7szu5GVm8yYzw5B4VzIvIM5ObI@5VbXCVhUszjpd@5qdOZ/I18Zjy84CNH3IlHP@Eh0aC6zk8BvdbZ3TRwxKPRELlKkAH/BY2XMY73eFx7ZkFZ/xh/1nvdNYsG27x0J1rBJgZkMB1xkM2YM@BCnnFr2l5aa1Dp3UAOtViftUFjP7w2KN3rFuKsaJxlvaBh0BJwGJIUi31CGDMYZLtFq3X3Lx61wCo65B6Hnxah5KBXMiR9BPlZcosZq2fWs0hr/NF27IbBikfBRA54kk5cP0FPCcpsP9t/kD "Charcoal – Try It Online") Link is to verbose version of code. I don't often get to use the `r` variable; I think this might be only the second time ever. Takes the set counts and unique entries as arguments. Explanation:
```
⊞υE⊕⌈θE№θι⟦⟧
```
Make a list of lists of sets (also actually lists), where each element of that list will have a number of sets equal to the count of occurrences of that index in the input set counts, and push that list to the predefined empty list, which is now technically a list of lists of lists of lists.
```
Fη«
```
Loop over the unique entries.
```
≔υζ≔⟦⟧υ
```
Move the list of lists of lists of sets into a temporary variable so that it can be cleared to accumulate the results of this pass.
```
Fζ
```
Loop over each list of lists of sets from the previous pass.
```
FLκ
```
Loop over each possible set count.
```
F∨⊕⌕§κλ⟦⟧№θλ
```
Loop over each set, but if there is more than one empty set then stop at the first.
```
¿‹L§§κλμλ
```
Ignore this set if it's full.
```
⊞υEκ⎇⁻ξλνEν⎇⁻ρμπ⁺π⟦ι⟧
```
Construct a new list of lists of sets by replacing the one at the current set count with a new list of sets constructed by replacing the current set by union with the current unique entry. This is done to ensure that the new lists are all clones.
```
»≔⟦⟧ζFυ«≔⟦⟧εFιFκ⊞ελ⊞ζε»
```
Flatten each list of lists of sets in the resulting list into a list of sets.
```
⪫ζ¶
```
Output the list of lists of sets in a human-readable manner. (This only costs 1 byte, so I think it's fair.)
### Submission history:
(1/5) Charcoal, 19 bytes (Retina 0.8.2, 68 bytes)
(2/5) Charcoal, 31 bytes (Retina, 74 bytes)
(3/5) vi, 48 bytes (Charcoal, 50 bytes; Batch, 265 bytes)
(4/5) Charcoal, 41 bytes
(5/5) Charcoal, 95 bytes
Total score: 234 bytes
Total Charcoal score: 236 bytes
Wooden Spoon score: 543 bytes
]
|
[Question]
[
**Input:** a sequence of uppercase letters (ASCII [65;90]) which is the ***N**th*\* lexicographical permutation of the multiset of its characters
\*permutations are numbered from 0 or 1 upwards
**Output:** base-10 integer ***N***
---
### Rulez
* **There might be duplicates** *(that's how this challenge differs from
[this one](https://codegolf.stackexchange.com/questions/34807))*
* The characters are ordered by their ASCII value
* In case of an input of length less than or equal to 1, the input is the
first permutation and the result is `0` or `1` respectively
* First permutation is that in which the leftmost character has the lowest
value, the rightmost character has the highest value, and the sequence
of characters between the first and the last character is the first
permutation of the multiset of its characters *(recursive definition!)*
* Shortest entry wins
---
### Example
* Input `AAB` produces output `0`
* Input `ABA` produces output `1`
* Input `BAA` produces output `2`

* Input `ZZZ` produces output `0`
* Input `DCBA` produces output `23`
---
### EDIT
Extra kudos to the one who can come up with a solution which doesn't produce all permutations and then search for the input. That's some challenge.
[Answer]
## Python 2, 69 bytes
[Try it online](https://tio.run/nexus/python2#y7GN@Z@TmJuUkqgQbFWcX1SSmqJRnFqiUZBalFtakliSmZ9XrBGsqampl5mXkloBZHKlFeXnKmSWpBaV5OfnFCtk5hYAtWn9LyjKzCtRyNHQUHdR11FQdwYRTiDCUV1T8z8A)
```
from itertools import*
lambda S:sorted(set(permutations(S))).index(S)
```
[Answer]
## Python, ~~302~~ 287 bytes
Dead Possum has already posted a short Pythonic solution, so I decided to go for the extra kudos. This solution does *not* generate all of the permutations. It can rapidly calculate the permutation index of a rather large string; it also handles an empty string correctly.
```
from math import factorial as f
from itertools import groupby as g
def p(t,b=''):
if len(t)<2:return 0
z,b=0,b or sorted(t)
for i,c in enumerate(b):
w=b[:i]+b[i+1:]
if c==t[0]:return z+p(t[1:],w)
if i<1 or c!=b[i-1]:
n=f(len(w))
for _,v in g(w):n//=f(len(list(v)))
z+=n
```
Testing code:
```
def lexico_permute_string(s):
''' Generate all permutations of `s` in lexicographic order '''
a = sorted(s)
n = len(a) - 1
while True:
yield ''.join(a)
for j in range(n-1, -1, -1):
if a[j] < a[j + 1]:
break
else:
return
v = a[j]
for k in range(n, j, -1):
if v < a[k]:
break
a[j], a[k] = a[k], a[j]
a[j+1:] = a[j+1:][::-1]
def test_all(base):
for i, s in enumerate(lexico_permute_string(base)):
rank = p(s)
assert rank == i, (i, s, rank)
print('{:2} {} {:2}'.format(i, s, rank))
print(repr(base), 'ok\n')
for base in ('AAB', 'abbbbc'):
test_all(base)
def test(s):
print('{!r}\n{}\n'.format(s, p(s)))
for s in ('ZZZ', 'DCBA', 'a quick brown fox jumps over the lazy dog'):
test(s)
```
**output**
```
0 AAB 0
1 ABA 1
2 BAA 2
'AAB' ok
0 abbbbc 0
1 abbbcb 1
2 abbcbb 2
3 abcbbb 3
4 acbbbb 4
5 babbbc 5
6 babbcb 6
7 babcbb 7
8 bacbbb 8
9 bbabbc 9
10 bbabcb 10
11 bbacbb 11
12 bbbabc 12
13 bbbacb 13
14 bbbbac 14
15 bbbbca 15
16 bbbcab 16
17 bbbcba 17
18 bbcabb 18
19 bbcbab 19
20 bbcbba 20
21 bcabbb 21
22 bcbabb 22
23 bcbbab 23
24 bcbbba 24
25 cabbbb 25
26 cbabbb 26
27 cbbabb 27
28 cbbbab 28
29 cbbbba 29
'abbbbc' ok
'ZZZ'
0
'DCBA'
23
'a quick brown fox jumps over the lazy dog'
436629906477779191275460617121351796379337
```
---
Non-golfed version:
```
''' Determine the rank (lexicographic index) of a permutation
The permutation may contain repeated items
Written by PM 2Ring 2017.04.03
'''
from math import factorial as fac
from itertools import groupby
def lexico_permute_string(s):
''' Generate all permutations of `s` in lexicographic order '''
a = sorted(s)
n = len(a) - 1
while True:
yield ''.join(a)
for j in range(n-1, -1, -1):
if a[j] < a[j + 1]:
break
else:
return
v = a[j]
for k in range(n, j, -1):
if v < a[k]:
break
a[j], a[k] = a[k], a[j]
a[j+1:] = a[j+1:][::-1]
def perm_count(s):
''' Count the total number of permutations of sorted sequence `s` '''
n = fac(len(s))
for _, g in groupby(s):
n //= fac(sum(1 for u in g))
return n
def perm_rank(target, base):
''' Determine the permutation rank of string `target`
given the rank zero permutation string `base`,
i.e., the chars in `base` are in lexicographic order.
'''
if len(target) < 2:
return 0
total = 0
head, newtarget = target[0], target[1:]
for i, c in enumerate(base):
newbase = base[:i] + base[i+1:]
if c == head:
return total + perm_rank(newtarget, newbase)
elif i and c == base[i-1]:
continue
total += perm_count(newbase)
base = 'abcccdde'
print('total number', perm_count(base))
for i, s in enumerate(lexico_permute_string(base)):
rank = perm_rank(s, base)
assert rank == i, (i, s, rank)
#print('{:2} {} {:2}'.format(i, s, rank))
print('ok')
```
**About `lexico_permute_string`**
This algorithm, due to Narayana Pandita, is from
<https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order>
To produce the next permutation in lexicographic order of sequence `a`
1. Find the largest index j such that a[j] < a[j + 1]. If no such index exists,
the permutation is the last permutation.
2. Find the largest index k greater than j such that a[j] < a[k].
3. Swap the value of a[j] with that of a[k].
4. Reverse the sequence from a[j + 1] up to and including the final element a[n].
FWIW, you can see an annotated version of that function [here](https://stackoverflow.com/a/43014919/4014959).
---
FWIW, here's the inverse function.
```
def perm_unrank(rank, base, head=''):
''' Determine the permutation with given rank of the
rank zero permutation string `base`.
'''
if len(base) < 2:
return head + ''.join(base)
total = 0
for i, c in enumerate(base):
if i < 1 or c != base[i-1]:
newbase = base[:i] + base[i+1:]
newtotal = total + perm_count(newbase)
if newtotal > rank:
return perm_unrank(rank - total, newbase, head + c)
total = newtotal
# Test
target = 'a quick brown fox jumps over the lazy dog'
base = ''.join(sorted(target))
rank = perm_rank(target, base)
print(target)
print(base)
print(rank)
print(perm_unrank(rank, base))
```
**output**
```
a quick brown fox jumps over the lazy dog
aabcdeefghijklmnoooopqrrstuuvwxyz
436629906477779191275460617121351796379337
a quick brown fox jumps over the lazy dog
```
And here's a function that I wrote while developing `perm_unrank` which shows the breakdown of the subcounts.
```
def counts(base):
for i, c in enumerate(base):
newbase = base[:i] + base[i+1:]
if newbase and (i < 1 or c != base[i-1]):
yield c, perm_count(newbase)
for h, k in counts(newbase):
yield c + h, k
def show_counts(base):
TAB = ' ' * 4
for s, t in counts(base):
d = len(s) - 1
print('{}{} {}'.format(TAB * d, s, t))
# Test
base = 'abccc'
print('total number', perm_count(base))
show_counts(base)
```
**output**
```
a 4
ab 1
abc 1
abcc 1
ac 3
acb 1
acbc 1
acc 2
accb 1
accc 1
b 4
ba 1
bac 1
bacc 1
bc 3
bca 1
bcac 1
bcc 2
bcca 1
bccc 1
c 12
ca 3
cab 1
cabc 1
cac 2
cacb 1
cacc 1
cb 3
cba 1
cbac 1
cbc 2
cbca 1
cbcc 1
cc 6
cca 2
ccab 1
ccac 1
ccb 2
ccba 1
ccbc 1
ccc 2
ccca 1
cccb 1
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
œêJ¹k
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@3908uFVXod2Zv//7@ToCAA "05AB1E – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
œê¹Sk
```
[Try it online!](https://tio.run/nexus/05ab1e#@3908uFVh3YGZ///7@Ls5AgA "05AB1E – TIO Nexus")
Independently discovered from Adnan's answer.
[Answer]
# PHP, 124 Bytes
```
$a=str_split($argn);sort($a);for($i=$j=join($a);$i<=strrev($j);$i++)$i==$argn?print+$n:(($c=count_chars)($i)!=$c($j)?:$n++);
```
## PHP, 136 Bytes
```
foreach($t=($c=count_chars)($argn)as$k=>$v)$i=$s.=str_repeat(chr($k),$v);for(;$i<=strrev($s);$i++)$i==$argn?print+$n:($c($i)!=$t?:$n++);
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/1a5b1733e1728b833f1b8db2ab14160b4a2a5521)
Run with
```
echo '<string>' | php -nR '<code>'
```
## Calculate with factorial
Expanded Version
```
function f($i){return array_product(range(1,$i));} #factorial
function p($s){
return f(strlen($s))/array_product(array_map("f",count_chars($s,1)));
} # factorial / divide through product of factorials for each char
$a=$argn;
$b="";
$r=[];
for($d=0;$a;$d++) # loop range before used chars in string
{
for($i=0;$i<strlen($a);$i++){ # loop for every char in the rest string
if($a[$i]<$a[0]) # if char is before first char order by ascii
$r[$d.$a[$i]]=p(substr_replace($a,"",$i,1)); # add range before
}
$a=substr($a,1); # remove first char
}
echo array_sum($r); # Output the range before the used permutation
```
Output for the string PPCG
```
Array
(
[0C] => 3 # in first run C is before P startposition = 3
[0G] => 3 # in first run G is before P startposition = 3+3
[1C] => 2 # in second run PC is before PP startposition = 3+3+2
[1G] => 2 # in second run PG is before PP startposition = 3+3+2+2=8
)
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/500b1e8deee5192010d133d332cef78cf1fab414)
[Answer]
# Julia, ~~121~~ 125 bytes
Noncompeting, as it does not deal with duplicate letters correctly. I ported this from another language, from part of a solution to a Project Euler problem I did several years ago, and the first, 121-byte version had a bug because I had transposed the use of the permuted string and the sorted, canonical reference string.
```
f(p)=(n=0;z=length(p)-1;s=join(sort(collect(p)));for c in p z-=(n+=factorial(z)*(search(s, c)-1);p=replace(s,c,"",1);1)end;n)
```
For large inputs, this version uses bignums at the cost of 8 extra bytes:
```
f(p)=(n=0;z=BigInt(length(p)-1);s=join(sort(collect(p)));for c in p z-=(n+=factorial(z)*(search(s, c)-1);p=replace(s,c,"",1);1)end;n)
```
Ungolfed:
```
function f(perm)
nth = 0
size = length(perm) - 1
sorted = join(sort(collect(p)))
for ch in sorted
index = search(perm, ch) - 1
nth += factorial(size) * index
perm = replace(perm, ch, "" , 1) # replace at most one copy
size -= 1
end
return nth
end
```
Uses a [factoriadic number system](https://en.wikipedia.org/wiki/Factorial_number_system), q.v. Thus, it does not produce all the permutations and for large inputs will run enormously faster than those that do.
For example, the alphabet can be permuted into the rather contrived sentence "Quartz glyph job vex'd cwm finks." That sentence is the 259,985,607,122,410,643,097,474,123rd lexicographic permutation of the letters of the alphabet. (Approximately 260 septillionth permutation.) This program finds that in about 65 µs on my machine.
```
julia> @time f("quartzglyphjobvexdcwmfinks")
0.000065 seconds (570 allocations: 19.234 KB)
259985607122410643097474122
```
Note that the number ends in ...122 rather than ...123 because OP requested that the permutations be numbered from 0 rather than from 1.
# Julia, 375 bytes
I've left the indentation in for readability, but the byte count is without it.
```
p(t,b="")=begin
l=length
if l(t)<2 return 0 end
f=factorial
g(w)=(a=[];
while w!=""
s=""
for c in w if c==w[1] s="$s$c" end end
w=replace(w,s,"")
push!(a,s)
end;a)
b=b>""?b:join(sort(collect(t)))
z=0
for(i,c) in enumerate(b)
w=b[1:i-1]*b[i+1:end]
if c==t[1] return z+p(t[2:end],w)
elseif i>1&&c==b[i-1] continue end
n=f(l(w))
for v in g(w) n=div(n,f(l(v))) end
z+=n
end
z
end
```
This one is just a straight Julia port of PM 2Ring's brilliant Python solution. I got hungry, so I decided I wanted the cookie after all. It's interesting to see the similarities and the differences between the two languages. I implemented `itertools.groupby` (in a limited form) as `g(w)`.
But the logic isn't mine, so go and upvote [PM 2Ring's answer](https://codegolf.stackexchange.com/a/115024/794).
Replace `f=factorial` with `f(x)=factorial(BigInt(x))` if you want to be able to handle large inputs like p("QUARTZGLYPHJOBVEXDCWMFINKS").
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~13~~ ~~12~~ 11 bytes
*1 byte saved thanks to [G B](https://codegolf.stackexchange.com/users/18535/g-b)!*
```
tY@Xu=!Af1)
```
Output is 1-based.
[Try it online!](https://tio.run/nexus/matl#@18S6RBRaqvomGao@f@/uouzk6M6AA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/hfEukQUWqr6JhmqPnfJeS/uqOjkzqXuqOTI5B0cgSRUVFRQNLFGSgEAA).
### Explanation
```
t % Input string implicitly. Duplicate
Y@ % All permutations, sorted; each in a different row
Xu % Unique rows
= % Compare for equality, with broadcast
! % Transpose
A % All: true for columns that contain all entries true
f % Find: indices of nonzero elements
1) % Get first of those indices. Implicitly display
```
[Answer]
# Mathematica, ~~33~~ 31 bytes
*Changing the problem spec allowed for a 2-byte savings.*
```
Permutations@Sort@#~Position~#&
```
Pure function taking a list as input and returning a nonnegative integer `N` in the form `{{N}}`.
[Answer]
# JavaScript (ES6), 130 bytes
```
s=>(o=new Set,p=(s,q)=>s.map((t,i)=>p(t=[...s],q.concat(t.splice(i,1))))[0]||o.add(q.join``))([...s],[])&&[...o].sort().indexOf(s)
```
*Less golfed*
```
s=>{
o = new Set; // use a set to avoid duplicates
// recursive function to build all permutations (no cookie for me)
p = (s, q) =>
{
y = s.map( (t,i) => // execute for each char at position i
(
t = [...s], // using t as local variable, store a copy of s
x = t.splice(i,1), // remove char from t in position i, and store in array x
p(t, q.concat(x)) // recursive call
));
if (!y[0]) // if s was empty, I have a new permutation in q
o.add( q.join('')) // convert to string and add to output set
}
// call p to enumerate all permutations
p( [...s], [] ) // convert string s to array, q starts empty
o = [...o].sort() // get elements of o and sort lexicographically
return o.indexOf(s) // return the position of the input in o
}
```
**Test**
```
F=
s=>(o=new Set,p=(s,q)=>s.map((t,i)=>p(t=[...s],q.concat(t.splice(i,1))))[0]||o.add(q.join``))([...s],[])&&[...o].sort().indexOf(s)
function update() {
O.textContent = F(I.value)
}
update()
```
```
<input id=I value='DCBA' oninput='update()'>
<pre id=O></pre>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Œ!QṢi
```
[Try it online!](https://tio.run/nexus/jelly#@390kmLgw52LMv///@/i7OQIAA "Jelly – TIO Nexus")
1-indexed output.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 7 bytes
```
q_e!\a#
```
[Try it online!](https://tio.run/nexus/cjam#@18Yn6oYk6j8/7@Ls5MjAA "CJam – TIO Nexus")
[Answer]
# Pyth, 5 bytes
```
xS{.p
```
[Online interpreter](//pyth.herokuapp.com?code=xS%7B.p&input=%27DCBA%27)
Takes quoted input.
[Answer]
# Scala, 40 bytes
```
s=>s.permutations.toSeq.sorted indexOf s
```
To use it, assign this function to a variable:
```
val f:(String=>Int)=s=>s.permutations.toSeq.sorted indexOf s
println(f("BAA"))
```
[Try it online at ideone](https://ideone.com/GdnzMB)
Unfortunately, `permutations` returns an iterator, which doesn't have a `sorted` method, so it has to be converted to a `Seq`
[Answer]
# C++, 96 bytes
We can make full use of the standard library here. The list of letters is passed as start/end iterators in standard C++ style.
```
#include<algorithm>
int f(char*a,char*z){int i=0;while(std::prev_permutation(a,z))++i;return i;}
```
We don't need to generate all permutations - since we have a transformation from one permutation to its predecessor, we simply count how many iterations it takes to reach the zeroth value.
### Test program:
```
#include<cstring>
#include<iostream>
int main(int argc, char **argv)
{
while (*++argv)
std::cout << *argv << ": "
<< f(*argv, *argv+std::strlen(*argv)) << std::endl;
}
```
### Test results:
```
BAA: 0
BAA: 1
BAA: 2
ZZZ: 0
DCBA: 23
: 0
```
[Answer]
# Ruby, 50 bytes
I expected this to be shorter. I wouldn't have added the `sort` if the docs didn't say "the implementation makes no guarantees about the order in which the permutations are yielded."
```
->x{x.chars.permutation.map{|v|v*""}.sort.index x}
```
[Answer]
# Japt, 6 bytes
0-indexed
```
ñ á bU
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8SDhIGJV&input=IkRDQkEi)
]
|
[Question]
[
What is the shortest way to see if an input is a wordinian using any programming language?
A wordinian is a word that contains words of length 1 to the original word's length. For example,
>
> ## bin
>
>
> 'I' is a word
>
> 'in' is a word
>
> 'bin' is a word
>
>
>
Or,
>
> ## stage
>
>
> 'a' is a word
>
> 'ta' is a word ([yes it is](http://www.urbandictionary.com/define.php?term=TA))
>
> 'age' is a word
>
> 'stag' is a word
>
> 'stage' is a word
>
>
>
# Input
Your code should take a word and a dictionary as inputs, in any reasonable format.
# Output
The output should be a value to indicate true or false, to tell us if the word is a wordinian.
[For more info on wordinians click here](http://www.wordinian.com/).
[Here is a list of words](https://raw.githubusercontent.com/JacquesMarais/ENABLE2K/master/words.txt) that I will be using as inputs and subwords. Also, in response to @xnor, it has to contain subwords of each length, not a chain of subwords. Note that only one word will be used as an input.
[Answer]
## Python, 52 bytes
```
lambda w,d:len({len(x)for x in d if x in w})==len(w)
```
An anonymous function that takes a word `w` and dictionary `d`. It takes the words in `d` that are substrings of `w`, makes a set of their lengths, and then checks that there as many distinct lengths as there are letters in `w`.
[Answer]
# Pyth, ~~20~~ ~~16~~ ~~15~~ ~~13~~ 11 bytes
Thanks to Leaky Nun for saving 4 bytes! Unfortunately, I changed the entire method afterwards, but it still helped.
```
gl{lM}#zQlz
```
Expects input as dictionary followed by word. Outputs True or False.
[Try it here!](http://pyth.herokuapp.com/?code=gl%7BlM%7D%23zQlz&input=%5B%22a%22%2C%22ta%22%2C%22tag%22%2C%22age%22%2C%22stag%22%2C%22stage%22%2C%22useless%22%2C%22test%22%5D%0Astage%0A&debug=0)
Explanation:
```
lz Collects the length of the word input
g and compares it to:
l The length of the following:
# Q Select all words from the dictionary that
} z are contained within the input word.
lM Map them to their respective lengths, and
{ then remove any duplicates.
```
This does not function if the empty string `""` is a valid word.
[Answer]
# Python 3, 108 bytes
```
lambda w,d,r=range:all(any(i in d for i in j)for j in[[w[i:i+s]for i in r(len(w)+1-s)]for s in r(1,len(w))])
```
An anonymous function that takes input, via argument, of a word `w` as a string and a dictionary `d` as a list of strings and returns `True` or `False`.
**How it works**
The first step is a list comprehension that generates a list of lists of all substrings of `w` excluding `w`, grouped by length. For example, for `'stage'`, the list `[['s', 't', 'a', 'g', 'e'], ['st', 'ta', 'ag', 'ge'], ['sta', 'tag', 'age'], ['stag', 'tage']]` is generated. This is achieved by looping over all valid start indices `i` for each substring length `s`, and slicing every `s`-length substring using `w[i:i+s]`. For each list in this list, the presence of each substring in the dictionary is checked; calling `any` returns a hit if at least one match for a given length is found. Finally, calling `all` checks if a match has been found for all substring lengths, and the result of this is returned.
[Try it on Ideone](http://ideone.com/sc90Cb)
[Answer]
# Ruby, 44 bytes
* 7 Bytes off thanks to @NotThatCharles and his set operator tricks!
* 2 bytes off thanks to @Jordan with the Ruby 2.3 safe navigation operator trick `w[x]&.size` :)
```
->w,d{[*1..w.size]-d.map{|x|w[x]&.size}==[]}
```
It's an anonymous functions which takes a word `w` and a dictionary (array of words) `d`. Creates two arrays: The first containing the numbers 1 up to and including the length of `w`; The second array is `d` with each word mapped to their size if they are a substring of `w`, otherwise `nil`. Then it does set substraction to check whether the second array contains all element of the first array.
[Answer]
## PowerShell ~~v3+~~ v2+, ~~127~~ ~~110~~ ~~70~~ 65 bytes
```
param($a,$d)($d|?{$a-match$_}|select length -U).count-eq$a.length
```
*(I see now that my approach is similar to @xnor's, though I developed it independently)*
Takes input word `$a` and dictionary `$d`, expecting `$d` as an array (see examples below). Loops through the entirety of `$d` and performs a `Where-Object` to pull out the entries where the current word `$_` is a regex `-match` against the input word `$a` (i.e., is the current word a substring of the input word).
We collect all of those substring words and pipe them to `Select-Object` on the `length` parameter and the `-U`nique constraint. That will pull out the unique lengths of each substring. For example, for input word `comb`, this will be an array of `(4,2)` for `('comb','om')`.
We take the `.count` of that resultant array and compare it against the input word's `.length`. If it's equal to, that means that every substring length is in the dictionary, so `$TRUE`, otherwise we're missing at least one, so `$FALSE`. That Boolean value is left on the pipeline and output is implicit.
NB - This *should* work in v2+, since the `-in` operator is no longer present, but I've not tested that version.
### Examples
```
PS C:\Tools\Scripts\golfing> .\is-it-a-wordinian.ps1 'stage' (gc .\words.txt)
True
PS C:\Tools\Scripts\golfing> .\is-it-a-wordinian.ps1 'metal' (gc .\words.txt)
True
PS C:\Tools\Scripts\golfing> .\is-it-a-wordinian.ps1 'comb' (gc .\words.txt)
False
```
[Answer]
## Perl, 86 bytes
Requires `-E` at no extra cost.
```
chop(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x
```
Accepts all input via STDIN. First input is target word, rest of input is dictionary. Prints `1` on success, empty string on failure.
### Usage
```
perl -E 'chomp(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x' <<< 'stage
a
ta
age
stag
stage'
1
perl -E 'chomp(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x' <<< 'stage
a
at
age
stag
stage'
perl -E 'chomp(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x' <<< 'bin
i
in
bin'
1
```
[Answer]
# Mathematica, 90 bytes
```
Sort[MemberQ[DictionaryWordQ/@StringPartition[#,t,1],True]~Table~{t,StringLength@#}][[1]]&
```
Uses *Mathematica's* builtin `DictionaryWordQ`.
Taking input `d` as dictionary is 5 bytes shorter, but much slower for long lists:
```
m=MemberQ;Sort[m[d~m~#&/@StringPartition[#,t,1],True]~Table~{t,StringLength@#}][[1]]&
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
*1 byte saved using an idea from [@xnor's answer](https://codegolf.stackexchange.com/a/89991/36398).*
```
XXgc32>!suz1Gn=
```
Outputs `1` or `0` for truthy or falsy.
[**Try it online!**](https://tio.run/##y00syfn/PyIiPdnYyE6xuLTK0D3P9v9/9eKSxPRUda5q9UR1HfUSCJEOJIsRVCqQLi1OzUktLgZJpxaXqNcCAA)
```
XX % Take the two inputs implicitly. Apply the second as a regex into the
% first. Since the second input is a cell array, each of its contents is
% applied separately as a regex. So for each dictionary word ("sub-word")
% this outputs the sub-word if found in the original word, or else an
% empty array. Gives a cell array of cells of strings
g % Remove one level of nestedness
c % Convert to char. This concatenates all found sub-words as rows of a 2D
% char array, padding with spaces as needed
32>!s % For each row, count how many non-space characters there are. This is
% the length of each sub-word
uz % Number of distinct non-zero elements
1Gn % Push length of the original word
= % Are they equal? Implicitly display
```
[Answer]
# Perl, ~~42~~ 41 bytes
Includes +2 for `-p0`
Give word followed by the dictionary on STDIN:
```
(echo stage; cat dictionary.txt) | ./wordinian.pl
```
(When testing on unix make sure dictionary.txt uses `\n` as line terminator, not `\r\n`)
`wordinian.pl`:
```
#!/usr/bin/perl -p0
s%\G.%!/^.*(.{$+[0]})\H*
\1
/%eg;$_=!//
```
[Answer]
## JavaScript (Firefox 30-57), 68 bytes
```
(w,a)=>new Set((for(x of a)if(~w.search(x))x.length)).size==w.length
```
Using a generator comprehension avoids creating an intermediate array. 73 byte ES6 version:
```
(w,a)=>new Set(a.filter(x=>~w.search(x)).map(x=>x.length)).size==w.length
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒÃ€gZLåP
```
Word as first input, dictionary-list as second input.
[Try it online](https://tio.run/##yy9OTMpM/f//6KTDzY@a1qRH@RxeGvD/f3FJYnoqV7RSopKOUgmESAeSQEEgWQzhgNUA6dLi1JzU4mKQotTiEqVYAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/W/s5ulir6SQmJeioGQPZj5qmwRkFv8/Oulw86OmNelRPoeXBvzX@V9ckpieyhWtlKiko1QCIdKBJFAQSBZDOGA1QLq0ODUntbgYpCi1uEQplispMw@oNRMokJkHJIBcVMESmCAA).
**Explanation:**
```
Œ # Get all possible substrings of the (implicit) input-string
à # Only keep the ones which are also in the (implicit) dictionary-list
€g # Get the length of each remaining string
Z # Push the maximum length (without popping the list)
L # Pop and push a list in the range [1, maximum-length]
å # Check for each value if it's in the list of lengths
P # And check if this is truthy for all
# (then output the result implicitly as result)
```
[Answer]
# [Kotlin](https://kotlinlang.org), 51 bytes
```
{w,d->w.indices.all{w.windowed(it+1).any{it in d}}}
```
[Try it online!](https://tio.run/##VY9BD4IwDIXv/IpyYouwxKsRTDxz8@B5umkaR0fYdDGE344Dg8EmPbz25X3tw3qDNL6kAXRn2ykklLQDdvId0j2HGp3ff0XFoajgaK3RkqAc@5CrogoCSeFVOyGN6YMIUdqgFUO/2XIh6d2jByRQwzCMtydBI5EYhz6BWBM5RC6U0GmpaiTN@EFEYMN4mv48EeH/PPNmqsW8GrjWoGcZZEtCG@/3htjqRzZR8zmX82QYL0hJ7OlS/AA "Kotlin – Try It Online")
[Answer]
# [SQF](https://community.bistudio.com/wiki/SQF_syntax), 147 bytes
Using the function-as-a-file format:
```
params["w","d"];a=[];c=count w;for"i"from 1 to c do{a=a+[""];for"j"from 0 to c-i do{q=w select[j,i];if(q in d)then{a set[i-1,q]}}};c==count(a-[""])
```
Call as: `["WORD", DICTIONARY] call NAME_OF_COMPILED_FUNCTION`
Ungolfed:
```
//name parameters
params["w", "d"];
a = []; c = count w;
//for each length of subword
for "i" from 1 to c do {
//add entry to the `a`
a = a + [""];
//for each starting position for that length
for "j" from 0 to c - i do {
//get subword
q = w select [j, i];
//check if in dictionary
if(q in d) then {
//set the entry to the wubword
a set [i - 1, q]
}
}
};
//check if length of word is equal to number of subwords
c == count (a - [""])
```
]
|
[Question]
[
Dead code sits there doing nothing, staring at us knowing it will never be executed... but today we can take revenge.
## Specification
The input will be a multiline string.
Each line may either be an **assignment** or an **expression** .
### Assignment
An assignment is of the form `<name> = number` where name is a sequence of letters, underscores and numbers, but not starting with a number.
Variables may be assigned any number of times.
### Expression
An expression is of the form `<var_name OR number> <operation> <var_name OR number> ...`
An expression may be any combination of:
* Variables already defined
* Basic arithmetic operators `+-*/`
* Numbers (integers)
## Expected output
You should output the string with redundant **assignments**, **assignments** that are never used by any of the **expressions** following it, removed. Please note that **assignments** can also be made redundant if an additional **assignment** to the same variable is performed before an **expression** using the variable is executed.
## Test cases
**in**
```
a = 10
a * 3
```
**out**
```
a = 10
a * 3
```
---
**in**
```
foo = 8
2 - 1
a = 18
```
**out**
```
2 - 1
```
---
**in**
```
a = 10
a = 8
b = 4
ab = 72
b / 6
b + 1
```
**out**
```
b = 4
b / 6
b + 1
```
---
**in**
```
a = 1
a = 2
a + 1
```
**out**
```
a = 2
a + 1
```
---
**in**
```
FooBar1 = 0
Fuz__ = 8
Fuz__ / 1
```
**out**
```
Fuz__ = 8
Fuz__ / 1
```
---
**in**
```
a = 1
a + 1
a = 2
a + 1
```
**out**
```
a = 1
a + 1
a = 2
a + 1
```
---
**in**
```
a = 1
1 / 5 * 8 + 4
```
**out**
```
1 / 5 * 8 + 4
```
---
**in**
```
a = 1
a + 1
a = 1
a + 1
```
**out**
```
a = 1
a + 1
a = 1
a + 1
```
---
**in**
```
a = 7
5 / a
```
**out**
```
a = 7
5 / a
```
[Answer]
## PHP - 197 bytes
The function works by analysing each line, in the reverse order and one after the other, and maintaining an array of the used variables.
* If there is an equal character `=` in the line, it's an assignment.
+ It the variable is used, the assignment is useful, and the line is printed, but the variable isn't considered used any more.
+ Otherwise, do nothing.
* Otherwise, the line is an expression. We split the line after each space, and add each symbol to the list of used variables. Numbers (`1`, `2`, …) and operators (`+`, `-`, …) will be added too, but since they aren't valid variables names, it's not a problem. The line is then of course printed.
```
function($c){$u=[];foreach(array_reverse(split('
',$c))as$l){if($p=strpos($l,'=')){if(!isset($u[$x=substr($l,0,$p-1)]))continue;
unset($u[$x]);}else$u+=array_flip(split(' ',$l));$f="
$l$f";}echo$f;}
```
Here is the ungolfed version:
```
function removeDeadCode($code)
{
$usedVariables = [];
$finalCode = '';
foreach (array_reverse(explode("\n", $code)) as $line)
{
if ($equalPosition = strpos($line, '='))
{
$variable = substr($line, 0, $equalPosition - 1);
if (isset($usedVariables[$variable]))
{
$finalCode = "\n" . $line . $finalCode;
unset($usedVariables[$variable]);
}
}
else
{
$usedVariables += array_flip(explode(' ', $line));
$finalCode = "\n" . $line . $finalCode;
}
}
echo $finalCode;
}
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 45 bytes
```
m`^(\w+) =.*\n(?=((?!\b\1\b)[^!])*(^\1 =|\Z))
<empty>
```
For counting purposes, each line goes in a separate file (where `<empty>` is an empty file) and `\n` should be replaced with an actual line feed (0x0A).
This assumes that the string will always end with a line feed.
As this regex doesn't use any .NET-specific features, [you can test it on regex101](https://regex101.com/r/wV4pQ3/1).
The idea is fairly simple: remove all assignments from which we can find (searching forward) another assignment to the same variable or the end of the string without passing another use of the variable.
[Answer]
# Pyth, 40 bytes
```
eMf|!}K\=eT&Jf}+dhceTK++dYdPT!}KeJ_.__.z
```
Seems kinda long. Maybe I can save one or two bytes tomorrow.
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=eMf|!%7DK%5C%3DeT%26Jf%7D%2BdhceTK%2B%2BdYdPT!%7DKeJ_.__.z&input=foo+%3D+8%0A2+-+1%0Aa+%3D+18&test_suite_input=a+%3D+10%0Aa+*+3%0A%0A%0A%0A%0Afoo+%3D+8%0A2+-+1%0Aa+%3D+18%0A%0A%0A%0Aa+%3D+10%0Aa+%3D+8%0Ab+%3D+4%0Aab+%3D+72++%0Ab+%2F+6%0Ab+%2B+1%0Aa+%3D+1%0Aa+%3D+2%0Aa+%2B+1%0A%0A%0A%0AFooBar1+%3D+0%0AFuz__+%3D+8%0AFuz__+%2F+1%0A%0A%0A%0Aa+%3D+1%0Aa+%2B+1%0Aa+%3D+2%0Aa+%2B+1%0A%0A%0Aa+%3D+1%0A1+%2F+5+*+8+%2B+4%0A%0A%0A%0A%0Aa+%3D+1%0Aa+%2B+1%0Aa+%3D+1%0Aa+%2B+1%0A%0A%0A&debug=0&input_size=6) or [Test Suite](http://pyth.herokuapp.com/?code=eMf|!%7DK%5C%3DeT%26Jf%7D%2BdhceTK%2B%2BdYdPT!%7DKeJ_.__.z&input=foo+%3D+8%0A2+-+1%0Aa+%3D+18&test_suite=1&test_suite_input=a+%3D+10%0Aa+*+3%0A%0A%0A%0A%0Afoo+%3D+8%0A2+-+1%0Aa+%3D+18%0A%0A%0A%0Aa+%3D+10%0Aa+%3D+8%0Ab+%3D+4%0Aab+%3D+72++%0Ab+%2F+6%0Ab+%2B+1%0Aa+%3D+1%0Aa+%3D+2%0Aa+%2B+1%0A%0A%0A%0AFooBar1+%3D+0%0AFuz__+%3D+8%0AFuz__+%2F+1%0A%0A%0A%0Aa+%3D+1%0Aa+%2B+1%0Aa+%3D+2%0Aa+%2B+1%0A%0A%0Aa+%3D+1%0A1+%2F+5+*+8+%2B+4%0A%0A%0A%0A%0Aa+%3D+1%0Aa+%2B+1%0Aa+%3D+1%0Aa+%2B+1%0A%0A%0A&debug=0&input_size=6)
### Explanation:
`_.__.z` gives all postfixes of the input lines in reversed order. E.g. the input `FooBar1 = 0; Fuz__ = 8; Fuz__ / 1` gives the list:
```
[['Fuz__ / 1', 'Fuz__ = 8', 'FooBar1 = 0'],
['Fuz__ / 1', 'Fuz__ = 8']
['Fuz__ / 1']]
```
Then I filter for list elements `T`, in which `=` doesn't is in the last element of `T` (expression) or (assignment) the last element in `T`, which contains the variable name, is an expression. Afterwards print the last element of each of the remaining elements on a separate line.
```
eMf|!}K\=eT&Jf}+dhceTK++dYdPT!}KeJ_.__.z
.z all input lines
_ reverse order
._ all prefixes
_ reverse order
f filter for elements T, which satisfy:
K\= K = '='
!}K eT '=' is not in T[-1]
| or
f PT filter for elements Y in T[:-1],
which satisfy:
hceTK extract variable name of T[-1]
with an additional space at the end
+d and at the beginning
} ++dYd ^ in space+Y+space
J assign these list to J
& J not empty and
!KeJ '=' is not in J[-1]
eM take the last element of each and print
```
[Answer]
# CJam, 49 bytes
```
LqN/W%{_'=#_){(<:V1$\e=_{\Va-\}&}{;S/+1}?},\;W%N*
```
[Try it online](http://cjam.aditsu.net/#code=LqN%2FW%25%7B_'%3D%23_)%7B(%3C%3AV1%24%5Ce%3D_%7B%5CVa-%5C%7D%26%7D%7B%3BS%2F%2B1%7D%3F%7D%2C%5C%3BW%25N*&input=a%20%3D%2010%0Aa%20%3D%208%0Ab%20%3D%204%0Aab%20%3D%2072%20%20%0Ab%20%2F%206%0Ab%20%2B%201)
The approach here is that a list of unassigned variables is maintained while processing the input lines back to front:
* If the line is an expression, all variables in the expression are added to the list. Actually, in the implementation, all tokens are added to the list, since it saves code and having numbers and operators in the list does not do any harm.
* If the line is an assignment, it tests if the assigned variable name is in the list. If it is, the assignment is accepted, and the variable name removed from the list. Otherwise, the assignment is skipped.
Explanation :
```
L Start with empty list.
qN/ Get input and split at newlines.
W% Reverse to process lines back to front.
{ Start of filter block.
_ Copy line.
'=# Find equal sign.
_ Copy position of equal sign, will use original later to extract
variable name from assignment.
) Increment to produce truthy/falsy value (-1 from find means not found).
{ Start if-block that processes assignments.
(< Slice off everything but variable name.
:V Save in variable V for later re-use.
1$\ Place copy of unassigned variable list and new variable name at
top of stack.
e= Count occurrences. This tells us if variable name was in list.
_ Copy the condition value because it will also be used as the
overall filter result.
{ Start of block that removes variable name from list.
\V Bring list to top, and push variable name.
a- Remove the variable name from list.
\ Swap to get variable list to bottom of stack for next iteration,
and filter result to top.
}& End of conditional block to remove variable name.
} End of if-block for assignment.
{ Start of else-block for expression.
; Pop result of find operation.
S/ Split expression at spaces.
+ Concatenate the new variables with the existing ones in the list.
1 Filter result, expressions are always accepted.
}? End of if for assignment vs. expression.
}, End of filter.
\; Get rid of variable list at bottom of stack.
W% Reverse order of filtered result, since we worked back to front.
N* Join with newlines.
```
[Answer]
# Python 2, ~~270~~ 267 bytes
```
import sys,re
d={}
s=list(enumerate(sys.stdin))
for n,l in s:
try:v,_=l.split('=');v=v.strip();d[v]=d.get(v,[])+[[0,n]]
except:
for v in re.findall('[a-zA-Z_]\w*',l):d[v][-1][0]+=1
print''.join(l for n,l in s if n not in[n for x in d.values()for c,n in x if c==0])
```
Indentation is:
1. Space
2. Tab
Saved 3 bytes thanks to @Kamehameha!
[Answer]
## R 144
```
Q=R=c()
for(L in rev(scan(,"",,,"\n"))){W=strsplit(L," ")[[1]]
if("="%in%W)if(W[1]%in%R)R=R[R!=W[1]]else next else R=c(R,W)
Q=c(L,Q)}write(Q,"")
```
where
* `L` is a line from the input (starting from the last one)
* `W` are the symbols (variables, operators, numbers) in a line
* `R` is a vector of symbols that will be printed. It includes variables whose assignment is needed.
* `Q` is the vector of lines in the output
[Answer]
# JavaScript (ES6) 164 ~~177~~
Using template strings, all newlines are signifcant and counted.
Test running the snippet in **FireFox** (required for ES6 compatibility including arrow functions)
```
f=s=>(k=>{s=s.split`
`,s.map((t,n)=>(r=t.match(/\w+/g)).map(v=>k[v]=f,~t.search`=`?k[s[k[v=r[0]]]=r[0]=0,v]=n:0))
for(v in k)s[k[v]]=0})([])||s.filter(r=>r).join`
`
ungolfed=s=>
{
k={} // list line defining variables, by name, until used
s=s.split`\n`
s.forEach((t,n)=>
{
r=t.match(/\w+/g); // list variables in the line, operators are lost
if (t.search`=` >= 0) // if it's an assignment
{
v=r[0] // new variable
s[k[v]]=r[0]=0 // kill previous definition if not used
k[v]=n
}
r.forEach(v=>k[v]='') // for each used variable, forget its definition line
})
for(v in k)s[k[v]]=0; // kill all remaining unused definitions
return s.filter(r=>r).join`\n`
}
// TEST
out=x=>O.innerHTML+=x+'\n';
;[['a = 10\na * 3', 'a = 10\na * 3']
,['foo = 8\n2 - 1\na = 18','2 - 1']
,['a = 10\na = 8\nb = 4\nab = 72\nb / 6\nb + 1','b = 4\nb / 6\nb + 1']
,['a = 1\na = 2\na + 1','a = 2\na + 1']
,['FooBar1 = 0\nFuz__ = 8\nFuz__ / 1','Fuz__ = 8\nFuz__ / 1']
,['a = 1\na + 1\na = 2\na + 1','a = 1\na + 1\na = 2\na + 1']
,['a = 1\na + a\na = 2', 'a = 1\na + a']
,['a = 1\n1 / 5 * 8 + 4', '1 / 5 * 8 + 4']
,['a = 1\na + a\na = 2', 'a = 1\na + a']
,['a = 1\na + 1\na = 1\na + 1', 'a = 1\na + 1\na = 1\na + 1']
,['a = 7\n5 / a', 'a = 7\n5 / a']
]
.forEach(([i,k])=>(r=f(i),
out('Test '+(r==k?'OK':'Fail')+'\nInput: '+i.replace(/\n/g,',')
+'\nResult: '+r.replace(/\n/g,',')
+'\nCheck: '+k.replace(/\n/g,',')+'\n')
));
```
```
Note: newlines trasformed to commas to save space in output
<pre id=O></pre>
```
[Answer]
# JavaScript ES6, ~~79~~ ~~75~~ 118 bytes
```
s=>s.split`
`.filter((l,i,a)=>(q=l.split`=`)[1]?!~(a.slice(i+1)+0).search(q[0]+'=')&&~s.search(q[0]+'[^=]'):1).join`
`
```
Tell me if this doesn't work for a case. Any ideas for golfing are welcome.
---
## Explanation
```
s=> // Function with argument "s"
s.split` // Splits each line
`
.filter( // Filters through each line,
(item,index,array)=>
(q=l.split`=`)[1]? // If there is something after the equal sign
!~ // XOR (~) will essentially make -1, 0. NOT (!) will make 0, 1, vice-versa
(a.slice(i+1)+0) // Gets following lines
.search`^${z=q[0]}=` // Checks if following lines have the same variable name and then =
&& // AND...
~s.search(z+'[^=]') // Check if there is an expression with the variable
:1) // If there is no equal sign, return 1 (true)
.join` // Join everything back, seperated by newlines
`
```
---
Tested on Safari Nightly. Firefox friendly version:
```
s=>s.split`
`.filter((l,i,a)=>(q=l.split`=`)[1]?!~(a.slice(i+1)+0).search(`^${z=q[0]}=`)&&~s.search(z+'[^=]'):1).join`
`
```
You can drop in in [babeljs](http://babeljs.io/repl) to get an ES5 version.
[Answer]
# Haskell, 187 bytes
Use `d`.
```
import Data.List
f=filter
(!)=map
b((v,e,w):t)=e||or((\(_,p,_)->p)!take 1(f(\(x,_,y)->v==x||v`elem`y)t))
d=unlines.(\l->snd!f fst(zip(b!tails(((\(v:o:w)->(v,o/="=",w)).words)!l))l)).lines
```
]
|
[Question]
[
We've had a few challenges for base conversion, but all of them seem to apply to integer values. Let's do it with real numbers!
# The challenge
Inputs:
* A real **positive number** *x*, expressed in base 10. This can be taken as a double-precision float or as a string. To avoid precision issues, the number can be assumed to be greater than 10−6 and less than 1015.
* A **target base** *b*. This will be an integer from 2 to 36.
* A **number of fractional digits** *n*. This will be an integer from 1 to 20.
Output: the **representation** of *x* in base *b* with *n* fractional digits.
When computing the output expression, the digits beyond the *n*-th should be **truncated** (not rounded). For example, `x = 3.141592653589793` in base `b = 3` is `10.0102110122...`, so for `n = 3` the output would be `10.010` (truncation), not `10.011` (rounding).
For *x* and *b* that produce a finite number of digits in the fractional part, the **equivalent infinite representation** (truncated to *n* digits) is also allowed. For example, `4.5` in decimal can also be represented as `4.49999...`.
Don't worry about **floating point errors**.
# Input and output format
*x* will be given without leading zeros. If *x* happens to be an integer you can assume that it will be given with a zero decimal part (`3.0`), or without decimal part (`3`).
The output is flexible. For example, it can be:
* A string representing the number with a suitable separator (decimal point) between integer and fractional parts. Digits `11`, `12` etc (for *b* beyond 10) can be represented as letters `A`, `B` as usual, or as any other distinct characters (please specify).
* A string for the integer part and another string for the fractional part.
* Two arrays/lists, one for each part, containing numbers from `0` to `35` as digits.
The only restrictions are that the integer and fractional parts **can be told apart** (suitable separator) and use the **same format** (for example, no `[5, 11]` for the list representing the integer part and `['5', 'B']` for the list representing the fractional part).
# Additional rules
* [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Shortest code in bytes wins.
# Test cases
Output is shown as a string with digits `0`, ..., `9`, `A`, ... , `Z`, using `.` as decimal separator.
```
x, b, n -> output(s)
4.5, 10, 5 -> 4.50000 or 4.49999
42, 13, 1 -> 33.0 or 32.C
3.141592653589793, 3, 8 -> 10.01021101
3.141592653589793, 5, 10 -> 3.0323221430
1.234, 16, 12 -> 1.3BE76C8B4395
10.5, 2, 8 -> 1010.10000000 or 1010.01111111
10.5, 3, 8 -> 101.11111111
6.5817645, 20, 10 -> 6.BCE2680000 or 6.BCE267JJJJ
0.367879441171442, 25, 10 -> 0.94N2MGH7G8
12944892982609, 29, 9 -> PPCGROCKS.000000000
```
[Answer]
## JavaScript (ES8), ~~81~~ ~~74~~ 71 bytes
```
f=
(x,b,n,g=x=>x.toString(b))=>g(x-x%1)+'.'+g(x%1).substr(2,n).padEnd(n,0)
```
```
<div oninput=o.textContent=f(+x.value,b.value,n.value)><input id=x><input type=number min=2 max=36 value=10 id=b><input type=number min=1 max=20 value=10 id=n><pre id=o>
```
Works for `x` between `1e-6` and `1e21`, `b` from `2` to `36` (exactly as required) and `n` from `1` to anything from `10` to `48` depending on the base before floating-point errors creep in. Edit: Saved 7 bytes with help from @Birjolaxew. Saved a further 3 bytes with help from @tsh. Previous 74-byte version also worked with negative numbers:
```
f=
(x,b,n,[i,d]=`${x.toString(b)}.`.split`.`)=>i+`.`+d.slice(0,n).padEnd(n,0)
```
```
<div oninput=o.textContent=f(+x.value,b.value,n.value)><input id=x><input type=number min=2 max=36 value=10 id=b><input type=number min=1 max=20 value=10 id=n><pre id=o>
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~153~~ ~~149~~ ~~144~~ ~~137~~ ~~135~~ 109 bytes
```
def f(x,b,m):
i=int(x);s=[];t=[]
while i:s=[i%b]+s;i/=b
while m:m-=1;x=x%1*b;t+=[int(x)]
return s or[0],t
```
Hadn't noticed I can just return the digits as numbers, so that makes it a lot simpler. Returns two lists of digits, first for the integer part, second for the fractional.
[Try it online!](https://tio.run/##dU7LboMwELzzFb5U2IG62JiHjZwfiXKAJiiugomMq1JF@Xa6pkQ9VfKuNbM7s3P79pfR8mU5nXvU4znt0oGoCBltrMczaSZ9ODYeWoS@LuZ6RkYBZV66YzI15k13T35Qw6tmzaznF7brGp/A1moBSnf2n86iCY3ukB1Tv7T62g7dqUVWvV8ctomoE2z3mmVkV5HIbePdrGIa04/RWBxv/9DecJtOhPSjA0dj0UyikN6v6W1If3NwOr7Pas@Kx71Te@g2dIUQurtHTEE8tKDQoNGg0jZ12uFdv5kQEkUeC1qkiGUpKkhAHEAOFUBOmWCF5GWRF7WsJPDw6n9Gq02YMcpzAaCE4iuRhRt8k/6ip1FJi5pVpQgL2dMho3lZ1ZUUgrGKiRCK/9lz4GvJZc3LTMIESpLlBw "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), 25 bytes
```
->\x,\b,\n{+x .base(b,n)}
```
[Try it](https://tio.run/##fVBda9tAEHy/X7GEppEaeXO79yFdQlOwCA4tbUP7GIViuwoYbMlYSXBJ88v61j/mrmyJljh04O643ZmduVuWq7nf3DclPHicnqnFD3g9GTflYFpXD@WqmdUVvN0Mzot1UkySono8XgO2hGiSVPHTZnl/B0eX5Xxeg0ir8aKEWQNHCTwfYpg8GXTOEjujXeZMAkYnkJ4pJVOiGNZrYLnc1iuYz6qyieLfv3BaLybRCRTfj@G6wPa8eQcnMS7Gy1N4c60R@QYeFQiWq1l1dwsHh6wbgEPebaeyN0V1kMDPV9/2ckVtFWL1tLHoEiAJ5OA5BucA0tYCkHAWbRAoyyKQVxC8qDAGt3TDmCuDZMkF9s64LKShfXwCWc8ljZo0E2l6ibpN1o9FbdgwkzVaEbKx0vSyeD8CoRlepD7PhtYEp8RFJnHnu8@WCEh6hzb5tqBph05t/q/uyR5dRqm3rZ/u0v9D9jjML9hnvVN3T98LlEbj0ywN1hKlZNtv5u4HWq3GYD/xx9FlOsoUsdCywCFjr4MQZYW/PldX@ejL5/zDV9Q9/gA "Perl 6 – Try It Online")
## Expanded:
```
-> \x, \b, \n {
+x # make sure it is a Numeric
.base( b, n ) # do the base conversion
}
```
Note that the space is so that it is parsed as `(+x).base(b,n)`
not `+( x.base(b,n) )`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 45 bytes
```
->x,b,n{(x*b**n).round.to_s(b).insert(~n,?.)}
```
### Why?
Since b^n in base b is 10^n, we multiply x by that number, and then add the decimal point where it belongs.
[Try it online!](https://tio.run/##dU/LCsIwELz7FT22JS7J5n1QP6QEaX2AB6NUCxUfv1431eJJ2IGdmc1kt@2a27BfDPNlzxoW73lfNmUZC2hPXdzC9bS@5E0Bh3jZtdf8FdkKiudQVQo0ywRnmQ5sVikkIgmJSBBKaI9GS@289aRTuT/WGJM8ASgVEUPAUeDpD/w@/bApyIB2whqVBviUwEEa66xXSggrVFoKf/FIuvPoHRruySH4EOBYn@@Pmm7fPM5ZNTYs23@aEJ7DGw "Ruby – Try It Online")
[Answer]
# Mathematica, 158 bytes
since this challenge allready got a very nice answer in mathematica by @KellyLowder, I tried to produce (with a different approach) **the exact results as shown in the test cases**
```
ToUpperCase[""<>Insert[StringReplace[ToString@BaseForm[#,p]&/@PadRight[#&@@(d=RealDigits[#,p=#2]),w=(#3+d[[2]])][[;;w]],"\n "<>ToString@p->""],".",d[[2]]+1]]&
```
**input**
>
> [12944892982609, 29, 9]
>
>
>
**output**
>
> PPCGROCKS.000000000
>
>
>
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~157~~ 152 bytes
Needs 64 bits `long int` for this to work with larger test cases.
*-5 bytes thanks to Peter Cordes*
```
#define P r=99;i=l=x;do{z[--r]=48+7*(l%b>9)+l%b;}while(l/=b);printf(z+r)
long i,r,l;char z[99];f(x,b,n)double x;{P;putchar(46);while(n--){x=(x-i)*b;P;}}
```
[Try it online!](https://tio.run/##jY/LboMwEEX3fIWVqpIdBopfgGXRb8g@ySK8EkvURFbSoiC@nTpptyXd2PLonDvXVXSsqnl@qZvW2AZtkCuU0qboikHX/XjbRpHbFyIPszXuXst3RUJ/6enrZLoGd29FSfTZGXtp8S10JOh6e0SPw4CDTleng0O3rVJ73eIBSrCk7q9l16BBjxt9vl7uBBYp0T@RNorIOBR4iAxZl3qjp2n28ejjYCz@7E1N0Bgg1GIRS6AJSKL987fCauf1aGdXj6FnWAyUA11ieEwFlYqlEjjk/yO5zFWmONwbLBk0ZlwATYGyRSzxf2HLyx/Mk4JpLHOapUICYgmg5W5JzNMsz5QQlGZUCOYl@UyizPO5YipnaaJiryhA6m/DNZersyjRwRTM3w "C (gcc) – Try It Online")
edit: a few bytes can be shaved if it's allowed to output two strings separated by a newline separator:
## 149 bytes:
```
#define P r=99;i=l=x;do{z[--r]=48+7*(l%b>9)+l%b;}while(l/=b);printf(z+r)
long i,r,l;char z[99];f(x,b,n)double x;{P;puts("");while(n--){x=(x-i)*b;P;}}
```
edit: this submission is not the longest one, yay!
[Answer]
## Mathematica 47 Bytes
```
TakeDrop@@r[#,#2,#3+Last@(r=RealDigits)[#,#2]]&
```
Calling `RealDigits` twice to first figure out the number of digits to the left of the decimal.
[Answer]
# [SageMath](http://www.sagemath.org/), 68 bytes
```
def f(n,b,k):y=n.str(b).split('.')+[''];return y[0],(y[1]+'0'*k)[:k]
```
[Try it online!](https://sagecell.sagemath.org/?z=eJwNw0EKgCAQAMB70B-87W6JmES0RS8RL1FCGBJqB39fA3OcXniMcpeBlrpFlUvCnVR-7qsgKKDeArg1neVNUVSrncRqB9eDhi6QXYJrm7Z50hULehwMj-PMhmczaZbC_JnoAydMG-g=&lang=sage)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
*×⁵b⁸ḞðṖḣ⁹,ṫø⁹N‘
```
[Try it online!](https://tio.run/##AToAxf9qZWxsef//KsOX4oG1YuKBuOG4nsOw4bmW4bij4oG5LOG5q8O44oG5TuKAmP///zE2/zEy/zEuMjM0 "Jelly – Try It Online")
Note that singletons are printed as the element in the output.
[Answer]
# [Haskell](https://www.haskell.org/), 188 bytes
```
f=fromIntegral
g 0 _=[]
g n p=g(div n p)p++[mod n p]
z=(!!)(['0'..'9']++['A'..'Z']++['.'])
h x p l|(i,d)<-properFraction x=z<$>(g i p++[36]++(last$g(floor$d*(f p**f l))p:[0<$[1..l]|d==0]))
```
[Try it online!](https://tio.run/##TVFta9swEP48/4qrCViKXaE3v4W4sIQuG1u3sn6bZ4apnRemxMJxN1P637NznYYdOvTonudOJ922PP6ujTmd1tm6bfafDl29aUvjbIDDrywvEBzAZhtS7f4MiFrfz/dNNeDCec7I1RUlucc9xrzUK5D03g/4x4iZV1BnCz1YMC9kF1R0fm3bxtbth7Z87HbNAfrseT65IRvYwVBbRZhITHnsJhuyNk3TTqopWYOdTtdgKLWznM8nuWDMFC9VlvGC0lPdl3tr6iNkkBPNwgAEDwA3Fw8czaUBEC0xrtAxrhQbg4oJLcJURqEKkzRO1WvekO6iREklpdBq1AomlUYyQsdarmBqcRtHy2ShVRqOEj7cjmQy8ByPgo/2H60uNBNne2UjFiYijvRQgZ@biNhieSuj5FKCMxXFSZxqLUQs9PAo@dYxZ6n@Ku9WH@NVMt4nUZekMk1kxFNUouNy7@@Xq@/flp8fGOeX/grH2Ze7A35i1Tjv9qW9A/KT9IENTFDT6xuwT91D1345wATcurf1Y1dXM3B9v/Z9NwAc6FNpZi74PpDjtvmLuvPsKYW3GZ3@AQ "Haskell – Try It Online")
`g` converts a number to a list representing that number in a given base
`z` maps integers to letters (`36 = .`)
`h` applies the previous functions to the integer and fractional part of a number.
[Answer]
# Axiom, 566 bytes
```
c:=alphanumeric()::List Character
f(a:INT,b:PI):List Character==(r:=[];repeat(y:=a rem b;r:=cons(c.(y+1),r);a:=a quo b;a=0=>break);r)
g(x)==floor(x)::INT
F(x)==>for i in 1..#x repeat z:=concat(z,x.i)
w(a:Float,b:PI,n:NNI):String==
z:="";b<2 or b>36 or a<0=>z
ip:=g(a); fp:=g((a-ip)*b^n)
ipb:=f(ip,b);fpb:=f(fp,b);cnt:=n-#fpb
for i in 1..cnt repeat fpb:=cons(c.1,fpb)
F(ipb);z:=concat(z,".");F(fpb)
z
h(a,b,n)==>(n>=0 and b>0=>(nd123:=10+g(n*log_2(b)/log_2(10));mxv123456:=digits(nd123::PI);res78484:=w(a,b,n);digits(mxv123456);res78484);"")
```
it was particular difficult this question; afther some time in write something, the right results it seems
generate using one macro for preserve digits()... it is not golfed too much...results:
```
(7) -> h(4.5,10,5)
(7) "4.50000"
Type: String
(8) -> h(42,13,1)
(8) "33.0"
Type: String
(9) -> h(%pi,3,8)
(9) "10.01021101"
Type: String
(10) -> h(%pi,5,10)
(10) "3.0323221430"
Type: String
(11) -> h(1.234,16,12)
(11) "1.3BE76C8B4395"
Type: String
(12) -> h(0.367879441171442,25,10)
(12) "0.94N2MGH7G8"
Type: String
(13) -> h(12944892982609,29,9)
(13) "PPCGROCKS.000000000"
Type: String
(14) -> h(6.5817645,20,10)
(14) "6.BCE267JJJJ"
Type: String
```
the real target is one function that convert to base 2..36 each Float
[that has k:=digits()] or each calculated number as %pi or %e or the division of
two float/int as in 1./3. ['oo' digits]
```
(15) -> h(%pi,13,800)
(15)
"3.1AC1049052A2C77369C0BB89CC9883278298358B370160306133CA5ACBA57614B65B410020
C22B4C71457A955A5155B04A6CB6CC2C494843A8BBBBA9A039B77B34CB0C036CAC761129B3168
B8BAB860134C419787C911812985646C7AAA3025BAA118B3AB8265CB347852065667291482145
6C533447BC53A5262177C9985455C395626091A2CC3126B395C91B65B654A1804226197528410
29A8A4A55CC7937B347B77B5A914127B11C6A57A84510775A9A467819A468B6B74339CC1290B2
24921C6A771BC2AB6AB41735119C2231545A86399483119AAA5AC34B46B7B5C9089946A364860
9B26CB0BAC0ABCBA182C12881933AA93C3942C71AA664753989A3C82166BA2109796C4A134607
59725A72C9117AC980556A147557C319438287226C94725B125753B009387A48AA45CB1960A04
A064052C00A6069371949872B14590895C555CB01A39B7589824B8621618A8B1971841201A2AB
B04B80C7534CC1CB079581491995B46C679555316288C82665645A1A600C1A669B865651B6B842470C018B03C1115B3C4306C015C0B45C"
Type: String
```
[Answer]
# Axiom, 127 bytes
```
g(a)==floor(a)::INT;f(a:Float,b:PI,n:NNI):Any==(b<2 or n>28=>%i;x:=g(a);radix(x,b)+radix(g((a-x)*b^n),b)::RadixExpansion b/b^n)
```
results
```
(4) -> f(%e,2,10)
(4) 10.1011011111
Type: RadixExpansion 2
(5) -> f(%e,3,10)
(5) 2.2011011212
Type: RadixExpansion 3
(6) -> f(%e,35,10)
(6) 2.P4VBNEB51S
Type: RadixExpansion 35
(7) -> f(1.4,35,10)
(7) 1.DYYYYYYYYY
Type: RadixExpansion 35
(8) -> f(%pi,3,8)
(8) 10.01021101
Type: RadixExpansion 3
(9) -> f(%pi,5,10)
(9) 3.032322143
Type: RadixExpansion 5
(10) -> f(1.234,16,12)
(10) 1.3BE76C8B4395
Type: RadixExpansion 16
```
It has a little problem for final zero example
```
f(4.5,10,5)
```
Would return '4.5' and not '4.50000'
]
|
[Question]
[
The 80's TV series [*Knight Rider*](https://en.wikipedia.org/wiki/Knight_Rider_(1982_TV_series)) featured an intelligent, self-aware car called KITT. One distinctive aspect of the car was a front-mounted scanner bar that allowed KITT to "see" (and that looked [suspiciously](https://en.wikipedia.org/wiki/KITT#Features) familiar to fans of another, earlier [TV series](https://en.wikipedia.org/wiki/Battlestar_Galactica_(1978_TV_series))).
The scanner had eight lights as seen in this picture:
[](https://i.stack.imgur.com/kJAA1.png)
The lights "moved" as shown in [this animated image](https://thumbs.gfycat.com/AdorableSlightBarnswallow-mobile.mp4).
Your task, as you have guessed by now, it to recreate the scanner bar with the moving lights in ASCII art.
# The challenge
Given an integer `t`, output the state of the scanner bar at that instant, defined as follows:
* The scanner consists of eight lights.
* At any instant one of the lights is *active*, and is shown as `#`. The lights that were active at times `t-1` and `t-2` are now *dimmed*, and are shown as `+`; unless they coincide with the current active one. The rest of the lights are *off*, and are shown as `-`.
* The active light moves left to right, then right to left.
The exact output for each `t` is detailed below.
```
0 --> #++----- % The leftmost light is active, and it just came from the right.
% The two neighbouring lights are dimmed
1 --> +#------ % The active light has bounced to the right, and it is covering
% one of the two lights that should be dimmed. So there is only
% one dimmed light
2 --> ++#----- % The active light has moved one more step to the right, and the
% two trailing dimmed lights are visible
3 --> -++#----
7 --> -----++#
8 --> ------#+ % The active light has bounced to the left
9 --> -----#++
10 --> ----#++-
13 --> -#++----
14 --> #++----- % Same as 0
15 --> +#------ % Same as 1
```
For negative values of `t` the cycle is simply extended:
```
-1 --> -#++---- % Same as 13
-2 --> --#++--- % Same as 12
```
#Additional rules
You can write a program or function.
Output can contain trailing whitespace and a leading newline.
Shortest code in bytes wins.
[Answer]
## JavaScript (ES6), ~~65~~ 67 bytes
**EDIT** - Fixed for negative values. Now supporting `N >= -8,000,000,000`, which should provide a fairly good extended operating time in AUTO CRUISE mode. :-)
```
let f =
n=>[..."------#++-----".substr((n+=8e9)%7,8)].sort(_=>n/7&1).join``
// testing 28 frames
for(var i = -14; i < 14; i++) {
console.log(f(i));
}
```
### Animated version
```
let f =
n=>[..."------#++-----".substr((n+=8e9)%7,8)].sort(_=>n/7&1).join``
let n = 0;
setInterval(function() { document.getElementById("o").innerHTML = f(n++) }, 90);
```
```
<pre id="o"></pre>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-6 bytes thanks to the help of @Dennis! (upend first, then concatenate)
```
”-ẋ6;“#++”ṙ7Ḷ’¤Ḋ€U;$⁸ị
```
[TryItOnline](http://jelly.tryitonline.net/#code=4oCdLeG6izY74oCcIysr4oCd4bmZN-G4tuKAmcKk4biK4oKsVTsk4oG44buL&input=&args=MA)
Or perform four oscillations with a bonus **[easter egg!!](http://jelly.tryitonline.net/#code=4oCdLeG6izY74oCcIysr4oCd4bmZN-G4tuKAmcKk4biK4oKsVTsk4oG44buLCjU24bi2w4figqzFvOKAnEcn4bq44bmaS-G4g-KBveG6ueG4peG6klDGpcOwcOG6oeKBt8aRRcOeRjpYxoHCv1U2wqXhuZnigbzhua3CpjLhuKPhuo7hupNOyK4xyZPhuIvhuqBL4bma4bukPzLEscat4bukwrDCocOH4bukUeG4jF3hu41U4bmg4bmAyqDDnuG5gzQqyaDCszMp4oG-xJbDt8i34bif4oG04oG-yZfhuZfCpsak4bqh4bqHa-G5h-G5m04zRMW8aOG6hmY84bu0cEkjwrPDplg54oG4xKHigbfhuo45ZcOHxorCqeKBuX7Jl8qCyLdExp3Dl8K_4buLxJZFw4bIrsmyxp1j4bmGxodva2FEITh4bMK74biywqRH&input=)**
### How?
```
”-ẋ6;“#++”ṙ7Ḷ’¤Ḋ€U;$⁸ị - Main link: n
”- “#++” - strings "-" and "#++"
ẋ6 - repeat six times: "------"
; - concatenate: "------#++"
¤ - nilad followed by atoms as a nilad (ie make a constant)
7Ḷ’ - range(7) decremented: [-1,0,1,2,3,4,5]
ṙ - rotate left by (makes)-----------> ["+------#+",
Ḋ€ - Dequeue each "------#++",
$ - last two atoms as a monad "-----#++-",
U - reverse (vectorises) "----#++--",
; - concatenate "---#++---",
⁸ - left argument (n) "--#++----",
ị - index into (1 based and modular) "-#++-----"])
```
[Answer]
## JavaScript (ES6), ~~90~~ 87 bytes
```
n=>"01234567".replace(/./g,i=>"-+##"[g=n=>!((+i+n)%14&&(n-i)%14),g(n)*2|g(n-1)|g(n-2)])
```
"-+##" is indexed by a bitmask, where bit 1 signifies an active light and bit 0 signifies a dimmed light. Active/dimmedness is now calculated by adding and subtracting the current position from the desired position and seeing if either result is divisible by 14.
[Answer]
## Python, 53 bytes
```
lambda n:('-'*5+'++#'+'-'*6)[-n%7:][:8][::-n/7%2*2-1]
```
Creates the string `-----++#------`, takes a length-8 window depending on the input modulo 7, reverses for inputs modulo 14 that lie between 1 and 7 .
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 51+3 = 54 bytes
```
<v{"------#++"%7&(7%*27:-1
}>:?!\1-$
{~&?r\~
l?!;o>
```
Input is expected on the stack at program start, so +3 bytes for the `-v` flag.
[Try it online!](http://fish.tryitonline.net/#code=PHZ7Ii0tLS0tLSMrKyIlNyYoNyUqMjc6LTEKfT46PyFcMS0kCnt-Jj9yXH4KbD8hO28-&input=&args=LXYgNQ)
[Answer]
# MATL, ~~34~~ ~~30~~ 27 bytes
```
'++#-'I:7XyY+4LZ)t2&P&viY))
```
*7 bytes saved thanks to @Luis*
[**Try it Online!**](http://matl.tryitonline.net/#code=JysrIy0nSTo3WHlZKzRMWil0MiZQJnZpWSkp&input=MA)
[Another example with the first 25 steps](http://matl.tryitonline.net/#code=OnEiJysrIy0nSTo3WHlZKzRMWil0MiZQJnZAWSkp&input=MjU)
**Explanation**
```
'++#-' % Push the string literal to the stack
I: % Create the array [1 2 3]
7Xy % Create a 7 x 7 identity matrix
Y+ % Perform 2D convolution between the vector and this matrix
4LZ) % Grab all but the first column. Yields the following matrix
%
% 2 3 0 0 0 0 0 0
% 1 2 3 0 0 0 0 0
% 0 1 2 3 0 0 0 0
% 0 0 1 2 3 0 0 0
% 0 0 0 1 2 3 0 0
% 0 0 0 0 1 2 3 0
% 0 0 0 0 0 1 2 3
%
t2&P&v % Copy this matrix, flip it horizontally and vertically concatenate
% it with itself.
i % Explicitly grab the input (n)
Y) % Get the n-th row of the above matrix (and use modular indexing)
) % Index into the initial string literal to replace 2 with #, 1 and 3 with +
% and all 0's with -
% Implicitly display the result
```
[Answer]
# Pyth, ~~33~~ 28 bytes
Saved 5 bytes by calculating all the lights the same way.
```
X:*8\-@LJ+U7_S7,-Q2tQ\+@JQ\#
```
Starts with the lights all off and turns them on one at a time.
[Try it out online!](http://pyth.herokuapp.com/?code=X%3A%2a8%5C-%40LJ%2BU7_S7%2C-Q2tQ%5C%2B%40JQ%5C%23&input=0&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A-1%0A-2%0A-3%0A-4%0A-5&debug=0)
[Answer]
## JavaScript, 204 bytes
```
function g(i){var a=(i%16+16)%16
if(!a)return g(2)
if(1==a%14)return(g(2)+'-').substr(1)
if((1<a)&&(a<8))return Array(a-1).join('-')+'++#'+Array(8-a).join('-')
return g(a-7).split("").reverse().join("")}
```
**Test**
```
function g(i){var a=(i%16+16)%16
if(!a)return g(2)
if(1==a%14)return(g(2)+'-').substr(1)
if((1<a)&&(a<8))return Array(a-1).join('-')+'++#'+Array(8-a).join('-')
return g(a-7).split("").reverse().join("")}
for (var i = 0; i < 16; ++i) {
console.log(i + '-->' + g(i));
}
```
[Answer]
# JavaScript (ES6), 72
```
t=>`------${(t=(13+t%14)%14)>6?'#++':'++#'}------`.substr(t>6?t%7:7-t,8)
```
*Less golfed*
```
t=>(
pad = '------',
t = (13+(t%14))%14,
u = t % 7,
t > 6 ? (pad + '#++' + pad).substr(u, 8)
: (pad + '++#' + pad).substr(7 - u, 8)
)
```
**Test**
```
f=
t=>`------${(t=(13+t%14)%14)>6?'#++':'++#'}------`.substr(t>6?t%7:7-t,8)
T=_=>(
O.textContent=f(++N.textContent),
setTimeout(T, 150)
)
T()
```
```
<input id=I type=number value=0 oninput='N.textContent=this.value'>
<pre id=N>-100</pre>
<pre id=O></pre>
```
[Answer]
# [Vim](https://www.vim.org), 95 bytes
```
D7i-<esc>7a_<esc>@=(<C-r>"%14+13)%14+1
|r#8|i
<esc>:v/#/d
:s/.#/+#
f#i+<esc>:s/\v^(_*)(\+*)#(_*)$/\3#\2\1
:s/_/-/g
```
[Try it online!](https://tio.run/##K/v/38U8U9cmtTjZzjwxHkw72GrYOOsW2SmpGppoGxprgimumiJli5pMLrAKqzJ9Zf0ULqtifT1lfW1lrjTlTG2IRLF@TFmcRryWpkaMtpamMoiloh9jrBxjFGMIUh@vr6ufzvX/v67Rf90yAA "V (vim) – Try It Online")
## Explanation
There might be a better way to do this...
```
D
```
Delete the input number into the `"` register.
```
7i-<esc>7a_<esc>
```
Insert the string `-------_______`.
```
@=...
|
```
Go to the character with the 1-based index given by this expression...
```
<C-r>"%14
```
The previously deleted number, mod 14. Unfortunately, Vim's mod operator gives negative results if the left-hand side was negative, so we have to correct for that...
```
(...+13)%14+1
```
... by adding 14 and taking the result mod 14. But at the same time, we can subtract 1, mod 14, and add 1 to give the 1-based mod (same as the regular mod, except it gives 14 instead of 0).
```
r#
```
Replace the character at that index (`-` or `_`) with `#`.
```
8|i
<esc>
```
Go to index 8 and insert a newline, putting the `-`s and the `_`s each on their own line.
```
:v/#/d
```
Whichever line doesn't contain the `#`, delete it.
```
:s/.#/+#
```
If there's a character before the `#`, replace it with `+`.
```
f#i+<esc>
```
Go to the `#` and insert another `+` before it.
```
:s/\v^(_*)(\+*)#(_*)$/\3#\2\1
```
If the line has `_` instead of `-`, reverse it.
```
:s/_/-/g
```
Replace `_` with `-`.
[Answer]
# Perl, 65 bytes
Includes +1 for `-n`
Run with the number on STDIN:
```
for i in 0 `seq 14`; do perl -M5.010 kitt.pl <<< $i; done
```
`kitt.pl`:
```
#!/usr/bin/perl -n
$_="311e".--$_%14+4e16|0;s/.(.{8})/$&|reverse/e;y/013/-+#/;say//
```
Not very competitive but deserves a post for the strange method
[Answer]
# Perl, ~~56~~ 55 bytes
Includes +3 for `-p`
Run with the number on STDIN:
```
for i in 0 `seq 14`; do kitt.pl <<< $i; echo; done
```
`kitt.pl`:
```
#!/usr/bin/perl -p
$_=eval'1x8
|1x(7-abs$_--%14-7).++$^F#'x3;y;1537;-+#
```
Put this in a file ***without*** the final newline (add a final `;` to the program if you don't want to bother with that). Unfortunately using a literal `^F` doesn't work
This program contains 2 comment characters (ignore the `#!` line). One of them really is a comment and actually ***gains*** a byte....
Implements the actual afterglow algorithm
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 23 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
±7%╵-8×#++1╋8m⁸╷³╵%7<?↔
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JUIxJXVGRjE3JXVGRjA1JXUyNTc1LSV1RkYxOCVENyUyMysrJXVGRjExJXUyNTRCJXVGRjE4JXVGRjREJXUyMDc4JXUyNTc3JUIzJXUyNTc1JXVGRjA1JXVGRjE3JXVGRjFDJXVGRjFGJXUyMTk0,i=LTI_,v=6)
]
|
[Question]
[
Did you know that a small number can *borrow* bits from a larger number? Here's an example. Let's say our two numbers 5 and 14. First, write them out in binary:
```
5 14
000101 001110
```
First we take the smallest *on* bit away from the larger number, and we give it to the smallest *off* bit on the other number. So
```
This bit turns off
|
v
000101 001110
^
|
This bit turns on
```
Now we have
```
000111 001100
```
and our numbers are 7 and 12. The first number is still smaller, so we continue.
```
000111 001100
001111 001000
```
Now we have 15 and 8, so we can stop. We'll call this set of operations "bit-borrowing" two numbers. Let's do another example. 20 and 61.
```
20 61
010100 111101
010101 111100
010111 111000
111111 100000
63 32
```
So our end result is 32, 63. Let's do *one* more. 31, and 12. 31 is already bigger than 12, so there's nothing to do! Bit-borrowing 31 and 12 gives 31 and 12, no change.
# The challenge
Your challenge is to write a program or function that takes two numbers and bit-borrows them. The two numbers will always positive integers. Your input and output can be in any reasonable format.
# Test IO:
```
Input: 2, 3
Output: 3, 2
Input: 3, 2
Output: 3, 2
Input: 8, 23
Output: 31, 0
Input: 42, 81
Output: 63, 0
Input: 38, 41
Output: 47, 32
Input: 16, 73
Output: 23, 0
Input: 17, 17
Output: 17, 17
```
Standard loopholes apply, and shortest answer in bytes wins!
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
~1¦&N$^µ</¿
```
[Try it online!](http://jelly.tryitonline.net/#code=fjHCpiZOJF7CtTwvwr8&input=&args=MjAsIDYx) or [verify all test cases](http://jelly.tryitonline.net/#code=fjHCpiZOJF7CtTwvwr8Kw4figqxH&input=&args=KDIsMyksICgzLDIpLCAoOCwyMyksICg0Miw4MSksICgzOCw0MSksICgxNiw3MyksICgxNywxNyk).
### Background
We can extract the last set bit of an integer **n** as follows.
**n + 1** toggles all trailing set bits of **n** and the adjacent unset bit. For example, **100112 + 1 = 101002**.
Since **~n = -(n + 1) = -n - 1**, **-n = ~n + 1**, so **-n** applies the above to the bitwise NOT of **n** (which toggles *all* bits), thus toggling all bits before the last **1**.
For example, **-101002 = ~101002 + 1 = 010112 + 1 = 011002**.
By taking **n & -n** the bitwise AND of **n** and **-n** all bits before the last set bit are nullified (since unequal in **n** and **-n**), thus yielding the last set bit of **n**.
For example, **101002 & -101002 = 101002 & 011002 = 001002**.
Thus XORing **n** with **n & -n** unsets the last set bit of **n**.
Conversely, to unset the last set bit of **n**, it suffices to apply the above to **~n**, from where we derive the formula **n ^ (~n & -~n)**.
### How it works
```
~1¦&N$^µ</¿ Main link. Argument: A (list of pairs)
¿ While loop:
</ Condition: Reduce p by less-than. True iff x < y.
µ Body chain:
~1¦ Apply bitwise NOT to the x, first item of the pair.
$ Convert the two links to the left into a monadic chain.
N Negate; multiply [~x, y] by -1, yielding [-~x, -y].
& Logical AND. Yields [-~x & ~x, -y & y].
^ Vectorized XOR with p. Yields [(-~x & ~x) ^ x, (-y & y) ^ y].
```
[Answer]
# J, ~~31~~ 26 bytes
```
,`(($:~(OR>:))~(AND<:))@.<
```
Straight-forward approach using recursion and bitwise tricks. In order to turn off (set to **0**) the right-most on (**1**) bit for a value *n*, you can perform bitwise-and between *n* and *n*-1, and to turn on (set to **1**) the right-most off (**0**) bit for a value *n*, you can perform bitwise-or between *n* and *n*+1.
## Usage
The input consists of two integers, one applied on the LHS and the other on the RHS, and the output is a list of the bit-borrowed values.
```
f =: ,`(($:~(OR>:))~(AND<:))@.<
2 f 3
3 2
3 f 2
3 2
8 f 23
31 0
42 f 81
63 0
38 f 41
47 32
16 f 73
23 0
17 f 17
17 17
```
## Explanation
```
,`(($:~(OR>:))~(AND<:))@.< Input: x on LHS, y on RHS
If x < y,
, Form a 2-element array [x, y] and return
Else
<: Decrement y
AND Perform bitwise-and on y and y-1, call it y'
>: Increment x
OR Perform bitwise-or on x and x+1, call it x'
$: Call recursively on x' and y' and return
```
[Answer]
# Python, 42 bytes
```
f=lambda x,y:x<y and f(x|x+1,y&y-1)or(x,y)
```
*Thanks to @jimmy23013 for golfing off 4 bytes!* *Thanks to @LeakyNun for golfing off 2 bytes!*
Test it on [Ideone](http://ideone.com/tkt7Un).
[Answer]
# Mathematica, 46 bytes
```
If[#<#2,BitOr[#,#+1]~#0~BitAnd[#2,#2-1],{##}]&
```
Same method as used in my [solution](https://codegolf.stackexchange.com/a/83113/6710) in J.
Thanks to @[Martin](https://codegolf.stackexchange.com/users/8478/martin-ender) for saving 1 byte and reminding me of infix application `~`.
## Usage
The input consists of two integer arguments and the output is a list with the bit-borrowed values.

[Answer]
# Pyth, ~~29~~ ~~27~~ ~~25~~ ~~22~~ ~~21~~ ~~20~~ ~~19~~ ~~18~~ 16 bytes
```
~~MxG^2x\_+\0.BG`HCm.W<FHgVZU2dC~~
~~MxG^2x\_+0jG2HCm.W<FHgVZU2dC~~
~~Cm.W<FH.bxN^2x\_+0jN2YZ2dC~~
~~m.W<FH.bxN^2x\_+0jN2YZ2~~ <-- changed input/output format
~~m.W<FH.exb^2x\_+0jb2kZ~~
~~m.W<FH.U,.|bhb.&ZtZZ~~
~~.W<FH.U,.|bhb.&ZtZZ~~ <-- changed input/output format
~~.W<FH.U,.|bhb.&ZtZ~~
.W<FH.U,.|bhb.&t
```
[Test suite.](http://pyth.herokuapp.com/?code=.W%3CFH.U%2C.%7Cbhb.%26t&test_suite=1&test_suite_input=%5B2%2C3%5D%0A%5B3%2C2%5D%0A%5B8%2C23%5D%0A%5B42%2C81%5D%0A%5B38%2C41%5D%0A%5B16%2C73%5D%0A%5B17%2C17%5D&debug=0)
[Answer]
## 05AB1E, ~~16~~ 15 bytes
```
[D`›#`D<&sD>~s‚
```
[Try it online](http://05ab1e.tryitonline.net/#code=W0Rg4oC6I2BEPCZzRD5-c-KAmg&input=WzM4LDQxXQ)
[Answer]
## [Labyrinth](https://github.com/m-ender/labyrinth), ~~37~~ 34 bytes
```
?"
}
|=:{:
) }
: :;-{
=&( {!;\!@
```
[Try it online!](http://labyrinth.tryitonline.net/#code=PyIKfQp8PTp7OgopICAgfQo6IDo7LXsKPSYoIHshO1whQA&input=MzggNDE)
### Explanation
Quick Labyrinth primer:
* Labyrinth operates on two stacks of arbitrary-precision integers, *main* and *auxiliary*, which are initially filled with an (implicit) infinite amount of zeros.
* The source code resembles a maze, where the instruction pointer (IP) follows corridors. All interesting control flow happens at junctions: when the IP has more than one cell to go to, the top of the main stack is inspected. If the value is negative, the IP turns left, if it's positive, the IP turns right, and otherwise it moves straight ahead. If the chosen direction is blocked by a wall (i.e. a space), the IP moves in the opposite direction instead.
The program uses the same algorithm as the other answers: we replace `(a, b)` with `(a | a+1, b & b-1)` as long as `a < b`. I'll add a full explanation after I've tried golfing it some more.
The IP starts in the top left corner, going right. `?` reads an integer `a`. Then `"` is a no-op, but it's necessary to prevent the IP from moving down immediately. This is also a dead end, so the IP turns around and executes `?` again to read `b`. `}` then moves `b` from *main* to *aux*, so now we've got:
```
Main [ ... 0 a | b 0 ...] Aux
```
The `|` then does nothing, because it takes the bitwise OR of `a` and `0`. Since we know `a` is always positive, the IP turns east (because it can't turn west). This begins the main loop of the program. We start with a short linear section in order to compare `a` and `b`:
```
= Swap tops of stacks, i.e. swap a and b.
: Duplicate b.
{ Pull a over to main.
: Duplicate a.
} Push one copy back to aux.
- Compute b-a.
```
The IP is now at another junction. First, let's consider the case where the result is positive. That means `b > a` and we need to perform one more iteration. That iteration is also completely linear. Note that the stacks are currently:
```
Main [ ... 0 b (b-a) | a 0 ...] Aux
; Discard b-a.
: Duplicate b.
( Decrement.
& Bitwise AND with b, clearing the least-significant 1.
= Swap new b with old a.
: Duplicate a.
) Increment.
| Bitwise OR with a, setting the least-significant 0.
```
And then we're back to the start of the loop (since `a` is again positive, the IP turns east again).
If at some point `b-a` is no longer positive, the IP will take one of the other two paths. Note that in both cases we fetch `a` with `{`, then hit a corner where the IP follows the bend and then print `a` with `!`. Now the top of the stack is again `b-a` which means that in both cases the IP will end up moving east. All that's left is a short linear bit now:
```
; Discard b-a.
\ Print a linefeed.
! Print b.
@ Terminate the program.
```
[Answer]
# Java 7, 73 bytes
```
void d(int x,int y){while(x<y){x|=x+1;y&=y-1;}System.out.print(x+","+y);}
```
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/sUg3Vi)
```
public class Main{
static void d(int x, int y){
while(x < y){
x |= x + 1;
y &= y - 1;
}
System.out.print(x + "," + y);
}
public static void main(String[] a){
print(2, 3);
print(3, 2);
print(8, 23);
print(42, 81);
print(38, 41);
print(16, 73);
print(17, 17);
}
public static void print(int a, int b){
d(a, b);
System.out.println();
}
}
```
**Output:**
```
3,2
3,2
31,0
63,0
47,32
23,0
17,17
```
---
**Old challenge rules [~~126~~ ~~125~~ 123 bytes]:**
*NOTE: The old challenge rules used two integer-arrays as input, instead of two loose integers.*
```
void d(int[]a,int[]b){int i=-1,x,y;while(++i<a.length){x=a[i];y=b[i];for(;x<y;x|=x+1,y&=y-1);System.out.println(x+","+y);}}
```
[Answer]
## JavaScript (ES6), 33 bytes
```
f=(n,m)=>n<m?f(n|n+1,m&m-1):[n,m]
```
Simple port of the answers by @miles.
[Answer]
# Julia, 27 bytes
```
x<|y=x<y?x|-~x<|y&~-y:[x,y]
```
[Try it online!](http://julia.tryitonline.net/#code=eDx8eT14PHk_eHwtfng8fHkmfi15Olt4LHldCgpmb3IgKHgseSkgaW4gKCAoMiwzKSwgKDMsMiksICg4LDIzKSwgKDQyLDgxKSwgKDM4LDQxKSwgKDE2LDczKSwgKDE3LDE3KSApCiAgICBAcHJpbnRmKCIlMmQsICUyZCAtPiAlMmQsICUyZFxuIiwgeCwgeSwgKHg8fHkpLi4uKQplbmQ&input=)
### How it works
We define the binary operator `<|` for our purposes. It is undefined in recent versions of Julia, but still recognized as an operator by the parser. While `\` (not explicitly defined for integers) is one byte shorter, its high precedence would require replacing `x|-~x<|y&~-y` with `(x|-~x)\(y&~-y)`, thus increasing the byte count.
`<|` checks if its first argument is strictly less than the second one. If so, it recursively calls itself with arguments **x | -~x = x | (x + 1)** and **y & ~-y = y & (y - 1)**.
Since adding **1** to **x** toggles all trailing set bits and the lowest unset bit, **x | (x + 1)** toggles the lowest unset bit (and no other bits). Likewise, since subtracting **1** from **y** toggles all trailing unset bits and the lowest set bit, **y & (y + 1)** toggles the lowest set bit.
Finally, when the inequality **x < y** no longer holds, `<|` returns the pair **[x, y]**.
[Answer]
## MATLAB, ~~67~~ 66 bytes
loop:
```
function[]=f(x,y)
while x<y
x=bitor(x,x+1);y=bitand(y,y-1);end
x,y
```
recursive (67 bytes):
```
function[]=f(x,y)
if x<y
f(bitor(x,x+1),bitand(y,y-1))
else
x,y
end
```
Same approach to changing bits as many other anwers.
[Answer]
# Clojure, 63 bytes
```
#(if(< % %2)(recur(bit-or %(inc %))(bit-and %2(dec %2)))[% %2])
```
Same method as used in my [solution](https://codegolf.stackexchange.com/a/83113/6710) in J.
## Usage
```
=> (def f #(if(< % %2)(recur(bit-or %(inc %))(bit-and %2(dec %2)))[% %2]))
=> (f 38 41)
[47 32]
=> (map (partial apply f) [[2 3] [3 2] [8 23] [42 81] [38 41] [16 73] [17 17]])
([3 2] [3 2] [31 0] [63 0] [47 32] [23 0] [17 17])
```
]
|
[Question]
[
## Background
A classical [logic gate](https://en.wikipedia.org/wiki/Logic_gate) is an idealized electronic device implementing a Boolean function, i.e. one that takes a certain number of Boolean inputs and outputs a Boolean. We only consider two-input logic gates in this challenge.
There are \$2^{2 \times 2} = 16\$ distinct two-input logic gates (2×2 input combinations and 2 possible outputs for each input combination). Out of the 16, only two, namely NAND and NOR gates, are [**universal**](https://en.wikipedia.org/wiki/Logic_gate#Universal_logic_gates), in the sense that you can build arbitrary circuits (any Boolean function) by composing the single type of gates. CGCCers might recognize NAND gates because we had a few [challenges](https://codegolf.stackexchange.com/questions/tagged/atomic-code-golf+logic-gates) to build arbitrary circuits out of them.
```
NAND | 0 1 NOR | 0 1
-----+------- -----+-------
0 | 1 1 0 | 1 0
1 | 1 0 1 | 0 0
```
We can generalize the concept of logic gates to n-ary inputs and outputs instead of Booleans, for example ternary for \$n=3\$. (Physical three-state circuits are also being studied.)
For ternary logic gates, the allowed states are often written as `- 0 +`. There are \$3^{3 \times 3} = 19683\$ distinct ternary logic gates in total, and Craig Gidney managed to [enumerate 3774 universal ternary logic gates](https://web.archive.org/web/20221102160829/http://twistedoakstudios.com/blog/Post7878_exploring-universal-ternary-gates) out of the 19683. ([Full C# code](https://github.com/Strilanc/UniversalTernaryGates))
Typos in the blog post and an off-by-one error corrected thanks to @AnttiP
One such logic gate looks like this (named `tand` in the blog post):
```
tand | - 0 +
-----+-----------
- | 0 + +
0 | + + +
+ | + + -
```
Another looks like this: (X can take any value out of `-0+`. All three gates represented by this pattern are universal.)
```
? | - 0 +
-----+-----------
- | + - 0
0 | X - -
+ | + + -
```
On the other hand, [Malbolge's Crazy operator](https://en.wikipedia.org/wiki/Malbolge#Crazy_operation) is NOT universal.
```
crz | - 0 +
-----+-----------
- | 0 - -
0 | 0 - +
+ | + + 0
```
For \$n=1\$, there is only one possible logic gate (constant), and it is trivially universal because the one logic gate can build every possible (the only one) logic gate.
## Challenge
Given the value of \$n \ge 1\$, compute the number of distinct universal n-ary logic gates.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. Note that your code must theoretically calculate the answer for any valid input, when run in an idealized machine (integers and/or floats have unlimited precision) with enough but finite time and memory.
The known values are:
```
1 -> 1
2 -> 2
3 -> 3774
4 -> 942897552 (first calculated by @AnttiP, needs cross-check)
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 287 282 242 bytes
-5 bytes thanks to @Dialfrost
```
f=lambda n,g=0,c=0:g<n**len(e:=range(n*n))!=(s:={g,sum(i//n*n**i for i in e),sum(i%n*n**i for i in e)})and f(n,g+1,c+([s:=s|{sum(g//n**(l//n**i%n*n+r//n**i%n)%n*n**i for i in e)}for _ in"a"*n**n**2for l in s for r in s]!=len(s)==n**n**2))or c
```
[Try it online!](https://tio.run/##bY/BCsIwEER/JRWE3TTQVi9S3C8RkVjbGGi3JakHqX57TaqeFAI7zJtMssN9vPa83Q1unhtqdXe@aMHKUK4qykuzZynbmqEuyWk2NbBkxITAlzQZ5W8d2CwLppRWNL0TVlgWNb7J@hc8UfNFNBDeSAtVpXAITf4xxbyJTRLaZSyXU/fV@K8r6lPQK72KMJxNtNqI/ZJ0izwmFJfwSPSJIQZYzYOzPEIDBarwp@DOLw "Python 3.8 (pre-release) – Try It Online")
Uses a simple integer encoding of the gates, and composes them to depth `n**(n*n)` which should be sufficient. It's able to calculate up to `n=2`.
Full disclosure, this python golf is just to qualify this answer as code golf. The rest of this answer will explain how to calculate `n=4`
# Explanation of the algorithm used to calculate n=4
The following algorithm works for all `n>=2`. In this explanation I refer to gates (also) as functions. `f(a,b)` denotes the value of gate `f` with inputs `a` and `b`. Gates can be composed just like functions. To keep every function binary, I often use the special functions `l(a,b)=a` and `r(a,b)=b` (which just pass the left/right argument).
## Core algorithm
### Unary completeness
A gate `f` is said to be unary complete if it's possible to create every unary function using `f`. Obviously, `f` has to be unary complete to be functionally complete.
We first check if `f` is unary complete. If not, then it's not functionally complete. Then we move to the next section.
### Functional completeness
Assuming that `f` is unary complete, we can check if `f` is functionally complete with the two following tests.
### Lonelyness-test
We want to find some symbols `a, b, c, d` where `a≠b` and `c≠d`, so that `f(a, c)` is distinct from `f(a, d)`, `f(b, c)` and `f(b, d)`. This means that `f` is "lonely".
Using these values, and unary functions, we can simulate all of boolean logic.
If there are no such `a, b, c, d` I claim that `f` can't be functionally complete.
To see why, let's look at how non-lonely functions compose. Note that the functions `l(x,y)=x` and `r(x,y)=y` are not lonely. Assume `L` and `R` are non-lonely functions. `g(a,b)=f(L(a, b), R(a,b))`. In general, `L`, `R` and `f` have the one of the three following "truth" tables, for the relevant inputs:
```
. a b
c x x
d y y
. a b
c x y
d x y
. a b
c x y
d y x
```
It should be clear that composing these does not make the resulting function lonely. This is a finitary problem and can be easily proved with brute-force. It is the same reason `xor` and `not` are not functionally complete.
In other words, composing non-lonely functions makes non-lonely functions, and since some gates are lonely, a non-lonely gate cannot be universal.
### Constructible-test
Again, we assume `f` is unary complete, and also lonely.
A function `f` is n+1-constructible if there are some subsets of the alphabet `L` and `R` where `|L|=|R|=n`, `|f[L,R]|≥n+1`. A function `f` is constructible iff it is n-constructible for all `n≥3` up to the length of the alphabet.
If `f` is constructible, then it is definitely functionally complete. You can just convert your input to base-2, do whatever calculations you want, and then convert back to the full alphabet.
Now is it possible to not be constructible and still be functionally complete? No.
Let's assume that there is some `n` so that `f` is not n-constructible. Note that the functions `l(x,y)=x` and `r(x,y)=y` are never n-constructible. Assume `L` and `R` are non-n-constructible functions. Then `g(a,b)=f(L(a,b),R(a,b))` is also non-n-constructible. Because the image of `L` and `R` has cardinality `≤n`, so does `g`. Therefore `g` is also non-n-constructible
Therefore `f` has to be constructible to be functionally complete, because again, non-n-constructible gates compose to create non-n-constructible gates and some gates are n-constructible.
## Optimizations
### Data Format
A duadic function `f` is represented as a `n*n` list, so that `f(a, b) = list[a*n+b]`.
This is a bit slow, so for `n=4` I use a 32-bit integer.
Every function has a unique index. The indices start from 0 and have no gaps.
Every monadic function `f(a,b)=g(b)` has a unique index. It also starts from 0 and has no gaps.
### Transposition
A transposition `fᵀ` is defined as `fᵀ(a,b)=f(b,a)`
### Permutation
`p` is a permutation of the alphabet. `p(x)` applies the permutation. `p⁻¹(x)` applies the inverse. `p(p⁻¹(x))=p⁻¹(p(x))=x`.
`fₚ` is defined as `fₚ(a,b)=p⁻¹(f(p(a),p(b)))`
### Theorem 1
Claim: `f` is functionally complete, iff `fᵀ` also is.
Proof: You can just swap the arguments lol
### Theorem 2
Claim: `f` is functionally complete, iff `fₚ` also is (for all permutations `p`)
Proof: When you do function composition with `fₚ`, the outer and inner permutations cancel out. So the "meat" of the function doesn't change, just that the alphabet is relabled.
### Minimal representation
`f` is said to be minimal if `f≤fₚ` and `f≤fₚᵀ` for all permutations `p` (here `≤` refers to some total order). By theorem 1 and 2, we only need to consider minimal elements.
# Rust code for n=4
## main.rs
```
#![feature(let_else)]
#![feature(map_first_last)]
#![feature(adt_const_params)]
#![feature(generic_const_exprs)]
#![feature(label_break_value)]
use indicatif::{ProgressBar, ProgressStyle};
use itertools::Itertools;
use rand::Rng;
use rayon::prelude::*;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::*;
use std::thread;
#[cfg(not(debug_assertions))]
macro_rules! get_unsafe {
[$a:expr, $i:expr] => {
*unsafe {$a.get_unchecked($i)}
};
}
#[cfg(debug_assertions)]
macro_rules! get_unsafe {
[$a:expr, $i:expr] => {
*$a.get($i).unwrap()
};
}
#[cfg(not(debug_assertions))]
macro_rules! get_mut_unsafe {
[$a:expr, $i:expr] => {
*unsafe {$a.get_unchecked_mut($i)}
};
}
#[cfg(debug_assertions)]
macro_rules! get_mut_unsafe {
[$a:expr, $i:expr] => {
*$a.get_mut($i).unwrap()
};
}
trait Function: std::hash::Hash + Clone + std::cmp::Eq + std::fmt::Debug + std::cmp::Ord {
const N: usize;
fn impl_eval(&self, a: usize, b: usize) -> usize;
#[cfg(debug_assertions)]
fn eval(&self, a: usize, b: usize) -> usize {
assert!(
a < Self::N && b < Self::N,
"Called eval with a={}, b={} but N={}",
a,
b,
Self::N
);
self.impl_eval(a, b)
}
#[cfg(not(debug_assertions))]
fn eval(&self, a: usize, b: usize) -> usize {
use std::hint::unreachable_unchecked;
if a >= Self::N || b >= Self::N {
// I am speed
unsafe {
unreachable_unchecked();
}
}
self.impl_eval(a, b)
}
fn pass_left() -> Self;
fn pass_right() -> Self;
fn compose(&self, left: &Self, right: &Self) -> Self;
fn unary_compose(&self, left: usize, right: usize) -> usize {
self.compose(
&Self::from_unary_index(left),
&Self::from_unary_index(right),
)
.unary_index()
}
// Used by fuzzers
fn random<R: Rng>(rng: &mut R) -> Self;
// Returns true if should be discarded
fn low_effort_discard(&self) -> bool {
for n in 0..Self::N {
if self.eval(n, n) == n {
return true;
}
}
false
}
// Unique, no holes, for r-unary ops
fn unary_index(&self) -> usize {
let mut ret = 0;
for a in (0..Self::N).rev() {
ret *= Self::N;
ret += self.eval(a, a);
}
ret
}
fn from_unary_index(i: usize) -> Self;
fn is_unary_complete(&self) -> bool
where
[(); Self::N.pow(Self::N as u32)]:,
{
// Bruteforce-checks if self is a unary-complete function
// Keeps track of all the visited nodes and has a queue of functions to add
// A function is popped from the queue and composed with every previous function, plus itself
// The new compositions are added to the queue
// visited is a "Linked list" containing the already visited unary functions
// 0 - not visited
// n - visited, next visited in n steps (n is possibly negative)
// Hack - this list can store BOTH the queue AND the already visited nodes
let mut visited = [0isize; Self::N.pow(Self::N as u32)];
let vl = visited.len() as isize;
let mut start = vl;
let mut queue;
let pri = Self::pass_right().unary_index();
get_mut_unsafe![visited, pri] = vl - pri as isize;
queue = pri as isize;
while queue != vl {
let ui = queue as usize;
// Pop from queue
queue += get_unsafe![visited, ui];
// Redundant, visited[ui] will get overwritten anyway
// visited[ui] = 0;
// Start iterating
let mut ptr = start;
while ptr != vl {
let add = [
self.unary_compose(ptr as usize, ui as usize),
self.unary_compose(ui as usize, ptr as usize),
];
// Push to queue
for x in add {
if get_unsafe![visited, x] == 0 {
get_mut_unsafe![visited, x] = queue - x as isize;
queue = x as isize;
}
}
// Next visited function
ptr += get_unsafe![visited, ptr as usize];
}
// Self-composition
let x = self.unary_compose(ui as usize, ui as usize);
// Push
if get_unsafe![visited, x] == 0 {
get_mut_unsafe![visited, x] = queue - x as isize;
queue = x as isize;
}
// Add self
get_mut_unsafe![visited, ui] = start - ui as isize;
start = ui as isize;
}
visited.iter().all(|&x| x != 0)
}
fn is_functionally_complete(&self) -> bool
where
[(); Self::N.pow(Self::N as u32)]:,
{
let n = Self::N;
let unary = self.is_unary_complete();
if !unary {
return false;
}
// Loneliness
let mut pass = false;
'a: for a in 0..n {
for b in 0..a {
for c in 0..n {
for d in 0..c {
let ac = self.eval(a, c);
let bc = self.eval(b, c);
let ad = self.eval(a, d);
let bd = self.eval(b, d);
let mut arr = [ac, bc, ad, bd];
arr.sort_unstable();
if arr[0] != arr[1] || arr[2] != arr[3] {
pass = true;
break 'a;
}
}
}
}
}
if !pass {
return false;
}
// k+1 - completeness
self.is_k_complete()
}
fn is_k_complete(&self) -> bool {
let n = Self::N;
let mut counter = vec![0; n];
let mut k = 2;
'b: while k < n {
let cmb: Vec<_> = (0..n).combinations(k).collect();
for l in &cmb {
for r in &cmb {
for &a in l {
for &b in r {
counter[self.eval(a, b)] = 1;
}
}
let s = counter.iter().sum();
counter.fill(0);
if s > k {
k = s;
continue 'b;
}
}
}
return false;
}
true
}
fn from_index(i: usize) -> Self;
fn to_index(&self) -> usize;
// If this function is minimal in it's equivalence class, returns the number of functions in the equivalence class
// Else returns zero
fn cifminelse0(&self) -> usize;
// Pretty prints this gate
fn pretty_print(&self) {
println!("Gate i={}", self.to_index());
let pad = " ";
let space = " ";
print!("{}?", pad);
for b in 0..Self::N {
print!("{}{}",space,b);
}
println!();
for a in 0..Self::N {
print!("{}{}", pad, a);
for b in 0..Self::N {
print!("{}{}",space,self.eval(a,b));
}
println!();
}
}
}
// Four bit functions
impl Function for u32 {
const N: usize = 4;
fn impl_eval(&self, a: usize, b: usize) -> usize {
*self as usize >> (a * 4 + b) * 2 & 3
}
fn pass_left() -> u32 {
0xFFAA5500
}
fn pass_right() -> u32 {
0xE4E4E4E4
}
fn compose(&self, l: &Self, r: &Self) -> Self {
let mut ret = 0;
for a in (0..4).rev() {
for b in (0..4).rev() {
ret <<= 2;
ret |= self.eval(l.eval(a, b), r.eval(a, b));
}
}
ret as u32
}
fn random<R: Rng>(rng: &mut R) -> Self {
rng.gen()
}
fn to_index(&self) -> usize {
*self as usize
}
fn from_index(i: usize) -> Self {
i as u32
}
fn unary_index(&self) -> usize {
*self as usize & 255
}
fn from_unary_index(i: usize) -> Self {
let r = i | (i << 8);
let r = r | (r << 16);
r as u32
}
fn cifminelse0(&self) -> usize {
const PERM4: [[usize; 4]; 24] = [
[0, 1, 2, 3],
[0, 1, 3, 2],
[0, 2, 1, 3],
[0, 2, 3, 1],
[0, 3, 1, 2],
[0, 3, 2, 1],
[1, 0, 2, 3],
[1, 0, 3, 2],
[1, 2, 0, 3],
[1, 2, 3, 0],
[1, 3, 0, 2],
[1, 3, 2, 0],
[2, 0, 1, 3],
[2, 0, 3, 1],
[2, 1, 0, 3],
[2, 1, 3, 0],
[2, 3, 0, 1],
[2, 3, 1, 0],
[3, 0, 1, 2],
[3, 0, 2, 1],
[3, 1, 0, 2],
[3, 1, 2, 0],
[3, 2, 0, 1],
[3, 2, 1, 0],
];
fn flipped(f: u32) -> u32 {
f & 0xc0_30_0c_03
| f << 6 & 0x30_0c_03_00
| f << 12 & 0x0c_03_00_00
| f << 18 & 0x03_00_00_00
| f >> 6 & 0x00_c0_30_0c
| f >> 12 & 0x00_00_c0_30
| f >> 18 & 0x00_00_00_c0
}
fn permuted(f: u32, p: &[usize; 4]) -> u32 {
let mut invp = [0, 0, 0, 0];
for i in 0..4 {
invp[p[i]] = i as u32;
}
let mut r = 0;
for a in (0..4).rev() {
for b in (0..4).rev() {
r <<= 2;
r |= invp[f.eval(p[a], p[b])];
}
}
r
}
let mut m = vec![*self; 48];
m[1] = flipped(*self);
if m[1] < *self {
return 0;
}
for (i, p) in PERM4.iter().enumerate().skip(1) {
m[i * 2] = permuted(*self, p);
m[i * 2 + 1] = flipped(m[i * 2]);
if m[i * 2] < *self || m[i * 2 + 1] < *self {
return 0;
}
}
m.sort_unstable();
m.dedup();
m.len()
}
}
impl<const N: usize> Function for [[usize; N]; N] {
const N: usize = N;
fn impl_eval(&self, a: usize, b: usize) -> usize {
self[a][b]
}
fn pass_left() -> Self {
let mut r = [[0; N]; N];
for a in 0..N {
r[a] = [a; N];
}
r
}
fn pass_right() -> Self {
let mut d = [0; N];
for b in 0..N {
d[b] = b;
}
[d; N]
}
fn compose(&self, l: &Self, r: &Self) -> Self {
let mut ret = [[0; N]; N];
for a in 0..N {
for b in 0..N {
ret[a][b] = self.eval(l.eval(a, b), r.eval(a, b));
}
}
ret
}
fn random<R: Rng>(rng: &mut R) -> Self {
let mut r = [[0; N]; N];
for a in 0..N {
for b in 0..N {
r[a][b] = rng.gen_range(0..N);
}
}
r
}
fn from_index(mut i: usize) -> Self {
let mut r = [[0; N]; N];
for a in 0..N {
for b in 0..N {
r[a][b] = i % N;
i /= N;
}
}
r
}
fn to_index(&self) -> usize {
let mut r = 0;
for a in (0..N).rev() {
for b in (0..N).rev() {
r *= N;
r += self[a][b];
}
}
r
}
fn from_unary_index(mut i: usize) -> Self {
let mut x = [0; N];
for n in 0..N {
x[n] = i % N;
i /= N;
}
[x; N]
}
fn cifminelse0(&self) -> usize {
let flip = |i: &Self| i.compose(&Self::pass_right(), &Self::pass_left());
let permute_self = |p: &[usize]| {
let mut inv = [0; N];
for i in 0..N {
inv[p[i]] = i;
}
let mut ret = [[0; N]; N];
for a in 0..N {
for b in 0..N {
ret[a][b] = inv[self.eval(p[a], p[b])];
}
}
ret
};
let mut m = vec![*self; (1..=N).product::<usize>() * 2];
m[1] = flip(self);
if m[1] < *self {
return 0;
}
for (i, p) in (0..N).permutations(N).enumerate().skip(1) {
m[i * 2] = permute_self(&p);
m[i * 2 + 1] = flip(&m[i * 2]);
if m[i * 2] < *self || m[i * 2 + 1] < *self {
return 0;
}
}
m.sort_unstable();
m.dedup();
m.len()
}
}
#[test]
fn test_pass() {
fn test_pass_g<F: Function + std::fmt::Debug>() {
let l = F::pass_left();
let r = F::pass_right();
for a in 0..F::N {
for b in 0..F::N {
assert_eq!(l.eval(a, b), a, "a is {}, b is {}, l is {:?}", a, b, l);
assert_eq!(r.eval(a, b), b, "a is {}, b is {}, r is {:?}", a, b, r);
}
}
}
test_pass_g::<u32>();
test_pass_g::<[[usize; 3]; 3]>();
test_pass_g::<[[usize; 4]; 4]>();
}
#[test]
fn test_compose() {
use rand::rngs::SmallRng;
use rand::SeedableRng;
fn test_compose_g<F: Function + std::fmt::Debug>() {
let mut rng = SmallRng::seed_from_u64(42);
let repeats = 1_000_000;
for _ in 0..repeats {
let f = F::random(&mut rng);
let l = F::random(&mut rng);
let r = F::random(&mut rng);
let c = f.compose(&l, &r);
let a = rng.gen_range(0..F::N);
let b = rng.gen_range(0..F::N);
assert_eq!(
c.eval(a, b),
f.eval(l.eval(a, b), r.eval(a, b)),
"a:{} b:{} f:{:?} l:{:?} r:{:?} c:{:?}",
a,
b,
f,
l,
r,
c
);
}
}
test_compose_g::<u32>();
test_compose_g::<[[usize; 3]; 3]>();
test_compose_g::<[[usize; 4]; 4]>();
}
#[test]
fn test_low_effort_discard() {
use rand::rngs::SmallRng;
use rand::SeedableRng;
fn test_low_effort_discard_g<F: Function + std::fmt::Debug>()
where
[(); F::N.pow(F::N as u32)]:,
{
let mut rng = SmallRng::seed_from_u64(42);
let repeats = 1_000;
for _ in 0..repeats {
let f = F::random(&mut rng);
assert!(
!f.low_effort_discard() || !f.is_functionally_complete(),
"Discarded f:{:?}",
f
);
}
}
test_low_effort_discard_g::<u32>();
test_low_effort_discard_g::<[[usize; 3]; 3]>();
test_low_effort_discard_g::<[[usize; 4]; 4]>();
}
#[test]
fn test_specifics() {
// Using the examples from the blog post + = 0, 0 = 1, 1 = 2
let triplets = [
([[0; 3]; 3], false),
([[1; 3]; 3], false),
([[2; 3]; 3], false),
([[0, 1, 2]; 3], false),
([[0; 3], [1; 3], [2; 3]], false),
([[0, 1, 2], [1, 1, 2], [2, 2, 2]], false), // Min
([[0, 1, 2], [0, 1, 1], [0, 0, 0]], false), // Imp
([[0; 3], [1; 3], [0; 3]], false), // Imp composition
([[2, 0, 0], [0, 0, 0], [0, 0, 1]], true), // Tand
([[2, 1, 1], [1, 0, 1], [1, 1, 1]], true), // Modified Tand
([[2, 2, 2], [2, 0, 2], [2, 2, 1]], true), // Modified Tand
([[1, 0, 0], [0, 2, 0], [0, 0, 0]], true), // Modified Tand
([[1, 1, 1], [1, 2, 1], [1, 1, 0]], true), // Modified Tand
([[1, 2, 2], [2, 2, 2], [2, 2, 0]], true), // Modified Tand
([[2, 0, 1], [0, 0, 0], [1, 0, 1]], true), // Pointy Tand
// Experimentally found
([[0, 2, 0], [0, 0, 0], [0, 0, 0]], false),
([[1, 2, 0], [0, 0, 0], [0, 0, 0]], true),
// From the post
([[2, 0, 1], [0, 0, 0], [2, 2, 0]], true),
([[2, 0, 1], [1, 0, 0], [2, 2, 0]], true),
([[2, 0, 1], [2, 0, 0], [2, 2, 0]], true),
([[1, 0, 0], [1, 0, 2], [2, 2, 1]], false),
];
for (f, r) in triplets {
println!("{:?} -> {}", f, r);
assert_eq!(f.is_functionally_complete(), r);
}
}
fn smart_method<F: Function>()
where
[(); F::N.pow(F::N as u32)]:,
{
let amount = F::N.pow(F::N as u32 * F::N as u32);
(0..amount).into_par_iter().for_each(|i| {
let n = F::from_index(i);
let m = n.cifminelse0();
if m == 0 {
return;
}
let r = n.low_effort_discard() || !n.is_functionally_complete();
if !r {
TC.fetch_add(m, Relaxed);
} else {
FC.fetch_add(m, Relaxed);
}
});
CONT.store(false, Release);
}
static TC: AtomicUsize = AtomicUsize::new(0);
static FC: AtomicUsize = AtomicUsize::new(0);
static CONT: AtomicBool = AtomicBool::new(true);
// Change this to [[usize;3];3] for n=3
type T = u32;
fn main() {
// Fluff
let start = std::time::Instant::now();
let amount = T::N.pow(T::N as u32 * T::N as u32);
let pb = ProgressBar::new(amount as u64);
pb.set_style(
ProgressStyle::default_bar().template(
"{wide_bar:.green/red}\n{pos}/{len} - {percent}% - {per_sec} - {eta} - {msg}",
),
);
let t = thread::spawn(move || {
while CONT.load(Acquire) {
thread::sleep(std::time::Duration::from_millis(100));
let t = TC.load(Relaxed);
let f = FC.load(Relaxed);
pb.set_position(t as u64 + f as u64);
pb.set_message(format!(
"Ratio at {}/{} = {:.5}",
t,
t + f,
t as f64 / (t as f64 + f as f64)
));
pb.tick();
}
});
// Call
smart_method::<T>();
// Fluff
match t.join() {
Err(_e) => {
println!("Failed to join ui-thread :/");
}
_ => {}
};
let t = TC.load(Relaxed);
let f = FC.load(Relaxed);
println!(
"Ended with {} universal gates and {} non-universal gates. Ratio is {}/{} = {:.5}",
t,
f,
t,
t + f,
t as f64 / (t as f64 + f as f64)
);
println!("Took {:?}", start.elapsed());
// Remember to reset TC, FC and CONT if you want to call again
}
```
## cargo.toml
```
[dependencies]
itertools = "0.10"
rand = {version="0.8", features=["small_rng"]}
rayon = "1.5"
indicatif = {version = "0.16", features = ["rayon"]}
```
Takes around 20 minutes on my machine™. The actual code is not that interesting, maybe with the exception of the unary completeness check, which uses a buffer with two non-overlapping linked lists, to form a very efficient deduplicated queue + set data structure.
# n=5?
For `n=5` you basically need a new idea (or a lot of computing power). Checking each gate individually becomes impractical (if you could do it in one cycle, it would still take two years). If someone manages to calculate `n=5`, I'm happy to forward Bubblers +500 bounty to them.
[Answer]
# [Python](https://www.python.org), 1648 bytes
```
lambda n:(K:=G(n))and n**(n*n)-sum(U([O({((x,y),):C(K)if x!=y else[(B[x],)]for x,y in W(K,K)},j)for j in[{((x,y),):C(S)for x,y in W(S,S)}for j in G(1,n)for S in combinations(K,j)]+[{Z(W(X,V)):sum(([*W(*[S]*len(X)*len(V))]for S in P if not S==X==V),[])for X,V in W(P,P)}for P in R(K)if 1<len(P)<n]+sum(([{Z(zip(X,V[i:]+V[:i])):[S[i:]+S[:i]for S in P for i in G(p)]for X,V,i in W(P,P,G(p))}for P in R(K)if set(map(len,P))=={p}]for p in G(2,n+1)if n%p<1),[])])for B in W(*[K]*n))or 1
from itertools import*
import math
from collections import*
W=product
Z=tuple
H=Counter
G=range
def T(l):
d={(i,):C(c)for i in G(len(l[0]))if{*H(x[:i]+x[i+1:]for x in l).values()}=={len((c:=H(x[i]for x in l)))}!=2>len({*c.values()})};r=Z({*G(len(l[0]))}-{*sum(d,())})
if r:d[r]=[*{Z(x[i]for i in r)for x in l}]
return d
E=lambda s:math.prod(map(len,s.values()))
C=lambda l:[(i,)for i in l]
def O(s,o):
q={i:[dict(zip(I,l))for l in s[I]]for I in s for i in I};D={}
for I in o:
d=[dict(zip(I,l))for l in o[I]];S=set()
for i in I:S|={*q[i][0]};d=[h for a,b in W(d,q[i])for h in[a|{}]if all(b[j]==h.setdefault(j,b[j])for j in b)]
for i in S:q[i]=d
for d in q.values():
if[]==d:return{Z(q):d}
t=Z(sorted(d[0]));D[t]=[Z(l[j]for j in t)for l in d]
for i in[*D]:
if d:=T(D[i]):D.pop(i);D|={Z(i[k]for k in j):d[j]for j in d}
return D
def M(l):
if l:
for a,b in M(l[1:]):yield(l[0],)+a,b;yield a,(l[0],)+b
else:yield(),()
R=lambda l:[(a+(l[0],),*t)for(a,b)in M(l[1:])for t in R(b)]if l else[()]
def U(L):
L=[s for s in L if E(s)]
if[]==L:return 0
x=L[0];L2=[];L1=[]
for i in L:
if i!=x!=E((j:=O(i,x)))<E(i):L1+=[i];L2+=[j]
return E(x)+U(L1)-U(L2)
```
[Attempt This Online! (only up to n=4)](https://ato.pxeger.com/run?1=dVXBbuM2EL0VsL6CORQhZSZYu1lklw4LdOMkG8RFglU2CcLyIFtyQq8sKpJcONXqS3oJULTf0F9pv6YzoiK7KHqRzOHjezNvRvSvf2TP5aNNX347lT_9virne-_-_iZLwuU0Ckkq6IWQZzRlLEwjkvo-Tf2U7RWrJf1M1SWtKF3zZ8aZOKYXzMzJekc-kzgpYkU_qLXmTM9tTgBDTEpu6QW_YDVfMAwuIKS2CQL2L2zAA1a_AskZHfC0AQS4nNnl1KRhaWxaAOuC6b6q7uktveM3jAlMkCr_lvoq0H4Sp_SONS_Y1B3JFYGMU1uSQMo7KW8YV7qRABKXwxW_cjlc4fqTq3FwhExX7CjVfScEyr-YDLWVEbp_o4TRkIUKmmWAyy1R_GlcTZnLBg5y0ylyjP9XtohLugwzCuKQFZOyyurmdOa4hjztDxCYfpsdDZpaXDUfHLOvLjQ0j0Fk4M1zuySmjPPS2qQgZpnZvPQ99ybLsHx0kJlNknjW2NyBbmWW22g1K717Wa6yJPY-ymO7SoHNO5N5mD7EXhTPyTVNmPB6kayoaRo8Y1ulo4eJegM-mXnlf6RrdKm_VqY_EG5oEJew_Z_DZBUXlNVQMR6iMyERbrZR4NeOHH6P-5U_25xh9SiX9xDbFqz3Kh8bF3EKC-b1wLRcRCrXUvnQy1fuJtOcbWRq7fXyuFzlKYm8E9l-JYVAv_bRlK5BRZcCY97xKzIRCq3ouBPdGHVJC27RqidZGaEiMyubeTrnUBiCEwQX6lw3aZ03q80Yndejsaxqr9dtWuAC3_-PySLTKJA4UVB9b8Mkgq-y8p-gfjCqHgHFY6MT8qkboojjZkP1iN9v-LWqNdgXJgmdqoWW8nEfaKGqcJWUdMEx2H3uZMr0tl4gkE1GLvUIQ0-dcViDmSugjIQzHVrzxEQElfZKaGoB0xhHNGp6OhqrEtp3Dy1e6E6v3BQdaa8TVv5YO3oSCXlNx1iTGO9nNqMGqMCEe2rUl4boC55egO42MSbRTsK46eGPbtiBMRFtia1psKNgpJl4NnESNSPIWR82R00AYK-xqdfDq7MFMphO79P26IT9Fsn9pjAKJGxLAUVLd2OA0ZhKexUzN2ef6QRznEjlpqdA7AQvwRNaYGec3ZPWbvLG663lBBRHk6FU8BzAc-MimbQemh0J9_4JpQshL2HA1zD0RyfgpJgM-hK8hfPwXmy-nhO6Zn1IZ8D24Dlk7o_nrz8frI2IJNf5KvZQJuUPKIQjrAZ8yL_jB5q7X4eHB_z9wfDd-8O3b4ca67Jw8hT-q5ouWLIjyQMmmOUmLel895RWac0AU9kaN6uHehenv9U8DcGqtgHdKcs84EIExF6JfkgSUsZFWZAsLIo42tlt8395ce9_AA)
Golfed version of my code for `n=5`.
# Explanation
This algorithm relies almost entirely on the fundamental theorem from the paper mentioned in the comments: [On n-Valued Sheffer Functions by
Roy O. Davies](https://doi.org/10.1002/malq.19790251903).
The fundamental theorem lists three conditions that are both sufficient and necessary for a given n-ary logic gate to be complete.
Let \$U=\{1,2,...,n\}\$
A function \$f:U\times U\rightarrow U\$ is complete if and only if none of the following hold:
* There exists a nonempty set \$S\subsetneq U\$ such that for all \$x,y\in S\$, \$f(x,y)\in S\$ (e.g. if `f(0,0)==0` then `f` must be incomplete)
* There exists a nontrivial equivalence relation on \$U\$ where if \$x\_1\sim x\_2\$ and \$y\_1\sim y\_2\$, then \$f(x\_1,y\_1)\sim f(x\_2,y\_2)\$ (that is, you can view \$f\$ as acting on the equivalence classes). (Here an equivalence relation is trivial if \$a\$ and \$b\$ are either always related, or related only when \$a=b\$).
* There exists a permutation \$\pi\$ on \$U\$ consisting of \$\frac{n}{p}\$ cycles where \$p\$ is a prime factor of \$n\$ such that for all \$x,y\in U\$: \$\pi(f(x,y))=f(\pi(x),\pi(y))\$. (For example, if \$(a,b,c)\$ is a cycle and \$(x,y,z)\$ is a cycle, then \$(f(a,x), f(b,y), f(c,z))\$ is a cycle)
So we can count the number of complete gates by counting the number of incomplete gates and subtracting that from the total number of gates. The number of incomplete gates can be calculated by considering each reason a gate could be incomplete individually and then combining the results using inclusion-exclusion.
For example, consider the set of gates that fail the first test where \$n=4\$ and \$S=\{0,1\}\$. It's pretty easy to see that \$f(0,0), f(0,1), f(1,0), f(1,1)\$ each have 2 choices (0 and 1), and the other 12 outputs have 4 choices each.
The other two cases are a little more complicated because values are no longer independent, so the representation I settled on is to partition \$U\times U\$ into pairwise disjoint sets \$S\_i\$, and for each such set list the outputs that the whole set can take.
The set of gates where \$f(0,0)=f(1,1)\$ would be represented by
* \$(f(0,0),f(1,1))\in\{(0,0),(1,1),(2,2),(3,3)\}\$
* \$f(0,1)\in U\$
* \$f(0,2)\in U\$
* ...
With this representation, calculating the size of the set is easy, finding the intersection of two sets is relatively easy (the number of options can easily blow up, so the code tries to compress the representation when possible), and the rest of the cases can be represented.
There is one other major optimization as well:
If we fix \$f(i,i)\$ for \$i\in U\$ then the number of cases to consider is dramatically reduced (which is helpful because PIE is exponential in the number of cases) at the cost of having \$n^n\$ disjoint cases. Moreover, if you consider the directed graph induced by \$f(i,i)\$, isomorphic graphs correspond to the same number of complete gates, reducing the amount of work for \$n=5\$ by nearly 250 times! In fact, for \$n=5\$ it actually also fixes \$f(0,1)\$ which fixes one very slow case. (this optimization (among others) is removed in the golfed code).
Full code:
```
import itertools
from collections import Counter
def length(x):
# counts the number of functions in the set
z = 1
for i in x.values():
z *= len(i)
return z
def intersect(A, B):
# finds the intersection of two sets
q = {}
for I, L in A.items():
d = [dict(zip(I,l)) for l in L]
for i in I:
q[i] = d
for I, L in B.items():
d = [dict(zip(I,l)) for l in L]
seen = set()
for i in I:
d1 = q[i]
if len(d1) == 0: return {tuple(q):[]}
if min(d1[0]) in seen: continue
seen.update(d1[0])
d2 = []
for a in d:
for b in d1:
h = a.copy()
for j, k in b.items():
if h.setdefault(j, k) != k:
break
else:
d2.append(h)
d = d2
if len(d) == 0: return {tuple(q):[]}
for i in seen:
q[i] = d
D = {}
for i, d in q.items():
if len(d) == 0:
return {tuple(q):[]}
elif i == min(d[0]):
t = tuple(sorted(d[0]))
D[t] = [tuple(l[j] for j in t) for l in d]
return simplify(D)
def simplify(self):
# simplifies the set representation
if length(self) == 0:
self = {(j,):[] for i in self for j in i}
else:
l0 = length(self)
for i in list(self):
l = self[i]
d = split_up(l)
if len(d) > 1:
for j, o in d.items():
self[tuple(i[k] for k in j)] = o
self.pop(i)
assert l0 == length(self)
return self
def split_up(l):
# helps to simplify a list of assignments
# e.g. [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2)] can be expressed as (0,1)x(0,1,2)
d = {}
for i in range(len(l[0])):
c = Counter(x[i] for x in l)
if len(set(c.values())) == 1:
q = Counter(x[:i]+x[i+1:] for x in l)
if set(q.values()) == {len(c)}:
d[i,] = [(j,) for j in c]
remaining = tuple(set(range(len(l[0])))-set(sum(d,())))
if remaining:
d[remaining] = list({tuple(x[i] for i in remaining) for x in l})
return d
def basic(l):
# returns the representation for the set of functions f where f(i,i) = l[i]
r = range(len(l))
a = [(i,) for i in r]
return {((x,y),):a if x != y else [(l[x],)] for x in r for y in r}
def nonempty_proper_subsets(l):
for i in range(1, len(l)):
yield from itertools.combinations(l, i)
def splits(l):
if len(l) == 0:
yield (), ()
return
x, *l1 = l
for a,b in splits(l1):
yield (x,)+a, b
yield a, (x,)+b
def partitions(l):
if len(l) == 0:
yield ()
return
x, *l1 = l
for a, b in splits(l1):
a += (x,)
for t in partitions(b):
yield (a,) + t
def special_permutations(n, p):
for P in partitions(list(range(n))):
if set(map(len, P)) == {p}:
d = {}
options = [S[i:]+S[:i] for S in P for i in range(p)]
for S1 in P:
for S2_ in P:
for i in range(p):
S2 = S2_[i:] + S2_[:i]
d[tuple(zip(S1, S2))] = options
yield d
def factors(n):
p = 2
s = set()
while n > 1:
if n%p == 0:
s.add(p)
n //= p
while n%p == 0:
n //= p
p += 1 + p%2
return s
def canonize_(l, d, r1, r2):
options = []
len0 = len(d)
r = r1 or r2
if len(r) == 0:
return ()
for i in r:
while i not in d:
d.append(i)
i = l[i]
p = (len(d)-len0, d.index(i))
options.append(p + canonize_(l, d,
[j for j in r1 if j not in d],
[j for j in r2 if j not in d]
))
while len(d) > len0: d.pop()
return max(options)
def canonize(l):
r2 = set(l)
r1 = set(range(len(l))) - r2
return canonize_(l, [], r1, r2)
def union_length(L):
L = [s for s in L if length(s) > 0]
if len(L) == 0: return 0
x = max(L, key=length)
L2 = []
L1 = []
for i in L:
if i is not x:
ix = intersect(i,x)
if length(ix) < length(i):
L1.append(i)
L2.append(ix)
return length(x) + union_length(L1) - union_length(L2)
def magic(n):
if n == 1: return 1
l = list(range(n))
Z = []
for S in nonempty_proper_subsets(l):
allowed = [(i,) for i in S]
Z.append({
((x, y),): allowed
for x in S
for y in S
})
for P in partitions(l):
if len(P) == n: continue
if len(P) == 1: continue
options = {}
d = {}
for S1 in P:
for S2 in P:
if S1 is S2:
option = []
for S in P:
if S is S1: continue
option.extend(itertools.product(S, repeat=len(S1)*len(S1)))
d[tuple(itertools.product(S1, S1))] = option
else:
ab = len(S1) * len(S2)
if ab not in options:
option = []
for S in P:
option.extend(itertools.product(S, repeat=ab))
options[ab] = option
d[tuple(itertools.product(S1, S2))] = options[ab]
Z.append(d)
for p in factors(n):
Z.extend(special_permutations(n, p))
if True:
cache = {}
out = 0
for ll in itertools.product(range(n), repeat=n):
if any(i==j for i,j in enumerate(ll)): continue
c = canonize(ll)
if c in cache:
out += cache[c]
else:
standard = basic(ll)
q = 0
rs = max(n-4, 0)
for t in itertools.product(range(n), repeat=rs):
x = standard
if rs:
x = intersect(x, {
((0,i+1),):[(t[i],)]
for i in range(rs)
})
q += length(x) - union_length([intersect(x,i) for i in Z])
cache[c] = q
out += q
return out
for i in [1,2,3,4,5]:
print(magic(i))
```
[Attempt This Online! (takes about a minute for n=5)](https://ato.pxeger.com/run?1=nVlLb9tGEL77H_S2RRGAG9OKqKZAIVQFkuYSQIcA6imEYKzElbU2taT5qKkYvvZP9JJL-6P6azqzL3L5cIzyIEu7M7PfvGfpv_7Jz9Uxk1-__l1Xh6uf__3uT3HKs6IiouJFlWVpeXEoshPZZ2nK95XIZEkMxW9ZLYHo4iLhB5JyeVMdg4YuLwg8PwAD7JakOnIi69OOFyQ7kEMtrQyptkpeKfovZEUi9e2QFUTgdjP7g6U1LwMjUpO9XuFRgaBqreBVXUjyRWMQCKcElMG7kLx3SA5CJhqIIwAICKd6yBBBqQjvAcLjk8PwMSRrhPFuBpY4eSgSoIwTAed8EXnwMUwpVSwp0q-3js6p8rHlVSfFYgsiksFZ7___WSXnEkhBm4B-E0ASASmi8FaF8mKQRJSsVmS-tNZ9rOo85cE9Xcbbpz7HSSBHPN9SPAdRLMH1shKy5h4tbs3qPGEVNww-pAUq6gNC-AzFJj58u7dTe9FwE58jyGOzfZafAzpKgBJuQ3KHQnZDw_cf0PU4A_NCoLE6rQJkpeT7Fbmb5sFnV3B2N0rB05JP8yaLGctzLpPg2LMUhs5i1HMvcpwLCuWs6cD84OeDCOFk4Lofmqp3vCfyWSg8BVaBXCqMMCh87gowaM4SKg5PNI1vjw9xhaBjTZfGt1vtWlViOsmSbLslo4QiBqefgw9UFw-3UPL04GqHWRW8tOUKBOQFL7msGJaRi9YAWP8Uc88MuIa2hJBB9bsOgA2HVWi7-FGRzsnKkz10YyrKqgvasapykB76aY7xU4JS1XWdBymdCKRfyUhemZTJlDmfTxl1snaJiO-00irVbil6KxswIcMsz3Jb2vFhZQlNSBlhxArWk7BgXNhqZf135GkOrsuce6GgoMGw-oN0cSNP4MnSUPPZzYzEwTyc0xA-I_W5gM9IrURqJYKVLdkzqBqc8AaDoeQJSCOKpcFPILmwtu7mEBqgYPIG4hTMnKpgbu23B2rTVIMGUxF5GuVj2k82LPR71yGpirmex-49cUuxvQShl9FyXK6RjXLvW7ko9hHP29OnoaOTWIQq9zC020je20w7MSGFvGmTGIT31adXuFrWpyAJURFqM8qxd5ph7BbxWBX5prI4e2kbWzLa0fXJC5tEx8yOlWLfCRi9q7Pdz3QlyRYBb5Y5kIcjLzg5BCIUFIHZnCvgR0dhoxxTJhPGZBqwV5weg6AJzxTKBUNLNNhmzqoyAF8aN9uQdpxYqK9n9fVJayUzyU95db7OiyznxXVZ73DOcXr2gjEKicHX2voseJoQNfu5URDa6WknpDIHCAuJoJ3Ma8WbGE37lVDLDGhIOj1Z66x-NiF5neJskjqULFRd3h4QDRCCpeglC8mutw5LamunEeasqITB_UKUL0ZIJiEycrlSMLyyXSF5B9CuV0MNAAYBckkqa2G-Fyy9Bm-e6sp4QIYk73j0U0-uyg_tYUmp37Ax6U4sx7gMySeT6Hkvxzvlyz5ZrmMeIngTi-X2coOVRR2_weM_9WMrp8OhbhMp0vEGs1lcT-xaCk_69AS1wZESpCFMMCR-W_Z6oaesaVc4Z28gIzYLqluV1njEQ6aEHNi-ygrwhsGSA5Oez0pvIn84ihQuQ35rBVfIV_nI4FTOWJKAft6iJG_erEjurRmxo0LGeHKMyQgMkr9aeH1UawONLZPiC7_G_E5CUoApioVRreN9bUgIHzOhwNDQlryIgJuKRTfNin6amWONcVq_thRaMwHVrBq5BSR2Pha9JtYtwNYfgUZ4hXhDnF1kwhvgbFmNalYoWKlvCu-U-Lbtd6AuKHnrcG6fIV30SB1lB4rW2w1iiHkJmHE48lrYiTWBgU1957kaVyxMCJpOX0Tmt9eVKLmy3jKiPdXjrQsDfUwt4cxrM5CtzVFrjIpSqaqu9-vuWIx6zLfdeFj3LitzXV9BCKq1htsVP680u4a-7twQ11H73UXO2ssqWCqVmRs_bAQe0b4pEGEzNgIjaNFQ8ov7MVJo1tFECGq4brPxvObelECE-YaM0A_-krX4id3AmCLbziX1wGeF6ncnqR2KXNFXy599Y6k6_a0JAR-WptkDT4bTyqYN289Wy0fPAjjAEDXBWCmjtV7NL5vRrbO_9dSWiUGbG15FP6ngGnsV4RFEIwRtiet0vl4jnOxhun9NtC84GplKoBhvWvro4XsQT_ozvdEeos4Y0238wBlvKhWnbsyDmEhqSI5NiDMwZxUmIjRF-tr8peOvVGwLHZGEDTXqNtSBgOnXIWxnWgxIIK_1t8U4AlAfqE11Na6cNta3DI7PS4zeynqJLdluwnytmDJmu2dMhc83bO0PLyhumLJJm1M5atgfZDSx0Wh6AHU3tt-LuuPBPdvDZcnLm6zGFzpzL49S9XJmqIUtYc5ssleB0dXyHIjV6ta8oFIdlsv6xAt8y5jifWY8CfCm3fbK4S14r66xqMDQ6ajE5Urvxns_cFQMEzLgKSsmE1ZgGTEXznQYAveebexTlKYlyqu3IZkP2dyN4gU2LMqJeRmbogU5lVjFM5nkN1Wo_Y_PJksQzENxGWF_iIMKhrWQTmegVbIz9oMek-RP41v36LS29_YabdwFLzqt7vN2KM66Hl-iT4VHu2E6NKxfXDixcRQuwh_Dt-FPW3NpKABBoNs8jqX63zHmvzL2vzP_AQ)
As an aside (also from the paper), another sufficient and necessary condition for completeness is if for each distinct \$a,b,c\in U\$, \$f\$ generates a function \$g:U\rightarrow U\$ such that \$f(a)=a\$ and \$f(b)=c\$, which means that unary completeness implies completeness.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 194 bytes
```
f=(n,c=[],k=0)=>k-n?1/c[n*n]?(F=>g=s=>s[n**n*8]?eval(`try{for(A=n;A--;)for(B=n;B--;)eval(s)+~(A<B?A:B)%n&&G;1}catch{}`):[...'AB()F'].some(_=>g(s+_)))(t=>u=>c[t*n+u])``:f(n,c,k+1)+f(n,[...c,k]):0
```
[Try it online!](https://tio.run/##Hc5BboMwEAXQq3TTZAaDG3YVdIzsRXoIZAXkQtpCxxV2IlVRenWKu5sn/a8/n/21D275@I4F@7dhXUcCzh21Np/ogKSmgpvyybWcsW3gSOpMgVTYnHH2bJvh2s/QxeXnNvoFNHGti6LGBLPBJPxnAopf0C@m0ZXBR97tXuvy7vro3m/3DqtWSrnXBvC4tzL4rwFO2xYEcUJEiKQupFwbMxYXi11XjenNfBIlinSm@kaL1WGtH5zn4OdBzv4MI5SI6x8 "JavaScript (Node.js) – Try It Online")
If a function can express `f(x,y)=max(x,y)+1`, then it's universal:
* `f(x,x)=x+1`, therefore we can get `x+c` for any `c`
* `max(x,x+1,...,x+n-2)` is `n-1`, unless `x` is zero where the result is `n-2`
* `max(x,max(a,a+1,...,a+n-2,b,b+1,...,b+n-2)+1)` is `x` if either `a` or `b` is not 0, and `n+1` if `a` and `b` are both 0
* Set the value using this
The `eval` never meet a function that can't fit the exact length:
* The expression built with `AB()F` is always of odd length (`F(A)(B)`)
* One can write `A` as `((((A))))` to use even spaces
]
|
[Question]
[
I'm letting this one out of the sandbox. Hopefully it is well-written and make sense, feel free to improve.
So in order to make 1+ more popular (and ease the creation of golfed 1+ text-printing programs) here comes the metagolf challenge:
## The 1+ Language
1+ is a fun [deque-based](https://en.m.wikipedia.org/wiki/Double-ended_queue) esolang where 1 is the only literal, and other numbers are constructed with operators
It is also "monotonic", that is, it only has the `+` and `*` operators, and not `-` or `/`
The deque is often referred to as a "stack", and one end of the deques is often referred to as the "top"
Here are the commands:
* `1` pushes 1
* `+` and `*` pop 2 numbers, and push their sum and product respectively
* `"` duplicates the top number
* `/` and `\` rotate the stack upwards and downwards respectively. That is, `/` moves the top number to the bottom and `\` does the exact reverse
* `^` swaps the top two numbers
* `<` is the only comparison operator (although it probably won't do much in [Kolmogorov-complexity challenges](https://codegolf.stackexchange.com/questions/tagged/kolmogorov-complexity))
* `.` and `,` input an integer and a Unicode character respectively, and push it onto the stack. You are not allowed to take input here
* `:` and `;` output an integer and a Unicode character respectively. In the original interpreter, the `:` command outputs with a trailing newline, but here we allow both with a trailing newline and without a trailing newline
* `#` is a goto-command that pops the top value n, and sends program flow to immediately after the nth # in the current line of execution (where numbering starts from 0)
* Functions are defined with `(name|code)` and are called with `(name)`. The name can be empty and the point where they are defined causes their execution too. They are separate lines of execution, so the numbering of #'s in them starts from 0
[Original interpreter](https://tio.run/##jVVbb5tIFH7nV5zgByBgME5W7UL80FRq1VVkRdn2YYUJwjCu0QLDzgy5aNvf7p4BY7Ade9exyVy@8537oXoVa1pON5sRrIWouOc4VcyS/FXELyS3RV0sc2YntHAqyoXz/t3k/W/v3Osr93cnKwVhFSP4HK8oG7vjrBxXDZ@ijC6cmjNnmZUOKZ9gezwC14SBHK7hvru6b/TCV6kYHPiDMFLIbWnBdOJeI@IuS0iZEMg4fPwIt3@N//wA1/YEwZ8@3IFrX@Hq8/wbfL6/e7pSsqKiTAB/5cqK0QISmuckERktOWzvUvJPTRSFW8BTmLVb3bDg35@KkpIV0JJUec11jtgZzHFreArgJ1tBSZGbiXa/PctJqaM@O2bfnwy4mMG0v5afiqHzoH7j8XfigQomdOhgEuJOhWCV5QQEhSUB8kKSWpA0VPdIpAh5yYTuGr3uskIDaTXQH7ihBRrTehCLnxGEUJuRONX3pO0kp5xsz0jO0bwWji42Z81jXVjwYMGSCwtuLZjjfRDKcFl97Cb4bcBYE5DIDCPRXpQSmM1A07X92NyCOQN37wj12HGFTqX63DhmMI4YxocMD4HkqGilG6HM4N4lEt3CDUz2WQZ5@lIs4zzGikthyeLkbyL4hXoE3uVj@oaNIw3iMkU9uJl4GMA3HJr3njcmXcyGNv0vWw5taB5zC5JCFi6m5FOMOW1On9eywubouKxWzI3R66KyivAomIdDV2SpI5N3GD0JRx9dzQPe@TUoyraUepw5xPE2K7IF2tVpucu35C7/W07dkwvGbnga6zRYRkUsyDkfFoshcHwG@dgAyYuQ2oOtsVZn9RlTboZmT2ScO59vdivZoXBG@Qg5ZHeui05zeBJrD/XFS65jvcm6iHAs1ELXSnwHEOZhvxlngm0NWShLhwzJOsaSFS0JTrozNB7StBW/tfsk0pcKsey5SGkt7GeWYULqMkvWrCuSM3oClG6b4yuryUnY4ZBqxqgouy7B6nW9B@yW0Ma3psjky0XXfmjGkRBSohzOZDQ6DeRyEsqJJFfT8Ai@e/HssMeUMr8Pw049ND7VYBdMpQfgbD/RyOEuKP24GAwoBEZRGRckiiRcjaIizsooUlu@zmZjs3FdU1Xxiz/n8tFRF83WX@D/S9U1fUfe@b7@wzXln6H6zqOqurqhmrphIkL1zUffX6i@bviO76PIxm6KycYQ/wI)
[Slightly modified interpreter to remove integer output trailing newline](https://tio.run/##jVVbb5tIFH73rzgZPwABg3Gyahfih6ZSq64iK8q2DytMEIZxjZbbzgy5aNvf7p4BY8COvevYZObMd75zH8pXsSny2XY7ho0QJXcsqwxZlL6K8IWmpqiyVcrMqMissuDCev9u@v63d/b1lf27leSCspJRfE7WBZvYkySflDXfaDS@sCrOrFWSWzR/gp14DLYOPT1cw317dF/bha/SMFjwB2U0k9vcgNnUvkbEXRLRPKKQcPj4EW7/mvz5Aa7NKYI/fbgD27zC1efFN/h8f/d0NVqzIoMgWFeiYjQIIMnKggkoGTqA0jwSCdrdSfkrbxSiIk1pfcRbjZj@U9HRiBvAY5g3W1Uz4N@fo1FM11DktEwrrnLEzmGBW80ZAX6SNeQFcjPR7HeylOYq2jND9v1Jg4s5zLpj@ak9VMk3Hn6nDhDQoUV7Ux93BLx1klIQBawo0BcaVYLGPtEGLFKHviRCtTt5kpfoYVH2HPBs3wCFKR2Ihc8IQqjJaBirA20zSgtOdzKacvSvgWOMtax@bDIDHgxYcWHArQELPPd8mS@jS94UvzUYWwci2QhINEhTBPM5KKoyTM4t6HOwByK0Y4YlBhWrC@2YQTtimBwyPHiSoyxKVfNlCQeHSHQLNzAdsvQK9SVbhWmIjRnDioXR31Twi4NiDAoye8PJsQJhHqMh3EwdzOAbES260GufLuZ9p/6fM4dO1I@FAVEmexeL8inEqtbS541ssgWGLhsWq6N1xgrZRyjyFn4/FtntyOQc5k/CMUhbcYC3gdnDDNG0w@l9HG/qIqegWZ3Wu3xL7/K/9chAz5vY/mmsVWNZIUJBz8WwXPaBkzPIxxpIX4S07u2cNVqvz7hy03d7KvPcxnyzX8kZhTPGx8gh53OTtZb9k1izby9ccVU2HDZBgBdDJVQlx5cFZQ5OnHYm2UafpWBxnyHahNizoiHBy@4MjYM0dcuDuk8ZMmIohJzWcqVxHAEu4qIS5jNLsDhVnkQb1tKcsemhdjMoX1lFT8IOr6z6UhV5OzHYybbzgJPjm/iqFYl816jKD@X4xkBK1MMbGp2OPbmc@vJ@kquZfwTfv4f22GNKWeuH/tQeOh8rsEusyjv1@qo/MdX@Pivd3dG7rhAYBHmYyVcwwkkQZGGSBwFp@Fqnte3WtnVC8Is/6/LRIst66y7x/yWxddeSZ66r/rB1@acR13okxFY1oquajgji6o@uuySuqrmW66LK1qw7y8Qc/wI)
## Challenge
Your challenge is to write a program that inputs some text and outputs a 1+ program that outputs the text. The program can be in any language (lesser-known ones preferably), but it must output valid programs for any text.
Do not golf the test cases manually, otherwise I'll change them.
## Winning criteria
Your score for a particular test case is your output length divided by the input length. The total score is the sum of the scores of all test cases. The lower, the better.
The test cases are:
1. ["Hello, World!"](https://codegolf.stackexchange.com/questions/55422/hello-world)
2. [We're no strangers to code golf, you know the rules, and so do I](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i)
3. [A keyboard so real you can almost TASTE it](https://codegolf.stackexchange.com/questions/103033/a-keyboard-so-real-you-can-almost-taste-it)
4. [Pascal's Tree-angle](https://codegolf.stackexchange.com/questions/207019/pascals-tree-angle)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~16.26 ... 12.30~~ 12.19
## 8.31 + 1.13 + 0.91 + 1.84
*Saved 1.69 by optimizing the initial code, as suggested by @JoKing*
*Saved 1.31 by using a precomputed table of code snippets, as suggested by @Mukundan314*
*Saved 0.11 by counting the patterns more accurately, as suggested by @JoKing*
## Source
```
const CHAR_SET =
" !\"#$%&'*+,-./0123456789:;<=>?@" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`" +
"abcdefghijklmnopqrstuvwxyz{}";
const CHAR_MAP = {
10 : '11+1+"*1+',
32 : '11+"*"*"+',
33 : '11+"*"*"+1+',
34 : '11+"*"*1+"+',
35 : '11+"*1+"1+1+*',
36 : '11+1+"+"*',
37 : '11+1+"+"*1+',
38 : '11+"1+"+"*+',
39 : '11+1+""+"*+',
40 : '11+"*"1+*"+',
41 : '11+"*1+"1+"*+',
42 : '11+1+"+"1+*',
43 : '11+1+"+"1+*1+',
44 : '11+"*"1+"+1+*',
45 : '11+1+""1+1+**',
46 : '11+1+""1+1+**1+',
47 : '11+"*1+"1+"1+*+',
48 : '11+1+"1+"**',
49 : '11+1+"+1+"*',
50 : '11+"*1+"*"+',
51 : '11+1+"1+"*1+*',
52 : '11+1+""+1+"*+',
53 : '11+1+"1+1+"*"++',
54 : '11+1+""**"+',
55 : '11+1+"+"1+"*+',
56 : '11+1+"+1+"1+*',
57 : '11+1+""*"+1+*',
58 : '11+"*"1+"*+"+',
59 : '11+1+""+1+"1+*+',
60 : '11+1+"1+"1+**',
61 : '11+1+"1+"1+**1+',
62 : '11+1+"+"1+"1+*+',
63 : '11+1+"""+1+**',
64 : '11+"*"+"*',
65 : '11+"*"+"*1+',
66 : '11+""*"+"*+',
67 : '11+1+"1+"+"*+',
68 : '11+"*""*1+*',
69 : '11+"*""*1+*1+',
70 : '11+""*""*1+*+',
71 : '11+1+"+1+"1+"*+',
72 : '11+1+"+"*"+',
73 : '11+1+"+"*"+1+',
74 : '11+1+"+"*1+"+',
75 : '11+1+"1+1+"**',
76 : '11+"*""+"1+*+',
77 : '11+"1+"1+1+"**+',
78 : '11+1+"+""+1+*',
79 : '11+1+"+""+1+*1+',
80 : '11+"*""1+**',
81 : '11+1+"*"*',
82 : '11+1+"*"*1+',
83 : '11+"1+"*"*+',
84 : '11+1+""*"*+',
85 : '11+1+""*"*+1+',
86 : '11+"1+""*"*++',
87 : '11+1+"""*"*++',
88 : '11+"*"+"1+1+1+*',
89 : '11+"*"+"1+"*+',
90 : '11+1+"*"1+*',
91 : '11+1+"*"1+*1+',
92 : '11+"1+"*"1+*+',
93 : '11+1+""*"1+*+',
94 : '11+1+""*"1+*+1+',
95 : '11+"1+""*"1+*++',
96 : '11+1+"1+"**"+',
97 : '11+1+"1+"**"+1+',
98 : '11+1+"+1+"*"+',
99 : '11+1+"*"1+1+*',
100: '11+1+"*1+"*',
101: '11+1+"*1+"*1+',
102: '11+"1+"*1+"*+',
103: '11+1+""*1+"*+',
104: '11+"*"1+"*1+*',
105: '11+"*1+""+"*+',
106: '11+1+"""*1+"*++',
107: '11+""*1+""+"*++',
108: '11+1+""+"**',
109: '11+1+"*"1+"*+',
110: '11+1+"*1+"1+*',
111: '11+1+""+"*1+*',
112: '11+1+"+1+"1+*"+',
113: '11+1+""*1+"1+*+',
114: '11+1+""+"*1+1+*',
115: '11+"*1+""+"1+*+',
116: '11+"*""1+"*+*',
117: '11+1+"""+"*+*',
118: '11+1+"*""1+"*++',
119: '11+1+"*"1+"1+*+',
120: '11+"*"1+"1+**',
121: '11+"1+"*+"*',
122: '11+"1+"*+"*1+',
123: '11+""1+"*+"*+',
124: '11+1+""*1+1+"*+',
125: '11+"*1+""**',
126: '11+1+""+"1+**'
}
const MAX_WINDOW = 100;
function encode(str) {
let out = '', cmd = [], stk = [], pos = [];
Buffer.from(str).forEach((c, i) => {
let j = stk.indexOf(c);
if(~j) {
cmd[pos[j]] = cmd[pos[j]].replace(/;/, '";');
cmd.push(';');
stk = stk.slice(0, j);
pos = pos.slice(0, j);
}
else {
cmd.push(CHAR_MAP[c] + ';');
}
stk.push(c);
pos.push(i);
});
out += cmd.join('');
for(let n = 0;; n++) {
let id = (function genId(n) {
return n ? CHAR_SET[n % CHAR_SET.length] + genId(n / CHAR_SET.length | 0) : ''
})(n);
let max = 0, best = null, stat = {};
for(let i = 0; i < out.length; i++) {
let sub = '', p = 0, c;
for(let w = 0; w < MAX_WINDOW && (c = out[i + w]); w++) {
sub += c;
p += (c == '(') - (c == ')');
if(p < 0 || c == '|') break;
if(!p) {
(stat[sub] = stat[sub] || []).push(i);
}
}
}
let A = Object.keys(stat).map(sub => {
let w = sub.length,
b = ~w,
cnt = stat[sub].reduce((t, a) => a < b + w ? t : (b = a, t + 1), 0),
saved = cnt * w - ((cnt - 1) * (id.length + 2) + w + id.length + 3);
return [ saved, sub, w ];
})
.sort((a, b) => b[0] - a[0]);
if(!A.length) break;
let [ saved, sub ] = A[0];
if(saved < 1) break;
if(saved > max) {
max = saved;
best = sub;
}
if(best === null) break;
out =
out.split(best).map((s, i) =>
i ? i == 1 ? `(${id}|` + best + ')' + s : `(${id})` + s : s
).join('');
}
return out;
}
```
[Try it online!](https://tio.run/##7Vn9e9pGEv5df8WGayPJEIzEh6DE6ZHEjt02dhq7dVLsOkJaQLaQqD5MOOP@67mZ1a60Enc/kXue63OHzSDe2X135p3ZRdi39r0dO5G3TJ4FoUu/qGlMSZxEnpOowy9OGMQJeXU8en9zfnhBDhRCauTJVe1v33z7VN2rN54191uG2e50e1Z/8N3w@cGL7/9eI3UcNnr56vXh0Zvjkx9@/Ont6dm7n9@fX/zy6@WHj7@Nr66uf7/5xMfZE8el09ncu73zF0G4/COKk/R@9Xn9j4fH2lBRpBDejt6RA/IAs4wW@Y6ohlE36rU9o642AGubHKvtwQ/H2iVMjOxIKFiOdnMUnki9l@G9Yi3wZZhVwgRvXzBkMEcHxdgC7bSKGGAlHkPHKMeQjzbl9URknXYF5XF0OjJ3Lc@k05UiYQlyvLeFCyarEg/4uKdfzEE3Z5JyZbVhaLcls4hcu0aZQUTZNWW9Cg26bXl8RsQ9HWnGXs7fLauT8/TKMebrWjJLoVq3X1JzT/RLd1CJM9em1yplluvcM7ZwrnOvUl@JS8qaLSO4pBoLnXvdEia4Rb61DOaoVYqlwKVsi5r0BhWUc1stiZs5OG5UNRb8VilTUSurXUEFf6eyz8T4brUXsjitnhSnpKJlSTuTT@CevrxCUXVrsIXzmPrSzi1q25cy3uP16JslTMxvS7HsCV36pR7O0W4FFRw9iYM5OC73sIz35c5At8izPyh7xMoD@YTN98jAqKA8noFZyinXfdAuxV/gnS1cMHXLmaGLe3qVE4f3wsDawgVXv3IaiRmDchYiO6PVkj9VagI1yihnN1qmlHOhnNFqS7nJeKd0jhSrdqXTsSaN78m1ZETCY@W7TkwRnn7ps0asMCjlm69glPPNIzKMEkuBm9WTsyaYKjnnlTaMToWrYKvkLc3pyTsMwhUzLPkslPC@lF9NVsqoZF6sYbbkauT72DANqap5D5hmGRU9YLZFJbhD4J2SHpLmZinrfNWerBKLRnkUNz9vRx9uLk9OX59dwu0PNCncFU3TwEm8MCA0cOC2TYM7Np3dGfk0IWGawEBVbRBn4cLV@LoBt3R3/GoZxuwKWAh5mU6nNGpOo3DBOJrTMDq0nbmmOQ3i6eTgBWPNeG9hHvA0vcCln8@mmqMzDkK8qfbnrc5HElx1DKuMb6@vYYb0rhnRpW87VNsf7jeIWhuqwJDPaS7TeK6pEpgFjUvGvgfTWg1ymzuzPMBuOx@ZpT7cyj5U@cWd5Ni5JnVSrJbNwbXYMIfDyM8AjwGPWcqocJ2l1rwNvUBT1QwH9TRUKoDIWsMhCep1XRLQw2poee1mNDhxtaAQLqJJGgUw@/v8nnsckG/zN02fBrNkjoHzuWS/6iQb0tLxfFOztHRYgJcJQ1jYnzG2BpnQGLskSH0fu8PGNw@PfKTIw2N5wMtzTJmvAO@LtDLWOJ3wjltm7A4nKqhWGdUKqKR@fvqUaA54gH3sQVqrax3GyPSEkaPYwxxZ4nucB2tqqk6eiTe6qucLs7ZcwnItstmQzL@BwZOI2nflUU@W8nqEaKjHGNa9Zu0nroFmfK3L7ZA9HhX59bEQewTTzya31Emad3QdM1q9ubCXGhPsRUlDFAhgLnJDCge1/XMlI06QyJHBvnJT2AJa0iA227Q25D1BPaGVEugGDTnsBlzXiaE3oEVkuti@p9iaSLsHc0BPDa@fwVgANM8VzVUnps5o60QG24XsvIfHGWkDU2rA@Gu@y3T20ozDKNE0CGjCwp2MW9ewmg0v0pnyZMRXKBcNxZLpCVZpBFOLmVlCzzF8eWbueYH7oKh5timYS1SVbw@gH8pVBYbMc5BtnTI/O3g5Ae6XeOl7CZuQVV2L@aFaNB/Ux8PWNODik/bNg@c@bj6BomyVOnY02BgqyJ36J/4@5hy6dALxMHkJIIKh8vgF5UrCxPbZBlSUiP6RehHV1Gms6tA5tnvk@fR8HThaS28m4Tl8@Q9mms6jV68C/FGLjwb4nBC9i9wRxXNY@hyCojhhRPGoA59okn38q4KoJyxz5H2mrmZm5cbPudCnTT@c4RyWSgUrmk0lk3VCY3VrlCrWZZqxaxiNsePITAM4OOrMBdLo/M8L@fwLNkRmYZOkaPXhl2Pq@2GDXIaR7z5RFOWSqjA8CDE/O5jRKIZZxA/vqfIxTMldEK5IMqckSn1Qyg5cEofEDcmJMiJTaCFIYbHwkgUNEjUmqzmcxCfqAqZ4wR0UgoRTxrMKU98N1ARO/gSdMcEPbeBbkxDoIzJL18oJuU2hb1Z2ENgkgUDJGqbOIQKknFLqA6PyJkwSG5r@jjJ3Ch/nEZwlgasop/QeqUKcP/Pu@YBlCceiI@yGq6DkiNKA2FEIfCxNl8Y0YkNLo/J1nWhdcsT2Gq5Cd7KmJZzlAct6lNHOU06KykOEKDDcB0FnciGgT1FiP4RUQbmIzKkdobYTSiFAZ46qTtIEnVi6JITazddYNQzBS5STIPZcSlaUTIAyKyEWRnDMQlaYACIo6juzF1mAK9YQWexwu8MYR4B7U5a2Hd8RGFktyusQi8tyXTB9RGgTcLssOEr/YgX6SwWrnYXzhhym/u8gfSuxBgkqiKK9@QrTpBb/b@/w/7Gz5//B/qeCVcgNPHY27ELZwM3UZrMx0Jho2mg6aLpoemgsNH00AzT4fWHzDM0BmpfneJu12QDXzc1mV4MP5Nq/ubna1eDjaqMU6e5sIMeL0UuW7uZnNJdoDtG8R3OB5iOaX9CcoDlD8w7NGA1@TdpcCb2ydHcWTinS3Vm4Qq@v0l@vRu/OM8FGaM7RvEZzhOYNmmM0P6D5Ec1PaIZoVKbu6cXhe1mvr9VfOwtW7a/dxOJ6nR@fHF1kO2rzG5oPaF6h@ZVtNzSnaN6iaaBpotln8hazC712Equi105iZXop0jdr@F5XPBQJNSWPUsBt@DGquEE6pAdPo4QbpIv/B4XfLvcUPF1ittBK4y1iGvg/TviFC0vgfWL28V9iVgstXPcBH@A/Pfsd/LMke8IlAAMpL7Nr/ou8Oj2TPbfyJQOzsz3esIxeZrLHPwE "JavaScript (Node.js) – Try It Online")
## Outputs
* ["Hello, World!"](https://tio.run/##jVVbb9s2FH73rziWH0RZsi5OhnZy/NAUaLEhMIK0fRhUTZAluham20gqFyz77e6hZFmSHXszEoE8/M53rjwsX8S2yOe73QS2QpTctawyZFH6IsJnmpqiytYpM6Mis8qCC@v9O/v9L@@c6yvnVyvJBWUlo/idbQo2c2ZJPitrvtFoMrYqzqx1kls0f4S9eAKODj09XMN9e3Rf24Wv0jBY8DtlNJPb3IC57Vwj4i6JaB5RSDh8/Ai3f8y@fIBr00bwpw934JhXuPq8@gaf7@8er0YbVmQQBJtKVIwGASRZWTABJUMHUJpHIkG7eyl/4Y1CVKQprY94qxHTvys6GnEDeAzLZks0A/75dzSK6QaKnJZpxQlH7BJWuNXcEeAv2UBeIDcTzX4vS2lO0J4Zsh@PGoyXMO@O5a/2kCjfePiDuqCADi3as33cKeBtkpSCKGBNgT7TqBI09hVtwCJ16HMiiNPJk7xED4uy54Dn@AaoTO1ALHxCEEJNRsOYDLTNKC043ctoytG/Bo4x1rL6s80MeDBgzYUBtwas8NzzZb6MLnk2/tVgbB2IZCMg0SBNESyXoBJ1mJxb0JfgDERoxwxLDComK@2UQTthmB0zPHiSoyxKovmyhINDJLqFG7CHLL1C/ZatwzTExoxhzcLoLyr4@KgYg4LM33ByokKYx2gIN7aLGXwjolUXeu3TeNl36v85c@xE/VkZEGWyd7Eon0Ksai192somW2HosmGxOlpnrJB9hCJv5fdjkd2OTO5x/iQcg3RUF3gbmDPMEE07nN7H8aYu8hY0q/N607f0pv@tpwz0vJnjn8daNZYVIhT0Ugzfv/eBswvIP2sgfRbSurd31mi9vuDKTd9tW@a5jfnmsJJ3FC4YnyCHvJ/brLXsn8WafXvhmhPZcNgEAQ6GShA1x8eCMhdvnHYh2UafpWBxnyHahtizoiHBYXeBxkWauuWBHFKGjBiKopzXWkjjeAW4iItKmE8sweJUeRJtWUtzwaaH2s1F@coqehZ2PLLqoSry9sZgJzvuA94c38SnViTyrSHqq3o6MZAS9XBCo9OxJ5e2L@eTXM39E/jhHTpgTyllrR/6t/bY@ViFfWIJ79TrUX/mVvuHrHSzozeuEBgEeZjJJxjhShBkYZIHgdLwtU5ru53j6I6u6MpU0cnrotlpU/zgP1FeiSbPtKmyUIiiOfpUIeMahgqaVEQRGWtSW1NQNtX1RQ1E@YI0RM25oy92Zt1yJib/Jw)
* [We're no strangers to code golf, you know the rules, and so do I](https://tio.run/##jVZrW9vGEv7Or1iWFs/aRraAJMSC0wZOkpIQlxJoDjWO64sISm3JkWQuzea303dmZbAh0MOTh6xmZ95557qMr/KzJF69vl5SZ3k@zhq12rib9odXefcyHHr5ZNQbpl4/GdXGSZbXNp7VN54889fX/Oe1KM7DdJyG@L1ymqQr/koUr4wFb2FhabE2ydJaL4prYXyuCvGS8itqxg5ntT@92he/6pAdq5p6E6bhiD/jqlqt@@vQ2Iv6YdwPVZSpnR21fbzy/oVa9@pQfvViT/neGk6vm0fq9f7e@drCaZqMVKdzOsknadjpqGg0TtJcjVMQgDTu5xH8FtLsKnMG/WQ4DOUqm1oMwi@TcGEhq6psoLbcJ5mq@vptYWEQnqokDsfDSUYZdLdUE5@msaDwE52qOAF2mrvvQjYMY4I/r5t@OjdqcUut3l7zjzAkfZR1P4UNpVVFTbVb9Ta@tGqdRsNQ5YnqhSq8DPuTPBy0tZlDYZvwMsrJv5VH8RgMk/EMgZbfrqpSWrpVSrsXUIKql4bdAc1Ze/1hkoWFLBxm4OfUEaPI5NfZqKoOqqqX5VW1XVVN3LfanK/qbfLq@CfKaB3V50YA0Fya@mprS5WoNJ@cbVXZUv6cCH687hhBDahp7iOYewgrdxEOWowxTsZk2lzCuUsAbatNVZ9HmSnU7qjXHXbRmAPVS7v9v8I8W7xTjLmCrH6H5FJJdeMBHOGj3kAGvxNR8zZ04bS4NUvq/yNzl4T8alZVf8S9i6K86qKqIr044yZrInRuWFTH3DpLuI8gajXbs7FwtwOpcTd/rI4g/VJDZdPA/PkMhcNbvcqsXubqwlPgTg/blb9nV/53Oz1n11rx2w/r1kQ3TfJuHj4Ww8nJrOLKI5ofRTG8zNl7qyBbnbJ@hMrmLO0653ka8@bNiWdUPeJ8CRg8n2ejqef2g7rerL9uLyNuODRBB4thklMpxmMRpg1MnHkk2dVZlCQdzCL0z7ro2dyBYNk9AtMAjLS8opuUARGhaP2wVcDOMQJZPkgmuXeRRijOJI76Z@kU5hGfLVi7QTlMJ@GDandXlizVPJ5ODDrZbxxgctoento84reGSrZ0f2MAEnbY0CA9aPGx3ub9xKfV9j31m3foRvc@JNf6YHZq75IflFSRWMpuzWXVPzDV7Zus3O6OmXUFxU4n7o74CYa67nRG3SjudLTDm5I219e@X/ErWuuyLlcqmmzgBKbsU99WdNmvGE3blozGh6nQj5a2DYR@pRxoWhJ9GJsy7qlm6TlUxQgKht5Z@tGUTUA/sCL1jYYa21bIs7QE6FXL9hUo0S4ri9kyQFgMUEBRzdAGMyhjgRoaWjjexWHH0g@CZchnMGgbGlhNHhybwFCPuTILQw2mpekTboFRCbShY5A1MENQn1hH0xN2wnEyB9/QUxcdJ8GJhUtA6wIGYeHcsMc1psAhcrgn8OOD4q6hzNITUDEGrHcMncDPsqFDy1F9ZApIqwkCJnkCiaGmDVjL0Ae44dxKDo4NoAHx1nHi7Eg2MqNh/EfBiLMX0D5/IShcadrjLDFND15QIsP50XTGuYE0t8yKua4jBsPcmoYSSx8MnRnaRx4Dmli@2pMYnhoaWZxx3BBDLbl7KxTPLSczQMSBAL5jgggqYCxPUrXBlh4Hi/8nIOCMd0V539AFl3fZSNVfSrBA1BwWaso0hgwjzpHXl4aL@AvThRmqx1mp8M2ORKyZxbKRuAMkCo7H7KCHTyFvSFtGecdwcPAMlYOTtmXJukScGBAMtFghcEAZemGZAFwfcZF4YOCXLsXK48RzIk8kf/TFctKQVc1ZAbVDCUII0pWVdsAGpL@lG6CyaKlj6auUX7uaamoYafrfrEQfif93kiZxFuBYEuH/LH3jAsHCUOjUtdzD9amlI54ZHpXPMgCLhrvT1SQ0PLyGyjz51JYaQKUDhN8Mz0xFmrkmhVyWkrhvzY1byD5KbV23DwFetUXlYf9ZSoyAvxj6Q4ouBTS0YkFETJZZFlDEYQGqy4SF7ksm@bmoao8r95flrC7z9Oxxal@5YK9YYU2Y7Yq6uP7d0t988ZE3C7djQ0jFVloaNYVlG44DjN@FsFuTCl5CNpTTW@mSplSOe7HntgZvJ25@Q5uWzgUUlheFc/aUIwzXQDUBWhb4CSBkghCgoS2LIEFZ6nA83UkBtSwj7Ipf2WtoYy0U1lyiBtO0YVRg9h8r48IZESiU74NUbEdKw6uFR6LJlBAbUAKKDUeu3QYw9Fpa0lFnK@FeUI8w/Y7Yc@RVM/xPlhckXzocWYbO0YbEui/urnhxspebcCLpHEO/WmlgTafciUUDaO5gzzXHEu8@zIgT8ixyQS8kC0953zlvz9xWODbMpywk3dZBO9LYTNVg2pLo3TQfSg45UC5Q3dIBNwq6kUoYBLQ8Ohj9iW7jDnllBKCO48vi0TCs/l62P88VfeXnMaA/ZWemTl5MMehhPmH0Rubo1LhHkVc1Z/K9NNifhn620KI3Lr9Oyhn9LBn9BlTo/5ebnZ@jYjVgQovb44LIkZEX4mfoSqTyAOLt4zF/g4HgahGGYxPdx52DyguNn1ASnr5fZGMhrfSCI3Zx8@8DjJrcXXvyN6SHv6b@AQ)
* [A keyboard so real you can almost TASTE it](https://tio.run/##jVVtc9pGEP7OrzgfcdiTQCDsxDaYOMaJnaQO8bjJhw6ljIBz0BQkKonEmV5/u/vsCQzYMS0DYm/v2Wdf7zT7kY3jqH53VxTjLJuljWp1FiTDyY8suNUTL5tPB5PEG8bT6ixOs@rhQe3wxYG/v@cfVcMo08ks0XhWbuKk4lfCqDKzfIVCcac6T5PqIIyqOvomFuqi8F2xZgdZXC23rqxf8Zkdi6r4oBM95WVUFvWavw/EZTjU0VCLMBVnZ6L9W@XXU7Hv1QA@P70UvrcH6aLzRVxcXX7bK9wk8VT0@zfzbJ7ofl@E01mcZGKWIABoo2EWwu9Cm/5Ic4NhPJlou5UuLUb6r7kuFNKySEeilS9JlcXf/xQKI30j4kjPJvOUUmBbooOlahQEPuGNiGJwJ1m@XugmOiL484Lk6zcldlqivtrmj42Q5Jc0@KobQgpXLNHdWg8rKbo34USLLBYDLfStHs4zPepJtcHCNvo2zMhf6cNohgjj2VoAXb9XFqWktAIlwXeAAPUSHYxow9obTuJUL3R6kiK@HI4crc4@xtOyuC6LQZqVRbssOtjv9rhe5VXxavhaMEZHDHkQQLRRpqFotUSJSpvFaQu3JfwNFfx4wQxJjaijHjOoRwyVhwzXXeaYxTNSPW7hxiaI2uJY1DZZ1hr1fjoIJgEGcyQGSTD8U2fpzoNmbDSk/pMgiyURRCM4wqLWQAV/klFnlbqNaae1HtT/C@ZhEPbRKYvhlGcXTTkP0FWr/T7mIesgdR5YdEetnMU8R1B1O731XHjawdR4WD@GI0m/1BDpMjF/s0J6ssK567g07wufglx62s75mZ3z33Zyw65b8XtPY6sWm8RZkOltOfz@@zqwsgX5hwXq24y9dxfBlpdRbwnleD3sGtd5mfPxvcRnVGxxXgQHn8/xdOm59yTWW/cXDFLigcMQ9HExzDMqRXhZ6KSBE6e2FLu8zhIno3WG4TjAzGY5CS67LTQN0NiRF3RfMjAiFSmftmqycxyBNBvF88z7noRozjwKh@NkSbPFZxfW@UH5nMz1k7CHV5a9VLNoeWIwyX7jGien5@FVm4X8rqGSKT2@MUAJO9zQCHrUZbHW4/uJpXrvEfz@PXSPfUzJvb5eP7UPgx@VxKKwlK7M7VX/xKnu3VdldXesXVcA9vtRMOVXMOCy358GYdTvy5xvGbS6u/Npz/iudBS9NdKRrpJkmj4ds9LHSjr02kBylOvKpqKioZqRTdlsSkWKzrHEPwT89g1dGCoCpPjHOknPTZPhUjUZuQty3wW3cnyXHEO7SrK0pyz7roKEKEjCihwFN4Ar4BlCEmB6ZyBK5ZJroGAq3jpFwNQxDrkYphx9ZFxeQf8O6CPYOpJaBtLCBgIdK9z29BYEVtVRksNzWHmsHMenV2CBX8ZIxyXfJiBBqbB6rhBm1XCk9J6TcXzlcrZckmeGzgwgLJ/xV9ELQx8MPcMe7@e6hpHMo6hsK0XvFR0aJvE5IMT3GmEiKdox9IvB9cfNoEMoSoYuDe1gB4tL/NqGSlAzqaIK4AgGfC7Hw07QA7RlX9GBbRt2ELmyPaAm2u/CJ2rFHWmyH5knbcNy0RcuD53wnDgubOvGdgS1eWPYxlE@aopN/qMThfcdKGyhsfKpxa316ZOBJF2LBwknCGLMmTXngVP0ynYDwkcuBVU5I1uxF6iTTa/NiXLyFfSgSReKv9AfcD52YFDSd8zhoGaLJOo2OWbHzpVxrPs3yk4WEoHIQ@HnUXO4/ODlkbJD6gAP5tcMkzw8jhUkXdlq7YLeJsaDfIJq7@bV@IhBpg@Kv41F/FDkGXCnFA8A9@Vc0Us7DvlEHCgeNvIMzxuCBT@Pav7HPYLTPGw398g95k5xhJwrzzImm8uBur6yQZ7Y6nJj6ZNNnGdsT9la2LqdLs6ALZSznEB02UOQ6MRL24UzK5Tts83jx72AzDPXvPPsy8XDNfsv)
* [Pascal's Tree-angle](https://tio.run/##jVVbc6JIFH73Vxwxs3QDgmiuGh8mUzVTu5WyUtmZhy2HtRDakVoEBtpcatnfnj2nkYgmumso0n36O9@5N9mzXKZJ/@WlA0sps2LoOJmfB/Gz9J9EbMv1ah7ndpCunCwtpHN50bs8u3BPB@6VEyVS5Fku8N1dpHnX7UZJN1N8rVan7ayL3JlHiSOSB9iIO@Ca0NDDNdzVR3fKLnwlw@DAbyIXK9omFvR77ikibqNAJIGAqIBPn@Dmj@7vH@HU7iH488dbcO0Brr5MvsGXu9uHQWuRpyuYzRZruc7FbAbRKktzCVmODqA0CWSEdjfS4rmoFII0joU6KmqNUPxci1arsKAIYVxtGbfg739arVAsIE1EFq8LViB2DBPc8mEL8BctIEmRO5fVfiOLRcLQnu3nPx44tMfQ3x7TT3nItG@F/0MMQQMTavS05@FOg@kiigXIFOYCxJMI1lKEnsZ3WEhHPEWSuVt5lGToYZo1HJi6ngV6rm9Buf@IIITaufBDtqNtB3FaiI1MxAX6V8ExRiVTr@XKgnsL5oW04MaCCZ5PPcqXtU1eDx8FxtaBgBoBiXbSFMB4DDrTd5NzA@YY3B0R2rH9DIMK2YS/ZeBvGLr7DPdT4sjSjHGPSrhziEQ3cA29XZZGoX5dzf3Yx8YMYZ77wV9CFu29YuwUpP@Okx0d/CREQ7jpDTGD70Q02YaufGqPm079P2f2nVCviQXBinoXi/LZx6oq6eOSmmyCoVPDYnX41lhKfYSi6cRrxkLdjkzD/fwRHIN09SEUdWDuboZEvMWZTVxR1YWmoFod1jPe0zP@W0/b0Zt2Xe8w1lHYPJW@FMdi@P69CeweQf6pgOJJkvXpxlmr9vqIK9dNt3uU5zrm69cVzSgcMd5BDprP5aq27B3E2k17/rxg1HDYBDO8GNaS6Ql@LEQ@xInjR5JtNVnSPGwyBEsfe1ZWJHjZHaEZIo1qeWCvKUNGDEXTDmuNyDiOQCHDdC3txzzC4qyTKFjmNc0Rm1PUrgbla74WB2H7V5a6VGVSTwx2sju8x8nxbPzUyoi@NUwv9bc3BlKiHt7Q6HQ4pWXPo/uJVn3vDfz1O/SKfUtJtb5vTu2@86EOm8SyYquurvoDU@29ZmV7dzSuKwTOZom/ok8wwrXZbOVHyWymVXy10/zlxWVu6ZqawTVDMzX2oRxp9MeZU7IPHJ8R11g5cl0TUZwZpYkDqOQaa5fMwVPODdckJdYrWRsxnA41VEIoPprJWQd5GVcchoJ2CYp6BO1x9os6R7BrGrjjrF@yDjfotMsRgP@tkqExgysVnTYGuqxOEM7ZZUnQD8p4n14niHFRQTNNBSB6gxanZbUmDFdHKpwz5cPWpxPObBJh2PxVF4WXfMTMksLRUIrcNsVMTp/UbyVBFDGzM64iHlBEKryLEgGUC9opJ5heoU9pxS44GyiHyOfzkipTp@WqJMCAY8zKcU0pVIsrhdC5yuQ5V6GQfaqRxsnMiLZdVboqlWyo@DROFcc0Dik6quG5YrR4pUDZwKxsTG1WDh@92OoOsXGa/gU)
## How?
### Building the code snippets
The table of code snippets `CHAR_MAP` was built with the following program. This is a brute-force search that keeps the shortest snippet for each character, or the one that contains the most `1`'s in case of a tie. The idea behind this last rule is to use similar building strategies whenever possible to improve the final compression.
```
let snippet = {};
(function search(stk, cmd) {
let n = stk[0];
if(stk.length == 1 && n < 127) {
snippet[n] =
!snippet[n] || (
snippet[n].length > cmd.length || (
snippet[n].length == cmd.length &&
snippet[n].split('1').length < cmd.split('1').length
)
) ?
cmd
:
snippet[n];
}
if(cmd.length < 15) {
if(stk.length >= 2) {
let a = stk[stk.length - 2], b = stk[stk.length - 1];
search([...stk.slice(0, -2), a * b], cmd + '*');
search([...stk.slice(0, -2), a + b], cmd + '+');
}
search([...stk, 1], cmd + '1');
search([...stk, stk[stk.length - 1]], cmd + '"');
}
})([1, 1], '11');
console.log(snippet);
```
[Try it online!](https://tio.run/##jZHNboMwEITvPMW2B2yHH8VIVaUS0gdBHIjjJG6pQdjpJeHZqcE4JQ2HnjDjb5Zh9qP8LhVrRaMjWe95j86Kg9KtYBqlfcU1KCmaxjwzuHSp5@HDWTItagmKly07YaU/Q2BfewIXD2BwSMMaNV8XhgcQh4GJKy6P@gRZBhR830AboMmrdYH7Si4LyEYB4GmmXa@AJ3nOuqHbIYB7uWOXaBNhhvv@MqyaSmiMKCKO3Iy2B/1mJ9OJwPtNM47p/LaQPzVaZyuaJTLFvLhe7svbZpC4G9t1OXU9gyJIihB2SxfUbmQMYbeXx3E8IKoSjON1CFFCQjN1BbtiXCsEgFaIpP@zBXNb4Gyd92gNTZgbSR35l1n4g1/Xs3V1XkdwTu1ARMdZHqulqiseV/URT32TtO9/AA "JavaScript (Node.js) – Try It Online")
### Optimizing the initial code
The initial code is first optimized by re-using characters that were previously generated whenever possible. For instance, `Hello, World!` is optimized as:
```
[H];[e];[l]";";[o]";[,];[ ];[W];;[r];;[d];[!];
```
where each character within brackets is one of the code snippets generated above.
### Compressing the code with functions
We then iteratively look for the sub-string in the code that leads to the highest savings when replaced with a function call.
We make sure that the selected sub-strings have balanced parentheses and do not contain a `|`.
Below are all the compression steps for "Hello, World!".
Initial code:
```
11+1+"+"*"+;11+1+"*1+"*1+;11+1+""+"**";";11+1+""+"*1+*";11+"*"1+"+1+*;11+"*"*"+;11+1+"""
*"*++;;11+1+""+"*1+1+*;;11+1+"*1+"*;11+"*"*"+1+;
```
We replace `;11+1+"` with a function with an empty name:
```
11+1+"+"*"+(|;11+1+")*1+"*1+()"+"**";"()"+"*1+*";11+"*"1+"+1+*;11+"*"*"+()""*"*++;()"+"*
1+1+*;()*1+"*;11+"*"*"+1+;
```
We replace `;11+"*"` with a function named `!`:
```
11+1+"+"*"+(|;11+1+")*1+"*1+()"+"**";"()"+"*1+*"(!|;11+"*")1+"+1+*(!)*"+()""*"*++;()"+"*
1+1+*;()*1+"*(!)*"+1+;
```
We replace `()"+"*` with a function named `"`:
```
11+1+"+"*"+(|;11+1+")*1+"*1+("|()"+"*)*";"(")1+*"(!|;11+"*")1+"+1+*(!)*"+()""*"*++;(")1+
1+*;()*1+"*(!)*"+1+;
```
[Answer]
# [Python 2](https://docs.python.org/2/), 13.62 + 3.18 + 3.17 + 2.90 = 22.87
```
def gen_prog(inp):
prog = ''
inp = map(ord, inp)
vals = sorted(set(inp))[::-1]
funcnames = ([''] + sorted(set(map(chr,range(32, 127))) - set('()|~')))[:len(vals)]
val2funcname = {k:v for (k,v) in zip(sorted(vals, key=lambda c:-inp.count(c)), funcnames)}
func_defined = {f: False for f in funcnames + ['~']}
for n in inp:
f = val2funcname[n]
frag = '(' + f
if not func_defined[f]:
frag += '|1'
for b in bin(n)[3:]:
frag += ('(~)' if func_defined['~'] else '(~|"+1+)') if b == '1' else '"+'
if b == '1': func_defined['~'] = True
frag += ';'
func_defined[f] = True
frag += ')'
if inp.count(n) == 1: frag = frag[2+len(f):-1]
prog += frag
return prog
```
[Hello, World!](https://tio.run/##jVZbb5tIFH7nV5w4D0CNLzhZtUvrh6ZSu7uKvFHaarUibIVhiFFghg5DmmzS/vXsOdyxY3dR5DAz3/nOfQ7ZvdoIvng6ho1SWe7MZpkvg@Re@XcsmaoiXSdyGoh0lolczV69nL/65aV9emL/Oou5YjKTDH8nkZATexLzSVbSadrx0azI5Wwd8xnjt1BvH4M9hp4cvsNFc3RR6oVPpBhm8AeTLKUlt2Axt08RcR4HjAcM4hzevYOzvycf38LpdI7g92/PwZ6e4NuH1Wf4cHF@e6LFaSakgvw@1yIpUghEkrBAxYLnUJ@F7GvBNC23IA9hWS0N04KH75oWsggEZ1lS5EaO2CWscGk6GuATR8AFcktVreu9hHED9U19eX1rwtESFt0xPZlE52H0OfevmQMjGEODducerkbgRnHCQAlYM2B3LCgUC73RgIRE2F2sDNvsdPMMDRRZT79rexboUu9A0v@GIIROJfNDYyA9DRKRs3qPJTmaV8HRxXKv/NmkFlxasM6VBWcWrPDc9ShcVhe7Of6VYKwJCCjDSDSIUgDLJeiGPozNGYyXYA@2UM/Uz9Cp0FiZuwzmDsNkm@HSJY5MZIbpUQYHh0h0Bm9gPmTp5en3dO0nPlZcCGvpBzdM5UejHXCbj8UzNh7r4PMQ9eBi7mAAn3Fo1XlemnS07Nv0v2zZtqH8WVkQpFS4mJL3Pua03P22oQpboeNUrZgbs9MlqIpwy115fVeo1JHJ2Y4ewdFHW3cgb/zqFWVVSh1u3MflVVaoBaq3/XIvnpN78XO50UDOndjefuysxEqhfMUO@XB11QdODiD/KYHsTpF2tzbWaqw@YMqbvtlzinPj85v2jToUDig/Rg7qzk3aaPb2Yqd9ff46N7DeqC6@4LVQKEPnOAOYdLDfzAPBtvosQoZ9hmDjY8mqigRvugM0DtJUFV/bvRf5mhRi2ecqFIWafpMxJqTgcbCRTZEc0OOidNUcn2TB9sK2L6nyGlW86RKsXtu5xG7xpjg1VUzDxdAfdXNHCClRDu9kNDp06XXu0Y1EbwtvB94Onha7S0n5vex36rbxoQ5tMLUOgHf7nkb22qB010V3QT3RRLxm/EsmxTUWSVZfHLREEV3XukmU@hkVgUXLyvJbZKRxgmOXYTcyVTKYruNgX1bzouAB91NGMMPVdRqIPThRYm4t6fNrZpwsLLAXLzHFMAE61g3z8QeVqOvQvUbq6prH10XDjdQPN85tOZuMGwuHNM6nf@PMqBWRmAU37H6Z@Ok69CFwJuV0FAU2RWBiA7dmmt9bs79gaGLO6BviIXKq6JU6IuLvHBuDq//Qve/tfOR0jgq6jETI0bfY5V2CI@mXkTZ0ZIq2b@i@IW7kDZNcimIW9UdbHx6gFWuyAj/VDG66J463W/KNNEb5h6mTwoEy8qm6kvD8cTS2x6ZuEmpdz4f6cDTWn2uMdTtFdlmf6c/Wlddbngz93xZtxUy9H7kuu9wkO2ynCTP9cxdjqqbIbKu0rfhxhSg38WO2kLzcf@p9dmpVM9S3VMyb7666Ywa9pGnNoKc7E84Zv1YbB7lHVjmoS0wNuUAh6actqIYQV4v5GAjJnC46iIkS4SujRZr4tdwyN2JX/M9CkQGi7HUmccyFpWOocNSgJvufkdbcXQNzrvhBmQ72oVV68TOlzQkp2g96@o0libDgLyGT8Og/ "Python 2 – Try It Online")
[We're no strangers...](https://tio.run/##7VdZb9tGEH7nr5jIDyQj6nSKpEz8YKeI4cJQjBwoAkYNKHIlsSZ32eXSsprjr6czy1uynD60QIPWCBxy95tv7hk63aq14NOvR7BWKs3c0Sj1ZRBvlX/L4qHKk0Ush4FIRqnI1OjJ4/GTHx5PHh1PfhxFXDGZSoa/B0shB5NBxAeppjOMowejPJOjRcRHjN9AeXwEkz605PAZrqqrK60X3pBiGMHPTLKEXrkD0/HkESIuo4DxgEGUwfPncPZu8PoUHg3HCH5xegmT4TE@nc/ewvnV5c2xESWpkAqybWYspUggEHHMAhUJnkF5F7Lfc2YYmQNZCCfFq2U78PGzYYRsCYKzNM4zK0PsCczw1XYNwJ9oCVwgt1TFe3kWM26hvqEvVzc2PDiBaXNNP6lE56H3NvNXzIUe9KFCe@M5vvXAW0YxAyVgwYDdsiBXLJz3OiQkwm4jZU3sRjdP0UCRtvR7k7kDpjQbkPQ3CELoUDI/tDrSwyAWGSvPWJyheQUcXdRn@tc6ceCVA4tMOXDmwAzvvTmFy2liN8Z/Gow1AQFlGIk6UQrg5ARMy@zG5gz6JzDpHKGeoZ@iU6E1s/cZ7D2GwS7DK484UpFa9pwy2LlEojN4BuMuSytPF8nCj32suBAW0g@umcoe9PbAdT6md9h4ZILPQ9SDL2MXA3iHQ7PGc23Sg5O2TX/Jll0b9K@ZA0FChYspeeFjTvXpZk0VNkPHqVoxN3ajS1AV4ZE3m7ddoVJHJnc3egRHHyemC1nlV6soi1JqcP02LiuyQi1QPB2We3iX3MNvy/U6ct5gMj@MHWmsFMpX7D4f3r9vAwf3IH/VQHarSLtXGutUVt9jyrO22WOKc@Xzs/qJOhTuUX6EHNSd66TSPD@IHbb1@YvMwnqjuviAYyFXlslxBzDpYr/Z9wTbabMIGbYZgrWPJasKEpx099C4SFNUfGn3QeRTUohln6lQ5Gq4kREmJOdRsJZVkdyjx0PpojneyJwdhO0OKT1GFa@6BKt34r7CbpkPcWuqiJaLZX4y7T0hpEQ5nMlodOjR43hOE4mepvM9eL14auw@JeX3VbtTd40PTaiDaTQAnO0HGnleB6UZF82A@kobccX4h1SKFRZJWg4OekUR0zSaTZT4KRWBQ6@F5TfISOsE1y7DbmRKM9ie62JfFvsi5wH3E0YwyzNNWogtOFFibh3p8xWzjqcOTKaPMcUwALo2LfvTFypRz6W5RurKmsfHacWN1B@v3Ru9m6xrB5c07qc/otQqFZGYA9dsexL7ySL0IXAHejuKHJsisLGBazPtz7XZHzA0EWf0DfFx6RbR0zqWxN841gfP/GLOP9f7kdM9KmgyskSOtsUebxK8lL6OtGUi03J3QrcN8ZbzbpK1KGbR/DQxuxdoxYKswE81i9vesTvfL/lKGqP8xTZJYUcZ@VSMJLz/1OtP@rZpE2pR7ofystc372qMRb1F9lnv6M/alac7nnT93xWtxWyzHbkmu9wmOyZuFWb6z5v2qZqWdl2ldcX3C4Q@xI/ZXHJ9/rX12WkUzVBOqYhX311lx3R6yTCqRU8zEy4ZX6m1i9w9Ry9qjSkhVygk/aQGlRDiqjGvAyGZ20QHMctY@MqqkTZ@LdfMldh7/jJXZIDQvc4krrlQO4YKexVqcPinZ1Szq2POe36vTAM7r5VefUtpdUOKDoO@/sJMybBDIFN6dsiMvq9jccOMdyKHay42oNYMZB5ji9LXWiYgFHBhnGJNxTH@4ZAkkUoYV2aGn0@@ggszQZGIX0d8hZHSPBuRxyE3FYZN0WUG@q8On29BIL2EVb41LuC3PFOw8Tn3QTEk36LoGi0gyiXD8c1XxrlQyscZes30dc5DNFqhZYYxYzdEJUh@Fd2UgLRzHqMBdByKDe9cyJyDL7HYQ@1myDImNbSDqvUGctu5yPwtPolwsWWdc@0Hqo2Ypl3nJamBkUcLKcAcmB@sy0DQyMkoA@gqRk7CmuHyxNguGEMDgzVFdZEruqTUKYG5W28pa2RCpIwLnkUhgw2DBVIWKaTEVBwroRPD0YImvyua/2TgRhdEYXsaF4yneI7TgNz2s2tA5G5SfhKUXO1rouNTmbbA61Abx9h3lqDvyljrpVg7bTPtQ0f2nmMO8J0Twzr/G8RaJf5vr/D/2Oz539h/xtg/AQ "Python 2 – Try It Online")
[A keyboard...](https://tio.run/##rVZbd5tGEH7nV4zlByBCF2SnTkj0YLuxk9RVVNtpmyKqIlhZHEsLXZBjNyR/3Z3hjmQpPUfl@HyG3W@uO7Oj4CGa@bz3uA@zKApCo9MJbOHMHyL7ns3b0XIxmYu24y86gR9GnRdH3RfPj/TDA/1lx@MRE4FgiK2pL1p6y@OtIFEnSft7nWUoOhOPdxi/g2x5H/QmVOTwHYb51jCxC9dkGDrwngm2oE@uQa@rHyLjwnMYdxh4IZyewsmn1tUxHLa7SD47vgC9fYBv54OPcD68uDuQvEXgiwjCh1CaCn8Bjj@fMyfyfB5Ctueyv5dMkkINQhf66aeiavDlqyS5bAo@Z8F8GSohcvswwE/VkAAfbwrcR90iSr@ztTnjCtpr2@LmToW9PvTKbXoCgcFD42No3zADGtCEnG12LfxqgDn15gwiHyYM2D1zlhFzrUZNCYmwey9SdLW0zQN00A8q9k3d0kAWckkS9mckIbUtmO0qNem2M/dDlq2xeYjupXQMMVlLYLbQ4FKDSRhpcKLBAPdNi9Kllbnr4l9CxpoAh04YFdWy5EC/D7Ii13NzAs0@6LUltNO2AwzKVQbqugZ1TUNrVcOlSToCP1BUi06wtomKTuA1dOtaKuf0bjGx5zZWnAsTYTu3LAr3Gmvk4jx6T/i4L4PNXbSDH10DE/hEQIMy8sSlvX7Vp//ky6oPCQw0cBZUuHgkZzaeabL6eUYVNsDAqVrxbNTSlk9VhEvmwKqGQqWOmozV7BEdY9RlA8I8rkpRpqVU8ppVXpieCrVA@rZZ7tlTcs@@L9eoyZkt3drM7SRc4Ud2xLbFMBpVia0tzD8TIruPyLqZOavlXm9x5XXV7S7lOY/5dfFGHQpbjO@jDurO2SK3bG3ktqv27EmoYL1RXYzxWlhGisxxBjBhYL@pW5KtVbX4wq1qcGY2lmyUKsGbbosaA9WkFZ/5vZH5igxi2YeR6y@j9mfh4YEsuefMRF4kW@yYKJ02x7VYso201UsquUYjnncJVq9uXGK3WG2cmpFHw0WRY1ldE0KVKId3MjrtmvTatehGoreetUYvBk/BXVdJ53tZ7dRV510ZimRKJQHv9g2NbBVJKa@L8oJ6pIl4w/g4EP4NFkmQXRz0iSKyLJWTaGEHVAQafaae36FGGic4dhl2I4sSDappGNiX6bxYcofbC0Y0xZRlGogVOqnEs9WEzW@YctDTQO8d4RFDC2hbVtT4G5WoadC9RuaymsfXXq4bVX@5Ne6S2aTcajikcT794wVKZojENLhlD/25vZi4NjhGK5mO/hKbwlGxgQs31a@F22NMjccZ/Yb4MjXS7CU2pqS/DKwJpvxNtr4W85HTPhooT2SKOqoem7w84Kmwk0wrMmqart7QVUfMqVU/5EQUT1GOdbm@gV5MyAv8qaZw1TwwrPWSz6Uxy99UmQzWjFFM6ZWE@3GjqTdVWSXWJJsP2WajKT/VGJNiiqxrfaI/i1BerURSj39VtBBT5WrmytPlKvmhG3ma6Z/Za1I1TdWiSouKb6aMZBF/zC4FT9YfKz87pbQZslvK4/nvrqxjar0kSfmgpzsTLhi/iWYG6m5oyaBOOBlliELCXhSkjEK6Cs6V4wtmlNlBznTu25FSMFX8tVxozsVG/MMyIgf8pNeZwDHnJoGhwUbOam1@GlJ@d9XcGfGtMiXtvDA6/J7RfIcMbSY9whifnSF5keL4L4jjWCfoERwQHBI8J/iB4IjgBcFLgi5Bi6BPcHJFxxHHqGs8jncFekhXZzwe7Qr0jGKpDHdnwBivj0@ScONfCH4jeENwSXBN8IngI8E7gg8EQwKTwCIY5flKw905cVIZ7s6JK/P1v9TX6fHwKk3YMcEVwY8EZwTnBG8J3hP8RHBB8IpATrI7uH5zWc3X/1VfOydstb52S1aWr6u3786u046K/yD4neCU4Nek3QgGBD8TaARtgk6S3lK6zNdOyVrJ107JSvP1Lw "Python 2 – Try It Online")
[Pascal's...](https://tio.run/##jVdLc5tIEL7zK9ryAYjQA2RZNokOcari2i2X1uUkhy3MphCMLMpoIMPg2Bsnf93bzRvJUlaWyEzP1@/uaZI8yXXMrZdjWEuZpPZolHjCj56k98iiocw2y0gM/XgzSuJUjs5m47PpzDyZmOejkEsmEsHwOVjFYmAOQj5IcnGKcnw0ylIxWoZ8xPgDlORjMPvQ4sM1XFdH17le@EyKYQR/MsE2tOUGWGPzBBFXoc@4zyBM4cMHuPh78Ok9nAzHCP74/grM4QRXl4svcHl99TBRwk0SCwnpU6qsRLwBP44i5ssw5imUZwH7ljFFSQ1IA5gXW0034MdPRQnYCmLOkihLtRSxc1jgVrcVwE@4Ah6jbCGLfUmLGNdQ39ATdw86HM3Bao7pkwh0HnpfUu@O2dCDPlRoZ@zirgfOKowYyBiWDNgj8zPJArfXEUIs7DGUmqk3unmCBsZJS79jugaoQm1AwvuOIIQOBfMCrcM99KM4ZSWNRSmaV8DRxZyWP9YbA24MWKbSgAsDFnjuuBQuo4ndGL85GGsCfMowCupEyYf5HFRN7cbmAvpzMDsk1DP0EnQq0Bb6rgR9R8JgW8KNQzKSONF0lzLYOURBF/AOxl0prTz9sVl6kYcVF8BSeP49k@lRbwdc58N6xcZjFTweoB7cjG0M4CsOLRrPc5OO5m2b/pct2zbkj4UB/oYKF1Py0cOc5tTva6qwBTpO1Yq50RtdMVURkpyF23aFSh0l2dvRIzj6aKo2pJVfraIsSqnB9du4tMgKtUCx2s/35jW@N7/n63X4nIHp7seOcqyIpSfZIR9ub9vAwQHkPzmQPUrS7pTGGpXVB0x51zZ7THGufH5Xr6hD4YDyY5RB3bneVJrdvdhhW5@3TDWsN6qLr3gtZFJTOc4AJmzsN/1AsI22lFgEbQn@2sOSlYUQvOkOiLFRTFHxpd17kW9JIZZ9KoM4k8PvIsSEZDz016IqkgN6HOQumuOzyNhe2PYllV@jklddgtVr2jfYLe4Qp6YMabho6rOq7zChSOTDOxmNDhxajl26kWhluTvwevDU2F2RlN@bdqduGx@oUAdTaQB4t@9pZLcOSnNdNBfUC03EO8a/JiK@wyJJyouDtsiiqkoziTZeQkVg0Law/AEl0jjBscuwG5nMJeiObWNfFvMi4z73NoxgmqOqNBBbcBKJuTWEx@@YNrEMMK0ZphgGQMeqpj//ohJ1bLrXSF1Z87i0Ktko@se9/ZDPJu3ewCGN8@nfMNFKRcRmwD17mkfeZhl44NuDfDrGGTaFr2MD12bqP2uzv2JoQs7oHeLHyi6il@tYkfzGsT446i/V/VnPR07nqKDJyApltC12eJPglfDySGsqSlpt39BtQ5yV201yzopZVJ9NtXuAVizJCnxV07juTGx3t@QrbozyL10lhR1l5FNxJeH5c69v9nVVJ9SynA/lYa@vvtYYy3qK7Ep9pT9rV95uedL1f5u1ZtPVduSa7HKd7DDtKsz0j2P1qZpWel2ldcX3C0ROxJfZTPCc/tJ67VSKZihvqZBX711lx3R6SVGqQU93JlwxfifXNsruGfmgzjEl5BqZhLepQSWEZNWYT34smN1EBzGrKPakViN1fFuuJVdst/yvTJIBcd7rTOCYC3LHUGGvQg32f3pKdXd1zLnlB3ka2GWt9Pp3SqsTUrQf9NIqEbO1VlpUq3WiNOQJ/pnbdBNO4BR/ZoduwhTMMX2n5UkjZ4r/f6FnCz8DC8VP6YuLWUU/A@sMpqcwG9MT12dIP4fJKZyhQus0/@ESCeet2rem1it@nZxa@W/HXzi3Tnbx5sw8LR4l/T8 "Python 2 – Try It Online")
Improved the average score for large test cases by embedding the print command into the functions.
---
# [Python 2](https://docs.python.org/2/), 13.62 + 4.00 + 3.87 + 3.65 = 25.14
```
def gen_prog(inp):
prog = '1(~|"+1+)'
inp = map(ord, inp)
vals = sorted(set(inp))[::-1]
funcnames = ([''] + sorted(set(map(chr,range(32, 127))) - set('()|~')))[:len(vals)]
val2funcname = {k:v for (k,v) in zip(sorted(vals, key=lambda c:-inp.count(c)), funcnames)}
for i,v in enumerate(vals): prog += '(' + val2funcname[v] + '|' + '1'*(i==len(vals)-1)
for i,v in enumerate(vals[::-1]):
diff = v - (vals[::-1] + [1])[i-1]
prog += '1' + bin(diff)[3:].replace('0', '"+').replace('1', '(~)') + '+)'
for n in inp: prog += '(' + val2funcname[n] + ');'
return prog
```
[Hello, World!](https://tio.run/##jVbbbttGEH3nV4zlB5IWdaHsIikTPcQB4rYwVMNJUBQ0G1DkyiJM7jLLpWw3jn/dnVleZUdKBYHg7p45c9m5ML9Xa8FnT4ewViovvMkkD2WU3qvwjqVjVWbLVI4jkU1yUajJ61fT17@8ck@O3V8nCVdM5pLhc7QScuSOEj7KNZ1hHB5MykJOlgmfML6BevsQ3CH05PAdLpqjC60XPpFimMAfTLKMltyB2dQ9QcR5EjEeMUgKeP8eTv8efXwHJ@Mpgj@8Owd3fIxvZ4vPcHZxvjk2kiwXUkFxXxgrKTKIRJqySCWCF1CfxexryQyjcKCIYV4tLduBb98NI2YrEJzlaVlYBWLnsMCl7RmAv2QFXCC3VNW63ksZt1DfOJTXGxsO5jDrjumXS3QeBp@L8Jp5MIAhNGh/GuBqAP4qSRkoAUsG7I5FpWJxMNgiIRF2lyjLtTvdPEcDRd7T77uBA6Y0O5AMbxGE0LFkYWxtSY@jVBSs3mNpgeZVcHRR7@nHOnPg0oFloRw4dWCB535A4XK62E3xr8GYExDRDSPRVpQimM/BtMzt2JzCcA7u1hbqGYc5OhVbC/slg/2CYfSc4dInjlzklh3QDW4dItEpvIXpNkvvnn7PlmEaYsbFsJRhdMNUcTB4AW7vY/YDGw9NCHmMenAx9TCAP3Bo0XmuTTqY9236X7Y8t0E/Fg5EGSUuXsmHEO9U796uKcMW6DhlK96N3ekSlEW45S@CviuU6sjkPY8ewdFH1/SgaPzqJWWVSh1u2McV1a1QCVRvu@WOfiR39HO5wZacP3KD3diJxkqhQsX2@XB11QeO9iD/0UB2p0i7XxvrNFbvMeVt3@wpxbnx@W37RhUKe5QfIgdV5zprNAc7seO@vnBZWJhvlBdfsC2UyjI5zgAmPaw3e0@wnT6LkHGfIVqHmLKqIsFOt4fGQ5oq42u7dyLfkEJM@0LFolTjW5nghZQ8idaySZI9enyUrorjkyzZTtjzJqXbqOJNlWD2ut4lVkswxqmpEhoulvlg2i@EkBLlsCej0bFPr9OAOhK9zYIX8HbwtNiXlHS/l/1KfW58bEIbTKMDYG/fUchBG5SuXXQN6okm4jXjX3IprjFJ8rpx0BKoDViPD4OhO7RNoxtJWZhTNji0rFzYIDXNFZy/DMuSKU1l@56HBVoNjpJHPMwYwSzfNGky9uBEiZfsyJBfM@t45oA7e4V3DSOgY9OyHx4pV32PGhypq5MfX2cNN1J/u/E2ekhZNw5OaxxU/ya5VSsiMQdu2P08DbNlHELkjfSYFCVWR2RjJbdm2t/beZc4GyJiWDNMUofQ6r0qRkOdUOhM3xB/Q@5hztDTNY@sZD5v7W76y07qKmq9Dh4nqxX6tsFg9ADIjaln@0kT4vbehrp/4zl@qVkkbPvHXoAfCHkaRswypyZ@RAyGpt1tubRlPdomNW@zuW4ykZOBGKW9/nLtr/2mEsPPwFJyjX/qfbAZVfbU9Z3w5oulzrWtLDSMZkRSt4Fzxq/V2kPugaNHnMbUkAsUkmHWgmoIcbWYj5GQzOvqAzGrVITKapE2fme2zI3YFf@zVGSA0FWi7yjWjqHCQYMa7f4NjKbqt8y54ntlOthZq/TiZ0qbE1K0G/T0G0tT4cBfQqbxwX8 "Python 2 – Try It Online")
[We're no strangers...](https://tio.run/##7VbbbttGEH3nV0zkB5IRdaGcIikTPdgpYrgwFMNJUAS0GlDkSmJN7rLLpWQ1l193Z5YXUXak9KEFGrSCQJC7Z87cZzfbqKXgo7sjWCqV5d5gkAUyTDYquGVJXxXpLJH9UKSDTORq8Ozp8NkPT90nx@6Pg5grJjPJ8NmbC9lzezHvZZrOMI4eDYpcDmYxHzC@gmr5CNwutOTwHS7rrUutF96SYhjAz0yylD65A6Oh@wQRF3HIeMggzuHlSzh933tzAk/6QwS/OrkAt3@Mb2eTd3B2ebE6NuI0E1JBvsmNuRQphCJJWKhiwXOo9iL2e8EMI3cgj2Bcflq2Ax8/G0bE5iA4y5Iit3LEjmGCn7ZnAP7iOXCB3FKV39VawriF@vqBXKxseDSG0XabfplE56HzLg8WzIMOdKFG@8MpfnXAn8cJAyVgxoDdsrBQLJp2dkhIhN3GynLtrW6eoYEia@n33akDpjS3IBmsEYTQvmRBZO1I98NE5KxaY0mO5pVwdFGv6ccydeDKgVmuHDh1YIL7/pTC5WxjN8S/BmNNQEgZRqKdKIUwHoNpmbuxOYXuGNydJdTTDzJ0KrIm9kMG@wFD7z7DlU8cmcgse0oZ3NlEolN4AcNdllaeztNZkARYcRHMZBDeMJU/6jwAN/kYfcXGIxMCHqEe/Bh6GMCvODTZeq5NejRu2/SXbLlvg35MHAhTKlxMyasAc6pX10uqsAk6TtWKubG3ugRVES75k2nbFSp1ZPLuR4/g6KNrepDXfrWKsiylLa7bxuVlVqgFyrf9co@/Jvf423KdHTm/5073YwcaK4UKFDvkw/V1G9g7gPxVA9mtIu1@ZaxTW33AlBdts4cU59rnF80bdSgcUH6EHNSdy7TWPN2L7bf1BbPcwnqjuviAY6FQlsnxDGDSw36zDwTbabMIGbUZwmWAJatKEpx0B2g8pCkrvrJ7L/I5KcSyz1UkCtVfyxgTUvA4XMq6SA7o8VG6bI63smB7YfeHlB6jitddgtXrelfYLdM@npoqpsPFMj@Z9gMhpEQ5nMlodOTT63BKE4neRtMH8ObgabAPKSm/V@1OvW98ZEITTGMLwNm@p5GnTVC242I7oO7oRFww/iGTYoFFklWDgz6BxoD15VOn63Zt09geSWmQUTU49Fm6sEJqOlfw/GXYlkxpKtv3PGzQ8uAoeMiDlBHM8k2TTsYWnCgxyY4M@IJZxyMH3NFTzDX0gLZNy/70hWrV92jAkbqq@PF1VHMj9ccbb6UPKevGwdMaD6o/4syqFJGYAzdsM06CdBYFEHo9fUyKArsjtLGTGzPtz815FzsrImLYM0zShNDqvTJGXV1Q6EzbEH9F7mHN0NM1H1vxeNzYXc@XvdRl1FoTPIrnc/RthcFoAZAbS8/24zrETd66en7jPt7ULBK2/WNviheELAlCZplDEy8Rna5pb5dcWrK@2CYNb7NON5nIyUCM0kF/ufbXfl6K4TWwkFzj71oXNqOsnqq/Y17fWKpa26lCw6iPSJo2cMH4Qi095O44@ojTmApyiUIySBtQBSGuBvMmFJJ52/5AzDwRgbIapI33zIa5FrvmrwtFBgjdJTpHkXYMFXZqVG//r2PUXb9jzjU/KLOFnTVKL7@ltN4hRftBd78wUzI8/SFXutlkTjfTRKyY8V4UcMPFGtSSgSwSbFa65@QCIgHnxgl2R5LglTtNY5UyrswcLx6BgnMzRZGY38R8gZHSPGtRJBE3FYZN0WYO@r4e8A0IpJewKDbGOfxW5ArWAecBKIbkGxRdogVEOWc4@PjCOBNKBTh0bpjeLniERiu0zDAmbEVUguQX8aoCZDvrCRpAy5FY850NWXAIJPZ@pN2MWM6khu6gGr2h3Oxs5MEG30Q027Cdde0Hqo2Zpl0WFamBkUcLKcDY8UG4rAJBTZZTBtBVjJyEJcNjB2M7YwwNDJcU1VmhaJNSpwTmbrmhrJEJsTLOeR5HDNYMZkhZppASU3MshE4MRwu2@V3QwCQD17ogSttxGmjGE1zHI4TcDvIbQOT9pPwkKLna11THpzZthtuRNo6x7yxB35Wx1muxdNpm2vuW7AeOOcDvrRjW2d8g1irxf3uF/8dmz//G/jPG/gk "Python 2 – Try It Online")
[A keyboard...](https://tio.run/##rVZbd5tGEH7nV4zlByBCF2SnTkj0YDuxk9RVVNtpmyKqIlhZHCOgsFLshuSvuzPLVXKk9BxFR@c7y/LNdWdmie75LAx6D/sw4zxKjE4nsmPHv@f2HfPbfDGf@HHbCeedKEx459lR99nTI/3wQH/e8QLO4ihmiK1pGLf0lhe0IqFOkvb3Oosk7ky8oMOCJeTb@6A3oSaHaxgWr4bCLlyTYejAOxazOT0GGvS6@iEyLjyHBQ4DL4HTUzj52Lo6hsN2F8lnxxegtw9wdT74AOfDi@WB5M2jMOaQ3CfSNA7n4IS@zxzuhUEC@TuX/bNgkpRokLjQzx4VVYPPXyTJZVMIAxb5i0RJkNuHAT6qhgT486YQhKg75tlzvuezQEF7bTu@Waqw14de9Zp@UYzBQ@NDYt8wAxrQhIJtdi18aoA59XwGPIQJA3bHnAVnrtVYUUIi7M7jiq5WtoMIHQyjmn1TtzSQY7kixfYnJCG1HTPbVVak244fJizfY36C7mV0DFHsCZjNNbjUYJJwDU40GOB706J0aVXuuvgXZKwJcOiEUdFKlhzo90FW5NXcnECzD/rKFtpp2xEG5SoD9bEG9ZGG1rqGS5N0RGGkqBad4MpLVHQCL6G7qqV2Tm/nE9u3seJcmMS2c8t4std4RC7Po/cNH/dlsAMX7eBD18AEfiOgQRW5cGmvX/fpf/my7oOAgQbOnAoXj@TMxjMVu59mVGEDDJyqFc9GrWyFVEW4ZQ6seihU6qjJWM8e0TFGXTYgKeKqFWVWShWvWecl2alQC2SrzXJPviX35PtyjRU5s6Vbm7kdwY1DbnO2LYbRqE5sbWH@JYjsjpN1M3dWK7ze4srLuttdynMR88tyRR0KW4zvow7qztm8sGxt5Lbr9uxJomC9UV2McSwsuCIHeAew2MB@U7ckW6trCWO3rsGZ2ViyPFOCk26LGgPVZBWf@72R@YIMYtkn3A0XvP0p9vBAFoHnzOKiSLbYMVE6a47reME20taHlBijPCi6BKtXNy6xW6w23prco8tFkVNZfSSEKlEOZzI67Zq07Fo0kWjVsx7Ry4un5D5WSed7We/UdeddGcpkShUBZ/uGRrbKpFTjohpQD3Qj3rBgHMXhDRZJlA8OegQaA8rXtNHUm6osVVfS3I6oGjR6zEJYomq6V/D@ZdiWjAtVqmkY2KDZxbEInMCeM6IppizTzVijk0o8ZC22gxumHPQ00HtHeNbQAnotK2r6lWrVNGjAkbm8@HHZK3Sj6s@3xlJcUsqthrc1XlT/epGSGyIxDW7Zfd@35xPXBsdoiWsyXGB3OCp2cumm@qW87zxtSYoY9gyLaUII80aWo6YoKAym7oi5pPCwZgh1@Yni9ful38V82ag6y1ptgrvedIqxLTEZNQLqxtJTTa9IcXluTTG/8T1@qSkkrJoHhoUfCJFvO0yRuzJ@RDSaslpt6bSlfFVlGt5ycdzkYkAOYpa2xhuIeNUXmRh@Bi7iQPAfah9sUlY9eX97QfHFktfaShVKUnFF0rSBCxbc8JmBuhuauOIEJ6cMUSi25yUpp5CuknPlhDEzqv5AztQPba6UTBW/M0vNhdgoeL/g5EAoukSckSsCQ4ONgtXa/GtIRdevuDMKtspUtPPS6PB7Ros3ZGgz6QHG@NsZxEJK078hTVOdoEdwQHBI8JTgJ4IjgmcEzwm6BC2CPsHJFR1HmqKu8TjdFehHujrj8WhXoN8olapwdwaM8fr4RISb/krwO8FrgkuCa4KPBB8I3hK8JxgSmAQWwajIVxbuzomTqnB3TlyVrx9SX6fHw6ssYccEVwSvCM4IzgneELwj@JngguAFgSyyO7h@fVnP14@qr50Ttl5fuyUrz9fVm7dn11lHpX8S/EFwSvCbaDeCAcEvBBpBm6Aj0ltJV/naKVlr@dopWVm@/gM "Python 2 – Try It Online")
[Pascal's...](https://tio.run/##jVbbcptIEH3nK9ryAxChC8iybGI9xKlKardcWpeTPGxhNoVgZFGGgQyDYm8S/7q3m7ssS1ldqKHnzOnumb5M@ijXCbeej2EtZZrZo1HqCT96lN4Di4Yyj5eRGPpJPEqTTI7OZuOz6cw8mZjno5BLJlLB8DlYJWJgDkI@SAs6RTk@GuWZGC1DPmJ8A5X4GMw@dNbhGK7rqetCL3wmxTCCP5lgMb1yA6yxeYKIq9Bn3GcQZvD@PVz@Pfj0Dk6GYwR/eHcF5nCCo4@LL/Dx@mozUcI4TYSE7DFTViKJwU@iiPkyTHgG1VzAvuVMUTIDsgDm5aumG/Djl6IEbAUJZ2mUZ1qG2Dks8FW3FcBPuAKeILeQ5XslixjXUN/QE3cbHY7mYLXT9EkFOg@9L5l3x2zoQR9qtDN28a0HziqMGMgElgzYA/NzyQK3t0VCS9hDKDVTb3XzFA1M0o5@x3QNUIXagoT3HUEIHQrmBdrW6qEfJRmrZCzK0LwSji4WsuKxjg24MWCZSQMuDVjgvOPSdhnt3o3xV4AxJsCnE0airV3yYT4HVVO39@YS@nMwt0SoZ@il6FSgLfRdBn2HYfCS4cYhjjRJNd2lE9yaRKJLuIDxNkvnnP6Il17kYcQFsBSef89kdtTbATfnYb1i47EKHg9QD76MbdzAVxxatJ4XJh3Nuzb9L1te2lA8Fgb4MQUuHskHD8@0kH5fU4Qt0HGKVjwbvdWVUBShyFm4XVco1JHJfrl7BEcfTdWGrParE5RlKLW4fheXladCKVCO9q9789q6N79f19ta5wxMdz92VGBFIj3JDvlwe9sFDg4g/ymA7EGSdqcy1qitPmDKRdfsMe1z7fNFM6IMhQPKj5GDsnMd15rdvdhhV5@3zDSMN4qLr1gWcqmpHHsAEzbmm35gs40uSyKCLoO/9jBkZUmCle4AjY00ZcRXdu9FviWFGPaZDJJcDr@LEA8k56G/FnWQHNDj4OoyOT6LnO2FvSxSRRmVvM4SjF7TvsFscYfYNWVIzUVTf6r6ziKkxHVYk9HowKHh2KWKRCPL3YE3jafB7lLS@d50M/Wl8YEKzWYqLQBr@55EdptNactFW6CeqSPeMf41FckdBklaFQ56BSoD2tPPXt/s66rStqTYSykaDHotXdggNfUV7L8M05LJgkp3bBsTtGwcOfe5FzOCaY6qUmfswIkSD9kQHr9j2sQywLRmeNYwAJpWNf3nE8WqY1OBI3VV8OPQqrmR@se9vSmalHZvYLfGRvVvmGqVIlpmwD17nEdevAw88O1B0SaTHLPD1zGTGzP1X02/C40NETHMGSaoQhTq7XKP@kVAoTNdQ5wNuYcxQ09TfaOF83ljd11f9lKXu9ap4EG4WqFvG9yMDgC5MfR0J6y3uDm3flG/cR5vahot1p2J7eIFIY08n2nqWMVLRK@v6q3IJJH2pKtUvNX6uMlETgbiLh30lxf@6m/LZXgNzAUv8M@dC5tSRk@V3yGvbyxVrG1FoaLULZKqDVwxfifXNnL3jKLFFZgKco2LhBc3oApCXA3mk58IZrf5gZhVlHhSa5A63jMb5nrZLf8rl2RAUmRJcUZB4Rgq7NWowf5PT6mzfsucW35wTQv72Ci9/p3SeoYU7Qc9d4qE2RkrHanVmVFa8QS/5ku5CSdwin9zS27CFMwx/abVTMszxZs/PTv4GVhIP6UfDma1/AysM5iewmxMTxyfofwcJqdwhgqt0@KPQxScd6qfNbVe8evk1Cr@O/7CuXWyizdn5mn5qOT/AQ "Python 2 – Try It Online")
Basically wraps every char that appears in the output into a named function. Almost every ASCII printable character is OK for function name, so we don't need any two-char names, and one of them can be zero-char, which is assigned to the most frequent character.
[Answer]
# C++, Score = Whatever
```
#include <iostream>
#include <vector>
#include <stack>
#include <cstdio>
#include <cctype>
using namespace std;
vector<char> a[256], code;
stack<unsigned long long> st;
int max_depth;
void constant_gen(int depth) {
if (depth == max_depth) {
if (st.top() < 256 && a[st.top()].empty()) {
a[st.top()] = code;
}
return;
}
st.push(1); code.push_back('1');
constant_gen(depth+1);
st.pop(); code.pop_back();
if (st.size() >= 1) {
st.push(st.top()); code.push_back('"');
constant_gen(depth+1);
st.pop(); code.pop_back();
}
if (st.size() >= 2) {
int h = st.top(); st.pop();
int r = st.top(); st.pop();
st.push(h + r); code.push_back('+');
constant_gen(depth+1);
st.pop(); code.pop_back();
st.push(r); st.push(h);
h = st.top(); st.pop();
r = st.top(); st.pop();
st.push(h * r); code.push_back('*');
constant_gen(depth+1);
st.pop(); code.pop_back();
st.push(r); st.push(h);
}
}
int main() {
char ch;
max_depth = 1;
for (int i=0; i<5; i++) {
a[0].push_back("11+1<"[i]);
}
while (max_depth < 16) {
constant_gen(0);
max_depth += 2;
}
while ((ch = getchar()) != EOF) {
if (isdigit(ch)) {
ch = ch - '0';
}
for (int i=0; i<a[ch].size(); i++) {
cout << a[ch][i];
}
if (ch < 10) {
cout << ":";
} else {
cout << ";";
}
}
return 0;
}
```
Most of the code generates the constant table.
[Answer]
# [Python 2](https://docs.python.org/2/), 14.15 + 13.40 + ~~13.61~~ 13.55 + ~~11.85~~ 10.01 = ~~53.01~~ 51.11
```
def gen_prog(inp):
prog = '1(|"+1+)'
parts = []
prev_int = False
for c in inp:
if prev_int and c.isdigit():
parts[-1] += c
elif c.isdigit() and c != '0':
prev_int = True
parts.append(c)
else:
prev_int = False
parts.append(c)
for c in parts:
if c == '0':
prog += "11+1<:"
elif c[0].isdigit():
prog += '1' + bin(int(c))[3:].replace('0', '"+').replace('1', '()') + ':'
else:
prog += '1' + bin(ord(c))[3:].replace('0', '"+').replace('1', '()') + ';'
return prog
```
[Hello, World!](https://tio.run/##lVZbb6NGFH7nV5zgB2CNsUlS7ZaNHzYrbdoqcqPsrqqKUAvD2EbFDJ0ZclG3vz09M9x9YVtkWczwne9c5lwmfxFbmp2/jmArRM696TQPWZS@iPCZpI4odquUORHdTXPKxfTd29m7H966lxfuj9MkE4TljOD/ZE3ZxJ0k2SRXdJo2OpsWnE1XSTYl2SNU2yNwx9CRw3e4qz/dKb3wRSqGKfxCGNnJZWbD@cy9RMRtEpEsIpBw@PgRrn@ffP4Al84MwZ8@3ILrXODbzeIr3NzdPl5oa0Z3sFyuC1EwslxCssspE5AzNAB3s0gkqLfa5S@8FIhomhL1idcSMfmrIJrGbeAxzMuladnw9z@aFpM10IzkacFNjtg5LHBpeRrgk6who8jNRLmu9lKSmajPCdnm0YKzOZy3n@WjLDT1rzzcEA90GEON9mcBrnTw10lKQFBYESDPJCoEiQPd6rFIGfKcCNNt95MsRwtp3jHAdwMbDGa0IBY@IQihDiNhbPaknSilnFR7JOVoXwlHH9We@tvubLi3YcWFDdc2LPC7H8h42W3wZvhTYEwdiGQiIFEvTBHM52CYRj841zCeg9vbQj1OmKNTsbmwDhmsA4bJPsO9LzlymptWII@w9xGJruEKZn2WzkH9vFuFaYiJGcOKhdGfRPCzvcPoHcj5ESNHBoRZjIpwMfMwgkc8WrSuK5vO5l2j/psx@0aov4UN0U7mLh7KpxBPVe0@bWWSLdB1mbB4OlarjMo8wi1/EXR9kdmOTN5@/CQcnXQND3jtmNuPEElb3LiL4@W5yCoo307LvTkm9@b7cnpPzp@4wWnsVGEZFaEgQz48PHSBkwHkHwpInoXU7lfG2rXVA6Zcdc2eyTjXPl81b7JGYUD5CDlkfW53tebgJNbp6gtX3JQJh0mwxMZQCNPIcFgQ5mHFWQPBtrsslMVdhmgbYs6KkgSb3QCNhzQq5cFsQoaM6Iqun5Z6L5VjCXAR00I4TyzBwymyJNqymmZAp4/SZaF8YQU5CdtvWaqpiqyuGMxk17vHygkcHLUikbPGNL4Zhx0DKVEOOzQaHfvydRbI/iTfzoMDeDOHGuwhpTzr@27V7hsfG1AF1uStuGr1J6o6aKLS9o62Xb3KCbkh2TJndIMZk1ddRC5B9gTzmz52x5bRtiMZFa5mRoUkj0t50LWC/thAyt7YaOCyn0ZOwuNkg/3O2puxUoesdGlkpPUi0REqSWSnNWbG/pRuzDrIBsVe53g0FMYD54Zo@o6rr0cm5qGhGGn0UnfdsXvl6XvOYp6cDFIliY0bkxbvcqriI8vyL7wAbwd5GkbERIV4g9DHhtVuuXLLtAzZtrFUBwOwr0P2hP@t471RRgevlQXLFOtr52qnlTefqvSTrL7aVFnYy09Nq0epbEpwS7KN2HrIrdtqEkqMVWPuUIqFuwZVYSRZC/ocUUa81mcErVMaCrOF4s215a7lHrJfCyFtoKqECMNREivfUKXe0E9OPwiqu4LS0zIPC7W4m0bv3Xf1Np96uo7AXn8iaUpt@I2yND77Fw "Python 2 – Try It Online")
[We're no strangers to code golf, you know the rules, and so do I](https://tio.run/##7VZtb9s2EP6uX3FxPkiqX5VkaOcmH5IODTIEbpC2GArXC2SJtrRIpEZScYx1vz27oyVLsmN3AzZgxSYYhkQ@99z7kdlSR4IfPR1CpHWmhv1@5ssgWWr/kSU9nafTRPYCkfYzoXT/1cvBq@9eeifH3vf9mGsmM8nwvzsTsut1Y97NDJ1lHR70cyX705j3GX@AYvkQvDbU5PAdbsqtG6MXPpBi6MOPTLKUPnkHjgbeCSKu44DxgEGs4M0buPjUfX8OJ70Bgt@eX4PXO8a3y9FHuLy5fji2ZlKkcHc3y3Uu2d0dxGkmpIZMogG4ygMdo95iVS3VSiAQScLMliolQvZrzixLdUCFcLb6dNwO/Pa7ZYVsBoKzLMmVoxB7BiP8dIcW4BPPgAvklnr1XawljDuor@fL@YMLB2dwVG3TYyx0Wh@VP2dDaEEbSvR4MMGvFoxnccJAC5gyYI8syDULJy23wUIy7DHWjletxzxDC0VWM2DsTTpgS7sCSX@BIIT2JPNDpyHdCxKhWLHGEoX2reDoo1kzf1HagdsOTJXuwEUHRrg/nlC8OlXwBvgzYCwdCKgQkKgRpgDOzsB27GZwLqB9Bl5jCfX0/AydCp2Ru83gbjF0Nxlux8SRicxxJ5TCxiYSXcApDJostURdpVM/8bEwQ5hKP7hnWh1sJKORkKNnjDy0wechKsKPwRAj@IxHo8p1Y9PBWd2oP2fMphHmb9SBIKXaxaS89TGrZnURUZGN0HUqWMyOWykTVEe4NB5N6r5QtSPTcDN@BEcnPXsIqnTMa0aIJRWuXcepVV6oC1Zvu@VePCf34utyrYbcuOtNdmP7BiuF9jXb58Pnz3Vgdw/yZwNkj5q0jwtjO6XVe0w5rZs9oDiXPp@u36hHYY/yQ@Sg/ozSUvNkJ7ZX1@dPlUMFh0Vwh4Mh147N8bBgcogd5@4JdqfOImRYZwgiH2tWr0hw2O2hGSKNKXlw1iFDRnSl1dot9ZqUYwsoHYpc9xYyxuTkPA4iWdLs0TlG6VWjfJA52wnbHFlmqGpedgxWsje8xc6Z9PCo1TGdNY79xd6eGEiJcjih0ehwTK@DCc0nejuabMHX59Aau01Jub6td@2m8aENRWAdVYmbUb@jqyfrqFSzoxpXT3RCzhm/y6SYY8VkxRShT6CZ4Hxptb22a1fjiKKizJlRINnDHSW6VNA8NpCycWys4TRPg16swniO887dOGNJB3U6GRlYjUjUhFYkNGntgb15Sq/N2qoGw17WeLAvjFvO7aNpOm52nzkxtw3FSKOXLc9re6fD1oazWCc7g1RI4uDGosW7nOn4wHXHx8MJ3g6yxA@YgwrxBtFq22615NGS49o0trFV9wZgUwfNhL@s47W9ig5eK3PJDetT7WpnrW4@RevHvLzaFFXYqE/LKo9SGkpwzfhcR0PkbnXMSUgYt8TcoJT00zWqwBBZBXofCMmGlc8ImiXC104FxZtrxV3Kfebvck02CNNCTOJREhrfUGVrTd/d/SConApGT8W8X6jCXa713nxV73qroesZ2NNPzJYMrwugtPT5nElFt9lEPDDrk8jhnosF6IiBzBOmTBMqAaGAK@scZnmS4DU9TWOdMq5thTcVX8OVnaJIzO9jPseAGZ6FyJOQ2xqjp2lTgbnj@3wJAuklzPOldQW/5ErDwufcB82QfImiEVpAlDOGbcLn1qXQ2ofUv2dmO@chGq3RMssasQeiEiQ/jx8KQNZYT9AAWg7Fgjc2ZM7BlwL5jJshU0waaAO11hvIZWND@Ut8E@F0yRrrxg9UGzNDG@UFqYWRRwspwByYH0RFIGiqKMoAuoqRkxAxHC8Y2yljaGAQUVSnuaZNSp0WmLtoSVkjE2JtXXEVhwwWDKZIuUohJabkmAuTGI4WVPmd@@nKwIUpiJXt2N@G8RzXcUKR2766B0RuJuUHQck1vqYmPqVpU9wOjXGMfWMJ@qaMdd6JqFM309215G451gG@sWI5l3@DWK3E/@0V/h@bPf8b@88Y@wc "Python 2 – Try It Online")
[A keyboard so real you can almost TASTE it](https://tio.run/##rVZtc5tGEP7Or1jjD0CEkLCdJlGsD7YbO0ldRbWdtqlMVQQniykCehyOM1V/u7t7gADJUtpRNJpn4NjX53b3LvkiZnF08LgPMyGStNfpJC73wi/CfWChJbL5JOSWF887SZyKzssX3ZfPX9hHh/arThAJxhPOENvTmLftdhC1E2lOUfb3OlnKO5Mg6rDoHorlfbBbUNPDZxiWn4bSL9yQY@jAe8bZnF4jEw669hFKXAYeizwGQQpnZ3D6qX19AkdWF4XPTy7Btg7x6WLwES6Gl/eHypTHcxiPp5nIOBuPIZgnMReQcAwAVyNPBOi3WE2/pLmCF4chk5/SUsNnf2VMUVITUh/6@atumPD3P4risynEEUvCLNVTlO3DAF@NngL4C6YQxWibi/y9WAtZpKM/y@V39wbs9eGg@kw/GaGufkzdO9YDFVpQSo@6Dr6pMJoGIQMRw4QBe2BeJpjvqEbDCumwh0DodrUeRAlGGCe1AEa2Y4LGtUqIu59RCEUtzlxfb2hbXhinrFhjYYrx5eKYo1yTMJubcGXCJBUmnJowwO8jh/gyK/K6@JfCWDrgUSGgoQZNHvT7oOlak5xTaPXBbiyhH8tNMClfHxjrFow1C@1VC1cjspHEiW44tIWNj2joFI6h27RS26h384kbuliYPky46/3JRLq3shmNDTl4Ish9DdzIR0f40u0hg09kNKhSlzHt9etB/bdgVoOQMDDBm1Pt4qacu7ircvXzjIpsgKlTweLuGJWzmOoIl0YDp54LVTta6q3yR@KYpK31IC0Ts5sMsbCSa9Xl0nxfqAvyp816z57Se/Z1PbWhN2rbzmbZjpTlsXAF25bD7W1dsL1F8ncpyB4EeR8VwZpl1FtCOa6H3SWey5yPl0/Uo7DF@T7aoP6czUvPzkZZq@7PnaQ6FRwWwRgHQyZ0LcLDgvEedpyxhWyzbiXmft2CN3OxZkVuBIfdFjM9NCNLHvQlZWgRU1HVzVqvyTm2QCr8OBPWZx7g5mRR4M14aWaLzxFq541ywzO2UWx1ZMmhKqKyY7CS7d4Vdo5j4VErAjprdG2hrU8MNIl6OKExaH9Ej12H5hM9HThr4stzaCm7bpL2@qretavB@xoUxOpppS5H/YaudpasVLOjGlePdELesWic8PgOKyYppgi9As0EfaG27JahVeOIWEnlmVFIsvsxbXTpoHlsoMnGsbEUp3nqWUHqB3c474yVM5Z8UKdTkJ7SYKKmlBuhSat1tdVTehnWWjVI62WNe9toXEtum5lm4vLrEyfmeqDINGap2nbLPu6pK8linWwkqdDEwY1Fi3c52fGeYYwOew7eDpLQ9ZiODvEGobY0o1qyaUk3NBrb2KpbCVj1QTPhf/t4reXs4LUy45G0@li72in5zado/SAqrzZFFTbqU1HKo5SGElyy6E7MemhbNeVJSDJGKTNELe7Ol1KFDBmrhK69mLNelTMKTcPYFXolijfXynapdxt9yATFEMsWYhyPEl/mhi7Vpfn25h8KlVNB@qksb1eq5C6Wfodf9bv81PD1hNgj3svxRr4ryAdlsfgDFouFTXBAcEhwRPCc4DuCFwQvCV4RdAnaBH2C02valsUCbY3Hi12BfmSrMx7f7gr0u10oVbo7A@Z4c3Iq0138RPALwRuCK4Ibgk8EHwneEXwgGBKMCByC25KvPN2diVOqdHcmruLrm9TX2cnwOifshOCa4HuCc4ILgrcE7wl@ILgkeE2gSXYHN2@u6nx9q/rambDV@tqNrIKv67fvzm/yjlr8RvArwRnBz7LdCAYEPxKYBBZBR9JbaVd87UTWCl87kZXz9S8 "Python 2 – Try It Online")
[Pascal's Tree-angle](https://tio.run/##lVdbc6M2FH7nV5yQB2CNsYWvYeOHzc5spp2Mm8nuPnQc6sEgx0wxUCFymW5/e3okwIBv2zo2I46@852Ljo6U9I1vkth@v4QN52nm9Hqpx/zojXuvNLJ4vl1FzPKTbS9NMt6bTvrT0YQMB@SqF8acspRRfHbXCeuSbhh3U0mnKJcXvTxjvVUY92j8DKX4EkgHGno4hvtq6l7ahW/CMPTgV8roVrzGJth9MkTEXejT2KcQZvD5M9z83v36CYZWH8FfPt0BsQY4up1/h9v7u@eBsmbJFpbLdc5zRpdLCLdpwjikDB1AaezzEO2W0uwtKxT8JIqonMoqjYD@lVNFyUzIApgVr7phwt//KEpA15DENI3yTM8QO4M5vhqOAvgJ1xAnyM148V7KIhrraM/y2NOzARczsOtp8ZEe6ur3zHuiDqjQgQq96Lv4psJiHUYUeAIrCvSV@jmngasaLRahQ19DrpNaHsYpepikDQcWxDVBY1oNYt4LghBqMeoFekvb8qMko6WMRhn6V8AxRimTj83WhAcTVhk34caEOc4vXJEvs05eH78SjKUDvigEJGqlyYfZDDRdayfnBjozIC0R2rG8FIMK9LlxyGAcMHT3GR4WgiNNUt1wxRK2JpHoBq6h32ZpLNQv25UXeViYAayY5/9JeXaxtxitBbGPOHmpgRcHaAhf@g5m8EhE8zp06dPFrOnUf3Nm3wn5mJvgb0Xt4qJ88XBVpfRlI4psjqGLgsXVMWpjiagjFC3mbjMWUe3I5OznT8AxSKI5kFWBkXaGaFTjOk1cVqyL2AXF6LTeh2N6H36up7b0Fl3insb2JJYl3OP0XAyPj01g9wzyDwmkr1xYX5TOmpXXZ1y5brrdF3muYr7ejcQehTPGL5FD7M/NtrLsnsRaTXveKtNFwWERLLEx5FzXYjwsKHNwxxlnkm02WRIWNBn8jYc1ywsSbHZnaBykkSUP@i5lyIihqOpprY/COG6BjAdJzq0XFuLi5HHob1hFc8bmArWLjfKN5fQkbL9lyabK42rHYCUT5wF3jmvhUctDcdbo2g/tsGMgJephh0ang4UY9l3Rn8TIdg/gu3Nohz2kFGv90Ny1@84HGpSJ1bNaXbb6E7va3WWl7h11u3oXJ@QTjZcpS56wYtKyi4hXED1B/6F2SMfQ6nYkspLJM6NE0uelWOjKQPvYQMrWsbGDi37qW2EWhE/Y74y9M1bYEDtdOOkrrUw0lAoS0Wm1vrZ/Su/cOqgGyV7VuH8ujQfBnaNpBy5nj5yYh45ipjFKlZAOuXbUvWCxTk4mqdTExo1Fi3c5ueN9w1gMHBdvB2nk@VRHg3iDUDuaUYuIEOmGJto2btWzCdi3IXrC/7bxUSuyg9fKnMWS9b1xtVOKm0@59cO4utqUVdiqT0WpjlLRlOCOxk984yC3asqTUGCMCnOPWszb7lAlRpDVoK9@wqhTx4ygdZR4XK@heHOtuSu9x/i3nAsfErmFKMOjJJCxoUl1R989/UFQ1RWknZr5vFKNu93Zvf@p3d1Uy9YR2HujAEhjrDSkdmNGqcUD/CP7cgJDGOOPtOQERkD64jsqZ2qeEf5PIZ4N/ARspB@JLw4mlXwK9hRGY5j0xRPHU5RfwWAMUzRoj@UPhyi4alS2PbKPxDUc2/J3EC9c2cNDPJmQcfEo5f8C "Python 2 – Try It Online")
[Answer]
# [MAWP](https://esolangs.org/wiki/MAWP), 173.69 + ? + ? + ? points
```
%[25W|]%%0~%[{![1A1:]%1A[1A76W1M;]%69W5M;}]
```
This submission only uses the `1` and `+` and `;` instructions. Not very efficient, but works reliably.
`Hello, World!` all by itself took 10 minutes to run and give output. The result was 2258 bytes, and the rest of the strings are way bigger.
I think it's better for my computer not to run any more of the test cases.
[Try it!](https://8dion8.github.io/MAWP/v1.1?code=%25%5B25W%7C%5D%25%250%7E%25%5B%7B!%5B1A1%3A%5D%251A%5B1A76W1M%3B%5D%2569W5M%3B%7D%5D&input=Hello%2C%20World!)
[Answer]
# Python 3, 10.08 + ? + ? + 5.36 points
Code is a bit slow, still running tests.
```
import itertools
from difflib import SequenceMatcher
string = '''Hello, World!'''
def create_constants(string):
chars = ['1','"','+','*']
g = list(set(string))
combinations = []
consts = []
nums = []
for i in range(2,13):
combinations.extend(list(map(''.join, itertools.product(chars, repeat=i))))
print('Generated combinations')
codes = [ord(i) for i in g]
for combination in combinations:
stack = [2]
for char in combination:
try:
if char == '1':
stack.append(1)
elif char == '+':
stack.append(stack.pop() + stack.pop())
elif char == '*':
stack.append(stack.pop() * stack.pop())
elif char == '"':
stack.append(stack[-1])
except:
pass
if stack != [] and stack[-1] in codes:
nums.append(stack[-1])
codes.remove(stack[-1])
consts.append('11+'+combination)
if codes == []:
return consts, nums
in_order = []
consts, nums = create_constants(string)
for i in string:
in_order.append(consts[nums.index(ord(i))])
code = ";".join(in_order) + ';'
substring_counts={}
f=lambda s,n:max(l:=[s[j:j+n]for j in range(len(s))],key=l.count)
k = {}
for i in list(range(2,len(code)))[::-1]:
d = f(code,i)
if code.count(d) > 1:
saved = len(d) * code.count(d) - 4 - ((code.count(d) + 1) * 2)
if saved > 0:
k[d] = saved
try:
most_occuring = max(k, key=k.get)
code = code.replace(most_occuring, '()')
code = code.replace('()','(|' + most_occuring + ')',1)
except:
pass
print(code)
```
This is my first answer to a question of such kind. I'm also quite inexperienced, but with the combined forces of my knowledge and stackoverflow I managed to make something half-decent :D
]
|
[Question]
[
### Introduction
When you are given a boring text, you just want to get it over with as quick as possible. Let's observe the following text:
```
Ens colligi timenda etc priorem judicem. De quascunque ii at contingere
repugnaret explicetur intellectu. Adjuvetis hoc fortassis suspicari opportune
obversari vix eam? Dei praemia prudens hominum iii constet requiri haberem. Ima
sane nemo modi fuit lus pro dem haud. Vestro age negare tactum hoc cui lor. Ne et
ut quod id soli soni deus. At constare innumera is occurret ea. Nia calebat seu
acquiro fraudem effingo dicimus.
```
**Note:** This text has newlines for readability, while the test cases you need to handle don't have newline characters.
One way to skim text is to find questions that the writer has put into the text. For example, there is 1 question in the text above. Namely:
```
Adjuvetis hoc fortassis suspicari opportune obversari vix eam?
```
This can be done by splitting the text into sentences. A sentence will *always* end with one of the following punctuation symbols: `.?!` (others don't have to be handled). Other symbols than these are part of the sentence.
---
### The Task
Given a line of text consisting of only
* **letters (A-Za-z)**
* **numbers (0-9)**
* **spaces**
* **punctuation (`,.;:?!`)** (a sentence cannot start with one of these).
Output the questions that are in the text in any reasonable format. You may assume that the text will always have **at least 1 question**. Outputting *trailing* and *leading* spaces before and after a question is allowed.
**Important**: Next to a *punctuation* symbol, there will **never** be another punctuation symbol (e.g. `??` is invalid and will not be required to handle).
---
### Test cases
In the format:
```
Input
Output(s)
```
The test cases:
```
Huh? I haven't heard what you just said. Could you repeat that please?
Huh?
Could you repeat that please?
plz can i haz cheesburgr? i am cat pls.
plz can i haz cheesburgr?
This is a badly formatted question.Can u please help me,or my friends,with formatting this question ?thankyou.
Can u please help me,or my friends,with formatting this question ?
a.b.c.d?
d?
Does this question have a question mark? yes
Does this question have a question mark?
Why example.com resolves to 127.0.0.1 in 99.9 percent of cases?
9 percent of cases?
A? b? c? d!
A?
b?
c?
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the lowest number of bytes wins!
[Answer]
## Retina, ~~13~~ 11 bytes
```
!`[^.?!]*\?
```
[Try it online!](http://retina.tryitonline.net/#code=IWBbXi4_IV0qXD8&input=SHVoPyBJIGhhdmVuJ3QgaGVhcmQgd2hhdCB5b3UganVzdCBzYWlkLiBDb3VsZCB5b3UgcmVwZWF0IHRoYXQgcGxlYXNlPwpwbHMgY2FuIGkgaGF6IGNoZWVzYnVyZ3I_IGkgYW0gY2F0IHBscy4KVGhpcyBpcyBhIGJhZGx5IGZvcm1hdHRlZCBxdWVzdGlvbi5DYW4gdSBwbGVhc2UgaGVscCBtZSxvciBteSBmcmllbmRzLHdpdGggZm9ybWF0dGluZyB0aGlzIHF1ZXN0aW9uICAgID90aGFua3lvdS4)
```
!` print all matches
[^.?!]* any number of non-ending-punctuation symbols
\? followed by a question mark
```
Thanks to [@MartinEnder](https://codegolf.stackexchange.com/users/8478/martin-ender) for 2 bytes!
[Answer]
# Python, 46 Bytes
```
import re
f=lambda s:re.findall("[^!?.]*\?",s)
```
Call with:
```
f("your string here")
```
output on tests:
```
['Can u please help me,or my friends,with formatting this question ?', 'Can u please help me,or my friends,with formatting this question ?', ' Huh?', ' Could you repeat that please?', ' plz can i haz cheesburgr?', 'd?', 'Does this question have a question mark?', '9 percent of cases?', 'A?', ' b?', ' c?']
```
another idea, 77 bytes (in python3 you'd need a list around filter):
```
import re
f=lambda s:filter(lambda x:x[-1]=="?",re.split("(?<=[\.\?!]).",s)))
```
I'm new to this so this, so this could probably be much shorter.
*-17 (!) bytes thanks to Martin*
*-2 bytes by matching anything that is not "!","?" or "." (Getting close to the shell solutions, but I doubt I could save much more)*
[Answer]
## JavaScript, ~~35~~ 24 bytes
```
a=>a.match(/[^.?!]*\?/g)
```
Returns all substrings that start after a `.`, `?`, or `!` (or the beginning of the text) and end in a `?`.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 12 bytes
```
Í[^.!?]*[.!]
```
[Try it online!](http://v.tryitonline.net/#code=w41bXi4hP10qWy4hXQ&input=SHVoPyBJIGhhdmVuJ3QgaGVhcmQgd2hhdCB5b3UganVzdCBzYWlkLiBDb3VsZCB5b3UgcmVwZWF0IHRoYXQgcGxlYXNlPwpIdWg_IENvdWxkIHlvdSByZXBlYXQgdGhhdCBwbGVhc2U_CnBscyBjYW4gaSBoYXogY2hlZXNidXJncj8gaSBhbSBjYXQgcGxzLgpwbHogY2FuIGkgaGF6IGNoZWVzYnVyZ3I_ClRoaXMgaXMgYSBiYWRseSBmb3JtYXR0ZWQgcXVlc3Rpb24uQ2FuIHUgcGxlYXNlIGhlbHAgbWUsb3IgbXkgZnJpZW5kcyx3aXRoIGZvcm1hdHRpbmcgdGhpcyBxdWVzdGlvbiAgICA_dGhhbmt5b3UuCkNhbiB1IHBsZWFzZSBoZWxwIG1lLG9yIG15IGZyaWVuZHMsd2l0aCBmb3JtYXR0aW5nIHRoaXMgcXVlc3Rpb24gICAgPw)
A very straightforward answer.
```
Í "Remove every occurrence, on every line
[^.!?] "Of any character that isn't '.', '!', or '?'
* "Repeated any number of times
[.!] "Followed by a a '.' or a '!'
```
Thankfully, handling newlines, or verifying all test-cases does not add any bytes.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
f€“.?!”0;œṗfÐf”?
```
[Try it online!](http://jelly.tryitonline.net/#code=ZuKCrOKAnC4_IeKAnTA7xZPhuZdmw5Bm4oCdPw&input=&args=Y2FuIGkgaGF6IHJlZ2V4PyBpIGFtIGplbGx5Lg) or [verify all test cases](http://jelly.tryitonline.net/#code=ZuKCrOKAnC4_IeKAnTA7xZPhuZdmw5Bm4oCdPwrhuaPigbfDh-KCrGrigbc&input=&args=SHVoPyBJIGhhdmVuJ3QgaGVhcmQgd2hhdCB5b3UganVzdCBzYWlkLiBDb3VsZCB5b3UgcmVwZWF0IHRoYXQgcGxlYXNlPwpwbHMgY2FuIGkgaGF6IGNoZWVzYnVyZ3I_IGkgYW0gY2F0IHBscy4KVGhpcyBpcyBhIGJhZGx5IGZvcm1hdHRlZCBxdWVzdGlvbi5DYW4gdSBwbGVhc2UgaGVscCBtZSxvciBteSBmcmllbmRzLHdpdGggZm9ybWF0dGluZyB0aGlzIHF1ZXN0aW9uICAgID90aGFua3lvdS4K)
[Answer]
# Shell utilities, ~~43~~ 38 bytes
Thanks to [rexkogitans](https://codegolf.stackexchange.com/users/51534/rexkogitans) for trimming 5 bytes!
```
tr ? "\n"|sed "s/.*[\.!]//;s/.\+/&?/"
```
Pipe input in, like this:
```
echo Huh? I haven't heard what you just said. Could you repeat that please?|tr ? "\n"|sed "s/.*[\.!]//;s/.\+/&?/"
```
If if matters, I'm using:
- GNU `tr` 5.3.0
- GNU `sed` 4.2.1
- Microsoft's `cmd.exe`, shipped with Windows 5.1.2600
[Answer]
## Perl 5.10, ~~21~~ 18 bytes (with *-n* flag)
```
say m/[^?.!]+\?/g
```
Straightforward implementation of the question.
[Try it here!](https://ideone.com/EG3fmR)
[Answer]
# Ruby 1.9, 17 bytes
```
$_=$F
```
A 5 bytes program that must be invoked with the following command line options:
```
paF[^?]*[.!]
```
[Answer]
## Batch, 174 bytes
```
@echo off
set/ps=
set t=
:l
set c=%s:~0,1%
set t=%t%%c%
if "%c%"=="?" echo %t%&set t=
if "%c%"=="!" set t=
if "%c%"=="." set t=
set s=%s~1%
if not "%s%"=="" goto l
```
Reading a line from STDIN is a byte shorter than using `set s=%*`.
[Answer]
## PowerShell v4+, 43 bytes
```
([regex]::Matches($args,'[^?!.]*\?')).Value
```
Really straightforward. Takes input `$args` and feeds that in as the first parameter to a .NET `[regex]::Matches(...)` static function. The regex we're matching is `[^?!.]*\?` -- that is, any number of non-sentence-ending characters that are followed by a question mark. The static function returns an array of objects detailing what capture group, index, etc., but we only want the `.Value`s, so the return is encapsulated in parens and we call that property. This is where the v4+ requirement comes into play, as in prior versions you'd need to instead do something like a loop `|%{$_.Value}` or `|Select Value` to get the appropriate properties.
**Example without the parens and `.Value`**
```
PS C:\Tools\Scripts\golfing> .\what-exactly-was-your-question.ps1 "Huh? I haven't heard what you just said! Could you repeat that please?"
Groups : {Huh?}
Success : True
Captures : {Huh?}
Index : 0
Length : 4
Value : Huh?
Groups : { Could you repeat that please?}
Success : True
Captures : { Could you repeat that please?}
Index : 40
Length : 30
Value : Could you repeat that please?
```
**Example with the parens and `.Value`**
```
PS C:\Tools\Scripts\golfing> .\what-exactly-was-your-question.ps1 "Huh? I haven't heard what you just said! Could you repeat that please?"
Huh?
Could you repeat that please?
```
[Answer]
## Python 3, 91 bytes
```
def f(x,a=0):
for n in range(len(x)):
if x[n]in".!":a=n+1
if x[n]is"?":print(x[a:n+1])
```
**Saves 1 byte in Python 2:**
```
def f(x,a=0):
for n in range(len(x)):
if x[n]in".!":a=n+1
if x[n]is"?":print x[a:n+1]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Using `replace` rather than `match`. Works out at the same byte count.
```
r"[^?]*[.!]
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciJbXj9dKlsuIV0&input=IkE/IGI/IGM/IGQhIg)
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), ~~72~~ 69 bytes
```
>i:0(?^:"?"=?v\"!."@=?v=?v
^>l?v00. > ovr: .12< <
^ ~< ;!0^?l<<:
```
[Animated Version](http://mousetail.github.io/Fish/#eyJ0ZXh0IjoiPmk6MCg/XjpcIj9cIj0/dlxcXCIhLlwiQD0/dj0/dlxuXj5sP3YwMC4gPiBvdnI6ICAgIC4xMjwgIDxcbiBeIH48IDshMF4/bDw8OiIsImlucHV0IjoiYWI/ZGUhZWYuZ2g/Iiwic3RhY2siOiIxMiAyMyAyMSIsIm1vZGUiOiJudW1iZXJzIn0=)
## Explanation
[](https://i.stack.imgur.com/ddvoi.png)
The top row reads a character, pushes it onto the stack, and checks if it is `.`, `!` or `?`.
If it's a `!` or a `.`, we jump to 2,1 where there is a loop to clear the stack.
If it's a `?` there is a similar loop, futher to the right. Instead of discarding elements we reverse the stack first and print items instead of just discarding them. We then enter the same green loop but the stack is already empty so we will soon exit it. We push a 0 to the stack so the program doesn't crash here.
]
|
[Question]
[
# Introduction
A code page maps integer values to a specific character. We can visualize a code page like this:
```
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | q | w | e | r | t | z | u | i | o | p | a | s | d | f | g | j |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 1 | k | l | y | x | c | v | b | n | m | Q | W | E | R | T | Z | U |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 2 | I | O | P | A | S | D | F | G | H | J | | | | | | |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
```
The rows specify the first digit and the columns the second digit of the hex-number.
# The Challenge
Given a string of 16-255 unique characters, output the corresponding code page using the zero-based index of each character in the string as it's value.
The input `qwertzuiopasdfgjklyxcvbnmQWERTZUIOPASDFGHJ` for example would yield the table above.
* The output has to be in the exact same format as the table above. Only a trailing newline is optional.
* If the input length is not a multiple of 16, you need to start a new row for the remaining characters and leave the unused cells empty (=filled with 3 spaces).
* Each character is placed exactly in the middle of a cell, padded by one space to the left and right.
* The values in the first row and column are given by hex-numbers with the digits `0123456789ABCDEF`. Those are padded with one space to the left and right as well. You may choose to use lowercase hex-digits but you need to stick to one.
* The only characters present in the output are hyphens `-`, pluses `+`, pipes `|`, spaces , the digits for hexadecimal numbers and the characters from the input.
* Any builtins that are related to ASCII-art tables or trivialize the problem in any way are forbidden.
* You may assume that the input consists only of characters of a specific encoding. Please specify if that is the case.
* If your language can **only** handle ASCII input, you may assume ASCII-only input and repeated characters.
# Rules
* Function or full program allowed.
* [Default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission.
**Happy Coding!**
[Answer]
## Pyth, 60 bytes
```
K+*"+---"hJ16\+Vm++"| "j" | "d" |"+]+]d.HMJ.e+.Hk.[bdJczJNK
```
The leading newline is significant.
[Try it here.](https://pyth.herokuapp.com/?code=%0A%0AK%2B%2a%22%2B---%22hJ16%5C%2BVm%2B%2B%22%7C+%22j%22+%7C+%22d%22+%7C%22%2B%5D%2B%5Dd.HMJ.e%2B.Hk.%5BbdJczJNK&input=qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJ&debug=0)
[Answer]
# Python 3.5, 326 355 bytes:
(*+29 bytes since if the length of the last row is **not** a multiple of 16, unused cells should be left empty (although, in my opinion, it looks much better if those empty cells are just not even shown)*)
```
def f(r):o=' 0123456789ABCDEF';r=[r[0+i:16+i]for i in range(0,len(r),16)];print('+---'*17+'+\n|',end='');[print(' {} |'.format(h),end='')for h in o];print(''.join([str(e+' | ')if e.isdigit()or e.isalpha()else str(e)for e in''.join([str('\n'+'+---'*17+'+\n| '+x[0]+x[1])for x in zip(o[1::1],r)])]),end='');print(' |'+' |'*(15-len(r[-1]))+'\n'+'+---'*17+'+')
```
Works like a charm!
**Sample Inputs and Outputs:**
```
Input: 'hopper'
Output:
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | h | o | p | p | e | r | | | | | | | | | | |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
Input: 'honkhonkhonkhonkhonk'
Output:
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | h | o | n | k | h | o | n | k | h | o | n | k | h | o | n | k |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 1 | h | o | n | k | | | | | | | | | | | | |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
Input: 'hi'
Output:
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | h | i | | | | | | | | | | | | | | |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
```
I hope this is okay.
Also, here is another version I created for this challenge, which, although is an invalid candidate since it does **not** print out extra empty cells for the last row if its length is not a multiple 16, in my opinion outputs a much better looking page than the one required by OP, mainly because it does not even show empty cells if the last row is not a multiple of 16, but instead just shows filled cells, and that's it:
```
def f2(r):o=' 0123456789ABCDEF';r=[r[0+i:16+i]for i in range(0,len(r),16)];print('+---'*17+'+\n|',end='');[print(' {} |'.format(h),end='')for h in o];print(''.join([str(e+' | ')if e.isdigit()or e.isalpha()else str(e)for e in''.join([str('\n'+'+---'*17+'+\n| '+x[0]+x[1])for x in zip(o[1::1],r)])]));print('+---'*(len(r[-1])+1)+'+')
```
Here is a sample input and output for the inapplicable code above:
```
Input: 'ggreuuobgugoubgoubguorgoruguor'
Output:
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | g | g | r | e | u | u | o | b | g | u | g | o | u | b | g | o |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 1 | u | b | g | u | o | r | g | o | r | u | g | u | o | r |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
(As you can see, there are no empty cells shown in the entire table. This looks much better to me.)
```
[Answer]
# Excel VBA, ~~157~~ 146 Bytes (Cheating?)
Anonymous VBE Immediate Window function that destructively takes input from range `[A1]` and outputs to the `ActiveSheet` object.
### Golfed
```
[B1:Q1]="=Dec2Hex(Column(B1)-2)":L=[Len(A1)]:For i=0To l:Cells(i\16+2,i Mod 16+2)=Mid([A1],i+1,1):Next:For i=1To l\16+1:Cells(i+1,1)=i:Next:[A1]="
```
### Formatted
```
[B1:Q1]="=Dec2Hex(Column(B1)-2)"
L=[Len(A1)]
For i=0To l:Cells(Int(i/16)+2,i Mod 16+2)=Mid([A1],i+1,1):Next
For i=1To Int(l/16)+1:Cells(i+1,1)=i:Next
[A1]=""
```
### Input / Output
Given:
```
[A1]="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJ"
```
the generated output is
[](https://i.stack.imgur.com/NM6YD.png)
[Answer]
# Excel (Version 1911), 247
```
A1 =DEC2HEX(COLUMN(A1:P1)-1)
A2 'Input String
A3 =2+LEN(A2)/16
A4 =CONCAT(" ",C2#)
A5 =TEXTJOIN("
"&REPT("+---",17)&"+
",0,,"| "&MID(A4,B2#+1,1)&" | "&MID(TEXTJOIN(" | ",0,A1#,MID(A2&REPT(" ",16),HEX2DEC(C2#&A1#)+1,1)),B2#*64+1,61)&" |",) ' Output
B2 =SEQUENCE(A3)-1
C2 =DEC2HEX(SEQUENCE(A3-1)-1)
```
Sample Test
[](https://i.stack.imgur.com/Mqg6S.png)
# Excel (Joke answer), 88 Bytes
Not a valid solution, but fun
```
B2 'Input
C4 =DEC2HEX(SEQUENCE(,16,0))
B5 =DEC2HEX(SEQUENCE(1+LEN(B2)/16)-1)
C5 =MID(B2,HEX2DEC(B5#&C4#)+1,1)
```
Output
[](https://i.stack.imgur.com/oipow.png)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~65~~ 63 bytes
Code:
```
"+---"17×'+J©,žhAu6£¹J16÷)v„| ?N>iðëN<16B}y«ð17×ðñvy„ |ðJ?}¶?®,
```
[Try it online!](http://05ab1e.tryitonline.net/#code=IistLS0iMTfDlycrSsKpLMW-aEF1NsKjwrlKMTbDtyl24oCefCA_Tj5pw7DDq048MTZCfXnCq8OwMTfDl8Oww7F2eeKAniB8w7BKP33Ctj_Criw&input=ISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0-P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fiDCocKiwqPCpMKlwqbCp8KowqnCqsKrwqzCrsKvwrDCscKywrPCtMK1wrbCt8K4wrnCusK7wrzCvcK-wr_DgMOBw4LDg8OEw4XDhsOHw4jDicOKw4vDjMONw47Dj8OQw5HDksOTw5TDlcOWw5fDmMOZw5rDm8Ocw53DnsOfw6DDocOiw6PDpMOlw6bDp8Oow6nDqsOrw6zDrcOuw6_DsMOxw7LDs8O0w7XDtsO3w7jDucO6w7vDvMO9w77Dvw). Uses **CP-1252** encoding.
[Answer]
## JavaScript (ES6), 148 bytes
```
s=>(s=' 0123456789ABCDEF'+s+' '.repeat(15)).match(/(?!^).{16}/g).map((t,i)=>d+`+
| `+[s[i],...t].join` | `,d=`+---`.repeat(17)).join` |
`+` |
${d}+`
```
The `' 0123456789ABCDEF'` exists to populate the first column, but conveniently also covers the first row. The input string is then padded with spaces to allow it to be split into substrings of length 16, with the `(?!^)` preventing the leading space from being matched. The rest is just joining up the pieces.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~127~~ ~~126~~ 121 bytes
```
($d='+---'*17+'+')
($n="0123456789ABCDEF$args"+' '*16)|sls '.{16}'-a|% m*|% v*|%{"$($n[$i++-1]+$_|% t*y|%{"| $_"}) |"
$d}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0MlxVZdW1dXV13L0FxbXVtdk0tDJc9WycDQyNjE1MzcwtLRydnF1U0lsSi9WElbXQGozkyzpjinWEFdr9rQrFZdN7FGVSFXC0iUAYlqJRWg/miVTG1tXcNYbZV4oHiJViVIokZBJV6pVlOhRolLJaX2////6oVAd5RUlWbmFyQWp6SlZ2Rl51RWJJcl5eUGhrsGhUSFevoHOAa7uLl7eKkDAA "PowerShell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pF`, ~~134~~ ~~109~~ 106 bytes
```
@F=(@a=($",0..9,A..F),@F);shift@F;printf+($_="+---"x@a.'+
')."|%2s "x@a."|
",$a[$i++],splice@F,0,16while@F
```
[Try it online!](https://tio.run/##HcjbCoIwAADQd78ihpGyCzMoCBEm1LpAdCcoIqy0VkuXsyt9eyt6OxwV57JmDOOBw6LAsQGihDRQSAh3EeOurw8iKRj3VS7SIoGOvQ4AxBiDB4tIBVoVl4B3uapL/wBvCyA7WtoCwhXSSoptzDiiyKvfD0L@bMzlHufF6yoyFeldsj@e5POxvW3S82jeGk8Xs@5gGE6avN3pfTJViCzVBvdrhHrUYMW/ "Perl 5 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, ~~127~~ 120 bytes
```
@.=($",0..9,A..F);$\='+---'x@..'+
';$_=join'',@.,s;.{1,16};$.[$.++].sprintf'%-16s',$&;gre;s;.;| $& ;g;s;.{1,68};$\$&|
;g
```
[Try it online!](https://tio.run/##JcvLCoJAFADQfV8RMTmFM5dcJMVFMOi96U1QRvRQsUwnx8pev94UtD9HuElYVcoGq0QKrAJQZw2AdhmJY1Gdc04zG4DqOYpkbR3iIKKU2cAkwtNghvlGAksCur4CKZIgSj1a5IYpKSMa@omLP4ivPNHy6OM/mbVfcoj2yqGv1PnmJunjEsRiI/eefziG92x33Uan0bw1ni5mvcGwMWm2O93@JxZpEEdScRF@AQ "Perl 5 – Try It Online")
Previous version:
```
@.=($",0..9,A..F);$~='+'.'---+'x@.;$_=join'',@.,s;.{1,16};$.[$.++].sprintf'%-16s',$&;gre;s;.;| $& ;g;s;.{1,68};$~
$&|
;g;$_.=$~
```
[Try it online!](https://tio.run/##JcvLasJAFIDhfZ5CymlGyczBLAzKIRDBptaNdwRFxLYxJE2TMRMvrTGP3jHQ7c//ySBPOlp76DbhibcRe7yP6LcIKpdZDJkQwmJXDwl2bpxFKWPcQ64Ibza3nTsBbgAta4tK5lFaHNizsB3FOJgU5gHVI5UNMBsU0j9yujWqDDBLo26wQxcqrY@XIC9@T1Em9@rzEMZfyc/14/yefk9XL7PFevk2nvTnA/91OPrLZBFlqdJCJg8 "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~47~~ 45 bytes
Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for -2 bytes!
```
16ôí16jí15ÝhJš¬ðìsøv"+---"69∍=yS3j€ÀõšĆ'|ý,},
```
[Try it online!](https://tio.run/##AXMAjP9vc2FiaWX//zE2w7TDrTE2asOtMTXDnWhKxaHCrMOww6xzw7h2IistLS0iNjniiI09eVMzauKCrMOAw7XFocSGJ3zDvSx9LP//cXdlcnR6dWlvcGFzZGZnamtseXhjdmJubVFXRVJUWlVJT1BBU0RGR0hK "05AB1E – Try It Online")
**Commented**:
```
16ô # split the input into groups of (up to) 16
í16jí # right-pad the groups to 16 with reverse, left-pad, reverse
15Ý # push [0, 1, ..., 15]
hJ # convert each number to hexadecimal and join into string
# => "0123456789ABCDEF"
š # prepend this string to the list
¬ # get the string back from the list
ðìs # prepend a space
ø # zip the list and the string
v } # iterate over the list
"+---" # push the string "+---"
69∍ # extend it to length 69
= # print it without removing the string from the stack
y # push the current entry
S # split into a list of characters
3j # left-pad each to 3 chars with spaces
€À # rotate each string left
õšĆ # prepend and append the empty string
'|ý # join by "|"
, # print the string
, # after the loop: print "+---"69∍, which is still on the stack
```
[Try the first part with step-by-step output](https://tio.run/##fY@9TsMwFEZ3nuKqS0FKomRoJJAQYmFgY2JADE5yGzsktvFPW/ouDOytxMDAjMVzBSe00CqFb7Aly@fc@wlNMoZtm6TuDQ5lpGXNDBiKwLi0xp9GQKmElRrEFI6tBCNOIEnPYJTG1cX5kafcOkkrtx7IFCupCSUpeuHG4n1JCnNmKCicodIYQI3T/l@wfdq190km7nlfLq2mcBcHkAQQRZG/J/cDzIde71K54H6AASQ5BW6bDFW3EcUFKTBnDamB8AIqwfh3d20U4@UhcZfPl999FEr06DgOTy/Dq3Gn7WrXTJu/cPhYaffqVnsCAlqSHLf8/wv00e7d80smfwb2JYZ02z7OffulZUISXUzL6qF@WuSzjDc3t18)
[Try one loop-iteration with step-by-step output](https://tio.run/##bZG/TsMwEMb3PsXJSwaIVAgEioQQf1@AETG46bV2FGzLvgoiMSAGxMJDsLMyMgVepC8S7BLRNM1JJ1nWfb/v/Fk7PpZY1wNgW3EcM@gWM3MngASCIyvVDKIwFx0BS4f5yfGgGUtHi9e3jhIfCNUEJAFpKFDNSPi5ldJBb60cs7m1qAh827LleN2vc6bwXlJ5Nw6FdAR6CpnglmeE1rVXTvI@QIFTig2fAPJMhKWTpdzBvfSrO8MzdOsPXzx/VE@bIKuJE/5hmtgCuxta9fnz/v3Sfb1FE2Ljoc3yGLLAO0NlA@tyfEWP1VebkmupYFz6@/@vqusbBmwb2HBnN9nbTw8OR6dn5xeXV@z2Fw)
]
|
[Question]
[
# Introduction
The [Hausdorff distance](http://en.wikipedia.org/wiki/Hausdorff_distance) measures the difference between two subsets of a metric space.
Intuitively, a metric space is just some set with a built-in distance function; in this challenge, we will use natural numbers with the ordinary distance `d(a, b) := abs(a - b)`.
The Hausdorff distance between two non-empty finite sets `A` and `B` is given by
```
max(max(min(d(a, b) for b in B) for a in A),
max(min(d(a, b) for a in A) for b in B))
```
in Python-like notation.
The Hausdorff distance can be computed by finding the element of `A` for which the distance to the nearest element of `B` is maximal, and the element of `B` for which the distance to the nearest element of `A` is maximal, and then taking the maximum of these distances.
In other words, if the Hausdorff distance is `d`, then every element of `A` is within distance `d` of some element of `B`, and vice versa.
# Input
Your input is a single list of integers.
It only contains the elements `0,1,2,3`, which signify whether the given index of the list is an element of neither `A` nor `B`, only `A`, only `B`, or both `A` and `B`.
For example, the input `[0,1,1,0,2,3]` means that `A = {1,2,5}` and `B = {4,5}`, if we use 0-based indexing (which makes no difference, as our metrics are translation invariant).
# Output
Your output is the Hausdorff distance between `A` and `B`; in the above example, it is `3`.
If either set is empty, then the distance is not defined, and you shall return `-1`.
# Rules
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
# Test Cases
```
[] -> -1
[0] -> -1
[0,1,0] -> -1
[2,0,0,2] -> -1
[0,1,2,3] -> 1
[0,3,3,0,0,0,0,3] -> 0
[1,0,0,1,0,0,1,3,1] -> 7
[1,0,0,0,0,3,0,0,0,0,2] -> 5
[0,1,1,3,1,3,2,1,1,3,0,3] -> 2
[2,2,2,1,2,0,3,1,3,1,0,3] -> 3
[1,3,0,2,0,2,2,1,0,3,2,1,1,2,2] -> 2
[1,0,1,1,2,0,1,2,3,1,0,0,0,1,2,0] -> 4
```
[Answer]
# CJam, ~~53~~ ~~52~~ ~~46~~ ~~38~~ 37 bytes
```
3,q~f{f&:L,{L=},}$~ff{-z}_z+::e<W+:e>
```
Takes input on STDIN as a CJam style array:
```
[0 1 2 3]
```
[Here is a test harness](http://cjam.aditsu.net/#code=qN%2F%7B%22-%3E%22%2F0%3D'%2CSer%3AQ%3B%0A%0A3%2CQ~f%7Bf%26%3AL%2C%7BL%3D%7D%2C%7D%24~ff%7B-z%7D_z%2B%3A%3Ae%3CW%2B%3Ae%3E%0A%0A%5DoNo%7D%2F&input=%5B%5D%20-%3E%20-1%0A%5B0%5D%20-%3E%20-1%0A%5B0%2C1%2C0%5D%20-%3E%20-1%0A%5B2%2C0%2C0%2C2%5D%20-%3E%20-1%0A%5B0%2C1%2C2%2C3%5D%20-%3E%201%0A%5B0%2C3%2C3%2C0%2C0%2C0%2C0%2C3%5D%20-%3E%200%0A%5B1%2C0%2C0%2C1%2C0%2C0%2C1%2C3%2C1%5D%20-%3E%207%0A%5B1%2C0%2C0%2C0%2C0%2C3%2C0%2C0%2C0%2C0%2C2%5D%20-%3E%205%0A%5B0%2C1%2C1%2C3%2C1%2C3%2C2%2C1%2C1%2C3%2C0%2C3%5D%20-%3E%202%0A%5B2%2C2%2C2%2C1%2C2%2C0%2C3%2C1%2C3%2C1%2C0%2C3%5D%20-%3E%203%0A%5B1%2C3%2C0%2C2%2C0%2C2%2C2%2C1%2C0%2C3%2C2%2C1%2C1%2C2%2C2%5D%20-%3E%202%0A%5B1%2C0%2C1%2C1%2C2%2C0%2C1%2C2%2C3%2C1%2C0%2C0%2C0%2C1%2C2%2C0%5D%20-%3E%204) which converts all the test cases to this format and runs the code on them. Although the results are in the input field, they are not used by the code (remove them if you don't trust me :)).
## Explanation
First, we parse the input to get the two sets A and B:
```
3,q~f{f&:L,{L=},}$~
3, "Push [0 1 2]. 1 is for A, 2 is for B, and 0 we can luckily ignore
as we'll see later.";
q~ "Read and evaluate the input.";
f{ } "Map this block onto the [0 1 2] array, copying in the input for
each iteration.";
f&:L "Take the bitwise AND with each element of the input and store the
result in L.";
,{ }, "Get the length N, and filter the range [0 .. N-1] by evaluating
the block for each element.";
L= "Check if the bitwise AND at that index yielded something non-zero.
This gives an empty array for 0, A for 1 and B for 2.";
$ "Sort the three arrays. This has two important effects: a) it moves
the empty array resulting from 0 to the front, and b) if only one
of A and B is empty, it moves the non-empty one to the end.";
~ "Unwrap the array, dumping all three sets on the stack.";
```
And now we find the absolute differences and select the max of the mins:
```
ff{-z}_z+::e<W+:e>
ff{-z} "Turn A and B into a matrix of absolute differences.";
_z "Duplicate and transpose.";
+ "Add the two together, so I've got one row of distances for
each element in either A or B.";
::e< "Find the minimum of each row.";
W+ "Add a -1 in case one set was empty.";
:e> "Get the overall maximum.";
```
Note that we've kept the empty array resulting from the initial `0` at the bottom of the stack all the time, but empty arrays don't contribute anything to the output.
[Answer]
# CJam, ~~57 56~~ 52 bytes
I think this can be golfed a bit, but here goes:
```
q~ee_{W=2%},\{W=1>},]0ff=_W%]{~ff-{:z$1<~}%W+$W=}/e>
```
Input goes in like a CJam styled list, eg.
```
[1 0 0 0 0 3 0 0 0 0 2]
```
>
> 5
>
>
>
**How it works**:
The code is split in two parts:
Parsing the input into the lists `A` and `B`:
```
q~ee_{W=2%},\{W=1>},]0ff=_W%]
q~ "Eval the input array";
ee "Enumerate and prepend index with each element. For ex:
[5 3 6]ee gives [[0 5] [1 3] [2 6]]";
_{W=2%}, "Make a copy and filter out elements with value 1 or 3";
\{W=1>}, "On the original, filter elements with value 2 or 3";
] "Wrap stack in an array. Stack right now contains
enumerated A and B in an array";
0ff= "Get the index of the enumerated arrays. Stack is [A B]";
_W% "Make a copy and swap order. Stack is now [A B] [B A]";
] "Wrap this in an array";
```
Performing the required actions on the two pairs of `A` and `B`:
```
{~ff-{:z$1<~}%W+$W=}/e>
{ }/ "Run this loop for both the pairs, [A B] and [B A]"
~ff- "Unwrap [A B] and take difference of every pair";
{ }% "For each row in the matrix difference";
:z$ "abs each term and then sort";
1<~ "Take only the first element of the array";
W+ "Add -1 to compensate for an empty array";
$W= "Take max";
e> "Take max of the two maximums";
```
[Try it online here](http://cjam.aditsu.net/#code=q%7Eee_%7BW%3D2%25%7D%2C%5C%7BW%3D1%3E%7D%2C%5D0ff%3D_W%25%5D%7B%7Eff-%7B%3Az%241%3C%7E%7D%25W%2B%24W%3D%7D%2Fe%3E&input=%5B1%200%200%200%200%203%200%200%200%200%202%5D)
[Answer]
# Lua, 235 bytes
Definitely not a winner, but at least a fun challenge.
```
A={}B={}c={}d={}m=math p=m.min q=m.max u=unpack for k=1,#arg do for h=0,1 do if
arg[k]/2^h%2>=1 then A[#A+1]=k for i=1,#B do l=m.abs(B[i]-k)d[i]=p(d[i]or
l,l)c[#A]=p(c[#A]or l,l)end end A,B=B,A c,d=d,c end end
print(q(q(-1,u(c)),u(d)))
```
Input works like so:
```
lua hausdorff.lua <space-separated-sequence>
```
...and here's a test script:
```
local testcase = arg[1] or 'hausdorff.lua'
print('testing '..testcase)
local function run(args)
return function(expected)
local result = tonumber(
io.popen('lua.exe '..testcase..' '..args):read'*a':match'%S+')
print(args..' -> '..expected..' :: '..result)
assert(result == expected,
("for input %q expected %s but got %s"):format(
args, expected, result))
end
end
run''(-1)
run'0'(-1)
run'0 1 0'(-1)
run'2 0 0 2'(-1)
run'0 1 2 3'(1)
run'0 3 3 0 0 0 0 3'(0)
run'1 0 0 1 0 0 1 3 1'(7)
run'1 0 0 0 0 3 0 0 0 0 2'(5)
run'0 1 1 3 1 3 2 1 1 3 0 3'(2)
run'2 2 2 1 2 0 3 1 3 1 0 3'(3)
run'1 3 0 2 0 2 2 1 0 3 2 1 1 2 2'(2)
run'1 0 1 1 2 0 1 2 3 1 0 0 0 1 2 0'(4)
```
...produces...
```
testing hausdorff.lua
-> -1 :: -1
0 -> -1 :: -1
0 1 0 -> -1 :: -1
2 0 0 2 -> -1 :: -1
0 1 2 3 -> 1 :: 1
0 3 3 0 0 0 0 3 -> 0 :: 0
1 0 0 1 0 0 1 3 1 -> 7 :: 7
1 0 0 0 0 3 0 0 0 0 2 -> 5 :: 5
0 1 1 3 1 3 2 1 1 3 0 3 -> 2 :: 2
2 2 2 1 2 0 3 1 3 1 0 3 -> 3 :: 3
1 3 0 2 0 2 2 1 0 3 2 1 1 2 2 -> 2 :: 2
1 0 1 1 2 0 1 2 3 1 0 0 0 1 2 0 -> 4 :: 4
```
[Answer]
# Pyth, ~~43~~ ~~40~~ ~~39~~ 38 bytes
```
J+m0yQQLq3.|Fb?eS.e&Yfy:J-kT+hkT0JyJ_1
```
My algorithm operates directly on the input string and never converts these number. It only calculate once a maximum and never a minimum.
Thanks to @isaacg for saving one byte.
Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=J%2Bm0yQQLq3.%7CFb%3FeS.e%26Yfy%3AJ-kT%2BhkT0JyJ_1&input=%5B1%2C0%2C1%2C1%2C2%2C0%2C1%2C2%2C3%2C1%2C0%2C0%2C0%2C1%2C2%2C0%5D&debug=0)
## Explanations:
First I'll insert a lot of zeros in front of the input.
```
implicit: Q = input()
yQ powerset(Q)
m0yQ map each element of the powerset to 0 (creates 2^Q zeros, I said lots)
+ Q zeros + Q
J assign to J
```
Then I define a helper function `y`, which tells if the indices of a list (like the input one) appear in both sets A and B. E.g. `y([0, 1, 0, 0, 1, 1]) = False`, but `y([0, 1, 0, 2]) = y([3]) = True`.
```
Lq3.|Fb
L define a function y(b), which returns _
.|Fb fold b by bitwise or
q3 == 3
```
Afterwards I first check if the result is `-1`.
```
?...yJ_1 print ... if numbers appear in both sets (`yJ`) else -1
```
Now to the interesting stuff:
```
.e J map each pair k,Y in enumerate(J) to:
&Y Y and ... (acts as 0 if Y == 0 else ...)
f 0 find the first number T >= 0, where:
y indices appear in both sets in the substring
:J-kT+hkT J[k-T:k+T+1]
eS sort and take last element (maximum)
```
Notice, that I will always find a number `T`, since I already know that indices appear in both sets in the list J. The number is maximal `length(Q)`. This is also the reason for inserting the zeros. If there are at least `length(Q)` zeros inserted, `k-T` is always `>= 0`, which is necessary for the list slicing. So why do I insert `2^length(Q)` zeros instead of `length(Q)` zeros? In the test-case `[]` I need at least 1 zero, otherwise `yJ` will return an error.
[Answer]
# Mathematica, 88 bytes
```
Max[Min/@#,Min/@Thread@#,-1]/.∞->-1&@Outer[Abs[#-#2]&,p=Position;p[#,1|3],p[#,2|3],1]&
```
[Answer]
# Haskell, ~~145~~ ~~126~~ 124 bytes
```
s t x=[e|(e,i)<-zip[0..]x,t i]
d#e=maximum[minimum[abs$i-j|j<-e]|i<-d]
[]%_= -1
_%[]= -1
d%e=max(d#e)$e#d
f x=s(>1)x%s odd x
```
Test run:
```
*Main> map f [[], [0], [0,1,0], [2,0,0,2], [0,1,2,3],
[0,3,3,0,0,0,0,3], [1,0,0,1,0,0,1,3,1],
[1,0,0,0,0,3,0,0,0,0,2], [0,1,1,3,1,3,2,1,1,3,0,3],
[2,2,2,1,2,0,3,1,3,1,0,3],
[1,3,0,2,0,2,2,1,0,3,2,1,1,2,2],
[1,0,1,1,2,0,1,2,3,1,0,0,0,1,2,0]]
[-1,-1,-1,-1,1,0,7,5,2,3,2,4]
```
`s` filters the natural numbers according to a predicate `t` and the input list `x`. `#` calculates the maximum distance of it's parameters `d` and `e`. `%` catches empty sets A or B or takes the final maximum of `d#e` and `e#d`. `f` is the main function which calls `%` with set A and B.
Edit: @Zgarb found lots of bytes to save; @ali0sha another 2. Thanks!
[Answer]
# Perl, ~~56~~ 55
Added +2 for `-lp`.
The input list should be given on stdin without spaces, e.g.:
```
echo 1011201231000120 | perl -lp hausdorf.pl
```
`hausdorf.pl`:
```
s%%$z=$_&=$p|=$'|P.$p;$q+=!!y/12/3/%eg;$_=$z=~3?$q:-1
```
To support spaces between the elements of the input list just divide the final `$q` by 2 for a cost of 2 strokes
[Answer]
# Python 2, 124
This definitely feels suboptimal. Oh well.
```
lambda a,E=enumerate:-min([1]+[~l*(n<3)for i,n in E(a)for l,_ in E(a)if{0}|set(n*a+n/3*[5])>{0,n}>=set(a[max(i-l,0):i-~l])])
```
[Answer]
# APL (49)
```
{(⊂⍬)∊∆←(↓2 2⊤⍵)/¨⊂⍳⍴⍵:¯1⋄⌈/{⌈/⌊/⍵}¨(+,⍉¨)|∘.-/∆}
```
Testcases:
```
({(⊂⍬)∊∆←(↓2 2⊤⍵)/¨⊂⍳⍴⍵:¯1⋄⌈/{⌈/⌊/⍵}¨(+,⍉¨)|∘.-/∆} ¨ testcases) ,⍨ '→',⍨ ↑ ⍕¨testcases
→ ¯1
0 → ¯1
0 1 0 → ¯1
2 0 0 2 → ¯1
0 1 2 3 → 1
0 3 3 0 0 0 0 3 → 0
1 0 0 1 0 0 1 3 1 → 7
1 0 0 0 0 3 0 0 0 0 2 → 5
0 1 1 3 1 3 2 1 1 3 0 3 → 2
2 2 2 1 2 0 3 1 3 1 0 3 → 3
1 3 0 2 0 2 2 1 0 3 2 1 1 2 2 → 2
1 0 1 1 2 0 1 2 3 1 0 0 0 1 2 0→ 4
```
Explanation:
* `⍳⍴⍵`: get a list of numbers from 1 to the length of the input list
* `↓2 2⊤⍵`: for each value in the input list, get the first byte and the second byte
* `∆←(`...`)/⊂⍳⍴⍵`: for both lists of bytes, select the corresponding values from `⍳⍴⍵`. Store these in `∆`.
* `(⊂⍬)∊∆`...`:¯1`: if this list contains the empty list, return `-1`. Otherwise:
* `|∘.-/∆`: get the absolute difference between every pair of values, giving a matrix
* `(+,⍉¨)`: get a rotated and a non-rotated copy of that matrix
* `{⌈/⌊/⍵}`: for both matrices, get the maximum of the minimums of the rows
* `⌈/`: then get the maximum of that
[Answer]
# Perl, ~~189~~ ~~176~~ 157B
Now with 500% more state.
```
use List::Util qw'max min';@I=<>;sub f{$n=($n%2)+1;map{$I[$_]&$n?$_:()}0..$#I}sub i{@t=f;max map{$b=$_;min map{abs$_-$b}@t}f}$r=max i,i;print defined$r?$r:-1
```
Legible:
```
use List::Util qw'max min';
@I=<>;
sub f {
$n = ($n%2) + 1;
map { $I[$_] & $n ? $_ : () } 0..$#I
}
sub i {
@t = f;
max map {
$b = $_;
min map { abs $_ - $b } @t
} f
}
$r = max i,i;
print defined $r ? $r : -1
```
Example usage:
input
```
0
1
2
3
```
`perl golf.pl < input`
[Answer]
## Clojure, 167 bytes
```
#(let[P apply F(fn[I](filter(fn[i](I(% i)))(range(count %))))A(F #{1 3})B(F #{2 3})d(fn[X Y](P min(for[x X](P max(for[y Y](P -(sort[x y])))))))](-(min(d A B)(d B A))))
```
There should be a shorter way... Is there?
]
|
[Question]
[
## Description
Given an object (json), write code to extract all the keys from it. This is a question that I really wanted to ask everybody for a long time ago but I did not have time to write it up. It can be helpful in some cases in your daily work.
## Rule:
* You can use any parse function to get the JSON object, it does not cost you any bytes
* Since a JSON object is a data structure that is not available in some languages, you can use any kind of data that has a similar structure in your favorite language.
* To be clear, the input to your function should be a JSON object if it can.
* The object can have nested keys.
* The object can contain arrays and if it contains an array you will use the index of each element as a key.
* Output can be a list with any format but it is preferred to be line by line.
* The output keys can be arranged in **any order**, it does not matter.
* Shortest bytes for each language will be win.
* You can use any delimiter between each child key and its parent. Here I use `.` (please see the sample output for more detail).
* The key can be a special character. For example:
The input I got from @tsh
```
{"":{"":4,".":5},".":2,"..":3}
```
But this is a special case and it is not required to handle it. You are better to avoid it.
## Example
Given an object:
```
A = {
"name" : {
"first": "jane",
"last": "doe"
},
"lang" : ["html", "css"]
}
```
Then the output should be:
```
"name"
"name.first"
"name.last"
"lang"
"lang.0"
"lang.1"
```
The index key (`0` and `1`) are a little tricky here, so for some languages like Javascript, it can be `[0]` and `[1]` instead.
So the example below is also correct:
```
"name"
"name.first"
"name.last"
"lang"
"lang[0]"
"lang[1]"
```
## A Sample test case:
### Input:
```
{
"quiz": {
"sport": {
"q1": {
"question": "Which one is a correct team name in the NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriors",
"Houston Rockets"
],
"answer": "Houston Rockets"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"11",
"12",
"13"
],
"answer": "12"
},
"q2": {
"question": "12 - 8 = ?",
"options": [
"1",
"2",
"3",
"4"
],
"answer": "4"
}
}
}
}
```
### Output:
```
[
"quiz",
"quiz.sport",
"quiz.sport.q1",
"quiz.sport.q1.question",
"quiz.sport.q1.options",
"quiz.sport.q1.options.0",
"quiz.sport.q1.options.1",
"quiz.sport.q1.options.2",
"quiz.sport.q1.options.3",
"quiz.sport.q1.answer",
"quiz.maths",
"quiz.maths.q1",
"quiz.maths.q1.question",
"quiz.maths.q1.options",
"quiz.maths.q1.options.0",
"quiz.maths.q1.options.1",
"quiz.maths.q1.options.2",
"quiz.maths.q1.options.3",
"quiz.maths.q1.answer",
"quiz.maths.q2",
"quiz.maths.q2.question",
"quiz.maths.q2.options",
"quiz.maths.q2.options.0",
"quiz.maths.q2.options.1",
"quiz.maths.q2.options.2",
"quiz.maths.q2.options.3",
"quiz.maths.q2.answer"
]
```
This is my solution using [jq](https://stedolan.github.io/jq/download/):
```
jq -r '[paths|map(.|tostring)|join(".")]'
```
Full code:
```
jq -r '[paths|map(.|tostring)|join(".")]' file.json
```
The content of `file.json` is an object from input
[Answer]
# [JavaScript (V8)](https://v8.dev/), 72 bytes
An edited version to support literal `false`, `true` and `null` values.
```
f=(o,s)=>!o|[o]==o||Object.keys(o).map(k=>f(o[k],k=s?s+[,k]:k,print(k)))
```
[Try it online!](https://tio.run/##nZJBT9wwEIXv@RVTnxIREFlARSsFBBcqgajUHhCKcjDBu@t14kk9XhB089u3sUNBy@JW7CWOv3nzMvOUOX/gVBnZ2t2H49VqkseYUpKffMFlgWWe43L5/W4uKrunxBPFmOw1vI1VfjKJsVBlqnI6pZ0iVeVYpa2R2sYqSZLVJP4dATC9qGsGY3Bn6sCE1yQc8S8eWbPwxJ0eaN544BxcizRk2RjYnGvB0gHWfGD3KFhPOt9Ycz11jQWb2aZmKbCKiJVRl0TDaEkUDYP14l8L@cz@fsQTatHYNTQIsw32YiDIStRujJuZrGaAWoAkqNCYPjGwgjfglgGp4fr87PRl@DUXbJ0H9SbFRtELrsUj3KJRcN5nSB9YeNUVEpzpqagFwaXU06DwAut7oeGn5VbADTdGGgyKvy3IooYfWClh2Yam/GAfrulRGJfJP5q711v3ZsEabme0Xf5HsANfIYftIs72QwFkWbAyClYOPptU77UeT/ougdH/E8hGsAvH20cQ2ia45kGocPjZ9Q@DP0c0PLtk9Qc "JavaScript (V8) – Try It Online")
---
# [JavaScript (V8)](https://v8.dev/), 69 bytes
Takes a native JSON object as input. Prints the results, using a comma as the delimiter.
```
f=(o,s)=>[o]==o||Object.keys(o).map(k=>f(o[k],k=s?s+[,k]:k,print(k)))
```
[Try it online!](https://tio.run/##nVJNS8NAEL3nVwx7SmgU0ypKIS16UVAU9CAScljTbbvdZCfubBU/8ttr0vhBbVexl4V58@bNvMfO@COnzMjS7jweLRbj2MeQgniQYBrH@PZ2dT8Tmd1V4pl8DHYLXvoqHox9TFQaqpiG1ElClfZVWBqpra@CIFiM/VcPgGleCAZ9aIq6HEtDlvWBzbgWLGzBnLfYCAWrkaqBa1BPmsGETW2RsxBYRsRSrwq8dkvgee2Omvwwly/sc8kSoRKNXYFaYrSGfQgIshJ1c8btVGZTQC1AEmRoTG0erOAFNGZAarg8OR5@HL@igmWjQbVIstZcEi7FE9yhUXAyz3PaILFkXSDBsZ6IXBCcSz1xEk8xHwkNN5ZbAbfcGGnQST6bk0UN15gpYdkaJ93gh2t6EqbJ5Jfh6quqviVYwe2Utsv/ADpwCDFsF3G05wogipydrrPT@29StdZqPOGPBLp/JxB1YQeOto/A5cZps@dq7P/X/r7zc3jtWwWLdw "JavaScript (V8) – Try It Online")
### How?
This is a recursive function walking through the keys at the root level and then in each sub-tree of the structure.
We need to process recursive calls on objects and arrays and to stop on strings and numbers. This is achieved with `[o]==o||Object.keys(o)`:
```
type of o | [o]==o | Object.keys(o) | string coercion example
-----------+-----------+-----------------+-------------------------------------
array | false | 0-based indices | ['foo', 'bar'] -> 'foo,bar'
object | false | native keys | {abc: 'xyz'} -> '[object Object]'
string | true | n/a | 'hello' -> 'hello'
number | true | n/a | 123 -> '123'
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 75 bytes
```
f=o=>Object.keys(o+''===o||o||0).flatMap(k=>[k,...f(o[k]).map(i=>k+'.'+i)])
```
[Try it online!](https://tio.run/##DchBDoMgEADA5wCRbtoeSfAHTR9gPCAurbJ1jWCTRn07NZnTjO7rkl@GOV8m7rGUYNnWz25EnyHiL0muhLDW8r6frgoCufxws4y2bqIGgCC5ia2Cz5mDrWMlQFSDalXxPCUmBOKXDHJzZlqJdGfysqL2JjhKqHsj3kjEQqNpbvre6mC241Cq/AE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~108~~ ~~146~~ ~~115~~ 92 bytes
+38 bytes to fix test cases for objects inside arrays.....
-31 bytes because we can take a parsed JSON object as input now.
-17 bytes by removing the duplicated `flat_map` usage.
```
f=->j,x=''{z=j==[*j]?[*0...j.size]:j.keys rescue[];z.flat_map{|k|[r=x+k.to_s]+f[j[k],r+?.]}}
```
[Try it online!](https://tio.run/##nZJbSwMxEIXf/RXDvhRsG9yqKMpaKoJXKlhBJASJ67TdS5M1k8Xaun/ddW1FqTWKnYfAnDk5MF9i8vvnsuwHzYO4MQ5qtekkiIOAr8eizdc3GGMxo2iCYi9mCT4TGKQwRy72J6yfSns3ktn0JXnhJhjXE2b1HYl6n8c8EQ1TbzNRFGWWW4I@P@tddlkmDSH0ro9Ou8ygfBDldA2q8h7zaOLtwbybKZRpYxekudFf0j4CkGykVTX1boZROAStECICCaE2BkMLFuUIlBxVsgI7ROgedtpeYzlLZ@9JVEXxpeHM0MUnuNUmgcM8TemHiJnrQhN01ABTJDiP1MBpPNbpAyroWWkRbqQxkTZO84nOyWoFVzpM0JK35BI/bCQVPaF5Z/Pr9eKzK75CvJG0Q1rtJbahDjsQwGqY/Q0XBN93TlrOyeZ/WVVZi3ga3wi0/ibgt6AJu6sjcGzDq/JanqjKse6mi8PWfzFsOT/J2vwsXj/2KJsmJq3eAA "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~122~~ ~~135~~ ~~122~~ 119 bytes
```
f=lambda d:`d`[0]in'{['and sum([[str(k)]+['%s.'%k+q for q in f(v)]for k,v in(enumerate,dict.items)['{'<`d`](d)],[])or[]
```
[Try it online!](https://tio.run/##nVJhb9MwEP2eX3GyNDlRTdWkQaDAhFqgIIH2AT5MKIo0N3FW08ZubWcbi/LbyyVFoNEFtCZKfPfu3bPu2dsfbqVVtN@X5xteLQsORXJVXKWTTCrapJSrAmxd@WlqnfHXQTZK6Zkd07P1aAelNrADqaD0b4Ksy9bsBnNfqLoShjvBCpm7sXSiskFKG/oatTO/CDKWZoE2abYvRAkLRJKtkcoBZUDH3zVqlAgGr3rUW/gNmZEkZGROEtK0hJG3GKRNm2H4jiRdxEjzvkVSG3he38E7nCxJEjOSY4yMApeQNURg9x1pM3yDnkydsI4mDeUUm@gdTSaM3tMkallDBWaoT5fdig0L32s8wIfsanlPEjhkPWK32rgH0IEYHmG/BHBfqRVWyeVK5ivQSoC0kGtjRO7ACV6B4pXofL6Yz94Qdqyit52GRZH0qNgTLsQtfNNmDfN6s7GPSPSsz9rCTF2LjbDwSarrQeIHvSmEgq8OjxguuTHS6EHyx9o6reCLztfCkSNO9sg8XNlbYTpP/tHc/s7aPxKk4m5lT/P/OYzgBZzDaRaHkyEDwnCwEg1Wpk91CrUe2sP@ciD6vwNhBM/g5ekWDE0zOOZ0qBA/dfx48HJ4h38b7CM29ab9F3sxm/4E "Python 2 – Try It Online")
Now handles an even broader class of inputs, including `lists` of `dicts`.
[Answer]
# [PHP](https://php.net/), ~~147~~ 146 bytes
```
function f($j,$t){foreach($j as$k=>$v){if(is_array($v)){echo trim($t.="$k.",'.')."\n";f($v,$t);$t=str_replace("$k.",'',$t);}else{echo$t."$k\n";}}}
```
[Try it online!](https://tio.run/##RY/RasQgEEXf9ytkEFSQfMCmaT@kLUHM2JhNNKi7UILfnhpTiA/CvWfmwKzjur99rOU3T6eT9Y4YTidJk9iMD6j0WCJRkT66d/oSmzXcxl6FoH55yWJDPXqSgl04TU0H9NGAZA0TDXw5aIvsdchamrqYQh9wnZVG/j/HKss4R6yioijkWMw571Vt@BS96wfUfkDOthspD5xaEMidnLFWxoaY4E5gUg5BXmBWZz94hNrmExbgfg7J5zU7pmUGSa5Cx3gufd8yk@XQJwpJGBPt/gc "PHP – Try It Online")
I'm sure that this is far from best solution in PHP, but I tried my junior talent. :D
```
$json = '{
"name" : {
"first": "jane",
"last": "doe"
},
"lang" : [
"html",
"css"
]
}';
/** We need to define a text string variable. */
$text = ''; // or keysChainString
/** Assume that our json is decoded. */
$array = json_decode($json, true);
/**
* Function that extract all multidimensional array keys.
* The result will be as:
* - firstKey
* - firstKey.firstSubKey
* - firstKey.firstSubKey.firstSubSubKey
* - firstKey.secondSubKey
* - secondKey
* - etc.
*/
function extractAndFormatMultidimensionalArrayKeys($array, $text){
/**
* Iterate through array.
*/
foreach($array as $key => $value) {
/**
* Check if key value is an array.
* Echo key appended to previously declared $text variable.
* Then make a recursive call to this function on that array.
* After that, delete the key from text string.
*/
if(is_array($value)) {
echo trim($text .= "$key.", '.') . "\n";
extractAndFormatMultidimensionalArrayKeys($v, $t);
$text = str_replace("$key.",'',$text);
/**
* If the value is not an array, echo the text concatenated with the key.
*/
} else {
echo $text . "$key \n";
}
}
}
```
[Answer]
# [Red](http://www.red-lang.org), 159 bytes
```
func[s][r: :rejoin g: func[s m][foreach k keys-of m[print p:
r[s k]if map? t: m/:k[g r[p"."]t]if block? t[repeat n length?
t[print r[p"."n]]]]]g ""load-json s]
```
Doesn't work in TIO since `load-json` was introduced recently, but works fine in the [Red](http://www.red-lang.org) console:
[](https://i.stack.imgur.com/l8p2Y.png)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~39~~ 27 bytes
```
MapIndexed[Echo@#2&,#,∞]&
```
[Try it online!](https://tio.run/##fZLfSsMwFMbv9xSHDHZjB6abKNRNNxAVdYheDBm9CO3ZGtcmW5Ix0XnvU/hwvkhNUis6/7QQkkPO9/vO1xbMZFgwwxNWTnvlFVucixQfMJ2cJJk8boatoBm8vbzGrdKgNhR6cLghghVIoN13@ylX2vgDuWcCSQAkZ3UllUg2/QAarihmvvhEMlPk7l6iNXne9KOGkw4r6eWKP9bSeiGVqQ9LWu@Y0GtUFeBMrrSRAm5kMkejiUNVj1WyqlyK6uI440kGUiBwDQwSqRQmBgyyAtw4wAXYKGA0HBx9VZELp6E/nI9wDXdSzWG4ynNHI5dSw0DMMEcNF1zMvlqw7acyT1HArWEGYcyU4lL5vm3jNocqKNtkv0em/5@bhk7k@4h7sAP7NkXr/9PBln@669oo9auXoB2Hrj2TZfgbrfsTRkNow0FF@ystj/GUjlu61ZDujRrTif@f4qhxrbgwk7guhXFUvgM) This function represents JSON arrays as `List`s and objects as `Association`s. The function takes a JSON object as input and prints a set of part specifications to the standard output, each on their own line and preceded by `>>` . A part specification is a list of indices, where each index is a 1-based number or a string wrapped in `Key`. The index of a parent object is printed after those of its children. The output for the first example is:
```
>> {Key[name], Key[first]}
>> {Key[name], Key[last]}
>> {Key[name]}
>> {Key[lang], 1}
>> {Key[lang], 2}
>> {Key[lang]}
```
If the `Key` wrapper is undesirable, it can be removed using [a 36-byte function](https://tio.run/##fZLfSsMwFMbv9xSHDHZjp7abKNRVNhCV6RC9GFJ6EdqzNa5NtiRj/pn3PoUP54vUpLUy558WQnLI@X7f@dqc6hRzqllMi0mvuKLzC57gAybhaZyKsOnt7Q7xsR2MopbTdN5f36JWoVFpF3pwvCac5kigHdj9hEmlywO5pxyJAySjdSURSNaBAw1b5NOy@ExSnWf2XqwUeVkHfsNKe5X0Ysmeamk1F1LXh4Vb7yhXK5QV4FwslRYcbkQ8Q62IRVWPUTKqTPDq4jhlcQqCIzAFFGIhJcYaNNIc7DjAOJhMYDTon2yqiLnVUJ/OR7iCOyFnMFhmmaWRS6Ggz6eYoYIh49NNC6b9TGQJcrjVVCOMqZRMyLJv27jJoQrKNJkPk6r/53Y9K/J9xAPYgUOTovH/5WDLv7tv21y3XEsJt2PRtWey8H6jdX/CXA/acFTR/kqrxJSUjl261ZD29RuTsPyfIr9xLRnXYVSXvMgvPgA):
### Wolfram Language (Mathematica), 36 bytes
```
MapIndexed[Echo[#2/.Key->N]&,#,∞]&
```
The original challenge's formatting can be achieved with [a 54-byte function](https://tio.run/##fVLLTgIxFN3zFTclYeOAzoDRBEFhowYlBhbEkFk0wx2mMtNCW4IP3PsVfpw/MrYdx@CzTfq4ufecc0@bUZ1gRjWLaB538mu6vOQzvMfZ9EYyrs/G2mzzEYvjFKfVYL8xwId6d@iRBglrXtV7e3kNa7lGpX3owMmWcJohgXrXnmMmlXYXckc5Eg9ISsvITCDZdj2o2CCfu@ATSXSW2rxIKfK87bYrFjoooFdr9lhCq6WQurys/PJEudqgLAguxFppwWEkogVqRSxVMQySQWWCF4mThEUJCI7AFFCIhJQYadBIM7DtAONgXIJhv3e6iyKWFkN9KB/iBm6FXEB/naaWjVwJBT0@xxQVDIyLuxJM@blIZ8hhrKlGmFApmZCu7rtw40NhlCkyT5Wo//v2AwvytcVD2IMj46LR/6ngm37/wJb5vlsdhN@01KVmsgp@Y2v9JPMDqMNxwfaXW47GsTTt0iqatLNdiafuP4XtivuD07AMBWE7fwc):
### Wolfram Language (Mathematica), 54 bytes
```
MapIndexed[Print@StringRiffle[#2/.Key->N,"."]&,#,∞]&
```
[Answer]
# [Julia 1.0](http://julialang.org/), 57 bytes
```
!x=[(k->["$k";"$k.".*!x[k]]).(keys(x))...;]
!x::String=[]
```
[Try it online!](https://tio.run/##rVJBT8IwFL7vV7w1HjaFxQFGAxkGYqKJhoMciFl2aEbDyrZ2tl0Y/vnZlYMkbIKJPby23/f19Xuv3ZYZxX5V13YVhE7an4boKkUTHTzkXdtVmEaR6zkp2Uuncl3P8yaRZVfj8VIJyjZBGNVbCOCJxsqxQA/0WdIvBMH0CDO4LLhQLcThkN/BGJYXinImjSQ8oY1kQXbwwUUK8zLLJOq1q964hBnbkIxIeNX2O4XPPFsTBkuFFYEVFoJy0Sl@4aVUnME7j1Oi2mTRKaT7RGRTlqkKrRIaJ8AZASoBQ8yFILECRXAODOcaZqASAov57LHlAoSZ3BFxyPW7H/dne7REOVaJ/IfnQf4t6gHyfRMHJg7R@QbcwQ3c6590tromZ1dBh7yDP5ht/BmTwyaMLjDqD6APD5c4HZ3tvJ5cy1pTWWR479hbt/4G "Julia 1.0 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 114 bytes
```
f=function(x){if(is.null(n<-names(x)))n<-seq(x);unlist(Map(function(y,z)c(z,if(is.list(y))paste(z,f(y))),x,n),,F)}
```
[Try it online!](https://tio.run/##PYxBEoIwDEWvwnTVzFQvoGzduXbdKa3WKQFJq4Dj2WsKA1n9l/@SIWdXu4Qm@g7lCF/vpKcjphAkng@oW0u8BmAg@@J4Shg8RXnVvdwPJzWDkbNar5d@Aug1RctbVwDUqBCUusAvO7ko5XtVV0t2fqDIIJ4arVBV0Cs2nRVQEO@bKh6xDawIQ1S6xr69sbTVvdnFm8em@7DEk/8 "R – Try It Online")
Defines a recursive function which takes an R list, possibly named, and returns the list of names using space as a separator. Here, a named list (or sub list) corresponds to an object in JSON, and an unnamed list corresponds to an array in JSON.
]
|
[Question]
[
*This challenge is related to some of the MATL language's features, as part of the [May 2018 Language of the Month](https://codegolf.meta.stackexchange.com/questions/16337/language-of-the-month-for-may-2018-matl) event.* *Associated challenge:* [Function clipboard: copy](https://codegolf.stackexchange.com/questions/164712/function-clipboard-copy).
---
# Introduction
MATL's *function clipboard* stores ("copies") the inputs to the four most recent calls to normal, input-taking functions. *Normal* functions are the most common type of functions in MATL. *Input-taking* means that the function takes at least one input. The stored clipboard contents can be pushed onto the stack ("pasted").
This challenge will take the clipboard contents as input. It will be assumed that all functions that have produced that clipboard state took one or more positive integers as inputs. So the clipboard state can be represented by a list of lists of numbers. (For more information on how the clipboard is actually filled see the related challenge; but that's not necessary for the current one).
### Interpreting the clipboard contents
**Example 1**
The *first* inner list refers to the *most recent* function call, and so on, Thus the clipboard state
```
[[11, 28], [12, 16], [4], [5, 6]]
```
indicates that the last function call took two inputs, namely `11`, `28`; the second-last call took inputs `12`, `16`; etc. (This clipboard state is produced by the code in the first example of the related challenge).
**Example 2**
If *there have not been enough function calls*, some trailing inner lists in the clipboard will be empty:
```
[[7, 5], [], [], []]
```
(This is produced by a program that simply adds `7` and `5`).
**Example 3**
Function calls can have *any number of inputs*, but always at least `1` (functions taking no inputs do not change the clipboard state). So the following is also possible.
```
[[3], [2, 40, 34], [7, 8, 15], []]
```
### Accessing the clipboard contents
The contents of the function clipboard are pushed onto the stack using MATL's function `M` (which, by the way, is not a normal function, but a clipboard function). This function takes a positive integer as input, and pushes some of the clipboard contents onto the stack, as follows. With reference to the clipboard state in example 1:
```
[[11, 28], [12, 16], [4], [5, 6]]
```
* `1M` returns *all inputs* to the most recent function call. So, for the considered example, it gives `11`, `28`.
* Similarly, `2M`, `3M` and `4M` return all inputs to the second, third and fourth most recent function calls. So `2M` gives `12`, `16`; `3M` gives `4`; and `4M` gives `5`, `6`.
* Numbers beyond `4` select *individual inputs* to function calls that took *more than one* input. So `5M` returns the *last* input to the *most recent* such call. In our case this gives `28`. `6M` returns the *preceding* individual input, which is `11`. `7M` returns the last input of the second-last call, that is, `16`, and `8M` gives `12`. Now, `9M` gives `6`. Note how input `4` is skipped because it was the *only* input in its function call. Lastly, `10M` gives `5`.
For the clipboard state in example 3:
```
[[3], [2, 40, 34], [7, 8, 15], []]
```
* `1M` gives `3`. `2M` gives `2`, `40`, `34`. `3M` gives `7`, `8`, `15`.
* `4M` has *undefined behaviour* (for the purposes of this challenge), because there have only been three function calls.
* `5M` gives `34`. `6M` gives `40`. `7M` gives `2`. `8M` gives `15`. `9M` gives `8`, `10M` gives `7`.
* `11M`, `12M`, ... also have *undefined behaviour*.
## The challenge
**Input**:
* the clipboard state, as a list of lists, or any other reasonable format;
* a positive integer *n*.
**Output**: the result of calling function `M` with *n* as input. The output will be one or several numbers with an unambiguous separator, or in any reasonable format such as a list or array.
Clarifications:
* The clipboard state consists of four lists of numbers. Some of the trailing lists may be empty, as in examples 2 and 3. If preferred, you can input the clipboard without those trailing empty lists. So example 3 would become `[[3], [2, 40, 34], [7, 8, 15]]`.
* All numbers in the clipboard will be positive integers, possibly with more than one digit.
* The number *n* is guaranteed to be valid. So for example 3 above, `n` cannot be `4` or `11`.
Additional rules:
* Input and output can be taken by [any reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* Programs or functions are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default).
* Shortest code in bytes wins.
## Test cases
```
Clipboard state
Number
Output(s)
[[11, 28], [12, 16], [4], []]
2
12, 16
[[11, 28], [12, 16], [4], []]
5
28
[[7, 144], [12], [4, 8], [3, 4, 6]]
1
7, 144
[[7, 144], [12], [4, 8], [3, 4, 6]]
10
4
[[30], [40], [50, 60], [70, 80, 90]]
2
40
[[30], [40], [50, 60], [80, 90]]
7
90
[[15], [30], [2, 3, 5], [4, 5, 10]]
3
2, 3, 5
[[15], [30], [2, 3, 5], [4, 5, 10]]
7
2
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~56 51~~ 47 bytes
~~-5~~-9 bytes thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni?tab=profile) (pattern match to ensure length > 1 and using `do`-notation over list comprehension)!
```
c!n=([]:c++do l@(_:_:_)<-c;reverse$pure<$>l)!!n
```
[Try it online!](https://tio.run/##lZHdasJAEIXvfYqjCElwpEaNf9VSKBT6DMtSQhxr6HaVzdo@vp3dVOmdSNhhZuc7OTPJvmw@2ZjzueraTar0qhoMtgeY5/R9JU@2HlaPjr/ZNdw/nhyv@08m63bt@ausLTbYHjpAvUNpDDw3PoYGfs9WGoBjf3IWaSYVm4bj5dHV1qP3WtaGt62i15GOqhKyicZ6CFNbbiBu@GD/crCerW8CY9ijEmPH5RZ97Grj2SF92CRIMlQJViso9Wa91tELsBfaJuEFrXkq@2ah/Nmz43b0tCJYgstEUKEbhKLsdNqVNmFApErlOWG80ASVjwn5LGTTELSmMV0uw8J0Cy9ISeuKzqU/nbZoxAhROCFIOhNBThfoHtGI1D/BZBSxGIuRIDGbS7aQsxy1a0j/huJKz0kt/9F5Ee0jIxvLHMXfXIWMGgQTujbuUInNOPL6LLgOFamJnKl8xxnNJZN/PvsF "Haskell – Try It Online")
### Pointfree, ~~58~~ 55 bytes
-3 bytes thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni?tab=profile) (moving `([]:)` and replacing `id`)!
Alternatively we could use this pointfree version
[`(!!).(([]:)<>map pure.(>>=reverse).filter((1<).length))`](https://tio.run/##lZHBbtswDIbvfoo/RQFLgOrFSZy0gePLhgE77AlUHwyHSYwpsiGr29vPo@Ql6K3oQQQpfr9/Ur404y8yZuquQ@88vjW@yX72tu@OEKKspEwSsZA44HUSi4XMhND1XpbVtRkwvDnKRFUdHP0mN5LMTp3x5ITIS5kZsmd/kXK6Np3lDxz7BOhOaIyBp9HHMMJfyHIDcOTfnIWQXJEZKV4OrrMeD9@bztBxVjwk3NFtqmxao3yC6SyNKB8rnMl/7a0n60dGDHm07OuoOeIR82gQXw4pUok2xX4PrX9YX9fRCrA32qbBY/YW7cLKUP65kKN5ctEqWAUX3qXFIghZmSTzRocwH4TWea6weq4VdL5SyLch24RQ12qlbpdhX/URXijNrTu64/5mM6MRU4jCtQKnWxbk6gZ9RrRU@p1gvYxYjMWSkZjtOHvm87Kc1@D@B4o7vVP65R2dF9E@Mrwxz1H8n6vgUYNgre6NT6jYZhX5emK8DpXSaz4bfset2nHG/3z7tz2Z5jxOT@0w/AM "Haskell – Try It Online").
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ḊƇUẎ⁸;⁹ị
```
[Try it online!](https://tio.run/##y0rNyan8///hjq5j7aEPd/U9atxh/ahx58Pd3f8PLz866eHOGf//R0cbG8TqKESbgElTAx0FMzDLHMiyAGJLg9jY/0YA "Jelly – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 [bytes](https://github.com/abrudz/SBCS)
```
{⍺⊃⍵⍪∊⊖¨⍵⌿⍨1<≢¨⍵}
```
[Try it online!](https://tio.run/##jZBPS8MwGMbv/RQBD10h25ou3eZQRHZxAxXcbmOHrE212H80GSjiSRAddniZNw/qZYhXL14E/Sb5IjPp2AaCfw7N@6bP70mevCQJiu4pCeLD2exMZG9idCGyV5E9i6uRGN19TNXu5l1kU7Qhrh/z/flMZPdgl/gR8IaRw/04AgU2HIQ@Y7I3NE3p2@7nQ6gzwGmYBIRT4MUp6Lb2QSGMXd/zqQt4DIhLEm40cscR5wlrlMvOEeElxolzTE9kHx3SkhOHZZ6SiDmpn/CybWHT3go3Mcbr2MT1tUWjaZ64vBXZ2FIPGU86B025dndanXmoLmWcpsvYmsblD@k4k1RufBGjp3mvH1A2DHgD6LBdaMvRGJ4skhlP2p39PUMNZsm2IpeegAIqDgijrqFM@TAXejPwk0FMUneuvJ6v4gBHWpimW7rKovd6CEGr3oc9ZEFUlRXLr9/XNd3@k0ALogYRxjmhZKjgCsSwOqfMf2HLQBVTqWqxTVhVtWbCugnXzZyr/cytoMoyu60uUaIFK9DO77Uh@nbUL9TsCw "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 57 bytes
```
a=>n=>a.map(e=>e[1]&&a.push(...[...e].reverse()))&&a[n-1]
```
[Try it online!](https://tio.run/##FY3LCoMwFET3@YqsSgLXYHxUi8RdvyJkcbHX2mITSVo3pd9udTEwh@EwT1wxDfGxvDMfbrSNZkPTe9OjeuEiyPRktTudUC2fNAmllN1DTkVaKSYSUsp9tT7TbjetLR1wWwCvcuBldUADvAWu66M71zFmNRRQAq/hDA20cAGdOzWGeMVhOi6/jPMh@BRmUnO4i1GgFCRlx36y2/4 "JavaScript (Node.js) – Try It Online")
This is an anonymous, curried function. Run it with `( function code )(clipboard)(n)`
## Explanation
```
a=>n=>{
// The strategy is to append the individual clipboard inputs to the end of a,
// after the function calls (lists). We then return a[n-1] to offset JavaScript's
// zero indexing.
a.map(e=>{
e[1]&& // if this list has more than one element...
a.push(...[...e].reverse()) // add each element to a, in reverse order.
// reverse() modifies the original array, so we have to use [...e] to "clone" e
})
return a[n-1]
}
```
[Answer]
# JavaScript (ES6), 72 bytes
Takes input in currying syntax `(clipboard)(n)`.
```
a=>m=>a[m-1]||(g=r=>(r=r|a[k][1]&&a[k].pop())?--m<5?r:g(1):g(!++k))(k=0)
```
[Try it online!](https://tio.run/##nZBBbsMgEEX3PQXdRIyCE7BN7FTFOQhigdLEah0Hi1Rd@e7ugImqyps2SIy@xLynGT7sl70d/fvwmV3d22k6q8mqpleN1X0mzDjSVnnVUK/8aHVntDCrVQibwQ0U4JBl/as8@JeWCsDyvF53ALRTHKaju97c5bS5uJaeqdZCMJLXhhEtckbELqQyFGOA5gAkne2WzA1P/zLIX4a8XtAVImU505FkJLoKRjDugkMEB9Jz60MGjgo0LOGCRyRWybE9pgpTjXfP778QYP5H@oes0vZI75e0kHHMyODP4bwyzS9xpSgo0urp@RFFdVdM3w "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~60~~ 56 bytes
thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) for -4 bytes.
```
lambda l,n:(l+sum([b[::-1]for b in l if b[1:]],[]))[n-1]
```
[Try it online!](https://tio.run/##lZDLCsIwEEX3/Yq7bHGEpk8N9EtiFi1aLMQoti78@joZH@BC1EWGO5kzz9N12h99NvfNZnbtodu2cOR17Bbj5RCbzmi9VLY/ntFh8HAYenRGaWvJ2CQxnqPztBunEQ1MBMQZwRilCNnKslTsqyqoIhhrEwpU@ROlAlVzqCjulBAEyckJLKsXm/4By5B5KoTYkrMrUTWrFb91@oTrz/A7mMtSpfSTMLfhv/IxCO@s3ot@ZyMbReH6nsLtPeTUmguczoOf0MeO4JP5Bg "Python 2 – Try It Online")
[Answer]
# Java 8, 110 bytes
A lambda (curried) taking the clipboard state as an `int[][]` and the number as an `int` and returning `int` or `int[]` (a single number may be returned through either type).
```
s->n->{if(--n<4)return s[n];else{int i=0,l;for(n-=4;(l=s[i].length)<=n|l<2;i++)n-=l>1?l:0;return s[i][l+~n];}}
```
[Try It Online](https://tio.run/##jZFNb9swDIbPzq8gChSQEVuIg3Qo6o@ilwE7DDv0aPig2nKmTKENSe4QZN5fz@jIbYJih15EiiIf6iV34lXEXS9x1/w69cOLVjXUWlgL34VCOC6COWidcGRahULDjqr44JTm7YC1Ux3yr7OTfUMnt9KUVVlFn0mM4MfLTtauKKAX1knITzYuMC6OqmVxjNkmNNINBsGWWKVSW3lU6EDlq0inbWcYxvkmZTq3paq4lrh1P8Msxz86W6dquQzpXRfJo35Ype8kVZV6@Zd443gK0sVHma@damBPE2DPzijclhUIs7XhNJDgSiE0wgnIAeVvuA5PacExSSJY34@Rv6wjSL7Ml81s7yLwoTGlg8QAm7QhIZOUTEZ2NTlLcnz3wI8LjLSDdpR4nhoXfa8PbPpOOPsYTszACwBi74VzsjkHVQtsBigkzVjLrr0omDsF70XU5rLKJ2PEwXLXeTRjV3Ue6juP0zHt6z80n3dhXFU8H0jPnneD4z29Of22BO4B7Oa2eYBbexMBRhdd4RlBhHExnv4B)
## Ungolfed
```
s ->
n -> {
if (--n < 4)
return s[n];
else {
int i = 0, l;
for (
n -= 4;
(l = s[i].length) <= n | l < 2;
i++
)
n -= l > 1 ? l : 0;
return s[i][l + ~n];
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
Díʒg<Ā}˜«s<è
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f5fDaU5PSbY401J6ec2h1sc3hFf//R0cbmsbqKEQbG4BIIx0FYx0FsIAJkNZRMDSIjeUyBwA "05AB1E – Try It Online")
**Explanation**
```
D # duplicate input list
í # reverse each
ʒg<Ā} # filter, keep only elements that are longer than 1
˜ # flatten
« # append to original list
s< # decrement the second input
è # get the element in the list at that index
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
!S+(m;ṁ↔f(¬ε
```
[Try it online!](https://tio.run/##yygtzv7/XzFYWyPX@uHOxkdtU9I0Dq05t/X////R0YaxOtFGQGwMxCY6pjpmOuZAVmzsfzMA "Husk – Try It Online")
### Explanation
Pretty much a direct port of the Haskell answer:
```
!S+(m;ṁ↔f(¬ε -- example inputs: [[1],[2,3],[4],[5,6,7],[]] 7
S+ -- concatenate itself with itself modified by
f( -- | filter
ε -- | | length 1
¬ -- | | not
-- | : [[2,3],[5,6,7],[]]
ṁ -- | map and flatten
↔ -- | | reverse
-- | : [3,2,7,6,5]
-- | map
-- | | pure
-- | : [[3],[2],[7],[6],[5]]
-- : [[1],[2,3],[4],[5,6,7],[],[3],[2],[7],[6],[5]]
! -- index into it: [2]
```
[Answer]
# [R](https://www.r-project.org/), 58 bytes
```
function(M,n)c(M,unlist(lapply(M[lengths(M)>1],rev)))[[n]]
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NXJ08zGUiW5uVkFpdo5CQWFORUavhG56TmpZdkFGv4atoZxuoUpZZpampGR@fFxv5P0wCrNNZJ1jDSMTHQMTbRBDLNdSx0DE1BLE1NHUMDzf8A "R – Try It Online")
Takes `M` as a `list` of vectors `c()`; so replacing `[[` with `list(`, `[` with `c(` and `]` with `)` should transform the test cases into R test cases.
For inputs `n<=4` with "undefined behavior", returns `NULL` and for other invalid inputs, throws a "subscript out of bounds" error.
```
function(M,n)
[[n]] # take the nth element of
c(M, ) # M concatenated with:
unlist( ) # the individual elements of
lapply( ,rev) # in-place reversals of
M[lengths(M)>1] # elements of M with length > 1
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~12~~ ~~14~~ 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
àJ├∙ε╝F▀ÿi☻Ia
```
[Run and debug it](https://staxlang.xyz/#p=854ac3f9eebc46df9869024961&i=[[11,+28],+[12,+16],+[4],+[]],+2%0A[[11,+28],+[12,+16],+[4],+[]],+5%0A[[7,+144],+[12],+[4,+8],+[3,+4,+6]],+1%0A[[7,+144],+[12],+[4,+8],+[3,+4,+6]],+10%0A[[30],+[40],+[50,+60],+[70,+80,+90]],+2%0A[[30],+[40],+[50,+60],+[80,+90]],+7%0A[[15],+[30],+[2,+3,+5],+[4,+5,+10]],+3%0A[[15],+[30],+[2,+3,+5],+[4,+5,+10]],+7&m=2)
Explanation:
```
vsc{%vfr$r+@]|u Full program, unpacked, implicit input
vs Decrement the number and get the list
c{ f Copy and filter:
%v Length not equal to 1?
r$r Reverse, flatten, and reverse again
+ Concat orig array and and modified array
@]|u Index, wrap into array, uneval
```
## Stax, 12 bytes
```
Å{b≈\☼╣Δ@░ ‼
```
Unpacked:
```
{vsc{%vfr$r+@}
```
This is a block, so I can get rid of the `]|u`, but I don't know if this is valid as it's packing a block.
[Answer]
# [J](http://jsoftware.com/), 33 22 bytes
-11 bytes (1/3 shorter) thanks to FrownyFrog's solution!
```
{0;],|.&.>;/@;@#~1<#&>
```
[Try it online!](https://tio.run/##jc5NCsIwEAXgfU/xsNAmEOKkTdra2NKLuBAxiBsXXfpz9TilXSiIuhgY8j7y5hzD2GkQWlC8kt@pm85079eDH9KH2aZZH2Wy0shDp3Mo3FuEMUmOh9MFBQKEMQpFI70whYKppIf12LezcD@FmUTN79ZyYAoPYRVYQ5QKvFZygfSvnM4qiVt4hCMOaEI1bw3PhhZXf3ZvpmRjnGcHjvh@rnJyrnZ8y@tf3118Ag "J – Try It Online")
## My initial solution:
# [J](http://jsoftware.com/), 33 bytes
```
<:@[{(,[:<"0@;[:|.&.>(1<#)&>#])@]
```
Not happy - I'm pretty sure it can be golfed much further.
## Explanation:
A dyadic function, taking the clipboard state as its rigth argument, the left argument is `n`
`<:@[` subtract 1 from the left argument
`{` selects the `i`th element (calculated above) from the list on its right
`(...)` the entire list
`#` copy
`]` from the list of clipboard state
`(1<#)` the sublists with length greater than 1
`|.&.>` rotate each copied sublist
`<"0@;` raze and box - puts each number into a separate box
`,` append the new list to the list of clipboard state
`@]` makes the entire verb in (...) monadic
[Try it online!](https://tio.run/##jc5BCoMwEAXQvaf4KGgCISTRqE20eA9xUUpD6aYLl23Pno7oooXSdjEw5D/y5xLD3EsoOKjYuWG8MTG6LlWDH91d5nLPdJfxfJ9NfJgiT1KJIvSygMDDIcxJcjqerzAIYFoLmJZ7po2ArrlH5XFwq7A/hV5EQ@9VRYE2HqwSIA1WCtBa8w2qf@VyVqmohYZZRYFaUENbS7NTm2s@uzdTktHWkwNFdD9VWb5WW7rl9a/vLj4B "J – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V) + [coreutils](https://www.gnu.org/software/coreutils/manual/coreutils.html), ~~53 45 43 42~~ 40 bytes
-9 bytes thanks to [DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem?tab=profile) (using `VGÇ /d` over `:,$g/^[^ ]*$/d`, `D@"dd` over `"aDÀdd` and `!!` over `:.!`)!
My very first attempt at [V](https://github.com/DJMcMayhem/V) (tips welcome!), the below code is using circled characters (eg. `ⓞ` for `\xf`) for readability:
```
jäGⓞVGÇ /d
ⓞò!!tr \ \\n|tac
jòHD@"ddjdG
```
[Try it online!](https://tio.run/##K/v/P@vwEnf@MPfD7Qr6KVz8hzcpKpYUKcQoKMTE5NWUJCZzZR3e5OHioJSSkpXi/v@/OZehKZexAZeRgrGCKZeJgqmCoQEXAA "V – Try It Online")
### Hexdump
```
00000000: 6ae4 470f 5647 c720 2f64 0a0f f221 2174 j.G.VG. /d...!!t
00000010: 7220 5c20 205c 5c6e 7c74 6163 0a6a f248 r \ \\n|tac.j.H
00000020: 4440 2264 646a 6447 D@"ddjdG
```
## Explanation
The first line contains *n* and the lines below contain the entries of the clipboard, each entry is separated by spaces if there were multiple inputs:
```
j " move to the beginning of the clipboard entries
äG " duplicate the clipboard
ⓞ " <C-o> move cursor to the beginning of the 2nd copy
VG " select everything from cursor to the end of buffer and ..
Ç /d " .. delete every line that doesn't contain a space
ⓞ " <C-o> move cursor to the beginning of the 2nd copy (now without single arguments)
ò ò " do the following until the end of buffer
!! " on the current line execute the shell command
tr \ \\n " replace spaces with newlines
|tac⮠ " and reverse the lines
j " move to next line
H " go to the beginning of buffer (where n is)
D " delete n (stores it in register ")
@" " that many times ..
dd " .. remove the line
j " move cursor to next line
dG " delete everything from here to the end of buffer
```
[Answer]
# [Red](http://www.red-lang.org), 91 bytes
```
func[b n][a: copy[]foreach c b[if 1 < length? c[append a reverse copy c]]pick append b a n]
```
[Try it online!](https://tio.run/##jc9BDoIwEAXQvaf4R2iBAhoT7@B2MgsorRBNbSqaeHpsiSZEF7JoZ/Ff86fBdNPRdMQbu5vs3Wlq4ZiaHfTVP4ntNZhG99BoabCQ2ONi3GnsD9DUeG9chwbBPEy4mfkNNLMf9BnvtI2548mHwY2wIJISWc0gmUGWcRbxMCPb/CVqQSrIophJypF0jgJlZHIlEwuXi5SnSwmUaVYCtcBWfK32Cz@qWn5ApaKUZsih5m4VGyPL17FqegE "Red – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 176 bytes
```
#define p printf("%d ",
int*_,i;f(x,n)int**x;{if(n<5){for(_=x[2*n-2];_-x[2*n-1];++_)p*_);}else{n-=4;for(i=0;i<8;i+=2)if(n&&x[i]+1-x[i+1])for(_=x[i+1];_-x[i]&&n;--_,--n);p*_);}}
```
[Try it online!](https://tio.run/##XZFBj5swEIXv/IpRVo1sMF1gSRTJobfeVr31hCwUERNGTUwEpkVC/HZqm2w2G5@en958M2OX4aks5/nlKCtUEq5wbVHpiqy@HWHFPKP9giGvyMAUtTd/4CNWRO03dKyalhTZkCe@ChPBi3CRseBBUNCrX1A@yXMnRxVmKbdpzCKO@x3HIEuoxazXQ44iiE0pBrGgH0h7cUAU67XiYViwMFSUL9BpfkFVnvujhH2nzcSn7/UPOyxcDqiIFYf2VDIo60MLvtF/c0Fh9MCc11f4OVxlqTvY2Fh/kcpokscMEgZvDFLBYENd2KJ8JTud7wS/OxW2xomj6MHrZNmo45Opa2yfvarpW10/mX6ZpwIyGB2a3WhsAbBbzfSZR@457UaLbKUr5J9mYs0F8@C6Jg76YG5dvWtxw5pvAILGjTgg7CHlEAT48YL2LC@r@ovtolvd/CHume3HMVjBivJ79l@NZwnEhB8J9pi1ze8HhnHQDboE/xL40uDX7/f3Z/Z0V8vWvh3AlFjwkppuKxEbYK6Pm3Qj6I3TSt23yuzqTd48xzEkuzlOIN7O6Txv/wM "C (gcc) – Try It Online")
Takes the array as a list of 4 start/end pointer pairs, then n.
Description:
```
#define p printf("%d ", // This gives us the short-hand for printing
int*_, // This defines _ as a pointer to int
i; // This defines i as an integer
f(x,n)int**x;{ // This defines f as a function taking int **x and int n
// NOTE: x is {start, end, start, end, start, end, start, end}
if (n<5) { // This is for the 1-4 case
for(_=x[2*n-2]; // Loop _ from the 'end pointer'
_-x[2*n-1];++_) // Until the 'start pointer'
p*_); // Using the short-hand, print *_
}else{ // This is for the 5+ case
n-=4; // Cut n to improve indexing
for(i=0;i<8;i+=2) // Loop over each 'start pointer index'
for(_=x[i+1]; // Loop _ from the 'end pointer'
_-x[i]&&n; // Until the 'start pointer' or n becomes 0
--_,--n); // Decreasing n each time
p*_);}} // _ now points to the 'correct' index, so print it
```
]
|
[Question]
[
### Background
If you do much code golfing, you're likely aware of the [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) operation. Given two integers, it gives another integer with `1`s in the bits where the two inputs differ. So, for example, `1010 XOR 0011 = 1001`.
It turns out to be very useful in game theory, where it's better known as the "nim sum". If you have the sum of two games (that is, you're making moves in one game at a time), the [value](https://en.wikipedia.org/wiki/Sprague%E2%80%93Grundy_theorem) of the position is the nim sum of the values of the positions in each individual game.
But we can take this a step further. With nim addition and an appropriate definition of [nim multiplication](https://en.wikipedia.org/wiki/Nimber#Multiplication), we can form a field from the nonnegative integers. So the challenge is to golf nim multiplication.
### Definition
Nim multiplication obeys the following rules:
The nim product of a Fermat 2-power n = (2^(2^k)) with any smaller number is the ordinary product.
The nim product of a Fermat 2-power n with itself is 3n/2.
Nim multiplication distributes over nim addition.
Nim multiplication is commutative and associative (as is nim addition).
The multiplicative identity is 1 (and the additive identity is 0).
Any nonnegative integer can be written as the nim sum of distinct powers of two, and any power of two can be written as the product of distinct Fermat numbers, so this is sufficient to define nim multiplication for all nonnegative integers.
### Example
That was all pretty abstract, so let's work through an example. I'll use `+` to denote nim addition (XOR) and `*` for nim multiplication.
```
6 * 13
= (4 + 2) * (8 + 4 + 1)
= (4 + 2) * ((4 * 2) + 4 + 1)
= (4 * 4 * 2) + (4 * 2 * 2) + (4 * 4) + (4 * 2) + (4 * 1) + (2 * 1)
= (6 * 2) + (4 * 3) + 6 + 8 + 4 + 2
= ((4 + 2) * 2) + 12 + 6 + 8 + 4 + 2
= (4 * 2) + (2 * 2) + 12 + 6 + 8 + 4 + 2
= 8 + 3 + 12 + 6 + 8 + 4 + 2
= 15
```
### Additional Test Cases
```
4, 4 -> 6
4, 3 -> 12
4, 7 -> 10
2, 4 -> 8
2, 3 -> 1
1, 42 -> 42
```
### Challenge
Write a program or function which, given two nonnegative integers in any convenient form, computes their nim product.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest submission wins.
[Answer]
# [Nim](http://nim-lang.org/), 120 bytes
```
proc f(a,b:int):int=
var s={0..a*b}
for i in 0..<a*b:s=s-{f(i%%a,i/%a)xor f(a,i/%a)xor f(i%%a,b)}
for i in s:return i
```
[Try it online!](https://tio.run/##TYzBCsIwDIbvfYpcCqvUKXMgFPsw6VgxB1tJpwjDZ6@Zh9FL@PLny5/oUeuT8wSxQxscpcVswyt4I0Px67nv8RC@CmJmIKAEktwkcsWX4xo70hotnTSajxhbTbP8j8G078XxvLw4AdV5umeRRjsatfOl4evOQ@MM4tQf "Nim – Try It Online")
OK, this might be crazy, but somebody had to do Nim multiplication in Nim...
This is standard algorithm from Wikipedia. The problem is that I don't know the language, so had to learn the basics on the fly. In particular, I was surprised that `-=` and `min` didn't work for sets, and the best way I managed to find for extracting the minimum was to use the iterator and return the first value. Hopefully, Nim experts will help me to improve this.
[Answer]
# [Python 2](https://docs.python.org/2/), 85 bytes
```
f=lambda x,y:min(set(range(x*y+1))-{f(i%x,i/x)^f(x,i/x)^f(i%x,y)for i in range(x*y)})
```
[Try it online!](https://tio.run/##hU7LasMwELz7K/ZispsqKXENgYBP@Y8UNZJaQfRA2lCb0m93pbj1tZedZZhXnPgj@G6ezXCT7k1JGMV0ctZj1oxJ@neN43Z6OhDtvgzadhT2eaSLwfWp3EQmJLBgPawe@qbZuhgSg5Ks2TrdVBXrzFWI2IueBBR4WeBYoVvIbiEPAvqO6NQAZJYlaljD9uvjwydSUcQU1P1aNQa3tYYethD/cVnPsDkHF@@sFZg2wTBAuWVkayDra/Aqb6AFrKHir6fMe4Tvlmm058Dy9vqrR6Jm/gE "Python 2 – Try It Online")
Slow as heck. Computes [mex({α′ β ⊕ α β′ ⊕ α' β′ : α′ < α, β′ < β})](https://en.wikipedia.org/wiki/Nimber#Multiplication) recursively.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
p’ß/;ß"^/ʋ€ṭ‘ḟ$Ṃ
```
Uses the recursive formula **xy = mex({ay ⊕ xb ⊕ ab : a < x, b < y})** for [nimber multiplication](https://en.wikipedia.org/wiki/Nimber#Multiplication "Nimber - Wikipedia").
[Try it online!](https://tio.run/##AVoApf9qZWxsef//cOKAmcOfLzvDnyJeL8qL4oKs4bmt4oCY4bifJOG5gv814bi2w6fDvmBHIOG4t@KAnCBtdWx0aXBsaWNhdGlvbiB0YWJsZSAoMC00IHggMC00Kf8 "Jelly – Try It Online")
### How it works
```
p’ß/;ß"^/ʋ€ṭ‘ḟ$Ṃ Main link. Left argument: x. Right argument: y.
p Cartesian product; yield the array of all pairs [a, b] such that
0 < a ≤ x and 0 < b ≤ y.
’ Decrement, changing the conditions to 0 ≤ a < x and 0 ≤ b < y.
ṭ Tack; yield [y, x].
ʋ€ Combine the four links to the left into a dyadic chain. Call it
with right argument [y, x] and each of the [a, b] as left one.
ß/ Reduce [a, b] by the main link, computing the product ab.
ß" Zip [a, b] with [y, x] using the main link, computing the
array of products [ay, xb].
; Concatenate, yielding [ab, ay, xb].
^/ Reduce by bitwise XOR, yielding ab ⊕ ay ⊕ xb.
All that's left is to compute the minimum excluded (mex) non-
negative integer.
$ Combine the two links to the left into a monadic chain.
‘ Increment the XOR sums.
ḟ Filterfalse; remove all incremented sums that appear in the
original sums.
Ṃ Take the minimum if the resulting array is non-empty or yield 0.
If x = 0 or y = 0, the array of sums is empty and Ṃ yields 0.
If x > 0 and y > 0, since 0 is among the sums, this finds the
smallest non-sum n+1 such that n ≥ 0 is a sum.
In either case, Ṃ yields xy.
```
[Answer]
# [CGSuite](http://cgsuite.sourceforge.net/), ~~52~~ ~~39~~ 22 bytes
```
(a,b)->a.NimProduct(b)
```
Didn't realize it has this builtin, and anonymous "procedures".
Original version, 36 bytes:
```
(a,b)->*a.ConwayProduct(*b).NimValue
```
Or 25 bytes if the input/output could be nimbers:
```
(a,b)->a.ConwayProduct(b)
```
Well, I hoped `*a**b`/`a*b` to work, but it doesn't.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 21 bytes
```
Mf-TsmmxxgkdgkHgGdGH0
```
[Demonstration](http://pyth.herokuapp.com/?code=Mf-TsmmxxgkdgkHgGdGH0%0Ag6+13&debug=1)
Uses the minimum excluded element formulation of nim multiplication, as given [here](https://en.wikipedia.org/wiki/Nimber#Multiplication).
Two nested maps are used to iterate over all smaller values (`mm ... GH`), then the results are flattened (`s`). The clever part comes with `f-T ... 0`, where we iterate over integers upward from 0 to find the first one not contained in the set mentioned above. By doing it this way, we don't need to calculate an iteration upper bound, saving a few bytes.
In the end, the function `g` computes the nim product.
[Answer]
## JavaScript (ES6), ~~142~~ 128 bytes
```
f=(x,y,z=Math.log2,v=x&-x,t=z(x),u=z(y),s=t&u,r=s&-s)=>x<2|y<2?x*y:x>v?f(v,y)^f(x^v,y):y&y-1?f(y,x):r?f(f(x>>r,y>>r),3<<r-1):x*y
```
```
<div oninput=o.textContent=f(x.value,y.value)><input id=x><input id=y><pre id=o>
```
The first step is to split both `x` and `y` into an XOR of powers of `2`, take their pairwise nim products, and then XOR the results (because nim product distributes over XOR). Once we have recursed to the case of `x` and `y` both powers of 2, we note that Fermat powers multiply with each other using ordinary arithmetic, so we can therefore factorise `x` and `y` into Fermat powers. If `x` and `y` don't share a Fermat power we can reverse the process and simply return `x * y`. However if they share a Fermat power, then we divide both `x` and `y` by that power, calculate the nim product, then take the nim product with the nim square of that Fermat power. Ungolfed:
```
function nimprod(x, y) {
if (x < 2 || y < 2) return x * y;
var v = x & -x;
if (x > v) return nimprod(v, y) ^ nimprod(x ^ v, y); // nimprod distributes over ^
if (y & (y - 1)) return nimprod(y, x); // x is a power of 2 but y is not
var t = Math.log2(x);
var u = Math.log2(y);
var s = t & u;
if (!s) return x * y; // x and y do not share a Fermat power
var r = s & -s;
return nimprod(nimprod(x >> r, y >> r), 3 << r - 1); // square the Fermat power
}
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 81 bytes
```
x_±y_:=Min@Complement[Range[0,x*y],##&@@Array[BitXor[x±#2,#±y,±##]&,{x,y},0]]
```
[Try it online!](https://tio.run/##rY1BCsIwEEX3PcVAoGgZodaCIChR1wVxJZQgQYIGTCKli8SQQ/UKvVhNpd7A1Zv5w5@nePsQirfyxofBXvvOXTfbSmp6NOr1FErotj5zfRd1jjZzDAlJKd03DXf1QbYX09S270iBJFYxToSl6C26gDljwyyDSigj39FgNGTz5OeILfc/UZKcGhk/eEICLHbwvUMKlFLwvkQoA8LI1cT1yGLKiylfxr0IYfgA "Wolfram Language (Mathematica) – Try It Online")
Using the formula:
\$\alpha \beta = \operatorname{mex}(\{\,\alpha' \beta + \alpha \beta' + \alpha' \beta' : \alpha' < \alpha , \beta' < \beta \,\}).\$
]
|
[Question]
[
Many programming languages are written using solely printable ASCII, tabs and newlines. These 97 characters are then stored in 8-bit bytes (which are actually capable of holding 256 different characters!), which is just terribly inefficient - especially in code-golfing, where every byte counts! In this challenge, you will be able to reduce your score by using base conversion.
## Challenge
Your program/function takes a string or character array as input, which it then interprets as a **base-97** number. It then converts this to a **base-256** number, and counts the number of symbols (i.e., bytes) necessary to represent this number. This count will be the output/return value of your program/function.
*A simple example using base-2 and base-10 (binary and decimal): if the input is `10110`, the output would be 2, since 101102=2210 (two digits necessary to represent output). Similarly, 11012 becomes 1310, giving an output of 2 as well, and 1102 becomes 610, so then the output would be 1.*
The input string can contain all 95 printable ASCII characters , as well as newline `\n` and literal tab `\t`, which creates a **source alphabet** of 97 symbols for your base conversion. The exact alphabet will thus be *(substituting the `\t` and `\n` with actual literal tab and newline; note the literal space following the newline)*:
```
\t\n !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
Note that the order of this alphabet is important: for example, base-97 `\t` corresponds to decimal `0`, and `!` corresponds to decimal `3`.
Some testcases: (you do not need to handle an empty string)
```
Input Output
'[[email protected]](/cdn-cgi/l/email-protection)' 15
'All your base are belong to us!' 26
' abcd' 9
'~ abcd' 10
'ABCDEFGHIJK' 9
'zyxwvutsrpq' 10
'{".~"}.~' 7
'\t\t\t\t\t\t\t\t' 1 (with \t a literal tab; the result is 0, which can be represented with 1 byte)
'!\t\t\t\t\t\t\t\t' 7 (with \t a literal tab)
```
# Scoring
1. **If your entry uses only printable ASCII, newline and/or tab:**
The score of your program will be the output of your program, when given its own source code as input.
2. **If your entry uses any characters that are not printable ASCII, newline or tab:**
The score of your program is simply the number of bytes, like in [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
[Answer]
# [Python 2](https://docs.python.org/2/), score 73 72 71
**Edit:** -1 thanks to [@Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)
```
def f(l,z=0):
	for i in map(ord,l):z+=i-[30,9][i<32];z*=97
print(len(bin(z))-2)/8or 1
```
[Try it online!](https://tio.run/##lZFbT4MwHMWfx6f4j5e1ynCwKA4l8X79CBsxXDptUlqETgdGvjq2ATNJ9MH27ZxfT9Jz8kq@CO62bUrWsEbMqoMZ9o3RWhRAgXLIohyJIrUY9uv9gE6X85m1CJf0dO6GJ/VesPCMUV5QLhEjHMWUoxrjqYsPjlWC00pSyqckKkkJASyNEZqQbZTljJylIosotxORTSxwDrGlzXPGoBKbAmL1BKKCQEyY4M8gBWzKsSLdo46E7kRxkip10YnNQHRmfejF5dX1ze3d/cPjDq2r7fvbRpZF/voD/TDtxvy0GyV5nbKSw6vhzhn/YnnYCA1Dl6f/bJFtThJJUl3krgm/bwy@bVU30g7uDZWAzMEgK76S/5hE43@PYuL2Cw)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), score 19 (23 bytes)
```
nHo127 uA9 md)sG l /2 c
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=bkhvMTI3IHVBOSBtZClzRyBsIC8yIGM=&input=Igki)
By coincidence, I don't think this can be golfed much even with non-ASCII chars...
### Explanation
```
UnHo127 uA9 md)sG l /2 c Implicit: U = input string, A = 10, G = 16, H = 32
Ho127 Create the range [32, 33, ..., 126].
uA9 Insert 9 and 10 at the beginning of this range.
md Map each to a character, yielding ["\t", "\n", " ", "!", ... "~"].
Un ) Convert U to a number via this alphabet ("\t" -> 0, "~" -> 96, etc.)
sG Convert this number to a base-16 (hexadecimal) string.
l Take the length of this string.
/2 c Divide by two and round up to get the length in base-256.
Implicit: output result of last expression
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) - score ~~18~~ 17
-1 byte thanks to Erik the Outgolfer (no need for a list of lists for the translation)
```
O“µœ½þ‘y_30ḅ97b⁹L
```
**[Try it online!](https://tio.run/##y0rNyan8/9//UcOcQ1uPTj609/C@Rw0zKuONDR7uaLU0T3rUuNPn/9E9h9sfNa3JAmKQum26dgqPGuZG/v8frZ5akZhbkJPqkJKfm5iZp5ecn6uuo@6Yk6NQmV9apJCUWJyqkFiUqpCUmpOfl65Qkq9QWqwIVKEAAYlJySlAXh0Kz9HJ2cXVzd3D08sbyKuqrCgvKy0pLiooBPKqlfTqlGr16oDMmBJUCBRSxBCLBQA "Jelly – Try It Online")**
### How?
```
O“µœ½þ‘y_30ḅ97b⁹L - Link: list of characters
O - convert from characters to ordinals
“µœ½þ‘ - code-page indices = [9,30,10,31]
y - translate (9->30 and 10->31)
_30 - subtract 30
ḅ97 - convert from base 97
⁹ - literal 256
b - convert to base
L - length of the result
```
---
--The best I've got with ASCII only is a score of **29**:
```
O10,31,9,30y_30Ux"J_1 97*$$$SSb256L
```
- this is **extremely** inefficient too. It translates the ordinals like above, but the conversion from base 97 is achieved by repeating the values and summing, rather than using direct multiplication - that is to convert `{".~"}.~` it gets the adjusted indexes `[93,4,16,96,4,95,16,96]` then reverses (`U`) and repeats them to make `[[96,96,..., 97⁷ times ...,96],[16,16,... 97⁶ times ...16],[95,95,... 97⁵ times ...95],[4,4,... 97⁴ times ...4],[96,96,... 97³ times ...96],,[16,16,... 97² times ...,16],[4,4,... 97 times ...4],[93]]` and then sums, converts to base 256 and gets the length (if it has not run out of memory :p).
[Answer]
# [J](http://jsoftware.com/), 36 bytes, score = 30
```
256#@(#.inv)97x#.(u:9,10,32+i.95)&i.
```
[Try it online!](https://tio.run/##y/r/P03B1krByNRM2UFDWS8zr0zT0rxCWU@j1MpSx9BAx9hIO1PP0lRTLVOPiys1OSNfIU1BnRjV6v//AwA "J – Try It Online")
J uses only the 7-bit ASCII characters for its primitives.
## Explanation
```
256#@(#.inv)97x#.(u:9,10,32+i.95)&i. Input: string S
( ) Form 7-bit ASCII alphabet
i.95 Range [0, 95)
32+ Add 32
9,10, Prepend 9 and 10
u: Convert to characters
&i. Index of each char in S in that alphabet
97x#. Convert from base 97 to decimal
256 #.inv Convert to base 256
#@ Length
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 14 bytes, score 14
```
9c₸c₵R]$;B₵rBl
```
[Try it online!](https://tio.run/##S0/MTPz/3zL5UdMOIN4aFKti7QSki5xy/v9/1DAntSIxtyAn1SElPzcxM08vOT/3UcNcAA "Gaia – Try It Online")
### Explanation
```
9c Push a tab character. (done like this since tab isn't in the codepage)
₸c Push a linefeed character.
₵R Push all printable ASCII characters.
]$ Concatenate everything together.
; Copy second-from-top, implicitly push input. Stack is now [ASCII input ASCII]
B Convert input from the base where the ASCII string is the digits.
₵rB Convert that to the base where the code page is the digits (base 256).
l Get the length of the result.
Implicitly output top of stack.
```
## ASCII only
This is the best I could come up with using only ASCII, giving a score of 19:
```
9c10c8373c'R+e]$;B256Bl
```
The difficulty is in the conversion of input. The only reasonable way to convert from the base-97 system is to use `B`, since mapping requires the non-ASCII `¦`. Additionally, there isn't currently a way to make a character range without mapping `c` over a number range, which suffers the same problem. The best solution I could see was constructing the string `₵R` and evaling it.
[Answer]
# [Python 2](https://docs.python.org/2/), score 60
```
lambda s:len(bin(reduce(lambda a,c:a*97+ord(c)-[30,9][c<' '],s,0)))+5>>3
```
[Try it online!](https://tio.run/##bZHNbsIwEITveYoll9jFjfgRRUQFldL/PgJwcGzTRnLs1HZoaFVePXUglUDq@vbN7Kw0LnbuXatBzTQXMIUwDFe1pHnKKdhECoXSTCEjeMkEajklLKEXk3FXG44YvlwOe2SyXrLrCKI1saSHMe6OZrNh7dNi60xWIBwEGx8vtlSi5hQOGLXCerQMAFA0lxJ2ujSQegzUCEiF1OoNnIbSdiICgytMDlZR0byQ4obrnGYqZjr3an/UqnAcmjLu8aSl@zPa77V4fru4u394fHp@eT0xf@2qz23prCk@Ts3fYbwPf@K9Z@MWrdz5a@yt1PlHa9bWvghtwBKoIFNwaCEBaq0wDjbIYphOoQoKkykHh1qcsM5C0Vh4HP0pi@a/LNNGJD55cyy1/gU "Python 2 – Try It Online")
## Mapping to base-97
The value of a character is obtained by `ord(c)-[30,9][c<' ']`: its ASCII code, minus 9 for tabs and newlines (which precede `' '` lexicographically), or minus 30 for everything else.
## Converting to a number
We use `reduce` to convert the string to a number. This is equivalent to computing
```
a = 0
for c in s: a = a*97+ord(c)-[30,9][c<' ']
return a
```
## Computing base-256 length
The return value of `bin` is a string, which looks somewhat like this:
```
"0b10101100111100001101"
```
Call its length `L`. A value with an `n`-bit binary representation has a `ceil(n/8)`-bit base-256 representation. We can compute `n` as `L-2`; also, `ceil(n/8)` can be written as `floor((n+7)/8)` = `n+7>>3`, so our answer is `L-2+7>>3` = `L+5>>3`.
The case where the input string has value 0 is handled correctly, as `bin` returns `"0b0"`, so we return `3+5>>3` = 1.
[Answer]
# APL, score 24 (bytes\*)
```
⌈256⍟97⊥97|118|¯31+⎕AV⍳⍞
```
Assumes the default `⎕IO←1`, otherwise just change ¯31 to ¯30.
**Explanation:**
```
⎕AV⍳⍞ Read a string and convert it to ASCII codepoints + 1
¯31+ Subtract 31, so that space = 2, bang = 3, etc.
118| Modulo 118, so that tab = 97, newline = 98
97| Modulo 97, so that tab = 0, newline = 1
97⊥ Decode number from base 97
⌈256⍟ Ceiling of log base 256, to count number of digits
```
**Examples:**
```
⌈256⍟97⊥97|118|¯31+⎕AV⍳⍞
[[email protected]](/cdn-cgi/l/email-protection)
15
⌈256⍟97⊥97|118|¯31+⎕AV⍳⍞
All your base are belong to us!
26
⌈256⍟97⊥97|118|¯31+⎕AV⍳⍞
abcd
9
⌈256⍟97⊥97|118|¯31+⎕AV⍳⍞
~ abcd
10
```
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
\*: APL can be written in its own legacy charset (defined by `⎕AV`) instead of Unicode; therefore an APL program that only uses ASCII characters and APL symbols can be scored as 1 char = 1 byte.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score: 18 (bytes)
```
9,⁷Ọ;ØṖiЀ⁸’ḅ97b⁹L
```
[Try it online!](https://tio.run/##y0rNyan8/99S51Hj9oe7e6wPz3i4c1rm4QmPmtY8atzxqGHmwx2tluZJjxp3@vz//189pgQVqgMA "Jelly – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 70 bytes, score 58
```
->n{x=0;n.bytes{|i|x+=i-(i<32?9:30);x*=97};a=x.to_s(2).size/8;a<1?1:a}
```
[Try it online!](https://tio.run/##rc5JDoIwGEDhNT3FD3HhEKviQhGrwXk4ghrSatUmSAmFCDJcHRe68AB@q7d8YczS6kqOVXviZwnp2j5macRVlos8aRHRrotx35xao363YSdNYg0Km5IER9JVdbOBlXjxztCm4960N6JF9bwLj8ONRwpBANdDzcXnu3wEJ8T9S6VpyPE8SGUcAqOKAw05MO5J/waRhFjpCD4oO19Q@dPObL5Yrtab7W6PMgOXRoFLpGtf6D/7bw "Ruby – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL) (19 bytes), score 16
```
9=?1}G9tQ6Y2hh8WZan
```
Non-printable characters (tab, newline) in the input string are entered by contatenating their ASCII codes (`9`, `10`) with the rest of the string.
* [Try it online!](https://tio.run/##y00syfn/39LW3rDW3bIk0CzSKCPDIjwqMe//f/XUisTcgpxUh5T83MTMPL3k/Fx1AA "MATL – Try It Online");
* [Verify all test cases](https://tio.run/##y00syfmfEOH139LW3rDWy7Ik0CzSKCPDIjwqMe9/rEvIf/XUisTcgpxUh5T83MTMPL3k/Fx1LnXHnByFyvzSIoWkxOJUhcSiVIWk1Jz8vHSFknyF0mJFoAoFCEhMSk4B8upQeI5Ozi6ubu4enl7eQF5VZUV5WWlJcVFBIZBXraRXp1SrV6fOFW2pgArV1WO5otUV1dGELWMB);
* [Compute the program's score](https://tio.run/##y00syfn/39LW3rDW3bIk0CzSKCPDIjwqMe//f3UsouoA).
The initial part `9=?1}G` is only necessary because of a bug in the `Za` (base conversion) function, which causes it to fail when the input only consists of "zeros" (tabs here). It will be fixed in the next release of the language.
### Explanation
```
9= % Implicitly input a string. Compare each entry with 9 (tab)
? % If all entries were 9
1 % Push 1. this will be the ouput
} % Else
G % Push input string again
9 % Push 9 (tab)
tQ % Duplicate, add 1: pushes 10 (newline)
6Y2 % Push string of all printable ASCII chars
hh % Concatenate twice. This gives the input alphabet of 97 chars
8W % Push 2 raised to 8, that is, 256. This represents the output
% alphabet, interpreted as a range, for base conversion
Za % Base conversion. Gives a vector of byte numbers
n % Length of that vector
% End (implicit). Display (implicit)
```
[Answer]
# Befunge-93, ~~83~~ 79 bytes, score ~~74~~ 65
```
<v_v#-*52:_v#-9:_v#`0:~
5v$
^6>>1>\"a"* +
>*- ^ 0$<
0_v#:/*4*88\+1\ $<
.@>$
```
[Try it here!](http://www.quirkster.com/iano/js/befunge.html)
The program first converts the input to a base-97 number, and then counts how many digits are required for a base-256 number. As such, the base-97 number is huge, so big that TIO will output a maximum value of 8 for large values; however, the JS interpreter doesn't care and will output the correct value.
[Answer]
# [Perl 5](https://www.perl.org/), 76 + 1 (-F) = 77 bytes
```
}{$d+=97**(@F+--$i)*((ord)-(/ |
/?9:30))for@F;say!$d||1+int((log$d)/log 256)
```
[Try it online!](https://tio.run/##K0gtyjH9/7@2WiVF29bSXEtLw8FNW1dXJVNTS0MjvyhFU1dDn7OGS9/e0srYQFMzLb/Iwc26OLFSUSWlpsZQOzOvREMjJz9dJUVTH0gpGJmaaf7/7@jk7OLq5u7h6eX9L7@gJDM/r/i/rq@pnoGhwX9dNwA "Perl 5 – Try It Online")
**How?**
Implicitly, separate the characters of the input (`-F`), storing all of that in @F. Close the implicit `while` loop and start a new block (`}{`) (*Thanks, @Dom Hastings!*). For each character, multiply its value by 97 to the appropriate power. Calculate the number of characters by finding the size of the sum in base 256 using logarithms.
]
|
[Question]
[
A very common need in algorithms classes and computer science in general is to iterate 4-directionally over a grid or matrix (such as in BFS or DFS). This seems to often result in a lot of clunky and verbose code with a lot of arithmetic and comparisons within loops. I've seen many different approaches to this, but I can't shake the feeling that there's a more concise way to do this.
The challenge is to write a pure function that, given the width and height of a finite plane `n, m` originating at point `(0,0)`, and coordinates `(x,y)` that can represent any valid point within that plane, returns an iterable object of all points within the plane that are 4-directionally adjacent to `(x,y)`.
The goal is to define that function in as few bytes as possible.
Some examples to help illustrate valid input/output:
```
n = 5 (y-axis), m = 3 (x-axis) (zero-based)
matrix = [
[A, B, C],
[D, E, F],
[G, H, I],
[J, K, L],
[M, N, O],
]
(x, y) => [valid iterable points]
E: (1, 1) => [(1, 0), (2, 1), (1, 2), (0, 1)]
A: (0, 0) => [(1, 0), (0, 1)]
L: (2, 3) => [(2, 2), (2, 4), (1, 3)]
N: (1, 4) => [(1, 3), (2, 4), (0, 4)]
```
```
n = 1 (y-axis), m = 1 (x-axis) (zero-based)
matrix = [
[A],
]
(x, y) => [valid iterable points]
A: (0, 0) => []
```
```
n = 2 (y-axis), m = 1 (x-axis) (zero-based)
matrix = [
[A],
[B],
]
(x, y) => [valid iterable points]
A: (0, 0) => [(0, 1)]
B: (0, 1) => [(0, 0)]
```
And here's an example (this one in Python) of a function that satisfies the conditions:
```
def four_directions(x, y, n, m):
valid_coordinates = []
for xd, yd in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
nx, ny = x + xd, y + yd
if 0 <= nx < m and 0 <= ny < n:
valid_coordinates.append((nx, ny))
return valid_coordinates
```
The example above defined a named function, but anonymous functions are also acceptable.
The inputs `n, m, x, y` are all unsigned 32-bit integers within the following ranges:
```
n > 0
m > 0
0 <= x < m
0 <= y < n
```
The output must take the form of an iterable (however your language of choice defines that) of (x, y) pairs.
*Additional clarifications:*
Complex numbers (and other representations/serializations) are OK as long as the consumer of the iterable can access `x` and `y` as integers knowing only their location.
Non-zero-based indexes are acceptable, but only if the language of choice is a non-zero-indexed language. If the language uses a mix of numbering systems, default to the numbering system of the data structure most commonly used to represent a matrix. If these are still all foreign concepts in the given language, any starting index is acceptable.
[Answer]
# [Python 2](https://docs.python.org/2/), 66 bytes
```
lambda m,n,x,y:[(x-1,y),(x+1,y)][~x:m-x]+[(x,y-1),(x,y+1)][~y:n-y]
```
[Try it online!](https://tio.run/##VcuxCoMwFIXhvU/hGMkJeGO7BPokmsFSpIUmijjcu/jq0YBQMx34fs4s62eKNo3PPv2G8HoPVUAEQ1yn2BCkhmKd13cbu2DY66NADOUC0ZSLuGjEp3n5xrUaVYsHCFTfrtCgKcGiLYFw/8PxLy/2hLQD "Python 2 – Try It Online")
Lists the four neighbors, then uses list slicing to remove those that are out-of-bounds.
---
# [Python 2](https://docs.python.org/2/), 71 bytes
```
lambda m,n,x,y:[(k/n,k%n)for k in range(m*n)if(k/n-x)**2+(k%n-y)**2==1]
```
[Try it online!](https://tio.run/##VcuxDsIgGATg3adgMQG8xkJ1MeFJbAeMogT525AO5emxTUyU7fLd3ZTn10i6ONOXt423u2URhAX5cuXhSAh7Em5MLDBPLFl6PniUJLzb2mYRUuoDX0dN3qIxaihT8jQzxzucoaDE7h9atDVodDUonH6w/uuL/kL5AA "Python 2 – Try It Online")
Instead of checking which of the four neighbors are in-bounds, we do it the slower way of checking all in-bounds points for those that are neighbors, that is have Euclidian distance exactly 1 from `(x,y)`. We also use the classic [div-mod trick to iterate over a grid](https://codegolf.stackexchange.com/a/41217/20260), saving the need to write two loops like `for i in range(m)for j in range(n)`.
I tried using complex arithmetic to write the distance condition, but it turned out longer to write `abs((k/n-x)*1j+k%n-y)==1`.
---
# [Python 2](https://docs.python.org/2/), 70 bytes
```
lambda m,n,x,y:[(x+t/3,y+t%3-1)for t in-2,0,2,4if m>x+t/3>=0<y+t%3<=n]
```
[Try it online!](https://tio.run/##VctBCsIwEEbhvaeYjdDSv5hM6qY0vYi6qEgwYKalZNGcPkoRNNuP95YUn7NwdvaaX1O4PyYKEGxI/aXamngySE08mlbXbl4pkpeWocDovKMw7slo1bBXg5VbXlYvkVxlcIaGrg//oKBKYJgSNLoffP5y4S/kNw "Python 2 – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 90 bytes
This uses a geometric approach: First we create an matrix of zeros of the desired size, and set a `1` to the desired location. Then we convolve with the kernel
```
[0, 1, 0]
[1, 0, 1]
[0, 1, 0]
```
which produces a new matrix of the same size with ones at the 4-neighbours of the original point. Then we `find()` the indices of the nonzero entries of this new matrix.
```
function [i,j]=f(s,a,b);z=zeros(s);z(a,b)=1;[i,j]=find(conv2(z,(v=[1;-1;1])*v'<0,'same'));
```
[Try it online!](https://tio.run/##NYxLDgIhEAX3cwp3dJs2kVFXLSchLBCYBBPB2CMLLo@f6O6lqvJqWH1LYyzPEtZcy8ZmujqzgJCnC3I3PT2qgLwnfIjR/EtyiRBqaTN0gmas5p1m7XDb1HlPSvwtKUQeqcTp/2qPdHI00wF5ilnu8BU4Xg "Octave – Try It Online")
convolution is the key to success.
[Answer]
# JavaScript (ES6), 74 bytes
Boring approach.
```
(h,w,x,y)=>[x&&[x-1,y],~x+w&&[x+1,y],y&&[x,y-1],++y-h&&[x,y]].filter(_=>_)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@18jQ6dcp0KnUtPWLrpCTS26QtdQpzJWp65CuxzE0wbzKkFMnUpdw1gdbe1K3QwINzZWLy0zpyS1SCPe1i5e839yfl5xfk6qXk5@ukaahqmOgrGOgiEQaWpyYZMyACIcUkZAEocU0EATTc3/AA "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 74 bytes
Less boring but just as long. Takes input as `([h,w,x,y])`.
```
a=>a.flatMap((_,d,[h,w,x,y])=>~(x+=--d%2)*~(y+=--d%2)&&x<w&y<h?[[x,y]]:[])
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLy0nscQ3sUBDI14nRSc6Q6dcp0KnMlbT1q5Oo0LbVlc3RdVIU6tOoxLGVlOrsClXq7TJsI@OBqmMtYqO1fyfnJ9XnJ@TqpeTn66RphFtqqNgrKNgCESxmppcWCUNgAinpBGQxCkJNNYEKPkfAA "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (V8)](https://v8.dev/), 67 bytes
If all standard output methods were allowed, we could just print the valid coordinates with:
```
(h,w,x,y)=>{for(;h--;)for(X=w;X--;)(x-X)**2+(y-h)**2^1||print(X,h)}
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvtfI0OnXKdCp1LT1q46Lb9IwzpDV9daE8SKsC23jgBxNCp0IzS1tIy0NSp1M0CMOMOamoKizLwSjQidDM3a/2kapjoKxjoKhkCkaa0AkdK05oKJGwARNnEjIIlNHGiOieZ/AA "JavaScript (V8) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
2ḶṚƬNƬẎ+⁸%ƑƇ
```
A dyadic Link accepting a list of two (0-indexed) integers on the left, `[row, column]`, and two integers on the right, `[height, width]`, which yields a list of lists of integers, `[[adjacent_row_1, adjacent_column_1], ...]`.
**[Try it online!](https://tio.run/##AS0A0v9qZWxsef//MuG4tuG5msasTsas4bqOK@KBuCXGkcaH////WzQsMF3/WzUsM10 "Jelly – Try It Online")**
### How?
```
2ḶṚƬNƬẎ+⁸%ƑƇ - Link: [row, column]; [height, width] e.g. [3,2]; [5,3] (the "L" example)
2 - literal 2 2
Ḷ - lowered range [0,1]
Ƭ - collect up while distinct, applying:
Ṛ - reverse [[0,1],[1,0]]
Ƭ - collect up while distinct, applying:
N - negate [[[0,1],[1,0]],[[0,-1],[-1,0]]]
Ẏ - tighten [[0,1],[1,0],[0,-1],[-1,0]]
⁸ - chain's left argument ([row, column]) [3,2]
+ - add (vectorises) [[3,3],[4,2],[3,1],[2,2]]
Ƈ - filter keep if:
Ƒ - is invariant under:
% - modulo ([height, width]) (vectorises) [3,0] [4,2] [3,1] [2,2]
- (...and [3,0] is not equal to [3,3] so ->) [[4,2],[3,1],[2,2]]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~42~~ 37 bytes
```
pNorm[{##}-p]&~Array~#~Position~1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v@D9pIV@@UW50dXKyrW6BbFqdY5FRYmVdcp1AfnFmSWZ@Xl1hmr/A4oy80ogSuzSopVjo5WNYmPVHBwcqrmqq410jGp1qo11TGtrdYBcQx1DZK6xjgky1wjIgHPhqkEkKt8IZpgRjMtV@x8A "Wolfram Language (Mathematica) – Try It Online")
Input `[{x,y}][{m,n}]`. 1-indexed, following Mathematica's convention.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~56~~ 49 bytes
*-7 bytes thanks to nwellnhof!*
```
{grep 1>(*.reals Z/@^b).all>=0,($^a X+1,-1,i,-i)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq9KLVAwdBOQ0uvKDUxp1ghSt8hLklTLzEnx87WQEdDJS5RIULbUEfXUCdTRzdTs/Z/cWKlQpqGobZhpo6GsY6ppqY1F0TIQNsAXchI2xhdyFDbBC70HwA "Perl 6 – Try It Online")
Removes the out of bounds elements by checking if when divided by the array bounds it is between 0 and 1. Takes input and output via complex numbers where the real part is the `x` coordinate and the imaginary is the `y`. You can extract these through the `.im` and `.re` functions.
[Answer]
# [J](http://jsoftware.com/), ~~30~~ ~~29~~ 28 bytes
```
(([+.@#~&,1=|@-)j./)~j./&i./
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NTSitfUclOvUdAxtaxx0NbP09DXrgIRapp7@f00urtTkjHygcgOFNAVjBRMIV10dQhsCIRZhI6AQWPg/AA "J – Try It Online")
How:
* Turn the right hand `m` x `n` arg into a grid of complex numbers `j./&i./`
* Same for left arg (our point) `j./`
* Create a mask showing where the distance between our point and the grid is exactly 1 `1=|@-`
* Use that to filter the grid, after flattening both `#~&,`
* Turn the result back into real points `+.@`
[Answer]
# Haskell, 62 bytes
Using 
```
f m n a b = [(x,y)|x<-[0..m-1],y<-[0..n-1],(x-a)^2+(y-b)^2==1]
```
[Try it online!](https://tio.run/##bYwxDoMgAEV3T/EHB0yFgLabnMRogtGmpoBGHSDx7kjTEaf/8pL/Pmr/TlqHYNRsITEuGaCnA28YWCgMUbbElb44XUNbzpihoiv9n@2PiaOq6KsH8XSIK6XoYmTdZnsgj6EaLwiIxHHwxFWob77PEC4 "Haskell – Try It Online")
Boring approach: 81 bytes
```
f m n x y=filter (\(x,y)->x>=0&&y>=0&&x<m&&y<n) [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 91 bytes
```
(a,b,x,y)=>new[]{(x+1,y),(x-1,y),(x,y+1),(x,y-1)}.Where(d=>((x,y)=d,p:x>=0&x<a&y>=0&y<b).p)
```
[Try it online!](https://tio.run/##XY0/D4IwEMV3PwUTuYaDUNAF226auLk5GAf@lEiiDQGJbYyfvRY1Bhnuvbtf8t6VfVj2jd0OqmSNuuF0dhs1XGWXFxfJYASeEyKEV3vcQo4FajSECyXvx9MDdEDdiaDDr6MJ6MdDSp7R4Sw7CRUXAO9chW2mBY99zXLfjIthBYlaYteLfedeQQ0prpAiJeQfxRjPUYLpHFFcTpHrmQeTH7Iv "C# (Visual C# Interactive Compiler) – Try It Online")
Alternatively:
```
(a,b,x,y)=>new[]{(x+1,y),(x-1,y),(x,y+1),(x,y-1)}.Where(d=>((x,y)=d).Item1>=0&x<a&y>=0&y<b)
```
[Try it online!](https://tio.run/##XY29D4IwEMV3/womcg0HoaCTbTdN2NwcjAMfJZBIBz5iG@PfXosagwz33t0vee/KISyH1h4nVbJWjbic7KCmTvZ5cZMMZuA5IUJ4tcct5FigRkO4UPJ@uT5AB9SdCDr8OpqAfjyk5BmdG9lLqLgAeOcqEmWj7Kjgsa9Z7pt5Mawgdr859e4V1JDiDilSQv5RjPEaJZiuEcXtErmedTD5IfsC "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
Jθη#FIζFIε«Jικ¿№KV#⊞υ⟦ικ⟧»⎚Iυ
```
[Try it online!](https://tio.run/##RY0xC8IwFITn5lc86vIexEHUqWO3DtJBXMQhlJSEpommfQ6Kvz2mIrrdcffddUbFLiiXUsPj9RjwJsFQJdpo/Yzlqsy6DxGwVtOMDyL4O53dUxRf0EoYcrmwfY4DZ7rVejgFf9A8Ku@RJCx7BC1PBlnCeUEumXmJ2mkV8ff7mWeiKqUN7GAL@7S@uzc "Charcoal – Try It Online") Link is to verbose version of code. Takes inputs in the order x, y, width, height. Explanation:
```
Jθη#
```
Print a `#` at the provided position.
```
FIζFIε«
```
Loop over the given rectangle.
```
Jικ
```
Jump to the current position.
```
¿№KV#⊞υ⟦ικ⟧
```
If there's an adjacent `#` then save the position.
```
»⎚Iυ
```
Output the discovered positions at the end of the loop.
Boring answer:
```
FIζFIε¿⁼¹⁺↔⁻ιIθ↔⁻κIηI⟦ικ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzmxuESjSlNTAcFLBfIy0xQ0XAtLE3OKNQx1FAJySos1HJOK83NKS1I1fDPzgNxMHQWw6kJNTU0dBTTJbKhkhiYYKAQUZeaVQEyPBmrMjtXUtP7/31DBRMFYwfS/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Works by finding the adjacent positions mathematically.
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-xp`, 18 bytes
```
$ALaCGbFI1=$+:_ADc
```
Takes three command-line arguments: m, n, and a list containing x & y. [Replit!](https://replit.com/@dloscutoff/pip) Or, here's a similar program in Pip Classic with a header to simulate the `-x` flag: [Try it online!](https://tio.run/##K8gs@B9mlWgdZpUExMnW/1UcfRKd3ZPcPA1tVbQdnazidZP///@vW/Df@L/p/2hDa5NYAA "Pip – Try It Online")
### Explanation
Generates a list of all points in the valid rectangle and filters for the ones that are one unit away from the given point.
```
$ALaCGbFI1=$+:_ADc
aCGb Generate a coordinate grid of a rows and b columns
$AL Fold on append-list: flatten once, giving a list of coord pairs
FI Filter on this function:
_ The argument
AD Absolute difference (element-wise) with
c The program's third argument
$+: The sum of the resulting pair
1= Must equal 1
```
]
|
[Question]
[
### Challenge
Given a `n`-dimensional array of integers and a permutation of the first `n` natural numbers, permute the array dimensions accordingly.
### Details
This challenge is inspired by MATLABs [`permute`](https://mathworks.com/help/matlab/ref/permute.html). [demonstration](https://tio.run/##y08uSSxL/f8/UcFWoSq1KL9Yw0gHCDWtuRI1rHSsdAw1gRLR0YbWRrE60cbWJrGxMBkjkAxMkbaJNVdKZnGBRqImlFGQWpRbWpKqkagTbaRjrGMYq6n5/z8A "Octave – Try It Online")
The permutation is given as a list of integers, e.g. `[1,3,2]` means 1 gets mapped to 1, 2 gets mapped to 3 and 3 gets mapped to 2 (here the `i`th entry is the value `i` gets mapped to). But you can use other formats that are convenient, for instance as cycles or as a function. If it is more convenient you can also use 0-based indexing.
The array can be assumed to be a full "rectangular" `m1 x m2 x ... x mn`-array (i.e. you can assume it is not [ragged/jagged](https://en.wikipedia.org/wiki/Jagged_array)).
You can assume that `n` is not too large, as many languages have a limit of the number of dimensions in a nested array.
If your language does not support multidimensional arrays, you can also take a string that represents the array as input.
### Examples
* Any `n`-dimensional array with the identity permutation `[1,2,3,...,n]` will be unchanged.
* The array `[[10,20,30],[40,50,60]]` with the permutation `[2,1]` gets mapped to `[[10,40],[20,50],[30,60]]`.
* The array `[[[1,2],[3,4]],[[5,6],[7,8]]]` with the permutation `[2,3,1]` gets mapped to `[[[1,3],[5,7]],[[2,4],[6,8]]]`.
[Answer]
# Languages with built-in solutions
*[based on this proposal by xnor](https://codegolf.meta.stackexchange.com/a/11218/8478)*
## [APL (Dyalog Unicode)](https://www.dyalog.com/), 1 byte
```
⍉
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHvZ3//xspGCsYKqQpGIHgo94tj3o3WwAA "APL (Dyalog Unicode) – Try It Online")
## [J](http://jsoftware.com/), 2 bytes
```
|:
```
[Try it online!](https://tio.run/##y/r/P83Wqsbqf2pyRr6CoYKRgoFCmkKmnhGQZfQfAA "J – Try It Online")
## [R](https://www.r-project.org/), 5 bytes
```
aperm
```
[Try it online!](https://tio.run/##K/qfpmCj@z@xILUo93@FjW5iUVFipYahlYVOsoaRDhBqalpXcIGlNSrAYsY6hpqa/wE "R – Try It Online")
## [Octave](https://www.gnu.org/software/octave/)/MATLAB, 8 bytes
```
@permute
```
[Try it online!](https://tio.run/##y08uSSxL/f8/UcFWoSq1KL9Yw0gHCDWtuRI1rHSsdAw1gRLR0YbWRrE60cbWJrGxMBkjkAxMkbaJNVdKZnGBRqImlFGQWpRbWpKqkagTbaRjrGMYq6n5/z8A "Octave – Try It Online")
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 9 bytes
```
Transpose
```
[Try it online!](https://tio.run/##NYs7CoAwEER7TzGlyhb5@CtzBAsvEETQwg@absnZ40ZwYeDN8mb3YV12H7bZp/HejgBXo0zT7Y/nOp8lVXDOgQvIMbNWBCOxKhK4EWolnYq5GoIW@F3W4ua/JTSfwK24GXrCEP@N/WZFTC8 "Wolfram Language (Mathematica) – Try It Online")
## [Julia](http://julialang.org/), 11 bytes
```
permutedims
```
[Try it online!](https://tio.run/##yyrNyUw0@/@/oCgzryQnT6MgtSi3tCQ1JTO3WIOLsyi1OCOxIFXD0MpCR0HDSEcBhDQ1dbg4QRxjHQVDTS5Nzf//AQ "Julia 0.6 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 168 bytes
`p` is a (type class polymorphic) function taking a permutation as a list of `Int`s, and a nested list representing a multidimensional array of `Int`s.
Call as `p [2,1] [[10,20,30],[40,50,60]]`, however if type defaulting doesn't succeed, you may have to add a type annotation like `:: [[Int]]` (nested appropriately) giving the type of the result.
```
import Data.List
class P a where p::[Int]->[a]->[a]
instance P Int where p _=id
instance P a=>P[a]where p(x:r)m|n<-p r<$>m,y:z<-sort r=last$n:[p(x:z)<$>transpose n|x>y]
```
[Try it online!](https://tio.run/##fZFNa9tAEIbv@hVD4oOEV0K2k7QIS9TQEAohhLrtRTFmY2/tpavRemeF5dT97e5ITiD0UB1mxL7PfOy7W0m/lDGnOL5tvULSNRI0pNZQoznAz9qB3yrwirzGDWylQ0UU/I4v4X72cPd9dncL81Vt1frbwaof0mn5bBSJAN5/M2Pq/ax61pumbqgj/yW6s5m1Rq@k73e4jP@cdGVr5@Gz9DK51@SDlZFE8AgS9lvlFNgsK7@gX8RFKc8h0Ehe4koxxcobB8tcr99rMi8eGX@VwzZzUXXEaWzBTQdFJQ7ZyzSmbrrLeagfYFZ22EvEsncSydakAI9tcViwezvwTis6m9XdD7i7KDl0sUsLkSQJaATfOIQGvTY9rdE2Hqx0pCgJdlnGnktjQCYQflVyDVLMt/WeE28d5cXrhec8DzdvOdhBC3QMKzaE5y6jbDmNHVcTUE5cPrAMVMd0OsrDHXzqtou6kiCopMZco1dOrvygQaP5hZNK2vDJxAW/klEe2qzK97XjdoZP@BJmOLx4wriAi@Gwb8hbRWE3EdoobPAMVxHTUdK3PJUjMRaTBbAd/Me2TMRV7861uOH0QXxkk4JyLEYdM0rFOBWTlJWrVFyn4iY9q5Oz/r8efwE "Haskell – Try It Online")
Golfing challenges with nested arrays of arbitrary depth are a bit awkward in Haskell, because the static typing tends to get in the way. While Haskell lists (with the exact same syntax as in the challenge description) can be nested just fine, lists of different nesting depth are of incompatible types. Also, standard Haskell parsing functions require knowing the type of the value you are trying to parse.
As a result, it seems inevitable that the program needs to include type-related declarations, which are relatively verbose. For the golfed part, I settled on defining a type class `P`, such that `p` can be polymorphic over the type of the array.
Meanwhile, the TIO's testing harness shows a way to get around the parsing problem.
# How it works
* To sum up the essence of this algorithm: It performs a bubble sort on the permutation list, transposing neighboring dimensions when the corresponding permutation indices are swapped.
* As given by the `class P a` declaration, in any instance, `p` takes two arguments, a permutation (always of type `[Int]`) and an array.
* The permutation can be given in the form in the challenge description, although the way the algorithm works, the choice of indices is arbitrary, except for their relative order. (So both 0- and 1- based work.)
* The base `instance P Int` handles arrays of dimension 1, which `p` simply returns unchanged, since the one dimension can only be mapped to itself.
* The other `instance P a => P [a]` is defined recursively, calling `p` with dimension *n* subarrays in order to define it for dimension *n+1* arrays.
+ `p(x:r)m` first calls `p r` recursively on every element of `m`, giving a result array `n` in which all dimensions except the first have been permuted correctly relatively to each other.
+ The remaining permutation that needs to be performed on `n` is given by `x:y:z = x:sort r`.
+ If `x<y` then the first dimension of `n` is already correctly placed, and `n` is simply returned.
+ If `x>y`, then the first and second dimension of `n` need to be swapped, which is done with the `transpose` function. Finally `p(x:z)` is applied recursively to every element of the result, ensuring the original first dimension is transposed to the right position.
[Answer]
# [Python 2](https://docs.python.org/2/), 312 bytes
This uses 0-indexing for the permutation
```
from numpy import*
from itertools import*
z=range
def f(i,r):
l=array(i).shape;R={b:a for a,b in enumerate(r)};r=len(r);m=eval('['*r+'0'+q('for k in z(l[R[%s]])]',r-1,-1,-1))
for d in product(*[z(p) for p in l]):exec'm'+q('[d[R[%s]]]',r)+'=i'+q('[d[%s]]',r)
return m
q=lambda s,*j:''.join(s%(j)for j in z(*j))
```
[Try it online!](https://tio.run/##PZDLbsMgEEXX8VewiQCbRiR9LBzxE9kiFiTGDS6vjEnVpOq3u8Z9SLO4Opo5M5p0y@cYdtPUQ/QoXH26IetThFxXC7LZQI7Rjf/4LkCHV1N1pkc9sQxoW62c0AD6RizdjGedzP4gPo@tRn0EpNkR2YDMbDegsyFAv/YgnAlz2nth3rUjWOIaGsxxcyG4TL2VmTtx8iDXo1JUYQYPW7YUpdWq9HSlJ0HsrqdMankniS4bU@FO0dZ8mBP2i1N2v6Yiog0W9g8XWFi1ApOvEJCvLsJpf@w0Glk9tBhvhmgDGddkoMU//NxWD5ROCWzI8yOk3HK24@yRKyafOHvm7IWrOW8ZV3T6Bg "Python 2 – Try It Online")
*-2 bytes thanks to @Jonathan Frech.*
[Answer]
# [Python 2](https://docs.python.org/2/), ~~41~~ 25 bytes
```
import numpy
numpy.einsum
```
[Try it online!](https://tio.run/##Dcw9DoMwDEDhPafwBlReCv0TEidxPRjaqJHqxErDwOnTTN/y9OwonxTH6mF51q/o@hIQtPkd4m/X3lAG53NSiLvaAUEt5XKqAgsAEZ1xZKQJL9ygK94ad3wws7OWdOsmnbMcYgHft@9Q/w "Python 2 – Try It Online")
The permutation vector `p` is given as a string of letters. So `[2,3,1]` can be be given as `'bca'`.
Thanks to @EriktheOutgolfer saved 16 bytes!
[Answer]
## JavaScript (ES6), ~~136~~ 132 bytes
```
(a,p,v=[],r=[],g=(a,[d,...p],_,h=(r,[i,...v])=>1/v[0]?h(r[i]=r[i]||[],v):r[i]=a)=>1/d?a.map((e,i)=>g(e,p,v[d]=i)):h(r,v))=>g(a,p)&&r
```
0-indexed. Explanation: `g` recursively iterates over the array `a` building up an array `v` of indices reordered using the permutation `p`. Once `p` is exhausted, `h` then recursively inserts the element into the result array `r` using the permuted indices.
]
|
[Question]
[
A "triplet bracket" (that I made up for this challenge) is one of the following:
```
(...+...)
[...:...]
{...|...}
<...-...>
```
A balanced triplet bracket string (BTBS for short) is either an empty string, two BTBSes concatenated, or one of the above triplet brackets with each `...` replaced with a BTBS.
Your task is to write a program or function that checks whether a string that consists of only `(+)[:]{|}<->` is balanced. Shortest code wins.
## Examples
Your program should return truthy for the following strings:
```
(+)(+)(+)
[[[:]:]:(+(+))]{<->|<(+)->[:]}(+)
<<<<<<<<<<<<->->->->->->->->->->->->
{|(+[:<-{|(+[:<->])}>])}
[[[:]:[:]]:[[:]:[:]]]
{[:](+)|<->{|}}[(+)<->:{|}(+)]
```
Your program should return falsy for the following strings:
```
:[
<|>
(+(+)
[:][:](+[[:]):]
{|{|{|(+{|{|{|}}}}}+)}[:]{|}
{{||}}
<<->-<->-<->>
[(+):((+)+)+(+(+))]
<<<<<->->->->->->
```
[Answer]
## JavaScript (ES6), ~~77~~ ~~58~~ ~~57~~ 56 bytes
```
f=s=>s==(s=s.replace(/\(\+\)|\[:]|{\|}|<->/,''))?!s:f(s)
```
### Test cases
```
f=s=>s==(s=s.replace(/\(\+\)|\[:]|{\|}|<->/,''))?!s:f(s)
console.log("Testing truthy values");
console.log(f("(+)(+)(+)"));
console.log(f("[[[:]:]:(+(+))]{<->|<(+)->[:]}(+)"));
console.log(f("<<<<<<<<<<<<->->->->->->->->->->->->"));
console.log(f("{|(+[:<-{|(+[:<->])}>])}"));
console.log(f("[[[:]:[:]]:[[:]:[:]]]"));
console.log(f("{[:](+)|<->{|}}[(+)<->:{|}(+)]"));
console.log("Testing falsy values");
console.log(f(":["));
console.log(f("<|>"));
console.log(f("(+(+)"));
console.log(f("[:][:](+[[:]):]"));
console.log(f("{|{|{|(+{|{|{|}}}}}+)}[:]{|}"));
console.log(f("{{||}}"));
console.log(f("<<->-<->-<->>"));
console.log(f("[(+):((+)+)+(+(+))]"));
console.log(f("<<<<<->->->->->->"));
```
[Answer]
# sed, ~~28~~ 27 bytes
```
:
s#(+)\|\[:]\|{|}\|<->##
t
```
*sed* doesn't have a concept of truthy/falsy, so I'm considering an empty string truthy and a non-empty string falsy. This checks out if we consider the conditional `/^$/`.
*Thanks to @Neil for golfing off 1 byte!*
[Try it online!](http://sed.tryitonline.net/#code=OgpzIygrKVx8XFs6XVx8e3x9XHw8LT4jIwp0&input=KCspKCspKCspCltbWzpdOl06KCsoKykpXXs8LT58PCgrKS0-WzpdfSgrKQo8PDw8PDw8PDw8PDwtPi0-LT4tPi0-LT4tPi0-LT4tPi0-LT4Ke3woK1s6PC17fCgrWzo8LT5dKX0-XSl9CltbWzpdOls6XV06W1s6XTpbOl1dXQp7WzpdKCspfDwtPnt8fX1bKCspPC0-Ont8fSgrKV0KOlsKPHw-CigrKCspCls6XVs6XSgrW1s6XSk6XQp7fHt8e3woK3t8e3x7fH19fX19Kyl9Wzpde3x9Cnt7fHx9fQo8PC0-LTwtPi08LT4-ClsoKyk6KCgrKSspKygrKCspKV0KPDw8PDwtPi0-LT4tPi0-LT4)
[Answer]
## Python, 77 bytes
```
lambda s:eval("s"+".replace('%s','')"*4%('(+)','[:]','{|}','<->')*len(s))==''
```
Uses [Arnauld's replacement idea](https://codegolf.stackexchange.com/a/97071/20260). Generates and evaluates a long string like
```
s.replace('(+)','').replace('[:]','').replace('{|}','').replace('<->','').replace('(+)','').replace('[:]','').replace('{|}','').replace('<->','')
```
to cycle between replacing all the bracket types. Then, checks if the result is the empty string.
[Answer]
# Mathematica, 55 bytes
```
StringDelete["(+)"|"[:]"|"{|}"|"<->"]~FixedPoint~#==""&
```
Anonymous function. Takes a string as input and returns `True` or `False` as output. Uses the standard method for doing this.
[Answer]
## [Grime](https://github.com/iatorm/grime), 39 bytes
```
e`\(_\+_\)|\[_\:_\]|\{_\|_\}|\<_\-_\>v*
```
[Try it online!](http://grime.tryitonline.net/#code=ZWBcKF9cK19cKXxcW19cOl9cXXxce19cfF9cfXxcPF9cLV9cPnYq&input=WygrKTwtPjpde3x9) Sadly, the TIO version runs out of memory on most of the test cases.
## Explanation
Nothing too fancy here.
`_` is shorthand for the entire pattern, and `v*` is the same as `*`, but with lower precedence.
```
e` Match entire input against this pattern:
\(_\+_\) '(', match of _, '+', match of _, ')'
| or
\[_\:_\]|\{_\|_\}|\<_\-_\> same for the other bracket types
v* repeated 0-∞ times
```
[Answer]
# J, 48 bytes
```
a:=([:delstring&.>/'(+)';'[:]';'{|}';'<->';])^:_
```
Similar to the others, this is also based on Arnauld's [method](https://codegolf.stackexchange.com/a/97071/6710).
## Usage
```
f =: a:=([:delstring&.>/'(+)';'[:]';'{|}';'<->';])^:_
f '(+)(+)(+)'
1
f '[[[:]:]:(+(+))]{<->|<(+)->[:]}(+)'
1
f '<<<<<<<<<<<<->->->->->->->->->->->->'
1
f '<|>'
0
f '[:][:](+[[:]):]'
0
f '{|{|{|(+{|{|{|}}}}}+)}[:]{|}'
0
```
## Explanation
```
a:=([:delstring&.>/'(+)';'[:]';'{|}';'<->';])^:_ Input: string S
( )^:_ Repeat until convergence
] Get S
'(+)';'[:]';'{|}';'<->'; Append to ['(+)', '[:]', '{|}', '<->']
[:delstring&.>/ Reduce right-to-left by deleting
occurrences of each string on the
left from the right
Return the final string as the new S
a:= Test if the final value of S is empty
```
[Answer]
# Japt, 25 bytes
```
!Ue"%(%+%)|%[:]|\{%|}|<->
```
[**Test it online!**](http://ethproductions.github.io/japt/?v=master&code=IVVlIiUoJSslKXwlWzpdfFx7JXx9fDwtPg==&input=IntbOl0oKyl8PC0+e3x9fVsoKyk8LT46e3x9KCspXSI=)
`e` on strings is a recursive-replace function. The second parameter defaults to the empty string, which means this recursively removes matches of the Japt regex `"%(%+%)|%[:]|\{%|}|<->"` (in regular terms, `/\(\+\)|\[:]|{\|}|<->/`). This returns an empty string for balanced triplet strings and a non-empty string for non-balanced, so the correct return value is the logical NOT of this.
[Answer]
## [Pip](http://github.com/dloscutoff/pip), 26 bytes
```
L#aaR:"(+)[:]{|}<->"<>3x!a
```
[Try it online!](http://pip.tryitonline.net/#code=TCNhYVI6IigrKVs6XXt8fTwtPiI8PjN4IWE&input=&args=e3x7fHt8KCt7fHt8e3x9fX19fSspfVs6XXt8fQ)
Loops len(a) times, replacing all occurrences of empty triplet brackets (`"(+)[:]{|}<->"<>3`, where `<>` is the "group" operator, => `["(+)"; "[:]"; "{|}"; "<->"]`) with empty string (`x`). This many iterations is overkill, but it will always be more than enough to completely reduce all properly formed triplet brackets to nothing. After the loop completes, outputs `!a`: `0` if `a` is truthy (still has some characters), `1` if `a` is falsey (empty).
[Answer]
# Scala, 96 bytes
```
def&(s:String):Any={val t=s.replaceAll(raw"\(\+\)|\[:]|\{\|}|<->","")
if(t==s)t.size<1 else&(t)}
```
This is basically the same idea as the other answers, but with some scala boilerplate.
### without stealing ideas from others (188 bytes):
```
import scala.util.parsing.combinator._
val a = new RegexParsers{def r:Parser[_]="("~r~"+"~r~")"|"["~r~":"~r~"]"|"{"~r~"|"~r~"}"|"<"~r~"-"~r~">"|""
def!(s:String)= !parseAll(r,s).isEmpty}!_
```
]
|
[Question]
[
Consider the standard equilateral triangle, with nodes labeled using [barycentric coordinates](https://en.wikipedia.org/wiki/Barycentric_coordinate_system):

We can turn this 3 node triangle into a 6 node triangle by adding a new line of 3 vertices (one more than was present on a side of the original 3 node triangle), remove any internal edges (but **not** internal nodes) and re-normalize the coordinates:
[](https://i.stack.imgur.com/cbF99.png)
Repeating the process to go from a 6 node triangle to a 10 node triangle, add a line of 4 vertices (again, one more than was present on a side of the original 6 node triangle), remove any internal edges (but **not** internal nodes) and re-normalize the coordinates:
[](https://i.stack.imgur.com/Ff1Zt.png)
This process can be repeated indefinitely. The goal of this challenge is given an integer `N` representing how many times this process has been performed, output all the nodes for the associated triangle in barycentric coordinates.
# Input
Your program/function should take as input a single non-negative integer `N` representing how many times this process has been applied. Note that for `N=0`, you should output the original triangle with 3 nodes.
The input may come from any source (function parameter, stdio, etc.).
# Output
Your program/function should output all the nodes in normalized barycentric coordinates. The order of the nodes does not matter.
A number can be specified as a fraction (fraction reduction not required) or a floating point number. You may also output "scaled" vectors to specify a node. For example, all 3 of the following outputs are equivalent and allowed:
```
0.5,0.5,0
1/2,2/4,0
[1,1,0]/2
```
If using floating point output, your output should be accurate to within 1%. The output may be to any sink desired (stdio, return value, return parameter, etc.). Note that even though the barycentric coordinates are uniquely determined by only 2 numbers per node, you should output all 3 numbers per node.
# Examples
Example cases are formatted as:
```
N
x0,y0,z0
x1,y1,z1
x2,y2,z2
...
```
where the first line is the input `N`, and all following lines form a node `x,y,z` which should be in the output exactly once. All numbers are given as approximate floating point numbers.
```
0
1,0,0
0,1,0
0,0,1
1
1,0,0
0,1,0
0,0,1
0.5,0,0.5
0.5,0.5,0
0,0.5,0.5
2
1,0,0
0,1,0
0,0,1
0.667,0,0.333
0.667,0.333,0
0.333,0,0.667
0.333,0.333,0.333
0.333,0.667,0
0,0.333,0.667
0,0.667,0.333
3
1,0,0
0.75,0,0.25
0.75,0.25,0
0.5,0,0.5
0.5,0.25,0.25
0.5,0.5,0
0.25,0,0.75
0.25,0.25,0.5
0.25,0.5,0.25
0.25,0.75,0
0,0,1
0,0.25,0.75
0,0.5,0.5
0,0.75,0.25
0,1,0
```
# Scoring
This is code golf; shortest code in bytes wins. Standard loopholes apply. You may use any built-ins desired.
[Answer]
## CJam (22 bytes)
```
{):X),3m*{:+X=},Xdff/}
```
This is an anonymous block (function) which takes `N` on the stack and leaves an array of arrays of doubles on the stack. [Online demo](http://cjam.aditsu.net/#code=2%0A%0A%7B)%3AX)%2C3m*%7B%3A%2BX%3D%7D%2CXdff%2F%7D%0A%0A~%60)
### Dissection
```
{ e# Define a block
):X e# Let X=N+1 be the number of segments per edge
),3m* e# Generate all triplets of integers in [0, X] (inclusive)
{:+X=}, e# Filter to those triplets which sum to X
Xdff/ e# Normalise
}
```
[Answer]
# Haskell, 53 bytes
```
f n|m<-n+1=[map(/m)[x,y,m-x-y]|x<-[0..m],y<-[0..m-x]]
```
[Answer]
# Python 3, 87 bytes
This is actually supposed to be a comment to [the solution by TheBikingViking](https://codegolf.stackexchange.com/a/90801/58861) but I don't have enough reputation for comments.
One can save a few bytes by only iterating over the variables `i,j` and using the fact that with the third one they add up to `n+1`.
```
def f(n):d=n+1;r=range(n+2);print([[i/d,j/d,(d-i-j)/d]for i in r for j in r if d>=i+j])
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/), 10 bytes
```
ÌL<¤/3ãDOÏ
```
**Explanation**
```
ÌL< # range(1,n+2)-1
¤/ # divide all by last element (n+1)
3ã # cartesian product repeat (generate all possible triples)
DO # make a copy and sum the triples
Ï # keep triples with sum 1
```
[Try it online](http://05ab1e.tryitonline.net/#code=w4xMPMKkLzPDo0RPw48&input=Mw)
[Answer]
## Mathematica, ~~44~~ 43 bytes
```
Select[Range[0,x=#+1]~Tuples~3/x,Tr@#==1&]&
```
This is an unnamed function taking a single integer argument. Output is a list of lists of exact (reduced) fractions.
Generates all 3-tuples of multiples of `1/(N+1)` between 0 and 1, inclusive, and then selects those whose sum is 1 (as required by barycentric coordinates).
[Answer]
# [MATL](http://github.com/lmendo/MATL), 17 bytes
```
2+:qGQ/3Z^t!s1=Y)
```
[Try it online!](http://matl.tryitonline.net/#code=Mis6cUdRLzNaXnQhczE9WSk&input=Mw)
### Explanation
The approach is the same as in other answers:
1. Generate the array `[0, 1/(n+1), 2/(n+1), ..., 1]`, where `n` is the input;
2. Generate all 3-tuples with those values;
3. Keep only those whose sum is `1`.
More specifically:
```
2+ % Take input and add 2: produces n+2
:q % Range [0 1 ... n+1]
GQ/ % Divide by n+1 element-wise: gives [0, 1/(n+1), 2/(n+1)..., 1]
3Z^ % Cartesian power with exponent 3. Gives (n+1)^3 × 3 array. Each row is a 3-tuple
t % Duplicate
!s % Sum of each row
1= % Logical index of entries that equal 1
Y) % Use that index to select rows of the 2D array of 3-tuples
```
[Answer]
## [Jellyfish](https://github.com/iatorm/jellyfish/blob/master/doc.md), ~~37~~ 33 bytes
*Thanks to Zgarb for saving 4 bytes.*
```
p
*%
# S
`
=E S
`/
1+r#>>i
3
```
[Try it online!](http://jellyfish.tryitonline.net/#code=cAoqJQojIFMKYAo9RSAgIFMKYC8KMStyIz4-aQogICAz&input=Mg)
Like my Mathematica and Peter's CJam answers, this generates a set of candidate tuples and then selects only those that sum to 1. I'm not entirely happy with the layout yet, and I wonder whether I can save some bytes with hooks or forks, but I'll have to look into that later.
[Answer]
# Perl 6: ~~50~~ 40 bytes
```
{grep *.sum==1,[X] (0,1/($_+1)...1)xx 3}
```
Returns a sequence of 3-element lists of (exact) rational numbers.
Explanation:
* `$_`
Implicitly declared parameter of the lambda.
* `0, 1/($_ + 1) ... 1`
Uses the sequence operator `...` to construct the arithmetic sequence
that corresponds to the possible coordinate values.
* `[X] EXPR xx 3`
Takes the Cartesian product of three copies of EXPR, i.e. generates all possible 3-tuples.
* `grep *.sum == 1, EXPR`
Filter tuples with a sum of 1.
[Answer]
# Ruby, 62
I'd be surprised if this can't be improved on:
```
->x{0.step(1,i=1.0/(x+1)){|a|0.step(1-a,i){|b|p [a,b,1-a-b]}}}
```
Taking the advice latent in the puzzle, this calculates the second node options based on the first, and the third node by subtracting the first two.
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 24 bytes
```
+:1f
yg:2j:eaL+?/g:Lz:*a
```
[Try it online!](http://brachylog.tryitonline.net/#code=KzoxZgp5ZzoyajplYUwrPy9nOkx6Oiph&input=MQ&args=Wg&debug=on)
[Answer]
# Python 3, 106 bytes
```
def f(n):r=range(n+2);print([x for x in[[i/-~n,j/-~n,k/-~n]for i in r for j in r for k in r]if sum(x)==1])
```
A function they takes input via argument and prints a list of lists of floats to STDOUT.
Python is not good at Cartesian products...
**How it works**
```
def f(n): Function with input iteration number n
r=range(n+2) Define r as the range [0, n+1]
for i in r for j in r for k in r Length 3 Cartesian product of r
[i/-~n,j/-~n,k/-~n] Divide each element of each list in the product
by n+1
[x for x in ... if sum(x)==1] Filter by summation to 1
print(...) Print to STDOUT
```
[Try it on Ideone](http://ideone.com/yuki0R)
[Answer]
# [Actually](https://github.com/Mego/Seriously), 15 bytes
This uses an algorithm similar to the one in [TheBikingViking's Python answer](https://codegolf.stackexchange.com/a/90801/47581). Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=dTt1cuKZgC8zQOKImWDOozE9YOKWkQ&input=Mw)
```
u;ur♀/3@∙`Σ1=`░
```
**Ungolfed:**
```
u; Increment implicit input and duplicate.
ur Range [0..n+1]
♀/ Divide everything in range by (input+1).
3@∙ Take the Cartesian product of 3 copies of [range divided by input+1]
`Σ1=` Create function that takes a list checks if sum(list) == 1.
░ Push values of the Cartesian product where f returns a truthy value.
```
[Answer]
# Ruby, ~~77~~ 74 bytes
Another answer using the algorithm in [TheBikingViking's Python answer](https://codegolf.stackexchange.com/a/90801/47581). Golfing suggestions welcome.
```
->n{a=[*0.step(1,i=1.0/(n+1))];a.product(a,a).reject{|j|j.reduce(&:+)!=1}}
```
Another 74-byte algorithm based on [Not that Charles's Ruby answer](https://codegolf.stackexchange.com/a/90828/47581).
```
->x{y=x+1;z=1.0/y;[*0..y].map{|a|[*0..y-a].map{|b|p [a*z,b*z,(y-a-b)*z]}}}
```
[Answer]
## JavaScript (Firefox 30-57), ~~88~~ 81 bytes
```
n=>[for(x of a=[...Array(++n+1).keys()])for(y of a)if(x+y<=n)[x/n,y/n,(n-x-y)/n]]
```
Returns an array of arrays of floating-point numbers. Edit: Saved 7 bytes by computing the third coordinate directly. I tried eliminating the `if` by calculating the range of `y` directly but it cost an extra byte:
```
n=>[for(x of a=[...Array(++n+1).keys()])for(y of a.slice(x))[x/n,(y-x)/n,(n-y)/n]]
```
]
|
[Question]
[
### Goal
Using the programming language of your choice, write the **shortest program** to eliminate comments from a string representing a C program.
---
### Input
The string can be taken as any form of input, but it may also be taken as a variable.
---
### Instructions
Two different kinds of comments are to be removed:
* **multiline comments**, starting with `/*` and ending with `*/`
* **single line comments**, starting with `//` and ending with Linux-style line breaks (LF, `\n`)
Comments within strings are not to be deleted. For the purpose of this challenge, you only need to consider `"`-delimited strings. In particular, you can ignore the possibility of `'`-delimited character literals. You may also ignore trigraphs and line continuations (`/\<LF>*...`).
---
### Examples
Input:
```
#include <stdio.h>
int main(int argc, char** argv)
{
// this comment will be removed
if (argc > 1) {
printf("Too many arguments.\n"); // this too will be removed
return 1;
}
printf("Please vist http://this.will.not.be.removed.com\n");
printf("/* This will stay */\n");
printf("\"/* This will stay too */\"\n");
printf("//and so will this\\");
// but not this
printf("just \"ano//ther\" test.");
return 0;
}
```
Output:
```
#include <stdio.h>
int main(int argc, char** argv)
{
if (argc > 1) {
printf("Too many arguments.\n");
return 1;
}
printf("Please vist http://this.will.not.be.removed.com\n");
printf("/* This will stay */\n");
printf("\"/* This will stay too */\"\n");
printf("//and so will this\\");
printf("just \"ano//ther\" test.");
return 0;
}
```
---
Input:
```
/*
this shall disappear
*/
#include <string>
int main(int argc, char** argv)
{
string foo = ""/*remove that!**/;
// Remove /* this
int butNotThis = 42;
// But do */ remove this
int bar = 4 /*remove this*/* 3; // but don't remove that 3. */
return 0;//just a comment
}/*end of the file has been reached.*/
```
Output:
```
#include <string>
int main(int argc, char** argv)
{
string foo = "";
int butNotThis = 42;
int bar = 4 * 3;
return 0;
}
```
[Answer]
# Shell + coreutils + gcc compiler collection, 31 bytes
This answer may seem a bit loopholey, but I didn't see anything specifically banning it in the question.
Rather than using clumsy regular expressions, why not use the tool that was built for the job. It should have no problem giving correct results:
```
cpp -fpreprocessed -o- -|sed 1d
```
Takes input from STDIN and output to STDOUT. Normally `ccp` will do all preprocessing (header files, macro expansion, comment removal, etc), but with the `-fpreprocessed` option, it will skip most of the steps, but it will still remove comments. In addition, cpp adds a line like `# 1 "<stdin>"` to the beginning of the output, so the `sed` is there to delete it.
[Answer]
# [Retina](https://github.com/mbuettner/retina), 35 + 1 + 2 = 38 bytes
This program consists of two files, hence I've included a [1-byte penalty for the second file](https://codegolf.meta.stackexchange.com/a/4934/8478).
```
//.*|/\*[\s\S]*?\*/|("(\\.|[^"])*")
```
```
$1
```
This is a simple regex replacement, using the .NET flavour (although this would work the same in most other flavours).
The idea is to match both comments and strings, but only write the match back if it was a string. By matching the strings explicitly, they are skipped when searching for comments.
[Answer]
## Java 365
```
String a(String s){String o="";int m=1;for(int i=0;i<s.length();i++){String u=s.substring(i,Math.min(i+2,s.length()));char c=s.charAt(i);switch(m){case 1:m=u.equals("/*")?5:u.equals("//")?4:c=='"'?3:1;break;case 3:m=c=='"'?1:c=='\\'?2:3;break;case 2:m=3;break;case 4:m=c=='\n'?1:4;continue;case 5:m=u.equals("*/")?1:5;i+=m==1?1:0;continue;}o+=m<4?c:"";}return o;}}
```
**Ungolfed**
```
public static final int DEFAULT = 1;
public static final int ESCAPE = 2;
public static final int STRING = 3;
public static final int ONE_LINE_COMMENT = 4;
public static final int MULTI_LINE_COMMENT = 5;
String clear(String s) {
String out = "";
int mod = DEFAULT;
for (int i = 0; i < s.length(); i++) {
String substring = s.substring(i, Math.min(i + 2 , s.length()));
char c = s.charAt(i);
switch (mod) {
case DEFAULT: // default
mod = substring.equals("/*") ? MULTI_LINE_COMMENT : substring.equals("//") ? ONE_LINE_COMMENT : c == '"' ? STRING : DEFAULT;
break;
case STRING: // string
mod = c == '"' ? DEFAULT : c == '\\' ? ESCAPE : STRING;
break;
case ESCAPE: // string
mod = STRING;
break;
case ONE_LINE_COMMENT: // one line comment
mod = c == '\n' ? DEFAULT : ONE_LINE_COMMENT;
continue;
case MULTI_LINE_COMMENT: // multi line comment
mod = substring.equals("*/") ? DEFAULT : MULTI_LINE_COMMENT;
i += mod == DEFAULT ? 1 : 0;
continue;
}
out += mod < 4 ? c : "";
}
return out;
}
```
[Answer]
**Python2 - ~~163~~ 134 bytes**
```
import re
def f(s):
for x in re.findall(r'("[^\n]*"(?!\\))|(//[^\n]*$|/(?!\\)\*[\s\S]*?\*(?!\\)/)',s,8):s=s.replace(x[1],'')
print s
```
As you can [see here](https://regex101.com/r/lP0tN2/1), the regex consists of 2 alternating capturing groups. The first one captures all the quoted strings. The second one all the comments.
All we need to do, is removing everything captured by the 2nd group.
Example:
```
Python 2.7.9 (default, Dec 11 2014, 04:42:00)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> def f(s):
... for x in re.findall(r'("[^\n]*"(?!\\))|(//[^\n]*$|/(?!\\)\*[\s\S]*?\*(?!\\)/)',s,8):s=s.replace(x[1],'')
... print s
...
>>> code = r'''#include <stdio.h>
...
... int main(int argc, char** argv)
... {
... // this comment will be removed
... if (argc > 1) {
... printf("Too many arguments.\n"); // this too will be removed
... return 1;
... }
... printf("Please vist http://this.will.not.be.removed.com\n");
... printf("/* This will stay */\n");
... printf("\"/* This will stay too */\"\n");
... printf("//and so will this\\");
... // but not this
... printf("just \"ano//ther\" test.");
... return 0;
... }
... /*
... this shall disappear
... */
... #include <string>
... int main(int argc, char** argv)
... {
... string foo = ""/*remove that!**/;
... // Remove /* this
... int butNotThis = 42;
... // But do */ remove this
... int bar = 4 /*remove this*/* 3; // but don't remove that 3. */
... return 0;//just a comment
... }/*end of the file has been reached.*/'''
>>> f(code)
#include <stdio.h>
int main(int argc, char** argv)
{
if (argc > 1) {
printf("Too many arguments.\n");
return 1;
}
printf("Please vist http://this.will.not.be.removed.com\n");
printf("/* This will stay */\n");
printf("\"/* This will stay too */\"\n");
printf("//and so will this\\");
printf("just \"ano//ther\" test.");
return 0;
}
#include <string>
int main(int argc, char** argv)
{
string foo = "";
int butNotThis = 42;
int bar = 4 * 3;
return 0;
}
```
[Answer]
# Rebol - 151
```
f: func[t][Q:{"}W: complement charset Q parse t[any[[Q any["\\"|"\"Q | W]Q]|[a:[["//"to[lf | end]]|["/*"thru"*/"]]b:(remove/part a b):a skip]| skip]]t]
```
Ungolfed + some annotations:
```
f: func [t] [
Q: {"}
W: complement charset Q ;; any char thats not a double quote
; rule to parse t (c program) - it can be ANY of
; 1. string
; 2. OR comment (if so then remove)
; 3. OR pass thru
parse t [
any [
;; 1. String rule
[Q any ["\\" | "\" Q | W] Q]
;; 2. OR comments rule
| [
a: ;; mark beginning of match
[
;; // comment OR /* comment */
["//" to [lf | end]] | ["/*" thru "*/"]
]
b: ;; mark end of match
(remove/part a b) :a skip ;; remove comment
]
;; 3. OR allow thru (so not a String or Comment)
| skip
]
]
t
]
```
[Answer]
# PHP
Converting @Martin Ender's answer for php:
```
$str = preg_replace_callback('/\/\/.*|\/\*[\s\S]*?\*\/|("(\\.|[^"])*")/m',
function($matches){
if(\is_array($matches) && (\count($matches) > 1)){
return $matches[1];
}else{
return '';
}
}, $str);
```
now `$str` has lost single- and multi-line comments.
This is useful for stripping comments in JSON data before feeding to `json_decode()`.
[Answer]
**C# (262 chars):**
From this very good [SO](https://stackoverflow.com/questions/3524317/regex-to-strip-line-comments-from-c-sharp/3524689#3524689) answer:
```
string a(string i){return Regex.Replace(i, @"/\*(.*?)\*/|//(.*?)\r?\n|""((\\[^\n]|[^""\n])*)""|@(""[^""]*"")+", m => { var v = m.Value; if (v.StartsWith("/*") || v.StartsWith("//")) return v.StartsWith("//") ? "\r\n" : ""; return v; }, RegexOptions.Singleline);
```
[Answer]
# JS (ES6), 47 chars (wip)
DEMO: <http://codepen.io/anon/pen/dPEMro>
```
a=b=>b.replace(/(\/\*[^]*?\*\/|\/\/.*)\n?/g,"")
```
Inspired by my codegolfed minifiers: <http://xem.github.io/miniMinifier/>
doesn't handle comments in strings yet...
I'm curious to see if it's possible to achieve that in JS regexes.
]
|
[Question]
[
The video game [Minecraft](http://en.wikipedia.org/wiki/Minecraft) is all about placing and removing different types of blocks in the 3D [integer lattice](http://en.wikipedia.org/wiki/Integer_lattice) that makes up the virtual world. Each lattice point can contain exactly one block or be empty (an "[air](http://minecraft.gamepedia.com/Air)" block officially). In this challenge, we will only be concerned with one horizontal 2D plane of the 3D world, and one type of block: [chests](http://minecraft.gamepedia.com/Chest).
Chests let players store items. When two chests are orthogonally adjacent in the same horizontal plane, their textures link up and a double chest with twice the capacity forms. Nothing bigger than a double chest can be made; there are no triple chests nor quadruple chests.
A chest block can only be placed in an empty lattice point if its four orthogonally adjacent points are all empty, or if exactly one contains a chest block that is not already part of a double chest. These placement rules ensure that there can never be any ambiguity about which chest blocks link to form double chests.
For example, suppose `.` is empty space and `C` is a chest: (The numbers are also empty space and just for identification purposes.)
```
.......C..
.1.C2.C3..
........5C
.CC4..CC..
..........
```
* A chest can be placed in spot 1 because its 4 neighbors are empty.
* A chest can be placed in spot 2 because the neighboring chest is not (yet) part of a double chest.
* A chest can't be put in spot 3 because there would be ambiguity over how the double chest forms.
* A chest can't be placed in spot 4 because the neighboring chest is already part of a double chest.
* A chest can be placed in spot 5. The diagonally neighboring double chest doesn't affect anything.
Assuming the area beyond the grid is empty, changing every `.` in the grid to a `*` if a chest could be placed there results in this:
```
******.C**
***C**C.**
*..***..*C
.CC.*.CC.*
*..***..**
```
Not all of the `*` spaces can be occupied with chests at the same time of course, but if you only had one chest, it could be placed in any of them.
# Challenge
Write a program or function that takes in a `.` and `C` grid, and changes every `.` to a `*` if a chest could be placed there, printing or returning the resulting grid.
* Input can be from stdin or a file or as a string argument to a function.
* You may assume the input is well formed - i.e. a perfectly rectangular grid of text, at least 1 character wide and tall, only containing `.` and `C` You may optionally assume there is a trailing newline after the last row (and there may be one in the output).
* You may assume the arrangement of chests in the input is consistent with the rules above. There will never be ambiguities about which chests form double chests.
* If desired, you may use any three distinct [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters in place of `.`, `C`, and `*`. You may not use something else in place of newlines.
* All the chests are normal chests. Not [trapped chests](http://minecraft.gamepedia.com/Trapped_Chest) or [ender chests](http://minecraft.gamepedia.com/Ender_Chest).
# Scoring
The submission with the [fewest bytes](https://mothereff.in/byte-counter) wins.
*For a Minecraft related challenge that's a bit more challenging, try [Nether Portal Detection](https://codegolf.stackexchange.com/q/45488/26997).*
[Answer]
# CJam, ~~82 76 66 62 58~~ 54 bytes
```
qN/::~4{[8_]f/[9_]f*z{[{1$8-g)+}*]W%}%}*{_8<\2<8?}f%N*
```
Input format expects `0` for air cell and `8` for a chest cell. Output contains `1` for all cells that can be placed with a Chest.
*UPDATE* : ~~Fixed a bug. Increased by 3 bytes :(~~ golfed further :) . 4 bytes saved thanks to @Sp3000
Example input:
```
0000000800
0008008000
0000000008
0880008808
0000000000
```
Output:
```
1111110811
1110018010
1008800108
0880088008
1008800110
```
I think I am done golfing for now...
**Explanation**
```
qN/::~ "This part converts the input into array of integer array";
qN/ "Split input on new line";
::~ "Parse each character in each row as integer";
4{[8_]f/[9_]f*z{[{1$8-g)+}*]W%}%}*
4{ ...z{ W%}%}* "Run the logic 4 times, first, columns in correct order, then,";
"columns in reverse order, then for rows";
[8_]f/[9_]f* "Convert adjacent chests represented by two 8 into two 9";
"This happens for all the rows in the columns iterations and";
"for all the columns in the rows iterations";
{ }% "For each row/column";
[{ }*] "Reduce and wrap it back in the array";
:I8- "Store the second number in I, remove 8 from it";
g "Do signum. Now we have -1 for < 8 number, 0 for 8 and 1 for > 8";
)+I "Increment to get 0, 1 & 2. Add it to first number and put I back";
{_8<\2<8?}f%N* "This part converts the output from previous iterations";
"to 3 character based final output and prints it";
{ }f% "Map each row using the code block";
_8< 8? "If the value is greater than 7, make it 8, else:";
\2< "If the value is greater than 1, make it 0, else 1";
N* "Join the arrays using new line";
```
[Try it online here](http://cjam.aditsu.net/#code=qN%2F%3A%3A~4%7B%5B8_%5Df%2F%5B9_%5Df*z%7B%5B%7B1%248-g)%2B%7D*%5DW%25%7D%25%7D*%7B_8%3C%5C2%3C8%3F%7Df%25N*&input=0000000800%0A0000008000%0A0008800008%0A0880088008%0A0008800000)
[Answer]
# .NET Regex ([Retina](https://github.com/mbuettner/retina)), ~~434~~ ~~416~~ 310 + 1 = 311 bytes
After the last challenge I answered in regex (the Nether Portal Challenge linked to in this challenge), I finally set out to write a command-line tool, which acts as an interpreter for .NET-style regular expressions, so I can answer questions with regex without being challenged that they're not a stand-alone language. I've named it Retina.
Now, this challenge doesn't lend itself very well to a regex submission, but I just had to use Retina now. ;) (Plus, Sp3000 challenged me to do so in chat.) So here it is:
**Regex file**
```
m`(?<=(?=.(.)*).*)(?<=((?<=(?<2>C|C(?(1)!)(\n|(?<-1>.))*)?)C(?=(?<2>C|(\n|(?<-1>.))*(?(1)!)C)?)(()(?(6)!)|(?<=^(?(7)!)(?<-7>.)*C).*\n(.)*()(?(8)!)))?){2}_(?=(?<2>((?(10)!)()|(?(11)!)()(.)*\n.*(?=C(?<-12>.)*(?(12)!)$))(?<=(?<2>C|C(?(1)!)(\n|(?<-1>.))*)?)C(?=(?<2>C|(\n|(?<-1>.))*(?(1)!)C)?))?){2}(?<-2>)?(?(2)!)
```
**Replacement file**
```
*
```
The regex file is mostly just the regex, except that ``` lets you put a few options in the file, in this case simply multiline mode. When given two files, Retina automatically assumes replace-all mode. These two files define a program which reads the input from STDIN and prints the result to STDOUT.
You can also test it on [RegexHero](http://regexhero.net/tester/?id=e62700a4-7ee3-4074-a04f-f96976b5a5b7) and [RegexStorm](http://regexstorm.net/tester?p=(%3f%3c%3d(%3f%3d.(.)*).*)(%3f%3c%3d((%3f(8)%5e(%3f(7)!)(%3f%3c-7%3e.)*)(%3f%3c%3d(%3f%3c2%3eC%7cC(%3f(1)!)(%5cn%7c(%3f%3c-1%3e.))*)%3f)C(%3f%3d(%3f%3c2%3eC%7c(%5cn%7c(%3f%3c-1%3e.))*(%3f(1)!)C)%3f)(()(%3f(6)!)%7c.*%5cn(.)*()(%3f(8)!)))%3f)%7b2%7d_(%3f%3d(%3f%3c2%3e((%3f(10)!)()%7c(%3f(11)!)()(.)*%5cn.*)(%3f%3c%3d(%3f%3c2%3eC%7cC(%3f(1)!)(%5cn%7c(%3f%3c-1%3e.))*)%3f)C(%3f%3d(%3f%3c2%3eC%7c(%5cn%7c(%3f%3c-1%3e.))*(%3f(1)!)C)%3f)(%3f(11)(%3f%3c-12%3e.)*(%3f(12)!)%24))%3f)%7b2%7d(%3f%3c-2%3e)%3f(%3f(2)!)&i=_______C_________%0d%0a___C__C_____C____%0d%0a____C____C__C____%0d%0a_CC___CC______CC_%0d%0a___C_____________%0d%0a&o=m). The regex works both with and without trailing newline, and uses `_` in place of `.`. (Apparently, RegexStorm occasionally has problems if there is no trailing newline, but RegexHero seems to handle either case fine.)
There is a horrible amount of duplication in the regex, and I have a couple of ideas for shortening it significantly... I'll give that a try later and then add an explanation. In the meantime, let me know if you can find any inputs which yield a wrong result.
[Answer]
# J, ~~75 73~~ 68 bytes
```
(+.0j1^i.4)(+:@](LF,@:,.~'*.C'{~>.)(2=f)+.[f]*f=.[:+/|.!.0)'C'&=;._2
```
Uses the format in the question, using `.`/`*`/`C` for space/usable space/chest, respectively.
Edit: fixes a small bug (I accidentally used a torus instead of properly treating the surrounding as empty space).
## Explanation
```
## Preparation
'C'&=;._2 NB. Map ./C to 0/1, turn into matrix
(+.0j1^i.4) NB. Compute offsets to shift into each direction
NB. (i.e. [[_1 0], [1 0], [0 _1], [0 1]] in any order)
## "Part B"
(2=f)+.[f]*f=.[:+/|.!.0 NB. This part computes a matrix that is 1 for cells that
NB. cannot contain a chest:
[:+/|.!.0 NB. Sum of shifts: shift in each of the four cardinal
NB. directions (using the array above) and then sum up.
f=. NB. Define this function as `f`; we'll use it some more.
]* NB. Multiply by the "is chest" matrix: this isolates
NB. double-chests.
[f NB. Sum of shifts--1 for double-chest neighbours.
(2=f) NB. Isolate cells with two neighbouring chest.
+. NB. Boolean or--either two neighbouring chests or next
NB. to a double-chest.
## Wrap up the result
(+:@] (fmt >.) PartB) NB. Maximum of the array from the above and twice the "is
+:@] >. PartB NB. chest" matrix--this is 0,1,2 for '*', '.' or chest,
NB. respectively.
## Output formatting
LF,@:,.~'*.C'{~ NB. Format output...
'*.C'{~ NB. Map 0,1,2 to '*.C' by using the value as index
LF ,.~ NB. Append line feed at end of each line
,@: NB. Ravel into one line
```
[Answer]
# C,193
2 unnecesary newlines for clarity. Changes with respect to ungolfed code include: characters as ascii codes instead of character literals; rearrangement of v=0,strlen, and strchr to save characters (strchr is the ugliest, as it means that a calculation that would otherwise be performed once only, is performed 5 times per cell!)
C functions do not accept strings as arguments or return them as values, so the best I can do is the following: `q` is a pointer to the input string. The function modifies the string and when the function returns the output is found in the original string.
```
g(char*q){int v,j,w,l;
int f(p,d){int s=0,i=w=strchr(q,10)-q+1,r;for(;w/i;i-=i-1?w-1:2)r=p+i,r>-1&r<l&&q[r]==67&&++s&&d&&f(r,0);v|=s>d;}
for(j=l=strlen(q);j--;f(j,1),46-q[j]||v||(q[j]=42))v=0;}
```
To summarize the rules:
a blank square (that does not contain C or newline) can be converted if it has max 1 neighbour with a C
...AND that neighbour has no neighbours with a C.
The function g contains a function f that recurses down from depth 1 to depth 0. With only 2 levels of recursion, a simple `f(r,0)` recursive call will do, there is no need for `f(r,d-1)`!
**Ungolfed code in test program**
Input test string is hardcoded. `gets` and `scanf` will not accept an input string with newlines in it; they chop it into pieces at each newline.
```
char n[]=".......C..\n...C..C...\n.........C\n.CC...CC..\n..........";
g(char*q){
int v,j,w,l;
int f(p,d){ //p=cell to be checked,d=recursion depth
int s=0,i=w,r; //sum of C's found so far=0, i=width
for(;w/i;i-=i-1?w-1:2) //For i in w,1,-1,-w = down,right,left,up
r=p+i, //r=cell adjacent to p
r>-1&r<l&&q[r]=='C'&&++s //If r not out of bounds and equal to C, increment s...
&&d&&f(r,0); //...and if recursion depth not yet at zero, try again one level deeper.
v|=s>d; //If the local s exceeds d, set global v to true to indicate invalid.
}
w=strchr(q,10)-q+1; //width equals index of first newline + 1
l=strlen(q); //length of whole string;
for(j=l;j--;) //for l-1 .. 0
v=0, //clear v
f(j,1), //and scan to see if it should be set
'.'-q[j]||v||(q[j]='*'); //if the character is a '.' and v is not invalid, change to '*'
}
main(){
g(n);
puts(n);
}
```
**Output based on question example**
```
******.C**
***C**C.**
*..***..*C
.CC.*.CC.*
*..***..**
```
[Answer]
# JavaScript (ES6) 124 ~~129~~
Using characters 0 (\*), 6 (C), 7(.)
```
F=s=>[for(c of(d=[o=~s.search('\n'),-o,1,i=-1],s))
d.map(j=>t-=s[i+j]==6&&~d.some(k=>s[i+j+k]==6),t=i++)|c<7|t>i&&c
].join('')
```
**Ungolfed** and explained
```
F=s=>
{
o=~s.search('\n') // offset to prev row (~ is shorter than +1 and sign does not matter)
d=[o,-o,1,-1] // array of offset to 4 neighbors
i=-1
result = '' // in golfed code, use array comprehension to build the result into an array, then join it
for (c of s) // scan each char
{
t = i++ // set a starting value in t and increment current position in i
d.forEach(j => // for each near cell, offset in j
{
if (s[i+j]==6) // if cell contains a Chest, must increment t
{
// In golfed code "~some(...)" will be -1(false) or -2(true), using decrement instead of increment
if (d.some(k=>s[i+j+k]==6)) // look for another Cheast in the neighbor's neighbors
{
// more than one chest, position invalid
t += 2
}
else
{
t += 1
}
}
})
if (c < 7 // current cell is not blank
|| t > i) // or t incremented more than once, position invalid
{
result += c // curent cell value, unchanged
}
else
{
result += 0 // mark a valid position
}
}
return result
}
```
**Test** In Firefox/FireBug console
```
a='\
7777777677\n\
7776776777\n\
7777777776\n\
7667776677\n\
7777777777\n';
console.log(F(a))
```
*Output*
```
0000007600
0006006700
0770007706
7667076670
0770007700
```
[Answer]
# Perl, 66
The regexp matching chest conflicts ended up on the long side, so no competing with CJam this time.
```
#!perl -p0
/.
/;$"=".{@-}";s%0%s/\G0/2/r!~/2((.$")?2(.$")?|2$"|$"2)2/s*1%eg
```
Uses 0 and 2 for empty and chest spaces on the input, 1 to mark the spots on the output.
Try it [here](http://ideone.com/cVbss2).
[Answer]
# Python 2 - 281 bytes
```
f=lambda x,y:sum(m[y][x-1:x+2])+m[y-1][x]+m[y+1][x]
m=[];o=''
try:
while 1:m+=[map(int,'0%s0'%raw_input())]
except:a=len(m[0]);l=len(m);m+=[[0]*a]
for y in range(l*2):
for x in range(1,a-1):
if y<l:m[y][x]*=f(x,y)
else:o+=`2if m[y-l][x]else +(f(x,y-l)<5)`
if y>=l:print o;o=''
```
*(Lines 8 and 9 are intended with a single tab character, which SE converts to 4 spaces. Every line in this program has either 0 or 1 bytes of leading whitespace.)*
Input: `0` for no chest, `2` for chest
Ouput: `0` for no chest, `2` for existing chest, `1` for possible new chest
---
God, this is horrible. I must be seriously out of practice. I threw every trick I know at it and it came out... well, it came out as 281 bytes, losing to every answer except the one in *regex*, haha. I honestly feel like I golfed it kinda well, so I'm guessing that my algorithm was just less than ideal.
**Ungolfed:**
```
def f(x,y):
"""Given x,y coords of the board, return the sum of that point and all
adjacent points.
"""
return (sum(board[y][x-1:x+2]) # (x-1,y) + (x,y) + (x+1,y)
+ board[y-1][x]
+ board[y+1][x])
board=[]
output=''
try:
while True:
row = '0%s0' % raw_input() # line from stdin with a leading and trailing 0
board.append(map(int, row)) # convert to list of ints
except:
pass # exception is thrown when stdin is empty
board_width = len(board[0])
board_height = len(board)
board.append([0]*board_width) # new row of all 0s
for y in xrange(board_height*2):
# board_height multiplied by 2 so we can use this loop to simulate two
for x in xrange(1,board_width-1):
if y < board_height: # "first loop"
board[y][x] *= f(x,y) # multiply everything on the board by itself + sum
# of neighbours
# empty cells (0) stay 0 no matter what
# lone chests (2 surrounded by 0) become 2*2==4
# double chests (2 touching another 2) are weird:
# - one chest becomes 2*(2+2)==8
# - the other chest becomes 2*(2+8)==20
else: # "second loop"
if board[y - board_height][x] != 0:
output += '2' # anything not equal to 0 is an existing chest
else:
valid = f(x, y - board_height) < 5 # if the sum of neighbours > 4, the
# current cell is either beside a
# double chest or more than one
# single chest
output += '01'[valid]
if y >= board_height: # only print during the "second loop"
print output
output=''
```
]
|
[Question]
[
# Challenge
This challenge will have you write a program that takes in two integers `n` and `m` and outputs the number non-intersecting loops on the `n` by `m` torus made by starting at `(0,0)` and only taking steps up and to the right. You can think of torus as the grid with [wraparound](https://en.wikipedia.org/wiki/Wraparound_(video_games)) both at the top and the bottom and on the sides.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes wins.
# Example
For example, if the input is `n=m=5`, one valid walk is
```
(0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (2,3) -> (2,4) ->
(2,0) -> (3,0) -> (4,0) -> (4,1) -> (4,2) -> (4,3) ->
(0,3) -> (1,3) -> (1,4) ->
(1,0) -> (1,1) -> (2,1) -> (3,1) -> (3,2) -> (3,3) -> (3,4) -> (4,4) ->
(0,4) -> (0,0)
```
as shown in the graphic.
[](https://i.stack.imgur.com/okBgBm.png)
Some example input/outputs
```
f(1,1) = 2 (up or right)
f(1,2) = 2 (up or right-right)
f(2,2) = 4 (up-up, up-right-up-right, right-right, right-up-right-up)
f(2,3) = 7
f(3,3) = 22
f(2,4) = 13
f(3,4) = 66
f(4,4) = 258
```
[Answer]
# [Python 2](https://docs.python.org/2/), 87 bytes
```
f=lambda m,n,z=0,l=[]:z==0if z in l else sum(f(m,n,(z+d)%m%(n*1j),l+[z])for d in(1,1j))
```
[Try it online!](https://tio.run/##VcqxDoMgFIXhvU9xFxOod1B0asKTGAcbJNLA1agdel@e4gSO3zn/9juXlVSMVvspvM0EAQlZN@j1ML5Y68ZZYHAEHmZ/zHB8g7DiqgTXRlahEvRsPxJ9PfAo7bqDSbloMY0ybrujE@xF@chQGeqOLqMrobAvnwJ9QvwD "Python 2 – Try It Online")
The interesting thing here is using a complex number `z` to store the coordinate of the current position. We can move up by adding `1` and move right by adding `1j`. To my surprise, modulo works on complex numbers in a way that lets us handle the wrapping for each dimension separately: doing `%m` acts on the real part, and `%(n*1j)` acts on the imaginary part.
[Answer]
# JavaScript (ES6), 67 bytes
This shorter version is derived from a Python 3.8 alternate version found by [@xnor](https://codegolf.stackexchange.com/users/20260/xnor). However, this works only for \$m\times n<32\$ in JS.
Takes input as `(m)(n)`.
```
m=>n=>(g=(k,l)=>l>>k&1?!k:g((k+m)%(m*n),l|=1<<k)+g(k-~k%m-k%m,l))``
```
[Try it online!](https://tio.run/##bczNCoJAFAXgfU9hC@Pe1GRGswhnehXFdKg7P5HRKnr1STBcaHDO6uOcW/2q@@ZxvT8T6y6t74Q3QlohQQmgWKOQWkrasPOaTgqAIoMhmK3FWL8FK0vCSAElHwpNMnRYYFX5xtne6XannYIOGA7BIE0DvloI/y98knwp2SiHmWST8D93@UgsW65@VBQzyifi@6P/Ag "JavaScript (Node.js) – Try It Online")
To have it work for any input, we could use BigInts for **73 bytes**:
```
m=>n=>(g=(k,l=k)=>l&(b=1n<<k)?!k:g((k+m)%(m*n),l|=b)+g(k-~k%m-k%m,l))(0n)
```
[Try it online!](https://tio.run/##dczNCoJAGIXhfVdhC@P7UlNnbJRw7FrUVGr@IqNVdOuTgYGYLd7VwzmX8lH29e18vQfanBrbcqt4oXkBHQfhSy6QF3IDFY91ngs8rsWhAxCeQhfUVqMvn7xCrwMRvISrgiFfIkKk0dZG90Y2O2k6aCHW@AmdMHTI6tfIHyMTSxaMjpbOjE6MLJ0mI8Z0YflFxmaYTJDss5myQdmoWZrRyL4B "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~76 73~~ 72 bytes
Takes input as `(m)(n)`.
```
m=>n=>(g=(x,y)=>g[x+=y*m]?!x:g(-~x%m,y,g[x]=1)+g(x%m,-~y%n)+--g[x])(0,0)
```
[Try it online!](https://tio.run/##bcxBDoIwEAXQvafABcmMtAIF0ZgUD2JYEIQGA60RY9oNV68QDAsg@Zv5L/Of@Tfvinf9@lCpHqWtuG15KnkKgoMmBnkq7trj5tBmt72@CqC9dltiyFBnPERPwHjT3rgSPUrHGiEgAdpCyU415bFRAioIcQg6vu@w3UrYtrBZ4rVEk5wXEs3CNubiicJo/fWnJFlQPBM7XewP "JavaScript (Node.js) – Try It Online")
### Commented
```
m => n => ( // m = width; n = height
g = ( // g is a recursive function taking:
x, y // the current coordinates (x, y) on the torus
) => //
g[ // the surrounding object of g is also used for storage
x += y * m // turn x into a key for the current coordinates
] ? // if this cell was already visited:
!x // return 1 if we're back to (0, 0), or 0 otherwise
: // else:
g( // first recursive call:
-~x % m, // move to the right
y, // leave y unchanged
g[x] = 1 // mark the current cell as visited by setting the flag g[x]
) + // add the result of
g( // a second recursive call:
x % m, // restore x in [0...m-1]
-~y % n // move up
) + //
--g[x] // clear the flag on the current cell
)(0, 0) // initial call to g with (x, y) = (0, 0)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ạƝ§=1Ȧ
²‘p/’ŒPÇƇḢÐṂ%⁸QƑƇṪÐṂL
```
A monadic Link accepting a list, `[m,n]`, which yields the count.
**[TIO-jt1qe1v9](https://tio.run/##y0rNyan8///hroXH5h5abmt4YhnXoU2PGmYU6D9qmHl0UsDh9mPtD3csOjzh4c4m1UeNOwKPTQQK7FwFFvD5//@/oY4hAA "Jelly – Try It Online")** ...although there is little point, it's way too inefficient.
(I can't even run `[2,3]` locally with 16GB ram)!
### How?
Brute force - creates coordinates of a tiled version big enough then filters the power-set of these points to those paths with neighbours only increasing by one in a single direction, then filters to those starting at a minimal coordinate (i.e. the origin) and, at the same time, removes this start coordinate from each. Then uses modulo arithmetic to wrap back to a torus and filters out any containing duplicate coordinates (i.e. those containing intersections) and, finally, filters to those with minimal ending coordinates (i.e. ending back at the origin) and yields the result's length.
```
ạƝ§=1Ȧ - Link 1: all neighbours differ by 1 in exactly one direction
Ɲ - for neighbours:
ạ - absolute difference
§ - sum each
=1 - equal to one (vectorises)
Ȧ - any and all? (falsey if empty or contains a falsey value when flattened)
²‘p/’ŒPÇƇḢÐṂ%⁸QƑƇṪÐṂL - Main Link: list of integers, [m,n]
² - square (vectorises) -> [m*m, n*n]
‘ - increment (vectorises) -> [m*m+1, n*n+1]
/ - reduce with:
p - Cartesian product
’ - decrement (vectorises) -> all the coordinates of an m*m by n*n grid
- including [0, 0] and [m*m, n*n]
ŒP - power-set -> all paths going either up OR right at each step, but not
- necessarily by only 1, and
- necessarily both up and right (e.g. [...[1,3],[5,7],[6,2],...])
Ƈ - filter keep those for which:
Ç - call last Link (1) as a monad
- ...now all remaining paths do only go in steps
- of one up or one right
ÐṂ - filter keep those minimal under:
Ḣ - head - removes the 1st coordinate from each and yields them for the filter
- ...so only those which started at [0,0] but without it
%⁸ - modulo by the left argument ([m,n]) (vectorises)
Ƈ - filter keep those for which:
Ƒ - is invariant when:
Q - de-duplicated
- ...so no repetitions of torus coordinates (and we already removed
- the first [0,0] which must be present exactly twice)
ÐṂ - filter keep those minimal under:
Ṫ - tail
- ...so only those which ended at [0,0]
L - length
```
[Answer]
## Haskell, ~~88~~ 80 bytes
```
n#m|let(x!y)a|elem(x,y)a=0^(x+y)|b<-(x,y):a=(mod(x+1)n!y)b+(x!mod(y+1)m)b=0!0$[]
```
[Try it online!](https://tio.run/##bctBC8IgGMbxe5/iHdtBWYE6T5GfJAqUCY183agdFPzuZh2128OP//PQ76d1LmffY3J2J6GLVCfrLJJwLFOxOwljpMlcTj85a0VwnQty6ktsxvL5QiyA1CjWseF6y6gXDwrm9QCwvRa/wwCkp8CBNyIqEX9kqmRqRIBsmlokyPwB "Haskell – Try It Online")
Simple brute force: try all up/right combinations, dropping those which intersect (we keep all positions we've visited in list `a`) and counting those which eventually hit positition `(0,0)` again.
The base case of the recursion is when we visit a position a second time (`elem(x,y)a`). The result is `0^0` = `1` when the position is `(0,0)` and counts towards the numbers of loops or `0` (`0^x`, with `x` non-zero) otherwise and doesn't increase the number of loops.
Edit: -8 bytes thanks to @xnor.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 44 bytes
```
×ƝṪ2*Ḥ_2Rḃ€2ċⱮؽ%³¬ẠƲƇịØ.Ṛ,Ø.¤ZÄZ%€ʋ€³ŒQẠ$€S
```
[Try it online!](https://tio.run/##y0rNyan8///w9GNzH@5cZaT1cMeSeKOghzuaHzWtMTrS/WjjusMzDu1VPbT50JqHuxYc23Ss/eHu7sMz9B7unKUDpA4tiTrcEqUKVHyqG0gc2nx0UiBQnQqQHfz//38THRMA "Jelly – Try It Online")
Works for 4,4, but has complexity \$O({2^m}^n)\$ so won’t scale that well.
This works by finding all possible routes of up to \$mn\$ length, filtering out those that don’t end at 0,0, and then excluding those that pass the same point twice.
[Answer]
# Java 8, 120 bytes
```
n->m->g(n,m,0,0);int g(int n,int m,int k,int l){return(l>>k)%2>0?k<1?1:0:g(n,m,(k+m)%(m*n),l|=1<<k)+g(n,m,k-~k%m-k%m,l);}
```
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/181211/52210), and also only works for inputs where \$n\*m<32\$.
[Try it online.](https://tio.run/##jZKxboMwFEX3fIWFFMkuxgKSdAjE2Sp16JSx6uASghzbLwhMqihNx35AP7E/QoEwOJk6@Ppdnyc/Xct7cRTBfqvaTIu6Ri9CwnmC0L47Zo2Vmu0ayKw8AHsai/QZbF7kFf1f01hwjnZo1ULATcALDNTQkIYkkWBRgXsF2qsZVA2qybnKbVMB1pwrMo15uFZptI6W4fJ6BVa@IVNsHoBQ/bmK0lQR/4pU8KWmJugW1SS5tMmki1U271pmqLbCdtvxILfIdInxxlYSitc3JEifHiGb1xZHNCKJa2PXxrc0vqcz185u6eyezl07v7Uxfbybu3D9YsSXPqCbbKDOy47RNqfa5oYdGsvKLrXVgMH3qOcb30O/3z/I8yH/GH4CJmzHRFnqEwYyFoaM0y7tHw)
[Answer]
## CJam (50 chars)
```
q~]:M:!a{9Yb2/\f{_W=@.+M.%a+_)a#g"WAR"=~}}:R~e_We=
```
[Online demo](http://cjam.aditsu.net/#code=q~%5D%3AM%3A!a%7B9Yb2%2F%5Cf%7B_W%3D%40.%2BM.%25a%2B_)a%23g%22WAR%22%3D~%7D%7D%3AR~e_We%3D&input=3%205). This is a program which takes two inputs from stdin.
Finally we have an answer to the question
>
> War, huh, what is it good for?
>
>
>
---
### Dissection
```
q~]:M e# Parse input, collect in array, store in M (for moduli)
:!a e# Zero and wrap in array for starting position (0, 0)
{ e# Define recursive block R
9Yb2/ e# Push [[1 0][0 1]], an array of movements
\f{ e# For each of those movements, with the current path,
_W=@.+ e# Add the movement to the last position in the path
M.% e# Apply the wrapping
a+ e# Add to one copy of the path
_)a# e# And find its index in another copy
g"WAR"=~ e# Switch on the sign of the index:
e# If the sign is -1, position not found, make a recursive call
e# If the sign is 0, found at start, push -1 to the stack
e# If the sign is 1, we have a self-intersection. We push 10 to
e# the stack for no other reason than to make the bad joke above
}
}:R
~ e# Execute R
e_We= e# Count the -1s which we pushed as sentinels
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~54~~ 39 bytes
```
ḣ2æ.2ị³¤+4
‘Ç;¥¦%³Ç=4ƊÑÇị$?
çⱮؽS
’Ñ0xÇ
```
[Try it online!](https://tio.run/##AVAAr/9qZWxsef//4bijMsOmLjLhu4vCs8KkKzQK4oCYw4c7wqXCpiXCs8OHPTTGisORw4fhu4skPwrDp@KxrsOYwr1TCuKAmcORMHjDh////zQsNA "Jelly – Try It Online")
I’ve posted this as a separate answer to my other Jelly one because it’s a completely different method. This is closer in principle to @Arnauld’s answer. It uses a recursive function that works through every possible path until it reaches a point it’s already got to, and then returns the result of a check whether it’s back to the start. I suspect a few more bytes could be shaved off. Now changed to using slice operator. It works well for up to 5x5. The recursion depth should be at most m x n.
]
|
[Question]
[
Given an expression matching the regex `/^[-~]*x$/`, evaluate it in terms of `x` and output a string matching the regex `/^-?x[+-]\d+$/`.
For example, the string `-~x` evaluates to `x+1`, while the string `-~-x` evaluates to `-x+1`, and the string `-~-~--x` evaluates to `x+2`.
We start from `x` and evaluate the string right to left. `-` negates the term, while `~` converts `y` to `-y-1`.
Testcases:
```
x x+0
~x -x-1
-~x x+1
~-~x -x-2
-~-~x x+2
--~~x x+0
~-x x-1
-~-x -x+1
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
The input/output format is strict. The `"x"` is mandatory.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~42~~ ~~41~~ 39 bytes
```
lambda s,x=0:'-x%+d'[len(s)%2:]%eval(s)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFYp8LWwEpdt0JVO0U9Oic1T6NYU9XIKlY1tSwxB8j@n5ZfpFCskJmnEK1eoa6jXgcidMFknS6UA6V166DCFeqxVlwKBUWZeSVA89V17dR10kBGAQA "Python 2 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~47~~ 44 bytes
```
+`--|~~
((~)|-)*x
$&+$#2
T`+`-`^~.*
~
-
--
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wXztBV7emro6LS0OjTrNGV1OrgktFTVtF2YgrJAEolxBXp6fFVcely6Wry/X/fwVXXQWXLhDX6YIZYFK3DixQAQA "Retina – Try It Online") Edit: Saved 3 bytes thanks to @MartinEnder. Expanation:
```
+`--|~~
```
Delete pairs of adjacent duplicates.
```
((~)|-)*x
$&+$#2
```
Count the number of `~`s which gives us the magnitude of the term.
```
T`+`-`^~.*
```
If the first character is a `~` then the term should be negative.
```
~
-
--
```
If the number of `~`s and `-`s is odd then the `x` should be negative.
[Answer]
# JavaScript, 59 bytes
```
x=>['-'[x.length&1]]+'x'+['+'[(x=eval(x.join` `))<0^0]]+~~x
```
[Try it online!](https://tio.run/##TY2xjsIwEER7vuIq1pZjK/SY/r5hzwgr2YBRZHOO4VYp/OshCs0VMxrNPGnu/uWnLodH0TH1tAx2YXtC0IBsRorXctsfnFPAoBAUoGBLLz8KNvcU4uXrIuWxPbcrUisvVcz20GT6fYZMUkAm348hEkjTrbnQdyyUB9@ReOTU0TSZqfQhSpOigI1svD3929KzmL8cCgmEnwiIczPb1uH66NQg0BjjFYCTUi68q7zTq6rewua6fvzT8xs)
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 102 bytes
```
$s=-1
switch -r($args[$args.Count..0]){.{$a=-$a;$s=-$s}~{$a--}}"$s`x+$a"|% *ce '+-','-'|% *ce '1x','x'
```
[Try it online!](https://tio.run/##bY5NT4QwEIbv/RUNGQWEIYtXQ0KyWa8a19tmo1i7okFZacmSsPDXseWjAbNzaDLPvPN0jvmJFyLlWYYsL3gHh6juQEQYEnH6lCylWDiQFB9i17/BOi9/ZBCs9m4d1JBECMmdzoNoWtUjNo0F4rXyILHOV/SGcWp7aPs22lMbVqqt7K4hJHYIVeXHjlVZPrUqb2W5BmHPcAnbEWI4T7bj@hIawRy3aBS3y/QkWWBs2wunjer/V1z8UJsRZ26Xnul9XmwSluLD2xdnktZ9GiQX0qfAq6OC/J1GFF6GScFFmUkFruFAY53r@e5xuy6FzL8Hzz4eRLq2JWNcCO0wPuS/k8rknpVLh4xT12Z2wbRthk/TLXNVQxrS/QE "PowerShell Core – Try It Online")
Passes an expression as a string using splatting
Then processes it from right to left
For each char, negate `$s` and `$a`, and if the char is `~` , decrement `$a`
Then concatenate them all: `$s + "x+" + $a`
Replace `+-` with `-`
Remove the useless 1 before x
[Answer]
# [Perl 5](https://www.perl.org/), 75 + 1 (-n)= 76 bytes
```
map{$y=-$y;$y--if/~/}reverse/-|~/g;printf"%sx%+d",((-1)**y/-~//)=~s/1//r,$y
```
[Try it online!](https://tio.run/##BcFBCoMwEAXQu4QIah0@LlyJhyk0loDGMBHJYDtH7/S9HHibzPZnvr0s5GX2QhRXKL4crsAlgD6K95w5pnN1TanN4@WGtqWx63sBKdAtWjACPHgxU6q/I5/xSMUo/QE "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 69 bytes
```
a;s;f(char*p){for(a=s=0;*p;a-=*p++%5*~-s)s^=2;printf("-x%+d"+!!s,a);}
```
[Try it online!](https://tio.run/##PY7LCoMwEEX3/QpNEfIwRQpdTdMfsRZCrDXQxmBSEER/PU1EujkzdxguR/GXUiFIcNBh1cuRWjJ3w4ilcKICakFyQS1jxYWu3BH3EGewoza@w4hPBWsRy3NXSgJLOGqj3t/2mV2db/Vw6m@H@Jh9pDaYzFu7rxsxowmVaE3gG1e@h33ydT9HVgskndSjo5CvdQOasSiJ007@MneDosMSfg "C (gcc) – Try It Online")
-1 byte thanks to @ThePirateBay
[Answer]
# [Ruby](https://www.ruby-lang.org/), 36 bytes
Port of [user48543‘s Python answer](https://codegolf.stackexchange.com/a/142941/11261).
```
->s{x=0
"-x%+d"[s.size%2..]%eval(s)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3VXTtiqsrbA24lHQrVLVTlKKL9Yozq1JVjfT0YlVTyxJzNIo1a6FqI6PVK9R11OtAhC6YrNOFcqC0bh1UuEI9Vi81MTlDISWfS0GhoLSkWEFJtVhB105BtVhJQVUhOt5QR8ENSMbGcqXmpUAsWLAAQgMA)
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), ~~91~~ 79 bytes
Was producing incorrect output, but for a change fixing this actually saved me bytes.
```
10>i:'-'=?v:'~'=?vv
.\r*-10r~<1-@:$~/~
d3/"+"on; .3dv?(0r/
;n^?)-10:o"x"\"-"o/
```
[Try this](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMTA+aTonLSc9P3Y6J34nPT92dlxuIC5cXHIqLTEwcn48MS1AOiR+L35cbmQzL1wiK1wib247IC4zZHY/KDByL1xuO25ePyktMTA6b1wieFwiXFxcIi1cIm8vIiwiaW5wdXQiOiItLX4tfngiLCJzdGFjayI6IiIsIm1vZGUiOiJudW1iZXJzIn0==)
[](https://i.stack.imgur.com/mlLSw.png)
[](https://i.stack.imgur.com/8gDrZ.png)
Significantly harder to parse in reverse order. Basically produce a expression of the form `ax + b`
* For a `-`, set `a` to `-a`.
* For a `~`, set `b` to `b-a`, then re-use the same code to set `a` to `-a`.
Rest of the code is printing the solution. Special cases for printing the `-` in front of `x` and needing a `+` if the extra number is not negative.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
á0:.E…-x+ì„+-¤:IgÉi¦
```
Port of [*(deleted) user48543*'s Python answer](https://codegolf.stackexchange.com/a/142941/52210).
[Try it online](https://tio.run/##ASsA1P8wNWFiMWX//8OhMDouReKApi14K8Os4oCeKy3CpDpJZ8OJacKm//8tfi14) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfaXL/8MLDaz0XB81LNOt0D685lHDPG3dQ0usKtMPd2YeWva/Vud/tFKFko5SHYjQBZN1ulAOlNatgwpDRSuUYgE).
**Explanation:**
```
á # Only keep the letters of the (implicit) input (the "x")
0: # Replace the "x" in the (implicit) input with "0"
.E # Evaluate and execute it as Python code
…-x+ì # Prepend string "-x+"
„+-¤: # Replace a potential "+-" with "-"
IgÉi # If the length of the original input is odd:
¦ # Remove the leading "-"
# (after which the result is output implicitly)
```
[Answer]
# Java 8, ~~186~~ ~~168~~ 167 bytes
```
s->{s=s.replaceAll("--|~~","");int l,i=s.length()-(l=(s=s.replace("-~","")).length())>>1;return(l-(s=s.replace("~","")).length()>0?"-"+s+~i:s+"+"+i).replace("--","");}
```
Definitely room for improvements..
-1 byte thanks to *@ceilingcat* replacing `(a-b)/2` with `a-b>>1`.
[Try it online.](https://tio.run/##jZDBTsMwDIbveworp0SdK7gStYgHYBeOiEPowsjw0ipJJ9BoXr0YtaDBAao4Upx8@f3be3M02HbW77cvY0MmRrg1zp9WAM4nG55MY2HzmQLcpeD8Dho5H6LSfD/w5ojJJNfABjxUY8T6FKtYBtsRC9wQSYH4nrNYC6E0KwOtHQNk/S49S4WSKnn2g/GJVd@IqutLHWzqg5eEP@HfbH1xLVAUscjuKhaCl1Nn0jjZGEY9ee/6R2LvcwvH1m3hwEOY@7x/AKPmCbzFZA9l26ey46dEXvqykeKVi@s/ifw/gguYjIuEFlGYFxX8YobVMH4A)
**Explanation:**
```
s->{ // Method with String as both parameter and return-type
s=s.replaceAll("--|~~",""); // Remove all "--" and "~~"
int l, // Temp integer to reduce bytes
i=s.length()-(l=(s=s.replaceAll("-~","")).length())>>1;
// Remove all "-~" and save count in `i`
return(l-(s=s.replaceAll("~","")).length()
// Remove all remaining "~"
>0? // and if its non-empty:
"-" // Start with a minus sign
+s // followed by the remaining `s`
+~i // followed by `-i-1`
: // Else:
s // Start with the remaining `s`
+"+" // followed by a plus sign
+i // followed by `i`
).replaceAll("--","");}// And then remove all "--"
```
]
|
[Question]
[
When making a *Dungeons & Dragons* character, an alternative to [rolling ability scores](https://codegolf.stackexchange.com/questions/52906/roll-my-dd-characters-ability-scores) is to assign them within a power budget called point buy. Higher ability scores cost more points, especially towards the upper end: a score of 8 is free, and raising a score by 1 costs 1 point, except raising to 15 or 16 costs 2 points, and raising to 17 or 18 costs 3 points.
```
+-------+------+
| Score | Cost |
+-------+------+
| 8 | 0 |
| 9 | 1 |
| 10 | 2 |
| 11 | 3 |
| 12 | 4 |
| 13 | 5 |
| 14 | 6 |
| 15 | 8 |
| 16 | 10 |
| 17 | 13 |
| 18 | 16 |
+-------+------+
```
In list form:
```
[(8, 0), (9, 1), (10, 2), (11, 3), (12, 4), (13, 5), (14, 6), (15, 8), (16, 10), (17, 13), (18, 16)]
```
The point buy cost is summed for all six ability scores.
```
Ability scores: 16 17 8 13 8 12
Point buy cost: 10 + 13 + 0 + 5 + 0 + 4 = 32
```
Given six ability scores, each 8 through 18, output the total point buy cost. Fewest bytes wins.
```
var QUESTION_ID=67472,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/67472/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
**Leaderboard:**
```
[Answer]
# JavaScript (ES7), ~~44~~ ~~42~~ 40 bytes
[Crossed out 44 is still regular 44 :(](https://codegolf.stackexchange.com/a/64604)
```
a=>a.map(s=>t+=s-9-~((s-14)**1.3),t=0)|t
```
*Thanks to [@apsillers](https://codegolf.stackexchange.com/users/7796/apsillers) for saving 2 bytes!*
## Explanation
The interesting part is `-1-~((s-14)**1.3)`. `(s-14)**1.3` produces `1`, `2`, `4` and `6` for the values `15 - 18`. Any number that is less than `15` causes an error because the JavaScript implementation of exponential cannot operate on negative values with a fractional exponent. Basically, any value for `s < 15` causes it to return `NaN`, so the `-1-~` is there to cast it to a number (`0`).
```
a=> // a = input scores as an array of numbers
a.map(s=> // for each passed score
t+= // add to the total
s-9 // point value = s - 8 (-1 used for next line)
-~((s-14)**1.3), // add extra points for scores 15 - 18
t=0 // t = total points (this happens BEFORE the map call)
)
|t // return the total points
```
### ES6 Solution (42 bytes)
```
a=>a.map(s=>t+=s-9-~[1,2,4,6][s-15],t=0)|t
```
## Test
This test uses `Math.pow` instead the exponential operator (`**`) so that it can run in any standard browser.
```
var solution = a=>a.map(s=>t+=s-9-~Math.pow(s-14,1.3),t=0)|t
```
```
Scores separated by spaces = <input type="text" id="input" value="16 17 8 13 8 12" />
<button onclick="result.textContent=solution(input.value.split(' '))">Go</button>
<pre id="result"></pre>
```
[Answer]
## CJam, 18 bytes
```
l~[8EG]ff-:~0fe>:+
```
or
```
l~[8EG]m*::m0fe>:+
```
[Test it here.](http://cjam.aditsu.net/#code=l~%5B8EG%5Dff-%3A~0fe%3E%3A%2B&input=%5B16%2017%208%2013%208%2012%5D)
### Explanation
The idea is decompose the point cost into three components:
```
Score: 8 9 10 11 12 13 14 15 16 17 18
0 1 2 3 4 5 6 7 8 9 10
0 0 0 0 0 0 0 1 2 3 4
0 0 0 0 0 0 0 0 0 1 2
--------------------------------
Cost: 0 1 2 3 4 5 6 8 10 13 16
```
All three components can be computed via a single subtraction and restricting the result to non-negative values.
```
l~ e# Read and evaluate input.
[8EG] e# Push [8 14 16].
ff- e# For each pair from the two lists, subtract one from the other.
:~ e# Flatten the result.
0fe> e# Clamp each difference to non-negative values.
:+ e# Sum them all up.
```
[Answer]
# Pyth, 14 bytes
```
s>#0-M*Q+14yB8
```
[Test suite](https://pyth.herokuapp.com/?code=s%3E%230-M%2aQ%2B14yB8&input=%5B16%2C+17%2C+8%2C+13%2C+8%2C+12%5D&test_suite=1&test_suite_input=%5B16%2C+17%2C+8%2C+13%2C+8%2C+12%5D%0A%5B8%2C9%2C10%2C11%2C12%2C13%5D%0A%5B14%2C15%2C16%2C17%2C18%2C18%5D&debug=0)
This uses the same fundamental means of calculation as Martin Büttner, namely:
```
max(n-8, 0) + max(n-14, 0) + max(n-16, 0)
```
That being said, the means of calculation are very different. To generate the list of numbers to subtract, I use the expression `+14yB8`. `yB8` means "Bifurcate 8 on the function y". y doubles numbers, so this gives `[8, 16]`. Then, we add on 14, giving the list `[14, 8, 16]`.
Next, we take the Cartesian product with the input and subtract every pair of values.
Next, perform the maximization operation, we simply filter for positive values only, and sum the remainder.
[Answer]
# [Samau](https://github.com/AlephAlpha/Samau/tree/master/OldSamau), 19 bytes
Not sure if the question is posted after [the last commit](https://github.com/AlephAlpha/Samau/commit/ca2e483ce371e8db45178eb5a3e5466825c3ace9) of my new language. They are both 2 hours ago. But all the features used here was added before that.
```
▐[8 14 16]`-o;0>*ΣΣ
```
Samau uses [CP737](https://en.wikipedia.org/wiki/CP737) as its default character encoding.
```
▐[8 14 16]`-o;0>*ΣΣ
‚ñê read a list of numbers
[8 14 16] push [8 14 16]
`- push the function [-]
o outer product
; duplicate
0> for each element, test if it's larger than 0
* times
ΣΣ take the sum twice because it's a 2d array
```
[Answer]
## PowerShell, 48 Bytes
```
$args|%{$t+=$_-8+@{15=1;16=2;17=4;18=10}[$_]};$t
```
(Pretty sure this isn't optimal.)
Takes input command-line arguments and pipes them into a loop `|%{...}`. Each iteration, we increment our total `$t+=` with the current number minus 8 `$_-8` plus the result of indexing into a hashtable for the more-expensive values `@{...}[$_]`. Then we simply output `$t` at the end.
[Answer]
# (üêÇüëç) Ox++, 248 bytes (62 characters)
```
üêÄüëâüåëüë∫üêÅüëâüåëüë∫üòÇüêÄüêüüåóüòÇüêÇüëâüò∑üò∫üò∫üò∑üë∫üêÅüëâüêÅüëèüêÇüôåüåôüëèüåúüêÇüê≥üåíüåïüåõüë•üåúüêÇüôåüåíüåïüåõüëèüåúüêÇüê≥üåíüåóüåõüë•üåúüêÇüôåüåíüåóüåõüë∫üêÄüëçüòÇüëÑüêÅüëÑ
```
Language I'm working on. Paste in the code [here](http://geokavel.cu.cc/emojilang.html).
]
|
[Question]
[
This is the second in a series of puzzles that I will be posting every Monday at Midnight PST. The first puzzle is located [Here](https://codegolf.stackexchange.com/questions/54147/take-it-or-leave-it-a-game-show-for-computers).
**Context:**
>
> A reclusive billionaire has created a game show to attract the world's best and brightest programmers. On Mondays at the stroke of midnight, he chooses one person from a pool of applicants to be the contestant of the week, and provides them with a game. You are this week's lucky contestant!
>
>
>
**This week's game:**
>
> The host provides you with API access to a stack of 10,000 digital envelopes. These envelopes are randomly sorted, and contain within them a dollar value, between $1 and $10,000 (no two envelopes contain the same dollar value).
>
>
> You have 4 commands at your disposal:
>
>
> 1. Read(): Read the dollar figure in the envelope at the top of the stack.
> 2. Take(): Add the dollar figure in the envelope to your game show wallet, and pop the envelope off the stack.
> 3. Pass(): Pop off the envelope on the top of the stack.
> 4. Oracle(M): Returns the mean value of the next M envelopes in the stack, not including the one you can currently Read().
>
>
>
**The Rules:**
>
> 1. If you use Pass() on an envelope, the money within is lost forever.
> 2. If you use Take() on an envelope containing $X, from that point forward, you may never use Take() on an envelope containing < $X. Take() on one of these envelopes will add $0 to your wallet.
> 3. If you use Oracle(M) on turn T, envelopes T+1 through T+M's mean will be returned. Oracle() is disabled until turn T+M.
>
>
>
Write an algorithm that finishes the game with the maximal amount of money.
If you're writing your algorithm in Python, feel free to use this controller provided by @Maltysen: <https://gist.github.com/livinginformation/70ae3f2a57ecba4387b5>
Notes 1: "Maximal" in this case means the median value in your wallet after N >= 1000 runs. I expect, though I would love to be proven wrong, that the median value for a given algorithm will converge as N increases to infinity. Feel free to try to maximize the mean instead, but I have a feeling that the mean is more likely to be thrown off by a small N than the median is.
Note 2: as all solutions to the previous part of this puzzle are valid here, reposting them has little value. Only algorithmic improvements of previous puzzles will be considered for part II.
Edit: The prize condition has been removed, in light of [this post](http://meta.codegolf.stackexchange.com/questions/5677/the-community-is-against-cash-prizes-but-should-that-be-advice-or-a-rule) on meta.
[Answer]
# Groovy $713337 $817829 $818227
### Bootstrap code:
```
class Instance {
List values = new ArrayList(1..10000); {
Collections.shuffle(values)
}
int i = 0
int value = 0
int max = 0
int nextOracle = 0
def pass() {
if (i >= 10000)
throw new NoSuchElementException()
i++
}
def take() {
if (i >= 10000)
throw new NoSuchElementException()
int v = values[i]
if (v > max) {
max = v
value += v
}
i++
}
double oracle(int m) {
if (m <= 0 || i < nextOracle || i + m >= 10000)
throw new NoSuchElementException()
nextOracle = i + m
values.subList(i + 1, i + m + 1).stream().reduce { l, r -> r+l }.get() / m
}
int read() {
if (i >= 10000)
throw new NoSuchElementException()
values[i]
}
}
```
### Algorithm
```
double square(double v) { v * v }
final double factor = Math.pow(1.5, 1.1)
int attempts = 5000
(1..attempts).stream().parallel().mapToLong {
def puzzle = new Instance()
int[] memory = 1..10000 // We will remember every envelope
int memStart = 0
while (memStart < 10000 - 3) {
int value = puzzle.read()
int i = Arrays.binarySearch(memory, memStart, 10000, value) - memStart
if (i < 0) { // We can't use the money
puzzle.pass()
continue
}
if (i == 0) { // Of course we take the lowest
puzzle.take()
memStart++
continue
}
int remaining = Arrays.stream(memory, i + 1 + memStart, 10000).sum() // Money we could win if taken
int losing = Arrays.stream(memory, memStart, memStart + i).sum() // Money we cna't win if taken
if (value > losing) { // If we pass, we lose money automatically
puzzle.take()
memStart += i + 1
} else if ((losing - value * 16 / 7) * square(Math.log(i)) > remaining / factor) {
System.arraycopy(memory, memStart, memory, ++memStart, i)
puzzle.pass()
} else {
puzzle.take()
memStart += i + 1
}
}
// It's broken down to last three elements
List values = Arrays.copyOfRange(memory, 10000 - 3, 10000)
while (!values.contains(puzzle.read())) // Skip values we can't use
puzzle.pass()
int value1 = puzzle.read()
int value2 = puzzle.oracle(1)
if (value1 == values.max() && (
values.contains(value2)
? (value1 * 2 < values.sum() && values.min() == value2)
: (value1 < values.min() / 2 + (values - [value1]).max())
)) {
puzzle.pass()
}
// Finish it
while (puzzle.i < puzzle.values.size()) {
puzzle.take()
}
puzzle.value as Long
}.sum() / attempts // Sum runs and average
```
I compare remaining values with possible values. This script is not fast (takes 1-minute per 1000x simulations)... but it will perform the simulations simultaneously.
I have no idea why my algorithm works, but it was just trial and error: lumping mathematical operations together and manipulating the constants. I ran it 5000x for the current score, in an attempt to reduce the score's fluctuations (it's +/- $4000 depending on iteration count).
Even without the oracle at the end, it should still be (barely) beating [@orlp's solution](https://codegolf.stackexchange.com/a/54207/42799) for the prior puzzle.
[Answer]
# C# - $803.603 now -> $804.760 (with oracle)
Bootstrap Code
```
public static class ShuffleExtension
{
private static Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
public class Puzzle
{
public List<int> Values = new List<int>(10000);
public Puzzle()
{
for ( int i = 1; i <= 10000; i++ )
{
Values.Add(i);
}
Values.Shuffle();
}
public int i = 0;
public int value = 0;
public int max = 0;
public int nextOracle = 0;
public void Pass() {
if ( i >= Values.Count )
throw new IndexOutOfRangeException();
i++;
}
public void Take() {
if (i >= Values.Count )
throw new IndexOutOfRangeException();
int v = Values[i];
if (v > max) {
max = v;
value += v;
}
i++;
}
public double oracle(int m) {
if (m <= 0) {
throw new IndexOutOfRangeException();
}
if ( i < nextOracle ) {
throw new IndexOutOfRangeException();
}
if ( i + 1 + m > Values.Count ) {
throw new IndexOutOfRangeException();
}
nextOracle = i + m;
var oracleValues = new List<int>();
for ( int l = 0; l < m; l++ )
{
oracleValues.Add(Values[i + 1 + l]);
}
return oracleValues.Average (v => v);
}
public int Read() {
if (i >= Values.Count )
throw new IndexOutOfRangeException();
return Values[i];
}
}
```
Game Code:
```
void Main()
{
var m = 0;
for ( int l = 0; l < 1000; l++ )
{
var game = new Puzzle();
var maxVal = 0;
var lastOracle = 0;
var lastOracleValue = 0.0m;
var oracleValueForIOf = 0;
for ( int i = 0; i < 10000; i++ )
{
var val = game.Read();
var oracleStep = 1;
var canUseOracle = (i - lastOracle >= oracleStep) && i + oracleStep + 1 <= 10000;
if ( canUseOracle )
{
var oracle = game.oracle(oracleStep);
lastOracle = i;
lastOracleValue = (decimal)oracle;
oracleValueForIOf = i + 1;
}
if ( TakeTheMoney(val, maxVal, oracleValueForIOf, lastOracleValue, i) )
{
maxVal = val;
game.Take();
}
else
{
game.Pass();
}
}
m += game.value;
}
((int)(m / 1000)).Dump();
}
private bool TakeTheMoney(int val, int maxVal, int oracleValueForIOf, decimal lastOracleValue, int i)
{
if ( val > maxVal )
{
if ( oracleValueForIOf != i + 1
&&
(val < 466.7m + (0.9352m * maxVal) + (0.0275m * i))
)
{
return true;
}
if (oracleValueForIOf == i + 1)
{
if ( val < 466.7m + (0.9352m * maxVal) + (0.0275m * i) )
{
return true;
}
if ( lastOracleValue > 466.7m + (0.9352m * val) + (0.0275m * i + 1) )
{
if ( val < 466.7m + (0.9352m * maxVal) + (0.0275m * i + 1) )
{
return true;
}
}
}
}
return false;
}
```
Credit belongs to Reto Koradi (<https://codegolf.stackexchange.com/a/54181/30910>)
Edit: Basic Use of Oracle implemented. If the next oracle is above the threshold to use expand the current envelope to the index of the Oracle Index. This doesn't hit often but IT IS an Improvement ;-)
[Answer]
# Python - $74112
Only take, if the current value is lower than the next value (i.e. you can take both).
```
def algo():
try:
o=oracle(1)
except ValueError:
take()
r=read()
if r>o:
passe()
else:
take()
```
# Python - (still calculating the mean)
This answer takes VERY LONG to calculate. It reaches around **670.000$**.
I remember each envelope I saw. Every time I have to make a decision, I generate two lists of remaining envelopes that I could potentially add to my wallet if I take the current envelope or leave it respectively.
I did not optimize the code.
```
def algo_2():
global max_taken, past
weight=0.92 #Empirically chosen.
r=read()
if len(past)==0:
past.append(r)
passe()
return
if r<max_taken:
past.append(r)
take() #the same as passe
return
coming=[x for x in range(1,10001) if x not in past and x>max_taken and x!=r ]
comingIfTake=[x for x in range(1,10001) if x not in past and x>r ]
if sum(coming)*weight<=sum(comingIfTake)+r:
past.append(r)
take()
else:
past.append(r)
passe()
```
And init\_game starts like this:
```
def init_game():
global stack, wallet, max_taken, oracle_turns, past
past=[]
```
[Answer]
# C# - $780.176
Check if the next value is within the lower 5% of all remaining values. Get more relaxed as we get to the end.
```
public class Taker
{
private List<int> remaining;
private Game game;
public Taker(Game game)
{
this.game = game;
remaining = Enumerable.Range(1, game.Size + 100).ToList();
}
int score = 0;
public int PlayGame()
{
for (int i = 0; i < game.Size; i++)
{
if (game.Read() < game.Max ||
game.Read() > selectThreshold() ||
doOracle()
)
{
remaining.Remove(game.Read());
game.Pass();
continue;
}
remaining = remaining.SkipWhile(j => j < game.Read()).ToList();
score += game.Take();
}
return score;
}
private bool doOracle()
{
return game.Oracle(1) < game.Read() &&
game.Oracle(1) > game.Max;
}
private int selectThreshold()
{
int selector = (int)(remaining.Count * 0.05);
return remaining.ElementAt(selector);
}
}
```
And my game class, very ugly, game class doesn't even validate if oracle is allowed, but since i only use Oracle(1) that shouldn't be a problem.
```
public class Game
{
private int[] list;
private int position = 0;
private int max = 0;
public int Max { get { return max; } }
public int Size { get { return list.Length; } }
public Game(int[] list)
{
this.list = list;
}
public int Read()
{
return list[position];
}
public int Take()
{
if (list[position] < max)
{
position++;
return 0;
}
max = list[position];
return list[position++];
}
public void Pass()
{
position++;
}
public int Oracle(int M)
{
int next = position + 1;
M = Math.Max(0, Math.Min(M, list.Length - next));
return new ArraySegment<int>(list, next, M).Sum();
}
}
```
[Answer]
# Java, $804,991
Score is from 1001 rounds. It is probably too close to call between this answer and [Stephan Schinkel's](https://codegolf.stackexchange.com/a/54215/2867).
This is based on my answer in the previous challenge, in that it uses the same entropy-based calculation to estimate payoffs. The main difference is that it simply now takes envelopes in pairs (1 & 2, then 3 & 4, so on) and looks at the possible combinations of take-take, take-pass, pass-take, etc. It also calculates the exact estimated score when the number of valid envelopes is really small.
The "wrapper" I wrote isn't really a true wrapper, it just gives envelopes in pairs instead of calling an `Oracle(1)` function every other round.
Overall, I would say that, despite the increased complexity, this bot really isn't better than my previous one.
## Player
```
import java.lang.Math;
public class Player2
{
public int[] V;
public Player2(int s)
{
V = new int[s];
for(int i = 0; i<V.length; i++)
{
V[i] = i+1;
}
////System.out.println();
}
public boolean [] takeQ(int x, int y)
{
//System.out.println("Look: " + x + " " + y);
boolean [] move = new boolean[]{false,false};
double max = 0;
double val = 0;
int[] nextV = V;
////System.out.println("look " + x);
int i = find(V,x);
if(i >= 0) //if found
{
//try taking first envelope
int[] newVt = takeSlice(V,i);
//System.out.println(" T: " + ats(newVt));
int j = find(newVt,y);
if(j >= 0)
{
//try taking first and second
int[] newVtt = takeSlice(newVt,j);
val = x + y + calcVal(newVtt);
//System.out.println(" TT: " + ats(newVtt) + " " + val);
if(val > max)
{
move = new boolean[]{true,true};
max = val;
nextV = newVtt;
}
}
//try taking first and passing second
int[] newVtp = passSlice(newVt,j);
val = x + calcVal(newVtp);
//System.out.println(" TP: " + ats(newVtp) + " " + val);
if(val > max)
{
move = new boolean[]{true,false};
max = val;
nextV = newVtp;
}
}
int[] newVp = passSlice(V,i);
//System.out.println(" V: " + ats(V));
//System.out.println(" P: " + ats(newVp));
int j = find(newVp,y);
if(j >= 0)
{
//try passing first and taking second
int[] newVpt = takeSlice(newVp,j);
val = y + calcVal(newVpt);
//System.out.println(" PT: " + ats(newVpt) + " " + val);
if(val > max)
{
move = new boolean[]{false,true};
max = val;
nextV = newVpt;
}
}
//try taking first and passing second
int[] newVpp = passSlice(newVp,j);
val = calcVal(newVpp);
//System.out.println(" PP: " + ats(newVpp) + " " + val);
if(val > max)
{
move = new boolean[]{false,false};
max = val;
nextV = newVpp;
}
V = nextV;
//System.out.println(" NEW: " + ats(V));
return move;
}
public static String ats(int [] a)
{
String s = "";
for(int i = 0; i < a.length; i++)
{
s += a[i] + ",";
}
return s;
}
public static int[] takeSlice (int[] list, int loc)
{
int [] newlist = new int[list.length - loc - 1];
for(int j = loc + 1; j < list.length; j++)
{
newlist[j - loc - 1] = list[j];
}
return newlist;
}
public static int[] passSlice (int[] list, int loc)
{
int [] newlist = list;
if(loc >= 0)
{
newlist = new int[list.length-1];
for(int k = 0; k < loc; k++)
{
newlist[k] = list[k];
}
for(int k = loc + 1; k < list.length; k++)
{
newlist[k-1] = list[k];
}
}
return newlist;
}
public static double calcVal(int [] list)
{
if(list.length < 8)
{
for(int i : list)
{
////System.out.print(i + ",");
}
////System.out.println();
return computeMean(list);
}
return smoothEstimate(list);
}
public static double computeMean(int[] V)
{
if(V.length == 1)
{
return V[0];
}
else if(V.length > 1)
{
double[] Es = new double[V.length];
for(int i = 0; i < V.length; i++)
{
int[] newVp = new int[V.length - 1];
for(int j = 0; j < i; j++)
{
newVp[j] = V[j];
}
for(int j = i + 1; j < V.length; j++)
{
newVp[j-1] = V[j];
}
double pass = computeMean(newVp);
int[] newVt = new int[V.length - i - 1];
for(int j = i + 1; j < V.length; j++)
{
newVt[j - i - 1] = V[j];
}
double take = V[i] + computeMean(newVt);
if(take > pass)
{
Es[i] = take;
}
else
{
Es[i] = pass;
}
}
double sum = 0;
for(double d : Es)
{
sum += d;
}
return sum/V.length;
}
else
{
return 0;
}
}
public static double smoothEstimate(int [] list)
{
double total = 0;
for(int i : list)
{
total+=i;
}
double ent = 0;
for(int i : list)
{
if(i > 0)
{
ent -= i/total * Math.log(i/total);
}
}
////System.out.println(" total " + total);
////System.out.println(" entro " + Math.exp(ent));
////System.out.println(" count " + list.length);
return total * Math.pow(Math.exp(ent),-0.5) * 4.0/3;// * 1.1287 + 0.05284);
}
public static int find(int[] list, int search)
{
int first = 0;
int last = list.length - 1;
int middle = (first + last)/2;
while( first <= last )
{
if ( list[middle] < search )
first = middle + 1;
else if ( list[middle] == search )
break;
else
last = middle - 1;
middle = (first + last)/2;
}
if(first > last)
{
return -1;
}
return middle;
}
}
```
## Controller
```
import java.lang.Math;
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
public class Controller2
{
public static void main(String [] args)
{
int size = 10000;
int rounds = 1001;
ArrayList<Integer> results = new ArrayList<Integer>();
for(int round = 0; round < rounds; round++)
{
int[] envelopes = new int[size];
for(int i = 0; i<envelopes.length; i++)
{
envelopes[i] = i+1;
}
shuffleArray(envelopes);
Player2 p = new Player2(size);
int cutoff = 0;
int winnings = 0;
for(int i = 0; i<envelopes.length; i+=2)
{
boolean [] take = p.takeQ(envelopes[i],envelopes[i+1]);
if(take[0] && envelopes[i] >= cutoff)
{
winnings += envelopes[i];
cutoff = envelopes[i];
}
if(take[1] && envelopes[i+1] >= cutoff)
{
winnings += envelopes[i+1];
cutoff = envelopes[i+1];
}
}
results.add(winnings);
}
Collections.sort(results);
System.out.println(rounds + " rounds, median is " + results.get(results.size()/2));
}
//stol... I mean borrowed from http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array
static void shuffleArray(int[] ar)
{
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
```
Bitcoin address: 1BVBs9ZEP8YY4EpV868nxi2R23YfL7hdMq
[Answer]
# Python 3 - $615570
Doesn't actually use the oracle... Eh :)
```
def algo():
global prevs
try:
prevs.append(read())
except NameError:
prevs = [read()]
if len(prevs) > 10000:
prevs = [prevs[-1]]
if read() < round(len(prevs),-1):
take()
else:
passe()
```
Builds up a list of all previous envelopes and check if the current envelope is less than the number of previous envelopes in 10 envelope increments.
[Answer]
## Python, 87,424
Here's a plain and easy algorithm, the lucky seven.
```
def LuckyNumber7():
Test = read()
if "7" in str(Test):
take()
else:
passe()
test(LuckyNumber7)
```
Basically what it does is it converts read() to a string and checks if there's a seven in it. If there is, it takes the envelope. If not, it passes it.
It averages around 81,000, I haven't been keeping track.
]
|
[Question]
[
#### Background
[*Scrabble*](https://en.wikipedia.org/wiki/Scrabble) is a word game in which players collaboratively build a board consisting of letter tiles that spell words. Each word must be connected to another word, and players gain points based on the letters they use and where they are placed. Words can be spelled either from left-to-right or top-to-bottom, and their validity is determined via the Scrabble Dictionary. Each contiguous set of more than one letter in a row or column must be a valid word.
#### The Challenge
Your challenge is to write a function that accepts a 2D grid of letters and determines whether or not it consitutes a valid Scrabble board. A board is valid if every word in every column and row is a valid word according to [this text file containing a Scrabble Dictionary](https://raw.githubusercontent.com/redbo/scrabble/master/dictionary.txt).
Your function should take a 2D grid of characters and a list of valid words as input. The board is assumed to be contiguous (every word is connected to the board) and padded with spaces to be rectangular. Your function must return a truthy value of your choice if the board is valid, and a falsey one otherwise. The board is assumed to contain at least 2 letters. This is [Code Golf,](https://codegolf.stackexchange.com/questions/tagged/code-golf) so the shortest answer wins, and the usual rules/loopholes apply.
#### Test Cases
All boards' validity is determined according to [this list of Scrabble words.](https://scrabble.hasbro.com/en-us/tools)
Valid boards:
```
MAP
O APP
NEW O
T EEL
HAD E
```
---
```
DANCING
A
SEEING
A O
LAZY T
```
---
```
SORDID
O U
LEEWAY
E
L
YESTERDAY
A
```
Invalid boards:
```
MOLAR
A
RATS
CR
HC
H
```
---
```
RASCAL
A
BAKING
B OO
ISLAND
T
```
---
```
JOYFUL
OFFER
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 9 bytes
-3 bytes thanks to Jonathan Allan
A dyadic function taking a list of lines on the left and a list of words on the right.
```
Z;⁸KḲḊƇfƑ
```
[Try it online!](https://tio.run/##TZExcsMgEEX7nGI7Gt0g1VqsLMUYNIBGgzUq4yLjC6RMmsykyynSpEqlPjO@h30RhQUpDoXe18KH5fP0eDo9z/Ph/voy7S7T92V6P78dzx/zz@f19Wueh0HssQUQhTCAbRupqQcT6YFIRdYogcRY3A1Coi4bveXVAAg8knREsXyrmlxWeAjgs9UZKxsJy0kdrGZF1GPImgBu9X86kPNkJYa0axoIedu9UWhjGZelFr1jljb/1@XSY81MFouuRLV6eHKDu9z@hnvnuzdOoZYpBPgzPphQdSpfzVQVWTGO8yBQFCAwfzlAWGNimSIEsTWeEaNkcC6J6e6s4hskGO1rFhodJmN8DEaLPSVraxQxbZewBh9VnFAhK06a1S238Rc "Jelly – Try It Online")
```
Z;⁸ -- concatenate list of columns and list of rows
KḲ -- join on spaces and split on spaces to get list of words
Ƈ -- keep words that are truthy (non-empty)
Ḋ -- when the first character is removed
Ƒ -- is this resulting word list invariant when
f -- all words not in the dictionary are removed?
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~60~~ 57 bytes
```
->b,d{(b+b.transpose).all?{|c|d==d|c.join.scan(/\w\w+/)}}
```
[Try it online!](https://tio.run/##PZJbT8JAEIXf51fMk6UBy7tJNSNdBF27TVtCqvLQCwYMFEJVYqy/HXeGSx96Tqc7nTNfuvsqfg7v/uH6tuhVv52iW3ifu7xutptm7nr5anX325Zt5ftVW3ofm2XtNWVed/pv@7d9t@/@/R2@89Wy8l/BeaYIEQxSFEGopmggRaU0jChA5fQAnIDCwTh8QEAk5MuaRClbOleMNZpeMkylITFxMA5QPjvBY4tWakoZO4V4rl1cppJUxQFlcKoQOjADWNaSE33kpEZTDDIQYkoThEHMfjSQTCN7l/ExJQPScMp6T0@c9J5jGhgnmsLArojn048mG060LIVmOFSxDJaRDpHTQ8eSYTlhYGv5sDyYlMWSYmEAorIpO4tWxITpiE1ICUmj5cwS0VRJa2S0Yo0nIke44uwLnR0dM2V3YeXMoCN4uidMrjfPywVWG2yL1u5T2CUKb7Ws5423zredq5tysVlv3ctDvmtce26L76/2P5rBvK4O/w "Ruby – Try It Online")
Takes the board as a list of lists of characters. Returns `true` for valid boards, `false` otherwise.
The board is valid if for every word on the board, the union of that word with the dictionary is equal to the dictionary.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~138~~ \$\cdots\$ ~~86~~ 79 bytes
```
lambda b,d:all(i in d+[*s]for s in[*map(''.join,zip(*b))]+b for i in s.split())
```
[Try it online!](https://tio.run/##TVJhb9owEP2eX3HKF8fUq9Z2UqVKmeQSU9hCjJIgxNJ8ABLUrBQi7KpdEb@d5ewQEVl5zz4/vzv76n/6Zbe9O63959Nm8bYsFrBkxcNis/EqqLZQXGU9la93e1DNNOu9LWqPkOu/u2rLvqra6y0pza@WgDuMQF2relNpj9LTx25fKD8jnDAg3P4nE4SAR/1R9IRUiBDhSaYIQx4ghPzP3KAQM27YmBvhWEbpEEnEE26EkZghTPhMGOlEhgIxnhpIhGiNkiYQzi2Lg5HZPBdJKuKgscgdXSqtwAcvcxszAJeBK6FJGEnjAhJJCk3CSJpMQbg5g8xtqzEKAA74WW7dL9al5VgfpFZts4Gz4RQ6va2@nQiAi8jlpCvCnm0@NLPHj2XIY4zw8/6Yp4kh/bhdGfbPGQ87XcyTPg87oQk/8t9tOY9YiylmlIQ8CuzVQKf@JeeDadjeghwMROzm1Ck/63KlywJv@YaBHd/toM7qpVy9lnsMkuf32/sfK3wiZDd3hDrYYZqV2GPYeOa5GJyPpA8OuuMDrj3NTOtRs1Tvq6321uSgj/DtJxzUEQ6tVVb6vsqPhJ7@Aw "Python 3 – Try It Online")
*Saved a whopping ~~27~~ 33 bytes thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)!!!*
*Saved 7 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!!!*
*TIO testing now works thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) and [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)!!!*
Inputs the boards as a list of strings (space padded so they're all the same length) and the dictionary as a list of strings.
Returns `True` for a valid board or `False` otherwise.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 8 bytes
Basically the same as my Jelly answer, but Gaia has a superset builtin.
```
:t+ṡṡḥ⁇⊃
```
[Try it online!](https://tio.run/##FYwxCsIwGEZ3T5FBcFBw95t@zE9bSJPQRErcOoh09wLiUPEWgvYMuvYm9iIxgQcfHw/eueu7GHeX9e/7zHze83WYH7e4WWE7jafptZzGebjHmqwQMIKsheZWGHjBrFCSFLwgUCIpSXpf6QJZFcZnDUXHAMXcUkDKoDbal9DkSOUULLUsYY1iNAeGY84Fl74KaRpZSQR2nhtJ4Q8 "Gaia – Try It Online")
```
:t+ṡṡḥ⁇⊃ -- function that expects a 2d-list character above the dictionary as a list of strings
:t -- duplicate the grid on the stack and transpose the copy
+ -- append transpose to original grid
ṡ -- join list by spaces
ṡ -- split resulting string on spaces
ḥ⁇ -- keep words that are truthy when the first character is removed
⊃ -- is the dictionary a superset of this word list
```
`⊃` only considers unique item and a list is a superset of itself (`⊇` might've been a more accurate symbol).
Almost all operators in Gaia are overloaded for different types, which is why `ṡ` can both split and join.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Dø«ðý#ʒ¦Ā}åP
```
First input is the board as a list of string lines; second is a list of words.
Uses the legacy version of 05AB1E, because it can zip/transpose lists of strings, where in the new version zip/transpose can only be done on character-matrices.
[Try it online.](https://tio.run/##JY0xDsIwDEV3ThGFlQEGDmARq60UkigJqkrVAaQeA4kzcAdYWBhZWBomLhXsZnn/2/r2X29P582Ys0rv6Zle6bP83abH93pJd5dzL/fghJAraQU4R2qwFZY0CkRNWoMSKIdFL4EmmDEHFZhdYypyJVjZWOJEDceOBbEFNlTCtCbWXAEBdKkiOmiRb5zVSOIPzIBYfgfa6m42XjWc6zBE9Ir@Dn8)
**Explanation:**
```
D # Duplicate the first (implicit) input-list
ø # Zip/transpose; swapping rows/columns
« # Merge the two lists together
ðý # Join the strings with space delimiter
# # Then split the entire string by spaces
ʒ # Filter this list of strings:
¦ # Remove the first character
Ā # And check if it's non-empty
} # After the filter: we have a list of the words
å # Check for each word if it's in the second (implicit) input-list
P # Check if this is truthy for all of them
# (after which the result is output implicitly)
```
I came up with it independently, but I noticed it's basically a port of [*@ovs*' Jelly answer](https://codegolf.stackexchange.com/a/236410/52210), with just larger builtins / stack management. (For convenient I also copied their test case to my TIO.)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
cUy)¸¸fÅe!øV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y1V5Kbi4ZsVlIfhW&input=WyJNQVAgICIsIk8gQVBQIiwiTkVXIE8iLCJUIEVFTCIsIkhBRCBFIl0KWyJBIiwiQUEiLCJBUFAiLCJEQU5DSU5HIiwiRUVMIiwiR09UIiwiSEFEIiwiTEFaWSIsIkxFRVdBWSIsIk1BUCIsIk1PTlRIIiwiTkFTQUwiLCJORVciLCJQQVdFRCIsIlBPTEUiLCJSVUUiLCJTRUVJTkciLCJTT0xFTFkiLCJTT1JESUQiLCJZRVNURVJEQVkiXQ)
[Answer]
# [Kotlin](https://kotlinlang.org/), ~~159~~ 129 bytes
```
{d,b->(b+b[0].indices.map{c->b.indices.joinToString(""){"${b[it][c]}"}}).all{r->r.split(" ").filter{it.length>1}.all{w->w in d}}}
```
-30 bytes thanks to using lambda and type inference (Parlor Trick)
[Try it online!](https://tio.run/##jVTfb9owEH7vX3GyeEi0EG2v04hkwBS2QFAShBjiIeRH6y1NUGLWalH@dmY7NBRirfWD73y@8/fdne3fOUtpdkqOGTwFNANNh@oO@PgTpPCcF1EJA0hpyZxEQxgZgHAzL5dCjPFiNFvcC5UQW4h7xxdiisdC2PjnRkpC1lhqcywD587CnwplgT0sAxdkLcQSrwkPlRwUAy0dmwg/dyWFR8gZ3@Mb9qbR3PFMwm@I5xN3zJH1NikWl@xNUi3Q7VqicbZ8vmaDHJDZXxs5fXBujT7IqlwbeWmAIN34P/K5sh1wANwoHftrKZT@TtcuegP@u0SaaoKqDCtQUmmardggYp6qIlrtZuPSwA59OURu72Ywd2zs3h6AVXAu9r2OceQqPKcjVQ@mH6HjYm@EbSWfzolD/EPR06FoaKejM8/Gi3H3CsJHSH13NpOVrbhVzmRC3PPzuTyi@OUQhyyOLu@IFcfYgGZOgrRUi8sJyVfN5pHfPFbQ7MEy4O1K71vDPE/jIBucqsjY9y1t/2m//bwzaRbRMC7Np@BQhX1r3xp@5TTz8yZeQ0ivUK/abynbbcNdjepaN4M0rYq@VZjlIaVMQ7woZkJTFhcVZWYaZw/s0fpSS7/nvvUM/DuM6ro@Ccpa8238pYc2dx6dFyQIH6ECbZ8HRWSIPR36VltEkWkQsiMXA0g0@aEaIJ311unAObM00zhjmoD26j9oTkPLoCzjCEHM6wdoEtCUr2rg4NCTJ3FA6DVR50bVd/XpHw)
**Explanation:**
First, merge the original and transposed board. In each row, find all words longer than 1 letter and for all of them, check their presence in the dictionary.
]
|
[Question]
[
Related: [Zeroes at the end of a factorial](https://codegolf.stackexchange.com/questions/79762/zeroes-at-the-end-of-a-factorial)
Today, we are going to calculate how many zeroes are there at the end of \$n!\$ (the factorial of \$n\$) in base \$m\$.
Or in other words: For given integers \$n\$, and, \$m\$. Calculate the integer \$p\$ which is the highest power of \$m\$ dividing \$n!\$: \$p \in \mathbb{N}\_0\$ which holds \$ \left( m^p \mid n! \right) \land \left( m^{p+1} \nmid n! \right) \$. Here, \$n!\$ is the factorial of \$n\$ which equals to the product of all positive integers less than or equal to \$n\$. The value of \$0!\$ is \$1\$.
## Input / Output
* Two integers \$n\$, \$m\$.
* One integer: How many zeroes at end of \$n!\$ in base \$m\$.
## Rules
* As [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest codes in bytes win.
* Your program is required to support \$0\le n\le 1{,}000{,}000\$; \$2\le m\le 1{,}000\$ at least. The program should be able to output correct results for any inputs in above range with reasonable resource (typically, <1 minutes on a normal laptop).
* As this question is only talking about integers. No floating point errors may allowed in your output. You may, however, output 3.0 when 3 is required. But 2.9999999999999996 is certainly not allowed.
## Testcases
```
n, m -> output
0, 2 -> 0
1, 2 -> 0
2, 2 -> 1
3, 2 -> 1
4, 2 -> 3
9, 6 -> 4
10, 100 -> 1
80, 100 -> 9
4, 8 -> 1
15, 12 -> 5
16, 12 -> 6
39, 45 -> 8
100, 2 -> 97
100, 3 -> 48
100, 4 -> 48
100, 5 -> 24
100, 6 -> 48
100, 7 -> 16
100, 8 -> 32
100, 9 -> 24
100, 10 -> 24
100, 13 -> 7
100, 36 -> 24
100, 42 -> 16
100, 97 -> 1
100, 100 -> 12
1000000, 2 -> 999993
1000000, 3 -> 499993
1000000, 4 -> 499996
1000000, 6 -> 499993
1000000, 7 -> 166664
1000000, 8 -> 333331
1000000, 9 -> 249996
1000000, 999 -> 27776
1000000, 1000 -> 83332
```
Above \$n\$ is written in base 10. You are allowed to receive \$n\$ as an array of integers in base \$m\$ if you want.
## Related OEIS
It is interesting that this question involve at least 14 sequences on OEIS. Maybe you can find out some helpful formula to solve this problem on it.
OEIS includes sequences for every \$2 \le m \le 16\$:
* 2: [A011371](https://oeis.org/A011371)
* 3, 6: [A054861](https://oeis.org/A054861)
* 4: [A090616](https://oeis.org/A090616)
* 5, 10, 15: [A027868](https://oeis.org/A027868)
* 7, 14: [A054896](https://oeis.org/A054896)
* 8: [A090617](https://oeis.org/A090617)
* 9: [A090618](https://oeis.org/A090618)
* 11: [A064458](https://oeis.org/A064458)
* 12: [A090619](https://oeis.org/A090619)
* 13: [A090620](https://oeis.org/A090620)
* 16: [A090621](https://oeis.org/A090621)
Also, by treating above sequences as a matrix, there are other related sequences:
* [A090622](https://oeis.org/A090622): Square array read by antidiagonals of highest power of k dividing n! (with n,k>1).
* [A098094](https://oeis.org/A098094): T(n,k) = greatest e such that k^e divides n!, 2<=k<=n (triangle read by rows).
* [A011776](https://oeis.org/A011776): a(1) = 1; for n > 1, a(n) is defined by the property that n^a(n) divides n! but n^(a(n)+1) does not.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes
```
#!~IntegerExponent~#2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X1mxzjOvJDU9tci1oiA/LzWvpE7ZSO1/QFFmXomCQ3q0oQEY6BjH/v8PAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Æfµ⁹ọ€S:ċⱮ`Ṃ
```
A dyadic Link accepting the base, \$m\$, on the left and the factorial-input, \$n\$, on the right that yields the number of trailing zeros of \$n!\_{m}\$ as an integer.
**[Try it online!](https://tio.run/##ASkA1v9qZWxsef//w4ZmwrXigbnhu43igqxTOsSL4rGuYOG5gv///zM2/zEwMA "Jelly – Try It Online")**
### How?
```
Æfµ⁹ọ€S:ċⱮ`Ṃ - Link: integer, m; integer, n e.g. 72 100
Æf - prime factorisation (m) [ 2, 2, 2, 3, 3]
µ - start a new monadic chain - f(x=that)
⁹ € - for each i in [1..n]:
ọ - (i) order (vectorised across x)
[[0,0,0,0,0],[1,1,1,0,0],[0,0,0,1,1],[2,2,2,0,0],...]
S - sum (vectorises) [97,97,97,48,48]
` - use x as both arguments of:
Ɱ - map across (x) with:
ċ - count occurrences [ 3, 3, 3, 2, 2]
: - integer divide [32,32,32,24,24]
Ṃ - minimum 24
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~133~~ 130 bytes
Saved **3 bytes** thanks to kops!
```
n,m=input()
f=()
i=2
k=lambda n,p:n and n/p+k(n/p,p)
exec"while m%i<1:m/=i;f+=i,\ni+=1\n"*m
print min(k(n,p)/f.count(p)for p in f)
```
[Try it online!](https://tio.run/##DctBCoMwEADAe16xCIWkhqYKvdjuT7xYTXDRbBaJtH19msvcRn55TdyXwjYisZxZGxWwQtirDfcpvpcJ2MrAMPEC7KTddNWKUf7r5@az0u4hXujVDdEhPUOLZEemFruRm2tUchBniMS6zvpcuM3p5KzFhHSAADEEU4p@2O5u/g "Python 2 – Try It Online")
Creates a list of all the prime factors of `m`. The program then computes the highest power of each prime factor that divides `n!` using the `lambda` function `k`. This number is divided by the number of times the prime factor is found in `f`. Finally, the program prints out the `min` of these values.
A math.stackexchange.com question with answers explaining how this works:
<https://math.stackexchange.com/questions/391067/power-of-a-number-in-a-factorial>
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes
```
NθNηW¬⁼ηΠυ⊞υ§Φ…·²η¬﹪÷η∨Πυ¹κ⁰I⌊Eυ÷↨E↨θι↨…↨θιμι¹№υι
```
[Try it online!](https://tio.run/##VU5NTwMhEL33V3AcEkxarz3pqske2m78B8gSmchCF5it/nocuFTfYb7fe2OcTiZqX@sYrlTOtHzYBKs87v72jvubQ28FnGOB15W0z@CUmFKcyRQgyRATZQekxFMZw2y/4Q19YfYYjKeMm33X4dPCoxJOKtGETsz2kQ/KC2442yZ5SXBXVeIgOXzJFveS35gShgKDzszGgAstcNLX5npXedbZ9mkvViWQ2b0efoy3g4v/V4tsuZspMURiA@qTjmOth33HruX6sPlf "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `n` and `m`.
```
W¬⁼ηΠυ⊞υ§Φ…·²η¬﹪÷η∨Πυ¹κ⁰
```
Find `m`'s prime factors.
```
Eυ Map over prime factors
↨θι Convert `n` to base `p`
E …↨θιμ All prefixes
↨ ι Converted from base `p`
↨ ¹ Take the sum
÷ Integer divided by
№υι Frequency of prime factor
⌊ Take the minimum
I Cast to string
Implicitly print
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ÆFZọ€Ḣ}S:ʋ@ẎṂ
```
[Try it online!](https://tio.run/##y0rNyan8//9wm1vUw929j5rWPNyxqDbY6lS3w8NdfQ93Nv0/vNxBHygc@f9/tIGOglGsjkK0IZQ2gtLGUNoEJg9UaGhgAGJaIJhAWQuwrBlQCKLPUkfBxBSiA242iGUMZ5nAWQh1ZnCWOZxlAWdZwlmGBggmwkRjhHYThI2W5kjaYPpAAOE1E4tYAA "Jelly – Try It Online")
After the `4, 48` fix it's too slow to run all of the test cases in one go, but I think it can still [handle them all individually](https://tio.run/##y0rNyan8//9wm1vUw929j5rWPNyxqDbY6lS3w8NdfQ93Nv0/vNxBHygc@f9/tIGOglGsjkK0IZQ2gtLGUNoEJg9UaGhgAGJaIJhAWQuwrBlQCKLPUkfBxBSiA242iGUMZ5nAWQh1ZnCWOZxlAWdZwlmGBggmwkRjhHYThI2W5kjaYPpAAOE1E4tYAA).
I'm not sure why `ɓ` (or `ð` for that matter) refuses to work here.
Takes \$m\$ on the left and \$n\$ on the right.
```
ÆF Factor m into [prime, exponent] pairs.
Z Zip.
ʋ@ With [[primes], [exponents]] as the right argument:
€ For each integer in [1 .. n],
ọ how many times is it divisible by
Ḣ} each prime? (the list of which is popped from the pair)
S Sum the divisibilities,
: and floor-divide the sums by the exponents.
Ẏ Dump inner lists (not entirely sure why they're singletons),
Ṃ and return the minimum.
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~242~~ 237 bytes
* Saved five bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
f(n,b){int*p=malloc(12*b),d=2,k,l;for(;b/d;++d){for(k=b;k%d<1;k/=d)p[d]++;for(k=2;p[d]&&k<d;p[d]*=d%k++>0);}for(k=0;n/++k;)for(d=2;k/d&&b/d;++d)for(l=k;p[d]&&l%d<1;l/=d)++p[b-~d];for(n=d=0;b/++d;k&&n<1|k/p[d]<n?n=k/p[d]:0)k=p[b-~d];d=n;}
```
[Try it online!](https://tio.run/##dZDPbsIwDMbve4pqE6Uh3kjS0NKFbC/BYRLjQBuYUEpA026MvTpzKH9Kxnyo@vtsf45dPX5U1X6/SByUZLt0X72NXs3qel0lXPRKAkYLsFCrxfozUWXfKEoN2XqyulS2Y0Zc2b42ZDMxU0pVkxHKYxzbkTn89bTpWEpfGFG7poIp16fUKuIRh6CJiePTAC/W2h5d6sOU2k@hdDMpH3/M9DDIaYNGJRoZZePYjfi37fuekXt1uvl9ZsTqU5PRTu32D2a@WLp5NPZbQ0U2n7j4IrnvVJHTHROV@Hl399BcRevqtfvUfe6@dcGzusPqaDVbuoRE27sIY5wwEMDIEXgbBAI/QdoGiZCeoIAM5NmAAWfsUjlsuLh0Di9JPgAuYHDGzGN2nliAHMDw4uxfWuRtTkFe5WXAAxCyzVmQz4FnbR5CKtpcBP24XSCkcP2gLCiQIhhR5K392fFa7aE@/KI@0lDHhW/qstGzUM/@qfeLY8hQxwP44KHuD3HLHzUQeZ7/SfCDG1rharv9Lw "C (gcc) – Try It Online")
---
# Annotated version
```
f(n,b){
int*p=malloc(12*b) /* Since `b>=2` holds,
`12*b>=8*b+8==2*4*(b+1)==2*(b+1)*sizeof(int)`.
The pointer `p` represents two sparse arrays of
length `b+1` only indexed by primes, the first
storing the base's prime factorization.
Its latter half's `b+1` elements stores how many of
`k`'s (where `1<=k<=n`) prime factors with
multiplicities. */
,d=2,k,l;
for(;b/d;++d{ // first half of `p`
for(k=b;k%d<1;
k/=d)
p[d]++;
for(k=2;p[d]
&&k<d;
p[d]*=d%k++>0)
;
}
for(k=0;n/++k;) // all factors of $n!$
for(d=2;k/d
&&b/d;++d) // all divisors $d | k$
for(l=k;p[d] // which are prime factors of $b$
&&l%d<1;l/=d)
++p[b-~d];
for(n=d=0;b/++d; /* calculate the minimum of $n!$'s factors
weighted according to $b$'s factor's
multiplicity */
k&&n<1|k/p[d]<n
?n=k/p[d]:0)
k=p[b-~d];
d=n;} // return
```
[Try it online!](https://tio.run/##jVTJktowEL3zFcpkAC/KGBuzjdHMOedwSNVkqrxIxiob2WWZEGbJr5OWzeoMqehA8Vr9XvfrFkRfllG028WawKH@2kFcVEZBVkGW5ZFmO0aoI8tA37iIGPLDB@L4KMkzKnEHXT@@Ij6QqRGaU0IcwzW00LR19bX@Ykj@wvJYg2K6f3dNaZEwVOSQw0rkFz4qWVEyyUQlUbXJkSyCUjIUlGWwlSiPr8lkTCyrBJo3bR/lItuCR8p@MYrCLSpKvmISowpqxbyU1TUVWeUlF8s6MQwk68uGi@IgUlcvQcVzcdXLV2g6CyplJQmyGNhNPyxjq9qR0mcSZrtBq0Bs/@HHT32ga5uElbASe07SORG@ftGORBteJdcUVuus4kXGI15xJu@QYXUQpsTBKc68DorzUvNCi3qmSV8bhmU106mbh97UPkBdZaYk9NIundvARKlFqK7KFk/02TS9Y47jqQjAXi@dUxVX2CC0m5rmw6DmQPS9s88feMIyzdTT99XhPR6tQflb8el2rw19e6lFa@l90/rB6J5I@U8uFfOWojeUKmZNzUhat3XI3SQ8SuBBsdYsVcGwZvV6WW01O/hEplk8hV9@02fvoCoIhfZDaJ966rcTBVm0ht2z@u2suOCr9epgAja5r3JtWRvGl0kFrzWIoryk9RvMVT9Hal/@x6K39ZZhQ72emNtvqaWMz4UKPQrSwPtmDyglJ0@UCO/9UhUmVbJqXYrdZ8piLhhaqH8PHOkwNlHF2k03QoJ04QcGHz/EDW7@XQiJHvt3/fv@9z5W2OtANrx2LjQdvdaVF9oAO3jfxkKzz4EDwD6A4TlwAQwPYIbH2D0KDLA9GJwypw2enZjT06U9wraDR0c4VnB8rDjD7ghPT8qq09nkHA@xe3HvtvAIO@45HrfuJ9gen@MpHjrneNbig7tWYIgvGxq3ElynVWI2OfM/2E/rvKg6yqg6w3YcDH8Yd5v4uB0fX8lXxuG47TgMQB27HVeD@EgfYtiZTCZ/Xdi1GkiBtffdHw "C (gcc) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) -MList::Util, 131 bytes
131 bytes without newlines, indentation and comments.
```
sub f{
%d=(); #init counting hash to empty
sub e{$M%$_ or$d{$_}++,$M/=$_,redo for@_} #sub that counts given factors of $M
e 2..($M=pop); #count factors of M
(%c,%d)=%d; #store and reset counts
for$M(2..pop){e keys%c} #count active factors of N! (N=pop)
~~min map$d{$_}/$c{$_},keys%d #how many of last counts in first
}
```
[Try it online!](https://tio.run/##fZRNb5tAEIbv/hVbskhgNubTYEw29aW3okqWeqorlBpsoZgFAZViIfLTQ/fDCmBQ5wDL8868sztaUSTlZd1lV7CrcfZS/NIPsaaff6NzmRRf9AcdVcUlrfUD0dHTkyQFC0DDQOxpgcdnYHBg3gOrByYH9j1wemALD@ZqGkafshkQf1C06VPMNSMmt1kL4vbEFa19Rpw1I5tbq8EJfG/EbMaccZ4zw7id5YyYO5Pn8c26I8YPYFsj5k/9TGOG8f2Ntmy70zTHmrb1vcHcjOG0P3fCYjAZFvZEExOa15xPzZ1o7n/qblOi4Uw0MS0W5kS7TW2mH0Vc8zzvTmILfheoo7VYnPJS2dVqw5OyqwIJghmCyVuh4h2M@I1/AJA887oXEgOSvNXBLR3Ac17jk6hSBS3KlNRCwMznq5S/Mg6krbRcLr/t9z/20jBVYtpK0TSYqiv6QTAk1BzDDADmwqwAoE7c7kBocdtVf/@AUyPHWFEDtk4aGMowAnkJ4wZGraYhGOoYRqhM4hzQY@6iNgHWaqXAEBd5oQaKfERyrGI5DqgMQ4WKTGgS8JpcK/nYvr9nKQH0xyA8dXhkL8TVuO26j7yo05xU3WP4Pa3q7fZnnV4wrfkH "Perl 5 – Try It Online")
```
print f(100, 13); # prints 7
print f(1000000, 999); # prints 27776
```
[Answer]
# MATLAB, 107 bytes
```
function F(n,m)
for i=1:max(n,m),f{i}=factor(i);end
c=f{m};fix(min(sum([f{1:n}]'==c)./sum(c==c')))
end
```
First get all factors from 1 to the maximum of n or m. This guarantees that all factors of 1-n are captured as well as the factors of m. Then, divide the sum of the appearance of each factor by the duplicity of that factor to determine the minimum amount of pairs of the factors of m appear in n!, which is the maximum power that m can be raised to to divide n!.
For example: F(80,100)
1. f -> all factors from 1-100 in a 1x100 cell array, where f{i}=factor(i)
2. c -> [2 2 5 5]
3. sum([f{1:n}]'==c) -> [78 78 19 19], there are 78 2s in all of f and 19 5s in all of f.
4. sum(c==c') -> [2 2 2 2], there are two of each factor
5. (3)/(4) -> [39 39 9.5 9.5]. element-wise division shows that at a minimum, 9 whole sets of factors of m are contained in n!'s factors, therefore n! is divisible by at most m^9
6. fix(min(3.3)) -> 9, which is the correct answer
[Answer]
# [Python 3](https://docs.python.org/3/) + [SymPy](https://www.sympy.org/en/index.html), 118 bytes
```
lambda n,m:min(g(n,f)//p for f,p in factorint(m).items())
g=lambda n,p:n and n//p+g(n//p,p)
from sympy.ntheory import*
```
[Try it online!](https://tio.run/##hZLLcoMgFIb3PgVLaZ1EBFEz45t0Y5uQOBOQMWx8esslSYlzQs9CGb7/3NGLuUyKrqL/Wq@D/D4OSBXyIEeVn3NVCLzfaySmGYlCo1EhMfyYaR6VySXejeYkbznG2bl/@uqDQoM6ImUdP20I@ys0zsQ8SXRbpF52ylxO07ygUeppNh@r9uFEjryVhftWGPU9KnH2CkkKVhEkW0hTkEWQbmHnIfeQbSBx1ZKyBMO2MezgnC3oSWoHSSio3kIeQb6B1FfLag/bV2hLifrsGpjS0OgbX5akIW3FYMqTvk2YBIdpmBOtYNql8pIySUO/8DAoT7myKlVy10CrDfD5YqJ@7J2zeEPOKKy4bymhYH8KDiv4vzEeO7HGYMV9L84IrHjs5l0d9j4omqaBBO4QXrPNUeH1Fw "Python 3 – Try It Online")
---
This is my reference implementation which generate all testcases:
```
from sympy.ntheory import factorint
def f(n, m):
factor_count = lambda n, p: n // p + factor_count(n // p, p) if n else 0
return min(factor_count(n, factor) // power for factor, power in factorint(m).items())
```
]
|
[Question]
[
Given an integer from 1 to 999 inclusive, output a truthy value if it appears horizontally, vertically, or diagonally, either forwards or backwards, anywhere in the 3x3 square of digits 1-9 on a standard [number pad](https://en.m.wikipedia.org/wiki/Numeric_keypad):
```
789
456
123
```
If the number does not appear, output a falsy value.
The exact 65 numbers you need to output truthy for are:
```
1
2
3
4
5
6
7
8
9
12
14
15
21
23
24
25
26
32
35
36
41
42
45
47
48
51
52
53
54
56
57
58
59
62
63
65
68
69
74
75
78
84
85
86
87
89
95
96
98
123
147
159
258
321
357
369
456
654
741
753
789
852
951
963
987
```
Everything else is falsy.
The shortest code in bytes wins.
[Answer]
## JavaScript (ES6), ~~83~~ ... ~~74~~ 73 bytes
Takes input as a string.
```
n=>1/([a,b,c]=[...n].map(v=>--v+v/3|0))||45242>>(a^b)&(~c&&n<99|b*2==a+c)
```
*Saved 3 bytes thanks to ETHproductions*
### How it works
We transform the number pad by applying an offset to each digit according to the row it belongs to:
* +1 for the top row
* 0 for the middle row
* -1 for the bottom row.
All codes below are represented in hexadecimal.
```
7 8 9 8 9 A (+1)
4 5 6 => 4 5 6 (unchanged)
1 2 3 0 1 2 (-1)
```
Let's consider all XOR combinations of these new key codes. Contiguous keys are highlighted with brackets.
```
XOR| 0 1 2 4 5 6 8 9 A
---+------------------------------------
0 | 0 [1] 2 [4] [5] 6 8 9 A
1 | [1] 0 [3] [5] [4] [7] 9 8 B
2 | 2 [3] 0 6 [7] [4] A B 8
4 | [4] [5] 6 0 [1] 2 [C] [D] E
5 | [5] [4] [7] [1] 0 [3] [D] [C] [F]
6 | 6 [7] [4] 2 [3] 0 E [F] [C]
8 | 8 9 A [C] [D] E 0 [1] 2
9 | 9 8 B [D] [C] [F] [1] 0 [3]
A | A B 8 E [F] [C] 2 [3] 0
```
We can see that two keys are contiguous if and only if XORing their codes leads to one of the following values:
```
1, 3, 4, 5, 7, C, D, F
```
This list can be packed into the following binary mask:
```
FEDCBA9876543210
----------------
0b1011000010111010 = 0xB0BA = 45242
```
Hence the test to determine if two key codes (a, b) correspond to two contiguous keys:
```
45242 >> (a ^ b) & 1
```
For three key codes (a, b, c), we need this additional test:
```
b * 2 == a + c
```
Example:
```
a = 0xA
b = 0x6
c = 0x2
0xB0BA >> (0xA ^ 0x6) & 1 == 0xB0BA >> 0xC & 1 == 1
=> 0xA and 0x6 are contiguous key codes
0x6 * 2 == 0xA + 0x2
=> 0xA, 0x6 and 0x2 are contiguous key codes on the same row, column or diagonal
```
### Demo
This snippet outputs the list of truthy values.
```
let f =
n=>1/([a,b,c]=[...n].map(v=>--v+v/3|0))||45242>>(a^b)&(~c&&n<99|b*2==a+c)
console.log([...Array(1000).keys()].filter(n=>n && f(n+'')).join(' '))
```
[Answer]
# Python3, 72 bytes
```
lambda n,s="123 456 789 741 852 963 42 753 86 26 159 84 ":n in s+s[::-1]
```
Input is taken as a string.
Golfing suggestions welcome! :D
[Answer]
# Befunge, ~~169~~ ~~161~~ 159 bytes
```
38*:2+"*0>DTV{51"3*\3*"kV"3*\3*"{w"3*\3*"mr"v
v:\&+*83:++66:+"c":+"?":+"$":++66:+"W":*6\*4<
_v#:\_v#*-+%+55g00*+55g02\*-g02\*-g00\`9::::p02/+55p00%"d":
0<@.!!<
```
[Try it online!](http://befunge.tryitonline.net/#code=MzgqOjIrIiowPkRUVns1MSIzKlwzKiJrViIzKlwzKiJ7dyIzKlwzKiJtciJ2CnY6XCYrKjgzOisrNjY6KyJjIjorIj8iOisiJCI6Kys2NjorIlciOio2XCo0PApfdiM6XF92IyotKyUrNTVnMDAqKzU1ZzAyXCotZzAyXCotZzAwXGA5Ojo6OnAwMi8rNTVwMDAlImQiOgowPEAuISE8&input=MTIz)
The first two lines are just pushing the list of test numbers onto the stack. This is done in order of size, since it can sometimes be easier to generate a number as an offset from the previous one in the series rather than generating it from scratch. Once we get to the larger numbers, we can also sometimes save a byte by generating them in pairs, e.g. `"kV"3*\3*` gives us 258 and 321 in nine bytes, where individually they would take five bytes each.
The main loop is on line three, executing right to left with wrap around. This just iterates through all the test numbers on the stack, comparing the value itself, value%100, and value/10. If any of those match the input number or the number <= 9 then we output 1 and exit. If there is no match, we continue looping. If we run out of test numbers on the stack then we output 0 and exit.
Thanks to [Mistah Figgins](/users/62574/mistah-figgins) for saving me a couple of bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ ~~24~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*Saved 5 bytes thanks to @Dennis's suggestion of `K` and `Ɠ`.*
```
9s3µUŒD;;Z;ŒDµ;UKƓẇ
```
[Try it online!](http://jelly.tryitonline.net/#code=OXMzwrVVxZJEOztaO8WSRMK1O1VLxpPhuoc&input=MTIz)
### Explanation
```
9Rs3µUŒD;;Z;ŒDµ;UKƓẇ Main link. Argument: number
9s3 Split [1..9] into [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
µ New monadic chain
U Reverse the rows
ŒD Take the diagonals of the result
; Append the original rows
;Z Append the original columns
;ŒD Append the original diagonals
µ New monadic chain
;U Append the reverse of everything
K Join by spaces
Ɠẇ Check if a line from STDIN is in the result
```
[Answer]
# Ruby, 77 bytes
```
->n{!!((s='123 456 789 147 258 369 753 951 86 62 24 48 ')+s.reverse)["#{n}"]}
```
[Answer]
# bash, 75
```
printf %s\\n 123 456 789 741 852 963 42 753 86 26 159 84|tee >(rev)|grep $1
```
outputs something and returns 0 for all the values in that list
prints nothing and returns 1 in all other cases
[Answer]
# Java, 397 bytes
```
public class Numpad {public static void main(String[] args){Scanner input=new Scanner(System.in);int in=input.nextInt();int h=in/100;int u=in%10;int t=(in%100)/10;boolean out=false;input.close();if(in<10)out=true;else if( h==0){int decider=Math.abs(t-u);if((decider==1)||(decider==3)||(decider==4))out=true;}else{if ( Math.abs(h-t) == Math.abs(t-u))out=true;}System.out.println("RESULT : "+out);}}
```
]
|
[Question]
[
Suppose a codegolf challenge doesn't count whitespace in the length of your program. Cheat this system by encoding your script into whitespace, and golf a script which decodes and executes embedded whitespace.
**Example**
My solution to [JBernardo](https://codegolf.stackexchange.com/users/2212/jbernardo)'s [Meta Golf Challenge](https://codegolf.stackexchange.com/q/3203/2180) was to encode Sage (or Python) code into whitespace, and golf the decoder.
```
s = ' '
for c in '<lots of whitespace>'.split(s):
s+=chr(len(c))
exec s
```
The encoding is to take a script, prepend a newline, and for each character `c` in the script, output `ord(c)` tabs followed by a space. Prepending a newline is necessary since I'm using Python and I start the script `s` with a space.
**Scoring**
A complete solution contains a description of the encoding you use (if it's complicated, provide a script), and a 'decode-and-execute' script. Your score is the number of non-whitespace characters in the decode-and-execute script.
**Whitespace (the language) is forbidden**
Moreover, any language which has a complete set of operators which only use whitespace characters is not allowed: I'll accept the lowest nonzero score.
[Answer]
## CPAN, 16
```
use Acme::Bleach;
```
CPAN has it all. Or at least, [just the right module.](https://metacpan.org/module/Acme%3a%3aBleach)
[Answer]
## Golfscript, 12 chars
String delimited by `'` goes before these 10 chars:
```
n/{,}%''+~
```
Each line is decoded into one character, whose ASCII (probably Unicode, in fact) value is the length of the line.
Unfortunately if I try pasting my Hello World example, Markdown removes the extra spaces, even in a `<pre>` block.
[Answer]
## Perl, 29
```
$_="";s/ */chr length $&/ge;eval
```
Inside that `s///` are a tab then a space. The encoding is an ultra-basic encode with spaces, precede with tabs.
Try this one on the command line:
```
$ tr ST ' \t' <<< '$_="TSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"; s/TS*/chr length $&/ge; eval' | perl
```
~~Edit: well, lol, I can't find a proper way to copy-paste the tab/space mix. Believe me, it works at home :)~~
Update: there, there, encoded with `tr`
[Answer]
## JavaScript
Replace `\t` with a tab to get the posted character count.
### Standard (64 characters)
```
eval(eval("'<code here>'".replace(/\t */g,function(s){return"\\"+s.length})))
```
### [Arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/arrow_functions) (49 characters)
```
eval(eval("'<code here>'".replace(/\t */g,(s)=>"\\"+s.length)))
```
### Encoder program for both
```
for(var i = 0, si = prompt("Enter the code."), so = ""; i < si.length; ++i) so += '\t' + Array(+si.charCodeAt(i).toString(8)).join(' '); prompt("Here is the result.", so);
```
[Answer]
## Yabasic (88 characters)
```
a$ = "<code here>"
for a = 1 to len(a$)
if mid$(a$, a) < " " then b = b + 1
else b$ = b$ + chr$(b) : b = 0
endif
next
compile(b$)
a()
```
Use the same encoder program as for my C solution, but do not remove the first character. Your original code must be in the form of a subroutine `a()`, for example:
```
sub a():?"hello, world":end sub
```
[Answer]
## C (99 characters)
```
main(c, p)
{
char *s = "<code here>";
for (p = popen("cc -xc -oa -", "w"); *s;)
*s++ - 9 ? c -= putc(c, p) : ++c;
execl("a", pclose(p));
}
```
Tested only with (and perhaps only works with) GCC.
Corresponding encoder program (manually remove the first character from its output):
```
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF) {
while (c--) putchar(9);
putchar(32);
}
return 0;
}
```
[Answer]
## D (101 chars)
```
import std.algorithm;mixin((){char[]r;foreach(c;splitter("<lots of whitspace>"," "))r~=cast(char)c.length;return r;}());
```
same encoding as in the question (no need for the newline)
[Answer]
## Bash (builtins only, 44 characters)
```
IFS=
eval `while read a
do printf '\'${#a}
done<<a
<code here>
a`
```
Corresponding encoder script:
```
od -b | cut -b9- | tr ' ' '\n' | while read a
do
for (( b = 0; b < $((10#$a)); ++b ))
do
echo -n ' '
done
echo
done
```
[Answer]
# K5, 12 bytes
```
.`c$-':&9=" "
```
Execute (`.`) the string formed from the ascii values (``c$`) given by the difference between each pair (`-':`) of the indices where (`&`) the input is a tab (`9=" "`).
Input is a string of tab- and non-tab characters, and the character values are encoded in the number of non-tabs (spaces or newlines) between each tab. An example encoder:
```
" ",/{(x#" "),"\t"}'-1+
```
Perform a running join beginning with a space over (`" ",/`) x spaces (`x#" "`) joined with a tab (`,"\t"`) where X is each of (`{...}'`) one minus the character values of the input string (`-1+`).
In action:
```
enc: " ",/{(x#" "),"\t"}'-1+
dec: .`c$-':&9=
enc "2+3"
" \t \t \t"
dec enc "2+3"
5
```
[Answer]
# Ruby, 43
Very straightforward, encoding is putting x spaces per line, where x is the ascii value of the char, decoding is reverse.
The following script is just a unary to ASCII converter and works even when things other than spaces are free:
```
eval("".split("\n").map{|x|x.length.chr}.join)
```
Just replace the empty string with the program that pleases you.
The thing in a more reusable format:
```
from_space = lambda {|text| text.split("\n").map{|x| x.length.chr}.join}
to_space = lambda {|text| text.chars.map{|x| " " * x.ord}.join("\n")}
p from_space [ to_space [ "abc" ] ] #=> "abc"
```
]
|
[Question]
[
I've recently stumbled upon a Russian site called [acmp.ru](https://acmp.ru/), in which one of the tasks, [HOK](https://acmp.ru/index.asp?main=task&id_task=14), asks us to find the LCM of two positive integers. The full statement, translated to English is as follows:
>
> The only line of the input contains two natural numbers A and B separated by a space, not exceeding 46340.
>
> In the only line of the output, you need to output one integer - the LCM of the numbers A and B.
>
>
>
On the [Python leaderboard](https://acmp.ru/index.asp?main=bstatus&id_t=14&lang=PY), the top solution is just 50 bytes, followed by a stream of 52s.
[](https://i.stack.imgur.com/pc5y4.jpg)
Note that the scoring method for this site is *not* standard, and uses the following formula:
>
> max(code length without spaces, tabs and newlines, full code length divided by 4)
>
>
>
With this in mind, I have come up with two solutions that give a score of 52. One of them simply uses `math.lcm`, while the other one calculates it more directly:
```
from math import*
print(lcm(*map(int,input().split())))
```
```
a,b=map(int,input().split())
v=a
while v%b:v+=a
print(v)
```
Now I'm stumped. How can I save 2 bytes off my solution? (the Python version is 3.9.5).
[Answer]
***My solution to 50 bytes:***
```
v=1
for x in input().split()*6**6:v+=-v%int(x)
print(v)
```
### Explanation
The solution itself is relatively simple, but finding it was significantly more difficult.
First, note that the LCM of `a` and `b` is the smallest number `v` such that `v%a==0` and `v%b==0`.
The main logic for this algorithm is in `v+=-v%int(x)`. In a nutshell, it sets `v` to the first multiple of `x` greater than or equal to `v`. This means that if `v%x==0`, `v` doesn't change.
In a `for` loop, we repeat this process cyclically with both numbers. Whenever `v` is not divisible by `x`, `v+=-v%x` ensures that `v` becomes the immediate next divisor of `x`. This means that, at some point in the loop, `v` will equal the LCM. When it does, `v` will stop changing, since both numbers will be divisible by `v`.
To better illustrate the algorithm, here is an example on the input `36 27`:
```
v=1
(36): v+=-v%36; v=36
(27): v+=-v%27; v=54
(36): v+=-v%36; v=72
(27): v+=-v%27; v=81
(36): v+=-v%36; v=108
(27): v+=-v%27; v=108
(36): v+=-v%36; v=108
...
```
It remains to determine how many iterations are required. In the worst case, `A` and `B` are coprime, for which the LCM is `A*B`. For this, we would need exactly `min(A,B)` iterations. The statement tells us that both numbers are guaranteed to be at most `46340`. We could simply use this number, but `6**6` is one shorter, and only does `316` extra operations.
]
|
[Question]
[
You teach a class of students with interesting preferences for how their chairs are arranged. There are 3 very specific requirements they have for how the chairs are arranged:
1. They most be arranged in a rectangle, even if it means some chairs go empty.
2. There must be as few empty chairs as possible.
3. They must be as "squarey" as possible. Squarey-ness is determined by the distance between the width and the height of the rectangle, lower is better. For example, a rectangle that is `4x7` has a squarey-ness of 3.
To be more specific, the "score" of an arrangement is the distance between the width and height plus the number of chairs that would go empty.
Let's take an example. Let's say you have 13 students. You could arrange the chairs any of these ways:
```
1x13
2x7
3x5
4x4
```
`1x13` is not very squarey. In fact, 1 and 13 are 12 apart, so we give this arrangement 12 points. It also has 0 empty chairs, so we add 0 points, giving this arrangement a score of 12. Not that great.
`2x7` is certainly better. 2 and 7 are only 5 apart, so we give this arrangement 5 points. However, if you actually arranged 2 rows of seven chairs, that would take 14 chairs, meaning one chair would be empty. So we add one point, giving this arrangement a score of 6.
We could also do `3x5`. 3 and 5 are 2 apart, so +2 points. It takes 15 chairs, meaning we'd have two extra chairs, so another +2 points, for a score of 4.
Last option, `4x4`. 4 and 4 are 0 apart, so we give this +0 points. 4x4 takes 16 chairs, so 3 chairs go empty, for a total score of 3. This is the optimal solution.
In case of a tie, the optimal solution is the one with less empty chairs.
# The challenge
You must write a program or function that takes an integer and outputs the optimal arrangement of chairs for that number of students. IO can be in any reasonable format. Here is sample output for any number of students from 1 to 100:
```
1: (1, 1)
2: (1, 2)
3: (2, 2)
4: (2, 2)
5: (2, 3)
6: (2, 3)
7: (3, 3)
8: (3, 3)
9: (3, 3)
10: (2, 5)
11: (3, 4)
12: (3, 4)
13: (4, 4)
14: (4, 4)
15: (4, 4)
16: (4, 4)
17: (3, 6)
18: (3, 6)
19: (4, 5)
20: (4, 5)
21: (3, 7)
22: (5, 5)
23: (5, 5)
24: (5, 5)
25: (5, 5)
26: (4, 7)
27: (4, 7)
28: (4, 7)
29: (5, 6)
30: (5, 6)
31: (4, 8)
32: (4, 8)
33: (6, 6)
34: (6, 6)
35: (6, 6)
36: (6, 6)
37: (5, 8)
38: (5, 8)
39: (5, 8)
40: (5, 8)
41: (6, 7)
42: (6, 7)
43: (5, 9)
44: (5, 9)
45: (5, 9)
46: (7, 7)
47: (7, 7)
48: (7, 7)
49: (7, 7)
50: (5, 10)
51: (6, 9)
52: (6, 9)
53: (6, 9)
54: (6, 9)
55: (7, 8)
56: (7, 8)
57: (6, 10)
58: (6, 10)
59: (6, 10)
60: (6, 10)
61: (8, 8)
62: (8, 8)
63: (8, 8)
64: (8, 8)
65: (6, 11)
66: (6, 11)
67: (7, 10)
68: (7, 10)
69: (7, 10)
70: (7, 10)
71: (8, 9)
72: (8, 9)
73: (7, 11)
74: (7, 11)
75: (7, 11)
76: (7, 11)
77: (7, 11)
78: (9, 9)
79: (9, 9)
80: (9, 9)
81: (9, 9)
82: (7, 12)
83: (7, 12)
84: (7, 12)
85: (8, 11)
86: (8, 11)
87: (8, 11)
88: (8, 11)
89: (9, 10)
90: (9, 10)
91: (7, 13)
92: (8, 12)
93: (8, 12)
94: (8, 12)
95: (8, 12)
96: (8, 12)
97: (10, 10)
98: (10, 10)
99: (10, 10)
100: (10, 10)
```
As usual, this is code-golf, so standard loopholes apply, and the winner is the shortest answer in bytes.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~16~~ ~~15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
÷RĊ,Rµạ/+PỤḢịZ
```
[Try it online!](http://jelly.tryitonline.net/#code=w7dSxIosUsK14bqhLytQ4buk4bii4buLWg&input=&args=MTM) or [verify all test cases](http://jelly.tryitonline.net/#code=w7dSxIosUsK14bqhLytQ4buk4bii4buLWgrCs8OH4oKsOyJAUkc&input=).
### How it works
```
÷RĊ,Rµạ/+PỤḢịZ Main link. Argument: n
R Range; yield [1, ..., n].
÷ Divide n by each k in [1, ..., n].
Ċ Ceil; round the quotients up to the nearest integer.
R Range; yield [1, ..., n].
, Pair; yield A := [[ ⌈n ÷ 1⌉, ..., ⌈n ÷ n⌉ ], [ 1, ..., n ]].
µ Begin a new, monadic chain. Argument: A
ạ/ Reduce A by absolute difference.
This yields [ |⌈n ÷ 1⌉ - 1|, ..., |⌈n ÷ n⌉ - n| ].
P Product; reduce A by multiplication.
This yields [ ⌈n ÷ 1⌉ × 1, ..., ⌈n ÷ n⌉ × n].
+ Add the results to left and right, element by element. This yields
[ |⌈n ÷ 1⌉ - 1| + ⌈n ÷ 1⌉ × 1, ..., |⌈n ÷ n⌉ - n| + ⌈n ÷ n⌉ × n ].
Ụ Grade up; sort the indices of the list of sums by their values.
Ḣ Head; extract the first value, which corresponds to the smallest
sum. Grading up is stable, so this selects the first index of all
with the smallest sum in case of a tie. In this event, the first
index will have the highest absolute difference of all indices
with the smallest sum, meaning that it has the lowest product and,
therefore, the lowest number of empty chairs.
Z Zip; transpose A's rows and columns.
This yields [[ ⌈n ÷ 1⌉, 1 ], ..., [ ⌈n ÷ n⌉, n ]].
ị Retrieve the pair at that index.
```
[Answer]
# Python 2, 68 bytes
```
lambda n:min((abs(~i-n/~i)+n/~i*~i,i+1,0-n/~i)for i in range(n))[1:]
```
Equivalent to the more “obvious”:
```
lambda n:min([(i+1,0-n/~i)for i in range(n)],key=lambda(p,q):abs(p-q)+p*q)
```
[Answer]
## Haskell, 65 bytes
```
f x=snd$minimum[((a*b+a-b,a*b),(b,a))|a<-[1..x],b<-[1..a],a*b>=x]
```
Usage example: `map f [1..5]` -> `[(1,1),(1,2),(2,2),(2,2),(2,3)]`.
Goes through an outer loop `a` from `1` to `x` (x -> number of students) and an inner loop `b` from `1` to `a`. Keeps all `(b,a)` where `a*b>=x` and builds pairs of `((arrangement points,seats left), (b,a))` which follow the lexicographical order we need to find the minimum. Note: `a` is always greater than `b`, so we don't need `abs` for squareyness. No need to subtract `x` from the "seats left" score, because only the relative order matters. Finally we remove the score pair with `snd`.
[Answer]
## Javascript, 98 bytes
My first code golf, so I post anyway!
```
f=n=>{for(o=1/0,i=1;i<=n;i++)for(j=n;i*j>=n;j--)t=i*j-n+Math.abs(i-j),o>t&&(o=t,a=[i,j]);return a}
```
Initially my `o` was an empty object and I checked if `o.a` was empty, so it was a special case at the first round. But I found the 1/0 trick in edc65's answer to initialize the variable to Infinity.
[Answer]
# Ruby, 64 bytes
```
->n{(1..n).map{|w|h=(n+w-1)/w;[(h-w).abs+h*w,w*h,w,h]}.min[2,3]}
```
A lambada that takes the number of people as an argument and returns an array with width and height of the optimal solution.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 18 bytes
```
:Gy/Xkvtd|yp+&X<Z)
```
[**Try it online!**](http://matl.tryitonline.net/#code=Okd5L1hrdnRkfHlwKyZYPFop&input=Mjc)
### Explanation
```
: % Implicit input number N. Range [1 2 ... N]
G % Push N again
y % Duplicate second-from-top: push [1 2 ... N] again
/Xk % Divide and round up
v % Vertically concatenate. Gives 2×N array of rectangle sizes
td| % Duplicate. Absolute difference of each column
y % Duplicate second-from-top: push 2×N array again
p % Product of each column
+ % Sum absolute differences and products
&X< % Arg min
Z) % Use as column index into the 2×N array. Implicitly display
```
[Answer]
# Pyth, ~~24~~ ~~22~~ 21 bytes
**Edit**: in the sorting key, I realize that there is no need to find the number of empty chairs. It is equivalent to score the total number of chairs. This saved me 2 bytes.
```
h.m_+B*FbaFbm,d.EcQdS
```
[Try it online!](http://pyth.herokuapp.com/?code=h.m_%2BB%2aFbaFbm%2Cd.EcQdS&input=13&debug=0)
[Answer]
# Matlab~~(174)(146)~~121
```
function g(n),f=@(n,i)ceil(n/i);x=[];for i=1:n,x=[sortrows(x); f(n,i)*i-1/(f(n,i)*i)+abs(f(n,i)-i) i f(n,i)];end,x(1,2:3)
```
* **trick 1:** i added the amount `1-1/length*width` as tie-scoring
* **trick 2:** i calculated `number_students/length` ceiled for the width of rectangle, ~~upper bound is the square but ceiled too~~
* I'm sure it can be golfed further ...
[try it](http://ideone.com/3CQ9CG)
---
**Edit :** referenced to @StewieGriffin 's remarks .
**Edit 2 :**
* `1` and `n` are constants no need to add 'em to the overall score.
* A function is few bytes less than stdin standalone program.
* I used ascendent sorting technique it saves too much bytes though.
**Edit 3:** peformance test.
[Answer]
# Python 2, 64 bytes
```
lambda n:max((~-i*~min(i,n/i),0-n/i,-i)for i in range(-n,0))[1:]
```
This is an amalgamation of [@Lynn's Python answer](https://codegolf.stackexchange.com/a/80125) (from where I took the `max(...)[1:]` trick) and the algorithm from [my Julia answer](https://codegolf.stackexchange.com/a/80167) (which allows a slightly shorter implementation).
Test it on [Ideone](http://ideone.com/vfGkXd).
[Answer]
# Julia, ~~61~~ ~~59~~ ~~55~~ ~~53~~ 52 bytes
```
/ =cld
n->[m=indmax([~i*~-max(i,n/i)for i=1:n]),n/m]
```
[Try it online!](http://julia.tryitonline.net/#code=LyA9Y2xkCgpmID0gbi0-W209aW5kbWF4KFt-aSp-LW1heChpLG4vaSlmb3IgaT0xOm5dKSxuL21dCgpmb3IgKG4sIChhLCBiKSkgaW4gKAogKDEsICAoMSwgMSkpLAogKDIsICAoMSwgMikpLAogKDMsICAoMiwgMikpLAogKDQsICAoMiwgMikpLAogKDUsICAoMiwgMykpLAogKDYsICAoMiwgMykpLAogKDcsICAoMywgMykpLAogKDgsICAoMywgMykpLAogKDksICAoMywgMykpLAogKDEwLCAoMiwgNSkpLAogKDExLCAoMywgNCkpLAogKDEyLCAoMywgNCkpLAogKDEzLCAoNCwgNCkpLAogKDE0LCAoNCwgNCkpLAogKDE1LCAoNCwgNCkpLAogKDE2LCAoNCwgNCkpLAogKDE3LCAoMywgNikpLAogKDE4LCAoMywgNikpLAogKDE5LCAoNCwgNSkpLAogKDIwLCAoNCwgNSkpLAogKDIxLCAoMywgNykpLAogKDIyLCAoNSwgNSkpLAogKDIzLCAoNSwgNSkpLAogKDI0LCAoNSwgNSkpLAogKDI1LCAoNSwgNSkpLAogKDI2LCAoNCwgNykpLAogKDI3LCAoNCwgNykpLAogKDI4LCAoNCwgNykpLAogKDI5LCAoNSwgNikpLAogKDMwLCAoNSwgNikpLAogKDMxLCAoNCwgOCkpLAogKDMyLCAoNCwgOCkpLAogKDMzLCAoNiwgNikpLAogKDM0LCAoNiwgNikpLAogKDM1LCAoNiwgNikpLAogKDM2LCAoNiwgNikpLAogKDM3LCAoNSwgOCkpLAogKDM4LCAoNSwgOCkpLAogKDM5LCAoNSwgOCkpLAogKDQwLCAoNSwgOCkpLAogKDQxLCAoNiwgNykpLAogKDQyLCAoNiwgNykpLAogKDQzLCAoNSwgOSkpLAogKDQ0LCAoNSwgOSkpLAogKDQ1LCAoNSwgOSkpLAogKDQ2LCAoNywgNykpLAogKDQ3LCAoNywgNykpLAogKDQ4LCAoNywgNykpLAogKDQ5LCAoNywgNykpLAogKDUwLCAoNSwgMTApKSwKICg1MSwgKDYsIDkpKSwKICg1MiwgKDYsIDkpKSwKICg1MywgKDYsIDkpKSwKICg1NCwgKDYsIDkpKSwKICg1NSwgKDcsIDgpKSwKICg1NiwgKDcsIDgpKSwKICg1NywgKDYsIDEwKSksCiAoNTgsICg2LCAxMCkpLAogKDU5LCAoNiwgMTApKSwKICg2MCwgKDYsIDEwKSksCiAoNjEsICg4LCA4KSksCiAoNjIsICg4LCA4KSksCiAoNjMsICg4LCA4KSksCiAoNjQsICg4LCA4KSksCiAoNjUsICg2LCAxMSkpLAogKDY2LCAoNiwgMTEpKSwKICg2NywgKDcsIDEwKSksCiAoNjgsICg3LCAxMCkpLAogKDY5LCAoNywgMTApKSwKICg3MCwgKDcsIDEwKSksCiAoNzEsICg4LCA5KSksCiAoNzIsICg4LCA5KSksCiAoNzMsICg3LCAxMSkpLAogKDc0LCAoNywgMTEpKSwKICg3NSwgKDcsIDExKSksCiAoNzYsICg3LCAxMSkpLAogKDc3LCAoNywgMTEpKSwKICg3OCwgKDksIDkpKSwKICg3OSwgKDksIDkpKSwKICg4MCwgKDksIDkpKSwKICg4MSwgKDksIDkpKSwKICg4MiwgKDcsIDEyKSksCiAoODMsICg3LCAxMikpLAogKDg0LCAoNywgMTIpKSwKICg4NSwgKDgsIDExKSksCiAoODYsICg4LCAxMSkpLAogKDg3LCAoOCwgMTEpKSwKICg4OCwgKDgsIDExKSksCiAoODksICg5LCAxMCkpLAogKDkwLCAoOSwgMTApKSwKICg5MSwgKDcsIDEzKSksCiAoOTIsICg4LCAxMikpLAogKDkzLCAoOCwgMTIpKSwKICg5NCwgKDgsIDEyKSksCiAoOTUsICg4LCAxMikpLAogKDk2LCAoOCwgMTIpKSwKICg5NywgKDEwLCAxMCkpLAogKDk4LCAoMTAsIDEwKSksCiAoOTksICgxMCwgMTApKSwKICgxMDAsICgxMCwgMTApKQopCiAgICBwcmludGxuKGYobikgPT0gW2EsYl0pCmVuZA&input=)
### How it works
The code is equivalent to the following, ungolfed version, where `cld` is ceiling division.
```
function chairs(n)
m = indmin([(i + 1) * (max(i, cld(n, i)) - 1) for i in 1:n])
return [m, cld(n, m)]
end
```
To find the optimal arrangement, it is clearly sufficient to examine the pairs **[i, j]**, where **1 ≤ i ≤ n** and **j = ⌈n / i⌉**.
The score for such an arrangement is **|j - i| + (ij - n)**, where the second summand is the number of empty chairs. Instead of the actual scores, we can compare scores augmented by a constant, such as **ij + |j - i| + 1**.
It is sufficient to consider pairs **[i, j]** where **i ≤ j** since the arrangements **[i, j]** and **[j, i]** are equally valid. We deal with strictly descending pairs by setting **j = max(⌈n / i⌉, i)** instead, which makes sure that **j ≥ i** and will yield a suboptimal score if **⌈n / i⌉ < i**.
Since **j - i ≥ 0**, we have **ij + |j - i| + 1 = ij + j - i + 1 = (i + 1) × (j - 1)**, which can be computed in fewer bytes of code.
Finally `indmin` / `indmax` gives the index **m** (and thus the value of **i**) of the optimal arrangement, which is **m** by **⌈n / m⌉**. Ties are broken by first occurrence, which corresponds to the lowest value of **i**, therefore the highest value of **j - i** and thus the lowest value of **ij - n** (empty chairs).
[Answer]
# JavaScript (ES6) 74 ~~78~~
*Edit* keeping the temp result as an array instead of 2 vars, borrowed from Thiht's answer
```
n=>(z=>{for(x=0;y=-~(~-n/++x),x<=y;)(s=y-x+x*y-n)>=z||(z=s,r=[x,y])})()||r
```
*Less golfed*
```
n=>{
z = 1/0
for (x=0; y=(n-1)/++x+1|0, x <= y; )
{
s = y-x+x*y-n;
if (s<z)
z=s, r=[x,y]
}
return r
}
```
**Test**
```
f=n=>(z=>{for(x=0;y=-~(~-n/++x),x<=y;)(s=y-x+x*y-n)>=z||(z=s,r=[x,y])})()||r
out=x=>O.textContent+=x+'\n'
for(i=1;i<=100;i++)out(i+' :( '+f(i)+' )')
```
```
<pre id=O></pre>
```
[Answer]
## PHP, 129 bytes
```
function f($i){$s=INF;for($x=1;$x<$i;$x++){if($s>$t=(abs($x-$e=ceil($i/$x))-$i+($e*$x))){$s=$t;$d[0]=$x;$d[1]=$e;}}var_dump($d);}
```
Ungolfed:
```
function f ($i){
$s=INF;
for($x=1; $x<$i; $x++){ // for every number less than the input
if( $s > $t=( abs($x-$e=ceil($i/$x))-$i+($e*$x) ) ){
// determine the other dimension, the score, and compare to the minimum score
$s=$t;
$d[0]=$x;
$d[1]=$e;
}
}
var_dump($d);
}
```
[Answer]
# PHP, 104 bytes
The algorithm that solves this problem is simple and it is probably used by other answers in languages similar to PHP (JavaScript, f.e.):
* start with a large value for the initial score; `n` is large enough (where `n` is the input value); the score of the arrangement computed on the first iteration (`1, n`) is `(n-1)+0`;
* iterate for all values of width between `1` and `n`; compute the minimum height as `ceil(n/width)`, compute the arrangement score using the formula provided in the question (i.e. `abs(width - height) + (width * height - n)`); if the score is better than the previous best score then remember the width, the height and the new best score; on ties use the value of `width * height - n` for current arrangement and previous best arrangement to detect the new best arrangement;
* that's all.
After golfing, this algorithm produces something like this (wrapped here for readability):
```
for($s=$h=$j=$n=$argv[$w=$i=1];$i<=$j;$j=ceil($n/++$i)
{$c=$j-$i+$i*$j-$n;if($c<$s||$c==$s&&$i*$j<$w*$h){$w=$i;$h=$j;$s=$c;}}
echo"$w,$h";
```
It uses **137 bytes** (when put on a single line) and it is far from the 104 bytes advertised in the title. The code can probably be shortened by another 2-3 bytes but the big source of improvement is somewhere else: in the details of the algorithm.
## The revised algorithm:
There are several places where the algorithm can be improved by removing useless code.
* there is no need to iterate the width from `1` to `$n`; for speed, the width (`$i`) must iterate between `1` and `floor(sqrt($n))` but this makes the code even longer instead of shortening it; but if the width doesn't exceed `sqrt($n)`, the minimum height (`$j`) will always be larger than `sqrt($n)` (their product must be at least `$n`);
* the previous statement allows using `$i <= $j` (width <= height) as the termination condition for loop; this way, the width will iterate from `1` to `floor(sqrt($n))` and the height will get values starting with `$n` and going down to `ceil(sqrt($n))` (not necessarily all of them);
* knowing that width is always smaller than or equal to the height allow us know that `abs(width - height)` is always `height - width` (`$j-$i`); 5 bytes saved this way;
* the input value `$n` is used in the computation of score (the number of unoccupied seats is `width * height - n`) but it is not needed; the score does not need to be displayed, it is computed only for comparison of the arrangements; by removing `- n` from the score formula we save another 3 bytes (the PHP code is `-$n`) without losing anything;
* given the last two statements, the score formula becomes `height - width + width * height` (`$j-$i+$i*$j`);
* on ties (the score of the current arrangement is the same as the previous best score), the rules say to use the arrangement with less free seats; because width always increases and height always decreases, the `height - width` part of the score decreases on each step;
* if the current score is equal with the previous best score, the previous statements tells us that the number of free seats of the current arrangement is larger than the one of the previous best arrangement; this means the previous best arrangement win the tie;
* because the ties are always won by the previous best arrangement, a new arrangement becomes the new best arrangement only when its score is smaller than the previous best; the code that checks for ties is useless and can be removed (`||$c==$s&&$i*$j<$w*$h` -- a lot of bytes);
* because of the removal of `-$n` from the score's formula, the score for the first arrangement (`1x$n`) is `$n-1+1*$n` (i.e. `2*$n-1`); the initial value of the best score (`$s`) can be any value greater than or equal to `2*$n`; the first iteration has a better score and it becomes the best arrangement letting the algorithm run without initialization problems.
The new code (**104 bytes**), after applying the improvements described above is:
```
for($s=2*$j=$n=$argv[$i=1];$i<=$j;$j=ceil($n/++$i))
if($s>$c=$j-$i+$i*$j){$w=$i;$h=$j;$s=$c;}echo"$w,$h";
```
It is wrapped here for readability. Prepend the code above with the PHP marker `<?php` (technically, it is not part of the code), put it into a file (let's say `arrange-your-chairs.php`) and run it with an integer greater than zero as argument. It will display the width and height of the computed arrangement, separated by comma:
```
$ php arrange-your-chairs.php 1001
28,36
```
### Another solution (116 bytes)
Another solution that uses a different algorithm:
```
for($n=$argv[1];++$j<=$n;)for($i=0;++$i<=$j;)
if($n<=$k=$i*$j)$a["$i,$j"]=($j-$i+$k-$n)*$n+$k;asort($a);echo key($a);
```
It puts all the combinations of at least `$n` seats into an associative list; the key is the text representation of the arrangement, the value is the arrangement's score. It then sorts the list (ascending by value) and gets the key of the first entry.
### One more (115 bytes)
```
foreach(range(1,$m=$n=$argv[1])as$i)
if(($d=ceil($n/$i))<=$i&&$m>=$s=$i*$d-$n+$i-$d){$m=$s;$w=$d;$h=$i;}echo"$w,$h";
```
This is the PHP version of @Neil's [answer](https://codegolf.stackexchange.com/a/80117/40534) (JavaScript/ES6, 85 bytes).
There are some noticeable differences due to the features of each language:
* the JS answer generates an array of `n` (undefined) values then uses its keys to iterate from `0` to `n-1`; it increments `i` (`d=(n+i++)/i|0`) to make it iterate from `1` to `n`; the PHP solution doesn't need to increment; it uses [`range()`](http://php.net/manual/en/function.range.php) to generate an array then it uses the generated values (`1` to `n`) to iterate;
* the JS answer uses `(n+i)/i` then converts the value to integer using `|0` to get the smallest integer larger than `n/i`; the PHP answer solves this issue easily with the PHP function [`ceil()`](http://php.net/manual/en/function.ceil.php); JavaScript also provides `Math.ceil()` but it uses 5 bytes more than the solution found by Neil;
* PHP provides the function [`array_map()`](http://php.net/manual/en/function.array-map.php) that is somehow similar with JS `Array.map()` but it doesn't help here; its syntax is verbose, a `foreach` produces shorter code; it is larger than the JS code, though;
* merging the assignments into the conditions using `||` is not possible in PHP because it lacks the comma operator; I translated `a||b||c` into `if(!a&&!b)c` then, because `a` and `b` are comparisons, I negated their operators (replaced `<` with `>=`); this also produces larger code than the JS version;
* another 23 bytes have to be added just because the names of variables in PHP have to be prefixed by `$`.
The ungolfed versions of all solutions and the test suite can be found [on Github](https://github.com/axiac/code-golf/blob/master/how-should-you-arrange-your-chairs.php).
[Answer]
## JavaSCript (ES6), 83 bytes
```
n=>[...Array(m=n)].map((_,i)=>(d=(n+i++)/i|0)>i||(s=i*d-n+i-d)>m||(m=s,r=[d,i]))&&r
```
[Answer]
## Julia, 87
I think this is one step in direction towards finding a *magic function* for the problem:
```
f(i)=(i+n)÷(i+1)|>j->(j*i<n)+j
_=indmin([sqrt(n)<=i?i-f(i)*(1-i):2n for i=1:n])
_,f(_)
```
It only looks at pairs `(i, j=(i+n)/(i+1))` or `(i, j+1)`
[Answer]
# Oracle SQL 11.2, 173 bytes
```
SELECT MIN(x||','||y)KEEP(DENSE_RANK FIRST ORDER BY y-x+(y*x-:1))FROM(SELECT CEIL(LEVEL/:1)x,CEIL(MOD(LEVEL+.1,:1))y FROM DUAL CONNECT BY LEVEL<=:1*:1)WHERE x<=y AND:1<=x*y;
```
Un-golfed
```
SELECT MIN(x||','||y)KEEP(DENSE_RANK FIRST ORDER BY y-x+(y*x-:1)) -- Keeps the minimal score
FROM (SELECT CEIL(LEVEL/:1)x,CEIL(MOD(LEVEL+.1,:1))y FROM DUAL CONNECT BY LEVEL<=:1*:1) -- Generate x,y combinations
WHERE x<=y AND :1<=x*y -- Filters out wrong combinations
```
[Answer]
## Q 58 Bytes
```
{c@d?&/d:+/(-/;*/)@\:+c:{((b<a)?1b)#+(b:-_-x%a;a:1+!x)}x}
```
Lamba that calculates minimal cost for a given value (x) and returns a sequence of two values (width,height)
Adding name to that lambda requires other two char (ex f:{..} instead of {..})
**Test**
```
{..}'1+!100
```
where {..} is the lambda. Read as "applies lambda to each value of 1+first 100 ints" (in other words to each value 1..100)
Generates
```
1 1
2 1
2 2
2 2
3 2
3 2
3 3
3 3
3 3
5 2
4 3
4 3
4 4
4 4
4 4
4 4
6 3
6 3
5 4
5 4
7 3
5 5
..
```
**Explanation**
Nested lamdba `{((b<a)?1b)#+(b:-_-x%a;a:1+!x)}` generates all candidates (widht,height) pairs for x chairs as two sequences (w1 w2 w3 ..; h1 h2 h3 ..) (widths and heights). Read from left to right, but evaluates from right to left
`a:1+!x` generates values 1..x and assign that sequence to a
`-_-` is negate floor negate, and implements ceil (ceil is not a primitive of the language)
`b:-_-x%a` applies ceil to each value of x divided by any item im a, and assign the resulting sequence to b. In other words, b is ceil each x dividedBy each 1..x
`+(b;a)` return a secuence composed of seq a and seq b, an then flips it (the result is a sequence of pair where i-pair contains element i of a and element i of b)
`b<a` compares item by item of b and a, and generates a secuence of logical values (true=1b for each index where b[i]
`s?x` returns the first position of item x in sequence s. With `(b<a)?1b` We look for 1b (true value) in sequence resulting of compare b and a, and get first position where b
`n#s` takes n first n items from seq s. We want to discard duplicate pairs, so we stop when first item of a pair < second item (ex. consider 13,1 but not 1,13).
As a side effect, each pair of the resulting sequence are of decreasing distance between a and b (ex (13 1; 7 2; 5 3; 4 4)
The candidate pair generated by nested lambda are assigned to c. We then flip c (obtains b,a again) and applies two functions to that argument: `*/` multiplies over, and `-/` subtract over. The result of `(-/;*/)@\:+c` is the difference and product of each pair. `+/` is sum over, and calculares final cost. The cost of each patir is assigned to d
&/ is minimum over, so `&/`d is the minimum cost. With `d?&/d` we find the first occurrence of minimum cost in d, and with c@.. we retrieve the pair at that position. As each pair is of decreasing distante between a and n, the first minimum found has the maximum distante betwwen other minimum pairs, so we apply tie rule correctly
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.