text
stringlengths 180
608k
|
---|
[Question]
[
Your task is to write a function or program that takes two non-negative integers `i` and `k` (`i` ≤ `k`), and figure out how many zeroes you'd write if you wrote all whole numbers from `i` to `k` (inclusive) in your base of choice on a piece of paper. Output this integer, the number of zeroes, to stdout or similar.
`-30%` if you also accept a third argument `b`, the integer base to write down the numbers in. At least two bases must be handled to achieve this bonus.
* You may accept the input in any base you like, and you may change the base between test cases.
* You may accept the arguments `i`, `k` and optionally `b` in any order you like.
* Answers must handle at least one base that is not unary.
Test cases (in base 10):
```
i k -> output
10 10 -> 1
0 27 -> 3
100 200 -> 22
0 500 -> 92
```
This is code-golf; fewest bytes win.
[Answer]
## Jelly, 1 byte
```
¬
```
This uses base `k+2`, in which case there's a single 0 iff `i` is 0. It takes two arguments, but applies the logical NOT to only the first one.
If we don't want to cheat:
### 7 bytes - 30% = 4.9
*-1.1 points by @Dennis*
```
rb⁵$¬SS
```
This gets the bonus.
```
dyadic link:
r inclusive range
b⁵$ Convert all to base input.
¬ Vectorized logical NOT
S Sum up 0th digits, 1st digits, etc.
S Sum all values
```
[Answer]
# Python 2, 36 bytes
```
lambda a,b:`range(a,b+1)`.count('0')
```
Credit to **muddyfish** for the `` trick.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~3~~ 1 byte
Uses base `k+2` like the Jelly answer, Code:
```
_
```
Explanation:
```
_ # Logical NOT operator
```
**3 byte non-cheating version:**
Code:
```
Ÿ0¢
```
Explanation:
```
Ÿ # Inclusive range
0¢ # Count zeroes
```
---
The bonus gives me **3.5 bytes** due to a bug:
```
ŸB)0¢
```
Explanation:
```
Ÿ # Inclusive range
B # Convert to base input
) # Wrap into an array (which should not be needed)
0¢ # Count zeroes
```
Uses CP-1252 encoding.
[Answer]
# Japt, 3 bytes
```
+!U
```
Uses base `k+2`, as the Jelly answer. There is a zero iff `i==0`. [Test it online!](http://ethproductions.github.io/japt?v=master&code=KyFV&input=MCA1MDA=)
### Better version, ~~10~~ 8 bytes
```
UòV ¬è'0
```
This one uses base 10. [Test it online!](http://ethproductions.github.io/japt?v=master&code=VfJWIKzoJzA=&input=MCA1MDAgMTA=)
### Bonus version, ~~14~~ 12 bytes - 30% = 8.4
```
UòV msW ¬è'0
```
Sadly, with the golfing I did, the bonus is no longer worth it... [Test it online!](http://ethproductions.github.io/japt?v=master&code=VfJWIG1zVyCs6Ccw&input=MCA1MDAgMTA=)
### How it works
```
UòV msW ¬è'0 // Implicit: U = start int, V = end int, W = base
UòV // Create the inclusive range [U..V].
msW // Map each item by turning it into a base-W string.
¬ // Join into a string.
è'0 // Count the number of occurances of the string "0".
```
[Answer]
## ES6, ~~91~~ 86 - 30% = 60.2 bytes
```
(i,k,b=10)=>([...Array(k+1-i)].map((_,n)=>(i+n).toString(b))+'0').match(/0/g).length-1
```
Or save 3 (2.1) bytes if b doesn't need to default to 10.
Best non-bonus version I could do was 65 bytes:
```
(i,k)=>([...Array(k+1).keys()].slice(i)+'0').match(/0/g).length-1
```
Edit: Saved 5 bytes by using @edc65's zero-counting trick.
[Answer]
## Seriously, 10 bytes
```
'0,,u@xεjc
```
Explanation:
```
'0,,u@xεjc
'0,,u push "0", i, k+1
@x swap i and k+1, range(i, k+1)
εjc join on empty string and count 0s
```
[Try it online!](http://seriously.tryitonline.net/#code=JzAsLHVAeM61amM&input=MAoyNw)
With bonus: 11.9 bytes
```
'0,,u@x,╗`╜@¡`Mεjc
```
[Try it online!](http://seriously.tryitonline.net/#code=JzAsLHVAeCzilZdg4pWcQMKhYE3OtWpj&input=MAoyNwoy)
Explanation:
```
'0,,u@x,╗`╜@¡`MΣc
'0,,u@x push "0", range(i, k+1)
,╗ push b to register 0
` `M map:
╜@¡ push b, push string of a written in base b
Σc sum (concat for strings), count 0s
```
[Answer]
# CJam, ~~12~~ ~~10~~ 3 bytes
```
li!
```
This uses the shortcut @ThomasKwa does.
If this is not allowed, then here is a 10 byte answer.
```
q~),>s'0e=
```
Nice and short! Works like @Mego's Seriously answer.
Thanks @Dennis!
Had fun writing my first CJam answer!
[Try it here!](http://cjam.tryitonline.net/#code=cX4pLD5zJzBlPQ&input=MAoyNw)
[Answer]
# T-SQL, 394 Bytes (No bonus)
I figure *'why not*', right?
```
DECLARE @i INT, @k INT SET @i = 100 SET @k = 200 WITH g AS (SELECT @i AS n UNION ALL SELECT n+1 FROM g WHERE n+1<=@k ) SELECT LEN(n) AS c FROM (SELECT STUFF((SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(n, 1, ''), 2, ''), 3, ''), 4, ''), 5, ''), 6, ''), 7, ''), 8, ''), 9, ''), ' ', '') FROM g FOR XML PATH ('')) ,1,0,'') n ) a OPTION (maxrecursion 0)
```
And the friendly one:
```
-- CG!
DECLARE @i INT, @k INT
SET @i = 100
SET @k = 200
WITH g AS
(
SELECT @i AS n
UNION ALL
SELECT n+1 FROM g WHERE n+1<=@k
)
SELECT LEN(n) AS c FROM
(
SELECT
STUFF((SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(n, 1, ''), 2, ''), 3, ''), 4, ''), 5, ''), 6, ''), 7, ''), 8, ''), 9, ''), ' ', '')
FROM g FOR XML PATH ('')) ,1,0,'') n
) a
OPTION (maxrecursion 0)
```
[Answer]
# Ruby, 46 - 30% = 32.2 bytes
You could probably golf this more, but at least I get the 30% bonus!
```
->i,k,b{((i..k).map{|a|a.to_s b}*"").count ?0}
```
...or without the bonus (27 bytes.)
```
->i,k{([*i..k]*"").count ?0}
```
Tips are welcome, still learning this whole "Ruby" thing.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 26 bytes
```
,{,.e?}?:1frcS:0xlI,Sl-I=.
```
Takes input as a list `[i,k]`.
### Explanation
```
,{ }?:1f § Unify the output with a list of all inputs which verify the
§ predicate between brackets {...} with output set as the input
§ of the main predicate
,.e? § Unify the input with a number between i and k with the ouput
§ being the list [i,k]
rcS § Reverse the list and concatenate everything into a single
§ number (we reverse it to not lose the leading 0 if i = 0 when
§ we concatenate into a single number). Call this number S.
:0xlI § Remove all occurences of 0 from S, call I the length of this new
§ number with no zeros
,Sl-I=. § Output the length of S minus I.
```
[Answer]
# Julia, 48 bytes - 30% = 33.6
```
f(i,k,b)=sum(j->sum(c->c<49,[base(b,j)...]),i:k)
```
This is a function that accepts three integers and returns an integer. One of the arguments specifies the base, so this qualifies for the bonus.
Ungolfed:
```
function f(i, k, b)
# For each j in the inclusive range i to k, convert j to base
# b as a string, splat the string into a character array, and
# compare each character to the ASCII code 49 (i.e. '1'). The
# condition will only be true if the character is '0'. We sum
# these booleans to get the number of zeros in that number,
# then we sum over the set of sums to get the result.
sum(j -> sum(c -> c < 49, [base(b, j)...]), i:k)
end
```
Implementing the bonus yields a score just barely better than the not implementing it (34 bytes):
```
f(i,k)=sum(c->c<49,[join(i:k)...])
```
[Answer]
# Seriously, 2 bytes
This might be taking the Jelly answer trick to the limit, but here is a simple 2 byte Seriously answer.
```
,Y
```
[Try it online!](http://seriously.tryitonline.net/#code=LFk&input=MAoyNw)
[Answer]
# Pyth, 6.3 bytes, with bonus (9 bytes - 30%)
```
/sjRQ}EE0
```
Explanation:
```
jRQ - [conv_base(Q, d) for d in V]
}EE - inclusive_range(eval(input), eval(input))
s - sum(^, [])
/ 0 - ^.count(0)
```
[Try it here](http://pyth.herokuapp.com/?code=jRQ%7DEE&input=10%0A10%0A20&debug=0)
Or 7 bytes without the bonus:
```
/`}EE\0
```
Explanation:
```
}EE - inclusive_range(eval(input), eval(input))
` - repr(^)
/ \0 - ^.count("0")
```
[Try it here](http://pyth.herokuapp.com/?code=%2F%60%7DEE%5C0&input=0%0A27&debug=0)
[Or use a test suite](http://pyth.herokuapp.com/?code=%2F%60%7DEE%5C0&input=0%0A27&test_suite=1&test_suite_input=10%0A10%0A0%0A27%0A100%0A200%0A0%0A500&debug=0&input_size=2)
[Answer]
# PHP, 50 Bytes
supports decimal only
```
<?=substr_count(join(range($argv[1],$argv[2])),0);
```
## supports decimal and binary with Bonus 63
```
<?=substr_count(join(array_map([2=>decbin,10=>""][$argv[3]],range($argv[1],$argv[2]))),0);
```
## supports decimal,hexadecimal, octal and binary with Bonus 77.7
```
<?=substr_count(join(array_map([2=>decbin,8=>decoct,10=>"",16=>dechex][$argv[3]],range($argv[1],$argv[2]))),0);
```
## supports base 2 - 36 with Bonus 78.4
```
<?=substr_count(join(array_map(function($i){return base_convert($i,10,$_GET[2]);},range($_GET[0],$_GET[1]))),0);
```
[Answer]
# JavaScript (ES6), 50 (71 - 30%)
```
(n,k,b)=>eval("for(o=0;n<=k;++n)o+=n.toString(b)").match(/0/g).length-1
```
*No bonus, base k+2* is 10 bytes `(i,k)=>+!i`
*No bonus, unary* is 8 bytes `(i,k)=>0`
**TEST**
```
f=(n,k,b)=>eval("for(o=0;n<=k;++n)o+=n.toString(b)").match(/0/g).length-1
function go() {
var i=I.value.match(/\d+/g)
R.textContent = f(i[0],i[1],i[2])
}
go()
```
```
i,k,b:<input id=I value='0,500,10' oninput="go()">
<span id=R></span>
```
[Answer]
# Jolf, 7 bytes
Replace `♂` with `\x11`. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=WmwRc2pKMA)
```
Zl♂sjJ0
sjJ inclusive range between two numeric inputs
♂ chopped into single-length elements
Zl 0 and count the number of zeroes
implicitly printed
```
[Answer]
## Lua 74 bytes
```
z,c=io.read,""for a=z(),z()do c=c..a end o,b=string.gsub(c,"0","")print(b)
```
There's gotta be a more effective way to do this...
I thought I was really onto something here:
```
c,m,z=0,math,io.read for a=z(),1+z()do c=c+((m.floor(a/10))%10==0 and 1 or a%100==0 and 1 or a%10==0 and 1 or 0) end print(c)
```
But alas... It keeps getting longer and longer as I realize there's more and more zeroes I forgot about...
[Answer]
# APL, 22 bytes
```
{+/'0'⍷∊0⍕¨(⍺-1)↓⍳⍵}
```
This is a monadic function that accepts the range boundaries on the left and right and returns an integer.
Ungolfed:
```
(⍺-1)↓⍳⍵} ⍝ Construct the range ⍺..⍵ by dropping the first
⍝ ⍺-1 values in the range 1..⍵
∊0⍕¨ ⍝ Convert each number to a string
{+/'0'⍷ ⍝ Count the occurrences of '0' in the string
```
[Try it here](http://tryapl.org/?a=f%u2190%7B+/%270%27%u2377%u220A0%u2355%A8%28%u237A-1%29%u2193%u2373%u2375%7D%20%u22C4%20100%20f%20200&run)
[Answer]
## Haskell, 29 bytes
```
i#k=sum[1|'0'<-show=<<[i..k]]
```
I'm using [base 10](http://cowbirdsinlove.com/43).
Usage example: `100 # 200` -> `22`
How it works: turn each element in the list from `i` to `k` into it's string representation, concatenate into a single string, take a `1` for every char `'0'` and sum those `1`s.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 7 (10 bytes − 30% bonus)
```
2$:i:qYA~z
```
[**Try it online!**](http://matl.tryitonline.net/#code=MiQ6aTpxWUF-eg&input=MTAwCjIwMAoxMA)
This works in [release 11.0.2](https://github.com/lmendo/MATL/releases/tag/11.0.2), which is earlier than this challenge.
### Explanation
```
2$: % implicitly input two numbers and generate inclusive range
i:q % input base b and generate vector [0,1,...,b-1]
YA % convert range to base b using symbols 0,1,...,b-1. Gives 2D array
~ % logical negation. Zeros become 1, rest of symbols become 0
z % number of nonzero elements in array
```
[Answer]
# Matlab: 27 bytes
```
@(q,w)nnz(num2str(q:w)==48)
```
creates a vector from lower number to larger one, then converts all numbers to string and counts all the '0' symbols.
[Answer]
# Python 3, 52.
Tried to implement the bonus, but it doesn't seem to be worth it.
```
lambda a,b:''.join(map(str,range(a,b+1))).count('0')
```
With test cases:
```
assert f(10, 10) == 1
assert f(0, 27) == 3
assert f(100, 200) == 22
assert f(0, 500) == 92
```
[Answer]
# [Perl 6](http://perl6.org), 23 bytes
```
{+($^i..$^k).comb(/0/)}
```
1. creates a Range ( `$^i..$^k` )
2. joins the values with spaces implicitly ( `.comb` is a Str method )
3. creates a list of just the zeros ( `.comb(/0/)` )
4. returns the number of elems in that list ( `+` )
### Usage:
```
my &zero-count = {…}
for (10,10), (0,27), (100,200), (0,500), (0,100000) {
say zero-count |@_
}
```
```
1
3
22
92
38895
```
[Answer]
# Mathematica, 39 bytes, 27.3 with bonus
```
Count[#~Range~#2~IntegerDigits~#3,0,2]&
```
[Answer]
# [C#](https://msdn.microsoft.com/en-us/library/kx37x362.aspx) 112 Bytes
```
int z(int i,int k)=>String.Join("",Enumerable.Range(i,k-i+1)).Count(c=>c=='0')
```
1. Create a string with numbers from the first number up to the last number
2. Count the zero characters in the string
[Answer]
# PHP, 84 bytes \*.7=58.8 (bases 2 to 36)
```
for(;($v=$argv)[2]>$a=$v[1]++;)$n+=substr_count(base_convert($a,10,$v[3]),0);echo$n;
```
or
```
for(;($v=$argv)[2]>$v[1];)$n+=substr_count(base_convert($v[1]++,10,$v[3]),0);echo$n;
```
takes decimal input from command line arguments; run with `-r`.
[Answer]
## PowerShell, ~~56~~ ~~54~~ ~~51~~ ~~48~~ 42 bytes
```
param($i,$k)(-join($i..$k)-split0).count-1
```
Takes input, creates a range with `$i..$k` then `-join`s that together into a string, followed by a regex `-split` command that separates the string into an array by slicing at the `0`s. We encapsulate that with `().count-1` to measure how many zeros. That's left on the pipeline, and output is implicit.
*Saved 6 bytes thanks to @ConnorLSW*
[Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSqaOSramhm5WfmQfk6OkBebrFBTmZJQaaesn5pXkluob///83@G9qYAAA "PowerShell – TIO Nexus")
---
Base-handling in PowerShell is [limited](https://msdn.microsoft.com/en-us/library/system.convert(v=vs.110).aspx) and doesn't support arbitrary bases, so I'm not going for the bonus.
[Answer]
# Java 8, 102 bytes - 30% = 71.4
Why not.
```
(i,k,b)->{int j=0;for(;i<=k;i++)for(char c:Integer.toString(i,b).toCharArray())if(c==48)j++;return j;}
```
Without the bonus, 96 bytes (so the bonus actually improves my score!):
```
(i,k)->{int j=0;for(;i<=k;i++)for(char c:String.valueOf(i).toCharArray())if(c==48)j++;return j;}
```
This implements the following:
```
interface Function {
public int apply(int i, int k, int b);
}
```
[Answer]
## Clojure, ~~50~~ 49 bytes
```
#(count(re-seq #"0"(apply str(range %(inc %2)))))
```
Oh regex is shorter than filtering. Original:
```
#(count(filter #{\0}(apply str(range %(inc %2)))))
```
Very basic, uses the set of character `\0` to remove others and counts how many were found.
] |
[Question]
[
# Generate a Koch Snowflake
A Koch snowflake is a triangle that for each `n`, another equilateral point is added in the middle of each side: <http://en.wikipedia.org/wiki/Koch_snowflake#Properties>
We already had a [kolmogrov-complexity](/questions/tagged/kolmogrov-complexity "show questions tagged 'kolmogrov-complexity'") [Koch Snowflake challenge](https://codegolf.stackexchange.com/questions/985/koch-snowflake-codegolf) for `n=4`. The new challenge is to draw a Koch snowflake with any `n` between `1` and `10`.
# Rules
>
> The snowflakes may not be hardcoded in the program or in files - they must be generated by your program.
>
>
> Your program must support all sized `n` between 1 and 10.
>
>
> The number of sides must be input by the user through std-in.
>
>
> You must print a graphical representation of the snowflake to the screen.
>
>
>
Sample Koch Snowflakes with `n` equaling 1, 2, 3, and 4 (green lines for clarity only, do not reproduce them):

In the event of a tie-breaker, the program with the highest number of upvotes wins (pop-contest).
[Answer]
# MATLAB, ~~119~~ 115
In an unusual turn of events, I found that this program actually worked better as I golfed it. First, it became much faster due to vectorization. Now, it displays a helpful prompt `~n:~` reminding the user of which quantity to enter!
Newlines are not part of the program.
```
x=exp(i*pi/3);
o='~n:~';
P=x.^o;
for l=2:input(o);
P=[kron(P(1:end-1),~~o)+kron(diff(P)/3,[0 1 1+1/x 2]) 1];
end;
plot(P)
```
n = 9:

`o` is an arbitrary string which is equal to `[0 2 4 0]` modulo 6. eiπ/3 raised to these powers gives the vertices of an equilateral triangle in the complex plane. The first `kron` is used to make a copy of the list of points with each one duplicated 4 times. `~~o` is the convenient way to get a vector of 4 ones. Secondly `diff(P)` finds the vector between each pair of consecutive points. Multiples of this vector (0, 1/3, (1 + e-iπ/3)/3, and 2/3) are added to each of the old points.
[Answer]
## T-SQL: 686 (excluding formatting)
For SQL Server 2012+.
Even though this will never be a contender, I had to see if I could get it done in T-SQL.
Gone for the approach of starting with the three initial edges, then recursing through each edge and replacing them with 4 edges for each level. Finally unioning it all up into a single geometry for the level specified for @i
```
DECLARE @i INT=8,@ FLOAT=0,@l FLOAT=9;
WITH R AS(
SELECT sX,sY,eX,eY,@l l,B,1i
FROM(VALUES(@,@,@l,@,0),(@l,@,@l/2,SQRT(@l*@l-(@l/2)*(@l/2)),-120),(@l/2,SQRT(@l*@l-(@l/2)*(@l/2)),@,@,-240))a(sX,sY,eX,eY,B)
UNION ALL
SELECT a.sX,a.sY,a.eX,a.eY,l/3,a.B,i+1
FROM R
CROSS APPLY(VALUES(sX,sY,sX+(eX-sX)/3,sY+(eY-sY)/3,sX+((eX-sX)/3)*2,sY+((eY-sY)/3)*2))x(x1,y1,x2,y2,x3,y3)
CROSS APPLY(VALUES(x2+((l/3)*SIN(RADIANS(B-210.))),y2+((l/3)*COS(RADIANS(B-210.)))))n(x4,y4)
CROSS APPLY(VALUES(x1,y1,x2,y2,B),
(x3,y3,eX,eY,B),
(x2,y2,x4,y4,B+60),
(x4,y4,x3,y3,B-60)
)a(sX,sY,eX,eY,B)
WHERE @i>i)
SELECT Geometry::UnionAggregate(Geometry::Parse(CONCAT('LINESTRING(',sX,' ',sY,',',eX,' ',eY,')')))
FROM R
WHERE i=@i
```


[Answer]
# LOGO: 95
```
to w:c ifelse:c=1[fd 2 lt 60][w:c-1 w:c-1 lt 180 w:c-1 w:c-1]end
to k:c repeat 3[w:c rt 180]end
```
Defines function `k` with a single level parameter.
### Edit
In the this online editor <http://www.calormen.com/jslogo/> you can add `k readword` to use prompt for input, but for some reason this command does not support the standard abbreviation `rw`.
The 102 characters solution below works in USBLogo with standard input as specified in the question. However the code needed slight changes as UCBLogo has some weird parser. It requires `to` and `end` to be in separate lines and space before `:` is required but on the other hand `:` are optional.
```
to w c
ifelse c=1[fd 2 lt 60][w c-1 w c-1 lt 180 w c-1 w c-1]
end
to k c
repeat 3[w c rt 180]
end
k rw
```
[Answer]
# Mathematica - 177
```
r[x_, y_] := Sequence[x, RotationTransform[π/3, x]@y, y]
Graphics@Polygon@Nest[
ReplaceList[#, {___, x_, y_, ___} Sequence[x,r[2 x/3 + y/3, 2 y/3 + x/3], y]
] &, {{0, 0}, {.5, √3/2}, {1, 0}, {0, 0}}, Input[]]
```

Bonus clip of varying the angle of middle piece

[Answer]
# BBC BASIC, 179
**REV 1**
```
INPUTn
z=FNt(500,470,0,0,3^n/9)END
DEFFNt(x,y,i,j,a)
LINEx-36*a,y-21*a,x+36*a,y-a*21PLOT85,x,y+a*42IFa FORj=-1TO1FORi=-1TO1z=FNt(x+24*a*i,y+j*14*a*(i*i*3-2),i,j,-j*a/3)NEXTNEXT
=0
```
As before, but in black and white, in ungolfed (but streamlined) and golfed versions. Not a winner, despite the fact that doing it ths way avoids the need for a special treament for n=1.
```
INPUTn
REM call function and throw return value away to z
z=FNt(500,470,0,0,3^n/9)
END
REM x,y=centre of triangle. a=scale.
REM loop variables i,j are only passed in order to make them local, not global.
DEFFNt(x,y,i,j,a)
REM first draw a line at the bottom of the triangle. PLOT85 then draws a filled triangle,
REM using the specified point (top of the triangle) and the last two points visited (those used to draw the line.)
LINEx-36*a,y-21*a,x+36*a,y-21*a
PLOT85,x,y+42*a
REM if the absolute magnitude of a is sufficient to be truthy, recurse to the next level.
REM j determines if the triangle will be upright, inverted or (if j=0) infinitely small.
REM i loops through the three triangles of each orientation, from left to right.
IFa FORj=-1TO1 FORi=-1TO1:z=FNt(x+24*a*i,y+j*14*a*(i*i*3-2),i,j,-j*a/3):NEXT:NEXT
REM return 0
=0
```

**REV 0**
According to the OP's answer to @xnor, filled in snowflakes are OK. This answer was inspired by xnor's comment. The colours are just for fun and to show the way it is constructed. Take a triangle (magenta in this case) and overplot with 6 triangles 1/3 of the base.
```
INPUTn
z=FNt(500,470,n,1,0,0)
END
DEFFNt(x,y,n,o,i,a)
a=3^n/22
GCOLn
MOVEx-36*a,y-o*21*a
MOVEx+36*a,y-o*21*a
PLOT85,x,y+o*42*a
IFn>1FORi=-1TO1:z=FNt(x+24*a*i,y+14*a*(i*i*3-2),n-1,-1,i,a):z=FNt(x+24*a*i,y-14*a*(i*i*3-2),n-1,1,i,a)NEXT
=0
```

[Answer]
**Mathematica 72**
```
Region@Line@AnglePath[Nest[Join@@({#,1,4,1}&/@#)&,{4,4,4},Input[]-1]π/3]
```
n=3
[](https://i.stack.imgur.com/NvMoQ.png)
Thanks for alephalpha.
[Answer]
# Python 3 - 139
Uses the turtle graphics library.
```
from turtle import*
b=int(input())
a=eval(("FR"*3)+".replace('F','FLFRFLF')"*~-b)
for j in a:fd(9/b*("G">j));rt(60*(2-3*("Q">j))*("K"<j))])
```
[Answer]
# Python 3, 117 bytes
```
from turtle import*
ht();n=int(input())-1
for c in eval("'101'.join("*n+"'0'*4"+")"*n):rt(60+180*(c<'1'));fd(99/3**n)
```
Method:
* The solution uses Python's turtle graphics.
* `n` is `input - 1`
* Starting from the string `0000` we join its every character with `101` `n` times iteratively with the [eval trick](https://codegolf.stackexchange.com/a/49155/7311) (thanks to @xnor for that).
* For every character in the final string we turn 60 degrees right or 120 degrees left based on the character value (`1` or `0`) and then move forward a length (`99/3^n`) which guarantees a similar size for all `n`'s.
* The last `0` in the string will be useless but it just redraws the same line the first `0` draws.
Example output for `input = 3`:

[Answer]
## R: ~~240~~ 175
Because I trying to get my head around R, here's another version. There's likely to be lot better ways to do this and I'm happy to receive pointers. What I've done seems very convoluted.
```
n=readline();d=c(0,-120,-240);c=1;while(c<n){c=c+1;e=c();for(i in 1:length(d)){e=c(e,d[i],d[i]+60,d[i]-60,d[i])};d=e};f=pi/180;plot(cumsum(sin(d*f)),cumsum(cos(d*f)),type="l")
```

[Answer]
*Wise fwom youw gwave...*
I knew I'd want to try implementing this in Befunge-98 using TURT, but I couldn't figure out how to go about it and I sat on it for several months. Now, only recently, I figured out a way to do it without using self-modification! And so...
# Befunge-98 with the TURT fingerprint, 103
```
;v;"TRUT"4(02-&:0\:0\1P>:3+:4`!*;
>j$;space makes me cry;^
^>1-:01-\:0\:01-\:0
0>I@
^>6a*L
^>ca*R
^>fF
```
Let's get some implementation details out of the way first:
* I tested this using [CCBI 2.1](https://deewiant.iki.fi/projects/ccbi/), whose implementation of TURT (the turtle graphics fingerprint) makes `I` "print" the image to a SVG file. If you run this in CCBI without the command-argument `--turt-line=PATH`, it will come out as a file named CCBI\_TURT.svg by default. This is the closest I could come to *"print a graphical representation of the snowflake to the screen"* with available Funge interpreters I could find. Maybe someday there will be a better interpreter out there that has a graphical display for the turtle, but for now...
* There has to be a newline at the end for CCBI to run it without hanging (this is included with the character count). I know, right?
Basically, this works by using the stack as a sort of makeshift L-system and expanding it on the fly. On each pass, if the top number on the stack is:
* -2, then it prints and stops;
* -1, the turtle turns counterclockwise 60 degrees;
* 0, it turns clockwise 120 degrees;
* 1, it moves forward (by 15 pixels here, but you can change it by modifying the `f` on the last line);
* some number *n* that's 2 or greater, then it is expanded on the stack to `n-1, -1, n-1, 0, n-1, -1, n-1`.
For `n = 10`, this process takes a *very long time* (a couple of minutes on my system), and the resulting SVG is ~10MB in size and invisible when viewed in the browser because you can't adjust the size of the brush using TURT. IrfanView seems to work decently if you have the right plugins. I'm not super familiar with SVG, so I don't know what the preferred method is for viewing those files (especially when they're really big).
Hey, at least it *works* - which, considering it's Befunge, is something to be thankful for on its own.
[Answer]
# [APL(Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 57 bytes [SBCS](https://github.com/abrudz/SBCS)
```
'A=↑1 +=⌽¯60 -=⌽60'⌂turtle'A' 'A-A++A-A'⌂lsys⍣⎕⊢'A++A++A'
```
APL has builtins for generation of fractal L-systems and drawing them using turtle graphics.
Requires Dyalog for Windows.
[](https://i.stack.imgur.com/gphuz.png)
[Answer]
# Python 2, 127 bytes
```
from turtle import *
def L(l,d=input()-1):
for x in[1,-2,1,0]:[L(l,d-1),rt(60*x)] if d>0 else fd(l)
for i in'lol':lt(120);L(9)
```
] |
[Question]
[
Make a program that simulates the basic logic gates.
**Input:** An all-caps word followed by 2 1 digit binary numbers, separated by spaces, such as `OR 1 0`. The gates `OR`, `AND`, `NOR`, `NAND`, `XOR`, and `XNOR` are needed.
**Output:** What the output of the entered logic gate would be given the two numbers: either 1 or 0.
**Examples:**
`AND 1 0` becomes `0`
`XOR 0 1` becomes `1`
`OR 1 1` becomes `1`
`NAND 1 1` becomes `0`
This is codegolf, so the shortest code wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 38 bytes
```
lambda s:sum(map(ord,s))*3%61%37%9%7%2
```
[Try it online!](https://tio.run/##XZA9C4MwEEBn/RW3BJPiYBQqFTIUOlvolKGLxYqCH8FESn99ioppkvHx7t3Bia9qpzHVDXvqvhpedQWykMuAh0rgaa5jScgpQ2eKshxdUI5S/Wm7/g20CAMZgwIG3SgWhUkYiLkbFTRYEmAMVAzrgMbRtbxBAkkUQ0LCA6mN1LV0s3RFfn/Y7Y6O3VsLzWY3dUs3NN1GpQktNFtLk1poLPdi7tXcy3np3f4/y2bXU88f938 "Python 2 – Try It Online")
A good ol' modulo chain applied to the sum of ASCII values of the input string, making for a solution that's just overfitting. The total ASCII value is distinct for each possible input, except that those with `0 1` and `1 0` give the same result, which is works out because all the logic gates used are symmetric.
The `*3` separates out otherwise-adjacent values for inputs that different only in the bits, since these make it hard for the mod chain to split up. The length and size of numbers in the mod chain creates roughly the right amount of entropy to fit 18 binary outputs.
A shorter solution is surely possible using `hash(s)` or `id(s)`, but I avoided these because they are system-dependent.
---
# [Python 2](https://docs.python.org/2/), 50 bytes
```
lambda s:'_AX0NRD'.find((s*9)[35])>>s.count('0')&1
```
[Try it online!](https://tio.run/##XZCxCsIwEEBn@xU3mURKSRQHCxGEzhE6BVREraUBjcWkiF9f0dKYZHy8e3dw7ds2Dz3va77vb6f7uTqBydFxI6koC5TVSlcYm9mK7BbLA1mvTXZ5dNpiRBGZsv7VqNsVWJ5MTAoWOCjddhaTZNI@lbZQY0OAc7ApfAd6jDaiAAoUpUBJMiLzkYWW/Sz7otyWfjtgYIfWQ7c5TMMyDF33I@FCD91W4VIPnZVRLKNaRrkU0e3/s3wOPYv8eP8D "Python 2 – Try It Online")
A slightly more principled solution. Each logic gate gives a different result for each count of zeroes in the input, encodable as a three-bit number from 1 to 6. Each possible logic gate is mapped to the corresponding number by taking `(s*9)[35]`, which are all distinct. For `OR`, this winds up reading one of the bits so the character could be `0` or `1`, but it turns out to work to check if it's `0`, and a `1` will correctly give a `1` result anyway.
[Answer]
# JavaScript (ES6), 39 bytes
```
s=>341139>>parseInt(btoa(s),34)%86%23&1
```
[Try it online!](https://tio.run/##lY1BS8QwFITv@RXvsqbBtruxZVGkAUUPXiq4F0E8ZGuyjcS@kjwVEX97TXePguhlBmaGb571m45dcCMVAz6ZyTZTbFRVS1mdKTXqEM3NQNmWUGdR5FUtFqfrxUl1JKflEkb0H9Z5DxYD7DcCCIFMJKDeRXh31EObwGxuoYEIjYLLV2tNKG3AlwQtCTcU3LDL@FZHs665YOz8gV@0Vzznt3dJ7vfaHpL2EM32yMr0fK27PsNxJn8ygA6HiN6UHndZuoPUHAOHFax4DrwoVDKbfsVvW/nnrfwHV/7kfonpGw "JavaScript (Node.js) – Try It Online")
### How?
We can't parse spaces with `parseInt()`, no matter which base we're working with. So we inject a base-64 representation of the input string instead. This may generate `=` padding characters (which can't be parsed with `parseInt()` either), but these ones are guaranteed to be located at the end of the string and can be safely ignored.
We parse as base \$34\$ and apply a modulo \$86\$, followed by a modulo \$23\$, which gives the following results. This includes inaccuracies due to loss of precision. The final result is in \$[0..19]\$, with the highest truthy index being at \$18\$, leading to a 19-bit lookup bitmask.
```
input | to base-64 | parsed as base-34 | mod 86 | mod 23 | output
------------+----------------+-------------------+--------+--------+--------
"AND 0 0" | "QU5EIDAgMA==" | 1632500708709782 | 26 | 3 | 0
"AND 0 1" | "QU5EIDAgMQ==" | 1632500708709798 | 42 | 19 | 0
"AND 1 0" | "QU5EIDEgMA==" | 1632500708866998 | 34 | 11 | 0
"AND 1 1" | "QU5EIDEgMQ==" | 1632500708867014 | 50 | 4 | 1
"OR 0 0" | "T1IgMCAw" | 1525562056532 | 52 | 6 | 0
"OR 0 1" | "T1IgMCAx" | 1525562056533 | 53 | 7 | 1
"OR 1 0" | "T1IgMSAw" | 1525562075028 | 58 | 12 | 1
"OR 1 1" | "T1IgMSAx" | 1525562075029 | 59 | 13 | 1
"XOR 0 0" | "WE9SIDAgMA==" | 1968461683492630 | 48 | 2 | 0
"XOR 0 1" | "WE9SIDAgMQ==" | 1968461683492646 | 64 | 18 | 1
"XOR 1 0" | "WE9SIDEgMA==" | 1968461683649846 | 56 | 10 | 1
"XOR 1 1" | "WE9SIDEgMQ==" | 1968461683649862 | 72 | 3 | 0
"NAND 0 0" | "TkFORCAwIDA=" | 61109384461626344 | 62 | 16 | 1
"NAND 0 1" | "TkFORCAwIDE=" | 61109384461626350 | 70 | 1 | 1
"NAND 1 0" | "TkFORCAxIDA=" | 61109384461665650 | 64 | 18 | 1
"NAND 1 1" | "TkFORCAxIDE=" | 61109384461665656 | 72 | 3 | 0
"NOR 0 0" | "Tk9SIDAgMA==" | 1797025468622614 | 76 | 7 | 1
"NOR 0 1" | "Tk9SIDAgMQ==" | 1797025468622630 | 6 | 6 | 0
"NOR 1 0" | "Tk9SIDEgMA==" | 1797025468779830 | 84 | 15 | 0
"NOR 1 1" | "Tk9SIDEgMQ==" | 1797025468779846 | 14 | 14 | 0
"XNOR 0 0" | "WE5PUiAwIDA=" | 66920415258533864 | 0 | 0 | 1
"XNOR 0 1" | "WE5PUiAwIDE=" | 66920415258533870 | 8 | 8 | 0
"XNOR 1 0" | "WE5PUiAxIDA=" | 66920415258573170 | 2 | 2 | 0
"XNOR 1 1" | "WE5PUiAxIDE=" | 66920415258573176 | 10 | 10 | 1
```
[Answer]
## CJam (13 bytes)
```
q1bH%86825Yb=
```
Assumes that input is without a trailing newline.
[Online test suite](http://cjam.aditsu.net/#code=qN%25%7B%0A%0A1bH%2586825Yb%3D%0A%0Ap%7D%2F&input=AND%200%200%0AAND%200%201%0AAND%201%200%0AAND%201%201%0AOR%200%200%0AOR%200%201%0AOR%201%200%0AOR%201%201%0AXOR%200%200%0AXOR%200%201%0AXOR%201%200%0AXOR%201%201%0ANAND%200%200%0ANAND%200%201%0ANAND%201%200%0ANAND%201%201%0ANOR%200%200%0ANOR%200%201%0ANOR%201%200%0ANOR%201%201%0AXNOR%200%200%0AXNOR%200%201%0AXNOR%201%200%0AXNOR%201%201)
This is just a simple hash which maps the 24 possible inputs into 17 distinct but consistent values and then looks them up in a compressed table.
## Python 2 (36 bytes)
```
lambda s:76165>>sum(map(ord,s))%17&1
```
This is just a port of the CJam answer above. [Test suite](https://tio.run/##XZA9C4MwEEBn/RW3tCbg4BVqQYhQ6JxCpwxdLFYU/MJESn99ioppkvHx7t3BjV9VD/1JV@yp26J7lQXI7JJies5zOXekK0YyTGUsKT3g5Yj6UzftGzALAxmDAgZNP86K0DAYp6ZXUBFJgTFQMSwDmkRXfoMEkiiGhIY7oo3oWlwtLijuD7vd0LFba6HZ7KZu6YamW4mb0EKzlZvUQmOFFwuvFl4uuHf7/yybXY@e3@//AA) using xnor's testing framework.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ ~~12~~ ~~10~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÇO₁*Ƶï%É
```
Port of [*@mazzy*'s alternative calculation mentioned in the comment on his Powershell answer](https://codegolf.stackexchange.com/questions/173492/logic-gates-manually/173584#comment419038_173584) (`*256%339%2` instead of `*108%143%2`).
[Try it online](https://tio.run/##yy9OTMpM/f//cLv/o6ZGrWNbD69XPdz5/7@fo5@LgoGCIQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/8Pt/o@aGrWObT28XvVw53@d/45@LgoGCgZcENoQTBsC@f5BYOEIJNoQKO0HkQcywBIQGqTeD6ogAiYRAZOB6YCKQ0VhymGqYcbA3OMHc5AfzEV@MKegMICGAAA).
**Explanation:**
```
Ç # Convert each character in the (implicit) input to a unicode value
O # Sum them together
₁* # Multiply it by 256
Ƶï% # Then take modulo-339
É # And finally check if it's odd (short for %2), and output implicitly
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶï` is `339`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes
```
§01÷⌕⪪”&⌈4Y⍘LH⦄vü|⦃³U}×▷” S∨⁺NN⁴
```
[Try it online!](https://tio.run/##NYxBC4MwDIX/SugphQ0UdttJkIGXKvPi1dmyFboqXSr791k6MPDI@0LeW15zWtY5MA/JR8KGumjdF1VVqxN0kVq/e@vw5qPFcQueUMHU36ExLcgyRcVP4iShQOmS2zKNJI1P1MJ9wiHkD/7vJr8fLuHxdqDwRctcmUt/BTWf9/AD "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The compressed string expands to a list of the supported operations so that the index of the given operation is then shifted right according to the inputs and the bit thus extracted becomes the result.
```
XOR 001
AND 010
OR 011
NOR 100
NAND 101
XNOR 110
inputs 011
010
```
74-byte version works for all 16 binary operations, which I have arbitrarily named as follows: ZERO AND LESS SECOND GREATER FIRST XOR OR NOR XNOR NFIRST NGREATER NSECOND NLESS NAND NZERO.
```
§10÷÷⌕⪪”&↖VρS´↥cj/v⊗J[Rf↓⪫?9KO↘Y⦄;↙W´C>η=⁴⌕✳AKXIB|⊖\`⊖:B�J/≧vF@$h⧴” S∨N²∨N⁴
```
[Try it online!](https://tio.run/##bY5NC8IwDIb/SugpA4VNvHkarpOBtNLuMLzNbWhhzlG64b@v6VS8GPJC8pCPt7nVtnnUvfcnawaHqSuGtnsiS2K2gmJwmZlN2@Gvys3Qoh5745BJwUGkIgNx5FqD0HwvQ3dQPC25ApEXSpdQCUk1ibIivel36LO0XAi3zlxJ@s2ARcHBODntyNsVI@qlxQWJ6X7pLBLZ/KXbiGLnfXgXQ@LXc/8C "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# Mathematica, 55 bytes
```
Symbol[ToCamelCase@#][#2=="1",#3=="1"]&@@StringSplit@#&
```
Pure function. Takes a string as input and returns `True` or `False` as output. Since [`Or`](https://reference.wolfram.com/language/ref/Or.html), [`And`](https://reference.wolfram.com/language/ref/And.html), [`Nor`](https://reference.wolfram.com/language/ref/Nor.html), [`Nand`](https://reference.wolfram.com/language/ref/Nand.html), [`Xor`](https://reference.wolfram.com/language/ref/Xor.html), and [`Xnor`](https://reference.wolfram.com/language/ref/Xnor.html) are all built-ins, we use `ToCamelCase` to change the operator to Pascal case, convert it to the equivalent symbol, and apply it to the two arguments.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 10 bytes
```
OSị“ʋN’Bݤ
```
[Try it online!](https://tio.run/##y0rNyan8/98/@OHu7kcNc051@z1qmOl0dPehJf8f7t5yuP1R05rI//8d/VwUDBUMuCL8gxQMFAy5gJQhkPKDiBsCAA "Jelly – Try It Online")
Port of Peter Taylor's answer.
[Answer]
# [J](http://jsoftware.com/), 21 bytes
```
2|7|9|37|61|3*1#.3&u:
```
[Try it online!](https://tio.run/##bc7BCsIwDAbg@54iKKwopTQOHFYUBM8RPOWsOKYXD@qtPnutbEtEdij9Sf/y5ZYmDkwDm2DAwjuAh3zSItZxFas6LjFWc5y6qnyFNCtO1@cjd3PLWw9oMd8BAYvicm7v0JRuC@Zw/L6bdRewCzhMctv8tne07@tdwj6hzP5/kAAkAglBIwYpQqqQMjTmsDgsDovDIw7raqy7sS7Hw3bpAw "J – Try It Online")
Port of [xnor's Python 2 solution](https://codegolf.stackexchange.com/a/173496/78410).
---
# [J](http://jsoftware.com/), 30 bytes
```
XNOR=:=/
NAND=:*:/
NOR=:+:/
".
```
[Try it online!](https://tio.run/##bY7NCsIwEITveYqlB4M/xOYaiaB4nkJPexeLePEJfPZ0a9pdkR4CH8NOvnkVXAM1gfxAOXk60CdRS/IKo@tzykeHC2457ZLQlOwFmvDtbd3Ukrpzj/vzTcMmnMl3vfzQ@lOFWCEuSZTk91o@n88rxZmiZv8NqABqgCqw4oBJYBaYBmseVg@rh9XDKx62aWzb2Mbxsq6M "J – Try It Online")
Some bit of fun with eval `".` and standard library (which already includes correct `AND`, `OR`, `XOR`).
---
# [J](http://jsoftware.com/), 41 bytes
```
({7 6 9 8 14 1 b./)~1 i.~' XXNNA'E.~_2&}.
```
[Try it online!](https://tio.run/##XYyxCsJAEET7fMWQImvgWG9FNB5YBLRdweo6IcVBbLULuV8/N11isQyPN7PvUjMo4RoIDnOAh13ZTWeccEEHOUIw8L7NgpEzIUbVnu6cX4dm5tJWw/j92N6W3nmIE8sgkGKABHo8qUrNErV9svJCvd7WqFurfzpudVzVfw "J – Try It Online")
More J-style approach.
### How it works
A very general J trick is hidden here. Often, the desired function has the structure "Do F on one input, do H on the other, and then do G on both results." Then it should operate like `(F x) G H y`. In tacit form, it is equivalent to `(G~F)~H`:
```
x ((G~F)~H) y
x (G~F)~ H y
(H y) (G~F) x
(H y) G~ F x
(F x) G H y
```
If `G` is an asymmetric primitive, just swap the left and right arguments of the target function, and we can save a byte.
Now on to the answer above:
```
({7 6 9 8 14 1 b./)~1 i.~' XXNNA'E.~_2&}.
1 i.~' XXNNA'E.~_2&}. Processing right argument (X): the operation's name
_2&}. Drop two chars from the end
1 i.~' XXNNA'E.~ Find the first match's index as substring
Resulting mapping is [OR, XOR, XNOR, NOR, NAND, AND]
7 6 9 8 14 1 b./ Processing left argument (Y): all logic operations on the bits
7 6 9 8 14 1 b. Given two bits as left and right args, compute the six logic functions
/ Reduce by above
X{Y Operation on both: Take the value at the index
```
[Answer]
# Powershell, ~~36~~ 34 bytes
Inspired by [xnor](https://codegolf.stackexchange.com/a/173496/80745), but the sequence `*108%143%2` is shorter then original `*3%61%37%9%7%2`
```
$args|% t*y|%{$n+=108*$_};$n%143%2
```
Test script:
```
$f = {
$args|% t*y|%{$n+=108*$_};$n%143%2
#$args|% t*y|%{$n+=3*$_};$n%61%37%9%7%2 # sequence by xnor
}
@(
,("AND 0 0", 0)
,("AND 0 1", 0)
,("AND 1 0", 0)
,("AND 1 1", 1)
,("XOR 0 0", 0)
,("XOR 0 1", 1)
,("XOR 1 0", 1)
,("XOR 1 1", 0)
,("OR 0 0", 0)
,("OR 0 1", 1)
,("OR 1 0", 1)
,("OR 1 1", 1)
,("NAND 0 0", 1)
,("NAND 0 1", 1)
,("NAND 1 0", 1)
,("NAND 1 1", 0)
,("NOR 0 0", 1)
,("NOR 0 1", 0)
,("NOR 1 0", 0)
,("NOR 1 1", 0)
,("XNOR 0 0", 1)
,("XNOR 0 1", 0)
,("XNOR 1 0", 0)
,("XNOR 1 1", 1)
) | % {
$s,$e = $_
$r = &$f $s
"$($r-eq$e): $s=$r"
}
```
Output:
```
True: AND 0 0=0
True: AND 0 1=0
True: AND 1 0=0
True: AND 1 1=1
True: XOR 0 0=0
True: XOR 0 1=1
True: XOR 1 0=1
True: XOR 1 1=0
True: OR 0 0=0
True: OR 0 1=1
True: OR 1 0=1
True: OR 1 1=1
True: NAND 0 0=1
True: NAND 0 1=1
True: NAND 1 0=1
True: NAND 1 1=0
True: NOR 0 0=1
True: NOR 0 1=0
True: NOR 1 0=0
True: NOR 1 1=0
True: XNOR 0 0=1
True: XNOR 0 1=0
True: XNOR 1 0=0
True: XNOR 1 1=1
```
[Answer]
# Java 10, ~~30~~ 28 bytes
```
s->s.chars().sum()*108%143%2
```
[Port of *@mazzy*'s Powershell answer](https://codegolf.stackexchange.com/a/173584/52210).
[Try it online.](https://tio.run/##dZLdSsMwFMfv9xSHwiBxLDTqhTA2ELw1grspiBcxq5rZZqVJByK99QF8RF@kZmlxrDm7SCC/nPM/n1u5l/Pt5qNThbQW7qU2XxMAbVxev0qVgzg8AwBF1q7W5g0sXXjYTvxlnXRagQADS@jsfGWZepe1JZTZpiT0gqc3U359Nb3sFgf7qnkpvP3gtt/pDZQ@5qD89AyS9gFdbh1JbsUdpJAmIeAp5DHkY8uHx9g7Owf5WFL0mmMa/BEYRReYaIb6ZyOB9ad1ecl2jWOVb4wrDKGhf6flcqTcmGFtifNC00LLQoci0KkIdCwCHcF5@p9s689x6cL2BLNhL7WpGjfsD9LB8D1L4Pf7B5KZYaondJBuuz8)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 20 bytes
```
*.ords.sum*108%143%2
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0svvyilWK@4NFfL0MBC1dDEWNXovzVXWn6Rgo2jn4uCf5BCBBD7gdh@IA6QsFOIqFNQUjBU0lFSMFBC5VRzcRYnVipoqMQr2Nop6KmlaXLV/gcA "Perl 6 – Try It Online")
A port of [maddy's approach](https://codegolf.stackexchange.com/a/173584/76162). Alternatively, `*256%339%2` also works.
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 24 bytes
```
*.ords.sum*3%61%37%9%7%2
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0svvyilWK@4NFfLWNXMUNXYXNVS1VzV6L81V1p@kYKNo5@Lgn@QQgQQ@4HYfiAOkLBTiKhTUFIwVNJRUjBQQuVUc3EWJ1YqaKjEK9jaKeippWly1f4HAA "Perl 6 – Try It Online")
A port of [xnor's answer](https://codegolf.stackexchange.com/a/173496/76162). I'll have a go at finding a shorter one, but I think that's probably the best there is.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~106~~ 94 bytes
```
x=>([a,c,d]=x.split` `,g=[c&d,c^d,c|d]["OR".search(a.slice(1+(b=/N[^D]/.test(a))))+1],b?1-g:g)
```
[Try it online!](https://tio.run/##bVFRa8IwEH7vrzgCk4SedZU96eoQ3GsLfRJKxTRNu0qx0mYqzP327uJWGW4HyXH3fd/d5bKTR9mptjqY8b7JdV8E/TlY8ESiwjwNzl53qCuzhS2WQaJGOaoNnUueJiyKmddp2ao3Lr2urpTmvsuzYBImm1U68YzuDJeCzPVTzF78cTkrRT93jrKFZbiCALhEyAQEC5AwggwdIIviO@QyIOs/0GaAwvuCPoxtk@/ED@dObilR/Jux/o@yHjhzp2ha4Hb8UhoNTQGMWmAUI3HQjoChDcLraq6Lw62ADwduworKP87JPcMTOdcV1Fg1@66ptVc3JT8RIbHlEXhFS5mKyRShepim3q6p9vYngL2eD1oZnc8Ygj7Kml/ncYFxRvdNZzPEJkd6GwgmKF4q8y5rqy34SdCzPp3@Cw "JavaScript (Node.js) – Try It Online")
Link to the code and all 24 cases.
+9 for forgotten to map the XNOR case.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 45 bytes
**Just a port of xnor's superb Python 2 answer posted upon consent, please give that answer upvotes instead of this.**
```
x=>Buffer(x).reduce((a,b)=>a+b)*3%61%37%9%7%2
```
[Try it online!](https://tio.run/##bZBvS8MwEMbf91McgUhis@o6cehsYaJvW@irgShNu3R0lKb03wrqZ6@X6YZU8yLH3fN77i7Zy142aZ1X7azUWzVm3jh4/mOXZapmA3dqte1SxZgUCfd8aSf8ckFv53SxpHd0Sd1xZfWyhnXwBB4gBQkHzwcJF5AIC/CE0UT5OCmbP9LbSQqmDecwM0O@Cz/MxG6QMPpNbP5DNidmZWW6BmbW38lWgc6A4AgRRgIZYVYQgUnwIk5TFXkbi5jDuwVnY47tr1cYHuAGg21zHJzqstGFcgq9YwcEXkx7ASzHT3H5lSsgp@6rs9d5GUMsgDwPlUpbtb0nAlQvC3bcxwbCCN5nn6kgjQH9JuGEY75O204WxpuxA8dnfVrjFw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 55 bytes
```
{Eval!$"${Sum!Id''Downcase!SplitAt!_}${N=>__2}"}@@Split
```
[Try it online!](https://tio.run/##RU7LasMwELzrK9ZCJBeffCw45FloD2pIcggIIYStpAZbNvW6SRD6dkcWgexlZ3aHmdGIuvg14wU@8tHt/nWdMMrccWiSr3I@37Y3W@jeJMeurnCFifLM8XyhVOapXy7jebS6MX0wgEgF/TnAim@Bh80ncA7gHBiVpLLdgFG7DrZrU7c3kaWQSYKmRzVlxe9nrVE4AmHUjDmYSt09MPfdVlY8UqBApadR4CFfgMqIn73cA42VJCHcmLIXrOuKqyT7v8riKeRsphhxSeEdKscn "Attache – Try It Online")
A rather brutish solution. Converts the input to the relevant Attache command and evaluates it. (Attache has built-ins for each of the 6 logic gates.)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 20 bytes
```
->s{76277[s.sum%17]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf16642tzMyNw8ulivuDRX1dA8tvZ/QWlJsYJquIajn4uCf5BCBBD7gdh@IA6Q0NQrKMpPKU0u0dAw0NMz1tTLTSyorqmoqdBLySzLzU9RMKqFiiXWFNsqqQINSwEiJdVEvbScxJKS1DxrkKCuHVgwulhHIS26OBZoMQA "Ruby – Try It Online")
### How it works:
Basically the same as Peter Taylor's answer, but Ruby makes it easier. The magic number is different but the idea was the same.
] |
[Question]
[
Your task is to print the following ASCII Art:
```
_ _ _______ _
| | | | (_______) _ | |
| |__ | | ____ ____ ____ _ _ _____ ____ ___| |_ ____ ____| |
| __)| |/ _ | _ \| _ \| | | | | ___) / _ |/___) _)/ _ )/ ___)_|
| | | ( ( | | | | | | | | |_| | | |____( ( | |___ | |_( (/ /| | _
|_| |_|\_||_| ||_/| ||_/ \__ | |_______)_||_(___/ \___)____)_| |_|
|_| |_| (____/
```
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest amount of bytes wins.
Good luck.
[Answer]
# Bubblegum, 130 bytes
```
0000000: 758f b579 0530 18c4 7a4f a1d2 7fe5 8102 u..y.0..zO......
0000010: 5ae4 760f 5de8 91ee b3cc 8400 f523 2c3c Z.v.]........#,<
0000020: 4656 0850 3f60 5b86 5fe4 8290 15a2 84a0 FV.P?`[._.......
0000030: 5a61 4d0b b64f 2b35 c476 eb1e 844e c841 ZaM..O+5.v...N.A
0000040: 08c8 731d 1a02 ead0 1547 1d70 beba 9fd6 ..s......G.p....
0000050: 31bf 5fdb 6c72 1d7b 1051 ed8a a884 7c76 1._.lr.{.Q....|v
0000060: 0fa7 db91 1503 c43c 9b18 124f cdb3 4220 .......<...O..B
0000070: 9631 716b a71c 3bd6 ed8b 0b62 7ebd 55cf .1qk..;....b~.U.
0000080: 7a07 z.
```
[Try it online.](http://bubblegum.tryitonline.net/#code=MDAwMDAwMDogNzU4ZiBiNTc5IDA1MzAgMThjNCA3YTRmIGExZDIgN2ZlNSA4MTAyICB1Li55LjAuLnpPLi4uLi4uCjAwMDAwMTA6IDVhZTQgNzYwZiA1ZGU4IDkxZWUgYjNjYyA4NDAwIGY1MjMgMmMzYyAgWi52Ll0uLi4uLi4uLiMsPAowMDAwMDIwOiA0NjU2IDA4NTAgM2Y2MCA1Yjg2IDVmZTQgODI5MCAxNWEyIDg0YTAgIEZWLlA_YFsuXy4uLi4uLi4KMDAwMDAzMDogNWE2MSA0ZDBiIGI2NGYgMmIzNSBjNDc2IGViMWUgODQ0ZSBjODQxICBaYU0uLk8rNS52Li4uTi5BCjAwMDAwNDA6IDA4YzggNzMxZCAxYTAyIGVhZDAgMTU0NyAxZDcwIGJlYmEgOWZkNiAgLi5zLi4uLi4uRy5wLi4uLgowMDAwMDUwOiAzMWJmIDVmZGIgNmM3MiAxZDdiIDEwNTEgZWQ4YSBhODg0IDdjNzYgIDEuXy5sci57LlEuLi4ufHYKMDAwMDA2MDogMGZhNyBkYjkxIDE1MDMgYzQzYyA5YjE4IDEyNGYgY2RiMyA0MjIwICAuLi4uLi4uPC4uLk8uLkIgCjAwMDAwNzA6IDk2MzEgNzE2YiBhNzFjIDNiZDYgZWQ4YiAwYjYyIDdlYmQgNTVjZiAgLjFxay4uOy4uLi5ifi5VLgowMDAwMDgwOiA3YTA3ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHou&input=)
Compressed using `zopfli --deflate --i10000`.
[Answer]
# JavaScript (ES6), ~~377~~ ~~373~~ ~~360~~ ~~359~~ 345 bytes
*Thanks to @Neil for a one byte savings, and to @edc65 for another 14!*
Figured I'd give it a shot. Compresses common repeating patterns in the text.
`_____` (5 underscores) is stored as `_5`
`     ` (5 spaces) is stored as ` 5`
` | | | | |` (5 of the ` |` pattern) is stored as `~5`
```
console.log(` _ 5_ 28_7 27_
|~ 2~2 26(_7) 10_ 13~2
|~_2~2 _4 _4 2_4 2_ 3_ 4_5 3_4 2_3|~_ 2_4 2_4|~
| 2_2)|~/ _ ~ 2_ \\| 2_ \\|~3 ~ 2_3) / _ ~/_3) 2_)/ _ 2)/ _3)_|
|~ 2~ ( (~9_|~ ~2_4( (~2_3~2_( (/ /|~ 4_
|_| 2~_|\\_|2_|~|_/|~|_/ \\_2 ~ ~_7)_|2_(_3/ \\_3)_4)_| 2~_|
13~_| 2~_| 3(_4/`.replace(/(.)(\d+)/g,(_,a,b)=>a.repeat(b)).replace(/~/g,' |'))
```
[Answer]
# [BinaryFuck](https://esolangs.org/wiki/Binaryfuck), ~~565~~ 378 bytes
This basically stores the characters used in the array, then navigates through the array, printing them accordingly. Currently quite long, will shorten it up.
```
1000010000000000000000110011110001010010000011011111010010110001011011000000010010111011001111011110010010010000010000010000000000000010000010000000000010000010000000000011011011011011011011011011001111010010000000000110001010000000000000000010000000000011011111010010001010001001001001010010001010000000000000000000000000000010001001001001010000000000000000000000000000000011011011011100010100011100100100100100010100011100100100100100100100100100100100100100100100100100100100100100100100100100100100100010100100100100100100100011100100100100100100100100100100100100100100100100100100100100100100100100100100100010100011100010010010010100011011011011011100010100011100010100100100011100010100011100010100100100100100100100100100100100100100100100100100100100100100100100100100100011011100010010010100100100100100100100010100011011100100100100100100100100100100010100011100100100100100100100100100100100100100100011100010100011100010010010010010100011011011011011100010100011100010010100100011100011100010100011100010100010100100100100011100010100100100100011100100010100100100100011100100010100011100100100010100011100100100100010100100100100100011100100100010100100100100011100100010100100100011011100010100011100010010100011100100010100100100100011100100010100100100100011011100010100011100010010010010010100011011011011011100010100100010100100010100011011011100010100011100011011100010010010100010100011100100011100010100100010100011100010010010100011011011011100010100100010100011100010010010100011011011011100010100011100010100011100010100011100010100100011100010100100010100100100010100011011100011011011100010010010100010100011100100011100011011100010010010010100100100010100011011100100010100010100011011011011011100010010010100010100011100100010010100011011011011011100010010010100010100100100010100011100011011100010010010010010100011011011011011100010100011100010100100100011100010100011011100010010100011011100010010100011100010100011100010100011100010100011100010100011100010100011100010100011100010100011100010100011100010010100011011100010100011100010100100011100010100011100010010100100100100011011011100010010100011011100010010100011100010100011100010010100100100011100011100010100011100010010100011011011100010010100011011100011100010010010100011011011100010010100010100011100010100100100100010100011100010010010010100011011011011011100010010100011011100010100100100011100010010100011011100010010010010100011011100011011100100010010100011011100010100011100100010010100011011011011100010010100010100011100100010010100011011011011100010010010100010010010100011011100100011100100011100010100100011100010010100100100100100100100010100011100011011100100010010100011011011100010010010100100100011011011011100010010010100010010010100011011100100100010100011100100100100010100011100011011100010100100100011100010010100011011100010010010010010100011011011011100100100100100100100100100100100100100100011100010010100011011100010100100100011100010010100011011100010100100100011011100010010010100100100100011011011011100
```
Here is the ungolfed code:
```
+>+++++[<[->>+<<]>>[-<<++>>]<-]<
[>>>+>+>++++>+>+++>+>+++<<<<<<<<<-]
>>+++[->+++++>+++<<]>>->---->>->+++++++++>---->++++++++++
<<<<.>.<.....>.<............................>.......<...........................>.<.>>>>.<<<<<.>.<.>...<.>.<.>..........................<<.>>>.......>.<<..........>.<..............<.>.<.>>>>>.<<<<<.>.<.>>..<.<.>.<.>.>....<.>....<..>....<..>.<...>.<....>.....<...>....<..>...<<.>.<.>>.<..>....<..>....<<.>.<.>>>>>.<<<<<.>..>..>.<<<.>.<.<<.>>>.>.<..<.>..>.<.>>>.<<<<.>..>.<.>>>.<<<<.>.<.>.<.>.<.>..<.>..>...>.<<.<<<.>>>.>.<..<.<<.>>>>...>.<<..>.>.<<<<<.>>>.>.<..>>.<<<<<.>>>.>...>.<.<<.>>>>>.<<<<<.>.<.>...<.>.<<.>>.<<.>>.<.>.<.>.<.>.<.>.<.>.<.>.<.>.<.>.<.>>.<<.>.<.>..<.>.<.>>....<<<.>>.<<.>>.<.>.<.>>...<.<.>.<.>>.<<<.>>.<<.<.>>>.<<<.>>.>.<.>....>.<.>>>>.<<<<<.>>.<<.>...<.>>.<<.>>>>.<<.<<..>>.<<.>.<..>>.<<<<.>>.>.<..>>.<<<<.>>>.>>>.<<..<..<.>..<.>>.......>.<.<<..>>.<<<.>>>...<<<<.>>>.>>>.<<...>.<....>.<.<<.>...<.>>.<<.>>>>>.<<<<..............<.>>.<<.>...<.>>.<<.>...<<.>>>....<<<<.
```
EDIT: by rearranging the order of the characters in the cells, I saved 186 bytes!
[Answer]
## JavaScript (ES6), 380 bytes
For completeness this is my effort to use a different compression method, although as it turns out it's not as efficient as run length encoding. Each digit specifies that the last N already generated characters are repeated. Subsequent digits can repeat already repeated characters, e.g. `| 23` turns into `| | |`. I only wish I could compress a run of three characters.
```
f=(s=` _ 26 2479__23 2499_
| 2 6 2379(__23) 25_ 237|2
| |__ |2 __25 __2 _ 4 ___2 __2 ___| |_ ___6_| |
| __)| |/ _ | _ \\6| 24 | ___) / _ |/___) _)/ _ )/ ___)_|
| 2 | (2 |248 |_| 23|__2( 2| |___ |2_( (/ /| 2 _
|_| |_|\\_||_| ||_/6 \\__ |3__23)_||_(___/ \\___)_5| |_|
237|_|6 (__2/`,r=s.replace(/(.*?)(\d)/,(_,p,n)=>p+p.slice(-n)))=>r==s?r:f(r)
o.textContent = f()
```
```
<pre id=o></pre>
```
[Answer]
# C, 517 427 407 bytes
* saved few bytes, thanks to @ceilingcat
```
c,i;main(m){for(char*s=" _ 4_ 999_6 998_ 1\n|B 2|B 997(_6) 9_ 94|B \n| |_1C _3 _3 1_3 1_ 2_ 3_4 2_3 1_2|B_ 1_3 1_3|B \n| 1_1)|B/ _ 1\\| 1_ \\| 1_E 1| 1_2) / _ 1|/_2) 1_)/ _ 1)/ _2)_| \n|B 2| ( (J_|B 1|B_3( (C_2C_( (/ /|B 3_ 1\n|_| 2|_|\\_||_|B1_/|B1_/ \\_1 1| 1|_6)_|1_(_2/ \\_2)_3)_| 2|_| \n 94|_| 2|_| 2(_3/\n";*s;s++)for(i=isdigit(*s)?c=m,*s-48:isalpha(*s)?c=0,*s-65:(c=*s,1);i--;)printf(c?m=c,&c:" |");}
```
**Ungolfed** [Try Online](https://tio.run/##NVDRasMwDPwVkYchpQmZ7SxrGkqhZS/7hoAI7poamqzUhT3U@/ZMTjOwdb6T5ZNs897aaRqaHm3m6PFzdpcvdHlO15sb7ye0Oxy2NnuxtEkgJNT8Dp0bkR6n7xvac3dL/TYBhpKhrmuuJK4ZVDuGPWjZdf2OXBHUki@FSwICqwOwiUvNGzSD4VIgMinjJWGWCsWKwr6A@HIbKTzhA1QETTDnQhGPimlmMWriAEszgICfLEclBkbIgfWBBQsoRDXPtuW@ltC2HAT2ios5iCGr2S3IOBwUI@tZFQtDS5VYxTH/mUY2RTsmTeobv1qR80fXuzumnnY9Dlnq83JNG@e7y/XcLfJrlKs32vQiZEp@fJr@AA)
```
#include <stdio.h>
#include <stdint.h>
char m = 0;
void g(char c, int i)
{
while(i--) c ? m=putchar(c) : printf(" |");
}
void p(char* s)
{
while(*s)
isdigit(*s) // golfed if-else-if
? g(m,*s-48)
: isalpha(*s)
? g(0,*s-65)
: g(*s,1)
,
s++;
}
int main()
{
p(" _ 4_ 999_6 998_ 1\n|B 2|B 997(_6) 9_ 94|B \n| |_1C _3 _3 1_3 1_ 2_ 3_4 2_3 1_2|B_ 1_3 1_3|B \n| 1_1)|B/ _ 1\\| 1_ \\| 1_E 1| 1_2) / _ 1|/_2) 1_)/ _ 1)/ _2)_| \n|B 2| ( (J_|B 1|B_3( (C_2C_( (/ /|B 3_ 1\n|_| 2|_|\\_||_|B1_/|B1_/ \\_1 1| 1|_6)_|1_(_2/ \\_2)_3)_| 2|_| \n 94|_| 2|_| 2(_3/\n");
return 0;
}
```
[Answer]
## JavaScript, 297 bytes
```
console.log(` 29 288999002889 3
19 18899 500_)82891
1__ 1 0_ 02022 290_2 02012020_1
|3_)162|3 \\|3 \\1 19|90) 62|/0)3)62)60)_|
19 |55 1 1 1 1 71910_(5 10 1_(56/193
7|4\\_|717/176\\_2|9|00_)_|7(06\\0)0_)_|4
8 44950_/`.replace(/\d/g,n=>`___,| |,_ , _, |_|, (,/ ,|_, , `.split`,`[n]))
```
Simple encoding of the ten most (as far as I can tell) common substrings. They are not in order because of overlaps; my encoder (below) needs to see e.g. `'_ '` and `' _'` before `' '`.
```
(s,a,t=s)=>a.map((t,i)=>s=s.split(t).join(i))&&[s,(b=>{b=new Map;for(i=0;i<s.length;i++)for(j=0;j<i;j++)b.set(s.slice(j,i),s.length-s.split(s.slice(j,i)).join().length-i+j-1);return[for(x of b)if(x[1]>0&&!/\d/.test(x[0]))x].sort(([a,b],[c,d])=>b-d)})(),t.length-(s+' '+a).length]
```
This takes a string and an array of substrings to encode and returns a) the encoded string b) the list of potential next savings c) the number of bytes saved so far.
[Answer]
# ùîºùïäùïÑùïöùïü, 72 chars / 209 bytes
```
`Эć훼쎧漤詼媰਀㻆僚픈耊Ⓢኍ⋱쬝ᇑ덆䖇䂊՛樥첾㨭쯠ཁ톇:덱螟醮䖉⥊覂削ꇉ漈涹႘챘ඕ꼳⁒᭷Ừ䒕鶀놜㆝〢ﱱꎀ쎴䋈㗂䅉Ⴄቀ쳵菨ⶩ∉툲耀
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=false&input=&code=%60%D0%AD%C4%87%ED%9B%BC%EC%8E%A7%E6%BC%A4%E8%A9%BC%E5%AA%B0%E0%A8%80%E3%BB%86%EF%A6%BB%ED%94%88%E8%80%8A%E2%93%88%E1%8A%8D%E2%8B%B1%EC%AC%9D%E1%87%91%EB%8D%86%E4%96%87%E4%82%8A%D5%9B%E6%A8%A5%EF%8F%AA%EC%B2%BE%E3%A8%AD%EC%AF%A0%E0%BD%81%ED%86%87%3A%EB%8D%B1%E8%9E%9F%E9%86%AE%E4%96%89%E2%A5%8A%E8%A6%82%E5%89%8A%EA%87%89%E6%BC%88%E6%B6%B9%E1%82%98%EE%A0%96%EC%B1%98%E0%B6%95%EF%9D%96%EA%BC%B3%E2%81%92%E1%AD%B7%EE%A0%B0%E1%BB%AA%E4%92%95%E9%B6%80%EB%86%9C%EF%87%8D%EE%97%8D%E3%86%9D%E3%80%A2%EF%B1%B1%EA%8E%80%EC%8E%B4%E4%8B%88%E3%97%82%E4%85%89%E1%82%A4%E1%89%80%EC%B3%B5%E8%8F%A8%E2%B6%A9%EF%88%A0%E2%88%89%ED%88%B2%E8%80%80)`
Well, at least the char count is great, but we can't use the custom code page. It's just an LZString-decompression. I'm also working on another solution - more on that later.
[Answer]
# Perl 5, 286 bytes
`perl -M5.01 happy.pl`, where `happy.pl` is:
```
$_='u5u28 7_27u
~~x~~25 (7_)10u7x~~
~p_ ~~4_ 4_x4_x_3u4 5_3 4_x3_~px4_x4_~~
~u_)~|/ux~u \~u \4~ ~ 3_) /ux|/3_)x_)/ux)/ 3_)_|
~~x~( ( 8~p~~ ~|4-( ( ~p__ ~p( (/ /~~3u
p~xp|\_|p~|p/~|p/ \__x~ p6_)_|p(3_/ \3_)4_)_~xp|
14 p~xp~x(4_/';s/u/ _/g;s/\d+(.)/$1x$&/ge;s/x/ /g;s/~/| /g;s/p/|_/g;say
```
Thanks to [Dom Hastings](/users/9365/dom-hastings) (in a comment hereon) for an idea that saved me two bytes and led to another idea of mine that saved four more.
[Answer]
# Python 2, 159 bytes
This source contains non-printable characters, so it is presented as a hexdump that can be decoded with `xxd -r`.
```
00000000: efbb bf70 7269 6e74 2278 017d 8fb5 7540 ...print"x.}..u@
00000010: 3114 c5fa 3f85 4abb f240 012d a2dd 432f [[email protected]](/cdn-cgi/l/email-protection)/
00000020: 4cba c732 1302 20ff e0c0 dfc8 1501 e33f L..2.. ........?
00000030: 580e 9b77 e40b d115 2911 aa23 1c33 05a7 X..w....)..#.3..
00000040: cf54 6ae4 74c7 7310 baa3 8310 c86d 8c27 .Tj.t.s......m.'
00000050: 04ea 6656 9c79 9bfb a5fb 6cdd f6fe b5c5 ..fV.y....l.....
00000060: a2ef 3182 4875 56a4 123d 770f 2702 902b ..1.HuV..=w.'..+
00000070: 03b2 5bcb 28cf 985b 8520 876d b974 a6dc ..[.(..[. .m.t..
00000080: be28 20bb f842 f6ee a57a 1e01 c1a2 733e .( ..B...z....s>
00000090: 222e 6465 636f 6465 2827 7a69 7027 29 ".decode('zip')
```
[Answer]
# Racket, 367 364 bytes
```
(require file/gunzip net/base64)((λ(o)(gunzip-through-ports(open-input-bytes(base64-decode #"H4sIAOhN/lYAA31QwQ3EMAj7dwqezYuFInkRhj+MoWor9UBCmGBDMBhN8cMg+9dhR1hkovhhZwutO/FhSadQzqJQDdXkjsOYfa5Hkm4QEsp0ZeYkEdmeKK8i91GHazesgoyJEdfXzvR4O1ooOLY7oA8QunnfhDdCCSE2oogBV7QN7RhzI3bwYPWUUDXRj9fVpj439h/OlCKU1gEAAA=="))o)(displayln(get-output-string o)))(open-output-bytes))
```
### Ungolfed
```
(require file/gunzip net/base64)
((λ (o)
(gunzip-through-ports
(open-input-bytes
(base64-decode
#"H4sIAOhN/lYAA31QwQ3EMAj7dwqezYuFInkRhj+MoWor9UBCmGBDMBhN8cMg+9dhR1hkovhhZwutO/FhSadQzqJQDdXkjsOYfa5Hkm4QEsp0ZeYkEdmeKK8i91GHazesgoyJEdfXzvR4O1ooOLY7oA8QunnfhDdCCSE2oogBV7QN7RhzI3bwYPWUUDXRj9fVpj439h/OlCKU1gEAAA=="))
o)
(displayln (get-output-string o)))
(open-output-bytes))
```
[Based off a similar challenge I answered](https://codegolf.stackexchange.com/questions/53925/minecraft-mirrored/53947#53947).
[Answer]
# [///](http://esolangs.org/wiki////), ~~282~~ 279 bytes
Improvement: I noticed that there are too many `//` in the replacement commands, so I decided to compress them also (to `m`), which saved me 3 bytes.
```
/m/\/\///l/ _mk/|amj/b_mi/\\\m/h/|cmg/ddmf/ccme/bbmd/aamc/ |mb/__ma/ /ldlgggdejgggal
hafggga(ej)ga_gdah
hbf e eaea_alde_a eajh_aeaeh
kb)hilak_ \\k_ \\|fcakj) ila|ij)a_)ila)i j)_|
hac ( (ffffc_hahe( (fjf_( (i ihd_
|_kc_|\\_||_h|_ih|_i \\bak|ej)_||_(ji \\j)e)_kc_|
gda|_kc_k (ei
```
Repeatly compress the most frequent substring.
### Thirteenth generation, 282 bytes
```
/l/ _//k/|a//j/b_//i/\\\///h/|c//g/dd//f/cc//e/bb//d/aa//c/ |//b/__//a/ /ldlgggdejgggal
hafggga(ej)ga_gdah
hbf e eaea_alde_a eajh_aeaeh
kb)hilak_ \\k_ \\|fcakj) ila|ij)a_)ila)i j)_|
hac ( (ffffc_hahe( (fjf_( (i ihd_
|_kc_|\\_||_h|_ih|_i \\bak|ej)_||_(ji \\j)e)_kc_|
gda|_kc_k (ei
```
[Try it online!](http://slashes.tryitonline.net/#code=L2wvIF8vL2svfGEvL2ovYl8vL2kvXFxcLy8vaC98Yy8vZy9kZC8vZi9jYy8vZS9iYi8vZC9hYS8vYy8gfC8vYi9fXy8vYS8gIC9sZGxnZ2dkZWpnZ2dhbCAKaGFmZ2dnYShlailnYV9nZGFoCmhiZiBlIGVhZWFfYWxkZV9hIGVhamhfYWVhZWgKa2IpaGlsYWtfIFxca18gXFx8ZmNha2opIGlsYXxpailhXylpbGEpaSBqKV98CmhhYyAoIChmZmZmY19oYWhlKCAoZmpmXyggKGkgaWhkXyAKfF9rY198XFxffHxfaHxfaWh8X2kgXFxiYWt8ZWopX3x8XyhqaSBcXGopZSlfa2NffApnZGF8X2tjX2sgKGVp&input=)
### First generation, 486 bytes
No compression. Escaped the `/` and the `\`.
```
_ _ _______ _
| | | | (_______) _ | |
| |__ | | ____ ____ ____ _ _ _____ ____ ___| |_ ____ ____| |
| __)| |\/ _ | _ \\| _ \\| | | | | ___) \/ _ |\/___) _)\/ _ )\/ ___)_|
| | | ( ( | | | | | | | | |_| | | |____( ( | |___ | |_( (\/ \/| | _
|_| |_|\\_||_| ||_\/| ||_\/ \\__ | |_______)_||_(___\/ \\___)____)_| |_|
|_| |_| (____\/
```
[Try it online!](http://slashes.tryitonline.net/#code=IF8gICAgIF8gICAgICAgICAgICAgICAgICAgICAgICAgICAgX19fX19fXyAgICAgICAgICAgICAgICAgICAgICAgICAgIF8gCnwgfCAgIHwgfCAgICAgICAgICAgICAgICAgICAgICAgICAgKF9fX19fX18pICAgICAgICAgIF8gICAgICAgICAgICAgIHwgfAp8IHxfXyB8IHwgX19fXyBfX19fICBfX19fICBfICAgXyAgICBfX19fXyAgIF9fX18gIF9fX3wgfF8gIF9fX18gIF9fX198IHwKfCAgX18pfCB8XC8gXyAgfCAgXyBcXHwgIF8gXFx8IHwgfCB8ICB8ICBfX18pIFwvIF8gIHxcL19fXykgIF8pXC8gXyAgKVwvIF9fXylffAp8IHwgICB8ICggKCB8IHwgfCB8IHwgfCB8IHwgfF98IHwgIHwgfF9fX18oICggfCB8X19fIHwgfF8oIChcLyBcL3wgfCAgICBfIAp8X3wgICB8X3xcXF98fF98IHx8X1wvfCB8fF9cLyBcXF9fICB8ICB8X19fX19fXylffHxfKF9fX1wvIFxcX19fKV9fX18pX3wgICB8X3wKICAgICAgICAgICAgICB8X3wgICB8X3wgICAoX19fX1wv&input=)
### Second generation, 402 bytes
Compressed two spaces to `a`. The `/a/ /` means "replace all occurrences of `a` to two spaces".
```
/a/ / _aa _aaaaaaaaaaaaaa_______aaaaaaaaaaaaa _
| |a | |aaaaaaaaaaaaa(_______)aaaaa_aaaaaaa| |
| |__ | | ____ ____a____a_a _aa_____a ____a___| |_a____a____| |
|a__)| |\/ _a|a_ \\|a_ \\| | | |a|a___) \/ _a|\/___)a_)\/ _a)\/ ___)_|
| |a | ( ( | | | | | | | | |_| |a| |____( ( | |___ | |_( (\/ \/| |aa_
|_|a |_|\\_||_| ||_\/| ||_\/ \\__a|a|_______)_||_(___\/ \\___)____)_|a |_|
aaaaaaa|_|a |_|a (____\/
```
[Try it online!](http://slashes.tryitonline.net/#code=L2EvICAvIF9hYSBfYWFhYWFhYWFhYWFhYWFfX19fX19fYWFhYWFhYWFhYWFhYSBfIAp8IHxhIHwgfGFhYWFhYWFhYWFhYWEoX19fX19fXylhYWFhYV9hYWFhYWFhfCB8CnwgfF9fIHwgfCBfX19fIF9fX19hX19fX2FfYSBfYWFfX19fX2EgX19fX2FfX198IHxfYV9fX19hX19fX3wgfAp8YV9fKXwgfFwvIF9hfGFfIFxcfGFfIFxcfCB8IHwgfGF8YV9fXykgXC8gX2F8XC9fX18pYV8pXC8gX2EpXC8gX19fKV98CnwgfGEgfCAoICggfCB8IHwgfCB8IHwgfCB8IHxffCB8YXwgfF9fX18oICggfCB8X19fIHwgfF8oIChcLyBcL3wgfGFhXyAKfF98YSB8X3xcXF98fF98IHx8X1wvfCB8fF9cLyBcXF9fYXxhfF9fX19fX18pX3x8XyhfX19cLyBcXF9fXylfX19fKV98YSB8X3wKYWFhYWFhYXxffGEgfF98YSAoX19fX1wv&input=)
### Third generation, 369 bytes
Compressed `__` to `b`. The `/b/__/` at the beginning means "replace all occurrences of `b` to `__`".
```
/b/__//a/ / _aa _aaaaaaaaaaaaaabbb_aaaaaaaaaaaaa _
| |a | |aaaaaaaaaaaaa(bbb_)aaaaa_aaaaaaa| |
| |b | | bb bbabba_a _aabb_a bbab_| |_abbabb| |
|ab)| |\/ _a|a_ \\|a_ \\| | | |a|ab_) \/ _a|\/b_)a_)\/ _a)\/ b_)_|
| |a | ( ( | | | | | | | | |_| |a| |bb( ( | |b_ | |_( (\/ \/| |aa_
|_|a |_|\\_||_| ||_\/| ||_\/ \\ba|a|bbb_)_||_(b_\/ \\b_)bb)_|a |_|
aaaaaaa|_|a |_|a (bb\/
```
[Try it online!](http://slashes.tryitonline.net/#code=L2IvX18vL2EvICAvIF9hYSBfYWFhYWFhYWFhYWFhYWFiYmJfYWFhYWFhYWFhYWFhYSBfIAp8IHxhIHwgfGFhYWFhYWFhYWFhYWEoYmJiXylhYWFhYV9hYWFhYWFhfCB8CnwgfGIgfCB8IGJiIGJiYWJiYV9hIF9hYWJiX2EgYmJhYl98IHxfYWJiYWJifCB8CnxhYil8IHxcLyBfYXxhXyBcXHxhXyBcXHwgfCB8IHxhfGFiXykgXC8gX2F8XC9iXylhXylcLyBfYSlcLyBiXylffAp8IHxhIHwgKCAoIHwgfCB8IHwgfCB8IHwgfCB8X3wgfGF8IHxiYiggKCB8IHxiXyB8IHxfKCAoXC8gXC98IHxhYV8gCnxffGEgfF98XFxffHxffCB8fF9cL3wgfHxfXC8gXFxiYXxhfGJiYl8pX3x8XyhiX1wvIFxcYl8pYmIpX3xhIHxffAphYWFhYWFhfF98YSB8X3xhIChiYlwv&input=)
### Fourth generation, 339 bytes
Compressed `|` to `c`. The `/c/ |/` at the beginning means "replace all occurrences of `c` to `|`".
```
/c/ |//b/__//a/ / _aa _aaaaaaaaaaaaaabbb_aaaaaaaaaaaaa _
|caccaaaaaaaaaaaaa(bbb_)aaaaa_aaaaaaa|c
|cbcc bb bbabba_a _aabb_a bbab_|c_abbabb|c
|ab)|c\/ _a|a_ \\|a_ \\|ccca|ab_) \/ _a|\/b_)a_)\/ _a)\/ b_)_|
|cac ( (ccccccccc_|ca|cbb( (ccb_cc_( (\/ \/|caa_
|_|ac_|\\_||_|c|_\/|c|_\/ \\ba|a|bbb_)_||_(b_\/ \\b_)bb)_|ac_|
aaaaaaa|_|ac_|a (bb\/
```
[Try it online!](http://slashes.tryitonline.net/#code=L2MvIHwvL2IvX18vL2EvICAvIF9hYSBfYWFhYWFhYWFhYWFhYWFiYmJfYWFhYWFhYWFhYWFhYSBfIAp8Y2FjY2FhYWFhYWFhYWFhYWEoYmJiXylhYWFhYV9hYWFhYWFhfGMKfGNiY2MgYmIgYmJhYmJhX2EgX2FhYmJfYSBiYmFiX3xjX2FiYmFiYnxjCnxhYil8Y1wvIF9hfGFfIFxcfGFfIFxcfGNjY2F8YWJfKSBcLyBfYXxcL2JfKWFfKVwvIF9hKVwvIGJfKV98CnxjYWMgKCAoY2NjY2NjY2NjX3xjYXxjYmIoIChjY2JfY2NfKCAoXC8gXC98Y2FhXyAKfF98YWNffFxcX3x8X3xjfF9cL3xjfF9cLyBcXGJhfGF8YmJiXylffHxfKGJfXC8gXFxiXyliYilffGFjX3wKYWFhYWFhYXxffGFjX3xhIChiYlwv&input=)
### The rest of the compression rules
So, the list of compression rules:
* Compress two spaces to `a`.
* Compress `__` to `b`.
* Compress `|` to `c`.
* Compress `aa` to `d`.
* Compress `bb` to `e`.
* Compress `cc` to `f`.
* Compress `dd` to `g`.
* Compress `|c` to `h`.
* Compress `\/` to `i`. Both the `\` and the `/` in the rules are further escaped.
* Compress `b_` to `j`.
* Compress `|a` to `k`.
* Compress `_` to `l`.
* Compress `//` to `m`.
As you can see, there are overlapping compression rules. For example, `g` encodes `dd` which encodes `aaaa` which encodes 8 spaces.
[Answer]
# Python 2, ~~343~~ ~~328~~ 316 bytes
This solution uses no decompression functions or other imports.
```
o=""
for i in range(250):j=ord(")*I*yyQZyyI*(!+9!+yyA,Z-q*y9!+(!+2)!!B)B1B1*9*AJ9B1:!+*1B1B!+(+12-!+/)*1+1*).+1*).!!!+1+1:-)/)*1+/:-1*-/)*1-/):-*+(!+9!,),)!!!!!!!!+*!+1!+B,),)!+:)!+*,),/)/!+A*(+*+9+*+.*3*!3*/!3*/).21+1+Z-*3*,:/).:-B-*+9+*+(y9+*+9+*+9,B/(".replace("!","+)")[i])-40;o+="\n _|()\/"[j&7]*(j/8+1)
print o
```
Readable version:
```
DATA=(")*I*yyQZyyI*("
"!+9!+yyA,Z-q*y9!+("
"!+2)!!B)B1B1*9*AJ9B1:!+*1B1B!+("
"+12-!+/)*1+1*).+1*).!!!+1+1:-)/)*1+/:-1*-/)*1-/):-*+("
"!+9!,),)!!!!!!!!+*!+1!+B,),)!+:)!+*,),/)/!+A*("
"+*+9+*+.*3*!3*/!3*/).21+1+Z-*3*,:/).:-B-*+9+*+("
"y9+*+9+*+9,B/(").replace("!","+)")
SIZE=250
o=""
for i in range(SIZE):
j=ord(DATA[i])-40
o+="\n _|()\/"[j&7]*(j/8+1)
print o
```
Uses a version of run length encoding with 3 bits for a symbol from the set "\n \_|()/". The remainder of the byte is the length, but I have limited the length to 10 and manipulated it so that the results are printable characters that are valid in a python string without any escaping.
Replacing the string corresponding with "| " with a single character in the encoded data saves a few more bytes.
I removed the trailing spaces on lines 1 and 5, which may be bending the rules a bit, but seems practical.
This program generates the packed data:
```
message="""
_ _ _______ _
| | | | (_______) _ | |
| |__ | | ____ ____ ____ _ _ _____ ____ ___| |_ ____ ____| |
| __)| |/ _ | _ \| _ \| | | | | ___) / _ |/___) _)/ _ )/ ___)_|
| | | ( ( | | | | | | | | |_| | | |____( ( | |___ | |_( (/ /| | _
|_| |_|\_||_| ||_/| ||_/ \__ | |_______)_||_(___/ \___)____)_| |_|
|_| |_| (____/"""[1:]
size=len(message)
symbols="\n _|()\/"
i=0
encoded=""
while i<size:
count=0
while count<10 and i+count+1<size and message[i+count+1]==message[i]:
count+=1
n = symbols.find(message[i]) | count<<3
encoded+=chr(n+40)
i+=count+1
encoded_lines = encoded.replace("+)","!").split(chr(40))
for line in encoded_lines:
print line+chr(40)
print len(encoded)
```
[Answer]
## [Your Mom](https://github.com/tuxcrafting/your-mom) (non-competing), 331 bytes
Decode the string and decompress it using the Jelly compressor
```
'IF8KfCgpL1z/AQAAAQAAAAAAAAAAAAAAAAAAEREREAAAAAAAAAAAAAAAAAAQIwMAAwMAAAAAAAAAAAAAAAAAQREREVAAAAAAAQAAAAAAAAAwMjAxEDAwEREBERABERABAAEAABEREAAREQAREwMQAREQARETAyMAEVMDYBADABBzABBzAwMDADABEVBgEANhEVABVgEAVgERUTIwMAAwQEAwMDAwMDAwMDEwMAMDERFAQDAxEQMDFARgYwMAABAjEwADE3EzEwMxYwMxYHEQAwAxERERUTMUERYHERUREVEwADEyAAAAAAAAADEwADEwAEERFg=='`
```
[Answer]
# Python 3, 377 bytes
```
from re import*;i=0
r=r'2_.7_./ .|2.| .4_.\\. _._d|.( (.3_). _ .2|_. |2 ._| |.a| |./ _2 .|3 |_. 4_2 . | |.\n'
e='an5n28 t27jf3b26 (t)10n14bfub pcp2n3n4 5_3c3g_2c4gar u)q|erjorjo|bhr k e|/k2n)e)sk_|f3 qlbbbb |g2bplb3_b_ls/q|4ja|mo_iqi/qisou2h|t)_i(3_sokp)ma14 |m3 (p/'
for j in r.split('.'):e=sub(chr(117-i),j,e);i+=1
print(sub('(\d+)(.)',lambda x:int(x.group(1))*x.group(2),e))
```
similar to the javascript answer, used RLE plus a bunch of replacements for common substrings.
Think I went a bit over the top with the replacing stuff, probably didn't help that much but oh well.
[Answer]
# JavaScript (ES6), 354 bytes
Another attempt. Not as efficient as run length, unfortunately.
```
i=0,console.log(`1c1bt96zfx1!1n4ikabr1w5!1n4iut4kyue!krgqthnkpkem8!43tb4j2urme!8hwrsagny80!69dfowb7hvk!2xj89rpvcb2!23l14ken5i1!1xzn6ns7j78!1tzyivgb4h2!1yy885vts00!12du7km7f51!1lvpcyzgbfq!17nicizf8og0!1246xqebgb9!1n4j181hywz!`.replace(/\w+!/g,v=>parseInt(v,36).toString(4).replace(/./g,w=>"_ |"[w]||`
()
)/\\\\)//))/)/)
((((((//
\\//\\)(/\\))
(/`[i++])))
```
Stores a bunch of base-36 numbers in the first string, delimited by a `!` separator. Then replaces the numbers (along with the `!`) with the numbers' base-4 representations. Replaces all the 0's, 1's, and 2's in the base-4 number with `_`, ` `, and `|` respectively, and all the 3's are replaced with the elements in the second string sequentially.
[Answer]
# Python 3, 263 bytes
Initial pass using builtins.
```
from base64 import*
from zlib import*
print(decompress(a85decode(b"Gas1Y_%\"=:#lAfQT$<1I,'acT5E):N/+l.oQs`98(esP<+T'c!7p'"
b";rpgIeCXZQ&]8Z,D1U/2<LjGq-FIBH)'D@dH'FCjS[&_Wa(Y9N^<LMJiMJrGNuf@S=?GWT(W34:oA%hQ<"
b"thh3pT#pD4$L]LSa%IG!R,BiQaoor91d>uo0VEQs4+2O[m4o")).decode())
```
some extra quotes and linebreaks added to avoid horizontal scroll for display purposes only (not counted in score)
[Answer]
# CJam, 229
```
"3WPPEFXvN'vlFBse/cTD>.x:Na,Y&NJH^tZ%xL(NkYzo0Rq%BeV&Zl1T^2y69,W/QC4pL`nv<Jo$'Cq.'m2-3H#9teHi&<uyO>f V)D\E y'*]oGq*ODjQLyoS*GyM7;\Z.n6B;J@OyEaE!4'E5p5MOl^#[,ZtA;`jy,gTP^\;;i<A6^:k1%"' fm91b31b"}*+{~'NHIF\JLM
OGQK)(P/RST|_- \""f=~
```
No funky characters and no built-in compression :)
[Try it online](http://cjam.aditsu.net/#code=%223WPPEFXvN'vlFBse%2FcTD%3E.x%3ANa%2CY%26NJH%5EtZ%25xL(NkYzo0Rq%25BeV%26Zl1T%5E2y69%2CW%2FQC4pL%60nv%3CJo%24'Cq.'m2-3H%239teHi%26%3CuyO%3Ef%20V)D%5CE%20y'*%5DoGq*ODjQLyoS*GyM7%3B%5CZ.n6B%3BJ%40OyEaE!4'E5p5MOl%5E%23%5B%2CZtA%3B%60jy%2CgTP%5E%5C%3B%3Bi%3CA6%5E%3Ak1%25%22'%20fm91b31b%22%7D*%2B%7B~'NHIF%5CJLM%0AOGQK)(P%2FRST%7C_-%20%5C%22%22f%3D~)
[Answer]
# Lua, 353 bytes
Program:
```
a=(" _ 5_ 28_7 27_\n|~ 2~2 26(_7) 10_ 13~2\n|~_2~2 _4 _4 2_4 2_ 3_ 4_5 3_4 2_3|~_ 2_4 2_4|~\n| 2_2)|~/ _ ~ 2_ \\| 2_ \\|~3 ~ 2_3) / _ ~/_3) 2_)/ _ 2)/ _3)_|\n|~ 2~ ( (~9_|~ ~2_4( (~2_3~2_( (/ /|~ 4_\n|_| 2~_|\\_|2_|~|_/|~|_/ \\_2 ~ ~_7)_|2_(_3/ \\_3)_4)_| 2~_|\n 13~_| 2~_| 3(_4/"):gsub("(.)(%d+)",function(a,b)return a:rep(b)end):gsub("~"," |")print(a)
```
Thanks to @jrich for compression.
[Answer]
# Ruby, ~~271~~ ~~262~~ 248 bytes
```
require'zlib'
require'base64'
puts Zlib.inflate Base64.decode64'eJx1UMENxDAI+zMFz+bFQpG8CMMX46DeVWpQrJjYhGDp6e7Cj3VBaz0p/CvKbrWBLkStYHAcEH8uafqhUKE6rjoFTWS+BxWdZD9ShHrDakosju6oe7sq8h04hZLPHgX0AdLwODOBG8VOy0a2MRFC31CPOTOiggPrq6LKyW6vqU1+Zhx2A7NMZ9I'
```
[Try it here](https://repl.it/CAS6/4)
[Answer]
# [Vim](http://www.vim.org/docs.php), ~~374~~ ~~365~~ ~~326~~ ~~319~~ ~~313~~ [311 keystrokes](http://retina.tryitonline.net/#code=KDxbXjw-XSs-fC4p&input=OmltIEAgX19fPENSPgo6aW0gJSBffDxDUj4KYSBfIyMgXzxlc2M-MjhhIDxlc2M-eWw3YV88ZXNjPjI3cGFfIDxDUj4KfCEjISE8ZXNjPjI2cGEoPGVzYz43YV88ZXNjPmEpPGVzYz4xMHBhXzxlc2M-MTRwYXwhPENSPgp8IV9fISE8ZXNjPjNhIEBfPGVzYz5iaSA8ZXNjPkEjXyMgXyMjQF9fIyBAXyNAfCFfI0BfI0AlITxDUj4KfCNfXyl8IS8gXyAhI18gXHwjXyBcPGVzYz40YXwgPGVzYz5hISNAKSAvIF8gIS9AKSNfKS8gXyMpLyBAKSU8Q1I-CnwhIyEgKCAoPGVzYz45YSE8ZXNjPmElISAhIUBfKCAoISFAISFfKCAoLyAvfCEjI18gPENSPgp8JSMhJVwlfF88ZXNjPjJhfCF8Xy88ZXNjPmEgXF9fICEgITxlc2M-N2FfPGVzYz5hKSV8XyhALyBcQClAXyklIyElPENSPgo8ZXNjPjE0cGF8JSMhJSMgKEBfLzxlc2M-Cjolcy8hLyB8L2c8Q1I-Cjolcy8jLyAgL2c8Q1I-)
9 keystrokes thanks to [@Dr Green Eggs and Ham DJ](https://codegolf.stackexchange.com/users/31716/dr-green-eggs-and-ham-dj) .
```
:im @ ___<CR>
:im % _|<CR>
a _## _<esc>28a <esc>yl7a_<esc>27pa_ <CR>
|!#!!<esc>26pa(<esc>7a_<esc>a)<esc>10pa_<esc>14pa|!<CR>
|!__!!<esc>3a @_<esc>bi <esc>A#_# _##@__# @_#@|!_#@_#@%!<CR>
|#__)|!/ _ !#_ \|#_ \<esc>4a| <esc>a!#@) / _ !/@)#_)/ _#)/ @)%<CR>
|!#! ( (<esc>9a!<esc>a%! !!@_( (!!@!!_( (/ /|!##_ <CR>
|%#!%\%|_<esc>2a|!|_/<esc>a \__ ! !<esc>7a_<esc>a)%|_(@/ \@)@_)%#!%<CR>
<esc>14pa|%#!%# (@_/<esc>
:%s/!/ |/g<CR>
:%s/#/ /g<CR>
```
Probably can be golfed further by using `:nn`?
[Answer]
# Javascript (ES6) ~~464~~ 352 bytes
```
00000000 63 6f 6e 73 6f 6c 65 2e 6c 6f 67 28 60 08 09 28 |console.log(`..(|
00000010 09 c3 a0 39 c3 98 09 08 0f 0c 08 0c 18 0c 08 0c |...9............|
00000020 c3 90 0a 39 0e 50 09 70 0c 08 0c 0f 0c 08 0c 11 |...9.P.p........|
00000030 08 0c 08 0c 08 21 08 21 10 21 10 09 18 09 20 29 |.....!.!.!.... )|
00000040 18 21 10 19 0c 08 0c 09 10 21 10 21 0c 08 0c 0f |.!.......!.!....|
00000050 0c 10 11 0e 0c 08 0c 0a 08 09 10 0c 10 09 08 0c |................|
00000060 10 09 08 0c 08 0c 08 0c 08 0c 10 0c 10 19 0e 08 |................|
00000070 0a 08 09 10 0c 0a 19 0e 10 09 0e 0a 08 09 10 0e |................|
00000080 0a 08 19 0e 09 0c 0f 0c 08 0c 18 0c 08 0a 08 0a |................|
00000090 08 0c 08 0c 08 0c 08 0c 08 0c 08 0c 08 0c 08 0c |................|
000000a0 08 0c 09 0c 08 0c 10 0c 08 0c 21 0a 08 0a 08 0c |..........!.....|
000000b0 08 0c 19 08 0c 08 0c 09 0a 08 0a 08 0a 0c 08 0c |................|
000000c0 20 09 08 0f 0c 09 0c 18 0c 09 0c 09 14 09 0c 08 | ...............|
000000d0 14 09 0a 0c 08 14 09 0a 08 11 10 0c 10 0c 39 0e |..............9.|
000000e0 09 14 09 0a 19 0a 08 19 0e 21 0e 09 0c 18 0c 09 |.........!......|
000000f0 0c 0f 70 0c 09 0c 18 0c 09 0c 18 0a 21 60 2e 73 |..p.........!`.s|
00000100 70 6c 69 74 28 22 22 29 2e 6d 61 70 28 61 3d 3e |plit("").map(a=>|
00000110 61 2e 63 68 61 72 43 6f 64 65 41 74 28 29 29 2e |a.charCodeAt()).|
00000120 6d 61 70 28 61 3d 3e 41 72 72 61 79 28 28 61 3e |map(a=>Array((a>|
00000130 3e 33 29 2b 31 29 2e 6a 6f 69 6e 28 22 20 5f 2f |>3)+1).join(" _/|
00000140 5c 5c 7c 28 29 5c 6e 22 2e 73 70 6c 69 74 28 22 |\\|()\n".split("|
00000150 22 29 5b 61 26 37 5d 29 29 2e 6a 6f 69 6e 28 22 |")[a&7])).join("|
00000160 22 29 29 |"))|
```
[Try it here!](https://jsfiddle.net/omw2028d/3/)
[Answer]
# HTML, 482 481 475 bytes
```
<pre> _ _ _______ _
| | | | (_______) _ | |
| |__ | | ____ ____ ____ _ _ _____ ____ ___| |_ ____ ____| |
| __)| |/ _ | _ \| _ \| | | | | ___) / _ |/___) _)/ _ )/ ___)_|
| | | ( ( | | | | | | | | |_| | | |____( ( | |___ | |_( (/ /| | _
|_| |_|\_||_| ||_/| ||_/ \__ | |_______)_||_(___/ \___)____)_| |_|
|_| |_| (____/
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 171 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"_ |0/)(
\"•1æÆ&¢ÙDÿœƒ˜¶f
¬π‚àç[sa√éŒõ√û√ÄŒ∏¬∂\‚Äöe‚Äì8(¬¨≈°√¥on&{wŒ±Œª¬µ.cR≈Ω1¬∫W√®√≠√Ñ íŒ£ Œπ.√¨¬®Gt‚Ä∞?W–∏Œõ√Ü‚ÄU√£≈°W#—Ç√ä√∑¬¥¬•b‚Ñ¢¬¢,V¬ß¬Øl‚Ǩ√©√†√∏j√≤√ê√∏¬¨√´√§√á kƒÄT¬¨√Ä–Ω4p¬´¬™√ídŒ±√±√°y√õ√ܬ¶‚Äö@√∏‚Äò√ë‚Äö–∏u‚ÇÖ‚ÇÇQp>√∏√Æ√∑^‚İ–∏√ì7¬Ø√ì√á≈†@√Ñ√©S‚Ä¢9–≤√®J0‚Ķ :
```
[Try it online.](https://tio.run/##DZBLSwJRGIb3/orBQAzCRii6LMpFELTr6iIptGxRUUJFRC0Og2kERTktuhHOWKY5ZYrpsZDge5sWBYfpL5w/Ms3ueTcPL4/aH0@Ek67rX1QO1N7uoC/ml8wMo4hMgExcjeHT1r9zv7fUXPFRWx6dzG/FcSpucAcmODVjkl0nJdMHg2TZBhqbG4H9XVETH/QWWpqyO2F6j6KEZ6R/cqKgiHYIFpXGtyV7HY063BNlJLug8iwKthHt@tNwjBY16CEh0yaZPXP0SNV1qVkoIw@@ijrOwMlCBffIKmtfbMYbzOn0pahCT8gtixpqMPbgmanovYuAS3aJcw8dviO1Q6lpk6kRcLygtSCZ4XDoA1SFjqydjyCN8rTXYMipozShSlZUFGXYdf8B)
**Explanation:**
```
"_ |0/)(
\" "# Push string "_ |0/)(\n\"
•1æÆ&¢ÙDÿœƒ˜¶f
¬π‚àç[sa√éŒõ√û√ÄŒ∏¬∂\‚Äöe‚Äì8(¬¨≈°√¥on&{wŒ±Œª¬µ.cR≈Ω1¬∫W√®√≠√Ñ íŒ£ Œπ.√¨¬®Gt‚Ä∞?W–∏Œõ√Ü‚ÄU√£≈°W#—Ç√ä√∑¬¥¬•b‚Ñ¢¬¢,V¬ß¬Øl‚Ǩ√©√†√∏j√≤√ê√∏¬¨√´√§√á kƒÄT¬¨√Ä–Ω4p¬´¬™√ídŒ±√±√°y√õ√ܬ¶‚Äö@√∏‚Äò√ë‚Äö–∏u‚ÇÖ‚ÇÇQp>√∏√Æ√∑^‚İ–∏√ì7¬Ø√ì√á≈†@√Ñ√©S‚Ä¢
# Push compressed integer 1097503083536947704653792841425892054204805659502021445044262296065039856679486956980779201344195600186307613120325421519873972685660197036332437042797892085831181080642513349371962439499848029872306826792254102689695782393365417312419084231420872539225014767457254170199022042856591776594745757160095950475758150232076499909206475280246564765470414367938
9–≤ # Converted to Base-8 as list: [1,0,3,1,1,0,3,3,3,3,3,3,3,3,3,1,0,0,0,0,0,0,0,3,3,3,3,3,3,3,3,3,0,7,2,1,2,3,2,1,2,3,3,3,3,3,3,3,3,1,1,6,0,0,0,0,0,0,0,5,3,3,3,1,0,3,3,3,3,1,1,2,1,2,7,2,1,2,0,0,1,2,1,2,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,3,0,3,1,0,0,0,0,0,3,0,0,0,0,1,1,0,0,0,2,1,2,0,1,1,0,0,0,0,1,1,0,0,0,0,2,1,2,7,2,1,1,0,0,5,2,1,2,4,1,0,1,1,2,1,1,0,1,8,2,1,1,0,1,8,2,1,2,1,2,1,2,1,1,2,1,1,0,0,0,5,1,4,1,0,1,1,2,4,0,0,0,5,1,1,0,5,4,1,0,1,1,5,4,1,0,0,0,5,0,2,7,2,1,2,3,2,1,6,1,6,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,0,2,1,2,1,1,2,1,2,0,0,0,0,6,1,6,1,2,1,2,0,0,0,1,2,1,2,0,6,1,6,4,1,4,2,1,2,3,1,0,7,2,0,2,3,2,0,2,8,0,2,2,0,2,1,2,2,0,4,2,1,2,2,0,4,1,8,0,0,1,1,2,1,1,2,0,0,0,0,0,0,0,5,0,2,2,0,6,0,0,0,4,1,8,0,0,0,5,0,0,0,0,5,0,2,3,2,0,2,7,3,3,3,3,1,1,2,0,2,3,2,0,2,3,6,0,0,0,0,4]
è # Index each into the string
J # Join all characters together to a single string
0… : # Replace all "0" with " " (3 spaces)
# (and output the string implicitly as result)
```
[See this 05AB1E tip of mine (section *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compressed integer and Base-8 list work.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~280~~ 279 bytes
```
f(i){for(char*A=" _|/\\()\n",*s="H@@H.@#IA-@AWP@PP-@M#IF$@H'@BzBJABBIIHIAHIAH@H@@IIA@II@IQPAHIAHIQPW@IVPCAP@AT@AT#P@BHIFCAPKIFH^H@^HINzBB@BEE(BJBBPPIIEEBJIPPihCSP@@AWQ@PQLRQPJSPJCLAP@J#INRiIY`IqIINB@Jz'@JB@JB@MIY";i=*s>63?:*s++;s++)for(;i--&31;)printf("%c%c",A[*s&7],A[*s/8&7]);}
```
[Try it online!](https://tio.run/##HY9hT8JADIY/u19BNoG7wSSGRI0L2ivZcj1h6cBIiIiSJZP7ICLzE8hvnwfJ8@ZtmzdtWkSfRVHXpbDyUH7vRLFe7UI18Bvvf73FQsjFxu@G1cDXAPoKAlIRqBkDcwTjgNJL0G3APRqFSKRJnQAXJlJOQDmfR85nQC88VAzq2REwoKbU9U@U6qWGpaZsjwiYJAINIjNRkqAhZrseThnc3Rw4H01yNlM2w5FbZQLKJpbmH/RDlCGYfRsMnhjT3I/tIKwebvqP92HV6cRO8vRibKOo1b@O5XZnN7@l8JtFs/C76jWsWrdvZ@/duUrGx9oFGl8ruxHSO3gXpZCxd6z/AQ "C (gcc) – Try It Online")
## Rundown
We define an alphabet of 8 symbols, `" _|/\\()\n"`, and compress the data by packing two symbols per byte according to its index in the alphabet, with the first symbol in bits 0..2, and the second in 3..5. Bit 6 is set to bring the resulting byte into printable ASCII territory. A simple RLE is then run on the compressed string. If a symbol in the string occurs more than twice in a row, it is stored as a character pair, with the first containing the run-length plus 32 (bit 5 set) and the second the symbol itself.
```
f(i){ i is run-length; not actually passed to f()
for( Loop over compressed string.
char*A=" _|/\\()\n", Alphabet
*s="..."; Compressed string.
i=*s>63?:*s++; If char is outside symbol range, use as run-length and skip to next. Stop on EOS.
s++) Advance to next char.
for(;i--&31;) Repeat symbol pair per run-length.
printf("%c%c",A[*s&7],A[*s/8&7]); Extract symbols from character and print.
}
```
[Try it online!](https://tio.run/##HY9hT8JADIY/u19BNoG7wSSERI0L2ivZcj2BdGAkRETJksl9EHXzE8hvnwfJ8@ZtmzdtmkcfeV7XhbDyUHyVIt9uylAN/cbbX2@1EnK187thNfQ1gL6CgFQEasHAHMEkoPQSdBtwj0YhEmlSJ8CFiZQTUMbnkfMF0DOPFIN6cgQMqCl1/SOleq1hrWm6RwRMEoEGkZkoSdAQs92O5gzubgacjWcZmzmb0ditMgFNZ5aW7/RDNEUw@zYYPDGhpR/bYVjdXw8e@ndh1enETvL0Y2yjqDXox/K7tLvfQvjNvJn7XfUSVq2b17P3bl0l42PtAo3Pjd0J6R28i0LI2DvW/w "C (gcc) – Try It Online")
[Answer]
# Javascript ES6, 314 bytes
Contains unprintable bytes. Uses some black JS magic to run.
If `console.log()` is needed for this answer to be valid, the byte count will be 327.
```
[...`Ãm°Ûm¶Ûm¶Ûm¶Û\`��m¶Ûm¶Ûm¶Ûm�ç�±Çm¶Ûm¶Ûm¶Ûh���¶Ûm°Ûm¶Ûm�<â�8à�À�°�l6Ãm��m��\`�Äl����Ç��§��Ça�ØfqÇ��À�����»
°Ú¬� ó�Øé¦8ã�8ã� ã±Ä�&�â�Ç�4Y�vØnAÛ�X$�HG��\`lv �� ���0��
�Ø�öÛm¶Ûb�Ø�¶���`].map(a=>'0'.repeat(8-(z=a.charCodeAt().toString(2)).length)+z).join``.replace(/.{1,3}/g,a=>`_|/\\()
`[parseInt(a,2)]).slice(0,-2)
```
This was a huge pain to get right, and I couldn't manage to get rid of the `.slice(0,-2)` :(
Will edit in an explanation tomorrow when I'm less tired.
Replaced every single byte with the corresponding hex value in order for the code snippet to be able to run
```
f=_=>
[...`\xc3\x6d\xb0\xdb\x6d\xb6\xdb\x6d\xb6\xdb\x6d\xb6\xdb\x60\x00\x00\x6d\xb6\xdb\x6d\xb6\xdb\x6d\xb6\xdb\x6d\x86\xe7\x1d\xb1\xc7\x6d\xb6\xdb\x6d\xb6\xdb\x6d\xb6\xdb\x68\x00\x00\x0b\xb6\xdb\x6d\xb0\xdb\x6d\xb6\xdb\x6d\x8e\x3c\xe2\x06\x38\xe0\x00\xc0\x01\xb0\x00\x6c\x36\xc3\x6d\x80\x00\x6d\x80\x03\x60\x01\xc4\x6c\x00\x1b\x00\x01\xc7\x9d\x80\xa7\x15\x86\xc7\x61\x99\xd8\x66\x71\xc7\x1d\x8e\xc0\x0b\x96\x1b\x14\x00\xbb\x0a\xb0\xda\xac\x00\xa0\xf3\x8e\xd8\xe9\xa6\x38\xe3\x8e\x38\xe3\x8e\x20\xe3\xb1\xc4\x00\x26\x98\xe2\x00\xc7\x11\x34\x59\x1c\x76\xd8\x6e\x41\xdb\x10\x58\x24\x1c\x48\x47\x12\x16\x60\x6c\x76\x20\x00\x00\xa0\x91\x00\x0b\x30\x05\x00\x0a\x0e\xd8\x83\xf6\xdb\x6d\xb6\xdb\x62\x0e\xd8\x83\xb6\x80\x00\x80`].map(a=>'0'.repeat(8-(z=a.charCodeAt().toString(2)).length)+z).join``.replace(/.{1,3}/g,a=>`_|/\\()
`[parseInt(a,2)]).slice(0,-2)
a.innerHTML=f()
```
```
<pre id=a>
```
[Answer]
# JavaScript, ~~294~~ 292 bytes
```
_='_&3,,& *.,,&_ 7+&+,,-(*.)&&& _,-+7+__1 . .-.3&_& ._&.-*+_-.-.+7|3_)+2_43 b|3 \\+14-*) 2_4/*)3)2_-)2*)_|7+&| 51111 6+-+.51*1_52/+& _ 7|0\\_|6+6/+62\\__44*.)_|6(*2\\*).)07,40&(./,&&&&0_|&6|&- .*_*___1 ++| |3-_4-|- 2/ 5( (6|_7\n';for(Y in $='7652-43+1*.&0,')with(_.split($[Y]))_=join(pop());_
```
This... is literally just encoding of the art... with [this](https://268271.playcode.io)...
If `console.log()` is required, then byte count is ~~307~~305 bytes.
294->292, -2B for encoding `\n` to `7`.
] |
[Question]
[
Make a code that takes a list and a number as input, and generates all possible combinations with the length of the number. For example, with the list **{0,1}** and the number **2**:
```
00
01
10
11
```
**Your program doesn't have to expect characters twice or more often in the list, such as** *{0,0,0,0,0,1,1,5,5}*
**Make sure you print the combinations out sorted, in the order of the list:**
With the list **{0,1}** and the number **5** (generated by some of my code, which is a way too long to win):
```
00000
00001
00010
00011
00100
00101
00110
00111
01000
01001
01010
01011
01100
01101
01110
01111
10000
10001
10010
10011
10100
10101
10110
10111
11000
11001
11010
11011
11100
11101
11110
11111
```
**But with the list *{1,0}* and the number *2*:**
```
11
10
01
00
```
As you can see, reversed list means reversed order.
Take a look at the structure, it's like a tree.
This is code-golf, so the shortest code in bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 [byte](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṗ
```
**[TryItOnline](http://jelly.tryitonline.net/#code=4bmX&input=&args=WzAsMV0+NQ)**
Cartesian power built-in atom, as a dyadic link with left argument the items and right argument the count, or as a full program with first argument the items and second argument the count.
[Answer]
## Haskell, 20 bytes
```
(mapM id.).replicate
```
Usage exaple:
```
*Main> ( (mapM id.).replicate ) 2 "01"
["00","01","10","11"]
*Main> ( (mapM id.).replicate ) 2 "10"
["11","10","01","00"]
```
`replicate` makes `n` copies of the 2nd parameter and `mapM id` builds the combinations. Btw, `mapM id` is the same as `sequence`, but 1 byte less.
[Answer]
# [MATL](http://github.com/lmendo/MATL), 2 bytes
```
Z^
```
Cartesian power builtin...
[Try it online!](http://matl.tryitonline.net/#code=Wl4&input=WzAgMV0KNQ)
[Answer]
# Pyth, 2 bytes
```
^F
```
A program that takes input in the form `list,number` and prints a list of lists.
[Test suite](http://pyth.herokuapp.com/?code=%5EF&test_suite=1&test_suite_input=%5B0%2C1%5D%2C2%0A%5B0%2C1%5D%2C5%0A%5B1%2C0%5D%2C2&debug=0)
**How it works**
```
^F Program. Input: Q
^FQ Implicit input fill
F Fold
^ repeated Cartesian power
Q over Q
Implicitly print
```
[Answer]
# [Perl 6](https://perl6.org), 15 bytes
```
{[X] @^a xx$^b}
```
## Explanation:
```
{[X] @^a xx$^b}
{ } # bare block lambda
@^a # declare first parameter as Positional
$^b # declare second parameter
xx # list repeat 「@a」, 「$b」 times
# at this point given 「 (0,1), 5 」
# ((0 1) (0 1) (0 1) (0 1) (0 1))
[ ] # list reduce
X # using cross meta-operator
# results in a list of lists
# ((0 0 0 0 0)
# (0 0 0 0 1)
# (0 0 0 1 0)
# (0 0 0 1 1)
# (0 0 1 0 0)
# (0 0 1 0 1)
# ...
# (1 1 1 1 1))
```
```
say {[X] $^a xx$^b}( (0,1), 2 ); # ((0 0) (0 1) (1 0) (1 1))
say {[X] $^a xx$^b}( (1,0), 2 ); # ((1 1) (1 0) (0 1) (0 0))
say {[X] $^a xx$^b}( (0,1,2), 2 );
# ((0 0) (0 1) (0 2) (1 0) (1 1) (1 2) (2 0) (2 1) (2 2))
put {[X] $^a xx$^b}( (0,1), 5 )».join;
# 00000 00001 00010 00011 00100 00101 00110 00111 01000 01001 01010 01011 01100 01101 01110 01111 10000 10001 10010 10011 10100 10101 10110 10111 11000 11001 11010 11011 11100 11101 11110 11111
```
[Answer]
# JavaScript (Firefox 30+), 55 bytes
```
f=(a,n)=>n?[for(b of a)for(c of f(a,n-1))[b,...c]]:[[]]
```
I'm 99% certain recursion is the best way to go about this in JavaScript.
[Answer]
# Mathematica, 6 bytes
```
Tuples
```
Still worse than Jelly :(
# Usage
```
Tuples[{0, 1}, 5]
```
>
> `{{0, 0, 0, 0, 0}, {0, 0, 0, 0, 1}, {0, 0, 0, 1, 0}, {0, 0, 0, 1, 1}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 1}, {0, 0, 1, 1, 0}, {0, 0, 1, 1, 1}, {0, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {0, 1, 0, 1, 0}, {0, 1, 0, 1, 1}, {0, 1, 1, 0, 0}, {0, 1, 1, 0, 1}, {0, 1, 1, 1, 0}, {0, 1, 1, 1, 1}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 1, 0}, {1, 0, 0, 1, 1}, {1, 0, 1, 0, 0}, {1, 0, 1, 0, 1}, {1, 0, 1, 1, 0}, {1, 0, 1, 1, 1}, {1, 1, 0, 0, 0}, {1, 1, 0, 0, 1}, {1, 1, 0, 1, 0}, {1, 1, 0, 1, 1}, {1, 1, 1, 0, 0}, {1, 1, 1, 0, 1}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}}`
>
>
>
[Answer]
## Perl, 30 bytes
28 bytes of code + `-nl` flag.
```
$"=",";say for glob"{@F}"x<>
```
To run it:
```
perl -alE '$"=",";say for glob"{@F}"x<>' <<< "1 0
2"
```
I think that taking the input as a list of numbers is logical for Perl. However, if we allow some fantasy, and take the input with the brackets and comma (as shown in the question), we can go down to **20 bytes**:
```
perl -nlE 'say for glob$_ x<>' <<< "{1,0}
2"
```
**Explanations:**
`glob` initial purpose in Perl is list and iterate through filenames, but when its argument contains curly brackets, it generates combinations formed of one element of each bracket group.
`-a` autosplit on spaces the input, and put the result inside `@F` array.
`$"` is the list separator: it's the separator inserted between the elements of a list inside a string. We set it to `,`, so `"{@F"}` produces `{.,.}` (if `@F` contains 0 and 1).
Then `x` is the string repetition operator (and `<>` gets one line of input).
And finally, `say for` iterates through the list generated by `glob` and prints the elements.
[Answer]
# Python, 57 bytes
```
from itertools import*
lambda o,n:list(product(*([o]*n)))
```
**[repl.it](https://repl.it/EmhD)**
Unnamed function taking a list of objects, `o` and a count, `n` and returning a list of the combinations.
[Answer]
# Pure Bash, 36
```
printf -vv %$2s
eval echo ${v// /$1}
```
Input by command-line params - The list is a comma-separated list in braces, e.g.:
```
./elemcombo.sh "{0,1}" 2
```
Note the input list needs to be quoted so the calling shell does not expand it too early.
[Ideone](https://ideone.com/bZ1geQ).
[Answer]
# [R](https://www.r-project.org/), ~~53~~ 45 bytes
```
function(x,n)rev(expand.grid(rep(list(x),n)))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQidPsyi1TCO1oiAxL0UvvSgzRaMotUAjJ7O4RKNCEyirqfk/TcPAylDHVPM/AA "R – Try It Online")
`rev` is there to the conform with the precise sort order requested (which doesn't really seem essential to the problem) and adds 5 bytes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~2~~ 1 [byte~~s~~](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ã
```
-1 byte thanks to *@Emigna*.
[Try it online.](https://tio.run/##MzBNTDJM/f//8OL//025og10DGMB)
Input as `number\nlist`, output as list of lists.
**Explanation:**
```
# Implicit input `a`, `b`
ã # Take the Cartesian product of list `b` repeated `a` times
```
[Answer]
## Racket 123 bytes
```
(let p((s "")(l(map number->string(sort l <))))
(if(= n(string-length s))(displayln s)(for((i l))(p(string-append s i)l))))
```
Ungolfed:
```
(define(f l n)
(let loop ((s "")
(l (map number->string (sort l <))))
(if (= n (string-length s))
(displayln s)
(for ((i l))
(loop (string-append s i) l)))))
```
Testing:
```
(f '(0 1) 2)
(f '(0 1) 3)
(f '(0 1) 5)
```
Output:
```
00
01
10
11
000
001
010
011
100
101
110
111
00000
00001
00010
00011
00100
00101
00110
00111
01000
01001
01010
01011
01100
01101
01110
01111
10000
10001
10010
10011
10100
10101
10110
10111
11000
11001
11010
11011
11100
11101
11110
11111
```
[Answer]
# PHP, 109 bytes
```
for($o=$a=array_slice($argv,2);--$argv[1];$o=$c,$c=[])foreach($a as$n)foreach($o as$s)$c[]=$n.$s;print_r($o);
```
Takes the length as the first argument and the list as any further arguments.
Use like:
```
php -r "for($o=$a=array_slice($argv,2);--$argv[1];$o=$c,$c=[])foreach($a as$n)foreach($o as$s)$c[]=$n.$s;print_r($o);" 5 0 1
```
Will run into an "out of memory" fatal error if asked for length 0.
] |
[Question]
[
The [Prime Signature](https://en.wikipedia.org/wiki/Prime_signature) of a number is the list of the exponents of the prime factors of a number, sorted in descending order (exponents of `0` are ignored). Inspired by [Combo Class](https://www.youtube.com/@ComboClass)'s "[The Magnificent Patterns of Prime Signatures](https://youtu.be/2xLMhB_cTgc)" video.
For example, the prime factorization of `6860` is `2 * 2 * 5 * 7 * 7 * 7`, or `2^2 + 5^1 + 7^3`. The exponents are `2`, `1`, and `3`, so the Prime Signature is `{3, 2, 1}`
# I/O
You will be given an integer on the interval `[1, 10,000,000]`.
You must output an array/list/vector or a string (in the format below) of the input's prime signature.
# Examples/Test Cases
| Numbers | Signature |
| --- | --- |
| 1 | ∅ or {} |
| 2, 3, 5, 7, 11 | {1} |
| 4, 9, 25, 49, 121 | {2} |
| 6, 10, 14, 15, 21 | {1, 1} |
| 8, 27, 125, 343 | {3} |
| 12, 18, 20, 28 | {2, 1} |
| 16, 81, 625, 2401 | {4} |
| 24, 40, 54, 56 | {3, 1} |
| 30, 42, 66, 70 | {1, 1, 1} |
| 32, 243, 3125 | {5} |
| 36, 100, 196, 225 | {2, 2} |
| 12345 | {1, 1, 1} |
| 123456 | {6, 1, 1} |
| 1234567 | {1, 1} |
| 5174928 | {5, 4, 3} |
| 8388608 | {23} |
| 9999991 | {1} |
Note that these are not sets in the computer science sense because they can contain duplicate values and have an ordering (admittedly, some set implementations are ordered).
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the fewest bytes wins!
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 6 bytes
```
∨2⌷2⍭⊢
```
[Try it online!](https://tio.run/##TY4xbsMwDEX3nkIHkAGTkmV57pKuTS4QwHaXoMnQoZ0LBIFRB82QC2TKkCBLgO4@Ci/ifkkeIkDi1yM/yeVmldVfy9X6LWs@P5r3uqnHUXZnlp8/lv4q3WlsZfsr/V66b@kv0t@Hm5HtQfbH@esz3sXsZT62w1nRU3hZK6NVoVWpFSVktaq0YjCLSJyog8xxkSWkJuqhgjNUG2siI/SkkEA5@4Tg9qSVC3Vs82k2elkUFYiFi8jga@F3MJR5QhwsWNJgSiJxl7BMBcUTJTb2QbkHWUZdUGmraSFvvHd50lU89A8 "APL (Dyalog Extended) – Try It Online")
`∨` descending sort of…
`2⌷` the second row of…
`2⍭` the table of primes (in the first row) and their exponents (in the second row) of…
`⊢` the argument
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
_YFSP
```
Try at [**MATL Online**](https://matl.io/?code=_YFSP&inputs=5174928&version=22.7.4)!
### Explanation
```
_YF % Implicit input. Prime factor exponents without zeros
S % Sort
P % Flip. Implicit display
```
[Answer]
# [Factor](https://factorcode.org/) + `math.primes.factors`, 37 bytes
```
[ group-factors values [ >=< ] sort ]
```
[Try it online!](https://tio.run/##NczLCsIwEEbhfZ/ifwEDilLvW3HTjbgqXYQ4raVpEmamgk8fpeL6fJzWOo2c77drddljtPo0ifuRxLRzEViR6AQSWfvQ/UjkBzESk@r7y4NiIA7kcSiKzbJc71bbXKPjOKXF//OyfiJBjfPpiGb@ocnOeg@TPw "Factor – Try It Online")
* `group-factors` Get the prime factorization of an integer as an assoc where keys are factors and values are exponents.
* `values` Get the exponents.
* `[ >=< ] sort` Sort into descending order.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 27 bytes
```
n->-vecsort(-factor(n)[,2])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NVBbCsIwEETwIEu_WkigebRNP-xFikgoVgRpQ62CZ_GnIOIhvImncbalgTCzszO7Ic9P8MP5cArTq6Xd-za20n07Wcn7sbn2wxjL1jdjP8RdUgu9TxbHb7P1IVwesSdZURjO3QgacRFRG_skEVQrQVqQEZQJKgQp1FZQCRWCBSoNKQemuGgp6Cw5AAfYZ6xhhssqjBqoEHKcZYe2KW9C3qKdATO0DbhFLAcvwI1mD2aZZey8lveWYJolpY1dIV8Rz8hUYUve6oxzeQpSzketnzFNC_4B)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes
```
Nθ≔²ηW⊖θ¿﹪θη≦⊕η«≔⁰ζW¬﹪θη«≦⊕ζ≧÷ηθ»⊞υζ»≔⟦⟧ζW⁻υζF№υ⌈ι⊞ζ⌈ιIζ
```
[Try it online!](https://tio.run/##dY89T8MwEIZn51fceJaCBBUIUKaqXTqkqlgRg0nc@iTHbv1RUFF/u7GbAOrA6Pee5/Vdp4TrrNAprcw@hnUc3qXDA2@qufe0MzirQeXXhyItAZeyc3KQJsg@QxxoC9jaPmqLhwJyaMV@Mlfmlx07pPYSvio2zW9rOOWUTdVrG66reGHZP30X82/4QjsVMhGWdKReZr@GcgQ7V2wTvcI4Kuefs17fxmD6vCUT/Qhx2FoHuLDRhJK04pOGOCCVjS5dp6uwqTaOMroQPmDWm5Qe7h7vn2dP6eaovwE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input the integer.
```
≔²η
```
Start trial division at `2`.
```
W⊖θ¿﹪θη≦⊕η
```
Until the integer has been reduced to `1`, keep incrementing the trial divisor until it divides the integer.
```
«≔⁰ζW¬﹪θη«≦⊕ζ≧÷ηθ»⊞υζ»
```
Calculate the multiplicity of the trial divisor and push it to the predefined empty list.
```
≔⟦⟧ζW⁻υζF№υ⌈ι⊞ζ⌈ιIζ
```
Sort the list in descending order and output the result.
36 bytes by importing Python modules:
```
≔▷”8±J≧∕*}G⦃⬤t;⁼hsλ”NθI⮌▷SE▷listθ§θι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DtSwxJyyxSEOpuDK3oFIvryQjNb@oUi8tMbkkvygzr0RJRyHaM6@gtMSvNDcptUhDM1ZTR6FQ05orACSr4ZxYXKIRlFqWWlScimRWflFJagpIq29iAUI4J7MYbF4hyAzHEs@8lNQKjUIdhUxNoKlAYP3/v6mhuYmlkcV/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔▷”8±J≧∕*}G⦃⬤t;⁼hsλ”Nθ
```
Use `sympy.ntheory.factorint` to get a dictionary of prime factors and their multiplicities.
```
I⮌▷SE▷listθ§θι
```
Extract the multiplicities, sort them, and output the reversed result.
This can be reduced to 26 bytes if you run the latest version of Charcoal locally:
```
I⮌▷SE▷”8±J≧∕*}G⦃⬤t;⁼hsλ”Nι
```
Unfortunately you can't try this online because the version of Charcoal on TIO can't enumerate dictionaries and the version of Charcoal on ATO can't import `sympy`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
∆ǐsṘ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiIbHkHPhuZgiLCIiLCIxMjM0NTYiXQ==)
So uh turns out the prime exponents built-in doesn't include 0s by complete accident - it's not a bug, just a consequence of how it's implemented and a different understanding of what a prime exponents built-in should do lol.
## Explained
```
∆ǐsṘ
∆ǐ # prime exponents of the input
s # sorted
Ṙ # reversed
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), ~~6~~ ~~9~~ 8 bytes
```
Đϼ1\⇹ḋɔŞ
```
[Try it online!](https://tio.run/##ARgA5/9weXT//8SQz7wxXOKHueG4i8mUxZ7//zE "Pyt – Try It Online")
```
Đ implicit input (n); duplicate top of stack
ϼ get the unique prime factors of n
1\ remove any pesky 1s
⇹ḋ get the prime factors of n (with duplicates)
ɔ count the number of occurrences of each unique prime factor
Ş sort in descending order
```
[Answer]
# [Python](https://www.python.org), 71 bytes
`-4` bytes for both code segments thanks to `Neil`.
`-8` bytes thanks to `corvus_192`
```
lambda n:sorted(factorint(n).values())[::-1]
from sympy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NVDLboMwELzzFXuEyonwAzBIOfcj0hxoAwpSsBE4lfiWXJCi9p_6Lb10FhpL1oxnZ3atvX8Pc7h4tzymw9vXLbQ7-_N6rfv3c02umvwYmnPc1h_Bj50LsUv2n_X11kxxkhyraidPUTv6nqa5H-a9C5fGjzN1_YDgy3-739aP5KhzdJSClCAtKBNUCJJ4G0ElVAgGKBWkHJjioiShs2QBHGCfNpoZLqswKqBEyHKWHcqkPAl5g3IGzFDW4AaxHLwA14o96KW3tutYnluCKZak0uYJ-RPxjUwWpuSpVlubpyDleuSpioiGdVMTdpVE2wqWZcM_)
# [Python](https://www.python.org), 128 bytes
Uses a recursive helper [function](https://codegolf.stackexchange.com/a/152433/110265) to calculate the prime factors of a number.
Failed on the test cases `1234567, 9999991` due to `RecursionError: maximum recursion depth exceeded`
```
lambda n:sorted(Counter(f(n)).values())[::-1]
f=lambda n,i=2:n//i*[0]and f(n,i+1)if n%i else[i]+f(n//i)
from collections import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVDdSsMwGMXbPsXnhazZMtf8tGsLuxJ8idqL2qYY6JLSZOIQwffwZiD6Tvo0flkZGAjn5Hzn5IR8fI9H_2TN6dPtHr4Ovl_nP-9Ds3_sGjCls5NXXXxnD8arKe5jQ8jtczMclIsJqcpyzeqo3138VO94aTYbvaySujEdYIDqFSO6B3OjQQ1OVbpeoYwmEvWT3UNrh0G1XlvjQO9HbFzO7_i9Sns7gQFtoGIUOAVBIaWwpcDwLCkUqKIgERlHKUNMcOOIoR6kHCEEgk9IERjuoKKRIzIM5SEbHFwmoQnzEscpYopjgVxiLEO-RS548OBdYr72XBt6C2Q8SIwLeYHsgviMlG1lEVpzkedZgqQ4L1aXEYCfjgEAxkkbH7vw3XhWL60a_f9Jv7hv9KA6sAa8ch7axil4NW_XCxLNv3c6zfgH)
[Answer]
# [SageMath](https://doc.sagemath.org), 45 bytes
```
lambda n:sorted(e for p,e in factor(n))[::-1]
```
[Try it online!](https://sagecell.sagemath.org/?z=eJxdUNtqhDAQfRf8h3lLAlnYXLysYH_E9cG6kcq2KiYLS8V_7yRmW-hAMueczC0z1Nc0-ey-3m8dTJWdV2du1MAwr7BwA-MEQ9e7eaUTY01VnUSbJmnijHVQAxUcJAfNIedQchBIBEKJijrjQa5yryudRfeiecEhE4W-SEwsVVnmZwSXYIKliXkupsdhfJum5dAIf8mAsIT3KiiR6KBE4iMizGKQ_Kfnf_A3NHzlqKqOljhI_2H6u1n9HOT6kIXuCYeAhCL47lfljlV9jwv1q-Hwmp5VaQJoFtMH6tjBlnWcHB3I5nY4vcFmd9him8bWtWl3wn4AEbhkqA==&lang=sage&interacts=eJyLjgUAARUAuQ==)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 77 bytes
```
f=(n,i=2,w)=>n%i?n-!w?f(n,i+1).concat(w||[]).sort((a,b)=>b-a):[]:f(n/i,i,-~w)
```
[Try it online!](https://tio.run/##ZcqxDsIgFIXh3bdwMOFGwFDrYBPsgzQdKIK52kBTiCSm8dFFHByMZ/zOf1V3FfSMU2TOn03OVhJHUVY0gTy5DbaOrVNrP7gVwLV3WkWSlqXrgQc/R0IUHUo7MAVN1zcl3SFFyp4JcsmDHw0f/YVYIgBWv1L/iaj29aFofvkpYrkyC1HpGwv4MPL43Rs "JavaScript (Node.js) – Try It Online")
Thank Arnauld for -1 or real`[]`ify(was two solutions)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ÆE¹ƇṢU
```
[Try it online!](https://tio.run/##y0rNyan8//9wm@uhncfaH@5cFPr//38LYwsLMwMLAA "Jelly – Try It Online")
A port of my vyxal answer.
## Explained
```
ÆE¹ƇṢU
ÆE # Prime exponents of the input - contains 0s
¹Ƈ # so filter out those 0s
Ṣ # sort the list
U # and reverse it
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~58~~ ~~51~~ 47 bytes
```
@(n)-sort(-diff(find(diff([0 factor(n) n<2]))))
```
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI09Ttzi/qERDNyUzLU0jLTMvRQPMijZQSEtMLskvAqpQyLMxitUEgv9pGoZGxiamZpr/AQ)
### Explanation
```
@(n) % Define anonymous function
factor(n) % Prime factors of input
[0 % Prepend 0 and...
n<2] % ...postpend 1 if n<2, 0 otherwise
diff( ) % Consecutive differences
find( ) % Indices of nonzeros
diff( ) % Consecutive differences
-sort(- ) % Negate, sort, negate
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ó0K{R
```
[Try it online](https://tio.run/##yy9OTMpM/f//8GQD7@qg///NLMwMAA) or [verify all test cases](https://tio.run/##LY27DcJAEERbsRy/4PZz57vIBZCRIgKQCIgIkJAscgqAkuiERo4FeYMdzc7o7eV6OJ5P/bbM4/B5PIdxXvr7lTb3bafvBMXITIjgNDTjDVGhIAlxJBOuotGJ1NxCkTgktCKFGuVI1FPgHE9kJxcs4UopTAnTiAz7I37oYLeChhU1X3dZZSLL5C3w1WotqdL@E4/C7b8).
**Explanation:**
```
Ó # Get a list of the prime factorization of the (implicit) input-integer
0K # Remove all 0s
{ # Sort it (from lowest to highest)
R # Reverse it (from highest to lowest)
# (after which the result is output implicitly)
```
[Answer]
# [R](https://www.r-project.org), 71 bytes
```
f=\(n,m=2,l=0)`if`(n%%m,-sort(-c(if(l)l,if(n>1)f(n,m+1))),f(n/m,m,l+1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGq4sz0vMSS0qJU26WlJWm6Fjfd02xjNPJ0cm2NdHJsDTQTMtMSNPJUVXN1dIvzi0o0dJM1MtM0cjRzdIBUnp2hZhpIsbahpqamDpCpn6uTq5MD4kKNS4NboGGmqaCsYKhgyIUQMjQCiRmhiBmZgMSMgSqRBI0NoJpRlBqbQbQbcUFsW7AAQgMA)
Recursive function that directly calculates prime exponents, and sorts them on every recursive call (which is unneccessary except for the outermost call, so overflows the stack for large inputs).
---
# [R](https://www.r-project.org), ~~74~~ 67 bytes
*Edit: -7 bytes thanks to pajonk*
```
\(n,`?`=\(n,m)if(n>1)`if`(n%%m,n?m+1,c(m,n/m?m)))-sort(-table(n?2))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGq4sz0vMSS0qJU26WlJWm6FjedYzTydBLsE2xBdK5mZppGnp2hZkJmWoJGnqpqrk6efa62oU6yBpCln2ufq6mpqVucX1SioVuSmJSTqpFnb6SpCTVqT3JiiQbcAg0zTR2lmDwlTQVlBUMFQy5USUMjhKwRhqyRCULWGKgbTdrYAMVoDO3GZsiGG2FYbWxiiqTCDGwCxA8LFkBoAA)
Uses recursive helper function `?` to calculate prime factors, and then sorts their exponents a single time (and thus copes with much larger inputs, but at the expense of 3 more bytes of code).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 59 bytes
```
.+
$*
m(+`\A(1+)(\1)+$
$1¶$#2
(?=(¶.+))(\1)+$
¶$#2
1A`
O^#`
```
[Try it online!](https://tio.run/##NYwxbsJAEEX7dw0bac0itDO7HtZFhFxRcgGEnCIFBRQoZ/MBfDFnIEnxR1/z/3/Pr@/b43PdhNO07iPtlnuI02UMErtwkS62tLLMbaOE40dY5n3s/oPft4wT52szrcvMbhWUTKHHOFAZkIQI4sWC9IghFU2oVwvaowe0khPZp0ZJFKUM9E4xzDmJ6oTkIH2RHDIY@pqWTHbZ2ychv1PN5e8aNddqqf4A "Retina 0.8.2 – Try It Online") Outputs prime signature on separate lines but link is to test suite that joins on commas for convenience. Explanation:
```
.+
$*
```
Convert to unary.
```
m(`
```
Run the rest of the script in multiline mode where `$` matches at the end of any line.
```
+`\A(1+)(\1)+$
$1¶$#2
```
Repeatedly extract the smallest prime factor of the input number. (`$#2` is actually one less than the smallest prime factor but it's consistent and we only care about the multiplicities anyway.) As this is slow for large numbers the test suite omits some of the slower cases.
```
(?=(¶.+))(\1)+$
¶$#2
```
Get the multiplicities of each factor.
```
1A`
```
Remove the `1` remaining after all of the prime factors have been extracted.
```
O^#`
```
Sort the multiplicities in descending numeric order.
[Answer]
# [J](https://www.jsoftware.com), 12 bytes
```
__\:~@{:@q:]
```
Independently found, but essentially a port of [Adám's APL answer](https://codegolf.stackexchange.com/a/256150/110888). An exact port would be `1\:~@{__ q:]`, at 12 bytes as well.
[Attempt This Online!](https://ato.pxeger.com/run?1=LY-xSkNBEEV7v-JgYQyYsDM7u293gxIIWFlZG1IEH2IjglZCfiTNs7DzB-z8Df8mY14GZi4z93Jg9p_Pw8_5fNJz3ZhwRaB5z-as7u9uv97f-ln53mwe2m750ZavbT2e_n6nZ4_bpxcu-8VuPb24QVAiiQ4RjIomrCIqZCQghiR8K6hn3I0WXRE_BLQgmeJhd9SC4wwLJCNlYsCUnOkCUd2KxCPiH-3smlFfRaOdZj5JR5LOquNLLCWHQj2WjH8Mw6gH)
```
__\:~@{:@q:]
__ q:] NB. find prime exponents excluding zero
{:@ NB. take the tail of the result
\:~@ NB. descending sort the result
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
↔OmLgp
```
[Try it online!](https://tio.run/##yygtzv7//1HbFP9cn/SC////GxoZm5iaAQA "Husk – Try It Online")
```
p # get the prime factors
g # group identical elements
mL # get the length of each group
# (these are the prime exponents)
O # sort into ascending order
↔ # and reverse
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
-6 thanks to @Shaggy
```
k ü mÊñn
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ayD8IG3K8W4&input=Njg2MA)
```
k ü mÊñn
k Get the prime factors of the input
ü Group the factors to lists of the same element
mÊ Map each group to its length
ñn Sort them in descending order
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Gave Jacob my initial solution, so here's an alternative.
```
k òÎmÊÍÔ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ayDyzm3KzdQ&input=Njg2MA)
```
k òÎmÊÍÔ :Implicit input of integer
k :Prime factors
ò :Partition between elements where
Î : The sign of their differences is truthy (non-zero)
m :Map
Ê : Length
Í :Sort
Ô :Reverse
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 7 bytes
```
fCf:)-]
```
[Try it online!](https://tio.run/##LYy5CsJQEEX78ycWwpvlbbZ@hJWNkICQxkgq8dufY8gUc7kL57Gty/R@bdP4rM8xX@fL6Xwf39syBMXIVERwOprxjqhQkIQ4kgnX0NhEa26hSAQJbUihxTga9RQ4xxPZyQVLuFIKNWEalWE74o8Odi9oWFHz45dDKlmq98A3a62kRt9Pfg "Burlesque – Try It Online")
```
fC # Prime factors
f: # Count occurrences
)-] # Map-Take counts
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 5 \log\_{256}(96) \approx \$ 4.12 bytes
```
Zhwz;
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZLozLKq6whbKjQgmWGRsYmpmYQHgA)
#### Explanation
```
Zhwz; # Implicit input
Zh # Prime factor exponents
w # Without zeros
z; # Reverse-sorted
# Implicit output
```
[Answer]
# [Arturo](https://arturo-lang.io), 45 bytes
```
$=>[factors.prime&|tally|values|sort|reverse]
```
[Try it](http://arturo-lang.io/playground?3mO3XD)
[Answer]
# [Desmos](https://desmos.com/calculator), 97 bytes
```
A=[2...n]
P=A[∑_{N=3}^A0^{mod(A,N-1)}=0]
L=log_P(gcd(n,P^n))
F=L.sort[L.length...1]
f(n)=F[F>0]
```
[Try It On Desmos!](https://www.desmos.com/calculator/n93kmv3xwq)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/ctrilb7bf4)
This theoretically works for all inputs \$\le19998\$, but in reality, because of floating point issues, this only works for numbers up to around \$15\$ or so.
Below is a version that works for all numbers up to \$19998\$, at the cost of a few bytes:
### 133 bytes
```
A=join([1....5n],n)
P=A[∑_{N=2}^{floor(A^{.5})}0^{mod(A,N)}=0]
L=log_P(gcd(n,P^{floor(log_Pn)}))
F=L.sort[L.length...1]
f(n)=F[F>0]
```
[Try It On Desmos!](https://www.desmos.com/calculator/12zffc7pyg)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/vgwvdmqoo6)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
òT║≥Q{U
```
[Run and debug it](https://staxlang.xyz/#p=9554baf2517b55&i=6860&m=2)
This is a packed stax program which unpacks to the following 8 bytes:
```
|n0-or|u
```
[Run and debug it](https://staxlang.xyz/#c=%7Cn0-or%7Cu&i=6860&m=2)
# Explanation
```
|n # list of prime exponents
0- # remove 0s
o # sort
r # reverse
|u # uneval (print array as array)
```
[Answer]
# Mathematica, 38 bytes
Golfed vesrion, [try it online!](https://tio.run/##y00syUjNTSzJTE78/z/NNii1LLWoONUhOL@oJNonsbhE38EtMbkkv8gzryQ1PbXIQTlW7X9atJmFmUGsvn5AUWZeyX8A)
```
f=Reverse@Sort[Last/@FactorInteger@#]&
```
Ungolfed version
```
PrimeSignature[n_Integer] := Module[{factorization, exponents},
factorization = FactorInteger[n];
exponents = Last /@ factorization;
Sort[exponents]//Reverse
]
PrimeSignature[6860]//Print
```
] |
[Question]
[
Given a string of parentheses `(` and `)`, find the length of the longest substring that forms a valid pair of parentheses.
Valid pairs of parentheses are defined as the following:
An empty string is a valid pair of parentheses.
If `s` is a valid pair of parentheses, then `(s)` is also a valid pair of parentheses.
If `s` and `t` are both valid pairs of parentheses, then `st` is also a valid pair of parentheses.
For example, the longest valid substring of `(()())` is `(()())`, with length 6.
Write a function or program that takes a string of parentheses as input and outputs the length of the longest valid substring.
Example:
Input: `(()())`
Output: `6`
Input: `)()())`
Output: `4`
Input: `()(())`
Output: `6`
Input: `()(()`
Output: `2`
Input: `))`
Output: `0`
Input:
Output: `0`
Code golf rules:
Write a function or program that takes a string of parentheses as input and outputs the length of the longest valid substring, using as few characters as possible.
The score of your solution will be the number of characters in your code. The solution with the shortest code wins. In case of ties, the earlier submission wins.
You can assume the input string contains only the characters `(` and `)`.
[Answer]
# Excel (ms365), 136 bytes
[](https://i.stack.imgur.com/ATgRk.png)
Formula in `B1`:
```
=LET(x,ROW(A:A),y,SCAN(")"&A1,x,LAMBDA(a,b,SUBSTITUTE(a,"("&REPT("|",(b-1)*2)&")",REPT("|",b*2)))),MAX(ISNUMBER(FIND(REPT("|",x),y))*x))
```
The idea here is that we create a loop to iteratively replace the fundamental base of balanced paranthesis, "()". The 1st replacement is simply "||". Next we replace all occurences of "(||)", with "||||" etc, untill we can't replace any more. Finally we calculate the longest occurence of consecutive "|" characters.
Yes, 136 bytes is a lot though!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 75 bytes
```
s=>[...s].map((c,i)=>q=(p=c>'('?i-a.pop():a.push(i+~p)*0)>q?p:q,q=p=a=[])|q
```
[Try it online!](https://tio.run/##fczBCoJAFAXQfV8hbnyvdJSIFsIbP0RcDJOWYc6bplpFvz4NChEG3c1dHO49q4dy@trzLRvNofUdeUeyFkK4RlwUA@i0R5KWgEnLBJKqz5Rgw4Bl6Ls7Qb95Ma4LlLbi0qaWmBTVDT6t12Z0ZmjFYI7QQQyAgBgjRnke7VcLxW/dLTXgn@2kcTTr9uc5UMisxVIn@6h/Aw "JavaScript (Node.js) – Try It Online")
Or [71 bytes](https://tio.run/##hc1BCoMwEAXQfU8hbpxpNUopXQiJBykuJMY2RczE1C579TQVoRQCnc1f/Mefe/fsnJw1PYrJ9MoP3DsuLowx17JZ9YtUADaXuUYugLgUGWSNLhwjQ4B1yMXdQB9ehPsKhW2otjnxCr00kzOjYqO5wgCfyRQAATFtEZOyTM67CMEfcoqRIP6trCRNNnKMPgp9uI1UMbKCL/Fv) if we take input as array of characters.
Let us denote the input sting as `s`. Let use denote the length of longest valid parentheses string which ends by `s[i]` as `d[i]`. Then question is asking for the greatest value in array `d`.
* If `s[i]` is `(`, `d[i]` is `0`
+ It is trivial, as the last `(` does not have a matching `)` and therefore be invalid.
* If `s[i]` is `)`, we first find out the matching `(` for it
+ If there is no matching `(` for it, `d[i]` is `0`
+ If `s[j]` is some `(` character which match `s[i]`, then `s[j..i]` is a valid parentheses string. And `d[i]=i-j+1+d[j-1]`.
To find out matching `(` for `s[i]`, we use a stack named `a` in the source code, and push `j-1-d[j-1]` into it.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 46 bytes [SBCS](https://github.com/abrudz/SBCS)
```
(⌈/≢¨×{0(∧.≤∧=∘⊃∘⌽)+\-⌿'()'∘.=⍵}¨)⍤⊃⍳∘≢,.(,/)⊂
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=03jU06H/qHPRoRWHp1cbaDzqWK73qHMJkLJ91DHjUVcziOzZq6kdo/uoZ7@6hqY6UEDP9lHv1tpDKzQf9S4BKendDFLVuUhHT0NHX/NRVxMA&f=e9Q39VHbhDQFdQ0NTQ1NTXUurkcwEU0MEaAANhEUTZrqAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
```
⊃⍳∘≢,.(,/)⊂ substrings
{0(∧.≤∧=∘⊃∘⌽)+\-⌿'()'∘.=⍵}¨ map balanced?
≢¨× times lengths
‚åà/ max
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
ǎ~øβÞGL
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwix45+w7jOssOeR0wiLCIiLCIoKCkoKSlcbikoKSgpKVxuKCkoKVxuKCkoKClcbikpXG5cIlwiIl0=)
## Explained
```
ǎ~øβÞGL
«é # substrings of the input
~øβ # with only those with balanced brackets kept
√ûGL # get the length of the longest substring that remains
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 30 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{0‚åଥ‚àæ1+/¬®0(=‚àß‚àß`¬®‚àò‚â§)+`¬®‚Üì¬Ø1‚ãÜùï©-@}
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHsw4oyIwrTiiL4xKy/CqDAoPeKIp+KIp2DCqOKImOKJpCkrYMKo4oaTwq8x4ouG8J2VqS1AfQoKPuKLiOKfnEbCqCDin6giKCgpKCkpIiwgIikoKSgpKSIsICIoKSgoKSkiLCAiKCkoKCkiLCAiKSkiLCAiIuKfqQ==)
`¬Ø1‚ãÜùï©-@` Map `(` to 1 and `)` to ¬Ø1.
`+`¨↓` Take the cumulative sum of each suffix.
`0(=∧∧`¨∘≤)` For each value in each suffix, is it equal to 0 and are all preceding values non-negative?
`∾1+/¨` All 1-based indices of 1s.
`0⌈´` Take the maximum or 0 if there is no such index.
[Answer]
# JavaScript (ES6), 95 bytes
```
f=(s,S=s)=>s!=(s=s.split`()`.join``)?f(s,S):s?Math.max(f(S.slice(1)),f(S.slice(0,-1))):S.length
```
[Try it online!](https://tio.run/##fczBDoIwDAbgu0@BnNoEBhrjgWTyBJ54gS04YGRuxC7Gt58TEjWY2FPbr39HeZfU3vTkc@suKoSOA2UNJ@Qn2saeE6PJaC8ABRudtkJg3b1usKL6LP3ArvIBHTSMjG4V7BCzz1RmeVxg1TCjbO@H0DpLzihmXB9DKQACYoqYFEVy3KwUv/Ww1oh/srOmyaL7n8@RYi1arnW2t4Yn "JavaScript (Node.js) – Try It Online")
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 30 bytes
```
{m:g/(\(<~~>\))*/>>.chars.max}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzrXKl1fI0bDpq7OLkZTU0vfzk4vOSOxqFgvN7Gi9n9xYqWCHlBlWn6RQk5mXmrxfw0NTQ1NTS5NCAUk4RQXkMEFAA "Raku – Try It Online")
Uses a recursive regex to find all sets of balanced parenthesis, then takes the maximum length of those strings.
### Explanation
```
{ } # Anonymous codeblock
m:g/ / # Find all non-overlapping matches in string
( )* # Zero or more of
\( \) # Literal brackets
<~~> # Containing balanced parenthesises
>>.chars # Map to length of string
.max # Maximum
```
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 135 bytes
```
0:i:0(?v$6p1+00. ;n+1-~~.?&52~\
@$:@02.\~~1-:0>:
>0&:6g2%2*1-&+:0(?v&1-$:@$:@)?^22.
>1+$1+$:{:})?v$d1.
.1f0v!?:-1-$/ .55/
^~~~ \0n;
```
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMDppOjAoP3YkNnAxKzAwLiA7bisxLX5+Lj8mNTJ+XFxcbkAkOkAwMi5cXH5+MS06MD46XG4+MCY6NmcyJTIqMS0mKzowKD92JjEtJDpAJDpAKT9eMjIuXG4+MSskMSskOns6fSk/diRkMS4gICBcbiAuMWYwdiE/Oi0xLSQvIC41NS9cbl5+fn4gXFwwbjsiLCJpbnB1dCI6IikpKCgpKCkpKCIsInN0YWNrIjoiIiwic3RhY2tfZm9ybWF0IjoibnVtYmVycyIsImlucHV0X2Zvcm1hdCI6ImNoYXJzIn0=)
[](https://i.stack.imgur.com/T9F5g.png)
Uses the classic paste the input on the source block for easy indexing trick
[Answer]
# [J](http://jsoftware.com/), 35 34 bytes
```
[:>./@,(#*''-:#rplc&('()';'')])\\.
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63s9PQddDSUtdTVda2UiwpyktU01DU01a3V1TVjNWNi9P5rcvk56SmgKkRVF2cVD1LJlZqcka@QpqCuoaGpoampDudrovGBXEw@knIQuyKzBOhwz7yC0hIrBYiBCv6lJWCuGRdMQhNVwgQuAbECiw6wBFzcCGESQtDgPwA "J – Try It Online")
*-1 thanks to ovs*
* For every every substring...
* Continually replace `()` with the empty string
* If the result is the empty string, return the length, otherwise 0
* Max of all results
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
≈í í‚Äû()√µ:√µQ}√©Œ∏g
```
[Try it online](https://tio.run/##ASUA2v9vc2FiaWX//8WSypLigJ4oKcO1OsO1UX3Dqc64Z///KCkoKCkp) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5NOTXrUME9D8/BWq8NbA2sPrzy3I/2/zv9oJQ0NTQ1NTSUdBSVNOAvIQGaBJcGkUiwA)
**Explanation:**
```
Œ # Get all substrings of the (implicit) input
í # Filter it by:
„() # Push string "()"
õ: # Keep replacing "()" with "" until it's no longer possible
õQ # Check if what remains is an empty string ""
}é # After the filter: sort the remaining strings by length
θ # Pop and keep the last/longest
g # Pop and push its length
# (which is output implicitly as result)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 39 bytes
```
M!`((\()|(?<-2>\)))+(?(2)^)
.
.
O^`
\G.
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w31cxQUMjRkOzRsPeRtfILkZTU1Nbw17DSDNOk0sPCP3jErhi3PX@/9fQ0NTQ1OTShFBAEk5xARkA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
M!`((\()|(?<-2>\)))+(?(2)^)
```
Find all nontrival substrings of balanced parentheses, using .NET's balancing groups; `?<-2>` prevents the number of matched `)`s from exceeding the number of `(`s seen so far, while the `?(2)` ensures that there are no unmatched `(`s.
```
.
.
```
Take the length of each substring in unary.
```
O^`
```
Sort in reverse order.
```
\G.
```
Output the first length or `0` if there were no matches.
[Answer]
# JavaScript, 130 bytes
```
s=>[...s,0].map((_,i,a)=>a.map((_,j,$,S=s.slice(i,j),b=0)=>{for(l of S)if((l==')'?--b:++b)<0)break;r=b|r>(l=S.length)?r:l}),r=0)|r
```
Try it:
```
f=s=>[...s,0].map((_,i,a)=>a.map((_,j,$,S=s.slice(i,j),b=0)=>{for(l of S)if((l==')'?--b:++b)<0)break;r=b|r>(l=S.length)?r:l}),r=0)|r
;[
'(()())', // 6
')()())', // 4
'()(())', // 6
'()(()', // 2
'))', // 0
'', // 0
].forEach(s=>console.log(f(s)))
```
**Algorithm**:
Take the all substrings of string and check if it is balanced parentheses. If yes, then check if the length of substring is maximum? If yes then update the max value. Else don't change the max value
[Answer]
# vim, 72 bytes
```
o:s/(\(a*\))/a\1a/g<C-v><CR>@"<ESC>v0dk@":s/[()]/<C-v><CR>/g
:g/^/.!wc -c
:%!sort -nr
jdG<C-x>
```
## Annotated
```
o:s/(\(a*\))/a\1a/g<C-v><CR>@"<ESC> # insert command that recursively replaces (a*) with aa*a as long as there are matches
v0dk@" # pulls the above command into register " and invokes it. (Any resemblance to the word "vodka" is entirely coincidental.)
:s/[()]/<C-v><CR>/g # Any parentheses that remain are invalid. Split the string into separate lines with them as delimiters
:g/^/.!wc -c # strlen of each line (including newline)
:%!sort -nr # put the largest number on top
jdG<C-x> # delete the rest, decrement the newline away
```
`<C-v>` is 0x16, `<C-x>` is 0x18 `<ESC>` is 0x1b, and `<CR>` is 0x0d.
[Try it online!](https://tio.run/##K/v/P9@qWF8jRiNRK0ZTUz8xxjBRP12My0FJuswgJdtBCSgZraEZqy/GpZ/OZZWuH6evp1ierKCbzGWlqlicX1SioJtXxJWV4i7x/7@mBghqgEhNDQA "vim – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Outputs `undefined` instead of `0` (pending confirmation).
```
ã ke"%(%)" mÊÍ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4yBrZSIlKCUpIiBtys0&input=IigpKCgpKSI)
## 9 bytes
This version takes input as a string of `1`s & `0`s, representing `(` & `)` respectively, which the comments on the challenge would seem to allow.
```
ã keA mÊÍ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&header=ciIlKCIxIHIiJSkiVA&code=4yBrZUEgbcrN&input=IigpKCgpKSI)
```
ã ke"%(%)" mÊÍ :Implcit input of string
√£ :Substrings
k :Remove items that return truthy (non-empty string)
e : Recursively replace
"%(%)" : RegEx /\(\)/ (or A=10, in the second version)
m :Map
Ê : Length
Í :Sort
:Implicit out output of last element
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 16 bytes
```
qe7%3%∫:çlR≥¤#aṀ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FjsKU81VjVUfday2Orw8J-hR59JDS5QTH-5sWFKclFwMVbTgppaShoamhqamEpeSJowBpJEYIBkQoQTRAgA)
```
qe7%3%∫:çlR≥¤#aṀ
q Non-deterministically choose a contiguous subsequence
e7%3% Convert the subsequence to a list of 2's and 0's
‚à´ Take the cumsum
: Duplicate
çl Prepend 0 and get the last item
R Range from 1 to this number
≥¤ Compare the cumsum and this range;
fail if the two list has different length,
or if any item in the cumsum is less than
the corresponding item in the range
# Get the length
a Get all possible values
Ṁ Get the maximum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ẆœṣØ(F$ÐLÐḟẈṀ
```
[Try it online!](https://tio.run/##y0rNyan8///hrrajkx/uXHx4hoabyuEJPocnPNwx/@Gujoc7G/4fbj866eHOGZqR//8raWoAoaaSjoKSBjILQoFIkAIlAA "Jelly – Try It Online")
Uses [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s [05AB1E algorithm](https://codegolf.stackexchange.com/a/258524/66833), be sure to give them an upvote!
## How it works
```
ẆœṣØ(F$ÐLÐḟẈṀ - Main link. Takes a string S on the left
Ẇ - All contiguous sublists of S
Ðḟ - Filter sublists, keeping those which return [] under:
$ - Group the last 2 links as a monad f(W):
√ò( - Yield "()"
œṣ - Split W on "()"
F - Flatten
ÐL - Repeatedly apply f(W) until a fixed point
Ẉ - Lengths of those remaining
Ṁ - Maximum
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
⊞υ⁰≔⮌υθFS«≦⊕υ≡ι(⊞υ⁰¿∧⊟υυ⊞θ⌊υ⊞υ⁰»I⌈θ
```
[Try it online!](https://tio.run/##VY69CoMwFIVn8xQXpxuw0Fkn6eQgSPsEIV41oFHzYwvFZ09D6NCuh@@c78hJGLmKOYTO2wl9AVdesdpaNWq800HGEnpewB7jYTWAjd68ezij9Iicw5tlrdi@hUZLQwtpR30BPjYy@1ROToAqkVJYghzzEn5tWU@D8LMrQQ2Ate6xW7ck9VGQyL2AVmm1@CXmvAKa49DfxslO1sVTDm/COmzFK9E7j3gIyBF5uBzzBw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⁰
```
Start with no characters at the current indent level.
```
≔⮌υθ
```
Also start with a maximum balanced run length of zero.
```
FS«
```
Loop over the input characters.
```
≦⊕υ
```
Increase the characters at all depths.
```
≡ι(⊞υ⁰
```
If this is a `(` then start a new depth level. Otherwise:
```
¿∧⊟υυ
```
Remove a depth level, and if there is still at least one level left, then...
```
⊞θ⌊υ
```
... push the length of the deepest level left to the list of found balanced substring lengths, otherwise...
```
⊞υ⁰
```
.. the `)` was unbalanced, so start a new empty indent level.
```
»I⌈θ
```
Output the maximum balanced substring length found.
[Answer]
# [Scala](https://scala-lang.org/), 242 bytes
I first know `replaceAllLiterally` in scala, it saved several bytes.
---
Golfed version, [try it online!](https://tio.run/##fZAxa8MwFIT3/IpXTXpgnKSUDg4eMnQopEtNp9JBdWRb4Vk2kig1Rr/dlexSUgzRJN13d3CypSAxdZ8XWTp4EUrDOJ1lBdWe26xwRukas2ft8rHiNrHoDzP9g0nx36UCusttamRPopRHopNy0giigTOOLGEMMXbddCQFeklWQqxLdaef2t4NOH4JApKVy4v0bLr@VdWN43s8RN3Exy@IWitck7bim4cpMYNJuMwmXMrHIiWpa9d4P20A4q42fAAXprYZHI0Rw/uy7QMzeNPKQQ5jcAL0QXWkYzXjHDliWAXbLTyuMF7jh3Ua@a30jBks@H5dHlg4C96t8Ayvsd/46Qc)
```
def f1(s:String):Int={f(s,s)};def f(s:String,S:String):Int={if(s!=s.replaceAllLiterally("()","")){f(s.replaceAllLiterally("()",""),S)}else if(s.nonEmpty){val left=S.dropRight(1);val right=S.drop(1);math.max(f1(left),f1(right))}else{S.length}}
```
Ungolfed version, [try it online!](https://tio.run/##fZDNSsQwFEb3fYprVvdC6TgiLgZmMQsXgm4srsRF7KQ/kqYlCWIZ@uw1aaZmpDCBQMg5uV/7mYJLPk3d55coLLzwRsEpATiKEsotmh3kVjeqoh08KQt7OJVoUkPj4kQlhXw5QtSdB9CUgAZu9mAyLXrJC3GQ8rmxQnMpB2RILAXGiM4@@LnXVZdGszuCkEaEiEx16rHt7RAHfXMJUpT@W/LsqLv@talqi1u64Npf/QmRtdzWWct/0DXhZ7hQd5pt@he@hOWZFKqydWCJ3@eeWlcscl25tg5a8@E9FPXhinpTTWyqd7dWKp/IEAmJfCubDTysMF3i@/VrwmuvZ8wg4Lv1cMfcCvh2hVn434jHZJymXw)
```
object Main {
def f1(s: String): Int = {f(s,s)}
def f(s: String, S: String ): Int = {
if (s != s.replaceAllLiterally("()", "")) {
f(s.replaceAllLiterally("()", ""), S)
} else if (s.nonEmpty) {
val left = S.dropRight(1)
val right = S.drop(1)
math.max(f1(left), f1(right))
} else {
S.length
}
}
def main(args: Array[String]): Unit = {
println(f1("(()())")) // 6
println(f1(")()())")) // 4
println(f1("()(())")) // 6
println(f1("()(()" )) // 2
println(f1("))" )) // 0
println(f1("" )) // 0
}
}
```
] |
[Question]
[
Related: [Iterated phi(n) function](https://math.stackexchange.com/q/2550437).
Your challenge is to compute the iterated phi function:
```
f(n) = number of iterations of φ for n to reach 1.
```
Where `φ` is [Euler's totient function](https://en.wikipedia.org/wiki/Euler%27s_totient_function).
Related [OEIS](http://oeis.org/A003434).
Here's the graph of it:
[](https://i.stack.imgur.com/mfoP5.jpg)
---
### Rules:
Your goal is to output `f(n)` from `n=2` to `n=100`.
This is code-golf, so shortest code wins.
Here's the values you can check against:
```
1, 2, 2, 3, 2, 3, 3, 3, 3, 4, 3, 4, 3, 4, 4, 5, 3, 4, 4, 4, 4, 5, 4, 5, 4, 4, 4, 5, 4, 5, 5, 5, 5, 5, 4, 5, 4, 5, 5, 6, 4, 5, 5, 5, 5, 6, 5, 5, 5, 6, 5, 6, 4, 6, 5, 5, 5, 6, 5, 6, 5, 5, 6, 6, 5, 6, 6, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 5, 6, 7, 5, 7, 5, 6, 6, 7, 5, 6, 6, 6, 6, 6, 6, 7, 5, 6, 6
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~53~~ 52 bytes
Thanks nimi for saving 1 byte!
```
f<$>[2..100]
f 1=0
f n=1+f(sum[1|1<-gcd n<$>[1..n]])
```
[Try it online!](https://tio.run/##FcqxDkAwEADQ3VfcYCCi6ZnVj9ChKUWcS6Nsvt1hedNbXNomIiEzSGjzrm@UQq1tFgCN/mSDVSjStfd4Y1vPfgT@HyrF1payu5XBQDxWPiEHkscHcnOS2sf4Ag "Haskell – Try It Online")
`sum[1|1<-gcd n<$>[1..n]]` gives `φ(n)` (Taken from [flawr](https://codegolf.stackexchange.com/a/149870/71256), thanks!)
`f` is a recursive function that calculates `1+φ(n)` if n is not `1`, and outputs `0` if `n` is `1`, as there are no more iterations to be taken to reach `1`
Finally `f<$>[2..100]` creates a list of `f` applied to each element of `[2..100]`
[Answer]
# [Haskell](https://www.haskell.org/), ~~70 69~~ 68 bytes
The function `(\n->sum[1|1<-gcd n<$>[1..n]])` is the totient function, which we repeatedly apply in the anonymous function. Thanks @laikoni for -1 byte!
EDIT: I just found out @xnor used this exact totient function in a [previous challenge](https://codegolf.stackexchange.com/a/83634/24877).
```
length.fst.span(>1).iterate(\n->sum[1|1<-gcd n<$>[1..n]])<$>[2..100]
```
[Try it online!](https://tio.run/##rcwxDoAgDADAr3RwgIHGOiMfUQaiqERsjNTNv2P8g9tNt4Wyx5xrNSZHXmXDpQiWM7BypDFJvIJENbJx5T4GesiadZqBbeMGQmTv9ccOkdrW1yMkhh7OK7FAA7@cLw "Haskell – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes
```
99:Q"@`_Zptq}x@
```
[Try it online!](https://tio.run/##y00syfn/39LSKlDJISE@qqCksLbC4f9/AA "MATL – Try It Online")
### Explanation
```
99: % Push [1 2 ... 99]
Q % Add 1 element-wise: gives [2 3 ... 100]
" % For each k in that array
@ % Push k
` % Do...while
_Zp % Euler's totient function
tq % Duplicate, subtract 1. This is the loop condition
} % Finally (execute on loop exit)
x % Delete
@ % Push latest k
% End (implicit)
% End (implicit)
% Display stack (implicit)
```
## Old version, 16 bytes
```
99:Qt"t_Zp]v&X<q
```
[Try it online!](https://tio.run/##y00syfn/39LSKrBEqSQ@qiC2TC3CpvD/fwA "MATL – Try It Online")
### Explanation
```
99: % Push [1 2 ... 99]
Q % Add 1 element-wise: gives [1 2 ... 100]
t" % Duplicate. For each (i.e. do the following 100 times)
t % Duplicate
_Zp % Euler's totient function, element-wise
] % End
v % Concatenate vertically. Gives a 100×100 matrix
&X< % Row index of the first minimizing entry for each column.
% The minimum is guaranteed to be 1, because the number of
% iterations is more than sufficient.
q % Subtract 1. Display stack (implicit)
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~50~~ ~~29~~ 25 bytes
Look 'ma, no built-in totient!
*4 bytes saved thanks to @H.PWiz*
```
{⍵=1:0⋄1+∇+/1=⍵∨⍳⍵}¨1+⍳99
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE6of9W61NbQyeNTdYqj9qKNdW9/QFij0qGPFo97NQEbtoRVA8d7Nlpb//wMA)
**How?**
*Apparently I went for the longer (and harder) totient formula first. See revisions history.*
`⍳⍵` - `1` to `n`
`⍵∨` - gcd with `n`
`1=` - equal to 1?
`+/` - sum 'em all
This is the totient. All the rest is wrapper for the counting (`1+∇`) and applying on the range `2..100` (`¨1+⍳99`).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ ~~11~~ ~~10~~ ~~9~~ 8 bytes
```
³ḊÆṪƬ>1S
```
[Try it online!](https://tio.run/##y0rNyan8///Q5oc7ug63Pdy56tgaO8Pg//8B "Jelly – Try It Online")
-1 byte thanks to HyperNeutrino!
-1 byte thanks to Mr. Xcoder!
-1 byte thanks to Dennis
## How it works
```
³ḊÆṪƬ>1S - Main link. No arguments
³ - Yield 100
Ḋ - Dequeue. Creates the list [2, 3 ... 99, 100]
Ƭ - Until the following produces a repeated value, collecting each loop:
ÆṪ - Totient of each
>1 - Greater than one?
S - Sum the columns
```
[Answer]
# Mathematica, 44 bytes
```
(i=-1;#+1//.x_:>EulerPhi[++i;x];i)&~Array~99
```
-10 bytes from @Misha Lavrov
-2 bytes from @user202729
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPTVtfQWlnbUF9fryLeys61NCe1KCAjM1pbO9O6ItY6U1OtzrGoKLGyztLyf0BRZl6JQ9p/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# J REPL, 23 bytes
```
<:#@(5&p:^:a:)"0|2+i.99
```
I haven’t checked, but this probably works in regular J if you define it as a noun (I golfed this on my phone on the REPL).
Built-ins, yo.
I’d say that there are *at least* 2-3 bytes to shave off (off-by-one because of the way `a:` works, having to use `|` as a noop, etc.).
[Answer]
# JavaScript (ES6), ~~115~~ ... ~~104~~ 99 bytes
Hard-coding might be shorter, but let's try a purely mathematical approach.
```
f=n=>n>97?6:(P=(n,s=0)=>k--?P(n,s+(C=(a,b)=>b?C(b,a%b):a<2)(n,k)):s>1?1+P(k=s):1)(k=n+2)+' '+f(-~n)
console.log(f())
```
[Answer]
# [Python 2](https://docs.python.org/2/), 80 bytes
```
n,_=r=2,0;exec'r+=r[sum(k/n*k%n>n-2for k in range(n*n))]+1,;print r[n];n+=1;'*99
```
[Try it online!](https://tio.run/##BcHRDkAgGAbQV@nGUBl1Zy0vYmZmoTWf9svG0@ec@KXjgs4ZcrZkteyMe91akrA03s9ZhRY8FBjQ6O0iFpgHowW7q8BR15NQ0kTySIxGTAbCKlPyvs/5Bw "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 82 bytes
```
l=0,1
exec"n=len(l);p=2\nwhile n%p:p+=1\nl+=l[p-1]+l[n/p]-n%4%3/2,;print l[n];"*99
```
[Try it online!](https://tio.run/##DcjRCkAwFAbge08htcKIjRvWeRJ2pRV1@p20wtOP7/KTN@4nbEpMfWOy8IStAHFAyZUTsivu/eCQQ8ksmswK1sSLtMZrXtCJb6FGNXS2cXIdiPm/3hX1NKX0AQ "Python 2 – Try It Online")
This uses the observations that:
* `f(a*b) = f(a) + f(b) - 1`, except the `-1` is omitted if `a` and `b` are both even
* `f(p) = f(p-1) + 1` when `p` is prime, with `f(2)=1`
These imply that if `n` has prime factorization `n = 2**a * 3**b * 5**c * 7**d * 11**e * ...`, then `f(n) = max(a,1) + b + 2*c + 2*d + 3*e + ...`, where each `p>2` in the factorization contributes `f(p-1)`.
I'm not sure if these continue to hold past `n=100`, but if they do, they give a way to define and calculate `f` without using `φ`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~10~~ 17 bytes
```
mö←LU¡Sȯṁε⌋ḣtḣ100
```
[Try it online!](https://tio.run/##yygtzv7/P/fwtkdtE3xCDy0MPrH@4c7Gc1sf9XQ/3LG4BIgNDQz@/wcA "Husk – Try It Online")
**Edit**: +7 bytes for actually mapping the function over the range that was asked for, before it was only the function computing [A003434](https://oeis.org/A003434).
### Explanation
The following computes [A003434](https://oeis.org/A003434):
```
←LU¡S(ṁ(ε⌋))ḣ -- takes a number as input, for example: 39
¡ -- iterate the following function on the input: [39,24,8,4,2,1,1,1..]
S( )ḣ -- with itself (x) and the range [1..x]..
ṁ( ) -- ..map and sum the following
ε⌋ -- 0 if gcd not 1 else 1
U -- longest unique prefix: [39,24,8,4,2,1]
L -- length: 6
← -- decrement: 5
```
The `m(....)ḣ100` part just map that function over the range [2..100], not sure how I missed that part before :S
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 49 bytes
```
00000000: 5d88 0511 0020 0003 ab2c 024e ff64 e8a3 ].... ...,.N.d..
00000010: 379f 956b f05d 206c 0545 7274 743a b876 7..k.] l.Ertt:.v
00000020: 2267 27f9 9f4d 9b9d fc85 e7e6 994d 6eb0 "g'..M.......Mn.
00000030: 2b +
```
[Try it online!](https://tio.run/##jY47DgIxDER7TjGioQBZXufjhJ4SbkCxJgkFnwIB11@CgJ4njYuR5sn2MDvX4@MyTfxljVBSAodhALNwP@wwmhzA4itaix41jQ7YUwc9K9pRIZp9DEN3OM0NOURD41AgHPs8@AAV9VDvRljSCCjRifY40@Z2v6/p@XVId4hEhWjLyM0XZMsF7ZACqtaInHsXqzEwPy6ItvRhe/394d4Ow38sp@kF "Bubblegum – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 110 bytes
```
$a=,0*101;2..100|%{$i=$_;for($z=$j=0;++$j-lt$i;$z+=$k-eq1){for($k=$j;$j%$k-or$i%$k;$k--){}};($a[$i]=$a[$z]+1)}
```
[Try it online!](https://tio.run/##HYrRCgIhFAV/5iysmYu318v9klhiH4x0BcuCQPPbzXqaYZh7erv8vLkYe8cmR3sgS3xaFrL2M1V4wYWvKc8ogiCWtUYw8QXPKFqwG/cgVf/HPg5GmEZMGX6QhxpVW@MZ2xl@lR/Kqkm13r8 "PowerShell – Try It Online")
Mathematical approach.
Actually, looking through it, very similar to the [C answer](https://codegolf.stackexchange.com/a/149936/42963), but developed independently. Creates an array of `0`s, loops from `2` to `100`, then calculates `phi` using the `gcd` formulation. The part in parens at the end both saves the result into `$a` for the next go-round, and places a copy on the pipeline, which results in the implicit output.
---
### PowerShell, 112 bytes
```
"122323333434344534444545444545555545455645555655565646555656556656665656565656656757566756666667566"-split'(.)'
```
[Try it online!](https://tio.run/##NYZBCoAwDAT/0kv1oGCbpi8qKAQsVvD5cRN0NzObfj7tGnsTUQ1bSjllhKxUAIy6Lb7sPztM30Kw8RdXS8UaFtuwjC7HHad1jqov "PowerShell – Try It Online")
Hard-coded. Ho-hum. ~~Shorter than I could get a mathematical approach by about 10-15 bytes.~~
[Answer]
# [Python 2](https://docs.python.org/2/), 83 bytes
```
n=2
exec"print len(bin(n))-3+n%2-~n%9/8-(0x951a5fddc040419d4005<<19>>n&1);n+=1;"*99
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WiCu1IjVZqaAoM69EISc1TyMpM08jT1NT11g7T9VIty5P1VLfQlfDoMLS1DDRNC0lJdnAxMDE0DLFxMDA1MbG0NLOLk/NUNM6T9vW0FpJy9Ly/38A "Python 2 – Try It Online")
Combines a heuristic estimate with a hardcoded constant that corrects each estimate as either `-0` or `-1`.
[Answer]
# PHP, 98 bytes
```
1,2,<?=join(',',str_split(unpack('H*','##3444E4DEEDEEUUEEVEUVUVVFUVVUfVfVVVVVegWVgVffgV')[1]))?>,6
```
[Try it online!](https://tio.run/##K8go@P/fUMdIx8beNis/M09DXUddp7ikKL64ICezRKM0ryAxOVtD3UMLKK6sbGxiYuJq4uLqCkShoa6uYa6hYaFhYW5AHJoWlhYGAqnp4WHpYWlp6WHqmtGGsZqa9nY6Zv//AwA "PHP – Try It Online")
I packed all digits into a binary string.
After unpacking it, converting it to a an array and then mergin the array again, i only had to prepend the 1,2 and append the 6 as those wouldnt fit or caused a control code to appear.
[Answer]
# [Perl 6](http://perl6.org/), 47 bytes
```
map {($_,{+grep 1==* gcd $_,^$_}...1)-1},2..200
```
[Try it online!](https://tio.run/##K0gtyjH7r/E/N7FAoVpDJV6nWju9KLVAwdDWVkshPTlFASgUpxJfq6enZ6ipa1irY6SnZ2Rg8F9TLys/M09DSUdBSVOvOLHyPwA "Perl 6 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
тL¦ε[DNs#sÕ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//YpPPoWXntka7@BUrFx@e@v8/AA "05AB1E – Try It Online")
**Explanation**
```
тL¦ # push range [2 ... 100]
ε # apply to each
[ # start a loop
D # duplicate the current number
N # push the loop iteration counter
s # swap one copy of the current number to the top of the stack
# # if true, break the loop
s # swap the second copy of the current number to the top of the stack
Õ # calculate eulers totient
```
[Answer]
# C, 112 bytes
```
a[101];f(i,j,k,t){for(a[i=1]=0;i++<100;printf("%d ",a[i]=a[t]+1))for(t=j=0;++j<i;t+=k==1)for(k=j;j%k||i%k;k--);}
```
Ungolfed:
```
a[101];
f(i,j,k,t){
for(a[1]=0,i=2;i<=100;i++) { // initialize
for(t=j=0;++j<i;t+=k==1) // count gcd(i, j) == 1 (t = phi(i))
for(k=j;j%k||i%k;k--); // calculate k = gcd(i, j)
printf("%d ",a[i]=a[t]+1); // print and store results
}
}
```
[Try it online!](https://tio.run/##HY1BCsMgEEWvUgIBZRSc9WROIi7EYhmHpiW4a3p2a7r87z34xT9KGSNHDJioGnHNqev2U1@HyVEYEwcSgA1DoPche69mWe@3xU2bOMeeAK298s5ttgBtE@rAyox/rtyorXqesiqp95a@45llN/PFXOMH "C (gcc) – Try It Online")
[Answer]
# [Alumin](https://github.com/ConorOBrien-Foxx/Alumin), 87 bytes
```
hhhhhdadtqdhcpkkmzyhqkhwzydqhhwdrdhhhwrysrshhwqdrybpkshehhhwrysrarhcpkksyhaydhehycpkkmr
```
[Try it online!](https://tio.run/##NYxRCoAwDEPPOo0QqZO1VUZ3@ToF8xN4j6Qcd93PTL5BwaXg2kTqCKqwj4CSHYbpu4Wbz1ZYLE2c20@LfTMPlsDE8Z1Y5gM "Alumin – Try It Online")
## Explanation
```
hhhhhdadt CONSTANT 100
RANGE FROM 100 to 0
q
dhc
p
REMOVE 0 AND 1
kk
OVER EACH ELEMENT...
m
zyh
q
kh
wzyd
q
DUPLICATE TOP TWO ELEMENTS...
hhwdrdhhhwrysrshhw
GCD...
qdryb
p
ks
he
hhhw
ry
s
rarhc
p
IS IT ONE? IF SO TERMINATE (FIXPOINT)
kksyhaydhehyc
p
kk
m
REVERSE THE VALUES
r
```
[Answer]
# Pyth, 38 bytes (not competitive)
```
.e-+1sl+1kb_jC"Éõ4ÕYHø\\uÊáÛ÷â¿"3
```
[Try it on the Pyth Herokuapp](http://pyth.herokuapp.com/?code=.e-%2B1sl%2B1kb_jC%22%0F%C3%89%C3%B5%C2%854%C3%95Y%16H%C3%B8%5C%5Cu%C2%91%07%C3%8A%C3%A1%C3%9B%C3%B7%C3%A2%C2%BF%223&debug=0), because it doesn't work on TIO for whatever reason.
I have no doubt the explicit Pyth solution is smaller, but I wanted to see how small I could get the code by compressing the sequence, and learn Pyth I guess. This uses the fact that an upper bound of the sequence is `log2(n)+1`.
## Explanation
```
.e-+1sl+1kb_jC"Éõ4ÕYHø\\uÊáÛ÷â¿"3
C"Éõ4ÕYHø\\uÊáÛ÷â¿" interpret string as base 256 integer
j 3 convert to array of base 3 digits
_ invert sequence (original had leading 0s)
.e map with enumeration (k=index, b=element)
+1k k+1
sl floor(log( ))
+1 +1
- b -b
```
I got the compressed string via `Ci_.e+1-sl+1ksb"122323333434344534444545444545555545455645555655565646555656556656665656565656656757566756666667566"3`, which is just the opposite of the code above with a few type conversions.
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 41 bytes
```
“ ‽W3>€þΣÌιZ§Á HgüυH§u·β}Bā€ΣNπáÂUõÚ,3“8B
```
[Try it online!](https://tio.run/##AU0Asv9vaG0y///igJwg4oC9VzM@4oKsw77Oo8OMzrlawqfDgSBIZ8O8z4VIwqd1wrfOsn1CxIHigqzOo07PgMOhw4JVw7XDmiwz4oCcOEL//w "Ohm v2 – Try It Online")
Literally completely hardcoded... I actually took the sequence above, stripped everything that wasn't a number, interpreted it as base 8, then turned it into Ohm's built-in base 255 number representation. That's what the quotes do. Then, the program simply turns that into base 8 again.
] |
[Question]
[
You might know Alan Walker from his ever popular song Faded. Now his "followers" are called Walkers and they have a logo, here is a simplified version:
```
\\
\\ //\\
\\ // \\ //
\\ // \\ //
\\ // \\ //
\\ // \\ //
\\ // \\ //
\\ // //\\ \\ //
\\// // \\ \\//
// // \\ \\
//\\ // \\ //\\
\\// \\// \\
\\
```
The goal of this challenge is to print this logo.
**RULES:**
1. If you return a list of strings from a function as per meta standards, please provide a footer that prints it to the screen.
2. All characters of the above logo have to be there. No shortcuts!
3. Shortest number of bytes wins!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~31~~ ~~30~~ ~~29~~ 27 bytes
```
F²«Jι⁰↙χ↖↖⁵↙↙⁵↖↖²P↖χ↙↗χ↘↘¹²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw0hToZqL06s0tyAkXyNTR8FA05qLM6AoM69Ew8olvzzPJzWtREfBECzsm1@WqmEVWgASQ1IGEdBRMEWogenEapgpEWYZgdWU5pRkFqBKILsEiy2hBUGZ6RlY1IGF0ZwDUwqyrPb///@6Zf91i3MA "Charcoal – Try It Online") Link is to verbose version of code. Sadly `Copy` doesn't do what I want in this case, so I have to loop instead. Explanation:
```
F²«Jι⁰
```
Draw everything twice, but with the cursor starting one character to the right the second time.
```
↙χ↖↖⁵↙↙⁵↖↖²P↖χ
```
Draw the main W from right to left, but leave the cursor near the inverted V.
```
↙↗χ↘↘¹²
```
Draw the inverted V.
[Answer]
# JavaScript (ES6), ~~172~~ 139 bytes
```
let f =
_=>`1
3s1
5o5o
7k9k
9gdg
bchc
d8l8
f48194
h08590
i899
g14d41
n0h05
1p`.replace(/.p?/g,n=>' '.repeat((n=parseInt(n,36))/2)+(c='/\\'[n&1])+c)
O.innerText = f()
```
```
<pre id=O>
```
### How?
The logo basically consists of groups of spaces followed by either `//` or `\\` and line feeds.
Spaces and ending patterns are encoded using base-36 values:
* The least significant bit gives the ending pattern: `0` for `//`, `1` for `\\`.
* All other bits give the number of spaces before the ending pattern.
Everything can be encoded this way with a single base-36 digit except the last line which consists of 30 spaces followed by `\\`, leading to 30\*2+1 = 61 = `1p` in base-36. This `p` should be interpreted as 12 spaces followed by `\\` but this pattern doesn't appear anywhere. So, we can simply handle this special case at the cost of 2 extra bytes in the regular expression: `/.p?/`.
---
# First version, 186 bytes
*NB: This one was submitted prior to the logo update.*
```
let f =
_=>[...`WALKER'S`].reduce((s,c)=>(x=s.split(c)).join(x.pop()),`E
ELSRE
'LK'
'LRWLR
WSKS'SK
S ESRLESR
S'KL'K
S 'RKEWR
LEAK'WA
L AKWW
SKERS'RE
L 'ALEA'
LLLS'S ' ER AE\\\\KSALSSA//WSE`)
O.innerText = f()
```
```
<pre id=O>
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 579 bytes
```
+++++++++[>+>+++++>+++>++++++++++<<<<-]>+>++>+++++>++..<<<.>>.>..<..............<..>>..<..<<.>>..>..<............<..>..>..<............<..<.>>...>..<..........<..>....>..<..........<..<.>>....>..<........<..>......>..<........<..<.>>.....>..<......<..>........>..<......<..<.>>......>..<....<..>..........>..<....<..<.>>.......>..<..<..>....<..>>..<....>..<..<..<.>>........>..<<..>....<..>..>..<....>..<<..<.>>.........<..>....<..>....>..<....>..<<<.>>........<..>>..<..<..>......>..<..<..>>..<<<.>>...........>..<<..>........>..<<..>..>..<<<.>>..............................>..
```
[Try it online!](https://tio.run/##bZDRCoAgDEU/KNoXyH4keqggiKCHoO9fQzfdphcEd@5BZPu7Xc/5HTfRpFlwwnxBOZLEmddc1h6AISAC8g1ceMRCi9EpKaMBLXpoij2gYrtC5Y6qbHhzA61uxVZ1tKlC1WxLMI2xM7Rye1YaK4M3g2tNs/ywCm2cHj7i55E9CNdEPw "brainfuck – Try It Online")
Generates the constants `47 92 32 10` in memory, then selects and outputs them as appropriate.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 38 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
6«╝5╚@┼╬⁷7«8ž'⁸3L╚ž92L╚╬5L«26«╝╬5:21╬5
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=NiVBQiV1MjU1RDUldTI1NUFAJXUyNTNDJXUyNTZDJXUyMDc3NyVBQjgldTAxN0UlMjcldTIwNzgzTCV1MjU1QSV1MDE3RTkyTCV1MjU1QSV1MjU2QzVMJUFCMjYlQUIldTI1NUQldTI1NkM1JTNBMjEldTI1NkM1)
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~77~~ 76 bytes
Hexdump:
```
0000000: 75cf c109 8000 0c43 d17b a6c8 0659 28fb u......C.{...Y(.
0000010: cf21 05cb a782 3de9 4b5a b495 5b9f 4946 .!....=.KZ..[.IF
0000020: 870f dac3 f8ea 5704 51b9 2284 c611 0114 ......W.Q.".....
0000030: 9029 f09e ec67 2362 21e1 075e 2136 29b9 .)...g#b!..^!6).
0000040: 08b9 bf97 8939 cf33 ebbf d33e .....9.3...>
```
[Try it online!](https://tio.run/##TY8/SwRBDMV7P8U7bbwmzEzmX4SzEQSxshIVhM3szDVabnUffo27Fr4iJIT3e4kuql/9vHyvq9t1h5LaQPNOUG2Ga5Ex@6KYcqtwOQlCHQostOmBLlbfbulqA3hDtBE8XGrmKTWA5y6ImiZolISkMhAlZoAOv4QTPb8TfdDT444IhqjFDcxTY4zaJ6TiIpJXyw41omVvAd5HQ2x6pRe63rodwYYQFwTDSUdvuSBwDgi@m7Gkbh1nBDEi6Gi@843aMZ@HfPxDREO4ansdUlCFxf5iRle1y5g7/mmLFmKr9@v6Aw "Bubblegum – Try It Online")
Bubblegum threshold. :P
[Answer]
# [///](https://esolangs.org/wiki////), 166 bytes
```
/-/!#//,/%"//'/%#//&/!!//%/ //#/\\\/\\\///"/\\\\\\\\//!/%%/"
"&!'"%
,&-,&-
% "&'!"&'
!"&#!,&#
! "!'&"!'
!,-&,-
!% "'-"!"'
&"#-,!"#
& #-!"!"
&#"'!,'"
&% "#&"#,
&&&!,
```
[Try it online!](https://tio.run/##HYoxDkMxCEN3ThGDgAXkC2XpUKlDt9xfKf2IB8b4fF/n8z73sgkji65k0kcHAdK5Fmncez@Q@t9PkaA7VZYGUl0qelp87sQgMwwVJliKjEFQHdWCCWUrNCXUuqAmsawxloRponLEpGz@JRGBuvcH "/// – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 377 bytes
```
char*r="2\\01 2\\14 2/2\\02 2\\12 2/2 2\\12 2/03 2\\10 2/4 2\\10 2/04 2\\8 2/6 2\\8 2/05 2\\6 2/8 2\\6 2/06 2\\4 2/10 2\\4 2/07 2\\2 2/4 2/2\\4 2\\2 2/08 2\\2/4 2/2 2\\4 2\\2/09 2/4 2/4 2\\4 2\\08 2/2\\2 2/6 2\\2 2/2\\011 2\\2/8 2\\2/2 2\\030 2\\";char d[9];main(i){do{if(*r==48)puts(""),r++;for(i=0;isdigit(*r);d[i++]=*r++);for(d[i]=0,i=atoi(d);i--;putchar(*r));}while(*r++);}
```
[Try it online!](https://tio.run/##PZBBjoMwDEWvglglpSgmZTpUUU7SskBk2lqaGSpK1QXi7NR2gE30vu3/LafNb207z@296Xe9T@3lAkVCb1Em1rCyoiyrjeAgCITlRiBYER1XgC8mkqZaAaTJ4WyKBN9MNqaZWIwaxLfUk61j4LQMl1uRR81iO65@OaeIniVKYuAgy1PHdyfhfKrdX4P/CvUYuhGviv7Cl5V@vIanSlO977PMXbteoQeHz4A3HGhGu3DGLKv9jvpaBqhQe9ijb4YOVdAO89xRDC9ih3bT@46/Pypapnn@AA "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 197 bytes
```
print''.join(i>'/'and(i<'2'and['/','\\'][int(i)]*2or' '*int(i))or i for i in"""1
19501
2193021
319 0419 0
41806180
51608160
61409 140
71204014120
8104021410
90404141
8012061201
921081021
99931""")
```
[Try it online!](https://tio.run/##JY09DsIwDIV3nyLq4hYhsN00xBLiIm0HJIQIQ1JVXTh9cGF4z9@T/5bP9ipZal3WlDfE07uk3KYbnvGeH226ouwwWj7iNOE82libuvkgZUWHh3/syuqSe/485aZpGBzrQAzC2pMw9KyO/G7gOVIwwcCBogkCe1JnBhcW8sTeCkQ2FGMCNfJGEMk6wcSgwra931bVnu1pV@sX "Python 2 – Try It Online")
Uses the logic from the JS answer.
[Answer]
## Haskell, ~~161~~ 160 bytes
```
foldr(\a->(++(' '<$[1..fromEnum a-last(96:[64|a<'`'])])++last("\\\\":["//"|a<'`'])))""<$>words"` `Na LbLb JdJc HfHd FhFe DjDf Bd`DBg @dbD@h ddDI `BfB`H b@h@k ~"
```
[Try it online!](https://tio.run/##NcndCoIwAIbhW/kYwhRJCUIoLIassLBOOtRoszkt/0KNTqJbtwh6D5@3kH2ZVdU45kvdVqozEzlZmbZtUlDfiKeOo7u2XjePGnJSyX4w594i9mYv6VNBT9bJsu0fk@QbWcTEdcl/WhYhvrF6tp3qiYA4SERplGKndheEOlTYFJsM/MY1AiV4kIOplLMCSvEtRKADESJlBSvxJmMtrw2WqOV9f8b9MRyHLmqQjx8 "Haskell – Try It Online")
Spaces before `\\` are encoded as lowercase letters and before `//` as uppercase letters where the number of spaces is the ASCII value minus 96 (or 64). Zero spaces is ``` / `@`. The Spaces of each line are stored in reverse order, because the are consumes by a right-fold.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 51 bytes
```
P↘¹²→↘¹²↑P↗⁵→↗⁵↓P↘⁵→↘⁵↑P↗χ→↗χM¹¹↓M⁵←P↖¹²←↖¹²↓P↙χ←↙χ
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9ng2P2mYc2nlo06O2SXDWRLDw9EeNW8GiEMZkiFqYIIQBVXm@HaLwfPv7PWuBZuwEK18LVjIBrGQaxOQJcBbEuJkgnRPA9P//AA "Charcoal – Try It Online")
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
P↘χ→↘χ↑P↗⁵→↗⁵M⁵↑←P↙χ←↙χMχ↗‖MM¹⁸←P↖²←↖²J²⁷¦⁹P↘²→↘²¦
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9ng2P2macb3/UNglKTwQLTX/UuBUsBmK837MWzJ34qG0CWHYmSOEEMA2UA3GmP2qYBmQC0aGdjxp3wBROO7QJrBBIv9@zCshp3H5o2aPGnRBrQZKTwPShZf//AwA "Charcoal – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~50~~ 31 bytes
```
F²«↘¹²↗↗⁵↘↘⁵↗↗⁹Mχ↓M⁴←↖¹²↙↙χJ¹¦⁰
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw0hToZpLAQgCijLzSjSsXPLL84Iy0zNKdBQMjTTBMr75ZakaVqEFYGFNZMVQMR0FU2SVcCM0cRhsSrS5lkgqDQ10FMCmIImZAIV8UtPQdYOE0N0P0omhFCYIVGwAkfAqzS0Iydcw1FEACtT@//9ft@y/bnEOAA "Charcoal – Try It Online") Link is to verbose version.
I tried. (Also, I will point out that I did this completely on my own, even if it looks somewhat similar to the other one. [Shiz, I did it again. This is still different, by the way. :P])
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 122 bytes (121 chars)
```
_=>@"
A
9;13) +
!(# 0$(
-)
4 ( €".SelectMany(j=>(j%2>0?"//":@"\\").PadLeft(j/4)+(j%4>1?"\n":""))
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5@UlZpcouPpmleam1qUmJSTapOckVhkZ5dm@z/e1s5BiYvHkUvAUsBaxFDCWEJTQVtGUUNZQdJAWkVQkkNCWINTUkCCW1dSQkqTQ1BBkMuEU4NT6FCDkl5wag7QXN/EvEqNLFs7jSxVIzsDeyV9fSUrB6WYGCVNvYDEFJ/UtBKNLH0TTW2gvImdob1STJ6SlZKSpuZ/a67wosySVI3ikqLMvHQ95/y85MQSjTQNY01NTev/AA "C# (Visual C# Interactive Compiler) – Try It Online")
# Explanation
Each part of the logo is just 0+ spaces with either a `\\` or a `//` at the end, plus maybe a newline. There are [52](https://regex101.com/r/FshY2m/1) of these. We then encode each segment into a character:
* Take the number of spaces in each segment, then add 2 to that number.
* Bit shift the number to the left 2 times.
* If the segment ends with `//`, bit-wise OR the number by one.
* If the segment ends with a newline, bit-wise OR the number by two.
* Take the number, and cast it into a char.
* Repeat for each segment.
Here are all of the 52 segments and the numeric value they encode into:
```
10,12,65,10,16,57,16,59,20,49,24,51,24,41,32,43,28,33,40,35,32,25,48,27,36,17,25,8,24,19,40,9,25,16,24,11,45,25,24,26,41,8,17,32,17,10,52,9,40,9,18,128
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 65 bytes
```
“<fṭY2Ẹ<ƭẹ£ʋ¥¹)Œ<Ẓ⁹ḣ⁶ıĠ\ṃṛ?04|ẏḌẉƙ+’b36⁶ẋ“ÇỴ$ñ⁵FḄ’Bị⁾\/¤ẋ€2¤żFs36
```
[Try it online!](https://tio.run/##AY0Acv9qZWxsef//4oCcPGbhua1ZMuG6uDzGreG6ucKjyovCpcK5KcWSPOG6kuKBueG4o@KBtsSxxKBc4bmD4bmbPzA0fOG6j@G4jOG6icaZK@KAmWIzNuKBtuG6i@KAnMOH4bu0JMOx4oG1RuG4hOKAmULhu4vigb5cL8Kk4bqL4oKsMsKkxbxGczM2/8KiWf8 "Jelly – Try It Online")
Returns a list of characters. TIO link has a footer to print on separate lines.
[Answer]
# PHP, 186 bytes:
Both versions require PHP 5.5 or later.
Run with `-nr` or [try them online](http://sandbox.onlinephpfunctions.com/code/579959d3865b656e2e0251beb67c2a2bdeb550d5)
---
space compression gives the shortest alternative:
(double backslash mapped to `0`, double slash to `f`, sapces compressed to digits)
```
while(~$c="0
1077f0
2066f2066f
3055f4055f
408f608f
506f806f
604f5504f
702f4f0402f
80f4f2040f
9f4f4040
8f02f602f0
560f80f20
87870"[$i++])echo+$c?str_pad("",$c):strtr($c,["\\\\",f=>"//"]);
```
PHP 7.1 yields warnings; replace `+$c` with `$c>0` to fix.
---
base 64 encoded bitmap (**187 bytes**):
(mapped space to `00`, newline to `01`, double backslash to `10` and double slash to `11`,
then concatenated 3 "pixels" each to one character,
prepended `1` and converted from binary to ASCII)
```
for(;$c=ord("d`@@@@yB@@@@p`@@@M@`@@C@H@@@t@`@@p@H@@M@B@@p@@`@M@@`C@@@H@t@@`pC`BCP@@l@p`Bt@@C@L@`BP@@xL@BCd@@@K@@Bpd@@@@@@@@@B"
[$i++]);)for($b=6;$b;)echo[" ","
","\\\\","//"][3&$c>>$b-=2];
```
(first linebreak for reading convenience; the other one is essential)
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 74 bytes
```
00000000: 758c 4b11 0400 0885 eea6 a081 85e8 9f63 u.K............c
00000010: 4fb2 7f4f 0e30 4f07 e5ed 7615 8613 e16f O..O.0O...v....o
00000020: 321c ab89 d484 4a22 2591 8a48 45a0 2052 2.....J"%..HE. R
00000030: 809e dfd5 481e 3d0d 7a24 4d96 bc43 b2fd ....H.=.z$M..C..
00000040: 96d3 cdbf fff9 7fa7 f300 ..........
```
[Try it online!](https://tio.run/##XdDNSgUxDAXgvU9xEN2GNE07qeBKhIsiF3yDdtq4UVxdF7782KsDimcRyObLTzu19jpeTm/bxntusCRboS0EsDKDzRLGqBmVLcDSMBTPETjRI/3JevEjhGmoN8Hi6uAReba8YKTRseSQYDlEjJAdOBIdiWelj7PxvhsyjShhRW1W0NUUWkUgqcwVqho0VYZwEkC@xz9cXhMd7gnPuxGnYVwGuvcEtTAQO88Vqkytl4y2akQT78BZONAtfV49Ed0R7YZOo@QesfbmcPcyr6oLPM7P/M/vK7btCw "Bubblegum – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~221~~ 220 bytes
```
$ofs=''
"b
b$(' '*14)/b
$((2..6|%{' '*$_+"b$(($a=' '*(14-++$i*2)))/$(' '*$i*2)b$a/`n"})) 4b /4/b4b /
44b/4/ b4b/
44 /4/4b4b
44/b /4 b /b
44 b/44b/ b
$(' '*30)b"-replace4,' '-replace'/','//'-replace'b','\\'
```
[Try it online!](https://tio.run/##RYzNCsIwEITveYolRDbp39oavPVNCtqViEKxpT14UJ89blrE08y3M7PT@AzzcgvDEKMZr0uLqDQrYGMRMKu9I1bG2qaqju/dK93MKdcSW9O3CW3tyzw396xxztE2W4lNT@eH/jgHAJ4ByBOvqrxnAQDBBCnx4sXS2pNEJLFMpSo1UbU9P@wd63IO09Bfgi9QKoA/RsICif7Mwl2HMX4B "PowerShell – Try It Online")
Fairly naïve approach (*and 50 bytes worse than the JS answer, cringe*). Anyone know of a way to do multiple `-replace`s in PowerShell?
*-1 byte thanks to Veskah.*
[Answer]
# [Python 2](https://docs.python.org/2/), 180 bytes
```
print''.join(c<'3'and'\\/\n\\/'[int(c)::3]or' '*(int(c,36)-2)for c in'0230g104240e140e1250c160c1260a180a127081a08128061c0612904161060412a0161406012b16160602a1041804102d01a01402w0')
```
[Try it online!](https://tio.run/##HYxLDsIwDESv0p0bxMd2QggVN6EsQsqnLJKqqoQ4fRhYPPvJo/H0WZ4la63TPOaFaPsqY27TiSzFPFDf7/qMQWekbTJdZy9lpoZW7f@wtt5s1NzL3KRmzMRq@SHs1PFNfuiek3ignqMEoAcOEoEG9pKAHtmJF/ZYGhnq4KJXmIdpxEd0nbAOjC5yfTOZWr8 "Python 2 – Try It Online")
The encoding is base 36:
```
0 => \\
1 => //
2 => \n
```
and otherwise,
```
n => (n-2) spaces
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~144~~ ~~140~~ 139 bytes
-4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
Each character in the string encodes a number of spaces to use before a certain string. If it's a lower-case letter (or a backtick), then the string is "\", and if upper-case or @, it's "//". A space signifies a newline.
```
f(c,i){for(i=0;c="` aN` bLbL cJdJ dHfH eFhF fDjD gBD`dB h@Dbd@ IDdd H`BfB` k@h@b ~"[i++];)printf("%*s",c%32+2,c<33?"\n":c<96?"//":"\\\\");}
```
[Try it online!](https://tio.run/##DcrdCoIwFADg63yKwwFhS6NQCPIHRUZYSC@QwdxZ0xVZWHdir2591x@tWqJ5Nox8y0fzHJhNNzGlKKE5SVCVqoCO@gi6NCVc990ejLgJaAshdQFdLpTO4SC0hlIWppBwz7tcwRfP1vMuMX8Ntv8Yhu7yjT65YeAFPiVhmGHdY0TJbpvheo0R1n/I42n@f3g0tmfcGZ2FYTx2pvkH "C (gcc) – Try It Online")
] |
[Question]
[
I've designed a new font which I call PrettyFont. I've put much much time into perfecting it, but since I'm a working man I don't have time to finish it. Therefore it only contains 4 characters right now. One day when I've become rich it will become my life-long goal to finish it, but for now...
This is PrettyFont: (0, 1, 2, 3)
```
#### ## #### ####
# # # # # #
# # # # ###
# # # # #
#### ### #### ####
```
Each character is 4 pixels wide and 5 pixels high. Now! I want you to write me a program that outputs a number in PrettyFont so I can start sending designs to print.
**Rules:**
The input is a string number in base 4 (only characters 0-3), for example "01321". The program should be able to handle at least 10 characters in the string. BONUS points is given to the program that takes an actual base 10 integer instead of a string. *EDIT* clarification: the integer bonus means that one can enter any base 10 number, like 54321, and the program will convert it to base 4 and output it (in this case 31100301).
The output will be the number printed with PrettyFont. Example input and output:
```
> "321"
####
#
###
#
####
####
# #
#
#
####
##
#
#
#
###
```
Huge bonus to the program that can output it in a single row-fashion like this:
```
> "321"
#### #### ##
# # # #
### # #
# # #
#### #### ###
```
The '#' character is not a requirement, and can be replaced by any character.
In vertical output, an empty row is required between each PrettyFont character. If anyone makes the horizontal output, one white space character ' ' or a tab character is required between each PrettyFont character.
This is code golf, shortest code wins! (I need it short because my office computer has limited storage.)
[Answer]
# k (~~118 117 72 71 69~~ 66 chars)
~~I haven't made much of an effort to golf this yet~~ but it achieves the desired horizontal output in not too many chars:
```
-1'" "/:'+(5 4#/:4 20#"# "@,/0b\:'0x066609ddd806db00e8e0)"I"$'0:0;
```
Takes input from stdin, prints output to stdout.
edit: By implementing a form of compression on the output "bitmap", I've reduced it to 72. The bitmap is now built by converting 64bit ints to binary and mapping the 0s and 1s to "#" or " ". ~~I could do it from hex like a few of the other solutions but I think this would end up longer~~. Turns out hex is better.
Sample output for 012301:
```
#### ## #### #### #### ##
# # # # # # # # #
# # # # ### # # #
# # # # # # # #
#### ### #### #### #### ###
```
//edit: -6 char
[Answer]
## Python3 (124)
```
s=input();[print(*["".join(" #"[0xf171ff429f72226f999f>>(20*int(x)+4*y+i)&1]for i in(3,2,1,0))for x in s])for y in range(5)]
```
Sorry, vertical was not interesting for me.
```
???/golf.py
1230012301203012030102301230
## #### #### #### #### ## #### #### #### ## #### #### #### #### ## #### #### #### #### ## #### #### #### #### ## #### #### ####
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # ### # # # # # # ### # # # # # # ### # # # # # # ### # # # # # # ### # # # # ### # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
### #### #### #### #### ### #### #### #### ### #### #### #### #### ### #### #### #### #### ### #### #### #### #### ### #### #### ####
```
[Answer]
## J, 84 82 81 80 75 69 characters
```
' #'{~(,4,.(4*".,' ',.1!:1[1)+/i.4){"1#:63231 37521 37415 37441 63487
```
Takes input from the keyboard:
```
' #'{~(,4,.(4*".,' ',.1!:1[1)+/i.4){"1#:63231 37521 37415 37441 63487 63487
0123210
#### ## #### #### #### ## ####
# # # # # # # # # # #
# # # # ### # # # #
# # # # # # # # #
#### ### #### #### #### ### ####
```
Magic numbers FTW (or for the second place in this case) :-)
[Answer]
# C - 164 151 characters horizontal
On IDEone: <http://ideone.com/gljc3>
The code (164 bytes):
```
i,j;main(){char n[99];gets(n);for(;j<5;++j){for(i=0;n[i];++i)printf("%.4s ","##### # ## # ### # #"+4*("01110233340135006460"[(n[i]-48)*5+j]-48));puts("");}}
```

# EDIT - 151 bytes
I added the suggestions from the comments and then some. It isn't exactly safe (0-length array that I `gets()` in to...) though.
```
char i,j=5,n[];main(){for(gets(n);j--;)for(i=puts("");n[i];printf("%.4s ","##### # ## # ### # #"+4*(0x1A600BA136E0248>>15*n[i++]-720+3*j&7)));}
```
Note, `i=puts("")` is undefined behavior since I'm treating `void` as `int`! It consistently returns `0` on my version of MinGW, but it returns `1` on the compiler IDEOne uses.
# Accepts decimal, outputs base 4 (167 bytes)
```
char i,j=5,n[];main(p){for(itoa(atoi(gets(n)),n,4);j--;)for(i=puts("");n[i];printf("%.4s ","##### # ## # ### # #"+4*(0x1A600BA136E0248>>15*n[i++]-720+3*j&7)));}
```
[Answer]
# Ruby, *0123* chars + a bonus ([0123] vs '#')
```
f=15
0.upto(4){|n|$*[0].chars{|x|$><<"%4s "%eval(:f6ff929192279241f7ff[x.to_i+4*n]).to_i.to_s(2).tr(?0,' ').tr(?1,x)}
puts}
```
Example:
```
% ruby ./font.rb 01231231
0000 11 2222 3333 11 2222 3333 11
0 0 1 2 2 3 1 2 2 3 1
0 0 1 2 333 1 2 333 1
0 0 1 2 3 1 2 3 1
0000 111 2222 3333 111 2222 3333 111
% ruby ./font.rb 01231231102020103201301203212302230
0000 11 2222 3333 11 2222 3333 11 11 0000 2222 0000 2222 0000 11 0000 3333 2222 0000 11 3333 0000 11 2222 0000 3333 2222 11 2222 3333 0000 2222 2222 3333 0000
0 0 1 2 2 3 1 2 2 3 1 1 0 0 2 2 0 0 2 2 0 0 1 0 0 3 2 2 0 0 1 3 0 0 1 2 2 0 0 3 2 2 1 2 2 3 0 0 2 2 2 2 3 0 0
0 0 1 2 333 1 2 333 1 1 0 0 2 0 0 2 0 0 1 0 0 333 2 0 0 1 333 0 0 1 2 0 0 333 2 1 2 333 0 0 2 2 333 0 0
0 0 1 2 3 1 2 3 1 1 0 0 2 0 0 2 0 0 1 0 0 3 2 0 0 1 3 0 0 1 2 0 0 3 2 1 2 3 0 0 2 2 3 0 0
0000 111 2222 3333 111 2222 3333 111 111 0000 2222 0000 2222 0000 111 0000 3333 2222 0000 111 3333 0000 111 2222 0000 3333 2222 111 2222 3333 0000 2222 2222 3333 0000
```
# EDIT: Ruby, 87 chars
```
0.upto(4){|n|$*[0].bytes{|x|$><<"%04b0"%:f6ff929192279241f7ff[x-48+4*n].to_i(16)}
puts}
```

[Answer]
# Ruby
## Vertical: 116 characters
```
f="f999f62227f924ff171f".chars.map{|c|c.hex.to_s(2).rjust(4).tr"01"," #"}
$<.chars{|c|i=c.to_i*5;$><<f[i,5]*$/+$/*2}
```
Sample run:
```
bash-4.2$ echo -n 321 | ruby -e 'f="f999f62227f924ff171f".chars.map{|c|c.hex.to_s(2).rjust(4).tr"01"," #"};$<.chars{|c|i=c.to_i*5;$><<f[i,5]*$/+$/*2}'
####
#
###
#
####
####
# #
#
#
####
##
#
#
#
###
```
## Horizontal: ~~150~~ 148 characters
```
f="f999f62227f924ff171f".chars.map{|c|c.hex.to_s(2).rjust(4).tr"01"," #"}
o=(0..4).map{""}
$<.chars{|c|5.times{|j|o[j]<<f[c.to_i*5+j]+" "}}
$><<o*$/
```
Sample run:
```
bash-4.2$ echo -n 321 | ruby -e 'f="f999f62227f924ff171f".chars.map{|c|c.hex.to_s(2).rjust(4).tr "01"," #"};o=(0..4).map{""};$<.chars{|c|5.times{|j|o[j]<<f[c.to_i*5+j]+" "}};$><<o*$/'
#### #### ##
# # # #
### # #
# # #
#### #### ###
```
[Answer]
# Mathematica 174 145 139 118 119 123 chars
Now works with input in base 10 (Integer bonus). Earlier versions can be found in edits.
---
**Using ArrayPlot**:
With `ArrayPlot` we can directly convert the 1's and 0's to black and white squares, saving a few chars in the process. For example, with n = 58021, which is **32022211** in base 4:
```
i = IntegerDigits; i[n, 4] /. Thread@Rule[0~Range~3, ArrayPlot /@ ((PadLeft[#, 4] & /@ i[#, 2]) & /@ (i@{89998, 62227, 89248, 81718} /. {8 -> 15}))]
```

---
**Explanation**
Input is program parameter, `n`.
Zero can be represented by `{{1,1,1,1},{1,0,0,1},{1,0,0,1},{1,0,0,1},{1,1,1,1}`
or by the hex counterpart `f999f`.
The expression, `f999f62227f924ff171f`, holds the information to display all the numbers {0,1,2,3}. (Note: it begins with `f999f`, which as we noted, is zero in disguise.) Because Mathematica does not recognize this as a number, I used `89998622278924881718` (in four integer strings) instead, broke up the number into its integer digits, and then used 15 in every place an 8 appeared. (That allowed me to use digits instead of strings throughout.)
[Answer]
## *Mathematica*, ~~112~~ ~~107~~ 103
My take on David's method.
```
i=IntegerDigits;Grid/@i@n/.Thread[0~Range~3->("#"i[i@#/.8->15,2,4]&/@{89998,62227,89248,81718}/.0->"")]
```

### 105 with the BONUS:
(for `n = 54321`)
```
i=IntegerDigits;Grid/@n~i~4/.Thread[0~Range~3->("#"i[i@#/.8->15,2,4]&/@{89998,62227,89248,81718}/.0->"")]
```

[Answer]
## APL (~~58~~ 57)
```
{' #'[1+5 4⍴1022367 401959 1020495 988959[1+⍎⍵]⊤⍨20⍴2]}¨⍞
```
Output:
```
0123
#### ## #### ####
# # # # # #
# # # # ###
# # # # #
#### ### #### ####
```
[Answer]
# Python 2.7
## Vertical 160
```
for i in input():print['****\n* *\n* *\n* *\n****',' ** \n * \n * \n * \n***','****\n* *\n * \n * \n****','****\n *\n ***\n *\n****'][int(i)]+'\n'
```
## Horizontal 234 216
```
x=[['****\n* *\n* *\n* *\n****',' ** \n * \n * \n * \n ***','****\n* *\n * \n * \n****','****\n *\n ***\n *\n****'][int(i)]for i in input()]
for i in range(5):print' '.join([y.split('\n')[i]for y in x])
```
Both take input as a quoted string on stdin
example:
$./pretty
"0123"
] |
[Question]
[
Your task is to write the shortest algorithm in a language of your choosing that accomplishes the following:
Given two matrices it must return the euclidean distance matrix. The euclidean distance between two points in the same coordinate system can be described by the following equation:
\$D = \sqrt{ (x\_2-x\_1)^2 + (y\_2-y\_1)^2 + ... + (z\_2-z\_1)^2 }\$
The euclidean distance matrix is matrix the contains the euclidean distance between each point across both matrices. A little confusing if you're new to this idea, but it is described below with an example.
Below is an example:
```
a = [ 1.0 2.0 3.0;
-4.0 -5.0 -6.0;
7.0 8.0 9.0] #a 3x3 matrix
b = [1. 2. 3.] #a 1x3 matrix/vector
EuclideanDistance(a, b)
[ 0.0;
12.4499;
10.3923]] # a 3x1 matrix/vector see rules for relaxed scoring
```
In a typical matrix representation of data, or coordinates, the columns represent variables. These could by \$\text{X,Y,Z...,J}\$ coordinates. Most people think in terms of \$\text{XYZ}\$ for 3-D space(3 columns), or \$\text{XY}\$ for 2D space(2 columns). Each row of the matrix represents a different point, or object. The points are what is being compared.
Using the example, matrix `b` is a single point at positions \$X= 1,Y = 2\$ and \$Z = 3\$. Matrix `a` contains three points in the same set of coordinates. The first point in `a` is the same as the point contained in `b` so the euclidean distance is zero(the first row of the result).
Not to be confusing, but, the matrices can be of any size(provided they fit into RAM). So a 7 by 11 matrix being compared with a 5 by 11 matrix is possible. Instead of X,Y,Z we would then have 11 coordinates(or columns) in both input matrices. The output would either be a 7x5 or a 5x7 matrix (depending on what way the points are compared). Make sense? Please ask for further clarifications.
Here's a 4 dimensional matrix example
```
a = [ [1. 2. 3. 4.];
[ -4. -5. -6. -7. ];
[ 6. 7. 8. 9. ] ] #a 3x4 matrix
b = [ [1. 2. 3. 4.];
[1. 1. 1. 1.] ] #a 2x4 matrix
EuclideanDistance(a, b)
[ 0.0 3.74166;
16.6132 13.1909;
10.0 13.1909] #a 3x2 matrix
```
And another example for soundness:
```
a = [ [1. 2.];
[ 3.3 4.4 ] ] #a 2x2 matrix
b = [ [5.5 6.6];
[7. 8. ];
[9.9 10.1] ] #a 3x2 matrix
EuclideanDistance(a, b)
[6.43506 8.48528 12.0341;
3.11127 5.16236 8.72067] #a 2x3 matrix
```
Rules:
1. If this function is included in your base language you can use it. You can import the direct function to do this as well. But you sacrifice style and honor! You will not be evaluated on style or honor but your street cred. will be - your call :P .
2. Your submission should be evaluated in bytes. So save off your code to plain text and read the file size. Less bytes is best!
3. No printing necessary, just a function, lambda, whatever, that computes this operation.
4. Reasonable round-off error is fine, and the transpose of the correct solutions is also fine.
5. This must work for matrices!
Happy golfing!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
_þ²§½
```
[Try it online!](https://tio.run/##y0rNyan8/z/@8L5Dmw4tP7T3////0dGGOgpGOgrGOgomsTpc0bomOgq6pkBsBsTmIBEFIMtcR8FCR8EyNhZDPZAHRbGxAA "Jelly – Try It Online")
A dyadic link that takes a matrix as each argument and returns a matrix.
## Explanation
```
_þ | Outer table using subtract
² | Square (vectorises)
§ | Sum (vectorises)
½ | Square root (vectorises)
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~45~~ 43 bytes
```
a#b=[sqrt.sum.map(^2).zipWith(-)l<$>b|l<-a]
```
[Try it online!](https://tio.run/##jY9PC4JAEMXvfooBPSisQ/5X0L5GB9lgpUBpNVO7RN99m/ZQEWs0y@/0dt5704r5dJRSKWE3VT1fpgXna4@9GN196OGtG3fd0rq@J0tn29xl6QuuetENUMHhbAHNOHXDAg7U9AIGEBIRcAZafU/txwz8hEhNKmS0lxMFcODWh2x/Wz/l9WgipoD1dCIzNiDl7xYrKfrDix9VyYYwGESovTE2F0iQboAUU9Nupo1zs3GBBYNgg7qVegA "Haskell – Try It Online")
I've been trying pretty hard to make this pointfree, and I think it would be shorter but I cannot get it down for some reason.
[Answer]
# [R](https://www.r-project.org/), 57 bytes
```
function(x,y)as.matrix(dist(rbind(x,y)))[a<-1:nrow(x),-a]
```
[Try it online!](https://tio.run/##dU3LCsIwELz7FXvchYlQ@1LRLxEPaUogB1NII8avj0vpVZiBeTBMqv5e/Tu6HJbIBV@x6/FlcwqF57BmTlOI81aIPOzNNNeYlg8XgbHP6vfecQM6gVpQJzg4Nh3I9MpBOW6RqhF0Bl1E/Z@d2h36V38 "R – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), ~~10~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes `b` as the first input and `a` as the second.
```
V£MhUí-X
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=VqNNaFXtLVg&input=WwpbMSAyIDNdCls0IDUgNl0KXQoKWwpbMS4wICAyLjAgIDMuMF0KWy00LjAgLTUuMCAtNi4wXQpbNy4wICA4LjAgIDkuMF0KXQ)
```
V£MhUí-X :Implicit input of 2d-arrays b & V=a and map each U in b
V£ :Map each X in V
Mh : Hypotenuse of
Uí-X : U interleaved with X with each pair reduced by subtraction
```
[Answer]
# [J](http://jsoftware.com/), ~~15~~ 13 bytes
```
+/&.:*:@:-"1/
```
[Try it online!](https://tio.run/##bYzLCsIwEEX3/YpLKaZRZ9q8WhsQBMGVK38gC7GIG/9/FUNSfIBcZnPnnPuINYsZew@BLXr4dMQ4Xs6nuOlW7Nf@4KlWXZQVqtv1/kRrYBoFDYNgERzCgBE7TBIz2vyQhRREJN6SRYOi2Y8YRnzb@odSJX/WdCIWjhPJNtsmt44dBl5WeYLqWcn4Ag "J – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
IEθEη₂ΣEιX⁻ν§λξ²
```
[Try it online!](https://tio.run/##bYw9C4MwFEV3f8Udn/AUa7/pVDp1EKSOwSFYQcEmNcbWf582oWPfcC6ce3lNJ02j5eBcaXpl6SInS4V80sjw0TGqcZamvWltqZofoewZpX63hopezRMpxtle1b1daGAscczI49@dnBMRhMAqzRjIA9dpVjMiQCQbL5Jt4M5rb7EPs0Pg8Wu9/vOjjmqXvIYP "Charcoal – Try It Online") Link is to verbose version of code. Outputs each element on its own line, double-spacing between rows. Explanation:
```
θ First matrix
E Map over rows
η Second matrix
E Map over rows
ι First matrix row
E Map over entries
ν First matrix entry
⁻ Subtract
λ Second matrix row
§ Indexed by
ξ Inner index
X ² Squared
Σ Summed
₂ Square rooted
I Cast to string
Implicitly printed
```
[Answer]
# [J](http://jsoftware.com/), 12 bytes
```
+/&.:*: .-|:
```
[Try it online!](https://tio.run/##bYxLCsIwFEXnXcVBimnUPJsmbW3AkeDIkRvIQCzixA2491ja4gfk8ib3nXPvaSGqZx9QbCgJwxnhcD4d03q7lLAKiHmGpDOy6@X2oHC43FLhiJ5YExtadnSanmJ86IlUxhj1ljw5k@Y/Ymz5tqsfyk75s1YNxMzJQIofbTe2tdQ0Mq9Khy3F6vQC "J – Try It Online")
### How it works
```
+/&.:*: .-|: Left: a, Right: b
|: Transpose b to get bT
. Customized matrix multiply:
- Subtract bT's columns from a's rows
&.:*: Square each element
+/ Sum
&.:*: Sqrt the result
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
δ-nOt
```
Takes `b` as first input and `a` as second.
[Try it online](https://tio.run/##yy9OTMpM/f//3BbdPP@S//@jow11jHSMdUxidaJ1TXR0TXV0zXR0zYE8Mx1zHQsdy9hYLmQ1hjpgGBsLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/s9v/cFt08/5L/Ov@jow11jHSMY2O5YCydaF0THV1THV0zINNcx0LHEiGpYwIUM9QBQzRRmCYdXXMgz0wHodNUz1THTA9qGpC01LPUMTTQgxsAFDLWAxqiZxIbCwA).
**Explanation:**
```
δ # Outer product; apply double-vectorized on the (implicit) input-lists:
- # Subtract
n # Then square each inner value
O # Sum each inner list
t # And root those sums
# (after which the result is output implicitly)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes
```
Outer[Norm[#-#2]&,##,1]&
```
[Try it online!](https://tio.run/##bY67CsMwDEX3fIVAkEkWzTsZWvIFbXfjIZSEZkgLwZ2Cv92Vm9AH1EigK5970dTZaz91drx0foC9Pz1sP@vjfZ40KkxNTIiUmNif5/Fm9YLoQB1g0IjGQAxt20awyEsIUoLMESwqJ1CFdBlURVATNC7Mb0pUBPCxEeS/TukqbGT4F7Dxorb6SmRBOPxmHDjOV2fBElzyepMw9YtpuBH3jkOA808 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~27~~ 25 bytes
```
{.&[XZ-]>>²>>.sum X**.5}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wk8tOiJKN9bO7tAmOzu94tJchQgtLT3T2v/WXMWJlQppChoahjpG1sZ6xjomeiaaOgoapnqmOmZ6ZtbmOhbWlnqWOoYGeoaamv8B "Perl 6 – Try It Online")
Returns the distance matrix as a flat list.
### Explanation
```
{ } # Anonymous block
.&[XZ-] # Cartesian product using zip-with-minus operator
>>² # Square each value
>>.sum # Sum of vector elements
X**.5 # Square root of each value
```
[Answer]
# JavaScript (ES6), 61 bytes
Takes input as `(a)(b)`.
```
a=>b=>a.map(a=>b.map(b=>Math.hypot(...a.map((v,i)=>v-b[i]))))
```
[Try it online!](https://tio.run/##lY5LDoMgEED3nGKWkMDEVqqSBm/QExgXaH82bTGtMenpLaC2LropgcnwGObNxfTmWT@athN3uz8MRz0YnVc6N3gzLfV5SBzZme6M51drO4qI4zvtecN03ouqaErm1lDb@9NeD3i1J3qkBQEoYIURB1iHGGMEJQfPhfREbEJMvhzSUJmFqDwnJZtbcVhziANiZCljW0J@yscfHKTrH4iQ3uqd7qQfq7ulHDIO6odw8d2Raf85xdwgRt8O5VKzQTdQgslc4yeZc4XKySKcfMMb "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 52 bytes
```
(a,b)->matrix(#a~,#b~,i,j,sqrt(norml2(a[i,]-b[j,])))
```
[Try it online!](https://tio.run/##PY1NDoIwEIWv0simTV4ngoCSRm7gCZouBhNNCWqtLHTj1ZGfSGbzZr5v8gJHr69huIjjIBmN0vWN@@jfMuEvkuYLjxavZ@zl/RFvXSbZejjd2BZOKTVwCN1HstC1CNHf@zFupmUjztx18gLBSkFYa1Nk2BmdQxfQpdnjgMpBnLiXC3PKTeKcka8m9N6U@OsrTjGPW34IGZkdjYDy6VJQgZLGFsKBTEUV0i2NslPDDw "Pari/GP – Try It Online")
[Answer]
# Julia, 45 bytes
Using the kernel trick! With broadcasting, starting from here(59 bytes)
```
D(X,Y)=sqrt.((sum(X.^2,dims=2).+sum(Y.^2,dims=2)').-2X*Y')
```
we can sneak by a bit here by condensing this down using ascii operators
58 bytes
```
D(X,Y)=.√((sum(X.^2,dims=2).+sum(Y.^2,dims=2)').-2X*Y')
```
and by adding a second function(could be a lambda or anonymous fn)
54 bytes
```
f(S)=sum(S.^2,dims=2)
D(X,Y)=.√(f(X).+f(Y)'.-2X*Y')
```
It may be tacky to submit an answer to your own question but I ensured I wouldn't win first and figured I'd share this approach. Maybe someone can condense it down further?
Update:
Thanks to @lyndonwhite we can shave this down to 45 bytes after operator overloading!
```
!S=sum(S.^2,dims=2)
X|Y=.√(!X.+!Y'.-2X*Y')
```
[Answer]
# [R](https://www.r-project.org/), 55 bytes
Inspired by @Nick Kennedy's [answer](https://codegolf.stackexchange.com/a/196012/88518), saving 2 bytes;
```
function(x,y)fields::rdist(rbind(x,y))[a<-1:nrow(x),-a]
```
(Sadly doesn't work on tio but does on a local R install with the fields package)
[Answer]
# Python (with numpy), 87 bytes
```
from numpy import *
f=lambda a,b:linalg.norm(r_[a][:,None,:]-r_[b][None,:,:],axis=2)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 59 bytes
```
->m,n{m.map{|i|n.map{|j|i.zip(j).sum{|a,b|(a-b)**2}**0.5}}}
```
[Try it online!](https://tio.run/##NYvLDsIgFET3/Yq7bMlALH3pQn@kYQEmTWhKQzRdKPDt@KhmNjNncm6beeTpnPnFYQ1OOO1DtHHdyxyteFpfzpW4by5EDRNLzU3FmEyMHUSXUsqeJnHVy0JjQTTWIAlqQK3CZ/MWvAPvwYcd9KABdASdVKHwlyQa/Iwa37zf/AI "Ruby – Try It Online")
[Answer]
# APL(NARS), chars 35, bytes 70
```
{⊃√+/¨2*⍨⍵∘-¨(⍴⍵)∘⍴¨{a[⍵;]}¨⍳↑⍴a←⍺}
```
test:
```
f←{⊃√+/¨2*⍨⍵∘-¨(⍴⍵)∘⍴¨{a[⍵;]}¨⍳↑⍴a←⍺}
a1←3 3⍴ 1 2 3 ¯4 ¯5 ¯6 7 8 9
b1←1 3⍴ 1 2 3
a2←3 4⍴1 2 3 4 ¯4 ¯5 ¯6 ¯7 6 7 8 9
b2←2 4⍴1 2 3 4 1 1 1 1
a3←⊃(1 2)(3.3 4.4)
b3←⊃(5.5 6.6)(7 8)(9.9 10.1)
a1 f b1
0
12.4498996
10.39230485
b1 f a1
0 12.4498996 10.39230485
a2 f b2
0 3.741657387
16.61324773 13.19090596
10 13.19090596
a3 f b3
6.435060217 8.485281374 12.03411816
3.111269837 5.1623638 8.720665112
{⊃√+/¨2*⍨⍵∘-¨(⍴⍵)∘⍴¨{a[⍵;]}¨⍳↑⍴a←⍺}
⍳↑⍴a←⍺ gets the number of rows and return 1..Nrows
{a[⍵;]}¨ for each number of row return the row
(⍴⍵)∘⍴¨ for each row build one matrix has same apparence of ⍵ (the arg of main function) and return it as a list of matrix
so we have the same row that repeat itself until has the same nxm of the ⍵ arg
⍵∘-¨ make the difference with the ⍵ arg
2*⍨ make the ^2
⊃√+/¨ sum each doing √ and (in what seems to me) make as colums the element (that are rows)
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/100578/edit).
Closed 6 months ago.
This post was edited and submitted for review 6 months ago and failed to reopen the post:
>
> Original close reason(s) were not resolved
>
>
>
[Improve this question](/posts/100578/edit)
**Definitions**:
* A *line* is a possibly empty sequence of characters terminated by a “newline character.”
A “newline character” is a character that cannot be a component of the aforementioned character sequence.
* A *line number comment* is a character sequence that does not alter the meaning of source code in the programming language of your submission.
It *contains* a decimal representation of the (integral) unique line number associated with the line of input.
(A conventional notation is sufficient, e. g. `4.2E1` for `42`.)
* A *content line* is a line that conveys meaning in the programming language of your submission.
**Task**:
* Write a program (or function) that numbers all lines, but *at least* all content lines.
The program shall *print* a line number comment followed by the respective processed (otherwise unaltered) input line.
The function shall *return* a value accordingly.
**Conditions**:
* Numbered lines must be numbered in ascending order in the order of input (i. e. not in the order a processor for the respective programming language might possibly process the input).
* Line numbers must be consecutive.
That means you may not omit numbers.
* The first line is identified either by the line number zero (`0`) or one (`1`).
The behavior must be consistent for all possible input.
* Line numbers must reproduce:
Feeding the output back as input again produces the same line numbers.
**Accommodations**:
* You *may* assume that input is valid source code in your submission’s programming language.
* You *may* assume that no token is spread across multiple lines (e. g. multiline string literals or backslash-continuation), thus insertion of a line number comment is guaranteed not to alter the source code’s meaning.
* You *may* assume input consists of lines.
Numbering of non-lines (that is empty input or input not terminated by a newline-character) is implementation-dependent.
**Test cases**:
C (note that tabulator characters are preserved):
```
#include <stdio.h>
int main()
{
char c;
c = getchar();
do
{
putchar(c);
}
while (c);
}
```
```
/* 0*/#include <stdio.h>
/* 1*/int main()
/* 2*/{
/* 3*/ char c;
/* 4*/ c = getchar();
/* 5*/ do
/* 6*/ {
/* 7*/ putchar(c);
/* 8*/ }
/* 9*/ while (c);
/*10*/}
```
Pascal (note that it is not specified that input *is* indeed source code):
```
Esolanging fruit is hanging low.
```
```
{ 1 }Esolanging fruit is hanging low.
```
If you input that output back in again, it must reproduce the same line number comments:
```
{ 1 }{ 1 }Esolanging fruit is hanging low.
```
SQL (note that only content lines were numbered):
```
-- populate foo with some data
insert into foo values (1, 'bar');
insert into foo values (2, 'foobar');
select * from foo;
```
```
-- populate foo with some data
/*0*/insert into foo values (1, 'bar');
/*1*/insert into foo values (2, 'foobar');
/*2*/select * from foo;
```
[Answer]
# Perl, 8+1 = 9 bytes
```
say"#$."
```
Run with `-p` (1 byte penalty). (Note to people unfamiliar with PPCG rules; you also need to specify a modern version of Perl syntax using `-M5.010`, but we decided that options to select language versions are free and don't incur a byte penalty, so I didn't mention it in the original version of this post.)
`-p` places the program into an implicit loop; it basically causes the program to become a filter that processes each line separately (i.e. the entire program is run on the first line, then the second, then the third, and so on). Perl also keeps track of a line number, called `$.`, that records how many lines of input have been read. So all the program's doing is letting `-p` read a line of input; output a `#`, the current line number (`$.`), and a newline (`say` adds a newline by default, which is helpful in this case, and is also shorter than the more commonly seen `print`); and then letting `-p` output the original line of code that it read (typically a program using `-p` would do some sort of processing on the input, but because we didn't, it's just output unchanged). Comments in Perl run from `#` to a newline (the `#` in the program itself doesn't start a comment because it's inside a string literal), so what we're basically doing is taking the opportunity to write comment lines into the file as we process it, without disturbing the "natural" read and write cycle of `-p`.
[Answer]
# Javascript, ~~43~~ 39 bytes
```
a=>a.replace(/^/gm,_=>`/*${++b}*/`,b=0)
```
Thanks to ETH and Conor for saving 4 bytes.
[Answer]
## Pyke, 7 bytes
```
o\Kz++r
```
[Try it here!](http://pyke.catbus.co.uk/?code=o%5CKz%2B%2Br&input=Test%0ATest)
```
o - o++
\K - "K"
z - input()
++ - sum(^)
r - while no errors: GOTO start
```
I'm declaring integer comments to be the integer followed by the character `K` and then the line. An extra byte is used to stop the newline opcode from kicking in and printing an extra thing.
[Answer]
# [V](http://github.com/DJMcMayhem/V), 10 bytes
```
O:1òYjjP
```
[Try it online!](http://v.tryitonline.net/#code=TzoxG8OyWWpqUAE&input=dGVzdAp0ZXN0)
[Answer]
# Lua, ~~80~~ 75 Bytes
*Saved some bytes by abusing the langauge.*
```
x=1print("--[[1]]"..(...):gsub("\n",load('x=x+1return"\\n--[["..x.."]]"')))
```
Simple enough starter answer.
## Ungolfed, +
```
x=1 -- Assign x to 1...
print( -- Print...
"--[[1]]" -- The first line number comment...
.. -- With...
(...):gsub( -- The input, replacing all...
"\n", -- Newlines...
load -- with a string compiled function...
(' \
x=x+1 --Increment x by one... \
return"\\n--[["..x.."]]" -- And return the new linecomment. \
')
)
)
```
[Answer]
## Batch, 91 bytes
```
@set n=
@for /f "delims= tokens=*" %%a in (%1) do @set/an+=1&call echo @rem %%n%%&echo %%a
```
Batch doesn't have a way of reading STDIN until EOF, so instead the file name has to be passed as a command-line parameter.
[Answer]
## awk (~~19~~ 13 bytes)
**19 bytes** : This insert "#"+line number above each line of code
```
{print"#"NR"\n"$0}
```
**13 bytes** : Credit & thanks to @manatwork for two 13 bytes solution
As `1` action defaults to `print $0`:
```
{print"#"NR}1
```
Or by replacing `$0` content
```
$0="#"NR RS$0
```
[Answer]
# Gema, ~~16~~ 15 characters
```
*\n=\!@line\n$0
```
In Gema there are only line comments, starting with `!`.
Sample run:
```
bash-4.3$ cat l33t.gema
e=3
g=9
i=1
o=0
t=7
bash-4.3$ gema -f l33t.gema <<< 'Hello World!'
H3ll0 W0rld!
bash-4.3$ gema '*\n=\!@line\n$0' < l33t.gema > l33t-nr.gema
bash-4.3$ cat l33t-nr.gema
!1
e=3
!2
g=9
!3
i=1
!4
o=0
!5
t=7
bash-4.3$ gema -f l33t-nr.gema <<< 'Hello World!'
H3ll0 W0rld!
```
The following are to answer [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)'s question, whether is possible to add the line number in kind of ignored code.
Gema code is essentially a collection of *from*=*to* transformation rules, or *template*=*action* in Gema terms. I see no way to define a *template* that will never ever match anything, this alone not seems to be the way.
## Gema, 18 characters
```
*\n=c:\=@line\;:$0
```
Transforms `e=3` into `c:=1;:e=3`.
Luckily in Gema there are *domains*, kind of namespaces. The above code defines the dummy rules in namespace c, that we never use. Unfortunately a mentioned domain remains in effect until the end of line, so we have to explicitly to switch back to default domain.
## Gema, 18 characters
```
*\n=@line\=\$0\;$0
```
Transforms `e=3` into `1=$0;e=3`.
A less complicated alternative is to use effectless code instead of ignored one. I mean to put back exactly what was matched.
[Answer]
# Kotlin extension function, 69 60 bytes
`fun String.a()=lines().mapIndexed{i,s->"/*$i*/$s"}.joinToString("\n")`
`fun String.a(){lines().mapIndexed{i,s->println("/*$i*/$s")}}`
Example usage:
```
fun main(args: Array<String>) {
//language=kotlin
val code = """fun main(args: Array<String>) {
println("Hello world!")
}"""
code.a()
}
```
Output:
```
/*0*/fun main(args: Array<String>) {
/*1*/ println("Hello world!")
/*2*/}
```
[Answer]
# BASH (+ GNU sed) 27 bytes
```
sed 'i#
='|sed 'N;s/\n//;N'
```
The first part (`i#` `\n` `=`) almost works in GNU sed (for 4 bytes), but it puts a newline after the `#`.
[Answer]
# APL (Dyalog Unicode), 53 bytes
```
N←(⍴P)[0]⋄P←((2×N)⍴0 1)⍀P⋄P[2×⍳N;]←⊂[1](N⍴'⍝'),[.5]⍳N
```
[Try it on TryAPL.org!](https://tryapl.org/?clear&q=%E2%8E%95IO%E2%86%900%E2%8B%84P%E2%86%905%201%E2%8D%B4%27line1%27%20%27anotherline%27%20%27yet%20another%27%20%27next%20to%20the%20last%27%20%27last%20line%27%E2%8B%84N%E2%86%90(%E2%8D%B4P)%5B0%5D%E2%8B%84P%E2%86%90((2%C3%97N)%E2%8D%B40%201)%E2%8D%80P%E2%8B%84P%5B2%C3%97%E2%8D%B3N%3B%5D%E2%86%90%E2%8A%82%5B1%5D(N%E2%8D%B4%27%E2%8D%9D%27)%2C%5B.5%5D%E2%8D%B3N%E2%8B%84P&run)
The environmental variable ⎕IO←0. The program to comment is contained in an (n 1) nested array of string statements. The result is returned in the same (expanded) array.
[Answer]
# CJam, 21 Bytes
I am not well-versed in CJam at all, but I knew for a fact it has comments :)
```
qN%ee{"e#"o(oNo(oNo}/
```
Explanation coming soon.
[Answer]
# Mathematica, 58 bytes
```
i = 1; StringReplace[#, StartOfLine :> "(*" <> ToString@i++ <> "*)"] &
```
[Answer]
# jq, 31 characters
(27 characters code + 4 characters command line options.)
```
"#\(input_line_number)\n"+.
```
In jq there are only line comments, starting with `#`.
Sample run:
```
bash-4.3$ cat l33t.jq
gsub("e";"3")|
gsub("g";"9")|
gsub("i";"1")|
gsub("o";"0")|
gsub("t";"7")
bash-4.3$ jq -Rr -f l33t.jq <<< 'Hello World!'
H3ll0 W0rld!
bash-4.3$ jq -Rr '"#\(input_line_number)\n"+.' l33t.jq > l33t-nr.jq
bash-4.3$ cat l33t-nr.jq
#1
gsub("e";"3")|
#2
gsub("g";"9")|
#3
gsub("i";"1")|
#4
gsub("o";"0")|
#5
gsub("t";"7")
bash-4.3$ jq -Rr -f l33t-nr.jq <<< 'Hello World!'
H3ll0 W0rld!
```
[Answer]
# GolfScript, 23 Bytes
```
n/0:i;{"#"i):i+n+\+}%n*
```
There are only line comments starting with "#".
Ungolfed & explained:
```
# the input is pushed on the stack automatically
n # n is a predefined variable for "\n"
/ # splits the input string with the previously pushed "\n" as delimiter
0:i; # i = 0
{ # A code block: It is used for map here (going through the input)
"#" # push a "#" onto the stack
i):i # save i + 1 in i, the value is again not popped from the stack
+ # implicitly converts the number i to a string and concatenates "#" with it
n # newline
+ # add a newline (# introduces a *line* comment)
\ # switch the top to elements (-> yields the comment as the bottom, and the line as the top element on the stack)
+ # concatenate them
} # end of the code block
% # map
n # newline
* # join the list with newlines between them
# outputs are done implicitly
```
I am pretty sure that this can be further simplified, especially the `i` can probably be left out.
You can test it here: <https://golfscript.apphb.com/>
Because this site doesn't support adding inputs, you'll have to put a string surrounded with double quotes in front of the code. `'\n'` will be a newline. Be aware of the fact, that there are other escape sequences as well. User `'\\'` if you are not sure.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 54 bytes
```
a;main(i){for(;gets(&a);)printf("/*%d*/%s\n",i++,&a);}
```
[Try it online!](https://tio.run/##NY3LDoIwEEX3fsUEg2kLWvBtqn6Jm6bl0QSB8IgLwrfXKdbZzJ175s6obaGUtVK8pamJoVPedEQU2dCTjaSCtp2ph5wEnIWa8bB/1UFsoih2cLaWswQYX5taVaPO4N4P2jS78rniLEWAWVgOUzT2aEzYD9gBS5WyAyXQOf4deAC@doBQB04e6AaHsx/cjYvXrtrxl1BL5OrJjPrm9ac0VQZ@IU0Yn78 "C (gcc) – Try It Online")
Why not
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 35 bytes
Revisited this question and found a shorter solution. It saves a few bytes to append `//` comments instead prepending `/**/` ones.
```
a=>a.replace(/$/gm,_=>"//"+v++,v=1)
```
[Try it online!](https://tio.run/##TYzBCoMwEETvfsUSethFm9Bzib9St2liLepKkgpS@u2p3noZGN68efHKycVhyedZHr4EW9i2rKNfRnYezcn0U3OzrTJG1WtdN6u9UHEyJxm9HqXHgJ16Jw8px8Flda2GaZGY4QNBBL4QokygtLlz3OFhZtjAAhLY9tgg6fz0M/LR/5@Z6FptuEdHVH4 "JavaScript (Node.js) – Try It Online")
# JavaScript, 47 bytes
Old answer:
```
a=>a.split`
`.map((l,i)=>"/*"+i+"*/"+l).join`
`
```
[Answer]
# C# 6, ~~66~~ 63 bytes
Thanks to CSharpie
~~(666, devils code ^^)~~ not any more ...
This works for all languages using "C style comments" (C, C++, C#, Java, ....)
It simply splits the string into lines, prepends every line with its index and joins the edited lines again with new line characters.
```
s=>string.Join("\n",s.Split('\n').Select((l,i)=>$"/*{i}*/"+l));
```
old version:
```
s=>string.Join("\n",s.Split('\n').Select((l,i)=>$"/*{i,3}*/{l}"));
```
[Answer]
## Python 2, 82 bytes
Works for space-only indentation
```
for i,l in enumerate(input().split('\n')):print l.split(l.lstrip())[0]+'#%d\n'%i+l
```
Indentation-less version for 56 bytes
```
for x in enumerate(input().split('\n')):print'#%d\n%s'%x
```
[Answer]
# [Nim](https://nim-lang.org/), 52 bytes
```
var n=0
for l in stdin.lines:n+=1;echo "#[",n,"]#",l
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3TcoSixTybA240vKLFHIUMvMUiktSMvP0cjLzUout8rRtDa1TkzPyFZSUo5V08nSUYpWVdHIgeqFGLLipmZNaolBhC9FYlJqY4piTw1WekZmTqlChaKtkoGTFpQA2pAKiAwA)
Nim is indentation-sensitive, but it doesn't seem to have a problem with comments before indentation.
[Answer]
# Haskell, 84 bytes
Assumes each indentation is done by a horizontal tab(`\t`).
```
unlines.zipWith(\n l->let(x,y)=span('\t'==)l in x++"{-"++show n++"-}"++y)[0..].lines
```
[Answer]
## Pascal, 198 bytes
* This is a full Pascal `program` as per ISO standard 10206 “Extended Pascal.”
Pascal does not permit multiline literals.
String and character literals spanning multiple lines are explicitly banned.
Therefore there is no problem with that.
* The `program` only works correctly for up to `maxInt + 1` input lines (zero-based indexing).
`MaxInt` is an implementation-defined value.
There is no safeguard installed when exceeding this limit.
* A *line* is a possibly empty sequence of characters *terminated* by a special “end of line character.”
This `program` might possibly number *non-lines*, too.
At any rate *empty* input is not numbered.
```
program p(input,output);var n:integer;c:char;begin n:=0;while not EOF do begin write('{',n,'}');repeat read(c);write(c)until EOF or_else EOLn;if not EOF then begin writeLn;read(c)end;n:=n+1 end end.
```
Expanded and annotated:
```
program prependLineNumberComment(input, output);
var
{ Contains the currently processed `input` line number. }
lineNumber: integer value 0;
{ Identifiers of buffer variables (`input↑`, `output↑`) are too long. }
c: char;
begin
while not EOF do
begin
write('{ ', lineNumber, ' }');
lineNumber ≔ succ(lineNumber);
{ Copy `input` to `output`. }
repeat
begin
{ This is equivalent to: `c ≔ input↑; get(input);`: }
read(c);
{ This is equivalent to: `output↑ ≔ c; put(output);`: }
write(c);
end
{ Invoking `EOLn(input)` if `EOF(input)` is `true` is fatal. }
until EOF or_else EOLn;
{ `get(input)` requires that `EOF(input)` is `false`. }
if not EOF then
begin
{ The only valid method for producing a newline character is: }
writeLn;
{ Advance reading cursor for the embracing `while`‑loop. }
read(c); { Shorter than `get(input);` }
end;
end;
end.
```
] |
[Question]
[
The goal of this code golf is to create a program or function that calculates and outputs the cube root of a number that's given as input.
The rules:
* No external resources
* No use of built-in cube root functions.
* No use of methods/operators that can raise a number to a power (that includes square root, 4th root, etc.).
* Your function/program must be able to accept floating-point numbers and negative numbers as input.
* If the cube root is a floating-point number, then round it to 4 numbers after the decimal point.
* This is a code golf, the shortest code in bytes wins.
Test cases:
```
27 --> 3
64 --> 4
1 --> 1
18.609625 --> 2.65
3652264 --> 154
0.001 --> 0.1
7 --> 1.9129
```
You can use all test cases above to test negative numbers (`-27 --> -3`, `-64 --> -4` ...)
[Answer]
# Haskell - 35
```
c n=(iterate(\x->(x+n/x/x)/2)n)!!99
```
Example runs:
```
c 27 => 3.0
c 64 => 4.0
c 1 => 1.0
c 18.609625 => 2.6500000000000004 # only first 4 digits are important, right?
c 3652264 => 154.0
c 0.001 => 0.1
c 7 => 1.9129311827723892
c (-27) => -3.0
c (-64) => -4.0
```
Moreover, if you import `Data.Complex`, it even works on complex numbers, it returns one of the roots of the number (there are 3):
```
c (18:+26) => 3.0 :+ 1.0
```
The `:+` operator should be read as 'plus *i* times'
[Answer]
## SageMath, (69) 62 bytes
However, don't ever believe it will give you the result, it's very difficult to go randomly through all the numbers:
```
def r(x):
y=0
while y*y*y-x:y=RR.random_element()
return "%.4f"%y
```
if you didn't insist on truncating:
```
def r(x):
y=0
while y*y*y-x:y=RR.random_element()
return y
```
## SageMath, 12 bytes, if `exp` is allowed
Works for all stuff: positive, negative, zero, complex, ...
```
exp(ln(x)/3)
```
[Answer]
# J: 16 characters
Loose translation of the Haskell answer:
```
-:@((%*~)+])^:_~
```
Test cases:
```
-:@((%*~)+])^:_~27
3
-:@((%*~)+])^:_~64
4
-:@((%*~)+])^:_~1
1
-:@((%*~)+])^:_~18.609625
2.65
-:@((%*~)+])^:_~3652264
154
-:@((%*~)+])^:_~0.001
0.1
-:@((%*~)+])^:_~7
1.91293
```
It works like this:
```
(-:@((% *~) + ])^:_)~ 27
↔ 27 (-:@((% *~) + ])^:_) 27
↔ 27 (-:@((% *~) + ])^:_) 27 (-:@((% *~) + ])) 27
↔ 27 (-:@((% *~) + ])^:_) -: ((27 % 27 * 27) + 27)
↔ 27 (-:@((% *~) + ])^:_) 13.5185
↔ 27 (-:@((% *~) + ])^:_) 27 (-:@((% *~) + ])) 13.5185
↔ 27 (-:@((% *~) + ])^:_) -: ((27 % 13.5185 * 13.5185) + 13.5185)
↔ 27 (-:@((% *~) + ])^:_) 6.83313
...
```
In words:
```
half =. -:
of =. @
divideBy =. %
times =. *
add =. +
right =. ]
iterate =. ^:
infinite =. _
fixpoint =. iterate infinite
by_self =. ~
-:@((%*~)+])^:_~ ↔ half of ((divideBy times by_self) add right) fixpoint by_self
```
Not one of the best wordy translations, since there's a dyadic fork and a `~` right at the end.
[Answer]
## Python - 62 bytes
```
x=v=input()
exec"x*=(2.*v+x*x*x)/(v+2*x*x*x or 1);"*99;print x
```
Evaluates to full floating point precision. The method used is [Halley's method](http://en.wikipedia.org/wiki/Halley%27s_method). As each iteration produces 3 times as many correct digits as the last, *99* iterations is a bit of overkill.
Input/output:
```
27 -> 3.0
64 -> 4.0
1 -> 1.0
18.609625 -> 2.65
3652264 -> 154.0
0.001 -> 0.1
7 -> 1.91293118277
0 -> 1.57772181044e-30
-2 -> -1.25992104989
```
[Answer]
## Perl, 92 bytes
```
sub a{$x=1;while($d=($x-$_[0]/$x/$x)/3,abs$d>1e-9){$x-=$d}$_=sprintf'%.4f',$x;s/\.?0*$//;$_}
```
* The function `a` returns a string with the number without
an unnecessary fraction part or insignificant zeroes at the right end.
Result:
```
27 --> 3
-27 --> -3
64 --> 4
-64 --> -4
1 --> 1
-1 --> -1
18.609625 --> 2.65
-18.609625 --> -2.65
3652264 --> 154
-3652264 --> -154
0.001 --> 0.1
-0.001 --> -0.1
7 --> 1.9129
-7 --> -1.9129
0.0000000000002 --> 0.0001
-0.0000000000002 --> -0.0001
0 --> 0
-0 --> 0
```
Generated by
```
sub test{
my $a = shift;
printf "%16s --> %s\n", $a, a($a);
printf "%16s --> %s\n", "-$a", a(-$a);
}
test 27;
test 64;
test 1;
test 18.609625;
test 3652264;
test 0.001;
test 7;
test "0.0000000000002";
test 0;
```
The calculation is based on [Newton's method](http://en.wikipedia.org/wiki/Newton%27s_method):

[Answer]
## Javascript (55)
`function f(n){for(i=x=99;i--;)x=(2*x+n/x/x)/3;return x}`
**BONUS, General formulation for all roots**
`function f(n,p){for(i=x=99;i--;)x=x-(x-n/Math.pow(x,p-1))/p;return x}`
For cube root, just use `f(n,3)`, square root `f(n,2)`, etc...
Example : `f(1024,10)` returns `2`.
**Explanation**
Based on Newton method :
Find : `f(x) = x^3 - n = 0`, the solution is `n = x^3`
The derivation : `f'(x) = 3*x^2`
Iterate :
`x(i+1) = x(i) - f(x(i))/f'(x(i)) = x(i) + (2/3)*x + (1/3)*n/x^2`
**Tests**
```
[27,64,1,18.609625,3652264,0.001,7].forEach(function(n){console.log(n + ' (' + -n + ') => ' + f(n) + ' ('+ f(-n) +')')})
27 (-27) => 3 (-3)
64 (-64) => 4 (-4)
1 (-1) => 1 (-1)
18.609625 (-18.609625) => 2.65 (-2.65)
3652264 (-3652264) => 154 (-154)
0.001 (-0.001) => 0.09999999999999999 (-0.09999999999999999)
7 (-7) => 1.912931182772389 (-1.912931182772389)
```
[Answer]
## PHP - 81 bytes
Iterative solution:
```
$i=0;while(($y=abs($x=$argv[1]))-$i*$i*$i>1e-4)$i+=1e-5;@print $y/$x*round($i,4);
```
[Answer]
# APL - 31
```
(×X)×+/1,(×\99⍴(⍟|X←⎕)÷3)÷×\⍳99
```
Uses the fact that `cbrt(x)=e^(ln(x)/3)`, but instead of doing naive `⋆` exponentiation, it computes `e^x` using Taylor/Maclaurin series.
Sample runs:
```
⎕: 27
3
⎕: 64
4
⎕: 1
1
⎕: 18.609625
2.65
⎕: 3652264
154
⎕: 0.001
0.1
⎕: 7
1.912931183
⎕: ¯27
¯3
⎕: ¯7
¯1.912931183
```
Seeing as there's a [J answer](https://codegolf.stackexchange.com/a/21871/7162) in 16 characters, I must be really terrible at APL...
[Answer]
## Java, 207 182 181
Sometimes when I play golf I have two many beers and play really really bad
```
class n{public static void main(String[]a){double d=Double.valueOf(a[0]);double i=d;for(int j=0;j<99;j++)i=(d/(i*i)+(2.0*i))/3.0;System.out.println((double)Math.round(i*1e4)/1e4);}}
```
Iterative Newton's Method of Approximation, runs 99 iterations.
Here is the unGolfed:
```
class n{
public static void main(String a[]){
//assuming the input value is the first parameter of the input
//arguments as a String, get the Double value of it
double d=Double.valueOf(a[0]);
//Newton's method needs a guess at a starting point for the
//iterative approximation, there are much better ways at
//going about this, but this is by far the simplest. Given
//the nature of the problem, it should suffice fine with 99 iterations
double i=d;
//make successive better approximations, do it 99 times
for(int j=0;j<99;j++){
i=( (d/(i*i)) + (2.0*i) ) / 3.0;
}
//print out the answer to standard out
//also need to round off the double to meet the requirements
//of the problem. Short and sweet method of rounding:
System.out.println( (double)Math.round(i*10000.0) / 10000.0 );
}
}
```
[Answer]
# TI-Basic, ~~26~~ 24 bytes
```
Input :1:For(I,1,9:2Ans/3+X/(3AnsAns:End
```
[Answer]
## Js 57 bytes
`f=(x)=>eval('for(w=0;w**3<1e12*x;w++);x<0?-f(-x):w/1e4')`
```
f=(x)=>eval('for(w=0;w**3<1e12*x;w++);x<0?-f(-x):w/1e4')
document.getElementById('div').innerHTML += f(-27) + '<br>'
document.getElementById('div').innerHTML += f(-64) + '<br>'
document.getElementById('div').innerHTML += f(-1) + '<br>'
document.getElementById('div').innerHTML += f(-18.609625) + '<br>'
document.getElementById('div').innerHTML += f(-3652264) + '<br>'
document.getElementById('div').innerHTML += f(-0.001) + '<br>'
document.getElementById('div').innerHTML += f(-7) + '<br><hr>'
document.getElementById('div').innerHTML += f(27) + '<br>'
document.getElementById('div').innerHTML += f(64) + '<br>'
document.getElementById('div').innerHTML += f(1) + '<br>'
document.getElementById('div').innerHTML += f(18.609625) + '<br>'
document.getElementById('div').innerHTML += f(3652264) + '<br>'
document.getElementById('div').innerHTML += f(0.001) + '<br>'
document.getElementById('div').innerHTML += f(7) + '<br>'
```
```
<div id="div"></div>
```
[Answer]
## Javascript: 73/72 characters
This algorithm is lame, and exploits the fact that this question is limited to 4 digits after the decimal point. It is a modified version of the algorithm that I suggested in the sandbox for the purpose of reworking the question. It counts from zero to the infinite while `h*h*h<a`, just with a multiplication and division trick to handle the 4 decimal digits pecision.
```
function g(a){if(a<0)return-g(-a);for(h=0;h*h*h<1e12*a;h++);return h/1e4}
```
Edit, 4 years later: As suggested by Luis felipe De jesus Munoz, by using `**` the code is shorter, but that feature was not available back in 2014 when I wrote this answer. Anyway, by using it, we shave an extra character:
```
function g(a){if(a<0)return-g(-a);for(h=0;h**3<1e12*a;h++);return h/1e4}
```
[Answer]
## Javascript - 157 characters
This function:
* Handle negative numbers.
* Handle floating-pointing numbers.
* Execute quickly for any input number.
* Has the maximum precision allowed for javascript floating-point numbers.
```
function f(a){if(p=q=a<=1)return a<0?-f(-a):a==0|a==1?a:1/f(1/a);for(v=u=1;v*v*v<a;v*=2);while(u!=p|v!=q){p=u;q=v;k=(u+v)/2;if(k*k*k>a)v=k;else u=k}return u}
```
Ungolfed explained version:
```
function f(a) {
if (p = q = a <= 1) return a < 0 ? -f(-a) // if a < 0, it is the negative of the positive cube root.
: a == 0 | a == 1 ? a // if a is 0 or 1, its cube root is too.
: 1 / f (1 / a); // if a < 1 (and a > 0) invert the number and return the inverse of the result.
// Now, we only need to handle positive numbers > 1.
// Start u and v with 1, and double v until it becomes a power of 2 greater than the given number.
for (v = u = 1; v * v * v < a; v *= 2);
// Bisects the u-v interval iteratively while u or v are changing, which means that we still did not reached the precision limit.
// Use p and q to keep track of the last values of u and v so we are able to detect the change.
while (u != p | v != q) {
p = u;
q = v;
k = (u + v) / 2;
if (k * k * k > a)
v=k;
else
u=k
}
// At this point u <= cbrt(a) and v >= cbrt(a) and they are the closest that is possible to the true result that is possible using javascript-floating point precision.
// If u == v then we have an exact cube root.
// Return u because if u != v, u < cbrt(a), i.e. it is rounded towards zero.
return u
}
```
[Answer]
# PHP, 61
Based on Newton's method. Slightly modified version of [Michael's answer](https://codegolf.stackexchange.com/a/21774/13847):
```
for($i=$x=1;$i++<99;)$x=(2*$x+$n/$x/$x)/3;echo round($x,14);
```
It works with negative numbers, can handle floating point numbers, and rounds the result to 4 numbers after the decimal point if the result is a floating point number.
[**Working demo**](https://eval.in/104560)
[Answer]
# Befunge 98 - Work in progress
This language does not support floating point numbers; this attempts to emulate them. It currently works for positive numbers that do not start with `0` after the decimal point (mostly). However, it only outputs to 2 decimal places.
```
&5ka5k*&+00pv
:::**00g`!jv>1+
/.'.,aa*%.@>1-:aa*
```
It works by inputting the part before the decimal point, multiplying that by `100000`, then inputting the part after the point and adding the two numbers together. The second line does a counter until the cube is greater than the inputted number. Then the third line extracts the decimal number from the integer.
If anyone can tell me why the third line only divides by `100` to get the correct values, please tell me.
IOs:
```
27.0 3 .0
64.0 4 .0
1.0 1 .0
18.609625 2 .65
0.001 0 .1
7.0 1 .91
0.1 0 .1
```
[Answer]
# Smalltalk, 37
credit goes to mniip for the algorithm; Smalltalk version of his code:
input in n; output in x:
```
1to:(x:=99)do:[:i|x:=2*x+(n/x/x)/3.0]
```
or, as a block
```
[:n|1to:(x:=99)do:[:i|x:=2*x+(n/x/x)/3.0].x]
```
[Answer]
# GameMaker Language, 51 bytes
```
for(i=x=1;i++<99;1)x=(2*x+argument0/x/x)/3;return x
```
[Answer]
## Haskell: 99C
Can't beat @mniip in cleverness. I just went with a binary search.
```
c x=d 0 x x
d l h x
|abs(x-c)<=t=m
|c < x=d m h x
|True=d l m x
where m=(l+h)/2;c=m*m*m;t=1e-4
```
Ungolfed:
```
-- just calls the helper function below
cubeRoot x = cubeRoot' 0 x x
cubeRoot' lo hi x
| abs(x-c) <= tol = mid -- if our guess is within the tolerance, accept it
| c < x = cubeRoot' mid hi x -- shot too low, narrow our search space to upper end
| otherwise = cubeRoot' lo mid x -- shot too high, narrow search space to lower end
where
mid = (lo+hi)/2
cubed = mid*mid*mid
tol = 0.0001
```
[Answer]
## J 28
```
*@[*(3%~+:@]+(%*~@]))^:_&|&1
```
Using Newtons method, finding the root of `x^3 - X` the update step is `x - (x^3 - C)/(3*x^2)`, where x is the current guess, and C the input. Doing the maths on this one yields the ridiculously simple expression of `(2*x+C/x^2) /3` . Care has to be taken for negative numbers.
Implemented in J, from right to left:
1. `|` Take abs of both arguments, pass them on
2. `^:_` Do until convergence
3. `(%*~@])` is `C / x^2` (`*~ y` is equivalent to `y * y`)
4. `+:@]` is `2 x`
5. `3%~` divide by three. This yields the positive root
6. `*@[ * positive_root` multiplies positive root with the signum of C.
Test run:
```
NB. give it a name:
c=: *@[*(3%~+:@]+(%*~@]))^:_&|&1
c 27 64 1 18.609625 3652264 0.001 7
3 4 1 2.65 154 0.1 1.91293
```
[Answer]
## AWK, 53 bytes
```
{for(n=x=$1;y-x;){y=x;x=(2*x+n/x/x)/3}printf"%.4g",y}
```
Example usage:
```
$ awk '{for(n=x=$1;y-x;){y=x;x=(2*x+n/x/x)/3}printf"%.4g",y}' <<< 18.609625
2.65$
```
Thanks go to @Mig for the `JavaScript` solution which this is derived from. It runs surprisingly quickly given that the `for` loop requires the iteration to stop changing.
[Answer]
# C, 69 bytes
```
i;float g(float x){for(float y=x;++i%999;x=x*2/3+y/3/x/x);return x;}
```
Just another implementation of Newton's method. [Try it online!](https://tio.run/nexus/c-gcc#NY/dqsIwEITv@xSDIjT2J3iKFyXWJ/Emx3Y1kCbSphiRvrqxOXpg2WGH@WB2rcxZT213GF2rbHk9Jut/p5fuuhhBCdJWOlzSj3r2JDt8j0fjRZapTV3Xwjd@@8Or7MEr7rlnYujcNBh4MQdlHHqpTMqeCRB5tHb61R2oKfYCdIgra8odGGIEuA0LRClWG8LfnMwqB@W42Xu6yK7kFctjLQYmFmRO5vA6k5aXMRREcnRF/CEUun8D "C (gcc) – TIO Nexus")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437
```
╘♀┘A╕äO¶∩'
```
[Run and debug online!](https://staxlang.xyz/#c=%E2%95%98%E2%99%80%E2%94%98A%E2%95%95%C3%A4O%C2%B6%E2%88%A9%27&i=27%0A64%0A1%0A18.609625%0A3652264%0A0.001%0A7&a=1&m=2)
## Explanation
Uses the unpacked version to explain.
```
gpJux*_+h4je
gp Iterate until a fixed point is found, output the fix point
Ju Inverse of square
x* Multiplied by input
_+h Average of the value computed by last command and the value at current iteration
4je Round to 4 decimal digits
```
[Answer]
**JAVA Solution**
public BigDecimal cubeRoot(BigDecimal number) {
```
if(number == null || number.intValue() == 0) return BigDecimal.ZERO;
BigDecimal absNum = number.abs();
BigDecimal t;
BigDecimal root = absNum.divide(BigDecimal.valueOf(3), MathContext.DECIMAL128);
do {
t = root;
root = root.multiply(BigDecimal.valueOf(2))
.add(absNum.divide(root.multiply(root), MathContext.DECIMAL128))
.divide(BigDecimal.valueOf(3), MathContext.DECIMAL128);
} while (t.toBigInteger().subtract(root.toBigInteger()).intValue() != 0);
return root.multiply(number.divide(absNum), MathContext.DECIMAL128);
}
```
[Answer]
**Python Solution**
```
def cube_root(num):
if num == 0:
return 0
t = 0
absNum = abs(num)
root = absNum/3
while (t - root) != 0:
t = root
root = (1/3) * ((2 * root) + absNum/(root * root))
return root * (num / absNum)
```
[Answer]
# MMIX, 44 bytes (11 instrs)
```
E0013FF0 48000002 E8018000 C1FF0100
1001FFFF 14010001 040101FF E401FFF0
11FF01FF 53FFFFFA F8020000
```
# Disassembly
```
cbrt SETH $1,#3FF0 // y = 1.
BNN $0,0F // if(x >= 0) goto loop (ensuring sign is correct)
ORH $1,#8000 // y = fnabs(y) (bit tricks!)
0H SET $255,$1 // loop: prev = y
FMUL $1,$255,$255 // y = prev *. prev
FDIV $1,$0,$1 // y = x /. y
FADD $1,$1,$255 // y = y +. prev
INCH $1,#FFF0 // y = y /. 2. (bit tricks again)
FCMPE $255,$1,$255 // prev = comp_eps(y, prev)
PBNZ $255,0B // if(prev) goto loop
POP 2,0 // return {y,x}
```
It is up to the caller to set a suitable value of `rE`. Much faster convergence may be arranged by essentially setting `y` up by dividing the exponent by 3, but that costs another four instructions (though in time it pays really quickly, since three `FDIV`s cost about the same amount as two `DIV`s):
```
cbrt SLU $1,$0,1 // 3B010001 shift left to erase sign
INCH $1,#8020 // E4018020 unbias exponent
DIV $1,$1,3 // 1D010103 divide by 3 as integer; approximate cube root
INCH $1,#7FE0 // E4017FE8 rebias exponent
SRU $1,$1,1 // 3F010101 shift right again
```
and then continue from the second line in the original.
If mispredicted branches are particularly expensive, I would also replace the second and third lines of the original with:
```
ZSN $255,$0,1 // 71020001 $255 = ($0 neg? 1 : 0)
SLU $255,$255,63 // 3B02023F $255 <<= 63
OR $1,$1,$255 // C0010102 $1 |= $255
```
This costs one more instruction, but is branchless.
] |
[Question]
[
True color (24-bit) at [Wikipedia](https://en.wikipedia.org/wiki/Color_depth#True_color_(24-bit)) is described in pertinent part as
>
> 24 bits almost always uses 8 bits of each of R, G, B. As of 2018
> 24-bit color depth is used by virtually every computer and phone
> display and the vast majority of image storage formats. Almost all
> cases where there are 32 bits per pixel mean that 24 are used for the
> color, and the remaining 8 are the alpha channel or unused.
>
>
> 224 gives 16,777,216 color variations. The human eye can discriminate up to ten million colors[[10]](https://en.wikipedia.org/wiki/Color_depth#cite_note-10) and since the gamut of a display is smaller than the range of human vision, this means this should cover that range with more detail than can be perceived. ...
>
>
> ...
>
>
> Macintosh systems refer to 24-bit color as "millions of colors". The term "True color" is sometime used to mean what this article is calling "Direct color".[[13]](https://en.wikipedia.org/wiki/Color_depth#cite_note-13) It is also often used to refer to all color depths greater or equal to 24.
>
>
> [](https://upload.wikimedia.org/wikipedia/commons/e/e9/16777216colors.png)
>
>
> All 16,777,216 colors
>
>
>
## Task
Write a program which generates and returns all 16,777,216 color variations within an array as strings in the CSS [`rgb()`](https://drafts.csswg.org/css-color/#rgb-functions) function
>
> 5.1. The RGB functions: `rgb()` and `rgba()`
>
>
> The `rgb()` function defines an RGB color by specifying the red,
> green, and blue channels directly. Its syntax is:
>
>
>
> ```
> rgb() = rgb( <percentage>{3} [ / <alpha-value> ]? ) |
> rgb( <number>{3} [ / <alpha-value> ]? )
> <alpha-value> = <number> | <percentage>
>
> ```
>
> The first three arguments specify the red, green, and blue channels of
> the color, respectively. `0%` represents the minimum value for that
> color channel in the sRGB gamut, and `100%` represents the maximum
> value. A `<number>` is equivalent to a `<percentage>`, but with a
> different range: `0` again represents the minimum value for the color
> channel, but `255` represents the maximum. These values come from the
> fact that many graphics engines store the color channels internally as
> a single byte, which can hold integers between 0 and 255.
> Implementations should honor the precision of the channel as authored
> or calculated wherever possible. If this is not possible, the channel
> should be rounded to the closest value at the highest precision used,
> rounding up if two values are equally close.
>
>
> The final argument, the `<alpha-value>`, specifies the alpha of the
> color. If given as a `<number>`, the useful range of the value is `0`
> (representing a fully transparent color) to `1` (representing a fully
> opaque color). If given as a , `0%` represents a fully
> transparent color, while `100%` represents a fully opaque color. If
> omitted, it defaults to `100%`.
>
>
> Values outside these ranges are not invalid, but are clamped to the
> ranges defined here at computed-value time.
>
>
> For legacy reasons, `rgb()` also supports an alternate syntax that
> separates all of its arguments with commas:
>
>
>
> ```
> rgb() = rgb( <percentage>#{3} , <alpha-value>? ) |
> rgb( <number>#{3} , <alpha-value>? )
>
> ```
>
> Also for legacy reasons, an `rgba()` function also exists, with an
> identical grammar and behavior to `rgb()`.
>
>
>
or RGB hexadecimal notation [`#RRGGBB`](https://drafts.csswg.org/css-color/#hex-notation) format
>
> 5.2. The RGB hexadecimal notations: `#RRGGBB`
>
>
> The CSS ***hex color*** notation allows a color to be specified by
> giving the channels as hexadecimal numbers, which is similar to how
> colors are often written directly in computer code. It’s also shorter
> than writing the same color out in `rgb()` notation.
>
>
> The syntax of a `<hex-color>` is a `<hash-token>` token whose value
> consists of 3, 4, 6, or 8 hexadecimal digits. In other words, a hex
> color is written as a hash character, "#", followed by some number of
> digits 0-9 or letters a-f (the case of the letters doesn’t matter -
> `#00ff00` is identical to `#00FF00`).
>
>
> The number of hex digits given determines how to decode the hex
> notation into an RGB color:
>
>
> **6 digits**
>
>
> The first pair of digits, interpreted as a hexadecimal number, specifies the red channel of the color, where `00` represents the
> minimum value and `ff` (255 in decimal) represents the maximum. The
> next pair of digits, interpreted in the same way, specifies the green
> channel, and the last pair specifies the blue. The alpha channel of
> the color is fully opaque.
>
>
>
> >
> > EXAMPLE 2
> > In other words, `#00ff00` represents the same color as `rgb(0 255 0)` (a lime green).
> >
> >
> >
>
>
>
See [Editor's Draft of CSS Color Module Level 4](https://drafts.csswg.org/css-color)
## **Examples**
**CSS `rgb()` function** ([space character](https://codegolf.stackexchange.com/questions/172716/true-color-code#comment416956_172716) can be substituted for comma character, e.g., `rgb(0 255 0)`)
```
// `rgb()` `<percentage>` as strings in resulting array
['rgb(0%,0%,0%)', ...,'rgb(0%,255%,0)', ...'rgb(255,255,255)']
// `rgb()` `<number>` as strings in resulting array
['rgb(0,0,0)', ...,'rgb(0,255,0)', ...'rgb(255,255,255)']
```
**CSS RGB hexadecimal notation `RRGGBB`**
```
// RGB hexadecimal notation as strings in resulting array
['#000000', ...,'#00ff00', ...'#ffffff']
```
## Winning criteria
Least bytes used to write the program.
[Answer]
# [R](https://www.r-project.org/), 25 bytes
```
sprintf("#%06X",1:2^24-1)
```
[Try it online!](https://tio.run/##K/qfnJ9TbKP7v7igKDOvJE1DSVnVwCxCScfQyijOyETXUPN/RmpiigZIlY6hgSZXSWJmDoSnAOLmpOall2SABTT/AwA "R – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~77~~ ~~40~~ ~~39~~ 37 bytes
```
print['#%06X'%c for c in range(8**8)]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM68kWl1Z1cAsQl01WSEtv0ghWSEzT6EoMS89VcNCS8tCM/b/fwA "Python 2 – Try It Online")
-1 byte thanks to Digital Trauma
-2 bytes thanks to dylnan
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~28~~ 26 bytes
```
1..16mb|%{"#{0:x6}"-f--$_}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPz9AsN6lGtVpJudrAqsKsVkk3TVdXJb72/38A "PowerShell – Try It Online")
Loops from `1` to `16mb` (16777216). Each iteration, we use the `-f`ormat operator acting on the current number pre-decremented `--$_` against the string `"#{0:x6}"`. Here, we're specifying he`x` values, padded to `6` digits, with a hash `#` in front. On TIO, limited to 60 seconds / 128KiB of output. Change the `1` to `(16mb-5)` to see [how it ends](https://tio.run/##K8gvTy0qzkjNyfn/X8PQLDdJ11RTTw/EqFGtVlKuNrCqMKtV0k3T1VWJr/3/HwA "PowerShell – Try It Online").
[Answer]
# JavaScript (ES7), ~~65~~ ~~62~~ 61 bytes
*Saved ~~3~~ 4 bytes thanks to @tsh*
Returns an array of `#RRGGBB` strings.
```
_=>[...Array(n=8**8)].map(_=>'#'+(n++).toString(16).slice(1))
```
[Try it online!](https://tio.run/##TY3LCsIwEEX3fsWAi8w0Gmyhj00Ev8GliITaltQ2CUkt9OtjFoJu7zmcO6pVhdZrtxyNfXaxl/EhzzchxMV7taGRTZY1dBezcpgI2zOOhnMSi70uXpsB84pEmHTbYU4UfRdAQo@0a60JdurEZAdM69c5HYqyJjFabZABI@DAANMfhJd2LgVhVmaDVU3vlEqAIBkcfom8qus6L4u/CsUP "JavaScript (Node.js) – Try It Online")
(truncated output)
[Answer]
# Common Lisp, 42 bytes
```
(dotimes(i 16777216)(format t"#~6,'0x "i))
```
[Try it online!](https://tio.run/##S87JLC74/18jJb8kMze1WCNTwdDM3NzcyNBMUyMtvyg3sUShREm5zkxH3aBCQSlTU/P/fwA)
[Answer]
# Japt, 14 bytes
Outputs as `#rrggbb`.
```
G²³ÇsG ùT6 i'#
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=R7PHc0cg+VQ2IGknIw==&input=LVM=) (Limited to the first 4096 elements)
---
## Explanation
```
G :16
² :Squared
³ :Cubed
Ç :Map the range [0,result)
sG : Convert to base-16 string
ù : Left pad
T : With 0
6 : To length 6
i'# : Prepend "#"
```
[Answer]
## Haskell, 41 bytes
```
l="ABCDEF"
mapM id$"#":(['0'..'9']++l<$l)
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzexwFchM0VFSVnJSiNa3UBdT0/dUj1WWzvHRiVHkyvHVsnRydnF1U0JqDIzT8FWISVfgUtBoaAoM69EQUWhJDE7VcHIUCENSSwnNS@9JEMh7f@/5LScxPTi/7rJBQUA "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ ~~14~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
15Ýh6ãJ'#ì
```
[Try it online.](https://tio.run/##yy9OTMpM/f/f0PTw3Ayzw4u91JUPr/n/HwA)
**Explanation:**
```
15Ý # Create a list in the range [0, 15]
h # Convert each to a hexadecimal value
6ã # Create each possible sextuple combination of the list
J # Join them together to a single string
'#ì # And prepend a "#" before each of them
```
[Answer]
## Batch, 87 bytes
```
@set s= in (0,1,255)do @
@for /l %%r%s%for /l %%g%s%for /l %%b%s%echo rgb(%%r,%%g,%%b)
```
Outputs in CSS format. The variable substitution happens before the `for` statement is parsed so the the actual code is as follows:
```
@for /l %%r in (0,1,255)do @for /l %%g in (0,1,255)do @for /l %%b in (0,1,255)do @echo rgb(%%r,%%g,%%b)
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 47 bytes
```
Enumerable.Range(0,1<<24).Select(q=>$"#{q:X6}")
```
[Try it online!](https://tio.run/##Tc1BC4IwGMbxe59iWIcNbGhEB527KRTRIYO62niVkb7DbdYh@uxmdKjzj//zKLdUTo/FgEpscxw6sNW1BVF6q7GRktQkI5SRTI4/5ccKG6BRGAuxWjNeQgvK0z6Ti2D@7JPL5hWwMZ3NzlZ72GsEGhTaOk/iKCLKtMa6JGDpn3//@M5opDnetTXYAXp@gMfHQ1JTxk/VDeg0wdjUjm8 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 75 bytes
```
()=>{int i=1<<24;var a=new string[i];for(;i-->0;)a[i]=$"#{i:X6}";return a;}
```
[Try it online!](https://tio.run/##bVDBTgIxFDzTr3hZPWwPbIAQD5YlMSR60YSoiSaGQ1PewgtLi68FNWS/fe0CKqJzaNLpvJnXMb5tHGO99mRn8PDhAy6VOL5lI1eWaAI567MbtMhkThS3ZF9PqEd8D6fUnFFPI5E9ar/wSgirl@hX2iCMorkr8Wq16oqtgAhTau9hzG7Gerlj9nwDH3QgAxtHU7jTZFMfOPq@TEDzzMtv3c9Eg@u1NYMv5RAKyOtU5sMt2QCUdweDXl9tNIPOLb7BQUgTVThOFbXbw46SOhL5eXK2pcvniypRjGHNFrSqavUr7PCh7IkpYOwH02TMTVJB7AN0O70@GFc69olUotWMxBzUZp42OzCQhSKVsaoFpo1aymN70Wr9TWD5/w73sfad4Oi9EvuzEvUn "C# (.NET Core) – Try It Online")
Port of JAVA 10 version with C# interpolated string format
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 19 bytes
**Solution:**
```
$(3#256)\'!16777216
```
[Try it online!](https://tio.run/##y9bNz/7/X0XDWNnI1EwzRl3R1MDg/38A "K (oK) – Try It Online") (limited to first 500 numbers)
**Explanation:**
Dump out rgb strings. Convert each number between 0 and 16777216 to base 256, then convert to strings...
```
$(3#256)\'!16777216 / the solution
!16777216 / range 0..16777215
( )\' / split each both
3#256 / 256 256 256
$ / string
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~17~~ 15 bytes
```
10W:q'#%06X,'YD
```
[Try it online!](https://tio.run/##y00syfn/39Ag3KpQXVnVwCxCRz3S5b@RSTiUG5MH4gMA "MATL – Try It Online")
The TIO version displays the first 2^10 only as not to time out. I included the final iteration in the footer to show that it indeed terminates at `#FFFFFF`. Saved one byte by changing to `fprintf` instead of manually assembling the string. Outputs a comma-separated list.
Explanation
```
24W:q % Range from 0 to 2^24-1
'#%06X,' % fprintf format spec (# followed by hexadecimal, zero-padded, fixed-width, followed by newline)
YD % Call fprintf. Internally loops over range.
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~47~~ ~~43~~ 20 bytes
```
'#',(⎕D,⎕A)[↑,⍳6⍴16]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkG////V1dW19EACrjoAAlHzehHbRN1HvVuNnvUu8XQLBYA "APL (Dyalog Unicode) – Try It Online")
Given enough time/memory, this anonymous function will output all \$2^{24}-1\$ color codes. To see this, you can swap the `6⍴` for a `4⍴` in the code, and you'll see it output every code with up to 4 digits.
Thanks to @Dzaima and @ngn for the 23 bytes.
Uses `⎕IO←0`.
### How:
```
'#',(⎕D,⎕A)[↑,⍳6⍴16] ⍝ Main function
⍳6⍴16 ⍝ Generate every possible 6 digit hex number in a matrix format
, ⍝ Ravel the matrix (from a 16x16x16x16x16x16 matrix to a 16^6x2 list)
↑ ⍝ Mix; (turns the list into a 16^6x2 matrix)
(⎕D,⎕A)[ ] ⍝ Use that matrix to index the vector of the digits 0-9 concatenated with the alphabet.
'#', ⍝ Then prepend a '#' to each.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 31 bytes
```
$><<("#%06x\n"*d=2**24)%[*0..d]
```
[Try it online!](https://tio.run/##KypNqvz/X8XOxkZDSVnVwKwiJk9JK8XWSEvLyERTNVrLQE8vJfb/fwA "Ruby – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 25 bytes
```
8É00lrx16777215ñÄ<C-a>ñ0<C-v>Gls#
```
[Try it online!](https://tio.run/##K/v/3@Jwp4FBTlGFseHhjYdbGA9vNBBzzylW/v8fAA "V – Try It Online") (replaced `16777215` by `31`)
### Explanation
```
8É0 " insert 8 zeroes
0l " move cursor to the second character
rx " replace by x
16777215ñ ñ " 16777215 times do ..
Ä " .. duplicate line
<C-a> " .. increment (leading 0x makes sure it uses hexadecimals)
0<C-v> " move cursor to beginning of line and start selection
Gl " select the column with 0x
s# " replace by #
```
[Answer]
## Batch, 69 + 4 = 73
### g.cmd, 69
```
for /L %%A in (0,1,16777215)do cmd/kexit %%A&set #%%A=#!=exitcode:~2!
```
Saves the hexadecimal value with form `#RRGGBB` into an 'Array'.
`g.cmd` is to be called using `cmd /V/Q/K g.cmd`. This is where the + 4 comes from, `/V/Q`, counting as 4 additional characters compared to just `cmd /K g.cmd`. This sets up an environment that has the 'Array' in memory. It also takes forever to run, so use very low values to try or break execution using `Ctrl+C`
---
## Breakdown
### Invokation
* `/V` enables delayed expansion, but is shorter than `setlocal EnableDelayedExpansion`, which is why we need the `cmd` call in the first place
* `/Q` omits the output and is equivalent to `@echo off`
* `/K` lets you execute an expression (In this case `g.cmd`) and does not exit afterwards, so you can check the 'Array' by using `set #`
### g.cmd
```
for /L %%A IN (0,1,16777215) DO (
cmd /k exit %%A
set #%%A=#!=exitcode:~2!
)
```
This bit uses a trick documented [here](https://www.dostips.com/forum/viewtopic.php?t=2261) to convert a normal number to a hexadecimal, then saves that value into an 'Array'.
---
I've been calling that storing structure an 'Array' but that is not actually right as true Arrays do not exist in Batch. BUT you can name variables so that they have arraylike names, like so:
```
set elem[1]=First element
set elem[2]=Second one
```
or, like in this case:
```
set #1=First element
set #2=Second one
```
You can still access them via `!#%position%!`
[Answer]
# [Groovy](http://groovy-lang.org/), 53 bytes
```
c={a=[];(1<<24).times{a.add "".format("#%06x",it)};a}
```
Function definition. c() returns an ArrayList (I assume that's fine, even through the question asks for an array).
Ungolfed, with implicit types:
```
ArrayList<String> c = {
ArrayList<String> a = []
(1 << 24).times {
a.add("".format("#%06x", it)) // add the hex-formatted number to the list.
}
return a
}
```
[Try it online!](https://tio.run/##Sy/Kzy@r/P8/2bY60TY61lrD0MbGyERTryQzN7W4OlEvMSVFQUlJLy2/KDexRENJWdXArEJJJ7NEs9Y6sfZ/SmqaQklRaapzfk5@aVGxgq1CsoYmV0FRZl5JTh6yjF5xaZJPZnGJhoGOoQF@FVAX6Boa6ChAmFxFqSWlRXn/AQ "Groovy – Try It Online")
[Answer]
# Java 10, ~~87~~ 84 bytes
```
v->{int i=1<<24;var r=new String[i];for(;i-->0;)r[i]="".format("#%06X",i);return r;}
```
-3 bytes thanks to *@archangel.mjj*.
[Try it online](https://tio.run/##PY9Ba8MwDIXv/RUiY2DDYtoddnFT2A9YL4MxGD1oblqUOU6RZY9S8tszh2W7CPTE0/tehxnr7vg1OY8xwgtSuK0AKEjLJ3Qt7OcV4FWYwvnjAE69DXSErG3Rx1UZUVDIwR4CNDDlencrbqBms91uHm1GBm5C@/33gg72NLCyVNe7tdVchKaqTNF6FFXd3a@f3qsH0pZbSRyA7TjZOeeSPn3JWeLyTNEXXPWPhnphvUZpezMkMZdyEh9UV2qaJOTNMzNeo5Hh16aCcSok77VeGo3TDw) (limited to the first `4,096` items).
**Explanation:**
```
v->{ // Method with empty unused parameter & String-array return-type
int i=1<<24; // Integer `i`, starting at 16,777,216
var r=new String[i]; // Result String-array of that size
for(;i-->0;) // Loop `i` in the range (16777216, 0]
r[i]= // Set the `i`'th item in the array to:
"".format("#%06X",i);// `i` converted to a hexadecimal value (of size 6)
return r;} // Return the result-array
```
[Answer]
# PHP, ~~68~~ 62 bytes
This is supposed to be placed inside a file, the array is returned in the end, to be usable.
```
<?foreach(range(0,1<<24)as$i)$a[]=sprintf('#%06x',$i);return$a;
```
To have access to the array, simply give the result of the include (e.g.: `$a = include 'xyz.php';`) to a variable.
---
Thanks to [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for saving me 6 bytes and fix a goof.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
'#'5Y26Z^Yc
```
[Try it online!](https://tio.run/##y00syfn/X11Z3TTSyDgqLjL5/38A "MATL – Try It Online") (with only three hex digits instead of six)
### Explanation
```
'#' % Push this character
5Y2 % Push '01234567890ABCDEF'
6 % Push 6
Z^ % Cartesian power. Gives a (16^6)×6 char matrix
Yc % String concatenation. '#' is implicitly replicated
% Implicitly display
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + jot, 22
```
jot -w\#%06X $[8**8] 0
```
[Try it online!](https://tio.run/##S0oszvj/Pyu/REG3PEZZ1cAsQkEl2kJLyyJWweD/fwA "Bash – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 31 bytes
```
printf"#%06X
",$_ for 0..8**8-1
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvJE1JWdXALIJLSUclXiEtv0jBQE/PQkvLQtfw/38A "Perl 5 – Try It Online")
[Answer]
# [Lua](https://www.lua.org), ~~47~~ 45 bytes
```
for i=1,8^8 do s='#%06X'print(s:format(i))end
```
[Try it online!](https://tio.run/##yylN/P8/Lb9IIdPWUMcizkIhJV@h2FZdWdXALEK9oCgzr0Sj2Aoon5tYopGpqZmal/L/PwA "Lua – Try It Online")
[Answer]
# T-SQL, ~~122~~ 117 bytes
Returns a 16,777,216-row table of `#RRGGBB` strings. The line break is for readability only:
```
WITH t AS(SELECT 0n UNION ALL SELECT n+1FROM t WHERE n<16777215)
SELECT'#'+FORMAT(n,'X6')FROM t option(maxrecursion 0)
```
Uses a recursive CTE for a number table from 0 to 2^24-1, then uses the built-in `FORMAT` command (available in SQL 2012 or later) to turn it into a [6-digit hex string](https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#XFormatString). Attach the `#` to the front, and we're done.
Edit 1: Removed `POWER()` function, the number was shorter :P
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
⁴ṖṃØHœċ6ṭ€”#
```
[Try it online!](https://tio.run/##AScA2P9qZWxsef//4oG04bmW4bmDw5hIxZPEizbhua3igqzigJ0j/8KiWf8 "Jelly – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ØHṗ6”#;Ɱ
```
[Try it online!](https://tio.run/##ARsA5P9qZWxsef//w5hI4bmXMuKAnSM74rGu/8KiWf8 "Jelly – Try It Online") (note: uses `2` rather than `6` as `6` times out on TIO)
Function submission (because Jelly full programs will, by default, print lists of strings with no delimiters between them, making it hard to see the boundaries). The TIO link contains a wrapper to print a list of strings using newlines to separate them.
## Explanation
```
ØHṗ6”#;Ɱ
ØH All hex digits (“0123456789ABCDEF”)
ṗ6 Find all strings of 6 of them (order relevant, repeats allowed)
”#; Prepend “#”
Ɱ to each of the resulting strings
```
[Answer]
# [PHP](https://php.net/), 43 bytes
```
<?php for(;$i<1<<24;printf("#%06X ",$i++));
```
[Try it online!](https://tio.run/##K8go@P/fxr4go0AhLb9Iw1ol08bQxsbIxLqgKDOvJE1DSVnVwCxCQUlHJVNbW1PT@v9/AA "PHP – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 40 bytes
```
(1 to 1<<24).map(x=>println(f"#$x%06x"))
```
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFCgUP1fw1ChJF/B0MbGyERTLzexQKPC1q6gKDOvJCdPI01JWaVC1cCsQklT83/tfwA "Scala – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 26 bytes
```
{map *.fmt("#%06X"),^8**8}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzo3sUBBSy8tt0RDSVnVwCxCSVMnzkJLy6L2f5qGph5Q1gooXZxYaf0fAA "Perl 6 – Try It Online")
Uses the same format as everyone else. Times out on TIO.
Or, in rgb format:
### 31 bytes
```
{map {"rgb($_)"},[X] ^256 xx 3}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzo3sUChWqkoPUlDJV5TqVYnOiJWIc7I1EyhokLBuPZ/moZmdJyhgYFBrB5QpZWCll5xYqX1fwA "Perl 6 – Try It Online")
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/68666/edit).
Closed 2 years ago.
[Improve this question](/posts/68666/edit)
As a spin-off to [my challenge over at Puzzling](https://puzzling.stackexchange.com/questions/25039/10-9-8-7-6-5-4-3-2-1-2016), your goal is to output `2016`.
Rules:
* You must include the numbers `10 9 8 7 6 5 4 3 2 1` in that order. They can be used as individual integers or concatenated together (like `1098`), but the `10` may not be separated into `1` and `0` - no character(s) may be present between the digits. Note that, in some languages, `10` may not actually represent the integer literal `10`, which is acceptable.
* Your code must not contain any other numbers or pre-defined number variables or constants (so `T` in Pyth is not allowed, since it is a numeric constant).
* You must **calculate** `2016` using numerics. Simply outputting `2016` without performing any operations on the required numbers (for example, by decoding an encoded string consisting of only alphabetic characters) is not allowed. Outputting `2016` in pieces (such as `20`, then `16`) is also not allowed; you must have a single output consisting of the numeric value `2016`.
* The valid answer with the fewest bytes wins.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~17~~ ~~15~~ 14 bytes
```
109876:54+3_21
```
[Try it online!](http://jelly.tryitonline.net/#code=MTA5ODc2OjU0KzNfMjE&input=)
### How it works
```
109876:54+3_21
109876 Initialize the left argument as 109876.
:54 Perform integer division by 54, yielding 2034.
+3 Add 3, yielding 2037.
_21 Subtract 21, yielding 2016.
```
[Answer]
# Hexagony, 61 bytes
Not gonna win, but I just wanted to do a challenge in Hexagony.
This uses a different method than other answers (much worse). It takes some factors of 2016 (2,3,6,7,8) and multiplies them all together.
Minified:
```
\109.8/7}_=\"6<}{>...$_5_4/*!@...../}3.."2\/="*=}<*...$1>"*"/
```
Unminified:
```
\ 1 0 9 .
8 / 7 } _ =
\ " 6 < } { >
. . . $ _ 5 _ 4
/ * ! @ . . . . .
/ } 3 . . " 2 \
/ = " * = } <
* . . . $ 1
> " * " /
```
Explanation coming soon;
[Answer]
# Pyth, 16 bytes
```
+/109876 54-3 21
```
Does integer division, then adds (3-21).
Try it [here](http://pyth.herokuapp.com/?code=%2B%2F109876+54-3+21&debug=0).
[Answer]
## TI-BASIC, ~~17~~ 15 bytes
```
int(109876/54-‚àö(321
```
This uses @nicael's method.
17 bytes:
```
10+9*8-7+654*3-21
```
[This solution](https://puzzling.stackexchange.com/a/25050/12917) from Puzzling can be directly translated into TI-BASIC.
[Answer]
# Japt, ~~17~~ 16 bytes
```
Â(109876/54-321q
```
~~I hate this 17. Probably will find another solution.~~ YAYZ.
Explanation:
* `321q` is a square root of 321.
* `~~` floors the number.
[Try it online!](http://ethproductions.github.io/japt?v=master&code=wigxMDk4NzYvNTQtMzIxcQ==&input=)
[Answer]
# Matlab / Octave, 23 bytes
```
(10-9+8-7)^(6-5+4)*3*21
```
[Try it online](http://ideone.com/cLWq29)
[Answer]
# bc, 14
```
109876/54+3-21
```
Nothing exciting here - borrows from other answers.
[Answer]
## Haskell, 31 bytes
```
[10,9*8*7+const 6 5..]!!4+3*2*1
```
Not the shortest, `10+9*8-7+654*3-21` like seen in other answers works in Haskell too, but something different.
This builds a list starting with `10` and `9*8*7+6 = 510`, so the offset is `500` for the following elements. The whole list is `[10,510,1010,1510,2010,2510 ...]`. We pick the `4th` element (index 0-based), i.e. `2010` and add `3*2*1 = 6`. Voilà.
I use `const 6 5 = 6` to get rid of the `5` which is not needed.
[Answer]
# Python 2, 20 bytes
```
print 109876/54+3-21
```
Again, that same boring `2016.(740)`. Makes use of the fact that if you don't have a decimal number in your expression it returns an integer.
[Answer]
# [BotEngine](https://github.com/SuperJedi224/Bot-Engine), ~~42~~ ~~39~~ ~~36~~ 13x2=26
```
v109876543210
>ee e@ eRP
```
[Answer]
# ><> (fish), 18 bytes
```
10987**r65r4*n;321
```
explaination:
multiplies 9 8 and 7 together to get 504, reverses the stack and reverses it again right before the 4 is added, then multiplies 504 and 4 to get 2016. Then prints the number and ends the program before the last 3 numbers (i could do it after too with no difference, if that matters rules-wise).
[Answer]
# [Math++](http://esolangs.org/wiki/Math%2B%2B), 17 bytes
```
_(109876/54)+3-21
```
Actually, this prints `2016.0`. But there's really no way to print the exact string `2016` in this language.
The 17-byte TI-BASIC solution would also work here.
[Answer]
# Polyglot, 17 Bytes
```
10+9*8-7+654*3-21
```
This code, first used in [Thomas Kwa's TI-BASIC answer](https://codegolf.stackexchange.com/a/68682/44713), also works in:
* AppleScript (full program)
* bc (full program)
* Math++ (expression or full program)
* Mathematica (function, therefore not valid)
* Powershell (full program)
* Japt (full program)
* ~~JavaScript (console input, therefore not valid)~~ Needs second verification
* ~~Perl 5 (function, therefore not valid).~~ Needs second verification
* Haskell (function, therefore not valid)
* Python REPL (expression, so REPL environment is needed to get the output)
[Answer]
# ùîºùïäùïÑùïöùïü 2, 15 chars / 17 bytes
```
109876/54+3-21‚çú
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=&output=&code=109876%2F54%2B3-21%E2%8D%9C)`
Translates to `round(109876/54+3-21)`.
*Thanks to @Dennis for saving 2 bytes!*
[Answer]
# Java 7, 31 bytes
```
int c(){return 109876/54+3-21;}
```
Boring port from other answers, of which I believe [*@Dennis*' Jelly answer](https://codegolf.stackexchange.com/a/68687/52210) was the first.
[Answer]
# PHP, 27 bytes
```
<?=~~(109876/54+3-21);
```
(22 bytes) was too boring,
so I used 10 to 9 as separate numbers:
```
<?=10*(9-8+7-6),5+4-3+2<<1;
```
other solutions, mostly with small cheats:
```
30: <?=10**(9+8-7-6)/5+4*3+(2<<1);
30: <?=10*trim(9*8,7),6+5+4+3-2*1;
29: <?=10*trim(9*8,76),5*4-3-2+1;
31: <?=10*trim(9*8,765),4+(3*2<<1);
31: <?=10*trim(9*8,765),4*3+(2<<1);
32: <?=ceil(1098*76/54)+321+ord(~j);
33: <?=(10<<9)/876*543/M_PI*2-M_E&~1;
```
[Answer]
# [CJam](https://esolangs.org/wiki/CJam), 15 bytes
```
109876 54/3+21-
```
Another port from Dennis' answer that I suspect works for many stack-based languages except 05AB1E, which seems to be the only stack-based answer besides Forth, which needs several more bytes.
[Answer]
# [Milky Way 1.6.5](https://github.com/zachgates7/Milky-Way), ~~28~~ 25 bytes
```
10+9*(8)7;^*6*5/4*3/2*A!1
```
---
### Explanation
```
10+9* ` perform 10*9 (leaves 90 at TOS)
(8)7;^* ` get rid of 8 and multiply the TOS by 7
6*5/4*3/2*A ` perform TOS*6/5*4/3*2 (leaves 2016 at TOS)
! ` output the TOS
1 ` push 1 to the stack
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 15 bytes
```
109876 54√∑3+21-
```
[Try it online!](http://05ab1e.tryitonline.net/#code=MTA5ODc2IDU0w7czKzIxLQ&input=)
Port of Dennis' answer.
[Answer]
# Forth, 22 bytes
Same calculation seen in other answers.
```
109876 54 / 3 + 21 - .
```
[**Try it online**](https://repl.it/ElA3)
[Answer]
# C 37 bytes
```
main(){printf("%d",109876/54+3-21);}
```
Same theme as many present.
[Answer]
# VBA, 15 bytes
```
?109876\54+3-21
```
(calculation unashamedly stolen from [Dennis](https://codegolf.stackexchange.com/a/68687/5011))
[Answer]
# JavaScript (ES6), 21 bytes
```
f=
_=>~~(109876/54+3-21)
console.log(f())
```
If the "countdown" went to 0, it could be done in 19 bytes.
```
f=
_=>109876/54+3-21|0
console.log(f())
```
And, seeing as it's 2017 now, that can also be done in 21 bytes:
```
f=
_=>-~(109876/54+3-21)
console.log(f());
```
] |
[Question]
[
Let \$n\$ be some positive integer. We say that \$n\$ is of *even kind* if the prime factorisation of \$n\$ (counting duplicates) has an even number of integers. For example, \$6 = 2 \times 3\$ is of even kind. Likewise, we say \$n\$ is of *odd kind* of the prime factorisation of \$n\$ has an odd number of integers, such as \$18 = 2 \times 3 \times 3\$. Note that as the prime factorisation of \$1\$ contains \$0\$ primes, it is of *even kind*.
Let \$E(n)\$ be the count of positive integers of even kind less than or equal to \$n\$, and \$O(n)\$ be the count of positive integers of odd kind less than or equal to \$n\$. For example, for \$n = 14\$, we have
* \$E(14) = 6\$ (\$1, 4, 6, 9, 10, 14\$), and
* \$O(14) = 8\$ (\$2, 3, 5, 7, 8, 11, 12, 13\$)
---
You are to write a program which takes some positive integer \$n \ge 1\$ as input, and outputs the two values \$E(n)\$ and \$O(n)\$. You may input and output in any [convenient method](https://codegolf.meta.stackexchange.com/q/2447), and you may output the two outputs in any format that consistently presents the values (e.g. you cannot output one in unary and another in decimal), and that clearly distinguishes between the two (typically, has some kind of obvious delimiter).
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code in bytes wins.
### Test cases
```
n -> [E(n), O(n)]
1 -> [1, 0]
2 -> [1, 1]
3 -> [1, 2]
4 -> [2, 2]
5 -> [2, 3]
6 -> [3, 3]
7 -> [3, 4]
8 -> [3, 5]
9 -> [4, 5]
10 -> [5, 5]
11 -> [5, 6]
12 -> [5, 7]
13 -> [5, 8]
14 -> [6, 8]
15 -> [7, 8]
16 -> [8, 8]
17 -> [8, 9]
18 -> [8, 10]
19 -> [8, 11]
20 -> [8, 12]
```
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
(-,])1#.2|1#@q:@+i.
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NXR1YjUNlfWMagyVHQqtHLQz9f5rcqUmZ@QrpCkYwhhGcBEDOMvkPwA "J – Try It Online")
* `1...+i.` 1 2 ... n
* `#@q:` Length `#` of prime factors `q:` of each
* `1#.2|` Sum of even lengths
* `(-,])` Input minus that sum `-` catted with `,` that sum `]`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
RÆE§ḂSṄạ
```
[Try it online!](https://tio.run/##ARwA4/9qZWxsef//UsOGRcKn4biCU@G5hOG6of///zE0 "Jelly – Try It Online")
```
RÆE§ḂSṄạ
R - Range [1, input]
ÆE - For each, get a list of the prime exponents
§ - Sum each
Ḃ - Modulo each by 2
S - Sum
Ṅ - Print (with a trailing newline)
ạ - Get the absolute difference between this and the input (also implicitly printed)
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 31 bytes
```
n->sum(i=1,n,I^(bigomega(i)%2))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboW-_N07YpLczUybQ118nQ84zSSMtPzc1PTEzUyNVWNNDUhqm6qpOUXaeQp2CoY6igYGegoFBRl5pUABZQUdO2ARJpGniZM7YIFEBoA)
Outputs a complex number where the real part is \$E(n)\$ and the imaginary part is \$O(n)\$.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LÓOÉ1Ý¢
```
[Try it online](https://tio.run/##yy9OTMpM/f/f5/Bk/8OdhofnHlr0/7@hCQA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9k4Opnr6TwqG2SgpK933@fw5P9D3caHp57aNF/nf8A).
**Explanation:**
-1 byte by realizing that: amount of prime factors of \$x\$ == sum(exponents of \$x\$'s prime factorization): [see that they are the same here](https://tio.run/##yy9OTMpM/f9fySezuMRKQcnex8X20DZ7Li4l14qC/LzUvJJihfw0hdTE5AyFssSc0lT1YoWCoszcVIW0xOSS/KLMqsSSzPw8kM7Dk225lIJLc2HqrRSAQMneXwdiXgCSrmIFjcy85JzSlMy8dIWU0oKczOTEktRiTbAWCACaNwlonk9qXnpJBsJIJftHTWvS7f//NzQBAA).
```
L # Push a list in the range [1, (implicit) input]
Ò # Get the prime exponents of each inner integer
O # Sum each inner list together
É # Check for each sum whether it's odd
1Ý # Push pair [0,1]
¢ # Count the occurrences of 0 and 1 in the list
# (after which the result is output implicitly)
```
[Answer]
# JavaScript (ES6), 71 bytes
```
f=(n,a=[0,0])=>n?f(n-1,a,a[(g=_=>k>n?0:n%k?g(k++):1^g(n/=k))(k=2)]++):a
```
[Try it online!](https://tio.run/##FY1BDoIwEEX3nGI2JjOhaMsSHDgIQTNBSrRkasC4MZ691t3Le/n5D3nLPm3356vSeJtT8oxqhAdr7Ejcae9RK2fEyIALX7kL2dlGD6FfMJQlNe6yoJ44EGHgmsa/k@TjhgoMrgWFM0NtM@QEnwJgirrHdT6uMU8N5AuitvimHw "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
a = [0, 0] // a[] = output array
) => //
n ? // if n is not equal to 0:
f( // do a recursive call:
n - 1, // decrement n
a, // pass a[]
a[ // update a[]:
( g = // g is a recursive function
_ => // which ignores its parameter
k > n ? // if k is greater than n:
0 // stop the recursion
: // else:
n % k ? // if k is not a divisor of n:
g(k++) // increment k and do a recursive call
: // else:
1 ^ // invert the result
g(n /= k) // divide n by k and do a recursive call
)(k = 2) // initial call to g, starting with k = 2
]++ // increment a[0] or a[1], depending on the
// parity of the number of prime divisors of n
) // end of recursive call
: // else:
a // return a[]
```
[Answer]
# [Desmos](https://desmos.com/calculator), ~~101~~ 97 bytes
```
f(K)=∑_{k=1}^Kmod([1,0]+∑_{n=2}^klog_n(gcd(n^{ceil(log_nk)},k))sign(∏_{a=3}^nmod(n,a-1)),2)
```
Output is the list \$[E(n),O(n)]\$. It will fail on larger values due to floating point inaccuracies, but I've tested values such as \$1000\$ and it gives the right output, so it's pretty much a nonissue.
[Try It On Desmos!](https://www.desmos.com/calculator/2yjtbj8wx9)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/stpjy9ydtp)
A shorter version of the above code technically works, but it fails for values greater than \$15\$ due to floating point errors (so it doesn't even pass all the test cases):
### ~~88~~ 84 bytes
```
f(K)=∑_{k=1}^Kmod([1,0]+∑_{n=2}^klog_n(gcd(n^k,k))sign(∏_{a=3}^nmod(n,a-1)),2)
```
[Try It On Desmos!](https://www.desmos.com/calculator/s5tgf5kpqk)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/xdlkkemv0u)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `o`, 8 bytes
```
ɾǐvL∷∑…ε
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJvIiwiIiwiyb7HkHZM4oi34oiR4oCmzrUiLCIiLCIxNCJd)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
'ǐ₂;L~ε"
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiJ8eQ4oKCO0x+zrVcIiIsIiIsIjFcbjJcbjNcbjRcbjVcbjZcbjdcbjhcbjlcbjEwXG4xMVxuMTJcbjEzXG4xNFxuMTVcbjE2XG4xN1xuMThcbjE5XG4yMCJd)
A flagless 8 byter that uses a method that is a little different to the other answer.
7 bytes using this approach with a flag:
## [Vyxal](https://github.com/Vyxal/Vyxal) `o`, 7 bytes
```
'ǐ₂;L…ε
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBbyIsIiIsIifHkOKCgjtM4oCmzrUiLCIiLCIxXG4yXG4zXG40XG41XG42XG43XG44XG45XG4xMFxuMTFcbjEyXG4xM1xuMTRcbjE1XG4xNlxuMTdcbjE4XG4xOVxuMjAiXQ==)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~72~~ 66 bytes
-6 bytes thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)
```
->n{[e=(1..n).map{|m|m.prime_division.sum{_2}}.count{_1%2<1},n-e]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7CI326WlJWm6FjeddO3yqqNTbTUM9fTyNPVyEwuqa3JrcvXACuNTMssyizPz8_SKS3Or441qa_WS80vzSqrjDVWNbAxrdfJ0U2NrISYtL1BwizY0iYXwFiyA0AA)
[Answer]
# [Factor](https://factorcode.org/) + `math.primes.factors`, ~~58~~ 50 bytes
```
[ dup [1,b] [ factors length odd? ] count tuck - ]
```
[Try it online!](https://tio.run/##NYw7DsIwEET7nGIOABFQQkGJaGgQlZXCcdZJFP@w1wWnDyYW3WjmzdNSsY/r63l/3M6wkqc2SjdSqjnE2VJq9UbVDonemZwqyELRkUGIxPwpqGPMHmnKWhvCpWlOB4jjru9WgSGHmiHw1xlyYxH6Ybiig/K5CDirBXv8LqEqe4N2m23wiUBSTesX "Factor – Try It Online")
* `dup` Create an extra copy of the input.
* `[1,b]` Create a range from one to the input (inclusive).
* `[ ... ] count` Count the number of elements in the range for which `[ ... ]` returns true.
* `factors length odd?` Does it have an odd number of factors?
* `tuck -` Subtract the result from the input non-destructively. (Implicit multiple return)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Had to sacrifice 2 bytes to handle `1` :\
```
2Æõk è_ʤ̦X
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Msb1ayDoX8qkzKZY&input=MjA)
```
2Æõk è_ʤ̦X :Implicit input of integer U
2Æ :Map each X in the range [0,2)
õ : Range [1,U]
k : Prime factors of each
è : Count the elements that return true
_ : When passed through the following function
Ê : Length
¤ : To binary string
Ì : Last character
¦X : Not equal to X?
```
[Answer]
# Mathematica, 40 bytes
```
Length/@PrimeOmega@Range@#~GroupBy~OddQ&
```
[View it on Wolfram Cloud!](https://www.wolframcloud.com/obj/a67e802b-076e-4cde-b16f-0bd0863a2f0a)
Output in the form `<|False->E(n),True->O(n)|>`.
[Answer]
# [R](https://www.r-project.org), 79 bytes
```
\(n)c(y<-sum(sapply(1:n,f<-\(n,p=2)sum(x<-!n%%p,if(n>1)f(n/p^x,p+!x))%%2)),n-y)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGa_JSU1LLUvOzMvBTbpaUlaboWN_1jNPI0kzUqbXSLS3M1ihMLCnIqNQyt8nTSbHSBUjoFtkaaIJkKG13FPFXVAp3MNI08O0NNIKlfEFehU6CtWKGpqapqpKmpk6dbqQkxdgfcICMDHSRbodILFkBoAA)
Returns O(n), E(n).
Helper function `f` returns the number of prime factors, `f%%2` returns whether-or-not this is odd: `f<-\(n,p=2)sum(x<-!n%%p,if(n>1)f(n/p^x,p+!x))`
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 63 bytes
```
.+
$*
M!&`.+
+%`^(2*(1+))\2+$
2$1
22|¶
O`2?1
(1)+(21)*
$#1 $#2
```
[Try it online!](https://tio.run/##K0otycxL/K@nzaWixeWrqJYAZPkncKlq@CYYoopqqybEaRhpaRhqa2rGGGmrcBmpGHIZGdUc2sYF1GFkb8ilYaiprWFkqKnFpaJsqKCibPT/v5EBAA "Retina 0.8.2 – Try It Online") Link is to test suite that outputs the results for `1..n`. Explanation:
```
.+
$*
```
Convert to unary.
```
M!&`.+
```
List all the numbers from `n` down to `1`.
```
+%`^(2*(1+))\2+$
2$1
```
Count the number of prime factors of each number, using repeated `2`s as the count. This leaves a lone trailing `1` once all of the prime factors have been counted.
```
22|¶
```
Take the parity of the counts of prime factors, so that `1` means that it had an even number and `21` means that it had an odd number, and join all of the results together.
```
O`2?1
```
Sort the `1`s and `21`s separately to make them easier to count.
```
(1)+(21)*
$#1 $#2
```
Count the number of `1`s and `21`s.
[Answer]
# [GeoGebra](https://www.geogebra.org/calculator), 66 bytes
```
InputBox(n
a=Sum(Zip(Mod(Length(PrimeFactors(a)),2),a,1...n
ai+n-a
```
[Try It On GeoGebra!](https://www.geogebra.org/calculator/zfv6h837)
Output is in the form \$E(n)+O(n)i\$.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
aBsm.&1lPh
```
[Try it online!](https://tio.run/##K6gsyfj/P9GpOFdPzTAnAMg2tAAA "Pyth – Try It Online")
Outputs `[O(n), E(n)]`.
### Explanation
```
aB bifurcate the absolute difference of implicit eval(input()) and
s the sum of
m map over implicit range(eval(input()))
.&1 modulo 2 (bitwise and 1)
l the length of
P the list of the prime factors of
h 1 + implicit map lambda variable
```
[Answer]
# [Julia 1.1], 92 bytes
```
using Primes
~N=(X=map(n->sum([b for (a,b)=factor(n)]),1:N);[sum(X.%2 .==0),sum(isodd.(X))])
```
Julia 1.0 [appears to be supported by the package Primes.jl](https://github.com/JuliaMath/Primes.jl/blob/fde566c12c3c1d5418d6d2e67087ed9cb2a11db0/Project.toml#L18), but I haven't been able to import it successfully. Here is the output in Julia 1.1:
```
julia> VERSION
v"1.1.1"
julia> using Primes
julia> ~N=(X=map(n->sum([b for (a,b)=factor(n)]),1:N);[sum(X.%2 .==0),sum(isodd.(X))])
~ (generic function with 1 method)
julia> map(x -> println(lpad(x,2) * " -> $(~x)"), 1:20);
1 -> [1, 0]
2 -> [1, 1]
3 -> [1, 2]
4 -> [2, 2]
5 -> [2, 3]
6 -> [3, 3]
7 -> [3, 4]
8 -> [3, 5]
9 -> [4, 5]
10 -> [5, 5]
11 -> [5, 6]
12 -> [5, 7]
13 -> [5, 8]
14 -> [6, 8]
15 -> [7, 8]
16 -> [8, 8]
17 -> [8, 9]
18 -> [8, 10]
19 -> [8, 11]
20 -> [8, 12]
```
This solution could be adapted without `Primes` in Julia 0.4, when `factor` was still part of base Julia.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
⟦₁{ḋl%₂}ᵍlᵐĊ|;0
```
[Try it online!](https://tio.run/##AS4A0f9icmFjaHlsb2cy///in6bigoF74biLbCXigoJ94bWNbOG1kMSKfDsw//8yMP9a "Brachylog – Try It Online")
### Explanation
4 additional bytes needed at the end to deal with the special case of `1`.
```
⟦₁ Range [1, ..., Input]
{ }ᵍ Group by:
ḋl%₂ Length of prime decomposition mod 2
lᵐ Map length
Ċ|;0 Output must have 2 elements; otherwise (Input = 1), Output = [Input, 0]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
F…·¹N«≔⁰θWΦι¬﹪ι⁺²λ«≧÷⁺²⌊κι≦¬θ»⊞υθ»IE²№υι
```
[Try it online!](https://tio.run/##RY7BDoIwEETP8BU9bpOaiPHmyWhMOEAIf1ChwsbSIu3iwfDttQQT9zabmTfT9HJqrNQhPOzEIDeNJoezqqXpFGSC5WYkX9JwVxNwztknTc7OYWdgL9iLn9Lk3aNWDG6offSgYKX1UNiWtF1VFYFwEExz/ssnhRw3Ro1d72Opv@KMrfqbCzQ40ABPzgXDteUfgsj/VS9pUpHrgTa9pNWExsNFurhAjivpYil@aKXEO4WQHcNu1l8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F…·¹N«
```
Loop from `1` up to and including `n`.
```
≔⁰θ
```
Assume even kind.
```
WΦι¬﹪ι⁺²λ«
```
While the current value has any nontrivial factors: ...
```
≧÷⁺²⌊κι
```
... divide it by the lowest such factor, and...
```
≦¬θ
```
... flip between even and odd kind.
```
»⊞υθ
```
Save the kindness of the current value.
```
»IE²№υι
```
Output the counts of even and odd kindness.
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 11 bytes
```
@€olé;ΣD³a«
```
[Try it online!](https://tio.run/##y8/INfr/3@FR05r8nMMrrc8tdjm0OfHQ6v//jQwA "Ohm v2 – Try It Online")
Returns a list of `[E(n), O(n)]`. Note that Ohm v2 formats numbers a little weirdly when they are in a list, but they are definitely the right numbers.
## Explained
```
@€olé;ΣD³a«
@ # Push a range from 1 to the input to the stack
€ ; # To each item in the range from before:
ol # Get the length of the full prime factorization of the item
é # and then push whether the length is even
ΣD # Push two copies of the sum of that list - the first copy is how many numbers are E(n), and the second will be used to calculate how many numbers are O(n)
³a # Get the absolute difference of the input and the E(n) count
« # Pair into a list
```
[Answer]
# [Arturo](https://arturo-lang.io), 52 bytes
```
$[n][x:∑map 1..n=>[%size factors.prime&2]@[n-x,x]]
```
[Try it](http://arturo-lang.io/playground?6Z5NSY)
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 13 \log\_{256}(96) \approx \$ 10.70 bytes
```
R1+Zh.S2%10dc
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZrgwy1ozL0go1UDQ1SkiFiUKkFiwxNICwA) Port of Kevin Cruijssen's 05AB1E answer.
### [Thunno](https://github.com/Thunno/Thunno), \$ 16 \log\_{256}(96) \approx \$ 13.17 bytes
```
DR1+Zh.S2%SDZKAD
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhYbXIIMtaMy9IKNVINdorwdXSDCUNkFiwxNICwA) Port of Steffan's Jelly answer.
#### Explanations
```
R1+Zh.S2%10dc # Implicit input
R1+ # Push range(1, input + 1)
Zh # Prime factor exponents
.S2% # Sum mod 2 of each
10dc # Count 1s and 0s
```
```
DR1+Zh.S2%SDZKAD # Implicit input
DR1+ # Duplicate and push range(1, input + 1)
Zh # Prime factor exponents
.S2% # Sum mod 2 of each
SDZK # Sum and print without popping
AD # Absolute difference with input
```
] |
[Question]
[
Given two integers, compute the two numbers that come from the blending the bits of the binary numbers of equal length(same number of digits, a number with less digits has zeros added), one after the other, like such:
```
2 1
10 01
1 0
1001
0 1
0110
```
some examples:
| Input | Binary | Conversion | Output |
| --- | --- | --- | --- |
| 1,0 | 1,0 | 10,01 | 2,1 |
| 1,2 | 01,10 | 0110,1001 | 6,9 |
| 2,3 | 10,11 | 1101,1110 | 13,14 |
| 4,9 | 0100,1001 | 01100001,10010010 | 97,146 |
| 12,12 | 1100,1100 | 11110000,11110000 | 240,240 |
| 1,3 | 01,11 | 0111,1011 | 7,11 |
| 7,11 | 0111,1011 | 01101111,10011111 | 111,159 |
| 7,3 | 111,011 | 101111,011111 | 47,31 |
The program must take integers as inputs and give integers as outputs
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 Thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)!
```
Bḅ4S+$
```
A monadic Link that accepts a pair of non-negative integers and yields a pair of non-negative integers.
**[Try it online!](https://tio.run/##y0rNyan8/9/p4Y5Wk2Btlf///5voWAIA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/p4Y5Wk2Btlf9H9xxuf9S05uikhztnAGkgygJRDXMUdO0UHjXMjfzPlZiUrKDg6OTswsVl4JjolOSc7KKg8D862lDHIFYHSBoBSSMdYyBpomMJEjHSMTQCy4DEzHUMDcGUcWwsAA "Jelly – Try It Online").
### How?
```
Bḅ4S+$ - Link: integers A e.g. [4, 9]
B - convert A to binary [[1,0,0],[1,0,0,1]]
ḅ4 - convert from base 4 [16,65]
...i.e. insert zeros between the binary digits
[16,65] = [[1,0,0,0,0],[1,0,0,0,0,0,1]]
$ - last 2 links as a monad - f(x):
S - sum x 81
+ - add x (vectorises) [97,146]
...i.e. the above S+$ is a rearrangement of
[(16+16)+65,(65+65)+16]
where 16+16 is the zero spaced bits of 4
shifted one place to the left & similarly
for (65+65) with respect to 9.
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 bytes
```
,⍥⊥⍥,∘⌽⍨⊤
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@dR79JHXUuBpM6jjhmPevY@6l3xqGvJ/7RHbRMe9fY96pvq6f@oq/nQeuNHbROBvOAgZyAZ4uEZ/D9NwVDBgAtEGgFJIwVjIGmiYAkSMQIisAxIzFzB0BBMGQMA "APL (Dyalog Extended) – Try It Online")
`⊤` Create a matrix where each column holds a binary representation of one of the integers.
`f∘⌽⍨` Apply the function `f` with that matrix on the left and the reverse of the matrix on the right.
`,⍥⊥⍥,` Flatten both matrices, convert both resulting vectors from binary and pair them up to return a length-2 vector of integers.
Alternatively, for a bit more symmetry: [`⊤,⍥⊥⍥,⌽⍤⊤`](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXEp1HvUsfdS0FkjqPevY@6l0CFPuf9qhtwqPevkd9Uz39H3U1H1pv/KhtIpAXHOQMJEM8PIP/pykYKhhwgUgjIGmkYAwkTRQsQSJGQASWAYmZKxgagiljAA)
[Answer]
3 versions, all work in 32 or 64-bit mode:
x86 machine code (clmul + AVX-512), 17 bytes. (Or 16B with AMD XOP instead of AVX-512)
x86 machine code (clmul + AVX1 32->64-bit, output pair in same order as input pair), 18 bytes
x86 scalar machine code (with BMI2 `pdep`), 22 bytes
# x86 machine code (clmul + AVX-512), 17 bytes
Takes 2 integers in the low two 16-bit elements of XMM0, returns 2 integers in 32-bit elements #1 and #0 of XMM0 (in that order, opposite of the input order). Swapping them would take another 4-byte instruction, `shufps xmm0, 0b00_01` (or a left shift of the original and a different rotate count), but if we're willing to stretch the bounds of [calling-convention plausibility](https://codegolf.stackexchange.com/a/165020/30206), this is fine. If not, use the 18 byte version below.
NASM listing: address, hexdump of machine code, source
```
;;; 16-bit inputs packed in XMM0, 32-bit outputs packed in XMM0 (opposite order)
bit_interleave_bothways_avx512:
00 C4E37944C000 vpclmulqdq xmm0, xmm0, 0 ; space out each bit
; movq rax, xmm0
; rol rax, 33 ; non-AVX512 emulation for the low qword
; movq xmm1, rax
06 62F1F50872C821 vprolq xmm1, xmm0, 33 ; <<=1 and swap 32-bit halves
0D 0F56C1 orps xmm0, xmm1 ; combine
10 C3 ret
```
Key building block: Carryless multiply of a number by itself spaces out the bits, interleaving with zeros. x86 has that as [`pclmulqdq`](https://www.felixcloutier.com/x86/pclmulqdq), single-uop on modern Intel, e.g. Skylake (and 4 uops on AMD Zen1/2/3). Same size for VEX or legacy-SSE encoding, 6 bytes. With an immediate `0`, reads the low qword of each input, writes a 128-bit output to the full dqword XMM register.
AVX-512 has SIMD rotates, but unfortunately earlier Intel doesn't. (TODO: [**AMD's XOP instruction set has `vprotq`**](https://en.wikipedia.org/wiki/XOP_instruction_set#Integer_vector_shift_and_rotate_instructions) with a 6-byte encoding according to NASM, 1 shorter than AVX-512 EVEX. AFAIK equivalent behaviour with an immediate count of 33. Would only run on AMD Bulldozer-family, which I don't have, so would be inconvenient to test but would still satisfy the rules of working on at least one implementation of a language.)
Combining the swap to line up outputs with each other along with a shift by 1 bit can be done with one rotate, but only with an EVEX encoding (4-byte prefix + opcode + modRM + imm8 = 7-byte encoding.) And only within a 64-bit qword, which means limiting the output size to two 32-bit integers, which means limiting the input to 16-bit integers.
Legacy SSE1 encodings are the smallest, only the escape byte no mandatory prefixes. We didn't dirty any YMM upper halves, so there's no SSE/AVX transition penalty here from mixing VEX/EVEX with legacy SSE. `vorps xmm0, xmm0, xmm1` or `por xmm0, xmm1` would each be 4 bytes.
# x86 machine code (clmul 32->64-bit), 18 bytes
Requires only AVX1 + CLMUL CPU features, e.g. Sandybridge.
As above with `clmul`, but using separate left-shift and swapping halves of the output to line them up for OR. This way we can handle 32-bit inputs (and the corresponding 64-bit outputs), and output in the same order as inputs.
Includes comments that trace the 4,9 test-case through it, confirmed from actual single-stepping in GDB. Would have output in hex, but the test cases strangely use decimal despite this being about bit-manipulation.
```
bit_interleave_bothways_avx512_32it:
; xmm0.v4_int32 = { 4, 9, 0, 0}
30 C4E37944C000 vpclmulqdq xmm0, xmm0, 0 ; xmm0.v2_int64 = { 16, 65 } value after clmul, from GDB
36 C5F9D4C8 vpaddq xmm1, xmm0, xmm0 ; xmm1 = { 32, 130 } ; VEX allows copy + left-shift with same size as paddw
3A 0FC6C04E shufps xmm0, xmm0, 0b01_00_11_10 ; xmm0 = { 65, 16 }
3E 0F56C1 orps xmm0, xmm1 ; xmm0 = { 97, 146 } ; in-place swap saves a byte vs. pshufd
41 C3 ret
```
Two 4-byte instructions (`vpaddq` and `shufps`) are only 1 byte larger than a single 7-byte EVEX `vprolq`.
---
# x86 scalar machine code (with BMI2), 22 bytes
```
bit_interleave_bothways:
00 BA55555555 mov edx, 0x55555555
05 C4E243F5FA pdep edi, edi, edx
0A C4E24BF5F2 pdep esi, esi, edx
0F 8D047E lea eax, [rsi + rdi*2] ; low bit = low b of arg1 = first out
12 8D1477 lea edx, [rdi + rsi*2] ; low bit = low b of arg2 = second out
15 C3 ret
```
Callable with the x86-64 System V calling convention (args in EDI, ESI),
return values in EAX (first), EDX (second).
The output is only 32 bits wide. This limit is more justifiable in 32-bit mode, where the same machine code does the same thing, disassembling as `lea eax, [esi + edi*2]` and so on. (Using 64-bit operand-size would cost an extra REX.W byte on each PDEP and LEA, and need a 10-byte `mov rdx, 0x5555555555555555` instead of 5-byte `mov reg, imm32`, so an extra 9 bytes total). The same machine code would *not* work in 16-bit mode; scaled index addressing modes would need an address-size prefix. VEX prefixes (for `pdep`) only decode in 16-bit protected mode, not real.
The key building block is [`pdep`, parallel bit-deposit](https://www.felixcloutier.com/x86/pdep), which takes low source bits and puts them at places where the control mask was non-zero. With `0b...010101`, this unpacks each input by interleaving it with zeros.
Doing `(x << 1) + y` and vice versa with LEA merges the unpacked bits into a single interleaved integer. `+` instead of the more idiomatic `|` allows using the shift-and-add LEA instruction.
[Try it online!](https://tio.run/##hZDdDoIwDIXveYpe@5MI/iRqfBJjSHETlwxG1qnw9NiiIlwYd9HtnOV8aYtEushsMy@RirbNTEhNGbS3Gu86zVy4PrChXQQAhbtz1aqewaJev498VEpX8mFmn1IPbBKHvjaTBYOMOXoyMAWvzCQ5sbkH6x7APcChf7kLoM9jdi7GE@tbqG5hAFIdSHUg@gtK2CF9dqUakLwOLVqTlxBvoty6DC2kFNCH6HXJ/N343Xxxr2SsJaszWgs/dheNsqtRdvs3Owrz0not@0uW0go1JIz2CQ "Assembly (nasm, x64, Linux) – Try It Online") with a brief test harness. (Only uses the first return value as exit status; I tested by single-stepping in a debugger. Not updated for the later CLMUL versions.)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
b4vβ:∑+
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLGmyIsImI0ds6yOuKIkSsiLCI7IiwiW1sxLDBdLFsxLDJdLFsyLDNdLFs0LDldLFsxMiwxMl0sWzEsM10sWzcsMTFdLFs3LDNdXSJd)
Port of (my suggested golf to) [Jonathan Allan's Jelly solution](https://codegolf.stackexchange.com/a/245550/85334). Input as a list of the two numbers.
```
b Convert each to binary,
4vβ then convert each from base 4.
b4vβ This has the effect of interleaving with a bit pattern of all zeroes.
+ Add each to
:∑ their sum.
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~91~~ 86 bytes
```
i;t;f(*a,*b){for(i=1<<17;i/=2;*b=*b&~i|(*b&i)*i)t=*a=*a&~i|(*a&i)*i;*a+=*b*2;*b+=2*t;}
```
[Try it online!](https://tio.run/##hZBhb4IwEIa/@ysuJBIoNdqCI6ayL8t@xfRDgeKaOTRAMjLHfvrYUVAxMxkpcL173vfaS2bJXua7ttWiEplDJCWxe8oOhaMjtl6zUOh5xAWJIxLb3/rLwZ92iXariEhcfU6anCDSQ4x0uBdxUomm1XkF71LnjgunCeDTJSpVViV72UJ0YhRwcQoBBtxsQlyNuIW5gReG9CmsehgjhgJ/RKv6qJJKpcYdOvuO7cyDB1QHi17Clpj22R0h74XojjzreoWDLuykqA3Op0sOeVlB8ioLgl@VvKmiF1ub@plv6tUTvkuLwnjvW4MaZwxO11nnqapRthBDuIZSf6pD5lwu486HDLmmBHie4V1j10/3fBuJfsOUDbMVN@X4XOZ/yscCgcyxpimFaQqzR8ALSAqxe2Uyx5bUHmfMBBm6Xud/r6/iI@Tf3tNykw/N6WXAMoqwkW1DjAHfDmdoJk37k2R7uSvb2ccv "C (clang) – Try It Online")
*Saved 5 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire)!*
Inputs pointers to two integers.
Returns the Interleaved Values™ ([Neil](https://codegolf.stackexchange.com/users/17602/neil)) through the input pointers.
[Answer]
# [Python](https://www.python.org), 54 bytes (@UnrelatedString)
```
lambda*I:map(sum,2*[J:=[int(f"{x:b}",4)for x in I]],J)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3zXISc5NSErU8rXITCzSKS3N1jLSivaxsozPzSjTSlKorrJJqlXRMNNPyixQqFDLzFDxjY3W8NKG6dQuKQOq00jQMdQw0NbngXHMdQ0NUvrEmVNOCBRAaAA)
### Old [Python](https://www.python.org), 57 bytes
```
lambda*I:[*map(sum,2*[J:=[int(f"{x:b}",4)for x in I]],J)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3LXMSc5NSErU8raK1chMLNIpLc3WMtKK9rGyjM_NKNNKUqiuskmqVdEw00_KLFCoUMvMUPGNjdbw0Y6EGaBUUgRVqGOoYaGpywXjmOoaGKFxjTU2IjgULIDQA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes
```
If[#1,0,Tr[a=#~Mod~2]+a+4#0[(#-a)/2]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zMtWvn9hG2GOgY6IUXRibbKdb75KXVGsdqJ2ibKBtEayrqJmvpGsbFq/wOKMvNKopV17dIclGPV6oKTE/PqqrmqgTprdUCUEYgy0jEGUSY6lmBBIx1DI4gsWNhcx9AQQhvXctX@BwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
## x64 machine code (requires VPCLMULQDQ, supported by Intel Ice Lake and later), ~~22~~ 21 bytes
Totally different approach than the BMI2 solution, ~~but by some cosmic coincidence it's exactly the same size~~, well it was until I saved a byte.
```
0: c4 e3 7d 44 c0 00 vpclmullqlqdq ymm0,ymm0,ymm0
6: c4 e3 fd 00 c8 4e vpermq ymm1,ymm0,0x4e
c: c5 f5 d4 c9 vpaddq ymm1,ymm1,ymm1
10: c5 f5 eb c0 vpor ymm0,ymm1,ymm0
14: c3 ret
```
Takes the input in a slightly odd way: a 256-bit vector with a 64bit number at index 0 and at index 2, the rest just padding. Maybe cheating?
Output is in a 256-bit vector again, but since it's two *128-bit* numbers, that doesn't feel like cheating to me.
The idea here is that a carryless square is equivalent to spacing the bits out just like we need here, so the first step is to carrylessly-multiply the input with itself. Then `vpermq` is used to get a copy of the squares but with the low and high halves switched around, `vpaddq` shifts that all left by 1, and `vpor` merges the even and odd bits together.
If you want to try this code, beware: there's a high chance your processor doesn't support this `vpclmulqdq` instruction. It was introduced with Intel's [Ice Lake](https://en.wikipedia.org/wiki/Ice_Lake_(microprocessor)) microarchitecture and is also supported by Tiger Lake and Rocket Lake. It is not officially supported on Alder Lake, but can be enabled on certain systems. Since this instruction is not officially part of AVX-512, it may not be present in future implementations.
[Answer]
# JavaScript, 55 bytes
```
q=v=>v&&q(v>>1)*4+v%2,a=>a.map((x,i)=>q(x)*2+q(a[i^1]))
```
[Try it online!](https://tio.run/##HYzBCoMwEAXv/Y/qrm6liULpIfkRm0JoFaIYE5Vgvz6NXubBPJhBB71@FuO22@rMt1um2Y7dL/YCohdByJBlHoKUDIumDFdOWkhdTdoB7GRQSA87Frz0oFvzZgox4sUtxm7QtozuihJ5Iqc6saHnYTgxfj6HexBj59RKneUeq2E2FvKXzVPvDw "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 89 bytes
```
(l,r)->{for(int i=1<<16;i>0;r=r&~i|(r&i)*i,i/=2)l=l&~i|(l&i)*i;return r+l*2+","+(l+r*2);}
```
[Try it online!](https://tio.run/##bZDBT4MwFMbv@yteSFgKdLgyo1EGBw8mHoyHHZcd6oClsyvktZAsc/7rtTDULPHw@tLv/fr1a/e847N98WHFoanRwN7t49YIGVet2hpRqzhMJ1vJtYZXLhScJgBN@y7FFrThxrWuFgUc3IysDAq1W2@A404HAwrwJJ5Hp@WLMuWuRPrTL3wOFWRgiaQYzPJTVSMRyoDI2HLJ7lKRz1PMcPolPglORRAKKm6yJJCZHDQ5aCmWpkUFGMkwiTzqRURGGCZBerbpkMP5Auk49uHg8SoiwKBnTot1I4UhziBIx1kfRrqEY@q447It3yrC1/PNFYT/QuwP6m/BUrfSOLKKedPIo3s24C@xOmpTHuK6NXHj/sZUxPML6hcwy8HXvvIo9DwdbcZz58mlJmdrGZ27SmxCF/aWPliWUJY4ZWHvKWNuWXwD "Java (JDK) – Try It Online")
This first interweaves 0 between each bit of each number, then weaves the two numbers together in both directions.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 22 bytes
```
L2PFB R J:R*TB(R:g)ZD0
```
Takes the two numbers as command-line arguments. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhbbfIwC3JwUghS8rIK0Qpw0gqzSNaNcDCCSUDXLos11DA1joTwA)
### Explanation
```
L2PFB R J:R*TB(R:g)ZD0
L2 Loop twice:
R: Reverse in-place
g The list of command-line args
TB( ) Convert each to binary
R* Reverse each binary representation
ZD0 Zip, filling in missing values with 0
J: Join into a single string of 1s and 0s
R Reverse
FB Convert from binary back to decimal
P Print
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~16~~ 14 bytes
```
F²⊞υ↨⁴↨N²I⁺Συυ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw0hTIaC0OEOjVEfBKbE4VcMESnvmFZSW@JXmJqUWaWjqKBhpampacwUUZeaVaDgnFpdoBOSUFmsEl@ZqlAJlS0Gy//@bcFn@1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes thanks to @UnrelatedString. Explanation:
```
F²⊞υ↨⁴↨N²
```
Input the two integers, convert them to base `2`, and then convert them from base `4`. This spaces the bits in the integers out.
```
I⁺Συυ
```
Vectorised add the list to its doubled sum. This interleaves the bits in both ways.
Example: With inputs of `4` and `9`, these are `0100` and `1001` in binary, and spaced out these are `00010000` and `01000001`. Adding the sum of these to each results in `00010000+00010000+01000001` and `00010000+01000001+01000001`, which is equivalent to `00100000+01000001` and `00010000+10000010`, resulting in `01100001` and `10010010`, which are the desired interleaved values.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 35 bytes
```
f(a)=if(a,4*f(a\2)+a%2*[2,1;1,2],a)
```
Takes input as a vector of two integers.
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN5XTNBI1bTOBpI6JFpCMMdLUTlQ10oo20jG0NtQxitVJ1IQqjU0sKMip1EhU0LVTKCjKzCsBMpVAHCUFkCGaOgrR0YY6BrFAGqxRAWiGMYgy0bEECwKNNILIgoXNdQwNIbRxbCzUEpi7AA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
b4öDO+
```
I/O as a pair of integers.
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/245550/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f8/yeTwNhd/7f//ow11jGIB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/JJPD21z8tf/r/I@ONtQxiNUBkkZA0kjHGEia6FiCRIx0DI3AMiAxcx1DQzBlHBsLAA).
**Explanation:**
```
b # Convert both integer in the (implicit) input-pair to binary strings
4ö # Convert them from base-4 strings back to integers
D # Duplicate this pair of integers
O # Sum them together
+ # Add this sum to both values
# (after which the resulting pair is output implicitly)
```
[Answer]
# [Desmos](https://desmos.com/calculator), ~~94~~ 87 bytes
```
f(a,b)=[g(a),g(b)]+g(a)+g(b)
g(A)=total(mod(floor(A/2^k),2)4^k)
k=[0...log_2(A+0^A)+.5]
```
Uses the base-4 interleaving trick that some of the other answers are using. Not sure if this is the optimal strategy for Desmos though, I will definitely look at alternate strategies.
The `+.5` trick works on the last line because if the end of an arithmetic range is not an integer, it will round it instead. For example, `[1...3.5]` is the same as `[1...4]`, while `[1...3.4]` is the same as `[1...3]`. We take advantage of the implicit rounding by noting that [round(x-.5) is equal to floor(x)](https://www.desmos.com/calculator/dunse6ylpi), so we can convert `[0...floor(log_2(A+0^A))+1]` to `[0...log_2(A+0^A)+.5]`.
[Try It On Desmos!](https://www.desmos.com/calculator/m1alglp5qj)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/vbuwczhpn3)
[Answer]
# [Factor](https://factorcode.org/), 59 bytes
```
[ [ 64 <bits> ] bi@ 2dup swap [ vmerge bits>number ] 2bi@ ]
```
[Try it online!](https://tio.run/##JY07DsIwEET7nGJO4CKKkPgI0SEaGkQVubDDAha2sdabIE5vYtKN5r3R3M0gby7Xy@l83CAYeapkOBMv2TrJeBFH8ksxUfUzEpPIN7GLgm3TdFiXHj1WHXZ1s4eGdQe0tzEhf0ya2RSIH4Q/jmOw84dGWy1dBuM9FFT5AQ "Factor – Try It Online")
* `[ ... ] bi@` Call a quotation on two objects.
* `64 <bits>` Convert an integer to a virtual sequence of sixty-four booleans.
* `2dup swap` Set up the data stack for both interleavings. `a b -> a b b a`
* `[ ... ] 2bi@` Call a quotation on two pairs of objects.
* `vmerge` Interleave two sequences.
* `bits>number` Convert a boolean sequence to an integer.
[Answer]
# ARMv8.2 A64 machine code (requires FEAT\_SHA3), 16 bytes
```
0e20e000 6e004001 ce608c20 d65f03c0
```
Following the [AAPCS64](https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst), this takes a `uint32x2_t` in the low half of v0 and returns a `uint64x2_t` in v0.
Disassembled:
```
0e20e000 pmull v0.8h, v0.8b, v0.8b
// Self-multiply as polynomials over GF(2);
// because this is a ring of characteristic 2, (a+b)^2 = a^2 + b^2 holds,
// thus squaring doubles each exponent in the polynomial, spreading out the bits.
6e004001 ext v1.16b, v0.16b, v0.16b, #8
// Extract bytes 8–23 from the concatenation of v0 and v0, and put them into v1.
// This swaps the positions of the two 64-bit numbers.
ce608c20 rax1 v0.2d, v1.2d, v0.2d
// Rotate each 64-bit element of v0 left by 1
// and then take the exclusive-or with v1, and put the result in v0.
d65f03c0 ret
// Return.
```
] |
[Question]
[
Produce a text file that prints "Hello World!" in as many programming languages as possible when compiled/interpreted, while also being as short as possible.
The score for your submission is calculated as `C / 2 ^ ((L - 1) / 4)`, where "C" is the length of the text file in characters and "L" is the number of languages that the program is valid in. Lowest score wins, of course.
[Answer]
```
print("Hello World!")
```
Works in at least Julia, Perl, PHP, Python2, Python3, Qbasic, R, Ruby ...
[Answer]
# JavaScript ES6, [Oration](https://github.com/ConorOBrien-Foxx/Assorted-Programming-Languages/tree/master/oration), [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), [Minkolang](http://play.starmaninnovations.com/minkolang/?code=) score = 71.94703045766462
`121 / 2^(3/4)`. Fun fact? I'm not trying to win, just to add as many languages as possible.
```
222 //X>"!dlroW olleH"Z
shush=0
alert("Hello World!")
sorry=`
listen
capture Hello World!`
$$$
=` >### .O$r"!"rXr<`
```
## What Vitsy sees
"Well, I'm a 1D language, so... for now, only the first line counts."
```
222 //X>"!dlroW ,olleH"Z
222 push three twos
// divide twice
X> drop the result and carry on
"!dlroW ,olleH"Z standard Hello, World! program
```
Thanks for the cookie, Vitsy :3
## What JavaScript ES6 sees
```
222 //X>"!dlroW ,olleH"Z
```
"Let's see... You put the number `222` and then put something in a comment. Alright, sure, I'll roll with that."
```
shush=0
```
"You made a variable. Noted."
```
alert("Hello, World!")
```
"Ah, I see where you're going with this. I'll display that."
```
sorry=`
listen
capture Hello, World!`
```
"Oo! A multiline string! Now we're talking, ES6 rulez, ES5 drools!"
```
(EOF)
```
"Well, I'm done. Peace out."
## What Oration sees
```
222 //X>"!dlroW ,olleH"Z
```
"This wasn't on my notes...! Best not do anything."
```
shush=0
alert("Hello, World!")
sorry=`
```
"Oh, here's some extra notes."
```
listen
```
"Listen..."
```
capture Hello, World!`
```
"...Hello, World!"
```
(EOF)
```
"*thinks* Nothing more! Great, I'm done here. *breathes deeply*"
## Minkolang explanation
(Too lazy to create narrative. Might do later, the code took a while.) Irrelevant code replaced with `#` or omitted. Also, added comments `C ... C`.
```
222 ###>"!dlroW olleH"#
$$$ C this separates layers C
###>### #####.O$r"!"rXr<`
```
### Layer 1, pt 1
```
222 ###>"!dlroW olleH"#
222 C push three 2s C
_ C space; fall to the next layer C
```
### Layer 2, pt 1
```
###>### #####.O$r"!"rXr<`
> C go this way C
_ C fall to the next (first) layer C
```
### Layer 1, pt 2
```
222 ###>"!dlroW olleH"#
>"!dlroW olleH" C go right and push those characters in that order C
_ C fall to the next layer C
```
### Layer 2, pt 2
```
###>### #####.O$r"!"rXr<`
< C starts here, going left C
r C reverse stack C
X C pop n (n = 2), and pop top n items on stack (2, 2) C
r C reverse stack C
"!" C push exclamation mark (for some reason, it's chopped off C
r C reverse stack C
$O C output stack as characters C
. C terminate program C
```
[Answer]
```
'Hello World!'
```
Runs in several scripting languages, including PHP, GolfScript, APL, ...
[Answer]
**Score of 0.84**
```
H
```
Works in H9+ and HQ9+.
1 / 2 ^ ((2 - 1) / 4) = **0.84**
[Answer]
## CoffeeScript and CJam, 46/2^((2-1)/4)=38.68
```
e###
"Hello, World!"
e###alert "Hello, World!"
```
[Answer]
# ES8, Japt, TeaScript, C#, C++, C, ESMin, score: ~8.8
```
main=_=>"Hello World!"();
```
ES8, TeaScript and Japt see `"Hello World!"`.
[Answer]
# Madbrain and [insert most BF derivatives here], ~~272~~ 227 bytes
Just posting for fun, not to win c:
```
956658555658
852224222254
************
c4993c839941
1****1**+**+
01cc70776ccc
g+11+g++*11
c003 c3c00
1gg* 1*1gg
0 c 0c0
g 1 g1g
0 0
g g[-]+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++.>>.>.<<<.+++.------.<<-.>>>>+.
```
***NOTE:*** There is no TIO for Madbrain, so you'll have to trust me on this one. I did, however, write an (admittedly not really well-written (but hey, at least it works!)) interpreter for Madbrain, which is on the esolangs wiki.
## Explanation
Madbrain sees: (I wrote this code c:)
```
956658555658
852224222254
************
c4993c839941
1****1**+**+
01cc70776ccc
g+11+g++*11
c003 c3c00
1gg* 1*1gg
0 c 0c0
g 1 g1g
0 0
g g
```
I admit, Madbrain reaches the BF code, but it doesn't do anything, so I didn't include it here.
Brainfuck (and a lot of BF derivatives) sees:
```
++++++[-]+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++.>>.>.<<<.+++.------.<<-.>>>>+.
```
BF ignores everything that isn't `><+-.,[]`, so it ignores *most* of the Madbrain code. However, there are some `+`s in the Madbrain code (that's what the `++++++` is), so you need to add `[-]` after that which sets the current cell to 0.
The code after `++++++[-]` is the code for printing `Hello World!`.
[Answer]
```
puts "Hello world!"
```
Works in Ruby and Tcl
[Answer]
# TI-BASIC and Pyth, 13/2^((2-1)/4)=10.93
```
"Hello World!
```
] |
[Question]
[
## Challenge
Assume two vectors \$\mathbf{a} = (a\_1,a\_2,\cdots,a\_n)\$ and \$\mathbf{b} = (b\_1,b\_2,\cdots,b\_n)\$ are given in an \$n\$-dimensional space, where at least one of \$b\_1,\cdots,b\_n\$ is nonzero. Then \$\mathbf{a}\$ can be uniquely decomposed into two vectors, one being a scalar multiple of \$\mathbf{b}\$ and one perpendicular to \$\mathbf{b}\$:
$$
\mathbf{a} = \mathbf{b}x + \mathbf{b^\perp}\text{, where }\mathbf{b^\perp} \cdot \mathbf{b}=0.
$$
Given \$\mathbf{a}\$ and \$\mathbf{b}\$ as input, find the value of \$x\$.
This can be also thought of as the following: Imagine a line passing through the origin and the point \$\mathbf{b}\$. Then draw a perpendicular line on it that passes through the point \$\mathbf{a}\$, and denote the intersection \$\mathbf{c}\$. Finally, find the value of \$x\$ that satisfies \$\mathbf{c}=\mathbf{b}x\$.
You can use an explicit formula too (thanks to @xnor), which arises when calculating the [projection](https://en.wikipedia.org/wiki/Projection_(linear_algebra)#Finding_projection_with_an_inner_product):
$$
x=\frac{\mathbf{a} \cdot \mathbf{b}}{\mathbf{b} \cdot \mathbf{b}}
$$
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Example
Here is an example in 2D space, where `a=(2,7)` and `b=(3,1)`. Observe that `(2,7) = (3.9,1.3) + (-1.9,5.7)` where `(3.9,1.3)` is equal to `1.3b` and `(-1.9,5.7)` is perpendicular to `b`. Therefore, the expected answer is `1.3`.
[](https://i.stack.imgur.com/NB2VX.gif)
## Test cases
```
a b answer
(2,7) (3,1) 1.3
(2,7) (-1,3) 1.9
(3,4,5) (0,0,1) 5
(3,4,5) (1,1,1) 4
(3,4,5) (1,-1,-1) -2
(3,4,5,6) (1,-2,1,2) 1.2
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 1 byte[SBCS](https://en.wikipedia.org/wiki/SBCS)
```
⌹
```
[Check all test cases!](https://tio.run/##SyzI0U2pTMzJT////1HPzv9pCo/aJig86u171NV8aL3xo7aJj/qmFhclA8mSjMzi/0YK5gppCsYKhlwQ1qH1hgrGXMYKJgqmQJ4BEBrCeYYgiMQDqQViqIgZVMwISBoBAA "APL (Dyalog Unicode) – Try It Online") When used dyadically, `X ⌹ Y` solves the least squares\* system \$Ya = X\$ for a result \$a\$ of the appropriate shape, e.g.:
* if \$Y\$ is a matrix and \$X\$ is a vector, we try to solve a linear system of equations.
* if \$Y\$ and \$X\$ are matrices, we compute \$Y\$'s (pseudo-)inverse and multiply it on the left of \$X\$.
* when both \$X\$ and \$Y\$ are vectors, the least squares formulation reduces to what we want, namely
$$\frac{X \cdot Y}{||Y||^2}$$
\**the least squares system \$Ya = X\$* can be understood as "what should \$a\$ be such that \$Ya\$ is as close as can be to \$X\$?", where closeness is measured with the usual L2 distance.
[Answer]
# [Haskell](https://www.haskell.org/), ~~33~~ 32 bytes
-1 byte thanks to @xnor!
```
(!)b=sum.zipWith(*)b
a#b=a!b/b!b
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/X0NRM8m2uDRXryqzIDyzJENDSzOJK1E5yTZRMUk/STHpf25iZp6CrUJBUWZeiYKKQrSxjomOqY5ZrIKyQrShjq6RjqGOUex/AA "Haskell – Try It Online")
---
# [Coconut](http://coconut-lang.org/), 35 bytes
```
(a,b)->p(a,b)/p(b,b)
p=sum..map$(*)
```
[Try it online!](https://tio.run/##TYzLDoIwEEX3fMUsXLSkVFpEIwnscOsHqAsgJRJ5NKX4SPh3bIFEk0lO7pk7U3RF1w56KuPrhDKSYy@RM7cS5QaOjPuhobTJ5Aa5eHrdq1oAixwArT4WAFUrB40w7WVdGcKYwFwXz6yeE71E/Aajm0Bpo1RVq82leBdCakjPp1SpTi3PciWyx4Q4OWBAAWEYGA2cNXuMBFYcHbPakdAon/i2FP4MI8ya3b/x7GDw@CrJftHcdLn9yL8 "Coconut – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 24 bytes
```
function(a,b)a%*%b/b%*%b
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdJM1FVSzVJPwlE/k/TSNYw0jHX1EnWMNYx1NTkQhLQNdQxhooY65jomILEDHQM4MrggoY6htgEdUEIWVjHDCphBNRgpKn5HwA "R – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/) + `numpy`, 20 bytes
```
lambda a,b:a@b/(b@b)
```
[Try it online!](https://tio.run/##ZczdCsIwDAXg@z5F7kwgm2vnDwqC76FepDqx0M2yVWVPP1cVFITc5MvJCX28XJtyOG/2g5fangSE7Vq2dop2a2lwdbi2EZpbHXr1uDhfgV4rOEpXwQa86yLWErC6i2dwTbhFpLwL3kWcwISIFITWNRHP@OrIpW2lx/S/Kw7E8Kf6MH4NaHhJgCVrAp2X6rNnmssEKzWeZjwfqeAiheZf0ayTzH4lS0OQmQ/y4s1mzJrUaJ4 "Python 3 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
Y\
```
[Try it online!](https://tio.run/##y00syfn/PzLm//9oY2vDWK5oI2vzWAA "MATL – Try It Online")
Least squares approach such as used in the APL answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes
```
ḋ`÷@ḋ
```
[Try it online!](https://tio.run/##y0rNyan8///hju6Ew9sdgNT/w8sdjs191LQm8v//6GgjHfNYnWhjHcNYIAXl6RrqGIO5xjomOqZAhoGOAVQBTMRQxxBDRBeEEGI6ZhBRI6BSo9hYAA "Jelly – Try It Online")
Simple translation of the given formula. Takes \$\mathbf{b}\$ as the left argument and \$\mathbf{a}\$ as the right argument.
```
ḋ The dot product of b and
` itself,
÷@ dividing
ḋ the dot product of b and a.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~21~~ 18 bytes
```
F²⊞υΣEA×κ§θλI∕⊟υ⊟υ
```
[Try it online!](https://tio.run/##JYs9C8IwFAB3f8UbX@A5WAcHJ9GlQyGgW8gQ2kiDaRLzUfz3T4u33HI3ziaP0XjmZ8yAnQDZyoyN4N4WHEzCPqRWURA83GILvggutQ@T/eCbwIuN805mFypeTal4c6ubLMqYsP2uv7eIWakjwUETqI7gpDXvV/8F "Charcoal – Try It Online") Link is to verbose version of code. Takes inputs in the order `b`, `a`. Explanation:
```
F²
```
Repeat twice...
```
⊞υΣEA×κ§θλ
```
Input a vector, take its dot product with `b` and push the result to the predefined empty list.
```
I∕⊟υ⊟υ
```
Retrieve the dot products and take their quotient.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
*OInO/
```
[Try it online](https://tio.run/##yy9OTMpM/f9fy98zz1////9oIx3zWK5oYx3DWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCoZXF/7X8D63L89f/r/M/OjraSMc8VifaWMcwNlZHAcbVNdQxhvCNdUx0TIEiBjoGMCUwIUMdQ0whXRBCEtQxgwgbARUbxcbGAgA).
Implements the given formula:
$$x = \frac{a\_1\times b\_1 + a\_2\times b\_2 + \dots + a\_n\times b\_n}{b\_1^2 + b\_2^2 + \dots + b\_n^2}$$
**Explanation:**
```
* # Multiply the values at the same indices in the two (implicit) input-lists
O # Sum this list
I # Push the second input-list again
n # Square each value
O # Take the sum of that
/ # And divide the two values
# (after which the result is output implicitly)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~84~~ ~~74~~ 73 bytes
Saved 10 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
float f(a,b,n)float*a,*b;{float x,y;for(;n--;y+=*b**b++)x+=*a++**b;x/=y;}
```
[Try it online!](https://tio.run/##xZLbaoNAEIbv@xSDEPAwWo8pYWtuSp8ikbJrtVVaE9QLQ/DZ7RhdXWjobZcddMfvn/l33dT@SNNhyL9OvIVc5yiwMm4rk6Mp2HX60uGF5adaZ5Vts4sVm8I0hWUZHb1yy6IF6x7jC@uHb15UugHXB6Axibl7SCCGq49PPZtzYs4F6C057t3h5pztYbCCvhSHGK3onHXRVYsGd9k566GnsuFdNpSsPc6VjhQatysfLbxP5f2erWdhQps1bfPGJ4S7SLum8CkCipBi6SxhMcGCYEGwIFgQLAgW0Vy9qFqobtx4fkAzkDNUDUDWnbOuzd5n1nOI8JwdQkQkAlmmpfScfvLahHrqrx27V//Y7V4oIg1BXQeabHKqQR/NlCRxGT2eYcvAskp5J8ZxrgnJdU3XDLYkF2kxSQuSVocyGdWFqr7tNycW9uAaSzFypFRT22wcN6fP8ujL5FAkCtr/8mUg/Ic18Ye16e811D/X142oSrxZUsTLbsDew8bxctg0x4q6NUj/lErF620oE6nsH/rhBw "C (gcc) – Try It Online")
Inputs two pointers to vectors \$a,b\$ and their dimension \$n\$ and returns their component..
Uses given formula:
$$x = \frac{a\_0\cdot b\_0 + a\_1\cdot b\_1 + \dots + a\_{n-1}\cdot b\_{n-1}}{b\_0^2 + b\_1^2 + \dots + b\_{n-1}^2}$$
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 9 bytes
```
#.#2/#.#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@19ZT9lIH0io/Q8oyswrcdBKU3BwcFAISi1LLSpOVdB3UKiurjbSUTCv1VGoNtZRMKwFMeAiuoY6CsYQIaCkiY6CKYhtoKNgAFeKJA5UbIhDXBeMUWR0FMxgkkZgjUa1tbXW/wE "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes **b** followed by **a** as input and returns a rational number as output. It just directly uses Mathematica's notation for the dot product.
[Answer]
# Fortran >= 95, 66 bytes
Taking advantage of implicit typing for the return type.
```
function x(a,b)
real a(:),b(:)
x=dot_product(a,b)/norm2(b)**2
end
```
[Answer]
# [[R]](https://cran.r-project.org/), 22 bytes
Taking advantage of a resident regression function, `lm`
```
function(a,b)lm(a~b-1)
```
[Try it online!](https://tio.run/##PcdBCoAgFEXReSv5L56RlgRBi0lDCNLAatrWrSZNLufmEqYSruTPdU8y02GLMt9OaZQgXnpaGtCLYccOqIKYWvQ4gF/eVY2tc9pzFN3Sgr@PZWo0UB4 "R – Try It Online")
[Answer]
# Java 10, ~~84~~ 74 bytes
```
a->b->{float A=0,B=0;int i=0;for(var t:b){A+=a[i++]*t;B+=t*t;}return A/B;}
```
[Try it online.](https://tio.run/##lVJNa4NAEL3nVww5aV2tJv2AWAVzCPRQesgxeBgTLZuaVdwxJYi/3a7JlpQ2lRQWZth5b9682d3iHu3t5r1b5yglvCAXzQhAEhJfw1ZVnZp47mS1WBMvhLPQyVOWF0irmF0HWvRJGEIGQYd2mNhhc6xBFLhsHrg@FwRcxayojD1WQLPEbCIrwBW3rPiG/LkVkAptlVJdCYhu537b@SM1bFknuRpWz7wv@AZ2yoexpIqLt1UMaPaeACiVZIj0A/RYzYQ9tgy@30yZ15r@tWjbY9M/4VN2x@5/EFzmDghcYnjM@zfD7s8whz38Zk2U1OREa0fnT3Bc6LGLxgKyLxokerXLg6R05xQ1OaXaOuXCGD@LsiY5g7F1/iJRVeFBOlScHsdA0xoDis0gKDG1l0sqrzUpmV4lc7As84PqqZMhnrbZdp8)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
í*V x÷Vx²
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=7SpWIHj3Vniy&input=WzMsNCw1XQpbMSwtMSwtMV0)
] |
[Question]
[
Let's consider a list \$L\$ (initially empty) and a pointer \$p\$ into this list (initialized to \$0\$).
Given a pair of integers \$(m,n)\$, with \$m\ge 0\$ and \$n>0\$:
1. We set all uninitialized values in \$L\$ up to \$p+m+n\$ (excluded) to \$0\$.
2. We advance the pointer by adding \$m\$ to \$p\$.
3. We create a vector \$[1,2,...,n]\$ and 'add' it to \$L\$ at the position \$p\$ updated above. More formally: \$L\_{p+k} \gets L\_{p+k}+k+1\$ for each \$k\$ in \$[0,..,n-1]\$.
We repeat this process with the next pair \$(m,n)\$, if any.
Your task is to take a list of pairs \$(m,n)\$ as input and to print or return the final state of \$L\$.
## Example
Input: `[[0,3],[1,4],[5,2]]`
* initialization:
```
p = 0, L = []
```
* after `[0,3]`:
```
p = 0, L = [0,0,0]
+ [1,2,3]
= [1,2,3]
```
* after `[1,4]`:
```
p = 1, L = [1,2,3,0,0]
+ [1,2,3,4]
= [1,3,5,3,4]
```
* after `[5,2]`:
```
p = 6, L = [1,3,5,3,4,0,0,0]
+ [1,2]
= [1,3,5,3,4,0,1,2]
```
## Rules
* Instead of a list of pairs, you may take the input as a flat list \$(m\_0,n\_0,m\_1,n\_1,...)\$ or as two separated lists \$(m\_0,m\_1,...)\$ and \$(n\_0,n\_1,...)\$.
* You may assume that the input is non-empty.
* The output must *not* contain any trailing \$0\$'s. However, all intermediate or leading \$0\$'s *must* be included (if any).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Test cases
Input:
```
[[0,3]]
[[2,3]]
[[0,4],[0,5],[0,6]]
[[0,3],[2,2],[2,1]]
[[0,1],[4,1]]
[[0,3],[1,4],[5,2]]
[[3,4],[3,4],[3,4]]
[[0,1],[1,2],[2,3],[3,4]]
[[2,10],[1,5],[2,8],[4,4],[6,5]]
```
Output:
```
[1,2,3]
[0,0,1,2,3]
[3,6,9,12,10,6]
[1,2,4,2,1]
[1,0,0,0,1]
[1,3,5,3,4,0,1,2]
[0,0,0,1,2,3,5,2,3,5,2,3,4]
[1,1,2,1,2,3,1,2,3,4]
[0,0,1,3,5,8,11,14,11,14,17,20,12,0,0,1,2,3,4,5]
```
[Answer]
# [J](http://jsoftware.com/), 27 bytes
```
[:+/[(>:@i.@[,~0$~])"0+/\@]
```
[Try it online!](https://tio.run/##PY3BCoMwEETv@YpBChqUuMYoJWDJf6SeSkPrpQfP9dfTTYJlDsu@mdndYtgXBYIFRW/b3jc3697K@e6gy7HKitr@7tYoRaVQh0XV6PC1CLsQz8frg6YbJQIPkgUYTJiZUFJBAysBU9aRMzqDAdNZSgpssc6SzsmS039MfP@avwSmyTGY4w8 "J – Try It Online")
Takes two separate lists for `m` an `n` - the list for `n` is the left argument of the function, the list for `m` - the right one.
# [K (ngn/k)](https://gitlab.com/n9n/k), 42 bytes
```
{+/{x,'((|/#'x)-#'x)#'0}((+\x)#'0),'1+!'y}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/Nqlpbv7pCR11Do0ZfWb1CUxdEKKsb1GpoaMeAWZo66obaiuqVtf/Too0UDBWMFEwUzKwVDA0UTBUsgGzT2P8A "K (ngn/k) – Try It Online")
Takes two separate lists for `m` an `n`
It's too long currently, I'll try to golf it.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes
```
Ä0ẋżR}F€S
```
A dyadic Link accepting a list of integers on each side, \$M\$ on the left \$N\$ on the right, which yields a list of integers.
**[Try it online!](https://tio.run/##y0rNyan8//9wi8HDXd1H9wTVuj1qWhP8////aCMdBUMdBSBpoqNgFvs/2tBAR8FUR8ECLGAaCwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8//9wi8HDXd1H9wTVuj1qWhP8P@rwcv2jkx7unKEZ@XDH/EeN2/7/j46ONtAxjo3l0omONoIxDHRMYnWApCmYNIMJGgO5RjpGYNIQJmgI5JoguCA1hmDtpkCVYEFjMBdBImk0hJpmjCwFNNwALGcKlrMAWwDSbAYUieWKBQA "Jelly – Try It Online").
### How?
```
Ä0ẋżR}F€S - Link: list of integers, M; list of integers, N
Ä - cumulative sums (M) = [m1, m1+m2, m1+m2+m3, ...]
0ẋ - zero repeated = [[0]*m1,[0]*(m1+m2),[0]*(m1+m2+m3), ...]
R} - range (right=N) = [[[1,2,3,...,n1]],[[1,2,3,...n2]],[[1,2,3,...,n3]], ...]
ż - zip together = [[[0]*m1,[[1,2,3,...,n1]]],[[0]*(m1+m2),[[1,2,3,...,n2]]],[[0]*(m1+m2+m3),[[1,2,3,...,n3]]], ...]
F€ - flatten each = [[0,0,...,0,1,2,3,...,n1],[0,0,...,0,1,2,3,...,n2],[0,0,...,0,1,2,3,...,n3], ...]
S - sum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes
```
+ɼ0x;R}ʋ/€S
```
[Try it online!](https://tio.run/##y0rNyan8/1/75B6DCuug2lPd@o@a1gT/Nzi08uikhztn1Fo/apijoGun8KhhrvXhdrCYCtfhdqCiyP//o7miow10jGNjdYAMIxjDQMckVgdImoJJM5igMZBrpGMEJg1hgoZArgmCC1JjCNZuClQJFjQGcxEkkkZDqGnGyFJAww3AcqZgOQuwBSDNZkCRWK5YAA "Jelly – Try It Online")
A full program that takes a list of lists of integers as its argument and returns a list of integers. Can be adapted to work as a link by resetting the register to zero after each call (as implemented in the footer on TIO).
Saved a byte now list can be non-empty.
[Answer]
# Java 8, ~~148~~ 147 bytes
```
N->M->{int l=M.length,s=M[l-1],p=0,L[],i=0,j;for(int n:N)s+=n;for(L=new int[s];i<l;i++)for(p+=N[i],j=s;j-->0;)L[j]-=j<p|j>=p+M[i]?0:~j+p;return L;}
```
-1 byte thanks to *@ceilingcat*.
Takes both integer-arrays as separated inputs.
[Try it online.](https://tio.run/##jZJPb4IwFMDvfooeIRQCqMtiLcsuOwEXj4QDU3TtamlocTGOfXX2ZCxqosa8w2vf@73Xvj@82BUuX312S1FojZKCycMIIW0Kw5aIg9drDBPeupFLwyrpvQ2HOZMmy/EjSK@iCK0R7VI3StzoACYkaOKJUm7MB9Y0yYQb5FhRH8cQw0Bzsq5q60jKWWprh8reEFNZfvU5dU7YXBDmOPbRoRyaZizHnGrCXTfyiR1nPHcpn6tvHlHlJOB@8Wc/3FGkLk1TSxSTtiMjqFg17wIqHgrfVWyFttAMa2FqJjdZjgr72BiETKmN9f@F/OC3@HQZtza5BoWPQD4GOQcneIqfbsIhvswKhuAmPDlHgztggKeXWSfwzHV4jEEu/wtyJ3N4ifeGmwFhHzCBBpyH@NCSZ7BO/6La0WlX@5H1SXoWJcPioXQY3GKvTbn1qsZ4CmZqhLROy/ta18Vee6b6m7e19gqlxN5K7OGQ2vbwZNv9Ag)
**Explanation:**
```
N->M->{ // Method with integer-array as two parameters as well as return-type
int l=M.length, // Length of the input-arrays
s= // Length of the output-array,
M[l-1], // starting at the last pointer-item of array `M`
p=0, // Position `p` as specified in the challenge, starting at 0
L[], // Output list, starting uninitialized
i=0,j; // Index integers
for(int n:N) // Loop over the value-list `N`:
s+=n; // And add all of them to the output-length
for(L=new int[s];// Now initialize the output-list of size `s`, filled with 0s by default
i<l;i++) // Loop `i` in the range [0, `l`):
for(p+=N[i], // Increase position `p` by the `i`'th pointer of `N`
j=s;j-->0;)// Inner loop `j` in the range (`s`,0]:
L[j]-= // Decrease the `j`'th item of the output-list by:
j<p // If `j` is smaller than position `p`
|j>= // or `j` is larger than or equal to
p+M[i]? // pointer `p` and the `i`'th value of `M` combined
0 // Leave the `j`'th item of output-array the same by adding 0
: // Else:
~j+p; // Decrease the `j`'th item of the output-array by `-j-1+p`
// (increase it by the difference between `j` and `p`, plus 1)
return L;} // And after the nested loops: return the resulting array
```
[Answer]
# [Zsh](https://www.zsh.org/), ~~59 56~~ 54 bytes
***-3 bytes** by changing to my Bash strategy, **-2 bytes** by switching back to my original strategy, now that the rules specify the list is non-empty.*
```
for m n;for ((i=0,p+=m;i<n;a[p+i]+=++i)):
<<<${a/#%/0}
```
**Try it online:** [[Original strat handling empty case]](https://tio.run/##NU3LCsIwELznKxZUSFihSdOImPRLxEMvwRxai96UfnuctA3LMDsz@/h@njlKJXN8vWmkyReWMvX6PHM/@hQmP9xnTg/umZNSNxFCOP4GBprDqdHLkpUQUUTSZAnUbqSpAxxwoT1s1zKbNMhNTYpwyCAt2op90Kx7tlo4Udwyf4XT4YET@Q8 "Zsh – Try It Online")
[[Adapted Bash strat]](https://tio.run/##NU07DsMgDN19Cg8dQG4lCKGqAqQHqTpkQWVIitKtlycmCbKe7Pex/f99ShRSlPhdccbFQR2ESEFdM4XZJZ9pcdMrvSkQpTE/0y0PSsoBvPeXqUiACBEVGuTWHU1hz7CMO55mt5c@qGZfN6cSyx5Tw2PDGdT7nmkSn6hqzT9Y6fmBLRs "Zsh – Try It Online")
**[[Current]](https://tio.run/##NU1bCsIwEPzPKRaqmJJCkz5EbHsS8SPYlAZsE2yqqHj2uuljwzCZmX18hnZqaEinxjygg77wTKmueGRZ1RW67At5sUxfWcWYDsMzKcty95VxsI/5bwoJaWCuAFRn3RtuclDwUlCb/uCglU8FziD39V1FYEZnRzcAxzEOKSAlC3HIEDniCGuYzE8sUmAutsSLHDOUKX43rI1inks3C1d41/ef0MnwQE6mPw/ "Zsh – Try It Online")**
---
Setting `a[5]=1` causes `a[1]` through `a[4]` to be initialized empty. The final parameter expansion replaces all empty elements with `0`.
```
for m n # implicit 'in "$@"'
for ((i=0, p+=m; i<n; a[p+i]+=++i)) # increment p by m, add to a[p,p+n-1]
: # ':' is a no-op builtin
<<<${a/#%/0} # the glob #% matches empty elements
```
[Answer]
## Haskell, ~~90~~ 87 bytes
```
(foldl(%)[].).zipWith(\o p->(0<$[1..o])++[1..p]).scanl1(+)
(a:b)%(c:d)=a+c:b%d
b%d=b++d
```
Takes the input as two separate lists `[m0,m1,...]` and `[n0,n1,...]`.
[Try it online!](https://tio.run/##TY5BT4QwEIXv/Io5SNJJuw1lwRgi/gPPHrqNKUVcYhca2D3oj7eOjQby0sy87720Pdv14837OLSnyIbZ957lqI1E@TWGl/F6ZqcZwuGJFY93Wkk5G@T8dwkG5ers5BXjmDHbdJgz1/TYWu6aLu8zOm3HeR8vdpyghYsNz6/AwjJOV5Bwm9xtWT5hQNAZANNGaIMirQXtx39T7k0hSAQqUYv7DZYitWiqDVaE1B4oUadWRe0/eBSkdB9p3ywTTnMLyhRU9DJFBX3hgUxt0MRvN3j7vsaDC@EH "Haskell – Try It Online")
A variant (function `%` same as above), also 87 bytes:
```
(foldl(\l(o,p)->((0<$[1..o])++[1..p])%l)[].).zip.scanl1(+)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ηOÅ0s€L‚ø€˜0ζO
```
Takes two separated lists. The list of positions \$(m\_0, m\_1, m\_2, ...)\$ as first input and list of values \$(n\_0, n\_1, n\_2, ...)\$ as second input.
[Try it online](https://tio.run/##yy9OTMpM/f//3Hb/w60GxT6PGmYd3vGoac3pOQbntvn//x9tpGOoY6RjomMWyxVtaKBjqmMB5JjGAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/p5nl4h4u9ksKjtkkKSvYJxf/Pbfc/3GpQ/Khpjc@jhlmHdwAZp@cYnNvm/1/nf3S0gY5xbCxXdLQRlDbQMYnVAZKmYNIMKmYM5BnpGIFJQ6iYIZBnAueBVBiC9ZoC1YHEjME8BInQZQg1yRhJBmiuAVjKFCxlATYcpNUMKBILAA).
**Explanation:**
```
η # Get all prefixes of the (implicit) input-list of positions
# i.e. [0,1,5] → [[0],[0,1],[0,1,5]]
O # Sum each inner list
# → [0,1,6]
Å0 # Convert each of the inner values into a list of 0s of that length
# → [[],[0],[0,0,0,0,0,0]]
s # Get the second (implicit) input-list of values
L # And create a list in the range [1,n] of each value
# i.e. [3,4,2] → [[1,2,3],[1,2,3,4],[1,2]]
‚ # Pair the two lists together
# → [[[],[0],[0,0,0,0,0,0]],[[1,2,3],[1,2,3,4],[1,2]]]
ø # Zip/transpose, swapping rows/columns
# → [[[],[1,2,3]],[[0],[1,2,3,4]],[[0,0,0,0,0,0],[1,2]]]
€˜ # Flatten each inner pair to a single inner list
# → [[1,2,3],[0,1,2,3,4],[0,0,0,0,0,0,1,2]]
0ζ # Zip/transpose, swapping rows/column, with 0 as trailing filler
# → [[1,0,0],[2,1,0],[3,2,0],[0,3,0],[0,4,0],[0,0,0],[0,0,1],[0,0,2]]
O # Take the sum of each inner list
# → [1,3,5,3,4,0,1,2]
# (after which the result is output implicitly)
```
[Answer]
# [PHP](https://php.net/), 93 bytes
```
for(;$n=$argv[++$i+1];)for($p+=$argv[$i++];$$i<$p+$n;)$l[$$i]+=$$i++<$p?0:$$i-$p;print_r($l);
```
[Try it online!](https://tio.run/##VVBfb4IwEH/nU1xIE0FQQdQsVuPznrbsFRtCXCcYVppSTJZln91dKyDycNzv3x2HLORtd5CFdByieaMb2EPqpGkUJoyF2Cz7JgpXLMS6tnXTkwnCZbi0Ne7JGOHqAY0ntvE1Oi2ZWPioo2DcTUvGEg6PrLa22otdYMIbZNDBqON81YrnpwK87pK8Adv58OsAPvxU1OC@CtnqLbgwh0tTi4yLU/3Jvc45B/coXDryv7XaBAaW5Op8NX9JtFXF7tzz5mHxe14qfwjkSuU/2TdXZ9xmuHDkojec4VEi9lZKg4CUQcyob2gig45GMmCUkHKHHBHUJ1WKiKFuJGQP0RbbGZFUqlLoDNMVTh/uabTKFJc8195kNgkhiR5H21sWU/jgDdfAxRWmi/4@j1zwhogCvnd7IKXpgsCHVqDZI@Ti3/9Fh8tnKJ8hfpLzd/sH "PHP – Try It Online")
Input is a flat list of `m0,n0,m1,n1,...` passed by command arguments (`$argv`) and output is string representation of `L`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~144~~ ~~119~~ ~~118~~ ~~111~~ ~~110~~ 106 bytes
```
def f(m,n):
p=k=0;l=[]
for i,j in zip(n,m):p+=j;l+=[0]*(p+i-len(l));exec("l[~k]+=i-k;k+=1;"*i)
return l
```
[Try it online!](https://tio.run/##Jc6xDsIgEADQna@4dIJyTVqrS8l9CWFSGin0Sggm6uCvY4zbG19@1fvBc2s3v8Iqd2S1CMgUaTSJrBOwHgUCbhAY3iFLxl0tWdNmkiY7ul5mHYbkWSaljH/6q@yS/USnKQzRRE2T6fqgBBRfH4UhtR0I7IgTXpzgn2c848mJXAJX@U@o9gU "Python 3 – Try It Online")
Thanks to:
-@mypetlion for saving me 25 bytes
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~92~~ ~~88~~ 84 bytes
```
->x{n,l=0,[];x.map{|a,b|0.upto(b-1+n+=a){|i|l[i]||=0};1.upto(b){|i|l[-i]+=1+b-i}};l}
```
Input is a list of pairs, in the form `[[m1, n1], [m2, m2], ...]`.
The approach is pretty much the algorithm as described.
Golfy tricks I've used include:
* `l[i]||=0` setting the value for L to 0 if it isn't already set
* That's pretty much it.
Thanks to Value Ink for
[Try it online!](https://tio.run/##bY5NCsMgFIT3PYXLBF@C5qcUgr2IuNBCQLBpKA2kRM9uVQKljZsRvpl5znNRbz8ihnx1XbcJDCPAxbDWdzlvVoKypF7m16NQFcUTZrLcrLaGa2EtI26gu7vjSgvMKFaVdm4wzs9orG/SmIJzAq0AxCl08emhEaI8/fm/pDkQEstB@6TnzAUIrSYpPbg08C7DYyvNyqxqE/9q7ibdf2yzmbCEpFCfQpc0Ip47ByJK/wE)
Ruby can be pretty terse. When the version with numbered block parameters comes out, this can be reduced by a few bytes to this (note the `@1` ins:
```
->x{n,l=0,[];x.map{|a,b|0.upto(b-1+n+=a){l[@1]||=0};1.upto(b){l[-@1]+=1+b-@1}};l}
```
[Answer]
# [J](http://jsoftware.com/), 20 bytes
```
+/@(0>.>:@i.@+-])+/\
```
[Try it online!](https://tio.run/##RY89DsIwDIX3nuKJpY3apvlrgUhFPQhMCAtYGDpz9uAkRJGV2Ja/55e8A@2rhILnE/pp69RFXvz2kls/3kQ/XYNoDhItrbLFgK8H7U3zuD8/0DCwGD26wQoQJyXyxGLBGdpAK66YcJi5IPbgKOrUcOa55ohTV2aWBZZlKrkwERuTGI05U0VvEl1vlx1jELccZWtkM68rWUoqy@r2/I4TNEtduY8wKv6tmsffxUUqwbGjv5HDEn4 "J – Try It Online")
I guess this is quite different from both [Galen Ivanov's](https://codegolf.stackexchange.com/a/194829/78410) and [Jonah's](https://codegolf.stackexchange.com/questions/194800/its-as-easy-as-1-2-3-except-you-have-to-add-them-up#comment463904_194823) answers. A dyadic train that takes `n`s as left argument and `m`s as right.
One trick was to avoid `(...)"0` (apply to each item) in favor of `...@+`. The conjunction `u@v` has the effect of `u@:v"v`. The rank-forcing effect is usually not desirable when `v` is an arithmetic verb, but it works perfectly here.
### How it works
```
+/@(0>.>:@i.@+-])+/\ Left(n): range generators ex) 3 4 2
Right(m): offsets ex) 0 1 5
+/\ cm: Cumulative sum of offsets ex) 0 1 6
+ Add n and cm element-wise ex) 3 5 8
i.@ Generate 0..x-1 for each x above
ex) 0 1 2;0 1 2 3 4;0 1 2 3 4 5 6 7
>:@ Increment each value
ex) 1 2 3;1 2 3 4 5;1 2 3 4 5 6 7 8
(Implicit) Form a 2D array, padding with 0s where needed
-] Subtract each item of cm from each row of above
ex) 1 2 3 0 0 0 0 0
0 1 2 3 4 -1 -1 -1
-5 -4 -3 -2 -1 0 1 2
0>. Max with 0; Change negative numbers to 0s
+/@( ) Take sum in column direction
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 19 bytes
```
1⊥0⌈(↑(⍳+)¨-⊢)∘(+\)
```
[Try it online!](https://tio.run/##VY6xasMwEIZ3P8WNEo7BkpzQvUsyFZqOWQyNisFNjO0hJmQqhGAq0w6BLl0KBW8d0i4Z/Sj3Iu5JdYdwcLr79f2/FGdpcF/F6fqh3wqsP3H/iua8ZWh@0HyHfITmRMKua/0FaTvPUSE@H4jcBGhaAjpqZ3@D@5c/qP9nGEEUdfJ51wZYf3A8vDF/wXtNLJoGm@PsBuun7kvZh5vj/Paa@t10Nu9Z6D6ghxPQvMPyMSsriPM8rkZQrCEpIcuTVVlAXAyXabJaekyQR5FXOO/lLrkXwRgmoCG05SmQINwmQXpimCPSI1LsLGBMHlsalC2iJCi321tplZBCr8BGaxcoaZ78Ag "APL (Dyalog Unicode) – Try It Online")
Uses the algorithm described in [my J answer](https://codegolf.stackexchange.com/a/195066/78410).
### How it works
```
1⊥0⌈(↑(⍳+)¨-⊢)∘(+\) left = n's, right = m's
∘(+\) m2 = cumulative sum of m's
(⍳+)¨ Nested array of 1..(each element of n+m2)
-⊢ Subtract each elem of m2 from each row
(↑ ) Promote nested array to matrix
0⌈ Take max with 0 (change negatives to 0)
1⊥ Sum in column direction
```
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 bytes
```
{1⊥↑⍺{(⍵⍴0),⍳⍺}¨+\⍵}
```
[Try it online!](https://tio.run/##VYwxa8MwEIV3/4o3OjQBS3JC9i7NFIgzdhHEKgY3MbYXEzIFMhhk2sFjx0K2Dm2Xjvkp90fck/ASHkj33t33dJHPdo3ODy/DcBTUftLlnezfMST7S/YnmkzJfnNwul0fnjk7DYYub2Q76vrVmtrz7Us5pOuTzSO/26dVMoSRR834g@wH0teibqDLUjdTVAdkNYoy29cVdDUu82yfBqFgRjErPHvv5SSIMccCBpFToCAhvJOQgRjnmPOYEzcLzJlxMlBOfCWhvHdb6ZKIS5dw1cYXSp4X/w "APL (Dyalog Unicode) – Try It Online")
A dyadic dfn whose left argument is the `n`s and right argument is `m`s.
### How it works
```
{1⊥↑⍺{(⍵⍴0),⍳⍺}¨+\⍵}
{ } ⍺ = n's, ⍵ = m's
+\⍵ Cumulative sum of offsets (M)
⍺{ }¨ Zip with n's
(⍵⍴0),⍳⍺ ... to create M zeros followed by 1..n
↑ Promote to matrix, filling zeros where necessary
1⊥ Sum column-wise
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~62...50~~ 45 bytes
```
Plus@@PadRight[a=1;Ramp@Range[a-=#,#2]&@@@#]&
```
[Try it online!](https://tio.run/##TY3NCoMwEITvvkbAU6QmUSmUlH0E8SoeltY/qCJtepI8e7ouFb0M@83s7E7ohnZCNz4wdDaUr@8HoMRnNfaDq9GqW4XTAhXOfVtjYoUUuokBQDRxKN/j7GqR3LsNL7BG65pK472kQe9DKjMvSXPWYjcNoZaaVe2mIswO3HYU13PaZNMwHnoqqv81c47oeMpZztmVH2zlghwf@fAD "Wolfram Language (Mathematica) – Try It Online")
Input a list of pairs.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 77 bytes
```
for N;{
b=($N)
for((i=0,p+=b;i<p+b[1];a[i]+=++i>p?i-p:0)){ :;}
}
echo ${a[@]}
```
[Try it online!](https://tio.run/##TUxLDsIgFNy/U7xFEyBoAv3FtKKeoBdouihGUlYlumx6dgSs1s1M5qvH1@QNZdSb@Yldu4BWNOsYBEmpVeLguNKtPTuuezm0Y28Hrji3F3e1R9cIxhZs2hVWeNynGbNl7G/D6hmAAYNEYEEiy8D4MUoSsUpYk28JSY55Qrl5Mqjyp2JDpm0VetErktpxX8ntqfhLwq9IUZWiUzqP0zo44N8 "Bash – Try It Online")
I couldn't port [my first Zsh answer](https://tio.run/##NU3LCsIwELznKxZUSFihSdOImPRLxEMvwRxai96UfnuctA3LMDsz@/h@njlKJXN8vWmkyReWMvX6PHM/@hQmP9xnTg/umZNSNxFCOP4GBprDqdHLkpUQUUTSZAnUbqSpAxxwoT1s1zKbNMhNTYpwyCAt2op90Kx7tlo4Udwyf4XT4YET@Q8) directly, since `${a[@]/#%/0}` doesn't work in Bash. So instead of fixing the empty elements at the end, I set all the elements with `a[i]+=0` along the way. ~~In the end, this strategy works out better for Zsh anyway!~~
[Answer]
# C, ~~204~~ ~~196~~ ~~195~~ ~~192~~ 185 bytes
```
*c(m,n,q,x,p,z)int*m,*n;{int i,j,*a=malloc(4);for(i=p=z=0;m[i]+1;i++){q=n[i]+(p+=m[i]);a=realloc(a,8*((x=z)>q?z:(z=q)));bzero(a+x,(z-x)*8);for(j=p;j<q;j++)a[j]+=j-p+1;}a[z]--;return a;}
```
De-golfed version:
```
* count (m, n, size_of_array, pointer_into_array, previous_size_of_array, final_element_counted_to) //all but m and n are implicitly int - return type of function is implicitly int pointer
int* m, * n;
{
pointer_into_array = size_of_array = 0;
int* array = malloc(sizeof(int)); //get a pointer so we can realloc later
for (int i = 0; m[i] + 1; i++) { //iterate through m and n, stopping at -1 sentinel value
final_element_counted_to = n[i] + (pointer_into_array += m[i]); //update pointer, get final element counted to on this pair
array = realloc(array, sizeof(int) * 2 * ((previous_size_of_array = size_of_array) > final_element_counted_to ? size_of_array : (size_of_array = final_element_counted_to) + 1)); //reallocate array to size of max(size_of_array, final_element_counted_to+1) * sizeof(int) * 2 [multiplying by 2 for the final statement of a[z] = -1]
bzero(array + previous_size_of_array, (size_of_array - previous_size_of_array) * sizeof(int) * 2); //initialises new memory to zero
for(int j = pointer_into_array; j < final_element_counted_to; j++) //do the actual counting + adding
array[j] += j - pointer_into_array + 1;
}
array[size_of_array]--; //make sure it's terminated by -1
return array;
}
```
[Try it online!](https://tio.run/##XZBBboMwEEX3nGKaqpINQwNVEkWdOD1Be4GIhUNIagQGXCJRI85ODcmmWdjyfL0Z//lpeEnT8VnptLieMtj9tKdCHV@/994/TVWPklH64rTRT1mJGhvssEbLlW79En1NvXuBwhx9KUpZFFXKVpzOlWFK1MKKiMqDSoKYVBDwvhF6qlgdiEnmJIXJbl0Stz5jnbB833zYd2ZFwzmno81MxWTQIbNhx/3tbXguasp3DeVuqjzkSSDysHa/DPJgkzAkk7VXo0HSME4GS6k0MA69BzDXh00CAvo3hBjB3SuEDUIYDwTLpTRG/sLnndV3No4Q1gjbGV4/wF832IcOwMFTWKA5OdW5BTaH5PSIoHN7w5Nw7QRTJrMngNoF3Z7Z4uUEC5yhuXtw575LRN7gjX8 "C (gcc) – Try It Online")
Function `c` takes two arguments (rest are for free declaration) `m` and `n`, both -1 terminated arrays corresponding respectively to the two separate lists for m and n. It returns a -1 terminated array.
Please note that this requires `sizeof(int)` to be 4, and also requires the non-standard and deprecated but widely-implemented function `bzero`.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 30 bytes
```
{+/0^(1+!'y)@'-n-\:!*|y+n:+\x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/Nqlpb3yBOw1BbUb1S00FdN083xkpRq6ZSO89KO6ai9n9atJGCoYKRgomCmbWhgYKpggWQaRr7HwA "K (ngn/k) – Try It Online")
[Answer]
# Java, 642 Bytes
This I think is kind of awful, but doing it with Java who knows what I was expecting. If someone could help me make this better I would really appreciate that, a bunch of bytes are taken up dealing with the fact that combiner can get two different length lists and need to add them, and also with the fact that there is a type needed for the BiConsumer lambda. I think there are a few ways, but it's getting late...
Input is n, expected to be an array of arrays.
```
IntStream.range(0, n.length).mapToObj((x) -> new int[] { n[x][0] + (x > 0 ? n[x - 1][0] : 0), n[x][1]})
.map((v) -> IntStream.range(0, v[0] + v[1]).map((x) -> x >= v[0] ? 1 + x - v[0] : 0).toArray())
.collect(Collector.of(
() -> new ArrayList<>(),
(BiConsumer<List<Integer>, int[]>) (l, v) -> IntStream.range(0, Math.max(l.size(), v.length)).forEach((i) -> {
if (i >= l.size()) l.add(0);
if (i < v.length) l.set(i, l.get(i) + v[i]);
}),
(a, b) -> {
while (a.size() > b.size()) b.add(0);
while (b.size() > a.size()) a.add(0);
return IntStream.range(0, a.size()).mapToObj((i) -> a.get(i) + b.get(i)).collect(Collectors.toList());
},
Characteristics.IDENTITY_FINISH
));
```
Improved and golf'd by Kevin Cruijssen:
```
n->IntStream.range(0,n.length).mapToObj(x->new int[]{n[x][0]+(x>0?n[x-1][0]:0),n[x][1]}).map(v->IntStream.range(0,v[0]+v[1]).map(x->x<v[0]?0:1+x-v[0]).toArray()).collect(Collector.of(()->new Stack<>(),(java.util.function.BiConsumer<List<Integer>,int[]>)(l,v)->IntStream.range(0,Math.max(l.size(),v.length)).forEach(i->{if(i>=l.size())l.add(0);if(i<v.length)l.set(i,l.get(i)+v[i]);}),(a,b)->{while(a.size()>b.size())b.add(0);while(b.size()>a.size())a.add(0);return IntStream.range(0,a.size()).mapToObj(i->a.get(i)+b.get(i)).collect(Collectors.toList());},Collector.Characteristics.IDENTITY_FINISH))
```
[Answer]
# Clojure, 170 Bytes
```
(fn [a](reduce #(mapv +(concat %1(repeat 0))%2)(mapv (fn [[x y]](concat(repeat x 0)(range 1(+ 1 y))))(reduce #(conj %1(mapv +[(nth(last %1)0)0]%2))[(first a)](rest a)))))
```
[Try it online!](https://tio.run/##dY7RisIwEEXf/YqBRZjBPCStFcFPCXkIMd1VurGkddGv785EF5Ft8zCEuWfuvaG7nK85TniMLbQwYZvAeoc5Hq8hwgd@@/4HNhguKfgR1oaVPvJPE60resjlyN7g7twT/KNuzGH26TOCwQ0YuBO/lzvTZzF9pFhM4xd2fpAg0qQdR5DF9pR55UlqlY@8iVbY51Mau8QFOF@r2ilr1JZnoyrniFaHA4xyEvwQhxlemPdtNbvVxVWrpszdLCHpFefKNLOEYW27oP3v/k7URXvNJX/zbFAvctxOF7Ap4L6UEtsdbxiffgE)
] |
[Question]
[
Given latitude/longitude of two points on the Moon `(lat1, lon1)` and `(lat2, lon2)`, compute the distance between the two points in kilometers, by using **any formula** that gives the same result as the haversine formula.
## Input
* Four integer values `lat1, lon1, lat2, lon2` in degree (angle) or
* four decimal values `ϕ1, λ1, ϕ2, λ2` in radians.
## Output
Distance in kilometers between the two points (decimal with any precision or rounded integer).
## Haversine formula
[](https://i.stack.imgur.com/hUhjO.png)
where
* `r` is the radius of the sphere (assume that the Moon's radius is 1737 km),
* `ϕ1` latitude of point 1 in radians
* `ϕ2` latitude of point 2 in radians
* `λ1` longitude of point 1 in radians
* `λ2` longitude of point 2 in radians
* `d` is the circular distance between the two points
(source: <https://en.wikipedia.org/wiki/Haversine_formula>)
## Other possible formulas
* `d = r * acos(sin ϕ1 sin ϕ2 + cos ϕ1 cos ϕ2 cos(λ2 - λ1))` [*@miles*' formula](https://codegolf.stackexchange.com/questions/161789/distance-between-two-points-on-the-moon#comment391848_161789).
* `d = r * acos(cos(ϕ1 - ϕ2) + cos ϕ1 cos ϕ2 (cos(λ2 - λ1) - 1))` [*@Neil*'s formula](https://codegolf.stackexchange.com/questions/161789/distance-between-two-points-on-the-moon/161802#comment391978_161802).
## Example where inputs are degrees and output as rounded integer
```
42, 9, 50, 2 --> 284
50, 2, 42, 9 --> 284
4, -2, -2, 1 --> 203
77, 8, 77, 8 --> 0
10, 2, 88, 9 --> 2365
```
## Rules
* The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963).
* Specify in the answer whether the inputs are in **degrees** or **radians**.
* No need to handle **invalid latitude/longitude values**
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes
```
ArcCos[Sin@#*Sin@#3+Cos[#2-#4]Cos@#*Cos@#3]1737&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Yb89@xKNk5vzg6ODPPQVkLTBprgwSUjXSVTWKBLKAwmDSONTQ3Nlf7nxZtYqTgkppelJqqo2AJZ5kawJkw6VgFfX0FPxARUJSZV/IfAA "Wolfram Language (Mathematica) – Try It Online")
Uses the formula `d = r * acos( sin ϕ1 sin ϕ2 + cos ϕ1 cos ϕ2 cos(λ2 - λ1) )` where `r = 1737`
[Answer]
# [R](https://www.r-project.org/) + [geosphere](https://cran.r-project.org/web/packages/geosphere/), ~~54~~ 47 bytes
```
function(p,q)geosphere::distHaversine(p,q,1737)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NAp1AzPTW/uCAjtSjVyiols7jEI7Estag4My8VJKljaG5srvk/TSNZw1LHxEhTJ1nDSMfUQFPzPwA "R – Try It Online")
Takes input as 2-element vectors of `longitude,latitude` in degrees. TIO doesn't have the `geosphere` package but rest assured that it returns identical results to the function below.
Thanks to Jonathan Allan for shaving off 7 bytes.
# [R](https://www.r-project.org/), 64 bytes
```
function(p,l,q,k)1737*acos(sin(p)*sin(q)+cos(p)*cos(q)*cos(k-l))
```
[Try it online!](https://tio.run/##K/qfrmCj@z@tNC@5JDM/T6NAJ0enUCdb09Dc2FwrMTm/WKM4EyiqqQWiCjW1QSJAHogqhFDZujmamv/TNUyMtAoy9Q0tDHQsYQxTAxgLJqf5HwA "R – Try It Online")
Takes 4 inputs as in the test cases, but in radians rather than degrees.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 65 bytes
```
(a,b,c,d,C=Math.cos)=>1737*Math.acos(C(a-c)+C(a)*C(c)*(C(d-b)-1))
```
[Try it online!](https://tio.run/##lZC/DsIgEId3nuJGDqGWqgGHunRyMPEVKP2jpinGNr4@Ytcy0OnCl/vdd9zLfM1kP8/3LEbXtL4rPTW85pY3vCpvZn5k1k1YXqQ6KLa8TQC0okZY3IWCrKIWWSCNqFFIRG/dOLmhzQbX044SgGMBDJbw/Qp7kDrngZ4hRk95jBarXoJIyMqUmuYbtvqb1l@KjhRFOpVpIqViYR3Vp/ZGRXLD6bROPp3/AQ "JavaScript (Node.js) – Try It Online")
Based on Kevin Cruijssen's answer, Miles' and Neil's comments, and upon request of Arnauld.
[Answer]
# JavaScript (ES7), 90 bytes
*Note: see [@OlivierGrégoire's post](https://codegolf.stackexchange.com/a/161862/58563) for a much shorter solution*
A direct port of [TFeld's answer](https://codegolf.stackexchange.com/a/161793/58563). Takes input in radians.
```
(a,b,c,d,M=Math)=>3474*M.asin((M.sin((c-a)/2)**2+M.cos(c)*M.cos(a)*M.sin((d-b)/2)**2)**.5)
```
[Try it online!](https://tio.run/##lZDBDoMgDIbvPAVHYIDKNLKDu@9AsldA1OliZBlmr8/U7SYHPDRt/vzt1/apP9qZ9/Ca2WSb1neVR5rW1NCGqkrpucfV9ZyXOVFcu2FCSPEtGaZxIjAh4qS4sQ4ZTH6FXovN07D671mCF9gbOzk7tny0D9QhAGEuIIErhd9vMIGZTOmiXmBILdKQKnZegDEAO1JsNz2w1UranxQcyUS8msWByjLULIP4WG8QlB14nZTRr/Nf "JavaScript (Node.js) – Try It Online")
# Using the infamous [`with()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with), 85 bytes
*Thanks to @l4m2 for saving 6 bytes*
```
with(Math)f=(a,b,c,d)=>3474*asin((sin((c-a)/2)**2+cos(c)*cos(a)*sin((d-b)/2)**2)**.5)
```
[Try it online!](https://tio.run/##lZA7DoMwDIb3nCJjnCY8UhDpQPcOlXqFEKCAEKka1B4/BdSNDGGwLf1@fLYH9VFWv/vXzCdTN859@7kjdzV30JZEsYppVkN5PWdFRpXtJ0I2p7mCWACl4qSNJRroGhTQLVvz6p9dLMrBaTNZMzbRaJ6kJQjjTGCKV0z0uOEYpzJhi3rBPjVPfKrY1SIAhHak0G52YKuVtD/JO5KLcDUNAxWFr1l68aG1XlB64HVSBr/O/QA "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~40~~ 35 [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")
Anonymous tacit function. Takes {ϕ₁,λ₁} as left argument and {ϕ₂,λ₂} as right argument.
Uses the formula 2 r √(sin²((ϕ₁-ϕ₂)⁄2) + cos ϕ₁ cos ϕ₂ sin²((λ₁ – λ₂)⁄2))
```
3474ׯ1○.5*⍨1⊥(×⍨1○2÷⍨-)×1,2×.○∘⊃,¨
```
[Try it online!](https://tio.run/##TcwxCoMwFMbxvad4oykqvjSSeBwh0EVocetcKKIU3J4XKLg5dk9ukoukj9hCtz8/Pr722hX21naXc4w2POaT0sqT2zDQVNbH8FwxjK/MUyqapH9zFcIT5tJTyRSGJYz33K2x5wMGngwLmipmPSgJ0AiwwF1XIMVhD64dedAkBAVu@ykXYGKtAcxXuU1C/Dswhg8@ "APL (Dyalog Unicode) – Try It Online") (the `r` function converts degrees to radians)
---
`,¨` concatenate corresponding elements; {{ϕ₁ , ϕ₂} , {λ₁ , λ₂}}
`⊃` pick the first; {ϕ₁ , ϕ₂}
`∘` then
`2×.○` product of their cosines; cos ϕ₁ cos ϕ₂
lit. dot "product" but with trig function selector (2 is cosine) instead of multiplication and times instead of plus
`1,` prepend 1 to that; {1 , cos ϕ₁ cos ϕ₂}
`(`…`)×` multiply that by the result of applying following function to {ϕ₁ , λ₁} and {ϕ₂ , λ₂}:
`-` their differences; {ϕ₁ - ϕ₂ , λ₁ - λ₂}
`2÷⍨` divide that by 2; {(ϕ₁ - ϕ₂)⁄2 , (λ₁ - λ₂)⁄2}
`1○` sine of that; {sin((ϕ₁ - ϕ₂)⁄2) , sin((λ₁ - λ₂)⁄2)}
`×⍨` square that (lit. self-multiply); {sin²((ϕ₁ - ϕ₂)⁄2) , sin²((λ₁-λ₂)⁄2)}
Now we have {sin²((ϕ₁ - ϕ₂)⁄2) , cos ϕ₁ cos ϕ₂ sin²((λ₁ - λ₂)⁄2)}
`1⊥` sum that (lit. evaluate in base-1); sin²((ϕ₁-ϕ₂)⁄2) + cos ϕ₁ cos ϕ₂ sin²((λ₁ - λ₂)⁄2)
`.5*⍨` square-root of that (lit. raise that to the power of a half)
`¯1○` arcsine of that
`3474×` multiply that by this
---
The function to allow input in degrees is:
```
○÷∘180
```
`÷180` argument divided by 180
`○` multiply by π
[Answer]
# [Python 2](https://docs.python.org/2/), 95 bytes
```
lambda a,b,c,d:3474*asin((sin((c-a)/2)**2+cos(c)*cos(a)*sin((d-b)/2)**2)**.5)
from math import*
```
[Try it online!](https://tio.run/##hY3NDoIwEITvPMUe27oolCJo4pt4WWgITexPoBefHrEYTxIPM3OYbzLhGUfv5DLc7suDbKcJCDvsUV8r1ShBs3GMJetz4ifJhZCH3s@s5@IdxEVqdd592lXHmmfD5C1YiiMYG/wUxRIm4yIMTFgKbCJtyM3IlES4INQFguScr96q7DeaGIS0@IMqhFxuKje0qHbQpkFoEVIktNgBy@2@bb/31bleXg "Python 2 – Try It Online")
Takes input in radians.
---
Old version, before i/o was slacked:
Takes input as integer degrees, and returns rounded dist
# [Python 2](https://docs.python.org/2/), 135 bytes
```
lambda a,b,c,d:int(round(3474*asin((sin((r(c)-r(a))/2)**2+cos(r(c))*cos(r(a))*sin((r(d)-r(b))/2)**2)**.5)))
from math import*
r=radians
```
[Try it online!](https://tio.run/##XY29DoMwDIR3nsJjnJoWQii0Em/SJRAhkEqCAh369DSEn6HD2dZ9p/P4nTtrxNJWr@WthlorUFRTQ/rZm5k5@zGaZbKQXE29YSwMxxqMHVOIN4Gci0tjp2Ai3y5P@J7Ua7I@kl7XHBGj1tkBBjV30A@jdTOPXOWU7pWZltH519AyKQgeBHlCINCrlNGBgkcQEn9IEsRiU7qiJDtRURCUBGF5lJwg3erKcq/L7vnyAw "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~55~~ 50 bytes
```
MsU *MsW +McU *McW *McX-V
ToMP1/7l¹ñ@McX aUÃv *#7
```
Not necessarily quite as precise as the other answers, but boy did I have fun with this one. Allow me to elaborate.
While in most languages, this challenge is quite straightforward, Japt has the unfortunate property that there is no built-in for neither arcsine nor arccosine. Sure, you can embed Javascript in Japt, but that would be what ever the opposite of Feng Shui is.
All we have to do to overcome this minor nuisance is [approximate arccosine](https://www.karltarvas.com/2018/04/10/japt-approximating-arccos.html) and we're good to go!
The first part is everything that gets fed into the arccosine.
```
MsU *MsW +McU *McW *McX-V
MsU // Take the sine of the first input and
*MsW... // multiply by the cos of the second one etc.
```
The result is implicitly stored in `U` to be used later.
Following that, we need to find a good approximation for arccosine. Since I'm lazy and not that good with math, we're obviously just going to brute-force it.
```
ToMP1/7l¹ñ@McX aUÃv *#7
T // Take 0
o // and create a range from it
MP // to π
1/7l¹ // with resolution 1/7!.
ñ@ // Sort this range so that
McX // the cosine of a given value
aU // is closest to U, e.g. the whole trig lot
// we want to take arccosine of.
à // When that's done,
v // get the first element
*#7 // and multiply it by 1737, returning implicitly.
```
We could've used any large number for the generator resolution, manual testing showed `7!` is sufficiently large while being reasonably fast.
Takes input as radians, outputs unrounded numbers.
Shaved off five bytes thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver).
[Try it online!](https://tio.run/##y0osKPn/37c4VEHLtzhcQds3GcRKDgcREbphXCH5vgGG@uY5h3Ye3ugAFFJIDD3cXKagpXxorfn//wZ6BmaWFobGhuYGBuaW5ubGhhZcukBBYxNLAzNTC1MDY0sLCzNTS@yCQDFDcxNTYyNLI1NDS0sTIMMUAA)
[Answer]
# Java 8, ~~113~~ ~~92~~ ~~88~~ 82 bytes
```
(a,b,c,d)->1737*Math.acos(Math.cos(a-c)+Math.cos(a)*Math.cos(c)*(Math.cos(d-b)-1))
```
Inputs `a,b,c,d` are `ϕ1,λ1,ϕ2,λ2` in radians.
-21 bytes using [*@miles*' shorter formula](https://codegolf.stackexchange.com/questions/161789/distance-between-two-points-on-the-moon#comment391848_161789).
-4 bytes thanks to *@OlivierGrégore* because I still used `{Math m=null;return ...;}` with every `Math.` as `m.`, instead of dropping the `return` and use `Math` directly.
-6 bytes using [*@Neil*'s shorter formula](https://codegolf.stackexchange.com/questions/161789/distance-between-two-points-on-the-moon/161802#comment391978_161802).
[Try it online.](https://tio.run/##jVBBTsMwELzzij3aYR2aUJSgCu4cWiH1iDhsbAMpqVPVbiWE@vZgJy5NbpVsa2a9q5nZDR1JbNR3JxuyFpZUm98bgNo4vf8gqWEVKIBqD1WjQbIICCOozkCegeILP3Ly1x/ryNUSVmDgCTpGWKFv5OI5K@6LZEnuKyXZWtajAEhIfnthPPnHkieXNiUqLjLOu8Wgs/PSXifKHdtawdZnYWu3r83n2zsQH4I4bR2b5/iIDzPMe6uxGDiGn3FxjiIPJxsXiwJLDM@4mIXxsozj0/i9n77rmvUNRtc/1ult2h5cuvMZXGOYSSWjYSGvL3dZOUOoplROqRpTHo2duj8)
**Explanation:**
```
(a,b,c,d)-> // Method with four double parameters and double return-type
1737*Math.acos( // Return 1737 multiplied with the acos of:
Math.cos(a-c) // the cos of `a` minus `c`,
+Math.cos(a)*Math.cos(c) // plus the cos of `a` multiplied with the cos of `c`
*(Math.cos(d-b)-1)) // multiplied with the cos of `d` minus `b` minus 1
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~68 66 52~~ 51 bytes
```
s=cos;(a!b)c d=1737*acos(s(a-c)+s a*s c*(s(d-b)-1))
```
[Try it online!](https://tio.run/##HYjBCoMwEAXvfsUTetiNhBptsaXkY9YoGLRWsv5/KrnMMLOIrvO25aw@/PRDUo8cMHk39IORa5GS2MCNQowimKsnO7J1zDl5OuLdvVrDVfWVuMPjSHE/cQPVDEp4dEXvwmdb1HH@Aw "Haskell – Try It Online")
-1 byte thanks to BMO
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~87 70 69~~ 68 bytes
```
->{extend Math;1737*acos(cos(_1-_3)+cos(_1)*cos(_3)*(cos(_4-_2)-1))}
```
### Unfortunately, TIO doesn't support `_1` syntax so for TIO, 69 bytes
```
->a,b,c,d{extend Math;1737*acos(cos(a-c)+cos(a)*cos(c)*(cos(d-b)-1))}
```
[Try it online!](https://tio.run/##nc89D4IwEAbg3V9xwcXWq7YFpGJkdzBxJwzlKzKoRCDRAL8dY1lkIw5v7nLJPcn7bOL3kB8HFmiMMcG0zV51dk/hrOvrQXi2R3XyqFbfaJaQtVkINTdCzT1lMWGCkH4om7oCa9nmIQ0dibBHcDmCjDY3XULbFR0UQI3t@5cTbEEo3kc9MBaAVI61@BXMK4KB/hMcBCbHiHkCt6eC5yEoBDNmCXz6L8YOSs3uYO9ca/gA "Ruby – Try It Online")
Now using Neil's method, thanks to Kevin Cruijssen.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23 22~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-4 bytes thanks to miles (use of `{` and `}` while using [their formula](https://codegolf.stackexchange.com/a/161824/53748).
```
;I}ÆẠP+ÆSP${ÆA×⁽£ġ
```
A dyadic function accepting `[ϕ1, ϕ2,]` on the left and `[λ1, λ2]` on the right in **radians** that returns the result (as floating point).
**[Try it online!](https://tio.run/##FcoxCgJBDAXQq1jYKUtmMvlJsLK0W7CULW1kLyBiYTNXsFW8hWDjeBG9SGRf/Q77cTxGrDbnVr/PW79oddvPT62u2/V3eb0fn3tE7KhTZmLLJsaKZGU5o840AwVZ3DWh2DDFJErq4Az1Yg5Mk7g4QUyI3Qziwx8 "Jelly – Try It Online")**
---
Mine... (also saved a byte here by using a `{`)
```
,IÆẠCH;ÆẠ{Ḣ+PƊ½ÆṢ×⁽µṣ
```
[Try it online](https://tio.run/##y0rNyan8/1/H83Dbw10LnD2swXT1wx2LtAOOdR3aC@TuXHR4@qPGvYe2Pty5@P///9EGeubGxgbGFkYWphbG5maGFiY6CgZ6FuZGZmYmZkamlpbmhmYmFrEghYam5gbmlmbGRmbmliYWlmZmIJUGxiaWBmamFqYGxpYWFmamlrEA "Jelly – Try It Online")
[Answer]
# MATLAB with Mapping Toolbox, 26 bytes
```
@(x)distance(x{:})*9.65*pi
```
Anonymous function that takes the four inputs as a cell array, in the same order as described in the challenge.
Note that this gives exact results (assuming that the Moon radius is 1737 km), because `1737/180` equals `9.65`.
Example run in Matlab R2017b:
[](https://i.stack.imgur.com/IMsGS.png)
[Answer]
# Python 3, 79 bytes
```
from geopy import*
lambda a,b:distance.great_circle(a,b,radius=1737).kilometers
```
TIO doesn't have geopy.py
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 29 [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")
Complete program. Prompts stdin for {ϕ₁,ϕ₂} and then for {λ₁,λ₂}. Prints to stdout.
Uses the formula r acos(sin ϕ₁ sin ϕ₂ + cos(λ₂ – λ₁) cos ϕ₁ cos ϕ₂)
```
1737ׯ2○+/(2○-/⎕)×@2×/1 2∘.○⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM95b@hubH54emH1hs9mt6tra8BonT1H/VN1Tw83cHo8HR9QwWjRx0z9IDCQEGQFq6iR20TgNzD24HihhYG/xXAIIWrSMHESMHUAEgrWCooGHEhxE0NgFIgcSOgFJK4gokC0GIgA0gqKBgiyZibAxFIhQUQIYkbGihYWMBMAgA "APL (Dyalog Unicode) – Try It Online") (the `r` function converts degrees to radians)
---
`⎕` prompt for {ϕ₁,ϕ₂}
`1 2∘.○` Cartesian trig-function application; {{sin ϕ₁,sin ϕ₂} , {cos ϕ₁,cos ϕ₂}}
`×/` row-wise products; {sin ϕ₁ sin ϕ₂ , cos ϕ₁ cos ϕ₂}
`(`…`)×@2` at the second element, multiply the following by that:
`⎕` prompt for {λ₁,λ₂}
`-/` difference between those; λ₁ – λ₂
`2○` cosine of that; cos(λ₁ – λ₂)
Now we have {sin ϕ₁ sin ϕ₂ , cos(λ₁ – λ₂) cos ϕ₁ cos ϕ₂}
`+/` sum; sin ϕ₁ sin ϕ₂ + cos(λ₁ – λ₂) cos ϕ₁ cos ϕ₂
`¯2○` cosine of that; cos(sin ϕ₁ sin ϕ₂ + cos(λ₁ – λ₂) cos ϕ₁ cos ϕ₂)
`1737×` multiply r by that; 1737 cos(sin ϕ₁ sin ϕ₂ + cos(λ₁ – λ₂) cos ϕ₁ cos ϕ₂)
---
The function to allow input in degrees is:
```
○÷∘180
```
`÷180` argument divided by 180
`○` multiply by π
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~100~~ ~~88~~ ~~65~~ 64 bytes
88 → 65 using [*@miles' formula*](https://codegolf.stackexchange.com/questions/161789/distance-between-two-points-on-the-moon#comment391848_161789)
65 → 64 using [*@Neil's formula*](https://codegolf.stackexchange.com/questions/161789/distance-between-two-points-on-the-moon/161802#comment391978_161802)
```
#define d(w,x,y,z)1737*acos(cos(w-y)+cos(w)*cos(y)*(cos(z-x)-1))
```
[Try it online!](https://tio.run/##RZDRboIwFIbv@xRnGhOK4Ci6gHHufolbdrMrZhZsqTTBslgEYfHVhy3IbNq//f6e09OWuntK27GQNDuxBJ4PcZHO0hd0d1TBRK6tdswSLmQCzKqcs1M7DSbBPLBjmivLjMqt8bRbYNtMNbY7v3HP2CUYt0IWcIiFtMpcMPyLQDfjldFiu@qI5addlsDt/N6jaXyE3YlHxPOHuCoVOszi@6RQlt5zQIkmyblZYw36yhLDwxrePzcbDH0p05SiseR9ymjCYOgjB8qpZ4QY8Y3M8eo/r1q/fX@82mXkbR9J6DnngUnP9cB@z83A847vB/0c9Yu5NZrMPP4lddn7b97KXdClXfiwBHjyAHyk1QfQDizRAlw9m0FQEEAIoBVCRLqYUPPyj/Is3qvWzQ5X "C (gcc) – Try It Online")
[Answer]
# Excel, 53 bytes
```
=1737*ACOS(COS(A1-C1)+COS(A1)*COS(C1)*(COS(D1-B1)-1))
```
Using @Neil's formula. Input in Radians.
[Answer]
# [Lobster](http://strlen.com/lobster), 66 bytes
```
def h(a,c,b,d):1737*radians arccos a.sin*b.sin+a.cos*b.cos*cos d-c
```
Uses miles's formula, but input is in degrees. This adds extra step of converting to radians before multiplying by radius.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~119~~ 103 bytes
This uses degrees.
```
from math import*
def f(L):a,o,A,O=map(radians,L);return 1737*acos(cos(a-A)+cos(a)*cos(A)*(cos(O-o)-1))
```
[**Try it online!**](https://tio.run/##JY3NCoMwEITvPsWClyRdodEWaYuH3AUfoPSwVINCkw0xPfTprT@HYT6@OUz4pZF9teRA0MCHkkbgjdjrLAdzyBKhO2S52MgOHKURJhc4JpX1gwUrWnknZDTYNY6CiNRP5Gds5SMO6Rs96LqqFb15FluoMPK0g1RbGal23xUsCy3lEuLkk7DieVnfbwjXM0L5Woc/ "Python 3 – Try It Online")
[Answer]
# [PHP](https://php.net/), 88 bytes
*Port of [Oliver](https://codegolf.stackexchange.com/a/161862/78039) answer*
```
function f($a,$b,$c,$d,$e=cos){return 1737*acos($e($a-$c)+$e($a)*$e($c)*($e($d-$b)-1));}
```
[Try it online!](https://tio.run/##bYpBDoIwFETX7Sn@4i/6axspatCgchYobWBTGoSV8exYuzNhMzN58@IQt3sTU/o12GWcAniBrcJOoVXYK3QPO73oPbtlnQOY6lTJNhGBLnkaLR3yIvkrSzIfvcaOtCGqP5uzwwScecEBGDuXICGOguAI5lqoDG@wAy/FDiz/Tc6o5s1z@wI "PHP – Try It Online")
[Answer]
# SmileBASIC, 60 bytes
```
INPUT X,Y,S,T?1737*ACOS(COS(X-S)+COS(X)*COS(S)*(COS(T-Y)-1))
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 66 bytes
Clearly the other Wolfram Language golfers only care about *bytes*. *This* program uses the beauty of Mathematica.
```
GeoDistance@@Map[#~GeoPosition~Entity["PlanetaryMoon","Moon"]&,#]&
```
Either I am misusing TIO, or it doesn't work there. This works on my machine, though.
] |
[Question]
[
## Introduction
This challenge requires you to set the trailing zeros of an integers binary representation to `010101…`, this is best explained with an example:
Given the integer `400`, the first step is to convert it to binary:
```
110010000
```
As we can see the fifth bit is the least significant `1` bit, so starting from there we replace the lower zeros by `0101`:
```
110010101
```
Finally we convert that back to decimal: `405`
## Challenge
Given a positive integer return/output the corresponding resulting value of the above defined process.
## Rules
* This sequence is only defined for integers with at least one `1` bit, so the input will always be ≥ 1
* You may take input as a string, list of digits (decimal) instead
* You don't have to handle invalid inputs
## Testcases
Here are some more testcases with the intermediary steps (you don't have to print/return these):
```
In -> … -> … -> Out
1 -> 1 -> 1 -> 1
2 -> 10 -> 10 -> 2
3 -> 11 -> 11 -> 3
4 -> 100 -> 101 -> 5
24 -> 11000 -> 11010 -> 26
29 -> 11101 -> 11101 -> 29
32 -> 100000 -> 101010 -> 42
192 -> 11000000 -> 11010101 -> 213
400 -> 110010000 -> 110010101 -> 405
298 -> 100101010 -> 100101010 -> 298
```
[Answer]
# [Python 3](https://docs.python.org/3/), 20 bytes
```
lambda n:(n&-n)//3+n
```
[Try it online!](https://tio.run/##NYpBCoMwFET3OcXHRTF0RE1cVEEvYrtQ2tBA/YrJpqdPjSUwMLyZt339e2UdTH8Pn2mZnxNxl/OlYFmW@srBv5x31NNYQ0GjgTrSQivUrUJTVQfdHkKYdafokuWzXSdo2y37PBIoK4YMZE6SMn2z5f@ShDgkSYYf "Python 3 – Try It Online")
## Explanation
Take `192` as an example. Its binary form is `11000000`, and we need to convert it to `11010101`.
We note that we need to add `10101` to the number. This is a geometric series (`4^0 + 4^1 + 4^2`), which has a closed form as `(4^3-1)/(4-1)`. This is the same as `4^3//3` where `//` denotes integer division.
If it were `101010`, then it would still be a geometric series (`2×4^0 + 2×4^1 + 2×4^2`), which is `2×4^3//3` for the reasons above.
Anyway, `4^3` and `2×4^3` would just be the least significant bit, which we obtain by `n&-n`:
We notice that the complement of `n` is `00111111`. If we add one, it becomes `01000000`, and it only overlaps with `n=11000000` at the least significant digit. Note that "complement and add one" is just negation.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
&N:3+
```
[Try it online!](https://tio.run/##y0rNyan8/1/Nz8pY@3@0oY6RjrGOiY4REFnqGBvpGFoa6ZgYGAB5FjrGQLaRsYVF7OH2R01rIv8DAA "Jelly – Try It Online")
This time a port of [Leaky Nun's approach](https://codegolf.stackexchange.com/a/151543/59487) (at least I helped him golf it down a bit :P)
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
^N+4:6ạ
```
[Try it online!](https://tio.run/##y0rNyan8/z/OT9vEyuzhroX/ow11jHSMdUx0jIDIUsfYSMfQ0kjHxMAAyLPQMbY0ij3c/qhpTeR/AA "Jelly – Try It Online")
Uses [JungHwan Min's fantastic approach](https://codegolf.stackexchange.com/a/151544/59487), with indirect help from [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~36~~ ~~28~~ ~~26~~ 24 bytes
-8 bytes thanks to @MartinEnder and -2 bytes thanks to @Mr.Xcoder
```
#+⌊(#~BitAnd~-#)/3⌋&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1n7UU@XhnKdU2aJY15Kna6ypr7xo55utf8BRZl5JQ5aafoO1VxchjoKRjoKxjoKJkAGCFsCeUARQ0sgYWJgABKx4OKq/Q8A "Wolfram Language (Mathematica) – Try It Online")
We only need to find the number of the trailing zeroes in the input, and find the number with alternating `0`s and `1`s with length one less than that, and add it to the input.
So, `400 -> 11001000 -> 110010000 + 0000 -> 110010101 + 101 -> 405`
The explicit formula for `n`th number with alternating `1`s and `0`s was given in [A000975](http://oeis.org/A000975) on OEIS. We can use the `n`th number since no two different numbers can the same length in binary and have alternating digits.
[Answer]
# [J](http://jsoftware.com/), ~~19~~ 18 bytes
```
+(2|-.i.@#.-.)&.#:
```
[Try it online!](https://tio.run/##y/r/P81WT1vDqCZTzyFTT83QoUZPU01P2ep/anJGvkKaQmpZalGlgqGCkYKxgomCERBZKhgbKRhaGimYGBgAeRb/AQ "J – Try It Online")
# Quick Explanation
This is an old answer, but it is very similar in nature to the current one, it just counts the trailing zeroes differently. See the comments for a link explaining how it works.
```
+(2|i.@i.&1@|.)&.#:
#: Convert to binary list
i.&1@|. Index of last 1 from right
|. Reverse
i.&1 Index of first 1
i. Range [0, index of last 1 from right)
2| That range mod 2
&. Convert back to decimal number
+ Add to the input
```
### Other Answers:
Previous answer (19 bytes).
```
+(2|i.@i.&1@|.)&.#:
```
Longer than it should be because `\` goes right-to-left.
```
+(2|#*-.#.-.)\&.(|.@#:)
```
[Answer]
# [Julia 0.6](http://julialang.org/), 12 bytes
```
!n=n|n&-n÷3
```
[Try it online!](https://tio.run/##yyrNyUw0@/9fMc82ryZPTTfv8Hbj/2n5RQp5Cpl5ChqGOgpGOgrGOgomQAYIWwJ5QBFDSyBhYmAAErHQ5OJ0KCjKzCtJ01BSNS5V0LVTAFIxeUo6Cnk6Cop5mlypeSn/AQ "Julia 0.6 – Try It Online")
[Answer]
# JavaScript (ES6), ~~40~~ 39 bytes
Takes input as a 32-bit integer.
```
n=>n|((n&=-n)&(m=0xAAAAAAAA)?m:m/2)&--n
```
### Test cases
```
let f =
n=>n|((n&=-n)&(m=0xAAAAAAAA)?m:m/2)&--n
console.log(f(1)) // 1 -> 1 -> 1
console.log(f(2)) // 10 -> 10 -> 2
console.log(f(3)) // 11 -> 11 -> 3
console.log(f(4)) // 100 -> 101 -> 5
console.log(f(24)) // 11000 -> 11010 -> 26
console.log(f(29)) // 11101 -> 11101 -> 29
console.log(f(32)) // 100000 -> 101010 -> 42
console.log(f(192)) // 11000000 -> 11010101 -> 213
console.log(f(400)) // 110010000 -> 110010101 -> 405
console.log(f(298)) // 100101010 -> 100101010 -> 298
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ ~~8~~ 5 bytes
Saved 5 bytes thanks to *Mr. Xcoder* and [JungHwan Min's neat formula](https://codegolf.stackexchange.com/a/151544/47066)
Saved another 3 thanks to *Mr. Xcoder*
```
(&3÷+
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fQ8348Hbt//8NLY0A "05AB1E – Try It Online")
**Explanation**
```
( # negate input
& # AND with input
3÷ # integer divide by 3
+ # add to input
```
[Answer]
# [R](https://www.r-project.org/), ~~71~~ 58 bytes
*thanks to NofP for -6 bytes*
```
function(n){n=n%/%(x=2^(0:31))%%2
n[!cumsum(n)]=1:0
n%*%x}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPszrPNk9VX1WjwtYoTsPAythQU1NV1YgrL1oxuTS3uDQXqCTW1tDKgCtPVUu1ovZ/moahpZHmfwA "R – Try It Online")
Assumes input is a 32-bit integer. R only has signed 32-bit integers (casting to `double` when an integer overflows) anyway and no 64-bit or unsigned ints.
[Answer]
# [brainfuck](https://esolangs.org/wiki/Brainfuck), 120 bytes
```
>+<[[>-]++>[[>]>]<[>+>]<[<]>-]>[-<+>[-<[<]<]>]>[>]<[>+<[->+<]<[->+<]<]>>[<]+>[-[-<[->+<<+>]>[-<+>]]<[->++<]<[->+<]>>>]<<
```
[Try It Online!](https://tio.run/##dVJNb8IwDL3nV/g4qXQa0w6bGvk3cI9yCI2BiJKgJDC2P8/sfogdNh9i2X5@fq67zS7E3aU/3lcGm9FMq9vZ0Gq9pMV0axFXVt@x0cZga5sG2VvGMUxebTmLTNHIwyEnOJ4A2rT82MUxFwMEKFDJcdfcbCfUA40oYu5ctVptcoi1gIOehgGubrgQPFV3pAi7nE5AJQ0u7gtsd3B2e1IGWR7zjwugMlpGIUsVz2GLBrrPQxhoZqNbKLUoAPi9PnQnHsJz1y9SYmWt7C2im0n2GGkxC50P1@AXxu3X3CUrcC3FCpHIQz2EMi4ixWWU0ZNHwTrv4e0daoJMJ76XpzwRjVsIotSUiZnoX8SeZNytTmqkqLXi2yj@vtDRUGhWk2De8ZtyGknwD1HKqu4sVwAXPfQDuQzk@gOMSvxDBoTIwZVyIR71LOfj/2f98foD)
Starts with the value in the current cell and ends on the cell with the output value. Obviously won't work on numbers above 255 as that's the cell limit for typical brainfuck, but will work if you assume infinite cell size.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 168 bytes
```
param($n)$a=($c=[convert])::ToString($n,2);if(($x=[regex]::Match($a,'0+$').index)-gt0){$c::ToInt32(-join($a[0..($x-1)]+($a[$x..$a.length]|%{(0,1)[$i++%2]})),2)}else{$n}
```
[Try it online!](https://tio.run/##FY1BDoIwFEQv84n9KTSAKzEcwIUr3TVdNPiFmlpIaZQEOXsty8m8eTONX/LzQNbGOGmv3wwcgm4ZdK3sRvchHxQ2zX28BW9cn@q8xrN5MgZLKz31tKimuerQDQx0fig5HFAY96AFiz6UuEK3zy8uHGtWvEbjEidLIZKgqFDxPcIiBGhhyfVhUL9sZWVeoQTDeVarDTGdbmRnWsFtMcbqVP8B "PowerShell – Try It Online")
Ouch. Conversion to/from binary and array slicing are not really PowerShell's strong suits.
Takes input `$n` as a number. We immediately `convert` that to binary base `2` and store that into `$a`. Next we have an if/else construct. The if clause tests whether a `regex` `Match` against 1 or more `0`s at the end of the string (`'0+$'`) has its `index` at a location greater than `0` (i.e., the start of the binary string). If it does, we have something to work with, `else` we just output the number.
Inside the `if`, we slice of the `x`th first digits, and array-concatenate `+` those with the remaining digits. However, for the remaining digits, we loop through them and select either a `0` or `1` to be output instead, using `$i++%2` to choose. This gets us the `010101...` pattern instead of `0`s at the end. We then `-join` that back together into a string, and `$c`onvert it back into an `Int32` from base `2`.
In either situation, the number is left on the pipeline and output is implicit.
[Answer]
# APL+WIN, 43 bytes
```
p←+/^\⌽~n←((⌊1+2⍟n)⍴2)⊤n←⎕⋄2⊥((-p)↓n),p⍴0 1
```
Prompts for screen input
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~41~~ 36 bytes
```
param($n)$n+(($x=$n-band-$n)-$x%3)/3
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPUyVPW0NDpcJWJU83KTEvRRcopKtSoWqsqW/8//9/Q0sjAA "PowerShell – Try It Online") or [Verify all test cases](https://tio.run/##DcjRCoIwFIDh@57iIEfY8Izm5kVe2ItEyCpXgh1lGgnms6/Bf/P90/jtwvzqhiH6D9@XfmTwW5xccG@BLJELIXBtkNXN8UOlpXDNrTzauB/Qhed80ddfvmXYgjpDBgUID9jKPcaSDFmqyKRqsobK2lClddLpDw "PowerShell – Try It Online")
Port of Leaky Nun's [Python answer](https://codegolf.stackexchange.com/a/151543/42963).
*Saved 5 bytes thanks to Leaky Nun*
[Answer]
# [PHP](https://php.net/), 47 bytes
```
<?php function b($a){echo(int)(($a&-$a)/3)+$a;}
```
[Try it online!](https://tio.run/##K8go@P/fxr4go0AhrTQvuSQzP08hSUMlUbM6NTkjXyMzr0RTA8hV0wUK6RtraqskWtf@T9IwMTDQtP4PAA "PHP – Try It Online")
Really just another port of @Leaky Nun's solution
[Answer]
# [Perl 5](https://www.perl.org/), 54 bytes
```
$_=sprintf'%b',<>;1while s/00(0*)$/01$1/;say oct"0b$_"
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3ra4oCgzryRNXTVJXcfGztqwPCMzJ1WhWN/AQMNAS1NF38BQxVDfujixUiE/uUTJIEklXun/f5N/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 56 bytes
```
lambda n:eval((bin(n).rstrip("0")+"01"*n)[:len(bin(n))])
```
[Try it online!](https://tio.run/##LcrNCoMwEATgu0@x5JRttyU/HqpgX8R6iFRpIF0lCYU@fapSGBg@ZtZvfi1sy9w9SnDv8emA2@njgpSjZ8l4jSlHv0qhBJ6F0uLE2Ldh4v@OA5Y8pZygg16TIUs1mS0NWUO6MVQrtek2VNW8RNi/4Pno1FawRs9Z7iIQl7sgmA8hlh8 "Python 3 – Try It Online")
Not really happy with this yet, but I really didn't want to use the formula... -2 thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod). -1 thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 15 bytes
Another port of Leaky Nun's approach.
```
->k{(k&-k)/3+k}
```
[Try it online!](https://tio.run/##JY7NCoMwEITv@xRTpZJQtJp4qIX6JIVi/QGJVdGEUsRnT5N2mMPOt8syi3l@bGfGGjfcbVyqjakoVvwsT2q3ul316jbHN8sgIJFDOBeQAlkhkKepSxdOv8PkVc0HFl319Og5UTct8Bz9iP@jZiI4zcbNQbh5uCMuEW6@QVJXw8A85HtA7diQ/QI "Ruby – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), 18 bytes
A port of Leaky Nun's approach
```
|n:i32|(n&-n)/3+n;
```
[Try it online!](https://tio.run/##KyotLvmflqeQm5iZp6GpUM2lAAQ5qSUKFQq2Cv9r8qwyjY1qNPLUdPM09Y2186z/g@QLijLzSnLyFDWUqmuVdBQqNAwtjTQ1rblq/wMA "Rust – Try It Online")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 24 bytes
A port of JungHwan Min's Mathmatica answer
```
$0=int(and($0,-$0)/3+$0)
```
[Try it online!](https://tio.run/##SyzP/v9fxcA2M69EIzEvRUPFQEdXxUBT31gbSP7/b2hpBAA "AWK – Try It Online")
[Answer]
# JavaScript ES6, 13 bytes
```
n=>(n&-n)/3|n
```
```
f =
n=>(n&-n)/3|n
;
console.log (f(8));
console.log (f(243));
console.log (f(1048576));
console.log (f(33554432));
```
[Answer]
# C, 56 bytes
```
i,k;f(n){for(k=i=1;n>>i<<i==n;k+=++i&1)k*=2;return n|k;}
```
[Try it online!](https://tio.run/##fc5BCsIwEAXQfU8RCkpiKzS1C8t0ehI3Eo0MwVFCXdWePUa3Os7yP/h/3PbiXEpUB/CazexvUQcktMDjSMNAiAyhwqqitTVhgy3E8/SIrPgZYEnEk7oeibUp5kLlu8cceV2uTgcua@W1NQZ@SyvKTpRObvtDvbwkP2F72bqm@bYs6rO2f9uSXg)
# C (gcc), 50 bytes
```
i,k;f(n){for(k=i=1;n>>i<<i==n;k+=++i&1)k*=2;k|=n;}
```
[Try it online!](https://tio.run/##fc5BCsIwEAXQfU8RCkpiKjS1C0s6PUk3EokMg1Mp7mrPHqNbO87yP/h/wvEWQkpYkY@azRKnWRMgOM/DgH2PAOzJgrW4d4YO0Hh65WhNyE91vyBrUyyFyveYcxR1ubuOXFYqameM35ZGlJMordz2hzp5SX7CdbK1df1rWdR37fyxNb0B)
**~~51~~ 48 bytes using [Arnauld's solution](https://codegolf.stackexchange.com/a/151547/61405):**
*Thanks to @l4m2 for saving three bytes!*
```
m;f(n){return n|((n&-n)&(m=-1u/3*2)?m:m/2)&n-1;}
```
[Try it online!](https://tio.run/##fc5BCsIwEAXQfU8xFAwzYmiTdmEN4kXcSDTSRQYJ7ar27DG61XGW/8H/4/Xd@5yjC8i0pNs0JwZ@IrLSTArjUZu56baWTvEQG0uKtXFrHnmCeBkZqVoqKPdIJQpYb65nrncQ0BC532JF6UTp5bY/NMhL8hNmkK1v228rAp@1/dvW/AI)
**43 with gcc:**
```
m;f(n){m=n|((n&-n)&(m=-1u/3*2)?m:m/2)&n-1;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/XOk0jT7M61zavRkMjT003T1NNI9dW17BU31jLSNM@1ypX30hTLU/X0Lr2f2ZeiUJuYmaehiZXNZcCEBQUAYXSNJRUU2LylHQU0jQMNTWtscsY4ZQxxiljgts0PFKWuG3C7QhDS9xyJgYGmHJAGQWwbRYgudr/AA)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 19 bytes
A port of Leaky Nun's approach.
```
n->n+bitand(n,-n)\3
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y5POymzJDEvRSNPRzdPM8b4f0FRZl6JRpqGoaWRpuZ/AA "Pari/GP – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 39 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.875 bytes
```
N⋏3ḭ+
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwiTuKLjzPhuK0rIiwiIiwiNDAwIl0=)
Bitstring:
```
011000110010011000101101101111111101001
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
BŒgṪµ2Ḷṁ×CḄ+³
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//QsWSZ@G5qsK1MuG4tuG5gcOXQ@G4hCvCs////zM5Mg "Jelly – Try It Online")
**Explanation**
Take 24 as an example input.
```
BŒgṪµ2Ḷṁ×CḄ+³
B Binary representation of the input → 11000
Œg Group runs of equal length → [[1,1],[0,0,0]]
Ṫ Tail → [0,0,0]
µ New monadic link
2Ḷ [0,1] constant
ṁ Mold [0,1] to the shape of [0,0,0] → [0,1,0]
× Multiply [0,1,0] by...
C 1-[0,0,0]. If last bit(s) of the original input are 1 this will add nothing to the original input
Ḅ Convert to decimal from binary → 2
+³ Add this with the original input → 26
```
] |
[Question]
[
Slightly more than an inverse of [this](https://codegolf.stackexchange.com/q/74557/43319).
**In:** Multi-line [DSV](https://en.wikipedia.org/wiki/Delimiter-separated_values) data and a single delimiter character. The DSV may be taken as a file, a filename, line-break separated string, list of strings, etc. All records have the same number of fields, and no field is empty. Data does not contain the delimiter character and there is no quoting or escaping mechanism.
**Out:** A data structure representing the DSV, e.g. a list of lists of strings or a matrix of strings.
**Examples**
`["here is,some,sample","data,delimited,by commas"]` and `","`:
`[["here is","some","sample"],["data","delimited","by commas"]]`
`["hello;\"","\";world","\";\""]` and `";"`:
`[["hello","\""],["\"","world"],["\"","\""]]` (escapes because this example uses JSON)
`["to be or not","that is the question"]` and `" "`:
`[["to","be","or","not"],["that","is","the","question"]]`
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 3 bytes
```
mqV
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=bXFW&input=WyJoZXJlIGlzLHNvbWUsc2FtcGxlIiwiZGF0YSxkZWxpbWl0ZWQsYnkgY29tbWFzIl0gIiwiIC1R) (Uses the `-Q` flag to prettyprint the output)
```
mqV // Implicit: U, V = inputs
m // Map each item in U by the following function:
qV // Split the item at instances of V.
// Implicit: output result of last expression
```
[Answer]
# Powershell, ~~25~~ 22/23 bytes
Two Options, one just calls split on the first arg, using the second arg as a delim value.
```
$args[0]-split$args[1]
```
One byte longer, builtin to parse csvs, takes filename as first arg and delim as second.
```
ipcsv $args[0] $args[1]
```
-2 because it doesn't require the `-Delimiter` (`-D`) param, and will assume it by default.
sadly powershell cannot pass an array of two params, as it will assume they are both files, and will run the command against it twice, no other two-var input method is shorter than this as far as I can see, so this is likely the shortest possible answer.
`ipcsv` is an alias for `Import-Csv`, takes a file name as the first unnamed input, and the delim character as the second by default behavior.
Run against the [example](https://en.wikipedia.org/wiki/Delimiter-separated_values#Delimited_formats) from the wiki page returns
```
PS C:\Users\Connor\Desktop> .\csvparse.ps1 'example.csv' ','
Date Pupil Grade
---- ----- -----
25 May Bloggs, Fred C
25 May Doe, Jane B
15 July Bloggs, Fred A
15 April Muniz, Alvin "Hank" A
```
[Answer]
# Python, 33 bytes
```
lambda a,c:[x.split(c)for x in a]
```
[Answer]
## Haskell, 29 bytes
```
import Data.Lists
map.splitOn
```
Usage example: `(map.splitOn) " " ["to be or not","that is the question"]` -> `[["to","be","or","not"],["that","is","the","question"]]`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
vy²¡ˆ
```
[Try it online!](https://tio.run/nexus/05ab1e#@19WeWjToYWn2/7/j1ZP1EnSSVbXUVBP1knRSVWP5dIBAA "05AB1E – TIO Nexus")
Explanation:
```
v For each element in the input array
y Push the element
² Push second input
¡ Split
ˆ Add to array
```
[Answer]
## JavaScript, 26 bytes
```
x=>y=>x.map(n=>n.split(y))
```
Receives input in format (array of strings)(delimiter)
[Try it online!](https://tio.run/nexus/javascript-node#S7P9X2FrV2lrV6GXm1igkWdrl6dXXJCTWaJRqan5Pzk/rzg/J1UvJz9dI00jWikjU0dJRylDJ1UnRycnXylWUwPIBaoDAA "JavaScript (Node.js) – TIO Nexus")
[Answer]
# Mathematica, 11 bytes
```
StringSplit
```
Builtin function taking two arguments, a list of strings and a character (and even more general than that). Example usage:
```
StringSplit[{"to be or not", "that is the question"}, " "]
```
yields
```
{{"to", "be", "or", "not"}, {"that", "is", "the", "question"}}
```
[Answer]
# MATLAB / Octave, ~~41~~ 25 bytes
```
@(x,d)regexp(x,d,'split')
```
Creates an anonymous function named `ans` which accepts the first input as a cell array of strings and the second input as a string.
```
ans({'Hello World', 'How are you'}, ' ')
```
[**Try it Online**](https://tio.run/#FudVb)
[Answer]
# Cheddar, 19 bytes
```
a->b->a=>@.split(b)
```
nice demonstration of looping abilities. I added new composition and f.op. blocks so that allows for interesting golfing. `(=>:@.split)` is supposed to work but it doesn't :(
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~3~~ 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*Dennis [points out](http://chat.stackexchange.com/transcript/message/35753610#35753610) that while the 2 byte solution appears to not work, the dyadic link itself does, and that it is actually the way command line arguments are parsed that make it look that way.*
```
ṣ€
```
**[Try It Online!](https://tio.run/nexus/jelly#@/9w5@JHTWv@P2qYk5FalKqQWaxTnJ@bqlOcmFuQkwoUTUksSdRJSc3JzM0sSU3RSapUSM7PzU0sftQw9/ByIKHj/v9rXr5ucmJyRioA)** - footer calls the function with left and right set explicitly, and formats as a grid\*.
Exactly as the below, except `ṣ` splits at occurrences of the right argument rather than at sublists equal to the right argument.
---
```
œṣ€
```
The **[3 byter](https://tio.run/nexus/jelly#AU4Asf//xZPhuaPigqz/w6dH//9bImhlcmUgaXMsc29tZSxzYW1wbGUiLCJkYXRhLGRlbGltaXRlZCxieSBjb21tYXMiXf8nLCf1bm8tY2FjaGU "Jelly – TIO Nexus")** - footer displays the result as a grid\*.
A dyadic link (function) that takes the DSV list on the left and the delimiter on the right.
### How?
```
œṣ€ - Main link: list l, delimiter d
€ - for each item in l:
œṣ - split at occurrences of sublists equal to d
```
\* As a full program the implicit output would simply "smush" together all the characters, so the footer of the TIO link calls the link as a dyad and uses `G` to format the result nicely.
[Answer]
# MATL, ~~14~~ ~~12~~ 4 bytes
```
H&XX
```
Try it at [**MATL Online**](https://matl.io/?code=H%26XX%0A%0AZD&inputs=%7B%27here+is%2Csome%2Csample%27%2C%27data%2Cdelimited%2Cby+commas%27%7D%0A%27%2C%27&version=19.8.0) (the link has a modification at the end to show the dimensionality of the output cell array).
**Explanation**
```
% Implicitly grab the first input as a cell array of strings
% Implicitly grab the delimiter as a string
H % Push the number literal 2 to the stack
&XX % Split the input at each appearance of the delimiter
% Implicitly display the result
```
[Answer]
# CJam, 5 bytes
```
l~l./
```
Explanation:
```
l~ e#Input evaluated (as list)
l e#Another line of input
./ e#Split first input by second
```
[Answer]
## Ruby using '-n', 17+1 = 18 bytes
```
p chomp.split *$*
```
### How it works
* Input from file
* separator is given as command line parameter
* since we only have 1 parameter, `*$*` splats the string and we can use it as a parameter for the `split` function
* I tried to avoid `chomp` but any other solution seems to be longer than this.
[Answer]
# Rebol, 33 bytes
```
func[b s][map-each n b[split n s]
```
[Answer]
## [GNU sed](https://www.gnu.org/software/sed/), 48 + 1(r flag) = 49 bytes
```
1h;1d
:
G
/,$/bp
s:(.)(.*)\n\1:,\2:
t
:p;s:..$::
```
**[Try it online!](https://tio.run/nexus/bash#DcVBCoAgEADA@75CRFDDVuy4@4A@4SkUPEiKBj3fmsvMnMQ@hF6hcEhAcIJ3yl8dJhm0Bjcb7xjIxYPgAeo8CVERLb0YSq61sQTJbxs1/csP)**
In sed there are no data types, but a natural representation of a list would be a collection of lines. As such, the input format consists of DSV records each on a separate line, with the delimiter present on the first line.
**Explanation:** by design, sed runs the script as many times as there are input lines
```
1h;1d # store delimiter, start new cycle
: # begin loop
G # append saved delimiter
/,$/bp # if delimiter is ',', skip replacements and go to printing
s:(.)(.*)\n\1:,\2: # replace first occurrence of delimiter with ','
t # repeat
:p;s:..$:: # print label: delete appended delimiter (implicit printing)
```
[Answer]
## REXX, 95 bytes
```
arg f d
do l=1 while lines(f)
n=linein(f)
do #=1 while n>''
parse var n w (d) n
o.l.#=w
end
end
```
Takes a filename and a delimiter as arguments, contents of file are put in stem `o`.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 4 bytes
In versions up to and including 15.0, this needs `⎕ML←3` which is default by many. From version 16.0 `⊂` can just be replaced by `⊆` for the same effect.
Takes separator as left argument and DSV as right argument.
```
≠⊂¨⊢
```
[Try it online!](https://tio.run/nexus/apl-dyalog#e9Q31dfnUdsE4/9pQPJR54JHXU2HVjzqWvTfrSg/1yvY3w8obG5oavmoZxtXSD5cwMwAKPAfIqCgrqOukKYA06CgHq2UkVqUqpBZrFOcn5uqU5yYW5CTqqSjlJJYkqiTkpqTmZtZkpqik1SpkJyfm5tYrBSrzgUzyhrTqJycfOsYJaD@GCXr8vyinBQIEyiEpE8BXV9JvkJSqkJ@kUJefglQQ0lGYgnQRQolGakKhaWpxSWZ@XlA/QA "APL (Dyalog Unicode) – TIO Nexus")
`≠` the inequalities (of the left argument and the right argument)
`⊂¨` partition each
`⊢` right argument
By partition is mean to remove all elements indicated by a corresponding zero in the left argument, and begin a new partition whenever a the corresponding number in the left argument is greater than its predecessor, i.e. on every one if the left argument is Boolean, as is the case here.
[Answer]
# R, 8 bytes (2 ways)
R has two builtin functions that meet the requirements of this challenge:
```
strsplit
```
takes a vector of strings and a separator, and returns a list of vectors of the separated strings.
```
read.csv
```
takes a file name and a separator, and returns a data frame. Technically this might be 10 bytes because it needs the option `header=F` so it won't read the first elements as the column names. Currently the TIO link reads from stdin.
[Try these online!](https://tio.run/nexus/r#bY0xCsMwEAR7v@K4SgKRD6jPK9w41oEEQhfrNsnzFeE0LtIty87OMHR71gK3O4bSQ0g7NQUHRt5AxQhZ6HiJoWhjH5jYL1csS60aV57IyvGjvaZfnNWcxznvsqXbbm9nSKU5H@7nzbgal3@@8QU)
[Answer]
# [Go](https://go.dev), 136 bytes
```
import."strings"
func f(S[]string,d rune)(O[][]string){for _,s:=range S{O=append(O,FieldsFunc(s,func(r rune)bool{return r==d}))}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZFPTgMhFMbjllO8YJrOJNi1sRk3TbozNemybSwFpiUOMAKjaQh77-CmMfEQHkVPI1OclW7g8eV9v_eHt_e9OX22lD3SvQBFpUZStcb6Ca6Vxx-dr6-uv14HzXkr9d5hVHeaQV0sV5ssEQ6206IsFqvNoJWhNhYeiLupLNUJvwyLirat0LxYkLkUDXfzxCkc6XGFzYidMU2wwndWg60qHssyovyOuZ_vizt_bAXMqBOQanXMQ0BLGAqj2ZmEIsp99mMVZUAs5Tu4qVJibw3ofA6ugA_CCpCOOKMEcVS1jcAEc-op4aKRSnrBye4IzChFHY5kTMaR_KU0jZmucbKu8fTF2IbnMEmRwHj6j8cb2AlI29LGp2R_oD41Av4g4KkTzkujz17ovRHlvbJ-lLzZPFlA9wnn6wKPLp9hO2JbqG4hxWuNCbDJsj9mJP3bEJdlov1u9XTK9w8)
] |
[Question]
[
Inspired by [this](https://codegolf.stackexchange.com/questions/56006/calculate-an-bn-with-cn-digits) question
Given a positive integer \$n\$, your code must output the first \$n\$ composite numbers.
**Input / Output**
You may write a program or a function. Input is through STDIN or function argument and output is to STDOUT, or function return value.
Output can be a List, Array, or String.
**Examples**
```
0 ->
1 -> 4
2 -> 4, 6
3 -> 4, 6, 8
13 -> 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22
```
---
## Rules
* As always [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
* Built-ins that generate prime or composite numbers are not allowed.
* Built-ins relating to prime or composite numbers are not allowed.
[Answer]
# Pyth - 10 bytes
A valid answer. Uses [Wilson's Theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem).
```
.f%h.!tZZQ
```
[Try it online here](http://pyth.herokuapp.com/?code=.f%25h.%21tZZQ&input=13&debug=0).
## Old answer
## Pyth - 6 chars
Uses builtin for *prime factorization*, not prime checking.
```
.ftPZQ
```
[Try it online here](http://pyth.herokuapp.com/?code=.ftPZQ&input=13&debug=0).
```
.f Q First n that passes filter of lambda Z, uses input for how many
t Tail. This makes all that have len-one prime factorization become empty list, and thus falsey.
P Prime factorization - primes have a len-one factorization.
Z Lambda var
```
[Answer]
# Pyth, 11 bytes
```
<S{*M^tSQ2Q
```
Generates overly large list of products of all combinations of [2, n] and truncates.
[Answer]
# TeX, 382 bytes
Because you can.
```
\newcount\a\newcount\b\newcount\c\newcount\n\newcount\p\newcount\q\let\v\advance\let\e\else\let\z\ifnum
\def\d#1:#2:#3:{\z#1>#2\v#1 by-#2\d#1:#2:#3:\e\z#1=#2#3=1\e#3=0\fi\fi}
\def\i#1:#2:#3:{#3=0\z#1>#2\a=#1\d\a:#2:\c:
\z\c=0\b=#2\v\b by 1\i#1:\the\b:#3:\e#1\par\fi\e#3=1\fi}
\def\l#1:#2:#3:#4:{\i\the#1:2:#4:
\z#4=0\v#2 by 1\fi\z#2<#3\v#1 by 1\l#1:#2:#3:#4:\fi}
\l\p:\n:10:\q:\end
```
The number in the last line is the number of composite numbers you want to have.
This is a simple divisor tester. `\d` checks if `#2` divides `#1`. `\i` calls `\d` for all possible dividers (i.e. < `#1`). `\l` lists the first `#2` numbers for which `\i` returns 0.
Ungolfed (well, half-golfed) version:
```
\newcount\a
\newcount\b
\newcount\c
\newcount\n
\newcount\p
\newcount\q
\def\div#1:#2:#3:{%
\ifnum#1>#2 %
\advance#1 by-#2 %
\div#1:#2:#3:%
\else%
\ifnum#1=#2 %
#3=1%
\else%
#3=0%
\fi%
\fi%
}
\long\def\isprime#1:#2:#3:{%
#3=0%
\ifnum#1>#2 %
\a=#1 %
\div\a:#2:\c: %
\ifnum\c=0 %
\b=#2 %
\advance\b by 1 %
\isprime#1:\the\b:#3:%
\else
#1\par%
\fi%
\else%
#3=1%
\fi%
}
\def\listprimes#1:#2:#3:#4:{%
\isprime\the#1:2:#4: %
\ifnum#4=0 %
\advance#2 by 1 %
\fi
\ifnum#2<#3 %
\advance#1 by 1 %
\listprimes#1:#2:#3:#4: %
\fi
}
\listprimes\p:\n:11:\q:
\end
```
[Answer]
## Python, 57
```
lambda n:sorted({(k/n+2)*(k%n+2)for k in range(n*n)})[:n]
```
Less golfed:
```
def f(n):
R=range(n)
return sorted({(a+2)*(b+2)for a in R for b in R})[:n]
```
The idea is to generate the set of composite numbers by multiplying all pairs of natural numbers except 0 and 1. Then, sort this set, and take the first `n` elements. It suffices to take the Cartesian product of the set `{2, 3, ..., n+2}` with itself, which we can get by shifting `range(n)` up by 2.
To golf this, we do a classic golfing trick of storing two values `(a,b)` in `range(n)` as a single value `k` in `range(n*n)`, and extract them as `a=k/n, b=k%n`.
[Answer]
# Java 8, ~~98~~ 97 bytes
```
i->{int a[]=new int[i],c=3,k=0,d;for(;k<i;c++)for(d=c;d-->2;)if(c%d<1){a[k++]=c;break;}return a;}
```
Expanded, with boilerplate:
```
public class C {
public static void main(String[] args) {
Function<Integer, int[]> f = i -> {
int a[] = new int[i], c = 3;
for (int k = 0; k < i; c++) {
for (int d = c; d --> 2;) {
if (c % d < 1) {
a[k++] = c;
break;
}
}
}
return a;
};
System.out.println(Arrays.toString(f.apply(5)));
}
}
```
[Answer]
# R, 53 bytes
```
n=scan();t=1:(n*n+3);t[factorial(t-1)%%t!=(t-1)][1:n]
```
**How it works**
This is also based on [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) and all it does is to run over a range of `1:n*n` and extract the composite numbers according to the above mentioned theorem. I've added `+3` because `n*n` isn't big enough range for `n < 3` integers
---
The only problem with this solution is that (sadly) R loses precision for a big enough factorial, thus, this won't work properly for `n > 19`
[Answer]
# CJam, ~~20~~ 18 bytes
```
li_5*{_,2>f%0&},<`
```
[Try it online](http://cjam.aditsu.net/#code=li_5*%7B_%2C2%3Ef%250%26%7D%2C%3C%60&input=13)
Does not use any built in prime or factorization operators. Fairly brute force check for numbers being composite.
One observation that is used here is that we can easily calculate a safe upper bound for the numbers we have to test. Since every second number larger than 4 is composite, `4 + n * 2` is an upper bound for the n-th composite number.
Based on a suggestion by @Dennis, the latest implementation actually uses `n * 5` as the upper limit, which is much less efficient, but 2 bytes shorter.
Explanation:
```
li Get and convert input.
_ Copy, will need the value to trim the list at the end.
5* Calculate upper bound.
{ Start of filter.
_ Copy value.
, Create list [0 .. value-1].
2> Slice off the first two, leaving candidate factors [2 .. value-1].
f% Apply modulo with all candidate factors to value.
0& Check if one of the modulo results is 0.
}, End of filter.
< Trim output to n values.
` Convert list to string.
```
[Answer]
# Javascript ES6, 88 chars
```
n=>{r=[];for(q=2;r.length!=n;++q)if(/^(..+)\1+$/.test("-".repeat(q)))r.push(q);return r}
```
[Answer]
# Haskell, ~~49~~ 46 bytes
```
(`take`[x|x<-[4..],or[mod x y<1|y<-[2..x-1]]])
```
Usage example:
```
*Main> (`take`[x|x<-[4..],or[mod x y<1|y<-[2..x-1]]]) 13
[4,6,8,9,10,12,14,15,16,18,20,21,22]
```
How it works
```
[x|x<-[4..] ] -- keep all x from the integers starting with 4 where
,or -- where at least one element of the following list is "True"
[mod x y<1|y<-[2..x-1]] -- "x mod y < 1" for all y from [2,3,...x-1]
(`take`[ ]) -- take the first n elements from the xes
-- where n is the parameter supplied when calling the function
```
[Answer]
## F#, 78 bytes
```
fun n->(Array.filter(fun i->Seq.exists((%)i>>(=)0)[2..i-1])[|2..n*n|]).[..n-1]
```
Explained:
```
fun n->
[|2..n*n|] // Generate an array of integers from 2 to n * n
Array.filter(fun i-> ) // Filter it using the following function on each element
[2..i-1] // Generate a list of possible divisors (from 2 to i-1)
Seq.exists( ) // Check if at least one of the divisors is valid, that is
(%)i>>(=)0 // That i % it is equal to 0. This is equivalent to (fun d -> i % d = 0)
( ).[..n-1] // Take the n first elements of the resulting, filtered array
```
[Answer]
## C++ 109
```
int main(){int n,i,x=4;cin>>n;while(n){for(i=2;i<x-1;i++){if(x%i==0){cout<<x<<' ';n--;break;}}x++;}return 0;}
```
**Ungolfed**
```
int main(){
int n,i,x=4;cin>>n;
while(n)
{
for(i=2;i<x-1;i++)
{
if(x%i==0){cout<<x<<' ';n--;break;}
}
x++;
}
return 0;
}
```
[Answer]
# Julia, 103 bytes
```
n->(n>0&&println(4);n>1&&(i=0;c=big(6);while i<n-1 mod(factorial(c-1),c)<1&&(i+=1;println(c));c+=1end))
```
This uses Wilson's Theorem.
Ungolfed:
```
function f(n::Int)
# Always start with 4
n > 0 && println(4)
# Loop until we encounter n composites
if n > 1
i = 0
c = big(6)
while i < n-1
if mod(factorial(c-1), c) == 0
i += 1
println(c)
end
c += 1
end
end
end
```
[Answer]
# ECMAScript 6 – ~~107~~ ~~91~~ 84 bytes
```
n=>eval('for(a=[],x=4;n&&!a[~-n];x++)for(y=2;y*2<=x;)if(x%y++<1){a.push(x);break}a')
```
The function returns an array of the first `n` composite numbers.
>
> `~-n` is a fancy way of writing `n-1`; same length, but much more fun, right?
>
> The only reason I use `eval` is that the template `n=>eval('...returnValue')` is 1 character shorter than `n=>{...return returnValue}`.
>
>
>
## Old versions
```
n=>eval('for(a=[],x=4;n&&!a[~-n];x++){for(z=0,y=2;y*2<=x;)if(x%y++<1)z=1;if(z)a.push(x)}a')
```
---
```
n=>eval('for(a=[],i=4;a.length<n;i++)if((x=>{for(y=2,z=1;y*2<=x;)if(x%y++<1)z=0;return!z})(i))a.push(i);a')
```
## Output
```
0 -> []
1 -> [4]
2 -> [4, 6]
3 -> [4, 6, 8]
13 -> [4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22]
```
[Answer]
# [Haskell](https://www.haskell.org/), 44 bytes
Heavily inspired by [Nimi's earlier answer](https://codegolf.stackexchange.com/a/57312/55329), replacing the predicate with a 2-byte shorter one based on `any` with a pointfree lambda instead of a nested list comprehension.
```
(`take`[x|x<-[4..],any((<)1.gcd x)[2..x-1]])
```
[Try it online!](https://tio.run/##LYyxCoMwFEV3v@INDgk0AdtOYocOHTp3tIIPjTFoYkhCidBvb9qKZ7lwuJwR/STmOSltFxfgsfogNL@Zl3KL0cIEIkW4Oulplg2XZyJtwEm0dXzHitVnzpsDmpWQihZcdj1EWh85j6xoGpo0KnOBfslgA38ZqBjsxd1ap0zIByBOYA85jP/ZrmUJdxNoSsXp0w0zSp9YZ@0X)
([thanks to Laikoni](https://codegolf.stackexchange.com/questions/57264/composite-number-sequences/144573?noredirect=1#comment354385_144573) for the accurate TIO link)
**Explanation:**
```
[x|x<-[4..], -- consider all integers x >=4
[2..x-1] -- consider all integers smaller than x
any((<)1.gcd x) -- if for any of them
(<)1 -- 1 is smaller than
.gcd x -- the gcd of x and the lambda input
-- then we found a non-trivial factor and thus the number is composite
(`take`[ ]) -- take the first <argument> entries
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~14~~ 12 bytes
```
↑fṠöV¬thM%ḣN
```
[Try it online!](https://tio.run/##AR8A4P9odXNr///ihpFm4bmgw7ZWwqx0aE0l4bijTv///zIw "Husk – Try It Online")
-2 bytes from Jo King.
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
↑fȯ≠2LḊN
```
[Try it online!](https://tio.run/##yygtzv7//1HbxLQT6x91LjDyebijy@////@mAA "Husk – Try It Online")
Uses the `Ḋ`ivisors function, if that is okay.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Èâ ʨ3}jU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yOIgyqgzfWpV&input=MTM)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
∞'KḢḢ;Ẏ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%88%9E%27K%E1%B8%A2%E1%B8%A2%3B%E1%BA%8E&inputs=5&header=&footer=)
```
∞ # The set of all positive integers
' ; # Filtered by...
K # The list of factors of n
ḢḢ # Has length > 2
Ẏ # Get first n
```
Using a isprime builtin doesn't actually save any bytes as 1 and 0 are considered nonprime.
] |
[Question]
[
Your task is to write a program that calculates the amount of different ways to display any given whole positive number using the following rules:
Meet the 'advanced binary system':
Any whole positive number can be displayed in binary form, but each bit can have every number from 0 to 9. This means, a valid number might look like this: **480** and would be calculated to 4 \* 2^2 + 8 \* 2^1 + 0 \* 2^0 = 32. You see, every 'bit' is multiplied with 2 to the power of the significance of the bit, just like in binary but with 10 (0 to 9) different possible bits instead of 2 (0 and 1).
It is given a whole positive decimal number in any kind of form. This can be text input, a variable value, an array element, etc. Then your program calculates in how many ways (using the number format explained above. Leading zeroes obviously do not count) the inputted decimal number can be displayed. The result should then be returned, printed or drawn in any readable way as a decimal number.
Examples:
Input: 3 -> Output: 2 >
Reason: the decimal number 3 can be displayed as 11 (1 \* 2^1 + 1 \* 2^0) and as 3 (3 \* 2^0), thus 2 different possibilities
Input: 1 -> Output: 1 >
Reason: the only possibility is 1 (1 \* 2^0)
Input: 2 -> Output: 2 >
Reason: possibilities are 10 and 2
And so on.
This is code golf: program with least amount of bytes wins!
**Test cases**
The first 30 values are:
```
1, 2, 2, 4, 4, 6, 6, 10, 10, 13, 13, 18, 18, 22, 22, 30, 30, 36, 36, 45, 45, 52, 52, 64, 64, 72, 72, 84, 84, 93
```
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
Based on the conjectured formula presented in [OEIS A309616](https://oeis.org/A309616).
```
f=lambda n:n<2or-f(n/2-5)*(n>9)+f(n-2)+f(n/2)
```
[Try it online!](https://tio.run/##Lc7BDoIwDAbgO0/R46YQoAwE4nwEX4BwmBGUBDsyufj0c1lJ/i9Ne@m//fa3JfR@1qv5PJ4GqKcrWpfNgnLMankSdOvkOawZxpGj9Ia@oGG4W5pSKFPAGBXTxJTFoTq0DJFVxaFhqmY1skaxC7JWsa4ak9k6IFgInKHXJML/dSIROknZJ7C5hXYIRSVoDeE60Oj/ "Python 2 – Try It Online")
[Answer]
# [Python](https://docs.python.org/3.8/), 53 bytes
```
f=lambda n:sum(f(k)for k in range(n)if~9<2*k-n<1)or 1
```
[Try it online!](https://tio.run/##RcqxDkAwEADQX7mxJwzVBakvEUOFoymnqRosfr2YzO/5Ky47q8qHlKhdzTaMBrg5zk2QcEh7AAeWIRieJ8Fo6a51mbmCtcQXZfLBchQdvQhf57/LHJTEHtMD "Python 3.8 (pre-release) – Try It Online")
The `if` condition is golfed from `0<=n-2*k<=9`.
---
# [Python](https://docs.python.org/3.8/), 46 bytes
```
f=lambda n:sum(map(f,range(n//2+1)[-5:n]),n<1)
```
[Try it online!](https://tio.run/##JcpBDkAwEAXQq8xyJipNiUSEk4hFhSLR36ZYOH0tvPWL770H1G1MObvhtH5eLKG7Hs/eRnYqWWwrQ@uqMDKWTYdJFHojOaYDN4@OIeRCItAB@rtRVBuZJH8 "Python 3.8 (pre-release) – Try It Online")
*-2 by dingledooper*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
BḌRDḄċ
```
[Try it online!](https://tio.run/##AS0A0v9qZWxsef//QuG4jFJE4biExIv/LMOHxZLhuZgkauKAnCAtPiDigJ0pWf//MzA "Jelly – Try It Online")
## How it works
For the input \$x\$, we generate the range \$[1, n]\$, where \$n\$ is the binary representation of \$x\$, treated as decimal. For example: \$x = 3\$ yields \$n = 11\$ and \$x = 6\$ yields \$n = 110\$. We then convert each number in this range to its decimal digits, convert them back to binary, and count the occurrences of \$x\$.
We use the fact that Jelly's base converter doesn't care about the digit values, and simply sums up \$a \times b^n\$ for digit \$a\$, base \$b\$ and position \$n\$.
```
BḌRDḄċ - Main link. Takes x on the left
B - Convert x to binary
Ḍ - Treat this binary representation as a base 10 number, n
R - Range from 1 to n
D - Convert each to digits
Ḅ - Convert the digits to binary
ċ - Count occurrences of x
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
↵2vβO
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLihrUyds6yTyIsIiIsIjUiXQ==)
Times out after default time online for anything over 4, times out for all inputs over 5 after maximum time.
Kind of similar to caird's jelly answer but much slower.
## Explained
```
↵2vβO
↵ # 10 to the power of the input - this will always be longer than the binary representation of the input
2vβ # convert each item in the range [1, that] to base 2 - the base converter just happens to be nice with digits greater than the base.
O # Count how many items in that list are equal to the input
```
[Answer]
# JavaScript (ES6), 35 bytes
Based on the [OEIS formula](https://oeis.org/A309616) found by [dingledooper](https://codegolf.stackexchange.com/a/251969/58563).
```
f=n=>n<2?n>=0:f(n-2)+f(n/=2)-f(n-5)
```
[Try it online!](https://tio.run/##FYzBCoMwEAV/ZQ8esoSoDXhRV3/FYE1pkbeipRfx29N4GgaG@YRfOOb9vX0d9LmkFAUyoPcjBqnbaOA824xKPLtbG05RdwMSenQE6qmpM61lmhWHrku56stMwRQnLs5Zcd4DviZOfw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Swift](https://swift.org/):
# - 187 bytes (standalone program)
# - 66 bytes (function f)
(The question asks for a "program" so providing it as a program.)
```
import Darwin.C.stdlib
guard let x=CommandLine.arguments.dropFirst().first,let n=Int(x) else {exit(1)}
func f(_ n:Int)->Int{n<1 ?n==0 ?1:0: n%2==0 ?f(n-1):f(n/2)+f(n-1)}
print("\(f(n))")
```
[Try it online!](https://jdoodle.com/a/5a0y)
To get multiple output for a range:
```
print("\((0...100).map(f))")
```
Notes:
* not that it matters for the sake of this contest, but the compiled & optimized standalone Swift program for arm64 macOS 11+ is 134,440 bytes, and can be downloaded [here](https://drive.google.com/file/d/1ypVZgHUTBPkbW3qvlzT5IEqykpUCIrTs/view?usp=sharing) for inspection; this might seem large but not when you consider that it requires no dependency to be installed also, such as a Python, Java, or Javascript runtime (Swift compiles in a manner similar to C or C++)
* if you have Swift installed (for linux/windows/Mac) you can just use the function (and not the full program) directly in the Swift REPL as you would use a function in the Python REPL etc.
The algorithm used is [Michael Somos](https://oeis.org/wiki/User:Michael_Somos)' Haskell answer above for [the OEIS sequence](https://oeis.org/A018819).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
NθI№E⊕⍘θ²⍘Iι²θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObEYSOSXApm@iQUannnJRam5qXklqSkaTonFqcElQFXpGoU6CkaamjoKSEJgjZmaUIlCTU1N6///jQ3@65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @caird's Jelly answer.
```
Nθ Input `n` as a number
θ Input `n`
⍘ ² Convert to a string in base `2`
⊕ Increment in base `10`
E Map over implicit range
ι Current value
I Cast to string
⍘ ² Interpret as base `2`
№ Count occurrences of
θ Input `n`
I Cast to string
Implicitly print
```
I tried to solve this myself but I ended up with a 21 byte port of @xnor's Python answer but using dynamic programming instead of recursion:
```
⊞υ¹FN⊞υΣΦυ¬÷⁻⊕ι⊗λχI⊟υ
```
[Try it online!](https://tio.run/##NYo7CsMwEER7n0LlChywSekyJpAiRuATyLKCF/Qx0q6vr2yKTDXvzbjDFpdtaM1wPYB7Neqp@@Si4JVOpoXj5gtorf77yhGeGEis0JJJjjTjhbuHNyauwq746BP5HVD3as68BelBC4yDlkydKZgIHrYSmHwC/2Rr96HdrvAF "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ¹
```
Start with `1` way to produce `0`.
```
FN
```
Repeat `n` times.
```
⊞υΣΦυ¬÷⁻⊕ι⊗λχ
```
Get the counts at `n/2`, `n/2-2` ... `n/2-8` and take their sum to produce the next count.
```
I⊟υ
```
Output the final count.
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$10\log\_{256}(96)\approx\$ 8.231 bytes
```
IxeBefa_Ob
```
[Try it online!](https://fig.fly.dev/#WyJJeGVCZWZhX09iIiwiMzAiXQ==)
Port of caird's Jelly answer.
[Answer]
# [Desmos](https://desmos.com/calculator), 75 bytes
```
f(n)=∑_{k=0}^{10^N}0^{(n-∑_{j=0}^Nmod(floor(k/10^j),10)2^j)^2}
N=log_2n
```
[Try It On Desmos!](https://www.desmos.com/calculator/hs4krz2bxb)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/rsnx9kdx6b)
We can golf some bytes, but it'll be super slow (it can't calculate values any higher than around \$n=6\$ in a reasonable amount of time.):
### 66 bytes
```
f(n)=∑_{k=0}^{10^n}0^{(n-∑_{j=0}^nmod(floor(k/10^j),10)2^j)^2}
```
[Try It On Desmos!](https://www.desmos.com/calculator/qtmuorhscj)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~42~~ ~~39~~ 37 bytes
```
f(n){n=n<1?!n:f(n-2)+f(n/=2)-f(n-5);}
```
[Try it online!](https://tio.run/##VZBtT4MwEMff71OcJEvogAzKg5sMfWH8FMILUtpJ1LLQJhIJX10sbYeuuV/b@/fu0jsSnAmZZ@ZyNPKCn6KnO/6gvAAjTx37AqNgcVOUT3PLJXzWLXcRjBtQaxHocKFE0ua1ggLGyAesLdGWaYtCS2w5GDA2xKElMySpIcWGLDHcY8MhMRzjKdf/IB0XEshb3e/UTsk77c13nHJ4weVwfFakjg///dix2azrwV1aaXlDB5UW5vZ6AtF@04651ybR3gq7VcnB83Q00sXMYK7DkaqaKeVBlN88CfXEXIluVarUdaI6s/oLuPQqhLnOtoHgEdS@FSVXXUkfhL82LoqCVrbstJnmH8I@6rOYg69f "C (gcc) – Try It Online")
*Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/251976/9481) based on [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)'s [Python answer](https://codegolf.stackexchange.com/a/251969/9481)!!!*
*Saved 3 bytes thanks to [jdt](https://codegolf.stackexchange.com/users/41374/jdt)!!!*
*Saved 2 bytes thanks to [alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha)!!!*
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 35 bytes
```
f(n)=if(n<1,!n,sum(i=0,4,f(n\2-i)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN5XTNPI0bTOBpI2hjmKeTnFprkamrYGOiQ5QKMZIN1NTUxOqVCUtv0gjT8FWwVBHwchAR6GgKDOvBCigpKBrByRABsHULlgAoQE)
A port of [@xnor's Python answer](https://codegolf.stackexchange.com/a/251967/9288).
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 42 bytes
```
n->sum(i=1,n^4,fromdigits(digits(i),2)==n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN7XydO2KS3M1Mm0NdfLiTHTSivJzUzLTM0uKNaBUpqaOkaatbZ4mVIdKWn6RRp6CrYKhjoKRgY5CQVFmXglQQElB1w5IpGnkaWpC1S5YAKEB)
A port of [@lyxal's Vyxal answer](https://codegolf.stackexchange.com/a/251970/9288), but uses the upper bound \$n^4\$.
In fact, when \$n>2\$, `fromdigits(digits(n,2),10)` \$\le 10/9\times10^{\log\_2 n}=10/9\times(10^{1/\log2})^{\log n}<(10/9\times10^{1/\log2})^{\log n}<(e^4)^{\log n}=n^4\$. It's easy to see that this is also true when \$n=1,2\$.
---
# [HOPS](https://akc.is/hops/), 28 bytes
```
A=1-x^9+x*A+(x-x^11)*A@(x^2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kI7-geG20kq5uQVFqsq2ZgVLsgqWlJWm6FnscbQ11K-IstSu0HLU1KoBMQ0NNLUcHjYo4I02IEqjKBVAaAA)
This is not a [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge. I cannot use the IO convention for [sequence](/questions/tagged/sequence "show questions tagged 'sequence'"). But it is still fun to find the generating function. So I won't post this in another answer.
The generating function of this sequence satisfies \$B(x)=(1-x^{10})B(x^2)/(1-x)\$. But we cannot determine the constant term of \$B(x)\$ from this equation.
We know that this constant term is \$1\$. Let \$B(x)=1+x A(x)\$, then we have \$1+x A(x)=(1-x^{10})(1+x^2A(x^2))/(1-x)\$, whence \$A(x)=1-x^9+x A(x)+(x-x^{11})A(x^2)\$.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
bLCI¢
```
[Try it online](https://tio.run/##yy9OTMpM/f8/ycfZ89Ci//@NDQA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9s4Opnr6TwqG2SgpK93/8kH2e/Q4v@6/wHAA).
**Explanation:**
```
b # Convert the (implicit) input-integer to binary
L # Pop and push a list in the range [1,binary(input)]
C # Interpret each integer as binary, and convert it to a base-10 integer
I¢ # Count how many times the input occurs in this list
# (which is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~40~~ 37 bytes
```
f=->n{n<1?1:(0..n/2).last(5).sum(&f)}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/G0N7QSsNATy9P30hTLyexuETDVFOvuDRXQy1Ns/Z/gYKGoZ6esYGmXm5iAUjoPwA "Ruby – Try It Online")
Based on xnor's answer.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 6 bytes
```
Đɓř2Ĩɔ
```
[Try it online!](https://tio.run/##K6gs@f//yISTk4/ONDqy4uSU//@NTAE "Pyt – Try It Online")
Port of [caird coinheringaahing's Jelly answer](https://codegolf.stackexchange.com/a/251966/116013)
```
Đ implicit input; Đuplicate
ɓ convert to ɓinary (automatically casted to decimal number)
ř řangify
2Ĩ interpret each element of the array as a base-2 Ĩnteger
ɔ ɔount occurrences of input in array; implicit print
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ô¢@¶Xì ì2
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=9MKiQLZY7CDsMg&input=NQ)
] |
[Question]
[
# Challenge
For any two non-empty strings A and B, we define the following sequence :
```
F(0) = A
F(1) = B
F(n) = F(n-1) + F(n-2)
```
Where `+` denotates the standard string concatenation.
The sequence for strings "A" and "B" starts with the following terms: A, B, BA, BAB, BABBA, ...
Create a function or program that, when given two strings `A` and `B`, and a positive integer `I` returns the `I`-th character of `F(∞)`.
You may choose to use 0-indexing or 1-indexing for `I`, just specify it in your answer.
You may assume the strings contain only uppercase (or lowercase) letters.
This is a variation of [Project Euler's Problem 230](https://projecteuler.net/problem=230), where the two strings were strings of digits of equal length, which trivialize the problem.
# Input/Output
You may choose any format for the input. The output should only contain the desired character, with trailing spaces/newlines allowed.
# Test Cases
```
ABC, DEF, 1234567890 → A
ACBB, DEFGH, 45865 → B
A, B, 3 → B
ABC, DEF, 10 → E
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest byte count for each language wins!
[Answer]
# [Haskell](https://www.haskell.org/), 15 bytes
```
a#b=b++b#(a++b)
```
[Try it online!](https://tio.run/##NYxLCoJAHMb3nuLvYzGDYxRltNBAzWrRDURw1NGGxgcqdIMO0BE7SNMotPnge/3udHwwIaSkZu7ntp2biCrFsqG89ctOA0goyQknXeo5z24ox1XFxcQGlLXdFAvWZMbn9SYG9qxjzaYbb5k69QNvJytBCot1HQ2MlsBx6vszcWbLIApDAqf4fLkS2LmHvQuKA6EWEFDF9u/CaFkR2KyXKP4WlaD1KJ2i738 "Haskell – Try It Online")
Takes strings `a` and `b` as input, returns the whole infinite Fibonacci word, as is usually allowed in [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges.
## How?
Not much to say. This answer relies on the identity
$$
F(a,b)=b+F(b,a+b),
$$
where \$F(a,b)\$ is the infinite Fibonacci word with starting words \$a\$ and \$b\$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes
```
⁹;¡⁵ị
```
[Try it online!](https://tio.run/##ASQA2/9qZWxsef//4oG5O8Kh4oG14buL////IkFCQyL/IkRFRiL/MTA "Jelly – Try It Online")
Uses 1 indexing
-1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan), noticing that we could avoid `⁵` becoming the right argument to `;¡` by forcing `;¡` into a nilad-dyad pair with `⁹`!
Dyadic `¡` is essentially Jelly's generalised Fibonacci operator
## How it works
```
⁹;¡⁵ị - Main link. Takes A on the left, B on the right and I as the third argument
⁹ - Set the return value to B
¡ - I times do the following, swapping the updated arguments each time:
; - Concatenate the arguments
⁵ị - Yield the i'th character of the result
```
When `;¡` is run with 2 arguments, it does the following (calling the initial left argument `B` and the initial right argument `A`, as `⁹` essentially "swaps" the order of the arguments. We'll do 3 iterations):
* Iteration 1: `;` concatenates `B` and `A`, yielding `BA`. We then move `B` to the right and take `BA` as our left argument for the next iteration
* Iteration 2: `;` concatenates `BA` and `B`, yielding `BAB`. Our arguments become `BAB` on the left and `BA` on the right
* Iteration 3: `;` concatenates `BAB` and `BA`, yielding `BABBA`. This is the last iteration, so we return `BABBA`
[Answer]
# [Python 3](https://docs.python.org/3/), 36 bytes
```
f=lambda a,b,i:b[i:i+1]or f(b,b+a,i)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIVEnSSfTKik60ypT2zA2v0ghTSNJJ0k7USdT839BUWZeiUaahpKjs5OTko6Ckourm7sHkGFiamFmqqn5HwA "Python 3 – Try It Online")
-8 bytes thanks to dingledooper
~~Not a particularly creative approach. In fact, basically this is just what l4m2 did but Python will error when accessing out of bounds instead of returning `undefined`.~~ Using `b[i:i+1]` returns `b[i]` (for strings) if it's in range, but doesn't error and instead gives `""` if it's out of range. Thanks to dingledooper for that.
Go upvote [this answer](https://codegolf.stackexchange.com/a/223326/68942) too. This isn't really intentionally a port because I thought of the same idea but it's an identical approach.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 26 bytes
```
n=>g=a=>b=>b[n]||g(b)(b+a)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i7dNtHWLgmIovNia2rSNZI0NZK0EzX/J@fnFefnpOrl5KdrpGkYa2qoO6oDCSd1TU0uVDlDA5CkkzNI2sXVDVOBiamFmSlIjbOTE1SRuwcWc4yMTUzNzC0sMcz7DwA "JavaScript (Node.js) – Try It Online")
Thank tsh for -1 Byte
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
A rip-off of [Delfad0r's beautiful Haskell answer](https://codegolf.stackexchange.com/a/223332/95792). Go upvote that!
```
S+S₀+
```
[Try it online!](https://tio.run/##yygtzv7/P1g7@FFTg/b///@VHJX@KzkpAQA "Husk – Try It Online")
Returns the entire infinite string/list.
`S+S₀+ a b` is `(S+) ((S₀) (+a)) b`, which expands to `(+b) ((S₀ (+a)) b)` (where `₀` is a self-reference to the main function) and then to `(+b) (₀ b (+a b))`, which is basically `b + F(b, a + b)`.
### Safer answer, 8 bytes
```
!₁
S+S₁+
```
[Try it online!](https://tio.run/##yygtzv7/X/FRUyNXsHYwkNL@//@/kqOTs9J/JRdXN6X/hoYA "Husk – Try It Online")
This one gets the Ith character, at the cost of 3 bytes.
[Answer]
# [R](https://www.r-project.org/), ~~96~~ ~~92~~ 84 bytes
```
function(A,B,I,`!`=function(k)"if"(k,"if"(k>1,paste0(!k-1,!k-2),B),A))substr(!I,I,I)
```
[Try it online!](https://tio.run/##K/pfXFKUlplk@z@tNC@5JDM/T8NRx0nHUydBMcEWLpStqZSZpqSRrQOh7Ax1ChKLS1INNBSzdQ11gISRpo6Tpo6jpmZxaRLQQA1FT6ARnppQwzWUHJV0FJScgISxtqEmF1zUyRkk7uLqBqQMDYBS/wE "R – Try It Online")
Takes `I` 1-indexed.
*-8 bytes thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes
-1 byte by assuming the input words consist only of letters (`è` implicitly swaps arguments if the first one doesn't look like a number)
Takes inputs `[A, B]` and `n`.
```
λèì}è
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3O7DKw6vqT284v//aCVHJ2clHQUlF1c3pVguQwMA "05AB1E – Try It Online")
**Commented**:
```
λè } # get the nth element of the sequence generated by:
ì # prepending the current string to the last string
# that starts with [A, B]
è # index with n into the nth element of the sequence
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes
```
≔⁻NLζθ≔⁰εW¬‹θ⁰«F¬&ε⊗ε≧⁻⁺Lζ∧﹪ε²Lηθ≦⊕ε»§⁺ηζθ
```
[Try it online!](https://tio.run/##RY/dagIxEIWvzVPM5QRSkKKl4NVurT/givQN1t3pJhATzU8tFp89Zt3W3p1hzjnzTSNr19hap1R4rzqDlTLR49ocY9jGw54ccgEbMl2QeOFZn/iM/XrHAihPZ6k0AW5twA15jycBY845/LDRp3XDolThrDwVpkUSMLdxrylL3vuq@jgUfqhOhoFAwE5njsdhAX20sm3Utm94/qeS/A9r9GjKDzSODmQCtQPkle2cMgGLsDYtfeO9Xgq43LN8ltJk@voyZcVbWbL5@2K5Sk9f@gY "Charcoal – Try It Online") Link is to verbose version of code. Takes the index as the first input. Explanation: I wanted to avoid building up a humunguous string but the code is still slow because I don't know a good way of calculating Fibbinary numbers.
```
≔⁻NLζθ
```
Subtract the length of `B` from `n`.
```
≔⁰ε
```
Start enumerating Fibbinary numbers.
```
W¬‹θ⁰«
```
Repeat until `n` is negative.
```
F¬&ε⊗ε
```
Is the current index a Fibbinary number?
```
≧⁻⁺Lζ∧﹪ε²Lηθ
```
If so then subtract the length of either `B` or `BA` from `n` depending on whether the current index is even or odd.
```
≦⊕ε
```
Increment the index.
```
»§⁺ηζθ
```
Output the `n`th character of `AB` (since `n` is negative here, Charcoal counts back from the end).
[Answer]
# [R](https://www.r-project.org/), ~~76~~ 66 bytes
*Edit: -10 bytes thanks to Giuseppe*
```
f=function(b,a,n)`if`(nchar(b)>n,substr(b,n,n),f(paste0(b,a),b,n))
```
[Try it online!](https://tio.run/##bYwxDsIwDEX3nqISg2PhoRUUsbRXoXGIaRaDmvT8IZFQu7B9/ff01iyBH26x65hllE1dCm81TJYU5yCz0QoN46QUN46pbNICSczHxuS7KiOVE3GPGXh6eS1AYB0z0HW434Zzj@2pBYbm0LgqQJd/rCQqZQfUdz/BQ5O/ "R – Try It Online")
Recursive function: input the starting strings `b` and `a` (note reversed order), and the 1-based index to output.
Could be a bit shorter ([53 bytes](https://tio.run/##bYzNCsIwDMfve4qBhzaYg0MnXuaLyHBNbdaCRBjz@btYpCB4@EHy/1oyJ7r76JYh88Bv8Wt6iSV0KDAlnuwzyLxGS3AVpJuMyNZ/fEDSCNS@quZh0ASFlVmJBlBlp6dXqAB46i/nft9Bu2v1b@pCCWj4@Mf7Wa@rVJYBu8O3EkyTNw)) if inputs are vectors of characters instead of strings.
---
# [R](https://www.r-project.org/), 48 bytes
```
function(a,b)repeat{c=b;cat(b<-paste0(b,a));a=c}
```
[Try it online!](https://tio.run/##TcsxDoAgDAXQ47RNMHFHzmJ@GzQsSKBOxrPj6ttfn0fRfXgv9UzzuKt5uSojqPTcMvyxpNHgrNvSMDyvrAEiEcneX2YCBVKS@QE "R – Try It Online")
Prints the infinite string.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 63 bytes
```
param($x,$y,$n)$a=$x,$y
1..$n|%{$a+=$a[$_]+$a[$_-1]}
$a[-1][$n]
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQ6VCR6VSRyVPUyXRFszmMtTTU8mrUa1WSdS2VUmMVomP1QZTuoaxtVxAFpCOVsmL/f//v6OT838XV7f/hgYA "PowerShell – Try It Online")
-11 bytes thanks to julian
[Answer]
# [Java (JDK)](http://jdk.java.net/), 70 bytes
```
(a,b,n)->{for(var t=a;b.length()<=n;a=b,b=t)t=b+a;return b.charAt(n);}
```
[Try it online!](https://tio.run/##hY4xT8MwEIX3/opTJlu4EQiKkIKRmkJhgKlSF8Rwdu3UJXUq5xIJRfntwQldUae74X3vewdscX7YfQ@6xLqGD3QeuhmA82SCRW1gi8GhKs278QXt105VHrV20IHeYwDLNhScLwAFnD8lRhw8z6CPVadGlU5DTUjxtJXbwTFqztznF2Aoaj5Z4V@blQNDoYTn86fOVoG10U0SM5WWU5TxR@kzlEooSZykusIsGGqCB5WOS5fE4qJ@yCbP5qcmc0yrhtJTnEGlZza1LFmu8jwRkDy/rF/f4nO3eLhfcH4BGokRu72YzFfn9nhurv/i/awffgE "Java (JDK) – Try It Online")
] |
[Question]
[
[Square numbers](https://en.wikipedia.org/wiki/Square_number) are those that take the form of \$n^2\$ where \$n\$ is an integer. These are also called perfect squares, because when you take their square root you get an integer.
The first 10 square numbers are: ([OEIS](https://oeis.org/A000290))
`0, 1, 4, 9, 16, 25, 36, 49, 64, 81`
---
[Triangular numbers](https://en.wikipedia.org/wiki/Triangular_number) are numbers that can form an equilateral triangle. The n-th triangle number is equal to the sum of all natural numbers from 1 to n.
The first 10 triangular numbers are: ([OEIS](https://oeis.org/A000217))
`0, 1, 3, 6, 10, 15, 21, 28, 36, 45`
---
[Square triangular numbers](https://en.wikipedia.org/wiki/Square_triangular_number) are numbers that are both square and triangular.
The first 10 square triangular numbers are: ([OEIS](https://oeis.org/A001110))
`0, 1, 36, 1225, 41616, 1413721, 48024900, 1631432881, 55420693056, 1882672131025, 63955431761796`
---
There is an infinite number of square numbers, triangle numbers, and square triangular numbers.
Write a program or named function that given an input (parameter or stdin) number \$n\$, calculates the \$n\$th square triangular number and outputs/returns it, where n is a positive nonzero number. (For \$n=1\$ return 0)
For the program/function to be a valid submission it should be able to return at least all square triangle numbers smaller than \$2^{31}-1\$.
# Bonus
-4 bytes for being able to output all square triangular numbers less than 2^63-1
-4 bytes for being able to theoretically output square triangular numbers of any size.
~~+8 byte penalty for solutions that take nonpolynomial time.~~
Bonuses stack.
This is code-golf challenge, so the answer with the fewest bytes wins.
[Answer]
# CJam, ~~12~~ 8 bytes
```
XUri{_34*@-Y+}*;
```
Makes use of the recurrence relation from the Wikipedia article.
The code is 16 bytes long and qualifies for both bonuses.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=XUri%7B_34*%40-Y%2B%7D*%3B&input=1000).
### How it works
My code turned out to be identical to xnor's in always every aspect, except that I use CJam's stack instead of variables.
```
XU e# Push 1 and 0 on the stack.
e# Since 34 * 0 - 1 + 2 = 1, this compensates for 1-based indexing.
ri{ }* e# Do int(input()) times:
_34* e# Copy the topmost integer and multiply it by 34.
@- e# Subtract the bottommost integer from the result.
Y+ e# Add 2.
; e# Discard the last result.
```
[Answer]
## Python 2, 45 - 4 - 4 = 37
```
a=1;b=0
exec"a,b=b,34*b-a+2;"*input()
print a
```
Iterates using the reccurence
```
f(0) = 1
f(1) = 0
f(k) = 34*f(k-1)-f(k-2)+2
```
In theory, this supports numbers of any size, but runs in exponential time, so it shouldn't qualify for the bonuses. Should work for numbers of any size. For example, for 100, gives
```
1185827220993342542557325920096705939276583904852110550753333094088280194260929920844987597980616456388639477930416411849864965254621398934978872054025
```
A recursive solution uses 41 chars, but shouldn't qualify because it takes exponential time.
```
f=lambda k:k>2and 34*f(k-1)-f(k-2)+2or~-k
```
[Answer]
# Pyth, 16 - 4 - 4 = 8 bytes
Uses the recursive formula from the OEIS article.
```
K1uhh-*34G~KGtQZ
```
It uses the post-assign command which is pretty new and seems really cool. Uses reduce to iterate `n-1` times because of 1-based indexing.
```
K1 Set K=1
u tQ Reduce input()-1 times
Z With zero as base case
hh +2
- Subtract
*34G 34 times iterating variable
~K Assign to K and use old value
G Assign the iterating variable.
```
Seems to be polynomial because it loops n times and does math & assignment each iteration, but I'm not a computer scientist. Finishes n=10000 almost instantly.
[Try it here online](http://pyth.herokuapp.com/?code=K1uhh-*34G%7EKGtQZ&input=100&debug=1).
[Answer]
# [Oasis](https://github.com/Adriandmen/Oasis), 7 - 4 - 4 = -1
```
34*c-»T
```
[Try it online!](http://oasis.tryitonline.net/#code=MzQqYy3Cu1Q&input=&args=MTA)
Uses `a(0) = 0, a(1) = 1; for n >= 2, a(n) = 34 * a(n-1) - a(n-2) + 2`
Oasis supports arbitrary precision integers, so it should be able to go up to any number so long as no stack overflowing occurs. Let me know if this does not count for the bonus because of stack overflowing. It is also possible that this particular algorithm is non-polynomial, and let me know if that is the case.
Explanation:
```
34*c-»T -> 34*c-»10
a(0) = 0
a(1) = 1
a(n) = 34*c-»
34*c-»
34* # 34*a(n-1)
c- # 34*a(n-1)-a(n-2)
» # 34*a(n-1)-a(n-2)+2
```
---
Alternative solution:
```
-35*d+T
```
Instead uses `a(n) = 35*(a(n-1)-a(n-2)) + a(n-3)`
[Answer]
# JavaScript (ES6), 29-4 = 25 bytes
```
n=>n>1?34*f(n-1)-f(n-2)+2:n|0
```
Saved 5 bytes thanks to *@IsmaelMiguel*!
I've had to hardcode the 0, 1 and the negatives to avoid infinite recursion.
Console, I've named the function, `f`:
```
f(1); // 0
f(13); // 73804512832419600
f(30); // 7.885505171090779e+42 or 7885505171090779000000000000000000000000000
```
**EDIT**: Turns out JavaScript will round the numbers to 16 (15) digits [(Spec)](http://www.ecma-international.org/ecma-262/5.1/#sec-8.5) because these numbers are too big causing an overflow. Put 714341252076979033 In your JavaScript console and see for yourself. It's more of a limitation of JavaScript
[Answer]
### Excel VBA - 90 bytes
Using the recurrence relation from the Wikipedia page:
```
n = InputBox("n")
x = 0
y = 1
For i = 1 To n
Cells(i, 1) = x
r = 34 * y - x + 2
x = y
y = r
Next i
```
When executed you are prompted for n, then the sequence up to and including n is output to column A:

It can be run up to and including n = 202 before it gives an overflow error.
[Answer]
# [Not Competing] Pyth (14 - 4 - 4 = 6 bytes)
```
K1u/^tG2~KGQ36
```
Used the first recurrence from [OEIS](https://oeis.org/A001110), that after 0,1,36 you can find An = (An-1-1)2/An-2. A Not competing because this solution starts at 36, if you go lower you divide by zero (so input of 0 gives 36). Also had to hardcode 36.
[Try it here](http://pyth.herokuapp.com/?code=K1u%2F%5EtG2~KGQ36&input=1000&debug=1)
[Answer]
# Java, 53 - 4 = 49 bytes
It's another simple recursion, but I don't often get to post Java with a <50 score, so...
```
long g(int n){return n<2?n<1?1:0:34*g(n-1)-g(n-2)+2;}
```
Now, for something *non*-recursive, it gets quite a bit longer. This one is both longer (112-4=108) -and- slower, so I'm not sure why I'm posting it except to have something iterative:
```
long f(int n){long a=0,b,c,d=0;for(;a<1l<<32&n>0;)if((c=(int)Math.sqrt(b=(a*a+a++)/2))*c==b){d=b;n--;}return d;}
```
[Answer]
# Julia, 51 bytes - 4 - 4 = 43
```
f(n)=(a=b=big(1);b-=1;for i=1:n a,b=b,34b-a+2end;a)
```
This uses the first recurrence relation listed on the Wikipedia page for square triangular numbers. It computes *n* = 1000 in 0.006 seconds, and *n* = 100000 in 6.93 seconds. It's a few bytes longer than a recursive solution but it's *way* faster.
Ungolfed + explanation:
```
function f(n)
# Set a and b to be big integers
a = big(1)
b = big(0)
# Iterate n times
for i = 1:n
# Use the recurrence relation, Luke
a, b = b, 34*b - a + 2
end
# Return a
a
end
```
Examples:
```
julia> for i = 1:4 println(f(i)) end
0
1
36
1225
julia> @time for i = 1:1000 println(f(i)) end
0
... (further printing omitted here)
elapsed time: 1.137734341 seconds (403573226 bytes allocated, 38.75% gc time)
```
[Answer]
## PHP, ~~65~~ ~~59~~ 56-4=52 bytes
```
while($argv[1]--)while((0|$r=sqrt($s+=$f++))-$r);echo$s;
```
repeat until square root of `$s` is ∈ℤ: add `$f` to sum `$s`, increment `$f`;
repeat `$argv[1]` times.
output sum.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 - 8 = 5 bytes
This qualifies for both bonuses.
```
×8‘,µÆ²Ạ
0Ç#Ṫ
```
[Try it online!](https://tio.run/##ASMA3P9qZWxsef//w5c44oCYLMK1w4bCsuG6oAoww4cj4bmq////Mw "Jelly – Try It Online")
Done alongside [caird coinheringaahing](https://politics.stackexchange.com/users/13251/caird-coinheringaahing) in [chat](https://chat.stackexchange.com/rooms/57815/jelly-hypertraining).
# Explanation
```
×8‘,µÆ²Ạ ~ Helper link.
×8 ~ 8 times the number.
‘ ~ Increment.
, ~ Paired with the current number.
µ ~ Starts a new monadic (1-arg) link.
Ʋ ~ Vectorized "Is Square?".
Ạ ~ All. Return 1 only if both are truthy.
0Ç#Ṫ ~ Main link.
0 # ~ Starting from 0, collect the first N integers with truthy results, when applied:
Ç ~ The last link as a monad.
Ṫ ~ Last element. Output implicitly.
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 25 - 8 = 17 bytes
```
{(0,1,2-*+34* *…*)[$_]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@79aw0DHUMdIV0vb2ERLQetRwzItzWiV@Nja/9YKxYkgNRoq8ZoKaflFCipann56OZl5qcX/DbgMuYy4jLkMDbiMzQA "Perl 6 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 - 8 = 2 bytes
```
1ÎGDŠ34*Ìα
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f8HCfu8vRBcYmWod7zm38/98EAA "05AB1E – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 23-4-4 = 15 bytes
```
{⍵<2:⍵⋄2+-/34 1×∇¨⍵-⍳2}
```
Recursive dfn
`⍵<2:⍵` is ⍵ less than 2, if so return ⍵
`⋄` otherwise
`∇¨⍵-⍳2` apply the function (∇) to the two previous values
`34 1×` multiply by the array 34 1
`-/` subtract
`2+` add 2
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR71YbIysg@ai7xUhbV9/YRMHw8PRHHe2HVgAFdR/1bjaq/Z/2qG3Co96@R13Nj3rXPOrdcmi98aO2iY/6pgYHOQPJEA/P4P9pCgZcaQqGQGwExMZAbAIA "APL (Dyalog Extended) – Try It Online")
[Answer]
# Prolog, ~~70~~ 74 - 4 - 4 = 66
```
n(X,R):-n(X,0,1,R).
n(X,A,B,R):-X=0,R=A;Z is X-1,E is 34*B-A+2,n(Z,B,E,R).
```
Running `n(100,R)` outputs:
```
X = 40283218019606612026870715051828504163181534465162581625898684828251284020309760525686544840519804069618265491900426463694050293008018241080068813316496
```
Takes about 1 second to run `n(10000,X)` on my computer.
**Edit**: The 66 version is tail-recursive. The previous non-tail-recursive version is the following:
```
n(X,[Z|R]):-X>1,Y is X-1,n(Y,R),R=[A,B|_],Z is 34*A-B+2;X=1,Z=1,R=[0];Z=0.
```
They have the same length in bytes but the non-tail-recursive generates stack overflows past a certain point (on my computer, around 20500).
[Answer]
# Javascript ES6, ~~77~~ ~~75~~ 71 chars
```
// 71 chars
f=n=>{for(q=t=w=0;n;++q)for(s=q*q;t<=s;t+=++w)s==t&&--n&console.log(s)}
// No multiplication, 75 chars
f=n=>{for(s=t=w=0,q=-1;n;s+=q+=2)for(;t<=s;t+=++w)s==t&&--n&console.log(s)}
// Old, 77 chars
f=n=>{for(s=t=w=0,q=-1;n;s+=q+=2){for(;t<s;t+=++w);s==t&&--n&console.log(s)}}
```
* The solution is linear.
* The solution can output all numbers less then 2^53 because of numbers type.
* The algorithm itself can be used for unlimited numbers.
Test:
```
f(11)
0
1
36
1225
41616
1413721
48024900
1631432881
55420693056
1882672131025
63955431761796
```
[Answer]
# C, 68 bytes
This was a fun challenge with C
`main(o,k){o==1?k=0:0;k<9e9&&k>=0&&main(34*o-k+2,o,printf("%d,",k));}`
Watch it run here: <https://ideone.com/0ulGmM>
[Answer]
# APL(NARS), 67 chars, 134 bytes
```
r←f w;c;i;m
c←0⋄i←¯1⋄r←⍬
→2×⍳0≠1∣√1+8×m←i×i+←1⋄r←r,m⋄→2×⍳w>c+←1
```
test:
```
f 10
0 1 36 1225 41616 1413721 48024900 1631432881 55420693056 1882672131025
```
f would search in quadratic sequence the elements that are triangulars number too, so they have to
follow the triangular check formula in APLs: 0=1∣√1+8×m with number m to check.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~14~~ 20 - 8 = 12 bytes
```
→!¡otS:o+2§-←o*34→ḋ2
```
[Try it online!](https://tio.run/##yygtzv7//1HbJMVDC/NLgq3ytY0OLdd91DYhX8vYBCj8cEe30f///w0NAQ "Husk – Try It Online")
Uses the same recurrence relation as the CJam answer. There's probably a better way to do this.
# [Husk](https://github.com/barbuz/Husk), 8 - 4 = 4 bytes
```
!Θf£∫Nİ□
```
[Try it online!](https://tio.run/##ARkA5v9odXNr//8hzphmwqPiiKtOxLDilqH///8z "Husk – Try It Online")
it can theoretically output square triangular numbers of any size, ~~but list intersection causes a stack overflow for anything above 3.~~
Instead of `n` uses `f£`, which is optimized for infinite lists.
Getting numbers takes a long, long, long time after 4.
[Answer]
### **x86\_64 machine code - 46 bytes**
Borrowed code from [Albert Renshaw](https://codegolf.stackexchange.com/questions/52175/triangular-square-numbers/95074#95074) C answer.
47 bytes using [**`ret`**](https://www.felixcloutier.com/x86/ret) instruction.
```
0000000000400080 <triangular_square>:
400080: 48 31 d2 xor rdx,rdx # rdx = 0
400083: 6a 00 push 0x0
400085: 41 58 pop r8 # r8 = 0
400087: 48 ff c3 inc rbx # rbx = 1
40008a: 49 89 d8 mov r8,rbx # copy rbx value to r8
000000000040008d <triangular_square.loop>:
40008d: e3 1f jrcxz 4000ae <triangular_square.done> # if rcx is zero go to .done
40008f: 4d 6b c0 22 imul r8,r8,0x22 # r8 * 0x22 (34)
400093: 49 29 d0 sub r8,rdx # r8 - rdx
400096: 49 83 c0 02 add r8,0x2 # r8 + 2
40009a: 4d 89 c1 mov r9,r8 # copy r8 value to r9
40009d: 48 ff c2 inc rdx # rdx + 1
4000a0: 48 ff ca dec rdx # rdx - 1
4000a3: 48 87 da xchg rdx,rbx # swap rbx value with rdx value
4000a6: 4c 89 cb mov rbx,r9 # copy r9 value to rbx
4000a9: 4c 89 c0 mov rax,r8 # copy r8 value to rax (output)
4000ac: e2 df loop 40008d <triangular_square.loop> # keep looping until rcx is zero
00000000004000ae <triangular_square.done>:
```
Input in `rcx` output in `rax`. You can use debugger to test it.
TODO: Make a tester program on [TIO](https://tio.run/).
] |
[Question]
[
### Goal
The program's goal is to draw an ASCII art rectangle repeatedly doubled in size, alternating horizontally and vertically. Each time the rectangle doubles in size, the extra area is represented by a different character and the previous areas remain unchanged. The two smallest sections contain one character each and may be in any corner.
The program accepts a single integer as input, defining the number of sections the full rectangle contains.
No other external resources or inputs are allowed.
### Sample input and output
```
10
ABDDFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
CCDDFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
EEEEFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
EEEEFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
```
### Selection criteria
The shortest code in a week wins the points.
[Answer]
# APL, 25 chars/bytes\*
```
{⍉⍣⍵⊃{a,⍺⍴⍨⍴a←⍉⍪⍵}/⌽⍵↑⎕A}
```
**Exploded view**
```
{ ⍵↑⎕A} ⍝ take the first ⍵ letters
⊃{ }/⌽ ⍝ fold over them, using the first one as initial accum. value
a←⍉⍪⍵ ⍝ ensure the accum. is a table, transpose it and call it 'a'
⍺⍴⍨⍴ ⍝ make a table as large as 'a' filled with the next letter
a, ⍝ append it to the right of 'a' and loop as new accumulator
⍉⍣⍵ ⍝ transpose the result as many times as the original ⍵ number
```
**Examples**
```
{⍉⍣⍵⊃{a,⍺⍴⍨⍴a←⍉⍪⍵}/⌽⍵↑⎕A}¨⍳8
A AB AB ABDD ABDD ABDDFFFF ABDDFFFF ABDDFFFFHHHHHHHH
CC CCDD CCDD CCDDFFFF CCDDFFFF CCDDFFFFHHHHHHHH
EEEE EEEEFFFF EEEEFFFF EEEEFFFFHHHHHHHH
EEEE EEEEFFFF EEEEFFFF EEEEFFFFHHHHHHHH
GGGGGGGG GGGGGGGGHHHHHHHH
GGGGGGGG GGGGGGGGHHHHHHHH
GGGGGGGG GGGGGGGGHHHHHHHH
GGGGGGGG GGGGGGGGHHHHHHHH
```
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
\*: 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, 30 characters
```
~(,[0`]{{[49+]1$,*+}+%zip}@/n*
```
Example (run [online](http://golfscript.apphb.com/?c=OyI3IgoKfigsWzBgXXt7WzQ5K10xJCwqK30rJXppcH1AL24q&run=true)):
```
> 7
01335555
22335555
44445555
44445555
66666666
66666666
66666666
66666666
```
[Answer]
## Python 2.7 - 85 ~~103~~
This uses the `zip(*s)` syntax to continually transpose the list. **Big thanks to Daniel for his tip that shaved 12 characters!** Then shaved a few more by using numbers instead of letters.
```
s=[]
for i in range(input()):x=1<<i/2;s=zip(*s+[chr(65+i)*x]*x)
for i in s:print''.join(i)
```
Also, this uses `1<<x` rather than `2**x` as bit shift has lower(?) precedence. Observe:
```
>>> 1<<(2*3)
64
>>> 1<<2*3
64
>>> 2**2*3
12
>>> 2**(2*3)
64
```
And some output:
```
10
01335555777777779999999999999999
22335555777777779999999999999999
44445555777777779999999999999999
44445555777777779999999999999999
66666666777777779999999999999999
66666666777777779999999999999999
66666666777777779999999999999999
66666666777777779999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
88888888888888889999999999999999
```
[Answer]
## Ruby, 88
Reads N from standard input.
```
s=[?A]
66.upto(64+gets.to_i){|i|x=i.chr*y=s.size;i%2<1?s.map!{|r|r+x}:s+=[x*2]*y}
puts s
```
Example Usage for N=8:
```
echo 8 | rectangular-pseudo-fractal.rb
```
Output:
```
ABDDFFFFHHHHHHHH
CCDDFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
```
N=10
```
echo 10 | rectangular-pseudo-fractal.rb
```
Output:
```
ABDDFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
CCDDFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
EEEEFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
EEEEFFFFHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ
```
[Answer]
**J, 57 43**
```
(,`,.@.(=/@$@[)$${&a.@(66+2&^.@#@,)^:)1$'A'
```
Examples:
```
5 (,`,.@.(=/@$@[)$${&a.@(66+2&^.@#@,)^:)1$'A'
ABDDFFFF
CCDDFFFF
EEEEFFFF
EEEEFFFF
7 (,`,.@.(=/@$@[)$${&a.@(66+2&^.@#@,)^:)1$'A'
ABDDFFFFHHHHHHHH
CCDDFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
```
[Answer]
**MATLAB, 86 Characters**
My shortest try in MATLAB, pimped by @flawr (twice!):
```
function M=f(n)
M='';
if n
M=cat(mod(n,2)+1,f(n-1),64+n*ones(2.^fix(n/2-[.5,1])));
end
```
Example output:
```
>> disp(f(7))
ACEEGGGG
BCEEGGGG
DDEEGGGG
DDEEGGGG
FFFFGGGG
FFFFGGGG
FFFFGGGG
FFFFGGGG
```
[Answer]
# q [73 chars]
```
{"c"$64+{n:x 0;m:x 1;if[2>n;m:(),m];(o;$[n-2*n div 2;,';,][m;(#m;#m 0)#o:n+1])}/[x-1;(1;1)]1}
```
### example
```
10
"ABDDFFFFHHHHHHHHJJJJJJJJJJJJJJJJ"
"CCDDFFFFHHHHHHHHJJJJJJJJJJJJJJJJ"
"EEEEFFFFHHHHHHHHJJJJJJJJJJJJJJJJ"
"EEEEFFFFHHHHHHHHJJJJJJJJJJJJJJJJ"
"GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ"
"GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ"
"GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ"
"GGGGGGGGHHHHHHHHJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
"IIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJ"
3
"AB"
"CC"
6
"ABDDFFFF"
"CCDDFFFF"
"EEEEFFFF"
"EEEEFFFF"
```
[Answer]
# [Sclipting](http://esolangs.org/wiki/Sclipting), 59 characters
```
❶塊갠分감⓶左貶終辦감標가⓺貶⓹開上❶❶貶雙是不⒉갠乘⒉終가①上뀀❷②갠分小是增終❸⓷另要감右⓶갠加⓶終丟字⓶終丟겠終
```
(This program could be quite a bit shorter if I had instructions for base-2 logarithm, but I don’t, so I do it manually with a loop.)
## Annotated code
`n` is the input.
```
❶ | n n
f = i => (1 << (i/2)) - 1;
塊갠分감⓶左貶終 | n n f
w = f(n);
辦 | n w f
d = 1;
감 | n w f d
s = "";
標 | n w f d M [s]
for (y in [0..f(n-1)])
가⓺貶⓹開上 | w d M [s] y
if ((y & (y-1)) == 0) d *= 2;
❶❶貶雙是不⒉갠乘⒉終 | w d M [s] y
for (x in [0..w])
가①上 | w d M [s] y x
c = 64; // '@'
뀀 | w d M [s] y x c
if (x < d/2) c++;
❷②갠分小是增終 | w d M [s] y x c
a = x | y;
❸⓷另 | w d M [s] y c a
while (a > 0) { a >>= 1; c += 2; }
要감右⓶갠加⓶終丟 | w d M [s] y c
s += (char) c;
字⓶ | w d M [s] y
終丟 | w d M [s]
s += "\n"
겠 | w d M [s]
終
```
## Output
For `n` = 6:
```
ABDDFFFF
CCDDFFFF
EEEEFFFF
EEEEFFFF
```
Of course you can change `뀀` (`@`) to any other base character, e.g. with `글` (space) and `n` = 7:
```
!"$$&&&&
##$$&&&&
%%%%&&&&
%%%%&&&&
''''''''
''''''''
''''''''
''''''''
```
The highest number that doesn’t make the program longer is `믰` (= 255), which gives us (`n` = 8 this time):
```
Āāăăąąąąćććććććć
ĂĂăăąąąąćććććććć
ĄĄĄĄąąąąćććććććć
ĄĄĄĄąąąąćććććććć
ĆĆĆĆĆĆĆĆćććććććć
ĆĆĆĆĆĆĆĆćććććććć
ĆĆĆĆĆĆĆĆćććććććć
ĆĆĆĆĆĆĆĆćććććććć
```
If we make the program 1 character longer, e.g. use `냟및` (= `\u4DFF`) and `n` = 9, we get:
```
一丁七七丅丅丅丅万万万万万万万万
丂丂七七丅丅丅丅万万万万万万万万
丄丄丄丄丅丅丅丅万万万万万万万万
丄丄丄丄丅丅丅丅万万万万万万万万
丆丆丆丆丆丆丆丆万万万万万万万万
丆丆丆丆丆丆丆丆万万万万万万万万
丆丆丆丆丆丆丆丆万万万万万万万万
丆丆丆丆丆丆丆丆万万万万万万万万
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈丈
```
[Answer]
## C#, 239 185 182 180 bytes
C# has nothing on the less verbose languages.
```
using C=System.Console;
class P{
static void Main(string[]a){
for(int x,i,n=int.Parse(a[0]);n-->0;C.CursorTop=0)
for(i=1<<n,x=1<<n/2+n%2;i-->0;)
C.Write((char)(n+33)+(i%x<1?"\n":""));
}
}
```
Output, characters chosen for prettiness:
```
!"$$&&&&((((((((****************
##$$&&&&((((((((****************
%%%%&&&&((((((((****************
%%%%&&&&((((((((****************
''''''''((((((((****************
''''''''((((((((****************
''''''''((((((((****************
''''''''((((((((****************
))))))))))))))))****************
))))))))))))))))****************
))))))))))))))))****************
))))))))))))))))****************
))))))))))))))))****************
))))))))))))))))****************
))))))))))))))))****************
))))))))))))))))****************
```
[Answer]
# PERL, 122 chars
```
$N=<>;$x=$r=1;do{$_=chr$a+++65;$s=$x;$o=$_ x$s;$o.=$_++x$s,$s*=2while$N+65>ord++$_;print"$o\n"x$r;$r=$x;$x*=2}while++$a<$N
```
with added whitespace:
```
$N=<>;
$x=$r=1;
do{
$_=chr$a+++65;
$s=$x;
$o=$_ x$s;
$o.=$_++x$s,$s*=2
while $N+65>ord++$_;
print "$o\n"x$r;
$r=$x;
$x*=2
} while++$a<$N
```
Output:
```
$ echo 8 | perl pseudo-fractal.pl
ABDDFFFFHHHHHHHH
CCDDFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
```
[Answer]
# PERL, 94 81 chars
```
$N=$_;$_=$:=A;$h=1;++$i%2?s/$/$:x$h/gem:($_.=($/.$:x2x$h)x$h,$h*=2)while++$:,--$N
```
It constructs the fractal iteratively letter by letter, adding new rows and columns and rows and columns... Uses simple string operations to do that. Note that I am abusing standard variable instead of letter one to allow for syntax sugar (like omitting spaces - `$:x2` etc.)
With added whitespace and comments:
```
$N=$_;
$_=$:=A; # $: is current letter
$h=1;
++$i%2?
s/$/$:x$h/gem: # every odd run - add "columns"
($_.=($/.$:x2x$h)x$h,$h*=2) # every even run - add "rows"
while++$:,--$N # iterate over letters
```
Some output:
```
$ echo 8 | perl -p pseudo-fractal.fill.pl.5a5
ABDDFFFFHHHHHHHH
CCDDFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
EEEEFFFFHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
GGGGGGGGHHHHHHHH
```
[Answer]
# [Sclipting](http://esolangs.org/wiki/Sclipting), 45 characters
```
가⓶貶上倘감雙⓶壹長⓸講增字⓶復⓷是標⓷各①合終并不⓶梴❸⓶疊合終不뀐標뀐并終終⓶丟各겠終
```
This solution works completely differently from the other Sclipting solution. It’s much more boring, but it’s shorter...
## Annotated
```
for i in [0..n-1]
가⓶貶上
if (i != 0)
倘
i &= 1
감雙
e = list[0].Length
⓶壹長
c = ((char) (c[0] + 1)).Repeat(e)
⓸講增字⓶復
if (i)
⓷是
concatenate c onto every element of list
標⓷各①合終并
else
不
concatenate c.Repeat(list.Length) onto list
⓶梴❸⓶疊合
終
else (i.e., i == 0)
不
c = "A"
뀐
list = ["A"]
標뀐并
終
終
concatenate "\n" to every element in list
⓶丟各겠終
```
[Answer]
### Delphi 348 || 449 with indent
### Without indent
```
var inp,j,i,x: integer;s:string;L:TStringlist;begin L:=TStringList.Create;readln(s);inp:=StrToIntDef(s,4);if inp<4then inp:=4;s:='';l.Add('AB');for I:=2to inp-1do begin j:=Length(L[0]);if i mod 2=0then for x:=0to L.Count-1do L.Add(s.PadLeft(j,Chr(65+i)))else for x:=0to L.Count-1do L[x]:=L[x]+s.PadLeft(j,Chr(65+i));end;Write(L.GetText);readln;end.
```
### With indent
```
var
inp,j,i,x: integer;
s:string;
L:TStringlist;
begin
L:=TStringList.Create;
readln(s);
inp:=StrToIntDef(s,4);
if inp<4then inp:=4;
s:='';
l.Add('AB');
for I:=2to inp-1do
begin
j:=Length(L[0]);
if i mod 2=0then
for x:=0to L.Count-1do L.Add(s.PadLeft(j,Chr(65+i)))
else
for x:=0to L.Count-1do
L[x]:=L[x]+s.PadLeft(j,Chr(65+i));
end;
Write(L.GetText);
readln;
end.
```
[Answer]
# CJam, 30 (23) bytes
CJam is a few months younger than this challenge so it's not eligible for the green checkmark.
```
l~(Sa1${{_,I'!+*+}%z}fI\{z}*N*
```
[Test it here.](http://cjam.aditsu.net/)
The OP clarified in a comment that any set of unique printable characters is allowed, so I'm just taking the printable ASCII characters from the start (with a space in the corner, `!` next and so on).
If the orientation may change between even and odd inputs (which I don't think, but that's what the GolfScript submission does), I can do it in 25 bytes:
```
S]l~({{_,I'!+*+}%z}fIN*
```
The idea is really simple: start with a grid containing a space, and then N-1 times transpose it and double all lines with the next character.
For the long version, at the end I also transpose again N-1 times in order to guarantee a consistent orientation.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 22 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
A;╷{┐⤢l;L┘¹Zj@┘┘*+}╶[⤢
```
[Try it here!](https://dzaima.github.io/Canvas/?u=QSV1RkYxQiV1MjU3NyV1RkY1QiV1MjUxMCV1MjkyMiV1RkY0QyV1RkYxQiV1RkYyQyV1MjUxOCVCOSV1RkYzQSV1RkY0QSV1RkYyMCV1MjUxOCV1MjUxOCV1RkYwQSV1RkYwQiV1RkY1RCV1MjU3NiV1RkYzQiV1MjkyMg__,i=Mw__,v=8)
] |
[Question]
[
The ubiquitous [Catalan numbers](https://codegolf.stackexchange.com/q/66127/110698) \$C\_n\$ count the number of *Dyck paths*, sequences of up-steps and down-steps of length \$2n\$ that start and end on a horizontal line and never go below said line. [Many other interesting sequences](http://dx.doi.org/10.1016/S0012-365X(98)00371-9) can be defined as the number of Dyck paths satisfying given conditions, of which the *Fine sequence* \$F\_n\$ (not the Fibonacci numbers and not related to any common definition of "fine") is one.
Let a *hill* be a sequence of an up-step followed by a down-step that starts – and therefore also ends – on the horizontal line. \$F\_n\$ is then the number of Dyck paths of length \$2n\$ with **no** hills. The picture below illustrates this: there are \$C\_5=42\$ Dyck paths of length \$10\$, of which \$F\_5=18\$ (marked in black) have no hills.

This sequence is [OEIS A000957](https://oeis.org/A000957) and begins
$$\begin{array}{c|ccccccccccc}
n&0&1&2&3&4&5&6&7&8&9&10\\
\hline
F\_n&1&0&1&2&6&18&57&186&622&2120&7338
\end{array}$$
$$\begin{array}{c|ccccccccccc}
n&11&12&13&14&15\\
\hline
F\_n&25724&91144&325878&1174281&4260282
\end{array}$$
Other things counted by the Fine numbers include
* the number of Dyck paths of length \$2n\$ beginning with an even number of up-steps
* the number of ordered trees with \$n+1\$ vertices where the root has no leaf children
* the number of ordered trees with \$n+1\$ vertices where the root has *an even number of* children
* and so on. For more interpretations see Deutsch and Shapiro's "[A survey of the Fine numbers](http://dx.doi.org/10.1016/S0012-365X(01)00121-2)".
## Formulas
You may use any correct formula to generate the sequence. Here are some:
* The generating function is
$$\sum\_{n=0}^\infty F\_nz^n=\frac1z\cdot\frac{1-\sqrt{1-4z}}{3-\sqrt{1-4z}}$$
* For \$n\ge1\$, \$C\_n=2F\_n+F\_{n-1}\$.
* An explicit formula:
$$F\_n=\frac1{n+1}\sum\_{k=0}^n(-1)^k(k+1)\binom{2n-k}{n-k}$$
## Task
Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply to this challenge, where permissible behaviours are
* outputting the \$n\$th term in 0- or 1-based indexing given \$n\$
* outputting the first \$n\$ terms given \$n\$
* outputting the infinite sequence with no input, either by printing or returning a lazy list/generator
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
```
i=a=1;b=0
while 1:print a;i+=1;a,b=2*b+7*a/2-(2*a+b)*3/i,a
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9M20dbQOsnWgKs8IzMnVcHQqqAoM69EIdE6UxsokaiTZGuklaRtrpWob6SrYaSVqJ2kqWWsn6mT@P@/oQEA "Python 2 – Try It Online")
Prints the sequence endlessly. The method substitutes \$C\_n = 2F\_n + F\_{n-1} \$ into the Catalan recurrence
$$
C\_n = 4C\_{n-1} - \left\lfloor \frac{6C\_{n-1}}{n+1} \right\rfloor
$$
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 22 10 7 bytes
-12 bytes by emanresu A (double welp)
-3 bytes by alephalpha using a clever approach
```
ꜝ$ʀƈ¦ṁȧ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLqnJ0kyoDGiMKm4bmByKciLCIiLCI1Il0=)
**How it works**
```
ꜝ$ʀƈ¦ṁȧ
ꜝ$ Bitwise not n and swap with input
ʀƈ Take the binomial coefficient
¦ṁȧ Cumultative sum, take the mean and push the absolute value
```
[Answer]
# [HOPS](https://akc.is/hops/), 19 bytes
```
C=1+x*C^2;C/(1+x*C)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kI7-geG20kq5uQVFqsq2RgVLsgqWlJWm6FpudbQ21K7Sc44ysnfU1wExNiAxUwQIoDQA)
The generating function of the Catalan numbers satisfies \$C(x)=1+x\ C(x)^2\$. The generating function of this sequence is \$F(x)=C(x)/(1+x\ C(x))\$.
---
# [HOPS](https://akc.is/hops/), 21 bytes
```
2/(1+2*x+sqrt(1-4*x))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kI7-geG20kq5uQVFqsq2RgVLsgqWlJWm6FluN9DUMtY20KrSLC4tKNAx1TbQqNDUhclAlC6A0AA)
A simplified version of the generating function.
It seems that HOPS on ATO is currently not working.
[Answer]
# [Python 3](https://docs.python.org/3/), 61 bytes
```
f=lambda n,v=1:sum(f(i,0)*f(n+~i,v)for i in range(v,n))or 1-n
```
[Try it online!](https://tio.run/##XcxBCoAgEEDRq8zSKQOlneBhjLIGchQzoU1XN9dt/4eXnnJEnlvz9nRhWR2wrFab6w7CC5IKBy94fElW9DEDATFkx/smqmTEnvTE7be0QpMycelCVxDbBw "Python 3 – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 50 bytes
```
f=(n,v=1,i=v)=>i<n?f(i,0)*f(n+~i,v)+f(n,v,i+1):+!n
```
[Try it online!](https://tio.run/##FcsxDoMwDEDRs7DFtUFkLXF7FkQxchXZCKqMXD0Ny5/@@85lPpdD919v/llrFQ5GhSMpF@CXJntLUBrhIcHwUiqAci@kGOGJnVXxIyiPk6bYggiL2@l5HbJvjTYOUP8 "JavaScript (Node.js) – Try It Online")
Another [47 bytes JavaScript](https://tio.run/##FcsxDoMwDEDR01Sya4rqgaUkcBaUxsgVshEgJsTVQ1n@9P5v2Ic1LTpvL/NvLkUiWKXRHnwcXDcYOw3WCyg@BYxORZJbEOPHAhfxBTS@Ww38DxEmt9WnXE8@glb3iOUC) answer but output `true` and `false` for `f(0)`, `f(1)`.
First, we write down following recursive formula:
$$F\_n=\sum\_{i=1}^{n-1}C\_i\cdot F\_{n-i-1}$$
$$F\_1=0, F\_0=1$$
$$C\_n=\sum\_{i=0}^{n-1}C\_i\cdot C\_{n-i-1}$$
$$C\_0=1$$
Then, we try to merge two functions into one
$$f(x,1):=F\_x$$
$$f(x,0):=C\_x$$
$$f(x,v)=\begin{cases}\sum\_{i=v}^{x-1}f(i,0)\cdot f(x-i-1,v) & x>v\\ 0 & x=v=1 \\ 1 & x=0 \end{cases}$$
[Answer]
# JavaScript (ES6), 48 bytes
Returns the \$n\$-th term (0-indexed).
Inspired by the Catalan recurrence [pointed out by Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus).
```
f=n=>n?(g=n=>n?g(n-1)*(4+6/~n):1)(n)-f(n-1)>>1:1
```
[Try it online!](https://tio.run/##JYxBDsIgEEX3PcUsupiRoJKoi1bwKiUViIYMpm3cELw6El29n5ef97Rvu87L47VJTndXq9esDd8w/BmQpaIdnsTl8GEaFCGT9D9rjBpU9WnB6DZg0HAcG64a1LkNIQhyBzAnXlN0@5gCThb7zIXat8@tQmWisSv1Cw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 60 bytes
Returns the \$n\$-th term (0-indexed).
This is based on the explicit formula provided in the challenge.
```
f=(n,k=n)=>~k&&(g=v=>v--?(v-n-k)*g(v)/~v:--k-n)(k)/~n-f(n,k)
```
[Try it online!](https://tio.run/##FYzNDoIwEITvPMUeCNkV15@DF3HxVWiwEG2zNUB6IfDqtZ5mvmS@@Zho5n56fxfW8LIpDYJ6dKIk7e6qCkeJ0kbmJ0ZWdnQYMdJ5j3dmx0roMigPf4nSECb0dgEFgUuT4yFwveVS1wRrAdAHnYO3Jx9G7AyWq26Ut@WaD2jrqCm29AM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes
```
ḤrcµJNÐeḋ:L
```
[Try it online!](https://tio.run/##ASUA2v9qZWxsef//4bikcmPCtUpOw5Bl4biLOkz/xbvDh@KCrFn//zEw "Jelly – Try It Online")
Port of emanresu A's golf to [mathcat's Vyxal solution](https://codegolf.stackexchange.com/a/258124/85334).
```
Ḥrc Each of [2n .. n] choose n.
µ ḋ Take the dot product of that with
J [1 .. n+1]
NÐe with every other element negated,
: and (floor) divide that by
µ L n+1.
```
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
o2µḤœcµṬ-*ÄAƑ×ṂḂ)S
```
[Try it online!](https://tio.run/##ATQAy/9qZWxsef//bzLCteG4pMWTY8K14bmsLSrDhEHGkcOX4bmC4biCKVP/xbvDh@KCrFn//zEw "Jelly – Try It Online")
Haven't actually tried any closed form or recursive formulae, but ignoring the special case fix for \$n=0\$ this brute-force enumeration feels elegant enough to post, ~~especially considering how the current golflang closed form solutions are~~. Leverages the "even number of leading up-steps" interpretation--or rather, "first down-step at an odd 1-index", hence the special case.
```
o2µ If n is 0, from here on out, pretend it's 2.
œc Get every combination of n elements from
Ḥ [1 .. 2n],
µ ) then for each combination:
Ṭ-* Produce a list of -1 at those indices and 1 elsewhere,
Ä take its cumulative sums,
AƑ and check that none of those is negative.
× Multiply that result by
Ṃ the smallest element of the combination.
Ḃ S How many are odd?
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ ~~21~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
xŸIc2Å€(}ηOÅAÄ
```
Port of [*@mathcat*'s Vyxal answer](https://codegolf.stackexchange.com/a/258124/52210), so make sure to upvote him as well!
Uses the formula: $$G\_{n,k} = (-1)^{(k+1)}\binom{k}{n} + G\_{n-1,k}\\
F\_n=\left|\frac{1}{n+1}\sum\_{k=n}^{2n}G\_{n,k}\right|$$
Given \$n\$, it'll output \$F\_n\$.
[Try it online](https://tio.run/##yy9OTMpM/f@/4ugOz2Sjw62PmtZo1J7b7n@41fFwy///hkYA) or [verify all test cases](https://tio.run/##ATIAzf9vc2FiaWX/MTXGkk4/IiDihpIgIj9Owqn/eMW4wq5jMsOF4oKsKH3Ot0/DhUHDhP8s/w).
**Explanation:**
```
x # Push double the (implicit) input (without popping)
Ÿ # Pop both, and push a list in the range [input,2*input]
Ic # Calculate the bionomical coefficient of each value with the input
2Å€(} # Negate every second item, starting with the first:
2 # Push a 2
Å€ } # Map over each item where the 0-based index is divisible by 2:
( # Negate that item
ηO # Calculate its cumulative sum:
η # Get all prefixed of this list
O # Sum each inner prefix-list together
ÅA # Get the arithmetic mean of that
Ä # Convert it to its absolute value
# (after which it is output implicitly as result)
```
---
**Original ~~22~~ 21 bytes answer:**
```
ÝεÈ·<y>Ixs‚y-`cI>zP}O
```
-1 byte thanks to *@emanresuA*
Uses the given explicit formula: $$F\_n=\sum\_{k=0}^n(-1)^k(k+1)\binom{2n-k}{n-k}\frac1{n+1}$$
Given \$n\$, it'll output \$F\_n\$.
[Try it online](https://tio.run/##yy9OTMpM/f//8NxzWw93HNpuU2nnWVH8qGFWpW5CsqddVUCt////hkYA) or [verify all test cases](https://tio.run/##ATkAxv9vc2FiaWX/MTXGkk4/IiDihpIgIj9Owqn/w53OtcOIwrc8eT7Crnhz4oCaeS1gY8KuPnpQfU//LP8).
**Explanation:**
```
Ý # Push a list in the range [0, (implicit) input]
ε # Map each integer to:
È # Check whether it's even
· # Double that check (2 if even; 0 if odd)
< # Decrease it by 1 (1 if event; -1 if odd)
y> # Push the current integer, and decrease it by 1
I # Push the input
x # Double it (without popping)
s‚ # Swap, and pair them together: [2n,n]
y- # Subtract the current integer from each: [2n-k,n-k]
` # Pop and push the values back to the stack
c # Calculate their binomial coefficient
I>z # Push 1/(input+1)
P # Take the product of the four values on the stack
}O # After the map: sum them together
# (after which the result is output implicitly)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 49 bytes
Prints the sequence indefinitely.
```
x=c=n=1
while 1:print x;n+=1;c=c*4-c*6/n;x=c-x>>1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8I22TbP1pCrPCMzJ1XB0KqgKDOvRKHCOk/b1tA62TZZy0Q3WctMP88aqFC3ws7O8P9/AA "Python 2 – Try It Online")
Based on the Sage program at the end of the OEIS page.
[Answer]
# [Desmos](https://desmos.com/calculator), ~~46~~ 41 bytes
```
f(n)=-∑_{k=1}^n(-1)^kknCr(2n-k-1,n-k)/n
```
A port of the explicit formula but with one-indexing instead of zero-indexing.
[Try It On Desmos!](https://www.desmos.com/calculator/1q5oj0ifah)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/hdplzbpejf)
### Proof for the formula:
We start with the explicit formula given in the question:
$$F(n)=\frac1{n+1}\sum\_{k=0}^n(-1)^k(k+1)\binom{2n-k}{n-k}$$
Then convert it to one-indexing (making a new function \$f\$) by doing the following:
$$f(n)=F(n-1)=\frac1n\sum\_{k=0}^{n-1}(-1)^k(k+1)\binom{2n-k-2}{n-k-1}$$
From there, shift the bounds of the summation up by one, making sure to correct the shift within the summation:
$$\frac1n\sum\_{k=0}^{n-1}(-1)^k(k+1)\binom{2n-k-2}{n-k-1}=\frac1n\sum\_{k=1}^n(-1)^{k-1}k\binom{2n-k-1}{n-k}$$
Factoring out a \$-1\$ gives the formula used in my answer:
$$f(n)=-\frac1n\sum\_{k=1}^n(-1)^kk\binom{2n-k-1}{n-k}$$
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 36 bytes
```
n->Vec(2/(1+2*x+sqrt(1-4*x+O(x^n))))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN1XydO3CUpM1jPQ1DLWNtCq0iwuLSjQMdU2ATH-Nirg8TSCAqF1TUJSZV6KRpmFkABNasABCAwA)
Using the generating function.
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 39 bytes
```
n->(matrix(n+1,,i,j,i>abs(j-2))^n)[1,1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN9XzdO00chNLijIrNPK0DXV0MnWydDLtEpOKNbJ0jTQ14_I0ow11DGOhylXS8os08hRsFQx0FIyAuKAoM68EKKCkoGsHJNI08jQ1NSFqFyyA0AA)
Using this interesting formula on OEIS:
```
a(n) = the upper left term in M^n, n>0; where M = the infinite square production matrix:
0, 1, 0, 0, 0, 0, ...
1, 1, 1, 0, 0, 0, ...
1, 1, 1, 1, 0, 0, ...
1, 1, 1, 1, 1, 0, ...
1, 1, 1, 1, 1, 1, ...
...
- Gary W. Adamson, Jul 14 2011
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
~cŻÄÆmA
```
This calculates `abs(mean(cumsum(choose(-n-1, [0..n]))))`.
[Try it online!](https://tio.run/##y0rNyan8/78u@ejuwy2H23Id/wMZ7Y@a1vz/b2gAAA "Jelly – Try It Online")
The "negative binomial coefficients" are defined as $$\binom{-a}{b} = (-1)^b \binom{a+b-1}{b}.$$
And they are supported by Jelly's `c`. So we can rewrite the closed form as:
\begin{align}
F\_n&=\frac{1}{n+1}\sum\_{k=0}^n(-1)^k(k+1)\binom{2n-k}{n-k} \\
& \color{gray}{\text{(introduce negative binomials:)}} \\
&=\frac{1}{n+1}\sum\_{k=0}^n(-1)^k(k+1) \color{#0bf}{(-1)^{n-k} \binom{-n-1}{n-k}} \\
& \color{gray}{\text{(factor out powers of $-1$:)}} \\
&=(-1)^n \frac{1}{n+1} \sum\_{k=0}^n (k+1) \binom{-n-1}{n-k} \\
& \color{gray}{\text{(substitute $j=n-k$:)}} \\
&=(-1)^n \frac{1}{n+1} \sum\_{j=0}^n (n+1-j) \binom{-n-1}{j}
\end{align}
The `~cŻ` generates the negative binomials \$\binom{-n-1}{0}\$ through \$\binom{-n-1}{n}\$.
Then we use an obscure trick: we can calculate \$\sum\_{j=0}^n (n+1-j) \cdot z\_j\$ as `sum(cumsum(z))`, or `ÄS` in Jelly parlance. But then because we want to divide by \$n+1\$ immediately after, and our list has \$n+1\$ elements, we can write `Æm` (mean) instead of `S` (sum).
Here's an example of why this works:
\begin{align}
& \textrm{sum}(\textrm{cumsum}([a,b,c,d])) \\ =~& (a) + (a+b) + (a+b+c) + (a+b+c+d) \\ =~& 4a+3b+2c+d
\end{align}
Finally we still have to multiply by \$(-1)^n\$ to fix the sign. But because we know the Fine numbers are never negative, we can just take the absolute value with `A`.
[Answer]
# [Factor](https://factorcode.org/) + `koszul math.combinatorics`, 69 bytes
```
[ 4 dupn + [a,b] [ -1^ -rot nCk * ] with map-index cum-sum mean abs ]
```
[Try it online!](https://tio.run/##JYyxDoJAEAV7v@LVKiYkVlpaGBsbY0UwWY4VL3B7eLcXlZ9HlHbmvbmTUR/G6@V0Pu4Q@ZlYDEc0LByoswOp9RLhSB@bQNJMruUg3KH1cUjdbIx3lRWaUtbM45lHnf5Rf7APrPrpgxXFfrHIc1ivNBbYok69YIWC1lWJAll@Qxa8Qg4tlijxsv9en1mp@Q2TXBaTg2MSUBVRjpPEZvwC "Factor – Try It Online")
"Mathy" answers cause far too much whitespace in Factor so this is a port of mathcat's [Vyxal answer](https://codegolf.stackexchange.com/a/258124/97916).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
⊞υ¹≔¹θFN≔⊘⁻↨⊞OυΣ×⮌υυ⁰θθIθ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6Fjf7A0qLMzRKdRQMNa25HIuLM9PzNAx1FAqBvLT8IgUNz7yC0hK_0tyk1CINTU0FqAqPxJyy1BQN38y80mINp8TiVA2QMf4FqUWJJflFIOOCS3M1QjJzU4s1glLLUouAKko1dRRKNTWBpIEmyAJNiC0BRZl5JRrOicUlGkAx6yXFScnFUMctj1bSLctRil1oBuEDAA) Link is to verbose version of code. Explanation:
```
⊞υ¹
```
Start with `C(0)` = 1.
```
≔¹θ
```
Start with `F(0)` = 1.
```
FN
```
Loop `n` times.
```
≔⊘⁻↨⊞OυΣ×⮌υυ⁰θθ
```
Calculate the next Catalan number from the dot product of the list of numbers with its reverse and use that to calculate the next Fine number.
```
Iθ
```
Output `F(n)`.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 32 bytes
```
Đ⁺Đř⁻ĐĐ05Ș↔+2ř*⇹ɐ-Á⇹ć⇹⁺*⇹1~⇹^·⇹/
```
[Try it online!](https://tio.run/##K6gs@f//yIRHjbuOTDg681Hj7iMTjkwwMD0x41HbFG2jozO1HrXvPDlB93AjkD7SDiSAKkFihnVAIu7QdiCp//@/IQA "Pyt – Try It Online")
Naive implementation of the formula in the question.
The following walkthrough of the code is worked on an input of n=3
| Code | Stack | Action |
| --- | --- | --- |
| Đ | 3 3 | implicit input; **Đ**uplicate |
| ⁺ | 3 4 | increment |
| Đ | 3 4 4 | **Đ**uplicate |
| ř | 3 4 [1,2,3,4] | **ř**angify |
| ⁻ | 3 4 [0,1,2,3] | decrement |
| ĐĐ | 3 4 [0,1,2,3] [0,1,2,3] [0,1,2,3] | **Đ**uplicate twice |
| 05Ș | 3 0 [0,1,2,3] [0,1,2,3] [0,1,2,3] 4 | Push **0**, then **Șwap** the top **5** items on the stack |
| ↔ | 4 [0,1,2,3] [0,1,2,3] [0,1,2,3] 0 3 | Flip the entire stack |
| + | 4 [0,1,2,3] [0,1,2,3] [0,1,2,3] 3 | Remove that pesky 0 by adding |
| 2ř | 4 [0,1,2,3] [0,1,2,3] [0,1,2,3] 3 [1,2] | Push **2** and **ř**angify |
| \* | 4 [0,1,2,3] [0,1,2,3] [0,1,2,3] [3,6] | Multiply |
| ⇹ | 4 [0,1,2,3] [0,1,2,3] [3,6] [0,1,2,3] | Swap the top two items on the stack |
| ɐ- | 4 [0,1,2,3] [0,1,2,3] [[3,2,1,0],[6,5,4,3]] | For **ɐ**ll pairs of values, subtract |
| Á | 4 [0,1,2,3] [0,1,2,3] [3,2,1,0] [6,5,4,3] | Push contents of **Árray** to stack |
| ⇹ | 4 [0,1,2,3] [0,1,2,3] [6,5,4,3] [3,2,1,0] | Swap the top two items on the stack |
| ć | 4 [0,1,2,3] [0,1,2,3] [20,10,4,1] | nCr |
| ⇹ | 4 [0,1,2,3] [20,10,4,1] [0,1,2,3] | Swap top two items on stack |
| ⁺ | 4 [0,1,2,3] [20,10,4,1] [1,2,3,4] | Increment |
| \* | 4 [0,1,2,3] [20,20,12,4] | multiply element-wise |
| ⇹ | 4 [20,20,12,4] [0,1,2,3] | Swap top two items |
| 1~ | 4 [20,20,12,4] [0,1,2,3] -1 | Push **1**, then negate |
| ⇹^ | 4 [20,20,12,4] [1,-1,1,-1] | Swap top two, then exponentiate |
| · | 4 8 | Dot product |
| ⇹/ | 2 | Swap top two items, then divide; implicit print |
[Answer]
# Mathematica, 51 bytes
It's [A000957](https://oeis.org/A000957)
Use the generating function
$$\sum\_{n=0}^\infty F\_nz^n=\frac1z\cdot\frac{1-\sqrt{1-4z}}{3-\sqrt{1-4z}}$$
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/NNji1KDO12Dk/NS0tMzkzNa8k2khfw1A7uLCoJNpQ10SrKlbbSKtKU6e6SsdAR7k2Vu1/moK@g0JQYl56arShQayCvn5AUWZeyX8A)
```
f=SeriesCoefficient[2/(1+Sqrt[1-4*z]+2*z),{z,0,#}]&
```
] |
[Question]
[
Write the shortest program or function that takes some text as input, and outputs either it or an empty line in a repeating pattern:
```
some text
some text
some text
some text
some text
some text
...
```
This must continue indefinitely, or until some unpreventable limitation occurs (stack size, memory, etc.). It must be newline separated, and you can assume the inputted text is made up of non-newline printable ASCII characters. Note that it doesn't have to follow the pattern text-text-empty, and text-empty-text would be equally valid.
The ratio of text lines and empty lines will also be specified by input. There are various ways you can do this (though you only need to support one):
* A fraction represented as a floating point number (this can represent the fraction which do OR do not have text in them, but it must be consistent)
* A ratio of lines with text to lines without (represented as two integer inputs)
* A fraction of lines which do OR do not have text in them (represented as an integer numerator and denominator)
Example:
Text: `Hello, world!`
Ratio: `2:3`
```
Hello, world!
Hello, world!
Hello, world!
Hello, world!
...
```
Text: `fraction`
Fraction: `1/3`
```
fraction
fraction
fraction
...
```
Text: `decimal decimal decimal`
Input: `0.6`
```
decimal decimal decimal
decimal decimal decimal
decimal decimal decimal
decimal decimal decimal
decimal decimal decimal
decimal decimal decimal
...
```
Text: `example with a different pattern`
Fraction: `2/5`
```
example with a different pattern
example with a different pattern
example with a different pattern
example with a different pattern
...
```
This is code golf, so the shortest answer in bytes, per language, wins.
[Answer]
## [Pip](https://github.com/dloscutoff/pip), ~~26~~ 12 bytes
```
T0{LbPaLcPx}
```
-14 bytes after taking ratio as two arguments.
### Explanation:
```
T0 Till 0 (infinite loop)
{Lb Loop b(second argument) number of times
Pa Print a(first argument) with newline
Lc Loop c(third argument) number of times
Px} Print x(empty string) with newline
```
[Try it online!](https://tio.run/##K8gs@P8/xKDaJykg0Sc5oKL2////aUWJySWZ@Xn/Df8bAwA)
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
def f(t,a,b,n=0):print(n%b<a)*t;f(t,a,b,n+a)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNo0QnUSdJJ8/WQNOqoCgzr0QjTzXJJlFTq8QaLqedqPk/TUPJIzUnJ1@hPL8oJ0VRSUfBSEfBVPM/AA "Python 2 – Try It Online")
Prints until exceeding max recursion depth, which the challenge seems to allow. As a program:
**45 bytes**
```
t,a,b=input()
n=0
while 1:print(n%b<a)*t;n+=a
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v0QnUSfJNjOvoLREQ5Mrz9aAqzwjMydVwdCqoCgzr0QjTzXJJlFTq8Q6T9s28f9/JY/UnJx8hfL8opwURSUdBSMdBVMA "Python 2 – Try It Online")
The idea is to to use a counter `n` that cycles through values modulo `b`, and only print the text if this is from `0` to `a-1`, and otherwise print a blank line. We could also do `n+=1` in place of `n+=a` to get a different pattern where the text and blank lines come in clumps rather than mixed throughout.
It almost works to use a float input for the density as below:
**40 bytes** (not working)
```
def f(t,p,n=0):print(n%1<p)*t;f(t,p,n+p)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNo0SnQCfP1kDTqqAoM69EI0/V0KZAU6vEGiqjXaD5P01DySM1JydfoTy/KCdFUUlHwUDPTPM/AA "Python 2 – Try It Online")
The issue is float imprecision -- a number like `12.6` might have its decimal part be very slightly bigger or smaller than `0.6`. This method would work for irrational densities as well, limited precision aside.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~67 ..~~ 38 bytes
```
i;f(s,a,t){for(;puts(i++%t<a?s:""););}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/TOk2jWCdRp0SzOi2/SMO6oLSkWCNTW1u1xCbRvthKSUnTWtO69r9yZl5yTmlKqoJNcUlKZr5ehh1XZl6JQm5iZp6GpkI1F2eahpJHak5OvkJ4flFOiqKSjpGOqaY1V@1/AA "C (gcc) – Try It Online")
* Thanks to @att for 11 byte saved and to @ErikF for 7 bytes saved!
Takes input as string, number of printed lines, total lines.
~~We flush buffer at every iteration.~~
puts() returns non negative if no error occours, hope it doesn't return 0 either!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Full program. Prompts for text, then for ratio of lines with text to lines without (as two integers). Runs forever.
```
⎕←⍣≢↑⎕/⍞''
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@jvqmP2iY86l38qHPRo7aJQK7@o9556uog2f8KYFDA5ZGak5Ovo1CeX5SToshlpGAMAA "APL (Dyalog Unicode) – Try It Online")
`⍞''` prompt for text and juxtapose with an empty string
`⎕/` prompt for replication factors and replicate
`↑` stack them on top of each other
`⍣≢` repeat until the value changes (i.e. never):
`⎕←` output
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Runs until the stack overflows. More golfing to follow ...
```
ÆOpWÃVÆOpPéß
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xk9wV8NWxk9wUMOp3w&input=MiwzCiJIZWxsbywgd29ybGQhIg)
[Answer]
# [J](http://jsoftware.com/), 17 16 bytes
```
$:,[echo@#'',:~]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Vax0olOTM/IdlNXVdazqYv9rchkpGCukKah7pObk5CuE5xflpCiq/wcA "J – Try It Online")
Note: If the empty lines cannot have spaces, then `$:,[echo@>@#a:;~]` works for 17 bytes.
## how
Uses a kind of "fork bomb" recursion:
* `$:` - calls entire verb again
* `,` - then append...
* `[echo@#` - the echo of the left argument applied as a line-wise multiplier to...
* `'',:~]` - the right argument catted line-wise with an empty string
[Answer]
# x86-16 machine code, IBM PC DOS, ~~34~~ 33 bytes
Binary:
```
00000000: be82 00ad 2d30 3092 52fe ca7c 0956 ac3c ....-00.R..|.V.<
00000010: 0dcd 2975 f95e b00a cd29 fece 75eb 5aeb ..)u.^...)..u.Z.
00000020: e7 .
```
Listing:
```
BE 0082 MOV SI, 82H ; SI to command line tail
AD LODSW ; load first two chars
2D 3030 SUB AX, '00' ; ASCII convert
92 XCHG AX, DX ; DL = numerator, DH = denominator
PATT_LOOP:
52 PUSH DX ; save original numerator/denominator
FRAC_LOOP:
FE CA DEC DL ; decrement numerator
7C 09 JL LF ; if less than 0, just display LF
56 PUSH SI ; save start of input string
CHAR_LOOP:
AC LODSB ; load next char of string
3C 0D CMP AL, 0DH ; is it a CR?
CD 29 INT 29H ; write to console
75 F9 JNZ CHAR_LOOP ; if not a CR, keep looping
5E POP SI ; restore start of input string
LF:
B0 0A MOV AL, 0AH ; LF char
CD 29 INT 29H ; write to console
FE CE DEC DH ; decrement denominator
75 EB JNZ FRAC_LOOP ; if not 0, keep looping
5A POP DX ; restore numerator/denominator
EB E7 JMP PATT_LOOP ; start over and loop indefinitely
```
Standalone DOS executable, input via command line. First two chars are numerator / denominator, followed by input string.
[](https://i.stack.imgur.com/Sng8n.png)
[](https://i.stack.imgur.com/Nr8V8.png)
*(note: program slightly altered to only repeat 3 times for screenshots)*
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~48~~ 47 bytes
Saved a byte thanks to Dion
```
def f(t,a,b):
while 1:print((t+'\n')*a+'\n'*b)
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PyU1TSFNo0QnUSdJ04pLoTwjMydVwdCqoCgzr0RDo0RbPSZPXVMrEUxrJWn@T9NQ8kjNyclXKM8vyklRVNJRMNJRMNb8DwA "Python 3.8 (pre-release) – Try It Online")
`t` is the text to print, `a`:`b` is the ratio of lines of text to empty lines.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ø.x⁹ẋṄ€1¿
```
A full program accepting the ratio as a list `[empty, full]` and the string which prints forever.
**[Try it online!](https://tio.run/##y0rNyan8///wDL2KR407H@7qfriz5VHTGsND@////x9trGMU@1/dA6gmX0ehPL8oJ0VRHQA "Jelly – Try It Online")**
### How?
```
Ø.x⁹ẋṄ€1¿ - Main Link: list of integers, ratio ([empty, full]); list of characters, text
e.g.: [3, 2]; "Hello, world!"
Ø. - bits [0, 1]
x - times (ratio) [0, 0, 0, 1, 1]
⁹ - chain's right argument "Hello, world!"
ẋ - repeat (vecorises) ["", "", "", "Hello, world!", "Hello, world!"]
¿ - while...
1 - ...condition: 1 (always)
€ - ...do: for each:
Ṅ - print with trailing newline
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 58 bytes
```
(s,n,d)->{for(int i=0;;)System.out.println(i++%d<n?s:"");}
```
[Try it online!](https://tio.run/##NY5Ba8MwDIXv@xVaYBBTN4zBLvPaXncZDHocO2ixUtw5crCVbqPkt2dO6x3Ekx687@mIJ1wf7dfcekwJXtExnG8AHAvFDluCN5S8Xl2AU3AWIg2EUu8lOj6A0I/oJQA89hRRQryeljj0jhdDmZye8gzjp3ctJEHJcqH1ubOw3j@gU6Xpv3coupnrpFlbtd6euxDrpcFt7o1R@98k1DdhlGbIFPFcu9Xqzj7zLj1VlTLTbC7IgmrK/9ULeR/gO0RvbysNDxoey6PT/Ac "Java (JDK) – Try It Online")
## Credits
* 4 bytes saved thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~100~~ ~~88~~ 87 bytes
```
T =INPUT
CODE('N' DUPL('; OUTPUT =T',INPUT) DUPL('; OUTPUT =',INPUT) ':(N)') :(N)
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/nzNEwdbTLyA0hIvT2d/FVUPdT13BJTTAR0PdmtM/NAQooWAboq4DVqKJIQOXULfS8NNU1@QEUVyufi7//6cVJSaXZObncRlyGQMA "SNOBOL4 (CSNOBOL4) – Try It Online")
Takes input as `TEXT`, `M`, `N` on separate lines.
Using the `CODE` function, this generates an infinite loop of
```
N; OUTPUT =T; OUTPUT =T ...; OUTPUT =; OUTPUT =; ... :(N)
```
Or equivalently (with `;` being replaced by newlines):
```
N
OUTPUT =T
OUTPUT =T
...
OUTPUT =
OUTPUT =
...
OUTPUT =:(N)
```
Which it then enters with the final `:(N)` and never leaves.
[Answer]
## Batch, 87 bytes
```
@set f=@for /l %%i in (1,1,
@set/ps=
:g
%f%%1)do @echo(%s%
%f%%2)do @echo(
@goto g
```
Takes the text and blank line counts as command line arguments and the text to repeat on standard input. Explanation:
```
@set f=@for /l %%i in (1,1,
```
Define what is effectively a macro for two very similar loops.
```
@set/ps=
```
Input the text.
```
:g
```
Begin an infinite loop.
```
%f%%1)do @echo(%s%
```
Print the text the desired number of times.
```
%f%%2)do @echo(
```
Print the desired number of blank lines.
```
@goto g
```
Rinse and repeat.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[s`¶×?F=
```
First input is the text, second input is a pair `[amount_of_nonempty_lines, amount_of_empty_lines]`; outputs the empty lines before the non-empty lines.
[Try it online.](https://tio.run/##yy9OTMpM/f8/ujjh0LbD0@3dbP//90jNycnXUSjPL8pJUeSKNtJRMI4FAA)
**Explanation:**
```
[ # Start an infinite loop:
s # Swap the two (implicit) inputs, so the pair it at the top of the stack
` # Pop and push its contents to the stack
¶× # Repeat a newline character "\n" the top value amount of times as string
? # Pop and output it without trailing newline
F # Pop and loop the top value amount of times:
= # And output the top string with trailing newline (without popping)
```
[Answer]
# [R](https://www.r-project.org/), ~~48~~ 47 bytes
*Edit: -1 byte thanks to Giuseppe*
```
function(t,c)repeat cat(rep(c(t,''),c),sep='
')
```
[Try it online!](https://tio.run/##XYxBCoAgEADvvUK67C7sqc6@JWTbShAVNXq@Cd26DTMwpRfN6pqP5xZ81Gr7cUdpPkVsLPRVI67hQJQhAWgErpotTED/Ac6XhpDYPKmEfWbBhVei/gI "R – Try It Online")
Function with arguments specifying text `t` and vector `c` of counts of text & blank lines.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
~o¢+RøR⁰
```
[Try it online!](https://tio.run/##yygtzv7/vy7/0CLtoMM7gh41bvj//79ScX5uqkJJakWJ0n@j/8YA "Husk – Try It Online") This program takes the string, the number of lines with text, and the number of lines without text as three separate arguments.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 40 bytes
Expects `(p, q)(s)`, where \$p/q\$ is the fraction of lines that have the string \$s\$ in them.
This runs until the call stack overflows.
```
(p,q,t=0)=>g=s=>print(t++%q<p?s:'')&g(s)
```
[Try it online!](https://tio.run/##BcEJCoAgEADAr4RQ7qJBEEFEa28RSzEqvPD7NnPrqrNJPpSxrs1SgyCjLDQhKUeZVEj@K1CE6OMejrxxjoODjM3CLLsFgZ2X8a9@GLYf "JavaScript (V8) – Try It Online")
[Answer]
## [Assembly (MIPS, SPIM)](https://github.com/TryItOnline/spim), 236 bytes, 6 \* 23 = 138 assembled bytes
Full program that takes the input in the order (`input string, numerator, denominator`). Output is to STDOUT.
```
.data
m:
.text
main:li$v0,8
la$a0,m
li$a1,99
syscall
li$v0,5
syscall
move$t0,$v0
li$v0,5
syscall
move$t1,$v0
s:li$t2,0
li$v0,4
la$a0,m
l:syscall
add$t2,$t2,1
blt$t2,$t0,l
li$t2,0
li$a0,10
li$v0,11
p:syscall
add$t2,$t2,1
blt$t2,$t1,p
b s
```
[Try it online!](https://tio.run/##hY29DsIwDIR3P0WGjlaVFJBo38YlroiUlKixSnn60B8FJsTg4Xzf3aXoQs61JSEIHdTCi0AgN3beVbPGK3iqSGOAVZPBtoX0SjfyHg7g8tHhMXMlGtfvD8/sXtqqpcFCnb8TXeHJ2g3ZzkDv5RAa99WSXTOmlBgD8U/aYIRepZx5oRA9q6eTuyJl3TDwxKOoSCI8jdDA6Q0 "Assembly (MIPS, SPIM) – Try It Online")
## Explanation
```
.data
msg: # Here's the string input buffer (dynamically allocated)
.text
main:
li $v0, 8 # Set syscall code 8
la $a0, msg # The first operand is the input buffer
li $a1, 99 # The second is the maximum length of input
syscall # Read a line of characters from input
li $v0, 5 # Set syscall code 5
syscall # v0 = integer from input
move $t0, $v0 # t0 = v0
li $v0, 5 # Re-set syscall code 5
syscall # v0 = integer from input
move $t1, $v0 # t1 = v0
start: # Main loop:
li $t2, 0 # t2 = 0 (our counter)
li $v0, 4 # Set syscall code 4
la $a0, msg # First operand: the inputted message at msg
loop: # loop:
syscall # Print the message at msg
add $t2, $t2, 1 # Increment counter
blt $t2, $t0, loop # If t2 < t0, jump back
li $t2, 0 # Clear counter
li $v0, 11 # Set syscall code 11
li $a0, 10 # First operand: '\n'
lop: # second loop:
syscall # Print character in a0
add $t2, $t2, 1 # Increment counter
blt $t2, $t1, lop # if t2 < t1, jump back
b start # Jump back to the main loop
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes
```
Do[Print@If[i>#2,#,""],∞,{i,#3}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yU/OqAoM6/EwTMtOtNO2UhHWUdJKVbnUcc8nepMHWXj2li1/2nRSh6pOTn5CuX5RTkpiko6RjrGsf8B "Wolfram Language (Mathematica) – Try It Online")
Takes `[text, num, denom]`, where `num/denom` is the ratio of lines *without* text.
[Answer]
# SimpleTemplate 0.84, 99 bytes
Yes, it is quite long, but it works!
```
{@callexplode intoM":",argv.1}{@while1}{@forfrom 1toM.0}{@echolargv.0}{@/}{@forfrom 1toM.1}{@echol}
```
Takes input in the form of an array with the format `['text', '1:1']`.
---
If taking input as 2 separate numbers (`['text', 1, 1]`) is acceptable, the code can be reduced to this (66 bytes):
```
{@forfrom 1toargv.1}{@echolargv.0}{@/}{@forfrom 1toargv.2}{@echol}
```
---
**Ungolfed:**
Below is a more readable version of the top code:
```
{@call explode into ratio ":", argv.0}
{@while true}
{@for i from 1 to ratio.0}
{@echo argv.0, EOL}
{@/}
{@for i from 1 to ratio.1}
{@echo EOL}
{@/}
{@/}
```
Notice that `{@echol}` and `{@echo EOL}` do the same thing: output whatever, ending with a newline.
---
You an try it on: <http://sandbox.onlinephpfunctions.com/code/abf48bd44a808e91f130d4a390fcb8a18d6ded39>
[Answer]
# [PHP](https://php.net/), ~~52~~ 51 bytes
```
for($a=$argv;;)echo($i++%$a[3]<$a[2]?$a[1]:"")."
";
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFQSbVUSi9LLrK01U5Mz8jVUMrW1VVUSo41jbYCkUaw9kDSMtVJS0tRT4lKy/v//f3FJaUlJapFCZnFOYl7Kf@P/pgA "PHP – Try It Online")
Nothing new under the sun: PHP arguments and vars prefix eating bytes.. Will go on "forever" (until it overflows the max integer value, and starts using floats for `$i`, then probably the legendary precision for big floats will cause inconsistent results)
EDIT: newline replaced by.. a newline to save 1 byte
] |
[Question]
[
Your goal is to write a program that takes no input and outputs the following text:
```
ca e na ŋa va o sa;
þa ša ra la ła.
ma a pa fa ga ta ča;
în ja i da ða.
ar ħo ên ôn ân uħo;
carþ taŋ neŋ es nem.
elo cenvos.
```
But there's a catch: for each letter (any character whose general category in Unicode starts with `L`) in your source, you get a penalty of 20 characters! (For reference, the text to be printed has 81 letters.)
The Perl 6 code below has 145 bytes and 84 letters, so it gets a score of 1,845:
```
say "ca e na ŋa va o sa;
þa ša ra la ła.
ma a pa fa ga ta ča;
în ja i da ða.
ar ħo ên ôn ân uħo;
carþ taŋ neŋ es nem.
elo cenvos."
```
The code below has 152 bytes and 70 letters, so it gets a score of 1,552:
```
$_="C e N ŋa V o S;
Þ Š R L Ł.
M a P F G T Č;
în J i D Ð.
ar ħo ên ôn ân uħo;
Crþ Tŋ neŋ es nem.
elo cenvos.";s:g/<:Lu>/{$/.lc~'a'}/;.say
```
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
*Originally, I thought of forbidding letters altogether, but I don't think there are many languages that make this possible. You're more than welcome to try.*
*(ŋarâþ crîþ [ˈŋaɹa̰θ kɹḭθ] is one of my conlangs. I wanted to capitalise its name here, but I get the ugly big eng here. Oh well, the language doesn't use capital letters in its romanisation anyway.)*
*Edit: realised that one of the lines is wrong, but I'll keep it since there are already answers. The correct version of the third line is `ma a fa ga pa ta ča`; at your choice, you may choose to produce the corrected text instead.*
[Answer]
# [7](https://esolangs.org/wiki/7), 410 characters, 154 bytes in 7's encoding, 0 letters = score 154
```
55104010504200144434451510201304004220120504005434473340353241135014335450302052254241052253052244241052335452241114014241310052340435303052335442302052335500302052335430302052313340435303135014243241310335514052312241341351052302245341351525755102440304030434030421030442030424030455733413512410523142410523030523112411350143355142410523414252410523102410523002410523413342411145257551220304010420030455741403
```
[Try it online!](https://tio.run/##TVEJDsRACPoSCqT/f1kX52g2aQ2ieM3zvnZBKBhqoCRRcoVtFBMKH9STAHiiDynQbFXR0ZCWwSjcbYVfgGN13JXTI6m0G5KF4QWlFnhy1LtOsIEPixcXP8nu3uKuNpIUn5xpxHxerRHX23X7mZUzF2a7/Fy2a2xuMHgx9iw6orNB3VX2sFX/B/AXVZCvBFeCL5qi@wxnll498wTzALtvSoDv@wM "7 – Try It Online")
In a challenge that dislikes using letters, what better language to use than one consisting only of digits?
This is a full program that exits via crashing, so there's extraneous output to stderr, but stdout is correct.
## Explanation
A 7 program, on its first iteration, simply pushes a number of elements to the stack (because out of the 12 commands that exist in 7, only 8 of them can be represented in a source program, and those 8 are specialised for writing code to push particular data structures to the stack). This program does not use the **`6`** command (which is the simplest way to create nested structures, but otherwise tends not to appear literally in a source program), so it's only the **`7`** commands that determine the structure; **`7`** pushes a new empty element to the top of stack (whereas the `0`…`5` commands just append to the top of stack). We can thus add whitespace to the program to show its structure:
```
551040105042001444344515102013040042201205040054344 **7**
33403532411350143354503020522542410522530522442410523354522411140142413100523
40435303052335442302052335500302052335430302052313340435303135014243241310335
514052312241341351052302245341351525 **7**
55102440304030434030421030442030424030455 **7**
33413512410523142410523030523112411350143355142410523414252410523102410523002
41052341334241114525 **7**
551220304010420030455 **7**
41403
```
The elements near the end of the program are pushed last, so are on top of the stack at the start of the second iteration. On this iteration, and all future iterations, the 7 interpreter automatically makes a copy of the top of the stack and interprets it as a program. The literal `41403` pushes the (non-literal, live code) **`47463`** (7 has 12 commands but only 8 of them have names; as such, I use bold to show the code, and non-bold to show the literal that generates that code, meaning that, e.g. `4` is the command that appends **`4`** to the top stack element). So the program that runs on the second iteration is **`47463`**. Here's what that does:
```
**47463**
**4** Swap top two stack elements, add an empty element in between
**7** Add an empty stack element to the top of stack
**4** Swap top two stack elements, add an empty element in between
**6** Work out which commands would generate the top stack element;
append that to the element below (and pop the old top of stack)
**3** Output the top stack element, pop the element below
```
This is easier to understand if we look at what happens to the stack:
* … *d* *c* *b* *a* **`47463`** (code to run: **`47463`**)
* … *d* *c* *b* **`47463`** *empty* *a* (code to run: **`7463`**)
* … *d* *c* *b* **`47463`** *empty* *a* *empty* (code to run: **`463`**)
* … *d* *c* *b* **`47463`** *empty* *empty* *empty* *a* (code to run: **`63`**)
* … *d* *c* *b* **`47463`** *empty* *empty* "*a*" (code to run: **`3`**)
* … *d* *c* *b* **`47463`** *empty* (code to run: *empty*)
In other words, we take the top of stack *a*, work out what code is most likely to have produced it, and output that code. The 7 interpreter automatically pops empty elements from the top of stack at the end of an iteration, so we end up with the **`47463`** back on top of the stack, just as in the original program. It should be easy to see what happens next: we end up churning through every stack element one after another, outputting them all, until the stack underflows and the program crashes. So we've basically created a simple output loop that looks at the program's *source code* to determine what to output (we're not outputting the data structures that were pushes to the stack by our `0`…`5` commands, we're instead recreating what commands were used by looking at what structures were created, and outputting those). Thus, the first piece of data output is `551220304010420030455` (the source code that generates the second-from-top stack element), the second is `3341351…114525` (the source code that generates the third-from-top stack element), and so on.
Obviously, though, these pieces of source code aren't being output unencoded. 7 contains several different domain-specific languages for encoding output; once a domain-specific language is chosen, it remains in use until explicitly cleared, but if none of the languages have been chosen yet, the first digit of the code being output determines which of the languages to use. In this program, only two languages are used: `551` and `3`.
`551` is pretty simple: it's basically the old Baudot/teletype code used to transmit letters over teletypes, as a 5-bit character set, but modified to make all the letters lowercase. So the first chunk of code to be output decodes like this:
```
551 22 03 04 01 04 20 03 04 55
c a SP e SP n a SP reset output format
```
As can be seen, we're fitting each character into two octal digits, which is a pretty decent compression ratio. Pairs of digits in the 0-5 range give us 36 possibilities, as opposed to the 32 possibilities that Baudot needs, so the remaining four are used for special commands; in this case, the `55` at the end clears the remembered output format, letting us use a different format for the next piece of output we produce.
`3` is conceptually even simpler, but with a twist. The basic idea is to take groups of three digits (again, in the 0-5 range, as those are the digits for which we can guarantee that we can recreate the original source code from its output), interpret them as a three-digit number in base 6, and just output it as a byte in binary (thus letting us output the multibyte characters in the desired output simply by outputting multiple bytes). The twist, though, comes from the fact that there are only 216 three-digit numbers (with possible leading zeroes) in base 6, but 256 possible bytes. 7 gets round this by linking numbers from 332₆ = 128₁₀ upwards to two different bytes; `332` can output either byte 128 or 192, `333` either byte 129 or 193, and so on, up to `515` which outputs either byte 191 or 255.
How does the program know which of the two possibilities to output? It's possible to use triplets of digits from `520` upwards to control this explicitly, but in this program we don't have to: 7's default is to pick all the ambiguous bytes in such a way that the output is valid UTF-8! It turns out that there's always at most one way to do this, so as long as it's UTF-8 we want (and we do in this case), we can just leave it ambiguous and the program works anyway.
The end of each of the `3…` sections is `525`, which resets the output format, letting us go back to `551` for the next section.
[Answer]
## Haskell, 0 letters, 423 bytes = score 423
```
(['\10'..]!!)<$>[89,87,22,91,22,100,87,22,321,87,22,108,87,22,101,22,105,87,49,0,244,87,22,343,87,22,104,87,22,98,87,22,312,87,36,0,99,87,22,87,22,102,87,22,92,87,22,93,87,22,106,87,22,259,87,49,0,228,100,22,96,87,22,95,22,90,87,22,230,87,36,0,87,104,22,285,101,22,224,100,22,234,100,22,216,100,22,107,285,101,49,0,89,87,104,244,22,106,87,321,22,100,91,321,22,91,105,22,100,91,99,36,0,91,98,101,22,89,91,100,108,101,105,36]
```
[Try it online!](https://tio.run/##TVDLCsIwEPyVCoIKUbKbtCZg/QJvHrWHUnxhleID@vXGbMymXpLJZHZ3ds7183poW9eXezfdTfYgJ4tFNRrNVuP1zlhhlgJRWKATpIxvhRARSJNQFOVEaCukQK25QKskY85ypQIkpApfYnkkqxnZBIZORUSY22EmmmCUlPxv83Cye1QyzfM3OSLW5LwDouYeqAYIBUOQy6QPU39JhU5a/5mjoGJyPsP48ohSGni/9G95oFCiCd8yCGXImEgqUkXlbvXlnpVZ935tX4/NPevdpzm29enp5k3XfQE "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~274 260~~ 212 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) + 2 letters = ~~314 300~~ 252
-48 bytes thanks to Nick Kennedy
```
“19ב+49;7883,8220,8216,7884Ọ“19937801,1169680277365253“38“68112“;107¤+1+\“@“&%"("/%"@%"6%"0"3%$!<%" %"2%"-%"?%#!.%"%"1%")%"*%"4%"=%$!9/",%"+"'%":%#!%2">0"8/";/"7/"5>0$!&%2<"4%@"/(@"(3"/(.#!(-0"&(/603#“_32¤”;";/V
```
(Uses `!"#$%&'()*+,-./0123456789:;<=>?@V\_¤×Ọ‘“”` of which `V` and `Ọ` are Unicode letters and are used once each)
**[Try it online!](https://tio.run/##HY29UcNAFIRbQSuvOJDsu3cn3Q8ytqogYoaIhHEDZCqAHALI3AWZqQQ1It4Q7O7svG/nvTyfTq/rusyfUn7el/mj7cuYcg5d9t6pSey09r/fb/9MCSk76URiidn5lEIc/BD0FrJazCJecxSXLudW2kctk6ohDCwxEZFwCNxUe@KK8MSWOLKudgQhxA1xS/TEvULFoiNaXBN3ytDj4JAtRotkMRzcpmro94pPsGaCCRq7ujJbh8bY6EKt75@Cv5yX@WvU3cO6/gE "Jelly – Try It Online")**
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), scores ~~601~~ 546
```
-join(67,65,0,69,0,78,65,0,299,65,0,86,65,0,79,0,83,65,27,-22,222,65,0,321,65,0,82,65,0,76,65,0,290,65,14,-22,77,65,0,65,0,80,65,0,70,65,0,71,65,0,84,65,0,237,65,27,-22,206,78,0,74,65,0,73,0,68,65,0,208,65,14,-22,65,82,0,263,79,0,202,78,0,212,78,0,194,78,0,85,263,79,27,-22,67,65,82,222,0,84,65,299,0,78,69,299,0,69,83,0,78,69,77,14,-22,69,76,79,0,67,69,78,86,79,83,14|%{[char]($_+32)})
```
[Try it online!](https://tio.run/##TVDRCsIwDPwZhQ07aNOuSb9FREQGU4aT@eCD@u0zaVrxoc01ueYuuc/PYXmMwzSta3edL7cmoom9sSYmvpD0ASkpoKgRpUpeHoCmAzDAJ5c8uMItCYy1iRXgQuZj1cnUErHG2iKUrx7/pWwUZ0wrZfTSqHq19CfDiH1wNno1DRb0M7gCXAoKqK@0IqS7IB2uupFd6GZSwQzI/3I8WNVOMntWlU5JCJQTTHfhvX3tz@NpOTSb485D@2nX9Qs "PowerShell – Try It Online")
Naive approach; I just took the code points and converted them to decimal, subtracted 32, then this code treats them as a `char` before `-join`ing it back together into a single string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 321 bytes + 2 letters = score 361
```
3343781777797791350694255572961968519437585132057650209974147122192542459108221624793330048943528237823681411832154316740173721249435700067706302064570847610741421342406380917446310820012503592770000532190167243585300911078873144513786923305473352724133578818457026824110152529235136461572588027747840738399150398304b354Ọ
```
[Try it online!](https://tio.run/##FZDbaURBDENbkmz51U4gP2EbSA/pKNWkko3uMGDskY7MfH2@Xt/vd6ZyluNzvsxCn6KqJq55vcWzpFwzUNOFwN2IGkbwohSqI9Zdh@YyE9DaVrFhfGQvRW4GS8kegZMTDD2qAdAz6DS75X41TTwhwTTfT4vjSJ1PEsAoZF3MY0aZfDA4jNty/tH@3UlKXn22L7xXadJrWUdXC7hPXvR6QrCiwkI7Wk1/Qu3CIZoVJjfv6ODbhD6y9Pf7837/Aw "Jelly – Try It Online")
This is hideous and someone can definitely do better.
[Verify score](https://tio.run/##TVBratwwEP4dnUIsBOwmLPPUjAp7g96g9Mdm7bSG1F5sB7J36I16mp5kO/pTKgTz0PdC19v@Y5n5fp9@Xpd1z@/zdFmGcTjv5@e83baU2phPrT9u@zDNx3U8D12f0hZbSOl1WfNHnubcgJ/Tw/T6v8jxct7H78t66z76r/Atn0758OUQsIctP50ypnRdp3nvDo9DfrntY2xztG/jvo9rc9guyzrG6pAfc/c2zl1T7iPbc/43BYcgf8pb39/vzMLmaHFqXGSFUoVU1agWrMUVa0A0KhOoFQWCWk1QDImwkgqJVgSPqZBYZWYA8aApOYU8cXEURGdCFcZiAmhshCQNZQBQzKBwaBeJ2cUKQjMh5NCPJ4eKJlK4OQEgKbBWskYGDeUKIUwh5xr@FYPvbowiEd28VIpcKsYRK3AYNQDozY@KxwYBlZQCGIwiBeMT1B3CRMwFjJ1rxTCuziAvrPLn96@/).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), score ~~209~~ 207 (187 bytes + 20 penalty for 1 letter)
```
•£?;\:'%¢;.'¡£/':¢?'¢°':¢°#@¢«>#%¡¤;®[¢:¥¢:©¢:¦¢;®¢>#¡£#¨¢#&¢+¢#,¢:§¡¤#¬¢#@¢#)¢#(¢#<¢#¢#/¡£#¯¢#.¢#>¢#±¢#«¡¤#?¢;¢#\¢#°¢#:¢'¢#%•[₅‰`©®_#∞158+9022014013016708040204090101502501027¾¡17∍.¥>:ç?
```
[Try it online!](https://tio.run/##JY5dSsNQEIUXM8RUKunca2PaRBL30YI/4INPPriBIgh96RYKvbWtUolxAz4cd3I3Es8o3HNm7gzfcB6fbu8e7vs@LgK2TTUv0wShylJssB2lJUKTIqCzDp1c0Y@1JNy@VmhnCCV2Zu9me5JoEWoxWvCGICcIQ5Yz2x8ME3zwz0NySg2oS4pv9A99ss2o2qZfZsc/rLHjQeY26WgMxGSSMPgsPr/ERXfDFO21xOXa5ZPhVL1XN1Z3ru6i0ImO1VNTdepy9TmrL/CNjSvicpVhV5c/h6bvfwE "05AB1E – Try It Online")
The only letter is `ç`. The currency symbols `€£¢` are not considered letters in Unicode.
[Answer]
# [Python 3](https://docs.python.org/3/), 380 bytes + 5 letters = 480
```
print("""\143\141 \145 \156\141 \513\141 \166\141 \157 \163\141;
\376\141 \541\141 \162\141 \154\141 \502\141.
\155\141 \141 \160\141 \146\141 \147\141 \164\141 \415\141;
\356\156 \152\141 \151 \144\141 \360\141.
\141\162 \447\157 \352\156 \364\156 \342\156 \165\447\157;
\143\141\162\376 \164\141\513 \156\145\513 \145\163 \156\145\155.
\145\154\157 \143\145\156\166\157\163.""")
```
[Try it online!](https://tio.run/##RVAxEsMgDNt5RY@pXXJxjGHIV/KAdklzvSx9PbWMnQ5wWEiyreN7Pt879358Xvt5zzlvVFgP3fQSvaSOSijg6ghJQ2XwmjZuwSwUzCWYxb9mQ6akkEQXY85RhXlp8eXaQhKdMJNU@F4NTOJMHm7oglHqomLYYV6GBFqGrz2KI1QleGuKGGwJXe0aBEFELOKFPjSHP6rLWXMZm1tOZieDggSlQTNp4o/efw "Python 3 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 140 characters, 159 bytes, 14 letters = score 439
```
%# ' 1# !# 9# 2 6#;¶þ# š# 5# /# ł#.¶0# # 3# (# )# 7# č#;¶î1 ,# + &# ð#.¶#5 ħ2 ê1 ô1 â1 8ħ2;¶%#5þ 7#! 1'! '6 1'0.¶'/2 %'1926.
T`!--/-9`ŋ\`-{
```
[Try it online!](https://tio.run/##HYshDsJAFER9TzGbSVkIbNu/pIWGayARRSAwiAaHwxIOAYYEQRCksqLbnmtZEJOZTN6rd8f9YSveRzGhIYQiSsKi4KprXEsMNyIn0rDOTLomI4g5MSYmxILor3/0JZgRU4wI9/6BzNE/LNxT4D4hd8EyHIGNmbs2qAqiFXQRKguCTi1iLaUtkmhdKWNSU1bDZVOZk/df "Retina – Try It Online") Edit: Saved 1 letter by switching from `K`` to a newline. Now also works in Retina 0.8.2 (but the title would be too long).
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), ~~304~~ 286 bytes + ~~2~~ 1 letter~~s~~ = ~~344~~ 306
Well, this is just god-awful!
```
"3 1
5
14 1
235 1
22 1
15
19 1 -37 -86 158 1
257 1
18 1
12 1
226 1 -50 -86 13 1
1
16 1
6 1
7 1
20 1
173 1 -37 -86 142 14
10 1
9
4 1
144 1 -50 -86 1 18
199 15
138 14
148 14
130 14
21 199 15 -37 -86 3 1 18 158
20 1 235
14 5 235
5 19
14 5 13 -50 -86 5 12 15
3 5 14 22 15 19 -50"·®¸®°d96} ¬
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=IjMgMQo1CjE0IDEKMjM1IDEKMjIgMQoxNQoxOSAxIC0zNyAtODYgMTU4IDEKMjU3IDEKMTggMQoxMiAxCjIyNiAxIC01MCAtODYgMTMgMQoxCjE2IDEKNiAxCjcgMQoyMCAxCjE3MyAxIC0zNyAtODYgMTQyIDE0CjEwIDEKOQo0IDEKMTQ0IDEgLTUwIC04NiAxIDE4CjE5OSAxNQoxMzggMTQKMTQ4IDE0CjEzMCAxNAoyMSAxOTkgMTUgLTM3IC04NiAzIDEgMTggMTU4CjIwIDEgMjM1CjE0IDUgMjM1CjUgMTkKMTQgNSAxMyAtNTAgLTg2IDUgMTIgMTUKMyA1IDE0IDIyIDE1IDE5IC01MCK3rriusGQ5Nn0grA)
[Answer]
# [PHP](https://www.php.net/) -a, 402 bytes + 200 penalty = 602 score
```
foreach([67,65,0,69,0,78,65,0,299,65,0,86,65,0,79,0,83,65,27,-22,222,65,0,321,65,0,82,65,0,76,65,0,290,65,14,-22,77,65,0,65,0,80,65,0,70,65,0,71,65,0,84,65,0,237,65,27,-22,206,78,0,74,65,0,73,0,68,65,0,208,65,14,-22,65,82,0,263,79,0,202,78,0,212,78,0,194,8,0,85,263,79,27,-22,67,65,82,222,0,84,65,299,0,78,69,299,0,69,83,0,78,69,77,14,-22,69,76,79,0,67,69,78,86,79,83,14] as $i){echo ''.mb_chr($i+32);}
```
Port of [Artermis Fowl's answer](https://codegolf.stackexchange.com/a/183256/51608), and my first codegolf entry!
Leaves me wishing that `chr()` could just support UTF-8; those extra 3 bytes + 40 characters hurts!
[Answer]
# [Python 3](https://docs.python.org/3/), 397 bytes + 19 letters = 777 score
```
print(''.join(chr(i+32)for i in[67,65,0,69,0,78,65,0,299,65,0,86,65,0,79,0,83,65,27,-22,222,65,0,321,65,0,82,65,0,76,65,0,290,65,14,-22,77,65,0,65,0,80,65,0,70,65,0,71,65,0,84,65,0,237,65,27,-22,206,78,0,74,65,0,73,0,68,65,0,208,65,14,-22,65,82,0,263,79,0,202,78,0,212,78,0,194,78,0,85,263,79,27,-22,67,65,82,222,0,84,65,299,0,78,69,299,0,69,83,0,78,69,77,14,-22,69,76,79,0,67,69,78,86,79,83,14]))
```
[Try it online!](https://tio.run/##TVAxDsMgDPxKtyQqrcAQDG@pOlWqQgcSRVn6empjqDKAD/vwnb19j2XNtpRtT/kYh@H@WVMeX8s@pquF6b3ul3RJ@eFR@Vlp5SNdGOQBMQoIXiJyNVh@AKobgAI6tWTBNG5LoO9NNAPjKh@7TqW2iD32Fq59tXiW0p6dEa2V0XKj7lWHkwwh8kFZb8U0aJDPYBow0QkIc6c1IdlFkOG6G96FbCY2TCDYf44G69qRZ6@q3CkyIdQE0Y17TlMpPw "Python 3 – Try It Online")
Port of [AdmBorkBork's answer](https://codegolf.stackexchange.com/a/183252/80756).
[Answer]
# [R](https://www.r-project.org/), 384 bytes + 12 letters \* 20 points = *684 score*
Not terribly original.
```
cat(intToUtf8(c(67,65,0,69,0,78,65,0,299,65,0,86,65,0,79,0,83,65,27,-22,222,65,0,321,65,0,82,65,0,76,65,0,290,65,14,-22,77,65,0,65,0,80,65,0,70,65,0,71,65,0,84,65,0,237,65,27,-22,206,78,0,74,65,0,73,0,68,65,0,208,65,14,-22,65,82,0,263,79,0,202,78,0,212,78,0,194,78,0,85,263,79,27,-22,67,65,82,222,0,84,65,299,0,78,69,299,0,69,83,0,78,69,77,14,-22,69,76,79,0,67,69,78,86,79,83,14)+32))
```
[Try it online!](https://tio.run/##7VE7bsMwDN1zCm2yGhWQKEeiht6gYzolGYrATQMYruFoK3p2l9QnyA26FIbMJ/KJj59lXc/vqbtOaf/1lj6wO3c@aL/TRvtIv4DlAjEWgL7YwFF0fIGgnwE00MkhB7ZyqyP4lsQwsH3mh6aTqdWGZluKvj514VHKeK6MaDUcHCdqtRp8kCFEdZDXu1I0GCiPwVZgY18A7hqtCpVZYGmuVcOzKJOJFRNAd/dRY007cu9ZlTNFJmB2EN32autAqbwAeZz4k2ozDtMlfXaXZZjJe5y/X3@kvqXlNo9X4v1v62@3JbWU6nCwp5MW87CM4kXsldrcd0gbdNiLrbAgngSY9Rc "R – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score ~~383~~ 365 (325 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) + 2 letters \* 20 penalty)
```
3343781777797791350694255572961968519437585132057650209974147122192542459108221624793330048943528237823681411832154316740173721249435700067706302064570847610741421342406380917446310820012503592770000532190167243585300911078873144513786923305473352724133578818457026824110152529235136461572588027747840738399150398304 354вç.««
```
Port of [*@HyperNeutrino*'s Jelly answer](https://codegolf.stackexchange.com/a/183255/52210).
Will try to improve here on. The number is divisible by [a bunch of numbers](https://tio.run/##hVFLbxMxEL73V1g57WrFap4em9JLJA4cUCV6gyK0NJvgkGxKslmEUH97mC3iVgnL1mg832Ps2XZT92q7@n65POy60ym878rw@yqEx/PXXXkIp7EbPUyHsgp7L1V347EMm0@fQ1fPsBCm7hiW4SYM/c@wdbF2343f2mXZvBvGftMfqwWzsCU0X9k3skLMQqpqlCPmmBSzQ9QjE6hFBYKcTVAMiTCTColmhORZJLHMzACSnKaUyOWJY0JBTEyowhhNAI2NkGRGGQBEM4js2lE8T2IRYTYhZNf3UoKMJhJ5dgJAUmDNZDMZ1JUzuDC5XFL3z@j8lIxRxFu3FDN5XyrG3pbj0KMDMM1@FJPfIKCSkgOdESWif4KmBG4ilgSME@eMbpwTgyzq6@dfXh@OVRnGUG7oOpQ3pF@8o/l41jT1MyaEsq6W7f6wql4aRDt1u3N/u65KXbf9j3O3O72M@/j2w239TzKEu1@nsd@3h/PYPvrsx91QlWbxOiyaZbsqU1n1/7VrFvfD35c8XT1dLn8A), but none of them would save any bytes unfortunately, and the larger divisors compressed contain at least 1 letter..
-18 (+2 bytes and -20 penalty) thanks to *@Grimy*, replacing the letter `J` (join) with `.««` (reduce by concatenating).
[Try it online.](https://tio.run/##FZC7bYQxDINXyQSBKFGvcRIgxVUpMtQV190IlwWy0R/aMCBIJj8K/v75@Lx9XVcEowets7qItFp6ZrZvYWsSK0mqhlt2pbntNsGGO9aTzlzYqCtnb0SYcWRLHxfeowYEJhzJQDUNHe1wHlWbWXVbhdhF9cMu2AlxhPh6Gls0WXGSzOBpket9zJYirwnswk0qfyH/TAdIrd5T69or2aG1pIOqBJiT5zWawJCeLqEcxYI@IWdMIeyhdUzsQsE7YXyL5N/z9/7@erwe1/UP)
] |
[Question]
[
Situation: You are a high school teacher, teaching your computing class how to write C programs. However, since it is just the beginning of the term, you haven't taught them about the importance of indentation and spacing. As you are marking their work, your eyes hurt so much you scream in agony, and realise that this can't go on.
Task: You have decided to write a program, in any language, that takes a valid C sourcecode as input and output it nicely formatted. You should decide what is a nicely formatted code, as it is a popularity contest. You are encouraged to implement as many features as you can, the following are some examples:
* Add proper indentation at the front of each line
* Add spaces after `,` and other operators, e.g. converting `int a[]={1,2,3};` to `int a[] = {1, 2, 3};`. Remember not to process operators within string literals though.
* Remove trailing spaces after each line
* Separating statements into several lines, e.g. the student may write `tmp=a;a=b;b=tmp;` or `int f(int n){if(n==1||n==2)return 1;else return f(n-1)+f(n-2);}` all in one line, you can separate them into different lines. Be aware of `for` loops though, they have semicolons in them but I really don't think you should split them up.
* Add a new line after defining each function
* Another other features you can come up with the help you comprehend your students' codes.
Winning criteria: This is a popularity contest, so the answer with most upvotes wins. In case of a tie, the answer with the most features implemented wins. If that is a tie again then shortest code wins.
You are suggested to include in your answer a list of features that you have implemented, as well as a sample input and output.
Edit: As requested in the comments here is a sample input, though keep in mind that it is only for reference and you are recommended to implement as many features as possible.
Input:
```
#include <stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
printf("----------------------\n;;What is your name?;;\n----------------------\n"); //Semicolon added in the string just to annoy you
/* Now we take the input: */
scanf("%s",s);
for(i=0;i<strlen(s);i++){if(s[i]>='a'&&s[i]<='z'){
s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}}printf("Your name in upper case is:\n%s\n",s);
return 0;}
```
This is how I would normally format this code: (I'm a lazy person)
```
#include <stdio.h>
#include <string.h>
int main() {
int i;
char s[99];
printf("----------------------\n;;What is your name?;;\n----------------------\n"); //Semicolon added in the string just to annoy you
/* Now we take the input: */
scanf("%s",s);
for(i=0;i<strlen(s);i++) {
if(s[i]>='a'&&s[i]<='z') {
s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}
}
printf("Your name in upper case is:\n%s\n",s);
return 0;
}
```
This is how I think is easier to read:
```
#include <stdio.h>
#include <string.h>
int main() {
int i;
char s[99];
printf("----------------------\n;;What is your name?;;\n----------------------\n"); //Semicolon added in the string just to annoy you
/* Now we take the input: */
scanf("%s", s);
for(i = 0; i < strlen(s); i++) {
if(s[i] >= 'a' && s[i] <= 'z') {
s[i] -= ('a' - 'A'); //this is same as s[i]=s[i]-'a'+'A'
}
}
printf("Your name in upper case is:\n%s\n", s);
return 0;
}
```
**Also, now that I start having answers, the answer with the highest vote count will be accepted 5 days after the last answer, i.e. if there are no more new answers within 5 days, this contest will end.**
[Answer]
Because we are talking about indentation and whitespaces we just have to write the code in a programming a language that is actually designed around **whitespace**, as that has to be easiest, right?
So the solution is:
```
```
Here it is in base64:
```
ICAgCQogICAgCgkJICAgIAkgCiAgICAKCQkgICAgCQkKICAgIAoJCSAgICAJICAKICAgIAoJCSAgICAJIAkKICAgIAoJCSAKIAogCQoKICAgCSAKICAgCQoJCQkgICAJCQkgCQkKCSAgCQoJICAJICAKICAgCQoJCQkgICAJIAkgCgkgIAkKCSAgCSAJCiAgIAkKCQkJICAgCSAgCQoJICAJCgkgIAkgCQogICAJCgkJCSAgIAkgICAgIAoJICAJCgkgIAkgCQogICAJCgkJCSAgIAkJCQkJIAkKCSAgCQoJICAJCSAKICAgCQoJCQkgICAJICAgCSAKCSAgCQoJICAJICAgIAogICAJCgkJCSAgIAkgCSAgIAoJICAJCgkgIAkgICAJCQogICAJCgkJCSAgIAkgCSAgCQoJICAJCgkgIAkgIAkgIAogICAJIAogICAJCgkJIAogCSAJCQkKICAgCQoJCQkJCiAgCgkKCiAgIAkgIAogICAJCgkJCQkKICAKCQoKICAgCSAJCgoJCgogICAJCSAKICAgCQkKICAgCQkKCQkJICAgCQoJICAJCQkgICAgCSAKICAgCQoJCSAKIAkgCQkJCiAgIAkKCQkJCQogIAoJCgogICAJICAgIAogICAJIAogICAJIAoJCSAKIAkgCQkJCiAgIAkKCQkJCQogIAoJCgogICAJICAgCQkKICAgCSAJCiAgIAkgCQoJCQkgICAJCgkgICAJCSAgICAJIAogICAJCgkJIAogCSAJCQkKICAgCQoJCQkJCiAgCgkKCiAgIAkgIAkgIAogICAJIAkKICAgCSAJCgkJCSAgIAkKCSAgCQkJICAgIAkgCiAgIAkKCQkgCiAJIAkJCQogICAJCgkJCQkKICAKCQoKICAgCQkKICAgCQoJCQkgICAJIAkgCgkgIAkKCSAgCQkgIAogICAJCgkJCSAgIAkJCQkgCQkKCSAgCQoJICAJCSAJCiAgIAkKCQkJICAgCQkJCQkgCQoJICAJCgkgIAkJCSAKICAgCQoJCQkgICAJCQkgCQkKCSAgCQoJICAJCQkJCiAgIAkKCQkJICAgCSAgIAkgCgkgIAkKCSAgCQkgCQkKICAgCQoJCQkgICAJIAkgCSAKCSAgCQoJICAJCQkgIAogICAJCgkJCSAgIAkgCQkJCQoJICAJCgkgIAkJCSAJCiAgIAkKCQkJICAgCSAJICAgCgkgIAkKCSAgCSAgCSAJCiAgIAkKCQkJICAgCSAJICAJCgkgIAkKCSAgCSAgCQkgCiAgIAkKCQkJCQogIAoJCgogICAJCSAgCiAgIAkgCiAgICAKCQkgCgkKCiAgIAkJIAkKICAgCQoJCQkJCiAgICAgCSAKICAgIAoJCSAgICAJCQogICAJCQoJCQkgICAJCgkgICAJCSAKCQoKICAgCQkJIAogICAJCQogICAJCQoJCQkgICAJCgkgIAkJCSAKIAkgCQkJCiAgIAkKCQkJCQogICAgIAkgCiAgICAKCQkgCgkKCiAgIAkJCQkKICAgCQoJCQkJCiAgICAgCSAJCgkJCQoJICAJIAkgCgoJCgogICAJICAJCQkKICAgCSAKICAgIAoJCSAKCQoKICAgCQkgCQkKICAgCQoJCQkJCiAgICAgCSAKICAgCSAKCQkgCgkKCiAgIAkJCSAgCiAgIAkgIAoJCQkgICAJIAkJCQkKCSAgCQoJICAJCQkJIAogICAJCgkJCQkKICAKCQoKICAgCQkJIAkKICAgCSAgCgkJCSAgIAkgCQkJCQoJICAJCgkgIAkJCQkJCiAgIAkKCQkJCQogIAoJCgogICAJCQkJIAogICAJCgkJCQkKICAgICAJIAogICAJCQoJCSAKCQoKICAgCQkJCQkKICAgCQoJCQkJCiAgICAgCSAKICAgCSAgCgkJIAoJCgogICAJICAJIAkKICAgCSAJCiAgIAkgCQoJCQkgICAJCgkgICAJCSAgICAJCgkJCQkKICAKCQoKICAgCSAgCQkgCiAgIAkgCQogICAJIAkKCQkJICAgCQoJICAJCQkgICAgCQoJCQkJCiAgCgkKCiAgIAkJCQogICAJIAkgCgkKICAgICAJCQoJCQkKICAgCSAgCQogCiAKCSAgCSAgIAogCiAKCQkgCSAgIAogICAJICAgICAKCQogICAgIAkgICAgIAoJCiAgICAgCQoJICAJCiAKIAkgIAkKCiAgIAkgICAKCgkKCiAgIAkgCSAJCiAgIAkKCQkJICAgCSAJIAoJICAJCgkgIAkJICAgCiAgIAkKCQkJICAgCSAgIAkgCgkgIAkKCSAgCQkgIAkKICAgCQoJCQkJCiAgCgkKCiAgIAkJICAgCiAgIAkgCiAgICAKCQkgCgkKCiAgIAkJICAJCiAgIAkgIAoJCQkgICAJIAkJCSAgCgkgIAkKCSAgCQkgCSAKICAgCSAKICAgCQoJCSAgICAJCgkJCQkKICAKCQoKICAgCQkgCSAKICAgCQoJCQkJCiAgCgkKCiAgIAkgCQkgCiAgIAkKCQkJICAgCSAJCQkJCgkgIAkKCSAgCSAgICAgCiAgIAkKCQkJCQogIAoJCgogICAJICAgICAKICAgCSAgCgkJCSAgIAkgCSAJIAoJICAJCgkgIAkgICAgCQogICAJCgkJCQkKICAKCQoKICAgCSAgICAJCiAgIAkKCQkJCQogICAgIAkgCiAgIAkKCQkgCgkKCiAgIAkgCQkJCiAgIAkKCQkJICAgCSAJIAoJICAJCgkgIAkgICAJIAogICAJCgkJCQkKICAKCQoKICAgCSAgIAkgCiAgIAkgCiAgICAKCQkgCgkKCiAgIAkKICAgCSAgCiAgIAkKCQkJCQkgICAgCQoJCgkgICAgCSAKCQkJCgkgIAkgCSAKICAgCSAKCQkJICAgCQoJICAJCgkgIAkgICAJCiAgIAkgCgkJCSAgIAkgCgkgIAkKCSAgCSAgCSAKICAgCSAKCQkJICAgCQkKCSAgCQoJICAJICAJCQogICAJIAoJCQkgICAJICAKCSAgCQoJICAJIAkgIAoKICAgCSAgIAkKCiAJIAkJCgogCiAJIAkJCgogICAJIAkgCgogCSAJIAoKIAogCSAJCQoKICAgCSAgCSAKCiAJIAkgCSAJCgogCiAJIAkJCgogICAJICAJCQoKIAkgCSAJCSAKCiAKIAkgCQkKCiAgIAkgCSAgCgogCSAJIAkJCQoKICAgCSAJCQoKIAogCQoKCgo=
```
For those who have issues printing out the code on a paper here is the annotated version (you can find a compiler for this at the end of the answer):
```
# heap structure:
# 1: read buffer
# 2: parser state
# 0: before indentation
# 1: after indentation
# 2: inside a string literal
# 3: inside a multiline comment
# 4: inside a single line comment
# 3: identation
# 4: old read buffer
# 5: parenthesis nesting amount
# -------------------
# initialize heap
# -------------------
SS 1 | SS 0 | TTS # [1] := 0
SS 2 | SS 0 | TTS # [2] := 0
SS 3 | SS 0 | TTS # [3] := 0
SS 4 | SS 0 | TTS # [4] := 0
SS 5 | SS 0 | TTS # [5] := 0
LSL 1 # goto L1
# -------------------
# sub: determine what to do in state 0
# -------------------
LSS 2 # LABEL L2
SS 1 | TTT | SS 59 | TSST | LTS 4 # if [1] == ; GOTO L4
SS 1 | TTT | SS 10 | TSST | LTS 5 # if [1] == \n GOTO L5
SS 1 | TTT | SS 9 | TSST | LTS 5 # if [1] == \t GOTO L5
SS 1 | TTT | SS 32 | TSST | LTS 5 # if [1] == ' ' GOTO L5
SS 1 | TTT | SS 125 | TSST | LTS 6 # if [1] == } GOTO L6
SS 1 | TTT | SS 34 | TSST | LTS 16 # if [1] == " GOTO L16
SS 1 | TTT | SS 40 | TSST | LTS 35 # if [1] == ( GOTO L35
SS 1 | TTT | SS 41 | TSST | LTS 36 # if [1] == ) GOTO L36
SS 2 | SS 1 | TTS # [2] := 1
LST 7 # call L7
SS 1 | TTT | TLSS # print [1]
LTL # return
LSS 4 # label L4 - ; handler
SS 1 | TTT | TLSS # print [1]
LTL # return
LSS 5 # label L5 - WS handler
LTL # return
LSS 6 # label L6 - } handler
# decrease identation by one
SS 3 | SS 3 | TTT | SS 1 | TSST | TTS # [3] := [3] - 1
SS 2 | SS 1 | TTS # [2] := 1
LST 7 # call L7
SS 1 | TTT | TLSS # print [1]
LTL # return
LSS 16 # label L16 - " handler
SS2 | SS 2 | TTS # [2] := 2
LST 7 # call L7
SS1 | TTT | TLSS # print [1]
LTL
LSS 35
SS 5 | SS 5 | TTT | SS 1 | TSSS | TTS # [5] := [5] + 1
SS 2 | SS 1 | TTS # [2] := 1
LST 7 # call L7
SS1 | TTT | TLSS # print [1]
LTL
LSS 36
SS 5 | SS 5 | TTT | SS 1 | TSST | TTS # [5] := [5] - 1
SS 2 | SS 1 | TTS # [2] := 1
LST 7 # call L7
SS1 | TTT | TLSS # print [1]
LTL
# -------------------
# sub: determine what to do in state 1
# -------------------
LSS 3 # LABEL L3
SS 1 | TTT | SS 10 | TSST | LTS 12 # if [1] == \n GOTO L12
SS 1 | TTT | SS 123 | TSST | LTS 13 # if [1] == { GOTO L13
SS 1 | TTT | SS 125 | TSST | LTS 14 # if [1] == } GOTO L14
SS 1 | TTT | SS 59 | TSST | LTS 15 # if [1] == ; GOTO L15
SS 1 | TTT | SS 34 | TSST | LTS 27 # if [1] == " GOTO L27
SS 1 | TTT | SS 42 | TSST | LTS 28 # if [1] == * GOTO L28
SS 1 | TTT | SS 47 | TSST | LTS 29 # if [1] == / GOTO L29
SS 1 | TTT | SS 40 | TSST | LTS 37 # if [1] == ( GOTO L37
SS 1 | TTT | SS 41 | TSST | LTS 38 # if [1] == ) GOTO L38
SS 1 | TTT | TLSS # print [1]
LTL # return
LSS 12 # LABEL L12 - \n handler
SS 2 | SS 0 | TTS # [2] := 0
LTL # return
LSS 13 # LABEL L13 - { handler
SS 1 | TTT | TLSS # print [1]
SS 2 | SS 0 | TTS # [2] := 0
SS 3 | SS 3 | TTT | SS 1 | TSSS | TTS # [3] := [3] + 1
LTL # return
LSS 14 # LABEL L14 - } handler
SS 3 | SS 3 | TTT | SS 1 | TSST | TTS # [3] := [3] - 1
LST 7 # call L7
SS 1 | TTT | TLSS # print [1]
SS 2 | SS 0 | TTS # [2] := 0
LTL # return
LSS 15 # LABEL L15 - ; handler
SS 1 | TTT | TLSS # print [1]
SS 5 | TTT | LTS 10 # if [5] == 0 GOTO L39
LTL
LSS 39
SS 2 | SS 0 | TTS # [2] := 0
LTL # return
LSS 27 # label L27 - " handler
SS1 | TTT | TLSS # print [1]
SS2 | SS 2 | TTS # [2] := 2
LTL
LSS 28 # label L28 - * handler - this might start a comment
SS 4 | TTT | SS 47 | TSST | LTS 30 # if [4] == / GOTO L30
SS1 | TTT | TLSS # print [1]
LTL
LSS 29 # label L29 - / handler - this might start a comment
SS 4 | TTT | SS 47 | TSST | LTS 31 # if [4] == / GOTO L31
SS1 | TTT | TLSS # print [1]
LTL
LSS 30 # label L30 - /* handler
SS1 | TTT | TLSS # print [1]
SS2 | SS 3 | TTS # [2] := 3
LTL
LSS 31 # label L31 - // handler
SS1 | TTT | TLSS # print [1]
SS2 | SS 4 | TTS # [2] := 4
LTL
LSS 37
SS 5 | SS 5 | TTT | SS 1 | TSSS | TTS # [5] := [5] + 1
SS1 | TTT | TLSS # print [1]
LTL
LSS 38
SS 5 | SS 5 | TTT | SS 1 | TSST | TTS # [5] := [5] - 1
SS1 | TTT | TLSS # print [1]
LTL
# -------------------
# sub: print identation
# -------------------
LSS 7 # label L7 - print identation
SS 10 | TLSS # print \n
SS 3 | TTT # push [3]
LSS 9 # label L9 - start loop
SLS | LTS 8 # if [3] == 0 GOTO L8
SLS | LTT 8 # if [3] < 0 GOTO L8 - for safety
SS 32 | TLSS # print ' '
SS 32 | TLSS # print ' '
SS 1 | TSST # i := i - 1
LSL 9 # GOTO L9
LSS 8 # label L8 - end loop
LTL #
# -------------------
# sub: L21 - string literal handler
# -------------------
LSS 21
SS 1 | TTT | SS 10 | TSST | LTS 24 # if [1] == \n GOTO L24
SS 1 | TTT | SS 34 | TSST | LTS 25 # if [1] == " GOTO L25
SS 1 | TTT | TLSS # print [1]
LTL
LSS 24 # \n handler - this should never happen, but let's be prepared and reset the parser
SS 2 | SS 0 | TTS # [2] := 0
LTL # return
LSS 25 # " handler - this might be escaped, so be prepared
SS 4 | TTT | SS 92 | TSST | LTS 26 # if [4] == \ GOTO L26
SS 2 | SS 1 | TTS # [2] := 1
SS 1 | TTT | TLSS # print [1]
LTL
LSS 26 # \\" handler - escaped quotes don't finish the literal
SS 1 | TTT | TLSS # print [1]
LTL
# -------------------
# sub: L22 - multiline comment handler
# -------------------
LSS 22
SS 1 | TTT | SS 47 | TSST | LTS 32 # if [1] == / GOTO L32
SS 1 | TTT | TLSS # print [1]
LTL
LSS 32
SS 4 | TTT | SS 42 | TSST | LTS 33 # if [4] == * GOTO L33
SS 1 | TTT | TLSS # print [1]
LTL
LSS 33
SS 1 | TTT | TLSS # print [1]
SS 2 | SS 1 | TTS # [2] := 1
LTL
# -------------------
# sub: L23 - singleline comment handler
# -------------------
LSS 23
SS 1 | TTT | SS 10 | TSST | LTS 34 # if [1] == \n GOTO L34
SS 1 | TTT | TLSS # print [1]
LTL
LSS 34
SS 2 | SS 0 | TTS # [2] := 0
LTL
# -------------------
# main loop
# -------------------
LSS 1 # LABEL L1
SS 4 | SS 1 | TTT | TTS # [4] := [1]
SS 1 | TLTS # [1] := read
SS 2 | TTT | LTS 10 # if [2] == 0 GOTO L10
SS 2 | TTT | SS 1 | TSST | LTS 17 # if [2] == 1 GOTO L17
SS 2 | TTT | SS 2 | TSST | LTS 18 # if [2] == 2 GOTO L18
SS 2 | TTT | SS 3 | TSST | LTS 19 # if [2] == 3 GOTO L19
SS 2 | TTT | SS 4 | TSST | LTS 20 # if [2] == 4 GOTO L20
LSS 17
LST 3 # call L3
LSL 11 # GOTO L11
LSS 10 # label L10
LST 2 # call L2
LSL 11
LSS 18
LST 21
LSL 11
LSS 19
LST 22
LSL 11
LSS 20
LST 23
LSS 11 # label L11
LSL 1 # goto L1
LLL # END
```
This is still work in progress, although hopefully it should pass most of the criterias!
Currently supported features:
* fix identation based on the `{` and `}` characters.
* add a newline after `;`
* handle indentation characters inside string literals (including the fact that string literals are not closed when encountering a `\"`)
* handle indentation characters inside single and multiline comments
* doesn't add newline characters if inside parentheses (like a `for` block)
Example input (I added some edge cases based Quincunx's comment, so you can check that it behaves properly):
```
/* Hai Worldz. This code is to prevent formatting: if(this_code_is_touched){,then+your*program_"doesn't({work)}correctl"y.} */
#include<stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
printf("----------------------\n;;What is your name?;;\n----------------------\n\""); //Semicolon added in the {;} string just to annoy you
/* Now we take the {;} input: */
scanf("%s",s);
for(i=0;i<strlen(s);i++){if(s[i]>='a'&&s[i]<='z'){
s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}}printf("Your \"name\" in upper case is:\n%s\n",s);
return 0;}
```
Example output:
```
[~/projects/indent]$ cat example.c | ./wspace indent.ws 2>/dev/null
/* Hai Worldz. This code is to prevent formatting: if(this_code_is_touched){,then+your*program_"doesn't({work)}correctl"y.} */
#include<stdio.h>
#include<string.h>
int main() {
int i;;
char s[99];;
printf("----------------------\n;;What is your name?;;\n----------------------\n\"");; //Semicolon added in the {;} string just to annoy you
/* Now we take the {;} input: */
scanf("%s",s);;
for(i=0;i<strlen(s);i++){
if(s[i]>='a'&&s[i]<='z'){
s[i]-=('a'-'A');; //this is same as s[i]=s[i]-'a'+'A'
}
}
printf("Your \"name\" in upper case is:\n%s\n",s);;
return 0;;
}
```
Note, that because whitespace doesn't support EOF checking the intepreter throws an exception, which we need to suppress. As there is no way in whitespace to check for EOF (as far as I know as this is my first whitespace program) this is something unavoidable, I hope the solution still counts.
This is the script I used to compile the annotated version into proper whitespace:
```
#!/usr/bin/env ruby
ARGF.each_line do |line|
data = line.gsub(/'.'/) { |match| match[1].ord }
data = data.gsub(/[^-LST0-9#]/,'').split('#').first
if data
data.tr!('LST',"\n \t")
data.gsub!(/[-0-9]+/){|m| "#{m.to_i<0?"\t":" "}#{m.to_i.abs.to_s(2).tr('01'," \t")}\n" }
print data
end
end
```
To run:
```
./wscompiler.rb annotated.ws > indent.ws
```
Note that this, apart from converting the `S`, `L` and `T` characters, also allow single line comments with `#`, and can automatically convert numbers and simple character literals into their whitespace representation. Feel free to use it for other whitespace projects if you want
[Answer]
**Vim** the easy way, technically using only one character: `=`
I am not a vim guru, but I do never underestimate it's power and some consider it as a programming language. For me this solution is a winner anyway.
Open the file in vim:
```
vim file.c
```
Within vim press the following keys
`g``g``=``G`
Explanation:
`g``g` goes to the top of the file
`=` is a command to fix the indentation
`G` tells it to perform the operation to the end of the file.
You can save and quit with `:``w``q`
It is possible to let `vim` run command from the command-line, so this can also be done in a one-liner, but I leave that to people who know `vim` better than I do.
---
**Vim example**
a valid input file (fibonacci.c) with bad indent.
```
/* Fibonacci Series c language */
#include<stdio.h>
int main()
{
int n, first = 0, second = 1, next, c;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
return 0;
}
```
Open in vim: `vim fibonacci.c` press `g``g``=``G`
```
/* Fibonacci Series c language */
#include<stdio.h>
int main()
{
int n, first = 0, second = 1, next, c;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
return 0;
}
```
[Answer]
Since this will be used to help the teacher understand the student's code better it is important to sanitize the input first. Pre-processor directives are unneeeded, as they just intruduce clutter, and macros can also introduce malicious code into the file. We don't want that! Also, it is completely unnecessary to retain the original comments the student wrote, as they are probably completely useless anyway.
Instead, as everyone knows good code needs good comments, apart from fixing the indentation, and the structure, why not add some highly useful comments around main points of the code to make the result even more understandable! This will definitely help the teacher in assessing the work the student has done!
So from this:
```
/* Hai Worldz. This code is to prevent formatting: if(this_code_is_touched){,then+your*program_"doesn't({work)}correctl"y.} */
#include<stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
printf("----------------------\n;;What is your name?;;\n----------------------\n\""); //Semicolon added in the {;} string just to annoy you
/* Now we take the {;} input: */
scanf("%s",s);
for(i=0;i<strlen(s);i++){if(s[i]>='a'&&s[i]<='z'){
s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}}printf("Your \"name\" in upper case is:\n%s\n",s);
return 0;}
```
Let's produce this:
```
int main() {
/* This will declare i. */
int i;
/* This will declare s[99]. */
char s[99];
/* This will call the function called printf with 1 parameters */
printf("----------------------\n;;What is your name?;;\n----------------------\n\"");
/* This will call the function called scanf with 2 parameters */
scanf("%s", s);
/* This will start a for loop, with initializator i = 0. It will loop until i < strlen(s), and will i++ at each iteration */
for (i = 0; i < strlen(s); i++) {
/* This will check, whether s[i] >= 'a' && s[i] <= 'z' is true or not. */
if (s[i] >= 'a' && s[i] <= 'z') {
s[i] -= 'a' - 'A';
}
}
/* This will call the function called printf with 2 parameters */
printf("Your \"name\" in upper case is:\n%s\n", s);
/* This will return from the function. */
return 0;
}
```
Isn't it much better, with all of the useful comments around the expressions?
---
So this is a **ruby** solution utilizing the `cast` gem, which is a C parser(Yes, I'm cheating). As this will parse the code, and re-print it from scratch it means the result will be perfectly indented and also consistent, e.g.:
* Proper indentation across the code based on block level
* Consistent whitespacing around expressions, statements, conditions, etc.
* Complete re-indenting based on the structure of the code
* etc.
And also it will contain highly useful comments about how the code works, which will super useful for both the students and the teacher!
`indent.rb`
```
#!/usr/bin/env ruby
require 'cast'
code = ''
ARGF.each_line do |line|
if line=~/\A#/
code << "// #{line.strip}\n"
else
code << line
end
end
class Comment < C::Literal
field :val
initializer :val
def to_s
"/* #{val} */"
end
end
tree = C.parse(code)
tree.preorder do |n|
break if n.kind_of?(Comment)
if n.kind_of?(C::Declaration)
dd = []
n.declarators.each do |d|
dd << "declare #{d.indirect_type ? d.indirect_type.to_s(d.name) : d.name}"
dd.last << " and set it to #{d.init}" if d.init
end
unless dd.empty?
n.insert_prev(Comment.new("This will #{dd.join(", ")}."))
end
end rescue nil
n.parent.insert_prev(Comment.new("This will call the function called #{n.expr} with #{n.args.length} parameters")) if n.kind_of?(C::Call) rescue nil
n.insert_prev(Comment.new("This will start a for loop, with initializator #{n.init}. It will loop until #{n.cond}, and will #{n.iter} at each iteration")) if n.kind_of?(C::For) rescue nil
n.insert_prev(Comment.new("This will check, whether #{n.cond} is true or not.")) if n.kind_of?(C::If) rescue nil
n.insert_prev(Comment.new("This will return from the function.")) if n.kind_of?(C::Return) rescue nil
end
puts tree
```
`Gemfile`
```
source "http://rubygems.org"
gem 'cast', '0.2.1'
```
[Answer]
# Bash, 35 characters
Input file must be named "input.c" and placed in the current working directory.
```
sh <(wget -q -O- http://x.co/3snpk)
```
Example output, having been fed the input in the original question:

It may take a few seconds to run depending on your hardware, so be patient :)
[Answer]
This is written in python and based on the GNU Coding Standards.
# Features so far:
* Indenting blocks
* Splitting lines (may split things that shouldn't be)
* GNU-style function definitions
Code:
```
import sys
file_in = sys.argv[1]
# Functions, for, if, while, and switch statements
def func_def(string):
ret = ["", "", ""]
func_name = ""
paren_level = -1
consume_id = False
for x in string[::-1]:
if x == "{":
ret[2] = "{"
elif ret[1] == "":
if x == "(":
paren_level -= 1
func_name += x
elif x == ")":
paren_level += 1
func_name += x
elif paren_level == -1 and x.isspace():
if consume_id:
ret[1] = func_name[::-1]
elif paren_level == -1:
consume_id = True
func_name += x
else:
func_name += x
else:
# Return Type
ret[0] += x
else:
ret[1] = func_name[::-1]
ret[0] = ret[0][::-1]
# Handle the case in which this is just a statement
if ret[1].split("(")[0].strip() in ["for", "if", "while", "switch"]:
ret = [ret[1], ret[2]] # Don't print an extra line
return ret
with open(file_in) as file_obj_in:
line_len = 0
buffer = ""
in_str = False
no_newline = False
indent_level = 0
tab = " " * 4
no_tab = False
brace_stack = [-1]
while True:
buffer += file_obj_in.read(1)
if buffer == "":
break
elif "\n" in buffer:
if not no_newline:
print(("" if no_tab else indent_level * tab) + buffer, end="")
buffer = ""
line_len = indent_level * 4
no_tab = False
continue
else:
buffer = ""
line_len = indent_level * 4
no_newline = False
continue
elif buffer[-1] == '"':
in_str = not in_str
elif buffer.isspace():
buffer = ""
continue
if "){" in "".join(buffer.split()) and not in_str:
for x in func_def(buffer):
print(indent_level * tab + x)
buffer = ""
line_len = indent_level * 4
no_newline = True
indent_level += 1
brace_stack[0] += 1
brace_stack.append((brace_stack[0], True))
continue
elif buffer[-1] == "}" and not in_str:
brace_stack[0] -= 1
if brace_stack[-1][1]: # If we must print newline and indent
if not buffer == "}":
print(indent_level * tab + buffer[:-1].rstrip("\n"))
indent_level -= 1
print(indent_level * tab + "}")
buffer = ""
line_len = indent_level * 4
else:
pass
brace_stack.pop()
line_len += 1
if line_len == 79 and not in_str:
print(indent_level * tab + buffer)
buffer = ""
line_len = indent_level * 4
continue
elif line_len == 78 and in_str:
print(indent_level * tab + buffer + "\\")
buffer = ""
line_len = indent_level * 4
no_tab = True
continue
```
Example input (pass a filename as argument):
```
#include <stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
printf("----------------------\n;;What is your name?;;\n----------------------\n"); //Semicolon added in the string just to annoy you
/* Now we take the input: */
scanf("%s",s);
for(i=0;i<strlen(s);i++){if(s[i]>='a'&&s[i]<='z'){
s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}}printf("Your name in upper case is:\n%s\n",s);
return 0;}
```
Example output:
```
#include <stdio.h>
#include<string.h>
int
main()
{
int i;
char s[99];
printf("----------------------\n;;What is your name?;;\n------------------\
----\n"); //Semicolon added in the string just to annoy you
/* Now we take the input: */
scanf("%s",s);
for(i=0;i<strlen(s);i++)
{
if(s[i]>='a'&&s[i]<='z')
{
s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}
}
printf("Your name in upper case is:\n%s\n",s);
return 0;
}
```
This **will** have bugs.
[Answer]
# Ruby
```
code = DATA.read
# first, we need to replace strings and comments with tilde escapes to avoid parsing them
code.gsub! '~', '~T'
lineComments = []
code.gsub!(/\/\/.*$/) { lineComments.push $&; '~L' }
multilineComments = []
code.gsub!(/\/\*.*?\*\//m) { multilineComments.push $&; '~M' }
strs = []
code.gsub!(/"(\\.|[^"])*"|'.'/) { strs.push $&; '~S' } # character literals are considered strings
# also, chop out preprocessor stuffs
preprocessor = ''
code.gsub!(/(^#.*\n)+/) { preprocessor = $&; '' }
# clean up newlines and excess whitespace
code.gsub! "\n", ' '
code.gsub! /\s+/, ' '
code.gsub!(/[;{}]/) { "#{$&}\n" }
code.gsub!(/[}]/) { "\n#{$&}" }
code.gsub! /^\s*/, ''
code.gsub! /\s+$/, ''
# fix for loops (with semicolons)
code.gsub!(/^for.*\n.*\n.*/) { $&.gsub ";\n", '; ' }
# now it's time for indenting; add indent according to {}
indentedCode = ''
code.each_line { |l|
indentedCode += (' ' * [indentedCode.count('{') - indentedCode.count('}') - (l =~ /^\}/ ? 1 : 0), 0].max) + l
}
code = indentedCode
# finally we're adding whitespace for more readability. first get a list of all operators
opsWithEq = '= + - * / % ! > < & | ^ >> <<'
opsNoEq = '++ -- && ||'
ops = opsWithEq.split + opsWithEq.split.map{|o| o + '=' } + opsNoEq.split
ops = ops.sort_by(&:length).reverse
# now whitespace-ize them
code.gsub!(/(.)(#{ops.map{|o| Regexp.escape o }.join '|'})(.)/m) { "#{$1 == ' ' ? ' ' : ($1 + ' ')}#{$2}#{$3 == ' ' ? ' ' : (' ' + $3)}" }
# special-cases: only add whitespace to the right
ops = ','.split
code.gsub!(/(#{ops.map{|o| Regexp.escape o }.join '|'})(.)/m) { "#{$1}#{$2 == ' ' ? ' ' : (' ' + $2)}" }
# special-cases: only add whitespace to the left
ops = '{'.split
code.gsub!(/(.)(#{ops.map{|o| Regexp.escape o }.join '|'})/m) { "#{$1 == ' ' ? ' ' : ($1 + ' ')}#{$2}" }
# replace the tilde escapes and preprocessor stuffs
stri = lci = mci = -1
code.gsub!(/~(.)/) {
case $1
when 'T'
'~'
when 'S'
strs[stri += 1]
when 'L'
lineComments[lci += 1] + "\n#{code[0, $~.begin(0)].split("\n").last}"
when 'M'
multilineComments[mci += 1]
end
}
code = (preprocessor + "\n" + code).gsub /^ +\n/, ''
puts code
__END__
/* Hai Worldz. This code is to prevent formatting: if(this_code_is_touched){,then+your*program_"doesn't({work)}correctl"y.} */
#include<stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
printf("----------------------\n;;What is your name?;;\n----------------------\n\""); //Semicolon added in the {;} string just to annoy you
/* Now we take the {;} input: */
scanf("%s",s);
for(i=0;i<strlen(s);i++){if(s[i]>='a'&&s[i]<='z'){
s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}}printf("Your \"name\" in upper case is:\n%s\n",s);
return 0;}
```
**Output:**
```
#include <stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
printf("----------------------\n;;What is your name?;;\n----------------------\n");
//Semicolon added in the string just to annoy you
/* Now we take the input: */ scanf("%s", s);
for(i = 0; i < strlen(s); i ++ ) {
if(s[i] >= 'a' && s[i] <= 'z') {
s[i] -= ('a' - 'A');
//this is same as s[i]=s[i]-'a'+'A'
}
}
printf("Your name in upper case is:\n%s\n", s);
return 0;
}
```
**Output** for @SztupY's edge case input:
```
#include<stdio.h>
#include<string.h>
/* Hai Worldz. This code is to prevent formatting: if(this_code_is_touched){,then+your*program_"doesn't({work)}correctl"y.} */ int main() {
int i;
char s[99];
printf("----------------------\n;;What is your name?;;\n----------------------\n\"");
//Semicolon added in the {;} string just to annoy you
/* Now we take the {;} input: */ scanf("%s", s);
for(i = 0; i < strlen(s); i ++ ) {
if(s[i] >= 'a' && s[i] <= 'z') {
s[i] -= ('a' - 'A');
//this is same as s[i]=s[i]-'a'+'A'
}
}
printf("Your \"name\" in upper case is:\n%s\n", s);
return 0;
}
```
Features so far:
* **`[x]`** Add proper indentation at the front of each line
* **`[x]`** Add spaces after `,` and other operators, e.g. converting `int a[]={1,2,3};` to `int a[] = {1, 2, 3};`. Remember not to process operators within string literals though.
* **`[x]`** Remove trailing spaces after each line
* **`[x]`** Separating statements into several lines, e.g. the student may write `tmp=a;a=b;b=tmp;` or `int f(int n){if(n==1||n==2)return 1;else return f(n-1)+f(n-2);}` all in one line, you can separate them into different lines. Be aware of `for` loops though, they have semicolons in them but I really don't think you should split them up.
* **`[ ]`** Add a new line after defining each function
* **`[ ]`** Another other features you can come up with the help you comprehend your students' codes.
[Answer]
# .Net
Open that file using Visual Studio
### Input:
```
#include<stdio.h>
#include<string.h>
int main() {
int i;
char s[99];
printf("----------------------\n;;What is your name?;;\n----------------------\n\""); //Semicolon added in the {;} string just to annoy you
/* Now we take the {;} input: */
scanf("%s",s);
for(i=0;i<strlen(s);i++){if(s[i]>='a'&&s[i]<='z'){
s[i]-=('a'-'A'); //this is same as s[i]=s[i]-'a'+'A'
}
}printf("Your \"name\" in upper case is:\n%s\n",s);
return 0;}
```
### Output:

] |
[Question]
[
# Background
[IEEE 754 Double-precision floating-point format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) is a way to represent real numbers with 64 bits. It looks like the following:

A real number `n` is converted to a `double` in the following manner:
1. The sign bit `s` is 0 if the number is positive, 1 otherwise.
2. The absolute value of `n` is represented in the form `2**y * 1.xxx`, i.e. a *power-of-2* times a *base*.
3. The exponent `e` is `y` (the power of 2) plus 1023.
4. The fraction `f` is the `xxx` part (fractional part of the base), taking the most significant 52 bits.
Conversely, a bit pattern (defined by sign `s`, exponent `e` and fraction `f`, each an integer) represents the number:
```
(s ? -1 : 1) * 2 ** (e - 1023) * (1 + f / (2 ** 52))
```
# Challenge
Given a real number `n`, output its 52-bit fraction part of the `double` representation of `n` as an integer.
# Test Cases
```
0.0 => 0
16.0 => 0
0.0625 => 0
1.2 => 900719925474099 (hex 3333333333333)
3.1 => 2476979795053773 (hex 8cccccccccccd)
3.5 => 3377699720527872 (hex c000000000000)
10.0 => 1125899906842624 (hex 4000000000000)
1234567.0 => 798825262350336 (hex 2d68700000000)
1e-256 => 2258570371166019 (hex 8062864ac6f43)
1e+256 => 1495187628212028 (hex 54fdd7f73bf3c)
-0.0 => 0
-16.0 => 0
-0.0625 => 0
-1.2 => 900719925474099 (hex 3333333333333)
-3.1 => 2476979795053773 (hex 8cccccccccccd)
-3.5 => 3377699720527872 (hex c000000000000)
-10.0 => 1125899906842624 (hex 4000000000000)
-1234567.0 => 798825262350336 (hex 2d68700000000)
-1e-256 => 2258570371166019 (hex 8062864ac6f43)
-1e+256 => 1495187628212028 (hex 54fdd7f73bf3c)
```
You can check other numbers using [this C reference](https://tio.run/##jY7RaoMwFIbv8xQ/HYJSFbXVDdPuOQpdGdYkWyCLRSMoxWd3ifWmu9rN@U8@yHf@Ovqq63l@kbpWPeM4dIZJbeLvd/LMGoeIGW@ccYFey0bjTgDW9FfFwajdO9P2tVkw0FtNsf80EGWe0WfEyzT9g7pyIRMlE06UkNVbnS844p7ESYg0zkLs4tSN3D4fMNvt8@J1WXmU5YVLG1ZEfiqp/WDpI5oWvr0FaXUJtXHAG8V2K4O17wmDuxSzY3WWl@lR79baP8LfeErAU4rBS9KdUsOH3oQYYuaGWEZAV8u4WqL/akanGZ1mXDUTmeb5Fw) which uses bit fields and a union.
Note that the expected answer is the same for `+n` and `-n` for any number `n`.
# Input and Output
Standard rules apply.
Accepted input format:
* A floating-point number, at least having `double` precision internally
* A string representation of the number in decimal (you don't need to support scientific notation, since you can use `1000...00` or `0.0000...01` as input)
For output, a rounding error at the least significant bit is tolerable.
# Winning Condition
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest bytes in each language wins.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~42~~ 30 bytes
```
long f(long*p){p=*p&~0UL>>12;}
```
Takes [a pointer to a *double*](https://codegolf.meta.stackexchange.com/a/11884/12012 "Input and output of a single value may be represented as a singleton list") as argument and returns a *long*.
Requires 64-bit longs and gcc (undefined behavior).
*Thanks to @nwellnhof for -2 bytes!*
[Try it online!](https://tio.run/##TZDBboMwDIbPyVNY1VolQBiBQScxeIJdd1p72CjQSIygDqRqFXt1ZkjYdslv/44/xylEXRTT1Oi2horN4nT81mVOt/sOXp7zXIbpOKm2h4831TJOb5Sc9PDelKD06xEyStAhgR94KNIPZ4l8aSRezLUYRg9xsrdJKcI4MZFrI2EvCosRliMsSMjfC/9R4o8lDIxSMqZ4VPoCbH67ggyCFOUJPtVXqSumNIf7NXEww6rrcrPNumDbDT124qLqmKK//JIeemNXbLdU@DyKdBccVLHNVjz6@xqyHLYyaQZg5/KK4V0go@bKD@3GM1zPgrCbjHScfgA "C (gcc) – Try It Online")
[Answer]
## Haskell, ~~27~~ 31 bytes
```
(`mod`2^52).abs.fst.decodeFloat
```
`decodeFloat` returns the significand and the exponent, but for some reason the former is [53 bit](https://tio.run/##y0gszk7Nyfn/PzcxM0/BVqGgKDOvREFFIS0nP7HEJTM9s6RYwUDP4P//f8lpOYnpxf91kwsKAA "Haskell – Try It Online") in Haskell, so we have to cut one bit off.
[Try it online!](https://tio.run/##ZUxJDoIwFN17ir@EBBooFlds3XkCJwr9DLFTaI23txaNceHmzXkTdzeUMgwNnELSKiNaemE0JbxzZHCeCOyNwL003AfFZw0NCLMBUNwerpDYZdaeDCnou@pwcX8N0Thyj79BXDwmXPAbxMNjQYoMSkIzqEi5Aov2E9Jqy@rdW2JOWb1ypDOEZz9IPrqQ99a@AA "Haskell – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
IZ%52W\0YA
```
[Try it online!](https://tio.run/##y00syfn/3zNK1dQoPMYg0vH/f8NUXSNTMwA "MATL – Try It Online")
### Explanation
```
% Implicit input
IZ% % Cast to uint64 without changing underlying byte representation
52W % Push 2^52
\ % Modulus
0YA % Convert to decimal. Gives a string. This is needed to avoid
% the number being displayed in scientific notation
% Implicit display
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~54~~ 50 bytes
```
f=lambda x:int(x.hex().split('.')[1].split('p')[0],16)
```
[Try it online!](https://tio.run/##NY3NDsIgEITvPsXeChE3/AgmTXyShkONJSWplFQO69MjrXEOM/PNZfKnzGsytYb7Mr4ezxGoj6kwwnkixvGdl1hYhx0flP9TbiS9UI7XsG5AEBMMEqUAhVqAQbWbbfgbtbladzvqdNHW7Xlu6fsTNOXteBQQGHFevw "Python 3 – Try It Online")
With Kirill's suggestion:
```
f=lambda x:int(x.hex()[4+(x<0):].split('p')[0],16)
```
[Try it online!](https://tio.run/##HY07DsMgGIP3nuLfAgpBPAKVUHsSxJCqQUFKCUoZ6OkpwcNnWx6cfnk7oqzVP/fl83ovUEyIGRW6rQVhO4@oPBg2jn7THjIa0oAtc4RrXP1xQoEQwTLKCEycCgIdkvILqtU@cSFnpe89rpNQ@vKxuTM3aEpn/yTgUcG4/gE "Python 3 – Try It Online")
[Answer]
# x86\_64 machine language for Linux, 14 bytes
```
0: 66 48 0f 7e c0 movq %xmm0,%rax
5: 48 c1 e0 0c shl $0xc,%rax
9: 48 c1 e8 0c shr $0xc,%rax
d: c3 retq
```
[Try it online!](https://tio.run/##TU/RboIwFH2Gr7ghM2nVMhBFE8ZezPYT1gfWFWzGqBFIGhd/fexiq/Ol95xzzz23V7BKiGEQumk7EIfiBOVunwfcpCk3yw030Ts36zdutpHlIuZGIhYPdHOl2yTIBtV08F2ohlD/x/c@df9RS1B6t4fc91DxojCaY4nDxViSMLZldRVvzUWyXKVrRyRbrFKLZg4xZ2Quhrkc5oJYfDc8RrH/LGbDfN@7ZPiU@gRk/LuCHKIMywu06ix1SZSm8HwjU2TYnc2oveZ2YHPsO5zEQ9U@Q73WTQW676xMyMjJlBLrp7Sk5Oql43LveMLVJQkmbBOuK8hfYRKndQ/kIA3CpyhOakN5E8ztprmLxmnv4l@GX1HWRdUO7CyNFG1XiK8/ "C (gcc) – Try It Online")
EDIT: Thanks to @Bubbler
[Answer]
## JavaScript (ES7), ~~52~~ 50 bytes
```
f=n=>n?n<0?f(-n):n<1?f(n*2):n<2?--n*2**52:f(n/2):0
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>0
```
Not using `Math.floor(Math.log2(n))` because it's not guaranteed to be accurate. Edit: Saved 2 bytes thanks to @DanielIndie.
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 28 bytes
```
$_=-1>>12&unpack Q,pack d,$_
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lbX0M7O0EitNK8gMTlbIVAHTKXoqMT//2@gZ8BlqGfEZaxnCMSmXIZgASNjE1MzcxArVdfI1AxIAcl/@QUlmfl5xf91C3IA "Perl 5 – Try It Online")
The 1e-256 and 1e256 test cases are off but that's because Perl 5 converts huge or tiny floating point strings inexactly.
[Answer]
# [C (gcc)](https://gcc.gnu.org/) macro, 49 bytes
```
-DF(x)=x?ldexp(frexp(fabs(x),(int[1]){})-.5,53):0
```
[Try it online!](https://tio.run/##lVDLboMwEDzjr1ilquQltjFQqNQk7aXKT1AOBNupJQoRDwkV8eulhqgf0MvO7OxodrUlv5blEvgLfz/TEU/jW6X0eKOm3Wpx6ZzKqK37LMxxmpGLhCUxvsjFD8iDrctqUBqOXa9sIz5fiXPCV2FrijARTzXDpdKgshxOMIEUkkEoIgaxCNeSuPYuRvFTkj5vVPMoSVd0APOBeKZpYT0BrEuRBwdH6Oy3bgxVCMEf9xW62X6PxPNurfMbunsMUyEN3OGj3jE4U5XZHFfCN4ZuQ6v7oa1dNpmXn9JUxbX7/0d@AQ "C (gcc) – Try It Online")
Returns a `double` but assuming IEEE precision, it won't have a fractional part. Also handles negative numbers now.
[Answer]
# [T-SQL](https://www.microsoft.com/sql-server), 80 bytes
```
SELECT CAST(CAST(n AS BINARY(8))AS BIGINT)&CAST(4503599627370495AS BIGINT)FROM t
```
The input is taken from the column `n` of a table named `t`:
```
CREATE TABLE t (n FLOAT)
INSERT INTO t VALUES (0.0),(1.2),(3.1),(3.5),(10.0),(1234567.0),(1e-256),(1e+256)
```
[SQLFiddle](http://sqlfiddle.com/#!18/34a183/1)
[Answer]
## [Hoon](https://github.com/urbit/urbit), 25 bytes
```
|*(* (mod +< (pow 2 52)))
```
Create a generic function that returns the input mod `2^52`.
Calling it:
```
> %. .~1e256
|*(* (mod +< (pow 2 52)))
1.495.187.628.212.028
```
[Answer]
# JavaScript (ES7), ~~98~~ 76 bytes
*Saved 22 (!) bytes thanks to @Neil*
More verbose than [Neil's answer](https://codegolf.stackexchange.com/a/160944/58563), but I wanted to give it a try with [typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays).
```
(n,[l,h]=new Uint32Array(new Float64Array([n]).buffer))=>(h&-1>>>12)*2**32+l
```
[Try it online!](https://tio.run/##hdHLTsMwEAXQPV/hFbL7SMfjx9iLRGLDDyBWVRchiduiNEFpeH19CAREBWlzZ@VZHI2uH9OX9Jg1@6d2WdV50YW449ViXS52m7gqXtn9vmoV3jRN@s4/37dlnbZWD4t1tRHRw3MIRSNEnPDd9VImSSJRzHA2Uzgvu6yujnVZRGW95QcWs8AhAvYVsWCHqK3v2mZfbbm0QrDVisUJ@xO4@o/ICKcQD0DSezSaNHjP@K54Y@o0YgRWkZyAUZP11I8Bo4jUALvsN/k4bCZg1WvWe0IwSI5wgDM4yRgsfwo9C0uJxnnvwTqNFvUA60kYlTaWIjjfMXnn0PSmMqCUHWDMraOLcLFEYy923B9sCBRJaS3I789zYNFZnWY2aDUOzydgqb2RjnoHJQK6ATY65DkFUg9BZaL7AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 38 bytes
```
{0=⍵:0⋄(2*52)ׯ1+×∘2⍣(1≤⊣)÷∘2⍣(1>⊣)|⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqA9tHvVutDB51t2gYaZkaaR6efmi9ofbh6Y86Zhg96l2sYfioc8mjrsWah7fDRexA/BqgtlqgGQoGegYKEMCVpmCoZ4TgGOsZInNMkZTBNYE4RsYmpmbmQBEQx/XQeiNTM5iUK5DNBWQcWo@sA@hCmD1gHtwiKM8UWSVMI4QHswvCg1sG5YI5AA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~19~~ 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
üâïc-Hò~÷]ó┬ó♪
```
[Run and debug it](https://staxlang.xyz/#p=81838b632d48957ef65da2c2a20d&i=0.0%0A1.2%0A-1.2%0A3.1%0A3.5%0A10.0%0A1234567.0%0A0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001%0A10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0&a=1&m=2)
Unpacked, ungolfed, and commented, the code looks like this.
```
|a absolute value
{HcDw double until there's no fractional part
@ convert to integer type
:B convert to binary digits
D52( drop the first digit, then pad to 52
:b convert back number
```
[Run this one](https://staxlang.xyz/#c=%7Ca+++%09absolute+value%0A%7BHcDw%09double+until+there%27s+no+fractional+part%0A%40++++%09convert+to+integer+type%0A%3AB+++%09convert+to+binary+digits%0AD52%28+%09drop+the+first+digit,+then+pad+to+52%0A%3Ab+++%09convert+back+number&i=0.0%0A1.2%0A-1.2%0A3.1%0A3.5%0A10.0%0A1234567.0%0A0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001%0A10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0&a=1&m=2)
[Answer]
# [Rust](https://www.rust-lang.org/en-US/), 21 bytes
```
|p|p.to_bits()&!0>>12
```
Pretty much copied C solution. Takes an `f64` argument.
[Try it online!](https://tio.run/##TY/RioMwEEXf/YrbPkjCOmK0uuBSH/cnllJaSFihTUVTKNh8uxvHrXQecifDvYeZ/j64yVhcT60VEmOEUBftYGrE31aYaidBDY7YI56e3bNL3e14bt0gZLzJmkbl09casvfrWfdD8P7wbK4szRKoNE9QpGp@yvBdhnmxK6tPbjXlZTXrByuxgThGnCMOEidXNr0h6MWgfwi7Dsty5tYjDtuhtay85bhyur617mI3YjvWSmmPfYPQVR7iVz8wqjpTxcPLbTKfmMCIIFIubB/5aPoD "Rust – Try It Online")
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 42 bytes
Assumes floats are double by default and cells are 8 bytes in length (as is the case on my computer and TIO)
```
: f f, here float - @ $fffffffffffff and ;
```
[Try it online!](https://tio.run/##XY0xDoMwEAR7XrEFJWthE4OUNPkKIr5QRCBZ/N@Bhju45nakXY2seZv5leOV8oRAGswpJ8hvHTcQb9RiD@Pywau0ewMOU668C2funDc5asfUQ/eI/aCcGGKvpHBwpUNaEa2JVkVvJzcZrzaeuvIH "Forth (gforth) – Try It Online")
## Explanation
```
f, \ take the top of the floating point stack and store it in memory
here float - \ subtract the size of a float from the top of the dictionary
@ \ grab the value at the address calculated above and stick it on the stack
$fffffffffffff \ place the bitmask (equivalent to 52 1's in binary) on the stack
and \ apply the bitmask to discard the first 12 bits
```
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/) 4-byte cell answer, 40 bytes
Some older forth installations default to 4-byte cells, instead
```
: f f, here float - 2@ swap $FFFFF and ;
```
## Explanation
```
f, \ take the top of the floating point stack and store it in memory
here float - \ subtract the size of a float from the top of the dictionary
2@ \ grab the value at the address above and put it in the top two stack cells
swap \ swap the top two cells put the number in double-cell order
$fffff \ place the bitmask (equivalent to 20 1's in binary) on the stack
and \ apply the bitmask to discard the first 12 bits of the higher-order cell
```
[Answer]
# [Go](https://go.dev), 68 bytes
```
import."math"
func d(n float64)uint64{return Float64bits(n)<<12>>12}
```
Can't do the `&-1` trick because Go disallows overflows.
[Attempt This Online!](https://ato.pxeger.com/run?1=lZRNbsIwEEY33ZBTWFkR0YnscfxXAYuq6rpXCJDQqBBQSFaIk3SDKvUSvUl7mppEqIoJKFUWlkfzvrGtp7x_LDfHr208f4uXCVnHWe552Xq7KUrip-vS_6zKFPT3U1ML_XVcvvpeWuVzshjmJF1t4lJGQZXldtkXSVkVOXluqrOs3A3zYDxmOJ0yPDRZP3fLGj_NGgZk7w0Wm2q2Sh7jXUIeJmThDezg8KWwkat8SEN6T_46TvuATCaEBu0-Jp3GU6Gz0yZIFG6oLXXnhtiODbHuM5QqZgyKSEXUGIfiIWtRdl9TGClplP0EFVwpfoEJB2sOxW2vNEYhFai0QveM7iOx8ysxhkIbY6jUEUqMXBB5JKRy6XO1jlBGaxQW5oJyLt2EBFDINl6Xmuva6UJRrhiTkjL3lVgyuoRHZ5hFRjCtJGpkSFE7MLiXhmtqwIUbcFUO6LADbugBrh_QTxBwDYGeioDrCPSUBC4sgb6aQLcn8B9RoMMU6K8KdLgCN2U5eM3_5nhs1l8)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->n{[n].pack(?D).unpack(?Q)[0]&~-2**52}
```
[Try it online!](https://tio.run/##jZFBasMwEEX3PoWhUOKkMqMZjUZaJN30Al0bLxI7JlAIoSTQkqRXd50qIDvd6GujxX@Ir/d52nz33bJXq/252tflYd18zF7fivK0D9f3ooL6@UfhfM547asMSsjveXlarvKHQKZLnBY8gGjvkY0Y8D6f7bZfOY1TZFTqCYRGrJfhMDCJUIBcE9PeIJ5ANDSt94LAKE4wQA2MUmQ6DviDtEZ23nuwzqBFEyDzACEZtnIjwybxziEPfWIgsgHC1joZQVuFbEebhodYgERra0HfP8KBRWfNurGdoRu0mEDaeNZOhg5qBHQBYtO1rXRCm46aIsvUw6h/UlS0ki5FRSvpUlS0ki5FRSvpUlS0ki5FRSvpUlS0ki6lLrfrZne@HC@HvKuO9bX/BQ "Ruby – Try It Online")
[Answer]
# [Java 8 or later](https://en.wikipedia.org/wiki/Java_(programming_language)), 38 bytes
```
x->Double.doubleToLongBits(x)&-1L>>>12
```
[Try it online!](https://tio.run/##bVLLboMwELznK1ZRU4GKrRgCkZrCoap6Sk/Jre3B5VWnxEbBRERVvp2agNKA2YN3NTueHa29o0eKRB7zXfRThxktCnijjMPvBFTk5VfGQigklSodBYtgr7rGRh4YT98/gR7SwuzITeyUHC4ly3BS8lAywfFrVzy9CKUWW7AWPA0gAb@uUNCCOLqkrWh6z0wWRmXeI7IOgoDY9eoq39LUXCbAvxnbxBzPrR5AsN0HHEyGgDu4oovYzsL1lhocI9v1htiDhiFNEGm2kOYLacYQGREat4bGvKHW3OQKnlf/dSIOYLSrBcbzUsKjWrA52G@mngZEKZu@DwmmeZ6djAvfXPWYm1Mh4z1WXJyrfyITYzpDZIGXKfgBzIgXgfEdVzCz7@bEqcwPPrXawVY34EbwPGnPc/0H "Java (OpenJDK 8) – Try It Online")
[Answer]
# Aarch64 machine language for Linux, 12 bytes
```
0: 9e660000 fmov x0, d0
4: 9240cc00 and x0, x0, #0xfffffffffffff
8: d65f03c0 ret
```
To try this out, compile and run the following C program on any Aarch64 Linux machine or (Aarch64) Android device running Termux
```
#include<stdio.h>
const char f[]="\0\0f\x9e\0\xcc@\x92\xc0\3_\xd6";
int main(){
double io[] = { 0.0,
1.2,
3.1,
3.5,
10.0,
1234567.0,
1e-256,
1e+256,
-0.0,
-1.2,
-3.1,
-3.5,
-10.0,
-1234567.0,
-1e-256,
-1e+256 };
for (int i = 0; i < sizeof io / sizeof*io; i++) {
double input = io[i];
long output = ((long(*)(double))f)(io[i]);
printf("%-8.7g => %16lu (hex %1$013lx)\n", input, output);
}
}
```
[Answer]
# [Julia 0.4](http://julialang.org/), 30 bytes
```
x->reinterpret(UInt,x)<<12>>12
```
[Try it online!](https://tio.run/##yyrNyUz8n2ablJqemfe/QteuKDUzryS1qKAotUQj1DOvRKdC08bG0MjOztDof2peCle6RoWmgq1CQRFQWU6ehpJKhYKKRhpQUBNIZ6RWQNiaSppAlYZ6RiDKWM8UzDPQMwDTqbpGpmYQFpShC1WpC1L6HwA "Julia 0.4 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ä[ÐïQ#·}b0₃׫À52£C
```
Port of [*@recursive*'s Stax answer](https://codegolf.stackexchange.com/a/160967/52210).
[Try it online](https://tio.run/##ASoA1f9vc2FiaWX//8OEW8OQw69RI8K3fWIw4oKDw5fCq8OANTLCo0P//y0xLjI) or [verify all test cases](https://tio.run/##yy9OTMpM/e@irnFo9aHVZZV6YS72SgqP2iYpKNn/P9wSfXjC4fWByoe21yYZPGpqPjz90OrDDaZGhxY7/9f5H22gZ6CjYKhnpKNgrGcIIkyBXIigkbGJqZk5iKn0qKlR49AGJQgLyIgFAA).
Alternatively:
```
_+Ä[DbD53∍©›#·}®¦C
```
[Try it online](https://tio.run/##ASkA1v9vc2FiaWX//18rw4RbRGJENTPiiI3CqeKAuiPCt33CrsKmQ///LTEuMg) or [verify all test cases](https://tio.run/##yy9OTMpM/e@irnFo9aHVZZV6YS72SgqP2iYpKNm7/I/XPtwS7ZLkYmr8qKP30MpHDbuUD22vPbTu0DLn/zr/ow30DHQUDPWMdBSM9QxBhCmQCxE0MjYxNTMHMZUeNTVqHNqgBGEBGbEA).
Alternatively (by porting [*@LucaCiti*'s Python answer](https://codegolf.stackexchange.com/a/160941/52210) in [the legacy version of 05AB1E](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b)):
```
Ä".hex()"«.E„.p¡Hà
```
[Try it online](https://tio.run/##MzBNTDJM/f//cIuSXkZqhYam0qHVeq6PGubpFRxa6HF4wf//uoZ6RgA) or [verify all test cases](https://tio.run/##MzBNTDJM/e@icWh1WaWLvZLCo7ZJCkr2/w@3KOllpFZoaCodWq3n@qhhnl7BoYUehxf81/kfbaBnoKNgqGeko2CsZwgiTIFciKCRsYmpmTmIqWSYqmtkaqYEZmmDWLEA).
**Explanation:**
```
Ä # Get the absolute value of the (implicit) input-float
[ # Start an infinite loop:
Ð # Triplicate the current value
ï # Cast the top to an integer
Q # Check if the top two values are the same†
# # If they are: stop the infinite loop
· # Double the current float
}b # After the loop: convert the integer to a binary string
0₃׫ # Append 95 trailing 0s
# (95 is the smallest single-byte constant >= 52)
À # Rotate it once towards the left, so the leading 1 becomes trailing
52£ # Only keep the first 52 bits
C # Convert it from a binary string to a base-10 integer
# (which is output implicitly as result)
```
```
_ # Check if the (implicit) input-float is 0
+ # Add it to the (implicit) input-float so it becomes 1
Ä # Convert it to its absolute value
[ # Start an infinite loop:
D # Duplicate the current value
b # Convert its integer part to a binary string
D # Duplicate this string
53∍ # Extend/shorten it to size 53
© # Store this result in variable `®`
› # Check if it's larger than the binary string
# # If it is: stop the infinite loop
· # Double the current float
}® # After the loop: push binary string `®` which we've saved
¦ # Remove its leading 1
C # Convert it from a binary string to a base-10 integer
# (which is output implicitly as result)
```
```
Ä # Get the absolute value of the (implicit) input-float††
".hex()"« # Append string ".hex()"
.E # Evaluate and execute it as Python code
„.p¡ # Split it on both the "." and "p"
H # Convert each inner part from a hexadecimal string to an integer
à # Push the maximum of this list
# (which is output implicitly as result)
```
† If 05AB1E didn't had [this bug](https://github.com/Adriandmen/05AB1E/issues/174) and the input format is also guaranteed to not contain any additional trailing `0` besides `#.0` (e.g. `12.0` is a valid input, but `12` or `12.10` aren't), the `DïQ` could have been `¤_` - which checks if the float contains a trailing zero.
†† Unlike the Python answer, `.hex()` doesn't work on negative values in the legacy version of 05AB1E, unless I add parenthesis around it (e.g. `-1.0.hex()` doesn't work, but `1.0.hex()` and `(-1.0).hex()` both do: [try it online](https://tio.run/##MzBNTDJM/f9fyVDPQC8jtUJDU0nPVUcBDJTK84uyi5ViuJQ0dIHSmijyCEldTK1KKfmpxXnqJQogRUox//8DAA)), which is why the `Ä` was necessary in the third program.
] |
[Question]
[
It is Friday and I am tired, so let's do a quick one! Take no input, however you should output all thirteen different numbered cards in a standard deck of cards. You should output 2 through Ace (Suit agnostic).
Each card has a top that is denoted with a space and ten `_` and another space.
The second row from the top is denoted with a `/` and ten spaces and a `\`
The third row is the same as all the middle-ish rows excepts the character(s) denoting the card value appear two spaces to right (if at the top) or two space to the left (if at the bottom) of the edge.
Each middle-ish row is a simple `|` and ten spaces and one more `|`
Finally the last line is a `\` and ten `_` and finally a `/`
If the value is multi-digit the overall width by height of the card should not change. (i.e. the 10 will not make the card's sides wider)
King Example:
```
__________
/ \
| K |
| |
| |
| |
| |
| |
| K |
\__________/
```
9 Example
```
__________
/ \
| 9 |
| |
| |
| |
| |
| |
| 9 |
\__________/
```
10 Example
```
__________
/ \
| 10 |
| |
| |
| |
| |
| |
| 10 |
\__________/
```
Output them in order from least to greatest (Aces are high!).
This is code-golf so the shortest code wins.
Have fun and have a fun weekend!
[Answer]
## PowerShell v2+, ~~120~~ ~~116~~ ~~114~~ 108 bytes
```
2..10+[char[]]'JQKA'|%{$z=' '*(8-!($_-10));$x='_'*10;$y=' '*10;" $x
/$y\
| $_$z|";,"|$y|"*5;"|$z$_ |
\$x/"}
```
Constructs a range `2..10` and does array concatenation with `char`-array `JQKA`. Feeds that into a loop `|%{...}`. Each iteration, we set `$z` equal to an appropriate number of spaces (based on whether we're at card `10` or not), set `$x` to `10` underscores, and set `$y` to `10` spaces.
Then, we begin our placements. We're going to leverage the default `Write-Output` to insert a newline between pipeline elements, so we just need to get the stuff on the pipeline. Note that in most places, we're using a literal newline rather than closing and reopening our strings to save a couple bytes.
The first is just `$x` with two spaces, then `$y` with two slashes, then the `| $_$z|"` the pipe, a space, the appropriate number of spaces, and another pipe. This forms the top of the cards up to and including the value line.
We have to semicolon here, since the next uses an array. The `,"|$y|"*5` constructs a string-array, with the comma-operator, of the pipe with spaces - on output, each element of this array gets a newline for free.
Then, the `"|$z$_ |` for the bottom value marking, and finally `$x` with slashes for the bottom of the card.
### Output Snippet
```
PS C:\Tools\Scripts\golfing> 2..10+[char[]]'JQKA'|%{$z=' '*(8,7)[$_-eq10];" $(($x='_'*10)) ";"/$(($y=' '*10))\";"| $_$z|";,"|$y|"*5;"|$z$_ |";"\$x/"}
__________
/ \
| 2 |
| |
| |
| |
| |
| |
| 2 |
\__________/
__________
/ \
| 3 |
| |
| |
| |
| |
| |
| 3 |
\__________/
__________
/ \
| 4 |
...
```
[Answer]
# Python, ~~161~~ ~~160~~ ~~156~~ 149 bytes
*One byte saved by Shebang*
This could use some work but here it is:
```
o=" ";v="_"*10
for x in map(str,range(2,11)+list("JKQA")):print o+v+"\n/",o*9+"\\\n|",x.ljust(8),"|"+("\n|"+o*10+"|")*5+"\n|",o*6+x.ljust(3)+"|\n\\"+v+"/"
```
## Explanation
We make a list of all the ranks in order using `map(str,range(2,11)`. Then we loop through each of the ranks and make a card.
```
print o+"_"*10+"\n/",o*9+"\\\n|",x.ljust(8),"|"+("\n|"+o*10+"|")*5+"\n|",o*6+x.ljust(3)+"|\n\\"+"_"*10+"/"
```
We make the top of the card:
```
o+v+"\n"
```
Then the rank goes on the left:
```
"/",o*9+"\\\n|",x.ljust(8),"|"
```
We use `.ljust` because `10` is two long and all the other ones are one wide.
Then we print the 5 rows in the middle:
```
"|"+("\n|"+o*10+"|")*5+"\n|"
```
and the bottom rank:
```
"\n|",o*6+x.ljust(3)+"|\n"
```
Finally we print the bottom of the card:
```
"\\"+v+"/"
```
[Answer]
## JavaScript (ES6), 151 bytes
```
f=
_=>`2345678910JQKA`.replace(/.0?/g,s=>` __________
/ \\
| `+(s+=` `+s).slice(0,4)+` |
| `.repeat(6)+s.slice(-4)+` |
\\__________/
`)
;
document.write('<pre>'+f());
```
[Answer]
# Perl, ~~128~~ ~~117~~ 111 bytes
```
map{printf$"."_"x10 ."
/".$"x10 .'\
| %-9s|
'.("|".$"x10 ."|
")x5 ."|%9s |
\\"."_"x10 ."/
",$_,$_}2..10,J,Q,K,A
```
The 6 literal newlines save 1 byte each. **This cannot be run directly from the command line because of the single quotes in lines 2 and 4** in order to save 1 byte by not having to escape a backslash.
Edit: I put Ace at the beginning, but it's supposed to be at the end. It doesn't change the byte count.
Edit 2: -11 bytes: Got rid of some unnecessary statements and added another literal newline. Everything is now output via a single printf.
Edit 3: -5 bytes thanks to @Ton Hospel. But for some reason, I'm getting 111 bytes instead of 112 at home when compared to at work, so I'm going with the byte count my home computer is giving me.
[Answer]
# PHP, 233 Bytes
```
foreach([2,3,4,5,6,7,8,9,10,J,Q,K,A]as$k){for($c="",$i=0;$i<10;$i++)$c.=str_pad($i?$i>1&$i<9?"|":($i<2?"/":"\\"):" ",11,$i%9?" ":_).($i?$i>1&$i<9?"|":($i<2?"\\":"/"):" ")."\n";$c[113]=$c[28]=$k;$k>9&&$c[29]=$c[113]=0&$c[112]=1;echo$c;}
```
[Answer]
# ///, ~~182~~ 180 bytes
```
/+/_____//*/# |
&//&/@@@@@|# //%/ |
\\\\++\\\/
//$/ ++
\\\/!\\\\
| //#/ //!/# //@/|!|
/$2*2%$3*3%$4*4%$5*5%$6*6%$7*7%$8*8%$9*9%$10#|
@@@@@|#10 |
\\++\/
$J*J%$K*K%$Q*Q%$A*A%
```
[Try it online!](http://slashes.tryitonline.net/#code=LysvX19fX18vLyovIyB8CiYvLyYvQEBAQEB8IyAvLyUvIHwKXFxcXCsrXFxcLwovLyQvICsrClxcXC8hXFxcXAp8IC8vIy8gICAgICAgLy8hLyMgICAvL0AvfCF8Ci8kMioyJSQzKjMlJDQqNCUkNSo1JSQ2KjYlJDcqNyUkOCo4JSQ5KjklJDEwI3wKQEBAQEB8IzEwIHwKXFwrK1wvCiRKKkolJEsqSyUkUSpRJSRBKkEl&input=)
*-2 bytes thanks to m-chrzan*
[Answer]
## Python 3.5, 110 bytes
```
u='_'*10
for c in[*range(2,11),*'JQKA']:print(' %s\n/%%11s\n'%u%'\\'+'| %-6s%2s |\n'*7%(c,*' '*12,c)+'\%s/'%u)
```
Prints
* The top two lines `' %s\n/%%11s\n'%u%'\\'` where `u` is `'_'*10`
* The middle 7 lines `'| %-2s %2s |\n'`, each of which has two string formatting slots. The first and last are filled with the card value, and the rest with spaces for no effect
* The bottom line '\%s/'%u
Python 3.5's new unpacking features are used in two places. The list of labels `[*range(2,11),*'JQKA']` unpacks the numbers and letters into one list. And, the tuple `(c,*' '*12,c)` unpacks twelve entries of spaces into the center.
[Answer]
# Scala, 161 bytes
```
val a=" "*7
val u="_"*10
((2 to 10)++"JQKA")map(_+"")map{x=>val p=" "*(2-x.size)
s" $u \n/$a \\\n| $x$p$a|\n" + s"|$a |\n" * 5 + s"|$a$p$x |\n\\$u/\n"}
```
[Answer]
## Batch, 236 bytes
```
@echo off
for %%v in (2 3 4 5 6 7 8 9 10 J Q K A)do call:v %%v
exit/b
:v
set s=%1 %1
echo __________
echo / \
echo ^| %s:~0,8% ^|
for /l %%l in (1,1,5)do echo ^| ^|
echo ^| %s:~-8% ^|
echo \__________/
```
I tried golfing this in three different ways but ended up with the same byte count each time...
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~71~~ ~~70~~ ~~68~~ ~~66~~ ~~65~~ 64 bytes
Uses [CP-1252](http://www.cp1252.com) encoding.
```
TL¦"JQKA"S«vð'_TשððT×…/ÿ\9yg-ð×y"| ÿÿ|"ÂðT×…|ÿ|5×sT‡®…\ÿ/JTä»,
```
Slightly modified link as `…` doesn't work with `ÿ` on TIO atm.
[Try it online!](http://05ab1e.tryitonline.net/#code=VEzCpiJKUUtBIlPCq3bDsCdfVMOXwqnDsMOwVMOXIi_Dv1wiOXlnLcOww5d5Inwgw7_Dv3wiw4LDsFTDlyJ8w798IjXDl3NUw4LigKHCriJcw78vIkpUw6TCuyw&input=)
**Explanation**
`TL¦"JQKA"S«` pushes the list `[2,3,4,5,6,7,8,9,10,J,Q,K,A]`
We then loop over each card value with `v`
`ð'_Tשð` constructs `" __________ "`
`ðT×…/ÿ\` constructs `"/ \"`
`9yg-ð×y"| ÿÿ|"Â` constructs the 2 rows with card values (the second row is the first reversed)
`ðT×…|ÿ|5×` constructs 5 rows of the form `"| |"`
Then we
```
s # move the 2nd card value row after the 5 "middle rows"
T‡ # and replace 1 with 0 and vice versa
```
`®…\ÿ/` constructs the bottom row
```
J # join everything into 1 string
Tä # split into 10 parts
», # merge by newline and print with newline
```
[Answer]
# [V](http://github.com/DJMcMayhem/V), 87 bytes
```
i ±_
/± \Ypr|$.Y6P3|r2Lhhr2o\±_/
H8ñy}GP2j6j? _ñ2j$X6jxG"04p/9
rJn.nrQn,nrKn.nrAn.
```
[Try it online!](http://v.tryitonline.net/#code=aSDCsV8gCi_CsSBcG1lwcnwkLlk2UDN8cjJMaGhyMm9cwrFfLwobSDjDsXl9R1AyagE2agE_IF_DsTJqJFg2anhHIjA0cC85CnJKbi5uclFuLG5yS24ubnJBbi4&input=)
Since this contains some unprintables, here is a hexdump:
```
0000000: 6920 b15f 200a 2fb1 205c 1b59 7072 7c24 i ._ ./. \.Ypr|$
0000010: 2e59 3650 337c 7232 4c68 6872 326f 5cb1 .Y6P3|r2Lhhr2o\.
0000020: 5f2f 0a1b 4838 f179 7d47 5032 6a01 366a _/..H8.y}GP2j.6j
0000030: 013f 205f f132 6a24 5836 6a78 4722 3034 .? _.2j$X6jxG"04
0000040: 702f 390a 724a 6e2e 6e72 516e 2c6e 724b p/9.rJn.nrQn,nrK
0000050: 6e2e 6e72 416e 2e n.nrAn.
```
[Answer]
# PHP, ~~135~~ ~~131~~ ~~158~~ 134 bytes
Hopefully, I can find a way to shorten this a little more.
```
foreach([2,3,4,5,6,7,8,9,10,J,Q,K,A]as$C)printf(" %'_9s
/%12s| %-8s|%s
|%8s |
\\%'_9s/
",_,'\
',$C,str_repeat('
| |',5),$C,_);
```
This takes advantage of `printf` to repeat multiple characters and format everything nicely.
---
**Old version:**
Not exactly a piece of beauty, but works!
```
$L=__________;$S=' ';foreach([2,3,4,5,6,7,8,9,10,J,Q,K,A]as$C)echo" $L
/ $S\
| $C".($P=substr($S,$C>9))."|
",str_repeat("| $S|
",5),"|$P$C |
\\$L/
";
```
---
Thanks to [Jörg Hülsermann](https://codegolf.stackexchange.com/users/59107/j%C3%B6rg-h%C3%BClsermann) for detecting a bug and for letting me use part of his code, that reduced it by **4** bytes! And for finding a fatal bug.
[Answer]
# Ruby, 115 bytes
Fairly straightforward use of `printf`.
```
([*(?2.."10")]+%w{J Q K A}).map{|e|printf" #{u=?_*10}
/%11s
| %-9s|
#{(?|+' '*10+"|
")*5}|%9s |
\\#{u}/
",?\\,e,e}
```
[Answer]
## Racket 327 bytes
```
(let*((ms make-string)(p #\space)(e? equal?)(sa string-append)(f(λ(s)(display(sa" "(ms 10 #\_)" \n""/"(ms 10 p)"\\\n""| "s
(ms(if(e? s"10")7 8)p)"|\n"(apply sa(for/list((i 6))"| |\n"))"| "(ms(if(e? s"10")6 7)p)s" |\n"
"\\"(ms 10 #\_)"/\n")))))(for((i(range 2 11)))(f(number->string i)))(for((i'("J""Q""K""A")))(f i)))
```
Ungolfed:
```
(define (main)
(let* ((ms make-string)
(e? equal?)
(sa string-append)
(f(lambda(s)
(display
(sa
" "
(ms 10 #\_)
" \n"
"/"
(ms 10 #\space)
"\\\n"
"| " s (ms (if(e? s "10") 7 8) #\space) "|\n"
(apply sa (for/list ((i 6)) "| |\n"))
"| " (ms (if(e? s "10") 6 7) #\space) s " |\n"
"\\" (ms 10 #\_) "/\n")
))))
(for ((i(range 2 11)))
(f (number->string i)))
(for ((i '("J" "Q" "K" "A")))
(f i))
))
```
Testing:
```
(main)
```
Output:
```
__________
/ \
| 2 |
| |
| |
| |
| |
| |
| |
| 2 |
\__________/
__________
/ \
| 3 |
| |
| |
| |
| |
| |
| |
| 3 |
\__________/
__________
/ \
| 4 |
| |
| |
| |
| |
| |
| |
| 4 |
\__________/
__________
/ \
| 5 |
| |
| |
| |
| |
| |
| |
| 5 |
\__________/
__________
/ \
| 6 |
| |
| |
| |
| |
| |
| |
| 6 |
\__________/
__________
/ \
| 7 |
| |
| |
| |
| |
| |
| |
| 7 |
\__________/
__________
/ \
| 8 |
| |
| |
| |
| |
| |
| |
| 8 |
\__________/
__________
/ \
| 9 |
| |
| |
| |
| |
| |
| |
| 9 |
\__________/
__________
/ \
| 10 |
| |
| |
| |
| |
| |
| |
| 10 |
\__________/
__________
/ \
| J |
| |
| |
| |
| |
| |
| |
| J |
\__________/
__________
/ \
| Q |
| |
| |
| |
| |
| |
| |
| Q |
\__________/
__________
/ \
| K |
| |
| |
| |
| |
| |
| |
| K |
\__________/
__________
/ \
| A |
| |
| |
| |
| |
| |
| |
| A |
\__________/
```
[Answer]
# Java 7, 287 bytes
```
String c(){String r="",l="__________",c=(" "+l+" \n/s\\\n| z |\nxxxxxx| y|\n\\"+l+"/\n").replace("x","|s|\n").replace("s"," ");for(int i=0;i++<13;r+=c.replace("z",i==10?"10":(l=i<2?"A ":i>12?"K ":i>11?"Q ":i>10?"J ":i+" ")).replace("y",i==10?"10 ":" "+l));return r;}
```
Ok, this is ugly and not very efficient, but it works.. That `10` as special case with a space before at the top and after at the bottom position really screws with everyone..
**Ungolfed & test code:**
[Try it here.](https://ideone.com/X2jsct)
```
class M{
static String c(){
String r = "",
l = "__________",
c = (" " + l + " \n/s\\\n| z |\nxxxxxx| y|\n\\" + l + "/\n")
.replace("x", "|s|\n")
.replace("s", " ");
for(int i = 0; i++ < 13; r += c
.replace("z", i == 10
? "10"
: (l = i < 2
? "A "
: i > 12
? "K "
: i > 11
? "Q "
: i > 10
? "J "
: i+" "))
.replace("y", i == 10
? "10 "
: " "+l));
return r;
}
public static void main(String[] a){
System.out.println(c());
}
}
```
**Output:**
```
__________
/ \
| A |
| |
| |
| |
| |
| |
| |
| A |
\__________/
__________
/ \
| 2 |
| |
| |
| |
| |
| |
| |
| 2 |
\__________/
__________
/ \
| 3 |
| |
| |
| |
| |
| |
| |
| 3 |
\__________/
__________
/ \
| 4 |
| |
| |
| |
| |
| |
| |
| 4 |
\__________/
__________
/ \
| 5 |
| |
| |
| |
| |
| |
| |
| 5 |
\__________/
__________
/ \
| 6 |
| |
| |
| |
| |
| |
| |
| 6 |
\__________/
__________
/ \
| 7 |
| |
| |
| |
| |
| |
| |
| 7 |
\__________/
__________
/ \
| 8 |
| |
| |
| |
| |
| |
| |
| 8 |
\__________/
__________
/ \
| 9 |
| |
| |
| |
| |
| |
| |
| 9 |
\__________/
__________
/ \
| 10 |
| |
| |
| |
| |
| |
| |
| 10 |
\__________/
__________
/ \
| J |
| |
| |
| |
| |
| |
| |
| J |
\__________/
__________
/ \
| Q |
| |
| |
| |
| |
| |
| |
| Q |
\__________/
__________
/ \
| K |
| |
| |
| |
| |
| |
| |
| K |
\__________/
```
[Answer]
# R, 175 bytes
```
for(x in c(2:10,"J","Q","K","A")){r=c("|"," ",x,rep(" ",9-nchar(x)),"|");cat(" __________ \n/ \\\n",r,"\n",rep("| |\n",5),rev(r),"\n\\__________/\n",sep="")}
```
A fairly competitive answer in R this time for an ascii-art challenge and should definitely be golfable.
[Try it on R-fiddle](http://www.r-fiddle.org/#/fiddle?id=9KU28Ep4)
**Ungolfed and explained**
```
for(x in c(2:10,"J","Q","K","A")){ # For each card in vector 1,...,10,J,Q,K,A
r=c("|"," ",x,rep(" ",9-nchar(x)),"|") # Create variable for 3rd row called "r".
;cat(" __________ \n/ \\\n", # Print: hardcoded top two rows,
r,"\n", # 3rd row,
rep("| |\n",5), # Repeat middle section 5 times,
rev(r), # Reversed 3rd row,
"\n\\__________/\n", # Hardcoded bottom row
sep="") # Set separator to empty string
}
```
The most interesting aspect where a few bytes are saved is the assignment of the third row:
```
r=c("|"," ",x,rep(" ",9-nchar(x)),"|")
```
Because there are `8` spaces in total between the character denoting the card value and the final `|` (except for `10`) we can repeat `9` spaces and subtract the number of characters in the currently printed card.
By storing each character in the `3rd` row as its own element in the string vector `r` we can reverse the vector and reuse it for the `9th` row.
[Answer]
# C#, 385 Bytes
My first ASCII Art challenge - it was fun!
Golfed:
```
string D(){var d=new string[15];for(int i=2;i<15;i++){var a=i>10?new Dictionary<int,string>(){{ 11,"J"},{12,"Q"},{13,"K"},{14,"A"},}[i]:i+"";var r="| |";d[i]=string.Join("\n",new string[]{" __________",@"/ \",a.Length>1?"| "+a+" |":"| "+a+" |",r,r,r,r,r,a.Length>1?"| " + a +" |" : "| "+a+" |",@"\__________/"});}return string.Join("\n",d);}
```
Ungolfed:
```
public string D()
{
var d = new string[15];
for (int i = 2; i < 15; i++)
{
var a = i > 10 ? new Dictionary<int, string>() {
{ 11, "J" },
{ 12, "Q" },
{ 13, "K" },
{ 14, "A" },
}[i]
: i+"";
var r = "| |";
d[i] = string.Join("\n", new string[] {
" __________",
@"/ \",
a.Length > 1 ? "| " + a + " |" : "| " + a + " |",
r,
r,
r,
r,
r,
a.Length > 1 ? "| " + a +" |" : "| " + a +" |",
@"\__________/"});
}
return string.Join("\n", d);
}
```
[Answer]
# [Actually](http://github.com/Mego/Seriously), 91 bytes
```
"JQKA"#9⌐2x+`;k' ;'_9u*@++'\' 9u*'/++"| {:<9}|"5'|;' 9u*@++n"|{:>9} |"'/'_9u*'\++kp@'
jf`Mi
```
[Try it online!](http://actually.tryitonline.net/#code=IkpRS0EiIznijJAyeCtgO2snIDsnXzl1KkArKydcJyA5dSonLysrInwgezo8OX18IjUnfDsnIDl1KkArK24ifHs6Pjl9IHwiJy8nXzl1KidcKytrcEAnCmpmYE1p&input=)
## Explanation
Part 1: setting up the list of face values:
```
"JQKA"#9⌐2x+`PART 2 CODE`Mi
9⌐2x range(2,11) ([2, 10])
"JQKA"# + extend with ["J", "Q", "K", "A"]
`PART 2 CODE`M do Part 2 for each item in list
i flatten resulting list and implicitly print
```
Part 2: creating the cards (newline replaced with `\n` for readability):
```
;k' ;'_9u*@++'\' 9u*'/++"| {:<9}|"5'|;' 9u*@++n"|{:>9} |"'/'_9u*'\++kp@'\njf
;k duplicate the face value, push both copies to a list
' ;'_9u*@++ construct the top line
'\' 9u*'/++ construct the second line
"| {:<9}|" create a format string to place the value in a left-aligned 9-width field in the top left of the card, one space away from the edge
5'|;' 9u*@++n create 5 copies of the blank middle section
"|{:>9} |" like before, but right-align the face value
'/'_9u*'/++ construct the bottom of the card
kp@'\nj push entire stack to a list, pop the list containing the face values out of that list, and join the rest (the card strings) with newlines
f format the card with the face values
```
] |
[Question]
[
Let `f` be the function that maps a bitfield (`{0 1}`) of size `n+1` to bitfield of size `n` by applying `XOR` to the `i`th and `i+1`th bit and writing the result in the new bitfield.
Example: `f("0101") = "111"`
Informal calculation:
```
0 XOR 1 = 1
1 XOR 0 = 1
0 XOR 1 = 1
```
Let `f_inverse` be the inverse function of `f`. Since the inverse is not unique, `f_inverse` returns one valid solution.
Input: bitfield as string (i.e. `"0101111101011"`) and a given natural number `k`
Output: bitfield as string, so that the string contains the result if `f_inverse` is applied `k` times to the input bitfield. (i.e. `f_inverse(f_inverse(f_inverse(input)))` )
Winning criteria: fewest Characters
Bonus:
`-25` Characters if `f_inverse` is not applied recursively/iteratively, instead the output string is directly calculated
Testscript:
```
a = "011001"
k = 3
def f(a):
k = len(a)
r = ""
for i in xrange(k-1):
r += str(int(a[i]) ^ int(a[i+1]))
return r
def iterate_f(a, k):
print "Input ", a
for i in xrange(k):
a = f(a)
print "Step " + str(i+1), a
iterate_f(a, k)
```
You can paste it for example [here](http://www.tutorialspoint.com/execute_python_online.php "An online python interpreter") and then try it.
[Answer]
# Pyth, ~~33~~ 30 - 25 = 5 bytes
```
Jiz8K+lzQ%"%0*o",KuxG/G8rQ^2KJ
```
Run it by input from stdin like (online interpreter: <https://pyth.herokuapp.com/>):
```
111
3
```
and the result will be written to stdout.
This is a direct translation of:
# Python 2, ~~127~~ ~~118~~ 79 - 25 = 54 bytes
```
def i(s,k):
l=int(s,8);t=len(s)+k
while k<1<<t:l^=l/8;k+=1
print'%0*o'%(t,l)
```
Call it like `i("111", 3)`, and the result will be written to stdout.
Note that we expect k not being too large, since for code-golfing purpose the inner loop will run for O(2k) times.
---
I think we usually call this operation "xorshift" or something. If we express the input as big-endian integers, then the function *f* is simply:
* f(x) = x ⊕ (x ≫ 1)
If we apply *f* twice we will get:
* f2(x) = x ⊕ (x ≫ 2)
However applying 3 times will have a different pattern:
* f3(x) = x ⊕ (x ≫ 1) ⊕ (x ≫ 2) ⊕ (x ≫ 3)
Applying 4 times get back to the basic form:
* f4(x) = x ⊕ (x ≫ 4)
And so on:
* f2k(x) = x ⊕ (x ≫ 2k)
Note that if we choose a big-enough 2k, then (x ≫ 2k) = 0, meaning f2k(x) = x, and the inverse is trivially the identity function!
So the strategy for finding f-k(x) without calling f-1(x) *at all* is:
1. Find K such that:
* K ≥ k
* K > log2 x
* K is a power of 2
2. Express f-k(x) = f-K + (K-k)(x) = f-K(fK-k(x)) = fK-k(x)
3. Thus, the result is `f` called K-k times
4. 25 chars profit :p
---
**Update 1**: Used octal representation instead of binary so that we could use `%` formatting to save lots of bytes.
**Update 2**: Exploit the periodic structure of `f`. Retired the iterative version since the non-iterative one is shorter even without the -25 bytes bonus.
**Update 3**: Reduced 3 bytes from Pyth, thanks isaacg!
[Answer]
# CJam, ~~15~~ 14 bytes
```
l~{0\{1$^}/]}*
```
Takes input like
```
"111" 3
```
[Test it here.](http://cjam.aditsu.net/)
## Explanation
```
l~{0\{1$^}/]}*
l~ "Read and evaluate input.";
{ }* "Repeat k times.";
0\ "Push a 0 and swap it with the string/array.";
{ }/ "For each element in the string/array.";
1$ "Copy the previous element.";
^ "XOR.";
] "Wrap everything in a string/array again.";
```
The result is automatically printed at the end of the program.
I say "string/array", because I start out with a string (which is just an array of characters), but I keep taking XORs between them and between numbers as well. `Character Character ^` gives an integer (based on the XOR of the code points), `Character Integer ^` and `Integer Character ^` give a character (based on the XOR of the number with the code point - interpreted as a code point). And `Integer Integer ^` of course just gives an integer.
So the types are flying all over the place, but luckily, whenever I have an integer it's either `0` or `1` and whenever I have a character it's either `'0` and `'1` and result is always the desired one (in either type). Since strings are just arrays of characters, mixing characters with numbers is not a problem at all. And at the end, when everything is printed, characters get no special delimiters, so the output is not affected by which bit is represented as a number or a character.
[Answer]
# J, 17 chars
Always using 0 as the leading digit.
```
(~:/\@]^:[,~[$0:)
3 (~:/\@]^:[,~[$0:) 1 1 1
0 0 0 1 0 0
```
Starting from top row's 128 1's state (left) and a random state (right), showing the last 128 digits through the first 129 iteration.
```
viewmat (~:/\)^:(<129) 128$1 viewmat (~:/\)^:(<129) ?128$2
```


[Answer]
## APL 11
```
((0,≠\)⍣⎕)⎕
```
Explanation:
```
≠\ compare increasing number of elements (1 1 1 ->1 0 1)
0, add a starting zero
()⍣⎕ repeat the function in parenthesis ⎕ times, ⎕ is the second argument
()⎕ apply all to ⎕, that is first argument
```
Try on [tryapl.org](http://tryapl.org/?a=a%u21901%201%201%u22C4%20b%u21903%20%u22C4%20%28%280%2C%u2260%5C%29%u2363b%29a&run)
[Answer]
# CJam, 25 − 25 = 0 bytes
```
q~1,*_@{[\{1$^}/_](;)\}/;
```
This is just a straight CJam port of the GolfScript answer below, since, after reading [Martin Büttner's answer](https://codegolf.stackexchange.com/a/45436), I realized that I could save one byte due to CJam's handling of integer and character types. (Basically, CJam doesn't need the `1&` used to force ASCII characters into bits in the GolfScript code, but does require a prepended `q` to read the input.) I would usually consider such a trivial port a cheap trick, but achieving a zero score made it IMO worthwhile.
In any case, this program works exactly like the original GolfScript program below, so please refer to its description and usage instructions. As usual, you can test the CJam version using [this online interpreter](http://cjam.aditsu.net/).
---
# GolfScript, 26 − 25 = 1 byte
```
~1,*.@{[1&\{1$^}/.](;)\}/;
```
This solution iterates over the input string only once, so I believe it qualifies for the −25 byte bonus. It works by internally maintaining a *k*-element array that stores the current bit of each of the *k* pre-iterates.
Input should be given via stdin, in the format `"1111111" 3`, i.e. as a quoted string of `0` and `1` characters, followed by the number *k*. Output will be to stdout, as a bitstring without quotes.
[Test this code online.](http://golfscript.apphb.com/?c=IyBDYW5uZWQgdGVzdCBpbnB1dDoKOycgIjExMSIgMyAnCgojIFByb2dyYW0gY29kZToKfjEsKi5Ae1sxJlx7MSRefS8uXSg7KVx9Lzs%3D) (If the program times out, try re-running it; the Web GolfScript server is notorious for random timeouts.)
---
Here's an expanded version of this program, with comments:
```
~ # eval the input, leaving a string and the number k on the stack
1,* # turn the number k into an array of k zeros ("the state array")
. # make a copy of the array; it will be left on the stack, making up the
# first k bits of the output (which are always zeros)
@ # move the input string to the top of the stack, to be iterated over
{
[ # place a start-of-array marker on the stack, for later use
1& # zero out all but the lowest bit of this input byte
\ # move the state array to the top of the stack, to be iterated over
{ 1$^ } / # iterate over each element of the state array, XORing each
# element with the previous value on the stack, and leave
# the results on the stack
. # duplicate the last value on the stack (which is the output bit we want)
] # collect all values put on the stack since the last [ into an array
(; # remove the first element of the array (the input bit)
) # pop the last element (the duplicated output bit) off the array
\ # move the popped bit below the new state array on the stack
}
/ # iterate the preceding code block over the bytes in the input string
; # discard the state array, leaving just the output bits on the stack
```
Basically, like most of the iterative solutions, this code can be understood as applying the recurrence
*b**i*,*j* := *b**i*,(*j*−1) ⊕ *b*(*i*−1),(*j*−1),
where *b*0,*j* is the *j*-th input bit (for *j* ≥ 1), *b**k*,*j* is the *j*-th output bit, and *b**i*,0 = 0 by assumption. The difference is that, whereas the iterative solutions, in effect, compute the recurrence "row by row" (i.e. first *b*1,*j* for all *j*, then *b*2,*j*, etc.), this solution instead computes it "column by column" (or, more accurately, "diagonal by diagonal"), first computing *b**i*,*i* for 1 ≤ *i* ≤ *k*, then *b**i*,*i*+1, then *b**i*,*i*+2, etc.
One (theoretical) advantage of this approach is that, in principle, this method can process an arbitrarily long input string using only O(*k*) storage. Of course, the GolfScript interpreter automatically reads all the input into memory before running the program anyway, mostly negating this advantage.
[Answer]
# Python, ~~94~~ 78
Will be executed at least once and thus gives the same result for `n=0` and `n=1`
```
def f(x,n):
c='0'
for i in x:c+='10'[i==c[-1]]
return f(c,n-1)if n>1 else c
```
Old version which converts the string to a numeric array and "integrates" modulo 2
```
from numpy import*
g=lambda x,n:g(''.join(map(str,cumsum(map(int,'0'+x))%2)),n-1)if n>0 else x
```
[Answer]
# Python 2, 68
```
g=lambda l,n,s=0:n and g(`s`+(l and g(l[1:],1,s^(l>='1'))),n-1)or l
```
A totally recusive solution. It's easier to understand if broken into two functions
```
f=lambda l,s=0:`s`+(l and f(l[1:],s^(l>='1')))
g=lambda l,n:n and g(f(l),n-1)or l
```
where `f` computes successive differences and `g` composes `f` with itself n times.
The function `f` compute the cumulative XOR-sums of `l`, which is the inverse operation to successive XOR-differences. Since input is given as a string, we need to extract `int(l[0])`, but do so shorter with the string comparison `l>='1'`.
---
# Python 2, 69
An iterative solution using an `exec` loop turned out 1 char longer.
```
l,n=input()
exec"r=l;l='0'\nfor x in r:l+='10'[l[-1]==x]\n"*n
print l
```
Maybe there's a shorter way to deal with the string. If we could have input/outputs be lists of numbers, it would save 5 chars
```
l,n=input()
exec"r=l;l=[0]\nfor x in r:l+=[l[-1]^x]\n"*n
print l
```
[Answer]
# Perl 5, 34
```
#!perl -p
s/ .*//;eval's/^|./$%^=$&/eg;'x$&
```
Parameters given on the standard input separated by a space.
```
$ perl a.pl <<<"1101 20"
101111011011011011010110
```
[Answer]
## Javascript ES6, 47 chars
```
f=(s,k)=>k?f(0+s.replace(s=/./g,x=>s^=x),--k):s
```
By the way, there is no side effects :)
[Answer]
# C# - 178 161 115 characters
```
static string I(string a, int k){var s = "0";foreach(var c in a)s+=c==s[s.Length-1]?'0':'1';return k<2?s:I(s,--k);}
```
Ungolfed with harness
```
using System;
using System.Text;
namespace InverseXOR
{
class Program
{
static string I(string a, int k)
{
var s = "0";
foreach (var c in a)
s += c == s[s.Length - 1] ? '0' : '1';
return k < 2 ? s : I(s, --k);
}
static void Main(string[] args)
{
Console.WriteLine(I(args[0], Convert.ToInt32(args[1])));
}
}
}
```
[Answer]
# CJam, 20 bytes
```
q~{:~0\{1$!_!?}/]s}*
```
Input is like `"111" 3`
[Try it online here](http://cjam.aditsu.net/)
] |
[Question]
[
This question involves taking input in Morse code as . (period) and - (minus symbol), with spaces to separate the input. Your task is to convert the code to standard output. You can assume that the only input contains character symbols found in the International Morse Code alphabet, found here: <http://en.wikipedia.org/wiki/Morse_code#Letters.2C_numbers.2C_punctuation>.
All output should use lowercase letters. A double space should be interpreted as a word space.
Sample input:
```
. -..- .- -- .--. .-.. . .-.-.- ... --- ...
```
Output:
```
example. sos
```
Shortest code after two weeks wins.
[Answer]
Drat, I was hoping to get here before the GolfScripters arrived :-(
Anyhoo...
# C: 228 characters:
```
char n,t,m[9],*c=" etianmsurwdkgohvf l pjbxcyzq 54 3 2& + 16=/ ( 7 8 90 $ ?_ \" . @ ' - ;! ) , :";
main(){while(scanf("%s",m)>0){for(t=m[6]=n=0;m[n];n++)t+=t+1+(m[n]&1);putchar(c[t]);}}
```
---
I thought I'd add an explanation of how this works.
The input data is parsed according to the tree data in `*c`, which can be expanded as follows (using `·` to represent a vacant node):
```
dot <-- (start) --> dash
e t
i a n m
s u r w d k g o
h v f · l · p j b x c y z q · ·
5 4 · 3 · · · 2 & · + · · · · 1 6 = / · · · ( · 7 · · · 8 · 9 0
····$·······?_····"··.····@···'··-········;!·)·····,····:·······
```
Starting at the top of the tree, work your way down while moving to the left for a dot and to the right for a dash. Then output whatever character you happen to be at when the input string ends (i.e., when a whitespace character is encountered). So for example, three dots and a dash will take you to `v` via `e`, `i` and `s`. Instead of explicitly checking for dots (ASCII `\x2e`) and dashes (ASCII `\x2d`), we only need to check the last bit (`m[n]&1`), which is 0 for `.` and 1 for `-`.
Six rows are enough to encode everything except `$`, which has 7 dot/dashes: `...-..-`, but since the input data is guaranteed to be valid, this can easily be fixed by truncating the input at 6 characters (`m[6]=0`) and interpreting `...-..` as `$` instead. We can also cut away the last 7 bytes from the tree data, since they are all empty and aren't needed if the input is valid.
[Answer]
## GolfScript (116 113 97 chars)
This includes non-printable characters used in a lookup table, so I'm giving it as xxd output:
```
0000000: 6e2d 2720 272f 7b60 7b5c 6261 7365 2035
0000010: 3925 2210 a9cd 238d 57aa 8c17 d25c d31b
0000020: 432d 783e 277a 3823 e146 e833 6423 23ac
0000030: e72a 39d5 021c 4e33 3b30 3138 dc51 2044
0000040: 3aa7 d001 df4b 2032 333f 36ae 51c3 223d
0000050: 7d2b 5b35 2d34 5d2f 2b32 3333 257d 256e
0000060: 2b
```
This decodes to a program equivalent to
```
n-' '/{`{\base 59%"\x10\xA9\xCD#\x8DW\xAA\x8C\x17\xD2\\\xD3\eC-x>'z8#\xE1F\xE83d##\xAC\xE7*9\xD5\x02\x1CN3;018\xDCQ D:\xA7\xD0\x01\xDFK 23?6\xAEQ\xC3"=}+[5-4]/+233%}%n+
```
which is essentially
```
n-' '/{`{\base 59%"MAGIC STRING"=}+[5-4]/+233%}%n+
```
This uses a (non-minimal) perfect hash based on the core idea of [An optimal algorithm for generating minimal perfect hash functions; Czech, Havas and Majewski; 1992](http://cmph.sourceforge.net/papers/chm92.pdf). Their basic idea is that you use two hash functions, `f1` and `f2`, together with a lookup table `g`, and the perfect hash is `(g[f1(str)] + g[f2(str)]) % m` (where `m` is the number of strings we wish to distinguish); the clever bit is the way they build `g`. Consider all of the values `f1(str)` and `f2(str)` for strings `str` of interest as nodes in an undirected graph, and add an edge between `f1(str)` and `f2(str)` for each string. They require not only that each edge be distinct, but that the graph be acyclic; then it is just a DFS to assign weights to the nodes (i.e. to populate the lookup table `g`) such that each edge has the required sum.
Czech et al generate random functions `f1` and `f2` which are expressed via lookup tables, but that's clearly no good: I searched for a suitable hash using simple base conversions with two distinct bases from -10 to 9. I also relaxed the acyclic requirement. I didn't want to assign the strings to values from 0 to 54, but to the corresponding ASCII codes, so rather than taking `(g[f1(str)] + g[f2(str)]) % m` I wanted `(g[f1(str)] + g[f2(str)]) % N` for some `N > 'z'`. But that allows freedom to try various `N` and see whether any of them allow a valid lookup table `g`, regardless of whether there are cycles. Unlike Czech et al I don't care if the search for the perfect hash function is O(n^4).
The graph generated by `-4base` and `5base` mod `59` is:

which is fairly nice apart from the biggest connected component, which has three cycles of length 1. We have to go up to `N=233` before we can find a `g` which is consistent.
[Answer]
# Mathematica 62
*Mathematica* allows us to cheat
```
f=ToLowerCase@StringDrop[WolframAlpha[". .- "<>#,"Result"],2]&
f@"."
f@". -..- .- -- .--. .-.. . .-.-.-"
f@".... .- ...- . -.-- --- ..- -- --- --- . -.. - --- -.. .- -.-- ..--.."
```
>
> e
>
>
> example.
>
>
> have you mooed today?
>
>
>
The first two symbols `.` and `.-` are necessary to interpret small codes correctly.
[Answer]
# [R](https://www.r-project.org/), 145 bytes
Translated a dot to a 2, a dash to a 1 and interpreting the number in ternary and taking the mod 89, which gives a unique number we can use in a hash table. The presence of a 13 (111 base-3) means adding 1 because ASCII 13 doesn't work in TIO.
```
cat(c(letters,0:9,".")[match(strtoi(chartr(".-","12",scan(,"",t=scan(,""))),3)%%89+1,utf8ToInt('DG,)62 5N*EHMAI.%"!4=@
'))],sep='')
```
[Try it online!](https://tio.run/##K/r/PzmxRCNZIye1pCS1qFjHwMpSR0lPSTM6N7EkOUOjuKSoJD9TIzkjsaikSENJT1dJR8nQSEmnODkxT0NHSUmnxBbG1NTU1DHWVFW1sNQ21CktSbMIyffMK9FQZ3NxF2fSkdJkNZMw4uSQNvUT5GPm1xJy9fB19NRTVVKUNLF14FbX1IzVKU4tsFVX1/yvp6Crp6erAES6IFJXD0joAQkQBYQKCnpAni5ITk/vPwA "R – Try It Online")
# [R](https://www.r-project.org/), 236 bytes (non-competing)
This is *not* going to be competitive, but it lets us show off something interesting in R: store the Morse code tree inside a quoted language structure `m` and retrieve it from the code of dots and dashes very simply using the fact that `[[` can be applied recursively to lists. For example `m[[c(2,2,3,2)]]` retrieves dot, dot, dash, dot or "f".
```
m=quote(.(e(i(s(h(5,4),v(,3)),u(f,M(,2))),a(r(l,.(.(,.),)),w(p,j(,1)))),t(n(d(b(6),x),k(c,y)),m(g(z(7),q),o(D(8),S(9,0))))))
for(w in scan(,"",t=scan(,"")))
cat(chartr("MDS","-. ","if"(is.symbol(z<-m[[(utf8ToInt(w)==45)+2]]),z,z[[1]])))
```
[Try it online!](https://tio.run/##NUzBTsJQELz7FS/vNBvnbQRBMbE3Lh444a3hUAqVKm3l9dVKf76@kri7mZmd2awfxyq5dE04QnFEiRYnLLkQ/oCPIuxQcAPOJeoMHmdqvKQKo9Hjm5/gTKY0oMYBezwJf4VfyHmNboUPDHgWXoQN1lgJt3jhg9zqrmg8elPWps2zGrSWIfmXU55nAfkp88HDbtZbS@vURCwLi7LV9lrtmzOGV1elKbpQrN6btzqglyRZLOV@vtsJBw5pOotKZFTjVJ2J4yaMzzQa5kaxjdG4uSlTHf8A "R – Try It Online")
[Answer]
## C, 169 chars
I couldn't find a better hash function..
(I posted the unminified code but counted it minified; to minify just do `:%s/ //g | %j!` in vim, then put the space in the string literal back.)
```
c, v = 1;
main() {
while (c = getchar(), ~c)
v = c < 33? putchar(
"& etianmsurwdkgohvf.l.pjbxcyzq..54.3.;!2).+...,16=/:..(.7.?_8.9o\"...$...@...'..-"[v < 64? (v != 40)*v : v % 51 + 33]
), 1 : v * 2 + c % 2;
}
```
### Test run
(`morse.in` is just the whole alphabet in morse on separate lines):
```
% clang morse.c && ./a.out </tmp/morse.in
abcdefghijklmnopqrstuvwxyzO123456789.,?'!/()&:;=+-_"$@
% ./a.out <<<'. -..- .- -- .--. .-.. . .-.-.- ... --- ...'
example. sos
```
### Explanation
This one is fairly straightforward. `c < 33` finds a whitespace/separator character (, `\n`, EOF, ...). `c % 2` translates a dot or dash into a bit. The idea is to create a unique number for each character simply by interpreting it as a binary number (after prefixing it with 1 to deal with the variable length) (this interpretation is the `v*2 + c%2` part). I then get a 137-char LUT, which I compacted by hashing the resulting value (`v < 64? v : v % 51 + 33`, constants found via trial-and-error and by looking at the distribution and try to find a huge gap). Unfortunately this hash function has a single collision, which is why I have to special-case the `40 → '&'` mapping.
[Answer]
# Powershell, 193 bytes
```
$n=1
-join("$args "|% t*y|%{if($_-32){$n=$n*2+($_-ne'.')}else{(" etianmsurwdkgohvf l pjbxcyzq 54 3 2& +~16=/ ( 7 8 90~~~?~ `" .~@ ' -~~;! )~ ,~:~~~~$"-replace'~',' ')[$n]
$n=1}})
```
Less Golfed Test script:
```
$f = {
$n=1
-join(
"$args "|% t*y|%{
if($_-32){
$n=$n*2+($_-ne'.')
}else{
(" etianmsurwdkgohvf l pjbxcyzq 54 3 2& +~16=/ ( 7 8 90~~~?~ `" .~@ ' -~~;! )~ ,~:~~~~$"-replace'~',' ')[$n]
$n=1
}
}
)
}
@(
,("example. sos",". -..- .- -- .--. .-.. . .-.-.- ... --- ...")
,("0123456789abcdefghijklmnopqrstuvwxyz","----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----. .- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..")
,("hello world", ".... . .-.. .-.. --- .-- --- .-. .-.. -..")
) | % {
$expected,$s = $_
$result = &$f $s
"$($result-eq$expected): $result"
}
```
Output:
```
True: example. sos
True: 0123456789abcdefghijklmnopqrstuvwxyz
True: hello world
```
[Answer]
# JavaScript (165 bytes, only implementing four planes.)
```
n=''.replace(/\./g,1).replace(/-/g,0).split(' ')
l='|te|mnai|ogkdwrus|cöqzycxbjpälüfvh'.split('|')
r=''
for(i in n){r+=l[n[i].length][parseInt(n[i],2)]}
alert(r)
```
The input should be assigned to `n`, execute the following code to get the output:
```
n='. -..- .- -- .--. .-.. .'.replace(/\./g,1).replace(/-/g,0).split(' ')
l='|te|mnai|ogkdwrus|cöqzycxbjpälüfvh'.split('|')
r=''
for(i in n) {r+=l[n[i].length][parseInt(n[i],2)]}
alert(r)
```
] |
[Question]
[
Your challenge is to print any 100 consecutive digits of π. You must give the index at which that subsequence appears. The 3 is not included.
For example, you could print any of the following:
* `1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679` (index 0)
* `8214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196` (index 100)
* `4428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273` (index 200)
Output may be as a string / digit list / etc.
To ensure answers actually produce known digits of pi, all answers must be verifiable through the [Pi API](https://api.pi.delivery/v1/pi?start=1&numberOfDigits=100) (note: This API counts the 3, your answer should not).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
[Answer]
# JavaScript (ES11), 53 bytes
Starts at index 0. Returns a BigInt.
```
f=(x=375n*10n**97n,k=3n)=>x?x/k+f(x*k++/k++/4n,k):82n
```
[Try it online!](https://tio.run/##FcndDkAgGADQ1@kHIRa2eJaWMmpfJrPePlycq3OoR0V97eddQlhNzlaiJLnogTQ1EDIKKJzkgOWclsQctSgRRyn7dd/haWgh6wAxeFP5sCGLMM4v "JavaScript (Node.js) – Try It Online")
The underlying formula is:
$$\pi-3=\sum\_{n=1}^{\infty}\frac{3}{4^n}\left(\prod\_{k=1}^{n}\frac{2k-1}{2k}\right)\times\frac{1}{2n+1}$$
(also used in [my answer](https://codegolf.stackexchange.com/a/206909/58563) to [this other challenge](https://codegolf.stackexchange.com/q/206906/58563))
[Answer]
# Trivial answers
This is mostly for answers that use a built-in arbitrary-precision pi constant, or a built-in that generates digits of pi.
# [Python 3](https://docs.python.org/3/), 49 bytes
```
from mpmath import*
mp.dps=102
print(str(pi)[3:])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1chtyA3sSRDITO3IL@oRIsrt0AvpaDY1tDAiKugKDOvRKO4pEijIFMz2tgqVvP/fwA "Python 3 – Try It Online")
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
žs¦т£
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6L7iQ8suNh1a/P8/AA "05AB1E – Try It Online")
# [Vyxal](https://github.com/Vyxal/Vyxal) `H`, 18 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 2.25 bytes
```
ɾ∆i
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJIPSIsIiIsIsm+4oiGaSIsIiIsIiJd)
### Explained
```
ɾ∆i­⁡​‎ # ‎⁡The H flag presets the stack to 100
ɾ # ‎⁢For each number in the range [1, 100]:
∆i # ‎⁣Push the nth digit of pi, 0 indexed, hence avoiding the `3`
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
# [M](https://github.com/DennisMitchell/m), 12 bytes
```
ØP%1µ×1ȷ100Ḟ
```
[Try it online!](https://tio.run/##ARcA6P9t///DmFAlMcK1w5cxyLcxMDDhuJ7//w "M – Try It Online")
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes
```
Print@@@RealDigits[Pi-3,10,100]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvxMHBISg1McclMz2zpDg6IFPXWMfQAIgMYv//BwA "Wolfram Language (Mathematica) – Try It Online")
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
P-×φψ¤≕PiT¹⁰⁰
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@3NKckM6AoM69Ew0pXRyEkMze1WCNNR6FSU9Oayy0zJ0fDPbUkLLEoMzEpJ1VDKSBTCSQRUpSZq2FoYKBp/f//f92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Starts at the `997`th digit of `π`. Explanation:
```
P-×φψ
```
Make space for `1999` characters in the canvas.
```
¤≕Pi
```
Fill those characters with the digits of `π`, including the leading `3.`, so `1997` decimals.
```
T¹⁰⁰
```
Take only the `100` digits starting at the `997`th.
# [Ruby](https://www.ruby-lang.org/), 53 bytes
`BigMath.PI` guarantees accuracy for a number of digits up to its argument, but it outputs more digits than that (requiring truncation), and it just so happens that `BigMath.PI(99)` is still accurate enough for the problem, saving a byte over `BigMath.PI(101)`.
```
require'bigdecimal/math'
p BigMath.PI(99).to_s[3,100]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hY-9DsFgFIZ3VyEWJNT5-77vnKGLzSCxi0hRNNGoagdX4CIsHbgod6MDs-l5lyd5n8ezrDe3pnnV1X6sb1emlzor0_4mO-zSbZYnp0meVMd-p-hOs8O8ndFiNjAbRtV5fV3yCAFWX_le1NW120NBZ-QdO7VgTKziyQuzMgVzQKqCFtAbm3FwCE4JLIiJtCJDUPQCntQTqFkLBRYlx0KIAXywXhz_u_Nr-gA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes
```
≔⊗Xχ¹⁰⁰θ≔θηFφ≔⁺θ÷×η⁻φι⊕⊗⁻φιη✂Iη¹
```
[Try it online!](https://tio.run/##XY2xCsMgFEX3fsUbn2BB50ylWTIUAu0PpOa1PjBK1KSfbxXSpePlHO4xdoomTK6US0r89tiH7eloxjF8KKJWErRSQkhYRXc6nFWCresVIlSjYjjA6LbU6OBzzzvPhA9eKKGVcGNfWbMlcPsbvIm0kM819ov@SaJ5rTRG9hnvjg3hdUoZbQVaiK6Uct7dFw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Calculates the first `1001` terms of `2 + 1/3*(2 + 2/5*(2 + 3/7*(2 + 4/9*(2 + ...))))`.
```
≔⊗Xχ¹⁰⁰θ
```
Calculate `2e100` as an integer.
```
≔θη
```
Start with that as an approximation to `1e100π`.
```
Fφ
```
Repeat `1000` times.
```
≔⁺θ÷×η⁻φι⊕⊗⁻φιη
```
Calculate the next approximation to `π`.
```
✂Iη¹
```
Output without the leading `3`.
[Answer]
## Python2, 91 bytes
```
print 0x296e417278c91bbebb472cab663a71405eef415a7751d7b251874642e34fa5406ba944ce62eb559eff7
```
Prints the first 100 digits starting at index 0.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 24 bytes
Prints 100 digits of pi, starting at [index 2](https://api.pi.delivery/v1/pi?start=2&numberOfDigits=100)
```
char(vpa(pi,102))(4:end)
```
[Try it online!](https://tio.run/##Dc5BDoMgEEDRq7QrIHExzAwwUy/QaxC00YWWiPX61NVfveR/y5mvufey5MNeNdu6Dh7QOcuveZ9cXz@2nUfZqs17Gwz7oBgDBdGkhCQcMTKRECYNgCLsNfmopEopeAiCoImV@YYESXxkiCgRQVTvCBALBmL0PkFMKsa5cVpbteb9O468DI8tn2WZ29O48Z7qfw "Octave – Try It Online")
# MATLAB, 30 28 bytes
```
t=char(vpa(pi,102));t(4:end)
```
---
For both versions, this first uses variable precision calculation to work out Pi exactly to 102 *digits* (not decimals, it includes the `3`).
Then it converts the result to a character vector and removes the string prefix `'3.1'` to leave exactly 100 characters. For the Octave version we can index directly into the returned value from the `char()` function, while MATLAB we have to save to a variable then truncate.
```
ans =
4159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798
```
Notes:
* We have to use 102 instead of 101 (3 + 100 decimals), because the `vpa` function rounds the final digit. If we used 101 the final digit would be incorrect due to rounding.
* Based on [this](https://codegolf.meta.stackexchange.com/a/7371/42295) meta post, when output is allowed to return a string, the `ans=` is acceptable.
[Answer]
# [Kamilalisp](https://github.com/kspalaiologos/kamilalisp), 21 bytes
```
↓ 2\⍫← \○⊢*(fr 101)\π
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70qOzE3MycxJ7O4YMFajcx8q_KizJLUnDwFjaWlJWm6FjcVHrVNVjCKedS7-lHbBIWYR9O7H3Ut0tJIK1IwNDDUjDnfAFG3SFMTwliwAEIDAA)
[Answer]
## Python 3, 165 bytes
(index 0)
```
s=''
a=10000
e=0
f=[a//5]*365
for c in range(364,0,-14):
d=0
for b in range(c,0,-1):
d=d*b+f[b]*a;g=2*b-1;f[b]=d%g;d//=g
s+=f"{e+d//a:04}";e=d%a
print(s[1:101])
```
[Try it in SageMathCell](https://sagecell.sagemath.org/?z=eJxdj0FrhDAQhe%2DB%5FIdhl7JGd9W46kGZW6%2DFUgo9iIdkE0NoyYrxUkr%5Fe0d7KHQODx7vezDvCLMH451fYw6P%5Fh1e4c2H1S6gPtydsyPItgH9uVrKn5%2DgevHB5ZxxFvF04kyhLOk4s0gy4aCKohnTa9uQuy9wAx9gUcHZ5NrW5%5FJ8kbXoOAOz8bAh%2Dg%2D57cCeE2BSnU2DHlPVO6xSfZH9ZtE8uN4UBTrCYobT4ctm5FVX1t%2DH3lKuOJsXmpHEQXaylKPYPp59XBdAIE1mn4fkdzctqIX43wBE2AtDRb4axQ%2DraE%2DN&lang=sage) (with verification).
This algorithm only uses integer arithmetic. It was derived from obfuscated C code by Dik T. Winter, but I've modified it a bit over the years. Dik's version was a bit more compact, and can generate hundreds of digits, but it eventually produces erroneous output due to integer overflow, which isn't an issue in Python. OTOH, this algorithm gets a bit sluggish for large numbers of digits, due to the O(n^2) inner loop.
Of course, for serious pi digit generation, there are various lovely AGM based algorithms that converge quadratically. The Borwein brothers found several, but I like the Gauss / Brent / Salamin <https://stackoverflow.com/a/26478803/4014959>
[Answer]
# Java 10, ~~176~~ 171 bytes
```
v->{var t=java.math.BigInteger.TEN.pow(100).shiftLeft(1);var p=t;for(int i=330;i>0;)p=t.add(p.multiply(t.valueOf(i)).divide(t.valueOf(i-~i--)));return(p+"").substring(1);}
```
Based on [my answer for the related challenge of outputting the first 500 digits of pi](https://codegolf.stackexchange.com/a/213932/52210).
-5 bytes thanks to *@Neil* by reverting the algorithm
[Try it online.](https://tio.run/##TVA9a8MwEN3zK45MEsXCIaNwhkKGQusOLV1KB8WSnXNlWcgnlRDcv@7KbYYuB/eOe1@9Sqro9efSWDVN8KTQXTcA6MiEVjUG6nUFeKGAroOGvY2oIXGZ0XmTx0SKsIEaHFSwpOJwTSoAVX0mFoOis7jH7iHTdSaI12Mt/PjFdmXJxXTGlh5NS2zH5frkK5LtGFgWB6z2@1LioZQ8w0JpzbwYoiX09sJIJGWjeW4Zci40JtTmP1h8Y1FwzmUwFINj/m67zYLxNP3GWAXnRa72fTzZbP@WIq3hhtwB@8v7/gGK3wq4TGQGMUYSPp/IOuZEw1y0lt/amJcf)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~45~~ 44 bytes
```
8₂;ו13CÒ₃Sˆ`£û‰ñêˆǝd‰Ž¿Ð†₆{©«62—lÚ̔߰dZγ•J
```
[Try it online!](https://tio.run/##AV0Aov9vc2FiaWX//zjigoI7w5figKIxM0PDkuKCg1PLhmDCo8O74oCww7HDqsuGx51k4oCwxb3Cv8OQ4oCg4oKGe8Kpwqs2MuKAlGzDmsOM4oCdw5/CsGRazrPigKJK//8 "05AB1E – Try It Online") Starts at index \$2{,}164{,}164{,}669{,}331\$.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 70 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.75 bytes
```
u∆C₁⇧ḞḢḢṪ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwideKIhkPigoHih6fhuJ7huKLhuKLhuaoiLCIiLCIiXQ==)
Calculates pi through \$cos^{-1}(-1)\$ and then formats to 100 decimal places.
## Explained
```
u∆C₁⇧ḞḢḢṪ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌­
u∆C # ‎⁡arccos(-1)
₁⇧Ḟ # ‎⁢Formatted to 102 decimal places
ḢḢ # ‎⁣Remove the `3.`
Ṫ # ‎⁤and the last digit. The last digit is needed for rounding purposes.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
## Python 3, 256 bytes
This version computes pi using an accelerated version of Archimedes' algorithm for `pi = 4*arctan(1)`.
```
m=338
M=1<<m
def s(y,x=M):
y<<=m;u=x
while u<0 or u>1:u=(x//2+y)//x-x;x+=u>>1
return x
a=b=x=M
g=s(2*M)
d=[a]
for i in range(16):
a=(a+g)>>1;p,d=d,[a];q=0
for u in p:q+=2;d+=[d[-1]-(u>>q)]
b-=b>>q;g=s(a*g>>m,g)
print(str(b*x//d[-1]*4*10**100>>m)[1:])
```
Try it in [SageMathCell](https://sagecell.sagemath.org/?z=eJw1kM1q4zAUhfcGv8PFXYz8k8Zy2jLElmE6i64MpVBmkclCjmRHYEuOJM%5FYffreNFQgdOB%2D5xxxoyiCSUFnzQgPkAD3XBMah0EYAJ53Jx385nZwRv9wwE8nOUjLvRTwT1qnjAbT3dBnY09nboVHbjRCdQqhXy8N8KE3VvnzeOP%2DoPZSQ7vCawPFm9I9FHmxu6f5ff74XfysNLcrdGrBlMko7b8Lb%5FMXM3RSZFA8PmGSly4MoigKg7sPhu%5FfMBjZbvczDBpGqwqbhezAkTVbWBPvMWKtKjaWM1tQ%5Fz%2DrQcJc5WAszDXdz4ws222RrvF2u2yWcknZXNcUUSv9bDWgi7OWYVgY9MyRImlwZYId%2DDEMOkxRoDRYrntJ6NNXIWeEp32MMeWUCSYyZMsLy3F0NcxXw7S%5FpKwoRcoO4rChxw3B2kuMmdBuWIu6vLbxpK%5FrMeuxcrK4GeK8JW2CX%5F5yJQ8JzRO8OVLxge6PCN7hVsobPUhNPuL4E7%2DVi4A=&lang=python)
This code implements binary fixed point arithmetic using Python integers. The core arctan algorithm was devised by Bille Carlson, see Carlson, B. C. [An Algorithm for Computing Logarithms and Arctangents](https://doi.org/10.2307/2005182), Mathematics of Computation, Apr 1972.
This algorithm rapidly calculates any of the standard inverse circular and hyperbolic functions. It even handles complex arguments (assuming the sqrt function does). Here's a [non-golfed demo](https://gist.github.com/PM2Ring/a4655b6029d78d449a8aa28c3986bf89) that computes `pi = 10*arcsin((sqrt(5)-1)/4)`.
This algorithm is very similar to the AGM (arithmetic-geometric mean), but it updates the two core terms `a` and `g` sequentially instead of in parallel. So it's sometimes referred to as the fake AGM. It's also known as Borchardt's modified AGM algorithm. The Borwein brothers pointed out that it is, in fact, the same algorithm Archimedes used to iteratively subdivide a polygon.
Carlson's innovation is to apply Richardson series acceleration, which speeds up the convergence considerably. It's not as fast as a true AGM, however it's quite efficient for high precision calculation because it only uses one non-trivial division. (The square root can be also be implemented to avoid non-trivial divisions, using the [Quake-style 1/sqrt algorithm](https://stackoverflow.com/a/70841843/4014959)).
For further details on algorithms related to pi and the AGM, please see [The Borwein brothers, Pi and the AGM](https://arxiv.org/abs/1802.07558) by Richard P. Brent.
FWIW, Carlson also developed and analysed a suite of true AGM algorithms for computing elliptic integrals and functions, and those algorithms can (of course) handle circular & hyperbolic functions. See [Numerical computation of real or complex elliptic integrals](https://arxiv.org/abs/math/9409227)
] |
[Question]
[
You are given a string \$s\$ of characters from a to z. Your task is to count how many unique strings of length \$n\$ you can make by concatenating multiple prefixes of the string \$s\$ together.
Since the result can be superlative you can either choose to output the whole result, the result mod \$2^{32}\$ or the result mod \$2^{64}\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins.
Tests:
```
aaaaa 8 -> 1
abcdef 10 -> 492
aerodynamics 10 -> 507
disbelief 10 -> 511
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 10 bytes
```
rJᵐ#rj@au#
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FmuKvB5unaBclOWQWKq8pDgpuRgqseCmmYWCUiIIKHEZGgCZSckpqWlQdmpRfkplXmJuZnIxRCQlszgpNScTqACiHQA)
```
rJᵐ#rj@au#
rJᵐ# Ordered integer partition
r Range each
j Concatenate
@ Nth (vectorized)
au# Count unique results
```
[Answer]
# JavaScript (ES12), 53 bytes
Expects `(s)(n)`, where `s` is given as an array of characters.
```
s=>g=(n,q=t=0)=>s.map(c=>q[n]?g[q]||=++t:g(n,q+=c))|t
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGiNNulpSVpuhY3TYtt7dJtNfJ0Cm1LbA00be2K9XITCzSSbe0Ko_Ni7dOjC2Nramy1tUus0kGKtG2TNTVrSqCadybn5xXn56Tq5eSna6RpROvp6SklgoBSrKaGhaamAgzo6ysYcmFTnJSckpoGUm1oAFcOVGxiaYRVeWpRfkplXmJuZnIxXBNQuamBOTblKZnFSak5magWgJQbGkI8sGABhAYA)
### Commented
```
s => // outer function taking s[] = input string
g = ( // inner recursive function taking:
n, // n = target length
q = // q = generated string (initially set to 0, then
// coerced to "0something")
t = 0 // t = output counter (defined in the global scope)
) => // NB: g is also used as an object to store all
// generated strings
s.map(c => // for each character c in s[]:
q[n] ? // if q[n] is defined (target length reached):
g[q] ||= // unless g[q] is already defined,
++t // set it to a truthy value and increment t
: // else:
g( // do a recursive call:
n, // pass n unchanged
q += c // append c to q
) // end of recursive call
) // end of map()
| t // return t
```
[Answer]
# [Python](https://www.python.org), 96 bytes
```
f=lambda s,n,j=0:n<2or sum(f(s,n-(j:=j+1))*all(s.find(s[k:j])for k in range(1,j))for c in s[:n])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PZBNbsIwEIX3OcXIK5s6KEZFUKvpRSiiThy3Ns44isOCa3TbDRu4E7epjdK-zWi-eZq_n9twnr4CXi7X02TK7f3D1F71jVYQOXJXVxJfV2GEeOqpoYmV1MnaPQnGFsp7GpfGoqZxd5Ruz0xyHsEijAo_Oyq4Yw_WZhZ3EvdsnvOdsc-YEKKyYAvlG4hCNa3uDIgqp88vq0J1Y9BnVL1t44zX1abQNjadt__WtRCp1TIO3k6UvCNhsoAkywNfHKAGP9fYAw-jxSmdZHmOgbF5s79P_AI)
## How?
Does the recursion
\$f(n) = \sum\_{j=1\ldots\min(n,|s|)}x(j)f(n-j)\$
where
\$x(n):=\begin{cases}0 & \text{if } s[:n] \text{ has a proper prefix equaling a suffix} \\\\ 1 & \text{else}\end{cases}\$
is there to avoid double counting.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 9 bytes
```
¹ƤṗF€ḣ€QL
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLCucak4bmXRuKCrOG4o+KCrFFMIiwiIiwiIixbIlwiYWJjZGVmXCIiLCI1Il1d)
This is very slow, so it will not run well for any of the test cases provided.
## Explanation
```
¹ƤṗF€ḣ€QL Main Link: word as left argument, number as right argument
¹Ƥ get prefixes of the word
ṗ cartesian power
F€ flatten (join into one string) each list of prefixes
ḣ€ take the first N characters of each string
Q deduplicate
L count the number of strings
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 100 bytes
```
(a=#1;n=#2;Length[Union@@Map[a[[;;#]]&,Permutations/@IntegerPartitions[n,All,Range@Length@a],{3}]])&
```
[Try it online!](https://tio.run/##RcwxC8IwEAXg3Z@RQlEIaO0YCnEUFIrgFDKcbdpGm6ukcSr97THVoMMHx/HeM@A6ZcDpCnxT@DUUScawSPbspLB1nbiiHpDzMzwFCMFYImVKS2XNy4XWgOOWH9GpVtkSrNOfl0B66Ht6AWwV/@5wkHTKZyk3qS@tRscbMZGaUKKDMbgFKujjb7kbMtNsJ1f/BsRkFdS/FCVt0MXmPXjEJbMs5NK/AQ "Wolfram Language (Mathematica) – Try It Online")
Based on idea, that lengths of all prefixes in valid combination is integer partition of given number.
Very fast, but may be golfed more, I'll try!
Needs input as array of chars and number.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ηIиæJIùÙg
```
[Try it online.](https://tio.run/##yy9OTMpM/f//3HbPCzsOL/PyPLzz8Mz0//8Tk5JTUrlMAA) (Extremely slow, so no test suite. It'll even time out for all provided test cases..)
Or alternatively, a port of [*@hyper-neutrino♦*'s Jelly answer](https://codegolf.stackexchange.com/a/260199/52210) is **9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** as well:
```
ηIãJIδ∍Ùg
```
[Try it online.](https://tio.run/##yy9OTMpM/f//3HbPw4u9PM9tedTRe3hm@v//iUnJKalcJgA) (Faster than my approach above, but still extremely slow, so again no test suite.)
**Explanation:**
```
η # Get the prefixes of the first (implicit) input-string
Iи # Repeat this list the second input-integer amount of times as flattened list
æ # Get the powerset of this
J # Join each inner list together to a string
Iù # Only keep strings of a length equal to the second input-integer
Ù # Uniquify this list of strings
g # Pop and push the length to get the amount of unique strings
# (which is output implicitly as result)
η # Get the prefixed of the first (implicit) input-string
Iã # Get the cartesian power with the second input-integer
J # Join each inner list together to a string
δ # Map over each inner string:
I ∍ # Extend or shorten it to a length of the second input-integer
Ùg # Same as above (including implicit output)
```
[Answer]
# [Haskell](https://www.haskell.org/), 125 bytes
```
import Data.List.Ordered
s#n=length(m!!n)where m=map(\n->nubSort$take n(cycle s):[p++q|l<-[1..n-1],p<-m!!l,q<-m!!(n-l)])[0..]
```
[Try it online!](https://tio.run/##HYyxDoIwFAB3v6ICAw20gdWAk6OJgyMyFHhKw@uztDXGxH@vxOmSS@5m5RdAjFEb@3SBnVRQ8qx9kBc3gYNp51NqEegR5tzs98Tf86aZaY2y@Y3EkV7DdSuzoBZglI@fEYF5fuhsUaxfbERXS0mi7kvbiO2A5fpnTgJ5z7tKyj4apam1TlPIkkn7AVDDPUnrKv4A "Haskell – Try It Online")
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2/tree/main) `L`, 11 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ƒọʠ€Jæl¹=;U
```
Port of [Kevin Cruijssen's 05AB1E answer](https://codegolf.stackexchange.com/a/260201/114446).
Warning: this is very slow. It manages to complete the test case in the screenshot in ~10s on my computer.
#### Explanation
```
ƒọʠ€Jæl¹=;U # Implicit input
ƒ # Prefixes of the first input
ọ # Repeated second input number of times
ʠ # Powerset of this list
€J # Join each inner list
æ ; # Filtered by:
l # Pop and push the length
¹= # Equals the second input?
U # Uniquify this list
# L flag gets the length
# Implicit output
```
---
Thunno 2 isn't on ATO yet, so here's a screenshot of the local interpreter:
[](https://i.stack.imgur.com/OFUSV.png)
[Answer]
# [Python](https://www.python.org), ~~120~~ 118 bytes
*-2 bytes thanks to @The Thonnu*
```
def g(s,n):a={0};f=lambda n,l="":n and[f(n-i,l+s[:i])for i in range(1,1+min(n,len(s)))]or a.add(l);f(n);return~-len(a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY9BCsIwEEX3niJklcFU2p209CTSxdQkdSCdSlIFEb2Im270Tt7GiIroX_7_H3_mctsexs3A03TdjS5b3vfGOtGpqBlKrI_5qXK1x741KFj7WsqSBbJZOcUZaT-Pq5IacEMQJIhFQO6sKnQx74lVIiyrCABNKuACjVEeqsRCFey4C3zOng2E93qzDcSj6pTEJKmXALOv1a7TcVIX-Y9rw2AOjD2t439mKLbW0wd6jXxefQA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
Nθ⊞υωFυF⁻Eθ…⁺ι…ηθ⊕κυ⊞υκI№EυLιθ
```
[Try it online!](https://tio.run/##TY1BCsMgEEX3OYXLGbDQrrN0FWhKrmCNrRKjiTotOb3VQqGbmc8b5n1lZFRBulIGv1G@0XrXEXbsu4mSAeLsXfMjRAaE7LtH6ynBKDfYOROHclqYsMHkKrX/xHC2I3I2eBX1qn3WMyzYCCGyn39pXdH6DEKmOgLV2Oz1dtX@mQ3Y9lNV2JdyOXdSxzAfXq5WpXJ6uQ8 "Charcoal – Try It Online") Link is to verbose version of code. Takes `n` as the first input and `s` as the second input. Explanation:
```
Nθ
```
Input `n`.
```
⊞υωFυ
```
Start a breadth-first search of concatenations of prefixes with the empty string.
```
F⁻Eθ…⁺ι…ηθ⊕κυ
```
For each concatenation so far, extend it up to the desired length with a cyclic prefix of the input string, then take each prefix of the result that has not yet been discovered.
```
⊞υκ
```
Push each new discovery to the list so that it can be processed on a later iteration.
```
I№EυLιθ
```
Count how many strings were of the desired length.
For example, with an input of `10` and `abcdef`, the first pass produces the strings `a`, `ab`, `abc`, `abcd`, `abcde`, `abcdef`, `abcdefa`, `abcdefab`, `abcdefabc` and `abcdefabcd`. This is golfier than only producing the first six strings and waiting until `abcdef` is processed to produce the remaining four.
[Answer]
# [Scala](http://www.scala-lang.org/), 183 bytes
Modified from [@97.100.97.109's answer](https://codegolf.stackexchange.com/a/260209/110802).
---
Golfed version, [try it online!](https://tio.run/##dY8/S8RAEMX7fIoh1Q7mlqSThBxYWlgdVmIxSTa5kf1z7O4JZ8hnj5vzBEGdbub33uNN6EnTyubkfISwLbJ3Wqs@srPSnCN1WmWZ697SCZ6ILczroEaYRKgP0bOdCls/2ojt/E4aqL155EHFly/Bq8hzbDbTKK7aQt@sbQL1s@XYckL7EkUF0YGheJSGrbBFkFrZKR4R5ei8ov4ouN0n8Y4LfRdkOHfhGiXKghFR6aCAJA2D0NgkHTYkA3@oXbWsAFsJk54Q5KdQw4P3dPluiTVsVaCFOYM0p3SN2opJ5JQmL@Ae8Rfp@pSZWFX@AZV3w8WS4T78Ixk4dErzz4glW7L1Ew)
```
def g(s:String,n:Int)={val a=mutable.Set[String]("");def f(n:Int,l:String=""):Unit=if(n>0)(1 to math.min(n,s.length)).foreach(i=>f(n-i,l+s.substring(0,i)))else a.add(l);f(n);a.size-1}
```
Ungolfed version
```
import scala.collection.mutable
object Main {
def g(s: String, n: Int): Int = {
val a = mutable.Set[String]("")
def f(n: Int, l: String = ""): Unit =
if (n > 0) (1 to math.min(n, s.length)).foreach(i => f(n - i, l + s.substring(0, i)))
else a.add(l)
f(n)
a.size - 1
}
def main(args: Array[String]): Unit = {
println(g("aaaa", 8))
println(g("abcdef", 10))
println(g("aerodynamics", 10))
println(g("disbelief", 10))
}
}
```
] |
[Question]
[
Given an 8086 segmented ("*logical*") memory address, output its actual linear physical address.
A segmented memory address has format `xxxx:xxxx`, where each of `x` is one of `0-9A-F`, and the two parts are parsed as hexadecimal integers. Both parts are exactly 4 digits.
To get its actual linear address, multiply the first part by sixteen and add the second part. You can return it in a reasonable format, e.g. integer or a length=5 string. You can choose whether to modulo the result by \$2^{20}\$ (like 8086, or 286+ with the [A20 gate](https://en.wikipedia.org/wiki/A20_line) closed). Yet input format is fixed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in each language wins.
Test cases
```
0000:0000 -> 0x00000
1111:1111 -> 0x12221
FFFF:0000 -> 0xFFFF0
FFFF:0010 -> 0x00000 or 0x100000
```
[Answer]
# JavaScript (ES6), 33 bytes
*-2 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
Returns an integer.
```
s=>eval(s.replace(/:|^/g,'0+0x'))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1i61LDFHo1ivKLUgJzE5VUPfqiZOP11H3UDboEJdU/N/cn5ecX5Oql5OfrpGmoaSARBYgQglTb2S/OCSosy8dA1DM01NBX19BYMKkIwBF5oeQyCwAhHY9RgaGRkZoutxAwI89oCkDXDoMcTnNoX8IpCVYPZ/AA "JavaScript (Node.js) – Try It Online")
Turns an input such as `"ABCD:1234"` into `"0+0xABCD0+0x1234"` and evaluates it as JS code.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 35 bytes
```
IFS=:;read a b;echo $[16*0x$a+0x$b]
```
Takes input from stdin and outputs to stdout
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kKbE4Y8GCpaUlaboWN5U93YJtrayLUhNTFBIVkqxTkzPyFVSiDc20DCpUErWBRFIsRClUx4KVhkBgBSIgAgA)
[Answer]
# [C (GCC)](https://gcc.gnu.org), 52 bytes
```
main(a,b){scanf("%X:%X",&a,&b);printf("%X",16*a+b);}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6FjdNchMz8zQSdZI0q4uTE_PSNJRUI6xUI5R01BJ11JI0rQuKMvNKwKJKOoZmWonaQLFaiF6oEQtWugGBlYGBoQFEAAA)
[Answer]
# MS-DOS .COM (386 instructions), 71 bytes
Takes input from the command line and prints the result. To convert each output character, I use a variant of [`AAM`](https://www.felixcloutier.com/x86/aam) that operates in base 16.
```
BE 82 00 E8 2A 00 8B DF 66 C1 E3 04 46 E8 20 00
66 03 DF 66 C1 CB 10 B9 05 00 8A C3 D4 10 3C 0A
7C 02 04 07 04 30 CD 29 66 C1 C3 04 E2 EC CD 20
66 33 FF B9 04 00 C1 E7 04 AC A8 40 74 02 2C 07
2C 30 03 F8 E2 F0 C3
```
TASM source:
```
IDEAL
P386
MODEL TINY
CODESEG
ORG 100H
MAIN:
MOV SI,82H ; Start of command line
CALL DECODE
MOV BX,DI
SHL EBX,4 ; Adjust segment portion
INC SI
CALL DECODE
ADD EBX,EDI ; Add offset
ROR EBX,16 ; Rotate address to point to first digit
MOV CX,5
LOOPM:
MOV AL,BL
DB 0D4H, 10H ; AAM 10H (base 16: AH=AL/16, AL=AL mod 16)
CMP AL,0AH
JL ASCADJ
ADD AL,7 ; Convert digits > 9 into A-F
ASCADJ:
ADD AL,48
INT 29H
ROL EBX,4 ; Next digit
LOOP LOOPM
INT 20H
DECODE:
XOR EDI,EDI ; Return register
MOV CX,4
LOOP1:
SHL DI,4
LODSB
TEST AL,40H
JZ DECADJ
SUB AL,7 ; Convert digits A-F to 10-16
DECADJ:
SUB AL,48
ADD DI,AX
LOOP LOOP1
RET
END MAIN
ENDS
```
Example results:
```
C:\WORK>segment FFFF:0000
FFFF0
```
[Answer]
# Excel (ms365), 37 bytes
[](https://i.stack.imgur.com/G7zZL.png)
Formula in `B1`:
```
=SUM(HEX2DEC(MID(A1,{1,6},4))*{16,1})
```
[Answer]
# x86 .COM, ~~64~~ 59 bytes
```
0100 BE 82 00 66 31 C9 66 F7-E1 B1 08 66 C1 CA 10 66 ...f1.f....f...f
0110 C1 C2 04 AC 3C 3A 74 F3-2C 30 D4 10 D5 09 66 01 ....<:t.,0....f.
0120 C2 E2 EC 66 92 66 99 B1-0A 66 F7 F1 66 85 C0 52 ...f.f...f..f..R
0130 74 03 E8 F0 FF 58 04 30-CD 29 C3 t....X.0.).
```
Thank Peter Cordes
for -5 bytes
```
org $100
mov si, $82
xor ecx, ecx
mul ecx
mov cl, 8
b: ror edx, 16
a: rol edx, 4
lodsb
cmp al, ':'
je b
sub al, '0'
aam $10
aad 9
add edx, eax
loop a
xchg eax, edx
p: cdq
mov cl, 10
div ecx
test eax, eax
push dx
jz q
call p
q: pop ax
add al, '0'
int $29
ret
```
Output decimal
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
\:/H16β
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiXFw6L0gxNs6yIiwiIiwiMDAwMDowMDAwXG4xMTExOjExMTFcbkZGRkY6MDAwMFxuRkZGRjowMDEwIl0=)
```
\:/H16β
\:/ # Split on colon
H # Convert each from hex string to int
16β # Convert list from base 16 to decimal
```
[Answer]
# [Python](https://www.python.org), 39 bytes
```
lambda x:int(x[:4],16)*16+int(x[5:],16)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY31XMSc5NSEhUqrDLzSjQqoq1MYnUMzTS1DM20IQKmVmABqPLsgiKQcEZqhUaahroBEFiBCHVNTU0uFClDILACEZhSbkCAQxdUyhAsBbFywQIIDQA)
[Answer]
# [Raku](https://raku.org/), 31 bytes
```
*+<4+*o{m:g/\w+/».&{:16(~$_)}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfS9vGRFsrvzrXKl0/plxb/9BuPbVqK0MzjTqVeM3a2v/FiZUKSirxCrZ2CtVpGkAxvaTE4lQNQzPNWiWFtPwiBRsDILACEQqGQGAFIhTcgAAiBmUZGtj9BwA "Perl 6 – Try It Online")
This is two anonymous functions composed together with the `o` operator. The first, `* +< 4 + *` returns its first argument shifted left four bits (ie, multiplied by 16) plus its second argument. The second, enclosed by braces, extracts the two hexadecimal substrings (`m:g/\w+/`) and parses them into integers (`:16(~$_)`).
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
q': ÔËnG *GpE
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=cSc6INTLbkcgKkdwRQ&input=IkZGRkY6MDAwMCI)
Output is an integer. [This](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=cSc6INTLbkcgKkdwRQ&footer=IjB4IitVeCBzRyB1&input=IkZGRkY6MDAwMCI) version includes a footer which translates to the format in the test cases (No modulus, so it outputs `0x100000` for the last test case).
Explanation:
```
q': ÔËnG *GpE
q': # Split input where the character ':' appears
Ô # Reverse the array
Ë # Map:
nG # Treat the string as a base-16 number
* # Multiply with
GpE # 16 to the power of the current index
-x # Output the sum of the resulting array
```
[Answer]
# [Factor](https://factorcode.org/), 35 bytes
```
[ ":"split1 hex> swap hex> 16 * + ]
```
[Try it online!](https://tio.run/##LY2xCsIwFEV3v@LSUaE0i0MER8XFRZzEIZSnLbZp8vIkivjtMW09w@FylnsztQyczqfDca8RXNeKtPaO3khTOsOBGA9iS92U4JhE3o5bK/ARgfyTbE0Bm4WPH1QZPQoqo0dhl5nbf6kK33RBoYvpT6Gh1xYhGjcvtcYSK1xTn0uZfg "Factor – Try It Online")
```
! "1111:1111"
":" ! "1111:1111" ":"
split1 ! "1111" "1111"
hex> ! "1111" 4369
swap ! 4369 "1111"
hex> ! 4369 4369
16 ! 4369 4369 16
* ! 4369 69904
+ ! 74273
```
[Answer]
# [Python](https://www.python.org), 53 bytes
```
lambda x:int((s:=x.split(':'))[0],16)*16+int(s[1],16)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3TXMSc5NSEhUqrDLzSjQ0iq1sK_SKC3IySzTUrdQ1NaMNYnUMzTS1DM20QfLF0YZgPlRzdkERSDQjtUIjTUPdAAisQARQnyYXipQhEFiBCEwpNyDAoQsqZQiWgli5YAGEBgA)
Returns an integer (ok as per OP). Footer on ATO converts to hexadecimal.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 [bytes](https://github.com/DennisMitchell/jelly)
Jelly has no built-in standard hex string conversion functions :/
```
ØHiⱮ’ṣ-ḅ⁴ḅ⁴
```
A monadic Link that accepts a list of characters (as defined) and yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8///wDI/MRxvXPWqY@XDnYt2HO1ofNW6BkP///1c3BAIrEKEOAA "Jelly – Try It Online")**
### How?
```
ØHiⱮ’ṣ-ḅ⁴ḅ⁴ - Link: list of characters, S
ØH - hex-characters -> "0123456789ABCDEF"
Ɱ - map across c in S with:
i - first 1-indexed index of c in the hex-characters or 0
’ - decrement (vectorises)
- - literal -1
ṣ - split the ØHiⱮ’ result at -1's (this is what ':' will have mapped to)
ḅ⁴ - convert from base sixteen (vectorises)
ḅ⁴ - convert from base sixteen
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
⍘↨E⪪S:⍘ι⊗⁸⊗⁸⊗⁸
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMpsTg1uATITAczNXwTCzSCC3IySzQ88wpKS6BSmjoKSlZKQBJJeaaOgkt@aVJOaoqGhaamJgoPVcr6/38zILACEf91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
⪪ Split on
: Literal string `:`
E Map over parts
ι Current part
⍘ Convert from base
⁸ Literal integer `8`
⊗ Doubled
↨ Convert from base
⁸ Literal integer `8`
⊗ Doubled
⍘ Convert to base
⁸ Literal integer `8`
⊗ Doubled
Implicitly print
```
Consecutive integers would require a separator so I double `8` instead of using a literal `16`. (The first one doesn't need to be double `8` but I wanted to be consistent.)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 87 bytes
```
:
0¶0
O#$`.
$.%`
¶
M!`..
[a-f]
55$&
T`l`d
.
$*
+`¶1{16}
1¶
1{16}
%M`1
T`d`l`..
b\B|¶
```
[Try it online!](https://tio.run/##LYsxCgIxEEX7fwsxEVkxZJCsmNLGarGxU2F2iQFBthA79Vo5QC4WJ6yv@Hz@vHneXvexL3p54OJhc7I4zhUbKKMZOQHdjI3BuV/HK5xTC5z4wQFiNFhxTvSm9gsSdWrQHZNIQTR5HC77j9xKsYKvARJ8DURh2v6NLFrB1wC5XfCb7RB/ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
:
0¶0
```
Replace the separator with a newline, but also suffixing a `0` to the first number and prefixing a `0` to the second number, reducing the problem to hexadecimal addition.
```
O#$`.
$.%`
¶
M!`..
```
Transpose the digits.
```
[a-f]
55$&
T`l`d
.
$*
```
Convert each digit to unary. As they are now transposed, each line now corresponds to the sum of the two digits in unary.
```
+`¶1{16}
1¶
1{16}
```
Propagate carries, but drop the 20th carry (allowed per spec).
```
%M`1
```
Convert each resulting "digit" to decimal.
```
T`d`l`..
b\B|¶
```
Convert each decimal number to a hexadecimal digit and join everything together.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 23 bytes
```
Uo{aFB16*16E Do}MSa^":"
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCJGIGEgW1xuW1wiMDAwMDowMDAwXCJdO1xuW1wiMTExMToxMTExXCJdO1xuW1wiRkZGRjowMDAwXCJdO1xuW1wiRkZGRjowMDEwXCJdXG5de1dHIFAoe1xuICIsIlVve2FGQjE2KjE2RSBEb31NU2FeXCI6XCIiLCJ9VmEpVEIxNlxufSIsIiIsIi1wIl0=)
I couldn't quite figure out a nice way to multiply the first part by 16, I'm sure @DLosc will be able to save the day
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 40 bytes
```
i;f(s){sscanf(s,"%x:%x",&i,&s);s+=i<<4;}
```
[Try it online!](https://tio.run/##ZY7RCsIgGIXv9xQiOLQ5cNDV3G57hqB2IZL1Q1nMQYOxV890WzXou/g9fBzh6PystfcgDXVscE4rGxLHpC9Jj3kKPHVMuqyGqtrK0YPt0E2BpSwZEhTQF9VuUHdy3aFBNZplBItAGQ/mP1kEynjWchf4ay6yWEsxpVFOj7m3iMY9UAs5L4BGIsgy9v3waEPBUExc2CZ6sj9azD9djgxdImMyGf1Lm6s6O58/3w "C (gcc) – Try It Online")
[Answer]
# [R](https://www.r-project.org), ~~44~~ 36 bytes
```
strtoi(scan(,"",,,":"),16)%*%c(16,1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN1WKS4pK8jM1ipMT8zR0lJR0dHSUrJQ0dQzNNFW1VJM1DM10DDUham8xphsAgRWI4OKC6lMyqADxDZQ0uZSJB1zE2MplCARWIALZNkMjIyNDWtjmBgQYfgMJ0sRvUNsMUWwzhAYlJLxhcQQA)
[Answer]
# [Perl](https://www.perl.org) `-aF:`, 29 + 4 = 33 bytes
```
print 16*hex($F[0])+hex $F[1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kILUoZ0W0km6im5VS7IKlpSVpuhZ7C4oy80oUDM20MlIrNFTcog1iNbWBTAUg0zAWogaqdMFKQyCwAhEQAQA)
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 7 bytes (14 nibbles)
```
`@4.`=$\$Nhex
```
Outputs decimal address value.
```
`@4.`=$\$Nhex
`=$ # chunk the input by
\$ # its character class:
N # is it alphanumeric?
. # now map over the 3 chunks
# (the middle one is ":")
hex # get hex value
# (value of ":" is zero)
`@4 # and convert the 3-element list
# to base-4
```
[](https://i.stack.imgur.com/z8FL0.png)
---
For the same bytes, we could also explicitly split `%` the input on the string `":"`, and convert from base-16, similarly to some other answers:
``@16.%$":"hex`
[Answer]
# [Go](https://go.dev), ~~83~~ 80 bytes
```
import."fmt"
func f(s string)int{l,r:=0,0
Sscanf(s,"%x:%x",&l,&r)
return l*16+r}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RU_BasQgFLz7FSJkia1dNNBShL32vNBj24OEGKSJCWpACPslvYSFvfUn-hn7N31vE9o5vMHRN-N8ndth-R5N_WnahvbG-cuU7MPz9ej6cQhpz2yfGLGTr6ktI40pON9y59PciaAPUkjyGmvj4VKwIusiM7HrxC5wEpo0BU-7O_V0H06b78_NCoNKTmdSm9hEqg-gjG-r-QeaEyYBGgfTMiNLQZgCaBwoqqqqFIgvgL-XeJD_orqJats_ETsEGoXDxGA8VF4_MJMjRCdbsiJSmQv5mDd690zghoCCnIPDVmRZVv4F)
Very similar to the other answers with some sort of `Scanf`: Look for 2 hex numbers, put them into variables, and return the result.
* -3 bytes from @Steffan: `var l,r int => l,r:=0,0`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
':¡H16β
```
Outputs as an integer.
[Try it online](https://tio.run/##yy9OTMpM/f9f3erQQg9Ds3Ob/v93AwIrAwNDAwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/datDCz0Mzc5t@u9in6GkoGFQcXi/ppLO/2glAyCwAhFKOkqGQGAFIoBsNyCAiUPZhgZKsQA).
**Explanation:**
```
':¡ '# Split the (implicit) input-string on ":"
H # Convert both strings in the pair from hexadecimal to base-10 integers
16β # Convert this list to a base-16 integer
# (which is output implicitly as result)
```
[Answer]
# [Arturo](https://arturo-lang.io), 44 bytes
```
$[s][+*16from.hex take s 4from.hex drop s 5]
```
[Try it](http://arturo-lang.io/playground?yvmCST)
[Answer]
# [Python 3](//docs.python.org/3.8), 42 bytes
Python translation of [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s JavaScript solution
```
lambda a:eval('0x'+a.replace(':','0+0x'))
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSHRKrUsMUdD3aBCXTtRryi1ICcxOVVD3UpdR0HdQBsoqqn5v6AoM69EIw2oCAisQARQlAsuaggEViACRTQNCDDVQkUNQaL/AQ "Python 3.8 (pre-release) – Try It Online")
] |
[Question]
[
>
> You are *James* and **four** of your friends (*Bjarne*, *Eich*, *Rossum*, *Ada*) are called for an interview. There are **n** interviewers, and they can *each serve one* person at a time, **alphabetically**. Each round of interview takes **20** min.
>
>
>
Let's take **n = 2**,
>
> So, the first round started with *Ada* and *Bjarne*, takes 20 min (they're handled simultaneously). Then, interviewers call persons for next round, who are *Eich* and ***James***, they took another 20 min.
>
>
>
Hence, finally you're out after 40 min.
---
# Challenge
Given an array as input like `["yourName", [an, Array, Of, Friends], numberOfInterviewers]`, your task is to output the time it'll take for you to complete the interview, in minutes.
Feel free to take three arguments as input, instead of the array.
### Sample I/O:
(`In = Out` format)
```
[ "James", ["Bjarne", "Eich" , "Rossum", "Ada" ], 2 ] = 40
[ "Stark", ["Steve" , "Tchalla", "Banner", "Scott"], 3 ] = 20
[ "spam" , ["bar" , "eggs" , "foo" , "lorem"], 1 ] = 100
[ "Oggy" , ["Jack" , "DeeDee" , "Marky" , "Bob" ], 10 ] = 20
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes will win!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~40~~ 39 bytes
*-1 byte thanks to @JonathanAllan!*
```
lambda s,l,n:~sum(x<s for x in l)/n*-20
```
[Try it online!](https://tio.run/##TY89T8MwEIb3/oqTFxJkShqYKjJQYKmEkChby@AmlzTUX7Ldql346@GcpCqWP87v3fv4bM9hZ3Te1cWmk0JtKwGeS67nv/6gktOTh9o4OEGrQab3@vYuz7pWWeMC@LOfxKRsNcY83ac@VK2eTwCSnpJywJPFMmAFBShhEzwKyXvL1FvZhoQVLE3J4NAfZKCqerSSZl2rw5jh41kUF2K3BrYUCj3jsGaLH@E0Usje2nLHgAbFn8bTP6L6XAkSvznktFOyoPWYTYixCsLte8Yq4BFZ9H3dvOyElCI6F0JrdDFalSYERoyHKyPvGd4KFY1rthWODW9j0/hLH7UxoyqNQxUZsytjlvWQj6Y5D5ClKPesL39FpDnE79RnX8AWZjt8Zpb9a@QP "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), ~~44~~ 40 bytes
```
(s,a,n)=>-~(a.map(S=>k+=s>S,k=0),k/n)*20
```
[Try it online!](https://tio.run/##Zc89T8MwEAbgnV9h3UIMbvMBayIRYKmEkAhbxXBNL26bxI5sU4mFvx7sJF2o5eHVyX703gnPaGtzHNxK6T2NTT5GVqBQPC9WvxGuexyiKi/a@9wWlWjzhIs2VvwuS8ZaK6s7WndaRk0EG@zJgmBbKE9oFPkIr8f6AMwfnz@0td99mD7t0Q@/BMsY5yyO2WNy8w@rHJp2wipHZ4IAfN4@H7DrMBAlKkUmpKrWzoHHHhYsu8LsgH0QtrBDA3MbktJemjVaL9NOG@oDli5Ymlxp71L@zNoG6xamfy9E/s75zTefHkCpd/OeaXKpNv4B "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~50~~ ~~49~~ ~~33~~ 32 bytes
*Edit: -1 byte thanks to Robin Ryder*
```
function(y,f,n)sum(f<y,n)%/%n*20
```
[Try it online!](https://tio.run/##lc@xTsMwEAbg3U9RGVWkKBJp6EgGCiyVEBJhj67uOTWNz8h2KvnpwyWwZGCIdNL9y/2fzg/RWGx6iqZrTAwNdF3jruirQfekonGUpVzntAm9zfRj4rS@X9NdWQzJ9ZU8gMUghfYG6RQqlcn9F3hCmctXo868PlzgWw5PJ5AbQVUpbla7QvwDZ1yb/9UxJsTE1BH8ZcbUEa@j8nn7fOZb4LgHIvQcauVinKwHtsqFVvgGO6OOwKUriW0bxq2dY6NzHu1kbNnYFguR97ZNM@QA6sK1L4g8HN744TQ@5Y6/SrHsleEH "R – Try It Online")
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 23 bytes
```
(*Xgt*).sum div*×20+20
```
[Try it online!](https://tio.run/##RY/RSsMwFIbv9xSHc6Gujq6t4o1UWHU3QxGsiDC9OOtOs7qkGUkdFHwPH8gH65JWZ0jg58/5v/zZsZFXnWrhpIS0OwteRROMQ/upYF3tg5/vJDpPou56ZKmFEr7UNAzGN2/pNJy/zO6h1AZkVbPtABek2OIElph9kKnZSZxXxQbBLaeftHVY787W5Mz3CST@ClJ3LqMRYN6Q2faEvOE9o089n95uSEryuYzqmo1XeaGbBh3h4khIPMHuSPnYEldkcHiXhbB/HUqtf12pDStPiI@EOPKIRyHaAbGgYov98B2z24N@cB37Acz0avhGHP2XOAA "Perl 6 – Try It Online")
Gets the number of other people before us in the queue, integer divides that by `n`, adds 1 and multiplies by 20.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṭṢi³N:⁵×-20
```
A full program accepting arguments `name`, `friends`, and `n` which prints the result.
**[Try it online!](https://tio.run/##y0rNyan8///hzrUPdy7KPLTZz@pR49bD03WNDP7//6/klZibWqz0P1rJKSuxKC9VSUdByTUzOQNEB@UXF5fmgliOKYlKsf@NAA "Jelly – Try It Online")**
### How?
```
ṭṢi³N:⁵×-20 - Main Link: name, friends
ṭ - tack (friends to name)
Ṣ - sort
³ - 1st program arg = name
i - (1-based) index of (name in sort result)
N - negate
⁵ - 3rd program arg = n
: - integer division
-20 - minus twenty
× - multiply
- implicit print
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~53~~ ~~45~~ ~~44~~ 43 bytes
```
lambda a,b,c:~sorted([a]+b).index(a)//c*-20
```
[Try it online!](https://tio.run/##Tc49T8MwEAbgnV8R3dKYBvq1VerQAEslhETY0g5n5/LRxnZkG0QX/nqwk7aq5eHVq3t0151drdWqLzf7vkXJC4ww4YlY/1ltHBVxjocpZ8@NKug3Rjabicen5bzvTKNcXMawQ0kWkiiH9IhGkY/w1ogaIv98/tTWfsvQbgv05SGJlow93Hzm0JwGnzn6IQjma/JSY9tiUCkqRSakTGjnwPvVvbcdyoBy4Ghg3ElVZa/7S60vbasNyeAX9/6jqs6j36E4wTD5SuT/mN/9ecMApJqP9y/mjPX/ "Python 3 – Try It Online")
Adds your name to list of friends, sorts the list and calculates the answer from the index of your name in the sorted list.
*Special thanks to Jonathan Allan for -1 byte*
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 40 39 38 31 bytes
```
->a,b,c{~b.count{|i|i<a}/c*-20}
```
-5 -1 byte from petStorm.
-1 byte from Rahul Verma.
-7 bytes from Dingus.
[Try it online!](https://tio.run/##Rc5Na8MwDAbge3@F0aUw0vVj166wdLsUxmDZLewgu8pHm8TFdgYh7f56JscdMcK8CD1IppXdkD0Pix1GMlL9r3xUum1cfy2v5RZvS/Ww2Kxuw0VkqYAD1mQhEinEJzQNcYS3UhUg@HH@1Na2te@@HJGb35HY8D8LOnFozqNOHP0QePE13xdYVehNjE1DxqdEaeeA9dOk7QVrT1KQaCDsozy3/7szre/dShuqvV5P@iPPu6APqM4wzr0ScYX8zqeNAxBrGS5fr1jPhj8 "Ruby – Try It Online")
# [Ruby](https://www.ruby-lang.org/), 83 bytes
```
->a,b,c{(b.push(a).sort.each_slice(c).map{|x|x.include?(a)}.find_index(true)+1)*20}
```
[Try it online!](https://tio.run/##Rc7fT4MwEAfw9/0V5F4ExWbMZzWiviwxJuIbMctRjh8OKGmLYdn2t@MVNGva5pvLfXKnh@wwFffT7QOGWSiPfib6wVQ@BsIobQWhrHamqSX5MhAt9sfTeBpF3clmyOmR@86iqLt8x49G3@qBgpsouN6sz1PvFakHW2zJQOilEH@j7ogjvNayAo8P5w9lzNC66lOOXPwKvQ3/q0UnFvV@1omlHwInPq@eK2wadCbGriPtUiKVtcD67qJNj60jKWSoYZlHZWn@ZxdK/VUbpal1Orro97I8LHqLcg9z3wsR3yW/8WpzA8QqWzaP1qxX0y8 "Ruby – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), ~~56~~ 55 bytes
```
|s,l:&[&str],n|20+l.iter().filter(|x|*x<s).count()/n*20
```
[Try it online!](https://tio.run/##ddBBT4MwFAfw@z5F1wNpJ0FATyoHiV6WGBPxZnZ4sAfDlda0xcyInx0LSLKY0DTNv6/NL33VrbF9KUkDtWScfK8IEWhJSRLSd8YXN96bZ6ze@bKLwwsR1BY140FZiyF0p25zujM8KFQrLeOXchOHPXHjdjWsYAxqu2b7vFqzknl0Cw0a6hOn0vQdtMRhQx/r4kDd/SG/KGPaZizf78FVdz6JCefuOEncch3yBTyzoI9/eGbxE@kIvhYHEAJGMQUpUY8xK5S11OFXZ3i8iJsPaEbP4Tno@bVYVWbOpVJzFEpjM@DRGR6Fi/pzVX3N@haKI52YB0Q3pzaeXHPTHZqqfPqXKPz39J/@Fw "Rust – Try It Online")
*Special thanks to user and madlaina*
This is my first ever code golf so I hope I have the format correct!
[Answer]
# [Io](http://iolanguage.org/), ~~48~~ 45 bytes
```
method(s,a,n,((a select(<s)size+1)/n)ceil*20)
```
[Try it online!](https://tio.run/##XY9PSwMxEMXvfophLiYasFtvUg@ueimI4Hr0Mk1nd2PzpyRR0C@/Jl210CGHN495P15MmHq4uYW3yXEew1YkRcorIQgSW9ZZrJJM5psvG3nlpWZjL5YLOfUC1@Q4oQJrUhbYvlP0XFZ8NHpEKFP0S0jpw1X3bkvFlAqWIGEfjc/Wn/UCsMsUd/@YLvMnY42@nt@PZC3VcEvec6yq0yFnLJhrOOGkPbkanDkbijhX4GFIf3X6EH5dGyK7ymlOOc/D8HXkrEnv8JB4YC5v1k@l8uEI27CZv9UsjpzpBw "Io – Try It Online")
## Explanation
```
method(s,a,n,(( // Take 3 arguments.
a select(<s) // Take all items in the array a that is smaller than s
size + 1) // Take the size of that, and add 1
/n) // Divide it by n
ceil * 20) // Take the ceiling of that, multiply by 20
```
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
20*1+(<.@%~0 i.~/:)
```
[Try it online!](https://tio.run/##HczLCoJQFIXhuU@xCeJkF9OaaUHZZSBFkD3A3trWNPXEORY08dVNg/XPPlbeDiyRwNoFAVOwwe2aWbC7no7twh47k9HK2gwbGzKrmbtma7YLgAREQCVr4YGfk6oYD1n8wKvU@l3i9k7G8o/CmtSzQ2HNH8bb7kFFQehTVbHCMJZ1bTh/qF9UCvAgIoWcphoTKbGQikvDsXtwSdNvDwKKn7hn7obn7vyLvox@ "J – Try It Online")
### How it works
```
20*1+(<.@%~0 i.~/:)
/: ascending indices for sorting
0 i.~ find your name
%~ divided by interviewers
<.@ and floored
20*1+ +1 then *20
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E) , 16 bytes
```
R`©¸«{®QsôOƶ20*O
```
Explentation:
```
R`©¸«{®QsôOƶ20*O
R Reverse input
` Push input to stack seperatly
© Store your name in register C
¸ Listify
« Merge lists (add your name to the list of names)
{ Sort
® Push your name
Q For each element; is it equal to your name?
s Swap (n on top)
ô Split list of names into n chunks
O Sum each element
ƶ Lift a, multiplying each element by its index
20* Multiply by 20
O Sum for the result
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/KOHQykM7Dq2uPrQusPjwFv9j24wMtPz//49WUPJKzE0tVtJRiFZyykosyksFMpVcM5MzlBQUFIDMoPzi4tJckKBjSiJQLFZHwQhIAgA)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 [bytes](https://github.com/abrudz/SBCS)
```
20×⌈⎕÷⍨⊃⍋⍋⎕
```
[Try it online!](https://tio.run/##HY1BDoJADEXXzinczcoE8QSibkiMiXiBgsOgDgyB0YS1C4kKO@IVvIEH4CZzEWxJmvbn9/UXcjU7VqC0HGz9iAfX6T/2Xdu263@2@drn3TYvqrYjYJjEjPuQipJPuXeGIhMoNqcowbHXZXlNUSyPwJnLiA0MFBe0AiNuhB5WCSgFdA1ZJgpaRdoYzhYjX@ZACSHQRkhJf2KtsStdiJSz@YjtpKzQ8yGi8LUQWCi2@Ix8T4dIOn8 "APL (Dyalog Unicode) – Try It Online")
Full program that takes the names and the value of n from stdin.
### How it works
```
20×⌈⎕÷⍨⊃⍋⍋⎕
⎕ ⍝ Take first input (names)
⍋⍋ ⍝ Rank the names alphabetically; A E C B D → 1 5 3 2 4
⊃ ⍝ Extract the first number
⌈⎕÷⍨ ⍝ Take second input (n), divide above by n, and ceiling it
20× ⍝ Multiply 20
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
Iײ⁰⊕÷ΣEη‹ιθζ
```
[Try it online!](https://tio.run/##FYy9CsIwFEZf5ZLpBiJIVyf/hhYFUbficEku9EqTapJ28OVj@g2Hwxk@O1C0E42l3KKEjEdKGZ/iOWGzNdAGG9lzyOywDfkkizjGx@zxSh8cDFw4JRQDX621gZ9etyulB9VRPVEGenV4UwxcVZ3FDgoAqt6nlGa/xr2j2l4GmsqyWcY/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
η Second input (array of friends)
E Map over array
ι Current friend
‹ Alphabetically precedes
θ First input (your name)
Σ Take the sum
÷ Integer divided by
ζ Number of simultaneous interviews
⊕ Incremented
× Multiplied by
²⁰ Literal `20`
I Cast to string
Implicitly print
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 68 bytes
```
l;f(p,n)char**p;{for(l=0;p[++l]&&strcmp(*p,p[l])>0;);n=20+--l/n*20;}
```
[Try it online!](https://tio.run/##hVBbS8MwFH7frzgEHOmaYTaHD8YJDn0RRHC@1SJZl3ZxaRqSqsjob59JVi97EhJy@G7n5BTjqij2e8VKbIhOig23o5Fhu7KxWM0pM1maqnw4dK0taoNHhphM5ckVZQnT8ylNx2N1qkdTyrp9zaXGCewGMQU0r4XLZnl2nsPcowA7dBcwRAAtXrnVIlS3stggAPDlY@PcWx3A6zVHAaIdib5ly@02EMtWvAsUxE@@i1I8hnGthY100bQt@vU5w@uoXnHbNxFV5fqybJq@Uo0V9R/fQ1V9Rt8dL7ZxEnQjhD8RvPfDHOhFs/qZs2MDqVvwV9h3KT6EDb8PX4cpOSMTMqHQaz64bL@5GSVT6rnwBN5vHnAM8jRl/rmEGYM0lUlcYqBeQoCnS3xYsszJcV@ZJyxoS8Cxl/S95gdb4nEAY72@xMhw5y7gZA34ZJ08a7@CKCLQ22KMUE4cuUou1T@ubtDtvwA "C (gcc) – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 54 bytes
```
(m,l,q)->l.filter(x->x.compareTo(m)<0).count()/q*20+20
```
[Try it online!](https://tio.run/##ZVJNj9owFLznVzwhreRsjQv0VrZIi9pDV9uutOFW9fAITjD4I9gOC6347fSRD1pUKU7s8cy8if02uMfhZrU9K1M5H2FDa1FHpcX9NPkPC9FLNJetXGMI8A2Vhd8JgLJR@gJzCQtlpG8wAO1sCZEAlkWvaG44ZI3FQwvMQPOLFnY12qjiMZ2S8JTQq6qXWuUQIkb67J1agaFqndOPn4C@DGlXqC0am/cnODPDNd@lw5kWhdKUjB2Gs4PInanQy4VjJn0YpbSubWTp@939ZPRuMjpPG689egg5Wtt4WfkGWbti2TFEaYSyact8WystgXVkscbwXR7is7KSpX2y1k8TRmaP3uMxCAzPKsSrzl5FIlRaRTbgMEi7Gq3eXNQXE1HKyEY3e/3REeMr3UJJjnvUtXwp2FXRTIL6RTWG41vrwitpV6H3D/WyCTfmcCvqNd0huDqKim4iFmxwFzg0Y/WRxp2l/Eby3plfE/L2hkTTEf8wurZi6V9qn/HUtMPp/IRGktN8g96S8IvK1xxeXQg1tdTjCjlMkiyi314aTO6JssjXqDVtzJtTJjx3MXL4kIQKSbREwmRZkmvhHP2t85LgcfJSlpT0CXPy@iwlPZz63G8JnLslMUZ/AA "Java (JDK) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ª{¹kI÷>20*
```
[Try it online](https://tio.run/##yy9OTMpM/f//0KrqQzuzPQ9vtzMy0Pr/3ysxN7WYK1rJKSuxKC9VSUfJNTM5A0gF5RcXl@YCGY4piUqxXEYA) or [verify all test cases](https://tio.run/##JY3NCoJQEIVfRWYZd6G2T5LaCBFkQSBCo01q/tzwmiDte4DeohZt29ub9CI2F2GYOcN854xUGGU0tJ0Dxu/@MMDpDrv@OfSvW//O99/PzDYngxiCIAD3jHVFIGCZxSmPjVTqWrKYHxFCAR6WpEDYoTCY9htqNbyNUywKZOViVVHNwo9l02iH32Cdg5iOjgj1kZKEQ@AkJfdC1lRqUl2QP1kj6GHMLlgQcbFYcUqnH8hIs@sk4c0yw/AP).
**Explanation:**
```
ª # Add the first (implicit) input-string to the (implicit) input-list
{ # Sort the list alphabetically
¹k # Get the 0-based index of the first input in the sorted list
I÷ # Integer-divide it by the input-integer
> # Increase it by 1
20* # And multiply it by 20
# (after which the result is output implicitly)
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~29~~ 23 bytes
*Saved 1 byte thanks to Rahul Verma*
```
y=>_.count(_<y)/_*20+20
```
[Try it online!](https://tio.run/##pdDfT4MwEAfwd/6KS59aJcrQp0WWbNEHFxcT8c2Y5daVjg1aQrtFYvzbsfyYG6@OELheuE@Or@GYYa1XW8EtLDBVIL6sUGsD06KAb@@AGcgxxLZMlYRoAvQlNfajO3/68Kwsa9ruDVFdRZPlDdd7ZenyoWK3y6swuA6Dei0SSGh1dHzAMQwdNe4pkLRiFF2HeR4aI0pLE0rmmAtD/HaKktkWSyXckTylfEPAXa5@08bs86Y7XaNrMh9C94QogvuAnWGxxXL3h8VWHARpgHe@wSzDRpihUqJsqphra4mz7norHFimwLwZ7qwVlqRbRkhpjoslWvfdTJcib7BRj42CgfYqZXXS5sh3pJ17FMLdXb1wy7cfkZledb85Ck6reYWL1GbqwtTYufP/wAbMBVkNnAtScvn81L8 "Scala – Try It Online")
Accepts `(y)(a, n)`. `y` is a `String` representing your name, `a` is a `List[String]` with your ~~competitors'~~ "friends'" names, and `n` is an `Int` representing the number of interviewers. The function is pretty straightfoward - it just finds how many friends will go before you (plus 1 because you're going to go too), divides that by `n` (rounding up), and multiplies by 20 to get the total time.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes
```
20⌈{#}~Union~#2~Position~#/#3⌉&
```
[Try it online!](https://tio.run/##Pc7RasIwFIDh@z1FSMGLUdDVyzGo4m6EoazuAY7ZaRttkpFEQUp6PcGn9EW6nDAMgfNf5CNHgW9RgZcCxpq9jcXsfvvtszB8aWn0kBXD1jjpU0@z@f12nYxbK7Uvn2tWliXrn1g8PV@DQsfzWMsDWI0x@bsULc1P49xJUS2@gYecFSH/Z5UHe0ys8nhOaida6DqgXILWaKkqYbwnOn9Q9wMqyT2kJ9g0tACvjaHRGYuKxMtDbJrmksQaBH3KV4jxUn3ENS7pS7NPaBbC6/gH "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes the three arguments in order and returns `{{x}}`, where `x` is the desired number of minutes.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
èsl=j/üI*
```
Inputs in the order and format `"myName" numberOfInterviewers "an","Array","Of","Friends"`.
Assumes the names only contains letters. Will delete and fix it if they can contain digits as well.
[Try it online.](https://tio.run/##FY7PCsIwDIfvPkXJUQT/nT049KAggvMFspp1bu0qbRX2Rj6Etz1Y/Q1C8pF8JHGcGuNtnfP4jXbXLsffaZ4zndlJJLVRVLQceqEFHZ@6Qbn5GN8OsH8wzahMHDpSWwWSz@TddcPWMqjgvpcAKLVPCXJ8sSO1VlTx1BZjIkrtPbL1QRycqzEDnJXCD7rD4CCCAFxwaZjW@or@)
**Explanation:**
```
è # Push all inputs as single string array
# i.e. "Oggy" 10 "Jack","DeeDee","Marky","Bob"
# → ['Oggy','10','Jack','DeeDee','Marky','Bob']
s # Sort this array alphabetically
# → ['10','Bob','DeeDee','Jack','Marky','Oggy']
l # Push the first input as string
# → ['10','Bob','DeeDee','Jack','Marky','Oggy'] and 'Oggy'
= # Get its 0-based index in the array
# → 5
j # Push the second input as float
# → 5 and 10.0
/ # Divide the index by this float
# → 0.5
ü # Ceil it to an integer
# → 1
I* # Multiply it by 20
# → 20
# (after which the entire stack joined together is output implicitly as result)
```
] |
[Question]
[
**NOTE**: The winner of this competition is [Jack](https://codegolf.stackexchange.com/a/172123/82007)!!!. No more submissions will be accepted.
[Here](https://chat.stackexchange.com/rooms/83075/reaper) is the chat room for this [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") challenge. This is my first one so I'm open to suggestions!
Reaper is a game concept developed by the Art of Problem Solving which involves patience and greed. After modifying the game to fit a KOTH style contest (Thanks to @NathanMerrill and @dzaima for your suggestions and improvements), here is the challenge.
The game works as the following: we have a value known as the Reap that multiplies by a given constant every tick. After each tick, each bot has the option of "reaping", which means adding the current value of Reap to one's score, and reducing Reap down to 1.
However, there's a fixed number of ticks that a bot must wait in between "reaps", and a fixed number of points necessary to win the game.
Simple enough? Here are your inputs:
# I/O
You are to write a function in Python 3 that takes 3 inputs. The first is `self`, used for referencing class objects (shown later). The second is the `Reap`, the current value of the Reap that you would earn if you were to "reap". The third is `prevReap`, a list of the bots that reaped during the previous tick.
Other objects you can access in your function:
```
self.obj: An object for your use to store information between ticks.
self.mult: The multiplier that Reap is multiplied by each tick
self.win: The score you need to win
self.points: Your current set of points
self.waittime: The amount of ticks that you must wait between reaps during the game
self.time: The number of ticks since your last reap
self.lenBots: The number of bots (including you) in the game.
self.getRandom(): Use to produce a random number between 0 and 1.
```
You **MUST** not edit any of the contents of these objects, except for `self.obj`.
You must output `1` to reap, and anything else (or nothing) to not reap. Note that if you reap when you haven't waited enough ticks, I'll ignore the fact that you have chosen to reap.
# Rules
The parameters I will be using are `winning_score=10000`, `multiplier=1.6-(1.2/(1+sqrt(x)))`, `waittime = floor(1.5*x)` where `x` is the number of bots in the KOTH.
* The game ends when a player (or multiple) reach the winning score.
* When multiple bots ask to reap at once, priority is given to the bots who have waited longer(in case of ties, the bots that have waited the max time all are allowed to reap and gain the points in the Reap)
* Your bot must take no more than 100 ms on average across 5 ticks.
* If you want to import libraries, ask! I'll try to add any libraries that I can run on my desktop version of Python (math is already imported: feel free to use it)
* All of the standard loopholes for KoTHs, such as duplicate bots, 1-up bots, etc, are similarly banned.
* Any bots that use any sort of randomness must use the `getRandom` function I've provided.
You can find the controller in the TIO link below. To use it, add the name of your function to `BotList` as a string, and then add the function to the code. Modify `multiplier` to change what the Reap is multiplied by each tick, modify `winning_score` to change what score is necessary to end the game, and modify `waittime` to change the number of ticks to wait between reaps.
For your convenience, here are some sample (and rather silly) bots. Submitting bots similar to these will not be permitted. However, they demonstrate how the controller works.
```
def Greedybot(self,Reap, prevReap):
return 1
def Randombot(self,Reap, prevReap):
if self.obj == None:
self.obj=[]
self.obj.append(prevReap)
if self.getRandom()>0.5:
return 1
```
For those interested, here is the Controller with the 15 submissions built into it: [Try it Online](https://tio.run/##1Vpbb9s4Fn73r@A4GESyHdV2651OEHUwly12Fp0L0gL7YBgexqZjJrLkoaSk3kV/e/cc3iRKlJN0Aiw2KGpbJM/lO1eS2h@KbZZOP3/mu30mCiJous52hOZEpD39bEeLbe/kl2zNNwdSbFnOSJGREj@2jKyytBBZkjDR@yEr3vG8IDGZn/6DivWP2eno9IdMsDV8Fq8K@X@KH7fsjqf4k4prhg/YHROHJT6i8I1es@VNxuDX@5TvmYAv14LvloJR9evvOH02hm//pKtb@NixPEdmrCiYuJRKwM/vFS1xukDZfuIrlO0//HxMNpkgnPCUaJk/9e55mvL0epmvQGCYNhnDX29XJgXfJ5yJeBL97SyYRNMXwWSIkET5n6IIEpYGmkYIf717youC71jM0wJmzwbOhF5vzTZEYRPkLNmMUKXRXrC7S/gSnveI/hOsKEVKcJi8IVO5TkKplhGcPiKNhSeEb8AoPCfwD42z4QLsIbIyXY/ImgE2O54ycshKQTb0jqTl7goMh2thZZoVZEtzWhRCcomyq5sR6cPEJWjTr0sHAI179uf9licMH8LTapKS6BW54kVOKIAq2J8lBxXQfVbZmpHJ2bckGF8B1JPQWWbNA/54zYLxiLwKXcKK@Cbhe0KBGE8j8nuJfMgE10kQgDHZJ3TFyGz8Nck2EhI0TosSKC8VBmdUzhOE5E1Motm4zVXpP4zJdDDgDWWBjsRWhxEKQPOcX6NnIbRgsGxdrgACqrEnGUjN1yqWpLaIyogU4kDoNeVpryEnGikYkwuQ4QKc1ANLwzjGkpG2I4yKnnYXEFZbhq4PQPq@V0cDoUIY5A/j2BW/E7IqhWBAEV0QXS4vNxu@4vgILYjUwdT3NSUM6T1YDKw1VEstD5666ugomNR4rjNJN@G3TFn5jiYl@87hUPNfo3WIXoEDjTh7BBdpUVRf@s53LV0kTF8TDPg213ZIWG7aBhDZFLKMfn6OrNHGGPm92vyxTAGQRXUCEBD9Wg@@Cbyh209oDmEbnlc@gE9IhbZZXkekOVc0c9LYSP4BXLbMS5qQ1ZatbvO281x0@Y4l5XUK4fcIFzkQu5pn5A09sxVuqQe4FNSbgSLvy6sbBsUB89IWY/ALYZ0bmReDtPcgthHd71m6DkTYMb7P9sE4fCr8QSf8YSf@wRH8wycZYD5edNlAFv3gpsyLEaEjcpPdGokcF6/X8O4aqZc0s/abACe/kI@xdg8GLgKDwdk4ej0ZT76dvn45k/xMk6B4XXbyYiqvHquV2jO6Y@nSBLUzWGQFGNEQd4ZWULoLZ6gmjEpYLMlrgQWiYcdhNYDmoZF/GmyHDQP65yo5hnEtSXbqZsK5WgcyEDCQTvZNCV40pp9362q7IvVc2g9bv2NNUXdjk0P76ZjLUUuOAue3FAB@ttT2hHoHa93ZmhUAprQAQ0NniVSnPp8zCnwQJWsZRg62A9XfCZFxNJV@prV6cPZrMxsNVGvdv8xOuDb3hpUcwcS7aI8heeJ1WOgJD0zkrb2AajZlb79iPAmaqEM7H4afHNtAeZ9I1z4SdK60Jus7clZJHoVR8qFEhmKHi2pF5upzYfME2Ed2RfWEJXcqrihhKzDLXWvKC@JbOCAvIxh6FVnBkAyunzutI6/QbUodSRHzIFzIXtvh0pwiGSI/t7YYJZWNXeiatM57D8Jn01vThy4bvZhhLd1b70WPubZehh2iRnoGdR0X4/b1gaD40pQDyYWcOdnngri@1Mw2tmqSwQD2bRdx13zZUcmte3fR7A5ntXKJKniDujYO2J9Numbgnqqenj1TYPzXLG1nvzqLN7E3WOtTpGM8wR5/pQw0jXIksWiI27B0FXwH2PGxSTBumM7txqae5QeuYOHiGDVlqVYdsqn1Iu7AnUzOn8n6j/MwB3ynK9UHVMdPX35OecFpwv/NCLAhG86Sdf5QccPDmfxfvNhmZXHZXela06pdPjJeQWLWJ3KeqZI9ucJmQRZiqFfUHAz5He3CC72H9NDfhz5S8Pe3fK9PTU4Fgw06TxLM3nbPjWa2RzZfkA1P9OGEZEFWNCXVtvfJedIcskUsItOZxPMc6tKQyHbh5TdQoaazEDeVdnuJo90dRb2NCw3539LkoA7@7rcstYbb0jtmrIeljhZgMrTiH@kf2uatPOcBH5JO@ngz@SFwIqN2YNsVHQ@EgKGARP3eL0eWOU9XTHaS/r5ObicUFf9uSk0QD2h3POl2cPM@HnZrcFw4/0bLg8L4WOi15ld17IT8lKWn6pTJBAceBEIsrLIsWWf36ZdEnCfkkOp1JsM4e4bYM6R5gQeOkN2JHL9iGzy2154k5zpe1WWhF178rR@4NM6g16@fdzTx7SjirnWc2FHXGw8c6deKyn4PGqfyOF3QwwNhZWd7Q6qiBdugT702MxSEZ2WuIFf97nGGWFNwcucJyKVxWssNytYOj4sppP28wPuN6qQ1R4/JGYM0iJ4DM64YJItVwe9YX539IpS29zcaOd2/VfMYBHPzbTHvy7Z04YRKuV/Two9@k297w4ZnyRhphYBWX9Y1ZW3pNqbuIaBQmgyleodnqX8Vk77yl37zjsXjIs1rA0sGWT0A0GOAQq9RWJ2TMdhehS/@@NR7LA0Ldmcz6l2kWS1aR1dym9azoKOzmMuXPtH5BQ1W9T4jY1u7vMtnK9q4l27g//R7EMumc0fQYOG/qXE2351XNnaq9yi3SynZ8SKKoJDpxFAbaDG5cKuEFSNJArVlt6Zt1AxJ4ZYdRiqh5H5XjHjBdrjtb4iEat4zDBgZTSjR9@/eVYHZwsQ5VLDT5K2Mc4J2Viu3mpXprhABiLk8S20O0jZgH4sqAdW50vTQhGFYKx3Pg8Vfdogj5/rHHVydutxnZbJGi2f3Llg203hc/kRbxQKbFTATUhfOxINeA7HK8grjapdSaXcIyGMgDiU/O7PKHK1wC/@PrGHh3tJkg/fa9crEHhuseFj3rMGKigXNsMIDxOn/EqzprPvq33vn/83sr4j7WGl7Jx9q72lUL9FE5HewrHlFo0whDiDz0KvsTl13R70VVKWc/CZvLBXlPTzQj3/J1tCxQiOlRrDHXC6xPVguVZf5Fkj@SqG5GjkvvIyqF11GRviR2Zg2WicMHWnemMz194CBhwQ8rNZ2UjdEq4NhK1LjEB83BzFxCLkT5FFlTCrijfXYSMakVQWtEu1dpGnf4nlbFnUPpQc0sAUTGti2kfGpnau1aE7VW80aizCOJ24nthd4ANfH214tBThNf1hbg3eudom72/ASUGmiP@xD3xbdQE50BAgdoRks1q8qrbl0RioONQ2qh3NXosUwnlhKguVgpLypvpbsLU@hArwvIJQAI9iu9FrvATmO51OPhzW7YNlo26W26QQRvwIbe96doTxnIEq2/7nAQALV7Bxkj69x1Z3jMQKadebmZ85HPMLQDuyikeN94cItL1zmFoOnIalusOYcsK7EMLzkFnk@WYA3yQyFsySVN7GNjUUdGUsRXdxzfuyLDCeYBrGNySO@iHx39CNGLf0ISES2zljxQYqG/u/L1cocSc15a7bUVRKKY01/4X@bzBJqG14TGHsGVNcwjK2qbQCUS8WgT0rr@lSSSxkVJWMCnnZAGU@O4d/JY9HIQIHrVLpCaB/tqg@25oxs4hy5OXhEPNm8USKQSJzQ3dWaNo41zg19383R8@Z/6FJiVSaDBmVlh7hxQqh1ifVnu5hID/GXkyND0lqxxTWC9ARPlsuaAfKis4wEfZDFpHtcOOyTc/xtjl6ULuHQ7HD7VSKsOhs/aZFGQnc@Ya9xC46vv5rbyzTKGVsHfDiZvpxMFX1oNEAp226YV1wf11XUXohVtO5YM7aB8sIwiqpCpF/jDT9//i8)
**FINAL RESULTS**
WOO THEY ARE FINALLY HERE! Check the TIO Link above to see what code I used to generate the final standings. The results are not terribly interesting. Over the 1000 runs I did with different random seeds, the results were
```
1000 wins - Jack
0 wins - everyone else
```
Congratulations to the Bounty winner Jack!! (aka @Renzeee)
[Answer]
# Indecisive Twitchy Mess
```
def mess(self, Reap, prevReap):
if not hasattr(self.obj, "start"):
self.obj.start = False
if self.time < self.waittime:
return 0
if self.points + Reap >= self.win:
return 1
if Reap >= self.waittime / (self.lenBots + 2):
self.obj.start = True
if self.obj.start:
return 1 if self.getRandom() > 0.2 else 0
return 1 if self.getRandom() > 0.8 else 0
```
This bot does the usual checks first(Can I reap, can I win?) and then looks for a target value before it reaps. However, it's indecisive, so after it reaches the target, it wonders how much longer it can wait and doesn't reap immediately. In addition, it's twitchy, so it might accidentally "hit the button" and reap before the target.
### **Fun fact:** This is basically how I play reaper as a human.
[Answer]
## Sniper
A bot fueled by spite. Keeps track of opponent's cooldowns and scores. Attempts to keep others from winning. Pretty much never actually wins, but makes the game frustrating to play for others.
**EDIT:**
* If reaping would cause it to win, reap.
* If no one is >= 70% of the winning score:
+ If everyone else is on their cooldown, wait until the last possible moment to reap.
+ If anyone else would win by reaping the current value, and they are active now or would be active next turn, reap.
+ ~~If at least half of the other users are on their cooldown, attempt to reap.~~ *This makes it difficult to target specific opponents, and so was removed.*
+ Otherwise, reap 25% of the time (essentially to guarantee that this bot does reap SOMETIMES, just in case something weird happens, like everyone is waiting several turns).
* **If someone IS >= 70% of the winning score:**
+ If Sniper can win a tiebreaker, and next round would be above the average Reap value for the highest scoring opponent, reap
+ If highest scoring opponent will leave their cooldown next turn, reap.
```
def Sniper(self, Reap, prevReap):
# initialize opponents array
if not hasattr(self.obj, "opponents"):
self.obj.opponents = {}
# initialize previous Reap value
if not hasattr(self.obj, "lastReap"):
self.obj.lastReap = 0
# increment all stored wait times to see who will be "active" this turn
for opponent in self.obj.opponents:
self.obj.opponents[opponent]["time"] += 1
# update opponents array
for opponent in prevReap:
# don't track yourself, since you're not an opponent
if opponent != "Sniper":
# initialize opponent
if opponent not in self.obj.opponents:
self.obj.opponents[opponent] = {"time": 0, "points": 0, "num_reaps": 0, "avg": 0}
self.obj.opponents[opponent]["time"] = 0
self.obj.opponents[opponent]["points"] += self.obj.lastReap
self.obj.opponents[opponent]["num_reaps"] += 1
self.obj.opponents[opponent]["avg"] = self.obj.opponents[opponent]["points"] / self.obj.opponents[opponent]["num_reaps"]
# done "assigning" points for last round, update lastReap
self.obj.lastReap = Reap
# get current 1st place(s) (excluding yourself)
winner = "" if len(self.obj.opponents) == 0 else max(self.obj.opponents, key=lambda opponent:self.obj.opponents[opponent]["points"])
# you are ready now
if self.time >= self.waittime:
# current Reap is sufficient for you to win
if self.points + Reap >= self.win:
return 1
if (
# a 1st place exists
winner != ''
# if current 1st place is close to winning
and self.obj.opponents[winner]["points"] / self.win >= .7
):
if (
# next round's Reap value will be above opponent's average Reap
(Reap * self.mult >= self.obj.opponents[winner]["avg"])
# we have been waiting at least as long as our opponent (tiebreaker)
and self.time >= self.obj.opponents[winner]["time"]
):
return 1
# current 1st place opponent will be active next round
if self.obj.opponents[winner]["time"] + 1 >= self.waittime:
return 1
else:
if (
# everyone is waiting for their cooldown
all(values["time"] < self.waittime for key, values in self.obj.opponents.items())
# and we're tracking ALL opponents
and len(self.obj.opponents) == self.lenBots - 1
# at least one person will be ready next turn
and any(values["time"] + 1 >= self.waittime for key, values in self.obj.opponents.items())
):
return 1
if (
# opponent will be active next round
any( (values["time"] + 1 >= self.waittime)
# current Reap value would allow opponent to win
and (values["points"] + Reap >= self.win) for key, values in self.obj.opponents.items())
):
return 1
if (
# a 1st place exists
winner != ''
# current 1st place opponent will be active next round
and (self.obj.opponents[winner]["time"] + 1 >= self.waittime)
# next round's Reap value will be above their average Reap
and (Reap * self.mult >= self.obj.opponents[winner]["avg"])
):
return 1
# # at least half of opponents are waiting for their cooldown
# if sum(values["time"] < self.waittime for key, values in self.obj.opponents.items()) >= (self.lenBots - 1) / 2:
# return 1
# 25% of the time
if self.getRandom() <= .25:
return 1
# default return: do not snipe
return 0
```
## Bored
Just for fun, this bot was brought along by a friend and doesn't actually want to be here. They roll a d16 until they get a number in 1-9, then they attempt to reap anytime a number contains the chosen digit. (Going to look for a d10 would disrupt the game, which is rude, and 0 is just too easy!)
```
def Bored(self, Reap, prevReap):
# if this is the first round, determine your fav number
if not hasattr(self.obj, "fav_int"):
r = 0
while r == 0:
# 4 bits are required to code 1-9 (0b1001)
for i in range(0, 4):
# flip a coin. Puts a 1 in this bit place 50% of the time
if self.getRandom() >= .50:
r += 2**i
# if your random bit assigning has produced a number outside the range 1-9, try again
if not (0 < r < 10):
r = 0
self.obj.fav_int = r
# you are ready now
if self.time >= self.waittime:
# current Reap is sufficient for you to win
if self.points + Reap >= self.win:
return 1
# do you like this value?
if str(self.obj.fav_int) in str(Reap):
return 1
# do you like your wait time?
if self.time % int(self.obj.fav_int) == 0:
return 1
# default return: do not reap
return 0
```
[Answer]
# Jack
This is a simple bot with 4 rules:
* Don't reap when it doesn't do anything
* Always reap when reaping lets us win
* Also reap when there has not been reaped for 3 ticks
* Otherwise do nothing
I have optimized the 3 ticks versus the current existing bots (Sniper, grim\_reaper, Every50, mess, BetterRandom, Averager, some more).
```
def Jack(self, Reap, prevReap):
if self.time < self.waittime:
return 0
if self.win - self.points < Reap:
return 1
if self.mult ** 3 <= Reap:
return 1
return 0
```
I have tried to stay with my old solution (5 ticks) but also reap if you haven't reap for longer than X ticks, and then reap after fewer ticks have been passed during non-reaping (i.e. 5, if waited longer than self.waittime + 5, also reap if not been reaped for 4 ticks). But this didn't improve just always reaping after 4 ticks instead of 5.
[Answer]
# Every 50
This bots will reap every time the `Reap` amount is above 50.
**Why 50?**
If I make the assumption there will be 25 bots in play, it means the `multiplier = 1.6-(1.2/(1+sqrt(25))) = 1.4` and the `waittime = floor(1.5*25) = 37`. Since the `Reap` starts at `1`, it will go up like this:
```
Round: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 etc.
Reap: 1 1.4 1.96 2.744 ~3.84 ~5.39 ~7.53 ~10.54 ~14.76 ~20.66 ~28.92 ~40.50 ~56.69 ~79.37 ~111.12 ~155.57 ~217.79 ~304.91 ~426.88 ~597.63 etc.
```
As you can see, it reaches above 50 after 13 ticks. Since the `Reap` will reset to 1 every time a bot reaps, and the `waittime` for a bot that reaps is 37, the likelihood a bot reaps sooner than later is pretty high, especially with bots similar to the example `GreedyBot`, which will reap as soon as their `waittime` is available again. At first I wanted to do 200 which is the 17th tick, somewhat in the middle of the 37 waiting time ticks, but with the assumption there are 25 bots in play there is a pretty high chance someone else snatches the `Reap` before me. So I lowered it to 50. It's still a nice rounded number, but especially because it's the 13th tick (with 25 bots), and 13 and 'reaping' also fit a bit in that same 'evil' genre.
**Code:**
The code is laughable trivial..
```
def Every50(self, Reap, prevReap):
return int(Reap > 50)
```
**Notes:**
This bot is pretty bad with low amount of bots in play. For now I will leave it, and I might make a better bot actually calculating the best time to `Reap`. With an extremely low amount of bots in play the `waittime` is much lower as well of course, so even `GreedyBot` might win quite easily from this bot if the `waittime` is low enough.
Hopefully more people will add a lot more bots. ;p
[Answer]
## Averager
```
def Averager(self,Reap,prevReap):
returner = 0
if not hasattr(self.obj,"last"):
self.obj.last = Reap
self.obj.total = 0
self.obj.count = 0
returner = 1
else:
if len(prevReap) > 0:
self.obj.total += self.obj.last
self.obj.count += 1
self.obj.last = Reap
if self.obj.count > 0 and Reap > self.obj.total / self.obj.count:
returner = 1
return returner
```
This bot tries to reap any time the current Reap value is above the average Reaped value.
[Answer]
# Grim Reaper
This bot keeps a running average of the values of all the previous reaps as well as the time each bot has been waiting. It reaps when it has been waiting longer than 3/4 of the other bots and the reap is at least 3/4 the size of the average reap seen so far. The goal is to grab a lot of reasonably sized, low risk reaps.
```
def grim_reaper(self, Reap, prevReap):
if self.obj == None:
self.obj = {}
self.obj["reaps"] = []
self.obj["prev"] = 1
self.obj["players"] = {i:0 for i in range(math.ceil(self.waittime / 1.5))}
if Reap == 1 and len(prevReap) > 0:
self.obj["reaps"].append(self.obj["prev"])
for player in prevReap:
self.obj["players"][player] = 0
retvalue = 0
if (len(self.obj["reaps"]) > 0
and Reap > sum(self.obj["reaps"]) / len(self.obj["reaps"]) * 3. / 4.
and sum([self.time >= i for i in self.obj["players"].values()]) >= len(self.obj["players"].values()) * 3 / 4):
retvalue = 1
for player in self.obj["players"]:
self.obj["players"][player] += 1
self.obj["prev"] = Reap
return retvalue
```
Edit: Fixed some embarrassing syntax errors.
[Try it Online](https://tio.run/##fZPBTsMwDIbPy1P8wKWFKqyMXSZ1D4AEB8StmlDYPBZomypJQQjx7CPOYGys0FNsJ78//3LbN78yzWi9XtASj1bX95ZUSzZxVC0z3IYgQ2vphU/pRAz0ElyS5uEJRYEb01DIDn5yeP/Yictj1nPHs1AoZ3sFVo35fD9dqTeymxfvejLE0lho6AZWNY@U1Mqv5Jx0FRHlq9Le65pwjlyO0/QjIjIt4@VQzQIVNcl2BkwxnPQRStW21CyS34RpuMwMGzAG@dZimT7ycnPiCYZCDCz5F1V1FEOmSxjooH8kg8DOx/BxlClcV/c9OccfWqcYyVC9lAeCrFTGF9G3aRHc3XrcM42M8C5JmbD41e/wVmzNnXlbdmfPgxX7PvbITMT/jp7FdelZIrYpWt3ZsClfXcVgfYKrznl4g1o9UxjeErSH7RongWsTQk/OO74xNzUdiXmlnMNdSCahBc09D9KGnDChT8ynwvwsXoFxCMPVgn8GsfsTmQz5ZYYyzy6y0SxdfwI)
[Answer]
# BetterRandom
```
def BetterRandom(self,reap,prevReap):
return self.getRandom()>(reap/self.mult**self.waittime)**-0.810192835
```
The bot is based on the assumption that the chance to reap should be proportional to the reap size because a point is a point, no matter when it's gotten. There is always a very small chance to reap, this keeps the behavior exploitable. First I thought it would be directly proportional and assumed the proportionality constant to be around `1/mult^waittime` (the maximum reap assuming at least one bot plays greedy) after running some simulations I found that this was indeed the optimal constant. But the bot was still outperformed by Random so I concluded the relation wasn't directly proportional and added a constant to calculate what the relation was. After some simulations I found that against my test set of bots `-1.5` was optimal. This actually corresponds to an inversely proportional relationship between the reap chance and `reap*sqrt(reap)` which is surprising. So I suspect this is highly depended on the specific bots so a version of this bot that calculates k while playing would be better. (But I don't know if you are allowed to use data from previous rounds).
EDIT: I made program to find the kind of proportionality automatically. On the test set `["myBot("+str(k)+")","Randombot","Greedybot","Every50","Jack","grim_reaper","Averager","mess"]` I found the new value.
[Answer]
# Target
```
def target(self,Reap,prevReap):
if not hasattr(self.obj, "target_time"):
self.obj.target_time = -1
self.obj.targeting = False
self.obj.target = None
if self.obj.target_time >= 0:
self.obj.target_time += 1
if self.time < self.waittime:
return 0
if self.points + Reap >= self.win:
return 1
if len(prevReap) > 0:
if not self.obj.targeting:
self.obj.target_time = 0
self.obj.target = prevReap[int(self.getRandom() * len(prevReap))]
self.obj.targeting = True
if self.waittime <= self.obj.target_time + 1:
self.obj.targeting = False
self.obj.target = None
self.obj.target_time = -1
return 1
return 0
```
My chances of winning with mess are almost none now, so time to mess up all the other bots in as many ways as possible! :)
This bot functions similar to sniper. Whenever someone reaps, it picks a random target from whoever reaped. Then, it simply waits until that target almost can reap again and snipes it. However, it doesn't change focus - once you've been chosen and locked on, you can't escape :)
[Answer]
# EveryN
I guess it's time for my second bot right before the deadline.
This bot will:
* Skip when it's still in its waiting time for the last Reap
* Reap when it can win
* Reap when no one reaped for at least `n` rounds, where `n` is calculated with `n = 3 + ceil(self.waittime / self.lenBots)`
Code:
```
def every_n(self, Reap, prevReap):
# Initialize obj fields
if not hasattr(self.obj, "roundsWithoutReaps"):
self.obj.roundsWithoutReaps = 0
# Increase the roundsWithoutReaps if no bots reaped last round
if len(prevReap) < 1:
self.obj.roundsWithoutReaps += 1
else
self.obj.roundsWithoutReaps = 0
# Skip if you're still in your waiting time
if self.time < self.waittime:
return 0
# Reap if you can win
if self.win - self.points < Reap:
return 1
# i.e. 25 bots: 3 + ceil(37 / 25) = 5
n = 3 + math.ceil(self.waittime / self.lenBots)
# Only reap when no bots have reaped for at least `n` rounds
if self.obj.roundsWithoutReaps >= n:
self.obj.roundsWithoutReaps = 0
return 1
return 0
```
I don't program in Python very often, so if you see any mistakes let me know.
[Answer]
Ongoing: My project to extend T4T to every open KOTH.
# Tit for Tat
```
def t4t(self, r, p):
if(not hasattr(self.obj,"last")): self.obj.last = self.win
if(p):
self.obj.last = r
return 0
# The usual checks
if self.time < self.waittime:
return 0
if self.points + r >= self.win:
return 1
if(r >= self.obj.last):
return 1
```
# Tit for *n* Tats
```
def t4nt(self, r, p):
n = 5 # Subject to change
if(not hasattr(self.obj,"last")): self.obj.last = [self.win]*n
if(p):
self.obj.last.append(r)
self.obj.last.pop(0)
return 0
# The usual checks
if(self.time < self.waittime):
return 0
if(self.points + r >= self.win):
return 1
if(r >= self.obj.last[0]):
return 1
```
---
# Kevin
Just to keep you on your toes.
```
def kevin(just, a, joke):
return 0
```
[Answer]
# Average Joe
I got inspired by *Averager* and created a bot which calculates on average how many turns it takes before someone reaps and tries to reap one turn prior to that.
```
def average_joe(self, Reap, prevReap):
if not hasattr(self.obj, "average_turns"):
self.obj.turns_since_reap = 1
self.obj.total_turns = 0
self.obj.total_reaps = 0
return 1
if len(prevReap) > 0:
self.obj.total_turns = self.obj.total_turns + self.obj.turns_since_reap
self.obj.total_reaps += 1
self.obj.turns_since_reap = 0
else:
self.obj.turns_since_reap += 1
# Don't reap if you are in cooldown
if self.time < self.waittime:
return 0
# Reap if you are going to win
if self.win - self.points < Reap:
return 1
# Reap if it is one turn before average
average_turns = self.obj.total_turns / self.obj.total_reaps
if average_turns - 1 >= self.obj.turns_since_reap:
return 1
else:
return 0
```
[Answer]
# HardCoded
Yes, it is.
```
def HardCo(self,reap,prevReap):
return reap > 2
```
Instead of averaging on the past reaps, use a pre-calculated average on a typical run. It's not going to get better with time anyway.
] |
[Question]
[
This challenge is pretty simple. As input, you take in a regular expression.
Then, you output a truthy/falsey of whether or not your source code matches the regular expression. It's that simple! Just two more things:
* No quine builtins; you may, however, access the code's source code by file IO, etc.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins!
## Example
If your source code was say, `abc`, an input of `a\wc` would return true and an input of `a\dc` would return false.
[Answer]
# Z shell, 12 bytes
```
grep "$@"<$0
```
Zsh conditionals understand only exit codes, and the scripts exits with 0 or 1 accordingly.
In addition, this prints a non-empty string (the source code) for a match and an empty one for a mismatch, which could be as truthy/falsy values in combination with `test`/`[`.
The program reads its own file, but according to [this comment](https://codegolf.stackexchange.com/questions/69203/quinean-regex-tester#comment168459_69203) by the OP, this is allowed.
[Answer]
# JavaScript (ES6), 39
```
(f=_=>!!`(f=${f})()`.match(prompt()))()
```
[Answer]
# Python 3, 119 bytes
This just *looks* cooler, IMO (and it doesn't read the file).
```
(lambda i:print(bool(__import__('re').search(input(),i))))("(lambda i:print(bool(__import__('re').search(input(),i))))")
```
---
# Python 3, 67 bytes
```
print(bool(__import__('re').search(input(),open(__file__).read())))
```
Added after reading [this comment](https://codegolf.stackexchange.com/questions/69203/quinean-regex-tester#comment168459_69203).
[Answer]
# Julia, ~~64~~ 54 bytes
```
r=readline;show(ismatch(Regex(r()),open(r,@__FILE__)))
```
Julia regular expressions use PCRE. While reading the source code of the file is a standard loophole for quines, in this case it has been explicitly allowed. Takes input with no trailing newline.
[Answer]
# Japt, 22 bytes
```
"+Q ³sAJ fU"+Q ³sAJ fU
```
[Standard quine framework](http://ethproductions.github.io/japt?v=master&code=IitRILNzN0oiK1Egs3M3Sg==&input=) with a few bytes added to fit this challenge. Truthy = match(es), falsy = null. [Try it online!](http://ethproductions.github.io/japt?v=master&code=IitRILNzQUogZlUiK1Egs3NBSiBmVQ==&input=Ii4rIg==)
```
// Implicit: U = input string, A = 10, J = -1, Q = quotation mark
"..."+Q // Take this string and concatenate a quotation mark.
³ // Repeat three times.
sAJ // Slice off the first 10 and last 1 chars.
fU // Match U to the result.
```
[Answer]
# Perl, 21 bytes
```
open 0;$_=<0>=~$_
```
17 bytes plus 4 bytes for `-pl0`. Run like this:
```
echo open | perl -pl0 quinean
```
The source file must contain only the code above (no shebang, no trailing newline). Outputs `1` if the regex matches and the empty string if it doesn't (the empty string is falsey in Perl).
---
Four bytes can be saved if the input is guaranteed not to end in a newline:
```
open 0;say<0>=~<>
```
Run like this:
```
echo -n open | perl -M5.010 quinean
```
`say` requires Perl 5.10+ and must be enabled with `-M5.010`. According to [Meta](http://meta.codegolf.stackexchange.com/a/274/31388), "the `-M5.010`, when needed, is free," giving a score of 17 bytes.
## How it works
This is a simple variation on the standard "cheating" quine:
```
open 0;print<0>
```
This opens the file named in `$0` and reads the contents with `<0>`.
`$_=<0>=~$_` reads one line from the source file, does a regex match against the contents of `$_` (which were read by the `-p` flag), and assigns the result to `$_`. `-p` prints `$_` automatically at the end.
[Answer]
# Mathematica, 63 bytes
```
StringMatchQ[ToString[#0, InputForm], RegularExpression[#1]] &
```
Note the trailing space. Uses the standard Mma quine mechanism, and tests if it matches the regex.
[Answer]
# Jolf, ~~18~~ 15 bytes
Supports the JS flavour of RegEx, I hope that's okay. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=IGgiJSIkY29kZS52YWx1ZSNp).
```
h$code.value#i
```
Commented:
```
$code.value# the document's element "code" (the program container)
_h i and output if it has (matches) the input string (i.e. regex)
```
[Answer]
# ùîºùïäùïÑùïöùïü, 14 chars / 26 bytes (non-competitive)
```
⟮‼(ⒸⅩ222+ᶈ0)đï
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=%5E%E2%85%A9222&code=%E2%9F%AE%E2%80%BC%28%E2%92%B8%E2%85%A9222%2B%E1%B6%880%29%C4%91%C3%AF)`
Using a version with bug fixes written after the challenge.
# Explanation
```
⟮‼(ⒸⅩ222+ᶈ0)đï // implicit: ï=input
⟮ // copy block: copy following code for later use
(ⒸⅩ222+ᶈ0) // take convert 10222 to char, add stuff inside copy block
‼ đï // check if input matches resulting string
// implicit output
```
NOTE: Copy blocks are NOT quine operators. They are meant to be more versatile alternatives to variable declarations.
] |
[Question]
[
# Bingo
Bingo is a numbers game where players match randomly drawn numbers to the numbers on their cards. Each bingo card is a square grid with 25 spaces, and the columns of the grid are labeled with letters such as "B", "I", "N", "G", "O". The letters help to identify the number range in each column, for example, the "B" column may contain numbers 1 to 15.
One of the spaces in the middle of the grid is often a "free" space, and is marked as such. To play the game, each player is given a bingo card with numbers on it. A caller then draws numbers randomly and announces them, and players mark the corresponding numbers on their cards. The first player to match a pre-determined pattern of marked numbers, such as a straight line, all four corners, or a full card, calls out "Bingo!" to win the game. The game continues until one player wins, or multiple players win on the same round. [1]
---
# Challenge
Create a set of `n` bingo cards that are printed / outputted in sequence separated by one or two empty lines. The center field should be marked as `free`.
The output should be a 5x5 grid where columns are either separated by a single space, a tab or the grid should be fixed width, and the lines are separated by a single new line.
The randomness must be uniform, i.e. all possible permutations and combinations should be equally likely to occur. All numbers must be unique.
The numbers:
```
B = 1 - 15
I = 16 - 30
N = 31 - 45
G = 46 - 60
O = 61 - 75
```
The number `n` must be taken as input.
## Example output for `n = 3`:
```
B I N G O
1 16 31 46 61
2 17 32 47 62
3 18 free 48 63
4 19 34 49 64
5 20 35 50 65
B I N G O
6 30 40 53 64
5 20 35 50 70
4 25 free 51 69
7 22 32 52 68
11 23 38 49 67
B I N G O
10 25 40 55 70
11 26 41 56 71
12 27 free 57 73
13 28 43 58 73
14 29 44 59 74
```
Yes, those were definitely randomly created.
---
This challenge is based on the fact that I recently had to create 100 Bingo cards. It turned out that this part of the challenge was the easy one. Making it pretty, printable and presentable was the time consuming part.
[1] <https://chat.openai.com/chat>
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `J`, 29 bytes
```
(‛₆ṫ⇧Ṅ75ɾ15ẇƛÞ℅5Ẏ;∩2≬2‛λċȦV⁋¶
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJKIiwiIiwiKOKAm+KChuG5q+KHp+G5hDc1yb4xNeG6h8abw57ihIU14bqOO+KIqTLiiawy4oCbzrvEi8imVuKBi8K2IiwiIiwiMyJd)
## Explained (old)
```
( # input times:
75ɾ15ẇ # push the range [1, 75] split into chunks of 15 items
ƛÞ℅5Ẏ; # to each: random_permutation[:5]
∩ # transpose
2≬2‛λċȦV # tos[2][2] = "free"
‛₆ṫ⇧p # .prepend("BINGO")
vṄ⁋ # .map(" ".join(x)).join("\n")
¶+, # + "\n" (then print)
```
[Answer]
# [QBasic](https://en.wikipedia.org/wiki/QBasic), 211 bytes
```
DIM b(5,5)
RANDOMIZE TIMER
INPUT n
FOR i=1TO n
ERASE b
?
?"B","I","N","G","O
FOR r=0TO 4
FOR c=0TO 4
4x=INT((c+RND)*15+1)
FOR p=0TO r
IF x=b(p,c)GOTO 4
NEXT p
IF(r=2)*(c=2)THEN?"free",ELSE?x,:b(r,c)=x
NEXT c,r,i
```
Try it at [Archive.org](https://archive.org/details/msdos_qbasic_megapack)! Example run:
[](https://i.stack.imgur.com/xBOwn.png)
## Explanation/ungolfed
```
DIM b(5, 5)
RANDOMIZE TIMER
INPUT n
```
Declare `b` as a 5x5 array; we'll use this to track already-selected numbers and avoid duplicates. Seed the pseudo-random number generator using the current time. Prompt the user for the number of cards `n`.
```
FOR i = 1 TO n
```
Loop `n` times:
```
ERASE b
PRINT
PRINT "B", "I", "N", "G", "O"
```
Set all values in `b` to zero. Print a blank line followed by the B I N G O header. The commas in the `PRINT` statements separate the items by tabs, using a default tab stop of 14 columns.
```
FOR r = 0 TO 4
FOR c = 0 TO 4
```
Loop over rows 0 through 4; for each row, loop over columns 0 through 4.
```
4 x = INT((c + RND) * 15 + 1)
```
Label this as line number [4](https://xkcd.com/221), which we'll use as a `GOTO` target later. Set `x` to be a random integer, greater than or equal to `c*15+1`, and less than `(c+1)*15+1`.
```
FOR p = 0 TO r
IF x = b(p, c) THEN GOTO 4
NEXT p
```
Loop over each previous row `p`. If `x` equals the value in array `b` at row `p`, column `c`, go back to line 4 and generate a new random number.
```
IF (r = 2) * (c = 2) THEN
PRINT "free",
ELSE
PRINT x,
b(r, c) = x
END IF
```
If both `r` and `c` are 2, print the string `"free"`; otherwise, print `x` and set the appropriate value in the `b` array to `x`. In both cases, end the print statement with a tab rather than a newline.
```
NEXT c, r, i
```
Close all the `FOR` loops.
---
Astute readers may have noticed this doesn't print a newline at the end of each row. Because of the size of the default tab stop, it just so happens that the sixth column wraps to the next line, so printing a newline explicitly is unnecessary (and, in fact, results in unwanted blank lines). This might be bending the I/O requirements a bit. If an explicit newline must be printed, modify the B I N G O line by adding `",` at the end, and add a line containing `?` in between the `FOR r` and `FOR c` headers.
[Answer]
# [Factor](https://factorcode.org/), 123 bytes
```
[ [ "free"2 75 [1,b] 15 group [ 5 sample ] map flip
[ third set-nth ] keep "BINGO"1 group prefix simple-table. nl ] times ]
```
[Try it online!](https://tio.run/##LY49D4JAEER7fsWEWkjQEBPtbIyNFsaKUBywBxeP4zyWRH/9uX60O/vejFYtTyHerqfzcYdR8ZAH5Xqa0Ydp8cb1mOmxkGvlJEk3jfCBmF8@GMcw0xfCnYIji32SbGKFCqkOROka2xJVsWpqFOXPKFmJWY3eEmphPbQ1PqnAgwmdlHHmxFeLkTzSg@y6pMWflWZtnpjNB89YNZZyOCvfbEYZWMdWWRvf "Factor – Try It Online")
* `[ ... ] times` Do something a number of times.
```
"free" ! "free"
2 ! "free" 2
75 ! "free" 2 75
[1,b] ! "free" 2 { 1 2 ... 75 }
15 ! "free" 2 { 1 2 ... 75 } 15
group ! "free" 2 { { 1 2 .. 15 } { 16 17 .. 30 } ... { 61 62 .. 75 } }
[ 5 sample ] map ! "free" 2 {
! { 9 13 14 1 5 }
! { 26 24 25 27 22 }
! { 32 38 41 31 33 }
! { 54 59 55 49 57 }
! { 75 74 70 71 63 }
! }
flip ! "free" 2 {
! { 9 26 32 54 75 }
! { 13 24 38 59 74 }
! { 14 25 41 55 70 }
! { 1 27 31 49 71 }
! { 5 22 33 57 63 }
! }
[ third set-nth ] keep ! {
! { 9 26 32 54 75 }
! { 13 24 38 59 74 }
! { 14 25 "free" 55 70 }
! { 1 27 31 49 71 }
! { 5 22 33 57 63 }
! }
"BINGO" ! { ... } "BINGO"
1 group ! { ... } { "B" "I" "N" "G" "O" }
prefix ! {
! { "B" "I" "N" "G" "O" }
! { 9 26 32 54 75 }
! { 13 24 38 59 74 }
! { 14 25 "free" 55 70 }
! { 1 27 31 49 71 }
! { 5 22 33 57 63 }
! }
simple-table. ! output to stdout
nl ! newline
```
[Answer]
# JavaScript (ES6), 132 bytes
```
f=N=>(F=n=>N?n<30?F[k=n%5]^(F[k]|=1<<(v=Math.random()*15))?(n++-17?"_BINGO"[n]||k*15-~v:'free')+`
`[k>>2]+F(n):F(n):`
`+f(N-1):n)``
```
[Try it online!](https://tio.run/##HcnLCoJAFIDhvU8RQnhOg9IkEoij0MJo0fQAYo146aKdCRVX0qtP0ubng/9VTMVQ9s/P6JKuamMaIUUMqSARy4Qif5ukWStoHeRXWJTPgkcRTOJcjA@vL6jSb8ANDxATIMZcvk/s2@Ekjxc7o3ye2@W53yl0mr6uHWRqZamsjeNdzlIgDP9RlmINSJdjSKiUKTUNuqu9Tt@hAR/R/AA "JavaScript (Node.js) – Try It Online")
### Commented
```
f = N => ( // outer function taking the number N of grids
F = n => // inner function taking a counter n
N ? // if there's still a grid to process:
n < 30 ? // if n is less than 30:
F[k = n % 5] // k is the column index in [0..4]
^ // if F[k] is not equal to its updated value
( F[k] |= 1 << ( // where the floor(v)-th bit is set
v = // where v is
Math.random() // randomly picked in [0,15[
* 15 //
)) ? // then:
( n++ - 17 ? // if this is not the center cell:
"_BINGO"[n] // append either a BINGO letter (if n <= 5)
|| // or
k * 15 - ~v // the number k * 15 + floor(v + 1)
: // else:
'free' // append the word 'free'
) + //
` \n`[k >> 2] + // append a line-feed if k = 4,
// or a space otherwise
F(n) // append the result of a recursive call to F
: // else:
F(n) // try again
: // else:
`\n` + // append a line-feed followed by
f(N - 1) // the result of a recursive call to f
: // else:
n // stop the recursion
)`` // initial call to F with n zero'ish
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mR`](https://codegolf.meta.stackexchange.com/a/14339/), ~~39~~ 38 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
75õ òF Ëö¤v5Ãg2Èh2`fe`ÃÕi"BINGO"¬ m¸·
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1S&code=NzX1IPJGIMv2pHY1w2cyyGgyYGacZWDD1WkiQklOR08irCBtuLc&footer=aVI&input=MwoteA)
```
75õ òF Ëö¤v5Ãg2Èh2`fe`ÃÕi"BINGO"¬ m¸· :Implicit map of range [0,input)
75õ :Range [1,75]
ò :Partitions of length
F : 15
Ë :Map
ö¤ : Shuffle
v5 : First 5 elements
à :End map
g2 :Modify the element at 0-based index 2 by
È :Passing it through the following function
h2 : Replace the element at 0-based index 2 with
`fe` : Compressed string "free"
à :End modification
Õ :Transpose
i :Prepend
"BINGO"¬ : "BINGO", split into an array
m :Map
¸ : Join with spaces
· :Join with newlines
:Implicit output joined with newlines
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~54~~ ~~52~~ 49 bytes
```
FN«≔⪪BINGO¹θF²⁵⊞θ⎇⁼κ¹²free‽⁻⁺×¹⁵﹪κ⁵…¹¦¹⁶θ⟦E⪪θ⁵⪫κ
```
[Try it online!](https://tio.run/##LY7BisIwEEDP9iuGnGYge2iX7sWTwiIV1OL6A1FTDaZJmzQLIn57Ng07hzm9N28ud@EuVugYO@sAGzOEaR/6s3RIBK9isfJe3Qz@DFpNyNbNfnNgHEriMNKyWGSrqgna4O84cjhJZ4R74vcYhPb4SGyVYNY5KZN4FOZqe9wpEzy2Oq2T6qXHsuaws9eg7azURBm9SSzTgS/KuTSpmEMh0WL4/2qcBQ5bq8wsM2CZfBetU2bCQMsYP@PHr/4D "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Now inspired by @Arnauld's answer.
```
FN«
```
Input `n` and loop that many times.
```
≔⪪BINGO¹θ
```
Start with a list of `BINGO` as separate characters which will make up the first row.
```
F²⁵
```
Loop `25` times.
```
⊞θ⎇⁼κ¹²free‽⁻⁺×¹⁵﹪κ⁵…¹¦¹⁶θ
```
Put the word `free` in the middle cell, otherwise take a random element of the appropriate numeric range for the cell but subtracting all of the numbers generated so far, and push the result to the list.
```
⟦E⪪θ⁵⪫κ
```
Split into rows of five cells, join the rows on spaces and output the resulting board double-spaced from the next board.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 39 bytes
```
VQkjd"BINGO"jjL\ Cc5X%3s.SMc5S75y6"free
```
[Try it online!](https://tio.run/##K6gsyfj/PywwOytFycnTz91fKSvLJ0bBOdk0QtW4WC/YN9k02Ny00kwprSg19f9/UwA "Pyth – Try It Online")
### Explanation
```
# implicitly assign Q = eval(input())
VQ # for N in range(Q):
k # print a newline
jd"BINGO" # print BINGO joined on spaces
S75 # range(1,76)
c5 # split into 5 equal parts
.SM # randomly shuffle each part
s # join the parts back together
%3 # take every third element
X y6"free # replace the 12th element with "free"
c5 # split into 5 equal parts again
C # transpose
jL\ # join each part on whitespace, converting all elements to strings
j # join on newlines and print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
F75L5äε.r5£N<i'€²2ǝ}}ø‘Èß‘Sš»,¶?
```
[Try it online.](https://tio.run/##ATwAw/9vc2FiaWX//0Y3NUw1w6TOtS5yNcKjTjxpJ@KCrMKyMsedfX3DuOKAmMOIw5/igJhTxaHCuyzCtj///zM)
**Explanation:**
```
F # Loop the (implicit) input-integer amount of times:
75L # Push a list in the range [1,75]
5ä # Split it into five equal-sized parts
ε # Map over each part:
.r # Randomly shuffle the list
5£ # Then only keep the first 5 integers
N<i # If the index is 2:
'€² '# Push dictionary string "free"
2ǝ # Insert it at (0-based) index 2 into the quintuplet-list
}} # Close both the if-statement and map
ø # Zip/transpose the matrix; swapping rows/columns
‘Èß‘ # Push dictionary string "BINGO"
S # Convert it to a list of characters: ["B","I","N","G","O"]
š # Prepend it to the matrix
» # Join each inner list by spaces; and then each string by newlines
, # Pop and print it with trailing newline
¶? # And print an additional newline character
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `'€²` is `"free"` and `‘Èß‘` is `"BINGO"`.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~50~~ 49 bytes
```
La{Y ZSH*\,75CH5y@2@2:"free"P_JsPBnMyH5PE"BINGO"}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhY3DX0SqyMVooI9tGJ0zE2dPUwrHYwcjKyU0opSU5UC4r2KA5zyfCs9TANclZw8_dz9lWohGqH6F0cbx0KZAA)
### Explanation
```
La{...}
```
Given command-line argument `a`, loop that many times:
```
Y ZSH*\,75CH5
\,75 ; Inclusive range from 1 to 75
CH5 ; Chop into 5 equal sections
SH* ; Randomly shuffle each section
Z ; Transpose
Y ; Yank that result into the y variable
y@2@2:"free" ; Set the element of y at index 2,2 to the string "free"
P_JsPBnMyH5PE"BINGO"
yH5 ; Take the first 5 elements of y
PE"BINGO" ; Prepend the element "BINGO"
M ; Map to each:
_Js ; Join on spaces
PBn ; and push a newline to the end of the resulting string
P ; Print that list, concatenated, with a trailing newline
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utils, 120
```
for((;j++<$1;));{
for((;++i<75;));{
a+=" <(shuf -i$i-$[i+=14] -n5)"
}
eval paste$a|sed '1iB I N G O
3s/\w*/free/3
$a
'
}
```
[Try it online!](https://tio.run/##S0oszvj/Py2/SEPDOktb20bF0FpT07qaCyKirZ1pY24KEUnUtlVSsNEozihNU9DNVMnUVYnO1LY1NIlV0M0z1VTiquVKLUvMUShILC5JVUmsKU5NUVA3zHTi9OT043Tn9OcyLtaPKdfSTytKTdU35lJJ5FLnqv3//78xAA "Bash – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 46 bytes
Full program. Prompts for `n`.
```
('BINGO'{'free'}¨@3@4⍤⍪(15×…4)+⍤1⍉)⍤2↑5?¨⎕5⍴15
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94L@GupOnn7u/erV6WlFqqnrtoRUOxg4mj3qXPOpdpWFoenj6o4ZlJpraQAHDR72dmkDa6FHbRFP7Qyse9U01fdS7xdAUZNB/BTAo4DIGAA "APL (Dyalog Extended) – Try It Online")
`⎕5⍴15` prompt for `n` and join that 5, then use that as dimensions for an array of 15s
`5?¨` for each 15, get 5 random numbers in the range 1 through that, without replacement
`↑` mix this matrix of lists into an `n`-by-5-by-5 array with each row being a randome 5-of-15
`(`…`)⍤2` on each layer:
`⍉` transpose, so the 5-of-15 rows become columns
`(`…`)+⍤1` add the following to each row:
`…4` the numbers 0 through 4
`15×` fifteen multiplied by those
`'BINGO'`…`⍤⍪` prepend a row of the given letters, then:
…`@4` at row 4:
…`@3` at column 3:
`{`…`}¨` replace each value (though there's only one) with:
`'free'` the given word
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~262~~ 225 bytes
* -37 thanks to c--
```
a[6][5]={L"BINGO"};f(n,i,j,k,r){--n&&puts("",f(n));for(j=5;j--;)for(k=i=0;k||++i<6;k||(a[i][j]=r))for(r=j*15+rand(k=i)%15+1;--k&&a[k][j]-r;);for(i=0;i<6;i+=puts(""))for(j=0;j<5;)printf(i*j-9?i?"%d ":"%c ":"free ",a[i][j++]);}
```
[Try it online!](https://tio.run/##LU/BisIwED3rV5RAS2ISUJYKGoOwl2VBdj8g5BDaRibBKLHupfbba2L3MjPvzeO9mYafm2aajNpqVWs5nNDn98/XLxqFxYEBc8yzSAbOQ1XdHv0dI8TShhBhrxE7WQvHuSAZeAlyLfzzSSkctnnARoFWTstI3ooo3WpT02hCm9WkTGAjOPdVZZTPSh7F7JytsgtQ@R87W7jEu0MtyC1C6C2GleO7IxxR2S7QHpVNrjZ23QKxOZ1STcQ4JXVxMRDw3xVaUgzLori/D@nh0uF1eigxFn@kPk4v "C (gcc) – Try It Online")
Ungolfed (``` used instead of literal tab character):
```
a[6][5]={L"BINGO"}; // bingo array, with header
f(n, // number of cards to generate
i,j, // row and column
k, // random number row checker
r // random number
) {
--n && puts("",f(n)); // recursively print cards, adding newline
for(j=5;j--;) // for each column
for(k=i=0;k||++i<6;k||(a[i][j]=r)) // for each row (redo duplicates)
for(r=j*15+rand(k=i)%15+1;--k&&a[k][j]-r;); // detect duplicates
for(i=0;i<6;i+=puts("")) // mark middle item as free; print board
for(j=0;j<5;)
printf(i*j-9?i?"%d`":"%c`":"free`",a[i][j++]);
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~38~~ 36 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
75s15Ẋ€ḣ€5Z“ƝM»€3¦€3¦“BINGO”ṭṚK€Y⁷Ṅ)
```
[Try it online!](https://tio.run/##y0rNyan8/9/ctNjQ9OGurkdNax7uWAwkTaMeNcw5Ntf30G4gx/jQMijZMMfJ08/d/1HD3Ic71z7cOcsbKB75qHH7w50tmv///zcGAA "Jelly – Try It Online")
Most of the credit goes to *@cairdcoinheringaahing* and *@UnrelatedString* for helping me [in chat](https://chat.stackexchange.com/rooms/57815/jelly-hypertraining).
* -2 thanks to UnrelatedString
This can probably be a bit shorter, though.
#### Explanation
```
75 # 75 (implicit range)
s15 # Split into 15 parts
Ẋ€ # Random permutation of each
ḣ€5 # First 5 elements of each
Z # Transpose
“ƝM» # Replace ↓ with "free"
€3¦€3¦ # The third item in the third item (1-indexed)
“BINGO” # Push "BINGO"
ṭṚ # Append and reverse (i.e. prepend)
K€ # Join each by spaces
Y⁷ # Join by newlines and append a newline
Ṅ # Print
) # Repeat input number of times
```
[Answer]
# [Python 3](https://docs.python.org/3/), 151 bytes
```
from random import *
print("B I N G O")
x=lambda n:n*15+randint(0,15)
[print(*[*("free"if(i==2 and j==2)else x(j)for j in range(5))])for i in range(5)]
```
[Answer]
# [Raku](https://raku.org/), 94 bytes
```
{join "
",({S:13th/\d+/free/}((<B I N G O>,|[Z] (1..75).rotor(15)».pick(5)).join("
"))xx$_)}
```
* `(1..75).rotor(15)` splits the range 1-75 into five subranges of size 15: 1-15, 16-30, etc.
* `».pick(5)` selects five distinct random elements from each of those subranges.
* `[Z]` reduces that list of lists of random choices with the `Z`ip operator. It effectively transposes the matrix, so the 1-15 selections are in the first column instead of the first row.
* `<B I N G O>,|...` prepends the header row to the lists of numbers.
* `.join("\n")` joins the rows with newlines, producing a Bingo board as a single string. The actual code uses a single newline character between the quotes to save a byte.
* `S:13th/\d+/free/` changes the thirteenth occurrence of a number in that string to `free`.
* `xx $_` replicates the preceding process a number of times given by the input argument `$_`, producing a list of board strings.
* `join "\n\n"` joins those boards together with two newlines between them.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~198 166~~ 157 bytes
```
lambda n:exec('m=["BINGO",*map(list,zip(*[sample(range(i,i+15),5)for i in range(1,75,15)])),""];m[3][2]="free";[print(*i)for i in m];'*n)
from random import*
```
[Try it online!](https://tio.run/##RYyxDsIgFAB3v4KwFJClNo2JpIuLcdEPQAa0oC/pA0IZ1J/HGgenGy536VUeMXTVD5c6WbyOloSde7oba3DQdH88Hc5UCrSJTTAX@YbEhJ4tpsmxbMPdMZCwbnsue@5jJkAgkJ9o5baXizGcS0qNQt0ZvTED9dk5qnTKEAoT8O/QqEYEvvI54ncyLgBMMRdRPet4/QA "Python 3 – Try It Online")
(ATO isn't working right now so I switched to TIO)
* -32 thanks to tsh
This can probably be golfed a bit more.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/185208/edit).
Closed 4 years ago.
[Improve this question](/posts/185208/edit)
In Emoji Math, a user created module for the video game Keep Talking And Nobody Explodes, numbers are written as strings of emoticons, where each emoticon represents a base 10 digit.
Below is the conversion table between digits and emoticons.
```
Digit | Emoticon
0 | :)
1 | =(
2 | (:
3 | )=
4 | :(
5 | ):
6 | =)
7 | (=
8 | :|
9 | |:
```
Given a number, output it in Emoji Math encoding. You may assume the absence of non-numeric characters.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~29~~ 24 bytes
*-5 bytes thanks to @Shaggy*
```
s":)=((:)=:():=)(=:||:"ò
```
Takes input as a string
[Try it online!](https://tio.run/##y0osKPn/v1jJStNWQwNIWGloWtlqatha1dRYKR3e9P@/pZmxgYWpkbmJIQA "Japt – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~62~~ 58 bytes
-4 bytes thanks to ceilingcat
```
f(n){n&&write(1,":)=((:)=:():=)(=:||:"+n%10*2,2,f(n/10));}
```
[Try it online!](https://tio.run/##ZYrBCsIwEAXP9itKwLKvRkzWnjbkYyRYycFFNOKh7bfHePYyDMOk4y2lWmdSLDoMn2cuV/LWCCJRgxAkgqKsq5iD7r0b2bJt/8k7IGw1a@nvl6yEbul2MzFC/3iXFxmD8Auez3/J8dRsq18 "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 26 bytes
```
"|:(=):)=:)"2ôºJ2ô`Šr)sSèJ
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fqcZKw1bTStPWSlPJ6PCWQ7u8gGTC0QVFmsXBh1d4/f9vbgYA "05AB1E – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~65~~ 62 bytes
```
lambda n:''.join(':=():)=(:|)(:=(:)=|:'[int(c)::10]for c in n)
```
[Try it online!](https://tio.run/##DclJCoAwDADAr@SW5CLuS6AvUQ8uFCuaingR/HvtbWCu99m85sGaIRzTOa8TqCAmu3dKKIZY2JB8TNGRn2Dv9KGFRbJ0tP6GBZyCcrjuGGAJu7pI2ypvygw5/A "Python 2 – Try It Online")
[Answer]
# TI-BASIC, 79 bytes
```
Ans→Str1:" :For(I,1,length(Str1:Ans+sub(":)=((:)=:():=)(=:||:",1+2expr(sub(Str1,I,1)),2:End:sub(Ans,2,length(Ans)-1
```
Input is a string of digits in `Ans`.
Output is the Emoji Math-encoded number.
**Examples:**
```
"134
134
prgmCDGF1C
:)(:)=
"2213894
2213894
prgmCDGF1C
(:(:=()=:||::(
```
**Explanation:**
```
Ans→Str1 ;store the input in Ans
" ;leave " " in Ans
For(I,1,length(Str1 ;loop over each character in the
; input string
Ans+sub(":)=((:)=:():=)(=:||:",1+2expr(sub(Str1,I,1)),2 ;convert the current character
; to a number and use it as the
; index into the encoding string
; then append the encoded digit
End
sub(Ans,2,length(Ans)-1 ;remove the prepended space and
; store the result in Ans
;implicit print of Ans
```
---
Alternatively, here's a **94 byte** solution that takes a number as input instead of a string:
```
int(10fPart(Ans₁₀^(seq(⁻X-1,X,0,log(Ans→L₁:" :For(I,dim(L₁),1,-1:Ans+sub(":)=((:)=:():=)(=:||:",1+2L₁(I),2:End:sub(Ans,2,length(Ans)-1
```
**Examples:**
```
134
134
prgmCDGF1C
:)(:)=
2213894
2213894
prgmCDGF1C
(:(:=()=:||::(
```
**Explanation:**
```
int(10fPart(Ans₁₀^(seq(⁻X-1,X,0,log(Ans→L₁ ;generate a list of the input's digits
; reversed and store it in L₁
" ;leave " " in Ans
For(I,dim(L₁),1,-1 ;loop over L₁ backwards
Ans+sub(":)=((:)=:():=)(=:||:",1+2L₁(I),2 ;use the value of the I-th element in L₁ as
; the index into the encoding string then
; append the encoded digit
End
sub(Ans,2,length(Ans)-1 ;remove the prepended space and store the
; result in Ans
;implicit print of Ans
```
---
**Notes:**
* TI-BASIC is a [tokenized language](http://tibasicdev.wikidot.com/tokens). Character count does ***not*** equal byte count.
* `|` is the two-byte token **0xBBD8** that can only be accessed using [this assembly program](http://tibasicdev.wikidot.com/hexcodes#toc65).
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 42 bytes
```
s/./substr":)=((:)=:():=)(=:||:",$&*2,2/ge
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX0@/uDSpuKRIyUrTVkMDSFhpaFrZamrYWtXUWCnpqKhpGekY6aen/v9vwGXIZcRlzGXCZcplxmXOZcFl@S@/oCQzP6/4v24BAA "Perl 5 – Try It Online")
[Answer]
# Java 8, 80 bytes
```
n->n.forEach(i->System.out.print(":)=((:)=:():=)(=:||:".split("(?<=\\G..)")[i]))
```
[Try it online.](https://tio.run/##ZZDBbsIwDIbvPIXVky3UCDa2sULZaZp2GBeOwCELZZi1oWpSpGnw7J1bMiFtUmLF8R9/v7PXRx3vN5@NybVz8KbZfvcA2Pqs2mqTwbxNAY4H3oDBvchV7TlXzleZLtSr9YvuBJYmojzLluW89mxgDhZSaGw8s2p7qJ612SHHs8WX81mhDrVXZSUojBJKESUkSElKmCanUxIpV@YsRXyapqvVi1IU0ZLXRM2kJ4yyfs@FEVCdwULso/hh@7Fcg6aLdyGjUIDTwQR4Omxjv09dDcBnziN35kMyvLkd3d0/jB8HYaTrQB3l8qJtaMvaB8i/mbpiP0ogCr2tMvh7G5EyO105JFXosv0TjkdjCsq/vXKLwcm5@QE)
**Explanation:**
```
n-> // Method with IntStream parameter and no return-type
n.forEach(i-> // For each digit `i` in the input:
System.out.print( // Print without newline:
":)=((:)=:():=)(=:||:" // Push this String
.split("(?<=\\G..)") // Split into parts of size 2
[i])) // And print the `i`'th part
```
[Answer]
# JS ES6, 77 66 bytes
Down to 66 thanks to suggestions from @Charlie Harding and @asgallant
Had to finally make an account on codegolf since this was such a fun little challenge!
The most minimal form of the original answer, when expecting string-only input:
```
n=>[...n].map(c=>":)=((:)=:():=)(=:||:".match(/../g)[c]).join("")
```
Secondly, my original answer which uses a longer regex and first coerces the input into a string, This works with both number type input and a string of digits input.
>
> I first coerce the input into a string, which is then destructured into an array using es6 spread. Then I map it through a matcher cb that grabs the correct emoticon from an array made with the regex `/.{1,2}/g`. Finally the resulting array of emoticons is joined back to a string.
>
>
>
```
n=>[...(""+n)].map(c=>":)=((:)=:():=)(=:||:".match(/.{1,2}/g)[c]).join("")
```
JS array stuff is fun. I'm sure there's still some room for optimization, this re-matches the regex on every loop of the `map`.
Crappily tested with the following:
```
let emoticonize = n=>[...(""+n)].map(c=>":)=((:)=:():=)(=:||:".match(/../g)[c]).join("")
let test = arr =>
console.log(arr.map(x => ({ask:x, ans: emoticonize(x)})))
test([1,40,3697, 2330])
test(["1","40","3697", "2330"])
```
[Answer]
# Haskell, ~~64~~ 56[Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) bytes
```
((words":) =( (: )= :( ): =) (= :| |: "!!).read.pure=<<)
```
[Try it online](https://tio.run/##DcY9CoNAEAbQq3xazRQRBCEwOFUuYJkizaDrD25M2DWk8exO8qo3W15DjP60ZYNi2faQrN/xgBN9X2nIpTCUQAJWCIEFyqD/DxyCsii4SsGG6v1JQduW3ZtrXZ/9GG3Kfrnfuu4H)
### Ungolfed
Apply the function [`words`](https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#v:words) to our space-separated string of symbols `":) =( (: )= :( ): =) (= :| |: "` to get a list, and get the *n*th element [`(!!)`](https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#v:-33--33-) for every *n* in our input string, combining the results. *n.b.* [`(=<<)`](https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#v:-61--60--60-) is equivalent to [`concatMap`](https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#v:concatMap) in this case, mapping a string to a list of strings and concatenating the results. `read . pure` converts a character to an int, by lifting a character to a string, then [`read`](https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#v:read)ing to an int.
```
f x = ((words ":) =( (: )= :( ): =) (= :| |: " !!) . read . pure) =<< x
```
[Answer]
# [R], ~~59~~ 48 bytes
different approach:
```
substr(":)=((:)=:():=)(=:||:",n<-2*scan()+1,n+1)
```
thanks to @aaron for directing me on again :)
original:
```
el(strsplit(":)x=(x(:x)=x:(x):x=)x(=x:|x|:","x",T))[scan()]
```
beats
```
c(":)","=(","(:",")=",":(","):","=)","(=",":|","|:")[scan()]
```
by 1 byte
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
“=:)|(”“ØḟƝoṣẈ’ṃs2ị@D
```
[Try it online!](https://tio.run/##AT0Awv9qZWxsef//4oCcPTopfCjigJ3igJzDmOG4n8adb@G5o@G6iOKAmeG5g3My4buLQET///8xMDIzNDU2Nzg5 "Jelly – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~64~~ ~~60~~ 59 bytes
-1 byte thanks to mazzy
```
-join($args|% t*y|%{':)=((:)=:():=)(=:||:'|% S*g(2*"$_")2})
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V83Kz8zT0MlsSi9uEZVoUSrska1Wt1K01ZDA0hYaWha2Wpq2FrV1FipA6WDtdI1jLSUVOKVNI1qNf/XcnGpqaQpKBkYGhmbmJqZW1gqcSkpQcQMDY2MjI1NTJBElP4DAA "PowerShell – Try It Online")
Takes a string, splits it in `toCharArray`, and then indexes into the emoji key by casting the character to its numerical value, doubles it because each emoji is two wide, and then takes the `substring` from that spot plus one higher. Finally it joins this all up into one string and pushes it to output.
[Answer]
# [Icon](https://github.com/gtownsend/icon), ~~78~~ 75 bytes
```
procedure f(n);s:="";s||:=":)=((:)=:():=)(=:||:"[!n*2+1+:2]&/n;return s;end
```
[Try it online!](https://tio.run/##TYy9DsIwEIN3nuLIgC50oA3ip4nyJIgBtRepAxd0SUFIffcSYOliW58tD13keX5I7KgfhSAga5esV8qlaSputUcsYlFbr9HbQtVlzVtTNZU1182OnVAehSE54n7xdb8NjHoFAPQkecNLhkwYsIYcodW/5s8WMWBTm317OJ2PZfE9/AA "Icon – Try It Online")
[Answer]
## [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~87~~, ~~86~~, ~~82~~, 67 bytes
Props to @Artholl and @someone for helping to optimize
```
n=>$"{n}".SelectMany(x=>":)=((:)=:():=)(=:||:".Substring(x*2-96,2))
```
[Try it online!](https://tio.run/##Jcq9CsIwFEDh3acoweFeaQtGEEybLKIg6OTgnIZUA/UK@YGK9dljweUs3zGhMsHlYyLTOorl6UDpab3uBtuah/ZKFX0hM0m1ZB/6svpqB2viRdMbRqmYQAkwRwAKiSDFNIl5Sl2I3tEdxhWvdtuSI@ZmcfMu2rMjC3@t9y8yOkIPa75BxCb/AA)
[Answer]
# JavaScript (ES6), 87 bytes
```
n=>{for(s=":)=((:)=:():=)(=:||:",i=0;i<20;)n=n.split(i/2).join(s[i++]+s[i++]);return n}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
“LƇ§×Yþ’ḃ5$s2ị“:)=(|”ị@D
```
[Try it online!](https://tio.run/##y0rNyan8//9RwxyfY@2Hlh@eHnl436OGmQ93NJuqFBs93N0NlLHStNWoedQwF8hzcPn//7@hkbGJqZm5haUBAA "Jelly – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 34 bytes
```
Chop[":)=((:)=:():=)(=:||:",2]&Get
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@985I78gWslK01ZDA0hYaWha2Wpq2FrV1Fgp6RjFqrmnlvz3S01NKY5WKShITo/lCijKzCsJSS0ucU4sTi2OTtNRMLCyjP0PAA "Attache – Try It Online")
] |
[Question]
[
## Challenge:
**Inputs:**
* A string containing printable ASCII (excluding spaces, tabs and new-lines)
* A boolean *†*
**Output:**
The parts of the String are divided into four groups:
* Lowercase letters
* Uppercase letters
* Digits
* Other
Based on the boolean, we either output the highest occurrence of one (or multiple) of these four groups, or the lowest, replacing everything else with spaces.
**For example:**
Input: `"Just_A_Test!"`
It contains:
- 3 uppercase letters: `JAT`
- 6 lowercase letters: `ustest`
- 0 digits
- 3 other: `__!`
These would be the outputs for `true` or `false`:
```
true: " ust est "
// digits have the lowest occurrence (none), so everything is replaced with a space
false: " "
```
(Note: You are allowed to ignore trailing spaces, so the outputs can also be `" ust est"` and `""` respectively.)
## Challenge rules:
* The input will never be empty or contain spaces, and will only consist of printable ASCII in the range `33-126` or `'!'` through `'~'`.
* You are allowed to take the input and/or outputs as character-array or list if you want to.
* *†* Any two consistent and distinct values for the boolean are allowed: `true`/`false`; `1`/`0`; `'H'`/`'L'`; `"highest"`/`"lowest"`; etc. Note that these distinct values should be used (somewhat) as a boolean! So it's not allowed to input two complete programs, one that gives the correct result for `true` and the other for `false`, and then having your actual code only be `<run input with parameter>`. [*Relevant new default loophole I've added, although it can still use a lot of finetuning regarding the definitions..*](https://codegolf.meta.stackexchange.com/a/14110/52210)
* If the occurrence of two or more groups is the same, we output all those occurrences.
* The necessary trailing spaces are optional, and a single trailing new-line is optional as well. Necessary leading spaces are mandatory. And any other leading spaces or new-lines aren't allowed.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
## Test cases:
```
Inputs: Output:
"Just_A_Test!", true " ust est " (or " ust est")
"Just_A_Test!", false " " (or "")
"Aa1!Bb2@Cc3#Dd4$", either "Aa1!Bb2@Cc3#Dd4$"
"H@$h!n9_!$_fun?", true " @$ ! _!$_ ?"
"H@$h!n9_!$_fun?", false "H 9 " (or "H 9")
"A", true "A"
"A", false " " (or "")
"H.ngm.n", true " ngm n"
"H.ngm.n", false " " (or "")
"H.ngm4n", false "H. 4 " (or "H. 4")
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ØṖḟØBṭØBUs26¤f€³Lİ⁴¡$ÐṀFf
¹⁶Ç?€
```
**[Try it online!](https://tio.run/##AVYAqf9qZWxsef//w5jhuZbhuJ/DmELhua3DmEJVczI2wqRm4oKswrNMxLDigbTCoSTDkOG5gEZmCsK54oG2w4c/4oKs////IkhAJGghbjlfISRfZnVuPyL/Mg "Jelly – Try It Online")**
The boolean values are `2` and `1` (or any other positive even/odd pair), which represent `True` and `False` respectively. I will try to add an explanation after further golfing.
Thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) for saving 2 bytes, and to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) for saving 4 bytes! Thanks to one of [Erik's tricks](https://codegolf.stackexchange.com/a/146736/59487), which inspired me to save 4 bytes!
## How it works
Note that this is the explanation for the 35-byte version. The new one does roughly the same (but tweaked a bit by Lynn), so I won't change it.
```
ØBUs26f€³µ³ḟØBW,µẎLİ⁴¡$ÐṀF - Niladic helper link.
ØB - String of base digits: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz'.
U - Reverse.
s26 - Chop into sublists of length 26, preserving shorter
trailing substrings.
f€³ - For each, keep the common characters with the input.
ØB - Base digits.
³ḟ - Get the signs in the input. Filter the characters of the
input that aren't alphanumeric.
W,µẎ - Concatenate (wrap, two element list, tighten).
ÐṀ - Keep the elements with maximal link value.
L - Length.
⁴¡ - Do N times, where N is the second input.
İ - Inverse. Computes 1 ÷ Length. 2 maps to the length itself,
because 1 ÷ (1 ÷ Length) = length; 1 yields
(1 ÷ Length), swapping the maximal numbers with minimal ones.
F - Flatten.
¹⁶e¢$?€ - Main link.
€ - For each character.
e¢? - If it is contained by the last link (called niladically), then:
¹ - Identity, the character itself, else:
⁶ - A space.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~166~~ 158 bytes
```
t=lambda c:('@'<c<'[','`'<c<'{','/'<c<':',1-c.isalnum())
def f(s,b):x=map(sum,zip(*map(t,s)));print''.join([' ',c][x[t(c).index(1)]==sorted(x)[-b]]for c in s)
```
[Try it online!](https://tio.run/##fYxRT4MwFIXf9yvKJLm9pqth24s4IlNjzJ73RgiWUlwNFEJLgvrjUfFhM5q9ffc759z2zR0asxxHF1WizgtBZEghho3cQAIMnif6@KKriUJgwUJybUVl@poizgpVkpJalmM4RLVoqe1r9q5bevl9OGYR8abttHEA/LXRhiZAgMk0GRJHJXJtCjXQANMosk3nVEEHTBZ5mpZNRyTRhlgcSzrf9dZl22yvrPPmjOy7XuHsr38Ulf0JtiLw7vJlfC9XFw/F2j8dPcX@wTPXmednZW9uz0cnL38VuXmpuflfHTeTWx/d@Ak "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~193~~ ~~186~~ ~~179~~ 158 bytes
*-7 bytes thanks to NofP and his suggestion of `cbind`*
*-6 bytes using `outer`, -1 byte switching `[^a-zA-Z0-9]` with `[[:punct:]]`*
*-21 bytes thanks to MickyT for pointing out a list of characters is allowed*
```
function(S,B){y=outer(c("[a-z]","[A-Z]","\\d","[[:punct:]]"),S,Vectorize(grepl))
S[!colSums(y[(s=rowSums(y))=="if"(B,max,min)(s),,drop=F])]=" "
cat(S,sep='')}
```
[Verify all test cases](https://tio.run/##tZDRSsMwFIbv@xRrHCyBdGy6m40F7RQd3la8sKslS7OukCYhSdFO9uw1VRFRwSsJh5z/gyTfielEtTXUtLDmbq8Ki4LdYBl1u0YyVykJE7xCLy1RjeMGMghSGh0ygEEaRw/9vtkUfUoXuj@xyDKAcILvOXPKVAcOS8O1QChI0pApkTS1hW0KLTHq6T0gRAiodgCucE2fcV1JBC3CuDBKk@sMZQQMQMCo8yqWazIaoWNXLqNPw5veMCFcQOuM1aJyHgHg3/xb@9FjTybR/J@8NbWOe3N/h6Da8jf9oKZaixaW2JvdNtblcX7HrQu90rcY02m42p7Gl@zs5KqYDT1aXwz3oZzn4TD3f3D@K4k/aj2WZT2WP7uZ9PMyOMUTv6ZfaoJQ9wo "R – Try It Online")
Takes `1/T` as truthy (`max`) and `0/F` as falsey (`min`), and takes `S` as a list of single characters.
[Try it online!](https://tio.run/##JY49T8MwEED3/IpyS@@kCwKJqcIDHRB7JAZcD8FxWkvxh86OIEX89tCI6ekNT3qyTv5TelkwuHpJQ6Fm3D236zhHW32K2PGRfhaV5uoELYLu26sBBv3Sfmw8nYbN9CFvxcEYIO743dmaxF8dnsXliajp9J1NUzeHgovGoiR9/QuRUuBHwCOH/puDj4SFmAdJWb0aMgp20Ni@3laKy2q/p991xFKl5MlXhLf7eA5P8XYBpPWjMfxA6x8 "R – Try It Online")
In my original version (with NofP's suggestions), the matrix `y` is constructed by evaluating `grepl(regex, S)` for each `regex`, then concatenating them together as columns of a matrix. This results in multiple calls to `grepl`, but as `S` is fixed, it seemed that something else needed to be done. As I noted:
>
> There are potentially shorter approaches; `mapply`, for example:
>
>
> `y=mapply(grepl,c("[a-z]","[A-Z]","\\d","[^a-zA-Z0-9]"),list(S))`
>
>
> unfortunately, this will not simplify as a matrix in the 1-character example of `"A"`.
>
>
>
I used `outer` rather than `mapply`, which *always* returns an array (a matrix in this case), and was forced to `Vectorize` `grepl`, which is really just an `mapply` wrapper around it.
I also discovered the predefined character group `[:punct:]` which matches punctuation (non-space, non-alphanumeric) characters.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~27~~ ~~26~~ ~~24~~ 22 bytes
-2 bytes thanks to [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb)
-2 bytes thanks to [Leo](https://codegolf.stackexchange.com/users/62393/leo)
Takes `' '` as `False` and `'a'` as `True` (In Husk, whitespace in Fasly and all other characters are Truthy)
```
Fż▲→ġ#¬Ö#≡⁰Ṫḟë½D±o¬□m;
```
[Try it online!](https://tio.run/##AUIAvf9odXNr//9GxbzilrLihpLEoSPCrMOWI@KJoeKBsOG5quG4n8Orwr1EwrFvwqzilqFtO////ycgJ/8iSC5uZ200biI "Husk – Try It Online")
### How does it work?
```
Fż▲→ġ#¬Ö#≡⁰Ṫḟë½D±o¬□m; Function, takes a character c and a string S as arguments
m; Wrap each character in S into it's own string
ë List of four functions returning booleans:
½D±o¬ Lower case?,Upper case?,Digit?,Not alphanumeric?
Ṫḟ Outer product with find†
Ö#≡⁰ Sort on how many characters have the same Truthyness as c
ġ#¬ Group strings with equal numbers of spaces
→ Take the last group
Fż▲ Squash it all into one list
```
*†* `ḟ` is a function that takes a predicate `p` and a list `L` and returns the first element of `L` that satisfies `p`. If no element satisfies `p` a default argument is returned. In this case `' '`. By applying `ḟ` to a one character string, we are essentially saying `if p c then c else ' '`.
`Ṫ` Is function that takes a function `f` and two lists `L1`,`L2`. It returns a table of `f` applied over all pairs of `L1` and `L2`. In this case `f` is `ḟ`, `L1` is our list of 4 functions, and `L2` is the list of one character strings.
After `Ṫḟ` we have a list of strings where each string is the result of replacing characters which don't satisfy one of the rules with a `' '`.
**NB:** In newer versions of Husk, `ġ#¬Ö#≡⁰` can be replaced by `k#≡⁰` for a 3 byte saving!
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~31 29~~ 28 bytes
```
SMS?' `ṁ§foSM≠?▲▼⁰M#Kë½D±o¬□
```
Uses 0 for minimal and 1 for maximal character counts.
[Try it online!](https://tio.run/##AUkAtv9odXNr//9TTVM/JyBg4bmBwqdmb1NN4omgP@KWsuKWvOKBsE0jS8Orwr1EwrFvwqzilqH///8x/yJIQCRoIW45XyEkX2Z1bj8i "Husk – Try It Online")
## Explanation
Lists of functions are cool.
```
SMS?' `ṁ§foSM≠?▲▼⁰M#Kë½D±o¬□ Inputs are bit B and string S.
ë Make a list L of the four functions
½ is-lowercase-letter,
D is-uppercase-letter,
± is-digit, and
o¬□ not is-alphanumeric.
M# For each of them, take number of matches in S,
?▲▼⁰ take maximum or minimum depending on B,
oSM≠ and mark those entries that are not equal to it.
§f K Remove from L the functions that correspond to marked entries, call the result L2.
These functions test whether a character should be replaced by a space.
SM Do this for each character C in S:
`ṁ Apply each function in L2 to C and sum the results.
S?' If the result is positive, return space, otherwise return C.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 140 bytes
```
g=lambda x:x.isalnum()-~(x>'Z')*x.isalpha()
def f(s,m):k=map(g,s).count;print''.join([' ',c][k(g(c))==sorted(map(k,range(4)))[m]]for c in s)
```
[Try it online!](https://tio.run/##bY1NT4NAFEX3/RVDJZn3munEVja2QVt1YVy7khAy5Vs6D8IMCW786xjFCEldvnPvua/5sEVN22HI/bPSp0SxftfL0qgzdRpw/Qn9HX/juBphUyjARZJmLAMjNO4qX6sGcmFQxnVHdt@0JVnO5XtdEgSccRGHQQU5xIi@b@rWpgl8O5VoFeUpeIgY6DDM6pbFrCRmcMhg@dIZGx2j19RYZynYeoOLS3r9A49q4zyctofH@ObqKfHcqf5PMirPB7dw6DZy3Cjr6H4yLoPfH7PRaUVSriXN7D8wK3jjPXwB "Python 2 – Try It Online")
Jonathan Frech saved a byte. Thanks!
Highest is `m=-1`, lowest is `m=0`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes
```
ØWṖs26µẎØṖḟW⁸;
¢ċ@€S¥€N⁹¡Mị¢Ẏ⁸f€ȯ€⁶
```
[Try it online!](https://tio.run/##y0rNyan8///wjPCHO6cVG5kd2vpwV9/hGUDOwx3zwx817rDmOrToSLfDo6Y1wYeWAkm/R407Dy30fbi7@9AioFKgijSg6In1QOJR47b///8reTioZCjmWcYrqsSnlebZK/03BAA "Jelly – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~448~~ ~~439~~ ~~432~~ ~~362~~ ~~361~~ ~~354~~ ~~352~~ ~~348~~ ~~343~~ 320 bytes
```
s->b->{int w[]=new int[4],m=0,n=-1>>>1,l;s.chars().forEach(c->{if(c>96&c<123)w[0]++;else if(c>64&c<91)w[1]++;else if(c>47&c<58)w[2]++;else++w[3];});for(int W:w){m=W>m?W:m;n=W<n?W:n;}l=m-n;m=b?m:n;return l<1?s:s.replaceAll("["+(w[0]!=m?"a-z":"")+(w[1]!=m?"A-Z":"")+(w[2]!=m?"\\d]":"]")+(w[3]!=m?"|[^a-zA-Z0-9]":"")," ");}
```
[Try it online!](https://tio.run/##pZLRbpswGIWvl6cwLJpggBUS1i1xIE27TtW0XXVSpFEWOcRJyGyDsClqM549M4V16rRKW@ECme/4Pz7yYY9vsJNmhO/X348Jy9Jcgr1isJAJhZuCxzJJOXyNelmxokkMYoqFAJ9xwsGhJySWin1ot02vZJ7wrf0bnKUpJZjboFGCAOyS7Y4I@Skt1Rv44CicYOUEh4RLUIaRz0kJ1Dr0Ipv5A5v7jhsEgWtTJGC8w7kwTLhJ8wsc74y4ntsYcTA@eRVP3eHILMNBZFmIUEHAvXLiKWXsKsF9LHhvlfDmnRKGvwTLKsNRhCoTqQOMOtBiUpoH5i8CNltMGOL@YsrViqOK@szhiPmrGVOfOZFFzgGdujMxETAnGcUxmVNq6KFuGXUqzWczHTt3@kTXzRq5DZo7Xx/QsEHX1@tIsaiBowb@CL@pabV74Iyj@wlbB7qJqiNqm2nLuEmTNWCqH6O58zAC2FRdvbi6FZIwmBYSZkqQlBuPyoA4y@itoV@e9ncaHy@1/lL1P9PNVpB5QUwT9UD7dPXbYHXnteE/J/tYCLmcL78opHWO9Vez/880x652thqensejl@/XXr9zricNn5Gte5gOp19CvmWQd/9//vB5SPIsI@8Jo6pXHX8C "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~118~~ 116 bytes
Takes `0` (lowest) or `-1` (highest) for its second argument.
-2 bytes thanks to Lynn.
```
->s,t{s.gsub(/./){|c|[/\d/,/[a-z]/,/[A-Z]/,/[^\da-z]/i].group_by{|x|s.scan(x).size}.sort[t][1].any?{|x|x=~c}?c:" "}}
```
[Try it online!](https://tio.run/##dZLBboJAEIbvPMWAHLCBRawXmyDa9kB67qlICSyIJO1KWEhAoK@Ou5RWqnUus5n/m5l/s5sVQdXtiNlpK6rmNUUxLQJFR/q0bnDj6NtQV3XH144uzxvtrc/v27AvJS6Ks0ORekFVN2VDEcU@UcoposkxahE9ZLmTu47hIp9UFkdK8wu3Fn6QQGrbLiFpkYMJjgAgvRQ09zbea0RzUVKBh2awPAFzBRIwlZeYCtINfHamR9HTG98QH4P5@gnfT57Dhcw6RsOvVN5ir@W9SJaeKHu7glh8x9jPWgYRgKtsh3Wr42zJ7s0s/7oajA@Tf2NwdcHMrpHvMTYi8SciP3e6ZICpQC7I/4aNnPXg4gZoI3ZcMNAVhP4JUeTjvUc/Ehwpc/Zz/CymDaSwI84dP7vQdic "Ruby – Try It Online")
## Ungolfed
```
->s,t{
s.gsub(/./) {|c|
[ /\d/,
/[a-z]/,
/[A-Z]/,
/[^\da-z]/i
]
.group_by {|x| s.scan(x).size }
.sort[t][1]
.any? {|x| x =~ c } ? c : " "
}
}
```
[Answer]
# Python 2, ~~190~~ ~~183~~ ~~174~~ 173 bytes
Thanks to Jonathan Frech for shortening it
```
from re import*
def f(i,c):
q='[a-z]','[A-Z]','\d','[\W_]';l=[len(set(finditer(p,i)))for p in q]
for j,k in enumerate(l):
if k-eval(c):i=compile(q[j]).sub(' ',i)
print i
```
This takes the strings `'max(l)'` and `'min(l)'` as true and false. (I don't think this breaks the rules...?)
This is longer than the other two python answers but different so I thought I'd post it. I'm not a great golfer so I'm guessing this could be improved further but all the things I tried didn't work.
[Try it online!](https://tio.run/##dY1BS8QwEIXP9ldMYyGJtIKrF5XiVj2IZ0GwW0q3nbCzm6Zpmor652t7kUV0Lo@Px/fGfvpdZ1bTpFzXgkOg1nbOnwUNKlCC4lreBNCnPK@Sr4LHPM@StyU3zQKb17LgtzrNNRoxoBeKTEMenbAxSSlV58ACGeiLABbYx4cF0Ywtusqj0PP@CSk4JPheaTG/o7TuWksaRZ/vC3k@jFvBgc97AVhHxgNNSrCndbQLzXUZRqUazR2DGFhbfcyDTAb/9WR@@udx8GVWvuDgQwbz/fL/7I/8rLoI77er9UN9efrYXEXsyJ@@AQ "Python 2 – Try It Online")
[Answer]
# PHP, ~~161~~ 158 bytes
```
for([,$s,$z]=$argv;~$c=$s[$i++];)foreach([punct,upper,lower,digit]as$f)(ctype_.$f)($c)?$$i=$f:$g[$f]++;while(~$c=$s[$k++])echo$g[$$k]-($z?min:max)($g)?" ":$c;
```
Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/e26f96f1adb2a7d5702c478480c8e5384ff2260c).
* first loop: for each position, remember the group of the character
and count the occurences of groups that the current character is *not* in.
(that negation saved 3 bytes)
* depending on second parameter, pick min non-count for truthy, max non-count for falsy.
* second loop: if (group of current character) non-count differs
from min/max non-count then print space, else print character.
[Answer]
## JavaScript (ES6), ~~151~~ 149 bytes
```
g=
(s,f,a=[/\d/,/[A-Z]/,/[a-z]/,/[_\W]/],b=a.map(r=>s.split(r).length))=>s.replace(/./g,c=>b[a.findIndex(r=>r.test(c))]-Math[f?"max":"min"](...b)?' ':c)
```
```
<input id=s oninput=o.textContent=g(s.value,f.checked)><input id=f type=checkbox onclick=o.textContent=g(s.value,f.checked)><pre id=o>
```
Sadly the rules probably don't allow me to pass `Math.max` or `Math.min` as the flag. Edit: Saved 2 bytes thanks to @JustinMariner.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes
```
ØWṖs26µẎØṖḟW⁸;
¢f@³L$ÐṂFe@Ѐ³¬¹⁴?a³o⁶
```
[Try it online!](https://tio.run/##AV0Aov9qZWxsef//w5hX4bmWczI2wrXhuo7DmOG5luG4n1figbg7CsKiZkDCs0wkw5DhuYJGZUDDkOKCrMKzwqzCueKBtD9hwrNv4oG2////SEAkaCFuOV8hJF9mdW4//zE "Jelly – Try It Online")
-6 bytes "borrowing" from Erik's post :D
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~307 + 34~~ ~~306 + 27~~ 295 bytes
My "interesting" take on the challenge.
Thanks to *Kevin Cruijssen* for ~~cutting down the import bytes~~ removing the import entirely!
```
s->b->{String t=s.replaceAll("\\d","2").replaceAll("[a-z]","0").replaceAll("[A-Z]","1").replaceAll("\\D","3"),v="";int a[]={0,0,0,0},i=0,z=0,y=-1>>>1;t.chars().forEach(j->{a[j%4]++;});for(int x:a){z=x>z?x:z;y=x<y?x:y;}for(;i<s.length();i++)v+=a[t.charAt(i)%4]!=(b?z:y)?" ":s.charAt(i);return v;}
```
[Try it online!](https://tio.run/##fZFPj5swEMXv@RSOtZVsAVbS9tI4Jk3/qYf2tLcStBqIk5h6DcWGBiI@O3VCpKp7qCxLo5@fn2bmFdBCVFbSFPufY67BWvQdlLnMELIOnMpR4RWscUqzQ2Nyp0rDvtyL9aOrlTmG/9V8KEstwYRoEscxOiKBRhvFWRRfJoicsKyWlYZcbrUmeLfb4xC/xvQfmkDUp54vXvJt9OPKly/4bvfJ0zeYhq3AmCvjECSpuCzC2xlCJRZh728nomUcx0vuWH6C2hLKDmX9GfITKXyTkBSv3qZBwAfKPSdXo/MK6KUX57jfnFc978R53fmq48NVwdXaMi3N0Z0I5SoIaBsISCb7rSOKesO5INmmX3V0gxFe2b9vvJauqQ1q@TAixGc@jKrJtA/jnklbqj169jmRaX9Jinw3XoZQNq0bZX7JkCxT5spv5W9ZfwQr/VjyVwPaEuzqRmLKb18eO@vkMysbxyrv5rQhRwZVpTsCySKl9zqjN/0wG8bx6/uH09y8e5o/PPnEN@PBm8o/ "Java (OpenJDK 8) – Try It Online")
**Explanation:**
```
String t=s.replaceAll("\\d","2")
.replaceAll("[a-z]","0")
.replaceAll("[A-Z]","1")
.replaceAll("\\D","3")
```
First replaces each group with an integer between 0 and 3 using some simple regex and stores this in a new String.
`int a[]={0,0,0,0},m,i=0,z=0,y=-1>>>1;`
Initialises an array of integers as well as a couple of other integers to use later. Sets the `y` variable to the max int size using unsigned right bit shift.
`t.chars().forEach(j->{a[j%4]++;});`
For each character in the modified string, this uses its ASCII value modulo 4 to calculate the index of the aforementioned array to increment.
```
for(int x:a){
z=x>z?x:z;
y=x<y?x:y;
}
```
This then loops through the counts of each group stored in the array and calculates the minimum (`y`) and the maximum (`z`).
```
for(;i<s.length();i++)
v+=a[t.charAt(i)%4]!=(b?z:y)?" ":s.charAt(i);
```
Loops through every character in the String again, checking if the group of that characters group is equal to the min/max (using the modulo trick mentioned earlier). If it isn't equal, then a space is added to the new String in the characters place, otherwise the original character is added.
`return v;`
Finally return the new String!
[Answer]
# Bash, ~~229~~ ~~227~~ 212 bytes
```
LANG=C;g="A-Z a-z 0-9 !A-Za-z0-9";declare -A H
f()(((i=$2?99:-1));r=$1;for h in $g;{ t=${r//[$h]};t=${#t};(($2?t<i:t>i))&&i=$t&&H=([$h]=1);((t-i))||H[$h]=1;};for h in $g;{((${H[$h]}))||r=${r//[$h]/ };};echo "$r")
```
[Try it Online](https://tio.run/##ZY3Bb4IwGMXv/hVfscH2UBH1gl2nnUtGlmUnT1sWggiUZMOk1MuQv50VlZiF2/fe@7337eNKte2bfH8RW54LR7IPiNkvzFgAyAp729PhhzT5jnUKTEI4ygglhBQCz9dBsGI@pVwL7PPsqEFBUQLOeQ1G4Fp73idWXw3vxNg0nBBbMg/FyjwWlLquHTGuGwrSYcKnFjDMJudzeHV483/WDtSXqOkgff/hQWPZNFFHcLB2aJvB5PVUmUhGu7QyaAL@aGDNOkvGPnrazzfbZDF@PizxjRzaFzrcYIXKIEI4yk7l@gYP3OtyP9V3p2X@My37Tq/u2bJT7R8)
[Answer]
# JavaScript (ES6), 139 bytes
```
s=>b=>s.map(c=>++a[g(c)]&&c,a=[0,0,0,0],g=c=>c>-1?0:/[a-z]/i.test(c)?c<"a"?2:1:3).map(c=>a.map(v=>v-Math[b?"max":"min"](...a))[g(c)]?" ":c)
```
Input and output is an array of characters. Takes actual boolean values for input.
A different approach from [@Neil's answer](https://codegolf.stackexchange.com/a/146776/69583); almost avoiding regular expressions. Instead, I used a series of checks to determine the category of each character:
* Digits return `true` for `c>-1` because non-digits fail mathematical comparisons
* Uppercase letters match the regex `/[a-z]/i` and have codepoints less than `"a"`
* Lowercase letters match that regex but have codepoints not less than `"a"`
* Symbols pass none of those tests
## Test Cases
```
f=
s=>b=>s.map(c=>++a[g(c)]&&c,a=[0,0,0,0],g=c=>c>-1?0:/[a-z]/i.test(c)?c<"a"?2:1:3).map(c=>a.map(v=>v-Math[b?"max":"min"](...a))[g(c)]?" ":c)
;[["Just_A_Test!", true],["Just_A_Test!", false],["Aa1!Bb2@Cc3#Dd4$", true],["Aa1!Bb2@Cc3#Dd4$", false],["H@$h!n9_!$_fun?", true],["H@$h!n9_!$_fun?", false],["A", true],["A", false],["H.ngm.n", true],["H.ngm.n", false],["H.ngm4n", false]]
.forEach(([S,B])=>console.log(`"${S}", ${B} -> "${f(S.split``)(B).join``}"`))
```
```
.as-console-wrapper{max-height:100%!important}
```
] |
[Question]
[
## Background
You are planning your trip away from the Diamond City, and must travel through Diamond Road. However, Diamond Road branches away from Diamond City to different locations.
Out of curiosity, you'd like to measure the total distance of unique roads used for all paths.
We define a path as a string that only contains `/` or `\`, which represent roads. You will be given a list of paths that can be traversed.
Starting from a central left most point, a path can be plotted on a map such that every `/` denotes a path upwards and every `\` denotes a path downwards. On every path, each road must strictly go from left to right.
Subsequent roads must be joined at the same level as the previous road if they are different types. If they are the same type, the level will change.
For example:
Given `//\\/\\\`
The map generated would be:
```
/\
Start here _ / \/\
\
\
```
Since you can have multiple paths, these paths may cross and share the same road.
For example:
Given `/\ /\/`
The map generated would be:
```
Start here _ /\/
```
Here, the first two roads in both paths are shared, but the total length of roads used would be 3, as shown on the map.
You must calculate the amount of unique roads used in all paths.
## Your Task
* Sample Input: A list of paths used, or a string of paths separated by spaces.
* Output: Return the total length of roads used.
**Explained Examples**
```
Input => Output
/ \ / \ => 2
Map:
Start here _ /
\
Of the roads used, the total distance is 2.
```
```
Input => Output
/\/ \/\ /// => 8
Map:
/
/
Start here _ /\/
\/\
Of the roads used, the total distance is 8.
```
```
Input => Output
//// \/\/ /\/\ //\\ => 12
Map:
/
/
/\
Start here _ /\/\
\/\/
Of the roads used, the total distance is 12.
```
```
Input => Output
/\//\//\/ \/\/\\//\ \//\/\/\/ \//\//\// /\/\/\/ \/ \\\ \//\/ \ => 28
Map:
/\/
/\/\/
Start here _ /\/\/\/\/
\/\/\ /\
\ \/
\
Of the roads used, the total distance is 28.
```
**Test Cases**
```
Input => Output
/ \ / \ => 2
/\/ \/\ /// => 8
//// \/\/ /\/\ //\\ => 12
/\//\//\/ \/\/\\//\ \//\/\/\/ \//\//\// /\/\/\/ \/ \\\ \//\/ \ => 28
\ => 1
/ => 1
\ \/\ => 3
/\ \/\/\/ => 8
/\ / \/\ \ => 5
//////////////////// => 20
////////// ////////// => 10
////////// \\\\\\\\\\ => 20
\ /\ \/ /\ \\\\\\\\\\ => 13
\/\ /\/ //\ \\/ \/ /\ / \ => 10
/\ /\/ /\/\ /\/\/ /\/\/\ /\/\/\/\ => 8
/\ \/ /\ /\ \/ /\ /\ \/ \/ \/ /\ /\ => 4
\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ / => 2
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins.
ps. I need help with tagging this question
[Answer]
# [Python](https://www.python.org), 59 bytes
```
lambda L,*i:len({i:=(*sorted(i),d)*(d>" ")for d in L}-{()})
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVFBboMwEFSvfsWKk41IHZpWQkTk1htP2EsqgmqJYkTIoYrykl4iVe0z-o_2NfWuTWi41IAYz8zOeuHts3sdnm17fq8L_DgM9SL7Xjfbl6dqC2USm7zZtfJo8kLGe9sPu0oalVQqltUmgkjVtocKTAvlaXGU6qRCxCMJJQm2cwFLlQswiYUCytt915hBRlBsXIAAIk07SOtw1xMySU1dbAg7_9x8aUCgx9XcCY0OakdoTUQmNCEkWnse2ZmSFSb64hg3BHwAan9zChIE3qPngg4TA4jBEk6VCd9TaP9CCOkrwWFcF5qBPz_LD3z6-eLI5R8JrrX0SsPLCnU0H_CwMy1dCRy_CYs62MIYlDtWzsBkZec9Tfjv5Qfx__EX)
Takes inputs as in the test cases, i.e. a single space separated string.
## How?
Encodes unique path elements by their left end and their direction.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 7 bytes
```
~pᵉloÐũ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FqvrCh5u7czJPzzh6MolxUnJxVDxBbeYVkUr6SvpKMXEAAkoI5YLKBYTA-HpQ2T09SHCIAZUGMTQRyiIiUFohcqgKEDTgyIK4cLshWG4RSCj9SEaoFJww5CUo5gNlQOTYJfBlSL8CLMSxoF5F-EJhGlIHkMKFphiLABNAhKGOOVisACEs-COQWLjVI8a_Ajl-mhGoEY2uiReESyGITuXJgQw0CBpFgA)
A port of [@Albert.Lang's Python answer](https://codegolf.stackexchange.com/a/262600/9288).
```
~pᵉloÐũ
~ Choose any item from the input
p Choose a prefix
ᵉ Ð A pair of
l Last item of the prefix and
o The prefix sorted
ũ Remove duplicate results
```
---
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 11 bytes
```
~e:∫xᵈÐcŤ~ũ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FpvqUq0edayueLi14_CE5KNL6o6uXFKclFwMlV5wi2lVtJK-ko5STAyQgDJiuYBiMTEQnj5ERl8fIgxiQIVBDH2EgpgYhFaoDIoCND0oohAuzF4YhlsEMlofogEqBTcMSTmK2VA5MAl2GVwpwo8wK2EcmHcRnkCYhuQxpGCBKcYC0CQgYYhTLgYLQDgL7hgkNk71qMGPUK6PZgRqZKNL4hXBYhiyc2lCAAMNkmYB)
-2 bytes thanks to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
```
~e:∫xᵈÐcŤ~ũ
~ Choose any item from the input
Each item represents a path
e Character code
So / and \ are represented by two different numbers
: Duplicate
The first copy represents the directions of the roads
∫ Cumsum
These are the y coordinates of the end points
x Range from 0 to length - 1 (without popping)
These are the x coordinates of the end points
ᵈÐc Group the above three results into a list
Ť Transpose
~ Choose any of the (x, y, direction) triples
ũ Remove duplicate results
```
`-n` counts the number of results.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 61 bytes
```
s=>s.map(c=>x/=1/c?x:c<{_:s[x+c]=s[x+c]||++n}?2:5,x=1,n=0)&&n
```
[Try it online!](https://tio.run/##hVFdb4IwFH3vr7hP0k7WCxoT4lZ82x/Yo3WG1GJcEBzowjL325n9QCcvK5DennPuaU95zz6zRtW7w/GxrDa6y0XXiLTh@@xAlUhbFDGqRTtXz9/rebNsx2ol3HQ@j8flz2Iyn4WtiMNSRGw0KrunWn@cdrWmQd4EjNc627zsCv36VSoahcHpmCcWPhSZ0hTfKH9gIFLc7kOg67BlIlVV2VSF5kW1pTldcs7bFWOsQ5BgPpHChKC8lHgBEA2QEDSVNDA6XFplbKRwg6@KfmEKZyDRvdZFmhLsWjrM83BDQEov8adKCHGbEnSTBG8/JdbNNvrdwAWw9MwefzisZ/SHgnsuvuPkdfg@ExBs2gEXT4nsL8WS6GU@h/HtOwfFTer/gwnw3@OC/AI "JavaScript (Node.js) – Try It Online")
-2B from Arnauld
# [JavaScript (ES12)](https://nodejs.org), 55 bytes
```
s=>s.map(c=>x/=1/c?x:c<{_:s[x+c]||=++n}?2:5,x=1,n=0)&&n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVHdTsIwGI23fYrvirUy-zEIcZl23PkC3kmRkNIRkrEhk2RGfBJviNHn8DnkaVx_AOHGbsu-nnO-0572_bMop3r7kYmv9XN2Ff9cVyKt-GKypEqkNYoI1aBO1O3rOKmGdVuNNhvRbhdvg27SD2sRhYXosFar8O0PNyv9tJ6vNA2yKmB8pSfTu3mu718KRTth0KhiCy_zidIUHym_ZCBSnC1CoOOwZiJVZVGVueZ5OaMZHXLO6xFjzK2w3V18I0gwn0ihS1A2JTYAogFigqaSBkaHS6uMjBSO8EGxn5jCGUh0r3WRpgQ7lw7zPBwRkNJL_K5iQtyiBN1PgrfvEetmG_1q4AJYum-3fz6sZ-cPBadcdMLJw_B9JiDYtGdc1CNyfyiWRC_zOYzvvvOsOEr9PZgA_z0uiLvIXw)
[Answer]
# Excel (ms365), 251 bytes
Not short perse, but I tried to make it so that one could freely add more values to column A:
[](https://i.stack.imgur.com/gwxvU.png)
Formula in `B1`:
```
=LET(x,TOCOL(A:A,1),s,SEQUENCE(MAX(LEN(x))),r,REDUCE(EXPAND(0,ROWS(x),,0),s,LAMBDA(y,z,HSTACK(y,TAKE(y,,-1)+SWITCH(MID(x,z,1),"/",1,"\",-1,"")))),REDUCE(0,s,LAMBDA(y,z,LET(c,CHOOSECOLS(r,z+{0,1}),y+ROWS(UNIQUE(FILTER(c,MMULT(--ISERR(c),{1;1})=0)))))))
```
There is probably still a considerable amount of bytes to be saved.
My idea was:
* Start with an array of zero's based on the amount of rows in input;
* Iterate as much as the longest input;
* During step 2 we add 1 if character equals '/', -1 if character is '/' or we add an empty string (results in error);
* If this 2d-array is completed we can iterate each pair of columns (thus: 1 & 2, 2 & 3 etc.) to count the unique rows if no error exists;
* Do this for all pairs and we get the total amount of distance travelled.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εÇDηOā)ø}€`Ùg
```
Input as a list of strings.
Port of [*@alephalpha*'s Nekomata's answer](https://codegolf.stackexchange.com/a/262596/52210), so make sure to that answer as well!
-2 bytes thanks to *@alephalpha*
[Try it online](https://tio.run/##yy9OTMpM/f//3NbD7S7ntvsfadQ8vKP2UdOahMMz0///j1bSj4nRh2ElHSUgCUYQEYiAPkxQH8EHYyAXXQ5MggBCKZilFAsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1sPt7uc2@5/pFHz8I7aR01rEg7PTP@v8z86WklfSUcpJgZIQBmxOgpAwZgYCFcfIqWvDxUHsaDiIIY@QkVMDLJmGIYrBknrQ9RCpeCGIClHmImQA5Ng0@FKkVwKtxTOhTkb5hYkJ@gjCyJ7EK4cC0CXgYQHbskYLADJcXAXIbFxa9CH6dGHBjJUvT6aGWiRh6QH2QxkIRRRbCGGMBuvCBa3oPiXJgQw3GMB).
**Explanation:**
```
ε # Map over each string of the (implicit) input-list:
Ç # Convert the string to a list of codepoint integers (47 if /; 92 if \)
D # Duplicate this list of 1s and -1s
η # Get the prefixes of the copy
O # Sum each prefix together
ā # Push a list in the range [1,length] (without popping the list)
) # Wrap all three lists on the stack into a list
ø # Zip/transpose; swapping rows/columns, to create a list of triplets
}€` # After the map: flatten the list of lists of triplets one level down
Ù # Uniquify this list of triplets
g # Pop and push its length
# (which is output implicitly as result)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
l{sm.e,bS<d
```
[Try it online!](https://tio.run/##K6gsyfj/P6e6OFcvVScp2Cbl//9odf2YGH0YVtdRUAdSYAQRgorow0T1kQTAGMTHkIVQIICkHMJUjwUA "Pyth – Try It Online")
Uses the idea that each unique road can be identified by its angle and starting position. Given any prefix of any input element this corresponds to looking at the last character and a "path key" which is the path up to that character sorted.
### Explanation
```
l{sm.e,bS<dkdQ # implicitly add kdQ
# implicitly assign Q = eval(input())
m Q # map Q over lambda d
.e d # enumerated map d over lambda b, k
, # 2 element list:
b # value (last char)
S<dk # sorted(d[:k]) (path key)
s # flatten nested list
{ # deduplicate
l # get the length
```
[Answer]
# [J](http://jsoftware.com/), 20 bytes
```
[:#@~.@;(/:~,{:)\&.>
```
[Try it online!](https://tio.run/##hZFRa8IwEMff8ykOBdPM7tLWDaSurmxzMBh72KtXRIayDcFBfRP86l3u0nZWB6ZNm9zvn7v8k@@qh3oNWQoaQoggdf0a4fH99bmap/38gPkksOkh3KeGBjitjHp7QGhRUlAU9CnEoSWTh4t4mFxpsnrwhcbJ1erjcwtruJvgInYlLFkgS2Ct1WfMNYaWVSwhOtcQCD8d@FemWvlFbMFZ0k9bWG42sFuVuxJ@lmV53yiCYJH0MN9jYSBzllwd92lK6bDY42GevqCGTA9maBxIoOBDipSrB9yzKSTqyBUHxuofKwxikfpXMPEQZE4@VnP4iwBRLanLjZVPpqz/kdR2w5GSZLLOb0P2yEGe38q2TpukjI4QdFncYdS2et3RTXRZPFJinZnA9ob8bjhvjWsdNa4b89S6uHTnLLzhg7j4eL/KVL8 "J – Try It Online")
This is mostly a port of Albert Lang's excellent approach, with one twist:
* Instead of sorting the prefix and appending the last element, we can sort *everything* (including the last elm) and append the last element.
* This allows for the golfier `(/:~,{:)` to replace `(/:~@}:,{:)`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 24 bytes
```
.
$%`$&¶
%O`.(?=.)
D`
.+
```
[Try it online!](https://tio.run/##hU@7DUIxDOw9hYsX9BBSbgJEQ09B6yIUFDQUiNkYgMWCPyF5ICSS2PKdrbv4dr5frqea5mPhmmlKZVo9H5QOJc@7bV7TvlDe1AoW1iCIZmgNkIYDMIIS78fzhljJjiW41ufBsEgbUXkVIEMmFAqwKjzFHb/PguTfrPSj2q7recGahbFOow3Eujz266u@Qf@nj38WQ8Zc/1@8AA "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite which accepts a list of space-separated examples for convenience. Explanation:
```
.
$%`$&¶
```
Get all of the prefixes of all of the roads.
```
%O`.(?=.)
D`
```
Remove prefixes that have the same number of each type of road, excluding the last road.
```
.+
```
Count the total unique distance.
[Answer]
# JavaScript (ES12), 52 bytes
*My initial answer was buggy. This fixed version takes inspiration from [@l4m2](https://codegolf.stackexchange.com/a/262594/58563) and [@Albert.Lang](https://codegolf.stackexchange.com/a/262600/58563) (although the relationship with the latter one is not obvious anymore).*
Expects a list of characters.
```
a=>a.map(c=>1/c?s=1:a[c+=s*=2^c>{}]||=++n,s=1,n=0)|n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVFNTsJAGI3bnuILm87QOkMBE4IZWOkFWDJomtIiSW2xLQsD3MDEjTs1MUbv4MoTeAFdcgGv4Mw3A4gbO-30m_fe9_Pa-5csH8dPz4l4nVfJYeezHYpeyC7DGYlEL-BRvxRBNxxGnijronkW9Rar0XIpPC_zFeNnokGXmc39KOKr-bSISS0pa5QVcTg-nabx4DqLSIOyKh9UxTSbEMrKWTqtSE1mSpbkxUkYXZASRA8WDkAaVzCEcx9CH_J5BSMQUKqRKiXihNWpFhI59iinx1ZfxCodEjJkjIUjhKM8K_M0Zmk-IZr2wFXLAzwIgaX74H6_3a4f7tTuQhfc9eONS1X6ihpPT18H7xwk6Ed1bTpcqpArgHMNdByuI6lhbnCJygCl5kZa6hDwLA1medghIKWV2HYdxxRzuHlJ7K3CloPFMM-MgTNqUJ-PcKy_F5Zs_KJgnwv2OLm9bJ7qoHvivscFLQetaw5JbmXWhq5raauTG9cb83LrwmbuB7uKKGzrD_HvMn7Nf_wB)
### Commented
```
a => // a[] = input array
a.map(c => // for each character c in a[]:
1 / c ? // if c is a space:
s = 1 // reset s to 1
: // else:
a[ //
c += // build a lookup key by appending to c:
s *= // the updated 'signature' s of the path:
2 ^ // obtained by multiplying by 2 if c = '/'
c > {} // or by 3 if c = '\'
] ||= ++n, // increment n if this key was not yet encountered
s = 1, // start with s = 1
n = 0 // start with n = 0
) | n // end of map(); return n
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
WS«J⁰¦⁰Fι≡κ/↗¹¶\»≔LKAθ⎚Iθ
```
[Try it online!](https://tio.run/##RY29DsIwDIRn/BRWJ0cqKqwwISYQA@Jn8xKV0ESEtDQpDIhnDykFIVnW@e47udSyLWtpY3xoYxXSyjVd2IfWuIqEwCeM1t21OdQ0yXEi5jA61y2SEegfJpQa6fKBSukVZkU2w22qBpodm52pdMhx2pdO6iw7G35pxo4564MXvGDhvakcbZSrgqatUpeFtel5jreELK2SLSUxVJfSB7oJMY@x4GIY4LS4l/C5efC@OfwdYP4iwBDHd/sG "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:
```
WS«
```
Loop over the roads.
```
J⁰¦⁰
```
Start each road at Diamond City.
```
Fι
```
Loop over each road segment.
```
≡κ/
```
If it's a `/`, then...
```
↗¹
```
... draw a `/` and move up left, otherwise...
```
¶\
```
... move down and draw a `\`.
```
»≔LKAθ
```
Get the count of cells covered.
```
⎚Iθ
```
Clear the canvas and output the count.
The first 16 bytes suffice to output the map itself:
```
WS«J⁰¦⁰Fι≡κ/↗¹¶\
```
[Try it online!](https://tio.run/##RYvNDoIwEITP7FNsemoTTPGKT6An489tL00ttLECgSIHw7NX/ozJZDM734y2qtW18jEO1nmD/Fg1fbiG1lUlFwI/kJz6V3OreZZiJg6QFHWL3AnsBhe0Rf5cSlp1BplkOZ6naeD5vbm40oYU9/PoYQrV@/CjjCoiNoMRxhglyVVA06HZwvLTmm0c/gkQbRUgiLu3/wI "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 99 bytes
```
f(char*p){int a[4096]={},n=0,s=0,c;while(c=*p++)~c&4?s=0:a[s+=1<<(c&=1)*6]&++c||(a[s]|=c,n++);p=n;}
```
[Try it online!](https://tio.run/##hU9ha8IwEP2eX3E4LEnbLRVE2GrcDzEySlptoIvFdBtM3V/vLom2bgyW5MK9d493d@p@p1Tfb6mqi0PcsqM2HRTrefa42IjjOTUiSy2Gyj9q3VRUibhNEvalovkz8k/F2iZitlxSFYkZixebKEnU6USR35yESg2K81aY/NzfaaOat7KCpe1KvX@oV8Q1ey20oe97XTI4EgA3B8QWBGQ5Qqs/q5cOmisOU@yqrtGmopFNIWpScIaGwQoyhhqA9oDOWzqZos8KpqU0ExSlsKWWsZycew4SMAiX@HPMOScYHnDggZK@Hp4vSJeCxzJwlzqMDEh5kaA9GhCHnFFw4C4LPaXv@PvckPA3K4eD3t7X/zesa@FYT/OLIKwL437DqlcwzOnlP5PRxnX9//Jv "C (gcc) – Try It Online")
it will collide when the strings have >= (2^6 = 64) of either direction.
increase the 6 (+1) and 4096 (\*4) to make it even better, to a theoretical maximum of 16 and 4294967296 (16 GiB of RAM, max 65535 of either direction). on TIO it only works up to 10 and 1048576 (4 MiB of RAM, max 1023).
] |
[Question]
[
Your function must accept one [string](https://codegolf.meta.stackexchange.com/questions/2214/whats-a-string/8964#8964) and return the opposite
The opposite string is a string where all characters go in reverse order, all letters are replaced with the opposite mirror letter from the English alphabet and are changed in case, and all digits are replaced with opposite mirror digits
**opposite mirror for letters** means that `a` must be replaced with `z`, `b` must be replaced with `y` and so on. In general let's say we have some letter which index in alphabet is `Index` then it must be replaced with letter which index is `25 - Index` (25 if zero based)
**opposite mirror for digits** means that `0` must be replaced with `9`, `1` must be replaced with `8` and so on. In general let's say we have some digit which index in `0123456789` is `Index` then it must be replaced with digit which index is `9 - Index` (9 if zero based)
If there is a symbol from non English alphabet or digits in string then you don't change it just move to the correct position in reversed string
Input string can contain any printable character. I mean that there also can be Chinese symbols, Arabic symbols, Russian symbols and so on. But all symbols will be printable
**Test cases**:
```
Hello world! --> !WOILD LOOVs
Z 02468 a 13579 A --> z 02468 Z 13579 a
~!@#$%^&*() --> )(*&^%$#@!~
(I) [LOVE] {PROGRAMMING} ,,more,, ..than.. ??10000000000!! --> !!99999999998?? ..MZSG.. ,,VILN,, }tmrnnzitlik{ ]velo[ )r(
By the way мне нравится программировать! --> !ьтавориммаргорп ястиварн енм BZD VSG By
```
The shortest code in each programming language wins!
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~22~~ ~~14~~ 12 bytes
```
P8Y2tP10YSXE
```
Try it at [MATL Online](https://matl.io/?code=P8Y2tP10YSXE&inputs=%27Hello+world%21%27&version=22.7.4)
**Explanation**
```
% Implicitly grab the input as a string
P % Reverse the input
8Y2 % Push the predefined literal ['0:9', 'A:Z', 'a:z'], a lookup array
t % Duplicate this array ...
P % Reverse ...
10YS % And circularly shift by 10 ...
% to construct the replacement array ['9:0', 'z:a', 'Z:A']
XE % Perform the translation
% Implicitly display the result
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 7 bytes
- 2 bytes by AndrovT porting [Suevers MATL answer](https://codegolf.stackexchange.com/a/257949/96037)
```
ṘkrḂ₀ǔĿ
```
No questionable constants :p
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZhrcuG4guKCgMeUxL8iLCIiLCJIZWxsbyB3b3JsZCEiXQ==)
**How it works:**
```
ṘkrḂ₀ǔĿ
Ṙ Reverse string
krḂ Bifurcate [0-9A-Za-z], (duplicate and reverse)
₀ǔ Shift string by 10 [9-0z-aZ-A]
Ŀ Transliterate
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + common Linux utils, 53
```
printf -vA %s {Z..A} {9..0}
tr a-z0-9A-Z $A${A,,}|rev
```
[Try it online!](https://tio.run/##PcFNC4IwGADg@37FO9LQ2Mbs25PtECZkhocORoGRYWAaUwxa66@vW89zydvSmKe8190NaC/AbkFljAkNymeMa9RJyOmbU1/QDCxhKUGI/siiN2ZTVFUDr0ZWV4wy4OPpfAk5eJPZwgeBvng1sOzzcOS4yIlcOG6Tw/oEap8mYSriONqFGgh5NLIgBBjryrxmDILA438Y/wA "Bash – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 26 bytes
```
RaRXA(Yz.AZ)@(Ry@?_)RXD9-_
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCJGYVtcbltcIkhlbGxvIHdvcmxkIVwiXVxuW1wiWiAwMjQ2OCBhIDEzNTc5IEFcIl1cbltcIn4hQCMkJV4mKigpXCJdXG5bXCIoSSkgW0xPVkVdIHtQUk9HUkFNTUlOR30gLCxtb3JlLCwgLi50aGFuLi4gPz8xMDAwMDAwMDAwMCEhXCJdXG5de1xuUCgoU1RhKVdSXFxcIlwiXFxcIikuXCIgLT4gXCIueyIsIlJhUlhBKFl6LkFaKUAoUnlAP18pUlhEOS1fIiwifVZhV1JcXFwiXCJcXFwiXG59IiwiXCJIZWxsbyB3b3JsZCFcIiIsIiJd)
Regex-based solution, as pip doesn't have bifurcation (that I could find). Annoyingly, there is no variable for lowercase and uppercase alphabet in pip, so it had to be constructed manually. Explanation:
```
R # Reverse
aR # The input regex replaced with
XA # The pattern [A-Za-z]
(Y # Yank (store in variable y) the
z.AZ) # alphabetical iterable (a-z + A-Z)
@( # at the index of
@?_) # the matched character in
Ry # the reverse alphabetical iterable
R # Regex replace again with
XD # Regex for digits
9-_ # Mirrored digit
# Implicit output
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
RžKÂT._‡
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/6Og@78NNIXrxjxoW/v@v4ampEO3jH@Yaq1AdEOTvHuTo6@vp516roKOTm1@UqqOjoKdXkpGYp6enYG9vaAAHiooA "05AB1E – Try It Online")
Port of Suever's MATL answer.
(Saved a byte by porting it)
#### Explanation
```
RžKÂT._‡ # Implicit input
R # Reverse
žK # Push [a-zA-Z0-9]
 # Bifurcate
T._ # Shift by 10
‡ # Transliterate
# Implicit output
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org),~~77~~ 76 bytes
```
f=([c,...x])=>c?f(x)+Buffer(c).map(t=>t+c>t?57-c:/[a-z]/i.test(c)?187-t:t):x
```
[Try it online!](https://tio.run/##XcoxDoIwFADQ3VPUiTbYIgoWMUB08gwShubTGkylBL5KvHw1js7v3dRTTTB2A/Letdp7U9AaVkKIuWFFCZWhMwtPD2P0SIGJuxooFiWGUGKVSg55VCv@bqJOoJ7wW6o4kxxzZPnswfWTs1pYd6WGBmdtrSMvN9p2GTB2WPz5haw3yS4jisTbVO7J8Zf8Bw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python](https://www.python.org), 86 bytes
```
lambda s:''.join(chr(abs((47<a<58)*105+(96<a|32<123)*187-a))for a in map(ord,s[::-1]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PZDNattAFIXpVk9xRX4040rCsuNYNnadmBTXYEchARXsOjCuJaRmLAlJqXHShNbrQB4gm0BI18Yh4IWdvMJo2T5NB1Xkzmbuud85c5m738E0dnzv_sGuf3k8j21F_2NSMh6OCERVSVK_-a6HvjohIsMIoZ1yjdRKOs5p-dJ7VNmtkR_FQk0rFLmilxWCse2HQMD1YEwC5IcjOepXq4o2wDhLNyaOSy3QqgIAkWEIdU4H5zHCahRQN0YSKMoHkDCfB6HrccE_k8C1wUYEQ73OLRaNLJBs4lIpi73_-876ZFHqw8QP6UhMM8TPRrtzAB3DMCOhB_nCzq7Ol9OKpXIF9lPkIlN7mUqEa3FvY3PrdDuHcEpglNs-3drc2BOvBdTG0O8Y5scBXB4dG63j_W63fdi6Alke-6Ely6CqsUM8VYVGQ8u_lZjtI1beSm80ONztnbQ4LMtmu3PI7VfxOPS8Czem7tklDL5b1O8DDpHQnELsWDAhU2ArtmbPwNbJTzZnC7ZMZsmv5BbYKxde2FMqr_hZpv2CzTlwk22Q3CSz1PXCh8sUm_PbU9q_QnLLo2Z8sEjlNbBn_tgKmr0DME9a0Jz-_-5_)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 15 bytes
```
T`dLld`Ro
O^$`.
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyQhxScnJSEon8s/TiVB7/9/j9ScnHyF8vyinBRFrigFAyMTMwuFRAVDY1NzSwVHrjpFB2UV1Tg1LQ1NLg1PTYVoH/8w11iF6oAgf/cgR19fTz/3WgUdndz8olQdHQU9vZKMxDw9PQV7e0MDOFBU5HKqVCjJSFUoT6xUuLDnwt4LWxUu7L3YcGHDhU0Xdlxsuth4sV/hwn6gwL4Lm8HCe4BwB5i/6cIGoIIeRQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`dLld`Ro
```
Transliterate the characters in the string `0..9A..Za..z0..9` to the characters in the reverse of that string.
```
O^$`.
```
Reverse the string.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
≔⪫⪪⭆χι⁵⁺αβθ⭆⮌S§⁺⮌θι⌕θι
```
[Try it online!](https://tio.run/##TYzNCsIwEITvfYp420AEPXjqqRexglDsE8Qm1MCy@W317WNiERwYmBk@ZnrKMFmJOXcxmpngag3B6NAkGFMwNN@kg@NBMMMFOxUPuESQgj14KZ63zVCof/iuVx2ihp7ckrYZKtulnpR@w/fgB3m@PZ8NKfA1V7U5XzSiZS8bUO2avF/xAw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪫⪪⭆χι⁵⁺αβθ
```
Build up the transliteration string `01234A..Za..z56789` by taking the digits, splitting into two substrings of length 5, then joining them with the upper and lower case letters.
```
⭆⮌S§⁺⮌θι⌕θι
```
Map over the reversed input string, finding each character in the transliteration string and looking up the character in the same position in the reversed transliteration string, but with the original character appended so that if it wasn't found then cyclic indexing picks up the original character.
[Answer]
# [Python](https://www.python.org), ~~105~~ 103 bytes
```
lambda s:s.translate([47<c<57and 105-c or(64<c<91or 96<c<123)and 187-c or c for c in range(128)])[::-1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY303MSc5NSEhWKrYr1SooS84pzEktSNaJNzG2SbUzNE_NSFAwNTHWTFfKLNMxMgGKWhvlFCpZmQJahkbEmWN7CHCyvkKyQBiYz8xSABqWnahgaWWjGakZbWekaxkKs21hQlJlXopGmkZlXUFqioampCRFfcNNKw1NTIdrHP8w1VqE6IMjfPcjR19fTz71WQUcnN78oVUdHQU-vJCMxT09Pwd7e0AAOFBUhRgAA)
*-2 thanks to @Mukundan314*
[Answer]
# [Factor](https://factorcode.org/) + `spelling`, ~~88~~ 86 bytes
```
[ reverse ALPHABET "0123456789"over >upper glue dup reverse 10 rotate zip substitute ]
```
[Try it online!](https://tio.run/##RY/tTuJAFIb/cxVv8SNgagN@wm4iQjRIUqyRXTaBYNLFWW0sbXdmqgsEs8tvE2@FYEz4AXoL0ytiT4rCmWRm3vM@58yZX3Zb@nz@vVY5L3@BYL9D5rWZgAiY6zreDe4Y95gLW7Qdh3bht8UKM9gfyW2BgDMpuwF3PImviX4CFMkz6uDjwefutZaEhu3tI2g/rIp5AtOy6mJBNZDZ2TvIwUZ2d/8wj@In2vswGh@GveAfteO19Y2rza1U@pNMp7Y2rzbW1461xwWTqqTRNK36aQv9i0urfFmsVul/A@h6x@dM12EY8tb2DAOFQjazDG01p5ZfRq5QIL7aqJWJ1/V6xTynDgPZ4Z7Xc6Tr3PXRumeu30SapxYTlLqQtwwPdhdqqmbqFWoW/VUjNVaTaBj9i56h3inxpl7i9JTWJNZjNSLgaTVJ9BQN48I38icxOaLbS6zfET1TtyEZ4zg9g3ql96YoNU5Qr5VR6iYG8yY4u2dcMBTNi7Ni6fQbkpnszu7e/sFhLp/0ycNRGAR03Lghw3UYLCuyGXBf2pKh5wQQ4U8hHRmSbM07dgBj/h8 "Factor – Try It Online")
Port of Suever's [MATL answer](https://codegolf.stackexchange.com/a/257949/97916).
[Answer]
# [Python](https://www.python.org), 86 bytes
```
lambda S:S.translate(dict(zip(A[65:],A[::-1])))[::-1]
*A,=range(123)
A[91:97]=A[48:58]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PZDPattAEMbpVU8xIv92jSysJE5kgerISXEMdlRiUMCqAmot16JrrZC3CXZIaH0O5AF6CZTmbBwCPtjJK6yOydN0kUVmLzPf_OabYf88xCPWp9H935755d9P1ivqrw7xB1-7PrSNtsoSPxoSnwWoG35jaBzGyHL3yoanWK5hFDUPY7xKpIKlmIL-HiBtewdLllvRjMq-Z1rurm6UdS93P-zRBAiEEdA4iFAJGxKECgUTiDpkiViA1WFMQoa2oFj8CFtYgjgJI4Z6KMRgmkDxyur-7UNwHBBC4ZImpCtnuHxmN5pH0LRtZyh1oLS9u6eDD9pOeb8CVoaMc7WTq750Ix-srW-cbxYQzgiMCpvnG-trB_KNhBoY3KbtfPLg6vOpXT-1Wq3GSf0aFGVAk0BRQFVZ349UFapVrfQecn6PXHkPvVoVcKvTrgtYUZxG80SMX7NBEkXjkJHwxxV4FwGhLuAESbURsH4Al_4I-IIv-RPwZfqLT_mMz9NJ-ju9A_4ihGf-mMkL8eZZPeNTAdzmF6S36SSbehbNeYZNRfaY1S-Q3gmriWjMMnkJ_EksW0CtcwROuw610eq7_wM)
[Answer]
# [Zsh](https://www.zsh.org/) `--braceccl --extendedglob`, 86 bytes
```
M=({a-z} {0-9} {A-Z})
<<<${(j..)${(Oas..)1//(#m)?/${M[1+$#M-$M[(Ie)$MATCH]]:-$MATCH}}}
```
[Try it online!](https://tio.run/##PYrfSgJBFIfv5ynO4hQztbu6/bcM2yJUaDMkulAMRndsjXEn1gXTZaO6DnoVMQIvtF5h9om2zaDzg/P7zseZDL10yEP5EEInYF3e7QrgjyH3Xe7eCdlBPUJJ6hyTiBmTGKKCUcy2bTRjikqlEo7IvWnSrOpsmIGVz5PcgJbzOHJa1ibOOQZ2WqTGKXbs67Nqu31o/FEcxylFaOT1BYeAMxeMAETf50fgStQD/MvIlT5Pq1wICSMZCFdDTShs7ewdAANre3e/CDZ60k5yeO12fYNQRGoUWhf1m/M2RFeNeqVhO07tshKDrg9kwHUdTDP0mG@aUC5bhf/RNHQ6htDjMGJjUAu1VJ@glsmzmqqZmievyUvyDuo7E1/qY6UXWeare6am2cObhn4A "Zsh – Try It Online")
Find the `(I)` last index in the array, count from the end to find the replacement, `:-` fallback to the original letter if none was found.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 135 bytes
In order for UTF-8 characters outside of the ASCII range to not turn into gibberish when reversed I used ICU's functions to iterate the string.
```
#import<unicode/utf8.h>
f(s,i,t)char*s;{i=0;U8_NEXT(s,i,0,t);*s&&f(s+i),isalnum(*s)?putchar(187-82*isdigit(*s)-*s):printf("%.*s",i,s);}
```
[Try it online!](https://tio.run/##PVDtSgJBFP3vU1y3kplx3FZN3drMCsIEP0IyoqhYVjcHdFd2xkTEqH4HvYoYQT@yXmF8IptVdC4D95xz77lwnMSj4ywWW6zb8wNx2PeY4zdbu33hmnr7KOIiThkV2GnbAeHWiOUNq2E@VM@uL5eKoTSL8FhMDcYZpozbHa/fRYTjQq8vwjWUNHMJM0UYb7JHJkIpof5BL2CecJG2oxOuKSuOrfFCUdC1mYeefNbEMIoAhB5A@O1dPkQA2nmr0/Fh4AedZlSjK@4GjNRe1gQbkulMbh9O1sJz9Hhre@c@RhBeU6iE4bZcuzq7g9FFvVasn1QqpWpxDJR2/aBFKei6aNuerkOhkDQ2L7q5djoE0W7BwB6CkUyl9zLZnLkP8kfO5BfI2fxFTuRUfs/f5q/zD5B/iviVn0v6R9X3Ek/lRA28r02rjXJZNWMKhIg8tyIKuH6ALCDCApUlR5qGV5EAbMLjkD8CTS0JvPJxERHxOLZCr8h48Q8 "C (gcc) – Try It Online")
Ungolfed:
```
#import<unicode/utf8.h>
f(s,i,t)char*s;{
i=0;U8_NEXT(s,i,0,t); // Get the next codepoint
*s&& // Terminate recursion at end of string
f(s+i), // Run the string in reverse
isalnum(*s)? // Is [0..9,A..Z,a..z]?
putchar(187-82*isdigit(*s)-*s): // Yes, invert character
printf("%.*s",i,s); // Print uninverted codepoint as UTF-8
}
```
[Answer]
# JavaScript, 109 bytes
```
s=>String.fromCharCode(...[...s].reverse().map(c=>/[a-z]/i.test(c,n=c.charCodeAt())?187-n:n<48|n>57?n:105-n))
```
Try it:
```
f=s=>String.fromCharCode(...[...s].reverse().map(c=>/[a-z]/i.test(c,n=c.charCodeAt())?187-n:n<48|n>57?n:105-n))
;[
'abcdefghijklmnopqrstuvwxyz',
'Hello world!',
'Z 02468 a 13579 A',
'~!@#$%^&*()',
'(I) [LOVE] {PROGRAMMING} ,,more,, ..than.. ??10000000000!!',
'By the way мне нравится программировать!'
].forEach(s => console.log(f(s)))
```
[Answer]
# [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 136 bytes
```
>]>:88*`v>:68*1-` v
^~v*8f3:_^v`+2*78:_,:!#@_
^<>+\`#v_^>!#v_,:!#@_
v`*8c::<
_7d*\`#v_^v$;>01-*v;
vf*-10< <v+**753<
v>2+b*+ >,:!#@_
```
[Try it online!](https://tio.run/##PYxdSwJBFIbv51ecQQud/WA/0h3HZdQgTMgML7qo3A9zzQtTEB2RSKrroL8iRuCF1l@Y/UXbotHzwoH3OYfTjfqz0UOklWiS8A5nlJJAcFakxNQCEMhbCkL7NvM9ESgWcSjzVYYzVR95LlfugozwPY7T@WdFQOg9Yy7ynR45rEW2zA1TI6KMQPSJZhougCsUQpyC7SLBLaVLFEjhhydJch4Nh2OYjyfDHkY3YFgnRQohmHbBKUENLXE1kz3yjkkuj3KNPNxetK7POvB01W7V27Vms3FZfwZVfRxPIlUFXZ8OwpGuQ6ViGv9gjE4XMB1EMA8XILdyJ79A7uIXuZJruYnf4tf4A@RPKr7l515v02z2fS1X6cE7/gU "Befunge-98 (FBBI) – Try It Online")
Not a hugely golfed answer, and probably invalid due to lack of handling for Unicode, but a fun exercise!
] |
[Question]
[
## Input
A single hex 6-digit colour code, capital letter, without `#`. Can also be a 24-bit integer if you prefer.
## Output
The closest HTML color *name* (e.g `red`, or `dark-salmon`, as defined as <https://www.w3schools.com/colors/colors_names.asp> or see below). Distance is defined by summing the difference in red, green and blue channels.
## Examples
>
> `FF04FE`: `magenta`
>
>
> `FFFFFF`: `white`
>
>
> `457CCB` (halfway between `steelblue` and `darkslateblue`): `steelblue` (round **up**)
>
>
>
## Rules
* Standard loopholes apply.
* Standard I/O applies
* Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g `red` = `#FF0000` = 16711680 > `blue` = `#0000FF` = 256
* If one hex code has two names (e.g. `grey` and `gray`), output either.
* Outputs can be capitalised and hyphenated how you like
* Trailing/preceding spaces/newlines are fine
* You must output the names in full.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
## Colors
As per suggestion in the comments, here are all of the color names with respective hex values in CSV format:
```
Color Name,HEX
Black,#000000
Navy,#000080
DarkBlue,#00008B
MediumBlue,#0000CD
Blue,#0000FF
DarkGreen,#006400
Green,#008000
Teal,#008080
DarkCyan,#008B8B
DeepSkyBlue,#00BFFF
DarkTurquoise,#00CED1
MediumSpringGreen,#00FA9A
Lime,#00FF00
SpringGreen,#00FF7F
Aqua,#00FFFF
Cyan,#00FFFF
MidnightBlue,#191970
DodgerBlue,#1E90FF
LightSeaGreen,#20B2AA
ForestGreen,#228B22
SeaGreen,#2E8B57
DarkSlateGray,#2F4F4F
DarkSlateGrey,#2F4F4F
LimeGreen,#32CD32
MediumSeaGreen,#3CB371
Turquoise,#40E0D0
RoyalBlue,#4169E1
SteelBlue,#4682B4
DarkSlateBlue,#483D8B
MediumTurquoise,#48D1CC
Indigo,#4B0082
DarkOliveGreen,#556B2F
CadetBlue,#5F9EA0
CornflowerBlue,#6495ED
RebeccaPurple,#663399
MediumAquaMarine,#66CDAA
DimGray,#696969
DimGrey,#696969
SlateBlue,#6A5ACD
OliveDrab,#6B8E23
SlateGray,#708090
SlateGrey,#708090
LightSlateGray,#778899
LightSlateGrey,#778899
MediumSlateBlue,#7B68EE
LawnGreen,#7CFC00
Chartreuse,#7FFF00
Aquamarine,#7FFFD4
Maroon,#800000
Purple,#800080
Olive,#808000
Gray,#808080
Grey,#808080
SkyBlue,#87CEEB
LightSkyBlue,#87CEFA
BlueViolet,#8A2BE2
DarkRed,#8B0000
DarkMagenta,#8B008B
SaddleBrown,#8B4513
DarkSeaGreen,#8FBC8F
LightGreen,#90EE90
MediumPurple,#9370DB
DarkViolet,#9400D3
PaleGreen,#98FB98
DarkOrchid,#9932CC
YellowGreen,#9ACD32
Sienna,#A0522D
Brown,#A52A2A
DarkGray,#A9A9A9
DarkGrey,#A9A9A9
LightBlue,#ADD8E6
GreenYellow,#ADFF2F
PaleTurquoise,#AFEEEE
LightSteelBlue,#B0C4DE
PowderBlue,#B0E0E6
FireBrick,#B22222
DarkGoldenRod,#B8860B
MediumOrchid,#BA55D3
RosyBrown,#BC8F8F
DarkKhaki,#BDB76B
Silver,#C0C0C0
MediumVioletRed,#C71585
IndianRed,#CD5C5C
Peru,#CD853F
Chocolate,#D2691E
Tan,#D2B48C
LightGray,#D3D3D3
LightGrey,#D3D3D3
Thistle,#D8BFD8
Orchid,#DA70D6
GoldenRod,#DAA520
PaleVioletRed,#DB7093
Crimson,#DC143C
Gainsboro,#DCDCDC
Plum,#DDA0DD
BurlyWood,#DEB887
LightCyan,#E0FFFF
Lavender,#E6E6FA
DarkSalmon,#E9967A
Violet,#EE82EE
PaleGoldenRod,#EEE8AA
LightCoral,#F08080
Khaki,#F0E68C
AliceBlue,#F0F8FF
HoneyDew,#F0FFF0
Azure,#F0FFFF
SandyBrown,#F4A460
Wheat,#F5DEB3
Beige,#F5F5DC
WhiteSmoke,#F5F5F5
MintCream,#F5FFFA
GhostWhite,#F8F8FF
Salmon,#FA8072
AntiqueWhite,#FAEBD7
Linen,#FAF0E6
LightGoldenRodYellow,#FAFAD2
OldLace,#FDF5E6
Red,#FF0000
Fuchsia,#FF00FF
Magenta,#FF00FF
DeepPink,#FF1493
OrangeRed,#FF4500
Tomato,#FF6347
HotPink,#FF69B4
Coral,#FF7F50
DarkOrange,#FF8C00
LightSalmon,#FFA07A
Orange,#FFA500
LightPink,#FFB6C1
Pink,#FFC0CB
Gold,#FFD700
PeachPuff,#FFDAB9
NavajoWhite,#FFDEAD
Moccasin,#FFE4B5
Bisque,#FFE4C4
MistyRose,#FFE4E1
BlanchedAlmond,#FFEBCD
PapayaWhip,#FFEFD5
LavenderBlush,#FFF0F5
SeaShell,#FFF5EE
Cornsilk,#FFF8DC
LemonChiffon,#FFFACD
FloralWhite,#FFFAF0
Snow,#FFFAFA
Yellow,#FFFF00
LightYellow,#FFFFE0
Ivory,#FFFFF0
White,#FFFFFF
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 231+21=252 bytes
```
s=>Color.FromArgb(Convert.ToInt32(s,16));f=s=>Enum.GetNames(typeof(KnownColor)).Select(x=>Color.FromName(x)).Where(x=>!x.IsSystemColor&x.A>254).OrderBy(x=>Math.Abs(x.R-C(s).R)+Math.Abs(x.G-C(s).G)+Math.Abs(x.B-C(s).B)).First().Name
```
Explanation:
```
using System.Drawing; //System library that handles Colors in C#
C=s=>Color.FromArgb(Convert.ToInt32(s,16)); //helper method. receives a hex string and returns it's Color
f=s=>Enum.GetNames(typeof(KnownColor)) //collection of color names from the System.Drawing.KnownColor enum
.Select(x=>Color.FromName(x)) //convert the color names to Colors
.Where(x=>!x.IsSystemColor&x.A>254) //filter out unwanted colors
.OrderBy(x=>Math.Abs(x.R-C(s).R) //order by increasing distance
+Math.Abs(x.G-C(s).G)
+Math.Abs(x.B-C(s).B))
.First().Name //return the closest color's name
```
For some reason, Tio complains that the namespace 'Drawing' does not exist in the namespace 'System', despite the source project [Mono](https://www.mono-project.com/docs/gui/drawing/) stating it's compatible. It works fine in VisualStudio though.
EDIT: apparently it [hasn't been implemented](https://github.com/TryItOnline/cs-mono/blob/master/README.md) into Tio yet!
[Try it online!](https://tio.run/##bc9Li8IwEAfwu5@i62FJWA2aah@4FpL0gewLdMFz7aZasMmSxLV@@m5rL0o9hfnNn5lJpseZLuqTLsTe2ly04SUKVXpuysUgPonsVRvVFCOrewMrv3cmj1IFFrOWtV4G1wrFSpZE7XeASfHHlUHfciWMjYEeTR0IF/myiUbiVKKEm8@05BqYyy@XOXgT8iyuQyBEG37kmQHV7dg2DaqmuT1wxdveU4VWurv8GnuuEAnwfAbRl/rhil7a0EdqDojsNKjQesyAhmgNX24w6TC5Q9ohbbbFhdIGQNSurxeDrSoMfy8EBzkYxrbvUG/Y/OveGaHuBPc9xFOX0b4T3w8j1veZEzqO23fbo9iPHuzFrj0nfXcp8WeTvseTcO49mONTHNl26/U/ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Node.js](https://nodejs.org), 1488 bytes
Takes input as a 24-bit integer. Outputs in lower case.
```
v=>(require('zlib').inflateRawSync(Buffer('TVRbm6o4EPxLE27CowziDOiIV+bwFkkrWUPCBBg/9tdvLurZFzGX7uqqrs6Z4fr2xvHv5OYEy9uZjRC3QOjY6r/oaH4X+ugqAXiWI/P1M28AzGxQPWHuBBkB6PrbpCPmyZs+GEb5Mwrag/O9sEn7TlJ+NSnCr4TRFk7z/+25mc7l5i0lnF6bQef6Pn6tiCBXkHo12yxTpo96wCbEqfbxRUjoB7tcxfvn0fJ4POgyeoYHuEo8IafINaY59co8exT1uJ+Uq/hVsn8KUykmzDTqzin6AcD8n/nb3Sur3nDSD9cmegUf5hHlhF6F6ySOviwY/bWwi/UO1ZiA4baIj1EtJL8wcbf8gspLJJyhrnE3yo6BExUbmx3/jLjFSis4pitCW83I/SrTVyEo3uQGiEh8Rpvi80U8+OMXVrXnTnTKowf7Z7i/fFsxfOdWx9l6XjdYDhLGHrxwvvkL75fqKwRHoS3RtahFsDEl5U8TRMudBbXrVP/8UsFgcOMP4xwJBPmlsVeLr8AH7J56TAiDsxR3nmTvRulHf4LotDQJzQptlsgyeFTxeUr1bYuwT/cdZlbyoDog0wRZN5TMy3wCpgS3PCNn0VPgHM927smgBvvvwhpeCRc/7GYEOq0KE2TjZ3mkIf6avPiOLd+nVVAQvXfiTmxr/ez9QlVvJa1vaLc01K6CEeBSkLDyfcvGVulk6zcp+slU5HrZUt++NfhG0Tote8p+QXpRVtgYy1mpGZb+h3Ye5npxWKQdyDF0dnUjaqEbHZzmswHzRbl4KKmmIt+ehob2A4OgLP0HfpI5r+Lm8VEzfaEgL9jVkra94GV8uGLK+7OQArnrTcfGVo3Z4TxKNt2FICgLtwbKTPYs8hj+Ba4kCedLO0eYtYK7u31p8wdlFZrWPdFz13ZdDQpmTpgHRobc32BGa+Nc92vWCA4TgTtKEvzvKCHtMSdWPd8LonsDeEBbd3YGegUvL+4NHaBvxQ2KlvKhloBbVEXXRvSDOfOCuLClOX78hflAf0YwJ6uZmiUOvKqshM86rSvQHzUNRD2rKsP2XYu1zOcPc89c/UZ2lN/cU6jYcPWoAYnyZBAtHoRfxY0Y9DGKCsPWizbWuPqq8xlae5mqPLS222Vgdk3Wz8hEVwtdlJd8d4Drphsvl+2HeuPxP8IQ2HutUO9LTzkKyjPtFbG0Vf2flOHgcGaY1w0Qg0JQoprR4QmryG6/eTZPqd434ZuazL5RtKtEv2LKlbf8yEDFKQtdLoInB/WyKR4Gtuq5uM+tSvu1KdougpD+Cjktza30Pw','base64'))+'').replace(m=/([a-z]+)([^a-z]+)/g,(_,s,d)=>[e=0,8,16].map(x=>e+=Math.abs((v>>x&255)-(t>>x&255)),t+=parseInt(d,36))|e>m||(o=s,m=e),t=0)&&o
```
[Try it online!](https://tio.run/##XZRbs5rKEsff8yl8irhZWVxFrB1XldxEQUEEFFL77OIyIMrN4c7O/uw5JqtOnST9Mj3/6V9XV0/P3LzWqwKYlPWnvAjBt2j1rV29IRA8mgQCZDqmiT@dvSZ5lHo1MLzuNOQBwjVRBCAyNW3Dz5iCFvVeFckFX3RjImjJ1kb9Trrf4dnSeY6LsWUdtmoDXWncXBbN4wErxqUjSPat3M41RxyWjXszeOqo3RwGYoUn0xe0iR/rS3LeYjqxJ9n1uOmP@lluOO7OMTr0S17PBrdCN6I/33fQizFtWYn5wkx36OGU85A2Dem@GDGUnGfBIp0neJpLjH8EEaPnTJ3w3OUuFwQ59GZZLJmO98VH5PeGdSu4RR30UZvj0Y7WtXgAhSM3YsFuvWh78Jz5MihY0JtEs0OtB3a1q5xVrOGejYL5GJOcWQcCm2O5T50aSOXCSVgGGYitaH6V06vESMxw0tqkczD/3CWYpRFusqZ9b3sjxHqnsl3gR2xclepuN1xhLlJDwXBib/lZT2E39Sadkoouk5o/s9QWO0HTHsSCao6bRLyyRtkmLG6xqLa/2PCSm7mpFF20cBcJFklVH2nhuV@mzOUWOsJV3ciw79r2ri7m0UPpDLk4UUbtXaVKENO5xZrGvgk5/wJtHWOtSooDba/Tfbfj9CytbKBCdi0vdnPGXCdC1RtUnpmt0aRyRKtFLRx347Gs0@rZQ8nsgQUJ32k6EwtCN/WHQihivDPcw9zcD1THl/GJ0vlDjtt6LO@X5KLKYq5t2@5aAt4IsMXGEbUHroikeXOp7L6NGK/VE00N0dy218f2EiVm1kMMjMtjarc7j2g9NcAJheFFwJ3uqjBEQbuxm/TOjEGJVqk1l6Fr1Sh6iK4b3CxqwJbo8VIadh07A5GVG9dHr5QD5nnZn5VjOAgSHubWzXuIvuyOWdXJo@GntKJk2bZGwbXwyTWtxaqOy1G5nUNUzVhbHCNPjNXlzb5Db0lvbLbZqAq60I5rmEMziDZ2Qbm02SuHmpS2fKzWna@YulOx1xvKefSdB6Gq4cCpHWXRUETJdmEqufCsh9JIUG4oHMvMLGPZKPyAIrmNhx6CJdme@TVtxmatiO3YKrxc70/hk2HVIq8EIHJ@SDmb52y2KkofZI9r@yOppK1yTQvOt8XLxWhPghZpfKPyqXZZsNcoXUe40@2Yxs0SS2uVR3Xdsww8tUd5tA6GQEKl0smL0xCjFugBuwwwyyXTAxZYzM0J9HOxdvLB5da1XBhR7@DOUtgofKWfk9E/N/rjwfapB@bZQ1dPJEnacXinziN7Fe2uDtNdyIa0AMtr1aYoKYNG73V2eyTlpra0pWqOd2W46bXkb3A7IqNUk@Ng4zlEhx9jfHcsSmjQxwwOGwYDpqs/Qpqi3cYb1blRK7XYkqqSPt/fIAqScqxDtdjmHHYeFIPe1M1j3uzR@tQ2hBIWTVwKKH@716NH4Xo3fZn6XgUYejqbodPnrwlBmXoBQLIVhnzxPo1/oTPky3/eHSx@Qf5@qV7C2ertC1jhL@wLwfz1mnkl0q/eALrae/X11fMrBGnf3vqP5Hw@@4TU/3NnLzW6Kj1YgW1eI@ELxcxmX8Fb9vUrUqyql2wFnhErfPbxY/EteF51kYLXtIiRqSThtCROVm@T6QSdRAjevyuz2QTDJpkXg7z2PvyGfLdfke/2jnTXpAa/AvR8wfPcz8C78g5UNQCpnza/Q7gkietfoB/KO1Q38NEUSfUbtMZ5gSJ/ht6Vd2gAaVp0MQQg/wWb/fnhQ1RAJJ@sJvifk3zyeUJ8X1F0Nvnnw2TSPvUf7YdeHhYZMpv8McF7Av9hk69P5hn0c0KEmHz@PCHp51k7e62LUw2TPEYI5vvGKksA@edgILPXKk2e80DMnsVO/191O3tW9O@3/wI "JavaScript (Node.js) – Try It Online")
### How?
The compressed string is 1683 characters long and looks like that:
```
"black0navy3KdarkblueBmediumblue1Ublue1EdarkgreenJK1green5J4(…)lightyellow68ivoryGwhiteF"
```
The colors are ordered from lowest to highest value. Each color is encoded as its name in lower case followed by the difference between its value and the previous value in base-36 and in upper case:
```
black[0] | 0x000000 + 0 --> 0x000000
navy[3K] | 0x000000 + 128 --> 0x000080
darkblue[B] | 0x000080 + 11 --> 0x00008B
mediumblue[1U] | 0x00008B + 66 --> 0x0000CD
blue[1E] | 0x0000CD + 50 --> 0x0000FF
darkgreen[JK1] | 0x0000FF + 25345 --> 0x006400
green[5J4] | 0x006400 + 7168 --> 0x008000
... | ...
lightyellow[68] | 0xFFFF00 + 224 --> 0xFFFFE0
ivory[G] | 0xFFFFE0 + 16 --> 0xFFFFF0
white[F] | 0xFFFFF0 + 15 --> 0xFFFFFF
```
### Commented
```
v => // v = input
( require('zlib') // using zlib,
.inflateRawSync( // inflate the
Buffer( // buffer obtained by
'TVRbm(…)Pw', // converting this string
'base64' // encoded in base-64
) //
) + '' // and coerce it back to a string
).replace( // on which we invoke replace():
m = // initialize m to a non-numeric value
/([a-z]+)([^a-z]+)/g, // for each color encoded as ...
(_, s, d) => // ... s = name, d = delta in base-36:
[e = 0, 8, 16] // using x = 0 for blue, 8 for green and 16 for red,
.map(x => // compute the error e:
e += // add to e:
Math.abs( // the absolute value of the difference between
(v >> x & 255) - // the component of the target color
(t >> x & 255) // and the component of the current color
), //
t += parseInt(d, 36) // start by adding the delta to t
) | e > m || // end of map(); if e is less than or equal to m:
(o = s, m = e), // update o to s and m to e
t = 0 // start with t = 0
) && o // end of replace(); return o
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~1015~~ 914 bytes
```
“¥.⁻ḲU3ŒẆȯ§.eḊC¤ŀ"}Ʋ59£Uŀ'⁶ɠıṇȥLcṆɓ?^¢Ỵɠ.ȮẆẆḊqʠu½ỊƑfĠ⁴ µ¥ɓƭÑUC½ṁUĿẆṃ⁹S/÷Ɓɗ>ṭ"»Ḳ33r64¤,Ọy“µṂFŀƲOḌẇȤạ2œxṾk,E.LẸpḄ2s⁵Ṛç¦ṆkAẋ=çw©ḌĊẒƤm`;ṄȧṄİɦbṠṆṛ⁴Ḟ[CƊėQẏƑ<:⁾Þḍ?çⱮ3ƈṗ¬!7Hẏywœ⁽Ẉ¤ṾƈpHṗ(⁾ƲḢdƲḃ'¦ṇ9ẏP¡ċ⁻ȤẒṬf§®ṬẒpJÞẒẸṪÄƊhḊḃ7ʠ%ƈėc+ġȦı©ḄO⁸ṗ:WṠß@Ä|ż_g¹Ʋ®[*ẹ5¡Ẹßė¶~[ȷ'ȧẊṖZẋ¦ẉ7Ġ⁽ė⁽ƁLP`²¶⁶* Ġv|$ṭⱮẋ_ƭø¦Ẇ-*ɓɼhCUṙƭƭƓS7Ø⁵¤³¢Ʋẉ!§ḟƇṣḟṛḳṠƬ4ẓḢTḌZżƇȦQxw}ḃçṣȮv⁷ȤĊẏyNỵʠÄ⁸hLġị³TİọȧfÞȤTO&ṡ°⁼`WẹạẇḂvðFmż]ɦo½ƓṂḟȯ#Æ⁺T)ṃç=ḣṆø⁽Wpʂqṫ&⁷¶S®¢ð:\ṚMĖḌ½⁽_ạ⁵]Xlȷg¿£⁺x0ṁo8ẒṛżøuɲẈ®§Bṡr:ċ³ḷb|Mku¬V°ḟƲ!ɦɠ4¬>ḷ^XḶɼ5[ṇƑȮ.XȮƙẎbḊÐþFæṁoOṗ⁺mṪ-&ƊṅƑḋ$!`€ɓḥƤ¡ɗbH⁻ḃÄ⁵!Ñėḅƈḳm⁴ḳcÐⱮ⁷ỤḍġḷȥṀSĖ»Ḳ
“⁸¢!İƝ\8¢[V⁸¢Ñ"ĠƙḶ-Æ⁷⁾Æ⁵¢⁸¢ƙhLṂS×®Ẓ©Aḅ¦ṚÆ&nj£ÇØ¿waþM=ÆḂḌ¢³(Ñḷx¦DẊ¢Aẓ©ḋ¬!ƁV ṾÐẉœ¦2Ä¢⁼C®⁶ẇ£ḋṀ¤çẠÐȧIæḌH€5ẋ¥®⁹µ⁻£⁴⁸¢AƇ¢⁸¢£*ç-Ụz¬>ƈ£ʋ¢^ạṭ(ÇṪĠ¤Çŀ¬ÇḞ¢ṪĠÐCȥṖÞ¦ø}×⁹YÐƬAÇ×CÆævÇ#©ḥƙ£sVṀṙ¤ỊAÞtỤ¦AǬ⁶ʠ¤⁼ƈµ£ŒÞ¿§Œ÷~2~Ðɲċ×⁻¤SƤÐ}Z¦Fƙ°¹£Ḣ©£Ṁx£⁹j£Ƒs¤ɓ8¬_ḶØz°®ʂƬÐḢ@¢ẉ€¦ỴA¢Ä8gß-Ė⁸¿zṛ¤mGKÄœ>jµ\ạ¥>R¢ƤÐƤœⱮpµỴI¤Œ¤a<[Ɱa]ṠŒɲB"'(?ŀÆȦ6ȯœ|Dy¿1€ƤØ-WXßm€v¤Uнµẋ¦iœg€Ḥ£0-‘©ṛ®Ḣ¤⁺;$%¡3¤®Ð¿Ḋḅ249:3ÄŻ,b⁹UạN,§ʋ@€/MṪị¢
```
[Try it online!](https://tio.run/##LVV9UxNHGP/fTwFogaJB5EUQFEUsxRZEy6uigliFqlTUyosDToKRINEayAwBrRCSIxltiBBecnfhZebZu507vsXeF6G/zXRgbudun93n97abRw@ePBk7OnLc/9BqsePJCDXVXmbOCX3K@k7x4gdCnaknxXTnTfBUxTmKtpvuAsezY4eNDaH5rNWm@0KbsoMX71JEZLbscLGVxFr5r848Owy/pD2RmeGzD42w49nKoW1atYN8jc2212NG87QbB7JWe@N4tNbTLM09dqhWaGt5JJGUlT0/W07KKZF5PyYRbgttssF081SLUN8L3WcpQl8pNYOjQtt/fOqn4iahq0NC9Za@cDyo/cTiFAO8x3VC919g8RH6inXGjNDnuDLYWyM0rxXHw1i3Y31CC6NUaJ@BU6hL3fV8xgjdEPpHPnu@2vHssyWhfrjI4s5GsoxPCy1EidzKRsyPjZhBx7Mn9GlSgINPDzVithBLeEqokd/l802BBOI7h/LrtGL4IbTEPie0xEOKUxIj3oZ@QRN81FWhfWNePjMAEbG48jD8A582QvdPGitWzNiQNLwtjgdloepOAGfLl5h33Nzt6SeNpyjZXSR0rYJWsBNbNkK087rbSheAqz4jtPlbUANw9HeV0pQ9I4QH9zRd76UU7cDbohwjPDx@Ai6AK2p74JcqF0y5iuygvTtQ3y60Rb6Gv2BrJVuA1qTQJkXAVH@XS3GhLnOf0KIYoadQNwGRJ8qFHoQebbDglrnLfVbsxujIBOgxeBC1ksOOJ20p0p2PY9dEZvswzLzgONBkrIiMnzbbjHWR@WDFH7IlS2lryRfaCq07nt3eTpBFDpAHoU4Os/WGQXP3jh17Sns8iMAAhfX9OJtyPHrbj0gai18QahReMxXEO4cOJ58J7d98dKedVkpShK1X30Z4mo15QKU9FPVge7C80/XESvfTAUWx12gJ4vu0KmviZ3OXqS/tlMxAkuKXAe15tQHMQk33jTc/fkmJDlqXsqRy7ZgdLqdELabudgl1x96t6EY0@KyVLO6yknxR6H/3wXcWYPsNLCabtMBndBxEKlz5HBa@5bNC9Z/I7XUmEzZEXeUKrdihvsbsAX4jddvOZbNGSKhvkVV1czAb6s37LABLwVRkFKQZwqppa1Vo7lZjPnvgjuGUQXOK5Brr/MvtKop0d2Tf2WyeEQY2dccllUzLAzEljY9kp/niQBOkbmUhZFmfo6916Cwj/4lN5f/5iKLMxxboYOQe22@@wHA3TEppI7RZyMAkPUqxK8gmRXBQgzLdfhwu7unIycGBYgGkygxSrJR5ZbvdegKFHdhNSJgf6ElBhPQwC1jxq1BMfd8IXSpkyldlqUbb0EWatpUFW8d9/8OmaBGLuyDGKxjCpyl66KfIXZklba2QIcLfjDA295luSuBVXcIlJ7@xQL2UbZ4tUYypEwzuaDdZgCfqwDNUz6ZYbJj5jksmq3yRoi86gBJnBhdEZqaOLf2FlhRDMSXA5BA9QAv9tylqzmHTA4pjTL8ufc0CdsrwywYZUlq5wgITtyjWgE3XSZP8I/QVg@Yelfw0KM1nX5BiB6so0QO32MIrVCYPJ3kCOqqRS2Cgv4M8MCezVQdjvVX9bNllzEtBDl4hy6QM/vwr85rB2ke0fRti0Grtb7AYvbmCq24jOYSLOLN1FT8Lc6TcO9@NT/fu4Iybc3bqcl5B4UXTzaas2FnruxkcvzJGB2fQEOsXXJ1dbHkQL8OktLMA7WEjeRf9YQb78VWoCkVLXI57AcoBSFLSgzR6zYkfaKUMl0wSiw6yl@Lb0vJz1WWAmTnVB@LtwHntFMUP/Zew0elm2CQvjcgRJrfaT5aMnkVHbIyPbKGxBjHPcdXmOO4vNcx3rLSotHz0TEkXVjruRebDePPoPw "Jelly – Try It Online")
Thanks to @Arnauld for a suggestion that saved 41 bytes!
Full program. Takes colour as 24-bit integer as its argument and returns the colour name.
## Explanation
### Helper link
Colour names. Stored using compressed string, but with common words replaced by single ASCII characters in range 33 to 64
```
“¥...» | Compressed string "blue brown coral..."
Ḳ | Split at spaces
33r64¤, | Pair the numbers 33 to 64 with these words [[33,34,35,...],["blue","brown","coral",...]]
Ọ | Convert the numbers to Unicode characters [["!",'"',"#",...],["blue","brown","coral",...]]
y“µ...» | Translate the compressed string "black navy %! ..." using the mapping generated above
Ḳ | Split at spaces
```
### Main link
Stage 1: Start generating list of colour numbers. The increments between colour numbers are stored as between 1 and 3 base 249 digits. The increment has been multiplied by 3, converted to base 249 and then the number of digits minus 1 has been added to the least significant digit, before reversing the order of digits.
```
“⁸...‘© | Copy compressed integers 136,1,33,198,... to register
ṛ | Right value (will yield value of the following):
¤®Ð¿ | - While the register is non-empty, do the following, collecting values as we go:
®Ḣ¤ | - Take the first value from the list held in the register, popping it from the list, x
%¡3 | - Repeat the following (x mod 3 times)
⁺;$ | - Concatenate the first value from the list held in the register, popping it from the list
Ḋ | Remove the first item (will be 'None')
```
Stage 2: Finish generating colour numbers and look up the input
```
ḅ249 | Convert from base 249 to integer
:3 | Integer divide by 3
Ä | Cumulative sum: 128,139,205,255,25600,...
Ż | Prepend zero
, | Pair with input
b⁹ | Convert to base 256: [[0],[128],[139],[205],[255],[100,0],...], [input in base 256]
U | Reverse order of innermost lists (so RGB becomes BGR, GB becomes BG and B remains as B); this is because colours with no red component will be a list with only two members, and colours with only blue will just have one member
ʋ@€/ | Reduce using the following as a dyad for each; effectively calls the following once for each colour with the reversed base-256 colour as left argument and the reversed base-256 input as right
ạ | - Absolute difference of the colour and the output of stage 1
N | Negate
, | - Pair with the colour
§ | - Sum each of these
M | Indices of maximum
Ṫ | Tail (will be the index of the largest colour value)
ị¢ | Index into helper link
```
Colours are reversed before comparing because colours with no red component (for example) will end up as a 2 component list.
TIO link generates 10 random colours and shows the output so will be different each time.
[Answer]
# Wolfram Language (Mathematica), 164 bytes
*Note:* This only works in Mathematica 12.0 due to a bug in previous versions. This also means there is no TIO link.
```
g[c_]:=Last@Keys@SortBy[Round[255List@@@<|"HTML"~ColorData~"ColorRules"~Join~{"RebeccaPurple"->RGBColor@"#639"}|>],{-Total@Abs[IntegerDigits[c,256,3]-#]&,Total,#&}]
```
Defines the function `g`, which takes an integer as input. Test cases:
```
AssociationMap[g, {327581, 3483113, 2820178, 4358965,
2058772, 13569770, 8698378, 2897368, 3896382, 12856883}]
(* <|
327581 -> "MediumSpringGreen",
3483113 -> "RoyalBlue",
2820178 -> "MidnightBlue",
4358965 -> "DarkOliveGreen",
2058772 -> "ForestGreen",
13569770 -> "Magenta",
8698378 -> "Olive",
2897368 -> "RoyalBlue",
3896382 -> "DarkOliveGreen",
12856883 -> "Brown"
|> *)
```
Unfortunately, quite a few bytes are wasted on adding "RebeccaPurple" to the built-in list of colors, which is missing for some reason. The rest is pretty straightforward, we just sort the colors by their distance to the input, breaking ties with the sum of channel values and then the absolute ordering.
[Answer]
# JavaScript (Firefox), 1050 bytes
```
c=>(b=document.body,_.match(/.[a-z]*/g).map(t=>getComputedStyle(b,b.style.color=t).color.match(/\d+/g).map((v,i)=>s+=Math.abs((c>>16-8*i&255)-v),s=0)|m>=s&&(m=s,r=t),r=m=c),r)
_='BlackNavy}~x~B2e}|G^ETeU}cy@Deeps,}t`xs*LimeS*Cy@Midnight~Dodg9~{s:GFo^1|S:|}s]JLime|xs:|T`RoyU~Steel~}s]~xt`Indigo}o6|Cadet~C?nfl59~Rebeccap<xa;DimJS]~O6drabS]J{s]Jxs]~Lawn|Chart^useA;Maro4P<O6GrayG^yS,{s,B2ev[}0}m+Saddleb>}s:|{|xp<}v[7|}?/YZ|SiEnaB>}J{~G^EyZ7t`{1eel~P5d9~Fi^brick}g_x?/Rosyb>}khakiSilv9xv[0Indi@0P9uChoco]T@{JT81leOr/G_7v[0Crims4GaQsb?oP2mBurlywood{cy@3}s=V[7g_{c?UKhakiAlice~H4eydewAzu^S@dyb>Wh:tBeigeWXsmokeMQtc^amGho1wXS=AntiquewXLQE{g_yZOldlaceRedM+Deep.Or-0TomatoHot.C?U}?-{s=Or-{.PQkGoldP:chpuffNavaj5XMoccasQBisqueMi1yroseBl@ched=dPapayaw8p3b2shS:shellC?nsilkLem4c8ff4Fl?UwXSn5YZ{yZIv?yWX~b2e}Dark|g^E{LightxMedium`urquoise_oldErod^re]late[ioletZell5X8teUalQinJg^yEen@an?or>r5n=Um4<urple;quamarQe:ea9er8hi7PUe6live5ow4on3LavEd92lu1st0^d/c8d.pQk-@ge,ky~+agEta*prQg|';for(i of'*+,-./0123456789:;<=>?@EJQUXZ[]^_`x{|}~')with(_.split(i))_=join(pop())
```
```
f =
c=>(b=document.body,_.match(/.[a-z]*/g).map(t=>getComputedStyle(b,b.style.color=t).color.match(/\d+/g).map((v,i)=>s+=Math.abs((c>>16-8*i&255)-v),s=0)|m>=s&&(m=s,r=t),r=m=c),r)
_='BlackNavy}~x~B2e}|G^ETeU}cy@Deeps,}t`xs*LimeS*Cy@Midnight~Dodg9~{s:GFo^1|S:|}s]JLime|xs:|T`RoyU~Steel~}s]~xt`Indigo}o6|Cadet~C?nfl59~Rebeccap<xa;DimJS]~O6drabS]J{s]Jxs]~Lawn|Chart^useA;Maro4P<O6GrayG^yS,{s,B2ev[}0}m+Saddleb>}s:|{|xp<}v[7|}?/YZ|SiEnaB>}J{~G^EyZ7t`{1eel~P5d9~Fi^brick}g_x?/Rosyb>}khakiSilv9xv[0Indi@0P9uChoco]T@{JT81leOr/G_7v[0Crims4GaQsb?oP2mBurlywood{cy@3}s=V[7g_{c?UKhakiAlice~H4eydewAzu^S@dyb>Wh:tBeigeWXsmokeMQtc^amGho1wXS=AntiquewXLQE{g_yZOldlaceRedM+Deep.Or-0TomatoHot.C?U}?-{s=Or-{.PQkGoldP:chpuffNavaj5XMoccasQBisqueMi1yroseBl@ched=dPapayaw8p3b2shS:shellC?nsilkLem4c8ff4Fl?UwXSn5YZ{yZIv?yWX~b2e}Dark|g^E{LightxMedium`urquoise_oldErod^re]late[ioletZell5X8teUalQinJg^yEen@an?or>r5n=Um4<urple;quamarQe:ea9er8hi7PUe6live5ow4on3LavEd92lu1st0^d/c8d.pQk-@ge,ky~+agEta*prQg|';for(i of'*+,-./0123456789:;<=>?@EJQUXZ[]^_`x{|}~')with(_.split(i))_=join(pop())
console.log(f(0xFF04FE));
console.log(f(0xFFFFFF));
console.log(f(0x457CCB));
document.body.style.color = 'black';
```
Third JavaScript language in this question now...
[`getComputedStyle`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle) always returns colors in `rgb(x, y, z)` form if `alpha == 1` on Firefox.
`_` variable holds the string with all color names in the form `BlackNavyDarkblueMediumblueBlueDarkgreen...White`.
Save 11 bytes thanks to Kevin Cruijssen by removing unnecessary colors.
Save ~350 bytes thanks to Arnauld by introducing some strange packing algorithm.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org) + `color-name` package, 259 ~~279~~ ~~284~~ ~~259~~ ~~278~~ ~~282~~ ~~299~~ ~~312~~ ~~364~~ bytes
```
c=>{w=[]
K=Object.keys
for(x in d=require('color-name')){(w[W=(p=i=>Math.abs(d[x][2-i]-(255&("0x"+c)>>8*i)))(2)+p(1)+p(0)]=w[W]||[]).push(x)}S=[]
for(s of r=w[K(w)[0]]){(S[z=(W=d[s])[0]+W[1]+W[2]]=S[z]||[]).push([d[s],s])}return S[K(S).pop()].sort().pop()[1]}
```
[Try it online!](https://tio.run/##fVjbbts4EH3PVwh92NibNBAp67aF8wPFYh/y0AfDCGiJttXIpCLJcdzLt3c5vI6ctEBMODrD28yZMyN/ZS9sqPqmGz8KWfNfPX8@Nj1/rGQr@8fHR8EO/DFaRt@jqyhibVPxTXvk/0SriC7iWzUUakjTaH0LuBib5yM/7ZvRmKRgkqRqIM7k@cgAivU0PFcBB9Y3Qs8kNHcGhFqDb8cebTyZvOHNzmLwWA80tlgzPNsT6zlUnZiUmQVbVj3Z88CffyqqPa9Ze5CiDlP1TWK3p/WDmRmOoh6/NLLlo75HonZbJLCt27GXJ6GhTK22oPCxyLFvzycpzYZUIaRYqCGxK1es5qPbtVSTSQpXyeyhqz3rx54fhwsHeliqmDIbGKKOTGKFJg6WPWv9TfXsIkBi28oT793mJIbpixJckgejoWmfgrM0M1wQFMMOgxTmZuAu9fEHPzPxLiVq1j9NvUySMkBonnp@Ae5kW3PRG2daP8JAkEnPziYQMNkOGObcrx8HcljsT1Of9uypMRsDVCSwQh7wA9txMTJDkPLtzWTbvHC/f5Hq6YooaAkVLrELrCaL6QFlX@0bc/dU7a7zMF4EvOc13h3NHDTp9cIJnBumEkqRAWf@aASoTQqg4SJBJsAzF7lcETkjFzfUFi4AC3W3vITPGwP@W4Px2D8fZTM4dtA4gwFZoCwELoKNDz/nXdcIxFZN6Dygw9MZUY@UBPOyOXjuxOmtHxDKf4vKehcSKdHbLtDaWyW@m74xokRydW6gbWJDp9JQpSnSV50uWodtCLey58PoA6Q5D0H2Kxyr/dAwPxtL1441YtjIXoY0tYPF93IYw@Y6wSf6D0kXzkWC@EyykRItWyA@llbem1qb7eAglIWAxOj5mbdKl4ynEqseLog@Bm/X3EvBzzU/XRQT58K9HCfcMAF0atiIumHC5g8FqKTwCehO@y9PbV67eS@yP6Og4R29XpjTGFZYrGUvXNS8NxnpYBX0KawYNeyR@GpOpM7mJELKUk036j3ZcpXvSi22W5v2gVSOtG2z2/vKY1xNMn0ShIcKsogvPW4MrF5TcwKs9Br3JAlhNcfQA8F7OcKohL71wwT3AgV7JVqgFlODPy4wJUABtbhMEI5UUltkWCWNBZLJBOZDLpMc3wJpDDGtRYYjq02wThKiq1wGqpy8NeJ/Nho5b0MMM90EQXLjQ2PPe5ZS77gDx3U6Do/9TS1toOI4VHARQmn5bTBUBt9okWoFpRQ@gUONOvC6OR4uusWY2m29g43ZRY/m@GxAVCML5YkiRSQwFt2x71qzA5QgQmAbUmITHGZNAqhThCQTG1wOCdXdgKHlxKpT19lhvdMuI@kCW03KXq6vXaLaboxM5XM1vgQDXYDdqZpa4IymOtT6fs5AjFXP2SG01FYUHD6M514OF101pc6/sqrY0IiLpruwzhXqneOrvKhiut/NE29xRl2fkxElEKpft5MS1@g7OumuaSr5GKl7tjFkgVBC4@0a68teKgvkNpBTe0Ch2fOgI5ApaYYeNhIda/m07IEKUSMFMbLxUgWaTFMIVEoDPgk4ydNbt1ARbCbxploA4Cy@oelYx85MObxD7zKaFdbfHWfVvjtut6h664ilDu@Pvt4R6AszN3MilKUmpIPaoyGQJl@mOwnLgE6eavQ6kWshWqBYosyz6e9JoPojruiFLCD7jd8SZ1JjUbFrKsKew9uXbVpR59rLM/MKmbnC70k9sLpueVgAHKg7/9LhoST4AujYMDBRh80pVCWSqcG9h2IZWWS2ZytyDw57pcyovKeIAUPDhTAvE@BkKFau8qs3shfTOujQuMGC75YflxRT0QKoxBJ6UZiou7Crshc16S0uJnUGtzTvCaF5J7U4rmS56bFQgzbaLoOYh6iVGrlpUN60J@NeCVpr34wz1@4TG5tRHtgo/WFBTnPL40lyQjwNi2O7bngDMS2Iad8seNpzNgaBNfpXOmza4eNeSWPDQT5d/uDhgv5eEY8xhCRngcr11c9PV9vlr2p5//20XK2vPi//23zl1Xj3xM/DlXqxmL2q/jaql@/@RjT/Pjutvixn3bJZ3v/Lxv0d2wyzevW6XtGPzfrjTJ3jr9mH@PXDTTW/vy/@bubz@YzOb7oZgSGer5dqgfWPH6v1/K5T3ezsdf7zAQ4CWw@R3Ea9svg8O81X8Xqt9ntYfVvOvizr1bCGRzdfVgQGul4vFYRXWoHNrTL72YOgiuhBrfOgQNnN5uu7QfbjzP6n1vj5Szl4HKJltLpOSE7S8vo2uk5TlRsFfNuyIqH6Wc1ZvdnCN1WW6g2Fb7zYVtviev0Jzh3NXlgfaUfBBfS6c/W/GBQz7lq5mxnsJrqOPt6r4Sbamkfz@adf/wM "JavaScript (Node.js) – Try It Online")
Commented:
```
c=>{w=[] // build dict of arrays of names, by color distance:
K=Object.keys
for(x in d=require('color-name')){
(w[W=
(p=i=>Math.abs(d[x][2-i]-(255&("0x"+c)>>8*i)))(2) + p(1) +p(0)
] = w[W]||[]).push(x)
}S=[] // distances were ordered by Object.keys()
for(s of r=w[K(w)[0]]){ // build dict of [[RGB, name]+] by channel sum for distance ties:
(S[ z= (W=d[s])[0] + W[1] + W[2] ]= S[z]||[]).push([d[s],s])
} return S[ K(S).pop() // highest channel sum
].sort().pop()[1]} // [name of] highest RGB
```
I had to
```
npm install color-name
```
for the require() to work. I don't think I can npm install on TIO, so I hardcoded the dictionary in the header.
This package contains the same 148 entries as the w3schools page, names are lowercase.
I have no idea who created it and when, I just found it while googling. There is a [Debian package](https://packages.debian.org/sid/node-color-name) for it, so I assume it's older than this question.
**[Edit: third size reduction / major overhaul]**
[Edit 5th/correction: that version had 282 bytes but was missing the tiebreak by RGB value. I don't think I can fix that one and then golf it smaller than this one, so I removed that code from the post.]
This time, I rewrote most of the code. I feel that it's so different from before, it doesn't make sense to keep history in the post.
@Shaggy saved me 4 bytes from the last version by omitting parentheses around single arrow function parameters. Now, there are 6 of those, so basically I owe 12 bytes of thanks.
I switched from constructing dicts/lists manually to using `map` and `filter` everywhere, which enabled/prompted a lot of restructuring. I also found some more situations where I could assign variables later.
**[Edit: 4th shrinking, return to the roots]**
Within a minute of dismissing history (above), I realized my mistake in saying that.
I applied the lessons learned so far to the old code, and I saw that the second sort() was pointless. So right now, that code is ahead by 4 bytes.
[Edit: 4.1th: DUH! all sorts were pointless. -19 more bytes]
**[Edit: 5th iteration, growing but now (hopefully) correct]**
@Lukas Lang pointed out that my code wasn't correct in cases where the channel sum was tied. I had the wrong impression that this never occurs.
To fix it, I needed to fill the arrays in `S` with [RGBarray, name] pairs instead of just names. This way, default array sorting completes the job.
**[Edit: 6th reduction - gift from a higher realm]**
@Shaggy gets all the credit for this round. `.reverse()[0]` is `.pop()`. Obviously... Also, implicit type conversion makes `('0x'+c)` work instead of `parseInt(c,16)`. And if you get the parantheses right, EVERY variable can be assigned at first use. This time, that was `W` and `p`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1175 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕפJÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWŬ޸%ð°¤]γθγçkÌã©Ð:8•
#`“ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0޹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0ަ0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0ަ0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0ަ0‡—Ê£ÿ s0ަ0°¯¦º0ަ0°¯–ís0ަ0‡—į0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇ⇎0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿǨ0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇݰŠ0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇݛȇŽ0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛ؉„¸“„0 K#•zÑĪåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ɔ¥2Œ’Ktθu1Sнdw΀(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“à §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºö쾫Â
åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;••O褕в.¥εI‚₄S₁β+₁∦`αO}Wkè
```
That took quite a while.. 139 colors to create a string of.. >.>
Takes input as a 24-bit integers to save 1 byte.
[Try it online](https://tio.run/##VVZrU1NXFP3ur4iiYqWl14oFsQ4d0WpBi9VSdByrOGqx1GpVtCp2rpcQ8BHFBN@8EpIAJkIeEJPATWb2ysWZMnMm/oX7R@g@9@blTBLOY5@119p7n324cr373KUL64c61@tN1W94jn0cb8MLCvTvx/ODSJnDD42USGCsD8/xkgJt8Iq57rzaQxkxillTcyHS20NBpGmGUiLe0r/p70/abQoaHlPNiPSRljvbxdxOyq16DiNOH8iHR3iMBGL7a/DIVKOFuKlO8UfESMcgniB8@CqcCMB9AL7bTED10cx2TN6AF7HGTxrGkMQ0Filmqq9oxlRH4Tx4UYyS/u8OpdZUvZjsxigttmBm09bNWylLEbh/@c9z7wg7axJxjBo6XmP551OFlZsiVtBrT3Y1i1d4fKmgG966vCriXRikCFultiBKUQqcFgkhYzDTy8ynaQ4jzU0cqw01Z011bNWDp/SO5tgzRRVmy4wki/flcXGFd9dcNCu/FIDrT2sJOQaihMIrI0qVqVyXGIZOaesYwpSrTMZMdQKq4SsekWG9VvFn6Arem06/bbuAl/agvGR5uC6xQwrrW5DYpQ32WTF0IIeFNVeVKnc1ySJElWbkHBZz1oqHNF0CKZpgAIOKkcVMaT6KeYUW4Sn6lap4K4MRhOCzqDk@8yEx2UUVdQpRpjKzcD4/4aQFi4XhRfjaBcXUIlxkFUdMThKQwBZcdRpkHD9fkIC5UqKnKGsNLyuYp1g3LeMpK@WyeVwMQFW8JVQlwEXJMssI0UwlJ8gZU3hbiloFytYmQWwS0kCRpvK4ZGRvVdJDK4gUh2zmVPCMFm0oI0sc82VKVPJV4Syh0pgsbpU0@nnRHhPnjgvpEYbgL8ZHMtMihsdCKoPbvOxDsohczEIa2LXgNbzW6epqGcK4oxiOKopWKbvZgcxTrnyn4IKNhyEZCKYPN9wW2ASlFEpQmCPwXOG25KcPCCjWuvRBUWPKnq16aPov20PZoRVTebWeKtzt3tj0i/m17ymnFIOycoZtcQgZHKEQJu0di2upQNioqIAdV01tDPnDeYw6rrLpG1ZQDA5Tc5RjZfjgLc/sgiLG91s3iRkvcy4GeMfJEPZZrnOPrcJSJmvkFTc@a4@7lSx8R3sNQ9zBM74c7xBE1Hww1U4LW/vqOnvyLiztwQNEL9Zj2tS0vQX90Jf07vsOSmJlbWzNxWt5l5Qe/EZ2@NftN0Sqb8fxgn7@Fp6w@G01XCJprHDNdFKaEiLWU9d0zBx2UwwhUx3HUDvC8tWYxFKvqQ1QTqQQ5677ARkeJwtxzG/89Tr3U01jua14Uc@H2wq6iIlUF9SeOyLG/YFflCwt9HPn8vGrFK3lvu6HLI2j/Cpg8Ewfwmf4cdAGjvIDtgX613svnabgLiQ6eO23A2x0yhyeYB75oWYR79zbxtSJ@U2tjZ2oNfT8fUTON@RVFij44qS7Kco4MocPMbKavAINScdl5hrC/dUlbugrJ6XkMQw45JP0hskzv0BBb8TEbmSg9RleytH8Hz@wpuPiLb9JkWukr3r@wWQnkzks4o2cBYpeEWkWkVe5lHS4ft@HEX53knxIxJgszd3E@IUDJ8QS4qZ2v/OTthPDeXXbLco03KUMP4wRdhuGtgHBTnBcN99tq2HBHd9tROonjv6eg5z1OQxfvOwgXZbgS4YPtH0cxxLflSn2lv5CLMPbzO64CaRbvuUGO8tXaFpSSOJ1A9yHznMcvvrRyPaD2@9dvNjNQeE64/c/yIcEd@gt@aEmpPNDJ@FD9uN4K8X2WG3E31FIUYD/FuL1FBRLJ6xQOY@zFhGv41/@Z0Dm4ayIddzr6sXs@nrDrsbW1n3/Aw) or [verify a few more test cases](https://tio.run/##VVZrU1NXFP2eXxFBxYqll2cA61AIiRa0WC1Fx7GWjlostVoVLYqd6wUCPqKY4JtXIAkgEfIATAIhM3vl4kyZuRP/wv0jdJ97A4kZCOexz9pr7b3PPly72fnblUvbfbd7G4qsustjLWroPda@XabL06rn1KfxFrwkf18zXhxFXB9@pMa1GMZ68AKvyN8CrzbfmZG7KKmNYk5XXAh1d1EACZqluBZt6Cv6@7PSSwHVo8tJLXGi4e5Bbb6S0pue44jSR/LhMZ4ghkhzMR7rcjgb1eUp/tEilMIgnmLh@HUMwA@3A75eJiD7aPYgJm/Bi4jts4IxrGIGyxTR5dc0q8ujGDh6WRul1L/lUokuezHZiVFabsBs0f69@2mDQnD/9J/n/gl2VqtFMaqm8AZrP57Lrt/WItlUydmOeu01nlzJplRvaUbWoh0YpBBbxfchTGHyn9dimojBbDczn6F5jNTXcqwsxb/q8timB8/oPc2zZwpLzJYZCRYfdse5Fd7dctGc@CU/XH8aS0gzEMUkXhmRCkzFusBQU5QwjmGB0vnJmC5PQFZ9uSMirDfy/tSUhA/6wLRpu4RX5mB3yfBwU2AHJda3JLB3Nthn3tCKNJa2XAWq3IUkcxAFmpG2GsxZKx7RzA5IzgT9GJTUDczuzEexKNEyPDm/QhVvJTGCIHwGNesXPgQmuyigTkFK5mcGzpcnBmjJYKF6sXDjkqQrIS6yvCMmJwgIYAOuMA0ijl8uCMD0TqKnaMMYXpWwSJFOWsMzVspl8yQXgIJ4C6h8gHOSRZYRpNl8TpBWp/BuJ2p5KFObADFJCANJmIrjgpG5lU8PrSOUG7LZgITntGxCqRvEMV@jWD5fec4CKoHJ3NaOxmleNMfEueNCeowhTOfiI5gpIdVjIO2Cm7zMQ6KIXMxCGJi14FW9xunCahnCuDUXjgKKRim72YHIU3r3TsEFEw9DIhBMH264DbAJiksUowWOwAuJ29I0fYRfMtaFDwqrU@Zs00Mzf5kedh0aMRVX65nE3e6tST@XX/OeckoxKCpn2BSHoMoRCmLS3DG47hQIG@UUsOOCqYkhvjiPYet1Nn3LCnLBYWrW3VipPnh3Z2ZBEeNPGzeJGa9xLvp5Z4AhzLNc5x5ThaFM1MhrbnzGHncrUfjW1mKGuIvnfDneI4Cw/nCqlZb295S2d2VcWDmMhwhfLsOMrihHsqljh@j9d220ivWtsS0Xr2VcQnqgQnT4N623tHhP@els6uIdPGXxB4q5RBJY55pppwTFtEhXae0pfdhNEQR1eRxDrVgQr8YkVrp1pZ/SWhxR7rofkeTxajaKxT0/3@R@qigs146XZXy4JZvSIlq8A3LXXS3C/YFflA1a6uPO5eNXKVzCfX0aojRO8quAwQs9WLjAj4PSf5IfsH1IfXPkynkKVCPWxmu/ONjonD48wTwyQ/VatP1IC1Mn5je1NXamRE1lHiB0sSojs0CNL06ik8KMI3L4CCObq9egYNV6lbkG8WBzhRv6@lkheQz9VvEkvWXyzM@fTdkwUYcklB7VS2la/MPJmk5r7/hNCt2g1KbnH0y2M5njWtTGWaDwNS3BIjIyl1IKrt@bMMLvziof0iJMluZvY/yS44y2gqiuPGj/rFRiOCMfuEPJqnuU5IcxxG4XoFgQaAfHde@9lmIW3PbtHsR/4OgfPspZn8fw5atWSokSfMXw/pZP41jhuzLF3hJfaWvw1rM7bgKJhhpusHN8hWYEhVW8qYL72EWOw9ffqxt94PZ7Dy/rOChcZ/z@B/iQxh16X2aoFonM0Fn4sPFp3E6Rw0YbmW7LxsnPf7PRMgpoK2eMUA2cZi1atJS/@Z8BkYdftUjb/Y5uzG0f2q6qttntTRanU6pyOixVktPpaLQ0SvbmygpeFB@LZHwsFTVSY7nNUldub66otNTUVVTaqy32SqezttJS52isqKuxVFTbmmuqLY5mW1NTnaXRYatqqvkf). (Both are slightly modified to take Hexadecimal strings as input instead, since it's easier to test.)
**Explanation:**
First we generate all the color-strings:
```
.•ŒRǝJÖ¤|DÕGø∊ŸγÜuÕפJÓΩaĀhºΔè₆ìkh¥ù§¸β?|"qтy¥Œ›ιM?z*Ω3¿ƒLò·¡ËÌóñD#Ë‰в††α½ÅÎëLpÄäÍEáyø‡§*ßtÓñ7тÜöãô±‘§—ÄGfΔ½~10'–ßaÔ´?ç"&$&¾¬ÍTʒ}M‰8βÔŽÙûQ[мvαн'YW:ΘÌiнœ+ĀβWŬ޸%ð°¤]γθγçkÌã©Ð:8•
'# Push compressed string "chiffon lavenderblush papayawhip blanchedalmond misty bisque moccasin navajo puff beige azure dew khaki violet lavender cyan burly plum boro crimson violet orchid tle violet khaki rosy orchid turquoise sienna orchid violet dle violet maroon drab cadet indigo turquoise turquoise cyan turquoise steelblue"
# # Split this string on spaces
` # Push each string separately to the stack
“ƒÏª©–°0‡—–í0‡—‡—–°0ˆ¨ˆ¨¤Æl–°ÿ•³0¤Ð0‡—–°ÿ–í0޹0ˆ¨ë¿Ž¹0ˆ¨Ü„Àš0‡—·¡r0‡—‡Ž0í™0ˆ¨ï×0ˆ¨í™0ˆ¨–°s0ަ0°¯ë¿0ˆ¨–í0í™0ˆ¨ ÿïˆ0‡—–Í0‡—–°s0ަ0‡—–íÿ ÿ–°0Ê£0ˆ¨ ÿ0‡—ÃÅ0žç0‡—Ôî0´Ò–í0Ü„0›Ðæá0°¯ s0ަ0‡—Ê£ÿ s0ަ0°¯¦º0ަ0°¯–ís0ަ0‡—į0ˆ¨œëre0€ÅÜ„0›Ð ÿ´ÒÊ£°¯¤Ð0‡—‡Ž0¤Ð0‡—‡—ÿ–°0†¾–°m0î±a»Ïÿ0ŽÌ–°0í™0ˆ¨‡Ž0ˆ¨–í0´Ò–°ÿæ§0ˆ¨–°ÿŠÛ0ˆ¨ ÿŽÌ–°0°¯‡Ž0‡—ˆ¨0ŠÛæ§ÿ‡Ž0–Í0‡—¼ì0‡—ŠÄ0Ñ´–°0ž®0»³–íÿ ÿ0ŽÌ–°ÿ‹ß–íÿ0†¾•‹0†¾¾ç¨ËÇ⇎0°¯€Œÿ ÿž®0»³æ§ÿ0†¾ ÿÆŠÿ ÿ ÿ0–œ‡Žÿ ÿ–°0ÇÝ ÿæ§0ž®0»³‡Ž0Í€ ÿ¿í0‡—Æàÿ ÿǨ0ŽÌÍÍ ÿ„¸0³«¼Õ0¥â·ä0„¸ÇݰŠ0„¸ƒ£n‡Ž0ž®0»³0ŠÛ„Ï0ÕÚ†¾ m0î±a•³0™Å›È0†¾æž…ß0™ÅÍ€–°0›È‡Ž0ÇݛȇŽ0™Å™Åˆ° p0‚Ìÿ ÿ0„¸ ÿ ÿ ÿ0šÓ ÿ ÿ ÿí™0¬•ÃÅ0»»ËÃÿÄ‚0„¸œÒŠÛ‡Ž0ŠÛ؉„¸“
# Push dictionary string "black navy dark0 blue medium0 blue blue dark0 green green teal darkÿ deep0 sky0 blue darkÿ medium0 spring0 green lime spring0 green aqua midnight0 blue dodger0 blue light0 sea0 green forest0 green sea0 green darks0 late0 grey lime0 green medium0 sea0 green ÿ royal0 blue steel0 blue darks0 late0 blue mediumÿ ÿ dark0 olive0 green ÿ0 blue corn0 flower0 blue rebecca0 purple medium0 aqua0 marine dim0 grey s0 late0 blue oliveÿ s0 late0 grey lights0 late0 grey mediums0 late0 blue lawn0 green chartre0 use aqua0 marine ÿ purple olive grey sky0 blue light0 sky0 blue blueÿ dark0 red darkm0 agenta sadÿ0 brown dark0 sea0 green light0 green medium0 purple darkÿ pale0 green darkÿ yellow0 green ÿ brown dark0 grey light0 blue green0 yellow paleÿ light0 steel0 blue powder0 blue fire0 brick dark0 golden0 rod mediumÿ ÿ0 brown darkÿ silver mediumÿ0 red indian0 red peru chocolate tan light0 grey thisÿ ÿ golden0 rod paleÿ0 red ÿ gainsÿ ÿ ÿ0 wood lightÿ ÿ dark0 salmon ÿ pale0 golden0 rod light0 coral ÿ alice0 blue honeyÿ ÿ sandy0 brown wheat ÿ white0 smoke mint0 cream ghost0 white salmon antique0 white linen light0 golden0 rod0 yellow old0 lace red m0 agenta deep0 pink orange0 red tomato hot0 pink coral dark0 orange light0 salmon orange light0 pink pink gold p0 eachÿ ÿ0 white ÿ ÿ ÿ0 rose ÿ ÿ ÿ sea0 shell corn0 silk lemonÿ floral0 white snow yellow light0 yellow ivory white"
# Where all `ÿ` are automatically filled with the strings on the stack
„0 K # Remove all "0 " from this string
# # Split the colors on spaces
```
Then we generate a list of forward differences (deltas) between each integer value of the colors:
```
•zÑĪåð≠K¯&u+UhĆõ;Éðf.ã₂=нH,ª@O¶ü˜ˆ₂Ɔ¥2Œ’Ktθu1Sнdw΀(#ç¹ü‹U¹³αh+8R∍±æ”ÇKë₆ßõk₃¿θòĀηú¿ζвî!Vs©₂™CÖ.∍JнαθWÀhzαÐé3¾¯|ë¡×°'βâá—P‘Å_uë_§₃P∊%ý/=i]¥5óO₃^E‘[∞₆ć:βU=J€¦†˜X'Žāìd4Ā’δ‹a°∊›ÊÐƶoÂö mвæÁƵ¨¼Yü“à §‚₂¾¤н7Þ9úÂuœ¿®jF™SΛ¬ìr½ƒxßU‘Lβ7≠°oι—ĀÅýÆgBÐγö™α₆©vÝeEXεò₁Uт3ÈĀ(wº4{ºö쾫Â
åUøò${J#₃O<!øN”;GÑéÈfm ½™×γäJǝõ¥àÐι)λÓ:α–ù?6¦¨·ã™ζÙ4ÍHd›-Iž|ï¦{Ö9ÊàÛ§¥–Σÿ%ć8ùćYáþǝC±;•
# Push compressed integer 199435987809271424589508700952987345999804200072375133628254343692108407476588500135573281889031649216370100759626064238727072489415325130552011943231372407222964404763401980843968947657212497212027480199840300219769136432328209307347145119976644138878553798683794751309798787883572249589074597119540397124774131357786254535108429605287982569524294490533853150008626425797260994727581899181000813165364870780739754491720041566206327597753141661846275821649635815830948299823383964329384068145070200611196756567681968774265025511020508722510627341700584849057763591073777679021648285012447092662591008342199952284925672007531443930335828262810273697784303468071652124201899153101970895280421720006686387730894329535589566680885995478455871002071758051626349351150223272343920758114226776399859623393233070539000599481915926111317851112136858026586181791
•O褕 # Push compressed integer 1579378
в # Convert the larger integer to Base-1579378 as list: [128,11,66,50,25345,7168,128,2827,13428,3794,11209,1126,127,128,1579377,358287,139691,120952,786485,50168,228835,648767,273759,35089,334035,113367,37953,143030,682669,668529,325453,105900,39441,170943,61796,78678,324205,460809,254037,103186,197376,212,44,128,32640,128,478827,15,154856,54302,139,17544,292732,78337,164427,36856,326341,14132,105062,361723,317437,294783,274237,9801,126911,54768,7176,82236,418793,118728,145852,75740,198997,414917,411351,10467,320479,19310,73543,322565,110846,13386,52083,41897,51360,50177,71594,149368,386811,176000,322676,26044,104406,26124,4723,1777,15,238689,80467,5929,25,2565,194821,100211,27493,1295,2540,195348,68122,255,5012,12397,7751,1645,5532,3248,5242,1158,4545,2570,5685,953,1012,1544,15,29,1772,1032,288,1273,750,497,35,10,1030,224,16,15]
.¥ # Undelta this list: [0,128,139,205,255,25600,32768,32896,35723,49151,52945,64154,65280,65407,65535,1644912,2003199,2142890,2263842,3050327,3100495,3329330,3978097,4251856,4286945,4620980,4734347,4772300,4915330,5597999,6266528,6591981,6697881,6737322,6908265,6970061,7048739,7372944,7833753,8087790,8190976,8388352,8388564,8388608,8388736,8421376,8421504,8900331,8900346,9055202,9109504,9109643,9127187,9419919,9498256,9662683,9699539,10025880,10040012,10145074,10506797,10824234,11119017,11393254,11403055,11529966,11584734,11591910,11674146,12092939,12211667,12357519,12433259,12632256,13047173,13458524,13468991,13789470,13808780,13882323,14204888,14315734,14329120,14381203,14423100,14474460,14524637,14596231,14745599,15132410,15308410,15631086,15657130,15761536,15787660,15792383,15794160,15794175,16032864,16113331,16119260,16119285,16121850,16316671,16416882,16444375,16445670,16448210,16643558,16711680,16711935,16716947,16729344,16737095,16738740,16744272,16747520,16752762,16753920,16758465,16761035,16766720,16767673,16768685,16770229,16770244,16770273,16772045,16773077,16773365,16774638,16775388,16775885,16775920,16775930,16776960,16777184,16777200,16777215]
```
Then we determine the index of the value closest to the input (in terms of absolute differences between each RGB color - and here I thought I could use builtin `.x`..), determine the index of this closest integer in the list, and use that to index into the color-strings we created earlier:
```
ε # Map each integer to:
I‚ # Pair it with the input-integer
₄S # Push 1000, split to digits: [1,0,0,0]
₁β # Converted from base-256 to an integer: 16777216
+ # Add that to both integers in the pair
₁в # Convert both integers to base-256 as list (we now have [1,R,G,B])
€¦ # Remove the leading 1
` # Push both lists to the stack
α # Get the absolute difference between the lists (at the same indices)
O # Sum these differences
}W # After the map: get the minimum (without popping the list itself)
k # Get the index of this minimum in the list
è # And use it to index into the string-color list
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (all four sections)](https://codegolf.stackexchange.com/a/166851/52210) to understand why:
* `.•ŒRǝ...Ð:8•` is `"chiffon lavenderblush papayawhip ... cyan turquoise steelblue"`
* `“ƒÏª©–°0‡—...‡Ž0ŠÛ؉„¸“` is `"black navy dark0 blue ... light0 yellow ivory white"`
* `•zÑÄ...C±;•` is `199...791`
* `•O褕` is `1579378`
* `•zÑÄ...C±;••O褕в` is `[128,11,66,...,224,16,15]`
] |
[Question]
[
I am new to the sport of code golf. I am trying to generate a ladder of integers using the least number of unique characters in C++.
Let's say we are given an integer 4.
We will generate the following ladder:
1
1 2
1 2 3
1 2 3 4
In short, my program will read a positive integer from stdin and print this ladder to the output. I am trying to do so with the **least number of unique characters** possible.
My program is as follows:
```
#include<iostream>
int i;
int ii;
int iii;
int iiii;
main() {
std::cin >> i;
for(ii++; ii <= i; ii++) {
int iii = iiii;
for(iii++; iii <= ii; iii++) {
std::cout << iii << " ";
}
std::cout << std::endl;
}
}
```
Here's the checker that I used to check the number of unique characters in my program:
```
#include <cstdio>
#include <cstring>
using namespace std;
int check[300],diffcnt=0,cnt=0,t;
char c;
double score;
int main(){
memset(check,0,sizeof(check));
FILE *in=fopen("ans.cpp","r");
while(fscanf(in,"%c",&c)!=EOF){
cnt++;
if(!check[c]){
check[c]=1;
if(c=='\r'||c=='\n') continue;
diffcnt++;
}
}
if(diffcnt<25) printf("100\n");
else if(diffcnt<30){
printf("%.3lf\n",20.0*100.0/cnt+20.0*(29-diffcnt));
}
else{
score=20.0;
for(int x=95;x<cnt;x++) score*=0.9;
printf("%.3lf\n",score);
}
printf("Unique Characters: %d\n", diffcnt);
printf("Total Characters: %d\n", cnt);
return 0;
}
```
Preferably I wish to use **less than** 25 unique characters to complete this program (excluding newline characters but including whitespace). Currently, my program uses 27. I am not sure how to optimize it further.
Could someone please advise me on how to optimize it further (in terms of the number of unique characters used)? Please note that only C++ can be used.
[Answer]
I believe I managed to remove the = character from your code, although it now is significantly slower
```
#include<iostream>
int i;
int ii;
int iii;
int iiii;
int main() {
std::cin >> i;
i++;
for(ii++; ii < i;) {
for(;iii>iiii;iii++);
for(;iii<iiii;iii++);
ii++;
for(iii++; iii < ii; iii++) {
std::cout << iii << " ";
}
std::cout << std::endl;
}
}
```
Its not pretty, but by abusing integer overflow we can get back to 0 without using =
Also we had to change the guards a little. Unfortunately because of the include I couldn't get rid of all new line characters (although its close) so that may be the next avenue for investigation.
Edit: Run out of time for now, but if you include and use strstream and various other libraries, I think you may be able to remove the " character too, again using integers to arrive at the correct character for space and passing it into the strstream
[Answer]
I finally got 24 unique characters by combining the answers of @ExpiredData and @someone. Also, using the short data type instead of int helped to speed up my program because it takes a shorter time to overflow a short data type.
My code is as follows.
```
%:include<iostream>
short i;
short ii;
short iii;
short iiii;
char iiiii;
main() <%
std::cin >> i;
iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;
iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;
iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;
iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;iiiii++;
i++;
for(ii++; ii < i; ii++) <%
for(;iii;iii++);
for(iii++; iii < ii; iii++)
std::cout << iii << iiiii;
std::cout << iii << std::endl;
%>
%>
```
[Answer]
# 23 unique characters using Digraphs. (25 without). No UB.
**Use [C++11 braced initializer syntax](https://en.cppreference.com/w/cpp/language/list_initialization)** to list-initialize an integer to zero with `int var{};` avoiding `=` and `0`. (Or in your case, avoiding global `iiii`). This gives you a source of zeros other than global variables (which are statically initialized to zero, unlike locals).
Current compilers accept this syntax by default, without having to enable any special options.
(The integer wraparound trick is fun, and ok for golfing with optimization disabled, but signed overflow is undefined behaviour in ISO C++. Enabling optimization will turn those wraparound loops into infinite loops, unless you compile with gcc/clang [`-fwrapv`](https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html) to give signed integer overflow well-defined behaviour: 2's complement wraparound.
Fun fact: ISO C++ `std::atomic<int>` has well-defined 2's complement wrap-around! `int32_t` is required to be 2's complement if defined at all, but the overflow behaviour is undefined so it can still be a typedef for `int` or `long` on any machine where one of those types is 32 bits, no padding, and 2's complement.)
---
Not useful for this specific case:
You can also initialize a new variable as a copy of an existing one, with either braces or (with a non-empty initializer), parens for [direct initialization](https://en.cppreference.com/w/cpp/language/direct_initialization).
`int a(b)` or `int a{b}` are equivalent to `int a = b;`
But `int b();` declares a function instead of a variable initialized to zero.
Also, you can get a zero with `int()` or `char()`, i.e. [zero-initialization](https://en.cppreference.com/w/cpp/language/zero_initialization) of an anonymous object.
---
**We can replace your `<=` compares with `<` compares by a simple logic transformation**: do the loop-counter increment right after the compare, instead of at the bottom of the loop. IMO this is simpler than the alternatives people have proposed, like using `++` in the first part of a `for()` to make a 0 into a 1.
```
// comments aren't intended as part of the final golfed version
int n;
std::cin >> n; // end condition
for(int r{}; r < n;) { // r = rows from 0 .. n-1
++r;
for(int i{}; i < r;) {
++i;
std::cout << i << ' ';
}
std::cout << std::endl;
}
```
We could golf that down to `for(int r{}; r++ < n;)` but IMO that's less easy for humans to read. We're not optimizing for total byte count.
---
**If we were already using `h`, we could save the `'` or `"` for a space.**
Assuming an ASCII or UTF-8 environment, space is a `char` with value 32. We can create that in a variable easily enough, then `cout << c;`
```
char c{};
c++; c++; // c=2
char cc(c+c+c+c); // cc=8
char s(cc+cc+cc+cc); // s=32 = ' ' = space in ASCII/UTF-8
```
And other values can obviously be created from a sequence of `++` and doubling, based on the bits of their binary representation. Effectively shifting a 0 (nothing) or 1 (++) into the LSB before doubling into a new variable.
---
This version uses `h` instead of `'` or `"`.
It's much faster than either of the existing versions (not relying on a long loop), and is **free of Undefined Behaviour**. It [compiles with no warnings with `g++ -O3 -Wall -Wextra -Wpedantic` and with `clang++`](https://godbolt.org/z/xGFtVR). `-std=c++11` is optional. It is legal and portable ISO C++11 :)
It also doesn't rely on global variables. And I made it more human-readable with variable names that have a meaning.
**Unique-byte count: 25**, *excluding the comments which I stripped with `g++ -E`*. And excluding space and newline like your counter. I used `sed 's/\(.\)/\1\n/g' ladder-nocomments.cpp | sort | uniq -ic` [from this askubuntu](https://askubuntu.com/questions/593383/how-to-count-occurrences-of-each-character) to count occurrences of each character, and piped that into `wc` to count how many unique characters I had.
```
#include<iostream>
int main() {
char c{};
c++; c++; // c=2
char cc(c+c+c+c); // cc=8
char s(cc+cc+cc+cc); // s=32 = ' ' = space in ASCII/UTF-8
int n;
std::cin >> n; // end condition
for(int r{}; r < n;) { // r = rows counting from 0
++r;
for(int i{}; i < r;) {
++i;
std::cout << i << s;
}
std::cout << std::endl;
}
}
```
The only 2 `f` characters are from `for`. We could use `while` loops instead if we had a use for `w`.
We could possibly rewrite the loops into an assembly-language style of `i < r || goto some_label;` to write a conditional jump at the bottom of the loop, or whatever. (But using `or` instead of `||`). Nope, that doesn't work. [`goto` is a *statement*](https://en.cppreference.com/w/cpp/language/goto) like `if` and can't be a sub-component of an expression like it can in Perl. Otherwise we could have used it to remove the `(` and `)` characters.
We could trade `f` for `g` with `if(stuff) goto label;` instead of `for`, and both loops always run at least 1 iteration so we'd only need one loop-branch at the bottom, like a normal asm `do{}while` loop structure. Assuming the user inputs an integer > 0...
---
## Digraphs and Trigraphs
Fortunately, [trigraphs have been removed as of ISO C++17](https://en.wikipedia.org/wiki/Digraphs_and_trigraphs#REMOVAL) so we don't have to use `??>` instead of `}` if we're unique-golfing for the most recent C++ revision.
But only trigraphs specifically: **ISO C++17 still has digraphs like `:>` for `]` and `%>` for `}`**. So at the cost of using `%`, we can avoid both `{` and `}`, and use `%:` for `#` for a net saving of 2 fewer unique characters.
And C++ has operator keywords like `not` for the `!` operator, or `bitor` for the `|` operator. With `xor_eq` for `^=`, you could zero a variable with `i xor_eq i`, but it has multiple characters you weren't using.
Current `g++` already ignores trigraphs by default even without `-std=gnu++17`; you have to use `-trigraphs` to enable them, or `-std=c++11` or something for strict conformance to an ISO standard that does include them.
**23 unique bytes:**
```
%:include<iostream>
int main() <%
int n;
std::cin >> n;
for(int r<% %>; r < n;) <%
++r;
for(int i<%%>; i < r;) <%
++i;
std::cout << i << ' ';
%>
std::cout << std::endl;
%>
%>
```
[**Try it online!**](https://tio.run/##bc2xCsMgEAbg3ae4RZISnEqXePgKHTuLMeHAaDDm9Ws1oSmBHg7e7/ejWRYxGZMz78kbtw0WKawpWj0rxsgnmDX59gbIGZSpiZf7dU1D3xvyoFSN9mwMsa0kIgeuJETA8na263RdlOfy9YS8cio8XvlRIXkJjq/DlgCxlhAaaH6EK/ZX7ov1gztoYeXk/Hib0elpzeJ5z@KlnfsA "C++ (gcc) – Try It Online")
The final version uses a `'` single-quote instead of `h` or `"` for the space separator. I didn't want to digraph the `char c{}` stuff so I deleted it. Printing a char is more efficient than printing a string, so I used that.
**Histogram:**
```
$ sed 's/\(.\)/\1\n/g' ladder-nocomments.cpp | sort | uniq -ic | tee /dev/tty | wc -l
15 // newline
95 // space
11 %
2 '
3 (
3 )
4 +
9 :
10 ;
14 <
8 >
2 a
4 c
6 d
3 e
2 f
12 i
2 l
2 m
11 n
5 o
7 r
5 s
11 t
3 u
25 // total lines, including space and newline
```
---
### The space separator (still unsolved)
In a now-deleted answer, Johan Du Toit proposed using an alternate separator, specifically [`std::ends`](https://en.cppreference.com/w/cpp/io/manip/ends). That's a NUL character, `char(0)`, and prints as zero-width on most terminals. So the output would look like `1234`, not `1 2 3 4`. Or worse, separated by garbage on anything that didn't silently collapse `'\0'`.
If you can use an arbitrary separator, when the digit `0` is easy to create with `cout << some_zeroed_var`. But nobody wants `10203040`, that's even worse than no separator.
I was trying to think of a way to **create a `std::string` holding a `" "`** without using `char` or a string literal. Maybe appending something to it? Maybe with a digraph for `[]` to set the first byte to a value of `32`, after creating one with length 1 via one of the constructors?
Johan also suggested the [`std::ios` fill() member function](https://en.cppreference.com/w/cpp/io/basic_ios/fill) which returns the current fill character. The default for a stream is set by [`std::basic_ios::init()`](https://en.cppreference.com/w/cpp/io/basic_ios/init), and is `' '`.
**`std::cout << i << std::cout.fill();`** replaces `<< ' ';` but **uses `.` instead of `'`**.
With `-`, we can take a pointer to `cout` and use `->fill()` to call the member function:
`std::cout << (bitand std::cout)->fill()`. Or not, we weren't using `b` either so we might as well have used `&` instead of its lexical equivalent, `bitand`.
**Calling a member function without `.` or `->`**
Put it inside a class, and define `operator char() { fill(); }`
```
// not digraphed
struct ss : std::ostream { // default = private inheritance
// ss() { init(); } // ostream's constructor calls this for us
operator char() { return fill(); }
}
```
Then `ss s{}` before the loop, and `std::cout << i << s;` inside the loop. Great, it compiles and works properly, **but we had to use `p` and `h` for `operator char()`,** for a net loss of 1.
At least we avoided `b` to make member functions `public` by using `struct` instead of `class`. (And we could override the inheritance with `protected` in case that ever helps).
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/) x86\_64 Linux only, ~~9295 8900 8712 6812 5590~~ 5218 bytes, 18 unique characters
```
int m[]={11111111111111111+1111111111111111+1111111111111+1111111111111+111111111+111111111+11111111+11111111+11111111+111111+11+11+11+11+11+11+11+1+1,11111111111+11111111111+11111111111+1111111111+111111111+111111111+111111111+111111+1111+1111+111+111+111+111+11+11+11+11+11+11+11+11+11+1+1+1,111111111111111111+11111111111111+11111111111+111111111+11111111+11111111+111111+111111+111111+111111+1111+111+111+111+111+111,111111111111111+111111111111111+111111111111111+111111111111111+11111111111111+111111111111+111111111+11111111+11111111+11111+1111+1111+111+111+11+11+1+1+1+1,11111111111111111+1111111111111111+1111111111111111+1111111111111111+111111111+111111111+11111111+111111+11111+11111+11111+1111+1111+1111+11+11+11+11+11+11+11,1111111111111111+111111111111111+111111111111+11111111111+1111111111+1111111111+11111111+111111+111111+11111+11+11+11+1+1+1+1+1+1+1+1,11111111111111111+1111111111111111+11111111111+11111111111+11111111+11111111+11111111+1111+1111+11+11+11+11+11+11+11+11+11+1+1+1,111111111111+11111111111+1111111111+1111111111+1111111111+1111111111+1111111111+1111111111+11111111+11111+11111+11111+11111+11111+11111+1+1,111111111111111+11111111111111+11111111111+11111111111+1111111111+1111111+1111111+11111+111+111+111+111+111+111+111+111+11+11+1+1+1+1+1+1,11111111111+1111111111+111111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+11+1+1+1+1+1+1+1,111111111111111111+1111111111111111+1111111111111111+111111111111111+111111111+11111111+11111+11111+11111+11111+11111+11111+111+111+111+111+111+111+11+11+1+1+1,11==1,1111111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+11+11+11+1+1+1,1111111111111+111111111111+11111111111+1111111111+111111111+111111111+11111111+111111+111111+111111+11111+1111+111+111+1+1,111111111111+111111111111+11111111111+11111111111+11111111111+11111111111+111111111+111111111+11111111+111111+1111+1111+111+111+111,111111111111+11111111111+1111111111+1111111111+111111111+1111111+111+111+1+1+1+1,11111111111111111+1111111111111111+1111111111111111+1111111111+1111111111+111111111+1111111+1111111+1111111+1111111+1111111+1111+1111+1111+111+111+11+1+1+1+1+1,111111111111111+1111111111111+1111111111111+11111111111+1111111111+11111111+11111111+1111+1111+1111+111+111+111+111+11+11,111111111+111111111+11111111+11111111+11111111+1111111+1111111+111111+11111+1111+1111+1111+1111+111+111+11+11+11+11+11+1+1+1+1+1+1+1+1,11111111111111+111111111111+111111111111+11111111111+111111111+111111+111111+111111+1111+1111+1111+1+1+1+1+1+1+1+1,111111111111111111+1111111111111+1111111111111+111111111111+111111111+111111111+111111111+11111111+1111111+111111+111+11+11+11+11+1+1+1,11111111111111111+111111111111111+1111111111+111111111+111111111+11111111+1111+1111+1111+111+111+111+11+11+11+11+11+11+11+11+11+11,111111111111111+1111111111111+1111111111+111111111+11111111+1111111+1111111+111111+11111+11111+11111+1111+111+111+111+111+11+11+11+1+1+1+1+1,1111111111111111+111111111111111+111111111111111+11111111+11111111+1111111+1111111+1111111+1111+1111+1111+1111+1111+111+11+11+11+1+1+1+1+1+1+1+1+1+1,111111111111111+1111111111111+111111111111+111111111111+111111111111+11111111111+1111111111+1111111111+111111111+111111+111111+111111+111111+1111+11+1+1,111111111111111+11111111111111+111111111111+111111111111+1111111111+1111111111+111111111+11111111+1111+1111+1111+111+111+111+111+111+11+11+11+11+11+11+11+11+1+1+1+1,11111111111111111+1111111111111111+11111111111+11111111+1111111+1111111+111111+11111+11111+1111+1111+111+111+111+111+111+111+111+111+11+11+1+1+1+1+1+1+1+1,11111111111111111+11111111111111+1111111111+1111111+111111+11111+11111+11111+1111+111+111+111+111+111+111+11+11+11+11+11+11+11+11+11,11111111111111111+1111111111111+1111111111111+1111111111111+1111111111+1111111+11111+11111+11111+1111+111+111+111+1+1+1+1+1+1+1,1111111111111+1111111111+11111111+11111111+11111111+11111+1111+111+111+11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1,1111111111111111+11111111111+11111111111+11111111111+111111111+111111111+111111111+11111+11111+11111+11111+11111+11111+11111+11111+11111+111+111+11,11111111111111+1111111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+11111+1111+1111+111+111+111+111+111+111+1+1+1+1+1+1,111111111111111+1111111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+1111111+111111+11111+11111+11111+1111+111+111+111+11+11+11+11+11,1111111111+111111111+1111111+1111111+111111+111111+11111+11111+11111+11111+11111+11111+1111+1111+1111+11+11+11+11+11+11+11+11+11+1+1+1,11111111111111111+11111111111111111+1111111111111111+1111111111111111+1111111111111+11111111111+111111111+111111+111111+111111+1+1+1+1+1+1+1,1111111111+111111111+111111111+11111111+1111111+1111111+1111111+111111+11111+11111+11111+11111+11111+111+111+111+11+11+11+1,111111111111111111+11111111111111111+111111111111111+111111111111111+111111111111111+11111111111+11111111111+11111111+11111+11111+11111+11111+11111+11+11+11+1+1+1,111111111111+11111111111+1111111111+111111111+111111111+111111+111111+111111+111111+11111+11111+11+11+11+11+11+1,111111111+11111+11111+111+11+1+1+1+1+1+1+1+1+1};main(){((int(*)())m)();}
```
[Try it online!](https://tio.run/##rVjLboMwEPyVHqEDB/ca8SVVDxFKI9SCIgWpVaP8et1cUoG9T5MIFsNll9nZ8ZD@dGqPfR/jMM1P4@tbdwnpD/ID7o5YsQvQB0LDJGLWsKywCskJoZh1OTQ6kLEAVQt5IWrL0mPbPYKrWBK3f2gocLDlAV8Q6LgK@dEEDzoqweRWIgWnECRyzSwQ3BR2vKVnCVOExmfHwCPLrJxJaxqznkBObb5m3NC1xfAApc3QgbrV13XLKvEgbDyBUOocO98gI3jEOalEmCcLfbXtgi4pQ6N4ppd9uL/QA6RczeXkBNJ5aYociSjfGt2yXQQbBgHBQHLYtxE4SSjbjntw6hNc5kLCDytWqh4MFiZy6VR9MVgJONLrjKCVhtQ9Eg@zC7TJtcBSmpvOAUW5dJsYvTRGLsvB3hgaLMqI4tDKTaKVWygzSabSeHNmp7g2gk25EvH1KYXxICDYdwJZ430ztd1UmL0h6xYba/ML7LGPtH7tcW5Kum7aCM4QWTVKcLas9JuQ1hv3t4jLeDDtQ8FGaseJ6InlG2zTvy6CbAux/PvdsUHm6VJMCABzlbruxv0wVfWlqoZprp7rqq7HW9hdY3wJv/375/54ju3P4fvQn@d9/xHbrz8 "C++ (gcc) – Try It Online")
This uses the character set `()*+,1;=[]aimnt{}` and is based on ideas from [this CGCC answer](https://codegolf.stackexchange.com/questions/110648/fewest-distinct-characters-for-turing-completeness/110834#110834). A machine language program is expressed as an array of 32 bit ints, each of which is represented as a sum of `1+11+111...`. It turns out that it may be more efficient to encode `x` as `y` such that `y%(1<<32)==x`. The encoded machine language program is the following
```
0x0000000000000000: 55 push rbp
0x0000000000000001: 31 ED xor ebp, ebp
0x0000000000000003: 53 push rbx
0x0000000000000004: 48 83 EC 18 sub rsp, 0x18
0x0000000000000008: 48 8D 74 24 0C lea rsi, [rsp + 0xc]
0x000000000000000d: 31 C0 xor eax, eax
0x000000000000000f: 31 FF xor edi, edi
0x0000000000000011: 6A 01 push 1
0x0000000000000013: 5A pop rdx
0x0000000000000014: 0F 05 syscall
0x0000000000000016: 89 C3 mov ebx, eax
0x0000000000000018: 85 C0 test eax, eax
0x000000000000001a: 74 0C je 0x28
0x000000000000001c: 6B ED 0A imul ebp, ebp, 0xa
0x000000000000001f: 03 6C 24 0C add ebp, dword ptr [rsp + 0xc]
0x0000000000000023: 83 ED 30 sub ebp, 0x30
0x0000000000000026: EB E0 jmp 8
0x0000000000000028: C7 44 24 0C 00 00 00 00 mov dword ptr [rsp + 0xc], 0
0x0000000000000030: FF C3 inc ebx
0x0000000000000032: 8B 44 24 0C mov eax, dword ptr [rsp + 0xc]
0x0000000000000036: 8D 78 01 lea edi, [rax + 1]
0x0000000000000039: 89 7C 24 0C mov dword ptr [rsp + 0xc], edi
0x000000000000003d: E8 27 00 00 00 call 0x69
0x0000000000000042: 6A 20 push 0x20
0x0000000000000044: 48 89 E6 mov rsi, rsp
0x0000000000000047: 52 push rdx
0x0000000000000048: 58 pop rax
0x0000000000000049: 50 push rax
0x000000000000004a: 5F pop rdi
0x000000000000004b: 0F 05 syscall
0x000000000000004d: 5E pop rsi
0x000000000000004e: 39 5C 24 0C cmp dword ptr [rsp + 0xc], ebx
0x0000000000000052: 7C DE jl 0x32
0x0000000000000054: 6A 0A push 0xa
0x0000000000000056: 48 89 E6 mov rsi, rsp
0x0000000000000059: 52 push rdx
0x000000000000005a: 58 pop rax
0x000000000000005b: 0F 05 syscall
0x000000000000005d: 5E pop rsi
0x000000000000005e: 39 DD cmp ebp, ebx
0x0000000000000060: 7F C6 jg 0x28
0x0000000000000062: 48 83 C4 18 add rsp, 0x18
0x0000000000000066: 5B pop rbx
0x0000000000000067: 5D pop rbp
0x0000000000000068: C3 ret
0x0000000000000069: 85 FF test edi, edi
0x000000000000006b: 74 2C je 0x99
0x000000000000006d: 89 F8 mov eax, edi
0x000000000000006f: 6A 0A push 0xa
0x0000000000000071: 59 pop rcx
0x0000000000000072: 48 83 EC 18 sub rsp, 0x18
0x0000000000000076: 99 cdq
0x0000000000000077: F7 F9 idiv ecx
0x0000000000000079: 89 C7 mov edi, eax
0x000000000000007b: 8D 42 30 lea eax, [rdx + 0x30]
0x000000000000007e: 89 44 24 0C mov dword ptr [rsp + 0xc], eax
0x0000000000000082: E8 E2 FF FF FF call 0x69
0x0000000000000087: 48 8D 74 24 0C lea rsi, [rsp + 0xc]
0x000000000000008c: 6A 01 push 1
0x000000000000008e: 58 pop rax
0x000000000000008f: 50 push rax
0x0000000000000090: 5F pop rdi
0x0000000000000091: 50 push rax
0x0000000000000092: 5A pop rdx
0x0000000000000093: 0F 05 syscall
0x0000000000000095: 48 83 C4 18 add rsp, 0x18
0x0000000000000099: C3 ret
```
...which is based on the following C code.
```
void print(int x){
if( x ) {
int y=x%10+'0';
print(x/10);
write(1,&y,1);
}
}
void f() {
int i=0,j=0,k;
for( ;read(0,&k,1);i=i*10+k-'0' );
do {
for( j++,k=0; print( ++k ), write(1," ",1), k<j; );
write(1,"\n",1);
} while(j<i );
}
```
Edit: Now accepts input from `stdin` instead of `argv[1]`. Thanks to @ASCII-only and @PeterCordes for their suggestions!
Edit4: ~~Slightly~~ Significantly improved encoding.
[Answer]
# 21 unique characters + 1 unremovable newline
```
%:include<iostream>
int(n)(int(i))<%
if(--i)if(n(i))<%%>
if(i)if(std::cout<<i<<std::addressof(std::cout)->fill())<%%>
%>
int(l)(int(i))<%
if(n(-(--i)))<%%>
%>
int(m)(int(i))<%
if(--i)if(m(i))<%%>
if(i)if(l(-i))<%%>
if(i)if(std::cout<<std::endl)<%%>
%>
int(c)(int(i))<%
if(m(-(--i)))<%%>
%>
int(main)(int(i))<%
if(std::cin>>i)<%%>
if(c(-i))<%%>
%>
```
Whitespaces aren't required except for the first newline. Compiled in g++ 7.3.0.
Used characters: `%:include<ostram>()f-`.
Improvements to other answers:
1. Removed semicolons by changing `for` loops to `if` and recursion.
2. Got the space character by `std::addressof(std::cout)->fill()`, aka `std::cout.fill()`.
[Answer]
# ~~21~~ 20 unique characters excluding whitespaces
All whitespaces could be changed into newlines.
```
%:include<iostream>
%:include<list>
int n;
const int co<%%>;
const int ci<%not co%>;
const int cmu<%-ci-ci-ci-ci%>;
const char ctd<%-cmu-cmu-cmu-cmu-cmu-cmu-cmu-cmu%>;
const int cia<%-ctd-ctd-ctd-ctd-ctd-cmu%>;
const int ciu<%cia- -ci- -ci%>;
struct<%struct<%struct<%struct<%struct<%struct<%struct<%
int c<:ctd-ci:>;
%>d<:ctd:>;int c<:ctd-ci:>;%>d<:ctd:>;int c<:ctd-ci:>;
%>d<:ctd:>;int c<:ctd-ci:>;%>d<:ctd:>;int c<:ctd-ci:>;
%>d<:ctd:>;int c<:ctd-ci:>;%>d<:-cmu:>;int c<:-ci-cmu:>;
%>e<:co:><:ctd:><:ctd:><:ctd:><:ctd:><:ctd:><:ctd:>;
int i<:co:>;
auto ia<%e%>;
auto iu<%e%>;
int l<%std::cin>>n and co%>;
struct s<%
int c<%std::cout<<i<:ciu:>- --i<:cia:><<ctd and n%>;
%>;
struct o<%
int c<%--ia and n%>;
%>;
struct t<%
std::list<s>c<%- --l%>;
std::list<o>r<%-l%>;
int m<%std::cout<<std::endl and n%>;
%>;
std::list<t>a<%n%>;
int main;
```
Exits with segfault. Used characters: `%:include<ostram>;-h`.
It works in this specific compiler version on a 64 bit Linux:
```
g++-5 (Ubuntu 5.5.0-12ubuntu1) 5.5.0 20171010
```
With the parameter:
```
-std=c++17
```
Even then, I'm not sure it would always work. It may also depends on a lot of other things. `cia` and `ciu` are the memory offsets divided by 4 between `ia` `iu` and `i`. (`int` is 32 bit in this version.) You may have to change the numbers to match the actual offset. The addresses would be much more predictable if they are all contained in a struct. Unfortunately non-static `auto` isn't allowed in a struct.
`e` is a 0-elements array of an element type with a size of (232-1) ×232 bytes. If the corresponding pointer type of `e` is decremented, the higher half of the pointer would be decremented by (232-1), which is equivalent to incrementing by one. This could reset the decremented counter without using the equality sign.
A more reasonable version that should work more reliably, but uses one more character `=`:
```
%:include<iostream>
%:include<list>
int n;
int ci<%not n%>;
int cmu<%-ci-ci-ci-ci%>;
char ctd<%-cmu-cmu-cmu-cmu-cmu-cmu-cmu-cmu%>;
int i;
int l<%std::cin>>n and n-n%>;
struct s<%
int c<%std::cout<<- --i<<ctd and n%>;
%>;
struct t<%
std::list<s>c<%- --l%>;
int r<%i=n-n%>;
int m<%std::cout<<std::endl and n%>;
%>;
std::list<t>a<%n%>;
int main;
```
Even this doesn't work in the latest version of g++ because it doesn't seem to allow defining `main` in an arbitrary type anymore.
These two programs don't use parentheses. But then semicolons don't seem to be avoidable.
[Answer]
22 Unique characters excluding whitespaces. Separates the numbers with a NUL character which displays correctly on Windows.
```
%:include<iostream>
int main(int n)<%
std::cin>>n;
for(int r<%%>;r++<n;)<%
for(int i<%%>;i<r;)
std::cout<<++i<<std::ends;
std::cout<<std::endl;
%>
%>
```
[Try it online](https://tio.run/##bYwxCsMwDEV3nyKLoMF06NDFErpLsJ0iSORgO@d3W5ekHarp//8e8tt2fXjfGjhRv@whkqRSc5xWNqJ1WCfRyzvoSGCG15UanPOizIp9mFPuRiYAxmwtKR7yL5fOhTKOJ/s@THslslaIeo8aCpo/ykGXDwU2wK3d7k8)
Histogram:
```
[%] 0x25 = 9
[:] 0x3A = 11
[)] 0x29 = 3
[i] 0x69 = 11
[n] 0x6E = 12
[c] 0x63 = 4
[l] 0x6C = 2
[u] 0x75 = 3
[d] 0x64 = 8
[e] 0x65 = 4
[<] 0x3C = 13
[o] 0x6F = 5
[s] 0x73 = 7
[t] 0x74 = 12
[r] 0x72 = 6
[a] 0x61 = 2
[m] 0x6D = 2
[>] 0x3E = 7
[(] 0x28 = 3
[;] 0x3B = 7
[f] 0x66 = 2
[+] 0x2B = 4
Unique Characters: 22
Total Characters: 189
```
] |
[Question]
[
[This is a Google interview question, see here for a youtube link.](https://www.youtube.com/watch?v=XKu_SEDAykw)
### The task:
Find 2 integers from an unordered list that sum to a given integer.
1. Given an unordered list of integers, find 2 integers that sum
to a given value, print these 2 integers, and indicate success (exit 0). They don't need to be any particular numbers (i.e. the first 2 integers summing to the right number), any pair that sums to the value will work.
2. an integer is positive and greater than zero.
3. a list of integers can be in any data structure including a file of
integers - one integer per line.
4. if no integers can be found, indicate a failure (exit 1).
5. two integers at different positions in list must be returned. (i.e. you can't return the same number from the same position twice)
(Note: in the video, these are not exactly the requirements. The 'interviewer' changed his multiple times.)
eg.
```
sum2 8 <<EOF
1
7
4
6
5
3
8
2
EOF
```
Prints `3` and `5` and exit status is 0.
Note that in this `1,7` and `2,6` would also be allowed results.
```
sum2 8 <<EOF
1
2
3
4
```
Returns exit status 1 since no possible combo. `4,4` isn't allowed, per rule 5.
[Answer]
# Bash, 84 bytes
My implementation of (roughly) Google's engineer's solution but using bash and an input stream - not my solution, so this does not count.
```
while read V;do((V<$1))&&{ ((T=R[V]))&&echo $T $V&&exit;((R[$1-V]=V));};done;exit 1
```
Method
while we can read integer V from input stream
if less than target $1 then
if already seen $1-V then print $1-V and V and exit 0
(else) save candidate for input $1-V
exit 1
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
h⊇Ċ.+~t?∧
```
[Try it online!](https://tio.run/nexus/brachylog2#@5/xqKv9SJeedl2J/aOO5f//R0cb6hjpGOuY6JjqmMXqGBrG/o8CAA "Brachylog – TIO Nexus")
Assuming I understood the challenge correctly…
### Explanation
```
h⊇Ċ Ċ ('couple') has two elements, and is a subset of the head of the input
Ċ. Output = Ċ
.+~t? The sum of the elements of the Output is the tail of the Input
∧ (disable implicit unification)
```
[Answer]
# [Perl 6](https://perl6.org), 59 bytes
```
$_=get;put lines().combinations(2).first(*.sum==$_)//exit 1
```
[Try it](https://tio.run/nexus/perl6#BcFLCoAgEADQ/ZzCRQttofSzQDxLVFgMpEUzRre39zIF8Vq9uVLN/gjs7szixBRIKr1dccW0MF6JZKv0jg@xrDXl6H01K2PChyyaUiZoYIQeLAzQwQTtDw "Perl 6 – TIO Nexus")
[Try it with no possible result](https://tio.run/nexus/perl6#Ky1OVSgz00u2/q8Sb5ueWmJdUFqikJOZl1qsoamXnJ@blJmXWJKZn1esYaSpl5ZZVFyioaVXXJpra6sSr6mvn1qRWaJg@P@/IZcRlzGXCQA "Perl 6 – TIO Nexus")
## Expanded:
```
$_ = get; # get one line (the value to sum to)
put # print with trailing newline
lines() # get the rest of the lines of input
.combinations(2) # get the possible combinations
.first( # find the first one
*.sum == $_ # that sums to the input
)
// # if there is no value (「Nil」)
exit 1 # exit with a non-zero value (「put」 is not executed)
```
[Answer]
# JavaScript ES6, 58 70 68 64 bytes
```
a=>b=>{for(i in a)if(a.includes(b-a[i],i+1))return[a[i],b-a[i]]}
```
Returns a pair of numbers in the form of an array if found, otherwise returns `undefined`, a falsy value.
```
f=a=>b=>{for(i in a)if(a.includes(b-a[i],i+1))return[a[i],b-a[i]]}
console.log(f([1,7,4,6,5,3,8,2])(8));
console.log(f([1,2,3,4,5,6,7,8])(8));
console.log(f([1,2,3,4])(8));
console.log(f([2,2])(4));
```
[Answer]
## JavaScript (ES6), ~~61~~ ~~57~~ 56 bytes
Takes the array of integers `a` and the expected sum `s` in currying syntax `(a)(s)`. Returns a pair of matching integers as an array, or `undefined` if no such pair exists.
```
a=>s=>(r=a.find((b,i)=>a.some(c=>i--&&b+c==s)))&&[r,s-r]
```
### Formatted and commented
```
a => // given an array of integers (a)
s => ( // and an expected sum (s)
r = a.find((b, i) => // look for b at position i in a such that:
a.some(c => // there exists another c in a:
i-- && // - at a different position
b + c == s // - satisfying b + c == s
) // end of some()
) // end of find(): assign the result to r
) && // if it's not falsy:
[r, s - r] // return the pair of integers
```
### Test
```
let f =
a=>s=>(r=a.find((b,i)=>a.some(c=>i--&&b+c==s)))&&[r,s-r]
console.log(f([1,7,4,6,5,3,8,2])(8))
console.log(f([1,2,3,4])(8))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
ŒcS=⁹$$ÐfḢṄo⁶H
```
[Try it online!](https://tio.run/nexus/jelly#ATIAzf//xZJjUz3igbkkJMOQZuG4ouG5hG/igbZI/8OH4bmb4oCc//9bNSw4LDIsOSw2Xf8xMQ "Jelly – TIO Nexus")
This is a function (not a full program) that outputs to standard output. (The TIO link has a wrapper that runs a function and disregards its return value.)
This program could be 4 bytes shorter if not for the exit code requirement; returning an exit code of 1 in Jelly is fairly hard. (It's possible that there's a terser way to do this that I've missed.)
## Explanation
```
ŒcS=⁹$$ÐfḢṄo⁶H
Œc All pairs of values from {the first argument}
Ðf Take only those which
S=⁹ sum to {the second argument}
$$ Parse the preceding three builtins as a group
Ḣ Take the first result (0 if there are no results)
Ṅ Output this result (plus a newline) on standard output
o⁶ If this value is falsey, replace it with a space character
H Halve every element of the value
```
We can halve every integer in a pair just fine, so the `o⁶H` will do nothing if we found a result, other than returning a useless return value that isn't relevant anyway (the `Ṅ` serves as a convenient single-byte method to determine the function's return value early, under PPCG rules). However, if we didn't find a result, we end up trying to halve a space character, an operation so meaningless it causes the Jelly interpreter to crash. Fortunately, this crash produces an exit code of 1.
[Answer]
# [Perl 5](https://www.perl.org/), 51 bytes
46 bytes of code + for 5 bytes for `-pli` flags.
```
$\="$_ $v"if$h{$v=$^I-$_};$h{$_}=1}{$\||exit 1
```
[Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAtyMm0@K8SY6ukEq@gUqaUmaaSUa1SZqsS56mrEl9rDeLF19oa1larxNTUpFZkligY/v9vyGXOZcJlxmXKZcxlwWUEAA "Perl 5 – TIO Nexus")
The idea is to iterate on the input list: on a number `x` (`$_`), if we previously saw `n-x` (`$^I-$_`) then we found what we were looking for, and set `$\` to these two values (`"$_ $v"`). At the end, if `$\` isn't set, then we `exit 1`, else it will be implicitly printed.
[Answer]
# [Röda](https://github.com/fergusq/roda), ~~60~~ 56 bytes
```
f s,a{seq 1,s|{|x|[[x,s-x]]if[x in a,s-x in a-x]}_|pull}
```
[Try it online!](https://tio.run/nexus/roda#jY3LCsIwEEXX7VfcpcIotFbtv4QgoU010JdNhUiTb69JF4qi4G7m3DN35gqaxKTlFQlpO1ljGTOkN4ZzVTED1UKEdRk8dSfb3@razY3wZIqjflDtiGqVE1hCSAk7QkbYEw6EIyHn65eVvVmficdpYONwR9nF0Y/yoBRiLC6QT0duG6m1OHtSdq380rE8@OfUzQ8 "Röda – TIO Nexus")
This code throws an error if there is no answer. It generates all possible pairs that can form the sum `s`, ie. `1, s-1`, `2, s-2`, `3, s-3`, ... Then it checks if both numbers are in the array `a` and if so, pushes them to the stream. `pull` reads one value from the stream and returns it. If there are no values in the stream, it throws an error. `a-x` returns the array `a` with `x` removed.
[Answer]
## Python 2, 60 bytes
This short, until rules with exiting with code 1 are clarified. Now exits with error if nothing is found.
-5 bytes thanks to @Peilonrayz
-4 bytes thanks to @Rod
[Try it online](https://tio.run/nexus/python2#@5@oU2ybmVdQWqKhyVWekZmTqpBoxaVQYZuoV5BfABRTyExTKNatUMjMA0oU2QKZOhVcBUWZeSUKRf//RxvqGOkY65jomOqYxepYAAA)
```
a,s=input()
while a:
x=a.pop()
if s-x in a:r=s-x,x
print r
```
[Answer]
# C++ 133 bytes (compiled with clang 4 and gcc 5.3 -std=c++14)
```
#include <set>
auto f=[](auto s,int v,int&a,int&b){std::set<int>p;for(auto i:s)if(p.find(i)==end(p))p.insert(v-i);else{a=v-i;b=i;}};
```
# C 108 bytes
```
void f(int*s,int*e,int v,int*a,int*b){do{int*n=s+1;do if(v-*s==*n){*a=*s;*b=*n;}while(++n<e);}while(++s<e);}
```
[Answer]
# [Haskell](https://www.haskell.org/), 34 bytes
```
(n:v)#s|elem(s-n)v=(n,s-n)|1<2=v#s
```
[Try it online!](https://tio.run/nexus/haskell#@6@RZ1WmqVxck5qTmqtRrJunWWarkacDYtQY2hjZlikX/89NzMyzTclX4FKAgoKizLwSlWhDHSMdYx2TWGVzdBkjHaNYZROc6i3@AwA "Haskell – TIO Nexus")
For each element of the list, this function checks if (sum-element) is in the following part of the list. Returns the first couple it finds. If the function reaches the end of the list it throws a "non -exhaustive patterns" error and exits with code 1.
[Answer]
## PowerShell, ~~109~~ 97 bytes
```
param($i,$a)($c=0..($a.count-1))|%{$c-ne($f=$_)|%{if($a[$f]+$a[$_]-eq$i){$a[$f,$_];exit}}};exit 1
```
Took a 12 byte deal that AdmBorkBork offered
**Explanation**
```
# Get the parameter passed where $i is the addition target from the array of numbers in $a
param($i,$a)
($c=0..($a.count-1))|%{
# We are going to have two loops to process the array elements.
# The first loop element will be held by $f
$f=$_
# Create a second loop that will be the same as the first except for the position of $f to
# prevent counting the same number twice.
$c|?{$_-ne$f}|%{
# Check if the number at the current array indexes add to the target value. If so print and exit.
if($a[$f]+$a[$_]-eq$i){$a[$f],$a[$_];exit}
}
}
# If nothing was found in the loop then we just exit with error.
exit 1
```
The current rules look for exit code which this does. Those could be removed and just check for numbers being returned and a falsy.
**Sample Usage**
If the code above was saved as function `s`
```
s 8 @(1,2,3,4)
s 8 @(1,7,4,6,5,3,8,2)
```
[Answer]
## R, 49 bytes
```
function(x,y){r=combn(x,2);r[,colSums(r)==y][,1]}
```
This finds all 2-combinations of `x` and returns a matrix. Then, sums by column and finds all the sums that equal to `y` (so without the `[,1]` part at the end it will print all the combinations that their sums equal to `y`)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
*Saved many bytes thanks to @ETHproductions*
```
à2 æ_x ¥V
```
[Try it online!](https://tio.run/nexus/japt#@394gZHC4WXxFQqHlob9/x9tqGOuY6JjpmOqY6xjoWMUq2MBAA "Japt – TIO Nexus")
### Explanation
```
à2 æ_x ¥V
à2 // Creates all combinations of the input, length 2
æ // Returns the first item where:
_x // The sum of the two items in each set
¥V // == Second input
```
### Example
```
Input: [1,2,3], 4
à2 // [[1,2],[1,3],[2,3]]
æ_x // [3, 4, 5 ]
¥V // 3!=4, 4==4 ✓
Output: // 1,3
```
[Answer]
## Javascript, ~~114~~ ~~96~~ ~~86~~ 84 bytes
```
a=>b=>{c=b.length;for(x=0;x<c;x++)for( y=x;++y<c;)if(b[x]+b[y]==a)return[b[x],b[y]]}
```
*Saved 1 byte thanks to @Cyoce and another 8 bytes thanks to @ETHProductions*
This returns a tuple with the first combination of list-elements that sum up to the given input, or nothing for no match. I've removed the `var`s in the function; REPL.it crashes without them, but the Chrome Dev Console handles this just fine...
[Try it online!](https://repl.it/G3vE/2)
[Answer]
## Clojure, 77 bytes
```
#(first(mapcat(fn[i a](for[b(drop(inc i)%):when(=(+ a b)%2)][a b]))(range)%))
```
Returns the first such pair or `nil`.
[Answer]
## Haskell, 62 bytes
```
r=return;s#[]=r 1;s#(a:b)|elem(s-a)b=print(a,s-a)>>r 0|1<2=s#b
```
I still don't know what's allowed by the challenge and what not. I'm going for a function that prints a pair of numbers and returns 0 if there's a solution and prints nothing and returns 1 if there's no solution. As printing is I/O, I have to lift the return values into the IO-Monad (via `return`) and the actual type of the function is `Num a => IO a`.
Usage example (with return value printed by the repl):
```
*Main> 4 # [2,2]
(2,2)
0
```
[Try it online!](https://tio.run/nexus/haskell#lY2xDoIwFEX3fsUNdSgBEml0QcoXOOlIGNpYIokU8lriwr9X6x@43ZPckxNJkQ0buYvn/aAI9XcI3Zh8ty87C1/p3KiVJheELhN1HeG4161Unps468lB4bEwABZthRPvZSmHxOsW7oGuDgdkt18FPuiw@QYZigL@ubxhWbqOST3/qY4sfgA "Haskell – TIO Nexus").
If raising exceptions is allowed, `fail` will save some bytes (total 51):
```
s#[]=fail"";s#(a:b)|elem(s-a)b=print(a,s-a)|1<2=s#b
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ŒcS=¥ÐfḢZ
```
Jelly has no way of setting the exit code to arbitrary values, so this produces a *TypeError* for input without a valid solution that will cause the parent interpreter to exit with exit code **1**.
[Try it online!](https://tio.run/nexus/jelly#@390UnKw7aGlhyekPdyxKOr///@GOgrmOgomOgpmOgqmOgrGOgoWOgpG/y0A "Jelly – TIO Nexus")
### How it works
```
ŒcS=¥ÐfḢZ Main link. Argument: A (array of integers), n (integer)
Œc Yield all 2-combinations of different elements of A.
Ðf Filter by the link to the left.
¥ Combine the two links to the left into a dyadic chain.
S Take the sum of the pair.
= Compare the result with n.
Ḣ Head; extract the first pair of the resulting array.
This yields 0 if the array is empty.
Z Zip/transpose the result.
This doesn't (visibly) alter pairs, but it raise a TypeError for 0.
```
[Answer]
# [Nova](http://nova-lang.org), 101 bytes
```
q(Int[] a,Int x)=>a{if(Int y=a.firstWhere({a.contains(x-a.remove(0))}))return [y,x-y];System.exit(1)}
```
One nice thing about code golf is that it helps me find bugs in my language. e.g. the space required between `return` and `[y,x-y]`.
Once I add push/pop functions to Array.nova and fix return, would be 96 bytes:
```
q(Int[] a,Int x)=>a{if(Int y=a.firstWhere({a.contains(x-a.pop())}))return[y,x-y];System.exit(1)}
```
Usage:
```
class Test {
static q(Int[] a,Int x)=>a{if(Int y=a.firstWhere({a.contains(x-a.remove(0))}))return [y,x-y];System.exit(1)}
public static main(String[] args) {
Console.log(q([1, 2, 3, 4, 5], 8)) // [5, 3]
Console.log(q([1, 2, 3, 4, 5], 5)) // [1, 4]
Console.log(q([1, 2, 3, 4], 8)) // exit code 1
}
}
```
Edit:
Also, there's this way at 73 bytes (69 using pop), too:
```
q(Int[] a,Int x)=>[Int y=a.firstOrThrow({a.contains(x-a.remove(0))}),x-y]
```
firstOrThrow will throw an Exception, which will be uncaught and therefore ultimately exiting the program with exit code 1. ;)
This way seems more readable too.
[Answer]
# Pyth, 12 bytes
```
hfqsThQ.ceQ2
```
### Explanation
```
.ceQ2 Get all pairs from the second input
fqsThQ Find the ones whose sum is the first input
h Take the first (exits with error code 1 if there aren't any)
```
[Answer]
# PHP, 88 bytes
```
for($i=1;$a=$argv[$k=++$i];)for(;$b=$argv[++$k];)if($a+$b==$argv[1])die("$a $b");die(1);
```
takes input from command line arguments, sum first. Run with `-nr`.
Fortunately, `die`/ `exit` exits with `0` when you give it a string as parameter.
I tried to merge the loops to one; but it requires a longer initialization and test this time.
[Answer]
## Mathematica, 76 bytes
```
f::e="1";If[(l=Cases[#~Subsets~{2},x_/;Tr@x==#2])=={},Message@f::e,First@l]&
```
Fairly straightforward: `#~Subsets~{2}` gets all 2-element subsets of the list, then `Cases[...,x_/;Tr@x==#2]` picks only the ones whose sum is the number we want. If there are none of these, `If[l=={}, Message@f::e,First@l]` prints the error message `f::e : 1` that we defined earlier (since I have no idea what else "exit status 1" might mean for Mathematica); otherwise, it returns the first entry in the list of pairs that sum to the correct thing.
If we're allowed to return a falsey value instead of doing that weird exit status thing, the following code has 58 bytes:
```
If[(l=Cases[#~Subsets~{2},x_/;Tr@x==#2])=={},1<0,First@l]&
```
[Answer]
# Scala, 55 41 bytes
```
(l,n)=>l combinations 2 find(_.sum==n)get
```
Returns a list of the two numbers if they exist and throws an error otherwise. Uncaught, this error will result in an exit status of 1.
[Answer]
# Ruby, ~~53~~ 48 bytes
```
->a,s{p(a.combination(2).find{|x,y|x+y==s})?0:1}
```
Input: a is the list, s is the expected sum.
If the 2 numbers are found, print them and return 0, otherwise return 1, as in the specification.
[Answer]
# TI-Basic, 59 bytes
```
Prompt L1
Prompt X
While 1
L1(1→B
seq(L1(C),C,2,dim(L1→L1
If sum(not(X-L1-B
Then
Disp B,X-B
Return
End
End
```
Explanation:
```
Prompt L1 # 4 bytes, input array like "{1, 2, 3}"
Prompt X # 3 bytes, Input target sum
While 1 # 3 bytes, until the list is empty
L1(1→B # 7 bytes, try the first element (now B)
seq(L1(C),C,2,dim(L1→L1 # 18 bytes, remove first element from list
If sum(not(X-L1-B # 10 bytes, if any element in the list plus B is the target
Then # 2 bytes, then...
Disp B,X-B # 7 bytes, print it and it's "complement"
Return # 2 bytes, and exit gracefully
End # 2 bytes
End # 1 byte
```
If the program did not exit gracefully, it will cause an error when there are not enough elements in the list for it to continue.
[Answer]
## CJam, 23 bytes
```
l~_,1>{e!2f<::+#)}{;;}?
```
Input is `sum numbers`. For example: `6 [3 2 3]`. Leaves a positive number for truthy and an empty string or 0 for falsey.
Explanation:
```
l~ e# Read input and evaluate: | 7 [3 2 3]
_ e# Duplicate: | 7 [3 2 3] [3 2 3]
, e# Take the length: | 7 [3 2 3] 3
1>{ e# If more than 1: | 7 [3 2 3]
e! e# Unique permutations: | 7 [[2 3 3] [3 2 3] [3 3 2]]
2f< e# Slice each to length 2: | 7 [[2 3] [3 2] [3 3]]
::+ e# Some each: | 7 [5 5 6]
# e# Index: | -1
) e# Increment: | 0
}{ e# Else: | 7 [3 2 3]
; e# Pop | 7
; e# pop |
}? e# Endif
e# Implicit output: 0
```
] |
[Question]
[
Write a program which parses the output of `uptime` and generates an anatomically suggestive progress bar (as shown) with a length equal to the current uptime in days:
```
$ uptime
23:01 up 34 days, 7:30, 5 users, load averages: 0.23 0.27 0.24
$ uptime|<command>
8==================================D
```
(34 days = 34 equal signs)
Shortest answer wins.
[Answer]
# Ruby, 39
No input required (by shelling out):
```
`w`=~/up (\d*)/;puts '8'+'='*$1.to_i+'D'
```
Or from stdin (40 chars):
```
gets=~/up (\d*)/;puts '8'+'='*$1.to_i+'D'
```
[Answer]
## Bash, 71 characters
```
a=`uptime` a=${a#*p } a=${a%% *};while((a--));do p==$p;done;echo I${p}I
```
I'm not that much into exposing my ~~gen~~uptimes on the internet, so I'm drawing a fence instead. It's the same character count. Think of resetting `p` between calls.
Pure bash, 71 characters including `uptime`.
```
$ uptime
23:35:12 up 159 days, 4:15, 15 users, load average: 1.07, 0.63, 0.38
```
Well, well, well... mine's bigger than yours.
[Answer]
## Perl - 26 24 characters
```
/p (\d+)/;say+8,"="x$1,D
```
Ran like so:
```
$ uptime
04:52:39 up 17 days, 11:27, 3 users, load average: 0.21, 0.07, 0.02
$ uptime | perl -nE '/p (\d+)/;say+8,"="x$1,D'
8=================D
```
*edit*: Unquoted the final 'D' - thanks **J B**
[Answer]
## Haskell, 88 characters
As is often the case, Haskell doesn't offer the most extreme golfability of some other languages, but does allow an elegant expression of the mathematical structures underlying the problem. Building on their seminal work in this field, I aim to introduce a Haskell implementation of the [Holkins-Krahulik Approximation operator](http://www.penny-arcade.com/comic/2000/9/22/). Briefly, the operator ignores both its inputs and returns a phallus-printing function parameterized by shaft length.
```
_⁑≈≈≈⊃_=(\n->concat["8",take n$repeat '=',"D"])
main=interact$(0⁑≈≈≈⊃1).read.(!!2).words
```
[Answer]
**Perl, 17 characters**
Now with say:
```
say+8,"="x$F[2],D
```
Yields
```
uptime | perl -naE 'say+8,"="x$F[2],D'
```
was:
```
print"8"."="x$F[2]."D"
```
Yields
```
]# uptime | perl -anle 'print"8"."="x$F[2]."D"'
8=========================D
```
(I can't "say", sadly)
[Answer]
## 57 characters
```
python -c "print'8'+'='*int(raw_input().split()[2])+'D'"
```
[Answer]
## 35 characters
```
awk '{printf"#%"$3"sp",p}'|tr \ \*
```
so,
```
uptime
12:27μμ up 111 days, 2:36, 1 user, load averages: 0,07 0,03 0,00
uptime | awk '{printf"#%"$3"sp",p}'|tr ' ' '*'
#***************************************************************************************************************p
```
**Edit**: was
```
printf "#%`awk '{print $3}'`sp"|tr ' ' '*'
```
**Edit 2**: J B's comment (use `\` instead of `''`)
[Answer]
## Windows PowerShell, 28
```
"8$('='*(-split$input)[2])D"
```
At least
```
echo 23:01 up 34 days, 7:30, 5 users, load averages: 0.23 0.27 0.24|powershell -file uptime.ps1
```
yields the correct output, so it should be able to handle `uptime`'s output. I cannot test, though, since GNUWin32 includes a broken `uptime` that tries to read from a non-existant file (Note to people porting Unix tools: Don't try to assume that Windows is a Unix and adheres to the same principles or conventions; there is no file containing the boot time on Windows).
[Answer]
## Common Lisp, 84 characters
```
(defun p(s)(write 8)(loop repeat(read-from-string(subseq s 9))do(write'=))(write'D))
```
This takes the uptime string as input. It seems like there ought to be a shorter solution mapping #'write over a list, but if so I can't come up with it.
[Answer]
## GolfScript (24 characters)
```
' '/{(;}3*(\;~'='*8\'D'
```
## Haskell (73 characters)
```
main=getLine>>=putStr.('8':).(++"D").(`take`repeat '=').read.(!!2).words
```
## C (131 characters)
```
#define r(a);read(0,x,a),
#define p ;putchar(
x[9];main(i){for(r(1)i<3;i+=*x==32)r(9)0
p'8');for(i=atoi((int)x+2);i--p'='))p'D');}
```
[Answer]
## PHP, 62 characters
```
<?$d=split(" ",`uptime`);echo 8;while($d[3]--)echo"=";echo"D";
```
No input required, it shells out.
[Answer]
## Python (42)
```
print('8'+int(input().split()[2])*"="+'D')
```
*Note: Python 3 used for reducing total character count.*
[Answer]
# Python, 65 Bytes
```
import sys
print '8'+'='*int(sys.stdin.readline().split()[2])+'D'
```
test:
```
echo '23:01 up 34 days, 7:30, 5 users, load averages: 0.23 0.27 0.24'|./time.py
8==================================D
```
[Answer]
## PHP, 61
```
<?$n=split(' ',$argv[1]);$v=8;while($n[2]--)$v.'=';echo"$vD";
```
[Answer]
### Common Lisp, 57 characters
(excluding implementation/OS-specific shebang)
```
#!/opt/local/bin/sbcl --script
(do()((eql(read-char)#\p)(format t"8~v,,,'=<~>D"(read))))
```
Based on an attempt to satisfy [Dr. Pain's answer](https://codegolf.stackexchange.com/questions/1570/uptime-progress-bar/1922#1922)'s wish for a shorter way to write a repeated character. This one can be used in a pipeline as shown in the question.
(The format string specifies to right-justify the empty string (between `~<` and `~>`), in a field of width specified by an argument, padded using the `=` character.)
[Answer]
# K, 35
```
-1"8",(("I"$(" "\:0:0)@3)#"="),"D";
```
.
```
$ uptime
17:21:47 up 242 days, 7:22, 35 users, load average: 0.33, 0.34, 0.44
$ uptime | q t.k
8============================================================================ ...
```
[Answer]
## Bash 67 chars
```
read t u d w
echo -e '\t'|expand -t $d|sed 's/^/8/;s/ /=/g;s/$/B/;'
```
invocation to the letter of the assignment:
```
uptime | ./cg1570uptime-bar.sh
```
Much shorter
### just 54 chars:
with this variation:
```
echo -e '\t'|expand -t $3|sed 's/^/8/;s/ /=/g;s/$/B/;'
```
invocation, not 100% in accordance with the rules:
```
./cg1570uptime-bar.sh $(uptime)
```
output in both times:
```
uptime && uptime | ./cg1570uptime-bar.sh
06:29:53 up 16 days, 21:03, 10 users, load average: 1.29, 1.34, 1.23
8================B
```
Non-everyday tricks:
```
read t u d w
```
reads 06:29:53=t, up=u, 16=d rest...=w
without w, everything to the end would be put into $d.
expand is normally used to translate a tab into an amount of blanks and takes a parameter if you don't like 8.
Grabbing the 3rd parameter with $3 in `echo -e '\t'|expand -t $3|sed 's/ /=/g'` is even shorter, but needs an invocation, not fitting to the words of the rules.
[Answer]
### bash/zenity 38 short version, 68 longer version
```
read c o d e
zenity --scale --value=$d --max-value=497 --text=uptime
```
The short version ends after $d, the longer takes into account that we know a max-value and like to have helpful text:

[Answer]
# [Gema](http://gema.sourceforge.net/), 24 characters
```
<D> d=8@repeat{$1;=}D;?=
```
Sample run:
```
bash-4.4$ uptime
18:35:31 up 13 days, 7:53, 16 users, load average: 0.31, 0.85, 1.24
bash-4.4$ uptime | gema '<D> d=8@repeat{$1;=}D;?='
8=============D
```
[Answer]
# [AutoHotkey](https://autohotkey.com/), 39 bytes
```
d:=A_TickCount//=8.64e+7
Send 8{= %d%}D
```
No input. Result is sent to active window.
The built-in `A_TickCount` is the number of milliseconds since the computer was rebooted.
] |
[Question]
[
Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
Santa likes to sort his presents in a special way. He keeps "uninterleaving" the pile of presents into smaller sub-piles until each sub-pile is either full of toys or full of coal.
Your job is to, given a pile of presents, determine the maximum number of uninterleavings.
Uninterleaving a pile of presents, (eg. \$1011011\$), means separating every `second` item and every `second + 1` item into its own sub-pile (\$1101\$, \$011\$).
Sorting \$010011100101\$ would be (implies that \$1\$ is a present full of toys and \$0\$ is a present full of coal):
```
- 010011100101
- 001100
- 010
- 00
- 1
- 010
- 00
- 1
- 101011
- 111
- 001
- 01
- 0
- 1
- 0
```
The answer would be the maximum number of times Santa has to uninterleave the presents (from \$010011100101\$ to \$0\$ or \$1\$), \$4\$.
The shortest code wins. [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
## Test cases
```
[In]: 1
[Out]: 0
[In]: 1010101
[Out]: 1
[In]: 101011
[Out]: 3
[In]: 1011001101110001101011100
[Out]: 5
```
```
[Answer]
# [J](http://jsoftware.com/), 34 bytes
```
1 i.~]*/@(1=#@=/.~)"1(|/~2^])@i.@#
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRUy9epitfQdNAxtlR1s9fXqNJUMNWr064ziYjUdMvUclP9rcqUmZ@QrpCnoGMJYhkAT4BhTEE0IRMJoQzgfIYIk@h8A "J – Try It Online")
Assuming my comments for test case corrections on the OP are correct, this answer should be right.
This generates "power of 2" masks for grouping the input like:
```
0 0 0 0 0 0 0 0
0 1 0 1 0 1 0 1
0 1 2 3 0 1 2 3
0 1 2 3 4 5 6 7
```
It uses each candidate to group the input, and then checks if, using that grouping, we have "pure" coal or present groups. Then it returns the index of the first grouping that works.
[Answer]
# [Python](https://www.python.org), 41 bytes (@dingledooper)
```
f=lambda e,j=1:e[j:]!=e[:-j]and-~f(e,j*2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PU9LCsIwFNy_U8SsEkkh8QNSyElCF5Em2FLT0ET8LLyIm270DF7F22ib1s0wvwfzHi9_jYfW9f3zFG22-1ArG33clxoZVkuRG1XnxUIalWd1oV2Z3S35JcsVnQ7e5qKPvjEBSaQAc8G5EANwgRngBFz89UBmNnZTfSSJYigAtAtn0wWpYMOAMxAM1gy2bMh8V7lIdNMQZUk0IVIpUx_ZtkODwyZdOXSrPJk3TnagBZ32z49_AQ)
### [Python](https://www.python.org), 49 bytes
```
lambda e,j=1:sum(e[j:]!=e[:j-(j:=2*j)]for _ in e)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY5NCsIwEIX3c4rYVSIpJP6AFHKSWCRiig1tWpoUf67ipiB6Bq_ibTRNdTPz3ps38N2e7cUfGzvcC7F99L5IN29eqXp_UEhTI3jm-hprabJ8JrTMTIpNJhZzQ_Ki6dAOlRZpMj2-9FnVbaUdEkhCwjhjnIfBeEIhiYPxvw_ip8ZurI8iygRyAGXdSXdOSFhRYBQ4hSWFNQ23tiutx6qqsCyw184TIWIfBb6Q0Ml_Sa9li3-MU-xITib-YYj7Aw)
Brazenly stole @jezza\_99's test harness.
### How?
Based on the observation that the required split depth equals the number of powers of two `j=1,2,4,8,...` such that `e[j:] != e[:-j]`.
For example, if `j=4` then `e[j:] == e[:-j]` means precisely that any two characters 4 positions apart must be equal. And the four full chains of such element are exactly the uninterleaved piles after two splits.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
WŒœ€ẎQƊƬE€Ạ$€¬S
```
A monadic Link that accepts a list and yields the maximal number of uninterleavings required to separate the items (works for more than just two categories).
**[Try it online!](https://tio.run/##y0rNyan8/z/86KSjkx81rXm4qy/wWNexNa5g9gIVIHVoTfD/h7u3hAGZh9tBApH//6urq8dwGXIZGoAhhAZThgYgbAiiwQwIE6gcAA "Jelly – Try It Online")**
### How?
```
WŒœ€ẎQƊƬE€Ạ$€¬S - Link: list, A
W - wrap (A)
Ƭ - collect up (starting with that) while distinct applying:
Ɗ - last three links as a monad:
€ - for each:
Œœ - odd-even (e.g. [1,0,1,0,0] -> [[1,1,0],[0,0]])
Ẏ - tighten
Q - deduplicate
€ - for each:
$ - last two links as a monad:
€ - for each:
E - all equal?
Ạ - all?
¬ - logical NOT
S - sum
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~29~~ 21 bytes
```
W⊙Eθ✂θλLθX²ⅈ‹⌊κ⌈κM→Iⅈ
```
[Try it online!](https://tio.run/##LYvBCgIhFEX3fcVbPsFAWzaraJsw1KatiIyPHG3UZurrTaOzuBzu5Rqnk4na17o58hbwFD6o9BMXDjdPxnbxHC42TMXhwjiMcbMJDxzuyBp9yxkVBZpfMz5aofT77w1QcbV4vNLkCht2Y6JQ8Kxzwd9/qFVIIaTsIWTdr/4L "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Now uses @Jonah's observation that the problem is equivalent to finding the smallest power of two count of groups where all of the groups are pure.
```
W⊙Eθ✂θλLθX²ⅈ‹⌊κ⌈κ
```
While at least one slice of step 2 to the power the number of iterations contains both toys and coal...
```
M→
```
Increment the number of iterations. (The previous version didn't need the `M` because the block meant that it wasn't ambiguous.) Moving the cursor horizontally doesn't change the output since the canvas trims automatically in this case.
```
Iⅈ
```
Output the number of iterations. Using the X position as the iteration count saves 3 bytes over pushing dummy values to the predefined empty list and 4 bytes over using a counter variable.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~12~~ 9 bytes
```
E?ẇ∩v≈A)Ṅ
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiRT/huofiiKl24omIQSnhuYQiLCIiLCInMSdcbicxMDEwMTAxJ1xuJzEwMTAxMSdcbicwMTAwMTExMDAxMDEnXG4nMTAxMTAwMTEwMTExMDAwMTEwMTAxMTEwMCciXQ==)
### Explanation
Based upon [Jonah's observation.](https://codegolf.stackexchange.com/a/255383/81098)
```
) # a lambda taking N:
E # 2 ** N
? # push input
ẇ # wrapped in chunks of length 2 ** N
∩ # transposed
v≈ # is every element the same? (vectorise)
A # all?
Ṅ # first non-negative integer where it is true
```
[Answer]
# [Python](https://www.python.org), ~~69~~ 58 bytes
```
f=lambda e:0if len({*e})<2else max(f(e[::2]),f(e[1::2]))+1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PZBNCsIwEIX3c4rQVaIREn9AijlJ6SLiBAtpLE3EPzyJm270DF7F22ia1s3jezOPYWYer-YS9gfXdc9jMLP1JzfK6nq70wRzURli0dHbBO9sM0frkdT6TA3FIs_nJeORZI9sKocJbzzrurHoiSIFZEIKIWUUITMOWRIh_z7CSH02xXtImEEJoJ0_YetVAUsOgoPksOCw4rHXtJULVFtLC0MD-sCUSnliDi2JFT74ypFr1dBxx6Hs2e-CtP_4iS8)
A recursive function that splits into two branches at each indentation if the pile is not all `0` or `1`, and returns the maximum number of indentations from all of the branches.
-11 bytes thanks to @GandhiGandhi
[Answer]
# JavaScript (ES6), 71 bytes
```
f=(a,g=q=>v=new Set(a).size>1&&1+f(a.filter(_=>++q&1)))=>g``<g(1)?v:g``
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjUSfdttDWrsw2L7VcITi1RCNRU684syrVzlBNzVA7TSNRLy0zpyS1SCPe1k5bu1DNUFNT09YuPSHBJl3DUNO@zArI/J@cn1ecn5Oql5OfrpGmEW2gY6hjoAMiDeEsII7V1ORCU4lVDKYelx64PG5ZhP3IrkCIIIkCzfgPAA "JavaScript (Node.js) – Try It Online")
Or:
```
f=(a,g=q=>v=/0,1|1,0/.test(a)&&1+f(a.filter(_=>++q&1)))=>g``<g(1)?v:g``
```
[Try it online!](https://tio.run/##dU7LDsIgELz7IWQ3IIWrEfwQYyypQGpI6YP05L8jHmwbYw@7mczMzuzTzGZqxrZPxy4@bM5OgWFeDUrPqhJMviQTFU92SmCQEEkdGO7akOwId6UpHYhERKV9XZ89SLzMpwJzE7spBstD9ODgWpKYYJ8tF1Tmhnj4cf7lvv69m0XfV9f@7Rcrs2FLRn4D "JavaScript (Node.js) – Try It Online")
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~12.5~~ 10.5 bytes (21 nibbles)
```
,|`,,$+.`'`/^2$@>>=~
```
Inspired by [Jonah's answer](https://codegolf.stackexchange.com/a/255383/95126).
```
,|`,,$+.`'`/^2$@>>=~
| # filter each n in
`, # 0..
,$ # length of input
`/ # get chunks of
@ # input
^2$ # of size 2^n,
`' # transpose,
. # and map over each group
=~ # collect identical elements into groups
>> # and remove the first group
, # finally, get the length
```
[](https://i.stack.imgur.com/qrSt3.png)
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 9 bytes
```
ˡ{ᵗ≡ĭ?}aṀ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FhtPL6x-uHX6o86FR9ba1yY-3NmwpDgpuRgqu-BmaLRhLFe0oY6BDhyj8BE8EAmjDeF8hAiSaCzEdAA)
```
ˡ{ᵗ≡ĭ?}aṀ
ˡ{ } Loop until failure, and count the number of iterations:
ᵗ≡ Check that elements in the list are not all equal
ĭ Uninterleave
? Choose any of the two lists
a All possible values
Ṁ Maximum
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 51 bytes
```
f(a,i=1)=if(i<#a&&a[1+i..-1]-a[1..-i-1],1+f(a,2*i))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN43TNBJ1Mm0NNW0z0zQybZQT1dQSow21M_X0dA1jdYFMICMTyNQx1AapNNLK1NSEaq1JLCjIqdRIVNC1UygoyswrATKVQBwlBaBSTU0dhehooEaFaEMdAx04RhVA4oJIGG0I5yNEkERjY6FugHkDAA)
A port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/255387/9288).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~13~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
èø2¤á)©ÒßUcó
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=6PgypOEpqdLfVWPz&input=WyIwMTAwMTExMDAxMDEiXQ)
```
èø2¤á)©ÒßUcó :Implicit input of (initially singleton) array U
è :Count the element that
ø : Contain any element of
2¤ : 2 converted to a binary string
á : Permutations
) :End count
© :Logical AND with
Ò :Negate the bitwise NOT of
ß :A recursive call with argument
Uc : Flat map U
ó : Uninterleave
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞<.Δoι0KSP
```
`o` is inspired by [*@Jonah*'s J answer](https://codegolf.stackexchange.com/a/255383/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//Ucc8G71zU/LP7TTwDg74/9/A0MDA0BBEGBgCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8fdcyz0Ts35dC64vxzOw28gwP@1@r8jzbUMTQAQwhtqKMEpIA0iDAwVAKJgvkQITADwowFAA).
`∞<.Δ` could alternatively be `ÅΔIN` for the same byte-count:
[Try it online](https://tio.run/##yy9OTMpM/f//cOu5KZ5@@ed2GngHB/z/b2BoYGBoCCIMDAE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8Pt56bcmidX/65nQbewQH/a3X@RxvqGBqAIYQ21FECUkAaRBgYKoFEwXyIEJgBYcYCAA).
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
< # Decrease each by 1 to an infinite non-negative list: [0,1,2,...]
.Δ # Pop and find the first which is truthy for:
o # Push 2 to the power this value
ι # Uninterleave the (implicit) input into that many parts
0KSP # Check if each item consists of unique digits (or is empty):
0K # Remove all 0s from the list (including "00","000",etc.)
S # Convert it to a flattened list of digits (also removes empty items)
P # Check if all are 1s by taking the product (only 1 is truthy in 05AB1E)
# (after which the found result is output implicitly)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 46 bytes
```
a=>(g=i=>a.some((v,j)=>v^a[j%i])&&1+g(2*i))(1)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1k4j3TbT1i5Rrzg/N1VDo0wnS9PWriwuMTpLNTNWU03NUDtdw0grU1NTw1Dzf3J@XnF@TqpeTn66RppGtIGOoY6BDog0hLOAOFZTkwtNJVYxmHpceuDyuGUR9iO7AiGCJAo04z8A "JavaScript (Node.js) – Try It Online")
Bit magic
[Answer]
# [Scala 3](https://www.scala-lang.org/), 120 bytes
A port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/255387/9288).
---
```
def f(a:Seq[Int],i:Int=1):Int=if(i<a.length&& !a.slice(i,a.length).sameElements(a.slice(0,a.length-i)))1+f(a, 2*i)else 0
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVE9T8MwEBVrdvYjQ-UjTpSUBUWkEgMDA1PFVHU4gpMaHBdig0BVfwlLFtj4QfBrcBKSggSWfE_37p3vwy9vJidFR837-upG5BYuSGrYvD7YIjz-eLoWBRSM0rm4X5xru-QydZAl2IEsmDyhSAld2tVkAgcUGSVzwSQfWIwMVeJMiUpoa9ggiEdBKBExCVwRDtNDiUIZAXFf_3NvH6BtoXJNMapLk8JpXdPzYm5rqcslpnCppYUMNh6480gKqBUYR3VK1vHw7STIf_s85uP9N_Z3pLUDJqO_Y36w2KWj10HfX1Ssa0H5ihFkM7hz01jlRoyq23405nMfIQAfwpkzQfsLblHuha237bfTND1-AQ)
] |
[Question]
[
Your objective is to write a program that takes an input, and, when chained together `N` times, performs "sequential multiplication". What is sequential multiplication, you may ask? It's a sequence with a seed `a` defined as thus:
```
f(0) = a
f(n+1) = f(n)*(f(n)-1)
```
So, let `a = 5`. Thus, `f(0) = 5`, `f(1) = f(0)*(f(0)-1) = 5*4 = 20`, and `f(2) = f(1)*(f(1)-1) = 20*19 = 380`.
If your program was `ABC`, then `ABC` should take input `a` and output `f(1)`. Program `ABCABC` should output `f(2)`, etc. Your program series should only take input once and only output once.
This is a code-golf so the shortest program in bytes wins. Standard loopholes are banned.
[Answer]
# Jelly, 3 bytes
```
×’$
```
[Try it online!](http://jelly.tryitonline.net/#code=w5figJkkw5figJkk&input=&args=NQ)
### How it works
```
×’$ Main link (or part thereof). Argument (initially input): n
’ Compute n - 1.
√ó Multiply n by (n - 1).
$ Combine the previous two atoms into a monadic quicklink.
```
Repeating the snippet **n** times will execute it **n** times, resulting in the desired output.
[Answer]
## Seriously, 4 bytes
```
,;D*
```
Explanation:
```
,;D*
, push input (NOP once input is exhausted)
;D dupe and push n-1
* multiply
(implicit output at EOF)
```
Just like in Dennis's [Jelly answer](https://codegolf.stackexchange.com/a/73540/45941), repeating this program `n` times will result in it running `n` times. That's one of the many advantages of imperative stack-based languages.
[Try it online!](http://seriously.tryitonline.net/#code=LDtEKg&input=NQ)
[Answer]
# MATL, 3 bytes
```
tq*
```
You can [try it online!](http://matl.tryitonline.net/#code=dHEq&input=NQ) Basically similar to the Seriously and Jelly answers. First, it duplicates the top of the stack (get's input first time when the stack is empty). Decrements the top of the stack and multiplies the two elements to give the next input, or result.
[Answer]
## Python 3, 56 bytes
```
+1if 0else 0
try:n
except:n=int(input())
n*=n-1
print(n)
```
Just wanted a solution without output-overwriting trickery. The lack of a trailing newline is important.
[Answer]
# CJam, 5 bytes
```
r~_(*
```
[Try it online!](http://cjam.tryitonline.net/#code=cn5fKCpyfl8oKg&input=NQ)
### How it works
```
r e# Read a whitespace-separated token from STDIN.
e# This pushes the input (when called for the first time) or an empty string.
~ e# Evaluate.
e# This turns the input into an integer or discards an empty string.
_ e# Copy the top of the stack.
( e# Decrement.
* e# Multiply.
```
[Answer]
# pl, 5 bytes
```
_▼•=_
```
[Try it online.](http://pl.tryitonline.net/#code=X-KWvOKAoj1f&input=Mw)
Would be 4 bytes if I hadn't been lazy and not implemented "assign to \_"...
## Explanation
```
_▼•=_
_ push _ (input var)
▼ decrement last used var (_)
• multiply, since it is off by one it auto-adds _ to the arg list
=_ assign result to _
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
Code:
```
D<*
```
Explanation:
```
D # Duplicate top of the stack, or input when empty
< # Decrement on top item
* # Multiply
```
[Try it online!](http://05ab1e.tryitonline.net/#code=RDwqRDwqRDwq&input=NQ)
[Answer]
# GolfScript, 5 bytes
```
~.(*`
```
[Try it online.](http://golfscript.tryitonline.net/#code=fi4oKmA&input=NQ)
De-golfed and commented:
```
~ # Eval the input to turn it from a string into a number.
. # Duplicate the number.
( # Decrement one of the copies by one.
* # Multiply the copies together.
` # Un-eval the number, turning it back into a string.
```
The GolfScript interpreter automatically reads the input and places it on the stack, but as a string, not as a number. Thus, we need to turn the input into a number with `~`, and stringify it again afterwards with ```. At the end, the interpreter will automatically print out the stringified number on the stack.
(Now, if the challenge had been to iterate `f(n+1) = f(n)*(-f(n)-1)`, I could've done that in 4 bytes with `~.~*`. Figuring out how and why *that* works is left as an exercise. :)
[Answer]
# JavaScript REPL, ~~25~~ 20 bytes
```
a=prompt();
a*=a-1//
```
Will work on eliminating a REPL
[Answer]
## Lua, ~~35~~ 18 Bytes
It's something that Lua can do pretty easily for once!
**Edit: I've discovered a lot of things in Lua since I did this, so I'm updating it :)**
```
print(...*(...-1))
```
`...` contains the command-line argument unpacked, inlining it will use it's first value in this case as it won't be allowed to expend, resulting in just printing `n*(n-1)`.
[Answer]
# [Y](https://github.com/ConorOBrien-Foxx/Y), 7 bytes
```
jzC:t*!
```
[Try it here!](http://conorobrien-foxx.github.io/Y/)
This is how it works: `j` takes numeric input. `z` activates implicit printing. `C` begins a new link. `:` duplicates the value on the stack, and `t` decrements it, leaving us with `[a a-1]`. Then, we get `[a*a-a]` from `*`. `!` skips the next command; on EOF, it does nothing. When chained together, it skips the input command, and the process begins again.
[Answer]
# Jolf, 6 bytes
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=b2oqandq)
```
oj*jwj
```
## Explanation
```
oj*jwj
oj set j to
*jwj j times j-1
implicit output
```
[Answer]
# ùîºùïäùïÑùïöùïü, 5 chars / 7 bytes
```
ïׇï;
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=5&code=%C3%AF%C3%97%E2%80%A1%C3%AF%3B)`
Must I truly explain this? Oh well, here goes...
# Explanation
It basically evaluates to `input*=--input;` in JS.
[Answer]
# Perl, 23 bytes
```
l;$_|=<>;$_*=~-$_;print
```
### Alternate version, 10 bytes
```
$_*=~-$_;
```
This requires the `-p` switch. I'm not sure if it is fair game in a [source-layout](/questions/tagged/source-layout "show questions tagged 'source-layout'") question.
[Answer]
## Haskell, ~~14~~ 11 bytes
```
(*)=<<pred$
```
Usage example
```
Prelude> (*)=<<pred$5
20
Prelude> (*)=<<pred$(*)=<<pred$5
380
Prelude> (*)=<<pred$(*)=<<pred$(*)=<<pred$5
144020
```
Maybe this isn't a proper function. If you're nitpicking you can go with `(*)=<<pred$id` (<-there's a space at the end) for 14 bytes.
Edit: @Zgarb rewrote the function using the function monad and saved 3 bytes. Thanks!
[Answer]
# Pure bash (no utilities), 40
```
((a=a?a:$1,a*=a-1))
trap 'echo $a' exit
```
[Answer]
# TI-Basic, 6 5 bytes
*Runs on TI-83/84 calculators*
```
:Ans²-Ans
```
This program works due to the fact that an expression on the last line of a program is printed instead of the regular `Done` text.
[Answer]
# Mathcad, 39 "bytes"
[](https://i.stack.imgur.com/zhiFQ.jpg)
From user perspective, Mathcad is effectively a 2D whiteboard, with expressions evaluated from left-to-right,top-to-bottom. Mathcad does not support a conventional "text" input, but instead makes use of a combination of text and special keys / toolbar / menu items to insert an expression, text, plot or component. For example, type ":" to enter the definition operator (shown on screen as ":="), "[" to enter an array index, or "ctl-]" to enter a while loop operator (inclusive of placeholders for the controlling condition and one body expression). What you see in the image above is exactly what appears on the user interface and as "typed" in.
For golfing purposes, the "byte" count is the equivalent number of keyboard operations required to enter an expression.
One thing I'm even less sure about (from an "byte" equivalence point of view) is how to count creating a new region (eg, a:=5 or k:=0..n-1). I've equated each move to a new region as being equal to a newline, and hence 1 byte (in practice, I use the mouse to click where I want the region).
I've only included the active statements and not the comments, and I've included 2 bytes each for the a and n inputs but not the values themselves (5 and 7 in the example).
[Answer]
# Haskell, 72 bytes
This challenge is not friendly to Haskell.. However, the following works if input is in unary and the code is executed in GHCI:
```
(\x->if odd x then let y=until((>x).(10^))(+1)0 in y*(y-1)else x*(x-1))$
```
# Explanation:
Unary is always odd, so the first application will convert to decimal. `x*(x-1)` is always even, so otherwise it returns `x*(x-1)`, where `x` is the input. Because Haskell is strongly typed and 'special' symbols cannot be called like `&1`, I believe that this is pretty much the only way to complete this in Haskell, unless one used global variables or an even odder input form.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 173 / 176 bytes
Both versions have a crucial newline at the end.
## Macro version, 173 bytes
```
#ifndef M
#define M(a,b)a##b
#define W(z,x)M(z,x)
#define B int W(m,__LINE__)=x++
#include<iostream>
int x,n;int main(){for(std::cin>>n;x--;)n*=n-1;std::cout<<n;}
#endif
B;
```
[Try it online!](https://tio.run/##7Y6xCoMwGIT3PIWQJanJ0KGLUQehQ6F27RhiEkug/opGCC199lRb8A26dbkPvrvh9DDwm9YxYteCsW1SI7zAgU1qolhDFcbNpq7kwQKtP7nJKnHgl6pjUp5Pl6OUtAhpirADfZ@NzV0/@dGqrkTrMDAQKzvlgNBn249k8ibLtIOyBBE4FxR2BfC9@Pp@9nkO4oWwBeNaVAn0P/urszEe3g "C++ (gcc) – Try It Online")
## Template version, 176 bytes
Somewhat more C++ish:
```
#ifndef B
#define B template
#include<iostream>
int x,n;B<int N>struct A{static int i;};int main(){for(std::cin>>n;x--;)n*=n-1;std::cout<<n;}
#endif
B<>int A<__LINE__>::i=x++;
```
[Try it online!](https://tio.run/##7Y6xCoMwFEX3fEXARWsdOnRJYsBAh0LxF4LEpDzQp@gTBPHbU6Xf0K3TuRy4cNw4Fm/nYkwgYOsDNyw5AOi54eT7sWvIswTQdUvrFQwzTb7pNQMkvl5RGnWuWh9@ccSrbaaGwPHTgtzlyb4BTLMtDFM6UyuEA9Qa5VoUMsNLicVNfv2wkFIod5Z4bCEwo/T5r5S1r2f9sFYLAeWa55L9e3/bG@P9Aw "C++ (gcc) – Try It Online")
[Answer]
## Burlesque - 5 bytes
```
J?d?*
blsq ) 5 J?d?*
20
blsq ) 5 J?d?* J?d?*
380
blsq ) 5 J?d?* J?d?* J?d?*
144020
```
] |
[Question]
[
You just invited a liberal arts major to your house and you're telling him/her
>
> "You know, I am a great programmer and I can do x and y and z..."
>
>
>
S/he quickly gets bored and asks you:
>
> "If you really are a great programmer, can you make a programme to let me draw, I just need to draw lines on the screen by using the
> mouse, and selecting different colours in any manner".
>
>
>
Your code may import standard libraries. Your code may require the colours to be selected via the keyboard.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest code wins.
# Bullet points
* The lines are drawn by moving the mouse around while pressing the left button.
* Bresenham's Line Algorithm is not necessary any built-in algorithm will do the trick
* If the user can change the line thickness in any way you get a **\* 0.8** bonus but it is not obligatory.
* I guess it should be nicer to implement the line-drawing ourselves, but if you want you can import a library for that just say it in the code description.
* The minimum is 5 different colours (red,green,blue,white,black). If you make them change randomly you get a penalty of \*1.2. You may change them in any way you may want (both buttons and key presses are OK).
* Drawing them pressing the mouse between to points or freehand would be best (i.e. as you do in paint) and gives you a bonus of \*0.7 , but any other method is okay: (example) click two points and draw a line between those points?
* The drawing canvas has to be **600x400**
* Changing the colour should change the colour only of the lines that will be drawn in the future.
* Implementing a "Clear All " command is not obligatory but if you implement that you get **\*0.9** bonus.
[Answer]
# Processing - 93 · 0.9 = 83.7
With next to no overhead for drawing, but a very verbose syntax, in Processing the best score is probably reached without any nice features and only one bonus:
```
void setup(){
size(600,400);
}
void draw(){
if(mousePressed)line(mouseX,mouseY,pmouseX,pmouseY);
}
```
Score: **93 · 0.9 = 83.7** (Newlines are for readability only and are not counted in the score.)
However, it's much more fun with all the bonuses in place:
```
void setup(){
size(600,400);
}
int i,x,y;
void draw(){
stroke(7*i%256,5*i%256,i%256);
strokeWeight(i%9);
if(keyPressed)i++;
if(!mousePressed){x=mouseX;y=mouseY;if(x<0)background(0);}
}
void mouseReleased(){
line(x,y,mouseX,mouseY);
}
```
Score: **221 · 0.8 · 0.7 · 0.9 = 111.4**
It's used like this:
* Click and drag the mouse to draw a straight line.
* While clicked, drag the mouse off the left side of the window and release the mouse button to clear the screen.
* Holding down any key will cycle through the red, green and blue values of the drawing colour and through different stroke thicknesses. Since the cycling periods are different, practically all combinations can be reached (with a bit of trying).

## Edit:
Since freehand drawing gives the 0.7 bonus as well, here is yet another solution:
```
void setup(){
size(600,400);
}
int i;
void draw(){
stroke(7*i%256,5*i%256,i%256);
strokeWeight(i%9);
if(keyPressed)i++;
if(key>9)background(0);
if(mousePressed)line(mouseX,mouseY,pmouseX,pmouseY);
}
```
Score: **188 · 0.8 · 0.7 · 0.9 = 94.8**
It's used like this:
* Click and drag to draw freehand lines.
* Hold the tab key to change the colour and stroke thickness. This can also be done while drawing (see picture).
* Hit any key but tab and then tab to clear the screen.

[Answer]
## HTML + jQuery + CSS - 507 x (0.7 x 0.8 x 0.9) = 255.528
Not as short as I thought it would be, but I like the result.
**Features:**
* Click-and-drag drawing mode. (**0.7**)
* Seven colors (black + rainbow).
* Variable brush width (slider control). (**0.8**)
* Clear all function. (**0.9**)
**Live Demo:** <http://jsfiddle.net/onsLkh8y/9/>
---
### HTML - 84 bytes
```
<input id="r" type="range" min="1" max="9"><canvas id="c" width="600" height="400"/>
```
---
### CSS - 35 bytes
```
#c{border:1px solid;cursor:pointer}
```
---
### jQuery - 388 / 446 bytes
**W3C compliant browsers (e.g. Chrome) - 388 bytes**
```
var t=c.getContext('2d');$.each('black0red0orange0yellow0green0blue0purple0clear'.split(0),function(k,v){
$(r).before($('<button>'+v+'</button>').click(function(){k>6?t.clearRect(0,0,600,400):t.strokeStyle=v}))})
$(c).mousedown(function(e){t.lineWidth=$(r).val();t.beginPath();t.moveTo(e.offsetX,e.offsetY)})
.mousemove(function(e){if(e.which==1){t.lineTo(e.offsetX,e.offsetY);t.stroke()}})
```
**Cross-Browser version (fixes for Firefox, Safari, IE) - 446 bytes**
```
var t=c.getContext('2d');$.each('black0red0orange0yellow0green0blue0purple0clear'.split(0),function(k,v){
$(r).before($('<button>'+v+'</button>').click(function(){k>6?t.clearRect(0,0,600,400):t.strokeStyle=v}))})
var d,p=$(c).offset();$(c).mousedown(function(e){d=t.lineWidth=$(r).val();t.beginPath()t.moveTo(e.pageX-p.left,
e.pageY-p.top)}).mousemove(function(e){if(d){t.lineTo(e.pageX-p.left,e.pageY-p.top);t.stroke()}}).mouseup(function(){d=0})
```
**Fixes:**
* FireFox - `event.offset[X|Y]` are undefined.
* Safari - `event.which` and `event.buttons` are not meaningfully defined on `mousemove`.
* Internet Explorer - works with both of the above fixes, although using `e.buttons` would have been sufficient.
[Answer]
# Python 2.7 - ~~339~~ ~~197~~ 324 \* (0.7 \* 0.8 \* 0.9) = 163
Edit: I discovered pygame can draw lines with variable width so here is an update.
An experiment in using the PyGame modules.
A simple paint program that draws lines from the MOUSEDOWN event (value 5) to the MOUSEUP event (value 6). It uses the pygame.gfxdraw.line() function. Pressing the TAB key will cycle through 8 colours. Pressing the BACKSPACE key will clear the display to a carefully crafted paper white colour. The ENTER key will cycle the brush size through 0-7 pixels in width.
I am new at code-golf so I may have missed some methods of reducing the code size.
```
import pygame as A,pygame.draw as G
P=A.display
D=P.set_mode((600,400))
C=(0,255)
S=[(r,g,b) for r in C for g in C for b in C]
w=n=1
while n:
e=A.event.wait()
t=e.type
if t==12:n=0
if t==2:
if e.key==9:n+=1
if e.key==13:w+=1
if e.key==8:D.fill(S[7])
if t==5:p=e.pos
if t==6:G.line(D,S[n%8],p,e.pos,w%8)
P.flip()
```
## Sample picture 1:

## Sample picture 2:

[Answer]
**C# 519 x 0.7 x 0.8 x 0.9 = 261.6** Using the DrawLine method.
**Golfed:**
```
using System;using System.Drawing;using System.Windows.Forms;class f:Form{[STAThread]static void Main(){f F=new f{Width=600,Height=400};Point s=default(Point);sbyte[]c={0,0,0,1};F.MouseDown+=(_,e)=>{s=new Point(e.X,e.Y);};F.MouseUp+=(_,e)=>{F.CreateGraphics().DrawLine(new Pen(Color.FromArgb(255,c[0],c[1],c[2]),c[3]),s.X,s.Y,e.X,e.Y);};F.KeyPress+=(a,e)=>{unchecked{switch(e.KeyChar){case'r':c[0]++;break;case'g':c[1]++;break;case'b':c[2]++;break;case't':c[3]++;break;case'c':F.Invalidate();break;}}};F.ShowDialog();}}
```
**Readable:**
```
using System;
using System.Drawing;
using System.Windows.Forms;
class f : Form
{
[STAThread]
static void Main()
{
f F = new f { Width = 600, Height = 400 };
Point s = default(Point);
sbyte[] c = { 0, 0, 0, 1 };
F.MouseDown += (_, e) => { s = new Point(e.X, e.Y); };
F.MouseUp += (_, e) => { F.CreateGraphics().DrawLine(new Pen(Color.FromArgb(255, c[0], c[1], c[2]), c[3]), s.X, s.Y, e.X, e.Y); };
F.KeyPress += (a, e) =>
{
unchecked
{
switch (e.KeyChar)
{
case 'r': c[0]++; break;
case 'g': c[1]++; break;
case 'b': c[2]++; break;
case 't': c[3]++; break;
case 'c': F.Invalidate();break;
}
}
};
F.ShowDialog();
}
}
```
By holding **r**, **g** or **b** on your keyboard it changes the color of the next line by incrementing an sbyte-array at the corresponding index. It will start at 0 again when overflowing. So this gives us plenty colors.
Same goes for thickness of the line which is increased by holding **t**.
Pressing **c** clears the form.
[Answer]
# Mathematica - 333 x 0.7 x 0.8 x 0.9 = 168
```
l = {}; c = Black; s = .01;
ColorSetter@Dynamic@c
Dynamic@s~Slider~{0, .02}
Button["Clear", l = {}]
"/" Checkbox@Dynamic@b
EventHandler[
Dynamic@Graphics@{White, Rectangle@{600, 400}, l},
{"MouseDown" :>
AppendTo[l, p = {}; {c, Thickness@s, Line@Dynamic@p}],
"MouseDragged" :> (p =
Append[p, MousePosition@"Graphics"][[If[b, {1, -1}, All]]]),
"MouseUp" :> (l[[-1, 3]] = Line@p)
}
]
```

[Answer]
# Tcl/Tk, 252
# x 0,8 x 0,7 x 0,9
# = 127,008
~~253 x 0,8 x 0,7 x 0,9= 127,512~~
~~254 x 0,8 x 0,7 x 0,9= 128,016~~
~~255 x 0,8 x 0,7 x 0,9= 128,52~~
```
grid [canvas .c -w 600 -he 400]
set c red
incr t
lmap k {1
B1-Motion
3
MouseWheel
2} s {{set L [.c cr l %x %y %x %y -f $c -w $t]}
{.c coo $L "[.c coo $L] %x %y"}
{set c [tk_chooseColor]}
{if $t|%D>0 {incr t [expr %D/120]}}
{.c de all}} {bind . <$k> $s}
```
# Tcl/Tk, 267
# x 0,8 x 0,7 x 0,9
# = 134,568
```
grid [canvas .c -w 600 -he 400]
set c red
set t 0
bind .c <1> {set L [.c cr l %x %y %x %y -f $c -w $t]}
bind .c <B1-Motion> {.c coo $L "[.c coo $L] %x %y"}
bind .c <3> {set c [tk_chooseColor]}
bind .c <MouseWheel> {if $t||%D>0 {incr t [expr %D/120]}}
bind .c <2> {.c de all}
```
To use it:
* Left mouse button behaves as question requests
* The initial color is red. Right mouse shows a dialog which allows the user to choose the color which will be used the next time. Always press OK button, otherwise color will be undefined. I could fix this, but it would consume bytes
* To adjust the thickness of the line that will be used next time, you can rotate the mouse wheel: Up=thicker, Down=thinner
* To clear the image press the middle mouse button
**A simple test:**
[](https://i.stack.imgur.com/dtbDv.png)
[Answer]
# DarkBASIC Pro - 318 x 0.7 x 0.9 = 200.34
The most interesting thing here is using some bitwise logic on the current keyboard scancode to change the color. I use two different bits from the scancode for each channel - so almost any 6-bit color is possible.
* Hold down any key on your keyboard to use a color (on my American keyboard: White=F5, Black=no key, Red=2, Green=- (minus), Blue=b)
* Right-click to clear
Here is a compiled EXE: [Download](http://www.brianmacintosh.com/code/golf_draw.zip)
```
#constant a set current bitmap
set display mode 800,400,32
create bitmap 1,800,400
do
s=scancode()
ink rgb((s&&3)*85,((s/4)&&3)*85,((s>>4)&&3)*85),0
m=mousex()
n=mousey()
o=mouseclick()
if o*(d=0) then d=1:x=m:y=n
a 1
if (o=0)*d then d=0:line x,y,m,n
if o=2 then cls
a 0
cls
copy bitmap 1,0
if d then line x,y,m,n
loop
```
[Answer]
# BBC BASIC - 141 no bonuses
My first programming language and generally never used by me anymore :)
```
SYS "SetWindowPos",@hwnd%,0,0,0,600,400,6:VDU 26
1 MOUSE X,Y,b
IF b=4 THEN GOTO 4
GOTO 1
4 MOUSE x,y,b
IF b=0 THEN LINE X,Y,x,y:GOTO 1
GOTO 4
```
[Answer]
# Python 2.7 - 384 \* .8 \* .7 = 215.04
```
from Tkinter import*;o=1
a='0f';C=['#'+r+g+b for r in a for g in a for b in a]
def i(a):global o;o+=1
def d(a):global o;o-=1
def I(a):global u;u+=1
def D(a):global u;u-=1
m=Tk();u=0;c=Canvas(width=600,height=400);c.bind("<B1-Motion>",lambda x:c.create_rectangle((x.x,x.y,x.x+o,x.y+o),fill=C[u],outline=C[u]));m.bind("q",i);m.bind("w",d);m.bind("x",D);m.bind("z",I);c.pack();mainloop()
```
## With all bonuses: 462 \* .9 \* .8 \* .7 = 232.848
```
from Tkinter import*;o=1
a='0f';C=['#'+r+g+b for r in a for g in a for b in a]
def i(a):global o;o+=1
def d(a):global o;o-=1
def I(a):global u;u+=1
def D(a):global u;u-=1
m=Tk();u=0;c=Canvas(width=600,height=400);c.bind("<B1-Motion>",lambda x:c.create_rectangle((x.x,x.y,x.x+o,x.y+o),fill=C[u],outline=C[u]));m.bind("q",i);m.bind("w",d);m.bind("x",D);m.bind("z",I);m.bind("m",lambda _:c.create_rectangle((0,0,602,402),fill=C[7],outline=C[5]));c.pack();mainloop()
```
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 65 bytes, no bonuses
```
P5.size←2⌿600
P5.draw←{P5.LM.p:P5.G.ln P5.mx P5.my P5.pmx P5.pmy}
```
A straightforward port of the existing processing answer.
## Explanation
```
P5.size←2⌿600 set canvas to 600x600 pixels
P5.draw←{ } do the following every frame:
P5.draw←{P5.LM.p: } if the mouse is held down:
P5.G.ln draw a line from
P5.mx P5.my current mouse position
P5.pmx P5.pmy to previous mouse position
```
] |
[Question]
[
Today's problem is easy. You're given two strings A and B of equal length consisting of only the characters `(` and `)`. Check whether after any number of operations you can make both strings balanced or not. The only operation allowed is swapping A[i] and B[i], where i is an arbitrary index.
Here is the definition of a balanced string.
* An empty string is a balanced string.
* If s is a balanced string, `"(" + s + ")"` is a balanced string.
* If x and y are balanced, `x + y` is balanced.
Tests:
```
( ) -> false
() () -> true
((())) ()()() -> true
()())) ((()() -> true
)))((( ((())) -> false
)))))) )))))) -> false
))))))) ))))))) -> false
()))))) (((((() -> false
```
Shortest code wins.
[Answer]
# [Rust](https://www.rust-lang.org), ~~204~~ ~~179~~ ~~147~~ ~~132~~ ~~123~~ ~~98~~ ~~90~~ 80 bytes
```
|a,b|a.iter().zip(b).fold([0;3],|[c,d,f],(&e,g)|[c+e+g,d^e^g,f.min(c+d)])==[0;3]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVNLboMwEF10VU4xYVHZik0-VaUo3yM0i6obRCoCdmQJTASmitpwkm6yaI_Qw7SnKeQDhISkyMj2zLzHDHrv4zOMI_Vt6pQyVygRSJ2A3m13O7r1Q7kE3xYSYXjXPKaA97lEz8wZit6Y7HdMx_Mg8GD0FStOez_TtU3ma9sQioUIG29iiebY4IHnIrM9uLfI2nSIS7hF0B0jC5xem6y5IO6MzRaEG376PafpYguPRlvAjvf3xh-ApvEgBMUi9eLYEQMhwdQgfdArcxpmxyKQH7jtRQwT7baSo-eSBAosgZoSelKjwrjCsl00f48Aea4WTi_gr8FpCbhfZ9G0ZkB6lK82UJv9F8t1pgs__RJZMWsxYokmk0arBU-pYCATTASPU3A8W_gR2CEDJ4hlKlO2sv2lx6KylM6w1rdUI4Vq0QlzFW2lPst6WIZCKk82kM7RKjVff_gwSUD189NhoCwySVLLcpS7wmgbjhdIhjAprGJ0DsGjaLd8ORQMtERLdq7bbHb7Hw)
* -9 bytes thanks to [SUTerliankov](https://codegolf.stackexchange.com/questions/263496/can-you-perform-swaps/263499?noredirect=1#comment576827_263499)
* -2 bytes thanks to [SUTerliankov](https://codegolf.stackexchange.com/questions/263496/can-you-perform-swaps/263499?noredirect=1#comment576943_263499)
Radically new algorithm. We know the only possible failure case is if:
* We get 2 simultaneous closing parenthesis when the nesting level is 0
* We get 2 different closing parenthesis when the nesting level is 0
We use `d` to store if there currently is an odd or even number of unequal pairs. If the nesting level `c-d` is negative, we fail. If the nesting level is not 0 or the number of unequal pairs is not even at the end we fail.
`d^((e^!g)+1)/2` should be 1 if e=g and 0 otherwise.
Uses `1` to represent an opening parenthesis and `-1` for closing.
[Answer]
# JavaScript, ~~109~~ ~~107~~ ... 95 bytes
*Thanks to @Arnauld for saving 2 bytes*
```
b=(x,k=0n)=>k<0?0:x?b(x/4n,k+x%4n-2n):!k
f=(l,r,k=0n,x=k&(r^l))=>b(l^x)&b(r^x)||k<l&&f(l,r,++k)
```
returns `false` (for `false`) or `1` (for `true`).
Encodes expressions as base four numbers with `3` for `(` and `1` for `)`
Helper functions for converting strings to the corresponding base 4 numbers
```
e=(s)=>s?4n*e(s.slice(1))+(s[0]=='('?3n:1n):0n
h=(x,y)=>f(e(x),e(y))
h(")))(((","((()))") // -> false
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ddFRbsIgGAfw7JVbrIn1_61oUftgGllvsAssc0kdnQZCE5kJJt5kLz5sh9pOM9rqTLYKL8D_9wGB9w9bv6jj8XP3Vo3mX8-lhOdaCkvyXi9EIXJflPBpZrlO_CCzo6ml_FazSsLwbUu5lzrGdmkoFJUwS09xGeaeDge9MHFctTRJNHXHfN88MCXhAndFZu8U3NiZzUphQpTAPYonKYcYFjObT8JxwrJ1c699KKig4Ikr7IkYW9XW1UaNTf2KNSJEPKIoBH_XKQToTQCiLm16b-1Z4IoIcchOglqRpv9Nt8tpcN1cUL_Cr0LbGtU96_kXfwA)
*I was unable to verify the last two Test-cases, as the function exceeded the maximum recursion depth (which as far as I known is allowed for code-golf)*
# Explanation
`b` checks if a the expression encoded by the given number is balanced, by counting the difference of `3` digits minus `1` digits and returning 0 if the intermediate count goes below zero,
or if the final count is not exactly zero.
`f` checks for all binary numbers `k` less than `l` (swapping the outer brackets cannot balance the expression) if swapping the bits of the two inputs at the positions that are one in `k` will result in a pair of balanced strings.
Swapping a bit has no effect if it is the low bit of a base 4 digit where both numbers have a `1` bit, if it is the high bit it will swap the characters that the given positions in the strings.
---
# JavaScript, 108 bytes
```
b=(x,k=0n)=>k<0?0:x?b(x/4n,k+x%4n-2n):!k
f=l=>r=>eval("for(v=0,k=0n;k<l;k++)v|=b(l^k&(r^l))&b(r^k&(r^l));v")
```
uses for-loop to prevent crash due to recursion limit
[Attempt This Online!](https://ato.pxeger.com/run?1=dZHfSsMwGMXxtm9hwO18tpuZ9kLafe21zyAO7EydJKTQaOnAN_FmF_pQ-jSm64ogbQL5d34n5yP5-LTVkzocvt5ey8XttykYbaRZWuJMr2UukzYv0F7FNtJhexHbxbWl5FwHJRvOas5U82ggyqpGw_LoTPXapDoMqXnnAmajZ6g3hmhW-HnYpI2gPvPn7C5QDOcDXR7bSwW3dOZlq7AiCuHu5QPzHPP8xiYrny1tsOuK3HtDCYWWyI97oiDYVtZVRi1N9YwdBEQkSHjh_zl5AaMKQNSrXR_1DgQmCC977UTQBNHfcVpMEX_IeCUDg2PrmP5Fh9_8BQ)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 59 bytes
```
a=>b=>(h=u=>u<d|!a[i]?u|d:h(u+=p=a[i]+b[i++],d^=!p))(i=d=0)
```
[Try it online!](https://tio.run/##jZDBboMwDIbvPIV7whY03WWXdga1Um899cqYGiCsTLQgCFOldc/OEkrXdbvMkWL5@@1fid/ku2zTpqj19Fhlqs@5lxwkHOCeOw66p@w8kVERh905m@@x87hmW3tJVHhe7GcvPKmJsOCMH6jfAIN4dLYmTU12tGp1KlvVGrBzEAimAeSybJWDBDiUuulMhUhkiT03SheKd9QgQ2Ac@TakIWBMv/CV3z3gAnCIH8JO6KY4IIm2LguN7vPRJXGQNZ6AAziNeAYYzs0MhTOixe2nIq@atUz3iJH0IfFBxWTnPhyAtDq2GpZmGZEQQsaDa2pVczGDiy6EsIE5bI3ltX819if/7F@bfnXR7b7cq1KVSpTVKxqdYZKj9VzGNORVTD78Qcb0kxb9Fw "JavaScript (Node.js) – Try It Online")
Input arrays of numbers: `0.5` for `(`, `-0.5` for `)`. Output falsy (0) for "can be balanced", truthy (non-zero) for "cannot be balanced".
Construct a string `c` using inputs `a` and `b` by:
* if the i-th characters match, aka. `a[i]==b[i]`, then `c[i]=a[i]`
* Otherwise, they mismatch. For the k-th mismatch (1-indexed), `c[i]=')'` when k is odd, and `c[i]='('` when k is even.
Test if `c` is balanced and there are even number of mismatching.
In above code, `u-d` is how many unclosed "(" in string `c`. `d` is a boolean, truthy when next mismatch should be "(".
I’m *feeling* its correctness. Although I don’t have a mathematical proof to it. However, at least no testcase rejects it currently.
[Answer]
# [Scala](https://www.scala-lang.org/), ~~165~~ 136 bytes
Port of [@mousetail's Rust answer](https://codegolf.stackexchange.com/a/263499/110802) in Scala.
---
Golfed version. [Try it online!](https://tio.run/##rVTfS8NADH73rwhDJGFnXRUcFFtwPu9p@DREbvWuVGo7e@dYO/q3z7RjbtN1lGGhND@/fClJTCgTuc5m7yq0MJZxCqsLgDel4YMVlHlkPHjMc1lMJzaP0@iFPHhOYws@R3IowEImoD3AifqcjgqrXgT8iAR@AKMsS5RMOWONUszID1BCGc9hRs6NV@chDsSAiFahNApDgaUoiONCRyfSjuV849BiwcYmXvdLsegXJFgqWCqJKh0nVuUY@UHkvLqBP7i6YuGWBarUMjbWbOr4Pq23xK0y9omxDbOrgZuOoGkGXcdmdRfUNIR47dLOomVi@HssXsBh6Cmfzb9aUY5Je9ntyqmarWDnMOyC25mk@38MOxE4XtE9m96JRv8Oi8PDmuA94Z8/0uJpgxi2Qgyp@8gS9PvQjdbvlKNFmhq0uQ86ywG3ewYP17udo@bY1M@cT4tNUjS9y9XWzTtcwb56W4FazvlQqTfvwHFXCYgyWxs17qUL2EumqrehVV3Ub7X@Bg)
Saved 29 bytes thanks to the comment of @corvus\_192
```
(a,b)=>(a zip b)./:(Seq((0,0))){case(c,(z,y))=>c.flatMap{case(f,v)=>Seq((f+z,v+y),(f+y,v+z))}filter(g=>g._1>=0&&g._2>=0)}exists((0,0)==)
```
Ungolfed version. [Try it online!](https://tio.run/##rVRRa9swEH7Pr/goo9wR1cQutBCWwrqnwvpU@lRCUBLJeGh2ZqmjXfBvzyQncZ02DqbswZZO33133x062YU0crMp5j/VwuFeZjnWA2CpNH55g2SZ2jG@laV8fXpwZZanUx7jMc8cJrUn8Eca6DHoQf1@un11airQbBmTG9wWhVEy9wSSAvP6bEsFZPQ3W9GcI12Y5Q@lXR2G7nIn4H88JRqJETNjDVoILyzQd2RgEWkj3b1ceViHuA2CIIJIR7MYQ0/zq4C3kp2VsEAbTQ7QmLmJVEU6M06VlIYEaaDcTDDC@XkwktrYe1eResmsszTDxJc7Eh7aYtWgaZZT1n2XVlnfkSByxw2VUxy5InSOxVb/RcxvJ1oa69dj/r6YA9dTmCufO6Mc27XY3capnJ3BPqOwT9zeIuP/p7CXgOMZ40/LO1Hox8sS7rGhK6YPHelAukJcd4a45v5XljEcop@s95SjSeocvB0zXZSg/Zzh68XbzHHz9Kz8a@ZMTvbsy3oP@@Gu0DaTCupl5d9GtRwfAJeVQFq4cKipRRdokbk6209/@KrBZvMP)
```
object Main {
def main(args: Array[String]): Unit = {
val f: (Seq[Byte], Seq[Byte]) => Boolean = (a, b) => {
a.zip(b).foldLeft(Seq[(Int, Int)]((0,0))) { (c, de) =>
c.flatMap { f =>
Seq((f._1 + de._1, f._2 + de._2), (f._1 + de._2, f._2 + de._1))
}.filter(g => g._1 >= 0 && g._2 >= 0)
}.exists(_ == (0, 0))
}
val testCases = Seq(
(Seq(1.toByte), Seq((-1).toByte), false),
(Seq(1.toByte, (-1).toByte), Seq(1.toByte, (-1).toByte), true),
(Seq(1.toByte, 1.toByte, 1.toByte, (-1).toByte, (-1).toByte, (-1).toByte), Seq(1.toByte, (-1).toByte, 1.toByte, (-1).toByte, 1.toByte, (-1).toByte), true),
(Seq(1.toByte, (-1).toByte, 1.toByte, (-1).toByte, (-1).toByte, (-1).toByte), Seq(1.toByte, 1.toByte, 1.toByte, (-1).toByte, 1.toByte, (-1).toByte), true),
(Seq((-1).toByte, (-1).toByte, (-1).toByte, 1.toByte, 1.toByte, 1.toByte), Seq(1.toByte, 1.toByte, 1.toByte, (-1).toByte, (-1).toByte, (-1).toByte), false),
(Seq.fill(6)((-1).toByte), Seq.fill(6)((-1).toByte), false),
(Seq.fill(7)((-1).toByte), Seq.fill(7)((-1).toByte), false),
(Seq(1.toByte) ++ Seq.fill(6)((-1).toByte), Seq.fill(6)(1.toByte) ++ Seq((-1).toByte), false)
)
for (testCase <- testCases) {
println(s"${testCase._1} ${testCase._2} expected: ${testCase._3}, got: ${f(testCase._1, testCase._2)}")
}
}
}
```
[Answer]
Oops, this doesn't work. Currently being kept as a placeholder.
# [C (gcc)](https://gcc.gnu.org/), ~~92~~ ~~91~~ 90 bytes
```
c;i;r;t(a,b,l)int*a,*b;{for(c=i=0,r=!(l&1);i<l;c+=a[i]+b[i++])r&=c>0|a[i]>0&b[i]>0;r&=!c;}
```
[Try it online!](https://tio.run/##lVPbboIwGL73KX4lI62UDeoxqXC3J5h3jBgosDVhuCBLzBzPzuoJO2RESQl8x5Q/lJtvnFcVZ4LlrEABCUmKRVYMAzIM2S5Z54g7wrFI7vRRqtuYiUXKuOEEnvCN0BOG4eNcd7hr/ewp19LDw4NJss9ZWWki4@lXFMNiU0Ri/fju9rQoTkQWw/L5ZYm2GApUxJtC07aatrIJXAAlsBHf8TpRDRiezqzcKMYMPnP5kqDBQ/SaDQjkmPUkAR@ByABh2PVAXntm32KvbM8HB3Z2yRoCPQpmU6F1hECLSP8XR0ryuMz6vrKqPbW3zTr@s5/u2rFS2906ObeaSt9pXVnprZ81bWvtcNM73LPu7tYEvTMxb8z6hkBzNsqQpPdgPvz58jBdAFXBSAVjFUxUMFXBTAVzCcrqFw "C (gcc) – Try It Online")
Returns in boolean r, takes the length and arrays where `(` is 1 and `)` is -1.
Less golfed variation:
```
int retFlag;
int test (int* a, int* b, int length) {
int counter = 0;
retFlag = !(length & 1);
for (int i = 0; i < length; i++) {
retFlag &= counter > 0 || (a[i] > 0 && b[i] > 0);
counter += a[i] + b[i];
}
retFlag &= !counter;
}
```
# [C (gcc)](https://gcc.gnu.org/), ~~73~~ 71 bytes by @c--
```
c;r;t(a,b,l)int*a,*b;{for(c=r=l&1;l--;c+=*b+++*a++)r|=c<-*b**a;r=r<!c;}
```
[Try it online!](https://tio.run/##lZLbToMwGMfveYrPEU1bqIaOHZKCdz6Bu1OzQAElQTAFk0Xk2bE7YWVINlLS/Po/AF8Q9FWIthVc8goFdmhnOM0rEtgk5HVSSCR86Wc3Ds8o5cLySWhZFgksC8tvX3iUhIQEXPrSuxK8ac00F9lnFINXVlFa3L7dG2YUJ2kew@rhcYU2GD6kekCCJtfRcz6xoUJVXFamuTHNtaOwA2ZDmX7FRaIbMNwdT1ULxpgbaof3IM0BYagNUNf2ZJtx1s7TC/hQOw3vCWwv0L7CuogNAyL7X5xqyf2i3X1i1Xs675DV/fM@47WuVjveOju2Uq3vsE6s7NzPmg@1jrjZBe7FePdggl2YWPZmfUagPxttSMq7M@9@ewfzX2A6THVwdZjpMNdhocNSQdP@AA "C (gcc) – Try It Online")
=======================
Operating hypothesis (WRONG): The strings can be swapped into both being balanced if and only if their length is even and both `F(A, B)` and `F(B, A)` are balanced, where `F(X, Y) := {X[0], Y[0], X[1], Y[1], X[2], Y[2], ...}`.
Reset edit: Previous program relied on caller manually setting internal variables. 3 bytes saved by @c--
Edit R+1: -1 byte from moving stuff into the conveniently empty for loop declaration.
Edit R+2: -1 byte from moving stuff into the empty for loop body. Thanks @c--
Edit R+3: c-- saved two bytes
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ZŒpÄṂȯṪƊ€oṚ$Ạ
```
A monadic Link that accepts a pair of lists of \$\{1,-1\}\$ representing `(` and `)` respectively and yields \$0\$ if balancable or \$1\$ if not (i.e. outputs the inverse).
**[Try it online!](https://tio.run/##y0rNyan8/z/q6KSCwy0PdzadWP9w56pjXY@a1uQ/3DlL5eGuBf///4@ONtRR0AViKAXBsToK0RAxZNnYWAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z/q6KSCwy0PdzadWP9w56pjXY@a1uQ/3DlL5eGuBf8f7t5yaOvDHZv8dbUeNcxJS8wpTn3UMBfILCkqBbEOt9tbA3kKNroKQJ61ZuT//xoKmlwamgoaQFJDQ1MTxAJBLhAB4mmAeUAmkKUAUQLigeQgFJQH44J0QvgaYAA2SQNkqgYA "Jelly – Try It Online").
### How?
```
ZŒpÄṂȯṪƊ€oṚ$Ạ - Link: pair of lists of -1 and 1 := ) and ( respectively
Z - transpose
Œp - Cartesian product
Ä - cumulative sums (vectorises)
Ɗ€ - for each: last three links as a monad:
Ṫ - tail
Ṃ - minimum (of the rest)
ȯ - {minimum} logical OR {tail}
$ - last two links as a monad:
Ṛ - reverse
o - logical OR (vectorises)
Ạ - all?
```
[Answer]
## [C89](https://en.wikipedia.org/wiki/C89_(C_version)), ~~79~~ ~~77~~ 69 bytes
```
r,c;f(*a,*b){for(c=r=1;*a&0<c;++a)c+=*a^*b++?r=-r:*a;return c==1==r;}
```
Using `(int)1` as `'('` and `(int)-1` as `')'`
```
int diff;
int count;
int check(int *a, int *b)
{
for ( c=1, r=1; *a!=0 && 0<c; ++a, ++b )
{
c += (*a != *b) ? (r=-r) : *a;
}
return (c==1) == r;
}
```
The logic is based on the consideration that if a solution exists, it will get a count on the nodes of different values lower than what it would get by alternating between `'('` and `')'`, so that would also be a solution
[Answer]
# [Haskell](https://www.haskell.org), 139 bytes
```
g=(\c->all(>=0) c&&last c==0).scanl(+)0
o j k=any(\(d,e)->g d&&g e).foldr(\(x,y)h->concat[[(x:a,y:b),(y:a,x:b)]|(a,b)<-h])[([],[])]$zip j k
```
`foldr(\(x,y)h->concat[[(x:a,y:b),(y:a,x:b)]|(a,b)<-h])[([],[])]$zip j k` gives a list of all possible pairs. `o` then uses `g`, which determines if a string is balanced, to get the final result. Input is taken as a sequence, with 1 representing `'('` and −1 representing `')'`.
[Attempt This Online!](https://ato.pxeger.com/run?1=hZK9boNADMfVlaewUERslYuSrYp6jF27dCMM5iNAcwECRIKqY7c-QpcsVZ-pfZpeQIgMafFJ5_-df2f5ZH98JVztIqVOp89jvRV33--xxE0gHFYKHbkkCCxLcVVDIPVpUQWcKbylpZHDM-wkZy1uMLQjEk4MoWXFENFim6uw1PeN3VIinCDPAq5dF5s12-3aJxtbrRqtvFdk26d7kXjkouvZrkfe7CUtztn7kn5u3g4wx7lcGdrTXIJYGXVU1Y_A4IOEHHDPBRyAaVA-GXtOMx0McwOgKNOshhn0r0w0wSQTpIQHVlV0BdDRbtPIU3m8RiAS9dR5_UfSQOIEqTHNmGPyvwukzsxRTKEjO_HxAcbOLuC-GcOc_AI)
[Answer]
# [Haskell](https://www.haskell.org), ~~77~~ 73 bytes
```
o a b=all(<1)$scanr(%)0$3:zipWith(+)a b
3%c= -c
0%c=c+1-2*mod c 2
n%c=c+n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZGxasMwEIbpqqc4RIzvSAwRWUKoOmbrFuisyCoxUWTHViCUvkmXLKXP1D5NZRnVbbEEutP__boT0tvHQXVHY-3t9n7xz8X687EGBXuprMV7QbNOK9diRsvZavNSNU-VP-CcgoOtMi2h0GyZ6de6LEFLXYh-J_VcMBejG4p-3T2cIcdcChYi5eGcYN50vm8F5toY7U0JEpq2ch6wBjypBs6gKGV7WvwYiZ1U5YK9rBlArMORAycOW2U7M4pBicuuvfxSEYkG0s__lBLFCRpQ0PlY5G9DioOPyRQe-cSFkwHjSIbhGdMffQM)
The other Haskell entry sets the precedent that `(`=`1` and `)`=`-1`. The right-to-left running totals of `A` and `B` are to stay `<1` (and end `>-1`, as checked by `3%`). `A+B` has all information we need. Wlog the running total of `A-B` stays in `[0,2]`. `scanr(%)0` maps `A+B` to the running total of `A+B + (A-B)/2`.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 8 bytes
```
Ťᵐ↕∫Ɔž∑≤
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6FluPLnm4dcKjtqmPOlYfazu671HHxEedS5YUJyUXQ1UsuPk-OlrXMFYn2jA2lgvE1AFxwBSUD0FgCJXRgRNwPWhKdNHVQGRhMqiKUNXATEHmocmiyyO7A1mJLsJGmGWxsRB_AwA)
Takes input as a list of lists of `-1` and `1` representing `(` and `)` respectively. For example, `[[-1,1,1,1],[-1,-1,-1,1]]` represents `())) ((()`.
```
Ťᵐ↕∫Ɔž∑≤
Ť Transpose
ᵐ↕ Non-deterministically permute each inner list
∫ Cumulative sum
Ɔ Split into the last element and the rest
ž Check if the last element is all 0s
∑ Sum; since the last element is all 0s, this will be 0
≤ Is the rest less than or equal to this sum (0)?
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 144 bytes
```
|^
$&#
+%`^(((\()|(?<-3>\)))*)#(.)(.* ((\()|(?<-7>\)))*)#(.)
$1$4#$5$8#$'¶$1$8#$5$4#
G`^((\()|(?<-2>\)))*(?(2)$)# ((\()|(?<-4>\)))*(?(4)$)#$
^.
```
[Try it online!](https://tio.run/##TYwxDsIwDEV3nyJSXPguohIliA6Ijr1EFZWBgYUBMfZcHICLBbuh0ERy/tPL9@P6vN0vqUA3JDdG4pWnTTFEAD1kRHva7s@9iJTiUQmq0v3NcWGIdxw8H7jxvH6/lBqj4KmzbXOlzhW0qIXFL5aFnwlmmGKVEpwQxEEnoFqTXbJhhIk0anL5i5G5/HxpRmtmxnTkAw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
|^
$&#
```
Place markers at the start of each string to determine progress through them.
```
^(((\()|(?<-3>\)))*)#(.)(.* ((\()|(?<-7>\)))*)#(.)
$1$4#$5$8#$'¶$1$8#$5$4#
```
If the current prefix of both strings is a validly balanced prefix, then progress through the string, generating results with and without a swap of the next character. Testing of balanced prefixes is unsurprisingly performed using .NET's balancing groups.
```
+%`
```
Repeat the above separately on each intermediate result until no new results can be obtained.
```
G`^((\()|(?<-2>\)))*(?(2)$)# ((\()|(?<-4>\)))*(?(4)$)#$
```
Keep only those results that progressed through the whole string and also are completely balanced rather than simply a balanced prefix (using conditional regex to enforce that the balancing group is now empty).
```
^.
```
Check that we had at least one result.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
∧⁼№⁺θη(Lθ⬤θ›№⁺…θ⊕κ…η⊕κ(|κ¹
```
[Try it online!](https://tio.run/##ZY3BCgIhEIZfRfY0gh06d9okIgjaVxB3SNlJ21GLnt70UkH/YfiYj5/fOsM2Gqp1Yh8yjGGGw1oMJdCxtMdEJcGqhJNKDDC0e8ZwzQ5W2Xgk6vLIaDLyb0W/LKF28d79KVjGG4aMMyy997Xuz36G9j4/fcILw6LEVvbsagUJDQRAh7p50Bs "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for balanced, nothing if not. Explanation:
```
θ First input
⁺ Concatenated with
η Second input
№ Count of
) Literal string `)`
⁼ Equals
θ First input
L Length
∧ Logical And
θ First input
⬤ All characters satisfy
θ First input
… Truncated to length
κ Current index
⊕ Incremented
⁺ Concatenated with
η Second input
… Truncated to length
κ Current index
⊕ Incremented
№ Count of
( Literal string `(`
› Is greater than
κ Current index
| Bitwise Or
¹ Literal integer `1`
```
The idea here is that the strings can be balanced if the following two conditions hold:
1. Exactly half of all of the characters are `(`s.
2. For each prefix of both strings, there are more `(`s than the 0-indexed position of the last character of the prefix, plus 1 if that is even.
Examples:
```
1st 2nd (s Needed
```
Valid:
```
( ( 2 >1
() (( 3 >1
()) ((( 4 >3
())) ((() 4 >3
```
Invalid:
```
( ( 2 >1
(( () 3 >1
(() ()) 3 >3
(()) ())( 4 >3
```
[Answer]
# [Perl 5](https://www.perl.org/), 53 bytes
```
sub{y/(/#/for@_;((pop)&pop)=~/^(#((!?)(?1)*\3)\))+$/}
```
[Try it online!](https://tio.run/##XY5RbsIwEET/fYoJhLILRFap@EoJPUgEamksIgViJUEVQnD1NF4HKB1Ltud51zs2q4pFuz8hNFiirY9f55MmPdSmrD42MZEtLb@4bXnVaxoSBSum1StP0jdOmaehvrSx@tnlRUbvCeMMhU7bXbm3sVxtlR8ag8Eomi9qjL7Tw2CGcDNDEIQmSgi1LfIGY4w9noPVRbUERpTAfBZ1pohBYpvq2DkiZkfcelD2lJ5ohzqCvuX@IYvQH//wjT8F8IBEfx@c436icSHIRyPf3giSSD7vA7NUSumtWcL6Kff5vw "Perl 5 – Try It Online")
First (wrong) version is in editing history, this one seems to pass. Please tell if it fails some test.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 108 bytes
Brute forces all combinations of the two inputs until it finds one that is balanced. Input is an array containing two arrays of integers, where 1 represents `(` and -1 represents `)`.
```
->a{(v=0,1).product(*[v]*~-a[0].size).any?{i=-1;j=k=0;_1.all?{|n|(j+=a[n][i+=1])|(k+=a[1-n][i])>=0}&&j|k<1}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY1NbsMgEIX3nIJFFQ1OQaarSCnJprdwUYQbnPqnjhXjVK6hF-kmUttD5TYFnII08z5meO_r5zTk4-W7EM-_gyno6trQjZrgLNJ7Tlh3Ou6HFwNJdpbJJ1VZKllffmjCVDtup1JQvq5ELdL1jjPVNNvJthaqpVBZK7NyKbgkFurAnIYXSTYidYtFZetH7twt8-n9tWw0PmjTI6ywwHc71ndNadib6iZvnY9G9xFsblec5smDcwh3g-lxkSmJdLufvS7XI2CCgGDwFYCQoMJFoQSCSF56heeVQGE2txv9Y_g5M8QTGSJ6CzLn_gE)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 47 bytes
Input: array, 2(`[`), -2(`]`)
Output: integer, 0(balanced), truthy(not)
```
a=>b=>a.some((v,i)=>0<(S=v-b[i]?S^1:S-v),S=0)|S
```
[Try it online!](https://tio.run/##jZBNb4MwDIbv/ArvhC1B2vVIF1Ar9dZTOTKmBhY2Jr5EMlRp229n4aNru12WSLb8vParxG@iEypt80a7Vf0s@4z3gvsJ9wVTdSkROycn7i8fMOSdm0R5HIRP917oduSEfEmfYb8HDivrYKK7siwtlU6FksrURwuBwPUhE4WSFhLgWOr23VSIRAMZ7oXSRPGGGmQIzCM/hjQemNMvfOY3D5gAjudKODLd5iUSU02Ra7QfK5tYKRo8AffhNOMFYOCZGQoWROvLT1lWtzuRviJGwoHEARnTMPdhAaR1pTRszDIixpiIR9d0UE3gHGy0IYA9eHAwluf@7dyf/LN/Z/rlpA/7ss9KXUhW1C9odA53GQ6em5jGvI3JgT/ImH7Ruv8G "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 52 bytes
```
a=>b=>!a.some((v,i)=>1<(S-=v-b[i]?j^=-2:v),S=j=1)==S
```
[Try it online!](https://tio.run/##jZBNb4MwDIbv/ArvhC1BqvbYzqBW6q2n9tgxNbCwUVFAJEOVpv12Fr7WdbsskWz5ee1Xic@ykTqps8r4Rfmi2pRbyUHMwYMUurwoxMbLiIP5Ix58bvz4mEXh@Zn9xbIh78BnnhPzod0Bw8LZ2@gvHMcobRKplbb1yUEg8ANIZa6VgwTYl6Z@txUiUUe6e6M0ULyjFlkC48i3IfUHxvQLT/zuAQPA/vwQTsLU2QVJ6CrPDLpPhUviIiu8AgdwHfEMMFzaGQpnRKvbT0Va1luZvCEepQexByqibu7DAUjKQhtY22UchRAy6l2TTrWBGVx0IYQdLGFvLaf@zdgf/7N/a/vVoHf7cielzJXIy1e0OkOKneU6oj5vIvL@Iuv5Sav2Cw "JavaScript (Node.js) – Try It Online")
```
1 if true
0 if some ")" mismatched, in which case S>1 so S!=0
|
a=>b=>!a.some((v,i)=>1<(S-=v-b[i]?j^=-2:v),S=j=1)==S
|
'-- If more ")" appeared
```
] |
[Question]
[
[UTF-9](https://datatracker.ietf.org/doc/html/rfc4042) was an April Fool's Day RFC joke specifications for encoding Unicode suitable for 9-bit nonet platforms.
# Challenge
Your task is to implement a program or a function or a subroutine that takes one integer, who represents the codepoint of a character, to return a sequence of integers that represents its corresponding UTF-9 value.
## Definition of UTF-9
In this problem, the definition of the UTF-9 shall be as follows:
From [section 3 of RFC 4042](https://datatracker.ietf.org/doc/html/rfc4042#section-3):
>
> A UTF-9 stream represents [ISO-10646] codepoints using 9 bit nonets.
> The low order 8-bits of a nonet is an octet, and the high order bit
> indicates continuation.
>
>
> UTF-9 does not use surrogates; consequently a UTF-16 value must be
> transformed into the UCS-4 equivalent, and U+D800 - U+DBFF are never
> transmitted in UTF-9.
>
>
> Octets of the [UNICODE] codepoint value are then copied into
> successive UTF-9 nonets, starting with the most-significant non-zero
> octet. All but the least significant octet have the continuation bit
> set in the associated nonet.
>
>
>
## Constraints
Input is nonnegative integers that is defined on Unicode: which is 0 to 0x7FFFFFFF (inclusive)
# Rules
* Standard loopholes apply.
* Standard I/O rules apply.
* Shortest code wins.
# Test cases
Leftmost column: Input in hexadecimal.
Right items: output as a sequence of octed integers.
```
0000 000
0041 101
00c0 300
0391 403 221
611b 541 033
10330 401 403 060
e0041 416 400 101
10fffd 420 777 375
345ecf1b 464 536 717 033
```
# ~~Hint~~ Notes
~~[Section 5.2 of RFC4042](https://datatracker.ietf.org/doc/html/rfc4042#section-5.2) has an example of the impmenentation.~~
Here is a non-competing Python function that represents the algorithm:
```
def ucs4utf9(x:int)->[int]:
l=[]
if x>0x100:
if x>0x10000:
if x>0x1000000:
l.append(0x100|(x>>24)&0xff)
l.append(0x100|(x>>16)&0xff)
l.append(0x100|(x>>8)&0xff)
l.append(x&0xff)
return l
```
[Test it online!](https://tio.run/##bZFBboMwEEX3PsWsClQ0GmMDSSRzhRwgzSIFW7GEAGEjUal3pwMkpJWysTXvf3@NZ7pvf2sbMU2VNjCUTg7eHMLxaBsffRRnui5HBrU6XxhYA2OBI0ck9Kda63/gjqDeXbtON1W48J9wLIpERm84GhOx1zrPnvoLeb@pmzg@SK/90DdQT147r4IgQJR8bgM4coZY4lIIRIbisCoSBSQJZxnnXwtI6QkKwTgduDr44sIMmX4kSp4RxCWYozGmmmGCkOc5iDxlQqa6NJQpMwmpyCDn@ZxLXTHT9lCDbWDuc@e62vow@GyCiIZm4/dW1XdIf7KKdhDamMbCoFXntdpHc4adM1raTNfPOCivTh@D2MYteU9qW6eNNkuv3VB7Mp2ezDrors7pinCr1CmafgE "Python 3 – Try It Online")
Those two programs were incorrect, as they convert codepoints 0x100, 0x10000, and 0x1000000 incorrectly; they should be converted to `257,0`, `257,256,0`, `257,256,256,0` respectively.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
b⁹+⁹_0¦⁹
```
[Try it online!](https://tio.run/##y0rNyan8/z/pUeNObSCONzi0DEj9///foMLQAAwA "Jelly – Try It Online")
## Explanation
```
b⁹+⁹_0¦⁹
b Convert to base
⁹ 256
+ Add
⁹ 256
¦ At index
0 last
_ subtract
⁹ 256
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~104 103~~ 97 bytes
```
def f(n):b=f'{0:08}{n:b}';l=len(b);return[256*(i<l-8)+int(b[i:i+8],2)for i in range(l%8or 8,l,8)]
```
[Try it online!](https://tio.run/##VZLPboMwDMbvPIW1aSJZ6eQQ/jVdd99pD1D1ADTZmGioaCoxIZ69S0JbbT6E@JfP9ieL44/56jS/XPZSgSKaimqjwhEFFtOoRTWF63bTSk0quu6lOfd6G6fZM2le22VBF402pNo2olkUuyimquuhgUZDX@pPSdqnwoIiaqOC7i6BkSdTlyd5gg1sMQIcEubO2t5tU3flK08yxir3Zci5F0rEWctQKbX30iSVtWLVLggeAW2AC/RJwnzCkPm0nt84@ld2lSbIXJ1DduwVcYhjV@QceJTaXtaFRd7MrdApMXPF8jYuYZnFeJ06G3U4RsjzHHieWnxzDUmWQMozyFnu@wfH3i0zfNfHs4F7fJzNv/wvtHvualO2IQ3c4k3tyH3JInDSuat6wGE0tXhdDRMs32A8mZ4oYmpKRYwTkDGMIHz57hpNDuWRtOWh2pcwCLD/wiCQd1MYzXo60Qd6@QU "Python 3 – Try It Online")
-1 thanks to Kevin Cruijssen
Explanation:
* The program converts the number to binary and left-pads it with 8 zeroes
* It takes each full chunk of 8 bytes (discarding additional zeroes at the start)
* The chunk is converted from a binary string to an int. 256 is added if it isn't the last chunk.
[Answer]
# [INTERCAL](http://www.catb.org/%7Eesr/intercal/), ~~164~~ ~~162~~ 154 bytes
I made this program before noticing the first comment of the OP. In my comment section the two example programs on both RFC document and my Python implementation says values 0x100, 0x10000, and 0x1000000 are converted incorrectly, while this program converts 256 to [257,0]; which seems to be correct.
```
DOWRITEIN:1DOCOMEFROM.3PLEASE.1<-!2$:1~#255'~#54613DOSTASH.1DO.2<-#128PLEASE:1<-:1~#65520$#65520(1)DO.3<-':1~:1'~#1(9)DORETRIEVE.1DOREADOUT.1PLEASE(9)NEXT
```
[Try it online!](https://tio.run/##TYzBTsMwDIbvfoqiTto4NJqTOkuqXirq0UisQWnYdkWIAxLigDjv1YurcuBk//4/fx9fP@/fb6@f89zHSwqZw9hgHx/iiY8pnpR5fuJuYoVtdac3Dd5KTbS9lVRbNH2ccjcNSh6UbqsStVvxRvCFtUR6v1nHDu8FM221laZBceDOyylxToHPvFgSd318yQpXjfQjX/M8xwE4PA65mAQci789XIt8if/TkJiLYzgzgCVAr8GjAV078mCtoSUfyHpAxBr3HtzBWe2k@QU "INTERCAL – Try It Online")
## Usage
* Input as INTERCAL-72 integer input (e.g. `ONE TWO THREE FOUR FIVE`).
* Outputs several integers as roman numbers, from first to last elements of the list.
## Ungolfed
```
DOWRITEIN:1
DONOTE from label (1) if .3 got at least one bit of one
DOCOMEFROM.3
DONOTE :1~#255 is done first on CLCI
PLEASENOTE obtain lowest 8 bits
DONOTE then do C operation such twospot[1]|spot[2]
DONOTE spot[2] is 256 if second time to visit here 0 otherwise
PLEASE.1<-!2$:1~#255'~#54613
PLEASENOTE this and RETRIEVE statements below
DOSTASH.1
DO.2<-#128
DONOTE like (twospot[1]>>8)
PLEASE:1<-:1~#65520$#65520
(1)DO.3<-':1~:1'~#1
PLEASENOTE finally, until no more .1 stacks
(9)DORETRIEVE.1
DOREADOUT.1
PLEASE(9)NEXT
```
### Algorithm
1. Write in to the codepoint.
2. Make a list from backward, using STASH and RETRIEVE statements and a stack.
3. Then output each item.
[Answer]
# JavaScript (ES6), 41 bytes
If returning an empty array for \$n=0\$ is not acceptable, this version returns `[0]` instead. Thanks to @tsh for pointing this out.
```
f=(n,q)=>n|!q?[...f(n>>8,256),n%256|q]:[]
```
[Try it online!](https://tio.run/##jZBBasMwEEX3PcV0EZDAVWYsS0oLdg/RZcjCcayQkozixJQucndXLd3JIM9GIPTfG/3P9qu9d7fTdXzhcOinydeCi0HWDT@eh/etUsoLbppNURorC17F4zHs3ra7qQt8D@dencNReIHfGAfiSHVpr4KhboDVGD7G24mPYiOlhPUa4qOnNFlRPklIM8lugVPPOfXrAmeFGsoy9VqifT5t4rdQ6yRN8RIXuOnPjzbdvv@vLEMgGwk42xyh9/6QJZQIzjnQziQEXZm@87TPEGwFRltw5H67mH4A "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 38 bytes
```
f=(n,q)=>n?[...f(n>>8,256),n%256|q]:[]
```
[Try it online!](https://tio.run/##jZBNi8IwEIbv/oq5CAl040zTJK7Q7o/wKB5qbYriTvwosof9790o3rIQcxkIPM878x7be3vrrofz@MFh30@TrwUXF1k3/LVRSnnBTbMsSmNlwfM4fi/b1WY7dYFv4dSrUxiEF/iDWBHEJ9V3exYMdQOsxrAerwcexFJKCYsFENIsJTvMkxoxJfXnG5kVaijLNNcS7fK0iWeh1glN8RPfyKZnPtp0@/5VWcZANhrw3@YIvff7rKFEcM6BdiYx6Mr0naddxmArMNqCI/foYvoD "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 51 bytes
```
f=function(x,s=0,b=256)c(if(x>=b)f(x%/%b,b),x%%b+s)
```
[Try it online!](https://tio.run/##XY7NCsMgEITveQ9B6UJ3/W0P9mG0EXIxEFPw7VMLJYnZyy473wyzbHnO41r8lnz65LhOc@YVikcIXhorIp8Sry8fRFvszgIEAZWxcCvi7@VYsY0Yyrqs88TbDQ8xnERNu0hIFzEeTnV1qufhjFyjAilJdIwlCifGaAJUqmeofbALIviFocUeHLuuDSTbQITW@pqYUnqfSYngnAPlTE8qbcaYuo7aajDKgiO3d92@ "R – Try It Online")
[Answer]
# Python 3.8, 81 bytes
```
def f(n):x=n.to_bytes(4,'big');return[i+256 for i in x.lstrip(b'\0')[:-1]]+[x[-1]]
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₁вā€₁¨+
```
Port of [*@xigoi*'s Jelly answer](https://codegolf.stackexchange.com/a/237337/52210).
I/O as integers.
[Try it online](https://tio.run/##MzBNTDJM/f//UVPjhU1HGg@teNS0BsjW/v/fzMzY1AgA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9TpuSZV1BaopBYrJCRWpGYkpqcmZuYY6UABEr2lbZcCOnMvJLU9NQisBRE2sNFh0vJv7QEVUGxFUz@/6OmxgubjjQeWvGoaQ2Qrf3fFkl5fnJJYo5CXmluEliPkr2F06OmFm2g0kPLHjXM01E4vPdRw7Low/tjdQ5ts/9vAARcBgYmhkAiGcgytjTkMjM0TOIyNDA2NuBKBUsZGqSlpaVwGZuYpiangeUMQBhGGhgAAA).
**Explanation:**
```
₁в # Convert the (implicit) input-integer to base-256 as list
ā # Push a list in the range [1,length] (without popping)
¨ # Remove the final item to make the range [1,length)
€₁ # Map each to 256
# (we now have a list of 256s of size length-1)
+ # Add the values at the same positions in the lists together
# (where the larger list keeps its trailing items as is)
# (after which this list is output implicitly as result)
```
In the new version of 05AB1E both `€₁` and `+` wouldn't work here. `€₁` will add a `256` before each item instead of replacing them (an alternative could be `Ā₁*`), and `+` will cause the final item to be removed, since it will adjust the list to the shortest. In 05AB1E it therefore requires a different approach, which would be 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead:
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₁в₁+`₁-)
```
[Try it online](https://tio.run/##yy9OTMpM/f//UVPjhU1AQjsBSOhq/v9vZmZsagQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaopBYrJCRWpGYkpqcmZuYY6UABEr2lbZcCOnMvJLU9NQisBRE2sNFh0vJv7QEVUGxFUz@/6OmxgubgIR2ApDQ1fxvi6Q6P7kkMUchrzQ3CaxFyd7C6VFTi/ajpjWHlj1qmKejcHjvo4Zl0Yf3x@oc2mb/3wAIuAwMTAyBRDKQZWxpyGVmaJjEZWhgbGzAlQqWMjRIS0tL4TI2MU1NTgPLGYAwjDQwAAA).
**Explanation:**
```
₁в # Convert the (implicit) input-integer to base-256 as list
₁+ # Add 256 to each
` # Pop and dump the contents of the list separated to the stack
₁- # Subtract 256 from the top item (the last item of the dumped list)
) # Wrap the entire stack into a list again
# (after which this list is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
I⮌E⮌∨↨N²⁵⁶⟦⁰⟧⁺ι∧κ²⁵⁶
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyi1LLWoOFXDN7EAzvYv0nBKBNKeeQWlJX6luUmpRRqaOgpGpmZAMtogVhNIBeSUFmtk6ig45qVoZEPkwMD6/38zM2NTo/@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. I/O is in decimal. Would have been 16 bytes if empty output was acceptable for an input of `0`. Explanation:
```
N Input as an integer
↨ ²⁵⁶ Converted to base 256 as a list
∨ Logical Or
⟦⁰⟧ List of literal `0`
⮌ Reversed i.e. LSB first
E Map over bytes
ι Current byte
⁺ Plus
κ Current index
∧ Logical And
²⁵⁶ Literal 256
⮌ Reversed i.e. MSB first again
I Cast to string
Implicitly print
```
Converting to groups of 8 bits also takes 20 bytes:
```
I⮌E⪪⮌⍘N²¦⁸⁺⍘⮌ι²∧κ²⁵⁶
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyi1LLWoOFXDN7FAI7ggJxMh4pRYnBpcAlSZruGZV1Ba4leam5RapKGpo2CkCSQsgDggp7QYWR1MayZYkY6CY16KRjaQaWqmCQbW//@bmRmbGv3XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. I/O is in decimal. Explanation:
```
N Input as an integer
⍘ ² Converted to base 2 as a string
⮌ Reversed i.e. LSB first
⪪ ⁸ Split into groups of up to 8 bits
E Map over bytes
ι Current byte
⮌ Reversed i.e. MSB first again
⍘ ² Converted from base 2
⁺ Plus
κ Current index
∧ Logical And
²⁵⁶ Literal 256
⮌ Reversed
I Cast to string
Implicitly print
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 71 bytes
```
.+
$*
+`(1+)\1
$+0
01
1
^
7$*0
r`.{8}
¶$&
1A`
.+¶
1$&
1
01
+`10
011
%`1
```
[Try it online!](https://tio.run/##FcsxDoJAFIThfs6xGOAlmzfALmxpZeUNjHkWFjYWxM54LQ7AxVZeM8mffLM@P6/3ozbtxWoUhB5iLaW7EUEUShB3zKFXrBa/yw/7Fk7g2RBl30APZ2J0TjTGeuzViM7Cwf2BqsgJLAMKRwzTkgpyHpP3nHIByYla/g "Retina 0.8.2 – Try It Online") Link includes test suite. I/O is in decimal. Explanation:
```
.+
$*
```
Convert to unary.
```
+`(1+)\1
$+0
01
1
```
Convert to binary.
```
^
7$*0
r`.{8}
¶$&
1A`
```
Split into bytes of 8 bits.
```
.+¶
1$&
```
Prefix a `1` to all bytes except the last.
```
1
01
+`10
011
```
Convert to unary.
```
%`1
```
Convert to decimal.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~62~~ 42 bytes
```
f=->n,w=0{w+=n%z=256;n<z ?[w]:f[n/z,z]<<w}
```
[Try it online!](https://tio.run/##PU/LboNADLznK6xEnEobm32pKbQfgjgUyt5Co0gRlIRvJ7aB@rDrGc/4cb3Vf/Mci9fPLu0LvPcvRZeMReb8R5eP8FX21SmW3XFMxyrP@2kuMQUcLMnbcM5KSc27Mp6olp/QGBW2iIuWMMb4o1Lr2iZSXb2dvy/3x/CAC8Ry@If75HefDNO02x0AOUACFVhSQEgKm6VmUKu0Si2S@ITirVbKQJaJSRZUynEvXpIp3XUzihK9mNttnCXPNK5TlzuEzhBCCGCCY3o7Cqy34IyHQEH6z08 "Ruby – Try It Online")
[Answer]
## Perl 5, 59 bytes
```
sub{my@o;do{unshift@o,$_[0]%256|256*!!@o}while$_[0]>>=8;@o}
```
* `do`-`while` loop to make sure that 0 outputs `(0)` and not `()`
* `unshift` pushes onto the array backwards
* `!!@o` is 0 if the output is empty (this will be the last nonet) or 1 otherwise
* consumes its input
* could lose `my@o;` for -5 points under the old-school Perl golf rules.
[TIO](https://tio.run/##PY7tqoJAEIb/z1WMZmBhMetmFFvifRwOkbaLRrpLq5RY126bB84D8/W8f8bI@y0ZZ55xEzorMVkTiwXUPQZdq/Z4HG2XD3WfaXHRQ9fYslJtpqPg9EO/8zjZvlwtPS/T70dZ3eTk0/S4E86MAtAxBRge0gUOk/hSlLo24v@05x6vumrQRz/C@mzQmnvVtCr058S1c8FpEf09tUrDUj6/QsB7JAcQbZhrhdv4nsGWsRwYcU4gp4iRUuoCfJPIQrH8Aw).
[Answer]
# [Rust](https://www.rust-lang.org/), 93 bytes
```
|n|(0..4).rev().map(|i|n>>i*8&255|(i>0)as i32*256).skip_while(|&n|n==256).collect::<Vec<_>>()
```
[Try it online!](https://tio.run/##bVHLbtswELzrKzY@OGSgEqSeKR2rQD@hh16KQFBlCiUi0ypJOQEsf7vLR5z4UAogxdnZ2eGuno29zEaAsTvO5YHz7/PwQ3S7TTIo2HdSIQwnGIWFYXtZ1IIoIQUmWhwRJvtuQotcVNPIh8d1VpYLkg3FnQGZZw9ZWWFiXuTUvv6Ro0DLWi1quw1wfxhH0VvOn36K/qltGoQvruRBwyiVAKk@Dbkf74KMh/7FHy5uvKkEgi2kUhBvkxMTOwxbmDptRCvVNFu09mQyq1ftjGK8eU/RwsyjddwBqQBOWio7qju0Op3hSwMn/u28SsEpR2ogdcYIbVvx9w5F9KbuJjm7z7fstryvzmFtrMZeFbmmpP657mziA6Kf/Wx9njUcYjecteDcTKO06B7uPxqGghWIdDcF6ye0HJfj3Xa9Wr0HUdj9cpU4H/Rh3zoTre528g2F1F/0mVgt9winzI3j2qL0IzOyGCHPRFqhr8M@Lv@TPKaPnxo3XqMcTs4X6lbQdWdCacHChVHmLn2M5D6Sf42RguaQZSypGPsdgNKl0DxPmNtoZLDAohVNxFWxYJUDaRBmdBiGnQczCnVdQ16XSV6Uoh@cZlEVUOYV1Kz2uv8A "Rust – Try It Online")
### Ungolfed
```
|n| {
(0..4).rev() // Iterator over integers from 3 down to 0
.map(|i|
(n >> i*8) & 255 // Extract the i'th octet from n
| ((i > 0) as i32) * 256 // Set the continuation bit if not the last byte
)
.skip_while(|&n| n == 256) // Remove 0x100 bytes at the start
.collect::<Vec<_>>() // Evaluate into a vector
}
```
] |
[Question]
[
Tom is going to implement a new programming language of his invention. But before actually starting working on it, he wants to know whether his language should be case sensitive or not.
On one hand, case insensitivity seems more easy to implement to him, but he worries that it could cause a lack in the possibilities of combinations of characters that form a variable, meaning that longer variable names should then be used to avoid naming clashes (for an example, you can use `Hello`, `HEllo`, `heLLo` and a bunch of other possibilities if the language is case sensitive, but only `HELLO` if not).
But Tom is a meticulous person, so just a worry isn't enough for him. He wants to know the numbers.
# The challenge
Write a function (or a full program if your language doesn't support them) that, given an integer `n` as the input, outputs (or returns) the difference in the number of permutations possible for a string of length `n` with case sensitivity and without.
In Tom's language, variable names can include all alphabet letters, underscores and, starting from the second character, digits.
# Testcases
```
Input (length of the variable) -> Output (difference between the possibilities with case sensitivity and the possibilities with case insensitivity)
0 -> 0
1 -> 26
2 -> 2340
5 -> 784304586
8 -> 206202813193260
9 -> 13057419408922746
```
# Non-competing C++ reference implementation
```
void diff(int n) {
long long total[2] = {0, 0}; //array holding the result for case insensivity ([0]) and case sensitivity ([1])
for (int c = 1; c <= 2; c ++) //1 = insensitivity, 2 = sensitivity
for (int l = 1; l <= n; l ++) //each character of the name
if (l == 1)
total[c - 1] = 26 * c + 1; //first character can't be a number
else
total[c - 1] *= 26 * c + 1 + 10; //starting from the second character, characters can include numbers
std::cout << total[1] - total[0] << std::endl;
}
```
# Scoring
Tom likes golf, so the shortest program in bytes wins.
# Note
It's okay if maybe the last two testcases aren't right because of numerical precision. After all, I am not even sure *my* code handled number 9 correctly.
[Answer]
## JavaScript (ES7), 43 bytes
```
f=(n,a=53,b=27)=>n?--n?f(n,a*63,b*37):a-b:0
```
```
<input type=number value=0 min=0 max=9 style=width:4ch oninput=o.textContent=f(+this.value)><div id=o>0</div>
```
Not `reduce`s day today - 55 bytes.
[Answer]
# TSQL, 41 bytes
```
DECLARE @ INT=10
PRINT 53*POWER(63.,@-1)-27*POWER(37.,@-1)
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/510256/is-case-sensitivity-important)**
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“~J“6j”OH*"’ÆḊḞ
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCcfkrigJw2auKAnU9IKiLigJnDhuG4iuG4ng&input=&args=Mg) or [verify all test cases](http://jelly.tryitonline.net/#code=4oCcfkrigJw2auKAnU9IKiLigJnDhuG4iuG4ngrFvMOH4oKsRw&input=&args=MCwgMSwgMiwgNSwgOCwgOQ).
### How it works
```
“~J“6j”OH*"’ÆḊḞ Main link. Argument: n
“~J“6j” Yield ['~J', '6j'].
O Ordinal; replace the characters with it code points.
This yields [[126, 74], [54, 106]].
H Halve, yielding [[63, 37], [27, 53]].
’ Yield n-1.
*" Exponentiation (zipwith); elevate 63 and 37 to the power n-1.
ÆḊ Take the determinant of the matrix
[[63 ** (n-1), 37 ** (n-1)], [27, 53]], thus yielding
63 ** (n-1) * 53 - 37 ** (n-1) * 27.
Ḟ Floor; round the result down to the nearest integer.
This is required for n = 0.
```
[Answer]
# Java, ~~77~~ 76 Bytes
~~O(1) solution, no loop involved~~
```
long x(long n){return 53*(long)Math.pow(63,n-1)-27*(long)Math.pow(37,n-1);}
```
[Answer]
# JavaScript (ES6) 47
```
n=>n&&eval("for(a=53,b=27;--n;a*=63)b*=37;a-b")
```
Note: the values are correct up to the 53 bits of precision of javascript numbers.
**Test**
```
F=n=>n&&eval("for(a=53,b=27;--n;a*=63)b*=37;a-b")
for(i=0;i<=10;i++)O.textContent+=i+' '+F(i)+'\n'
```
```
<pre id=O></pre>
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~17~~ 16 bytes
```
37iqY"27vt26+hpd
```
[**Try it online!**](http://matl.tryitonline.net/#code=MzdpcVkiMjd2dDI2K2hwZA&input=NQ)
Last test case (input 9) is not exact due to numerical precision.
### Explanation
```
37 % Push number 37
iq % Input number n and subtract 1
Y" % Row array [37 ...37] of size n-1
27v % Concatenate 27 vertically. Gives column array [37; ... 37; 27]
t26+ % Duplicate and add 26. Gives column array [63; ... 63; 53]
h % Concatenate horizontallty. Gives 2D array [37 63; ... 37 63; 27 53]
p % Product of each column
d % Difference of the two values. Implicitly display
```
[Answer]
# Python 3, 36 bytes
```
lambda n:n and 53*63**~-n-27*37**~-n
```
An anonymous function that takes input via argument and returns the output.
Hooray for operator precedence!
**How it works**
```
lambda n: Function with input string length n
n and ... Base case: return 0 if n=0
(Case sensitive)
53*... The first character can be any of [a-z], [A-Z] and _ , giving 53 possibilities
...63**~-n 63^(n-1): the remaining n-1 characters can be any of above and [0-9], giving
63 possibilities
(Case insensitive)
27*... The first character can be any of [A-Z] and _ , giving 27 possibilities
...37**~-n 37^(n-1): the remaining n-1 characters can be any of above and [0-9], giving
37 possibilities
...-... Subtract the case insensitive value from the case sensitive value
:... Return the above
```
[Try it on Ideone](https://ideone.com/Ytonbd)
[Answer]
## Pyth, 16 bytes
```
L*b^+TbtQ-y53y27
```
[Try it here!](https://pyth.herokuapp.com/?code=L%2ab%5E%2BTbtQ-y53y27&input=2&debug=0)
Works the same as my Pyke answer
[Answer]
# [Factor](http://factorcode.org), 54 bytes
```
[ 1 - [ 63 swap ^ 53 * ] [ 37 swap ^ 27 * ] bi - ⌊ ]
```
Test output (too lazy to make a test suite right now)
[](https://i.stack.imgur.com/Hs3D5.png)
To 100 because I can:
```
0 0
1 26
2 2340
3 173394
4 11884860
5 784304586
6 50726849940
7 3244471004034
8 206202813193260
9 13057419408922746
10 825083183338785540
11 52071473691679633074
12 3283878468805254213660
13 207009241705220196670506
14 13046203459736972095009140
15 822081803558828931061964514
16 51797480091236011152730146060
17 3263475325027970876967575323866
18 205607606410125945699743561920740
19 12953599658372394455762938112142354
20 816088635295235866150191568376990460
21 51414022725857535138635748098295218826
22 3239099663712558709867478263942757120340
23 204063879397281956578587897577149556950594
24 12856046623614221305157697924464388847546860
25 809931759486357889731081403194103267502851386
26 51025731268991039110785546457483836346653407940
27 3214622195536403670115403894902928918116194213234
28 202521239965622254844299280697898069287570327415260
29 12758839658766868529390921590771079620628184030477546
30 803806955516821376897030535770307562553491969842783540
31 50639840307096567147692815348943369659664900009235194274
32 3190310017399946085222303356013750037654300219219990995660
33 200989533984152510500958383022988009088751140000471861713306
34 12662340747855976725442649179430749571102940189045387160447140
35 797727471068538170566530927116489907924415111563438806390997714
36 50256830823601535309646277474395913542200557575679083168097488060
37 3166180347299391055374044156331053378848244132513532459112333134666
38 199469362080123926730618942840288463417954913542445303046398068798740
39 12566569818457512122984997355621160915700234281355486142448958342967554
40 791693898836982339089426979801403683342770524668108612843741935926892460
41 49876715636873773150264669144187442239779806356971223086325671695231877626
42 3142233085498371482609012624501672238105982542695761132093804716877601438340
43 197960684400284383047634318675066295949671525651476192195155330966174637087794
44 12471523117731734378801823439793231607942107258123800020604874301575774756008860
45 785705956436110540996146747147743624935526399518788998053580353675424396549238186
46 49499475256178381262627624276616339615439587933192321957328073370569308698667165940
47 3118466941165264455200744360060243571819246756040935041269911532639516601510442382434
48 196463417294374638796889443817231669538334996131822201644459414237154601574451074437260
49 12377195289581232434616009278422739187922835424850800583245777641132746959324266250272346
50 779763303244935960426051634304306897098424666501802506291342869526467319662381170513981540
51 49125088104479743237515245802427284662794337274853034469588379271166298804053252422013315474
52 3094880550584028599998398220679389089143005829869601804793717698250434558272314733733240577660
53 194977474686860578513191784102480908365326982799277757130761257743954813314983341977611019396106
54 12283580905274687184722912157844434869740351690501733906101969819773718376165568553428918153085140
55 773865597032396709958041167041560489574457972145056938738392490176213167779330685193080529096190914
56 48753532613044375168215008464220671276081037423946152138715557367728779243091128221265244694777630060
57 3071472554621920785909306886048189626410042209324487489672362842172125030215492994941453756154541985466
58 193502770941185640073821503874720577896459322697230268331890319993036718605903879610376090231927542876740
59 12190674569294866655427556036093727770484123879787646494762754214200448415158073789829080317596516919552754
60 768012497865582938530677678077399109971765706771520893994639085516276250445445435611121365429028589509594460
61 48384787365531959679266134687605431564178077913367085420171928478326379788811073557020550322585378011481976426
62 3048241604028522138211603801162125831073621928852293338115689139494198039092774045292531129443472159001332956340
63 192039221053797215808791020159404322131263093269170657697148148666441012621558792067838210142400699755368808584994
64 12098470926389236476707853555431516900893696610762369998567143482483125633030622907206930951507336372904773737270860
65 762203668362522337620493487551580215201395390665800196764662013706838562882208746410562227308797606160712680915464986
66 48018831106838923534843342117447155624156332266892935209806189913015690437626492644356866682916159530830240509968123940
67 3025186359730852784490963892261982080781180571047313262322191837350928353684220676552666116434808733122402791782863511634
68 190586740663043747689376558750428888318209646590603894258160955047853260958314713301270755405603305445874988549550654259260
69 12006964661771756928289219042180208601520032747949102211343066331920312103393552933082810823150791387679177947309210580307146
70 756438773691620716964985145770771121482256588592212543618533446975485259045523696603018951464617833773583196421918482952379540
71 47655642742572106296656344989755045898082462523751897107212657077842278391541997773285863117697288652678155847014078432541996674
72 3002305492782042738420254124183837105633106144366742271546464242884371700319084040546949135905704694741593153841915859492202959660
73 189145246045268694064519472247264698574880394293808554997733720639986819101224007245165566663218089624766534104801769122964901718906
74 11916150500851927783194334861253945564257269006861979264798563913835211476678615826001618230525611319033999768874671043820165072923140
75 750717481553671452455038596317020544047680701587330184780139088571711872342908421711680887160599764988069185889174180556385321385544114
76 47295201337881301582877865070119107294484376103737744811768456374021309282152988680758316620704776514138665127670559852493727353570572060
77 2979597684286522002615091538996935841273293894973707820454341421941470553783979337065903514099119599226677240459390970372438551207353876266
78 187714654110050886271820850421245945023886308799558098889201870386303383441699317091742715367049125868210495633339022021080976659562384154740
79 11826023208933205839086306664722737056380582810772096959441117184084770483299475874473650445339864801023664915823061850169943403091896529897954
80 745039462162791968009016264140349407787379295265439767433382158538003861527346479306512775013394967703567826260992924685854583715749735525096460
81 46937486116255893989991445578566240700314790994634218730880971697698786156163569667253198313252271919170619707315735295839320298967762741317515226
82 2957061625324121321570127646145469600479097962199681775200883358217791614396112323461838552769003522200045367717199022141204995255363640622751674340
83 186294882395419643266342704970909052975476018411475813658404790794443290909593951451816650008709306376417822233966923239519043908642509112264039442194
84 11736577590911437526054302953925815658830824491260123147847219971438656837802057319192119334366383427393476471247901403340755546923998264934769791332860
85 739404388227420564151585450105392563397247850208862193146980429802018372669942231085027322266336949575917703497413242262756663341354137752789503193531786
86 46582476458327495541925964824938180038990133131758872257066173226778328178077627497465902058225655188337576695262466055088365154255573819716001935756281940
87 2934696016874632219155250798298147938620028574339029453481005940809327991114127409087391517619734089372293502673776337794350733176860886869847861631505600834
88 184885849063101829807295655822883896191116857103773014116879344289312516128313791212146134064249406693214458990720825405024094143116346113226785650902666881260
89 11647808490975415277878675971455406774188399103593023755623709580904708065544348130631903778853340506994629744339509897103777855276371884029063199627227132581946
90 733811934931451162507061423422398315397346516450407479655925206552083331459335365747677739381568683697580070526580745691266622080032985612974682610468596757977540
91 46230151900681423237970948652777278349101493334565409591233653622119458645149661082264806229649731647953525118602676998977756027354075699625721942715793229749237874
92 2912499569742929663993134687280117361718934603610641124045403705739039618883255370668643812466536563096293367462807981691433106666850680498728209106577023932078141660
93 183487472893804568831603187418387900340137879398192142647374723980743503786481677084105117925340131838249669694817958084526161366922717594045263062187188374662340681706
94 11559710792309687836392321785788836463846951378802809804587636359996649027031299439381903065674516455247507129925990403129885565051842823161990850791287794680559919961140
95 728261779915510333692765148706621450691833741003095095947733154400551795376841154655141276683483798209790732933978380017958074358887427604479576881170443366718075867057314
96 45880492134677151022646012787988367271956130436320159940279535084902990655674156472314911622261081963797134173540354372100044183752897139657357014922552487271422413276314060
97 2890471004484660514426765717163702125632948593353801325373787525582612830543998915730356846276907462752691218884931833388144147044723120219693807782246945239322406481520807066
98 182099673282533612408888715907569328452365119288317839716587156275352411836023432836069625636200164217658002129970617297449211712144308789428081576440224676102555002804992632740
99 11472279416799617581760080704048343190386108757724073082212416905402170675604281811039500754948545126089276981776285626117157164453181285710701891703604838257394970772074262003154
100 722753603258375907650888473624290214416147782711338423841877029262370595570657559163071778136871929817566895212667053691361603944309744782913331015678320105744441365668988373398460
```
[Answer]
# dc, 19 bytes
```
1-d63r^53*r37r^27*-
```
This is just a difference of two exponentials, `53 × 63^(n-1) - 27 × 37^(n-1)`. The special case of zero falls out naturally, as `dc` starts with a precision of `0`, meaning that *x*^-1 == `0` for all positive *x*.
As normal for `dc`, input is taken from top of stack, and output is pushed to top of stack. For a full program, enclose between `?` and `p` to make a pipeline filter.
## Test output
```
$ for i in {0..30}; do printf '%2d -> %s\n' "$i" `./85108.dc <<<$i`; done
0 -> 0
1 -> 26
2 -> 2340
3 -> 173394
4 -> 11884860
5 -> 784304586
6 -> 50726849940
7 -> 3244471004034
8 -> 206202813193260
9 -> 13057419408922746
10 -> 825083183338785540
11 -> 52071473691679633074
12 -> 3283878468805254213660
13 -> 207009241705220196670506
14 -> 13046203459736972095009140
15 -> 822081803558828931061964514
16 -> 51797480091236011152730146060
17 -> 3263475325027970876967575323866
18 -> 205607606410125945699743561920740
19 -> 12953599658372394455762938112142354
20 -> 816088635295235866150191568376990460
21 -> 51414022725857535138635748098295218826
22 -> 3239099663712558709867478263942757120340
23 -> 204063879397281956578587897577149556950594
24 -> 12856046623614221305157697924464388847546860
25 -> 809931759486357889731081403194103267502851386
26 -> 51025731268991039110785546457483836346653407940
27 -> 3214622195536403670115403894902928918116194213234
28 -> 202521239965622254844299280697898069287570327415260
29 -> 12758839658766868529390921590771079620628184030477546
30 -> 803806955516821376897030535770307562553491969842783540
```
Performance is reasonable for small *n*, but does start to tail off once it reaches a few hundred thousand or so:
```
1024: 0.00s
2048: 0.00s
4096: 0.01s
8192: 0.04s
16384: 0.12s
32768: 0.38s
65536: 1.16s
131072: 3.48s
262144: 10.41s
524288: 30.63s
1048576: 93.70s
```
That last example does produce a 1941435-digit result, so maybe it's not too bad for all that.
[Answer]
## Pyke, ~~17~~ 15 bytes
```
53[DT+Qt^*)27[-
```
[Try it here!](http://pyke.catbus.co.uk/?code=53%5BDT%2BQt%5E%2a%2927%5B-&input=2)
```
[DT+Qt^*) - [ = lambda a: a*(a+10)^(input-1)
53[ 27[- - [53)-[27)
```
] |
[Question]
[
**Objective** Given an input of text that does not contain characters `[` or `]`, perform the following actions:
1. For every instance of `Amen` with at least one capital letter (so all instances of `Amen` excluding `amen`), output that same `Amen` (retain capitalization).
2. For every instance of `/all the people said[?: ]/i` (that's a Regular Expression), also output `Amen` (any case is fine.)
After every output, you may choose any *constant* separator, e.g. a newline, space, or nothing.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins.
# Example IOs
```
Input: I said AMEN! AMEN, PEOPLE!
Output: AMENAMEN ; any separator is fine, I choose none.
Input: amen amen amen amen
Output: ; nothing
Input: ; empty
Output: ; nothing
Input: *blah blah blah* And all the people said?
Output: Amen
Input: all the people said:
Output: Amen
Input: AMEN AMeN AmeN aMEN amen AmEn
Output: AMEN AMeN AmeN aMEN AmEn
Input: All the people said Amen! And all the people said AMEN!
Output: Amen Amen Amen AMEN
Input: LAMEN! Amen.
Output: AMEN Amen
Input: AmenAmenAmenAmenAMENamen
Output: Amen Amen Amen Amen AMEN
Input: And he was like, "Amen", then we were all like, "Amen, bruh."
Output: Amen Amen
Input: And all the aMen people said.
Output: aMen
```
## Bonus
* **-20 bytes** if you can "grab" the punctuation that follows the `Amen`, i.e., `Amen! => Amen!`, `AmEN. => AmEN.`, `I said Amen, bruh. => Amen,`, and `AMEN!!!! => AMEN!!!!`. `!` is the only character to be preserved multiple times. `.?!,` are the only characters to be preserved thus.
* **-40 bytes** if, there is an instance of `amen`, output, `Heresy! at index [i]` instead of nothing, where `[i]` is the index of the offending word i.e. `amen`.
### Bonus IOs
Input and output is of the form `input => output`. (Separator here is a space.)
```
BONUS 1
Can I get an Amen! => Amen!
AMEN! and AMEN! and a final Amen... => AMEN! AMEN! Amen.
Amen? Amen, and amEn! => Amen? Amen, amEn!
BONUS 2
The man sighed and said, "amen," and left. It's AMEN! => Heresy! at index [26] AMEN!
```
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
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 leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=64109,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([-\d.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 37 bytes
```
S`amen
i`all the people said[?: ]
amenx
!i`amen([.,?]|!*)
```
The code if **57 bytes** long and qualifies for the **-20 bytes** bonus. [Try it online!](http://retina.tryitonline.net/#code=U2BhbWVuCmlgYWxsIHRoZSBwZW9wbGUgc2FpZFs_OiBdCmFtZW54CiFpYGFtZW4oWy4sP118ISop&input=QWxsIHRoZSBwZW9wbGUgc2FpZCBBbWVuISBBbmQgYWxsIHRoZSBwZW9wbGUgc2FpZCBBTUVOIQ==http://retina.tryitonline.net/#code=U2BhbWVuCmlgYWxsIHRoZSBwZW9wbGUgc2FpZFs_OiBdCmFtZW54CiFpYGFtZW4oWy4sP118ISop&input=QWxsIHRoZSBwZW9wbGUgc2FpZCBBbWVuISBBbmQgYWxsIHRoZSBwZW9wbGUgc2FpZCBBTUVOIQ==)
*Thanks to @MartinBüttner for porting [my Perl answer](https://codegolf.stackexchange.com/a/64122) to Retina!*
### How it works
```
S` Split the input at...
amen matches of "amen".
i` Case-insensitively search for
all the people said[?: ] matches of "all the people said",
followed by '?', ':' or ' '...
amenx and replace them with "amenx"
!i` Print all case-insensitive matches of...
amen([.,?]|!*) "amen", followed either by a single '.',
',' or '?', or by 0 or more '!'s.
```
[Answer]
# VBA, 193 bytes
```
Function v(b)
For i=1 To Len(b)
If StrConv(Mid(b,i,19),2) Like "all the people said" Then v=v& "Amen"
q=Mid(b,i,4):k="amen"
If StrConv(q,2) Like k And Not q Like k Then v=v& q
Next
End Function
```
No Separation, No Regex, No Bonus. Had a version that got both Bonus but was MUCH longer.
[Answer]
# Perl, 51 bytes
```
s/amen/x/g;s/all the people said[?: ]/amenx/ig;say/amen[.,?]|amen!*/ig
```
The actual source code contains **70 bytes**, it must be run with `perl -nE` (**+1 byte**), and it qualifies for the **-20 bytes** bonus.
[Answer]
# Python 2, 155 bytes
```
from re import*
F,m=findall,"((?i)amen)"
for i in split(m,input()):
if F("((?i)all the people said[?: ])",i):print'AMen'
elif F(m,i)and i!="amen":print i
```
---
### Example
```
$ python2 test.py
"All the people said Amen! And all the people said AMEN!"
AMen
Amen
AMen
AMEN
```
[Answer]
## JavaScript, 88 bytes
108 bytes - 20 bytes (catches punctuation)
```
alert(prompt().replace(/amen/g,' ').replace(/all the people said[?: ]/ig,'Amen').match(/amen(\??!?\.?)+/ig))
```
[Answer]
## grep and sed, 85 83 84 77 - 20 = 57 bytes
```
sed 's/all the people said[?: ]/Amenx/ig'|grep -oi 'amen[.,!?]*'|grep \[AMEN]
```
[Answer]
# Perl, 103 - 60 = 43 bytes
```
#!perl -p
s/amen/Heresy! at index [@-]/g;s/all the people said[?: ]/Amen /gi;s/(amen([.,?]|!*)|h[^h]+\])\K|.//gi
```
Counting the shebang as one, input is taken from stdin. Maintains punctuation for *-20* bytes, and identifies heresy for *-40*.
---
**Sample Usage**
```
$ echo amen amen, and all the people said?? amen amen | perl amen.pl
Heresy! at index [0]Heresy! at index [5]AmenHeresy! at index [37]Heresy! at index [42]
$ echo AMEN AMeN AmeN aMEN amen AmEn | perl amen.pl
AMENAMeNAmeNaMENHeresy! at index [20]AmEn
$ echo The man sighed and said, "amen," and left. It's AMEN! | perl amen.pl
Heresy! at index [26]AMEN!
```
---
# Perl, 70 - 20 = 50 bytes
```
#!perl -p
s/all the people said[?: ]/Amen /gi;s/amen|(?i:amen([.,?]|!*))\K|.//g
```
Counting the shebang as one, input is taken from stdin. Maintains punctuation for *-20* bytes.
---
**Sample Usage**
```
$ echo All the people said Amen, and all the people said AMEN!! | perl primo-amen.pl
AmenAmen,AmenAMEN!!
```
[Answer]
# ùîºùïäùïÑùïöùïü, 66 - 20 = 46 chars / 80 - 20 = 60 bytes
```
ïċ/all the people said[?: ]⍀,`Amen”ċ(/amen⌿,`x”ĉ/amen(\??!?\.?)+⍀)
```
[Try it here](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=Amen&code=%C3%AF%C4%8B%2Fall%20the%20people%20said[%3F%3A%20]%E2%8D%80%2C%60Amen%E2%80%9D%C4%8B%28%2Famen%E2%8C%BF%2C%60x%E2%80%9D%C4%89%2Famen%28%5C%3F%3F!%3F%5C.%3F%29%2B%E2%8D%80%29) - Firefox only.
First time here at PPCGSE. Hope this golf is pretty good.
EDIT: Actually, I'm beating CJam (in char count), so that's pretty good!
[Answer]
# CJam, 57 bytes
```
q_,,\f{\:I>_4<_el"amen":A=*_A="Heresy! at index ["I+']+@?oK<)"?: "&,*el"all the people said"=A*o}
```
The code is **97 bytes** long and qualifies for the **-40 bytes** bonus.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q_%2C%2C%5Cf%7B%5C%3AI%3E_4%3C_el%22amen%22%3AA%3D*_A%3D%22Heresy!%20at%20index%20%5B%22I%2B'%5D%2B%40%3FoK%3C)%22%3F%3A%20%22%26%2C*el%22all%20the%20people%20said%22%3DA*o%7D&input=AMEN%20AMeN%20AmeN%20aMEN%20amen%20AmEn).
[Answer]
## JavaScript, 100 bytes
```
alert(prompt().replace(/all the people said[?: ]/ig,'Amen').replace(/amen/g,'x').match(/amen/ig));
```
[Answer]
# JavaScript, ~~136~~ 135 - 40 - 20 = 75 bytes
```
alert(prompt(A="ameN").replace(/all the people said[?: ]|(amen)([.,?]|!*)|./ig,(v,a,p,i)=>a?a>A?`Heresy! at index [${i}]`:v:v[1]?A:""))
```
Explanation:
This code is driven by a three-part regex that feeds results into a [`replace` callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter). The parts are:
* `all the people said[?: ]` - simply matches the required `all the people said` pattern
* `(amen)([.,?]|!*)` - matches any-case `amen` and punctuation (one of `.,?` or zero or more `!`, which makes the punctuation optional) into separate match groups -- credit to [Dennis for the punctuation pattern](https://codegolf.stackexchange.com/a/64128)
* `.` - matches any other character, not part of the above patterns, one at the time
Therefore, any match must either be an all-the-people string, an Amen match with optional punctuation, or a single character not part of either of those phrases. We use logic in the replacer callback to save and replace the appropriate parts of the string, and change every other character to the empty string.
```
alert(
// store "ameN" in `A` and then prompt
prompt(A="ameN")
.replace(
// three-part regex:
/all the people said[?: ]|(amen)([.,?]|!*)|./ig,
// replacer callback, with arguments
// v - total match
// a - "amen" match group
// p - punctuation match group (unused)
// i - index of match
(v,a,p,i)=>
a? // if there is an Amen match
a>A? // if the Amen is lowercase (lexically more than "ameN")
`Heresy! at index [${i}]`
:v // otherwise, output full Amen with punctuation
:v[1]? // if there is no Amen, but more than one character
A // this must be all-the-people; output "ameN"
:"" // otherwise, not an Amen or all-the-people
)
)
```
[Answer]
# Python 2, 191 - 40 = 151 bytes
```
i=input()
a='amen'
for j in range(len(i)):
s=i[j:j+20];w=s[:4]
if s[:-1].lower()=="all the people said"and s[-1]in'?: ':print a
if w.lower()==a:print'Heresy! at index[%d]'%j if w==a else w
```
No regex, and Bonus 2
] |
[Question]
[
'exaggerated' is an example of a word which can be typed on the left hand, on a normal qwerty keyboard map. 'monopoly' is an example for the right hand.
Searching the unix `words` file for words that can be typed on one hand. Output should be two lines: space separated list of such words for the left hand, followed by the list for the right hand. e.g.
```
a abaft abase abased abases abate abated abates abbess abbesses ...
h hi hill hilly him hip hippo hippy ho hokum ...
```
The left-hand letters are:
```
qwertasdfgzxcvb
```
The right-hand letters are:
```
yuiophjklnm'
```
Uppercase letters count as one-handed; letters with diacritics count as two-handed and hence words containing them can be ignored.
[Answer]
## sed, 78 bytes
```
1{x;s/^/! /;x};/^['h-puy]*$/IH;/^[a-gq-tv-xz]*$/I{G;x};${x;y/\n/ /;s/! */\n/p}
```
requires GNU sed, run with `sed -n -f words.sed < /usr/share/dict/words`
[Answer]
### Bash (100 89 chars)
```
for x in a-gq-tvwxz h-puy\'
do grep -iE ^[$x]*$ /usr/share/dict/words|tr '
' \
echo
done
```
Note that 21 chars go to the full path to the words file: if we're allowed to assume that pwd is /usr/share/dict then 16 of those can be saved.
Credit to [chron](https://codegolf.stackexchange.com/users/3856/chron) for the shorter regexes.
[Answer]
## Bash, 86
```
for x in a-gq-tvwxz h-pyu\'
do egrep ^[$x]*$ /usr/share/dict/words|tr '
' \
echo
done
```
Taylors `for`, my egrep, chrons grouping of chars.
By definition, if you type by two hands blind, if you like to produce an uppercase letter, you always use the left hand to produce an uppercase character of the right hand and vice versa.
Of course you may produce an uppercase `W` with only the left hand, but you can produce `junk` with the left hand, too, if you like.
[Answer]
## Python 2.7 (139 characters)
```
import os
a=set("yuiophjklnm'")
c=os.read(0,9**9).lower().split()
print'\n'.join([' '.join(filter(x,c))for x in a.isdisjoint,a.issuperset])
```
[Answer]
## Bourne shell, 55 chars
(Or any Bourne-like shell but `bash`, `zsh` or `yash`)
```
w=$1;f()echo `grep -ixe[$1]*<$w`;f a-gq-tvwxz;f h-puy\'
```
Called as `sh -f words.sh /usr/share/dict/words`. (of course, on systems where `sh` is actually `bash` like on some Linux distributions, use another Bourne-like shell like `ash`, `ksh`, `mksh`, `pdksh`, `posh`...)
[Answer]
# Python 3.8 - 126 135 139 144 152 137 chars
```
r,a={*"YUIOPHJKLNM'"},'\n'
try:
while w:=input():
s={*w.upper()}
if r|s==r:a=w+' '+a
if s-r==s:a+=w+' '
except:print(a)
```
**edit:** handle upper case and apostrophe.
**edit 2:** move to python 3. get rid of `' '.join()`. use walrus operator. change `+=w` to `+=[w]` to fix bug.
**edit 3:** change printing to save 5 characters.
**edit 4:** change set creation from `set(iterable)` to `{*iterable}` to save 2 characters twice.
**edit 5:** change two lists to one string to hold result allowing one less assignment on the first line and one less print statement on the last line to save 9 characters.
[Answer]
## Javascript (node), 201 byte
```
f=require('fs');c=d='';r=(a=f.readFileSync('/dev/stdin')+c).split('\n');a.
replace(/[aqzxswcdevfrbgt]/ig,'').split('\n').map(function(k,i){k==r[i]&&(
d+=k+' ');!k.length&&(c+=r[i]+' ')});console.log(c,d)
```
This can probably be rewritten to a much shorter version in another language, but I just wanted to give node a try.
Run with `node words.js < /usr/share/dict/words`
[Answer]
# Q (121 140 Bytes)
Output isn't the exact same (backticks instead of spaces) but this is symptomatic of how Q displays string types.
```
i:read0`:/usr/share/dict/words;
0N!/:i:`$/:i where each (min each) each flip i in/:\:(x,upper x:"qwertasdfgzxcvb";y,upper y:"yuiophjklnm");
```
EDIT: Had to handle mixed case, +20 chars
[Answer]
## Ruby, 112 92 characters
EDIT: This is shorter, though not nearly as fun:
```
puts %w(a-gq-tv-xz 'h-puy).map{|r|File.read('/usr/share/dict/words').scan(/^[#{r}]+$/i)*' '}
```
Original:
```
puts File.read('/usr/share/dict/words').scan(/(^[a-gq-tv-xz]+$)|(^['h-puy]+$)/i).transpose.map{|w|w.compact*' '}
```
Pretty simple regex-based solution. As with the others, you could save some characters if you're allowed to pass the filename in ARGV or if it's assumed to be in your current directory.
[Answer]
## Python, 130 Bytes
```
a="\n"
b=""
try:
while 1:v=raw_input();m=[x.lower()in"yuiophjklnm'"for x in v];v+=" ";a+=v*all(m);b+=0**any(m)*v
except:print b+a
```
Run with `python one_handed_words.py < /usr/share/dict/words`
[Answer]
## Haskell (191)
```
import Char
g x=all(`elem`x)
f m[]=m
f[x,y](w:ws)|g"quertasdfgzxcvb"w=f[w:x,y]ws|g"yuiophjklnm'"w=f[x,w:y]ws|1<2=f[x,y]ws
main=getContents>>=mapM(putStrLn.unwords).f[[],[]].lines.map toLower
```
[Answer]
## Perl, 72 bytes
```
$a{/^['h-puy]+$/i-/^[a-gq-tv-xz]+$/i}.=y/\n/ /rfor<>;print@a{1,-1,$,=$/}
```
run with `perl words.pl /usr/share/dict/words`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 24 25 bytes
```
Øqs€5⁾q'ṭZF€
ỴŒlfƑ¥ƇⱮ¢K€Y
```
[Try it online!](https://tio.run/##HY4xTsNAFET7fxGfgCNACkRHA93aO7E/Xu9u/t91lJI0qaGiRqIDJCQahEQRRO4RX8QsdDNPM6O5gXObef5@WOm0fT6Zbr9W1fHj5fqsODp@vv/cu@Xhbv902E1vr/vH84Kv5nkeQ2NqB7KsNRxjhCVw26WOOo4x0BDEONZE7DVLC9@AYoi5sIFOFwuyqE2CVEocfEkV3SAmyt5DxrJspDRgeYBPpMZa/K@VnEU0kv64ccRVLrTp2Ld0yb6HpLChmEUzJ1oKQKwOSmv2lj1Uy0O64KZnUB0ENgxUC0xvw9r/Ag "Jelly – Try It Online")
## Explanation (older version)
```
Øqs€5⁾q'ṭZF€ Auxiliary niladic link
Øq Lowercase QWERTY keyboard
s€5 Split each row into chunks of at most 5 letters
⁾q'ṭ Append the string "q'"
Z Zip (transpose)
F€ Flatten each => ["qwertasdfgzxcvbq", "yuiophjklnm'"]
ỴŒlfƑƇⱮ¢K€Y Main monadic link
Ỵ Split on newlines
Œl Lowercase
Ɱ¢ Map over the result of the auxiliary link:
Ƈ Filter by
Ƒ Invariant under
f Filtering by the right argument
K€ Join each with spaces
Y Join with a newline
```
[Answer]
## Python, 243 chars
edit: here's a more compliant program according to the question:
```
import sys
def o(w):
r="yuiophjklnm'";f=2;w=w.lower()
for l in w:
if(f==1)&(l in r)|(f==0)&(l not in r):return 2
f=l not in r
return f
y=[[],[],[]]
for w in sys.stdin.read().split('\n'):y[o(w)].append(w)
for i in y[0:2]:print' '.join(i)
```
invoke: `python onehanded.py > /usr/share/dict/words` or any other words file with newline-separated words
old: 141 chars, just a single-word function
returns `right` or `left` if `w` is onehanded, and `both` if both hands are used.
```
def o(w):
r="yuiophjklnm'";f=2
for l in w:
if(f==1)&(l in r)|(f==0)&(l not in r):f=2;break
f=[1,0][l in r]
return'rlbieogfththt'[f::3]
```
[Answer]
# Q, 95 (111 with hardcoded dict path)
```
{`$'e[(w(&)l(w)in .Q.a except a)],(e:enlist)w(&)(l:all')(w:(_)read0 -1!`$x)in a:"yuiophjklnm'"}
```
usage
```
q){`$'e[(w(&)l(w)in .Q.a except a)],(e:enlist)w(&)(l:all')(w:(_)read0 -1!`$x)in a:"yuiophjklnm'"} "/usr/share/dict/words"
`a`a`aa`aa`aaa`aaa`aaaa`aaaaaa`aaas`aaberg`aae`aaee`aaf`aag`aar`aara`aarc`aas..
`h`h`hh`hi`hi`hi`hih`hiko`hikuli`hili`hill`hill`hillo`hilly`hilly`hilo`hilum`..
```
14 more chars if you hardcode it
```
`$'e[(w(&)l(w)in .Q.a except a)],(e:enlist)w(&)(l:all')(w:(_)read0`:/usr/share/dict/words)in a:"yuiophjklnm'"
```
[Answer]
# J, 109
```
1!:2&2;:^:_1('qwertasdfgzxcvb';'yuiophjkl''nm')((#@[>[:>./i.)&>/#]);:1!:1<'/usr/share/dict/words'[9!:37]0,3$_
```
I'm sure this can be done better, I don't know how to do string manipulation :-(
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 44 bytes
```
Ljdf.A}RbrT0cQdy."az:ïÑý>Íï“"y"yuiophjklnm'
```
[Try it online!](https://tio.run/##AUkAtv9weXRo//9MamRmLkF9UmJyVDBjUWR5LiJhejrDr8ORBcO9PsONw6/CkyJ5Inl1aW9waGprbG5tJ///ImFiYmVzcyBraWxvIGEi "Pyth – Try It Online")
---
```
Ljdf.A}RbrT0cQdy."az:ïÑý>Íï“"y"yuiophjklnm' | # Python 3 Translation
---------------------------------------------+------------------------------
| from operator import contains
| from itertools import repeat
| Q = eval(input())
L | y = lambda b:
jd | " ".join(
f | filter(lambda T:
.A | all(
}R | map(contains,
b | repeat(b),
rT0 | T.lower()
| )
| ),
cQd | Q.split(" ")
| )
| )
y."az:ïÑý>Íï“" | print(y("qwertasdfgzxcvb"))
y"yuiophjklnm' | print(y("yuiophjklnm'"))
```
[Answer]
**Python: 122**
```
import os
S=set("yuiophjklnm'")
c=os.read(0,9**9).lower().split()
print"\n".join(w for w in c if set(w)<=S or set(w)^S>=S)
```
Launched with:
```
python name_of_program.py < /usr/share/dict/words
```
---
The idea is mostly the same of Dillon Cower's, but I use `set(w)<=S` to indicate a subset while `set(w)^S>=S` for a disjoint set.
] |
[Question]
[
Given a list, `L`, of sets of numbers like this:
```
[[1], [0,2,3], [3,1], [1,2,3]]
```
Output a single list of numbers such that 2 numbers A and B appear next to each other at least once if and only if `B in L[A]`.
That is all such pairs *must* exist in the output, and *only* such pairs *may* exist in the output, where the order of any pair in the output may be read in either direction.
If `A` is in `L[B]` then `B` is guaranteed to be in `L[A]`, in other words, the relationship is symmetric.
In this case, one possible output would be this:
```
[0, 1, 2, 3, 3, 1, 3]
```
In this case, you can see `0` is only ever next to `1`, which matches our adjacency list. `1` appears next to `0` and `2` in the first instance and `3` in the second instance. It appears next to `3` again but that doesn't matter. Numbers are adjacent if they appear together at least once, but more doesn't matter. `2` appears next to `1` and `3`, and finally `3` appears next to `2`, `1`, and itself (necessary since `L[3]` contains a `3`).
For any given adjacency list there are many possible solutions. You may choose to output any valid solution. Your solution does not need to be the shortest one, but it does need to have a finite length.
## Test Cases
| Input | Possible Solution |
| --- | --- |
| `[[0]]` | `[0, 0]` |
| `[[1],[0]]` | `[0, 1]` |
| `[[0,1,2], [0], [0]]` | `[1, 0, 0, 2]` |
| `[[0,1,2], [0,1,2], [0,1,2]]` | `[0, 1, 1, 2, 2,0, 0]` |
| `[[1,2,3,4], [0], [0], [0], [0]]` | `[1, 0, 2, 0, 3, 0, 4]` |
| `[[1, 2], [0, 2], [0, 1]]` | `[0, 1, 2, 0]` |
| `[[], [2], [1]]` | `[1,2]` |
## IO
Any of list of sets, dict of sets, list of lists, list of dicts, adjacency matrix, are valid input formats. You don't have to use numbers if you use a mapping, any primitive data type with a potentially infinite number of elements is valid.
For the input `[[0,1,2], [0], [0]]` the following would all be possible input formats from you to choose from. You only need to handle one of these of your choice.
* `[[0,1,2], [0], [0]]`
* `{0: {0,1,2}, 1: {0}, 2: {0}}`
* `{'a': "abc", 'b': "a", 'c': "a"}` (Strings and arrays of characters are considered equivalent.
* `[[1,1,1],[1,0,0],[1,0,0]]` (Adjacency matrix)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~13~~ ~~11~~ 12 bytes
```
Wsvεèyδ‚yš}˜
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/vLjs3NbDKyrPbXnUMKvy6MLa03P@/4@OjtVRiDYCEYaxsQA "05AB1E – Try It Online")
If it shouldn't output "0" for 0 it can be fixed with +1 byte by appending `ï`.
## Explanation
Suppose `i` is adjacent to `[a1, ..., a2, ..., an]`. If we start with some path, we can replace all instances of `i` with `i, a1, i, a2, i, a3, i, ..., i, an, i` and remain with a valid path.
If we do it N times, we will necessarily traverse all edges, since N-1 is the maximal distance in a connected graph, after N-1 times all vertices will appear, and the N-th iteration will add all edges.
```
W push the minimum number in the input
s and swap it, so the input is back on top
v for each element in the input (we do this to repeat N times)
ε replace each value in our list (which starts with "0") with
è index it into the implicit input
y push the index
δ and for each element in the adjacency list
‚Äö pair it with the index
y push the index again
š and prepend it to the list
} (the list isn't flat, but we flatten it later)
Àú and flatten
```
[Answer]
# [Python](https://www.python.org), 131 bytes
```
f=lambda l,h=[],*t:h*({*zip(h,[r:=range(len(l))]+h)}>{(a,b)for a in r for b in l[a]})or f(l,*t,*(h+[i]for i in[*l,r][[-1,*h][-1]]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PZAxbgIxEEXrcIoRlW1mpTVVtNJykdEUXrGOLTlmZUyRIArEMdLQhDtxG-wlpPn_zXzJ8-Wf2_SV3S5er7-HbJv3-8X2wXwOWwMBXU-MKndOiaP69pNwSKnrk4kfowhjFEFKXjl52hyFwUHaXQIDPkKCikPFQIZPskxWhPIWKuFW5LnmvuSkAiYmajQqx8WYpfyrcs7jPu-hBwKilhmhuGb85xY1rguWxSxVSSOs57h9QnX9jKrMqzLzolbIteJ8plu8TcnHLDIum80SrcivIq-_eQA)
Since it's a bit less readable than a typical python submission, here's the explanation:
The code does a BFS, keeping track of the queue using varargs. `h` is the entry to be explored this iteration.
We first check if `h` is a solution using `{*zip(h,[r:=range(len(l))]+h)}>{(a,b)for a in r for b in l[a]}`. This checks if the left set is a strict superset of the right one.
The left set is the set of all ordered adjacencies present in `h` plus an extra element `(h[0],r)`.
For the purposes of this part of the code, the exact value of `r` does not matter, only that it's distinct from integers.
The right set is the set of all possible adjacencies.
The comparison is a bit more strict than necessary, but due to the symmetry of `l` it doesn't matter.
If the comparison succeeds this means that `h` gets multiplied by 1 and the `or` short circuits and `h` is returned, otherwise we explore `h`.
We recurse, adding new paths at the end of the queue (varargs). There is also code that handles the special case of `h=[]` which happens at the start
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~83~~ 72 bytes
```
(c=1;FindPostmanTour[Reap[(Sow[#<->c]&/@#;c++)&/@#][[2,1]]][[1,All,1]])&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPZ1tDaLTMvJSC/uCQ3MS8kv7QoOig1sSBaIzi/PFrZRtcuOVZN30HZOllbWxPEiI2ONtIxjI0F0oY6jjk5ILam2v@Aosy8Eoc0h@pqQx0FIx0F41odhWpDCFH7HwA "Wolfram Language (Mathematica) – Try It Online")
Start from `1` notation!
Much shorter, but still has problem with `[[1]]`...
[Answer]
# [ATOM](https://github.com/SanRenSei/ATOM) 70 chars, 74 bytes
```
{i=*;p=[];g={p+*;i.*‚àÄ{*üèïp:*üö™g;p+$1}};0üö™g;ü¶∂(püó∫{a=[*];i.*‚àÄ{a+*+$1};a})}
```
Edit: Decided to add integer for-loops to the language as an alternative to arrays, and with that plus changing the algorithm to the top one used by 05AB1E, I got this down to 38 char/43 bytes. The change happened after the question was posted, and it feels like cheating to steal someone else's algorithm, so I'll keep the label on this answer as 70 char/74 bytes.
```
{r=[0];üßµ*‚àÄr=ü¶∂(rüó∫ü¶∂ü¶∂[*,$2.*üó∫[*,$1]]);r}
```
## Usage
```
input=[[1], [0,2,3], [3,1], [1,2,3]];
input INTO {i=*;p=[];g={p+*;i.*‚àÄ{*üèïp:*üö™g;p+$1}};0üö™g;ü¶∂(püó∫{a=[*];i.*‚àÄ{a+*+$1};a})}
```
### [Try it online](https://sanrensei.github.io/ATOM/)
## Explanation Using Commented Non-Golfed Code
```
input=[[1], [0,2,3], [3,1], [1,2,3]];
visited=[];
path=[];
# Create a path of indices that hits each at least once
# Depth first traversal
visit = {
visited+*; # Add the index to the list of visited indices
path+*; # Add the index to the path
# Look at each connected index and check if its already visited
input.* FOREACH {
* NOTIN visited:
* INTO visit;
path+$1; # Return to the original index at the end
}
};
0 INTO visit;
üñ®"Path";
üñ®path;
# Create a function that takes an index and generates a proper neighbor sequence
neighbors = {
arr = [*];
input.* FOREACH {
arr + *;
arr + $1;
};
arr
};
# Map the path into neighbor sequences
result = (path MAP neighbors);
üñ®"Preflattened Result";
üñ®result;
# Flatten it and return
ü¶∂ result
```
Essentially it builds a path of indices that is guaranteed to hit each of them at least once. Then, it takes that path, and turns each point on the path into a sequence of numbers that hits every pair from the input. The solution it finds is very brute forced and longer than what is optimal.
Between the time of the question being posted and this solution, I implemented the flatten operator (the foot). Hopefully that function is considered standard enough to not be considered breaking a loophole.
[Answer]
# Python3, 244 bytes
```
def F(r,k=[],s=[]):
if not r-{*s}:yield k
for x,y in r:
if(x,y)not in s and([]==k or k[-1]==x):yield from F(r,k+[x,y][k!=[]:],s+[(x,y)])
def f(l):
v={i for j in l for i in j if i<len(l)}
return F({(x,y)for x in v for y in v if x in l[y]})
```
[Try it online!](https://tio.run/##fU9BboMwELzziu3NbjYShiSlqFz7CcuHSoDqQA0yNAIh3k7XBlVtRXOwd9Y7Mztux/69MXHS2mXJixJemcUqkwo7ungagC7BND3Y4/TYzemoizqHKoCysTDgCNqAJRbRGLXcUempgzeTM6myrAIiVvIoCA9805e2@Vg3HSSplKweaFtKSw/S2ygeuDAlq12EWzZpv/DqvGsPtYNXl06/1IUh4hyALfpPa8h58i4@o@PdvGRcIUn8Yy1HNfOltdr0zBRDz0omZagU5zz48yoU/jMJUWCkEGjsr/uc32B3E0YY4wnPPzzvuwuEzfO7il2iG3rG/li4T8Z0LnQERXhyPZ4xoXrCi68R9c8bj0KiF3mBAwmKENeUyxc)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes
```
≔Eθ⟦κ⟧ηFη¿¬ⅉ¿⊙θ⁻κE⌕AΦινλ§ιμF§θ↨ι⁰⊞η⁺ι⟦κ⟧Iι
```
[Try it online!](https://tio.run/##XU7LCsIwELz7FXvcQARft56iIHio9Colh9CmJjSm2qSiXx83Fi8u7GtmdtjGqLEZlEtJhGCvHkt1xweHupeMg2HFohtGQMPAdoDnIeIFGZs34d9ZWlo/BexpoNOj9a1wjrqLekTLwZOPoxTx5Fv9ytCN5YCv8w8mo70KOtOrTFZTMGg4VI7M7fwQK0C7oKEarY94UCGiJTCluq7XHDYcthx2ksSr/yJlWj7dBw "Charcoal – Try It Online") Link is to verbose version of code. Actually outputs the shortest list of numbers such that both pairs `A, B` and `B, A` appear in the list. Explanation:
```
≔Eθ⟦κ⟧η
```
Start with the trivial lists of just one item. (This is needed so that we know which next item(s) are valid.)
```
Fη¿¬ⅉ
```
Start a breadth first search of lists but stopping once a solution is found.
```
¿⊙θ⁻κE⌕AΦινλ§ιμ
```
Check whether all the pairs exist in this list.
```
F§θ↨ι⁰⊞η⁺ι⟦κ⟧
```
If not then try all the lists obtained by appending one of the legal neighbours of the last element.
```
Iι
```
If they do then output this solution.
30 bytes for a port of @CursorCoercer's nondeterministic but fast Pyth answer:
```
⊞υ⌈⌈θW⊙θ⁻κE⌕AΦυνλ§υμ⊞υ‽§θ↨υ⁰Iυ
```
[Try it online!](https://tio.run/##NU3BCsIwDL37FTumEGHVORVPUxA8CMPr6KFsgxW7zq2rzq@v6XCBx8tL3kvKRg5lJ7X3ubMNOIzuclKta2HhnjF2Wn0apesIMvOFnjzKOAvPYH7BVZkq05pYj/UQThiGkSZk481U9RRGLQsVLU8e0lRdC4uBTp6lrcMmZvO/fFBmhIu0IzjS3hdFwbnAYktICRwT3AeNOzwQJ5jOvCF9/PsS6ufQHAjNAXmMsRDCr9/6Bw "Charcoal – Try It Online") Link is to verbose version of code. Outputs a random list containing all the pairs and their reversals. Explanation:
```
⊞υ⌈⌈θ
```
Push the maximum number from the lexicographically maximum list.
```
W⊙θ⁻κE⌕AΦυνλ§υμ
```
Repeat while the list does not contain all of the pairs...
```
⊞υ‽§θ↨υ⁰
```
... push a random hop from the last number.
```
Iυ
```
Output the final list.
[Answer]
# [Scala](https://www.scala-lang.org/), 336 bytes.
\$ \color{red}{\text{It failed on some cases. Any help would be appreciated.}} \$
Modified from [@Ajax1234's answer](https://codegolf.stackexchange.com/a/261438/110802).
---
Golfed version. [Try it online!](https://tio.run/##lVKxbsIwEN35CneJ7sTVIqVdCKnE0KEDA@oCqlDlBoemMU6auIgo4tupDS0BCWgbyfHdu3fvni2XkVBik72@y8iwoUg0kysj9axkgzxn9cZUuWSj8FGb1kzGLAbVe5Ifz26NplMMa4fOYWlRYxE6KlPa20Wh3QCp3KYwohF@Q/hDqOOsgFX/ehlU9of1Uig23nJWVCFfJDpw0OQAEqsgieGq5FGmjXVeAoxpguh5CibYoGPEQprPQjufpChtt52I4/JZkeVgVVKuM/2wyE3leSlXojRhOEafSVVK1nHO2zvxdZCugzmA4omeJZEseayEGQqrEt4rSJDHiTKygJe@4krquXlD5Caz14OkcL1pMZYXiTZKQwzOx6AoRAU@EttFHbqh7j7rUlPxtxX7ndHoXKhZld9JHbIjGiMH0Z97TmQXTLkD0S3dnZz5Px8@scPBx4l/vvHZPu0p7MlN265n3dp8AQ)
```
type Q=Int
def f(l:Seq[Seq[Q]])={def g(v:Set[Q],l:Seq[Seq[Q]],k:Seq[Q]=Seq(),s:Seq[(Q,Q)]=Seq()):Seq[Q]={for(x<-v;y<-v){val X=Seq(x,y).min;val Y=Seq(x,y).max;if(!s.contains((X,Y))&&l(Y).contains(X))return g(v,l,k++Seq(X,Y).drop(if(k.nonEmpty&&k.last==X)1 else 0),s:+(X,Y))};k};g((l.indices.flatMap(i=>l(i).filter(_<l.length)).toSet),l)}
```
Ungolfed version. [Try it online!](https://tio.run/##lVJNSysxFN33Vxw3ktC8MOPHps8KLlwICoKbFimSN5PR2JgZklhapL@9ZjIzTgtDeW7u5Obc89GbukxosduV/95l5vEglIFce2lyh5uqwtcIyGWBgugJbqwVm@em3hm/WNAJ7pXzscE0DgPFp8kI0VyZXGXS8UIL/yAqojC9hiaK8kJpLy15wRU019K8@jdKuS@fpKcMmgaZ7agzrtVWEwQs2gR8IAjD8jBKfSZBzLXXJNwzhEJ7dDh9aUHWuPqD1V9s4pe2ELASGq60XuaPQtlOaM2woby53xucBbwfJgndw@aHWNphqgA5cTwrjQ8v4QiZMcwpxelp2Nyc9sCMdhTASv9pTbupsJ@wDIzHTbbI57ktw/6D9pKb0tx@VH5TSy65Fs5jOsWMIoXUTiKpl4bJGK11dNnGuuzepbLKeG1IQeITtDUNzOaUsDN2/tOdsx5JI0Kj7LBKchQNSv8zlrBg1MfZO/2CNdAdjVb/NHbBLgd9f5slZdg3P2zSY9T4dyY/4z2xYW1Hu903)
```
object Main extends App {
def f(l: Array[Array[Int]]): List[Int] = {
func((l.indices.flatMap(i => l(i).filter(_ < l.length)).toSet), l)
}
def func(v: Set[Int], l: Array[Array[Int]], k: List[Int] = List(), s: List[(Int, Int)] = List()): List[Int] = {
for (x <- v; y <- v) {
val sortedPair = List(x, y).sorted
val X = sortedPair(0)
val Y = sortedPair(1)
if (!s.contains((X, Y)) && l(Y).contains(X))
return func(v, l, k ++ List(X, Y).drop(if (k.nonEmpty && k.last == X) 1 else 0), s :+ (X, Y))
}
k
}
println(f(Array(Array(1), Array(0,2,3), Array(3,1), Array(1,2,3))))
println(f(Array(Array(0))))
println(f(Array(Array(1),Array(0))))
println(f(Array(Array(0,1,2), Array(0), Array(0))))
println(f(Array(Array(0,1,2), Array(0,1,2), Array(0,1,2))))
println(f(Array(Array(1,2,3,4,5), Array(0), Array(0), Array(0), Array(0))))
println(f(Array(Array(1, 2), Array(0, 2), Array(0, 1))))
println(f(Array(Array[Int](), Array(2), Array(1))))
}
```
[Answer]
# [R](https://www.r-project.org), ~~89~~ 82 bytes
*Edit: -7 bytes thanks to pajonk*
```
f=\(l,p=max(?l),n=p,`?`=unlist)`if`(n,f(l,?Map(\(x)c(x,rbind(l[[x]],x)),p),n-1),p)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVFLCsIwEMWlniLgZgamiyQKbmJP4KbbthA_FAq1lNpC7uKmLjyUnsaY4CcqwjB5MG_ee0mOp3YYzn1XRItLUqgMKmrUfm0grpBq1ZCOterrqjx0qMtCQ02F5cSrdQMZGNyCoXZT1juo0tTkORlEauxqxO-nV76OErtkJWALHBHZlKnl2GJiHCfPkUD6mou3OSdBEondSb6_qMJKuZK_Fz5Q6OFKuvqMRJJmNA9M_wXwCjPX54EOe9i_gPiKIUN3R_R0EVrZW_qnfXzeDQ)
Same approach as [Command Master's answer](https://codegolf.stackexchange.com/a/261434/95126): upvote that one!
(uses 1-based indexing)
**Ungolfed:**
```
f=function(l,p=unlist(l)[1],n=1){
if(n==length(l))return(c(unlist(p)))
else{
f(l,unlist(sapply(p,function(x)c(x,rbind(l[[x+1]],x)))),n+1)
}
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 73 bytes
```
x=>g=(i=x.findIndex(x=>x+x))=>[i,...x[i].flatMap(j=>[...g(j),i],x[i]=[])]
```
[Try it online!](https://tio.run/##bY5RT8MgFIWf3a/oWy96ZYXtwcQw30x88MlHxIS00NBgW9tuwV9fKc65JUtuDuQ7l3No9EGP5eD66b7tKjNbMQexqwU4Eah1bfXSViZAZOEuECJ20iGlNEinqPV6etU9NJFGVkND0ClcPCEVUfPjajBfezcYyO2YEzoYXT07b96@2xIKzPeTfUi497o0sP6gt0/v0/qzxthXdu3YeUN9V4MFc9Ae4geAEDJLWSiV3cgCs0KtpGQK/wlbSIEMucIs4iSLx@J2Gn65cXn5S0nDlzm1IMcNbs9Sr@XzpJuk299n2TH@dLKzFn5MX6zks2MYVz8 "JavaScript (Node.js) – Try It Online")
Each appearance of edge runs twice
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 19 bytes
```
KOQWnQXKH.{
=KO@QK
```
[Try it online!](https://tio.run/##K6gsyfj/n8vbPzA8LzDC20OvmsvW298h0Pv//2oDK4VqAx1DHaNaHQVDEBtIG4HpWgA "Pyth – Try It Online")
Takes input as a dictionary of sets. Starts at a random node and randomly traverses the graph until all edges have been hit.
### Explanation
```
# implicitly set H to an empty dict
# implicitly set Q = eval(input())
KOQ # set K to a random key in Q
\n # print(K)
WnQ # while Q != H:
XKH # add to H[K] (or assign to if H has no key K)
.{ # set containing
=K # K assigned to
O@QK # a random element of Q[K]
\n # print(K)
```
] |
[Question]
[
Given a list of positive integers, write code that finds the length of longest contiguous sub-list that is increasing (not strictly). That is the longest sublist such that each element is greater than or equal to the last.
For example if the input was:
\$[1,1,2,1,1,4,5,3,2,1,1]\$
The longest increasing sub-list would be \$[1,1,4,5]\$, so you would output \$4\$.
Your answer will be scored by taking its source as a list of bytes and then finding the length of the longest increasing sub-list of that list. A lower score is the goal. Ties are broken in favor of programs with fewer overall bytes.
[Answer]
# [Pyth](https://pyth.readthedocs.io), score 2 (8 bytes)
```
lefSIT.:
```
[Try it here!](https://pyth.herokuapp.com/?code=lefSIT.%3A&input=%22lefSIT.%3A%22&debug=0)
Code points `[108, 101, 102, 83, 73, 84, 46, 58]`. Another shorter solution, `leSI#.:` scores 3, but its code points are `[108, 101, 83, 73, 35, 46, 58]`, which are very close to a score of 1, actually. ~~Rearranging a bit may help~~ Nevermind, the substrings built-in is `.:` which cannot be rearranged, so the lowest score must be 2 if the program makes use of it.
### How?
```
lefSIT.: Full program. Accepts either a list or a string from STDIN.
.: Substrings.
f T Only keep those that are...
SI Sorting-Invariant.
le Length of the last item.
```
[Answer]
# [Haskell](https://www.haskell.org/), score 2, ~~66~~ ~~64~~ ~~61~~ ~~60~~ 65 bytes
* -2 bytes thanks to [Max Yekhlakov](https://codegolf.stackexchange.com/users/82142/max-yekhlakov)
* -1 byte thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi)
* +5 bytes to handle the empty list
```
foldr1 max.g
g[]=[0]
g(x:y:z)|x>y=1: g(y:z)
g(_:y)|a:b<-g y=1+a:b
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPy0/J6XIUCE3sUIvnStdo8Kq0qpKs6bCrtLW0EohXQPMS7RKstFNVwGybQ21gRyudIV422jD2P@ZeQWlJbZKyGbE5BFpCFAhxBQlrtzEzDzbgqLMvBKVNAWwmf//JaflJKYX/9dNLigAAA "Haskell – Try It Online") (verifies itself).
I never thought I could get a score of 2 with Haskell, and yet here I am!
Function `g` computes the lengths of all the increasing substrings recursively.
`foldr1 max.g` takes the maximum of those lengths (`foldr1 max` is equivalent to `maximum`, but with a lower score).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~score 3, ~~53~~ 46 bytes~~ score 2, ~~51~~ 50 bytes
-7 bytes thanks @Arnauld
~~+5~~ +4 spaces in exchange of -1 score
```
a=> a.map($= p=n=>$=(p<=(p=n)?++ x:x=1)<$?$: x)&&$
```
[Try it online!](https://tio.run/##ZcpLCsIwFIXhuasIJZRcEgPxMSm9LbiNUmiovdJSk9CqZPdRcaI4OD9n8E32Ydd@GcNt6/x5SITJYsWsvtogOLKADiuOIpSvoYNaShaLiAZKXvOCRchznnrvVj8PevYXQaIxyqidevegjmr/@S3A5ts1WuvTnWhYRJZJglZPfnQd634Z/UOA9AQ "JavaScript (Node.js) – Try It Online")
Assumes non-empty input. 61 bytes if empty list must be handled. Score 2 still.
```
a=> a.map($= p=n=>$=(p<=(p=n)?++ x:x=1)<$?$: x)&& a.length&&$
```
[Try it online!](https://tio.run/##fc5NCoMwEAXgfU8RJIQMpgH7sxFHodcQwWCTVrFJUFu8fWpx09LSxTwej28xnXqosRlaP22tO@tgMCjMiZI35TlF4tFiTpH7bDm0UMQxmdMZE8hoQVMyA2OL7rW9TFfGaGicHV2vZe8u3PAyEYnYiVcexFHs114BbN5dKaU83Y3RA4@i2EAlO9famtSfzHxD@CfWp6JfapnCEw "JavaScript (Node.js) – Try It Online")
...or 58 if returning `false` is allowed. Score 2 still.
```
a=> a.map($= p=n=>$=(p<=(p=n)?++ x:x=1)<$?$: x)&& a>[ ]&&$
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 [bytes](https://github.com/barbuz/Husk/wiki/Codepage "Husk's codepage"), score = 2
```
00000000: bc6d 4cdc 14 ▲mLġ≥
```
[Try it online!](https://tio.run/##yygtzv7//9G0Tbk@RxY@6lz6////aEMLCx1DA0sdczMdIyMDHSODWAA "Husk – Try It Online")
It's unlikely to get a score lower than 2 with Husk because `ġ`1 has a really high codepoint and there needs to be something before it to get the maximum and length. An attempt could be made with trying to use multiple functions but `\n` would be before any helper functions which has a really low codepoint so anything after it would create an increasing byte-sequence of at least length 2.
1: This seems like the best way to use for the comparison operators would need to follow the various split functions like `↕` (`span`).
### Explanation
```
▲mLġ≥ -- example input: [1,1,2,1,1,4,5,3,2,1,1]
ġ≥ -- group elements by geq: [[1,1,2],[1,1,4,5],[3],[2],[1,1]]
mL -- map length: [3,4,1,1,2]
▲ -- maximum: 4
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 40 bytes, score 3
```
\d+
$*
(?<=(1+)),(?!\1)
¶
T`1`_
^O`
\G,?
```
[Try it online!](https://tio.run/##LUw5DgIxDOz9CySKhJ0iXpvsRgKlpKShjGCRoKChQLyNB/CxEEdI1ngOj1/39@N5rbXcBlpvyOXd3vHgPVxeFfb0/dBp4eVC5@NC5YBcaxrBIUClLUiEmoYGREFsyMY12YFyH/2nImhli9gqPPfmrEjR3IZpa05STF0aHzH1F1F@ "Retina 0.8.2 – Try It Online") Link includes itself as byte codes as input. Explanation:
```
\d+
$*
```
Convert to unary.
```
(?<=(1+)),(?!\1)
¶
```
Split on decreasing pairs.
```
T`1`_
```
Delete the digits.
```
^O`
```
Sort the commas in reverse order. (I would normally write this as `O^` but can't do that here for obvious reasons.)
```
\G,?
```
Count the longest comma run, and add one to include the final number.
[Answer]
# Japt `-h`, 6 bytes, score 2
Don't *think* a score of 1 is possible. Should work with strings & character arrays too.
```
ò>¹mÊn
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8j65bcpu&input=WzI0Miw2MiwxODUsMTA5LDIwMiwxMTBdCi1o) - included test case is the charcodes of the solution.
---
## Explanation
```
ò :Partition after each integer
> : That's greater than the integer that follows it
¹ :End partition
m :Map
Ê : Length
n :Sort
:Implicitly output last element
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), score 2, 13 bytes
```
d0< ~Y'w)X>sQ
```
Input can be:
* An array of numbers.
* A string enclosed with single quotes. Single quotes within the string are escaped by duplicating.
MATL uses ASCII encoding. The codepoints of the above code are
```
100, 48, 60, 32, 126, 89, 39, 119, 41, 88, 62, 115, 81
```
[Try it online!](https://tio.run/##y00syfn/P8XARqEuUr1cM8KuOPD/f3UoHyqgDgA "MATL – Try It Online")
### Explanation
```
d % Implicit input. Consecutive differences (of code points)
0< % Less than 0? Element-wise. Gives true or false
% Space. This does nothing; but it breaks an increasing substring
~ % Negate
Y' % Run-length encoding. Gives array of true/false and array of lengths
w % Swap
) % Index. This keeps only lenghts of runs of true values
X> % Maximum. Gives empty array if input is empty
s % Sum. This turns empty array into 0
Q % Add 1. Implicit display
```
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), score 2
111 bytes
```
var a,b,c,t:bYte;bEgIn repeat read(a); iNc(c); if a<b then c:=1; if c>t then t:= c;b:= a;until eOf;write(t)eNd.
```
[Try it online!](https://tio.run/##bVBLb4MwDP4rPlKJTTGEPGDdbYdduvOOIQ0dUoUQTbefz2KHrZW2iw2f/T2c2V28Oz8Ms1/XT7eAK/vSl7Ht32Po@pfT6wRLmIOLqblj4XYdjAdfeOoDuKce4keYwLd7ZMQ/x4zEdg@@61N13XWK4xnC29B9LWMMRdyFw/FxXRENWA2IEuqKvqQEa7haqogKGkOQsfyDAqGxBKgEiBp0nXBBbBKhMWLFnXXV/YQQIUAKdmIhmooGtGFDwfV@gKLakilBrqxGMX682DqxUkqFIO0/XAuqukX5Q95uTOxNic@7IZoQRM37mU/aOUuS0ZadeMlutza/jyUzJx3Fuya/gIJv "Pascal (FPC) – Try It Online")
Assumes non-empty input. Numbers are taken from standard input separated by spaces.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), score 2, 46 bytes
```
{my&g=1+*×*;+max 0,|[\[&g]] [ |@_] Z>=0,|@_ }
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq3Ui3d1lBb6/B0LWvt3MQKBQOdmuiYaLX02FiFaIUah/hYhSg7W6CgQ7xC7X9rruLESoU0jWhDHUMdIx0QaaJjqmMMYcdqIskbAUWNUcWQ2AhmYQJpbkjQS81Lzk9J1XMsKkqs1LT@DwA "Perl 6 – Try It Online")
Handles the empty list. The original code was:
```
{my&g=1+*×*;+max 0,|[\[&g]] @_ Z>=0,|@_}
```
So only 5 extra bytes to reduce the score to 2.
Edit: Ah, I figured out how to [remove the assignment](https://tio.run/##hY5NDoIwGET3nOIzENJiQ/hRNwSi17A2QKBEE1q0GpUA5/BAHqyCLli6mbzMLOaduao3WrRgVxCD7kyRP8Ho6YHaaOEtnffLwYwBhX6bMtgnsUdGgkGbiovmzqFohODyBrksQfJHfZLcuOYtVIj6xCcBmXJF1iT8McPRvAdjG85dRytkpXj8AStNErc4qi8O6JJ1k9h/r8zlsmhK7u6Uylsc6Q8), but then I can't get that score below 3 because of the `)]]`...
### Explanation:
```
{ } # Anonymous code block
my&g= ; # Assign to &g an anonymous Whatever lambda
1+*×* # That multiplies the two inputs together and adds 1
@_ Z 0,|@_ # Zip the list with itself off-set by one
>= # And check if each is equal or larger than the previous
# e.g. [5,7,7,1] => [1,1,1,0]
[\[&g]] # Triangular reduce it by the function declared earlier
# This results in a list of the longest substring at each index
# e.g. [5,7,7,1] => [1,2,3,1]
+max 0,| # And return the max value from this list, returning 0 if empty
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), score 2
There is probably a score 1 solution somehow...
```
IṠµṣ-ZL‘
```
**[Try it online!](https://tio.run/##y0rNyan8/9/z4c4Fh7Y@3LlYN8rnUcOM////R5sb6ygYGZjqKFgCaSMgxwTENtBRMDcDCpgaxQIA "Jelly – Try It Online")**
Source code as a list of byte values:
```
[73, 205, 9, 223, 45, 90, 76, 252]
```
### How?
```
IṠµṣ-ZL‘ - Link: list of integers e.g. [ 1, 1, 2, 1, 1, 4, 5, 3, 2, 1, 1]
I - increments [ 0, 1,-1, 0, 3, 1,-2,-1,-1, 0]
Ṡ - sign [ 0, 1,-1, 0, 1, 1,-1,-1,-1, 0]
µ - start a new monadic chain (a low byte to stop score being 3)
- - literal minus one -1
ṣ - split at [[0, 1], [0, 1, 1], [], [], [0]]
Z - transpose [[0, 0, 0], [1, 1], 1]
L - length 3
‘ - increment 4
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score 3 (9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))
```
Œʒ¥dP}éθg
```
Can most likely be a score of 2 somehow.
Code points of the program-bytes: `[140,1,90,100,80,125,233,9,103]` (two sublists of length 3: `[1,90,100]` and `[80,125,233]`)
[Try it online.](https://tio.run/##yy9OTMpM/f//6KRTkw4tNfBOCag9vPLcjvT//6MNdQx1jHRApImOqY4xhB0LAA)
**Explanation:**
```
Œ # Sublists
ʒ } # Filter by:
¥ # Take the deltas
d # Check for each whether the number is >= 0
P # And check if it was truthy for all deltas
é # Then sort by length
θ # Take the last element
g # And take its length as result
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), score 3, 94 bytes
```
a->{int m=0,p=0,x=0,i=0,n;while(i<a.length){n=a[i++];m=(p<=(p=n)?++x:(x=1)) <m?m:x;}return m;}
```
[Try it online!](https://tio.run/##tZJNj4MgEIbv/opJYxqIlm7346LSZi9766nHpgfWqqUraBBbG@Nvd4GYTffjuglD9IV5h3ngzC5scT5@jFzUldJwNv@k1bwkr0qxWxN7XlqypoEt4xJ6D7jUmcpZmsH29tbKVPPK6XYBciMg87E/AMOxB4MHjWaap/eb8/hLtXk5UFguGV0zIliNfFpTSdc@RXVigkq8CYIu6ugKJ/7Gjzo8n/sjW6x7W1DQh7A20ZngJmR8PfEyQzxhpMxkoU@4l5TteRAcYvHDE1lTDInYiKiLB5XpVkkQ8TACfDv8peJHKKtiaq3B7uC7W6MzQapWk1qZlVKinDgCDZ6ar9v30uTf2wjDEe20SSgsJVVMbtZeZldwJfpVCGY8utmM5xBeQnj6UgbrDxNow2/2vzxmJD0x1SBMdOWeBXL180qBRQIcInPfYKRfUBCHAGYwcwl/EHO67X16L8P4CQ "Java (JDK) – Try It Online")
Port of my (with suggestions from Arnauld) JS answer. `etu` in `return` and `hil` in `while` make it impossible to golf to score 2.
`for` cannot be used here because:
* `;for` is ascending
* `for` cannot be used at the beginning of the lambda body (scope restrictions). It is possible to wrap it with `{}` but apparently using `while` saves bytes.
[Answer]
# Powershell, score 3, 44 bytes
```
($args|%{$i*=$_-ge$p;$p=$_;(++$i)}|sort)[-1]
```
Test script:
```
$f = {
(
$args|%{ # for each integer from argument list
$i*=$_-ge$p # -ge means >=.
# This statement multiplies the $i by the comparison result.
# A result of a logical operator is 0 or 1.
# So, we continue to count a current sequence or start to count a new sequence
$p=$_ # let $p stores a 'previous integer'
(++$i) # increment and return incremented as length of a current sequence
}|sort # sort lengthes
)[-1] # take last one (maximum)
}
@(
,(4, 1,1,2,1,1,4,5,3,2,1,1)
) | % {
$e,$a = $_
$r = &$f @a
"$($r-eq$e): $r"
}
```
Output:
```
True: 4
```
Explanation:
* The script takes integers as argument list ([spaltting](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting)).
* Each integer maps by a function to legnth of `contiguous sub-list that is increasing (not strictly)`. Then the script sorts lengthes and take a last (maximum) `(...|sort)[-1]`.
---
## Powershell 6, score 3, 43 bytes
```
$args|%{$i*=$_-ge$p;$p=$_;(++$i)}|sort -b 1
```
Same as above. One difference: `sort -b 1` is shortcut for `sort -Bottom 1` and means [1 element from the end of sorted array](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/sort-object?view=powershell-6). So we need not an index `[-1]`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), score 3 (15 bytes)
```
Z|[F|]F:^!C_%|M
```
[Run and debug it](https://staxlang.xyz/#c=Z%7C[F%7C]F%3A%5E%21C_%25%7CM&i=[1,1,2,1,1,4,5,3,2,1,1]%0A[]%0A[0]%0A[3,2,1]%0A[1,2,1,2]%0A%22Z%7C[F%7C]F%3A%5E%21C_%25%7CM%22&a=1&m=2)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~score 5, 87 bytes~~ score 2, ~~101~~ ~~93~~ ~~92~~ 101 bytes
```
lambda a,m=1,o=[1]:max(reduce(lambda B,c:[B[:-m]+[B[-m]+m],B+o][c[0]>c[m]],zip(a,a[m:]), o)) *(a>[ ])
```
[Try it online!](https://tio.run/##bVG7csMgEKzNV1wHREQTpdRELlzkJwgFgpNF9EADeOLk5xVky5Mm1cLtwd7uLd@p9/PrarxFaCBQStdRT63VoMXUVMI3slL1pK8soL0YZDt7EqaWJ1k/T6rIuMGkxKnwShr5oo5GTkqJH7cwLbScasUFeM7hiemjBMXXrFTGFHIDJwSvaIB2DS22QQhZgpsTdGx0MbFJL8wHKzaKc/7HSvW47CX67gOkHiHqAcF3kL5QD24@C@gx4AeNN9b0l3mIZVlSQix2cGaa1wTaRkqdZ1eKQJc/MsKCm@HhocoeanJwHdg3kw@HtmkLKW1uP@AYcS/lSKocSStvsLEQMOZsJcuOP72bb4ZMH4ThXIw4s4x3wU2uzQ92N6MOZ4zpPi@4SMV9D1HAgN/NvglTm7wivsmkS5g3tUdE538DXH8B "Python 2 – Try It Online")
Ooops! Thought this was code-golf first time through...
[Answer]
# [Dyalog APL](https://www.dyalog.com/), score 2, 20 bytes
```
{⍵≡⍬:0⋄⌈/≢¨⍵⊂⍨1,2>/⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79ZHnQsf9a6xMnjU3fKop0P/UeeiQytAwl1Nj3pXGOoY2ekDebX/H/VNfdQ2gXgNhrpAHlCTY9ij3s3qxOtT5yLZJh0gUwdEmuiY6hhD2P8B "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), score 3, 45 bytes
```
Max[Length/@SequenceCases[#,x_/;OrderedQ@x]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d83sSLaJzUvvSRD3yE4tbA0NS851TmxOLU4WlmnIl7f2r8oJbUoNSXQoSI2Vu2/g4JzRmJRYnJJalFxtBJJepViY/8DAA "Wolfram Language (Mathematica) – Try It Online")
`SequenceCases` and `OrderedQ` by themselves give a score of 3, so the score can't be improved without changing the approach significantly.
[Answer]
# Java (JDK), 126 bytes, Score 6
Golfed
```
private static int l(byte[] o){int m=0;int c=1;int p=0;for(byte i:o){if(m<c){m=c;}if(i>=p){p= i;c++;}else{c=1;p=0;}}return m;}
```
Ungolfed
```
private static int longest(byte[] input) {
int maxc = 0;
int consec = 1;
int prev = 0;
for (byte i : input) {
if (maxc < consec) {
maxc = consec;
}
if (i >= prev) {
prev = i;
consec++;
}
else {
consec = 1;
prev = 0;
}
}
return maxc;
}
```
Input
```
[112, 114, 105, 118, 97, 116, 101, 32, 115, 116, 97, 116, 105, 99, 32, 105, 110, 116, 32, 108, 40, 98, 121, 116, 101, 91, 93, 32, 111, 41, 123, 105, 110, 116, 32, 109, 61, 48, 59, 105, 110, 116, 32, 99, 61, 49, 59, 105, 110, 116, 32, 112, 61, 48, 59, 102, 111, 114, 40, 98, 121, 116, 101, 32, 105, 58, 111, 41, 123, 105, 102, 40, 109, 60, 99, 41, 123, 109, 61, 99, 59, 125, 105, 102, 40, 105, 62, 61, 112, 41, 123, 112, 61, 32, 105, 59, 99, 43, 43, 59, 125, 101, 108, 115, 101, 123, 99, 61, 49, 59, 112, 61, 48, 59, 125, 125, 114, 101, 116, 117, 114, 110, 32, 109, 59, 125]
```
[Answer]
**Kotlin, Score 6, 119 bytes**
```
fun x(a : IntArray){var m=1;var k=0;var d=1;while(k<a.size-1){if(a[k]<=a[k+1])m++;else{if(d<m)d=m;m=1};k++};println(d)}
```
[Try Online](https://rextester.com/live/ORBXZ48091)
Explanation
1. Step 1: Check for previous value to next value
2. Step 2: If previous value is less or equal then add plus 1 keep doing while condition
is true
3. Step 3: check previous count with next count, keep highest count in variable d.
[Answer]
# Kotlin, Score 4, 67 bytes
```
{a:IntArray->var i=0;var p=0;a.map{if(it<p){i=0};p=it;(++i)}.max()}
```
Main idea is: Transform each integer to length of contiguous sub-sequences that is increasing (not strictly). Return maximum.
* `a.map{...}` - for each integer in the array do
* `if(it<p){i=0}` - if current integer is less then a previous integer, then reset counter
* `p=it` - store current integer in the previous
* `(++i)` - increment counter and return value of the expression
* `.max()` - get maximun of all length
[Answer]
# [Ruby](https://www.ruby-lang.org/), 64 bytes
```
->e{e.size.downto(1).find{|l|e.each_cons(l).find{|c|c==c.sort}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y61OlWvOLMqVS8lvzyvJF/DUFMvLTMvpbompyZVLzUxOSM@OT@vWCMHJpxck2xrm6xXnF9UUltb@7@gtKRYIS062lDHUMdIB0Sa6JjqGAPZxmCWGUgsNvY/AA "Ruby – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), score: 2 (8 bytes)
```
⊇L≤₁&sLl
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FXu8@jziWPmhrVin1y/v@PNtQx1DHSAZEmOqY6xhB27P8oAA "Brachylog – Try It Online")
This code, according to [Brachylog’s code page](https://github.com/JCumin/Brachylog/wiki/Code-page), is the following string of char codes / integers:
```
[08, 4C, 03, 80, 26, 73, 4C, 6C]
[8, 76, 3, 128, 38, 115, 76, 108]
```
[Which results in a score of 2.](https://tio.run/##SypKTM6ozMlPN/r//1FXu8@jziWPmhrVin1y/v@PttBRMDfTUTDWUTA0ArKNgdjQ0BQiaGhgEfs/CgA)
### Explanation
```
⊇L L is a sublist of the input (trying from longest to shortest)
L≤₁ L is increasing
&sL L is also a contiguous sublist of the input
l Output the length of L
```
We need to use `⊇` to get the longest sublists first and then check that it is contiguous with `s`, because `s` does not try them longest first (see [this Brachylog tip](https://codegolf.stackexchange.com/a/231602/41723)).
[Answer]
# [Go](https://go.dev), score 4, 172 bytes
```
type y=int
type x=[]y
func f(q x)y{l,o:=*new(x),*new(x)
for _,e:=range q{n:=len(o)
if n>0&&o[n-1]>e{if len(l)<n{l=o}
o=append(*new(x),e)}else{o=append(o,e)}}
return len(l)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=1VJLTsMwEJXY1acYdVHFyEUtHwlFdU_QBfuqolFxSlTXTmM3tIp8EjYVgh0n4CZwGsZxUgo3QIo8ma_fm-fnl6U-fOTJYpUsBayTTJFsnevCwkU3Xdvu29am_dvPd7vPBex5piypf3d8OtuTdKsWkEYb2NF9JZmO-bkST9GOssaSVBdwz0TMi0ThBZtKxVwKFWlKshTUeNDr6anqD2djUWHApyQdqUpy7YjmSZ4L9RC1UwV1QhpRHRPahxwphN0Wqul2AfPX2WuZFLACDh5mNJnOED2tz4p0pEY8xjINMYcQdKyxpPMH9gQbOg08TccD6PVAT4MXsGO-LWgmUxg19VBn2xsRj_a-84fm4UrhvcAthE_4kboWv5ZlmEMcCVLkYGyxXSCpxSMSRidTS1ImErxaWFWr5KWNPJTdD-EhG7JL5s9rdsOuwr8jdzjAShWtcOX06KW1R4xvn_-n5zBH0DKQzlHb0pwo3gLyoQDJeLWwnkMz00gGeRW2GgnKsA-NQ1lw0rGqNAxChpKfDRpJT7ZZml_rrN3msR4OwX4D)
I'm pretty sure this is the absolute minimum this bit of code can achieve, because `=int` is ascending in terms of value.
If you change `y` to be `rune`, and `x=[] y` you then get hung up on `\nfor`. Unless someone finds a way to make case-insensitive keywords in Go, then 4 is the minimum score.
] |
[Question]
[
After all the fun we've had with polyglot challenges in the ([recent](https://codegolf.stackexchange.com/questions/97472/trick-or-treat-polyglot)) past, how about a challenge where the output can be in two languages?
Your answer needs to accept boolean input `b` and output the text `"true"` or `"false"`. The same code needs to output, when run in another language, `"waar"` or `"onwaar"` or any other translation of `true`and `false`.
**Input**
* Input is a clearly distinguishable truthy/falsey. Admissible are the actual values T/F, a bit, int or (empty) string.
* Input needs to be the same for all parts of your submission.
**Output**
* Output may be returned by a function, written to `STDOUT`, placed in a popup-window, 3D-printed and mailed etc.
* The output needs to represent the state of `b`. So a 'truthy' needs to output 'true', 'waar' ... and 'falsey' should lead to 'false', 'onwaar', etc.
* Different languages may use different output methods.
**Languages used**
* One of your outputs MUST be `"true"` and `"false"`.
* Different versions of programming languages count as different languages for this challenge.
* Different dialects of a human language count as different languages for this challenge.
* You may extend the polyglot to more than two programming languages. Every programming language needs to output a distinct human language.
The answer with the most languages incorporated will be declared the winner. When tied, bytecount is considered.
[Answer]
# 6 languages, 169 bytes
Expects `0\n` or `1\n` as input, and prints words in:
* Python 2 (Dutch `vals/waar`),
* Python 3 (French `faux/vrai`),
* Ruby (English `false/true`),
* CJam (Norwegian `usant/sant`),
* Golfscript (Danish `usand/sand`),
* Befunge-93 (Italian `falso/vero`).
---
```
"#{puts gets>?1;exit}"" "#"& 1v
""
print('vwfvaaarlauasrxi'[int(1/2*4+int(input()))::4])
""#";;;;ri"u">"sant"+o
""""
__END__
]0=~"u">"sand"""#@,,,,"vero" _"oslaf",,,,,@
```
[Answer]
## All the Funges, 6 languages, 146 bytes
üí• Now in 3D! üí•
```
A vv"faux"0"vrai"mv#<v&#;9*j"kslaf"6j"etke">:#,_@;
; >"otreic"0"oslaf"v^<
&^>"murev"0"muslaf">
&^&<"false"0"true"<
>_>:#,_@
^_^
```
*For clarity I've separated the two planes of code so you can see how they're layered. On disk these two blocks would be separated with a form feed character at the end of the line above.*
```
h"vals"0"waar"<
```
The rules did say different versions of a language count as separate languages, so this one is six versions of Funge/Befunge. :)
* Befunge-93 (Spanish - cierto/falso) [Try it online!](http://befunge.tryitonline.net/#code=QSB2diJmYXV4IjAidnJhaSJtdiM8diYjOzkqaiJrc2xhZiI2aiJldGtlIj46IyxfQDsKOyA-Im90cmVpYyIwIm9zbGFmInZePAomXj4ibXVyZXYiMCJtdXNsYWYiPgomXiY8ImZhbHNlIjAidHJ1ZSI8Cj5fPjojLF9ACl5fXgwgICBoInZhbHMiMCJ3YWFyIjw&input=MQ)
* Befunge-96 (Latin - verum/falsum) [Try it online!](http://befunge-96-mtfi.tryitonline.net/#code=QSB2diJmYXV4IjAidnJhaSJtdiM8diYjOzkqaiJrc2xhZiI2aiJldGtlIj46IyxfQDsKOyA-Im90cmVpYyIwIm9zbGFmInZePAomXj4ibXVyZXYiMCJtdXNsYWYiPgomXiY8ImZhbHNlIjAidHJ1ZSI8Cj5fPjojLF9ACl5fXgwgICBoInZhbHMiMCJ3YWFyIjw&input=MQ)
* Befunge-97 (French - vrai/faux) [Try it online!](http://befunge-97-mtfi.tryitonline.net/#code=QSB2diJmYXV4IjAidnJhaSJtdiM8diYjOzkqaiJrc2xhZiI2aiJldGtlIj46IyxfQDsKOyA-Im90cmVpYyIwIm9zbGFmInZePAomXj4ibXVyZXYiMCJtdXNsYWYiPgomXiY8ImZhbHNlIjAidHJ1ZSI8Cj5fPjojLF9ACl5fXgwgICBoInZhbHMiMCJ3YWFyIjw&input=MQ)
* Befunge-98 (English - true/false) [Try it online!](http://befunge-98.tryitonline.net/#code=QSB2diJmYXV4IjAidnJhaSJtdiM8diYjOzkqaiJrc2xhZiI2aiJldGtlIj46IyxfQDsKOyA-Im90cmVpYyIwIm9zbGFmInZePAomXj4ibXVyZXYiMCJtdXNsYWYiPgomXiY8ImZhbHNlIjAidHJ1ZSI8Cj5fPjojLF9ACl5fXgwgICBoInZhbHMiMCJ3YWFyIjw&input=MQ)
* Unefunge-98 (Norwegian - ekte/falsk)
* Trefunge-98 (Dutch - waar/vals)
Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis), all of the Befunge versions can now be tested online at [TIO](https://tio.run/). There aren't currently working implementations of the Unefunge and Trefunge variants, though, so for those I'd recommend [Rc/Funge](http://www.rcfunge98.com/).
`A` is ignored in Befunge 93 and 96, but is the *About Face* command in 97 and is unsupported in 98 and thus reflects. This means that 93 and 96 follow the `v` downwards while 97 and 98 wrap around to the opposite side of the playfield.
In Befunge 96 a `;` followed by space at the start of the line marks it as a comment, so that line is skipped and the interpreter continues to the `>` on the third line. In 93, though, the interpreter follows the `>` on the second line.
The 97/98 path continues on the first line from right to left, skipping over the section inside the `;` comment markers, bridges the `&` command, eventually reaching the U-bend sequence `v<^<`. In Unefunge, these direction changes aren't supported so the interpreter reverses direction and executes the previously skipped section in the comments. In Befunge/Trefunge it continues to the left.
In Befunge 97 the `m` command is unsupported and thus skipped, so the interpreter continues along the first line. In 98 it's 3D-only so it reflects in Befunge (2D) and the interpreter follows the `v` to the right of it down to the fourth line. In Trefunge (3D) it's a *High-Low* branch which transfers up a level along the z-axis to the second plane.
So other than the Unefunge case, we have each version gathering their string pair from a separate line before being directed to one of the `&` commands to get the user input. Those code paths then all merge together via the `^` commands in the second column, directing the program flow upwards through the top of the playfield, wrapping around to the bottom again.
Finally we have the `^_^` sequence which decides which path to follow based on the user input. If *0*, we go straight to the output sequence (`>:#,_`) writing out the *false* string. If *1*, we first execute `>_` which clears the first string off the stack, and thus output the *true* string.
[Answer]
# [Dyalog APL](https://dyalog.com), ~~243~~ 237 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319): 14 languages, extendable to 131\*
-6 bytes thanks to [Soaku](https://codegolf.stackexchange.com/users/72792/soaku).
Requires `‚éïIO‚Üê0` which is default on many systems. Prompts for input of `0` or `1`.
```
((⎕AV⍳'ëáàÆÅÄòðÓÈÇ')⍳⍎⎕D∩⍨4↑1⊃#⎕WG'APLVersion')⊃⎕⊃s¨⌽(s←{1↓¨⍵⊂⍨⍵=⊃⍵})';,true,adevarat,haqiqiy,otito,tunay,bener,prawda,dogru,vrai,that,wahr,vero,verdade,cierto;,false,fals,yolg''on,eke,mali,palsu,falsz,yanlis,faux,sai,falsch',18⍴',falso'
```
Depending on version (9.0 through 16.0, with minor versions) it outputs in English,
Spanish,
Portuguese,
German,
Vietnamese,
French,
Turkish,
Italian,
Polish,
Sundanese,
Filipino,
Yoruba,
Uzbek, or
Romanian, although without diacritics.
 `⎕AV⍳'ëáàÆÅÄòðÓÈÇ'` in the indices of the **A**tomic **V**ector (151 142 141 133 132 131 122 121 111 102 101 96)
`((`...`)‚ç≥`...`)` find the position of
‚ÄÉ`‚çé` the evaluated
‚ÄÉ`‚éïD‚à©‚ç®` intersection of **D**igits and
‚ÄÉ`4‚Üë` the four\* first characters of
 `1⊃` the second element of
‚ÄÉ`#‚éïWG'APLVersion'` the version number
`(`...`)⊃` then use that to pick among
`⎕⊃` the input'th (0: first; 1: second) element of
`s¨` the function *s* (which we will define shortly) applied to each of
`‚åΩ` the reverse of
`(s←{`...`})` *s* applied to – where *s* is defined as
 `1↓¨` the first character dropped from each of
 `⍵⊂⍨` the argument partitioned where
‚ÄÉ`‚çµ=` the characters of the argument are equal to
 `⊃⍵` the argument's first character
`';,true,adevarat,`...`,falsch',` this string prepended to
`18⍴',falso'` eighteen characters taken cyclically from that string
*\** Since version 12.1, the version number includes build number, so by increasing the number of characters taken from this string, it is easy to cover all [131 Latin script languages](https://en.wikipedia.org/wiki/List_of_languages_by_writing_system#Latin_script).
[Answer]
## 5 languages, 249 bytes
**Note: the `\r` and `\e` are literal line-feed and escape characters, but `\x5b` has to be as-is otherwise Ruby complains about the character class in the regex.**
A bit late to the party, and not a winner by any means, but I started working on a polyglot for the thanksgiving challenge and felt it might be a bit late so transformed it into this!
```
q=0//1;'''<?die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));?>/.to_s.ord;def input()gets.to_i;end;q=+q+0;True="Vrai";False="Faux";'+;sub a{<><1?Vals:Waar}q-
input=prompt;print=alert;True="Vero";False="Falso"//'#'''
a=[False,True];b=input();1-+1;print(a[b])
```
### Explanation
**Python: `True` / `False`**
```
q=0//1;'''<?die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));?>/.to_s.ord;def input()gets.to_i;end;q=+q+0;True="Vrai";False="Faux";'+;sub a{<><1?Vals:Waar}q-
input=prompt;print=alert;True="Vero";False="Falso"//'#'''
a=[False,True];b=input();1-+1;print(a[b])
```
Here we set `q` to `0//1` which is `0`, then we have a `'''` string that contains most of the other code, store an array containing `False` and `True` and indicies `0` and `1` respectively, assign the input to `b` (which should be `0` or `1` to signify `Falsy` and `Truthy`) then `print` the `b`th index of `a`, showing `False` or `True`.
---
**Ruby: `Vrai` / `Faux`**
```
q=0//1;'''<?die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));?>/.to_s.ord;def input()gets.to_i;end;q=+q+0;True="Vrai";False="Faux";'+;sub a{<><1?Vals:Waar}q-
input=prompt;print=alert;True="Vero";False="Falso"//'#'''
a=[False,True];b=input();1-+1;print(a[b])
```
As with the Python script, we set the variable `q`, but in Ruby this is set to `0 / /1;'''<?die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));?>/.to_s.ord`, as Ruby breaks this down as `0/` as "zero divided-by" and the following `/` as "beginning of regex literal". Using this literal I'm able to conceal the PHP code and begin Python's `'''`. We have to add `.to_s.ord` because the right operand to `/` has to be a `Fixnum`. After this we define a function `input()` and the variable `True` and `False` to contain their French counterparts and finally start a string `'` which continues onto the next line. Finally we create an array `a` which contains `"Vrai"` and `"Faux"` and select them using the `input()`ed number `0` or `1`.
---
**Perl: `Waar` / `Vals`**
```
'0//1;\'\'\'<?die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));?>/.to_s.ord;def input()gets.to_i;end;q}+q{0;True="Vrai";False="Faux";\'';sub a{<><1?Vals:Waar}'
input=prompt;print=alert;True="Vero";False="Falso"//\'#\'\'\'
a=[False,True];b=input();1'+1;print(a[b])
```
In Perl, the `q=..=`, `q+...+` and `q-...-` blocks are quoted literals using unusual delimiters, in the code above I've replaced these with `'...'`. Most of the code is contained in a literal string, but we do define `sub a` (which contains a `<><`!) that checks if `STDIN` is less than `1`, returning either `Waar` or `Vals`. The `print(a[b])` actually `print`s the result of calling the `sub` `a` with and argument of `[b]` which is an ArrayRef that contains the bare-word `b`.
---
**JavaScript: `Vero` / `Falso`**
```
q=0//1;'''<?die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));?>/.to_s.ord;def input()gets.to_i;end;q=+q+0;True="Vrai";False="Faux";'+;sub a{<><1?Vals:Waar}q-
input=prompt;print=alert;True="Vero";False="Falso"//'#'''
a=[False,True];b=input();1-+1;print(a[b])
```
The first line is mostly commented out by the division `0//1` (`//` is line comment in JavaScript) so we just set `q` to `0`. The next line deals with mapping the JS functions to their Python names and setting variables `True` and `False` to be the Italian strings, finally we execute the same as the Ruby code, setting a to an array of the Italian words and selecting using an `input` of `0` or `1`.
---
**PHP: `Ekte` / `Falsk`**
```
die("\r\e\x5bK".(fgetc(STDIN)?Ekte:Falsk));
```
Since PHP only executes code between `<?...?>` everything else is output as-is, so our code here simply prints a line-feed (to put us back to the beginning of the current line) and the ANSI escape sequence to clear to the end of the current line, followed by either `Ekte` or `Falsk` depending on whether the input char (`0` or `1`) is truthy or falsy.
[Answer]
# Pyth, Python - 28 bytes
```
#>"onwaar"yQ.q
print input()
```
[Answer]
# C#, Java, 104 Bytes
Golfed:
```
String M(Boolean b){String s=b+"";if(s=="True")return "Wahr";if(s=="False")return "Falsch";return b+"";}
```
Ungolfed:
```
class MultiLingualChallenge
{
public String M(Boolean b)
{
String s = b + "";
if (s == "True")
return "Wahr";
if (s == "False")
return "Falsch";
return b + "";
}
}
```
Test:
**C#**
```
Console.WriteLine(new MultiLingualChallenge().M(true));
//Wahr
Console.WriteLine(new MultiLingualChallenge().M(false));
//Falsch
```
**Java**
```
System.out.println(new MultiLingualChallenge().M(true));
//true
System.out.println(new MultiLingualChallenge().M(false));
//false
```
Explanation:
When calling `ToString()` or `toString()` on a Boolean in C# and Java respectively, C# prints the string with a capital first letter, `True` and `False`, but Java prints all in lower case `true` and `false`.
```
Console.WriteLine(true+"");
//True
System.out.println(true+"");
//true
```
[Answer]
# 2 languages, 60 bytes
```
print('onwaar'[2*int(input()):]);1#¶ị“¡ẈẆ“⁸1»
```
Languages are:
* Jelly `true` `false`
* Python3 `waar` `onwaar`
Note: There are UTF-8 bytes, not Jelly bytes.
[Answer]
# Lua/JavaScript, 68 bytes
```
x=1//1print(...and"true"or"false")
--x;alert(prompt()?"vrai":"faux")
```
Don't know why I golfed it; I just felt like it.
[Answer]
# JavaScript / BF
In both these languages, no input is considered as false and any input is considered true.
When you see the structure of the program rotated 90 degrees to the left, the BF symbols look like towers in a city :)
[Try it online (BF true testcase)!](http://brainfuck.tryitonline.net/#code=Y29uc29sZS5sb2cocHJvbXB0KCk_ImhpIjoibm8iKQovKgogICAgICAgICAgID4sWz4KKyAgICAgICAgICA8PF0-PlstPi08XQorICAgICAgICAgID5bPC0-Wy1dXTw-Wy1dPFs-PgorKysgICAgICAgIFstPgorKysrICAgICAgIDxdPlstPgorKysrKysrKysrIDxdPi0tLS4-XT4KKysrKysrKysrKyBbLT4KKysrKysrKysrKyA8XQorKysgICAgICAgIFstPgorKysrKyAgICAgIDxdPi48CisrKysgICAgICAgWy0-LS0tLTxdPi0tLjwKKysrICAgICAgICBbLT4KKysrKyAgICAgICA8XT4KKyAgICAgICAgICAuPAorKysgICAgICAgIFstPi0tLTxdPi0uCiov&input=dHJ1ZQ)
[Try it online (BF false testcase)!](http://brainfuck.tryitonline.net/#code=Y29uc29sZS5sb2cocHJvbXB0KCk_ImhpIjoibm8iKQovKgogICAgICAgICAgID4sWz4KKyAgICAgICAgICA8PF0-PlstPi08XQorICAgICAgICAgID5bPC0-Wy1dXTw-Wy1dPFs-PgorKysgICAgICAgIFstPgorKysrICAgICAgIDxdPlstPgorKysrKysrKysrIDxdPi0tLS4-XT4KKysrKysrKysrKyBbLT4KKysrKysrKysrKyA8XQorKysgICAgICAgIFstPgorKysrKyAgICAgIDxdPi48CisrKysgICAgICAgWy0-LS0tLTxdPi0tLjwKKysrICAgICAgICBbLT4KKysrKyAgICAgICA8XT4KKyAgICAgICAgICAuPAorKysgICAgICAgIFstPi0tLTxdPi0uCiov&input=)
```
console.log(prompt()?"true":"false")
/*
>,[>
+ <<]>>[->-<]
+ >[<->[-]]<>[-]<[>>
+++ [->
++++ <]>[->
++++++++++ <]>---.>]>
++++++++++ [->
++++++++++ <]
+++ [->
+++++ <]>.<
++++ [->----<]>--.<
+++ [->
++++ <]>
+ .<
+++ [->---<]>-.
*/
```
## Explanation
### JavaScript
If the `prompt` is true (ie not empty because `prompt` returns a string), outputs `true`, or else outputs `false`.
### BF
Outputs `sand` (Danish for true) if there is an input, or else outputs `usand` (false) if the input is empty.
**TL;DR** If input is not empty (ie true), don't output anything. If input is empty (ie false), output `u`. Then, regardless whether the input is true or false, output `sand`.
I have taken inspiration from <https://esolangs.org/wiki/Brainfuck_algorithms> with which I constructed the logic of my program.
Take input. If input is not empty, increment memory, let's call this cell "Cell A". End if-statement
```
>
,[
>+
<<
]>
```
Compares the value of "Cell A" with `0`. If they are equal, let "Cell B" be `1`, or else let it be `0`.
```
>
[->-<]+>[<->[-]]<
```
If "Cell B" is 1, then output `u`. Close if-statement
```
>[-]<
x[>>
+++[->++++<]>[->++++++++++<]>---.
>]
```
Output `sand`
```
>
++++++++++[->++++++++++<]+++[->+++++<]>.
<++++[->----<]>--.
<+++[->++++<]>+.
<+++[->---<]>-.
```
[Answer]
# Haskell, JavaScript, Python, 115 Bytes
```
q=1//1#1;f True="waar";f False="false";a//b=0;a#b=0{-
1//1;f=lambda x:"wahr"if x else"falsch";"""
f=x=>x+[]//"""#-}
```
] |
[Question]
[
Can you write a program that renders to screen a group of pixels exploding apart (as in a simple particle engine) and can you do this in any remarkably small number of characters (key strokes)? (Recall the game lemmings, when those little guys would explode and their little pixel pieces fly apart.)
Someone programmed [a simple particle](http://processing.org/learning/topics/simpleparticlesystem.html) system here as a [Processing](http://processing.org/) sketch and it is pretty hefty compared to what I think others should be able to accomplish if they tried. But I'd be much more impressed if it someone could do the same in c++ and sdl, or even java or c#.
[Answer]
## Python, 245 chars
```
import random,time
R=lambda:random.randrange(-999,999)/1e3
P=[(40+20j,R()+1j*R())for i in' '*20]
for i in' '*20:
C=([' ']*80+['\n'])*40
for p,v in P:C[int(p.real)+81*int(p.imag)]='*'
print''.join(C);P=[(p+v,v*.95)for p,v in P];time.sleep(.1)
```
[Answer]
## C#, WPF – 1523
Not terribly serious; this was mainly an attempt whether it actually worked.
What I'm doing here is using an ItemsControl (Menu, since it's shorter) in WPF to display particles via data binding and templating. A data template controls how the particles look like (in this case a simple circle) and data binding controls color and position of the particles.
Each particle has a position, a color and a direction which get updated by a timer. Initially a bunch of particles are generated in the center of the window with (normal-distributed) random directions. That collection gets data-bound to the ItemsControl which then handles displaying the particles automatically, whenever the properties are updated. Particles are dragged down a bit due to gravity.
It got a little lengthy, admittedly. But at least it looks nice:

It can surely be made shorter by omitting:
* gravity, causing particles to expand uniformly to all sides;
* the normal distribution for the initial vectors, causing the particles to expand in a sparse »box«;
* the brightness variation, leaving particles black.
I opted not to do so in the interest of aesthetics. This solution is way longer than almost anything else regardless. The data-binding and templating approach might be elegant but it's also quite verbose compared with simply updating a bitmap. (Note: I got it down to **1356** by leaving all of the above out, but it looks horrible then.)
The code is distributed in three files, which are given here in formatted form for legibility:
[**App.xaml**](http://svn.lando.us/joey/Public/SO/CG2571/Particles/Particles/App.xaml)
```
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" StartupUri="W.xaml"/>
```
[**W.xaml**](http://svn.lando.us/joey/Public/SO/CG2571/Particles/Particles/W.xaml)
```
<Window x:Class="W" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Menu Name="i">
<Menu.ItemTemplate>
<DataTemplate>
<Ellipse Width="2" Height="2" Fill="#000" Opacity="{Binding O}">
<Ellipse.RenderTransform>
<TranslateTransform X="{Binding X}" Y="{Binding Y}"/>
</Ellipse.RenderTransform>
</Ellipse>
</DataTemplate>
</Menu.ItemTemplate>
<Menu.Template>
<ControlTemplate>
<ItemsPresenter/>
</ControlTemplate>
</Menu.Template>
<Menu.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</Menu.ItemsPanel>
</Menu>
</Window>
```
[**W.xaml.cs**](http://svn.lando.us/joey/Public/SO/CG2571/Particles/Particles/W.xaml.cs)
```
using M = System.Math;
using T = System.Timers.Timer;
using System;
using System.ComponentModel;
partial class W
{
int a;
T t = new T(99);
public W()
{
InitializeComponent();
Height = Width = 500;
var r = new Random();
Func<double> n = () => 2 * (M.Sqrt(-2 * M.Log(r.NextDouble())) * M.Sin(6 * r.NextDouble()));
var l = new System.Collections.Generic.List<P>();
for (; a++ < 300; )
l.Add(new P { X = 250, Y = 250, f = n(), g = n() });
i.ItemsSource = l;
t.Elapsed += delegate
{
foreach (P x in l)
{
x.X += x.f;
x.Y += x.g += .2;
x.O = M.Max(1 - M.Sqrt(M.Pow(250 - x.X, 2) + M.Pow(250 - x.Y, 2)) / 250, 0);
}
};
t.Start();
}
}
class P : System.Windows.ContentElement, INotifyPropertyChanged
{
public double y, f, g;
public double X { get; set; }
public double O { get; set; }
public double Y
{
get { return y; }
set
{
y = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(""));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
```
[Answer]
# postscript - 287 244 chars
```
currentpagedevice/q{exch def}def/PageSize get/z{dup 3 1 roll add exch 4 2 roll}def{2
div}forall/y/r{rand 2 27 exp div 8 sub}def q/x q[99{[x r y r]}repeat]50{dup{aload/t q
3 index 2 index 4 4 rectfill 1 sub z z t astore pop}forall showpage}repeat
```
run with `gs -dNOPAUSE asplode.ps`
You could even print it out and make a flipbook
[Answer]
# Javascript - 268 chars
Here's a 1 dimensional, 2 particle, explosion:
```
javascript:d=document;c=d.createElement('canvas');d.body.appendChild(c);g=c.getContext("2d");function e(x,y,m){g.arc(x,y,m,0,2*Math.PI,false);g.fill()}function s(a,b,v,t){c.width=c.width;e(50+t*v,50,b);e(50+t*b*v/(b-a),50,a-b);setTimeout(function(){s(a,b,v,t+1)},100)};s(9,5,1,0)
```
To run it, open an about:blank page in a good web browser, paste into the url bar and press enter. You can modify the explosion by editing the values at the end in `s(10,5,1,0)`. The first value is the size of the particle that is exploded. The second value is the size of the particle that is exploded out of it. The third value is the speed of the particle exploded out of it. Leave the '0' as it is.
[Answer]
## APL (~~120~~ 118)
It has the same kind of output as the Python entry (i.e. it just outputs the states on a character grid). Only the grid is 30x15 and the particle origin is at 15x7.
```
⍎⊃,⌿(9⍴⊂'(⎕DL.1)⊢{{(A+2↑⍵),0.95×A←2↓⍵}¨⍵⊣⎕←'' ⍟''[1+(⍳15 30)∊2↑¨⌊⍵]}'),⊂',⌿⍉10 4⍴⍎''⍬'',420⍴'',(7 15,.01×99-?2⍴199)'''
```
[Answer]
### JavaScript ~~502~~ ~~500~~ 496
This is a combination of the [Joey](https://codegolf.stackexchange.com/users/15/joey)'s and [david4dev](https://codegolf.stackexchange.com/users/682/david4dev)'s answers (it's a shameless copy of Joey's algorithm implemented using Javascript/canvas ☺):
```
W=500;H=250;function r(){return 2*m.sqrt(-2*m.log(m.random()))*m.sin(6*m.random())}function n(){z=[];for(i=W;i;i--){s={};s.x=s.y=H;s.f=r();s.g=r();z.push(s)}}function w(){x.clearRect(0,0,W,W);z.forEach(function(a){a.x+=a.f;a.y+=a.g+=.2;x.fillStyle="rgba(0,0,0,"+m.max(1-m.sqrt(m.pow(H-a.x,2)+m.pow(H-a.y,2))/H,0)+")";x.fillRect(a.x,a.y,2,2)})}z=[];m=Math;d=document;c=d.createElement("canvas");c.width=c.height=W;d.body.appendChild(c);x=c.getContext("2d");n();setInterval(n,2e3);setInterval(w,10)
```
JSFiddle preview: <http://jsfiddle.net/GVqFr/60/> (you can press the TidyUp button to format the code nicely)
[Answer]
### Bash 380
```
C="4443311177"
t=".-xxXMXxx-."
alias c='echo -e "\e[2J"'
g(){
echo -e "\e[1;$4\e[$2;$1H$3"
}
f(){
x=$1
y=$2
p=$((2-RANDOM%5))
q=$((2-RANDOM%5))
for i in {-5..5}
do
x=$((x+p))
y=$((y+q))
n=$((5+i))
c=$((5+i))
g $x $y ${t:n:1} 3${C:c:1}m
w=$(printf "%04i\n" $((5*i*i)))
sleep ${w/0/0.}
g $x $y " " 3${C:c:1}m
done
}
e(){
c
for i in {1..10}
do
f $((COLUMNS/2)) $((LINES/2)) &
done
}
```
Call e like explode.
### update: colorized
t=text, c=cls, g=gotoxy, f=fly, C=COLOR
[Answer]
## C with SDL, 423 chars
Since the original problem description explicitly mentioned SDL, I felt it was past time that an SDL solution was submitted. Unfortunately, the names of the SDL function and structs aren't particularly terse, so this program is a little long. In fact, I can't even leave out the `#include`.
```
#include<math.h>
#include"SDL.h"
SDL_Surface*s;SDL_Event e;SDL_Rect p;int i,n;double q[256];main(){
SDL_Init(SDL_INIT_VIDEO);s=SDL_SetVideoMode(320,320,32,0);
for(srand(time(0));e.type-SDL_QUIT;n=-~n%64){
for(i=256*!n;i;q[--i]=rand()%65536*9.5874e-5);
for(SDL_FillRect(s,0,i=0);++i<256;SDL_FillRect(s,&p,-n*67372036))
p.x=160+cos(q[i])*q[i-1]*n,p.y=160+sin(q[i])*q[i-1]*n,p.w=p.h=1;
SDL_Flip(s);SDL_Delay(50);SDL_PollEvent(&e);}}
```
(Since the code is already so huge, I left in some extra bits so that it would compile without warnings. I miss compiling without warnings sometimes. Removing them would save about 30 or so chars.)
The animation runs in an infinite loop. Close the window to exit the program. Each explosion uses a new set of random particles.
I would also like to point out the number`67372036` in the code. It appears in the expression for the last argument in the second call to `SDL_FillRect()`. As the code stands, the explosion is rendered entirely in grays. Changing this number slightly will add a very subtle but pleasant color effect to the explosion. The number `67372032` colors the particles at the start of the explosion, while the number `67372034` provides a color effect as they fade out at the end. Other numbers can produce less subtle color-cycling effects. I encourage you to try them out.
[Answer]
After seeing some of the other great examples here, I decided to give it a go, and make a particle function that fits in **[140byt.es](http://www.140byt.es/)**
# Javascript, 282 chars
(*138* chars particle function and *150* chars basic canvas drawing boilerplate)
```
p=function(a,t,x,y,n,g,s,i,d){with(Math)for(i=n;i--;d=cos(i*sin(i*s)),a.globalAlpha=n/t/i,a.fillRect(x+t*sin(i)*d, y+t*cos(i)*d+t*g,2,2));};d=document;a=d.body.appendChild(d.createElement('canvas')).getContext('2d');t=setInterval("a.clearRect(0,0,300,150);p(a,t++, 50,50,1e3,.2,1)")
```
**[Live JSFiddle example here](http://jsfiddle.net/nyeSD/)**
By making the code fully procedural I no longer needed any array or object-assignment code, reducing the size a lot. Making a procedural effect also has some other nice side-effects.
The code could be made smaller by ommitting Gravity, Seeds, Number of Particles, etc, but I think these features are too nice to remove ;).
# Features
* Configurable X,Y center of explosion.
* Configurable number of particles
* Gravity in the vertical direction: Have your particles fall down or fly up!
* Seedable, each seed has its own explosion and will show exactly that explosion each time, across computers.
* Slowmotion, Fast Forward and playing explosions Backwards is all possible, due to the procedural way the effect is created.
* Size:138 bytes.
[Also check it out on GitHub](https://gist.github.com/Qqwy/6810542), for an annotated version.
[Answer]
# Python with PyGame, 240 chars
I realize that there is already a solution in python, but since that one just prints characters, I thought it would be worthwhile to make one that draws a nice animation.
Ungolfed, what I started with:
```
import math
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
particles = [(random.gauss(0,.5), random.uniform(0,6.28318)) for i in range(2000)]
for i in range(399):
screen.fill((255,255,255))
for speed, angle in particles:
distance = i * speed
x = 400 + distance * math.cos(angle)
y = 400 + distance * math.sin(angle)
screen.set_at((int(x), int(y)), (0,0,0))
pygame.display.flip()
```
After much hackery. Fullscreen to save some characters. Not using sound or fonts, so I think `init()` is unnecessary (it works for me).
```
import math as m,random,pygame
d,x,g=pygame.display,range(999),random.gauss
s,e=d.set_mode(),[(g(0,.2),g(0,9))for i in x]
for i in x:
d.flip(),s.fill([255]*3)
for v,a in e:
y=400+i*v*m.cos(a),400+i*v*m.sin(a)
s.set_at(map(int,y),[0]*3)
```
[Answer]
# Python -- 327 chars
Intresting things:
* Use complex number as 2D vector
* `(v * cos(a), v * sin(a))` implemented as `v*e**(1j*a)`
* Looks like a 3D explosion.
* Gravity.
.
```
import pygame as P,random as R,math
R=R.random
D=P.display
D.init()
W=800
S=D.set_mode((W,W))
T=P.time.Clock()
C=lambda v:map(int,(v.real,v.imag))
X=[(8+R())*math.cos(R()*1.57)*2.7**(1j*R()*6.28) for i in range(999)]
for t in range(250):
D.flip();T.tick(30);S.fill(2**24-1)
for v in X:S.set_at(C(v*t+.005j*t*t+W/2*(1+1j)),0)
```
[Answer]
# dwitter 112
```
c.width^=0
t?o.push({X:1e3,Y:500,U:S(99*t),V:C(9*t)}):o=[]
o.map(a=>{a.X+=a.U,a.Y+=a.V,x.fillRect(a.X,a.Y,9,9)})
```
try it out by copy/pasting the code to dwitter.net
] |
[Question]
[
## Introduction
In [this TED-Ed video](https://www.youtube.com/watch?v=SXXrQlJoNsw) (which I'd recommend watching first), a puzzle is presented. 27 unit cubes must be painted with one of red, green, or purple on each face, so that they can be reassembled into a large 3x3x3 cube that shows only red on the outside, then a different arrangement that shows only green, and then only purple. One solution is presented at the end of the video, but it is not obviously generalisable (and [there are lots more solutions](https://brilliant.org/practice/color-cube-assembly/)).
Then, in [this lazykh video](https://www.youtube.com/watch?v=5UGrxA18Qao), a simple algorithm for solving the puzzle is presented. It is as follows:
1. Paint the faces that currently make up the exterior of the large cube green
2. For each dimension of the cube (X, Y, Z), shift the arrangement of the cubes over in that direction by 1 unit
3. Repeat these steps for each colour
The lazykh video has graphics which explain the algorithm more clearly than can be done in this textual medium, so I suggest you watch that as well.
This algorithm generalises easily for higher sizes and numbers of colours than 3 (e.g. a 5x5x5 cube which must be painted with 5 different colours). Interestingly, it also generalises to higher dimensions than 3, but I'll save that for a different challenge.
## Challenge
Given the size \$ n \$ (where \$ n \$ is a positive integer) of the large cube, output *a* solution to the \$ n \times n \times n \$ version of this generalised puzzle.
Using the algorithm described above is certainly not the only way to find a solution, but I've included it as a starting-point. You are free to work out the solution however you choose.
Output should be given as a list of 6-tuples (or similar structure), representing the face colours of each small cube. The elements of the tuples should be from a predictable sequence of distinct values, (e.g. integers from \$ 0 \$ to \$ n - 1 \$), each representing a colour. The faces within a tuple can be in whatever order you choose but **it must be consistent**. The list should be flat and \$ n ^ 3 \$ in length, but its elements can be in any order (since they will need to be rearranged anyway for assembly into the \$ n \$ alien probes).
## [Test cases](https://gist.github.com/pxeger/a82bdce4427f487490ce0df19840807a)
```
Input Output
1 [(0, 0, 0, 0, 0, 0)]
2 [(0, 0, 0, 1, 1, 1), (1, 0, 0, 0, 1, 1), (0, 1, 0, 1, 0, 1), (1, 1, 0, 0, 0, 1), (0, 0, 1, 1, 1, 0), (1, 0, 1, 0, 1, 0), (0, 1, 1, 1, 0, 0), (1, 1, 1, 0, 0, 0)]
3 [(0, 0, 0, 2, 2, 2), (2, 0, 0, 1, 2, 2), (1, 0, 0, 0, 2, 2), (0, 2, 0, 2, 1, 2), (2, 2, 0, 1, 1, 2), (1, 2, 0, 0, 1, 2), (0, 1, 0, 2, 0, 2), (2, 1, 0, 1, 0, 2), (1, 1, 0, 0, 0, 2), (0, 0, 2, 2, 2, 1), (2, 0, 2, 1, 2, 1), (1, 0, 2, 0, 2, 1), (0, 2, 2, 2, 1, 1), (2, 2, 2, 1, 1, 1), (1, 2, 2, 0, 1, 1), (0, 1, 2, 2, 0, 1), (2, 1, 2, 1, 0, 1), (1, 1, 2, 0, 0, 1), (0, 0, 1, 2, 2, 0), (2, 0, 1, 1, 2, 0), (1, 0, 1, 0, 2, 0), (0, 2, 1, 2, 1, 0), (2, 2, 1, 1, 1, 0), (1, 2, 1, 0, 1, 0), (0, 1, 1, 2, 0, 0), (2, 1, 1, 1, 0, 0), (1, 1, 1, 0, 0, 0)]
6 https://gist.github.com/pxeger/a82bdce4427f487490ce0df19840807a#file-6-txt
20 https://gist.github.com/pxeger/a82bdce4427f487490ce0df19840807a#file-20-txt
```
## Rules
* Your solution does not need to complete in reasonable time for large \$ n \$, but it must work in theory
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
* You may use [any sensible I/O method](https://codegolf.meta.stackexchange.com/q/2447)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~36~~ ~~34~~ ~~33~~ 30 bytes
```
#-1|#&~Array~#~Tuples~3/.#->0&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1nXsEZZrc6xqCixsk65LqS0ICe1uM5YX09Z185A7X9AUWZeSTSQneagHKtWF5ycmFdXzWWow2Wkw2Wsw2UGZBhw1f4HAA "Wolfram Language (Mathematica) – Try It Online")
Returns a length-\$n^3\$ list of \$\{x|x',y|y',z|z'\}\$ colorings.
[Verify](https://tio.run/##bY9BiwIxDIXP218RGPCwZMGZPS4DFVZPCiJ4Kj2U2Q4OjCnWeJDS@etj7SqiuyQh4X08yNsb3tm94a4xY1uPofgosYgT@b7sjjzMvDfnIRSYKg4r9zMUk/HbKQG@buW82TlF@ktAlqA1jT1CDcErBVDirO/zpLPUGsUbAGRED1Q9oSzdnGlVfxDdXa/o7kz9@S@iqyuhmN6Fte@I1fxwMr2U@W2ELXWO5KI3zJZ@xWu0lHTj2LBd2paVx5DCYBm1ACQtMBBW06jHCw) with a \$n\times n\times n\$ matrix output.
---
Explanation:
Consider a cube \$x\$th from the front in some initial configuration. If the frontmost layer of cubes is painted \$1\$, the second \$2\$, etc., so that the color number increments with each shift, the front face of the cube will be painted \$x\$. After one more shift, the cube will be in the backmost layer, so the back face is painted \$x+1\$.
The same logic applies in other dimensions, so we can paint the cube at position \$(x,y,z)\$ with colors \$(x,y,z,x+1,y+1,z+1)\$ (modulo \$n\$).
```
#-1|#&~Array~#~Tuples~3 (* 3-tuples of {0|1, 1|2, ..., n-1|n} *)
/.#->0& (* and replace n with 0. *)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
NθFθFθFθF⟦ικλ⟧⭆²﹪⁺μνθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orLb9IAchQwEpHZ@ooZOso5MRqKgQUZeaVaASXAKl038QCDSMdBd/8lNKcfI2AnNJijVwdhTxNHYVCTSCw/v/f@L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Outputs the faces in order `162534` (relative to dice numbering). Explanation:
```
Nθ
```
Input `n`.
```
Fθ
```
Loop over the x-axis.
```
Fθ
```
Loop over the y-axis.
```
Fθ
```
Loop over the z-axis.
```
F⟦ικλ⟧
```
For each coordinate...
```
⭆²﹪⁺μνθ
```
... output it, then output it incremented modulo `n`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~39~~ 36 bytes
* -3 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor).
```
f n=mapM(\_->zip<*>(n:)$[1..n])"..."
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY3scBXIyZe164qs8BGy04jz0pTJdpQTy8vVlNJT09P6X9uYiZEVbxGTKauXUp@dUFRZl6JQqY1mFZJU8is1QTpMIn9DwA "Haskell – Try It Online")
The relevant function is `f`, which takes as input the integer `n` and returns a list of \$n^3\$ cubes; each cube is represented as a list of three pairs, such as `[(1,2),(1,3),(2,3)]`. Each pair represents the colors of two opposite faces, and colors are numbered from `1` to `n`.
## How?
The strategy described by the OP is equivalent to the following. Consider the cube at coordinates \$(x,y,z)\$, with \$1\le x,y,z\le n\$. Paint the two faces orthogonal to the \$x\$ axis with colors \$x\$ and \$x+1\$ (considered \$\mod n\$). Similarly, color the faces orthogonal to the \$y\$ axis with colors \$y\$, \$y+1\$ and the faces orthogonal to the \$z\$ axis with colors \$z\$, \$z+1\$.
Therefore, to generate the \$n^3\$ colored cubes, we just have to independently pick three pairs of colors from the set
$$
\{(1,2),(2,3),\ldots,(n-1,n),(n,1)\},
$$
and this is exactly what the code above does.
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~113 ... 108~~ 95 bytes
*Saved 2 bytes thanks to [@EliteDaMyth](https://codegolf.stackexchange.com/users/100752/elitedamyth)*
*Saved 1 byte thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)*
Prints the cubies.
```
n=>{for(x=n**3;x--;print(a))for(a=[c=n];c--;)for(j=6;j--;)(x/n**(j>>1)%n+c)%n^j%2*~-n?0:a[j]=c}
```
[Try it online!](https://tio.run/##TYvRCoIwGIXve4r/RtwcqyyoaP32IGIwRoZD/omKCGKvvra66eYcznfOsXrSg@mbbpTTxdfoCYuldj2bkbLsqGYpVdc3NDLNeeQaS4NUKROKL7B4UjYGNu/ChdmiyHlCwgR52OSQvSXd91dd2grN6uOFACFXQHBDOAcXgsOyATCOBtc@t617sTSOUhBAXIWqZj//nwSw@g8 "JavaScript (V8) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~67 66 56~~ 54 bytes
```
->n{(1..n**3).map{|y|(0..5).map{|x|(x+y/n**(x/2))%n}}}
```
[Try it online!](https://tio.run/##NY7BDoMgEETvfAWXRrCyVk2P9kcIaZTEU0uNxQhx@XYqWi@b2cybnZ3m3sehjeJhVlYBmDxvOLy7cUWP7AZw/28Ombv6cvOZK2vOLyaEEFPkJDQSOs72u02qD0kzIURG6CC1OqAeR9oHkph0HTSH4dXZ524uKKuiLhp1Vu45/ZmNTe/4Q7KFt63b2lEqEuIP "Ruby – Try It Online")
### Explanation:
* Look at the existing answers
* Try to find a pattern in the results
* Replicate the pattern without understanding the underlying process
* Feels like cheating.but it works
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṗ3ż’$%
```
A monadic Link accepting a positive integer that yields a list. Each element is a pair of lists, the first gives the colours of three faces around a corner and the second gives the colours of their respective opposites.
**[Try it online!](https://tio.run/##y0rNyan8///hzunGR/c8apipovr//38zAA "Jelly – Try It Online")**
### How?
The strategy is to paint each of the \$n^3\$ cubes in a consistent direction (e.g. always clockwise) around any corner with a different one of the \$n^3\$ possible \$3\$-tuples of the \$n\$ colours. Then chose any ordering of the colours and paint every unpainted face with the "next" colour after the painted face it is opposite. This gives the same resulting painting as the strategy given in the question, just in a different order.
```
ṗ3ż’$% - Link: integer, n
3 - three
ṗ - (implicit range [1..n]) Cartesian power (3) -> all 3-tuples made from [1..n]
$ - last two links as a monad - f(x=that):
’ - decrement (x) (vectorises)
ż - (x) zip with (that)
% - modulo (n) (vectorises)
```
[Answer]
# [R](https://www.r-project.org/), 53 bytes
```
n=scan();cbind(e<-expand.grid(a<-1:n-1,a,a),(e+1)%%n)
```
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOjkpMy9FI9VGN7WiIDEvRS@9KDNFI9FG19AqT9dQJ1EnUVNHI1XbUFNVNU/zv/F/AA "R – Try It Online")
Returns a matrix with rows corresponding to different small cubes, and columns - to their faces.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
L3ãεD>‚I%
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fx/jw4nNbXeweNczyVP3/3xgA "05AB1E – Try It Online")
```
L3ãεD>‚I% # full program
ε # replace each element in...
ã # all lists of length...
3 # literal...
ã # of elements in...
L # [1, 2, 3, ...,
# ..., implicit input...
L # ]...
ε # with...
‚ # [...
# (implicit) current element in map...
‚ # , ...
D # (implicit) current element in map...
> # plus 1...
‚ # ]...
# (implicit) with each element...
% # modulo...
I # input
# (implicit) exit map
# implicit output
```
] |
[Question]
[
Write the shortest code you can solving the following problem:
**Input:**
An integer X with `2 <= X` and `X <= 100`
**Output:**
Total combinations of 2, 3, and 5 (repetition is allowed, order matters) whose sum is equal to X.
**Examples:**
Input: `8`
Output: `6`, because the valid combinations are:
```
3+5
5+3
2+2+2+2
2+3+3
3+2+3
3+3+2
```
Input: `11`
Output: `16`, because the valid combinations are
```
5+3+3
5+2+2+2
3+5+3
3+3+5
3+3+3+2
3+3+2+3
3+2+3+3
3+2+2+2+2
2+5+2+2
2+3+3+3
2+3+2+2+2
2+2+5+2
2+2+3+2+2
2+2+2+5
2+2+2+3+2
2+2+2+2+3
```
Input: `100`
Output: `1127972743581281`, because the valid combinations are ... many
Input and output can be of any reasonable form.
The lowest byte count in each language wins.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~46~~ 45 bytes
thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for -1 byte
```
f=lambda n:n>0and f(n-2)+f(n-3)+f(n-5)or n==0
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc8qz84gMS9FIU0jT9dIUxtEGUMoU838IoU8W1uD/2lARqZCZp6ChY6CoaEVl4JCQVFmXglQT6bmfwA "Python 2 – Try It Online")
[Answer]
# [Oasis](https://github.com/Adriandmen/Oasis), 9 bytes
```
cd5e++VT1
```
[Try it online!](https://tio.run/##y08sziz@/z85xTRVWzssxPD///@GBgYA "Oasis – Try It Online")
**Explanation**
```
1 # a(0) = 1
T # a(1) = 0, a(2) = 1
V # a(3) = 1, a(4) = 1
# a(n) =
c + # a(n-2) +
d + # a(n-3) +
5e # a(n-5)
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 9 bytes
```
/sM{y*P30
```
**[Try it here!](http://pyth.herokuapp.com/?code=%2FsM%7By%2aP30&input=5&debug=0)**
# [Pyth](https://pyth.readthedocs.io), 16 bytes
```
l{s.pMfqT@P30T./
```
**[Try it here](http://pyth.herokuapp.com/?code=l%7Bs.pMfqT%40P30T.%2F&input=11&debug=0)**
### How?
1. Generates the prime factors of **30**, namely **[2, 3, 5]**, gets the powerset of it repeated **N** times, removes duplicate elements, sums each list and counts the occurrences of **N** in that.
2. For each integer parition **p**, it checks whether **p** equals **p ‚à© primefac(30)**. It only keeps those that satisfy this condition, and for each remaining partition **k**, it gets the list of **k**'s permutations, flattens the resulting list by 1 level, deduplicates it and retrieves the length.
[Answer]
# Perl, 38 bytes
Includes `+1` for `p`
```
perl -pE '$_=1x$_;/^(...?|.{5})+$(?{$\++})\1/}{' <<< 11; echo
```
Interesting enough I have to use `\1` to force backtracking. Usually I use `^` but the regex optimizer seems too smart for that and gives too low results. I'll probably have to start giving perl version numbers when using this trick since the optimizer can change at every version. This was tested on `perl 5.26.1`
This `49` is efficient and can actually handle `X=100` (but overflows on `X=1991`)
```
perl -pe '$\=$F[@F]=$F[-2]+$F[-3]+$F[-5]for($F[5]=1)..$_}{' <<< 100;echo
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
5ÆRẋHŒPQḅ1ċ
```
[Try it online!](https://tio.run/##y0rNyan8/9/0cFvQw13dHkcnBQQ@3NFqeKT7P1AQAA "Jelly – Try It Online")
## How it works
```
5ÆRẋHŒPQḅ1ċ -> Full program. Argument: N, an integer.
5ÆR -> Pushes all the primes between 2 and 5, inclusively.
ẋH -> Repeat this list N / 2 times.
ŒP -> Generate the powerset.
Q -> Remove duplicate entries.
·∏Ö1 -> Convert each from unary (i.e. sum each list)
ċ -> Count the occurrences of N into this list.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
30fIиæÙOI¢
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f2CDN88KOw8sOz/T3PLTo/39TAA "05AB1E – Try It Online")
[Answer]
# C, 41 bytes
```
G(x){return x>0?G(x-2)+G(x-3)+G(x-5):!x;}
```
[Try it online!](https://tio.run/##S9ZNT07@/99do0Kzuii1pLQoT6HCzsAeyNc10tQGUcYQylTTSrHCuvZ/Zl6JQm5iZp6GJlc1lwIQFBQBhdI0lFRTYvJUU5R0FNw1LDRBpKGhpqY1V@1/AA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 43 bytes
```
Tr[Multinomial@@@{2,3,5}~FrobeniusSolve~#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6Qo2rc0pyQzLz83MzHHwcGh2kjHWMe0ts6tKD8pNS@ztDg4P6cstU45Vu1/QFFmXkl0mr5DtYWOoaGOoYFBbex/AA "Wolfram Language (Mathematica) – Try It Online")
Explanation: `FrobeniusSolve` computes all solutions of the unordered sum `2a + 3b + 5c = n`, then `Multinomial` figures out how many ways we can order those sums.
Or we could just copy everyone else's solution for the same byte count:
```
f@1=0;f[0|2|3|4]=1;f@n_:=Tr[f/@(n-{2,3,5})]
```
[Answer]
# JavaScript (ES6), 32 bytes
Same algorithm as in [ovs' Python answer](https://codegolf.stackexchange.com/questions/155938/sum-of-combinations-with-repetition/155950#155950).
```
f=n=>n>0?f(n-2)+f(n-3)+f(n-5):!n
```
### Test cases
```
f=n=>n>0?f(n-2)+f(n-3)+f(n-5):!n
console.log(f(8))
console.log(f(11))
console.log(f(13))
```
[Answer]
# [R](https://www.r-project.org/), ~~56~~ ~~49~~ 47 bytes
Recursive approach from [ovs's answer](https://codegolf.stackexchange.com/questions/155938/sum-of-combinations-with-repetition/155950#155950). [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) shaved off those final two bytes to make it 47.
```
f=pryr::f(+`if`(x<5,x!=1,f(x-2)+f(x-3)+f(x-5)))
```
[Try it online!](https://tio.run/##K/r/P822oKiyyMoqTUM7ITMtQaPCxlSnQtHWUCdNo0LXSFMbRBlDKFNNTc3/aRoWmlxpGoZGYBJEGGn@BwA "R – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
:"5Zq@Z^!XsG=vs
```
Very inefficient: required memory is exponential.
[**Try it online!**](https://tio.run/##y00syfn/30rJNKrQISpOMaLY3bas@P9/Q0MA)
### How it works
```
:" % For each k in [1 2 ... n], where n is implicit input
5Zq % Push primes up to 5, that is, [2 3 5]
@ % Push k
Z^ % Cartesian power. Gives a matrix where each row is a Cartesian k-tuple
!Xs % Sum of each row
G= % Compare with input, element-wise
vs % Concatenate all stack contents vertically and sum
% Implicit end. Implicit display
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
f=->n{n<5?n==1?0:1:[n-5,n-2,n-3].sum(&f)}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/G1D7P1tbQ3sDK0Co6T9dUJ0/XCIiNY/WKS3M11NI0a/8XKKTpaZiYav4HAA "Ruby – Try It Online")
This is a recursive solution, the recurcive call being: `[n-5,n-2,n-3].sum(&f)`.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 32 bytes
```
n->1/(1-x^2-x^3-x^5)%x^(n+1)\x^n
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/XzlBfw1C3Is4IiI2B2FRTtSJOI0/bUDOmIi7vf1p@kUaegq2CoY6CsYGOQkFRZl4JUEBJQdcOSKRp5GlqanJBRA0NDBDiQA6yBKoMUOo/AA "Pari/GP – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
⁺¤fẋfṗUṠO
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiwr3ijIoiLCLigbrCpGbhuotm4bmXVeG5oE8iLCIiLCI4Il0=)
The header in the link halves the input to make things faster. It will return the same result if you remove it, but it may time out.
`⁺¤f` could alternatively be `30ǐ` (prime factors of 30) or `5~æ` (prime numbers up to 5).
```
⁺¤fẋfṗUṠO
⁺¤f # Push the digits of 235: [2, 3, 5]
ẋf # Repeat the list the input times
·πó # Powerset
U # Uniquify
·π† # Sum each
O # Count the number of times the input appears in this array
```
[Answer]
# Regex `üêá` (ECMAScript[RME](https://github.com/Davidebyzero/RegexMathEngine/) / Perl / PCRE / Raku`:P5`), 14 bytes
```
^(xxx?|x{5})*$
```
Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Ordered-partitions-with-2-3-5) (RegexMathEngine)
[Try it online!](https://tio.run/##RU/LTsMwELz3KyxrVXnJowmilzpOUqlcOXGjxSpRK1mYNsRBCjjmyAfwifxI6gQkLqvd2dmdmfrQ6OXw8k6g4cTqc7XXBBbcjyLbrO/XuZsdzw0DIxKe5RwtUUc/oa0bdWoJ3Z4od6TUwtRatYxGNDRvT6b1JzKM0jDFw@tIKv7RxOO4Aol8/GW84r4pdXaNttQP6U74muy4mxEyKas/AFQmJoLvggAtVN4SYbSjHSgUnwtW9KxYQYOssEEAlcPtcyblR94DK6YmRhyjmfl8cj@Z98lSTn7TgIop@fn6JjSGyhN7v3JOytu7jZTDI@u6rug7u3R4BcOQRDfJBQ "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##fVTbbtNAEH3PV0wNbdaxU8UEEIrjRqUU8RBaFKUSKA2Wu1k7qzpra22T9JJXPoBP5EMIs944dSlgJfZ6dubMmTOzpmnajijdPOOCxsWMQT@lkh3Ojxp0Hkjw08kUPBgZb5fL66tu8eXm5vN4/no5J5uvZLVaDe5Xd6/WZuv5xvzTw7ChlXp@ajlu4wE9y2c8UfB1k@QiemzjCVpZsHjqd9TgIocUl7nPpEwkoYnIcijpthYsy4KImXeYp9ej6AD9PmytalnamZjFLkiWF1KA464bhch4JNgM4kRE@haIbMmkW2Zb3Pg0iOOkyIlSp3rxr@KEXkOLmnCn3S1rB9tB2DI24IKgQwPwSidYRMwESc22M/U6LmhCujRIqWeQQc9wcWV5qX4YJhmc4H/PRHuBkN0Xfg6JClb4ES5K7DoQF2mRq3DJoCWZC3WNUJQ0lzpasqyIc71WaoZhxnIbsDhkGeVzvZN8YzRP5KQ71akQ1QOtRLJIecxQlkPqY3Ji2vDpZHTqvzsfHw@HcK/fLsbv39hwoDPrRZWqY2pMHgLZk8ys9AvLFocEy0JvGwwFVHKUECClMhz2Zz3Yzy4FDlsNU@fZAtc7hrQfeqm3Q8QjqshbpWgpYsTymAtG9AxxYWs9TRd9nKqVJWcMEx0EDfKEk9KpkgF1EI4NaZLhtt4JuZiRZru55aUu4Sgh0WfPq/ev1xPKOPgLLlilvwVIpIfJH7B0c1U6wZb6bSIcy5m6OP8L1IVkNjRXTUUMS8lwc@rV4ndCcE@o2ep7wnHBsni94qpTtyYgKZWENC9FU0uzlY8qofGocXUz4Of3H4CTqw8Isqul1LOkJrCaJ7ZilEhmw9nFcGgDMuY4IuVvO4Q2dE33CR@N0u/AwUGFiJKWs3c6Gp2P/LPzj8fjkw/mo8jdsakoG6dqvozH@CzO2P/DtrVVn5cwLrL5P6qsVb9u6Hs50z09jJIxrMXcfUW257Ox3nTaLzu/aBgHUbZpx0qs3w "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##hVXrTttIFP6fpzi4uzCTON2EbisUx0Q0RAKpDVUatN1S1jL2OBnVGVv2uAS6/O0D9BH3QZY9c0liSKS1wJnLOd@5fec4yvP2LIoeX8Qs4YLBh@FkdBgML05HweX4fBr8cX46PYOjxgsuorSKGfTzqGCHL@fHjWgeFhDkV9fgw8R5e3v79eZV9efd3afp/M3tnDz@RZbL5eDv5ffXD7T5yyN9LuG40Mz9IG91vRp8KQsuZgp/c8YzPGXh4nhL7rjBhYQclzJgRZEVJMpEKUH71lywsgxnjML3Usa9XoQS0O@DPVZLfc5EnHpQMFkVArrewxam2kdZzFy4ybIUMj8J01LBajMW7urw9ZtrrwH48ASITlMwYxYjsFLE4BCT58vh2cnkqEntpQslv2dZQtaO/7Y6qclTSrUV9ZAMBiaIKKsk9GAdKFXhOVoNtAc9cJ4Fr5UdB7WcL8Kh63wkaVXOTSTrpDQeGpUo@UywGNJMzMwrFOUtKzydsMVdEIVpim7Y2O0uuEmz6Cs0Ixe@ZTyGZhzKEHOnkqSW4PtA1E2T7m8wqMVutdaV6djKLEIuCAJoB/MrJELKBMlpu3vtdzwTgmEH5JHvkEHP8XDV8nPz41AyGOL/HsXzChFfHQYSi4q6Cn6GCw1dB@Iir6RS14FhCaFZsNV@EcpoHuhYmpu1QStYWaXSNSXwbHt9PP880idJUjK8xHgxhJmcPxFoZt9YJFHLVgLbbGV/kfOUEUuKjx@mE5pHL6MAnSXUtRifR5OLYDqavD8fn0xHp6vj0afpaHyq9vvaJ/trPenQDYP3CiSgzX29G/TbytVC97eyEeA@lCxIimwR5KGUrBCkQJaPL9@9swB1HWxdyZYSk7ha@bvuLSzZQsEI1hRcQbg1Xrq7ePYcwJhK@YLXQdpd6tWEYpbL/xUqWFQVJc/ETkFtNskK0NPlfs1cnBgpDmJiGpkL13CPeivG6/KgiuhgekKZcaIFVuXH@ouuC3lW4rW5wcEek4P2gTWqHtFVuUWZPb/O815PqMPBDlxoafkWdCkODNHZYJlZq8wJdmt2V6Lb6l57OGwWmAlSunCwPFCOYYJKvLz2a/rrJHBfqB7s@6LrQavF6xGvSHlPAZ1SRsjBF4EhYepQWvMzIc6vMfzz4yfgp4XjlRkh6FjNmukl1ZRP2aWJWe8odJpjQ@i/DadxbctIvS3nDG6/A/v71saeb7tuMrmYBOOL9yfT4Rl9oqjpV2uv1cSQRcWe2WD41dnS3Ux/nN824h2TXD0Pjc17V2MlBWNkE992QxuB9Z7WJ6K5xJmxHtgmEvx0PHbav3f@jZI0nJWP7VTrtI/@Aw "C++ (gcc) – Try It Online") - PCRE2
[Try it online!](https://tio.run/##K0gtyjH7X1qcquDr7@ftGmmt4Brm6KMQGF2cWKmgraGhXqFeoRKvWVeXa5VaYRVgqh@rUKegYpuWmZdZnAFkBkbrayqk5RcpxBkbWsdac0Fl/sdpVFRU2NdUVJvWamqp/P8PAA "Perl 6 – Try It Online") - Raku
Same method as used for [Fibonacci function or sequence](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence/250137#250137), directly enumerating the ordered partitions.
```
^ # tail = input number
(
xxx? # tail-=2 or tail-=3
| # or
x{5} # tail-=5
)* # Loop the above as many times as possible, minimum zero
$ # Assert tail == 0
```
# Regex `üêá` (Raku), 14 bytes
```
^(xxx?|x**5)*$
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoFKkYKugb6Nim5aZl1mcYadvrVCcWKmgraFeoV6hEq@pl5tYkpyhoVKkY5VaoamQll@kEGdsYM0FVf8/TqOiosK@pkJLy1RTS@X/fwA "Perl 6 – Try It Online")
Raku's plain regex alternation operator is `||`, and `|` does something special – it chooses the alternative making the longest match. But it'll still try every alternative when backtracking, so this makes no difference in the number of matches.
# [Perl](https://www.perl.org/), 38 bytes (full program)
```
1x<>~~/^(...?|.{5})*$(??{++$i})/;say$i
```
[Try it online!](https://tio.run/##K0gtyjH9n5evUJ5YlJeZl16soJ5aUZBalJmbmleSmGNlVZybWFSSm1iSnKFu/d@wwsaurk4/TkNPT8@@Rq/atFZTS0XD3r5aW1sls1ZT37o4sVIl8/9/Q8N/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online")
Interestingly, I noticed after making this post that [Ton Hospel already used](https://codegolf.stackexchange.com/a/155955/17216) the same basic method (and it predates my [Perl Fibonacci answer](https://codegolf.stackexchange.com/a/223243/17216) by 3 years), but did it with Perl `-p` in 37 bytes (which can be reduced to 34 bytes), by exploiting Perl actually using literal `{` `}` to create the `-p` loop. I previously assumed Perl emulated a loop when launched with `-p`, not that it literally string-concatenated the program into a loop.
Using the `$\` trick (setting the `print` record separator), there's an alternative 38 byte flagless full program:
```
1x<>~~/^(...?|.{5})*$(??{++$\})/;print
```
[Try it online!](https://tio.run/##K0gtyjH9n5evUJ5YlJeZl16soJ5aUZBalJmbmleSmGNlVZybWFSSm1iSnKFu/d@wwsaurk4/TkNPT8@@Rq/atFZTS0XD3r5aW1slplZT37qgKDOv5P9/Q0MA "Perl 5 – Try It Online")
Sadly it's only literally a `print` record separator and doesn't apply to `say`.
# [Raku](https://raku.org/), 27 bytes[SBCS](https://en.wikipedia.org/wiki/Windows-1252) (anonymous function)
```
{+m:ex/^(...?|.**5)*$/}o¬πx*
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WjvXKrVCP05DT0/PvkZPS8tUU0tFvzb/0M4Krf/WxYmVCnpAdWn5RQpxxgb/AQ "Perl 6 – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 101 bytes
```
l=mod(floor(nk/n^{[1,2,3]}),n)
f(n)=‚àë_{k=1}^{n^3}0^{(n-total([2,3,5]l))^2}l.total!/‚àè_{a=1}^3l![a]
```
Ugh, no recursion sucks. I literally see all these answers going `f(n-2)+f(n-3)+f(n-5)`, like super golfy, but nope, can't do that in Desmos.
[Try It On Desmos!](https://www.desmos.com/calculator/dnqm2xi5df)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/s3jdt2lnig)
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 50 bytes
```
N+O:-N>0,N-2+A,N-3+B,N-5+C,O is A+B+C;N<0,O=0;O=1.
```
[Try it online!](https://tio.run/##DcTBCoQgEADQX@mozEzoxkLUJlR35ypEhw4RgpVk0Oe7vcOL1xnOjdLjc7bADVmj0NIH@vcKhvcvjMiFT0UPA4yt/SnkTrXc6TI3tC8x@HSLyc3GCAeMz@XvNRzCkWEpcapRa9TVLMv8Bw "Prolog (SWI) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
Œṗe€2,3,5$Ạ$ÐfŒ!Q$€ẎL
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7p6c@alpjpGOsY6rycNcClcMT0o5OUgxUAQo@3NXn8///f0NDAA "Jelly – Try It Online")
Surely can be golfed
[Answer]
# Pyth, 12 bytes
```
l{fqQsTy*P30
```
This is horrendously inefficient and hits the memory limit for inputs above 5.
[Try it online](http://pyth.herokuapp.com/?code=l%7BfqQsTy%2aP30&input=5&debug=0)
### Explanation
```
l{fqQsTy*P30
P30 Get the prime factors of 30 [2, 3, 5].
* Q Repeat them (implicit) input times.
y Take the power set...
fqQsT ... and filter the ones whose sum is the input.
l{ Count unique lists.
```
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 32 bytes
```
f=n=>n>0?f(n-2)+f(n-3)+f(n-5):!n
```
[Try it online!](https://tio.run/##KyjKL8nP@/8/zTbP1i7PzsA@TSNP10hTG0QZQyhTTSvFvP8FRZl5JRppGqaamv8B "Proton – Try It Online")
Same approach as [ovs' answer](https://codegolf.stackexchange.com/questions/155938/sum-of-combinations-with-repetition/155950#155950).
[Answer]
# [Haskell](https://www.haskell.org/), 40 bytes
```
f 0=1
f n|n<0=0|1>0=f(n-2)+f(n-3)+f(n-5)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwNaQK00hrybPxsDWoMbQzsA2TSNP10hTG0QZQyhTzf@5iZl5CrYKBaUlwSVFCioKxRn55UAqTcHQ8D8A "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
1λèƵ†S₆O
```
Port of [*@ovs*' Python 2 answer](https://codegolf.stackexchange.com/a/155950/52210).
[Try it online](https://tio.run/##yy9OTMpM/f/f8NzuwyuObX3UsCD4UVObP1DAEAA) or [verify all test cases](https://tio.run/##ATEAzv9vc2FiaWX/dnk/IiDihpIgIj95/zHOu8OoxrXigKBT4oKGT/99LP9bOCwxMSwxMDBd).
Outputting the infinite sequence would be 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead:
```
λƵ†S₆O
```
[Try it online.](https://tio.run/##yy9OTMpM/f//3O5jWx81LAh@1NTm//8/AA)
**Explanation:**
```
λ # Start a recursive environment
è # to output the (implicit) input'th value
# (which is output implicitly in the end)
1 # Starting with a(0)=1, and a(-1)=a(-2)=a(-3)=a(-4)=0
# And where every next a(n) is calculated as:
Ƶ† # Push compressed integer 235
S # Convert it to a list of digits: [2,3,5]
‚ÇÜ # Calculate a(n-v) for each value v in this list: [a(n-2),a(n-3),a(n-5)]
O # Sum this list together: a(n-2)+a(n-3)+a(n-5)
λ # Start a recursive environment
# to output the infinite sequence
# (which is output implicitly in the end)
# (implicitly starting with a(0)=1, and a(-1)=a(-2)=a(-3)=a(-4)=0)
# And where every next a(n) is calculated as:
Ƶ†S₆O # Same as above
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶ†` is `235`.
] |
[Question]
[
**This question already has answers here**:
[Appending String Lengths](/questions/103377/appending-string-lengths)
(48 answers)
Closed 1 year ago.
The task is simple. You're given an arbitrary string message. Return that message prefixed with a number, such that the length of that number plus the message equals the number. In other words, the length in your output must be the total length of your output.
If multiple candidates exist, you can output any of them.
For example, take the following message: `pull the other one`, with a length of 18. Your final output should be `20` + `pull the other one`, because the total length of `20` + the total length of `pull the other one` is 20 ASCII characters.
Restrictions/clarifications:
* Your input and output can be given by [any convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* The outputted length can be encoded in any way you like, as long as the encoding can represent any arbitrary positive number, and the encoding is consistent. You can, for example, output `10111` + `pull the other one` (10111 is 23 in binary, and the total length is 23). This also extends to types: e.g. a tuple of `(int, string)` is accepted as output, as long as you specify the encoding the integer must have.
* The input string can also have any encoding you like (well, except for the encoding in this question).
* Your program should be able to handle at least all messages of length <= 1,048,575 (2^20-1).
* The program can be a full program or just a function; either is fine.
* [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* Shortest code wins.
Some more test cases:
```
# base 10
"hello world" -> "13" + "hello world"
"the axes" -> "9" + "the axes"
"the axes" -> "10" + "the axes" # both of these are valid outputs
"" -> "1" + "" # the empty message should result in simply the output "1"
# base 2
"hello world" -> "1111" + "hello world"
"test" -> "111" + "test"
"test" -> "1000" + "test" # both of these are valid outputs
"" -> "1" + "" # the empty message can result in simply the output "1"
"" -> "10" + "" # in binary, this is also a valid result for the empty message
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 43 bytes
```
f(b,s,n){for(;sprintf(b,"%d%s",++n,s)>n;);}
```
[Try it online!](https://tio.run/##vVFNi8IwFDybX/EoCImJ0D0HBb@7/oE9iIcaEw3UVJIUFkp/e01a3e1hr@u7ZJh5vAkzYnoRom0VPjHHDKlVaTF3d6uNj1wyPo9dwig1zJG54YQ3bZDglmuDCaoRhBHX3E7AS@cPR5hBT8ZJMlkUJXyVtjgn7Jf2Vwn5t3R/cYshuViu1pvtLvvc/xN6q1k2dBvgtEMN755QAOAYsZ6lvA9VHzloSkmn12gU1UKaELXzNgD83CIcjfouTpUK6i0P6QscVyl8pIT/OIZqK8Ve11m8NlDvlXdxId5TVson7j6JmvYB "C (gcc) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 4 bytes
```
+Chl
```
[Try it online!](https://tio.run/##K6gsyfj/X9s5I@f/fyWf1Lz0kgyF1Lzk/JTUFIXS4sy8dIUAoIr8PIWE5IyiBD0lAA "Pyth – Try It Online")
Length encoded using Python `chr`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~7~~ 6 bytes
*-1 byte thanks to [@isaacg](https://codegolf.stackexchange.com/users/20080/isaacg)*
```
+fql+Q
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72koLIkY8GCpaUlaboWy7TTCnO0AyEcmFi0km6KUuxapYzUnJx8hfL8opwUJYgUAA)
## Explanation
```
+fql+QTT<None>Q
+ # add
f # first input (T) where
l # length of
+QT # testcase + T
q T # equals T
Q # to the testcase
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
3(Lp
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIzKExwIiwiIiwiaGVsbG8gd29ybGQiXQ==) -1 thanks to lyxal, -2 thanks to Kevin Cruijjsen.
```
3( # Three times
p # Prepend to input
L # Length of current value
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
⁺L⁺L⁺Lθθθθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMgp7RYwyc1L70kAye7UFNHoVATibD@/z85PyVVIT0/J43rv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Charcoal doesn't really do recursion, but the recursive approach of repeatedly taking the length of the string with the previous length prefixed to it never needs to iterate more than twice.
```
θ Input string
L Take the length
⁺ Concatenated with
θ Input string
L Take the length
⁺ Concatenated with
θ Input string
L Take the length
⁺ Concatenated with
θ Input string
Implicitly print
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÈsY}f+U
```
[Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yHNZfWYrVQ&input=InB1bGwgdGhlIG90aGVyIG9uZSI)
```
ÈsY}f+U :Implicit input of string U
È :Function taking a string and a 0-based iteration index Y as arguments
sY : Slice the string from the Yth character
} :End function
f :Get the first string that returns falsey (empty string)
+U : Where each string is U appended to the current iteration index
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
,ḟS=ȯL+¹sN
```
[Try it online!](https://tio.run/##yygtzv7/X@fhjvnBtifW@2gf2lns9///f6WC0pwchZKMVIV8IFGkkJ@XqgQA "Husk – Try It Online")
```
,ḟS=ȯL+¹sN
ḟ # get the first
N # integer from 1..infinity
= # that equals
ȯ # (compose 3 functions)
L # the length of
+¹ # the input added to
s # itself as a string
, # finally, construct a pair of
# this number and the input
```
[Answer]
# JavaScript (ES6), 31 bytes
*-1 thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)*
Uses a decimal prefix.
```
s=>(g=n=>(S=++n+s)[n]?g(n):S)``
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k4j3TYPSAbbamvnaRdrRufF2qdr5GlaBWsmJPxPzs8rzs9J1cvJT9dI01DySM3JyVcozy/KSVHS1ORCky3JSFVIrEgtxiIFFPoPAA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 15 bytes
```
iys>l`Sys<l+u&o
```
[Try it online!](https://tio.run/##y6n8/z@zstguJyG4stgmR7tULf///5KMVIWSosTkbAA "Ly – Try It Online")
```
iys - Read STDIN onto the stack, push stack size, save it
>l` - Switch to new stack, load saved size, increment by 1
Sys - Convert number to digits, get size of stack, save it
< - Switch back to the original stack (w/ STDIN and strlen)
l+ - Load number of digits in the "strlen + 1", add to strlen
u - Write length as a number
&o - Write STDIN codepoints as characters
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
3Fgì
```
Similar as [my answer for the related challenge](https://codegolf.stackexchange.com/a/255215/52210), but with a prepend instead of append. Will therefore also use base-10, and always use the smallest (`9` instead of `10`) if more than one option is available.
[Try it online](https://tio.run/##yy9OTMpM/f/f2C398Jr//0syUhUSK1KLAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCS7/jd3SD6/5X6vzP1opIzUnJ1@hPL8oJ0VJR6kkI1UhsSK1GMgE8VKLS5RiAQ).
**Explanation:**
```
3F # Loop 3 times:
g # Pop the current string, and push its length
# (which will use the implicit input-string in the first iteration)
ì # Prepend this length to the (implicit) input-string
# (after which the result is output implicitly)
```
[Answer]
# [Python](https://www.python.org), 24 bytes
```
lambda a:chr(len(a)+1)+a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwdI0BVuFmKWlJWm6FjtyEnOTUhIVEq2SM4o0clLzNBI1tQ01tRMh0je9C4oy80o0ilILijTSNJQyUnNy8hXK84tyUpQ0NTW5UGVLMlIVEitSi7FIgYQgRi5YAKEB)
---
# [Python](https://www.python.org), 50 bytes
```
f=lambda a,b=1:(len(s:=str(b)+a)==b)*s or f(a,b+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3jdJscxJzk1ISFRJ1kmwNrTRyUvM0iq1si0uKNJI0tRM1bW2TNLWKFfKLFNI0gEq0DTWhOi0LijLzSjTSNJQyUnNy8hXK84tyUpQ0Nbng4iUZqQqJFanFKIJADsQAmBMA)
---
# [Python 2](https://docs.python.org/2/), 49 bytes
```
f=lambda a,b=1:(len(`b`+a)==b)*(`b`+a)or f(a,b+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWNw3TbHMSc5NSEhUSdZJsDa00clLzNBKSErQTNW1tkzS1oOz8IoU0DaAKbUNNqEbLgqLMvBKNNA2ljNScnHyF8vyinBQlTU0uuHhJRqpCYkVqMYogkAMxAOYCAA)
Python 2 solution suggested by [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 41 38 bytes
```
{a=length;$0=length(length(a)+a)+a$0}1
# E.g.
awk '{a=length;$0=length(length(a)+a)+a$0}1' <<< "input"
```
[Try it online](https://tio.run/##SyzP/v@/OtE2JzUvvSTDWsUAytKAUoma2iCkYlBr@P9/YlJySmpaekYmAA)
Remove the space (`" "`) between the final length and the string as suggested by @Dominic van Essen (-3 bytes)
[Answer]
# [Python](https://www.python.org), 65 bytes
I'm not 100% sure I understood the question right
```
lambda a,b=0:(z:=len(a)+len(str(b)))and((z,a)if z==b else f(a,z))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Vcw9CgIxEEDh3lMMqWYwgqUupPAeNhOSkIWYLElkNVexCYjeyduI-ANWD77iXe7TufoU-9Wp_e1Y3Wrz2AU-aMPAUqv1gG1QwUZkWr5SakZNRBwNYpNMo4OmlAYbigWHLBvRZ7Sd8hgrOhTehpBgTjkYQbT4efUW-GTLH4rvoPd3nw)
[Answer]
# [Python](https://www.python.org), 47 bytes
```
f=lambda a,b=1:(b*f"{b}{a}")[-b:b*b]or f(a,b+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY39dNscxJzk1ISFRJ1kmwNrTSStNKUqpNqqxNrlTSjdZOskrSSYvOLFNI0gPLahppQbZYFRZl5JRppGkoZqTk5-Qrl-UU5KUqamlxw8ZKMVIXEitRiFEEgB2IAzH4A)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~39~~ 34 bytes
```
->c,a=0{a+=1while(b=[a]*c+c)[a];b}
```
-5 bytes thanks to observations from jdt's C and Arnauld's JS.
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3lXTtknUSbQ2qE7VtDcszMnNSNZJsoxNjtZK1kzWBtHVSLVSlY0FpSbFCtFJBaU6OQklGqkI-kChSyM9LVdJRUMpIzcnJVyjPL8pJAXFB8okVqcUgtlKsXm5igYJaGsSgBQsgNAA)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
£▌£▌£▌
```
[Try it online.](https://tio.run/##y00syUjPz0n7///Q4kfTehDE///qGak5OfkK5flFOSnqXOolGakKiRWpxUAmiJdaXAKkEmkO1AE)
**Explanation:**
```
£ # Pop and push the length of the (implicit) input-string
▌ # Prepend it to the (implicit) input-string
£ # Pop and push the length of that
▌ # Prepend it to the (implicit) input-string
£▌ # Rinse and repeat
# (after which the entire stack is output implicitly)
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~43~~ 41 bytes
```
r1>:0v >o<
1(?v$>1+$a,:
2l~<.03+1v?=@:$+-
```
[Try it online!](https://tio.run/##S8sszvj/v8jQzsqgTMEu34bLUMO@TMXOUFslUceKyyinzkbPwFjbsMze1sFKRVv3////usUZqTk5@Qrl@UU5KQA "><> – Try It Online") or [Try without input](https://tio.run/##S8sszvj/v8jQzsqgTMEu34bLUMO@TMXOUFslUceKyyinzkbPwFjbsMze1sFKRVv3/38A)
**Explanation**
```
r1 # initialize with length as 1 (L)
>:0v # initialize length of (L) as 0 (N)
1(?v$>1+$a,: # calculate (N)
2l~< v?=@:$+- # if the length of string (S) + (N) = (L)
>o< # print L followed by the string
.03+1 # else, increment (L) and go back to calculation of (N)
```
The length is output as a charcode.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 4.5 bytes (9 nibbles)
```
/\`.$:,$@
```
Inspired by [Pacmanboss's comment](https://codegolf.stackexchange.com/questions/103377/appending-string-lengths/255215#comment562305_252736).
```
`. # iterate while unique
$ # starting from the input:
: # prepend
,$ # its length
@ # to the original input
\ # then, reverse the list
/ # and fold over it
# getting the left-hand argument each time
# (so getting the first element)
```
[](https://i.stack.imgur.com/PdMSx.png)
---
Previous approach:
# [Nibbles](http://golfscript.com/nibbles/index.html), 5.5 bytes (11 nibbles)
```
:/|,~~-,:`p
```
[Nibbles](http://golfscript.com/nibbles/index.html) adds implicit variables to the end of each program if they are needed for the arity of the functions used.
In this case, this works particularly well.
```
| # filter
,~ # 1..infinity
~ # for elements that are falsy for
, # the length of
`p # the string represention
# (implicitly: of each element)
: # concatenated with
# (implicitly: the input)
- # minus
# (implicitly: itself)
/ # now, fold over this list
# returning for each pair
# (implicitly: the left-hand argument)
# (so the fold returns the first element)
: # finally, prepend this to
# (implicitly: the input)
```
[Answer]
# [Go](https://go.dev), 95 bytes
```
import."fmt"
func f(s string)string{S:=Sprint
return S(len(s)+len(S(len(s)+len(S(len(s))))),s)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BmoLE5OzE9FSF3MTMvKWlJWm6FjfjM3ML8otK9JTSckuUuNJK85IV0jSKFYpLijLz0jUhVHWwlW1wAZBVwlWUWlJalKcQrJGTmqdRrKkNorByQECnWLMWYs0txlqw0SCLNTQVqrmSE4tTixWsbBWiY6F2cClAgZJHak5OvkJ4flFOipIOQrgkI1UhsSK1GJuYI7Kgo5Ozi6ubu4enF41YdLXMA9k2ILuWKy2_SCFeJxkUekWJecDohARmNVcAKIpy8jSSdRSUbO2UdIAxmaypCdQBjYUFCyA0AA)
##### [Go](https://go.dev), Old 125 bytes
```
import(."fmt";."strings")
func f(s string)string{S:=Repeat("-",len(s))+s
for range`---`{S=Sprintf("%d%s",len(S),s)}
return S}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=vZHPSsQwEMbxmqcYBhYSTPcsKxXWv9WT2IMHWdyQTWqxTUuSglD6JF6K4M0X0qexbQruwavOZYaPGb6P-b2-ZVX_UQv5LDIFpcjNe-N1dPTZ5WVdWU-XqEuPx0t03uYmc8iIbowETR0EiYXWpqv4TtVKeIoR8kIZ6hg7dERXFqwwmdpGUbRt0zith32vKS52Cxc2U8Yd64hVvrEG0i6E-DroJq8xFmXQEimccrCK4WEzmxKYCxNVFBXcV7bYIf-R_ZMC8aLcb9p6X1yfnp1fXF4l1zd_NP2rWbLvNszdhOGRy_F7Ew0Iz2zJ7UijMFRywPgE-YBWMjZczBT6PvRv)
[Answer]
# Excel, ~~21~~ 27 bytes
```
=LEN(LEN(LEN(A1)&A1)&A1)&A1
```
Admittedly boring. I tried to do something fancy with `LOG()` but it's longer than this solution.
[Answer]
# JavaScript, 29 bytes
```
s=>(g=x=>x.length+s)(g(g(s)))
```
[Try it online!](https://tio.run/##DcnBDYAgDADAXXiVGNmg7EKwFgy2xhLD9kjueVf6kuW3Pn0XPWieOA0jMA6MIzQS7mUzD7yY935mFdNGoSnDCc70pl6qsFv3Aw)
[Answer]
## SQL (24 bits)
```
print len(@)+len(len(@))
```
Assuming we have: `declare @ as varchar(max) = 'any-string'`
[Answer]
## SAS, ~~47~~ 58 bytes
Fix `something` error. I just find this anwser is same with the Excel one.
```
%macro e(m);
%put%length(%length(%length(&m)&m)&m)&m;
%mend;
```
Try some example:
```
%e(hello world);
13hello world
%e(something);
11something
%e(the axes);
9the axes
```
[Answer]
# [PLIS](https://github.com/ConorOBrien-Foxx/PLIS), 81 bytes
```
&R($Z(strlen($0))$D(1+@(H@({$0^2}{$0-spT@$0-Z}a))@0)catat(48+digits(D),spT@D,$0))
```
Takes a string sequence as input, and returns a string sequence as output.
```
print(R("hello world")); #=> 13hello world
print(R("the axes")); #=> 9the axes
print(R("pull the other one")); #=> 20pull the other one
print(R("")); #=> 1
```
## Explanation
Here is an equivalent, commented, ungolfed version of the above, with shortnames expanded.
```
&R(
# set Z to strlen(input)
$Z(strlen($0))
# set D to 1 + the first index where
$D(
1 + @(
# we find a 0 in
A000007@(
# the squared sequence of (i.e. absolute value of)
{$0^2}
# the difference between increasing positive integers ($0),
# the length of that integer (A055642), and the input
# string's length (Z)
{$0 - A055642@$0 - Z} A000027
)
)@0
)
# D is now the appropriate number we need to prepend
# 48 + digits(D) gives the ASCII version of this sequence
# catat(A,n,B) will use the first n entries of A followed by
# the entries in B
# this line has the effect we want
catat(48 + digits(D), A055642@D, $0)
)
```
[Answer]
# [Terse](https://gymhgy.github.io/TerseLang/), 4 bytes
```
地用找儿
```
[Try it here](https://gymhgy.github.io/TerseLang/?code=t7XAng&in=IlRoaXMgaXMgYSBzdHJpbmcgdGhhdCBpcyA0MyBjaGFyYWN0ZXJzIGxvbmci)
```
地 Length
用 +1
找 To character
儿 Append input
```
] |
[Question]
[
Imagine throwing a rock into a pond. You get to see perfect circles of ripples spreading out over the pond, bouncing off of each other. Of course, nothing can be as serene as that in coding, but, we can try!
Given a point on a 2D array `(x, y)` and the dimensions of a 2D array/pond `(w, h)`, and a "frame" count, `f`, return a array of 2D arrays length f that shows a ripple animation starting at `(x, y)`.
An ON value (choose between int, bool, or any val for that matter that has two values) should spread out one point in a diamond shape, as the examples show.
Example 1
>
>
> ```
> Input: (0, 0, 3, 3, 7)
> Output = a[]
> a[0] =
> 1 0 0
> 0 0 0
> 0 0 0
>
> a[1] =
> 0 1 0
> 1 0 0
> 0 0 0
>
> a[2] =
> 0 0 1
> 0 1 0
> 1 0 0
>
> a[3] =
> 0 0 0
> 0 0 1
> 0 1 0
>
> a[4] =
> 0 0 0
> 0 0 0
> 0 0 1
>
> a[5]+ =
> 0 0 0
> 0 0 0
> 0 0 0
>
>
> ```
>
>
Example 2
>
>
> ```
> Input: (2, 2, 5, 5, 5)
> Output: b
> b[0] =
> 0 0 0 0 0
> 0 0 0 0 0
> 0 0 1 0 0
> 0 0 0 0 0
> 0 0 0 0 0
>
> b[1] =
> 0 0 0 0 0
> 0 0 1 0 0
> 0 1 0 1 0
> 0 0 1 0 0
> 0 0 0 0 0
>
> b[2] =
> 0 0 1 0 0
> 0 1 0 1 0
> 1 0 0 0 1
> 0 1 0 1 0
> 0 0 1 0 0
>
> b[3] =
> 0 1 0 1 0
> 1 0 0 0 1
> 0 0 0 0 0
> 1 0 0 0 1
> 0 1 0 1 0
>
> b[4] =
> 1 0 0 0 1
> 0 0 0 0 0
> 0 0 0 0 0
> 0 0 0 0 0
> 1 0 0 0 1
>
> b[5]+ =
> 0 0 0 0 0
> 0 0 0 0 0
> 0 0 0 0 0
> 0 0 0 0 0
> 0 0 0 0 0
>
> ```
>
>
Requirements
* Output should be an array of an array of an array, or a format that well represents the desired output shown above (comments appreciated on this part)
* Must be a method
* Must not use libraries that do everything for you
* values in the arrays of output must only use 2 unique values
+ this means you can't just return the plain manhattan distance, you must make it a ripple
* Standard loopholes apply
Information
* Parameters are (`int x`, `int y`, `int w`, `int h`, `int f`)
* \$0 \le x < w \le 10\$
* \$0 \le y < h \le 10\$
* \$0 < f \le 10\$
* `w` and `h` are equal
* if your language does not support functions, just print to stdout
Test cases:
* The two examples
* `(3, 2, 5, 5, 3)`
* `(0, 0, 1, 1, 1)`
* `(1, 2, 3, 3, 4)`
* `(4, 4, 10, 10, 10)`
Please try to make it testable online, would be appreciated
This is code golf, so shortest code for each language wins!
[Answer]
# [J](http://jsoftware.com/), 30 27 26 bytes
```
1 :'i.@u=/1#.(|@-"1]#:i.)'
```
[Try it online!](https://tio.run/##LYqxCoAwEMV2v@Khw/XAnq1ShEKhIDg5uTuJoi5Obv57VTCQJeRIudCK4EEoYeBftaAbhz5ZeNolXqGyhag76txOhd@FKXG2zNsJZWAYLVaoBs0fSb/QP9SoGe4bHBynBw "J – Try It Online")
Using `(2 2) 5 f (5 5)` as the example:
* `]#:i.` Creates the w,h coordinate system (showing it boxed here for clarity):
```
┌───┬───┬───┬───┬───┐
│0 0│0 1│0 2│0 3│0 4│
├───┼───┼───┼───┼───┤
│1 0│1 1│1 2│1 3│1 4│
├───┼───┼───┼───┼───┤
│2 0│2 1│2 2│2 3│2 4│
├───┼───┼───┼───┼───┤
│3 0│3 1│3 2│3 3│3 4│
├───┼───┼───┼───┼───┤
│4 0│4 1│4 2│4 3│4 4│
└───┴───┴───┴───┴───┘
```
* `|@-"1` subtract from x,y and take absolute value:
```
┌───┬───┬───┬───┬───┐
│2 2│2 1│2 0│2 1│2 2│
├───┼───┼───┼───┼───┤
│1 2│1 1│1 0│1 1│1 2│
├───┼───┼───┼───┼───┤
│0 2│0 1│0 0│0 1│0 2│
├───┼───┼───┼───┼───┤
│1 2│1 1│1 0│1 1│1 2│
├───┼───┼───┼───┼───┤
│2 2│2 1│2 0│2 1│2 2│
└───┴───┴───┴───┴───┘
```
* `1#.` Sum each cell for the Manhattan distance:
```
4 3 2 3 4
3 2 1 2 3
2 1 0 1 2
3 2 1 2 3
4 3 2 3 4
```
* `i.@u=/` Equality "table" (3d table) with 0, 1, 2, 3, 4:
```
0 0 0 0 0
0 0 0 0 0
0 0 1 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 1 0
0 0 1 0 0
0 0 0 0 0
0 0 1 0 0
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
0 0 0 0 0
1 0 0 0 1
0 1 0 1 0
1 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 1
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~55~~ 52 bytes
*-3 bytes thanks to @MarcMush*
`x` and `y` are 1-indexed. Outputs an `Array{BitArray{2},1}`.
```
x*y*w*h*f=0:~-f.|>d->@.abs((1:w)-x)+abs((1:h)-y)'==d
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v0KrUqtcK0MrzdbAqk43Ta/GLkXXzkEvMalYQ8PQqlxTt0JTG8rJ0NSt1FS3tU3576tgq6ClYayjAESmEKTJlZJZXJCTWKnhq2mtUFCUmVeSk6ehHpOnrsnlqwA0ViGxqEhB105BQwGmUE8bKISuWEHzPwA "Julia 1.0 – Try It Online")
It simply generates a 2D matrix consisting of the manhattan distances from the point `(x,y)`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 53 bytes
```
Table[Abs[#1-i]+Abs[#2-j]==k,{k,0,#5},{i,#3},{j,#4}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQxKSc12jGpOFrZUDczVhvMMtLNirW1zdapztYx0FE2rdWpztRRNgZSWTrKJrWxav/zS0tsnfLzgTrToo11jHVMQTA2losroCgzr8TBwQGoIDraECgCFohWislTikWVNMInaYxP0gSfpCk@SbPY2P8A "Wolfram Language (Mathematica) – Try It Online")
Defines a pure function that takes the inputs `x, y, w, h, f` (in that order). Constructs a `h`-by-`w`matrix using `Table`, where each matrix element is either `True` or `False` depending on whether the Manhattan distance from `(x, y)` equals `k`, an iteration variable corresponding to the kth element in the output array. `x` and `y` are 1-indexed. In the TIO I have wrapped the output in `Boole` so that the output has `0` for `False`and `1` for `True`.
[Answer]
# [R](https://www.r-project.org), 62 bytes
```
\(x,y,d,f,`[`=outer)abs(1:d-x-1)[abs(1:d-y-1),"+"][1:f-1,"=="]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHKosyCgpxUBRvdpaUlaboWN-1iNCp0KnVSdNJ0EqITbPNLS1KLNBOTijUMrVJ0K3QNNaNhnEogR0dJWyk22tAqTddQR8nWVikWaoqiNsRcDQMdAx1jHXNNLpiAkY6RjqmOqSZE4YIFEBoA)
Returns a 3-d `logical` `array`--`+` is prepended to the function call to make the output more readable.
Computes the manhattan distances of each cell with the starting cell, then computes the equality with each frame number.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 63 bytes
A port of [dingledooper's Julia answer](https://codegolf.stackexchange.com/a/245902/9288). `x` and `y` are 1-indexed. Outputs a vector of matrices.
```
(x,y,w,h,f)->[matrix(w,h,i,j,abs(i-x)+abs(j-y)==d)|d<-[0..f-1]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY5BCsIwEEWvMnSV4KS0tmIXth4kBImWaEqVUCu24CVcuymIeCZvY2JaEN6QP4_MMI-3kY3e7M3wVJC_Lq1i2WdNOuzxigdUlBX8KNtGd8T1GiuU2zPRrKMzFyrW0zwv6a1cMR6FoWKxEOOauzSm7okEVoBp9Km1MXBNADtZ10QhSEoROI8RLMmPpbDGx4XHifRPJE74kREn5tMCS-qE_xxHUwlB_WHD4N8v)
[Answer]
# [Factor](https://factorcode.org/) + `math.matrices math.unicode pair-rocket`, 80 bytes
```
[ <iota> [ '[ 2array _ => _ v- vabs Σ _ = ] <matrix-by-indices> ] 4 nwith map ]
```
Takes input as `h w y x f` and gives output as a sequence of matrices.
I'm using a modern build of Factor for this, so have a picture:
[](https://i.stack.imgur.com/3iHVZ.gif)
There are two reasons for that:
* `make-matrix-with-indices` is now called `<matrix-by-indices>`.
* Values can be fried directly into literals now, so I can say `_ => _` instead of `_ _ 2array`.
See [here](https://tio.run/##LY7BTsNADETv/Yq5cdoeKnIp4oy4cEE9RRFyty6xst0NXjcl/A7/wy@FzYJGsuyn8WjO5C3pcnh9fnnaI/PHlaPnDFKlOeNC1m/LUFlhvSZePzIG1sgBo7LZPKpEgySMJOo0@YHtz36N4tOJcda5ArxzZKUgX2SSYsbDZtOgwa6oWdqSYYQWdy12tQPeiv7XyWGiY8bPd2GP6ErgwK7W@3Q3sd5JPNWmHe4RV1IsI7rFUwglNctlDOyMjoG3iKH4mHy//AI "Factor – Try It Online") for a version that runs on TIO at a cost of 7 bytes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 (or 17) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
F²Lã€αO²ôNQ,
```
Three inputs in the order: \$f\$, \$d\$, \$[x,y]\$, where \$d\$ is both \$w\$ and \$h\$ since it's guaranteed that \$w==h\$ anyway, and \$[x,y]\$ are 1-based indices. Outputs each matrix on a separated line to STDOUT.
[Try it online.](https://tio.run/##ASYA2f9vc2FiaWX//0bCskzDo@KCrM6xT8Kyw7ROUSz//zcKMwpbMSwxXQ)
For a more strict I/O as described in the challenge description, it would be 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead:
```
L<²L`âε³>αO}²нôδQ
```
[Try it online.](https://tio.run/##ATEAzv9vc2FiaWX//0w8wrJMYMOizrXCsz7OsU99wrLQvcO0zrRR//83ClszLDNdClswLDBd)
**Explanation:**
```
F # Loop `N` in the range [0, first (implicit) input `f`):
²L # Push a list in the range [1, second input `d`]
√£ # Create all coordinate-pairs by taking the cartesian product of
# itself
€ # Map over each coordinate-pair:
α # Calculate the absolute difference with the (implicit) third
# input [x,y]
O # Sum each inner pair to get the Manhattan distance
²ô # Split this list into parts of size `d` to turn it into a matrix
NQ # Check for each value if it equals `N`
, # Pop and output this matrix with trailing newline
```
```
L # Push a list in the range [1, first (implicit) input `f`]
< # Decrease it by 1 to range [0, f)
² # Push the second input-pair [w,h]
L # Transform both to a list in the range [[1,w],[1,h]]
` # Pop and push both lists separated to the stack
√¢ # Create pairs of both lists with the cartesian power
ε # Map over each pair:
³ # Push the third input [x,y]
> # Increase it from a 0-based to 1-based index
α # Take the absolute difference with the current pair
O # Sum to get the Manhattan distance
}²н # After the map: push the first value of the second input: w
ô # Split the list into parts of that size
δ # Apply on the two lists double-vectorized:
Q # Check which values in the matrix are equal to the value of the
# [0,f) list
# (after which the list of matrices is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 81 bytes
```
->x,y,w,h,f{(0...f).map{|c|(-y...h-y).map{|m|(-x...w-x).map{|n|m.abs+n.abs==c}}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165Cp1KnXCdDJ61aw0BPTy9NUy83saC6JrlGQ7cSyM/QrYSK5AJFKoAi5boVUJG8mly9xKRi7TwQaWubXAsE/9OiDXQMdIyB0DwWoiyxpqC0pFghEcIrqymDMNJr0hXsDa0MarXU1WutQUpqubjSoo10jHRMQZBk3f8B "Ruby – Try It Online")
[Answer]
# Java 10, ~~140~~ 134 bytes
```
(x,y,w,h,f)->{var r=new int[f][h][w];for(;f-->0;)for(int d=h*w;d-->0;)r[f][d%h][d/h]=Math.abs(d%h-x)+Math.abs(d/h-y)==f?1:0;return r;}
```
Could technically be 132 bytes since `w==h`, but this also works for non-square matrices.
[Try it online.](https://tio.run/##fVLBatwwEL3nK4ShINWy4yaUtiuckGMOSQo5GgcU26q89cpGktc2Yb99O5IFm9AlCAbpzdPTvBlt@Z4n2/rvseq4MeiBt@rtAqFW2UYLXjXo0R09UJRuoQrDHs3UxcXHyUfpoyAM@IcLCMZy21boESmUH/FMFzpRSQVJbt72XCOdq2byuqIsZFlMJRO9xkwkyU3GiNs7wTqXXydWr6B23PoLsOtLWeYP3MqUvxoMUDKT@HS@lMlC8lzcfttkTDd21AppdjgyV9gwvnZQWKhv37c12oFv/Gx1q/4UJSerZ9sYizOa0WtYP7yxAF7RK/rdrf/BnwF83wL/hOd83rr12efF2GaX9qNNByjIdgpH92oYrdnA3SWP4jmOaBQvccRAQAIweUA6QMBRhLLOKT2NFqQ2KAqcAbpjl98ufac1X54EdFG3VWOwSqt3Yzvv6pPrpy/DXSa4c3N149852ow2H5KntO4nyK0kEnJnDW3hA6ejbbvUv29S269zxCBBUt0MHXzju67DUfGSJb9QCa2KSHB/VjLkDt7v4fgP)
**Explanation:**
```
(x,y,w,h,f)->{ // Method with the 5 parameters & int[][][] return-type
var r=new int[f][h][w];// Result array of `f` amount of `h` by `w` sized
// matrices, filled with 0s by default
for(;f-->0;) // Loop `f` in the range (f,0]:
for(int d=h*w;d-->0;)// Inner loop over all cells of a matrix:
r[f] // Modify the matrix at index `f`
[d%h][d/h]= // at the current cell, to:
Math.abs(d%h-x) // Calculate the absolute difference of the current
// cell's x-coordinate and `x`
+Math.abs(d/h-y) // Add the same for `y`
==f? // If this Manhattan distance is equal to `f`:
1 // Fill the current cell with a 1
:0; // Else: keep the 0
return r;} // Return the result
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 90 bytes
```
lambda a,b,c,d,e,R=range:[[[i==abs(k-a)+abs(j-b)for k in R(c)]for j in R(d)]for i in R(e)]
```
[Try it online!](https://tio.run/##dY7NasMwEITvfoq9RSKbktQpLQG9RK5uMJIlN3JcycgKJU/v6schbalhDB6@mVkNN3@2pnwb3NSy96nnn0Jy4CiwQYkKj8xx86EOVVVpxrgYyWXD6Tr@dBtBW@vgAtrAkTT0FF2XncxOZ6foaZKqhcEp72/14LTxhCMIhAZBIih6KKCtA746oyQwaP/wgMOe/7K1rHs9@jj8KIR24uNV3OEjGiHkmytYPXVWGzJ6R9bC2l5xQ1N1NrE6r9BwdO7Rovj19i1CUJn0muB/qWeEoJesxVT5I1UupvLFXdZiape28rv2i6l9gGFle//o9A0 "Python 3.8 (pre-release) – Try It Online")
Returns a 2d list of booleans indicating whether or not the Manhattan distance from the original point is equal to the iteration number, for each iteration number from 0 to `e` (frame count).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
NθNηNζNεENEε⭆ζ⁼ι⁺↔⁻ηλ↔⁻θν
```
[Try it online!](https://tio.run/##Xcs9DsIwDAXgnVN4dCSzUDF1YmBgKKrECdIqIpFM2vwx9PLBlRiq2NP3nj1bHedFc60Pv5b8LJ/JRAyqPx1tG2@NjXiMzmcc9IrHRhHskSF4ZTl479gI7qFoTugIRi4Jb1NauGSDg/NCS8BKPps4EHj1n77WDi5wle3q@cs/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ First input as a number
Nη Second input as a number
Nζ Third input as a number
Nε Fourth input as a number
N Fifth input as a number
E Map over implicit range
ε Fourth input
E Map over implicit range
ζ Third input
⭆ Map over implicit range and join
ι Current frame
⁼ Equal to
η Second input
↔⁻ Absolute difference with
λ Current row
⁺ Plus
θ First input
↔⁻ Absolute difference with
ν Current column
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
Uses [Jonah's method](https://codegolf.stackexchange.com/a/245904/53748) of precalculating the Manhattan distance matrix and then filtering for equality with the step number.
```
;ạ⁵SƲþ/‘=Ɱ
```
A full-program that accepts `[w, h] f [x, y]` and prints a list of frames which are each lists of lists of integers `1` (ripple) and `0` (calm). The coordinates, `w h x y` are all 1-indexed (top-left = `[1,1]`).
**[Try it online!](https://tio.run/##ATsAxP9qZWxsef//O@G6oeKBtVPGssO@L@KAmD3isa7/w6dH4oKsauKBvsK2wrb//1s1LCA1Xf83/1syLCAzXQ "Jelly – Try It Online")** (Footer formats the result for ease on the eyes.)
### How?
```
;ạ⁵SƲþ/‘=Ɱ - Main Link: [w, h]; f
/ - reduce [w, h] by:
þ - table between i in [1..w] and j in [1..h] of:
∆≤ - last four links as a monad - f(i, j):
; - concatenate -> [i, j]
⁵ - third program argument = [x, y]
·∫° - absolute difference (vectorises) -> [abs(i-x), abs(j-y)]
S - sum -> Manhattan distance of [i, j] from [x, y]
‘ - increment (vectorises)
Ɱ - map across (implicit range) [1..f] with:
= - equals? (vectorises)
- implicit print
```
] |
[Question]
[
A truck fleet dispatcher is trying to determine which routes are still accessible after heavy rains flood certain highways. During their trips, trucks must follow linear, ordered paths between `26` waypoints labeled `A` through `Z`; in other words, they must traverse waypoints in either standard or reverse alphabetical order.
The only data the dispatcher can use is the trip logbook, which contains a record of the recent successful trips. The logbook is represented as a list of strings, where each string (corresponding to one entry) has two characters corresponding to the trip origin and destination waypoints respectively.
If the logbook contains a record of a successful trip between two points, it can be assumed that the full path between those points is accessible. Note that logbook entries imply that both directions of the traversal are valid. For example, an entry of `RP` means that trucks can move along both `R --> Q --> P` and `P --> Q --> R`. Note that the trips `A --> B` and `C -> D` do not together imply that `B -> C` is usable. Entries can have the same character twice, such as `C -> C`, but this indicates no paths.
Given an array of logbook entries, your task is to write a function to return the length of the longest consecutive traversal possible; in other words, compute the maximum number of consecutive edges known to be safe. (In even more formal terms, compute the diameter of the largest tree on this graph.)
**Example**
For `logbook = ["BG", "CA", "FI", "OK"]`, the output should be `8`
Because we can get both from `A` to `C` and from `B` to `G`, we can thus get from `A` to `G`. Because we can get from `F` to `I` and access `I` from `G`, we can therefore traverse `A --> I`. This corresponds to a traversal length of `8` since `8` edges connect these `9` waypoints. `O` through `K` is a length `4` traversal. These two paths are disjoint, so no longer consecutive paths can be found and the answer is `8`.
---
**Guaranteed constraints:**
`1 ≤ logbook.length ≤ 100`,
`logbook[i].length = 2`,
`logbook[i][j] ∈ ['A'..'Z']`.
---
**Test Cases:**
`logbook: ["AZ"]`
`Output:25`
`logbook: ["AB", "CD"]`
`Output:1`
`logbook: ["BG", "CA", "FI", "OK"]`
`Output: 8`
`logbook: ["KM", "SQ", "ON", "XM", "UK"]`
`Output:13`
`logbook: ["XU", "WY", "ZD", "HH", "BK", "LG"]`
`Output: 24`
`logbook: ["QR", "PC", "TK", "OE", "YQ", "IJ", "HB"]`
`Output: 23`
`logbook: ["MG", "QQ", "JV", "IZ", "SQ", "PN", "TI", "NK"]`
`Output: 19`
`logbook: ["II", "ZW", "CI", "DT", "IM", "II", "TR", "XO", "AL"]`
`Output: 25`
---
The input will always be an array of strings, each of which has exactly two characters corresponding to the trip origin and destination waypoints respectively. The characters will always be letters, in a consistent case of your choice. The input will never contain more than 100 pairs.
Your program should output the **longest consecutive traversal possible** (number of edges) given the input.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 bytes
```
≢⍉↑⊆⍨∨/≠/∨⍀⎕a∘.=⎕
```
[Try it online!](https://tio.run/##PY69DoJAEIR7nsLuKuUJLDjxBwERPQXpSAw2JNraWSGYYGJhYmmsiI@1L4I7Jkfz3c3N7O2kp7y/P6f58dBSec1aqj5UV1Q86FZQ3VDZmFS9TT6pvtD9mVL5Ggz5gnibGQjXX2ElwmBRPIQlRU@MbC3lFNJiTBxG4GrD9VmuQ7wtGDHkpnPjDctox0hsxmzGkC7Dm@pIuGK5HDEUjGDM2OE/Z44JqXM@GoQw5lu4id67xF6FVoturwOZROiMm60wgWp/Q2FlHDAsT/wA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 39 bytes
```
{⌈/≢¨⊆⍨∊∨¨/{(⊂⍵){1 3 2≡⍋∊⍺[⍋⍺]⍵}¨⎕A}¨⍵}
```
[Try it online!](https://tio.run/##NY4xTsNAFER7TrHdQoEiyAnWNsSOkziON8QxooiETBMJWmTRgGQ5ho1AiAOQyh0VTUof5V/E/NmI5u3szN@dv3pYn94@rtb3d11X0FvVo82ubaguyTRU1VQ1bdMrjql@JvN7UpyJvjinzTeZV6Rmfw1l9jecPvG77ZfCwZcup/KdzJbql/anT@UHZ8nMZWo/SLpcUPkpVSaPciGVI4V0PaudAbRiXAaMKLRuOGadxDAmjBTX@SFK56wXS0bmMXyf4YSM0cDm8Yz11GVouNEFY4mfgiHGHTs0RmsMd3iFKPuvm6JOY5PJoS6AzhZYEsrTGMc6NtAoSyOGGsk/ "APL (Dyalog Unicode) – Try It Online")
-4 bytes thanks to ovs
-6 bytes thanks to following a similar approach to [Jonah's J answer](https://codegolf.stackexchange.com/a/223525/68942)
-6 bytes thanks to a clever observation from ovs
[Answer]
# [J](http://jsoftware.com/), 52 48 41 40 38 34 29 bytes
```
3 :'>./#;._1#.~:/"1+./\a.=/y'
```
[Try it online!](https://tio.run/##NcrZDsFQEAbg@z7FaCWHljlOq5ahokssKRpELEUjQsSNazd99TpaMvmTmf@bZ9YtkdU@NSABGUVFdgeHgEFN3iRTR/BXs1FmAbEBcq2HidAwJa4KA/nxgg5/s6yqLDyEmOSH6NNQw8SJyeCAenqm5LtesBKTzlODH3UZrA5vqIqTotyujxcIcOAOppwyMNfzA1b0pp1DjZh7@FWdvGkWr97Yd0fTKPyZsHK0Cwzn62W02M03fzabObcK3m22@0MwmXjhbMyyDw "J – Try It Online")
Based on [ngn's beautiful insight](https://codegolf.stackexchange.com/a/223587/15469).
-5 thanks to Lynn for realizing an explicit verb would be shorter than a tacit one
This is a corrected answer after the clarification that `ABCD` should return 1, not 3.
## answer before clarification, 52 48 41 40 38 bytes
```
[:>./[:<:@#;._1@OR a.(+/\*+/\.)@e."1]
```
Input is a matrix whose rows are the pairs of strings like `AC`. For example,
let's assume our input is:
```
AC
EB
```
* `a. ... e."1]` - Is each ascii character an element of an input row? This returns a 0-1 matrix like:
```
A C at positions 65 and 67
v v
0 0 0 0 .... 0 1 0 1 0 0 ... 0
0 0 0 0 .... 0 0 1 0 0 1 ... 0
^ ^
B E
```
* `(+/\*+/\.)` - Applies to each row from last step. We'll look at happens
to the first row. Create scan sums from both directions:
```
0 0 0 0 .... 0 1 1 2 ... 2 2 2 <-- +/\
2 2 2 2 .... 2 2 1 1 ... 0 0 0 <-- +/\.
```
and multiply them together `*`:
```
0 0 0 0 .... 0 2 1 2 ... 0 0 0
```
* `[:...OR` Reduce resulting rows by OR:
```
0 0 0 0 .... 0 1 1 1 1 1 ... 0
```
* `[:<:@#;._1` Split on zeroes, and take the length of each resulting segment
of ones, minus 1 `<:@#`.
* `[:>./` Max
[Try it online!](https://tio.run/##NcnNCoJAGEbhfVfxYsFk2WeaRkwZ/oQaapIhmRYRoUSb7n81idbibM7zFhKxBhYHg4I5eNuM4GWxLyq@JbXiG24P13TX7DTDg8ZT9TppI9muSdJuQh7Uz9cHugkLDRTOnJL1a9UdAzpGYG7gOf4@jX6mLTo0e4yS0zE9FEn@Z93oeNlzkZ8v5S4M3SgOmPgC "J – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 86 bytes
* -5 bytes thanks to [kops](https://codegolf.stackexchange.com/users/101474/kops) for suggesting `fst$span(`elem`y)[a..]`.
* +8 bytes to comply with the updated challenge rules.
```
f x|y<-do[a,b]<-x;[a..pred b]++[b..pred a]=maximum[length.fst$span(`elem`y)[a..]|a<-y]-1
```
[Try it online!](https://tio.run/##JYzbboJAAETf@Yp5IFGjS6O2SRvBxEurKzexWFFC4hJWJeVigKaa@O8U6OPMnDkXln/zKCrLE26Pu0yC1GU935PJbeQySfK9btf1JYl5SsxuYfwTuxFPzsVFOuWFmF9Z0j7yiMfHe6fGvQeTyd0j/TJmYaIEqQC0w17akUnDPikt0urI4vjMCy1MeDVHvABTftMsyBGOfCXjLBCDLL1igPp@zcKkEE8Vo/hVrL3ldIHZBB8Upgoyxqug6vi0YBpwdGybrj8UnC12exzmWC4xVaEt6n7wLFgbrGewVZjv2FugKyynzTQU9AUsC6sv0EMtXBuwKYx/4ZtAKQ47zCjmNqiOKtobOCYmWnN/@QM "Haskell – Try It Online")
The function `f` takes the logbook `x` as input (as a list of two-character strings) and returns the longest possible traversal.
## How?
```
f x| -- f is the function that takes a logbook x
y<-do[a,b]<-x; -- define y to be the concatenation for each "ab" in x
[a..pred b]++[b..pred a] -- of the two ranges [a..pred b] and [b..pred a] (one of which will be empty)
=maximum[length. -- f returns the maximum length
fst$span(`elem`y)[a..] -- of the longest range starting from a whose elements all belong to y
|a<-y] -- where a is a character in y
```
[Answer]
# [R](https://www.r-project.org/), ~~61~~ ~~69~~ 65 bytes
```
for(i in scan(,""))F[(j=utf8ToInt(i)*2):j[2]]=1;max(rle(F)$l)%/%2
```
[Try it online!](https://tio.run/##VZBBb4JAEIXv/RUbrMluQ9NAa2JtPYAURVSkXStiPBACCcaCwSWlbfrbKZkhDZy@3XlvZudtXsXk@ZbERRqKJEtpycgPuYRB2ql@yd@sJD0eXQT5zIPzOcqrOMtpQpIU3FSWJMbMPT2OCxEPeWalgibsRmWj4149HMbK00dQ0vwUUZNdn1j/rq9Wv1cxDalkWXUrHjW/PvaIU4hzIUbqoKnqkkykidHWFJT0aS3VmgYwLYBjt51kiFZ7CeKbi54VwMPiptOh3GOHtwFxuwP4BmA2A@g2YDHtPKU@YKf7Cup6AuDodV4AO1zAmuM4vTugeXqJuVz0zt@xxW8nWGMCjplX3czK4//fwu5b/Ca8GRzHYfbGwnFlzwFoi@5ag@oP "R – Try It Online")
Unfortunately, edits made to the task specification broke the original answer :(
On the brighter side, the changes needed to fix it were not so drastic.
### Explanation
First, we use `utf8ToInt` to convert the characters to their byte values.
Then, we fill the vector `F` with ones at the range of positions from start byte to end byte. R allows assigning to indices outside of existing range, and upon such assignment sets all preceding empty positions to `NA`. Finally, we take Run Length Encoding and return the length of the longest run. Conveniently, `rle` doesn't list all `NA` as a single long run, but rather as many runs of length 1.
In the original version, ranges such as `AB CD` became fused together:
```
... A B C D ...
... 64 65 66 67 68 69 ...
... NA 1 1 1 1 ...
```
To resolve this, we simply multiply the range boundaries by 2, and thus gain a separator between adjacent routes when they don't overlap:
```
... A B C D ...
... 129 130 131 132 133 134 135 136 ...
... NA 1 1 1 NA 1 1 1 ...
```
Finally, integer division by 2 gives the desired result.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~79~~ 71 bytes
```
->a{r=c=0
a.map{|i|r|=-1<<i.ord^-1<<i[1].ord}
(c+=1;r&=r*2)while r>0;c}
```
[Try it online!](https://tio.run/##VZBha8IwEIa/91eECmObU5puwpxGaNVprVrr6qwtHdQ6WUFZCZYxrL@9Y3cRmk9P8t57l3vD8@1vuWdloxefOUuYpsTNY5ydi7TgBWvQbjdtfvPdB5xCGv1fLsptUme0w28Yv9fvfr7SwyfhPa2TXMqM7MNQNQw1ikjNyU9ZfnrRFKGaVZVe1aCq6i0hmyP1gRC1bwBeLYBjV73kWXjtGVTfXDTNAT6KK6mFPooWfwXV9QYQDADjMcC0AdOR9Jj@JFrdJZQXfYCHZmcI2OAK1gTnmfKE6@MzzOaiefKOPUE1xAJDeJh7LuembTHIwnKwxr/C28DDeZhfWDxc2ncAxlRerFX@AQ "Ruby – Try It Online")
Ruby probably isnt' the best language for this bit twiddling approach, but I haven't seen it yet so it's worth posting. The idea is to take `-1` and shift it to the left according to each letter, then XOR it with the other letter in the pair. It's best explained with an example (ignore 64 zeroes missing to the right.)
```
B -> ...1111111100
G -> ...1110000000
XOR ...0001111100
```
Thus there are 5 clear paths between `B` and `G`.
These are then combined by `OR`ing together.
At the end of `["BG", "CA", "FI", "OK"]` we have `r=111100111111110` (plus 64 trailing zeroes).
To find the longest run of `1`s, we now count the number of times `r` must be `AND`ed with `r*2` until `r` becomes zero. Each time we perform this operation, the length of each group of 1's is reduced by one.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
IL⌈⪪⭆α⬤θ⊖ΣEλ‹ιν1
```
[Try it online!](https://tio.run/##HYrBCsIwEER/JeS0Qjx49lQrirRFIcfSwxJDG9jEmqzi38ekc3gMM88sGM0LKedHdIGhxcTQ2zDzAgP@nP940Cs5Bs1FmAdcAZVoiOCtxNmaaL0NbJ@gi1lfUqK3KYFTIuy2KCEPcmvHnMdRnq6yTG1TeblV3js5TXn/pT8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: For each uppercase letter, compare it against all of the logs to see whether it precedes neither or both entries, resulting in a string of exclusions e.g. `00000000110000111111111111` for an input of `BG`, `CA`, `FI`, `OK`. Split that string on `1`s and output the length of the longest string of `0`s.
```
α Predefined uppercase alphabet
⭆ Map over characters and join
θ Log array input
⬤ All satisfy
λ Current log
E Map over elements
ι Outer character
‹ Less than
ν Inner character
Σ Summed
⊖ Decremented
⪪ 1 Split on literal `1`
⌈ Take the maximum (longest)
L Take the length
I Cast to string
Implicitly print
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 71 bytes
```
A`(.)\1
%O`.
%T`L`_L`.$
\B
-
¶
~`.+
.+¶26$*¶Y`\_`L¶[$&]¶_
L`_+
O^`
\G_
```
[Try it online!](https://tio.run/##FcsxUsMwFEXR/q/DZgJ@0Uwo6CUbbEWyFSVKYhsHf4oUaSgYapalBWhjJpR35tzv68/t63Oz5KsDY5G8Eo/ThnLHgvLAlmfLIqNJ0ZpSJPplUZAoUnx@yZ5SHHia2ab4nj1cUpzp7gtyH0xTPS@LHEkqlBWpGqXEm4YzZFocPFyHvsXRUH/EecBYoWmgDGxNfo9diWDgXjF46C0aRW0N77E9QY//@65D0OgMaY3xjFKjCtAt7hn26B2k/QM "Retina – Try It Online") Takes a newline-separated list, but the test suite takes a comma-separated list for convenience. Explanation:
```
A`(.)\1
```
Delete identical pairs, as they have nothing to contribute (other than crashes).
```
%O`.
```
Sort each pair of letters into order.
```
%T`L`_L`.$
```
Decrement the second of each pair, as the ranges are effectively half-open intervals.
```
\B
-
```
Insert a `-` between each pair of letters.
```
¶
```
Join all of the letter ranges together.
```
~`.+
.+¶26$*¶Y`\_`L¶[$&]¶_
```
Wrap the letter ranges in Retina code that replaces legal edges with `_`s, then evaluate that code.
```
L`_+
```
Keep only the runs of `_`s, discarding any remaining letters.
```
O^`
```
Sort the longest first.
```
\G_
```
Output its length.
Example of generated Retina code for the input `BG`, `CA`, `FI`, `OK`:
```
.+
26*
Y`\_`L
[B-FA-BF-HK-N]
_
```
Explanation:
```
.+
26*
```
Replace the ranges with 26 `_`s.
```
Y`\_`L
```
Cyclically transliterate the `_`s to uppercase letters.
```
[B-FA-BF-HK-N]
_
```
Replace all the legal edges with `_`s.
[Answer]
# [Haskell](https://www.haskell.org/), ~~77~~ 66 bytes
```
f l=maximum$scanl(\m c->sum[m+1|any(foldr1(/=).map(c>))l])0['A'..]
```
[Try it online!](https://tio.run/##JY3LToNQFEXnfMUekACxVGk10VhIgGp7SymlUvuyg1selXgvEGijJn67CHVwBmets/d5p9VHzFhdJ2A6p18pP3OxCmnG5DeOUDWqM9/xK@2HZt9ykrOo1ORrXelyWsihoShsr9zsJFPqdvc1p2mmR7kAyGknVwZqVdCsuZZUSRmIxjE@TdMsbjSLT6D6Z15GFdLHg17GNBKjMi/QQxsvyjQ7iTLtHDoJaDu6flAa0X6oTQv2EKoBTbBGsE08E3hOC@4Fx8WLD2@GtYvlhWl9Yb3EaoPtEOMxLAfTUct7t4K/wNxG4MB7wsYHmWBsXVRfcEfwfUxeQbZt4XyGgGD2X/ggEILtCjbBMABx0azBAmsP5vQSv/sNE0aPVa2GRfEH "Haskell – Try It Online")
-11 bytes thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor) by reformulating as a `scanl` and informing me that `['A'..]` is a finite list!
`f` computes for each character in effectively `A..Z` whether or not it is starting point of a traversable leg, and keeps track of the running count.
The magic is in the condition `any(foldl1(/=).map(c>))l` which makes use of the fact that `x` is comprised of length 2 strings. `map(c>)` asks whether each endpoint of the journey is beyond `c` and `foldl1(/=)` takes the `xor` of the results, so `c` satisfies this condition only when it is in the half-inclusive journey. If `c` satisfies this for any journey, our count will get incremented, otherwise reset to `0`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
ØA<þ^/€€|/ṣ0ṀL
```
[Try it online!](https://tio.run/##FYsxDoIwAEX3nuLfAA/gUkChlFKKRaCDm4vhAiYOxsXdid3VyThITFyIB6kXqTX5@S//JX@37fu9c9NA59N7E3xPN59DYMfrzI7H3NnXwz7v3k1nX5@LHQfPzjlqCA0RxSRMEFEsGSQnXGClIAu0AjUnbY2mg4mRpgg58oSoCmUEzSEX6BRYhjQkIoFSyNZg5n8vC2iGghPGYBpEDLEGE/BTV2glaP4D "Jelly – Try It Online")
This steals the idea to check if a letter precedes neither or both bound to determine if it's in range from [Neil's Charcoal answer](https://codegolf.stackexchange.com/a/223505/68942). Go upvote them!
## Explanation
```
ØA<þ^/€€|/ṣ0ṀL Main Link; takes a list of pairs of characters
þ Make a product table
< using the < operator
ØA between the entire uppercase alphabet
and the input (gives a list of lists of pairs)
€ For each sublist (corresponding to a input pair)
€ For each pair (corresponding to each letter in the alphabet)
^/ Reduce by logical XOR (now a list of length-26 lists each being 0 or 1 depending on if the letter is in the range)
|/ Reduce the entire thing by logical OR (now a length-26 list with 1 where the letter is in a range and 0 otherwise)
ṣ0 Split at 0s
Ṁ Maximum
L Length
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 177 bytes
```
b=>Math.max(...b.map(t=>[...t].sort()).sort((w,x)=>(w[0]>x[0])-.5).reduce((r,x)=>x[0]<p[1]?(p[1]=(x[1]<p[1]?p:x)[1],r):[p=x,...r],p=[]).map(g=>(i=parseInt)(g[1],36)-i(g[0],36)))
```
[Try it online!](https://tio.run/##XZBNT8JAEIbv/grT005SNhijMcStaUGhQCnVIqVNDwUBayJulhX67@t2xgPpZZ7Zd9@dj/0qTsVxo0qpO6eHeifqtXCCQn/y76JinPO1SSTTwsnMQef8@KM0AyCys12BcNg56@ZOZQJ0@B1wtf343WwZU3jb6I8yu8mfWBMFq0wkQfYqMLQV9DIpKtu0ULktRZYDtt2b2qWQhTpu/YMGtm/Mt/fQKU3axRSglqo8aLZjmeWmVg5wdSF4ln1t9Qct2Rsa2egu4sVHhJOWaxKg/hbR9QyRkLhom5MF6ssVIh0gRiOEN0FMh6030Svq8z4iJlf4jFhRV39MhbzW04A2iMg1fidzejnwnAaOabtZe2Cf9HRJX0GnQUyFaMl/S0xjJiHCnTaF6j8 "JavaScript (V8) – Try It Online")
Tried to do this without looking at any of the other answers' tricks. This can potentially be pretty heavily outgolfed.
] |
[Question]
[
\$P\_k(n)\$ means the number of partitions of \$n\$ into exactly \$k\$ positive parts. Given \$n\$ and \$k\$, calculate \$P\_k(n)\$.
>
> Tip: \$P\_k(n) = P\_k(n‚àík) + P\_{k‚àí1}(n‚àí1)\$, with initial values \$P\_0(0) = 1\$ and \$P\_k(n) = 0\$ if \$n \leq 0\$ or \$k \leq 0\$. [[Wiki]](https://en.wikipedia.org/wiki/Partition_(number_theory)#Restricted_part_size_or_number_of_parts)
>
>
>
# Examples
```
n k Ans
1 1 1
2 2 1
4 2 2
6 2 3
10 3 8
```
# Rules
* General [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~61~~ ~~55~~ ~~51~~ 50 bytes
*-10 bytes thanks to Erik the Outgolfer. -1 byte thanks to Mr. Xcoder.*
I will say, I did copy the hint from OP and translate it to Python. :P
```
P=lambda n,k:n*k>0and P(n-k,k)+P(n-1,k-1)or+(n==k)
```
[Try it online!](https://tio.run/##Tc3BCoMwEATQe75ij1ldwaSlByF@g/fiIcWWhm03EnPp16dWKTinBwMz8yc/o9hSBvfy79vkQYg7qbhvvUwwaGmYGOsfDHFjMKZai3OMJd@XvICDq4I12hAYpN2WwP59PvhysGkJTqhGpR4xQYAgsC12Wz2nIHn9rwKWLw "Python 2 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 7 6 bytes
-1 byte thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer)!
```
/lM./E
```
[Try it online!](http://pyth.herokuapp.com/?code=%2FlM.%2FE&test_suite=1&test_suite_input=1%0A1%0A%0A2%0A2%0A%0A2%0A4%0A%0A2%0A6%0A%0A3%0A10%0A&debug=0&input_size=3)
Inputs to the program are reversed (i.e. `k, n`).
[Answer]
# [Swift](https://www.swift.org), ~~76~~ 73 bytes
```
func P(_ n:Int,_ k:Int)->Int{return n*k>0 ?P(n-k,k)+P(n-1,k-1):n==k ?1:0}
```
[Try it online!](http://swift.sandbox.bluemix.net/#/repl/5978b4a324f31b189780f907)
---
# Explanation
### How does the code structurally work?
First of all, we define our function `P`, with two integer parameters `n` and `k`, and give it a return type of `Int`, with this piece of code: `func P(_ n:Int,_ k:Int)->Int{...}`. The cool trick here is that we tell the compiler to ignore the names of the parameters, with `_` followed by a space, which saves us two bytes when we call the function. `return` is obviously used to return the result of our nested ternary described below.
Another trick I used was `n*k>0`, which saves us a couple of bytes over `n>0&&k>0`. If the condition is true (both the integers are still higher than `0`), then we recursively call our function with `n` decremented by `k` as our new `n` and `k` stays the same, and we add the result of `P()` with `n` and `k` decremented by 1. If the condition is not true, we return either `1` or `0` depending on whether `n` is equal to `k`.
### How does the recursive algorithm work?
We know that the first element of the sequence is **p0(0)**, and so we check that both integers are positive (`n*k>0`). If they are not higher than 0, we check if they are equal (`n==l ?1:0`), here being two cases:
* There is exactly 1 possible partition, and thus we return 1, if the integers are equal.
* There are no partitions if one of them is already 0 and the other is not.
However, if both are positive, we recursively call `P` twice, adding the results of `P(n-k,k)` and `P(n-1,k-1)`. And we loop again until `n` has reached 0.
---
\* *Note:* The spaces cannot be removed.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
œċS€ċ⁸
```
[Try it online!](https://tio.run/##y0rNyan8///o5CPdwY@a1hzpftS44////4YG/40B "Jelly – Try It Online")
[Answer]
# Mathematica, 33 bytes
```
Length@IntegerPartitions[#,{#2}]&
```
here is n x k table
```
\k->
n1 0 0 0 0 0 0 0 0 0
|1 1 0 0 0 0 0 0 0 0
v1 1 1 0 0 0 0 0 0 0
1 2 1 1 0 0 0 0 0 0
1 2 2 1 1 0 0 0 0 0
1 3 3 2 1 1 0 0 0 0
1 3 4 3 2 1 1 0 0 0
1 4 5 5 3 2 1 1 0 0
1 4 7 6 5 3 2 1 1 0
1 5 8 9 7 5 3 2 1 1
```
[Answer]
# JavaScript (ES6), ~~42~~ ~~40~~ 39 bytes
I think this works.
```
f=(x,y)=>x*y>0?f(x-y,y)+f(--x,--y):x==y
```
---
## Try it
```
k.value=(
f=(x,y)=>x*y>0?f(x-y,y)+f(--x,--y):x==y
)(i.value=10,j.value=3)
onchange=_=>k.value=f(+i.value,+j.value)
```
```
*{font-family:sans-serif}input{margin:0 5px 0 0;width:100px;}#j,#k{width:50px;}
```
```
<label for=i>n: </label><input id=i type=number><label for=j>k: </label><input id=j type=number><label for=k>P<sub>k</sub>(n): </label><input id=k readonly>
```
[Answer]
## Haskell, 41 bytes
```
0#0=1
n#k|n*k>0=(n-k)#k+(n-1)#(k-1)
_#_=0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/30DZwNaQK085uyZPK9vOwFYjTzdbUzlbG0gbaiprZANJrnjleFuD/7mJmXkKtgoFRZl5JQoqCoYGCsoKxgr/AQ "Haskell – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
y:Z^!S!Xu!Xs=s
```
[Try it online!](https://tio.run/##y00syfn/v9IqKk4xWDGiVDGi2Lb4/39DAy5jAA)
### Explanation
Consider inputs `6`, `2`.
```
y % Implicitly take the two inputs. Duplicate from below
% STACK: 6, 2, 6
: % Range
% STACK: 6, 2, [1 2 3 4 5 6]
Z^ % Cartesian power
% STACK: 6, [1 1; 1 2; ... 1 5; 1 6; 2 1; 2 2; ...; 6 6]
!S! % Sort each row
% STACK: 6, [1 1; 1 2; ... 1 5; 1 6; 1 2; 2 2; ...; 6 6]
Xu % Unique rows
% STACK: 6, [1 1; 1 2; ... 1 5; 1 6; 2 2; ...; 6 6]
!Xs % Sum of each row, as a row vector
% STACK: 6, [2 3 ... 6 7 4 ... 12]
= % Equals, element-wise
% STACK: [0 0 ... 1 0 0 ... 0]
s % Sum. Implicitly display
% STACK: 3
```
[Answer]
# [Haskell](https://www.haskell.org/), 41 bytes
```
n&0=0^n
n&k=sum$map(&(k-1))[n-1,n-k-1..0]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0/NwNYgLo8rTy3btrg0VyU3sUBDTSNb11BTMzpP11AnTxfI1tMziP2fm5iZp2CrUFCUmVeioGFooKCmYKz5HwA "Haskell – Try It Online")
An alternate recurrence.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 35 bytes
[Pari/GP has a built-in for iterating over integer partitions.](http://pari.math.u-bordeaux.fr/dochtml/html/Programming_in_GP__control_statements.html#forpart "forpart")
```
n->k->i=0;forpart(x=n,i++,,[k,k]);i
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y5b1y7T1sA6Lb@oILGoRKPCNk8nU1tbRyc6Wyc7VtM6839BUWZeiUaahqEmEGlywbhGmkCE4Jqgcs1QuYYGmhrGmpr/AQ "Pari/GP – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÅœIùg
```
[Try it online](https://tio.run/##yy9OTMpM/f//cOvRyZ6Hd6b//29owGUMAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P/DrUcnRxzemf5f5390tKGOYaxOtJGOEZA0AZNmYNLQQMc4NhYA).
**Explanation:**
```
Ŝ # Get all lists of positive integers that sum to the first (implicit)
# input-integer `n`
√π # Only keep the lists with a length equal to
I # the second input-integer `k`
g # Pop and push the length to get the amount of remaining lists
# (which is output implicitly as result)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~41~~ 40 bytes
```
f(n,k){n=n*k>0?f(n-k,k)+f(--n,--k):n&k;}
```
[Try it online!](https://tio.run/##Zc7BCsIwDAbge59CBkqjLbTdGGJR8T16kUpllAXR3saevXbdYdaFXJJ8/MTyp7UxOorMw4Bn3PuLuKaR@7Q4OMo5Ms49nHDn9Rj7e4cUyEA2qV7vDoOjFZrgTbjhx4Q5yGAFuiDShLm3j3RkjkomAfRECqdMUIVTTMFfVpONWkyzNm0G9WLatZEii@PPU4LVkxpJ/AI "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
I ~~have a feeling~~ [know](https://codegolf.stackexchange.com/a/135878/53748) this basic approach **won't** be the golfiest!
```
RŒṖL€€Ṣ€QṀ€=S
```
**[Try it online!](https://tio.run/##y0rNyan8/z/o6KSHO6f5PGpaA0QPdy4CkoEPdzYAKdvg////Gxr8NwYA "Jelly – Try It Online")**
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
L²ã€{ÙO¹¢
```
[Try it online!](https://tio.run/##AR4A4f8wNWFiMWX//0zCssOj4oKse8OZT8K5wqL//zEwCjM "05AB1E – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 18 bytes
```
{_,:)@m*:$_&::+e=}
```
[Try it online!](https://tio.run/##S85KzP1fWPe/Ol7HStMhV8tKJV7Nyko71bb2f91/YwVDAwA "CJam – Try It Online")
Expects inputs in reverse, i.e. `k n` instead of `n k`.
[Answer]
# R (+ pryr), 49 bytes
```
f=pryr::f(`if`(k<1|n<1,!n+k,f(n-k,k)+f(n-1,k-1)))
```
Which evaluates to the recursive function
```
function (k, n)
if (k < 1 | n < 1) !n + k else f(n - k, k) + f(n - 1, k - 1)
```
`(k < 1 | n < 1)` checks if any of the initial states are met. `!n + k` evaluates to TRUE (1) if both `n` and `k` are 0, and FALSE (0) otherwise. `f(n - k, k) + f(n - 1, k - 1)` handles the recursion.
[Answer]
# [Scala](http://www.scala-lang.org/), 98 bytes
Well this is some easy unreworked use of OP's tip.
`k` and `n` are the parameters of my recursive function `f`.
```
def f(n:Int,k:Int):Int={(k,n)match{case(0,0)=>1
case _ if k<1|n<1=>0
case _=>f(n-k,k)+f(n-1,k-1)}}
```
[Try it online!](https://tio.run/##Vc2xCsIwEAbgPU9xdEowhaSWDtIEHB18BolpijU1FptBqH32mIBau/z8dx/cjVr1KtzPV6M9HFXnwDy9cc0I@2GYUGhMCy12u4Pz1KYkKcSELXXkpry@TFqNBjPKiJAcpQFO0LVga/5yNReSfZZCxkO5pZZsUuHU5pzMc0DDo3O@dzjjlEMuIYseKyGLFLT4Sqz/Ui5SrqVapFoLZ3T7exR7NDSHNw "Scala – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
ṄvL=∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuYR2TD3iiJEiLCIiLCI2XG4yIl0=)
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ŒṗẈ=S
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7pz/c1WEb/P//f0OD/8YA "Jelly – Try It Online")
Dang it, ninja'd by Kevin because I took the time to get the shortest jelly answer too :p
Exact same approach as the 05ab1e answer, derived independently - both answers get the integer partitions of the first input and then count the number of partitions where the length equals the second input.
[Answer]
# Regex `üêá` (Perl/PCRE+`(?^=)`[RME](https://github.com/Davidebyzero/RegexMathEngine)), ~~32~~ 28 bytes
```
^((?^=(\2?x))(\1|^x)x*)+,\2$
```
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Restricted-Integer-Partitions-PCRE) (RegexMathEngine)
Takes its input in unary, as the lengths of two strings of `x`s delimited by a `,`, specifying \$(n,k)\$. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.)
This simply enumerates all the partitions. In order to count unordered partitions, it enforces that partitions occur in strictly nondecreasing order. This is accomplished by starting with an arbitrary-sized partition on the first iteration, then increasing it by an arbitrary nonnegative integer on each subsequent iteration. Each iteration increments the counter, which is then compared with \$k\$ at the end.
On each iteration, the size of the partition (arbitrarily chosen) is captured in `\1`, which is accessed via a nested backreference. The counter is stored in `\2`. Lookinto is used to ensure there is room to read and increment `\2` on each iteration.
```
^ # tail = N
( # \1 = the following, looping:
(?^= # Lookinto; tail = N
( # \2 = sum of the following:
\2? # previous value of \2 if set, else 0
x # 1
)
)
# \1 = the sum of the below items
(
\1 # On subsequent iterations, \1
|
^x # On the first iteration, 1
)
x* # any nonnegative integer
# \1 = some of the above items
)+ # Iterate the above as many times as possible, min 1
, # Assert tail == 0; tail = K
\2$ # Assert tail == \2
```
This uses nested backreferences (supported by Java / Perl / PCRE / .NET), a branch reset group (Perl / PCRE / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), and a **lookinto**, a feature just added to [RegexMathEngine](https://github.com/Davidebyzero/RegexMathEngine). The parameterless form of it, `(?^=pattern)`, is equivalent to one of the common uses of variable-length lookbehind, `(?<=(?=pattern)^.*)` – it allows matching against the entire string, even after the top-level cursor has advanced past the start. It also has a parametrized form, e.g. `(?^5=pattern)` will match `pattern` against the current contents of `\5`.
# Regex `üêá` ([RME](https://github.com/Davidebyzero/RegexMathEngine/) / Perl / PCRE2 v10.35+), ~~36~~ 34 bytes
```
^((?|(?=.*,(\2x))\1x*|^(x)+))+,\2$
```
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Restricted-Integer-Partitions-PCRE2-v1035) (RegexMathEngine)
[Try it online!](https://tio.run/##Rc7LaoQwFAbgfZ8ihDPDOSZ4K7NoYwzCdNtVl6IUW2FQM0OYRYraV7epXXT188N3LrdPN5626YuBU2wer937yCBRoeriXL1V5foAky5K1V8dgtWZAltomEIIQTPYMjseb@5i77y2XLGdDb9sCMyG2Nnwz1hQ0OlUIXLPPViKueTxXxmI9HeC5hkcoTGzENDJdKXw0T7dM354/OASurBkCWfWtW1fXs9tuzWIZkGj40hinXuiOvPR0qAnQSRkncO25U8/ "Perl 5 – Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=Rc7NSsNAEAfwu0-xLGOZ6a5pkx4UN5ulUK-ePIYGSQ1Ikm1ZKqwk8UW8FNEn8Sn6Nq6J4Ok_A7_5eP88PLnmdP5uXxk4xbpmXz42DBYqtDrdrB_W2XABrU4zVe0dgtWxAptqaEMIQR3YLJ7NDu7ZHnluuWIjq39ZHZgNMbL6n7GgoNRLhcg992Ap4pJHU1MT6bcFmltwhMZ0QkAplwOFj8bpivHL1Y5LKMOSPpwZhqK4u98UxdfLsbq6OfMtounR6GguMU88UR77eb9FT4JIyDyBSZ7-4iO5nqof "Perl - Attempt This Online") - Perl v5.36+
[Attempt This Online!](https://ato.pxeger.com/run?1=hVZfT9tIEH895Qvc6-Beya5tOBJ0FSIxiEIkkFqo0qDrNVDLOOvEir227HWBXvkk93I66R77gXqf5mb_OHESTmdhZ3Y889udmd-M-eNbmCdVKW9_GobfxtZOkocF6-4cWLffhy8mLIo5g3enw0HXP706G_jXlxcj_9eLs9E5HLRexDxMqgmDvnLanR21wllQgJ-Pb8GDofX6_n5-t1_99vj4YTR7dT8jf1ci2jn4bn0i5PgrOfZ2bZfcdB8ovek82F8_kQfqUOq4N92ftOU_P_xI10EsF-zc83On02ucoBRFzKfyCEtdnKGWBenRht1RK-YCchSFz4oiK0iY8VKAOr6dsrIMpozC76WYHB6GaAH9Phi1FJWe8UnSg4KJquDQ6T1tYMp1mE2YC3dZlkDmRUFSSli1jYEbd395ddtrAV5xBERl0p8yg-EbK6JxiC7F9en5yfDApualC2X8hWURWRz851rTsKeUql3kRTI41kGEWSXgEBaBUhmepdxAneAQrLXglbNloZd1wy26yEeENJrpSBZJaT21Kl7GU84mkGR8qh8BL-9Z0VMJSx_9MEgSPIaJ3az8uyQL52CHLnzO4gnYk0AEmDuZJCmC5wGRb2y6vcSgBttxFpXZM5VJg5gTBFAHzMdIhIRxktOdzq2319MhaHZAHnoWOT60eig5Xq5_LEqOT_HeoqivEHG_6wssKvpK-CkKCroJFPO8EtJdBYYlBLtg9ToNRDjzVSz2UtZoBSurRLi6BD3Tge8vPg6UJopKhi8xXgxhKmYrBnb2mYUCvUwlsBPr_dM8ThgxpHj_bjSkebgb-nhYQl2D8XEwvPJHg-Hbi8uT0eCsVg8-jAaXZ3K9rc5kfs1J9uiSwVsFEtDkvtkN6mnsGqF7G9nwcR0I5kdFlvp5IAQrOCmQ5ZfXb94YgKYPtq5gDwKTWEvec-8NLNlAwQgWFKwh3AYv3ed4tg6gt0riNG6C7HRor2E0Ybn4X6OChVVRxhl_1nBJMZwRCU5nols35q5mG9UESjEJgchiopR1kY2_HnMlmnB2r1fj1Ok4eJtRFGUFqPnFvU4PeN9L8ek4dfvUteZHHQqILyFI-4a3zQYrEHMJMe97HJ-rEDXMfAUGmiiKLSzFxJBSyi60H9oucAxz4yrHHEB-edpu-3kEhzsdgzA3icIOknnA6Oc4BMa4lAh7q_56qCi9ac1Vjil6NvuqdCUwNob6W3IbZVPOtRhlGjRyfw-2t80uW57pvuHwauhfXr09GZ2e0xVHRcNGm9WTQxQVW9uD4ddnLfsL74hYL_cn-G3VoWJyIjXPJb2WfK-vp9aq9PRfTYlNzBhZxrzZ7NpgsabNaalf4jxZDHMdHX5W9P8Hf_7V7WjpXw "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+
[Attempt This Online!](https://ato.pxeger.com/run?1=hVbLbttGFF1XXzFmCmuGolxRbg1DNC24tgAbSOyAkdE0tkPQ1EgiTA4Jchg_Gm_7Ad12002X2fVn0mW_pHcepEhLRQWRmse95z7njH7_EmZxWYjHX4ThlyujH2dhTof9fePmq_dqRucRo-jtsTcZ-scXJxP_8vxs6v90djI9RfudVxEL43JG0YFU2lkedsJlkCM_u7pBLvKMH-_v7253y58fH99Pl3v3S_xnyef9_a_GR4zHn_HY3TEtfD18IOTafjA_f8QPpEdIz7oefqsk__5mm7wEMSxkZq6f9Wyn4UHB84gthAurtSiFVRokh2tyh52IcZTBkPs0z9MchykrOJLumwktimBBCfql4LPRKAQJdHCA9LIYynXKZrGDcsrLnCHbeV7DFPMwnVEL3aZpjFJ3HsSFgJVmNNzV8Ie9G6eD4BPNEZaZ9BdUY_haCiscrEpxeXx65O2bRG9aqIieaDrHtePfVSsNeUKItCI-OEVjFUSYlhyNUB0oEeEZUg1JD0bIeBG8VDYM0DKumUHqfMyhjZYqkjopnedOyYpowegMxSlbqFfAinuaOzJhyaMfBnEMbujY9cy_jdPwDpmhhT6l0QyZs4AHkDuRJDFErouw2DHJ9gqDaOxer67MQFcmCSKGAUA6mF1BI8SU4Yz07Rt34KgQVHegLHQNPB4ZDox6bqZ-DILHx_BsEVgvAXF36HMoKugK-AUMJHQTKGJZyYW6DAxKiMycVvMk4OHSl7GYq7FCy2lRxtxSJXD0CXx39mEiV-bzgsImxAshLPiyJWCmn2jIQUtXAk5iZT_Jophi3RTv3k49koU7oQ_OYmJpjA8T78KfTrw3Z-dH08lJtTx5P52cn4j5tvRJ_2pPBmTVwVs5NKDOffM0yLeWa4TurmXDh3nAqT_P08TPAs5pznAOXX5--fq1BmjqwNHl9IFDEquRu2lfw-I1FIigbsEKwmr0pbWpz14CKFNxlERNkL5NnIbQjGb8f4VyGpZ5EaVso6A0O09zJNnlqe5cYIwYuBqrgxwxS_UecaqOr8rzRBCsCwbC3WvWBdNPru3ILamxI5gDE9cdECQsR6ykzgoBjELPCbOKK4vVXu1VlhYg0LJc6TJ674O-hRgUKeBppI3qJkQ9oUyctp6gRVh9AVefNUlhgrUsw1mXADtYuGoSKD_ULsQFFFT7AZvi3UM2PEyYt8kGjCsQ6vXEnda1uu39Z0SB0ze5tjKcKLsNoxtNPbdmCU2gG3ABgjJh3YcuZA3KJb0RGApNeFU1QZUJ1gaG5IGQSjRc6DMMUVhyVTpRJVgwaoO8RiMms34LebtzlLgrKH3d33YZ0D-__oaAIxUTS_dqScVr7QMqz3aTlKBAMuSB_K6IAcb6LDQyJ5xXqAcDtL2tLWy5mrY878Lzzy_eHE2PT0k7Kw1uquiW5yVtYIvStnRager4Nlx_z__FUcBplOJVFOvcpwTqOWleHmoT6LW-25TfcMuqv0t__GVbdmdoDTvfw7MHjz2wdtXevw "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+ - test cases only
Without lookinto, there's still always room within \$k\$, accesible via lookahead, to count iterations.
Starting with a positive arbitrary-sized partition on the first iteration is done by `^(x)+`, which also initializes the counter to \$1\$. On subsequent iterations, `\1x*` advances by the sum of `\1` and any arbitrary nonnegative integer, which also gets captured in `\1`. At the end, `,` asserts that the cumulative sum is equal to \$n\$.
To enforce \$k\$ as the number of partitions, it starts by setting `\2` \$=1\$ on the first iteration with `^(x)+`. On subsequent iterations, `(?^=(\2x))` increments `\2` by \$1\$. Lookahead is used to avoid not having room for `\2`\$+1\$ when nearing the end of \$n\$. The Branch Reset Group `(?|`...`|`...`)` allows `\2` to be captured/recaptured in these two places.
```
^ # tail = N
( # \1 = the following, looping:
(?| # Branch Reset Group
# This alternative can only match on iterations after the first, because
# it unconditionally matches \1 and \2.
(?= # Lookahead
.*, # tail = K
(\2x) # \2 += 1
)
\1x* # \1 += {any nonnegative integer}; tail -= \1
|
^ # Anchor to start, to only match on the first iteration.
(x)+ # \2 = 1; \1 = {any nonnegative integer}; tail -= \1
)
)+ # Iterate the above as many times as possible, min 1
, # Assert tail == 0; tail = K
\2$ # Assert tail == \2
```
# Regex `üêá` ([RME](https://github.com/Davidebyzero/RegexMathEngine/) / Perl / PCRE2), 50 bytes
```
^((?=(?(3)(\3)))((?|(?=.*,(\4x))\2x*|^(x)+)))+,\4$
```
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Restricted-Integer-Partitions-PCRE2-all) (RegexMathEngine)
[Try it online!](https://tio.run/##RY49a8MwEIb3/gohruEuEs6Hk6GVZRFI104dRUxwGwi2lSA6qNjuX3ev7tDp5bl77uP@Edv91H0JiEb07a0@twJWhtEWx8PboRwfoLNFaS63iBDsxkAoLHQcSlEPodwsFvd4DZ/SB2nErDW/WsNa4Ji15l8TbEFt1wZRJpkgUCa1zP6gIbLfK3TPEAmd65WCWq9H4o/m6YuQj/m71FDzkoHPjGNVvbweq2o6ITqLDnNCnxMR48CVbKnR7xKR36blcMJEiptK@x1M0/bpBw "Perl 5 – Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=RY7BSsNAEIbvPsWyjGWmG9M26UHdbEKhXj31GBokbUCSbMtSIZLEF_FSRJ_Ep-jbOCaCp3_-me-fmffP495V58t3_SrAadFWh_ypEjDTbE20Xm1WcX8FtYliXRwcgjULDTYyULMoRS3YeDGZHN2zPcnUSi0GrPzFSsYsy4CV_5hgCnIz14iykQ1Y8qUn_dGUROZthsk9OMIkaZWC3Jv3xB8N6ULI63AnPch5Scdn-j7LHh7XWfb1cipubi_BFjExmGBImIZExLbjjj_1MF02RGnQTLstNqR4qLx0CWPy_Ccfwd1Y_QA "Perl - Attempt This Online") - Perl v5.36+
[Try it online!](https://tio.run/##hVVtT9tIEP6eXzG4d2TXNhwJvQqRGEQhEkgtVGnQ9ZpQyzjrxIq9tux1gWv56@VmX5w4CaezwJmdnXl2n3lzmOd7szB8eTNlUcwZfDofDrr@@c3FwL@9vhr5f11djC7hqPUm5mFSTRn087Bg3f35SSucBwX4@fgOPBha7x8eFveH1d9PT19G83cPc/LyjZBTj5ySQ0omh5RSXP5Ezb7tksnbR0on3Uf75zfySB3cdNzJ299e6CaK5YKde37udHqNK5SiiPlM3mGlizPUsiA92bI7acVcQI6i8FlRZAUJM14KUPe3U1aWwYxR@FGK6fFxiBbQ74NRS1HpGZ8mPSiYqAoOnd7zFqZch9mUuXCfZQlkXhQkpYRVxxi4cffPd3e9FuATR0BUKP0ZMxi@sSIah@hc3J5fng2PbGo2XSjjf1gWkeXF/6g1DXuMqDpFPiSDU00izCoBx7AkSiU9S7mBusExWBvklbNloZc14RZdxiNKqnKumSyD0npuVbyMZ5xNIcn4TL8CXj6woqcClj75YZAkeA3D3az8@yQLF2CHLnzP4inY00AEGDsZJCmC5wGROzbdXWFQg@04y8wcmMykQcwJAqgL5mMshIRxktO9zp130NMUdHVAHnoWOT22eig5Xq5/LEpOz/F/h6K@QsTDri8wqegr4WcoKOgmUMzzSkh3RQxTCHbB6nUaiHDuKy72StZoBSurRLg6BT3Tgp@vvg6UJopKhpvIFynMxHzNwM6@s1Cgl8kEtmJ9fprHCSOmKD5/Gg1pHu6HPl6WUNdgfB0Mb/zRYPjx6vpsNLio1YMvo8H1hVzvqjuZX3OTA7qq4J0CC9DEvtkN6m3sGtS9rWj4uA4E86MiS/08EIIVnBRY5de3Hz4YgKYPtq5gjwKDWEvea/sGlmyhIINlCdYQbqMu3dfqbBNAH5XEadwE2evQXsNoynLxv0YFC6uijDP@quGqxHBGJDieiW7dmLu62qguoBSDEIgsJkpZJ9n46zFXoglnD3o1Tp2Og/9mFEVZAWp@ca/TA973Unw7Tt0@da75SYcC4ksI0p7wtjlgDWIhIRZ9j@N7HaKGWazBQBNFVQtLMTCklLIL7ce2Cxxpbj3lmAPIT0/bbb@O4HCnYxAWJlDYQTIOyH6BQ2CMS4lwsO6vh4rSm9ZcrzFVns2@Kl0JjI2h/la1jbJJ5wZHGQaN3D@A3V1zyo5num84vBn61zcfz0bnl7S1SbzZZvXkEEXFNs5g@PXZiP7SOyLW74dT/LZqqhicSM1zWV6req@f59a69PxfTYlNzBhZcd5udm2wXNPmtNSbOE@Ww1yzw8/KS7fzK4ySYFa@7CXKY@/oXw "C++ (gcc) – Try It Online") - PCRE2 v10.33 / [Attempt This Online!](https://ato.pxeger.com/run?1=hVZfb9s2EH8d_AX2yqhbTEpyFjtdEcRWjNQxkABtUqgO1tVOBUWmbMESJUhU7WzNJ9nLMGCP_UDdp9nxj2zZzjDBko7Hux_5O96d_MfXIIvLQtzeLAi-jo1WnAU57bROjftv7ospDSNG0buBO-x4g9vLoXd3cz3yfrm-HF2h08aLiAVxOaWoJ52O5ueNYO7nyMvG98hBrvF6uVw8nJS_Pj5-GM1fLef475KHrdNvnU8Y9x3cxycET04IITD8Apoj08aTlytCJp2V-eUTXhELJi178vIH5fnPd9-TXVDDRmbmeJnV7tZ2VPA8YjOxpY0uSkFL_eR8z-68ETGOMhC5R_M8zXGQsoIjScdMaFH4M0rQ7wWfnp0FYIF6PaTVQpR6yqZxF-WUlzlD7e7THqYYB-mU2ughTWOUOqEfFwJWLqPhxp2fX913GwiuKERYRtabUY3haSuscLA6mrvB1YV7ahI9aaMi-o2mIV5v_KdKU7OHyMpVxIVT1FckgrTk6AytiRJBz5BuSO7gDBk75KWzYYCXMWEGWccjhLSaKybroDSeGiUrohmjUxSnbKYePiuWNO_KgCWPXuDHMWxDc9cj7yFOgwUyAxt9TqMpMqc-9yF2IkhCRI6DsJgxyeEGg2hsy1qfzLE-mcSPGAYAucFsDIkQU4Yz0mrfO8ddRUFlB8oCx8D9M6MLkuVk6mUQ3B_AfUBAXwLiScfjcKjgK-BnIEjoOlDEspILd0kMjhCZOa3Gic-DuSe5mBtZoeW0KGNuqyPo6op8f_1xKDVhWFCYBL5AYcbnWwZm-pkGHLz0SUBlVusnWRRTrJPi_buRS7LgKPBgs5jYGuPj0L31RkP37fXNxWh4WamHH0bDm0sxPpR70m-9k2OyyeCDHBJQx75eDfKp7WrUnb1oeDD2OfXCPE28zOec5gznkOU3d2_eaIC6D5QupysOQawk57l5DYv3UIDBOgUrCLuWl_ZzebYLoJaKoySqg7TapFszmtKM_69RToMyL6KUPWu4STHoETF0a6xKN2K2yjaiEiiBIPg8jbBUVoes_VWbK8CE0aUajROrbcGtW1GY5kj2L-a0u4j1nASellWVT3XW7LxNEOALCNycsKZeYAtiISAWPYfBcxuigllswaA6iswWmkBgcCFkGzVXTRsxoLl3FWOGkPgSNe3m8wgWs9oaYaEDBRUk4gDsF9AExjAUCMfb_qqpSL0uze0ck-lZr6vCFsBQGPK3yW2Q9XHucBRhUMi9Y3R4qFc5cHT1ue6t693cvr0YDa7IlqNMw1qZVZ2D5yXdWYPC12cn-mvvEBs_nkzh26qoQnBC2c9Fem3yvbqeGtvS038VJRQxpXjDeb_YlcF6TOrdUk1CP1k3c8UOPivq_8Gff3XaSvoX "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+
[Attempt This Online!](https://ato.pxeger.com/run?1=hVbLbttGFF1XXzFmCmuGolxJdg1DNC04tgAbSORAkdE0kkPQ1EgiTA4Jchg_Gm_7Ad12002X2fVn0mW_pHcepEhLRQVTmrlz77nPOfTvX_0kzDPxuEvf_zo12mHip7TXPjJuvo1fzekiYBS9OxsPe-7Z1fnQvR5dTtyfLs8nF-io8SpgfpjPKTqWRnurk4a_8lLkJtMb5KCx8fr-_u52P__58fHDZHV4v8J_5nzRPvrW-4TxwMEDvE_wbJ8QAtsvINkzLTw7eCBk1nswv3zCD6QFhy1rdvC9svz7u13yEtSwkJk4btLq2pWIMp4GbClCWsuCGKTUi0429E4aAeMogSV3aZrGKfZjlnEk0zEjmmXekhL0S8bn_b4PGuj4GGmxWEo5ZfPQRinlecpQ137ewBR7P55TC93GcYhiZ-GFmYCVbjTctPfj4Y3dQPAJFgjLyrpLqjFcrYUVDlatuT67OB0fmUQfWigLnmi8wGXgPxSSij5UVnoRHxyjgUrCj3OO-qhMlIj0DGmGZAR9ZLxIXhobBlgZM2aQsh4LGKuVyqQsSuO5kbMsWDI6R2HMlurLY9k9TW1ZsOjR9b0whDB07nrn3oaxf4dM30Kf42COzLnHPaidKJJYIsdBWJyYZHeNQTR2q1V2pqM7E3kBwwAgA0ymMAghZTgh7e6N07FVCmo6UOI7Bh70DRtWLSdRPwbBgzN4dgjIc0Dc77kcmgq2An4JCwldBQpYknNhLhODFiIzpcU-8ri_cmUu5nqt0FKa5SG3VAtsfSPfX34cSslikVE4hHwhhSVf1RTM-DP1OVjpTsDNLPxHSRBSrIfi_bvJmCT-nu9CsJhYGuPjcHzlTobjt5ej08nwvBAPP0yGo3Ox35Ux6V8dSYesJ3gnhQHUta_eBvmt9SqpOxvVcGHvceou0jhyE49zmjKcwpSPrt-80QBVG7i6nD5wKGKxcrada1i8gQIZlCNYQFiVubS2zdlLAOUqDKKgCtLuEruiNKcJ_1-llPp5mgUx26oo3S7iFEl2eSonFxgjBO7G6iIHzFKzR-xi4ov2PBEEcsFAuDljTXD95HRteSQt9gRzYOI4HYKE54Dl1F4jgFOYOeFWcWW2PiujSuIMFGqeC1tG712wtxCDJnk8DrRTPYSoJYyJXbcTtAjSF3DlXZMUJljLMuxNDfCDRagmgfZD73ycQUN1HHAovluoCw8T7rtkC8YUlFot8Y5rWs36-TOiwOnbQls7jpTfitOtrp5ru4hGMA04A0VZsOZDE6oG7ZLRCAyFJqIqhqCoBKsDQ_FASRUaXvBzDFlYUiqDKAosGLVCXv0-k1W_hbrd2UrdEZS-GW-9DeifX39DwJGKiWV4pabitfoFlXe7SkrQIJlyR_6tiQHW-i5UKieCV6jHHbS7qz3sOJq2xuOrsTu6ens6Obsg9apUuKmgW57mtIItWluzqSWq89vy-nv-L44CTqMUr7PY5D6lUO5J9eWhDoFey3ebihvesurfpT_-6lrdRs_qNQ7gOYSn27H21dm_ "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+ - test cases only
PCRE1, and PCRE2 up to v10.34, automatically makes any capture group atomic if it contains a nested backreference. To work around this, the capture is copied back and forth between `\2` and `\3` using only forward-declared backreferences.
This would also make the regex compatible with Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) and Ruby, but they have no way of doing `üêá` output without source code modifications.
It still doesn't work under PCRE1, probably due to its bug where in certain conditions, captures are not reverted to their earlier values when backtracking: [Try it online!](https://tio.run/##bZRhb5swEIa/51dc2drYgVahqaYphEZd12kfsnaKUmlT0iLqGIICBhlYUrX968vOGNqkGQqOffieu3t9wLLsOGRs8yESLC7nHAYZk/xkcd5iC1@Cl03vwIWx8WW1Wj70yt@Pj78mi0@rBdncEzJ0yZD0KJn1KKW4fEbLSccis7M1pbPTdef5nqypiQ9Na3b2cUPfUwwLOpnrZabttN4yyIt5lKoUtk0yEuGuLUrRyv1kf995KxIFZDgtPC5lKglLRV5AVVIn4Xnuh5w@YZx@n@EGGAygtqppZediHjsgeVFKAbbz0ipFHoWCzyFORagHX@QrLp0qWvLoMT@O07IgSsFm4T3EKVtCh1F40ttN8xXbRWzl60eC4IYW4JVNsYiYC5LRY/vO7TqgE9KlQcZcgwz7hoMz0830n0HJ8BLvA4r2EpG9U6@AVDkrfoiTir0NikRWFspdcuhI7sC2RihKVkjtLXlexoWeKzWDIOeFBVgcZhkWC/0k/cNZkcpp706HQqoLWok0yaKYoywnzMPghFrw83J85X29mVyMRvCsV7eTb58tONKR9aQJ1aWaGQVADiSnjX5BdcQBwbJwtwWGAlU5SvAxpcodDud9OMxnAptti6nj1ODtE8O0385yS7aQF3EkONFdEwlLK0h1@Qm6@UUakcrYFFrjtaY5bhF8pVfTxLRNvGu1AsyYKI5wbQfEwE1wNM2mJ5rixblNAfkKQdoz0a4D7CCWCrEcuALHXUSDWe5gYJuiroQnKBHJ1dyC9rptgcAy9658KgDU56Fttf9PMIVp14RlLRT2jNIBq186SMClInR3/fWbUtnr9muaia85I5JbcH07GlmQWwqIHVL96h60oPeuIlW05gy6cHTUMA9c3XpX4/HN2Lu@@XExufxOW3t1VieuWgM/DsaVai9jl8/jnO@51c1pHPbm2Hq6JBQhCOIyX6g2SlX3vLq9tN7GQHKOCdPXL0X9DrZeNqf2XxbEfphvjmOlyD8 "C++ (gcc) – Try It Online")
```
^ # tail = N
( # \1 = the following, looping:
(?=
(?(3)(\3)) # If \3 is set, \2 = \3, else leave \2 unset
)
( # \3 = the following, to avoid a nested backreference
(?| # Branch Reset Group
# This alternative can only match on iterations after the first,
# because it unconditionally matches \1 and \2.
(?=
.*, # tail = K
(\4x) # \4 += 1
)
\2x* # \3 = \2 + {any nonnegative integer}; tail -= \3
|
^ # Anchor to start, to only match on the first iteration.
(x)+ # \4 = 1; \3 = {any nonnegative integer}; tail -= \3
)
)
)+ # Iterate the above as many times as possible, min 1
, # Assert tail == 0; tail = K
\4$ # Assert tail == \4
```
] |
[Question]
[
Write a square block of code that is N characters wide and N characters tall, for some positive integer N.
For instance, your N may be 5 and the block look like this:
```
ThisI
sMy5B
y5Cod
eBloc
kOkay
```
This block needs to behave as follows:
1. When the top row is extracted and run as a program, the exact text `row` needs to be printed to stdout.
For example, `ThisI` would print `row`.
2. When the left column is extracted and run as a program, the exact text `col` needs to be printed to stdout.
For example, `Tsyek` would print `col`.
3. When the main diagonal from the top left to the bottom right corners is extracted and run as a program, the exact text `dia` needs to be printed to stdout.
For example, `TMCoy` would print `dia`.
4. When the entire block is run as a program, **including the newlines** (with an optional trailing newline), the exact text `blk` needs to be printed to stdout.
For example,
```
ThisI
sMy5B
y5Cod
eBloc
kOkay
```
would print `blk`.
**Details**
* All four programs are run in the same programming language.
* The N2 characters in the original block may be anything but [line terminators](http://en.wikipedia.org/wiki/Newline#Unicode).
* If your language does not have an stdout, you may use another common output method. It must be the same method across all four programs.
**The submission whose original block contains the fewest distinct characters (not counting newlines) wins.** Tiebreaker goes to the submission with the smaller N.
[Answer]
# CJam, ~~13~~ 12 unique characters, N = 5
```
"row"
cd;"a
oaiaa
l"aa;
"blk"
```
As straight forward as it gets
*UPDATE* : Converted space to `a` (no-op in this case) as pointed out by Runner112
[Try it online here](http://cjam.aditsu.net/#code=%22row%22%0Acd%3B%22%0Ao%20i%0Al%22%20a%3B%0A%22blk%22)
[Answer]
# Bash, 19 unique characters, N = 19
```
trap echo\ row exit
t=t trap exit
t=t echo blk
exit
=
t e
c
e h
c o
h
o d
i
c a
o
l
```
* The first row is `trap echo\ row exit`. This causes `echo row` to be executed when the script exits (just the first line)
* The first column is `ttt=t echo col`
* The diagonal is `t=tt echo dia`
* The full block works by canceling the EXIT handler set up in the first line, then `echo blk` then exits.
[Answer]
# [><> (Fish)](http://esolangs.org/wiki/Fish), 3 unique characters (N = 2000)
The code uses `1` and `-` to put arbitrary numbers on the stack and `p` to (self-)modify the code based on the top 3 numbers on the stack.
E.g Putting a `!` at position `0 0` would look like `003b*p` in normal ><> and with `p1-` it becomes `111-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--11-11-p`.
After the modification the instruction pointer (IP) wraps around the code and runs the modified part. In the "block" case the IP is redirected for further modification (then reredirected back) to differ from the "row" case. In the "row" case the same two redirection happens but there is no code in between them so they have no effect.
The final generated codes for the 4 cases (omitting the unchanged `p1-` parts):
```
row: "wor"\ooo;
column: "loc"ooo;
diagonal: "dia"ooo;
block: "wor"\"klb"ooo;
```
The code size is 4 MB and the code is accessible [here](http://pastee.co/0IwyR0/raw). (There is no difficulty running it.)
The generator python3 program is accessible [here](http://ideone.com/AFVTDz).
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 14 unique characters, N = 10
```
"wor"\ooo;
"
l a k
o i l
c db
" "
o oo
o o o
o o o
; ; ;
```
Pretty straightforward in a 2D language. The only tricky part is that we need the `\` to distinguish between `row` and `blk`.
[Answer]
# Brainfuck, 2 unique characters, N = 378
*With possible slight bending of rules.*
The program is a tad large, so here's a [link to it on Pastebin](https://pastebin.com/RvidCEV8).
The `row`, `col` and `dia` programs are straightforward. They simply increment the byte cell until the right ASCII code is reached and then outputs. If the letter has already passed, it increments until the cell overflows so it can start again at 0.
The `blk` program is where the slight rule bending occurs. In order to print the "exact text `blk`" as asked in the challenge, backspaces are used (ASCII code 8), which requires the displaying console/terminal to support it. Whenever errant values from the `row`/`col`/`dia` programs are printed, I ensure they are removed by outputting a few backspace control codes. To simplify things, I've ensured that all errant values outputted at one point are part of the printable ASCII range.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 26 unique chars, N = 29
```
*w;main(){printf(w?w:"row");}
ww;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;/*;;;;;;;;;;;;;;;;;;;;;;;;
m;;m;;;;;;;;;;;;;;;;;;;;;;;;;
a;;;a;;;;;;;;;;;;;;;;;;;;;;;;
i;;;;i;;;;;;;;;;;;;;;;;;;;;;;
n;;;;;n;;;;;;;;;;;;;;;;;;;;;;
(;;;;;;(;;;;;;;;;;;;;;;;;;;;;
);;;;;;;);;;;;;;;;;;;;;;;;;;;
{;;;;;;;;{;;;;;;;;;;;;;;;;;;;
p;;;;;;;;;p;;;;;;;;;;;;;;;;;;
r;;;;;;;;;;r;;;;;;;;;;;;;;;;;
i;;;;;;;;;;;i;;;;;;;;;;;;;;;;
n;;;;;;;;;;;;n;;;;;;;;;;;;;;;
t;;;;;;;;;;;;;t;;;;;;;;;;;;;;
f;;;;;;;;;;;;;;f;;;;;;;;;;;;;
(;;;;;;;;;;;;;;;(;;;;;;;;;;;;
";;;;;;;;;;;;;;;;";;;;;;;;;;;
c;;;;;;;;;;;;;;;;;d;;;;;;;;;;
o;;;;;;;;;;;;;;;;;;i;;;;;;;;;
l;;;;;;;;;;;;;;;;;;;a;;;;;;;;
";;;;;;;;;;;;;;;;;;;;";;;;;;;
);;;;;;;;;;;;;;;;;;;;;);;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
};;;;;;;;;;;;;;;;;;;;;;;};;*/
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;*w="blk";
```
[Try it online!](https://tio.run/##rZHPCsMgDMbveQxPKozeF8aexTk6ZK0tUsih9Nldu/V/zXbZB2riD4lfYk8Pa2PUhKVxXqq2Ds43uaQrnUWoSCjsgAh5Qb8yzdISseTfmn4zLHXD7jjq34dnqPycMk3VGKgkbaeoTdF6DusEDUscGEejHONo1N4YNJu02dF8m@fJbsza5CD2P1lfgD3YuK9odezBYgyKRAMNX3ddG5KzmSYG@E3QMaC/19mPt/@mmi7iVjwFxvgC "C (gcc) – Try It Online")
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 11 unique characters, N=6
```
irow␛␛
cdddd␛
o␛i␛␛␛
l␛␛a␛␛
␛kdd␛␛
␛iblk␛
```
[Try it online!](https://tio.run/##K/v/P7Mov9wmtTjZDkxwJacAAYSZD6YyEZIQ4RwEOxFJGExmQ/UiCWUm5WSDGf///9ctAwA "V (vim) – Try It Online")
lot of escapes here. N=5 might be achievable, but I can't see a way to do it without increasing the unique characters.
[Answer]
# Ruby, 24 unique chars, N=17
```
trap(0){$><<:row}
rr=a=:blk;%;00000
a0a00000000000000
p00p0000000000000
(000(000000000000
00000000000000000
)00000)0000000000
{000000{000000000
$0000000$00000000
>00000000>0000000
<000000000<000000
<0000000000<00000
:00000000000:0000
c000000000000d000
o0000000000000i00
l;;trap(0){$><<a;
};000000000000;{}
```
[Try it online!](https://tio.run/##ZZBBC4MwDIXv@R0dtLecm@p/idtlTLAERaT0t3fq1KXbOySPjwd5RKZuKWUUjhZdMm0IXoY5g0jDje/6F90INwEjYyWIiLEmdh22IvgrcPtyiqTPTl9iDmMu0p7uNBCuePgjBwKvDu8e7rrLYyNDVe@5kp5IP4QJMukMpVzKGw "Ruby – Try It Online")
] |
[Question]
[
The goal is to write a program that encodes an other program (input) with the fewest character possible.
### Scoring
* The score is equal to the different number of characters needed for the output.
* Lower score is better.
### Rules
* No target languages with a limited set of commands. (No Brainf\*\*k, Whitespace etc)
**Edit**: I mean at least 26 significant characters, `A` doesn't change the way a brainf\*\*k program operates, so you can't count this character. Same applies to whitespace.
* The target language must exist at the time where this question is written.
* You have to include a small explanation how you achieve your score.
* The input program is valid.
* The encoded program must be a valid program in the same language as the input.
* The encoded program must do the same job as the original program.
* Your encoder must work for every valid program in that language.
* Include some sample input and output.
### Notes
* The encoder might be written in any language, not only in the language it targets.
* This is not [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), readable programs are encouraged.
* The great goal is to see how many different characters are needed to write anything in that language. I disallowed BF etc because there would be no challenge.
* This was inspired by [Print a string in as few distinct characters as possible](https://codegolf.stackexchange.com/q/11336/34718), you could take it as [metagolf](/questions/tagged/metagolf "show questions tagged 'metagolf'") for that question.
### Example
In Java, you can use `\uXXXX` instead other characters. A valid entry encodes every character from the input this way. This would have a score of 18. (`\ 0-9a-f`)
Code in Tcl, encodes a Java program:
```
set res {}
foreach char [split [read stdin] {}] {
append res [format \\u%04x [scan $char %c]]
}
puts $res
```
[Answer]
# Python -> Python, 8 distinct characters
```
def minimal_python(input_code):
"""Convert Python code to minimal Python code."""
# Create a list of the ordinal numbers of <input_code>'s characters.
# '%' signs have to be treated specially and are represented with -1.
ords = []
num_escaped_chars = 0
for char in input_code:
if char == '%':
ords.append(-1)
else:
ords.append(ord(char))
num_escaped_chars += 1
modulo_sign_escape = '%' * 2**num_escaped_chars
def formatters():
num_escaped_chars_so_far = 0
for o in ords:
if o == -1:
yield modulo_sign_escape
else:
yield '%' * 2**num_escaped_chars_so_far + 'c'
num_escaped_chars_so_far += 1
format_str = "'" + ''.join(formatters()) + "'"
values_str = ''.join('%' + '-~'*o + '0' for o in ords if o != -1)
return 'exec' + format_str + values_str
```
This uses modulo formatting to rebuild the input string. For example, `print 1` results in this program:
```
exec'%c%%c%%%%c%%%%%%%%c%%%%%%%%%%%%%%%%c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%c%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%c'%-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0
```
In theory you can encode any program like this, but the resulting program will always have more than 2n characters, where n is the number of characters in the input, not including `%` symbols.
[Answer]
### GolfScript / GolfScript, score 4
```
"'',,"\{"'"\","*"',+"}%"''+~"
```
The encoder itself is a GolfScript program which takes the original code on STDIN and transforms it into a sequence of characters `',+~`. This output itself is valid GolfScript code which performs the same operations as the original version.
The basic method consists of an encoding of the code as a string (using chars `',+`, see below) and then evaluate this string using the eval command `~`.
If one concatenates any string together with an array of numbers in GolfScript the numbers are converted to code points and the result is a string itself. Thus the string encoding simply builds a list of numbers (from the code points of the input code) and then concatenates all those with an empty string.
*Example:*
The input code
```
"hi"
p
```
is translated into (note: line breaks and comments added for readability)
```
# initialize an empty array []
'',,
# append number 34 (length of string ',,, ... ,,,')
',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,',+
# ... other numbers
',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,',+
',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,',+
',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,',+
',,,,,,,,,,',+
',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,',+
# result is array [34 104 105 34 10 112]
# append empt string, i.e. convert array to string (results in "\"hi\"\np")
''+
# evaluate
~
```
[Answer]
# CJam -> CJam, score: 3
CJam is newer than the question so it's not eligible to win.
```
q{[{_'(>{'(-')*''\+}{is'c+T}?}%{"+"T}*'~]}:T~
```
It uses `')~`. `')` is the character `)`, and each extra `)` increments it by one. `~` can evaluate a character or a string. The complete program is evaluated after concatenating all the characters by evaluating `+`. And an integer of the character value and a number-to-character operation is evaluated for each character less than `)`.
### Examples
```
XX{_2$+}I*]N*
```
is translated into:
```
'))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~'))))))))))')))~')))))))))))'))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))')))~'))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))')))~'))))))))))))))))))))))))))))))))))))))')))~'))')))~~
```
and
```
q{[{_'(>{'(-')*''\+}{is'c+T}?}%{"+"T}*'~]}:T~
```
is translated into:
```
')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~'))))))))))))'))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~'))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~'))))))))))))'))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')))))')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')')))~'))')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~'))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))')))~'))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))')))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))'))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')))')))~')))))))))))'))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~'))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~'))')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~'))))))))))))))))))')))~'))))))))))))))))))))))))))))))))))))))))))))')))~'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~
```
[Answer]
## APL (score: 10)
```
'⍎⎕AV[',(⊃,/{'(⍴',(⍵/'⍬'),')'}¨⎕AV⍳⍞),']'
```
Characters used in encoding: `⍎⎕AV[(⍴⍬)]`
The APL program to encode must restrict itself to the APL charset and not use any extra Unicode.
Encoding for the program `42` (which outputs the answer to Life, the Universe, and Everything):
```
⍎⎕AV[(⍴⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬)(⍴⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬)]
```
How it works: `⍬` is the empty list, `⍬⍬⍬⍬` is therefore a list of four empty lists, `⍴⍬⍬⍬⍬` is the length of the list of four empty lists, which is four. Dyadic `⍴` is reshape, so the length-of-list-of-lists instructions must be wrapped in parenthesis, giving the final encoding of character number four as `(⍴⍬⍬⍬⍬)`.
These numbers are then looked up in `⎕AV` which is the character set, and `⍎` executes the resulting string.
(At first sight it looks like the score could be brought to 9 by using `⎕UCS` instead of `⎕AV` and saving `[]`, but that doesn't work, because `(⍴⍬)(⍴⍬)` is a list of lists of scalars, i.e `[[1], [1]]` instead of the `[1, 1]` that would be required, and working around that would require interspersing the encoded values with commas, bringing the score back up to 10.)
[Answer]
# [Lenguage](https://esolangs.org/wiki/Lenguage), score 1
The program consists of \$1{,}517{,}807\$ of any characters. These can be any characters you want, as Lenguage only depends on the length of a program. This does not break rule 1 as all characters are significant in Lenguage because of this fact.
This is one of the extremely few useful Lenguage programs that fits into the observable universe. [Here](https://gofile.io/d/t863mw) is one of the \$1{,}114{,}112^{1{,}517{,}807}\$ possible Lenguage self-encoders.
# Explanation
Lenguage starts by calculating the program's length and converting it to binary. `1517807` in binary is `101110010100011101111`. Next, it left-pads that number with zeros until the length of that number is a multiple of three. The length of `101110010100011101111` is 21, which is already a multiple of three, so we don't need to worry about this. After that, it splits it into chunks of three. This becomes `101 110 010 100 011 101 111`. Finally, it is translated to BF using this simple table:
| BF | Translated Lenguage |
| --- | --- |
| `+` | `000` |
| `-` | `001` |
| `>` | `010` |
| `<` | `011` |
| `.` | `100` |
| `,` | `101` |
| `[` | `110` |
| `]` | `111` |
And then evaluated as BF code. Here, `101 110 010 100 011 101 111` becomes `,[>.<,]`. Here's what it does:
```
,[>.<,] # full program
, # input* to current cell
[ ] # while current cell is nonzero...
> # move pointer right
. # output current cell as a char
< # move pointer left
, # input to current cell
```
This outputs a null byte for every character inputted. This doesn't change the execution of the inputted program since, as I said, the program is only dependant on the length of the program. Why a null byte, you ask? Because the tape initially starts out filled with zeros, and it's easier to just output the null byte that can already be output from the second cell than to set the second cell to some other value and output that every time. If you don't understand, here's an example:
Say the input is \$23{,}855\$ `$`s. This is one of the many variations of a [cat program](https://esolangs.org/wiki/Cat_program) in Lenguage. It decodes to `,[.,]`, which is the standard BF cat. Here's the tape through each command:
| `36` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | … |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `^` | | | | | | | | | | | | | | | | | | | | | | | |
| `,` | | | | | | | | | | | | | | | | | | | | | | | |
| `36` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | … |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| | `^` | | | | | | | | | | | | | | | | | | | | | | |
| `[>` | `.` | | | | | | | | | | | | | | | | | | | | | | |
| `36` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | … |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `^` | | | | | | | | | | | | | | | | | | | | | | | |
| `<,]` | | | | | | | | | | | | | | | | | | | | | | | |
etc.
As you can see, each `.` command ends up on a `0`, outputting a null byte for each character inputted.
\*This program assumes that EOF is a null byte.
[Answer]
# [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 7 Distinct Characters, Noncompeting
RProgN is newer than this question.
`' do.Lc`
Convert the program to `'oooo...' L c 'ooooo...' L c 'oo...' L c . . . do`, where each 'oo...' represents the character code in o's, surrounded by apostrifies to make a string out of them. L c then turns them into a number constant. After all the strings are placed on the stack, a chain of .'s equal to the amount of characters in the encoded string minus one rebuild the encoded string, and do executes it.
## Encoder, also written in RProgN.
```
'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooo' L c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . do
```
[Try it online!](https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27ooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooo%27%20L%20c%20%27oooooooooooooooooooooooooooooooooooooooooooooo%27%20L%20c%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20.%20do&input=%22ENCODE%20THIS%22)
[Answer]
# Ruby -> Ruby, 8
```
#Convert a number from 0 to 255 to the form "111+11+11+1+1+1"
def byte_to_ones(byte)
output = []
ones = [111,11,1]
ones.each do |one|
while byte>=one
byte-=one
output<<one
end
end
output.join('+')
end
bytes = $<.each_byte.map { |byte| byte_to_ones(byte) }
puts "eval''<<#{bytes.join('<<')}"
```
Sample:
```
puts "Hello, world!" => eval''<<111+1<<111+1+1+1+1+1+1<<111+1+1+1+1+1<<111+1+1+1+1<<11+11+1+1+1+1+1+1+1+1+1+1<<11+11+11+1<<11+11+11+11+11+11+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1<<111<<11+11+11+11<<11+11+1+1+1+1+1+1+1+1+1+1<<111+1+1+1+1+1+1+1+1<<111<<111+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1<<11+11+11<<11+11+11+1<<1+1+1+1+1+1+1+1+1+1
```
Implements the Ruby solution given in [the linked problem](https://codegolf.stackexchange.com/questions/11336/print-a-string-in-as-few-distinct-characters-as-possible/11355#11355) and replaces I/O with eval.
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), score ~~5~~ 4
```
AE+1
```
Using the `ASCII` function, we can assemble arbitrary strings using `+A(whitespace)1`. However, since we know that all Knight programs will always be printable ASCII, tab, CR, or LF, we can always assume codepoints will be >= 9.
Therefore, to avoid whitespace, we can use EVAL.
`+` can be used to both concatenate strings and do addition, `A` converts an integer to a string with its ASCII value, and `1` is used to add a bunch of 1's together to get any non-zero integer (strings with null bytes are illegal in Knight).
For example, if we wanted a string with a tab (ASCII 9) followed by a newline (ASCII 10) we would do this:
```
+A++++++++E1E1E1E1E1E1E1E1E1A+++++++++E1E1E1E1E1E1E1E1E1E1
```
Now, we can simply encode a Knight program using this method and evaluate it with `E`.
Here is the conversion program in Knight. It adds a leading newline and leaves out the trailing newline, but otherwise encodes a functionally equivalent program.
This could be further optimized if we used `111` and `11`, but this isn't [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") despite the question being tagged it...
```
# start with empty string
; = acc ""
# slurp the entirety of stdin and concatenate with newlines
; WHILE(= tmp PROMPT)
: = acc + + acc ASCII(10) tmp
# First output the E to evaluate the next expression
# note: #"# is just to fix syntax highlighting
; OUTPUT("E\") #"#
# Now output length - 1 `+`'s to build the string one ASCII at a time
; OUTPUT(+ * "+" (- LENGTH(acc) 1) "\") #"#
# Now loop through the string
: WHILE(acc)
# Grab the ASCII value of the first character in acc
; = char ASCII(acc)
# snip off the first character of acc
; = acc SUBSTITUTE(acc 0 1 "")
# output the ASCII keyword
; OUTPUT("A\") #"#
# output n - 1 pluses
; OUTPUT(+* "+" (- char 1) "\") #"#
# output n ones
: OUTPUT(+*"E1" char "\") #"#
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 4 distinct [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[„)\ìNú₅ö©g₅Qi®ƒ„.g}¤…B.VJ?q
```
No TIO of the actual program, since the output would be way too big. It basically encodes the input-program into a program using the approach I've also used in the [*Fewest (distinct) characters for Turing Completeness*](https://codegolf.stackexchange.com/a/210771/52210) challenge.
[Try it online](https://tio.run/##yy9OTMpM/f8/@lHDPM2Yw2v8Du961NR6eNuhlelAOjDz0DolF7t0J70wJS/7wv//HQ/vBgA) (with `ƒ„.g}¤…B.V` replaced with `"D>gB.V"` so we push the number instead of that many `.g` or [try it online](https://tio.run/##yy9OTMpM/f8/@lHDPM2Yw2v8Du961NR6eNuhlelAOjDT8tgkoIxeeu2hJY8aljnphXnZF/7/73h4NwA) (with `®` replaced with `9` as an example).
**Explanation:**
```
[ # Start an infinite loop:
„)\ì # Prepend ")\" in front of the (implicit) input
Nú # Pad it with the loop-index amount of leading spaces
₅ö # Convert it from a base-255 string to a number
© # Store this number in variable `®` (without popping)
g₅Qi # If the length of this number is 255:
®ƒ„.g} # Push `®` + 1 amount of ".g" to the stack
¤ # Tail (without popping): pushes "g"
…B.V # Push "B.V"
J # Join the stack together
? # Output it without trailing newline
q # And stop the program
```
This will produce a program with the 4 distinct bytes `.gBV` in the following format:
Loads and loads of `.g` to push a huge number. Then one additional `.g`+`g` to push 255, followed by `B.V`.
* Loads of `.g`: Push the amount of items on the stack, which will become one larger every time, where only the last two are relevant
* `g`: Pop the top number, and push its length (which will always be 255)
* `B`: Convert the large number to base-255, resulting in the original input-program with prepended `)\`, to clean the stack from all the numbers we've pushed with `.g` (`)` wraps the entire stack into a list and `\` discards it)
* `.V`: Execute it as 05AB1E code
[Try such a program for `Aû`](https://tio.run/##HY87akNRDER3FEbS6DONi5A1pLchBFcusn9edN1JoDNn9Pq7P54/18Wc9hSscqYUFSGOo8rJ7EjMDtOmqYQ80VUWw0mNUMp0Oo0zMgVYtgetbgjLzqR75MatZ9OHWeIuDMzwuIlUOGKnk5lL8k0Uet0xFr6FBGn72KLrjkarUJtZiIIbfcugLYwwP5Uz0MEiwqmFu3x/O1/IVtXR@XX7/fz4vq5/) (with the many `.g` replaced with a huge number plus additional `D>`). `Aû` will push the lowercase alphabet & palindromizes it.
[Answer]
# [Julia 0.7](http://julialang.org/), score 12
```
function f(a)
u = unique("eval(parse(-*))")
d = Dict{Union{Char,Int},String}(u .=> repr.(u))
while a ⊈ keys(d)
d2 = empty(d)
for (k1,v1) in d
for (k2,v2) in d
try
d2[k1-k2] = "($v1-$v2)"
catch
end
end
end
merge!((x,y)->x,d,d2)
end
if length(a) == 1
return "eval(parse(*($(d[a[1]]))))"
elseif length(a) > 1
return "eval(parse(" * join(getindex.([d],[a...]),'*') * "))"
else
return ""
end
end
print(f(read(stdin,String)))
```
[Try it online!](https://tio.run/##fVP3V5tlFD5uRY97z68R7RcM0eCoC7S2auvWWqsiaiQfkJIGGhIK1ip7hL333nvvdc6d/h3@I5iCp9KDx/vTfe/z3OeO933Ph3xe97Hd3ZSQPznozfAbKabbHmVELGTEGyG/92LIMm1WtttnZroDWZYZG2O32/YZngjjpDc5ePmsP5J5@USaO@A47Q9ecZwJBrz@1CtmyHDGJxgBKzPgNEN2e9Re1qU0r88y3MZf4TIj3crNMj37anuKcRFJ60JmMPdgNCUjYJjpLke2y254/YbnGvAvGOfIjvsP8KoFA7mHYvu1EtNdselxSZGSNjM62xUbHdGwHeImu4PJaYeilv/6SgfPB/0LViDVOmKaOY5ce2xCjsPj8MTtT3aVted4Uwyf5U8NpkU2b8THG65ryQErGAr4jYPrjzGjTU@iO9GVlGSP2H67li/Luk4l4f9FbEaMcT7D6zdTraDX77FynGaiJ8mR6HY6nUl2x9GYo/YIw3ZQ/pCc7doQe4NkRm48aKaYAcvtMbOCHq//n1cQaXJ3dx8NuC/ZbLZTls@XYZzLCPg8R6JuuPGmm2@59bbb74i6866ou@@59777H3jwoYcfefSxx5948qmnnzGO2J6Nfu75o6Y95gVHrPPFl1xxL7/y6mvHXn/jzbfejk94593j7504@f4HH546/dHHn3z62edffPnVma/PfnPu2@@@T/wh6ceffnb/kuyxUlLTvOfTfRf8GZkXA1nBUPalnNxfL/925fc/IA/yoQAKoQiKoQRKoQzKIQwVUAlVUA01UAt1UA8N0AhN0Awt0Apt0A4d0Ald0A090At90A8DMAhDMAwjMApjMA4TMAlTMA0zMAtzMA8LsAhLsAwrsAprsA4bsAlbsA07mIf5WICFWITFWIKlWIblGMYKrMQqrMYarMU6rMcGbMQmbMYWbMU2bMcO7MQu7MYe7MU@7McBHMQhHMYRHMUxHMcJnMQpnMYZnMU5nMcFXMQlXMYVXMU1XMcN3MQt3MYdyqN8KqBCKqJiKqFSKqNyClMFVVIVVVMN1VId1VMDNVITNVMLtVIbtVMHdVIXdVMP9VIf9dMADdIQDdMIjdIYjdMETdIUTdMMzdIczdMCLdISLdMKrdIardMGbdIWbdMO53E@F3AhF3Exl3Apl3E5h7mCK7mKq7mGa7mO67mBG7mJm7mFW7mN27mDO7mLu7mHe7mP@3mAB3mIh3mER3mMx3mCJ3mKp3mGZ3mO53mBF3mJl3mFV3mN13mDN3mLt3lH8iRfCqRQiqRYSqRUyqRcwlIhlVIl1VIjtVIn9dIgjdIkzdIirdIm7dIhndIl3dIjvdIn/TIggzIkwzIiozIm4zIhkzIl0zIjszIn87Igi7Iky7Iiq7Im67Ihm7Il27KjeZqvBVqoRVqsJVqqZVquYa3QSq3Saq3RWq3Tem3QRm3SZm3RVm3Tdu3QTu3Sbu3RXu3Tfh3QQR3SYR3RUR3TcZ3QSZ3SaZ3RWZ3TeV3QRV3SZV3RVV3Tdd3QTd3Sbd35My/yIe1/Aw "Julia 0.7 – Try It Online")
* the 12 used characters are `eval(prs-*')`
* `parse("string")` parses a string into an expression (AST)
* `eval` evaluates an expression
* we use character arithmetic to compute any character (`'b'-'a'==1`, `'b'-1=='a'`)
* characters are combined into a string with multiplication (`'a'*'b'=="ab"`)
* `d` stores every character and number for which we have found a representation with the allowed characters
* every combination of `d[k1]-d[k2]` is computed and added to `d` until all the characters of the input are found
* in Julia 1.x, `parse` is replaced with `Meta.parse`, which would add 3 to the score
* there is a warning in stderr due to the usage of `parse` instead of `Meta.parse`, which can be disabled with `--depwarn=no` if it is a problem for this challenge
] |
[Question]
[
Your task is to generate an emoticon of three characters, the first character being one eye, the second the mouth, and the third another eye. Each eye is a random one of these characters: `$'*+-;O^`ox~`, and the mouth is a random one of these: `,-._coux`.
Each eye and the mouth must be on the same general level. These eyes: `'*;^`` and these mouths: `-coux` are "upper-level", while these eyes: `$+-Oox~` and these mouths: `,._` are "lower-level". Any emoticon has a 50 % chance of using only upper-level eyes and mouth, and a 50 % chance of using only lower-level ones.
Additionally, the eyes should usually not be different. The chance of the eyes using the same symbol must be somewhere between 50 % and 67 %.
## Rules
* The submission must be a function or a full program.
* The submission must either print the emoticon to the screen with optional trailing and/or preceding whitespace, or returning the emoticon as a string.
* The emoticon should have a 50 % chance of being upper-level and a 50 % chance of being lower-level.
* All eyes and mouths of the same level must have the same chance of occuring.
* The eyes should be the same 50-67 % of the time.
* Standard [loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
## Examples:
```
-_- // All symbols are lower-level: valid
~o.~ // Two eyes on the left side: invalid
^^ // No mouth - invalid
^_^ // The mouth is lower-level but the eyes are not: invalid
^-* // All symbols are upper-level: valid
--- // Eyes are lower-level but mouth is upper-level: invalid
```
Enjoy!
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 43 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
"'*;^` -coux $+-Oox~ ,._"¸ò ö
mö
Vp[VU]ö Îö
```
Saved four thanks to Shaggy
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=IicqO15gIC1jb3V4ICQrLU9veH4gLC5fIrjyIPYKbfYKVnBbVlVd9iDO9g) or [generate 10 emoticons](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=IicqO15gIC1jb3V4ICQrLU9veH4gLC5fIrjyIPYKbfYKVnBbVlVd9iDO9g&footer=V3E&input=MTAgLW1S)
```
"'*;^` -coux $+-Oox~ ,._"¸ò ö : Implicit input
"'*;^` -coux $+-Oox~ ,._" : Each part, separated by spaces
¸ : Split on spaces
ò ö : Random pair; store in U
mö : Map each element of U to a random character of that string
: The result is [random eye, random mouth]; store in V
Vp[VU]ö Îö
Vp : Append to V:
[VU]ö : Random element of the tuple [V, U]
Î : First element, either first eye or all eyes
ö : Random character
: -P joins this array to a string
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 45 39 36 bytes
- 6 bytes yeah lyxal outgolfed me in about 2 5 minutes
- 3 bytes by AndrovT using an amazing approach
```
`-⇩Ḋx '*;^\`,._ $+-Oox~`½℅⌈÷2ƈṅ2ƈ$℅Y
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgLeKHqeG4inggJyo7XlxcYCwuXyAkKy1Pb3h+YMK94oSF4oyIw7cyxojhuYUyxogk4oSFWSIsIiIsIiJd)
**How it works**
```
`-⇩Ḋx '*;^\`,._ $+-Oox~`½℅⌈÷2ƈṅ2ƈ$℅Y
`-⇩Ḋx '*;^\`,._ $+-Oox~`½℅⌈ Compressing part:
`-⇩Ḋx '*;^\`,._ $+-Oox~` Slightly compressed string "-coux '*;^`,._ $+-Oox~"
½℅ Get random half of string (upper and lower level)
⌈ Split on space (eyes and mouth)
÷2ƈṅ2ƈ$℅Y Random part:
÷ Dump list on register
2ƈṅ Choose two random eyes and concatenate them
2ƈ Again, choose two random eyes from the above string (probability of having same eyes: 7/12)
$℅ Swap and choose random mouth
Y Interleave eyes with mouth
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~46~~ ~~45~~ ~~43~~ ~~39~~ 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"-coux '*;^`,._ $+-Oox~"2äΩ#`©âΩ¤®Ω‚Ωì
```
-1 byte by taking inspiration of [*@mathcat*'s Vyxal answer](https://codegolf.stackexchange.com/a/257693/52210) regarding the split on space in the string.
-4 bytes taking inspiration of [*@Jacob*'s Japt answer](https://codegolf.stackexchange.com/a/257697/52210) regarding the 'random element of the tuple [first eye, random eye]'.
[Try it online](https://tio.run/##ATwAw/9vc2FiaWX//yItY291eCAnKjteYCwuXyAkKy1Pb3h@IjLDpM6pI2DCqcOizqnCpMKuzqnigJrOqcOs//8) or [output a given input amount of random outputs](https://tio.run/##AUAAv/9vc2FiaWX/Rv8iLWNvdXggJyo7XmAsLl8gJCstT294fiIyw6TOqSNgwqnDos6pwqTCrs6p4oCazqnDrP8s/zEw).
**Explanation:**
*Code explanation:*
```
"-coux '*;^`,._ $+-Oox~" # Push this string
2ä # Split it into 2 equal-sized parts:
# ["-coux '*;^`",",._ $+-Oox~"]
Ω # Pop and push a random string of the two
# # Split it on the space
` # Pop and push the strings in the current pair separately to
# the stack
© # Store the top string (the eyes) in variable `®` (without
# popping)
â # Get all possible pairs with the cartesian product of the two
Ω # Pop and push a random partial emoticon from this list
¤ # Push the last character (the eye) (without popping)
® # Push the eyes-string of variable `®` again
Ω # Pop and push a random eye from this string
‚ # Pair the first eye and random eye together
Ω # Pop and push a random eye from this pair
ì # Prepend it to the partial emoticon to complete it
# (after which it is output implicitly as result)
```
Minor note: compressing `"-coux '*;^`,._ $+-Oox~"` as a list of codepoint integers we then convert to ASCII characters would be 3 bytes longer than the literal string with [`•1Γ∞™årÒCиÐ}‡δíl|“"5Ì•ƵQвçJ`](https://tio.run/##ATwAw/9vc2FiaWX//@KAojHOk@KInuKEosOlcsOSQ9C4w5B94oChzrTDrWx84oCcIjXDjOKAosa1UdCyw6dK//8).
*Percentages explanation:*
* The 50%/50% for either upper-/lower-level emoticons is done by the first `Ω` after we've split the string into two parts with `2ä`.
* The 50-67% of the same eyes in comparison to different eyes is 50%/50% as well, with the last `Ω` just before the `¬®нΩ‚`, which pairs the first eye with a random eye together.
[Answer]
# [Thunno](https://github.com/Thunno/Thunno) `K`, \$ 58 \log\_{256}(96) \approx \$ 47.74 bytes
```
"'*;^` -coux$+-Oox~ ,._"2APZwA_ZiAusDZwsZw+DZwsZw+sZwsAuZs
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSt1LsgqWlJWm6FjetlNS1rOMSFHST80srVLR1_fMr6hR09OKVjBwDosod46MyHUuLXaLKi6PKtaEUEBc7lkYVQ0yAGrQASgMA) or [generate 10 emoticons](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abRSilLswuqlpSVpuhY3rZTUtazjEhR0k_NLK1S0df3zK-oUdPTilYwcA6LKHeOjMh1Li12iyoujyrWhFBAXO5ZGFUNMWBnlaxzk6OkV5Q3hL1hkaABhAQA).
Port of mathcat's Vyxal answer.
Outputs a list of characters. Add the `J` flag if you want a single string.
#### Explanation
```
"..."2APZwA_Zi
"..." # Push the string
2AP # Split it in half
Zw # Get a random half
A_Zi # Split on the space
AusDZwsZw+DZwsZw+sZwsAuZs
Aus # Dump onto the stack and swap
DZwsZw+ # Get two random items from the eyes:
D # Duplicate
Zw # Get a random item
s # Swap
Zw # Get another random item
+ # Concatenate
DZwsZw+ # Get two random items from this string:
Zw # Get a random item
s # Swap
Zw # Get another random item
+ # Concatenate
sZw # Swap and get a random item from the mouths
sAu # Swap and dump onto the stack
Zs # Swap the second and third items on the stack
# The K flag pushes the stack, which is output implicitly
```
[Answer]
# [Factor](https://factorcode.org/) + `pair-rocket`, 102 bytes
```
[ { "'*;^`"=> "-coux""$+-Oox~"=> ",._"} random
last2 over [ random ] tri@ .5 [ . over ] whenp 3array ]
```
[Try it online!](https://tio.run/##NZDdT8IwFMXf91dcGxMTdR1gRD4yI0ZCfMFE4hOZWssdayhtvS0CIexfnxPw9fzuxzknFzJYqt4mz@NRDzx@r9BI9KAsOKEoJisXGICEmdklLJAMapB2@aWMqBc9PxFBJLYeHGEIW0fKhL8ppzQSD4TIHVkn5iIoa7gUWseY5ygD9KOo2aimsAN2cdl//2TpPbBY2tWGsfOr@MVuyoN0zT/Y/uQj0sKHFtgfJJj@e8sgkHoAfltL/MgyWBdoHNwc3EFWETqtpAgYsTiOyzJNdzAcP8Fo8Po4GA1hn6ZlWRMGxwgAZzBBhCIE53tJIu0M51bn3AdR97KRhTBz5HXSRCStVqPTaSfdu26zDbml@vkWQqHqMj0USBhNgTGtFni6ngEKWVS/ "Factor – Try It Online")
An anonymous function that returns an emoticon when called.
* `{ "'*;^`"=> "-coux""$+-Oox~"=> ",._"}` A shorter way to write
```
{ { "'*;^`" "-coux" } { "$+-Oox~" ",._" } }
```
* `random` Pick the high set or the low set at random
* `last2 over` Place two copies of the eyes on the stack and one copy of the mouths
* `[ random ] tri@` Get a random character from each
* `.5 [ . over ] whenp` 50 + ~8% chance of ditching the random right eye and replacing it with a copy of the left
* `3array` Combine the three characters into a string
[Answer]
# [Python](https://www.python.org), 125 bytes
```
from random import*
a,b,c=map(choice,([(x:="'*;^`"),"-coux",x],[(y:="$+-Oox~"),",._",y])[r:=random()>.5])
print(a+b+(a,c)[r])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3a9OK8nMVihLzUoBUZm5BflGJFleiTpJOsm1uYoFGckZ-ZnKqjka0RoWVrZK6lnVcgpKmjpJucn5phZJORaxOtEYlUEJFW9c_v6IOJKWjF6-kUxmrGV1kZQsxVkPTTs80VpOroCgzr0QjUTtJWyNRJxmoIFYT4gioW2BuAgA)
or [generate 10 emoticons](https://ato.pxeger.com/run?1=LY5NCsIwFIT3PUUIgi_2tehCkEq9ggcoVdOYahZNQkghXehF3BRBF97I29hiVzMwP3yPt-381ej-I8xZkpxQSl-tr5PN91Y70xDH9XkQ1Vjj_CLiWKHIG25BXI0SEqGAkOV0vtgeTpQhTYRpA8VQYgHdEMziZG_CfYwwPVLsSla4LP_fAtul65JF1intgcdVDBzFUCjZBJEMPFFUG0eOROmR5iJhLCttWw-MsYzIIAWM-NOof66Wf_cD)
The eyes are the same if they are upper level (50% of the time) or if the `choice` function selects the same eye again (less than 17% so we don't have to worry about that).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~108~~ ~~107~~ 105bytes
```
x=>([a,b]=C([["'*;^`","-coux"],["$+-Oox~",",._"]]),c=C(a))+C(b)+C(C(a)+c)
C=x=>x[Math.random()*9|0]||C(x)
```
[Try it online!](https://tio.run/##FYy9DoIwFEZ3HqMxsdcWgoODqXXpbHyApmop4E8qtwE0HYivXmH5knNy8r3s1w6uf4Yx77BuUitTlEeqLa@MVFRrst6Iy41wkjv8RGK4JiuWnzH@ZseLKzEGuJtTC8AUrZZZgDnIlJy/oj7Z8VH0tqvxTWGzn0ozTYpGSCJrsac@yFL4cNjuBGM@gMNuQN8UHu@0pQAi/QE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes
```
≔⪪‽⪪“V2+⌊>"f↶8)D⦄∕9₂↔≡7¿”¹¹ θ≔E²‽⌊θη⪫E²‽η‽⌈θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8juCAns0QjKDEvJT8XylFS17KOS1DQTc4vrVDR1vXPr6hT0NGLV9JRMDTU1NRRUFJQApKFmtZcUDN8Ews0jHQUoIb4ZuZl5pbmahRqghRnAJUFFGXmlWh45WeiK80AqYBpS6yAa9O0/v//v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @mathcat's Vyxal answer.
```
≔⪪‽⪪“V2+⌊>"f↶8)D⦄∕9₂↔≡7¿”¹¹ θ
```
Split the string `'*;^` -coux$+-Oox~ ,._` into two pieces of length 11, pick one at random, and split it on space. The first element of the resulting list is the eyes and the second is the mouths, but more interestingly, the elements are sorted, so we can use `Minimum` and `Maximum` to refer to them.
```
≔E²‽⌊θη
```
Pick two eyes at random.
```
⪫E²‽η‽⌈θ
```
Pick two eyes at random from the two eyes (this gives a slightly greater than 50% chance of two identical eyes since the original two eyes might have been the same anyway) and join them with a random mouth.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 60 bytes
```
K`'*;^`¶-coux$+-Oox~¶,._
L@s`.{11}
V?`
L$`(.){2}¶(.)
$1$2$?1
```
[Try it online!](https://tio.run/##K0otycxLNPz/3ztBXcs6LuHQNt3k/NIKFW1d//yKukPbdPTiuXwcihP0qg0Na7nC7BO4fFQSNPQ0q41qD20D0lwqhipGKvZAAwA "Retina – Try It Online") Explanation:
```
K`'*;^`¶-coux$+-Oox~¶,._
```
Insert the literal string `'*;^`¶-coux$+-Oox~¶,._`. This is shorter than using a Replace stage because `*`s and `$`s don't need to be quoted here.
```
L@s`.{11}
```
Pick a set of eyes and mouths at random.
```
V?`
```
Separately shuffle the eyes and mouths.
```
L$`(.){2}¶(.)
$1$2$?1
```
Output the last eye, the first mouth, and then a random eye from the last two (giving an exactly 50% chance of a pair of identical eyes).
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), ~~43~~ ~~41~~ 39 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
"'$*+;-^O`o x-~c o,u.x_"ó ö ¸ê ÇpçZöÃmö
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=IickKis7LV5PYG8geC1%2bYyBvLHUueF8i8yD2ILjqIMdw51r2w232)
```
"..."ó ö ¸ê ÇpçZöÃmö
"..." :String Literal
ó :Uninterleave
ö :Random element
¸ :Split on spaces
ê :Palindromise
Ç :Modify last element, Z
p : Append
ç : Repeat to the same length
Zö : Random character of Z
à :End modify
m :Map
ö : Random character
:Implicitly join & output
```
[Answer]
# [Scala](https://www.scala-lang.org/), 414 bytes
Modified from [@l4m2's Javascript answer](https://codegolf.stackexchange.com/a/257689/110802).
\$ \color{red}{\text{The scala code outputs invalid emoticons at times. Any help would be appreciated.}} \$
\$ \text{414 bytes, It can be golfed much more.} \$
---
Golfed version. [Try it online!](https://tio.run/##bZBfS8MwFMXf8ykuoQ@Jq2GiYzBR8EXwQQSHT@Kf2ywbkTSdSSYVmV@99ralDObLD05yzrk3iRodNo0tt1VIEEmpXbJOPaJfVSVjVfFhdIJ7tB5@GMDKrKFshcCwiQu4CQG/n5cpWL95kQt48jbBVecE@EIHoVV9l/KmTreuwiQkXMNUzUYTtqal@RT8hOfALwmvhHcuxUH4zidxIeUYK4ZYFz2lgCZUhB2h5jLvizOSE0Lnexh9NeGXSynsGkSQMAXjooGzo8nD/ay/nx/soYc9cBiWU6civB0/4Fz@M6ur2rafmJwXkWeYFZnmdLxne9Y0fw)
```
import scala.util.Random
object Main {
def main(args: Array[String]): Unit = {
val r = Random.nextFloat() > 0.5
val a = Seq("*", ";", "^", "`")(Random.nextInt(4))
val b = Seq(Seq("-", "c", "o", "u", "x"), Seq("$", "+", "-", "O", "o", "x", "~"))(if (r) 0 else 1)(Random.nextInt(if (r) 5 else 7))
val c = Seq(a, Seq(",", ".", "_")(Random.nextInt(3)))(if (r) 0 else 1)
println(s"$a$b$c")
}
}
```
Ungolfed version. [Try it online!](https://tio.run/##nZI9T8MwEIb3/IpTlMGGELGwFIEEAxIDQmrFhPi4uG5r5Nip7UAQKn892PmGkQyvcvc@d76cYxlKbBpRlNo4sCHKKidktkS11kUU6fyNMwd3KBR8RRHAmm@A7bRgnFi@X8CK7x9Xzgi1faI@at/gwrPgn3eUYNpOPqX4B/RtB0@oNa@91TGZ4rW7VS40ziRXW7ejLepj0qIhPAxTFH4mgmZrF3BlDH7OxnhQwv0awn4WuZbW5/y8JD6KU4jPgzwHeY3pSEruHDcjeRJ8FkQHqYLUM1yX3KDTU0ESiOMgben9WFoH@Z6VlpVirkIntBqr0wBlQV48Oe1wAddaS47Kg8tpWTdSoyMULuE0O5twginkKTDqabEBYmi/is5Gnx6usNsLnbn55Pa7GNy@LXbxAbi0/H@Nx63NfTb589X8OZ31p3dfW/obd1IRGyeY5AmLuz/kEDXNDw)
```
import scala.util.Random
object Main {
def choice(seq: Seq[String]): String = {
val random = new Random
val index = random.nextInt(seq.length)
seq(index)
}
def main(args: Array[String]): Unit = {
val symbols = Seq("*", ";", "^", "`")
val letters = Seq("-", "c", "o", "u", "x")
val operators = Seq("$", "+", "-", "O", "o", "x", "~")
val punctuations = Seq(",", ".", "_")
val r: Boolean = Random.nextFloat() > 0.5
val (a, b, c) = if (r) {
val a = choice(symbols)
val b = choice(letters)
(a, b, a)
} else {
val a = choice(symbols)
val b = choice(operators)
val c = choice(punctuations)
(a, b, c)
}
println(s"$a$b$c")
}
}
```
] |
[Question]
[
Consider the following probability puzzle.
We start with a string of bits all set to 0. At each step we choose a bit uniformly and independently at random and flip it. The value your code has to compute is the probability of getting to the all 1s bit string before you get back to the all 0s bit string.
Let \$n\$ be the length of the starting bitstring.
Examples:
\$n = 1\$. The output is 1.
\$n = 2\$. The output is 1/2.
\$n = 3\$. The output is 2/5.
The remaining outputs for n up to 20 are:
```
3/8,3/8,5/13,60/151,105/256,35/83,63/146,630/1433,1155/2588,6930/15341,12870/28211,24024/52235,9009/19456,9009/19345,17017/36362,306306/651745,2909907/6168632.
```
Your code should take \$n\$ as the input and give the right output. The output must be exact, for example as a fraction. There is no need for the fraction to be fully reduced.
Your code must work for \$n\$ up to at least \$20\$ and run without timing out on [TIO](https://tio.run/#) .
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes
$$n! \div \left( \sum ^n \_{k=0} k!(n-k)! \right)$$
```
#!/Sum[k!(#-k)!,{k,0,#}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X1lRP7g0NzpbUUNZN1tTUac6W8dAR7k2Vu1/QFFmXomCvkO6vkNQYl56arSBjpFB7P//AA "Wolfram Language (Mathematica) – Try It Online")
-4 bytes from @ovs
[Answer]
# [M](https://github.com/DennisMitchell/m), ~~7~~ 6 bytes
```
cRİS‘İ
```
[Try it online!](https://tio.run/##y/3/PznoyIbgRw0zjmz4H2R9uF3lUdOaLCB@1Lgt61Hj9v//jQwA "M – Try It Online")
M is Jelly's more mathematical (and out-of-date) sibling. While Jelly uses floating point maths, M uses rational numbers where possible.
Similarly to [J42161217's Mathematica answer](https://codegolf.stackexchange.com/a/222515/66833), we use the binomial coefficient. This calculates the exact value of
$$1 \div \left(1 + \sum ^n \_{k=1} \frac 1 {\binom n k}\right)$$
## How it works
```
cRİS‘İ - Main link. Takes n on the left
R - Range [1, 2, ..., n]
c - Calculate nCk for each k
İ - Inverse; Get the reciprocal of each
S - Sum
‘ - Increment, to account for nC0
İ - Inverse; Get the reciprocal again
```
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, ~~45~~ 43 bytes
```
[ dup [0,b] [ nCk -1 ^ ] with map Σ -1 ^ ]
```
[Try it online!](https://tio.run/##LYwxDsIwEAR7XrEPgChQQkmBaGgQlRUkx7mQU8jZOGch3sN/@JIJIt3OaLStdepjvpyPp8MWPUWhOwarXdEmccpexj86P9QsdorZzSpaudG8k7DzDSFEUn2FyKIY6ZFI3JTsFpsS7NVmgyYFmHJZVzCQfY/VGldUeLJ201XA5z2r/KMifwE "Factor – Try It Online")
This uses the formula graciously offered in the following [M answer](https://codegolf.stackexchange.com/a/222516/97916).
*Edit:* use `-1 ^` instead of `recip` since it's 1 byte shorter.
## Explanation:
It's a quotation (anonymous function) that takes an (0-indexed) integer as input and returns a number (probably a ratio) as output. Assuming `4` is on top of the data stack when this quotation is called...
* `dup` Duplicate TOS (top of stack). **Stack:** `4 4`
* `[0,b]` Create a range object from the number at TOS (0 to 4 inclusive). **Stack:** `4 T{ range f 0 5 1 }`
* `[ nCk -1 ^ ]` Push a quotation to the data stack to be used later by `with`. **Stack:** `4 T{ range f 0 5 1 } [ nCk -1 ^ ]`
* `with` Partial application on the left. It sticks that 4 that's been lingering on the data stack into the quotation that's about to be used by `map` in such a way that it comes before the range elements being mapped over. **Stack:** `T{ range f 0 5 1 } [ 4 [ nCk -1 ^ ] swapd call ]`
* `map` Apply a quotation to each element of a sequence, collecting the results into a sequence of the same size. (Inside the quotation now...) **Stack:** `4 0`
* `nCk` Outputs the total number of unique combinations of size TOS that can be taken from a set of size NOS (next on stack). Also known as 4 choose 0. **Stack:** `1`
* `-1 ^` Take the reciprocal. Shorter than `1 swap /` and `recip`. **Stack:** `1`
* Now `map` applies the quotation to each element of the range sequence and we end up with... **Stack:** `{ 1 1/4 1/6 1/4 1 }`
* `Σ` Take the sum of a sequence. **Stack:** `2+2/3`
* `-1 ^` Take the reciprocal. **Stack:** `3/8`.
[Answer]
# [Python 2](https://docs.python.org/2/), 85 bytes
```
n=input()
B=9**9;p=1;q=0
for i in range(n+1):x=(B+1)**n/B**i%B;q=p+x*q;p*=x
print p,q
```
[Try it online!](https://tio.run/##DcxLCoMwFEbh@b@KECjEKNXr@0Em7kSKtgGJNzaldvXW0Zl8HP6F1@by8/uy6yyon4/5IaU8nbGOP0FFGE2ndTewocGbDMu2CyusE/vknrNyMUX9YdR4VWuXjlrb23hJjg/tB9bmAO/WBcGJP6/z/R12yyqKZbKs2xQUR6mXJyFHgRIVajRo0YEyEIFyUAEqQRWoBjWgFtQhz/4 "Python 2 – Try It Online")
A nice solution made uglier by the requirement that we output an exact fraction. With floats, it looks like:
**62 bytes**
```
lambda n,B=9**9:1/sum(1./((B+1)**n/B**i%B)for i in range(n+1))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPx8nWUkvL0spQv7g0V8NQT19Dw0nbUFNLK0/fSUsrU9VJMy2/SCFTITNPoSgxLz1VIw8oq/kfJJiHEDTUMTLUtOLiLCjKzCvRyNNRSNPIA6oCAA "Python 2 – Try It Online")
We use the formula $$ \left(\sum ^n \_{i=0} {\binom n i}^{-1}\right)^{-1}$$ and compute the binomials coefficients using [this trick](https://codegolf.stackexchange.com/a/169115/20260). This gives us a sleeves-rolled-up solution without any imports or built-ins for factorial or binomial coefficients.
The original code implements fraction arithmetic by updating the fraction `p/q`. It might be shortenable but I don't really care to golf it. A more direct but longer conversion uses the [`fractions`](https://docs.python.org/3/library/fractions.html) library:
**94 bytes**
```
from fractions import*
lambda n,B=9**9:1/sum(1/Fraction(((B+1)**n/B**i%B))for i in range(n+1))
```
[Try it online!](https://tio.run/##Rco9CsMwDEDhuTmFloKsGoyzJZDFQ@/h/rgV1LJRnKGnd1ModP3eq@/2LDL2nrRkSBqvjYuswLkWbTSk5RXz5RZBbFgmomn2bt0yenf@vYgYTt4QiQtEfAzGpKLAwAIa5XFH2bPpX5Q/ejt6Mw@HqiwNxUJC2a8P "Python 2 – Try It Online")
---
This replace-and-evaluate monstrosity would save bytes over the floats version, but it gives wrong answers where some \$\binom{n}{i}\$ ends in a zero digit.
**56 bytes, doesn't work**
```
lambda n:1/eval(`(10**17+1)**n`.replace('0'*9,'e0+1./'))
```
[Try it online!](https://tio.run/##BcHBDoIwDADQs35Fb2vHAisXA4l/woGqnZLMsizExK8f75X/8dltbOm@tCzfx0vAZh70JxlX5Og93zom723tq5YsT0UXnZ@C09hxPziilvYKBptBFXsrchiZ5uul1M0OsAAJjdoJ "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~83~~ 77 bytes
-4 thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)! (`from math import factorial as f` -> `f=lambda n:0**n or n*f(n-1)`)
-2 thanks to ovs! (`0**n or` -> `n<1or`)
```
f=lambda n:n<1or n*f(n-1)
lambda n:(f(n),sum(f(i)*f(n-i)for i in range(n+1)))
```
An unnamed function accepting `n` that returns a tuple `(numerator, denominator)` (not simplified).
**[Try it online!](https://tio.run/##RY6xDsIwDET3fsVtxFCQ0rGia7@CJUBTLBGnSsKAKr69uAiBF/tOd0@enuUWpVnG7rTcXThfHaQ13gjV@RH0YNqq2jP5mMBgQXIyDkZ2logq3/1acrQakU/c0uJTDPDJXQpHyeAwxVTQfw24jL6qVqj8obZGY6mtoJOGjA6jfvKRU2Ip2MyvFvMLJivvzp41VOJq0eagsOCKkXrt1ujNVjfR8gY "Python 2 – Try It Online")** (1-20, including simplified fraction)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 61 bytes
```
n=>[(g=n=>n?n*g(~-n):1)(n),(h=k=>g(k)*g(n-k)+(k&&h(~-k)))(n)]
```
[Try it online!](https://tio.run/##LY3BjsIwDETvfMVcAJu0FDjSTfkQxCEJbVpSJQjQXlbLrxcHOFijeTO2L@bX3N1tuD7KmM7t1Okp6uZIXovEQ1x5epaR91umyAX1OujGU2DhsQysKCwWvVQCc26cJu/O0CBTwDJ0A4M5LA4QTrb4WMYetp516UZj@8AgC5ta5Ae7rEox/mZAzo6msCfJOxq4/jInPp97/8jQpXhPY7sekydTOSgsUcko2MpJ4396AQ "JavaScript (Node.js) – Try It Online")
Search the sample output given by OP on OEIS, and you may find out [A046825](https://oeis.org/A046825). Use the formula given on that page:
$$
\begin{split}
f(n) & = \frac{1}{\sum\_{k=0}^{n}\frac{1}{C\_n\left(k\right)}} \\
& = \frac{1}{\sum\_{k=0}^{n}\frac{k!\left(n-k\right)!}{n!}} \\
& = \frac{n!}{\sum\_{k=0}^{n}k!\left(n-k\right)!}
\end{split}
$$
It may need +1 byte (change `1` to `1n`) if larger (\$n>21\$) testcases is required.
Note: I have no idea why it works.
[Answer]
# [R](https://www.r-project.org/), ~~45~~ 40 bytes
Using [J42161217's Mathematica answer](https://codegolf.stackexchange.com/a/222515/85958), and following [Guiseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)'s astounding improvement,
```
function(n,`!`=gamma)c(!n,(!1:n)%*%!n:1)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jTydBMcE2PTE3N1EzWUMxT0dD0dAqT1NVS1Uxz8pQ83@ahqEmV5qGEYgwBhEmIMIURBgagGUMNP8DAA "R – Try It Online")
[Answer]
# [Sledgehammer](https://github.com/tkwa/Sledgehammer), 11 bytes
```
⣸⢄⠔⢅⢉⢟⣹⢤⢟⡹⣽
```
Decompresses into this Wolfram Language function:
```
Tr[Binomial[#1, Range[0, #1]]^(-1)]^(-1) &
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6Qo2ikzLz83MzEnWtlQRyEoMS89NdpAR0HZMDY2TkPXUBNCKqgp/A8oyswriVbWtUuLVo6NVasLTk7Mq4NpMLSM/Q8A "Wolfram Language (Mathematica) – Try It Online")
Returns 0-indexed fractions.
---
Can't say I have much to add in terms of golfing, but as, judging by the other answers, no one seems to know why the formula works, I can offer an explanation:
Let \$P\_n(k)\$ be the probability that, following the given algorithm, a string of all ones is reached before a string of all zeroes, starting from an \$n\$-length bitstring which has \$k\$ ones. We can immediately see that \$P\_n(0)=0\$ and \$P\_n(n)=1\$. The desired value is \$P\_n(1)\$: one bit is flipped on first.
When we flip a bit at random, there is a \$\frac kn\$ chance that bit was a one, and a \$\frac{n-k}n\$ chance it was a zero. Therefore, for \$0<k<n\$, we have \$P\_n(k)=\frac knP\_n(k-1)+\frac{n-k}nP\_n(k+1)\$. In other words, \$P\_n(k)\$ is the weighted average of \$P\_n(k-1)\$ and \$P\_n(k+1)\$, with weights \$k\$ and \$n-k\$, respectively.
If we denote \$P\_n(x)-P\_n(x-1)\$ by \$\Delta P\_n(x)\$, we can equivalently say \$\Delta P\_n(k+1)=\frac{k}{n-k}\Delta P\_n(k)\$.
Checking some values of \$k\$:
* \$\Delta P\_n(2)=\frac 1{n-1}\Delta P\_n(1)\$
* \$\Delta P\_n(3)=\frac 2{n-2}\Delta P\_n(2)=\frac{1\cdot 2}{(n-1)(n-2)}\Delta P\_n(1)\$
* And, in general, \$\Delta P\_n(k)=\frac{(k-1)!(n-k)!}{(n-1)!}\Delta P\_n(1)={n-1\choose k-1}^{-1}\Delta P\_n(1)\$ by induction.
Now, consider the telescoping sum
\$P\_n(n)-P\_n(0)=1=\sum\_{k=1}^n\Delta P\_n(k)=\sum\_{k=1}^n{n-1\choose k-1}^{-1}\Delta P\_n(1)\$.
Solving, we get our formula \$\Delta P\_n(1)=P\_n(1)=\left(\sum\_{k=1}^n{n-1\choose k-1}^{-1}\right)^{-1}\$.
The zero-indexed form is slightly more compact: \$P\_{n+1}(1)=\left(\sum\_{k=0}^n{n\choose k}^{-1}\right)^{-1}\$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
[5 bytes](https://tio.run/##y0rNyan8/z/56O4jG4KPbPj//78JAA) with `cŻİSİ` if we may print with floating point inaccuracy.
```
cŻPṄ:ƊS
```
A full program printing a numerator and then a denominator (not simplified).
**[Try it online!](https://tio.run/##y0rNyan8/z/56O6AhztbrI51Bf///98EAA "Jelly – Try It Online")**
### How?
```
cŻPṄ:ƊS - Main Link: integer, n
Ż - zero range -> [0,1,2,...,n]
c - (n) choose (that) (vectorises) -> [1, n, ..., n, 1] (Pascal row n)
Ɗ - last three links as a monad - f(Pascal row n):
P - product (of Pascal row n)
Ṅ - print (product) and a newline; yield (product)
: - (product) integer divide (Pascal row n) (vectorises)
S - sum
- implicit print
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
FN⊞υ∨¬ι×⌈υιI⟦⌈υΣE⮌υ×ι§υκ
```
[Try it online!](https://tio.run/##TY2xDsIwDAV3viKjLYWNjQkxdWipChtiCMWoFk1TOXHVvw8BFqYn3ZPu@sFJH9yY8zOIgWqaNTXq7ySAaFqNA6g1J4EmJGC05sKeItRuZa8etBBGxP2mFZ4SHF1McP1/z2VrN0NHC0mkL/s52JpDqqYHrZ/Eq1jwVkw57/J2Gd8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Flipping `n` random bits in a string is equivalent to a random walk over the vertices of an `n`-dimensional hypercube; moving along an edge corresponds to flipping one of the bits. The starting point is the string of all `0`s and the diagonally opposite vertex is the string of all `1`s. The probability that it visits that vertex before it returns to the starting point is then documented in the linked page as being (n-1)!/[A003149](https://oeis.org/A003149)(n-1).
```
FN⊞υ∨¬ι×⌈υι
```
Input `n` and calculate the factorials up to `n-1`.
```
I⟦⌈υΣE⮌υ×ι§υκ
```
Output `(n-1)!` as the numerator and the sum of the termwise product of the factorials with their reverse as the denominator.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ ~~9~~ 8 bytes
*-1 thanks to [Command Master](https://codegolf.stackexchange.com/users/92727/command-master).*
```
!,Ý!Â*O,
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fUefwXMXDTVr@Ov//G1oCAA "05AB1E – Try It Online")
```
!,Ý!Â*O, # full program
, # output...
# implicit input...
! # factorial
, # output...
O # sum of...
Ý # [0, 1, 2, ...,
# ..., implicit input...
Ý # ]...
# (implicit) with each element...
! # factorial...
# (implicit) with each element...
* # multiplied by...
# (implicit) corresponding element in...
Ý # [0, 1, 2, ...,
# ..., implicit input...
Ý # ]...
# (implicit) with each element...
! # factorial...
 # reversed
```
] |
[Question]
[
### Input:
Integer `n` which is `>=0` or `>=1` (`f(0)` is optional)
### Output:
The `n`'th number in the sequence below, OR the sequence up to and including the `n`'th number.
### Sequence:
```
(0),1,-1,-3,0,5,-1,-7,0,9,-1,-11,0,13,-1,-15,0,17,-1,-19,0,21,-1,-23,0,25,-1,-27,0,29,-1,-31,0,33,-1,-35,0,37,-1,-39,0,41,-1,-43,0,45,-1,-47,0,49,-1,-51,0,53,-1,-55,0,57,-1,-59,0,61,-1,-63,0,65,-1,-67,0,69,-1,-71,0,73,-1,-75,0,77,-1,-79,0,81,-1,-83,0,85,-1,-87,0,89,-1,-91,0,93,-1,-95,0,97,-1,-99
```
How is this sequence build?
`f(n=0) = 0` (optional)
`f(n=1) = f(0) + n` or `f(n=1) = 1`
`f(n=2) = f(1) - n`
`f(n=3) = f(2) * n`
`f(n=4) = f(3) / n`
`f(n=5) = f(4) + n`
etc.
Or in pseudo-code:
```
function f(integer n){
Integer result = 0
Integer i = 1
Loop as long as i is smaller than or equal to n
{
if i modulo-4 is 1:
result = result plus i
if i modulo-4 is 2 instead:
result = result minus i
if i modulo-4 is 3 instead:
result = result multiplied with i
if i modulo-4 is 0 instead:
result = result integer/floor-divided with i
i = i plus 1
}
return result
}
```
But as you may have noted there are two patterns in the sequence:
```
0, ,-1, ,0, ,-1, ,0, ,-1, ,0, ,-1, ,0, ,-1, ,...
,1, ,-3, ,5, ,-7, ,9, ,-11, ,13, ,-15, ,17, ,-19,...
```
so any other approaches resulting in the same sequence are of course completely fine as well.
## Challenge rules:
* 0-indexed and 1-indexed inputs will result in the same result (which is why the `f(0)` is optional for 0-indexed inputs if you want to include it).
* You are allowed to output the `n`'th number of this sequence. Or the entire sequence up and including the `n`'th number. (So `f(5)` can result in either `5` or `0,1,-1,-3,0,5`.)
+ If you choose to output the sequence up to and including the `n`'th number, output format is flexible. Can be a list/array, comma/space/new-line delimited string or printed to STDOUT, etc.
* The divide (`/`) is integer/floor division, which rounds towards 0 (not towards negative infinity as is the case in some languages).
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
## Additional test cases above `n=100`:
```
Input Output
1000 0
100000 0
123 -123
1234 -1
12345 12345
123456 0
```
[Answer]
# JavaScript (ES6), 19 bytes
```
n=>[0,n,-1,-n][n&3]
```
[Try it online!](https://tio.run/##JYfLDsIgEEX3fsWsBOLQQGmrxtCdX0FYEGx9pBlMa/x9LDa555zcV/iGJc7P90dSug15tJls7xQSSo2SvKO98fniNNZosMEWOzziCc@o1Tq1qaQ2heavdnPnd9WY5muID05ge4iJljQN1ZTunAXO4AC0wgRYKGfkJITIPw "JavaScript (Node.js) – Try It Online")
### Proof
Let's assume that we have the following relations for some **n** multiple of 4. These relations are trivially verified for the first terms of the sequence.
```
f(n) = 0
f(n+1) = n+1
f(n+2) = -1
f(n+3) = -(n+3)
```
And let **N = n + 4**. Then, by definition:
```
f(N) = f(n+4) = f(n+3) // (n+4) = -(n+3) // (n+4) = 0
f(N+1) = f(n+5) = f(n+4) + (n+5) = 0 + (n+5) = N+1
f(N+2) = f(n+6) = f(n+5) - (n+6) = (n+5) - (n+6) = -1
f(N+3) = f(n+7) = f(n+6) * (n+7) = -1 * (n+7) = -(N+3)
```
Which, by mathematical induction, proves that the relations hold for any **N** multiple of **4**.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
Outputs the `nth` number
```
ÎD(®s)sè
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cJ@LxqF1xZrFh1f8/28OAA "05AB1E – Try It Online")
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
Outputs a list of numbers upto N using the patterns in the sequence
```
ÅÉāÉ·<*āÉ<‚øí˜
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cOvhziONhzsPbbfRAtE2jxpmHd5xeO3pOf//G5oCAA "05AB1E – Try It Online")
**Explanation**
Example using N=7
```
ÅÉ # List of odd numbers upto N
# STACK: [1,3,5,7]
ā # Enumerate 1-based
É # is odd?
# STACK: [1,3,5,7],[1,0,1,0]
·< # double and decrement
# STACK: [1,3,5,7],[1,-1,1,-1]
* # multiply
# STACK: [1,-3,5,-7]
āÉ< # enumerate, isOdd, decrement
# STACK: [1,-3,5,-7],[0,-1,0,-1]
‚ø # zip
# STACK: [[1, 0], [-3, -1], [5, 0], [-7, -1]]
í # reverse each
˜ # flatten
# RESULT: [0, 1, -1, -3, 0, 5, -1, -7]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 25 bytes
Port of Arnauld's answer:
```
lambda n:[0,n,-1,-n][n%4]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKtpAJ09H11BHNy82Ok/VJPZ/Wn6RQp5CZp5CUWJeeqqGkYGmFZdCQVFmXolCmkae5n8A "Python 2 – Try It Online")
---
Naive solutions:
# [Python 3](https://docs.python.org/3/), ~~50~~ 49 bytes
```
lambda n:n and eval('int(f(n-1)%sn)'%'/+-*'[n%4])
```
[Try it online!](https://tio.run/##LctNDkAwEAbQvVPMpmmHiN9VEyfBYoQi4SMlEqevjbd/53svB6rgmi5ssg@jECxIMNL0yGb0its4g7RgdYG10lmSxrqFqnsO7vAEWkFeME@mzNlGdPr/MIcP "Python 3 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), ~~78~~ ~~77~~ ~~76~~ ~~58~~ ~~57~~ ~~53~~ 52 bytes
```
lambda n:n and eval('int(1.*f(n-1)%sn)'%'/+-*'[n%4])
```
[Try it online!](https://tio.run/##FctNDkAwEAbQvVPMpmmH@I2VxEmwGKFI@EiJxOmLt3/Hc807Cm/r1q@y9YMQKpBgoPGW1egFl8mT0BrEOasTrJVOozjUDVTZsbe7I9ACcoJpNEXGVUCH@9t3mP0L "Python 2 – Try It Online")
Used a bunch of bytes on `int`, because python floor divides, and not towards `0`, as in the question.
[Answer]
# [J](http://jsoftware.com/), 12 bytes
Port of Arnauld's answer:
```
4&|{0,],_1,-
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/TdRqqg10YnXiDXV0/2typSZn5CukKajZKRhqZ@oZGcAEDA0MUNhIPCNjJKYJMtsUhWPG9R8A "J – Try It Online")
# [J](http://jsoftware.com/), 28 bytes
Naive solution:
```
{(0 _1$~]),@,.(_1^i.)*1+2*i.
```
Outputs the nth number
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/qzUMFOINVepiNXUcdPQ04g3jMvU0tQy1jbQy9f5rcqUmZ@QrpCmo2SkYamfqGRnABAwNDFDYSDwjYySmCTLbFIVjxvUfAA "J – Try It Online")
[Answer]
# [TIS](https://github.com/Phlarx/tis.git) `-n` `2` `1`, 123 bytes
Outputs the `n`th number for `0 <= n <= 999`. (The upper limit is due to language limitations).
```
@0
MOV UP ACC
MOV ACC ANY
L:SUB 4
JGZ L
JEZ L
ADD 5
JRO -5
@1
MOV UP ACC
JRO UP
SUB ACC
JRO 3
MOV 1 ACC
NEG
MOV ACC ANY
HCF
```
[Try it online!](https://tio.run/##K8ks/v/fwYDL1z9MITRAwdHZGcwE0gqOfpFcPlbBoU4KJlxe7lEKPlxeriDS0cVFwZTLK8hfQdeUy8EQWStIMDSAC6QHxjUGyxuC@X6u7iimezi7/f9vaGT83@i/4X/dPAA "TIS – Try It Online")
---
# [TIS](https://github.com/Phlarx/tis.git) `-n` `2` `1`, 124 bytes
Outputs the `n`th number for `0 <= n <= 999`. (The upper limit is due to language limitations). Multiple `n` may be provided, separated by whitespace.
```
@0
MOV UP ACC
MOV ACC ANY
L:SUB 4
JGZ L
JEZ L
ADD 5
MOV ACC ANY
@1
MOV UP ACC
JRO UP
SUB ACC
JRO 3
MOV 1 ACC
NEG
MOV ACC ANY
```
[Try it online!](https://tio.run/##K8ks/v/fwYDL1z9MITRAwdHZGcwE0gqOfpFcPlbBoU4KJlxe7lEKPlxeriDS0cVFwRRFlYMhsn6vIH8gkwukEcY1Bssbgvl@ru7Imv//NwBKGCkYK5gomCqYKZgrWChYKhgCBQ3/G/03/K@bBwA "TIS – Try It Online")
---
# [TIS](https://github.com/Phlarx/tis.git) `-n` `3` `1`, 192 bytes
Outputs the values for `0..n` for `0 <= n <= 999`. (The upper limit is due to language limitations).
```
@0
MOV UP ACC
ADD 1
MOV ACC ANY
JRO -1
@1
SUB UP
JLZ C
HCF
C:ADD UP
MOV ACC ANY
ADD 1
SWP
ADD 1
MOV ACC ANY
SUB 4
JEZ W
ADD 4
W:SWP
@2
MOV UP ACC
JRO UP
SUB ACC
JRO 3
MOV 1 ACC
NEG
MOV ACC ANY
```
[Try it online!](https://tio.run/##bY4xDsIwDEX3fwpfoFJNO3VKcAsograiKhG9AQsL3N/EQUgZGP//T89@P16qrsZlutE6kxeB73viXKREfrwjXCeqGI6xrPuEIZw3EpzkAOkMT1XJfw1LnP@4zNAiDBvFvLaInZFuV/5gF5PU4F9s8s45j8OxlKpyrY2yVs8P "TIS – Try It Online")
---
All use numeric I/O (the `-n` flag). The first two solutions use two compute nodes, one positioned above the other. The third has a stack of three nodes.
For the first two solutions, the upper node reads input, sends the original number on, then repeatedly subtracts 4 until we go negative, then adds 5 to index for our jump table. This is equivalent to `(n % 4) + 1`.
The third solution split this task across two nodes; the top one just repeats the limit until the end of time, and the middle node counts up in parallel the index (compared against that limit) and the modulo like above.
The lower node of all three solutions is the same; it has a jump table, and this is where the magic happens. We store the original number in `ACC`, then `JRO` (probably **J**ump **R**elative **O**ffset) forward by `1`, `2`, `3`, or `4`, depending on what the node above says.
Working backward:
* `4` will *a*) `NEG`ate `ACC`, and *b*) move `ACC` down for output.
* `3` will put `1` into `ACC`, then perform steps `4`*a* and `4`*b*.
* `2` will jump directly to step `4`*b*.
* `1` will `SUB`tract `ACC` off itself (effectively zeroing `ACC`), then do step `2`, which jumps to `4`*b*.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 62 bytes
```
f(n,k){k=~-n;n=n?n%4?k%4?n-2&3?f(k)*n:f(k)-n:f(k)+n:f(k)/n:0;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI08nW7M627ZON886zzbPPk/VxD4biPN0jdSM7dM0sjW18qxAlC6E0oZQ@nlWBta1/3MTM/M0vDSr0/KLNLxsDay9bCwtrTULijLzStI0lFRTdJR00jS8tLU1NYGKAQ "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
,-;N;0⁸ị
```
[Try it online!](https://tio.run/##y0rNyan8/19H19rP2uBR446Hu7v///9vaGRsAgA "Jelly – Try It Online")
-1 thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn).
What others are doing (port of Arnauld's solution), supports `0`.
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
A:A}××Ṡ¥
R_×ç+4ƭ/
```
[Try it online!](https://tio.run/##y0rNyan8/9/RyrH28PTD0x/uXHBoKVdQPJC9XNvk2Fr9////GxoAAA "Jelly – Try It Online")
`0` is not supported.
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 25 bytes
```
n->n%2>0?n*(2-n%4):n%4/-2
```
[Try it online!](https://tio.run/##NY49b8IwEIZ3fsUrpEhOIS4NTHyKsUPVAXWqOpgEowvhbNkXpKjit6cuVYd7n@FOz72NuZmiqS9D1ZoY8WaI8T0CfHdsqUIUIwk3RzWuaacOEojPn18w4RzzxynQJInuhFptO66EHOtXlg82oX/3p2DEBVhsBi62nJXb2Y6fVFlwtsiXKZ6Lclg9PNYFRSwgbPCySlijnCVOJv@fgEMf5XTVrhPtUxWxapzN6yVSZDyegqaw2njf9vuYSijK8z/5ffQ79@EH "Java (JDK 10) – Try It Online")
Shorter than the contender algorithm in other languages with 28 bytes
```
n->new int[]{0,n,-1,-n}[n%4]
```
[Try it online!](https://tio.run/##NY4xa8MwEIX3/IpHwGATWSRtp6YpdOxQOoROxoNqW@Fc5ySkc4oJ/u2umtLh7hve8d3rzcWUffu1NIOJEW@GGNcV4MfPgRpEMZJwcdTinLL8KIH4VNUw4RSL2ynQJ4kehQZtR26EHOtXlg82YXr3XTDiAiwOC5fP3H2DWKr6ulWsyp0qea44e6iX/U1lXchTDsIBu33CE@62iZvN/zPgOEXpztqNon1qIzZfZ/ftI9LKeK1AClYb74fpJaYeORXFn3xe/c68/AA "Java (JDK 10) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 46 bytes
```
.+
*
r`(____)*$
_$.=
____
-
___.*
-1
__
_.*
0
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9Pm0uLqyhBIx4INLVUuOJV9Gy5QBwuXRClp8WlawhkcHGBmAb//xsaGXMBsQmYMIWQZgA "Retina – Try It Online") Explanation:
```
.+
*
```
Convert to unary.
```
r`(____)*$
_$.=
```
Convert back to decimal, but leave `n%4+1` underlines.
```
____
-
```
In the case that that's 4, then the result is `-n`.
```
___.*
-1
```
Case 3: `-1`
```
__
```
Case 2: `n`
```
_.*
0
```
Case 1: `0`
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
```
f 0=0
f n=([(+),(-),(*),quot]!!mod(n-1)4)(f(n-1))n
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwNaAK00hz1YjWkNbU0dDF4i1NHUKS/NLYhUVc/NTNPJ0DTVNNDXSwAzNvP@5iZl5CrYKuYkFvvEKGgVFmXklemmaCtGGBgYGOiACRBkZg7AJmDCFkGax/wE "Haskell – Try It Online")
Arnauld's solution, ported to Haskell is 23 bytes:
```
z n=cycle[0,n,-1,-n]!!n
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 22 12 bytes
Massive 10 bytes saved due to Erik the Outgolfer's remarks. Thank you!
```
4∘|⊃0,⊢,¯1,-
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qn/6O2CQb/04CkyaOOGTWPupoNdB51LdI5tN5QR/f//zQFQy4gNgURBgYGUArCMDKGkCZQyhRGmwEA "APL (Dyalog Classic) – Try It Online")
Outputs the nth number
I don't know APL, I just tried to make my J port of Arnauld's solution work in Dyalog APL.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~20~~ 19 bytes
```
Iun:^>s1ns:u@Ota3s0
```
[Try it online!](https://tio.run/##Sy5Nyqz4/9@zNM8qzq7YMK/YqtTBvyTRuNjg/39DI2MTUwA "Cubix – Try It Online")
Ports the same approach to cubix.
On a cube:
```
I u
n :
^ > s 1 n s : u
@ O t a 3 s 0 .
. .
. .
```
The first bit `^Iu:n>s1ns:u0s` builds the stack and then `3at` copies the appropriate item to TOS, then `O` outputs and `@` ends the program.
[Answer]
# Whitespace, ~~84~~ 83 bytes
```
[S S S N
_Push_0][S N
S _Duplicate_0][T T S _Store][S S S T S N
_Push_2][S S T T N
_Push_-1][T T S _Store][S S S T N
_Push_1][S N
S _Duplicate_1][T N
T T _Read_STDIN_as_integer][S S S T T N
_Push_3][S S S T N
_Push_1][T T T ][S S T T N
_Push_-1][T S S N
_Multiply][T T S _Store][T T T _Retrieve_input][S S S T S S N
_Push_4][T S T T _Modulo][T T T _Retrieve_result][T N
S T _Print_as_integer]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIOTmBDAVOIAvI5ILywBIQDlAQLMIJ4oFUALUBmZwQSRAHxOYEKeP8/98cAA) (with raw spaces, tabs and new-lines only).
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/162106/52210).
**Explanation (example input `n=7`):**
```
Command Explanation Stack Heap STDIN STDOUT STDERR
SSSN Push 0 [0]
SNS Duplicate top (0) [0,0]
TTS Store [] {0:0}
SSSTSN Push 2 [2] {0:0}
SSTTN Push -1 [2,-1] {0:0}
TTS Store [] {0:0,2:-1}
SSSTN Push 1 [1] {0:0,2:-1}
SNS Duplicate top (1) [1,1] {0:0,2:-1}
TNTT Read STDIN as nr [1] {0:0,1:7,2:-1} 7
SSSTTN Push 3 [1,3] {0:0,1:7,2:-1}
SSSTN Push 1 [1,3,1] {0:0,1:7,2:-1}
TTT Retrieve input [1,3,7] {0:0,1:7,2:-1}
SSTTN Push -1 [1,3,7,-1] {0:0,1:7,2:-1}
TSSN Multiply (-1*7) [1,3,-7] {0:0,1:7,2:-1}
TTS Store [1] {0:0,1:7,2:-1,3:-7}
TTT Retrieve input [7] {0:0,1:7,2:-1,3:-7}
SSSTSSN Push 4 [7,4] {0:0,1:7,2:-1,3:-7}
TSST Modulo (7%4) [3] {0:0,1:7,2:-1,3:-7}
TTT Retrieve [-7] {0:0,1:7,2:-1,3:-7}
TNST Print as integer [] {0:0,1:7,2:-1,3:-7} -7
error
```
Stops with error: Exit not defined.
] |
[Question]
[
You have been collecting data from a *Advanced Collecting Device Controller™* for a long time. You check the logs, and to your horror you discover that something has gone terribly wrong: the data only contains the last bits of the numbers!
Luckily, you know the starting value and that the value never changes fast. That means you can recover the rest by just finding the distance from the start.
## Challenge
You will write a program or a function to calculate the amount a value has changed, given a modulus `N` and a list of the intermediate values modulo `N`.
The change between every pair of numbers **is always less than `N/2`**, so there will only be one valid answer for each test case.
You will be given as input an integer `N` > 2 and a list of values, in a format of your choice. Input may be given via STDIN or command line or function arguments.
You will output a single integer, the amount the original value has changed. Output may be printed to STDOUT or returned.
## Rules
* Your program must work for any distance and modulus less than `2^20`.
* You may assume that:
+ `N` is at least `3`.
+ The list has at least 2 values.
+ All the values in the list are at least 0 and less than `N`.
+ All changes in the numbers are less than `N/2`.
* Anything else is an invalid input, and your program may do whatever it wants.
* Standard loopholes, any non-standard libraries and built-in functions for this exact purpose are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins.
## Example test cases
Input:
```
3
0 1 2 2 0 1 0 2 1 2 0 1 2 1 1
```
Output:
```
4
```
Explanation (with example value):
```
Value mod 3: 0 1 2 2 0 1 0 2 1 2 0 1 2 1 1
Value: 0 1 2 2 3 4 3 2 1 2 3 4 5 4 4
```
Input:
```
10
5 2 8 9 5
```
Output:
```
-10
```
Explanation (with example value):
```
Value mod 10: 5 2 8 9 5
Value: 15 12 8 9 5
```
### Invalid inputs:
```
2
0 0 0 0 0
```
(too small modulus)
```
6
2 5 4 2
```
(too large change between 2 and 5)
[Answer]
# Python 2, 53 bytes
```
lambda n,l:sum((b-a+n/2)%n-n/2for a,b in zip(l,l[1:]))
```
Super straight forward answer. I wonder if there is a shorter way.
[Answer]
# Mathematica, 30 bytes
```
Tr@Mod[Differences@#2,#,-#/2]&
```
This is an anonymous function which takes two arguments. Example usage:
```
Tr@Mod[Differences@#2,#,-#/2]&[3, {0, 1, 2, 2, 0, 1, 0, 2, 1, 2, 0, 1, 2, 1, 1}]
(* 4 *)
Tr@Mod[Differences@#2,#,-#/2]&[10, {5, 2, 8, 9, 5}]
(* -10 *)
```
This works by taking the `Differences` between successive elements, wrapping them to the range `-n/2` to `+n/2` with `Mod` and its offset parameter, then taking the total with `Tr` (matrix trace, sum of diagonal elements).
---
Note that even ungolfed it's only 43 bytes!
```
f[n_, l_] := Total[Mod[Differences[l], n, -n/2]]
```
[Answer]
# J, 24 bytes
```
[+/@(]-(>-:)~*[)[|2-~/\]
```
Usage:
```
f=:[+/@(]-(>-:)~*[)[|2-~/\]
3 f 0 1 2 2 0 1 0 2 1 2 0 1 2 1 1
4
10 f 5 2 8 9 5
_10
```
Will try to golf more and add some explanation after that.
[Try it online here.](http://tryj.tk/)
[Answer]
# Pyth, 20 19 bytes
```
sm-J/Q2%+-FdJQ.:vw2
```
Stole `.:_2` from Jakube, idea from Mauris.
[Answer]
# R, 38 bytes
```
function(n,v)sum((diff(v)+n/2)%%n-n/2)
```
This creates an unnamed function that accepts an integer and a vector as input and returns a single integer. To call it, give it a name, e.g. `f=function(n,v)...`.
Ungolfed + explanation:
```
f <- function(n, v) {
# Compute the differences between sequential elements of v
d <- diff(v)
# Add n/2 to the differences and get the result modulo n
m <- (d + n/2) %% n
# Subtract n/2 then sum the vector
sum(m - n/2)
}
```
Examples:
```
> f(3, c(0, 1, 2, 2, 0, 1, 0, 2, 1, 2, 0, 1, 2, 1, 1))
[1] 4
> f(10, c(5, 2, 8, 9, 5))
[1] -10
```
[Answer]
# MatLab, 33 bytes
```
@(x,y)sum(mod(diff(y)+x/2,x)-x/2)
```
My apologies, this is my first answer on this website. Typing this in MatLab then using the input `ans(modulus_value, [intermediate_values])` will return the requested value, where 'modulus\_value' is the modulus value, and 'intermediate\_values' is a list of the intermediate values separated by either spaces or commas.
Example:
```
ans(3, [0 1 2 2 0 1 0 2 1 2 0 1 2 1 1])
```
The anonymous function takes advantage of MatLab's `mod`, `diff`, and `sum` functions to compute the answer. First, the difference between each of the intermediate values is calculated. The result is then offset by the modulus divided by two, resulting in a set of difference values that is bound by [-modulus/2 modulus/2]. The result is then offset and summed again.
I think this can be golfed more, I'll be back soon with an update. Special thanks to @2012rcampion for the idea.
**Edit:** Matlab's `unwrap` function almost works here, but it's tough to golf. The following code returns an array where the last value is the amount the first value has changed:
`@(x,y)unwrap(y/x*2*pi)/2/pi*x-y(1)`
The intermediate values are scaled to the range of [-pi pi], then "unwrapped" such that no consecutive value is more than pi apart. These values are then re-scaled and shifted, resulting in an array of distances from the starting value.
Interesting, but not very practical for this challenge :D
[Answer]
## TI-BASIC, 15 bytes
```
Input N
sum(N/πtan⁻¹(tan(ΔList(πAns/N
```
Takes the list from `Ans` and the modulus from `Input`.
```
πAns/N ; Normalize the list to [0,π)
ΔList( ; Take differences, which are in the range (-π,π)
tan⁻¹(tan( ; Modulo, but shorter. Now elements are in (-π/2,π/2)
N/π ; Multiply by N/π. These are displacements at each step.
sum( ; Add up all the displacements
```
[Answer]
# Pyth, 29 bytes
```
+sm**._K-Fdvz>y.aKvz.:Q2-eQhQ
```
Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=%2Bsm**._K-Fdvz%3Ey.aKvz.%3AQ2-eQhQ&input=10%0A%5B5%2C2%2C8%2C9%2C5%5D&debug=0)
[Answer]
# CJam, 27 bytes
```
0q~:_2ewf{~\m1$2/:I+\,=I-+}
```
[Test it here.](http://cjam.aditsu.net/#code=0q~%3A_2ewf%7B~%5Cm1%242%2F%3AI%2B%5C%2C%3DI-%2B%7D&input=10%20%5B5%202%208%209%205%5D)
[Answer]
# [Pip](http://github.com/dloscutoff/pip), 39 bytes
```
Qn$+({a>n/2?a-na<-n/2?a+na}Mg@>1-g@<-1)
```
Requires the list of data as command-line arguments and the modulus on STDIN. If that's too much of a stretch, I have a version that takes two command-line args for 5 bytes more.
Explanation:
```
g is list of cmdline args (implicit)
Qn Read n from stdin
g@>1 All but the first of the cmdline args
-g@<-1 ...minus all but the last of the cmdline args
(i.e. a list of the differences of adjacent items)
{ }M ...to which, map the following function:
a>n/2?a-n If diff is too big, subtract n;
a<-n/2?a+n else if too small, add n;
a else return unchanged
$+( ) Sum; print (implicit)
```
And just to prove that this not-so-competitive score is more reflective on my golfing skills than my language, here's a port of Mauris's Python solution in **30 bytes**:
```
Qn$+({(n/2-$-a)%n-n/2}MgZg@>1)
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly)
**6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)**
```
Iæ%H}S
```
[Try it online!](http://jelly.tryitonline.net/#code=ScOmJUh9Uw&input=&args=NSwyLDgsOSw1+MTA)
### How it works
```
Iæ%H}S Main link. Left input: A (list). Right input: N (integer).
I Compute the increments (deltas of consecutive elements) of A.
H} Halve the right input (N).
æ% Mod the increments into (-N/2, N/2].
S Take the sum of all results.
```
] |
[Question]
[
This is a code-golf question. You need to take the contents of two separate files (i.txt and o.txt) and swap them. You can create a third file to help you with the process, but have your program delete it after the file contents are swapped. Renaming the files is now allowed again.
Programs must work for any file content.
Shortest code wins, all eligible submissions will be up-voted.
[Answer]
## zsh, 20 + 4 = 24
The script needs to be named `.txt`.
```
(mv [io]$0;>i$0)<o$0
```
or **14** with parameters:
```
(mv $@;>$1)<$2
```
[Answer]
# Python, 77
```
import os;t='.txt';r,i,o,x=[os.rename,'i'+t,'o'+t,'1'+t];r(i,x);r(o,i);r(x,o)
```
# Python, 65
```
import os;t='.txt'
for a,b in zip('iox','xio'):os.rename(a+t,b+t)
```
# Python, 63
```
import os;t='.txt'
for a,b in 'ix','oi','xo':os.rename(a+t,b+t)
```
# PHP, 68
```
<?$r=rename;$t='.txt';$r("i$t","x");$r("o$t","i$t");$r("x","o$t");?>
```
# Windows Batch File, 42
```
move i.txt x&move o.txt i.txt&move x o.txt
```
# Windows Batch File (args), 30
```
move %1 x&move %2 %1&move x %2
```
[Answer]
## PHP, 89
I thought I'd give it a shot.
```
<?php $f1='f1.txt';$f2='f2.txt';$ft='ft.txt';copy($f1,$ft);copy($f2,$f1);rename($ft,$f2);
```
Ungolfed version:
```
<?php
$f1 = 'f1.txt';
$f2 = 'f2.txt';
$ft = 'ft.txt';
copy($f1, $ft);
copy($f2, $f1);
rename($ft, $f2);
```
Apparently I took 2 answers of here and combined them.. oh well.
[Answer]
# VBA (148...132) and (126...110)
Renaming with a temp file t in the c:\ drive. Also first attempt at golf :S
```
Sub s():Set f=CreateObject("Scripting.FileSystemObject"):i="c:\i.txt":t="c:\t":f.MoveFile i,t:f.MoveFile "c:\o.txt",i:Kill t:End Sub
```
If scrrun.dll is referenced already, could cut it down a bit to 126...110.
```
Sub s():Set f=new FileSystemObject:i="c:\i.txt":t="c:\t":f.MoveFile i,t:f.MoveFile "c:\o.txt",i:Kill t:End Sub
```
[Answer]
## Ruby, 72 bytes
Wow! A Ruby code golf! I don't think that's ever been attempted before!
In all reality though, this required some nice Ruby shortcuts and a couple patterns which I found. It was my first golf ever and it was very fun to do. Without further ado, here's the golfed code:
```
3.times{|x|x*=2;t=".txt";a=([?i,?a,?o]*2);File.rename(a[x]+t,a[x+1]+t)}
```
And the ungolfed version
```
3.times do |x|
x = x * 2
t=".txt"
a=([?i,?a,?o]*2)
File.rename(a[x]+t, a[x+1]+t)}
end
```
The key factor in this is that the parameters passed to the `File.rename` are this, exactly:
```
File.rename "i.txt", "a.txt"
File.rename "o.txt", "i.txt"
File.rename "a.txt", "o.txt"
```
Hope this (doesn't) make sense!
[Answer]
# Powershell, ~~44~~ 49 bytes
```
$t='.txt'
ren i$t a$t -fo
ren o$t i$t
ren a$t o$t
```
where `ren` is alias for [Rename-Item](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/rename-item). The script uses and delete a third file `a.txt`.
[Answer]
# Two [bash](/questions/tagged/bash "show questions tagged 'bash'") based answers; 52 and 62 chars
## shell: diff + patch (+ tee + sed...) 52
Maybe not the shorter, but I find this fun (and there is no use of *temporary* file):
```
diff -u [io]*|tee >(patch -r -)|sed 1s/i/o/|patch -R
```
Where content is swapped and files are modified **in place**:
### Sample run
```
swapContent() { diff -u $1 $2|tee >(patch -r -)|sed 1s/$1/$2/|patch -R ;}
while read page file ;do man -Pcol\ -b $page >$file.txt;done <<<$'man i\nbash o'
printf "%s %8d %s\n" $(join -j 2 <(stat -c '%s %n' [io]*) <(md5sum [io]*))
swapContent [io]*
printf "%s %8d %s\n" $(join -j 2 <(stat -c '%s %n' [io]*) <(md5sum [io]*))
```
Could produce something like:
```
i.txt 46007 1da1f7533e0eab1e97cce97bb7ca1d3b
o.txt 321071 7dcd230890faf4ef848d4745eda14407
patching file o.txt
i.txt 321071 7dcd230890faf4ef848d4745eda14407
o.txt 46007 1da1f7533e0eab1e97cce97bb7ca1d3b
```
## use of xargs to *simplify* `mv` requests
Not as funny, but nice anyway.
```
set -- {i,o}.txt t&&eval 'xargs -n2 mv<<<"' \${1,3,2,1,3,2} \"
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E) `--no-lazy`, ~~39~~ ~~37~~ 35 bytes
*-2 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).*
```
'°ŽDÀøεS’.í¼t"’«`’File.‚™‚ˆ"ÿ,"ÿ’.E
```
[Try it online!](https://tio.run/##yy9OTMpM/f@oYd7hmYf7HjXsPLRJWf3w4kcNuw7vKKtMeNQw0y0zJ1XvUcPCw2s11A/v1zu89tCeEnUdIFNdEyir5wpSNAekSAEoW1JR8qhpzaGlRxccngZkHN0LMng5UAaoRqf2v/qhDUf3uhxuOLzj3NZgkG6waUpA1qHVSHbNetSyCEieblM6vF9HCaQZaM//Woi7yiqRFB6eoYjkKqiDMNxzeDLIURuQ3fL/v65uXr5uTmJVJQA "05AB1E – Try It Online") Link includes a header and footer to create the files and prove that it worked.
```
'°ŽDÀøεS’...’«`’...’.E # trimmed program
ε # for each in...
ø # all characters of...
'°Ž # "bio"...
ø # paired with corresponding characters of...
'°ŽD # "bio"...
À # rotated left one character...
.E # evaluate...
’...’ # "File.rename\"ÿ\",\"ÿ\""...
# (implicit) with the first ÿ replaced by...
` # second element of...
S # list of characters of...
# (implicit) current element...
# (implicit) with each element...
« # concatenated with...
’...’ # ".txt"...
# (implicit) with the second ÿ replaced by...
` # first element of...
S # list of characters of...
# (implicit) current element...
# (implicit) with each element...
« # concatenated with...
’...’ # ".txt"...
.E # as Elixir code
====================
File.rename # full program
File.rename # rename file with name argument 1 to argument 2
```
[Answer]
# Ruby
```
i1="i.txt"
i2="o.txt"
c1=IO.readlines(i2)
c2=IO.readlines(i1)
File.open(i1){|x|x.puts(c1)}
File.open(i2){|x|x.puts(c2)}
```
Shortened version:
```
a=["i.txt","o.txt"]
(0..1).each{|x|b[x]=IO.readlines(a[x])*"\n"}
a.reverse!
(0..1).each{|x|IO.write(a[x],b[x])}
```
Not the shortest, but very simple and easy to read. Also, no intermediate files, only RAM.
[Answer]
## Shell script, 24
Works in Bash and probably most shells. Pass with your two filenames as parameters.
```
mv $1 ੴ;mv $2 $1;mv ੴ $2
```
If you want fixed filenames then this will do it, for a 12 char penalty:
```
mv i.txt ੴ;mv o.txt i.txt;mv ੴ o.txt
```
[Answer]
**Python:**
```
import os
l,e='i_o'*2,'.txt'
for x,y in zip(l,l[1:])[::2]:
os.rename(x+e,y+e)
```
[Answer]
# Windows Batch File (48)
```
type i.txt>a&type o.txt>i.txt&type a>o.txt&del a
```
I forgot about the move command when I wrote this...
[Answer]
## C 162
Golfed: uses t.txt as tmp file and swaps names then removes t.txt.
```
#include <stdio.h>
#define R(x,y) rename(x,y)
#define X(x) remove(x)
int main(){char *i="i.txt",*o="o.txt",*t="t.txt";R(i,t);X(i);R(o,i);R(t,o);X(t);return 0;}
```
Edit: removed 2 spaces
[Answer]
**PHP** - 172
Golfed version of @EisaAdil's answer
```
$f1='file1.txt';$f2='file2.txt';$f1contents=file_get_contents($f1);$f2contents=file_get_contents($f2);file_put_contents($f1,$f2contents);file_put_contents($f2,$f1contents);
```
[Answer]
# Rebol - 46 (rename file) or 55 (r/w contents)
Rename file (using `t` as temporary file):
```
r: :rename
r i: %i.txt %t
r o: %o.txt i
r %t o
```
Read in then write out file contents:
```
a: read i: %i.txt
b: read o: %o.txt
write o a
write i b
```
[Answer]
# PHP, 45
```
<?php
copy('i','t');copy('o','i');rename('t','o');
```
Not very golfy but shortest PHP so far.
[Answer]
## Groovy - 99 chars
This is my attempt, with Groovy 2.2.1. I tried to do it without renaming:
```
f={new File(it+".txt")}
w={x,y->x.withWriter{it.write y}}
i=f "i"
o=f "o"
t=i.text
w i,o.text
w o,t
```
Ungolfed:
```
file = { new File(it+".txt") }
writeTextToFile = { x,y -> x.withWriter{it.write y} }
iFile = file("i")
oFile = file("o")
iText = iFile.text
writeTextToFile (iFile,oFile.text)
writeTextToFile (oFile,iText)
```
[Answer]
# C: 65 characters
```
#define r(a,b)rename(#a".txt",#b".txt");
main(){r(i,)r(o,i)r(,o)}
```
A quite simple solution in C that does the job. It uses a temporary name (`.txt`) for one of the files before giving it its proper new name.
Ungolfed (note how the syntax highlighting fails in the define, a bug has been uncovered!):
```
#include <stdio.h>
#define r(a, b) rename(#a ".txt", #b ".txt");
int main()
{
r(i, ) // rename("i.txt", ".txt");
r(o, i) // rename("o.txt", "i.txt");
r( , o) // rename( ".txt", "o.txt");
return 0;
}
```
[Answer]
# Perl, 120 bytes (Contents swapping without file renaming)
```
use open IO,':bytes';undef$/;open I,"<i.txt";$I=<I>;open I,"<o.txt";open O,">i.txt";print O<I>;open O,">o.txt";print O$I
```
The file contents is put into memory and written back to the other file. Thus `i.txt` and `o.txt` must fit into memory.
Since the file contents are actually exchanged, hard links are updated automatically, see AJManfield's [comment](https://codegolf.stackexchange.com/questions/16502/swap-contents-of-two-files#comment59884_16502).
**Ungolfed:**
```
use open IO => ':bytes'; # binmode, not needed for Unix, but needed for Windows
undef $/; # read whole file instead of lines
open I, "<i.txt"; # open i.txt for reading
$I = <I>; # read i.txt
open I, "<o.txt"; # open o.txt for reading
open O, ">i.txt"; # open i.txt for writing
print O <I>; # read o.txt and put the contents in i.txt
open O, ">o.txt"; # open o.txt for writing
print O $I; # write o.txt with contents of old i.txt
```
[Answer]
## Windows Batch, 39 bytes
```
ren i.txt x&ren o.txt i.txt&ren x o.txt
```
[Answer]
# [Lua](https://www.lua.org), ~~71~~ 70 bytes
```
_ENV=os t='.txt'i,o,r='i'..t,'o'..t,rename r(i,t)r(o,i)r(t,o)remove(t)
```
[Try it online!](https://tio.run/##tc6xCsJADAbg3afIlguk9wDCja6OrnLQDAF7Kbkovn0tVToIji75h//jJ7d7XYYBZtcWqfYuvodatlkaoOZ4BtLRpY6AFYnhh7RvScv1dL4U6xAFt1LZ2Asq5hyMtoVLq5OAJ@UgT8a63mAjl8kekoL@@uNhHf@oZgG7fMPlBQ "Lua – Try It Online")
Define `os`, the operating system library, as the global table so we can write `rename` and `remove` instead of `os.rename` and `os.remove`. (Incidentally this also means the one-letter variables are actually fields in the `os` table.) Make short alias for `os.rename` to save some space. Set up filename variables, using `'.txt'` as temporary file. Do the renaming and deleting.
[Answer]
# PHP, 52 bytes
[AsksAnyway´s php](https://codegolf.stackexchange.com/a/16793/55735) modernized & golfed:
```
($r=rename)(i.$e=".txt",x);$r(o.$e,i.$e);$r(x,o.$e);
```
Run with `php -nr '<code>'`.
[Answer]
# [Tcl](http://tcl.tk/), 122 bytes
```
set A [read [open i.txt]]
puts [set i [open i.txt w]] [read [open o.txt]]
puts [set o [open o.txt w]] $A
close $i
close $o
```
[Try it online!](https://tio.run/##jY/BCsIwDIbveYpQd/Yd5uykIC3owMPoQWaFwjDDVfTtqx0tzrnDcgrJ/@f745rWr4oDzyuOFkux59Abh1eLNXXmhnbtXg6fGrqH6zH7zNmG74REVaIAsaSAy@0gZ9C01JtwBSBBaQSlCKUJlEZQBWpJJaj6Qgl8oORY3835Mv5PR1Id9tPP9Y@e/vTT0BqzPDFtasgPBib5CQslKy6rY4hnWbw0EwnmLTRjian8Gw "Tcl – Try It Online")
---
# [Tcl](http://tcl.tk/), 169 bytes
```
set A [read [set i [open i.txt r]]]
set B [read [set o [open o.txt r]]]
close $i
close $o
puts [set i [open i.txt w]] $B
puts [set o [open o.txt w]] $A
close $i
close $o
```
[Try it online!](https://tio.run/##jY/BCoMwDIbveYrgPO8d1NUhjBY2YQfpYTgHBVlEO9zbO1sVq/NgTm2S///@6LzsDtGVBSlDhXFyYdAUGl8KM6qKN6qj/mpsJVQf3aDf972QnROOIsYEkj0FjJ/sugd5SU1hXAAmKDlQGqG0gpIDFSD21AQVM5SgM5QAs7p4PDEzn@WZtZTSJgndnWUquzNaqulBQ9INy1ZK9ENnvL6xHwf/fp0VeJzdMRI8ZTy9mWuUNzoN6WZOnwm2JbQhoUHS/QA "Tcl – Try It Online")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 66 bytes
```
a=FILENAME,b=!b?a:b{c[a]=c[a]$0RS}END{printf c[a]>b;printf c[b]>a}
```
[Try it online!](https://tio.run/##SyzP/v8/0dbN08fVz9HXVSfJVjHJPtEqqTo5OjHWFkSoGAQF17r6uVQXFGXmlaQpgMTskqzhvKRYu8Ta//8B "AWK – Try It Online")
Note: I provided a TIO line, but I have no idea how to make it work when the code needs to read from input files?
The rename approaches seem to be much shorter, but here's one in AWK that copies the data instead. At a high level, it takes a commandline like,
```
gawk '...code...' i.txt o.txt
```
which feeds both files into the program on STDIN. It uses the magic variable `FILENAME` to cache the contents of each one into a separate entry in an associative array. Then the `END` clause just overwrites each file with the content from the other one.
The "test" per line, which is always truthy, sets `a` to the current filename over and over. And it also ensures `b` is to the first filename seen.
```
a=FILENAME,b=!b?a:b
```
The code block executed per line, just appends the current line to the accumulated data for the current filename.
```
c[a]=c[a]$0RS
```
Then once all the lines from both files have been read, the `END` code block writes out the files with the content swapped.
```
printf c[a]>b;printf c[b]>a
```
[Answer]
# SmileBASIC, ~~36~~ 35 bytes
```
@L
RENAME@OI[2-I],@IO[I]I=I+1GOTO@L
```
] |
[Question]
[
## Background
Consider the following sequence ([A051935](https://oeis.org/A051935) in OEIS):
* Start with the term \$2\$.
* Find the lowest integer \$n\$ greater than \$2\$ such that \$2+n\$ is prime.
* Find the lowest integer \$n'\$ greater than \$n\$ such that \$2 + n + n'\$ is prime etc.
A more formal definition:
$$a\_n=\begin{cases}2 & \text{if }n=0 \\ \min\{x\in\Bbb{N}\mid x>a\_{n-1} \text{ and }\left(x+\sum\_{i=0}^{n-1}a\_i\right) \text{ is prime}\} & \text{otherwise}\end{cases}$$
The first few terms of the sequence are (please refer to these as test cases):
```
2, 3, 6, 8, 10, 12, 18, 20, 22, 26, 30, 34, 36, 42, 44, 46, 50, 52, 60, 66, 72, 74, ...
```
## Task
Your task is to generate this sequence in any of the following ways:
* Output its terms indefinitely.
* Given \$n\$, output \$a\_{n}\$ (\$n^{\text{th}}\$ term, \$0\$ or \$1\$ indexed).
* Given \$n\$, output \$\{a\_1, a\_2, \dots, a\_n\}\$ (first \$n\$ terms).
You can compete in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487) and can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) for *every language* wins.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
~l.<₁a₀ᵇ+ᵐṗᵐ∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy5Hz@ZRU2Pio6aGh1vbtR9unfBw53Qg@ahj@f//hqb/owA "Brachylog – Try It Online")
Output is the list of first **n** terms of the sequence.
```
?~l.<₁a₀ᵇ+ᵐṗᵐ∧ Full code (? at beginning is implicit)
?~l. Output is a list whose length is the input
<₁ Output is an increasing list
a₀ᵇ+ᵐ And the cumulative sum of the output
ṗᵐ Consists only of prime numbers
∧ No further constraints on output
Explanation for a₀ᵇ+ᵐ:
a₀ᵇ Get the list of all prefixes of the list
Is returned in increasing order of length
For eg. [2, 3, 6, 8] -> [[2], [2, 3], [2, 3, 6], [2, 3, 6, 8]]
+ᵐ Sum each inner list -> [2, 5, 11, 19]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~63~~ 62 bytes
```
n=f=a=b=1
while 1:
f*=n;n+=1;a+=1
if~f%n<a-b:print a;b=a;a=0
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P882zTbRNsnWkKs8IzMnVcHQikshTcs2zzpP29bQOhFIcClkptWlqebZJOomWRUUZeaVKCRaJ9kmWifaGvz/DwA "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 bytes
```
0Ḥ_ÆnɗСI
```
This is a full program that takes **n** as an argument and prints the first **n** terms of the sequence.
[Try it online!](https://tio.run/##ARsA5P9qZWxsef//MOG4pF/Dhm7Jl8OQwqFJ////MjI "Jelly – Try It Online")
### How it works
```
0Ḥ_ÆnɗСI Main link. Argument: n
0 Set the return value to 0.
С Accumulating iterate. When acting on a dyadic link d and called with
arguments x and y, the resulting quicklink executes
"x, y = d(x, y), x" n times, returning all intermediate values of x.
Initially, x = 0 and y = n.
ɗ Drei; combine the three links to the left into a dyadic chain.
Ḥ Unhalve; double the left argument.
_ Subtract the right argument.
Æn Compute the next prime.
This computes the partial sums of the sequence a, starting with 0.
I Increments; compute the forward differences.
```
[Answer]
# [05AB1E v2](https://github.com/Adriandmen/05AB1E), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2λλOD₁+ÅNα
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f6Nzuc7v9XR41NWofbvU7t/H/fwA "05AB1E – Try It Online")
This only works in the non-legacy version, the Elixir rewrite. Outputs an infinite stream of integers. There are some bugs with the prime test that have been fixed in the latest commits, but are not yet live on TIO. It does work locally, though. [Here](https://i.stack.imgur.com/CFV90.jpg) is a GIF of its execution on my machine, modified to output the first few terms rather than the whole stream.
### How it works
```
2λ
```
Defines a recursive infinite sequence with base case \$2\$. The `λ` structure is among 05AB1E's very cool new features. Briefly speaking, it takes a function \$a(n)\$, setting \$a(0)\$ to the integer argument given, in this case \$2\$.
```
λO
```
In this portion of code, `λ`'s role is different. Already being inside a recursive environment, it instead generates \$[a(0),a(1),\dots,a(n-1)]\$, the list of all previous results. Then, `O` sums them
up.
```
D₁+
```
Duplicate the sum for later use and add \$a(n-1)\$ to the second copy.
```
ÅN
```
Generates the lowest prime stricly greater than the above sum.
```
α
```
Finally, retrieve the absolute difference between the prime computed above and the first copy of the sum computed earlier (the sum of all previous iterations).
The stream is then implicitly printed to STDOUT indefinitely.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, 34 bytes
```
2.step{|i|$.+=p(i)if($.+i).prime?}
```
[Try it online!](https://tio.run/##KypNqvz/30ivuCS1oLoms0ZFT9u2QCNTMzNNA8jM1NQrKMrMTbWv/f//X35BSWZ@XvF/3SKwGAA "Ruby – Try It Online")
Outputs indefinitely.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~12~~ 11 bytes
```
.f&P-;Z=-;Z
```
[Try it online!](https://tio.run/##K6gsyfj/Xy9NLUDXOsoWiP//NzICAA "Pyth – Try It Online")
Saved 1 byte thanks to isaacg.
Generates the first `n` such numbers, using a 1 based index.
`.f` finds the first `k` integers that satisfy a particular criterion starting from zero. Here, the criterion is that the previous prime we calculated, `;`, plus the current number, `Z`, is prime (`P`). If it is, we also update the last calculated prime using the short-circuiting behaviour of the logical and function (`&`). Unfortunately `.f`'s default variable is `Z` which costs a byte in the update.
The trick that isaacg figured out was to store the negation of the last prime and test on that minus the current value. This is shorter in Pyth since the primality check is overloaded: on positive numbers it finds the prime factorisation while on negative numbers it determines if the positive value of the number is prime.
This more or less translates into:
```
to_find = input()
last_prime = 0
current = 0
results = []
while to_find > 0:
if is_prime( current + last_prime ):
results.append( current )
to_find -= 1
last_prime += current
current += 1
print results
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 45 bytes
```
2,{first (*+@_.sum).is-prime,@_[*-1]^..*}...*
```
[Try it online!](https://tio.run/##K0gtyjH7X5xYqaDx30inOi2zqLhEQUNL2yFer7g0V1Mvs1i3oCgzN1XHIT5aS9cwNk5PT6tWD0j814yOMzKK/Q8A "Perl 6 – Try It Online")
Returns a lazy list that generates the sequence with no end.
### Explanation:
This uses the Sequence operator `...` which defines the sequence as:
```
2, # The first element is 2
{ # The next element is:
first # The first value that:
(*+@_.sum).is-prime, # When added to the sum is a prime
@_[*-1]^..* # And is larger than the previous element
}
...* # And continue the sequence indefinitely
```
[Answer]
# JavaScript (ES6), 63 bytes
Returns the \$n^{th}\$ term, 1-indexed.
```
n=>(k=0,s=1,g=d=>s%d?g(d-1):d<2?--n?g(s-=k-(k=s)):s-k:g(s++))()
```
[Try it online!](https://tio.run/##DYpBCsMwDAS/oktBIlapA724UfKWEMemdZBLFPp916dlZvaz/lbbzvf3Yq1xb0mayoxFHs7EuyxRZrvFJWNkTyFO48KsHY2lcP8ZUTAuoZthIEJqqZ6oIOBfoDDB@OzbE2xVrR77/agZ1UFCJWp/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 21 bytes
```
O2hGq:"t0)yd0)+_Yqh]d
```
[Try it online!](https://tio.run/##y00syfn/398ow73QSqnEQLMyxUBTOz6yMCM25f9/cwA "MATL – Try It Online")
Output is the first **n** terms of the sequence.
### Explanation:
Constructs a list of primes (with an initial 0), and at the end finds the returns the differences between successive primes in the list.
```
% Implicit input, say n
O2h % Push P = [0, 2] on the stack
Gq:" % for loop: 1 to n-1
t0) % Take the last element of P
% Stack: [[0, 2], [2]] (in first iteration)
yd0) % Take the difference between the last
% two elements of P
% Stack: [[0, 2], [2], [2]]
+ % Add those up
% Stack: [[0, 2], [4]]
_Yq % Get the next prime higher than that sum
% Stack: [[0, 2], [5]]
h % Concatenate that to the list P
% Stack: [[0, 2, 5]]
] % End for loop
d % Get the differences between successive elements of
% the final list P
```
[Answer]
# [Haskell](https://www.haskell.org/), 67 bytes
```
(1#1)2 2
(p#n)s k|p`mod`n>0,n-s>k=k:(p#n)n(n-s)|w<-p*n=(w#(n+1))s k
```
[Try it online!](https://tio.run/##HYsxDsIwDAB3XmEpDA4QKemISF/C0Kg0UDl1LVKpS9@OKWx3Ot0rVRpK0RzvisEE20BzQDFsK9Am3TQ/Om79hV1tKdL1nxh3tdt6c3LiiKtBPgf7O3RKI0MEeY@8wBGWRAME73fM4PXT55KeVV0v8gU "Haskell – Try It Online")
`(1#1)2 2` is a [functions that takes no input](https://codegolf.meta.stackexchange.com/a/12945/64121) and outputs an infinite list.
---
old answer:
# [Haskell](https://www.haskell.org/), ~~88~~ ~~83~~ ~~78~~ 76 bytes
The primality test is from [this answer](https://codegolf.stackexchange.com/a/57704/64121) and improved by [Christian Sievers](https://codegolf.stackexchange.com/users/56725/christian-sievers) (-2 bytes).
-5 bytes thanks to [W W](https://codegolf.stackexchange.com/users/56656/w-w).
```
2#2
(p#s)n|n<1=p|w<-until(\m->mod(product[1..m-1])m>0)(+1)$s+p+1=(w-s)#w$n-1
```
[Try it online!](https://tio.run/##FccxDoMgFADQvacgkQFCIH6TbuINegJ1INhSUsAfwbB49tL0be9t8ucZQnN6aUM33Bh2macrjaDxqqM8U/GBLVFOcd8YHvt22jKDUlHCyuPUcyaA0yxQgGZVZt5VmiS0aHwimkSDD4KHT4XQf4gjc68U3Nf2ta9gXG7SIv4A "Haskell – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 12 bytes
```
0U[XN+DpiN,U
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fIDQ6wk/bpSDTTyf0/38A "05AB1E (legacy) – Try It Online")
**Explanation**
```
0U # initialize X as 0
[ # start an infinite loop
XN+ # add X to N (the current iteration number)
Dpi # if the sum is prime:
N, # print N
U # and store the sum in X
```
There are a couple of different 12-byte solutions possible.
This particular one could have been 10 bytes if we had a usable variable initialized as 0 (instead of 1 and 2).
[Answer]
# [Python 2](https://docs.python.org/2/), 119 bytes
```
f=lambda n,k=1,m=1:m%k*k>n or-~f(n,k+1,m*k*k)
def g(i):
r=[2]
for j in range(i):r+=[f(sum(r)+r[-1])-sum(r)]
return r
```
[Try it online!](https://tio.run/##LZDNboMwEITP8VPspRIOToX5SxqJvgjikDaQugkmWptDLn11OmBbsjTeGe0H83z5n8nmixmfE3tyLydw313vuf@e2ZnJPsxofKIzHLkMzeMyfl0vZNW90Wps9Hl8u@/vn5YmPvwNCeYp5nvMpLj2A90SI8@CuGnzTtAwMf2SscQXe@tXi9OmHRI3jwnLlNuD7uQhvBDn3s@M8OJ75x011IpdkinKpYLQiopN5IrqTRSKTpsoFelsUxVUiNdQwT1iQ3BPUMH9gApLNABFsPWKKIMEpIgBYMr4CQCVMQBSGQNAVXEDWFXMAlbHKWh1yOagHUMgB@1YStEJsfa0/rNCBW5@@LWyrYOz2D3ZWI9e17dc/gE "Python 2 – Try It Online")
Next Prime function f() taken from [this answer](https://codegolf.stackexchange.com/a/108539/73368).
Function g() takes a non-negative integer i and returns a list of all items in the sequence up to that index.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~99~~ 98 bytes
```
def f(n,s=2,v=2):
k=s-~v
while any(k%i<1for i in range(2,k)):k+=1
return n and f(n-1,k,k-s)or v
```
[Try it online!](https://tio.run/##XYzBDoIwEETv/Yq9GGhcErsUMES@xHgwEaSpKaQgxou/Xserh8m@md2d@b2OU5CUbv1AQx546YS3TnSryHdL8dkUvUb36Oka3rnfuZMZpkiOXKB4Dfc@F/Zat37fGUWxX58xUMDx7ddWGPbsi0XjZUtzdGGl85A7Tf8loi8qyzJFwlQy1UxHJnOAEBiwgAUsWJXg0kJgi8yCLbhCXsHXmDV8A24s/4pT@gI "Python 2 – Try It Online")
1 byte thx to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).
[Answer]
# [Haskell](https://www.haskell.org/), ~~101 99~~ 97 bytes
The function `l` takes no arguments and returns an infinite list. Not as short as the more direct [approach](https://codegolf.stackexchange.com/a/170793/24877) by @ovs (and I obviously stole some parts form their answer), but maybe still golfable?
Thanks @H.PWiz for -2 bytes!
```
import Data.List
p m=mod(product[1..m-1])m>0
l=2:[until(p.(+sum a))(+1)$last a+1|a<-tail$inits l]
```
[Try it online!](https://tio.run/##BcGxCsMgEADQPV9xg4MikVroUppOHfsHIcPRBHrkTkXPrf9u3/tiOw/mMUhKrgovVAxvajoVkEXybkvNe//oGkOQOW5OnpeJl@t97UmJbQnWty6AzlkfnWFsCujjDx@zIrGhRNqAtyFICRYolZKCAcXzgHgDHn8 "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~82~~ 80 bytes
```
s=p=2
i=input()
P=n=1
while i:
P*=n;n+=1
if P%n>0<n-s-p:p=n-s;s=n;i-=1
print p
```
[Try it online!](https://tio.run/##LU1LDoIwFNzPKV5ITPyEhBb8gXWHW1l4AcUaGs2jKSXK6bFEVzOZrx1807Ic6/auVRRFY6eskjDKsO39fIFKsRJ4N@alyeSgaqm44FXQyDyomvExOXDcxTa3KmDRBdvEwbbOsCc7hlH8@xfX6zBB3g0TEOmPrmm6xsRrbT2V51PpXOt@gZvT1@eYQEAiRYY1Nthihz1EEAWEhEghsi8 "Python 2 – Try It Online")
This outputs the nth number of the sequence (0-based). By moving the `print` in the loop, this can be modified to output the first `n` items at the same bytecount: [Try it online!](https://tio.run/##DcpNCoAgEEDh/ZxiNkE/CCmttOkMXqJwIKYhjej05vJ9PP1KusTVmknJAROLPqUfIJKQhTfxuSN7wDiSBJmaIR8YO9nmVUw26vVmKahBqXXIbWNDtla7/A "Python 2 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~100~~ 99 bytes
* Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
p(r,i,m,a,l){for(l=m=a=0;a-r;)m+=i=p(a++);while(r*!l)for(++i,l=a=2;a-m-i;)l=(m+i)%a++?l:0;r=r?i:2;}
```
[Try it online!](https://tio.run/##Jc3BCsIwDIDhV1FhkNgU5m4uhN37FmU6DaSzBMGD@Oyz4v3j/@d4m@dtq@CkVCiT4Xt5OJgUydJzjs5YgqhUyCEgv@5qV/Dj3vDnQlCyJocmS1RGEyhBsWt4srFnF590HPizlawrpH8@tXSKpzNjdV2fCxy6C@0OVCG1CTb9BQ "C (gcc) – Try It Online")
[Answer]
# PARI/GP 73 bytes
```
a(n)=v=[2];s=vecsum;while(n--,v=concat(v,nextprime(s(v)+v[#v]+1)-s(v)));v
```
1-indexed, output: first n terms
[Answer]
# Pyth, 13 bytes
```
I%sjs.BQ2 2\1.?0
```
Simply converts a given input to binary and prints the respective output whether the sum of 1's in the output list is even or not.
Made in about 5 seconds, and can probably be done in way fewer characters than I have, but hey, I tried.
[Answer]
# Japt, 17 bytes
Outputs the `n`th term, 0-indexed.
```
@_+T j}aXÄT±X}g2ì
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=QF8rVCBqfWFYxFSxWH1nMuw=&input=OA==)
] |
[Question]
[
The **optimal matrix** (for the rather narrow scope of this challenge) is obtained by "zipping" the elements from the corresponding rows and columns of a square matrix and getting the maximum of each pair.
For instance, given the following matrix:
```
4 5 6
1 7 2
7 3 0
```
You can combine it with its transpose to get: `[[[4,5,6],[4,1,7]],[[1,7,2],[5,7,3]],[[7,3,0],[6,2,0]]]`. If you zip each pair of lists, you obtain the following: `[[(4,4),(5,1),(6,7)],[(1,5),(7,7),(2,3)],[(7,6),(3,2),(0,0)]]`. The last step is to get the maximum of each pair to get the optimal matrix:
```
4 5 7
5 7 3
7 3 0
```
Your task is to output the optimal matrix of a square matrix given as input. The matrix will only contain integers. I/O can be done in any reasonable format. The shortest code in bytes (either in UTF-8 or in the language's custom encoding) wins!
### Tests
```
[[172,29],[29,0]] -> [[172,29],[29,0]]
[[4,5,6],[1,7,2],[7,3,0]] -> [[4,5,7],[5,7,3],[7,3,0]]
[[1,2,3],[1,2,3],[1,2,3]] -> [[1,2,3],[2,2,3],[3,3,3]]
[[4,5,-6],[0,8,-12],[-2,2,4]] -> [[4,5,-2],[5,8,2],[-2,2,4]]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
»Z
```
[Try it online!](https://tio.run/##y0rNyan8///Q7qj/h9sfNa1xB@KsRw1zDm07tO3//@joaENzIx0FI8tYHS4FhWggQ0dBwSAWyONSiI420VEw1VEwg8gZ6iiYA1VCOECWsQ5CIVAOaIoxVKGCDhIHKgNVqAAxUkEXaqiCgY6ChY6CriHUXF0jsHoFBZPY2FgA "Jelly – Try It Online")
### How it works
```
»Z Main link. Argument: M (integer matrix)
Z Zip the rows of M, transposing rows and columns.
» Take the maxima of all corresponding integers.
```
[Answer]
# [Haskell](https://www.haskell.org/), 40 bytes
```
z(z max)<*>foldr(z(:))e
e=[]:e
z=zipWith
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzv0qjSiE3sULTRssuLT8npUijSsNKUzOVK9U2OtYqlavKtiqzIDyzJON/bmJmnoKtQkFRZl6JgopCmkJ0tImOqY5ZrE60oY65jhGQNtcx1jGIjf3/LzktJzG9@L9uckEBAA "Haskell – Try It Online")
I would ungolf this as:
```
import Data.List
f m = zipWith (zipWith max) m (transpose m)
```
...which is so much more elegant.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~5~~ 4 bytes
Whoop, never got to use `‡` before (or `†`):
```
S‡▲T
```
[Try it online!](https://tio.run/##yygtzv7/P/hRw8JH0zaF/P//PzraRMdUR9csVifaQMdCR9fQCMjSNdIx0jGJjQUA "Husk – Try It Online")
### Explanation
```
S T -- apply the function to itself and itself transposed
‡▲ -- bi-vectorized maximum
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 13 bytes
```
@(A)max(A,A')
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQcNRMzexQsNRx1Fd83@agq1CYl6xNRdXmka0obmRgpGlNRArGMRqgkRMFEwVzKwVDBXMFYysgYQxTMJQwUjBGCSBoBA6dIFaDBQsFHQNgZp0gWYqmMRq/gcA)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
t!2$X>
```
[Try it online!](https://tio.run/##y00syfn/v0TRSCXC7v//aBMFUwUzawVDBXMFI2sgYaxgEAsA)
**Explanation:**
```
t % Duplicate the input.
! % Transpose the duplicate.
2$X> % Elementwise maximum of the two matrices.
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 3 bytes
Anonymous tacit prefix function.
```
⊢⌈⍉
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXYse9XQ86u0EchWMFYwf9W4xUTBVMFMwVDBXMAJiYwUDrjSFR20TH/VN9Qr291NQj442NDfSMbKM1Yk2stQxiI1Vx1BgomOqYwaUN9Qx1zEC0uY6xtgVGuoY6RiDFSLTOEzUBRlpoGOho2sIMlQX6AgdE6BiAA "APL (Dyalog Unicode) – Try It Online")
`⊢` argument
`⌈` ceiling'd with
`⍉` transposed argument
[Answer]
# JavaScript (ES6), 48 bytes
```
m=>m.map((r,y)=>r.map((v,x)=>v>(k=m[x][y])?v:k))
```
### Test cases
```
let f =
m=>m.map((r,y)=>r.map((v,x)=>v>(k=m[x][y])?v:k))
console.log(JSON.stringify(f([[172,29],[29,0]] ))) // -> [[172,29],[29,0]]
console.log(JSON.stringify(f([[4,5,6],[1,7,2],[7,3,0]] ))) // -> [[4,5,7],[5,7,3],[7,3,0]]
console.log(JSON.stringify(f([[1,2,3],[1,2,3],[1,2,3]] ))) // -> [[1,2,3],[2,2,3],[3,3,3]]
console.log(JSON.stringify(f([[4,5,-6],[0,8,-12],[-2,2,4]]))) // -> [[4,5,-2],[5,8,2],[-2,2,4]]
```
[Answer]
# [J](http://jsoftware.com/), 4 bytes
Tacit prefix function.
```
>.|:
```
[Try it online!](https://tio.run/##y/r/P83Wyk6vxup/anJGvkKagrGCsYqJgqmCmYKhgrmCERAbKxhwQSWNFIxUDM2BpCUIwYXx6gFJGgIFjRWQSHSd8WYKBgoWCvGGRgrxQOMVTP4DAA "J – Try It Online")
`>.` ceiling [of the argument] with
`|:` the transposed argument
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~12~~ ~~10~~ 8 bytes
Look, Ma, no transposing or zipping!
```
£XËwUgEY
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=o1jLd1VnRVk=&input=W1s0LDUsLTZdLFswLDgsLTEyXSxbLTIsMiw0XV0KLVE=)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 8 bytes
```
{_z..e>}
```
Anonymous block (function) that takes the input from the stack and replaces it by the output.
[**Try it online!**](https://tio.run/##S85KzP1fWPe/Or5KTy/VrvZ/XcH/6GgTBVMFs1iFaEMFcwUjIG2uYKxgEBsLAA "CJam – Try It Online") Or [**verify all test cases**](https://tio.run/##TYxBCoAgFAWv8jYtFf1a1qaLyCci2gRBbRO9umkUtJoHw7xlm/d8ppDDdEm5jjGnIzbZe@0INDA8DVBc6C1adGVoOFChg3mNBsE85s@vETVS6CF0zUT5hWXmGw).
### Explanation
```
{ } e# Define block
_ e# Duplicate
z e# Zip
. e# Apply next operator to the two arrays, item by item
e# (that is, to rows of the two matrices)
. e# Apply next operator to the two arrays, item by item
e# (that is, to numbers of the two rows)
e> e# Maximum of two numbers
```
[Answer]
# [R](https://www.r-project.org/), 23 bytes
```
function(A)pmax(A,t(A))
```
[Try it online!](https://tio.run/##K/qfpmD7P600L7kkMz9Pw1GzIDexQsNRpwTI1PyfppGSmZiuYQJkAgA "R – Try It Online")
This is equivalent to most other answers. However, R has two distinct `max` functions for the two common scenarios:
>
> `max` and `min` return the maximum or minimum of all the values present in their arguments, as integer if all are logical or integer, as double if all are numeric, and character otherwise.
>
>
> `pmax` and `pmin` take one or more vectors (or matrices) as arguments and return a single vector giving the ‘parallel’ maxima (or minima) of the vectors. The first element of the result is the maximum (minimum) of the first elements of all the arguments, the second element of the result is the maximum (minimum) of the second elements of all the arguments and so on. Shorter inputs (of non-zero length) are recycled if necessary.
>
>
>
[Answer]
# [Clean](https://clean.cs.ru.nl), 58 bytes
```
import StdEnv,StdLib
@l=zipWith(zipWith max)(transpose l)l
```
I don't think this needs an explanation.
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r0wHSPlkJnE55NhWZRaEZ5ZkaEBpoOIKTY2SosS84oL84lSFHM2c/8EliUCdtgoOCtHRJjqmOrpmsTrRBjoWOrqGRkCWrpGOkY5JbOz/f8lpOYnpxf91PX3@u1TmJeZmJkM4ENsA "Clean – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~79~~ 77 bytes
* Saved two bytes thanks to [Steadybox](https://codegolf.stackexchange.com/users/61405/steadybox); only taking in one matrix dimension parameter as all matrices in this challenge are square.
```
j,i;f(A,n)int*A;{for(j=0;j<n*n;j++)printf("%d,",A[A[j]>A[i=j/n+j%n*n]?j:i]);}
```
[Try it online!](https://tio.run/##bc7RCoIwGAXga3uKEIItj6SztFoWsx4iEC/CMDZoRdmV@Ow2lago2Haz75z/z91TnjeNguQFEdBU6nIseFVcbkTFHlcrPdZcOQ693sxXQezRETZEKlKVrUUqYzXRjhoZlW3UUmaU1835IDWh1cAaWCYzFGkWV37EwBbt8epuFKP8@ijvxLYp713SuilmCOEjAjM36HWC4Edvu1ajAny8rd7@0btXtxvCwxyuz@CajTBtE7s/if27vzP7743r5gk "C (gcc) – Try It Online")
Takes a flat integer array `A` and the matrix dimension `n` (as the matrix has to be square) as input. Outputs a flat integer array string representation to stdout.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes
A port of my [Pari/GP answer](https://codegolf.stackexchange.com/a/152474/9288).
```
(#+#+Abs[#-#])/2&
```
`` is [`\[Transpose]`](http://reference.wolfram.com/language/ref/character/Transpose.html).
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/BfQ1lb@X1/u7ZjUnG0si6IGaupb6T2P6AoM68kOi26utpEx1THrFan2lDHXMcISJvrGOsY1NbGxv4HAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/), 13 bytes
`max.` applies the function `max` elementwise to it's arugments.
```
a->max.(a,a')
```
[Try it online!](https://tio.run/##yyrNyUw0@5@mYKuQlJqemfc/UdcuN7FCTyNRJ1Fd839qXgpXSmZxQU5ipUaaRrSJgqmCmbWhgrmCkbW5grGCQaym5n8A "Julia 0.6 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
ø‚øεøεà
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8I5HDbMO7zi3FYwX/P8fHW2iY6qjaxarE22gY6Gja2gEZOka6RjpmMTGAgA "05AB1E – Try It Online")
**Explanation**
```
ø # transpose input matrix
‚ # pair with original matrix
ø # zip together
ε # apply on each sublist ([[row],[transposed row]])
ø # zip
ε # apply on each sublist (pair of elements)
à # extract greatest element
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
żZZṀ€$€
```
[Try it online!](https://tio.run/##y0rNyan8///onqiohzsbHjWtUQHi////R0eb6JjqmMXqRBvqmOsYAWlzHWMdg9hYAA "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
```
lambda k:[map(max,*c)for c in zip(k,zip(*k))]
```
[Try it online!](https://tio.run/##lZDLboMwEEX3/oqpu8HpECUmDQkSi35BN91RFpSYQnkY2U5fP09tlyhZRKq68chzfebO9fhlajnwqUqfp67oXw4FtEnWF2PQF5@4KFklFZTQDPDdjEGL7ly0jOWTEdpoSCHLsg3e4zbHbI0xcltjjHCV52i1NXKMvHRZveSo0GEr3GG4dmDIrbyZydhe9rbJ925YTrTsjqaRw4VpbGV7@slXTPlcIytdmnKP7fBPS@LSu6AIJ/fTV/j457ZmCYFRNYMB@lQLUEIfOwONpgi0lEqJ0iQUmgoqjzJI0/NM0WkB9EPJ4TWhqI0K5ldsqd6O2gTRlt3RJSXkFh4HAb1UAspalG0C/12y0Fooc20NQnwAMsd46LpfDw118S5gdOThhk4/ "Python 2 – Try It Online")
Thanks to totallyhuman for a few bytes saved.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 21 bytes
```
m->(m+m~+abs(m-m~))/2
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9X104jVzu3TjsxqVgjVze3TlNT3@h/QVFmXolGmka0iY6pjpm1oY65jpG1uY6xjkGspuZ/AA "Pari/GP – Try It Online")
[Answer]
# [Mathematica](https://www.wolfram.com/wolframscript/), 30 bytes
*-8 bytes thanks to Jonathan Frech.*
```
Map@Max/@t/@t@{#,t@#}&
t=#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zexwME3sULfoQSIHKqVdUoclGvVuEpsld/3t6v9DyjKzCuJTlNwUKiuNtEx1TGr1ak21DHXMQLS5jrGOga1tbH/AQ "Mathematica – Try It Online")
] |
[Question]
[
It's time for [another](https://codegolf.stackexchange.com/questions/197764/whats-the-mayan-date) Mesoamerican calendar! The [Xiuhnelpilli](https://en.wikipedia.org/wiki/Aztec_calendar#Xiuhmolpilli) was used by the Aztecs (more properly, the Mexica) to name their years. Each year has a number and a sign. Here's part of the cycle:
```
Input; Output
1089; 13 Calli
1090; 1 Tochtli
1091; 2 Acatl
1092; 3 Tecpatl
1093; 4 Calli
1094; 5 Tochtli
1095; 6 Acatl
1096; 7 Tecpatl
1097; 8 Calli
1098; 9 Tochtli
1099; 10 Acatl
1100; 11 Tecpatl
1101; 12 Calli
1102; 13 Tochtli
1103; 1 Acatl
1104; 2 Tecpatl
1105; 3 Calli
1106; 4 Tochtli
1107; 5 Acatl
1108; 6 Tecpatl
1109; 7 Calli
1110; 8 Tochtli
1111; 9 Acatl
1112; 10 Tecpatl
1113; 11 Calli
1114; 12 Tochtli
1115; 13 Acatl
1116; 1 Tecpatl
1117; 2 Calli
1118; 3 Tochtli
1119; 4 Acatl
1120; 5 Tecpatl
1121; 6 Calli
1122; 7 Tochtli
1123; 8 Acatl
1124; 9 Tecpatl
1125; 10 Calli
1126; 11 Tochtli
1127; 12 Acatl
1128; 13 Tecpatl
1129; 1 Calli
1130; 2 Tochtli
1131; 3 Acatl
1132; 4 Tecpatl
1133; 5 Calli
1134; 6 Tochtli
1135; 7 Acatl
1136; 8 Tecpatl
1137; 9 Calli
1138; 10 Tochtli
1139; 11 Acatl
1140; 12 Tecpatl
1141; 13 Calli
1142; 1 Tochtli
```
The pattern should be clear enough: the number is counting up to 13, and the sign goes Tochtli, Acatl, Tecpatl, Calli. After 52 years the pattern repeats itself.
**The program** will take as input an integer between 1064 (the year the Mexica left their mythological homeland of Aztlan) and 1521 (fall of Tenochtitlan to the Spaniards), inclusive, and output the corresponding year name. It can be a single string (in which case there needs to be a space between number and sign), or a tuple (e.g. `["2", "Calli"]`) of your preferred format. The sign name is always capitalised.
Handling years outside the specified range is not necessary. It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins!
**Test cases**
The entire example list above, plus:
```
Input; Output
1064; 1 Tecpatl
1521; 3 Calli
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~68~~ ~~62~~ 59 bytes
Saved ~~6~~ 9 bytes thanks to [my pronoun is monicareinstate](https://codegolf.stackexchange.com/users/36445/my-pronoun-is-monicareinstate)!!!
```
lambda n:((n+2)%13+1,"TCTAeaocclcaplhtaitlt l l i"[n%4::4])
```
[Try it online!](https://tio.run/##DcGxDsIgEADQ3a@4NGnCWQaxHSyJg/EXuqnDicWSnAchLHw99r1UyxZlbP76bEy/94dArFIynLE342B0t9yX20rROXaUeCsUChfgfege0k/WTi9sPmaoEAQyyXdV5nSZtdmhPUDKQYqq@uhVRWx/ "Python 3 – Try It Online")
[Answer]
# dc, ~~63~~ 62 characters
```
[Tecpatl]0:y[Calli]1:y[Tochtli]2:y[Acatl]3:y?d2+13%1+n32P4%;yp
```
Explained:
```
[Tecpatl] 0 :y # store the string "Tecpatl" in array y at index 0
[Calli] 1 :y # store the string "Calli" in array y at index 1
[Tochtli] 2 :y # store the string "Tochtli" in array y at index 2
[Acatl] 3 :y # store the string "Acatl" in array y at index 3
? # read input input
d # duplicate it to keep a copy for later
2+ 13% 1+ n # the usual formula: (year + 2) % 13 + 1, then print it
32 P # print a space
4 % # use the left copy of input for formula: year % 4
;y p # get the value from array y at the given index, then print it
```
Sample run:
```
bash-5.0$ dc -e '[Tecpatl]0:y[Calli]1:y[Tochtli]2:y[Acatl]3:y?d2+13%1+n[ ]n4%;yp' <<< 1111
9 Acatl
```
[Try it online!](https://tio.run/##S0n@/z86JDW5ILEkJ9bAqjLaOTEnJzPWEMgKyU/OKAGyjYBsx2SQvLFVpX2Kkbahsaqhdp6xUYCJqnVlwf//hkAAAA "dc – Try It Online") / [Try all test cases online!](https://tio.run/##lZRdb9MwFIavm19honbZNFXysfO5NYIJccEVCHEXIhQST62IkqjNJKrBby@2j7vmBLjgJrHe2o/tR2/zrTpsT42q22qv2PqBjeowfq2rg8qvvUURAI/DoMwDYJ9VPVRjG3gYp5mNJXtbte0uwDDjbm5fb8dLCiYV7KG26zETJpMXKqbSpCFl2v2jOTMyaUyZscmSOTMxaUqZqcmyOROvxKdQ4HgloFTg9k4gpljgwjkhXOASrRBsiE5m1AitEGiMTmbMBK0QZopOZswMrUyZwNEJZQKglSkThHNCoSCdFUINnZMZNnJWCDeetQrTBK0QauqaQqEZWpkyBXdNIUwBaGXKFMI1hTCFRCuEGbqmUGbkrBBofG4KpSbOCsGm56ZQLjaQYCV3TSFUCWhlCpXCNYUwpUQrhBm6plBmhFYIM3ZNocwErRBmem4KhWbOypQa8nNTCDaEP78pEIrZN8XGkQDyV7nxvGG/68ZHFvxkqzXwA/vLW@jnly5gwftueBr1@5M6PLVm8O7HoOpRNXr44bve47Hfs52ZpJ/MXz6/evkuFm/KX/49a3pvsberc395zZqarRULToW7UcnvjoU9Wwl65A5fCj22Ikp5d3zdiFuQK7jtpPgYru6Pw2kRsM1moze0e/vsxtfX/Y@LvSz0l3g4M3q@nB1/1hdg5tBFMZmX5/@aWpbs6oqpettbOeZQTd@p028 "Bash – Try It Online")
[Answer]
# perl -pl, 61 bytes
```
$_=(($_+3)%13||13).$".(qw[Tecpatl Calli Tochtli Acatl])[$_%4]
```
[Try it online!](https://tio.run/##Fc3BCoJQEEbhfU8hYaBEcWdGSxctoldwJyIiQcIlrYQ2Pns3z@b8MPAx0/3t8xDi9pIkcbu3dCe2LGLpMd4ek9e3ru791M0@unXeD1E19o953Wu/3pq0jttd1oQgrig34kpHhCgxkpGcnMiZFGQV4hwRosRIRnJyImdSEIQgBCEaUYhABCIQgQhEIApRiPJEEYpQhCIUoQhFGMIQhjCEZb9xmofx@QmHyf8B)
Nothing special going on, modding the year twice, with some aligning. `$"` is a variable which by default holds a space.
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 344 bytes
```
[S S S N
_Push_0][S N
S _Duplicate_0][T N
T T _Read_STDIN_as_integer][T T T _Retrieve][S N
S _Duplicate_input][S S S T S N
_Push_2][T S S S _Add][S S S T T S T N
_Push_13][T S T T _Modulo][S S S T N
_Push_1][T S S S _Add][T N
S T _Print_as_integer][S S S T S S T N
_Push_9_tab][T N
S S _Print_as_character][S S S T S S N
_Push_4][T S T T _Modulo][S N
S _Duplicate][N
T S S N
_If_0_Jump_to_Label_0][S S S T N
_Push_1][T S S T _Subtract][S N
S _Duplicate][N
T S T N
_If_0_Jump_to_Label_1][S S S T N
_Push_1][T S S T _Subtract][N
T s S S N
_If_0_Jump_to_Label_2][S S S T T N
_Push_3_l][S S S T S T T N
_Push_11_t][S S T T S S S N
_Push_-8_a][S S T T T S N
_Push_-6_c][S S T T S T S S S N
_Push_-40_A][N
S S N
_Create_Label_PRINT_LOOP][S S S T T S T S S T N
_Push_105][T S S S _Add][T N
S S _Print_as_character][N
S N
N
_Jump_to_Label_PRINT_LOOP][N
S S S N
_Create_Label_0][S N
N
_Discard][S S S T T N
_Push_3_l][S S S T S T T N
_Push_11_t][S S T T S S S N
_Push_-8_a][S S S T T T N
_Push_7_p][S S T T T S N
_Push_-6_c][S S T T S S N
_Push_-4_e][S S T T S T S T N
_Push_-21_T][N
S N
N
_Jump_to_Label_PRINT_LOOP][N
S S T N
_Create_Label_1][S N
N
_Discard][S S S N
_Push_0_i][S S S T T N
_Push_3_l][S N
S _Duplicate_3_l][S S T T S S S N
_Push_-8_a][S S T T S S T T S N
_Push_-38_C][N
S N
N
_Jump_to_Label_PRINT_LOOP][N
S S S S N
_Create_Label_2][S S S N
_Push_0_i][S S S T T N
_Push_3_l][S S S T S T T N
_Push_11_t][S S T T N
_Push_-1_h][S S T T T S N
_Push_-6_c][S S S T T S N
_Push_6_o][S S T T S T S T N
_Push_-21_T][N
S N
N
_Jump_to_Label_PRINT_LOOP]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[Try it online](https://tio.run/##dU9BCsMwDDvbr9AT2tv2nFIC7W2wQZ@f2rLddLA5ECWyLCXHtn/a@7WsrXcAaktUvOxkZSBgGWMdB/DgOwi8a4iA0CjntLRJyCDowGuQgZJs5numE1pSyC3cPb1F/OfkVl@Gl69ozkvOl0dGlZLfqSjo72ePCNyeHhG9z9PjeQI) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
```
Integer year = STDIN as integer
Print (year+2) modulo-13 + 1 as integer to STDOUT
Print '\t' as character to STDOUT
Integer temp = year modulo-4
If(temp == 0):
Push the codepoints of "ltapceT" minus 105 to the stack
If(temp-1 == 0):
Push the codepoints of "illaC" minus 105 to the stack
If(temp-2 == 0):
Push the codepoints of "ilthcoT" minus 105 to the stack
Else:
Push the codepoints of "ltacA" minus 105 to the stack
Start PRINT_LOOP:
Add 105 to the top integer on the stack
Print this integer as character with this codepoint to STDOUT
Go to the next iteration of PRINT_LOOP
```
Uses [this Whitespace tip of mine](https://codegolf.stackexchange.com/a/158232/52210) to print the output, which will exit the program with an error as soon as we're done with printing and the stack is empty. The optimal constant `105` is generated by [this Java program](https://tio.run/##fZJNa9wwEIbv@RViThLamC20h9grwib0YOjmULtJIYQgO8quUq3sSuOFpexvd@TY3o8m5CKheWcezdeL3Mjzl6c/bVsa6T1ZSG3/nRFSN4XRJfEoMVybSj@RdZBohk7b5f0DkaxzI6Q3EKd8Y5AIIu@nD8mboi0Sv5bGKN8JqUW1VC5azH8/3s5//Po@Iam4SI4ho/fPEQbQ68@Vox1OizTRsy/fponmfEjgkIIAmOCkFmNUH1dsUZEi7hOMlgqvgsFTtg8nBEWA59XdSgellqW60la6bc@lxblmyd7XCYqR@ttI42nNLiG7ySBGxt3BpRY4PnbDrZ@pi4yyS1xRRmb7So@SeFf8EfGojQfMQU6DXZ9@2Z/Z1qNaR1WDUR1qQWMp9OEC@AjlkITGAk85kJgA/6wXKRu@/Z9MT9N/89qdhWPYoGFGn7G7AduhIRvpwlQgy4BTK8T0EiC2s3DlEEMG7HQtynhcLqxOkJ3KFhJXkSw8tYx9NH/kopx9vQijDOx82J2@f05h42zwgBvoK9q1bZurspZorkPBOq/KFRo9L4PhFQ).
[Answer]
# jq (with `-r` switch), 57 characters
```
"\((.+2)%13+1) "+("Tecpatl Calli Tochtli Acatl"/" ")[.%4]
```
Sample run:
```
bash-5.0$ jq -r '"\((.+2)%13+1) "+("Tecpatl Calli Tochtli Acatl"/" ")[.%4]' <<< 1111
9 Acatl
```
[Try it online!](https://tio.run/##yyr8/18pRkNDT9tIU9XQWNtQU0FJW0MpJDW5ILEkR8E5MScnUyEkPzmjBEg7JgPFlPSVFJQ0o/VUTWL//zcEgn/5BSWZ@XnF/3V1ixLLdfNLSwpKSwA "jq – Try It Online") / [Try all test cases online!](https://tio.run/##lZRNj9MwEIbPza8YrHadqurisfMpWokV4sAJCXHLRiikWbVQtSXNSkgLv70bZ5xtJsCBSxK9dR57Hr3N1@K8vWyqcl/UFSzvoKnOzZeyOFdr35tkElUUyHwtET5X5alo9tKjOEm72MC7Yr/fSQpT5dYey21zTdGmGu7K7n3KtM3MlUqpsWnAmd3@4ZgZ2jTizMhm8ZgZ2zThzMRm6ZhJI6khFBWNhJyKqpsJ9RCLSjsnjIvKkBWGDcjJiBqSFQaNyMmIGZMVxkzIyYiZkpUhExU54UxEsjJkonZOOBSNs8KogXMywobOCuNGo1ZRGpMVRk1cUzg0JStDplauKYypkawMmVq7pjCmNmSFMQPXFM4MnRUGjfqmcGrsrDBs0jeFc6mBDGuUawqjGiQrQ6jRrimMaQxZYczANYUzQ7LCmJFrCmfGZIUxk74pHJo6K0NqoPqmMGyAf35TMNCjb0oXhxrZX2Xuead6d2geQP6C2RLVGf5y1@31/iBBfjicHpv2/qk6P@7tw/ufp6psqk37@PF7u8fDsYadXdReQUyfXr18F7O3@W/xBjZHb1J3b6/F1IdvP2BZg7yIe9@/Xej5DM0C5yAWvnAz0kn7MUiHeC1AzLPbWZBfJhJWq1W7V7etgLloJ/2PmV5eFFM6l316uh6bfm7PDva8WTZYt17/a2mew80NVOX22Hmxh9ocD9XlGQ "Bash – Try It Online")
[Answer]
# Java 8, ~~63~~ 62 bytes
```
y->1-~-~y%13+" "+"Tecpatl Calli Tochtli Acatl".split(" ")[y%4]
```
-1 byte thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##LdFPa8IwGMfx@17FQ0FocS19kvqfDcbO8zJv4iGLdYuLaWmjo4i@9S4/9fItTfsJD8lenVS63/722qq2pQ9l3PmJyDhfNjulS1rilejTN8Z9k47DF@qSRVi8PIW0XnmjaUmOXqjv0ldOr@m1G7AcRhQNo1Wpa@UtvStrDa0q/ePD802HtShra2t8HP5L1t2g2PQL7Fgfv2zY8bHxqTJbOoSp4vsE6w2p5D7Srmru05SqoTm58g9jrzdnzqezZ85nOcKIQCRSICNkjEyQKRIE5znCiEAkUiAjZIxMkCkCwRAMwRAMwRAMwRAMwRAMISAEhIAQEAJCQAgIASEgBISEkBASQkLI4pLcDiHcTNf68pBVR5/V4YS8dTFOZBjNw/m7TN/ekseNXfp/)
**Explanation:**
```
y-> // Method with integer parameter and String return-type
1- // Decrease 1 by:
~-~y // (-y-2)
%13 // Modulo-13
+" " // Append a space
+"Tecpatl Calli Tochtli Acatl".split(" ")
// Split these four words as array
[y%4] // And take the (0-based) year-modulo-4'th value
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ì13%>.•19ŠSBÿ®Ï¿¾Ñλ1Ï7qι•#™Iè‚
```
[Try it online](https://tio.run/##AUAAv/9vc2FiaWX//8OMMTMlPi7igKIxOcWgU0LDv8Kuw4/Cv8K@w5HOuzHDjzdxzrnigKIj4oSiScOo4oCa//8xMDg5) or [verify all test cases](https://tio.run/##Fc2/asJQGIbxWwlHuoVy3u/E/FkUeguOpUMLDp2KCEK2DOIkSDt2KpmcuovQQA6uXkRuJM2zPHzw8eP92L6@va/HXb10yXD4StyyHuNR4WHxODStqtvP6il2/W889V3/Fz/vV8VTsblfpu9s2Ld1PA/N95iOz/JllcpXnogYCSQjc5KTgpRkEvKeiBgJJCNzkpOClAQhhJS6Kea4McIII4wwwghjGGPFWDGEIQxhCEMYwhABERABERAhe/kH).
**Explanation:**
```
Ì # Increase the (implicit) input by 2
13% # Take modulo-13 on that
> # And increase it by 1
.•19ŠSBÿ®Ï¿¾Ñλ1Ï7qι•
# Push compressed string "tecpatl calli tochtli acatl"
# # Split it on spaces: ["tecpatl","calli","tochtli","acatl"]
™ # Titlecase each: ["Tecpatl","Calli","Tochtli","Acatl"]
Iè # Index the input into it (0-based and with automatic wraparound)
‚ # Pair the two together
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•19ŠSBÿ®Ï¿¾Ñλ1Ï7qι•` is `"tecpatl calli tochtli acatl"`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 36 bytes
```
+3ịⱮ13R,“©ȥƒị Œñ⁾<ŻĠ)?ỵ%uxÐZỵȯẏ1»Ḳ¤¤
```
**[Try it online!](https://tio.run/##AVMArP9qZWxsef//KzPhu4visa4xM1Is4oCcwqnIpcaS4buLIMWSw7Higb48xbvEoCk/4bu1JXV4w5Ba4bu1yK/huo8xwrvhuLLCpMKk/8OHS///MTUyMQ "Jelly – Try It Online")**
### How?
```
+3ịⱮ13R,“...»Ḳ¤¤ - Link: integer, Y
+3 - add three (to Y)
¤ - nilad followed by link(s) as a nilad:
13R - range(13) = [1,2,3,4,5,6,7,8,9,10,11,12,13]
¤ - nilad followed by link(s) as a nilad:
“...» - compressed string = "Tochtli Acatl Tecpatl Calli"
Ḳ - split at spaces = ["Tochtli","Acatl","Tecpatl","Calli"]
, - pair these together = [[1,2,3,4,5,6,7,8,9,10,11,12,13],["Tochtli","Acatl","Tecpatl","Calli"]]
Ɱ - map accross (these two lists) with:
ị - index into (1-based & modular)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~55~~ 54 bytes[SBCS](https://en.wikipedia.org/wiki/SBCS)
```
{((4 7⍴'TecpatlCalli TochtliAcatl ')⌷⍨4|⍵),1+13|2+⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp7/Co7YJCgb/qzU01ENSkwsSS3LUFdSdE3NyMoF0SH5yRgmY5ZgMktF81LP9Ue8Kk5pHvVs1dQy1DY1rjLSB7Nr/aWBzHvX2PepqPrTe@FHbRKDpxUXJQLIkI7P4P1Ag7dAKBUMDC0ughs2GhiZGuiAOVxpQzMwERJkaGQIA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 100 bytes
```
&:2+67+%1+.4%:#v_"ltapceT",,v
<"Calli"_v#!-1:<@,,,,, < <
>2`!#v_"ltacA"^
^ ,,"Tochtli"<
```
[Try it online!](https://tio.run/##S0pNK81LT/3/X83KSNvMXFvVUFvPRNVKuSxeKacksSA5NURJR6eMy0bJOTEnJ1MpvkxZUdfQysZBBwQUbBSAwIZLAQbsjBIUoVqTHZXiuOIUFHR0lELykzNKgJpt/v83NLA0AgA "Befunge-93 – Try It Online")
Reads the year from input, and duplicates it. Adds 2, mods it with 13, adds 1 to the result and prints it. Then mods the year with 4, and using a series if if statements, selects the right name to print.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~87~~ \$\cdots\$ ~~70~~ 69 bytes
Saved 2 bytes thanks to [my pronoun is monicareinstate](https://codegolf.stackexchange.com/users/36445/my-pronoun-is-monicareinstate)!!!
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
f(n){printf("%d %.7s",1-~-~n%13,"TecpatlCalli TochtliAcatl"+n%4*7);}
```
[Try it online!](https://tio.run/##TY1BCsIwFET3PcUQCCS2EYNClaggXqFLNyWamhLTUrsr7dVjBCt9q/kzwx8tKq1DMMzzoe2s7w0j9A66zt8kk2ISk6dym5Hioduyd9fSOQsUjX72zl50tEjq6W6VczWGV2k94xgSREzTgcWHqHGC3OwPKqojZEQhTeu592WxLM4gGWqu/qFhy2uu3jz5uWMyhg8 "C (gcc) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 43 bytes
Straightforward implementation. Takes a number like 1090, returns boxed tuple [1|Tochtli].
```
(1+13|2+]);Tecpatl`Calli`Tochtli`Acatl{~4|]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NQy1DY1rjLRjNa1DUpMLEktyEpwTc3IyE0LykzNKgLRjMlCsus6kJva/5n@NaOs0TSUDBR09BQ1DAwtL7Uw9EwNNAA "J – Try It Online")
### How it works
```
(1+13|2+]);Tecpatl`Calli`Tochtli`Acatl{~4|]
4|] x mod 4
Tecpatl`Calli`Tochtli`Acatl{~ select from boxes
(1+13|2+]) ((x + 2) mod 4) + 1
; join left & right side
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
NθI⊕﹪⁺²θ¹³ §⪪”(0«βxo%↔W^⊘S≧L≔Z⮌⍘|Nº” θ
```
[Try it online!](https://tio.run/##PYyxCsMgGIT3PoVk@gULTbu0ZAqZHFoCzQtYFSL8UWN@S9/emqG95Y47vtOzSjooLEX6mOmRl5dNsPLuMCbnCQa1EUivk12sJ2vgHkzGACPmDc6CrVyw9sKrfkTDmn/uSXpjP/CM6OoyWR0VIRsUomNT0DNV73XtGsF2cD/kXSnt6Xorxzd@AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθI⊕﹪⁺²θ¹³
```
Input the year, add 2, reduce modulo 13, add 1, and print as a string, followed by a space.
```
§⪪”(0«βxo%↔W^⊘S≧L≔Z⮌⍘|Nº” θ
```
Split the compressed string `Tecpatl Calli Tochtli Acatl` on spaces and print the entry cyclically indexed using the year.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 54 bytes
```
->y{[(y+2)%13+1,%w[Tecpatl Calli Tochtli Acatl][y%4]]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf166yOlqjUttIU9XQWNtQR7U8OiQ1uSCxJEfBOTEnJ1MhJD85owRIOyYDxWKjK1VNYmNr/xcopEUbGpiZxHKBWaZGhrH/AQ "Ruby – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 41 bytes
```
(h%+2Q13@c." t£>Ì<ëWȶAdh|Å],%œ¯s")%Q4
```
[Try it online!](https://tio.run/##AT0Awv9weXRo//8oaCUrMlExM0BjLiIgdBTCoz7DjDzDq1fDiMK2QWRofMOFXSwlE8Kcwq9zDiIpJVE0//8xNTIx "Pyth – Try It Online")
The number is calculated with `1+((x+2)%13))`, x being the input.
The sign is retrieved by indexing into a packed string, split on whitespace.
Oddly enough, using repeated indexing for the string (like in other answers) yielded the same bytecount for me.
[Answer]
# JavaScript, ~~58~~ 57 bytes
-1 byte using the numerical method from @ceilingcat used in [Kevin Cruijssen's Java answer](https://codegolf.stackexchange.com/a/205779/41938)
```
n=>[1-~-~n%13,["Tecpatl","Calli","Tochtli","Acatl"][n%4]]
```
[Try it online!](https://tio.run/##HclPC8IgGIDx@z7FizCYOEOrQ/8Moq@w2/AgNpchvsONXaJ9dVudfg88LzOb0SY/TDzio8tO5aiureQLX2Ipd3VLms4OZgqkJncTgl9t0D6nf93s7@g2lnuts8ME1WwSeCXF4XgGf5FbIVYZo/AuACzGEUO3CdhXnpETEOYqT2nxyV8 "JavaScript (Node.js) – Try It Online")
It's been a long time since I got to a question fast enough to post a Javascript answer. (July 15, 2017 appears to have been my last for one that wasn't a king of the hill challenge.)
Pretty straightforward, get the right number with some ~~basic~~ modular arithmetic and get the sign with some array indexing mod 4.
[Answer]
# [PHP](https://php.net/), 69 bytes
```
fn($n)=>(($n+2)%13+1).' '.['Tecpatl','Calli','Tochtli','Acatl'][$n%4]
```
[Try it online!](https://tio.run/##HY1BCsMgFET3nuITDCoWqU0LAWNL6RWyS7MIEjEgKiW70rPb387mzTADU0Kpw62EAtTb6hOnSdgrR8iTaHUntVAMmJrYuLqy7JEd2GOJcUOO2YX97@7u18wTTe15rob4/OJ0Awv62PcGpMQwgNbdxYB4E0CtLmT8xJkABc0zNYZ86hc "PHP – Try It Online")
Just a port of Abigail's perl answer using Arnauld's edit suggestion, i fear.. but I had to, it's a 69
[Answer]
# [Kotlin](https://kotlinlang.org), 72 bytes
```
fun f(x:Int)=(x+2)%13+1 to "Tecpatl Calli Tochtli Acatl".split(" ")[x%4]
```
[Try it online!](https://tio.run/##HczBCoJAFEbhdT7Fz6BwL4I0Zi2EFtGqvbtoIdLQxemO2ASC@OwmbQ98pw/Ri66r@yocTfVNI59pykvO7CG3iAGmeXZDGz2urfeCJnSvzeDSbc0Un8FLJAPD9ymrHv/RuxUlxpzsXBhBAlHY/akqCnssLWMYRaNXMqnUSGdHwovhZFl/ "Kotlin – Try It Online")
] |
[Question]
[
# Introduction
The EKG sequence begins with 1 and 2, then the rule is that the next term is the smallest positive integer not already in the sequence and whose common factor with the last term is greater than 1 (they are not coprimes).
The first terms are:
>
> 1, 2, 4, 6, 3, 9, 12, 8, 10, 5, 15, ...
>
>
>
It's called EKG because the graph of its terms is quite similar to an EKG.
It's [sequence A064413 in the OEIS](https://oeis.org/A064413).
# Challenge
You have to write a function which takes an integer *n* as input and outputs how many of the *n* first terms of the sequence are greater than *n*.
As the sequence's rule begins with the third term, the input integer has to be greater or equal to 3. For example, given input `10` the output is `1` because the 7th term is `12` and none of the other first ten terms exceed 10.
# Test cases
>
> 3 -> 1
>
>
> 10 -> 1
>
>
> 100 -> 9
>
>
> 1000 -> 70
>
>
>
# Rules
* For integers lower than 3, the function may output 0 or an error code.
* No other particular rules except: it's code golf, the shorter the better!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ ~~19~~ 18 bytes
```
S‘gṪ’ɗƇḟ¹Ṃṭ
1Ç¡>¹S
```
This is a full program.
[Try it online!](https://tio.run/##ATEAzv9qZWxsef//U@KAmGfhuarigJnJl8aH4bifwrnhuYLhua0KMcOHwqE@wrlT////MTAw "Jelly – Try It Online")
### How it works
```
1Ç¡>¹S Main link. Argument: n (integer)
1 Set the return value to 1.
Ç¡ Call the helper link n times.
>¹ Compare the elements of the result with n.
S Take the sum, counting elements larger than n.
S‘gṪ’ɗƇḟ¹Ṃṭ Helper link. Argument: A (array or 1)
S Take the sum of A.
‘ Increment; add 1.
ɗƇ Drei comb; keep only elements k of [1, ..., sum(A)+1] for which the
three links to the left return a truthy value.
g Take the GCD of k and all elements of A.
Ṫ Tail; extract the last GCD.
’ Decrement the result, mapping 1 to 0.
ḟ¹ Filterfalse; remove the elements that occur in A.
Ṃ Take the minimum.
ṭ Tack; append the minimum to A.
```
Note that the generated sequence is \$[1, \mathbf{0}, 2, 4, 6, 3, 9, 12, 8, 10, 5, 15, \dots]\$. Since calling the helper link \$n\$ times generates a sequence of length \$n + 1\$, the \$0\$ is practically ignored.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~66~~ ~~63~~ ~~59~~ 58 bytes
*-4 bytes thanks to Jo King*
```
{sum (1,2,{+(1...all *gcd@_[*-1]>1,*∉@_)}...*)[^$_]X>$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0V0HDUMdIp1pbw1BPTy8xJ0dBKz05xSE@WkvXMNbOUEfrUUenQ7xmLVBSSzM6TiU@NsJOJb72f3FipUKahkq8pkJafpGCsY6CoQEIG/wHAA "Perl 6 – Try It Online")
Too slow on TIO for n = 1000.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
#>¹↑¡§ḟȯ←⌋→`-Nḣ2
```
[Try it online!](https://tio.run/##AS0A0v9odXNr//8jPsK54oaRwqHCp@G4n8iv4oaQ4oyL4oaSYC1O4bijMv///zEwMDA "Husk – Try It Online")
## Explanation
```
#>¹↑¡§ḟȯ←⌋→`-Nḣ2 Implicit input, say n=10
ḣ2 Range to 2: [1,2]
¡ Construct an infinite list, adding new elements using this function:
Argument is list of numbers found so far, say L=[1,2,4]
N Natural numbers: [1,2,3,4,5,6,7...
`- Remove elements of L: K=[3,5,6,7...
ḟ Find first element of K that satisfies this:
Argument is a number in K, say 6
§ → Last element of L: 4
⌋ GCD: 2
ȯ← Decrement: 1
Implicitly: is it nonzero? Yes, so 6 is good.
Result is the EKG sequence: [1,2,4,6,3,9,12...
↑ Take the first n elements: [1,2,4,6,3,9,12,8,10,5]
# Count the number of those
>¹ that are larger than n: 1
```
[Answer]
# JavaScript (ES6), ~~107~~ ~~106~~ 105 bytes
```
f=(n,a=[2,1],k=3)=>a[n-1]?0:a.indexOf(k)+(C=(a,b)=>b?C(b,a%b):a>1)(k,a[0])?f(n,a,k+1):(k>n)+f(n,[k,...a])
```
[Try it online!](https://tio.run/##FYxNDsIgFISvwsbICz8B3VWhix7AAxAWj7aYSgOmNcbbI93MTGYm3wu/uI/b8v6IXKa51mho5mjchWvPk7mCseiy0L5XHcolT/PvEWkCRgdDkYe2h36ggeMpQIdWA00cnfLQx4PEE9PQ0WQzsKNwiUsp0UONZaOZGKJvJJN7c6VaYgzIWPJe1lmu5dkejJyJELYpI40AUP8 "JavaScript (Node.js) – Try It Online")
### How?
The helper function \$C\$ returns *true* if two given integers are *not* coprime:
```
C = (a, b) => b ? C(b, a % b) : a > 1
```
The array \$a\$ is initialized to \$[2,1]\$ and holds all values that were encountered so far in reverse order. Therefore, the last value is always \$a[0]\$.
To know if \$k\$ qualifies as the next term of the sequence, we test whether the following expression is equal to \$0\$:
```
a.indexOf(k) + C(k, a[0])
```
`a.indexOf(k)` is equal to either:
* \$-1\$ if \$k\$ is not found in \$a\$
* \$0\$ if \$k\$ is equal to the last value (in which case it's necessarily not coprime with it)
* some \$i\ge 1\$ otherwise
Therefore, `a.indexOf(k) + C(k, a[0])` is equal to \$0\$ if and only if \$k\$ is not found in \$a\$ and \$k\$ is not coprime with the last value (\$-1+true=0\$).
[Answer]
## Haskell, ~~89~~ 82 bytes
Edit: -7 bytes thanks to @H.PWiz
```
f l=[n|n<-[3..],all(/=n)l,gcd(l!!0)n>1]!!0:l
g n=sum[1|x<-iterate f[2]!!(n-2),x>n]
```
[Try it online!](https://tio.run/##JYlBDoMgEADvfcV6gwQp6K0Rf@ALCGlIi5R02RiliQf/Tm16mJnDvPz2Doi1zoDG0kFDa3spnfCI7GqIo4iPJ8OmUZxG7c7e8BKBzPbJVh/70KYSVl8CzLY7N6O242IfydXsE4GB7JfpDmxZExWQEDnYXoBWP/5Srn4B "Haskell – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 39 [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")
-2 bytes thanks to ngn, -1 byte by using proper conditional checking.
```
{+/⍵<⍵⍴3{(1=⍺∨⊃⌽⍵)∨⍺∊⍵:⍵∇⍨⍺+1⋄⍵,⍺}⍣⍵⍳2}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1pb/1HvVhsgftS7xbhaw9D2Ue@uRx0rHnU1P@rZCxTWBHFAQl1AjhVIXUf7o16QkLbho@4WoIAOkF37qHcx2IzNRrX/0x61TXjU2/eob6qnP9CcQ@uNH7VNBPKCg5yBZIiHZ/D/NAVjrjQFQwMwASUNAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 29 bytes
```
qq:2:w"GE:yX-y0)yZdqg)1)h]G>z
```
[Try it online!](https://tio.run/##y00syfn/v7DQysiqXMnd1aoyQrfSQLMyKqUwXdNQMyPW3a7q/39DAwMDAA "MATL – Try It Online")
Explanation:
```
#implicit input, n, say 10
qq: #push 1:8
2: #push [1 2]. Stack: {[1 .. 8], [1 2]}
w #swap top two elements on stack
" #begin for loop (do the following n-2 times):
GE: #push 1...20. Stack: {[1 2], [1..20]}
y #copy from below. Stack:{[1 2], [1..20], [1 2]}
X- #set difference. Stack: {[1 2], [3..20]}
y0) #copy last element from below. Stack:{[1 2], [3..20], 2}
yZd #copy from below and elementwise GCD. Stack:{[1 2], [3..20],[1,2,etc.]}
qg) #select those with gcd greater than 1. Stack:{[1 2], [4,6,etc.]}
1) #take first. Stack:{[1 2], 4}
h #horizontally concatenate. Stack:{[1 2 4]}
] #end of for loop
G>z #count those greater than input
#implicit output of result
```
[Answer]
# JavaScript, ~~93~~ ~~91~~ 87 bytes
Throws an overflow error for `0` or `1`, outputs `0` for `2`.
```
n=>(g=x=>n-i?g[++x]|(h=(y,z)=>z?h(z,y%z):y)(x,c)<2?g(x):(g[c=x]=++i,x>n)+g(2):0)(i=c=2)
```
[Try it online](https://tio.run/##Dc3RCsIgFADQX@mh4F50Euup0XX0DT2ukWJlxtLhRuiqb1/7gXOe@q0HE10/Fj5cb/OdZk8SLCWSvnC1bRhL7RceBJlPSHKqHzDxvJmwygiJGzyUtYWEFdjGUGqJMceT9MgslFhtERwZKnE2wQ@hu4kuWGiEEMcYdYb9Hlvx0j3AhafFV@tPYlT@lOj19TTqOMIOmVqRXCl2Xx4Uz@C8OnuF8x8)
[Answer]
# APL(NARS), chars 121, bytes 242
```
∇r←a w;i;j;v
r←w⋄→0×⍳w≤2⋄i←2⋄r←⍳2⋄v←1,1,(2×w)⍴0
j←¯1+v⍳0
j+←1⋄→3×⍳1=j⊃v⋄→3×⍳∼1<j∨i⊃r⋄r←r,j⋄i+←1⋄v[j]←1⋄→2×⍳w>i
r←+/w<r
∇
```
test in less one minute here in running time:
```
a¨3 10 100 1000 2000
1 1 9 70 128
```
Natural there is no check for type and for range...
[Answer]
# Japt, ~~23~~ 21 bytes
```
@_jX ªAøZ}f}gA=ì)Aè>U
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=QF9qWCCqQfhafWZ9Z0E97ClB6D5V&input=MTAw)
```
@_jX ªAøZ}f}gA=ì)Aè>U
:Implicit input of integer U
A :10
ì :Digit array
= :Reassign to A
@ }g :While the length of A < U+1, take the last element as X,
:pass it through the following function & push the result to A
_ }f : Find the first integer Z >= 0 that returns falsey
jX : Is Z co-prime with X?
ª : OR
AøZ : Does A contain Z?
) :End loop
Aè>U :Count the elements in A that are greater than U
```
[Answer]
# [Python 3](https://docs.python.org/3/), 153 bytes
```
import math
def f(n):
l=[1];c=0
for _ in range(n-1):l+=[min(*range(2,n*4),key=lambda x:n*8if x in l or math.gcd(x,l[-1])<2else x)];c+=l[-1]>n
return c
```
[Try it online!](https://tio.run/##JY1NDoMgFIT3nOItQWkD2kVjSy9iTEMVlBSehtLEnt76k8zM4ktmZvqlYcRyWVyYxpgg6DSQzliwFFlFwKtaNrdWCQJ2jPAEhxA19obiSbLK56oODml2sIJjdmH8bX7K6/DqNMwVZldnYd6KHtaJ7eHctx2dua9PsmH3wviPgZmtP7na2QMJRJO@EaFdpugw0SzoiVpelxyk2HyEaBhbSiLFqt3iDw "Python 3 – Try It Online") (Warning: Takes ~30 seconds to evaluate)
] |
[Question]
[
ASCII art is fun. Modern text editors are very good at manipulating text. Are modern programming languages up to the task?
One common task in ASCII art manipulation is to crop text to a rectangle between two characters. This is the task you must implement in this challenge.
## Details
Your program will take 3 inputs:
* the first is the 'start' character of the block - marking the top-left corner
* the second is the 'end' character of the block - marking the bottom-right corner
* the third is some form of multiline text, either a string, or list of strings, or filename, or whatever
The result will be multiline text (again, in any of the above formats) cropped to the rectangle between the given inputs. Note that the first two inputs may not be unique.
## Edge cases
Boxes must always have volume at least 2. Thus these:
```
() (
)
```
*are* boxes but these:
```
)( ) (
( )
```
are not (with start=`(` and end=`)`).
The input will only contain one box. Thus the start and end characters must only occur once, unless they are the same character in which case they must occur exactly twice.
Additionally each line in the input must be at least as long as the distance from the start of a line to the right edge of the box in the input.
Your program does not need to handle invalid inputs; they may result in undefined behavior.
## Rules
Typical code-golf rules apply. Shortest code wins.
## Examples
Sunny-day: `start: ( end: ) input:`
```
This is some text
. (but this text
is in a box ).
So only it is important.
```
Output:
```
(but this text
is in a box )
```
Note the stripping of horizontal space as well. ASCII art crops are 2d.
Rainy-day: `start: ( end: ) input:`
```
This is some text (
But is that even )
really a box?
```
Output:
```
(
)
```
Same start/end: `start: / end: / input:`
```
Oh, I get how this could be useful
/----------------------------\
| All this text is in a box! |
\----------------------------/
```
Output:
```
/----------------------------\
| All this text is in a box! |
\----------------------------/
```
Invalid input: `start: ( end: ) input:`
```
Boxes are rectangular ( so this has
0 volume ) which is illegal.
```
Invalid input 2: `start: ( end: ) input:`
```
(The lines must already be square
so this line that is too short
relative to this end, is illegal)
```
[Answer]
# Vim, ~~16~~, 12 bytes/keystrokes
```
#<C-v>Nj*yggVGp
```
[Try it online!](https://tio.run/##K/v/X9nGWbfMzi9LqzI9Pcy94P9/fS59Lv8MHQVPhfTUEoWM/HKFkozMYoXk/NKcFIWkVIXS4tS00hwuBX1dPCCGS6FGwTEnB6K3JLWiRAFIZ@YpJCok5VcoKtRwKcTg06//X7cMAA) in the V interpreter
>
> Modern text editors are very good at manipulating text. Are modern programming languages up to the task?
>
>
>
I bet *old* text editors are even better! :D
Even though it doesn't necessarily have to, this answer does work with both of the given "invalid" inputs, outputting
```
rectangular (
) which is ill
```
and
```
(The lines must already be square
so this line that is too short
relative to this end, is illegal)
```
Explanation:
```
# " Move backward to the previous occurrence of the word (or in this case, character) under the cursor
<C-v> " Start a visual block selection
N " Go to the next occurrence of the last searched term (guaranteed to be line 1)
j " Move down a line
* " Move forward to the next occurrence of the character under the cursor
y " Yank (copy) the whole visually selected block
gg " Go to line 1
VG " Select every line
p " And paste what we last copied over it, deleting the whole buffer and replacing it with the block
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
=€SŒṪr/,þ/Zœị
```
A dyadic link accepting a list of start and end characters on the left and a list of lines (as lists of characters) on the right which yields a list of lines (as lists of characters).
**[Try it online!](https://tio.run/##y0rNyan8/9/2UdOa4KOTHu5cVaSvc3ifftTRyQ93d/8/vPzh7i21kf//6@v/98/QUfBUSE8tUcjIL1coycgsVkjOL81JUUhKVSgtTk0rzeHS18UDYrhqFBxzciA6S1IrShSAdGaeQqJCUn6FokINVww@3foA "Jelly – Try It Online")** (full program - if inputs are valid Python they will require Python-string-quoting.)
### How?
```
=€SŒṪr/,þ/Zœị - Link: [start, stop], lines
€ - for each (of [start, stop]):
= - equals? (vectorises across the lines)
S - sum (vectorises)
ŒṪ - multi-dimensional truthy (i.e. non-zero) indices
/ - reduce by:
r - inclusive range (vectorises)
/ - reduce by:
þ - outer product with:
, - pair
Z - transpose
œị - multi-dimensional index-into (the lines)
```
As an example, with left = `['a', 'b']` and right (as a list of lists of characters - the lines):
```
--------
--a+++--
--++++--
--+++b--
--------
```
`=€` yields a list of two lists of lists (the first performs `'a'=`, the second `'b'=`):
```
00000000 00000000
00100000 00000000
00000000 , 00000000
00000000 00000100
00000000 00000000
```
summing this yields a single list of lists (summing element-wise):
```
00000000
00100000
00000000
00000100
00000000
```
`ŒṪ` then gives us the (1-indexed) multi-dimensional indices of the non-zeros, `[[2,3],[4,6]]` - i.e. `[[top,left],[bottom,right]]`.
`r/` then performs `[2,3]r[4,6]` which, since `r` vectorises, is like `[2r4, 3r6]`, evaluating to `[[2,3,4],[3,4,5,6]]` - i.e. `[rows,columns]`.
`,þ/` then performs `[2,3,4],þ[3,4,5,6]` where `þ` is an outer-poduct instruction and `,` is pair. This yields all the `[row,column]` values by column, in this case:
```
[[[2,3],[3,3],[4,3]],
[[2,4],[3,4],[4,4]],
[[2,5],[3,5],[4,5]],
[[2,6],[3,6],[4,6]]]
```
We want these by row, so `Z` is used to transpose this to:
```
[[[2,3],[2,4],[2,5],[2,6]],
[[3,3],[3,4],[3,5],[3,6]],
[[4,3],[4,4],[4,5],[4,6]]]
```
Finally `œị` indexes back into the input lines:
```
a+++
++++
+++b
```
It's worth noting that when both bounding characters are the same `=€` identifies both twice but `SŒṪ` ends up doing the right thing, since `2` is truthy, e.g. with `['a','a']`:
```
-------- 00000000 00000000 00000000
--a+++-- 00100000 00100000 00200000
--++++-- =€ -> 00000000 , 00000000 S -> 00000000 ŒṪ -> [[2,3],[4,6]]
--+++a-- 00000100 00000100 00000020
-------- 00000000 00000000 00000000
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~38~~ 30 bytes
*4 bytes saved thanks to @EriktheOutgolfer*
```
(1-⍨w-⍨⊃⍸⎕=s)↑(w←∊⊃⌽⍸⎕=s)↑s←↑⎕
```
[Try it online!](https://tio.run/##fY@xTsMwEIb3PMXPZEciVDxAhWBjYoCxi0OdppIbV/WZtFI3pFBVFNGBd@ARWHgZv0g4J1LpUNXyneT7f393p@YmG6@UsZM2bN6KVl5nYfddxxS2r2H3Ez6@hi4NzV7WofkMm20sv/8eKy4KzZ7fkdEWiXgqpw58nZ1pkF6SgABk7gkUpUMp2ioo5HYJpFx6tLCVWWFKnTab2wWpiq5EIlIOKZJEDDmdagLJgDvf/aRSEfSLrnrsQivD1K7RzQnWQ3mJe0w0obR1P@Oz9WaMXMM7XXjDkEF25ozYsMatMf8bHm93gTUbRucIA56pjz8 "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
œẹⱮẎQr/Ṛṭþ/œị⁸
```
[Try it online!](https://tio.run/##y0rNyan8///o5Ie7dj7auO7hrr7AIv2HO2c93Ln28D59oPDu7keNO/4fXq6t/6hpzdFJD3fO@P8/Wt0/Q0fBUyE9tUQhI79coSQjs1ghOb80J0UhKVWhtDg1rTRHXUdBXUFfFw@IiQGrqVFwzMmBGFGSWlGiAKQz8xQSFZLyKxQVasBKYvAZo68e@19fHwA "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 130 bytes
```
def f(s,e,t):
a=[(i,l.find(c))for i,l in enumerate(t)for c in s+e if c in l];r,c,R,C=a[0]+a[-1]
for l in t[r:R+1]:print l[c:C+1]
```
[Try it online!](https://tio.run/##fY8xT8MwEIV3/4pjsqO6CWVMVSHoxIRU2NIMbnomlly7ci7QSv3vwXaFQAy1PPjePX/37nim3ruHadqjBi0GiZKKmoFaNcJIW2rj9qIrCu0DxBqMA3TjAYMiFJTlLonDDMHo69u2yyA7uZHrlWru25lq5ouWQfJmADWh3swWbX0MxhHYpqvXsZy04IJLXnDZ8PfeDBDv4A8IhCfikvESxG4koNT70SC5IlTBzp8AijKJbx68s2cwlLuHow@kHJW8LRjLUxm7OQ1EwjyP@T/1igA/0UV8kgMqG@F54uM/ZBWRVUK@9hJe4AMJev91jdz50e5hhzAOqEeb01fzG2e7zZ4LPFn7u/Xfhe/gki3bW5gqZpy@AQ "Python 2 – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 37 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
{³⁴⁰;x≡‽┐
X⁸)J╵⁶;┤ω┤⁵X⁶⁸⁰K├;┐┤└∔┘┘∔;@
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjVCJUIzJXUyMDc0JXUyMDcwJXVGRjFCJXVGRjU4JXUyMjYxJXUyMDNEJXUyNTEwJTBBJXVGRjM4JXUyMDc4JXVGRjA5JXVGRjJBJXUyNTc1JXUyMDc2JXVGRjFCJXUyNTI0JXUwM0M5JXUyNTI0JXUyMDc1JXVGRjM4JXUyMDc2JXUyMDc4JXUyMDcwJXVGRjJCJXUyNTFDJXVGRjFCJXUyNTEwJXUyNTI0JXUyNTE0JXUyMjE0JXUyNTE4JXUyNTE4JXUyMjE0JXVGRjFCJXVGRjIw,i=JTIyJTI4JTIyJTBBJTYwJTYwJTYwJTBBVGhpcyUyMGlzJTIwc29tZSUyMHRleHQlMEElMjAlMjAlMjhidXQlMjB0aGlzJTIwdGV4dCUwQSUyMCUyMGlzJTIwaW4lMjBhJTIwYm94JTIwJTIwJTI5JTBBU28lMjBvbmx5JTIwaXQlMjBpcyUyMGltcG9ydGFudC4lMEElNjAlNjAlNjAlMEElMjIlMjklMjI_,v=8)
36 bytes for getting the coordinates of the characters (and converting them to x,y,w,h because that's what `@` takes) and 1 byte for getting the subsection.. There must be a better approach
[Answer]
# JavaScript (ES6), 98 bytes
Takes input as two integers and an array of strings. Returns an array of strings.
```
(x,y,a,X=Y=0)=>a.filter(s=>!Y&&(Y=-~s.indexOf(y,X?X-1:X=-~s.indexOf(x)),X)).map(s=>s.slice(X-1,Y))
```
[Try it online!](https://tio.run/##jZBBT4QwEIXv/IrZy9ImpejVhN3ozdMe9AAREwoMC6a0hJYVko1/HaGarCZmYzOnN6/fm5k3cRKm6JvOBkqXOFfRTEY2McHiKIluaLQTvGqkxZ6YaLdJtluSRMGH4Y0qcTxUZGLxPg5u7@Jf6kgpiynlrejWf4Yb2RRIFiNLKJ0LrYyWyKU@kor4xGc@9dmLlz3XjYGljG4RLI42Y14GQPLBgl17F201KhCQ6xGArtqTBq3kBI11zbbTvRXK8uyVUs/7fyaQlfYwOIythQU8ofoO6VHIJcPl7v8khws5dORDzeARjmih1u9f8xd6kCXkCIPBapBulTC48tLUec5wL@XlBD@338DZWdL0GidcZ50/AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
( x, // x = start character
y, // y = end character
a, // a[] = array of strings
X = // X = position of x, plus 1
Y = 0 // Y = position of y, plus 1
) => //
a.filter(s => // for each string s in a[]:
!Y && // reject this string if Y is non-zero
( // otherwise, use the 2nd condition:
Y = -~s.indexOf( // update Y:
y, // by looking for y in s
X ? // if X is non-zero:
X - 1 // start the search at X - 1
: // else:
X = -~s.indexOf(x) // update X and start the search at X
), // end of Y update
X // keep this string if X is non-zero
) // end of 2nd condition
) // end of filter()
.map(s => // for each remaining string s:
s.slice(X - 1, Y) // remove left and right characters outside the box
) // end of map()
```
[Answer]
# Java 10, 204 bytes
```
(s,e,a)->{int b=-1,i=0;for(;i<a.length;i++)a[i]=(b=b<0?a[i].indexOf(s):b)<0|a[i].length()<b?"":a[i].substring(b);for(b=-1;i-->0;)a[i]=(b=b<0?a[i].indexOf(e):b)<0|a[i].length()<b?"":a[i].substring(0,b+1);}
```
Modifies the input-array instead of returning a new one to save bytes. This does mean that removed lines become `""` instead, though. If this is not allowed I will change it.
[Try it online.](https://tio.run/##lVRNb@IwEL33V8z65CgfwLVJirq3lXbbldgb4WAHA@4aB8UTCqL8dtYxpo2oKGwUWY4z782bZ49f2JrFL9O/h1IxY@AXk3p3ByA1inrGSgFP7SfAupJTKOkIa6nnYCLwM3GajSfAgtTG7u/sYJChLOEJNORwoCYSEQvih53lBZ7Hg0jm/XRW1TSVGUuU0HNcpDIMAzaWk5zynGf9YTtPpJ6KzfOMmuCeB1n/zS0eATTI@JCQe7dkGm6cEMoDx9ymSWUcP/TTy6ziZtZ@xMNBkO4PaVvfquHK1ufLdOYsrXW048XRNxQGKaEkIgGJtHh9d2tH/iykAfuaails3AZJ5CCXH5IA5Q0CtsjbENBmkBoY8GoDECTXIaMKKq22INFhl6uqRqYxIXu3v/9XE9DrCb83LhMuGIJYC21lXgfVgikr0tU1PJPWs9J659KeFxH8gLlAWFSvRwvLqlFT4AIaI2aNusHNXvzFUxQ3MLzBo1IfO9jdnm/wdgNBUXyloeet6HahO57OmVP7Iqvxo4X1tNPEUq8a/Cm1MP4E66SkHuAiOwFHz1e1QNz@tnikn36OtgbFMqkaTFZthNLU6wM4U9jleZdju@@xrtnWi/GSsXJh9m4h4zE5Zmp7vl1T@QnjG9rdNSAzZQd7w3iDPUWYU5kN2n4nMCZBSApCwhOBvQHahQkJbZCKbVhUaBs5IZer87y@yP3hHw)
**Explanation:**
```
(s,e,a)->{ // Method with 2 Strings & String-array parameters and no return
int b=-1, // Boundaries-integer, starting at -1
i=0;for(;i<a.length;i++) // Loop `i` in the range [0, amountOfLines)
a[i]= // Change the `i`th line in the array to:
(b=b<0? // If `b` is -1:
a[i].indexOf(s) // Set `b` to the index of `s` in the current line
// (which is still -1 if it's not found)
: // Else (starting index already found)
b // Leave `b` unchanged
)<0 // Then, if `b` is -1,
|a[i].length()<b? // or the current line-length is too short:
"" // Remove the current line
: // Else:
a[i].substring(b); // Shorten the line by removing every character before `b`
for(b=-1; // Reset `b` to -1
i-->0;) // Loop `i` in the range (amountOfLines, 0]
a[i]= // Change the `i`th line in the array to:
(b=b<0?a[i].indexOf(e):b)<0|a[i].length()<b?"":
// Similar as above (with end `e` instead of start `s`),
a[i].substring(0,b+1);}
// except we remove every character after `b` this time
```
**For example:**
With the inputs `start = "("`, `end = ")"` and `lines =`
```
["This is some text",
". (but this text",
" is in a box ).",
"So only it is important."]
```
the first loop will crop it at the top and left, changing it to this:
```
["",
"(but this text",
"is in a box ).",
" only it is important."]
```
the second loop will crop it at the bottom and right, changing it to this:
```
["",
"(but this text",
"is in a box )",
""]
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 110 bytes
```
^((.)¶.)(.*¶)+(.*\2)
$1¶$4
^(.)(¶.¶\1)
$2
}s`(?<=^.¶.+)¶.
¶
s`^¶(.)¶(.*\1).*
$2
+m`^((.)+).¶((?<-2>.)+)$
$1¶$3
```
[Try it online!](https://tio.run/##LYxNCoMwEIX3c4pZuJgoDWi77M8h2qUEFYQKNSlmCnbRa@UAuVg6sYWBx7zvvbeMPNk@JUOkVQxakS5jUJVI2ygo6hiKAxiBJDSGthazgY/v6HI8GXF0lXsQA/jOxLDN5HatdJmj1dxt45WSMElr15zzV/zG9ykRKLjdJ49y3s0j8rgyINLwYuQM/kaOWOxxcCuigqtDZx9vnHgj89Mt3FvWXw "Retina 0.8.2 – Try It Online") Explanation:
```
^((.)¶.)(.*¶)+(.*\2)
$1¶$4
```
Delete the input lines preceding the first line of the box.
```
^(.)(¶.¶\1)
$2
```
If the start character is in the left column of the input, delete it.
```
}s`(?<=^.¶.+)¶.
¶
```
If the start character hasn't been deleted yet, shift all the input columns left by one and repeat from the beginning.
```
s`^¶(.)¶(.*\1).*
$2
```
Delete the end character and everything in the input after the end character.
```
+m`^((.)+).¶((?<-2>.)+)$
$1¶$3
```
Truncate all the lines to the length of the next line. This works by counting all but one character on each line, then attempting to match up to that many characters on the next line; if this succeeds then the second line was shorter, so the last character is deleted and the loop repeats.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 237 bytes
```
f(c,r,o,p)char*p,*c;{char*_=strchr(p,r),*a,b;*_=0;a=strrchr(p,10);a=(a?a:p);*_=r;r=_-a;p=a;_=strrchr(p,o);*_=0;a=strrchr(p,10);a=(a?a:p);*_=o;o=_-a+1;_[1]=0;for(_=p;_;_=strchr(_+1,10)){b=_[o];_[o]=0;strcat(c,_+r);strcat(c,"\n");_[o]=b;}}
```
[Try it online!](https://tio.run/##jY/fasMgFIfv8xSHwkBTW5JsV5Owh9juMhEjTRNYVU7saAl5dqdJ2J@7hSDH7/sdPerDWesQOqIZMssc1b3C3LFc82kpZT161D0Sx5CyXLGWR1ZwlfgmyoLGPVEv6tnRpJFjLQ@Ku1px@Sto6T@aLbepeV9y2ZQipjuLRNaOS/49jNyXqZFObS0bK3haYjJZ5eNb5B7pz273bnZ0zbR8nsNgPFzUYEgqFJ41g/RWyGP92QgKUwbxW1h77ZqyqJ4E/8OqFdZTMa9iWdKN7k6iZ8tRj4KutkusYusFpdiKSrCIt4jDOE1Hdg9jnDbxahN48lc0UPBsDoEEGt76YYT4j/ZyAn@6@ewI8XwPPokFQPKDAQWtvQHQY/ZqwZqPOwx@URdn0Svjj18 "C (gcc) – Try It Online")
I'm 99% sure this can be shortened using some kind of helper function to find horizontal index of and pointer to a character, as it is repeated twice. Alas I couldn't find a short enough way to do it, I may try again later if I find the time.
### Description
```
f(c,r,o,p)char*p,*c;{
char*_=strchr(p,r),*a,b; // find opening char (and declare vars)
*_=0;a=strrchr(p,10); // find \n before it
a=(a?a:p); // deal with single line inputs
*_=r;r=_-a; // save left margin width in r
p=a; // crop everything before opening line
_=strchr(p,o); // find closing char
*_=0;a=strrchr(p,10); // find \n before it
a=(a?a:p); // deal with single line inputs
*_=o;o=_-a+1; // save width in o
_[1]=0; // crop everything after closing char
for(_=p;_;_=strchr(_+1,10)){ // for each line
b=_[o];_[o]=0;
strcat(c,_+r);
strcat(c,"\n");
_[o]=b;
}
}
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╛↨½╝v∞░W╧)╗Ö≈☼k
```
[Run and debug it](https://staxlang.xyz/#p=be17abbc76ecb057cf29bb99f70f6b&i=%28%29%0AThis+is+some+text%0A.+%28but+this+text%0A++is+in+a+box++%29.%0ASo+only+it+is+important.&a=1)
It takes the set of box delimiter characters (1 or 2) on the first line of input. The rest of the lines are the input body.
Unpacked, ungolfed, and commented, it looks like this.
```
first line of input is the delimiter characters
dL discard the first line of input and listify the rest into an array
{ begin block for iteration
Mr rotate matrix 90 degrees
{ begin block for while loop
ch copy first row of block
y|&C if it insersects with the first line of input, break iteration
D drop the first line
W do-while loop until break
}4* execute block 4 times
m display result lines
```
[Run this one](https://staxlang.xyz/#c=++++++++%09first+line+of+input+is+the+delimiter+characters%0AdL++++++%09discard+the+first+line+of+input+and+listify+the+rest+into+an+array%0A%7B+++++++%09begin+block+for+iteration%0A++Mr++++%09rotate+matrix+90+degrees%0A++%7B+++++%09begin+block+for+while+loop%0A++++ch++%09copy+first+row+of+block%0A++++y%7C%26C%09if+it+insersects+with+the+first+line+of+input,+break+iteration%0A++++D+++%09drop+the+first+line%0A++W+++++%09do-while+loop+until+break%0A%7D4*+++++%09execute+block+4+times%0Am+++++++%09display+result+lines&i=%28%29%0AThis+is+some+text%0A.+%28but+this+text%0A++is+in+a+box++%29.%0ASo+only+it+is+important.&a=1)
] |
[Question]
[
Consider the array of positive integers:
```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ...
```
Then, concatenate them:
```
1234567891011121314151617181920212223242526...
```
And then split them into chunks of variable length, each length being equal to the **N**th positive integer:
```
[1][23][456][7891][01112][131415][1617181][92021222][324252627][2829303132] ...
---------------------------------------------------------------------------
1 2 3 4 5 6 7 8 9 10 ...
```
# Task
Given an integer **N** (positive for 1-indexing or non-negative for 0-indexing), your task is to output the sum of the deltas of the digits in the **N**th chunk (the differences between consecutive digits).
* [Default-forbidden loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* [Standard Input and Output methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply.
* You may choose either 0 or 1-indexing for **N**.
* The sequence must start with **1**.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins.
# Examples & Test cases
1-indexed test cases. If you want 0-indexed ones, just decrement N.
```
N, Chunk, Deltas, Sum
1 -> 1 -> [] -> 0
2 -> 23 -> [1] -> 1
3 -> 456 -> [1, 1] -> 2
4 -> 7891 -> [1, 1, -8] -> -6
5 -> 01112 -> [1, 0, 0,1] -> 2
6 -> 131415 -> [2, -2, 3, -3, 4] -> 4
7 -> 1617181 -> [5, -5, 6, -6, 7, -7] -> 0
8 -> 92021222 -> [-7, -2, 2, -1, 1, 0, 0] -> -7
9 -> 324252627 -> [-1, 2, -2, 3, -3, 4, -4, 5] -> 4
10 -> 2829303132 -> [6, -6, 7, -6, -3, 3, -2, 2, -1] -> 0
```
**[Puzzle 2](https://github.com/Mr-Xcoder/CodeGolf-Hackathon/blob/master/Puzzle%202/Puzzle%202.md) on [CodeGolf-Hackathon](https://github.com/Mr-Xcoder/CodeGolf-Hackathon) (I am the original author there too, so I am allowed to repost). [Related, Inspiration](https://codegolf.stackexchange.com/questions/145883/binary-prime-chunks). [Related](https://codegolf.stackexchange.com/questions/145421/the-binary-square-diagonal-sequence).**
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
ΣẊ-!SCṁdN
```
[Try it online!](https://tio.run/##yygtzv7//9zih7u6dBWDnR/ubEzx@///vwkA "Husk – Try It Online")
My solution to the Hackathon.
Explanation:
```
ΣẊ-!SCṁdN⁰
S (x -> y -> z):f -> (x -> y):g -> x:x :: return f(x, g(x))
C f= [num]:x -> [x]:y -> [x] :: cut y in pieces where each piece has its respective length in x
ṁ g= (x -> [y]):f -> ([x]:x -> [y]) :: maps f over x then concatenate
d f= num:x -> [num] :: return decimal digits of x
N x= sequence of natural numbers [1..]
! ⁰ [x]:x -> num:y -> x :: get yth (impl. input) element of x (above result)
Ẋ (x -> x -> y):f -> [x]:x -> [y] :: map f over overlapping pairs of x (above result)
- f= num:x -> num:y -> num :: return y - x
Σ [num]:x -> num :: return sum of x (above result)
```
[Answer]
# JavaScript (ES6), ~~54~~ ~~53~~ ~~51~~ 50 bytes
*Saved 1 byte thanks to @tsh*
0-indexed.
```
k=>-(n=1,g=s=>s[x=k*-~k/2]-s[x+k]-n||g(s+n++))``-n
```
### Test cases
```
let f =
k=>-(n=1,g=s=>s[x=k*-~k/2]-s[x+k]-n||g(s+n++))``-n
for(i = 0; i < 10; i++) {
console.log('a(' + i + ') = ' + f(i));
}
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 32 bytes
```
{+/2-⍨/⍎¨⍵↑(+/⍳⍵-1)↓' '~⍨⍕⍳+/⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqbX0j3Ue9K/Qf9fYdWvGod@ujtoka2kDeZiBb11DzUdtkdQX1OqCKR71TgaIwqVqgdgWQhs0KhgYA "APL (Dyalog Unicode) – Try It Online")
**How?**
`+/⍳⍵` - sum of `1` to `n`
`⍳` - make range of that
`' '~⍨⍕` - into string, without spaces
`(+/⍳⍵-1)↓` - drop first (sum of `1` to `n-1`) chars
`⍵↑` - keep the next `n` chars
`⍎¨` - make every char into integer
`2-⍨/` - differences list (backward subtraction for every 2 items)
`+/` - sum it up.
[Answer]
# [Haskell](https://www.haskell.org/), ~~61~~ 60 bytes
```
l=fromEnum<$>(show=<<[1..])
f n|t<-sum[2..n]=l!!t-l!!(t-n+1)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P8c2rSg/1zWvNNdGxU6jOCO/3NbGJtpQTy9WkytNIa@mxEa3uDQ32khPLy/WNkdRsUQXSGiU6OZpG2r@z03MzFOwVchNLPCNV9AoKMrMK9FL01QAaTc0iP0PAA "Haskell – Try It Online")
### Explanation:
The sum of the deltas of a list is the same as the difference between the last and the first element.
The last element (zero-indexed) is `t`, `triangle(n)-1 = sum[2..n]`. The first element, then is `t-n+1`, as the list has `n` elements.
[Answer]
# [Python 2](https://docs.python.org/2/), 80 bytes
```
n=input()
s=map(int,''.join(map(str,range(2**n))))
print s[n*-~n/2]-s[~-n*n/2+1]
```
[Try it online!](https://tio.run/##FYqxCoAgAAV3v6ItNS2SVr9EHByiDHqK2tDir5vddAcX33IGqNagPeJTKCNZ3y5SjyLGcb6CB/07lySSw7FTxTlYh8TUpyEbcFmxKCuzqRK867Ta1rYP "Python 2 – Try It Online")
`2**n` is way overkill, of course, but it’s a byte shorter than something like `n*n+1`.
[Answer]
# Mathematica, 71 bytes
```
Tr@Differences[TakeList[Join@@IntegerDigits[Range[#^2]],Range@#][[#]]]&
```
[Try it online!](https://tio.run/##HcYxCsMwDADArxgMmTI02QMasrR0CMWbUEAE2RUlKtj6vwO56U72r5zsenDPYQk9VVg1Z6lihzRM/JO3NsfXXw3gaS5F6qpFveGHrQjGfSYa70MkxEhEQ9@qmgfIOD2oXw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
∞LJā£è¥O
```
0-indexed.
[Try it online!](https://tio.run/##MzBNTDJM/e/mZ69kpaBk7@fy/1HHPB@vI42HFh9ecWip/3@d/4YGBgA "05AB1E – Try It Online")
[Answer]
## JavaScript (ES6), ~~60~~ ~~57~~ 53 bytes
```
f=(n,s=i='',m=n*-~n/2)=>s[m]?s[m]-s[m-n+1]:f(n,s+i++)
```
```
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>
```
1-indexed. Previous 60-byte nonrecursive version:
```
f=
(n,s=[...Array(n*n+1).keys()].join``)=>s[m=n*-~n/2]-s[m-n+1]
```
```
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>
```
[Answer]
# [Python 2](https://docs.python.org/2/), 87 bytes
```
n=input()
a=map(int,''.join(map(str,range(1,n*n))))[n*~-n/2:][:n]or[0]
print a[-1]-a[0]
```
[Try it online!](https://tio.run/##NY5BDsIgFET3nOKHTaFpVbok4SSExbdFxdgPoZjoxqsjNXF2M8m8mfQut0hTnePiDee8kgmUnkVIhmbFJAKVoesO9xhI7H4rechIVy/UQD3JJkv9Z6TjpJ3V5GK2J8dSbkVAOyo3YgtqY7NLzBAgEPwBSknNAH6LYOCB63lBDaFl/uVn2F/VLw "Python 2 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 11 bytes
```
²ɾṅ?ʀʀÞṁi⌊¯
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiwrLJvuG5hT/KgMqAw57huYFp4oyKwq8iLCIiLCI3Il0=)
0-indexed
## Explained
```
²ɾṅ?ʀʀÞṁi⌊¯
²ɾ # the range [1...input**2]
ṅ # joined into a single integer - call it x
?ʀ # the range [0...input]
ʀ # [range [0...n] for n in that]
Þṁ # reshape x to the shape of that
i # get the input(th) item of that
⌊ # convert each item to integer
¯ # and take the deltas of that
# the -s flag sums that
```
[Answer]
# [Python 2](https://docs.python.org/2/), 104 bytes
```
def f(N):A=map(int,"".join(map(str,range(1,N*N)))[~-N*N/2:][:N]);return sum(a-b for a,b in zip(A[1:],A))
```
[Try it online!](https://tio.run/##NY89TsQwEIVrcoqnVB40WZKw7I9RilwgF4hSeIUDRlo7GnsLKLh68EZQzfv5NNJbvtJH8O26vtkZsxpI993VLMr5xGW5@wzOq7uPSViMf7eq4eFxIKLxp8riqdXTqIeJXsWmm3jE21WZ6oI5CAxf4Dy@3aL6sdET90TrvXCM8N8UD/klWsYzA3vGC@PAOGZzYpwZTU2cmTqrDasO28lkjqrjplBTQRomRispz3CErkMoFsk7UA7hr3LBw4oEibty/QU "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), ~~58~~ 55 bytes
```
{[+] ($_=(1..*).map(|*.comb).rotor(1..*)[$^a])[1..*]Z-@$_}
```
[Test it](https://tio.run/##K0gtyjH7n1upoJaYU5JalJdaXJKaomD7vzpaO1ZBQyXeVsNQT09LUy83sUCjRksvOT83SVOvKL8kvwgiEa0SlxirGQ1ix0bpOqjE1/4vKMrMK0lTUFI1AhpkpwCkYvKUdBRU4nUUkOwAmq2pkJZfpBBnaPAfAA "Perl 6 – Try It Online")
```
{[+] ($_=(1..*).map(|*.comb)[^$^a+[+] ^$a])[1..*]Z-@$_}
```
[Test it](https://tio.run/##K0gtyjH7n1upoJaYU5JalJdaXJKaomD7vzpaO1ZBQyXeVsNQT09LUy83sUCjRksvOT83STM6TiUuURukIE4lMVYzGqQiNkrXQSW@9n9BUWZeSZqCkqoR0BQ7BSAVk6eko6ASr6OAZAHQYE2FtPwiBaBWQ4P/AA "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with placeholder parameter 「$a」
[+] # reduce using &infix:«+» the following
(
$_ = # store into 「$_」 for later use
( 1 .. * ) # Range of all positive integers
.map( | *.comb )\ # split into digits and flatten into single list
[ # index into the sequence (1 based)
^$^a # Range up to (and excluding) the input
# 「0 ..^ $a」 or 「0 .. $a-1」
+ # shift it up by
[+] ^$a # the sum of the values up to (and excluding) the input
]
)[ 1 .. *] # skip the first value
Z- # zip using &infix:«-»
@$_ # 「$_」 used as a List
}
```
[Answer]
# [PHP](https://php.net/), ~~163~~ 147 bytes
```
$v=$argv[1];for($i=1;$i<=$v*$v;$i++){$s.=$i;$j+=$i<$v?$i:0;}$s=array_slice(str_split($s),$j,$v);for($i=0;$i<$v-1;$i++){$k+=$s[$i+1]-$s[$i];}echo$k;
```
[Try it online!](https://tio.run/##NYxBCoMwFEQvMwutVsyy/QYPIiJibf0qTciXQClevWkQ3My8Wcyzkw1VbWPCa/Tu5RvV0tO4BKwVgSsNf4GPlGXpF1JoMGHOYlXwNfhe0g7RvXP9p5OVhzGRzXViV94SSJpjzuHT01nScbyq07hElTRxqPZ6QEv7OEwGC4XwM3Zj85ZQDOYxFpHD7Q8 "PHP – Try It Online")
My first attempt at code golfing... have a feeling that this can be shorter
Edit: saved 16 bytes by removing several instantiations
[Answer]
# [Perl 5](https://www.perl.org/), 79 + 1 (`-p`) = 80 bytes
```
$_=substr join('',1..$_**2),$_*($_-1)/2,$_;1while s/(.)(.)/$r+=$2-$1;$2/e;$_=$r
```
[Try it online!](https://tio.run/##DYxLCoAgFACv4uKBWn5QaiWeRQiEDElRo9v3EgZmVlNjyzsiBN@fo49GrpJuRqkwSkFYFsvFFIMgDdd2tjPvmXIkXTPFJxra6sFKMA6sjm6eoCFuX6kjlbujrD8 "Perl 5 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~29~~ 27 bytes
Saved 2 bytes thanks to @Mr.Xcoder.
```
s.+msdc:sm+hd""U*QQKsUQ+QK1
```
[Try it online!](https://tio.run/##K6gsyfj/v1hPO7c4JdmqOFc7I0VJKVQrMNC7ODRQO9Db8P9/EwA "Pyth – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
²RDFṫ³ḶS‘¤ðḣIS
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//wrJSREbhuavCs@G4tlPigJjCpMOw4bijSVP///8xMA "Jelly – Try It Online")
**Explanation**
```
²RDFṫ³ḶS‘¤ðḣIS Main Link
² Square input
R Range: [1,2,3,..,n^2]
D Digits: [1,2,...,[1,0],[1,1],...]
F Flatten list
³ḶS‘¤ n(n-1)/2+1
ṫ Remove the first n(n-1)/2+1 elements from the list of digits
ðḣ Take the first n digits of the list. ð is needed to prevent I from acting on n.
I Increment. Take the diferences
S Sum
```
I originally started by taking the range( n(n+1)/2 ) but since you can have extra digits at the end of the list before slicing it I changed it to range(n^2). You have extra digits after 1-9 anyway.
] |
[Question]
[
The world of art is full of colour, but the world of the network is even fuller than the world of art of diferent colours and it's renderings. That's why we need to know how to convert one type of colour format to another.
### The challenge is self-evident:
Write a program / function than converts an given [HEX](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) code (`#00ff0080`, for instance) to [RGBA](https://en.wikipedia.org/wiki/RGB_color_model) (like `rgba(0, 255, 0, 0.5)`).
# Rules:
* External libraries/ built-ins for converting HEX to RGBA are disallowed. However, jQuery and syntax replacers like that are acceptable.
* Standard Input/Output rules apply.
* Format of the alpha can be between (1 == 100%) or the other (100 == 100%) that's not really important.
* The output *is flexible*, as long as it returns the 4 converted values (as a String, Array, List, your choice).
* You may choose to take the input without the `#` in the beginning. Hence, you can take input as either `#RRGGBBAA` or `RRGGBBAA`. You can assume that the hex code (excluding the `#`) will always be 8 characters long.
* You should divide all the values by 255, including the alpha. The minimum decimal precision (for the alpha will be 2 decimal places).
# Test Cases
```
Input: 00ff0080
Output: 0, 255, 0, 0.5
```
# Scoring
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the code with the least amount of bytes wins.
[Answer]
# JavaScript (ES6), ~~73~~ ~~54~~ 50 bytes
(Saved some bytes thanks to @LeakyNun, the edited challenge, and @CraigAyre.)
```
s=>s.match(/../g).map((c,i)=>('0x'+c)/(i-3?1:255))
```
```
let f=
s=>s.match(/../g).map((c,i)=>('0x'+c)/(i-3?1:255))
console.log(f('00ff0080'));
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~13~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as a string, without the leading `#`. Outputs the rgba value as an array.
```
ò mnG o÷#ÿ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=8iBtbkcgb/cj/w&input=IjAwZmYwMDgwIg)
```
ò mnG o÷#ÿ :Implicit input of string
ò :Partitions of length 2
m :Map
n : Convert to integer from base
G : 16
o :Modify last element
÷ : Divide by
#ÿ : 255
```
[Answer]
# [PHP](https://php.net/), 63 bytes
Output as array
```
$h=array_map(hexdec,str_split($argn,2));$h[3]/=255;print_r($h);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoMClkliUnmerZGCQlmZgYGGgZP1fJcM2sagosTI@N7FAIyO1IiU1Wae4pCi@uCAns0QDrF7HSFPTWiUj2jhW39bI1NS6oCgzryS@SEMlQ9P6/38A "PHP – Try It Online")
# [PHP](https://php.net/), 80 bytes
Output as rgba value, Input without `#`
```
$h=array_map(hexdec,str_split($argn,2));$h[3]/=255;echo"rgba(",join(",",$h),")";
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoMClkliUnmerZGCQlmZgYGGgZP1fJcM2sagosTI@N7FAIyO1IiU1Wae4pCi@uCAns0QDrF7HSFPTWiUj2jhW39bI1NQ6NTkjX6koPSlRQ0knKz8zD0gp6ahkaOooaQIN/A8A "PHP – Try It Online")
# [PHP](https://php.net/), 88 bytes
Output as rgba value, Input with `#`
```
for(;$i<7;)$h[]=hexdec($argn[++$i].$argn[++$i]);$h[3]/=255;echo"rgba(",join(",",$h),")";
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoMClkliUnmerpGxgkJZmYGBhoGT9Py2/SMNaJdPG3FpTJSM61jYjtSIlNVkDrDJaW1slM1YPia1pDVRkHKtva2Rqap2anJGvVJSelKihpJOVn5kHpJR0VDI0dZQ0gQb/BwA "PHP – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 139 bytes
```
C(x){x=x>57?x-87:x-48;}
#define Z C(h[i])*16+C(h[++i]))
i;f(char*h){printf("rgba(");for(i=0;i<6;i++)printf("%i, ",Z;printf("%g)",(Z/256.);}
```
[Try it online!](https://tio.run/##RYxNDoIwFIT3PUVTY9JHqVYjP7GCC2@BcYHYwluIhrhoQjh7LQt0VvPNTKaRbdN4f@EORle4MsnOTubZ0clDrieyehiLvaEVvfDuijeIdqmYrRABgKC2vOnqIepgfA/YfyxnQ3uvOQNtXwPHQmk8pRqFgKVfY0xZXOkft8BiXm33SboBPfmQ0meNPYeR0KBlZ41SxuSKypLO9/8kEJn8Fw "C (gcc) – Try It Online")
My other attempt clocked in at [145 bytes](https://tio.run/##TUy7CsIwFN3zFZeIkNs2GsU@MLQO/YKuikONSZvBIsUhUPrtMQgtnjOdp@KdUt7XzOHkSlel@cXxIj87firkTDZPbeygoYGa9Tcbx3eMDlm8ClwbV3iPdvgYRrc2AZo0xErDVN@OUY@TLYVc8rF7tIyivP64rjqkCWv2xzTboZx9cOHV2oHhRCBg6RkthNaFAF5BOPlzgiKz/wI). I'm not much of a C golfer, so this could probably be shorter.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
2ôH`255/)
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f6PAWj4Sj@6r0Nf//NzBwczMwsDAAAA "05AB1E – Try It Online")
At least we have supporters like [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) to often use some common sense...(that's what you get for golfing all day and then you start producing stuff like `2ô16öRć255/¸ìR` ಠ\_ಠ)
[Answer]
# Vim, 46 bytes
```
:s/../$((16#&)) /g␊iecho ␛$hhi*100/255␛:w !sh␊
```
Takes input without the `#` and returns by printing on the screen.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes
```
Øhi$€’s2ḅ⁴÷4¦⁹
```
[Try it online!](https://tio.run/##AS8A0P9qZWxsef//w5hoaSTigqzigJlzMuG4heKBtMO3NMKm4oG5////IjAwZmYwMDgwIg "Jelly – Try It Online")
**How it Works**
```
Øhi$€’s2ḅ⁴÷4¦⁹ - main link, takes input without # and all lowercase
$€ - to each input character:
i - return its 1-based index in
Øh - the string "0123456789abcdef"
’ - decrement (otherwise 0 is mapped to 1 and f to 16)
s2 - split the characters into groups of two
ḅ⁴ - convert from base 16 to decimal
4¦ - on the fourth element:
÷ - divide by
⁹ - 256
```
*-1 byte thanks to @EricTheOutgolfer*
[Answer]
# PHP, 72 bytes
Jörg´s array output version is unbeatable; but there are other options:
```
<?=($a=hexdec($argn))>>24,",",255&$a>>16,",",255&$a>>8,",",(255&$a)>256;
```
Run as pipe with `-F`. `#` does not matter, plain csv output
or **73 bytes** (run with `-R`):
```
for($a=hexdec($argn);$i++<4;)echo(255&$a>>32-8*$i)/($i<4?:256),","[$i>3];
```
**74 bytes** with the spaces:
```
<?=($a=hexdec($argn))>>24,$c=", ",255&$a>>16,$c,255&$a>>8,$c,(255&$a)>256;
```
not so plain, **81 bytes**:
```
rgba(<?=($a=hexdec($argn))>>24,$c=", ",255&$a>>16,$c,255&$a>>8,$c,(255&$a)/256?>)
```
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), ~~47~~ ~~45~~ 41 bytes
```
[2#<$unhexmap(1::256)/', '#`'rgba(@id)'!]
```
[Try it online!](https://tio.run/##JcbRCoIwFIDh@z3FCYOzQdFxqcWI8D1EaG1nLcSSVKinX1L/xc83TtZ17FNqdHZaz4/I794OMjdGl5Xa4QYwu@DrdrWyvnuFqzbVJgghkSgEoiMhYPhFfzJ779xCyvW@KKsDKtHAaD@AsD0vG@YJArCLT2iBrYvpCw "Stacked – Try It Online")
[Answer]
# Excel, 99 bytes
```
=HEX2DEC(LEFT(A1,2))&","&HEX2DEC(MID(A1,3,2))&","&HEX2DEC(MID(A1,5,2))&","&HEX2DEC(RIGHT(A1,2))/256
```
[Answer]
# SmileBASIC, 50 bytes
```
INPUT H$RGBREAD VAL("&H"+H$)OUT R,G,B,A?R,G,B,A/#L
```
The hexadecimal string is converted to a number using VAL(), then RGBREAD extracts each byte. #L is a constant with the value 256.
RGBREAD is designed to extract the channels from an ARGB color, but really it just splits a 4 byte integer into 4 separate bytes, so the order doesn't matter.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~73~~ 62 bytes
```
$args-split'(..)'-ne''|%{"0x$_"/(1,1,1,256)[$i++]}|% *g "0.##"
```
-11 bytes thanks to Mazzy
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SpmCrUP1fJbEovVi3uCAns0RdQ09PU103L1VdvUa1WsmgQiVeSV/DUAcEjUzNNKNVMrW1Y2trVBW00hWUDPSUlZX@13KpAQ1SMjBISzMwsDBQ4lJSgoikGaQZphmlGSj9BwA "PowerShell Core – Try It Online")
[Answer]
## JS ES2015, 84 bytes
```
$=>{a=[1,3,5,7].map(b=>eval("0x"+$.substr(b,2)));a[3]=(a[3]/256);return a.join(",")}
```
this is a function. Run it using
```
( CODE )("#00ff0080")
```
[Answer]
# q/kdb+, 43 bytes
**Solution:**
```
{(16 sv'(.Q.n,6#.Q.a)?/:2 cut x)%1 1 1 256}
```
**Example:**
```
q){(16 sv'(.Q.n,6#.Q.a)?/:2 cut x)%1 1 1 256}"00ff0080"
0 255 0 0.5
```
**Explanation:**
```
{ } / anonymous lambda function
2 cut x / split input into 2-char length lists
?/: / returns index where (each-right) item is found in 'the list'
( ) / 'the list'
6#.Q.a / Q.a is lowercase alphabet, 6# takes first 6 chars
.Q.n, / Q.n is "012..89", so prepend this onto the "abcdef"
16 sv' / converts each index from base 16 to base 10
( )%1 1 1 256 / divide this output by 1,1,1,256 to get alpha in 0..1 range
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 24 bytes
Requires `⎕IO←0` which is default on many systems. Prompts for input as uppercase without `#`.
```
256÷⍨@3⊢16⊥⍉4 2⍴⍞⍳⍨⎕D,⎕A
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862ovSkxL/G5maHd7@qHeFg/GjrkWGZo@6lj7q7TRRMHrUu@VR77xHvZuBckBdLjpAwvE/UNd/BTAAaeYyMHBzMzCwMAAA "APL (Dyalog Unicode) – Try It Online")
`⎕D,⎕A` **D**igits followed by **A**lphabet
`⍞⍳⍨` prompt for text input (mnemonic: console with quote) and find the **ɩ**ndex of each letter in that
`4 2⍴` **r**eshape as four row two column matrix
`⍉` transpose (because base conversion works columnwise)
`16⊥` evaluate as **base** sixteen
`⊢` yield (serves to separate 3 and 16)
`256÷⍨@3` divide the 4th element by 256
[Answer]
# [Yabasic](http://www.yabasic.de), 96 bytes
Yet another [basic](/questions/tagged/basic "show questions tagged 'basic'") answer; Takes input as string and outputs to the console.
```
Input""a$
For i=1To 7Step 2
?Dec(Mid$(a$,i,2))/(j+1);
If i=5Then j=255Fi
If i<7Then?", ";Fi
Next
```
[Try it online!](https://tio.run/##q0xMSizOTP7/3zOvoLRESSlRhcstv0gh09YwJF/BPLgktUDBiMveJTVZwzczRUUjUUUnU8dIU1NfI0vbUNOayzMNqNQ0JCM1TyHL1sjU1C0TLGRjDhKyV9JRULIGCvmlVpT8/29gkJZmYGBhAAA "Yabasic – Try It Online")
[Answer]
# Excel VBA, 90 bytes
An anonymous VBE immediate window function that takes input from the range `[A1]` and outputs to the VBE immediate window.
```
For i=1To 7Step 2:[B1]=i:?[Hex2Dec(Mid(A1,B1,2))]/IIf(i=7,256,1)&""+IIf(i<7,", ","");:Next
```
[Answer]
# Batch, 150 bytes
```
@for /f "tokens=2-5 delims=. " %%a in ('ping/n 1 0x%1^|find "h"')do @echo/%%a,%%b,%%c&set/ay=%%d*100/255@set y=0.%y%@if %y%==0.100 set y=1@echo/%y%
```
[Answer]
# [Perl 6](http://perl6.org/), 42 bytes
```
{m:g/../.map({:16(~$_)}) »/«(1,1,1,255)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OtcqXV9PT18vN7FAo9rK0EyjTiVes1ZT4dBu/UOrNQx1QNDI1FSz9r@1QnFipUKahrqBQVqagYGFgbqm9X8A "Perl 6 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 62 bytes
```
lambda h:[int(h[x:x+2],16)for x in(0,2,4)]+[int(h[6:],16)/255]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHDKjozr0QjI7rCqkLbKFbH0EwzLb9IoUIhM0/DQMdIx0QzVhuqwswKLK1vZGoa@7@gCCSYpqFuYJCWZmBgYaCuqfkfAA "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 54 bytes
```
lambda h:[int(h[i-2:i],16)/2.**(8&i)for i in(2,4,6,8)]
```
[Try it online!](https://tio.run/##DcrBDkAwDADQX@mJTYpqRBaJL8GBSLMmzLK4@Prxzi@@j78DZ5mWfG7Xfmzgx1nDY/ysNY@6YjfYlpuqMq5QK3cCBQ2GsccBnV1zTH8HMSWRCJGj0uYP "Python 2 – Try It Online")
] |
[Question]
[
**Challenge**
Your goal is to write a program that prints another program.
That printed program should print another program, and the new program should print another program, until the end.
**Rules**
1. Each program must less than 256 bytes. (If this needs to be changed, leave a comment)
2. The last program must be an empty program.
3. There must be a finite number of programs, so the program cannot be a quine.
4. The programs must all run in the same language.
5. No input is allowed.
6. The winning program is the program that prints as many programs as possible, counting itself.
Good Luck!
[Answer]
# CJam, 4.56 × 10526 programs
```
2D#2b{"\256b_(256b:c'\s`_:(er`":T~{;38'ÿ*`{:T~{;63'ÿ*`{:T~{;88'ÿ*`{:T~{;114'ÿ*`{:T~{;140'ÿ*`{:T~{;166'ÿ*`{:T~{;192'ÿ*`{:T~{;219'ÿ*`{Q?\"_~"}s(\T}?\"_~"}s(\T`}?\"_~"}s(\T`}?\"_~"}s(\T`}?\"_~"}s(\T`}?\"_~"}s(\T`}?\"_~"}s(\T`}?\"_~"}s(\T`}?\"_~"}_~
```
Exact score: **254219 + 254192 + 254166 + 254140 + 254114 + 25488 + 25463 + 25438 + 25413 + 3**
All programs have to be saved using the ISO-8859-1 encoding to comply with the file size limit.
*Thanks to [@ChrisDrost](https://codegolf.stackexchange.com/users/3913/chris-drost) who pointed out a bug and suggested the nesting approach.*
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=2D%232b%7B%22%5C256b_(256b%3Ac'%5Cs%60_%3A(er%60%22%3AT~%7B%3B38'%C3%BF*%60%7B%3AT~%7B%3B63'%C3%BF*%60%7B%3AT~%7B%3B88'%C3%BF*%60%7B%3AT~%7B%3B114'%C3%BF*%60%7B%3AT~%7B%3B140'%C3%BF*%60%7B%3AT~%7B%3B166'%C3%BF*%60%7B%3AT~%7B%3B192'%C3%BF*%60%7B%3AT~%7B%3B219'%C3%BF*%60%7BQ%3F%5C%22_~%22%7Ds(%5CT%7D%3F%5C%22_~%22%7Ds(%5CT%60%7D%3F%5C%22_~%22%7Ds(%5CT%60%7D%3F%5C%22_~%22%7Ds(%5CT%60%7D%3F%5C%22_~%22%7Ds(%5CT%60%7D%3F%5C%22_~%22%7Ds(%5CT%60%7D%3F%5C%22_~%22%7Ds(%5CT%60%7D%3F%5C%22_~%22%7Ds(%5CT%60%7D%3F%5C%22_~%22%7D_~).
## 254219 + 2 ≈ 4.56 × 10526 programs
The line share of the score can be achieved by the following, much simpler program1.
```
"ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"
{\256b_(256b:c'\s`_:(er`Q?\"_~"}_~
```
Running this program produces the program
```
"ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿþ"
{\256b_(256b:c'\s`_:(er`Q?\"_~"}_~
```
and after **254219 - 1** more iterations, the program
```
{\256b_(256b:c'\s`_:(er`Q?\"_~"}_~
```
This last non-empty program exits with an error2 and prints nothing (the empty program).
### How it works
Assume the string is already on the stack.
```
{ e# Push a code block.
\ e# Swap the string on top of the code block.
e# This will cause a runtime error if there is no string on the stack.
256b e# Convert the string (treated as a base-256 number) to integer (I).
_( e# Copy the integer and decrement the copy.
256b e# Convert the integer into the array of its base-256 digits.
:c e# Cast each base-256 digit to character. Converts from array to string.
'\s e# Push a string that contains a single backslash.
` e# Push its string representation, i.e., the array ['" '\ '\ '"].
_:( e# Push a copy and decrement each character. Pushes ['! '[ '[ '!].
er e# Perform transliteration to replace "s with !s and \s with [s.
e# This skips characters that require escaping.
` e# Push its string representation, i.e., surround it with double quotes.
Q e# Push an empty string.
? e# Select the first string if I is non-zero, the empty string otherwise.
\ e# Swap the selected string with the code block.
"_~" e# Push that string on the stack.
} e#
_~ e# Push a copy of the code block and execute it.
e# The stack now contains the modified string, the original code block
e# and the string "_~", producing an almost exact copy of the source.
```
## 254192 ≈ 5.35 × 10461 more programs
This is where things get a little crazy.
The first program is highly compressible. By writing a similar program that, instead of the empty program, eventually produces the first program from the above section, we can improve the score by **254192** programs3.
The program
```
"ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ"
{"\256b_(256b:c'\s`_:(er`":T~{;219'ÿ*`{Q?\"_~"}s(\T}?\"_~"}_~
```
is similar to the first program of the previous section, and running the former and its output for **254192** iterations produces the latter.
Assume the string is already on the stack:
```
{ e# Push a code block.
"\256b_(256b:c'\s`_:(er`" e# Push that string on the stack.
e# The characters inside it behave exactly as
e# they did in the previous section.
:T~ e# Save the string in T and evaluate it.
{ e# If the integer I is non-zero, keep the generated
e# string; else:
; e# Pop the code block from the stack.
219'ÿ*` e# Push a string of 219 ÿ's (with double quotes).
{Q?\"_~"} e# Push that block on the stack.
s e# Push its string representation.
(\ e# Shift out the { and swap it with the tail.
T e# Push T.
}? e#
\ e# Swap the selected string with the code block
e# or T with the tail of the code block.
"_~" e# Push that string on the stack.
} e#
_~ e# Push a copy of the code block and execute it.
```
## Moar programs
The first program of the previous section is still highly compressible, so we can apply a similar method and write a program that, after **254166** iterations, produces the aforementioned program.
Repeating this technique over and over again until we hit the 255 byte limit, we can add a total of **254166 + 254140 + 254114 + 25488 + 25463 + 25438 + 25413 + 1 ≈ 1.59 × 10399** programs to those of the previous sections.
---
1 Newline added for clarity.
2 Per [consensus on Meta](http://meta.codegolf.stackexchange.com/a/4781), this is allowed by default.
3 or 0.0000000000000000000000000000000000000000000000000000000000000012 %
[Answer]
# JavaScript, 1000 programs
```
x=999;
q=";alert(x=999?`q=${JSON.stringify(q)+q}`.split(x).join(x-1):``)";
alert(
x ? `x=999;q=${JSON.stringify(q)+q}`.split(x).join(x-1) // basically .replaceAll(x, x-1)
: ``
)
```
Whether this is valid depends on precisely how to understand the third rule.
[Answer]
# Ruby, 1.628 × 10^237 programs
```
a=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;_="a=%#x-1;_=%p;puts _%%[a,_]if a";puts _%[a,_]if a
```
Same approach as my Perl answer, but because Ruby handles big ints already, it's easier to store as hex.
---
# Ruby, 9.277 × 10^90 programs
```
a=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;b=0xf;(b<1)&&(a-=1)&&b=eval('0x'+'f'*(74-("%x"%a).length));_="a=%#x;b=%#x;(b<1)&&(a-=1)&&b=eval('0x'+'f'*(74-('%%x'%%a).length));_=%p;puts _%%[a,b-1,_]if a";puts _%[a,b-1,_]if a
```
So this attempt is a slightly different variation on the previous quine-like, but because of all the extra functions I'm not getting the number anywhere near as high as the other one... Was interesting to try another approach though!
[Answer]
# Python 2, 9.7\*10^229 programs
```
O=0
if len(hex(O))<191:print"O=0x%x"%(O+1)+open(__file__).read()[-68:]
```
[Answer]
# C, 2.2 \* 10^177 programs
```
#define S(s)char*q=#s,n[]="#####################################################################################################";i;s
S(main(){while(n[i]==91)n[i++]=35;i==101?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
```
It's not perfect, but pretty good. I mean it's exactly `255` bytes long and generates programs of the same length. You could probably fiddle arround some more to gain some more programs, but I'll leave it as it is for now.
The program is based of a simple C quine. Additionally there's a quite simple counting algorithm which counts through all possible values of the char array `n`. We have as many programs as permutations of the string `n`.
The char range is limmited to a range from `#` (=35) to `[` = (91). That's because I don't want any `"` or `\` in the string, because they need to be escaped.
The program generation ends when all values in the char array `n` are `[`. Then it outputs a simple dummy program `main(){}`, which itself outputs nothing.
```
#define S(s) char *q = #s; /* have the source as a string */ \
char n[] = "#####################################################################################################"; \
int i; \
s /* the source itself */
S(main() {
while(n[i]=='[') /* clear out highest value, so next array element be incremented */
n[i++]='#';
i==101 /* end of array reached? output dummy program */
? q = "main(){}"
: n[i]++; /* count one up in the whole array */
printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)", n, q);
})
```
As a demonstration that it should work I just changed the limits, so only characters between ASCII-Code `35` and `36` are used and only 4 array elements.
The resulting programs are
```
% echo > delim; find -iname 'program_*.c' | xargs -n1 cat delim
#define S(s)char*q=#s,n[]="####";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$###";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="#$##";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$$##";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="##$#";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$#$#";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="#$$#";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$$$#";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="###$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$##$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="#$#$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$$#$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="##$$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$#$$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="#$$$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="$$$$";i;s
S(main(){while(n[i]==36)n[i++]=35;i==4?q="main(){}":n[i]++;printf("#define S(s)char*q=#s,n[]=\"%s\";i;s\nS(%s)",n,q);})
#define S(s)char*q=#s,n[]="####";i;s
S(main(){})
```
This outputs `2^4 + 1 = 17` different programs.
So the program above outputs `((91-35)+1)^101 + 1 = 57^101 + 1 ~= 2.2 * 10^177` different programs.
I'm not entierly sure if this counts, or if my calculation is even correct
[Answer]
# Perl, 1 × 10^163
Otherwise this is a pretty basic quine, shrunk down to as few chars as possible, that only runs whilst the counter isn't `0`.
```
use bigint;$i=9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999||die;$_=<<'e';eval
print"use bigint;\$i=$i-1||die;\$_=<<'e';eval
${_}e
"
e
```
[Answer]
# Common Lisp, 10113-1
```
(LET ((X
99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999))
(WHEN #1=(PLUSP X)
#2=(SETF *PRINT-CIRCLE* T)
#3=(PRINT (LIST 'LET `((X ,(1- X))) (LIST 'WHEN '#1# '#2# '#3#)))))
```
* There are 113 nines.
* The next program has 112 nines followed by a 8
* The next program has 112 nines followed by a 7
* ...
The number of nines is limited by the maximum size of code, 256, *taking into account* the spaces introduced by the printer.
[Answer]
# Perl, 1.4\*10^225
```
use bignum;open$F,__FILE__;$_=<$F>;s/0x\w+/($&-1)->as_hex/e;0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff&&print
```
Similar approach to python; same result!
[Answer]
# Python, 1 × 10^194 programs
```
n=99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
if n:print open(__file__).read().replace(str(n),str(n-1))
```
This must be run from a file, **not** an interactive repl.
It is not a quine.
Thanks to @The Turtle for helping me save 3 bytes, which is more room for nines!
Thanks to @poke for helping me save 2 bytes, which is more room for nines!
[Answer]
## [><>](http://esolangs.org/wiki/Fish), 65534 (?) Programs
I've added a question mark next to 65533 since I have yet to verify that it can print 65533 (although I have reason to believe it should). Once I have a bit more time, I'm going to figure out a way to test it.
```
":?!;1-r00gol?!;a0.�
```
You can try it online [here](http://fishlanguage.com/).
The gist of this program is that it changes the output of the character at the very end and then decrements its numerical value before printing. I got 65534 programs because the ascii value of the character at the end of the code is 65533, so counting the first program we have 65534 (if you count the empty program 65535, I guess). The last program "returned" is nothing; it simply ends when the character value is 0.
I'm quite sure it will be able to print a character for all iterations: I couldn't find a definitive source for how many characters ><> can print, but there are characters directly below 65533, numerically.
Let me know if there are any problems with this implementation; I'm a little unsure about the validity of my entry.
---
## Explanation
I have shamelessly stolen the idea of using a single quotation mark to create a pseudo-quine from the ><> wiki and a comment I saw here once.
```
":?!;1-r00gol?!;a0.�
" begins string parsing
:?!; terminates program if final character is 0, numerically
1- decrements final character by 1
r reverses stack
00g grabs quotation mark (fancy way of putting " ")
ol?!; prints and terminates if stack is empty
a0. jumps back to o to loop
```
What it does is parse everything after the quotation mark as characters, then decrement the last one. From there it just reverses the stack (so as to print in the right order), pushes a quotation mark onto the stack, and then prints until the stack is empty.
[Answer]
# Bash, 52 programs
Utterly uninspired, and (hopefully) solidly in last place.
```
echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo
```
] |
[Question]
[
You have a box with a single digit number in each corner:
```
1|2
---
3|4
```
If we concatenate the digits along rows left to right, we get 12 and 34. If we concatenate the digits along columns top to bottom, we get 13 and 24. If we add all of these numbers, we get 12+34+13+24 = 83.
### Challenge
Write a program to print all such boxes where the sum calculated as above is equal to 100.
Assuming each corner contains a single digit number between 1 and 9, there are 9 combinations: 1157, 1247, 1337, 1427, 1517, 2138, 2228, 2318, and 3119. (Note that there are 25 combinations if we include 0, but we're not for this challenge.)
Note that the example 1234 doesn't work since 12+34+13+24 does not equal 100.
### Input
None
### Output
Answer boxes in the following format:
```
A|B
---
C|D
```
Output should be printed to STDOUT or closest alternative.
### Rules
* AB + CD + AC + BD = 100
* Each corner will contain the positive integers 1-9 only.
* 0 is excluded.
* Numbers can be used more than once.
* You need to draw the boxes, as above. (`A|B\n---\nC|D\n`)
* You need to output all valid answers.
* An additional trailing newline is fine.
* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
* Standard loopholes and T&C's apply.
This is my first submission so please do let me know if I need to clarify anything.
[Answer]
# Pyth, 42 38 34 bytes
```
V^ST4IqC\ds*VNsM^,T1 2Xj\|N3"
---
```
The trailing newline in the code is important. The main reason I'm competitive is because I use the vector dot product of `[1, 1, 5, 7]` and `[20, 11, 11, 2]` and compare it to 100.
[Answer]
# Ruby, 71
As hardcoding is not disallowed (and in any case it is difficult to draw a line) here's a partial hardcoded answer.
```
1.upto(3){|i|1.upto(7-i*2){|j|print i,?|,j,'
---
',8-j-2*i,?|,i+6,'
'}}
```
Explanation
The formula for a solution is as follows:
```
A*20+(B+C)*11+D*2=100
```
By modular arithmetic arguments, we see that A and D must differ by a constant amount, such that `(A*20+D*2)%11` is constant. In fact D=A+6. The `i` loop iterates through the three possible values of A.
The value of B can be anything from 1 to `7-i*2` and the total of B and C must be `14-A-D`. Thus we obtain the following expressions, which are printed. Ruby allows literal newlines in strings enclosed in `''`
```
i | j
------------------
8-j-2*i | i+6
```
[Answer]
## Java, ~~202~~ ~~200~~ 198
Trying for the first time :D
EDIT: saved 2 bytes with slightly smaller calculation found in an other comment.
```
class C{public static void main(String[]c){for(int i=0;++i<5;)for(int j=0;++j<7;)for(int k=0;++k<10;)for(int l=0;++l<10;)if(20*i+11*(j+k)+2*l==100)System.out.printf("%s|%s%n---%n%s|%s%n",i,j,k,l);}}
```
[Answer]
## Batch - 187 bytes
Brute force.
```
@!! 2>nul||cmd/q/v/c%0&&exit/b
set y=for /l &set z= in (1,1,9)do
%y%%%a%z%%y%%%b%z%%y%%%c%z%%y%%%d%z%set/aa=%%a%%b+%%c%%d+%%a%%c+%%b%%d&if !a!==100 echo %%a^|%%b&echo ---&echo %%c^|%%d
```
Un-golfed it's *slightly* less disgusting:
```
@echo off
setLocal enableDelayedExpansion
for /l %%a in (1,1,9) do (
for /l %%b in (1,1,9) do (
for /l %%c in (1,1,9) do (
for /l %%d in (1,1,9) do (
set/aa=%%a%%b+%%c%%d+%%a%%c+%%b%%d
if !a!==100 (
echo %%a^|%%b
echo ---
echo %%c^|%%d
)
)
)
)
)
```
[Answer]
# CJam, 40 bytes
```
A4m*{[KBBY].*:+56=},{:)2/'|f*"
---
"*N}/
```
The approach for finding the combinations is different from @Optimizer's, but the code for printing them is identical.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=A4m*%7B%5BKBBY%5D.*%3A%2B56%3D%7D%2C%7B%3A)2%2F'%7Cf*%22%0A---%0A%22*N%7D%2F).
### How it works
```
A4m* e# Push all vectors of length 4 with coordinates in [0 ... 9].
e# We'd normally use [0 ... 8] here, but "9 4m*" is 1 byte longer and
e# "A4m*" doesn't produce any false positives.
{ e# Filter the vectors:
[KBBY].* e# Multiply the elements of the vector by 20, 11, 11 and 2.
:+ e# Add all four products.
56= e# Check if the sum is 56. 56 is used instead of 100 since all elements
e# of the vector will be incremented and 56 + 20 + 11 + 11 + 2 == 100.
}, e# Keep only vectors for which = pushed a truthy value.
{ e# For each vector:
:) e# Increment each coordinate.
2/ e# Split into pair.
'|f* e# Join each pair, delimiting by '|'.
"
---
"* e# Join the two pairs, delimiting by "\n---\n".
N e# Push "\n".
}/ e#
```
[Answer]
# Haskell, 107 131 bytes
```
s=show
r=[1..9]
v=putStr$unlines[s a++"|"++s b++"\n---\n"++s c++"|"++s d++"\n"|a<-r,b<-r,c<-r,d<-r,(2*a+b+c)*10+b+2*d+c==100]
```
The second version of my first Haskell program ever!
This time with display as per requirements, shamelessly stolen adapted from nimi's (well I did some research but it seems there aren't so may efficient ways to display characters in Haskell so that putStr$unlines is hard to avoid).
And...apart from the factorisation of the formula at the end, it's still readable =)
[Answer]
# Haskell, ~~125~~ 121 bytes
```
s=show
f=putStr$unlines[s a++'|':s b++"\n---\n"++s c++'|':s d|[a,b,c,d]<-mapM id$"abcd">>[[1..9]],20*a+11*(b+c)+2*d==100]
```
Usage:
```
*Main> f
1|1
---
5|7
1|2
---
4|7
1|3
---
3|7
1|4
---
2|7
1|5
---
1|7
2|1
---
3|8
2|2
---
2|8
2|3
---
1|8
3|1
---
1|9
```
`>>` in `"abcd">>[[1..9]]` makes a list with 4 (length of 1st parameter) copies of the second element, i.e. `[[1..9],[1..9],[1..9],[1..9]]`. `mapM id` makes a list of all combinations thereof, i.e `[0,0,0,0]` to `[9,9,9,9]`. Keep those that sum up `100` and build a string with the box of it. Print all boxes.
Thanks @Mauris for 1 byte and making me review my post to find 3 more.
[Answer]
# Python 2, ~~145~~ 129 Bytes
I'm currently toying with a few different methods of calculating which should be shorter than what is outlined, but I will post what I have now.
```
i=int
for k in range(1000,9999):
a,b,c,d=`k`
if i(a+b)+i(c+d)+i(a+c)+i(b+d)==100and not'0'in`k`:print a+'|'+b+'\n---\n'+c+'|'+d
```
[Answer]
# CJam, ~~43~~ 42 bytes
```
A,1>4m*{2/_z+Afb:+100=},{2/'|f*"
---
"*N}/
```
Explanation to follow.. by today EOD
[Try it online here](http://cjam.aditsu.net/#code=A%2C1%3E4m*%7B2%2F_z%2BAfb%3A%2B100%3D%7D%2C%7B2%2F%27%7Cf*%22%0A---%0A%22*N%7D%2F)
[Answer]
# Python 3, 159
Quick and dirty.
```
N='123456789'
D='%s|%s\n'
O=D+'---\n'+D
I=int
[print(O%(a,b,c,d)if I(a+b)+I(c+d)+I(a+c)+I(b+d)==100 else'',end='')for a in N for b in N for c in N for d in N]
```
[Answer]
# R, 165 bytes
```
e=expand.grid(d<-1:9,d,d,d)
a=apply
o=a(e[a(e,1,function(x)20*x[1]+11*(x[2]+x[3])+2*x[4]==100),],1,function(x)cat(x[1],"|",x[2],"\n---\n",x[3],"|",x[4],"\n",sep=""))
```
This would have been significantly shorter had I chosen to hard-code the output in some way. Like a few other solutions, this takes advantage of the identity 20 *x*1 + 11 (*x*2 + *x*3) + 2 *x*4 = 100.
Ungolfed + explanation:
```
# Create a matrix where each row is a combination of the digits 1-9
e <- expand.grid(1:9, 1:9, 1:9, 1:9)
# Filter the rows of the matrix using the aforementioned identity
e <- e[apply(e, 1, function(x) 20*x[1] + 11*(x[2]+x[3]) + 2*x[4] == 100), ]
# Print each row formatted into boxes
o <- apply(e, 1, function(x) cat(x[1], "|", x[2], "\n---\n", x[3], "|", x[4], sep = ""))
```
You may be wondering why the last statement is an assignment. As it turns out, the `cat` function, which concatenates and prints, returns a value of `NULL`. When you call `cat` from within a function like `apply`, the output will be followed by `NULL`, which is undesirable. There are two ways around this: assign it to a variable or wrap it in `invisible`. Here I've opted for the former since it's significantly shorter.
You can [try it online](http://www.r-fiddle.org/#/fiddle?id=dpMoCVjz).
[Answer]
# Java, 450
My first (ungolfed) attempt looked like this:
```
class B{
public static void main(String[]a){
for(int i=1;i<10;i++)
for(int j=1;j<10;j++)
for(int k=1;k<10;k++)
for(int l=1;l<10;l++)
if(Integer.parseInt(i+""+j)+Integer.parseInt(k+""+l)+Integer.parseInt(i+""+k)+Integer.parseInt(j+""+l)==100){
System.out.println(i+"|"+j);
System.out.println("---");
System.out.println(k+"|"+l+"\n");
}
}
}
```
[Answer]
## PowerShell , 98
adapted steveverrill's formula
```
:\>cat printbox.ps1
1..9|%{for($j=1;$j-lt10;$j++){if(($k=(8-$j-2*$_))-gt0){"{0}|{1}`n---`n{2}|{3}"-f$_,$j,$k,
($_+6)}}}
:\>powershell -f printbox.ps1
1|1
---
5|7
1|2
---
4|7
1|3
---
3|7
1|4
---
2|7
1|5
---
1|7
2|1
---
3|8
2|2
---
2|8
2|3
---
1|8
3|1
---
1|9
```
] |
[Question]
[
Consider 30 by 30 [Toeplitz](https://en.wikipedia.org/wiki/Toeplitz_matrix) matrices all of whose entries are 0 or 1. This challenge is a simple optimization challenge to find the matrix with the largest determinant possible.
**Input** None
**Output** A 30 by 30 Toeplitz matrix all of whose entries are 0 or 1 along with its determinant.
**Score** The determinant of the matrix you output. If two people get the same score, the first answer wins.
**Leading entries so far**
* 65,455,857,159,975 in **Matlab** by Nick Alger (roughly (10^13.8)
* 65,455,857,159,975 in **Python** by isaacg (roughly 10^13.8)
* 39,994,961,721,988 in **Mathematica** by 2012rcampion ( roughly 10^13.6)
* 39,788,537,400,052 in **R** by Flounderer (roughly 10^13.6)
* 8,363,855,075,832 in **Python** by Vioz- (roughly 10^12.9)
* 6,984,314,690,903 in **Julia** by Alex A. (roughly 10^12.8)
---
**Annoying additional constraints July 16 2015**
If it is at all possible, please use arbitrary or high precision arithmetic to compute the final output determinant so that we can be sure what it really is (it should always be an integer). In python [this](https://stackoverflow.com/questions/6876377/numpy-arbitrary-precision-linear-algebra) should be helpful.
[Answer]
# Matlab, 65,455,857,159,975 (10^13.8159)
The method is [gradient ascent](https://en.wikipedia.org/wiki/Gradient_descent) in the interior of the cube [0,1]^59, with many random initial guesses, and rounding at the end to make everything zeros and ones.
**Matrix:**
```
0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0
0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1
1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1
1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1
1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0
0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1
1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1
1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1
1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0
0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1
1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0
0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0
0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0
0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1
1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0 0
0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1 0
0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0 1
1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 0
0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1
1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1
1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0
0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0 1
1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0 0
0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0
0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0 0
0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 0
0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1
1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1
1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1
1 1 1 0 0 0 0 1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 0 1 1 1 0 0
```
**Code:**
```
% Toeplitz 0-1 determinant optimization
n = 30;
m = n + n-1;
toeplitz_map = @(w) toeplitz(w(n:-1:1), w(n:end));
objective = @(w) det(toeplitz_map(w));
detgrad = @(A) det(A)*inv(A)';
toeplitz_map_matrix = zeros(n^2,m);
for k=1:m
ek = zeros(m,1);
ek(k) = 1;
M = toeplitz_map(ek);
toeplitz_map_matrix(:,k) = M(:);
end
gradient = @(w) (reshape(detgrad(toeplitz_map(w)),1,n^2)*...
toeplitz_map_matrix)';
%check gradient with finite differences
w = randn(m,1);
dw = randn(m,1);
s = 1e-6;
g_diff = (objective(w+s*dw) - objective(w))/s;
g = gradient(w)'*dw;
grad_err = (g - g_diff)/g_diff
warning('off')
disp('multiple gradient ascent:')
w_best = zeros(m,1);
f_best = 0;
for trial=1:100000
w0 = rand(m,1);
w = w0;
alpha0 = 1e-5; %step size
for k=1:20
f = objective(w);
g = gradient(w);
alpha = alpha0;
for hh=1:100
w2 = w + alpha*g;
f2 = objective(w2);
if f2 > f
w = w2;
break;
else
alpha = alpha/2;
end
end
buffer = 1e-4;
for jj=1:m
if (w(jj) > 1)
w(jj) = 1 - buffer;
elseif (w(jj) < 0)
w(jj) = 0 + buffer;
end
end
end
w = round(w);
f = objective(w);
if f > f_best
w_best = w;
f_best = f;
end
disp(trial)
disp(f_best)
disp(f)
end
M = toeplitz_map(w_best);
```
**The math behind computing the gradient:**
In the elementwise inner product (Ie., Hilbert-Schmidt inner product), the [gradient of the determinant](https://en.wikipedia.org/wiki/Determinant#Derivative) has Riesz representative G given by
G = det(A)A^(-\*).
The map, J, from optimization variables (diagonal values) to toeplitz matrices is linear, so the overall gradient g is the composition of these two linear maps,
g = (vec(G)\*J)',
where vec() is the [vectorization operator](https://en.wikipedia.org/wiki/Vectorization_%28mathematics%29) that takes a matrix and unfolds it into a vector.
**Interior gradient ascent:**
After this all you have to do is pick an initial vector of diagonal values w\_0, and for some small step sizes alpha iterate:
1. w\_proposed = w\_k + alpha\*g\_k
2. to get w\_(k+1), take w\_proposed and truncate values outside of [0,1] to 0 or 1
3. repeat until satisfied, then round everything to 0 or 1.
My result achieved this determinant after doing roughly 80,000 trials with uniform random initial guesses.
[Answer]
# Python 2 with Numpy, 65,455,857,159,975 ~= 10^13.8
This is hill climbing, as straightforward as can be. Final determinant calculation performed using SymPy to enusure an exact result. All matrices found with this determinant are circulant.
Matrices found with this determinant, given as value of diagonal from bottom left to upper right:
```
01000100101101000011100111011101000100101101000011100111011
01011101110011100001011010010001011101110011100001011010010
01100001000111011101001110100101100001000111011101001110100
01110100111010010110000100011101110100111010010110000100011
01011101110001000011010010111001011101110001000011010010111
01000101100010110100111101110001000101100010110100111101110
01000100101101000011100111011101000100101101000011100111011
```
The first one, as a matrix:
```
[[1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1]
[1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1]
[1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0]
[0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1]
[1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1]
[1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1]
[1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0]
[0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0]
[0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1]
[1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1]
[1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1]
[1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0]
[0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0]
[0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0]
[0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1 0]
[0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0 1]
[1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 0]
[0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1]
[1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1]
[1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1 0]
[0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0 1]
[1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 0]
[0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0]
[0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1]
[1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0 0]
[0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0 0]
[0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 0]
[0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1]
[1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0]
[0 1 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1]]
```
Code:
```
import numpy as np
import sympy as sp
import random
import time
SIZE = 30
random.seed(0)
def gen_diag():
return [random.randint(0, 1) for i in range(SIZE*2 - 1)]
def diag_to_mat(diag):
return [diag[a:a+SIZE] for a in range(SIZE-1, -1, -1)]
def diag_to_det(diag):
matrix = diag_to_mat(diag)
return np.linalg.det(matrix)
def improve(diag):
old_diag = diag
really_old_diag = []
while really_old_diag != old_diag:
really_old_diag = old_diag
for flip_at in range(SIZE * 2 - 1):
new_diag = old_diag[:]
new_diag[flip_at] ^= 1
old_diag = max(old_diag, new_diag, key=diag_to_det)
return old_diag
overall_best_score = 0
time.clock()
while time.clock() < 500:
best = improve(gen_diag())
best_score = diag_to_det(best)
if best_score > overall_best_score:
overall_best_score = best_score
overall_best = best
print(time.clock(), sp.Matrix(diag_to_mat(overall_best)).det(), ''.join(map(str,overall_best)))
mat = diag_to_mat(overall_best)
sym_mat = sp.Matrix(mat)
print(overall_best)
print(sym_mat.det())
```
[Answer]
# R, 39 788 537 400 052
Here is my attempt to do a genetic algorithm but only with asexual reproduction. I hope I understood the challenge correctly. Edit: sped it up a bit, tried a different random seed, and restricted to 100 generations.
```
options(scipen=999)
toeplitz <- function(x){
# make toeplitz matrix with first row
# x[1:a] and first col x[(a+1):n]
# where n is the length of x and a= n/2
# Requires x to have even length
#
# [1,1] entry is x[a+1]
N <- length(x)/2
out <- matrix(0, N, N)
out[1,] <- x[1:N]
out[,1] <- x[(N+1):length(x)]
for (i in 2:N){
for (j in 2:N){
out[i,j] <- out[i-1, j-1]
}
}
out
}
set.seed(1002)
generations <- 100
popsize <- 25
cols <- 60
population <- matrix(sample(0:1, cols*popsize, replace=T), nc=cols)
numfresh <- 5 # number of totally random choices added to population
for (i in 1:generations){
fitness <- apply(population, 1, function(x) det(toeplitz(x)) )
mother <- which(fitness==max(fitness))[1]
population <- matrix(rep(population[mother,], popsize), nc=cols, byrow=T)
for (i in 2:(popsize-numfresh)){
x <- sample(cols, 1)
population[i,x] <- 1-population[i,x]
}
for (i in (popsize-numfresh +1):popsize){
population[i,] <- sample(0:1, cols, replace=T)
}
print(population[1,])
print(fitness[mother])
print(det(toeplitz(population[1,]))) # to check correct
}
```
Output:
```
print(population[1, 1:(cols/2)]) # first row
print(population[1, (cols/2+1):(cols)]) # first column (overwrites 1st row)
to <- toeplitz(population[1,])
for (i in 1:(cols/2)) cat(to[i,], "\n")
1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0
0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1
1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0
0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0
0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0
0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1
1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1
1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1
1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1
1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0
0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1
1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1
1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1
1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0
0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0
0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 0
0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0
0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1
1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0
0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0
0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1
1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0
0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0 0
0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 0
0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0
0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1
1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0
0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1
1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1
1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 1 0 1
```
[Answer]
# Julia, 6,984,314,690,902.998
This just constructs 1,000,000 random Toeplitz matrices and checks their determinants, recording the maximum encountered. Hopefully someone will come up with an elegant analytical solution, but in the meantime...
```
function toeplitz(a, b)
n = length(a)
T = Array(Int, n, n)
T[1,:] = b
T[:,1] = a
for i = 2:n
T[i,2:n] = T[i-1,1:n-1]
end
T
end
d = 0
A = Any[]
for i = 1:1000000
# Construct two random 0,1 arrays
r1 = rand(0:1, 30)
r2 = rand(0:1, 30)
# Compute the determinant of a toeplitz matrix constructed
# from the two random arrays
D = det(toeplitz(r1, r2))
# If the computed determinant is larger than anything we've
# encountered so far, add it to A so we can access it later
D > d && begin
push!(A, (D, r1, r2))
d = D
end
end
M,N = findmax([i[1] for i in A])
println("Maximum determinant: ", M, "\n")
println(toeplitz(A[N][2], A[N][3]))
```
You can view the output [here](http://pastebin.com/6ujGmMkS).
[Answer]
# Mathematica, 39,994,961,721,988 (10^13.60)
A simple simulated annealing optimization method; no optimization or tuning yet.
```
n = 30;
current = -\[Infinity];
best = -\[Infinity];
saved = ConstantArray[0, {2 n - 1}];
m := Array[a[[n + #1 - #2]] &, {n, n}];
improved = True;
iters = 1000;
pmax = 0.1;
AbsoluteTiming[
While[improved || RandomReal[] < pmax,
improved = False;
a = saved;
Do[
Do[
a[[i]] = 1 - a[[i]];
With[{d = Det[m]},
If[d > best,
best = d;
current = d;
saved = a;
improved = True;
Break[];,
If[d > current || RandomReal[] < pmax (1 - p/iters),
current = d;
Break[];,
a[[i]] = 1 - a[[i]];
]
];
;
],
{i, 2 n - 1}];,
{p, iters}];
];
]
best
Log10[best // N]
a = saved;
m // MatrixForm
```
Sample output:
```
{20.714876,Null}
39994961721988
13.602
(1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0
0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0
0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0
0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0
0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1
1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0
0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0
0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0
0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0
0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1
1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1
1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0
0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1
1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1
1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 0
0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1
1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 1
1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1
1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1 0
0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1 1
1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0 1
1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 0
0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0
0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0 0
0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1 0
0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 1
1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0
0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1
1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1
1 1 0 1 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1
)
```
[Answer]
# Python 2, 8 363 855 075 832
This has a very basic, nearly nonexistent strategy involved.
```
from scipy import linalg
start = 2**28
mdet = 0
mmat = []
count = 0
powr = 1
while 1:
count += 1
v = map(int,bin(start)[2:].zfill(59))
m = [v[29:]]
for i in xrange(1,30):
m += [v[29-i:59-i]]
d = 0
try: d = linalg.det(m, check_finite=False)
except: print start
if d > mdet:
print d
print m
mdet = d
mmat = m
start += 1
powr = 1
else:
start += 2**powr
powr += 1
if start>(2**59-1):
start-=2**59-1
powr = 1
if count%10000==0: print 'Tried',count
```
Here is the best matrix it found after ~5,580,000 tries:
```
1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0 1 0 1 1 0 1 0
1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0 1 0 1 1 0 1
1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0 1 0 1 1 0
0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0 1 0 1 1
1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0 1 0 1
0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0 1 0
1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0 1
0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0
0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0 1 0
1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0 1
1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0
0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0
0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0
0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0
0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0
0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0
1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1
0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1 1
1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 1
1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0
1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1
1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1
1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1
1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0
1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1
1 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 1
0 1 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0
0 0 1 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1 0
1 0 0 1 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 1
0 1 0 0 1 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1
```
Still running...
] |
[Question]
[
Given an atomic number in the inclusive range `[1,118]`, write the shortest program/function that outputs one of `{2,8,18}` if the element with that atomic number follows the duplet, octet, or 18-electron rule, respectively.
### Notes
* The [Octet/Duplet/18-electron](https://en.wikipedia.org/wiki/Octet_rule) rule is a rule of thumb that describes how many electrons is needed for an element to completely fill their outer electron shells.
* The Duplet rule only applies to H, He, and Li (atomic numbers 1, 2, and 3)
* The 18-electron rule applies to all transition metals (21-30, 39-48, 72-80, 104-112), lanthanides (57-71), and actinides (89-103).
* The Octet rule applies to everything else (4-20, 31-38, 49-56, 81-88, 113-118).
### Test Cases
```
input => output
1 => 2
2 => 2
3 => 2
4 => 8
18 => 8
19 => 8
20 => 8
21 => 18
26 => 18
30 => 18
31 => 8
92 => 18
118 => 8
```
[Answer]
# Excel, 60 bytes
```
=IFNA(8+10*ISEVEN(MATCH(A1,{4,21,31,39,49,57,81,89,113})),2)
```
Input in cell `A1`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
I⊗§”|↖⁵Z·⁰χ⦄P↑mMρbl∨”N
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyW/NCknNUXDscQzLyW1QkPJEAhM0IElHBAjggqIk1fSUfDMKygt8SvNTUot0tAEAev//43M/uuW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Most of the program is simply a compressed look-up table.
```
”...” Compressed look-up table
§ Indexed by
N Input as a number
⊗ Doubled
I Cast to string
Implicitly print
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~19~~ 18 bytes
```
»µ7!¾∷»₄τ¦>ḣ∑∷+›²d
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCu8K1NyHCvuKIt8K74oKEz4TCpj7huKPiiJHiiLcr4oC6wrJkIiwiIiwiMTIiXQ==) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJBIiwi4oyIaOKMinfCqFMiLCLCu8K1NyHCvuKIt8K74oKEz4TCpj7huKPiiJHiiLcr4oC6wrJkIiwiIiwiMSA9PiAyXG4yID0+IDJcbjMgPT4gMlxuNCA9PiA4XG4xOCA9PiA4XG4xOSA9PiA4XG4yMCA9PiA4XG4yMSA9PiAxOFxuMjYgPT4gMThcbjMwID0+IDE4XG4zMSA9PiA4XG45MiA9PiAxOFxuMTE4ID0+IDgiXQ==).
*-1 byte* by porting part of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/257708/116074).
```
»...» # push compressed integer
₄τ # convert to base 26
¦ # cumulative sum
this results in the list [3,20,30,38,48,56,80,88,112]
> # is less than input?
ḣ # extract head, pushes a[0] and a[1:] (a[0] == 0 iff input is less than 4)
∑ # sum
∷ # modulo 2 (this is 1 iff the 18-electron rule applies)
+ # add
› # increment
² # square
d # double
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
->m{m>3?8+5*(2&70352637804063<<-m/2+12):2}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y63OtfO2N5C21RLw0jN3MDY1MjM2NzCwMTAzNjGRjdX30jb0EjTyqj2v4ahnp6hoYWmXm5iQXVNVk2BQnSWTlp0Vmxs7X8A "Ruby – Try It Online")
Unfortunately this fairly unimaginative approach works best.
Ruby rounds toward `-infinity`, so the minus sign in `-m/2` ensures that transitions occur in the right place. This expression evaluates to `-10` for both `19` and `20` input, and `-11` for both `21` and `22` input. To get the first `18` output, we take this `-11` and add `12` for an overall shift of `+1`. This gives a final answer of `8+5*(2)` which is 18. Larger numbers give negative leftshift, which Ruby interprets as positive rightshift.
the magic number can be replaced by `0x3ffc3ffc3e1f`
which is the same number of bytes. If three leading zeroes are added to the hex number, `+12` can be deleted, but it's the same number of bytes.
# [Ruby](https://www.ruby-lang.org/), 65 bytes
```
->m{n=0
" $(1:JZ".bytes{|i|n+=15<<i}
m>3?18-10*(1&n>>(m+67)/2):2}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y63Os/WgEtJQUXD0MorSkkvqbIktbi6JrMmT9vW0NTGJrOWK9fO2N7QQtfQQEvDUC3Pzk4jV9vMXFPfSNPKqPa/hqGenqGhhaZebmJBdU1WTYFCdJZOWnRWbGztfwA "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
>“Þœ&08PXp“¤‘§ḂS‘²Ḥ
```
A monadic Link that accepts an integer from \$[1,118]\$ and yields the rule, \$2\$, \$8\$, or \$18\$.
**[Try it online!](https://tio.run/##y0rNyan8/9/uUcOcw/OOTlYzsAiIKAByDi151DDj0PKHO5qCQYxND3cs@X@4/VHTmv//DQ0tAA "Jelly – Try It Online")**
### How?
```
>“...“¤‘§ḂS‘²Ḥ - Link: Atomic number, A e.g. 48
“...“¤‘ - lists of code-page indices -> [[20,30,38,48,56,80,88,112],[3]]
> - (A) greater than? (that) [[ 1, 1, 1, 0, 0, 0, 0, 0],[1]]
§ - sums [3,1]
Ḃ - mod two [1,1]
S - sum 2
‘ - increment 3
² - square 9
Ḥ - double 18
```
[Answer]
# [Python](https://www.python.org), ~~72 71 56~~ 55 bytes
```
lambda n:(n<4or sum(i>n for i in b"\x04\x15\x1f'19QYq")%2*5+4)*2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3HXISc5NSEhXyrDTybEzyixSKS3M1Mu3yFNKA7EyFzDyFJKWYCgOTmApDUyBOUze0DIwsVNJUNdIy1TbR1DKCmmMJV1-UmJeeqmGoo2BoaKlpxaUABAVFmXklGpk6CuoKCjElurp2MSUKCuo6CmkamZqaEAMWLIDQAA)
(But the `\x04\x15\x1f` should be replaced with the actual unprintable characters)
Based off Jos Woolley's Excel answer.
*-15 thanks to dingledooper*
*-1 thanks to pan*
## [Python](https://www.python.org), 66 bytes
```
lambda n:(n<4)*2+((20<n<31)+(38<n<49)+(56<n<81)+(88<n<113))*18or 8
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYwxDoJAEEV7TzEdM7AkDotmIWjhOWgwuroJDoSshWex2cTonbyNS_A3__1X_OdnfPjrIOFld-377m1uvoe-ux1PHUiN0pSUFhlisW6k0UwZahOprCJttpHM7MzsmDVRymaYwPyfKhuHAycwdXI5IytgrqheQcw4OfHoFCQArc_zfesBEgUWHdFyEMLSPw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
49Þ1š•N‚Ÿи––•₂вÅΓ·Iè
```
Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/257673/52210).
[Try it online](https://tio.run/##yy9OTMpM/f/fxPLwPMOjCx81LPJ71DDr6I4LOx41TAajRY@ami5sOtx6bvKh7Z6HVwCVAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/X8Ty8PzDI8ufNSwyO9Rw6yjOy7seNQwGYwWPWpqurDpcOu5yYe2Vx5e8V/nf7ShjpGOsY6JjqGFjqGljpGBjhFQxEzH2EDH2FDH0kjH0NAiFgA).
A port of [*@AndrovT*'s Vyxal answer](https://codegolf.stackexchange.com/a/257687/52210) is **20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** as well:
```
•¶sWü„•₂вηO›ćsOÉ6«*Ì
```
[Try it online](https://tio.run/##yy9OTMpM/f//UcOiQ9uKww/vedQwD8h@1NR0YdO57f6PGnYdaS/2P9xpdmi11uGe//9NAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Rw2LDm0rDj@851HDPCD7UVPThU3ntvs/ath1pL3Y/3Cn2aHVWod7/uv8jzbUMdIx1jHRMbTQMbTUMTLQMQKKmOkYG@gYG@pYGukYGlrEAgA).
Make sure to upvote both *@Neil*'s and *@AndrovT*'s answers as well!
**Explanation:**
```
49 # Push 49
Þ # Cycle it indefinitely: [4,9,4,9,4,9,...]
1š # Prepend a 1: [1,4,9,4,9,4,9,...]
•N‚Ÿи––• # Push compressed integer 25350987139094
₂в # Convert it to base-26 as list: [4,17,10,8,10,8,24,8,24,6]
ÅΓ # Run-length decode the two lists: [1,1,1,1,4,4,4,...]
· # Double each: [2,2,2,2,8,8,8,...]
Iè # (0-based) index the input into it
# (after which the result is output implicitly)
•¶sWü„• # Push compressed integer 766210902312
₂в # Convert it to base-26 as list: [3,17,10,8,10,8,24,8,24]
η # Get all prefixed of this list: [[3],[3,17],[3,17,10],...]
O # Sum each inner prefix: [3,20,30,38,48,56,80,88,112]
› # Check if the (implicit) input-integer is larger than the values
ć # Extract head; push first item and remainder-list separately
s # Swap so the remainder-list is at the top of the stack
O # Sum it
É # Modulo-2 (with an is_odd check)
6« # Append a 6 to this 0 or 1
* # Multiply it to the extracted head
Ì # Increase it by 2
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•N‚Ÿи––•` is `25350987139094`; `•N‚Ÿи––•₂в` is `[4,17,10,8,10,8,24,8,24,6]`; `•¶sWü„•` is `766210902312`; and `•¶sWü„•₂в` is `[3,17,10,8,10,8,24,8,24]`.
[Answer]
# JavaScript (ES6), 42 bytes
A hash formula with a 32-bit lookup.
```
n=>n<4?2:60620415>>(-~n>>1)*223%511&1?18:8
```
[Try it online!](https://tio.run/##DcZLDoIwEADQPaeYjaYVIUz5pEEoK0/gCQhQAiEzpDRujF69snpv7d/9Mbhl9wnxOAXbBmoNNUWn6iqrVFZgaYxIfmQMyptS@aVEvGKHutbBshMELeADCJpT1OfiWMInAhiYDt6mdONZUOr55d1Cs5Dp3o9PGkUu72AFSRl9wx8 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 47 bytes
A longer but slightly more subtle method.
```
n=>n<4?2:--n%16>="_468080"[n>>4]^n>29&n<32?18:8
```
[Try it online!](https://tio.run/##DcbRCoMgAAXQX5FgQ2lJVoRrak/7gj2ObUhmNOIaFvt919M5X/uz2xDndS8Q3Ji8TtAGqumrrihwEq3R2adpZSnL7AljmtcbprqeoeqqF7KTyYdIQTQRNwKiDoU8lueMDAFbWEa@hImC7@GxxxkTZXy17g5Ha3YhnoKx9Ac "JavaScript (Node.js) – Try It Online")
### Method
This is based on the pattern that appears when the atomic numbers are arranged by groups of \$16\$, starting at \$0\$ instead of \$1\$. We use the following condition to determine whether it's *18-electon* or *octet*:
$$(n \bmod 16)\ge T\_{\lfloor n/16 \rfloor}$$
There's unfortunately an exception for \$n=30\$ and \$n=31\$ (atomic numbers \$31\$ and \$32\$) which is not golfed very efficiently, making this method overall less competitive than the one using a more basic hash.
In the diagram below, we use `+`, `.` and `x` for *duplet*, *octet* and *18-electron* respectively.
```
| 0 1 2 3 4 5 6 7 8 9 A B C D E F
---+--------------------------------
00 | + + + . . . . . . . . . . . . .
10 | . . . . x x x x x x x x x x . .
20 | . . . . . . x x x x x x x x x x
30 | . . . . . . . . x x x x x x x x
40 | x x x x x x x x x x x x x x x x
50 | . . . . . . . . x x x x x x x x
60 | x x x x x x x x x x x x x x x x
70 | . . . . . .
```
[Answer]
# [C (GCC)](https://gcc.gnu.org), 81 76 71 68 57 bytes
*thanks neil for -11 bytes*
```
f(x){x=x<4?2:0x1fffffe01fffffe01ff807fell<<20>>x&1?18:8;}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZDdSsNAEIURr5KnGAqVXTrCzqbopvkpPoeWEtJdWVijNKkshDyJN73pQ-nTuNFW6oU4N4c5w3cOzNuhXj_W9X5_2HXmWr2nhnne-8Ln86VcCE9mHC3OVIlbo53LcynK0l_RktRCZcN3wMfFpW06eKpswzj0cTRunW67dV21ur1fQQE9ocQE50gKKUUpUAbnBhOBCWEqkUgNWRyZ5y2wkbcBElmQHCgJOpt9RUcv23A1bDLdQFHCdPPQTPC8zK4QDPtlcB6Ch_gHvXMOXiu3022A-V-lpP5rtWOTPaYff3F66ic)
Return 2 for <= 3, otherwise lookup the value in the 64-bit constants, where 0 is the 18 rule and 1 is the 8 rule.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~61 47~~ 41 bytes
```
Ia<4P2EL{P%#({\a>a}FI(A*"
&08PXp"))*t+8}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7IKlpSVpuhY3NT0TbUwCjFx9qgNUlTWqYxLtEmvdPDUctZRE5NQMLAIiCpQ0NbVKtC1qIRqg-pZEWxrBzAAA)
*-20 thanks to @DLosc*
#### Explanation
```
Ia<4 # if the input is less than 4:
P2 # print 2
EL{ # else:
P # print the following:
%#( # length mod 2 of:
{\a>a} # is the input greater than this number?
FI(A*"...") # filter the list [20,30,38,48,56,80,88,112] by the above
)*t+8 # times 10 plus 8
} # enf if
```
Old:
```
Ia<4 # if the input is less than 4:
P2 # print 2
EL{ # else:
Fi { # for i in ...
A*"..." # the ASCII code points of the string
# [20,30,38,48,56,80,88,112]:
l:lAE # append the following to l
(a>i) # is the input greater than i?
} # end for
P # print ...
(1Nl) # ... the count of 1s in l ...
% # ... mod 2 ...
*t+8 # ... times 10 plus 8
} # end if
```
[Answer]
# [Scala](https://www.scala-lang.org/), 103 bytes
Modified from [@The Thonnu's answer](https://codegolf.stackexchange.com/a/257654/110802).
---
Golfed version. [Try it online!](https://tio.run/##LY1dS8MwFIbv@ytexoRks9LUlmnZBnrnnVB3tQ2JXTIjNdH0CCulv70m4oHz8HA@eLtGtnJybx@qITz39O7si6vjEMN0Uhqa2erJEt@YYOuC51Btp1itvvePPakjyy5ZcZ1dRBmhA/JVwK2IuA8oo5XRVoLfNO7HEnvF1vKrfFEuC77IJyAmfUpjmfTnrsKD97Lf1@SNPR95hZ01hA2GBKG082AG6xQC5CDEHf/fAF/hg1rLutncAAdK0@2BgPmgmeHjjP@djUnsMZl@AQ)
```
def f(n:Int)=if(n<4)2 else(Seq[Byte](0x04,0x15,0x1f,0x27,0x31,0x39,0x51,0x59,0x71).count(_ >n)%2*5+4)*2
```
Ungolfed version.
```
object PythonToScala {
def f(n: Int): Int = {
val b = Array[Byte](0x04, 0x15, 0x1f, 0x27, 0x31, 0x39, 0x51, 0x59, 0x71)
if (n < 4) 2
else (b.count(_ > n) % 2 * 5 + 4) * 2
}
def main(args: Array[String]): Unit = {
for (i <- 1 to 118) {
println(s"$i \t-->\t ${f(i)}")
}
}
}
```
] |
[Question]
[
You are the electoral strategist for a sudden late entrant in the 2020 US presidental election.
**Your task**: print out the names of states\* your candidate will win, totalling at least 270 electoral college votes.
## Background
Each state (and Washington DC) in the US system has an arbitrary number of "electoral college votes". A candidate has to win a majority of the 538 votes available, so at least 270 votes.
The number of votes for each state is:
`[['Alabama', 9], ['Alaska', 3], ['Arizona', 11], ['Arkansas', 6], ['California', 55], ['Colorado', 9], ['Connecticut', 7], ['Delaware', 3], ['Florida', 29], ['Georgia', 16], ['Hawaii', 4], ['Idaho', 4], ['Illinois', 20], ['Indiana', 11], ['Iowa', 6], ['Kansas', 6], ['Kentucky', 8], ['Louisiana', 8], ['Maine', 4], ['Maryland', 10], ['Massachusetts', 11], ['Michigan', 16], ['Minnesota', 10], ['Mississippi', 6], ['Missouri', 10], ['Montana', 3], ['Nebraska', 5], ['Nevada', 6], ['New Hampshire', 4], ['New Jersey', 14], ['New Mexico', 5], ['New York', 29], ['North Carolina', 15], ['North Dakota', 3], ['Ohio', 18], ['Oklahoma', 7], ['Oregon', 7], ['Pennsylvania', 20], ['Rhode Island', 4], ['South Carolina', 9], ['South Dakota', 3], ['Tennessee', 11], ['Texas', 38], ['Utah', 6], ['Vermont', 3], ['Virginia', 13], ['Washington', 12], ['Washington DC', 3], ['West Virginia', 5], ['Wisconsin', 10], ['Wyoming', 3]]`
## Input
None
## Output
A list (or similar) containing just the names of the states in your winning strategy. If a string, there must be separators between state names. States must be capitalised as in the list provided above.
You must not output anything other than valid state names and separators. The number of states in your strategy is up to you.
## Rules
You may not use any external (or built-in) list of US state names. Standard loopholes are forbidden.
This is code golf. Shortest code in bytes wins, with the electoral college score as a tie-breaker.
Since there is no input, your code can be a program/script/statement rather than a function.
If you are using space as a separator, then you can't include any states with spaces in the name. Or you would have to do something like enclosing each state name in double quotes. (A separator has to be something that could be used to automatically split the string up into the correct elements.)
`*` For the purpose of this challenge, Washington DC is considered a state.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~52 ... 45~~ 42 bytes (270 votes)
A list of states that optimizes the compression with Brotli.
```
”}∧J⟧´⪫3⎚>↘≡VNb7>¹l↙⁵Þ7/…ξ⌕↑τc<y\MΦGC&⸿Dρ~
```
[Try it online!](https://tio.run/##AWQAm/9jaGFyY29hbP//4oCdfeKIp0rin6fCtOKqqzPijpo@4oaY4omh77y277yuYjc@wrls4oaZ4oG1w543L@KAps6@4oyV4oaRz4RjPHlcTc6m77yn77yj77yG4ri/RM@Bfv///y1j "Charcoal – Try It Online")
### Output
```
Texas
Pennsylvania
Georgia
Illinois
Washington
Indiana
California
Arizona
Michigan
Virginia
Florida
New York
```
### Node.js script
The initial list was found with the following Node.js script that shuffles the 30 most efficient states, extracts the shortest leading sub-list with a score greater than or equal to 270, joins it with `\r` and invokes the Brotli compressor on the resulting string.
It was optimized some more by shuffling the most promising sub-list to find an order offering the best compression.
```
let states = [ ['Alabama', 9], ['Alaska', 3], ['Arizona', 11], ... ];
states =
states.map(a => [a[0], a[1], a[1] / a[0].length])
.sort((a, b) => b[2] - a[2])
.slice(0, 30);
const zlib = require('zlib');
let bestLen = 1 / 0, bestScore = 1 / 0,
list, score, str, pack;
while(1) {
for(let i = states.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[ states[i], states[j] ] = [ states[j], states[i] ];
}
for(
let n = 1;
(score = (list = states.slice(0, n)).reduce((p, c) => p + c[1], 0)) < 270;
n++
) {}
str = list.map(s => s[0]).join('\r');
pack = zlib.brotliCompressSync(Buffer(str));
if(pack.length < bestLen || (pack.length == bestLen && score <= bestScore)) {
bestLen = pack.length;
bestScore = score;
console.log(bestLen, bestScore, str.split('\r').join('\\r'));
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~68~~ 66 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage), 271 votes
```
.•2Y±e1¸Zí¼³sçj†Ê蔚ʒÕʒ½‘ε-нUeC·ûÝ죅
õ%î!¯aàáè˜3ÒƵLweh³•#`„€¢…Œ»™
```
Outputs the following 12 states newline-separated, totaling 271 votes:
```
California,Florida,Georgia,Illinois,Indiana,Michigan,Ohio,Pennsylvania,Texas,Utah,Virginia,New York
```
[Try it online.](https://tio.run/##AYEAfv9vc2FiaWX//y7igKIyWcKxZTHCuFrDrcK8wrNzw6dq4oCgw4rDqOKAncWhypLDlcqSwr3igJjOtS3QvVVlQ8K3w7vDncOswqPigKYKw7Ulw64hwq9hw6DDocOoy5wzw5LGtUx3ZWjCs@KAoiNg4oCe4oKswqLigKbFksK74oSi//8)
If builtins were allowed, we could have used the dictionary for **27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage), 270 votes**
```
”‡Â†éЧ›ÕïÁ–ۗї‡¹¢ÇŸÏžÏ
```
Outputs the following 13 states space-delimited, totaling exactly 270 votes:
```
California Texas Florida Pennsylvania Illinois Ohio Michigan Georgia Virginia Washington Tennessee Massachusetts Indiana
```
[Try it online.](https://tio.run/##AUgAt/9vc2FiaWX//@KAneKAocOC4oCgw6nFoMKn4oC6w5XDr8OB4oCTw5vigJTDkeKAlMOvxb3FveKAocK5wqLDh8W4w4/FvsOP//8)
**Explanation:**
```
.•2Y±e1¸Zí¼³sçj†Ê蔚ʒÕʒ½‘ε-нUeC·ûÝ죅
õ%î!¯aàáè˜3ÒƵLweh³• # Push compressed string "california florida georgia illinois indiana michigan ohio pennsylvania texas utah virginia"
# # Split it on spaces
` # Push them all separated to the stack
„€¢…Œ # Push dictionary string "new york" (which are both English words)
» # Join all strings on the stack by newlines
™ # And title-case each word
# (after which it is output implicitly as result)
”‡Â†éЧ›ÕïÁ–ۗї‡¹¢ÇŸÏžÏ
# Push the dictionary string "California Texas Florida Pennsylvania Illinois Ohio Michigan Georgia Virginia Washington Tennessee Massachusetts Indiana"
# (after which it is output implicitly as result)
```
[See this 05AB1E tips of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why:
* `.•2Y±e1¸Zí¼³sçj†Ê蔚ʒÕʒ½‘ε-нUeC·ûÝ죅\nõ%î!¯aàáè˜3ÒƵLweh³•` is `"california florida georgia illinois indiana michigan ohio pennsylvania texas utah virginia"`;
* `„€¢…Œ` is `"new york"`;
* and `”‡Â†éЧ›ÕïÁ–ۗї‡¹¢ÇŸÏžÏ` is `"California Texas Florida Pennsylvania Illinois Ohio Michigan Georgia Virginia Washington Tennessee Massachusetts Indiana"`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~59~~ ~~51~~ ~~50~~ 41 bytes
```
”}∧I⊗⪫σ³»α“"⸿u↙¦C^±W)RLκ&⁰Y2E¬«]f“WN+'|⁺≕
```
[Try it online!](https://tio.run/##HYxBCsJADEWvIl3pwhO4FBQXlS6KRZhNGGMnGBJIxqqnH0N3n/8eLxewrMCtDUZSt92IX/AkN7KZhCDJhZlEKb6ecqEZJMkZNXDAAUX8xwus6onV6BFjAi8kc9Vwr/jZ3NVeSY7A9FRb1R7cIZe3Y62RHqOD7ojd7tBa2y/8Bw "Charcoal – Try It Online") Link is to verbose version of code. Simply the compressed string for `Texas\nVirginia\nIllinois\nMichigan\nGeorgia\nPennsylvania\nFlorida\nWashington\nNew York\nCalifornia\nMassachusetts\nTennessee`; total 270 votes.
This solution was found with the help of a Python 3 program that randomly selected voting states and took the length of the resulting string. It then tracked the number of times each state appeared in the strings that were less than a certain cutoff length, initially 60, but gradually reduced to 45 as I optimised the input.
Optimisation consisted both of creating a list of frequently used states and removing infrequently used states from the list thus allowing more shuffles to be performed.
Eventually I got to the point where each shuffle always had the states California, Florida, Georgia, Illinois, Michigan, New York, Pennsylvania and Texas, and four of the six states Arizona, Indiana, Massachusetts, Tennessee, Virginia and Washington. At this point I could generate all 15 combinations of 12 states and just had to shuffle the states around in the hope of getting a short answer. Shuffling script:
```
import brotli
import itertools
import random
import sys
bigstates = ['California', 'Florida', 'Georgia', 'Illinois', 'Michigan', 'New York', 'Pennsylvania', 'Texas']
smallstates = ['Arizona', 'Indiana', 'Massachusetts', 'Tennessee', 'Virginia', 'Washington']
while True:
for states in itertools.combinations(smallstates, 4):
states = bigstates + list(states)
for j in range(100):
random.shuffle(states)
if len(brotli.compress('\n'.join(states).encode("ascii"))) < 39:
print(states)
sys.exit()
```
[Try it online!](https://tio.run/##TVGxTsNADN3zFRZLElFFRWUBwYCQQAxFDBUIAcM1cRKXi12dr7Tl50OuSWm29yz7@fl5vfe18KxtqVmL87B04i1FAyOPzotYPRac4UKaI9O9RtGSKvXGo8ItfMT3xlIpjsnEE4gfrDgqDvARxVV99claYiENeE55TZXhgJ9xC@/ivgN@QWbd2x8zKC1wZzT@irQx1o723Tn6Fe5luSDTw7lRNXm9UfRe@3FmVEUM5JU6J4Pum9GauPLCnXi0rckiLNwGryPozoBhE/EpiiyXZklsPAlrMvIzgcu0G4N/d6dkzsGS@qRnadcTtFdBtgu0wuRiOj2MDvlmWm/K0uJoAKgEi5z0/wke1q47KIk/Oc5WQnzszZBzKTA5M5oTnaVpCjcwuzqow9oRj21AeGGGO/JJ2rZ/ "Python 3 – Try It Online") The script also found the following shuffles with the same byte count:
```
Print("Texas\nTennessee\nVirginia\nPennsylvania\nWashington\nCalifornia\nMichigan\nMassachusetts\nNew York\nGeorgia\nFlorida\nIllinois");
Print("Texas\nVirginia\nMichigan\nIllinois\nGeorgia\nPennsylvania\nFlorida\nWashington\nTennessee\nMassachusetts\nNew York\nCalifornia");
Print("Texas\nGeorgia\nTennessee\nVirginia\nIllinois\nPennsylvania\nMichigan\nWashington\nCalifornia\nNew York\nMassachusetts\nFlorida");
Print("Texas\nNew York\nVirginia\nPennsylvania\nWashington\nFlorida\nMassachusetts\nGeorgia\nCalifornia\nTennessee\nMichigan\nIllinois");
```
Previous 50-byte solution:
```
”}∧UV↔ΦJU№EIG➙eêPn¡F{⦃←στ⸿M⊕!⪫¹P?Mξ⁹#<″⊘bh%0RZ⌈⧴↑·
```
[Try it online!](https://tio.run/##JYwxCgJBEAS/Ihdp4AuMRFAUlAtEETYZ1vWuceiBWTk9P7@umlZ1dezFo4mW0jr4mDZtIvOogxASeEaOxgwGHtNLcuBKFDfzn92qgoZKD@k5uZjfA9dqjmuVm2TefVd7xB6d1IsTKvmVS8fbKP9wlzynsZktSinzQT8 "Charcoal – Try It Online") Link is to verbose version of code. Simply the compressed string for `Pennsylvania\nWisconsin\nTexas\nCalifornia\nIllinois\nNew York\nFlorida\nGeorgia\nMichigan\nVirginia\nArizona\nNew Jersey`; total 271 votes.
I started off with the best value states, Texas, California, Florida, Ohio, New York, Illinois, Georgia, Michigan, Pennsylvania, Virginia and Arizona, plus Iowa to make up the numbers. I then tried various permutations of states to find out which ones Charcoal compressed best; moving Ohio, Illinois and New York to the end worked best. (There are 12! possibilities so I'm not trying them all.) I then tried switching Arizona and Iowa with Indiana and Utah, taken from @SurculoseSputum's answer; Arizona made no difference but Utah saved a further byte.
Edit: Saved 8 bytes by printing Utah and Ohio literally instead of trying to compress them. Saved a further byte by using New Jersey and Wisconsin instead of Utah and Ohio. (This did mean reordering the states again for optimal compression. Colorado,
Indiana, Maryland, Massachusetts, Minnesota, Mississippi and Missouri and also work instead of Wisconsin.)
[Answer]
# [Python 2](https://docs.python.org/2/), 106 bytes, 271 votes
```
print"California,Florida,Georgia,Illinois,Indiana,Michigan,New York,Ohio,Pennsylvania,Texas,Utah,Virginia"
```
[Try it online!](https://tio.run/##FcwxDoJAEEbhqxjqqbwCiYYCsFATyoks7B8nM2R2g3L6dS3fK77tyNH0XMrm0Ny0LFjMFUwXMcfMdA3ma@1OBGpI1OkMVqYer4iVlYbwOU3mbxojjG5BNR2y8x@5hy8nemSO9ERl6mtK@QE "Python 2 – Try It Online")
Picks the states with the best votes/name length ratio.
Turns out this is the shortest possible combination of states to achieve at least `270`, as shown in [this DP program](https://tio.run/##dVPvj9pGEP3uv2J0@RCsMxUmpemhUqk61OaScle1aU4VQtViD3iKvYt21wZS5W@/zO46ti9q0XFinue9efPDx4stlJw@PRkrLJrFev3yp1JsRSVeJnCzScDH5uDCVyHU9FFJF6dpCxyENMIw8p0HbkVJO6UluaTZLGCqVFrkqlO9VVJiZimrLWOvPbbEUpyExq7Wz0yi3MlMA@sXVHrvddNQ6w0TiDj@1od3uShUH5UlSUXO2XQSEJmTGJq/UyfRGX/3vI93KG2dHS4MfO@BX1VNpuUHZCVIYldvJfSlFDJ38pMWMUZkRW3QWtNXXVFW0F7Ivo8V8TiMsmLAJWPc3/FInSWHqVrTIEtJGxyFkd3jVrf7mrVAI/K@x3s8wRtRHU1Bunfu0LeoDbpm0x5b4ZkyNdA6wV9KH/qF3CttC7gVWvGovfnZAF@KQ2gpeHsoyGmlYXYPh5KX5Q8trP9B417JLvwNpTSXshHhkNoN/l6oHOHOtHMOVv9Q9XMXNwP4KxPv0U3aIPbreI9nv/ZXwdifVhTdvD6grnjEHf0D8QEGR2lAHgXPUu6tt55Ov8JgedtxH9FYGAiEUT2SyZQ0JPulPl5UxXRP3ETREhbwr39B59Aoi8BvF/g4CTHJEJpPUfQCKqwUfcQcNJq6tCZaOb5/tCOZgy0QWB5kXYHaQVYILTLL2werYI8WhIUSBXtlRuMrGNhpVbVFgFziLOWnI0sIW43iANsLFOoElZAXwLPVIhBjzuJVgSiN8pVLYmEu22qxEr8ghA3yUy7MxqiqqyjHnfv9d4ly1CRA8TwCeAFbYRAy/scR7aD5YTGZa7S1ljBJYBQHmH5cOF4oEc@hzbhxH5fllHQtDfCB9F4SFpbWT6DtOvI1wzyFJSWDPBui2A191Umv1sHlJlA0ZrU2gTBc1KIttabNlyeuwz2f6QI6y/F1Ck4l9YvOVFUJrzrlXSnKeGoFar6FI2WHIMIr4UypLOeVaQImZb1ufGNXO6HrNPaP4XrxrDSDjcs3dTVars8bX/Xsj8ozTM9InMCU9adDfW48aDfT/5XxDfjzc6fHM3c2ndSzC9rzD75EvgorSj8yV7Di6fHXVKHoaOS448b3GfM@ncy48bZiX8kljkpPcba65Tg@x@3OqiiqBm1MX/MFTeLoqImv4CrMZn6VQLWebMbpFzws0OFXydU3/yj2U63TzXo@H6ebju3PZ84p/zEOlx4/PX0G).
[Answer]
# [Turing Machine Code](http://morphett.info/turing/turing.htm), 1059 bytes (270 votes)
```
0 * C r 1
1 * a r 2
2 * l r 3
3 * i r 4
4 * f r 5
5 * o r 6
6 * r r 7
7 * n r 8
8 * i r 9
9 * a r π
π * , r a
a * T r b
b * e r c
c * x r d
d * a r e
e * s r f
f * , r g
g * F r h
h * l r i
i * o r j
j * r r k
k * i r l
l * d r m
m * a r n
n * , r o
o * N r p
p * e r q
q * w r r
r * _ r s
s * Y r t
t * o r u
u * r r v
v * k r w
w * , r x
x * I r y
y * l r z
z * l r A
A * i r B
B * n r C
C * o r D
D * i r E
E * s r F
F * , r G
G * P r H
H * e r I
I * n r J
J * n r K
K * s r L
L * y r M
M * l r N
N * v r O
O * a r P
P * n r Q
Q * i r R
R * a r S
S * , r T
T * O r U
U * h r V
V * i r W
W * o r X
X * , r Y
Y * G r Z
Z * e r `
` * o r ¬
¬ * r r "
" * g r £
£ * i r $
$ * a r %
% * , r ^
^ * M r &
& * i r (
( * c r )
) * h r +
+ * i r {
{ * g r }
} * a r [
[ * n r ]
] * , r -
- * N r =
= * o r :
: * r r '
' * t r @
@ * h r #
# * _ r ~
~ * C r
> * o r .
. * l r ?
? * i r /
/ * n r |
| * a r \
\ * , r ©
© * N r À
À * e r Á
Á * w r Â
 * _ r Ã
à * J r Ä
Ä * e r Å
Å * r r Æ
Æ * s r Ç
Ç * e r È
È * y r halt
```
This will print:
```
California (55; 55)
Texas (38; 93)
Florida (29; 122)
New York (29; 151)
Illinois (20; 171)
Pennsylvania (20; 191)
Ohio (18; 209)
Georgia (16; 225)
Michigan (16; 241)
North Carolina (15; 256)
New Jersey (14; 270)
```
Or to be more precise:
`California,Texas,Florida,New York,Illinois,Pennsylvania,Ohio,Georgia,Michigan,North Carolina,New Jersey`
*Updated to reflect a later rule change - thanks @Laikoni. No byte size change.*
[Try it online!](http://morphett.info/turing/turing.html?92b5459a6c9d7729d6568e08354ff8da)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 75 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax), 271 votes
```
ê╢G.₧¢ƒdXb╜L7äF9₧⌐Ä╚ç⌂oPrçer┬♦s4⌠╧!S∟☻ƒÆà²ÿ☼{4?àç÷Uó("Φå9dgYútY°lènÜÉ↔TI╙í↨
```
[Run and debug it](https://staxlang.xyz/#p=88b6472e9e9b9f645862bd4c378446399ea98ec8877f6f5072876572c2047334f4cf21531c029f9285fd980f7b343f8587f655a22822e88639646759a37459f86c8a6e9a901d5449d3a117&i=)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 115 bytes
```
puts"California
Texas
Florida
Nor#{s="th Carolina
New "}York
Sou#{s}Jersey
Illinois
Ohio
Georgia
Michigan
Virginia"
```
[Try it online!](https://tio.run/##DY1BCsJADEX3OUUZz9FVQVGoLpSCy6hpJzhMJOmgpfTsY5bvP/hPy2Op9VNmCx0mHkUzI9zohwb7JMovhLPobrU2zLHpUCVx9o2@Tdjuom@4SnG9nUiNFjgm98IGl8gCBxKd/LDnZ@QJMwzs7IlQ6x8 "Ruby – Try It Online")
Makes use of the string `"th Carolina\nNew "`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 37 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“£+ʠṅṖḳ!⁺PUB.BJçŒṖ{ScḤ?[¢¤c}€£Y,qbẆ|»
```
A niladic Link which yields a list of characters using a space as the separator. The states have a total value of 270 (and contain no spaces themselves):
```
California 55
Texas 38
Florida 29
Pennsylvania 20
Illinois 20
Ohio 18
Georgia 16
Virginia 13
Massachusetts 11
Indiana 11
Arizona 11
Maryland 10
Colorado 9
Alabama 9
= 270
```
**[Try it online!](https://tio.run/##AUgAt/9qZWxsef//4oCcwqMryqDhuYXhuZbhuLMh4oG6UFVCLkJKw6fFkuG5lntTY@G4pD9bwqLCpGN94oKswqNZLHFi4bqGfMK7//8 "Jelly – Try It Online")**
### How?
A compressed string. After taking big hitters containing no spaces I chose states which are earlier alphabetically to keep the result shorter.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~102~~ 108 bytes (270 electoral votes)
```
echo \"{{Californ,Georg,Virgin}ia,Florida,Arizona,Indiana,Texas,Ohio,New\ {York,Jersey},Illinois,Michigan}\"
```
[Try it online!](https://tio.run/##DcVNCsIwEAbQq5Su5xIiKBXUjQhCNtN2TD4MMzBZ@BNy9tS3eTOX1LssyYYw1rrnjKe50lHMI93hEdrAdMjmWJl2jp8p06Qr@P9NPlzommB0kXcY6sP8RSfxIt9GU85QQ6EzloTI2sLY@wY "Bash – Try It Online")
*Added 6 bytes to accommodate the modification to the challenge on using a space as a separator. The original answer was:*
```
echo {Californ,Georg,Virgin}ia Florida Arizona Indiana Texas Ohio New\ {York,Jersey} Illinois Michigan
```
[Answer]
# [Whitespace](https://esolangs.org/wiki/Whitespace "Whitespace – Try It Online"), 777 bytes; 274 EV's
```
```
Outputs the states as a `j`-separated list. You read that part right.
[Try it online!](https://tio.run/##fVLLDsIwDDs7X@FfQ2gS3JBA4vPLujaJ244dpi6rEz@W7@P52d6v230rhQRI2v6AOA70iq3uRX3frwJs0qnd1ClAjtCOejrP@HmmDFjg2siZP1UP9MHGZKtSUzZUvTP1G65ma9nQNolGwk4iQvjgitLe9GLhWupuachGgbj6O6LGB/ivpgbT/FECjFwjVQ@CA/KkNTZDGDQW2B8wRslR43oD12WIhTNL@/XOd3xXbKX8AA)
## States
`"Arizona", "California", "Florida", "Georgia", "Illinois", "Indiana", "Iowa", "Michigan", "Ohio", "Pennsylvania", "Tennessee", "Texas", "Utah", "Virginia"`
List chosen using @Surculose Sputum's Python script, but modified to ignore states with spaces in their names. This was because spaces have an ascii value of `32`, and `32 - 105= -73`, so pushing it would raise the byte count by a lot (I think). I have yet to test this theory though (because when removing NY I had to add something like 4 more states), so the code may yet get smaller.
## Code
A pretty standard Whitespace answer. Pushes the names of the states minus 105 to the stack, separated by a `j`, and then runs through the stack adding back the `105` and printing the result as a character. The printing part looks something like:
```
label 0:
push 105
add
printc
jmp 0
```
`105` because the character with the most occurences is `i`, which has an ascii value of 105. Outputting as a `j` separated list because `j` has a value of `106`. I used [this](https://tio.run/##fVJNbxMxEL37V4zcQ9eiiahACEUECSGBKoHgAFzSHNysN57KtS3bYRv@fBjbGy@54Itnxu@9@bI/Ju3sq7c@nE4xyaQirGHDPwT846zkN8A/SoODCxaL98m4gH0xPysX9jV6Zwxah7HYtkdZqXduLPdX3GncS5vtbxpdvr8ra@PR/JaT8A/yVYxKVedZFrGfSep8/0JKlZFbxgY0ysonRYVyd0j@kJbpOXHmhiGqRFG0qUNL8U4ItnN9Rm62jErQKmbAS2bceDapNyidE68accWATn7YaRlafLNaLW639TEfq0ZScKHvMkzAAmoJDYBDwbyDmm5m5tNKIEh7UGbivIep3EvS3MO/rNzjUnqvbN9xf4gaOLygmkNHKEEmv7dcsP9Dcx/8kc9tNCJclSYFxeHNa3YhwTkz8kEZGmRV401vFiGQ7HvmA21mxx6fPKEpKBi7KrEuS4qzQznv7Rdl90mvWnW08ooqgvBwpDXxRqmzbO40JdLPO8S8wCDtXs0qi1tRB0vjzoENbmG9nsyLJbdX4P3B0zgYGzFpcNR/d/6KN3A9XguQEYbp7yzHgIm2SX@6Zjyd/gI) script to generate the WSA (WhiteSpace Assembly) to quickly test the offset number, and used [this IDE](http://vii5ard.github.io/whitespace/) to compile it to regular Whitespace.
[Answer]
## JavaScript, 114 characters, 270 votes
```
_=>`California,Texas,Florida,Nor${s='th Carolina,New '}York,Sou${s}Jersey,Illinois,Ohio,Georgia,Michigan,Virginia`
```
Just a straight port of Level River St's Ruby answer.
] |
[Question]
[
Inspired by [this glove-themed 538 Riddler Express Puzzle](https://fivethirtyeight.com/features/can-you-get-the-gloves-out-of-the-box/).
## Task
You are given a positive integer `n`, and a list `A = [a_1, a_2, ..., a_k]` of `k` distinct positive integers.
Then a restricted composition is an ordered list `P = [p_1, p_2, ..., p_m]` where each `p_i` is a (not necessarily distinct) member of `A`, and `p_1 + p_2 + ... + p_m = n`.
So, if `n = 10`, and `A = [2,3,4]` then an example of a restricted composition would be `P = [3,4,3]`. Another example would be `P = [2,3,3,2]`. A third example would be `P = [3,3,4]`. But there's no restricted composition that starts `[3,3,3,...]`, because `10-(3+3+3) = 1`, which is not in `A`.
We want the total number of different restricted compositions given the inputs, as an integer.
## Inputs
A positive integer `n` and a list `A` of distinct positive integers. All reasonable input formats allowed.
## Output
The number of distinct restricted compositions.
## Terms and Conditions
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); and thus we seek the shortest submissions in bytes satisfying the constraints. Any use of the usual loopholes voids this contract.
## Test Cases
```
(5, [2, 3, 4]) => 2
(10, [2, 3, 4]) => 17
(15, [3, 5, 7]) => 8
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~50~~ 49 bytes
*-1 byte thanks to @Jonathan Allan*
```
f=lambda n,A:n>=0and(n<1)+sum(f(n-x,A)for x in A)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU/H0SrPztYgMS9FI8/GUFO7uDRXI00jT7dCx1EzLb9IoUIhM0/BUfN/QVFmXolCmoapjkK0kY6CsY6CSawmF0zU0AC7MEg1UAxImcdq/gcA "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), ~~48~~ 40 bytes
Takes input as `(a)(n)`.
```
a=>g=n=>n>0?a.map(x=>t+=g(n-x),t=0)|t:!n
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7dNs/WLs/OwD5RLzexQKPC1q5E2zZdI0@3QlOnxNZAs6bESjHvf3J@XnF@TqpeTn66RppGtJGOgrGOgkmspoaCqaamgr6@ghEXTiWGBhAlhuboaoAKTHUUzEFqoMZY/AcA "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 24 17 bytes
```
1#.[=1#.[:>@,{\@#
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1om1BhJWdg051jIPyf02u1OSMfAUjBVsFU4U0BQ0bIwVjBROoqKE5UNjQAEn8PwA "J – Try It Online")
Recursive version was too verbose in J, so I went brute force.
Take the integers in the right arg as a boxed list and the target number `n` in the left arg.
* `{\@#` - We create a series of cartesian products of the list with itself, starting with 1 (the list unchanged) and up to `n` (the list crossed with itself n times).
* `[:>@,` We flatten all of those, open them, and sum them.
* `[=` Check which sums equal `n`. This returns a boolean list.
* `1#.` Sum it.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 18 bytes
Accepts `n` as the right argument and `A` as the left argument.
```
{⍵>0:+/⍺∘∇¨⍵-⍺⋄⍵=0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71b7QystPUf9e561DHjUUf7oRVAIV0Qt7sFyLI1qP3/30jBWMFEIU3BlAvGMjTgMlYwVTAHMU0B "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṗⱮẎ§ċ
```
**[Try it online!](https://tio.run/##ASEA3v9qZWxsef//4bmX4rGu4bqOwqfEi////1syLDMsNF3/MTA "Jelly – Try It Online")** (Very inefficient.)
### How?
Builds all lists of lengths \$1\$ to \$n\$ made from the integers in \$A\$ and then counts how many sum to \$n\$.
```
ṗⱮẎ§ċ - Link: list of positive integers, A; positive integer, n
Ɱ - map across x in (implicit range [1..n]) applying:
ṗ - Cartesian power -> all length x lists made from values in A
Ẏ - tighten (to a list of lists)
§ - sum each list
ċ - count occurrences of (n)
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 23 bytes
```
{$[x>0;+/(x-y)o\:y;~x]}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlolusLOwFpbX6NCt1IzP8aq0rquIrb2fwhIprKuyCpNQU@hwjohP9taIyEtMTPHusK60rpIM7aWKyRaQ8HU2kjBWMFEE0jFggQMDWAChuYQAVNrYwVTBXNNawuF2P8A "K (ngn/k) – Try It Online")
recursive
[Answer]
# [Io](http://iolanguage.org/), 57 bytes
Port of the Python answer.
```
f :=method(n,A,if(n>0,A map(x,f(n-x,A))sum,if(n==0,1,0)))
```
[Try it online!](https://tio.run/##fclLCoMwFEbhuau4w3vhF6JWhEIKWUpBQwPmQY3g7tMgQmfOzuFzsRRLT@2X/IkzBxg4y@GlYMi/Ex@o1x4wItvuT9NaoYMSkWJ5JNDqtsw9aAA9RCh9XchraCx36g7HC6vUnP5Yfg "Io – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~10~~ 8 bytes
```
#o=¹ΣuṖ*
```
[Try it online!](https://tio.run/##yygtzv7/Xznf9tDOc4tLH@6cpvX//3/j/9GGOkY6xrEA "Husk – Try It Online")
This is so ridiculously inefficient that it struggles on [TIO](https://tio.run/##yygtzv7/Xznf9tDOc4tLH@6cpvX//3/j/9GGOkY6xrEA "Husk – Try It Online") to even run any of the given test cases: link is to a super-easy test case of n=2, a=[1,2,3] (for which [output is 4](https://tio.run/##yygtzv7/Py3f9tDOc4tLH@6cpvX//3/j/9GGOkY6xrEA)).
Repeats and concatenates (`*`) the input list n times, and then generates all possible subsets (`uṖ` - this is the slow step!). Then counts the number (`#`) of subsets for which the total equals n (`o=¹Σ`).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/language/), ~~56~~ ~~49~~ ~~46~~ ~~43~~ 41 bytes
2 bytes golfed thanks to [J42161217](https://codegolf.stackexchange.com/users/67961/j42161217)
```
n_~f~a_=If[n<1,1+Sign@n,Tr[f[n-#,a]&/@a]]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8vvi6tLjHe1jMtOs/GUMdQOzgzPc8hTyekKBoooquskxirpu@QGBv7P6AoM6/EIS3aVKfaSMdYx6Q2lgsmZGiARQyozljHVMe8Nvb/fwA "Wolfram Language (Mathematica) – Try It Online")
Initial solution:
```
Length[Join@@Permutations/@IntegerPartitions[#,∞,#2]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yc1L70kI9orPzPPwSEgtSi3tAQol59XrO/gmVeSmp5aFJBYVJIJFopW1nnUMU9H2Sg2Vu1/QFFmXolDWrSpTrWRjrGOSW0sF0zI0ACLGFCdsY6pjnlt7P//AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 89 bytes
Port of the Python answer.
Edit: Outgolfed by Noodle9 :/
```
int n;f(int x,int*a){if(x<=0)return!x;int y=0,i=0;while(i++<n)y+=f(x-a[i-1],a);return y;}
```
[Try it online!](https://tio.run/##bYzLDoIwEEXX8BUVY9LKYEAkLkr9EXRRXjIJVoMQIYRvx1ZcsrmTmXPnZN49y@Ytqqzu8oLE7zbH56G6zKhaonhJzexB516yEUvax8JnTdF2jdr03NBB@IDC558K64Ki68aKDa7QVU8m6AU3kIwvH2Tg08/8kKgoG23LLDK5EUHGI4RwmrhtKRHqfDWaldTZ5VflQEkjrWEr98D/A6NKF1UIEZyntXIEqSlP8xc "C (gcc) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~65~~ 63 bytes
Saved 2 bytes thanks to [my pronoun is monicareinstate](https://codegolf.stackexchange.com/users/36445/my-pronoun-is-monicareinstate)!!!
```
f(n,a,l,s,i)int*a;{for(s=i=!n;i<l&n>0;)s+=f(n-a[i++],a,l);n=s;}
```
[Try it online!](https://tio.run/##bYzBDoIwEAXvfEUl0XTtkoDYeKj1R5BDqalpgquh3ki/vZYQT3p982Zsdbc2JccJDY4Y0IOn996o2T0nHrTXG1L@PO7oUisIQudnZTovRL8IoEgHFdPDeOIwF9llQ9czzeYDshbZMariNeXZ8XJ7u1KJjkscsAX4BU39JUvHrp0ckchOfzqNRLveY/oA "C (gcc) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~40~~ 36 bytes
Python answer port but Ruby strict typing means I can't coerce booleans into integers.
-4 bytes from dingledooper.
```
f=->n,a{n>0?a.sum{|e|f[n-e,a]}:1<<n}
```
[Try it online!](https://tio.run/##NYtNCoMwFIT3nmIWpYsSQ4wGi6g9SBFJaWwFfQ1VKUU9e/o2XQzz8zHv5fYNoavimoRdqVYXK6dlXDe3dVeKnbDNXiRlSXv4PPvB4eHmKQJI4GRR4dDKyQ/9LEfrcSzmV9sz9eCzgG0iR/dgoJEiixL1D4bNIOegGHLVOU8pyxhkWsGc1Q8 "Ruby – Try It Online")
[Answer]
# Perl, 52 bytes
```
$r.=1x$_."|"}{(1x$^I)=~/^($r@){1,$^I}$(?{$\++})(*F)/
```
## Usage
```
printf "2\n3\n4" | perl -p -i10 glovebox.pl
```
## Explanation
Attempts to turn the problem into a string matching one, then uses regex backtracking to do the hard work! In the example given above it ends up constructing a regex match similar to `1111111111 =~ /^(1{2}|1{3}|1{4}){1,10}$(?{$count++})(*F)/`
This will cause the regex engine to attempt each combination of the regex, using `(?{$count++})` to increase `$count` each time the engine matches the input and reaches that point in the pattern, but forcing a fail `(*F)` before the match returns to cause the engine to backtrack and start again with the next combination. `$count` ends up being the answer.
Slightly different approach, was hoping it'd end up a bit shorter though...
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
```
n!a|n<0=0|n<1=1|n>0=sum$(!a).(n-)<$>a
```
[Try it online!](https://tio.run/##y0gszk7NyfmvoaipYGWl4JlXoqBrpxANpGNBDCD9P08xsSbPxsDWAEga2hrW5NkZ2BaX5qpoKCZq6mnk6WraqNgl/s9NzMxTsFVIyedSUCgoygSao6JgqqCoEG2ko2Cso2ASiyRuaIBLAqwDKGqqo2Ae@x8A "Haskell – Try It Online")
Quick port of the Python answer, call as `n ! a`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~21~~ 20 bytes
```
⊞υ¹Fθ⊞υ↨Φυ№η⁻⊕ιλ¹I⊟υ
```
[Try it online!](https://tio.run/##NYy7CgIxEEV7v2LKGRjBXe22c0GwENIvW4QYSSAmmsf@/pgtLM89l2OczibpIKJacdgYBpoOr5QBvwT/7aqLxZsP1eYd59RiRcfw8LEVvEeT7dvGap/oiSEQ0d7pIZV9f866VFTpg62bSWQZTgzLyHBmuKyrHLfwAw "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 1 byte by using base conversion from 1 instead of summing a potentially empty list. Explanation:
```
⊞υ¹
```
Start our result list with the number of solutions for `n=0` which is always `1` (the empty list).
```
Fθ⊞υ
```
Loop `n` times, so that we calculate the results for `1..n`, appending them to the result list.
```
↨Φυ№η⁻⊕ιλ¹
```
Sum those results so far that contribute to the next total. For example, if `A` is `[2, 3, 4]`, then to calculate the result for `n=10`, we already know the results for `n=0..9`, but we only add the results for `n=6`, `n=7` and `n=8`. The sum is calculated by converting from base 1 in case the list is empty.
```
I⊟υ
```
Print the result for `n`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L€ãO˜¹¢
```
-4 bytes thanks to *@ovs*.
Very slow approach!
[Try it online](https://tio.run/##yy9OTMpM/f/f51HTmsOL/U/PObTz0KL//w0NuKKNdBSMdRRMYgE) or [verify the first two test cases at once](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6KGV/33ObY0oPry41v/0nEPrDi36r/M/OtpURyHaSMdYxyQ2FsgyNEBwYwE) (third one times out..).
**Explanation:**
```
L # Push a list in the range [1, first (implicit) input-integer]
€ # Map over each integer in this list
ã # Take the cartesian product of the second (implicit) input-list that many times
O # Sum each inner-most list
˜ # Flatten the list of lists
¹¢ # And count how many times the first input occurs in this list
# (after which the result is output implicitly)
```
---
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÅœʒåP}€œ€`Ùg
```
Here a faster (but now way longer) approach using the `Ŝ` builtin.
[Try it online](https://tio.run/##yy9OTMpM/f//cOvRyacmHV4aUPuoac3RyUAi4fDM9P//DU25oo11THXMYwE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P/DrUcnn5oUUXx4aUDto6Y1RycDiYTDM9P/6/yPjjbVUYg20jHWMYmNBbIMDVC5IFljHVMd89jYWAA).
**Explanation:**
```
Ŝ # Get all lists of positive integer that sum to the (implicit) input-integer
ʒ # Filter this list of lists by:
å # Check for each value whether it's in the second (implicit) input-list
P # And check if this is truthy for all of them
}€œ # After the filter: get the permutations of each remaining list
€` # Flatten one level down
Ù # Uniquify the list of lists
g # Pop and push the length for the amount of remaining lists
# (after which the result is output implicitly)
```
[Answer]
# [Julia 1.0](http://julialang.org/), 35 bytes
*port of [this](https://codegolf.stackexchange.com/a/203346/98541) Python answer*
```
f(n,A)=n>=0&&+(n<1,f.(n.-A,[A])...)
```
[Try it online!](https://tio.run/##bY1NCsIwEIXX5hSPIpLgGFp/qAtT6DlKF6IJpJQotkIPIq48nRepTVo34oNh4L1v3lT32h6Tru8Nd5QL5TIVLxZL7g4JGcmdXOVU5KWQUoq@1U3bQKFgGMR3hGJN2BC2pYDKsKYxSOLfJEm/kT8a/GGlY7QnVjJmLjdwS5WAdQh/Am8NDLf@OZRCFTyv6826tnY8er8eiAjWN02kCJSuG/0Pf/7ihGjGdXfVp1afMa9ENBW4Mxum/wA "Julia 1.0 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~59~~ 55 bytes
*Edit: -4 bytes thanks to Giuseppe*
```
g=function(t,l,u=t-l)sum(!u,unlist(sapply(u[u>0],g,l)))
```
[Try it online!](https://tio.run/##K/qfnpNflpqUX2H7P902rTQvuSQzP0@jRCdHp9S2RDdHs7g0V0OxVKc0LyezuESjOLGgIKdSozS61M4gViddJ0dTUxNugoapTrKGkY6xjommpoKyghEXXMLQAEXG0BxJCqTJWMdUxxwsZfEfAA "R – Try It Online")
Recursively removes each element from the glove box, and calls itself with the new total if there's anything left.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 54 bytes
```
Tr[Length/@Permutations/@IntegerPartitions[#,All,#2]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6Qo2ic1L70kQ98hILUot7QEKJOfV6zv4JlXkpqeWhSQWFSSCRaKVtZxzMnRUTaKjVX7H1CUmVei4JAebapTbaRjrGNSG8sFFzM0wCYIVGmsY6pjXhv7/z8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), ~~81~~ 80 bytes
```
f: func[x y][case[x = 0[1]x < 0[0]on[sum collect[foreach a y[keep f x - a y]]]]]
```
[Try it online!](https://tio.run/##VYzBCoMwEETvfsXgXdDaUihtP6LXZQ8xbmhpNBIV9OvTTaGHzmXmMcNE6dNDeuLkLnDraGnDzmTNLJpuqKnhDVf1msNI8zrABu/FLuRCFGOfMNjpLTLBYUOVkbPSryeDjqlA1gl0QIsjf7Gp/1HbVidnLpgwxde4gPRvCL5Hh7K6l06xA4PTBw "Red – Try It Online")
The same recursive approach almost everyone is using, much longer though.
[Answer]
# [Racket](https://racket-lang.org/), ~~74~~ 64 bytes
```
(λ(x y)(if(< x 1)(+(sgn x)1)(apply +(map(λ(a)(f(- x a)y))y))))
```
[Try it online!](https://tio.run/##fYwxDsIwFEN3TmGJAX9VSC0FsfQyXzSpIkIUtQzJ2bgDVwoJIwOSB1vP9qq3u3mWvdewYP2GHWdjXTCwhe8XE7LQWU5IGIQdtyUgSbUao8/o@NDYiiq0PNaWSpYmkSL1zG3Ra/YBtLjgwBNGnCv8QUP/h7XdWNfXdvoB "Racket – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes
```
Tr[Multinomial@@@FrobeniusSolve@##]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6Qo2rc0pyQzLz83MzHHwcHBrSg/KTUvs7Q4OD@nLNVBWTlW7X9AUWZeSbSyrl2agwOQXxecnJhXV81VXW2kY6xjUqtjWquD4BgagHnGOqY65kCeaS1X7X8A "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
Another sequence, another challenge.\*
### Definition
A prime `p` is in this sequence, let's call it `A`, iff for every digit `d` in `p`'s decimal expansion, you replace `d` with `d` copies of `d` and the resulting integer is still prime; zeros are not permitted.
For example, `11` is trivially in this sequence (it's the first number, incidentally). Next in the sequence is `31`, because `3331` is also prime; then `53` because `55555333` is also prime, and so on.
### Challenge
Given an input `n`, return `A(n)`, i.e. the `n`th item in this sequence.
### Examples
Here are the first 20 terms to get you started. This is [A057628](http://oeis.org/A057628) on OEIS.
```
11, 31, 53, 131, 149, 223, 283, 311, 313, 331, 397, 463, 641, 691, 937, 941, 1439, 1511, 1741, 1871
```
This means `A(0) = 11`, `A(1) = 31`, etc., when using zero indexing.
### Rules
* You can choose zero- or one-based indexing; please specify in your answer which.
* Instead of returning just the `n`th element, you can instead choose to return the first `n` terms.
* You can assume that the input/output will not be larger than your language's native integer format; however, the repeated-digit prime *may* be larger than your language's native format, so that will need to be accounted for.
* For example, `1871`, the last number of the examples, has a corresponding prime of `18888888877777771`, which is quite a bit larger than standard INT32.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, returned from a function, displayed in an alert popup, etc.
* [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.
\*To be fair, I had come up with the first few terms of the sequence just playing around with some numbers, and then went to OEIS to get the rest of the sequence.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
!fo§&öεpd´ṘΠdİp
```
[Try it online!](https://tio.run/##ASEA3v9odXNr//8hZm/CpybDts61cGTCtOG5mM6gZMSwcP///zQ "Husk – Try It Online")
```
! Index into
İp the list of primes
f for which:
d the digits of p
o§& satisfy both:
öεpd´Ṙ repeated "themselves" times, they form a prime.
Π they are all nonzero.
```
Erik the Outgolfer saved a byte. Using `ṗ` instead of `εp` would save another byte, but that makes the program so slow it times our even for n = 2.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes
-1 byte thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna)!
```
µNSÐPŠ×JpNpP½
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0Fa/4MMTAo4uODzdq8CvIOBIw///JgA//8K1TlPDkFDFoMOXSnBOcFDEgMK9//80 "05AB1E – Try It Online")
### Explanation
```
µNSÐPŠ×JpNpP½
µ # Do until the input is reached...
N # Push the iteration counter
S # Split it to its digits
Ð # And push two copies of it to the stack
P # Get the digital product of the counter
Š # And place it two places down the stack
×J # Repeat each digit by itself and join it back to a number
p # Check for primality on that result
Np # And on the original counter as well
PĀ # Create the product and truthify the result
# Implicit: If it is true increment the input number
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 14 bytes
```
ÆPaDxDḌÆPaDẠµ#
```
[Try it online!](https://tio.run/##y0rNyan8//9wW0CiS4XLwx09YNbDXQsObVX@//@/KQA "Jelly – Try It Online")
Mr. Xcoder: -1 Byte (logical all)
Erik the Outgolfer: -2 Bytes (one line instead of two)
HyperNeutrino: -1 Byte (return first n elements of sequence)
**Explanation**
```
ÆPaDxDḌÆPaDẠµ# First Link
ÆP Is prime?
a logical and
D convert number to list of digits
xD repeat each digit as many times as it's value
Ḍ convert to an integer
ÆP is prime?
a logical and
D list of digits
Ạ logical all
µ the following link as a monad
# Do this until n matches are found and return them all
```
Edit: originally submitted an answer that included numbers with 0 in it's decimal representation which is specifically not allowed.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 100 bytes
```
Nest[#+1//.i_/;!PrimeQ@FromDigits[##&@@#~Table~#&/@(l=IntegerDigits@i)]||Min@l<1:>NextPrime@i&,1,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n1aal2z73y@1uCRaWdtQX18vM17fWjGgKDM3NdDBrSg/1yUzPbOkOFpZWc3BQbkuJDEpJ7VOWU3fQSPH1jOvJDU9tQiiwiFTM7amxjczzyHHxtDKzi@1ogRsikOmmo6hjnKs2n8gN6/EAWRhtJFB7H8A "Wolfram Language (Mathematica) – Try It Online")
Jonathan Frech saved 3 bytes
and -7 bytes from JungHwan Min
-15 bytes from Martin Ender
also thanks to Jenny Mathy
[Answer]
## [Alice](https://github.com/m-ender/alice), ~~72~~ ~~70~~ ~~66~~ ~~62~~ 56 bytes
*Thanks to Leo for saving 5 bytes.*
```
/.\&wh...tz~F0/*$\W.tzt$W?K/ o
\i/&.,a:.$K;d&\FR/K.!w.a%
```
[Try it online!](https://tio.run/##S8zJTE79/19fL0atPENPT6@kqs7NQF9LJSYcyCxRCbf31lfI54rJ1FfT00m00lPxtk5Ri3EL0vfWUyzXS1T9/98UAA "Alice – Try It Online")
Uses 1-based input.
### Explanation
The neatest golfing trick here (even though it only saves a couple of bytes) is that I'm using a primality test which gives `0` for composite **n** for `n` for non-composite **n**. That way, we don't have to use the result directly in a conditional, but we can pass it straight on to the next part that checks that the input doesn't contain any zeros.
```
/i\ Read all input in Ordinal mode (the usual way to read decimal input).
&w Push the current IP position onto the return address stack (RAS)
n times. This effectively begins our main loop. We will return
here after each number we've checked, but whenever we come across
a repeated digit prime (RDP), we will pop one copy of the address
from the RAS, so that the loops ends once we've found n RDPs.
h. Increment our main loop iterator X (initially an implicit zero on
the empty stack) and duplicate it.
. Make another copy.
.tz Drop all factors less than X. This gives X for prime X and 1 for
non-prime X.
~F Check whether X divides this value. Of course, X divides X so this
gives X for non-composite X. But X doesn't divide 1 (unless X is 1),
so we get 0 for composite X. Call this Y.
0 Push a 0.
\ Switch to Ordinal mode.
F Implicitly convert both to string and check whether Y contains 0.
$/K If it does, return to the w. Either way, switch back to Cardinal mode.
Note that the only numbers that get to this point are 1 and prime
numbers which don't contain 0. It's fine that we let 1 through here,
because we'll use a proper primality test for the digit-expanded
version later on.
.! Store a copy of X on the tape. Let's call the copy that remains on
the stack Z, which we're now decomposing into digits while expanding
them.
w Push the current IP position to the RAS. This marks the beginning
of an inner loop over the digits of Z.
.a% Duplicate Z and retrieve its last digit D by taking Z % 10.
\./ Duplicate D (in Ordinal mode but that doesn't matter).
&. Duplicate D, D times. So we end up with D+1 copies of D.
, Pop the top D and pull up the Dth stack element, which is Z.
a: Discard the last digit by taking Z / 10.
.$K If Z is zero now, skip the K and end the inner loop, otherwise
repeat the inner loop.
; Discard the 0 (what used to be Z).
We now have D copies of each digit D on the stack, but the digits
were processed in reverse order, so the last digit is at the bottom.
d& Repeat the next command once for each stack element.
\* Concatenate in Ordinal mode. This joins all the digits on the
stack into a single string.
R Reverse that string. This is the digit-expanded version of X.
/ Switch back to Cardinal mode.
W Pop the inner loop's return address from the RAS. We could have done
this right after the most recent K, but putting it here helps lining
up the two Ordinal sections in the program layout.
.tzt Is the digit-expanded number a prime?
$W If so, we've found an RDP. Pop one copy of the main loop address
from the RAS.
g Recover the current value of X from the top left grid cell.
K Jump back to the w if any copies of the return address are left
on the RAS. Otherwise, we leave the main loop.
/o Implicitly convert the result to a string and print it in
Ordinal mode.
The IP will then bounce off the top right corner and start
travelling through the program in reverse. Whatever it does
on the way back is utter nonsense, but it will eventually get
back to the division (:). The top of the stack will be zero
at that point and therefore the division terminates the program.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 130 bytes
* Thanks to [ArBo](https://codegolf.stackexchange.com/users/82577/arbo) for this four byte shorter solution.
```
f=lambda n,c=9:n and f(n-(('0'in`c`)<p(c)*p(int("".join(d*int(d)for d in`c`)))),c+1)or~-c
p=lambda n:all(n%m for m in xrange(2,n))
```
[Try it online!](https://tio.run/##PY3BCsIwEETvfsVSkO7WVGz0YrH/0pgYrSSbEHrQi78eEwTn8GDgMRPf6yOwzNlOTvmrUcBCT@eRQbEBi9wjtod24VnPdImoqYu48IpNs3@GhdF0tRmyIYGBn1ci9G6gkD693sT/8qicQ956qLIvMryS4vsNpWCiHFOZKp8DCYuy4lhxovwF "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), ~~195~~ ~~179~~ ~~167~~ ~~140~~ ~~138~~ ~~136~~ ~~135~~ 134 bytes
* Saved 27 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs); using `xrange` instead of `range`, thus circumventing a `MemoryError` and compacting the prime function; improving integer index counting.
* Saved two bytes; using binary pipe or operations `|` to save bytes over `or`.
* Saved two bytes; inverting the prime function and doing some further logic manipulation.
* Saved a byte; using `~-` instead of `0**` to invert the existence of a zero in `j`, as `&` followed by a true boolean isolates this value's boolean property.
* Saved a byte thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn); golfing `~-A&B&C` (equivalent to `(not A) and B and C`) with `A, B, C` being booleans to `A<B==C`.
```
def f(n,j=9,p=lambda n:all(n%j for j in xrange(2,n))):
while n:j+=1;n-=("0"in`j`)<p(j)==p(int("".join(d*int(d)for d in`j`)))
print j
```
[Try it online!](https://tio.run/##JYxBCsIwEEX3PcUQEGa0iq1ubM1dGkliM8RpCAX19LHBzYP3efz0XedF@lKs8@BRWta3NuloXg9rQAYTI8qOwS8ZGILAJxt5OuxbIaKhgfccottCPuhulKNGdVZBJp7onpBJ64RBVlTqxEsQtPtqluqfhX9I1EDK2w5cPHY0euwrLhVXKj8 "Python 2 – Try It Online") (1-indexed)
# Explanation
Defines a main function `f` which takes in an integer index, `n`, and a by default set value `j`, the current sequence canditate (intitiated to `9` to improve performance whilst keeping program size) and a prime checking function.
As long as `n` is non-zero, the `n`-th sequence entry is not yet found. Thus `j` is incremented and `n` is decremented by one iff `j` is a number which satisfies the required properties.
When the loop ends, `j` is the `n`-th sequence entry and thus printed.
[Answer]
# [Pyth](https://pyth.readthedocs.io), 21 bytes
```
.f&.AKjZT&P_ss*VK`ZP_
```
**[Try it here!](https://pyth.herokuapp.com/?code=.f%26.AKjZT%26P_ss%2aVK%60ZP_&input=4&debug=0)**
Rather lengthy as Pyth doesn’t have a *Decimal Expansion* built-in.
* Take the first **N** positive integers (`.f`), that:
+ Have all the digits truthy (`.AKjZT`), and (`&`)...
+ The vectorized multiplication of their string representation with their digits (`*VK`Z`), joined together and converted to an integer (`ss`) are prime (`P_`), and (`&`)...
+ That are primes themselves (`P_`).
[Answer]
# [Perl 6](http://perl6.org/), 51 bytes
```
{(grep {!/0/&is-prime $_&S:g/./{$/x$/}/},2..*)[$_]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiO9KLVAoVpR30BfLbNYt6AoMzdVQSVeLdgqXV9Pv1pFv0JFv1a/VsdIT09LM1olPrb2v7VCcWKlgpJKvIKtnUJ1GlB1rZJCWn6RQpyhgfV/AA "Perl 6 – Try It Online")
* `grep {...}, 2..*` filters the infinite sequence of natural numbers starting from 2 using the predicate function between the braces. `(...)[$_]` indexes into this filtered list using the function's argument `$_`.
* `!/0/` filters out numbers that contain a zero digit.
* `S:g/./{$/ x $/}/` replicates each digit in the test number's decimal expansion.
* `is-prime $_ & S:g/./{$/ x $/}/` calls the built-in `is-prime` function with an and-junction of `$_`, the test number, and the number resulting from replicating its digits. The function will return true if both members of the and-junction are prime.
[Answer]
# J, 81 bytes
```
f=.[:1&p:(*@(*/)*x:@#~)&.(10&#.inv)
[:{.(4&p:@{.@]([,]+f@[){:@])^:([>{:@])^:_&2 0
```
This is [one of those situations](https://stackoverflow.com/questions/47493520/nth-number-for-which-a-filter-verb-returns-true/47493751?noredirect=1#comment81952558_47493751) for which I haven't yet found a good J solution.
Nevertheless, I post this in hopes of learning something new.
`f` tells us if a given number is a "repeated digit prime". It breaks down as follows:
```
[:1&p: is the following a prime?
(*@ the signum of...
(*/) the product of the digits
* times...
x:@ force extended precision of...
#~) self-duplicated digits
&. "Under": perform this, then perform its inverse at the end
(10&#.inv) convert to a list of digits
```
And finally the main Do... While verb, with its pesky, seemingly unavoidable boilerplate, which arises from the fact that we need to use a list to store our progress, which requires both "current prime" and "found so far" registers, since our left argument is already taken to store the stopping condition, ie, `n`. This means that we must use many precious bytes for the simple task of specifying args (`[` and `]`) and unpacking our 2 element list (`{.` and `{:`):
```
[:{. take the first element of the final result, of the following Do... While:
(4&p:@ the next prime after...
{.@ the first element of...
] the right arg
{:@]) the last (2nd) elm of the arg...
([,]+f@[) those two now become the left and right args to this verb...
[, left arg appended to...
]+ right arg plus...
f@[ f of the left arg...
^:( )^:_ keep doing all that while...
[> the left is bigger than...
{:@] the last elm of the right arg
&2 0 seed the process with 2 0, ie,
the first prime, and 0 rdps found so far.
```
[Try it online!](https://tio.run/##LUtLCsIwFNz3FA8LIWlD7EvSTwJK8ABeoFQXYmtdqCsRCl49vhQXM8z3HuO4U71H9vK8CLzYiuLjQ/4VTHGsWK7mx1tkU9osiluahUWFgfdyKMfQi8WHQZw87/d/dWYaqng8KECUYAi1kYBJoHUStCarO5O6dZBUao1rJdiGbGPJNo7IGcqcXb@GzlinD7Zr0rWJnXXZ9XJ7Ap82lQAsZ6Ux/gA "J – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 88 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 11 bytes
```
Þp'f:ẋfṅ⌊æ;~AẎ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwiw55wJ2Y64bqLZuG5heKMisOmO35B4bqOIiwiIiwiNyJd)
Bitstring:
```
0010101101000000100111110011100100110010100100011000111001011001000011111011010100010010
```
] |
[Question]
[
## Goal
Your task is to create a program taking no input that returns the link to your answer. You can find a link to your answer by clicking at the share button on your answer.
## Rules
1. Standard loopholes apply except for searching for the answer online. In fact, you are expected to find the answer online.
2. You are allowed to use curl or the equivalent, but you are not allowed to use any html parser library or built-in. If you need to import the library, the import declaration does **NOT** count into the code size as long as you don't rename any identifiers.
3. **You are not allowed to assume, or hardcode, the link to your answer**. You have to search this page for your submission. If you remove your submission and re-add it, and your code breaks, you fail the challenge.
4. You may still assume your username, the contents of your code, and the programming language/byte count you are using. You are not allowed to assume the description below your code. If you edit the description part of the submission and the code breaks, you fail the challenge. You may assume that the code of each submission is unique and no one copies your submission into another answer.
5. Your answer has to be exactly the same as what you get when you clicked on the share button.
6. You may post the dummy answer for the prototyping purpose. Just delete it immediately after posting, and edit your answer into it once completed.
7. You are not allowed to take an user input
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so, the shortest answer in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~61~~ 57 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
“¦ɦḍɓḃɠṭṢ⁽&½ṛøHØÐ»Ȯ;⁾q/;“£ɓ⁶’ŒGœṣ“"/a/”iƇ”ɦṪṣ”=-3ịḊḣ6⁾a/;
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDy04ue7ij9@TkhzuaTy54uHPtw52LHjXuVTu09@HO2Yd3eByecXjCod0n1lk/atxXqG8N0rH45ORHjdseNcw8Osn96OSHOxcDBZX0E/UfNczNPNYOJIEm7lwFFp9rq2v8cHf3wx1dD3csNgMakahv/f8/AA "Jelly – Try It Online")
What's a worse idea than parsing HTML with regex? Parsing HTML with *Jelly*
This outputs `codegolf.stackexchange.com/a/226641`. This will fail if this is "reposted" after ~780000 more posts are posted to the site, but that is currently 3.5 times the number of posts we currently have. A more future-proof version comes out as [the same length](https://tio.run/##y0rNyan8//9Rw5xDy04ue7ij9@TkhzuaTy54uHPtw52LHjXuVTu09@HO2Yd3eByecXjCod0n1lk/atxXqG8N0rH45ORHjdseNcw8Osn96OSHOxcDBZX0E/UfNczNPNYOJIEm7lwFFp9rq2v8cHd32uEZLkD9ifrW//8DAA)
## How it works
This works in two parts. First we build and print the string to fetch the HTML of the question (including the answers), then we process and extract my answer id
```
“¦ɦḍɓḃɠṭṢ⁽&½ṛøHØÐ»Ȯ;⁾q/;“£ɓ⁶’ŒG - Main link
“¦ɦḍɓḃɠṭṢ⁽&½ṛøHØÐ» - Compressed string "codegolf.stackexchange.com/"
Ȯ - Print this
;⁾q/ - Concatenate "q/"
“£ɓ⁶’ - Compressed integer: 226635
; - Concatenate; "codegolf.stackexchange.com/q/226635"
ŒG - GET request, prepending "http://"
```
Building the string this way takes 2 more bytes than simply compressing `codegolf.stackexchange.com/q/226635`: [`“ñoHƑ;ɦŻt%WɓḤȦ3æḶ2ỤƭȮ¦1ẈA»`](https://tio.run/##ATgAx/9qZWxsef//4oCcw7FvSMaRO8mmxbt0JVfJk@G4pMimM8Om4bi2MuG7pMatyK7CpjHhuohBwrv//w). However, by having `“¦ɦḍɓḃɠṭṢ⁽&½ṛøHØÐ»` (`"codegolf.stackexchange.com/"`) by itself at the start, we can print it using `Ȯ`, allowing us to just output `a/226641` later on
```
œṣ“"/a/”iƇ”ɦṪṣ”=-3ịḊḣ6⁾a/; - Main link.
To our left, we have the HTML content of this page
“"/a/” - Yield '"/a/'
œṣ - Split at '"/a/', splitting roughly into answers
iƇ”ɦ - Keep those with the "ɦ" character in them. Currently, that's just me
Ṫ - Extract this bit of HTML
ṣ”= - Split at equals signs
-3ị - Take the 4th from last, which is '"226641"> <div class'
Ḋ - Remove the quote
ḣ6 - Extract the first 6 characters
fØD - Future proof version: keep only digits
⁾a/; - Prepend "a/" and output
```
[Answer]
# JavaScript (Browser Console), 155 bytes
```
alert(`${c='https://codegolf.stackexchange.com/'}a/${(await(await fetch(c+`search?q=user:${u=44718}+inquestion:226635`)).text()).match(/(?<=s#)\d+/)}/${u}`)
```
I'm using Firefox 88. The code need to be executed under same domain due to permission restriction of fetch.
Btw, top level await is allowed in most browsers' console.
[Answer]
# [Red](http://www.red-lang.org), 151 byte
```
r: :rejoin n:"104280"u: https://codegolf.stackexchange.com/ r[u"a/"parse read r[u"questions/226635"][collect[thru[{"}ahead[22 skip n]]keep to{"}]]"/"n]
```
No TIO link, since it uses an outdated toolchain and errors out during lexing. Try it [locally](https://www.red-lang.org/p/download.html) instead, using the latest automated build.
---
Red's implementation of GZIP and DEFLATE decompression is completely broken, so, instead of working with [StackExchange API](https://api.stackexchange.com/docs/compression), I had to fall back on HTML parsing... which is a nice showcase in its own regard, since the solution relies on the embedded PEG parsing DSL.
[Answer]
# [PHP](https://php.net/) 5, 211 bytes
```
foreach(json_decode(gzdecode(join(file('http://api'.($s='.stackexchange.com/').'2.2/questions/226635/answers?site=codegolf'))))->items as$i)if($i->owner->user_id==90841)echo"https://codegolf{$s}a/$i->answer_id";
```
[(Cannot) Try it online!](https://tio.run/##NY7dboMwDIVfZaqQklyQbGxD@4M@ShUFQ0zbOMNBTKv67DSomy8s68jnOyf6uH7tY949TWCdlyNTOHTgqAM5/P4dI2GQPZ5ACp9S/DDGRhRaFtwIzcm6I/w4b8MA2tHZCKVFpSvzPQMnpMCmqur6@dXYwAtMvGdM0GzkgU69UHnKNktnfrBcoMJeFli2tASYynZmmA7YNc3749vLkwLnabe14Fzjn3Ep@GrNZrpH5P/d57reAA "PHP – Try It Online")
Unfortunately, `file` and `gzdecode` functions re disabled in PHP online testers, but it works so far on my localhost
**EDIT:** first version didn't work (because of the content of my own answer, lol) and was easy to break with a single comment, switched to a supposedly foolproof version with the API, much longer though
**EDIT 2:** saved 5 bytes with strings optimizations
**EDIT 3:** another byte saved (the dust) by using `http` instead of `https` for the API
[Answer]
# [Go](//golang.org), 342 bytes
```
package main
import(."encoding/json"
."net/http")
func main(){t,u:="codegolf",".stackexchange.com/"
r,_:=Get("https://api"+u+"2.2/questions/226635/answers?site="+t)
var s struct{Items[]struct{Answer_ID int
Owner struct{User_ID int}}}
NewDecoder(r.Body).Decode(&s)
for _,i:=range s.Items{if i.Owner.User_ID==7815{print(t,u,"a/",i.Answer_ID)}}}
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + [Wget](https://www.gnu.org/software/wget/) + [Sed](https://www.gnu.org/software/sed/), 114 bytes (104 bytes + 5 byte user ID twice)
```
U=https://codegolf.stackexchange.com
wget $U/q/226635 -O-|sed -nE '/44694/s?.*answer-([0-9]+).*?'$U'/a/\1/44694?p'
```
Prints `https://codegolf.stackexchange.com/a/226723/44694` on stdout.
Note that `wget` prints logs to stderr, which should be ignored.
(No TIO link because wget doesn't work on TIO; I assume TIO blocks internet access.)
Explanation:
* Save the string `https://codegolf.stackexchange.com` in `$U`
* `wget` the webpage for this question, piping it to `sed`
* Using `sed`:
+ Search for all lines containing my user ID.
+ (Specifically we are looking for the line containing `<div
id="answer-**XXXX**" class="answer" data-answerid="XXXX"
data-ownerid="**YYYY**" ...`, where `**YYYY**`
is my user ID, and `**XXXX**` is the answer ID we are
looking for.)
+ If the line contains `answer-**XXXX**`, then
- The `**XXXX**` is the answer ID; capture it in a subexpression.
- Print the string saved in `$U` followed by `/a/`, followed by the answer ID using `\1` subexpression replacement, followed by a slash and my user ID.
---
# [Bash](https://www.gnu.org/software/bash/) + [Wget](https://www.gnu.org/software/wget/) + [Sed](https://www.gnu.org/software/sed/), 100 bytes (95 bytes + 5 byte user ID)
If the output format is not as strict, then I have a 100 byte version that prints the URL without the `https://` or the trailing user ID.
Prints `codegolf.stackexchange.com/a/226723` on stdout.
```
U=codegolf.stackexchange.com
wget $U/q/226635 -O-|sed -nE '/44694/s?.*answer-([0-9]+).*?'$U'/a/\1?p'
```
* -8 bytes: no `https://`
* -(1+5) bytes: no trailing `/` and user ID
[Answer]
## JavaScript (ES6), 216 bytes
```
fetch("https://api.stackexchange.com/2.2/questions/226635/answers?site=codegolf").then(r=>r.json()).then(j=>"https://codegolf.stackexchange.com/a/"+j.items.find(a=>a.owner.user_id==17602).answer_id).then(console.log)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 60 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
’ƒËŠˆ.‚‹º.ŒŒ’žYì©…/q/•3{Ä•J.w“"/a/“¡ʒ'ʒå}`'=¡4(èþ'a®rŽÍ¿'/ý
```
Port of [*@cairdCoinheringaahing*'s Jelly answer](https://codegolf.stackexchange.com/a/226641/52210), so make sure to upvote him.
Assumes this is the only answer that contains a `ʒ`. If another answer should pop up with this character, it could be switched to another unique character from my program that probably isn't used in a lot of languages instead, like `þ` or `®`.
No TIO of the entire program, since `.w` is disabled.
**Explanation:**
Generate the question URL, and get its HTML content:
```
’ƒËŠˆ.‚‹º.ŒŒ’ # Push dictionary string "codegolf.stackexchange.com"
žYì # Prepend "https://"
© # Store this string in variable `®` (without popping)
…/q/ # Push string "/q/"
•3{Ä• # Push compressed integer 226635
J # Join the entire stack together
.w # Browse to this URL and get its HTML content as string
```
[Try it online](https://tio.run/##yy9OTMpM/f//UcPMY5MOdx9dcLpN73DTo4ZZjxp2Htqld3TS0UlAqaP7Ig@vObTyUcMy/UL9Rw2LjKsPtwApr///AQ) (without `.w`).
And then get the answer-ID and generate the resulting URL:
```
“"/a/“¡ "# Split the HTML content on '"/a/'
ʒ # Filter these parts by:
'ʒå '# Check if it contains character "ʒ"
}` # After the filter: pop and push this only part to the stack
'=¡ '# Split it on "="
4(è # Index to get the 0-based -4'th item (fourth item from the back)
þ # Only leave its digits
'a '# Push string "a"
® # Push the string from variable `®`
r # Reverse the three values on the stack
ŽÍ¿ # Push compressed integer 52210
'/ý '# Join the stack with "/" delimiter
# (after which the result is output implicitly)
```
The URL generated by TIO would be too big for a stackexchange answer and most URL-shorteners unfortunately, so here the TIO where you'll have to insert the question's HTML content yourself (Ctrl+U in your browser, select everything, and past it between the `"""` in the input-block of the TIO):
['Try it online.'](https://tio.run/##yy9OTMpM/f@oYeaxSYe7jy443aZ3uOlRw6xHDTsP7dI7OunoJKDU0X2Rh9ccWvmoYZl@of6jhkXG1YdbgJRXDFDfHCX9RKDYnEMLT01SPzXp8NLaBHXbQwtNNA6vOLxPPfHQuqKjew/3Htqvrn947///SkpKXB4hvj7xzv5@Ia5@IfHu/q7B8R6uQa5cQCkA)
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how `’ƒËŠˆ.‚‹º.ŒŒ’` is `"codegolf.stackexchange.com"`; `•3{Ä•` is `226635`; and `ŽÍ¿` is `52210`.
] |
[Question]
[
*Huge omega thanks to @wasif for emailing me this challenge idea in its basic form*
Everyone knows that questions on StackExchange require tags - labels that allow posts to be grouped together by category. However, most of the time, I barely know which tags exist, because there's just *so many* of them.
Henceforth, today's task is to tell me every single tag that exists on the Code Golf and Coding Challenges Stack Exchange.
## The Challenge
Write a program or function that prints/returns a list of all available tags on <https://codegolf.stackexchange.com>
As tags can be created/deleted at any time, simply hard-coding a list of tags is not a valid solution - the list must be correct at run-time regardless of when the program/function is executed.
The tags avaliable can be seen [here](https://codegolf.stackexchange.com/tags)
## Rules
* As this is an [internet](/questions/tagged/internet "show questions tagged 'internet'") challenge, internet connections are allowed. However, web requests can only be made to codegolf.stackexchange.com and api.stackexchange.com domains.
* Output can be given in any convenient and reasonable format.
* The tags can be in any order, so long as all current tags are returned.
* The exact name of the tags must be used (e.g. `code-golf` is valid, `code GOLF` is not valid.)
* And as usual, standard loopholes apply, shortest code wins
## Example Program
```
import urllib.request
import regex
pobj = regex.compile('rel="tag">(.*)</a>')
page_number = 2
req = urllib.request.urlopen(f"https://codegolf.stackexchange.com/tags?page=1&tab=name")
data = req.read().decode('utf-8')
tags = []
while data.count("tag") != 43:
tags += pobj.findall(data)
req = urllib.request.urlopen(f"https://codegolf.stackexchange.com/tags?page={page_number}&tab=name")
data = req.read().decode('utf-8')
page_number += 1
print(tags)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~60~~ ~~57~~ 56 bytes
```
[N>’¸¸.‚‹º.ŒŒ/›´?€¼=ƒËŠˆ&€®=ÿ’.wD2è'eQ#“e":"“¡¦ε'"¡н]\)
```
Outputs as a list of pages, where each page is a list of tags.
```
[N>’...’.wD2è'eQ#“e":"“¡¦ε'"¡н]\) # trimmed program
[ # # while...
è # character in...
.wD # data of response from URL...
# (implicit) "http://" concatenated with...
’...’ # "api.stackexchange.com/tags?site=codegolf&page=ÿ"...
# (implicit) with ÿ replaced by...
N # current index in loop...
> # plus 1...
è # at index...
2 # literal...
# # is not...
Q # equal to...
'e # literal...
.w # push data of response from URL...
# (implicit) "http://" concatenated with...
’...’ # "api.stackexchange.com/tags?site=codegolf&page=ÿ"...
# (implicit) with ÿ replaced by...
N # current index in loop...
> # plus 1...
¡ # split by...
“e":"“ # literal...
¦ # excluding the first...
ε # with each element replaced by...
н # first element of...
# (implicit) current element in map...
¡ # split by...
'" # literal
] # exit map
] # exit infinite loop
\ # delete top element of stack
) # push stack
# implicit output
```
[Answer]
# [Jyxal 0.2.0](https://github.com/Vyxal/Jyxal/tree/0.2.0), 44 bytes
```
0{›:`ȯø.⟩β•∵.•⅛/ɾƈ?λ→=%&λẋ=¬⋎»₅`%¨UøJht(ntt,
```
[Jyxal-is-not-hosted-anywhere-so-read-the-readme-to-see-how-to-try-this](https://github.com/Vyxal/Jyxal/blob/master/README.md)
Fixed thanks to @emanresu A
Absolutely crushes 05AB1E. On my machine, it goes through the first 25 pages before getting a 403 and printing `4` forever. Unfortunately, Vyxal cannot decompress zipped responses so I kinda had to use Jyxal in place. This is heavily dependent on the ordering of the values in the JSON response.
```
0{›:`ȯø.⟩β•∵.•⅛/ɾƈ?λ→=%&λẋ=¬⋎»₅`%¨UøJht(ntt, # I don't need the 2 closing parens at the end.
0 # Push 0 (Jyxal does not have implicit input yet)
{ # Loop forever
› # And increment the number
% # Replace all "%" in the string...
`ȯø.⟩β•∵.•⅛/ɾƈ?λ→=%&λẋ=¬⋎»₅` # "api.stackexchange.com/tags?page=%&site=codegolf"
: # With the current loop index
¨U # Make a GET request to that URL...
øJ # And decode the JSON response
h # Get the first key-value pair...
t # And the second item; that is, the "items" array
(n # For each item in that array...
t # Get the last key-value pair and then...
t # Get the value
, # Print that value
```
[Answer]
# Python 3 + `requests`, 143 bytes
```
from requests import*
p=1
while[print(x["name"])for x in get(f"http://api.stackexchange.com/tags?page={p}&site=codegolf").json()["items"]]:p+=1
```
-19 bytes thanks to Jonathan Allan
-5 bytes thanks to dingledooper
[Answer]
# JavaScript (Firefox chrome), 135 bytes
```
f=async(i=1)=>(await((await fetch('http://codegolf.stackexchange.com/tags?page='+i)).text())).match(/[\w-]+(?=)/g).map(alert)|f(i+1)
```
1. ~~Open [Browser Console of Firefox](https://developer.mozilla.org/en-US/docs/Tools/Browser_Console);~~ You may however open console on this page instead;
2. Paste codes there;
3. Invoke it by running `f()`;
4. Click to close many many `alert`'s
---
Source codes for tags page contains line
```
<a href="/questions/tagged/code-golf" class="post-tag" title="show questions tagged 'code-golf'" rel="tag">code-golf</a>
```
We match the text `code-golf` between `'` by `/[\w-]+(?=)/g`.
The recursion terminate when ith page contains no tags. While the match result is null, and `.map` on `null` cause an error.
[Answer]
# JavaScript, 176 bytes
```
async _=>{t=[];i=1;do t.push(...(j=await (await fetch("http://api.stackexchange.com/2.2/tags?site=codegolf&page="+i++)).json()).items);while(j.has_more)return t.map(d=>d.name)}
```
Must be run on `api.stackexchange.com` subdomain; I use `/docs` for testing.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + wget + jq, 86
Assumes there are no more than 99 pages of results (currently 10 pages).
```
wget -qO- api.stackexchange.com/tags?site=codegolf\&page={1..99}|zcat|jq .items[].name
```
Testing this blew through my daily API requests limit pretty quick.
] |
[Question]
[
This is the **Robbers** thread. For the Cops challenge, see [here](https://codegolf.stackexchange.com/q/212068/66833)
As the robbers, your job is to crack the cops' answers. Choose an uncracked, unsafe cop answer and attempt to figure out which languages, in which order, the cop used.
Note that a crack is valid *even if the languages are different*. So long as the the languages you find, in the order you state them, produce the specified final phrase, the crack is valid, even if the languages are not the same as the intended or original cop answer.
If you are unable to fully crack a cop's answer and decide to abandon your attempt, you can (but are by no means expected to) comment underneath the cop's answer with the languages you've already figured out, in order to help other users.
Having fully cracked a cop's answer, post an answer to this thread listing all the languages, along with their outputs in the following format:
```
# [<cop>'s answer](<link to answer>), <N> layers
Languages used:
- Layer 1: [<language 1>](<link to interpreter>), outputted <output>
- Layer 2: [<language 2>](<link to interpreter>), outputted <output>
...
- Layer <N>: [<language N>](<link to interpreter>), outputted <final phrase>
---
<anything else>
```
After posting an answer, leave a comment below the cop's post to let them know it's been cracked. If you have \$<50\$ reputation at the time of posting, and therefore cannot comment, I (or another able user) will be happy to do so for you, simply make a note of this in your answer and someone will take care of it.
This challenge can result in some very difficult answers to crack - more so than the standard [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") - due to the fact that the number of languages a cop could've used increases exponentially per layer they have. Therefore, be sure to check out the [Robbers' chatroom](https://chat.stackexchange.com/rooms/113749/peel-away-the-layers-robbers-room) to get help cracking an answer, or to help others.
Your score is calculated the following way:
* If you crack \$n\$ answers, with \$x\_1, x\_2, ..., x\_n\$ languages being used (i.e. the first has \$x\_1\$ languages, the second \$x\_2\$ etc.), your score is
$$\frac{1}{n}\sum^n\_{i=1}x\_i$$
i.e. the total number of languages you cracked, divided by the total number of answers you cracked. The lower your score, the better. Don't bother editing your score into your answers, a winner will be declared when all cop answers are either cracked or safe.
Good luck!
[Answer]
# [Sisyphus's Answer](https://codegolf.stackexchange.com/a/212086/68942), 33 layers
```
i=496;a= 0
print('gREETINGS!'.swapcase()if a==447775else'i=%3s;a=%6s%s'%(i-16,a+(int(1/2*2)*int('syd0s6ncczl7ka1ioletm9t1atoqjq2awpshwfxcorai94tcmzim91j2zzq2c08wxjmfmzr0x9euhjojhltjpay0g8t1o78y83a',36)>>i&0xFFFF),open(__file__).read().strip()[14:]))
```
All layers are Python, in this order: 3, 3, 3, 3, 3, 2, 3, 3, 2, 2, 2, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2/3 (the last layer does not matter).
Special thanks to @Riolku for helping me find the right algorithm for subset sum (because I'm bad at computer science and Google)
Since there are so many layers, writing them all as a list would be rather difficult and take me a lot of time (and anyone who wants to verify it a ton of time), so instead you can verify it by running all 33 layers with [this Bash program](https://tio.run/##7VNNT4NAEL3zK7AJwtaKLCAfNvRWGy8e1JsxZNwuZRHYLbsNH38eWz8Sj55MavpOM2/evMxMMq8g83GkJOf6hCV@HMwh0Q9wNNGwWlnm5mG5fLq7Xz2embZsQRCQ1EIs0yFJfD8Mw2taSmqyxPDkvtkIpCFNw2KXOJjBhXXwwFfu1EXTDzvZrx0Z1IQMZfgGmPGSqipWGBTfFlsXWiHzNusIb4DFviLVwKoYF@4wbF3iRG1XVFk1NE4X011e8CIvVSGgdzaRwjyM@sgDc@YFaLFg5053uweacUFrK00zVtI0RXZDYW0hW6qGCQs9Y//mBaGJvtAVlcoWvaaJXuW89r6JfQlsvlNznYD6DH@oj1fsHuEY7hEu@O9PdxKfxH//g7901g7kVzKO7w) that compiles all of the layers together.
Let me know if this posting format is invalid.
[Answer]
# [Bubbler's answer](https://codegolf.stackexchange.com/a/212093/48931), 3 layers
```
101;1111011;0000;11011111;{110000;11100010;11011110;00110;10111011;000110;10001;0100000;11011;000;11010101;0000010000;10100000;101101;0100000;1101111;0101111;}1001010;0000;100000;10110001;011001;011"00001101110100100010011001000;{111;011111;}1000\1101100;010110;110011;0\;110001;0111010;110010\10110;110001;0110000;\11011;0010;11001;011\11;0100000;11010100\;10110001;101110;1\001;001010;110111\0000;10110001;10\1011;0000;10100\000;0100110111\101101111111"@
```
Layer 1: [Hexagony](https://tio.run/##XVE5EsIwDPwLL9it1fAQNRQMqUILk@HtRqdNcGYiKdpDcrb76/Z47u8xCArtgBTYkUjtyGFZfvDI2YHh/B1V0bK2KAhSgaUzf0IepTlhTv1jMeqIHyLINdoPJ71Y4YIcIiZKEyLbzjhSc0pCmSJpFL4xrsqSJrph8IlqW@Nq79g47yjP23iua@QcUagBB9e96nm3MpV1XQ6QWsvxRP8q2/86xhc), outputted
```
echo'@',~;0j1":&.>10#.#:91 7 4 5 160 127 7 172 30 198
```
Layer 2: [J](https://tio.run/##y/r/PzU5I1/dQV2nztogy1DJSk3PztBAWU/ZytJQwVzBRMFUwdDMQMHQyBzIMzQ3UjAGciwt/v8HAA), outputted
```
1011011.0111.0100.0101.010100000.01111111.0111.010101100.011110.011000110.0@
```
Layer 3: [Labyrinth](https://tio.run/##y0lMqizKzCvJ@P/f0MAQhPSAGEQYGIAIMAvINgBzIQCuAqwDKg6mgKrALIf//wE), outputted
```
Code Golf.
```
[Answer]
# [User's Answer](https://codegolf.stackexchange.com/a/212239/97691), 3 layers
```
class Main:
print(
"""class Main {public static void main(String[] args) {String a="ɗefine";char c=10;String z="pɼint";char d=23;String y="⁸fẇ×ịṛs⁷";String e="";char x=90;String b="⁺°`¬²ịĿ°£Oḋ®ẋṄ¢¦";String w="⁸Ḷ⁸Ŀ~ʋ^ḋ*Ẓ>{S";String i="return";String n=" ";String f="Game";String s="main";String t="def";String k="#";String u="ƈlass";String m="Іt'ѕ Dоnе.";String o="¨";String g="ƊƝƤƬƲȤɓ";
if (""")
print(((1 ^ (29 * -54) + 23 & 103) / 3))
print(">")
print(302 - 67 + (2 % 590) | 930 - 123 * (-169))
print(""") {
System.out.printf("73----T---|---111-T T46%c | / | 1%c 39- 1 %c | 0%c/ %c 1 | 1 1%c| -6 / 1 |%cL115---- | 0 /%c %c 8 L76%c 3 6%c 2-J",10,10,92,10,92,10,10,10,92,10,10,10);
} else if (""")
print((65 % (59 - 20 * 24)) / -193 * 134)
print(">")
print((624 & 13 + 3012) / 23 * 9)
print(""") {
System.out.printf("%cm=%cIt's Done%c;print %c$m%c;", 36, 34, 34, 34, 34);
} else if (""")
print(12345 * 4 / 910 - 2 * 401)
print(">")
print((1 + 3 / 3) % (24 - 36 * 90))
print(""") {
System.out.printf("Flexibility speaks for yard%cairport announces all lies%cring a ring a rosie%ccaesars sat bad%csay %cIt's Done.%c%cAmerica is great",10,10,10,10,34,34,10,10);
} else if (""")
print((393 / 91 * 56) - 12 * 78 + 192)
print(">")
print(67 | -123 + 21 * 34 - 193)
print(""") {
System.out.printf("You are done%cSay %cIt's Done.%c(It really is that simple!!)",10,34,34);
} else if (""")
print(154 % 91 * 10 + 345 - 2)
print(">")
print(89 + -920 | 65 * 2 ^ 12)
print(""") {
System.out.printf("4@abƤḞ⁹%dỴ !Ṙȯ/ṣƥA^?rCs>Y|°ỵ4$m(0a+4r /ZÐæ⁽e)D1ṖÐ,Ḅ Ḃ &ẉ1ɗḌ¢ġʋḞṬŒ$c “¢¤ƲgṖḳ®[⁾»",29,10,90,3,102,11,1234,95,666);
} else if (""")
print(10203 / 192 + 182)
print(">")
print(12 - 45 * 69 | 3)
print(""") {
System.out.println("YoucAnTryTofIguReoUtwHatThislaNgUagEiSButyOUwoNtBeaBleTobEcaUseiamToOpoWeRFulmWahAHaHaAnDhEreIssOmefilLeRteXtCOmmeNTcOmmeNtCommenTpRInTLpAreNcAPeitSiNGLeQsCaPeDonEdoTrpArencoMmEntCoMMentCoMMeNTfOOBaRyAbBaDabbadAbBAdOOcAnyOuFIndoUtTHEsEcREtBUrIEdINtHIsMEaNInGLeSStEXtNOYoUcaNTbEcaUseIhaVetHepOweRofNopUncTUatIoNandilItERaCYoNmySiDEbyeByePPl");
} else {
System.out.printf("%s"+e+"ẊD.%1$s",o);
}
}
}""")
def main(Main:Main):
Main=Main
@main
def mian():
Main=main(Main())
```
layer 1, [Scala (with Dotty)](https://scastie.scala-lang.org/5t041CQnQPqHb502g75zkw), Outputted
```
class Main {public static void main(String[] args) {String a="ɗefine";char c=10;String z="pɼint";char d=23;String y="⁸fẇ×ịṛs⁷";String e="";char x=90;String b="⁺°`¬²ịĿ°£Oḋ®ẋṄ¢¦";String w="⁸Ḷ⁸Ŀ~ʋ^ḋ*Ẓ>{S";String i="return";String n=" ";String f="Game";String s="main";String t="def";String k="#";String u="ƈlass";String m="Іt'ѕ Dоnе.";String o="¨";String g="ƊƝƤƬƲȤɓ";
if (32>21757) {
System.out.printf("73----T---|---111-T T46%c | / | 1%c 39- 1 %c | 0%c/ %c 1 | 1 1%c| -6 / 1 |%cL115---- | 0 /%c %c 8 L76%c 3 6%c 2-J",10,10,92,10,92,10,10,10,92,10,10,10);
} else if (0>225) {
System.out.printf("%cm=%cIt's Done%c;print %c$m%c;", 36, 34, 34, 34, 34);
} else if (-748>2) {
System.out.printf("Flexibility speaks for yard%cairport announces all lies%cring a ring a rosie%ccaesars sat bad%csay %cIt's Done.%c%cAmerica is great",10,10,10,10,34,34,10,10);
} else if (-520>463) {
System.out.printf("You are done%cSay %cIt's Done.%c(It really is that simple!!)",10,34,34);
} else if (973>-817) {
System.out.printf("4@abƤḞ⁹%dỴ !Ṙȯ/ṣƥA^?rCs>Y|°ỵ4$m(0a+4r /ZÐæ⁽e)D1ṖÐ,Ḅ Ḃ &ẉ1ɗḌ¢ġʋḞṬŒ$c “¢¤ƲgṖḳ®[⁾»",29,10,90,3,102,11,1234,95,666);
} else if (235>-3093) {
System.out.println("YoucAnTryTofIguReoUtwHatThislaNgUagEiSButyOUwoNtBeaBleTobEcaUseiamToOpoWeRFulmWahAHaHaAnDhEreIssOmefilLeRteXtCOmmeNTcOmmeNtCommenTpRInTLpAreNcAPeitSiNGLeQsCaPeDonEdoTrpArencoMmEntCoMMentCoMMeNTfOOBaRyAbBaDabbadAbBAdOOcAnyOuFIndoUtTHEsEcREtBUrIEdINtHIsMEaNInGLeSStEXtNOYoUcaNTbEcaUseIhaVetHepOweRofNopUncTUatIoNandilItERaCYoNmySiDEbyeByePPl");
} else {
System.out.printf("%s"+e+"ẊD.%1$s",o);
}
}
}
```
Layer 2, [Groovy](https://tio.run/##fVTtT9tGGP/ev@J6IyuMBOIkBCLkbAkxxRM4LHHWsmrVLpdLsGr7It@l1INOY6r2Uvah6rQxaS/SWlbtA@oQW9cAWysZFpV@Yn@C@UfY5QXDxIp1d889z@95v/PVHEpvukdH2ESMgRlk2GCx3iibBgaMIy7ITWpUgCWA/iJ3DLt27X2AnBobAItdHiAZ7q@SqmETOI7nkQOwLEXHe@CHMqzv/2nYvIdV5Fj8GHNleLjcrPrbn@2u@jsr/tZ37HD5KTyGiQx7RrfkVOCw3Dba9jY@8Na9TWG199zb8B7m/eaK99jfFk7ueA@8R4GThU4Mv/mHWPeef/Ry5brQfMPfvp9eLAZKhgwdwhuOHUhsGYKAqcrwMrJIwDMZtvsR8FyGFVIN2BsyfC1gGjJsfd7ubSCxZHjwKb/0z9cgd/DMPngyFCBUht4vAVcTlndbP7TWWuutzRdr@1/B8QtAfEYV9Mdj6Zg0OjIqDqEjA6DoMk6sIdrgQ3Vhzqv9cDQeEZ8u5pKYkiRFdKGoJ5Ih3LVZ6qzDwV4SQDwVEZsu3tVrI9EQHu4KelBXv2vTcRNJghNvbWAphKclaaSdwkmsqFA4jt7zP9bZTo8mT@QgDsBpFsQib8OwFG2PVOxkPS3pjIFuh24DYjLSaVQ0HYuNnNulELbkEFb5JQZy1CYhPN5BRHJ9lmBgGMSTYiZOz7NxIqOJsXTs3ECTJrlllA3T4C5gdYJuMFClDnCRUwlhZDh16nCAbJs2bEwYQKYJTIOwEO7@ZOCYUGaILDEiDDkMMMRBGQkPDLngVB1DIRzCGYs4BkbAYKDmEMThSdfEELWI8YrGRUZi0XQiGT8p6X@LmqMN8RoQUOm0rngmh36VAxHZNN12EnxeZMsMq26SixcHYJDE2fCp0Xg6Miadf8ETb6Fya81v/ni4vBWq@Du/g4v@1rcvfh32tx62fs5cf9OZYOm5JW/D33mS6LP6o2gw4Ygb@N7uvd1Hh8t/kYGc5G99s3sv7DfvAL/5CXjd3/5C2l/1m196D/Z@erkifPtb63/f78Pg8OPvxcOy1tqsCRO/@Zv3@Nrh8jNvB4Zjqc41FLUIKi6jFJZioqzUSDiZTJ4tLRYfSUfi0VT81bWZdqezOGPrjqvTqlprFAgt8YUpxPV5g5lIq5VQTTGK2QZ386UFqvEsQVmT6LSsYFRixECWTvN1eoUUJhumdQXNZ6bQFMrYuXnFISpjeUs82eY0KXBylU/kLYtoOu4QPkEFsfV6QbX16XrGIRrOzBKDFw3t8jR5h02gWSLOV6lQ3WnDNqYzlmILu5kZ0iOaXs3ns6jgZspZlENlcUfFLlPJ50VVbr4xqdoVUZE@pTAFFxSeLTmqUlE1PqWyGQVpqi1CFYtcucq1/BwtYaTpvdLUefQu4VOknl8gBVrVaL1kY72EuEo1ZFcMU@VKAU3MUc1yi0ZOKbsk65LZWRP@9zDOexQYHCSD0N@@mxsKSX0Mhumx7YX2vH109C8), Outputted
```
4@abƤḞ⁹29Ỵ !Ṙȯ/ṣƥA^?rCs>Y|°ỵ4Іt'ѕ Dоnе.(0a+4r /ZÐæ⁽e)D1ṖÐ,Ḅ Ḃ &ẉ1ɗḌ¢ġʋḞṬŒ
“¢¤ƲgṖḳ®[⁾»
```
Layer 3, [Jelly](https://tio.run/##AZkAZv9qZWxsef//NEBhYsak4bie4oG5Mjnhu7QgIeG5mMivL@G5o8alQV4/ckNzPll8wrDhu7U00IZ0J9GVIETQvm7QtS4oMGErNHIgIC9aw5DDpuKBvWUpRDHhuZbDkCzhuIQg4biCICbhuokxyZfhuIzCosShyovhuJ7huazFkgog4oCcwqLCpMayZ@G5luG4s8KuW@KBvsK7//8), Outputted (for real this time)
```
Іt'ѕ Dоnе.
```
[Answer]
# [Kevin Cruijssen's answer](https://codegolf.stackexchange.com/a/212098/48931), 2 layers
```
,322,241,245,241,245,313,245,241,241,315,245,241,245,241,315,245,245,245,245,245,245,315,315,245,245,241,241,315,313,245,313,245,245,315,241,241,241,241,241,315,245,245,315,245,241,245,315,322,241,245,245,245,245,245,241,315
```
Layer 1: [μ6](https://esolangs.org/wiki/Mu6), outputted
```
zaeaeueaaweaeaweeeeeewweeaawueueewaaaaaweeweaewzaeeeeeaw
```
Layer 2: [evil](https://tio.run/#evil), outputted
```
Greetings!
```
[Answer]
# [Dion's Answer](https://codegolf.stackexchange.com/a/212100/48931), 4 layers
Layer 1: [MAWP 2.0](https://8dion8.github.io/MAWP/v2.0/), outputted
```
print('112;114;105;110;116;39;84;104;101;32;76;97;115;116;32;49;39;')
```
Layer 2: [Python 3](https://tio.run/#python3), outputted
```
112;114;105;110;116;39;84;104;101;32;76;97;115;116;32;49;39;
```
Layer 3: [MAWP 2.0](https://8dion8.github.io/MAWP/v2.0/), outputted
```
print'The Last 1'
```
Layer 4: [Python 2](https://tio.run/#python2), outputted
```
The Last 1
```
---
You need to set the 'Max executions' to a high number on the online interpreter for the first one.
[Answer]
# [Aiden4's answer](https://codegolf.stackexchange.com/a/213964/91569), 3 layers
```
"D'`;#]8JIY4jEhw5uRQ+rpLo98*Z('D2CAdbx>+<)yxZpunsl2SRngfe+Lhg`_^$EaZ_^]V[TxXQ9UNrLQJOHMLEiCBAF?>=a;@?8=<54X876/4-Q10/o-&Jkj"75*1-"F&%edAbaw|{tyr8vuWVlkj0Qgfejib(`H^]#a`YA]\[TxXWP8TSLQJnHlkE-CHAeED&B;_?>=}|4Xy1U543s+O/o-&Jk)"75*1-"!&}C{c!x>|{zyxqY6Wsrqpi/mleMiha'HG]#a`_^W?[ZYRvPUTMqQJ2NMLKDhBG@?>b%;:?876;:3W10543,P0/on&J*)('&%${z@~w|uts9Zvutmlk1oQPfkd*bg`_%cbaCYX|\U=YXWPtT6RKoOHMFEi,HGF?DC<A:^>~6;4381Uv4-2+*Non&+*#Gh~}|{"75*1-"y?wvuzyr8vXWsl2ponmfN+Lbgfe^c\"75*1-"`Y^WVUySRWVOTMqQPONM/EiCHG@EDCB;_?>=}|49870/.R,1*N.n&%$Hi!EDC#zb~}|uts9Zpo5Vlkj0Qgfejib(`edc\"75*1-"`B^]VUTxXWP8Nr54PImML.DhHA@EDCB;_?>~<5Y9270Tu-,+Op.-&+$)"75*1-"Fg%|B"75*1-"!~wv<)"rooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo;
```
Layer 1: [><>](https://tio.run/##7ZHrmqlgHEevxSmjhCgiJBWNSWQkGUIOU04Z5Ni4dfPac9jPvoD9bf5f63nXs35ram3N283LBQeUr0dWHjV8xpsHwmnIyGYt2mkS7jwEuTjLjI1jHsmGTsfO2lltF/Hnxup1OkFE83XQ1/38sNPXe62X5rEtpxVpI8qVmlAVeYstMiU6nxtSBZrMZQm8TaaSURyVsVjURqHKfOZNETCGektQYDJmjOHBvexOG3LvqK3FfBaTAWNmGQ8DQe/5hgON6XXvDLVONp8BYyUs5jzKCsyE56Ai1QekdxdvnzCFwBNbpPbJCH0xPNA7exl5jnn3cj4d37Skut28ra3ocjGpWuYwKJTvjL6u0i8drbGvK83qm1yJS1XxiTOL5QKdNwJUhgYGVCahYjHACNeBxwqqwKGHIBTwX86F68F1dtt0Z@/slos5Zsv16XwMG2ClwMgYslrb7So5DRjsmsnGkw1WKvFWWCiXaI7NMhk9f01SeILElD2OxhFYAq8jsK9sXt/dy5fHiT7snfN9pbYKSqzt1XIqIaIBttJH3a@fBpqutpTTc0Nt1e4e9ZpUjYIeQrnAc@zPVmkyFYtGGmEMliIrYCBYHvDZdzYA74/H2ib@LTEZ/2UUQXPls4e0IfD647IqRjhTYH4Y1yyhpeOpWNNBw0htHUEhxP/do/QacIvfba6HfTbk3di/93v/66jb7QM "><> – Try It Online")
```
D'`;#]8JIY4jEhw5uRQ+rpLo98*Z('D2CAdbx>+<)yxZpunsl2SRngfe+Lhg`_^$EaZ_^]V[TxXQ9UNrLQJOHMLEiCBAF?>=a;@?8=<54X876/4-Q10/o-&Jkj"F&%edAbaw|{tyr8vuWVlkj0Qgfejib(`H^]#a`YA]\[TxXWP8TSLQJnHlkE-CHAeED&B;_?>=}|4Xy1U543s+O/o-&Jk)"!&}C{c!x>|{zyxqY6Wsrqpi/mleMiha'HG]#a`_^W?[ZYRvPUTMqQJ2NMLKDhBG@?>b%;:?876;:3W10543,P0/on&J*)('&%${z@~w|uts9Zvutmlk1oQPfkd*bg`_%cbaCYX|\U=YXWPtT6RKoOHMFEi,HGF?DC<A:^>~6;4381Uv4-2+*Non&+*#Gh~}|{"y?wvuzyr8vXWsl2ponmfN+Lbgfe^c\"`Y^WVUySRWVOTMqQPONM/EiCHG@EDCB;_?>=}|49870/.R,1*N.n&%$Hi!EDC#zb~}|uts9Zpo5Vlkj0Qgfejib(`edc\"`B^]VUTxXWP8Nr54PImML.DhHA@EDCB;_?>~<5Y9270Tu-,+Op.-&+$)"Fg%|B"!~wv<)
```
Layer 2: [Malbolge](https://tio.run/##VZHXcqpgFEafxYYFu6BYEQElBhBURExEQbGi2MCGvrr5PZnJzLneM@tbs/ZGM3XLnBuvFxUcF31DrPmhICt6cUbttggfdqyVxyKDUJBKk8RUv1TgUvh6Gezs7dFMd9rb@cyA2cV8PFL9tDYYqcPeV/fSF/MSf2DFZovhWHpJ1og6XilrxSqOlUso0sdy2QQSE1PJhBWDmuuVtw4FjCmha2f3froeMMeWe@Z6lRQBfbXUQ2NGHfq0sUIMv990WcC6HUDfMuaajpEMYdAUVCuOwMbDRfrXlIQimSPc@qWHvR7oQd4nnkvFvd@ul72SlY@H/W6Z2JgGt1xoQabxpo9UGf8aKG1HkLrcXmymeY79pBa1RhWv6IFiAQfWxUJGTiUBPSoA9y3UjIRDQSjgv9@qz7Nrn475gWOfNuY6ZYnCbD2N6KBMYKJrpNJ3v6WyAtxP3Wz70wJl6vQyyjTqOEWWiIJaeWaLSAZLSQ4SS8MRHtDhiK@xeD7cu/eKnx379i7Tl0H3nbXdzHiY1UEfdfLtHSuq3JOunbbca73dhRbPJUB3plGlKfKvTB7LJRPxdjQV4eNbYM0sPeDsu@lg45/7zkL/725M3/Qa@Kr0250/oIjwseHYOLVgiD/6s4Qq@XQu2bVjUbi1i8cg2B/21ucBt@b1PM9OKfx6/QA "Malbolge – Try It Online")
```
macro_rules!f{($t:tt$i:ident$m:ident)=>{fn$i$t{$m!["The Last 1"]}}}f!{()main print}
```
Layer 3: [Rust](https://tio.run/##JcWxCoAgEADQX1G5QcdWob6gsS0ipJQOOgs9J/HbbegtL5XMvZM70rOncvssQ9XAlhnQ4ukjA/2bcaohAgJXILmq5fJidpnFoLbWWpBVG3IYxZswcuv9Aw "Rust – Try It Online")
```
The Last 1
```
[Answer]
# [JosiahRyanW's Answer](https://codegolf.stackexchange.com/a/212129/48931), 4 layers
```
"/-G^A_:;aT$e}qz\"7\"y^&'7T|-q3ZO@,]GN6==3g4U^Y)S_L7:fVp6_4'!s,a8IUK1[ Sp.)Ae)/P%ZY&D*K>j6feVfN1Fky,Vl2Z'?ie%\"<f,nv\\VS&T^e]5ZP}j!6/AivE` 0>9x<DdQL# kdzrz~sSO\"7[&U"{32-}%95base
3base{'
'1/=}%
```
Layer 1: [Golfscript](https://tio.run/#golfscript), outputs:
```
```
Layer 2, [Whitespace](https://tio.run/#whitespace), outputs:
```
print" ".join("o"*int(c)for c in str(int("hevvbe0ammyi19tg9ubck4j315jnmd5y0ppsvgebn",36)))
```
Layer 3, [Python 2](https://tio.run/#python2), outputs:
```
ooo o o o oooooo o ooo o ooooo ooo ooo o oooooo oo oooo ooo oo ooo oo ooooo o oooo o oo oooooo oooooooo oooo oo ooooooo oooooo ooooo ooo o ooooooo ooooo o ooo ooo ooooooo ooo o ooooooo oooooo oo ooooooo oooooo o ooooooo ooooo oo ooooooo oooo ooo ooooooo ooooo o ooo o ooooooo ooooo ooo ooo oooo ooooooo
```
Layer 4, [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/), outputs:
```
Code Golf.
```
[Answer]
# [Quintec's Answer](https://codegolf.stackexchange.com/a/212166/48931), 2 Layers
```
//"/pr/in/t('C/o/de /G/o/lf./')"#ec/ho/'C/o/d/e/ G/o/l/f/.'#con/sole/.l/og/('C/o/d/e/ G/o/l/f/.')#g))#:jd@#$%6a
```
Layer 1, [Laser](https://github.com/Quintec/LaserLang), outputs:
```
print('Code Golf.')
```
Layer 2, [Python 3](https://tio.run/#python3), outputs:
```
Code Golf.
```
[Answer]
# [PkmnQ's Answer](https://codegolf.stackexchange.com/a/212178/48931), 2 layers
```
printf("Code %s." % "Golf") # Python doesn't use printf?? (Of course I know what Python uses. (print))
# ^ The letter i. Superb letter. Seriously, it's one of the only two letters that can be a word by itself.
```
Layer 1: [Underload](https://tio.run/#underload), outputs:
```
print("Code %s." % "Golf")
```
Layer 2: [Python 3](https://tio.run/#python3), outputs:
```
Code Golf.
```
] |
[Question]
[
**This is Hole-1 from [*The Autumn Tournament* of APL CodeGolf](https://apl.codegolf.co.uk/problems#1). I am the original author of the problem there, and thus allowed to re-post it here.**
---
Given a list of numbers, produce a horizontal bar chart of `#` characters for how many numbers fit into each of ten equal-sized groups. For example, if the data ranges from 0-100, the ranges will be 0–9.9, 10–19.9, …, 90–100. (Formally, [0,10), [10,20), …, [90,100].). You may assume that there will be at least two numbers and that not all numbers will be the same.
### Examples:
`[1,0,0,0,0,0,0,0,0,0]` gives:
```
#########
#
```
`[0,1,2,3,4,5,6,7,8,9]` gives:
```
#
#
#
#
#
#
#
#
#
#
```
`[0,1,2,3,4,5,6,7,8,9,10]` gives:
```
#
#
#
#
#
#
#
#
#
##
```
`[0,1,2,3,4,5,6,7,8,9,10,11]` gives:
```
##
#
#
#
#
#
#
#
#
##
```
`[0,-0.5,-1,-1.5,-2,-2.5,-3,-3.5,-4,-4.5,0.5,0,-0.5,-1,-1.5,-2,-2.5,-3,-3.5,-4,1,0.5,0,-0.5,-1,-1.5,-2,-2.5,-3,-3.5,1.5,1,0.5,0,-0.5,-1,-1.5,-2,-2.5,-3,2,1.5,1,0.5,0,-0.5,-1,-1.5,-2,-2.5,2.5,2,1.5,1,0.5,0,-0.5,-1,-1.5,-2,3,2.5,2,1.5,1,0.5,0,-0.5,-1,-1.5,3.5,3,2.5,2,1.5,1,0.5,0,-0.5,-1,4,3.5,3,2.5,2,1.5,1,0.5,0,-0.5,4.5,4,3.5,3,2.5,2,1.5,1,0.5,0]` gives:
```
###
#######
###########
###############
#########
###################
###############
###########
#######
###
```
`[9014,9082,9077,9068,8866,8710,9049,8364,8867,9015,9064,9023,9024,8804,8805,8800,8744,8743,8714,9076,8593,8595,9075,9675,8968,8970,8711,8728,8834,8835,8745,8746,8869,8868,9073,9074,9042,9035,9033,9021,8854,9055,9017,9045,9038,9067,9066,8801,8802,9496,9488,9484,9492,9532,9472,9500,9508,9524,9516,9474,8739,9079,8900,8592,8594,9053,9109,9054,9059]` gives:
```
#
####
#########
############
######
#########################
###########
#
```
`[0,8,10,13,32,12,6,7,27,9,37,39,95,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,1,2,175,46,48,49,50,51,52,53,54,55,56,57,3,165,36,163,162,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,4,5,253,183,127,193,194,195,199,200,202,203,204,205,206,207,208,210,211,212,213,217,218,219,221,254,227,236,240,242,245,123,125,168,192,196,197,198,201,209,214,216,220,223,224,225,226,228,229,230,231,232,233,234,235,237,238,239,241,91,47,92,60,61,62,45,43,247,215,63,126,42,40,124,59,44,33,243,244,246,248,34,35,30,38,180,64,249,250,251,94,252,96,182,58,191,161,41,93,31,160,167]` gives:
```
#############
######################
##########################
#########################
#########################
#
########
################
########################
##########################
```
[Answer]
# [Python 2](https://docs.python.org/2/), 96 bytes
```
l=input()
m=min(l)
w=max(l)-m
for i in range(10):print"#"*sum(w*i<=(x-m)*10<w*-~i+i/9for x in l)
```
[Try it online!](https://tio.run/##JY/NboQwDITv@xRoewEW1IT82dXyJFUPe@hPJJJFlBX00lennvTyKbE94/H8s37d83Ac0xjz/Fjr5pTGFHM9NadtTLddHn06fdyXKlYxV8stf77XWjUv8xLzen46t9@PVG9tvI713qem1eq6tf1vvMRnhmyHbGqO45WVth0rGgQhCDx1RN53FLSSr@WOjLeooasdRqAYDICGKnCAEpm1gIEB5oJYOTYAtEHgBcRYxAEKrQUD9hpYGQeDAo@9DBC0WBlgahHXwM@UGGJADg2HmkZSW7qQleC4iBTmlGgtewERYPGVmjNoBLzkDoF0nRzITmM44CzDSCCBGKc6kQnKXomhFbr/MfjtDw "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~107~~ 95 bytes
```
l=input();m=min(l);s=(max(l)-m)/10.;c=0
exec'print"#"*sum(m<=v-c*s<m+s+c/9for v in l);c+=1;'*10
```
[Try it online!](https://tio.run/##jZPNThtBEITvPIXlHDDQhumen52N8VvkhjhEjiMsYYP4C3l68tVyixSIvO7dnamp7qruvf/9dHN3iLfN3Y/tej6fv92ud4f756fFyWq/3u8Oi9uT1eN6sf/@ytNyf3Lh6Xy1Waej7et2c3z/sDs8zb/MTx@f94v95fpluTl9vNyfPZ5tLsafdw@zl9nuMINic7b21fGppzdyHP262d1uZ98enrdfj2YzMc2Un@eJ8Hg5Ia/c0t@/66OrZG5h2YpVazZYt3FaXabzakvn0j24dM9cuhcu7sJ8DvX/wWntM2B8jpr@H8LyZxhV8xGofIyQL/@EYO2YvNiYehCGgdC69d6a9cETr2W0nlvRmna9CqITkRW0kaZQFRLHSlHIIhBugKqOWUFnB0Ij9FGJxkEn3AmhvFlUuYpgCk15R4Wus0o5iLSo3Cy@PJUBQa/aqFpzVVqmXR2bCpeinoRLnC1jI/SuUPTKWs3aGPSEDgK7FYFjdYEHycqjKqCgUVIrxwhTXsrwpN33Mt6nthseejaYPaZ5DmqxPJiIKJA3sozAwFGdU5ynzJ85xVJPjf/AX1TgxIddDp1D7Fjs9MQp0ZHtDs7BBThc8Yjpg3Icx8zSjX7WZNWthlE01WJZbVapybwxJjA1PVIw32Az7MN9ukCvBjcMog@4ASW9ZWaGbrIEudiLI/Qar@ifhgjDcQtLpk86SOkAHB@coXDMc4xwPAg8CPQH@gP9gf5Af6A/0B9oD7QH2gPtgd5wrXMWrYGWgDdQEAUsQxJMgYfycUeF0zGn9z4qP2fxPPA18DHwMPAtwEeIi/yhNXABJrOXwdPNYOyCYQ1mMLJygqGnUZw5sEJfsS9Zc8NHiuB7iKJ6sVTl0AvW1SRsGY1vRowTCtYiBd1IAD9pYXf8bdoiCQ0MOoh3QRclB9ur1NFxUqoIhk4vZGjD9R8 "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~77~~ 81 bytes
*+4 bytes to fix some test cases*
```
for(i in hist(x<-scan(),seq(min(x),max(x),,11),r=F)$c)cat(rep('#',i),'\n',sep='')
```
[Try it online!](https://tio.run/##HcvLCoMwEEbhVxEszAz8glN7E@q2T9FNCCmdhakmLvL2ae3qwAcn1fr6JLbGYvO2vHG5d9m7yDksE4EEOaw8W@QimF3ZA1VBmh5y8OLdxiksTC3BBPSMhP9KUnsojhhwwhkXXHHDCP2h1i8 "R – Try It Online")
Link is to a version of the code that takes comma-separated input; this version takes space-separated.
Reads from stdin, prints to stdout.
R is a statistical programming language that does its best to give high-quality results, which is sometimes frustrating:
`hist` bins the inputs into a histogram with `breaks` as its second argument. Normally, one would expect that you could specify that the number of breaks to be 10. Indeed, this is the case:
>
> `breaks`
>
>
> one of:
>
>
> * a vector giving the breakpoints between histogram cells,
> * a function to compute the vector of breakpoints,
> * **a single number giving the number of cells for the histogram,**
> * a character string naming an algorithm to compute the number of cells (see ‘Details’),
> * a function to compute the number of cells.
>
>
>
(emphasis added).
The next sentence, however, says:
>
> In the last three cases the number is a suggestion only; as the breakpoints will be set to [`pretty`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/pretty.html) values, the number is limited to `1e6` (with a warning if it was larger).
>
>
>
So I looked at the documentation of `pretty` and it just doesn't work for our situation, because it picks break points thusly:
>
> Compute a sequence of about `n+1` equally spaced ‘round’ values which cover the range of the values in `x`. The values are chosen so that they are 1, 2 or 5 times a power of 10.
>
>
>
Which simply won't do.
So the `seq(min(x),max(x),,11)` specifies 11 equally-spaced points as the `breaks`, `hist(x,breaks,r=F)$c` gives the counts, `r=F` ensures that the bins are right-open intervals, and the `for` loop takes care of the rest.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 241 bytes
```
#define P(x)for(;x--;putchar('#'));puts("");
double a[999],u,l,x;i,j,n[9];main(k){for(;scanf("%lf",&x)>0;u=u>x?u:x,l=l<x?l:x,a[i++]=x);for(;j<i;++j)for(k=0;k<9;)if(a[j]<l+(++k)*(u-l)/10){n[k-1]++;break;}for(k=0;k<9;++k){i-=n[k];P(n[k])}P(i)}
```
[Try it online!](https://tio.run/##jdBBb4MgFAfw@z6FsdnKG7Bp2x3c0/YreDceqNUNYXaxIyExfnYHnnaZNnnkD@T3yAsV/6iqadpc6kZ2dZATC821J2g5x2/zU32Knmw3WwB/upEwBHy4XM1Z14EokiQpmWGaWZSsZV2RlPglZEcUDPMrt0p0DQkfdROyJwvHCE1mjvZk3i3TmU7tSbudKCSlZWYB56Y2lUhpO8@hsghVmiDIhoiiLVNNCaUKnonhGl7jCIauUDwuKcVzXwuF4982TwfJM2dKzIkPGHMiYZymKODRy1vAY1c@d6587l35PLhy6c06je9x/m4N7tbVvBbZfs34aZbQYVn4f/mX/AI "C (gcc) – Try It Online")
[Answer]
# Mathematica, 152 bytes
```
(Do[Print[""<>Table["#",Length@Select[s=#,Min@s+(t=#2-#&@@MinMax@s/10)(i-1)<=#<Min@s+t*i&]]],{i,9}];Print[""<>Table["#",Length@Select[s,Max@s-t<=#&]]])&
```
[Try it online!](https://tio.run/##jdBBC4IwGAbgvyIORGsrp3aINHbomBDUbeywZOZADXKHQPzta7NzLnjHy8azj7GOq0Z0XMmK69orPB2envTykr2ivp8fb/zeCuoDH55F/1ANuYpWVIoOBYCl7MmwDlUBEgQCQsy@5G8ybHEchRLhKC9A/kVqJQPGGBwl3E/s8Md8OI9CysywN6NA13SMIYo3O4iwie3ExHZqYjszMW2Nm@J/nD1zwcSt5rXIUpexr1lC2bKw//KTTEx/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# JavaScript (ES6), 99 bytes
*Edit* 2 bytes save thx @JustinMariner
A function returning an array of strings
```
l=>l.map(v=>o[i=(v-n)/(Math.max(...l)-n)*10|0,i>9?9:i]+='#',o=Array(10).fill``,n=Math.min(...l))&&o
```
*Less golfed*
```
list => {
var max = Math.max(...list),
min = Math.min(...list),
output = Array(10).fill(''),
index;
list.forEach( value => (
index = (value - min) / (max - min) * 10 | 0,
output [index > 9 ? 9 : index] += '#'
) )
return output
}
```
**Test**
```
var F=
l=>l.map(v=>o[i=(v-n)/(Math.max(...l)-n)*10|0,i>9?9:i]+='#',o=Array(10).fill``,n=Math.min(...l))&&o
var test=[
[1,0,0,0,0,0,0,0,0,0],
[0,1,2,3,4,5,6,7,8,9],
[0,-0.5,-1,-1.5,-2,-2.5,-3,-3.5,-4,-4.5,0.5,0,-0.5,-1,-1.5,-2,-2.5,-3,-3.5,-4,1,0.5,0,-0.5,-1,-1.5,-2,-2.5,-3,-3.5,1.5,1,0.5,0,-0.5,-1,-1.5,-2,-2.5,-3,2,1.5,1,0.5,0,-0.5,-1,-1.5,-2,-2.5,2.5,2,1.5,1,0.5,0,-0.5,-1,-1.5,-2,3,2.5,2,1.5,1,0.5,0,-0.5,-1,-1.5,3.5,3,2.5,2,1.5,1,0.5,0,-0.5,-1,4,3.5,3,2.5,2,1.5,1,0.5,0,-0.5,4.5,4,3.5,3,2.5,2,1.5,1,0.5,0],
[0,8,10,13,32,12,6,7,27,9,37,39,95,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,1,2,175,46,48,49,50,51,52,53,54,55,56,57,3,165,36,163,162,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,4,5,253,183,127,193,194,195,199,200,202,203,204,205,206,207,208,210,211,212,213,217,218,219,221,254,227,236,240,242,245,123,125,168,192,196,197,198,201,209,214,216,220,223,224,225,226,228,229,230,231,232,233,234,235,237,238,239,241,91,47,92,60,61,62,45,43,247,215,63,126,42,40,124,59,44,33,243,244,246,248,34,35,30,38,180,64,249,250,251,94,252,96,182,58,191,161,41,93,31,160,167],
[9014,9082,9077,9068,8866,8710,9049,8364,8867,9015,9064,9023,9024,8804,8805,8800,8744,8743,8714,9076,8593,8595,9075,9675,8968,8970,8711,8728,8834,8835,8745,8746,8869,8868,9073,9074,9042,9035,9033,9021,8854,9055,9017,9045,9038,9067,9066,8801,8802,9496,9488,9484,9492,9532,9472,9500,9508,9524,9516,9474,8739,9079,8900,8592,8594,9053,9109,9054,9059]];
output=x=>O.textContent+=x+'\n\n'
test.forEach(t=>output(t+'\n'+F(t).join`\n`))
```
```
<pre id=O></pre>
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~126~~ 121 bytes
```
def f(a):
m=min(a);r=range(10);A=[sum(x>=m+i*(max(a)-m)/10.for x in a)for i in r]+[0]
for i in r:print'#'*(A[i]-A[i+1])
```
[Try it online!](https://tio.run/##jZTNbhsxDITvfgoDPcRu6FSkflabwAXyHIYPBhq3PtgJ3BRInz79ZnMokLZJ4V1KK41IzpDyw8/Hb/eneH7@cref7xe75fVsflwfDyemN@f1eXf6erfwtLy5XW@@/zgunj6vj5eHj4vj7gnE6rj85Olqf3@eP80Pp/luqelB0/P2cpO2s/nvheuH8@H0ePHh4uPidnPYrjCXvl0@7xcbt/T6t13OXvCr1cUMSDK3sGzFqjUbrNv4J2SVrqqtnEdj8GjMPBoLD6Mw70P9f3Baew8Y76Om901Yfg@jbN4ClbcR0uWfkNc6j8mLjakHZhgwrVvvrVkfPPFZRuu5Fa1p16sgOhFZRhtpMlUmcawUmSwHwg24qmOW0dkB0zB9VKBx0Al3TChulqtc5WAyTXFHma6zCjnIaVG6Wf7ylAYOetVG1Zor0zLt6tiUuBj1JFzibBkbpneZok/WatbGoBk8MOxWCI7VBR5EK4/KgIRGUa0cw0xxScOTdl/S@Es/d0NQz0YYj6ntg8QsDyavZMsXIUdg4EjVydRT5qWD0ddT4x145Qqc/KGd485x7OjtFMjJ19HAHZyDC3BI5BHTvXPkR9nSjeLWZNWthsGA1NGvNqvkZN5oIDw1TUmYq9oMLSkFJaFwgxtqURSkwSWFpoGGbtIHumiNPBQe4SimOgr1kQ59ppsfhHQAjg5OhzhKOkI4GgQaBPwD/gH/gH/AP@Af8A@4B9wD7gH3gG@41jkL14BL4DdgEAUsHRO0hIfiMcLCKZ/TCD4qPmfRPNA10DHQMNAtwEfIF/FDa@ACTGYvg6eaQQ8GnRs0ZGTFBENNozhNYYW6Il@y5oaOJMHliKJ8kVTpUAvWVSRkGY0LJI8TCq9FDLoRAP@Exbujb9MWQShgUEG0C6ooOshexY6KE1JJ0HT6IEIb@JP@BQ "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
A monadic link returns a list of strings.
```
_Ṃµ÷Ṁ×⁵Ḟµ<⁵+ċЀ⁵R¤”#ẋ
```
[Try it online!](https://tio.run/##JY8xTgQxDEUPQ8kUyTiObYlT0CGEqGjQXoBu2YZiGzoqtqKkHcFSznCRmYuE/0PzlNj@39@PD7vdU2v36/kwT8vXet4vb9vztH6f5ukKj8vf4/K6HT7xvJ4/tv37xfpzbMvLTWu3kXIZIvkImAHVB/daB7ec8C0xuNTCGrtZOULFKAQbqUOJBFkphNCAcwYrDSGoNaACHlwURkXOwMi9QitRGnRU7g3CqeVKo2lhXKGf9BgwcGVDWctMWnqXsh6cF3niXIK2RAXcicIvaipsGF@4A0BXcWBo5rDxLAkmQKDgqQoZ0PciRk7s/seIuz8 "Jelly – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~32~~ 31 bytes
```
*R\#_M.++msmgk+JhSQ*dc-eSQJTQTZ
```
**[Try it here!](https://pyth.herokuapp.com/?code=j%2aR%5C%23_M.%2B%2Bmsmgk%2BJhSQ%2adc-eSQJTQTZ&input=%5B0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C-3%2C-3.5%2C-4%2C-4.5%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C-3%2C-3.5%2C-4%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C-3%2C-3.5%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C-3%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C3%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C3.5%2C3%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C4%2C3.5%2C3%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C4.5%2C4%2C3.5%2C3%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%5D&debug=0)** or **[Verify all the test cases.](https://pyth.herokuapp.com/?code=j%2aR%5C%23_M.%2B%2Bmsmgk%2BJhSQ%2adc-eSQJTQTZ&input=%5B0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C-3%2C-3.5%2C-4%2C-4.5%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C-3%2C-3.5%2C-4%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C-3%2C-3.5%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C-3%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C3%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C3.5%2C3%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C4%2C3.5%2C3%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C4.5%2C4%2C3.5%2C3%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%5D&test_suite=1&test_suite_input=%5B1%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%5D%0A%5B0%2C1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%5D%0A%5B0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C-3%2C-3.5%2C-4%2C-4.5%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C-3%2C-3.5%2C-4%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C-3%2C-3.5%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C-3%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C-2.5%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C-2%2C3%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C-1.5%2C3.5%2C3%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C-1%2C4%2C3.5%2C3%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%2C-0.5%2C4.5%2C4%2C3.5%2C3%2C2.5%2C2%2C1.5%2C1%2C0.5%2C0%5D%0A%5B9014%2C9082%2C9077%2C9068%2C8866%2C8710%2C9049%2C8364%2C8867%2C9015%2C9064%2C9023%2C9024%2C8804%2C8805%2C8800%2C8744%2C8743%2C8714%2C9076%2C8593%2C8595%2C9075%2C9675%2C8968%2C8970%2C8711%2C8728%2C8834%2C8835%2C8745%2C8746%2C8869%2C8868%2C9073%2C9074%2C9042%2C9035%2C9033%2C9021%2C8854%2C9055%2C9017%2C9045%2C9038%2C9067%2C9066%2C8801%2C8802%2C9496%2C9488%2C9484%2C9492%2C9532%2C9472%2C9500%2C9508%2C9524%2C9516%2C9474%2C8739%2C9079%2C8900%2C8592%2C8594%2C9053%2C9109%2C9054%2C9059%5D%0A%5B0%2C8%2C10%2C13%2C32%2C12%2C6%2C7%2C27%2C9%2C37%2C39%2C95%2C97%2C98%2C99%2C100%2C101%2C102%2C103%2C104%2C105%2C106%2C107%2C108%2C109%2C110%2C111%2C112%2C113%2C114%2C115%2C116%2C117%2C118%2C119%2C120%2C121%2C122%2C1%2C2%2C175%2C46%2C48%2C49%2C50%2C51%2C52%2C53%2C54%2C55%2C56%2C57%2C3%2C165%2C36%2C163%2C162%2C65%2C66%2C67%2C68%2C69%2C70%2C71%2C72%2C73%2C74%2C75%2C76%2C77%2C78%2C79%2C80%2C81%2C82%2C83%2C84%2C85%2C86%2C87%2C88%2C89%2C90%2C4%2C5%2C253%2C183%2C127%2C193%2C194%2C195%2C199%2C200%2C202%2C203%2C204%2C205%2C206%2C207%2C208%2C210%2C211%2C212%2C213%2C217%2C218%2C219%2C221%2C254%2C227%2C236%2C240%2C242%2C245%2C123%2C125%2C168%2C192%2C196%2C197%2C198%2C201%2C209%2C214%2C216%2C220%2C223%2C224%2C225%2C226%2C228%2C229%2C230%2C231%2C232%2C233%2C234%2C235%2C237%2C238%2C239%2C241%2C91%2C47%2C92%2C60%2C61%2C62%2C45%2C43%2C247%2C215%2C63%2C126%2C42%2C40%2C124%2C59%2C44%2C33%2C243%2C244%2C246%2C248%2C34%2C35%2C30%2C38%2C180%2C64%2C249%2C250%2C251%2C94%2C252%2C96%2C182%2C58%2C191%2C161%2C41%2C93%2C31%2C160%2C167%5D&debug=0)** (with pretty-print using `j`)
# How this works
This is a full program that takes input from STDIN. This is for the 32-byte version. I'll update it soon.
```
*R\#_M.++msmgk+hSQ*dc-eSQhSQTQTZ ~ Full program.
m T ~ Map over [0, 10) with var d.
m Q ~ Map over the input with var k.
g ~ Is higher than or equal to?
k ~ The current element of the input, k.
+hSQ*dc-eSQhSQT ~ We'll break this down into pieces:
hSQ ~ The lowest element of the input list.
+ ~ Plus:
*dc-eSQhSQT ~ We'll break this down into more pieces:
* ~ Multiplication.
d ~ The current element of [0, 10), d.
c T ~ Float division by 10 of:
-eSQhSQ ~ The difference between the maximum and minium
of the input list.
s ~ Sum. Count the number of truthy results.
+ Z ~ Append a 0.
.+ ~ Get the deltas.
_M ~ Gets -delta for each delta in the list above.
\# ~ The literal character "#".
*R ~ Vectorized multiplication. Optionally, you can
use j to join by newlines (as the link does).
~ Output implicitly.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
≔I⪪S,θEχ×#ΣEθ⁼ι⌊⟦⁹⌊×χ∕⁻λ⌊θ⁻⌈θ⌊θ
```
[Try it online!](https://tio.run/##VZLJahtREEX3@QqhbFpwA131ZrwKGSALQcDZGS@EY5wGzYPJ3yvnWYGQhqLV9c6rqntLT79Wx6fdan29fjydppft8Gl1Og/3@/V0Hr5t95fz/fk4bV@GhWZzzRe8Dou7d9/JnYflaj/YqNmPafN8Gubv55rdXzZv6YNmXw6X1fo0TJotp@204eChafZ1vdsdh9uNfvfz9Dr9fB5ALqdh/Y899Fa37HL1@2/qv2Oex8XtubteH@ajqqhoQcFlrqwiL2oKRaGpJTW@qloDgxuNgBwDEYlEZKIQvRRcr2dwlDMKm8EZnMEZnMEZnMM5nMOJKEkxK1bFpjQqmZIrBaWolJSyEjPJclKgUu4/GTgpZ@WiXJWbyqhiKq4SVKIoWZBUVKpKU0WuqbpqUI2qSTWrFtWqithRdJLT0gAMH6zxbsyPEYYHjgeOfke/o9/R7@h39Dv6He2Odke7o93R69bz3EWro8Wp6yjwCBvhIrW99@ONCmt40VDYen/u4rnjq@Oj46Hjm8O791r0956Dc5jAWYBnmx5gAkyACb0nDDv1aGqmyF6xb1Q24SNDRPjY58XSPg67IN@XhC1NMapXfKOoGruCKhpQn7ZUN/zN/YgmLNDZIN45W@xysD11dWycln0I/nT9gw65zB@vH17XfwA "Charcoal – Try It Online") Link is to verbose version of code. Input of variable-length lists seems to a little awkward in Charcoal, so I've had to wrap the list in an array containing a string. Explanation:
```
S Input string
⪪ , Split on commas
I Cast elements to integer
≔ θ Assign to variable q
Eχ Map from 0 to 9
Eθ Map over the list
⁻λ⌊θ Subtract the minimum from the current
⁻⌈θ⌊θ Subtract the minimum from the maximum
∕ Divide
×χ Multiply by 10
⌊ Floor
⌊⟦⁹ Take minimum with 9
⁼ι Compare to outer map variable
Σ Take the sum
×# Repeat # that many times
Implicitly print on separate lines
```
[Answer]
# Fortran 2003, 263 bytes
I wrote it on GNU gfortran 5.4.0, and compiled without any additional flags.
It reads from STDIN, one value at a time, and prints to STDOUT.
Here it goes:
```
program h;real,allocatable::a(:);character f*9;allocate(a(0));do;read(*,*,end=8)r;a=[a,r];enddo;9 format("(",i0,"(""#""))")
8 a=(a-minval(a))+epsilon(1.);a=ceiling(10*a/maxval(a));do i=1,10;j=count(a==i);if(j==0)print*;if(j==0)cycle;write(f,9)j;
print f;enddo;end
```
Ungolfed explanation: (I don't know if "golfed" can be applied to fortran but either way :P)
```
program h
real,allocatable::a(:) ! Create an allocatable array so we can reallocate dynamically
character f*9 ! A character array to format the output
allocate(a(0)) ! Allocate "a" empty at first
do
read(*,*,end=8)r ! Read from STDIN. If EOF, goes to 8, otherwise
a=[a,r] ! Appends to "a"
enddo
9 format("(",i0,"(""#""))") ! A format label
8 a=(a-minval(a))+epsilon(1.)! (8) Normalizes a (adds epsilon to avoid zero-indexing)
a=ceiling(10*a/maxval(a)) ! Normalizing and multiplying by the number of bins
do i=1,10 ! Looping on all the bins
j=count(a==i) ! Counting the number of occurrences
if(j==0)print* ! If none, prints empty line
if(j==0)cycle ! And skips the rest of the loop
write(f,9)j ! Otherwise writes the count(j) to the print label
print f ! And prints to STDOUT
enddo
end
```
Fun fact: I made a similar code just yesterday to test my implementation of a Weibull random number generator, so it only needed a little adaptation :)
[Answer]
# [Perl 5](https://www.perl.org/), 85 + 1 (`-a`) = 86 bytes
```
@F=sort{$a<=>$b}@F;map$r[($_-$F[0])/($F[-1]-$F[0])*10].='#',@F;$r[9].=pop@r;say for@r
```
[Try it online!](https://tio.run/##jdDBCgIhEAbgV1lI2C1y0931EJvhyVtPsCxhUBBUiu4lolfPZqJrGvzDz8h3GHRHfxExKi2D9dODmI3cksNT6f5qHPFDRfaU6IGN81UFTfn4XRecjbUsZ@USLMA1bM465ftg7sXJeuVjZAVltSgoh2A3EOwWgt1BoNHkKf/H4VsONnn1mSRrcwavSaEuLfBffpKXddPZ3kKkO1EzziI1bw "Perl 5 – Try It Online")
[Answer]
# Perl 5, 84 + 19 (-MList::Util=min,max) bytes
```
$s=-($m=min@_=@ARGV)+max@_;$a[($_-$m)*10/$s]++for@_;$a[9]+=pop@a;print"#"x$_,$/for@a
```
[Try It Online](https://tio.run/##jdC9CsIwFAXgd6l3aG1j/wdbAnFy0UXQRaR0UAg0TWgy9OmNuXW2EU44kHwk4arnNNSWHS7HGw2zhGS7OiG5C3bhgl26YFcurtH4af6Pwz0fLPxqWaus9Bn8zRqq1gXO5SeJWguakhAEFXxkHV3mHcWin1nXQn8PoSMgom2epaAfcfyS0/dg/4ipkor1rZr4aIJNMEOXQIqgt/YtleFy1JacT1ybprkaPuAbibv6Aw)
[Answer]
# Perl 5, 102 bytes
```
$l=(@n=sort{$a<=>$b}<>)[-1]-($f=$n[0]);$m=$f+$l*$_/10,say'#'x(@n-(@n=grep$_>=$m,@n))for 1..9;say'#'x@n
```
[Try it online](https://tio.run/##jdDfCoIwFAbwe58i6ICu3Nr8cxE68QV6AhEp0Ah0kylRRK/e2qLbXPCND8bvwOGMrepTraHnQSn4JNX8gGPOCzg98wJVmNU4gI6DqGiNMhg4dFvoN9DsGA2n491f@zczie30WbUjNAWHISwFQp1UK0bIPvuyUmhNPUxJ6mFmYjsysR2b2E5MTFvjpuwfZ/9cMHKrz1tkscvYbZZQsizsXX6TlxznixSTxodrShh9Aw).
Ungolfed:
```
my @n = sort { $a <=> $b } <>;
my $f = $n[0];
my $l = $n[-1] - $n[0];
for (1 .. 9) {
my $m = $f + $l * ($_ / 10);
my $c = scalar @n;
@n = grep { $_ >= $m } @n;
say('#' x ($c - scalar @n));
}
say('#' x scalar @n);
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~246~~ ~~221~~ ~~209~~ ~~207~~ ~~206~~ ~~163~~ ~~162~~ ~~161~~ 157 bytes
```
l->{String x="";double b=l[0],m=b,q,i;for(double d:l){b=d<b?d:b;m=d>m?d:m;}for(i=(m-b)/10,q=b;q<m;q+=i,x+="\n")for(double d:l)x+=d>=q&d<q+i?"#":"";return x;}
```
[Try it online!](https://tio.run/##fVJNj5swED2HX2FRqQKFUAhfdoiz0m7VU/eye0xzgJhtnWI@zW5WUX57OkOSSm3VcHiyZ@a9eQ/YZa/ZrG6Kaid@nqRq6k6THdTcQcvS/Sp7nRr/lF@GaqtlXbn38svleGvqoa76QRXdrZkbOr3uikyBSlkWW113/f9nPtdDXhbP4yU1jAZucku2Zdb35DGTFTkYk15nGorXhUsxctYbhwBPVt9XRBfVU/12n3UPPzLYwsmpnK0O5y7Zc9NMzxyS83LtbRzFc6d1ZPpSd9alIxalfci5WOZ3YpGniouVgpNKjzgkuaVmuf3J95yW52m7VGk75dLZT7n5rTLtv4SgLFa8/SiW7VTemR/MBVjoCj10FdmnxxMknVyiXsK91lIQBYGts@v1hmQ2hCeXZ3INTQTEq4o3ci0cmOeHDvPoHCBJAGLqUBrHDk3ALvNC5tAgDrGGXT/CEWTMAwRseCNECB7QwhAhQAGcS0AqYgECchOAGIAyXMQSZPg@wBz3BigVRCgwQox7GQJFLq5MUDREuwHqBaMNEKARNiKs@eg0HLtIG41jIurhnAfckMUAlCKEeIVaFGAjwRPkAIBuBAFZ5ONwgrEChg7AEMOoEdAAxr1gw/ewe7bBjvCVfr/@5/deF8qtB@028H209ecv52ZNU75bwrbTkTM5GsfTLw "Java (OpenJDK 8) – Try It Online")
[Answer]
# q/kdb+, 52 bytes
**Solution:**
```
{sum[t=/:bin[m+.1*(t:(!)10)*max[x]-m:min x;x]]#'"#"}
```
[Try it online!](https://tio.run/##HZJLTgNBDESvUoAEExCkXf2PxIkQYsMCCTh7eGZhdabnTdlVztvzx9v1@n08nT9fz5fj/eklHo/Py02U0@Pxc/46PR/vl3vO08PX6e7h9u72t2gpiqKqWmENTXlqq07Vrd21eVraGwyuBAVZKtWoTg1qUikFl3oBh1wgHAEXcAEXcAEXcIYznOFEza421JbaVi/qoW71qt7Uu/pQZybF6KoojfzJwF1jaEyNpbE1i2ZoWrNqNiE5sTQ1l@bWwm5oWatqNa2uNbSm1tLCbBGdZFoGQJBDbM7N/AQRZGAyMP6Nf@Pf@Df@jX/j33g33o134934deQ93@LVeDG6xoEbbINraDv7ceIiNllsHO7sz7dkbnI1OZoMTW6Gt1OL/s47OMNU3lV4tukKU2EqTM2eMOzULbRDjb0SX9EIkSNDNPiW8xJpjsMuuM8lEctWa0rFfwrVlg6WaIA@bVEP8h35iiYs0GyQ7MwW0w6x93THxmmZQ/Cnywc6jHm9/gE "K (oK) – Try It Online") (Note the TIO link is a 44 byte [K (oK)](https://github.com/JohnEarnest/ok) port of this solution as there is no TIO for q/kdb+).
**Examples:**
```
q){sum[t=/:bin[m+.1*(t:(!)10)*max[x]-m:min x;x]]#'"#"}1 0 0 0 0 0 0 0 0 0f
"#########"
""
""
""
""
""
""
""
""
,"#
q){sum[t=/:bin[m+.1*(t:(!)10)*max[x]-m:min x;x]]#'"#"}9014 9082 9077 9068 8866 8710 9049 8364 8867 9015 9064 9023 9024 8804 8805 8800 8744 8743 8714 9076 8593 8595 9075 9675 8968 8970 8711 8728 8834 8835 8745 8746 8869 8868 9073 9074 9042 9035 9033 9021 8854 9055 9017 9045 9038 9067 9066 8801 8802 9496 9488 9484 9492 9532 9472 9500 9508 9524 9516 9474 8739 9079 8900 8592 8594 9053 9109 9054 9059f
,"#"
"####"
"#########"
"############"
"######"
"#########################"
""
""
"###########"
,"#"
```
**Explanation:**
Most of the code is used creating the buckets that `bin` buckets the input into.
```
{sum[t=/:bin[m+.1*(t:til 10)*max[x]-m:min x;x]]#'"#"} / ungolfed solution
{ } / lambda function with implicit x as parameter
#'"#" / take (#) each-both "#", 1 2 3#'"#" => "#","##","###"
sum[ ] / sum up everything inside the brackets
bin[ ;x] / binary search each x in list (first parameter)
m:min x / store minimum of list x in variable m
max[x]- / subtract from the maximum of list x
(t:til 10)* / range 0..9 vectorised multiplication against max delta of list
.1* / multiply by 0.1 (aka divide by 10)
m+ / minimum of list vectorised addition against list
t=/: / match each-right against range 0..9 (buckets)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
_Ṃµ÷Ṁ×⁵Ḟ«9ċЀ⁵Ḷ¤”#ẋ
```
[Try it online!](https://tio.run/##JY8xUsQwDEUPQ5vCjixbOgrDMFQ0zF6AbtmGYhs6KqjooF1gKRMuklwk6JnmjS3pf33d3e5299t2s5wP02n@Ws77@Xl9OC3fr9O7/x7np/Xw0f@f09u6f7lYfo7b/Hi5bVeechk82RhoLVBtMKt1sJZTfIsPJrVQo5uVERSjABqpQ0EKWSlAMGCuhZW6ALQtUAPmLPKGIufAyF7BShSDjspeB4aWlQ3TQlzBT3qMMDClodQySUvvIuvBucgScym0xWvADBS@UVOh0XjFHYHoahzomhlunCVOggjknKohC/S9ESMnuv8x/PoP "Jelly – Try It Online")
This is based upon my APL answer for the original problem, which I will post after that competition is over.
## How? (I'm not good at explaining things)
```
_Ṃµ÷Ṁ×⁵Ḟ«9ċЀ⁵Ḷ¤”#ẋ
_Ṃ = subtract the minimum
µ = Sort of like a reverse-order compose
÷Ṁ = divide by the max
×⁵ = Multiply by 10
Ḟ = Take the floor
«9 = x => min(x,9)
ċЀ⁵Ḷ¤ = count occurrences of [0,...,9]
”#ẋ = create the list
```
] |
[Question]
[
Weather conditions at airports are reported to pilots in [METAR](https://en.wikipedia.org/wiki/METAR) (METeorological Aerodrome Report) format. This format could be described as being "golfed." Here are some examples:
```
METAR KPDX 241653Z 16003KT 1/4SM R10R/4500VP6000FT FG SCT000 01/M01 A3040 RMK AO2 SLP293 FG SCT000 T00061006 $
METAR PAMR 241753Z 00000KT 10SM OVC080 00/M02 A2985 RMK AO2 SLP111 T00001017 10022 21006 55003
METAR KLAX 241653Z VRB05KT 10SM FEW030 SCT060 17/11 A2992 RMK AO2 SLP130 T01720106
METAR KBOS 241754Z 27012G19KT 10SM FEW045 SCT250 09/M05 A3000 RMK AO2 SLP158 T00941050 10094 20044 56020
```
These are all American METARs, which is all your program needs to accept. The international format is slightly different.
You only need the wind component, which is after the third space.
```
METAR KLAX 241653Z | VRB05KT | 10SM FEW030 SCT060 17/11 A2992 RMK AO2 SLP130 T01720106
Things that don't matter | *Wind* | More things that don't matter
```
However, your program will be given the entire METAR.
Let's take the METAR from KPDX as the first example. Its wind component is `16003KT`. When the code looks like this, it's simply indicating the wind direction and speed. The first three digits, `160`, are the direction in degrees; the last two, `03`, are the speed in [knots](https://en.wikipedia.org/wiki/Knot_(unit)) (`KT`; a knot is a [nautical mile](https://en.wikipedia.org/wiki/Nautical_mile) per hour). In this case, the output should clearly indicate the direction and speed as separate values. You do not have to indicate units.
When there is no wind, it will look like the PAMR METAR: `00000KT`. This indicates zero knots; zero degrees is used as a placeholder, because there is, of course, no way to measure wind direction without wind. Just parse these the same as regular codes; your program does not have to treat this as a special case.
Sometimes, as was the case at KLAX at the time of writing, the wind direction is variable. This is encoded as `VRB05KT`. The direction is replaced with `VRB`, which your program must parse, and the speed is encoded normally.
Wind with gusts is encoded like this: `27012G19KT`. The `270` indicates the direction. The `12` indicates that the average wind speed is 12 knots, while `G19` indicates that gusts are reaching 19 knots.
I did not find a current METAR that actually had this, but your program must also handle variable winds with gusts, which would look like this: `VRB12G19KT`.
Your program must return or output three numbers. The first is the wind direction in degrees, or -1 if the wind is `VRB`. The second is the wind speed. The third is the gust speed if there are gusts, or `-1` otherwise. Leading zeros are not allowed.
Here are some test cases. They are the four real METARs from the start of the question, plus a constructed one to test for variable gusty winds.
```
METAR KPDX 241653Z 16003KT 1/4SM R10R/4500VP6000FT FG SCT000 01/M01 A3040 RMK AO2 SLP293 FG SCT000 T00061006 $
160 3 -1
METAR PAMR 241753Z 00000KT 10SM OVC080 00/M02 A2985 RMK AO2 SLP111 T00001017 10022 21006 55003
0 0 -1
METAR KLAX 241653Z VRB05KT 10SM FEW030 SCT060 17/11 A2992 RMK AO2 SLP130 T01720106
-1 5 -1
METAR KBOS 241754Z 27012G19KT 10SM FEW045 SCT250 09/M05 A3000 RMK AO2 SLP158 T00941050 10094 20044 56020
270 12 19
METAR KTVG 241754Z VRB12G19KT 10SM FEW045 SCT250 09/M05 A3000 RMK AO2 SLP158 T00941050 10094 20044 56020
-1 12 19
```
[Answer]
# Google Sheets, 80 bytes
```
={iferror(--mid(A1,20,3),-1),mid(A1,23,2),ifna(--regexextract(A1,"G(\d\d)"),-1)}
```
Put the input in cell `A1` and the formula in `B1`. Output in cells `B1:D1`.
Simple text manipulation in an [{ array expression }](https://support.google.com/docs/answer/6208276).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~17~~ ~~16~~ 15 bytes
```
…IE⪪ε³⁻Σ⁺ψι›ια³
```
[Try it online!](https://tio.run/##FcrBisIwGEXhV7nLBDr4J03U4qpTnC5qsDRBwV0oBQMZLbUKPn2su8PH6a9@6u8@ptRO4Taz6t3HobreR1b5x8yMH5kdY5jZkCHnGUy4PR/MPv9ZG5d4Zwh84Xoa/DxMLGTwnH8l53yXktm7skNTWwepxEarC07dr5C1KBoHQdbgb38mpWErJzWBipUhjTInInSmQXmUsIdW6C0cUaEELZf4FiSRUtBrkpR@XvED "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
ε Fourth word of input
⪪ ³ Split into groups of three characters
E Map over groups
ψ Null byte
⁺ Concatenated with
ι Current group
Σ Extract embedded integer
⁻ Minus
ι Current group
› Is greater than
α Predefined variable uppercase alphabet
I Cast to string
… ³ Take the first three
Implicitly print
```
In practice `-1` is only needed for `VRB` and `T` so comparing to any string between `99` and `T` would work.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 15 bytes
```
Ḳ4ịs3ḣ3f€ØDȯ€-V
```
[Try it online!](https://tio.run/##rZA7TsNAEIb7nGKKtIlnZnftWJGQnGfhWLFsy0B6KKJ0VHQRTQouQEEqWiQkRBEUiSYN17Av4swmGJIeS@sZ7eP7/t35zWJxX1XF5l0X28c7VWxe1G358Lp7Gny/SW3l9Vq5fG632yAFpJbL9bxr@9aFTK27u1Xx@dVsFNuP3UqOXVdVNMyCBMJ4cAWsyTVqBuQiqjADcnQaQUKYONog5rHM4yiD0RjSfiY9IDkREgQKNUIShRBMGdJJzL462WV/LsmAZuOoi4MosTrP6tB@Vodim@Z97AgYBcwQsN8xp2AiOuCQkDw5gczAB7SRhOoHH06Cv9vkSQ9NjR8NL1HhIZiLQJ4jPJH4fCZRNjN5LBa3Rvam6TGxngF7SDwm/5SqjaWykey@ZDf2UfDsUch0bHZfE8oush0wotZgXGSsReM0@xVJ9v8X7QE "Jelly – Try It Online")
A monadic link taking a METAR-formatted string and returning a list of integers. (Has the side effect of sometimes outputting some zeros to STDOUT which is permitted as per [this meta post](https://codegolf.meta.stackexchange.com/a/9658/53748).)
*Thanks to @JonathanAlkan for saving three bytes!*
## Explanation
```
Ḳ | Split at spaces
4ị | 4th sublist
s3 | Split into pieces of length 3
ḣ3 | First three
fۯD | Keep only digits
ȯ€- | Replace blanks with -1
V | Interpret as Jelly code
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 39 bytes
```
4=M!`\w+
3M!`.{1,3}
%(`\D
^0+\B
^$
-1
```
[Try it online!](https://tio.run/##rZDLTsMwEEX3/opBaqWiFnJnbCfNgkX6yqKNGiVRQVWFwoIFGxYIiQXit/gAfiyMWwrtHkt@yBqfcz0vj69Pzw9df5C3nbspLtrd29BY3a/feWQ/TH/Q7mbG3GO4m@jWM1fcXeat@fo0o66YN1lFy3J2R@I49nZLHAN22RBHri6oYlSR88Cm1HssGlrkVE8bPRM4KsCUWThQVSwpWwvVq1JSe1IVlph1Us8cdGVWVEGXBB3CCDqobb2ZYqxgKFgok3TsT8HMvMeBwYm@gAjJHu01of3BL1fZ32821QT@iF/Mb2GxDxaDOImUp5JUziQ2ZOZE1BIfkZN1fUjstiQJWHJOT6nOB6p4zZ5qdh@agrOmsB@H7KljaBWHEwngHPkYgqMor5tfkWb/f9E3 "Retina 0.8.2 – Try It Online") Outputs the values on separate lines but link is to test suite that joins on commas for convenience. Explanation:
```
4=M!`\w+
```
Extract the fourth word.
```
3M!`.{1,3}
```
Split it into three triplets.
```
3G`
```
Keep only three.
```
%(`
```
Apply the remainder of the script to each line independently.
```
\D
```
Delete non-digits.
```
^0+\B
```
Delete leading zeros.
```
^$
-1
```
Insert `-1` on empty lines.
[Answer]
# JavaScript, ~~54~~ 45 bytes
```
s=>[19,22,25].map(x=>~(-1-s.substr(x,x/7^1)))
```
[Try it online!](https://tio.run/##rZBha9swEIa/91fch0FsSOy7s2XHKwm4XRNKahIck42ODTxHGR6ZndnOCIztr6entNnS7xNIOoTueV7pW/4zb4um3HWDql7r42Z0bEfjjxT1mfusPjnf8511GI3/WAMatE67/9J2jXXoH9zwM9m2fby@avSPfdloq9fofL0tK92znULqTt9XnW42eaGtX2W123dvYdfUhW6F063L6rft1JXVO7X0wWyjcVFXbb3Vzrb@am0scyaS62Nyl8UpzBbvPgD7FCjvEShA9GYZkOsvE0gJU9dXiKuFnOMkg8kUlreZ1IDkJkgQe@gjpMkM4jnD8mHBkXdxyywByYQ3V8@6RZykRhcaHZphdCi2@eoWhwJGATPEHA3VJZiITjgkpFA6kBn4hFaS0HvBzx7if69ZpTeozvjJ3Xv08BQsQKDQFZ5IIn4l8UxmClkswRl5M18@J/YfgUMknlJ0SfWVobKS7JFkV@ZT8NWnkBqa7JFPKLfIVMCIvg8qQMazKFtN/4ok@/8XPQE "JavaScript (Node.js) – Try It Online")
−9 by using indices directly in the input string and [the (deprecated) `String.prototype.substr` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr).
---
* `[19,22,25].map(…)`: Produce an array of the results of calling the function inside with argument 19, 22, and 25.
* `s.substr(x,x/7^1)`: Take the substring starting at index `x`, of length 3 for `x`=19, or length 2 for the other values of `x`. This extracts the digits that make up the desired values; in the absence of a number, the substring is `VRB` from `x`=19 or `T` from `x`=25.
* `(-1-…)`: Subtract it from −1, implicitly performing numeric coercion. If the string does not express a number, it becomes `NaN`, and the subtraction produces `NaN`.
* `~…`: Bitwise NOT. This reproduces the original number, while `NaN` becomes 0 when converted to a 32-bit integer, and then the bitwise NOT of 0 is −1.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#3è3ô3£εþ®s‚à
```
[Try it online](https://tio.run/##Fco9DgFBGAbgq7yJA3i/@cGWS9YWY0J2JiQ6myhUir2Ac6gkGpWKVrHTO4SLDLqneI7drj3scx7odNPpofvr@5le/b37nM7pkrOvYtnA1SFCGRlbs8W6mYqqpXARwuAxrzY0FmEWlSVYDD0tSk0SjXcolwphsRI7QSQLI/wt@QuKNAZ2RMUv) or [verify all test cases](https://tio.run/##rZC/SgNBEId7n2KIlsL9Znb3/lThEpMUlyPH3RElnYKFlUVACChY@QCWVoKNlZW2Frneh8iLnLOJ0aR3YZdhmf2@3871/Pzi6rK9vVl0O7R6eKROd9EemubVNO9m@fL10Xwu3@ar@6fmub07bvNBnZaUFSdnJJZDZ2bEIWCymjiwVU4lowysA6aF3mNY03BEVb/WmsBBDqbUwILKPKN0IlSNC0nMTpc/QtZNRwcbXZHmpddFXge/vA5qm0z7iBUMBQulksRuF8zMaxwYHOkLiJCs0U4Tmh98Nk7/fjMte3Bb/HBwCoN1sBDEUaA8lSSyJzE@M0eilnCL7E2qTWI7I4nAMuJkl2qdp4rT7Ilmd34o2BsKu9hnTyxDu9hXJIC15EIItqJRVf@KNPv/i74B).
**Explanation:**
```
# # Split the (implicit) input-string on spaces
3è # Pop and keep the (0-based) 3rd item (aka the fourth item)
3ô # Pop and split this substring into parts of size 3
3£ # Pop and only keep the first three parts
ε # Map over this triplet of parts:
þ # Only keep the digits of the current string-part
®s‚ # Pair it with a leading -1 (push -1; swap; pair top two)
à # Pop and push the maximum of this pair, which serves two purposes:
# 1. It will convert the values in the pair to integers to determine the
# max, removing the leading 0s from the digit-strings
# 2. It will take the first item if the pair contains a non-number, hence
# the need for the swap `s` when pairing it to the empty string
# (after which the resulting triplet of integers is output implicitly)
```
[Answer]
# [sed](https://www.gnu.org/software/sed/) -E, ~~81~~ 75 bytes
*-6 bytes thanks to [@Jordan](https://codegolf.stackexchange.com/users/11261/jordan)*
```
s/.{19}(...)(..)(G(..))?.*/ \1 \2 \4/;s/ VRB| $/ -1/g;s/ 0*(\w)/ \1/g;s/ //
```
[Attempt This Online!](https://ato.pxeger.com/run?1=tZLPSsNAEMbBo08xtD20hWRnJrv5gwdJa9tDGhqSUKXGm39uXqp4UJ_ES0H0nfRpnE2sTaFXB3bZDbPz-76PvL2vb64_LzvOpHO1-Xh8uHXCr2St3GeKXvuu6w76ds3sPjh1hwoqgoqh0upkrWCZj16gp8AhdWfvOOxXTwPb1NyVakb-Tt58H92nkzLOIcnOLoA1-cZbAfmIXlICKV2kkBPmShvEZSbfcVrCdAbFuJQzIKkUCWIPNUKeJhAvGIp5xpHX6rKbT7KgB1JdCwBPRB438CxOcwsPLBxtWTgKe7EcYygYFAxDzFFo2hgiqocjIQXyApmBa5ARvR4cqC7IuB06mcc735Iemi16OjlHD2sLopYCJSwREPGeAM-6o4BFgX8It492CEyLPVoUjW29Ag6QeEZRG6-NxbMRxZEEYGzOuJczmdAGEGlC6SJ7AkbUGoyPjG22AIAYKNrSZ0X5Rxfn_0sX5zW8-e9-AA)
[Answer]
# [Uiua](https://uiua.org) 0.4.1, 80 [bytes](https://codegolf.stackexchange.com/questions/247669/i-want-8-bits-for-every-character/265917#265917)
```
⊐∵parse≡(⊂⊂∩□⊃((∘|"¯1")≍"VRB"⊔.↙3|⊃↙(□↘+1)⊗@G.(⊂:"G¯1"|∘)∊@G.↙-2⧻.↘3)⊔⊡3⊜□≠@ .⊔)
```
[See it in action](https://uiua.org/pad?src=0_4_1__eyJNRVRBUiBLUERYIDI0MTY1M1ogMTYwMDNLVCAxLzRTTSBSMTBSLzQ1MDBWUDYwMDBGVCBGRyBTQ1QwMDAgMDEvTTAxIEEzMDQwIFJNSyBBTzIgU0xQMjkzIEZHIFNDVDAwMCBUMDAwNjEwMDYiCiAiTUVUQVIgUEFNUiAyNDE3NTNaIDAwMDAwS1QgMTBTTSBPVkMwODAgMDAvTTAyIEEyOTg1IFJNSyBBTzIgU0xQMTExIFQwMDAwMTAxNyAxMDAyMiAyMTAwNiA1NTAwMyIKICJNRVRBUiBLTEFYIDI0MTY1M1ogVlJCMDVLVCAxMFNNIEZFVzAzMCBTQ1QwNjAgMTcvMTEgQTI5OTIgUk1LIEFPMiBTTFAxMzAgVDAxNzIwMTA2IgogIk1FVEFSIEtCT1MgMjQxNzU0WiAyNzAxMkcxOUtUIDEwU00gRkVXMDQ1IFNDVDI1MCAwOS9NMDUgQTMwMDAgUk1LIEFPMiBTTFAxNTggVDAwOTQxMDUwIDEwMDk0IDIwMDQ0IDU2MDIwIgogIk1FVEFSIEtHU1QgMjQxNzU0WiBWUkIxMkcxOUtUIDEwU00gRkVXMDQ1IFNDVDI1MCAwOS9NMDUgQTMwMDAgUk1LIEFPMiBTTFAxNTggVDAwOTQxMDUwIDEwMDk0IDIwMDQ0IDU2MDIwIn0K4omhKAogIOKKoTPiipzilqHiiaBAIC7iipQKICDiipQKICDiioMoCiAgICAo4oiYfCLCrzEiKeKJjSJWUkIi4oqULuKGmTMKICB8IOKKg-KGmSjilqHihpgrMSniipdARy4o4oqCOiJHwq8xInziiJgp4oiKQEcu4oaZLTLip7su4oaYMwogICkKICDiioLiioLiiKnilqEKKQriipDiiLVwYXJzZQo=)
[Answer]
# Python3, 104 bytes
```
lambda s:((-1 if'VRB'in(s:=s.split()[3])else s[:3]),s[3:5],s[(i:=s.index('G'))+1:i+3]if'G'in s else -1)
```
[Try it online!](https://ato.pxeger.com/run?1=tdLLSsNAFAZgcNmnOGSTBFt7zlzaJNBFvDSLGFqSUKW1i0pbDNQqTgV9FjcF0XfSp_FMS0VFlwbmQjgz_zfDPL3ePq6ubpbr53nn4uV-NW8Eb1eLyfXldAIm8rwGQTV3B_mhWy09E3XMgbldVCvPH8mxP1uYGZhRxNO6GclIj3nwKltVLaezB89NXN_fp6jal2PeJuFNwMBmWYP82jbvfc-dGDO7W8Hcc7KTMs4h7R-fg1DU0nII1EKUaQnUVEUGOWHeVBpx0Of_2C2hm0BxVPIckJoZEsQSFUKepRD3BBSnfRHKL1W2axE3x4dOBzyHA5w6OCi5ZxbUfnL6cZZbTtty0H6Wg6zpDY4w4GDkYAGxCAP9NZiINnFISG1egUKAsNGg-QRyB-CCDQD_AqSHvWILUEMQbSSRULgzdE_OUGl7OqGZEjJF2zvAb3dAOrCUUBFyFdkZCESlQLdQ4I7Cm1sKiU0fOr9hkqL8xPDL-DdMg35Itu9lvd6OHw)
Another approach (much shorter and nicer):
# Python3, 83 bytes
Thanks to [Jonathan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!
```
lambda s:[int(''.join(c for c in s.split()[3][i:i+3]if':'>c)or'-1')for i in(0,3,6)]
```
[Try it online!](https://ato.pxeger.com/run?1=tZJfSsNAEIfBx55iECUJ1nZm_yRNQSFq24cYGpJQxdoHrQQj2pY2PngWXwqid9LTONtgjQdwIZslO_m--S37-rF4Ke_ns_VbfnT9_lzmh53P9PHm6fbuBlbdcTErbctqPcyLmT2FfL6EKRQzWLVWi8eitJ2xnIyLbnEgJ0Vuda3jqTNfWodkOaa04FIbm7LpOpMK_bWz3zA7pYHYDdiNelmQQBifXYJQ5Gp5BeQiyjADaqs0goQwaSuNOIr5O_Yz6A8gPc14DUjtCAkCiQohiUIIhgLS81j4slZlJpf4gb3d5lYZB1FilJ5RohlGiWwcjk6xw3BkuIBA-B1dhxPRBomE5PEfKASIDV5zl7KmCM-D31Sj5AT1j6Lfu0CJmwZdBPLazGSRL_6IpOmdPMEmt449GaZV5-oKhIckBuTXyUobstCcwecM2hwQ_jkg0h2TwVeEXEVmBQJRKdAuCqzLBmm2lXGGf5E53QbwWCzNbcvt0nGq27JeV-9v)
[Answer]
# [Perl 5](https://www.perl.org/) `-n`, 59 bytes
```
/ (...)(..)G?(..)?KT/;say for$1eq VRB?-1:$1*1,$2*1,$3*1||-1
```
[Try it online!](https://tio.run/##VZDBSsNAEIbvPsVQcrDFTWYmu2liDyHWJocYGpIQpTcPFQRpautF6LMbZ6xCXdifZZn9vp/dbw9vbhwDuPZ9fyoxLVLNtOyCxfH5E16Gg0fbd@ibu9TQrUczuvFYI5zR6WRo1LGJMWayGKtVlzVQ1vdPwJYiF26AIsSw7IAC21bQEDaBdYh9LfeYd5AX0C47OQNSUCFBFqJFaKoSsjVD@1BzEl5MaUQk@@osq7OqUdlcZahLZSiudb/EWLAoWIaMk9hdYonoB4aENJcXyAysYHDSL/zFl0XbnfF2o39AXFDyZ8hXj2idNmMnokRETvvjv/7kYhUlllCmSE/AiNaCi5Dxa9h/vA6742gq50uZ0ey@AQ "Perl 5 – Try It Online")
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 33 bytes
```
w<>3:3/`3tk"\D"""\ /#1_.||# map N
```
[Try it on scline!](https://scline.fly.dev/#H4sIAD0BbWUCA7WQQU6EQBBF957iL1xoYsKvohumo5mkZ5yZBUMgQNDMRjyAxvuvrEZRPIALCIHivVc9TVf1YYgdqvbxGeqk8PkFUpB5NUAy19fohF3mPDm29p7HAccT.v1gz6BkNQUxpyO6ukJsFP251ZCvptKtELtw_a1rY90lXZl09pVMOpqtGffcGJgGVkQNG78Gi8iMo1BK.4Oq0BntrTBftjnH323Gbke_4I.HJ.acwwpCysx4Jgn6R2ITg_HVLMWC3DX9V7G7QEuKniSsqc4nqnprD9bu06HY7mus36T24IQ2ZdHBQUnn4AsqF9GpH35E1v4PognvD1vc4B7biFu8vX7g7uUTBK8.6AsCAAA#H4sIAD0BbWUCAyu3sTO2MtZPMC7JVopxUVJSilHQVzaM16upUVbITSxQ8AMAWTp_lCEAAAA#)
## Explanation
Prettified code:
```
w<> 3: 3/` 3tk .. get 4th word, chunk by 3s, take 3
"\D"""\ /# .. (vectorized) remove non-digits
1_.||# map .. replace empty (falsy) with -1
N .. (vectorized) convert to number
```
] |
[Question]
[
We all know run-length decoding: A list of character-length pairs expands to a string of that many characters, so `A1B4C2` expands to `ABBBBCC`. But what if we stretch this concept to 2 dimensions?
Instead of character-length pairs, in this challenge you will be given character-length-direction triples. For example, using N/S/E/W to indicate direction, the input `A4E B5S C3W D3N E1W` should yield the output
```
AAAAB
B
E B
D B
D B
DCCC
```
You can take input in any reasonable format (such as a list of `(char, length, N/E/S/W)` like shown here, or perhaps `(0/1/2/3, length, char)`).
The input will not overlap itself, so `A5E B3W` or `A5E B4S C4W D4N` is invalid input.
The input will also not expand past the left or top edges of the string, only the bottom and right edges will be expanded.
The character will always be within the printable ASCII range.
Consistent trailing or leading whitespace that does not affect the presentation of the output is fine.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission per language, measured in bytes, wins.
Here are a couple cases to test your entry against:
```
A4E B5S C3W D3N E1W
AAAAB
B
E B
D B
D B
DCCC
A4E B5S C3W D3N -2E -1N 2W |1S
AAAAB
| B
---B
D B
D B
DCCC
.3S 2E ,3N 2E .5S
. .
. , .
. , .
, .
.
>6E v3S <6W ^2N >5E v1S <5W
>>>>>>v
>>>>>vv
^<<<<<v
^<<<<<<
```
[And here's an example implementation in JavaScript.](https://ato.pxeger.com/run?1=hVPBjpswEFWvfMWIk1HAWpJmtdKGSG2XnqocyoEDpRIiZkNKTQp2lajJl-wlh_aj2tv-yKpjGxJ2K6WRItvj996M5w0PP3m9ZMfjLykK7-bPq8dC8lyUNYdl2TC9y6qPkn9g_F6s7liOaFLyjQM_LIC85q2ArGkggCS9xUjFBGzxdNUfdv2hqBsgSb7KGhcvlJp7zpFCXcBJtgMreqnpuMw6Eu5Hox4GKneyS2G_7wtQv7IAYi6oIcEsgO2ZNNBfG_016m9xUdIdcyPbFbHBdnrVw7OUyTZFqnrOMOvpQRAEAdih7WA3RgH4F0CxBnmXQRGCdv9TWmjQWUlVrP4NE7LhqvBb69A7_WTMw6ZLgS9p2DeJasQuWtuhDcuW78uKRTuekysXbCTdqFboxhlmVXLW2SYFbTdVKYj9idvOcDZ0WE0HpVQRtEfmKl9J_qXFO43BlEuZM0JM2AXOtsKBYN65pp5rrmgmiOc7vbXq5ROnUzOuJWlnGqtaBs9ZGqC1DaTrjQGp0MGFJEmNgilUNWOnzdZCX7MNGQyynuJUV9oFR-foUKSVlerEhe9KJzpx6orRqr4nqm3_BI2crkX7gNnVStd1yYmNHnQ77cdLsnMag-Pv_M3rEN5OI3g3ieFusoDQj62XMW8cgucvAMYx7P3IopMI9yG4k4Ve6TSy5tchfMf47DqGz-MFzKd49vE8jU2uvw)
[Answer]
# [Python](https://www.python.org), 120 bytes
```
def f(A):
G=[];X=Y=0
for c,n,(x,y)in A:
for _ in" "*n:G+=[[]];G[Y]+=[_]*(X-~len(G[Y]));G[Y][X]=c;X+=x;Y+=y
return G
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY9BToQwFIb3nOKlq3amTCCjiYF0gUrYzWYWQJpmFgxozaSQUiLE6EXcsNELeADP4W1smTFx1ff9f_O_979_dpN5bNU8fwym8W9-xmPdQIMTEnmQMS7igpUs8KBpNVRUUTzSiUgFifUX8QBSIUArFWVrxrkQccZLYceDWOHCfzvVCjuFkMXghWBVXKzZGJdrNnmgazNoBdll_7dUvdFDZWSremA2vBsMJpu-O0n7eg9aHq3cYI5HHghqPxg7hZEfCkLhBVCKIsAhhcAiyh34f7R3FFAIHewu4IcEXvnIbYAgS6XRhsL_OwTxnK7bZ-e4E1x7gE677QhtnlqpsLUJOdeYv5KrFG6v93C3zeF-u4M0zM_WLw)
* -29 bytes thanks to [noodle man](https://codegolf.stackexchange.com/users/108687/noodle-man)
* -2 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
WS✳§ι⁰×§ι¹I✂ι²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDM6@gtCS4pCgzL11DU1MhAMgo0XDJLEpNLsnMz9NwLPHMS0mt0MjUUTDQ1NRRCMnMTS1GFjUECjonFpdoBOdkJqeCRIw0gcD6//8gOzMulzJjLh8bM67QOCOuIDtTIN8QyDfl@q9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated triples using a leading `UDLR` instead of a trailing `NSEW`. Explanation:
```
WS
```
Loop over each triple.
```
✳§ι⁰
```
Output in the direction given by the first character.
```
×§ι¹I✂ι²
```
Output the required character repeated by the length.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
ṫ⅛ƛy›Y;¾J⟑÷ø∧
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLhuavihZvGm3nigLpZO8K+SuKfkcO3w7jiiKciLCIiLCJbW1wiQVwiLCA0LCAyXSxbXCJCXCIsIDUsIDRdLFtcIkNcIiwgMywgNl0sW1wiRFwiLCAzLCAwXSxbXCItXCIsIDIsIDJdLFtcIi1cIiwgMSwgMF0sW1wiIFwiLCAyLCA2XSxbXCJ8XCIsIDEsIDRdXSJd)
Vyxal does have a built-in canvas (fork of 05AB1E's canvas element), but it partially overwrites the drawn characters, so the input has to be modified.
Takes in input as a list of `[char, length, direction (0/2/4/6)]`.
```
ṫ⅛ƛy›Y;¾J⟑÷ø∧
·π´‚Öõ # Push tail to global array
∆õ ; # For all other elements ...
y›Y # Uninterleave, increment, interleave (increment the middle)
¾J # Push global array (wraps tail in list), join with rest
‚üë # Map through list
÷ø∧ # Draw modified input to canvas
```
[Answer]
# [Perl 5](https://www.perl.org/), 156 bytes
```
sub f{($o,$p,$c,$n,$d,@r)=@_;@_%3?$n?do{$$o[$p]=$c;f($o,$p+1+{N,-99,S,97,W,-2}->{$d},--$n?($c,$n,$d):(),@r)}:"@$o"=~s/.{98}/$&\n/gr:f([(' ')x1e4],$"='',@_)}
```
[Try it online!](https://tio.run/##hVPNbtpAEL7vU4ycbdcoa1tATAsG4gTopRVI0CiHkCAX1sQteF3b0FSO8xK99NBDny0vQnfXkFhRq45kf579Zr75sR2xeGXvdsnmE/iZjjnFEcVzikOKF9SNKx135rizV/VTHJ4ueIYxv8LRdQfPHb@IPq4eZ0NqNJt0Qptv6CU1arnRzfAip4YhkvSDWqWlV6Ri3tJczLXOQ2KZWfNtbuHX09Baxi1fv9IJkMpdlZ1cU6x1CKHurJLv1t8B@16wcpDPYx1dkbOTAaFAzu2JhF79UkK/PpQwqEqv3SbkmqIzYecAgMQF5wgG6t4v33u9HvqPpFFTnFFVHtQUd1@d/K3OvVI1DOMfdcz6pBBRkrQ@LHmmXZI0hZwJAqiAZ4QCi4lMqdhtqORtIdxuqO5uakq4axdcteDs0mq6yrZQPGy36KYt7YBthCqZLCKXz@4iNk/ZAjoQ8QhcPHP2lBuE0SYV52svggySaBWklgV5OQYvuYzw9UN0xUGSKsk@QGJNk2NsWeulA0daj4dJkKQsTCGNxZsPwiXwGFbMW8jHb7dBypLImzNIb70UFpwlSlFWUvZS0TTNUHCe74uKIolBFLNE6HtpwEPgvjrjm1T2FyTgByEzNXSYQMRuVnKI557Z16LcKRD@hUAL5N8hv9IOGY4@wug9yZ8WoMZO0lgIfOZBqN68WJhG8IxotNiKCo7iQIysGU92KD0NtXKAymg9C@/poz19aLI1DZ8afqEgWpesAEXkaH8uPFr8bXKyx5@/YTAej8YTeDe6GPblnOTx1w/wViuWwHKTillkjrMbdxuov62jD@0GuripoXHXFn5V@Db6Aw "Perl 5 – Try It Online")
[Answer]
# [J](https://www.jsoftware.com), 42 bytes
```
1 :'#&u@[[`]`(u:@32$~1+>./@])}[:}:0+/\@,#'
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dU_BTsJAFLzvVwxi3NbC0m1pI5valG7ryfQghx5qAWMgysULbTyAP-IFD34U3-EP-FrQ4MHZzJt9Lzuzee8fq93-YdRRsvQ7asQ5y2IBCcW7F1VUwAjEICo3opiXc6NSkeucv0mrUKEYbKLS3JqF2irbGtxHvS5nZ4Ivca3A0YMNRewL6Lvbm89qvexf7S9_g__mhc0n5vY06-j4Mtni8ekFQ3hw6UgYfBzrJOVLE5aAvZI0s1cziVmjsn1Oa7Qunxw-HPJKosHDOpgS__MeO8YWr89ryhgPU8TeBNrNkbgZUpmzMSEGwIiIGdK2JqdVa81CP0XtThD4OaZOhtCjXlLv5SxsUeNwqWs2DRr8aHBYfbc76Dc)
A J adverb, which modifies the list of characters to produce a verb that takes the counts as a left arg and the directions as the right arg, as complex numbers in list form.
* `[:}:0+/\@,#` Duplicate each direction by the counts, add `0 0` as a starting point, scan sum, and remove last.
* `#&u@[` Also duplicate the characters by the counts.
* `u:@32$~1+>./@]` Create a canvas of spaces of the appropriate size.
* `[`]`...)}` Update the canvas at the points computed by the scan sum, using the duplicated characters.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 29 [bytes](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{/‚üúùïó{ùﮂåæ(ùï©‚ä∏‚äë)""‚ÜëÀú1+‚åଥùï©}¬∑+`‚ä∏-/}
```
Try it [here](https://mlochbaum.github.io/BQN/try.html#code=X0Yg4oaQIHsv4p+c8J2Vl3vwnZWo4oy+KPCdlaniirjiipEpIiLihpHLnDEr4oyIwrTwnZWpfcK3K2DiirgtL30KCm7igL9z4oC/ZeKAv3cg4oaQIOKfqMKvMeKAvzAsMeKAvzAsMOKAvzEsMOKAv8KvMeKfqQrigKJTaG93IDTigL814oC/M+KAvzPigL8xICJBQkNERSJfRiBl4oC/c+KAv3figL9u4oC/dwrigKJTaG93IDTigL814oC/M+KAvzPigL8y4oC/MeKAvzLigL8xICJBQkNELS0gfCJfRiBl4oC/c+KAv3figL9u4oC/ZeKAv27igL934oC/cyAK4oCiU2hvdyAz4oC/MuKAvzPigL8y4oC/NSAiLiAsIC4iIF9GIHPigL9l4oC/buKAv2XigL9zCuKAolNob3cgNuKAvzPigL824oC/MuKAvzXigL8x4oC/NSAiPnY8Xj52PCJfRiBl4oC/c+KAv3figL9u4oC/ZeKAv3PigL93CkA=).
Defines a 1-modifier which takes the lengths as left argument, the directions (as a list of `‚ü®dx,dy‚ü©` pairs) as right argument, and the characters as a list (string) in the role of the function `ùîΩ` being modified.
Explanation:
The basic idea is to [replicate](https://mlochbaum.github.io/BQN/doc/replicate.html#replicate) both the characters and the directions by the lengths, do a prefix sum on the directions to get the list of indices corresponding to each character, and then use [structural under](https://mlochbaum.github.io/BQN/doc/under.html#structural-under) to index into a blank array and place the characters at their corresponding indices.
```
{/‚üúùïó{ùﮂåæ(ùï©‚ä∏‚äë)""‚ÜëÀú1+‚åଥùï©}¬∑+`‚ä∏-/} #
/ # The directions replicated by lengths
+`‚ä∏- # subtracted from its own prefix sum (shifts right so starts with 0‚Äø0)
}¬∑ # becomes right argument ùï© to inner function.
/‚üúùïó # The characters replicated by lengths
{ # becomes left argument ùï® to inner function.
‚åଥùï© # Get the maximum x,y values from the indices,
1+ # add 1 to get the shape of the output,
""↑˜ # and take from empty string to get the blank character array.
‚åæ(ùï©‚ä∏‚äë) # Pick out the indices in the array
ùï® # and place the characters.
```
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 131 bytes
```
{for(;$2--;y+=/S$/-/N$/){g[+x,+y]=$1;x>X&&X=x;y>Y&&Y=y;x+=/E$/-/W$/}}END{for(y=-1;y++<Y;print"")for(x=0;x<=X;)printf"%1s",g[x++,y]}
```
[Try it online!](https://tio.run/##HcxBC4IwGIDhuz9jrJHMsZZ1mp9QuY5ePKiIhy6KBCoqtSH@9ZZ6fXl4X9@3tXPVDUeJz4xJQ4EnmDMeY@7OdUG1R00JWEgdZoRkoKUJc0JyMFKvVm02xXxZVBztHwNMrBsa5LIfmnZCyN2yhpPUAWTS3WuFDmJEXl1oSj1TLtbeLsq5XxPn4adO5MeOEqn9df3UdO1o2eeZwB8 "AWK – Try It Online")
[Answer]
# [Scala 3](https://www.scala-lang.org/), ~~207~~ ~~166~~ 149 bytes
Port of [@hyper-neutrino‚ô¶'s Python answer](https://codegolf.stackexchange.com/a/266285/110802) in Scala.
Saved so many bytes thanks to the comment of @noodle man and @Kjetil S
---
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=VVE9b9swEEVX_4qDltzBlCDBLVBYloE08VCgyeIWHgyhYPXBUFUol6ITGYbn_oJOXbIkS39R-mtKSqkDEzge8N4d393j76c24zWf_Fl7vmruuVZe-nzZfKuKzMAVlwr2oxHc8RrKKX6SrVnjxQ3X7KMyDN1lgyhN5svix9qFY9OUIHncmtJ___yLJ_P9HdcomGQVJXhaiMRCFlJcNhoxY4phx3ZEM5_HX2d-aBpQfkR7kYjpuJfv25BiiwTbTc5NkWPFBFYUbHj-ucFoLNkZnNGRlSwjiuU46eJqnOziQywOw3B_3_wEyIsSbu2iyLVop3CuNd-tl0ZLJVKawhclDSTWBbDH-ZBLbb2RjbriG0vYG3sOwFt44M8BIwYhsf_gagD9U3Q5oCGD6BW8PoJ25x6ko6xUrdHbXri1ss4L9M7fLjwG3od3S5cuJiuXLifXLi2ilffaLrTMbVuJ1mjADmb-yYsEO1nUuWXQDgld0NYyK9wmXVAXSpgb8O2kgWncn594gLaCt8ZSg2lEg2ovpJt7J-XUCTaWNrVyYHD7_aXa1h5GL__x8DDkfw)
```
a=>{var(g,i,j)=(Seq[Seq[Char]](),0,0);for((c,n,(x,y))<-a;_<-0to n-1){g=g:+List[Char]();g=g.updated(j,g(j).padTo(1+i,' ').updated(i,c));i+=x;j+=y;};g}
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=bVNda9swFH3oW37FqV8qUdkkZIMSmkHWhjBo-xJGYkoYmj8Sra4cZGV1KP0le-nL-qP6aybJip2N-eHK95xzda91rF9vVcILPnx9_b3TeXjxfnJafv-RJRq3XEg894A0y5GTyQg3otL35GrDFcMXqRmIiyZQuqKed8FqViuMXT3wkyvMTPavgNCWXhq632Zxm-WlAiEJgzTtaoY9pbgMMaF-a6_4ZsE-dlKLArIjAZGDzKIik2u9weUYMXWjzDA6RzeKn8Q-TxtRZKaGxPSobOnLot025TpLScxgJXabM5x15f9VtfmSIaGdeInzMeo2jW269-lLr4uznn3zXjwaYwhX62qEiVJ8fz_XSsi1deCrFPro1AukQhkvRSlv-dYQJhK_fTANEH4CGTD0KTuAiwYM_0bnDdpnGHTgXQuGg-aLaNtWyEqrnWtced9JMPkwDRiCzx_ndrkaLuxyPbyzy3SwCLrytRKpKcuJ87a23h7vSLEXWZEahpghUUdVIZLMfkl9cCw0k0a6dP_n8RkQo-CVNlRzaNSb4Rqp8sm2st0ptobWhbRg9Pjg1c6Gl-am-AtzuDh_AA)
```
object Main {
def f(A: List[(Char, Int, (Int, Int))]): List[List[Char]] = {
var G = List[List[Char]]()
var X = 0
var Y = 0
for ((c, n, (x, y)) <- A) {
for (_ <- 0 until n) {
if (G.length <= Y) G = G :+ List[Char]()
while (G(Y).length <= X) G = G.updated(Y, G(Y) :+ ' ')
G = G.updated(Y, G(Y).updated(X, c))
X += x
Y += y
}
}
G
}
def main(args: Array[String]): Unit = {
val directionMap = Map(
"E" -> (1, 0),
"W" -> (-1, 0),
"S" -> (0, 1),
"N" -> (0, -1)
)
val instructions = List("A4E", "B5S", "C3W", "D3N", "E1W")
val grid = f(for (x <- instructions) yield (x(0), x.slice(1, x.length - 1).toInt, directionMap(x.last.toString)))
for (row <- grid) println(row.mkString)
}
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~119~~ 116 bytes
```
A=>A.map(([c,n,[x,y]])=>{for(_=0;_<n;_++){G[Y]=[...(G[Y]??[]).join``.padEnd(X)];G[Y][X]=c;X+=x;Y+=y}},G=[],X=Y=0)&&G
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVLLbtswEAR69A_0utAhIGGKsKw6CKrQgduqvvmig2ywrCNIVKxWpVw9Ahuuv6SXoGg_Kv2aUqQQIOmJw9nd2eEuf_5WVSYffuXsT9fm7tVju2DzBf2W7BHiKVGEH8hRCMzmp7yq0ZZNgu21CrbjMT4t-UYwTilFPbq54QLTL1Whbm_pPslClaE1FkEf42vB0mA9ZodgM2bH85ksGRdkzTZsgi8ulrb331ev00o1LRRq37XAoJbfu6KWyMkbB9NaJtnHopTRUaVoQsDRRVcODkbaGCBbWRZKQpVbBdrsy6JFziflYAynEYBNMrSW7633BSJ4CqW7Tn1tdMzk6JZZl0qELE1AyUOLgc2NGECRwxCiSYtcD9NSqrt2B4wx8PGgRvdds0N6OIEpkmUj4XmVSTDaNqWWbVerIamnzgQ4F1bBGu2HcdQ-B6FhX7ukJqA9EMiKWhinAzk27AnCt8A9AhNBINbQHfBKYz1S19M4stgTcOa9zPO2TVf2s8uRcfAUqkpJy-oO9fP8j7RVxqRZkLbVn-azIEcvZ0BmUS-LNXG2_-PhMV28CeHdLIL3fgwf_BWEXjx6ybnTUD9kBTCN4YcXjagfaRwC8VfmpLNoNL8M4V7z15cxfJ6uYD7Td0_fZ7Ht9Q8)
This is a golfed version of the example implementation I provided. It takes the input as a list of `[char, length, [dx, dy]]`.
Explanation:
```
A.map(([c,n,[x,y]])=>{ ... },G=[],X=Y=0)&&G
```
This first assigns G (a 2d array of characters) to an empty list and X and Y both to 0. It returns G after first running the following on each character `c`, length `n`, dx `x`, and dy `y`:
```
for(_=0;_<n;_++){ ... }
```
Run `n` times:
```
G[Y]=[...(G[Y]??[]).join``.padEnd(X)];
```
Pad the Y'th list in G to length X with spaces.
```
G[Y][X]=c;
```
Set the X'th character of the Y'th list in G to `c`.
```
X+=x;Y+=y
```
Add `x` to X and `y` to Y.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ā¤Ê+ŠΛ
```
-1 byte thanks to *@CommandMaster*
Inputs as three separated lists of the same length: \$lengths,directions,characters\$, where the \$directions\$ are `0246` for `NESW` respectively.
[Try it online.](https://tio.run/##yy9OTMpM/f//SOOhJYe7tI8uODf7//9oEx1THWMgNNIxBOFYrmgjHRMdMx0DIM8ASJsARZQclXSUnIDYGYhdgFgXihWAuEYpFgA)
If the input as a list of triplets is mandatory, it's **8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead:
```
ø`ā¤Ê+rΛ
```
Inputs as a list of triplets \$[direction,char,length]\$, where the \$directions\$ are again `0246` for `NESW` respectively.
[Try it online.](https://tio.run/##yy9OTMpM/f//8I6EI42Hlhzu0i46N/v//@hoIx0lRyUdk1idaBMdJSclHVMgy0xHyVlJxxjIMtBRcoGwgOp0lXSMIGJAliFEnQJEDKi3BiQWCwA)
**Explanation:**
```
ā # Implicitly push the first input-list of lengths, and then
# push a list in the range [1,list-length], without popping the list
¤ # Push its last item (the list-length) without popping the list
Ê # NOT-equals check on each value, so we'll have a list of [1,1,...,1,0]
+ # Add the values at the same positions of the top two lists together
Š # Triple-swap to push the list of characters and directions from the third and
# second inputs implicitly
Λ # Use the Canvas builtin with these three lists as arguments
# (after which the result is output immediately)
```
```
√∏ # Zip/transpose; swapping rows/columns of the implicit input-list of triplets
` # Pop and push all three lists separately to the stack
ā¤Ê+ # Same as above to change the top list of lengths
r # Reverse the order of the three lists on the stack
Λ # Use the Canvas builtin with these three lists as arguments
# (after which the result is output immediately)
```
[See this 05AB1E tip of mine to understand how the Canvas builtin works](https://codegolf.stackexchange.com/a/175520/52210), and why we increase the lengths (except for the last one) by 1 first.
] |
[Question]
[
Isn't it annoying when you're taking a picture, but the background detracts from the actual substance of the image? I'd say it is. I need to know how much I should crop so that I get rid of this problem! But - as usual - I am quite lazy, so I need someone to do this for me...
## Task & Rules
Given a binary matrix representing the image, output the dimensions (width and height) of the smallest sub-matrix that contains all the \$1\$s in the original matrix. A *sub-matrix* is a block of adjacent entries from the original matrix. Equivalently, it is a new matrix formed by overlapping a subset of adjacent rows and a subset of adjacent columns of the original.
* It is allowed to take the width and the height of the matrix as input as well.
* The input is guaranteed to contain at least one \$1\$.
* 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), 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](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to complete the task in the least bytes you can manage in your [language](https://codegolf.meta.stackexchange.com/a/2073/59487) of choice.
## Example
$$\left[\begin{matrix}
\color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0\\
\color{red}0&\color{blue}1&\color{blue}0&\color{blue}1&\color{blue}0&\color{blue}0\\
\color{red}0&\color{blue}1&\color{blue}1&\color{blue}0&\color{blue}1&\color{blue}1\\
\color{red}0&\color{blue}0&\color{blue}1&\color{blue}0&\color{blue}1&\color{blue}0\\
\color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0\end{matrix}\right] \longrightarrow \left[\begin{matrix}1&0&1&0&0\\1&1&0&1&1\\0&1&0&1&0\end{matrix}\right]\longrightarrow(5,3)$$
## Test cases
```
Input | Output
[[0,1,0,0,0,1,0]]
--> (5,1) or (1,5)
[[0,0,0,0,0],[0,1,0,1,0],[0,0,1,0,0]]
--> (3,2) or (2,3)
[[1,1,1,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
--> (4,4)
[[0,0,0,0,0,0],[0,1,0,1,0,1],[0,0,0,0,0,0]]
--> (5,1) or (1,5)
[[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]]
--> (3,3)
[[0,0,0,0,0,0],[0,1,0,1,0,0],[0,1,1,0,1,1],[0,0,1,0,1,0],[0,0,0,0,0,0]]
--> (5,3) or (3,5)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
JYaZy
```
[Try it online!](https://tio.run/##y00syfn/3ysyMary//9oA2sFQ2sFAxgCsWMB "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8N8rMjGq8r9LyP9oAx1DHQMwBNKxXNEGUJ6BNUTGEMyCqgLKG@qAoTVCFYSGmoJsArIZCB3oqrDZgyaG32QIG8IzhJuBoheoGwA).
### Explanation
```
JYa % Implicit input. Unpad matrix. This removes outer zeros
Zy % Size. Implicit display
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 [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")
Anonymous tacit prefix function.
```
(1+⌈/-⌊/)⍸
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X8NQ@1FPh77uo54ufc1HvTv@pz1qm/Cot@9R31RP/0ddzYfWGz9qmwjkBQc5A8kQD89gkBKQiFewv596dLSBjqGOARgC6dhYdS50aSiM1YEqNYSyoRoxtRjqgCFUkQFcOYQFtQ2PTah2IRtEQCNOJ2KKk@gGGA/CN0QyHM1IsKEA "APL (Dyalog Unicode) – Try It Online")
`⍸` indices of 1s.
`(`…`)` apply the following tacit function to that:
`⌊/` the minimum (lowest *y* coordinate and lowest *x* coordinate)
`⌈/-` the maximum minus that (this gives us the range)
`1+` one plus that (to be inclusive)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~57 56~~ 45 bytes
Here `find` does the heavy lifting: It `finds` the row and colum indices of the nonzero entries. Then we just have to find the difference between the maximum and the minimum (plus one) for each of those seperately.
Thanks @beaker and @AndrasDeak for -1 byte, and @LuisMendo for -11 bytes!
```
@(a){[I{1:2}]=find(a),cellfun(@range,I)}{2}+1
```
[Try it online!](https://tio.run/##jZDLCoMwEEX3@Qo3hYSOYoxuKha3foO48BGLIFrtYyN@uzUm2rQFKbPImTt3bkLa/J4@@dQFlmVNIU7JEEcDPTljEpRVU8wC5Lyuy0eDwz5tLhwiMg7OeKRTGsSxDRTspeYzSXyULaKqxFcGqljZhTGfjRSWUiN7M0lSycJc6Kmfufr6aud/PeJX3wLKnfvWTvZUi/wKklGoqG5X3M0fSfyVM41zjQuNucalYIQOpnk2sAeUGG1vYAoeURoDR2oOsFVzwSW7K@w9ZnLMxBhNLw "Octave – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~92~~ 86 bytes
```
def f(a,L=len):exec"a=zip(*a[1-any(a[0]):])[::-1];"*4*L(a[0])*L(a);return L(a[0]),L(a)
```
[Try it online!](https://tio.run/##lVDLisMwDDwnXyFySoIKVtmTS/@gf2B0MLsOG1jcEFJo9@eza8eJ82ghRQJLo9GMcPPovq/22PdfpoIq13g5/xhbSHM3n5k@/9ZNXmpFB20fuVaCC8mFkvJAfMrKj/IygO4tTq3pbq2FgKHD@uragobaggKlBBIKH/8vM3ooBGMYU6gDeaAR@ggDMVGGKqiuFJea8@VATpNkzwFbfIfb2A09zQRXMk6IZZo0bW070Fi5X3O6QAhiTFczpx6P6S6YiBSBuOx3yLcu41ws2GMXLbdmz/w2kq@Wd1z6mvHmSTNsgmnt99TBm/wB "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
S,§t€0Ẉ
```
[Try it online!](https://tio.run/##y0rNyan8/z9Y59DykkdNawwe7ur4f7gdyHL//1@DSyE62kDHUMcADIF0bKwORAwKY3Wg8oZQNlQ1VJ2hDhhCZQzgaiAsqLnoZqKaiqwbm2qcLsAUJ8Y2GA/CN0QyEc0ciEmaAA "Jelly – Try It Online")
### How it works
```
S,§t€0Ẉ Main link. Argument: M (matrix)
S Take the columnwise sum. Let's call the resulting array A.
§ Take the sum of each row. Let's call the resulting array B.
, Pair; yield [A, B].
t€0 Trim surrounding zeroes of A and B.
Ẉ Widths; yields the lengths of the trimmed arrays.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~63~~ 55 bytes
-8 with help from Vincent (take the input matrix as a Numpy array)
```
lambda a:[len(`a.max(x)`[7::3].strip('0'))for x in 0,1]
```
An unnamed function accepting a 2-d Numpy array of integers (in `{0,1}`) which returns a list of integers, `[width,height]`.
**[Try it online!](https://tio.run/##lVLLCsMgELznK/amgg2xPRSE9keMEEsbGmiMGAvJ16cxsUn6ps7B3XVmdmE1rTtXet3lu7S7qPJwVKC4uJw0zlRcqgY3JBNbzjcyrp0tDEYJIiSvLDRQaEgok11Rmso60NfStKBq0CbyBHeqnedgIXoaTQb0t5QRLA71zwGSBioLcRC@ShgdEEjJRB@j0O1Lp8deS6Mfwo8jvtb/nOGejTlbmD9ZfjJlbzFL378@WhE@pH5/1i/PL5FPDGML7SCzmWD@S0RzDa32iEKOtYmVtarFXkgIBZRq1N0A "Python 2 – Try It Online")**
---
Non-Numpy version in 63 bytes (accepting a list of lists of integers in `{0,1}`):
```
lambda a:[len(`map(max,v)`[1::3].strip('0'))for v in zip(*a),a]
```
[Try it online!](https://tio.run/##lVJBDoIwELzzit7amtVQvTXRj0ATaoRIAoWUhqifRwoVQUBj99Dd6czsJtvybq6F2jfJMWwymZ8vEkkeZLEiUS5Lkssb1DQKGOcHsauMTkuCfUxpUmhUo1ShR4tsJAUpGouZuDIWJkHgAwO/i/YWwkOjA/bZhQBHZS53wrmEQReO5A/0PnPdvnSa9hob/RCujjjH/5zhVfU1G5l/WK6ZssV4S5dfp1aUd6Xdn7bLs0vkA6PUqTIo0u4XeG8Mb08YUEIsnwLCocLNEw "Python 2 – Try It Online")
### How?
Given a matrix, `a`, `for` each (`v`) of the transpose, `zip(*a)`, and `a` itself we find the height required (given the transpose this is the width).
Mapping `max` across `v` yields a list of zeros and ones, representing if each row of `v` contains any ones. The string representation of this list is found using backticks (``...``), this gives a string with a leading `[`, then the zeros and ones delimited by `,` (comma+space). We slice this string starting at index one in steps of three using `[1::3]` getting us a string of only the zeros and ones, which allows us to use the string function `strip` to remove the outer zeros (`strip('0')`).
For example:
```
a = [[0,0,0,0,0] map(max,a) = [0,1,1]
,[0,1,0,0,0] `map(max,a)`[1::3] = '011'
,[0,0,0,1,0]] `map(max,a)`[1::3].strip('0') = '11'
len(`map(max,a)`[1::3].strip('0')) = 2
zip(*a) = [(0,0,0) map(max,zip(*a)) = [0,1,0,1,0]
,(0,1,0) `map(max,zip(*a))`[1::3] = '01010'
,(0,0,0) `map(max,zip(*a))`[1::3].strip('0') = '101'
,(0,0,1) len(`map(max,zip(*a))`[1::3].strip('0')) = 3
,(0,0,0)]
--> [len(`map(max,v)`[1::3].strip('0'))for v in zip(*a),a] = [3,2]
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 83 bytes
```
+`^0+¶|¶0+$
+1`((.)*).(¶(?<-2>.)*).(?<=(1)¶.*|(.))
$1$3$4$5
(¶?)*0*(.*1)0*
$#1 $.2
```
[Try it online!](https://tio.run/##JYoxDoMwDEV3n6ISHmxHWDaFLSU3QTAwsHSoOnKuHCAXS1P4f/h6ev@zf4/3VmtYFwslnyVbQIDgK5GysFLJlGI/zDel@CLnklXO5hnQ8YkjTtB@icWEVJxNADt/oA612hUwb/1PWwe7EG73Aw "Retina 0.8.2 – Try It Online") Explanation:
```
+`^0+¶|¶0+$
```
Delete leading and trailing zero rows.
```
+1`((.)*).(¶(?<-2>.)*).(?<=(1)¶.*|(.))
$1$3$4$5
```
Remove all `0`s on the lines above the last. Remove all the `1`s two, but change the digit underneath on the next line to a `1` in that case. This bitwise or's the rows together.
```
(¶?)*0*(.*1)0*
$#1 $.2
```
Count the number of rows as the number of newlines plus 1 and the number of columns as the number of digits between the first and last 1.
[Answer]
# [J](http://jsoftware.com/), 31 bytes
```
[:$([:|.@|:}.^:(0=1#.{.))^:4^:_
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D/aSkUj2qpGz6HGqlYvzkrDwNZQWa9aT1Mzzsokzir@vyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagqGCuQrQFEMgNoDQMBljBVMFFagwXBJZIUKpCRCqAIUg0AANQkUQ5pqhmYswGUUzTIMpYYfg147bPgjbEE5iMQYYvAA "J – Try It Online")
## Explanation:
```
^:_ - repeat until the result stops changing
( )^:4 - repeat 4 times
^:( ) - is
1#. - the sum of
{. - the first row
= - equal
0 - to 0
}. - if yes, drop the first row
[:|.@|: - transpose and reverse (rotate 90 degrees)
[:$ - what's the shape of the result?
```
[Answer]
# q/kdb+, 16 bytes
```
sum@'(|/;|/')@\:
```
[Answer]
# Mathematica, 34 bytes
```
Max@#-Min@#+1&/@(#~Position~1)&
```
Pure function. Takes a nested list of integers as input, and returns a list of two integers (the height followed by the width) as output. The Unicode character is U+F3C7 for `\[Transpose]`.
[Answer]
# [R](https://www.r-project.org/), ~~48~~ 46 bytes
```
function(m)1+diff(apply(which(m>0,T),2,range))
```
[Try it online!](https://tio.run/##lU7bCsIwDH33SxLMQ@PlcX7FfqBW4wq2G2Wy7evrdOLoqIocOAkh5xKiFFFu3rS29uCQ1ycrArpprgN0lTUVuIOiEmlDQfvLGTEKON0G24MBRUzqiXHiSMch1F1RIq6SrxlMieah2uZVTBPUAq8L0u532pyX@HzM/No077T/p8W085szjgvPeAc "R – Try It Online")
-2 bytes saved by Giuseppe.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ζ‚Oε0Û0Üg
```
-2 bytes thanks to *@Mr.Xcoder*.
[Try it online](https://tio.run/##yy9OTMpM/f//3LZHDbP8z201ODzb4PCc9P//o6MNdMAwVgfKMoSzIGKGKLIGsbEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/3PbHjXM8j@31eDwbIPDc9L/1@r8j46ONtAx1DEAQyAdG6ujABKCwlgdqLQhlA1VDFFmqAOGUAkDuBIIC2oqmomoZiJrxqIYp/WY4kTYBeNB@IZIBqIZg2YQXArdp4Zofo6NBQA).
**Explanation:**
```
ζ # Swap the rows and columns of the (implicit) input-list
‚ # Pair it with the (implicit) input-list
O # Take the sum of each column and row
ε # Map Both the list of column-sums and list of row-sums to:
0Û # Remove all leading zeros
0Ü # Remove all trailing zeros
g # Take the length of the remaining lists
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ŒṪZṀ_ṂƊ€‘
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7V0U93NkQ/3Bn07GuR01rHjXM@P//f3S0gQ4cxuoAeYY6EAzjQfiGYB5cFsqD6YsFAA "Jelly – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 76 bytes
```
f x=length.s.reverse.s<$>[foldr(zipWith(:))e x,x]
e=[]:e
s=snd.span(all(<1))
```
[Try it online!](https://tio.run/##XckxCgMhEEDR3lNMsYWCSGyXNddIIRbCjlFijDhLkFzewGKT8KvHj54emPMYAbrJWO5HVKQavrERKtqWqw2vvDf@SfWWjshXIRC67I6hsW5FRobKrqj6wn3OfNNCjKdPBQzUlsoBCwSwDOxFzpw8pU/pqd83799z4ws "Haskell – Try It Online")
[Answer]
# Japt, ~~16~~ 15 bytes
```
[UUy]®=ðd)ÎaZÌÄ
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=W1VVeV2uPfBkKc5hWszE&input=W1sxLDEsMSwxXSxbMCwwLDAsMF0sWzAsMCwwLDBdLFsxLDAsMCwwXV0KLVE=) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=W1VVeV2uPfBkKc5hWszE&input=WwpbWzAsMSwwLDAsMCwxLDBdXQpbWzAsMCwwLDAsMF0sWzAsMSwwLDEsMF0sWzAsMCwxLDAsMF1dCltbMSwxLDEsMV0sWzAsMCwwLDBdLFswLDAsMCwwXSxbMSwwLDAsMF1dCltbMCwwLDAsMCwwLDBdLFswLDEsMCwxLDAsMV0sWzAsMCwwLDAsMCwwXV0KW1swLDAsMCwwLDBdLFswLDEsMCwxLDBdLFswLDAsMSwwLDBdLFswLDEsMCwxLDBdLFswLDAsMCwwLDBdXQpbWzAsMCwwLDAsMCwwXSxbMCwxLDAsMSwwLDBdLFswLDEsMSwwLDEsMV0sWzAsMCwxLDAsMSwwXSxbMCwwLDAsMCwwLDBdXQpdCi1tUg==)
---
## Explanation
```
[ ] :Create an array containing
U : The input and
Uy : The input transposed
® :Map each Z
ð : Indices of elements where
d : Any element is truthy (not 0)
= ) : Reassign to Z
Î : First element
a : Absolute difference with
ZÌ : Last element
Ä : Plus 1
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 60 bytes
```
->m{[m,m.transpose].map{|x|x.map(&:max).join[/1.*/]=~/0*$/}}
```
[Try it online!](https://tio.run/##lVDLCoMwELz7FTmU0pY0yV4L9kdCDhYqtBAVbSFF7a/bJEbjEyy7kN3Z2Zkl@fv2aeKwOV9lySWW5JVHSZGlxV0QGWVlpSplisP@IiN1JM/0kXAK5ERF@KXstKN13fAAcc4wYGZDv0LgFnMhsJuDqx3b8QDbcBPWc9rK6U41x6rD7SX26gVzfItb17U9DBQnOkYp6P8yQzFXQv@YJiDAiHVpak20uE@BkSeCB/yy3QHbmvRzNmJ3nbecmy35zSTXljdcus7486QB1sMw9Vt0sCY/ "Ruby – Try It Online")
] |
[Question]
[
Your challenge is to turn input text to brain-flak code that will output the text.
# Tutorial taken from [here](https://github.com/DJMcMayhem/Brain-Flak/blob/master/README.md) with permission [here](https://chat.stackexchange.com/transcript/message/42965636#42965636)
Brain-Flak has two stacks, known as 'left' and 'right'. The active stack starts at left. If an empty stack is popped, it will return 0. That's it. No other variables. When the program starts, each command line argument is pushed on to the active stack.
The only valid characters in a Brain-Flak program are `()[]{}<>`, and they must always be balanced. There are two types of functions: *Nilads* and *Monads*. A *nilad* is a function that takes 0 arguments. Here are all of the nilads:
* `()` Evaluates to one.
* `[]` Evaluates to the height of the current stack.
* `{}` Pop the active stack. Evaluates to the popped value.
* `<>` Toggle the active stack. Evaluates to zero.
These are concatenated together when they are evaluated. So if we had a '3' on top of the active stack, this snippet:
```
()(){}
```
would evaluate to `1 + 1 + active.pop()` which would evaluate to 5.
The monads take one argument, a chunk of Brain-Flak code. Here are all of the monads:
* `(n)` Push 'n' on the active stack.
* `[n]` Evaluates to negative 'n'
* `{foo}` While zero is not on the top of the stack, do foo.
* `<foo>` Execute foo, but evaluate it as 0.
These functions will also return the value inside of them, so
```
(()()())
```
Will push 3 but
```
((()()()))
```
Will push 3 *twice*.
The `{}` will evaluate to the sum of all runs. So if we had '3' and '4' on the top of the stack:
```
{{}}
```
would evaluate as 7.
When the program is done executing, each value left on the active stack is printed, with a newline between. Values on the other stack are ignored.
# Rules
* You may assume that the Brain-Flak is being run with ascii out. (`-A`)
* The brain-flak code must NOT require input
* All standard rules apply
* The code must run within 1 minute for any input up to 1024 bytes on TIO. (If no TIO output is available supply an interpreter and I will run it on my machine (my machine should be able to come close to TIO)).
* You must support arbitrary length input.
* You may take input from a file.
* Optimization for test cases is not allowed
* Deterministic output is required
* Programs don't need to be stack clean
## Test cases (try your code on these, actual scoring texts will be released in 1-2 weeks after challenge is posted)
```
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
The meaning of brain-flak is to flak your brain with pain.
`1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?
To be, or not to be, that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles
And by opposing end them. To die-to sleep,
No more; and by a sleep to say we die
<your brain-flak code here>
The fitness pacer test is a multi stage test. Avacado Avacado Avacadad Avacadad carrot.bat carrot.jar carrot.carrot Quack Quack Quack Quack Quack Quack Quack Quack Quack downgoat doawngoat down down gaot
This challenge came from a online program that turned text into brain-fuck. However brain-fuck has limitations and it is not nearly as cool as brain-flak. I really am looking forward to cool programs :) I am glad you took the time to read this and look forward to seeing your answer.
```
# Winning
To win you must give the total length of the brain-flak code given by each of the test cases which will be released 1-2 weeks after the post date. The shortest total length wins.
# NOTE!!!!!!:
This is not [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), length of your code will not effect your final score in any way. Making clean readable code is appreciated. Thanks!
# Test cases
[here](https://gist.github.com/Cis112233/d403c04900899db16e2aadf132c8adfb)
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 130 bytes
```
{({}<>)<>}<>{((((()()()()()){}){}){}<>)<>{(((((()()()()()){}){}){}<>)())<>({}[()])}<>((((()()()()()){}){}){}())<>{}}<>{({}<>)<>}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1qjutbGTtPGDkhWa4CAJgxqVtdCEFgeIoldFsizsQMaFK2hGasJFMChEqysuhZsE8LW//9tKvNLixSS4K5SSM5PSVXISC1KtfuvmwwA "Brain-Flak – Try It Online")
# Output for `<your brain-flak code here>`: 5045 bytes
```
(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())
```
[Try it online!](https://tio.run/##7dZBCgAQEEbhvZOYhUOhlMjC/et3CqnxcoDp6zWTsnNfqc08pBjt3bOn07FQjDr0RYKP/aPwv1voS3ZT4/sSe9RxeVDyB6A2Vnw@zBYkpXoA "Brain-Flak – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 17744 bytes
Edit: I've added a couple of options to help golf in stack safe situations.
```
import sys
sys.setrecursionlimit(1000000)
import time
def copy(n, code):
if n == 1: return code
for x in range(2, n):
if n%x == 0: return '('*(x-1) + copy(n//x, code) + ')'*(x-1) + '{}'*(x-1)
return '('*(n-1) + code + ')'*(n-1) + '{}'*(n-1)
letterCache = {}
def letterGen(n, stackLen, prev=0, enclosed=0):
if (n, stackLen, prev, enclosed) in letterCache: return letterCache[(n, stackLen, prev, enclosed)]
if n == 0: return ''
if n == 1: return '()'
if n == stackLen: return '[]'
f = []
if n < 0:
f.append('[%s]'%letterGen(-n, stackLen, prev, enclosed))
else:
if prev != 0:
diff = n-prev
#Saves ~200 bytes but 20x longer
#for x in range(min(diff, 0)-stackLen, max(diff, 0)+stackLen+1):
#f.append(letterGen(x, stackLen - enclosed) + 's' + letterGen(diff - x, stackLen))
f.append('s' + letterGen(diff, stackLen))
f.append(letterGen(diff, stackLen - enclosed) + 's')
x = 2
while x*x < n:
f.append(copy(x, letterGen(n//x, stackLen, prev, enclosed)) + letterGen(n%x, stackLen, prev, enclosed))
x += 1
f.append(letterGen(n-1, stackLen, prev, enclosed)+'()')
if abs(n-stackLen) < n and stackLen > 1: f.append(letterGen(n-stackLen, stackLen, prev, enclosed) + '[]')
letterCache[(n, stackLen, prev, enclosed)] = min(f, key=len)
return letterCache[(n, stackLen, prev, enclosed)]
def s2BrainFlak(c, checkReverse = True):
g = []
c = c[::-1]
stack = []
out = []
enclosed = 0
if checkReverse:
g.append(''.join(out) + s2BrainFlak(c, False) + '{({}<>)<>}<>')
#for x in range(1,11): g.append(s2BrainFlak(list(c)+[chr(0)]*x, False) + '{({}<>)<>}<>')
#if c and c[0] == chr(0):
# out.append('<>')
# while c[0] == chr(0):
# stack.append(0)
# out[0] = '(' + out[0] + ')'
# c = c[1:]
for letter in range(len(c)):
char = ord(c[letter])
x = '(%s)'%letterGen(char, len(stack), stack[-1] if stack else 0, enclosed)
if 's' in x:
out[-1] = x.replace('s', out[-1])
enclosed += 1
else:
out.append(x)
enclosed = 1
if checkReverse and c[letter+1:]:
g.append(''.join(out) + '<>' + s2BrainFlak(c[letter+1:], False) + '{({}<>)<>}<>')
m = min(list(map(ord, c[letter+1:])))-1
#for i in range(1,m): g.append(''.join(out) + '<>' + s2BrainFlak(list(map(lambda x: chr(ord(x)-i), c[letter+1:])), False) + "{({}%s<>)<>}<>"%letterGen(i, 0))
g.append(''.join(out) + '<>' + s2BrainFlak(list(map(lambda x: chr(ord(x)-m), c[letter+1:])), False) + "{({}%s<>)<>}<>"%letterGen(m, 0))
#for x in range(1,11): g.append(''.join(out) + s2BrainFlak(list(c)+[chr(0)]*x, False) + '{({}<>)<>}<>')
stack.append(char)
g.append(''.join(out))
return min(g, key=len)
```
[Try it online!](https://tio.run/##7Vj3f9vGFf90V2w/3XteSJEEuERSIGWzoutEiUQ7TpvEShctpyB5JGFhMABokXGdZu@9d5q9996fz90f5r53AAiIlmS76Y@hRBC4e@/d9817h8HY7Vvm/AmtZ1o2Peiq7fUG1Xp9l9TJsqo7NOZoZk/3ZoKxE5oxsGyXOGMnBt@CQ12btoe2o1mmrhmaK5WK4iPHfEpXM2gs1qFd0rYGY8nMwW@HyrXYjNYlJqnXSalGbOoObVPMxGa6lk1GRDOJrZo9KpVzxERyQZ8cIUdxwpGW0hlplC/JJOvLn5sb@UvAUFoOp9PHjvsPsZkotxlwd2jAYUY58CEW06nrUntJbfcp2OLYcaGRN7hCTVTLQTsdoHA3sOnRejFHqNnWLYd26kVf3ZNMXSOgV8AIcovwGHB5j8B1svBQtIx2imCbGCYy1txRwFroiIhZ01u5Jy3JkfFAYjjdXIPpLuBuBkIXQSao1C2ogwE1O1K6mXTW0snQbvmdoIGjKMSc73ucJGfVPYkzHa2LK5l5HMaBxEH1KHXIFeVikbTGLty2hi4pF0dEtyCMbEEzFVqGZkooKEeKcj6EYaijyXA2GM6WRBCikECbUI1RqAXJR5wDMeSk4RpSCtx5EmEANVFuaKMtODZRR4m3IzsZBfJB8pAy/G70NZ2SUWYEDjJrmwSKJAJ0kdAWGbW9kzaBhQTd2aEIIgtBFdtSCci1HdizGICyFw1qywHqiVVQEaKandAAezBwt1wilL99VmVFNMNap59HYFuMJ3DCOh3XdQA1qTNnkIyirjjlc2xVM5d1dV1qQzXr0/b6xfQotR0sPqv2UNTPqeFNj2gK04I6HZbw2EzPT802UjdrtXwJHhy/vOOENXT9u01FSCRzVDyGTG8Sr@nCEQsUB2a02xR2sWt4xVQ6dnxxj7y4B67Ci9PZWMqVIMfIRHBUkq45rtSWs81235aK8lpmtJPoBOIVNmg3i2tYrDw2wJ1AJSfQocAjuZ8QWxB75gnoi4IYJQhK3D9gef9R7B1i3rNvqQbe9HYzz/@hphAcoIyoJ@2@agO5ZUPqNT26tSBV01LSkaPVEokxNU1JwJL9SGqCIwmo7LkSSyaJ7D6ivMAs1hVAMBL5jpiRq05GBZsOdLVNsfDkiD8hMnUSBH7CBsU4asLRZkqPcCpcfE94emTBLkLIdgGUBh9Ox1GEd8eQmjH8LBTxYqgDCQyb27S2LMv50mQz0KLhZ0Sj79SoJmvoqtHqqGBZETnoypGc1@TpdSPI44g86QTY4xEfa7jryGdooJ2hGP8jFGMC5VSpukMNOLPM3ZxvGO8wuOUyYXVFf/fCqnsC9n53SXWgA4BaZsfj8a989Wtf/8Y3v/Xtmdh3vhv73vd/8MMf/fgnP/3Zz3/xy1/9@je//d3vyVnxxGwyBZtLJpvLF@aKpfK8Uqku7Npd@8Nifc8f9559ztK55y2vNPbtP//ABX/684UXXXxw9ZK//PVvf/9H89Da4Uv/qbbaULV7fe3Ium6Y1uAy23GHRzdG48uP/ev4Ff9mV7Kr2NXsGnYtu45dz25gN7Kb2M3sFnYru43dzu5gd7K72N3sHnYvu4/dzx5gD7KH2MPsEfYoe4w9zp4g7En2FHuaPcOeZc@x59kL7EX2EnuZvcJeZa@x19kb7E32FnubvcPeZe@x99kH7EP2EfuYfcI@ZZ@xz/mV/Cp@Nb@GX8uv49fzG/iN/CZ@M7@F38pv47fzO/id/C5@N7@H38vv4/fzB/iD/CH@MH@EP8of44/zJ/h/@JP8Kf40f4Y/y5/jz/MX@Iv8Jf4yf4W/yl/jr/M3@Jv8Lf42f4e/y9/j7/MP@If8I/4x/4R/yj/jn4MDcjG4rELnfNlQgwrVsq0Nk3StETkyNAZQNSwoE8SFeV29fEw6Vi/g2d7y288EvBeo67D5kQ1IAuf0rwWCvYJDHEqxpA6oNcCdQQW8Wm9oQy0jG@qYuBZx@nC8gUYDcEOJM@nIBTKMuppM5IkCLdxT8QxExtaQdGhb64DCwN6xgFNzctDJfHGSYLmL0L76mNhDk2xobp8YNEc2BH7sBnxqokJLDBOmtUEwPanXOlktdVwIJIkEzmMGE2DogjxYbWBbPVs1BDUCARMM9Q4Zgv6aSww42wTsiqKUlYVMRVlYWKgrSnVOKcFIeX6XUq9WKxWlXIJnJSMdTqaSs8lMKrFXCm3W@KKf/g5T/dMVIuBg@Vge6jpuuj2wJ1QkHW8pWWzruLuR/rC/x7MqGpYsuhAIOKC6ONCzMAbBdC2IHEccRfAXhFgb4MHWWIS9PdQxbi4URlUhyCZsbcuAFtFxwJEQV6f@SFt/wLyzqYSUSc1Kmb2HZ1OZlaXl1N4MaTRSqf5CP5MiK0uplQSMpzKJ5ZVMCr@NS85VSAX@yWGiVCtEqShVoiglFy5V@MvMkTx8s9U8yVcVUiBwU1XmC5l8lST2S3IjsdyQGo3zdhclObG7mJzNJGRpfyMhrcpSA7@ytAzfU0BonL9/hZD5XQvdShXBVKE0d4nSg5svwX0J7v8OrlKdXghKQAxaec0ceIcj77BQgibWtcc1aIoGQX8Ct0NXEu8tRm06cGuw1VF1HXi7SIYvgYSQ9CHT72TgWRZnMBtPXljhC3iRYBDfB0UbKY8UlpkmHNia6UrxQ@Y@XL4Wz3mU3rAZEhwQJQzmxQnClHNx8Z4kHlKsgkScjycLxXI3npRgtbwABx1j3KFty@wgvX8Q2Bb2pB2N4M@RSV8mT1Z0hkakd4UDsQk1LJf23t9gzwmFUvD5W6tDB6qtuhS2OOhFk4UyHHo8VOmkFIHhg8ajz5YgvdXFQSpi4dAtEaiBmbaC41o9CvXbngYT3w6M/04UmuiOZZwRNtE@e3wF/EGaUq5cqcqyQHZppDnH169rm4HjmL@s/3bs9CCfOLufI/tENwR7U1r0PwY0Qxac8Ia6Kxoi6Jyorhf@Cw "Python 3 – Try It Online")
A ~~simple~~ recursive solution which I will continue to improve further. This does *very* well with smaller inputs, but loses out to [MegaTom's Ruby answer](https://codegolf.stackexchange.com/a/157853/76162) for longer inputs.
Notes:
* This needs a clean stack to operate, otherwise the improvements with `[]` become useless (though they can be disabled by commenting out a couple of lines, and they only improve it by ~~about 100 bytes~~ quite a bit).
* ~~Since this is a recursive algorithm, it will take longer for chars with large values. For example, the character ÿ (value 255) takes 9 seconds to evaluate, where every test case at once takes 1.6 seconds.~~ Cache implemented!
* Idea of checking the reverse shamelessly borrowed from [HyperNeutrino's answer](https://codegolf.stackexchange.com/a/157665/76162), saving 800 bytes from the total.
* I changed the total from all test cases at once to the total of each test case. This saves some bytes by adding more uses for the stack length operator (`[]`)
* ~200 bytes from choosing the minimum of prepending the difference between characters, or appending them (again, this saves bytes through the stack length operator)
* Implemented a cache (which caches values based on stack length), which allowed me to check more possible avenues without going over the time limit. This saved 1500 bytes from the total.
+ Also, I switched the em dash in the Shakespeare test case to a normal `-`. This cut out a few bytes, and a *lot* of time given the value of that em dash was 8212 :o .
* Cut out 1200 bytes from the longer test cases by cutting them into slices and checking whether it was shorter to switch to the other stack, construct it in reverse, and push it back to the first stack again. Next up, even more slicing, and saving time by optimising the minimum slicing range.
* Combined the number generating function with the checking for efficiencies with the previous character part into one recursive function. There's a couple of sections in here that save some bytes, but extend the runtime of the program a bit beyond the the one minute limit.
+ Uncommenting those parts can cut it down to 11394 bytes... but takes about 16 minutes.
Example outputs:
### `<your brain-flak code here>` (312 bytes):
```
(()(((((((((()()()){}()){}()){}){})){}())[(()[][]){}])[][])[[]])([]((((([]((()[][][]){})[][]){})(()[]){})[()[][]])[()][]))([()][]([[]]((((([][]){}())){}[])(()()()){})))([()()()][]((((((()()[[][]]([()()()()][]((([][])[]){}()))[])())[((()()[])){}{}])[()()][]){})[()()()]))(([][]){}())((()()()()()[]){}){({}<>)<>}<>
```
[Try it online!](https://tio.run/##TVBBDsJACPwOHPxB08R3EA7Vi8bEg9emb0dmAOvuhrLMMEz39tme78d2f0WIqPyWYut@nAGnckvY3DxvXomZu4o5W/lhnZShKossFOpIgGUnE4FMS5CZszJmevrRYmN7zyNoVBxowDI3UhCiezY45PgHzW9rvOWUPxPzHt2Ht5D9WFZd1owRcbl@AQ)
### `Hello, World!` ([142 bytes](https://codegolf.stackexchange.com/a/157866/76162) [Note: The ~~current~~ previous best was [148 bytes](https://codegolf.stackexchange.com/a/92975/76162), and is now 136 bytes]):
```
((()(((((((((()()()()){}){}){}()))){}{}())([][]){})[][])[[]])[((()[]){}){}])([()[]](((()(()[]([][]((()[][]){}[]))){}[])[()()()])))(([][][]){})
```
[Try it online!](https://tio.run/##PU0xDoBACPtOGXyE7yAMp4vGxMHV3NuR0kQg0DYFtmec9zH2KxOA4Q9T2jtVBUkawMODck/3qMYVie@McpCFDhH2ijztqmYarkfkaJeuZOayfg "Brain-Flak (BrainHack) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 17398 bytes for all (new) test cases
```
# cache for holding shortest push results
$p_cache = {}
# Get code to push a number "a" to the stack,
# given top of stack "b" and stack height "h"
def push a,b=nil,h=0
return $p_cache[[a,b,h]] if $p_cache[[a,b,h]]
arr = []
if b
arr.push "(({})#{add(a-b,h)})"
end
arr.push "(#{add a,h} )"
arr.push "([]#{add a-h,h} )"
i=2
while i*i<=a && i<4
arr.push "#{'('*(i-1)}#{push a/i,b,h}#{')'*(i-2)+'{}'*(i-1)}#{add(a%i,h)})"
i+=1
end
$p_cache[[a,b,h]] = arr.min_by(&:length)
end
$cache = {}
# Get code to add a number "n" to the 3rd stack
# given stack height "h"
def add n,h=0
return $cache[[n,h]] if $cache[[n,h]]
arr = []
if n > 0
arr.push("()"*n)
elsif n == 0
return ""
else
if h > 0
1.upto(-n/h){|i|
arr.push "[#{'[]'*i}]#{add(h*i+n,h)}"
}
end
arr.push "[#{add(-n,h)}]"
return ($cache[[n,h]] = arr.min_by &:length)
end
if h > 0
if n > h
arr.push "[]#{add n-h,h}"
else
arr.push "[]#{add n-h}"
end
end
i=2
while i*i<=n && i<4
arr.push "#{'('*(i-1)}#{add n/i,h}#{')'*(i-1)+'{}'*(i-1)}#{add(n%i,h)}"
x=n-h-i+1
if x > 0
arr.push "#{'('*(i-1)}#{add x/i,h}#{')'*(i-1)}[]#{'{}'*(i-1)}#{add(x%i)}"
end
i+=1
end
$cache[[n,h]] = arr.min_by &:length
end
def push_arr(arr)
i=0
code = push(arr[0]) + "\n" +
arr.each_cons(2).map{|r|
i+=1;push r[1],r[0],i
}.join(?\n)
while code =~ /^\((.*)\)\n(\(*)\{\}/
code.gsub!(/^\((.*)\)\n(\(*)\{\}/, '\2\1')
end
code.split(/\n| /).join
end
# push a string to the stack
def push_string(text)
push_arr text.chars.map(&:ord)
end
$str_cache = {}
# Push a string in reverse order
def push_string_r(text)
return $str_cache[text] if $str_cache[text]
a = [push_string(text)+"{({}<>)<>}<>", push_string(text.reverse)]
min = text.bytes.min-1
a.push push_arr(text.bytes.map{|x|x-min}) + "{({}<>#{add min})<>}<>"
# Try cutting it into bits
3.upto([text.length/20, 10].min)do|x|
spl = x*9
a.push push_string_r(text[spl..-1]) + "<>" +
push_string(text[0...spl]) + "{({}<>)<>}<>"
spl = x*10
a.push push_string_r(text[spl..-1]) + "<>" +
push_string(text[0...spl]) + "{({}<>)<>}<>"
end
a.map!{|code|code.gsub("<><>","")}
$str_cache[text] = a.min_by &:length
end
```
[Try it online!](https://tio.run/##7Vfpd9vGEf/ODz3Tu2nHIEUtIBI8BFK2IypunEis07RO6/QiKRUkIQI2CDA4LNIk09z3fd9p7vu@7/d2/zB3FktSFGnHfq95/RRIAMGd2ZnfzPx2dumF9d7p03Fo6A3TgG3XA9O1m5bTAt90vcDwA@iEvgme4Yd24McSnS2hWoL@EGKxOGwYATTcpgGBK1R1cMJ23fBA0iU@GKC2H@iNEynUhpZ10nBwuAPuthgGqS6B7jRH30zDapkBSKYUaxrbI5Opesmx7JRZysYAsQSh58AYSqWC4pRZq4G1PT@I@rrnIdwKf0WNOn5EY2pkWiKkP5Tjfb3ZJHoap8hDWUIVw2nG9qhFKojEHAJEGlOySm0kTZu7cquUx@eOadkGWIq1WtIhmQRrVZsBEO8vkkWFWOmcPIz3RbwZi6PHr4tyJMrLS4v94a5WhHbBmqBFb0ul3AT2fGpKkcO25WzVeyR50DacVmDKMa4eiyV2Szpb0SiqSUGdSUGXvVG9dms6Wz5kBy8gt@DMVG4EzplUbXpgrmIOrEF2T9KIRGRJcWQesO1HKqXSSGfkQ5KE0BDZ2QZzYgUgp4adwCVpJ2PK/YE1GA1PV6WCua/UFhVrKGpLTMVacnjCpZH2MPoUCZ@ZyfXTkXJNmgZF9kY@XRTYLcrYaGwG9ygVZmwO64h@TkQ/4XES@lkUx2qRp11/s5x1zoezkUmk7BRhc2cgrCMIKxx3SwgibS3lxqF1p@rzTY66s46GPKo5Z90FS94T4@wSOXclxOoYN6Et1CB4y1GaONJojZQiIRdUsjUZlkCq4ipZglGDMNDLVsN1fJKX1bbe6Q@8wQTMRaK1VnK1FJ@dslAyVI@7lkMurkbsnhRD@LoGMptVQlRFrspVh1QJvvSrw0xkkauoLT@s7yNn1krBYjVfzS3uYVg0y@/YVkAyVWcAGTkCIGKPjzu6H3h8T5ju5ruJEUISGN2Amx4nC/iA2jB1z@eRY9dxveao5SRwztRGgo6O7nFkObhkThqebwBOMrxZZ1vexN24p0wsVrhEtJWZMV4T3lfmUC9JfdwFVtfk1TV8Sqm5uNQRGrkmsoZMQUORpN7DXZJTJ83JpQveTggzrcKr3x1006g7jJginApaR4PCfQztxOGY14NGGARROgLMCCa/buEWDLAs2lcUlCq4mslnU5DL1jgQuemin4gTWFjE2VUOiPU7BW5PHiuop6rpnCAwQhAE5tdsJipZVeV8qU1FMMY97TGX/T@5nDBZ5xne1x9wRg8mi4GgbV5SSZKHPLFzPCnxifML/zQ/@6Cib/icMjHpe9//wQ9/9OMLfvLTn/38F7/81a8v/M1vYV9ViicWkotEVpZSaTWTzeWXtUJxZf@BgxetltYuPvS7Sw5fetn6Rvn3Ry7/wxV//NPRK//8l2NX/fVvf//HPyvVam1z6196vYHMbpnW8RN223E7V3t@EJ7c6fZO9QfDa/5Nr6XX0evpDfRGehO9md5Cb6W30dvpHfROehe9m95D76X30fvpA/RB@hB9mD5CH6WP0cfpE/RJ@hR9mj4D9Fn6HH2evkBfpC/Rl@kr9FX6Gn2dvkHfpG/Rt@k79F36Hn2ffkA/pB/Rj@kn9FP6Gf2cfkG/pF/Rr9m17Dp2PbuB3chuYjezW9it7DZ2O7uD3cnuYneze9i97D52P3uAPcgeYg@zR9ij7DH2OHuCPcmeYk@zZ9h/2LPsOfY8e4G9yF5iL7NX2KvsNfY6e4O9yd5ib7N32LvsPfY@@4B9yD5iH7NP2KfsM/Y5@4J9yb5iX0spPJxIx7BJXB1aeLaoe@6Og4fULhwP2x2jCS4uyqgj2fqpHjTdlphx9rSfXSJmXqGf4OttB5uOf/5PFYhtBD74hsHbTsdwO7xl64jVaoWegV1nR@/x7ikO1Q7HjK3NQQKCoNhBGQ@NAnzdDQMIrLYBPTeEptGwmhgqTm7y7mv5KdC/BRXh7EqeV7sHXujAjhWY0DZSsBNhd9xgrAu67ToocNwdsC2fB8DP625d76nCziWejg1w3dZPAKpvh070a8BzW57ejnQ5CAw@tJsQYuTY0NquZ4jJmqbltRWloK2srJQ0rZjRcjiSX96vlYrFQkHL5/C7ppDNheRCYkFJxg@Rca7K/@tlfoPIPF8jAsx6aNsgGgjgrmfzVwNWGzbfOsAMzTWRTJ5PWOXNhw/oAR9ouaPttY5k8QHT3eKfaMTdwbJhb@Is90KbU@VolE0deTWZ1nDbHfyJ5mP9kErnvsiZL8xsIhknSjJBlEObiaSycXg9eUiBcjmZNFdMJQkbh5MbcRxPKvH1DSXJ7/JVl2pQwH/YBK1YAK2gFUHTcgE@ivinZCCN91IxDemiBirgS1FbVpV0EeJHiFyOr5dJuXzZgSyR4weyCwklLpMj5Tg5JpMyv2Wyjvc5IJQvP7KBO@P@le1CkYMpYiPeBq2FL9@B@w7ctw6uUJxxJMVqsU6Iu8DuwYEfXNL5mjj5NQbQIXvPQQ1ZVn3rlDFU/bAdi3f2HpOmDEVH8tP/BQ "Ruby – Try It Online")
---
## `<your brain-flak code here>`, ~~362~~ 358 bytes
```
((((((((((()()()){}()){}()){}){})){}())[[][][][][]])[][])[()()()])((((((((([][][]()){}))){}{}()())[][]()())[[][]()])[][()])()()()()())([][][][]())(((([]([]())[]{}){})(()()()){})[[][()()()]])([]([][][]()){})((([][])[]){}())([]([][]())[]{})((([][]()())[]{})())((((((()()()()())[]{})[][()()]){})[()()()])((()()()){}){}())([][][][]())(((()())[]{}){}){({}<>)<>}<>
```
[Try it online!](https://tio.run/##VU9JCsMwDPyO55AfhEDeYXRID4XSkEOvJm9Xrc1yLCMLjWY0fv2Oz7W8z@PLXPJAAu3OJNfqWimCIBnV5gmDb7ARJQlRqNoMDWH0V4kjUEJcapUqWlcyE2lOVXw1wQZzrbvoPLMdeEg57r6kAcy/T8C3kK6cvjp8hP7DNybPrbR73bBuPTPzsv8B "Brain-Flak – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 16222 bytes
```
cache = {}
def generate_number(num, height, level = 0, output = False): # Idea to use Stack Height inspired by Jo King
if output: print(" " * level + str(num) + " " + str(height))
if (num, height) in cache: return cache[(num, height)]
if num == 0: return ""
if num < 0: return "[" + generate_number(-num, height, level + 1, output) + "]"
if num == height: return "[]"
value = min((["[]" + generate_number(num - height, height, level + 1, output)] if height > num * 2 and abs(num - height) < num else []) + ["()" + generate_number(num - 1, height, level + 1, output)] + ["(%s)%s{}" % (generate_number(num // i, height, level + 1, output), "({})" * (i - 2)) for i in range(2, num) if num % i == 0], key = len)
cache[(num, height)] = value
return value
generate_number(256, 0, 0, False)
def generate_string(array):
string = ""
last = 0
for height, num in enumerate(array):
string = min("(" + string + generate_number(num - last, height) + ")", "<" + string + ">" + "(" + generate_number(num, height) + ")", key = len)
last = num
return string
a = lambda s: generate_string(list(map(ord, s)))
i = sys.stdin.read()
j = i[::-1]
print(min(a(j), a(i) + "{({}<>)<>}<>", key = len))
```
[Try it online!](https://tio.run/##fVTbjuIwDH0mX2F1hZTMlBlgtftQMTyu9vK4j6gaBWogQ5tWSTpShfh21knLdYGKXuLYPvbxCVXj1qX@uldFVRoHtrGM7heLzuCiNlaVOleFcnw0DJfYL@RijfAG2x1jGS5hhRqNdPiu62KOhtMrhjWq1drFkOMn5uQ8jKGsXVU7@v4hc4sigS/wK0MJroTaIvx1crGBnyEOlLaVMpjBvIHfJfxResV6atnlSKAySjseQQRPHcQzWBewBX36jdbQ1iFEiD4vTRAGhFYSMOhq061mF05piCMLvFEPR88oOton5@aZh73mY3CDkGcYHQgJ9abROVDre5bWb3/KvPa0F0pzPvO2G1g@weCIdR8zBUJrt2EaYJ9gDFJnIOf2IougDv0aaWYwS321s4iL@@Cjx7ghvG9F3253EfSB38ry@grqUZoYIr7dCT99rghzLAQsSwPKD9VIvUI@jiGIoWO1T3t@hGkMG2yIxhw1ieLWyGkzcM16Hf/til0XOv72Pfa6pl@r6KvjQPIj2XJpjGxEwnrtmrJ79eTS@qMwZD1f96FTXyl1gPQOOU7Bp2g//4h3@vame4PwECe1k8hERLxNLiKjqV@26R6c42P4OXeHHsjvSFWbmDHpvWQxzyTY5D9KcmUdL2TFS5PFYAUdT0bjgfDH4zKlXwzKjAv2QUY1S5LBKGWsPfO@fck/SAKSq1DXlqQwmYrJlJ4XJYr9ftKUtYG5kUoPlrncwKLMkJoyOP0H "Python 3 – Try It Online")
First below 1000 for `<your brain-flak code here>` :D
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 448 bytes
```
<((((((<(((<((((<((((<((((((()(()(()(()()()){}){}){}){})(()((()()[]){}){})({}){})()((()[]){}){})[()(([]){}){}])()()())>((()([])({}){}){})()((()(()()[]){}){}){})[()])()()()[])[()()()[]])>(()()([])({}){})(()(()[]){})({}){})[(()()()()()){}])()(()()()()()){})[(()()()){}])>(([])({}){})()(([]){}){})[()()()()()])[(()()()()){}])>((([])({}){}){})[((()()()()){}){}])[(()[])({}){}])()(()()()()()[])({}){})()()())[(()()()){}])(()()()()()){})>((()()()()[]){})
```
[Try it online!](https://tio.run/##XVBLDkIxCLwOLN4NXpp4jqaL58LEaFy4NZ4dC3QeYOl3ygzTXt/H/bXdnsdDZCdr@xppmo2jz@DPN7rBivYBZC2Gn2jXM06Dl1Iz7oQpBBkFg@x8sCbcsRsqwUXD2c4lkIkRKF@QM8NuG2W55Bt1NUZSBau@pFNOsJzuzih@IQRLSeUUT39@W2i7ORHZLj8 "Brain-Flak – Try It Online")
(originally 827 for `<your brain-flak code here>`)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), too many bytes (My first BF anything)
```
ÇεDÑDg;<èUX÷VX"()"×"(ÿ)"YX-"()"׫"(ÿ)"}»"{({}<>)({<({}[()])><>({})<>}{}<><{}><>)<>}<>"«
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cPu5rS6HJ7qkW9scXhEacXh7WISShqbS4elKGof3aypFRuhCuIdWQwRqD@1WqtaorrWx09SotgEyojU0YzXtbOyATE0bu1qQjE11LVAAxLOxUzq0@v9/m8r80iKFpKLEzDzdtJzEbIXk/JRUhYzUolQ7AA "05AB1E – Try It Online")
---
Extremely basic attempt at golfing using a the premade "multiplication" Brain-flak code. All this does is finds the smallest-sum divisor pair for each ASCII code point, then pushes both of those divisors pairs as numbers. The Brainflak code `({}<>)({<({}[()])><>({})<>}{}<><{}>)` is then appended and executed in a loop until all values are on the alternate stack.
---
List of people I'm thanking:
* DJMcMayhem for pointing out `(()())(()()())` = `((()())())` (`-252 bytes`)
* DJMcMayhem for showing me how loops should work (`-927 bytes`).
---
Example golf of `<your brain-flak code here>` at ~~3470~~ ~~3218~~ 2291 bytes:
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 2291 bytes
```
((()()()()()())()()()())
((())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())
((()()())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())
((()()()()()()()()())()()()())
((()()()()()())()()()()()()()()()()()()())
((()()()())()()()())
((()()()()()()())()()()()()()())
((()()()()()())()()()()()()()()()()()()())
((())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())
((()()()()()()())()()()()()()()())
((()()()()()()()()()())())
((()()()()())()()()())
((()()()()()())()()()()()()()()()()())
((()()()()()()()()())()()())
((())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())
((())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())
((()()()())()()()())
((()()()()()()()()())()())
((()()())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())
((()()()()())()()()()()()()()()()()()()()())
((())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())
((()()()())()()()())
((()()()()()()()())()()()()())
((())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())
((()()()()()())()()()()()()()()()()()()())
((())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())
((()())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()){({}<>)({<({}[()])><>({})<>}{}<><{}><>)<>}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDQxMBEQwukISmxgiDEG@jhAR1jMMTyFgk8JuEx3gC9hO0YBhFIE4/Y48UsEJUKVKDEW9sD6vwHeZ5H28Wg0vTtKwYWdFAdNCPjCAYGUU1us8pMaJao7rWxk5To9oGyIjW0IzVtLOxAzI1bexqQTI21bVAARDPxo7r////uo4A "Brain-Flak – Try It Online")
---
Each row represents one character being golfed, [this beats the basic solution I posted by 60%](https://tio.run/##MzBNTDJM/f//cPu5rUoamkqHpytpHN6vqVQb5PX/f2JSMgA), and going in knowing literally nothing about Brainflak I feel this is a good baseline of what not to do. I'll score the answer in a little while, in the middle of something else and I'm sure I can improve on this. (I'm including the newlines in the byte-count because I don't expect this to win).
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack)
```
For each character (main loop)
(([])<{({}[()]<
Get the difference between the top two characters
(({}<>)<>[({})]<><({}<>)>)
Push an open paren on the other stack
<>(((((()()){}()){}){}){})
Retrieve difference
(<>{}<>)
Greater than zero
([(({})[(())])](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}
If
{{}
While non-zero
({
Add value if not 1
<(({})[()])>{()(<{}>)}{}
<
Divmod 2
({}(())(<()>)){({}[()]<({}([{}]()))>)}{}({}[({})])
Hold the div
({}<
Push the mod part
{({}[()]<
((((((()()){}()){}){}){})())
>)}{}
Put div down
>)
Open paren if div non-zero
(({}))
{(<({}<{}
(((((()()){}()){}){}){})
>)>)}{}
Less than 4
([([({})[()()()()](())])](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}
If
{{}
Make that many 1s
{({}[()]<
((((((()()){}()){}){}){})())
>)}{}
End if
((<()>))}{}
End loop puting number of times run on the stack
>}{})
For each close push and pop
{({}[()]<
((((()()()()()){}){}){}())(((((((()()()()()){}){}){}())){}{})()())
>)}{}
End if
((<()>))}{}
Less than zero
([([({})(())])](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}
If
{{}
([{}]<
Push open bracket
((((((()()){}()){}()){}){}()){}())
>)
While non-zero
({
Add value if not 1
<(({})[()])>{()(<{}>)}{}
<
Divmod 2
({}(())(<()>)){({}[()]<({}([{}]()))>)}{}({}[({})])
Hold the div
({}<
Push the mod part
{({}[()]<
((((((()()){}()){}){}){})())
>)}{}
Put div down
>)
Open paren if div non-zero
(({}))
{(<({}<{}
(((((()()){}()){}){}){})
>)>)}{}
Less than 4
([([({})[()()()()](())])](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}
If
{{}
Make that many 1s
{({}[()]<
((((((()()){}()){}){}){})())
>)}{}
End if
((<()>))}{}
End loop puting number of times run on the stack
>}{})
For each close push and pop
{({}[()]<
((((()()()()()){}){}){}())(((((((()()()()()){}){}){}())){}{})()())
>)}{}
Push close bracket
((((((()()){}()){}()){}()){}){}())
Endif
((<()>))}{}{}
Remove top character
<>{}
End of main loop
>)}{}{}
Close the open parens
<>>){({}[()]<(((((()()){}()){}){}){}())>)}{}
Reverse code
([]){({}[()]<({}<>)<>>)}{}<>
```
[Try it online!](https://tio.run/##7VVNb5wwEL37V4xysg85pOrRshT1W2rVaC89IA7sYgpasJExu0otfjudMV@bNlHUXHrJsjJg4zdv3jxr9i6rTJkdjuP40TrQ2aGEQ5m57OC1A97gKtTWtoJxnqRCBh6GhItUMvZJe/ClhrwqCu20OWjYa3/W2sRpb1vwZ7uhdQgRBqmEVAk@IIaS04QSjN31XQmZAdvi/jZDPLATkMXBQeeRJJOKx5/gQoQhDvOfsZ32rtKnS0KMSxUjIFunM0rJlxjkl3aW8YT4CByFSEWKnyIcj6hSDWEInMswKHoLw0AwYWDsS8EC3X@UVa3BWHM9gQXGbvMcTlnda6gKXPFww@QcAgOogKwj4ED7UcD31amxObxhFBSjcsnFzCFKTNNJGFJcEnFXXCDlMJ/Pts5n@U8EIGcJaYpQUULPtmrxp3TDZzZTuus9oUFuz4aRZt@3WmBGtLTlSzwEBoglxN1P1kWJGf6r7rpJ/rekfTIrM13py6rwLTtqwvTQZOYebrp/TPmDyTE1/HSSfp0jy0Pb@8r8BNM3ezSOLcBXje7A9as1J1MSTVRrOz@17TTujobGStj2T1ZiuVZSVP6N8N@LOEbmz3DfNF4sHmV@mbjRfIuv4rnc40k@av@ItAvb5YVFA70ektdD8n8PSSz3FOsZ8144OKb3MGPC2unGnqbGtjY1NklNcmDua7ucwtPKuxg79rHVKB3uUhcWfrwEXCym2GFXc4hysDm2NGzDl@6PDTV@KBUbx/H6dryS97Z3lHBlros6O8adgG1Uq6vf "Brain-Flak (BrainHack) – Try It Online")
## Output for `<your brain-flak code here>`, 582 bytes:
```
([()((()(()(()()()){}){}){}){}]((()(()()){}){}([(()()()){}](()(()){}((()(((()(()()){}){}){}){}){}([(()((((()()){}){}){}){}){}]([(((()()){}){}){}](()(((()()){}){}){}([((()()){}){}]([()(()()){}](()(((((()()){}){}){}){}){}([()(((()(()()()){}){}){}){}]([(()()()){}](()(()(()()){}){}([(()(()()){}){}](()(()((()((()()){}){}){}){}){}([()(()((((()()){}){}){}){}){}]([((()()()){}){}](()(()(()()){}){}([()](()((()(((()()){}){}){}){}){}([(((()((()()){}){}){}){}){}](()(()){}([()((()()()){}){}](()((()()()){}){}(()(()(()((()()){}){}){}){}((()(()(()(()()()){}){}){}){})))))))))))))))))))))))))))
```
] |
[Question]
[
Your program / function, etc. will take 2 inputs. The first will be a list of who came to my party and when. Example:
```
Kevin 13:02
Ruby 5
Sam 3
Lisa 6
Bob 12
```
What does that mean? It means that Kevin got to my party first (at 13:02, 24-hour time), then Ruby 5 minutes later, then Sam 3 minutes later, then Lisa 6 minutes later, and last Bob 12 minutes later.
The second input will be when my party started. Example:
```
13:15
```
(24-hour time). Your output must be the list of people who *were late.* (Anyone exactly on time is fine.) Example calculations (just for example, don't output these)
```
Kevin 13:02
Ruby 13:07
Sam 13:10
Lisa 13:16
Bob 13:28
```
Lisa and Bob arrived after `13:15`, therefore this program should print "Lisa,Bob".
# Input assumptions
* Input 1 will always be a name (regex `[A-Z][a-z]*`), then a space, then a 24-hour time in the form `hours:minutes` on the first line, then a name, a space, and a positive integer (number of minutes later) on the next lines. There will always be at least 1 line.
* If you would like, you may take input 1 with any other character instead of a line break.
* Input 2 will be in the format `hours:minutes`.
* You may take your inputs as one string separated by any character if you want. This is optional.
* Don't worry about day crossover. My parties never to after `23:59`.
# Output rules
* Output can be a function return value or a string echoed to STDIN, a file, etc. You must return a string or an array / list.
+ If you return a string, it must be each person who was late (order does not matter), separated by any non-alphanumeric delimiter.
+ If you return an array / list, it must be a list of everyone who was late.
[Answer]
## JavaScript (ES6), ~~98~~ 97 bytes
*Saved 1 byte thanks to Neil*
Takes the list of guests `l` and the party time `h` in currying syntax `(l)(h)`. Expects a trailing linebreak on the list. Returns a space-separated list of names such as `Lisa Bob`.
```
l=>h=>l.replace(/(.* )(.*)\n/g,(_,a,b)=>(t-=T(b))<0?a:'',t=(T=h=>eval(h.replace(/:/,'*60+')))(h))
```
### Formatted and commented
```
l => h => // given a list of guests l and a party time h
l.replace( // for each guest in l:
/(.* )(.*)\n/g, // extract the name a and arrival time b
(_, a, b) => // subtract the arrival time from the time counter
(t -= T(b)) < 0 ? // if the result is negative:
a // the guest is late: keep the name
: // else:
'', // the guest is on time: remove this entry
t = ( // initialize the time counter t
T = h => // define T():
eval( // a function that takes either a time
h.replace(/:/, '*60+') // in hh:mm format or an amount of minutes
) // and returns an amount of minutes
)(h) // call it with the party time
) // end of replace()
```
### Demo
```
let f =
l=>h=>l.replace(/(.* )(.*)\n/g,(_,a,b)=>(t-=T(b))<0?a:'',t=(T=h=>eval(h.replace(/:/,'*60+')))(h))
console.log(f(`Kevin 13:02
Ruby 5
Sam 3
Lisa 6
Bob 12
`)('13:15'))
```
[Answer]
# PHP, ~~118 98 95~~ 91 bytes
```
while($n=$argv[++$i])$i&1?$p=$n:($t=($f=strtotime)($n)?:$t+60*$n)<=$f(end($argv))?:print$p;
```
takes input from command line arguments (you may interprete that as lines separated by spaces if you like); prints names without a delimiter. Run with `-r` or [test it online](http://sandbox.onlinephpfunctions.com/code/f8464741bbd58e5c785df0d1c8eaf4e31a2cd06b).
edit 1: saved 20 bytes with direct printing
edit 2: saved 3 bytes by removing the delimiter
edit 3: saved 4 bytes by exploiting that plain integers are no valid dates for `strtotime`
**breakdown**
```
while($n=$argv[++$i]) # loop through arguments, skip [0]
$i&1 # if index is odd
? $p=$n # then assign name to $p
: ($t= # else $t =
($f=strtotime)($n) # if $n is a valid time, parse it
?:$t+60*$n # else add $n minutes to current $t
)<=$f(end($argv)) # if $t <= parsed party start
? # then do nothing
:print$p; # else print name
```
[Answer]
## c, 178 bytes
```
main(c,o,d,e,g,O,l,f,x,y)char**o,d[80],*O,*l,*f;{for(sscanf(o[2],"%d:%d",&e,&g),x=e*60+g,l=";",f=o[1];O=strtok(f,l);f=0)(y=sscanf(O,"%s%d:%d",d,&e,&g)^2?e*60+g:y+e)>x?puts(d):0;}
```
[Try it online](https://tio.run/nexus/c-gcc#Tc5Ba4MwGMbx@z5FsLQk6cuIlpZhmhZ23UDYjuIgNYkNs0kxOpSxz@4C87Drn4cfz8q6uh2URsfQd9Y1j9fTw@pfU9bHNN@kdbgGDwo0NFBACwZGmEh9lR2lsZdPrAJaAG2BGv5tfIdDqKUz2JdZBcla5WuVwEbDpiEwCk0PbNtAKxKegBG@TCteiHii95/YQEu4EYzgSSxKEYmwIGphPrLzH5NPW01O4/k@9AErkjP@M8/zi/6yDqW7nGX8bbhMaM/f5Q3t@KsNEh34s7@gNJvjIN3/Ag)
[Answer]
# JavaScript ES6, 185 bytes
```
l=>t=>l.split`
`.map(p=>p.split` `).map((p,i,a)=>[p[0],i?d(a[0][1])+a.slice(1,i+1).reduce((a,p)=>a+=+p[1],0)*6e4:(d=x=>Date.parse(`2017T${x}`))(p[1])]).filter(p=>p[1]>d(t)).map(p=>p[0])
```
### Try it online!
```
const f = l=>t=>l.split`
`.map(p=>p.split` `).map((p,i,a)=>[p[0],i?d(a[0][1])+a.slice(1,i+1).reduce((a,p)=>a+=+p[1],0)*6e4:(d=x=>Date.parse(`2017T${x}`))(p[1])]).filter(p=>p[1]>d(t)).map(p=>p[0])
console.log(f('Kevin 13:02\nRuby 5\nSam 3\nLisa 6\nBob 12')('13:15'))
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~215~~ ~~196~~ 180 bytes
```
param($a,$b)$x,[array]$a=$a-split',';$z=@{};$i,$j=-split$x;$z[$i]=($y=date $j);0..($a.count-1)|%{$i,$j=-split$a[$_];$z[$i]=($y=$y|% *es $j)};($z|% *or|?{$_.value-gt(date $b)}).Name
```
[Try it online!](https://tio.run/nexus/powershell#VYxLC4JAFEb/yiBXcmIclGqTDLUPWtRSJK51EcVXPsLnb5@SNrX8zsc5usQKMwtQQMihEz5WFfYBoAK06zKNm5VYeTCo4zh7EAtI1BdD96E@xIGyoFcPbIhBwj1Hyk9M3os2b2yXT@b4J6EPt@BXhH4y2ZrqRZ49C4ZlFtV0GOEmX5i2ZEeN9c2HfObyjBlprY0TveKcuZu9uxWXNuzZTlyfLVFExFzH0MZyOcYb "PowerShell – TIO Nexus")
Roughly 1/3rd of this is input parsing, so I'm not sure how much further I can golf it.
Takes input `$a` as a comma-delimited string of names and times/minutes, and `$b` as `hh:mm` as a string. First, we `-split` `$a` on `,`, store the first result into `$x` and the remaining into `$a`, with an explicit re-cast of `$a` as an `array` (so that the loop later works properly). We the initialize our hashtable `$z`, set `$i` and `$j` to be `$x` `-split` on whitespace, and set `$z[$i]` to be the `date` of `$j` (stored into `$y` for use later).
Then we loop through the remaining `$a`. Each iteration, we do similar -- `-split` the string on whitespace, set the appropriate `$z` index to be that many more minutes beyond where we're currently at. This uses a [shortened property name](https://codegolf.stackexchange.com/a/111526/42963) trick to save some bytes, using `|% *es $j` instead of `.AddMinutes($j)`.
Finally, we `.GetEnumerator()` (again using the trick) of our hashtable, and `Where-Object` select those entries with a `value` that's `-g`reater`t`han `$b` (i.e., they're late to the party). We then select just the `.Name`s thereof. Output is as an implicit array, which the default `Write-Output` inserts newlines between.
*Saved a bunch thanks to briantist for reminding me that [array] is a thing. And a bunch more for shortened property name tip.*
[Answer]
# [Python 2](https://docs.python.org/2/), ~~140,148,~~144 bytes
```
t,h,n=map(str.split,input().replace(':','').split(';')),100,0
for a,v in t[:-1]:
n+=int(v)
if n%h/60:n=n/h*h+n%h%60+h
if`n`>t[-1][0]:print a,
```
[Try it online!](https://tio.run/nexus/python2#JYxBC4IwGEDv/orvEtty2ZZlsGGHrnWqowTOMDbQz6FL6NfbouPj8d4SuOVY9sbTKYzZ5DsXuEP/DpRlY@s782wpUYQTwv6WEk0Y41IILpLXMILhMziEUKmNfKgEMC0dBjqzBNwLcGW3hVBY4taubRpxVYjU/lyN9SlUMarEQ/kxRvG1LOTSzvEnc7U/6tu7@cBB300Pub66yUChz0MDcqflXglBvg "Python 2 – TIO Nexus")
Input Format:
```
'Kevin 13:02;Ruby 5;Sam 3;Lisa 6;Bob 12;13:15'
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 31 bytes
```
jYb1L&)1&)XUYs1440/0whwYO+jYO>)
```
The first input uses space instead of line break (allowed by the challenge).
Output uses line break as separator.
[Try it online!](https://tio.run/nexus/matl#@58VmWToo6ZpqKYZERpZbGhiYqBvUJ5RHumvnRXpb6f5/793allmnoKhsZWBkUJQaVKlgqlCcGKugrGCT2ZxooKZglN@koKhERdQgaEpAA "MATL – TIO Nexus")
### Explanation
```
j % Input first string
Yb % Split at spaces. Gives cell array of strings
1L&) % Separate into subarrays with odd and even indices. Odd are names, even
% are time and increments in minutes
1&) % Separate the subarray of even indices into first entry and remaining
% entries. The first is a string representing the time of first arrival,
% the rest are strings representing increments in minutes
XU % Convert strings representing increments into the actual numbers
Ys % Cumulative sum
1440/ % Divide by 1440 (number of minutes in a day)
0wh % Prepend a 0
w % Swap. Bring the string with time of first arrival to the top
YO % Convert to serial date number. Fractional part indicates time
+ % Add. This gives all arrivals as serial date numbers
j % Input second string
YO % Convert to serial date number
> % Less than?, element-wise
) % Index: select the names for which the comparison gave true
% Implicitly display
```
[Answer]
# Bash, ~~135~~ ~~124~~ 115 bytes
```
a=($1)
for i in `seq 3 2 ${#a[@]}`
do((v+=a[i]))
((`date -d${a[1]} +%s`+v*60>`date -d$2 +%s`))&&echo ${a[i-1]}
done
```
[Try it online!](https://tio.run/nexus/bash#Pc0xC8IwFATg/f2KB9aSWApNSjsIFXHVScdSyKuNmMEGjQak9LfH6OB693EXqGGJ4HCxDzRoRlRO37FEicm0oHbbzQoGy5jPGmpNxzkwpgZ6asyHZKJWdDNmS6cyv6qLzb@Rv5DzNNXnq8WvNHm0cWvUIYS99vFLlOtCwvHVv7GCE92whINxhDXsbI9ChghE9QE "Bash – TIO Nexus")
[Answer]
## CJam, ~~66~~ ~~54~~ ~~58~~ ~~54~~ ~~51~~ ~~49~~ 46 bytes
```
{{':/60b}:K~)rSrKs++q+S/2/z~:i[{1$+}*]2$+$@#>}
```
Input 1 is given through STDIN, input 2 is given as a string on the stack. Output is an array on the stack. Separator for input 1 is a space, e.g. `Kevin 13:02 Ruby 5 Sam 3 Lisa 6 Bob 12`.
### Stack trace:
```
e# Stack: | "13:15"
{ e# Define K and run it:
':/ e# Split on colon: | ["13" "15"]
60b e# From base 60: | 795
}:K~ e# End def
) e# Increment: | 796
r e# Read token: | 796 "Kevin"
S e# Push space: | 796 "Kevin" " "
r e# Read another token: | 796 "Kevin" " " "13:02"
K e# K() | 796 "Kevin" " " 782
s e# Convert to string: | 796 "Kevin" " " "782"
++ e# Add together: | 796 "Kevin 782"
q e# Read rest of input: | 796 "Kevin 782" " Ruby 5 Sam 3 Lisa 6 Bob 12"
+ e# Add together: | 796 "Kevin 782 Ruby 5 Sam 3 Lisa 6 Bob 12"
S/ e# Split on spaces: | 796 ["Kevin" "782" "Ruby" "5" "Sam" "3" "Lisa" "6" "Bob" "12"]
2/ e# Group by 2: | 796 [["Kevin" "782"] ["Ruby" "5"] ["Sam" "3"] ["Lisa" "6"] ["Bob" "12"]]
z e# Transpose: | 796 [["Kevin" "Ruby" "Sam" "Lisa" "Bob"] ["782" "5" "3" "6" "12"]]
~ e# Unpack: | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] ["782" "5" "3" "6" "12"]
:i e# Convert all to int: | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 5 3 6 12]
[{1$+}*] e# Accumulate: | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 787 790 796 808]
2$ e# Copy back element: | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 787 790 796 808] 796
+ e# Add into array: | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 787 790 796 808 796]
$ e# Sort: | 796 ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] [782 787 790 796 796 808]
# e# Find index: | ["Kevin" "Ruby" "Sam" "Lisa" "Bob"] 3
> e# Slice: | ["Lisa" "Bob"]
```
Explanation:
* The procedure `K` converts between a time `hh:mm` and a number representing how many minutes that is since midnight.
* We read the first person and replace their time with K(their time). We then add this to the front of the input.
* We then preform some string operations to get a list of names and a list of times, like `[782 5 3 6 12]`.
* By accumulating this list, we get `[782 787 790 796 808]`, which gives the times that everybody came.
* The shortest way to find who is late is to insert the start time into the array and then re-sort it to place it where it should be. We then find the index to figure out where it places, and then slice the list of names from that index.
[Answer]
# JavaScript, ~~285~~ 283 bytes
Takes the list of guests `i` and the party time `p` in currying syntax `(i)(p)`. Returns a comma-separated list of names such as `Lisa,Bob`.
```
i=>p=>{n=i.split`
`,a=new Date(0,0,0,...n[0].split` `[1].split`:`),y=new Date(0,0,0,...p.split`:`),t=[a];w=a;n.slice(1).map((j,k,l)=>{h=l[k].split` `[1]*6e4;t.push(new Date(w.getTime()+h));w=new Date(w.getTime()+h)});return n.filter((j,k,l)=>t[k]>y).map(j=>j.split` `[0]).join()}
```
I know it's pretty long and currently at last place by a fair margin, but that's what I could come up with.
```
f=i=>p=>{n=i.split`
`,a=new Date(0,0,0,...n[0].split` `[1].split`:`),y=new Date(0,0,0,...p.split`:`),t=[a];w=a;n.slice(1).map((j,k,l)=>{h=l[k].split` `[1]*6e4;t.push(new Date(w.getTime()+h));w=new Date(w.getTime()+h)});return n.filter((j,k,l)=>t[k]>y).map(j=>j.split` `[0]).join()}
console.log(f(`Kevin 13:02
Ruby 5
Sam 3
Lisa 6
Bob 12
`)('13:15'))
```
[Answer]
## [C#](http://csharppad.com/gist/0082641e96018f7113995aea3edd8c10), ~~269~~ 267 bytes
---
### Golfed
```
(l,t)=>{var h=System.DateTime.MinValue;var s=System.DateTime.ParseExact(t,"HH:mm",null);var o="";foreach(var p in l.Split('\n')){var i=p.Split(' ');h=h.Ticks<1?System.DateTime.ParseExact(i[1],"HH:mm",null):h.AddMinutes(int.Parse(i[1]));if(h>s)o+=i[0]+" ";}return o;};
```
---
### Ungolfed
```
( l, t ) => {
var h = System.DateTime.MinValue;
var s = System.DateTime.ParseExact( t, "HH:mm", null );
var o = "";
foreach( var p in l.Split( '\n' ) ) {
var i = p.Split( ' ' );
h = h.Ticks < 1
? System.DateTime.ParseExact( i[ 1 ], "HH:mm", null )
: h.AddMinutes( int.Parse( i[ 1 ] ) );
if( h > s )
o += i[ 0 ] + " ";
}
return o;
};
```
---
### Ungolfed readable
```
( l, t ) => {
// var to check the time of arrival
var h = System.DateTime.MinValue;
// var to store the start time of the party
var s = System.DateTime.ParseExact( t, "HH:mm", null );
// var with the names of those who arrived late
var o = "";
// Cycle through which line
foreach( var p in l.Split( '\n' ) ) {
// Split the name and time
var i = p.Split( ' ' );
// Check if the time of arrival still has the initial value
h = h.Ticks < 1
// If so, grab the time of the first person
// Expects to have a time format of 'hh:mm'
? System.DateTime.ParseExact( i[ 1 ], "HH:mm", null )
// Otherwise, add the difference to the var
: h.AddMinutes( int.Parse( i[ 1 ] ) );
// Check if the current time is later than the party start time
if( h > s )
// If so, add the name to the list
o += i[ 0 ] + " ";
}
// Return the names of the persons who arrived late
return o;
};
```
---
### Full code
```
using System;
using System.Collections.Generic;
namespace Namespace {
class Program {
static void Main( String[] args ) {
Func<String, String, String> f = ( l, t ) => {
var h = System.DateTime.MinValue;
var s = System.DateTime.ParseExact( t, "HH:mm", null );
var o = "";
foreach( var p in l.Split( '\n' ) ) {
var i = p.Split( ' ' );
h = h.Ticks < 1
? System.DateTime.ParseExact( i[ 1 ], "HH:mm", null )
: h.AddMinutes( int.Parse( i[ 1 ] ) );
if( h > s )
o += i[ 0 ] + " ";
}
return o;
};
List<KeyValuePair<String, String>>
testCases = new List<KeyValuePair<String, String>> {
new KeyValuePair<String, String>(
"Kevin 13:02\nRuby 5\nSam 3\nLisa 6\nBob 12",
"13:15"
),
new KeyValuePair<String, String>(
"Kevin 13:15\nRuby 5\nSam 3\nLisa 6\nBob 12",
"13:15"
),
};
foreach( KeyValuePair<String, String> testCase in testCases ) {
Console.WriteLine( $" Input:\n{testCase.Key}\n\n{testCase.Value}\n\nOutput:\n{f( testCase.Key, testCase.Value )}\n" );
}
Console.ReadLine();
}
}
}
```
---
### Releases
* **v1.1** - `- 2 bytes` - Thanks to [VisualMelon](https://codegolf.stackexchange.com/questions/116534/better-late-than-never/116630?noredirect=1#comment285347_116630)
* **v1.0** - `269 bytes` - Initial solution.
---
### Notes
* **Output format:** Outputs the names separated by spaces
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~43~~ 41 bytes
```
q~':/60b:Y;Sf/()':/60b+a\+{)iT+:TY>{;}|}%
```
[Try it online!](https://tio.run/nexus/cjam#@19Yp26lb2aQZBVpHZymr6EJ4WknxmhXa2aGaFuFRNpVW9fW1Kr@/x@t5J1alpmnYGhsZWCkxKUUVJpUqWAKZAQn5ioYA2mfzOJEBTMgwyk/ScHQSCmWi0sJqNjQVAkA "CJam – TIO Nexus")
**Explanation**
```
q~ e# Read and eval all input.
':/ e# Split the start time on colons.
60b e# Convert the result from base 60, to get the start time in minutes.
:Y; e# Store this time in variable Y, and discard it from the stack.
Sf/ e# Split each string in the guest list on spaces.
( e# Pull out the first guest from the list.
) e# Pull out the time from the guest.
':/60b+ e# Convert the time to a number of minutes (same way as before), then add it back
e# to the guest.
a\+ e# Add the guest back to the start of the guest list.
e# At this point, the first guest has his/her arrival time in minutes, and everyone
e# else still has their original number.
{ e# Apply this block to each guest:
)i e# Pull out the number and cast it to an integer.
T+ e# Add the value of variable T to it (T is initially 0).
:T e# Store the result back into T.
Y>{;}| e# If the resulting number of minutes is not after the start time, delete the
e# guest's name.
}% e# (end of block)
e# Implicit output.
```
[Answer]
## Lua, ~~211~~ 206 Bytes
First codegolf of the year for me, should still be golfable.
**Edit: Saved 5 Bytes by using a shorthand for `string.match`**
```
function f(l,T)m=T.match
r=function(X)return
m(X,"^%d+")*3600+60*m(X,"%d+$")end
T=r(T)z={}y=0
for i=1,#l do
h=m(l[i],"%d.*")h=i>1 and y+h*60or r(h)y=h
z[#z+1]=h>T and m(l[i],"%u%l*")or nil
end return z end
```
### Explanations
```
function f(l,T) -- declare the function f(list,partyTime)
r=function(X) -- declare a function r that convert hh:mm in seconds
return X:match("^%d+")*3600 -- return the sum of seconds the hours
+60*X:match("%d+$") -- and in the seconds
end
T=r(T) -- convert the partyTime in seconds
z={} -- create the shameList for late partygoers
y=0 -- y will keep us updated on the second count
for i=1,#l -- iterate over l
do
h=l[i]:match("%d.*") -- h is a shorthand for the time of arrival
h=i>1 -- if we're on the second line at least
and y+h*60 -- update h with the time of arrival in second
or r(h) -- else use r()(for the first partygoer only)
y=h -- update our reference for adding time
z[#z+1]=h>T -- if the last partygoer was late
and l[i]:match("%u%l*") -- add its name to the shameList
or nil -- else, don't do anything
end
return z -- return the shameList
end
```
if you want to try this code, you can use the following snippet
```
function f(l,T)r=function(X)return
X:match("^%d+")*3600+60*X:match("%d+$")end
T=r(T)z={}y=0
for i=1,#l do
h=l[i]:match("%d.*")h=i>1 and y+h*60or r(h)y=h
z[#z+1]=h>T and l[i]:match("%u%l*")or nil
end return z end
retour = f({"Kevin 13:02","Ruby 5","Sam 3","Lisa 6","Bob 12"},"13:15")
for i=1,#retour
do
print(retour[i])
end
```
[Answer]
# Java, ~~346~~ ~~304~~ ~~284~~ 275 bytes
* -9 bytes, thanks to @KevinCruijssen
```
void g(int m,String[]n,String[]a,int M){for(int i=0;i<n.length;i++)if((M+=i>0?p(a[i]):0)>m)System.out.print(n[i]);}
int p(String n){return new Short(n);}
int h(String t){return p(t.split(":")[0])*60+p(t.split(":")[1]);}
void f(String[]n,String[]a,String b){g(h(b),n,a,h(a[0]));}
```
**Detailed** [Live](http://ideone.com/yeG961)
```
public static void g(int m, String[] n, String[] a, int M)
{
for(int i = 0; i < n.length; i++)
{
if((M += i>0 ? p(a[i]) : 0) > m)
{
System.out.println(n[i]);
}
}
}
public static int p(String n)
{
return Integer.parseInt(n);
}
public static int h(String t)
{
return p(t.split(":")[0])*60+p(t.split(":")[1]);
}
public static void f(String[] n, String[] a, String b)
{
g(h(b),n,a,h(a[0]));
}
```
[Answer]
## Batch, 163 bytes
```
@set/pp=
@set/ap=%p::=*60+%
:l
@set g=
@set/pg=
@if "%g%"=="" exit/b
@set t=%g:* =%
@set/ap-=%t::=*60+%
@for %%g in (%g%)do @(if %p% lss 0 echo %%g)&goto l
```
Takes input on STDIN. First line is the start time of the party, then the list of guests. Uses @Arnauld's trick to convert the hh:mm into minutes.
Batch's preferred input for this would be as a series of command-line parameters (starting with the time of the party, then each guest and time as separate arguments). This would only take 129 bytes:
```
@set p=%1
@set/ap=%p::=*60+%
:l
@set t=%3
@set/ap-=%t::=*60+%
@if %p% lss 0 echo %2
@shift
@shift
@if not "%2"=="" goto l
```
[Answer]
# Groovy, 121 bytes
```
{g,t->y={Date.parse('hh:mm',it)};u=y(t);d=y(g.remove(0)[1]);g.find{z=it[1];use(groovy.time.TimeCategory){d+z.minutes}>u}}
```
[Answer]
## PowerShell, 170 160 bytes
```
select-string '(?m)^((\w*) )?((\d\d):)?(\d?\d)$'-a|% matches|%{,$_.groups[2,4,5].value}|%{}{$b+=($c=60*$_[1]+$_[2]);$a+=,@{n=$_[0];t=$b}}{$a|? n|? t -gt $c|% n}
```
[Try it online!](https://tio.run/nexus/powershell#DY09D4IwGIT3/op3qIEKGD7EAdNAXHXSUdAUaJAEqrFFY4Dfju9wl@dyl1xmkaP8tAqCKPFDch7KH8TkInqIyKnVAnbk8CwhCAkOgphY2bRo2cnKeNq8W9WAZac9u9l2/l0zYClCndcsQcrrFIlanphW0AtTPaSeVqNL75vm/Rxe@hq6WzcuNh/RDXLGah5p6XCbVnznr@n9GhQOeliwPRUOd7NRccx@sTecljOuxZSCQhnwGgO0wiM1L8sf "PowerShell – TIO Nexus")
] |
[Question]
[
The challenge is to filter a large file quickly.
* Input: Each line has three space separated positive integers.
* Output: All input lines `A` `B`, `T`that satisfy either of the following criterion.
1. There exists another input line `C`, `D`, `U` where `D = A` and `0 <= T - U < 100`.
2. There exists another input line `C`, `D`, `U` where `B = C` and `0 <= U - T < 100`.
To make a test file use the following python script which will also be used for testing. It will make a 1.3G file. You can of course reduce nolines for testing.
```
import random
nolines = 50000000 # 50 million
for i in xrange(nolines):
print random.randint(0,nolines-1), random.randint(0,nolines-1), random.randint(0,nolines-1)
```
**Rules.** The fastest code when tested on an input file I make using the above script on my computer wins. The deadline is one week from the time of the first correct entry.
**My Machine** The timings will be run on my machine. This is a standard 8GB RAM ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code.
**Some relevant timing information**
Timings updated to run the following before each test.
```
sync && sudo bash -c 'echo 3 > /proc/sys/vm/drop_caches'
time wc test.file
real 0m26.835s
user 0m18.363s
sys 0m0.495s
time sort -n largefile.file > /dev/null
real 1m32.344s
user 2m9.530s
sys 0m6.543s
```
**Status of entries**
I run the following line before each test.
```
sync && sudo bash -c 'echo 3 > /proc/sys/vm/drop_caches'
```
* **Perl** (Waiting for bug fix.)
* **Scala** 1 minutes 37 seconds by @James\_pic. (Using scala -J-Xmx6g Filterer largefile.file output.txt)
* **Java**. 1 minute 23 seconds by @Geobits. (Using java -Xmx6g Filter\_26643)
* **C**. 2 minutes 21 seconds by @ScottLeadley.
* **C**. 28 seconds by @James\_pic.
* **Python+pandas**. Maybe there is a simple "groupby" solution?
* **C**. 28 seconds by @KeithRandall.
**The winners are Keith Randall and James\_pic.**
I couldn't tell their running times apart and both are almost as fast as wc!
[Answer]
## C, ~ 7 4.1 seconds
Radix sort on T, then walk through the array looking for matches.
It is fast because it is cache friendly. The radix sort reasonably so, and the final walk very. I have to check each row against about 100 others, but they are all adjacent in the cache.
Added: I no longer have to check each row against a scan of 100 other rows. A small table of counts of low order bits of b's in the window suffices to eliminate most instances of this scan.
Now about 1/2 time parsing, 1/3 time sorting, 1/6 time doing the actual matching.
```
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
// B = # of bits per radix pass
// R = # of radix passes
#define B 9
#define R 3
#define M ((1<<B)-1)
#define MAXN 50000000
int count[R][1<<B];
typedef struct {
int a,b,t,print;
} entry;
entry A[MAXN];
entry C[MAXN];
// Sized to fit well in L1 cache
unsigned char bcount[16384];
int main(int argc, char *argv[]) {
FILE *f = fopen(argv[1], "r");
fseek(f, 0, SEEK_END);
int size = ftell(f);
fclose(f);
int fd = open(argv[1], O_RDONLY);
const char *p = (const char*)mmap(0, size, PROT_READ, MAP_SHARED, fd, 0);
const char *endp = p + size;
// parse, insert into array
int n = 0;
while(p < endp) {
// parse line
int a = 0;
while(*p != ' ') {
a *= 10;
a += *p - '0';
p++;
}
p++;
int b = 0;
while(*p != ' ') {
b *= 10;
b += *p - '0';
p++;
}
p++;
int t = 0;
while(*p != '\n') {
t *= 10;
t += *p - '0';
p++;
}
p++;
// insert it
if(n == MAXN) {
printf("too many elements\n");
exit(1);
}
A[n].a = a;
A[n].b = b;
A[n].t = t;
n++;
// compute counts for radix sort
count[0][t&M]++;
count[1][(t>>B)&M]++;
count[2][t>>2*B]++;
}
// accumulate count entries
for(int r = 0; r < R; r++) {
for(int i = 0; i < M; i++) {
count[r][i+1]+=count[r][i];
}
}
// radix sort, 3 rounds
for(int i = n-1; i >= 0; i--) {
C[--count[0][A[i].t&M]] = A[i];
}
for(int i = n-1; i >= 0; i--) {
A[--count[1][(C[i].t>>B)&M]] = C[i];
}
for(int i = n-1; i >= 0; i--) {
C[--count[2][A[i].t>>2*B]] = A[i];
}
// Walk through array (now sorted by T) and find matches.
// We maintain a window of T values that might match.
// To facilitate finding matches within that window, bcount
// keeps track of a count of how many b's in that window
// have the given low 14 bits.
int j = 0;
for(int i = 0; i < n; i++) {
int a = C[i].a;
int t = C[i].t;
while(C[j].t <= t - 100) {
int x = C[j].b & 16383;
if(bcount[x] != 255) bcount[x]--;
j++;
}
if(bcount[a & 16383] > 0) {
// somewhere in the window is a b that matches the
// low 14 bits of a. Find out if there is a full match.
for(int k = j; k < i; k++) {
if(a == C[k].b)
C[k].print = C[i].print = 1;
}
}
int x = C[i].b & 16383;
if(bcount[x] != 255) bcount[x]++;
}
for(int i = 0; i < n; i++) {
if(C[i].print)
printf("%d %d %d\n", C[i].a, C[i].b, C[i].t);
}
}
```
[Answer]
# Scala 2.10 - 0:41
The problem is basically:
```
select * from data x, data x where x.a = y.b and 0 <= x.t - y.t and x.t - y.t < 100
```
Most RDBMSs would notice that the join from `x.a` to `y.b` has the highest specificity, and plan this as a hash join.
So that's what we'll do. We create a hashtable of the data on `a`, hash join it with the same table on `b`, and filter on the difference in `t`.
```
import scala.io.Source
import scala.reflect.ClassTag
import java.io._
object Filterer {
def roundUpToNextPowerOfTwo(x: Int) = {
// blatantly stolen from http://bits.stephan-brumme.com/roundUpToNextPowerOfTwo.html
var y = x - 1
y |= y >> 1
y |= y >> 2
y |= y >> 4
y |= y >> 8
y |= y >> 16
y + 1
}
// We hash join the array with itself, a to b, and emit both rows if t is within 100. 50m records should fit into 8GB OK.
def main(args: Array[String]): Unit = {
val input = Source.fromFile(args(0), "ASCII").getLines()
val output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(args(1)), "US-ASCII"))
try {
val data1: Array[Row] = input.map{line =>
Row(line)
}.toArray
/*
* In theory, data1 and data2 could be created in parallel, but OpenHashMultiMap needs
* to know its size at creation time, to sidestep the need for rehashing. I could just
* hard-code 50 million (the size of the data in the challenge), but that seems dishonest.
*/
val data2 = new OpenHashMultiMap[Int, Row](roundUpToNextPowerOfTwo(data1.size) * 2, -1)
for (r <- data1) data2.insert(r.a, r) // data2 is hashed by a
for (row1 <- data1.par) {
val Row(a, b, t) = row1
for (Row(c, d, u) <- data2.get(b) if (0 <= u - t) && (u - t < 100)) {
// The conditions are symmetric, so if row1 matches, so does row2
output.write(s"$a $b $t\n$c $d $u\n")
}
}
} finally {
output.close()
}
}
}
object Row {
def apply(data: String): Row = {
val l = data.length
var i = 0
var a = 0
var b = 0
var c = 0
while (data.charAt(i) != ' ') {
a = a * 10 + (data.charAt(i) - '0')
i += 1
}
i += 1
while (data.charAt(i) != ' ') {
b = b * 10 + (data.charAt(i) - '0')
i += 1
}
i += 1
while (i < l) {
c = c * 10 + (data.charAt(i) - '0')
i += 1
}
Row(a, b, c)
}
}
final case class Row(a: Int, b: Int, t: Int)
/*
* None of the standard Java or Scala collections are particularly efficient as large MultiMaps,
* so we write our own. We use open hashing with quadratic probing.
*/
class OpenHashMultiMap[@specialized(Int) K: ClassTag, V: ClassTag](capacity: Int, default: K) {
require((capacity & (capacity - 1)) == 0) // Power of 2 capacity
private val keys = Array.fill(capacity)(default)
private val values = new Array[V](capacity)
private val mask = capacity - 1
private def hash(k: K) = {
// Hash mingling - Int has a particularly poor hash
k.hashCode * 428916315
}
def insert(k: K, v: V) = {
var found = false
var loc = hash(k) & mask
var inc = 0
while (inc <= capacity && !found) {
loc = (loc + inc) & mask
inc += 1
found = keys(loc) == default
}
keys(loc) = k
values(loc) = v
}
def get(key: K) = new Traversable[V] {
override def foreach[U](f: V => U) = {
var break = false
var loc = hash(key) & mask
var inc = 0
while (inc <= capacity && !break) {
loc = (loc + inc) & mask
inc += 1
val k = keys(loc)
if (key == k) f(values(loc))
else if (k == default) break = true
}
}
}
}
```
Compile with:
```
scalac Filterer.scala
```
And run with:
```
scala -J-server -J-XX:+AggressiveOpts -J-Xms6g -J-Xmx6g Filterer input_file.dat output_file.txt
```
On my machine, this runs in 2 minutes 27.
Still, it might be interesting to try the approach from @Lembik's answer, but in a faster language. It corresponds to something like a merge join on `t`. On paper, it should be slower, but it has better cache locality, which may push it ahead.
## Update
I've managed to shave a large chunk of time off with a surprisingly small change - a better hash mingler. The hash map is very sensitive to hash clumping, so this change brings it down to 1:45 on my machine.
Most of that time is spent reading the data into an array.
I'm curious as to why my data reading code is so much slower than @Geobits. It takes my code 70 seconds to read the data in - longer than @Geobits entire program, once the `Thread.start` bug is fixed. I'm tempted to steal @Geobits approach to reading data, but I'm not sure how the Stack Exchange gods would feel about that.
## Update 2
I've made further improvements, this time to the data reader. Using pattern matching and monad operations inside the loop was hurting performance, so I've simplified it. I think `scala.io.Source` is the next bottleneck to tackle.
It's down to 1:26 on my machine now.
## Update 3
Got rid of `probe` from OpenHashMultiMap. The code is now more java-ish, and runs in 1:15.
## Update 4
I'm now using an FSM to parse input. Run time is down to 0:41
[Answer]
# C - 12 seconds
I decided to port my Scala answer to C, to see how much more performance I could get.
It's more or less the same approach (build an open hash table on `a`), except that I skip the step where I build the initial array, and iterate from the hash table directly (for some reason I could never get this approach to perform in Scala - I suspect JVM inlining was to blame).
I didn't bother with threads, as it's a pain to do portably.
The code is:
```
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
// Should be 37% occupied with 50m entries
#define TABLE_SIZE 0x8000000
#define MASK (TABLE_SIZE - 1)
#define BUFFER_SIZE 16384
#define END_OF_FILE (-1)
#define DEFAULT_VALUE (-1)
typedef struct Row {
int32_t a;
int32_t b;
int32_t t;
} Row;
int32_t hash(int32_t a) {
return a * 428916315;
}
void insert(Row * table, Row row) {
long loc = hash(row.a) & MASK; // Entries are hashed on a
long inc = 0;
while (inc <= TABLE_SIZE) {
loc = (loc + inc) & MASK;
inc++;
if (table[loc].a == DEFAULT_VALUE) {
table[loc] = row;
break;
}
}
}
int readChar(FILE * input, char * buffer, int * pos, int * limit) {
if (*limit < *pos) {
return buffer[(*limit)++];
} else {
*limit = 0;
*pos = fread(buffer, sizeof(char), BUFFER_SIZE, input);
if (*limit < *pos) {
return buffer[(*limit)++];
} else return END_OF_FILE;
}
}
void readAll(char * fileName, Row * table) {
char* buffer = (char*) malloc(sizeof(char) * BUFFER_SIZE);
int limit = 0;
int pos = 0;
FILE * input = fopen(fileName, "rb");
int lastRead;
Row currentRow;
uint32_t * currentElement = &(currentRow.a);
// As with the Scala version, we read rows with an FSM. We can
// roll up some of the code using the `currentElement` pointer
while (1) {
switch(lastRead = readChar(input, buffer, &pos, &limit)) {
case END_OF_FILE:
fclose(input);
return;
case ' ':
if (currentElement == &(currentRow.a)) currentElement = &(currentRow.b);
else currentElement = &(currentRow.t);
break;
case '\n':
insert(table, currentRow);
currentRow.a = 0;
currentRow.b = 0;
currentRow.t = 0;
currentElement = &(currentRow.a);
break;
default:
*currentElement = *currentElement * 10 + (lastRead - '0');
break;
}
}
//printf("Read %d", lastRead);
}
int main() {
Row* table = (Row*) malloc(sizeof(Row) * TABLE_SIZE);
memset(table, 255, sizeof(Row) * TABLE_SIZE);
readAll("test.file", table);
// We'll iterate through our hash table inline - passing a callback
// is trickier in C than in Scala, so we just don't bother
for (size_t i = 0; i < TABLE_SIZE; i++) {
Row * this = table + i;
if (this->a != DEFAULT_VALUE) {
// Lookup entries `that`, where `that.a == this.b`
long loc = hash(this->b) & MASK;
long inc = 0;
while (inc <= TABLE_SIZE) {
loc = (loc + inc) & MASK;
inc++;
Row * that = table + loc;
if ((this->b == that->a) && (0 <= that->t - this->t) && (that->t - this->t < 100)) {
// Conditions are symmetric, so we output both rows
printf("%d %d %d\n", this->a, this->b, this->t);
printf("%d %d %d\n", that->a, that->b, that->t);
}
else if (that->b == DEFAULT_VALUE) break;
}
}
}
free(table);
return 0;
}
```
Compile with:
```
gcc -std=c99 -O3 -m64 filter.c
```
And run with:
```
./a.out
```
The location of the test file is hard-coded as "test.file".
Once again, reading the data takes up most of the time (just under 9 seconds). Matching takes the rest of the time.
Again, it'll be interesting to see how this fares against Scott Leadley's answer, which uses the same language but a different strategy. Scott is joining on T, which in principle means he'll have more to join against, but again, joining on T gives better cache locality.
[Answer]
# Java : 1m54s
**(On my i7)**
Since every match will be within 100 `t` of its mate, I decided to bucket the inputs by `t`. There is a bucket for each 100, so to check a number, it only has to check against +/-1 buckets.
On average, each bucket only contains 100 entries, so it doesn't take long to scan a few buckets for each. Well over half the time is spent reading and bucketing, matching takes only 40 seconds or so.
*Note:* Depending on your JVM setup, you may need to increase the heap size. This also assumes file name of `test.file`. Simply change it on line 24 if that's not the case.
```
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Filter_26643 {
final static int numThreads = 8;
final static int numInputs = 50000000;
final static int bucketSize = 100;
final static int numBuckets = numInputs/bucketSize;
ArrayList<ArrayList<int[]>> buckets;
public static void main(String[] args) {
new Filter_26643().run();
}
void run(){
try{
buckets = new ArrayList<ArrayList<int[]>>(numBuckets);
for(int i=0;i<numBuckets;i++)
buckets.add(new ArrayList<int[]>(bucketSize*2));
BufferedReader reader = new BufferedReader(new FileReader("test.file"));
int c=0,e[];
while(c++<numInputs){
StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
e = new int[] {
Integer.parseInt(tokenizer.nextToken()),
Integer.parseInt(tokenizer.nextToken()),
Integer.parseInt(tokenizer.nextToken())
};
buckets.get(e[2]/100).add(e);
}
reader.close();
MatchThread[] threads = new MatchThread[numThreads];
for(int i=0;i<numThreads;i++){
threads[i] = new MatchThread(i);
threads[i].start();
}
for(int i=0;i<numThreads;i++)
threads[i].join();
} catch(Exception e){
e.printStackTrace();
}
}
class MatchThread extends Thread{
int index;
public MatchThread(int index){
this.index = index;
}
@Override
public void run() {
for(int i=index;i<numBuckets;i+=numThreads){
int max = i+2 >= numBuckets ? numBuckets : i+2;
int min = i-1 < 0 ? i : i-1;
for(int[] entry : buckets.get(i)){
outer:
for(int j=min;j<max;j++){
ArrayList<int[]> bucket = buckets.get(j);
for(int[] other : bucket){
if(((entry[0]==other[1] && entry[2]-other[2]<100 && entry[2]>=other[2]) ||
(entry[1]==other[0] && other[2]-entry[2]<100 && other[2]>=entry[2]))
&& entry != other){
System.out.println(entry[0] + " " + entry[1] + " " + entry[2]);
break outer;
}
}
}
}
}
}
}
}
```
[Answer]
# perl, 17m46s on a core i7 w/ 8GB mem
First, we use sort -n -k3 to get the most important field in order, taking advantage of the built-in parallelism on modern versions of sort(1). Then, since perl is greatly hampered by the fact that a simple scalar takes on the order of 80 bytes each (50 million \* 3 \* 80 is too much - at least 12GB), we slurp the output in to a 50 million \* 12 byte array (12 bytes per line, each line contains 3 integers that can be represented as a 32 bit integer). Then we fire off 8 threads covering (roughly) 1/8th of the data each (+ some overlap).
```
#!perl
use strict;
use warnings;
# find lines s.t. $lines[$M]->{a} == $lines[$N]->{b} and
# 0 <= $lines[$M]->{t} - $lines[$N]->{t} < 100
# OR $lines[$M]->{b} == $lines[$N]->{a} and
# 0 <= $lines[$N]->{t} - $lines[$M]->{t} < 100
my $infile = shift;
open(my $fh, "sort -n -k3 $infile |") || die "open sort pipe: $@";
my @lines;
my $bytes_per_int = 4;
my $bytes_per_line = $bytes_per_int * 3;
my $nlines = 50_000_000;
my $buf = "\0" x ($nlines * $bytes_per_line);
my $ln = 0;
my $nprocs = 8;
my $last_group_start = 0;
my $this_group_start;
my $group = $nlines / $nprocs;
my @pids;
while(<$fh>) {
my ($A, $B, $T) = split/\s+/;
substr($buf, $ln * $bytes_per_line, $bytes_per_line, pack "L3", ($A, $B, $T));
if( defined $this_group_start ) {
if( $T - $last_group_start >= $group + 100 ) {
if(my $pid = fork()) {
push @pids, $pid;
$last_group_start = $this_group_start;
undef $this_group_start;
} else {
#warn "checking $last_group_start - $ln...\n";
for(my $l=$last_group_start; $l<=$ln; ++$l) {
my $lpos = $l * $bytes_per_line;
my ($A, $B, $T) = unpack "L3", substr($buf, $lpos, $bytes_per_line);
my ($lA, $lB);
my $lT = $T;
for(my $lb=$l; $lb>=$last_group_start && $T - $lT <= 100; $lb--, $lpos -= $bytes_per_line) {
($lA, $lB, $lT) = unpack "L3", substr($buf, $lpos, $bytes_per_line);
if($A == $lB || $B == $lA) {
#print "($last_group_start) $A $B $T matches $lA $lB $lT\n";
print "$lA $lB $lT\n$A $B $T\n";
}
}
}
exit;
}
}
} elsif( !defined $this_group_start && $T - $last_group_start >= $group ) {
$this_group_start = $ln;
}
$ln++;
}
waitpid $_, 0 for @pids;
```
Unsorted output:
```
8455767 30937130 50130
20468509 8455767 50175
47249523 17051933 111141
17051933 34508661 111215
39504040 36752393 196668
42758015 39504040 196685
25072294 28422439 329284
35458609 25072294 329375
45340163 42711710 6480186
39315845 45340163 6480248
1435779 49643646 12704996
38229692 1435779 12705039
18487099 24556657 6665821
24556657 28498505 6665884
6330540 35363455 18877328
22500774 6330540 18877347
10236123 22026399 598647
39941282 10236123 598717
45756517 24831687 6726642
34578158 45756517 6726670
29385533 7181838 621179
7181838 29036551 621189
40647929 11895227 25075557
11895227 1900895 25075652
17921258 42642822 18935923
40140275 17921258 18935949
44573044 38139831 12899467
38139831 1321655 12899468
11223983 1788656 12920946
1788656 21905607 12921040
1357565 8148234 801402
8148234 46556089 801498
30929735 303373 19105532
31258424 30929735 19105543
34899776 9929507 6990057
9929507 49221343 6990078
49779853 43951357 25306335
41120244 49779853 25306424
6177313 41551055 25343755
24462722 6177313 25343804
16392217 32915797 31472388
32915797 19696674 31472479
6834305 36264354 25440771
44983650 6834305 25440800
26559923 47360227 19356637
47360227 49749757 19356700
33018256 36233269 37654651
36233269 5459333 37654671
6932997 23123567 25502355
23123567 7882426 25502356
5878434 43421728 25510707
43421728 40827189 25510765
38695636 33504665 1099515
13504170 38695636 1099605
32832720 40188845 37689854
8335398 32832720 37689927
35858995 41917651 1130028
41917651 28797444 1130096
47102665 6796460 43806189
6796460 6113288 43806229
21248273 5422675 43819677
48011830 21248273 43819728
32187324 39177373 25624030
39177373 42539402 25624102
41722647 14351373 25626925
14351373 45070518 25627013
22298566 25860163 37862683
2273777 22298566 37862692
10617763 32776583 7561272
35581425 10617763 7561279
18526541 18709244 31960780
18709244 32777622 31960867
36976439 24222624 31973215
24222624 9534777 31973262
25751007 11612449 38066826
43652333 25751007 38066923
8303520 2615666 7633297
2615666 29961938 7633357
22317573 31811902 31982722
14298221 22317573 31982819
43089781 7653813 44154683
8732322 43089781 44154769
24227311 43800700 13711475
40906680 24227311 13711539
48061947 30109196 7660402
43993467 48061947 7660488
29580639 5292950 38140285
5292950 21293538 38140356
17646232 47737600 32058831
47737600 42934248 32058836
13262640 23462343 1617194
23462343 1901587 1617259
5150775 7046596 44270140
7046596 22819218 44270181
17749796 34924638 32171251
8386063 17749796 32171346
30095973 12202864 38257881
12202864 42679593 38257912
10353022 40646034 26158412
40646034 36237182 26158412
8416485 16245525 32223010
16245525 32420032 32223081
20420340 1371966 7893319
1371966 2031617 7893335
2864137 20279212 26199008
29145409 2864137 26199080
29141766 19729396 44433106
44115780 29141766 44433141
6513924 34515379 32283579
12686666 6513924 32283636
20116056 49736865 44464394
49736865 47918939 44464416
38212450 3465543 32302772
3465543 39217131 32302873
12019664 37367876 44485630
3639658 12019664 44485639
18053021 1279896 7973955
2220749 18053021 7974031
19701732 12984505 1857435
24625926 19701732 1857528
9876789 34881917 26285125
27687743 9876789 26285134
5696632 6064263 44534580
34888313 5696632 44534629
14865531 46418593 38457138
5929897 14865531 38457191
44378135 4051962 38485208
4051962 10804515 38485308
11865822 21793388 14142622
7760360 11865822 14142649
32333570 24478420 44702533
24478420 23749609 44702588
29098286 25015092 44723985
32171647 29098286 44723985
20522503 20522503 2127735
20522503 20522503 2127735
22597975 20938239 8260902
20938239 48618802 8260905
8310032 34659671 2153994
34659671 25406149 2154075
49085033 5708432 26644257
5708432 32265692 26644305
18751513 18226037 32726402
18226037 33885794 32726424
45877488 23211339 20566948
23211339 26209405 20567002
48554034 25770643 38853402
9683274 48554034 38853467
9770420 14556349 2309265
27255587 9770420 2309324
32926392 16744099 44954824
24840989 32926392 44954840
29066838 49434549 26755357
49434549 12635292 26755407
21927714 32352409 20626921
32352409 15895076 20626932
7422009 23559357 14550898
32743911 7422009 14550982
38816601 5850890 26851026
5850890 32996623 26851107
42148171 47021378 26872907
47021378 32628418 26872908
9850929 10501741 32998960
10501741 24899993 32999043
27491904 4393602 33033499
4393602 17712085 33033570
37978226 42226216 39114479
42226216 2511412 39114525
42859989 49908919 45241083
48131208 42859989 45241088
39753103 30674979 14807321
30674979 45637890 14807371
30154199 11988643 2641926
11988643 11241926 2641976
7191871 13518594 45370275
13518594 45354921 45370344
54745 19711137 8871851
24814115 54745 8871937
38770495 34574748 2756244
41962321 38770495 2756337
26229406 39306415 21057327
10735951 26229406 21057347
46704290 11506122 39359422
18181795 46704290 39359481
38796645 28410469 45452212
28410469 13478996 45452222
412456 27727741 39466147
27727741 19639136 39466226
24470627 13030982 21266756
13030982 21713410 21266825
6058593 23139172 27435254
19236012 6058593 27435303
14457750 39190113 39701131
30253141 14457750 39701227
26898421 39016446 45812750
40952330 26898421 45812829
18647206 27663400 45817956
27663400 21728474 45817989
5559358 41319001 33664547
41319001 37210583 33664636
29066692 30653068 39759813
30653068 38963132 39759856
12086617 49971187 3232640
49971187 32302154 3232649
12008399 13656671 3239395
43088998 12008399 3239439
10061612 38594475 39804389
38594475 6327106 39804405
16703379 21150436 39851057
21150436 34093320 39851136
1035486 4199407 3314170
26974438 1035486 3314196
21869320 14532221 33851404
15208937 21869320 33851473
38840190 4742355 3402401
4742355 46055869 3402462
34432016 8734566 39966972
27614117 34432016 39967002
9988172 49209666 46063078
49209666 29374155 46063087
3208946 47030309 21722002
47030309 39809983 21722030
10928661 46423741 3496854
46423741 29486710 3496862
42464855 22978174 46154827
22978174 3814497 46154901
47090840 16768393 46169667
39523858 47090840 46169714
28186104 11618234 34024001
11618234 33711158 34024019
45471813 37332848 3585557
37332848 4607526 3585600
14885742 38990612 15863749
38990612 3710491 15863779
42391514 33643913 22005928
33643913 32254640 22006022
4299590 19482026 34202327
19482026 35838894 34202406
24298776 16276160 3858885
16276160 3198758 3858958
29322567 12536696 40433239
12536696 26083938 40433317
16080151 9648322 22221443
9648322 43846385 22221458
999302 19218350 10078183
10296062 999302 10078189
40544377 34492433 34463953
19908418 40544377 34463993
10765321 45143043 34542584
39154522 10765321 34542646
48642526 31097951 4104790
2940654 48642526 4104887
26972730 47422139 46846889
39228577 26972730 46846901
13788696 11503551 34728076
11503551 9151627 34728130
8676030 30463644 10406398
15204754 8676030 10406405
42984277 41087708 34805119
48741576 42984277 34805143
29634598 2151247 22699609
12264074 29634598 22699614
47525963 48470003 16667878
48470003 4566846 16667953
9725907 43325112 4498307
26465445 9725907 4498368
306967 11708860 10633595
11708860 31017081 10633669
39420965 46595640 41089015
46595640 41260374 41089048
29232745 39705052 16754836
4739295 29232745 16754840
35246405 42811088 41273637
48986699 35246405 41273719
2398239 36985098 35181790
36985098 7460784 35181841
18955749 23678549 35221035
47264406 18955749 35221129
18105816 26003002 17044057
26003002 17467477 17044087
14430126 46039962 47492180
46039962 29118827 47492275
30329324 40926812 41425850
43304610 30329324 41425912
34966996 36567528 17095113
3967517 34966996 17095144
42829171 42530474 23209891
25923738 42829171 23209967
28187681 26297990 35474412
48986691 28187681 35474475
5707126 41598794 17298139
40466899 5707126 17298188
28838696 30725820 5142797
30725820 35360418 5142798
44642019 42570370 17339657
42570370 19022469 17339727
42193681 8389736 17386517
48906013 42193681 17386586
42303185 30337820 41795129
30337820 42473956 41795170
30935782 8441903 17515229
41549758 30935782 17515275
41239019 10011768 23619001
10011768 25386353 23619062
494288 13341166 29815779
49113152 494288 29815876
7106674 26227442 29833029
47459682 7106674 29833047
17246497 35389391 17628365
35389391 34005133 17628371
23347674 48243185 17792799
48243185 22907892 17792836
21852744 1662414 36088704
8040124 21852744 36088775
32384657 27122374 36100767
24980361 32384657 36100782
31016207 26300043 42222489
26300043 36869529 42222544
17178756 44315094 42223989
44315094 11222466 42224042
34139317 39164101 36197907
39164101 27563542 36197947
31638631 22215137 17999735
22215137 10771707 17999769
30257199 32883043 24127009
32883043 179099 24127047
47774058 17451960 30283073
44583527 47774058 30283162
13816647 12695130 24145102
12695130 42284941 24145188
42749234 20004242 5893793
20004242 38129713 5893819
22210359 22178109 18109989
22178109 112961 18110049
42509645 28599506 42508465
28599506 3722411 42508513
34412629 22547405 48610262
22547405 16664124 48610296
2330283 32267749 24256113
35915758 2330283 24256157
44560231 49353986 12101694
6471293 44560231 12101780
23289721 8186827 30407293
10624448 23289721 30407389
12329357 35765163 30560085
4511908 12329357 30560158
31332240 39704929 12269193
39704929 47770487 12269249
22286152 22082044 36734758
22082044 25076919 36734833
47381309 9459604 36735886
9459604 31071680 36735890
43832763 45342283 30707519
45342283 26992816 30707602
2883029 18642608 42989696
14697025 2883029 42989793
15149987 40746227 24700535
40746227 34776566 24700549
2387554 49015265 43057085
49015265 21103141 43057139
23057202 13308993 30982514
34596334 23057202 30982553
44598498 31714790 43285828
18170064 44598498 43285841
38273701 11976319 31179763
15344094 38273701 31179764
3651338 27427037 37188945
12876654 3651338 37189007
10081580 3418061 37221143
3418061 38353019 37221143
172544 18699860 37295343
824744 172544 37295372
13914 8890169 37303853
8890169 14008003 37303898
18716557 29456130 49605004
29456130 16390535 49605083
15398102 22446674 43711290
22446674 38760679 43711383
```
I'm sure this would be an order of magnitude faster in C, but I probably won't take the time to do so.
[Answer]
# C# - 30 Seconds
A different approach from most if I read right - I don't use any hash based structures.
~~I tend to get no results, not sure if this a statistical anomaly, or error in my reasoning.~~ Fixed, comparison for binary sort was flawed.
```
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace FilterFile
{
class Program
{
const int COUNT = 50000000;
static string inputFile = "data" + COUNT + ".txt";
static string outputFile = "results.txt";
static void Main(string[] args)
{
Console.WriteLine("Prepping Test");
if (args.Length > 0) inputFile = args[0];
if (args.Length > 1) outputFile = args[1];
if (!File.Exists(inputFile))
{
Console.WriteLine(inputFile);
File.WriteAllLines(inputFile,
GenerateData(COUNT)
.Select(r => string.Format("{0} {1} {2}", r.A, r.B, r.C)));
}
File.Delete("results.txt");
Console.WriteLine("Starting Test \n\n");
using (Timer.Create("Total Time"))
{
Row[] sortedA, sortedB;
//http://codegolf.stackexchange.com/questions/26643/filter-a-large-file-quickly
using (Timer.Create("Reading Data"))
FillData(out sortedA, out sortedB);
using (Timer.Create("Parallel Sort A"))
ParallelSort.QuicksortParallel(sortedA);
using (Timer.Create("Parallel Sort B"))
ParallelSort.QuicksortParallel(sortedB, (x, y) => x.B - y.B);
object rLock = new object();
List<Row> results = new List<Row>();
var comparison = Comparer<Row>.Create((B, A) => B.B - A.A);
using (Timer.Create("Compute Results"))
Parallel.ForEach(sortedA, row =>
//foreach (var row in sortedA)
{
var i = Array.BinarySearch(sortedB, row, comparison);
if (i < 0) return;
Row other;
bool solved = false;
for (var tempI = i; tempI < sortedB.Length && row.A == (other = sortedB[tempI]).B; tempI++)
{
var diff = row.C - other.C;
if (diff >= 0 && diff < 100)
{
lock (rLock) results.Add(row);
return;
}
}
for (var tempI = i - 1; tempI >= 0 && row.A == (other = sortedB[tempI]).B; tempI--)
{
var diff = row.C - other.C;
if (diff >= 0 && diff < 100)
{
lock (rLock) results.Add(row);
return;
}
}
});
using (Timer.Create("Save Results"))
{
File.WriteAllLines(outputFile, results.Select(r => r.ToString()));
}
}
}
private static void FillData(out Row[] sortedA, out Row[] sortedB)
{
var tempA = new Row[COUNT];
var tempB = tempA;//new Row[COUNT];
const int PARTITION_SIZE = 1 << 22;
ReadAndSort(tempA, tempB, PARTITION_SIZE);
sortedA = tempA;
sortedB = new Row[COUNT];
Array.Copy(sortedA, sortedB, COUNT);
/*using (Timer.Create("MergeA"))
{
int destIndex = 0;
int[][] partitions = Enumerable.Range(0, COUNT / PARTITION_SIZE + 1)
.Select(i => new[] { i * PARTITION_SIZE, Math.Min(i * PARTITION_SIZE + PARTITION_SIZE, COUNT) - 1 })
.ToArray();
for (int i = 0; i < COUNT; i++)
{
foreach (var partition in partitions)
{
while (partition[0] <= partition[1] && tempA[partition[0]].A == i)
{
sortedA[destIndex++] = tempA[partition[0]++];
}
}
}
}*/
/*//Verify Paritioning Works
var results = new List<Tuple<Row, int>> { Tuple.Create(tempA[0], 0) };
for (int i = 1; i < tempA.Length; i++)
{
var r = tempA[i];
if (r.A < tempA[i-1].A)
results.Add(Tuple.Create(r, i % PARTITION_SIZE));
}
results.ForEach(t => Console.WriteLine(t.Item1 + " " + t.Item2));*/
}
private static void ReadAndSort(Row[] tempA, Row[] tempB, int PARTITION_SIZE)
{
List<Task> tasks = new List<Task>();
using (var stream = File.OpenRead(inputFile))
{
int b;
int tempMember = 0;
int memberIndex = 0;
int elementIndex = 0;
using (Timer.Create("Read From Disk"))
while ((b = stream.ReadByte()) >= 0)
{
switch (b)
{
case (byte)'\r':
case (byte)' ':
switch (memberIndex)
{
case 0: tempA[elementIndex].A = tempMember; memberIndex = 1; break;
case 1: tempA[elementIndex].B = tempMember; memberIndex = 2; break;
case 2: tempA[elementIndex].C = tempMember; memberIndex = 0; break;
}
tempMember = 0;
break;
case (byte)'\n':
/*if (elementIndex % PARTITION_SIZE == 0 && elementIndex > 0)
{
var copiedIndex = elementIndex;
tasks.Add(Task.Run(() =>
{
var startIndex = copiedIndex - PARTITION_SIZE;
Array.Copy(tempA, startIndex, tempB, startIndex, PARTITION_SIZE);
ParallelSort.QuicksortSequentialInPlace(tempA, startIndex, copiedIndex - 1);
ParallelSort.QuicksortSequentialInPlace(tempB, startIndex, copiedIndex - 1, (x, y) => x.B - y.B);
}));
}*/
elementIndex++;
break;
default:
tempMember = tempMember * 10 + b - '0';
break;
}
}
/* tasks.Add(Task.Run(() =>
{
elementIndex--; //forget about the last \n
var startIndex = (elementIndex / PARTITION_SIZE) * PARTITION_SIZE;
Array.Copy(tempA, startIndex, tempB, startIndex, elementIndex - startIndex + 1);
ParallelSort.QuicksortParallelInPlace(tempA, startIndex, elementIndex);
ParallelSort.QuicksortSequentialInPlace(tempB, startIndex, elementIndex, (x, y) => x.B - y.B);
}));
using (Timer.Create("WaitForSortingToFinish"))
Task.WaitAll(tasks.ToArray());*/
}
}
static Random rand = new Random();
public struct Row : IComparable<Row>
{
public int A;
public int B;
public int C;
public static Row RandomRow(int count)
{
return new Row { A = rand.Next(count), B = rand.Next(count), C = rand.Next(count) };
}
public int CompareTo(Row other)
{
return A - other.A;
}
public override string ToString()
{
return string.Format("{0} {1} {2}", A, B, C);
}
}
public static Row[] GenerateData(int count)
{
var data = new Row[count];
for (int i = 0; i < count; i++)
data[i] = Row.RandomRow(count);
return data;
}
public static Row[] GenerateSplitData(int count)
{
var data = new Row[count];
for (int i = 0; i < count; i++)
data[i] = Row.RandomRow(count);
return data;
}
public class Timer : IDisposable
{
string message;
Stopwatch sw;
public static Timer Create(string message)
{
Console.WriteLine("Started: " + message);
var t = new Timer();
t.message = message;
t.sw = Stopwatch.StartNew();
return t;
}
public void Dispose()
{
Console.WriteLine("Finished: " + message + " in " + sw.ElapsedMilliseconds + "ms");
}
}
// <summary>
/// Parallel quicksort algorithm.
/// </summary>
public class ParallelSort
{
const int SEQUENTIAL_THRESHOLD = 4096;
#region Public Static Methods
/// <summary>
/// Sequential quicksort.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="arr"></param>
public static void QuicksortSequential<T>(T[] arr) where T : IComparable<T>
{
QuicksortSequentialInPlace(arr, 0, arr.Length - 1);
}
/// <summary>
/// Parallel quicksort
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="arr"></param>
public static void QuicksortParallel<T>(T[] arr) where T : IComparable<T>
{
QuicksortParallelInPlace(arr, 0, arr.Length - 1);
}
#endregion
#region Private Static Methods
public static void QuicksortSequentialInPlace<T>(T[] arr, int left, int right)
where T : IComparable<T>
{
if (right > left)
{
int pivot = Partition(arr, left, right);
QuicksortSequentialInPlace(arr, left, pivot - 1);
QuicksortSequentialInPlace(arr, pivot + 1, right);
}
}
public static void QuicksortParallelInPlace<T>(T[] arr, int left, int right)
where T : IComparable<T>
{
if (right > left)
{
if (right - left < SEQUENTIAL_THRESHOLD)
QuicksortSequentialInPlace(arr, left, right);
else
{
int pivot = Partition(arr, left, right);
Parallel.Invoke(() => QuicksortParallelInPlace(arr, left, pivot - 1),
() => QuicksortParallelInPlace(arr, pivot + 1, right));
}
}
}
private static void Swap<T>(T[] arr, int i, int j)
{
T tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
private static int Partition<T>(T[] arr, int low, int high)
where T : IComparable<T>
{
// Simple partitioning implementation
int pivotPos = (high + low) / 2;
T pivot = arr[pivotPos];
Swap(arr, low, pivotPos);
int left = low;
for (int i = low + 1; i <= high; i++)
{
if (arr[i].CompareTo(pivot) < 0)
{
left++;
Swap(arr, i, left);
}
}
Swap(arr, low, left);
return left;
}
#endregion
#region Public Static Methods
/// <summary>
/// Sequential quicksort.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="arr"></param>
public static void QuicksortSequential<T>(T[] arr, Func<T, T, int> comparer)
{
QuicksortSequentialInPlace(arr, 0, arr.Length - 1, comparer);
}
/// <summary>
/// Parallel quicksort
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="arr"></param>
public static void QuicksortParallel<T>(T[] arr, Func<T, T, int> comparer)
{
QuicksortParallelInPlace(arr, 0, arr.Length - 1, comparer);
}
#endregion
#region Private Static Methods
public static void QuicksortSequentialInPlace<T>(T[] arr, int left, int right, Func<T, T, int> comparer)
{
if (right > left)
{
int pivot = Partition(arr, left, right, comparer);
QuicksortSequentialInPlace(arr, left, pivot - 1, comparer);
QuicksortSequentialInPlace(arr, pivot + 1, right, comparer);
}
}
public static void QuicksortParallelInPlace<T>(T[] arr, int left, int right, Func<T, T, int> comparer)
{
if (right > left)
{
if (right - left < SEQUENTIAL_THRESHOLD)
{
QuicksortSequentialInPlace(arr, left, right, comparer);
}
else
{
int pivot = Partition(arr, left, right, comparer);
Parallel.Invoke(() => QuicksortParallelInPlace(arr, left, pivot - 1, comparer),
() => QuicksortParallelInPlace(arr, pivot + 1, right, comparer));
}
}
}
private static int Partition<T>(T[] arr, int low, int high, Func<T, T, int> comparer)
{
// Simple partitioning implementation
int pivotPos = (high + low) / 2;
T pivot = arr[pivotPos];
Swap(arr, low, pivotPos);
int left = low;
for (int i = low + 1; i <= high; i++)
{
if (comparer(arr[i], pivot) < 0)
{
left++;
Swap(arr, i, left);
}
}
Swap(arr, low, left);
return left;
}
#endregion
}
}
}
```
[Answer]
### C
Brutal, brute force, in-your-face ugly C. On a do-over I would choose just about any other compiled language.
```
/*
Filter a file based on these rules:
Input:
- each item is an ordered list of three integers ( A B T )
- each line represents an item
- each line is formated as <number> <w> <number> <w> <number>
- <w> is whitespace (a single blank in the challenge)
- <number> is an integer in the range 0..49_999_999
- the first number on a line is A, second B, third T
Output a given item ( A B T ) if:
1 - there exists an item ( C D U ) such that 0 <= T-U < 100 and D == A
OR
2 - there exists an item ( C D U ) such that 0 <= U-T < 100 and B == C
CLARIFICATION:
An item should be output only once, even if there is more than one match.
We're sorting on T, we know the number of Ts to be sorted and the Ts are random.
Trade space for speed and create a lookup table that can handle collisions
(AKA hash table).
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <pthread.h>
#include <assert.h>
#define NTHREADS (16)
#define BINSPERTHREAD (1*1000*1000)
bool oneThread = false;
typedef struct {
pthread_t tid;
long begin;
long end;
} threadState;
void *initTID() {
return NULL;
}
#define MAXITEMS (50*1000*1000)
// items on the boundary are not included in the search
#define SEARCHBOUNDARY (100)
void usage(char *name) {
fprintf(stderr, "usage: %s [-n 1..%d]\n", name, MAXITEMS);
}
typedef struct item {
long A;
long B;
long T;
bool unprinted;
struct item *b; // b(ackward to previous item)
struct item *f; // f(orward to next item)
struct item *BINb; // backward to previous bin
struct item *BINf; // forward to next bin
#ifdef DEVTEST
long lineNumber;
#endif
} item;
#ifdef DEVTEST
bool printVerbose = false;
#endif
// Why global variables? Because large MAXITEMS overflow the stack.
long maxItems; // entries allocated in list & lookup
item *list;
long listN; // number of entries (max index + 1)
item **lookup;
long lookupN; // number of entries (max index + 1)
/*
input -
n - index of current bin
list - global
lookup - global
lookupN - global
side-effects -
list[] (.unprinted)
stdout
*/
static inline void *walkThisBin(long n) {
item *p;
item *searchHead;
item *searchTail;
item *currentItem;
long i;
// for all items in bin
for ( currentItem = lookup[n]; currentItem != lookup[n]->BINf;
currentItem = currentItem->f)
{
/*
merged forward&backward search
*/
searchHead = currentItem;
// step to index min((T+100-1),lookupN-1), find largest U<T+100
i = ((n+SEARCHBOUNDARY-1) < lookupN) ?
n+SEARCHBOUNDARY-1 :
lookupN-1;
// find largest i such that U-T<100 (U is lookup[i]->T)
// degenerate case is i == n
for(p=lookup[i];
!((p->T-searchHead->T)<SEARCHBOUNDARY);
p=lookup[i]) {
i--;
}
searchTail = p->BINf; // boundary, not included in search
p = currentItem;
do {
if (searchHead->B == p->A) {
// matches are symmetric
if (searchHead->unprinted) {
printf("%ld %ld %ld\n", searchHead->A, searchHead->B,
searchHead->T);
searchHead->unprinted = false;
}
if (p->unprinted) {
printf("%ld %ld %ld\n", p->A, p->B, p->T);
p->unprinted = false;
}
}
p = p->f;
} while (p!=searchTail);
}
return NULL;
}
/*
Must handle out-of-range indexes for lookup.
input -
n - index of current bin
list - global
lookup - global
lookupN - global
side-effects -
list (.unprinted)
stdout
*/
static inline void *walkTheseBins(void *tState) {
long startIndex = ((threadState *)tState)->begin;
long finishIndex = ((threadState *)tState)->end;
long n;
startIndex = (startIndex<0) ? 0 : startIndex;
finishIndex = (finishIndex>lookupN-1) ? lookupN-1 : finishIndex;
for (n=startIndex; n<=finishIndex; n++) {
walkThisBin(n);
}
return NULL;
}
int main(int argc, char *argv[]) {
#ifdef DEVTEST
item *head;
item *tail;
long count = 0;
#endif
// subroutines? subroutines? we don't need no stinkin' subroutines
// this is all the scoping you're going to need
// ... truuuuust me
/*
Allocate list[] and lookup[]. Set maxItems.
input -
argc
argv
side-effects -
list
lookup
maxItems
malloc()
DEVTEST stuff
*/
{
int c; // option character
maxItems = MAXITEMS;
while ((c = getopt(argc, argv, ":n:sv")) != -1) {
switch(c) {
#ifdef DEVTEST
case 'v':
// print some reassuring messages
printVerbose = true;
break;
#else
case 'v':
fprintf(stderr, "unknown option -%c\n", optopt);
usage(argv[0]);
exit(1);
break;
#endif
case 'n':
if (sscanf(optarg, "%ld", &maxItems) != 1) {
fprintf(stderr, "-n argument \"%s\" unscannable\n", optarg);
usage(argv[0]);
exit(1);
}
break;
case 's':
// use only one thread?
oneThread = true;
break;
case ':': // -s needs an argument
usage(argv[0]);
exit(1);
break;
case '?': // not a valid option
fprintf(stderr, "unknown option -%c\n", optopt);
usage(argv[0]);
exit(1);
break;
}
}
if ((maxItems<1) || (maxItems>MAXITEMS)) {
fprintf(stderr, "-s argument \"%ld\" out of range\n", maxItems);
usage(argv[0]);
exit(1);
}
list = (item *) malloc(sizeof(item) * maxItems);
if (list == NULL) {
fprintf(stderr, "ERROR: list = malloc() failure\n");
exit(1);
}
lookup = (item **) malloc(sizeof(item *) * maxItems);
if (lookup == NULL) {
fprintf(stderr, "ERROR: lookup = malloc() failure\n");
exit(1);
}
}
/*
Convert STDIN into an array of items.
input -
list
lookup
maxItems
side-effects -
list
lookup
listN
stdin
*/
{
long largestT = 0;
item x;
for (listN=0; scanf("%ld%ld%ld", &x.A, &x.B, &x.T)==3; listN++) {
if (listN == maxItems) {
fprintf(stderr, "ERROR: > %ld input items read\n", maxItems);
exit(1);
}
x.b = x.f = NULL;
x.unprinted = true;
x.BINb = x.BINf = NULL;
largestT = (x.T>largestT) ? x.T : largestT;
#ifdef DEVTEST
x.lineNumber = listN + 1;
#endif
list[listN] = x;
}
if (!feof(stdin)) {
fprintf(stderr, "ERROR: ferror() = %d\n", ferror(stdin));
exit(1);
}
// Be paranoid. Because cores are obnoxious.
if (largestT>=maxItems) {
fprintf(stderr, "ERROR: T:%ld > %ld \n", largestT, maxItems-1);
exit(1);
}
}
#ifdef DEVTEST
(printVerbose) && printf("in: %ld\n", listN);
#endif
// Short-circuit on 0 items. Simplifies things like finding the head.
if (listN == 0) {
exit(0);
}
/*
Populate the lookup table. Build a doubly linked list through it.
input -
list
lookup
listN
side-effects -
list[]
lookup[]
lookupN
DEVTEST stuff
*/
{
long n;
/*
Populate the lookup table. The lookup table is an array-of-lists.
The lists are LIFO. This is the most primitive of hashes, where the
key, item.T, is used as the index into the lookup table.
*/
for (n=0; n<maxItems; n++) {
lookup[n] = NULL;
}
for (n=0; n<listN; n++) {
long t = list[n].T;
if (lookup[t] == NULL) {
lookup[t] = &(list[n]);
} else {
// collision
list[n].f = lookup[t]; // forward pointer assigned
lookup[t] = &(list[n]);
}
}
/*
Collapse lookup to squeeze out NULL references. This breaks
the linear mapping between T value & lookup index, but worth it for
simpler search logic. Build a doubly linked list of bins.
*/
item *previousBin = NULL; // last non-NULL lookup entry
lookupN = 0;
for (n=0; n<maxItems; n++) {
if (lookup[n] != NULL) {
lookup[lookupN] = lookup[n];
lookup[lookupN]->BINb = previousBin;
if (previousBin) {
previousBin->BINf = lookup[lookupN];
}
previousBin = lookup[lookupN];
lookupN++;
}
}
previousBin->BINf = NULL;
/*
Build a doubly linked list. The forward pointers already exist
within each lookup table bin.
*/
item *p;
item *binHead;
item *previous;
// create a loop in each bin
for (n=0; n<lookupN; n++) {
#ifdef DEVTEST
count++;
#endif
binHead = lookup[n];
for (p=binHead; p->f; p=p->f) {
p->f->b = p;
#ifdef DEVTEST
count++;
#endif
}
p->f = binHead;
binHead->b = p;
}
// break the loops and connect them tail-to-head
#ifdef DEVTEST
head = lookup[0];
#endif
previous = NULL;
for (n=0; n<lookupN; n++) {
binHead = lookup[n];
p = binHead->b; // p => tail of this bin list
binHead->b = previous; // connect bin head to list
if (previous) { // connect list to bin head
previous->f = binHead;
}
previous = p;
}
previous->f = NULL;
#ifdef DEVTEST
tail = previous;
#endif
}
#ifdef DEVTEST
if (printVerbose) {
printf("out: %ld\n", count);
// run through the list forwards
item *p;
count = 0;
for (p=head; p; p=p->f) {
count++;
}
printf("forwards: %ld\n", count);
// run through the list backwards
count = 0;
for (p=tail; p; p=p->b) {
count++;
}
printf("backwards: %ld\n", count);
/*
// print the list
for (p=head; p; p=p->f) {
printf("%ld %ld %ld\n", p->A, p->B, p->T);
}
*/
}
#endif
/*
Find matches & print.
(authoritative statement)
Print item ( A B T ) if:
1 - there exists an item ( C D U ) such that 0 <= T-U < 100 and D == A
OR
2 - there exists an item ( C D U ) such that 0 <= U-T < 100 and B == C
TBD
- threading
input -
lookupN
side-effects -
lots hidden in walkTheseBins(), all thread-local or thread-safe
*/
{
volatile threadState tState[NTHREADS]; // use as cicular buffer
long h; // cicular buffer head
long n;
if (oneThread) {
tState[0].begin = 0;
tState[0].end = lookupN-1;
walkTheseBins((void *)tState);
} else {
// every slot has a thread to wait for
for (h=0; h<NTHREADS; h++) {
assert( pthread_create(&(tState[h].tid), NULL, initTID, NULL) == 0);
}
h = 0;
for (n=0; n<lookupN+BINSPERTHREAD; n+=BINSPERTHREAD) {
pthread_join(tState[h].tid, NULL);
tState[h].begin = n;
tState[h].end = n + BINSPERTHREAD - 1;
assert( pthread_create(&(tState[h].tid), NULL, walkTheseBins, (void *)(tState+h)) == 0);
h = (h + 1) % NTHREADS;
}
// wait for any remaining threads
for (h=0; h<NTHREADS; h++) {
pthread_join(tState[h].tid, NULL); // may have already join'ed some
}
}
}
return 0;
}
```
Compile with "gcc -m64 -pthreads -O". Expects input on stdin. Runs multi-threaded by default. Use "-s" option to use only one thread.
[Answer]
I finally got a chance to build a physical Ubuntu 14.04 system similar to Lembik's and do a post-mortem on my solution to this puzzle. In my choice of importance:
1. The true master is James\_pic, because he didn't optimize prematurely.
* he had a plan
* he executed the plan at a high level of abstraction (Scala) and refined it there
* he refined it further in C
* he didn't over-refine it (see next point)
2. File system I/O time is probably the lower-bound on elapsed time for the target system.
* Lembik alludes to this, i.e. "The winners ... both are almost as fast as wc!"
3. Some of the reasons my original solution ~~sucked~~ was non-performant:
* Locality of reference is the dominant factor on the target system.
* Sorting on A or B is a good idea when doing a hash sort. Sorting on T adds complexity (and cache-hostile indirection) to the hash sort, at least the way I did it.
* Scanf() is a pig.
* Massive bandwidth (disk->memory->cache) changes where the bottlenecks are. The target system doesn't have massive bandwidth. (see next point)
4. Rapid development works best if done in the target environment.
* Duh! But, I was stuck with Solaris/SPARC originally and couldn't play otherwise.
* It's difficult to eliminate caching effects in a virtualized and SAN environment.
* Linux VMs typically have the same issues.
5. A little bit of math helps.
* Fetching one tuple directly from the hash table cuts the probability of indirect references to ~37% (~1/e).
* Fetching two tuples directly from the hash table would have cut references to the overflow table to ~10%. It wasn't necessary.
6. The 32-bit memory model (gcc -m32) is a distraction.
* Sometimes a small win for unthreaded programs, sometimes a small loss.
* Sometimes a significant loss for threaded programs.
* If 32-bit is a significant win (and the target isn't an embedded controller), it's probably cheaper to refresh the hardware.
* Take the extra registers and larger address space and don't look back.
7. Scanf() is a pig, but using stdio is not hopeless.
* Most of scanf()'s overhead appears to be in the format-driven parsing and string to integer conversion.
* Replacing sscanf() with:
+ strtok() + atoi() is ~2x faster (see table below)
+ strtol() is ~3x faster
+ a custom, local strtol() is ~6.5x faster
+ replacing strtol() with a local solution puts it on par with "wc"
+ a FSM using getc\_unlocked() is almost as fast as Keith Randall's minimalist mmap() solution
+ the results of my experiments while re-implementing in C [in CSV, since Stack Exchange apparently doesn't do tables]:
```
"solution (64-bit unless noted)","disposition of input","user","system","elapsed"
"dd if=? of=/dev/null bs=1024k","","0.010","1.107","26.47"
"wc {LANG=C}","","4.921","0.752","26.38"
"","","","",""
"fscanf()","discard","13.130","0.490","26.43"
"fgets(), no integer conversion","discard","1.636","0.468","26.42"
"fgets() + sscanf()","discard","16.173","0.498","26.48"
"fgets() + strtok(), no integer conversion","discard","4.659","0.481","26.48"
"fgets() + strtok() + atoi()","discard","8.929","0.490","26.49"
"fgets() + strtol()","discard","6.009","0.483","26.50"
"fgets() + custom-strtol()","discard","3.842","0.474","26.43"
"fgets() + custom-strtol()","sort (load hash) while reading","7.118","1.207","26.70"
"fgets() + custom-strtol()","sort, match & print","10.096","1.357","28.40"
"fgets() + custom-strtol(), 32-bit","sort, match & print","10.065","1.159","28.38"
"","","","",""
"james_pic's solution","sort, match & print","9.764","1.113","28.21"
```
Rather than boring you with yet another FSM parser, the solution below uses fgets() and a local strtol() replacement [look for s2i()].
A reference implementation in Ruby:
```
#!/usr/bin/ruby2.0
# only tested against ruby v1.9 & v2.0
=begin
Filter a file based on these rules:
Input:
- each line is a set of three integers
- each line is formatted as <number> <w> <number> <w> <number>
- <w> is whitespace (a single blank in the challenge)
- <number> is an integer in the range 1..50_000_000
Output a given tuple ( A B T ) if:
- there exists a tuple ( C D U ) 0 <= T - U < 100 and D == A
OR
- there exists a tuple ( C D U ) 0 <= U - T < 100 and B == C
Typical use:
filter.rb test.input | sort | uniq > test.output
=end
list = Array.new
lookupB = Hash.new { |hash, key| hash[key] = Array.new }
ARGF.each_with_index do |line, index|
abt = line.split.map { |s| s.to_i }
list << abt
lookupB[abt[1]] << index
end
for abt in list do
for i in Array( lookupB[abt[0]] ) do
delta = abt[2] - list[i][2] # T - U
if (0<=delta) && (delta<100)
puts "#{abt.join(' ')}"
puts "#{list[i].join(' ')}"
end
end
end
```
It's a dog, ~50x slower than a C solution, but perl is just as slow and less concise.
The C solution:
```
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
// Throw caution, and error checking, to the winds.
// #include <assert.h>
#define RANGEMIN (1)
#define RANGEMAX (50*1000*1000)
#define SEARCHBOUNDARY (100)
typedef struct {
int A;
int B;
int T;
} tuple_t;
typedef struct bin {
tuple_t slot;
struct bin *next; // NULL=>0 items, self=>1 item, other=>overflow
} bin_t;
#define LISTSIZE (RANGEMAX)
tuple_t list[LISTSIZE];
#define HASH(x) (x-1)
#define LOOKUPSIZE (LISTSIZE)
bin_t lookup[LOOKUPSIZE];
bin_t overflow[LISTSIZE];
int overflowNext = 0;
// based on strtol()
static inline int s2i(char *s, char **r)
{
char c;
int l = 0;
do {
c = *s++;
} while (!isdigit(c));
do {
l = l * 10 + (c - '0');
c = *s++;
} while (isdigit(c));
*r = s - 1;
return l;
}
static inline void lookupInsert(tuple_t x)
{
bin_t *p = lookup + HASH(x.B);
if (p->next) {
overflow[overflowNext].slot = x;
overflow[overflowNext].next = (p->next == p) ? p : p->next;
p->next = overflow + overflowNext;
overflowNext++;
} else {
p->slot = x;
p->next = p;
}
}
static void printOverflow(bin_t * head, bin_t * tail)
{
if (head->next != tail) {
printOverflow(head->next, tail);
}
printf("%d %d %d\n", head->slot.A, head->slot.B, head->slot.T);
}
static inline void dumpLookupSortedOnB()
{
bin_t *p;
for (p = lookup; p < (lookup + LOOKUPSIZE); p++) {
if (p->next) {
printf("%d %d %d\n", p->slot.A, p->slot.B, p->slot.T);
if (p != p->next) {
printOverflow(p->next, p);
}
}
}
}
static inline void printIfMatch(tuple_t abt, tuple_t cdu)
{
int A, B, T;
int C, D, U;
A = abt.A;
D = cdu.B;
if (D == A) {
T = abt.T;
U = cdu.T;
if ((0 <= (T - U)) && ((T - U) < SEARCHBOUNDARY)) {
B = abt.B;
C = cdu.A;
printf("%d %d %d\n", A, B, T);
printf("%d %d %d\n", C, D, U);
}
}
}
static inline void printMatches(int n)
{
tuple_t *p;
for (p = list; p < (list + n); p++) {
bin_t *b = lookup + HASH(p->A);
if (b->next) {
bin_t *q;
printIfMatch(*p, b->slot);
for (q = b->next; q != b; q = q->next) {
printIfMatch(*p, q->slot);
}
}
}
}
static inline void overflowTattle(int n)
{
fprintf(stderr, "%d/%d items in overflow\n", overflowNext, n);
}
int main(int argc, char *argv[])
{
int n;
// initialize lookup[]
{
bin_t *p = lookup;
for (n = 0; n < LOOKUPSIZE; n++) {
p->next = NULL;
p++;
}
}
// read all tuples into list[] and insert into lookup[] & overflow[]
{
char line[64];
char *lp;
tuple_t *p = list;
for (n = 0; fgets(line, sizeof(line), stdin); n++) {
p->A = s2i(line, &lp);
p->B = s2i(lp, &lp);
p->T = s2i(lp, &lp);
lookupInsert(*p);
p++;
}
}
printMatches(n);
exit(0);
}
```
Compile with "gcc -O3 -std=c99 -Wall -m64".
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.