text
stringlengths 180
608k
|
---|
[Question]
[
I am standing at point `(0,0)` in a `H` x `W` map where the altitude is represented by digits, for example:
```
1132
2221
1230 # H = 3, W = 4
```
I'd like to experience the views from every peak, which in this case are the areas with altitude `3`. However, climbing up hills is not an easy task, and I am also running out of time.
# Challenge
The challenge is to find the quickest path to visit all the peaks and come back.
**Shortest program wins.**
## Input
* H, W - height and width of the map (Integers) (optional, may be a list/tuple or two separate integer inputs)
* The map, given as `H` sets of `W` digits (`0`-`9`), in any convenient format (2D list, string separated by newlines, etc.)
## Output
* Shortest time taken to visit every peak and come back to your starting point (Integer)
## Conditions
* The altitude of a given area is represented by a digit from `0` to `9`.
* The "peak" is defined by the area with the highest altitude.
* The path must both begin and end at the **top-left (0,0)** area.
* You can only move to areas adjacent to your current area, and you may not move diagonally.
+ It takes **3 minutes** to move from one area to another if there is no change in altitude.
+ It takes **11 minutes** to climb up; that is, moving from one area to another area that is exactly `1` unit higher.
+ It takes **2 minutes** to climb down; that is, moving from one area to another area that is exactly `1` unit lower.
+ **You cannot move** to areas that are more than `1` unit higher or lower than where you are. (You cannot go from an area with altitude `1` to an adjacent area with altitude, say, `3`)
* A path to all the peaks is guaranteed
* Maximum number of peaks is `15`.
# Samples
## Input
```
4 5
32445
33434
21153
12343
```
## Output
```
96
```
## Explanation
You start at the top-left `3`. You have to visit the two `5`s that are located at `(0,4)` and `(3,3)` and come back to the `3` at `(0,0)` in the shortest time possible.
```
3 2 4->4->5
V ^
3->3->4 3 4
2 1 1 5 3
1 2 3 4 3 # 3 + 3 + 11 + 3 + 3 + 11 = 34 minutes to visit 1st peak
3 2 4 4 5
V
3 3 4 3 4
V
2 1 1 5 3
^ V
1 2 3 4<-3 # 2 + 2 + 3 + 11 + 11 = 29 minutes to visit 2nd
3 2 4 4 5
^
3 3 4 3 4
^
2 1 1 5 3
^ V
1<-2<-3<-4 3 # 2 + 2 + 2 + 2 + 11 + 11 + 3 = 33 minutes to come back
# 34 + 29 + 33 = 96 minutes total is the answer
```
## Input
```
2 7
6787778
5777679
```
## Output
```
75
```
[Answer]
# Mathematica ~~745~~ 681 bytes
The basic idea is to make a weighted graph of possible moves. Weights are the time it takes to move from one place to the next. The path with the least weight will be the quickest.
The input digits are placed in an r by c (rows by columns) rectangular array and then three distinct representations come into play: (1) an r by c grid graph, where each vertex corresponds to a cell in the array, (2) (r*c) by (r*c) weighted adjacency matrix that holds weights corresponding to the time it takes (2, 3, or 11 minutes) to move from one location (in the grid graph) to another, and (3) a directed, weighted adjacency graph constructed from the matrix.
The grid graph helps determine which cells (i.e. which vertices) are possibly reachable from each vertex--"possibly reachable" because a neighboring cell must not only be right, left, above or below a given cell. It's value must also be within 1 unit of distance from the neighbor (e.g., a 3 does not connect to a neighboring 5 or a 1). If vertex `a` is not connected to vertex `b` then the adjacency matrix cells {a,b} and {b,a} will have a value of ∞. Accordingly, the weighted adjacency graph will not have an edge from a to b, nor from b to a.
The weighted adjacency graph serves to determine the minimum distance (`GraphDistance`) and shortest route between any vertices. The optimal path must begin with 1, touch each of the peaks, and return to 1. In this case, "shortest route" is not necessarily the one with the fewest moves. It is the one with the shortest overall time, measured in edge weights.
---
## Golfed
```
o=Sequence;v[a_<->b_,z_]:=(m_~u~q_:={Quotient[m-1,q[[2]]]+1,1+Mod[m-1, q[[2]]]};j=z[[o@@u[a,i=Dimensions@z]]];k=z[[o@@u[b,i]]];Which[j==k,{{a,b}->3,{b,a}->3},j==k-1,{{a,b}->11,{b,a}->2},j==k+1,{{a,b}->2,{b,a}->11},2<4,{{a,b}->∞, {b, a}->∞}]);w@e_:=Module[{d,x,l,y},x=Map[ToExpression,Characters/@Drop[StringSplit@e,2],{2}];d_~l~c_:=d[[2]](c[[1]]-1)+c[[2]];g_~y~p_:=(Min[Plus@@(GraphDistance[g,#,#2]&@@@#)&/@(Partition[#,2,1]&/@({1,o@@#,1}&/@Permutations@p))]);y[WeightedAdjacencyGraph[ReplacePart[ConstantArray[∞,{t=Times@@(d=Dimensions@x),t}],Flatten[#~v~x &/@Union@Flatten[EdgeList[GridGraph@Reverse@d,#<->_]&/@Range@(Times@@d),1],1]]], l[Dimensions@x, #] & /@ Position[x, Max@x]]
```
---
## Longer, more readable form
```
(*determines a weight (number of minutes) to go from vertex a to b and from b to a*)
weight[a_ <-> b_, dat_]:=
Module[{cellA,cellB,dim,valA,valB,vertexToCell},
(*Convert graph vertex index to cell location*)
vertexToCell[m_,dimen_]:={Quotient[m-1,dim[[2]]]+1,1+Mod[m-1,dimen[[2]]]};
dim=Dimensions[dat];
cellA = vertexToCell[a,dim];
cellB = vertexToCell[b,dim];
valA=dat[[Sequence@@cellA]];
valB=dat[[Sequence@@cellB]];
Which[
valA==valB,{{a,b}-> 3,{b,a}-> 3},
valA==valB-1,{{a,b}-> 11,{b,a}-> 2},
valA==valB+1,{{a,b}-> 2,{b,a}-> 11},
2<4,{{a,b}->∞,{b,a}->∞}]];
(* weights[] determines the edge weights (times to get from one position to the next), makes a graph and infers the shortest distance
from vertex 1 to each peak and back. It tries out all permutations of peaks and
selects the shortest one. Finally, it returns the length (in minutes) of the shortest trip. *)
weights[str_]:=
Module[{d,dat,neighbors,cellToVertex,peaks,z,gd},
dat=Map[ToExpression,Characters/@Drop[StringSplit[str],2],{2}];
cellToVertex[dim_,cell_]:=dim[[2]] (cell[[1]]-1)+cell[[2]];
peaks[dat_]:= cellToVertex[Dimensions[dat],#]&/@Position[dat,peak =Max[dat]];
(* to which cells should each cell be compared? neighbors[] is a function defined within weights[]. It returns a graph, g, from which graph distances will be derived in the function gd[] *)
neighbors[dim_]:=
Union@Flatten[EdgeList[GridGraph[Reverse@dim],#<->_]&/@Range@(Times@@dim),1];
d=Dimensions[dat];
m=ReplacePart[ConstantArray[∞,{t=Times@@d,t}],
(*substitutions=*)
Flatten[weight[#,dat]&/@neighbors[d],1]];
g=WeightedAdjacencyGraph[m,VertexLabels->"Name",ImageSize->Full,GraphLayout->"SpringEmbedding"];
(* finds shortest path. gd[] is also defined within weights[] *)
gd[g3_,ps_]:=
Module[{lists,pairs},
pairs=Partition[#,2,1]&/@({1,Sequence@@#,1}&/@Permutations@ps);
Min[Plus@@(GraphDistance[g3,#,#2]&@@@#)&/@pairs]];
gd[g,peaks[dat]]]
```
---
## Tests
```
weights["4 5
32445
33434
21153
12343"]
```
96.
---
```
weights@"2 7
6787778
5777679"
```
75.
---
```
weights@"3 4
1132
2221
1230"
```
51.
---
## Explanation
Think of lines 2-5 of the following input
```
"4 5
32445
33434
21153
12343"
```
as representing an array with 4 rows and 5 columns:
[](https://i.stack.imgur.com/TgFyk.png)
where each vertex corresponds to a digit from the input array: 3 is at vertex 1, 2 is at vertex 2, 4 is at vertex 3, another 4 at vertex 4, 5 at vertex 5, etc. The grid graph is only a rough approximation of the graph we are aiming for. It is undirected. Furthermore, some of the edges will be unavailable. (Remember: we cannot move from a position to another that is more than 1 height unit above or below the current one.) But the grid graph let's us easily find those vertices that are next to any chosen vertex. This reduces the number of edges we need to consider, in the first example (a 4 by 5 grid), from 400 (20 \* 20) to 62 (31 \*2 is the number of edges in the grid graph). In the same example, only 48 of the edges are operative; 14 are not.
The following 20 by 20 weighted adjacency matrix represents the distance between all pairs of vertices from the grid graph.
The key code which decides on which number to assign is below.
```
Which[
valA==valB,{{a,b}-> 3,{b,a}-> 3},
valA==valB-1,{{a,b}-> 11,{b,a}-> 2},
valA==valB+1,{{a,b}-> 2,{b,a}-> 11},
2<4,{{a,b}->∞,{b,a}->∞}]
```
Cell {1,2}--in one-indexing-- contains the value 2 because the move from vertex 1 to vertex 2 is downhill.
Cell {2,1} contains 11 because the move from vertex 2 to vertex 1 is uphill.
The 3's in cells {1,6} and {6,1} signify that the movement is neither up nor down.
Cell {1,1} contains ∞ because it is not connected to itself.
[](https://i.stack.imgur.com/ftNYH.png)
The following graph shows the structure underlying the above input. The colored arrows show the optimal path from vertex 1 to the peaks (at 5 and 14) and back to 1. Blue arrows correspond to moves at the same level (3 min); red arrows mean ascent (11 min.) and green arrows indicate descent (2 min).
[](https://i.stack.imgur.com/pqnk0.png)
The path from vertex 1 (cell {1,1} to the two peaks and back to vertex 1:
```
3 + 3 + 11 + 3 + 3 + 11 + 2 + 2 + 3 + 11 + 11 + 2 + 2 + 2 + 2 + 11 + 11 + 3
```
96
[Answer]
# Pyth, 92 bytes
```
[[email protected]](/cdn-cgi/l/email-protection),bhS,@Gb+@G,hbH@G,HebG[FQ.dm,(Fb?|tsaMCb>[[email protected]](/cdn-cgi/l/email-protection)@[3hT2)J*QQC.<B+]hSQd1.p.M@Q
```
The input format is a dict mapping coordinates to heights: `{(0, 0): 3, (0, 1): 2, (0, 2): 4, …}`. This finds the fastest paths between all pairs of points using the [Floyd–Warshall algorithm](https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm), then minimizes the total time of the desired cycle over all permutations of peaks.
[Try it online](https://pyth.herokuapp.com/?code=hSms%40Lu.dm%2CbhS%2C%40Gb%2B%40G%2ChbH%40G%2CHebG%5BFQ.dm%2C%28Fb%3F%7CtsaMCb%3E.aJ-F%40LQb1.n4%40%5B3hT2%29J%2aQQC.%3CB%2B%5DhSQd1.p.M%40Q&test_suite=1&test_suite_input=%7B%280%2C0%29%3A3%2C%280%2C1%29%3A2%2C%280%2C2%29%3A4%2C%280%2C3%29%3A4%2C%280%2C4%29%3A5%2C%281%2C0%29%3A3%2C%281%2C1%29%3A3%2C%281%2C2%29%3A4%2C%281%2C3%29%3A3%2C%281%2C4%29%3A4%2C%282%2C0%29%3A2%2C%282%2C1%29%3A1%2C%282%2C2%29%3A1%2C%282%2C3%29%3A5%2C%282%2C4%29%3A3%2C%283%2C0%29%3A1%2C%283%2C1%29%3A2%2C%283%2C2%29%3A3%2C%283%2C3%29%3A4%2C%283%2C4%29%3A3%7D%0A%7B%280%2C0%29%3A6%2C%280%2C1%29%3A7%2C%280%2C2%29%3A8%2C%280%2C3%29%3A7%2C%280%2C4%29%3A7%2C%280%2C5%29%3A7%2C%280%2C6%29%3A8%2C%281%2C0%29%3A5%2C%281%2C1%29%3A7%2C%281%2C2%29%3A7%2C%281%2C3%29%3A7%2C%281%2C4%29%3A6%2C%281%2C5%29%3A7%2C%281%2C6%29%3A9%7D)
] |
[Question]
[
[Dowker notation](http://katlas.math.toronto.edu/wiki/DT_(Dowker-Thistlethwaite)_Codes) is a common way of representing mathematical knots.
Dowker notation can be derived from a knot diagram in the following way (based on the description from [the wikipedium](https://en.wikipedia.org/wiki/Dowker_notation)):
>
> We will label each of the \$n\$ intersections with two numbers whose absolute value is on the range \$1, \dots 2n\$ (one odd one even). To do this choose an arbitrary starting point and direction on the knot and begin traversing from there. At every intersection encountered label the intersection \$m\$ where \$m\$ is one more than the number of intersections already encountered (e.g. the first intersection is labeled 1, the second 2 etc.). However, if \$m\$ is even and the strand being followed passes over instead label the intersection with \$-m\$. We do this until we reach the starting point again, at which point every intersection should have two labels.
>
>
>
>
> Now that each intersection is labeled we create a list of the even labels, sorted by their corresponding odd label (in ascending order). You could also think of this as the order we traversed the intersections skipping every other intersection.
>
>
>
>
> This list is our Dowker notation
>
>
>
Consider this example knot:

*Taken with permission from wikipedia user [Frentos](https://en.wikipedia.org/wiki/User_talk:Frentos)*
If we traverse the pairs as indicated in the diagram we get the following labels:
```
(1, 6) (3, −12) (5, 2) (7, 8) (9, −4) (11, −10)
```
This gives us a Dowker notation of
```
[6, -12, 2, 8, -4, -10]
```
Your task is to take two knots in Dowker notation and determine if they are isotopic (the same knot represented in different ways).
Two knots are isotopic if you can rearrange one into the other without crossing it through itself.
The [Reidemeister moves](https://en.wikipedia.org/wiki/Reidemeister_move) can be used to determine whether two diagrams contain isotopic knots.
# Input
Dowker notation is actually the name given to a couple of related ways of representing knots. There are a couple of permissable modifications you can make to the format:
* You may choose to represent integers as a tuple of a boolean and a positive integer, where the boolean's value represents sign of the original number and the positive integer its magnitude.
e.g.
```
-5 -> (True, 5)
14 -> (False, 14)
```
* Since the values in Dowker notation are always even you can choose to have them all divided by 2.
If we use our example from earlier:
```
[6, −12, 2, 8, −4, −10]
=>
[3, -6, 1, 4, -2, -5]
```
You may make any combination of these modifications to your input format. Of course your input format must be consistent.
# Output
Your code should output one of two distinct consistent values. One of these should always be output when the notations represent the same knot and the other should always be output when the notations represent different knots.
# Scoring
This is code-golf answers will be scored in bytes with fewer bytes being better.
# Test cases
## The same
```
-- Reidemeister move I
[6, -12, 2, 8, -4, -10] [6, -8, 2, -4]
-- Reidemeister move II
[4, 6, 2] [8, 6, 10, -2, 4]
-- Mirror
[6, -12, 2, 8, -4, -10] [-6, 12, -2, -8, 4, 10]
-- Change of starting location
[6, -12, 2, 8, -4, -10] [4, -6, 10, -2, -8, 12]
-- Two trefoils
[4, 6, 2] [ 6, -8, 2, -4]
```
## Different
```
-- Unknot and trefoil
[] [4, 6, 2]
-- Trefoil and figure 8
[4, 6, 2] [6, 8, 2, 4]
```
[Answer]
# JavaScript (ES2020), ~~736~~ ~~730~~ 720 bytes
*-3 thanks to Kevin Cruijssen*
*-10 thanks to Neil*
```
(t,e,l="slice",n=0)=>(f=(t,e=Object.assign([],Object.fromEntries(t[a="map"](((a,f)=>[2*f,a<0?-a:a,a>0])).flatMap((([a,f,p])=>[[a,[--f,p]],[f,[a,!p]]])))))=>n=(f[(e.map((a=>e.find((([a,f],p)=>a==p+1?e=[...e[l](0,p),...e[l](p+2)].map((([a,f])=>[a-2*(a>p),f])):p<a&&a==e[p+1][0]+1&e[p+1][1]==f?e=[e[l](0,p),e[l](p+2,a-1),e[l](a+1)].flat().map((([f,m])=>[f-2*(f>p)-2*(f>a),m])):0)))),e)]||(f[e]=t,f(t,[...e[l](1),...e[l](0,1)].map((([a,f])=>[(a||e.length)-1,f]))),f(t,e.map((([a,f])=>[a,!f]))),(m=[1,-1]).map((a=>m.map((m=>e.map((([e,l],n,[...o],s=o[n+1]?.[0])=>s+1&&l==o[n+1][1]&s+m===o[e+a]?.[0]&&f(t,o,[o[n],o[n+1],o[e],o[e+a],o[s],o[s+m]]=[[s+m,l],[e+a,l],[s,p=o[e+a][1]],[n+1,!l],[e,!p],[n,!l]]))))))),t))!=t|n)(t)|f(e)
```
```
input.value="# interactive; edit or add lines and the annotation will update\n\n# isotopic\n[6, -12, 2, 8, -4, -10] [6, -8, 2, -4]\n[4, 6, 2] [8, 6, 10, -2, 4]\n[6, -12, 2, 8, -4, -10] [-6, 12, -2, -8, 4, 10]\n[6, -12, 2, 8, -4, -10] [4, -6, 10, -2, -8, 12]\n[4, 6, 2] [6, -8, 2, -4]\n[] [2]\n[2] []\n[2] [2]\n[] [6, 4, 2]\n[] [6, -4, 2]\n[] []\n\n# not isotopic\n[] [4, 6, 2]\n[] [6, -8, 2, -4]\n[2] [6, -8, 2, -4]\n[6, -4, 2] [6, -8, 2, -4]";(input.onchange=input.oninput=()=>{input.style.minHeight="1px";input.style.minHeight = (input.scrollHeight)+"px";output.textContent=input.value.split("\n").map(x=>{if(!x.trim()||x.startsWith("#"))return"";let M=/^(\[\s*((?:-?\d+\s*,\s*)*-?\d+\s*)?\]) (?:\[\s*((?:-?\d+\s*,\s*)*-?\d+\s*)?\])$/.exec(x);if(M){let[A,B]=[M[2],M[3]].map(x=>x?x.trim().split(/\s*,\s*/).map(x=>+x):[]);try{f=(
(t,e,l="slice",n=0)=>(f=(t,e=Object.assign([],Object.fromEntries(t[a="map"](((a,f)=>[2*f,a<0?-a:a,a>0])).flatMap((([a,f,p])=>[[a,[--f,p]],[f,[a,!p]]])))))=>n=(f[(e.map((a=>e.find((([a,f],p)=>a==p+1?e=[...e[l](0,p),...e[l](p+2)].map((([a,f])=>[a-2*(a>p),f])):p<a&&a==e[p+1][0]+1&e[p+1][1]==f?e=[e[l](0,p),e[l](p+2,a-1),e[l](a+1)].flat().map((([f,m])=>[f-2*(f>p)-2*(f>a),m])):0)))),e)]||(f[e]=t,f(t,[...e[l](1),...e[l](0,1)].map((([a,f])=>[(a||e.length)-1,f]))),f(t,e.map((([a,f])=>[a,!f]))),(m=[1,-1]).map((a=>m.map((m=>e.map((([e,l],n,[...o],s=o[n+1]?.[0])=>s+1&&l==o[n+1][1]&s+m===o[e+a]?.[0]&&f(t,o,[o[n],o[n+1],o[e],o[e+a],o[s],o[s+m]]=[[s+m,l],[e+a,l],[s,p=o[e+a][1]],[n+1,!l],[e,!p],[n,!l]]))))))),t))!=t|n)(t)|f(e)
);let r=f(A,B);return" ".repeat(M[1].length)+(r?"=":"≠")}catch(e){}}return" ".repeat(x.length+1)+"?"}).join("\n")})()
```
```
#input{width:100%;height:100%;border:0;outline:0;padding:5px}body,html{width:100%;height:100%;margin:0}body{overflow:auto}*{box-sizing:border-box}#output{position:absolute;pointer-events:none;top:0;left:0;padding:5px;white-space:pre;opacity:.5}#input,#output{font-family:monospace;font-size:15px;overflow:hidden}
```
```
<div id="output"></div><textarea id="input"></textarea>
```
## Ungolfed / Explanation
```
// First, we'll convert the dowker notation to a more convenient format:
// Original:
// 6, -12, 2, 8, -4, -10
// Reconstruct the pairs:
// (1,6), (3,-12), (5,2), (7,8), (9,-4), (11,-10)
// Add in the even pairs:
// (1,6), (2,-5), (3,-12), (4,-9), (5,2), (6,-1), (7,8), (8,-7), (9,-4), (10,11), (11,-10), (12,3)
// Extract the sign:
// (1,6,+), (2,5,-), (3,12,-), (4,9,-), (5,2,+), (6,1,-), (7,8,+), (9,4,-), (10,11,+), (11,10,-), (12,3,+)
// Zero-index:
// (0,5,+), (1,4,-), (2,11,-), (3,8,-), (4,1,+), (5,0,-), (6,7,+), (8,3,-), (9,10,+), (10,9,-), (11,2,+)
// Convert to array: [
// [5, true],
// [4, false],
// [11, false],
// [8, false],
// [1, true],
// [0, false],
// [7, true],
// [6, false],
// [3, false],
// [10, true],
// [9, false],
// [2, true],
// ]
function dowkerToKnot(dowker) {
return Array.from({
// Twice as many pairs
length: dowker.length * 2,
...Object.fromEntries(
dowker
.map((x, i) => [i * 2, Math.abs(x) - 1, Math.sign(x) == 1])
.flatMap(([a, b, x]) => [
[a, [b, x]],
[b, [a, !x]],
])
),
});
}
// Continually simplify using Reidemeister moves I and II
function simplify(knot) {
let prev;
while (prev !== (prev = knot)) {
for (let a of knot.keys()) {
/* Reidemeister move I */ {
// Reidemeister move I resolves simple twists like
// \ _
// a↘\ / \
// /↙a+1 |
// / \ _ /
// /
// This can be expressed by the condition:
// a' = a + 1 [where x' is the other number associated with the crossing at x]
if (knot[a][0] /* a' */ === a + 1) {
knot = [
...knot.slice(0, a), // the crossings before the loop
...knot.slice(a + 2), // the crossing after the loop
].map(([x, o]) => [x > a ? x - 2 : x /* adjust the indices */, o]);
break;
}
}
/* Reidemeister move II */ {
// Reidemeister move II resolves strings tucked under/over another like
// \ |
// a↘\|
// |↑b+1
// |\
// | |
// | |
// |/↙a+1
// b↑|
// /|
// / |
// This can be expressed as the conditions:
// b' = a+1
// a' = b+1
// #a = #(a+1) [where #x is the over/under sign associated with x]
let b = knot[a + 1]?.[0]; // (b = (a+1)' is the same as b' = a+1)
if (
a < b /* a and b are symmetric, so this dedupes */ &&
knot[a][1] /* #a */ === knot[a + 1][1] /* #(a+1) */ &&
knot[a][0] /* a' */ === b + 1
) {
knot = [
...knot.slice(0, a) /* before a */,
...knot.slice(a + 2, b) /* between a and b (we know that a < b) */,
...knot.slice(b + 2) /* after b */,
].map(([x, a]) => [
x - (x > a) * 2 - (x > b) * 2 /* adjust indices */,
a,
]);
break;
}
}
}
}
return prev;
}
// Applies manipulations to a given knot, calling processKnot for every resulting knot.
// Manipulations include:
// - Shifting the starting location
// - Mirroring
// - Reidemeister move III
function manipulate(knot, processKnot) {
// Shift the starting location by 1
if (knot.length)
processKnot(
knot
.slice(1)
.concat([knot[0]]) /* cycle the crossings */
.map(([a, b]) => [(a || knot.length) - 1 /* adjust indices */, b])
);
// Mirror
processKnot(knot.map(([a, b]) => [a, !b /* reverse over/under */]));
/* Reidemeister move III */ {
// Reidemeister move III moves a string across a crossing:
// \ / \ /
// \ / -------------
// \ / \ /
// / → /
// / \ / \
// ------------- / \
// / \ / \
// Let's label the crossings in the original:
// \ /
// \ /
// \ /
// b+1↗/↖c+1
// / \
// a→ / \ →a+1
// ---------------
// b↗/ \↖c
// / \
// This can be expressed with the following conditions:
// b = a'
// c = (a+1)'
// (b+1)' = c+1
// #a = #(a+1)
// Now, the b and c strings could go in either direction.
// Here's another example, with b reversed (note b-1):
// \ /
// \ /
// \ /
// b-1↙/↖c+1
// / \
// a→ / \ →a+1
// ---------------
// b↙/ \↖c
// / \
// Thus, we'll generalize the conditions as follows, where B and C are each either 1 or -1:
// b = a'
// c = (a+1)'
// (b+B)' = c+C
// #a = #(a+1)
for (let B of [1, -1])
for (let C of [1, -1])
for (let a of knot.keys()) {
let b = knot[a][0];
// Edge case: a + 1 might not exist, as it could wrap around the array.
// This is fine, as it will be handled by one of the knots with a shifted starting location.
let c = knot[a + 1]?.[0];
if (
c != null &&
knot[a][1] /* #a */ === knot[a + 1][1] /* #(a+1) */ &&
knot[b + B]?.[0] /* (b+B)' */ === c + C
) {
// Now that we've identified a location to apply this manipulation,
// we need to determine how to modify the knot.
// Here's the original knot, again (this uses B=1 and C=1, but is generally applicable):
// \ /
// \ /
// \ /
// b+1↗/↖c+1
// / \
// a→ / \ →a+1
// ---------------
// b↗/ \↖c
// / \
// This needs to be transformed to:
// \ /
// \ /
// ---------------
// \ /
// \ /
// /
// / \
// / \
// / \
// Labeling the crossings, we get:
// \ /
// a→ \ / →a+1
// ---------------
// c+1↖\ /↗b+1
// \ /
// b↗/↖c
// / \
// / \
// / \
let newKnot = [...knot];
newKnot[a] = [c + C, knot[a][1]];
newKnot[a + 1] = [b + B, knot[a][1]];
newKnot[b] = [c, knot[b + B][1]];
newKnot[b + B] = [a + 1, !knot[a][1]];
newKnot[c] = [b, !knot[b + B][1]];
newKnot[c + C] = [a, !knot[a][1]];
processKnot(newKnot);
}
}
}
}
// We can finally checks if two knots are equal!
function isotopic(a, b) {
// We'll track the result in this variable.
let result = false;
// First, we're going to create an empty object to serve as a record.
// This will serve as a dictionary from knots to either "a" or "b".
let record = {};
function processKnot(knot, marker /* either "a" or "b" */) {
// Before doing anything with the knot, we'll first simplify it.
knot = simplify(knot);
// Then, we'll check to see if the record already has an entry for this knot.
let value = record[knot];
if (value === undefined) {
// We've never seen this knot; add it to the record.
record[knot] = marker;
// Process all of the knots we can make by manipulating this one.
manipulate(knot, newKnot => processKnot(newKnot, marker));
} else if (value === marker) {
// We've already seen this knot for this marker, so we don't need to do anything.
} else {
// We've already seen this knot, but for a different marker.
// This means that both original knots (a and b) are isotopic to this knot.
// By transitivity, they're isotopic to each other as well.
result = true;
}
}
processKnot(a, "a");
processKnot(b, "b");
return result;
}
function main(a, b) {
// Convert each of a and b to our format and then check if they're isotopic.
return isotopic(dowkerToKnot(a), dowkerToKnot(b));
}
```
] |
[Question]
[
Trigonometry has LOTS of identities. So many that you can expand most functions into sines and cosines of a few values. The task here is to do that in the fewest bytes possible.
# Identity list
Well, the ones we're using here.
```
sin(-x)=-sin(x)
sin(π)=0
cos(-x)=cos(x)
cos(π)=-1
sin(a+b)=sin(a)*cos(b)+sin(b)*cos(a)
cos(a+b)=cos(a)cos(b)-sin(a)sin(b)
```
For the sake of golfing, I've omitted the identities that can be derived from these. You are free to encode double-angles and such but it may cost you bytes.
# Input
* You should take in an expression as a string with an arbitrary number of terms consisting of a coefficient and some sine and cosine functions, each with an exponent and an arbitrary number of arguments.
* Coefficients will always be nonzero integers.
* Each argument will be a coefficient, followed by either a single latin letter or pi.
* You can decide whether to take in pi as `pi` or `π`. Either way remember that you're scored in bytes, not characters.
# Output
Output the same expression, but…
* All trig functions are either `sin` or `cos`.
* All arguments of trig functions are single variables, with no coefficients.
* All like terms are combined.
* Terms with a coefficient of 0 are removed.
* All factors in the same term that are the same function of the same variable are condensed into a single function with an exponent.
Note: Leading `+` signs are allowed, but not required. `a+-b` is allowed, and equivalent to `a-b`. If there are no terms with nonzero coefficients, then output either `0` or an empty string.
# Worked Example
We'll start with `sin(-3x)+sin^3(x)`. The obvious first thing to do would be to deal with the sign using the parity identity, leaving `-sin(3x)`. Next I can expand `3x` into `x+2x`, and apply the sine additive identity recursively:
```
-(sin(x)cos(2x)+cos(x)sin(2x))+sin^3(x)
-(sin(x)cos(2x)+cos(x)(sin(x)cos(x)+sin(x)cos(x)))+sin^3(x)
```
Next, some distributive property and like terms:
```
-sin(x)cos(2x)-2cos^2(x)sin(x)+sin^3(x)
```
Now, I expand the `cos(2x)` and apply the same reduction:
```
-sin(x)(cos(x)cos(x)-sin(x)sin(x))-2cos^2(x)sin(x)+sin^3(x)
-sin(x)cos^2(x)+sin^3(x)-2cos^2(x)sin(x)+sin^3(x)
2sin^3(x)-3sin(x)cos^2(x)
```
And now, it's finished!
# Test Cases
In addition to the following, all of the individual identities (above) are test cases. Correct ordering is neither defined nor required.
```
cos(2x)+3sin^2(x) => cos^2(x)+2sin^2(x)
sin(-4x) => 4sin^3(x)cos(x)-4sin(x)cos^3(x)
cos(a+2b-c+3π) => 2sin(a)sin(b)cos(b)cos(c)-sin(a)sin(c)cos^2(b)+sin(a)sin(c)sin^2(b)-cos(a)cos^2(b)cos(c)+cos(a)sin^2(b)cos(c)-2cos(a)sin(b)cos(b)sin(c)
sin(x+674868986π)+sin(x+883658433π) => 0 (empty string works too)
sin(x+674868986π)+sin(x+883658434π) => 2sin(x)
```
…and may the shortest program in bytes win.
[Answer]
# [Bracmat](https://github.com/BartJongejan/Bracmat), 221 bytes
```
(P=F v a b.!arg:((sin|cos):?F.?v)&(!v:@&(!F.!v)|!F$!v)|!arg:%?a_%?b&(P$!a)_(P$!b)|!arg)&(f=i a b n u.1+(!arg:e^(?n*((i|-i):?i)*?u+?b)&(!i*(sin.!u)+(cos.!u))^!n*f$(e^!b)|!arg:%?a_%?b&(f$!a)_(f$!b)|!arg)+-1)&(Z=.f$(P$!arg))
```
[Try it online!](https://tio.run/##jY7NboMwEITvfQosEbK2haUESl0k5J4455wDkY0gtdRCxF858O7UBlKuvXhXszPzWTUy/5bdPMMlSZ3BkY5iSDb3GKDV1ZTXLY5FysSAPUBD/GHelKEBTyh1l2G9ByFvB6E8uLhI4psdaj2ZVJlo2@pUTs9OFJZAkYGoCICefG36NSaip0JZhiYWzFCPKRi6XXCGKlK6UGTP2p1YrsRyJ1L/ZHquCTMJ@x8j4fnn8@sI96I7xqIYH03RtrquvLrv3KuLdgXPC/xMRvyy0NfNan5gVrqsI86C/UwD8lTPmzX8y0t6Jsr8iOTG9tBb10ijt5BH/J1HVtxaKedB9MrD4P/OcHH@Ag "Bracmat – Try It Online")
[Answer]
# Python3, 841 bytes
Longer than I hoped, but the logic is straightforward.
```
E=enumerate
S,O='sin','cos'
def f(e):
e=[[(a,b,[([1,-1][j<0]*([1,j]['pi'==C]),C)for j,C in c for _ in range(1,abs(j)+1 if'pi'!=C else 2)],d)for a,b,c,d in i]for i in e]
P=1
while P:
P=0
for i,a in E(e):
F=0
for I,A in E(a):
if len(A[2])>1:q,*w=A[2];l=[[(A[0],S,[q],1),(1,O,w,1)],[(A[0],S,w,1),(1,O,[q],1)]]if S==A[1]else[[(A[0],O,[q],1),(1,O,w,1)],[(-1*A[0],S,[q],1),(1,S,w,1)]];l=[u+a[:I]+a[I+1:]for u in l];e=e[:i]+e[i+1:]+l;F=1;break
if F:P=1;break
r={}
for i in e:
R,T={},1
for a,b,[(C,V)],d in i:
if C==-1 and'sin'==b:a*=-1
if'pi'==V:
if(L:=[[1,-1][abs(C)%2],0][b==S])==0:R,T={},0;break
else:T*=L*a
else:R[(b,V)]=R.get((b,V),0)+d;T*=a
r[M]=r.get(M:=str(sorted(R.items())),0)+T
return' + '.join(str(b)+''.join(f'{j}{["^"+str(l),""][l==1]}({k})'for(j,k),l in eval(a))for a,b in r.items()if b)
```
[Try it online!](https://tio.run/##tVTdbtowFL7PU3igKTZxKkwyxsI8qUKtVKlVK6h6Y7lTAqYNTUMbYDAhpL3hHokd2yTQtap2sxvr/H7nOz/J08/5/TQPOk/FdnvCVb54VEU8V86AXnJ3luYudYfTmeuM1BiNsSKRgxQXAsc0oQILRn0mxeRrUza0MpHCfUpdznuS0B4ZTws0oT2U5miItPJdi0Wc3ynMaJzM8IR4DKVjnfSB95DKZgq1iKQjk6uLDOlIJ6VSG1ItKumgK84ctLxPM4WugBLoTXhNCI110InlitCp8RjXGT22rti6oDDKVI6PRUuSbyx6po0l10o30y0ei6akAyqeJWWEAuFLugRJ0sq1rBw2SEpAHHDAYFK3UoJcvgnis8arEhZTGgYLLxbRmYT3zGOR6X@h@Weyq7gSUSo9JVLt8rLuKWfdpFDxg2P7Oo2u9paCrzcO2g9Qd9@n12ClbDc2u88evdHDNwOPdkg9zn2G4nxkzoHzJIobYLFeu@2bcpz4PILJ2aPQ6@2Rjy1Jm1IknA8k4bwZ7eo292zN1qPrBj9vxE6p9gVONBneP7pTc2wU2iTeqAuBOqwQF5IXxnkR8dm8wLNpMVcj3D9K5@pxhgkxCdfQvpovitxFHnKPJtM0xzo6IZ67U8fuerJZi9ptzdOejNBaTYqMcyY3eP2wIS5MCE/oA6GZmd@POIMbKk/U3HRZFAaWkK1jvhFGkf2EECw7AGXlwnSR3f6hk1W@AHaP6mCHhBXxQLgN8Io4T0Waz7H@AAmqt0qzH@jIFYEv9Lalw2xmCNJrAuEhAfkSMSwRAUnjhntcU96pa0fstRJ/6AW/fx3g679D2UPsEopwC6TESL4JMKJuH27l7fK6IRiofhNDwb5D4u8dw12XiZlKZdTEtdE3BKsYm@5ZYxmzw2xV1qqaxXLs/FZe@3PYaXe@dNrQqWdNnU7Q/tQJg5fN/7VA6LNKfdFvGfM6vsJ9bz6u@y/Uwv9ELXyPWhVkKwfUAh3eA6vuYXcO9ld5iFMm72mURff3tCuP6u3DzR2ibP8A)
] |
[Question]
[
>
> [There is fairly strong support on meta](http://meta.codegolf.stackexchange.com/a/8906/8478) for challenge-writing questions to be on topic on main, provided these questions are specific and answerable. However, we don't have any such questions yet, so I figured I'd test the waters. This question is probably entering [good subjective, bad subjective](https://blog.stackoverflow.com/2010/09/good-subjective-bad-subjective/) territory, but I think that's likely what challenge-writing questions will have to be. To ensure that they still generate high-quality content, please don't just post wild speculative ideas in the answers. Explain why they avoid the problems mentioned below, or ideally point to existing challenges which have successfully used the suggested technique in the past.
>
>
>
For certain optimisation challenges, a free parameter in setting the challenge is the size of the problem to be optimised. By "optimisation challenge" I don't mean things like our [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") genre, where answers are usually required to be exact/optimal, and the challenge is scored either on a fixed problem size or on the largest problem size that can be handled in a fixed amount of time. I mean specifically challenges where suboptimal solutions to the underlying problem are allowed and even likely, and the goal is to do as well as possible.
For the sake of definiteness, consider [busy beaver](https://en.wikipedia.org/wiki/Busy_beaver) challenges, although in principle this applies to other challenge types without known optimal solutions as well (I'm just using busy beavers here because they exacerbate the problems mentioned below). Say, I wanted to make a challenge about finding the busiest Brainfuck beaver. The free parameter in busy beaver problems is the size of the code. I can't set the challenge without making reference to the code size in some way. In a way, each value of the problem-size parameter `N` gives a separate (increasingly difficult) challenge. My main question is how I can make such a challenge work without running into balancing problems.
The obvious solution is to fix `N`: "Find a terminating Brainfuck program with `N` bytes of source code which prints as many characters as possible/runs for as many ticks as possible." This has massive balancing issues: if I pick the size too small, someone might quickly find *the* busiest beaver and the challenge is over. If I pick the size too large, the optimal solution will print an astronomical amount of characters before terminating, which means that it will likely be trivial to find such programs and the challenge becomes a chore/exercise in patience — this also leaves the territory where busy beavers can be found programmatically, and instead people would need to start proving their results formally which a lot of people might not consider very fun. Of course, this problem is more pronounced in busy beaver challenges than other types, due to the growth of the optimal solutions, but it applies to other challenges nevertheless.
The next option would to leave `N` unconstrained and make it part of the scoring via some function. Even for "normal" challenges getting the balance of combined scores right is incredibly difficult, but in the case of busy beavers it's actually fundamentally impossible, due to the fact that optimal solutions grow faster with `N` than any computable function. That means I can always beat the best existing answer by going to a sufficiently large `N` where I can easily find a program that runs for so long that I can get a better score without much effort.
I have also considered setting a fixed `N` and allowing people to also submit beavers for larger `N` which will be used as successive tie breakers. This has a similar problem, in that someone can just "happen to find an equally good busy beaver" for a `N`, thereby creating a tie and then just submitting pretty much anything for the next `N` where finding a large score is easier (even if finding the optimal score gets harder). In these cases, how would you deal with multiple people using the same solution? Forbidding it would also be weird in case it's optimal.
Maybe one could strike a middle ground, by making an educated guess at a reasonable `N` and then asking for busy beavers for all sizes within (say) 5 bytes of `N`, so that there's some leeway in both directions (and then you combine the ~10 scores into a single one by one technique or another). This doesn't feel quite satisfactory either because my initial guess for `N` could still be widely off the range that makes for interesting challenges.
**TL;DR:** in cases where the challenge is to (suboptimally solve and) optimise a problem whose size is variable, how do I incorporate the size into the challenge? Ideally I would want people to be able to work with a value of `N` that is near the upper end of the range of tractable sizes. But just in case it turns out that optimal solutions are possible for that `N`, it would be great if solutions for slightly larger `N` would start to weigh in, such that the challenge could continue with a more interesting problem size.
[Answer]
# Find the next N
The challenge would indicate an `N` that submissions should start at.
Then, people would submit answers at the current `N`. If a given submission is proven to be optimal, then `N` is increased by 1, and the process repeats.
There are several ways to score this:
1. Score the best submission at the current `N`
2. Give a point to the best submission at the current `N`, plus a point for each optimal solution
3. Same as #2, but also give a point to the person that proved that a given submission was optimal.
[Answer]
# Give points for solutions within a bounded N
Allow `N` to be within a fixed bounds. The lower bound should exclude obviously trivial answers, and that the higher bound shouldn't be too far from the lower bound.
Then, give 1 point for each person that has the best solution for each `N` within the bounds. If higher `N` means that the solution is harder, then give N points to them. (or some formula based on N).
This method is similar to how [AZsPCs](http://azspcs.net/Contest/Tetrahedra) does it, but partial points aren't given.
] |
[Question]
[
As we learned from [The Holy Numbers](https://codegolf.stackexchange.com/questions/73426/the-holy-numbers), there are 5 holy digits (`0, 4, 6, 8, 9`), and positive integers consisting solely of those digits are holy. Additionally, the holiness of a number is the sum of the holes in the number (`+2` for every `0` or `8`, and `+1` otherwise).
Now, there is an additional property to take into consideration, to truly and accurately represent the holiness of a number. You see, it's not just the number of holes in the digit that matters, but also where in the number it occurs.
Consider the number `88`. By our old rules, it would have a holiness of `4`. But that's hardly fair! The `8` on the left is doing more work than the other `8` - 10 times the work! It should be rewarded for its work. We will reward it with extra holiness points equal to the total holiness of all the digits to its right (including the extra holiness points granted by this rule to the digits on its right), minus 1.
Here are more examples to take into consideration:
```
Number: 8080
Digital holiness: (2 + 7 - 1) + (2 + 3 - 1) + (2 + 1 - 1) + (2 + 0 - 1)
Total holiness: 15
Number: 68904
Digital holiness: (1 + 5 - 1) + (2 + 2 - 1) + (1 + 1 - 1) + (2 + 0 - 1) + (1 + 0 - 1)
Total holiness: 10
```
All of the digits are appropriately rewarded for their work with extra holiness, and all is well. We shall call this property "enhanced holarity".
In the great language Python, an algorithm for calculating enhanced holarity might look something like this:
```
# assumes n is a holy number
def enhanced_holarity(n):
if n < 10:
return 1 if n in [0, 8] else 0
else:
digits = list(map(int,str(n)[::-1]))
res = []
for i,x in enumerate(digits):
res.append(enhanced_holarity(x))
if i > 0:
res[i] += sum(res[:i])
return sum(res)
```
## The Challenge
Given an integer `n > 0`, output the first `n` Holy Numbers, sorted by ascending enhanced holarity, using numeric value as a tiebreaker. You may assume that the input and output will be no greater than the maximum representable integer in your language or `2^64 - 1`, whichever is less.
For reference, here are some test cases (input, followed by output):
```
25
4, 6, 9, 44, 46, 49, 64, 66, 69, 94, 96, 99, 0, 8, 84, 86, 89, 40, 48, 60, 68, 90, 98, 80, 88
100
4, 6, 9, 44, 46, 49, 64, 66, 69, 94, 96, 99, 444, 446, 449, 464, 466, 469, 494, 496, 499, 644, 646, 649, 664, 666, 669, 694, 696, 699, 0, 8, 84, 86, 89, 844, 846, 849, 864, 866, 869, 894, 896, 899, 40, 48, 60, 68, 90, 98, 404, 406, 409, 484, 486, 489, 604, 606, 609, 684, 686, 689, 80, 88, 804, 806, 809, 884, 886, 889, 440, 448, 460, 468, 490, 498, 640, 648, 660, 668, 690, 698, 840, 848, 860, 868, 890, 898, 400, 408, 480, 488, 600, 608, 680, 688, 800, 808, 880, 888
200
4, 6, 9, 44, 46, 49, 64, 66, 69, 94, 96, 99, 444, 446, 449, 464, 466, 469, 494, 496, 499, 644, 646, 649, 664, 666, 669, 694, 696, 699, 944, 946, 949, 964, 966, 969, 994, 996, 999, 4444, 4446, 4449, 4464, 4466, 4469, 4494, 4496, 4499, 4644, 4646, 4649, 4664, 4666, 4669, 4694, 4696, 4699, 0, 8, 84, 86, 89, 844, 846, 849, 864, 866, 869, 894, 896, 899, 40, 48, 60, 68, 90, 98, 404, 406, 409, 484, 486, 489, 604, 606, 609, 684, 686, 689, 904, 906, 909, 984, 986, 989, 4044, 4046, 4049, 4064, 4066, 4069, 4094, 4096, 4099, 80, 88, 804, 806, 809, 884, 886, 889, 440, 448, 460, 468, 490, 498, 640, 648, 660, 668, 690, 698, 940, 948, 960, 968, 990, 998, 4404, 4406, 4409, 4484, 4486, 4489, 4604, 4606, 4609, 4684, 4686, 4689, 840, 848, 860, 868, 890, 898, 400, 408, 480, 488, 600, 608, 680, 688, 900, 908, 980, 988, 4004, 4006, 4009, 4084, 4086, 4089, 800, 808, 880, 888, 4440, 4448, 4460, 4468, 4490, 4498, 4640, 4648, 4660, 4668, 4690, 4698, 4040, 4048, 4060, 4068, 4090, 4098, 4400, 4408, 4480, 4488, 4600, 4608, 4680, 4688, 4000, 4008, 4080, 4088
```
[Answer]
## Lua, 317 Bytes
I had some troubles doing this, some things in Lua don't work as I think it does. I will have to try and play with them if I want to golf this down.
You can test lua [online](http://www.lua.org/cgi-bin/demo) by replacing `arg[1]` by the number of elements you want :).
```
function f(y)h=0(y..''):reverse():gsub(".",function(c)h=c:find("[08]")and 1+h or h end)return h end
x,a=0,{}while(#a<arg[1]+0)do a[#a+1],x=(x..''):find("^[04689]*$")and x or nil,x+1 end
for i=1,#a do m=1
for j=1,#a do x=a[m]m=(f(x)~=f(a[j])and f(x)>f(a[j])or x>a[j])and j or m
end end print(a[m])table.remove(a,m)end
```
### Ungolfed and explanations
```
function f(y) -- function returning the enhanced holiness of a holy number
h=0 -- h is the cumulated holyness of processed digits
(y..''):reverse() -- reverse the digits in y
:gsub(".",function(c) -- iterate over each digits
h=c:find("[08]")and 1+h or h -- ternary based on the digit being [08] or [469]
end)
return h -- return h
end
x,a=0,{} -- initialise a counter, and the array of holy numbers
while(#a<arg[1]+0) -- iterate until we have n holy numbers
do
a[#a+1]=(x..'')
:find("^[04689]*$") -- if we can't find an unholy digit
and x or nil -- insert x into a
x=x+1 -- increment x anyway
end
for i=1,#a -- iterate n times(current size of a)
do
m=1 -- m is the index of the lowest value
for j=1,#a -- iterate over a
do
x=a[m] -- x is shorter to write than a[m]
m=(f(x)~=f(a[j]) -- nested ternaries, translated in
and f(x)>f(a[j]) -- nested if below
or x>a[j])and j or m
end
print(a[m]) -- output a[m]
table.remove(a,m) -- remove it from the table a
end
```
The nested ternaries used for the new value of `m` can be translated in nested ifs as:
```
if(f(a[m])~=f(a[j])) then -- if a[m] and a[j] don't have the same holyness
if(f(a[m])>f(a[j])) then m=j end-- compare by holyness
else
if(a[m]>a[j]) then m=j end -- else, compare by numeric value
```
Also, I would have loved to replace the nested `for` by using `table.sort`, but, for a reason I don't know, the following doesn't work despite not producing an infinite loop or crushing the sort function.
```
table.sort(a,function(i,j)
return f(i)~=f(j)
and f(i)>f(j)
or i>j
end)
```
[Answer]
# Python 2, ~~138~~ 122 bytes
This looks for holy numbers up to 5*N* for an input *N*, which is ridiculously slow:
```
e=lambda s:s and(s[0]in'08')+e(s[1:])*2or 0
lambda N:sorted([`x`for x in range(5**N)if set(`x`)<=set('04689')][:N],key=e)
```
Here the limit is 5*N*2, and you can actually run the test cases, at the cost of a single byte:
```
e=lambda s:s and(s[0]in'08')+e(s[1:])*2or 0
lambda N:sorted([`x`for x in range(5*N*N)if set(`x`)<=set('04689')][:N],key=e)
```
The first snippet is valid, as 5*N* ≥ 5*N*2 for all positive integers *N*.
[Answer]
## JavaScript (ES6), ~~166~~ 165 bytes
```
f=n=>[...Array(n)].map((_,i)=>i.toString(5)).sort((a,b)=>e(a)-e(b),e=n=>'0b'+[...n.replace(/./g,c=>'10010'[c])].reverse().join``).map(n=>+n.replace(/./g,c=>"04689"[c]))
```
Edit: Saved 1 byte by returning an array of strings.
Ungolfed:
```
function base5_to_extended_holiness_binary(c) {
return "10010"[c];
}
function extended_holiness(n) {
var binary = n.toString(5).replace(/./g, base5_to_extended_holiness_binary);
binary = s.split("").reverse().join("");
return parseInt(s, 2);
}
function extended_holiness_sort(a, b) {
return extended_holiness(a) - extended_holiness(b);
}
function base5_to_holy_number(c) {
return "04689"[c];
}
function list_by_extended_holiness(n) {
var array = new Array(n);
for (var i = 0; i < n; i++)
array[i] = i;
array = array.sort(extended_holiness_sort);
for (var i = 0; i < n; i++)
array[i] = parseInt(array[i].toString(5).replace(/./g, base5_to_holy_number);
return array;
}
```
] |
[Question]
[
# Introduction
Write a solver for [integer linear programming](https://en.wikipedia.org/wiki/Linear_programming#Integer_unknowns).
# Challenge
Your task is write a solver for integer linear programming (ILP). In ILP, linear inequalities of a set of unknowns (all of which are integers) are given, and the goal is to find the minimum or maximum of a linear function.
For example, for the inequalities (example taken from [Mixed Integer Linear Programming](http://www.iibmindialms.com/library/operation-management/supply-chain-management/mixed-integer-linear-programming/))
```
4x+2y-15≤0
x+2y- 8≤0
x+ y- 5≤0
- x ≤0
- y ≤0
```
and the objective function `3x+2y`, the maximum of the objective function should be `12` (`x=2,y=3`), while the minimum should be `0` (`x=y=0`).
The input is given as an 2d array (or any equivalent following the standard specifications), each row corresponds to one inequality, with the exception of the final row. The numbers in the array are the coefficients, and the `≤0` part is always omitted. If there are `n` elements in each row, it means there are `n-1` unknowns.
The last row of the array correspond to the linear function. The coefficients are listed.
For example, the input array for the problem above is
```
[[4,2,-15],[1,2,-8],[1,1,-5],[-1,0,0],[0,-1,0],[3,2,0]].
```
The output should be the minimum and the maximum, given in any reasonable form.
For the following problem (two of the restrictions are taken away from the problem above):
```
[[4,2,-15],[1,2,-8],[1,1,-5],[3,2,0]].
```
The maximum is still `12`, but the minimum does not exist and the objective function can have arbitrarily large (in the sense of absolute value) negative values. In this case, the program should output `12`, following a falsy value that is decided by the answerer. Another case is that there are no solution at all, for example,
```
[[4,2,-15],[-1,-2,7],[-1,0,3],[0,1,0],[3,2,0]].
```
In this case, falsy values should be output as well. It would be nice to discern the case where the "optimal value" for the objective function is infinity and the case where there are no solutions at all, but this is not necessary.
The input only contains integer coefficients both for the inequalities and for the objective function. **All** the unknowns are also integers. The coefficient matrix of the inequalities is guaranteed to have full rank.
# Test Cases
Credit to @KirillL. for finding a bug in the original test suite and deepening my understanding of ILP problems.
```
Input
Output
[[4,2,-15],[1,2,-8],[1,1,-5],[-1,0,0],[0,-1,0],[3,2,1]]
[1,13]
[[4,2,-15],[1,2,-8],[1,1,-5],[3,2,0]]
[-inf, 12]
[[4,2,-15],[-1,-2,7],[-1,0,3],[0,1,0],[3,2,0]]
[NaN, NaN]
[[-1,-1,-1,-1,-1,8],[1,1,1,1,0,0],[5,5,5,5,6,7]]
[55, inf]
[[-1,-1,-1,-1,-1,8],[1,1,1,1,0,0],[0,0,0,0,0,4]]
[4, 4]
[[4,2,-15],[-1,-2,7],[-1,0,3],[0,1,0],[0,0,4]]
[NaN, NaN]
```
# Specs
* No need to worry about exception handling.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the lowest number of bytes wins.
* Maximal number of unknowns: `9`. Maximal number of inequalities: `12`.
* You can take input and provide output through [any standard form](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and you are free to choose the format.
* As usual, [default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply here.
[Answer]
# [Python 3](https://docs.python.org/3/), 534 bytes
```
import itertools as t
import operator as o
I=float("inf")
e=lambda p,A:sum([i[0]*i[1]for i in zip(p,A[:-1])])+A[-1]
def w(x,j):
d=len(x[0])-1;C=[0]*d;v,w=I,I
while 1:
L={(*n,):(sum([0 if e(n,A)<=0 else e(n,A)for A in x[:-1]]),j*e(n,x[-1]))for n in [[sum(a) for a in zip(C,c)]for c in t.product(*[[-1,0,1]]*d)]};C,P=min(L.items(),key=o.itemgetter(1))[0],C;v,w,p,q=L[C][0],L[C][1],v,w
if(all([e(C,A)<=e(P,A)for A in x[:-1]]))*(j*(e(C,x[-1])-e(P,x[-1]))<0)+(p==v>0):return I
if(p==v)*(q<=w):return j*q
f=lambda x:(w(x,1),w(x,-1))
```
[Try it online!](https://tio.run/##lVPBjtowED2Tr7D2EjtMVskCbRVwJcQJCVWoVyuHlDhd05CExCxsq347nTGERWqltjEi45n35s14nObVPtfV6Hw2u6ZuLTNWt7auy45lHbPe1Vs3us1s3ZKz9payKOvM8gdTFQ/C07LMdl/yjDUwT7rDjiujojQwKk4LpBhmKvbdNBzDKgnjVKRiOFdoeLku2JGfYCsSb5DLUlf8hFQRxtOFpBz59AWOcglLb3B8NqVmMQIHK/mDBxWIhDu1iJmCaV7BXMxkxHTZ6euW5Ockf3LCqYBtQJETqQsXriisFCXKBCNP1te7gI1wHWzIYx@bts4PG8sDhXSIABMGuUh/ThewljtT8dUjnt6u4wK@6VdZu91XbfFEeSwE9gML6gca2MuVWqTkce84BfRjZ6bgWVlypVGcutF8/ac2RMC3ASfQpZOQcNemZpEY8kbKl4@RSFptD23FlpfU5EXqfiaPt9A22HtFP8BTwmkcsQB6hVj02erObrJOd0wy5XGlxvCEkUkKKibrgzNiCMnjjgWbUhGQicYIMVixw4zw/P@WgfAR4f0QL5cPLH76jYWpwyd43@uNnN6bnKN/qisNjP6vdCLd/XpRWpeSJ3BZ7zAzbSfAfCrhX/kR9GtM/DGw8f9UfiPeV@6lnkfD74fg7mE/kMRj@DStqSz3P@vuUNqE@WzIOtvygvc4@p6EuMeuW91tWtNYU1dvjBueLtE9PLx7fHH@BQ "Python 3 – Try It Online")
## Overview
It is an iterative algorithm, starting from the origo. It collects the neighbour positions and assigns a potential function: `x:(a,b)` where `x` is the position, `a` is the sum of the position's distances from the half-spaces of each linear inequality, `b` is the value of the objective at that position.
`x:(a,b) < y:(c,d)` iff `a<c` or `a=c and b<d`
The iteration stops, when:
* the first coordinate of the potential hasn't decreased and positive: the system is infeasible
* the distance from every half-space has decreased just like the objective: the system is unbounded.
* none of previous and the potential hasn't decreased: it is the optimal value.
[Answer]
## Matlab, 226 bytes
**DISCLAIMER**: *Not an "original" implementation, only for fun.*
Simple solution taking advantage of the `intlinprog` function:
```
function r=f(a);b=-1*a(1:end-1,end);p=a(end,1:end-1);c=a(1:end-1,1:end-1);[~,f,h]=intlinprog(p,1:size(a,2)-1,c,b);[~,g,i]=intlinprog(-p,1:size(a,2)-1,c,b);s=[inf,nan,f];t=[inf,nan,g];r=a(end,end)+[s(4-abs(h)) -t(4-abs(i))];end
```
It returns the optimal values, or inf (-inf) if the problem is unbounded or nan if it is infeasible.
```
a = [4 2 -15; 1 2 -8; 1 1 -5; -1 0 0; 0 -1 0; 3 2 1]
b = [4 2 -15; 1 2 -8; 1 1 -5; 3 2 0]
c = [4 2 -15; -1 -2 7; -1 0 3; 0 1 0; 3 2 0]
d = [-1 -1 -1 -1 -1 8; 1 1 1 1 0 0; 0 0 0 0 0 4]
e = [4 2 -15; -1 -2 7; -1 0 3; 0 1 0; 0 0 4]
>> f(a)
ans =
1 13
>> f(b)
ans =
Inf 12
>> f(c)
ans =
NaN NaN
>> f(d)
ans =
4 4
>> f(e)
ans =
NaN NaN
```
] |
[Question]
[
# A little genetics lesson
When you only have access to someone's visible traits or *phenotype*, a pedigree of their family history is often used to figure out the actual genetic information or, *genotype* of each family member.
When dealing with [simple dominance](http://study.com/academy/lesson/simple-dominance-definition-lesson-quiz.html) as we will be, a simple pedigree chart will be enough to figure out the alleles, or the version of the genes that they have, of each person. In simple dominance a person with a dominant allele (denoted with a capital letter) will always have the trait that that version represents, no matter the other allele. It takes two recessive alleles (denoted with a lowercase letter) to have that version expressed. In other words the dominant allele always masks the recessive version of that gene. Here is an example of a pedigree chart:

Each row here is a generation. Circles are female, males squares, horizontal lines are marriage, vertical lines children. Pretty simple. Black means recessive phenotype, white, dominant. Starting from the top, (assume the alleles are `A` and `a`), we know person 2 has `aa`, homozygous recessive because that is the only possible option for the recessive phenotype. Now even though person one could be either `Aa` or `AA` to be dominant phenotype, because he has a recessive child, he must be `Aa`, or heterozygous. You can do this for all the other people. In the event you don't have any information that enables you to figure out the second allele, it can be done like so: `A_`.
# Your Task
* You will receive a pedigree chart in the form of a list of generations like `[GenI, GenII, etc.]` in any sane format.
* Each generation will be a list of strings, each string representing a person.
* The people are made up of three parts - an ID, their phenotype, and their "connections".
* Their ID is a single printable ascii character that is unique in the entire tree other than `A` or `a`. (No, there won't be more than 95 people in the chart).
* Their phenotype is one of `A` or `a`, `A` being the dominant allele, and `a` being recessive.
* Their connections are a sequence of ID's of other people that they have connections with.
* A connection in the same generation is marriage, in different generations is child and parent.
* The connections are repeated on both sides (i.e. the husband has say he is a husband of wife, and wife says she is husband of wife).
* You have to figure out the genotypes of everyone as much as possible.
* Return the same list, except instead of people, put their genotypes in the same position.
* The genotype has to be outputted in order so `Aa` instead of `aA`.
* A little leeway on the input format is fine.
* This is code-golf so shortest answer in **bytes** wins.
# Examples
```
[["0A1234", "1a0234"], ["2A01", "3a01", "4A015678",
"5a4678"], ["6a45", "7A45","8A45"]] (The one above) ->
[["Aa", "aa"], ["Aa", "aa", "Aa", "aa"], ["aa", "Aa", "Aa"]]
[["0A12", "1A02"], ["2A301", "3a2"]] ->
[["A_", "A_"], ["A_", "aa"]]
```
# Bonus
* **-30 bytes** if you deal with [incomplete and co-dominance](http://www.hobart.k12.in.us/jkousen/Biology/inccodom.htm) also. On the detection of three phenotypes instead of two in the entire chart, apply incomplete/co dominance to your algorithm.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 39 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εNUε'aåi„aaë¯.øX<X>‚è˜y2£lSδåPài„Aaë„A_
```
Port of [my Java answer](https://codegolf.stackexchange.com/a/156874/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//3Fa/0HNb1RMPL8181DAvMfHw6kPr9Q7viLCJsHvUMOvwitNzKo0OLc4JPrfl8NKAwwtAihyBikBU/P//0dFKBo6GRsYmSjpKhokGIEasTrSSkaOBIVDEOBFMmQB5pmbmFkCmaaIJiAFSY5ZoYgoUMXcEUxYgKjYWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLjHVr5/9xWv9BzW9UTDy/NfNQwLzHx8OpD6w6t1zu8I8Imwu5Rw6zDK07PqTQ6tDgn@NyWw0sDDi8AKXMEKgNR8f9rgUDn0Db7/9HR0UoGjoZGxiZKOkqGiQYgRqxOtJKRo4EhUMQ4EUyZAHmmZuYWQKZpogmIAVJjlmhiChQxdwRTFiAqNlZHAWoiyDxHAyOoacZQ44D82FgA).
**Explanation:**
```
ε # Map over the rows of the (implicit) input-list:
NU # Store the outer-map index in variable `X`
ε # Map over the strings `y` of the current row:
'aåi '# If the current string contains an "a":
„aa # Push string "aa"
ë # Else (it contains an "A" instead):
¯.ø # Surround the (implicit) input-list with two empty lists
# (05AB1E has automatic wrap-around when indexing lists,
# so this is to prevent that)
X<X>‚ # Push `X-1` and `X+1` and pair them together
è # Index both into the list to get (potential) parent and child rows
˜ # Flatten it to a single list
y # Push the current string we're mapping again
2£ # Only leave the first 2 characters (its id and the letter "A")
l # Lowercase the "A" to "a"
S # And convert it to a list of characters: [id, "A"]
δå # Check in each string whether it contains the id and "A"
P # Check for each whether it contained BOTH the id AND "A"
ài # If a child/parent is found for which this is truthy:
„Aa # Push string "Aa"
ë # Else:
„A_ # Push string "A_"
# (after which the mapped result is output implicitly)
```
[Answer]
# Java 10, ~~356~~ ~~349~~ 340 bytes
```
a->{int i=0,j,k,f,z=a.length;var r=new String[z][];for(;i<z;i++)for(r[i]=new String[j=a[i].length];j-->0;)if(a[i][j].contains("a"))r[i][j]="aa";else{var t=".a.*"+a[i][j].charAt(0)+".*";for(f=k=0;i>0&&k<a[i-1].length;)f=a[i-1][k++].matches(t)?1:f;for(k=0;i+1<z&&k<a[i+1].length;)f=a[i+1][k++].matches(t)?1:f;r[i][j]=f>0?"Aa":"A_";}return r;}
```
[Try it online.](https://tio.run/##fVLbbqMwEH3vV1h@qMwClsmlreo4FR@wfem@IbSaEtMYiBMZJ1WD@PasTUiFVtqVEJ45njPHc6ngBHG1qS9FA22LfoLS3R1CSltpSigkevUuQm/WKP2R5VmOCjJxIODuvr9zv9aCVQV6RRoJdIF43bksSAkWVVEdldFZAG2k/rBbfgKDjNDy85b37HLxcm8IV6szV2EYeMdkKp9GVQIcMibJeRXHa8YDVRIPZ1VOi722roKWYMBBYK6owACYy6aVnde1AlOgP3D4TdqCSS1hQYgdPLyiFLVgXK3Z/X29cnFxclPlQSmuQFaHYU53YIutbIkNXpLnciAP1DBZnUdy@Dc5/Af59t5yzV5wCvgZp78x7420R6OR4f3F99p9h@N74zo9Nvy0Vxu0c2V/zwWC69CsbC2Z9M81ueswS5PZfIEjnADzRh91eJayxCFzGI6F85YPj0/OXMLCGz7mARZLhzymw/Hkj74fxv8/Ja@TstmoMh9lZjfqdHOGQoZMkwXz/ljO21dr5Y7uj5Ye3L1tNKnc@tKjVQ1NjYGvlm6kPPzaX/lE04IM/GDU6i9/AA)
**General explanation:**
1) Any `a` will always become `aa`
2a) If a child `A` has parents `aa` and `A`, it will become `Aa`
2b) If a child `A` has parents `A` and `A`, it will become `A_`
2c) (It is not possible for a child `A` to have parents `aa` and `aa`)
3a) If a parent `A` has at least one child `a`, it will become `Aa`
3b) If a parent `A` only has children `A`, it will become `A_`
**Code explanation:**
```
a->{ // Method with 2D String array as both parameter and return-type
int i=0,j,k, // Index-integers
f, // Flag-integer
z=a.length; // Length-integer
var r=new String[z][]; // Result 2D String array
for(;i<z;i++) // Loop over the rows:
for(r[i]=new String[j=a[i].length];
// Create the inner String-array of the result
j-->0;) // Loop over the columns:
if(a[i][j].contains("a"))
// If the current node contains "a":
r[i][j]="aa"; // Set the result at this node to "aa"
else{ // Else(-if the current node contains "A" instead):
var t=".a.*"+a[i][j].charAt(0)+".*";
// Set a temp String to a regex to check relations and "a"
for(f=k=0; // Set the flag to 0
i>0&& // If the current node has parents:
k<a[i-1].length;)
// Loop over the row above:
f=a[i-1][k++].matches(t)?
// If a parent with "a" is found:
1:f; // Set the flag to 1 (else: leave it unchanged)
for(k=0;i+1<z&& // If the current node has children:
k<a[i+1].length;)
// Loop over the row below:
f=a[i+1][k++].matches(t)?
// If child with "a" is found:
1:f; // Set the flag to 1 (else: leave it unchanged)
r[i][j]=f>0? // If the flag is 1:
"Aa" // Current node changes from "A" to "Aa"
: // Else (flag is still 0):
"A_";} // Current node changes from "A" to "A_"
return r;} // Return the result
```
] |
[Question]
[
On modern game consoles and other devices without traditional keyboards, trying to input text is a nightmare. Having to type with a few buttons and a joystick on a virtual keyboard is annoying, and I like to make as few movements/button presses as possible.
The keyboard you will be using looks like this:
```
+---+---+---+---+---+---+---+---+---+---+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 |
+---+---+---+---+---+---+---+---+---+---+
| q | w | e | r | t | y | u | i | o | p |
+---+---+---+---+---+---+---+---+---+---+
| a | s | d | f | g | h | j | k | l | - |
+---+---+---+---+---+---+---+---+---+---+
| z | x | c | v | b | n | m | _ | @ | . |
+---+---+---+---+---+---+---+---+---+---+
```
The following operations can be used:
* `L`: move one square to the left on the keyboard (wraps)
* `R`: move one square to the right on the keyboard (wraps)
* `U`: move one square up on the keyboard (wraps)
* `D`: move one square down on the keyboard (wraps)
* `Y`: insert a space
* `B`: move the insertion pointer one space to the left (does nothing if pointer is at the beginning)
* `F`: move the insertion pointer one space to the right (does nothing if pointer is at the end)
* `C`: toggle caps lock
* `A`: insert the selected character at the position of the insertion pointer
Given an input string containing only ASCII characters that can be typed using the above keyboard and commands (matches `[a-zA-Z0-9 [[email protected]](/cdn-cgi/l/email-protection)]*`), output a sequence of commands that will result in the output string. The initial position of the cursor is on the `1` key (the top-left), and caps lock is initially off.
## Scoring
For any given string, a naive approach would be, for each character in the string, navigate to the character on the keyboard by the shortest path, toggle caps lock if necessary, and select the character. Such a naive approach would generate a command of length `(length of input string) + (sum of Manhattan distances on keyboard between consecutive non-space characters) + (number of times the string alternates between lowercase and uppercase characters) + (1 if string starts with an uppercase letter else 0)`. For example, the naive approach for `101` would result in `ALARA`, a length 5 command, and `Noob 5` would result in `DDDRRRRRCAUURRRCAADDLLLLAYUUUA`, a length 30 command.
Your submission, however, seeks to do better than the naive approach. For each input string, your submission will receive points equal to the number of commands the naive approach uses minus the number of commands your submission outputs. Your overall score will be the sum of the individual scores.
## Rules
* Submissions will be run on a [Cloud9](http://c9.io) free virtual workspace. The workspace has 512 MB of RAM, 2 GB of disk space, 8 Intel(R) Xeon(R) CPUs @ 2.50 GHz (full CPU info, found by running `cat /proc/cpuinfo`, can be found [here](https://gist.github.com/Mego/aa84d3706bf7414f2aa6409512076417)), and is running 64-bit Ubuntu 14.04 Trusty. You may request access to the [testing workspace](https://ide.c9.io/mego/virtual-keyboard-testing) in order to run and score your submission, or I can score it for you.
* Submissions will be run once per test case. Storing state between runs is forbidden. Submissions may not write to or read from any files other than the source file (which may not be modified between runs), with the possible exception of reading an input file if required.
* Submissions are limited to 1 minute of runtime for each test case. Submissions may output multiple solutions, but only the last valid solution within the allotted time will be used for scoring. Failure to output any valid solutions within the allotted time will result in a score of 0 for that test case.
* Please include directions on how to invoke your submission, as well as any tools/libraries that need to be installed that aren't included with a standard Ubuntu 14.04 install.
* The winner will be the submission with the largest score. In the event of a tie, the submission with the better algorithmic complexity will win. If the tie is still not resolved, the first submission to reach the score and algorithmic complexity will win.
* Submissions may not optimize for the test cases. I reserve the right to change the test cases if I feel there is a need.
## Test cases
Format: `input string => naive score`
(if you see any errors in these, please leave a comment with the correction)
```
101 => 5
quip => 12
PPCG => 15
Mego => 25
Noob 5 => 26
penguin => 27
867-5309 => 32
2_sPoOkY_4_mE => 60
The Nineteenth Byte => 76
[[email protected]](/cdn-cgi/l/email-protection) => 95
8xM3R__5ltZgrkJ.-W b => 98
correcthorsebatterystaple => 104
verylongRUNSOFCAPSandnocaps => 118
This is an English sentence. => 122
WNtza.akjzSP2GI0V9X .0epmUQ-mo => 131
Programming Puzzles and Code Golf => 140
```
[Answer]
# C
The score is 193.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define LEFT 'L'
#define RIGHT 'R'
#define CAPS 'C'
#define UP 'U'
#define DOWN 'D'
#define SPACE 'Y'
#define CURSORLEFT 'B'
#define CURSORRIGHT 'F'
#define APPLY 'A'
#define TABLEX 10
#define TABLEY 4
#define casediff(A,B) (isupper(A)*islower(B)+islower(A)*isupper(B))
typedef struct {int x; int y;} coord;
coord letters[300];
#define initLetter(letter, X, Y) \
letters[letter].x=X, letters[letter].y=Y
#define initAllLetters(); \
initLetter('1',0,0);\
initLetter('1',0,0);\
initLetter('2',1,0);\
initLetter('2',1,0);\
initLetter('3',2,0);\
initLetter('3',2,0);\
initLetter('4',3,0);\
initLetter('4',3,0);\
initLetter('5',4,0);\
initLetter('5',4,0);\
initLetter('6',5,0);\
initLetter('6',5,0);\
initLetter('7',6,0);\
initLetter('7',6,0);\
initLetter('8',7,0);\
initLetter('8',7,0);\
initLetter('9',8,0);\
initLetter('9',8,0);\
initLetter('0',9,0);\
initLetter('0',9,0);\
initLetter('Q',0,1);\
initLetter('q',0,1);\
initLetter('W',1,1);\
initLetter('w',1,1);\
initLetter('E',2,1);\
initLetter('e',2,1);\
initLetter('R',3,1);\
initLetter('r',3,1);\
initLetter('T',4,1);\
initLetter('t',4,1);\
initLetter('Y',5,1);\
initLetter('y',5,1);\
initLetter('U',6,1);\
initLetter('u',6,1);\
initLetter('I',7,1);\
initLetter('i',7,1);\
initLetter('O',8,1);\
initLetter('o',8,1);\
initLetter('P',9,1);\
initLetter('p',9,1);\
initLetter('A',0,2);\
initLetter('a',0,2);\
initLetter('S',1,2);\
initLetter('s',1,2);\
initLetter('D',2,2);\
initLetter('d',2,2);\
initLetter('F',3,2);\
initLetter('f',3,2);\
initLetter('G',4,2);\
initLetter('g',4,2);\
initLetter('H',5,2);\
initLetter('h',5,2);\
initLetter('J',6,2);\
initLetter('j',6,2);\
initLetter('K',7,2);\
initLetter('k',7,2);\
initLetter('L',8,2);\
initLetter('l',8,2);\
initLetter('-',9,2);\
initLetter('-',9,2);\
initLetter('Z',0,3);\
initLetter('z',0,3);\
initLetter('X',1,3);\
initLetter('x',1,3);\
initLetter('C',2,3);\
initLetter('c',2,3);\
initLetter('V',3,3);\
initLetter('v',3,3);\
initLetter('B',4,3);\
initLetter('b',4,3);\
initLetter('N',5,3);\
initLetter('n',5,3);\
initLetter('M',6,3);\
initLetter('m',6,3);\
initLetter('_',7,3);\
initLetter('_',7,3);\
initLetter('@',8,3);\
initLetter('@',8,3);\
initLetter('.',9,3);\
initLetter('.',9,3);
typedef struct {int length; char instr[300];} movement;
movecasefold(char*instr,coord A, coord B){
register int i=0;int j;
if(A.x<B.x)
if(B.x-A.x<=TABLEX/2)
for(;B.x-A.x!=i;)instr[i++]=RIGHT;
else
for(;TABLEX-B.x+A.x!=i;)instr[i++]=LEFT;
else if(A.x>B.x)
if(A.x-B.x<=TABLEX/2)
for(;A.x-B.x!=i;)instr[i++]=LEFT;
else
for(;TABLEX-A.x+B.x!=i;)instr[i++]=RIGHT;
j=i;
if(A.y<B.y)
if(B.y-A.y<=TABLEY/2)
for(;B.y-A.y!=i-j;)instr[i++]=DOWN;
else
for(;TABLEY-B.y+A.y!=i-j;)instr[i++]=UP;
else if(A.y>B.y)
if(A.y-B.y<=TABLEY/2)
for(;A.y-B.y!=i-j;)instr[i++]=UP;
else
for(;TABLEY-A.y+B.y!=i-j;)instr[i++]=DOWN;
instr[i]='\0';
return i;
}
char sentence[50], oldcase, oldletter;
int sentencelength;
typedef struct {
int sentencetoorder[50];
int ordertosentence[50];
int length;
} order;
ordercopy(order*a, order b){
register int i;
for(i=0;++i<sentencelength;) a->sentencetoorder[i]=b.sentencetoorder[i], a->ordertosentence[i]=b.ordertosentence[i];
a->length=b.length;
}
order currentOrder;
movetwo(char*instr,int A, int B){
register int j; int i=0;
if(A<B)
{ for(j=A+1;j<B;j++)
if(currentOrder.sentencetoorder[j]<currentOrder.sentencetoorder[B])
instr[i++]=CURSORRIGHT;
}
else
{ for(j=A;j>B;j--)
if(currentOrder.sentencetoorder[j]<currentOrder.sentencetoorder[B])
instr[i++]=CURSORLEFT;
}
if(sentence[B]==' '){
instr[i++]=SPACE;
instr[i]='\0';
return i;
}
i+=movecasefold(instr+i,letters[oldletter],letters[sentence[B]]);
oldletter=sentence[B];
if(casediff(oldcase,sentence[B]))oldcase=sentence[B],instr[i++]=CAPS;
instr[i++]=APPLY;
instr[i]='\0';
return i;
}
moveall(char*instr){
int j;int i = 0;
oldcase='a';
oldletter='1';
for(j=0;++j<sentencelength;)
i+=movetwo(instr+i,currentOrder.ordertosentence[j-1],currentOrder.ordertosentence[j]);
return i;
}
iteration();
main(){
initAllLetters();
gets(sentence+1);*sentence='1';sentencelength=strlen(sentence);
int i;
for(i=0;++i<sentencelength;)currentOrder.sentencetoorder[i]=currentOrder.ordertosentence[i]=i;
char instr[300];
currentOrder.length=moveall(instr);
puts(instr);
while(iteration());
}
#define inside(item, start, stop) (((start)<=(item))&((item)<(stop)))
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
iteration(){
char instr[300];
register int i;
int newstart, start, l;
static order oldorder, neworder;
ordercopy(&oldorder,currentOrder);
ordercopy(&neworder,currentOrder);
for(l=0;++l<sentencelength-1;)
for(start=0;++start<sentencelength-l;)
for(newstart=0;++newstart<sentencelength-l;)
if(start!=newstart){
for(i=0;++i<sentencelength;)
if(inside(i,start,start+l))currentOrder.ordertosentence[i-start+newstart]=oldorder.ordertosentence[i];
else if(inside(i,min(start,newstart),max(start+l,newstart+l)))currentOrder.ordertosentence[newstart<start?i+l:(i-l)]=oldorder.ordertosentence[i];
else currentOrder.ordertosentence[i]=oldorder.ordertosentence[i];
for(i=0;++i<sentencelength;) currentOrder.sentencetoorder[currentOrder.ordertosentence[i]]=i;
currentOrder.length=moveall(instr);
if(currentOrder.length<neworder.length){
puts(instr);
ordercopy(&neworder, currentOrder);
}
}
ordercopy(¤tOrder, neworder);
return neworder.length<oldorder.length;
}
```
Compile with as "gcc virtualKeyboard.c".
Run it without arguments "./a.out". It reads the input from stdin and writes the output to stdout.
] |
[Question]
[
Your task is to write a program, that given a list of chat messages, count how many times each person gets pinged, so I can know how popular everyone is. But, since I have to do it surreptitiously, I need it to be as small as possible so I can hide the code.
# Specs
* The input comes in a list of 2-tuples, with each item being of the form `("username", "message")`.
* A ping to another user is defined as an `@` followed by 3 or more letters that unambiguously refers to that user.
* However, you also have to consider replies, which have to start with `:messageid` followed by a space.
* Assume the first message has id `0` and proceed sequentially.
* Output each user and say how many times each one got pinged.
* The output can be in any order/reasonable format.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins!
# Test Cases
```
[["AlexA.", "I am wrong"], ["Quartatoes", "@Alex you are very wrong"], ["AlexA.", ":1 I am only slightly wrong"]]
AlexA.: 1
Quartatoes: 1
[["Doorknob", "I have never eaten an avocad."], ["AquaTart", ":0 I will ship you an avocad"], ["AlexA.", ":0 this is shocking"]]
Doorknob: 2
AquaTart: 0
AlexA.: 0
[["Geobits", "I like causing sadness through downvotes."], ["Flawr", "I want to put random message ids in my chat messages :0 askjdaskdj"]]
Geobits: 0
Flawr: 0
[["Downgoat", "goatigfs.com/goatgif"], ["Downotherthing", "@Downgoat cool gifs"], ["Dennis", "@Down cool gifs this is an ambiguous ping"]]
Downgoat: 1
Downotherthing: 0
Dennis: 0
```
[Answer]
# JavaScript (ES6), ~~245~~ 210 bytes
```
a=>(p={},a.map(b=>p[b[0]]=0),(a.map(b=>b[1].match(/@[a-z]{3,}|^:\d+/gi)||[]).map(c=>c.map(d=>(z=(d[0]=='@'?(y=Object.keys(p).filter(e=>e.startsWith(d.slice(1)))).length<2?y:0:a[d.slice(1)[0]]))&&p[z[0]]++))),p)
```
Uses an object to create a unique list of names alongside pings. Then it looks through the messages for matches to either ping condition. If a name, it looks through the list of names to find if there is only one match, and then increments. If a reply, it simply references that index in the message array and pulls the name to be incremented. Finally, it returns the object.
[Answer]
# PHP, 227 Bytes
```
foreach($_GET[a]as $c){$r[]=&$n[$c[0]]??$n[$c[0]]=0;preg_match("#^(:(\d+)|@(\w+))#",$c[1],$m);$m[2]==""?!$m[3]?:count($a=preg_grep("#^{$m[3]}#",array_keys($n)))>1?:$n[end($a)]++:$r[$m[2]]++;}foreach(($n)as$k=>$v)echo"$k: $v\n";
```
] |
[Question]
[
# Introduction
Every letter in the English alphabet can be represented as an ASCII code. For example, `a` is `97`, and `S` is `83`. As we all know, the formula for averaging two numbers \$x\$ and \$y\$ is \$\frac{x+y}{2}\$. I'm pretty sure you can see where this is going. Your challenge is to average two letters.
# Challenge
Your program must take two letters as input, and output the average of the ASCII values in it. If the average is a decimal, you should truncate it.
* Input will always be two ASCII letters. You can assume they will always be valid, but the case may vary. Basically, both letters will be in the range `97-122` or `65-90`. The second letter will always have a greater ASCII value than the first. If your language has no method of input, you may take input from command line arguments or from a variable.
* You must output the ASCII character signified by the average of the two numbers. As stated above, it should always be truncated to `0` decimal places. If your language has no method of output, you may store it in a variable. Exit codes and return values are considered valid output methods.
# Example I/O
* `Input: A, C`
`Output: B`
* `Input: a, z`
`Output: m`
* `Input: d, j`
`Output: g`
* `Input: B, e`
`Output: S`
* `Input: Z, a`
`Output: ]`
# Rules
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 20 bytes
```
a=>b=>(char)(a+b>>1)
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5yRWKSDYIEIO7s02/@JtnZJtnYaIL6mRqJ2kp2doeZ/a67wosySVI00DfVEdU0N9WR1TU3r/wA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# x86-16 machine code, IBM PC DOS, ~~13~~ ~~12~~ 10 bytes
Binary (xxd):
```
00000000: a182 0002 c4d0 e8cd 29c3 ..........
```
Listing:
```
A1 0082 MOV AX, [0082H] ; load two chars into AH and AL from command line
02 C4 ADD AL, AH ; AL = AL + AH
D0 E8 SHR AL, 1 ; AL = AL / 2
CD 29 INT 29H ; write to console
C3 RET ; return to DOS
```
Standalone PC DOS executable. Input is via command line, output to console.
Example:
[](https://i.stack.imgur.com/ROu9m.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
OSHỌ
```
[Try it online!](https://tio.run/##y0rNyan8/98/2OPh7p7///8rpSjpKChlKQEA "Jelly – Try It Online")
# Explanation
```
OSHỌ Main Link: takes (a, b)
O (ord(a), ord(b))
S sum; ord(a) + ord(b)
H halve; (ord(a) + ord(b)) / 2
Ọ chr
```
[Answer]
# [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/index.html), 163 bytes
```
software inside a computer
a robot+a man+a keypad+a plan=a PC
still,P.C.this,P.C.that?i await a day i crush a PC
resist P.C,Google,or an Apple
i do Linux,i suppose
```
[Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?LYwxDsIwEAT7vGJ7rPwAIZSChiJfuOCDnHB8lu@ikNcHC9GMpphd06dvVBmSTSKD8NClrM61I1Sd1E@EhXLjm/dCsUlJlM@EcejMJaUw9kPvs9hfyC8C2ki8vUXaIXjU1Wb8JpVNzNHScFN9JQ5aQRnXUhJ3gqi4S14/QWBrKWp8jMMxUfwC)
Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.
(I actually use PC myself. üòâ)
[Answer]
# [J](http://jsoftware.com/), 17 bytes
```
(+/<.@%#)&.(3&u:)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NbT1bfQcVJU11fQ0jNVKrTT/a3KlJmfkK6g7qSvYKqQpqDs6q0NFcqEiiVUwkXSoSEqWusJ/AA "J – Try It Online")
* `(+/<.@%#)` truncated average...
* `&.` ["Under"](https://code.jsoftware.com/wiki/Vocabulary/ampdot), which applies a transform, then the verb it modifies -- truncated avg in this case -- then the inverse transform....
* `3&u:` convert to ascii byte integer.
That is, it converts each letter to its ascii number, gets the truncated average of those, and applies the inverse of "convert to ascii number", which takes an ascii number and returns a letter.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 22 bytes
```
->a,b{""<<(a+b).sum/2}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6laScnGRiNRO0lTr7g0V9@o9n9BaUmxQrS6o7O6jnpiFZBIyVKP1ctNLKiuSa5Ji9ZK1kvOSCwqjq39DwA "Ruby – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~56~~ 37 bytes
```
intToUtf8(mean(utf8ToInt(scan(,""))))
```
[Try it online!](https://tio.run/##K/r/PzOvJCQ/tCTNQiM3NTFPoxTICsn3zCvRKE4GcnWUlDSB4L9SYorSfwA "R – Try It Online")
**Description**
* `intToUtf8()` converts the average into its ASCII character.
* `mean()` takes the average which is automatically truncated.
* `utf8ToInt()` converts the inputs into two ASCII numbers.
* `scan()` allows inputs.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg) `-ir` `-oc`, ~~5~~ 2 bytes (SBCS)
Works in all 3 test cases.
```
+¬Ω
```
[Try it online!](https://tio.run/##y05N///fXttI/1HLkv//HZ0B "Keg – Try It Online")
# Explanation
```
-ir will *not* try to evaluate the input
+ Add them
¬Ω Halve the value
-oc Output all as a character, if possible
Implicit print. The output is print nice by default.
```
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 8 bytes
**Solution:**
```
`c$.5*+/
```
[Try it online!](https://tio.run/##y9bNz/7/PyFZRc9US1tfKbFK6f9/AA "K (oK) – Try It Online")
**Explanation:**
Sum, multiply by 0.5 and convert to ASCII.
```
`c$.5*+/ / the solution
+/ / sum (add-over)
.5* / multiply by 0.5
`c$ / convert to ASCII
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 56 bytes
```
printf \\x$(printf %x $[`printf "(%d+%d)/2" \'$1 \'$2`])
```
[Try it online!](https://tio.run/##S0oszvj/v6AoM68kTSEmpkJFA8pWrVBQiU6AcpQ0VFO0VVM09Y2UFGLUVQxBhFFCrOb///8d/zsDAA "Bash – Try It Online")
[Answer]
# Shakespeare Programming Language, 144 bytes
[Try it online!](https://tio.run/##TYsxDsIwEAS/sg@Ijj5dCopUIKVCiOLsHGBC7BCfBXm9sanoZlazcXnmvKPuwZ@GjslODXVW0bc0WPFS4bz3KitqAvYjanWp1h4W8ZidH3/PPz2FBBehd8ErBXXiFUb0LQXKFtOMcN1K1INh3A2WlYZFeCqfjXJm8wUj)
(Whitespace added for readability)
```
/.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]
Ajax:Open mind.
Puck:Open mind.
You is the quotient betweenthe sum ofyou I a big cat.
Speak thy.
```
Simple enough, just finds the average. ASCII characters and numbers are identical in SPL, so this language was ideal for the task.
[Answer]
# dzaima/APL, 11 bytes
```
(+/÷≢)⍢⎕UCS
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P@1R2wQNbf3D2x91LtJ81LvoUd/UUOfg/0AKKJGm7qiuoO6szgXjJgK5VQhuCpCbpf4fAA "APL (dzaima/APL) – Try It Online") dzaima/APLs `⎕UCS` - convert to/from char currently ignores the fractional part of the given number, so no floor is necessary.
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 7 bytes
```
~~+2/,@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@vq9M20tdx@P/f0RkA "Befunge-98 (PyFunge) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 31 bytes
```
lambda*A:chr(sum(map(ord,A))/2)
```
[Try it online!](https://tio.run/##Jcu9CoMwEADg2T5FtruTg4KjoBB8jOpwNgQtzQ/RDvryacTtW7547EvwTbbdmL/iZiO1bt9Lwu3n0EnEkAxromdD2YakhGe1evVC0MAwALFCkMLzpin8AE3to4pp9fsVGLoe2GIh5T8 "Python 2 – Try It Online")
[Answer]
# [jq](https://stedolan.github.io/jq/), 23 characters
```
[explode|add/2]|implode
```
Sample run:
```
bash-5.0$ jq -Rr '[explode|add/2]|implode' <<< 'AC'
B
```
[Try it online!](https://tio.run/##yyr8/z86taIgJz8ltSYxJUXfKLYmMxfM/f/f0ZkrsYorJetffkFJZn5e8X/doP@6RQA "jq – Try It Online")
[Answer]
# Excel, 28 bytes
```
=CHAR((CODE(A1)+CODE(B1))/2)
```
[Answer]
# [Lua](https://www.lua.org/), ~~42~~ 41 bytes
```
a=...print(a.char(a:byte()+a:byte(2)>>1))
```
[Try it online!](https://tio.run/##yylN/P8/0VZPT6@gKDOvRCNRLzkjsUgj0SqpsiRVQ1MbyjDStLMz1NT8D1RbBQA "Lua – Try It Online")
Removed 1 byte using [ouflak's method](https://codegolf.stackexchange.com/a/195630/71126) of taking input as a single command line argument.
Takes input as a single command line argument of two characters. Uses the convenient operator precedence of `>>`.
Note that this is actually a full standalone Lua 5.3 program, because command line arguments are accessible as a top-level vararg.
[Answer]
# [Julia 1.0](http://julialang.org/), 26 bytes
```
a\b=Char(sum(Int[a,b])√∑2)
```
TIO was timing out for me, so only tested at REPL.
[Try it online!](https://tio.run/##yyrNyUw0rPj/PzEmydY5I7FIo7g0V8MzryQ6UScpVvPwdiPN/w7FGfnlCuqO6jHqzupcUJ4hkBel/h8A "Julia 1.0 – Try It Online")
[Answer]
# [Preproc](https://gitlab.com/PavelBraginskiy/preproc), 1187 bytes
```
#define A
#define B,
#define C,,
#define D,C
#define E,D
#define F,E
#define G,F
#define H,G
#define I,H
#define J,I
#define K,J
#define L,K
#define M,L
#define N,M
#define O,N
#define P,O
#define Q,P
#define R,Q
#define S,R
#define T,S
#define U,T
#define V,U
#define W,V
#define X,W
#define Y,X
#define Z,Y
#define a Z H
#define b,a
#define c,b
#define d,c
#define e,d
#define f,e
#define g,f
#define h,g
#define i,h
#define j,i
#define k,j
#define l,k
#define m,l
#define n,m
#define o,n
#define p,o
#define q,p
#define r,q
#define s,r
#define t,s
#define u,t
#define v,u
#define w,v
#define x,w
#define y,x
#define z,y
#define _(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,_,cb,cc,cd,ce,cf,cg,ch,ci,cj,ck,cl,cm,cn,co,cp,cq,cr,cs,ct,cu,cv,cw,cx,cy,cz,da,db,dc,dd,de,df,dg,dh,di,dj,dk,dl,dm,dn,do,dp,dq,dr,ds,dt,du,dv,dw,dx,dy,dz,ea,eb,ec,ed,ee,ef,eg,eh,ei,ej,$,...)#$
#define $($a,$b)_($a $b z,y,y,x,x,w,w,v,v,u,u,t,t,s,s,r,r,q,q,p,p,o,o,n,n,m,m,l,l,k,k,j,j,i,i,h,h,g,g,f,f,e,e,d,d,c,c,b,b,a,a,`,`,_,_,^,^,],],\\,\\,[,[,Z,Z,Y,Y,X,X,W,W,V,V,U,U,T,T,S,S,R,R,Q,Q,P,P,O,O,N,N,M,M,L,L,K,K,J,J,I,I,H,H,G,G,F,F,E,E,D,D,C,C,B,B,A,A)
```
[Try it online!](https://tio.run/##RdLZbuJAEEbh@zyFxXARpKO8wVwAIXsgK4snmYzd3ez7Di@f@SFORSdSfW5KwrGZzsN0PnGfn798aPfGISqefKuEscyPzymbK5ybL6iYL7kwX3FpvubKfMO1@ZYb8x235nvuzFXuzTWq5gdq5kcezE88mp95Mr/wbH7lxVzn1dygbm7SMLdommNa5iSKo5//LCUxO1Kzx5kD3twmmDu0zV065h5dc5@eeUDfPGRgHjE0jxmZJ4zNUybmGVPznJl5wdy8ZGFesTSvWZk3rM1bNuYdW/OenfnjNCHF4Qm06dClR58BQ0aMmTBlxpwFS1as2bBlx54iJcqcU@GCS6645oZb7rinSo0HHnnimRdeqdOgSYuYD5y@yOH0GgKujevgurgero8b4Ia4EW6Mm@CmuBlujlvglrgVbo3b4La4HW6PT/ApXvft8XqXbXwH38X38H38AD/Ej/Bj/AQ/xc/wc/wCv8Sv8Gv8Br/F7/B7QkJICY6gxxAI@kF0CF1Cj9Anz9nZWeFX3p5Z/jSfkE8LH5pRPj08T7VVG7VWK7VUCzVXMzVVEzVWIzVUA9VXPdVVHdVWuge9ET0olapE/VMf6q96V29vh78/KlYt1VQNVVev6kU9qyf1qB5UTVXVvbpTt@pGXasrdakuVEWdq7IqqSLFwmf@tEhULES/o6NKXyplZ7li7uR4XrbzbKP8vVE6bMRE8fEqPlwlRMnXlpR@Kc3Ockm24ew823DfG@lhY0@0P17tszvYf23F31vvuRN9UD9e5k8b2Wxms5XN@Gem2XTZ9NkM2Wxns5PNbuHzPw "Preproc – Try It Online")
Defines a macro `$` which can be called (as shown in the footer of the TIO link above)
This challenge is barely possible in preproc (pure macro) -- if the input can be non-alphanumeric characters too, it would not be possible.
I don't see any simple way to shorten this code -- it might be possible to make the part to take the (n)th element shorter, but that would come at the cost of making the initial macro definitions significantly longer.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~33~~ 32 bytes
-1B from Embodiment of Ignorance using bit ops.
Exactly as specified. For a Python 3 answer change the `/` into `//`.
```
lambda a,b:chr(ord(a)+ord(b)>>1)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfqGCrEPM/JzE3KSVRIVEnySo5o0gjvyhFI1FTG0QladrZGWr@LyjKzCvRSNRQclTSUXJW0tTkgoskAkWqUERSgCJZQJH/AA "Python 2 – Try It Online")
[Answer]
# [Lua](https://www.lua.org/), ~~63~~ 60 bytes
```
s=io.read()print(s.char(math.floor((s:byte()+s:byte(2))/2)))
```
Takes the two letters with no delimeters, i.e. `AB`, `j$`, `|1`, etc....
[Try it online!](https://tio.run/##yylN/P@/2DYzX68oNTFFQ7OgKDOvRKNYLzkjsUgjN7EkQy8tJz@/SAMolFRZkqpRrKkNY@kYaWrqA7Hm//@OzgA "Lua – Try It Online")
*Saved 3 bytes thanks to PhillipRoman*
[Answer]
# [MarioLANG](https://github.com/tomsmeding/MarioLANG), 63 bytes
```
,
)
,
>[!(>[!
"=#="=#
- ( >
) ( + -
!+< ) [
#=" !-<)
#=".
```
[Try it online!](https://tio.run/##y00syszPScxL//9fh0uTS4fLLlpRA4i5lGyVbYGYS0FBV0FDwY5LE0hqK@hyKWrbKGgqRHMBZRUUdW00gQoUFIAcvf//nVIB "MarioLANG – Try It Online")
Super golfable, I'm sure - not really able to think in MarioLANG yet. Calculates \$\lfloor\frac{x+y}{2}\rfloor\$.
[Answer]
# Zsh, ~~33~~ 31 characters
```
a=({$1..$2} 0)
echo ${a[$#a/2]}
```
This one does no character code conversion.
Sample run:
```
manatwork ~ % set -- A C
manatwork ~ % a=({$1..$2} 0);echo ${a[$#a/2]}
B
```
[Try it online!](https://tio.run/##qyrO@P8/0VajWsVQT0/FqFbBQJMrNTkjX0GlOjFaRTlR3yi29v///47/nQE "Zsh – Try It Online")
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 15 bytes
```
: f + 2/ emit ;
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf//WymkKWgrGOkrpOZmlihYA/kFCvllqUUQfkppgUJxQWJyKoSrp6SgoGunoATUk1ykYM2l7qig7qxQwKWeqKBeBaJTFNSzQLSTgnoqiI5SAEoVcP0HAA "Forth (gforth) – Try It Online")
### Code Explanation
```
: f \ start a new word definition
+ \ add top two stack arguments
2/ \ divide top stack value by 2
emit \ output char of resulting ascii value
; \ end word definition
```
[Answer]
# [K4](http://kx.com/download), ~~9~~ 8 bytes
**Solution:**
```
10h$_avg
```
**Examples:**
```
q)k)10h$_avg"AC"
"B"
q)k)10h$_avg"az"
"m"
q)k)10h$_avg"dj"
"g"
```
**Explanation:**
~~Unfortunately the space is needed.~~ Turns out the space isn't necessary!
```
10h$_avg / the solution
avg / calculate mean
_ / floor
10h$ / cast to char
```
**Bonus:**
* `10h$-256+avg` for a 12 byte Q version (more/less hacky than `10h$(_)avg` for 10)
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), ~~14~~ 13 bytes
```
|*;:2@+/',{,|
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/79Gy9rKyEFbX12nWqfm///EFAA "Hexagony – Try It Online")
[](https://i.stack.imgur.com/bYRZN.png)
Linear control flow: `,{,'+{*2':;@`
I decide to plug it in [the Hexagony brute forcer program](https://codegolf.stackexchange.com/a/165095/69850), and it can't find a 12-byte program. At least for that specific linear code.
Other possible linear control flows:
```
,{,'+'2=':;@
,{,'+'2{=:;@
,},"+{*2':;@
,},"+'2=':;@
,},"+'2{=:;@
,{,'+{+2':;@
```
(none of them results in a 12-byte solution (there are only some non-halting 12-byte solutions); nevertheless, the brute force program has room for improvement.)
[Answer]
# [Perl 5](https://www.perl.org/), ~~31~~ 30 bytes
```
$x+=ord for@ARGV;print chr$x>>1
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lQts2vyhFIS2/yMExyD3MuqAoM69EITmjSKXCzs7w////if9TAQ "Perl 5 – Try It Online")
Shortened to 30 bytes thanks to comment by [Dadsdy](https://codegolf.stackexchange.com/users/118038/dadsdy)
[Answer]
# [Red](http://www.red-lang.org), 18 bytes
```
func[a][average a]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85OjE2OrEstSgxPVUhMfZ/QVFmXolCmkK0spKjkoKykrNSLBeSWCJIrApVLAUklqUU@x8A "Red – Try It Online")
Takes the input as a list of two letters.
If this is not acceptable:
# [Red](http://www.red-lang.org), 20 bytes
```
func[a b][a + b / 2]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85OlEhKRZIaCskKegrGMX@LyjKzCtRSFNQVnJUAhLOSlwIkUSQSBWySApIJEvpPwA "Red – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
Ymc
```
[Try it online!](https://tio.run/##y00syfn/PzI3@f9/dUcXdQA "MATL – Try It Online")
### Explanation
```
Ym % Implicit input: string of two letters. Implicitly convert to ASCII, and take mean
c % Implicitly round down, and convert to char
% Implicit display
```
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 7 bytes
```
ii+2,k@
```
[Try it online!](https://tio.run/##KyrNy0z@/z8zU9tIJ9vh/39HhSgA "Runic Enchantments – Try It Online")
Input is space sepatrated. Use invalid inputs at your own peril.
] |
[Question]
[
# Challenge
You have one string of input bytes, output *only* the last byte in it.
# Rules
Your submission may be a program or function outputting the last byte in the input which
* is either a string, *stdin* or command-line arguments, and
* is non-empty.
I was trying to solve this with brainfuck, however all languages are allowed to participate. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
# Examples
```
"?" -> "?"
"29845812674" -> "4"
```
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 4 bytes
```
Last
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@98nsbjkv19qakpxtEpBQXJ6LFdAUWZeSUhqcYlzYnFqcXSajkK0kr2SjoKSkaWFiamFoZGZuQmIm5Gak5Ovo1CeX5SToqgUG/sfAA "Attache – Try It Online") (If the input could be a list of characters, `&/S` could work.)
## Alternatives
**5 bytes:** ``@&-1`
**8 bytes:** `&/S@List`
**10 bytes:** ``@«_,-1»`
**10 bytes:** `Fold!Right`
**10 bytes:** ``@<~_,-1~>`
**10 bytes:** ``^^&:Right`
**10 bytes:** `{Right^^_}`
**11 bytes:** `Get«_,-1»`
**11 bytes:** `Get<~_,-1~>`
**12 bytes:** ``@«_,#_-1»`
**12 bytes:** ``@<~_,#_-1~>`
**13 bytes:** `Get«_,#_-1»`
**13 bytes:** `Get<~_,#_-1~>`
[Answer]
# x86-16 machine code, 2 bytes
As @CodyGray correctly points out, taking input as a string and output to a register removes the bulk of the standalone program version.
Input string is in `SI`, length in `CX` and output character is in `AL`:
```
F3 AC REPZ LODSB ; start at memory location pointer in SI, put next value in AL,
; loop CX number of times. The last char will be in AL when done.
```
Or **4 bytes** as a "Pascal string" (length is prepended to beginning of string):
```
AC LODSB ; first byte is string length
91 XCHG AX, CX ; move length to CX for loop
F3 AC REPZ LODSB ; start at memory location pointer in SI, put next value in AL,
; loop CX number of times. The last char will be in AL when done.
```
Or **5 bytes** as a "C string" (zero/null terminated), input in `DI`:
```
F2 AE REPNZ SCASB ; scan for value in AL (0), end when found and advance DI
8A 45 FE MOV AL, [DI-2] ; DI is now two bytes ahead of last, put value of DI-2 into AL
```
# x86-16 machine code, IBM PC DOS, ~~12~~ ~~11~~ 10 bytes
Or as complete program as IBM PC DOS executable. Input is from command line, output is to console.
```
B3 80 MOV BL, 80H ; BX to DOS PSP at 80H
8A 07 MOV AL, BYTE PTR[BX] ; get command line tail length
D7 XLAT ; AL = [BX+AL]
B4 0E MOV AH, 0EH ; PC BIOS write to screen function
CD 10 INT 10H ; display
C3 RET ; exit to DOS
```
**Output:**
[](https://i.stack.imgur.com/H3s4u.png)
[Answer]
# Brainf\*\*\*, 7 bytes
```
,[>,]<.
```
[Answer]
# MATL, 2 bytes
```
0)
```
MATL uses 1-based modular indexing so this solution grabs the element in the `0`-th position of the input which is the same as the last since the `0` wraps around to the end.
Try it out at [MATL Online](https://matl.io/?code=0%29&inputs=%27123%27&version=20.10.0)
**Explanation**
```
% Implicitly grab the input
0 % Push the literal 0 to the stack
) % Use this zero to grab the character at the end of the string
% Implicitly display the result
```
[Answer]
# [INTERCAL](http://www.catb.org/%7Eesr/intercal/), ~~270~~ ~~258~~ ~~247~~ 246 bytes
```
DO,1<-#1PLEASECOMEFROM(2)DOWRITEIN,1DO.1<-,1SUB#1DO.5<-#1$.1~#256DO.2<-.3DO(1)NEXTPLEASE.2<-!3~#15'$.3~#240PLEASE.2<-!2~#15'$.2~#240PLEASE.2<-!2~#15'$.2~#240DO(1010)NEXTDO,1SUB#1<-.3DOREADOUT,1(1)DO(1002)NEXTDO(1009)NEXTDO.3<-.3~#255(2)DOFORGET#1
```
[Try it online!](https://tio.run/##fU9NC4JAEP0tsUIKujijawperF1DyDbWlbpGdAiiQ3T2r2@OeujUaT7em/fePF6f@/t2fTondQhlxOB0UFWndrpVtdGtj4HUZ9NY1RxDkJqPnBC6fstoEHTgcRgYimycsYx4IrUPwVFd7KxEy1UyMBBrj48V0/gHwAXA/wBpxhBPshR0CjCbGVVJ3dsQRteJFuNCo75Yep4Qm3KK6aVam72yDJzDIk9FDpht0i8 "INTERCAL – Try It Online")
*-8 thanks to 鳴神裁四点一号 removing `DOGIVEUP` to terminate by NEXT stack explosion, opening up another -4 changing a `PLEASE` to `DO`.*
*-11 removing some grouping from the bit-reversing expression from hell. It seems that binary operators generally act right-associative in C-INTERCAL, though having no precedence among themselves.*
*-1 trying something else for bit reversal--definitely expected more savings than that! A more principled approach might be able to do it in two steps unless there's some obvious invariant I'm missing, but I'm too tired to take a stab at that just yet.*
Writing this was... interesting. I was thinking I might want to use INTERCAL [to INTERCALate](https://codegolf.stackexchange.com/questions/50798/is-it-a-leap-year), but I'm a bit less sure now.
[Ungolfed and commented:](https://tio.run/##3VZdb9s2FH3Pr7hFCjgGHM0fy4YCAYYsdVsDqV04zrpXWqJsLhIpkJRVv/SvZ@eSsmMH6Yy@zghiQ7oizz3n3EMp7aVNRfH0RO3n/Yx6g@vL8wEdfr7cjW/uxzSdLcb0VVIjtCe/lqR0VXsS1ooteUNGF1tai40kV4lUUm4srkmShSyl9j1yhpSnRhVFrPXiUYYKgVXIq1KeHQC5nX0e04f57DNdDLuHN77OJwAymQLqawgnOcApR/hjkLmyztNy67FV/gy7BygdAGmswh3lHW1EUcskSWiJplRO2rwowrNn9J@fysqNMnW7FpVK4/d@bSpNRsOr35LDZhLQ3RvcP/x5Pji6fMUqvH0z@H6OJzove0yuuL0Rw3wWAldQ26MhGVy0jXJHfCbD68tkdHjlYtCl6fjvxdmJtl6w28iOlYQdZI9/b1jpWmcBicT3Ic0JTU3DZaSlzNgllVWwD3ywFOkjGZSA8tvLyXQxnt/e3HXcCTDRbpNfZhBHk7GZtLxsJuFlEA57roXf@0ykvhYFvBa2hQXrpbe4GL0RZYHGjlZG6dUzvtya8mcEZxdfOM9btir3SICLRvl12OqFNTKZi7rw7Z79bqxGoSYrRRbhLdk6LZts4BNgmNBG2MwldG@OyFmZfUPt/s1ujMGcclURJ/jo/k6wnL/BiaH5@OY9zR4WrOcJLOhWWief29i3t1MgIuJxoLlgv@K2wG2kReoP2mdj60xtVBaF5IWg86oIi5eEiyewMBMcQ9@ggXPK6B5NDpaIRuRlgQiUrEWxkUe8U62hLHtKZJCmrpgW0fYoiuTseMzo@pLejL6fD6469Db8Gv7a77xSM9zXDH@i5niC@4N@HOLXhjUZgB72E@dySAcmQ2EOmrVK15wYaGFLqdEbqZVk4yO0G9Zpa@q9BfaaAdRetiMgbYQx5GT0g9Sgf2okMcPhGsMZjPjIaCU5/uemhPy6LqUV4Fo7z4WtCqmxlm2BhzhUDnfemRIQDhFNOwv6OPlrTA9fXs2xO7NSOPp2gVVZs7KiTOiTaVjWHkcrIGdGdzzhVirzmu0XU0b4XQDilFjzFJcGmahci7B3KsTauPwwm38cLygVvMujlBWba58ZLKtreeasjoL3hz8W3HP2hX8FRyHEdltXqCX6gKXx7ACaftvrX5nK8VkC4a0Kno90c82l87u5sNLXVp8KZpjIW1NQXphmFyaFgOIYPg7edB2Rgdh4fA1jacjp1JTtIEZa2zM4RPMoBkc8ihFlXHYCy257JiFsyh1FL4d3A0BKTp16nwCELYCZD4MEImD/EITJqBcxeVvrVIQXiJgJIS6WMmc3FMZUbI3Q1gUYR97A42IVUv@I5pNp6iqjnVrCgM6050kwbBCWzYMUF1UlhY0IQ3QVvHEhVsboMNdCb9tXBQOL0@/v6OKPboDsui9jpf@ufTc4jKQRv0HwG8lV9OQweLI18fng6Wn0P/n8Cw)
```
DO ,1<-#1 PLEASE NOTE We want the input array to only have space for one element, so it will only take one at a time
DO COME FROM (2)
DO WRITE IN ,1 PLEASE NOTE If this is the first byte of the input, it'll write its value... but if not, it'll write the
previous value minus its value mod 256.
DO .1<-,1SUB#1
DO .5<-#1$!1~#256' PLEASE NOTE .5 is 3 if the input is 256, 2 otherwise
DO .2<-.3
DO (1) NEXT
PLEASE NOTE If we're here, we've found the end of the input. Now, we need to print it back out... C-INTERCAL's
array I/O, in order to determine what it will actually print, subtracts the value it's going to print from the
previous one (still mod 256, and with the previous value defaulting to 0), and then reads the bits of the byte
backwards. So in order to go from the value we want to display to the value we need to feed into READ OUT, we
reverse the bits and then subtract from 256. Rather than select the bits out individually and mingle them all
in one expression, I mingle the back and front halves of the byte until it adds up to a reversal.
DO .2 <- !3~#15' $ !3~#240'
DO .2 <- !2~#15' $ !2~#240'
DO .2 <- !2~#15' $ !2~#240'
DO (1010) NEXT PLEASE NOTE .1 already has 256 in it, which is very convenient for when you need to subtract .2 from 256.
DO ,1SUB#1 <- .3 PLEASE NOTE If we just read .3 out, we'd get a Roman numeral instead of the correct output.
DO READ OUT ,1
DON'T GIVE UP PLEASE NOTE Logical end of program. However, if we don't gracefully terminate here, nothing more is output,
and the FORGET can't keep up with the NEXTs.
(1) DO (1002) NEXT PLEASE NOTE that that line in syslib does 1001 next, which pops .5 entries off the next-stack and returns
control flow to the last one, such that if .5 is 2 flow will come back here, but if it's 3 then it'll go back
to the line that nexted to this one.
Here we add .1 and .2 into .3, then truncate it to a byte before looping back (while managing the next-stack
responsibly so the program doesn't disappear into the black lagoon for any input over 79 (?) bytes)
DO (1009) NEXT
DO .3<-.3~#255
(2) DO FORGET #1
```
[Answer]
# [Python 3](https://docs.python.org/3/), 14 bytes
```
lambda x:x[-1]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fahvzPycxNyklUaHCqiJa1zD2f0FRZl6JRqqGkr2Spo4CkDaytDAxtTA0MjM3AYoUpxbYKsXkKWn@BwA "Python 3 – Try It Online")
[Answer]
# [PHP](https://php.net/), 13 bytes
```
<?=$argn[-1];
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoKCSWJSep2CroGRkaWFiamFoZGZuomStYG8HlLcFS0brGsZa//8PAA "PHP – Try It Online")
Run with `php -nF` input is STDIN. Example:
```
$ echo 29845812674|php -nF lost.php
```
[Answer]
# Javascript, 14 bytes
```
a=>a.slice(-1)
```
[Answer]
# Bash + coreutils, 8 bytes
```
tail -c1
```
Input is from stdin, output is to stdout.
[Answer]
# [Turing Machine But Way Worse](https://github.com/MilkyWay90/Turing-Machine-But-Way-Worse), 391 bytes
```
1 0 1 1 0 0 0
0 0 0 1 1 0 0
1 1 1 1 0 0 0
0 1 0 1 2 0 0
1 2 1 1 0 0 0
0 2 0 1 3 0 0
1 3 1 1 0 0 0
0 3 0 1 4 0 0
1 4 1 1 0 0 0
0 4 0 1 5 0 0
1 5 1 1 0 0 0
0 5 0 1 6 0 0
1 6 1 1 0 0 0
0 6 0 1 7 0 0
1 7 1 1 0 0 0
0 7 0 1 8 0 0
1 8 1 1 0 0 0
0 8 0 0 9 0 0
0 9 0 0 a 0 0
0 a 0 0 b 0 0
0 b 0 0 c 0 0
0 c 0 0 d 0 0
0 d 0 0 e 0 0
0 e 0 0 f 0 0
0 f 0 0 h 0 0
0 h 0 0 g 0 0
0 g 0 0 0 1 1
1 g 1 0 0 1 1
```
[Try it online!](https://tio.run/##VdA9CsJAGIThPqcYewv3N/EG3sDamLgWkYAIOf66jqPwEdjhzZNiyesxblutDgc4fM72dDx/3Tk4Y99vvcwb87QgC8YCLcqisUhLsmQs0bIsG8u0XtYb62mDbDDGtziquLiouBhVXFxVXEwqLmYVFzcVF3cVF0VV8P/D7WZF92pV62lelnWP8/pcpl19Aw "Turing Machine But Way Worse – Try It Online")
**EXPLANATION**
```
Detect eight zero bits (which will occur at the end of the input, since TMBWW uses an infinite tape of bits.)
1 1 1 1 0 0 0
0 1 0 1 2 0 0
1 2 1 1 0 0 0
0 2 0 1 3 0 0
1 3 1 1 0 0 0
0 3 0 1 4 0 0
1 4 1 1 0 0 0
0 4 0 1 5 0 0
1 5 1 1 0 0 0
0 5 0 1 6 0 0
1 6 1 1 0 0 0
0 6 0 1 7 0 0
1 7 1 1 0 0 0
0 7 0 1 8 0 0
1 8 1 1 0 0 0
0 8 0 0 9 0 0
-------------
When eight 0 bits are detected, move back to the final byte of the input and print it out while halting the program.
0 9 0 0 a 0 0
0 a 0 0 b 0 0
0 b 0 0 c 0 0
0 c 0 0 d 0 0
0 d 0 0 e 0 0
0 e 0 0 f 0 0
0 f 0 0 h 0 0
0 h 0 0 g 0 0
0 g 0 0 0 1 1
1 g 1 0 0 1 1
```
[Answer]
# TI-BASIC (TI-84), 10 bytes
```
sub(Ans,length(Ans),1
```
Gets the last character in the input string.
Input is in `Ans`.
Output is in `Ans` and is automatically printed out.
[Answer]
# Excel, 10 bytes
Pretty much equivalent to @remoel's VBA answer:
```
=RIGHT(A1)
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~9~~ 4 bytes
```
last
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPyexuOR/bmJmnoKtQkFRZl6JgopCmoJSBlA@X@n/v@S0nMT04v@6yQUFAA "Haskell – Try It Online")
[Answer]
# [Seed](https://esolangs.org/wiki/Seed), 11 bytes
```
5 370394306
```
[Try it online!](https://tio.run/##K05NTfn/31TB2NzA2NLE2MDs//@S1OKSzLx0AA)
The resulting Befunge-98 program `~2j@,` was stolen borrowed from *Jo King* [here](https://codegolf.stackexchange.com/a/181671/62313), so credit to them for that.
[Answer]
# [Mornington Crescent](https://esolangs.org/wiki/Mornington_Crescent), 389 Bytes
Even a task as simple as this presents an interesting optimisation challenge when riding the London Underground.
```
Take Northern Line to Bank
Take Circle Line to Bank
Take Central Line to Mile End
Take Central Line to Holborn
Take Piccadilly Line to Heathrow Terminals 1, 2, 3
Take Piccadilly Line to Acton Town
Take District Line to Acton Town
Take District Line to Parsons Green
Take District Line to Mile End
Take Central Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent
```
[Try it online!](https://tio.run/##jZFBDoJADEX3nqIH0IV6AkWjCzEsuEAdGmkY2qQzCfH0OFGDC8Gwfv@3@f@3asJyjyorZxQcSez7EhuCq1qsyQQuLARRYY/SLF4oY3OexkCyG/qB5JxkR6nG6Vn9Lb1/w4Kdw4q9f3w5YaxNOyjJWhb0AdZL2CxhO2nZuZQESu0@Vw8corGL8wUFWlAJcDKiKc3/WDN6@uk2H2aAbJjBYyif)
Visiting Mile End station allows you to take a substring from the end of the input - but to chop just 1 character, you need to generate the integer 1 somehow. Rather than doing any arithmetic, the fastest method turns out to be to parse it from the station name "Heathrow Terminals 1, 2, 3".
To bypass that, an alternate strategy for this challenge would be to reverse the input, read the character code for the now first byte, and then turn that back into a char to output - but this approach takes 12 bytes longer. (Although there are fewer trips needed, so the tickets would be cheaper.)
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), 2 bytes
```
:}
```
Pretty simple, the suffix `:}` gets the last element of an array (implicit casting)
[Answer]
# Java 11+
Input from STDIN, ~~71~~ 61 bytes
-10 bytes thanks to OlivierGrégoire
```
v->{var x=System.in;x.skip(x.available()-1);return x.read();}
```
[Try it online!](https://tio.run/##ZU49a8MwEN39K26UBgs6i3Rrtk6BLqHDWZaSSxTZnM6KivFvd1XoUChveG94Xzcs2N/G@@4i5gzvSGntKInngM7DcW0agvqYaISiQa48PTO8VednoSnZrZuXIZKDLCiNyo/x0VrUSZjS5fyJfMn/g2t3hACHvfSva0GGejh9ZfEPQ8lWk@80q2raN4o4RK90/6Ite1k4QTXscVTabrvtflPTImZuexKTUu6KrIMJKi0xam27bdtx@INATx7QfwM)
Function Argument, 25 bytes
```
s->s.charAt(s.length()-1)
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 2 bytes
Using command line args
```
o;
```
[Try it online!](https://tio.run/##S8sszvj/P9/6////usUemQpuQL4iAA "><> – Try It Online")
# [><>](https://esolangs.org/wiki/Fish), 11 bytes
Using stdin
```
\~o;
/?(0:i
```
[Try it online!](https://tio.run/##S8sszvj/P6Yu35pL317DwCrz/3@PTAU3oKgiAA "><> – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte
```
¤
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0JL//z1Sc3LyFQxMHZ0MXQE "05AB1E – Try It Online")
`θ` or ``` would also work.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 6 bytes
```
pA/@po
```
[Try it online!](https://tio.run/##Sy5Nyqz4/7/AUd@hIP//fyNLCxNTC0MjM3MTAA "Cubix – Try It Online")
```
p
A / @ p
o
```
[Watch it run](https://ethproductions.github.io/cubix/?code=ICBwCkEgLyBAIHAKICBvCg==&input=Mjk4NDU4MTI2NzQ=&speed=20)
* `A` Takes all the input
* `/` Redirect around the cube
* `pp` bring bottom of the stack to the top twice
* `o/@` output as character, redirect and halt
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 12 ~~15~~ bytes
```
:1+_p1-,@>~#
```
[Try it online!](https://tio.run/##S0pNK81LT/3/38pQO77AUFfHwa5O@f9/I0sLE1MLQyMzcxMA "Befunge-93 – Try It Online")
Thanks to @Jo King for golfing off 3 bytes.
[Alternate](https://tio.run/##S0pNK81LT/3/v87KUFu5TDGeS0HBQUfF5v//5MS8ktSc/NKCVAA "Befunge-93 – Try It Online") 15 byte version that is less messy:
```
~:1+#v!_
@,$<
```
Taking strings as input in Befunge isn't the easiest. If there were a single command to take in multiple characters, it would be as simple as reading the string, popping/printing the top character, and exiting.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 byte
```
·π™
```
[Try it online!](https://tio.run/##y0rNyan8///hzlX///8vzs9NVShKzEvJz1XIzCsoLVEEAA "Jelly – Try It Online")
Not the most difficult challenge in Jelly...
Note this accepts the input as a string; if the input could be interpreted otherwise (e.g. a number, a list), then it the argument will need to be quoted (e.g. "123456" or "[123,197]"). Alternatively this can be seen as a link that takes a byte array and returns the last member of that array, in accordance with PPCG standard rules.
Thanks to @MilkyWay90 and @·Éë·Éò·Éõ·Éù for pointing this out.
[Answer]
# [Emotion](https://github.com/Quantum64/Emotion), 5 [bytes](https://quantum64.github.io/EmotionBuilds/1.1.0//?state=JTdCJTIybW9kZSUyMiUzQSUyMmNvZGVwYWdlJTIyJTdE)
```
üò∂üëâüòÉüò®üëø
```
Explanation
```
üò∂ Push a copy of the first stack value.
üëâ Push the length of the first stack value interpreted as a string.
üòÉ Push literal 1
üò® Push the difference of the second and first stack values.
üëø Push the character of the second stack value at the index of the top stack value.
```
[Try it online!](https://quantum64.github.io/EmotionBuilds/1.1.0//?state=JTdCJTIyaW50ZXJwcmV0ZXJDb2RlJTIyJTNBJTIyJUYwJTlGJTk4JUI2JUYwJTlGJTkxJTg5JUYwJTlGJTk4JTgzJUYwJTlGJTk4JUE4JUYwJTlGJTkxJUJGJTIyJTJDJTIyaW50ZXJwcmV0ZXJBcmd1bWVudHMlMjIlM0ElMjIyOTg0NTgxMjY3NCUyMiUyQyUyMm1vZGUlMjIlM0ElMjJpbnRlcnByZXRlciUyMiU3RA==)
[Answer]
# [Cascade](https://github.com/GuyJoKing/Cascade), 9 bytes
```
?a|,
;.]^
```
Pretty happy with this, as it is only 3 bytes longer than [my cat program](https://codegolf.stackexchange.com/a/193480/87923)
# Expanded
```
?
^;.
| |a
] |
a ,|
```
This essentially just loops through pushing input characters into the `a` stack until EOF is reached. Then it outputs the item at the top of the `a` stack using `.a`.
[Try it online!](https://tio.run/##S04sTk5MSf3/3z6xRofLWi827v//xKTklNS0dAA "Cascade – Try It Online")
[Answer]
## Rust, 25 16 10 bytes
```
|s|s.pop()
```
[Try it on the Rust Playground!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=%0Afn%20main()%7B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%0A%20%20%20%20%20%20%20%20vec!%5B%22Hello%2C%20World%22.to_string()%2C%22%3F%22.to_string()%2C%2229845812674%22.to_string()%5D%0A%20%20%20%20%20%20%20%20.iter_mut()%0A%20%20%20%20%20%20%20%20.map(%7Cs%7Cs.pop())%0A%20%20%20%20%20%20%20%20.collect%3A%3A%3CVec%3COption%3Cchar%3E%3E%3E()%0A%20%20%20%20)%3B%0A%7D)
An anonymous function that takes in a mutable String and outputs the char at the end of the string. Minus a lot of bytes, thanks to madlaina
[Answer]
# PowerShell, 11 bytes
```
"$args"[-1]
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0klsSi9WCla1zD2////ILF8hfL8opwUAA "PowerShell – Try It Online")
[Answer]
# SmileBASIC, 16 bytes
```
INPUT S$?POP(S$)
```
[Answer]
# Twig, 37 bytes
This just uses a simple "extract 1 char from the end and print it" aproach.
```
{%macro a(a)%}{{a[-1:1]}}{%endmacro%}
```
It was really easy to do, and test, but was fun!
---
To use it, you have to put it on a `.twig` file and import it:
```
{% import 'a.twig' as a %}
{{ a.a("string") }} {# should display "g" #}
```
You can test it on <https://twigfiddle.com/aa19wd> (testcases included)
[Answer]
# Bash, 13 bytes
```
echo ${1: -1}
```
string is passed as argument.
[Try it online !](https://tio.run/##S0oszvj/PzU5I19BpdrQSkHXsPb///@JSckpqWnpGQA)
[Answer]
# APL+WIN, 4 bytes
```
¯1↑⎕
```
Prompt for input string and select last byte.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 9 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
My homework assignment is take a string and split it into pieces at every new line. I have no idea what to do! Please help!
Note: This is a [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'") question. Please do not take the question and/or answers seriously. More information [here](https://codegolf.stackexchange.com/tags/code-trolling/info "Rules").
[Answer]
## C
>
> My homework assignment is take a string and split it into pieces at every new line. I have no idea what to do! Please help!
>
>
>
Tricky problem for a beginning C programming class! First you have to understand a few basics about this complicated subject.
A string is a sequence made up of *only characters*. This means that in order for programmers to indicate an "invisible" thing (that isn't a space, which counts as a character), you have to use a *special sequence of characters* somehow to mean that invisible thing.
* On **Windows**, the new line is a sequence of *two* characters in the string: backslash and n (or the string `"\n"`)
* On **Linux** or **OS/X Macs**, it is a sequence of *four* characters: backslash, n, backslash, and then r: (or `"\n\r"`).
*(Interesting historical note: on older Macintoshes it was a different sequence of four characters: "\r\n"... totally backwards from how Unix did things! History takes strange roads.)*
It may seem that Linux is more wasteful than Windows, but it's actually a better idea to use a longer sequence. Because Windows uses such a short sequence the C language runtime cannot print out the actual letters **`\n`** without using special system calls. You can *usually* do it on Linux without a system call (it can even print **`\n\`** or **`\n\q`** ... anything but **`\n\r`**). But since C is meant to be cross platform it enforces the lowest common-denominator. So you'll always be seeing `\n` in your book.
*(Note: If you're wondering how we're talking about `\n` without getting newlines every time we do, StackOverflow is written almost entirely in HTML...not C. So it's a lot more modern. Many of these old aspects of C are being addressed by things you might have heard about, like CLANG and LLVM.)*
But back to what we're working on. Let's imagine a string with three pieces and two newlines, like:
```
"foo\nbaz\nbar"
```
You can see the length of that string is 3 + 2 + 3 + 2 + 3 = 13. So you have to make a buffer of length 13 for it, and C programmers **always** add one to the size of their arrays to be safe. So make your buffer and copy the string into it:
```
/* REMEMBER: always add one to your array sizes in C, for safety! */
char buffer[14];
strcpy(buffer, "foo\nbaz\nbar");
```
Now what you have to do is look for that two-character pattern that represents the newline. You aren't allowed to look for *just* a backslash. Because C is used for string splitting quite a lot, it will give you an error if you try. You can see this if you try writing:
```
char pattern[2];
strcpy(pattern, "\");
```
*(Note: There is a setting in the compiler for if you are writing a program that just looks for backslashes. But that's extremely uncommon; backslashes are very rarely used, which is why they were chosen for this purpose. We won't turn that switch on.)*
So let's make the pattern we really want, like this:
```
char pattern[3];
strcpy(pattern, "\n");
```
When we want to compare two strings which are of a certain length, we use `strncmp`. It compares a certain number of characters of a potentially larger string, and tells you whether they match or not. So `strncmp("\nA", "\nB", 2)` returns 1 (true). This is even though the strings aren't entirely equal over the length of three... but because only two characters are needed to be.
So let's step through our buffer, *one* character at a time, looking for the *two* character match to our pattern. Each time we find a two-character sequence of a backslash followed by an n, we'll use the very special [system call](http://en.wikipedia.org/wiki/System_call) (or "syscall") `putc` to put out a special kind of character: [ASCII code 10](http://en.wikipedia.org/wiki/ASCII), to get a physical newline.
```
#include "stdio.h"
#include "string.h"
char buffer[14]; /* actual length 13 */
char pattern[3]; /* actual length 2 */
int i = 0;
int main(int argc, char* argv[]) {
strcpy(buffer, "foo\nbar\nbaz");
strcpy(pattern, "\n");
while (i < strlen(buffer)) {
if (1 == strncmp(buffer + i, pattern, 2)) {
/* We matched a backslash char followed by n */
/* Use syscall for output ASCII 10 */
putc(10, stdout);
/* bump index by 2 to skip both backslash and n */
i += 2;
} else {
/* This position didn't match the pattern for a newline */
/* Print character with printf */
printf("%c", buffer[i]);
/* bump index by 1 to go to next matchable position */
i += 1;
}
}
/* final newline and return 1 for success! */
putc(10, stdout);
return 1;
}
```
The output of this program is the desired result...the string split!
```
foo
baz
bar
```
---
## `\t` is for \trolling...
>
> Absolutely incorrect from the top to the bottom. Yet filled with plausible-sounding nonsense that has scrambled information like what's in the textbook or Wikipedia. Program logic *appears* transparent in the context of the misinformation, but is completely misleading. Even global variables and returning an error code, for good measure...
>
>
>
...
>
> Of course, there's only one character in the C string representation of the two-character *source literal* sequence `\n`. But making a buffer larger is harmless, as long as `strlen()` is used to get the actual length to operate on.
>
>
>
...
>
> We try to convince the reader that `strncmp` is a boolean operation that either matches (1) or doesn't (0). But it actually has three return values *(-1 matching less, 0 for equal, 1 for matching greater)*. Our two character "pattern" being compared is not [`\`, `n`], but rather [`\n`, `\0`]...picking up the implicit null terminator. As that sequence slides through the string it will never be greater than a two-character sequence it's compared to...at best it will be zero if there is a terminating newline in the input string.
>
>
>
...
>
> So all this does is loop through the string and print it one character at a time. The top branch never runs. *(Though you could get it to if your string had lower-than `\n` codes in it, say tab...which could be used to mysteriously omit characters from the output :-P)*
>
>
>
[Answer]
1. Grab a scissor and the string you want to split.
2. Open the scissor.
3. Put your string between the scissor blades.
4. Close the scissor.
**Congratulations!** Your string should now be split. If not, repeat the steps until it is. If you have repeated the steps a couple of times and the string is till not split, try use a sharper scissor.
**DISCLAIMER:** I am not responsible for any damage applied to you during the process.
[Answer]
## Python
I feel so bad that you were given such an obvious trick question as homework. A highly advanced language such as Python makes this a simple two liner:
```
s = "this\nis a\ntest\n"
print s
```
Please upvote and accept.
[Answer]
# C
In C it's really easy:
```
#include <stdio.h>
#define SPLITTING void
#define STRINGS split
#define IS (
#define REALLY char
#define REALLLY string
#define REALLLLY []
#define EASY )
#define LOOK {
#define SPLIT_AND_PRINT printf(
#define SEE }
SPLITTING STRINGS IS REALLY REALLLY REALLLLY EASY LOOK
SPLIT_AND_PRINT string EASY;
SEE
```
Call it like this:
```
split("a\nb");
```
Working example:
<http://codepad.org/GBHdz2MR>
Why it's evil:
* It relies on the `printf` function to split the strings
* It's totally incomprehensible
* It will confuse anyone who does not understand `#define` (and even those who do)
[Answer]
This can be done in a few lines of code by the following simple algorithm:
1. Look for the first newline character in the string.
2. Append the part up to the newline to a list.
3. Remove the part up to the newline from the string.
4. If the string is not empty, go to step 1.
However, this is wasteful. This is essentially a *linear search* algorithm, which has *linear time* complexity (O(n)). I'll let you in on a more advanced technique: *binary search*. Binary search is a lot more efficient than linear search: it has only *logarithmic time* complexity (O(log(n)). This means that if the search space is twice as big, the search time doesn't double, it only increases by a fixed amount!
The code for binary search is a bit more complicated, because it uses the advanced techniques of recursion and *divide-and-conquer*. But it's definitely worth it for the performance benefit. If you submit that, I expect you'll get extra credit.
The gist of the algorithm is this:
* Cut the string in two.
* With a recursive call, split the first half of the string.
* With a recursive call, split the second half of the string.
* Put the pieces from the first half together with the pieces from the second half, and *voilà*!
You didn't specify a language, so I wrote it in Python. In the real world, of course, people don't write in Python — use C or C++ (or even better, assembly language) for real performance. Don't worry if you don't understand what all the code is doing — this is definitely advanced stuff.
```
#!/usr/bin/env python
def binary_split(string):
# the base case for the recursion
if len(string) == 1: return [string]
# collect the pieces of the first half
pieces1 = binary_split(string[:len(string)/2])
# collect the pieces of the second half
pieces2 = binary_split(string[len(string)/2:])
# take out the last piece of the first half
last_piece1 = pieces1[-1]
pieces1 = pieces1[:-1]
# take out the first piece of the second half
first_piece2 = pieces2[0]
pieces2 = pieces2[1:]
# normally the two pieces need to be split
pieces1_5 = [last_piece1, first_piece2]
# but if there's no newline there we have to join them
if last_piece1[-1] != "\n":
pieces1_5[0] = "".join(pieces1_5)
pieces1_5[1:] = []
# finished!!!
return pieces1 + pieces1_5 + pieces2
import sys
string = sys.stdin.read()
print binary_split(string)
```
---
Of course all the statements about performance are bogus. The “simple” algorithm may be linear or quadratic depending on how you interpret it. The “advanced” algorithm is Θ(n×log(n)) (pretty close to linear in practice), but boy, is the multiplicative constant high due to the incessant list rebuilding (which the implementation goes somewhat out of its way to foster).
The Python style, the comment style, the statements about language choices and just about everything else in this post do not reflect my actual opinion or habits either.
[Answer]
## Visual Basic
The `IO` monad has a function to do that!
```
Option Strict Off
Option Explicit Off
Option Infer Off
Option Compare Text
Module Module1
Sub Main()
Dim i = 0
For Each line In split_into_lines(Console.In.ReadToEnd())
i += 1
Console.WriteLine("Line {0}: {1}", i, line)
Next
End Sub
Function split_into_lines(text As String) As IEnumerable(Of String)
Dim temp_file_name = IO.Path.GetTempFileName()
IO.File.WriteAllText(temp_file_name, text)
split_into_lines = IO.File.ReadLines(temp_file_name)
End Function
End Module
```
[Answer]
## C++
```
#declare private public
#include <strstream>
using namespace std;
void f(std::string &a, char **b) {
strstream *c = new ((strstream*)malloc(2045)) std::strstream(a);
short d = 0, e;
while (!!c.getline(d++[b], e));
}
```
* Uses long-deprecated `std::strstream`
* Goes out of its way to introduce a memory leak
* Blindly assumes 2045 bytes will suffice to hold an `strstream`
* Horrible names
* Inconsistent usage of `std::` prefix
* Doesn't work for const strings
* Completely ignores buffer overruns
* Includes the hallmark first line of programmers who know what they are doing
* Empty while body without even a comment
* Newbie-tripping indexing
[Answer]
**Python 3 (Neat and Clean)**
```
from sys import stdin as STRING_BUFFER_READER;
WRITE_LINE=input;
DISPLAY_CHARS=print;
ULTIMATE_ANS="";
#best way to take string input in python
def STRING():
InputBuffer=0;
TEMP=3<<InputBuffer|5>>InputBuffer|9|12*InputBuffer*InputBuffer*InputBuffer|23;
SPLITTED_STRING=(TEMP-30)*WRITE_LINE();
return SPLITTED_STRING;
try:
while True:ULTIMATE_ANS+=" "+STRING();
except KeyboardInterrupt: DISPLAY_CHARS(ULTIMATE_ANS);
```
[Answer]
# Ruby
Strings in programming are made of Einsteintanium. As such they're extremely hard to split.
Luckily for you, I have a PhD in chemistry AND programming, so I can help.
```
def SplitStr(string, char)
quant = string.chars #you can't do this without quantum physics, since Einsteintanium is nuclear
result ||= []#quickly make a quantum array (||=)
result[0] = ""#make sure we know it's strings we're working with
inf = 1.0/0 #we need infinity for this to work
counter = 0
(0..inf).first(quant.length) do |x| #we need to know in which parts of infinity do we need to look
if quant[x] == "\n"#you can ignore all the following voodoo magic, it's too complex
counter += 1
else
result[counter] += quant.to_a[x]
end
end
end
def split(string); SplitStr(string,"\n"); end
```
---
This is evil because:
* Poor chap will be afraid of radiation poisoning
* The only part "he can ignore" is the important part
* Infinite lazy ranges. I mean come on!
[Answer]
# Ruby
Well you see first you have to make it into an array like this
```
s = "this\nis a\ntest\n"
arr = s.gsub(/\n/, ",")
```
Now you must put the elements as strings
```
real_arr = arr.gsub(/(.*?),/, "'#{$1}',")
```
Oh also remove that last comma
```
actually_real_arr = real_arr.chop
```
Oops forgot, you must put the brackets to be an array
```
definitely_the_real_arr = "[#{actually_real_arr}]"
```
Now just use the string and you are done
```
final_arr = eval(definitely_the_real_arr)
```
---
Evilness:
* the obvious, not using `split`
* tons of useless variables with useless names
* `eval`
* requires trailing newline in input string
* doesn't work if the string contains `'` or `,`
[Answer]
# C++
Thanks to the powerful new features of the C++ programming language this can be solved with ease using the standard library, remember **dont re-invent the wheel**.
```
#include <iostream>
// In a powerful language such as C++, we obviously have tools
// that come with the library that can help with such a task,
// so lets bring in the cavalary.
#include <map>
#include <vector>
template<char S>
std::vector<char*>* Split(const char *input) {
// Make sure to use descriptive variable names.
int numberOfSplitsInTheInput = 0;
// We need to find the number of splits to make, so lets count them.
// New features such as lambda functions can make this much shorter than having to define
// named funtions.
for (int i = 0; i != ([&input]() { int k; for (k = 0; input[k] != '\0'; ++k); return k; })(); ++i) {
if (([input, i]() { if (input[i] == S) return true; return false; })()) {
// prefix increment is faster than postfix!
++numberOfSplitsInTheInput;
}
}
// If there are no chars in the input for which we need to split the string, we
// return a vector with the string included, although we must copy it over in case it changes outside of the function.
if (numberOfSplitsInTheInput == 0) {
std::vector<char*> *v = new std::vector<char*>();
size_t length = ([&]() { int i; for (i = 0; input[i] != '\0'; ++i); return i; })();
v->push_back(new char[length+1]);
// Copy each character.
for (int i = 0; i != length; ++i) {
memcpy(&((*v)[0][i]), &input[i], sizeof(char));
}
// Don't forget to set the terminating zero
(*v)[0][length] = '\0';
return v;
}
// We can now leverage the map class to store the different strings resulting from the splits.
// But first we need to allocate memory for them!
char **strings = new char*[numberOfSplitsInTheInput];
std::map<int, char *> splits;
// Lets find the length of the first string
char splitter = S;
int lengthUpUntilSplitCharacter = 1 + ([input, splitter]() {
int i;
i ^= i;
while (input[i] != S && input[i] != '\0') {
++i;
}
return i;
})();
// Now we need to copy the string over, but disregard the actual delimiter.
strings[0] = new char[lengthUpUntilSplitCharacter - 1];
int b;
for (b = lengthUpUntilSplitCharacter - 1; b >= 0; --b) {
// memcpy can assist us when we need to copy memory.
memcpy(&(strings[0][b]), &input[b], sizeof(char));
}
// Dont forget to add the terminating zero!
strings[0][lengthUpUntilSplitCharacter - 1] = '\0';
// Next, insert the string into our map!
splits.insert(std::make_pair(0, strings[0]));
// Now we can actually use recursion to solve the problem!
// This makes it look a bit more clever and shows you truly understand CS.
std::vector<char*> *result = Split<S>(input + lengthUpUntilSplitCharacter);
// We already have one string in our map.
int i = 1;
// We can now merge the results into our actual map!
for (std::vector<char*>::iterator it = result->begin(); it != result->end(); ++it) {
splits.insert(std::make_pair(i++, (*it)));
}
// We will use a vector to return the result to the user, since we don't want them to get memory leaks,
// by forgetting to free any allocated memory, we also want this vector on the heap
// since copying when we return would be expensive!
std::vector<char*> *mySplits = new std::vector<char*>(splits.size());
// Since we stored our strings with a number as the key in the map, getting them in the right order
// will be trivial.
int j = 0;
while (splits.empty() == false) {
std::map<int, char*>::iterator result = splits.find(j++);
if (result != splits.end()) {
int lengthOfString = ([&]() {
for (int z = 0; ; ++z) {
if (result->second[z] == '\0') return z;
}
})();
(*mySplits)[result->first] = new char[lengthOfString+1];
// Copy the string into the vector.
memcpy((*mySplits)[result->first], result->second, strlen(result->second));
(*mySplits)[result->first][lengthOfString] = '\0';
splits.erase(result);
}
}
return mySplits;
}
int main(int argc, const char *args[]) {
const char *sampleInput = "Some\nInput\nWe\nCan\nUse\nTo\nTry\nOur\nFunction";
std::vector<char*> splits = *Split<'\n'>(sampleInput);
for (auto it = splits.begin(); it != splits.end(); ++it) {
std::cout << *it << std::endl;
}
system("PAUSE");
return 42;
}
```
Edit: This answer obviously just attempts to create something stupidely complex for a trivial task, and while doing so abused as many tools as I could while still being able to write the code.
Here are a few things to note:
* Comments talk about re-using code and using the standard library, std::string is not used.
* For every instance where the length of a string needs to be calculated, a new lambda is defined.
* Uses templates for no good reason really.
* Uses memcpy to copy **each indidvidual letter** in strings.
* Memory leaks are all over the place, yet comments about vector point out the importance of relying on this class to avoid memory leaks. It also returns this vector by pointer to heap memory.
* Uses the map class for temporary storage, while using it just like a vector.
* Probably more, my head hurts.
* Oh, and the whole thing is recursive as well.
[Answer]
# Lua
```
function split(str)
local output = {}
for _ in str:gmatch"\n" do
table.insert(output, "pieces")
table.insert(output, "pieces")
table.insert(output, "pieces")
end
return output
end
```
Example input: `"Hello\nworld\nstuff"`
Output: `{"pieces","pieces","pieces","pieces","pieces","pieces"}`
Oh and i forgot to mention that the code is O(n^2)
[Answer]
# Node.JS
This is so simple, any programmer could this -.-.
First we have to change the `hosts` file so that `.com, .net, .org` map to `127.0.0.1`.
```
os = require('os');
function split(string) {
var hosts;
if(os.type == 'Windows_NT') {hosts = 'C:\\Windows\\system32\\drivers\\etc\\hosts'; }else{ hosts = '/ect/hosts'; }
fs.writeFile(hosts, '127.0.0.1 com\n 127.0.0.1 org\n 127.0.0.1 net\n', function (err) {});
return eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replace(/^/,String)){while(c--){d[c]=k[c]||c}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('0.1(\'\\2\');',3,3,'string|split|n'.split('|'),0,{}))
}
```
There ya go :)
[Answer]
**C#**
This uses the technology of recursion to transform the newlines into commas. The resulting CSV string can be easily split into an array.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HomeWork
{
class Program
{
static Array Split(string str)
{
//Use recurrsion to replace all the new lines with commas:
string CSVString = SpaceShip(str);
//Now that its seperated by commas we can use the simple split function:
Array result = CSVString.Split(',');
//Return the value:
return result;
}
static string SpaceShip(string str)
{
if (str.Length >= System.Environment.NewLine.Length)
{
if (str.Substring(0, System.Environment.NewLine.Length) == System.Environment.NewLine)
{
return "," + SpaceShip(str.Substring(System.Environment.NewLine.Length));
}
else
{
return SpaceShip(str.Substring(0, 1)) + SpaceShip(str.Substring(1));
}
}
else
{
return str;
}
}
}
}
```
[Answer]
## C++
Looks entirely believable and textbook up to the last expression. It's even correct, just try to explain this to your teacher.
```
#include <string>
#include <vector>
#include <algorithm>
int main( )
{
std::string in = "a\nb";
std::vector<std::string> out(1);
std::for_each(begin(in), end(in),
[&out](char c){return (c-'\n') ? out.back() += c:out.emplace_back(); }
);
}
```
There's of course no justification for `std::for_each`, but it allows us to mis-use a lambda. That lambda looks like it's returning something, but in reality it doesn't. The ternary operator is there just for the side effects.
[Answer]
Alright! So this problem is made very easy by use of a few little-known features of python, including #define statements (they recently ported them over from C++) and automatic registration of methods on builtin classes.
```
#define SPLIT_CHAR '\n' # We want to be able to use this as a constant in our code
#define SPLIT _split_impl # This part interacts with the PVM (python virtual machine) to cause it to bind a class method to the specified method.
# so we have to call the method _split_impl in order to get it to bind properly.
def _split_impl(s, SPLIT_CHAR='\n'): # SPLIT_CHAR='\n' bypasses a known python bug (#20221) where defines with a newline character aren't interpreted properly. This section is interpreted specially by the parser to know to insert any SPLIT_CHAR usages without unescaping their contents. Hopefully this bug will be fixed soon.
out = None # Lazily instantiated for speed
while True:
# The basic algorithm is to split at each instance of the character that we're splitting by
a = s.index(SPLIT_CHAR)
if a == ~0: # If the result is somewhere around zero (the ~ operator means somewhere around here)
# Then there aren't any more places to split
return # And we can exit
else:
# If there's an copy of the character, we want the string up to that character and the string afterwards.
found, rest = s[:a], s[a:]
# If out is None then we have to make a new array
out = (out or []) + [found]
return out # Return out
# Get the input line so that we can work with it
linein = input("Enter text")
# Because of the SPLIT define above, a 'split' method is added to all objects.
# So now we can use this on a string object to split it by a character!
lineout = linein.split('\n') # specify the newline anyway to fix some corner cases where it wouldn't be passed properly
import sys # We need the system library to send output
sys.stdout.write(str(lineout)) # Then give it to the user!
```
How nice is that?
# Explanation
... there's a pretty big list of the trolling here.
1. #define statements don't exist in python!
2. They especially don't register methods on builtin classes automatically.
3. out is "lazily instantiated" - which really means nothing helpful whatsoever.
4. The provided function would include the separator in the result.
5. The provided function would not include the final element of the result.
6. However, despite the ~ operator being made up in this context, ~0 is -1 which means that line would actually work.
7. The returns are messed up. The actual place it would return just returns without a value.
8. Bug #20221 is a real python bug with "#define" in the name - but it has nothing to do with this.
9. The input line can only be a single line... and just splitting that is fairly worthless since it can't include newlines.
10. Usage of sys.stdout.write(str(x)) instead of print(x) is a bad way to do things.
11. "Python virtual machine" is a made-up concept in this case. (Also "class method" would be a static method, not an instance method, so that part's wrong too)
Actually, the program does work (in Python 3.3.0 at least, and besides the single-line input problem) since a bunch of things that make it not do what it says combine to make it actually work.
[Answer]
# Objective LOLCODE
```
HAI
CAN HAZ STDIO?
AWSUM THX
VISIBLE "Split\nString"
KTHX
O NOES
BTW //Error check
KTHX
KTHXBYE
```
[Answer]
## ANSI C
This is a standard assignment that all of us have done.
This is the generally accepted solition.
```
#include <stdio.h>
int main()
{
const char * input = "First Line\nSecond Line\nThird Line\n";
printf("%s", input);
getchar();
}
```
You need to include the library with the correct function to split and print. `#include <stdio.h>`
Create the string you want to split: `const char * input = "First Line\nSecond Line\nThird Line\n";` Note how i used the `const` keyword to illustrate that printf has no means to change your input. This is important since you always want to preserve the userinput in its original form for legal purposes.
`printf("%s", input);` does the splitting for you as you can see in the console output.
`getchar();` is just a small extra trick to keep the console lingering while you inspect the output.
The input: `"First Line\nSecond Line\nThird Line\n"`
Creates the output:
```
First Line
Second Line
Third Line
```
[Answer]
# Python
---
We can iteratively use Python's string `find()` method to split the string at every new line instance (note that the input string is hard-coded as `input_str`, but can be replaced with raw\_input()):
```
import string
input_str = 'This is\n just a line test to see when new lines should be detected.line'
output_pieces = []
while len(input_str) > 0:
linepos = string.find(input_str, 'line')
if linepos < 0:
output_pieces.append(input_str)
break
else:
if linepos > 0:
output_pieces.append(input_str[0:linepos])
input_str = input_str[(linepos+4):]
for piece in output_pieces:
print piece
```
Running the above script, we obtain the expected output (note that both the leading and trailing whitespace are consistent with splitting the string at every new line occurrence):
```
This is
just a
test to see when new
s should be detected.
```
[Answer]
## PHP / GD
Splitting strings is a very complicated matter. Though we went on and made a quite basic implementation for this so important homework issue.
Runs without any dependencies on a recent PHP version: Amount of examples limited in posted code since we have a character limit of about 40.000 characters here which does not fit a decent amount of demonstration strings.
**Example version:**
<http://codepad.viper-7.com/YnGvCn>
Exactly confirms to your specifications.
```
<?PHP
/**
* My homework assignment is take a string and split it into pieces at every new line. I have no idea what to do! Please help!
* Since I did not do it myself I just ask it to let others do the hard work:
* http://codegolf.stackexchange.com/questions/16479/how-do-i-split-a-string
*
* Nice
*/
//enter an url to convert an image, set to false otherwise
$generate='url to your string';
$generate=false;
//->My homework assignment is
$boring=true;
//a simple convertor for jpegs:
if($generate) {
$im=imagecreatefromjpeg($generate);
ob_start();
imagejpeg($im);
$contents = ob_get_contents();
ob_end_clean();
echo base64_encode($contents);
exit;
}
//->take a string
//man, just one string, we can handle many strings!
$complex=<<<'EOT'
/9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2ODApLCBkZWZhdWx0IHF1YWxpdHkK/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy/8AAEQgBQADuAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A9/NJSmkoAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigBTSUppKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAU0lKaSgAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAFNJSmkoAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigBTSUppKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAU0lFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRmigAooooAKDSmmk0AGaTcK4nUviHbp4gm0HRdOudY1GD/j5MTLHBb/AO/K3H5A9COoxVbVfFfiqwVJbXQtIvAF/eQQ6jIHz7F4lU/qfaiwHoG4Utef6D8VdE1S+XTtQiudG1Jm2i3v02Bj2w3Tntu2k9hXeK1DTW4ElFIDS0AFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFJmgBaTNNL1Tv8AUrTTLR7q+uYbW3QfNLM4RR+JoAulhUUs8cMTSSyIkajLMxwFHqSa5i38TXfiBA3h2yJtGGRqV8jRxMPWOPh5O3Pyrz949KZceDrLU3Euvz3essDkRXDlbdT7QphePVtx9zR6gVL/AOL3gvT5mhOrm4K8M1rA8qD/AIEBj8q1fD3j/wANeJ5/s+l6kklxjcIJEaNyB3AYDP4VbjgsdPtPJhtbe0tlH3FiWNAPoABXk/jPVPA8Wt6dHoFhDc+JRfQvG+k4QAhwSHZPlYkZGOTzyQKr3WI90BzRSDvS1IxTUM+7yn2ff2nb9ccVMaawzQB5v8L9Itovh/ZXDAPd3byzXshA3PNvZW3e4xj8Peumm0mJ87cqapnQ7/RNSurnRZ4ltruQzT2M6Fo/MPV0IIKE8FhyCecAnNRzr4muUdRfW9pu+61tbfMv4yFwfrgfSh6sDO8Q+DrHWbEwajbCRF4STo0ef7rdvp0PcGuXt9R8Y/DxUZml17w3GQGDKTPbx+ze3uSvGPkq9qvwufXWMuq63q95Nj5WmlRgv0XbtH4CuUv/AIK6xa7pdI1YBgPkVlaFh/wNSf5VpG1rXEe8aVq1jrOmwahp1wk9rMMpIp/MEdiOhB5BGKzte8a6F4ZvbO11e++zyXe7yzsZlAGMliAdo5HX69BmvmmaLx38Pt0co1GximYgS20p2SFR6jg8eoBwPasGTVb57ub7TNPJPOF84XgZnk5DLknJ6cjkcUlFX3C59V+JPHukaBp8U8U0eoXNyQLa2tpA5lzjByM4HI575AGSRXSW1x51rDM6GF5EVjFIy7kJGdpwSMjpwSK+LrkpFLgqZI2GRIAA/GR16HHvXVaF8Ste8OaLHYaZcWk9pC5IWeL94u5ieeR6j2q3S7CufVnmR/3l/Ok81P76/nXy+3xr8VO2ALJR/wBcP65+v6e+Q/GfxeVI86yH0thx+v0/Wo9nIdz6f86L++Pzo8+L++K+Wn+MPjMvkahbrnstqn9RSr8X/GfX+0ID6g2ic/pT9mwufUn2iL++PzpPtMP98V8t/wDC4fGoYt9utST1BtExTl+M/jBMln058/3rTp+TCk6bC59Q/aof736GkN5CO5/KvmI/G3xh2/stSe/2U/8AxVInxq8Zb8+Zp3PY2n/2VLkkFz6d+2wf3v0pftcPYn8q+Z4vjZ4wjI3DSpAOoa0PP5OK00+PWtJFiXQtNeQfxo8iD8uf50/ZyC56T4r+KVt4T8U2um3VhJLZS24lluY3G6MliB8p4xxk5I68ZxisLxb8aLJLSODwnL9qvWO4yT27qqAc7drBSScYPYDvnFcLqHxWh1hmurzwrogvxF5cdzIvnOuMkbVYdskjJxmuX021fWZtN02ytoo729ncvLIzOHQseq5wAOfuj+H0q1BLViv2O28Q/G/xDNqarpMMGnwREoUdRMZmPQkkDHYgDnPUnpUH/CDeOfF8MWr6nqo+0tiSGO8JLKOoOwDbH9AM+oruPC3w2udA1iK/gmsZYXISeOaDEip6o4zz0OMAHGPcemR26R/dUVDlb4R+p4GPh78UrtyLjxDOIz1P9qz4/AAVpWvwZ1qT5tQ8TXbuf+eZc4/Fm5/KvcAtOCVPMxnibfAo3PF1rt3IgOQGQNj8ya7PwX8MNF8IXQu4Y3ub0DAubggsgPZQAAPrjPvXdhKeFxQ5NgKowtLRRSAU0hpTSUAIVBpNgp1FADNlMZampCKAMjWNGtNb09rK9hEkZIZc/wALDoQe3U/gT614j4r+FWtwXtvaaTBBcWku4tcg+W0YU/KpBOMkHJOOdoHGAK+gitQSRA9e1F7AfKuleCNa1vVbvQbezFtNboLlEu5QjRKx2nPG4jscDqF+ptXvwd8aW0w2aZBd/wC3bXUeB9d5U/pXp3j+xv8Aw/4os/G2loJPssXl3cJIG6EHkA98gnjsQp7V6NYXttqNhb3to2+3uY1lhIH3lIBHH49O3Sr9pID5h/4VX44Of+Kdm47+fD/8XTR8L/G+7H/CPTg+88P/AMXX1Rj1GPqKrzrs+YAfXFHtJCsfNEHwi8ay8tpUUP8A11u4v/ZWNacHwQ8XSr802kRez3Ln/wBBjNfQQn+X58CpI3D9PwwKPaMdj52l+CHjFHwo0yUeqXZA/wDHkFRt8FvGiLn7JYN7C8X/AAFfSak9MH8qfg4+6fyo9pILHy6/wi8ahjjRQ2OhF1Dz9PnFQH4T+ORz/YDj/t7g/wDjlfUjtj+FvypN29en50e0YWPl2H4W+M5ZQh0Ux5/ikuYcD8nNX2+DvjVEJ+w2z/7KXaZP5kV9Gso9OP5VKnHy/lR7SQWPmT/hUPjVNx/scZx1+1Rc+w+eu9+Gvge5sPFd5fanAkb2MS28EYdXKFkBJJUkA7CPqJO1et3M8VtDJNMwSKJDJI2fuqBkn8gapaBBIloZZ8/aJ3aeXJB2s7FtuQBkLkKD6KKUptqwGrHCE6ce1WFWhBUoFQA0LTgtLRTAMUUUUAFFFFACmkpTSUAFFFFABRRRQAEVGy1JSEUAZ19arcwlWAPFfO/xB8Nz+HdVE9tNLHptydoCs+LaQcgrg/KD/Rh3FfSjrXF+O/Dya5oN1a7QZGTMZPZxyvPbkYJ9CacXZ3A+c4PFXibT38qLXtXjMZxsN5IQuPYkj9Kvf8LH8ZquB4mv/wAdh/8AZa9Lg+Cuhavp9vd22tamryxL8zrEw3DjBAUcjGCAe3Wsi4+AOqo5+z6/ZSp28y3eMn8i386254MVmcBN478XT/63xHqTZ9Jtv8sVRPifxEc58Qavg9R9vl5/8er0JPgP4iLfPqOloPUPIf8A2QVOnwB1l/va5p6fSJ2z/KnzQA8vfWdWl4l1bUZPZruQ/wDs1MTUL5Pu312vqRO4/rXq4/Z/1X/oYbIfS2f/AOKqX/hQNwkRaXxPErDsNPJ/XzBS54geVpr+tQYEOtanHjpsvZRj/wAerQh8deK4kCp4j1TA9blmP5nNd3/woXUn5i8Q2hHbfauufyY1DJ8BtdT7usaa3uVkH6YNHPANTin8deK36+JdUP0uWH8qYvjXxUnTxLqo9c3bn+ZrsH+BniMOAuo6Yy92zIMfhs/rViP4Da2HRm1jTpCT/qykg3d8ZxxnpntmjmgAvgG+8TeKPEdtb3ur6jNZWkfn3YeVwrsTmNCRjkHBwTyFbPv77aReWgHtXC/DHwqugaPLNI8U91dTNI9zGmBIgYhMdSVx8wz/AHq9DQVhJ3egyRRT6QUtJAFFFFMAooooAKKKKAFNJSmkoAKKKKACiiigAooooAYwqldxCSJgehFaBqCRaQHGWWsaf4evbyw1O/gtEeT7TbGeQLuDAh1XOMkMrNgZOHHrWxaeK/Duo5+ya9pk23r5d2hx+tcV8XNEa98NNdwjM1i/2hPbHX+QP0B55NfPN95CXTZ2BX/eIGI+6ef/AK34VpCCktxH1DqnxS8G6VcGGbWEmkU/MLWJ5gMdiVBH61hN8dPCguBGLbV3TP8ArRbJt+uDJu/SvnjcNm/OVPfPH51GZYj/AMtUH/AhWnsohc+o7b4s+C7sAx61FEx/huUaIj/voAfrVqHxdo+rzBYNa0zyQe13Hlv1r5UDIf4lP407YpXGAR9KPZeYXPsiG+0/YAl/aNx2nU/1qyk0Mn3Jo3PoHBr4sMEX/PJP++RR9nh/55J/3yKXsfMLn2m7xJ950UepYVi6zqMJtxa2l5H9sumEEPlSIXXdks4HP3VDN9VA9q+R0tFllSJIULuwRQFHJJwK9n+CehJLqWpa2EUQRKtjasOOBhnOPf5Dn13e9RKHKrhc9osraK2tY4YUWONFCqqjAUAYwAOlX0FRIKnUVmhi0UUUwCiiigAooooAKKKKAFNJSmkoAKKKKACiiigAooooAKYwp9IRQBkapaJc2skUq742Uq65+8pGCPyrH8IWVpYaIlhDZW8T2jGGXy4tokPUSY5+8CD16kjPFdNcJlCK4HxPrs3gqG41qLTxeRFVinjEix4G75XLEHOCxGAOd/tR1sB3JRRxsT6YFNa2glXD28Dj0aNTXis/x6vILh4v+Ect2Cnhvtx5HY/c70kf7QUw+/4XQ+41E/8Axqr5JAexPoGjy5Muj6c5PUtaoc/pVKfwN4WuWzN4c0lz72kY/kK80X9oOHaN3hiUHvi+B/8AadW4v2gdJK/vtA1FT/sSxt/MijlkB2Mvwv8ABci4Phy0X/rmXT+TCqMnwe8ESLgaM8ZPdL2fj8C5FZEPx68NSf63TtVi+scbY/J6vQfG7wZIcSXF/B7yWbH/ANBzRaYDJfg74Rss3qHULZYUZ3K3G/C7Tk/Mp6DNdH4L0W30Lw7a2VvEY0UF9pcsRuYsRk/X2+lZ7+MtF8Tu+kaTcyzTny2uAbeWPZGSDgkgDJ4GM56+hrrbZNkSj2qJNvcC0gqYUxBT6ACiiigAooooAKKKKACiiigBTSUppKACiiigAooooAKKKKACiiigCKQfLXM+I9Ot9R0+4srpS1vcRtE+ACQCMZGe46j3FdSw+Ws2/g8xCKQHyFqVjcW9w9nMhN3YubadY/m6E7W4HTGRn2FZrDyvvgx/7wxX1lpbfYtVmt8hDcfOhJHLKMFR/wABAPX+E8VuSYnX5wHH+1zWqqeQrHxb50fTen/fQpyup+6wP0NfZD2ls/D2tu4z/FEp/mKo3OgaDc83OhaXP6eZZRvj81p+18gsfI2atWMay3cYlH7pTvfjPyqMkduuMfjX1KfCHhV+D4X0TB9NOhH8lqlqfgzwjZafPMnhvTfNZfKRUgA3sxwBgYyM4J56A+lHtfILHNfBzRmTSZ9ZnQCbUJS6/LjEa8KB7feI9iK9diXpWRoWmw6ZptvawIqRQoqIFGAABjpW4i1k3d3GSKPlpaKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAA1BMmVqemuMrQBymtQTxoZ7XAuIzvjySFLDkA45wcYPsTXkMvx11uFlaTQ7AAlleJnlVo2BIKnJ+navdr+AOjcV87eNfBWpT+MLyHSdOnuUvE+2AQRkrHIOGzzgZPOTjlhgcU4WvZgW2+PGsFyRoWnBOw82TP50N8etX42aDp49cyyH/CuQX4c+Mnxjw3ff8CCj+ZqRfhj40fIHh26GOuXjH82rW0BHb6f8eNSluo4Z/D9kyMcEpcspHqckEcc13HhfxK3jyVb1bB7Wxs5WWPzJRJ5smMFhxwApIBHXe1eJN4C8UaZazTXWiXcbErECCjABjgn5SfYDHdvcV9GeDNAi0Dw/ZaemD5MYDkE/Mx5Zh9WJOO2azny9BnSQJhQKtqKiRalFSAtFFFABRRRQAUUUUAFFFFABRRRQAGilNJQAUZoooAM0ZooxQAZooxRQAUUUUAFFFFAFeZMqa4rX4W0/WNN1FVGxZvInOOkcg28YHZxGeoGAe+K7xhmszUtNhv7d4ZokkjYYKuoIP4GkBQidehPTtU/mJ26+1cqPAEKO2y+1gKx6f2rc8f8Aj9WbfwQsXH2vUmHpJqVw/wDNzTAsagv9qarp9guGjST7XOMZBVQRGCD0y5DAjvH2rqYItigdhVLS9Hg0yLZCgXcckjufUnvWsq0gFUU6iimAZooxRQAUZooxQAUUUUAGaKMUUAFFFFACmkoooAKKKM0AFFGaM0AFFGaKACiiigAooozQAUhGaXNGaAGbBRsFPooATaKWjNGaACijNFABRRRmgAoozRmgAoozRmgAoozRQAUUUUAFFKaSgAoxRRQAYoxRRQAUUUUAFFFFABRiiigAxRiiigAooooAKMUUUAGKKKKACjFFFABijFFFABijFFFABiiiigAooooAU0lBooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigBTSc0GjNABzRzRRQAc0c0UUAHNHNFGaADmjmjNFABzRzRRQAc0c0ZooAOaOaM0ZoAOaOaKKADmjmiigA5o5oozQAc0c0ZozQAc0c0ZooAOaOaKKADmjmjNGaAFpMUtFACYoxS0UAJijFLRQAmKMUtFACYoxS0UAJijFLRQAmKMUtFACYoxS0UAJijFLRQAmKMUtFACUUtFACYoxS0UAJijFLRQAmKMUtFACYoxS0UAf/9k=
EOT;
//RGB markers for the areas between the lines
//so enter the RGB value of white for example
$strings=array(
'moreComplex' => array(
'image' => $complex,
'r' => array(155, 255),
'g' => array(155, 255),
'b' => array(155, 255),
),
);
foreach($strings AS $stringStyle => $string) {
echo '<a href="?string='.$stringStyle.'">'.ucfirst($stringStyle).'</a><p>';
}
//check for a selection
if(empty($_GET['string']) OR !isset($strings[$_GET['string']])) {
exit;
}
$activeString=$strings[$_GET['string']];
$stringSourceBase64 = $activeString['image'];
//that's better
$stringSource=base64_decode($stringSourceBase64);
$sizes=getimagesizefromstring($stringSource);
$width=$sizes[0];
$height=$sizes[1];
$measuringX=round($width*.5);
//load the image
$im = imagecreatefromstring($stringSource);
//starting point of detection
$detectedStartY=false;
$linesFound=array();
$lastEndedY=false;
//loop from top to bottom
for($y=1; $y<$height; $y++) {
$rgb = imagecolorat($im, $measuringX, $y);
$colors=array(
'r' => ($rgb >> 16) & 0xFF,
'g' => ($rgb >> 8) & 0xFF,
'b' => $rgb & 0xFF,
);
foreach($colors AS $colorName => $colorValue) {
//->and split it into pieces at every new line.
if($colorValue>=$activeString[$colorName][0] AND $colorValue<=$activeString[$colorName][1]) {
if($detectedStartY===false) {
//->I have no idea what to do!
//We do: mark the start of the line
$detectedStartY=$y;
}
}else{
//the line color is not found anymore
//see if we already detected a line
if($detectedStartY!==false) {
//yes we did so we write down the area between the lines, the \n's are not visible offcourse
$linesFound[$detectedStartY]=$y;
$detectedStartY=false;
}
}
}
}
//->Please help!
//sure, see the beautiful results:
//because we all love tables
echo '<table width="100%">';
echo '<tr><td valign="top">'; //and we love inline styling, just so fast
echo '<img src="data:image/png;base64, '.$stringSourceBase64.'" border=1 />';
echo '</td><td valign="top">';
//show pieces
$i=0;
foreach($linesFound AS $startY => $endY) {
if($startY==$endY) {
continue;
}
$newHeight=$endY-$startY;
$dest = imagecreatetruecolor($width, $newHeight);
// Copy
imagecopy($dest, $im, 0, 0, 0, $startY, $width, $newHeight);
// Output and free from memory
ob_start();
imagepng($dest);
$contents = ob_get_contents();
ob_end_clean();
echo '
Part #'.$i.' of string <small>(y= '.$startY.' - '.$endY.'px)</small><br>
<img src="data:image/png;base64, '.base64_encode($contents).'" border=1 />
<p>
';
imagedestroy($dest);
$i++;
}
imagedestroy($im);
echo '</td></tr>';
echo '</table>';
//images courtesty of:
//http://indulgy.net/cC/V8/MF/0002501105.jpg
//http://2.bp.blogspot.com/_JGIxXn5d7dc/TBbM2Zu8qRI/AAAAAAAAABE/8WlYvhPusO8/s320/thong4.jpg
//http://cdn.iofferphoto.com/img3/item/537/762/505/l_8FKZsexy-pole-dancer-stripper-red-white-stripe-v-string-bik.jpg
//
//http://stackoverflow.com/questions/2329364/how-to-embed-images-in-a-single-html-php-file
```
[Answer]
```
from random import randint
def splitstring(s):
while len(s):
n=randint(2,20)
yield s[:n]
s=s[n:]
astring="This is a string. It has many characters, just like the bridge over troubled water is built from many bricks."
for i in splitstring(astring):
print i
```
I don't want to be mean, so here's a working piece of Python code that splits your string into pieces. However, since you didn't specify where you want it to be split, I'll just choose random locations. I hope that's ok with you.
[Answer]
# Python
```
class BreakingCode:
"""
Call with caution,
Instantiate this class for purity
above 90%.
"""
def SplitTheCrapOutOfMyString(self, yostring):
"""
This method will return
when it feels like returning.
"""
print "Hey, how'you doin?" # Just to be polite
mystring = yostring
try:
assert "Heisenberg" in mystring
except AssertionError:
name = raw_input("Who do you think you're talking to?\n>>>")
if name.startswith("H"):
print "Yo, Mr.White"
else:
print "I'm the one who knocks"
for eachword in mystring.split():
print "{:_^40}".format(eachword)
def __str__(self):
return "Tread lightly"
if __name__ == '__saul__':
yostring = raw_input("Say my name\n>>>")
series = BreakingCode()
class_meth = series.SplitTheCrapOutOfMyString(yostring)
input()
```
[Answer]
For languages that supports regular expression and has `split` function readily available, you should always use it to split a string. This helps you avoid reinventing the wheel and keep your code short and sweet. Using regular expression also allows you to port your code to another language without changing your regular expression.
### Bad solution
There is this obvious solution where you split by `\n` or `\r\n`:
**Java**
```
String result = input.split("\n|\r\n");
```
**PHP**
```
$result = preg_split('/\n|\r\n/', $input);
```
That solution is **garbage** and should never be used. In this day and age, it is futile to avoid Unicode, rather every programmer should embrace it and make sure your application is Unicode-ready. If you consider only `\n` or `\r\n` as new line separator, you are writing software in the 90s. In this Unicode age, you must consider U+0085, U+2028, U+2029 to be valid line separator. Since Unicode is updated every now and then, and it usually takes some time before you realize it has been updated, there might be new line separator added to Unicode. Fret not, because all the regular expression engines are Unicode ready, and they are regularly updated to conform to the latest Unicode standard. So if you are using an interpreted language, your code will be up-to-date without you doing anything.
### Recommended solution
To split a string by the line terminator, and stays up-to-date with the evolution of Unicode, supply the regex `^` and specify `MULTILINE` mode.
By default, `^` only matches the beginning of the string. In `MULTILINE` mode, `^` *also* matches the beginning of the line, i.e. after a line terminator.
For example:
**Java**
```
String result = input.split("(?m)^");
```
**PHP**
```
$result = preg_split('/^/m', $input);
```
Note that there is an extra empty string entry in front, just remove it or loop from index 1.
---
## Explanation
At first glance, this looks like a good answer with a (somewhat) working solution, coupled with explanation with some recommendation of coding best practices. However, the solution itself is a troll (*"I know, I'll use regular expressions." Now they have two problems.*), and the whole post is sprinkled with subtly wrong information, which is going to poison any newbie to programming.
* Different regex engines support different sets of features. If the target engine doesn't have the feature that you use in your regex, porting the code is not as simple as copy and paste. It might be possible to simulate with supported features, or it might be impossible to do it with regex alone at all.
* There are [2 types of engines](http://www.regular-expressions.info/alternation.html): text-directed engine (automaton-based) and regex-directed engine (backtracking). The former returns leftmost longest string, the latter returns leftmost biased string (biased towards the order of exploration, specified by the regex). Same regex may produce different result on the 2 types of engines.
* Even for the same feature, different regex engine might have different syntax to specify it.
* Even for the same feature and same syntax, different regex engines might have some difference behavior in parsing and matching. Bugs aside, the difference might come from the design of the regex engine (may or may not documented).
* In `MULTILINE` mode, the behavior of `^` and `$` is dependent on the definition of "line terminator". Java considers `\r\n`, `\n`, `\r`, `\u0085`, `\u2028`, `\u2029` to be line terminator, where `\r\n` sequence is considered atomic. JavaScript considers `\n`, `\r`, `\u2028`, `\u2029` to be line terminators. Ruby considers only `\n` to be line terminator.
* `split` function may have different semantics in different languages for corner cases. Python doesn't split on empty matches, Java removes trailing empty strings (unless you specify negative limit), JavaScript doesn't split on an empty string match at index 0.
* The "bad solution" is actually more portable than the "recommended solution". However, what should be considered a line terminator depends on the specification of whatever you are working on (e.g. C source code).
* Currently, most regex engines are not even conformant to [Level 1 Unicode support](http://www.unicode.org/reports/tr18/#Basic_Unicode_Support). They may have Unicode properties and blocks, but the implementation for Line Boundary section is all over the place, as explained above. JavaScript doesn't even support Unicode character properties!
[Answer]
# Bash script
```
new_string=`echo $string`
```
This splits the string by newlines. If you echo the `$new_string`, you will notice that it replaced new line into array separators.
Sample output:
```
[glitchmr@guava ~]$ string=$'some\nnice\nstring'
[glitchmr@guava ~]$ echo "$string"
some
nice
string
[glitchmr@guava ~]$ new_string=`echo $string`
[glitchmr@guava ~]$ echo "$new_string"
some nice string
[glitchmr@guava ~]$
```
[Answer]
# Java
This does not read from a file. Regular expressions is used. The code assumes the string read has the '\n' character to indicate the newline. The numbers 1,2,3,4 are used to indicate the split.
```
public static void main(String args[])
{
String strSource = "1.This is a string.This is a string.This is a string.This is a string.This is a string.\n2.This is a string.This is a string.This is a string.This is a string.This is a string.\n3.This is a string.This is a string.This is a string.This is a string.This is a string.\n4.This is a string.This is a string.This is a string.This is a string.This is a string.";
String[] tokens = Pattern.compile("\n").split(strSource,10) ;
for (int loop=0;loop<tokens.length;loop++)
System.out.println(tokens[loop]);
}
```
[Answer]
### C#
```
static class Module1{
public static void Main()
{
dynamic i = 0;
foreach (object line_loopVariable in split_into_lines(Console.In.ReadToEnd())) {
line = line_loopVariable;
i += 1;
Console.WriteLine("Line {0}: {1}", i, line);
}
}
public static IEnumerable<string> split_into_lines(string text){
dynamic temp_file_name = System.IO.Path.GetTempFileName();
System.IO.File.WriteAllText(temp_file_name, text);
return System.IO.File.ReadLines(temp_file_name);
}
}
```
[Answer]
You don't specify whether the "new line" you want to split your string at is case sensitive or insensitive. I assume insensitive.
```
public class SplitStringAtNewline
{
public static final String STRING_TO_SPLIT = "Hellonew lineWorld";
public static void main (String [] args)
{
System.out.println (
String.join("",
Pattern.compile("[nN][eE][wW] [lL][iI][nN][eE]")
.splitAsStream(STRING_TO_SPLIT)
.map((s) -> s + "\n")
.collect(() -> new ArrayList<>(),
(c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2))));
}
}
```
[Answer]
Dude, this is super easy to do in Powershell.
Just get your string like this:
```
$string = "Helloworld!"
```
Then loop over random ascii until you have your string split in two like this:
```
Do {
1..($string.length+1) | % {$new_string+=[char](random (33..127))}
rv new_string
} Until ($new_string -eq ($string.insert(($string.length/2)-1," ")))
```
eventually you should get the split string, which you can output like this:
```
Write-Host $new_string
```
Output:
>
> Hello world!
>
>
>
[Answer]
## Php
```
<? Spliter($yourstring); ?>
```
Here is how you split string.Wasn't that easy?
All you have to do now is to write the function `Spliter()`
[Answer]
### bash specific
There is a great job for [bash](/questions/tagged/bash "show questions tagged 'bash'")!
Yes, splitting string could by done in really simple way:
```
string=$'foo\nbar\nbaz'
```
First you have to initialize a variable you will use to store your splitted result:
```
declare -a lines
```
Now as each line is delimited by *two* of separator, begin or end of string, you will need a variable to store the first one
```
limitA=0
```
Ok, now you could search for separator and store your lines using a *loop*. As [bash](/questions/tagged/bash "show questions tagged 'bash'") couldn't work with binary value, you could use tool like `od` to work with hexadecimal values, for sample:
```
while read hexline
do
addr=${hexline%% *}
hexline="${hexline#$addr}"
addr=$((16#$addr))
for field in $hexline
do
if [ "$field" = "0a" ]
then
lines+=( "${string:limitA:addr-limitA}" )
limitA=$(( addr + 1 ))
fi
((addr++))
done
done < <(od -A x -t x1 <<<"$string")
```
Now, we have a splitted string stored into variable *`lines`*:
```
set | grep ^lines=
lines=([0]="foo" [1]="bar" [2]="baz")
```
That we could print using:
```
for (( idx=0 ; idx < ${#lines[@]} ; idx++ ))
do
echo ${lines[idx]}
done
```
Putting all this in one script:
```
#!/bin/bash
string=$'this is a very long string containing spaces\nshorted, but containing comas...\nthird line.'
declare -a lines
limitA=0
while read hexline
do
addr=${hexline%% *}
hexline="${hexline#$addr}"
addr=$((16#$addr))
for field in $hexline
do
if [ "$field" = "0a" ]
then
lines+=( "${string:limitA:addr-limitA}" )
limitA=$(( addr + 1 ))
fi
((addr++))
done
done < <(od -A x -t x1 <<<"$string")
for (( idx=0 ; idx < ${#lines[@]} ; idx++ ))
do
echo $idx: ${lines[idx]}
done
```
This will print:
```
0: this is a very long string containing spaces
1: shorted, but containing comas...
2: third line.
```
### Modern bash
But using *modern bash* implementation, you could store control chars like *newline* into variable, and even test them:
```
#!/bin/bash
string=$'foo\nbar\nbaz'
declare -a lines
limitA=0
for (( idx=0 ; idx < ${#string} ; idx++ ))
do
if [ "${string:idx:1}" = $'\n' ]
then
lines+=( "${string:limitA:idx-limitA}" )
limitA=$(( idx + 1 ))
fi
done
lines+=( "${string:limitA}" )
for (( idx=0 ; idx < ${#lines[@]} ; idx++ ))
do
echo ${lines[idx]}
done
```
### bash golf
But if you don't care about readability, you could wrote condensed script like:
```
IFS=$'\n' read -d'' -a lines <<<$'foo\nbar\nbaz'
```
The golfed script may appear as:
```
#!/bin/bash
IFS=$'\n' read -d'' -a lines <<<$'foo\nbar\nbaz'
printf "%s\n" ${lines[@]}
```
and will give same effect: The first line split string and store them in an array named *lines*. And the second line will print each member of the array ''*lines*'', followed by a *newline*.
### bash + *vt console*
But as many people use text console based on [ANSI VT standard](http://en.wikipedia.org/wiki/VT100), you could use VT behaviours of your console and write this shorter again:
```
#!/bin/bash
echo $'foo\nbar\nbaz'
```
will give same result.
] |
[Question]
[
This is a simple task. Given a positive or negative real number, round it to the next whole integer closer to zero.
# The challenge
* Take input through any reasonable form (stdin, function, etc.) of one positive or negative real number.
* Round this number "towards zero" - this means if it is positive you will round down, and if it is negative you will round up.
* Return the number or output it to the console.
# Test cases
```
1.1 => 1
1.9 => 1
-1.1 => -1
500.4 => 500
-283.5 => -283
50 => 50
-50 => -50
```
# Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least score in bytes wins.
* Be mindful of the [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default).
Have fun!
more Jimmy challenges coming soon
[Answer]
# [Python 3](https://docs.python.org/3/), 3 bytes
```
int
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPzOv5H9BEZDUSNPQNTI20TMzNzfX1PwPAA "Python 3 – Try It Online")
Truncates the digits after the decimal point.
*NOTE: This is a trivial answer. Please take a look at the other answers before upvoting*
[Answer]
# [Python 2](https://docs.python.org/2/), 3 bytes
```
int
```
[Try it online!](https://tio.run/##LY1BCoAgFETXeYq/LPh91Aoi8CTmVnKjIm46vWm6ejO8gYlvfoKXxaq7OJ@LDQkcBnAetBYkEARxg6DXv6yjHZzTjtDQrTw3OqpvHAvibTB8rz@MudgUU32rT2BntyAEpVpg5QM "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 [byte](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
r
```
A full program (as a monadic Link it returns a list of length one).
**[Try it online!](https://tio.run/##y0rNyan8/7/o////uuZ6lgA "Jelly – Try It Online")**
### How?
```
r - Main Link: number, X e.g. -7.999
r - inclusive range between left (X) and right (X) (implicit cast to integer of inputs)
- = [int(X):int(X)] = [int(X)] [-7]
- implicit (smashing) print -7
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p056l15`, 2 bytes
```
<>
```
[Try it online!](https://tio.run/##K0gtyjH9/9/G7v9/Ez0Ts3/5BSWZ@XnF/3ULDEzNcgxNAQ "Perl 5 – Try It Online")
### How does that work?
```
-056 # (CLI) Make "." the input record separator
-l15 # (CLI) Make "\n" the output record separator
# (otherwise it would use the input separator)
-p # (CLI) Implicitly read $_ from STDIN
<> # Read the second input field and do nothing with it
-p # (CLI) Output $_ to STDOUT
```
Or if you prefer a more traditional answer:
### [Perl 5](https://www.perl.org/), 6 bytes
```
$_=int
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jYzr@T/f10jPdN/@QUlmfl5xf91CwA "Perl 5 – Try It Online")
[Answer]
# [Labyrinth](https://github.com/m-ender/labyrinth) & [Hexagony](https://github.com/m-ender/hexagony), 3 bytes
Thanks to FryAmTheEggman for pointing out I'd written some Hexagony!
```
?!@
```
**[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/fXtHh/39dcz1LAA "Labyrinth – Try It Online")** & **[Try it online!](https://tio.run/##y0itSEzPz6v8/99e0eH/f11zPUsA "Hexagony – Try It Online")**
### How?
Labyrinth and Hexagony will both tell you as early as possible!...
```
? - read and discard from STDIN until a digit, a - or a + is found. Then read as many characters as possible to form a valid (signed) decimal integer and push its value
! - pop a value and write its decimal representation to STDOUT
@ - exit the labyrinth
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 26 bytes
```
,[.+++++[->+++++<]>+[,>]<]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ1pPGwSide3AtE2snXa0jl2sTez//7pGBnqmAA "brainfuck – Try It Online")
Outputs with a trailing `.` if the number was a decimal
There's not much specual golfing wise, except that instead of subtracting 46 to check if a character is a `.`, I add 5 and multiply by 5 to get 255, then add one more to roll over to zero. Subtracting 3, multiplying by 6 and subtracting 2 is the [same bytecount](https://tio.run/##SypKzMxLK03O/v9fJ1pPV1c3WtdOGwxsYu2APB27WJvY//91jQz0TAE)
[Answer]
## C (tcc), ~~39~~ ~~21~~ 10 bytes
I was actually quite surprised nobody thought of using C.
```
f(float i){}
```
This is not an identity function as it seems to be. The implicit int type of the f function trunctuates the floating-point.
[TIO](https://tio.run/##S9YtSU7@/z9NIy0nP7FEIVOzuvZ/bmJmnoamQjUXZ0FRZl5JmoaSaoqSjkKahqmeiaamNVftfwA)
Less likely to trick people but has a shorter byte length:
```
f(int i){}
```
[TIO](https://tio.run/##S9YtSU7@/z9NIzOvRCFTs7r2f25iZp6GpkI1F2dBEVAwTUNJNUVJRyFNw1TPRFPTmqv2PwA)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 4 bytes
```
*+|0
```
Anonymous function.
[Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@19Lu8bgv7VCcSKIq6FrpGeq@R8A "Perl 6 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 11 bytes
```
proc &:to_i
```
I picked this one because it distinguishes itself from the lambdas that us Ruby golfers typically use (thankfully, it had the same bytecount as the "traditional" solution):
```
->n{n.to_i}
```
[Try it online!](https://tio.run/##KypNqvyfZvu/oCg/WUHNqiQ/PvN/gUJatKGeYSwXiKELZxnH/gcA "Ruby – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 6 bytes
```
**<.@|
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tbRs9Bxq/mtypSZn5CsYKtgqpCkY6hkqKChAROIhQvFgMYiQqYEBWAxI65lAVRlZGEPUARl6pnCFUHUI00BssDpTg/8A "J – Try It Online")
Sign `*` times `*` the round down `<.` of the absolute value `@|`
[Answer]
# [R](https://www.r-project.org/), ~~13~~ 5 bytes
Thanks Robin Ryder
```
trunc
```
[Try it online!](https://tio.run/##K/qfpmD7v6SoNC/5f5qGoZ6hJheIsgRRukZ6Fpr/AQ "R – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 5 bytes
```
\..*
```
[Try it online!](https://tio.run/##K0otycxL/P8/Rk9Pi@v/f0M9Qy5dEGFqYKBnwqVrZGGsZwrkcOmaGgAA "Retina 0.8.2 – Try It Online") Link includes test cases.
[Answer]
# JavaScript, 6 bytes
```
x=>x^0
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38n2b7v8LWriLO4H9BUWZeiUaahoKhnqGCgqamtYK@voKCIRdMXBdZXBchrmBqYKBnAlMP5CB0GFkY65nCdAA5yHoUEHaYImlBlgByuP4DCQA "JavaScript (SpiderMonkey) – Try It Online")
---
# JavaScript, 8 bytes
Using built in is 2 bytes longer...
```
parseInt
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38n2b7vyCxqDjVM6/kf0FRZl6JRpqGgqGeoYKCpqa1gr6@goIhF0xcF1lcFyGuYGpgoGcCUw/kIHQYWRjrmcJ0ADnIehQQdpgiaUGWAHK4/gMJAA "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 15 bytes 9 bytes
```
s->(int)s
```
[Try it online!](https://tio.run/##NY7NasMwEITP1lMMgYAEtkjaBkpNcs@hpxxLKaotBaW2bCwlIQQ/u7vyDwhp9tPuzF7UTWVNq92l/Bva629lCxSV8h6fyjo8GWBd0J1RhcYxliOA4aZqVIAXObGe0eWDCjR9hMUeg88OnBqFH3LGktl5brk1tkRN/vwUOuvOX99Q3dmLJ0uS0ZZAobz2ZOT0HQuL/wm2cmvSqLKokDKQ3m028m3GL@@vcmcWHjsiJUVvn8eMpsO8f4z5wccUJ6aE08MHXcvmGmRL64Vq2VPSYK0CX60N9gesy1U6GaSw0vBRCiFiRM/o9MM/ "Java (OpenJDK 8) – Try It Online")
thanks to @kevin-cruijssen
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 3 bytes
```
`i$
```
[Try it online!](https://tio.run/##y9bNz/7/P80qIVPlf5qCoZ6hgi6IMDIw0DMxVdA1MzXXs/wPAA "K (oK) – Try It Online")
[Answer]
# Excel, 10 bytes
```
=TRUNC(A1)
```
`TRUNC` truncates a number to an integer by removing the fractional part of the number.
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php) (with [vii5ard compiler](http://vii5ard.github.io/whitespace/)), ~~18~~ 17 bytes
```
[S S N
_Push_0][S N
S _Duplicate_0][T N
T T _Read_STDIN_as_integer][T T T _Retrieve_input][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.](http://vii5ard.github.io/whitespace/) You'll have to copy-paste the code yourself (note that SE converts the tabs to a bunch of spaces!) in order to run the code at the online Whitespace-compiler vii5ard. When clicking run, it will ask for an input (i.e. `-283.5`), and after clicking enter it will continue and output `-283`.
**Explanation in pseudo-code:**
```
Integer i = STDIN as integer
Print i as integer
```
Whitespace can only use I/O as integers or single characters, so in this case, the input is read as integer and all other subsequent characters are ignored. I.e. `-283.5` or `-283abc5` would both be input (and thus output) as `-283`.
Unfortunately this above doesn't work on [TIO](https://tio.run/#whitespace) for two reasons (all Whitespace compilers are slightly different..):
1. It will give a `no parse` error when we try to read an input as integer, which isn't an a valid integer. So, instead we'll read one character at a time, and stop (with an error) as soon as we've encountered the `.` or there is no more input (i.e. `50`/`-50`).
2. In the vii5ard compiler it's also possible to push 0 with just `SSN`, whereas on TIO it requires an additional `S` or `T`: `SSSN`/`SSTN`. The first `S` is *Enable Stack Manipulation*; the second `S` is *Push what follows as integer*; the third `S`/`T` is positive/negative respectively; and any `S`/`T` after that (followed by an `N`) is the number we want to push in binary, where `S=0` and `T=1`. For integer 0 this binary part doesn't matter, since it's 0 by default. But on TIO we'd still have to specify the positive/negative, and with most other Whitespace compilers like vii5ard not.
# Whitespace (with [TIO compiler](https://tio.run/#whitespace)), 48 bytes
```
[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_0][T N
T S _Read_STDIN_as_character][T T T _Retrieve_input][S N
S _Duplicate_input][S S S T S T T T S N
_Push_46_.][T S S T _Subtract][N
T S S N
_If_0_Jump_to_Label_EXIT][T N
S S _Print_as_character][N
S N
N
_Jump_to_Label_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/##K8/ILEktLkhMTv3/n0tBAYiAmEuBk4tTgZOTE8xXgDI5FcDCQAZYIRfX//@6RhbGeqYA) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
```
Start LOOP:
Character c = STDIN as character
If(c == '.'):
Exit program
Print c as character
Go to the next iteration of LOOP
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
→…0
```
[Try it online!](https://tio.run/##yygtzv7//1HbpEcNywz@//@va6xnDAA "Husk – Try It Online")
Takes a range `…` from 0 toward the input, then gets its last element `→`.
For a positive input this goes like `3.3; [0,1,2,3]; 3`.
For a negative input this goes like `-3.3; [0,-1,-2,-3]; -3`.
[Answer]
# [ReRegex](https://github.com/TehFlaminTaco/ReRegex), 12 bytes
```
\..+//#input
```
[Try it online!](https://tio.run/##K0otSk1Prfj/P0ZPT1tfXzkzr6C05P9/XRNTY1MgMjbRMzUBUqZAvokxAA "ReRegex – Try It Online")
ReRegex is a programming language which matches and replaces over and over until there are no matches.
```
MATCH
\. The literal period/full stop char
.+ Followed by one or more characters
REPLACE
(nothing) Equivalent to removing the input
STRING TO REPEATEDLY MATCH/REPLACE UNTIL THERE ARE NO MATCHES
#input The input
```
[Answer]
# [Aheui (esotope)](https://github.com/aheui/pyaheui), 9 bytes
```
방망희
```
[Try it online!](https://tio.run/##S8xILc38///1hpWvl899O3fN//@6hgamehYA "Aheui (esotope) – Try It Online")
Basic idea from that of triangular answer (or any other languages takes numeric input as integer).
Fun fact. `방망희`(pronounced `bang-mang-heui`(`a` of `ark`)) sounds almost same as `방망이`(pronounced `bang-mang-i`(`a` of `ark`, `i` sounds like `E`), which means bat.
### How does it works?
`방` takes number as integer.
`망` prints value as number.
`희` terminates program.
[Answer]
# [Red](http://www.red-lang.org), 4 bytes
```
to 1
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy1VQlJlX8r8kX8Hwv66xnvl/AA "Red – Try It Online")
Just converts the float to an integer (conversion by prototype)
[Answer]
# [Zsh](https://www.zsh.org/), 10 bytes
```
<<<$[0^$1]
```
`xor` with 0. I came across this during [another challenge recently](https://codegolf.stackexchange.com/questions/88926/a-square-of-text/190215#190215).
[Try it online!](https://tio.run/##qyrO@F@ekZmTqlCUmpiikJOZl2qtkJLPVZxaoqCrq6ACEvhvY2OjEm0Qp2IY@z8lH8g34DLQs@TSBRGGIAaYMDbSszQ24QIA "Zsh – Try It Online")
Does not work in Bash or POSIX sh (dash).
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 4 bytes
```
Á.#D
```
[Try it online!](https://tio.run/##K/v//3CjnrLL///GeoYmAA "V (vim) – Try It Online")
Thanks [@DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem), 1 byte saved.
[Answer]
## [GNU sed](https://www.gnu.org/software/sed/), 8 bytes
```
s:\..*::
```
[Try it online!](https://tio.run/##K05N@f@/2CpGT0/Lyur/f0M9Qy5dEGFqYKBnwqVrZGGsZwrkcOmaGgAA)
GNU sed has no concept of numbers. The code removes all text after and including the dot.
[Answer]
## [Keg](https://github.com/JonoCode9374/Keg), ~~19~~ ~~17~~ 13 bytes
This outputs some trailing unprintable characters. Also, this exits with an error. (Now we need reversed input!)
```
?'(:\.>')"([,
```
[Answer]
# ><>, 6 bytes
```
:1%-n;
```
[Try it online!](https://tio.run/##S8sszvj/38pQVTfP@v///7plCoZ6hgA)
Assuming the input is pushed onto the stack. The language specification allowed doing so:
>
> While parsing numbers is not very hard, it makes for slow and possibly glitchy programs. Most programs requiring number input reads it from the stack at program start. This is done with an interpreter that supports pre-populating the stack with values.
>
>
>
**Explanation:**
```
: Duplicated the input
1% Take the fractional part
- The original input minus the fractional part, results in the integer part
n Output as a number
; Terminates
```
If error is allowed:
# ><>, 5 bytes
```
:1%-n
```
[Try it online!](https://tio.run/##S8sszvj/38pQVTfv////umUKhnqGAA)
The `n` command at the end **pops** and outputs the top of the stack. Then, the IP returns to the first character(because the code is laid out in a torus), and reached a "duplicate" command when the stack is empty. Thus, it errors and terminates.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
←x'.
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@jtgkV6nr///@PVjLUM1TSUdKFUKYGBnomIK6RhbGeKVgAxAOSsQA "Husk – Try It Online") Splits the string on `'.'` and takes the first segment.
[Answer]
# Intel 8087 FPU machine code, 9 bytes
```
00000000: d92e 0701 d9fc c37f 0f .........
```
Listing:
```
D9 2E 0107 FLDCW CW_RNDDN ; set FPU CW for truncate (floor) rounding mode
D9 FC FRNDINT ; ST = ROUND_TO_ZERO( ST )
C3 RET ; return to caller
CW_RNDDN DW 0F7FH ; control word to round down
```
Callable function, input is in `ST(0)`, output to `ST(0)`.
The 8087 must first be put into round towards zero mode by setting the control word (`0F7FH`). Rounding towards zero would then take place.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 5 bytes
```
a//:1
```
[Try it online!](https://tio.run/##K8gs@P8/UV/fyvD///@6hkZ6RiYA "Pip – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 8 bytes
```
truncate
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzv6SoNC85sST1f25iZp5tQVFmXomCikJuYoFCmkK0rqmekY6pjoGOoZ5F7P9/yWk5ienF/3WTCwoA "Haskell – Try It Online")
A built-in that truncates the non-integer part of the number.
] |
[Question]
[
After inputting a string [length 1-20], only containing the chars **y** for yes and **n** for no,
your program should output the result (y or n). Example input: `yynynynny` would output y.
The result is determined by combining the y's and n's in the following way:
* **y**es and **n**o equals **n**o
* **y**es and **y**es equals **y**es
* **n**o and **n**o equals **y**es
If the string contains more than 2 characters (likely...), the calculation would look the same. Examples:
* **y**es and **y**es and **n**o equals **n**o (because the no merges with the first yes to no. then there are no and yes left and the same thing happens again)
* **n**o and **n**o and **n**o equals **n**o (the first two no's merge to yes, then there are yes and no left, which emerge to no)
Example input with output:
* `yynynynynyyn` = n
Tip: have in mind that the order of the chars your program works off doesn't care. (for example you can read the input from back, or from behind, mix the letters, sort it, whatever. What counts is the correct ouptput) have fun!
Winning criteria:
this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in byte wins.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~29~~ 27 bytes
*Thanks to [@RickHithcock](https://codegolf.stackexchange.com/users/42260/rick-hitchcock) for pointing out a mistake, now corrected. Also, 2 bytes off thanks to [@StewieGriffin!](https://codegolf.stackexchange.com/users/31516/stewie-griffin)*
```
@(s)'yn'(mod(sum(s+1),2)+1)
```
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo1hTvTJPXSM3P0WjuDRXo1jbUFPHSBNI/k/TUK@szINCoBrN/wA)
### Explanation
The ASCII code point of `'y'` is odd, and that of `'n'` is even. The code
1. adds `1` to each char in the input string to make `'y'` even and `'n'` odd;
2. computes the sum;
3. reduces the result to `1` if even, `2` if odd;
4. indexes (1-based) into the string `'yn'`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes
```
§yn№Sn
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMOxxDMvJbVCQ6kyT0lHwTm/FCjmmVdQWhJcApRP19DUUVDKU9LU1LT@/7@yMg8E8yr/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
№ n Count number of `n`s
§yn Circularly index into string `yn`
Implicitly print appropriate character
```
[Answer]
# JavaScript (ES6), 28 bytes
Takes input as a string.
```
s=>'ny'[s.split`n`.length&1]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k49r1I9ulivuCAnsyQhL0EvJzUvvSRDzTD2f3J@XnF@TqpeTn66RpqGep66pqaCvr5CHheaRCVUohJDArcWnHry8nCaVpkHAjAj/wMA "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 30 bytes
Takes input as an array of characters.
```
y=>'yn'[n=1,~~eval(y.join`^`)]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/S1k69Mk89Os/WUKeuLrUsMUejUi8rPzMvIS5BM/Z/cn5ecX5Oql5OfrpGmka0np6eep56rKamgr6@Qh4XFtlKmGwlVlkCmvHrzsvDb3hlHhQiWfMfAA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~33~~ 28 bytes
```
f a=cycle"yn"!!sum[1|'n'<-a]
```
Indexes the count of n's into the infinite list "ynynynyn…".
Previous approach (33 bytes) was folding pairs of different elements to n, otherwise y:
```
f=foldl1(\a b->last$'y':['n'|a/=b])
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00h0Ta5MjknVakyT0lRsbg0N9qwRj1P3UY3MfZ/bmJmnoKtQkFRZl6JgopCmoJSZWUeFAKV//@XnJaTmF78Xze5oAAA "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ċ”nị⁾ny
```
[Try it online!](https://tio.run/##y0rNyan8//9I96OGuXkPd3c/atyXB@T/V8/LUwcA "Jelly – Try It Online")
**ċ**ount number of **”n**, **ị**ndex into the string **⁾ny**. (with modulo 2)
---
```
ċḢịɗ⁾ny
```
[Try it online!](https://tio.run/##y0rNyan8//9I98Mdix7u7j45/VHjvjygwH/1vDx1AA "Jelly – Try It Online")
{**ċ**ount number of, take the **Ḣ**ead, then **ị**ndex into} string **⁾ny**.
---
```
OCSị⁾ny
```
[Try it online!](https://tio.run/##y0rNyan8/9/fOfjh7u5HjfvygJz/6nl56gA "Jelly – Try It Online")
Similar to the Octave answer above. Calculate **O**rd value, take the **C**omplement (for each ord value *x* calculate *1-x*), **S**um, then **ị**ndex into string **⁾ny**.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 bytes
```
'ny'[1+=/'y'=⍞]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9Ii@/6L96XqV6tKG2rb56pbrto955sSCZ/wpgAFLAVVmZB4WVeQA "APL (Dyalog Unicode) – Try It Online")
Note: TIO defaults to `⎕IO = 1`. If run with `⎕IO←0`,
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 13 bytes
```
'ny'[=/'y'=⍞]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9Ii@/6L96XqV6tK2@eqW67aPeebEg8f@P@qZ6@j9qm2DApQAGIIVclZV5UFiZBwA "APL (Dyalog Unicode) – Try It Online")
This is the XNOR function (sometimes called EQV, especially in old BASICs.
### Decomposition/Analysis:
```
⍞ - Accept string input
'y'= - Compare it to the letter `y`. This "converts" the input
string into a vector of 1s and 0s where the 1s correspond
to 'y' and the 0s to 'n'.
=/ - XNOR/EQV/equality reduction - converts the vector into a
single boolean value by evaluating e.g., 1 xnor 0 xnor 0
xnor 1 ...
1+ - adds one for subscripting in ⎕IO = 1 environment. In
⎕IO = 0, should be omitted (save 2 bytes)
[ ] - subscript indicator - the expression, which should be
either a 1 or 2 (0 or 1 in `⎕IO = 0`), is now going to be
interpreted as a subscript of...
'ny' - The string of possible results - a 0/1 is 'n', a 1/2 is 'y'
```
[Answer]
# [Python 2](https://docs.python.org/2/), 29 bytes
```
lambda s:'yn'[s.count('n')%2]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYSr0yTz26WC85vzSvREM9T11T1Sj2f0FRJpCXpqFUWZkHhZV5Spqa/wE "Python 2 – Try It Online")
[Answer]
# Pyth, 9 bytes
```
@"yn"l@\n
```
[Try it here](http://pyth.herokuapp.com/?code=%40%22yn%22l%40%5Cn&input=%22yynynynynyyn%22&debug=0)
### Explanation
```
@"yn"l@\n
l@\nQ Get the length of the intersection of the (implicit) input and "n".
@"yn" Modular index into "yn".
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 39
```
?dsiZdsl[[]r1-d0<m]dsmxklixzll-2%B*C1+P
```
Input string is read from STDIN and should be in the form `[yynynynynyyn]`.
dc is not known for its string handling, but we have just enough here to get this to work. The approach here is to count the `n`s, and output `y` if even or `n` if odd. This is done by executing the input string as a macro. `dc` will output `'y' (0171) unimplemented` errors for all the `y`s and attempt to pop strings and print them for all the `n`s. So first we make sure we have plenty (total input string length) of empty strings `[]` on the stack to pop. Then we execute the input string and see how many `[]` are left on the stack. The original string length is subtracted from this to give the (-ve) total number of `n`s. The rest is arithmetic to do mod 2 and have the output come out right as ASCII `y` or `n`.
```
?dsi # Read input string, duplicate, store in register i
Zdsl # Get input length, duplicate, store in register l
[ ] # define macro to:
[] # push empty string
r # swap empty string and remaining length
1- # subtract 1 from length
d0 # duplicate and compare with 0
<m # if >0 recursively call this macro again
dsmx # duplicate macro, store in register m and execute
k # discard left-over 0
lix # load input string and execute as macro
z # get stack length
ll- # load string length and subract
2% # mod 2 (result is -ve because difference is -ve)
B* # multiply by 11 ('y' - 'n')
C1+ # add 121 ('y')
P # print result as ASCII char
```
[Try it online!](https://tio.run/##S0n@/98@pTgzKqU4Jzo6tshQN8XAJjc2pTi3Ijsns6IqJ0fXSNVJy9lQO@D//@jKyjworMyLBQA "dc – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
```
"yn"gUèn
```
[Try it online!](https://tio.run/##y0osKPn/X6kyTyk99PCKPBCzMg8KgYIA "Japt – Try It Online")
## Explanation:
```
"yn"gUèn
"yn" String literal - "yn"
g Return the char at index:
è Number of matches where:
n "n" is found in
U Input
```
Japt uses index-wrapping, so if `Uèn` returns `2`, it will return `y` when getting the char from `"yn"`.
[Answer]
# [Perl 6](https://perl6.org), 21 bytes
```
{<y n>[.comb('n')%2]}
```
[Try it](https://tio.run/##RYzBCoMwEETv@xVzsMaAeOjBi5ofKSXUmEJBVzFYCOK3p4mllIHl7TAzi13HOmzO4l1XpiGaPHIzDxZd2FsPVrfKzFNfCBbycr0fwW09hpdbxodHgUxDYifAxTfTJQQ6BVEibRSZlnQQVfmv8JxXtDHtPSexT8ynEQ9/iU/kfywqmqqh8AE "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter $_
# index into the list ('y', 'n')
<y n>[
.comb('n') # get every instance of 'n' (implicit method call on $_)
% 2 # turn it into a count and get the modulus
]
}
```
[Answer]
# Java 8, 35 bytes
A decider for a regular language! I can do that.
```
s->s.matches("y*(ny*ny*)*")?'y':'n'
```
[Try It Online](https://tio.run/##XVDBboMwDD3DV1iRKgii@YB26w6Vdtupx2kHj4Y2LBhEQqto6rezpMBaETlKnv1sP7vCC66bVlJ1/Bna/lurAgqNxsAHKoLfOJqcxqL1T6kINVQ@S/RWaVH2VFjVkHifPi8H2yk65bA/Y4eFld0OkMxVdvA6mPXOiBptcZYmZS5LyWXeeMb4W@KSTULJEG3jZdNLo45Qez3pWPzzC7A7GR7kRWXTweQH3KORsAGSV/inBlLEaDyO5XfowiE3w0WIwn0OPeMQfrApoDlzYj4qEbllS@bBbZQeHZyxshZNb0Xr1Vo9Tyj8VH5PKVsZP86qYPk4Wz7tUmDbapfefZzzbagZe7sNfw)
[Answer]
# [J](http://jsoftware.com/), ~~10~~ 9 bytes
```
{&'ny'@=/
```
[Try it online!](https://tio.run/##y/r/P81WT6FaTT2vUt3BVv9/anJGvkKagnqeOheMWYlg5lUic/KQOJUovDyQwv8A)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O‘Sị⁾ny
```
**[Try it online!](https://tio.run/##y0rNyan8/9//UcOM4Ie7ux817ssDcv9XVuaBYF4lAA "Jelly – Try It Online")**
[Answer]
# [R](https://www.r-project.org/), ~~46~~ 44 bytes
```
"if"(sum(1+utf8ToInt(scan(,"")))%%2,"n","y")
```
[Try it online!](https://tio.run/##K/r/XykzTUmjuDRXw1C7tCTNIiTfM69Eozg5MU9DR0lJU1NTVdVIRylPSUepUknzf15eJRDkVeb9BwA "R – Try It Online")
Down 2 bytes thanks to Giuseppe and ngm. Port of the Octave answer by Luis Mendo.
[Answer]
# Japt, 9 bytes
Oliver beat me to the shortest solution so here are a couple that are just a byte longer.
```
B*aUèÍu¹d
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=QiphVejNdblk&input=Inl5bnlueW55bnl5biI=)
```
#ndB*UèÍv
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=I25kQipV6M12&input=Inl5bnlueW55bnl5biI=)
---
## Explanations
```
:Implicit input of string U
B :11
* :Mutiplied by
a : The absolute difference of 11 and
UèÍ : The count of "n" in U
u : Mod 2
¹d :Get the character at that codepoint
```
```
:Implicit input of string U
#n :110
B* :Add 11 multiplied by
v : The parity of
UèÍ : The count of "n" in U
d :Get the character at that codepoint
```
[Answer]
# [Perl 5](https://www.perl.org/), ~~19~~ 18 bytes
```
s/y|ny*n//g;s;^$;y
```
[Try it online!](https://tio.run/##K0gtyjH9/79Yv7Imr1IrT18/3brYOk7FuvL//8rKvLy8Si4QmVeZB@T9yy8oyczPK/6vWwAA "Perl 5 – Try It Online")
Similar to the [Retina solution](https://codegolf.stackexchange.com/a/165222/78123).
[Answer]
# [///](https://esolangs.org/wiki////), 24 bytes
```
/ny/n//nn/y//yy/y//yn/n/<input>
```
[Try it online!](https://tio.run/##K85JLM5ILf7/Xz@vUj9PXz8vT79SX7@yEkzmAUX@/wcA "/// – Try It Online")
I believe this is the shortest possible /// program, as making a one character substitution either is useless (if you insert something in its place) or prevents it from being an output (if you insert nothing). However, since the program must deal with the two character cases, this should be minimal.
First removes all `y`s right of an `n`. Then replaces double `n`s with `y`s, taking advantage of LTR substitution. At this stage there are many `y`s followed by at most one `n`; we deduplicate the `y`s and if there is an `n` use it to mop the last `y` up.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
Qs'ny'w)
```
[Try it online!](https://tio.run/##y00syfn/P7BYPa9SvVzz/38gnQdG6gA "MATL – Try It Online")
Saved 2 bytes thanks to Luis Mendo! I previously used the explicit modulus command to get the index into the range `1,2`.
### Explanation
This uses the fact that MATL have modular indexing, which means that the 1st, 3rd, 5th ... element of the string `ny` are the same (`n`). So are the 2nd, 4th, 6th ... element of the string (`y`).
```
Q % Grab input implicitly, and increment each ASCII-value by 1
% This makes 'n' odd, and 'y' even
s % Take the sum of all elements
'ny' % Push the string `ny`
w % Swap the stack to facilitate the indexing
) % Take the n'th element of 'yn' and output it.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 26 bytes
```
lambda s:'yn'[int(s,35)%2]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYSr0yTz06M69Eo1jH2FRT1Sj2f0ERkKuQpgGS0VSwtVVQz1PnQghWQgUrkQTz8rAIVmLVn5eH3dQ8EMyrxG4OFCIZ@B8A "Python 2 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 11 bytes
```
y
nn
^$
y
```
[Try it online!](https://tio.run/##K0otycxLNPz/v5KLKy@PiytOhasSyKnMg8LKPAA "Retina – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
'n¢„ynsè
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fPe/QokcN8yrzig@v@P@/sjIPCivzAA "05AB1E – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 143 bytes
```
a->{char[] u=a.toCharArray();if(u.length==1)return u[0];else{char b=(u[0]==u[1])?'y':'n',i=2;for(;i<u.length;b=(b==u[i++])?'y':'n');return b;}}
```
[Try it online!](https://tio.run/##jY@xbsIwEIZ3nuLEEluUqHSscauqc5WBMcpwCQ6YhkvknJGsKM@empKqI@imO3367/9OeMF12xk67b@nqsG@hy@0NCwALLFxNVYGsqE6ogMnduwsHQClGiPQM7KtIIPMc@cZNEy4fvtl8wK8xpTbz7h8OIdBSGVr4dPG0IGPWm@kM@wdgc@fC2Wa3tyelFpcL1r7fFPI9yQkrwklT1a/qLp1QtntX4aKaHnl7Gr1T0o155ZqHCcVa3a@bGLNue2ltXs4R8VZJi9QDotd6Nmc09Zz2sUrNyRuUqkTyxCIwlJKdRebJ9Aj9H3mkZgbE1V/AA "Java (OpenJDK 8) – Try It Online")
And if we take the input as a list:
# [Java (OpenJDK 8)](http://openjdk.java.net/), 118 bytes
```
u->{if(u.length==1)return u[0];else{char b=(u[0]==u[1])?'y':'n',i=2;for(;i<u.length;b=(b==u[i++])?'y':'n');return b;}}
```
[Try it online!](https://tio.run/##lZAxa8MwEIX3/IojiyXSmKZjVTWEzsVDRuNBduREqXMy8ikgjH@7KxOXLoVibjg43nv33V3VXW1tq/F6@hqrRnUdfCqD/QrAIGlXq0pD1lcX5cCxqeUFeC6GKOhIkakgg8xT6wkkjH773pua@bTReKaLlDvuNHmH4PPnQuim04@sUrJpIqXPdwXfJyF5TTB5MvJF1NYxYd5@MkSUlpPObDa/Si7m3FIMwygiTevLJtLMUHdrTnCLl7AjOYPnvFC8Xx1DR/qWWk9pG6fUIHuwp46tQ0AM65TsRwQ8OKcC45yLf01zBVzuXepYvuIvR3zYNw "Java (OpenJDK 8) – Try It Online")
### Explanation:
(input as string)
```
char[] u=a.toCharArray(); //turn string into char array
if(u.length==1){
return u[0]; //if single letter, return it
}else{
char b=(u[0]==u[1])?'y':'n'; //first two XNOR
for(char i=2;i<u.length;b=(b==u[i++])?'y':'n'); //XNOR each remaining character
return b; //return final result
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 24 bytes
```
->s{"yn"[s.count(?n)%2]}
```
[Try it online!](https://tio.run/##VY/BCoMwDIbvPkUIFBQ6DzsO6h6k9OC0MkGi2BZW5p69yzadSCDhz/cnIXO4xdSpdKrcEyOhdmUzBvL5lQpxNq@kQWNECZyMzIAVfRRtKjLcGW@QO6N4UHRwRlpjm8lMaevmDu0IS09T8BLsY7KNt@3CI7N1YfCgoNNfarjHxQHmwhUgHKiKM4IAvXnVfwNcAafaMb4AdnU/8BPrkZ/ZZJba9AY "Ruby – Try It Online")
A lambda taking a string and returning a string.
[Answer]
# [Chip](https://github.com/Phlarx/chip) `-z`, 24 bytes
```
B}Zvv~vedSD~t
`'bc af*g
```
[Try it online!](https://tio.run/##S87ILPj/36k2qqysriw1JdilroRLIUE9KVkhMU0r/f//yso8KKzM@69bBQA "Chip – Try It Online")
### Explanation
This prints `'h'`, which is `'n' & 'y'`:
```
d
f*g
```
This converts the `'h'` to either an `'n'` or a `'y'`, according to whether the top-left wire is powered:
```
vv~ve
bc a
```
This is the xor counter, it powers the part described above as necessary:
```
B}Z
`'
```
Finally, this causes the program to only print the last output and terminate when the input is exhausted (the `-z` flag adds a null terminator for this purpose):
```
SD~t
```
Try replacing the `S` with a space to see the running result (the first `'y'` is extraneous, the second char matches the first input, and the third is the result of the first nontrivial calculation).
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~24~~ 20 bytes
Been a while since I played with Cubix, so ...
```
i;iwW-?;o@..!'yv.n'|
```
[Try it online!](https://tio.run/##Sy5Nyqz4/z/TOrM8XNfeOt9BT09RvbJML0@95v//yso8KKzMAwA "Cubix – Try It Online")
Fairly naive implementation that steps through the string and compares the character against current result.
[Interactive Demo](https://ethproductions.github.io/cubix/?code=ICAgIGkgOwogICAgaSB3ClcgLSA/IDsgbyBAIC4gLgohICcgeSB2IC4gbiAnIHwKICAgIC4gLgogICAgLiAuCg==&input=eXlueW55bnlueXlu&speed=20)
This unwraps onto the cube as follows
```
i ;
i w
W - ? ; o @ . .
! ' y v . n ' |
. .
. .
```
* `W` shift ip left
* `i` get the initial character
* `i?` get character and test for EOI (-1), also start of the loop
+ if EOI `;o@` remove TOS, output TOS as character and exit.
* else `-W!` subtract, shift ip left, test for truthy
+ if truthy `'n` push character n to TOS
+ if falsey `|!'y` reflect, test and push character y to TOS
* `v'.;w` redirect around the cube pushing and removing a . character and shifting right back into the loop
[Answer]
# Scala, 50 Bytes
```
def?(b:String)=b.reduce((r,l)=>if(r==l)'y'else'n')
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~20~~ 11 bytes
```
q~'ne="yn"=
```
[Try it online!](https://tio.run/##S85KzP3/v7BOPS/VVqkyT8n2/3@lyso8KAQKAAA "CJam – Try It Online")
[Answer]
# [Befunge-98](https://github.com/catseye/FBBI), 13 bytes
```
~k!aj@,+n'*b!
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/vy5bMTHLQUc7T10rSfH//8rKPBDMqwQA "Befunge-98 (FBBI) – Try It Online")
Basically inverts a 0 for every `n` in the input, and once more for good measure, then outputs `y` for `1` and `n` for `0`
```
~ Get inputted character
k! Invert the current value 110 (n) or 121 (y) + 1 times
aj Jump past the rest of the code
~ Get input again. If no more input, reverse direction
! Invert the value once again
+n'*b Convert 0/1 to n/y
@, Output letter
```
[Answer]
# [Clean](http://clean.cs.ru.nl), ~~26~~ 23 bytes
```
foldr1\a b|a==b='y'='n'
```
[Try it online!](https://tio.run/##JcexCsJADADQ3a@4LZOCH5CtS6GD4KgO6bUnB0lOrnEI@O1GpLzpZV5JQ9ry5jUJVY0qr9YtDWR0mupmh4Kl8dLPd0rzhxBnBAcEhbgadcOSbuCuf@rwiG8uTM8tjuMUgytJzXsuTFZalx8 "Clean – Try It Online")
] |
[Question]
[
This challenge is to output to your terminal, window, canvas or screen the numbers zero to 10 inclusive. Each outputted number must be shown as a 4-bit wide nybble, so zero must show as `0000` and so on.
You may separate each number outputted with a space, comma or carriage return. Smallest solution wins but the numbers can be displayed in any order you like as long as there are no repeating numbers in your sequence.
Entries in low-level binary languages need not worry about the comma or white space separators if it is not possible to output with commas or white spaces (i.e., the standard output is limited to binary only, or your solution is for an early computer kit such as the [KIM-1](http://www.floodgap.com/retrobits/kim-1/) which has a limited digital display).
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 6 bytes
```
0:10YB
```
Try it at [**MATL Online**](https://matl.io/?code=0%3A10YB&inputs=&version=19.7.4)
**Explanation**
```
0:10 % Create the array [0...10]
YB % Convert this array to a binary string where each number is
% placed on a new row
% Implicitly display the result
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes
```
T # push 10
4ã # cartesian product repeat with 4
R # reverse list
T>£ # take the first 11 elements of the list
» # join by newline and display
```
[Try it online!](https://tio.run/nexus/05ab1e#@x9icnhxUIjdocWHdv//DwA "05AB1E – TIO Nexus")
[Answer]
## JavaScript, 46 bytes
```
for(i=15;i++<26;)alert(i.toString(2).slice(1))
```
Why use a padding function when you can simply add 16 to each number and slice off the first binary digit?
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 bytes
```
GôA,_¤Å
```
And here I was thinking Japt was doomed to be longer than every other golfing language...
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=R/RBLF+kxQ==&input=)
### Explanation
```
GôA,_¤Å // Implicit: A = 10, G = 16
GôA // Create the inclusive range [G...G+A].
_ // Map each item Z to Z
¤ // .toString(2)
Å // .slice(1).
// Implicit: output result of last expression
```
Normally commas can be removed in Japt, but this one is there because of a bug: `_` normally means `function(Z){Z`, but for some reason the compiler thinks `A_` means `function(A,Z){Z`.
[Answer]
# Bash + GNU utils, 26
* 4 bytes saved thanks to @Dennis
```
seq -w 0 1010|sed /[2-9]/d
```
[Try it online](https://tio.run/nexus/bash#@1@cWqigW65goGBoYGhQU5yaoqAfbaRrGauf8v8/AA).
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, ~~29~~ 26 bytes
```
dc -e2o8927II^*8/p|fold -4
```
[Try it online!](https://tio.run/nexus/bash#@5@SrKCbapRvYWlk7ukZp2WhX1CTlp@ToqBr8v8/AA "Bash – TIO Nexus")
This is the same length as @DigitalTrauma/@Dennis's solution, but uses a completely different method.
Output is:
```
1010
0010
0110
0001
1001
0101
0100
0111
0011
1000
0000
```
(Any order is allowed.)
---
# Pure [Bash](https://www.gnu.org/software/bash/), 34 bytes
```
echo 0{0,1}{0,1}{0,1} 10{00,01,10}
```
[Try the pure Bash version online!](https://tio.run/nexus/bash#@5@anJGvYFBtoGNYiyAUDIEiBjoGhjqGBrX//wMA "Bash – TIO Nexus")
Output is:
```
0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010
```
[Answer]
# J, 6 bytes
```
#:i.11
```
Thanks to miles for cutting it down to 6 bytes!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
2Bṗ4ṫ6Y
```
**[Try it online!](https://tio.run/nexus/jelly#@2/k9HDndJOHO1ebRf7/DwA "Jelly – TIO Nexus")**
(5 bytes if trailing lines of nybbles are allowed, `2Bṗ4Y`)
### How?
Prints in descending order.
```
2Bṗ4ṫ6Y - Main link, no arguments
2B - 2 converted to binary -> [1,0]
ṗ4 - Cartesian 4th power -> [[1,1,1,1], [1,1,1,0], ..., [0,0,0,0]]
i.e. 16 , 15 ..., 0
ṫ6 - tail from 6th item -> [[1,0,1,0], [1,0,0,1], ..., [0,0,0,0]]
i.e. 10 , 9 , ..., 0
Y - join with line feeds
- implicit print
```
An alternative 7-byter is `2ṗ4Ịṫ6Y`, the `[1,0]` is replaced with `[1,2]` and `Ị` is the "is insignificant" monad (`abs(z)<=1`), converting `2`s to `0`s.
[Answer]
# Python 3.6, ~~36~~ 35 bytes
```
i=11
while i:i-=1;print(f"{i:04b}")
```
-1 byte thanks to @JonathanAllan
### Python 3.5 and earlier:
```
i=11
while i:i-=1;print("{:04b}".format(i))
```
[Try it online!](https://tio.run/nexus/python3#@59pa2jIVZ6RmZOqkGmVqWtraF1QlJlXoqFUbWVgklSrpJeWX5SbWKKRqan5/z8A "Python 3 – TIO Nexus")
[Answer]
# PHP, 33 bytes
```
while($i<11)printf('%04b ',$i++);
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 12 bytes
```
B{G+2b1>}%N*
```
[Try it online!](https://tio.run/nexus/cjam#@@9U7a5tlGRoV6vqp/X/PwA "CJam – TIO Nexus")
### Explanation
The Cartesian power approach would have been my choice, but was already taken.
So this generates numbers from 0 to 10, and for each it adds 16 and converts to binary. Adding 16 ensures that the required leading zeros are produced, together with an extra leading one which is removed.
```
B e# Push 11
{ }% e# Map over "11", implicitly converted to the array [0 1 ... 10]
G+ e# Add 16. This makes sure there will be 5 binary digits: a leading 1
e# which will have to be removed and the remaining, valid digits
2b e# Convert to array of binary digits
1> e# Remove first digit
N* e# Join by newlines. Implicitly converts arrays to strings
```
[Answer]
# [Intel 8080 machine code](https://en.wikipedia.org/wiki/Intel_8080), [MITS Altair 8800](https://en.wikipedia.org/wiki/Altair_8800), 10 bytes
```
00 00 00 00 00 00 00 00 76
```
Listing:
```
0000 00 NOP
0001 00 NOP
0002 00 NOP
0003 00 NOP
0004 00 NOP
0005 00 NOP
0006 00 NOP
0007 00 NOP
0008 00 NOP
0009 00 NOP
000A 76 HLT
```
Uses the CPU's program counter (PC, aka instruction pointer) to count from 0 to 10 then halt. The output display is conveniently in nibble format already.
**Output:**
Output is displayed on [Blinkenlights](https://commons.wikimedia.org/wiki/File:Blinkenlights-original.png#/media/File:Blinkenlights-original.png) A3-A0.
[](https://i.stack.imgur.com/wM78o.gif)
[Try it online!](https://s2js.com/altair/sim.html)
[Answer]
# MATLAB / Octave, 13 bytes
```
dec2bin(0:10)
```
[Online Demo](http://ideone.com/sHy3Vm)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10, 9~~, 8 bytes
```
⁴r26BḊ€Y
```
[Try it online!](https://tio.run/nexus/jelly#@/@ocUuRkZnTwx1dj5rWRP7/DwA "Jelly – TIO Nexus")
I'm not that great at jelly, so I'd be open to any tips!
This uses [Emigna's first algorithm](https://codegolf.stackexchange.com/revisions/110172/1)
---
*Thanks to Dennis for ~~shaving off two bytes~~ making me tie his own answer. :P*
Explanation:
```
Ḋ€ # Return all but the first element of each item in the list:
⁴r26 # [16, 17, 18, ... 26]
B # Converted to binary
Y # And joined with newlines
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
2Ḷṗ4ḣ11Y
```
[Try it online!](https://tio.run/nexus/jelly#@2/0cMe2hzunmzzcsdjQMPL/fwA "Jelly – TIO Nexus")
### How it works
```
2Ḷṗ4ḣ11Y Main link.
2Ḷ Unlength 2; yield [0, 1].
ṗ4 Take the fourth Cartesian power.
ḣ11 Head 11; discard all but the first eleven elements.
Y Join, separating by linefeeds.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~38~~ 36 bytes
```
n=16;exec"print bin(n)[3:];n+=1;"*11
```
*Thanks to @DJMcMayhem for golfing off 2 bytes!*
[Try it online!](https://tio.run/nexus/python2#@59na2hmnVqRmqxUUJSZV6KQlJmnkacZbWwVa52nbWtoraRlaPj/PwA "Python 2 – TIO Nexus")
[Answer]
# SmileBASIC, 26 bytes
```
FOR I=0TO&HA?BIN$(I,4)NEXT
```
[Answer]
# RProgN, 15 Bytes
```
~16.aL1{2B26q}:
```
~~This has been a *very* good modivation to add a `pad` function. The entirety of `]L4\-'0'\m\.`, more than half the code, is to pad.~~
\_Saved 6 bytes thanks to [@ETHProductions](https://codegolf.stackexchange.com/users/42545/ethproductions), that's the pad function cut in half.
## Explained
```
~16.aL1{2B26q}:
~ # Zero Space Segment
16. # The literal number 16
aL # The length of the Alphabet
1 # The literal number 1
{ }: # For each number between 16 and 26 inclusive
2B # Convert to base 2
26q # Get the characters between 2 and 6 inclusive.
```
[Try it online!](https://tio.run/nexus/rprogn#@19naKaX6GNYbeRkZFZYa/X/PwA "RProgN – TIO Nexus")
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~36~~ 33 bytes
```
%%%%
+`(^|\b)%
0$%'¶$%`1
11!`\d+
```
[Try it online!](https://tio.run/nexus/retina#@8@lCgRc2gkacTUxSZqqXAYqquqHtqmoJhhyGRoqJsSkaP//DwA "Retina – TIO Nexus")
**Explanation**
```
%%%%
```
Replace the empty (non-existent) input with `%%%%`.
```
+`(^|\b)%
0$%'¶$%`1
```
On the first run of this stage, it will match `^%` and essentially replace the text `%%%%` with the two lines `0%%%` and `1%%%`. The stage will loop until the output stops changing. On the second run, it will match `\b%` (since digits count as word characters and `%` doesn't), and replace the groups by duplicating them and adding `0` to one copy and `1` to the other: `0%%%` becomes the lines `00%%` and `01%%` (and the same sort of thing for `1%%%`). Through this loop all 16 bitstrings will be produced, linefeed separated.
```
11!`\d+
```
The first 11 matches of `\d+` (a run of at least 1 digit) are retrieved. The matches are output in a linefeed-separated list.
[Answer]
## Ruby, 25 bytes
```
11.times{|n|puts"%04b"%n}
```
[Answer]
# BF, ~~121~~ 101 bytes
```
,....>,.<...+.>.<-..+.-.>.<..+..>.<-.+.-..>.<.+.-.+.>.<-.+..-.>.<.+...>.<.-...>.<+.-..+.>.<.-.+.-.!0
```
Requires a trailing newline. Makes use of `!` symbol (so, check the box that says `!`) with [this interpreter (try it online!)](https://fatiherikli.github.io/brainfuck-visualizer/#LC4uLi4+LC48Li4uKy4+LjwtLi4rLi0uPi48Li4rLi4+LjwtLisuLS4uPi48LisuLS4rLj4uPC0uKy4uLS4+LjwuKy4uLj4uPC4tLi4uPi48Ky4tLi4rLj4uPC4tLisuLS4hMAo=).
Potentially 51 bytes if each operator was considered as 4 bits
[Answer]
## C#, 96 bytes
---
**Golfed**
```
()=>{for(int i=0;i++<11;)System.Console.WriteLine(System.Convert.ToString(i,2).PadLeft(4,'0'));}
```
---
**Ungolfed**
```
() => {
for( int i = 0; i++ < 1; )
System.Console.WriteLine( System.Convert.ToString( i, 2 ).PadLeft( 4, '0' ) );
}
```
---
[Answer]
## C ~~170~~ 120 bytes
```
n,i,m,k[4]={0};f(){for(m=0;m<=10;m++){n=m;i=0;for(;n;i++){k[i]=n;n/=2;}for(i=4;i>0;i--)printf("%d",k[i-1]%2);puts("");}}
```
Ungolfed version:
```
void f()
{
int n,i,m,k[4]={0};
for(m=0;m<=10;m++)
{
n=m;
i=0;
for(;n;i++)
{
k[i]=n;
n/=2;
}
for(i=4;i>0;i--)
printf("%d",k[i-1]%2);
puts("");
}
}
```
Can definitely be shortened!?
@Ahemone Awesome idea, Thanks!
Should work now!
[Try it online!](https://tio.run/nexus/c-gcc#FYzBCoMwEAX/JSBkMaFRvL2uPyI5FIqwSLZi7Snk29PkMocZmKpOXHLHtkTOoSC9RC3l/XPZxAHpyVPjOFJWTpCmeoJCujs2iazQB88oPQgvkDVAvKfzEr13a4a3aX/xUxxmwvm7v9YYQim1/gE "C (gcc) – TIO Nexus")
[Answer]
## R - 23
We can use `intToBin` function from the **`R.utils`** package:
```
R.utils::intToBin(0:10)
[1] "0000" "0001" "0010" "0011" "0100" "0101" "0110" "0111" "1000" "1001" "1010"
```
[Answer]
# C, ~~75~~ ~~68~~ 69 bytes
**Approach 1: ~~75~~ ~~73~~ ~~74~~ bytes**
```
m;p(i){putchar(i?m&i?49:48:9);}r(){for(m=11;m--;p(4),p(2),p(1),p(0))p(8);}
```
[Try it online!](https://tio.run/nexus/c-gcc#@5@rk6eTb52moVmdll@kkWtraGidq6trrQni5dnm6uTbmlrnAwXytGyNNAtKS5IzEos08u3z1CzsTSytTCysLDWta/9n5pUo5CZm5mmAGFU6CiBVWlqVmgrVXAoKCkDTreF07X8A "C (gcc) – TIO Nexus")
---
**Approach 2: ~~68~~ 69 bytes**
```
m,n,o;f(){for(m=11;m--;)for(n=m,o=5;o--;n*=2)putchar(o?n&8?49:48:9);}
```
[Try it online!](https://tio.run/nexus/c-gcc#@5@rk6eTb52moVmdll@kkWtraGidq6trrQni5dnm6uTbmlrnAwXytGyNNAtKS5IzEos08u3z1CzsTSytTCysLDWta/9n5pUo5CZm5mmAGFU6CiBVWlqVmgrVXAoKCkDTreF07X8A "C (gcc) – TIO Nexus")
[Answer]
# C, 68 bytes
```
f(){puts("0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010");}
```
Somehow, this is the shortest C answer so far…
EDIT: I was missing `1000` somehow. Well, it’s still winning.
[Answer]
# Commodore VIC-20/VC-20/C64 - 95 69 68 67 tokenized BASIC bytes used (obfuscated and minimized)
```
0dEfnb(x)=sgn(xandb):fOi=0to10:b=8:fOj=0to3:?rI(stR(fnb(i)),1);:b=b/2:nE:?:nE
```
Copy and paste the above text into WinVice, for instance. Just about fits onto 80 characters on a Commodore 64.
Here's the non-obfuscated symbolic listing for illustrative purposes:
```
0 DEF FN B(X)=SGN(X AND B)
1 FOR I=0 TO 10
2 LET B=8
3 FOR J=0 TO 3
4 PRINT RIGHT$(STR$(FN B(I)),1);
5 LET B=B/2
6 NEXT J
7 PRINT
8 NEXT I
```
Of course this may be minimised and further obfuscated. Explanation:
The `DEF FN` command in line zero is a simple function which accepts one numeric parameter. This will give the algebraic sign the number passed to it as a parameter, in this case is `AND`ed with the value `B` (declared elsewhere, but becomes global once declared).
Line 1 starts the loop counter `I`
Line 2 sets the value of the 3rd BIT.
Line 3 starts loop counter `J` (we want bits 0 - 3 essentially).
Line 4 gets the `STR$` value (string value) of the function `FN B(I)`, this is then passed to the `RIGHT$` command as CBM BASIC auto-pads outputted numbers with a white space, so we get the last character in the string created by `STR$`.
Line 5 moves the BIT counter down one (like `x >> 1` in C I suppose).
Line 6 moves the `J` loop up one.
Line 7 prints a new line (line `echo PHP_EOL;` in PHP).
Line 8 moves the `I` loop up one.
I've 'nested' the listing in the example to better show the loop and loop order.
[](https://i.stack.imgur.com/6nsF7.png)
[Answer]
# Python 2, 44 bytes
```
for x in range(11):print bin(x)[2:].zfill(4)
```
This uses the `zfill` function which works like `rjust` except it always padds with `0` so you don't waste bytes on an argument.
[Answer]
## Pyke, 8 bytes
```
TFw0+b2t
```
[Try it here!](http://pyke.catbus.co.uk/?code=TFw0%2Bb2t)
```
TFw0+b2t - for i in range(10):
w0+ - i+16
b2 - bin(^)
t - ^[:-1]
```
Also 8 bytes:
```
TF 4@b2t
```
[Try it here!](http://pyke.catbus.co.uk/?code=TF+4%40b2t)
```
4@ - set_bit(4, i)
```
[Answer]
# Pyth - ~~8~~ 7 bytes
```
<5^_`T4
```
[Try it online here](http://pyth.herokuapp.com/?code=%3C5%5E_%60T4&debug=0).
] |
[Question]
[
>
> Based off a Scratch project
>
>
>
The pen extension in Scratch has a `set pen color to ()` block. The `()` is normally a color dropdown, but you can also use the `join()()` block. In the `join()()` block, normally a hex value is in the first input, but the second is just an empty string.
However, many new Scratchers that want to take advantage of this find it hard (after all we count in decimal). Your task today, is: given three positive integers `r`,`g`,`b`, calculate the hex value and return it as `#rrggbb`.
## Input:
`r`, `g`, `b`.
1. \$0\le r\le255\$
2. \$0\le g\le255\$
3. \$0\le b\le255\$
4. Input will always follow these rules
5. Input won't have leading zeros except for `0` itself
## Output
A string in the format `#rrggbb`. Hexadecimal letters can be all uppercase or all lowercase.
## Method
1. Convert `r`,`g`,`b` to hexadecimal
2. Concatenate `r`,`g`,`b`
3. Prepend a `#`
4. Return it
## Testcases:
```
r, g, b -> Output
0, 127, 255 -> #007fff
1, 1, 1 -> #010101
245, 43, 2 -> #f52b02
72, 1, 134 -> #480186
0, 0, 0 -> #000000
255, 255, 255 -> #ffffff
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins!
**NOTE**: There's [an earlier question](https://codegolf.stackexchange.com/questions/13132/color-rgb-int-to-hex) that qualifies this as a duplicate, but it's closed (because the scoring criterion was ambiguous)
[Answer]
# [Python 3](https://docs.python.org/3.8/), 22 bytes
```
("#"+"%02x"*3).__mod__
```
[Try it online!](https://tio.run/##JYrbCsIwEAXf9yuWiJDUIM2NitA/EYJgSwM1DWW9fX1cKwyHwzDlQ9OS3amsdewvVYqdOIh9a9@iceoY4325xVhfU5oHNGdA6ofndZYplwdJpQDLmjLJUZJStdVobKfRhgCGPwPWB43esYTO/p3zwOUP4HLLt/kC "Python 3.8 (pre-release) – Try It Online")
Takes inputs as a tuple. The idea is to avoid a `lambda` or `def` by [having the answer be an object method](https://codegolf.stackexchange.com/a/95156/20260).
Same length:
```
f"#{'%02x'*3}".__mod__
```
[Answer]
# [`[5,171,30]`üòâ - 05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₁+h€¦J'#ì
```
Input as list `[r,g,b]`. Outputs in uppercase.
[Try it online](https://tio.run/##yy9OTMpM/f//UVOjdsajpjWHlnmpKx9e8/9/tKmOobmhjrFBLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/R02N2hmPmtYcWualrnx4zX@d/9HRhjpAGKsTbWRiqmNirGMEZJobgcSMTYBMAx1DI3MdI1NTMBsIQSpNTXWgGMgz1TE0N9QxNoiNBQA).
**Explanation:**
```
‚ÇÅ+ # Add 256 to each value in the (implicit) input-triplet
h # Convert each from integer to a hexadecimal string
€¦ # Remove the leading "1" from each string
J # Join them together
'#ì '# Prepend a leading "#"
# (after which the result is output implicitly)
```
[Answer]
# [C (GCC)](https://gcc.gnu.org), 39 bytes
```
m(r,g,b){printf("#%06x",r<<16|g<<8|b);}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6FjfVczWKdNJ1kjSrC4oy80rSNJSUVQ3MKpR0imxsDM1q0m1sLGqSNK1rocrTcxMz8zQ0Faq5OHM1jExNdaBY0xqmPSZPSdOaSwEIcjUMdBRACLukoZGFjoKhpZGOgoU5ugqodTBXAgA)
I could to this all day in every language
[Answer]
# [R](https://www.r-project.org), 20 bytes
```
\(...)rgb(...,m=255)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhZbYjT09PQ0i9KTQLROrq2RqakmROrm2jQNAx0FQyNzHQWQqLKCgoKunYKygYF5WloaV5qGIVASiMASCjBJQxAEShqZmOoomBgDtULkQZJppkZJBkZASXMjiFZjE4SkiYWBoYUZF9hOEEI1FgxAxpqagl0DcxLYWDCAOHrBAggNAA)
Somehow, when I first posted this answer, I managed to overlook the linked related challenge, where it was clearly pointed out that R has a built-in for this specific task...
My original non-built-in solution:
# [R](https://www.r-project.org), 38 bytes
```
cat("#",sprintf("%02x",scan()),sep="")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN9WSE0s0lJSVdIoLijLzStI0lFQNjCqA3OTEPA1NTZ3i1AJbJSVNiOqVBgqGRuYKRqamED7MFAA)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 19 bytes
```
->*v{?#+"%02x"*3%v}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf106rrNpeWVtJ1cCoQknLWLWs9n@BQlq0oaGOkZGOsXEsF4hnoGNoZK5jZGoa@x8A "Ruby – Try It Online")
[Answer]
# JavaScript (ES6), 49 bytes
Not the right tool for the job.
Expects `[r,g,b]`.
```
a=>'#'+a.map(x=>(x>>4&&'')+x.toString(16)).join``
```
[Try it online!](https://tio.run/##ZczRCoMgGIbh812FEKTSZmrWOsmb2OEY5LaKomlUjO6@ZcMO6v/hO3p4G/VVw6uvu/GizbuYy2xWmYQeDBT5qA5NmUSTlML3IcTBREZzG/taV4glGJPG1DrP55fRg2kL0poKlegOAD0DNw@MQRgCj653OlBm1X82yuzvKRfxokRkKXe0jPmT8j29cotslUXCUZFSliaHarxU3WzV9eYf "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 53 bytes
Expects `r,g,b`.
```
(r,g,b)=>'#'+(r+256<<16|g<<8|b).toString(16).slice(1)
```
[Try it online!](https://tio.run/##XcxBDoMgEIXhfU9B0oUQrTII1AX2Ej2BWiU2Rho0XXl3KlY2zCRv9eV/N99m6ez4WW@zefVuqB22mc5aUj@Sa5JimzIhlQK5aaWqrSX5ap6rHWeNQZJ8mcaux0BcZ@bFTH0@GY0HjBDNUBhCUFGgKz3uEkPw5j8Bgv8IMi52w0sP2QkHwVrKInhnnvgilPyEvKJQybgo9mKYUDzO/QA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 7 bytes
```
H2↳›\#p
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBcyIsIiIsIkgy4oaz4oC6XFwjcCIsIiIsIlswLCAxMjcsIDI1NV1cblsxLCAxLCAxXVxuWzI0NSwgNDMsIDJdIl0=)
The benefits of string padding. And flags. Helps not be beaten by half a byte :p
## Explained
```
H2↳›\#p
H # Convert each item in the input to hexadecimal
2↳› # append 0s until each string is of length 2
\#p # and prepend a "#"
# the s flag joins the top of the stack into a single string
```
[Answer]
# [Excel](https://www.microsoft.com/en-us/microsoft-365/excel), ~~31~~ 29 bytes
-7 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)
-2 bytes thanks to [Taylor Alex Raine](https://codegolf.stackexchange.com/users/61846/taylor-alex-raine)
```
="#"&CONCAT(DEC2HEX(0&A1#,2))
```
Where `A1` contains the following: `={0,127,255}`.
[](https://i.stack.imgur.com/1DNzj.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
”#2Øhṗị@‘
```
A full program that accepts a list of integers from \$[0,255]\$ and prints the resulting hexadecimal string.
**[Try it online!](https://tio.run/##ASgA1/9qZWxsef//4oCdIzLDmGjhuZfhu4tA4oCY////WzI0NSwgNDMsIDJd "Jelly – Try It Online")**
...a fair bit shorter than the naive approach of a monadic Link like `+⁹b⁴Ḋ€‘ịØh”#;` which comes in at 13 bytes - [TIO](https://tio.run/##ATIAzf9qZWxsef//K@KBuWLigbThuIrigqzigJjhu4vDmGjigJ0jO////1syNDUsIDQzLCAyXQ).
### How?
```
”#2Øhṗị@‘ - Main Link: list of integers, Colours
”# - '#' character
... the chaining of `nilad nilad nilad` (”#2Øh)
forces this to be printed to STDOUT with no trailing character(s)
2 - two
√òh - hexadecimal characters -> "0123456789abcdef"
·πó - Cartesian power -> ["00","01",...,"ff"]
‘ - increment (Colours) (vectorises)
@ - with swapped arguments:
ị - index into
- implicit, smashing print
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 7.5 bytes (15 nibbles)
```
"#"+.$&"0"2hex
```
```
"#"+.$&"0"2hex
. # map over
$ # each number in the input
hex # converting it to hexadecimal
$ # and justifying it
2 # to two characters wide
"0" # using "0" as filler,
+ # then, flatten this list
"#" # and prepend a "#" character.
```
[](https://i.stack.imgur.com/lWMfa.png)
[Answer]
# [Python 3](https://docs.python.org/3/), 20 bytes
```
lambda x:"#"+x.hex()
```
[Try it online!](https://tio.run/##JYrbCgIhFEXfz1ccphclibwxMDB/0otDDgpmIlb69WYTLDabxUqtuGeUfV9vPZjHdjdYl@k0nevF2Upo/zgfLPIFsKz2bQLxMb0KoRQwZR8L2cnWijU5m0YKpbRfGXIxMxRaAx9/AEJphkoOCbP4O6lglD9glEd@zBc "Python 3 – Try It Online")
Takes input as a `bytearray`.
Test bed borrowed from @xnor.
[Answer]
# [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) machine code, 34 DECLEs1 = 42.5 bytes2
*1. A CP-1610 opcode is encoded with a 10-bit value (0x000 to 0x3FF), known as a 'DECLE'.*
*2. This routine is 34 DECLEs long, i.e. 340 bits. As per the exception described in [this meta answer](https://codegolf.meta.stackexchange.com/a/10810/58563), the score is **42.5 bytes**.*
A routine expecting a pointer to three bytes in **R3** and writing the result at **R4** (in white, assuming ColorStack mode).
### Test code
```
| | ROMW 10 ; 10-bit ROM
| | ORG $4800 ; map the program at $4800
| |
4800|001 | SDBD ; set up an ISR for minimal
4801|2B8 030 048| MVII #isr, R0 ; STIC initialization
4804|240 100 | MVO R0, $100
4806|040 | SWAP R0
4807|240 101 | MVO R0, $101
| |
4809|002 | EIS ; enable interrupts
| |
480A|001 | SDBD ; R4 = BACKTAB pointer
480B|2BC 000 002| MVII #$200, R4
480E|001 | SDBD ; R3 = pointer to test cases
480F|2BB 01E 048| MVII #test, R3
| |
4812|004 148 040|loop CALL rgb ; invoke our routine
| |
4815|2FC 00D | ADDI #13, R4 ; advance to the beginning
| | ; of the next line
4817|001 | SDBD
4818|37B 030 048| CMPI #done, R3 ; done?
481B|225 00A | BLT loop
| |
481D|017 | DECR R7 ; loop forever
| |
481E|000 07F 0FF|test DECLE 0, 127, 255 ; #007fff
4821|001 001 001| DECLE 1, 1, 1 ; #010101
4824|0F5 02B 002| DECLE 245, 43, 2 ; #f52b02
4827|048 001 086| DECLE 72, 1, 134 ; #480186
482A|000 000 000| DECLE 0, 0, 0 ; #000000
482D|0FF 0FF 0FF| DECLE 255, 255, 255 ; #ffffff
| |done
| | ;; ------------------------------------------- ;;
| | ;; ISR ;;
| | ;; ------------------------------------------- ;;
| |isr PROC
4830|240 020 | MVO R0, $0020 ; enable display
4832|280 021 | MVI $0021, R0 ; colorstack mode
| |
4834|1C0 | CLRR R0
4835|240 030 | MVO R0, $0030 ; no horizontal delay
4837|240 031 | MVO R0, $0031 ; no vertical delay
4839|240 032 | MVO R0, $0032 ; no border extension
483B|240 028 | MVO R0, $0028 ; black background
483D|240 02C | MVO R0, $002C ; black border
| |
483F|0AF | JR R5 ; return from ISR
| | ENDP
```
### Routine ($4840-$4861)
```
| | ;; ------------------------------------------- ;;
| | ;; our routine ;;
| | ;; ------------------------------------------- ;;
| |rgb PROC
4840|275 | PSHR R5 ; push the return address
| |
4841|2B8 01F | MVII #$1F, R0 ; draw the '#'
4843|260 | MVO@ R0, R4
| |
4844|2BA 003 | MVII #3, R2 ; repeat 3 times
| |
4846|298 |@@loop MVI@ R3, R0 ; R0 = byte to display
4847|00B | INCR R3 ; advance R3
4848|004 148 054| CALL @@hexa ; draw the upper nibble
484B|04C | SLL R0, 2 ; shift the lower nibble
484C|04C | SLL R0, 2
484D|004 148 054| CALL @@hexa ; draw it
4850|012 | DECR R2 ; loop?
4851|22C 00C | BNEQ @@loop
| |
4853|2B7 | PULR R7 ; return
| |
4854|081 |@@hexa MOVR R0, R1 ; copy R0 into R1
4855|3B9 0F0 | ANDI #$F0, R1 ; isolate the upper nibble
4857|2F9 10F | ADDI #$10F, R1 ; add the offset for '0'
| | ; and set the lower nibble
| | ; so that we write in white
4859|379 19F | CMPI #$19F, R1 ; if greater than '9' ...
485B|206 002 | BLE @@print
| |
485D|2F9 270 | ADDI #$270, R1 ; ... advance to 'a'
| |
485F|061 |@@print SLR R1 ; right-shift to get the
| | ; final value
4860|261 | MVO@ R1, R4 ; write it
4861|0AF | JR R5 ; return
| | ENDP
```
### Output
[](https://i.stack.imgur.com/qJnOS.gif)
*screenshot from [jzIntv](http://spatula-city.org/%7Eim14u2c/intv/)*
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~86 84 76 75 69 65 61~~ 57 bytes
```
b;main(c){for(;~scanf("%d",&c);printf("#%02X"+!!b++,c));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/JOjcxM08jWbM6Lb9Iw7quODkxL01DSTVFSUctWdO6oCgzrwTIV1Y1MIpQ0lZUTNLW1knW1LSu/f/fQMHQyFzByNT0X3JaTmJ68X/dcgA "C (gcc) – Try It Online")
* Kudos to @mousetail for shaving 2 bytes (from 86 to 84)
* Kudos to @corvus\_192 for shaving 4 bytes (from 65 to 61)
* Kudos to @jdt for shaving 4 bytes (from 61 to 57)
### Ungolfed with comments, courtesy of @jdt:
# [C (gcc)](https://gcc.gnu.org/), 326 bytes
```
// all global and static variables are initiated to 0.
int b = 0;
main(int c)
{
// scanf will retun -1 when done. ~-1 = 0
while (~scanf("%d",&c))
{
// Here we do some pointer arithmetic.
char* format = "#%02X";
printf(format + (b != 0) , c);
// now we increment b
b++;
}
}
```
[Try it online!](https://tio.run/##PU9LboMwEF3Xp3ilSgQlHxIp6iLqvkfodjADWDJ2ZNx6ESVHLx1oldnNvO/obaf1NO33IGvRWV@TBbkGY6RoNL4pGKotj6DAMM5EQ5EbRI9qB2VcRI13VGcoNZBx@XzRhboqyIjtqMm1SEbcA8cvh@0BqWeHxjve4S6ryBd26o1l5PdFkmerJtusdVFgAa/qSdw@WFokFjFGPzAuXvI4SDkT@4Gl8W5hz6N7Cq9ofRgoSkb2sqqOn9n5gV@CaNv8n1Air/EsVQps5IGzevAk1vk0pxqnAw88//xA67L8s7yp2zRVOBzfcDydfnRrqRunbfoF "C (gcc) – Try It Online")
[Answer]
# [Python](https://www.python.org), ~~38~~ 23 bytes
* -1 byte thanks to @py3\_and\_c\_programmer
```
lambda*x:"#"+"%02x"*3%x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwdI0BVuFmKWlJWm6FjtyEnOTUhIVtCqslJSVtJVUDYwqlLSMVSsg0jctC4oy80o00jSMTE11oFhTkwsmamhkARY1QxIz0AFCTU2IAQsWQGgA)
[Answer]
# [Perl 5](https://www.perl.org/) + `-pl043`, 19 bytes
```
$\.=unpack H2,chr}{
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJFxcLj11bnBhY2sgSDIsY2hyfXsiLCJhcmdzIjoiLXBsMDQzIiwiaW5wdXQiOiIyNDVcbjQzXG4yIn0=)
## Explanation
Uses the commandline flag `-l043` to prepopulate `$\` with `'#'` and for each input line, appends the result of `unpack`ing the number to `H2` (`0`-padded hex representation).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 49 bytes
```
.+
$*
%`^(.{16})*(.)*
$#1¶$#2
T`d`l`..
.\B|¶
^
#
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZyg819Pm0tFi0s1IU5Dr9rQrFZTS0NPU4tLRdnw0DYVZSOukISUhJwEPT0uvRinmkPbuLjiuJT//zfQMTQy1zEyNeUy1AFCLiMTUx0TYx0jLnMjEN/YhMtABwi5gCp0oBgA "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on commas for convenience. Explanation:
```
.+
$*
```
Convert to unary.
```
%`^(.{16})*(.)*
$#1¶$#2
```
Divmod by `16`, resulting in a list of six integers from `0-15`.
```
T`d`l`..
```
Adjust `10-15` by transliterating `0-5` to `a-f`.
```
.\B|¶
```
Remove the leading digit from integers that used to be above `9` and join all of the digits together.
```
^
#
```
Prefix a `#`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 25
```
printf \#${f=%02x}$f$f $@
```
[Try it online!](https://tio.run/##S0oszvhfnpGZk6pQlJqYYq2Qks9VnFqioKuroBLkGuAT@b@gKDOvJE0hRlmlOs1W1cCoolYlTSVNQcXhf2pyRj5XSn5e6n8DBUMjcwUjU1MuQwUg5DIyMVUwMVYw4jI3AvGNTbgMFICQC6hCAYoB "Bash – Try It Online")
[Answer]
# Java 8, ~~41~~ 40 bytes
```
(r,g,b)->"".format("#%06x",r<<16|g<<8|b)
```
-1 byte thanks to *@Arnauld* by porting [@mousetail's C answer](https://codegolf.stackexchange.com/a/254095/52210).
Output in lowercase. Could be in uppercase by replacing the `x` with `X`.
[Try it online.](https://tio.run/##ZVDLbsIwELzzFautKtmyE5GQQFXS/kG59Fj1YAfjhiZO5BjUqvDtqRN8AKGVR9rZ13j24iii/fZ7KGvR9/AmKvM3A6iMU3YnSgWbMQV4d7YyGkriK2D5iHpCSde@4Tzz0DvhqhI2YOBlIJZrLmn0ihjvWtsIR/Dhcb78QW6LIlmedFE8nSQd1uNod5C1Hw0bjm21hcZLIZezH5@CXmQ41TuScB/T2UCkWc6zBU@vuVU6di2ya27Ok3TF0zy/JX3cbMtzHt7d3yZlU9e9D8Go396pJm4PLu68dlcbYhlyZHpCyfAZGQLGVnXKm5LMI4LIrK9LGtfKaPdFKGUmLoOFQcR5@Ac)
**Explanation:**
```
(r,g,b)-> // Method with three integer parameters and String return-type
"".format("#%06x", // Return a String with a format as:
# // A leading hash "#"
% x // And an integer converted to a hexadecimal value
6 // of size 6
0 // with potential leading 0s if it's smaller than 6
// Where the integer is:
r<<16 // Input `r` bitwise right-shifted by 16
| // Bitwise-ORed with
g<<18 // Input `g` bitwise right-shifted by 8
| // Bitwise-ORed with
b) // Input `b` as is
```
[Answer]
# [Raku](https://raku.org), ~~26~~ 25 bytes
```
{printf '#'~'%02x'x 3,@_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/uqAoM68kTUFdWb1OXdXAqEK9QsFYxyG@9n@agoGOoZG5jpGpqTVXmoKhDhCCGEYmpjomxjpGILa5EUjU2ATENtABQrACU1MdKLb@DwA)
*-1 byte thanks to [@IsmaelMiguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel)*
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 12 bytes
```
"#",`hex@`c$
```
[Try it online!](https://ngn.codeberg.page/k#eJwtilEKgCAQBf89xWMTMjCyVQlciI4iRNEB/BCiu2cQw3wMzJmoI5uvo25510qVZBxmXsAxyoyGcIgIHiwLf+2DODSkHfgdVHbpNgSaRq91HSxhXEH23OrTlxdB3hVN)
Takes input as a list of 3 integers.
``c$` Cast to string (bytes).
``hex@` Format bytes as hexadecimal values.
`"#",` Prepend a `#`.
[Answer]
# [Julia 1.0](http://julialang.org/), 36 bytes
```
~x="#"*(string.(x,base=16,pad=2)...)
```
[Try it online!](https://tio.run/##TdDNagMhEAfwc32KP@aiRRY1azYULBT6FiEH013DtpIuqwF7yatvrUnajjCXn/PBvJ/D6FRelku2dEUfWUzzeDo2LIuDi4NVGzG53mreNA1fSG9fx7fEyMNOCgBKdwLamD3sM@hKys57T0VhVbkm4M7q51XWrRFo18X1L3ujD1JX7rS4V6/bG7dbqbabynX2Nf01r3Ftbkzd6v9qvkZhTsg8xHNIERYuBHbJsBb9Lu/hP2dkjCd8DF@R9bz8nco1EqMvISANsRRNLsZyoCdQgVsjTpZv "Julia 1.0 – Try It Online")
-1 byte thanks to @amelies: Replace `prod` with `*`. A single operator can behave as both a monad and dyad in Julia!
[Answer]
# C#, 31 bytes
```
(r,g,b)=>$"#{r:X2}{g:X2}{b:X2}"
```
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 102 bytes
Since this challenge is super easy I wanted to try some esolangs.
Takes input as raw byte values.
```
"#"o03i:&82*,01.
:9)?v68*+o.
v+"W"<;
o14&82*%01.
\.05i:&82*,01.
06&82*%01.
07i:&82*,01.
52&82*%01.
```
[See it in action (animated)](https://mousetail.github.io/Fish/#%7B%22text%22%3A%22%5C%22%23%5C%22o03i%3A%2682*%2C01.%5Cn%20%3A9%29%3Fv68*%2Bo.%5Cnv%2B%5C%22W%5C%22%3C%3B%5Cno14%2682*%2501.%5Cn%5C%5C.05i%3A%2682*%2C01.%5Cn%2006%2682*%2501.%5Cn%2007i%3A%2682*%2C01.%5Cn%2052%2682*%2501.%22%2C%22input%22%3A%22i%245%22%2C%22stack%22%3A%22%22%2C%22mode%22%3A%22numbers%22%7D) - [Try it online](https://tio.run/##S8sszvj/X0lZKd/AONNKzcJIS8fAUI9LwcpS077MzEJLO1@Pq0xbKVzJxpor39AEpEAVpCBGz8AUWb2BGVxKwcAcWcbUCCbz/39iUjIA)
## Explanation:
This is a function that prints a single hexadecimal number:
```
:9)?v68*+o.
v+"W"<
o
\.
```
Basically, check if the number is more than 9, if so add "W" ("W"+9 = 'a'), and print it. Otherwise add 6\*8='0'. In both cases we use . to "return" from the function.
The function wraps around the left margin since this is "dead space". Since you can't jump to the leftmost
The rest of the code is either of these 2 statements repeated:
```
07i:&82*,01.
```
First 2 values are the return pointer, it's where the function will return. Then we take input and copy 1 value to the register. We divide by 16 (2\*8), then push the start address of the print function, and call it with .
The other variant is very similar:
```
14&82*%01.
```
Again 14 is the return value. We take the value form the register, but this time modulo it by 16. Again we call the function at 01.
Notice the last function returns to 52, which is the location of the stray `;` (right of the `<` inside the function) that exits the program.
# [><>](https://esolangs.org/wiki/Fish), 119 bytes
```
"#"oi:&82*,:9)"'"*+"0"+o&82*%:9)"'"*+"0"+oi:&82*,:9)"'"*+"0"+o&82*%:9)"'"*+"0"+oi:&82*,:9)"'"*+"0"+o&82*%:9)"'"*+"0"+o;
```
[Try it online!](https://tio.run/##S8sszvj/X0lZKT/TSs3CSEvHylJTSV1JS1vJQEk7HySiiiJCTVXW//8nJiUDAA "><> – Try It Online")
Alternate solution that uses just 1 line.
[Answer]
# x86-32 machine code, 28 27 bytes
```
"\x6a\x23\x58\x99\xaa\xb1\x1c\xac\xd3\xc0\x3c\x0a\x1c\x69\x2f\xaa"
"\xd3\xe8\x30\xce\x75\xf4\x42\x7b\xee\x88\x27"
```
#### Requirements:
* SS:ESP-4 -> 4 bytes of writable memory
* DS:ESI -> 3 bytes of readable memory containing `r`, `g`, `b`
* ES:EDI -> 8 bytes of writable memory to receive NUL-terminated ASCII string (`"#XXXXXX\0"`)
* Direction Flag clear
#### In assembly language:
```
6a 23 push 23h ; "#"
58 pop eax
99 cdq
aa stosb
b1 1c mov cl, 1Ch
__byteloop:
ac lodsb
d3 c0 rol eax, cl
__nibbleloop:
3c 0a cmp al, 0Ah ; someone's old trick for converting a nibble to hex
1c 69 sbb al, 69h
2f das
aa stosb
d3 e8 shr eax, cl
30 ce xor dh, cl
75 f4 jnz __nibbleloop
42 inc edx
7b ee jnp __byteloop
88 27 mov [edi], ah
```
[Answer]
# Scratch, 235 Bytes
[](https://i.stack.imgur.com/w2GIg.png)
[Link to the editor for the script](https://scratch.mit.edu/projects/836662188/editor/)
Source:
```
when gf clicked
set[I v]to(0
set[X v]to[#
repeat(3
change[I v]by(1
set[X v]to(join(x)(join(letter(((item(I)of[C v])-((item(I)of[C v])mod(16)))+(1))of[0123456789ABCDEF])(letter(((item(I)of[C v])mod(16))+(1))of[0123456789ABCDEF
end
say(X
```
It was exhausting to put this into plain text, so I'm not golfing this down YET.
[Answer]
# [Bitcoin Cash Script (BitAuth IDE)](https://alpha.ide.bitauth.com/), 601 bytes, 93 bytes as raw bytecode
```
// Input
<127>
<0>
<255>
// Program
OP_DUP
<16> OP_MOD
OP_SWAP
<16> OP_DIV
OP_DUP <9> OP_GREATERTHAN
OP_IF
<7> OP_ADD
OP_ENDIF
<48> OP_ADD
OP_SWAP
OP_DUP <9> OP_GREATERTHAN
OP_IF
<7> OP_ADD
OP_ENDIF
<48> OP_ADD
OP_CAT
OP_ROT
OP_DUP
<16> OP_MOD
OP_SWAP
<16> OP_DIV
OP_DUP <9> OP_GREATERTHAN
OP_IF
<7> OP_ADD
OP_ENDIF
<48> OP_ADD
OP_SWAP
OP_DUP <9> OP_GREATERTHAN
OP_IF
<7> OP_ADD
OP_ENDIF
<48> OP_ADD
OP_CAT
OP_ROT
OP_DUP
<16> OP_MOD
OP_SWAP
<16> OP_DIV
OP_DUP <9> OP_GREATERTHAN
OP_IF
<7> OP_ADD
OP_ENDIF
<48> OP_ADD
OP_SWAP
OP_DUP <9> OP_GREATERTHAN
OP_IF
<7> OP_ADD
OP_ENDIF
<48> OP_ADD
OP_CAT
OP_ROT
OP_CAT OP_CAT
<'#'> OP_SWAP OP_CAT
// Output string left on stack
// We can also execute it all using raw bytecode
OP_DROP // Clean up
// Input
<127>
<0>
<255>
/// Program
0x7660977c60967659a0635793680130937c7659a0635793680130937e7b7660977c60967659a0635793680130937c7659a0635793680130937e7b7660977c60967659a0635793680130937c7659a0635793680130937e7b7e7e01237c7e
```
[Try it online!](https://ide.bitauth.com/import-template/eJztlFFv0zAQx7-KZZD20jVuSuOlqiaFprA-bIm6jj1QVLnusQYSJ4ovY2jqd-fsMDQkxBMSPPDi8_3u_z_rJNuP_KXVB6gUn_IDYmOnQbArUHV4GOq6CvqiDRwAg4VWWNTmFKFqSoVwei-GvWT4ydaGD_gerG6LxqmoJQGjKqDdDZmxhD0R1wcLsHz6eBzwXu4St1WoD9tG7V363XndU5YrZ-7lhIOALU3T4cbMRqE8pyDcEk4mFKiYt_Vdq6qNyfJtepM7WXTOKLnMUg-vb5NnNF2-e5KyWezR29UiWS9W64vkypeWb0gufSlJ-x6Lq9TTV2c_4b71n-o2T9Y-rrL1_2n-8WkoZ094dvLixIvdkT8oXc2sQ7q4zGJbmDtWwkdktaFU6c8b4xW3wLQyTJW2ZvAAukNgBVJess46U6u-sN1XBF3voZ9mleWMnPMSyNg1vs3vHsizFyIeZBSJWEpNaySjSaxENJ7IeBydidFYxGOpf0lB7v6KEySIUegUwI_uD-mapm6Rfpfpe_56frENRSi2YsI_DPg9tNZ_RuL4DS6ufJw=)
[Answer]
# [Factor](https://factorcode.org/), 25 bytes
```
[ "#%02x%02x%02x"printf ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQll@Um1hSkpmXrpCdWpSXmqNgzWVkYqpgYqxg9D9aQUlZ1cCoAoaVCooy80rSFGL/Jyfm5PwHAA "Factor – Try It Online")
[Answer]
# [Clojure](https://clojure.org/), 30 bytes
```
#(format"#%02x%02x%02x"% %2%3)
```
[Try it online!](https://tio.run/##VU5BCsIwELznFUtLIIEKyTaxBcGPhBysbUSprcYK/j6mqVacnb3sMLNz7MfL03eBtZ0DF3LmRn89TFlOBb6@m1GgSEseOGHt@Ojuxng4QWPBECMKkFgVgFpbANht9pALUTnniJFRi5zvsGpyHmJQ6QJUGY121ZzGRiAxFS7GUv00VQtZb9O/mf@ZCTFT61Tk02bJTCDWEnbz52HqB2AOUn/OeXgD "Clojure – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 28 bytes
```
h¦⟨)₵HE¤\⟩¦¦$¦⟨0¤+3⊂ḥ⟩¦$'#¤+
```
[Try it online!](https://tio.run/##S0/MTPz/P@PQskfzV2g@atrq4XpoScyj@SsPLTu0TAUsanBoibbxo66mhzuWgsVV1JWBIv@jzY0UDBUMjU1iH7VN/A8A "Gaia – Try It Online")
28 bytes may seem like a lot of bytes until you discover that there is no "convert a number to hexadecimal as a string" built-in in Gaia. Why was "convert to base 16 as a list of digits" the thing that got added and not to string?
Using a similar algorithm to the 05AB1E and MathGolf answers would probably be longer.
Gaia does not have list input in the input box, so this is a function submission.
## Explained
```
h¦⟨)₵HE¤\⟩¦¦$¦⟨0¤+3⊂ḥ⟩¦$'#¤+
h¦ # Convert each number to base 16 (list of digits)
⟨ ⟩¦¦ # To each digit in each number:
) # Increment it to account for 1-indexing
₵HE # and index it into the string "0123456789ABCDEF"
¤\ # Remove some extra junk from the stack
$¦ # Convert each list to a single string
⟨ ⟩¦ # To each hex string:
0¤+ # Prepend 0
3⊂ # repeat the first character of the string enough times to make it at least length 3
ḥ # remove the leading 0
$'#¤+ # join into a single string and prepend the # character
```
[Answer]
# [Sequences](https://github.com/nayakrujul/sequences), \$22 \log\_{256}(96) \approx 18.1\$ bytes
```
"#"H3x{\016iB2jH}g""JF
```
### Explanation
```
"#"H3x{\016iB2jH}g""JF
"#"H // Push "#" to the list
3x{ } // Repeat 3 times:
i // Get a numeric input
16 B // Convert to hexadecimal
\0 2j // Fill with 0s on the left up to 2 characters
H // Append to the list
g // Get the list
""J // And join by ""
F // Output the joined string
```
### Screenshot
[](https://i.stack.imgur.com/JwQTM.png)
] |
[Question]
[
## Challenge
Write a program that, given a string `x` which is 10 characters long and a character `y`, outputs the number of times character `y` occurs in string `x`.
The shortest program in bytes to do so wins.
## Example
```
Input: tttggloyoi, t
Output: 3
```
---
```
Input: onomatopoe, o
Output: 4
```
[Answer]
# Pyth, 3 bytes
```
/ww
```
Example run:
```
$ pyth -c '/ww'
sdhkfhjkkj
k
3
```
Of course, the user could input more or less than 10 letters on the first input, but we don't need to worry about what happens when the user violates the spec.
[Answer]
# Pyth - 3 bytes
A different, less obvious, Pyth answer of the same size. It folds counting over the input.
```
/FQ
```
[Test Suite](http://pyth.herokuapp.com/?code=%2FFQ&test_suite=1&test_suite_input=%22tttggloyoi%22%2C%20%22t%22%0A%22onomatopoe%22%2C%20%22o%22&debug=0).
[Answer]
# JavaScript, 32
```
(p=prompt)().split(p()).length-1
```
[Answer]
# Bash, 24 characters
```
x=${1//[^$2]}
echo ${#x}
```
Sample run:
```
bash-4.3$ bash letter-count.sh tttggloyoi t
3
bash-4.3$ bash letter-count.sh onomatopoe o
4
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 12 bytes
```
(.)(?=.*\1$)
```
Simply a regex which matches a character which is equal to the last character in the input (except itself). When given a single regex, Retina simply returns the number of matches.
[Answer]
# [Labyrinth](https://github.com/mbuettner/labyrinth), ~~32~~ ~~29~~ ~~27~~ 24 bytes
```
),}{)-
@ , +);__
!-`{:}
```
This reads the single character first, followed by the string in which to count, and assumes that there are no null-bytes in the string.
## Explanation
The code starts with `),}`, which sets the bottom of the stack to `1`, reads the first character and moves it to the auxiliary stack for future use. The `1` will be our counter (the offset of 1 will be cancelled later and is necessary for the IP to take the required turns).
The IP will now move down to read the first character of the search string with `,`. The value is negated with ```, again to get the correct turning behaviour. While we're reading characters from STDIN, the IP will now follow this loop:
```
}{)-
, +);__
`{:}
```
`{:}` makes a copy of the stored character code and `+` adds it to the current value. If the result is `0` (i.e. the current character is the one we're looking for), the IP moves straight ahead: `-` simply gets rid of the `0`, `)` increments the counter, `{}` is a no-op.
However, if the result after `+` is non-zero, we don't want to count the current character. So the IP takes a right-turn instead. That's a dead-end, so that code there is executed twice, once forwards and once backwards. That is, the actual code in this case becomes `);___;)+-){}`. `);` just gets rid of that non-zero difference, `___` pushes 3 zeroes, but `;` discards one of them. `)` increments one of the two remaining two zeroes, `+` adds them into a single `1`, `-` subtracts it from the counter and `)` increments the counter. In other words, we've created a very elaborate no-op.
When we hit EOF, `,` pushes `-1`, which ``` turns into `1` and the IP takes a right-turn. `-` subtracts the `1` from the counter (cancelling the initial offset). `!` prints the counter and `@` terminates the program.
[Answer]
# Python 3, 29 bytes
```
print(input().count(input()))
```
Meh, this was easy. Assumes that input is a ten letter string.
[Answer]
## [Snowman 1.0.2](https://github.com/KeyboardFire/snowman-lang/releases/tag/v1.0.2-beta), 16 characters
```
~vgvgaSaLNdEtSsP
```
Surprisingly short. Explanation:
```
~ make all vars active (even though we only need two, we don't really care)
vgvg get two lines of input
aS split first line on second line
aL length of the new array
NdE decrement (because ex. "axbxc""x"aS -> ["a" "b" "c"] which is length 3)
tSsP to-string and print
```
[Answer]
# C++ Template-Metaprogramming, ~~160~~ ~~154~~ 116 bytes
Just for the giggles.
*Thanks to ex-bart for golfing it down!*
```
template<int w,int x,int y,int...s>class A:A<w+(x==y),x,s...>{};A<0,'t','t','t','t','g','g','l','o','y','o','i',0>a;
```
Usage:
The first char in the template instanciation is the character to search.
Complile with *clang -std=c++11 -c* -> the result is at the beginning of the error message.
```
Occurences.cpp:1:66: error: too few template arguments for class template 'A'
template<int w,char x,char y,char...s>class A{static const int a=A<w+((x==y)?1:0),x,s...>::a;};
^
Occurences.cpp:1:66: note: in instantiation of template class 'A<3, 't', '\x00'>' requested here
template<int w,char x,char y,char...s>class A{static const int a=A<w+((x==y)?1:0),x,s...>::a;};
```
Complile with *gcc -std=c++11 -c* -> the result is at the bottom of the error message.
```
Occurences.cpp: In instantiation of ‘const int A<3, 't', '\000'>::a’:
Occurences.cpp:1:64: recursively required from ‘const int A<1, 't', 't', 't', 'g', 'g', 'l', 'o', 'y', 'o', 'i', '\000'>::a’
Occurences.cpp:1:64: required from ‘const int A<0, 't', 't', 't', 't', 'g', 'g', 'l', 'o', 'y', 'o', 'i', '\000'>::a’
Occurences.cpp:2:62: required from here
Occurences.cpp:1:64: error: wrong number of template arguments (2, should be at least 3)
```
*Search for the A<**3**, 't', '\000'> and A<**3**, 't', '\x00'>*
**154 byte version**
```
template<int w,char x,char y,char...s>class A{static const int a=A<w+(x==y),x,s...>::a;};
int a=A<0,'t','t','t','t','g','g','l','o','y','o','i','\0'>::a;
```
**160 byte version:**
```
template<int w,char x,char y,char...s>class A{static const int a=A<w+((x==y)?1:0),x,s...>::a;};
int a=A<0,'t','t','t','t','g','g','l','o','y','o','i','\0'>::a;
```
[Answer]
# Bash + grep, 26 bytes
```
grep -o "$1"<<<"$2"|wc -l
```
[Answer]
# Javascript (ES6), 26 bytes
```
(a,b)=>a.split(b).length-1
```
This quick'n'easy solution defines an anonymous function. To use it, add a variable declaration to the beginning. Try it out:
```
z=(a,b)=>(a.split(b)||[0]).length-1;
input1=document.getElementById("input1");
input2=document.getElementById("input2");
p=document.getElementById("a");
q=function(){
setTimeout(function(){
p.innerHTML=z(input1.value,input2.value)||0;
},10);
};
input1.addEventListener("keydown",q);
input2.addEventListener("keydown",q);
```
```
<form>Text to search: <input type="text" id="input1" value="hello world!"/><br>Char to find: <input type="text" id="input2" value="l"/></form>
<h3>Output:</h3>
<p id="a">3</p>
```
**EDIT:** Oh, I see there's a very similar solution already. I hope that's OK.
[Answer]
# Haskell, 21 bytes
```
a!b=sum[1|x<-a,x==b]
```
[Answer]
# C++, 78 bytes
```
int main(int,char**v){int c=0,i=0;while(i<10)v[1][i++]==*v[2]&&++c;return c;}
```
Call like this:
```
$ g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out tttggloyoi t; echo $?
3
```
[Answer]
# [Element](https://github.com/PhiNotPi/Element), 23 bytes
```
__);11'[)\
~="0 1@][+]`
```
The newline is part of the program. I am actually using it as a *variable name*.
This program basically works by storing the target character in a variable, keeping the current string on the top of the stack, and then looping the "chop, compare, and move result underneath" process, adding up the results in the end.
The newline as a variable name comes from using the newline at the end of input by chopping it off and storing into it. The newline in the code is where I read from it.
Input is like this:
```
qqqqwwweee
q
```
Output is like this
```
4
```
[Answer]
# Julia, ~~26~~ 25 bytes
```
f(s,c)=endof(findin(s,c))
```
The `findin` function returns the indices in the first argument at which the second argument is found as a vector. The length of the vector is the number of occurrences.
Saved one byte thanks to Glen O.
[Answer]
# APL, ~~7~~ 3 bytes
```
+/⍷
```
This creates a function train. It works by creating a vector of zeros and ones corresponding to the indices at which the character appears in the string (`⍷`). The vector is then summed (`+/`).
Saved 4 bytes thanks to kirbyfan64sos and NBZ!
[Answer]
# Perl, ~~21~~ 16 characters
(13 characters code + 3 character command line option.)
```
$_=0+s/$^I//g
```
Sample run:
```
bash-4.3$ perl -it -pe '$_=0+s/$^I//g' <<< tttggloyoi
3
bash-4.3$ perl -io -pe '$_=0+s/$^I//g' <<< onomatopoe
4
bash-4.3$ perl -i5 -pe '$_=0+s/$^I//g' <<< 1234
0
```
[Answer]
# PHP, ~~36~~ 35 bytes
```
<?=substr_count($argv[1],$argv[2]);
```
**Usage:**
Call the script with two arguments.
`php script.php qwertzqwertz q`
# PHP, 23 bytes
If you register global Variables (only possible in PHP 5.3 and below) you can save 12 bytes (thanks to [Martijn](https://codegolf.stackexchange.com/questions/55880/find-the-occurrences-of-a-character-in-an-input-string/55886?noredirect=1#comment135755_55886))
```
<?=substr_count($a,$b);
```
**Usage:**
Call the script and declare global variables `php script.php?a=qwertzqwertz&b=q`
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 3 bytes
```
+/=
```
I.e. "The sum of the equal bytes". E.g.:
```
f ← +/=
'onomatopoe' f 'o'
4
```
or just
```
'onomatopoe'(+/=)'o'
4
```
K doesn't beat APL this time.
[Try it online.](http://tryapl.org/)
[Answer]
# T-SQL, ~~99~~ 40 Bytes
```
SELECT 11-LEN(REPLACE(s,c,'')+'x')FROM t
```
Simply does a difference between the input string and the string with the character removed. Takes input from table t
**Edit** changed to remove an issue with counting spaces and to take into account current acceptable inputs for SQL. Thanks @BradC for all the changes and savings
[Answer]
## Octave / Matlab, 33 bytes
```
sum(input('','s')==input('','s'))
```
[Answer]
# J, 5 bytes
```
+/@:=
```
I feel like J would have a built-in for this, but I haven't been able to find one - maybe one of the active J users can enlighten me. So instead this first applies `=` to the inputs, turning each character into `1` if it's equal to the requested one or `0` otherwise. Then `+/` computes the sum of that list.
[Answer]
# Batch File, 121 Bytes
Because I'm a masochist ...
```
SET c=0
SET e=_
SET t=%1%%e%
:l
SET a=%t:~0,1%
IF "%a%"=="%2" SET /A c+=1
SET t=%t:~1%
IF NOT "%t%"=="%e%" GOTO l
ECHO %c%
```
### Warning: Assumes that `_` doesn't occur in the input string. If it does, then the variable `e` needs to be adjusted appropriately.
This sets up our counter variable, `c`, and our end-of-string demarcation as `_`, before appending that to our input string `%1` and setting the concatenated string to `t`. Then, we're entering loop `:l`, we set a temporary character variable `a` to be the first character of `t`, check if it matches our second input string `%2` and increment `c` if true, then trim the first character off of `t`. Our end-of-loop condition checks `t` against our end-of-string demarcation, and loops back if not. We then `echo` out the value of our counter.
It would probably be possible to use a `FOR` loop instead, but that would necessitate enabling [DelayedExpansion](http://ss64.com/nt/delayedexpansion.html), which I think will actually be longer byte-wise than this. Verification of that is left as an exercise to the reader.
[Answer]
# CJam, 5 bytes
```
ll/,(
```
## Explanation
```
l e# read x
l e# read y
/ e# split x by y
, e# count
( e# subtract one
```
[Answer]
# PowerShell, 32 Bytes
A four-for-one! And they're all the same length! :)
```
($args[0]-split$args[1]).Count-1
```
or
```
param($a,$b)($a-split$b).Count-1
```
Alternatively,
```
$args[0].Split($args[1]).Count-1
```
or
```
param($a,$b)$a.Split($b).Count-1
```
The first two styles use the inline operator `-split`, while the second two implicitly casts the first argument as a String and uses the `.Split()` string-based operator. In all instances an array is returned, where we must decrement Count by one, since we're getting back one more array item than occurrences of the second argument.
This one was kinda fun...
[Answer]
# Julia, 21 bytes
```
f(s,c)=sum(i->c==i,s)
```
Note that it requires that `c` be a char, not a single-character string. So you use it as `f("test me",'e')` (which returns 2) and not `f("test me","e")` (which returns 0, because `'e'!="e"`).
[Answer]
## [><> (Fish)](http://esolangs.org/wiki/Fish), 30 bytes
```
0&v
=?\ilb
=?\:@=&+&l1
n&/;
```
Takes the string, then character to count. Input isn't separated (at least in the online interpreter). Try it on the online interpreter: <http://fishlanguage.com> I counted the bytes by hand, so let me know if I'm wrong.
**Explanation**
First off, ><> is 2 dimensional and and loops through a line or column until it hits a `;` or error. This means that if it's proceeding left to right (like it does at the beginning of a program), it will wrap around the line if it reaches the end and is not moved or told to stop the program. Some characters per line will be repeated because they have different functions depending on the direction of the pointer, and the fourth line will have characters in reverse order because the pointer moves right to left.
A summary of the program is provided below.
Look at the [instructions listed for ><> on esolangs](http://esolangs.org/wiki/Fish#Instructions) to see what each individual character does.
Line 1: `0&v`
```
0&v -put 0 into the register and change direction to down-up
```
Line 2: `=?\ilb`
(starting where line 1 moves the pointer to, i.e. the third character)
```
\ -reflect the pointer and make it move left-right
i -read input
lb=?\ -reflect downwards if there are 11 values in the stack
```
line 3: `=?\:@=&+&l1`
(starting at the third character)
```
:@ -duplicate y and shift the stack e.g. ['x','y','y'] -> ['y','x','y']
=&+& -increment the register if the character popped from x = y
l1=?\ -reflect downwards if there is 1 value in the stack
```
Line 4: `n&/;`
(starting at the third character)
```
/ -reflect right-left
&n; -print value of the register
```
[Answer]
# Ruby, ~~22~~ 20 bytes
```
p gets.count(gets)-1
```
Demo: <http://ideone.com/MEeTd2>
The `-1` is due to the fact that `gets` retrieves the input, plus a newline character. Ruby's [`String#count`](http://ruby-doc.org/core-2.2.0/String.html#method-i-count) counts the number of times *any* character from the argument occurs in the string.
For example, for the input [`test\n`, `t\n`], the `t` occurs twice and the `\n` occurs once, and needs to be subtracted.
[Answer]
# Ruby, 18 bytes
```
->s,c{p s.count c}
```
# Usage:
```
->s,c{p s.count c}.call 'tttggloyoi', 't'
->s,c{p s.count c}.call 'onomatopoe', 'o'
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 bytes
```
èV
```
[Try it online!](https://tio.run/##y0osKPn///CKsP//lUpKStLTc/Ir8zOVuJRKlAA "Japt – Try It Online")
] |
[Question]
[
In the webcomic [Darths & Droids](http://darthsanddroids.net/episodes/0001.html), Pete, who plays R2-D2 in the fictional roleplaying campaign around which the comic is based, [once claims](http://darthsanddroids.net/episodes/1174.html) (warning: potential spoilers in the linked comic) that, with the Lost Orb of Phanastacoria rigged up to his shock probe, he can now dish out a whopping [1048576d4](http://en.wikipedia.org/wiki/Dice_notation) of damage. (The GM has neither confirmed nor denied this.) Since it should be reasonably obvious that almost no one will actually have the patience to roll that many dice, write a computer program to do it for him, outputting the total value rolled in some reasonable format. Entries will be ranked by program size (shortest program, by byte count, wins), both overall and per-language, with run time breaking ties. Answer may be either a full program or a function definition.
# Scores Per-Language
**Pyth**
Maltysen - 8 bytes\*
Jakube - 10 bytes
**APL**
Alex A - 10 bytes
**CJam**
Optimizer - 11 bytes
**J**
ɐɔıʇǝɥʇuʎs - 12 bytes \*\*
**Clip10**
Ypnypn - 12 bytes \*\*
**K**
JohnE - 13 bytes
**Ti-84 BASIC**
SuperJedi224 - 17 bytes\*
**R**
MickyT - 23 bytes
**OCTAVE/MATLAB**
Oebele - 24 bytes
**PARI/GP**
Charles - 25 bytes \*\*
**Wolfram/Mathematica**
LegionMammal978 - 27 bytes
**Perl**
Nutki - 29 bytes
AsciiThenAnsii - 34 bytes
**Ruby**
Haegin - 32 bytes \*\*
ConfusedMr\_C - 51 bytes \*\*
**Commodore Basic**
Mark - 37 bytes \*\*
**PHP**
Ismael Miguel - 38 bytes
**VBA**
Sean Cheshire - 40 bytes \*\*
**PowerShell**
Nacht - 41 bytes \*\*
**Javascript**
Ralph Marshall - 41 bytes
edc65 - 54 bytes (Requires ES6 functionality not available in all browsers.)
**Lua**
cryptych - 51 bytes
**Java**
RobAu - 52 bytes \*\*
Geobits - 65 bytes
**C**
Functino - 57 bytes
**Python**
CarpetPython - 58 bytes
**Postgre/SQL**
Andrew - 59 bytes \*\*
**Swift**
Skrundz - 69 bytes
GoatInTheMachine - 81 bytes
**Haskell**
Zeta - 73 bytes \*\*
**ActionScript**
Brian - 75 bytes \*\*
**><>**
ConfusedMr\_C - 76 bytes
**GO**
Kristoffer Sall-Storgaard - 78 bytes
**C#**
Brandon - 91 bytes \*\*
Andrew - 105 bytes
Ewan - 148 bytes
**Scratch**
SuperJedi224 - 102 bytes
**C++**
Michelfrancis Bustillos - 154 bytes
**Polyglots**
Ismael Miguel (Javascript/ActionScript2) - 67 bytes
---
# Top 10 Overall
```
Maltysen
Alex A
Jakube
Optimizer
ɐɔıʇǝɥʇuʎs/Ypnypn (order uncertain)
JohnE
SuperJedi224
MickyT
Oebele
```
---
Warning- entries marked with a \* are VERY SLOW.
Programmed marked \*\* I have not yet been able to properly test
[Answer]
# Pyth - 9 8 bytes
Uses obvious simple method of summation of randint. Took me minute to realize `1048576` was `2^20`, now I feel really stupid. Thanks to @Jakube for saving me a byte by pointing out `2^20 = 4^10`.
```
smhO4^4T
```
The runtime is horrible, it has yet to finish on my computer, so there is no point running it online so here is the `2^10` one: [Try it online here](http://pyth.herokuapp.com/?code=smhO4%5E2T&debug=0).
```
s Summation
m Map
h Incr (accounts for 0-indexed randint)
O4 Randint 4
^4T Four raised to ten
```
[Answer]
# Perl - ~~48~~ ~~44~~ ~~37~~ ~~39~~ 34 bytes
```
$-+=rand(4)+1for(1..2**20);print$-
```
Prints the sum without a trailing newline.
Saved 4 bytes by substituting for `2**20` (thanks Maltysen) and removing quotes around print.
Saved another 7 bytes by rearranging the code (thanks Thaylon!)
Lost 2 bytes because my old code generated 0-4 (it should be 1-4).
Once again, saved 5 bytes thanks to Caek and nutki.
Ungolfed, properly written code:
```
my $s = 0
$s += int( rand(4) + 1 ) for (1 .. 2**20);
print "$s";
```
[Answer]
# APL, ~~11~~ 10 bytes
```
+/?4⍴⍨2*20
```
This just takes the sum of an array of 220 = 1048576 random integers between 1 and 4.
```
+/ ⍝ Reduce by summing a
? ⍝ random integer
4⍴⍨ ⍝ array with values between 1 and 4
2*20 ⍝ of length 2^20
```
You can [benchmark this on TryAPL](http://tryapl.org/?a=%u2395ts%u22C4+/%3F4%u2374%u23682*20%u22C4%u2395ts&run) by printing the timestamp before and after. It takes about 0.02 seconds.
Saved a byte thanks to marinus and FUZxxl!
[Answer]
# Ti-84 Basic, 17 bytes
Total footprint - Size of program header = 17 bytes
Run Time: Unknown, estimated at 5-6 *hours* based on performance for smaller numbers of rolls (so, basically, not very good)
```
Σ(randInt(1,4),A,1,2^20
```
[Answer]
# R, ~~32~~ ~~24~~ ~~23~~ 21 bytes
Edit: Got rid of the `as.integer` and used integer division `%/%`. Speed it up slightly.
Thanks to Alex A for the sample tip ... and Giuseppe for removing the `r=`
```
sum(sample(4,2^20,T))
```
Tested with
```
i = s = 0
repeat {
i = i + 1
print(sum(sample(4,2^20,r=T)))
s = s + system.time(sum(sample(4,2^20,r=T)))[3]
if (i == 10) break
}
print (s/10)
```
Outputs
```
[1] 2621936
[1] 2620047
[1] 2621004
[1] 2621783
[1] 2621149
[1] 2619777
[1] 2620428
[1] 2621840
[1] 2621458
[1] 2620680
elapsed
0.029
```
For pure speed the following completes in microseconds. However I'm not sure I've got my logic correct for it. The results appear consistent with the random method. Shame it's a longer length.
```
sum(rmultinom(1,2^20,rep(1,4))*1:4)
```
Here's a timing run I did on my machine
```
system.time(for(i in 1:1000000)sum(rmultinom(1,2^20,rep(1,4))*1:4))
user system elapsed
7.330000000000040927262 0.000000000000000000000 7.370000000000345607987
```
[Answer]
# Python 2, 58 bytes
We get 1048576 random characters from the operating system, take 2 bits of each, and add them up. Using the `os` library seems to save a few characters over using the `random` library.
```
import os
print sum(1+ord(c)%4 for c in os.urandom(1<<20))
```
This takes about 0.2 seconds on my PC.
[Answer]
# CJam, ~~12~~ 11 bytes
```
YK#_{4mr+}*
```
This is pretty straight foward:
```
YK e# Y is 2, K is 20
# e# 2 to the power 20
_ e# Copy this 2 to the power 20. The first one acts as a base value
{ }* e# Run this code block 2 to the power 20 times
4mr e# Get a random int from 0 to 3. 0 to 3 works because we already have
e# 2 to the power 20 as base value for summation.
+ e# Add it to the current sum (initially 2 to the power 20)
```
But the beauty of this is that its really fast too! On my machine (and using the [Java compiler](https://sourceforge.net/p/cjam/wiki/Home/)) it takes on an average of 70 milliseconds.
The [online version](http://cjam.aditsu.net/#code=esYK%23_%7B4mr%2B%7D*es%40-p) takes around 1.7 seconds on my machine.
*Update*: 1 byte saved thanks to DocMax
[Answer]
# JavaScript (ES6), 54 bytes
Average time < 100 msec. Run snippet to test (in Firefox)
```
// This is the answer
f=t=>(i=>{for(t=i;i--;)t+=Math.random()*4|0})(1<<20)|t
// This is the test
test();
function test(){
var time = ~new Date;
var tot = f();
time -= ~new Date;
Out.innerHTML = "Tot: " + tot + " in msec: " + time + "\n" + Out.innerHTML;
}
```
```
<button onclick="test()">Repeat test</button><br>
<pre id=Out></pre>
```
**Explanation**
With no statistical package built-in, in Javascript the shortest way to obtain the sum of 1 million random number is to call random() for a million times. So simply
```
f=()=>{
var t = 0, r, i
for (i=1<<20; i--; )
{
r = Math.random()*4 // random number between 0 and 3.9999999
r = r + 1 // range 1 ... 4.999999
r = r | 0 // truncate to int, so range 1 ... 4
t = t+r
}
return t
}
```
Now, adding 1 for a million times is exactly the same than adding 1 million, or even better, start the sum with 1 million and then add the rest:
```
f=()=>{
var t, r, i
for (t = i = 1<<20; i--; )
{
r = Math.random()*4 // random number between 0 and 3.9999999
r = r | 0 // truncate to int, so range 0 ... 3
t = t+r
}
return t
}
```
Then golf, drop the temp variable r and drop the declaration of local variables. `t` is a parameter, as one is needed to shorten the declaration of `f`. `i` is global (bad thing)
```
f=t=>{
for(t=i=1<<20;i--;)
t+=Math.random()*4|0
return t
}
```
Then find a way to avoid 'return' using a nameless inner function. As a side effect, we gain another parameter so no globals used
```
f=t=>(
(i=>{ // start inner function body
for(t=i;i--;)t=t+Math.random()*4|0 // assign t without returning it
})(1<<20) // value assigned to parameter i
| t // the inner function returns 'undefined', binary ored with t gives t again
) // and these open/close bracket can be removed too
```
[Answer]
# Perl, 29
Generates a table of the required length.
```
print~~map{0..rand 4}1..2**20
```
[Answer]
# [J](http://jsoftware.com/) (12 bytes, about 9.8 milliseconds)
```
+/>:?4$~2^20
```
I suspect this is mostly memory bandwith-limited: I can't even get it to max out a single core...
You can test this with the following code:
```
timeit =: 13 : '(1000 * >./ ($/x) 6!:2"0 1 y)'
4 20 timeit '+/>:?4$~2^20'
9.90059
```
This runs it in 4 groups of 20 trails, and returns the number of milliseconds of the avarage time in the quickest group. An interpreter can be found [here](http://www.jsoftware.com/download/j803/install/).
[Answer]
# Pyth, 10 bytes
```
u+GhO4^4TZ
```
This has slightly more bytes than @Maltysen's Pyth solution. But it runs in 8.5 seconds on my laptop, while @Maltysen's solution produced no solution in 20 minutes running time.
But still a little bit too slow for the online compiler.
### Explanation
```
u ^4TZ start with G = 0, for H in 0, ... 4^10-1:
G =
+GhO4 G + (rand_int(4) + 1)
result is printed implicitly
```
[Answer]
# Java, 65
Since we have scores listed by language, why not throw Java into the mix? There's not much to golf here, just a simple loop, but I was able to squeeze a couple out of my initial attempt:
```
int f(){int i=1<<20,s=i;while(i-->0)s+=Math.random()*4;return s;}
```
[Answer]
# Matlab, 24
First submission ever!
```
sum(randi([1,4],1,2^20))
```
I had hoped to make use of randi([1,4],1024), which gives a matrix of 1048576 elements, but then I needed a double sum, which takes more characters than this.
Regarding the running speed mentioned in the question, `timeit` tells me the runtime is about 0.031 seconds. So, pretty much instant.
[Answer]
## Haskell, 73 bytes
```
import System.Random
f=fmap sum.(sequence.replicate(2^20))$randomRIO(1,4)
```
Usage:
```
$ ghci sourcefile.hs
ghci> f
2622130
```
[Answer]
**C#: 105 bytes**
```
using System.Linq;class C{int D(){var a=new System.Random();return new int[1<<20].Sum(i=>a.Next(1,5));}}
```
[Answer]
# PHP, ~~38~~ 37 bytes
This uses a very simple idea: sum them all!
Also, I've noticed that `1048576` is `10000000000000000000` in binary, equivalent to `1<<20`.
Here's the code:
```
while($i++<1<<20)$v+=rand(1,4);echo$v
```
---
Test in your browser (with **VERY LITTLE** changes):
```
$i=$v=0;while($i++<1<<20)$v+=rand(1,4);printf($v);
```
```
//'patch' to make a TRUE polyglot, to work in JS
if('\0'=="\0")//this will be false in PHP, true in JS
{
//rand function, takes 2 parameters
function rand($m,$n){
return ((Math.random()*($n-$m+1))+$m)>>0;
/*
*returns an integer number between $m and $n
*example run, with rand(4,9):
*(Math.random()*(9-4+1))+4
*
*if you run Math.random()*(9-4+1),
*it will returns numbers between 0 and 5 (9-4+1=6, but Math.random() never returns 1)
*but the minimum is 4, so, we add it in the end
*this results in numbers between 0+4 and 4+5
*
*/
}
//for this purpose, this is enough
function printf($s){
document.write($s);
}
}
/*
*Changes:
*
*- instead of echo, use printf
* printf outputs a formatted string in php
* if I used echo instead, PHP would complain
*- set an initial value on $i and $v
* this avoids errors in Javascript
*
*/
$i=$v=0;while($i++<1<<20)$v+=rand(1,4);printf($v);
```
All the changes in the code are explained in comments.
[Answer]
# Mathematica, ~~30~~ 27 bytes
```
Tr[RandomInteger[3,2^20]+1]
```
Mathematica has quite long function names...
[Answer]
# C, 57 bytes
```
main(a,b){for(b=a=1<<20;a--;b+=rand()%4);printf("%d",b);}
```
This code works... once. If you ever need to roll those dice again, you'll need to put `srand(time(0))` in there, adding 14 bytes.
[Answer]
# PostgreSQL, 59 bytes
```
select sum(ceil(random()*4)) from generate_series(1,1<<20);
```
I'll admit to the slight problem that `random()` could, in theory, produce exactly zero, in which case the die roll would be zero.
[Answer]
# Ruby, 32 bytes
```
(1..2**20).inject{|x|x-~rand(4)}
```
In a more readable form:
```
(1..2**20).inject(0) do |x|
x + rand(4) + 1
end
```
It creates a range from 1 to 1048576 and then iterates over the block that many times. Each time the block is executed the value from the previous iteration is passed in as `x` (initially 0, the default for `inject`). Each iteration it calculates a random number between 0 and 3 (inclusive), adds one so it simulates rolling a d4 and adds that to the total.
On my machine it's pretty fast to run (`0.25 real, 0.22 user, 0.02 sys`).
If you've got Ruby installed you can run it with `ruby -e 'p (1..2**20).inject{|x|x+rand(4)+1}'` (the `p` is necessary to see the output when run in this manner, omit it if you don't care for that or just run it inside IRB where the result is printed to the screen for you). I've tested it on Ruby 2.1.6.
Thanks to histocrat for the bit twiddling hack that replaces `x + rand(4) + 1` with `x-~rand(4)`.
[Answer]
## PARI/GP, 25 bytes
Really, no need for golfing here -- this is the straightforward way of doing the calculation in GP. It runs in 90 milliseconds on my machine. Hoisting the `+1` saves about 20 milliseconds.
```
sum(i=1,2^20,random(4)+1)
```
Just for fun: if one were optimizing for *performance* in PARI,
```
inline long sum32d4(void) {
long n = rand64();
// Note: __builtin_popcountll could replace hamming_word if using gcc
return hamming_word(n) + hamming_word(n & 0xAAAAAAAAAAAAAAAALL);
}
long sum1048576d4(void) {
long total = 0;
int i;
for(i=0; i<32768; i++) total += sum32d4();
return total;
}
```
has a very small total operation count -- if [xorgens](https://maths-people.anu.edu.au/~brent/random.html) needs ~27 cycles per 64-bit word (can anyone verify this?), then a processor with POPCNT should take only about 0.5 cycle/bit, or a few hundred microseconds for the final number.
This should have close-to-optimal worst-case performance among methods using random numbers of similar or higher quality. It should be possible to greatly increase average speed by combining cases -- maybe a million rolls at a time -- and selecting with (essentially) [arithmetic coding](https://en.wikipedia.org/wiki/Arithmetic_coding).
[Answer]
# Javascript, ~~55~~ ~~53~~ ~~50~~ ~~47~~ 41 bytes
```
for(a=i=1<<20;i--;)a+=(Math.random()*4)|0
```
I didn't realize that non-random numbers were a known irritant, so I figure that I ought to post a real solution. Meant no disrespect.
Commentary: as noted by others above you can skip the +1 to each roll by starting off with the number of rolls in your answer, and by not having to write a=0,i=1<<20 you save two bytes, and another 2 because you don't add +1 to each roll. The parseInt function does the same thing as Math.floor but is 2 characters shorter.
[Answer]
## [Clip 10](https://esolangs.org/wiki/Clip), 12 bytes
```
r+`m[)r4}#WT
#4T .- 4^10 = 1048576 -.
m[ } .- that many... -.
)r4 .- ...random numbers -.
r+` .- sum -.
```
It takes approximately 0.6 seconds to run on my machine.
[Answer]
# Go, 78 bytes
## Golfed
```
import."math/rand";func r()(o int){for i:=2<<19;i>=0;i--{o+=Intn(4)+1};return}
```
Still working on it
Run online here <http://play.golang.org/p/pCliUpu9Eq>
[Answer]
# Go, 87 bytes
## Naive solution
```
import"math/rand";func r(){o,n:=0,2<<19;for i:=0;i<n;i++{o+=rand.Intn(4)};println(o+n)}
```
Run online here: <http://play.golang.org/p/gwP5Os7_Sq>
Due to the way the Go playground works you have to manually change the seed (time is always the same)
[Answer]
## Commodore Basic, 37 bytes
```
1F┌I=1TO2↑20:C=C+INT(R/(1)*4+1):N─:?C
```
PETSCII substitutions: `─` = `SHIFT+E`, `/` = `SHIFT+N`, `┌` = `SHIFT+O`
Estimated runtime based on runs with lower dice counts: 4.25 hours.
It's tempting to try to golf off two bytes by making `C` an integer, getting implicit rounding of the random numbers. However, the range on integers in Commodore Basic is -32678 to 32767 -- not enough, when the median answer is 2621440.
[Answer]
## PowerShell, 41 37 bytes
```
1..1mb|%{(get-random)%4+1}|measure -s
```
Took my machine 2 minutes 40 seconds
[Answer]
## Ruby, ~~51~~ 47 chars
```
x=[];(2**20).times{x<<rand(4)+1};p x.inject(:+)
```
I looked at all of the answers before I did this, and the `sum(2**20 times {randInt(4)})` strategy really stuck out, so I used that.
## ><>, 76 chars
```
012a*&>2*&1v
|.!33&^?&:-<
3.v < >-:v >
vxv1v^<;3
1234 n+
>>>> >?!^^
```
I'm not sure if this one works, because my browser crashed when I tried to test it, but [here](http://fishlanguage.com/playground/L8bSSCWp9R3Wo9pG8)'s the online interpreter.
[Answer]
# Swift, 64 bytes
Nothing clever, golfing in Swift is hard...
```
func r()->Int{var x=0;for _ in 0..<(2<<19) {x+=Int(arc4random()%4)+1;};return x;}
```
Version 2 (too late)
```
var x=0;for _ in 0..<(2<<19){x+=Int(arc4random()%4)+1;};print(x)
```
[Answer]
# Java (Java 8) - 52
```
int f(){return new Random().ints(1<<20,1,5).sum();}
```
] |
[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/25003/edit).
Closed 1 year ago.
[Improve this question](/posts/25003/edit)
Inspired by the ill-fated [sorting-a-numbers-digits-without-using-an-array](https://stackoverflow.com/questions/22720895/sorting-a-numbers-digits-without-using-an-array#comment34628217_22720895), but I thought it made a better code golf than SO question.
Given a positive integer, sort the digits in that integer.
Lowest score wins!
1. Start with 0 points.
2. Add one point per character.
3. Add 20 points for each array you use.
4. Add 10 points for each multi-character string in your code. (Except the initial input as long as it is converted to an integer without any other operations done on it.)
5. Add 32 points if the maximum number of digits your program can handle is limited by your program (as opposed to the machine).
6. Subtract 10 points if your code can change the direction of the sort given another argument (whatever you want, but for example 0 for descending sort and 1 for ascending.)
*Every language is different, but the idea is to avoid any kind of iterable-of-digits hackery.*
### Example:
**Input**: 52146729
**Output**: 97654221 or 12245679
### Notes:
1. Use any built-in sorting capabilities your programming language provides, but if that sort feature involves strings or arrays, take the penalty!
2. You can write the solution as a function that takes an integer directly, or as a program that takes an argument from argv, a file or stream and converts it to an integer. As long as you convert it to an integer immediately and discard the original char\* input without doing any further operations on it, no penalty applies.
3. The penalties apply not only to string literals in your program text, but any part of your program feature that arguably inputs or outputs a string or iterable. For example, JavaScript [`String.prototype.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) has at least one string as input (`this`) and an Array as output, so +30 for using that.
4. I've tried to make these rules guide the principle of the algorithm design, not the initial/final I/O (hence note #2). I don't think the penalty ought to apply to `int(input())` even if `input`'s signature says it returns a string, as long as that expression is the *initial entry point* of the program. Likewise, if the final output of the program is `print(x)` and `x` must be a string, the penalty doesn't apply to the last-ditch string casting operation. All that said, I explicitly never said that this had to be a *program* or where the I/O had to come from or go. A function that takes an `int` and returns an `int` would serve, and wouldn't suffer from these ambiguities.
[Answer]
# Haskell 106
```
t=10;d=divMod;s z|z<w z=s$w z|t>0=z
w x|x<t=x|y>z=(q*t+y)*t+z|t>0=y+t*(w v)where{(v,y)=d x t;(q,z)=d v t}
```
example:
```
ghci> s 502010406072952146729521467295214672952146729
999997777766666555554444422222222221111100000
```
An answer that doesn't dodge the question.
An explanation was requested, here it is ungolfed. It's a very inefficient bubble sort.
```
-- t=10 - alias for 10. d=divMod - alias for divMod.
-- The alias for '10' turns out to be unnecessary; inlining it
-- and using '1>0' for True has the same character count. It's
-- a relic of earlier versions of the code.
-- 's': if no digits need swapped, return the number,
-- otherwise return 's' applied to the number with
-- that pair of digits swapped.
sort z=
let temp=sort_pair z
-- because we are sorting in descending order,
-- sorting a pair of digits always increases the number.
-- testing > costs one less char than ==.
if z<temp then
-- golfed version uses guards instead of if/else to save space.
-- t>0 is '10 > 0', which is 'True', in fewer chars.
sort temp
else
z
-- 'w': recursively swap one pair of out of order digits, or
-- return the original number if no pairs needed swapped.
sort_pair x=
-- haskell does the assignments below lazily, they aren't
-- calculated unless I use them. 'divMod' lets me do this
-- with fewer chars.
let y = x `mod` 10 -- last digit
v = x `div` 10 -- all but last digit
z = v `mod` 10 -- second last digit
q = v `div` 10 -- all but last 2 digits
in
if x < 10 then
x
else if y > z then
-- last 2 digits are out of order. swap them & return
-- This is rearranged using Horner's method to save space
-- http://en.wikipedia.org/wiki/Horner%27s_method
-- ... although it turns out not to save anything, it's a relic.
(q * 10 + y)*10 + z
else
-- last digit is ok, so try sort_pair on remaining digits
let temp = sort_pair v in
-- put last digit back on the end and return
-- having the bracketed expression last here
-- let me remove a space before 'where'
y+(10*temp)
```
Shorter answers exist in Haskell, equivalent to some of the others posted, eg:
```
import Data.List;s=read.sort.show::Integer->Integer
```
... scores 52+20=72, or this, scoring 45+20=65:
```
import Data.List;main=interact(reverse.sort)
```
... but the spirit of the question - no arrays, strings, or characters - is more interesting.
[Answer]
# GolfScript, ~~11~~ 4
### (4 + 10 (string) - 10 (reverse option))
Input on STDIN.
```
~`$%
```
Input format is this:
```
(1 or -1) (the number)
```
`1` to sort normally, `-1` to reverse. 4 characters - 10 for reverse option = score of -6.
The input is technically a string, so I'm not sure whether that counts for +10. I'm interpreting the rule as "a string declared in your program" (since it says "in your code").
---
Old answer (score of 11):
```
$
```
[Answer]
# C + x86 assembly, 636
I know this isn't gonna win but it felt so much unnatural and twisted that I had to share it. No arrays or strings (as long as you don't count the input arguments). The number of digits its limited by the 32 bit range.
So here's a little explanation on what I did:
I thought I'd do this without using any arrays or strings, and then recursion came into mind, but of course, with recursion I wouldn't be able to swap values from other recursive calls... and then was when I realized that there was a way. Linking my C program with an assembly function I could jump up in the stack and return a pointer to the base pointer of the desired call, that's what "recursionStackAt" function does. Of course recursionStackAt is a very ugly function, its result doesn't only depend on the input or program's state but on the caller itself. Note that that's what made me change the indexes from 0 based to 1 based.
Without further ado, here's the code:
```
#include <stdio.h>
#include <stdlib.h>
int numberToSort;
int totalLength = 0;
int decreasing;
int* recursionStackAt(int pos); //Here's the magic
void swapAtStack(int pos1, int pos2) {
int a = *(recursionStackAt(pos1)+3);
*(recursionStackAt(pos1)+3) = *(recursionStackAt(pos2)+3);
*(recursionStackAt(pos2)+3) = a;
}
int getAt(i) {
return *(recursionStackAt(i)+3);
}
void printNumber(int len) {
int i = 0;
for(i = 1; i <= len; ++i) {
printf("%d",*(recursionStackAt(i)+3));
}
printf("\n");
}
void computeNextDigit(int remainingNumber, int nextDigit) {
if(remainingNumber == 0) {
//Bubble sort cause I was lazy and it's quite compact
++totalLength;
int i, j;
for(i = 1; i <= totalLength; ++i)
for(j = 1; j <= totalLength-1; ++j) {
if(decreasing) {
if(getAt(j) > getAt(j+1))
swapAtStack(j,j+1);
}
else {
if(getAt(j) < getAt(j+1))
swapAtStack(j,j+1);
}
}
printNumber(totalLength);
}
else {
++totalLength;
computeNextDigit(remainingNumber/10, remainingNumber%10);
}
}
int main(int argc, char* argv[]) {
if(argc == 3) {
numberToSort = atoi(argv[1]);
decreasing = atoi(argv[2]);
}
else exit(1);
computeNextDigit(numberToSort/10, numberToSort%10);
}
```
And of course the x86 (AT&T sintax, btw) assembly code for the recursionStackAt function:
```
.text
.align 4
.globl recursionStackAt
.type recursionStackAt, @function
recursionStackAt:
pushl %ebp
movl %esp,%ebp
pushl %esi
movl $0, %esi #i = 0
movl (%ebp), %eax #pointer
while:
cmp %esi, 8(%ebp)
je endwhile
movl (%eax),%eax
incl %esi
jmp while
endwhile:
popl %esi
movl %ebp, %esp
popl %ebp
ret
```
Some examples on the output: (1 means increasing and 0 decreasing)
```
$ ./sortasort 6543210 1
0123456
$ ./sortasort 32507345 1
02334557
$ ./sortasort 32507345 0
75543320
```
Here's the obfuscated version (which is unreadable but works fine):
<http://pastebin.com/XkYt9DLy> (C code)
<http://pastebin.com/h0S0dfeU> (x86 code)
So if LibreOffice isn't lying my obfuscated code consists of 646 characters (without spaces, should I count them?) and with all the other conditions met I get a -10 for the incresing/decreasing choice.
Oh, and to compile this you should do (On Unix-like systems)
```
gcc -c [-m32] recursionStackAt.s
gcc -o sortasort [-m32] sortasort.c recursionStackAt.o
```
Note that the -m32 flag is only if you're on a 64 bit machine. You also need the 32 bit libraries to compile it.
[Answer]
## Bash (echo) (0+7+0+0+32-10) = 29
Sorta:
```
echo $*
```
Usage:
```
sorta 5
5
```
Use "-e" to sort in reverse:
```
sorta -e 3
3
```
* produces the correct result for positive integers 1-9, plus 0
* avoids any kind of iterable-of-digits hackery.
* 7 characters (+7)
* no arrays
* no multi-character strings
* maximum number of digits it can handle: 1 (+32)
* can optionally reverse the sort (-10)
EDIT: changed "cat" to "echo" so it would actually work.
EDIT 2: Added " $\*" and put it into "sorta" script
[Answer]
# Python3
My script features:
**No arrays**
**No strings**
**Complexity is O(n):** I used countingsort (modified by me to not use arrays, but **prime numbers** to count occourences)
**No limitations in size**
**Characters: 260 234**
```
n=int(input())
def C(n,k):
return (n//(10**(k-1)))%10
P=lambda l:((((29-6*l%2,19-2*l%2)[l<9],13-2*l%2)[l<7],2*l-1)[l<5],2)[l==1]
p=1
while n>=1:
c =C(n,1)
p*=P(c+1)
n=n//10
f=1
k=r=0
while p>2:
if(p%P(f)==0):
r+=(f-1)*10**k
p=p//P(f)
k+=1
else: f+=1
print(r)
```
[Answer]
# Bash+coreutils, 14 (24 chars - 10 for reverse)
I think this might be bending the rules a bit, but here goes, its Friday...
I assume use of standard libraries is allowed. My interpretation of standard library for `bash` is `coreutils`:
```
fold -1|sort $1|tr -d\\n
```
* No arrays - streams are used instead
* No quotes == no multi-character strings
* No limit to input/output length
* optional arg "-r" reverses the output.
Input from stdin. In use:
```
$ declare -i i=52146729
$ ./ksort.sh <<< $i
12245679 $
$ ./ksort.sh -r <<< $i
97654221 $
$
```
[Answer]
# C - 64 characters, 64 points
```
main(int a,char**b){b++;qsort(*b,strlen(*b),1,strcmp);puts(*b);}
```
You might wonder how I get this to work without any headers. Simple, compile with:
```
gcc -include stdio.h stdlib.h string.h test.c -o test --std=gnu11 -Wall -g -O3
```
**Un-golfed:**
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main(int a, char **b)
{
b++;
qsort(*b, strlen(*b), sizeof(char), strcmp); // sizeof(char) is guaranteed to be 1 by standards
puts(*b);
}
```
---
I also decided to include sorting of characters, just because I could.
Test runs:
```
$ ./test 132815
112358
$ ./test 423791
123479
$ ./test 1234767189728975213132471243985123957120837412
0111111112222222233333344445556777777788889999
$ ./test 4789359uihjasvb8ygohq9poi3n4jiouy58g
3344557888999abgghhiiijjnooopqsuuvyy
```
[Answer]
# c function (little-endian arch), 131 108 chars
No sorting challenge is complete without a [sleepsort](https://dis.4chan.org/read/prog/1295544154) answer. This one will take up to 10 seconds to return, but it does work, and I think it is fully within spec. This function takes a single int param and returns an int with the decimal digits sorted:
```
c=0,d;
k(i){
for(;i;i/=10,fork()?c++:(sleep(d),exit(d)))
d=i%10;
for(;c--;i=i*10+(d>>8&255))
wait(&d);
return i;
}
```
*newlines and indentation added for readability*
Call as follows:
```
int main (int argc, char **argv) {
int i = 52146729;
printf("%d\n", k(i));
return (0);
}
```
[Answer]
# TeX/LaTeX (332)
If the actual code is put in a package `s`, then the main LaTeX file looks nice and easy. The number is just given as math. If the number is negative, the sorting order is reversed. The code of package `s` can also used with plain TeX, example further below.
```
\documentclass{book}
\usepackage{s}
\begin{document}
$52146729$
$-52146729$ % reversed ordering
$277981468517523153773703292073191466142223027369188752287219582183$
\end{document}
```
**The package `s`** (one line, line ends are not needed):
```
\TeXXeTstate1\everymath{\aftergroup\B\def~#1{\gdef#1{}\aftergroup#1}
~\a~\b~\c~\d~\e~\f~\g~\h~\i~\j\aftergroup\E\xdef\B{}\xdef\E{}}
\def~#1#2{\mathcode`#1"8000\lccode`~`#1\lowercase{\def~{\xdef#2{#2#1}}}}
~0\a~1\b~2\c~3\d~4\e~5\f~6\g~7\h~8\i~9\j\mathcode`-"8000\lccode`~`-
\lowercase{\def~{\xdef\B{\beginR}\xdef\E{\endR}}}
```
**Result:**
>
> 
>
>
>
**Score:** hopeless
* Using plain TeX with `etex` or `pdftex`, the file can be reduced to:
`*<contents of s.sty>*\rm\shipout\hbox{$*<number>*$}\bye`
Bytes: **318** bytes (`s.sty`) + **24** bytes for the rest without the number
* Arrays are not used: **0**
* I do not see multi-character strings: **0**
* The number is not limited by the algorithm. The largest TeX number is 231 - 1 = 2147483647. The example uses a 66-digit number, way larger:
**0**
* If a minus is given, then the sorting order is reverted to descending: **−10**
0 + 318 + 24 + 0 + 0 − 10 = **332**
**Algorithm:**
The digits are made active characters in math mode. Each digit remembers and collects each usages in a macro. After the math mode the macros are output with the digits in ascending order.
The direction change is done by right-to-left text, an e-TeX feature.
**Degolfed version** of the code in `s.sty`
```
\TeXXeTstate = 1 % enable mixed direction typesetting
\everymath{%
% \B and \E surround the number, they will be redefined
% with right-to-left primitives to output the reverted number
\xdef\B{}
\xdef\E{}
\aftergroup\B
% the active character ~ is defined as help macro;
% the argument is the collector macro
\def~#1{%
\gdef#1{}% initially the macro is empty
\aftergroup#1%
}%
% the ten macros \a to \j form the result number
~\a~\b~\c~\d~\e~\f~\g~\h~\i~\j
\aftergroup\E
}
% the active ~ is used as helper macro;
% first argument is the digit, the second argument is the collector macro
\def~#1#2{%
\mathcode `#1 = "8000 % make digit active in math mode
\lccode `~ = `#1 % trick for defining the active digit
\lowercase{%
\def~{%
\xdef#2{#2#1}% the digit adds itself to its collector macro
}%
}%
}
~0\a~1\b~2\c~3\d~4\e~5\f~6\g~7\h~8\i~9\j
% Defining the minus character as switch for descending digits:
\mathcode `- = "8000 % minus sign active in math mode
\lccode `~ = `- % trick for defining the active minus
\lowercase{%
% the minus sign redefines the wrapper macros \B and \E that
% surround the result number. These macros now uses
% primitives for right-to-left typesetting.
\def~{%
\xdef\B{\beginR}%
\xdef\E{\endR}%
}%
}
```
**Reproducing**
There are some online LaTeX compilers, a list can be found [here](http://texblog.net/latex-link-archive/online-compiler/).
I tried the first item on the list, [LaTeX servlet on sciencesoft.at](http://sciencesoft.at/latex/?lang=en). It can be used without signing and it can also create permanent URLs:
[source](http://sciencesoft.at/lpng/586c8fd7d3db8442114e009514240cfe9c96f9f.txt) and [result as image](http://sciencesoft.at/lpng/586c8fd7d3db8442114e009514240cfe9c96f9f.png&size=100).
[Answer]
# Java : 262 points
*Yeah, yeah I know, it's hopeless, but still..*
```
class G{Object m(StringBuffer s,int o){for(int i=1;i<s.length();i++){int j=i-1,t=s.charAt(i),u=s.charAt(j);boolean c=o==0?t>u:t<u;for(;j>-1&c;){s.setCharAt(j+1,s.charAt(j));c=--j>-1;c=c?(o==0?t>s.charAt(j):t<s.charAt(j)):c;}s.setCharAt(++j,(char)t);}return s;}}
```
**Analysis (marking):**
1. Starting with 0. (score = 0)
2. 262 characters total. (score = 0 + 262 = 262)
3. +10 - for using `StringBuffer` (I used it because it's *shorter* than `StringBuilder`) (score = 262 + 10 = 272)
4. -10 - for making the output flexible. I've considered **0 = descending**, **1 = ascending**, so back to 262!
**Usage:**
When you try and compile the `G.java` file in command prompt, it generates a hell lot of problems (errors). So, the solution?
>
> Compile the `G.java` class in an IDE like `NetBeans` or `Eclipse` or even `BlueJ`. It should compile without any trouble (ignore any warnings).
>
>
>
Then, this class should be called by a `main()` method from any other class (or even that class itself). I'm putting it another class, so I'm not adding it to my character count. Compile the other class in a similar manner (without using `cmd`). Now the `main()` method in the *other* class should be something like:
```
public static void main(String[]a){
System.out.println(new G().m(new StringBuffer(a[0]),1));
//for descending, put '0' instead of '1'
}
```
Excluding unnecessary spaces, comments and line breaks, it's another 93 characters. I'm not adding it to my character because this is just for demonstration through console.
**Output:**
*ZERO* i.e. `0` is considered. Supposing the external class is `Helper.java`, and it has been successfully compiled, a few examples through console are:
>
> `INPUT :` C:...>java Helper 008321
>
> `OUTPUT:`001238
>
>
> `INPUT :` C:...>java Helper 79359105
>
> `OUTPUT:`01355799
>
>
>
When changed to `0` i.e. descending...
>
> `INPUT :` C:...>java Helper 008321
>
> `OUTPUT:`832100
>
>
> `INPUT :` C:...>java Helper 79359105
>
> `OUTPUT:`99755310
>
>
>
**NOTES:**
1. I didn't explicitly declare any array in `G.java`. That is the *core* class.
2. I'm using [*insertion sort*](http://en.wikipedia.org/wiki/Insertion_sort) to sort the number digit-wise.
3. The number can be of of the **maximum length** - [`Integer.MAX_VALUE`](http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#MAX_VALUE) because that is the maximum size any array can hold (in Java).
4. This answer can be shortened (I believe) so please help me (improve my first answer).
5. *Darn those great Gods who accidentally created such a lengthy yet great language like Java (and also who came up with code conventions)!*
[Answer]
# C - 65
```
r,t,i;s(n){for(;++i;)for(t=n;t;t/=10)r=t%10-i?r:10*r+i;return r;}
```
The astute observer will note that this sorting algorithm runs in O(n) time on the number of digits in `n`.
The pragmatic observer will note that this sorting algorithm runs in time proportional to the range of signed integers on the platform, that it mutates global state which must be re-initialized between runs, and that many other sacrifices have been made in favor of brevity.
The ungolfed version is not exactly equivalent, but it better conveys the actual algorithm involved.
```
int s(int n)
{
int r = 0;
int t;
int i;
for(i = 0; i < 10; i++)
{
for(t = n; t != 0; t /= 10)
{
if(t % 10 == i)
{
r = 10 * r + i;
}
}
}
return r;
}
```
Here's a test harness for the function:
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if(argc != 2) return 1;
printf("%d\n", s(atoi(argv[1])));
return 0;
}
```
[Answer]
## Haskell - 96
*96 characters, no arrays, no strings, no integer limit, can't reverse*
```
d=(`divMod`10)
a&(0,0)=a
a&(y,z)=(z%d a)&d y
a%(y,z)|z>a=10*(a%d y)+z|1<3=100*y+10*z+a
s=(0&).d
```
Examples:
```
λ: s 52146729
12245679
λ: s 502010406072952146729521467295214672952146729
1111122222222224444455555666667777799999
λ: s 100
1
```
This one is insertion sort, performed directly on the integers themselves. This is similar to the other Haskell entry which is bubble sort, though I swear I was working on it before I saw that one.
Brief guide:
* `d` divides a number into units and tens, i.e.: `d 135` is the pair `(13,5)`
* `a%x` is sorted insertion of digit `a` into the number `x`
* `a&x` sorts `x` by inserting the units digit into `a` and recursing on the result and remainder
* `s x` sorts x by kicking off the `&` recursion on 0 and `x`
The trick is that the second argument of `%` and `&` isn't `x` directly, but `x` divMod'd using `d`
[Answer]
# **Python3.3 61 points**
```
print(''.join(sorted(input())))
```
This program takes in the input as a string, which counts as a string because it is not changed to an integer immediately. **+10**
The string is sorted into an array **+10**
This array is joined together into a string **+10**
**Note:** The `''` used to join the array's contents is not a multi character string, so +10 is not added to the score.
The program consists of 31 characters. **+31**
**31+10+10+10 = 61 points**
[Answer]
## J, 10 characters (+ 1 string) score = 20
```
s=./:~&.":
```
Usage:
```
s 52146729
12245679
```
Works for all 32 bit numbers.
**Explanation:**
`/:~` sort up `&.` under `":` format. My previous version used an array as well, but they're costly so now I need to just use a string and sort the characters alphabetically. `":` converts the number that is input into a string and `/:~` sorts the digits into ascending order. Because the sort is done 'under' format, when the sort is finished, the string is converted back into a number. Adding the ability to reverse would probably cost more than it saves, so I didn't bother.
The argument could be made that since J, like APL and K, is an array-based language, the single input is an array of 1 item, but I chose not to take such a harsh view when calculating my score.
The 32-bit limit is imposed by J, rather than my program. Any higher and J switches the numbers to scientific notation. It's not clear from the question whether the 32 point penalty applies in this case, but even if both of the previous penalties apply (I don't think they should) the score goes up to 72 and still comfortably beats the vast majority of the other answers.
[Answer]
# Python 2.7: 174
```
import math
i=input()
d={n:0for n in xrange(10)}
for n in(i/10**c%10for c in xrange(1+math.log10(i))):d[n]+=1
print"".join(str(n)for n in xrange(10)for c in xrange(d[n]))
```
* No arrays (iterators and a dictionary are used instead)
* No multi-character strings (except output)
* No artificial maximum number of digits
* No reversing
It works by creating a dictionary mapping all 10 digits to 0. Then it iterates over the length of the number (`log10(i)`), extracting each digit (`(i / (10 ** c)) % 10`), and incrementing the counter for that digit in the dictionary. Finally it creates a string made by iterating over all 10 digits, and for each digit yielding one instance of the digit as a string.
I could change the last line to `print"".join(d[n]*str(n)for n in xrange(10))` which would be 16 characters less, but would use multi-character strings.
[Answer]
# C (up to C90) ~~or C++,~~ ~~78~~ 66 points
The function so sort an integer is called `s`.
```
s(i){t=10,a=i?s(i/t):0,b=i%t,c=a%t;return c>b?t*s(a-c+b)+c:t*a+b;}
```
Scoring:
* 66 Characters (+66)
* 0 arrays (+0)
* 0 strings (+0)
* Range defined by machine (size of `int`) (+0)
* Only one sorting direction (-0)
Old version (78 points, works also with C++ and more modern C versions)
```
int s(int i){int t=10,a=i?s(i/t):0,b=i%t,c=a%t;return c>b?t*s(a-c+b)+c:t*a+b;}
```
[Answer]
## C# - 179
```
using System.Linq;class S{void Main(string[] a){Console.Write(string.Concat(string.Concat(a).Replace("-","").OrderBy(o=>a[0].Contains('-')?-o:o)));}}
```
**Un-golfed**
```
using System.Linq;
class S
{
void Main(string[] a)
{
Console.Write(string.Concat(
string.Concat(a)
.Replace("-", "")
.OrderBy(o => a[0].Contains('-') ? -o : o )));
}
}
```
**Test**
Normal:
```
app.exe 52313698
```
Reversed:
```
app.exe 52313698-
```
**Points:**
(I hope I understood the point system properly - feel free to correct)
* Chars: 149
* Strings: 10+10
* Arrays: +20
* Order: -10
* Total: 149+10+20-10 = **179**
---
## C# with [LINQPAD](http://www.linqpad.net) - 123
```
void Main(string[] a){Console.Write(string.Concat(string.Concat(a).Replace("-","").OrderBy(o=>a[0].Contains('-')?-o:o)));}
```
**Test**
Normal:
```
lprun.exe sorta.linq 52313698
```
Reversed:
```
lprun.exe sorta.linq 52313698-
```
**Points:**
* Chars: 122
* Strings: 10+10
* Arrays: +20
* Order: -10
* Total: 122+10+20-10 = **152**
[Answer]
# Java 1469
A string and array free solution in Java. 1437 characters + 32 because it only takes up to Long.MAX\_VALUE as input. By using Double I could go to over 300 digits instead but that would be too tedious to implement. Anything bigger than that would need BigInteger and AFAIK that uses arrays internally. If you use less than 19 digits for the input the output will have leading zeroes. Negative input will give all zeroes and anything not a number will cause an exception.
For the sort I used the easiest I could think of so it's pretty inefficient. (should be O(n\*n))
```
input: 9212458743185751943
output: 1112233444555778899
```
I know this doesn't really compare to the solutions in other languages but I feel this at least is the shortest I can get it in Java. (if anyone knows how to get this even shorter feel free to edit/comment)
```
class D
{
long c,d,e,f,g,h,k,l,m,n,o,p,q,r,s,t,u,v,w;
long x;
public D(Long a)
{
x = a;
c = g();
d = g();
e = g();
f = g();
g = g();
h = g();
k = g();
l = g();
m = g();
n = g();
o = g();
p = g();
q = g();
r = g();
s = g();
t = g();
u = g();
v = g();
w = g();
int i=0;
while(i++ < 19) s();
System.out.printf("%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d",c,d,e,f,g,h,k,l,m,n,o,p,q,r,s,t,u,v,w);
}
long g()
{
if( x <= 0 ) return 0;
long b = x % 10;
x = x / 10;
return b;
}
void s()
{
if(c > d) {c += d; d = c - d; c -= d;}
if(d > e) {d += e; e = d - e; d -= e;}
if(e > f) {e += f; f = e - f; e -= f;}
if(f > g) {f += g; g = f - g; f -= g;}
if(g > h) {g += h; h = g - h; g -= h;}
if(h > k) {h += k; k = h - k; h -= k;}
if(k > l) {k += l; l = k - l; k -= l;}
if(l > m) {l += m; m = l - m; l -= m;}
if(m > n) {m += n; n = m - n; m -= n;}
if(n > o) {n += o; o = n - o; n -= o;}
if(o > p) {o += p; p = o - p; o -= p;}
if(p > q) {p += q; q = p - q; p -= q;}
if(q > r) {q += r; r = q - r; q -= r;}
if(r > s) {r += s; s = r - s; r -= s;}
if(s > t) {s += t; t = s - t; s -= t;}
if(t > u) {t += u; u = t - u; t -= u;}
if(u > v) {u += v; v = u - v; u -= v;}
if(v > w) {v += w; w = v - w; v -= w;}
}
public static void main(String[] y)
{
D d = new D(Long.parseLong(y[0]));
}
}
```
[Answer]
# AWK - 101
The 'x' file:
```
BEGIN{n=ARGV[1]
r=ARGV[2]
for(d=r;d<10;d++)for(p=1;p<=length(n);p++){D=r?d:9-d
if(D==substr(n,p,1))printf D}print}
```
The run:
```
$ awk -f x 52146729
97654221
$ awk -f x 52146729 0
97654221
$ awk -f x 52146729 1
12245679
$ awk -f x 1234567890123456789012345678901234567890
9999888877776666555544443333222211110000
$ awk -f x 1234567890123456789012345678901234567890 1
111122223333444455556666777788889999
```
The only array used is ARGV and this is no help in sorting, it only is access to the commandline parameters and these values are in non-array variables where actually needed for calculations. I think this won't count against this solution. The following calculation does not take the ARGV-array into account:
111 (chars) - 10 (can do reverse)
[Answer]
I don't see anything about sorting functions in the question, so... (I'm gonna remove the answer if it bends or breaks the rules, let me know)
### JavaScript ~~56~~ 96
```
function s(){alert(+prompt().split('').sort().join(''))}
```
### JavaScript ~~69~~ 109 (reversable)
```
function s(r){x=prompt().split('').sort();x=r?x.reverse():x;alert(+x.join(''))}
```
Can be golfed down a bit using EcmaScript 6 *arrow functions*:
### ES6 ~~50~~ 90
```
s=()=>{alert(+prompt().split('').sort().join(''))}
```
### ES6 ~~63~~ 103 (reversable) (73-10)
```
s=(r)=>{x=prompt().split('').sort();x=r?x.reverse():x;alert(+x.join(''))}
```
[Answer]
# SED 67 Chars (score either 67 or 107)
```
s/$/;0123456789/;:a;s/\(.\)\(.\)\(.*;.*\2.*\1\)/\2\1\3/;ta;s/;.*//;
```
This uses a bubble sort for brevity.
Score would be 107 if each regular expression pattern and replacement count as a string (i.e. 67 + (10 \* 4))
Number of digits handled limited by memory (and probably patience)
[Answer]
## Python lambda function (reversible), 69
```
lambda n,d:''.join(sorted(n,reverse=d))
```
* 39 chars **(+39)**
* Two multi-char strings: `n`(input) and `''.join(...)` **(+20)**
* One list: `sorted(...)` **(+20)**
* Can reverse direction depending on the parameter `d` **(-10)**
---
## Python lambda function (non-reversible), 67
```
lambda n:''.join(sorted(n))
```
---
EDIT: Input should be a string. I am considering the penalty of using that string directly.
[Answer]
# Common Lisp - 126
```
(defun s(n p)(labels((a(n)(if(= 0 n)()(cons(mod n 10)(a (floor n 10)))))(b(a)(if(null a)0(+(car a)(* 10(b(cdr a)))))))(b(sort(a n) p))))
```
The ungolfified (stylistically as well as lexically, but functionally identical) version:
```
(defun sorta (n p)
(labels ((digits (n)
(unless (zerop n)
(multiple-value-bind (quotient remainder)
(truncate n 10)
(cons remainder (digits quotient)))))
(digit-cat (digits)
(if (null digits)
0
(+ (car digits)
(* 10 (digit-cat (cdr digits)))))))
(digit-cat (sort (digits n) p))))
```
The digits of a negative number are treated as having negative value, and digits are sorted least-significant-first (i.e., little-endian). Examples:
```
CL-USER> (sorta 1234 #'<)
=> 4321
CL-USER> (sorta 12344321 #'<)
=> 44332211
CL-USER> (sorta 12344321 #'>)
=> 11223344
CL-USER> (sorta -12344321 #'>)
=> -44332211
CL-USER> (sorta 0 #'>)
=> 0
CL-USER> (sorta 8675309 #'<)
=> 9876530
```
There are 136 characters in the golfed version, including whitespace. It uses no strings and no arrays, and handles arbitrary-precision integers, including negative integers. The sorting is parameterized on a binary predicate which defines a total ordering on the integers in `[-9, 9]`, including but not limited to `<` and `>`:
```
CL-USER> (sorta 3546219870 (lambda (a b)
(cond ((and (evenp a)
(oddp b))
t)
((and (evenp b)
(oddp a))
nil)
(t
(< a b)))))
=> 9753186420
```
This gives a score of 126.
[Answer]
# JavaScript 416 / 185
**No Arrays, no Strings, no arbitrary length constraint**...
But sorting up/down would have used up more than 10 characters ^^ But I found the idea of counting digits and printing them interesting - maybe someone can use this idea in GolfScript and win the prize ;-)
```
var x=window.prompt(),y=0,z=0,a=0,b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0;
do
{
z=x%10;
x=(x-z)/10;
if(!z)a++;
if(z==1)b++;
if(z==2)c++;
if(z==3)d++;
if(z==4)e++;
if(z==5)f++;
if(z==6)g++;
if(z==7)h++;
if(z==8)i++;
if(z==9)j++;
}while(x);
while(a--)y=y*10;
while(b--)y=y*10+1;
while(c--)y=y*10+2;
while(d--)y=y*10+3;
while(e--)y=y*10+4;
while(f--)y=y*10+5;
while(g--)y=y*10+6;
while(h--)y=y*10+7;
while(i--)y=y*10+8;
while(j--)y=y*10+9;
alert(y);
```
The same code shorter, using eval: (but that would likely be considered using strings...)
```
var i = window.prompt(),o=0,i0=0,i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0;
do
{
eval("i"+i%10+"++");
i = ~~(i/10);
} while (i > 0)
for(var j=0;j<10;j++) while (eval("i"+j+"--")>0) o = o*10+j;
alert(o);
```
[Answer]
# C (222)
```
static int a[10],r=1;o(n,c){while(n--)printf("%""i",c);}p(){int n;for(n=r<0?9:0;n>=0&&n<10;n+=r)o(a[n],n);}main(int _,char**v){char*s=v[1];if(*s=='-'){r=-1;++s;}do++a[*s-'0'];while(*++s);p();}
```
Points:
* 192 (192 Chars)
* 40 (2 Arrays: argv(v) and a)
* 0 (no multi char strings)
* 0 (it's not limited to n digits)
* -10 (sorts reverse if the number (argv[1]) is negative)
= 222 Points
Flags needed to get rid of the 1000 compiler warnings:
`gcc -Wno-implicit-function-declaration -Wno-return-type -Wno-implicit-int -Wno-char-subscripts -o count2 counta2.c`
"Better" readable:
```
static int a[10],r=1;
o(n,c){while(n--)printf("%""i",c);}
p(){int n;for(n=r<0?9:0;n>=0&&n<10;n+=r)o(a[n],n);}
main(int _,char**v){char*s=v[1];if(*s=='-'){r=-1;++s;}do++a[*s-'0'];while(*++s);p();}
```
Somewhat ungolfed:
```
static int a[10],r=1;
o(n,c){
while(n--) printf("%""i",c);
}
p(){
int n;
for(n=r<0?9:0;n>=0&&n<10;n+=r) o(a[n],n);
}
main(int _,char**v){
char*s=v[1];
if(*s=='-'){
r=-1;
++s;
}
do ++a[*s-'0']; while(*++s);
p();
}
```
[Answer]
Is there a reason I dont see this solution already?
**Ruby**
```
pry(main)> 52146729.to_s.split("").sort.join.to_i
=> 12245679
```
Am not sure how to score this. The split would generate an array, but beyond that not sure.. 38 chars + 2x20 for arrays? Or should it include all arrays that sort might create internally?
[Answer]
## VBScript - 76 (96?)
```
x = "7892347684578892348025023389054859034234"
for i=0 to 9:n=n&string(len(x)-len(replace(x,i,"")),""&i):next:x=n
' x -> 00002222233333344444455556777888888889999
```
66 character + 10 for the use of string `n`
(Don't know if the use of the `replace` function and `string` function that returns n amount of character x is counted as an extra string).
It counts the amount of a certain digit by comparing the length of the original string with the same string with the certain digit replaced. Then it attaches that amount of digits to n.
[Answer]
# Python 3 sleepsort (168)
With absolutely no list or loop, only generators.
```
import math, threading
n=input()
if any(threading.Timer(x,lambda x:print(x,end='',flush=1),(x,)).start()for x in(n//10**i%10for i in range(math.log10(n)//1+1))):pass
```
could probably be improved.
[Answer]
# Racket 97
97 points (87 +20 for two strings, -10 for sorting, no arrays)
```
(define(s n <)(string->number(list->string(sort(string->list(number->string n))<))))
```
This uses lists of chars so you need to give it a char comparison function like `char<?` or `char>?`. I feel this also passes as ungolfed since it's not much to do than add spaces and increase variable names. My old version is perhaps more honorable :)
Old version without strings:
110 points (120 bytes (utf-8) - 10 for allowing for changing sort order. It uses no strings and no arrays)
```
(define(S d <)(foldl(λ(x a)(+(* a 10)x))0(sort(let L((l'())(
d d))(if(= d 0)l(L(cons(modulo d 10)l)(quotient d 10))))<)))
```
Ungolfed:
```
(define (number-digit-sort number <)
(foldl (λ (x a) (+ (* a 10) x))
0
(sort (let loop ((acc '()) (number number))
(if (= number 0)
acc
(loop (cons (modulo number 10) acc)
(quotient number 10))))
<)))
```
I tested it with the 100,000th fibonacci number:
```
(number-digit-sort (fibonacci 100000) <)
;==> 1111... basically it's the digits:
; 1 2135 times
; 2 2149 times
; 3 2096 times
; 4 2023 times
; 5 2053 times
; 6 2051 times
; 7 2034 times
; 8 2131 times
; 9 2118 times
```
And the same in opposite order:
```
(number-digit-sort (fibonacci 100000) >)
; ==> 999... and the digest is
; 9 2118 times
; 8 2131 times
; 7 2034 times
; 6 2051 times
; 5 2053 times
; 4 2023 times
; 3 2096 times
; 2 2149 times
; 1 2135 times
; 0 2109 times
```
] |
[Question]
[
**Task:**
Input will consist of some text, with nested `[]` separating some of it into nested groups:
```
abc[d[fgijk]nopq]rst[u[v[[w]]]xy[[[z]]]]
```
Your task is to remove all brackets, and everything wrapped in an odd number of brackets. For example, `a[b]c` would remove the `[]`, and the `b` inside of it. `a[[b]]c`, however, would only remove the brackets (as `b` is wrapped in an even number of brackets). If the string were instead `a[b[c]d]f`, the result would be `acf`, as the `b` and `d` are wrapped in an odd number of brackets, but `c` is not.
The correct output for the input given at the top would be:
```
abcfgijkrstvwz
```
**I/O:**
You can take input as a string, or any reasonable representation of one (like an array of characters). You can output in a similar fashion, with trailing whitespacing being allowed. You can assume all non-bracket characters are lowercase letters, and you can choose whether the brackets are `()`, `[]`, or `{}`.
You can assume the brackets are properly nested (e.g., `[` or `][` won't be given as inputs), and that there is at least one letter in the input.
**Test cases:**
```
abc abc
a[b]c ac
[ab]c c
ab[c] ab
[]abc abc
a[]bc abc
abc[] abc
a[[b]]c abc
a[[[b]]]c ac
a[b][c]d ad
a[b][]c ac
[a[b]c] b
a[b[c]d]f acf
[ab]c[df] c
a[a]a[[a]] aaa
abc[d[fgijk]nopq]rst[u[v[[w]]]xy[[[z]]]] abcfgijkrstvwz
zyx[w]v[ut[s]r[[qp][kj]i]gf][d][][][c][b[][a]] zyxvsia
```
**Other:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) per language wins!
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 7 bytes
```
\W\w*.
```
[Try it online!](https://tio.run/##K0otycxLNPz/PyY8plxLj@v//8Sk5OiU6LT0zKzs2Lz8gsLYouKS6NLosujo8tjY2IrK6OjoKiAjFgA "Retina – Try It Online")
* -7 bytes (50%) thanks to DLosc :)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 bytes
```
e€Ø[œpm2
```
[Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzOij04uyDX6//9/VWVFdHlsWXRpSXRxbFF0dGFBbHR2VmxmbHpabHRKbDQIJsdGJwGpxNhYAA "Jelly – Try It Online") or [see all test cases](https://tio.run/##nZIxbsJAFET7PQVnyG2i0RR/vSyyIYnBYLDLNBwgTerUqRAFUkorB3EusvzFkSKl@2y10u7TzJ/51Xy16lKa/7x@Du/4fqufHtJ4OY2Xj@Hoxq/zcNSXx5TEFzPrUcYJPK2kFA5ix1TMo6DZpAPt002z8T7OF@BdehqmMZZfLoMmUqbqNM9gkgsTZnWZG8@bYovFZ7FskdEkFqf9Qoi07ReEGqbQgInIrfCAuCirJZ9f6jU3zRY7tMBeazl02k@vF/4r7gbo13bfu7476OcWuy0aboB1TSwrllxEImjgyF1pGvyzp0zblHIF "Jelly – Try It Online")
Full program as we use Jelly' smash printing. Uses some tricks from [Jonah's J answer](https://codegolf.stackexchange.com/a/233885/66833), so be sure to upvote that as well!
-2 bytes thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy).
## How it works
```
e€Ø[œpm2 - Main link. Takes a string S on the left e.g. S = "a[b[c]d]e"
Ø[ - Builtin constant; Yield "[]"
€ - Over each character in S:
e - Is it a bracket? e.g. [0,1,0,1,0,1,0,1,0]
œp - Partition S at the truthy indices e.g. [['a'], ['b'], ['c'], ['d'], ['e']]
m2 - Take every second sublist e.g. [['a'], ['c'], ['e']]
Smash-print and return e.g. 'abc'
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 4 bytes
```
øW4Ḟ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiw7hXNOG4niIsIiIsIidhKGIoYylkKGUpZilnKGgoaSkpJyJd)
```
øW # Split on words (Matches sequences of word chars + single non-word chars)
# (Used for dictionary compression algorithm)
4Ḟ # Get every fourth item.
```
Beating Jelly :) -2 thanks to Aaron Miller.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), ~~7~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Vyxal was being too cocky for my liking! :D
```
q\W ë
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVA&code=cVxXIOs&input=ImFbYltjXWRdZiI) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=cVxXIOs&footer=cQ&input=WwoiYWJjIgoiYVtiXWMiCiJbYWJdYyIKImFiW2NdIgoiW11hYmMiCiJhW11iYyIKImFiY1tdIgoiYVtbYl1dYyIKImFbW1tiXV1dYyIKImFbYl1bY11kIgoiYVtiXVtdYyIKIlthW2JdY10iCiJhW2JbY11kXWYiCiJbYWJdY1tkZl0iCiJhW2FdYVtbYV1dIgoiYWJjW2RbZmdpamtdbm9wcV1yc3RbdVt2W1t3XV1deHlbW1t6XV1dXSIKInp5eFt3XXZbdXRbc11yW1txcF1ba2pdaV1nZl1bZF1bXVtdW2NdW2JbXVthXV0iCl0tbVI)
```
q\W ë :Implicit input of string
q :Split on
\W : RegEx /[^a-z0-9]/i
ë :Get every second element, starting with the first
:Implicitly join and output
```
[Answer]
# [J](http://jsoftware.com/), 39 24 23 18 15 bytes
```
#~'_'(*=/\)@I.]
```
[Try it online!](https://tio.run/##XY7BCsJADETvfkXQQ1S0ei4IgiAInryOg7RbV1vBVqtVe/DX66pVwYRAkjcZklRNT62MfFHpyVB8V31PJov5tGrddaXt7miw7IxnHqtOY222qVjRACEMI1ptvHcaGKvS9/9gzUJjN3GyO@an4lJ@ZaFBhBfgPs0OdBhnFMCF5PUGoHQNVX5RG5a3a5HHwcfJje6mwPmEnEfgkBG7hDE3loiIZxq6r4ig9qse "J – Try It Online")
*-3 bytes and new approach thanks to FrownyFrog!*
## old answer, 39 24 23 18 bytes
```
(+:~:/\)@e.&'[]'#]
```
[Try it online!](https://tio.run/##XY7NCsJADITvPkVQMIpaPS8IguDJk9dxDu3W1bbgX7VqD756XbUqmBBI8k2GpFUzUCdjIyp9GYnxNQhkupjPqk7P3M1w2Z2sgraC2mLVbazsZidONEQEy5hOG@@dhtapDMwfrFlk3TpJs2N@Ki7lVxZZxHgBbnf7Az3GGQVwIXm9ASh9Q5Vf1Ibl7VrkSfhx8qO/KXA@IecROOyJLGXCtSNi4pmW/isirP2qBw "J – Try It Online")
*Saved around 10 bytes after reading [dingledooper's answer](https://codegolf.stackexchange.com/a/233887/15469) and realizing I didn't have distinguish between open and close brackets.*
*-6 thanks to some damn clever tricks by Bubbler!*
Consider `'a[b[c]d]f'`:
* `e.&'[]'` Is the input a bracket? Returns a boolean mask:
```
0 1 0 1 0 1 0 1 0
```
* `(+:~:/\)@` Transform that mask first by a scan using a not equal reduction. Only items with odd numbers of brackets to their left (including themselves) become 1. Then "not-or" `+:` that result with the original mask:
```
1 0 0 0 1 0 0 0 1
```
* `#]` Use that to filter the original input:
```
acf
```
[Answer]
# [Python 3](https://docs.python.org/3/), 45 bytes
Input is taken from STDIN, and outputs a list of characters, each on its own line.
```
n=1
for c in input():n^=c<'a'or n>0==print(c)
```
[Try it online!](https://tio.run/##JY1BjoMwFEP3OQViU9hNNbtqmItYrhQS0qYdhZSGFnp55odI0Zfl2M9xTdcxfG/vq/8bquOpGpbBNHVdb6E7KjdOlal8kBfn1LSncO7Mz0EfxA@/X10XJx9SY9qtiFaK7aZ7ozR6GgWdr@5hqMDiM9/egKIllP@xC5aWZG0ROyBzcjQzLF1BwrrsaUpVkzvPwl387c4wxgenZ8KMF/AW7rLKwEcE1WddxHphTnhyAh6RuN/oeXGElUnkfRlj5v4D "Python 3 – Try It Online")
The main observation is that whether or not a letter is wrapped in an odd number of brackets can be solely determined by taking the parity of the number of brackets preceding that letter.
### [Python 3](https://docs.python.org/3/), 48 bytes
Same as above, but outputs the entire string on one line.
```
n=1
for c in input():n^=not'`'<c!=print(end=c*n)
```
[Try it online!](https://tio.run/##JY3BboMwEETv/grKJdBb1FtUvmQ0VY2NEyeVcYhJID9P11iyVrPjnTdxTZcxfG2vi/8bquOpGpbBNHVdb6E7KjdOlal8kBfn1LSn8NOFMR1@D9/mo4uTD6kZgu3MZ2i3sraSbTfdG6XR0yjoPHUPQwUWn3n2BhQtR/kfu2BJya0tYgdkTj7NDEtXkLAue5oS1eTOs3Bnf70xjPHO6ZEw4wm8hLusUvAWQfVeF7GemBMenIB7JG5Xep4dYaUSuV/KmLn/ "Python 3 – Try It Online")
### [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 49 bytes
A `lambda`-based solution which is just slightly longer, in comparison:
```
lambda L,n=1:[c for c in L if(n:=n^(b:=c<'a'))>b]
```
[Try it online!](https://tio.run/##nZJNbsMgEIX3PgW72FJUKeqmskpPkBtMp9KAS0LiYGJj5@fy7hBXqtTdhA0I5tMb3pt4S/suvL7Ffnb6c27pZBpS23XQmxqscl2vrPJBbZV3Zah1@CpNre37ilZV9WFwvux9@602dcFVca26MUWl1Yli2fohrfPtmMrqZYit570qVOx9SKUr@aVSWj@QaiZjlXQxUxAYlJJkCyA5xmIGLIqbLADlv1v@hs9xxgI@pcdmCm355TIoImmJjv1sRHLNgkm7zInnSZHZYrJYbhGdSMwt8wWNQ9l8ASGbSSjAiOgReANu5w9HDF08Yz8kGGECuHAs1xvnc@cD/gvuAXDpdLkX99uViycYEwzYA5wjwvGAHncOoWHDIWfFbuBfe8xMg6cf "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
```
StringSplit[#,"["|"]",All][[;;;;2]]<>""&
```
[Try it online!](https://tio.run/##PY7JEoIwEETvfkas8oQXry6lf2AVx64@DGAwiogY9@XXcUAgl7z0dLrnIH67OYh3sVR2XoW@dHkaFpnzGAYG5m1oglWWEZjqmZCzhTGjaq0@tYwXdjnk6BvGkn9fAyNRbAK9ELEBSAsSIWajsPewA3Wzw5rZh@inpOcusg5nq9YG2r4KiW0nQg0T/l@RDmBTt9szPxYnlmePC67ATcvuD219KjTe5@Ou6hUXjzNL4FQQ@x0dU0skugTqpbSYTfrgU/0A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~33~~ 32 bytes
*-1 byte thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy).*
```
function(s)gsub("\\W\\w*.","",s)
```
[Try it online!](https://tio.run/##pZLNDoIwEITvPoWpFzDGN/A5PAx72NKUoAkq5Ud5edwiYvTW2lMP/Tq7M1OP9jDatsqb8lIlLi1cqxOVZccs67d7tVNq59LRJop1rtLNOvQItvI0NEXwPMHgKPglrJFThLCehClq62Vn@ofWOegPbTE83LQP7fFQnpeoxXMTqM1mgSPmnnviWxZsmp6F/dBkQ1e2S0NhbKD27BeTGM4UBjPzuyYGtihPZ6ou1xvVrkGLDuglwPtDkhzk8vu3YBMjr7t@8B8Nj7sgHdoGjmrgdiWcT1RSYQlGQoFPVVyir1EF61zJ4xM "R – Try It Online")
Simple regex-based solution.
[Answer]
# [Zsh](https://www.zsh.org/), 19 bytes
```
<<<${(e)1//[][]/\`}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhabbWxsVKo1UjUN9fWjY6Nj9WMSaiEyUAU3daKVEpOSo1Oi09Izs7Jj8_ILCmOLikuiS6PLoqPLY2NjKyqjo6OrgIxYpVioJgA)
Replaces `[` and `]` with ```, and `(e)`xpands the backtick substitutions. For example, `A[[]BCD]` becomes
```
A```BCD`
```
The contents of backticks when in strings are evaluated as commands. Since there are no commands made only of uppercase letters, the bits in backticks do nothing and aren't included in the output.
If we can't assume input is uppercase, the same method can be adapted to force it to uppercase:
## [Zsh](https://www.zsh.org/), 26 bytes
```
<<<${(L)${(eU)1//[][]/\`}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuha7bGxsVKo1fDSBRGqopqG-fnRsdKx-TEJtLUQBVN1NnWilxKTk6JTotPTMrOzYvPyCwtii4pLo0uiy6Ojy2NjYisro6OgqICNWKRaqCQA)
---
## [Zsh](https://www.zsh.org/), 21 bytes
```
<<<${1//[][][a-z]#?/}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjU7SSrm5qRUlqXkpqSnpOfpJS7IKlpSVpuhZbbWxsVKoN9fWjY4EwUbcqVtlevxYiB1VyUydaKTEpOTolOi09Mys7Ni-_oDC2qLgkujS6LDq6PDY2tqIyOjq6CsiIhZsLAA)
A less interesting alternative that uses the equivalent of the `\W\w*.` regex method used by some other answers: `[][]` matches any square bracket, then `[a-z]` any letter (`#` means "0 or more times"), then `?` matches any single character.
Must be run with `--extendedglob` to enable the `#` pattern feature.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~96~~ ~~89~~ 71 bytes
-25(!) bytes thanks to [Daniel Cristofani](https://codegolf.stackexchange.com/users/10650/daniel-cristofani)
Uses `()` as brackets.
```
,[[>+>+<<-]+++++[>--------<-]>[-[[-]>>[<]<[.<<]]]>[>-[++>]<[<]]>[-]<<,]
```
[Try it online!](https://tio.run/##LYhbCoNQDAW3k0OMKwjZSMiHDyxWEGtrtd38bS50zsdwpt@7eZ2OYSmlcTc2VpXgipv8yWIu7ilzDfVWNSKbiTNbBq1PQrWJUr6fi0686XjREzvRYwMtd8y4TaARVDeA@lQH/AA "brainfuck – Try It Online")
~~This is the most complex brainfuck I've ever written and I had quite a few troubles with getting the pointer back to a common position after branches, so I suspect there is some room for optimization.~~
With some comments:
```
tape layout: _; input1; input2; parity flag
,[ while loop: runs as long as there is input
[>+>+<<-] make two copies of the input to the right
+++++[>--------<-]> subtract 40 from the first copy
[-[ if the result is not 0 or 1:
[-] set first copy to 0
>>[<]<[.<<] print second copy is not set
pointer is now at _
]]
>[ if the pointer is at input1
>-[++>]<[<] toggle the parity flag
]
>[-]<< set second copy to 0
,]
```
[Try it online!](https://tio.run/##hZLfboMgFMbvfYpzCbEu7bKrjvAixjTUomW1wOAw517egZrFpH92SDwh8fd93wGOTijdhPoyjvC0UFgJnRhMwD0c3kFpG3C39Nd3sMIpHKDpRJttymdK/Vl1UcoYuwcXtAfh4063qeNZOgnKz7IZQMlznjNWVHeEruIiAXsDtbFKejBN4mcU0Ewbp9pz0slTlbxYKgryPx0fjuhEjfC2hcaZ6wQ2ynlMykNKUTyeSM2uTvrQYYquDcIWjIPdPks/lHfDL9YSV04p9HZiOC9ZxcoXxm5Z65TGSNZGn2ZsMY1iGfxT1kRYuhnpQSAcIlNV8cOf3Noy5IqO5PwE5rxFmec8Jr6TF03bxguf@NUjia63PlOMomLs8XGtB5/Oa1ON48/wTXr6RQISTx0hn5aSywdVtG0oOVGSVk3JMTZB6S8 "brainfuck – Try It Online")
[Answer]
# [AutoHotKey](https://www.autohotkey.com), 44 bytes
```
#UseHook
[::
]::
A:=not A
BlockInput,%A%
```
You need execute it as Administrator permission. And you can always back to normal input status with `Ctrl-Alt-Delete` if you are in trouble.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 10 bytes
```
@UW:a^`\W`
```
[Try it online!](https://tio.run/##K8gs@P/fITTcKjEuISY84f///4lJydEp0WnpmVnZsXn5BYWxRcUl0aXRZdHR5bGxsRWV0dHRVUBGLAA "Pip – Try It Online")
### Explanation
The key observation is that the two types of brackets don't need to be distinguished...
```
a First command-line argument
^`\W` Split on this regex (any non-word character, i.e. a bracket)
UW: Unweave (the : is needed for precedence reasons, unfortunately)
@ Take the first of the unweave results
```
Unweave turns a list like `[1 2 3 4 5]` into `[[1 3 5] [2 4]]`, so `@UW` applied to the split results gives every other result, starting with the first.
[Answer]
# JavaScript, ~~27~~ 26 bytes
Using [pajonk's RegEx replacement approach](https://codegolf.stackexchange.com/a/233899/58974); be sure to `+1` them if you're `+1`ing this.
```
s=>s.replace(/\W\w*./g,``)
```
[Try it online!](https://tio.run/##PY5LkoIwGIT3HsMVTDl4Ar3GLNquMiSEAhkSCeLj8vgTI6t81enH36pJBT00fvztnalme5jD4RiKofKd0lW2P/2d7j/Fvt6dz/msXR9cVxWdqzNstqrU2508KBkBKoEqoRkVrh4mKDX4USSW7IjMtU3SZuVv97KSkku9oV03YWz6UZQyRX6nDGzdtBf2zl85hBE3TMBdxh5PWX0JRO/r@RB1wm1E4ABcPXFp2bC2hJEjsBwlw4ztGxb/ymc2z@c3)
## Original, 44 bytes
Adaptation of [my Japt solution](https://codegolf.stackexchange.com/a/233906/58974).
```
s=>s.split(/\W/).filter((_,y)=>++y%2).join``
```
[Try it online!](https://tio.run/##PY5NbsMgFIT3OUakSqCkROreuUYXr6MGg7FwXEMMceNc3sWUeMWnYX5eJycZ1Gh9fB@cbhZTLaE6BxF8byM7fX2euDC2j83I2Pdx5tX5cJjfPrjonB0ul0W5Ibi@Eb1rGe32slb7Y3qoRgaSBWRNClnB5kGBWhH@lRQrdsqMrS2l9cav7nWlJNd6DbNtkjblRyKVSeA1pcm0trticP6GMUS600T0m8Yec1p9Jsje5/xI6kT3SAEj0c2Drh0sWgPS6Qhaj0rDyO07iB/pmeF8@QM)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~55~~ 52 bytes
-3 thanks to dingledooper.
Scans through the string and increments a even-starting depth counter, printing any characters on an even depth: as the input is guaranteed to be balanced, the starting depth will always be an even number. Uses Jonah's trick of only scanning for brackets regardless of direction.
```
l;f(char*s){for(;*s;s++)*s>96?l%2||putchar(*s):l++;}
```
[Try it online!](https://tio.run/##dVJNT8MwDL33V1hFk9pscOCABGHjD0zcOFk@pAnZAmXdmrTAYL99OOu0tSBycPz88fwSWV8utN7vS2kzvVS18PmXrepMCi/9eJwLP7u9eShH19/f6ybEioxL7srxWO72F26ly8Y8w70PxlVXy1kyCJWuiLHErQK8KbfK2sqZHL4SgMgEwiNNIwJIVaHTydHFgk4AVQ@oAjWdMjTooR4oNNI5w3Q9CjxgGkxjVjPA/flRTY8tSjBkB/rQ2F6FIh6iiPpyDNqFe3mlVbXeUO0DNtgivrOQj09WtGXnVL/9/OBMi01ATzXiZk34@kKOFpbQsDiMglkI9aY8Ps3n7OwmINSvX@XrYDu36Kz@/zp/jTk3d23anomUOjYdXsZvat@3McLyW@/UX10iRNPIhHHcsTD1E2imSoIIEni9fJamebcffNY1743N0pGH6QyYWYRcdimbicDLKYeFkPll1ZQGimfAkac89jTHul2y2/8A "C (gcc) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
```
f(h:t)=[h|h>']',even$sum[1|b<-t,b<'a']]++f t
f x=x
```
[Try it online!](https://tio.run/##DcZBDsIgEAXQvaeYNE3QtC7cmuJFfmYBCoJtsRZa0fTu6Fs9p2JvhqEUu3fndJBwm7sIFq1ZTajjMuK06e6YWt0JJZibxlLaWcoyl1H5QJKm2YdENVmqlL7iBnv3j57Dc3rxHBMWrMCbmfMHwPcfrsoP "Haskell – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `K`, 24 bytes
Thanks to [exedraj](https://codegolf.stackexchange.com/users/78850/exedraj), [emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a) and [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino) for guiding me through my Vyxal journey's beginning.
```
ƛ91≠*;ƛ93≠*;'[¥¬|¥¬£];C∑
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%C6%9B91%E2%89%A0*%3B%C6%9B93%E2%89%A0*%3B%27%5B%C2%A5%C2%AC%7C%C2%A5%C2%AC%C2%A3%5D%3BC%E2%88%91&inputs=zyx%5Bw%5Dv%5But%5Bs%5Dr%5B%5Bqp%5D%5Bkj%5Di%5Dgf%5D%5Bd%5D%5B%5D%5B%5D%5Bc%5D%5Bb%5B%5D%5Ba%5D%5D&header=&footer=)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 46 bytes
```
x=>[...x].filter(x=>(z^=b=x>'z')>b,z=1).join``
```
[Try it online!](https://tio.run/##DchhCsIgGADQ46hQQgfQi0QxdTo08Vtqy/zw7LZ/jxfUoYrJfq/XBKudTswm5J1z3h7c@VhtpmfQ/hRaNEk6YVJfurgxHsCnZZkGUoFoeYSNOkqUNrii23x4jQT7e@RS8YMH4neM0X6I2E8Mwtj8Aw "JavaScript (Node.js) – Try It Online")
Port of dingledooper's answer thanks to dingledooper.
# [JavaScript (Node.js)](https://nodejs.org), 51 bytes
```
x=>x.replace(/[{}]([^{}]*)/g,(a,b)=>i++%2?b:'',i=0)
```
[Try it online!](https://tio.run/##DcbRDoIgFADQr2lAkrYe27APcbUBAsOcEJhRd/fbyZezM8lNZp18XE9LGE21ohbRlzaZOEttaDcA3unw2D2yznEquWKi901zuNzUlRDuxZlVHZYcZtPOwVFLiVQaRrDOT09cQnxhyiu8YQP4IGL5AsBvDxLG6h8 "JavaScript (Node.js) – Try It Online")
This makes use of the fact that after an even amount of open or close brackets, the bit of the string up until the next bracket should be kept. After an odd amount, it shouldn't. For example, on the demo input string, the following happens:
```
Full: abc[d[fgijk]nopq]rst[u[v[[w]]]xy[[[z]]]]
Valid: abc [fgijk ]rst [v [w ] [ [z ] ]
Invalid: [d ]nopq [u [ ] ]xy [ ] ]
```
We just smoosh the valid half together, remove all the brackets, and we have our answer!
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 22 bytes
```
{((~≠\⍵∊'[]')/⍵)~'[]'}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/WkOj7lHngphHvVsfdXSpR8eqa@oD2Zp1IGbt//8A "APL (Dyalog Classic) – Try It Online")
**Explained**
```
{ } ⍝ Monadic function, takes string on left
⍵∊'[]') ⍝ Boolean mask for characters which are braces
((~≠\ ⍝ Scan the mask by not-equal and negate (Mask for characters that is needed to kept with braces)
/⍵) ⍝ Filter the input using the scanned mask
~'[]' ⍝ Remove the braces
```
[Try it online!](https://tio.run/##bZBBTsMwEEX3OcXfNZGIuAMLdt3AElhMnUlsxbVDPKGqEF0DUo@AxCW4UC4S7AYkimJpFrZm3vse6mxZ7cn6plSWQjBqmp6xcF5ijccPrL2jyijUg1NivLuAUMsBQXrjGngHy7Vk89B4/Bpf31d3D6viLytxrry3TA5bCi1q30Np6kkJ9wE7bZQG9YxNfOKQIc8P49vn/UKuxLpVESSaZ9hmD@el5MeBLMhVcNyQMPL1gko0CUyIPVxxBfFouRPsjOgfeZGd@S7jn4oz@7WxEXXyG9cNgiGkTaR7iMFcxKZc2f/kh7SXX8gNb/0Tn4Zm7TR9Aw "APL (Dyalog Classic) – Try It Online")
# [APL (Dyalog Classic)](https://www.dyalog.com/), 24 bytes
```
{((~2|+\⍵∊'[]')/⍵)~'[]'}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/WkOjzqhGO@ZR79ZHHV3q0bHqmvpAtmYdiFn7/z8A "APL (Dyalog Classic) – Try It Online")
Monadic function, takes the string on right
Approaches in array oriented languages are really neat
[Answer]
# [jq](https://stedolan.github.io/jq/), 19 bytes
```
gsub("\\W\\w*.";"")
```
Uses the regular expression from [tsh's answer](https://codegolf.stackexchange.com/a/233895/90812).
[Try it online!](https://tio.run/##yyr8/z@9uDRJQykmJjwmplxLT8laSUnz/3@lxKTk6JTotPTMrOzYvPyCwtii4pLo0uiy6Ojy2NjYisro6OgqICNWCQA "jq – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
FS¿№βιF¬﹪Lυ²ι⊞υι
```
[Try it online!](https://tio.run/##HYs7DsIwEAWvsuVaCg1tSiokQJEoVy4Sx3EMljc46/C5vDF0T29mzNwnw30oZeIEeIxLlqskHx0qBX4CPHCOgkMDvh5/6cKCZx5zYDzZ6GTGrBrYq8q7Wgp61YINq4UurxX@0raUfjA00uT87a4jLw@dVqFMG9FTa/16E9GnDl12W/gC "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Prints lowercase letters unless an odd number of other characters have been recorded.
Alternative solution, also 16 bytes:
```
⪫Φ⪪⪫⪪S]¦[¦[¬﹪κ²ω
```
[Try it online!](https://tio.run/##RYqxCsIwEEB/pXS6QF1c3QsKitDxuCGmWmNDLsZLW/35GFFweTwez1x1NKxdzsdovcCOrYfWOjlH6IKzv/LVrQ9JOinjAKqpaqo/xD8PLLDnPjmGsanWSpU2K7XJWZ8M9ngZ7G0kz@FO8SGYcEKciWh5IuKrCOXV5N4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Replaces `]`s with `[`s, then splits on `[`s and outputs alternate elements.
[Answer]
# [Haskell](https://www.haskell.org/), ~~66~~ 61 bytes
```
f(x,y)c=(x-sum[x+x|c>'z'],y++[c|c<'{',x>0])
snd.foldl f(1,"")
```
[Try it online!](https://tio.run/##BcFBDsIgEADAu69oiAkQsKl36UeaHnCBlgirEU220r4dZ1ZbHj6l1oIgvUkwgi7lmydStMPIf3zWm1IT7HDjlWsah1meFlPQ9eGZXOqCuGrGZMs2onm9I37OC7N3qA7RYfU@H/6IkbU/ "Haskell – Try It Online")
Haskell doesn't really do regex.
[Answer]
# [Python 3](https://docs.python.org/3/), 40 bytes (using regex)
```
lambda s:re.sub("\W\w*.","",s)
import re
```
[Try it online!](https://tio.run/##JY3BjoMwDETv@YooJ1ihSqu9VWJ/Yw/Gh4SQNi0NaRJK6c@zNlys8Xj8Jq7lOoWfzbXdNuqHsVrmcxpOeTaV6v665eukGqWaXAv/iFMqMg3bcvXjIL/PQo4@DLKVPsS5VLWQMflQKnYbqdpfqRrp9rWuN216ocFgL0Dz1AZ6FICHjzxND0iaQnyHXeDxRVl7iB3AHI4yw6I7kGAdexrpVSPuPAvu4m93DFN8YsoFZngBLMR9r1TwIYHis77JesFcIGMCeEaE@w09XhyCpUrgfipD5v4D "Python 3 – Try It Online")
## Version without lambda, 44 bytes
```
import re
print(re.sub("\W\w*.","",input()))
```
[Try it online!](https://tio.run/##LY7BboMwEETv/gprT1ChSFFvkehv9LDZg8EmcUINMSZAqn473YVcVuPZnTful3Ttwudad9aVEQBW/9N3MenoVB99SFl0h2GsMjh/n6ePAxQAhQ/9mLI8z1cOqNYHp0vNyrqGc8Zm@UnpS9tVptWyVeymMYb9oaarb50@8s07@uYpvTeKW2govzQU2gVbAvDOza7O5JvFL2wBOEnXX76aqlYGK6oVGpmmwpoU0u6TzKpGYs1HssdN0J7iW7uLDSAcORWGpWZHom3EM8RRQ7TxLDYXf7tT6PoHxSHhiE/EibnzwgUvFqRey8zWE8eEA0XER094v5GnS0NouRKln8tIuP8 "Python 3 – Try It Online")
Thanks to @emanresu A for the lambda version
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 12 bytes
```
{x&=\x>:93}#
```
[Try it online!](https://ngn.bitbucket.io/k#eJydU8FugzAMvfsrUDdNmzRph50GWn/Es9QElIp2WlugFFp13z7bUAbdZS6HiDh+ec+OX4hPzcP7RzOP317PdwBVfLrH9ruIQxRFTbLYrJPHRXD5Z9IkbVI80RkqnDmfzhJdSbfoSQP9Hp3un2eXc48pKaA/pz8X0FXAp0jTDOagK5DGJsyihLkyCWWj0JU80Usi0A85gqKgWWFUBWaBxpWgI+Z1pOKc+1WbYVjmqzV9bbY7KsoK91gjHlhf07LQI//0BWkeZ9SHYwc/tg0n1rivsKQCcbclXK8op2UgzFg8Sk0skXpiBtRlLuQAL8BXRtaPMaBdsOJS0LYYYUwmDbaSedBJMcOkNroNJ3N3E5+O5y24boYtuO7pZGBNdBn0VrCplBdXv5hgHgZPmcgCDLYz4KQjF2Ma2JyD/1p3gpt4GGz27a7oHQw/AARD6g==)
Takes advantage of the input restrictions, i.e. only having to deal with lower cased characters and `[]` as the brackets.
* `{...}#` set up a filter, removing items from the (implicit) input that do not match the criteria in `{...}`
+ `x>:93` determine which characters in the input are letters, updating `x` inplace (ASCII codes for `[]` are `91 93`, `a..z` are `97..122`)
+ `=\` do an equals-scan over this (characters at an even level of nesting become 1, otherwise are 0)
+ `x&` take the logical and, essentially asking "is this a letter AND is it at even level of nesting?"
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 37 bytes
```
1s>ir['aL:[pfpl!sp0]p![pl[p:o0]pp0]p]
```
[Try it online!](https://tio.run/##Fce7EYAgFATAWohMNSWwAju4uQB1cFBGnuC/ecRs1z85N6l1EZXpNMSKV0lqioJ4iA6Ff5mz6QeMsJObF65BNsa048AJXCTvB8BbwA8 "Ly – Try It Online")
This code takes advantage of the input constraints that the characters will only come from the set of characters `a-z` and `[` or `]`. Which means checking to see if the codepoint is less than the codepoint for `a` is sufficient to identify the brackets. It also relies on the constraint that only valid sequences of open and close brackets will given. That allows each bracket to be a "on/off" toggle for the print setting, since it doesn't matter whether it's an open or close, it will always change the even/odd state of the accumulated groupings.
```
1s -- Set "true" as initial print boolean state
> -- Change to a clean stack
ir -- Read all input as codepoints, reverse stack
[ ] -- Loop to process each input codepoint
'aL -- Compare top of stack to "a"
:[p 0]p -- if/then, true is codepoint is "[" or "]"
fp -- Pull codepoint forward and delete
l!sp -- Flip "on/off" boolean print state
![p 0]p -- if/then, true if codepoint is "a-z"
l -- Load print boolean state
[p 0]p -- if/then, true if we should print the character
:o -- Duplicate the codepoint and print one copy
p -- Delete the current codepoint from the stack
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 439 bytes
```
,[>[-]>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]>[-]<<<<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<[-<->][-]>[-]<<[->+>+<<]>>[-<<+>>][-]+<[[-]>[-]<]>[[-]>[-]+<<<<<<[->>>>>>[-]<<<<<<]>>>>>>[-<<<<<<+>>>>>>]<<<<+>>>]<<++>[-]+<[[-]>[-]<]>[[-]>[-]+<<<<<[->>>>>[-]<<<<<]>>>>>[-<<<<<+>>>>>]<<<+>>]<[-]+<[[-]>[-]<]>[[-]>[-]>[-]<<<<<[->>>>+>+<<<<<]>>>>>[-<<<<<+>>>>>][-]+<[[-]>[-]<]>[[-]<<<<.>>>>]<<]<<,]
```
[Try it online!](https://tio.run/##tY/dDoIwDIUfqOATNLxIcy4Ag0ESoyj@vfxsKV2MIdy5sXG6nn3tmrHuT93UDomlBPPWXv0OO9OVCglJ/xtRgudmtDpVZBreiUkyCc1yWSHb1Txb4TY1WY5YwqF7tM@c8f4@P0DEHpKHCK3C@9uALsxA4htIGUfe/zooX3bW8v5V1BrC0rulkH4FUnq/nvLAXaabXDGKXM6Q4Ygehw6yh9hsIY3@auAD "brainfuck – Try It Online")
---
Generated using a self-written yet poorly optimizing brainfuck compiler still under development. Its *brainfuck macro assembler* source code without the prelude can be seen below. I am certain a carefully layed out tape together with hand-written brainfuck would dramatically improve this byte count.
```
(macro ppcg233884 () (
; define parity cell
(let:nve $parity 0 (
; read in character stream
(let:nve $char 0 (
(getc:w $char)
(while:re $char (
; check if it is a bracket and update parity
(let:nve $wasbracket 0 (
(let:nve $bracket 91 (
; '['
(sub:ra $char $bracket)
(ifnot:re $bracket (
(not:a $parity)
(inc:a $wasbracket)))
; ']'
(inc:a $bracket)
(inc:a $bracket)
(ifnot:ze $bracket (
(not:a $parity)
(inc:a $wasbracket)))))
; only print on even parity when it was not a bracket
(ifnot:ze $wasbracket (
(ifnot:re $parity (
(putc:r $char)))))))
(getc:w $char)))))))))
(macro main () (
(ppcg233884)))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Aм¡ιн˜
```
I/O as a list of characters. If a nested list output is allowed, the trailing `˜` could be removed.
[Try it online](https://tio.run/##yy9OTMpM/f/f8cKeQwvP7byw9/Sc//@jlRKVdJSSgDgZiKOBOAVKpwFxOhBnAnEWEGcDcSwQ5wFxPhAXAHEhVKwIiIuBuASqtxRKl0FpEC6HqoXhCiCuRJIH4So0NbFKsQA) or [verify all test cases](https://tio.run/##PY49DoJAFISvQrb2DvS2lpMpdlkxYCK/ongAa2Nt4zFMtJHSxHAGL4KPdaWbzJuZ72WVNslyaNpQBZ/jOVBhu@hOQ3ft78/r@9Y/XpdhPhugtInULFAahk5Ae6ENIjqHU4ZemAj8OVLzcTjNaU3adtL/7ZHim@O8ZTwxYWN/0ZQxTf5RFvEqSdfcZHnBsqqxRQPsBLZvhXoQ4bKHdi9ug22NiiVQ5MQ6ZcJVTFh5AuNTAqZb5xc).
**Explanation:**
```
A # Push the lowercase alphabet
м # Remove all these letters from the (implicit) input-list
¡ # Split the (implicit) input-list on the remaining characters ["[","]"]
ι # Uninterleave this list of lists into two parts
н # Only leave the first part of sublists
˜ # Flatten this nested list into a single list of characters
# (after which it is output implicitly as result)
```
(Could also work for mixed cased letters by replacing `A` with `á`.)
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 19 bytes
Thanks to [Aaron Miller](https://codegolf.stackexchange.com/users/101522/aaron-miller) for this two bytes shorter version.
```
äh:s/]/[/g
òf[df[òx
```
[Try it online!](https://tio.run/##FcXLDYAgFATAu81wt5XNHlQEPzFBQQTrsQJaoLCnZg4TReoztV5RQdmmFgNtUEsSwbi5kHnnhIsRZ4DnAeyOWBfOtIbQxG8g@q@OfAE "V (vim) – Try It Online")
---
# [V (vim)](https://github.com/DJMcMayhem/V), 21 bytes
```
xPP:s/]/[/g
òf[df[ò0x
```
[Try it online!](https://tio.run/##FcWxDYAgFAXA3mWwdgr6l1eoCFFjgoIIjsUKDvbVXHFJJGvdBUUF5ZqnWhiLp7ZZBNPmY@FdMi4mnBGBB7B7Yl0401nCEL@RGL568gU "V (vim) – Try It Online")
## Explanation
```
xPP " Duplicate initial character,
" since `f[` would else skip it.
" If the input is empty, error out.
:s/]/[/g " Unify all brackets to `[`.
ò " As long as necessary,
f[ " keep everything until even `[` and
df[ " discard everything until odd `[`.
ò " End the loop.
0x " Remove the duplicate character.
```
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 55 bytes
```
f(h:t)=[h|h>']',0<foldl(*)1[-1|b<-t,b<'a']]++f t
f[]=[]
```
[Try it online!](https://tio.run/##Fci7DsIgFADQvV9BGhPAFmNXAu5OupM78AxEig3SwaT/jvGMx@61ftmmX/bTeyCRNypVPOINA56vIryzy@RMF8WWwwjWZiOwxgDTFFAbggKpoK86FcQ5elafd@cv9wcidPiv3Goq7RRGbaxypbiivF/BQ0pj/wE "Curry (PAKCS) – Try It Online")
This is based on [Lynn's Haskell answer](https://codegolf.stackexchange.com/a/234976). There are two difficulties adapting it to Curry however. The first is that curry doesn't have falling through so the case `f x=x` needs to be replaced\* with `f[]=[]` for an extra byte.
The next is that curry doesn't have `sum` so we need to replace it with some sort of fold. The most efficient way to do this is to actually make a `product` instead of a `sum` since it is way cheaper to check if something is positive than whether it is even.
\*: This doesn't actually behave like I would expect. I'm not a curry expert. However in both the expected behavior and the actual behavior it fails so...
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~66~~ 63 bytes
```
f(char*s){for(char*z=s,n=0;*z=*s++;*z-91&&*z-93?n%2||++z:++n);}
```
[Try it online!](https://tio.run/##rVJNT4NAEL3zK1aSNlDaxOpJa2uaqImJBxOP4xwW6NbtB1CW0pZa/3qdpR4AT1vlwD7YeW/fzrygNw2C41E4wQdPO8rdizg94WKoutHwckCgozyP1t5Nv93Wy/V91Lr6/PS84tbzIndwOOaxDFk2UVnJZR3ZZScQu2xvnbC/FqCydDGJHOl6fRxYjD6DZOfQTpdJl34IjTWQgjkXenuZnLZj17UYS1IZZcKx717Hb2@PDyNGT0uxrxG93yObVHQl8ScLNanWP42fXxr17GJYYf0cMrAOlrXkMnJc8l3eyOZ@QDWmT0nTVn5EwEdzGZtXNYCfpVGz4UOAZ9jwqzbwnI786gf@g4gfAP7dCY3GuK@/RbSKoUx9vDoiNJ3QzInNw6bGGZepx0xn1bSvtl@3oW@CwrQdohl3CIWZk3rcgSONhqORhs05b6QsBDGVszlGcbLCVGWwhhxgQxPf7mj0BYHGEZpWcqg63xQVvWK3JWYO6wwUpgCrBGE@Q4lTgRDS@EDHgDqIVeOalitZGjscvwE "C (gcc) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 53 bytes
```
s?(x:r)|x<'a'=(1-s)?r|s>0=s?r|s<1=x:s?r;_?q=q;f=(0?)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/n6vYXqPCqkizpsJGPVHdVsNQt1jTvqim2M7AthhE2xjaVlgBWdbx9oW2hdZpthoG9pr/cxMz8xRsFTLzSlKLEpNLFNL@AwA "Haskell – Try It Online")
] |
[Question]
[
Think of cleave as the conceptual inverse of map. If map applies a function to each number in a list...
`map([1, 2, 3], x -> x * 5)` -> `[5, 10, 15]`
then cleave applies each function in a list to a number.
`cleave(5, [x -> x * 2, x -> x - 1, x -> x * x])` -> `[10, 4, 25]`
More formally, given:
* \$n\$, an integer, and
* \$L\$, a list of [black box functions](https://codegolf.meta.stackexchange.com/questions/1324/standard-definitions-of-terms-within-specifications/13706#13706) with type signature `integer -> integer` or equivalent
Apply each function in \$L\$ to \$n\$, collecting the results in a list the same length as \$L\$. (It can be the same list if you want.)
## Challenge
Implement the cleave function in your language of choice.
## Format
You must accept an integer and a list of [black box functions](https://codegolf.meta.stackexchange.com/questions/1324/standard-definitions-of-terms-within-specifications/13706#13706) and output a list of integers in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Argument order doesn't matter. The list of functions is flexible. You may accept:
* A list of black box functions (including a list of function pointers, etc.).
* A variable number of black box functions as parameters (varargs).
* A number indicating how many functions to accept.
* Etc.
## Rules
* Builtins are allowed, but please consider adding a less trivial answer so we can see how cleave might be implemented in your language.
* Explaining your answer(s) is encouraged!
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes (in each language) wins.
## Test cases
Note: for simplicity, instead of showing functions like `x -> 10 * x`, I will show them like `10x`. Imagine there is an \$f(x) =\$ in front of each of these.
```
3, [] -> []
42, [x] -> [42]
0, [10x, x/2, abs(x), -x] -> [0, 0, 0, 0]
8, [10x, x/2, abs(x), -x] -> [80, 4, 8, -8]
-5, [abs(x), -x, x+10] -> [5, 5, 5]
5, [abs(x), -x, x+10] -> [5, -5, 15]
10, [x*x, x/10, x*x + 2x + 1, 13, x%3 - 3] -> [100, 1, 121, 13, -2]
950, [x*x, x/10, x*x + 2x + 1, 13, x%3 - 3] -> [902500, 95, 904401, 13, -1]
```
[Answer]
# Haskell, 11 bytes
`map.flip($)`
(If using Stack, this can be dropped to 7 bytes: `map.(&)`.)
[Answer]
# [Python 3](https://docs.python.org/3/), 27 bytes
```
lambda L,n:[g(n)for g in L]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUcFHJ88qOl0jTzMtv0ghXSEzT8En9n9OsYKtQjRURYWVgqGBVoWOAoJfoa9vhMzPTazQACrQrdBEFtWtiOXKAxpkwVVQlJlXopGmkVOso5CnqfkfAA "Python 3 – Try It Online")
Anonymous function that takes the list of functions and a number as arguments.
[Answer]
# JavaScript, 20 bytes
```
a=>n=>a.map(f=>f(n))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7P1i5RLzexQCPN1i5NI09T839yfl5xfk6qXk5@ukaaRnSFgq2dQoWCloKRjgKUratgCGdrKVTEamqYAvUBAA) or [run all test cases](https://tio.run/##rZLBbsMgDIbvewpfJkELiU2IlBySN9gTVDnQrllbtUnVVBNvn0IXpmpUuzTIWJYx/4eBg/k2w@ayP19l139ux7Yau6o2zpKTObO2qlvWcT5u@m7oj9vk2H@xlgFknK0azuG1kaawat7@aGvltC1UNdhXCF5bq0gdMKgTLqyAH1CqpujDXHeJWQ/M8ikjn57Cq6OAyWJKMRulcAAtoBAgi4gj88B5Jhm4S8L/b9JzcgHe4lZmRUg3KYbQ76vYh@siDOHCwhLU3dOUoywsvmcgIfN4DyF0u1wRKe9ckYw@QZnPhytR5Z5YusZK1BoDlZrxBg) (courtesy of Arnauld)
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 22 bytes
```
L->x->L.map(a->a.f(x))
```
[Try it online!](https://tio.run/##jVGxTsMwEJ3rr7jRqeIEmFBSLDGAhNRObSfEcE2d1CFxIvtSpUL99uBCqJAqRBf7/N47v2dfiXsUTatMuX0fdN02lqD0WNSRrqJpyi4wR1ZhfaLiGC7YvDMZ6caceKYNKZtjpuB5hGG2CmEt4YNN2m5T6QzWkPMVUJCyI2MjllXoHCxQm19CR0h@2zd6C7Wn@JKsNsXrG6AtXHBSTn5sZsuvkLPz@cUnKZQNYSykDOGSHLvOGumTKNwreBjmQvZCzqMaW45CYpTzPgiG1Jt@azzwaC0eXIRurh1x/rd5ALwHIeH2BqbQByFcoe0hhrv/pAukXZLgxl11pfAvGMfJfZXze7809gmzHV8eHKk6ajpKktb/M1XGj2hyZMfhEw "Java (OpenJDK 8) – Try It Online")
-4 bytes thanks to Olivier Grégoire
`L` is a stream of `Function<Integer, Integer>` and `x` is an `int`. `Function` here is not `java.util.function.Function` but rather is a custom interface `Function<T, U>` with a single method `U f(T t)`. This is just to save bytes over the normal `Function<T, U>` which requires the method name `apply`, which is apparently allowed.
[Answer]
# [Julia 1.0](http://julialang.org/), 9 bytes
```
a^b=a.|>b
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/PzEuyTZRr8Yu6X9BUWZeSU6ehqlCnEJ0ha5dhZaRjgKI1jWE0FoVsZr/AQ "Julia 1.0 – Try It Online")
# Julia 1.6+, 3 bytes
As pointed out by [@MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush), Julia 1.6 has since allowed defining `.|>` as a function, giving this 3-byter:
```
.|>
```
TIO does not offer Julia 1.6, but here's an interactive example:
```
julia> f=.|>
Base.Broadcast.BroadcastFunction(|>)
julia> println(f(5, [x->x*2, x->x-1, x->x*x]))
[10, 4, 25]
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 23 bytes
```
a=>b=>b.Select(x=>x(a))
```
C# was born for this
[Try it online!](https://tio.run/##lY4xC8IwEIV3f8XR6SJp1eogtA2IKCh1cnBuQ9RATaFJsSD@9hibwUWhHsfx7nF877gOuZYWtq3iqVSGepVLbdKP5wZjFHYb1d5EU5SVSHuLwdndQAa2yFjpOjqKSnCDXcY6LAixyWi0rpWuKxGdGmlELpVAbRqpLtG@lgoDCgF9U3BOUIk7fItG4ioZQuofwkVMEH7D4AHYEfciPP/jLodhx7Mp9WoSe3EozDValdot3gi7Ptq@AA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 38 bytes
```
function(i,m)sapply(m,do.call,list(i))
```
[Try it online!](https://tio.run/##nZLdioMwEIXvfYqB0kXbyTaJCvWi@yJLIalrQUh/ULfYp3cnpqabshftSpTxMOdzcmIzlKbSl2oz7L@PZVefjnGNh6TV57O5xgf8Or2X2hg0ddvFdZIMM5gaQZtat1UL@1MDXdV2sGuqS91d4Q1KoxuqItUverXx6D6hdxJDKVKCh5LgY9tKho0rGSm9a6lUG1uoSDEyKkZFvxQ87CbBMh7l1Sgv@qWkjsfZlpJuQQOl4TwpWeYpC9V@bqUocgnGKQKMMSUJPHPNgH3A53ayZxKdneJ5huDsmfQAPn1/jBPH@HDKC21SIdYByHVbHrT@F2hNjAyBzGztUSyfNvXbju60/tilQ5HJLk/J/UAvUuznxZ0juI944TZGfrz/DGjPHW8nTVzHEZxsgpa0Dzplds@8yDm@Tiy4zC20oPEKnmV8Aovt8AM "R – Try It Online")
[Answer]
# Ruby 2.7, 19 bytes
```
->a,b{b.map{_1[a]}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6k6SS83saA63jA6Mba29n@BQlq0qU60rl1FdYWWUW1s7H8A "Ruby – Try It Online")
Doesnt work on TIO cause of Numbered arguments.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 0 bytes
APL doesn't normally use lists of functions, but there are ways to use such. Even if the syntax for their creation is awkward, their use is simple: [Try it online!](https://tio.run/##SyzI0U2pTMzJT//v96htwqO@qX7Bh1aYPurd8qir6VHvGi6/aMNYvTSgVPWj3q2HpwOJWqCYEZLYdkMDkJAxVEgDpk5TQVtBwwjONAQpMoEqMjQG8UxhWoxrwIp0FYDCPkARP720////@ygYGnD5KFiaGgAA "APL (Dyalog Unicode) – Try It Online")
For the specific case of a list of integer↦integer functions, it is convenient to represent \$L\$ as a [train](https://apl.wiki/train), though it, despite appearances, isn't a list of functions. The calling syntax is identical to the above: [Try it online!](https://tio.run/##SyzI0U2pTMzJT//vY/CobYIOl48hiFKoftS7tZbLxwjIqTY0ODwdxIWIHt5uBGLVQBQY41cApHUhCk1AClHEIKq1DQ2AsqYgWZBeFHOAUkCmBkxcU0FbQcMIzjQESRoag5UY14AFdRWMa///B3pFwRjoEQUTI6ADFQyAliscWm8KooCEqYKhAYi0NDUAAA "APL (Dyalog Unicode) – Try It Online")
If we absolutely wanted something that took \$L\$ and \$n\$ and applied \$L\$ to \$n\$ using the above juxtaposition syntax, we write a full program which prompts first for \$\$ and then for \$L\$, applying \$L\$ to \$n\$ by juxtaposition of the input values:
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 2 bytes
```
⎕⎕
```
Each stylised console prompts for a value from the console (STDIN).
[Try it online!](https://tio.run/##SyzI0U2pTMzJT//v96htwqO@qX7Bh1aYPurd8qir6VHvGi6/aMNYvTSgVPWj3q2HpwOJWqCYEZLYdkMDkJAxVEgDpk5TQVtBwwjONAQpMoEqMjQG8UxhWoxrwIp0FYDCPkARP700rkcd7QoF/4EOAqL/QM5/BTAo4DI04PLhgnEsTYE8AA "APL (Dyalog Unicode) – Try It Online")
Alternatively, we could define an "apply" operator that takes \$L\$ on the left and \$n\$ on the right:
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 [bytes](https://github.com/abrudz/SBCS)
```
{⍺⍺⍵}
```
`⍺⍺` is the left [operand](https://apl.wiki/operand) and `⍵` is the right [argument](https://apl.wiki/argument).
[Try it online!](https://tio.run/##fVC9isJAGOzzFFsqGtmfbGFto7CkuNiJReDQRoitqI2ChRC5Kw5fwUKwUYQrkzfZF4nzZRPR4g7CzmS@mWTni@cz/3MRz5JpEdrdlz38hFF20ja92v3GpmcvHIlxZ4LR0qa3/IhjDU2@aHfBSVKV1Kh9TdZiDfmkgkxBZRKK3nQdUavS5DPIBkrYmXiGg7Q9IwjYsvyxkWWYu3s4Nb9LYitnUP8bgL4zBmR805y7RW2Mfitcfwcj0L8LYohiZHkpVCD7Wz63dZHQjtOD3W@xWyw5u@DC39h69NHDOewPosKwhAnuEXQ1kIMo7AEQSDQEQg0A2UU7AtBVSrvYAw "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Raku](http://raku.org/), 13 bytes
```
{@^f».($^n)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2iEu7dBuPQ2VuDzN2v/FiZUKaRrRWoc26Sho6Rsa6ChUK6jEH9qkoK1gpKUSD6QMa4FihsZAUktBVcFYQVfBOFZHwdBA8z8A "Perl 6 – Try It Online")
[Answer]
# [R](https://www.r-project.org/) >= 4.1, 21 bytes
```
\(l,i)Map(\(x)x(i),l)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRydT0zexQAMuUKFZoZGpqZOj@T9NIyezuARFRkFbwVBHAUUkTsEITURLwVJTR8FE8z8A)
An anonymous function taking a list of functions and an integer and returning a list of integers.
TIO version uses `function` instead of `\` since TIO hasn’t been upgraded to R 4.1 yet.
[Answer]
# BQN, 7 bytes
```
{ùïéùï©}¬®‚üú<
```
[Try it!](https://mlochbaum.github.io/BQN/try.html#code=Q2xlYXZl4oaQe/CdlY7wnZWpfcKo4p+cPCAKYXJy4oaQLeKAvyvigL8oM+KKuCsp4oC/KOKMiuKImOKImikKYXJyIENsZWF2ZSAz)
-2 bytes from dzaima.
Takes a list of monadic BQN functions, returns a list of the same length.
[Answer]
# [J-uby](https://github.com/cyoce/j-uby), 3 Bytes
```
:-@
```
J-uby actually has a built-in for this, despite me never having actually used it. You are intended to use it with `-[f, g, h]` to create a function that will "cleave" a provided argument over the functions in the array. `:-@` is the symbol for unary minus in Ruby, which is callable in J-uby. It would take input in the form `:[[email protected]](/cdn-cgi/l/email-protection)(L).call(n)`.
But built-ins are boring. How would it be implemented otherwise?
# 13 Bytes
```
~:*%(:& &~:^)
```
There are basically three components to this function. First is `~:*` which just creates a flipped-argument map function: `->(a, f){ a.map(&f) }`.
Next, there is `:& &~:^`. This defines the "n-applicator" function: given the input `n`, this defines a function that will apply `n` to whatever function you pass it. Essentially, it’s equivalent to `->(n){ ->(f){ f[n] } }`. How does this work? `^` is the function application operator, so `~:^` is function application with flipped arguments: `->(x, f){ f[x] }`. Since `&` is the partial application operator, `:& & ~:^` means you partially apply the flipped function application operator to the partial application operator. Anyone else getting semantic satiation?
Finally, we've got `%` in the middle. The `%` operator has different functionalities depending on its arguments, but in this case it denotes a "hook": given a binary function `F` and a unary function `G`, it returns a function that applies `G` to one of its two arguments before passing them on to `F`: `F % G == ->(L,n){ F[L, G[n]] }`. In this case, that means calling a flipped map (`~:*`) on the input array L and the n-applicator function (`:& & ~:^`).
The result is mapping the n-applicator function over the supplied array of functions, applying n to each element of the array. In plain Ruby, it's equivalent to `->(L,n){ L.map { |f| f[n] } }`
[Answer]
# [Elm](https://elm-lang.org), 14 bytes
```
(|>)>>List.map
```
[`|>`](https://package.elm-lang.org/packages/elm/core/1.0.5/Basics#(%7C%3E)) is function application: `a |> f` means `f a`.
[`>>`](https://package.elm-lang.org/packages/elm/core/1.0.5/Basics#(%3E%3E)) is function composition: `(f >> g) a` is `g (f a))`.
You can try it [here](https://elm-lang.org/try). Here is a full test program:
```
import Html exposing (text)
f = (|>)>>List.map
main =
f 5 [\x -> x * 2, \x -> x - 1, \x -> x * x]
|> Debug.toString
|> text
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
v€
```
[Try it online!](https://tio.run/##y0rNyan8/7/sUdOa////KxkaHJ6uoqSjoHR4uxGYdgQRfkr/LQA "Jelly – Try It Online")
Accepts a list of functions on the left in Jelly source code and the value on the right.
```
v€ Main Link; (x: functions, y: value)
€ For each function in x
v Evaluate it at y
```
Less trivial answer:
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
³Ç$СḊ
```
[Try it online!](https://tio.run/##ASsA1P9qZWxsef8xMMOXJCDDtzIkIEEgTiA0xq3/wrPDhyTDkMKh4biK////OP80 "Jelly – Try It Online")
Full program that accepts the blackbox-functions as a tied function in the header (standard for inputting blackbox-functions for Jelly), the initial value in the third argument (first value), and the number of functions in the fourth argument (second value).
```
³Ç$СḊ Main Link; (x: value, y: number of functions)
С Collecting intermediate values, repeat y times:
$ - last two:
³ - x
Ç - call the helper link (the blackbox)
Ḋ All but the first element
```
Basically, calls the black-box N times, where each time the function cycles its behavior (that's how tie works), and collects all N+1 results, then removes the initial value.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 7 bytes
```
Through
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PySjKL80PeN/QFFmXkm0sq5dWrRzfl5xSVFpcomDg3JsrFpdcHJiXl01V3V1rY6Cca0OkKGsBmSaGIHZhgbKajoKyvpGQNIxqThaORbI0AWrMCCkwAKsAFkQqFDb0AAkp2uKRxIip6wFMRkoBqS0lLWNgPJApqExkPDNT4lW1jGO1TUGaTA0IFWHpalBLVftfwA "Wolfram Language (Mathematica) – Try It Online")
Built-in. Input `[L[n]]`.
---
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 12 bytes
```
nÔí°#@n&/@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P@/9pIXKDnlq@g7Kav8DijLzSqKrlWt17dKilY1io5VjY9UcHByquaqra3UUjGt1gAxlNSDTxAjMNjRQVtNRUNY3ApKOScVA9UCGLliFASEFFmAFyIJAhdqGBiA5XVM8khA5ZS2IyUAxIKWlrG0ElAcyDY2BhG9@SrSyjnGsrjFIg6EBqTosTQ1quWr/AwA "Wolfram Language (Mathematica) – Try It Online")
Input `[n][L]`.
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 37 bytes
```
(d C(q((F N)(i F(c((h F)N)(C(t F)N))(
```
[Try it online!](https://tio.run/##JY6xDoMwEEP3foXHu650KkMHJEam/kAIV3FSEmhyqOLraWgnP8uWZdO0By3rcdCEjt5EPQYmRU@eaEbP1XVkP2A6KCxuQtAxu7zzhfwSoyTDc84ieG3Jmy6p3KHJZzmjFnELpmvYMe5oWpgUw2cWmyUjbXGsogVr1ih1sQPVQ3YOVHJxnBxoYNAVAxrmf/HBuDV8fAE "tinylisp – Try It Online")
### Ungolfed/explanation
```
(load library) Library contains ungolfed aliases for builtins
(def cleave Define cleave to be
(lambda (F N) a function taking a list of functions F and a number N
(if F If F is nonempty:
(cons Construct a list
((head F) N) whose head is the first function in F applied to N
(cleave and whose tail is the result of a recursive call
(tail F) with the remaining functions in F
N)) and the same number N
nil)))) Else, return empty list
```
[Answer]
# [Standard ML (MLton)](http://www.mlton.org/), 19 bytes
(-1 from [Laikoni](https://codegolf.stackexchange.com/questions/230145/implement-a-cleave-function/230215?noredirect=1#comment547575_230215) by manipulating names and spacing on the original `fn n=>map(fn f=>f x)`.)
```
fn! =>map(fn f=>f!)
```
[Try it online!](https://tio.run/##TYzBCoAgFAR/ZbtpVFDQ0e6dO0aEREagz6iHv28SER1n2ZnL2dJZ9hSDtljsqsMKFQ1lUJ3ThzAEozqTyecwQyGtEMe5E8OjJ67YD5xwkxBvoMWYPEoJUN4U@KCsf5DTJOMN "Standard ML (MLton) – Try It Online")
[Answer]
# Rust, 49 bytes
```
|u,k:Vec<Box<_>>|k.iter().map(|z|z(u)).collect();
```
Maximally abusing [this ruling](https://codegolf.meta.stackexchange.com/questions/25156/should-rust-anonymous-functions-fully-specify-parameter-types). Would be nearly twice as long if all types where specified.
[Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=e2b006e3ff95c6dcada6a3bd089532c0)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
S
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCI1XG7in6jOuzEwKjt8zrvCvTt8zrtOO3zOuzIqNSszLTvin6kiLCJTIiwiIiwiIl0=)
A full program that takes `number` then `functions`.
## Explained
```
S # Converts each function to a string. This involves evaluating them, which somehow takes input from the stack.
```
Takes input in the header because that's how to input functions
[Answer]
# [Factor](https://factorcode.org/) + `combinators`, 6 bytes
```
cleave
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnJ@blJmXCBQpVrD@n5yTmliW@v8/AA "Factor – Try It Online")
Built-in.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ṛĿⱮ
```
[Try it online!](https://tio.run/##y0rNyan8z3V4uqEBlweXI5cflzaQdWgT1@HtYFr74Y4ljxpmcBkac6kaxxv/f7hz9pH9jzau@394ub63ZuT//9HGOgrRsbFAwsQISBiCmQZADOQBpUx0FEzBQhaYQrqmIF1Ano6CGVgAnW8IMsdcRwGo11JHAcQzhJhvaYpVBgA "Jelly – Try It Online")
Takes \$n\$ on the left and a list of link indices on the right.
```
Ɱ For each element of the right argument,
·πõƒø call the link at that index monadically on the left argument.
```
[Answer]
# [Red](http://www.red-lang.org), 32 bytes
```
func[g n][forall g[g/1: g/1 n]g]
```
Modifies the list in place.
Doesn't work in `TIO`, but works fine in the Red GUI console:
[](https://i.stack.imgur.com/bUxYf.png)
Here's a `TIO`-compatible version:
# [Red](http://www.red-lang.org), 41 bytes
```
func[L n][collect[foreach g L[keep g n]]]
```
[Try it online!](https://tio.run/##TYyxCoNAEAV7v@LVQooEbPwGq7TLK8LebhIiq1wU7u9PsdFuBobJlurTkrDxvvoaKgOCotM4mi7iU7aXfvDGID@zeYcgWT3@PeToC6WgxYM49Yb7VVsUspnzNxY4sqVVDfsCXd0A "Red – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes the integer as input as a single digit array with the array of functions pre-assigned to variable `V`, outputs and array of single integer arrays.
```
V£mX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=CltAWCoyfSxAWC0xfSxAWCp4fV0&code=VqNtWA&input=WzVdCi1R)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~62~~ 52 bytes
```
f(n,L)int(**L)();{while(*L)printf("%d ",(*L++)(n));}
```
[Try it online!](https://tio.run/##dZBBDoIwEEXX9hQTjUkHwUSjq6onaNy5Mi60LdoEiyIoCeHsOEUxunBWM7/v/06roqNSTRNzF0q0LudBIJGjqB4nmxhOwyUjOeb9oYZ@SMJohNwhiroZWKeSQhtY3HJt0/FpxX6kxB68RnbQaXFIjOW@LxEqyExeZA5KCGAqoH5BRn0Iqi8ogkkH3a7FPvuTVHbQeW8dv6dWE8B8VvsyuZ3t0BsRlqT33kuFLeHLLxCy3vsK6tYbKdvTWnQx4Mg8f43@10CiYDVrng "C (gcc) – Try It Online")
Takes `L` as a `NULL`-terminated array of pointers to functions taking an int and returning an int. Outputs results space-separated on stdout (with a trailing space).
-10 bytes from [@EasyasPi](https://codegolf.stackexchange.com/questions/230145/implement-a-cleave-function/230223?noredirect=1#comment528265_230223)
(also [C++ (gcc)](https://gcc.gnu.org/), 79 bytes with `#include<cstdio>` and ANSI function syntax. [Try it online! (C++)](https://tio.run/##hY5BDoIwEEX3nGKCMekUWGh0VfUE3ICwMAW0SR2aWpSEcHZsQRdudBaT/Jc/f740JrtIOU0rRVJ3VX2Qd1ep9hQ9WlVBwxQ5oNRvxnmOQSIOz6vSNfPaWA8aFq8riFMPkgQZIYpxCne3syIWchCGCPzMMXmxK5cgOL55mKKcf/XeC7Z2nSXogcNWwJj@NmWw@W/i0H@ZqNPaOLuAUXzqAflS@0U2jFLIUUTj9AI "C++ (gcc) – Try It Online"))
---
If writing to a caller-allocated array that is passed to the function is a valid form of output, then:
# [C (gcc)](https://gcc.gnu.org/), ~~59~~ 51 bytes
```
f(int n,int(**L)(),int*r){while(*L)*r++=(*L++)(n);}
```
[Try it online!](https://tio.run/##dY/BTsMwDIbP61NYQ0hJ0yFgcMrGE1TcOJUKdUnKLJUU0nZUTHn24nTtgAM@JPaf358dtXpVahhKhrYFm9DJ4jjljIc0dvz4ucfKMJJiJ8SWEiE4s1z64QKtqjptYNO0Guur/UP0R6pwF7QA1nW3qwyOQ3oOR3Cm7ZyFHmK4leBPJqPODopfphXczKbmoyvcP6R@Nr0VaNmhRk2GKLDGb6XZXc5DI4ct6YtpqWR0hAgLJNFiGkHZ41Oajq9ezhiw1Hz/U6rKFAejs3V@0kpmE0iTWeeTWjtgDX6ZlxaQANeSrg2sJQiB85Ih3h1BS7a81M92eaZkmE8gH/lo@AY "C (gcc) – Try It Online")
Same input as above, but outputs results through `r`, which must point to at least as many `int`s as `L` does `int(*)(int)`s (not including `L`'s `NULL` terminator).
-8 bytes from [@EasyasPi](https://codegolf.stackexchange.com/questions/230145/implement-a-cleave-function/230223?noredirect=1#comment528265_230223)
(also [C++ (gcc)](https://gcc.gnu.org/), 59 bytes [Try it online! (C++)][TIO-kq6vpd7q])
[Answer]
# JavaScript, 43 bytes
I know there's already a nice JS entry, but I wanted to give it a go by giving both parameters to a single function. Different approach, same output.
Here's mine:
```
(n,a)=>a.reduce((A,F)=>A.concat([F(n)]),[])
```
[Try it online!](https://tio.run/##Pcg9CoAwDEDhq2RMJBYUHCu4eInSIdQqirTiH719dRC3771FbjncPm9nGeLg86gzBhbSrajdD5fziB33b3fKxeDkRNNjIEtsLOV3HXH1ao0TjtiwSaBbSFBAzfC5hOp3AckS5Qc "JavaScript (Node.js) – Try It Online") Also [test cases](https://tio.run/##rZHPisMgEMbv@xRzWdBWEzUGkkMKvfS2TxBycNN0/1CS0qSLb58dtwqllr00Moh@jt9vHL/Njxnb89dp4v2w7@ZDNZOeGVptTHLu9pe2I2TLdrjfJu3Qt2Yi9Y70tKGsbuiM0jgcu@Q4fJADAcicSuG5kaZQNy931lqx2kK1AfsMwFlrFZmD8OZSrCyDKydVfvVmps/EvI/EUq/wh0U4c8HARwwploIU6K8Z@gEvIgzPPeaRY8Cupfi/jQ6TM3ARP2RJApYLMmbI8CP2plcoQhBhDepvll6TWTh8zYBD5uiOIQXewiSp3IRJPPr/Ml@MVgqVO2CJzyqF1iJAZTP/Ag "JavaScript (Node.js) – Try It Online") (modified from Arnauld's imlementation).
This is NOT memory friendly because I had to create a new array each time I used `Array.prototype.concat`. It would have been much nicer and slightly shorter if JavaScript's `Array.prototype.push` would just return the modified array...
[Answer]
# [Mlatu](https://github.com/mlatu-lang/mlatu), 20 bytes
```
->n;{n swap call}map
```
Explanation:
`->n;` pops off the stack and binds it to `n`. The list is left as the implicit parameter of `map` and is never bound. `{n swap call}` is a closure in Mlatu, which pushes `n` (the number) onto the stack, swaps the placement of the number and the function, and then calls the function with `n` as its argument. `map` takes the list and the closure and `map`s the list with the given closure.
[Answer]
# [Binary Lambda Calculus](https://tromp.github.io/cl/cl.html), 58 bits = 8 bytes
```
0000010110000000000101110011111011111100101111011010000010
```
[Try it online!](https://tio.run/##S8pJ/v/fAAQMDQwNDeAAxANyDUEAQhpCBcHqDKGK/v8HAA "Binary Lambda Calculus – Try It Online")
It's a higher-order function that takes in a Church numeral and a list and returns a list. The list encoding is the one where a list is identified with its right fold function (e.g. `[1, 2]` would be `\c n. c 1 (c 2 n)`). (I'm using `\` as \$\lambda\$ in this answer.)
**“Readable” version:**
```
\\@@1\\\\@@2@46@@321\\1
```
Here, I'm using prefix notation. `\` is abstraction and `@` is application. Numbers are de Bruijin indices (starting at 1). Of course, (for example) `321` here means `3`, then `2`, then `1`, not the number `321`.
**Actually readable version:**
```
\k l. l (\a b c n. c (a k) (b c n)) (\c n. n)
```
## Explanation
Todo. It’s late and I’m tired.
[Answer]
# [Go](https://go.dev), 78 bytes
```
func(x int,F[]func(int)int)(O[]int){for _,f:=range F{O=append(O,f(x))}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=xVTLToNAFN244ismTUxmdNBSWtOasHDTZeu-MWYKM5UIA8JAMIQvcdOY-FH1a5wHfcTQBW5ckHmdc--5c8_w8blJtrtZSvxXsqEgJiG3wjhNMgFuwIDFYnCyjIl4GVhWSTLgR5SUFHhfhWD2dLdgBfdhBUIu8Hz1pFdyjtQHl6snNdYsycAzZvdeRrjMNa-XHklTygO4xAxWCDVWRkWR8cZE_b4oxXtKAePAA6chrXY7l_syGTeSSBDscQslBDFem3jgqE7R97sVuAaLptHkvFj3JdsHclxEfclXB3IQln3Jt8fMSe-aLw9kP-H9yIpobuutIBndkzvLq0yOMKBcnAcaEFnnZyFyCh_WOWRRQsTdWNlE-sRSYO1WiEBtPWYSFnFoXAknWJmjlm2BI4RVb6GjRq26Qeg33jX4jpPxyBzpMjrOh8dMzlCmkM3UKWVFWNkC2g7qoE3_RrPbwk5hWPleRenA94Q7bTXmnowqLa-7MwYmGyKfkblqM3carKwFHfcsVdoWuhpuA7fpkDKb_KOW9vez3ZrxBw)
### [Go](https://go.dev), 79 bytes, generic
```
func f[T any](x T,F[]func(T)T)(O[]T){for _,f:=range F{O=append(O,f(x))}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=xVQxboMwFF06cQorUiW7gTaEpEorZeiSMXRgi1DlAG5RwVBjIiLECXqELlGlHio9TW0MSVSRgS4dkM33e__97__g4_M52e2HKfZe8XMAYhxSLYzThHFwDQYk5oOT1xjzl8FXzokx29skpx4gKwdgunVhARx9sXJlEDrIQdBeuQ4qScLAk07u5wxTkX5R2nOcpgH1oa0TWCBUaSzgOaOVSvt98b7BDHhRgDcBmIv8IeWupvFtGgBCZUQqiCASTxvORFxoU02TZOz7LW4JJJLQUomoYAEaehstwBAsq6omZ_m6L9k4kOM86ku-OpD9cNOXfHNUTnr3fHkgewntR5ZEdVtvOWZBS-5sr1AaoR9Qfh6oQHidnYWILXxYZ5BECea3E-kdYR6tdqF0LUSg1B6ZgEUUKv_AqS7NUYqxwDHS5WyhKde66gqh33hL4TtOJmN1VLfRcT46KpkjISGGWUuKjnRpC2iYqIM2-xvNaBo7henS9zJLB74n3Gy6UfekqqrL656MgomBiM9IXbXam5UurQVN6yxV2BZaNdwAVtVRyt30H2tp_km7nVp_AA)
[Answer]
# [Lua](https://www.lua.org/), 55 bytes
```
function g(L,n)for k,v in pairs(L)do print(v(n))end end
```
[Try it online!](https://tio.run/##Tcs7DoAgEITh3lNsuWuo9BpcwvgKwQxmARvj2fFRqMU0/5dZclfKlNEnF0AzWwOZgpI3GznQ2jmNbGUItKpD4o0hMmKga9/PX1XHlBWEurmtei3@rX1s5t2beJhGygk "Lua – Try It Online")
] |
[Question]
[
# Calculate the area of a polygon.
Inspired by this [shoelace algorithm video.](https://www.youtube.com/watch?v=0KjG8Pg6LGk&t=0s)
## Task
Your job is to create a program or function that calculates the area of a polygon. Program or function is defined according the the default definition in meta.
## Input
You will receive the X and Y coordinates of each vertex of the polygon. You can take the input as a list of tuples (`[[x1, y1], [x2, y2], etc]`), a matrix, or a flat list (`[x1, y1, x2, y2, etc]`). Two lists containing `x` and `y` coordinates respectively are allowed as well. The vertices are numbered counterclockwise and the first vertex is the same as the last vertex provided, thus closing the polygon.
If you want you can take the input without the last vertex (so receive each coordinate just once).
You can assume that the edges of the polygons don't intersect. You can also assume that all vertices have integer coordinates.
## Output
The area of the polygon. All standard output methods are allowed. If your language does not allow for float division and the solution would not be an integer, you are allowed to return a fraction. The fraction does not necessarily have to be simplified, so returning `2/4` would be allowed.
## Winning criterium
Shortest code wins!
## Test cases
```
[[4,4],[0,1],[-2,5],[-6,0],[-1,-4],[5,-2],[4,4]]
55
```
[](https://i.stack.imgur.com/GWDit.png)
```
[[1,1],[0,1],[1,0],[1,1]]
0.5
1/2
```
[](https://i.stack.imgur.com/hwdr5.png)
[Answer]
## Mathematica, 13 bytes
```
Area@*Polygon
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 9 bytes
```
@polyarea
```
Inputs are a vector with the *x* values and a vector with the *y* values. This works in MATLAB too.
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en99@hID@nMrEoNfF/mka0iYKBgq6Rgq6Zgq6hgqmCSayOAlAMxASKm4CkTGI1uYAKDYEChgqGIHkgBeLEav4HAA)
[Answer]
# JavaScript (ES6), ~~69 67 47~~ 44 bytes
*Thanks to @Rick for noticing that we don't need the absolute value if the vertices are guaranteed to be sorted in counterclockwise order and for suggesting to take a flat list as input, saving 20 bytes!
Saved 3 more bytes thanks to @Shaggy*
Takes input as a flat list of vertices, including the last vertex.
```
f=([x,y,...a])=>a+a?x*a[1]/2-y*a[0]/2+f(a):0
```
[Try it online!](https://tio.run/##XYtBDoIwFET3nqLLVqa1n4ALE/QgTRc/SI2GUCPGwOnrx6WbyczLvAd/eO5f9@fbTvk6lJI6HRascM5xNN2ZK74sew4UD7VdpXgpVdJsTr70eZrzOLgx33TSoUED5UFQtkYreYSXJFjhLQQquURjdn8ibc5PpM2QKafyBQ "JavaScript (Node.js) – Try It Online")
### How?
This is based on the formula used in many other answers. For \$n\$ 0-indexed vertices:
$$area=\left|\frac{(x\_0y\_1-y\_0x\_1)+(x\_1y\_2-y\_1x\_2)+\ldots+(x\_{n-1}y\_0-y\_{n-1}x\_0)}{2}\right|$$
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to Emigna (redundant `€`, `ÆḊ` has a left-depth of 2)
-1 byte thanks to Emigna, again (halve, `H`, is floating point no need to `÷2`)
```
ṡ2ÆḊSH
```
A monadic link taking a list of pairs of coordinates in counter-clockwise fashion as per the examples (with the one repeat) and returning the area.
**[Try it online!](https://tio.run/##y0rNyan8///hzoVGh9se7ugK9vj//390tImOSaxOtIGOIZDUNdIxBVFmOgYgylBHFyRnqqNrBKRACmMB "Jelly – Try It Online")**
### How?
Applies the shoelace algorithm, just as described in the video (which I happened to also watch just the other day!)
```
ṡ2ÆḊSH - Link: list of [x,y] coordinate pairs anticlockwise & wrapped, p
ṡ2 - all overlapping slices of length 2
ÆḊ - determinant (vectorises)
S - sum
H - halve
```
[Answer]
# [Python 3](https://www.python.org), ~~72~~ 71 bytes
```
from numpy import*
g=lambda x,y:(dot(x[:-1],y[1:])-dot(x[1:],y[:-1]))/2
```
Takes two lists, as it was allowed in the comments
```
x = [x0,x1,x2, ...]
y = [y0,y1,y2, ...]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1chrzS3oFIhM7cgv6hEiyvdNicxNyklUaFCp9JKIyW/RKMi2krXMFanMtrQKlZTFyICZAIFQOKamvpG//8DAA)
This is basically just the implementation of the [shoelace-formula](https://en.wikipedia.org/wiki/Shoelace_formula#Definition).
May I get plus points for a golf that you actually would implement like that? :D
-1, there is no need for a space behind `x,y:`.
---
[Answer]
# R, ~~54~~ 52 bytes
```
pryr::f({for(i in 2:nrow(x))F=F+det(x[i-1:0,]);F/2})
```
Which evaluates to the function:
```
function (x)
{
for (i in 2:nrow(x)) F = F + det(x[i - 1:0, ])
F/2
}
```
Makes use of the predefined `F = FALSE = 0`. Implements the shoelace algorithm in the linked video :)
-2 bytes thanks to Giuseppe
[Answer]
# [Mathics](http://mathics.github.io/), 31 bytes
```
Total[Det/@Partition[#,2,1]/2]&
```
[Try it online!](https://tio.run/##y00sychMLv6fpmCr8D8kvyQxJ9oltUTfISCxqCSzJDM/L1pZx0jHMFbfKFbtf0BRZl5JdFp0dbWJjkmtTrWBjiGQ1DXSMQVRZjoGIMpQRxckZ6qjawSkQAprY2O5EFoNwZogWg3BWkAiQDX/AQ "Mathics – Try It Online")
---
# Mathematica, 25 bytes
```
Tr@BlockMap[Det,#,2,1]/2&
```
[Answer]
# [Factor](https://factorcode.org/), 35 bytes
```
[ dup pick [ rest v. ] 2bi@ - 2 / ]
```
[Try it online!](https://tio.run/##VYyxCsIwGIR3n@JeINGE6qCLm7i4iFPpEOMvhsYak7Qg0mePSTvJwc/dfcd/Vzq@fLqcj6fDFi35jiyeKj6mwwcqOMB5ivHjvOkiAr176jQF7FKNW@/gjG5Rw1OIGDgayKvZg0FiiSZ9UWEFJsE2YALrHMdFKYvPoCosd/MbrawFz1xkJrLGyc/pf6MtKZ9@ "Factor – Try It Online")
Takes two arrays of x- and y-coordinates on the top of the stack, and returns the area as an integer or a rational.
Exploits the vector dot product `v.` which ignores excess elements on either side, so calculating one side of the shoelace is as simple as "remove the first element from the top array, and compute the dot product". And we can reuse it to evaluate the other side of the shoelace by simply swapping the two input arrays.
Honorable mention goes to the Apply combinator `2bi@`, which lets us simplify multi-application of the inner function.
```
Input:
{ 4 0 -2 -6 -1 5 4 }
{ 4 1 5 0 -4 -2 4 }
Remove the first element from top:
{ 4 0 -2 -6 -1 5 4 }
{ 1 5 0 -4 -2 4 }
Evaluate the dot product (sum of elementwise product, ignoring any excess element)
[ ! Input: ( x y )
dup pick ! Copy stack items to form ( x y y x )
[ rest v. ] ! The function that evaluates one side of shoelace
2bi@ ! Apply the above to ( x y ), then to ( y x )
- 2 / ! Subtract the two and halve
]
```
[Answer]
# JS (ES6), ~~98~~ ~~95~~ ~~94~~ ~~93~~ ~~88~~ ~~86~~ ~~82~~ ~~81~~ ~~77~~ 73 bytes
```
(X,Y)=>{for(i in X){a+=(X[i]+X[i-1])*(Y[i]-Y[i-1]);if(!+i)a=0}return a/2}
```
Takes input like `[x1, x2, x3], [y1, y2, y3]`, and skips the repeated coord pair.
-3 bytes thanks to @JarkoDubbeldam
-4 bytes thanks to @JarkoDubbeldam
-1 byte thanks to @ZacharyT
-4 bytes thanks to @ZacharyT
-4 bytes thanks to @Rick
[Answer]
# J, 12 bytes
Assuming the input is a list of 2 element lists (ie, a table)
```
-:+/-/ .*2[\
```
* `2[\` -- breaks it down into the shoelace Xs, ie, overlapping squares of 4 elms
* `-/ .*` -- the determinant of each
* `+/` -- sum it
* `-:` -- divide by 2
If we get the input as a single list, we need to first transform into a table, giving us 20 bytes:
```
-:+/-/ .*2[\ _2&(,\)
```
[Answer]
# MS-SQL, 66 bytes
```
SELECT geometry::STPolyFromText('POLYGON('+p+')',0).STArea()FROM g
```
MS SQL 2008 and higher support Open Geospatial Consortium (OGC)-standard spatial data/functions, which I'm taking advantage of here.
Input data is stored in field *p* of pre-existing table *g*, [per our input standards](https://codegolf.meta.stackexchange.com/a/5341/70172).
Input is a text field with ordered pairs in the following format: `(4 4,0 1,-2 5,-6 0,-1 -4,5 -2,4 4)`
Now just for fun, if you allowed my *input* table to hold Open Geospatial Consortium-standard geometry objects (instead of just text data), then it becomes almost trivial:
```
--Create and populate input table, not counted in byte total
CREATE TABLE g (p geometry)
INSERT g VALUES (geometry::STPolyFromText('POLYGON((5 5, 10 5, 10 10, 5 5))', 0))
--23 bytes!
SELECT p.STArea()FROM g
```
[Answer]
# [Haskell](https://www.haskell.org/), 45 bytes
```
(a:b:c)?(d:e:f)=(a*e-d*b)/2+(b:c)?(e:f)
_?_=0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/XyPRKskqWdNeI8Uq1SpN01YjUStVN0UrSVPfSFsDIgMS54q3j7c1@J@bmJmnYKtQUJSZV6KgohBtomOgo2uko2umo2uoY6pjEqtgDxIEsYESJiA5k9j/AA "Haskell – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 14 bytes
```
2÷⍨1⊥2-/⍤×∘⌽/⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/3@jw9ke9KwwfdS010tV/1Lvk8PRHHTMe9ezVf9S16H/ao7YJj3r7HnU1P@pd86h3y6H1xo/aJj7qmxoc5AwkQzw8g/@naZgomGgqKGgYKBiCqEPrjRRMIQwzBQMIw1Dh0HqwGlMgwwjEAOsBAA "APL (Dyalog Extended) – Try It Online")
Same formula as in Arnauld's answer.
Takes input as a list of points, sorted in counterclockwise order.
## Explanation
```
2÷⍨1⊥2-/⍤×∘⌽/⊢
⊢ take the input (list of pts)
2 / reduce overlapping pairs by the following function:
× multiply the first
∘⌽ with the second reversed
-/⍤ reduce the multipled pair by subraction
1⊥ sum the resultant array (using decoding)
2÷⍨ halve it
```
[Answer]
# PARI/GP 61 bytes
```
c=concat;s(z,v=1)=c(z,z)[^#x*2]+c(z[^1],z)*v
s(x,-1)*s(y)~/4
```
assumes coordinates given by two vectors x=[x1,...xn], y=[y1,...,yn]
## Test cases
```
A(x,y)={my(c=concat,s(z,v=1)=c(z,z)[^#x*2]+c(z[^1],z)*v);s(x,-1)*s(y)~/4};
A([1, 0, 1, 1],[1, 1, 0, 1])
1/2
A([4,0,-2,-6,-1,5,4],[4,1,5,0,-4,-2,4])
55
```
[Answer]
# [PHP](https://php.net/), 76 75 73 bytes
Well, i probably shoot myself in the knee with PHP and his $ prefix for variable but i just wanna try the challenge with it anyway.
Header just remove error reporting for conviniance and format input as 2 array like it's allowed in post... i was just lazzy to retype it myself XD. (you can test both case by switching var in the for loop)
Edit: Figure out i can pass 2 arg to for() and save carac from while keyword with the same logic
Edit : Saved 2 bytes by reverse the iteration order and use juste `$i` for condition, saved `<0` (need to substract for 2nd option since result will be negative otherwise, but same bytes length)
```
for($i=count($x);$i;){$s-=$x[$j=$i--]*$y[$i]-$y[$j]*$x[$i];}$s=abs($s)/2;
```
[Try it online!](https://tio.run/##TY7BbsMgEETvfMUe9gAVKMZKeiGoH4JQ5bq0JoeAwJUcRfl2ByiVupedHc0bbVzifn6LSyQupZDek4shrf76TQemCK4urxI0GHPkcLQczMBB1i1GDqcmXjkMTUgOomVORYxVNMj2nrH1yM7/9chON79ECW41V6FbF18huWlegPZ3pgw4h5A@GdwJlMHN2JL9Nc1QkObe/ruyuA@yly6KXs/h57pS3JhCr9gds9ClBC8avRD2paDorajrUq6tXuqBWU8fmWJmh1Htbl4CYFb7Ew "PHP – Try It Online")
# [PHP](https://php.net/), 67 66 64 bytes
Solution without the `abs()` who work on both given case but feel like cheat since can return negative values in some cases ^^'
```
for($i=count($x);$i;){$s-=($x[$j=$i--]*$y[$i]-$y[$j]*$x[$i])/2;}
```
[Try it online!](https://tio.run/##TYzBbsMgEETvfMUe9mAqUIyV9EKsfAhCVeTQmhwCwo7kyPK3uwulUvayM6N5E8e4ny9xjMylFNJXcjGk2T9@mpZrhrObZgU9GHMUcLQCTCtA5S87AaciPgW0RSgBsnROJLosCmTrTld2VOX/d1SlS05VhkvuZehVxXdI7jqM0NSZ6wQ4hJBuHFYGdLgYS92/0LSElPT1nipKN7bTVoO@H8LzMTe4cI1e8xUn2ZMzeO/RS2k/iEVvZX53ckt2/NDpbXfDGAAnvf8C "PHP – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, 62 bytes
```
map$\+=$F[$i]*($a[($i+1)%@a]-$a[$i++-1]),@a=eval<>}{$\=abs$\/2
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUAlRttWxS1aJTNWS0MlMVpDJVPbUFPVITFWF8gDcrR1DWM1dRwSbVPLEnNs7GqrVWJsE5OKVWL0jf7/N9FRMNBR0DUCYjMgNtRRMNVRMOECCkOYIEkTiAKTf/kFJZn5ecX/dX1N9QwMDf7rFiQCAA "Perl 5 – Try It Online")
Takes input as a list of X coordinates on the first line followed by a list of Y coordinates on the second.
[Answer]
# [R](https://www.r-project.org/), ~~51~~ 46 bytes
*Edit: save 5 more bytes since no need to take `abs()` if points always encircle the polygon in counter-clockwise fashion*
```
pryr::f(sum(x*(1:0-.5)*x[2:1,c(2:ncol(x),1)]))
```
[Try it online!](https://tio.run/##dU/LCsMgELz7FUIvGtYSxfQg5EtKKTZN04DRYBKafL1VSB@klIVl9jGzOz70ziyNs2fta12G3i9eqRsZpo7MGeEqZ/uCZvNRKA4VEcpWzpCZAqcnSsPoW20bU/Oy0xHPpCI5pBDAOPAEKQiKdzjJY45eBPFL2Oybwa0kfJlGfNNVaxs83mvsYvL4oZc4d5O9otXCR1KCjFIcmIAC2CHi@A2TqRBxJNMN9G2cvI386W/314KiEJ4 "R – Try It Online")
After 3 years, ~~1~~ 6 bytes shaved from the previously-best [R](https://www.r-project.org/) solution!
[Answer]
# [Python 3](https://docs.python.org/3/), 58 bytes
```
lambda x,y:sum(x[i-1]*(j-y[i-2])/2for i,j in enumerate(y))
```
[Try it online!](https://tio.run/##FYxBCsMgFESv4vIrXxpt0kUhJ7EuLFVqqEasgdjLW93MG3jMpFree7w2tz7ax4Tny5AT6/17BDiV50Iz2HjtTWp6kW7PxONGfCQ2HsFmUyxUSlvKPhZwwH4@AVNqxlmjmlD05BKXgRtOAwL5cAv2S0379g8 "Python 3 – Try It Online")
Implementation of the shoelace algorithm.
[Answer]
# Excel, 97 bytes
```
=LET(a,A1#,x,ROW(a),y,{2,1},b,IF(x=ROWS(a),INDEX(a,1,y),INDEX(a,x+1,y)),SUM(MMULT(a*b,{1;-1}))/2)
```
LET and dynamic arrays were not Excel features in 2017.
] |
[Question]
[
This challenge is rather simple:
You are given an array of positive (not including 0) integers, and have to select a random element from this array.
But here's the twist:
The probability of selecting an element is dependent on the value of the integer, meaning as the integer grows larger, the probability of it to get selected does too!
# Example
You are given the array `[4, 1, 5]`.
The probability of selecting 4 is equal to *4 divided by the sum of all elements in the array*, in this case `4 / ( 4 + 1 + 5 ) = 4 / 10 =` **`40%`**.
The probability of selecting 1 is `1 / 10` or **`10%`**.
# Input
An array of positive integers.
# Output
Return the selected integer if using a method, or directly print it to `stdout`.
# Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes in any language wins.
* Standard loopholes are forbidden.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
x`X
```
[Try it online!](https://tio.run/##y0rNyan8/78iIeL////RJjoKhjoKprEA "Jelly – Try It Online")
Look 'ma, no Unicode!
Explanation:
```
x`X
` Make monad from dyad and use same left and right arguments
x Repeat each element of the left argument (implicit) list its respective number of times in the right argument list
X Random element
```
[Answer]
# [R](https://www.r-project.org/), 25 bytes
```
function(s)sample(s,1,,s)
```
[Try it online!](https://tio.run/##K/qfpmD7P600L7kkMz9Po1izODG3ICdVo1jHUEenWPN/mkayhgmQbaqp@R8A "R – Try It Online")
Explanation:
```
function(s){
sample(x = s, size = 1, replace = FALSE, prob = s)
}
```
Takes a sample from `s` of size `1` without replacement, with weights `s`; these are rescaled to be probabilities.
To verify the distribution, use [this link](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NYJ8/WULMkMSknVaM4MbcAROnk6YToFGtq6uf9T9NI1jDRMdQx1dQxNAACzf8A "R – Try It Online").
[Answer]
# [Pyth](https://pyth.readthedocs.io), 4 bytes
```
OsmR
```
**[Try it here.](https://pyth.herokuapp.com/?code=OsmR&input=%5B4%2C+1%2C+5%5D&debug=0)**
Saved one byte, thanks to @Jakube, with a rather unusual approach.
# [Pyth](https://pyth.readthedocs.io), 5 bytes
```
Osm*]
```
**[Try it here!](https://pyth.herokuapp.com/?code=Osm%2a%5D&input=%5B4%2C+1%2C+5%5D&debug=0)**
# How?
### #1
```
OsmR - Full program.
R - Right Map...
m - ... Using Map. This essentially creates the list [[4,4,4,4], [1], [5,5,5,5,5]].
- ... Credit goes to Jakube for this!
s - Flatten.
O - Random element of ^. Display implicitly.
```
### #2
```
Osm*] - Full program.
m - Map over the input.
] - The current element, d, wrapped; [d].
* - Repeated d times.
s - Flatten.
O - Random Element. Implicitly print the result.
```
[Answer]
## CJam (9 bytes)
```
q~_]ze~mR
```
[Online demo](http://cjam.aditsu.net/#code=q~_%5Dze~mR&input=%5B4%201%205%5D). This is a full program which takes input in CJam array format on stdin and prints the selected element to stdout.
### Dissection
```
q~ e# Read and parse input
_]z e# Copy and transpose
e~ e# Run-length decode
mR e# Select random element uniformly
```
[Answer]
# [Perl 6](https://perl6.org), 20 bytes
*Saved 1 byte thanks to @Brad Gilbert b2gills.*
```
{bag(@_ Zxx@_).pick}
```
[Try it online!](https://tio.run/##FcxBC4IwHIbxe5/ihTz8BzE2R3YwRfoYHZIV25KsyTR0RJ992ek5/Z7BhL5Iz4jMokL6XLWjpsV5WZqW8aG7Pb6p3FBm6SiRQ9UM1gdcpBCC8ZN2fNSxxBazwaxfEyaP0RgE/3b3PuL/kySLA9shJ6XUWkX7FTOefg "Perl 6 – Try It Online")
This takes 1 list argument. We zip 2 copies of this list using the `xx` operator. So with `@_ Zxx@_`, we get a list in which element `x` is presented `x` times. It is then coerced to `Bag`, which is a collection that stores objects along with how many times they appear in the collection. Finally, we pick a random element from this collection with `pick`, which takes the counts into the account and does The Right Thing™.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 32 bytes
```
->a{a.flat_map{|x|[x]*x}.sample}
```
[Try it online!](https://tio.run/##KypNqvyfpmD7X9cusTpRLy0nsSQ@N7GguqaiJroiVquiVq84MbcgJ7X2v5GBXklmbmqxQrVCgUJatEK0oY6RjrGOiY5prEKsQu1/AA "Ruby – Try It Online")
[Answer]
# [Python 3.6](https://docs.python.org/3/), 44 bytes
```
lambda A:choices(A,A)[0]
from random import*
```
Yay for built-ins. The other `A` in `choices(A, A)` is an optional `weights` argument.
[Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUcHRKjkjPzM5tVjDUcdRM9ogliutKD9XoSgxLwVIZeYW5BeVaP1PU7BVwKmBKy2/SCFeITMPpCs9VcPQwEDTiktBoaAoM69EI00j2kRHwVBHwTRWU/M/AA "Python 3 – Try It Online")
[Answer]
# Mathematica, 19 bytes
```
RandomChoice[#->#]&
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~8~~ 6 bytes
```
tY"1Zr
```
Try it at [**MATL Online!**](https://matl.io/?code=tY%221Zr&inputs=%5B4%2C+1%2C+5%5D&version=20.4.1)
### Explanation
```
t % Implicit input. Duplicate
Y" % Run-length decoding
1Zr % Randomly take one value with uniform distribution. Implicitly display
```
[Answer]
# [Python 3](https://docs.python.org/3/), 62 bytes
```
lambda k:choice(sum([x*[x]for x in k],[]))
from random import*
```
[Try it online!](https://tio.run/##FYu7DsMgDAD3fIVHEzE0artE6pdQBvKgsVIwcqhEv56Q6aTTXfrnjeO9@te7fl2YFgf7OG9M84rHL6ApvSnWs0ABirBbbaxSnRcOIC4uDRQSS@7rFdEVNf9ZcbipsYMkFDN6NIN@6Gdb6wk "Python 3 – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~88~~ ~~87~~ ~~86~~ 83 bytes
```
a->{int r=0,x=-1;for(int i:a)r-=i;for(r*=Math.random();r<1;)r+=a[++x];return a[x];}
```
[Try it online!](https://tio.run/##TZAxb8IwEIV3fsWNcU0sIrUdaozEUqkDE92iDFdIWtNwji4OBUX57akTUuib7j3bT9/5gCeMXZXTYf/dV81HaXewK7GuYYOW2tkMgmqPPuSFJSzhEF6oxttSFQ3tvHWk3t0b@dfJLS35NFsBgYEe41UbPLBZzM8mTnThOBoC@4KCY2PHgB/MBv2XYqS9O0ZC8zLRgqXBVMpzpjn3DRNgGuauH4j0FWwCnvhOzu7hGLCjrWdLn2kGKNrx4qCRCzhgUf4zuudM305vYGahwS6TxaRgpPzXMohTUlhV5WVdh8Wjv7oM2sd5Mn/qRCblvbm7TdtL7fOjco1XVQD0JUX331wz46VW3l3hIxbi2tHNuv4X "Java (OpenJDK 8) – Try It Online")
[Answer]
# J, ~~8~~ ~~7~~ 8 bytes
The 7 byter is invalid; I'll revert this to a previous edit when I get back to my computer in a day or two.
[Try it online!](https://tio.run/##y/r/P81Wz95BW79auY6LKzU5I18hTcFQwUTB9P9/AA)
```
?@+/{#~
```
:( selecting random elements from an array is costly.
**8 bytes**
```
#~{~1?+/
```
**9 bytes**
```
(1?+/){#~
```
# Explanation
```
?@+/{#~
? Choose random number in range
+/ Sum of the array
{ Select that element from
#~ The elements duplicated as many times as their value
```
[Answer]
# JavaScript (ES6), 50 bytes
```
a=>a.sort((a,b)=>b-a)[Math.random()**2*a.length|0]
```
Hopefully it's apparent how this works, but I'll explain it here anyway. It sorts the integers in descending order, then chooses one at random with a [beta distrubution (1/2,1)](http://www.wolframalpha.com/input/?i=beta+distribution+%281%2F2%2C1%29).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
εD¸.×}˜.R
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3FaXQzv0Dk@vPT1HL@j//2gTHQVDHQXTWAA "05AB1E – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 27 bytes
```
($args[0]|%{,$_*$_})|Random
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0MlsSi9ONogtka1WkclXkslvlazJigxLyU/9////w4aJjqGOqaaAA "PowerShell – Try It Online")
Takes input `$args[0]` as a literal array. Loops through each element `|%{...}` and each iteration constructs a new array `,$_` of `$_` elements -- e.g., for `4` this will create an array `@(4,4,4,4)`. Those array elements are then piped into `Get-Random` which will pluck out one of the elements with (pseudo) equal probability. Since, e.g., for `@(4,1,5)` this gives us `@(4,4,4,4,1,5,5,5,5,5)` this satisfies the probability requirements.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 93 89 87 76+18 = 94 bytes
```
a=>{int i=-1,r=new Random().Next(a.Sum());while(r>=0)r-=a[++i];return a[i];}
```
[Try it online!](https://tio.run/##TY6/q8IwFIVn81fcMcW2KOgU00Vweoqo8IbSIaQXvVBveEnqD0r/9prlgdM533K@Y0NhncepD8RXOL9DxLsS31T@EP8pYTsTAhwHEaKJZGHXs90Qx7rJIUUFF9AwGV0NiYB0scy9ZnzCyXDr7jIrD/iK0pTnPkGmnjfqUPpKLzJfaFPP59Qoj7H3DKZOfZyU@Jc9HLWwN8QyE4OYbR0H12H56yliuofyIpOqbmBY5ut8NaZ9MYpx@gA "C# (.NET Core) – Try It Online")
An extra 18 bytes for `using System.Linq;`
### Acknowledgements
11 bytes saved thanks to Nevay, whose random number implementation was a lot more concise (as well as being an `int` instead of a `double`).
### Degolfed
```
a=>{
int i=-1,
r=new Random().Next(a.Sum());
while(r>=0)
r-=a[++i];
return a[i];
}
```
### Explanation
Get a random number, `r`, between 0 and sum of elements. Then at each iteration subtract the current element from `r`. If `r` is less than `0`, then return this element. The idea is that there are bigger portions of the random number for the larger numbers in the array.
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 7 bytes
```
ËÆD
c ö
```
[Test it here](https://ethproductions.github.io/japt/?v=1.4.5&code=y8ZECmMg9g==&input=WzQsMSw1XQ==)
---
## Explanation
Implicit input of array `U`.
```
Ë
```
Map over the array passing each element through a function where `D` is the current element.
```
ÆD
```
Generate an array of length `D` and fill it with `D`.
```
c
```
Flatten.
```
ö
```
Get a random element.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 5 bytes
```
lS/mR
```
[Try it online!](https://tio.run/##S85KzP3/PydYPzfo/38DBQsFcwVjAA "CJam – Try It Online")
Note: seperate numbers by a space
[Answer]
# Perl, 31 bytes
```
@a=map{($_)x$_}@ARGV;$a[rand@a]
```
This assumes the input to be command line arguments. Note that it may run out of memory if the numbers are large.
[Answer]
# [Perl 5](https://www.perl.org/), 31 + 1 (-a) = 32 bytes
```
@p=map{($_)x$_}@F;say$p[rand@p]
```
[Try it online!](https://tio.run/##K0gtyjH9/9@hwDY3saBaQyVes0IlvtbBzbo4sVKlILooMS/FoSD2/38TBUMF03/5BSWZ@XnF/3V9TfUMDA3@6yYCAA "Perl 5 – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 17 bytes
```
~{.({.}*}%.,rand=
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v65aT6Nar1arVlVPpygxL8X2//9oEwVDBdNYAA "GolfScript – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
F⪪θ;FIι⊞υι‽υ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBI7ggJ7NEo1BHQclaSVNTASzmnFhcopEJ5AWUFmdolOooZGpacwUUZeaVaAQl5qXk52qUampa//9vYm1obfpft@y/bnEOAA "Charcoal – Try It Online") Link is to verbose version of code. Since Charcoal tries to be too clever, I'm having to use semicolon-delimited input for the array. Explanation:
```
θ Input variable as string
⪪ ; Split on semicolons
F Loop i over each string
Iι Cast i to integer
F Repeat that many times
⊞υι Push i to (originally empty) list
‽υ Random selection from list
Implicitly print
```
[Answer]
# [Haskell](https://www.haskell.org/), 87 bytes
```
import System.Random
f l|m<-[x<$[1..x]|x<-l]>>=id=randomRIO(0,length m-1)>>=print.(m!!)
```
[Try it online!](https://tio.run/##HYyxCoMwFEVn8xVP6BBBQwLtZtw7FewoDoJpDM17SkzBgv@ehm73cu65y7S/jfcpOdzWEOH53aNB0U80r8he4E9sm@FoL4MS4hjPo2382HXazTr8N/39wWXtDdm4ADaqynALjqLgWJZVsiDB62DiJxCvmAXKdV5Zkb9ZYYFTdnJkODkCDRaUlDCo@lrfxvQD "Haskell – Try It Online")
[Answer]
# Javascript (ES6), ~~61~~ 54 bytes
-7 bytes thanks to @Justin Mariner
```
a=>a.find(m=>(n-=m)<0,n=Math.random()*eval(a.join`+`))
```
## Example code snippet
```
f=
a=>a.find(m=>(n-=m)<0,n=Math.random()*eval(a.join`+`))
console.log(f([4,1,5]))
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~78~~ 77 bytes
```
import System.Random
f l=randomRIO(0,sum l-1)>>=pure.((l>>= \n->n<$[1..n])!!)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRCG4srgkNVcvKDEvJT@XK00hx7YIzAzy9Ncw0CkuzVXI0TXUtLOzLSgtStXT0MgBMhVi8nTt8mxUog319PJiNRUVNf/nJmbmKdgqpClEG@oYGgCRQawCSGVBUWZeyX8A "Haskell – Try It Online") Usage example: `f [1,99]` probably yields `99`.
### Explanation:
* `f` takes a list of integers `l` and returns the randomly selected integer as `IO Int`.
* `l>>= \n->n<$[1..n]` constructs a list with each element `n` repeated `n` times.
* `randomRIO(0,sum l-1)` yields an integer in the range from 0 to the length of the list of repeated elements, which is exactly the sum of all elements, minus one to avoid a out of bound exception.
---
**Bonus:** 85 byte point-free version
```
import System.Random
(>>=).randomRIO.(,)0.pred.sum<*>(pure.).(!!).(>>= \n->n<$[1..n])
```
[Try it online!](https://tio.run/##HYqxCsMgFAD3fsULdNCSPnSP7p0K6ZhmEGKoNL7I0wz9emsLx8HBvVx@@22rNcS0c4HHJxcfcXS07PG0GmGtkcj/HG93FL1UmNgvmI84XKxIB3uUKLquqc3wpKul4TxpRJpljS4QGFhh0r1WDTXDb0scqNQv "Haskell – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 51 bytes
```
for n in $@;{ printf $n\\n%.s `seq $n`;}|shuf|sed q
```
Takes space-separated or newline-separated input in one argument or multiple arguments.
[Try it online!](https://tio.run/##S0oszvj/Py2/SCFPITNPQcXBulqhoCgzryRNQSUvJiZPVa9YIaE4tRDIS7CurSnOKE2rKU5NUSj8//@/iYKhgikA)
[Validate the random frequencies](https://tio.run/##dVBBasMwELzrFYMiQ9KS1A4NgQZDL/1A6a0pWLHXWGDLiVemhjhvd6U00Fx60Apmd2Z256C5mho9pEkcx5hBN21vHdoSrjO6ZiG4b9JYlG2HAcZCve5QtJjPPY7HFMNiEQBLQlBetZAfxI5foLyoFMfOWFdCRstnRrTc@sJ7KyFn/r2TriP/vw1Hyh0VkfyzyZhOV40sqE8Btzf7M26qyu73Nlrxbdhmu8vIVV@OTAVOU1hq5LZzY2/NCct8/K5MTehIF6iNpaAsjKOG07kKwEL4Xp1mv4dwrmtKNzuo83XoM/664Om6FB7g85LjIc8EDcd/GckvI0R1x7gLpQihrJISkS8hmHumCttAeQMRbpmmZO1FsMEa2x8) with a more complicated test case.
[Answer]
# [Perl 6](http://perl6.org/), 21 bytes
```
{flat($_ Zxx$_).pick}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Oi0nsURDJV4hqqJCJV5TryAzObv2v7VCcWKlghJQ2NZOoTpNw1BPDyipUFGhYGRQq6SQll@kABQyNLD@DwA "Perl 6 – Try It Online")
`$_ Zxx $_` zips the input list with itself using the `xx` replication operator, turning (for example) `(1, 2, 3)` into `((1), (2, 2), (3, 3, 3))`. `flat` flattens that into a list of integers, and finally `pick` picks one at random.
[Answer]
# Java 8, ~~127~~ ~~122~~ 121 bytes
```
import java.util.*;a->{List l=new Stack();for(int i:a)for(int j=i;j-->0;Collections.shuffle(l))l.add(i);return l.get(0);}
```
-1 byte thanks to *@Nevay*.
Uses a similar approach as [*@ErikTheOutgolfer*'s Jelly answer](https://codegolf.stackexchange.com/a/142733/52210), by adding `n` times the item `n` to the list, and then select one randomly from that list.
**Explanation:**
[Try it here.](https://tio.run/##xZA/T8MwEMX3foonJoc6acp/atqFFQpSR8TgJk5x6tiRcwFVVT57cdPCAsxItuy707u73yvlu4xdrWyZr3e6qp0nlCGXtKRNcioAjEZ4liHtCtCbwnJDKs5ca2kwyIxsGjxKbbcDQFtSvpCZwnwfAk/LUmWEjIXKyytkJEK6CzechiTpDHNYTLGT8Wz7oBuCmVr1gQXJbM0iUTi/10JPZPT1L6dalHE8S8W9Myb01842SfPWFoVRzESRSWSeMx0Jr6j1FiZZKWJpJLqdOMyu26UJs48rvDudowoMbEFe21W/6QEgoD@1VLeEcZqCdKUaSHhpc1f1uCvlUfgQ7J0xAWDS6773nqYC@i6IwzMcHrsCi01DqkpcS0kdRhKzScb24L1R2ws@5pddhCFO@Elv2sG2n0Jj2bH@d@WfIMb8jJ/zC37Jr/g1v@G3fJz@wtQNut0n)
```
import java.util.*; // Required import for List, Stack and Collections
a->{ // Method with integer-array parameter and integer return-type
List l=new Stack(); // Create a List
for(int i:a) // Loop (1) over the input array
for(int j=i;j-->0; // Inner loop (2) from `i` down to 0
Collections.shuffle(l))
// and shuffle the List randomly after every iteration
l.add(i); // Add `i` that many times to List `l`
// End of inner loop (2) (implicit / single-line body)
// End of loop (1) (implicit / single-line body)
return l.get(0); // And then return the first item of the list
} // End of method
```
[Answer]
# [Dyalog APL](https://www.dyalog.com/), 8 bytes
```
/⍨⌷⍨1?+/
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20TqjX0H/WueNSzHUga2mvraz7q3WxWe2gFkDI2@P8fAA "APL (Dyalog Classic) – Try It Online")
## How?
* `/⍨`, `n` copies of `n` for each `n` in the argument.
* `⌷⍨`, at the index of
* `1?`, a random value between `1` and
* `+/`, the sum of the argument
[Answer]
# GNU APL 1.2, 26 23 bytes; 1.7 21 19 bytes
Approach inspired by [Erik the Outgolfer's Jelly answer](https://codegolf.stackexchange.com/a/142733/14280). Relies on `⎕IO` being 0 instead of 1, which is the default for GNU APL (sort of +5 bytes for `⎕IO←0`).
-3, -2 bytes thanks to @Zacharý
`∇` function form
```
∇f R
S[?⍴S←∊0 0⍉R∘.⍴R]∇
```
Anonymous lambda form
```
{S[?⍴S←∊0 0⍉⍵∘.⍴⍵]}
```
For the explanation, I will use `⍵` to represent the argument passed to the function, but it is equivalent to `R` in the `∇` form.
`⍵∘.⍴⍵` computes the outer product on the list using the reshape (`⍴`) operator. Effectively, this creates a table (like a multiplication table) but instead of multiplying, it repeats the element in the column a number of times equal to the element in the row. For the example given in the question, this is:
```
4 4 4 4 1 1 1 1 5 5 5 5
4 1 5
4 4 4 4 4 1 1 1 1 1 5 5 5 5 5
```
`0 0⍉⍵∘.⍴⍵` transposes the matrix and returns just the main diagonal. This gives us just the parts where the row and column in `⍵∘.⍴⍵` were the same i.e. we repeated the number a number of times equal to its value. For the example, this is:
```
4 4 4 4 1 5 5 5 5 5
```
`∊` turns its argument into a list. Using the transpose (`⍉`) operator, we got a vector containing 3 vectors. Enlist (`∊`) turns it into a single vector containing all the elements.
`S←...` assigns this new vector to vector `S`. `⍴S` gives us the length of that list. `?` is the random operator, so `?⍴S` gives us a random number between 0 and the length of the list (exclusive) (this is why it relies on `⎕IO` being 0; otherwise it's between 1 and the length, inclusive). `S[...]` returns the element at the given index.
] |
[Question]
[
An Automorphic number is a number which is a suffix of its square in base 10. This is sequence [A003226](https://oeis.org/A003226) in the OEIS.
## Your Task:
Write a program or function to determine whether an input is an Automorphic number.
## Input:
An integer between 0 and 10^12 (inclusive), that may or may not be an Automorphic number.
## Output:
A truthy/falsy value indicating whether or not the input is an Automorphic number.
## Examples:
```
0 -> truthy
1 -> truthy
2 -> falsy
9376 -> truthy
8212890625 -> truthy
```
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 24 bytes
```
lambda n:`n*1L`in`n**2L`
```
[Try it online!](https://tio.run/##RYxBDsIgEEX3c4pZlsYFYKxtk96gN6iNoIKS6LQBNp4eaVn4Nu8vXv76ja@FZLLDJb315/bQSL2iWozKUXYtR5WiCfF618EEHHACzPDDLlEki7rjuSmrlUK2HW/kCWYAu3h06Aj/R/2erd5RRFs5BlD2RLjVtNVe09NUgm8wdDaHxOb0Aw "Python 2 – Try It Online")
For the first time in history, Python 2's appending an `L` to the repr of longs is a feature rather than a bug.
The idea is to check if say, `76^2=5776` ends in `76` by checking if `76L` is a substring of `5776L`. To make the `L` appear for non-huge numbers, we multiply by `1L` or have `2L` as the exponent, since an arithmetic operation with a long with produces a long.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
~√a₁?
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v@5Rx6zER02N9v//WxqbmwEA "Brachylog – Try It Online")
## How it works
```
~√a₁?
~√ the input is the square root of a number
a₁ whose suffix is
? the input
```
[Answer]
# [Python 2](https://docs.python.org/2/), 31 bytes
Out-golfed by xnor... (this happens every single time) >< But hey, it's surprisingly Pythonic for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
People don't tend to remember Python has `str.endswith()`...
```
lambda n:str(n*n).endswith(`n`)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPqrikSCNPK09TLzUvpbg8syRDIyEvQfN/SWpxSXxyYnFqsYKtQjSXAhAY6IApQwhlBKEsjc3NICwLI0MjC0sDMyNTrlgurrT8IoVMhcw8BYRBVmBlBUWZeSUKaRqZmv8B "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
n.s¹å
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/T6/40M7DS///tzQ2NwMA "05AB1E – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 44 bytes
```
$
;918212890625;81787109376;0;1;
^(\d+;).*\1
```
[Try it online!](https://tio.run/##K0otycxL/P9fhcva0tDCyNDIwtLAzMjU2sLQ3MLc0MDS2NzM2sDa0JorTiMmRdtaU08rxvD/f5AwAA "Retina – Try It Online")
There are exactly 4 solutions to the 10-adic equation `x*x = x`.
[Answer]
## [Alice](https://github.com/m-ender/alice), 17 bytes
```
/o.z/#Q/
@in.*.L\
```
[Try it online!](https://tio.run/##S8zJTE79/18/X69KXzlQn8shM09PS88n5v9/czMA "Alice – Try It Online")
Outputs nothing (which is falsy in Ordinal mode) or `Jabberwocky` (which is non-empty and therefore truthy in Ordinal mode; it's also the canonical truthy string value).
### Explanation
```
/.../#./
....*..\
```
This is a slight modification of the general framework for linear Ordinal mode programs. The `/` in the middle is used to have a single operator in Cardinal mode in between (the `*`) and then we need the `#` to skip it in Ordinal mode on the way back. The linear program is then:
```
i..*.QLzno@
```
Let's go through that:
```
i Read all input as a string and push it to the stack.
.. Make two copies.
* This is run in Cardinal mode, so it implicitly converts the top two
copies to their integer value and multiplies them to compute the square.
. Implicitly convert the square back to a string and make a copy of it.
Q Reverse the stack to bring the input on top of the two copies of its square.
L Shortest common supersequence. This pops the input and the square from
the top of the stack and pushes the shortest string which begins with
the square and ends with the input. Iff the square already ends with the
input, this gives us the square, otherwise it gives us some longer string.
z Drop. Pop the SCS and the square. If the square contains the SCS (which
would mean they're equal), this removes everything up to the SCS from
the square. In other words, if the SCS computation left the square
unchanged, this gives us an empty string. Otherwise, it gives us back
the square.
n Logical not. Turns the empty string into "Jabberwocky" and everything
else into an empty string.
o Print the result.
@ Terminate the program.
```
[Answer]
# Mathematica, 31 bytes
```
Mod[#^2,10^IntegerLength@#]==#&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvvfNz8lWjnOSMfQIM4zryQ1PbXIJzUvvSTDQTnW1lZZ7X9AUWZeiYJDmoKDqaWloYWRoZGFpYGZkel/AA "Mathics – Try It Online") Mathics prints an extra message but the answer is correct
[Answer]
# Python 2, ~~37~~ ~~33~~ ~~30~~ 29 bytes
```
lambda n:n*~-n%10**len(`n`)<1
```
Saved 4 bytes thanks to @LeakyNun.
Saved 3 bytes by noticing that the input is lower than 10^12 so `n` doesn't end with an "L".
Saved 1 byte thanks to @Dennis because I miscounted in the first place.
[Try it online!](https://tio.run/##K6gsycjPM/pfUJSZV6KQlplTklqk8T8nMTcpJVEhzypPq043T9XQQEsrJzVPIyEvQdPG8L@OQlFiXnqqhqEBGGhq/gcA) (TIO link courtesy of @Dennis).
[Answer]
# Ruby, 22 bytes
```
->n{"#{n*n}"=~/#{n}$/}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWkm5Ok8rr1bJtk4fyKpV0a/9H82loGCgAyQMQYQRiLA0NjcD0RZGhkYWlgZmRqZcsXqpickZCtUKNXk1CgWlJcUKiopp0XmxCrX/AQ "Ruby – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 57 bytes
```
f(__int128 n){n=n*n%(long)pow(10,printf("%u",n))==n;}
```
Based on @betseg's answer, this is a function that returns **1** or **0**. It produces garbage output to STDOUT, which is [allowed by default](https://codegolf.meta.stackexchange.com/a/9658/12012).
The score contains **+4 bytes** for the compiler flag `-lm`.
[Try it online!](https://tio.run/##VY9NasQwDIXX0SlESordSZ1kVoX8nKQwuE48MThy8NjtYpizp6Ltpto8CYnv6X3o23oYnXBCnVPYQtxXZ5TBYUB1WHG5OErd@Q1J3mmkF6qED3SVe/gSXVvvkddWlFUua5JyHKl/HE@OjM/zgsMtzS6odQLgM9y0IyHhDoUNEX84SDhi27MM2LW/xdPpJKEonEVhBWO5L@yfFSOXGGssq/mdypr/6uEBCuBqDL767X8MUI1WISc8T88dZ2zm5bOh7P3xDQ "Bash – Try It Online")
[Answer]
# R, 28 bytes
```
pryr::f(x^2%%10^nchar(x)==x)
```
Creates a function:
```
function (x)
x^2%%10^nchar(x) == x
```
Takes the modulus of `x^2` such that we keep the last digits, which we compare to `x`.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 47 bytes
```
n=>$"{BigInteger.Multiply(n,n)}".EndsWith(n+"")
```
[Try it online!](https://tio.run/##TY1Bq8IwEITv/RVL8ZDyNBdFeVQ9KAqCiqjgOaRrXWg3kk0Fkf722gqCc5sZ5hsrA@s8NpUQ53B6SsAyjX6d3lclerKSRrYwInDwLvemfEUAEkwgCw9HGewMsUq6FGBdsZ1uOIxH/YVzBRqewxVmDc/mvfi1oLztMEevd1UR6F48Ffc5qWO94kwuFG6K/@I4aTpW@iEuHUsL0hdPAdVVtf6BPuiz@9yob39Ek22JUSWtumkd1c3/cDJ@Aw "C# (.NET Core) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 11 bytes
```
I¬⌕⮌IXIθ²⮌θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9npWH1jzqmfpoXQ@Q@X7PDiB5bsehTUD@uR3//1sam5sBAA "Charcoal – Try It Online")
Returns `False` as `falsey` and `True` as `truthy`.
* 1 byte saved thanks to ASCII-only! (How could I miss the `Power` function?)
[Answer]
# JavaScript (ES6), 23 bytes
```
n=>`${n*n}`.endsWith(n)
```
---
## Try it
Wrote this Snippet up on my phone, so please edit if it's not working correctly.
```
f=
n=>`${n*n}`.endsWith(n)
oninput=_=>o.innerText=f(+i.value);o.innerText=f(i.value=1)
```
```
<input id=i type=number><pre id=o>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
²ṚwṚ⁼1
```
[Try it online!](https://tio.run/##y0rNyan8///Qpoc7Z5UD8aPGPYb///@3NDY3AwA "Jelly – Try It Online")
[Answer]
# Kotlin, 36 bytes
```
fun a(i:Int)="${i*i}".endsWith("$i")
```
[Answer]
# C, 77 + 4 (`-lm`) = 81 bytes
```
#import<tgmath.h>
i;f(long double n){i=fmod(n*n,pow(10,(int)log10(n)+1))==n;}
```
[Try it online!](https://tio.run/##XY1LDoIwFEXnrIJoSPoUhMZIUcSVOMFiS5P2lWCNA8LWrTJSGN5zfzyRnHu/VqazvTs7aWrX7tpLoEpBtEUZNvZ50/cQYVCVMLYhuMG4sy9Cs5godKCtpBlB2FKAqsJy9GlqaoUEhq7/BgRZRc0qFiQHKMdgYRWUFYxmxz07nMKoueIP5EvAJjAt/ZVgJvO5ZNOjf3Oha/nwiTYf "C (gcc) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 15 + 1 (-p) = 16 bytes
```
$_=$_**2=~/$_$/
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lYlXkvLyLZOXyVeRf//f9N/@QUlmfl5xf91CwA "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
²_ọæċ⁵$
```
[Try it online!](https://tio.run/##y0rNyan8///QpviHu3sPLzvS/ahxq8r///8tjc3NAA "Jelly – Try It Online")
Positive number for yes, 0 for no.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~47~~ 33 bytes
14 bytes thanks to Martin Ender.
```
.+
$*
$
¶$`
\G1
$%_
M%`1
(.+)¶\1$
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLhevQNpUErhh3Qy4V1XguX9UEQy4NPW3NQ9tiDFX@/zc3AwA "Retina – Try It Online")
[Answer]
# [PHP](https://php.net/), 41 bytes
```
<?=preg_match("#$argn$#",bcpow($argn,2));
```
[PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/bd634da28574a838b859407ccbc0f911cb4729fc)
# [PHP](https://php.net/), 42 bytes
without Regex
```
<?=strtr(bcpow($argn,2),[$argn=>X])[-1]>A;
```
# [PHP](https://php.net/), 44 bytes
Use the [levenshtein](http://php.net/manual/en/function.levenshtein.php) distance
```
<?=!levenshtein($argn,bcpow($argn,2),0,1,1);
```
[Answer]
# [Dyvil](https://github.com/dyvil/Dyvil), 26 bytes
```
x=>"\(x*x)".endsWith"\(x)"
```
Usage:
```
let f: int->boolean = x=>"\(x*x)".endsWith"\(x)"
print(f 20) // false
```
[Answer]
## Batch, 122 bytes
```
@set/an=%1,t=f=1
:l
@set/at+=t,f*=5,n/=10
@if %n% gtr 0 goto l
@cmd/cset/a"(!(%1%%t)|!(~-%1%%t))&(!(%1%%f)|!(~-%1%%f))
```
Algorithm is limited only by the integer type used for variables. In the case of Batch, this is 32-bit signed integers, so the maximum is 2147483647. Works by testing both n and n-1 for necessary powers of 2 and 5 as factors. (Except when n is 0 or 1, n and n-1 will have one factor each.)
[Answer]
## [><>](https://esolangs.org/wiki/Fish), 30 bytes
```
1&0}\{n;
:&(?\:::*&a*:&%={+}:&
```
[Try it online](https://tio.run/##S8sszvj/31DNoDamOs@ay0pNwz7GyspKSy1Ry0pN1bZau9ZK7f///7plCqaWloYWRoZGFpYGZkamAA "><> – Try It Online"), or watch it at the [fish playground](https://fishlanguage.com/playground)!
Assumes the input number *x* is already on the stack.
Explanation: The fish takes the quotient of *x*2 by increasing powers of 10, and counts how many times this equals *x*. When the power of 10 gets larger than *x*, it prints the count and halts. The count will be 1 if *x* is automorphic, and 0 if it isn't.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 23 bytes
```
n->n^2%10^#digits(n)==n
```
[Try it online!](https://tio.run/##FcrdBoBAEIbhW/mUaJlld9LfwXYjKSJlyRjVSVe/1dn78OpyRrtr2hCQxA4yc@HdnK9xj/dViglB0qJ6PKXADtAzyv1l9iPD9h2GMDqCJzChr9qG0LHnrncN15NJLw "Pari/GP – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~10~~ 9 bytes
-1 byte thanks to [isaacg](https://codegolf.stackexchange.com/users/20080/isaacg).
```
x_`^vz2_z
```
Returns 0 when the number is automorphic, anything else if it is not.
[Test it online!](https://pyth.herokuapp.com/?code=x_%60%5Evz2_z&input=8212890625&debug=0)
**Explanations**
```
x_`^vz2_z
^vz2 # Evaluate the input to a number, compute the square
` # Convert the squared number to a string
_ # Reverse it
x _z # Find the index of the first occurrence of the reversed input in the reversed square. That's basically equivalent of doing an endswith() in Python
# Implicit input of the index. If 0, then the reversed square starts with the reversed input
```
[Answer]
# [Rexx (Regina)](http://www.rexx.org/), 48 bytes
```
numeric digits 25
arg n
say right(n*n,length(n))=n
```
[Try it online!](https://tio.run/##K0qtqPj/P680N7UoM1khJTM9s6RYwdSAK7EoXSGPqzixUqEoMz2jRCNPK08nJzUvvSRDI09T0zbv/39LY3MzMAEA "Rexx (Regina) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 45 bytes
```
f=reverse.show
g a=and$zipWith(==)(f a)$f$a^2
```
[Try it online!](https://tio.run/##BcGxCoAgEADQva9wcNBFrOb7joYoOOjUIzNRKejn7b2A9aQYe3dQ6KFSydRwv4MXCJgO@XFeuAUFoJUTqKWTuE/9Qk6QC6cmHcdGRfh1NGa2dus/ "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/) + [Data.Function](http://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Function.html), 42 bytes
```
g a=and$on(zipWith(==))(reverse.show)a$a^2
```
[Try it online!](https://tio.run/##BcExDsMgDADArzAwwIKSLJnYqn6hQ5VKVuoGK8Qg4zRSP0/vErQdc@501CJqbqAQ7ievSoX7ZiACv21h96P6IE0uRu@d4BelYWipXB4svKZ@AHGsQqz2Q1lRzPYcQ5iHYel/ "Haskell – Try It Online")
```
and.(on(zipWith(==))(reverse.show)<*>(^2))
```
[Try it online!](https://tio.run/##BcExDsIwDADAr3RgsBmswsJCmBBfYEBUisA0FqkTOYZKfD7cpdjenHOXpRbz4Rw90uWjD5eifQ5RnwRF4Sf1Kp4gBEQw/rI1ppbKisftCaY9Yl@iaKgm6puXZGcb5tuO6DCO9/4H "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/) + [Data.Function](http://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Function.html) + [Control.Monad](http://hackage.haskell.org/package/base-4.10.0.0/docs/Control-Monad.html), 40 bytes
```
and.ap(on(zipWith(==))$reverse.show)(^2)
```
[Try it online!](https://tio.run/##LcihDsIwEABQz1dMTLTmMmZQVRAceoKw5MLKeqG7a64HJPx8MTz5EtZnzLnRVkStO6EhnF98NxLe/fMobCoZLsK4tDUgL4DFCbsvlYksuRC87zW@o9YINcnHu3n0bUPiUJTY@gdli9qt1z3AYRhu7Qc "Haskell – Try It Online")
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~36~~ 34 bytes
```
param([bigint]$a)""+$a*$a|% En* $a
```
[Try it online!](https://tio.run/##VY/LasJQEIbXOU8xyFgSq6ARrVKEQOm6UpcS5CROrCW3ngstaJ79dFJjxeX334apq29S@oPyfJRWihxmq5OrpZKFv02Oh2NpYpRBr/eIcoDy3IfXcgAoXSNE5AtvGPnjIaBRloI/mtxRyJTJXHe4nD7N7/xFOAkXy/E8nP3LAZyhDyfhYWmLhBQb9FNTamgPK8AdG4q0zQ3TA2bQxYS3XW9erDZV8ZZ8cjyOeMPb2DQlrdtm1xrR122RE@v2VzKk2sxl65nl9@uNrsdaIxrnfgE "PowerShell Core – Try It Online")
Could be 8 bytes shorted if passing a `bigint` as parameter was allowed
-2 bytes thanks to *Zaelin Goodman*!
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 3 bytes
```
²øf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQciIsIiIsIsKyw7hmIiwiIiwiNjciXQ==)
First time using the `r` flag.
] |
[Question]
[
## Introduction
You're making a robot that can navigate a set of books of varying heights. It can climb books and jump off books, but if the distance is too big it will stop to prevent damage. To figure out the ideal design, you're writing a simulator.
Your program will take as input a list of numbers, representing the heights of the books in the bookshelf, as well as a number indicating the durability of the robot. Starting from the first item of the list, your robot will traverse the bookshelf. If the robot comes across a change in height, it will only be able to continue if the change is less than or equal to the robot's durability. Your job is to output which book the robot is on when it stops, starting from either 0 or 1. You may safely assume that the height of the first book the robot is on will be equal to or less than the robot's durability.
## Scoring
This is code-golf, so shortest answer wins.
## Examples (starting from 1)
```
[1, 1, 1], 1 -> 3
[0, 1, 0], 0 -> 1
[1, 2, 3, 2], 1 -> 4
[1, 3, 4, 4, 0], 2 -> 4
[1, 3, 4, 4, 0, 1], 2 -> 4
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
dÔí°If[Abs[#2-#]>d,0,1+#0@##2,0]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P@X9pIWeadGOScXRyka6yrF2KToGOobaygYOyspGOgaxav8DSzNTSxwCijLzSqKrlZVrde3SgEpjHRyUY9UcHByquaqrDXWAsBaEwBwjEMsAzjHWMULIGeuYAKEBiG9Uy1X7HwA "Wolfram Language (Mathematica) – Try It Online")
Input `[durability][heights...]`. Returns 0-indexed.
```
If[Abs[#2-#]>d ] is the next height difference out of limits?
,0 yes: 0
,1+#0@##2 no : recurse on tail and add 1
,0 err: 0 (input len <2)
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, ~~37~~ 35 bytes
*2 bytes saved thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)!*
```
@(x,d)sum(cumprod(abs(diff(x))<=d))
```
Output is 0-based.
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0InRbO4NFcjuTS3oCg/RSMxqVgjJTMtTaNCU9PGNkVT83@aRrShjgIIxQKxJheEbwThGyDxjYEkshIg3wSMDICiRpr/AQ)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
¯ȧ<1JTh
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCr8inPDFKVGgiLCIiLCJbMSwgMiwgMywgMV1cbjUiXQ==)
```
¯ȧ # Get absolute differences
< # Find all less than the input
1J # Append a 1
h # Get the first...
T # Index of a 1
```
[Answer]
# JavaScript (ES7), 41 bytes
*-6 thanks to @emanresu A*
```
d=>f=([a,...x])=>(a-x[0])**2<=d*d&&-~f(x)
```
# JavaScript (ES7), 42 bytes
```
d=>f=([a,...x])=>(a-x[0])**2<=d*d?f(x)+1:1
```
Recursive solution. Takes input via currying, robot durability first.
Relies on `NaN <= x` always being false, saving a check to see if `x` is long enough.
[Answer]
# [Emojicode](http://www.emojicode.org/), 272 bytes
```
üèÅüçáüíØüÜïüî°üëÇü躂ùóÔ∏è‚ùóÔ∏è‚û°Ô∏èdüé∂üÜïüî°üëÇü躂ùóÔ∏è‚ùóÔ∏è‚û°Ô∏èl l‚û°Ô∏èüñçüÜïa 0‚û°Ô∏èüñçüÜïcüê®a 0‚ùóÔ∏èüîÇv aüçá‚Ü™Ô∏èüç∫üíØv‚ùóÔ∏è‚ûñüç∫üíØüêΩl c‚ùóÔ∏è‚ùóÔ∏è‚ñ∂üôåüç∫düçáüö™üêáüíªc‚ùóÔ∏èüçâc‚¨ÖÔ∏è‚ûï1üçâüö™üêáüíªc‚ùóÔ∏èüçâ
```
[Try it online!](https://tio.run/##S83Nz8pMzk9JNfv//8P8/sYP83vbP8yftP7D/LapH@ZPWfhh/sQmoPieR3Onv9/RDyXnLQSSKR/m920jrCxHIQfC@DB/Wi9IeaKCAapA8of5E1aARMG6gKY1lSkkgtzxqG0VWKB3F8hFZTBTp8FEgPr25igko9g5DeikmT0gFSkQr8xaBVQG8tLuZJgFvZ3Jj9a0gs2aagji4lD1/78hlyEQAAA "Emojicode – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) + `-pa`, 40 bytes
```
//,$\++while!eof&&"@F">=abs+($_=<>)-$'}{
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiLy8sJFxcKyt3aGlsZSFlb2YmJlwiQEZcIj49YWJzKygkXz08PiktJCd9eyIsImFyZ3MiOiItcGEiLCJpbnB1dCI6IjJcbjFcbjNcbjRcbjRcbjAifQ==)
## Explanation
Thanks to `-pa` the durability is stored in `$_` (although this is quickly overwritten) and `@F`. This then loops `while` STDIN is not `eof` and `"@F"` (interpolates the values in `@F`, just the durability in this case) is greater than the next input (retrieved with `<>` and stored in `$_`) subtracted from the remainder of the previous `m//`atch (which starts out empty, `0` in numeric context). The body of the `while` is matching against nothing, purely to store the previous value in `$'` without having to set manually, and incrementing `$\`, which is automatically output thanks to `-p`. The final `}{` is to break out of the implicit `while (<STDIN>)` from `-p` (well, `-n` which is implied by `-p`) to prevent `$_` being output as well.
[Answer]
# [Python 3](https://docs.python.org/3/), 80 bytes
Returns 0-based index.
```
lambda l,n:next((i for i,(a,b)in enumerate(zip(l,l[1:]))if abs(a-b)>n),len(l)-1)
```
[Try it online!](https://tio.run/##fY@9CsMwDIT3PoVGCRTIT6dA@yJpBpva1KAoIXWg7cu7TrJ0ScVJy3fHoekdH6M2yV9uScxg7waEtVX3iogB/DhDYDRsKSg4XQY3m@jwEyYUlq5qe6LgwdgnmsLSVYnFKQoVFaU1LewgRzvsKoZVfV5iOMHPbLDeYXkEm3wPwxmeN5XZUhP/c@w9NfXt5prmoBF9/gccUfoC "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
5 if we may output 1-indexed and modular (i.e. yield 0 for the rightmost) - remove `;1`
```
IA>;1T·∏¢
```
A dyadic Link accepting a list and an integer that yields the 1-indexed stopping point.
**[Try it online!](https://tio.run/##y0rNyan8/9/T0c7aMOThjkX///@PNtRRMNZRMAEjAx0Fw9j/RgA "Jelly – Try It Online")**
### How???
```
IA>;1T·∏¢ - Link: list, B; integer, D
I - incremental differences of B
A - absolute values
> - greater than D?
;1 - concatenate a one
T - truthy 1-indexed indices
·∏¢ - head
```
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
(a:b:r)!s|s<abs(a-b)=1
(h:t)!s=1+t!s
x!_=0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/XyPRKsmqSFOxuKbYJjGpWCNRN0nT1pBLI8OqBChoa6hdoljMVaEYb2vwPzcxM0/BViEln0uhoCgzr0RBRSHaUEcBhGIVFBUMUYWNoMIGGMLGQBKLBqCwCRgZgCSNuBT@w00HYgVdOwVjLrjBQFUgEUMuZDOhyky40IwDyoHFAQ "Haskell – Try It Online")
Three definitions of infix `!`
* 1st: guards against big step stopping the robot.
* 2nd: step was fine, continue.
* 3rd: end of list.
Due to 1 indexing it was possible to save something by reaching end of list instead of ending at a single element e.g. [x]!\_=0
[Answer]
# [Factor](https://factorcode.org/), ~~50~~ 43 bytes
```
[ differences vabs [ >= ] with count-head ]
```
[count-head](https://docs.factorcode.org/content/word-count-head,sequences.extras.html) postdates build 1525, the one TIO uses, so here's a screenshot running this in Factor's REPL:
[](https://i.stack.imgur.com/E9coq.gif)
## Explanation
Takes input as `durability heights`. 0-indexed. `count-head` is a combinator that applies a quotation to each element of a sequence, counting how many times the quotation returns `t` and stopping once an `f` is encountered.
```
! 2 { 1 3 4 4 0 }
differences ! 2 { 2 1 0 -4 }
vabs ! 2 { 2 1 0 4 }
[ >= ] with count-head ! 3
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¥Ä‹1ª1k
```
0-based.
[Try it online](https://tio.run/##yy9OTMpM/f//0NLDLY8adhoeWmWY/f9/tKGOsY4JEBroGMZyGQEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC8f9DSw@3PGrYaXholWH2f53/0dHRhjpAGAtCCiCOEYhlAOcY6xgh5Ix1TIAQKGmEKgBSYBQbCwA).
**Explanation:**
```
¥ # Get the deltas/forward-differences of the first (implicit) input-list
Ä # Convert each to its absolute value
‹ # Check for each integer in the list whether the second (implicit)
# input-integer is smaller than it
1ª # Append a trailing 1
1k # Pop the list, and push the (0-based) index of the first 1
# (which is output implicitly as result)
```
---
Could be 5 bytes if we're allowed to output a modular index, so it'll output `-1` if it's able to travel across all books:
```
¥ÄÅΔ‹
```
[Try it online](https://tio.run/##yy9OTMpM/f//0NLDLYdbz0151LDz//9oQx1jHRMgNNAxjOUyAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P9DSw@3HG49NyWi@FHDzv@1Ov@jo6MNdYAwFoQUQBwjEMsAzjHWMULIGeuYACFQ0ghVAKTAKDYWAA).
**Explanation:**
```
¥Ä # Same as above
ÅΔ # Push the first 0-based index which is truthy for
# (or -1 if none were truthy)
‹ # Check if the second (implicit) input-integer is smaller than the
# current integer
# (after which the found index is output implicitly as result)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~56~~ ~~51~~ 49 bytes
```
f(a,n,d)int*a;{n=!--n||(*a-*++a)/~d?:1+f(a,n,d);}
```
[Try it online!](https://tio.run/##bZLfToMwFMbv9xRHEhL@lGyM7cIh7sL4FBtZSFsmUctCSSRu@OjioYWOqU05hf6@0/O1hQZHSrsudzIiCHMLUXtZfBbJXRCIy8XxssDz/cydf7HtJvRHWdx2qIT3rBCOC@cZYOsnai7rcJdCAueQQN/b2IClActbEE1BhHHCVoYhWKm@mOADM3yhCk5zD0LDaExeY2zj0a2nRFJrlHOifeoh0sMkAXhz4rTmzCwbak@DhJZC1kBfssrDyOkrr7TS2jfPy31z/4TP2iIw/Y6sITsvK3D6KoVgvMG0RTy8PoAsPnmZO2N9dz5MeGYmBt9Xalctpq/kulFcTm9WadJ4ioENFA/zPyxGLP7gq@fBL3oVyoprNH07VSjKHcuWNsP9F9v@EDbWDod6V6TubUGJi@VOrf@0G8KRmEv4bWYskhKwGQSPfbTlXmARRkASMJfCk0SORdtZ233T/C07yi74@AE "C (gcc) – Try It Online")
*Saved 5 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!!*
*Saved 2 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!!*
Inputs a pointer to an array of integers, its length (because pointers in C carry no length info), and the durability of the robot.
Returns to the number of the book (starting at \$1\$) that the robot stops at.
[Answer]
# [Python 3](https://docs.python.org/3/), 53 bytes
```
s=lambda d,f,*t,p=0:d<abs(f-p)or t==()or-~s(d,*t,p=f)
```
[Try it online!](https://tio.run/##TY3BCsMgEETv/Yq5RYOCTXoKtT8ScjCIGGiNRC9F7K9bk1wCs7u8mYH132hX15cS5Ft9Zq2gmWFtZF6KQT/VHIjhnq4bopSkXv4LRJ8FQ4upgWUai8NIxjvDrqkOZTi4O1lcuK/7Wqn8OCSq29FpuAHw2@IiMU2yGUln8BfS/hitpbmh5Q8 "Python 3 – Try It Online")
Input is taken as varargs. Surprisingly the 1-based indexing makes the code shorter, since "or" is a byte shorter than "and".
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I am ridiculously out of practice! 0-indexed.
```
äa pVÄ b>V
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=5GEgcFbEIGI%2bVg&input=WzEsMyw0LDQsMF0KMg)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
Output is 0-base
```
LengthWhile[Abs@Differences@#-#2,#<=0&]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Yb898nNS@9JCM8IzMnNdoxqdjBJTMtLbUoNS85tdhBWVfZSEfZxtZALVbtf0BRZl5JdFp0taGOAgjVAnFsrDUXsrgRRNwAi7gxkMSmBShuAkYGQFkjkOx/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
I⌕Eθ∨⁼κ⊖Lθ‹η↔⁻ι§θ⊕κ¹
```
[Try it online!](https://tio.run/##RYxNC8IwEET/yh43sIJVb57EDyi06L30EJPFhsatTVLx38eqB4fhHQbemE4HM2if8yU4SbjXMeHJicVaP3AkOAc8jpP2EXuCA5vAd5bEFiuWW@pwVEoRVBwjdgS7axz8lBhrJ1NENy@pFMuvz1Upf7tXvxAUM7c5N01BsCbYfLtsCVZtXjz9Gw "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation:
```
θ Input list
E Map over values
κ Current index
⁼ Equals
θ Input list
L Length
‚äñ Decremented
‚à® Logical Or
η Input durability
‹ Is less than
ι Current value
↔⁻ Absolute difference with
θ Input list
§ Indexed by
κ Current index
‚äï Incremented
‚åï Find index of
¬π Literal integer `1`
I Cast to string
Implicitly print
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 21 bytes
```
{*&(y<x|-x:1_-':x),1}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rWUtOotKmo0a2wMozXVbeq0NQxrOXiSos2VABCawXDWG1DMM8IxDNA8IwVjJBkjRVMgNDAWsEITQSkCyQGADZFFyg=)
[Answer]
# [Julia 1.0](http://julialang.org/), 37 bytes
```
h/r=findfirst(abs.(diff([h;Inf])).>r)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P0O/yDYtMy8lLbOouEQjMalYTyMlMy1NIzrD2jMvLVZTU8@uSPM/l0NxRn65gr5GtKGOAgjFArGmgq2tgjGKlBFEygAsZYguZQwk4RpNUGSBUiZgZABUYARV8B8A "Julia 1.0 – Try It Online")
**35 bytes** porting @LuisMendo's Octave solution: `h/r=sum(cumprod(abs.(diff(h)).<=r))`
[Answer]
# [Python 3](https://docs.python.org/3/), 71 bytes
```
lambda h,d:([abs(h[i+1]-h[i])>d for i in range(len(h)-1)]+[1]).index(1)
```
[Try it online!](https://tio.run/##TY7BCoMwDIbve4rcTLAOqzsJ@iJdD5XWteBqUQ8b4rN31V2EPwlf@AgJ39VOvo7LasLSPuOo3r1WYJluUKh@QStczmWRhqROwzDN4MB5mJV/GRyNR0sFJ5kLLunuvDYf5BQPLx05TIGCMzgiUxGDk6s/lxeuU78qiR9nyrStSDY3AAiz8ysO2WZ32PQORQfb@TxaBpr2jOIP "Python 3 – Try It Online")
[Answer]
# APL+WIN, ~~12~~ 14 bytes
Plus 2 bytes to accomodate new example suggested by @chunes
Prompts for heights then durability. Index = 1
```
+/^\1,⎕≥|-2-/⎕
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv7Z@XIyhDlDwUefSGl0jXX0g8z9Qhut/GpehAhByGXKBWEZANpcBlGkMxFBxYwUTIDTgMkLmAXUZAQA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 58 bytes
```
\d+
$*
,(1*)(1*)(?=,\1(1*))
,$2$3
(1*)(,(?!1\1)1*)*,.*
$#2
```
[Try it online!](https://tio.run/##HYgxDoAwDAP3/AKRoQ0RalLWqh/pggQDCwPi/yFEln22n/O97t1sHAsgASehHO6Nh/wtA6NihXg59UmGZO/EKwHOaiYcguKpTglWVvDl3FzlAw "Retina 0.8.2 – Try It Online") Link includes test cases. 0-indexed. Takes the durability first followed by the list of heights. Explanation:
```
\d+
$*
```
Convert to unary.
```
,(1*)(1*)(?=,\1(1*))
,$2$3
```
Take the absolute difference between each height and the next (`$2` is for the positive difference, `$3` for the negative). Note that the last height remains in the input.
```
(1*)(,(?!1\1)1*)*,.*
$#2
```
Match the durability and as many differences that don't exceed the durability, then replace everything with the count of those differences. (The comma is necessary to avoid matching the last height.)
[Answer]
# x86-16 machine code, 17 bytes
```
00000000: 33ff 47ac 2a04 7302 f6d8 3ac4 7702 e2f2 3.G.*.s...:.w...
00000010: c3 .
```
Listing:
```
33 FF XOR DI, DI ; zero jump counter
BOOK_LOOP:
47 INC DI ; increment jump counter
AC LODSB ; AL = current height
2A 04 SUB AL, [SI] ; AL = AL - next height
73 02 JAE IS_POS ; is positive?
F6 D8 NEG AL ; if not, negate to get abs value
IS_POS:
3A C4 CMP AL, AH ; over threshold?
77 02 JA DONE ; if so, push the AZ-5 button
E2 F2 LOOP BOOK_LOOP ; otherwise, keep plugging
DONE:
C3 RET ; return to caller
```
Input list at `[SI]`, length in `CX`, threshold in `AH`. Output stopping index (1 based) in `DI`.
About as vanilla asm as you can get. Any time I tried to get clever it was more bytes...
[Answer]
# [R](https://www.r-project.org/), ~~43~~ 42 bytes
*Edit: -1 byte thanks to pajonk (who anyway found a better approach...)*
```
function(x,y)which(c(abs(diff(x))>y,T))[1]
```
[Try it online!](https://tio.run/##jY7LCoMwFET3fsWFbnIhBV8bC/UruitFfCQkVI2YFM3X20Qp9AmFmVkM5w53XLRRQ1GaolLqelz4ra@NVD2ZqcVJyFqQmpSVJo3knMyIuaUnxHN0eTl0UETBC71hB/sckuANCVckRO8NiYLPlZhC4vJpKP1COSRd5efiv8Dtu59shjTLHn8B8a0WrOUwSSNA9a11wcD3BzCCwagqZcCvaJBdxxpZGtZaDJY7 "R – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 41 bytes
```
function(x,y)match(T,c(abs(diff(x))>y,T))
```
[Try it online!](https://tio.run/##jY7NCoMwEITvPsVCL7uQgj@9WKhP4V1ijCRUTTEpNU9vjVLoLxRm5jB8O@w4W2cuFXdVbcz5NLfXQThtBpyYp547obBkAnltsdFtixNR4VlJ9HKHAhMGQRQMO9gXkEVvSLwiMQVvSBJ9rqQMsiWfhg5fqAU5rApz6V/g9t1PNieW54@/AENrlexauGmnwAydX0JC6I/glITR1MZBWLGg@142mjvZeYrmOw "R – Try It Online")
Based on [@Dominic van Essen's answer](https://codegolf.stackexchange.com/a/242294/55372), so test harness taken from there.
The idea emerged when golfing Dominic's answer and using `which`: "hmm, we need the first index and I remember that there's a function that returns only the first index (which is annoying in some challenges). Oh, it's `match`!"
[Answer]
# [Desmos](https://www.desmos.com/calculator), 96 50 47 bytes
*- a whopping **46** bytes thanks to [Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow)
- 3 bytes thanks to Aiden Chow again*
```
L=l.length
\min(\{(l[2...]-l)^2>aa:[1...L],L\})
```
Probably not the right language, but I had a lot of fun coding this.
Receives a list `l` and durability `a` as input.
[Online Version](https://www.desmos.com/calculator/bmnbivkwwd)
] |
[Question]
[
Closely related: [How high can you count?](https://codegolf.stackexchange.com/q/124362/78410)
## Challenge
In your programming language of choice, write as many different identity programs/functions as possible, under the following constraints:
* Each program should be a function or full program that is one of the following:
+ A function that takes a single positive integer and returns it unchanged
+ A function that takes a single string of printable ASCII (codepoints 32 to 126 inclusive) and returns it unchanged
+ A full program that takes a single positive integer from stdin and prints to stdout unchanged, with an optional trailing newline (and possibly other outputs that cannot be suppressed in your language)
+ A full program that takes a single line of printable ASCII from stdin and prints to stdout unchanged, with an optional trailing newline (and possibly other outputs that cannot be suppressed in your language)
* Different programs using different I/O methods is acceptable.
* **Any single byte cannot appear in two or more programs**, though it may appear more than once in a single program. You may freely use multi-byte characters, as long as every byte value consisting of each multi-byte character follows this exact rule.
* The programs must be independent of each other.
* If an empty program satisfies the condition above, you can include it only once in your answer.
* Symbol independent languages such as [Lenguage](https://esolangs.org/wiki/Lenguage) (including partially independent ones such as [Headsecks](https://esolangs.org/wiki/Headsecks)) are disallowed.
* If your language accepts flags, all programs in an answer must use a single combination of flags (e.g. one answer for "Keg" programs without flags, a separate answer for "Keg `-hr`" programs). According to [this meta](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends), a language with different flag combination is a different language.
## Examples
In Python 3, all of `lambda a:a`, `print(input())`, `int`, and `str` are valid identity programs independently, but only two of them can be used in an answer since the last three programs share the character `t`.
## Scoring
The submission with the largest number of programs wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~130~~ ~~133~~ ~~144~~ ~~148~~ ~~150~~ ~~151~~ ~~155~~ ~~156~~ ~~157~~ 159 programs
Uses the custom [05AB1E encoding](https://github.com/Adriandmen/05AB1E/wiki/Codepage) for all programs.
All programs are a TIO-link to verify them.
**Either type of input is fine:**
1) [(empty program)](https://tio.run/##yy9OTMpM/Q8EJanFJQA): Implicit input is output implicitly
2,3) [(a space)](https://tio.run/##yy9OTMpM/f9f4f//ktTiEgA), [`\n` (a newline)](https://tio.run/##yy9OTMpM/f@f6///ktTiEgA): The whitespaces are ignored; implicit input is output implicitly (with trailing newline)
4) [`w`](https://tio.run/##yy9OTMpM/f@//P//ktTiEgA): Unbound no-op; implicit input is output implicitly (with trailing newline)
5) [`I`](https://tio.run/##yy9OTMpM/f/f8///ktTiEgA): Explicit input is output implicitly (with trailing newline)
6) [`¹`](https://tio.run/##yy9OTMpM/f//0M7//0tSi0sA): Explicit first input is output implicitly (with trailing newline)
7) [`$`](https://tio.run/##yy9OTMpM/f9f5f//ktTiEgA): Push 1 and the input, after which the top input is output implicitly (with trailing newline)
8) [`Î`](https://tio.run/##yy9OTMpM/f//cN///yWpxSUA): Push 0 and the input, after which the top input is output implicitly (with trailing newline)
9) [`,`](https://tio.run/##yy9OTMpM/f9f5///ktTiEgA): Implicit input is output explicitly with trailing newline
10) [`=`](https://tio.run/##yy9OTMpM/f/f9v//ktTiEgA): Implicit input is output explicitly with trailing newline (without popping)
11) [`?`](https://tio.run/##yy9OTMpM/f/f/v//ktTiEgA): Implicit input is output explicitly without trailing newline
12) [`q`](https://tio.run/##yy9OTMpM/f@/8P//ktTiEgA): Exit program; implicit input is output implicitly (with trailing newline)
13,14) [`D`](https://tio.run/##yy9OTMpM/f/f5f//ktTiEgA), [`Ð`](https://tio.run/##yy9OTMpM/f//8IT//0tSi0sA): Duplicate / triplicate the implicit input and output the top implicitly (with trailing newline)
15) [`r`](https://tio.run/##yy9OTMpM/f@/6P//ktTiEgA): Reverse the values on the stack (which is empty); implicit input is output implicitly (with trailing newline)
16,17) [`s`](https://tio.run/##yy9OTMpM/f@/@P//ktTiEgA), [`Š`](https://tio.run/##yy9OTMpM/f//6IL//0tSi0sA): Swap / triple swap two / three implicit inputs; the top is output implicitly (with trailing newline)
18) [`Δ`](https://tio.run/##yy9OTMpM/f//3JT//0tSi0sA): Loop until the result no longer changes; the implicit input is used, it loops twice, and the unmodified input is output implicitly (with trailing newline)
19) [`:`](https://tio.run/##yy9OTMpM/f/f6v//ktTiEgA): Replace the implicit input-string with the implicit input-string, after which the unmodified input is output implicitly (with trailing newline)
20,21,22,23) [`J`](https://tio.run/##yy9OTMpM/f/f6///ktTiEgA), [`»`](https://tio.run/##yy9OTMpM/f//0O7//0tSi0sA), [`O`](https://tio.run/##yy9OTMpM/f/f////ktTiEgA), [`P`](https://tio.run/##yy9OTMpM/f8/4P//ktTiEgA): Join the empty stack without delimiter / join the empty stack with newline delimiter / sum the empty stack / take the product of the empty stack, after which the implicit input is output implicitly (with trailing newline)
24,25) [`U`](https://tio.run/##yy9OTMpM/f8/9P//ktTiEgA), [`V`](https://tio.run/##yy9OTMpM/f8/7P//ktTiEgA): Pop the implicit input, and store it in variable `X` or `Y` respectively, after which the implicit input is output implicitly (with trailing newline)
26) [`©`](https://tio.run/##yy9OTMpM/f//0Mr//0tSi0sA): Store the implicit input in variable `®` (without popping), after which it is output implicitly (with trailing newline)
27) [`ˆ`](https://tio.run/##yy9OTMpM/f//dNv//yWpxSUA): Pop the implicit input, and add it to the global array, after which the implicit input is output implicitly (with trailing newline)
28) [`i`](https://tio.run/##yy9OTMpM/f8/8///ktTiEgA): If-statement, if the (implicit) input is 1 it enters it. But whether the input is 1 and it enters the if-statement or not, the implicit input is output implicitly (with trailing newline) either way
29) [`v`](https://tio.run/##yy9OTMpM/f@/7P//ktTiEgA): For-each over each character/digit of the implicit input (but don't push any, since we don't use `y`). After the loop, the implicit input is output implicitly (with trailing newline)
30,31) [`}`](https://tio.run/##yy9OTMpM/f@/9v//ktTiEgA), [`]`](https://tio.run/##yy9OTMpM/f8/9v//ktTiEgA): Close the inner-most or all if-statement(s)/loop(s), for which there are none right now. The implicit input is output implicitly (with trailing newline)
32) [`†`](https://tio.run/##yy9OTMpM/f//UcOC//9LUotLAA): Filter the implicit input to the front of the implicit input; it will remain unmodified and is output implicitly (with trailing newline)
33) [`‡`](https://tio.run/##yy9OTMpM/f//UcPC//9LUotLAA): Transliterate the characters of the implicit input to the characters of the implicit input; it will remain unmodified and is output implicitly (with trailing newline)
34) [`´`](https://tio.run/##yy9OTMpM/f//0Jb//0tSi0sA): Clear the global array (which is already empty). After which the implicit input is output implicitly (with trailing newline)
35) [`§`](https://tio.run/##yy9OTMpM/f//0PL//0tSi0sA): Cast the implicit input to a string, after which it is output implicitly (with trailing newline)
36) [`Ã`](https://tio.run/##yy9OTMpM/f//cPP//yWpxSUA): Keep all values of the implicit input in the implicit input, after which the unmodified result is output implicitly (with trailing newline)
37) [`é`](https://tio.run/##yy9OTMpM/f//8Mr//0tSi0sA): Sort the implicit input by length. Since it's a single string/integer, the characters/digits will remain at the same position, after which the unmodified input is output implicitly (with trailing newline)
38,39) [`.`](https://tio.run/##yy9OTMpM/f9f7///ktTiEgA), [`Å`](https://tio.run/##yy9OTMpM/f//cOv//yWpxSUA), [`ž`](https://tio.run/##yy9OTMpM/f//6L7//0tSi0sA): All three are used to open up more 2-byte operations, but on their own they're unbound no-ops. So the implicit input is output implicitly (with trailing newline).
40) [`\`](https://tio.run/##yy9OTMpM/f8/5v//ktTiEgA): Discard the top item on the stack (which is already empty), after which the implicit input is output implicitly (with trailing newline)
41) [`¼`](https://tio.run/##yy9OTMpM/f//0J7//0tSi0sA): Increase the counter\_variable by 1. After which the implicit input is output implicitly (with trailing newline)
42) [`½`](https://tio.run/##yy9OTMpM/f//0N7//0tSi0sA): If the implicit input is `1`, increase the counter\_variable by 1. After which the implicit input is output implicitly (with trailing newline)
43) [`ë`](https://tio.run/##yy9OTMpM/f//8Or//0tSi0sA): Else-statement, which is a no-op without if-statement. So the implicit input is output implicitly (with trailing newline)
44) [`ÿ`](https://tio.run/##yy9OTMpM/f//8P7//0tSi0sA): Used for string interpolation; outside of a string it's a no-op. So the implicit input is output implicitly (with trailing newline)
45) [`šн`](https://tio.run/##yy9OTMpM/f//6MILe///L0ktLgEA): Convert the implicit input implicitly to a character-list, and prepend the implicit input at the front. Then pop and push the first item of this list, which is output implicitly (with trailing newline).
46) [`ªθ`](https://tio.run/##yy9OTMpM/f//0KpzO/7/L0ktLgEA): Convert the implicit input implicitly to a character-list, and append the implicit input at the end. Then pop and push the last item of this list, which is output implicitly (with trailing newline).
47) [`η¤`](https://tio.run/##yy9OTMpM/f//3PZDS/7/L0ktLgEA): Get all prefixed of the implicit input. Push its last item (without popping), after which the top of the stack is output implicitly (with trailing newline).
48) [`ðý`](https://tio.run/##yy9OTMpM/f//8IbDe///L0ktLgEA): Join the empty stack with space delimiter, after which the implicit input is output implicitly (with trailing newline).
49) [`õK`](https://tio.run/##yy9OTMpM/f//8Fbv//9LUotLAA): Remove all empty strings from the implicit input, after which the unmodified result is output implicitly (with trailing newline).
50) [`¸``](https://tio.run/##yy9OTMpM/f//0I6E//9LUotLAA) : Wrap the implicit input into a list, and then pop and dump the contents of that list to the stack, after which it is output implicitly (with trailing newline)
51) [`ʒX`](https://tio.run/##yy9OTMpM/f//1KSI//9LUotLAA): Start a filter, and push variable `X`, which is 1 (truthy) by default. So all characters/digits in the implicit input will remain, and the unmodified input is output implicitly (with trailing newline)
52) [`RR`](https://tio.run/##yy9OTMpM/f8/KOj//5LU4hIA): Reverse the implicit input, and reverse it back. After which the unmodified input is output implicitly (with trailing newline).
53) [`ÂÂ`](https://tio.run/##yy9OTMpM/f//cNPhpv//S1KLSwA): Bifurcate (short for Duplicate & Reverse copy) twice, after which the unmodified input at the top of the stack is output implicitly (with trailing newline)
54) [`ÁÀ`](https://tio.run/##yy9OTMpM/f//cOPhhv//S1KLSwA): Rotate the implicit input once towards the right, and then back towards the left. After which the unmodified input is output implicitly (with trailing newline).
55) [`ƨ`](https://tio.run/##yy9OTMpM/f//SNuhFf//l6QWlwAA): Enclose the implicit input, appending its own first character/digit, and then remove the last character/digit again. After which the unmodified input is output implicitly (with trailing newline).
56) [`Σ9`](https://tio.run/##yy9OTMpM/f//3GLL//9LUotLAA): Sort the characters/digits in the implicit input by 9 (so they'll all stay at the same positions), after which the unmodified input is output implicitly (with trailing newline).
57) [`8ì¦`](https://tio.run/##yy9OTMpM/f/f4vCaQ8v@/y9JLS4BAA): Prepend an `8` in front of the implicit input, and then remove the first character again. After which the unmodified input is output implicitly (with trailing newline)
58) [`āĀÏ`](https://tio.run/##yy9OTMpM/f//SOORhsP9//@XpBaXAAA): Push a list in the range [1, implicit input-length] (without popping). Python-style truthify each value in this list (so they'll all becomes 1s). Only keep the characters/digits of the implicit input at the truthy (1) indices, after which the unmodified result is output implicitly (with trailing newline).
59) [`""«`](https://tio.run/##yy9OTMpM/f9fSenQ6v//S1KLSwA): Append an empty string to the implicit input, after which the unmodified input is output implicitly (with trailing newline).
60,61) [`‘‘Û`](https://tio.run/##yy9OTMpM/f//UcMMIDo8@///ktTiEgA), [`’’Ü`](https://tio.run/##yy9OTMpM/f//UcNMIDo85///ktTiEgA): Trim all leading / trailing empty strings of the implicit input, after which the unmodified input is output implicitly (with trailing newline).
62) [`““¡`](https://tio.run/##yy9OTMpM/f//UcMcIDq08P//ktTiEgA): Split the implicit input on an empty string, after which the unmodified input is output implicitly (with trailing newline).
63) [`₆¢`](https://tio.run/##yy9OTMpM/f//UVPboUX//5ekFpcYm4FIAA): Count the amount of 36 in the implicit input. Not sure why, but when using a multi-character value with the count, there seems to be a bug and it results in the unmodified string, instead of the actual amount of `36` substrings in the string I was expecting.. So this will output the unmodified input implicitly (with trailing newline).
**Only string input:**
64 through 125) [`ǝαβив!%&(*+-/÷;<>BLbcefhjmnoptxz~‰£°±·¿ÃÆÈÉÌÍÑÒÓÕÖרÝãäçèîôöùú`](https://tio.run/##AYEAfv9vc2FiaWX//yLHnc6xzrLQuNCyISUmKCorLS/Dtzs8PkJMYmNlZmhqbW5vcHR4en7igLDCo8KwwrHCt8K/w4PDhsOIw4nDjMONw5HDksOTw5XDlsOXw5jDncOjw6TDp8Oow67DtMO2w7nDuiJ2eT8iIOKGkiAiP3kuViz//3Rlc3Q): All these are integer operations (see the Wiki-page linked in the title to see what each does). They are no-ops for the (implicit) input-string(s); after which the unmodified input at the top of the stack is output implicitly.
126) [`∍`](https://tio.run/##yy9OTMpM/f//UUfv//8lqcUlAA): Extend/shorten the implicit input-string to a size equal to the implicit input-string, after which it is output implicitly (with trailing newline).
127) [`δ`](https://tio.run/##yy9OTMpM/f//3Jb//0tSi0sA): Apply double-vectorized. For integer inputs, it will implicitly convert to a \$[1, a]\$ range before applying double-vectorized. For strings, the implicit input is output implicitly.
128) [`Λ`](https://tio.run/##yy9OTMpM/f//3Oz//0tSi0sA): Apply the Canvas with three options. For the digits `0` through `7`, it will output the digit in [a certain direction and length](https://codegolf.stackexchange.com/a/175520/52210), depending on the input. For any other input, it will be a no-op outputting the implicit input implicitly (with trailing newline).
129) [`–`](https://tio.run/##yy9OTMpM/f//UcPk//9LUotLAA): If the top of the stack is `1`, it will print index `N`. So this will output `0` for input `1`, but will output the implicit input itself implicitly (with trailing newline) for any other input.
130) [`—`](https://tio.run/##yy9OTMpM/f//UcOU//9LUotLAA): If the top of the stack is `1`, it will print item `y`. So this will output an empty string for input `1`, but will output the implicit input itself implicitly (with trailing newline) for any other input.
131) [`œW`](https://tio.run/##yy9OTMpM/f//6OTw//9LUotLAA): Get all permutations of the implicit input-string. Then push the minimum (without popping), which for string inputs will simply use the very first string. Then output this unmodified input at the top of the stack implicitly (with trailing newline).
**Only string input, and the output is a character-list:**
132) [`S`](https://tio.run/##yy9OTMpM/f8/@P//ktTiEgA): Convert the implicit input to a list of characters and output it implicitly (with trailing newline).
133,134) [`ε`](https://tio.run/##yy9OTMpM/f//3Nb//0tSi0sA), [`€`](https://tio.run/##yy9OTMpM/f//UdOa//9LUotLAA): Map over each character in the implicit input, and output the resulting character-list implicitly (with trailing newline).
135) [`gι`](https://tio.run/##yy9OTMpM/f8//dzO//9LUotLAA): Push the length of the implicit input. Uninterleave the implicit input using this length as block-size. After which the resulting character-list is output implicitly (with trailing newline).
136) [`øøø¬`](https://tio.run/##yy9OTMpM/f//8A4QPLTm//@S1OISAA): Zip/transpose three times; swapping rows/columns. If it's a matrix, it will do as expected. If it's a string or list, it will use the implicit input as a pair-and-zip/tranpose. Since we're doing it three times, the following will happen: `"abc"` → `["aa","bb","cc"]` → `[["a","aa"],["b","bb"],["c","cc"]]` → `[["a","b","c"], ["aa","bb","cc"]]`. Then we'll push the first inner list (without popping), after which this list at the top of the stack is output implicitly (with trailing newline).
137) [`ü1`](https://tio.run/##yy9OTMpM/f//8B7D//9LUotLAA): `ü` is the overlapping builtin. It can be used with any other builtin to execute that builtin on every overlapping pair. But it can also be used with a single digit to create overlapping pair (2), triplets (3), quartets (4), etc. Apparently it also works with 1 to just convert the (implicit) input-string into a character-list, which is output implicitly (with trailing newline).
**Only character-list input:**
138) [`í`](https://tio.run/##yy9OTMpM/f//8Nr//6OVSpR0lFKBuBiIS5RiAQ): Reverse each character in the implicit input-list, after which the unmodified input-list is output implicitly (with trailing newline).
139) [`˜`](https://tio.run/##yy9OTMpM/f//9Jz//6OVSpR0lFKBuBiIS5RiAQ): Flatten the implicit input-list, after which the unmodified input-list is output implicitly (with trailing newline).
140) [`ζζΩ`](https://tio.run/##yy9OTMpM/f//3DYgXPn/f7RSiZKOUioQFwNxiVIsAA): Zip/transpose the (implicit) input-list twice: `["a","b","c"]` → `[["a","a"],["b","b"],["c","c"]]` → `[["a","b","c"],["a","b","c"]]`. And then pop and push a random item of this list of lists, which are both the unmodified input-list. After which it will be output implicitly (with trailing newline).
**Only integer input:**
141,142,143,144) [`E`](https://tio.run/##yy9OTMpM/f/f9f9/QyNTAA), [`F`](https://tio.run/##yy9OTMpM/f/f7f9/QyNTAA), [`G`](https://tio.run/##yy9OTMpM/f/f/f9/QyNTAA), [`ƒ`](https://tio.run/##yy9OTMpM/f//2KT//w2NTAE): Start a ranged loop with the implicit input (`E` = \$[1, a]\$; `F` = \$[0, a)\$; `G` = \$[1, a)\$; `ƒ` = \$[0, a]\$), and output the implicit input implicitly (with trailing newline) afterwards.
145) [`ï`](https://tio.run/##yy9OTMpM/f//8Pr//w2NTAE): Convert the implicit input to an integer, after which the unmodified input is output implicitly (with trailing newline).
146) [`ò`](https://tio.run/##yy9OTMpM/f//8Kb//w2NTAE): Round to the nearest integer (which it already is), after which the unmodified input is output implicitly (with trailing newline).
147) [`þ`](https://tio.run/##yy9OTMpM/f//8L7//w2NTAE): Only keep the digits of the implicit input-integer, after which the unmodified input is output implicitly (with trailing newline).
148) [`#`](https://tio.run/##yy9OTMpM/f9f@f9/QyNTAA): Split the implicit input-integer by spaces (it has none), after which the unmodified input is output implicitly (with trailing newline).
149,150,151) [`u`](https://tio.run/##yy9OTMpM/f@/9P9/QyNTAA), [`l`](https://tio.run/##yy9OTMpM/f8/5/9/QyNTAA), [`™`](https://tio.run/##yy9OTMpM/f//Ucui//8NjUwB): Convert the implicit input-integer to uppercase / lowercase / titlecase, after which the unmodified input is output implicitly (with trailing newline).
152) [`¶м`](https://tio.run/##yy9OTMpM/f//0LYLe/7/NzQyBQA): Remove all newline characters of the implicit input-integer, after which the unmodified input is output implicitly (with trailing newline).
153) [`‚ß`](https://tio.run/##yy9OTMpM/f//UcOsw/P//zc0MgUA): Pair the implicit input-integer with the implicit input-integer, and then pop and push its minimum. After which it is output implicitly (with trailing newline).
154) [`AÚ`](https://tio.run/##yy9OTMpM/f/f8fCs//8NjUwB): Trim leading and trailing lowercase alphabets of the implicit input-integer, after which the unmodified input is output implicitly (with trailing newline).
155) [`|M`](https://tio.run/##yy9OTMpM/f@/xvf/f0MjUwA): Push all inputs as list. Push the largest value on the stack (including in all inner lists/matrices). After which the top of the stack is output implicitly (with trailing newline).
156) [`∞@0k`](https://tio.run/##yy9OTMpM/f//Ucc8B4Ps//8NjUwB): Push an infinite positive list [1,2,3,...]. Check for each value if the (implicit) input is larger than or equal to this value (1 if truthy; 0 if falsey). And then get the 0-based index of the first 0 in this infinite list. After which it is output implicitly (with trailing newline).
157) [`µ¾Ê`](https://tio.run/##yy9OTMpM/f//0NZD@w53/f9vaGQKAA): Continue looping until the counter\_variable (default 0) is equal to the implicit input-integer. Push the counter\_variable each iteration, and check that it's NOT equal to the implicit input-integer. If this is truthy, the counter\_variable will implicitly be increased by 1 after every iteration. When it becomes falsey, it means it's equal to the input-integer, and thus the loops stops, after which the counter\_variable is output implicitly (with trailing newline) as result.
158) [`Έ`](https://tio.run/##yy9OTMpM/f//6KTDC/7/NzQyBQA): Push all substrings of the implicit input-integer, and then pop and push its maximum. After which this top of the stack is output implicitly (with trailing newline).
159) [`Z)Z`](https://tio.run/##yy9OTMpM/f8/SjPq/39DI1MA): Get the largest digit of the implicit input-integer (without popping). Then wrap all values on the stack into a list, which is the input itself and its max digit. And then get the maximum again of this integer-pair (without popping), which will be the input itself. Then output the input at the top of the stack implicitly (with trailing newline).
**Unused characters / builtins:**
I'm pretty sure nothing useful is left anymore now..
```
Integer constants: 234567Tт₁₂₃₄₅Y®N•
Empty list constant: ¯
Empty string constant (if used twice): ”
(Partially) uniquify / sort builtins: Ù{êÔγ
Convert from binary/hexadecimal to integer (which works on any input unfortunately): CH
Checks resulting in truthy/falsey (0/1): Θ≠Qad›‹Ëå
Recursive environment (which I can't close without `}` nor `]`): λ
Infinite loop (which I can't stop without `#` nor `q`): [
(Compressed) string/integer builtins, which result in errors on their own: '„…ƵŽ
Ord (convert to codepoint integers): Ç
Convert to a list and cycle infinitely: Þ
Only leave the letters (which won't work if the input contains anything else): á
Get the second or third input (we are only allowed to take a single input): ²³
Palindrome / mirror: ûº
Cartesian product: â
```
[Answer]
# perl -pe, 85 86 87 programs
```
perl -pe 000
perl -pe 111
...
perl -pe 999
perl -pe aaa
perl -pe bbb
...
perl -pe zzz
perl -pe AAA
perl -pe BBB
...
perl -pe ZZZ
perl -pe '__'
perl -pe '$$'
perl -pe '%%'
perl -pe '@@'
perl -pe ';;'
perl -pe '**'
perl -pe '##'
perl -pe '""'
perl -pe "''"
perl -pe '``'
perl -pe '//'
perl -pe '::'
perl -pe '??' # Only if your perl is old enough (pre 5.22)
perl -pe ' ' # Spaces (or tabs, or newlines, etc)
perl -pe '()'
perl -pe '[]'
perl -pe '<>'
perl -pe '{}'
perl -pe '\&\'
perl -pe '' # Empty program
```
They all copy their input to output.
## How does it work?
`perl -pe` reads the input line by line, and executes the given program, where `$_` contains the read line. After executing the program, it prints whatever is left in `$_`. None of the given programs modify `$_`, all statements are just noops.
In short, all digits, all upper case letters and all but 3 lower case letters can used single (or double, triple, etc). They're either numbers or strings in void context. Since `m`, `s`, and `q` used single may be commands, (and for `q`, this is also the case when used double), using them all as triples will do.
Many other characters can be used, sometimes single, or otherwise double. But if we can use them single, double will work too, hence we used doubles. `__` is just a string. `$$`, `@@`, `%%`, and `**` are variables. `;;` are two command separators. `""` is an empty string, and so is `''`. Double backticks just execs a empty command. `##` is a comment. `::` is an alternative way of spelling the package `main`. `//` is an empty regexp. `??` is the weird regexp operator you never needed, or probably never knew about (it repeats the last successful match).
Any of the whitespace characters (space, newline, tab, etc) can use used as well.
This leaves a few characters I could not use by themselves, and I had to pair them with another: `[]` is an empty array. `()` is an empty list. `<>` reads line from the input. `{}` is an empty block.
`\&\` is a reference to (non-existing, but Perl is fine with that) subroutine named `\`.
And of course, the empty program qualifies as well (thanks to David G. for pointing that out).
This leaves `!`, `+`, `,`, `-`, `.`, `=`, `^`, `|`, `~` as an exercise for the reader.
That's 10 (digits) + 52 (lower + upper case letters) + 6 (white space) + 13 (other characters used by themselves) + 5 (programs with 2 different characters) + 1 (empty program) = 87 programs.
[Answer]
# R, ~~11~~15 programs
This is a very interesting challenge for R, we get to use lots of different features of the language!
firstly, in R, any expression that isn't assigned somewhere is printed by default, so the empty program counts (it will return an integer unchanged, for example)
`c` can be treated as a function of one argument that will return it unchanged.
`I` adds a class attribute, but this does not affect the printing.
`t` will return its argument as a 1x1 matrix (I hope this counts as "unchanged" for the purposes of the problem).
`min` will return its argument unchanged if that is a single integer.
`as.raw` will return a hexadecimal integer unchanged (from my reading of the problem, I *think* that's acceptable.)
`+` as a unary function of one integer will return it unchanged.
`1*` as a program will then generate a prompt for the second argument: entering it will return the entered integer unchanged.
`--`, similarly to `1*`, will generate a prompt for a number which is then negated twice and therefore printed unchanged. (Edit: `T%x%` will do the same, taking the Kronecker product of the entered number with `TRUE==1` --- thanks Robin Ryder)
`(` and `'{'` both return their argument (they are formal functions in R). They need the quotes to function, but luckily R lets you use different kinds of quotes.
`"\u73\u75\u6D"` will also work as a function; the escapes evaluate to "s", "u" and "m" respectively which gives `sum`, which will return its argument unchanged if it is a single integer.
Lastly, everyone always forgets about complex numbers but `Re` and `Mod` will return the real part and modulus of the argument respectively. If that argument is a positive integer then they are no-ops.
Thanks to Giuseppe for the `min` and brackets ideas and to Robin Ryder for some other suggestions!
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 252 programs
The first 5 programs are:
```
[]
()
<><>
#{}
```
and the empty string. These programs have 9 unique characters total.
Each of the remaining 247 programs consist of an individual byte other than `(){}<>{}#`.
## How?
In brain-flak, an empty program prints it's input. Any character other than `#(){}[]<>` has no affect on the behavior of the program.
[Try it online!](https://tio.run/#brain-flak)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~12~~ 15 programs
Edit: Added three more programs which are no-ops only on numeric input.
```
↧
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R2/L//w0A "Charcoal – Try It Online") Lowercases the implicit input, which has no effect for numeric input.
```
↥
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R29L//w0A "Charcoal – Try It Online") Uppercases the implicit input, which has no effect for numeric input.
```
θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRKNQ0/r/f4P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Prints the default input.
```
S
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMzr6C0JLgEyE7X0NS0/v/f4L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Prints the explicit string input.
```
A
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMzr6C0RENT0/r/f4P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Prints the explicit input.
```
IN
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzOvoLTErzQ3KbVIQ1NT0/r/f4P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Casts the explicit numeric input to string so that it can be printed.
```
∨⁰
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9Rx4pHjRv@/zcAAA "Charcoal – Try It Online") Prints the logical OR of 0 and the implicit input.
```
∧χ
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9Rx/Lz7f//GwAA "Charcoal – Try It Online") Prints the logical AND of 10 and the implicit input.
```
⮌⮌
```
[Try it online!](https://tio.run/##S85ILErOT8z5///Ruh4g@v/fAAA "Charcoal – Try It Online") Prints the implicit input reversed twice.
```
⁺ω
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R467znf//GwAA "Charcoal – Try It Online") Prints the empty string concatenated with the implicit input.
```
×¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5///w9EM7//83AAA "Charcoal – Try It Online") Prints the implicit input repeated once.
```
﹪%s
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9zlWqxf//GwAA "Charcoal – Try It Online") Formats the implicit input as a string.
```
⊟⊞Oυ
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R1/xHXfPe71l/vvX/fwMA "Charcoal – Try It Online") Pushes and pops the implicit input to a list before printing it.
```
⎇℅ψφ
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9RX/ujltbzHefb/v83AAA "Charcoal – Try It Online") Prints the implicit input if the null byte's ordinal is zero.
```
⭆⊖²⊖⊕
```
[Try it online!](https://tio.run/##S85ILErOT8z5///R2rZHXdMObQISj7qm/v9vAAA "Charcoal – Try It Online") Increments and decrements one implicit (numeric) input, then joins the results together.
[Answer]
# Brachylog, 88 programs
I doubt this is the longest I can get it, as I'm only posting this now because I need to take a break from making more of these, and if character lists are admissible for strings I know this can be expanded even further. The reason so many one-character solutions exist is that Brachylog has a lot of variables, constraint predicates, and flow control commands, plus a fair number of nondet predicates that happen to have the exact input as their *first* output.
1. The empty program, for integers or strings.
2 - 27. Any uppercase ASCII letter, for integers or strings.
28. `İ` for integers.
29. `Ṡ` for strings.
30 - 42. Any one of `ȦḂḞĠḢṄṖṘẆẊẎŻ`, for integers or strings.
43. A space, for integers or strings.
44. A newline, for integers or strings.
45. `?`, for integers or strings.
46. `.`, for integers or strings.
47. `&`, for integers or strings.
48. `|`, for integers or strings.
49. `≜`, for integers.
50. `w`, printing an integer from stdin.
51. `ẉ`, printing an integer from stdin with a trailing newline.
52. `p`, for strings.
53. `s`, for strings.
54. `≡`, for integers or strings.
55. `!`, for integers or strings.
56. A backtick, for integers or strings.
57. `⊆`, for strings.
58. `⊇`, for strings.
59. `()`, for integers or strings.
60. `{}`, for integers or strings.
61. `↔↔`, for strings.
62. `↺↻`, for strings.
63. `∈h`, for strings.
64. `,Ė`, for strings.
65. `ṅṅ`, for integers.
66. `gṛ`, for integers or strings.
67. `ℤ`, for integers. (can't believe I forgot this earlier, but I can't be bothered to renumber everything)
68. `ḋ×`, for integers.
69. `+₀`, for integers.
70. `ℕ`, for integers. (I didn't notice the restriction to positive!)
71. `ȧ`, for integers. (again, specifically positive)
72. `ṫị`, for integers.
73. `ċ₂`, for strings.
74. `÷↙Ḋ`, for integers.
75. `ḅc`, for strings.
76. `<<<-₃`, for integers.
77. `aʰ`, for strings.
78. `f⌉`, for integers.
79. `dᵗ`, for strings.
80. `=ᵐ`, for strings.
81. `≠ˢ`, for strings.
82. `;1/`, for integers.
83. `^₁`, for integers.
84. `jḍt`, for strings.
85. `~⌋⌋`, for integers or strings.
86. `⟦bl`, for integers.
87. `⟧k∋ᶜ`, for integers.
88. `≤`, for integers.
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 38 functions/programs
The code to be counted is parenthesised below. The first two entries are full programs, the rest are tacit prefix functions, except `{⍵}` which is a prefix lambda.
```
(⎕) ⍝ prompt for numeric input and implicitly print it
(⍞) ⍝ prompt for string and implicitly print it
(⍮)I ⍝ 1-element with (no visual difference on simple scalar)
(⌷)S ⍝ materialise (no-op on anything but certain objects)
(∧)I ⍝ LCM reduction (no-op on scalar)
(∨)I ⍝ GCD reduction (no-op on scalar)
(⌽)I ⍝ mirror (no-op on scalar)
(⍉)I ⍝ transpose (no-op on scalar; TIO's version has a bug that has since been fixed)
(⊖)I ⍝ flip (no-op on scalar)
(+)I ⍝ complex conjugate (no-op on real number)
(∊)S ⍝ enlist (no-op on strings)
(↑)S ⍝ mix (no-op on simple arrays)
(↓)I ⍝ split (no-op on simple scalars)
(⊢)S ⍝ identity
(⊣)S ⍝ identity
(⌈)I ⍝ ceiling (no-op on integer)
(⌊)I ⍝ floor (no-op on integer)
(⍕)I ⍝ stringify (no-op on string)
(⊂)I ⍝ enclose (no-op on simple scalar)
(⊃)I ⍝ first (no-op on simple scalar)
(∪)I ⍝ unique (no-op on simple scalar)
(|)I ⍝ absolute value (no-op on positive numbers)
(,)I ⍝ ravel (no-op on strings)
(⍪)I ⍝ table (no visual difference on scalars)
(⍷/)I ⍝ use find (arbitrary otherwise unused function) to reduce (no-op on scalar)
(1⌿)S ⍝ replicate all elements to 1 copy each (no-op on string)
(9○)I ⍝ real part (no-op on real number)
(⍟*)I ⍝ natural logarithm of e to the power
(⍬,)S ⍝ prepend the empty list (no-op on string)
(⊥⊤)I ⍝ the base-2 evaluation of the base-2 representation
(--)I ⍝ negate the negation
(÷÷)I ⍝ reciprocate the reciprocal
(~∘8)S ⍝ remove all occurences of number 8 (no-op on string)
({⍵})S ⍝ user-defined identity function
(!⍣0)I ⍝ apply the factorial zero times
(''⍴)I ⍝ reshape to 0D (no-op on scalar)
(.5×2×)I ⍝ half the double
(⍳∘≢⍛⊇⍨)S ⍝ use all the indices to permute the argument (this one is supposed to say ⍤ instead of ∘ but TIO isn't updated)
```
[Try it online!](https://tio.run/##jVZNbxxFEL3nVzSn9ZIsxBaREuWYSMgSiEP4A7UzNTsd9XQ3/bH2hI8DSGGz2UEgFIyEIFI@RIQQF0A@IQ7@J/NHTPVs987Yzsac1ut@r7rq1avqBS0m@QPgFZzutw@/fW/vyj36GJUohGIHyoh8dNp@84T@t0MfY9Y2PzNtVKUdK5Rh0ldoeMa41N4xkDnjlRY8407UhOPSMe6upADNLxcCWEeg2eXMP8b7HXV3ggIrpNMD7kq2IxWbc@tBsJwXBRqUGTIlmQ3RkNkMBJjxJs7qeHyvi1OBo8RBcIshyETpwAJZuzLkM6VqMjQOuGRqeh8zZ/sgi19jMh/c@ZAZzH3mOJH7MOdvXbyKhPfv3P1fhNU/kVBxY0il7cjmUUQ6A9JqdaacNfg2@3j/o5FlczQ2XFuCZUAVzpgrwXVfLQ@yTRElK/gh5n385Q8xfiG43p7H1YjKVJD9kD7lfT8jjQcUg9QlMswUh9IsY0NQUi/c8IbOGQPZH36XescPh7h1p8EYqIfo72NKllzlLuLXBQwIy2cxPM/JXtzV/cnzbSerRaobuQi@6a8hA@NsWOlquVFSnWnpBWTzJKXeScCL@oIsg7S/jGByvjjX/tfPwPKrlAg31l2OX/wW8V7yT/zlF3wW4TC1SniywBzEGRq5lDs@x2iGvgfXItPAHMWbrNCklBxMBb5hC5xvcnP8biqGpCo4rZ0dMFNO02NqplyJ5iCsBC/pPGeFl92ojplT68HF7TOw267@jUYxGFZZsD8IweLGsiHILo2GrhlCVm5v6q326HGSIgyNBuMuG6Tm6duRIsF5QwihZmBoSVZMFQzD5VQeiX@Apmf9fi2mrClnJDkCBmk71@y18ziw0ct2@SK1gUhTsDjZYxi6Dd1@o2sHBxTfoCUdusMUZjJJWWO3LgKh@3OAOTk@Od7IkXF6PbIE3XwXCfxFu/jx5qYNlZqve6CyzHe2sCGttXjs5vbyPm2bvz@PYcgKZpIjuYUskXbAxhuJ8VbbPL@erK81vWIhwQIyp8JDwx6goQ7wCm1ijEZt89emMFuC7rp0/e52j71z4@Ro7@QokkoQa4lz5WkO@q7@SSK0j561zU/t8uu2edUX0okRKGR9HtSgCzWaykdBwcx897zu0ENIWklC0vvgdXha8oC2UFOwFxTAOoQ8yEm3dS8mvTOEliPHvM6pRfn49JR@UQx@TPwH "APL (dzaima/APL) – Try It Online")
[Answer]
## Haskell, ~~5~~ 6 programs
### 1:
```
id
```
Haskell has an identity function, so that is a good start. It uses `i` and `d` which are not terribly valuable anyway.
### 2:
```
k x=x
```
A simple definition of an identity. It uses `=` which is going to make it hard for us to define any new functions (instead we will have to build them). And it also uses the space which is would be useful otherwise.
### 3:
```
\z->z
```
This is a lambda of the last version. This marks the end of the straight forward identities.
### 4:
```
(*1)
```
Multiplies the input by 1, which is an identity for members of the `Num` class. This uses up the very valuable parentheses.
### 5:
```
abs
```
As pointed out by H.PWiz since the input is positive `abs` is an identity
### 6:
```
fromEnum
```
This is an identity on integers.
---
At this point we still have a lot of room we could use `<$>` or `$` (replacement for space or parentheses), however I can't get anything to fit the `t` in `Just` is a problem for things like `subtract`, `const` and `repeat` which would be useful.
[Answer]
# Husk, 1 program + 24 functions
* 8 functions by [@Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb)!
* 4 functions by [@Razetime](https://codegolf.stackexchange.com/users/80214/razetime)
Programs:
1. `ḟ=⁰N` - Find an element that equals the last command-line argument in the infinite list of natural numbers. [Try it online](https://tio.run/##yygtzv7//@GO@baPGjf4/f//3wQA)
Functions:
1. `I` - the identity function
2. `+0` - Add 0
3. `*1` - Multiply by 1
4. `D½` - Double and then halve
5. `ĠK` - Scan right without an initial value. The `K` combinator just discards the second argument, so the list remains the same.
6. `←;` - Make a singleton list, then get the first element. [Try it online](https://tio.run/##yygtzv7//1HbBGvL//8B)
7. `__` - Negate twice
8. `⌉` - Ceiling (identity for integers)
9. `⌋` - Floor (identity for integers)
10. `i` - Round (identity for integers)
11. `a` - Absolute value (identity for positive numbers)
12. `√□` - Square root of square
13. ```` - Swap arguments of binary function twice
14. `\\` - Reciprocal twice ([Try it online!](https://tio.run/##yygtzv7/Pybm////xgA))
15. `LR"3"` - Repeat `"3"` `n` times, then take the length, giving back n. Can be something other than 3
16. `-ø` - Remove the empty list ([Try it online!](https://tio.run/##yygtzv7/X/fwjv///0cb6hjFAgA))
17. `cc` - Convert integer to character, convert character back to integer
18. `dd` - `d` can both get the base 10 digits or interpret digits in base 10
19. `n¹` - Bitwise and with itself
20. `tΘ` - Prepend default value, then get tail
21. `s` - Show (for strings)
22. `↔↔` - Swap pair/reverse list/reverse digits twice
23. `!4∞` - Get fourth (arbitrary) element of infinite list of copies of argument
24. `ΣC2` - Cut into sublists of size 2, concatenate them (for lists of size > 1)
[Answer]
# [Stack Cats](https://github.com/m-ender/stackcats), 19 programs
All programs that are exactly mirrored in Stack Cats function exactly as cat programs. Therefore, we can score one program for each valid symmetric character by having there be two of them, and we can score one program for each pair of matching characters. These character sets are:
```
!"*+-:=ITX^_|
(){}[]<>\/
```
Unfortunately, most other characters cause syntax errors in the existing interpreters. However, the empty program is also symmetric, so it also produces a cat program.
Sample symmetric program:
```
II
```
[Try it online!](https://tio.run/##Ky5JTM5OTiwp/v/f0/P/f0cnZxcA "Stack Cats – Try It Online")
Sample matching program:
```
{}
```
[Try it online!](https://tio.run/##Ky5JTM5OTiwp/v@/uvb/f0cnZxcA "Stack Cats – Try It Online")
Empty program example:
[Try it online!](https://tio.run/##Ky5JTM5OTiwp/g8Ejk7OLgA "Stack Cats – Try It Online")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~21~~ ~~22~~ ~~24~~ ~~25~~ ~~26~~ 27 programs
*Edit: thanks to Abigail for duplicate-letter-spotting, for the suggestion that led to `l^l`!, and for ~~+2~~ +3 more programs; and thanks to cnamejj for +1 program*
Awk will print the input line by default if a condition evaluates to TRUE.
non-zero values that evaluate to TRUE:
```
1
2
3
4
5
6
7
8
9
```
experessions that evaluate to TRUE:
```
$0 # only if input is not equal to the digit zero (so Ok for positive integer)
a~a
c==r
d---d
++f
!h
"j"
'k'
//
m^m
q**q
```
built-in variables that evaluate to TRUE:
```
NR
OFMT
SUBSEP
```
functions that evaluate to TRUE
```
log
exp
int i
sub(v,v)
```
[Try it online!](https://tio.run/##dY/JTsNAEETv9RVNjBRQZIV9k8IBKdwgKMsHjJ223diaMTM9Yfl5M@FMjiXVU9Uzn@0wZGSdzX/YO9qZLnIgbYwS74NRJnW0Xm7mDzjHBS5xhWvc4BZ3uEdG/NWz5xDE2YPc8Rll5Gz3TVKR2D4qSUijqfsRTbcvasO0lVqU/n6cBEeLlirnqXdBVHacQOWa/SmK2axE9ZjnNSaTBkeC0fsI43aM6ZTSpSJKp7nYZOPFFN1hodclFs8va6w2T6v5W0KraEv9X0V9ZHhjt8NgivIX "AWK – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 4 programs
Python turned out to be much harder than I thought, with only 4 so far.
```
int
abs
repr
(1).__mul__
```
[Try it online!](https://tio.run/##RYxNCsIwEIX3OcWQTWaoFGp3Qq5Quq8SqkSM1ElIIujpYyKIq@/x/sI73zyPpcygYVGOs9qBWs@pIdoQG3Gg3pjHczNGncTVR3DgGOaDAPuyF5SmjiV01e5AHjnE@oMGh/1IJEmIqeZK9XfvGH9MNqMjgv8diTUlGzNslnEi0PqrWnEiKuUD "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 4 programs
```
->x{x}
```
The basic stabby lambda form. [Try it online!](https://tio.run/##KypNqvyfZhvzX9euorqi9n@0oY6CUkamUqxeamJyhkJKvkJNZg2XgkJBaUmxglJatGpBrIKtgmqBkmp0po5CWnRmbCxXal7KfwA "Ruby – Try It Online")
```
def f e;e;end
```
The classic way of defining functions in Ruby. [Try it online!](https://tio.run/##KypNqvz/PyU1TSFNIdUaCPNS/kcb6igoZWQqxeqlJiZnKKTkK9Rk1nApKBSUlhQrKKVFqxbEKtgqqBYoqUZn6iikaWRqxnKB9AEA "Ruby – Try It Online")
```
puts(ARGF.to_a.sum(""))
```
Takes the input stream `ARGF` (points to STDIN if no program arguments are present), turns it into an array, combines it again (using `sum` because `join` shares an `n` with the previous program) and outputs it. [Try it online!](https://tio.run/##KypNqvz/v6C0pFjDMcjdTa8kPz5Rr7g0V0NJSVPz/3@P1JycfB2F8vyinBRFAA "Ruby – Try It Online")
```
b=*$<
STDOUT<<b*''
```
`$<` is an alias for `ARGF`. Same as above, but uses the splat operator `*` to turn it into an array, and joins it using the array join operator `*`. [Try it online!](https://tio.run/##KypNqvz/P8lWS8WGKzjExT80xMYmSUtd/f9/j9ScnHwdhfL8opwURQA "Ruby – Try It Online")
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), `-hr`, `-lp` 17 programs
There'll be more soon.
```
#
```
[Try it online!](https://tio.run/##y05N//9f@f9/QyPj/7oZRf91cwoA "Keg – Try It Online")
```
,
```
[Try it online!](https://tio.run/##y05N//9f5/9/Ryfn/7oZRf91cwoA "Keg – Try It Online")
```
.
```
[Try it online!](https://tio.run/##y05N//9f7/9/QyPj/7oZRf91cwoA "Keg – Try It Online")
[Try it online!](https://tio.run/##y05N/w8EhkbG/3Uziv7r5hQAAA "Keg – Try It Online")
```
0+
```
[Try it online!](https://tio.run/##y05N///fQPv/fyMD4/@6GUUA "Keg – Try It Online")
```
1*
```
[Try it online!](https://tio.run/##y05N///fUOv/fyMD4/@6GUUA "Keg – Try It Online")
```
¿
```
[Try it online!](https://tio.run/##y05N////0P7//40MjP/rZhQBAA "Keg – Try It Online")
```
᠀
```
[Try it online!](https://tio.run/##y05N////4YKG//@NDIwB "Keg – Try It Online")
```
∑)
```
[Try it online!](https://tio.run/##y05N////UcdEzf//jQyM/@vmFPzXzSgCAA "Keg – Try It Online")
```
:
```
[Try it online!](https://tio.run/##y05N///f6v9/IwPj/7oZRQA "Keg – Try It Online")
```
"
```
[Try it online!](https://tio.run/##y05N//9f6f9/IwPj/7oZRQA "Keg – Try It Online")
```
±±
```
[Try it online!](https://tio.run/##y05N////0MZDG///NzIw/q@bUQQA "Keg – Try It Online")
```
⅍
```
[Try it online!](https://tio.run/##y05N////UWvv//9GBsYA "Keg – Try It Online")
```
;⑨
```
[Try it online!](https://tio.run/##y05N///f@tHEFf//GxkY/9fNKAIA "Keg – Try It Online")
```
⑵½
```
[Try it online!](https://tio.run/##y05N////0cSth/b@/29kYPxfN6MIAA "Keg – Try It Online")
```
④_
```
[Try it online!](https://tio.run/##y05N////0cTF8f//GxkYAwA "Keg – Try It Online")
```
⑩᠈
```
[Try it online!](https://tio.run/##y05N////0cSVDxd0/P@fmJT8XzejCAA "Keg – Try It Online")
[Answer]
# Scala, 9 functions
```
x=>x
```
A lambda function.
```
math.abs
```
A utility function from the math package.
For the following functions, we use the fact that methods on objects can be converted to functions if no arguments are given.
```
1*
0+
2-2| // bitwise or with (2-2)
~(8&4)& // bitwise and with ~(8&4)
3^3^ // bitwise xor with (3^3)
Nil::: // concat with an empty sequence
```
```
_ ##
```
Here, the underscore is syntactic sugar for a lambda argument. It calls the method `##` on it, which calculates a hash code, but is an identity function for integers.
[Answer]
# [Brainetry](https://github.com/RojerGS/brainetry), 1 program
1 is the maximum score attainable by the [Brainetry](https://github.com/RojerGS/brainetry) programming language. The programs below are cat programs, they take any user input and output it unchanged.
```
a b c d e f
a b c d e f g h
a b c d e f g
a b c d e f
a b c d e f g h i
```
[Brainetry](https://github.com/RojerGS/brainetry) is partially symbol independent but it needs spaces to understand what instruction each line refers to, so a program with no spaces can only be composed of empty lines and lines with one word, corresponding to the `«` and `»` instructions, which are not useful for this challenge.
The program above was golfed from this other program:
```
This program you are currently reading
has the particularity of explaining itself. In fact,
this program has one simple mission :
Take some input provided by you
and throw it right back at your face !!!
```
[Answer]
# [PHP](https://php.net/), 6 programs (functions)
```
abs
fn($n)=>$n
iNtvAl
chop
HeBreV
TRIm
```
[Try it online!](https://tio.run/##LYwxC8IwEIX3/IqjBC4BEapjTEUnXRxEXGqHWBJTqGloaxfxt8eE9oa77917PG992O193NR8XD2AhBJQPQdcARrHqOOyoC6p5jJOhzZRbTuf7kkfe31PdLue3wiVIKbrtaotW9rUADPxL4E4elItQ2okwnpxIqBALmY/Vsc/a9yYklT1r6nMK85jKnu4TJBfCCHfbP8 "PHP – Try It Online")
We're taking advantage of PHP looseness about functions lower/upper case and types (all these fall into first case: taking an integer and return it unchanged), still searching for more
[Answer]
# Clojure, 8 functions
They are:
```
+
*
/
->
do
max
str
(fn[n]n)
```
Arithmetic operations in Clojure are variadic functions that when given only one argument return it unchanged, and thus work as identity functions for numerics.
Minus is an exception, because with one argument it becomes unary negation. But in its place we can use threading macro `->`, which with no further functions to apply returns the supplied value as is.
`do` is a special form that is normally used to group several expressions into one and returns the value of the last one (in our case - the only one).
`max` of one entry is obviously equal to the entry itself.
`str` converts the argument to string, and so is the identity for strings.
Finally, the last one is an explicitly written out identity function.
Many important letters are now exhausted, and with `()` used up we aren't going anywhere further in a Lisp. I haven't included several other possible functions because they collide with those above:
```
identity
min
and
or
```
[Answer]
# Rust, 2 functions
```
|x|x
i8::abs
```
Sadly, the colon is needed for all other ways to define a function.
[Answer]
# [Zsh](https://www.zsh.org/), 4 functions/math functions
```
()((argv)) # bind as a math function
int # math function from zsh/mathfunc
echo -E - $@ # string arg to stdout
<&0 # stdin to stdout
```
[Try it online!](https://tio.run/##HYy9CsMgAIR3n@IGITqE0lBaurVDx75BFvNjFKIGtSVN6bNbDQfHfRx3W1BpM26YnRiwBXUwIir5sj0pFrWzAfUTBscsQ4hpE@OMCT@9OSfSeUgLZiC6AFmsH/UMObvcaBtLEpF/CYCxVw6UMVBp2anhyAe/RKulXS9Nu56vNlaoaVUwB9Ab2Sf1Y4eU7r7T0Qv/QYhe2@kP "Zsh – Try It Online")
This is with `zmodload zsh/mathfunc` for `int`.
This is not the only combination of 4 functions, but it is the shortest set I found that only uses a single `zsh/mathfunc` function.
Either `echo` or `print` can use `$'\xHH'` notation to replace conflicting characters, in which case `ceil` can also be substituted in place of `int`.
[Answer]
# J, 13 functions
## Either
`[` and `]` return their arguments.
`>` removes their argument from a box. Strings and integers don't have boxes.
## Rank 0 Array
(characters or integers)
`=/` acts on a more than length 1 array. Rank 0 arrays are always length 1.
## Positive Integers
`|` is magnitude, which is `abs(x)` in Python. Does nothing for positive integers.
`+` is complex conjugate, which negates the imaginary part.
`----` negates the number 4 times.
`%%%%` takes the reciprocal of the number 4 times.
`**` is a hook that becomes `y*(*y)`. For positive integers, `*y` always returns 1. That means `(**)y` is `y*1`.
`^#` is a hook that becomes `y^(#y)`. For rank 0 arrays, `#y` always returns 1. That means `(^#)y` is `y^1`.
`<.` rounds down a number to the nearest integer. The nearest integer from an integer is the integer itself.
`1&!` returns how many ways you can pick 1 ball from a bag of `y` balls, which is `y`.
`0}~` works.
[Answer]
# Vyxal, 108 bytes, 67 answers
1. (Empty) [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=&inputs=1&header=&footer=)
2. (Space) [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%20&inputs=1&header=&footer=)
3. (Newline) [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%0A&inputs=1&header=&footer=)
4. `#` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=#&inputs=1&header=&footer=).
5. `?` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=?&inputs=1&header=&footer=).
6. `_` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=_&inputs=1&header=&footer=).
7. `:` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=:&inputs=1&header=&footer=).
8. `D` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=D&inputs=1&header=&footer=).
9. `∑` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%91&inputs=1&header=&footer=).
10. `£` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%A3&inputs=1&header=&footer=).
11. `∴` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%B4&inputs=1&header=&footer=).
12. `∵` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%B5&inputs=1&header=&footer=).
13. `ṅ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%B9%85&inputs=1&header=&footer=).
14. `¤j` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%A4j&inputs=1&header=&footer=)
15. `÷Ṡ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C3%B7%E1%B9%A0&inputs=Hello%2C%20world!&header=&footer=).
16. `1/` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=1/&inputs=14&header=&footer=).
17. `⁰` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%81%B0&inputs=14&header=&footer=)
18. `¹` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%B9&inputs=14&header=&footer=)
19. `d½` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=d%C2%BD&inputs=14&header=&footer=)
20. `ƒh` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C6%92h&inputs=14&header=&footer=)
21. `²√ṙ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%B2%E2%88%9A%E1%B9%99&inputs=14&header=&footer=)
22. `‹›` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%80%B9%E2%80%BA&inputs=14&header=&footer=)
23. `ɾL` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C9%BEL&inputs=14&header=&footer=)
24. `øCĖ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C3%B8C%C4%96&inputs=153&header=&footer=)
25. `→` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%86%92&inputs=153&header=&footer=)
26. `±` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%B1&inputs=Hello%2C%20world!&header=&footer=)
27. `⅛` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%85%9B&inputs=14&header=&footer=)
28. `ɖt` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C9%96t&inputs=4&header=&footer=)
29. `₴` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%82%B4&inputs=153&header=&footer=)
30. `,` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%2C&inputs=153&header=&footer=)
31. `…` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%80%A6&inputs=4&header=&footer=)
32. `ḣJ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%B8%A3J&inputs=Hello&header=&footer=)
33. `ṫ+` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%B9%AB%2B&inputs=Hello&header=&footer=)
34. `v` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=v&inputs=Hello&header=&footer=)
35. `↔` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%86%94&inputs=Hello&header=&footer=)
36. `•` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%80%A2&inputs=Hello&header=&footer=)
37. `(₈)!` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%28%E2%82%88%29!&inputs=9&header=&footer=)
38. `I` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=I&inputs=9&header=&footer=)
39. `$` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%24&inputs=9&header=&footer=)
40. `Ŀ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C4%BF&inputs=Hello%2C%20world!&header=&footer=)
41. `NN` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=NN&inputs=9&header=&footer=)
42. `S` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=S&inputs=Hello%2C%20world!&header=&footer=)
43. `V` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=V&inputs=9&header=&footer=)
44. `Yy` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=Yy&inputs=Hello%2C%20world!&header=&footer=)
45. `^` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%5E&inputs=Hello%2C%20world!&header=&footer=)
46. `ei` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=ei&inputs=Hello%2C%20world!&header=&footer=)
47. `g` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=g&inputs=5&header=&footer=)
48. `G` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=G&inputs=5&header=&footer=)
49. `s` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=s&inputs=5&header=&footer=)
50. `⌈` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%8C%88&inputs=5&header=&footer=)
51. `⌊` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%8C%8A&inputs=5&header=&footer=)
52. `ȧ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C8%A7&inputs=5&header=&footer=)
53. `ġ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C4%A1&inputs=5&header=&footer=)
54. `ṁ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%B9%81&inputs=5&header=&footer=)
55. `0ȯ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=0%C8%AF&inputs=5&header=&footer=)
56. `@a|` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%40a%7C&inputs=5&header=&footer=)
57. `Aẋ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=A%E1%BA%8B&inputs=Hello%2C%20world!&header=&footer=)
58. `§` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%A7&inputs=Hello%2C%20world!&header=&footer=)
59. `ε` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%CE%B5&inputs=Hello%2C%20world!&header=&footer=)
60. `µ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%B5&inputs=5&header=&footer=)
61. `wṄ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=w%E1%B9%84&inputs=Hello&header=&footer=)
62. `↵⁋` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%86%B5%E2%81%8B&inputs=Hello&header=&footer=)
63. `ṘṘ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%B9%98%E1%B9%98&inputs=Hello%2C%20world!&header=&footer=)
64. `Ḃ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%B8%82&inputs=4&header=&footer=)
65. `Π` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%CE%A0&inputs=5&header=&footer=)
66. `„` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%80%9E&inputs=5&header=&footer=)
67. `‟` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%80%9F&inputs=5&header=&footer=)
68. `[` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%5B&inputs=5&header=&footer=)
69. `∇` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%87&inputs=5&header=&footer=)
70. `⋎` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%8B%8E&inputs=5&header=&footer=)
71. `⋏` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%8B%8F&inputs=5&header=&footer=)
72. `ꜝꜝ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%EA%9C%9D%EA%9C%9D&inputs=5&header=&footer=)
73. `⇧⇩` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%87%A7%E2%87%A9&inputs=5&header=&footer=)
74. `¬Ǔ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%AC%C7%93&inputs=Hello&header=&footer=)
75. `¥ǔ` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%A5%C7%94&inputs=Hello&header=&footer=)
76. `꘍꘍` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%EA%98%8D%EA%98%8D&inputs=54&header=&footer=)
This took well over two hours.
[Answer]
# [str](https://github.com/ConorOBrien-Foxx/str), 19 programs
This is a very flexible language, because the empty program works, and there are a lot of no-op functions, or things that can be combined into no-ops. All of these are programs taking strings as input.
1. The empty program
2. A space character
3. A tab character
4. A newline character
5. `.` (this and the whitespace above explicitly do nothing)
6. `;` (the `;` character is used as a separator and does nothing by itself)
7. `3~` (push a value, then swap it. The language only pays attention to the top value of the stack for each character)
8. `2$` (push a value, then discard it)
9. `e:` (concatenate each character with the empty string)
10. `oq` (explicitly print each character, then tell the language not to implicitly print it)
11. `1x` (repeat each character one time)
12. `bu` (move each character to the buffer, then back to the stak)
13. `yc` (convert to a number, then back to a string)
14. `m` (convert to a string, which it already is)
15. `XY` (increment by one codepoint, then decrement again)
16. `w` (unlike all the above programs, this adds a trailing newline. I have no idea why this works)
17. `0-` (subtracts 0 from each character)
18. `_` (`_` is the reverse function, except it operates on each character individually, so does nothing here)
19. `d` (duplicates each character, but the implicit output only prints one character per input, so this amounts to nothing)
[Answer]
# Python 3, 5 solutions (a program, three functions and a default-value variable)
I see there's already a Python 3 answer, but I thought I'd try and make another one anyway. Or should it have been a comment?
* `exec("p\x72\x69\x6e\x74(\x69\x6epu\x74())")` # reads a line from standard input and writes it to standard output, the code has most letters escaped so they aren't directly included, and then the quotes unescape them and exec runs them
* `str` # returns an argument as a string
* `lambda a:a` # returns an argument
* `''.join` # returns a string with nothing inserted between the characters
* `_` equals the previous line (this one only works in the interactive interpreter, but the other ones work there too, so it should probably be okay). I think I saw some solution to another puzzle here using a default variable like that as an input, so hope that's okay. Otherwise this is four solutions, like the other answer.
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 3 programs
><> has exactly two characters that can be used for output. `n` prints an integer.
Program 1:
`n;`
The other output character is `o`, printing an ascii character. Since we have already spent the program terminator `;` and programs are required to halt, we can trigger the "something smells fishy..." by division by zero
Program 2:
`io00,`
But yet another program is still possible. A `n` or `o` character can be obtained by reflection, which only `p` can perform.
Program 3:
`ab*aa-:p4f*1-1aa-p`
The useable IO instructions in ><> are then depleted.
[Answer]
# Elixir, 5 functions
```
+
abs
round
ceil
&(&1)
```
Well, unary `+` is technically an operator, but I think it should count, as it really quacks like a function in Elixir. For instance, it can be captured and passed as an argument to a higher-order function in the same way as a named function, and even the syntax for overriding unary operators is like defining normal functions.
The next three are numerical functions that work as identity for positive integers. These are all defined in `Kernel` module (`ceil` available from version 1.8+), which is imported by default, and thus callable directly without qualifying the module name.
Finally, the last one is a shorthand form of the explicit identity function.
As always, there are other unused candidates that share characters with those above. In particular, the letter `n` is rather "popular":
```
floor
trunc
to_string
Function.identity
fn n->n end
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 1 function and 9 programs
Functions:
1. [`λ;`](http://lyxal.pythonanywhere.com?flags=&code=%CE%BB%3BM&inputs=%5B0%2C1%2C2%2C3%5D&header=&footer=) - A lambda that does nothing.
Programs:
1. [The empty program](http://lyxal.pythonanywhere.com?flags=&code=&inputs=%5B0%2C1%2C2%2C3%5D&header=&footer=) - Nothing happens to the input, so it remains on top of the stack (and gets popped off at the end).
2. [`#`](http://lyxal.pythonanywhere.com?flags=&code=%23&inputs=10.4&header=&footer=) - Basically the same as the empty program, except it has an (empty) comment too.
3. [`:`](http://lyxal.pythonanywhere.com?flags=&code=%3A&inputs=%5B0%2C1%2C2%2C3%5D&header=&footer=) - Duplicate the input. Since we only care about the top of the stack, this can be treated as an identity function even though it leaves trash behind.
4. [`D`](http://lyxal.pythonanywhere.com?flags=&code=D&inputs=%5B0%2C1%2C2%2C3%5D&header=&footer=) - In the same vein as the previous program, this triplicates the input.
5. [`SE`](http://lyxal.pythonanywhere.com?flags=&code=SE&inputs=%5B0%2C1%2C2%2C3%5D&header=&footer=) - Convert to string, then evaluate.
6. [`d½`](http://lyxal.pythonanywhere.com?flags=&code=d%C2%BD&inputs=10.4&header=&footer=) - Double, then halve.
7. [`,`](http://lyxal.pythonanywhere.com?flags=&code=%2C&inputs=10.4&header=&footer=) - Print the input.
8. [`¤$F`](http://lyxal.pythonanywhere.com?flags=&code=%C2%A4%24F&inputs=foobarbaz&header=&footer=) - Finally, an almost non-trivial program! This one pushes the empty string, swaps with the input, then keeps all the characters in the input that aren't in the empty string (which is all of them). It also works with normal lists, but errors.
9. [`ṙ`](http://lyxal.pythonanywhere.com?flags=&code=%E1%B9%99&inputs=10&header=&footer=) - Round an integer.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~14~~ ~~15~~ 16 functions
Verify: [with `Re`](https://tio.run/##y00syUjNTSzJTE78n1aal1ySmZ9XbKukrMal8n7SQhWuqhpduyqutHh9/TTbNK6YGAMTYxBhxvWop@tRT/fjhlme2p4KQPi4YTaXhoahuiYIa0ZHG6pHG8bGxnK5cPlx@RdxOealcPk4@3IF55dzuVZklnAF5JQWcwWlKv1PqixJLbb1yy/KTczRdwguKcrMSw/JdwKKOhYVJVbChIILcjJLouFO1FGKyVOK5QoASpXoO4DNgHCiIeaF5gFVQSWgyqJdSoFmJCeWpLoVpaYGRnvlZ@Y5QFXE/v8PAA) or [with `Ramp`](https://tio.run/##y00syUjNTSzJTE78n1aal1ySmZ9XbKukrMal8n7SQhWuqhpduyqutHh9/TTbNK6YGAMTYxBhxvWop@tRT/fjhlme2p4KQPi4YTaXhoahuiYIa0ZHG6pHG8bGxnK5cPlx@RdxOealcPk4@3IF55dzuVZklnAF5JQWcwUl5hYo/U@qLEkttvXLL8pNzNF3CC4pysxLD8l3Aoo6FhUlVsKEggtyMkui4Y7UUYrJU4rlCgBKleg7gM2AcKIh5oXmAVVBJaDKol1KgWYkJ5akuhWlpgZGe@Vn5jlAVcT@/w8A)
Mathematica only has so many ways to define a function.
1. [`#&`](https://tio.run/##DcO9CoAgEADgvdcQWjLQoLEwaI4oaBGH648O8gS7nt/64PPA1@GBcYN0Nknkad6A7BiR2IqyPY1wucx00a2PmcJLu5mA9uAXiAh82CFED3ePD0dcX8ZAVisl/8rJqnYufQ "Wolfram Language (Mathematica) – Try It Online").
A function that returns its first argument.
2. [`$$`](https://tio.run/##y00syUjNTSzJTE78n2b7X@X9pIUq/4OTE/OiA4oy80qilXXt0hyUY9V0uAy1HZOKHYLyS/NSHIIS81Lyc8MSizITS1Kj/fKLchNzXDKLS4oyk0pLMvPzog0NDHSA2CBWx8g0NvY/AA "Wolfram Language (Mathematica) – Try It Online").
A function of one variable that returns that variable. `` is [U+F4A1](https://reference.wolfram.com/language/ref/character/Function.html).
3. `z|->z`. Identical to #2. `|->` was [added in 12.2](https://reference.wolfram.com/language/guide/SummaryOfNewFeaturesIn122#411725539).
4. [`f_//f=f`](https://tio.run/##DcPBCoQgEADQe78RdMnQFva4i0HniIK9iCxTKQ3kCDZ9v/XgBeDdBWBcIWf/l9J/fJ5XIDMmJDZl8/W6tJUo2rpbTj3FizY9AW0x/CAhsDNDTAGOHk9OuFyMkUyrlHgqK15va/MN "Wolfram Language (Mathematica) – Try It Online").
Defines a function `f` that returns its argument.
5. [`\043\046`](https://tio.run/##y00syUjNTSzJTE78n2b7P8bAxBiIzf4HJyfmRQcUZeaVRCvr2qU5KMeq6XAZajsmFTsE5ZfmpTgEJeal5OeGJRZlJpakRvvlF@Um5rhkFpcUZSaVlmTm50UbGhjoALFBrI6RaWzsfwA "Wolfram Language (Mathematica) – Try It Online").
Escape sequences for `#&`.
6. [`⌊⌋〚I+I I I〛`](https://tio.run/##y00syUjNTSzJTE78n2b7/1FP16Oe7scNszy1PRWA8HHD7P/ByYl50QFFmXkl0cq6dmkOyrFqOlyG2o5JxQ5B@aV5KQ5BiXkp@blhiUWZiSWp0X75RbmJOS6ZxSVFmUmlJZn5edGGBgY6QGwQq2NkGhv7HwA "Wolfram Language (Mathematica) – Try It Online").
The floor function `Floor[][[0]]` = `Floor`. `⌊⌋〚〛` are [U+230A](https://reference.wolfram.com/language/ref/character/LeftFloor.html), [U+230B](https://reference.wolfram.com/language/ref/character/RightFloor.html), [U+301A](https://reference.wolfram.com/language/ref/character/LeftDoubleBracket.html), and [U+301B](https://reference.wolfram.com/language/ref/character/RightDoubleBracket.html), respectively.
7. [`((1')(1'))[[1'[1]]]`](https://tio.run/##Fcy9CsIwEADg3dco2BYj5ARHJYKzSAWX44brHx6YC6TX5491@NYvsn2myCYDl/lSmgbq9q9FhBqBiMprYMVnFjWsjtc5VLR3Ozjc@iV0adUxdKxjim/OwjbhI@XI37sslqVfTZIieO82ntzpvIU/ "Wolfram Language (Mathematica) – Try It Online")
The exponent function `Times[1', 1'][[1'[1]]]` = `Power[0&, 2][[0]]` = `Power`. Returns the argument when called with only one argument.
---
But there are also a good number of built-ins up to the task.
8. [`D`](https://tio.run/##DcNBC0AwFADgu7@hXEyNcqQpZ4lyWTs8bHllbzXP7x9ffR74sh4YD0iuS2NaDyA9RyTWedU7lZtCZHU57I9awkunWoDO4DeICGz1FKKHe8SHI@4vYyBdSyn@0oimNSZ9 "Wolfram Language (Mathematica) – Try It Online").
Computes the [derivative](https://reference.wolfram.com/language/ref/D.html), but acts as identity when passed only one argument.
9. [`N`](https://tio.run/##DcNBC0AwFADgu7@hXEyNcqQpZ4lyWTu8DXllbzXP7x9ffR74OjwwOkhnl6a0OiA9RyTWedWfKjeFyOpysI9awku7WoD24DeICHzoKUQP94gPR7QvYyBdSyn@0oimNSZ9 "Wolfram Language (Mathematica) – Try It Online").
Converts the argument to a numeric (approximate) value. For `Integer`s, returns the `Rational` corresponding to that integer.
10. [`Or`](https://tio.run/##y00syUjNTSzJTE78n2b737/of3ByYl50QFFmXkm0sq5dmoNyrJoOl6G2Y1KxQ1B@aV6KQ1BiXkp@blhiUWZiSWq0X35RbmKOS2ZxSVFmUmlJZn5etKGBgQ4QG8TqGJnGxv4HAA "Wolfram Language (Mathematica) – Try It Online").
Logical or. Returns the argument when called with only one argument.
11. [`And`](https://tio.run/##DcNBC0AwFADgu7@hXExtypGmnCXKZe3wGHllbzXP7x9ffR74Ojww7pDONvXk0rIDmSkiscmr7tS5LUSmyn579BxecnoGcsGvEBH4MGOIHu4BH464vYyBjJJS/KUVdWNt@gA "Wolfram Language (Mathematica) – Try It Online").
Logical and. Returns the argument when called with only one argument.
12. [`LCM`](https://tio.run/##y00syUjNTSzJTE78n2b738fZ939wcmJedEBRZl5JtLKuXZqDcqyaDpehtmNSsUNQfmleikNQYl5Kfm5YYlFmYklqtF9@UW5ijktmcUlRZlJpSWZ@XrShgYEOEBvE6hiZxsb@BwA "Wolfram Language (Mathematica) – Try It Online").
Computes the least common multiple of its arguments.
13. [`Sow`](https://tio.run/##y00syUjNTSzJTE78n2b7Pzi//H9wcmJedEBRZl5JtLKuXZqDcqyaDpehtmNSsUNQfmleikNQYl5Kfm5YYlFmYklqtF9@UW5ijktmcUlRZlJpSWZ@XrShgYEOEBvE6hiZxsb@BwA "Wolfram Language (Mathematica) – Try It Online").
Returns its argument. Additionally, allows that value to be collected by an enclosing `Reap`.
14. [`Exit`](https://tio.run/##NU5NC4JAFLz7KxaDTooW2K3YoA5dIiy6yEIvXe2Buytv31L/3hTqMIf5YGYM8EsbYKxhrF2jt/F4/CCPcZZdmdB2N0ITsTZDD6y3P@1HZfx2fUtgfE04sEjbYGtGZ8XjIVKPnQUOpMXJsu40iRSo85MXRwdXXaYmrhbprgxW/geq@UOyUNm62Kil3D@9LF2wjSzBNs7cgXBOnR0Z6A/opzvPMC9WqzxPJuRKJVGhxi8 "Wolfram Language (Mathematica) – Try It Online"). A function that returns an integer via exit code.
Note that `Run` returns 256\*(return code) on TIO instead. [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@oNC9aqaCyJCM/T0E3WUE9tSKzRMNQU10pVl8/oCgzr@T/fwA "Wolfram Language (Mathematica) – Try It Online")
[![Exit[927] on Mathematica 12.1 for Windows](https://i.stack.imgur.com/fseEJ.png)](https://i.stack.imgur.com/fseEJ.png)
15. [`Plus`](https://tio.run/##DcO9CoAgEADgvdcIWjKwoLEwaI4oaBGH648O8gQ9n9/64LPAz2WB8YB0d2l@Y0jrAaRnj8Q6r/pb5aYQWV0Oe1CLi3SqBeh0dgOPwJeenLfwjhjY4x4ZHelaSvGXRjStMekD "Wolfram Language (Mathematica) – Try It Online").
Returns the sum of its arguments.
---
[Answer]
# [Julia](http://julialang.org/), 12 functions
```
X->X
==(==)=(==)
*
+
&
|
⊻
Real
sum
prod
big
Int
```
[Try it online!](https://tio.run/##yyrNyUw0rPjvo2CrEP0/QtcugkvD1haINMGEtSaXFpc2lxpXDdejrt1cQamJOVzFpblcBUX5KVxJmelcnnkl/2O50vKLFNIUMvMUfLgUgKCgKDOvJCdPI03DxEhTkys1L@U/AA "Julia 1.0 – Try It Online")
[More identity functions!](https://tio.run/##PY9NSgNBEIXXvlO0GdAZxUDU7bgZEHThQjchu57@mXTo7hr6J0zAAwSv5G1ykbGThbUo6j2ox/d22Rq@muZ5/fCyxvWm3eAO97jBN04/v5gogMsdGZ@QAvdxpKhgpPLJpAO@UjB@wJtPV3i1xNPTI3ozIJrBK4lA2UtoSyVFKGPBozAG5zjwPkKbEBMEjQdYXi5XfMcnxOwwBpJQe27hs1OBp5JRkbcHVqbySsnI3s/wbLV8RrXnYXG7gBUOg5D4VOXxI7teBXTkRqsmdGLLi5KUe6vQnSt1lgp@F7cUEnT2IhnytW6YZqqQ15ppCkUYz1bNUv8bp@Pxotu2btvmsub5Dw "Julia 1.0 – Try It Online")
[Answer]
# Java, 2 functions
```
x->x
```
A lambda function.
```
Function.identity()
```
This returns the identity function.
Without the letters *e* and *t*, we can't use any of the `{byte,char,short,int,long}Value`, `valueOf` or `toString` methods.
] |
[Question]
[
## Concept
Write a program that outputs code in its programming language. That code, when executed, must output the original program.
## Rules
* Since this is a cheating quine, you can read the original source code.
* First output program must be in the same language as the original program.
* You may not output a regular quine. The two programs must be different.
* Standard loopholes apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer wins, however it will not be selected.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, 11 bytes
```
tr xy yx<$0
```
This prints
```
tr yx xy<$0
```
[Try it online!](https://tio.run/nexus/bash#@19SpFBRqVBZYaNi8P8/AA "Bash – TIO Nexus")
In turn, that prints
```
tr xy yx<$0
```
[Answer]
# Snails, 0 bytes
The second program is
```
1
```
The first program counts the number of matches of the empty pattern on the empty input (which really has area 0, but the pattern is always run at least once as a hack to allow programs to decide what they want to print on empty input). The second program begins with a quantifier (like `{1}` in regex), which causes a parse error. Since the program does not parse successfully, STDOUT is the empty string.
[Answer]
# [7](http://esolangs.org/wiki/7), 2 bytes
7 uses a 3-bit character set, but takes input packed into bytes (and according to meta, [languages with sub-byte character sets are counted using bytes for the file on disk](http://meta.codegolf.stackexchange.com/a/10810/62131)). Here's an `xxd` dump of the program:
```
00000000: 4cf4 L.
```
When giving this file to the 7 interpreter, it will output the following program:
```
00000000: 4fa6 7f O..
```
which will then in turn output the original program again.
So what's happening here? There's no source reading involved (actually, I don't think it's possible to read the source in 7), although arguably the program is cheating in another way; let me know what you think. Here's how the program works. (Note that each 7 command has two variants, some of which don't have names and can't appear in the original program. There are twelve commands total, in six pairs. I'm using bold for active commands, nonbold for passive commands, and in cases where the active command has no name, I'm giving it the same name as the corresponding passive command and relying on the bold to distinguish. In the case where both are named, e.g. `**7**` which is the active variant of `1`, each command gets its own name and the bold is just syntax highlighting.)
```
231**7**23 Original program, unpacked into octal
231 Push **237** onto the stack
23 Push **23** onto the stack
(implicit) append a copy of the top of stack to the program
**2** Duplicate top of stack (currently **23**)
**3** Output top of stack, pop second stack element
```
At this point, the 7 interpreter sees that the top of stack contains commands (**`2`** and **`3`**) that aren't representable, so it escapes the top of the stack, producing `**7**23` (which is). The first command output selects the output format; in this case, it's format 7, "format the output the same way as the program". So the commands get output packed into bytes. Then the program continues:
```
231**7**23**23**
(implicit) append a copy of the top of stack to the program
**2** Duplicate top of stack (currently **237**)
**3** Output top of stack, pop second stack element
**7** Push an empty element onto the stack
```
At this point, there's nothing but empty stack elements on the stack, so the program exits. We output `23` earlier. If we escape **`237`** (and we have to, because it contains unrepresentable commands), we get `**7**231`. That gets output directly, making the final output of the program `237231` (formatted the same way as the program, i.e. packed into bytes). That's `4fa67f`. (It can be noted that the `1` was entirely pointless in terms of affecting the output; the only reason it's there is to make the two programs different.)
Running `237231` proceeds almost exactly the same way; the difference is that the useless `1` runs just after the first print (and the empty element gets implicitly deleted the second time the current end of the program is reached). Again, the `231` ends up outputting itself, the `23` ends up outputting itself preceded by a `7`, and we get `231723`, the original program.
The observant might note that the two programs, despite being the same length in the language's "native" octal, are different lengths on disk. That's because a 7 program can be padded with an arbitrary number of 1 bits, and the packed format discards the trailing padding. Here's how the encoding happens:
```
2 3 1 7 2 3
010011001111010011(1...)
4 c f 4 padding
```
In other words, two bytes, `4C` `F4`, are enough to represent the program, so that's all I used.
[Answer]
# Python 3, ~~297~~ ~~279~~ ~~251~~ ~~243~~ ~~225~~ ~~218~~ ~~208~~ ~~180~~ ~~126~~ 111 bytes
Non-cheating:
```
A=''';print(("A="+("'"*3+A)*2).translate({65:66,66:65}))''';print(("A="+("'"*3+A)*2).translate({65:66,66:65}))
```
This prints:
```
B=''';print(("B="+("'"*3+B)*2).translate({65:66,66:65}))''';print(("B="+("'"*3+B)*2).translate({65:66,66:65}))
```
which, when executed, prints the original program.
[Answer]
## Batch, 14 bytes
```
@echo @type %0
```
Which when run as `cyclicquine.bat` outputs
```
@type cyclicquine.bat
```
Which when run outputs the original batch file.
[Answer]
# [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 4 Bytes.
[The community seems to consider this sort of thing as a cheating quine](https://codegolf.stackexchange.com/a/78/58375), which thus satisfies the criteria.
```
1
2
```
With a trailing newline.
This prints
```
2
1
```
With a trailing newline, which prints the first code.
RProgN prints the stack popping, so from top to bottom.
[Try it online!](https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=1%0A2%0A&input=)
[Answer]
# Jolf, 6 bytes
```
1q_a_q
```
When run, this outputs:
```
q_a_q1
```
Which in turn outputs `1q_a_q`.
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=MXFfYV9x)
# Explanation
```
1q_a_q
1 the digit one (ignored)
q the source code (ignored)
q the source code
_ reversed
a and outputted
_ and reversed (ignored)
q_a_q1
q the source code (ignored)
1 the digit one (ignored)
q the source code
_ reversed
a and outputted
_ and reversed (ignored)
```
[Answer]
# JavaScript (ES6), ~~69~~ ~~60~~ 59 bytes
```
(_0=_=>console.log(`(_0=${_0})()`.replace(/0/g,n=>+!+n)))()
```
Outputs:
```
(_1=_=>console.log(`(_1=${_1})()`.replace(/1/g,n=>+!+n)))()
```
---
-1 byte (@ETHProductions): use 0 in regex instead of \d
[Answer]
# Bash + Sed, 15 bytes
Same idea as [Dennis's Answer](https://codegolf.stackexchange.com/a/102940/48922).
```
sed y/xz/zx/ $0
```
[Answer]
# Bash, ~~Cat,~~ and Rev, ~~19~~ 16 bytes
```
rev $0 # 0$ ver
```
*-3 thanks to @izabera*
[Answer]
## ><>, 16 bytes
```
"$r00gol?!;50.01
```
[Try it here!](https://starfish.000webhostapp.com/?script=EQEgTgDBDmD2A2B+AhAbgKwQHQQIxA)
**Outputs**
```
"$r00gol?!;50.10
```
This is a modification of the one provided [here](https://esolangs.org/wiki/Fish#Quine). I'm not sure if it's cheating, it reads the codebox and outputs it.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 55 bytes
```
N,s[];main(){*s^=read(open(__FILE__,0),s,54);puts(s);}
```
Note the trailing newline.
First run:
```
x,s[];main(){*s^=read(open(__FILE__,0),s,54);puts(s);}
```
[Try it online!](https://tio.run/##S9ZNT07@/99Ppzg61jo3MTNPQ7NaqzjOtig1MUUjvyA1TyM@3s3TxzU@XsdAU6dYx9RE07qgtKRYo1jTupbr/38A "C (gcc) – Try It Online")
Second run:
```
N,s[];main(){*s^=read(open(__FILE__,0),s,54);puts(s);}
```
[Try it online!](https://tio.run/##S9ZNT07@/79Cpzg61jo3MTNPQ7NaqzjOtig1MUUjvyA1TyM@3s3TxzU@XsdAU6dYx9RE07qgtKRYo1jTupbr/38A)
This one is rather simple. It reads the file, and XORs the first byte (technically first `int`, but it is effectively the same) with `54`. Since it is an unused variable, it doesn't affect anything.
Note that this abuses the empty array cheat where GCC will let you write up to one page in an array with empty brackets. It also expects the page to be zero filled, which is the default.
A version which does not write out of bounds is this:
```
y,s[15];main(){*s^=read(open(__FILE__,0),s,56);puts(s);}
```
[Try it online!](https://tio.run/##S9ZNT07@/79Spzja0DTWOjcxM09Ds1qrOM62KDUxRSO/IDVPIz7ezdPHNT5ex0BTp1jH1EzTuqC0pFijWNO6luv/fwA)
Which will turn into this
```
A,s[15];main(){*s^=read(open(__FILE__,0),s,56);puts(s);}
```
[Try it online!](https://tio.run/##S9ZNT07@/99Rpzja0DTWOjcxM09Ds1qrOM62KDUxRSO/IDVPIz7ezdPHNT5ex0BTp1jH1EzTuqC0pFijWNO6luv/fwA)
I xor against `read()` because it returns the number of bytes read, and it is shorter than XORing against a constant.
[Answer]
# [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), ~~22~~ 20 bytes
Note that SMBF stores the program itself to the left of the initial pointer.
```
~<[<]>[-<->]<.>>[.>]
```
[Try it online!](https://tio.run/##K85NSvv/v84m2ibWLlrXRtcu1kbPzi5azy72/38A)
It will output this (replace `\x82` with a `0x82` byte)
```
\x82<[<]>[-<->]<.>>[.>]
```
Which in turn will print this:
```
~<[<]>[-<->]<.>>[.>]
```
Explanation:
```
~ Dummy byte to be negated to 0x82 (or on second, 0x7e or ~)
<[<] Scan backwards to the start of the program
> Go forwards to the first byte
[-<->] Negate cell 0 into cell minus 1
<. Print the negated byte
>> Skip to the second byte of the program
[.>] Print the rest of the program
```
Because I can't directly do it with TIO because it treats inputs as UTF-8, here is a Bash script version which prints outputs with `xxd`:
[Try it online!](https://tio.run/##S0oszvj/P7UiNVnByE7NkKs4tURBt4yroCgzryRNQanOJtom1i5a10bXLtZGz84uWs8uVknBTqEktbhErzg3KY2roiJFQTfdEEmESz@/oEQfxAQTCBmoPiOoMmSdRri1GiHrNcaiFyL2/z8A)
# [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/) (infinite loop, theoretical), 15 bytes
This version is shorter, but instead of exiting normally, it hangs in an infinite loop. Note that you won't see this in the console as the console is line buffered.
```
<[.<]-[][+]<.[<
```
[Try it online!](https://tio.run/##K85NSvv/3yZazyZWNzo2WjvWRi/a5v9/AA)
This will print this:
```
<[.<]+[][-]<.[<
```
which, when run, will print this
```
<[.<]-[][+]<.[<
```
[Try it online!](https://tio.run/##K85NSvv/3yZazyZWOzo2WjfWRi/a5v9/AA)
**Note that in both cases, the code will get stuck in an infinite loop after printing, so you have to manually stop TIO or wait for the timeout**
Explanation:
```
<[.<] Print the program backwards
-[] Enter an infinite loop to avoid executing the backwards code
[+]<.[< The same code backwards (minus the last bracket) which uses a minus
instead of a plus before the infinite loop.
```
My previous 11 byte infinite loop solution:
```
<[.<]]<.[<+
```
[Try it online!](https://tio.run/##K85NSvv/3yZazyY21kYv2kb7/38A "Self-modifying Brainfuck – Try It Online")
I *thought* this was an infinite loop which just sat there spinning, but the instruction pointer will eventually underflow and the program will *very slowly* print endless `0x00` as it tries to traverse a 4 GB loop.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
`:qpq`:qpq
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%60%3Aqpq%60%3Aqpq&inputs=&header=&footer=)
This outputs
```
`\`:qpq\`:qpq`
```
Which outputs the original code.
The first is a quine that unevaluates itself, and the second is a string.
] |
[Question]
[
Write the shortest code in the language of your choice to perform run length decoding of the given string.
The string will be supplied as **input on stdin** in the form
```
CNCNCNCNCNCNCNCN
```
where each `C` could be any printable ASCII character and each `N` is a digit `1` to `9` (inclusive).
Sample input:
```
:144,1'1
```
Corresponding output:
```
:4444,'
```
[Answer]
# Brainfuck, 34 characters
```
,[>,>++++++[<-------->-]<[<.>-]<,]
```
[Answer]
# [Shakespeare Programming Language](http://esolangs.org/wiki/Shakespeare), 406 bytes
```
.
Ajax,.
Ford,.
Act I:.
Scene I:.
[Enter Ajax and Ford]
Scene II:.
Ford:
Open your mind.Is sky nicer than you?If so, let us return to scene IV.
Ajax:
Open your mind.You is sum you and sum big big big big big big pig and big big big big cat!
Scene III:.
Ford:
Speak thy mind.
Ajax:
You is sum you and pig!Is you as big as zero?If so, let us return to scene II.Let us return to scene III.
Scene IV:.
[Exeunt]
```
Ungolfed version:
```
The Decoding of the Lengths of Veronan Runs - A Drama of PPCG.
Romeo, quite a character.
Juliet, Romeo's lover and multiplicand.
Act I: In which the lengths of runs are decoded.
Scene I: A silent entrance.
[Enter Romeo and Juliet]
Scene II: In which neither Romeo nor Juliet believes the other open-minded.
Juliet:
Open your mind. Is my mother jollier than thou? If so,
we must proceed to scene IV.
Romeo:
Open your mind. Thou art the sum of thyself and the sum of my good aunt and
the difference between nothing and the quotient of the square of twice the sum
of thy foul fat-kidneyed goat and thy death and thy evil variable!
Scene III: In which Romeo snaps and brutally insults Juliet.
Juliet:
Speak thy mind.
Romeo:
Thou art the sum of thyself and a hog! Art thou as rotten as nothing? If so,
let us return to scene II. Let us return to scene III.
Scene IV: Finale.
[Exeunt]
```
I'm using [drsam94's Python SPL compiler](https://github.com/drsam94/Spl), which has a few bugs (which is why, for instance, I use `Open your mind` instead of `Open thy mind` in the golfed version).
To run this program, use:
```
$ python splc.py rld.spl > rld.c
$ gcc rld.c -o rld.exe
$ echo -n ":144,1'1" | ./rld
:4444,'
```
## How it works
SPL is an esoteric programming language designed to make programs look like Shakespeare plays. It does this by using characters as variables, and processing is performed by having the characters say things to one another.
```
The Decoding of the Lengths of Veronan Runs - A Drama of PPCG.
```
This is the title of the play; it's ignored by the compiler.
```
Romeo, quite a character.
Juliet, Romeo's lover and multiplicand.
```
Here we're declaring the variables used in the rest of the program. Everything betwen `,` and `.` is ignored by the compiler. In this case, we declare `Romeo`, used to hold the character being decoded, and `Juliet`, used to hold the run length of the character.
```
Act I: In which the lengths of runs are decoded.
```
Here we declare the first and only act in the program. Acts and scenes are like labels; they can be jumped to at any time by using `let us return to scene II` or some variant of that. We only use one act, because it's sufficient for our needs. Again, anything between `:` and `.` is ignored by the compiler.
```
Scene I: A silent entrance.
```
Here we declare the first scene. Scenes are numbered in Roman numerals: the first is `Scene I`, the second `Scene II`, and so on.
```
[Enter Romeo and Juliet]
```
This is a stage direction; in it, we tell the `Romeo` and `Juliet` variables to come onto the "stage". Only two variables can be on the "stage" at once; the stage is used so that the compiler can figure out which variable is addressing which when they speak. Because we have only two variables, Romeo and Juliet will stay onstage for the length of the program.
```
Scene II: In which neither Romeo nor Juliet believes the other open-minded.
```
Another scene declaration. Scene II will be jumped to in order to decode another run-length.
```
Juliet:
```
This form of declaration means that Juliet is going to start speaking. Everything until the next `Romeo:`, stage direction, or scene/act declaration will be a line spoken by Juliet, and thus "me" will refer to Juliet, "you"/"thou" to Romeo, etc.
```
Open your mind.
```
This command stores the ordinal value of single character from STDIN in `Romeo`.
```
Is my mother jollier than thou?
```
In SPL, nouns translate to either 1 or -1 depending on whether they are positive or negative. In this case, `my mother` translates to 1. Adjectives (positive or negative) multiply their noun by 2.
This is a question; in it, Juliet asks if `my mother` (AKA 1) is "jollier" than Romeo. Comparatives either translate to `less than` (if they are negative, like `worse`) or `greater than` (if they are positive, like `jollier`). Therefore, this question boils down to `Is 1 greater than you?`.
The reason we ask this question is to detect the end of the input. Since the value of `EOF` varies by platform, but is usually less than 1, we use this to detect it.
```
If so, we must proceed to scene IV.
```
If the preceding question evaluated to `true`, we jump to scene IV—which is simply the end of the program. In short, if we detect an EOF, we end the program.
```
Romeo:
```
It's now Romeo's line: "me" and "you" refer to Romeo and Juliet, respectively.
```
Open your mind.
```
Again, this statement puts the ordinal value of a single character from STDIN into Juliet, which in this case is the run-length of the character stored in `Romeo`.
```
Thou art the sum of thyself and the sum of my good aunt and the difference
between nothing and the quotient of the square of twice the sum of thy foul
fat-kidneyed goat and thy death and thy evil variable!
```
This one's too long to go over in great detail, but just trust me in that it translates to `Juliet -= 48`. We do this because Juliet holds the ASCII value of a numeral, and `ord('0') == 48`; in subtracting 48, we translate from the ASCII value of a number to the number itself.
```
Scene III: In which Romeo snaps and brutally insults Juliet.
```
Another scene declaration. This one is for the loop in which we repeatedly print the character value of `Romeo`, `Juliet` times.
```
Juliet:
Speak thy mind.
```
This statement causes Romeo to print his value as a character; that is, whatever character value was previously stored in Romeo is now output.
```
Romeo:
Thou art the sum of thyself and a hog!
```
A hog is a negative noun, so `a hog` translates to -1; therefore, this statement evaluates to `Juliet -= 1`.
```
Art thou as rotten as nothing?
```
Romeo here asks if Juliet is "as rotten as", or equal to, 0.
```
If so, let us return to scene II.
```
If Juliet's value is 0, we loop back to scene II to decode another character's run-length.
```
Let us return to scene III.
```
Else, we loop back to scene III to output Romeo's character again.
```
Scene IV: Finale.
[Exeunt]
```
This final scene declaration is just a marker for the end of the program. The `[Exeunt]` stage direction is necessary to get the compiler to actually generate the final scene.
[Answer]
### GolfScript, 10 characters
```
2/{1/~~*}/
```
[Answer]
# perl, 27 characters
```
print<>=~s/(.)(.)/$1x$2/ger
```
[Answer]
## Python 3, 52
Python 3 allows me to merge the approaches of my two python2 solutions.
```
s=input()
t=''
while s:a,b,*s=s;t+=a*int(b)
print(t)
```
[Answer]
## R 67
```
x=strsplit(readline(),"")[[1]];cat(rep(x[c(T,F)],x[c(F,T)]),sep="")
```
[Answer]
# Malbolge Unshackled (20-trit rotation variant), 4,494e6 bytes
Size of this answer exceeds maximum postable program size (eh), so the code is [located in my GitHub repository](https://github.com/KrzysztofSzewczyk/codegolf-submissions/raw/master/12902.mb).
## How to run this?
This might be a tricky part, because naive Haskell interpreter will take ages upon ages to run this. TIO has decent Malbogle Unshackled interpreter, but sadly I won't be able to use it (limitations).
The best one I could find is the fixed 20-trit rotation width variant, that performs very well, **decompressing 360 bytes per hour**.
To make the interpreter a bit faster, I've removed all the checks from Matthias Lutter's Malbolge Unshackled interpreter.
My modified version can run around 6,3% faster.
```
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh"
"OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";
typedef struct Word {
unsigned int area;
unsigned int high;
unsigned int low;
} Word;
void word2string(Word w, char* s, int min_length) {
if (!s) return;
if (min_length < 1) min_length = 1;
if (min_length > 20) min_length = 20;
s[0] = (w.area%3) + '0';
s[1] = 't';
char tmp[20];
int i;
for (i=0;i<10;i++) {
tmp[19-i] = (w.low % 3) + '0';
w.low /= 3;
}
for (i=0;i<10;i++) {
tmp[9-i] = (w.high % 3) + '0';
w.high /= 3;
}
i = 0;
while (tmp[i] == s[0] && i < 20 - min_length) i++;
int j = 2;
while (i < 20) {
s[j] = tmp[i];
i++;
j++;
}
s[j] = 0;
}
unsigned int crazy_low(unsigned int a, unsigned int d){
unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
int position = 0;
unsigned int output = 0;
while (position < 10){
unsigned int i = a%3;
unsigned int j = d%3;
unsigned int out = crz[i+3*j];
unsigned int multiple = 1;
int k;
for (k=0;k<position;k++)
multiple *= 3;
output += multiple*out;
a /= 3;
d /= 3;
position++;
}
return output;
}
Word zero() {
Word result = {0, 0, 0};
return result;
}
Word increment(Word d) {
d.low++;
if (d.low >= 59049) {
d.low = 0;
d.high++;
if (d.high >= 59049) {
fprintf(stderr,"error: overflow\n");
exit(1);
}
}
return d;
}
Word decrement(Word d) {
if (d.low == 0) {
d.low = 59048;
d.high--;
}else{
d.low--;
}
return d;
}
Word crazy(Word a, Word d){
Word output;
unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
output.area = crz[a.area+3*d.area];
output.high = crazy_low(a.high, d.high);
output.low = crazy_low(a.low, d.low);
return output;
}
Word rotate_r(Word d){
unsigned int carry_h = d.high%3;
unsigned int carry_l = d.low%3;
d.high = 19683 * carry_l + d.high / 3;
d.low = 19683 * carry_h + d.low / 3;
return d;
}
// last_initialized: if set, use to fill newly generated memory with preinitial values...
Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) {
if ((mem[d.area])[d.high]) {
return &(((mem[d.area])[d.high])[d.low]);
}
(mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word));
if (!(mem[d.area])[d.high]) {
fprintf(stderr,"error: out of memory.\n");
exit(1);
}
if (last_initialized) {
Word repitition[6];
repitition[(last_initialized-1) % 6] =
((mem[0])[(last_initialized-1) / 59049])
[(last_initialized-1) % 59049];
repitition[(last_initialized) % 6] =
((mem[0])[last_initialized / 59049])
[last_initialized % 59049];
unsigned int i;
for (i=0;i<6;i++) {
repitition[(last_initialized+1+i) % 6] =
crazy(repitition[(last_initialized+i) % 6],
repitition[(last_initialized-1+i) % 6]);
}
unsigned int offset = (59049*d.high) % 6;
i = 0;
while (1){
((mem[d.area])[d.high])[i] = repitition[(i+offset)%6];
if (i == 59048) {
break;
}
i++;
}
}
return &(((mem[d.area])[d.high])[d.low]);
}
unsigned int get_instruction(Word** mem[], Word c,
unsigned int last_initialized,
int ignore_invalid) {
Word* instr = ptr_to(mem, c, last_initialized);
unsigned int instruction = instr->low;
instruction = (instruction+c.low + 59049 * c.high
+ (c.area==1?52:(c.area==2?10:0)))%94;
return instruction;
}
int main(int argc, char* argv[]) {
Word** memory[3];
int i,j;
for (i=0; i<3; i++) {
memory[i] = (Word**)malloc(59049 * sizeof(Word*));
if (!memory) {
fprintf(stderr,"not enough memory.\n");
return 1;
}
for (j=0; j<59049; j++) {
(memory[i])[j] = 0;
}
}
Word a, c, d;
unsigned int result;
FILE* file;
if (argc < 2) {
// read program code from STDIN
file = stdin;
}else{
file = fopen(argv[1],"rb");
}
if (file == NULL) {
fprintf(stderr, "File not found: %s\n",argv[1]);
return 1;
}
a = zero();
c = zero();
d = zero();
result = 0;
while (!feof(file)){
unsigned int instr;
Word* cell = ptr_to(memory, d, 0);
(*cell) = zero();
result = fread(&cell->low,1,1,file);
if (result > 1)
return 1;
if (result == 0 || cell->low == 0x1a || cell->low == 0x04)
break;
instr = (cell->low + d.low + 59049*d.high)%94;
if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r'
|| cell->low == '\n');
else if (cell->low >= 33 && cell->low < 127 &&
(instr == 4 || instr == 5 || instr == 23 || instr == 39
|| instr == 40 || instr == 62 || instr == 68
|| instr == 81)) {
d = increment(d);
}
}
if (file != stdin) {
fclose(file);
}
unsigned int last_initialized = 0;
while (1){
*ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0),
*ptr_to(memory, decrement(decrement(d)), 0));
last_initialized = d.low + 59049*d.high;
if (d.low == 59048) {
break;
}
d = increment(d);
}
d = zero();
unsigned int step = 0;
while (1) {
unsigned int instruction = get_instruction(memory, c,
last_initialized, 0);
step++;
switch (instruction){
case 4:
c = *ptr_to(memory,d,last_initialized);
break;
case 5:
if (!a.area) {
printf("%c",(char)(a.low + 59049*a.high));
}else if (a.area == 2 && a.low == 59047
&& a.high == 59048) {
printf("\n");
}
break;
case 23:
a = zero();
a.low = getchar();
if (a.low == EOF) {
a.low = 59048;
a.high = 59048;
a.area = 2;
}else if (a.low == '\n'){
a.low = 59047;
a.high = 59048;
a.area = 2;
}
break;
case 39:
a = (*ptr_to(memory,d,last_initialized)
= rotate_r(*ptr_to(memory,d,last_initialized)));
break;
case 40:
d = *ptr_to(memory,d,last_initialized);
break;
case 62:
a = (*ptr_to(memory,d,last_initialized)
= crazy(a, *ptr_to(memory,d,last_initialized)));
break;
case 81:
return 0;
case 68:
default:
break;
}
Word* mem_c = ptr_to(memory, c, last_initialized);
mem_c->low = translation[mem_c->low - 33];
c = increment(c);
d = increment(d);
}
return 0;
}
```
## It's working!
[](https://i.stack.imgur.com/5KgEv.png)
[Answer]
## APL (22)
```
,/{⍺/⍨⍎⍵}/↑T⊂⍨~⎕D∊⍨T←⍞
```
Explanation:
* `T←⍞`: store input in `T`
* `T⊂⍨~⎕D∊⍨T`: split `T` on those characters that aren't digits
* `↑`: turn it into a `2`-by-`N/2` matrix
* `{⍺/⍨⍎⍵}/`: on each row of the matrix (`/`), replicate (`/`) the first character (`⍺`) by the eval (`⍎`) of the second character (`⍵`)
* `,/`: concatenate the output of each row
[Answer]
# Ruby, 30 bytes
```
gsub!(/(.)(.)/){$1*$2.to_i}
```
27 bytes code + 3 bytes to run it with the `-p` flag:
```
$ ruby -p rld.rb <<< ":144,1'1"
:4444,'
```
[Answer]
**8086 assembly, 106 98 characters**
```
l:
mov ah,8
int 21h
mov bl,al
int 21h
sub al,48
mov cl,al
xor ch,ch
mov al,bl
mov ah,14
p:
int 10h
loop p
jmp l
```
If the numbers were before the characters in the input stream, two lines (18 characters) could be shaved off of this.
[Answer]
## GNU SED, 122 + 2 (-r)
```
#n
s/.*/\n&\a987654321\v\v\v\v\v\v\v\v\v/
:a
s/\n(.)(.)(.*\a.*\2.{9}(.*))/\1\n\4\3/
tb
bc
:b
s/(.)\n\v/\1\1\n/
tb
ba
:c
P
```
Needs to be run with the `-r` flag
May be reduced to 110 + 2 by replacing `\v` with the unprintable `0x0B` and `\a` with `0x07`
[Answer]
## C, 65 chars
Gets the input as a parameter.
```
main(p,v)char*p,**v;{
for(p=v[1];*p;--p[1]<49?p+=2:0)putchar(*p);
}
```
[Answer]
## Perl, ~~19~~ 18 characters
```
perl -pe 's/(.)(.)/$1x$2/ge'
```
The rules for counting switches on the command-line are [here](http://meta.codegolf.stackexchange.com/a/274/199).
[Answer]
# Forth, 45 characters
```
BEGIN KEY KEY 48 - 0 DO DUP EMIT LOOP 0 UNTIL
```
Tested with pforth on OS X.
[Answer]
# Python, ~~63~~ 62 characters
```
print''.join([c*int(n)for c,n in zip(*[iter(raw_input())]*2)])
```
[Answer]
## Windows PowerShell, 55 chars
```
-join((read-host)-split'(..)'|%{(""+$_[0])*(""+$_[1])})
```
I get the feeling that this can be golfed down more, specifically with the casts from char to string and int, but I don't have the time to keep working on it right now.
[Answer]
# C, 68 characters
@ugoren's answer in C is slightly shorter, but this answer complies with the requirement that "the string will be supplied as input on **stdin**."
```
n;main(c){for(;;){c=getchar(),n=getchar()-48;while(n--)putchar(c);}}
```
[Answer]
# Haskell, ~~58~~ 56 characters
```
f[]=[]
f(x:y:s)=replicate(read[y])x++f s
main=interact$f
```
My first real attempt at golfing anything, so there's probably some improvement to be made here.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 8 bytes
Input as an array of characters, output as a string.
```
ò crÈpY°
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=8iBjcshwWbA&input=WyI6IiwiMSIsIjQiLCI0IiwiLCIsIjEiLCInIiwiMSJd)
```
ò crÈpYn :Implicit input of character array
ò :Groups of 2
r :Reduce each pair
È :By passing them through the following function as [X,Y]
p : Repeat X
Yn : Y, converted to an integer, times
:Implicitly join and output
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2ι`ÅΓ
```
-1 byte thanks to *@Grimy*.
Outputs as a list of characters.
[Try it online.](https://tio.run/##yy9OTMpM/f/f6NzOhMOt5yb//29laGKiY6huDAA)
**Old 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer without run-length decode builtin:**
```
2ôε`×?
```
[Try it online.](https://tio.run/##yy9OTMpM/f/f6PCWc1sTDk@3///fytDERMdQ3fi/rm5evm5OYlUlAA)
**Explanation:**
```
2ι # Uninterleave the (implicit) input-string in two parts
# i.e. ":144,1'3" → [":4,'","1413"]
` # Push both separated to the stack
ÅΓ # Run-length decode
# i.e. ":4,'" and "1413" → [":","4","4","4","4",",","'","'","'"]
# (after which the result is output implicitly)
2ô # Split the (implicit) input-string into parts of size 2
# i.e. ":144,1'3" → [":1","44",",1","'3"]
ε # Loop over each of these pairs:
` # Push both characters separated to the stack
× # Repeat the first character the digit amount of times as string
# i.e. "'" and "3" → "'''"
? # And print it without trailing newline
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `J`, 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
d^N×
```
[Try it online!](https://Not-Thonnu.github.io/run#P2hlYWRlcj0mY29kZT1kJTVFTiVDMyU5NyZmb290ZXI9JmlucHV0PSUzQTE0NCUyQzEnMSZmbGFncz1K)
#### Explanation
```
d^N× # Implicit input -> ":144,1'1"
d # Cast to characters -> [":","1","4","4",",","1","'","1"]
^ # Uninterleave -> [":","4",",","'"] ["1","4","1","1"]
N # Cast to integer -> [":","4",",","'"] [1,4,1,1]
× # Multiply together -> [":","4444",",","'"]
# Implicit output -> :4444,'
```
[Answer]
**Python, 78 72 66 char**
```
d=raw_input()
print"".join([x*int(d[i+1])for i,x in enumerate(d)if~i&1])
```
```
s=raw_input()
print"".join(i*int(j)for i,j in zip(s[::2],s[1::2]))
```
[Answer]
### GolfScript (10 chars)
```
2/{)15&*}/
```
[Answer]
# J - 24
```
;@(_2(<@#~".)/\])@1!:1 3
```
The point of this submission is to use the infix adverb.
[Answer]
## Befunge, 49 chars
```
>~:25*- v
$>\1-:v:-*68~_@
$^ ,:\_v
^ <
```
[Answer]
# K, 35
```
{,/(#).'|:'"*I"$/:(2*!-_-(#x)%2)_x}
```
[Answer]
## Python 2, 58
This is inspired by Darren Stone's python solution -- iterator abuse!
```
x=iter(raw_input())
print''.join(a*int(next(x))for a in x)
```
This is my original solution (60 chars)
```
s=raw_input()
t=''
while s:t+=s[0]*int(s[1]);s=s[2:]
print t
```
A different approach is 3 chars longer:
```
f=lambda a,b,*x:a*int(b)+(x and f(*x)or'')
print f(raw_input())
```
[Answer]
Java: 285 charas
```
import java.util.Scanner;public class A{public static void main(String args[]){Scanner s = new Scanner(System.in);while(s.hasNext()){String t=s.next();for(int i=0;i<t.length();i++) {for(int j=0; j<(Byte.valueOf(t.substring(i+1,i+2)));j++){System.out.print(t.substring(i,i+1));}i++;}}}}
```
[Answer]
## Befunge-98, 22 chars
```
>#@~~"0"-v
^#:\,:\-1<_
```
[Answer]
## Whitespace, 135
```
LSSSLSSSSLSLSTLTSTTTSLSSSSTSSSSLTSSTLTTTTLSSSSLSLSTLTSTTTSSSTTSSSSLTSSTLSSSSLSLSLTSTLSSSTLTSSTSTSSTLTLSSLSLSSLLSSTLSLLSLLLSLSLLSSTTLLLL
```
(Replace S,T,L with Space,Tab,Linefeed characters.)
Try it online [[here]](http://ideone.com/NV9xnx).
Explanation:
```
"assembly" whitespace stack
---------- ---------- -----
s: LSS SL ;input loop []
push 0 SS SSL [0]
dup SLS [0,0]
getc TLTS ;input & store char c [0]
rcl TTT ;recall c [c]
dup SLS [c,c]
push 16 SS STSSSSL [c,c,16]
sub TSST [c,c-16]
jlt tt LTT TTL ;exit if ord(c) < 16 [c]
push 0 SS SSL [c,0]
dup SLS [c,0,0]
getc TLTS ;input & store char n [c,0]
rcl TTT ;recall n [c,n]
push 48 SS STTSSSSL ;convert n to m = ord(n)-ord('0') [c,n,48]
sub TSST [c,m]
ss: LSS SSL ;inner loop outputs c, m times [c,m]
dup SLS [c,m,m]
jeq t LTS TL ;if m==0, stop outputting this c [c,m]
push 1 SS STL ;otherwise decr m [c,m,1]
sub TSST [c,m-1]
copy 1 STS STL ;copy c to tos [c,m-1,c]
putc TLSS ;output this c [c,m-1]
jmp ss LSL SSL ;loop back to output this c again [c,m-1]
t: LSS TL [c,m]
pop SLL [c]
pop SLL []
jmp s LSL SL ;loop back to get the next c,n []
tt: LSS TTL [c]
end LLL ;exit
```
] |
[Question]
[
## Challenge
Given a list of numbers, calculate the population standard deviation of the list.
Use the following equation to calculate population standard deviation:

## Input
The input will a list of integers in any format (list, string, etc.). Some examples:
```
56,54,89,87
67,54,86,67
```
The numbers will always be integers.
Input will be to STDIN or function arguments.
## Output
The output must be a floating point number.
## Rules
You may use built in functions to find the standard deviation.
Your answer can be either a full program or a function.
## Examples
```
10035, 436844, 42463, 44774 => 175656.78441352615
45,67,32,98,11,3 => 32.530327730015607
1,1,1,1,1,1 => 0.0
```
## Winning
The shortest program or function wins.
## Leaderboard
```
var QUESTION_ID=60901,OVERRIDE_USER=30525;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]
# [Clip](https://esolangs.org/wiki/Clip), 3
```
.sk
```
`.s` is the standard deviation, `k` parses the input in the form `{1,2,3}`.
[Answer]
# Mathematica, ~~24~~ 22 bytes
Nice, Mathematica has a built-in `StandardDevi...` oh... that computes the sample standard deviation, not the population standard deviation.
But what if we use `Variance`... oh... same deal.
But there is yet another related built-in:
```
CentralMoment[#,2]^.5&
```
Yay. :)
This also works for 22 bytes:
```
Mean[(#-Mean@#)^2]^.5&
```
And this for 27:
```
N@RootMeanSquare[#-Mean@#]&
```
[Answer]
# Octave, 14 bytes
```
g=@(a)std(a,1)
```
Try it on [ideone](http://ideone.com/noczhf).
[Answer]
# [kdb+](http://kx.com/software-download.php), 3 bytes
```
dev
```
One of the APL derviates *had to* have this as a built-in.
### Test run
```
q)dev 56, 54, 89, 87
16.53028
q)f:dev
q)f 10035, 436844, 42463, 44774
175656.8
q)f 45,67,32,98,11,3
32.53033
```
[Answer]
# Dyalog APL, ~~24~~ ~~23~~ ~~21~~ ~~20~~ ~~19~~ 17 bytes
```
*∘.5∘M×⍨-M×M←+/÷≢
```
This defines an unnamed, monadic function train, which is equivalent to the following function.
```
{.5*⍨M(×⍨⍵)-M⍵×(M←{(+/⍵)÷≢⍵})⍵}
```
Try them online on [TryAPL](http://tryapl.org/?a=%28%20%28*%u2218.5%u2218M%D7%u2368-M%D7M%u2190+/%F7%u2262%29%20%2C%20%7B.5*%u2368M%28%D7%u2368%u2375%29-M%u2375%D7%28M%u2190%7B%28+/%u2375%29%F7%u2262%u2375%7D%29%u2375%7D%20%29%2056%2054%2089%2087&run).
### How it works
The code consists of several trains.
```
M←+/÷≢
```
This defines a monadic 3-train (fork) `M` that executes `+/` (sum of all elements) and `≢` (length) for the right argument, then applies `÷` (division) to the results, returning the arithmetic mean of the input.
```
M×M
```
This is another fork that applies `M` to the right argument, repeats this a second time, and applies `×` (product) to the results, returning **μ2**.
```
×⍨-(M×M)
```
This is yet another fork that calculates the square of the arithmetic mean as explained before, applies `×⍨` (product with itself) to the right argument, and finally applies `-` (difference) to the results.
For input **(x1, …, xN)**, this function returns **(x1 - μ2, …, xN - μ2)**.
```
*∘.5∘M
```
This composed function is applies `M` to its right argument, then `*∘.5`. The latter uses right argument currying to apply map input `a` to `a*0.5` (square root of `a`).
```
(*∘.5∘M)(×⍨-(M×M))
```
Finally, we have this monadic 2-train (atop), which applies the right function first, then the left to its result, calculating the standard deviation as follows.
[](https://i.stack.imgur.com/GH3oK.png)
[Answer]
# R, ~~41~~ ~~40~~ ~~39~~ ~~36~~ ~~30~~ 28 bytes
### code
Thanks to [beaker](https://codegolf.stackexchange.com/users/42892/beaker), [Alex A.](https://codegolf.stackexchange.com/users/20469/alex-a) and [MickyT](https://codegolf.stackexchange.com/users/31347/mickyt) for much bytes.
```
cat(sd(c(v=scan(),mean(v))))
```
### old codes
```
v=scan();n=length(v);sd(v)/(n/(n-1))**0.5
m=scan();cat(sqrt(sum(mean((m-mean(m))^2))))
m=scan();cat(mean((m-mean(m))^2)^.5)
```
This should yield the population standard deviation.
[Answer]
# Julia, ~~26~~ 19 bytes
```
x->std([x;mean(x)])
```
This creates an unnamed function that accepts an array and returns a float.
Ungolfed, I guess:
```
function f(x::Array{Int,1})
# Return the sample standard deviation (denominator N-1) of
# the input with the mean of the input appended to the end.
# This corrects the denominator to N without affecting the
# mean.
std([x; mean(x)])
end
```
[Answer]
# Pyth, ~~20~~ ~~19~~ ~~17~~ 13 bytes
```
@.O^R2-R.OQQ2
```
*Thanks to @FryAmTheEggman for golfing off 4 bytes!*
[Try it online.](https://pyth.herokuapp.com/?code=%40.O%5ER2-R.OQQ2&input=56%2C54%2C89%2C87)
### How it works
```
.OQ Compute the arithmetic mean of the input (Q).
-R Q Subtract the arithmetic mean of all elements of Q.
^R2 Square each resulting difference.
.O Compute the arithmetic mean of the squared differences.
@ 2 Apply square root.
```
[Answer]
# CJam, ~~24~~ ~~22~~ 21 bytes
```
q~_,_@_:+d@/f-:mh\mq/
```
*Thanks to @aditsu for golfing off 1 byte!*
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~_%2C_%40_%3A%2Bd%40%2Ff-%3Amh%5Cmq%2F&input=%5B56%2054%2089%2087%5D).
### How it works
```
q~ e# Read all input and evaluate it.
_, e# Copy the array and push its length.
_@ e# Copy the length and rotate the array on top.
_:+d e# Copy the array and compute its sum. Cast to Double.
@/ e# Rotate the length on top and divide the sum by it.
f- e# Subtract the result (μ) from the array's elements.
:mh e# Reduce by hypotenuse.
e# a b mh -> sqrt(a^2 + b^2)
e# sqrt(a^2 + b^2) c mh -> sqrt(sqrt(a^2 + b^2)^2 + c^2)
e# = sqrt(a^2 + b^2 + c^2)
e# ⋮
\mq/ e# Divide the result by the square root of the length.
```
[Answer]
# APL, 24 bytes
```
{.5*⍨+/(2*⍨⍵-+/⍵÷≢⍵)÷≢⍵}
```
A little different approach than [Dennis' Dyalog APL solution](https://codegolf.stackexchange.com/a/60913/20469). This should work with any APL implementation.
This creates an unnamed monadic function that computes the vector (*x* - *µ*)2 as `2*⍨⍵-+/⍵÷≢⍵`, divides this by *N* (`÷≢⍵`), takes the sum of this vector using `+/`, and then takes the square root (`.5*⍨`).
[Try it online](http://tryapl.org/?a=%7B.5*%u2368+/%282*%u2368%u2375-+/%u2375%F7%u2262%u2375%29%F7%u2262%u2375%7D%2045%2067%2032%2098%2011%203&run)
[Answer]
# TI-BASIC, 7 bytes
```
stdDev(augment(Ans,{mean(Ans
```
I borrowed the algorithm to get population standard deviation from sample standard deviation from [here](http://tibasicdev.wikidot.com/stddev).
The shortest solution I could find without `augment(` is 9 bytes:
```
stdDev(Ans√(1-1/dim(Ans
```
[Answer]
# Haskell, 61 bytes
```
d n=1/sum(n>>[1])
f a=sqrt$d a*sum(map((^2).(-)(d a*sum a))a)
```
Straightforward, except maybe my custom length function `sum(n>>[1])` to trick Haskell's strict type system.
[Answer]
# Python 3.4+, 30 bytes
```
from statistics import*;pstdev
```
Imports the builtin function `pstdev`, e.g.
```
>>> pstdev([56,54,89,87])
16.53027525481654
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly)
**11 bytes**
```
S÷L
Dz_²ÇN½
```
This is a direct translation of [my APL answer](https://codegolf.stackexchange.com/a/60913) to Jelly. [Try it online!](http://jelly.tryitonline.net/#code=U8O3TArDh8KyX8Kyw4dOwr0&input=&args=NDUsNjcsMzIsOTgsMTEsMw)
### How it works
```
S÷L Helper link. Argument: z (vector)
S Compute the sum of z.
L Compute the length of z.
÷ Divide the former by the latter.
This computes the mean of z.
Dz_²ÇN½ Main link. Argument: z (vector)
Ç Apply the previous link, i.e., compute the mean of z.
² Square the mean.
² Square all number in z.
_ Subtract each squared number from the squared mean.
Ç Take the mean of the resulting vector.
N Multiply it by -1.
½ Take the square root of the result.
```
[Answer]
# Prolog (SWI), 119 bytes
**Code:**
```
q(U,X,A):-A is(X-U)^2.
p(L):-sumlist(L,S),length(L,I),U is S/I,maplist(q(U),L,A),sumlist(A,B),C is sqrt(B/I),write(C).
```
**Explanation:**
```
q(U,X,A):-A is(X-U)^2. % calc squared difference of X and U
p(L):-sumlist(L,S), % sum input list
length(L,I), % length of input list
U is S/I, % set U to the mean value of input list
maplist(q(U),L,A), % set A to the list of squared differences of input and mean
sumlist(A,B), % sum squared differences list
C is sqrt(B/I), % divide sum of squares by length of list
write(C). % print answer
```
**Example:**
```
p([10035, 436844, 42463, 44774]).
175656.78441352615
```
Try it out online [here](http://swish.swi-prolog.org/p/dzwqjuYT.pl)
[Answer]
# J, 18 bytes
```
[:%:@M*:-M*M=:+/%#
```
This is a direct translation of [my APL answer](https://codegolf.stackexchange.com/a/60913) to J.
[Try it online!](https://tio.run/nexus/j#@5@mYGulEG2lauXgq2Wl66vla2ulra@q/D81OSNfIU3BxFTBzFzB2EjB0kLB0FDB@D8A "J – TIO Nexus")
[Answer]
# [Haskell](https://www.haskell.org/), 45 bytes
```
(?)i=sum.map(^i)
f l=sqrt$2?l/0?l-(1?l/0?l)^2
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/X8NeM9O2uDRXLzexQCMuU5MrTSHHtriwqETFyD5H38A@R1fDEMLQjDP6n5uYmadgq1BQlJlXoqCikKYQbWKqY2auY2ykY2mhY2ioYxz7/19yWk5ievF/3eSCAgA "Haskell – Try It Online")
The value `i?l` is the sum of the i'th powers of elements in `l`, so that `0?l` is the length and `1?l` is the sum.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÅA-nÅAt
```
-3 bytes thanks to *@ovs*.
[Try it online](https://tio.run/##yy9OTMpM/f//cKujbh6QKPn/P9rCWMfQ0EzH0hxMGRqaxgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8Otjrp5QKLkv87/6GhDAwNjUx0TYzMLExMdEyMTM2MdExNzc5NYnWgTUx0zcx1jIx1LCx1DQx1joJChDhzGxgIA).
**Explanation:**
```
ÅA # Get the arithmetic mean of the (implicit) input-list
- # Subtract it from each value in the (implicit) input-list
n # Square each of those
ÅA # Take the arithmetic mean of that
t # And take the square-root of that
# (after which it is output implicitly as result)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes
```
⟨∋-⟨+/l⟩⟩ᶠ^₂ᵐ↰₂√
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8FY86unWBlLZ@zqP5K4Ho4bYFcY@amh5unfCobQOQ8ahj1v//0YYGBsamOgomxmYWJiZA2sjEzBhImZibm8T@jwIA "Brachylog – Try It Online") [(all cases at once)](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/9H8FY86unWBlLZ@zqP5K4Ho4bYFcSAVWyeAlbY86pj1/390tKGBgbGpjoKJsZmFiQmQNjIxMwZSJubmJrE6CtEmpjpm5jrGRjqWFjqGhjrGIDFDHTgEcU3NdExNdCwsdSzMQVygchDXDKgvNhYA "Brachylog – Try It Online")
I feel like *maybe* there's some shorter way to compute the squared deviations than 13 bytes.
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), [~~19~~ ~~18~~ 14 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
¯‡iʠØbmÅQƥªÈªÆ
```
[Try it!](https://zippymagician.github.io/Arn?code=Oi9tZWFuKG57OipuLW1lYW46c31c&input=MTAwMzUgNDM2ODQ0IDQyNDYzIDQ0Nzc0CjQ1IDY3IDMyIDk4IDExIDMKMSAxIDEgMSAxIDE=)
# Explained
Unpacked: `:/mean(n{:*n-mean:s}\`
```
:/ Square root
mean Mean function
( Begin expression
n{ Block with key of n
:* Square
n
- Subtraction
mean
_ Variable initialized to STDIN; implied
:s Split on spaces
} End of block
\ Mapped over
_ Implied
) End of expression; Implied
```
[Answer]
# [Simplex v.0.5](http://conorobrien-foxx.github.io/Simplex/), 43 bytes
Just 'cuz. I really need to golf this one more byte.
```
t[@u@RvR]lR1RD@wA@T@{j@@SR2ERpR}u@vR@TR1UEo
t[ ] ~~ Applies inner function to entire strip (left-to-right)
@ ~~ Copies current value to register
u ~~ Goes up a strip level
@ ~~ Dumps the register on the current byte
R ~~ Proceeds right (s1)
v ~~ Goes back down
R ~~ Proceeds right (s0)
~~ Go right until an empty byte is found
lR1RD ~~ Push length, 1, and divide.
@ ~~ Store result in register (1/N)
wA ~~ Applies A (add) to each byte, (right-to-left)
@T@ ~~ Puts 1/N down, multiplies it, and copies it to the register
{ } ~~ Repeats until a zero-byte is met
j@@ ~~ inserts a new byte and places register on it
SR ~~ Subtract it from the current byte and moves right
2E ~~ Squares result
RpR ~~ Moves to the recently-created cell, deletes it, and continues
u@v ~~ takes 1/N again into register
R@T ~~ multiplies it by the new sum
R1UE ~~ takes the square root of previous
o ~~ output as number
```
[Answer]
# JavaScript (ES6), 73 bytes
```
a=>Math.sqrt(a.reduce((b,c)=>b+(d=c-eval(a.join`+`)/(l=a.length))*d,0)/l)
```
[Answer]
# Perl5, ~~39~~ 38
---
16 for the script
+22 for the `M` switch
+ 1 for the `E` switch
```
perl -MStatistics::Lite=:all -E"say stddevp@ARGV" .1 .2 300
```
Tested in Strawberry 5.20.2.
---
Oh, but then I realized that you said our answers can be functions instead of programs. In that case,
```
{use Statistics::Lite":all";stddevp@_}
```
has just 38. Tested in Strawberry 5.20.2 as
```
print sub{use Statistics::Lite":all";stddevp@_}->( .1, .2, 300)
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~10~~ 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
ë_▓-²▓√
```
Port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/210034/52210).
[Try it online.](https://tio.run/##y00syUjPz0n7///w6vhH0ybrHtoEJB91zPr/39DAwNhUwcTYzMLERMHEyMTMWMHExNzchMvEVMHMXMHYSMHSQsHQUMGYy1ABDgE)
**Explanation:**
```
ë # Read all inputs as float-list
_ # Duplicate that list
▓ # Get the average of that list
- # Subtract that average from each value in the list
² # Square each value
▓ # Take the average of that again
√ # And take the square root of that
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 105 bytes
```
> Input
>> #1
>> ∑1
>> 3÷2
>> L-4
>> L²
>> Each 5 1
>> Each 6 7
>> ∑8
>> 9÷2
>> √10
>> Output 11
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hMvOTkHZEEQ@6pgIpo0PbzcC0T66JmDq0CYQ5ZqYnKFgqmAIZ5spmEN1WYBoS6iuRx2zDA1ADP/SEqDxCoaG//9HGxoYGJvqKJgYm1mYmABpIxMzYyBlYm5uEgsA "Whispers v2 – Try It Online")
In the latest version of Whispers, the builtin [`σ`](https://github.com/cairdcoinheringaahing/Whispers/blob/master/whispers%20v3.py#L1474) can be used to shave off around 70 bytes.
## How it works
For those unfamiliar with Whispers, the language works by using numbers as line references in order to pass values between lines. For example, the line `>> 3÷2` doesn't calculate \$3 \div 2\$, rather it takes the values of lines **3** and **2** and calculates their division. Execution always begins on the last line.
This program simply implements the standard formula for standard deviation:
$$\sigma = \sqrt{\frac{1}{N}\sum^N\_{i=1}{(x\_i-\bar{x})^2}}$$
$$\bar{x} = \frac{1}{N}\sum^N\_{i=1}{x\_i}$$
Lines **2**, **3** and **4** define \$\bar{x}\$, with it's specific value accessible on line **4**. Line **2** stores \$N\$. We then calculate \$(x\_i-\bar{x})^2\$ for each \$x\_i \in x\$ with the lines **5**, **6**, **7** and **8**:
```
>> L-4
>> L²
>> Each 5 1
>> Each 6 7
```
Line **7** runs line **5** over each element in the input, which takes the difference between each element in the input and the mean, We then square these differences using lines **8** and **6**. Finally, we take the sum of these squares (line **9**), divide by \$N\$ (line **10**) and take the square root (line **11**). Finally, we output this result.
[Answer]
# [Shasta v0.0.10](https://github.com/jacobofbrooklyn/shasta/tree/d66d19a634eb70bd73feac1972327867a7f0ede4), 65 bytes
```
{(**(/(sum(map${|x|(**(- x(/(sum$)(length$)))2)}))(length$)).5)}
```
Online interpreter not set up yet, tested on my machine
Explanation:
`{...}` Function taking argument $
`(** ... .5)` Square root of
`(/ ... (length $))` Dividing ... by the length of $
`(sum ...)` The sum of
`(map $ {|x| ...})` Mapping each x in $ to
`(** ... 2)` The square of
`(- x ...)` The difference between x and
`(/ (sum $) (length $))` The mean of $
[Answer]
# Python, 57 bytes
```
lambda l:(sum((x-sum(l)/len(l))**2for x in l)/len(l))**.5
```
Takes input as a list
Thanks @xnor
[Answer]
### PowerShell, 122
```
:\>type stddev.ps1
$y=0;$z=$args -split",";$a=($z|?{$_});$c=$a.Count;$a|%{$y+=$_};$b=$y/$c;$a|%{$x+
=(($_-$b)*($_-$b))/$c};[math]::pow($x,0.5)
```
explanation
```
<#
$y=0 init
$z=$args -split"," split delim ,
$a=($z|? {$_}) remove empty items
$c=$a.Count count items
$a|%{$y+=$_} sum
$b=$y/$c average
$a|%{$x+=(($_-$b)*($_-$b))/$c} sum of squares/count
[math]::pow($x,0.5) result
#>
```
result
```
:\>powershell -nologo -f stddev.ps1 45,67,32,98,11,3
32.5303277300156
:\>powershell -nologo -f stddev.ps1 45, 67,32,98,11,3
32.5303277300156
:\>powershell -nologo -f stddev.ps1 45, 67,32, 98 ,11,3
32.5303277300156
:\>powershell -nologo -f stddev.ps1 10035, 436844, 42463, 44774
175656.784413526
:\>powershell -nologo -f stddev.ps1 1,1,1,1,1,1
0
```
[Answer]
# Fortran, 138 bytes
Just a straightforward implementation of the equation in Fortran:
```
double precision function std(x)
integer,dimension(:),intent(in) :: x
std = norm2(dble(x-sum(x)/size(x)))/sqrt(dble(size(x)))
end function
```
[Answer]
# SmileBASIC, 105 bytes (as a function)
I just noticed it's allowed to be a function. Whoops, that reduces my answer dramatically. This defines a function `S` which takes an array and returns the population standard deviation. Go read the other one for an explanation, but skip the parsing part. I don't want to do it again.
```
DEF S(L)N=LEN(L)FOR I=0TO N-1U=U+L[I]NEXT
U=1/N*U FOR I=0TO N-1T=T+POW(L[I]-U,2)NEXT RETURN SQR(1/N*T)END
```
## As a program, 212 bytes
Unfortunately, I have to take the input list as a string and parse it myself. This adds over 100 bytes to the answer, so if some input format other than a comma-separated list is allowed I'd be glad to hear it. Also note that because `VAL` is buggy, having a space *before* the comma or trailing the string breaks the program. After the comma or at the start of the string is fine.
```
DIM L[0]LINPUT L$@L I=INSTR(O,L$,",")IF I>-1THEN PUSH L,VAL(MID$(L$,O,I-O))O=I+1GOTO@L ELSE PUSH L,VAL(MID$(L$,O,LEN(L$)-O))
N=LEN(L)FOR I=0TO N-1U=U+L[I]NEXT
U=1/N*U FOR I=0TO N-1T=T+POW(L[I]-U,2)NEXT?SQR(1/N*T)
```
Ungolfed and explained:
```
DIM L[0] 'define our array
LINPUT L$ 'grab string from input
'parse list
'could've used something cleaner, like a REPEAT, but this was shorter
@L
I=INSTR(O,L$,",") 'find next comma
IF I>-1 THEN 'we have a comma
PUSH L,VAL(MID$(L$,O,I-O)) 'get substring of number, parse & store
O=I+1 'set next search location
GOTO @L 'go again
ELSE 'we don't have a comma
PUSH L,VAL(MID$(L$,O,LEN(L$)-O)) 'eat rest of string, parse & store
ENDIF 'end
N=LEN(L) 'how many numbers we have
'find U
'sum all of the numbers, mult by 1/N
FOR I=0 TO N-1
U=U+L[I]
NEXT
U=1/N*U
'calculate our popstdev
'sum(pow(x-u,2))
FOR I=0 TO N-1
T=T+POW(L[I]-U,2)
NEXT
PRINT SQR(1/N*T) 'sqrt(1/n*sum)
```
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/126326/edit).
Closed 6 years ago.
[Improve this question](/posts/126326/edit)
Write a function (not a full program), so that if the function is called with a single global variable (or your language's closest equivalent) as its argument, it outputs (i.e. prints or returns) the name of that variable. If the argument is not a variable, output a falsey value instead. (You don't have to handle the case where the argument is a variable, but not global.)
There must not be a compile-time connection between the function call and function definition (notably, the function definition cannot be a macro or similar construct that receives arguments in the form of a literal fragment of source code, neither in text nor abstract syntax tree form). That is: in languages which support separate compilation, the program must work even if the function call is compiled first (with no knowledge of the function definition but possibly a type signature or equivalent), then the function definition is compiled afterwards. If the language doesn't have separate compilation, you must nonetheless aim for a similar separation between the call and definition.
If using a compiled language, you may read the compiled form of the complete program from disk, and may assume that the program was compiled with debug information. (Thus, solutions that work by attaching a debugger from a program to itself are allowed.)
Note that this task may not be possible in every language.
## Examples:
```
var apple = "Hello"
p(apple) // apple
var nil = "Nothing"
p(nil) // nil
var SOMETHING = 69
p(SOMETHING) // SOMETHING
function foo(){}
p(foo) // foo
p(3.14159) // false
p(function foo(){}) // false
```
[Answer]
# Java
```
String getParamName(String param) throws Exception {
StackTraceElement[] strace = new Exception().getStackTrace();
String methodName = strace[0].getMethodName();
int lineNum = strace[1].getLineNumber();
String className = strace[1].getClassName().replaceAll(".{5}$", "");
String classPath = Class.forName(className).getProtectionDomain().getCodeSource().getLocation().getPath() + className + ".class";
StringWriter javapOut = new StringWriter();
com.sun.tools.javap.Main.run(new String[] {"-l", "-c", classPath}, new PrintWriter(javapOut));
List<String> javapLines = Arrays.asList(javapOut.toString().split("\\r?\\n"));
int byteCodeStart = -1;
Map<Integer, Integer> byteCodePointerToJavaPLine = new HashMap<Integer, Integer>();
Pattern byteCodeIndexPattern = Pattern.compile("^\\s*(\\d+): ");
for (int n = 0;n < javapLines.size();n++) {
String javapLine = javapLines.get(n);
if (byteCodeStart > -1 && (javapLine == null || "".equals(javapLine))) {
break;
}
Matcher byteCodeIndexMatcher = byteCodeIndexPattern.matcher(javapLine);
if (byteCodeIndexMatcher.find()) {
byteCodePointerToJavaPLine.put(Integer.parseInt(byteCodeIndexMatcher.group(1)), n);
} else if (javapLine.contains("line " + lineNum + ":")) {
byteCodeStart = Integer.parseInt(javapLine.substring(javapLine.indexOf(": ") + 2));
}
}
int varLoadIndex = -1;
int varTableIndex = -1;
for (int i = byteCodePointerToJavaPLine.get(byteCodeStart) + 1;i < javapLines.size();i++) {
if (varLoadIndex < 0 && javapLines.get(i).contains("Method " + methodName + ":")) {
varLoadIndex = i;
continue;
}
if (varLoadIndex > -1 && javapLines.get(i).contains("LocalVariableTable:")) {
varTableIndex = i;
break;
}
}
String loadLine = javapLines.get(varLoadIndex - 1).trim();
int varNumber;
try {
varNumber = Integer.parseInt(loadLine.substring(loadLine.indexOf("aload") + 6).trim());
} catch (NumberFormatException e) {
return null;
}
int j = varTableIndex + 2;
while(!"".equals(javapLines.get(j))) {
Matcher varName = Pattern.compile("\\s*" + varNumber + "\\s*([a-zA-Z_][a-zA-Z0-9_]*)").matcher(javapLines.get(j));
if (varName.find()) {
return varName.group(1);
}
j++;
}
return null;
}
```
This currently works with a few gotchas:
1. If you use an IDE to compile this it might not work unless it is run as Admin (depending on where the temporary class files are saved)
2. You must compile using `javac` with the `-g` flag. This generates all debugging information including local variable names in the compiled class file.
3. This uses an internal Java API `com.sun.tools.javap` which parses the bytecode of a classfile and produces a human readable result. This API is only accessible in the JDK libraries so you must either use the JDK java runtime or add tools.jar to your classpath.
This should now work even if the method is called multiple times in the program. Unfortunately it does not yet work if you have multiple invocations on a single line. (For one that does, see below)
[Try it online!](https://tio.run/##nVdrb9s2FP1s/wpOGAqqjhi76IYtTjIEnYd1SFsDCTZgcVbQMmPToUSNpPJo6r9e75LU01aHbECQ2Pd9zz28ZNb0jkYyY@l6cbvd8iSTyqA1CAmXZKp4av5Q3DA17u/oLgwol13K3HBBzpSij7pD8SvVq3c069Ccc206xN3Gii3ZA@hMvOrM7/VTaqC8dNzvx4JqjSboqd/L8rngMdKGGvhzJ/kCJZSn2Hd0dY2oWurQWvYmiKETlLJ7NMHhGATeBnwVyAPD9GXQFr/6ivx1S27Uo4vfu3jUhiVE5oZkFmyRYkaWzEyposl7mjAMvqFL/TzbV//F@HVhzMjcf32mKyMxDr3vBsV2BnjyELPMcJkiNvLY9djI@18YGt9eKhozj@Gmb3/6JTityIUss4IQmZWS9zC1KvaTw7QMNxEsYamBiUHx8L0cVWmOQ1v2bvoiRcLMSi5sUnDz/lfDa@vwrtJ4B2gBCZ6y93lSm46c6bkXz5nypnV4x7d2dO/yplRAdYplAjRnQuCAPH23@TY4QEHQrNKFARavIIzzJDdSOe8qgWtyqqRhsW36Z@nI7KRv5IJdyFzZ1l25EoZVAWPD4hANGrUOUEDct6DVjT/l7nRlH3JT4NzU@fZjmRCdp8RIKTRx5nBEeUpUnuLaBQb2FETCNhvF8LtqcnPgAjfWDi5zerbZFXHsg5z6cuwENBTk9w2h2ppUXlCJt4aOdSa4wcFspn6azdIgrGY7fzTMIWWosr1FI6uBtXP8NjWwRtQBKj6cVrZTCZ5MXcrfINPUFlGAUqy3fVePULGQqjhv0wV7KIUnqPhEAMiMC4aDv2Yz/RLPZotBeIQ8M4AACNu6rcNwnKLjBhJE80@WtulgUJzCgkiVCTg1zIEGOPXHnt8g3IbiFKBAL14g3HCGLnMh0OfPQFTC/s6p0LUadoJP2psrRm9d2I39Vezpdtul8KQTDZJ4dSP6XpnNMOSGpwtcF/DVQZEsN7iYCoFFoyGM6Q65VDLP8CgMgZc@@wYxoRmyRVR1wbRSAyzXOLBrAgVwjMp9AQfqKNgrqmTaXhV1TJ3PtWduLeO2tg83OLBUgNDlrt@4pVqw@Y6qc0kXro@KzIXiks4Fa2sqNvHGHDpAs0RplW8LGI15J/t4xT4LVKuiYzS0lNqhIA8bIPr962BsLOk2kjtdcodDz8bgac5q4nXWUPL634qwq1L8ThW3kDnc2tlbUBbp26TftO4DAdm7j1@rtAiNQgIeSX31gN5fMa2HQyXtolGZrMGiSlSRiFqR49H3ZcrmjY6wj/@LVHASG9d7AYJiJoedZbdBcam7atdQTxse4Kk1uF/ZhfZNx9bwMKyr5VHuBduiv0D31qLdipYfNQpAD7cqr2j06Sz68@N18WEY/fjx@mUYhPv7pMo7btLEptzZJUWrpbLcCjXL1oNBiUEbFvfOcS/M@bOeNvsvr9bryPuG4/YDCt5izrtIbV@ZJnA2m@32S3wj6FJvo@U2irMtOTrMtToUfH64vksOLRbRiPxAhuX/AE5V3t/qi3TF6f/j@w8 "Java (OpenJDK 8) – Try It Online")
---
### Explanation
```
StackTraceElement[] strace = new Exception().getStackTrace();
String methodName = strace[0].getMethodName();
int lineNum = strace[1].getLineNumber();
String className = strace[1].getClassName().replaceAll(".{5}$", "");
String classPath = Class.forName(className).getProtectionDomain().getCodeSource().getLocation().getPath() + className + ".class";
```
This first part gets some general information about what class we're in and what the name of the function is. This is accomplished by creating an exception and parsing the first 2 entries of the stack trace.
```
java.lang.Exception
at E.getParamName(E.java:28)
at E.main(E.java:17)
```
The first entry is the line that the exception is thrown on which we can grab the methodName from and the second entry is where the function was called from.
```
StringWriter javapOut = new StringWriter();
com.sun.tools.javap.Main.run(new String[] {"-l", "-c", classPath}, new PrintWriter(javapOut));
```
In this line we are executing the javap executable that comes with the JDK. This program parses the class file (bytecode) and presents a human-readable result. We'll use this for rudimentary "parsing".
```
List<String> javapLines = Arrays.asList(javapOut.toString().split("\\r?\\n"));
int byteCodeStart = -1;
Map<Integer, Integer> byteCodePointerToJavaPLine = new HashMap<Integer, Integer>();
Pattern byteCodeIndexPattern = Pattern.compile("^\\s*(\\d+): ");
for (int n = 0;n < javapLines.size();n++) {
String javapLine = javapLines.get(n);
if (byteCodeStart > -1 && (javapLine == null || "".equals(javapLine))) {
break;
}
Matcher byteCodeIndexMatcher = byteCodeIndexPattern.matcher(javapLine);
if (byteCodeIndexMatcher.find()) {
byteCodePointerToJavaPLine.put(Integer.parseInt(byteCodeIndexMatcher.group(1)), n);
} else if (javapLine.contains("line " + lineNum + ":")) {
byteCodeStart = Integer.parseInt(javapLine.substring(javapLine.indexOf(": ") + 2));
}
}
```
We're doing a couple different things here. First, we are reading the javap output line by line into a list. Second we are creating a map of bytecode line indexes to javap line indexes. This helps us later to determine which method invocation we want to analyze. Finally we are using the known line number from the stack trace to determine which bytecode line index we want to be looking at.
```
int varLoadIndex = -1;
int varTableIndex = -1;
for (int i = byteCodePointerToJavaPLine.get(byteCodeStart) + 1;i < javapLines.size();i++) {
if (varLoadIndex < 0 && javapLines.get(i).contains("Method " + methodName + ":")) {
varLoadIndex = i;
continue;
}
if (varLoadIndex > -1 && javapLines.get(i).contains("LocalVariableTable:")) {
varTableIndex = i;
break;
}
}
```
Here we are iterating over the javap lines one more time in order to find the spot where our method is being invoked and where the Local Variable Table starts. We need the line where the method is invoked because the line before it contains the call to load the variable and identifies which variable (by index) to load. The Local Variable Table helps us actually look up the name of the variable based on the index we grabbed.
```
String loadLine = javapLines.get(varLoadIndex - 1).trim();
int varNumber;
try {
varNumber = Integer.parseInt(loadLine.substring(loadLine.indexOf("aload") + 6).trim());
} catch (NumberFormatException e) {
return null;
}
```
This part is actually parsing the load call to get the variable index. This can throw an exception if the function isn't actually called with a variable so we can return null here.
```
int j = varTableIndex + 2;
while(!"".equals(javapLines.get(j))) {
Matcher varName = Pattern.compile("\\s*" + varNumber + "\\s*([a-zA-Z_][a-zA-Z0-9_]*)").matcher(javapLines.get(j));
if (varName.find()) {
return varName.group(1);
}
j++;
}
return null;
```
Finally we parse out the name of the variable from the line in the Local Variable Table. Return null if it isn't found although I've seen no reason why this should happen.
### Putting it all together
```
public static void main(java.lang.String[]);
Code:
...
18: getstatic #19 // Field java/lang/System.out:Ljava/io/PrintStream;
21: aload_1
22: aload_2
23: invokevirtual #25 // Method getParamName:(Ljava/lang/String;)Ljava/lang/String;
...
LineNumberTable:
...
line 17: 18
line 18: 29
line 19: 40
...
LocalVariableTable:
Start Length Slot Name Signature
0 83 0 args [Ljava/lang/String;
8 75 1 e LE;
11 72 2 str Ljava/lang/String;
14 69 3 str2 Ljava/lang/String;
18 65 4 str4 Ljava/lang/String;
77 5 5 e1 Ljava/lang/Exception;
```
This is basically what we're looking at. In the example code the first invocation is line 17. line 17 in the LineNumberTable shows that the beginning of that line is bytecode line index 18. That is the `System.out` load. Then we have `aload_2` right before the method call so we look for the variable in slot 2 of the LocalVariableTable which is `str` in this case.
---
For fun, here's one which handles multiple function calls on the same line. This causes the function to not be idempotent but that's kind of the point. [Try it online!](https://tio.run/##nVhbb9s2FH7Pr@CEoZDqmImLbtjiJEOQtViHtDGQIAMWZwUtMzYd3UZSuTT1X693DnUxJdFGOj2oMc/9OzeqC3bP@mnGk8X0brUScZZKTRZwSEVKR1Ik@i8pNJfDnRbtQgNx5iLmWkT0REr2pByEP5iaf2SZg3ImlHYcu5kln/FHoOlw7rRf0EdMg3vJcGcnjJhS5Io87xB4snwSiZAozTT8c5@KKYmZSPwiqOsbwuRMBSUzPleEkyOS8Ady5QfD@rjgBz0SqJ7m6tJzEd9spb51ULV8sqwb/ieleUzTXNMM0xIlPqczrkdMsvgTi7kPqoJg@CK@N4EVxIu1v21LcTopzr9XGaehH9jaliTEVPrvHkOeaZEmhA@CFgJ8UKi70Cy8u5Qs5HYqljvrt3mVyYXyOSyw3iUfEg1lIY9JJBJ@yqJIlUkti7LDWBkok9WIoTzL8CAgei7TB0XW/j9bma78fRfxmCca6gtQg9@l9VrIDxAmd3yluZjreTpFB0C40HK9f4NiH2uKLQZ4mWg/5fFaYGAEzorjCZe2QNugaZymvUL8tCKA15JnEVBOosj36PNPyx@9XeJ5Xe@NMmjKOSgz8vQ2lUZHbcZAMJKp5iFC8ntqGtOcnqZTfpHmEoExAaRQNDVsqNYPSM/yuEc8an55bk8QAfCkIXDgwbtEzIFKWRkkzOWZVUR1QaEnfq3cTsQt8ZtCkPw8itpVvtaU5ZamXTJotAuPFH@pZMNsr6loU96LwW4Ganae67JSbZpdNGEaU5UnVKcpmDdCMJtFQmWe@GvB65tnrx9hbfRDeNfVsNw12q1141eG7SGBC6Js0ePCMwwL4S@2DWUKWWpZcKfghgJRWSS0743H8rfxOPGCVotMnjQ35aWZxGD7gzUdB0OZdmuEVBKjFOS5vEz/BKujsqLsmdIRtYErF1St7UMy5Y/V4VFFpoBvJiLue/@Mx@q1Px5Pe8EBsRsM@oj4GAmK7Q8TcmghRJX4glMh6fXa5Va2Q80L0pYcFnPSmu5YyE24jgEu8uoV8S0tRXGTr19hDlD@b84itSbD6G@5gc9EcnbXtLVs/Cq3fROs6vDIiSGNC7Jle3M0tj56K5Kp7/ZzY@ZN45VpprAYFKjUbvUzmeaZPwgCKP2WS2Vzo2e111ABiYaGUr6HbU6sIVUMra2eVlXdcW2tX@UTVfTK@kygw@e3voelBmY6t4alNUca7XTP5FnKpibiVjeV5Es2ifgmeoiT6jy5nItqRO87Kl1YOXfkAmu3AQCGMBgKZ2eIbmcg/o04Dsk@VnmrPURg5abYwSY71qLenCC00eu1wz3evE9cSvBpAS6GHa5l5wTdFknOt7XcdkSqxt8GCS7p6IpJgQk3Wd@ARbsoHDFsnRAbVxmJwGH3bGtE04fNSEEibt@fgKu4J227n9dMrj6rPLDarD6qu4zhkWm0nys/ujdk4hdW3qcSRpt1XW5DKrnOYYfgFHate4xrAa42UYceXzM/zHHl/OCY3wV4i@4Yr4YxglFcGTsbDBcY9scaL2gPs9WuWf/LSf/vzzflH/v9Xz/fvA68oDvEaweG7hJF41smeIlNxVjN4m2NsOj1XDB2ULY@QMxn5eQ7vhO6n02ND45CQ9CxU91ofTvU0jH8rtReJbJcrb6FtxGbqVV/tuqH2Yoe7OVK7kVisre4j/cQ4P6A/kL3q/8TMKTqWie/pcZp9X9k/wM "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/)
This is about the most dirty code I've written but it works. ¯\\_(ツ)\_/¯ Throws an error on a non-existent variable as Python will immediately dislike you for calling the function with one. Also throws an error on non-variables but this can be fixed with a try/except if needed.
```
import inspect
import re
def name_of(var):
for i in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
return re.search(r'\bname_of\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', i).groups()[0]
```
[Try it online!](https://tio.run/##XU9Nb8IwDL3nV2SnxohWiO2ySTvsxj9AWltVoTg0WutETjoBf76ko@yAD/5479nW85fYOdpOkx284ygtBY9tFMvIKMQRjSQ9YOOM@tUMH0KmMI6lTfLHRnHCaDjJLBmnHmA7MiPdCQWFaQ66/YHytb4fmYMxjkypFAE1t53irDos/6qwqlRKqvzKv3V@beql2eTvTb2CmYdsLS0UJ3ajDwrKTT112PdOfspsNzdruXfcH18yEbweEvy2FcKzpfhv628BnsBZ/YyRIzzbEJMnmG4 "Python 2 – Try It Online")
If we're allowed to take the argument as a string, this satisfies the requirements of outputting a falsy value on an invalid input.
```
import inspect
import re
def name_of(var):
# return var :P
try:
eval(var)
except NameError:
return False
for i in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
try:
return re.search(r'\bname_of\s*\(\s*[\'"]([A-Za-z_][A-Za-z0-9_]*)[\'"]\s*\)', i).groups()[0]
except AttributeError:
return False
```
[Try it online!](https://tio.run/##ZVBNb8IwDL3nV2S7JEG04msHJu3AYdNOu05aW1WhuDRam0ROimB/vksLDAY@RPZ7fnae7cFXRs@6TjXWoKdKOwuFJ6cSgZANlFTLBnJT8p1E8UxoCI@HY9IH7GQ9cAMC@wKspx9B84po8NKH4FvU9E3WLgzukdIgVWHreXG8BV9iUCpdGn4GixYR9JHgIi7ztSy@RTLPLqP//edqF0LsQGJRcWTp@uQjdaOUhydJ2WPGk1X0JaOfPDslk2iZZyMxkH2nYGOqRLxF01rHRTLJLsaPVlfeo1q3/tbvreeugro29IWy9z4Z00@D9eaBEWdlE@DFjBCLSvu/g7NBwcQt3Avu0Xk8XUyflveENhr2yvlwRCa6Xw "Python 2 – Try It Online")
[Answer]
## Mathematica
```
f[x_] := ValueQ @ x && ToString @ HoldForm @ x
SetAttributes[f, HoldFirst]
```
The `HoldFirst` attribute prevents `f` from evaluating its argument before invoking the function. `ValueQ @ x` then checks whether the given argument is a variable that has been given a value. If not we just return `False` due to short-circuiting. Otherwise, we obtain the variable name with `ToString @ HoldForm @ x`.
[Answer]
# Mathematica
```
f~SetAttributes~HoldAll;
f[_] = False;
f[x_Symbol?ValueQ] := SymbolName@Unevaluated@x;
```
Mathematica likes to evaluate **everything**, so to make it stop, we have to fight against it. In its own language.
## How?
```
f~SetAttributes~HoldAll;
```
Tells Mathematica that whenever function `f` is called, its arguments shouldn't be evaluated (i.e. held).
---
```
f[_] = False;
```
When `f` is called with an argument, output `False`. (?!)
---
```
f[x_Symbol?ValueQ] := SymbolName@Unevaluated@x;
```
When `f` is called with a defined Symbol (which has a value), output the symbol name of the input.
The previous line does not take precedence, despite being defined earlier, because this definition is more specific. As the Wolfram Documentation states: Mathematica "tries to put specific definitions before more general definitions."
Mathematica is very stubborn and keeps trying to evaluate variables whenever possible. The extra `Unevaluated` takes care of that.
[Answer]
# C#
```
string n<T>(Expression<Func<T>>m) =>
(m.Body as MemberExpression)?.Member?.Name ?? null;
```
Full/Formatted version:
```
using System;
using System.Linq.Expressions;
class P
{
static void Main()
{
var apple = "Hello";
var nil = "Nothing";
var SOMETHING = 69;
Console.WriteLine(n(() => apple));
Console.WriteLine(n(() => nil));
Console.WriteLine(n(() => SOMETHING));
Console.WriteLine(n(() => 3.14159));
Console.ReadLine();
}
static string n<T>(Expression<Func<T>>m)
=> (m.Body as MemberExpression)?.Member?.Name ?? null;
}
```
---
Another way to do this is by reflecting on the type like so:
```
public static string GetParameterName<T>(T item)
{
var properties = typeof(T).GetProperties();
return properties.Length > 0 ? properties[0].Name : null;
}
```
However, you have to call it like:
```
GetParameterName(new { apple });
```
It then also fails for `3.14159` by returning `Length` and for that you also have to call it like the following instead:
```
GetParameterName(new double[]{ 3.14159 });
```
---
In C# 6.0 we also have:
```
nameof
```
But this won't compile if you pass it something that isn't a variable e.g. `3.14159`. I believe it also evaluates the input at compile time so it seems like it fails that requirement as well.
[Answer]
# MATLAB
```
varname = @(x) inputname(1);
```
Within a function there are a few preset variables like `varargin` or `nargin`, among those we also have `inputname`.
[stolen from here](https://stackoverflow.com/a/11453337/2913106)
[Answer]
## R
```
function(x) if (identical(substitute(x), x)) FALSE else substitute(x)
```
`substitute` returns the parse tree for an unevaluated expression. The `identical` conditional makes sure that this unevaluated expression isn't identical to the expression itself; i.e. that the passed in parameter isn't a literal.
[Answer]
## Python 2
Some research has been done. And it seems to be possible in python, but I still expect some troubles to be found.
Solution is not perfect, as it assumes some structure of the code. Yet I didn't break it still.
```
import inspect
import re
def get_name(var):
called = inspect.getouterframes(inspect.currentframe())[1][4][0]
return re.search('(?<=get_name\().*(?=\))', called).group().lstrip().rstrip()
```
This uses inspect to look at surround scope and find where function `get_name` is called.
For example `inspect...[1]` will return
>
> `(< frame object at 0x01E29030>, 'C:/Users/---/PycharmProjects/CodeGolf/Name_var.py', 14, '< module>', ['print get_name( a )\n'], 0)`
>
>
>
And `inspect...[1][4]` will show us list with code, where function is called:
>
> `['print get_name( a )\n']`
>
>
>
After that I used regex to retrieve name of the argument
```
re.search('(?<=get_name\().*(?=\))', called).group()
```
And `.lstrip().rstrip()` to remove all whitespaces that may be placed into bracets.
[Example with some tricky input](https://tio.run/##ZY7bCoMwDIbv@xTe2YxR3NjVWPFBVEat8QBaS4yDPb3rRBnMQEjy5c/Bv7kd3XVZusGPxFHnJo@WxVYSClFhHTXIT2cGlC9DcBdRMGv6HqtI7yMqaMaZkWoKwknu2M5E6HilEiC7FNmtyJJiXULIM7kQ1ISGbCtjmT70fi2XoE4y1TlAfN4OgmponH3o9BNT901oSxajE1EGtzorRKWtEJ46x7/vDfyT8kDsgVSwfAA)
[Answer]
## PowerShell
```
function t($t){(variable($MyInvocation.Line.Split(' $'))[-1]-ea si).Name}
$apple = 'hi'
t $apple
apple
t 3.141
```
But it doesn't work reliably, it's rudimentary.
[Answer]
# [PHP](https://php.net/)
Needs that the variable value is unique in the array of the global variables
```
function v($i){echo"$".array_search($i,$GLOBALS);}
```
[Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MUyjRUMjWrU5Mz8pVUlPQSi4oSK@OLUxOLkjOAEjoq7j7@To4@wZrWtf9VMlJzcvJtTay5gHrAbE3r/1/z8nWTE5MzUgE "PHP – Try It Online")
# [PHP](https://php.net/), 96 bytes
```
function v($i){
echo($i==end($g=$GLOBALS))?"$".key(array_slice($g,-1)):0;
}
$hello=4;
v($hello);
```
[Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MUyjRUMjWruVKTM/KBLFvb1LwUDZV0WxV3H38nR59gTU17JRUlvezUSo3EoqLEyvjinMzkVKAKHV1DTU0rA2uuWi6VjNScnHxbE2suoGFgtqb1//8A "PHP – Try It Online")
Needs that the variable is initialized directly to the function call.
Checks if the last global variable is equal surrendering variable
[Answer]
# JavaScript (ES6)
For all property names in `window` (`Object.getOwnPropertyNames(w)`), attempt to define a getter for that property that returns the property name.
Then, add an entry to a Map `M` where the key is the (possibly overridden) value of the property, and the value is the name of the property.
The function `f` simply takes a variable (i.e. a property of `window`) and returns the entry in `M` for that value.
```
let
w = window,
M = new Map(),
L = console.log,
P = Object.getOwnPropertyNames(w),
D = Object.defineProperty
for(const p of P){
try {
D(w, p, {
get(){
return p
}
})
} catch(e){ L(e) }
try {
M.set(w[p], p)
} catch(e){ L(e) }
}
let f = v => M.get(v)
```
This works for all built-in global variables except `window` itself, as there is no way to distinguish it from `top` (unless run in a frame):
```
L( P.filter(p => p !== f(w[p])) )
// -> ['window']
```
[Answer]
# Perl 5 + Devel::Caller
```
use 5.010;
use Devel::Caller qw/caller_vars/;
use Scalar::Util qw/refaddr/;
sub v {
# find all operands used in the call, formatted as variable names
my @varsused = caller_vars(0,1);
scalar @varsused == 1 or return; # exactly one operand, or return false
$varsused[0] =~ s/^\$// or return; # the operand actually is a variable
# it's possible we were given an expression like "~$test" which has only
# one operand, but is not a variable in its own right; compare memory
# addresses to work this out
refaddr \ ($_[0]) == refaddr \ (${$varsused[0]}) or return;
return '$' . $varsused[0];
}
# some test code
our $test = 1;
our $test2 = 2;
our $test3 = 3;
say v($test2);
say v(2);
say v(~$test3);
say v($test);
say v($test + 1);
say v(++$test);
say v($test3);
```
We use Devel::Caller (a debugger-like module) to walk the call stack, looking for the call to the function, and return all the operands within the argument, returning them as variable names. If there's more (or less) than one operand, we weren't called with a variable. If the operand wasn't a variable, it won't have a name and we can detect that too.
The trickiest case is if we get a one-operand expression involving a variable, such as `~$x`. We can figure out if this has occurred by taking a reference to the variable directly from the symbol table (using the `${…}` symbolic reference syntax) and comparing its memory address to the value we were passed as an argument (which is, conveniently, passed by reference). If they're different, we have an expression rather than a lone variable.
Note that if we call this function with a preincrement or predecrement expression on a single variable, as in `v(--$x)`, we get `$x` returned. This is because it's actually the variable itself that's being passed to the function in this case; it just gets incremented or decremented beforehand. I hope this doesn't disqualify the answer. (In a way, it makes it better, because it shows that we're checking the argument itself rather than just reading the source code.)
[Answer]
## PHP
While the other PHP submissions only test if the given value matches a value of a global, this version works by taking a reference to the value:
```
// take a reference to the global variable
function f(&$i){
foreach(array_reverse($GLOBALS) as $key => $value)
if($key != 'GLOBALS') {
// Set the value of each global to its name
$GLOBALS[$key] = $key;
}
foreach($GLOBALS as $key => $value)
if($key != 'GLOBALS' && $key != $value) {
// The values mismatch so it had a reference to another value
// we delete it
unset($GLOBALS[$key]);
// and update the value to its name again
$GLOBALS[$key] = $key;
}
echo '$', is_array($i) ? 'GLOBALS' : $i, "\n";
}
```
This should now work even if the global variable is a reference to another value at the time of calling.
Test it [here](http://sandbox.onlinephpfunctions.com/code/3b424a6c7bc1229359d37684983bf0e2bdea01cf).
[Answer]
# [Röda](https://github.com/fergusq/roda)
```
f(&a...) {
a() | name(_) | for str do
false if [ "<" in str ] else [str]
done
}
```
[Try it online!](https://tio.run/##TY6xCsIwFEXn5CseGaRZAqIIio5iHayDbkUk0EQDaV5Ju9V@e00yGLd77zk8nsdGzrMuFlIIwWGkRBYcPuBkq4pnTBo99IOHBikhWtpegdFQA9szMC6hB6g41yE/KGnQKTrNrQw03us6q2B3AFYqa5FR0nnjBtBFIpwSSpyxyahweBv3@nMCScbtejney3N1it5mm4UfSJpGjMI4ZSFMnOa6Ess1z3WcePj1Cw "Röda – Try It Online")
Röda has a builtin function for this – `name`. Unfortunately, though, it doesn't return a falsy value when not given a variable.
This code abuses several features of reference semantics. Explanation line by line:
`f(&a...) {`
The function takes a variable number of reference arguments (`&a...`). This is the only way in Röda to create a list of references.
`a() | name(_) | for str do`
At the second line the elements of `a` are pushed to the stream (`a()`). These elements are references if the function was given variables and normal values otherwise.
The elements are iterated using an underscore loop. The underscore syntax is syntax sugar for `for` loops, so `name(_)` is equivalent to `name(var) for var`. The name of the variable used in the `for` loop is of form `<sfvN>` where N varies. (Ie. "`name(<sfv1>) for <sfv1>`") It is illegal for a user-defined variable to contain `<` or `>`, so the generated names don't collide with existing variable names.
The `name()` function returns the name of the given variable. If the element in `a` being iterated is a reference, then it is the variable given to `name`. Otherwise, if the element was a normal value, the variable given to `name` is the underscore variable `<sfvN>`. This is due to the semantics of references in Röda: if a function accepts a reference and the function is passed a reference variable, the passed value does not point to the reference variable but to the variable the reference variable points to.
`false if [ "<" in str ] else [str]`
At the third line we examine if the variable name in the stream contains a `<` character. If so, it is an underscore variable and the value passed to `f` was not a reference. Otherwise we output the name of the reference.
This solution does not work if the variable given to the function is a reference or an underscore variable. However, the question specifies that only global variables must be handled, and they can't be references or underscore variables in Röda.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 bytes
Feels like the dirtiest code I've ever written for Ruby.
Requires that the global variables you call has a unique value that isn't on any other global variable, because the only way to do this challenge in Ruby is to do an search on all global variables and return the first match. OP says it's ok, and is free to judge if my solution is valid.
Note that global variables start with `$` in Ruby, for if you want to add extra test case stuff.
```
->v{global_variables.find{|n|eval(n.to_s)==v}}
```
[Try it online!](https://tio.run/##TY7NCsIwEITveYpQctCDhVqrWIh3D4IPIJTUbjSwbkv6h7R99hqtYg/L7nw7DGPr9DkKLS/j6tB0N8xThUmjrFEpQulrQ1nXUw@NwgX5VZ6USymbYRjFHRBzLrk3HW1uMfOYoPqRgnU8WIebaLtjojBOnVR1j@PzkbEMNCdok8IaqrjLrYFxUg9wLqH9q0L8UaO/D8nJIOO8mDZgCW9VV@XH4Ahl7D3snzwVnIOp2pwUZq70TIR@sAmi/fgC "Ruby – Try It Online")
[Answer]
# PHP
```
function f($v){foreach($GLOBALS as$n=>$x)$x!=$v?:die($n);}
```
if value is found, print variable name and exit. print nothing and don´t exit else.
**61 bytes** to return variable name or `NULL`:
```
function f($v){foreach($GLOBALS as$n=>$x)if($x==$v)return$n;}
```
It will not find named functions, only those assigned to variables.
And a PHP function cannot detect wether a parameter was provided by reference or by value. The function will just return the first name where the value matches the function parameter value.
[Test it online](http://sandbox.onlinephpfunctions.com/code/e3b9cd0b166614552f0d7b9a9b7623be4c3d597a)
[Answer]
## PowerShell
New version but works starting from PowerShell 3.0
```
function p{[scriptblock]::create($myinvocation.line).ast.findall({$args[0]-is[Management.Automation.Language.VariableExpressionAst]},0)[0]|% v*h|% u*|%{($_,!1)[!$_]}}
```
[Try It Online!](https://tio.run/##PY9RS8MwFIXf@ys6yGg7Zmh1Ig76sIehgpsPE19KGbc1bYNpEpJ0Kll@e00Z7uVc@M45l3ul@CZKd4SxcWwGXhsqeChtoWtFpamYqL/K9bpWBAyJUf9L@UnUMKUwo5wkGLTBDeWfwFhsEahWF2l5Q3WxAw4t6Qk3eDMY0V9Kr8DbwXP8AYpCxcj2Ryqitfc22pRumSa@f56Hp0XndVic5zZGx@UsS4oZOpbOjTJAICUjeTSdLaJAhhcQIE5ZHu2F6ShvPY8nkATo8Lbbvj@/7J/y1W32kE7GFSXB9e1GCOv8Nj@93uFsld0/@rB1yUT/YxUo68Y/)
**Previous version**
```
function p{$t=[management.automation.psparser]::tokenize($myinvocation.line,[ref]@())|? type -match '^[cv]'|? start|% content;($t,!1)[!$t]}
```
[Try It Online!](https://tio.run/##PY9RS8MwEMff@ykyiKSBWaxOZBtFX0R9cD7Mt1IhhOsaTC8hvU1m189eUwd7@h@/3x13590PhK4Ba8ex3qMm45D5nlNRtgrVDlpAytSeXKsml/nOq9BBqFYrct@A5hdS3h4NHpw@d1iDMC8D1NVTKuXpkdHRA7uO87ph4qvUh0pE2pEKdLpi2iHFHeuU03yWy3LGqRpGrry3UIjpMicSn56BTDgaW4iNo8bg7l9EEPH24/358/Vt81IsbvOHm0lckEwur9XO9UOUMWWMuyxf5PfLqewHOf4B)
[Answer]
# tcl
```
proc p a {puts [subst $a]}
```
## [demo](http://rextester.com/ZOEWO55299)
[Answer]
# JavaScript (ES6)
Requires that the value of the variable passed to the function is unique to that variable. Returns `undefined` if a variable wasn't passed.
```
arg=>{
for(key in this)
if(this[key]===arg)
return key
}
```
---
## Try it
For some reason, it throws a cross-origin error in a Snippet when a "literal" is passed.
```
var fn=
arg=>{
for(key in this)
if(this[key]===arg)
return key
},
str="string",
int=8,
arr=[1,2,3],
obj={a:1}
console.log(fn(fn))
console.log(fn(str))
console.log(fn(int))
console.log(fn(arr))
console.log(fn(obj))
```
---
## Explanation
Loop through all the entries in the global object (`this`), checking if the value of each one is strictly equal to the value of the argument passed to the function. If a matching entry is found then its key (name) is returned, exiting the function.
---
] |
[Question]
[
Given a multidimensional array, find the recursive alternating sum. An alternating sum is simply the sum of an array, where every other item (starting with the second) is negated. For example, the alternating sum of `[7, 1, 6, -4, -2]` is the sum of `[7, -1, 6, 4, -2]`, or `14`. In this challenge, you'll take the alternating sum of a multidimensional array.
**Task:**
Given an array like this:
```
[
[
[1, 2], [2, 4], [4, 8]
],
[
[-4, -4], [-1, 1], [2, -2]
]
]
```
First find the alternating sums of all of the deepest nested arrays:
```
[
[-1, -2, -4],
[0, -2, 4]
]
```
Then do this again:
```
[-3, 6]
```
And finally:
```
-9
```
You can choose how input is represented, but it must be able to handle multidimensional arrays of any number of dimensions possible in the language you use. You don't need to support ragged arrays.
**Test cases:**
```
[1] 1
[-1] -1
[1, 2] -1
[2, 0, 4] 6
[1, -2] 3
[[1]] 1
[[1, 2], [4, 8]] 3
[[-1, -1], [2, 2]] 0
[[[[1], [2]], [[4], [8]]]] 3
[[[1, 2], [2, 4], [4, 8]], [[-4, -4], [-1, 1], [2, -2]]] -9
```
**Other:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (per language) wins!
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 4 bytes [SBCS](https://github.com/abrudz/SBCS)
```
-/⍣≡
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=09V/1Lv4UedCAA&f=S1d41DZBIQ1ITnzUu/hR58JHvUse9U31Cvb340pXUI82jFUH07owhqGOghGCqQtjAxXCWSAVOgrRJjoKFnBBXZBiQ5CwEUgaJgzSBxKLBZHRJiASqAchDTMLqMkEYSZIrS6QqQsWAxkNMxnoHqBmAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Alternating sum (aka right-reduce by subtraction) along last axis `-/` until convergence `⍣≡`.
[Answer]
# [Python](https://www.python.org), 58 bytes
```
f=lambda a,s=-1:sum(f(x)*(s:=-s)for x in a)if[]==a*0else a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVBLCsIwFNx7irdMSh6Y0kUp5CShi4gNBvqjaaE9i5tu9E6ewiuYp1ZpNo_MzJuZJNd7v4yXrl3X2zRazB-FVbVpTmcDRniFsvBTwyybecJ8odBz2w0wg2vBcGd1qZRJjlXtKzDfhGc_uHYMHi1Lzg8_hHsoBaQxgXsmBESYPAJ0JiCPJCS7JDGlpb1ISaSUNHVGM_jjpS09BGT_FnJgOOKbo5qtJdyWIj7P3j7wBQ)
# [Whython](https://github.com/pxeger/whython), 45 bytes
```
f=lambda a,s=-1:sum(f(x)*(s:=-s)for x in a)?a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728PKOyJCM_b8GCpaUlaboWN3XTbHMSc5NSEhUSdYptdQ2tiktzNdI0KjS1NIqtbHWLNdPyixQqFDLzFBI17ROhmt4XFGXmlQCVRRvGampywXm6qFxDHQUjdAFdVBGgAWh8kB4dhWgTHQULNCldkHZDkKQRSBGqJMgkkEwsiIw2AZFA_eiKYKYDDTBB2ALSoQtk6oLFQNbAbAG6FmQExNuwMAMA)
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
f=lambda A,*a:(f(*A)if f<A else A)-(a>()and f(*a))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVFBCsIwEMSrr9hjUpJDQw9FVMg7QpFIGyzUWjQefIuXXsQ36WvctcTSFLwMm5mdmZDcn93NH06t6vvH1TuZv5TbNPa4Ly1okdgVcyzRvHbg1hqq5lKB5pLZLeO2LQFFy_ngfC923bluPTlMWnC-HI8yOqcC1IyREYUhMUE2ASYTkMeapISUVEVbkUphJBWEJiPEhNlWKMCIbCwii8RRfjkqCj145UkGJaA-QCHMb0bAHDMlxGSb5H_u8M7hpz4)
Expects splatted input. Test harness borrowed from @pxeger.
How?
Hybrid recursion implementing depth first traversal. Detail: `f<A` depends on Python 2's comparability of objects of different types.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
ċ↰ᵐ-|
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/0g3kA9k6Nb8/x8dbRirEx0PIgx1FIyAlJGOgoGOgglEIB4kAlQCJsHyCtEmOgoWYIF4kAJDkJARSAokBDYOyI8FkdEmIBKoFiIF028ENh1uDlBdPJAZDxYDGQkzEWg3XCNYHErB1SEJQ81BFwUKomsGKyTKxNhYAA "Brachylog – Try It Online")
```
↰ᵐ Recur on each element
- then take the alternating sum
ċ | if it's a list, else return it unchanged.
```
[Answer]
# [C++ 20](https://gcc.gnu.org), 87 bytes
```
int f(int a){return a;}int f(auto a){int s=0,i=1;for(auto b:a)s+=f(b)*i,i=-i;return s;}
```
This answer is in the same spirit as [@HatsuPointerKun's](https://codegolf.stackexchange.com/questions/247398/alternating-sums-of-multidimensional-arrays/247460#247460), but it (ab)uses C++ 20's `auto` parameter declaration, which allows us to ditch the whole `#include<vector>` shenanigans (it works with any container).
[Attempt This Online!](https://ato.pxeger.com/run?1=jZTNbqMwFIU33eCnuMosGgZbBZekNIQ8xUhdZKIRJTBCSmGETTZRnmQ23cyyfZ_p09TXNpMSWZ0ssMyF-51zDz-_X4pfu17g8eNnUbyuJ0zIbVYEAQ8nm-c_vaxY8vehbiRUU1xz_9CVsu8ayNOjKee9bLGOZyILaZ1FadV2pv64yH0RZNX00f9aq0usTm2_SI8G_3YlvtRNseu3JSz3ZSHbbkVOlboVsivzpxUh-7begiyF1Fa6UvQ76ZMD8ZTnxaJoewnLpa3j7vp7c52SIyF4-1NeN1Mk6I6bG_imQFDkooR1tLEMI79U969gH0EGB4jgmBJPq1bTfeT7KTlvZ-5-rvvZGMBdgIhyJ-HWOKDAR4xbF4PTkMZOSqwpnEJIIR6BYrcZ5nYzG9ywsZ2Zi6IyPYOcAxVxrok64xFx7iaqHDYU1jGF5AL43QDX8VG1w8YzpTunEsMhI9TiqPl_rcRqmUajxrXuSC1xqmFWKLXBdR3jqub7TPVTN-jn3vghnmfj1YbQDbW12NR0HsQb27x32xzyV4PFp-eAnpnaMl3DAIbg1Gt06RDGuPrkQjRuLQaKFdhHF3A6WFZaQfJxFKNuLmr9f_kzbsf7-AWHOJ399zzbX9w7)
[Answer]
# [flax](https://github.com/PyGamer0/flax), 4 3 bytes
```
-/´
```
[Try It Online!](https://dso.surge.sh/#@WyJmbGF4IiwiIiwiLS/CtCIsIiIsIiIsIltbW1sxLDJdLFsyLDRdLFs0LDhdXSxbWy00LC00XSxbLTEsMV0sWzIsLTJdXV1dIl0=)
Another port of @ovs' APL answer.
*¯1 byte due to update changing direction of fold/scan to match evaluation order*
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes
```
∑{¬£d
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FstOba8-tDhlSXFScjFUaMHN-dGGsVzRuiDCUEfBCEgZ6SgY6CiYQAR0QSJAJWASJK-jEG2io2ABFtAFKTAECRmBpEBCILUgfiyIjDYBkUC1ECmYfiOQ6XBzQOp0gUxdsBjISJiJQLtjYyHuBAA)
```
∑ Repeat the following function until it fails:
{ Start a block
£d Convert from base -1; fail if the input is not a list
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 11 bytes
```
({y-x}/|:)/
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs9KortStqNWvsdLU5+JKt0pziE/IsudKV1CKNoxVAtO6MIahjoIRgqkLYwMVwlkgFToK0SY6ChZwQV2QYkOQsBFIGiYM0gcSiwWR0SYgEqgHIQ0zC6jJBGEmSK0ukKkLFgMZDTMZ6B6gZgCKwjFE)
Port of @ovs' APL answer.
[Answer]
# [Haskell](https://www.haskell.org/) + [free](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html#v:iter), 14 bytes
```
iter$foldr(-)0
```
[Try it online!](https://tio.run/##fVA9b4MwFNz5FW9Aqi0VKSWt1ESFqYrUqR26Vahyg12sgEHGtBny3@nzB2mQIgbAd@/e3ZmK9Qde12OSwAmeuZBKqm8wleyh4ppDL9WeI@YgNOfQtOVQc5C9ujHAfpis2RfiVsH7y2tUMsNgZ3UCWASQwduAHvZ48jwRQCYBpVEkVW8YJqCCwG5Qe9NqEIgoPmiQn8mwZvlf28zNRcM6tCIu5kghcyz42Bgnx5nMWVzIHI79mHgRxZVIGq5hu/0vZItgdQZJjr3te7qEY/zCZ@iBgmziukqG2MayDp4HT3GO9Cgyy8SirUtNEroaGyZVVrZYstNSGXcRb/LhAu4Kem12nfUbt/6XpAuaNGgewne97DfrM4PphGaSoljucCFeB@X93HcT6MeioOMf "Haskell – Try It Online")
We need the free library to represent arbitrarily nested lists. This code works on any ragged list as well. `foldr(-)0` computes the alternating sum of a flat list and `iter` applies it recursively to a free monad.
[Answer]
# [R](https://www.r-project.org), ~~51~~ 48 bytes
*Edit: -3 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
f=\(l)"if"(is.list(l),Reduce(`-`,Map(f,l),,T),l)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWNw3SbGM0cjSVMtOUNDKL9XIyi0uAXJ2g1JTS5FSNBN0EHd_EAo00HaCYTogmkILou8XMl6YBVmyoqamsQC4w5IKaokuJMbpwYwx1FIzINghhjJGOgoGOggl5JpkhOUaXbNcYw0yBBTLZwWOIahIohHQUwGwTHQULUg1GdZcuyI-GMPOMwKFPinkGKKYh-xdmpCaMBXExjAdyN1E2GWPagBwERqBoRgkOZOt0gUK6cHmQZ5H9CopcqBt0LSHZApatAA)
Takes input as a list of lists.
---
Old version:
```
f=\(l)"if"(is.list(l),sapply(l,f)%*%-(-1)^seq(l),l)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN43TbGM0cjSVMtOUNDKL9XIyi0uAXJ3ixIKCnEqNHJ00TVUtVV0NXUPNuOLUQpBUjiZE6y1mvjQNsHpDTU1lBXKBIRfUFF1KjNGFG2Ooo2BEtkEIY4x0FAx0FEzIM8kMyTG6ZLvGGGYKLJDJDh5DVJNAIaSjAGab6ChYkGowqrt0QX40hJlnBA59UswzQDEN2b8wIzVhLIiLYTyQu4myyRjTBuQgMAJFM0pwIFunCxTShcuDPIvsV1DkQt2gawnJFrCcBQA)
Takes input as above. Outputs a \$1\times1\$ matrix.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 33 bytes
```
f(a)=if(#a',f(a[1])-f(a[^1]),a,a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVBBCgIxDPxKXA-2kIAtPexFP7Ko5FIpiJRlPfgWL3sRP-MH_I1pmwWxh2QynUzSPl6Zx3Q653l-3qZI_WcVDdtdimbNGxQ8uIOlko8CkJGtCt-c8-VuGGgPeUzXSWBXig6KhUUYpFci1egQfMkeYYsQlKLKia4l1QSEvjFUNE77fOPUVqvqJGq9-xkT_qwEUmgLISyesoAcfdPyCV8)
```
f(a)=if(#a',f(a[1])-f(a[^1]),a,a)
f(a)= Define a function `f` with argument `a`:
if(#a', If the length of `a`'s derivative is nonzero,
so `a` is a nonempty list:
f(a[1]) apply `f` to the first element of `a`,
- minus
f(a[^1]), apply `f` to `a` with the first element removed.
a, Otherwise, if `a` is truthy,
so `a` is a nonzero integer:
a return `a`.
) (Implicitly) Otherwise, return 0.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes
```
Fold[#2-#&]@*Reverse//@#&
```
[Try it online!](https://tio.run/##PU29CsMgEN59DcGheISIQ5cWp879GUMGSQ0VmgRS2@Uwr25PLV3u4/u9yYaHm2zwg03jIZ2W573jCrjoze7qPm59uaYxXKTL27tgzqufQ8fhOBrei@022HlDhm2UDKHcVqoKUJCsCllGLfeVAvkUR0VyEXKQKBFETYdyP6M2ldT/PtW1hMxppq7QsxhZTF8 "Wolfram Language (Mathematica) – Try It Online")
Right-fold subtraction on every level. Supports ragged arrays.
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 9 bytes
```
itr$lH(-)
```
## Explanation
Seeing how short my [haskell answer](https://codegolf.stackexchange.com/a/247445/56656) turned out I couldn't help but port it to hgl. This works *basically* the same.
It takes input as a free monad of lists, that is a ragged list. `lH(-)` is equivalent to the haskell `foldl1(-)` and calculates the alternating sum of a flat list. We use it with `itr` to recursively reduce a ragged list.
## Reflection
This is pretty tight as far as things go.
It feels clunky to use `(-)` here but the alternative is `fsb` which would lose a byte due to spacing. In order for it to save bytes `fsb` would have to be 1 byte long.
The one thing that seems like it could be worthwhile would be an alternating sum builtin. It would probably save 2 bytes here.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 15 bytes
```
{0==ùï©?ùï©;ùïä-Àù‚éâ1ùï©}
```
Anonymous function. Takes a multidimensional array, returns a [0-dimensional array](https://mlochbaum.github.io/BQN/doc/enclose.html#whats-a-unit) containing a number.
### Explanation
```
{0==ùï©?ùï©;ùïä-Àù‚éâ1ùï©}
{ } Anonymous function:
= Rank (number of dimensions) of
ùï© the argument
0= equals zero?
? If so:
ùï© Return the argument unchanged
; If not:
Àù Right fold
- on subtraction
‚éâ1 the innermost axis of
ùï© the argument
ùïä and call this function recursively on that array
```
[Answer]
# [Java 17](https://en.wikipedia.org/wiki/Java_(programming_language)), 101 bytes
```
int f(Object[]a){int s=0,m=-1;for(var i:a)s+=(m=-m)*(i instanceof Long j?j:f((Object[])i));return s;}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nVNBboMwEFTVW16xR7s1UUA5oCDUD7jqIccoB4fayAhMhA1VhfKSXji0T-hj2tfUQBKlqKlCTpZnxjOzK_ntPWEVaz6jlGkNj0wqqCcA2jAjo4_SCMf_4lIZEOhpk_DIrNYM1y2gwxnJQscNRF6gihUgFwzr-xBZMMN3SIJU1kZFPBdAcxVD8pAsBDr6YIlxUHBTFgp0sOvDvm9vALblJpXRvgRUuXyGzDZDS1NIFa_WwIpY464owPJVG55N89JMt5Y2qUICKf4Ch5zapTubdKHYGaV2KfHG6D1KZpTMR0Y4ozKGs1__lIANJvALnVPiX-_ptKbtigeuXrfHEa6dDOAv7Bw6wNsS5zjb5UidqC7ynf_j659yh4j-7GaftLf9T2ia_vwB)
Java 17+ is required for pattern matching; this is probably the first time it is useful in a golf :).
[Answer]
# [Arturo](https://arturo-lang.io), 52 bytes
```
f:$[a][(block? a)?->([]=a)?->0->-f a\0f drop a 1->a]
```
[Try it](http://arturo-lang.io/playground?A6TCrA)
[Answer]
## C++, ~~194~~ ~~147~~ ~~141~~ 130 bytes
-17 (6+11) bytes tanks to ceilingcat
[TIO Link](https://tio.run/##lZPLboMwFET3@QpLVSVI7AY7zpOYr8gOsUAUKqS8BC6LIr49HYcmreo4TbO4Ctf4zHiuyY5H9pZlp9NTuTseKr1u8kwfqmhQ7jUpPFNTv61y/V7tSRp2Ot8dt6nO19k2rWuyifr3av26WvVb15sIO0y7VgEtVRAWh8oLy3X6UpcfueeHfs1U4aVxmfhDrxyNnsVQMO6HXyp12F3dZBDJKx0Ndmm59/x2QPAbj8kmrzXBYk5inpybPx1APGq4ankXntd6iFd4DfeVgtLgBoe5QEK1zCYJkJgDxalwsCYwRYUFm1xgpn0DKGhApQMpVXtetqAS0JnLIHM5nBqHzLY4BW1ym4YRJEQRbgF/w6NmplpMxYLP3GOBVyISSmJJySJJHtCYGw2ETFtJF7bW/M5BGMRwD6hJHKqPqC2ghm24IRRzELbeAnqBQ89EZ8QSU2NpKs74h@5dP3C0hCOTMvx0KK1EQQ62s@WdJK6xIwj5Hb@xyfCXnXsmrktauFD/8N17bXhgvPbDElReRgbTEGHmGRJ9sriS9gl4YD6cJc7QnT4B)
This code uses templates to have any kind of vectors as input ( `vector<int>`, `vector<vector<int>>`, `vector<vector<vector<int>>>` ... )
The code :
```
#import<vector>
int f(int a){return a;}template<class T>int f(std::vector<T>a){int s=0,i=1;for(auto x:a)s-=f(x)*(i*=-1);return s;}
```
Here's the code for testing :
```
int main() {
// Test case [1]
std::vector<int> v1 = { 1 };
assert(f(v1) == 1);
// Test case [-1]
std::vector<int> v2 = { -1 };
assert(f(v2) == -1);
// Test case [1,2]
std::vector<int> v3 = { 1,2 };
assert(f(v3) == -1);
// Test case [2,0,4]
std::vector<int> v4 = { 2,0,4 };
assert(f(v4) == 6);
// Test case [1,-2]
std::vector<int> v5 = { 1,-2 };
assert(f(v5) == 3);
// Test case [[1]] = 1
std::vector<std::vector<int>> v6 = { {1} };
assert(f(v6) == 1);
// Test case [[1, 2], [4, 8]]
std::vector<std::vector<int>> v7 = { {1,2}, {4,8} };
assert(f(v7) == 3);
// Test case [[-1, -1], [2, 2]]
std::vector<std::vector<int>> v8 = { {-1,-1},{2,2} };
assert(f(v8) == 0);
// Test case [[[[1], [2]], [[4], [8]]]] 3
std::vector<std::vector<std::vector<std::vector<int>>>> v9 = { {{{1},{2}},{{4},{8}}} };
assert(f(v9) == 3);
// Test case [[[1, 2], [2, 4], [4, 8]], [[-4, -4], [-1, 1], [2, -2]]]
std::vector<std::vector<std::vector<int>>> v10 = { {{1,2},{2,4},{4,8}},{{-4,-4},{-1,1},{2,-2}} };
assert(f(v10) == -9);
}
```
[Answer]
# [Uiua](https://uiua.org), 9 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
⍥(/-⇌)⧻△.
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4o2lKC8t4oeMKeKnu-KWsy4KZiBbMV0KZiBbwq8xXQpmIFsxIDJdCmYgWzIgMCA0XQpmIFsxIMKvMl0KZiBbWzFdXQpmIFtbMSAyXSBbNCA4XV0KZiBbW8KvMSDCrzFdIFsyIDJdXQpmIFtbW1sxXSBbMl1dIFtbNF0gWzhdXV1dCmYgW1tbMSAyXSBbMiA0XSBbNCA4XV0gW1vCrzQgwq80XSBbwq8xIDFdIFsyIMKvMl1dXQojIDEgYDEgYDEgNiAzIDEgMyAwIDMgYDkK)
Similarly to BQN and K, alternating sum in Uiua requires a reverse before reduction by subtraction. Uiua doesn't have "converge" builtin, and "do while" isn't a good fit here because getting the iteration count directly is cheap.
```
⍥(/-⇌)⧻△. input: a possibly multidimensional array
⧻△. keep input and push number of dimensions
‚ç•( ) repeat that many times:
/-‚áå alternating sum over the leading axis
```
[Answer]
# [Julia 1.0](http://julialang.org/), 24 bytes
```
!x::Int=x
!x=!foldr(-,x)
```
[Try it online!](https://tio.run/##pZDBasQgEIbvPsUYyqKgoaY5tAv21kMPfQLJwTQuuIgbTHYRSp89dRq6vXZTD4OMfP984/EcvFV5WWje71/jrDOhWdPDKQyJSZH5Qg6nBB58hOTsEHx0E@MEyrGiBw3uYkPN3txs69GmydVsGoOfmReQKvhoxGfF@QqMycc5RGZBPwO1a5NaoBp62O2u79VLHt377Aa46ytOXBwWozrYehQxcjsuC64ENN2/cLmRfyCmrN5t33x1F2BaAY@3BeFsie4K@QZzbuDvC43uiHZYTYu1OPwlBWdf1cvo9ncFjJLlKr97KPjjVz55zZZPXw "Julia 1.0 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
⊞υθFυFΦι⁺⟦⟧κ⊞υκF⮌υ⊞ι↨E⮌ιΣ⁺⟦⁰⟧⊟ι±¹Iθ
```
[Try it online!](https://tio.run/##PYzNDoIwEITvPMUet0mbCOFgwk0Tb5pGjw2HhlRpQIH@8Pp1QXAuuzO73zStds2g@5Rk9C1GDhOrsufgACODdV5sH4xDy0H20aOqOXSMMdiBbgfuZjbOGwK3IyEnTcFVj/@jZRwe8Y2/rgOVyWGklFF@My8dDOZkqkw6@wl41j7gRD4lRco5FISogkO5zJLDsV4WJWgVayboKd@eRFGTkpj7Lw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υθFυFΦι⁺⟦⟧κ⊞υκ
```
Get all of the sublists of the input.
```
F⮌υ
```
Loop over the sublists in reverse, i.e. from deepest back up to the original input.
```
⊞ι↨E⮌ιΣ⁺⟦⁰⟧⊟ι±¹
```
Remove all the elements of the sublist in reverse order, convert them from integers or sublists to integers, then interpret them as base `-1` to obtain the alternating sum, and push the result back to the sublist.
```
Iθ
```
Output the final result.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"ИÊi®δ.V}.«-"©.V
```
As always, 05AB1E and recursive functions are not a good match..
[Try it online](https://tio.run/##yy9OTMpM/f9f6fCE03MOd2UeWndui15Yrd6h1bpKh1bqhf3/Hx0dbahjFKsTbaRjAiRNdCxigVS0romOLoiva6hjCJbUNYqNjQUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/pcMTTs853JV5aN25LXphtXqHVusqHVqpF/Zf5390tGGsjkK0Lpg01DECUUY6BjomEL4uWMBcx1DHTEfXBMoFaoFQIOXRJjoWEK4uUDnQGKB2I4gA2OxoECc6GmheNFAdVAKi0whkC1Q/UDvQeBAfaAzEFKBlQAAA).
**Explanation:**
```
"..." # Create the recursive-string explained below
© # Store it in variable `®` (without popping)
.V # Evaluate and execute it as 05AB1E code
# (after which the result is output implicitly)
#
Ð # Triplicate the current list
Àú # Flatten the top copy
Êi # If the top two lists are NOT equal (so there is an inner list):
δ # Map over each inner item:
® .V # Do a recursive call
} # After the if-statement, whether we've executed it or not
.¬´ # Right-reduce the list by:
- # Subtracting
```
[Answer]
# [Factor](https://factorcode.org/), 73 bytes
```
: f ( s -- n ) dup array? [ [ 0 ] [ unclip f swap f - ] if-empty ] when ;
```
[Try it online!](https://tio.run/##XZAxD4IwEIV3fsUbdaiRhsHg4GhcXIyTcWiwKBFrbUsIIfx2PAqo2Da9d/eu3yVNReKepj0edvttDGGMqCzu0iiZw8pXIVUiLR7C3aCNdK7SJlMO62C3j3F95mkbI8UMFoxBYY5LoXvMBifaS5zpLlSSZ5oabSm6wKiapUw@tKtIljepsG7rALRqhGgGxb4yBP9oTtjox2Ffy7@eZORRjLCa1IncwT2MT5yRUfd1n0c@esJf78jnQ88wp58Rdafpp41IxgdGEwQn@oozfa6GdSK5L9o3 "Factor – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ŒJ’§-*ḋF
```
[Try it online!](https://tio.run/##y0rNyan8///oJK9HDTMPLdfVerij2@3/4XbNyP//ow1jdaJ1QYShjhGQNNIx0DEB83RBXKA0mATLmehYgHm6QElDsFojMD8abAiEDdILVAURhxlpgqzZREfXBGynDsQMoD0w1SAxHagEnA2yC2orQkAHRTXEibh1xwIA "Jelly – Try It Online")
```
ŒJ Enumerate the multidimensional indices of every element, in flat order.
’ Decrement each dimension (indexed from 1) of each index.
§ Sum each index,
-* and raise -1 to the power of each sum.
ḋF Take the dot product of that with the flattened input.
```
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes
```
߀ŒḊ¡U_@/
```
[Try it online!](https://tio.run/##y0rNyan8///w/EdNa45Oerij69DC0HgH/f@H2zUj//@PNozVidYFEYY6RkDSSMdAxwTM0wVxgdJgEixnomMB5ukCJQ3Bao3A/GiwIRA2SC9QFUQcZqQJsmYTHV0TsJ06EDOA9sBUg8R0oBJwNsguqK0IAR0U1RAn4tYdCwA "Jelly – Try It Online")
```
߀ Recur on each element of the argument
¬° as many times as
ŒḊ its depth.
U Reverse the list of results (or do nothing to the scalar argument)
_@/ and left-reduce by reversed subtraction.
```
Previous solution was `߀NÐeSµ)Ƒ¡`. Gaze upon it and despair.
[Answer]
# JavaScript (ES6), 46 bytes
```
f=a=>1/a?+a:a.map(n=>p-=(a=-a)*f(n),p=0,a=1)|p
```
[Try it online!](https://tio.run/##rdKxDoIwEAbg3afo2GoPKBKjJsUHIR0uCEaD0Ihx8t2RE2UAiUro0DQdvvx/rye8YRlfjvYKebFPqirVqEPl4m6BW3TOaHmuQwuaowYU85TnQlrtSdRK3G0VF3lZZImTFQee8kgZNmYJwVyXqVlHg3Fco0GPU5L5ZjrOl8yTLDCjuNWHcDAiXaMtu1o9CDPdHJqXkywKJFv/Dg9lA@qqyPPJNf9oXk@jrkQZ2qOA9jrjN3UoW1vVp9G2lYmG@gjPOyrwzl8PzZjXF9lUDw "JavaScript (Node.js) – Try It Online")
Or **43 bytes** with optional chaining (ES11), as suggested by @MatthewJensen:
```
f=a=>a.map?.(n=>s-=(a=-a)*f(n),s=0,a=1)?s:a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ndMxDoIwFAbgwc3BM3RstQ8oEoMmhYOQDo2KC4IJehoXBj2UnkaeFQaQiGVoSBO-_H8fvd7yYrevqvvlnEL4WKRSy0g7R32KHZrLqARJtQTN5inNGS-lx7UULC432nzynMy2RV4W2d7JigNNaSIUsXkYI65LxLSjgR1nNOhxghPfAhzifE48ToJ_RcOtvoQDi3RGW3a1ehA2RzcwB3NynCQBJ-F4eCgbYFeBno_uSM9oXk_DrkgpXJMA1zrjL3UoW1vVx9G2lZGG-hXee1igyV8PTanPL7I216K5US8)
[Answer]
# [J](http://jsoftware.com/), 7 5 bytes
```
-/^:_
```
[Try it online!](https://tio.run/##VY1BCsIwEEX3nuIjhRpIYzMNYgNdCa5ceQBnIRbpxvuv4iRTSkomiz@P/2ZJR9fOmCJaWPSI8juH2/NxT935FTmZw@f9/cFjwgzrNfEaeZ89SPOlRBJZ0MWwcqadzvkak7wmSxBwVdBXQI5whlR3TuIAGdgotq3Go8IB1JSKGAUaG/OGA/L4coop/QE "J – Try It Online")
*-2 thanks to Bubbler*
Just a J translation of the APL answer, for completeness.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 66 bytes
```
lambda n:n*0==0and n or sum((1-i%2*2)*f(e)for i,e in enumerate(n))
```
[Try it online!](https://tio.run/##pZLPToQwEMbvfYq5mLab1lCWw4rhSbocqpTYBErDH6NPjzOL6NVFDg2dye@bb5ovfc5vQzxf0ri21XXtXP/SOIhlPGVVlbnYQIRhhGnphTA6POSnXJ5a4WWL1aA8hAg@Lr0f3exFlHINMS3zBBVwzpk1NRz9DLP6OK4RNwry@l@4PsifmcXV6@Obb94V2ELB5T4hmq3JuyE@J507@Axp8k5oTact6EQPf1Gh2T/WcXTxuwJJafzVtxoZ3P3hI2/a@olhaKwp0frjlLowC36NXLJb2GKisG3xKhmGDwZMmXVAXffd2zEALiG04GoGaQxxFv7ddSJIBbzkCtr9ToVn8B/Jv86@odYg1y8 "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 108 bytes
```
\d+(?<=((])|(?<-2>\[)|(?(2).|((,)|.)))*)
$#4$*-$&
--
O^`-?\d+
(-)|\d+|.
$*1$1
1>`-
(1+)-\1
-
r`(1*)-?$
$.1
```
[Try it online!](https://tio.run/##VY2xDsIwDER3f0UkArLbuMJRBgagIyMfkAYVCQYWhoox/17sIpBYzs6782W6vx7P67zG0zgPtxb7/QGxUNWF43HItmGkriIGqh0RNQR@lXzDfgPMAOfLyL2eAjJVnbUD34gXkOOoNkpLPAgwTCNKQ9x78J3Mc5YCmU0kuKgjBrcNLn0AG9HIouYHl1NwuwWwBcRQNMuQZe1dTHMy1ezfebTyX43FWFdemDV@C/XrUt4 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\d+(?<=((])|(?<-2>\[)|(?(2).|((,)|.)))*)
$#4$*-$&
```
Negate each value a number of times given by the sum of its multidimensional indices.
```
--
```
Simplify any double negations.
```
O^`-?\d+
```
Sort the negative numbers to the end.
```
(-)|\d+|.
$*1$1
```
Convert the values to unary but delete everything else that isn't a `-`. This sums the positive values together.
```
1>`-
```
Sum the negative values together.
```
(1+)-\1
-
```
Take the difference between the positive and negative values.
```
r`(1*)-?$
$.1
```
Convert to decimal, ignoring any trailing `-`.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 6 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
-´⚇1⍟≡
```
`-´` alternating sum
`‚öá1`‚ÄÉat depth 1 (simple lists)
`⍟≡` repeated as many times as the depth of the argument
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkC3CtOKahzHijZ/iiaEKRiDin6jin6jin6gxLDLin6ks4p+oMiw04p+pLOKfqDQsOOKfqeKfqSzin6jin6jCrzQswq804p+pLOKfqMKvMSwx4p+pLOKfqDIswq8y4p+p4p+p4p+p)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes
```
λ∑u$e;€f?fÞ•
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu+KIkXUkZTvigqxmP2bDnuKAoiIsIiIsIltbWzEsIDJdLCBbMiwgNF0sIFs0LCA4XV0sIFtbLTQsIC00XSwgWy0xLCAxXSwgWzIsIC0yXV1dIl0=)
This is like, really, really, really bad.
[Answer]
# [Scala](http://www.scala-lang.org/), 100 bytes
Golfed version. [Try it online!](https://tio.run/##fU89a4QwGN79Fe@YtEk5xeHQRuhYSKej03GUaNVGNLZJOCjib7dRi8hVmyV5PnliMlGLoU2rPLPwIqSCzvOuooYiOuVf57cLS56VBTYIlnRXoZEhDWboQKiP46LVSD5SgbuGAW1iCY2w2UeXCZNDFfFWlSwx96y5qx5s63riSUmX6kkrUIr7PjZxPwC854UrkQoJXZoInrQW3@eT1VKVFxzBq5JujNsI7nw61tYKFcj1IZ9jjDd4uif4nAQ7UsDJgZNwP0j3ksuSfZGACxMYQcjJ8T8zHd3jB2Z78Lt4yz5RAKvnDZjh2HVDucqFWYkb4fBv@LgOe@t7ntl7vTf8AA)
```
a=>{var(s,m)=(0,-1);for(i<-a){m= -m;i match{case j:Long=>s+=m*j.toInt;case b:Seq[_]=>s+=m*f(b)}};s;}
```
Ungolfed version. [Try it online!](https://tio.run/##hVDLToQwFN33K86yVTADYTEhYuLSpK6MK2NMRUDIUExpTIzh27FAeWVg3FDOPY/e0zoWJ9G21XuRxBqPIpf4JcBHkiKlIsS9UuLn5e2VhXiQGlHPAt9CoTboMKHSINfrYVop0By3LgSzegx8aUGOUuj4cyKBWNQJihC8khmiOxN@HRnPFYobXZmb10Kh1LzaSm6WVopZdUPmb026P1utND2NMKvHlCetcpl1LZ9lPtf8MlN9kjSlvYx6nDG2ybj7lMcdf5f0uXPgTnDJ7O67F1tdFjgwIc5QlgbcOf5ncTtPV2o0@bbFtsk@@AqcwXHQpZ4NTfg0W9A7EcFWxHEZQZbnsHZDGtK2fw)
```
object Main {
def f(a: Array[_]): Int = {
var s = 0
var m = -1
for (i <- a) {
m = -m
i match {
case j: Long => s += m * j.toInt
case arr: Array[_] => s += m * f(arr)
}
}
s
}
def main(args: Array[String]): Unit = {
println(f(Array(1L)))
println(f(Array(-1L)))
println(f(Array(1L,2L)))
println(f(Array(2L,0L,4L)))
println(f(Array(1L,-2L)))
println(f(Array(Array(1L))))
println(f(Array(Array(1L, 2L), Array(4L,8L))))
println(f(Array(Array(-1L, -1L), Array(2L,2L))))
println(f(Array(
Array(
Array(
Array(1L),
Array(2L)
),
Array(
Array(4L),
Array(8L)
)
)
)))
}
}
```
] |
[Question]
[
Write a function or program that takes string inputs, fully-spelled, English month names in title case: `January`, `February`, `March`, etc. (null/CR/LF terminated OK, delimited with some non-alpha character if you so choose) and either
* compares two inputs, returning a Truthy value if the second input is greater (in month order) than the first. Equal values result in a Falsey value
* or sorts an arbitrary sequence (list, delimited string, etc.) of them in chronological order
(The crux of the challenge is defining a method/expression that gives the correct lexicographical sort. Some languages might have a shorter answer with one or the other)
You cannot use any internal time parsing methods (e.g. `strptime`) to translate the month name into a number or a pre-canned mapping of month names. Use properties of the strings themselves, a parsimonious look-up table you define, or something clever.
# Example
Functioning examples, though the first is prohibited by the rules...
```
import datetime
def is_later_month(a, b):
'''
Example of prohibited code because it relies on language
features about how to parse month names
'''
return datetime.strptime(a, '%B') < datetime.strptime(b, '%B')
```
The below versions are OK though, because we code that info
```
months = {
'January': 1, 'February': 2, 'March': 3,
'April': 4, 'May': 5, 'June': 6,
'July': 7, 'August': 8, 'September': 9,
'October': 10, 'November': 11, 'December': 12,
}
def is_later_month(a, b):
"""
Returns True/False when comparing two months.
"""
return months[a] < months[b]
```
Or you could do a sorting function
```
months = {'as above...'}
def sort_months(l):
"""
Sorts list and returns it. Different input and output than the above,
but equally valid. Sorting versus comparing might be shorter in your
favorite language.
"""
return sorted(l, key=lambda x: months[x])
```
Example tests
```
assert is_later_month('January', 'February')
assert is_later_month('January', 'December')
assert is_later_month('November', 'December')
assert not is_later_month('July', 'July')
assert not is_later_month('October', 'September')
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
11ị“bMAanlseovc”iµÞ
```
This is a monadic link that takes a list as argument and sorts it. [Try it online!](http://jelly.tryitonline.net/#code=MTHhu4vigJxiTUFhbmxzZW92Y-KAnWnCtcOeCuG6isOHauKBtyAgICAgICAgICAgICAgICAgIOG4t-KAnCDhuoogc2h1ZmZsZXMgdGhlIGxpc3QsIMOHIGFwcGxpZXMgdGhlIGxpbmssIGrigbcgam9pbnM&input=&args=IkphbnVhcnkiLCAiRmVicnVhcnkiLCAiTWFyY2giLCAiQXByaWwiLCAiTWF5IiwgIkp1bmUiLCAiSnVseSIsICJBdWd1c3QiLCAiU2VwdGVtYmVyIiwgIk9jdG9iZXIiLCAiTm92ZW1iZXIiLCAiRGVjZW1iZXIi)
### Background
Jelly uses modular, 1-based indexing. If we repeat the months names often enough to obtain 11 characters, we get the following array.
```
J a n u a r y J a n u
F e b r u a r y F e b
M a r c h M a r c h M
A p r i l A p r i l A
M a y M a y M a y M a
J u n e J u n e J u n
J u l y J u l y J u l
A u g u s t A u g u s
S e p t e m b e r S e
O c t o b e r O c t o
N o v e m b e r N o v
D e c e m b e r D e c
```
In the 11th (last) column, all characters are different, so we can use them to identify the order of the months.
### How it works
```
11ị“bMAanlseovc”iµÞ Monadic link. Argument: A (array of months)
µ Combine the preceding chain into a link.
Þ Sort A by that link.
11ị Select the 11th character of the month's name.
“bMAanlseovc” Find the index of that character in "bMAanlseovc".
For 'u' ("January"), this returns 0 (not found).
```
[Answer]
# x86 machine code, 26 25 bytes
Hexdump:
```
ff 32 8b 01 34 c0 68 30 5f 43 01 59 f7 e1 91 5a
80 f2 c0 f7 e2 3b c8 d6 c3
```
Assembly code:
```
push dword ptr [edx];
mov eax, [ecx];
xor al, 0xc0;
push 0x01435f30;
pop ecx;
mul ecx;
xchg eax, ecx;
pop edx;
xor dl, 0xc0;
mul edx;
cmp ecx, eax;
_emit 0xd6;
ret;
```
The following hash function happens to put the month names in the proper order (found by brute force):
```
(x ^ 0xc0) * 0x01435f30
```
It is applied to the first 4 bytes (32 bits) of the input string, arranged in little-endian order. Then comparing the result and using `SALC` to set the result register (al):
* -1 (true) if the months are in order
* 0 (false) if the second month precedes the first month (or they are the same)
[Answer]
## [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Oḅ32 354*%991µÞ
```
No online interpreter link here because this is one *slow* submission. The program uses the hashing function `354^(input interpreted as base 32 int) % 991` as the sort key, which happens to give outputs in the right order. The program won't finish any time soon because the results of the exponentiation are giant - for "September", a number with 0.24 quadrillion digits needs to be calculated!
Jelly explanation:
```
Þ Sort by...
µ Monadic link consisting of...
O Convert month string to code points
ḅ32 Take base 32
354* Perform 354 to the power of the result
%991 Take modulo 991
```
Python proof of concept script - note the use of `pow` for modular exponentiation, which is much more efficient:
```
import random
def base_convert(string, base):
total = 0
for c in string:
total = total * base + ord(c)
return total
def month_hash(month):
return pow(354, base_convert(month, 32), 991)
months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"]
random.shuffle(months)
print(months)
print(sorted(months, key=month_hash))
```
[Answer]
# Python, ~~64~~ ~~61~~ 57 bytes
```
lambda x,y,g='bMAanlseovc'.find:g((x*4)[10])<g((y*4)[10])
```
The lambda takes two months as input and compares them. Test it on [Ideone](http://ideone.com/deFYC2).
*Thanks to @ljeabmreosn for golfing off 3 bytes and paving the way for 3 more!*
[Answer]
## Python, ~~81~~ 71 bytes
```
lambda x,y,m='anebarprayunulugepctovec':m.index(x[1:3])<m.index(y[1:3])
```
<https://repl.it/CluN/1>
Compares the index in `m` of the second and third letters of two months.
83 byte version to sort a list of months:
```
lambda x:sorted(x,key=lambda i:'JanFebMarAprMayJunJulAugSepOctNovDec'.index(i[:3]))
```
[Answer]
# [Julia 1.0](http://julialang.org/), 28 bytes
```
~m=hash("lWbAj"*m)
m^n=~m<~n
```
[Try it online!](https://tio.run/##dcwxa8MwEIbhXb9CvUlqJ3c0McTQekumQIcmhnNRqjPSOUh2my7@646dYhcK3u69D566c4TJdRh6n1mMVoF7q/IaHr0WvuSs95uehy4Sf8oXbE2UQlwCcavgELrWkompBC220TbfEp1T777h1jJ6o0iXf1FreW6CJEkskzR5vlc9FT1NfdIzXKCLd/cf/KBW6VU7SWmEf2XHCo78ekV/cSO/4JCPs4MS9s2X8ZUJMA@FqUKH4WfclnPedji9dxg@LIjhBg "Julia 1.0 – Try It Online")
This solution prepends a string to each month before calculating the hash. The magic values in this and the other solutions were found by brute force.
## Simple hash, 29 bytes
```
~m=hash(m)%69675331
m^n=~m<~n
```
[Try it online!](https://tio.run/##dczBa8IwFMfxe/6KLCAkeIqyjpUJCurNnXbbVnhKZl5JXiVptbv0X@/ajnYw8Pa@7wefvHIIum7bxq8sRCu9miXPydPjcqmZz2jV@JeG2ioinfkWShM5Y5eAVErxFqrSookpF4qtoy1uHJyT776g0hJ4I1Flf5Er/lUEjhyJ61Qvhsr7wnnfn2qE9@Di4P6DH@Rd@q6tU@zgX9mRFB@0q8FfXMdPuNh0sxOZeC2uxh9NEOOwN8dQQfjutukctwP07wOEkxWs/QE "Julia 1.0 – Try It Online")
## String repetition + modulo, 29 bytes
```
~m=hash(m^69)%22670
m*n=~m<~n
```
[Try it online!](https://tio.run/##dcwxa8MwEIbhXb9CEQQkd6k9pMQk0ELjzZ26JSmcg1Kdkc5Bstt08V93bQe7UMh2733wlI1FiK9d17qtgWCk@1it1TJJVk@PzEW0bd2mpa4JSJ/8FWodOGMXj1RL8e6b2qAOKReKPQdTfXOwVu5dRbUhcFqiiv6iVPxceY4cicdpnIxVDoUPQx/VBGdgw@j@gxfyLn3XjlPs4ZtsSYoD7a7gLrbnZ1y89LMVkXirvrQrtBfTkOnCN@B/@m0@py2H4Z2DPxnBul8 "Julia 1.0 – Try It Online")
[Answer]
# Ruby, 58 bytes
Uses the month sorting trick from [@atlasologist's answer](https://codegolf.stackexchange.com/a/89455/52194).
```
->a{a.sort_by{|i|"anebarprayunulugepctovec".index i[1,2]}}
```
The comparison function is a bit longer, at **63 bytes**
```
->a,b{m=->i{"anebarprayunulugepctovec".index i[1,2]};m[a]<m[b]}
```
[Answer]
# J, ~~66~~ 65 bytes
Uses the fact that f(m) = 2\*(ord(m[0])+ord(m[-1]))//len(m) is a valid function in the limited domain of the 12 months:
```
>/@:('7/HEäWa<+0'&i.@(3 :'u:<.(#>y)%~+:+/3&u:({.>y),({:>y)')"0)"1
```
Usage:
```
bigger =: >/@:('7/HEäWa<+0'&i.@(3 :'u:<.(#>y)%~+:+/3&u:({.>y),({:>y)')"0)"1
bigger ('May'; 'March')
1
bigger ('May'; 'June')
0
```
(By no means is this the best idea, but I didn't want steal anyone's ranking trick!)
Here is a shorter version using *@atlasologist's* method:
### J, 63 bytes
```
m=:[:}.3{.]
[:>/(12 2$'anebarprayunulugepctovec')i.([:m[),:[:m]
```
Usage:
```
bigger =: [:>/(12 2$'anebarprayunulugepctovec')i.([:m[),:[:m]
'January' bigger 'May'
0
'June' bigger 'May'
1
```
And a much shorter version using *@Dennis's* clever method:
### J, 34 bytes
```
>&:('ubMAanlseov'&i.@:{.@:(10&|.))
```
[Answer]
# Haskell, 74 bytes
My first code golf, yay! The general idea of this one is inspired by the top answer in Jelly, and the fact that when the month names are cycled, the 11th character is always unique.
```
e s=head.drop 10$cycle s;a#b=elem(e b)$tail$dropWhile(/=e a)"ubMAanlseovc"
```
Here is an ungolfed version to see how it works:
```
order :: String
order = "ubMAanlseovc"
eleventhChar :: String -> Char
eleventhChar
= head . drop 10 $ cycle
inOrder :: String -> String -> Bool
inOrder m1 m2
= elem (eleventhChar m2) (tail $ dropWhile (/= eleventhChar m1) order)
```
The `e` function represents the eleventhChar function (sadly can't strip off 4 bytes due to the monomorphism restriction I think) and the `#` infix function corresponds to the `inOrder` function.
A neat little solution, but there may be ways of shaving off more bytes (I found some just while writing this!)
[Answer]
# Java, ~~133~~ 123
Golfed:
```
boolean f(String a,String b){return h(a)<h(b);}int h(String s){return"anebarprayunulugepctovec".indexOf(s.substring(1,3));}
```
I was searching for a clever technique like in the assembler answer, but it was taking too long to figure out so I went with the same technique everyone else used.
Ungolfed:
```
import java.util.Random;
public class SortTheMonthsOfTheYear {
public static void main(String[] args) {
// @formatter:off
String[] MONTHS = new String[] {
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
};
// @formatter:on
Random r = new Random();
for (int i = 0; i < 100; ++i) {
int m1 = r.nextInt(MONTHS.length);
int m2 = r.nextInt(MONTHS.length);
System.out.println("Input: " + MONTHS[m1] + " < " + MONTHS[m2]);
System.out.println("Expected: " + (m1 < m2));
System.out.println("Actual: " + new SortTheMonthsOfTheYear().f(MONTHS[m1], MONTHS[m2]));
System.out.println();
}
}
// Begin golf
boolean f(String a, String b) {
return h(a) < h(b);
}
int h(String s) {
return "anebarprayunulugepctovec".indexOf(s.substring(1, 3));
}
// End golf
}
```
[Answer]
# ARM machine language on Linux ~~44~~ 40 bytes
```
e28fc001 add ip, pc, #1
e12fff1c bx ip
6803 ldr r3, [r0, #0]
6808 ldr r0, [r1, #0]
4a05 ldr r2, [pc, #20]
f08303dd eor.w r3, r3, #221
f08000dd eor.w r0, r0, #221
4353 muls r3, r2
4350 muls r0, r2
4283 cmp r3, r0
bfac ite ge
2000 movge r0, #0
2001 movlt r0, #1
4770 bx lr
2f68f24c
```
I used a different hash function than [anatolyg](https://codegolf.stackexchange.com/users/25315/anatolyg)'s [solution](https://codegolf.stackexchange.com/a/89541/52904) and tried to use thumb instructions to save a few bytes (though I blew 8 bytes entering thumb mode).
You can try this out on a Raspberry Pi or Android device with GNURoot.
```
int main(int argc,char**argv){
return ((int(*)(char*,char*))"\
\1\xc0\x8f\xe2\
\x1c\xff\x2f\xe1\
\3\x68\x8\x68\
\5\x4a\x83\xf0\
\xdd\3\x80\xf0\
\xdd\x43\x53\x43\
\x50\x4a\x83\x42\
\xac\bf\0\x20\
\1\x20\x70\x47\
\x4c\xf2\x68\x2f\
")(argv[1],argv[2]);}
```
To run enter something like
```
$ ./foo January February; echo $?
```
The current version now handles the equality case (and others) correctly.
[Answer]
# [Perl 6](http://perl6.org), 55 bytes
```
*.sort({index 'anebarprayunulugepctovec',.substr(1,2)})
```
It would require a few more bytes for the comparison versions:
```
{[<] @_».&{index 'anebarprayunulugepctovec',.substr(1,2)}}
{[<] .map: {index 'anebarprayunulugepctovec',.substr(1,2)}}
```
# Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
my @months = <
January February March April May June July
August September October November December
>;
my &month-sort = *.sort({index 'anebarprayunulugepctovec',.substr(1,2)});
plan 100;
for ^100 {
# 「.pick(*)」 returns all elements in random order
is-deeply month-sort(@months.pick(*)), @months.List;
}
```
[Answer]
## Haskell, 118 characters
```
data M=Ju|Fr|Mc|Ai|My|Je|Jy|Au|St|Oo|Ne|De deriving(Ord,Eq,Read)
r=read.([head,last]<*>).lines.take 4
a#b=(r a::M)<r b
```
Uses the fact that each month name is unique in its first and fourth characters (or 3rd for May) to define a data type that can be automatically parsed and compared by the language. The 'r' function converts a string by grabbing the first four characters (or fewer), then just picking the first and last. Then 'a#b' is an operator to compare the values:
```
*Main> "June" # "March"
False
*Main> "June" # "July"
True
*Main> "January" # "July"
True
*Main> "January" # "November"
True
*Main> "December" # "November"
False
```
Could probably be done in a more efficient way, but I wanted to try doing it using a useful data type to represent the months.
[Answer]
# PowerShell, 96 88 63 bytes
```
$input|Sort{'anebarprayunulugepctovec'.IndexOf((-join$_[1,2]))}
```
e.g.
```
PS C:\Code> 'February', 'January', 'December', 'April' | .\monthsort.ps1
January
February
April
December
```
---
Now does the second challenge of sorting a list into order; previous versions did the comparison of two month test:
```
v2.
$l,$r=$args|%{-join$_[1,2]};($d='anebarprayunulugepctovec').indexof($l)-lt$d.IndexOf($r)
v1.
$l,$r=$args|%{-join$_[1,2]};$r-match('an|eb|ar|pr|ay|un|ul|ug|ep|ct|ov|ec'-split$l)[1].Trim('|')
e.g.
PS C:\code> .\Test-MonthsInOrder.ps1 January February
True
```
Based on the second two characters in the month name.
[Answer]
# Python 83 82 bytes
```
lambda x,y,m=(lambda a:'2&9<@FD6A?L%'.find(chr(sum(map(ord,a[:3]))%77))):m(x)<m(y)
```
Test: <https://repl.it/repls/TimelyDecimalBrowsers>
Gets the sum of the first 3 chars and creates a single char to search.
[Answer]
# awk, 73 bytes
```
function __(_){return index("=anebarprayunulugepctovec",substr(_,2,2))/2}
```
The full function, for any `awk` and any locale setting, **73 bytes**
```
echo -n 'function __(_){return index("=anebarprayunulugepctovec",substr(_,2,2))/2}' |
gwc -lcm
0 73 73
```
The core components only, **50 bytes**
```
echo -n 'index("=anebarprayunulugepctovec",substr(_,2,2))/2' |
gwc -lcm
0 50 50
```
This is better than the shorter trick involving the 11th letter, because that one requires all inputs to be full length names. this one works for ***both*** 3-letter abbreviated ones and their full length counterparts
[Answer]
# Javascript, 118 bytes
```
u=p=>{p=p.split` `.sort();c=[];for(i=0;i<12;i++){c.push(p["4 3 7 0 8 6 5 1 11 10 9 2".split` `[i]]);}return c.join` `}
```
Could be golfed more, probobly by getting rid of `c` and using `array.map`, but this is what I have for now...
[Answer]
# Bash, 101 bytes
this is function like is\_later
```
f(){ s=ubMAanlseovc a=$1$1$1 b=$2$2$2 c=${a:10:1} d=${b:10:1} e=${s%$c*} f=${s%$d*};((${#e}<${#f}));}
```
test
```
$ f January December && echo later || echo not later
not later
```
[Answer]
# k4, 29
```
{x@<"ubMAanlseovc"?(*|11#)'x}
```
A port of [*@Dennis's* Jelly answer](https://codegolf.stackexchange.com/a/89464/14217).
This is the sorter, not the comparator; interestingly, the comparator is trivially implementable by the same algorithm, and only one byte longer:
```
{(<)."ubMAanlseovc"?(*|11#)'x}
```
[Answer]
# Bash + coreutils, 94 bytes93 bytes
```
s(){ x=FMAyulgSOND;for y;{ rev<<<${y:0:3}|tr -d -C $x|tr $x C-M;echo B$y;}|sort|cut -f2 -dB;}
```
This is an attempt to come up with a transform that sorts lexicographically. If you look closely at the transform key `FMAyulgSOND` you can see the months February through December (January becomes empty after the transform; it's pulled to top by use of 'B' as the separator). Reversing, truncating, and removing non-keyed letters allow this trick to be pulled off.
## 90 bytes using C Locale
```
s(){ x=FMAyulgSOND;for y;{ rev<<<${y:0:3}|tr -d -C $x|tr $x C-M;echo \␉$y;}|sort|cut -f2;}
```
...where ␉ is the tab character.
## 80 bytes using C Locale
```
s(){ x=anebarprayunulugepctovec;for y;{ echo ${x%${y:1:2}*}\␉$y;}|sort|cut -f2;}
```
...using @atlasolog's method. Bound to be a way to use this approach to work with more locales.
**Test/Usage**
```
s December November October September August July June May April March February January
```
outputs:
```
January
February
March
April
May
June
July
August
September
October
November
December
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 29 \log\_{256}(96) \approx \$ 23.87 bytes
```
De11AH"bMAanlseovc"AhEZZz:.AK
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZ7XVINDR09lJJ8HRPzcopT88uSlRwzXKOiqqz0HL0haqBKF9ysilYPTi0oSc1NSi1S11FQ908uyYcyvUrzUkG0S2oyXNo3sRJCFSVngBiOpemlxSUgll9-GVyVY0FRZg7YiMS80sSiSohpOWDaLTWpCCwWC3ECAA)
Port of Dennis's Jelly answer.
#### Explanation
```
De # Duplicate and map over the list
11AH # Get the 11th item of the string (1-indexed, modular)
"..." # Push the string of each month's 11th letter
Ah # Get the index in this string (January returns -1)
E # End map
ZZ # Zip with the original list
z: # Sort this list
.AK # And get the last item of each
# Implicit output
```
] |
[Question]
[
Your task: Print or return a conversion table with every byte from `00` to `ff`'s value as an unsigned integer, to its value as a signed one (using [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement)).
For example:
```
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
12 12
13 13
14 14
15 15
16 16
17 17
18 18
19 19
20 20
21 21
22 22
23 23
24 24
25 25
26 26
27 27
28 28
29 29
30 30
31 31
32 32
33 33
34 34
35 35
36 36
37 37
38 38
39 39
40 40
41 41
42 42
43 43
44 44
45 45
46 46
47 47
48 48
49 49
50 50
51 51
52 52
53 53
54 54
55 55
56 56
57 57
58 58
59 59
60 60
61 61
62 62
63 63
64 64
65 65
66 66
67 67
68 68
69 69
70 70
71 71
72 72
73 73
74 74
75 75
76 76
77 77
78 78
79 79
80 80
81 81
82 82
83 83
84 84
85 85
86 86
87 87
88 88
89 89
90 90
91 91
92 92
93 93
94 94
95 95
96 96
97 97
98 98
99 99
100 100
101 101
102 102
103 103
104 104
105 105
106 106
107 107
108 108
109 109
110 110
111 111
112 112
113 113
114 114
115 115
116 116
117 117
118 118
119 119
120 120
121 121
122 122
123 123
124 124
125 125
126 126
127 127
128 -128
129 -127
130 -126
131 -125
132 -124
133 -123
134 -122
135 -121
136 -120
137 -119
138 -118
139 -117
140 -116
141 -115
142 -114
143 -113
144 -112
145 -111
146 -110
147 -109
148 -108
149 -107
150 -106
151 -105
152 -104
153 -103
154 -102
155 -101
156 -100
157 -99
158 -98
159 -97
160 -96
161 -95
162 -94
163 -93
164 -92
165 -91
166 -90
167 -89
168 -88
169 -87
170 -86
171 -85
172 -84
173 -83
174 -82
175 -81
176 -80
177 -79
178 -78
179 -77
180 -76
181 -75
182 -74
183 -73
184 -72
185 -71
186 -70
187 -69
188 -68
189 -67
190 -66
191 -65
192 -64
193 -63
194 -62
195 -61
196 -60
197 -59
198 -58
199 -57
200 -56
201 -55
202 -54
203 -53
204 -52
205 -51
206 -50
207 -49
208 -48
209 -47
210 -46
211 -45
212 -44
213 -43
214 -42
215 -41
216 -40
217 -39
218 -38
219 -37
220 -36
221 -35
222 -34
223 -33
224 -32
225 -31
226 -30
227 -29
228 -28
229 -27
230 -26
231 -25
232 -24
233 -23
234 -22
235 -21
236 -20
237 -19
238 -18
239 -17
240 -16
241 -15
242 -14
243 -13
244 -12
245 -11
246 -10
247 -9
248 -8
249 -7
250 -6
251 -5
252 -4
253 -3
254 -2
255 -1
```
**Formatting:**
* The output doesn't have to be padded to nicely line up like it does above (just a space in between would be fine)
* The separators can be any two strings which can't be confused for the data or each other
* Any base can be used (but if using binary, `-1` would be `-00000001`, not `11111111`)
* Trailing (and/or leading) whitespace and separators are allowed
* The output must be in the correct order
* **The output must be textual; returning arrays/lists/dictionaries is not allowed**
**Valid outputs:**
(using `...` to skip over some repetitive chunks)
Zero-padded hexadecimal:
```
00 00
01 01
...
7f 7f
80 -80
81 -7f
...
fe -02
ff -01
```
Binary with `,` and `;` for separators:
```
0,0;1,1;10,10;11,11;...;01111111,01111111;10000000,-10000000;10000001,-01111111;...;11111110,-00000010,11111111,00000001
```
Negadecimal with custom separators:
```
0 The HORSE is a noble animal. 0
1 The HORSE is a noble animal. 1
...
287 The HORSE is a noble animal. 287
288 The HORSE is a noble animal. 1932
289 The HORSE is a noble animal. 1933
...
354 The HORSE is a noble animal. 18
355 The HORSE is a noble animal. 19
```
Good luck!
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + [coreutils](https://www.gnu.org/software/coreutils/), 30
```
(seq 0 127;seq -128 -1)|nl -v0
```
[Try it online!](https://tio.run/##S0oszvj/X6M4tVDBQMHQyNwaxNI1NLIAEpo1eTkKumUG//8DAA "Bash – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~54~~ ~~50~~ 47 bytes
```
i;main(){for(;i<256;printf("%u,%hhd ",i++,i));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/TOjcxM09Dszotv0jDOtPGyNTMuqAoM68kTUNJtVRHNSMjRUFJJ1NbWydTU9O69v9/AA "C (gcc) – Try It Online")
## Explanation
```
i; // Static variable initialized to 0
main() {
for(;i<256; // While the variable is <= 255:
printf("%u,%hhd ",i++,i));
// Output the original, then the char-coerced
// value. Increment after use.
}
```
# [C (gcc)](https://gcc.gnu.org/), 45 bytes
Non-portable, but 2 bytes shorter.
```
f(i){for(i=-1;i++<255;printf("%u,%hhd ",i));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI1OzOi2/SCPTVtfQOlNb28bI1NS6oCgzryRNQ0m1VEc1IyNFQUknU1PTuvZ/bmJmngZQvQaIAwA "C (gcc) – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 18 bytes
Full program printing to stdout with `¯` as negative symbol. Requires 0-based indexing.
```
(⍳∘≢,⍪)…127,-128…1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862gv@azzq3fyoY8ajzkU6j3pXaT5qWGZoZK6ja2hkAWL@B6r5XwAA "APL (Dyalog Extended) – Try It Online")
`128…1` integers 128 through 1
`-` negate those
`127,` prepend 127
`…` fill integers from 0 until the first element of that (127)
`(`…`)` apply the tacit function:
`,⍪` columnify and prepend [a column consisting of]…
`⍳⍤≢` the **ɩ**ndices of the tally
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 10 bytes
```
⁹Ḷ_H%⁹żƊṢG
```
[Try it online!](https://tio.run/##y0rNyan8//9R486HO7bFe6gCGUf3HOt6uHOR@///AA "Jelly – Try It Online")
*-1 byte thanks to Jonathan Allan*
## Explanation
```
⁹Ḷ_H%⁹żƊṢG Main niladic link
⁹ 256
Ḷ [0..255]
_ Subtract
H half (of 256) = 128 => [-128..127]
Ɗ (
% Modulo
⁹ 256
ż Zip with the list at the beginning of this inner link
Ɗ )
Ṣ Sort
G Format as a grid
```
[Answer]
# [Python 2](https://docs.python.org/2/), 37 bytes
```
for i in range(256):print i,127-i^127
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFTITNPoSgxLz1Vw8jUTNOqoCgzr0QhU8fQyFw3Mw5I/v8PAA "Python 2 – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), ~~31~~ 28 bytes
```
r=0:255
@.println(r=>r%Int8)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v8jWwMrI1JTLQa@gKDOvJCdPo8jWrkjVM6/EQvP/fwA "Julia 1.0 – Try It Online")
Output format:
```
0 => 0
1 => 1...
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₅ÝƵQݱ«ø»
```
-1 byte thanks to *@ovs*.
Uses single spaces and newlines as delimiters for the output.
[Try it online.](https://tio.run/##AR4A4f9vc2FiaWX//@KChcOdxrVRw53DgsKxwqvDuMK7//8)
**Explanation:**
```
₅Ý # Push a list in the range [0,255]
ƵQÝ # Push a list in the range [0,127]
 # Bifurcate it; short for Duplicate & Reverse copy
± # Get the bitwise-NOT of each (n → -n-1)
« # Merge the top two lists together
ø # Create all possible pairs of the [0..255] and [0..127,-128..-1] lists
» # Join each pair by spaces, and then each string by newlines
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ƵQ` is `127`.
[Answer]
# JavaScript (ES6), ~~41~~ 40 bytes
*Saved 1 byte thanks to @ovs*
Output format: `0,0 1,1 ... 255,-1`.
```
f=n=>n>>8?'':[~~n,128+~n^127]+' '+f(-~n)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7Pzs7CXl3dKrquLk/H0MhCuy4vztDIPFZbXUFdO01Dty5P839yfl5xfk6qXk5@ukaahqbmfwA "JavaScript (Node.js) – Try It Online")
Or maybe [39 bytes](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7Pzs7CXl3dKrquLk/H0MhCuy4vztDIXEdHJ1Y7TUO3Lk/zf3J@XnF@TqpeTn66RpqGpuZ/AA) or even [38 bytes](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7Pzs7CXl3dKrquLk/H0MhCuy4vztDIPFY7TTtNQ7cuT/N/cn5ecX5Oql5OfrpGmoam5n8A) by abusing the loose output format. (But it's ugly.)
### Commented
```
f = // f is a recursive function
n => // taking a counter n, which is initially undefined
n >> 8 ? // if n = 256:
'' // stop the recursion
: // else:
[ // build an array consisting of:
~~n, // the unsigned value (coerced to a number because
// it's undefined on the first iteration)
128 + ~n ^ 127 // the signed value, which is (127 - n) XOR 127
// = (128 + (-n - 1)) XOR 127
] // end of array
+ ' ' // coerce the array to a string and append a space
+ f(-~n) // append the result of a recursive call with n + 1
```
[Answer]
# [Nim](http://nim-lang.org/) `-d:danger`, 33 32 bytes
```
for b in 0..255:b.echo' ',b.int8
```
[Try it online!](https://tio.run/##y8vM/f8/Lb9IIUkhM0/BQE/PyNTUKkkvNTkjX11BXSdJLzOvxOL//3/JaTmJ6cX/dVOsUhLz0lOLAA "Nim – Try It Online")
# [Nim](http://nim-lang.org/), 40 39 bytes
```
for b in 0..255:b.echo' ',cast[int8](b)
```
[Try it online!](https://tio.run/##y8vM/f8/Lb9IIUkhM0/BQE/PyNTUKkkvNTkjX11BXSc5sbgkOjOvxCJWI0nz/38A "Nim – Try It Online")
Probably doesn't work on big-endian architectures.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
†szeŀ256Sṙohṡ128
```
[Try it online!](https://tio.run/##yygtzv7//1HDguKq1KMNRqZmwQ93zszPeLhzoaGRxf//AA "Husk – Try It Online"), [Another method](https://tio.run/##ASIA3f9odXNr///igKBz4bmgemVvzpjFgFPhuZlvaOG5oTEyOP// "Husk – Try It Online"), [Another method](https://tio.run/##ASAA3/9odXNr///igKBzwqd6ZW/FgERT4bmZb2jhuaExMjj//w "Husk – Try It Online")
## Explanation
```
†szeŀ256Sṙohṡ128
ṡ128 symmetric range of 128 [-128...128]
oh remove last element
Sṙ rotate 128 spaces
ŀ256 range [0...255]
ze zip the two, creating pairs
†s convert all the numbers to strings
(can also be mw)
```
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
```
unlines[show x++' ':show(x-x`div`128*256)|x<-[0..255]]
```
[Try it online!](https://tio.run/##y0gszk7NyflfkpiUk2ob8780LyczL7U4ujgjv1yhQltbXUHdCsTWqNCtSEjJLEswNLLQMjI106ypsNGNNtDTMzI1jY39n5uYmWdbUFoSXFLkk6cANuz/v@S0nMT04v@6yQUFAA "Haskell – Try It Online")
* Sadly `xor` is not in prelude module.
* Table is a string of pairs separated by newlines.
[Answer]
# C#, 61 bytes
Not very creative, but I think the shortest this can get.
```
for(var i=0;i<256;)System.Console.Write(i+$",{(sbyte)i++};");
```
[Try it online!](https://tio.run/##Sy7WTS7O/P8/Lb9IoyyxSCHT1sA608bI1MxaM7iyuCQ1V885P684PydVL7wosyRVI1NbRUmnWqM4qbIkVTNTW7vWWknT@v9/AA "C#– Try It Online")
This is a **complete** program thanks to C#9 and top-level statements. [SharpLab](https://sharplab.io/#v2:C4LgTgrgdgPgZgezACgG4EMwAICWBeABgG4cAeAJgFYA2IgSgFgAoLVrAAQEYA6AYQSgBnBABsAptwDqYHMDHIcAagAkAIgA0Ab2SCARgE85dJYoC+RVXSLMgA==)
[Answer]
# [R](https://www.r-project.org/), 37 bytes
```
for(i in 0:255)cat(i,i-(i>127)*256,T)
```
[Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwcDKyNRUMzmxRCNTJ1NXI9PO0MhcU8vI1EwnRPP/fwA "R – Try It Online")
Separator between converted numbers is ""; separator between each element of the list of conversions is " `TRUE`". List is appended with a trailing separator (as allowed by the challenge rules).
"`TRUE`" is a pre-defined variable in [R](https://www.r-project.org/) that can be specified by a single character, `T`, and that has non-numeric output, so it's used as a convenient golfy separator here.
---
# [R](https://www.r-project.org/), 38 bytes
```
cat(paste(0:255,c(0:127,-128:-1),'
'))
```
[Try it online!](https://tio.run/##K/r/PzmxRKMgsbgkVcPAysjUVCcZSBsamevoGhpZWOkaauqoc6lrav7/DwA "R – Try It Online"), [Another approach](https://tio.run/##K/r/PzmxRKMgsbgkVSPRRtfAysjUVCdR18jUTEsj0c7QyFxTR51LXVPz/38A)
Previous, slightly longer attempt, but with more-conventional separators (space & newline).
[Answer]
# Python 3, ~~47~~ 41 bytes
-6 thanks to @EasyasPi
```
print([(127-i^127,i)for i in range(256)])
```
[Answer]
# [Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html "Primitive Data Types - Java Tutorials"), 58 chars
```
void f(){for(int i=0;i<256;out.println(i+" "+(byte)i++));}
```
[Try it online!](https://tio.run/##NcxBDoIwFATQfU/RsGptbIyJbqqngJ1xUaGQj/DblC8JIVzd2hjdzryZ3s5274PDvnkmGIOPxCeyBDXvc6UHi50ul4ncqHeGAZKLra0dr1b2c7OHho8WUJQUAbvb3cqVtUIatv1N@qKcra2PIr9wuB4MXI6ns/Ev0iEPaUABquCFEo@FnASlpDRb2tLbBwKPU6o@ "Java (OpenJDK 8) – Try It Online")
The `byte` data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), `j`, ~~14~~ ~~9~~ 8 bytes
```
₈ʁ₇ʁḂꜝJZ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%E2%82%88%CA%81%E2%82%87%CA%81%E1%B8%82%EA%9C%9DJZ&inputs=&header=&footer=)
[OP says it's allowable](https://chat.stackexchange.com/transcript/message/56815478#56815478)
*-5 bytes due to porting 05AB1E*
## Explained
```
₈ʁ₇ʁḂꜝJZ
₈ʁ # Push range [0, 256)
₇ʁḂ # Push [0, 128) and (128, 0]
ꜝ # Bit-not over that last copy
JZ # Merge and zip
# The j flag joins on newlines
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 15 bytes
```
₈‹ʀ₇‹ʀḂN₇NpJZvṄ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%E2%82%88%E2%80%B9%CA%80%E2%82%87%E2%80%B9%CA%80%E1%B8%82N%E2%82%87NpJZv%E1%B9%84&inputs=&header=&footer=)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~49~~ ~~53~~ 51 bytes
Saved 2 bytes taking a peek at [ovs](https://codegolf.stackexchange.com/users/64121/ovs)'s [Python answer](https://codegolf.stackexchange.com/a/217621/9481)!!!
Added 8 bytes to fix a rule violation kindly pointed out by [ovs](https://codegolf.stackexchange.com/users/64121/ovs).
Saved 2 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
```
f=lambda i=255:i*' 'and'%d '*2%(i,127-i^127)+f(i-1)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIdPWyNTUKlNLXUE9MS9FXTVFQV3LSFUjU8fQyFw3Mw5IamqnaWTqGmr@LyjKzCvRSNPQ1PwPAA "Python 2 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 34 bytes
```
0..255|%{"$($_;($_-bxor128)-128)"}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30BPz8jUtEa1WklFQyXeGoh1kyryiwyNLDR1QYRS7f//AA "PowerShell – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~17~~ 16 bytes
```
V256++Nd-J127xNJ
```
[Try it online!](https://tio.run/##K6gsyfj/P8zI1Exb2y9F18vQyLzCz@v/fwA "Pyth – Try It Online")
-1 byte thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman)!
---
Python 3.8 translation:
```
for N in range(256):print(str(N)+" "+str((J:=127)-N^J))
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~29~~ 33 bytes
+4 bytes: fit to the task rules. Thanks @Zaelin Goodman
```
0..127+-128..-1|%{"$(($i++);$_)"}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30BPz9DIXFvX0MhCT0/XsEa1WklFQ0MlU1tb01olXlOp9v9/AA "PowerShell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 36 bytes
```
256.times{|i|puts [i,127-i^127]*' '}
```
[Try it online!](https://tio.run/##KypNqvz/38jUTK8kMze1uLoms6agtKRYITpTx9DIXDczDkjGaqkrqNf@/w8A "Ruby – Try It Online")
[Answer]
# AWK, ~~48~~ 45 bytes
*Lowered to 45 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/questions/217614/print-a-conversion-table-for-unsigned-bytes/217641?noredirect=1#comment507707_217641).*
```
BEGIN{for(;i<256;i++)print +i,i<128?+i:i-256}
```
[Try it online!](https://tio.run/##SyzP/v/fydXd0686Lb9IwzrTxsjUzDpTW1uzoCgzr0RBO1Mn08bQyMJeO9MqUxcoV/v/PwA "AWK – Try It Online")
Had to workaround the fact that bitwise functions in GNU AWK don't accept negative arguments. Anyway, this should work on any AWK implementation.
[Answer]
# [Scala](https://www.scala-lang.org/), ~~46~~ 45 bytes
```
()=>for(i<-0 to 255)print(s"$i,${i.toByte} ")
```
Output format: `0,0 1,1 2,2 ... 127,127 128,-128 129,-127 ... 253,-3 254,-2 255,-1` with `,` and for separators.
[Try it online!](https://tio.run/##JcxBCsIwEAXQfU/xKV3MgIoI3Ygp1L1LDzCtEUZCEppBlNKzx4XvAK/MEqSm6eVnw000wn/Mx0fBmDPWBnhLgMkU/BnEcAPuUQ2uErvhmRbSy/4ISzj1PedFo1FpO911qx4sXb/mN7Rc8T@Im63@AA)
**Edit**: Due to conventions, the String Interpolator `f` was changed to `s`. Thanks to [user](https://codegolf.stackexchange.com/users/95792/user)!
---
### 37 bytes
... if ignoring the seperator rule.
```
()=>for(i<-0 to 255)print(i,i.toByte)
```
Output format: `(0,0)(1,1)(2,2)(...)(127,127)(128,-128)(129,-127)(...)(253,-3)(254,-2)(255,-1)` with `,` and `)(` for separators, but unfortunately also with a leading `(` and trailing `)`.
[Try it online!](https://tio.run/##JcsxCsJAEAXQPqf45QxEESFNcAOmt/QAk2SEkWV3SQZRgmdfC1//tlmi1Dw9dXbcxBL07ZqWDddSsDfASyJcpqg9iBEG3JM5QiUOwyOvZJfDCZ5x7jouqyUna@3oefy4csX/Ejff@gM)
[Answer]
# [FALSE](https://github.com/somebody1234/FALSE), 37 bytes
```
0[$$$$256=~][128>[256-]?\.44,.10,1+]#
```
[Try it online!](https://tio.run/##S0vMKU79/98gWgUIjEzNbOtiow2NLOyigWzdWPsYPRMTHT1DAx1D7Vjl//8B "FALSE – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 38 bytes
```
for i in range(256):print(i,127-i^127)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFTITNPoSgxLz1Vw8jUTNOqoCgzr0QjU8fQyFw3Mw5Iav7/DwA "Python 3 – Try It Online")
[Answer]
# PHP, 64 bytes
```
<?php for($x=0;$x<256;$x++){echo$x.','.($x<128?$x:$x-256).";";}
```
```
<?php for($x = 0; $x < 256; $x++){ #Go through each number
echo $x . ',' . #Write x, then...
($x < 128 ? $x #if x is less than 128, write x again,
: $x - 256) . ";"; #otherwise write x - 256
}
```
Uses ',' and '.' as separators.
[Answer]
# [Factor](https://factorcode.org/), 43 bytes
```
256 iota [ dup pprint bl 8 >signed . ] each
```
[Try it online!](https://tio.run/##JcoxCsJAEAXQq/wTpBAiYsBWbGzESiwmm68ZjLvrzoTg6deA9XsPCZ5KvV5O5@Mexs/MGGh4sUROyIXu31w0OjThLT42vfqiRohZCoaubtrtii64YZgz8r/3E3Y4mD4jBzS4gxLGWn8 "Factor – Try It Online")
[Answer]
# [jq](https://stedolan.github.io/jq/), 30 bytes
```
range(256)|[.,(128+.)%256-128]
```
[Try it online!](https://tio.run/##yyr8/78oMS89VcPI1EyzJlpPR8PQyEJbT1MVyNcFMmP///@XX1CSmZ9X/F83DwA "jq – Try It Online")
output format:
```
[
0,
0
]
...
[
255,
-1
]
```
[Answer]
# [Red](http://www.red-lang.org), 45 bytes
```
repeat n 256[print[p: n - 1 p xor 128 - 128]]
```
[Try it online!](https://tio.run/##K0pN@R@UmhId@78otSA1sUQhT8HI1Cy6oCgzryS6wArI1VUwVChQqMgvUjA0sgDxjCxiY///BwA "Red – Try It Online")
Uses @Arnauld's formula
] |
[Question]
[
Given a list of 2 or more strictly positive integers, sum the first and last half of the list, with the middle element being counted only in the right half if the list has an odd number of elements
Some examples of the middle element being counted in the right half:
```
[1, 2, 3, 4] -> Left: [1, 2]; Right: [3, 4]
[1, 2, 3] -> Left: [1]; Right: [2, 3]
[1, 2, 3, 4, 5] -> Left: [1, 2]; Right: [3, 4, 5]
[1, 2, 3, 4, 5, 6] -> Left: [1, 2, 3]; Right: [4, 5, 6]
```
## Test Cases
### Input
```
[1, 9]
[9, 5, 5, 7]
[6, 7, 5, 1, 3, 9, 7, 1, 6]
[2, 8, 10, 9, 9, 3, 7, 8, 9, 8, 6, 1, 2, 9, 8, 3, 8, 9, 5]
[2, 3, 1, 8, 6, 2, 10, 6, 7, 6]
```
### Output
```
[1, 9]
[14, 12]
[19, 26]
[65, 59]
[20, 31]
```
[Reference Program With Two Output Methods](https://tio.run/##lZHLasMwEEX38xWDs7Go7Dy6M7SbtsuSLpJVMMGJx7HAlowsQ/z1riXl0bpQWoEQ3DtXc4ZpelMq@TgMom6UNlh08miUqlq4CDqTuaoBcirwIGSm@72mvDtSKKShE@mW@5BQkiWA46moMBy1OJUGn/BatksqkrcQw/kcVym/2z/dJHXfaTKdlri7ocUXgGtb7joyjr9UOBqWAhhqTTti7VIolEY5AtgZTxQuFws/gLS2nzu2z0gVLjlaHyeZSdWK42rBmON2jeKsaUjmoWQAM3wpbQhNSag603QGa5UTlqQphtl6u/nYbvbv69e3ESBQkqLxBjDRhRyDkc8HAKLAbwVfkn4bltiyWGjH5GV7Gm2hrcgxiKLngE9W7K0qqw95hmeOfYJnfMCeMaCqpX80YE6Du8j@lv0zj40Mwyc "Python 3 – Try It Online")
## Rules
* Input/Output can be Taken/Given in any convenient and reasonable format.
* Functions and full programs are both acceptable.
[Answer]
# [Python 2](https://docs.python.org/2/), 40 bytes
Takes as input a list \$ l \$, and outputs the two sums in reverse order (`[right, left]`).
```
lambda l:[sum(l.pop()for x in l),sum(l)]
```
## Explanation
In `sum(l.pop()for x in l)`, we pop the last element, in each iteration, and sum the popped elements. Surprisingly, the loop only runs \$ \lceil{\frac{|l|}{2}}\rceil \$ times, since for every element we iterate from the left, we are removing an element from the right, resulting in the loop terminating somewhere in the middle. Therefore it gives us the sum of the right portion of the list. The sum of the remaining elements make up the left portion.
[Try it online!](https://tio.run/##NY3dCsMgDEbv@xS5VJCxWmpnYU/SleFYSwWr0p91e3oXIgXRnO8kMf62KXiZxvsjOTO/3gZc2637zNwlhsj4GBb4gvXguKCY9@mYrBugbAuIi/UbjGz4GMcWczytj/vGOOepKwXovui0gJpOg6DwIUBZoSfEWqGTAm4IV4o1@YYiTbeiRnlidao6j1akc5/Ma/Jnqv8D "Python 2 – Try It Online")
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 41 bytes
```
lambda l:[t:=sum(l[:len(l)//2]),sum(l)-t]
```
[Try it online!](https://tio.run/##NY3RCoMgFIbvfYpzqdDWpmQZ9CTOi0bFBDMpN@jpmx0JRM/3f@ccwx4/ixdNWI@pex2un99DD67Vse2270ydbt3oqWNlyQ0rMGK3aA47h2WNsO0bIdOygrN@BOvP4L7FwfqWgIMOxl/v6CkZgbBaH@mUNrBDPwtQhmhVQIWnTiDTg5CkSB4x1TI5XkCT4IGxQl9jpPCW2MgvFJeq8qhAnft4XpM/k@YP "Python 3.8 (pre-release) – Try It Online")
Straightforward solution. Takes in a list, and returns the list of left and right sum.
---
Interesting idea that didn't go anywhere :(
### [Python 3](https://docs.python.org/3/), 45 bytes
```
lambda l,t=1j:l>[]and l[-1]+t*f(l[-2::-1],-t)
```
[Try it online!](https://tio.run/##NY3RDoMgDEXf@Yo@6obLxKiTxP0I84FFzVgQjZIlfj2rJSYEeu5py7L7z@yKMLavYPX07jVY7tv8K@1Tddr1YFWWd1d/GROshJRIPPNpMNMyrx62fWNsnFewxg1g3BHcNt8bJxlYaGH4aZscMmWwrMb5BDelaVA5h6ZjquFQ0qkRKnwIUBboCbGu0AkOD4Q7xQ35mqKG7ooaxYnFqco4WpCOfSKuiZ9V3R8 "Python 3 – Try It Online")
Returns `a+bj` where `a, b` is the right and left sum respectively.
[Answer]
# [Haskell](https://www.haskell.org/), ~~44~~ 43 bytes
```
f x=[sum$y(div(length x)2)x|y<-[take,drop]]
```
[Try it online!](https://tio.run/##PUzdCoIwFL7vKc5FFwqnaBvOBvkIPcEYMVBTdGuohULvvo4icTjw/Td27Kq@j7GGudDj2x2XpGw/SV/559TAnPJ0/i63k55sV2E5vIIx0dnWQwHOhvsDkjC0foIz1OkBQINmqAwhBK0wo8t3JjEnxlCgIsRQ7jrHK7ILiYqsnIiilxTgGxKbkv3DgpzV52tp3dx2TPwB "Haskell – Try It Online")
Based on [Steven Fontanella's answer](https://codegolf.stackexchange.com/a/204244/56656) with some non-trivial modification.
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k) / [oK](https://github.com/JohnEarnest/ok) / K4, 8 bytes
```
+/'2 0N#
```
[Try it online!](https://tio.run/##HYxRCoAwDEOvEvBjiohbxzbr7uAx5oew@//VbJTS5CX0O/rbzdq9n07gn8WaWwO0QpE4pSKjUAREosKbKwQXgqdX0kKj3MxMpoqTpNGLhCOS0R@f8mY/ "K (ngn/k) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
-@>.@-:@#+/\|.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/dR3s9Bx0rRyUtfVjavT@a3KlJmfkK6QpGCoYKRijcBRM/gMA "J – Try It Online")
Output is in reverse.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
ḍ+ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/@GOXm0Q/T862lBHwTJWRyHaUkfBFIzMQTwzIA3mAaWNgSrAXCDbDCRppKNgAeQZgMUtwQrMwUKWYNIMrNIIxjWGSZlC9RqD5SEKjSDmQKwzi40FAA "Brachylog – Try It Online")
Brachylog's cut-a-list-in-half predicate just so happens to already make the right half larger.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~6~~ 5 bytes
Outputs the two sums in reverse order (right sum, then left sum)
```
sMc2_
```
[Try it online!](https://tio.run/##K6gsyfj/v9g32Sj@//9oIx0FYx0FQx0FCx0FMx0FINfQAMwyB5KxAA "Pyth – Try It Online")
```
sMc2_
_ Reverse the input
c2 Chop into 2 equal-sized chunks, with the first chunk
one element longer if necessary
sM Sum each chunk
```
[Answer]
# Rust, 71 bytes
```
|x:&[u8]|{let s=x[..x.len()/2].iter().sum();(s,x.iter().sum::<u8>()-s)}
```
A closure that takes a reference to a slice of 8-bit unsigned numbers and returns a tuple of two 8-bit unsigned numbers.
[try it online](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=%0Afn%20main()%20%7B%0A%20%20%20%20let%20f%3D%7Cx%3A%26%5Bu8%5D%7C%7Blet%20s%3Dx%5B..x.len()%2F2%5D.iter().sum()%3B(s%2Cx.iter().sum%3A%3A%3Cu8%3E()-s)%7D%3B%0A%20%20%20%20assert_eq!((1%2C%209)%2C%20f(%26%5B1%2C%209%5D))%3B%0A%20%20%20%20assert_eq!((14%2C%2012)%2C%20f(%26%5B9%2C%205%2C%205%2C%207%5D))%3B%0A%20%20%20%20assert_eq!((19%2C%2026)%2C%20f(%26%5B6%2C%207%2C%205%2C%201%2C%203%2C%209%2C%207%2C%201%2C%206%5D))%3B%0A%20%20%20%20assert_eq!((65%2C%2059)%2C%20f(%26%5B2%2C%208%2C%2010%2C%209%2C%209%2C%203%2C%207%2C%208%2C%209%2C%208%2C%206%2C%201%2C%202%2C%209%2C%208%2C%203%2C%208%2C%209%2C%205%5D))%3B%0A%20%20%20%20assert_eq!((20%2C%2031)%2C%20f(%26%5B2%2C%203%2C%201%2C%208%2C%206%2C%202%2C%2010%2C%206%2C%207%2C%206%5D))%3B%0A%7D) on the rust playground.
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
```
f x=(\(a,b)->sum<$>[a,b])$splitAt(length x`div`2)x
```
[Try it online!](https://tio.run/##RU/NCoMwDL7vKXLwoBDHVNQVpjB29glUpkOdZbUV2w3f3kWHLCHw/SWQvtavVoiFD6OaDNyUNJMSx0zJugG7U1N2d5YO5sQu7Bofjpvq93Cx0pxI6Vh6FNxcjS1a@TQ9zFXDP5XvzMtQcwkJbAcgPwBV7iEr8QcZhtTxTiOMiXoYICPkYbQbPp7RO5HKyIuJMJqIEv6Ggk0J/@mArDXgr1vr1agswYJi1uCm0KgtN05cGlLpLb18AQ "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŻŒH§
```
A monadic Link accepting a list which yields the pair: first-half-sum, last-half-sum.
**[Try it online!](https://tio.run/##y0rNyan8///o7qOTPA4t////f7SZjoK5joKpjoKhjoKxjoIlmAtkm8UCAA "Jelly – Try It Online")**
### How?
```
ŻŒH§ - Link: list, A
Ż - prepend a zero to A
ŒH - split that in half (if the length is odd the first half gets the extra element)
§ - sums
```
[Answer]
# Rust macro, 480 bytes
```
macro_rules!f{($($r:expr)*)=>{f!(@I;[$($r),*];[];)};(@$($d:ident)*;[];[$($a:tt)*];$($b:tt)*)=>{f!(%($)0;0;[$($a)*]$($b)*)};(@$($d:ident)*;[$x:expr$(,$r:tt)*];[$($a:tt)*];$($b:tt)*)=>{f!(@I$($d)*;[$($r),*];[$($a)*;($($d)*,$x)];($($d)*,$x);$($b)*)};(%($m:tt)$s:expr;$t:expr;[;($($d:ident)+,$x:expr)$($a:tt)*]$(;)*($($e:ident)*,$y:expr)$($b:tt)*)=>{{macro_rules!i{($($d)*$m(I)+)=>{f!(%($m)$s+$x;$t+$y;[$($a)*];$($b)*)};($($d)*)=>{($s,$t+$y)};($m(I)*)=>{($s,$t)}}i!($($e)*)}};}
```
[try it online](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&code=%23!%5Bfeature(trace_macros)%5D%0A%0Atrace_macros!(true)%3B%0A%0A%2F%2F%20Define%20a%20macro%20called%20f%0Amacro_rules!%20f%20%7B%0A%0A%20%20%20%20%2F%2F%20This%20rule%20is%20the%20starting%20point%0A%20%20%20%20%2F%2F%20It%20matches%20any%20number%20of%20expressions%0A%20%20%20%20(%24(%24r%3Aexpr)*)%20%3D%3E%20%7B%0A%20%20%20%20%20%20%20%20%2F%2F%20Use%20the%20internal%20rules%20with%20an%20at%20sign.%0A%20%20%20%20%20%20%20%20%2F%2F%20Provide%20the%20I%20as%20the%20first%20index.%0A%20%20%20%20%20%20%20%20f!(%40%20I%3B%20%5B%24(%24r)%2C*%5D%3B%20%5B%5D%3B)%0A%20%20%20%20%7D%3B%0A%0A%20%20%20%20%2F%2F%20The%20rules%20starting%20with%20an%20at%20sign%20are%20responsible%20for%20producing%20a%20reversed%20version%0A%20%20%20%20%2F%2F%20of%20the%20input%20and%20counting%20with%20tallys.%0A%20%20%20%20%2F%2F%20This%20pattern%20is%20known%20as%20tt-muncher%20because%20it%20consumes%20a%20token%20tree%20recursively.%0A%0A%20%20%20%20%2F%2F%20This%20is%20the%20base%20case.%20It%20matches%20when%20the%20input%20is%20an%20empty%20set%20of%20brackets.%0A%20%20%20%20(%40%20%24(%24d%3Aident)*%3B%20%5B%5D%3B%20%5B%24(%24a%3Att)*%5D%3B%20%24(%24b%3Att)*)%20%3D%3E%20%7B%0A%20%20%20%20%20%20%20%20%2F%2F%20Call%20the%20second%20set%20of%20internal%20macros%20(the%20ones%20starting%20with%20a%20percent%20sign).%0A%20%20%20%20%20%20%20%20%2F%2F%20We%20use%20zeros%20as%20the%20accumulators%0A%20%20%20%20%20%20%20%20f!(%25%20(%24)%200%3B%200%3B%20%5B%24(%24a)*%5D%20%24(%24b)*)%0A%20%20%20%20%7D%3B%0A%20%20%20%20%2F%2F%20This%20is%20the%20recursive%20case.%0A%20%20%20%20%2F%2F%20It%20extracts%20one%20expression%20(called%20x)%20from%20the%20input.%0A%20%20%20%20(%40%20%24(%24d%3Aident)*%3B%20%5B%24x%3Aexpr%20%24(%2C%24r%3Att)*%5D%3B%20%5B%24(%24a%3Att)*%5D%3B%20%24(%24b%3Att)*)%20%3D%3E%20%7B%0A%20%20%20%20%20%20%20%20%2F%2F%20Call%20the%20at-macro%20recursively.%0A%20%20%20%20%20%20%20%20%2F%2F%20Add%20one%20I%20to%20the%20current%20tally%20list.%0A%20%20%20%20%20%20%20%20%2F%2F%20append%20(tallys%2C%20%24x)%20to%20the%20first%20%22array%22.%0A%20%20%20%20%20%20%20%20%2F%2F%20prepend%20(tallys%2C%20%24x)%20to%20the%20second%20%22array%22.%0A%20%20%20%20%20%20%20%20f!(%40%20I%20%24(%24d)*%3B%20%5B%24(%24r)%2C*%5D%3B%20%5B%24(%24a)*%3B%20(%24(%24d)*%2C%20%24x)%5D%3B%20(%24(%24d)*%2C%24x)%3B%20%24(%24b)*)%0A%20%20%20%20%7D%3B%0A%0A%20%20%20%20%2F%2F%20This%20part%20of%20the%20macro%20is%20called%20with%20the%20original%20and%20the%20reversed%20version.%0A%20%20%20%20%2F%2F%20The%20first%20argument%20is%20a%20dollar%20sign%20because%20that%20it%20needed%20later.%0A%20%20%20%20%2F%2F%20It%20extracts%20the%20count%20%24d%20and%20value%20%24x%20of%20the%20forwards%20array%2C%0A%20%20%20%20%2F%2F%20and%20count%20%24e%20and%20value%20%24y%20of%20the%20backwards%20array.%0A%20%20%20%20(%25%20(%24m%3Att)%20%24s%3Aexpr%3B%20%24t%3Aexpr%3B%20%5B%3B%20(%24(%24d%3Aident)%2B%2C%20%24x%3Aexpr)%20%24(%24a%3Att)*%5D%20%24(%3B)*%20(%24(%24e%3Aident)*%2C%20%24y%3Aexpr)%20%24(%24b%3Att)*)%20%3D%3E%20%7B%0A%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20To%20compare%20the%20two%20tally%20counters%20at%20compile%20time%2C%20we%20use%20an%20internal%20macro.%0A%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20It%20defined%20rules%20based%20on%20%24d.%0A%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20The%20argument%20of%20this%20macro%20will%20be%20%24e.%20%0A%20%20%20%20%20%20%20%20%20%20%20%20macro_rules!%20i%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20This%20case%20matches%20when%20%24e%20is%20larger%20than%20%24d.%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20That%20means%20we%20haven%27t%20found%20the%20end%20yet.%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20(%24(%24d)*%20%24m(I)%2B)%20%3D%3E%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20call%20this%20part%20recursively%2C%20adding%20%24x%20and%20%24y%20to%20their%20accumulators%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20f!(%25%20(%24m)%20%24s%2B%24x%3B%20%24t%2B%24y%3B%20%5B%24(%24a)*%5D%3B%20%24(%24b)*)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20%24e%20and%20%24d%20are%20equal.%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20This%20case%20is%20reached%20when%20there%20is%20an%20odd%20number%20of%20element%20in%20the%20input.%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20(%24(%24d)*)%20%3D%3E%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20Add%20the%20value%20to%20the%20right%20accumulator%20and%20expand%20to%20a%20tuple%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20(%24s%2C%20%24t%2B%24y)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20%24e%20is%20less%20than%20%24d.%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20We%20have%20moved%20past%20the%20midpoint.%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20(%24m(I)*)%20%3D%3E%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20Expand%20to%20a%20tuple%20containing%20the%20accumulators%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20(%24s%2C%20%24t)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20call%20the%20internal%20macro%20with%20%24e%0A%20%20%20%20%20%20%20%20%20%20%20%20i!(%24(%24e)*)%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%3B%0A%7D%0Afn%20main()%20%7B%0A%20%20%20%20assert_eq!((1%2C%209)%2C%20f!(1%209))%3B%0A%20%20%20%20assert_eq!((1%2C%205)%2C%20f!(1%202%203))%3B%0A%20%20%20%20assert_eq!((14%2C%2012)%2C%20f!(9%205%205%207))%3B%0A%20%20%20%20assert_eq!((19%2C%2026)%2C%20f!(6%207%205%201%203%209%207%201%206))%3B%0A%20%20%20%20assert_eq!((65%2C%2059)%2C%20f!(2%208%2010%209%209%203%207%208%209%208%206%201%202%209%208%203%208%209%205))%3B%0A%20%20%20%20assert_eq!((20%2C%2031)%2C%20f!(2%203%201%208%206%202%2010%206%207%206))%3B%0A%20%20%20%20println!(%22tests%20passed%22)%3B%0A%7D)
This is kind of insane and I kind of hate myself now. The code defines a macro that takes a sequence of whitespace-seperated numbers and expands to a tuple of 2 integers. Everything is calculated at compile-time, so the code runs in \$O(1)\$, but compile times may vary.
For an introduction to Rust macros, I recommend [the Rust book](https://doc.rust-lang.org/book/ch19-06-macros.html), [the Rust refeence](https://doc.rust-lang.org/reference/macros-by-example.html) and [The Little Book of Rust Macros](https://danielkeep.github.io/tlborm/book/README.html).
## Explanation
So rust macros operate on token streams that are matched against patterns. For our case, the main difficulty is that you basically have to consume the token stream front-to-back.
To defeat this, I first replace the list of numbers with two numbers, where one of them is reversed. Also, to be able to find the middle, I put an index next to each number. Since yout can't evaluate integer expression like `0+1`, I use a tally counter made up of `I` identifier tokens. That way, I can detect the midpoint by comparing the length of the tally counter. Each part is replaced with ad addition of all its components, which can be evaluated at compile time.
### Example
Let's use `1 2 3` as an example. This shows the basic idea, but is still simplified a bit.
```
1 2 3
[1 2 3] [] [] // input forward backward
[2 3] [(I, 1)] [(I, 1)]
[3] [(I, 1); (I I, 2)] [(I I, 2); (I, 1)]
[] [(I, 1); (I I, 2); (I I I, 3)] [(I I I, 3); (I I, 2); (I, 1)]
0; 0; [(I, 1); (I I, 2); (I I I, 3)] [(I I I, 3); (I I, 2); (I, 1)] // two accumulators
0 + 1; 0 + 3; [(I I, 2); (I I I, 3)] [(I I, 2); (I, 1)]
(0 + 1; 0 + 3 + 2)
```
Refer to the compiler output in the rust playground for the complete expansion.
```
// Define a macro called f
macro_rules! f {
// This rule is the starting point
// It matches any number of expressions
($($r:expr)*) => {
// Use the internal rules with an at sign.
// Provide the I as the first index.
f!(@ I; [$($r),*]; [];)
};
// The rules starting with an at sign are responsible for producing a reversed version
// of the input and counting with tallys.
// This pattern is known as tt-muncher because it consumes a token tree recursively.
// This is the base case. It matches when the input is an empty set of brackets.
(@ $($d:ident)*; []; [$($a:tt)*]; $($b:tt)*) => {
// Call the second set of internal macros (the ones starting with a percent sign).
// We use zeros as the accumulators
f!(% ($) 0; 0; [$($a)*] $($b)*)
};
// This is the recursive case.
// It extracts one expression (called x) from the input.
(@ $($d:ident)*; [$x:expr $(,$r:tt)*]; [$($a:tt)*]; $($b:tt)*) => {
// Call the at-macro recursively.
// Add one I to the current tally list.
// append (tallys, $x) to the first "array".
// prepend (tallys, $x) to the second "array".
f!(@ I $($d)*; [$($r),*]; [$($a)*; ($($d)*, $x)]; ($($d)*,$x); $($b)*)
};
// This part of the macro is called with the original and the reversed version.
// The first argument is a dollar sign because that it needed later.
// It extracts the count $d and value $x of the forwards array,
// and count $e and value $y of the backwards array.
(% ($m:tt) $s:expr; $t:expr; [; ($($d:ident)+, $x:expr) $($a:tt)*] $(;)* ($($e:ident)*, $y:expr) $($b:tt)*) => {
{
// To compare the two tally counters at compile time, we use an internal macro.
// It defined rules based on $d.
// The argument of this macro will be $e.
macro_rules! i {
// This case matches when $e is larger than $d.
// That means we haven't found the end yet.
($($d)* $m(I)+) => {
// call this part recursively, adding $x and $y to their accumulators
f!(% ($m) $s+$x; $t+$y; [$($a)*]; $($b)*)
};
// $e and $d are equal.
// This case is reached when there is an odd number of element in the input.
($($d)*) => {
// Add the value to the right accumulator and expand to a tuple
($s, $t+$y)
};
// $e is less than $d.
// We have moved past the midpoint.
($m(I)*) => {
// Expand to a tuple containing the accumulators
($s, $t)
}
}
// call the internal macro with $e
i!($($e)*)
}
};
}
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 33 bytes
```
@(x)x*[u=(t=find(x))<mean(t);~u]'
```
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzQiu61FajxDYtMy8FyNW0yU1NzNMo0bSuK41V/5@mEW2oYBmryQVkWCqYAqE5hGOmYA7kGCoYK1gCWYYKZhBhIwULBUMDoJglUMYcyLEEYjOgvBGYZQwWMYWpNQZKgKSNQHpAJgJN@Q8A "Octave – Try It Online")
### How it works
```
@(x)x*[u=(t=find(x))<mean(t);~u]'
@(x) % Define an anonynous function with input x
find(x) % Indices of nonzero entries of x. Gives [1 2 ... n]
% where n is the length of x
(t= ) % Assign that to variable t
<mean(t) % Test if each entry of t is less than the mean of t.
% This gives [1 ... 1 0 ... 0], with floor(n/2) ones
% and n-floor(n/2) zeros
u= % Assign that to variable u
[ ;~u] % Build a 2×n matrix containing u in the first row
% and u negated in the second row
' % Conjugate transpose. Gives an n×2 matrix
x* % Matrix-multiply x (size 1×n) times the above n×2
% matrix. Gives a 1×2 vector containing the result
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 180 bytes
```
++>>>>>+>,[[<]>+[>],]<[<]>[<+>-]<[<<<<[>>+<+<-]>[<+>-]>[<+>>>-[<<<[-]>>+>-]<[>+<-]<<[>-[>>>-<<<[-]]+<-]>-]>>>+<]>[<<+>+>-]<<[>>+<<-]>[>-<[-]]>[[>]<[<+>-]<[<]>-]>>>[<<[->+<]>>>]<.<.
```
[Try it online!](https://tio.run/##PY1dCsJADISxRU16lXR7gjAXCftgBUEEHwTPv2Z21bzkZ76Z7K/L/Xl7Xx@tmYFlWCO8wgJ1rc4x3FA4ZkUSbl5@196AQjFyxUBBhHQJqkOs3UcoZTrT2vGR2kOTJYnI9/5//HUFY7oXqW6@tTbJojqfReV0mFRm0eMH "brainfuck – Try It Online") (testcase [2, 8, 10, 9, 9, 3, 7, 8, 9, 8, 6, 1, 2, 9, 8, 3, 8, 9, 5])
Takes input as bytes on stdin.
Outputs the two sums as bytes on stdout in reverse order.
Compiled from this [VBF 1.0](https://github.com/zachs18/vbf/tree/1.0) code with mapping requirement `x:5` :
```
# set y to 2
y++
# Input is to the right of x; which is the length and the divdend
# Ensure that x is the rightmost variable
# x is the length of a length-prefixed array of numbers
x+>,[[<]>+[>],]
<[<]>
#cursor is at x
# x = x / y
# from user Calamari from esolangs wiki at https://esolangs.org/wiki/Brainfuck_algorithms
x[A+x-]
A[
y[B+C+y-]
C[y+C-]
B[
C+
A-[C[-]D+A-]
D[A+D-]
C[
B-
[x-B[-]]+
C-]
B-]
x+
A]
# After this, x = x / 2, A,B,C,D = 0, y = y
# If x, x = x - 1
# from https://esolangs.org/wiki/Brainfuck_algorithms#if_.28x.29_.7B_code_.7D
x[D+A+x-]D[x+D-]
A[
x-
A[-]
]
# Add up first half, cursor starts at x
# Requires that the cell to the left of x is 0
x[
[>]< # last input
[<+>-] # add into left neighbor
<[<]>- # back to x, decrement x
]
>>>
[
<<[->+<]>>>
]<.<.
```
[Answer]
# [asm2bf](https://esolangs.org/wiki/Asm2bf), 157 bytes
A rather long submission. Let's take a look at the golfed code first:
```
@l
in r1
cner1,0
cadr2,1
cpsr1
cjn%l
movr3,r2
modr3,2
divr2,2
movr4,r2
addr2,r3
@x
popr1
addr5,r1
decr2
jnzr2,%x
@y
popr1
addr6,r1
decr4
jnzr4,%y
outr6
outr5
```
[**Try it online!**](https://tio.run/##5VTLagMxDPyWtrlNnS8Q@hHhQ1sIlEIOhX7/VpLttezdbE4lh5pA1rIeo9HY799vn9fLz8fXsoAhzAwi/elXsk9KWW2iH9D/lEncbI7JHPVY9Mi8hBJLyurSvc2sf@QRWBOKO1is2PaV@6rudbVUYSEcu68iKtY8OgrFNWZZi1QnbSraJVSynm8CsOo5r8gxlXb4rfZubp5aB1s5UAMoq4sMtEykzKgqbEwVSiLmDMem/PtOMfquTmoHBnY5VfMNWhvOQ4yundJib7OX6Mn7tKZEJTJPysl35FZcxY9RsovnrCDg96AUqYe25WQkkTRech@gNJKK7MseHbpJA01t0T72jDsqNIjCnSwEJrfsTeSJx9qtdc3anS1xniUHDUpnZI8gaZJOlejKs@bAAx4P2UjcBWWytpxUlQ43VcwufaKDB2Kr5VHMmGLDdfPnKEwb47jxp9LXyv9mBvN7MkzB2wdo/2q1RHj0SxTWmc5jP8fREa@9Rsvy9Pxy@gU "brainfuck – Try It Online")
# I/O format
The program takes input in form of so-called ASCII characters, and produces the output analogically. It's recommended to test the program on a 16-bit brainfuck interpreter (so that the addition doesn't overflow quickly).
**asm2bf** is a separate language to brainfuck, therefore the Brainfuck restrictions theoretically don't apply to it (because for instance, asm2bf specification says that registers for programmer's convience are at least 16 bits long), but as there is no asm2bf interpreter on TIO, I have to somehow cope with these limitations.
That being said, let's look at some I/O examples:
```
!"#$% => [33, 34, 35, 36, 37] => [33 + 34, 35 + 36 + 37] => [67, 108] => Cl
!"#$ => [33, 34, 35, 36] => [33 + 34, 35 + 36] = [67, 71] => CG
```
# Explanation
Let's take a look at the ungolfed representation of the code.
## Golfing 101
```
@inloop
in r1
cne r1, 0
cadd r2, 1
cpush r1
cjn %inloop
mov r3, r2
mod r3, 2
div r2, 2
mov r4, r2
add r2, r3
@right
pop r1
add r5, r1
dec r2
jnz r2, %right
@left
pop r1
add r6, r1
dec r4
jnz r4, %left
out r6
out r5
```
Let's answer two questions first:
`=>` Why does the code compile without spaces between operand and the operation?
The answer is quite simple: the assembler is a very primitive tool. It assumes instruction length of three, therefore after reading instruction name, all spaces are then consumed (but obviously there can be no spaces inbetween).
`=>` Why is there a space between `in` and `r1`?
`in` is a special instruction, because it has two character length. Under the hood, it's padded to three characters using the floor character (\_). Therefore, if the space was ommited, then the assembler would interpret `r` as the instruction name.
`=>` Instructions changed. `cpo` took place of `cpush`, `cad` of `cadd`. Why?
It is perfectly legal, because if every instruction has to have a three byte name, then there must be some alias that magically swaps long instruction names into short instruction names, right?
That's the full list of aliases, as of *v1.3.9* (taken from the `lib-bfm.lua` file):
```
; Don't ask questions, this is beyond explaining
?band=x00
?bor=x01
?bxor=x02
?bneg=x03
?cflip=x04
; Some common defines
?push=psh
?xchg=swp
; Conditional instructions
?cadd=cad
?csub=csu
?cmul=cmu
?cdiv=cdi
?cmod=cmd
?casl=csl
?casr=csr
?cpow=cpw
?cpush=cps
?cpsh=cps
?cpop=cpo
?cxchg=csw
?cswp=csw
?csrv=crv
?cmov=cmo
?crcl=crc
?csto=cst
?cout=cou
```
That being said, let's dive into the algorithm.
## Algorithm
Let's dissect the code step by step for better understanding:
```
@inloop
in r1
cne r1, 0
cadd r2, 1
cpush r1
cjn %inloop
```
Some parts are obvious (label declarations for example), some are less. A new feature introduced around v1.3.5 named *conditional instructions* helps us greatly to solve this task.
The conditional pipeline of this fragment follows:
```
; if r1 is not zero, set the flag, otherwise clear it
cne r1, 0
; if flag is set, add 1 to r2 (we accumulate the list length)
cadd r2, 1
; push the number on the stack if the flag is set.
cpush r1
; jump to @inloop if the flag is set.
cjn %inloop
```
As you can see, it's quite simple to notice, that this tiny block of code will is responsible for:
* reading the list
* accumulating it's elements on the stack
* keeping track of the amount of elements read (in `r2`)
* looping until hit EOF
*Note: Yes, it's true that you have to set the stack before accessing it, otherwise stack overflow error occurs. In this case, I simply don't make memory accesses, so it's not required to set the stack (because it has nowhere to overflow to)*
Between these two loops, there is a tiny block of setup code:
```
; r3 = r2
mov r3, r2
; r3 = r2 mod 2
mod r3, 2
; r2 = r2 / 2
div r2, 2
; r4 = r2
mov r4, r2
; r2 = r2 + r3
add r2, r3
```
This means, the register values are now:
```
r4 = r2 / 2
r3 = r2 mod 2
r2 = (r2 / 2) + r3
```
r3 is used as a flag to indicate whenever the middle element is present and it has to be merged to the list on the right (if count mod 2 is 1, then the count is odd, therefore we have a middle element obviously). The flag is added to the r2 register so the following loop will slurp it from the stack.
Next, there are two *very simillar* loops. Let's dissect these:
```
@right
pop r1
add r5, r1
dec r2
jnz r2, %right
@left
pop r1
add r6, r1
dec r4
jnz r4, %left
```
`@right` will execute until `r2` is not zero (id est, the amount of elements left to extract from the stack to make the *right* list). Everytime an element is popped, the pointer (`r2`) decreases and the popped value is added to `r5`.
This being said, `@right` will simply extract `r2` elements from the stack and sum them up to `r5`.
`@left` works pretty much the same (it will build the list on the left) returning the result in r6.
And finally, we output both values (sum for the left and the right):
```
out r6
out r5
```
# Appendix A
Generated brainfuck code (around 1.9 kilobyte):
```
+>+[>>>+<<+<<[>>->+<<<-]>>>[<<<+>>>-]<[->+<<[>>>-<<+<-]>[<+>-]>>[<->[-]]<[<<<+>>>-]<]>>[-]<<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>,>>>>>>>>>>>[-]<<<<<<<<<<<[<<<+>>>>>>>>>>>>>>+<<<<<<<<<<<-]<<<[->>>+<<<]>>>>>>>>>>>>>>[<<<<<<<<<<<<<+>>>>>>>>>>>>>-]<<<<<<<[<<<<<<->+>>>>>-]<<<<<[>>>>>+<<<<<-]<[>>>>>>>>>>>>>+<<<<<<<<<<<<<[-]]>>>>>>[-]+>>>>>>>[<<<<<<<[<<<+<<+>>>>>-]<<<<<[>>>>>+<<<<<-]>>>>>>>>>>>>[-]<+>]<[>+<-]<<<<<<[-]>>>>>>>[<<<<<<<<<<<[<+>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<-]<[>+<-]>>>>>>>>>>>>>>>>>[>>]+<<[<<]>[>[>>]<+<[<<]>-]<<<<[-]<+>]<[>+<-]<<<<<<+>>>>>>>[<<<<<<<<<<<<<<+>+>>>>>>>>>>>>>-]<<<<<<<<<<<<<<[>>>>>>>>>>>>>>+<<<<<<<<<<<<<<-]>[<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>[-]]>>>>>>[-]<<<<<<]<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>>[-]<[>+<<<+>>-]<<[>>+<<-]>>>>>++[>>>>+<<<<-]<<[>>>>>+>-[<<]<[[>+<-]<<]<<<-]>>>>>[<<<<<+>>+>>>-]>[<<<<+>>>>-]<<<<[-]++<<<[<<<<+>>>>-]<<<<[>>>>>>>[<<<<<<+>+>>>>>-]<<<<<[>>>>>+<<<<<-]<[>+<<-[>>[-]>>>>>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<[<-[>>>-<<<[-]]+>-]<-]>>>+<<<<]>>>>>>>[-]<[-]<<[>>+<<<<+>>-]<<[>>+<<-]>>>[<+<<+>>>-]<<<[>>>+<<<-]<]>++<<+<<[>>->+<<<-]>>>[<<<+>>>-]<[->+<<[>>>-<<+<-]>[<+>-]>>[<->[-]]<[<<<+>>>-]<]>>[-]<<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>[-]>>>>>>>>>>>>>>>[-]>[>>]<<->[<<<[<<]>+>[>>]>-]<<<[<<]>[<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<[>>>>>>>>>>>>+<<<<<<<<<<<<<+>-]<[>+<-]>>->>>++<<<[<<<<+>+>>>-]<<<<[>>>>+<<<<-]>[<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>[-]]>>>>>>[-]<<<<<<]>+++<<+<<[>>->+<<<-]>>>[<<<+>>>-]<[->+<<[>>>-<<+<-]>[<+>-]>>[<->[-]]<[<<<+>>>-]<]>>[-]<<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>[-]>>>>>>>>>>>>>>>[-]>[>>]<<->[<<<[<<]>+>[>>]>-]<<<[<<]>[<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<[>>>>>>>>>>>>>+<<<<<<<<<<<<<<+>-]<[>+<-]>>>>->+++<[<<<<<<+>+>>>>>-]<<<<<<[>>>>>>+<<<<<<-]>[<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>[-]]>>>>>>[-]<<<<<<]<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>>>>>>>>>>>>>.<.<<<<<<<<<<<<<<]<<<[>>+>+<<<-]>>[<<+>>-]>[[-]<<<[-]>[-]>>]<<]
```
# Appendix B
The code possibly can be golfed down using `constpp` - the tool used to set macros on certain `[A-Za-z]+` strings and alias them into other, preferably longer strings. Syntax: `?find=replace`
There is a tiny chance that one could golf the code down using Lua preprocessor. If you'd like to start a multiline Lua block, use `${...)` syntax; single line Lua statements can be prepended with `#`.
Example on both methods: [lib-bfm.lua](https://github.com/KrzysztofSzewczyk/asmbf/blob/master/lib-bfm.lua).
lib-bfm is a file included everytime an assembly program is built using `bfmake` tool (the one to assemble your code into a ready-to-use Brainfuck program). It's overall recommended to take advantage of it, because it contains some predefined macros (like a memory allocator or quite basic code-preprocessing capabilities).
PS: If anything is unclear, please let me know down in the comments. I'll try to clarify it when I'll have some time on my hands.
[Answer]
# brainfuck, 45 43 bytes
```
>>>,[>,[[<]>[<+>-]>[>]],]<[[>[<+>-]<<]>.<<]
```
Shorter, but assumes ',' continues to return 0 after EOF, not just the first time after EOF.
Earlier version:
```
>>>>>,[>+[<<]+>>->>[>>]+>,]<[[<[<<+>>-]<]<.<]
```
Reads numbers as characters, outputs right sum first.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 bytes
Anonymous tacit prefix function
```
+/2 ¯.5⍴⌽,0⍨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X1vfSOHQej3TR71bHvXs1TF41Lvif9qjtgmPevsedTU/6l0DlDi03vhR28RHfVODg5yBZIiHZ/D/NAVDBUuuNAVLBVMgNAeyzBTMgSxDBWOgmDmQNgOKGSlYKBgaAAUsgcLmQI4lEJsBJY3ALGOwiClYoTFQFCRnBNIAMsuMCwA "APL (Dyalog Extended) – Try It Online")
`0⍨` zero
`⌽,` appended to the reverse of the argument
`2 ¯.5⍴` **r**eshape to 2 rows and as many columns as needed, chopping trailing elements if uneven
`+/` sum the rows
[Answer]
# JavaScript (ES6), ~~47~~ 45 bytes
Outputs in reverse order.
```
a=>[a.reduce(s=>s+a.pop(),0),eval(a.join`+`)]
```
[Try it online!](https://tio.run/##nc/dCoMgGAbg812Fh0rOypbNg7qRCJKyUURGbt1@sy86WYP9iIh/3/Nqp2Zlq6kd7@fB1Hpp0kWlWa7YpOtHpbFNM@spNpoRExoQqmfVY8U60w6lV5JiqcxgTa9Zb264wXlIkSwIQf8030db/ekFlRTF0JPfaUAvFIX8wAoHAutCI5cLSzcXX6QA6yq4OLCcoqtzAhAl0AlsSRgFZPB9Ge1H8Zq6smL9q3zHRlC6GXyL2P7w6cUry93tKCyWJw "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
R2äO
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/yOjwEv///6PNdBTMdRRMdRQMdRSMdRQswVwg2ywWAA "05AB1E – Try It Online")
[Answer]
# [Clojure](https://clojure.org/), 47 bytes
```
#(for[x(split-at(quot(count %)2)%)](apply + x))
```
[Try it online!](https://tio.run/##NY7bCsMgDEDf/YrAKETWwWZpO79FfChthQ6pvVjovt5lkYJoTk4u9j58jm1MOIwOXLqhC5s5cV/8FB9dxPUIEftwzBEKqWQhLXbL4r9wh1PKJAUOYR9XMCcYYV4laCuMLqHm0xI09DCQrMgzUtyQUyW8CZ6c1uxbTmm@Gy5UF1aXqnNrxTrXqTwmL6PR1gpctmmOfgZ0/7/K9AM "Clojure – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~46~~ 45 bytes
```
sum((v=scan())[l<-1:(sum(v|1)/2)]);sum(v[-l])
```
[Try it online!](https://tio.run/##K/r/v7g0V0OjzLY4OTFPQ1MzOsdG19BKAyRYVmOoqW@kGatpDeZF6@bEav434zLnMuUy5DLmsgSyDLnMuLj@AwA "R – Try It Online")
*Edit: thanks to Giuseppe: -1 byte*
[Answer]
# [Risky](https://github.com/Radvylf/risky), 12 bytes
```
_?+_0\!?/_2_+?+_0+_0+_0
```
[Try it online!](https://radvylf.github.io/risky?p=WyJfPytfMFxcIT8vXzJcbl9cbis_K18wK18wK18wIiwiW1s2LCA3LCA1LCAxLCAzLCA5LCA3LCAxLCA2XV0iLDBd)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
r2Ẇʂ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPXIyJUUxJUJBJTg2JUNBJTgyJmZvb3Rlcj0maW5wdXQ9JTVCMSUyQyUyMDklNUQlMEElNUI5JTJDJTIwNSUyQyUyMDUlMkMlMjA3JTVEJTBBJTVCNiUyQyUyMDclMkMlMjA1JTJDJTIwMSUyQyUyMDMlMkMlMjA5JTJDJTIwNyUyQyUyMDElMkMlMjA2JTVEJTBBJTVCMiUyQyUyMDglMkMlMjAxMCUyQyUyMDklMkMlMjA5JTJDJTIwMyUyQyUyMDclMkMlMjA4JTJDJTIwOSUyQyUyMDglMkMlMjA2JTJDJTIwMSUyQyUyMDIlMkMlMjA5JTJDJTIwOCUyQyUyMDMlMkMlMjA4JTJDJTIwOSUyQyUyMDUlNUQlMEElNUIyJTJDJTIwMyUyQyUyMDElMkMlMjA4JTJDJTIwNiUyQyUyMDIlMkMlMjAxMCUyQyUyMDYlMkMlMjA3JTJDJTIwNiU1RCZmbGFncz1W)
#### Explanation
```
r2Ẇʂ # Implicit input
r # Reverse the list
2Ẇ # Split it in two pieces
# (with a left-bias)
ʂ # Sum each inner list
# Implicit output
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
Fθ⊞υ⊟θI⟦ΣθΣυ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8juDRXw7kyOSfVOSO/QKNQR8EjMacsNUXDJzUvvSRDo1BTU1NHIUPTmiugKDOvRMM5sbhEIzpDR8E3M6@0GKy7EKwgVlPT@v//6GgjHQULHQVDAx0FSzAy1lEwBwtZgkkzoJyOghGMawyTMo2N/a9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Port of @dingledooper's answer. Explanation:
```
Fθ
```
Loop over the list.
```
⊞υ⊟θ
```
Move the last element of the list to the empty list.
```
I⟦ΣθΣυ
```
Output the sums of the lists.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 77 bytes
```
i,l;f(a,n)int*a;{l=0;for(n-=i=n/2;i--;!i?i=n,n=l=!printf("%u ",l):0)l+=*a++;}
```
Takes as input an array and its size.
[Try it online!](https://tio.run/##NYrNCoMwEITvPsU2UEh0Q63SH7uEPkjpIVhSAmkUq72Iz54ugsMwMPNNq99tm5LHQE5ajMrHMbc0B1OS6wYZtfEmHiryWtPO37lgNMHs@oGfTor9BAKDupUqFCa3RUFLYgIf66P8df6lsjkDlpOS98dTzRXCFeFYIjSra4TLOjVrnpkhVFutN3RaGDSKoJ/GrxRCUbakPw "C (gcc) – Try It Online")
[Answer]
# APL+WIN, 18 bytes
Prompts for vector of integers:
```
+/(2,⌈.5×⍴s)⍴s←0,⎕
```
[Try it online! Coutesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5r62sY6Tzq6dAzPTz9Ue@WYk0QAZQ20AEq/A9U8j@Ny1DBkitNgctSwRQIzbnSuMwUzIEsQwVjBUsgy1DBDChmpGChYGgAFLAECpsDOZZAbAaUNAKzjMEipmCFxkBRkJwRSAPILDMuAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 52 bytes
```
func[a][reduce[sum take/part a(length? a)/ 2 sum a]]
```
[Try it online!](https://tio.run/##PU47DoMwDN05xRNTO1Q0QUDTob1D1yhDREypyk8hnJ86gGrL0vvY1vPk1hc5bZLmvjbLUGtrtCe31KTnpUewX8om6wPsqaPhHdon7DmDRHStMWszerJ1i0BzgE7ApQWU2ZFCwV0drETFTCCHYiRQHrrEDeLKomKrYqJ4Sl6QG8o3pfgv5@xEX8aj@JP/GD35z8AJ@rFze5j08kjR7JiD/gA "Red – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
mΣ½↔
```
[Try it online!](https://tio.run/##yygtzv7/P/fc4kN7H7VN@f//f7SRjrGOoY6FjpmOkY6hAZAy1zGLBQA "Husk – Try It Online")
# Explanation
```
↔ Reverse the input
½ Split the input into about-equal parts of 2
m For every item in the list:
Σ Sum this list
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 35 bytes
```
?[zRla+salFx]sU[lb+sbz0<U]dsFxlblaf
```
[Try it online!](https://tio.run/##S0n@/98@uiooJ1G7ODHHrSK2ODQ6J0m7OKnKwCY0NqXYrSInKScx7f9/IwULBUMDBUsgNFYwB3IsgdhMwVDBCMwyBouYAgA "dc – Try It Online")
[Verify the test cases online.](https://tio.run/##TY5dC4IwFIbv9yteJAiKwA/UFlJXCV0FgVfRxdSZwlJxShH9dzszoja2nfO8D4elQpdjJnps0XbNtRM3RJG1P8bWuDs/T0ostVDx46KTs0qXOn3aUXLJdfxQqRLFSCJj97JSEp0UOVRVSwbkDV2AzMoG1qFuh36DmcmsHz8OveF/4sfAC3mGVfH9z0@YL8yaT/NrOTrgjMOnHbIAIb0OPHCqHATMxRqOTS0nGFLD6QQUuVPlTcQnzSNmEtfoZk7A3g)
Input is a space-separated list of numbers on stdin.
Output is on stdout, on two lines: the sum of the left part, then the sum of the right part.
**How it works:**
```
? Read the input and push it on the stack.
(The last number in the list is at the top of the stack.)
[ Start a macro.
zR Move the bottom item on the stack to the top,
moving the rest of the stack down one item.
la+sa Pop the top item on the stack and add it to register a.
This number comes from the left part.
lFx Execute F recursively.
]sU End the macro and name it U.
[ Start a macro.
lb+sb Pop the top item on the stack and add it to register b.
This number comes from the right part.
(Note that if the stack is empty so that there's
nothing to pop, then b is left unchanged.
This will happen the last time through when the
original list had an even number of items.)
z0< If there's anything still on the stack,
U then execute macro U (which adds the bottom item on the
stack to register a and then executes F recursively).
]dsFx End the macro, name it F, and execute it.
lblaf Print a, then print b.
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 67 bytes
```
f(x,y,a,b)int*x,*y,*a,*b;{for(*a=*b=0;x<y--;*a+=x<y?*x++:0)*b+=*y;}
```
[Try the test cases online!](https://tio.run/##jY9da4MwFIbv8ytCoSUfR7C62maZDL9@RbeLRHF4UTvKGIr4210Sl91OCOGcJ897ktTBR10vS0sGGEGBpl3/xQZgIzAFTMupvT8IUynTaSiHlzEIJFM8NdUrGzh/DinTPGWjnBeTxDfV9eT73jUUTQhbkl3f0@kIWMxyBbkFAvDJrbPHhcWJAQ6bQGwyrjV14q3SWhHgi8GhE4Qzzw4JtycuEvk29kcnP6T6HRI7cU1E68D1AX/XKcBaIoRbkkHGIzgoOGgqPx/msCW7fYP3zVu/AydSacUccv60RSyg4GKLWELJj5vMCipufvGfOaPlBw "C (gcc) – Try It Online")
This is a function with two "in" parameters (`x` and `y`) and two "out" parameters (`a` and `b`).
Input is taken as an array of ints, and is passed as a [pointer `x` to the beginning of the array and a pointer `y` to (the location immediately after) the end of the array](https://codegolf.meta.stackexchange.com/a/14972/59825).
The function returns the left and right sums in `*a` and `*b`, respectively.
[Answer]
# Julia, 41 bytes
```
a->[sum(a[1:(e=end÷2)]),sum(a[e+1:end])]
```
] |
[Question]
[
The [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity) of two vectors \$A\$ and \$B\$ is defined using their [dot product](https://en.wikipedia.org/wiki/Dot_product) and [magnitude](https://en.wikipedia.org/wiki/Magnitude_(mathematics)#Euclidean_vector_space) as:
\$\frac{A\cdot B}{\|A\|\|B\|}\$
Or in other terms
\$\frac{\sum\_{i=1}^nA\_iB\_i}{\sqrt{\sum\_{i=1}^nA\_i^2}\sqrt{\sum\_{i=1}^nB\_i^2}}\$
# Challenge
Given two nonempty, nonzero vectors containing only integers (can be taken as lists) calculate their cosine similarity.
* If their lengths are not equal, then the shorter vector should be padded on the right to length of the longer vector with zeroes.
Input and output may be done via any [reasonable method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
Test cases below.
```
[1,2,3], [4,5,6] => ~0.974
[9, 62, 0, 3], [25, 3, 6] => ~0.25
[-7, 4, 9, 8], [16, 1, -2, 5] => ~-0.35
[82, -9], [7, 52, 3] => ~0.024
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
`*OInOtP/
```
Input as a pair of lists.
[Try it online](https://tio.run/##yy9OTMpM/f8/QcvfM8@/JED////oaEsdMyMdAx3jWJ1oI1MdYx2z2FgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/BC3/yjz/kgD9/zr/o6OjDXWMdIxjdaJNdEx1zGJjdRSioy11zIx0DMCiRqY6xjBhXXMdEx1LHQugsKGZjqGOrpGOKUTGwkhH1xIobK5jCjIsNhYA).
**Explanation:**
```
` # Push both lists of the (implicit) input-pair separately to the stack
* # Multiply the values at the same positions in the lists together
# (discarding trailing items of unequal length input-lists)
O # Sum all these values together
I # Push the input-pair of lists again
n # Square each inner value
O # Sum the two inner lists
t # Take the square root of both sums
P # Take the product of this pair
/ # Divide the earlier dot-product by this
# (after which the result is output implicitly)
```
Here a minor equal-bytes alternative: `øPInOtP/O`. I haven't been able to find anything shorter unfortunately, but there are a lot of approaches for this at 1 or 2 bytes longer: [try it online](https://tio.run/##yy9OTMpM/f8/QcvfM8@/JEBfAQh0uA7vCIBw/SF8qHRZJUi@FsSHcv3h/LJKoAiC718MEYDwgSzPBK2jC/UO7QYpgQgALfGHCIGtCA1LUIABpeLUktIChbT8IoWS8nyFnPz84lSFzLyC0hLdnMzikmIgu7gkNTFFIT9NIVGhIDGzSCmGS8s/MuJRwyyYvbU6//9HR1vqmBnpGOgYx@pEG5nqGOuYxcYCAA).
[Answer]
# [Desmos](https://desmos.com/calculator), 42 bytes
This non-padding version miraculously works out:
```
f(a,b)=total(ab)/(a^2.totalb^2.total)^{.5}
```
[Try It On Desmos!](https://www.desmos.com/calculator/7e69ztsfva)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/pb7kqinlej)
I originally had constructed an answer that was 123 bytes (around 3 times longer than with no padding!!!) long that did actually do the padding, but then I realized, to my complete surprise, that the test case outputs were matching on both my padding and no-padding answers (which is this 42 byte answer), even for test cases that I made up myself. This led me to dig a bit deeper into why this was the case, resulting in the explanation below.
### Explanation
The question essentially asks to pad the shorter list with zeros at the end to make both lists the same, and then multiply each element of the lists together and sum them, then divide it by the square root of the product of the sums of the elements of each of the two lists squared.
Now let's say that the unpadded, original input lists are `a=[a_1,a_2,...,a_A]` and `b=[b_1,b_2,...,b_B]`, where the capitalized version of the list represents the length of the list. WLOG, assume that `A<B`. Now let `c` and `d` be the padded versions of `a` and `b` respectively, meaning `c=[a_1,a_2,...,a_A,0,...,0]`, where there are `B-A` zeros, and `d=[b_1,b_2,...,b_B]`, which is `b` unchanged.
Now to explain my non-padding answer first:
In Desmos, every time an operation is applied to two lists, it will almost always clip the resulting list to the length of the shorter list out of the two lists. This includes multiplication (implicitly vectorized), which is used in this answer.
For the numerator of the formula given in the question, it is essentially equivalent to using vectorized multiplication on the two lists (which will multiply the lists element-by-element), and then taking the total sum of that vectorized product. We know that vectorized multiplication will clip the lists to the length of the shorter lists, which means that when we take the product `a*b`, we will get the result `[a_1 * b_1, a_2 * b_2,...,a_A * b_A]`, where it is clipped off at the shorter list `a`. Taking the total of this would give `a_1 * b_1 + a_2 * b_2 + ... + a_A * b_A`.
Wait! Now let's take a look at what happens when we take the product `c*d` and sum that list instead. Recall that `c=[a_1,a_2,...,a_A,0,...,0]` and `d=[b_1,b_2,...,b_B]`, so `c*d` would be `[a_1 * b_1, a_2 * b_2,...,a_A * b_A, 0 * b_(A+1),...,0 * b_B]`. Taking the sum of all those terms gives `a_1 * b_1 + a_2 * b_2 + ... + a_A * b_A`, due to all the zeros vanishing from the sum. But this is the exact same sum that we got without padding!!! This indicates that padding at least does not affect the final result of the numerator of the formula, so it is fine to take the sum without padding the two lists beforehand, as it will result in the same answer as with padding anyways.
Now let's consider what is happening in the denominator. In my answer with no padding, I am simply just multiplying each of the lists by themselves (i.e. squaring them), and then summing the resulting elements. So basically, we have that `a^2 = [(a_1)^2, (a_2)^2,...,(a_A)^2]` and `b^2 = [(b_1)^2, (b_2)^2,...,(b_B)^2]`, which means that their sums are `(a_1)^2 + (a_2)^2 + ... + (a_A)^2` and `(b_1)^2 + (b_2)^2 + ... + (b_B)^2` respectively.
But now consider the sums when there is padding involved. We then have that `c^2 = [(a_1)^2, (a_2)^2,...,(a_A)^2, 0^2,...,0^2]`, and `d^2` would be the same as `b^2` because as stated earlier, `d` is the same as `b` unchanged. So, the sum of `d^2` would obviously match that of `b^2`. But what about the sum of `c^2`? We have that the sum of `c^2` is `(a_1)^2 + (a_2)^2 + ... + (a_A)^2 + 0^2 + ... + 0^2`, but because all the zeros just vanish, the sum simplifies down to `(a_1)^2 + (a_2)^2 + ... + (a_A)^2`. Comparing this to the sum that we got with no padding, we can see that they are exactly the same!!!
Obviously, we have assumed that `A<B` at the very start of our proof. But what happens if `B>A`? Then simply just switch all the `a`'s and `b`'s, `A` and `B`'s, and also `c` and `d` and you will have the proof for the `B>A` case.
Lastly, what happens if `A=B`; in other words, what happens if they are both the same length? The clipping will shorten the longer list into the same length of the shorter list, but because they are the same length, this will not affect either of the lists. Similarly, padding will lengthen the shorter length to match the length of the longer list, but again, because the two lists are the exact same length, this won't affect either of the lists. Because both clipping and padding preserve the original lists, both of them will obviously result in the same calculations and therefore the same outputs as well.
Thus, by proving that the sums in both the numerator and denominator are the same with both padding (which is what the question is asking for) and with no padding (which is what is happening in my answer), my answer is valid, even though I am not actually doing any padding like the question asks for.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~60~~ ~~31~~ 27 bytes
```
Dot@@Normalize/@PadRight@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yW/xMHBL78oNzEnsypV3yEgMSUoMz2jxEFZ7X9AUWZeiUOaQ3W1hZGOgq5lrU61uY6CKZBtXFv7HwA "Wolfram Language (Mathematica) – Try It Online")
Many thanks to @att and @
polfosol ఠ\_ఠ ! They should have posted their answers (-\_-)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ÆḊ€÷ƒḋ/
```
A monadic Link that accepts the pair of vectors and yields their cosine similarity.
**[Try it online!](https://tio.run/##y0rNyan8//9w28MdXY@a1hzefmzSwx3d@v@PTnq4c4bO4fasRw1zFGztFB41zNWM/P8/OjraUMdIxzhWRyHaRMdUxyw2VodLITraUkfBzEhHwUBHASxlZApkAIWgsrrmOgomOgpARRYgWUMzHQVDHQVdoAZTqAoLIFvXEiQJVGpqBDIGKBELAA "Jelly – Try It Online")**
### How?
```
ÆḊ€÷ƒḋ/ - Link: pair of lists, V
€ - for each vector:
ÆḊ - get its norm
/ - reduce V by:
ḋ - dot-product
ƒ - starting with the dot-product reduce the norms by:
÷ - division
```
---
Here's a dyadic version, also at seven bytes:
```
,ÆḊ€÷ƒḋ
```
[Try it online!](https://tio.run/##y0rNyan8/1/ncNvDHV2PmtYc3n5s0sMd3f@PTnq4c4bO4eX6WY8a5ijY2ik8apirGfn/f3R0tKGOkY5xrI5CtImOqY5ZbKwOl0J0tKWOgpmRjoKBjgJYysgUyAAKQWV1zXUUTHQUgIosQLKGZjoKhjoKukANplAVFkC2riVIEqjU1AhkDFAiFgA)
[Answer]
# MATLAB, 37 32 bytes
-5 bytes thanks to [@loopywalt](https://codegolf.stackexchange.com/questions/259755/cosine-similarity-of-two-vectors/259849#comment572456_259849)
```
@(a,b)sum(diag(a'*b))/norm(a'*b)
```
Instead of padding `a` or `b` to the length of the other, or cropping it, which should be equivalent in the numerator, we take the outer product of the two vectors, then sum the diagonal (ie trace). This is equivalent to the dot product of the two vectors cropped to the shortest length.
Unfortunately, this doesn't work if the two vectors have different length, `trace` requires a square matrix:
```
@(a,b)trace(a'*b)/norm(a'*b)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 7 bytes
```
*□²Ṡ√Π/
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJB4biLcyIsIiIsIirilqHCsuG5oOKIms6gLyIsIiIsIlsxLDIsM10sIFs0LDUsNl1cbls5LCA2MiwgMCwgM10sIFsyNSwgMywgNl1cblstNywgNCwgOSwgOF0sIFsxNiwgMSwgLTIsIDVdXG5bODIsIC05XSwgWzcsIDUyLCAzXSJd)
Link includes test cases. `ḋ` flag prints numbers as decimals (for convenience) rather than as rationals, but is not needed.
*-1 thanks to @lyxal*
#### Explanation
```
*□²Ṡ√Π/ # Implicit input
* # Vectorised multiplication
□² # Input list squared
Ṡ√ # Sum and square root
Π # Product
/ # Divide
# s flag sums the list
# Implicit output
```
Old:
```
Þ•2(?²∑√)*/ # Implicit input
Þ• # Dot product: seems to handle the padding with 0s
2( ) # Repeat twice:
? # Next input
² # Squared
∑ # Summed
√ # Square rooted
* # Multiply both
/ # Divide
# Implicit output
```
[Answer]
# [Python](https://www.python.org) NumPy, 50 bytes
```
lambda a,b:(z:=a*b[:,1>0]).trace()/(z*z).sum()**.5
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5BboMwEEX3nGKWNhpocDAFpPQijhWZtqhIxVjGLOAq3SBFiXql3iZ23NW8mXnzNT93s7qvSe_X_nS-La7P6j_2rcbuQ4HCriVbe1JpJ1os3g6S5s6q909CX8iWbjSfl5HQNM35_-XvMJrJOtDLaFZQM2iTJP1kQxQMGoQQBTI8SgRRIsdKBhINQsUQDgjPDeMe_Cgus1eEEsE7deiLCqFAyLzPo1B7zJqA3uQshEjZJgDGDtqRnmiT24tQEiN0ktL4777H-gA)
[Answer]
# [R](https://www.r-project.org), 40 bytes
```
\(x,y)sum(diag(z<-x%*%t(y)))/norm(z,"f")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Xc_NCoJAEAfwe08xGMJszJqurh-QPUkQYRkeVPAD1EMv0sUOnXqNXqK3adPI6jTL8P_9hz1fiv4W5WWSHbZlkobXuoq5_8ANNtSysk5xn-yO2K14oy_0ClvG2DLLixQ70mKNvfP3qQIjtEiQzQgidEiSyxjMIVzDyTQCz5n9RAMCVxCYBCMQUr3U7ssI-Uu4R-AQKOkPxHIJLAKuauSHcdOw_5yvAjwYiGqQ4nVyumIKZ_xL34_zCQ)
R port of [Cris Luengo's MATLAB answer](https://codegolf.stackexchange.com/a/259849/67312).
# [R](https://www.r-project.org), 48 bytes
```
\(x,y)(x%*%x*y%*%y)^-.5*(x*y)%*%!seq(!x)-seq(!y)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Xc87DsIwDAbgnVO4QpXiyqnSkPQxlJMgGKoidQAEBSlduAhLGZi4BpfgNpgWUcoSx5G_38rlemjvxa6utuWqrjb57XRcy_SpFsJRg8L5ge-Chs8GlzK0geAOufXqci88h7KrDX7cY4gShYhI0wwJCmHIUowIU8jncFZhlpjJaDQjiDWBIuiBtnzjtx-j7ZjIhMAQsEw7EsUEEYHkGPtlUoWzP5fygMw6wglWv1cOW5Q2_V_atq8v)
A slight rearrangement and golf of [Dominic van Essen's answer](https://codegolf.stackexchange.com/a/259770/67312), posted at his request.
Works by maximizing operator precedence and vector recycling.
[Answer]
# JavaScript (ES6), 76 bytes
Expects `(a)(b)`.
```
a=>b=>[...a+b].reduce(t=>t+~~a[i]*~~b[i++]/h(...a)/h(...b),i=0,h=Math.hypot)
```
[Try it online!](https://tio.run/##Tc5NbsMgEAXgvU8xS6gHTPyTxKrwrsueALEAxw6uohA5tFI3vrqLa9cqGyT43pv5MF/m2Y7DI7C7v3RzL2cjGysbxTk3qdV87C6fbUeCbEI6TUYN@mWarBrSVGeOLIqut6U4SIFOvpvguPt@@EDnV5UAKFAHhByh0AiqRKgQjhr2E1@zDCbB61O58jqC6MUWyWOg2DM7z6tVsxNCbI2h86IPR4Q4j8WCSv9pJnix8XP8YPUiY676XevfLrCVi7xMdMJ7P76Z1hGiDILVFGQDrb8//a3jN38lPTGUWErp/AM "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // outer function taking the 1st vector a[]
b => // inner function taking the 2nd vector b[]
[...a + b] // build a large enough array to make sure that we
// iterate on all values of the largest vector
.reduce(t => // using t as an accumulator, for each entry in there:
t + // add to t:
~~a[i] // either a[i] or 0
* ~~b[i++] // multiplied by either b[i] or 0 (then increment i)
/ h(...a) // divided by hypot(a)
/ h(...b), // divided by hypot(b)
i = 0, // start with t = i = 0
h = Math.hypot // h is an alias for Math.hypot
) // end of reduce()
```
[Answer]
# [R](https://www.r-project.org), 52 bytes
*Edit: +2 bytes to fix when either vector is length-1, thanks to Giuseppe*
```
\(x,y,`?`=sum)?x*y*(seq(!x)==seq(!y))/(?x^2*?y^2)^.5
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Xc9LDoIwEAbgvacY46YlU4TS8ljUXsQgCcGEBRpFErrxIm5w4cpreAlvYwUj4momk_n-yVyux-6e7-tyV2zqslK35rRl8VOsSYsGM52puqmobh3jkLo4kHlLleobQ-mS6DbljjYpp6krP_YxxpGc-MgxoAg5ESgxpBQWoFZw9twkErPJaoIQcgQPYQBc2s7OfgyXU8IiBIFgZdwTP0TwEZiNkV_GPDf4c7FdYElPbILk75PjFY-L4ZeuG-oL)
[Answer]
# TI-BASIC (TI-84), ~~43~~ 41 bytes
Padding is expensive.
```
:Prompt A,B
:max(dim(ʟA),dim(ʟB→dim(ʟA
:Ans→dim(ʟB
:sum(ʟAʟB/√(sum(ʟB²)sum(ʟA²
```
Example usage:
```
prgmCOSSIM
A=?{9,62,0,3}
B=?{25,3,6}
.2531554274
```
For comparison:
## TI-BASIC (TI-84), no padding, ~~19~~ 17 bytes
Errors when the inputs aren't equal length. Takes the first input via `Ans`.
```
:Prompt A
:sum(ʟAAns/√(sum(Ans²)sum(ʟA²
```
Example usage:
```
{1,2,3}:prgmCOSSIM
A=?{4,5,6}
.974631462
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 17 bytes [SBCS](https://github.com/abrudz/SBCS)
```
↓∘↑+.×.÷.5*⍨1⊥¨×⍨
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9Q2@VHHjEdtE7X1Dk/XO7xdz1TrUe8Kw0ddSw@tODwdyAQA&f=LcyxEcAgDATB3FVcCJklkEAN0R49UBmYcfj7MzdIglIyqWJ4fgYpcOW9qEb5dc1GJeiHxRHWVOxeXc@I4w37Yhs&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
Lots of dots.. .
Input an array containing the two vectors.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes
```
z₀×ᵐ+D&{^₂ᵐ+√}ᵐ×;D↔/
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v@pRU8Ph6Q@3TtB2UauOe9TUBGI@6phVC6QPT7d2edQ2Rf///@hoCyMdhXjLWB2FaHMdBVMgxzg29n8EAA "Brachylog – Try It Online")
### Explanation
```
z₀×ᵐ+D&{^₂ᵐ+√}ᵐ×;D↔/
Input is a list of two lists representing the two vectors
z₀ Zip the two vectors, clipping to the shorter length
×ᵐ Multiply each pair of corresponding values
+ Sum the products
D Save this value as D (for Dot product)
& Start over with the original list of lists
{ }ᵐ Do this to each vector:
^₂ᵐ Square each of its elements
+ Sum the squares
√ Get the square root of the sum
× Multiply the two results
;D Pair with D from earlier
↔ Reverse the list, putting D first
/ Divide
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~13~~ 11 bytes
*-2 bytes thanks to FryAmTheEggman*
```
cF+s*MCQ.aM
```
[Try it online!](https://tio.run/##K6gsyfj/P9lNu1jL1zlQL9H3///oaAsjHQVdy1gdhWhzHQVTIMc4NhYA "Pyth – Try It Online")
### Explanation
```
cF+s*MCQ.aMQ # implicitly add Q
# implicitly assign Q = eval(input())
CQ # transpose the input, truncating to the shortest element
*M # map each element to its product
s # sum the elements
+ # prepend this to
.aMQ # the input elements mapped to their norms
cF # fold this over division
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-x`, 17 bytes
```
$*_MS Zg/RT$+*SQg
```
Takes the vectors as two command-line arguments, each one formatted as a Pip list. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboVS7IKlpSVpuhYbVbTifYMVotL1g0JUtLWCA9Mh4lDp7dFK0RZG1rqWsUo6CkrR5tamRtbGsXDdAA)
### Explanation
We use the equivalent formula \$\sum\_{i=1}^n\frac{A\_i}{\sqrt{\sum\_{i=1}^nA\_i^2}}\frac{B\_i}{\sqrt{\sum\_{i=1}^nB\_i^2}}\$:
```
$*_MS Zg/RT$+*SQg
; g is list of command-line args, evaluated (-x flag)
SQg ; Square each value in the list of two vectors
$+* ; Sum each squared vector
RT ; Take the square root of each sum
g/ ; Divide the list of two vectors by that list of two magnitudes
Z ; Zip (transpose) the list of two vectors, pairing up corresponding
; elements and trimming the longer vector to the length of the
; shorter one (which, at the dot product stage, is equivalent to
; right-padding the shorter one with zeros)
MS ; Map this function to each pair of values and sum the results:
$*_ ; Take the product of the values
```
[Answer]
# [Python](https://www.python.org), 73 bytes
*-95 bytes thanks to `Neil`, -3 bytes thanks to `att` and -3 bytes thanks to `xnor`.*
This works despite the `zip` function stopping at the shorter sequence, since we right pad with `0`. Essentially, the elements of the longer sequence do not affect the calculation.
```
lambda a,b:d(a,b)/(d(a,a)*d(b,b))**.5;d=lambda*a:sum(map(int.__mul__,*a))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY9BDoJADEX3nqLLmUlBQQYBwwE8w0jIEEIkYYAgLLyAl3BDYvRO3sYOsGn_b19-2te3f4y3rp3fVXr9TGPlRL9Lo01RatBYJCWjyvfMds1FyQqyXAhXnst05YRO7pNhRvesbkc3z83U5DkKzfkW-Ky6waZB3YJSykMfjxmCClBimFmlYoTQRzggLBtfkqDRunROCAECMZH1XojgITjEyxWISDqxlURK34ZkWbID6Ac6iVXLE9s187z2Pw)
*P.S. I edited out the other versions of this answer made with `scipy`, `numpy` and `scikit-learn`, because they were significantly longer.*
[Answer]
# [Julia 1.0](http://julialang.org/), ~~68~~ ~~60~~ ~~44~~ 43 bytes
```
x^y=sum(prod,zip(x,y))
a\b=a^b/√(a^a*b^b)
```
[Try it online!](https://tio.run/##hc9LCoMwEAbgvaeYZSyJjbG@FkLv4QMS2oXFohiF2BP0DD1eL2InKRSE0mYRkmH45p/L3LUyNOtqmqXQ85UMY3@it3Yghi6@78lKFbJR@@f9QWQjd6pR/nqUWp/HCVotB@w3BEoIKYCgENWAp4LygH@I8Upq@wLgQZ5iUU59V/CAh773jckpJMhwJyEjLBFtGFf6zbAUW3AYapljwgQLGJGhHaPEeBD9ZzLsZrnb6L2UZWNhE33ScLFZan0B "Julia 1.0 – Try It Online")
* The power operator `^` is redefined for the intermediate function. This adds a few bytes where a square or square root is needed, but its high precedence in order of operations cuts down on parentheses used.
+ [Documentation for operators](https://docs.julialang.org/en/v1/manual/mathematical-operations/)
+ [Source code with all supported operators](https://github.com/JuliaLang/julia/blob/def2ddacc9a9b064d06c24d12885427fb0502465/src/julia-parser.scm)
* `zip` is used to accommodate vectors with different lengths.
+ Otherwise, `x^y=sum(x.*y)` could be used.
Alternatively, [`LSHFunctions.cossim`](https://docs.juliahub.com/LSHFunctions/nLuMy/0.1.2/similarities/cosine/) could be adapted for this challenge.
* -8 bytes thanks to Giuseppe: rewrite with an improved formula
* -16 bytes (!!) thanks to Giuseppe: `sum` supports a calling function
* -1 byte thanks to MarcMush: replace `sqrt` with `√`
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~110~~ 61 bytes
saved 49 bytes thanks to the comment
```
@(A,B)A(1:(p=min(numel(A),numel(B))))*B(1:p)'/norm(A)/norm(B)
```
[Try it online!](https://tio.run/##XY9dC4IwFIbv/RW7a4tpbVPTQmjnb0QXEgmCX5gF/Xp754So3WznnOd5D@tvU/m6zxUrWBRF85lbScJydeRD0dYd757tveFWSP8ggbMlzAex2XX92GLmbxKzVYi5KMm0ZOZ6CmipY8kSyVLUj7qtm3Ksp7cbVNwCJSWCwGoH5qBg7ld56Wmo5t/W3gZL2tnGkeFBMqxCSObspadSybAjBJn8JBifgGQyLiF2dAYszJ28lMhL1o98xdiLWESxCOYP)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
Þ•∇"²Ṡ√Π/
```
Edit: Thunno ninja'd me but kinda want to leave my answer here as it (was) shorter
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLDnuKAouKIh1wiwrLhuaDiiJrOoC8iLCIiLCJbOSwgNjIsIDAsIDNdXG5bMjUsIDMsIDZdIl0=)
**How it works:**
```
Þ•∇"²Ṡ√Π/
Þ• Calculate the dot product
∇ Shift stack
" Pair the vectors
²Ṡ√ Square, take vectorised sum and square root
Π/ Push product and divide
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 20 bytes
```
Đ←Đ04Ș*Ʃ⇹²Ʃ↔+²Ʃ⇹↔*√/
```
[Try it online!](https://tio.run/##K6gs@f//yIRHbROOTDAwOTFD69jKR@07D20CUm1TtMF0@04gU@tRxyz9//@jdc11THQsdSxiuaINzXQMdXSNdExjAQ "Pyt – Try It Online")
```
Đ←Đ04Ș Gets stack set up for calculations
*Ʃ A·B
⇹²Ʃ↔+²Ʃ⇹↔*√ ||A||*||B||
/ divide; implicit print
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~16~~ 14 bytes
```
I∕Σ×θη₂ΠE²ΣXA²
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjejA4oy80o0nBOLSzRcMssyU1I1gktzNUIyc1OLNQp1FDI0NXUUggtLE4tSg_LzSzQCivJTSpNLNHwTCzSMgDJAtQH55alFGp55BaUlGkDFRppQYL2kOCm5GGrR8mgl3bIcpdjd0dGWOgpmQK0GOgrGsToK0UamQAZQKDYWohIA) Link is to verbose version of code. Explanation:
```
θ First input
× Vectorised multiply by
η Second input
Σ Take the sum
∕ Divided by
² Literal integer `2`
E Map over implicit range
A Next input
X Vectorised raise to power
² Literal integer `2`
Σ Take the sum
Π Take the product
₂ Take the square root
I Cast to string
Implicitly print
```
[Answer]
# [Factor](https://factorcode.org) + `math.similarity`, 17 bytes
```
cosine-similarity
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owU2r0GBPP3crhYKi1JKSyoKizLwShdzEkgy94szczJzEosySSgVrLq5qBQsjBV1LhVqFagVzBVMjBWOF2qWlJWm6FhuT84sz81J1Eeoh4gv1IPSCBRAaAA)
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 14.5 bytes (29 nibbles)
```
^/^+*100!$_*~*;~$+.$^$~$_-2
```
Nibbles only handles integers, and perhaps isn't the ideal language to calculate a value that will always lie in the range between `-1` and `1`.
So this program outputs the cosine similarity multiplied by 100: the extra code for this costs +3.5 bytes - without it, the program would be `/+!$_*^*;~$+.$^$~$_-2` (11 bytes), but can only output to an accuracy of zero decimal places, so either `1`, `0` or `-1`.
```
^/^+*100!$_*~*;~$+.$^$~$_-2
# First get the dot-product multiplied by 100:
! # zip together
$_ # arg1 and arg2
* # by multiplication
*100 # multiply each element by 100
+ # and get the sum
^ ~ # and then square the dot-product;
# Now get the squares of the product of the magnitudes:
;~$ # apply to arg1 and save as function:
.$ # map over each element:
^$~ # square
+ # and sum the squared elements
$_ # apply the same function to arg2
* # and multiply the two results together;
/ # Now divide the squared 100x dot-product
# by the squares of the product of the magnitudes
^ -2 # and return the square-root of the result
```
[](https://i.stack.imgur.com/0esoD.png)
[Answer]
# [Raku](https://raku.org/), 45 bytes
```
->\a,\b{sum(a Z*b)/sqrt sum(a Z*a)*sum b Z*b}
```
[Try it online!](https://tio.run/##NcxBCoMwFATQqwwixUhCTTRRQXOQVpEIzUppq@1CrGdPDeLqz7yB/3pMg3LjgotF7ZhuDG36df6OkcEt7sl1fk8fnN2QeI/o/bS52SwIwu6etBT74S1qjdXiF3ZbAPucEFUcAqmmqDJIKE3obiWUQHKwkEhPZzkylCi8cwUOJiCPqRBgpfcc0j8k7g8 "Perl 6 – Try It Online")
This is a straightforward translation of the cosine similarity formula. `x Z* y` zips two lists together with multiplication, and `sum` and `sqrt` are self-explanatory.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), ~~20~~ 17 bytes
*-3 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)*
```
D←+´⊣×≠⊸↑
D÷×○√○D
```
The first line defines a helper function; the second line is the solution, an anonymous tacit function that takes two lists of numbers as left and right arguments. [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=ROKGkCvCtOKKo8OX4omg4oq44oaRCkYg4oaQIETDt8OX4peL4oia4peLRAoKODLigL/CrzkgRiA34oC/NTLigL8z)
### Explanation
The helper function `D` calculates the dot product of two vectors (or, given one argument, the dot product of a vector with itself). The default behavior of `↑` turned out to be *very* convenient here.
```
D←+´⊣×≠⊸↑
D← Assign this function to D:
≠⊸↑ Take (length of left arg) elements from (right arg)
If left arg is shorter, trims right arg to that length
If left arg is longer, pads right arg with zeros
⊣× Multiply itemwise with left arg
+´ Sum
D÷×○√○D
○D Apply D to each argument (i.e. multiply it by itself and sum)
○√ Apply square root to each of those sums (magnitude of each vector)
× Multiply those two results
D Apply D to both arguments (i.e. get their dot product)
÷ Divide the dot product by the product of magnitudes
```
[Answer]
# [Arturo](https://arturo-lang.io), 69 bytes
```
$[a b][//∑map couple a b'p->∏p∏map@[a b]=>[sqrt∑map&'x->x^2]]
```
[Try it](http://arturo-lang.io/playground?5ojPMT)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
í*V x÷NËx²¬Ã×
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=7SpWIHj3Tst4sqzD1w&input=Wy03LCA0LCA5LCA4XQpbMTYsIDEsIC0yLCA1XQ)
[Answer]
# [jq](https://stedolan.github.io/jq/), 68 bytes
```
(transpose|map((.[0]*.[1])?)|add)/(map(map(.*.)|add|sqrt)|.[0]*.[1])
```
[Try it online!](https://tio.run/##RYwxDsMgDEX3nMIjRA4NNJBk6kEsD0jpUqltEjJyd2pYOlj6eu/Jr6MUdZ3xk/ZveuZ33JUyNHJvyLJ@6By3Td9U5fVMbxrK6Tgvnf9lKUQWHd4ZgSb0GJg7ohUhOIQRoQnnZQhqbpgRJgRJlupsQLAIg@S@@UXWsFYloXf1BXc/ "jq – Try It Online")
`transpose` pads the arrays with `null`s, which we then simply remove with `?` when the multiplication fails, instead of replacing with zero.
[Answer]
# JavaScript, 175 bytes
```
(e,r)=>(l="length",p=(e,r)=>Array.from({...e,[l]:r[l]},e=>e??0),e[l]<r[l]?e=p(e,r):r=p(r,e),e[_="reduce"]((e,$,c)=>e+$*r[c],0)/(e[_]((e,r)=>e+r*r,0)*r[_]((e,r)=>e+r*r,0))**.5)
```
Try it:
```
c=
// start code
(e,r)=>(l="length",p=(e,r)=>Array.from({...e,[l]:r[l]},e=>e??0),e[l]<r[l]?e=p(e,r):r=p(r,e),e[_="reduce"]((e,$,c)=>e+$*r[c],0)/(e[_]((e,r)=>e+r*r,0)*r[_]((e,r)=>e+r*r,0))**.5)
// end code
console.log(c([1,2,3], [4,5,6]))
console.log(c([9, 62, 0, 3], [25, 3, 6]))
console.log(c([-7, 4, 9, 8], [16, 1, -2, 5]))
console.log(c([82, -9], [7, 52, 3]))
```
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), ~~17~~ 16 bytes
```
÷/×√∩/+⍉×.⟜/×⬚0⊟
```
[Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAgw7cvw5fiiJriiKkvK-KNicOXLuKfnC_Dl-KsmjDiip8KCmYgWzEgMiAzXSBbNCA1IDZdCmYgWzkgNjIgMCAzXSBbMjUgMyA2XQpmIFvCrzcgNCA5IDhdIFsxNiAxIMKvMiA1XQpmIFs4MiDCrzldIFs3IDUyIDNdCg==)
] |
[Question]
[
# Challenge
Consider the rainbow as seven colours, represented by strings as `Red Orange Yellow Green Blue Indigo Violet`.
Your task is to create a program that receives one of these colours as input and outputs next in order rainbow colour. This includes overlapping `Violet -> Red`
# Input
A string containing one of rainbow colours.
# Output
The next in order colour of the rainbow.
# Rules
* Colour names are case sensitive. They must match the case included in this post.
* The input will always be valid. Any behavior is allowed for invalid input.
* This is code golf, so the shortest amount of bytes wins!
# Example Input and Output
```
Input -> Output
Red -> Orange
Orange -> Yellow
Yellow -> Green
Green -> Blue
Blue -> Indigo
Indigo -> Violet
Violet -> Red
```
[Answer]
# JavaScript, 68 bytes
```
s=>'RedOrangeYellowGreenBlueIndigoVioletRed'.match(s+'(.[a-z]*)')[1]
```
For input `"Red"`, this function first construct an RegExp `/Red(.[a-z]*)/` to match the string `'RedOrangeYellowGreenBlueIndigoVioletRed'` and then return the first capture result.
```
f=
s=>'RedOrangeYellowGreenBlueIndigoVioletRed'.match(s+'(.[a-z]*)')[1]
document.write('<table><tr><th>Input<th>Output')
for(i='Red';;){
document.write(`<tr><td>${i}<td>${i=f(i)}`);
if(i=='Red')break;
}
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~58~~ 57 bytes
```
#!/usr/bin/perl -p
$_={(Red,Orange,Yellow,Green,Blue,Indigo,Violet)x2}->{$_}
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3rZaIyg1Rce/KDEvPVUnMjUnJ79cx70oNTVPxymnNFXHMy8lMz1fJywzPye1RLPCqFbXrlolvvb/f4jIv/yCksz8vOL/ugX/dX1N9QwN9AwA "Perl 5 – Try It Online")
Now that the challenge has been changed to be cyclic the regex solution
```
say RedOrangeYellowGreenBlueIndigoVioletRed=~/$_(.[a-z]+)/
```
isn't optimal anymore (due to the double `Red`)
Also 57 bytes:
```
#!/usr/bin/perl -p
$_=(Indigo,Blue,Violet,Yellow,Orange,Red,Green)[ord>>2&7]
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lbDMy8lMz1fxymnNFUnLDM/J7VEJzI1Jye/XMe/KDEvPVUnKDVFx70oNTVPMzq/KMXOzkjNPPb/f6Dov/yCksz8vOL/ugX/dX1N9QwN9AwA "Perl 5 – Try It Online")
[Answer]
# [Python](https://docs.python.org/2/), 79 bytes
```
z="Red Orange Yellow Green Blue Indigo Violet".split()*2
dict(zip(z,z[1:])).get
```
[Try it online!](https://tio.run/##ncyxCsIwEADQvV9xdGkisWDHQh1cxElwEEQcxFziQbiEeGLMz8d/8H3AS195Rp5aq0t/QgvHfGePcMEQ4gf2GZFhF94IB7bkI5wpBpR@fKVAovRq6txi6SGqUlLV1Otmvmk9epTmYoYCxPBPPHeQMrFAMcN6Oxinim4/ "Python 2 – Try It Online")
Handles `Violet -> Red`. The desired function is given anonymously in the second line.
---
**80 bytes**
```
lambda x:"Red Orange Yellow Green Blue Indigo Violet Red".split(x)[1].split()[0]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCSikoNUXBvygxLz1VITI1Jye/XMG9KDU1T8EppzRVwTMvJTM9XyEsMz8ntUQBqFRJr7ggJ7NEo0Iz2jAWytaMNoj9n5ZfpFChkJmnQIKBMMM0rbgUCooy80oUKnTUde3UddKA5v8HAA "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 56 bytes
```
{<Indigo Blue Violet Yellow Orange Red Green>[.ord/4%8]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2sYzLyUzPV/BKac0VSEsMz8ntUQhMjUnJ79cwb8oMS89VSEoNUXBvSg1Nc8uWi@/KEXfRNUitvZ/cWKlgpJKvIKtnUJ1moZKvGatkkJafpGCDUg5VCfUHLBmiAVQyyD22P0HAA "Perl 6 – Try It Online")
Exploits the fact that bits 2-4 of the ASCII codes of each color's first letter happen to map to 0-6.
```
say map (*.ord +> 2) % 8, <R O Y G B I V>
# (4 3 6 1 0 2 5)
```
Here's a nice non-competing solution that uses "purple" instead of "indigo" and "violet" (38 chars, 59 bytes):
```
{'üçéüß°üíõüíöüíôüíúüçé'.uninames~~m/$^a.\S+.<(\S+/}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wv3D/N6@D/OXL/wwf9JsIJ4FxDOBeA5IXF2vNC8zLzE3tbiuLldfJS5RLyZYW89GA0jq1/4vTqxUUFKJV7C1U6hO01CJ16xVUkjLL1KwCXJ1UfAPcvRzd1WIdPXx8Q9XcA9ydfVTcPIJdVUICA0K8HG1@w8A "Perl 6 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, ~~62~~ 60 bytes
-2 by Asone Tuhid.
```
p"RedVioletIndigoBlueGreenYellowOrangeRed"[/.[a-z]+(?=#$_)/]
```
[Try it online!](https://tio.run/##KypNqvz/v0ApKDUlLDM/J7XEMy8lMz3fKac01b0oNTUvMjUnJ7/cvygxLz0VqEYpWl8vOlG3KlZbw95WWSVeUz/2/3@g@L/8gpLM/Lzi/7p5AA "Ruby – Try It Online")
Regex approach looks promising for Ruby too. However, I arrived at a shorter solution using a lookahead and directly printing the match, rather than playing with capturing groups. The list of colors is in reverse direction since lookahead is 1 byte cheaper than lookbehind.
[Answer]
# [Red](http://www.red-lang.org), 87 bytes
```
func[c][print first find/tail[Red Orange Yellow Green Blue Indigo Violet Red]to-word c]
```
[Try it online!](https://tio.run/##JcwxCsMwDEDRPacQ3kP3jl1Kp0CHQjEegi0Hg5CK6pDjO468SB8hnmJqb0w@TPne8s7Rx@B/WrhCLvq/JqdbXQv5/gaLrrwhfJFIDngqIsODdoQXp7IJfIoQVuivocp8iCaIoWVw/eKmvgdgORBLg6wuzGKAlgN17QQ "Red – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes
```
“†¾›ÈŠÛˆ¨‡—ëßigo°Íolet“#™DIk>è
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcOcRw0LDu171LDrcMfRBYdnn247tOJRw8JHDVMOrz48PzM9/9CGw735OaklQJXKj1oWuXhm2x1e8f9/WCZIEAA "05AB1E – Try It Online")
**Explanation**
```
“†¾›ÈŠÛˆ¨‡—ëßigo°Íolet“ # push a string of colours
# # split on spaces
‚Ñ¢ # title-case each
D # duplicate
Ik # get the index of the input
> # increment
è # get the element at that index
```
[Answer]
# Excel, 85 bytes
```
=CHOOSE(MOD(CODE(A1),12),"green","indigo","yellow",,,"orange","blue",,"violet","red")
```
Uses lowercase names.
Same approach, with Uppercase letters 86 bytes:
```
=CHOOSE(MOD(CODE(A1),12),"Violet","Red",,,"Green","Indigo","Yellow",,,"Orange","Blue")
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~80 71~~ 75 bytes
Thanks to Laikoni for shortening 9 bytes!
```
g x=snd(span(/=x)$words"Red Orange Yellow Green Blue Indigo Violet Red")!!1
```
[Try it online!](https://tio.run/##VZDBasMwEETv/orR0oN9KvkAXXIJISGGBgq9xaCNbaJIwZKJ@/WuHLki0m00b5eZ7Rp3Y63nucUknVGlezSm/JRT9fG0g3L0xQr10JiW8RNA@8RuYDbY6pGxN6pvLb57q9kjoFQJsZknXFxnR622fMEvJB6jP/vhaFD2V0yQMvz6Lmyh@kBg7Rh0sh71QQhBVVHcm96EOWULhNdiiUHvWylmon9/lRkS8yZklRny6pKIqDJgqZn8l8jseIAErDJD4nESssoMWcoV8x8 "Haskell – Try It Online")
---
Another solution, slightly more idiomatic, but I could not get it shorter:
```
data R=Red|Orange|Yellow|Green|Blue|Indigo|Violet deriving(Enum,Read,Eq)
succ.read
```
It needs to derive `Read` because of the requirement that the input is a string and at least `Eq` or `Show` in order to either test for equality or show the result.
[Answer]
## [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~65~~ 58 bytes
```
$
(.[a-z]+)
L$:`RedOrangeYellowGreenBlueIndigoVioletRed
$1
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F@FS0MvOlG3KlZbk8tHxSohKDXFvygxLz01MjUnJ7/cvSg1Nc8ppzTVMy8lMz0/LDM/J7UEqIZLxfD/fxANUcwFUc0FVs4FUs8F0cAF0QEA "Retina – Try It Online")
### Explanation
```
$
(.[a-z]+)
```
We start by appending `(.[a-z]+)` to the input, thereby turning it into a regex which matches the input colour, immediately followed by exactly one more colour (capturing the latter).
```
L$:`RedOrangeYellowGreenBlueIndigoVioletRed
$1
```
Now the `:` swaps the stage's input with its own regex. So the previous result becomes the regex and it's matched against the list of colours. The (single) match gets replaced with its first capturing group (i.e. the next colour in the cycle) and returned. Output at the end of the program happens automatically.
[Answer]
# Vim, 59 56 53 52 Bytes
-1 byte thanks to tsh
```
2IYellow Green Blue Indigo Violet Red Orange *<Esc>**wywVp
```
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 77 bytes
```
s->"Red Orange Yellow Green Blue Indigo Violet Red".split(s)[1].split(" ")[1]
```
[Try it online!](https://tio.run/##Nc/BaoQwEAbgu0/xExC0aKDXpvXQQ0sPpVChUJY9pBptbEzEjFuWss9u1biHMBlmMt@kkyeZd/XPrPvBjYRuyflE2vBmshVpZ/mNiCojvcer1BZ/ETBMX0ZX8CRpCSena/RLLSlp1LY9HCHH1qdbK/C0z7kP1SyEAg0eZp8X7F3VeBulbRU@lTHuF8@jUhaPZlJ4sbVuHT60M4qwtDLuB6Mp8enh9rjfGdiazWLzGjfui4CUJ9xhJUQgRCDERoiVEIEQgRCl6xV9L4@vEBMsvX4FKM@eVM/dRHxYCGoSFnvkBWIfW5ZtYoaGy2Ew52TN0jSsdYnWc5n/AQ "Java (JDK 10) – Try It Online")
## Credits
* -10 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
* -1 byte thanks to [Okx](https://codegolf.stackexchange.com/users/26600/okx)
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 23 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
k‰³d∆|ΝμHō↑≥░δ÷f‘θ⁽,WIw
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=ayV1MjAzMCVCM2QldTIyMDYlN0MldTAzOUQldTAzQkNIJXUwMTREJXUyMTkxJXUyMjY1JXUyNTkxJXUwM0I0JUY3ZiV1MjAxOCV1MDNCOCV1MjA3RCUyQ1dJdw__,inputs=Qmx1ZQ__)
Explanation:
```
...‘θ⁽,WIw
...‘ push "red orange yellow green blue indigo violet"
θ split on spaces
‚ÅΩ uppercase the 1st letter of every item (SOGLs dictionary only has lowercase words)
,W get the inputs index in the array
I increment
w and get that item in the array, wrapping if necessary
```
[Answer]
# [Coconut](http://coconut-lang.org/), 79 bytes
```
s->"# Violet Red # # Green Indigo Yellow # # Orange Blue".split()[ord(s[0])%12]
```
[Try it online!](https://tio.run/##S85Pzs8rLfmfZhvzv1jXTklZISwzPye1RCEoNUVBGQjdi1JT8xQ881Iy0/MVIlNzcvLLweL@RYl56akKTjmlqUp6xQU5mSUamtH5RSkaxdEGsZqqhkax/9PyixQqFDLzFJRAhkE1QI2AGAvSDTMbYi/cLCsuhYKizLwSjQoddV07dZ00jQpNzf8A "Coconut – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 28 bytes
```
S!o→€⁰w¨ṙ}ΘΞĠ«ẇ₇G²€ḃλBżḃIÿö⌉
```
[Try it online!](https://tio.run/##AUkAtv9odXNr//9TIW/ihpLigqzigbB3wqjhuZl9zpjOnsSgwqvhuofigodHwrLigqzhuIPOu0LFvOG4g0nDv8O24oyJ////VmlvbGV0 "Husk – Try It Online")
Maybe there are better options for managing the arguments, but this is the best I could find
### Explanation
```
S!o→€⁰w¨ṙ}ΘΞĠ«ẇ₇G²€ḃλBżḃIÿö⌉
¨ṙ}ΘΞĠ«ẇ₇G²€ḃλBżḃIÿö⌉ Compressed string with all the colors
"Red Orange Yellow Green Blue Indigo Violet"
w Split on spaces
S Pass the list to both the following functions:
€⁰ 1) Find the index of the input in the list
o‚Üí and increase it by one
! 2) Get the element of the list at the
resulting position (indexing is cyclical)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~31~~ ~~30~~ 29 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ÇôF┘≡▓ƒ◄╙>┘☼░⌂╪B<U[ÇQ╒eöΣQ╔÷n
```
[Run and debug it](https://staxlang.xyz/#p=809346d9f0b29f11d33ed90fb07fd8423c555b8051d56594e451c9f66e&i=Red%0AOrange%0AYellow%0AViolet&a=1&m=2)
This uses the ring translation instruction. It replaces each element in an array with the following one from the "decoder ring". Usually, it's used to do character replacement in a string, but it can be used on an entire string too, if it's wrapped in a singleton array.
Here's the unpacked, ungolfed, commented ascii representation of the same program.
```
] wrap input in singleton array
`5^bZ_9G*h]h%oM~X9e-0ZQJkb2` compressed string literal with color names
:.j title case and split on spaces
:t do ring translation
```
[Run this one](https://staxlang.xyz/#c=]%09wrap+input+in+singleton+array%0A%605%5EbZ_9G*h]h%25oM%7EX9e-0ZQJkb2%60%09compressed+string+literal+with+color+names%0A%3A.j%09title+case+and+split+on+spaces%0A%3At%09do+ring+translation&i=Red%0AOrange%0AYellow%0AViolet&a=1&m=2)
[Answer]
# [J](http://jsoftware.com/), 67 64 62 bytes
-2 bytes thank to FrownyFrog
```
>:&.((cut'Red Orange Yellow Green Blue Indigo Violet Red')i.<)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7azU9DQ0kktL1INSUxT8ixLz0lMVIlNzcvLLFdyLUlPzFJxySlMVPPNSMtPzFcIy83NSSxSAStU1M/VsNP9rcilwpSZn5CukKYAMUIdzwHoRXIhGda7/AA "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~109~~ 93 bytes
```
function(x){y=c("Red","Orange","Yellow","Green","Blue","Indigo","Violet");y[match(x,y)%%7+1]}
```
[Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP0@jQrO60jZZQykoNUVJR8m/KDEvPRXIiEzNyckvBzLci1JT84C0U04pSNwzLyUzPR/ICMvMz0ktUdK0rozOTSxJztCo0KnUVFU11zaMrf2fBjFPkwvIgBoJZkNNBbMhBoOZYLPBLKjxYDbMhv8A "R – Try It Online")
-16 thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) for the use of `match` advice
[Answer]
## Batch, 97 bytes
```
@set s=Red Orange Yellow Green Blue Indigo Violet Red
@call set s=%%s:*%1 =%%
@echo %s: =&rem %
```
Explanation: The `call` on the second line has the effect of substituting the parameter into the command and evaluating it, turning it into e.g. `set s=%s:Red =%`, which deletes the prefix of the string that includes the parameter. The substitution on the third line then replaces all the spaces with statement separators and comments. This works because string substitution happens before parsing.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, ~~75~~ 69 bytes
```
a=%w{Red Orange Yellow Green Blue Indigo Violet};p a[-~(a.index$_)%7]
```
[Try it online!](https://tio.run/##KypNqvz/P9FWtbw6KDVFwb8oMS89VSEyNScnv1zBvSg1NU/BKac0VcEzLyUzPV8hLDM/J7Wk1rpAITFat04jUS8zLyW1QiVeU9U89v9/iOy//IKSzPy84v@6eQA "Ruby – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/), 76 bytes
```
f(s)=match(Regex("$s(.[a-z]*)"),"RedOrangeYellowGreenBlueIndigoViolet"^2)[1]
```
[Try it online!](https://tio.run/##yyrNyUw0@/8/TaNY0zY3sSQ5QyMoNT21QkNJpVhDLzpRtypWS1NJU0cpKDXFvygxLz01MjUnJ7/cvSg1Nc8ppzTVMy8lMz0/LDM/J7VEKc5IM9ow9v9/AA "Julia 0.6 – Try It Online")
This handles the Violet->Red by recycling the string with the power `^` operator.
Here's a slightly longer solution without regexes:
```
g(s,l=split("Red Orange Yellow Green Blue Indigo Violet"," "))=l[(findin(l,[s])[1])%7+1]
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 74 bytes
```
(-split("Red Orange Yellow Green Blue Indigo Violet "*2-split$args)[1])[0]
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0O3uCAns0RDKSg1RcG/KDEvPVUhEiiTX67gXpSamqfglFOaquCZl5KZnq8Qlpmfk1qioKRlBNGlkliUXqwZbRirGW0Q@///f3WIAnUA "PowerShell – Try It Online")
Takes the string `"Red ... Violet "` and string-multiplies it out by two to properly handle the `Violet -> Red` test case. We then `-split` that string on input `$args` to give us an array of two strings. We take the second string thereof `[1]`, then `-split` that on whitespace to give us an array of strings and take the first `[0]`.
For example, for input `"Yellow"`, the first step will result in `@("Red Orange ", " Green Blue Indigo ... Indigo Violet ")`. We take the second one of that, split it on whitespace (which removes the whitespace), resulting in `@("Green", "Blue", ... "Violet")`, so taking the `[0]` one thereof results in the proper next string.
[Answer]
# IBM/Lotus Notes Formula Language, ~~79~~ 74 bytes
```
@Left(@Right("Red Orange Yellow Green Blue Indigo Violet Red ";a+" ");" ")
```
Previous version for 79:
```
R:=@Explode("Red,Orange,Yellow,Green,Blue,Indigo,Violet,Red");R[@Member(a;R)+1]
```
Takes input from an editable text field called `a`.
There is no TIO for formula language so here's a couple of screenshots.
[](https://i.stack.imgur.com/znDjS.png)
[](https://i.stack.imgur.com/wylU4.png)
[](https://i.stack.imgur.com/qqlZZ.png)
[Answer]
# PHP, 92 bytes
```
$a=" Red OrangeYellowGreen Blue IndigoVioletRed";echo substr($a,strpos($a,$argv[1])+6,6)
```
[Try it online!](https://tio.run/##JYyxCsIwEEB/5SgZLNahSxetBRdxKjgIIlKiOZJAuAtJqn/vWXF6b3i86KLIblC6r@CMBgDGpMniFUPg9zEhEhzCjAAnMt7yxXPAspTVFp@OIc@PXNJK6WZB5PwzpZN93dp7ve6arh72IvLffTgWz5RlYyA7TmXiiDQVbXumLw "PHP – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 73 bytes
```
x->"RedOrangeYellow Green BlueIndigoVioletRed".substringAfter(x).take(6)
```
[Try it online!](https://tio.run/##Lc7BCsIwDAbg@54iFA8tdDt6GDhQEPEkKAgeq6azWFvpMh2MPfvsVn8I5PAnfE9P1rhRtw5eyjj@UUGFGuI0JZwoGFcL6DOIYUe8y0NQrkZ5QWv9V@4CopMb26Lcu7upvTwbb5FY0bytIc4kE4X2Yatuj/@XKe/4lqzjbGEI8goWveaGxMDEXBmyIcs@yoIueVf@EXmVllU/dnk1WRIlSWCWAEyUJEmQWIuW9trMt2tNGHgnClJP5EsxDuMP "Kotlin – Try It Online")
Taking advantage of the fact that many colors are 6 characters, the ones that are not are prefixed with spaces to make them 6 characters long. Hopefully it's acceptable that some of the colors are outputted with spaces before them.
e.g. Red is `" Red"`, Blue is `" Blue"`
[Answer]
# SmileBASIC, ~~94~~ 84 bytes
```
C$="Red OrangeYellowGreen Blue IndigoViolet
INPUT I$?MID$(C$*2,INSTR(C$,I$)+6,6)
```
[Answer]
# [Gema](http://gema.sourceforge.net/), 67 characters
```
*=@subst{*\?<J>=\?\$2\;\?=;RedOrangeYellowGreenBlueIndigoVioletRed}
```
Sample run:
```
bash-4.4$ echo -n Yellow | gema '*=@subst{*\?<J>=\?\$2\;\?=;RedOrangeYellowGreenBlueIndigoVioletRed}'
Green
bash-4.4$ echo -n Violet | gema '*=@subst{*\?<J>=\?\$2\;\?=;RedOrangeYellowGreenBlueIndigoVioletRed}'
Red
```
# [Gema](http://gema.sourceforge.net/), 59 characters
```
R=Orange
O=Yellow
Y=Green
G=Blue
B=Indigo
I=Violet
V=Red
*=
```
Boring one. Dumbest approach ever, but quite short.
Sample run:
```
bash-4.4$ gema 'R=Orange;O=Yellow;Y=Green;G=Blue;B=Indigo;I=Violet;V=Red;*=' <<< 'Yellow'
Green
bash-4.4$ gema 'R=Orange;O=Yellow;Y=Green;G=Blue;B=Indigo;I=Violet;V=Red;*=' <<< 'Violet'
Red
```
[Answer]
# [q/kdb+](http://kx.com/download/), ~~59~~ 55 bytes
**Solution:**
```
.[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange]
```
**Examples:**
```
q).[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange]"Red"
"Violet"
q).[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange]"Orange"
"Red"
q).[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange]"Blue"
"Green"
```
**Explanation:**
Create a dictionary of colour => next colour, the input is the key to the dictionary:
```
.[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange] / the solution
.[ ; ] / apply multiple args to function
`Red`Violet`Indigo`Blue`Green`Yellow`Orange / list of colours
($) / convert to strings
2 8# / reshape into 2x8 grid
! / create dictionary
```
**Bonus:**
It's **53 bytes** in K4:
```
.[!;2 8#$`Red`Violet`Indigo`Blue`Green`Yellow`Orange]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~45~~ 43 bytes
*-2 bytes thanks to Shaggy*
```
`R‚sO√é√ŃY√ÅMwsG√é9sBluƒI˜igosVio¬§t`qs
g1+UbNg
```
[Try it online!](https://tio.run/##y0osKPn/PyHoUFOx/@G@w42HmiMPN/qWF7sf7rMsdsopPdTseWhGZnp@cVhm/qElJQmFxVzphtqhSX7p//8rAcVyUkuUAA "Japt – Try It Online")
[Answer]
# sed, 72 bytes
```
s/$/%RedOrangeYellowGreenBlueIndigoVioletRed/;s/(.+)%.*\1(.[a-z]+).*/\2/
```
[Try it Online](https://tio.run/##K05N@f@/WF9FXzUoNcW/KDEvPTUyNScnv9y9KDU1zymnNNUzLyUzPT8sMz8ntQSoRt@6WF9DT1tTVU8rxlBDLzpRtypWW1NPSz/GSP//f6ACLogpXBBjuMDmcIEM4oKYxAUx6l9@QUlmfl7xf90iAA)
**Example 1:**
Input:
```
Red
Orange
Yellow
Green
Blue
Indigo
Violet
```
Output:
```
Orange
Yellow
Green
Blue
Indigo
Violet
Red
```
**Example 2:**
Input:
```
Indigo
Yellow
Red
Red
Blue
Green
Orange
Violet
Green
Green
Green
Blue
Blue
Violet
```
Output:
```
Violet
Green
Orange
Orange
Indigo
Blue
Yellow
Red
Blue
Blue
Blue
Indigo
Indigo
Red
```
] |
[Question]
[
Your task is to sort an array containing the strings "quarter", "dime", "nickel", and "penny" any number of times in no specific order and sort them so that they are in this order: `quarter dime nickel penny` (in other words, greatest to least monetary value).
---
## Rules
1. Your program must take an array as input containing the names of U.S coins and sort them from greatest to least by monetary value.
* For those who are not from the U.S or don't use change, the values of U.S coins, from greatest to least, are:
+ Quarter: 25 cents
+ Dime: 10 cents
+ Nickel: 5 cents
+ Penny: 1 cent
2. You may sort this array in any way you wish, as long as the output is ordered by the monetary values shown above.
3. Input can be taken in any way, be it command-line arguments or STDIN.
4. An input array would be all lowercase strings, something like this:
* `quarter dime nickel nickel quarter dime penny penny`
5. The actual format of input and output is up to you.
---
## Test Cases
```
"penny nickel dime quarter"
-> "quarter dime nickel penny"
"nickel penny penny quarter quarter quarter dime dime dime dime"
-> "quarter quarter quarter dime dime dime dime nickel penny penny"
"quarter dime nickel nickel quarter dime penny penny"
-> "quarter quarter dime dime nickel nickel penny penny"
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard rules & loopholes apply.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~5~~ 3 bytes
```
ñg9
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=8Wc5&input=WydxdWFydGVyJyAnZGltZScgJ25pY2tlbCcgJ25pY2tlbCcgJ3F1YXJ0ZXInICdkaW1lJyAncGVubnknICdwZW5ueSdd)
### Explanation
I, too, have added a sorting function to my language in the last few weeks :-) `ñ` takes in an array and a function and sorts the array as if each item had been mapped through that function.
The `g` function on a string takes in a number `n` and returns the `n`th char in the string, wrapping if `n` is negative or past the end of the string. The strings can thus be aligned as follows:
```
quarterqu**a**rter...
dimedimed**i**medi...
nickelnic**k**elni...
pennypenn**y**penn...
```
The 9th char (0-indexed) of each string has been highlighted in bold. These are in the correct order, so all we have to do is `ñg9`. (Though now that I look back on it, `ñg5` would work as well...)
[Answer]
# [V](https://github.com/DJMcMayhem/V), 7 bytes
```
ú/¨qu©¿
```
[Try it online!](https://tio.run/nexus/v#@394l/6hFYWlh1Ye2v//f15mcnZqDldBal5eJZQsLE0sKkktwqBTMnNT0QgA "V – TIO Nexus")
This uses the spiffy new *sort* command I added to V around a week ago (`ú`). Sweet timing!
The way this works is by sorting every line by default sorting (ASCII values) but ignoring the first match of a certain regex. In this case, the regex is `(qu)?`, although it has some gross non-ASCII stuff to avoid using backslashes. If you ignore the first two letters of "quarter", it starts with 'a', and then all of the coins are already in alphabetical order.
# Non-competing version, 4 bytes
```
ú!/.
```
This feature was already implemented, but I hadn't tested it extensively yet so it had a bug that I only realized because of this challenge. There is no TIO link because TIO is slightly behind.
This works by reverse sorting every line but ignoring the first character on each line.
[Answer]
# Python, 36 bytes
```
lambda a:a.sort(key=lambda x:x[-5:])
```
Unnamed function that sorts the list in-place by the key function given.
The slices of each coin name are then, `arter`, `dime`, `ickel`, and `penny` - which are in alphabetical (or more importantly, ordinal) order.
[Answer]
# Bash + coreutils, 18
```
tr q b|sort|tr b q
```
* Transliterate q to b
* Sort
* Transliterate b back to q
[Try it online](https://tio.run/nexus/bash#@19SpFCokFRTnF9UUgNkJykU/v9fWJpYVJJaxJWSmZvKlZeZnJ2aA6NQpApS8/IqISQA).
[Answer]
# [Python 3](https://docs.python.org/3/), ~~42~~ ~~41~~ 38 bytes
An unnamed lambda function which takes input as a list of strings, sorts in place.
[*(Outgolfed by Jonathan Allan)*](https://codegolf.stackexchange.com/a/109057/60919)
```
lambda x:x.sort(key=lambda s:(s*2)[5])
```
**[Try it online!](https://tio.run/nexus/python3#S1OwVYj5n5OYm5SSqFBhVaFXnF9UopGdWmkLFSu20ijWMtKMNo3V/F8MVKyUl5mcnZqjUJCal1cJJQtLE4tKUosw6JTM3FQ0QkmvuCAns0RDkytNo1iTq6AoM68EyPgPAA "Python 3 – TIO Nexus")**
Other solutions I messed around with:
```
lambda x:x.sort(key=lambda s:s*(s<'q'))
lambda x:x.sort(key=lambda s:(s+'pi')[5])
lambda x:x.sort(key=lambda s:ord(s[3])%16)
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 21 bytes
```
$args|sort{($_*3)[9]}
```
[Try it online!](https://tio.run/nexus/powershell#@6@SWJReXFOcX1RSraESr2WsGW0ZW/v///@8zOTs1ByFgtS8vEooWViaWFSSWoRBp2TmpqIRAA "PowerShell – TIO Nexus")
### Explanation
Shamelessly stole the algorithm in [ETHproductions's answer](https://codegolf.stackexchange.com/a/109047/30402) (basically). I multiply each string by 3, then sort based on the 9th character of the resulting string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
6ịµÞ
```
**[Try it online!](https://tio.run/nexus/jelly#@2/2cHf3oa2H5/0/3B75/3@0emFpYlFJapG6jnpKZm4qkMrLTM5OzUFmYCgpSM3Lq4TTsQA)** (the footer, `ÇY`, joins the resulting list with line feeds for a prettier print out.)
### How?
```
6ịµÞ - Main link: list of strings
µ - monadic chain separation
Þ - sort the list of strings by the monadic function:
6ị - the sixth index - Jelly indexing is modular and 1-based
```
The Nth index of a list in Jelly is the Nth item starting at the left, counting from 1, and looping back to the start when need be. (The 0th is at the right, the -1th one left of that and so on too).
So the sixth character of `['d','i','m','e']` is `'i'` since six is congruent to two modulo four.
The sixth character of the four coins in order are quart`e`r, d`i`me, nicke`l`, `p`enny
. These are in alphabetical (or more importantly, ordinal) order.
---
Another way to achieve the same thing would be to sort by the rotated strings with `ṙ5µÞ`, where `ṙ` rotates to the right, making the strings `erquart`, `imed`, `lnicke`, and `penny`.
[Answer]
# [Python](https://docs.python.org/2/), 32 bytes
```
lambda s:s.sort(key="npr".strip)
```
[Try it online!](https://tio.run/nexus/python2#ZYwhDoAwDAA9r2imNsMDSPgJZkBJGkYpbRG8fiBQYO7M5RboYaglb@OcwTprbVePK159YNHQmitJqvZkgWlasYAg8/XyOLM66s8zbfjB85JCHlOzREuNKLGD1Rs "Python 2 – TIO Nexus") Sorts the list in place.
The idea is to use a sorting key function without a `lambda`. A good candidate was `x.strip`, which takes the string `x` and removes its the left and right edges all characters in the input. For example, `"abcdef".strip("faces") == "bcd"`.
The method `"npr".strip` takes:
```
quarter -> np
dime -> npr
nickel -> pr
penny -> r
```
which are lexicographically sorted. I found the string `npr` by brute force. `npu` and `npt` also work, and there are none shorter.
[Answer]
# Bash (+coreutils) 11 bytes
**Golfed**
```
sort -rk1.2
```
**How It Works**
Reverse sort, with the "sort key" from the second character of the first field (word) till the end of line, i.e.:
```
uarter
ime
ickel
enny
```
**Test**
```
>echo penny nickel dime quarter|tr ' ' '\n'|sort -rk1.2
quarter
dime
nickel
penny
```
[Try It Online !](http://www.tutorialspoint.com/execute_bash_online.php?PID=0Bw_CjBb95KQMVWE1MW9JXzVFajg)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 8 bytes
```
q~{5=}$p
```
[Try it online!](https://tio.run/nexus/cjam#@19YV21qW6tS8P9/tFJeZnJ2ao6SglJBal5eJRJdWJpYVJJahIOVkpmbip2KBQA "CJam – TIO Nexus")
**Explanation**
```
q~ Get and eval all input (array of coin names)
{5=}$ Sort the array by the 5th index of each element (array indices loop in CJam)
p Print the result
```
[Answer]
## Pyke, ~~9~~ ~~7~~ 5 bytes
```
.#5R@
```
[Try it here!](http://pyke.catbus.co.uk/?code=.%235R%40&input=%5B%22penny%22%2C+%22nickel%22%2C+%22dime%22%2C+%22quarter%22%5D&warnings=0)
```
.#5R@ - sort_by:
5R@ - i[5]
```
[Answer]
# Retina, 10
* 6 10 bytes saved thanks to @ETHproductions
```
q
b
O`
b
q
```
* Substitute `q` to `b`
* Sort
* Substitute `b` back to `q`
[Try it online](https://tio.run/nexus/retina#@1/IlcTlnwAkCv//LyxNLCpJLeJKycxN5crLTM5OzYFRKFIFqXl5lRASAA).
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~8~~ 7 bytes
*1 byte saved thanks to @DJMcMayhem*
```
Úçq/:m0
```
[Try it online!]
See @DJMcMayhem's [answer](https://codegolf.stackexchange.com/questions/109043/count-my-change/109046#109046) in V (~~1~~ 0 bytes shorter than mine)
[Try it online!](https://tio.run/nexus/v#@3941uHlhfpWuQb//xeWJhaVpBZxpWTmpnLlZSZnp@bAKBSpgtS8vEoICQA "V – TIO Nexus")
```
Ú " sort all lines "
ç " globally "
q/ " where there a q is matched, "
:m0 " move it to the top of the buffer "
```
Here is an older solution at 1 byte larger, but I really like it.
### [V](https://github.com/DJMcMayhem/V), 8 bytes
```
Ú/q
dGHP
```
[Try it online!]
[Try it online!](https://tio.run/nexus/v#@394ln4hV4q7R8D//4WliUUlqUVcKZm5qVx5mcnZqTkwCkWqIDUvrxJCAgA "V – TIO Nexus")
### Explanation
```
Ú " sorts the lines
```
Now the buffer will be in this format:
```
dimes
nickels
pennies
quarters
```
The only thing left to do now is to move the quarters to the top.
```
/q " search for a q "
dG " delete everything from the first quarter to the end of buffer "
HP " and paste it at the top of the buffer
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 3 bytes
```
ñé5
```
[Try it online!](https://tio.run/nexus/japt#@3944@GVpv//R6sXliYWlaQWqSuoF6Tm5VUC6ZTM3FQglZeZnJ2ag8xAKIUqgemA0RgqYwE "Japt – TIO Nexus")
---
## A couple other 3-byte solutions:
```
üÅw
```
[Try it online!](https://tio.run/##y0osKPn///Cew63l//9HqxeWJhaVpBapK6gXpOblVQLplMzcVCCVl5mcnZqDzEAohSqB6YDRGCpjAQ)
---
```
ü é
```
[Try it onlin!](https://tio.run/##y0osKPn///AehcMr//@PVi8sTSwqSS1SV1AvSM3LqwTSKZm5qUAqLzM5OzUHmYFQClUC0wGjMVTGAgA)
[Answer]
# T-SQL, ~~41~~ ~~36~~ 34 bytes
```
select*from @ order by right(a,5)
```
### Explanation
Assume the input is pre-loaded in a table variable named `@`, with a single column named `a`, where each value is one coin to be sorted.
The `select * from @` part is boiler-plate 'get all values to return'. The real magic happens in the `order by` clause.
Using the same strategy as [Johnathan Allan](https://codegolf.stackexchange.com/a/109057/26408), I sort by the last five characters (SQL will return the entire string if it's too short): `arter`, `dime`, `ickel`, `penny`.
[Answer]
## JavaScript (ES6), ~~35~~ 33 bytes
```
a=>a.sort(([,...a],[,...b])=>b>a)
```
### Test cases
```
let f =
a=>a.sort(([,...a],[,...b])=>b>a)
console.log(f(['penny','nickel','dime','quarter']).join` `);
console.log(f(['nickel','penny','penny','quarter','quarter','quarter','dime','dime','dime','dime']).join` `);
console.log(f(['quarter','dime','nickel','nickel','quarter','dime','penny','penny']).join` `);
```
[Answer]
# Befunge, 158 bytes
```
~:0`v0v4<~_
9:%8_^>8*`^1p9\+1g
$:!#@_1-0" ynnep">:#,_>
1-0" lekcin">:#,_>$:!#^_
" emid">:#,_>$:!#^_1-0
>:#,_$1>-:!#^_0" retrauq"
*84g9< ^*84g91-*84g94-*84g96-
```
[Try it online!](http://befunge.tryitonline.net/#code=fjowYHYwdjQ8fl8KOTolOF9ePjgqYF4xcDlcKzFnCiQ6ISNAXzEtMCIgeW5uZXAiPjojLF8+CjEtMCIgbGVrY2luIj46IyxfPiQ6ISNeXwoiIGVtaWQiPjojLF8+JDohI15fMS0wCj46IyxfJDE+LTohI15fMCIgcmV0cmF1cSIKKjg0Zzk8IF4qODRnOTEtKjg0Zzk0LSo4NGc5Ni0&input=bmlja2VsIHBlbm55IHBlbm55IHF1YXJ0ZXIgcXVhcnRlciBxdWFydGVyIGRpbWUgZGltZSBkaW1lIGRpbWU)
String processing and sorting are not the sorts of things you'd typically want to attempt in Befunge, but this solution is taking advantage of [John Kasunich's](https://codegolf.stackexchange.com/users/65168/john-kasunich) observation that we don't actually need to sort anything. We just count the number of occurrences of each coin (which can easily be determined from the first character), and then output that many of each coin name in the appropriate order.
It's still not at all competitive with other languages in terms of size, but this approach is at least better than it would have been if we'd tried to handle the challenge as a string sorting exercise.
[Answer]
# Pyth, 3 bytes
```
@D5
```
[Demonstration](https://pyth.herokuapp.com/?code=%40D5&input=%5B%27quarter%27%2C+%27dime%27%2C+%27nickel%27%2C+%27nickel%27%2C+%27quarter%27%2C+%27dime%27%2C+%27penny%27%2C+%27penny%27%5D&debug=0)
Based on [ETHproductions](https://codegolf.stackexchange.com/a/109047/20080)'s answer in Japt.
Explanation:
```
@D5
@D5Q Variable introduction
D Q Sort the input by
@ 5 Its fifth character
```
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/), 11 bytes
Takes and returns list of strings.
```
{⍵[⍋↑5⌽¨⍵]}
```
[Try it online!](https://tio.run/nexus/apl-dyalog#U0/JLC5Qf9Q31TlSPSUtr1hd4X/ao7YJ1Y96t0Y/6u1@1DbR9FHP3kMrgPzY2v9AdUBJkBaFNAX1gtS8vEp1BfW8zOTs1BwgIyUzNxVIFZYmFpWkFqlzoSqHK4Ppg9Ew9dhZUEOxUGjmY2iBWwhnYChBdcp/AA "APL (Dyalog APL) – TIO Nexus")
`{` anonymous function:
`⍵[`…`]` the argument indexed by
`⍋` the ascending-making indices of
`↑` the matrix whose rows are the padded
`5⌽` five-steps-rotated
`¨⍵` items of the argument
`}`
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
↺₉ᵒ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/1HbrkdNnQ@3Tvr/PzpaqSA1L69SSUdBKS8zOTs1B8RKycxNBdGFpYlFJalFSrE6CtFI0nAdcAZMIU4mzESsNNh4LIoRNiJYWJShOSc2FgA "Brachylog – Try It Online")
Approach stolen from ETHproductions' Japt answer.
```
The input
ᵒ sorted by
↺ its elements rotated left
₉ by 9
is the output.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
Öṙ9
```
[Try it online!](https://tio.run/##yygtzv7///C0hztnWv7//z9aqbA0sagktUhJRyklMzcVSOVlJmen5iAzMJQUpOblVcLpWAA "Husk – Try It Online")
Ported from my Brachylog answer, which rips off ETHproductions' Japt answer but isn't an exact translation since it uses rotation instead of simple accessing-the-nth-element. There, I did it because `∋` doesn't let you index past the end of the input (which is probably quite helpful in many circumstances due to the declarative nature of the language). In Husk, `!` *does* let you index past the end of the input, with the same modular wrapping around that Japt `ñg9` uses, but it's from 1 so this program in particular would end up being one byte longer: `Ö!10`.
```
Ö Sort by
ṙ rotation by
9 9.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
µ5i
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCtTVpIiwiIiwiWyduaWNrZWwnLCAncGVubnknLCAncGVubnknLCAncXVhcnRlcicsICdxdWFydGVyJywgJ3F1YXJ0ZXInLCAnZGltZScsICdkaW1lJywgJ2RpbWUnLCAnZGltZSddIl0=) or [Run all the test cases](https://vyxal.pythonanywhere.com/#WyJQaiIsInbijIg6xpsiLCLCtTVpIiwiOztaYCA9PiBgdmoiLCJbXCJwZW5ueSBuaWNrZWwgZGltZSBxdWFydGVyXCIsIFwibmlja2VsIHBlbm55IHBlbm55IHF1YXJ0ZXIgcXVhcnRlciBxdWFydGVyIGRpbWUgZGltZSBkaW1lIGRpbWVcIiwgXCJxdWFydGVyIGRpbWUgbmlja2VsIG5pY2tlbCBxdWFydGVyIGRpbWUgcGVubnkgcGVubnlcIl0iXQ==)
## How?
```
µ5i
µ # Sort by:
5i # Index 5 into the list (zero-indexed, modular)
```
Port of Jelly.
[Answer]
## Batch, 82 bytes
```
@for %%c in (quarter dime nickel penny)do @for %%a in (%*)do @if %%a==%%c echo %%c
```
Takes input as command-line arguments and outputs to STDOUT. Works by concatenating the lists resulting from filtering the original list on each coin.
[Answer]
# Ruby, 34 bytes
```
->m{m.sort_by{|c|c[1..2]}.reverse}
```
input and output as an array of strings
[Answer]
## Ruby, 31 bytes
```
->s{s.sort_by{|i|i[1]}.reverse}
```
[Answer]
# Ruby, 30 bytes
```
->m{m.sort_by{|s|s[3].ord^16}}
```
Magical numbers found by trial and error. A bit clumsy, but shorter than using `.reverse`.
[Answer]
# [Perl 6](https://perl6.org), ~~40 36~~ 34 bytes
```
*.sort: {(<q d n p>Zxx 1..*).Bag{~m/./}}
```
[Try it](https://tio.run/nexus/perl6#ZYy7DoJAEEX7/YpbGSBhiI2Fr8LPsCPLqhthFnZBIQT/2hqjbKLE5t7JnJnTOIXbiuRGFB0W0miOnbE1dmNE72GNPthWyMAo98e2xZIoCumQnvtHkVAyDOPJWOSalQtC9AIomxpfEd2NzZwYxlIxd2AtrypHpguFqkltrazwu@lgSo/@@vM3DzFj3uVrhn78TzaxTOVFvQA "Perl 6 – TIO Nexus")
```
*.sort: {%(<q d n p>Z=>1..*){~m/./}}
```
[Try it](https://tio.run/nexus/perl6#ZYxBDoIwEEX3PcXfaICEEjcuVDiIO1LG2AhTaAFDCN7aNUZposTN/5N5M69zhH4v1VFUA7bKaI6dsS3SOZLv4YBxE5waFGDU2TnNdlJG4fioEplM03wxFqVmckGIUQB11@IrkXdjCyemuSbmAazVjUoUuiI0XW5bssLvloMlPfrrz986xIp5l68V@vE/2cQqV1d6AQ "Perl 6 – TIO Nexus")
```
*.sort: {%(<q d n p>Z=>^4){~m/./}}
```
[Try it](https://tio.run/nexus/perl6#ZYzBCoJAEIbv@xT/pdDA9RIdKn0QD4GsEy3prO5qIWJv3dkoF0q6/P8w38zXOcJtJ9VBVD3WymiOnLEtkmkj38Mewyo4NijAqNMsSU/bcHhUsYzHcTobi1IzuSDEIIC6a/FVyLuxhRPjVBNzD9bqSiUKXRGaLrctWeF388GcHv31528ZYsG8y9cC/fifbCKVqwu9AA "Perl 6 – TIO Nexus")
## Expanded:
```
*\ # WhateverCode lambda ( this is the parameter )
.sort: # sort using the following code block
{ # bare block lambda with implicit parameter 「$_」
%( # treat this list as a hash
<q d n p> # list of first characters
Z[=>] # zipped using pair constructor
^4 # Range from 0 up-to 4 ( excludes 4 )
){ # get the value associated with this key
~m/./ # regex which gets the first character ( implicitly from 「$_」 )
}
}
```
[Answer]
# Mathematica, 50 bytes
```
Flatten@{Last@#,Most@#}&@Split@Sort@StringSplit@#&
```
[Answer]
# [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 18 bytes
```
~{3mtt¢\3mtt¢>}$
```
## Explained
```
~ # Zero Space Segment
{ } # Anonymous Function
3m # Repeat the inputted string 3 times
tt¢ # And take the tenth character of that
\3mtt¢ # Do the same for the entry underneith
> # Compare the ascii value of the two
$# Sort the input by the anonymous function.
```
[Try it online!](https://tio.run/nexus/rprogn#@19XbZxbUnJoUQyEsqtV@f//f3VeZnJ2ao5OQWpeXiWULCxNLCpJLcKgUzJzU9GIWgA "RProgN – TIO Nexus")
[Answer]
# java 8, ~~128~~ 112 bytes
This is a lambda expression for a `java.util.function.Function<String[],String[]>`
```
s->{String r="";for(String k:"q d c p".split(" "))for(String t:s)if(t.contains(k))r+=" "+t;return r.split(" ");}
```
Explantion:
For each of the 4 coins in order, go through the input and append the coin's name to the result every time there is a match for that coin's unique character. Split the result into an array and return it.
] |
[Question]
[
*This is a cross-post of a problem I posted to anarchy golf: <http://golf.shinh.org/p.rb?tails>*
Given two integers \$ n \$ and \$ k \$ \$ (0 \le k \le n) \$, count the number of combinations of \$ n \$ coin tosses with at least \$ k \$ tails in a row.
For example, if \$ n = 3 \$ and \$ k = 2 \$, the answer is \$ 3 \$:
```
HHH ‚ùå
HHT ‚ùå
HTH ‚ùå
HTT ✔️
THH ‚ùå
THT ‚ùå
TTH ✔️
TTT ✔️
```
**For convenience sake, you do not need to handle the case where \$ n = k = 0 \$**.
## Rules
* The input must take in two integers \$ n \$ and \$ k \$, and output the answer as a single integer
* Inaccuracies due to integer overflow are acceptable, but floating point errors are prohibited
* As usual for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins
## Test Cases
```
n, k -> ans
---------------
1, 0 -> 2
1, 1 -> 1
2, 0 -> 4
2, 1 -> 3
2, 2 -> 1
3, 1 -> 7
3, 2 -> 3
3, 3 -> 1
5, 2 -> 19
6, 4 -> 8
9, 2 -> 423
12, 0 -> 4096
13, 5 -> 1262
14, 8 -> 256
16, 7 -> 2811
```
More terms are listed under [OEIS A109435](https://oeis.org/A109435).
[Answer]
# [Python](https://www.python.org), 50 bytes
```
lambda n,k:sum(k*"1"in bin(i)for i in range(2**n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3jXISc5NSEhXydLKtiktzNbK1lAyVMvMUkjLzNDI10_KLFDIVgNyixLz0VA0jLa08TU2oTnuQZB5C0tBA04pLoaAoM69EQ0sjTak6TSNPRyFb08q4VkkBpDYbodZUE2bMggUQGgA)
Brute-force solution seems to be the shortest.
---
## [Python](https://www.python.org), 67 bytes
```
lambda n,k:2**n-(g:=lambda a:a*k>0and(a<3or g(a-1)*2-g(a+~k)))(n+2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXMSc5NSEhXydLKtjLS08nQ10q1soWKJVola2XYGiXkpGok2xvlFCukaibqGmlpGukCGdl22pqamRp62kSbUKPs0oJI8hcw8haLEvPRUDUMDTSsuhYKizLwSDS2NNKXqNI08HYVsTSvjWiUFkNpshFpToFkQYxYsgNAA)
-11 bytes thanks to Neil.
More mathematical answer.
$$
f(n, k) = 2^n - k \operatorname{-bonacci}(n+k)
\\
k \operatorname{-bonacci}(n) =
\begin{cases}
0 & n < k-1 \\
1 & n = k-1 \\
\sum^k\_{i=1} k \operatorname{-bonacci}(n-i) & n > k-1
\end{cases}
$$
[Answer]
# x86-64 machine code, 28 bytes
```
31 C0 99 52 89 F1 FF C9 78 07 D1 EA 72 F8 75 F4 41 FF C0 5A FF C2 0F A3 FA 73 E8 C3
```
[Try it online!](https://tio.run/##pVLBctMwED1rv2IbJjMStjtJyHBwai6cuXBihnBwJDnekMjBcsChza/j7iYtDTPcqsNKu9J7@54km62tHYYy7lB/HmmoctU3LfqyTyWAsu4HlLnaH2KNrethlatd8xO9lQORwObKeSs5qE1EByrWjHe8PeWKRcsx/MYVqNvVsfM46edTcLmiYC8d9s3@zHypyGLVXQi8IwFbLEG1vgMzMgug0GGlJYYUZfrORXjD4O3BebyLnaPmtv5wPrgrKWgD99yl5bzSI8QHYVEVuzyzbLDAyYKnmwKnM14kiQG8Gn@R4zmNUtwI@rm2DFmWZK8Y/2qhixZ61kKiRbH6q4bjGT2wDBLgf1zcFUhPJtQL7Ek731u6MYI8gbp2sQyfSltT8Ggb5/OzKqHthTbFI6euwfsXusnsC/MdC60PIdI6eIe2Ltu3pjJf@yT5ZhYn/FXT1qM@iptJ//Hd9cWhHhPKf4hmGZipl01@40Mb2AechuGPrbblOg7Z7v2cA//QgqF@@wg "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes n in EDI and k in ESI and returns the answer in EAX.
In assembly:
```
f: xor eax, eax
cdq
a: push rdx
b: mov ecx, esi
c: dec ecx
js d
shr edx, 1
jc c
jnz b
.byte 0x41
d: inc eax
pop rdx
inc edx
bt edx, edi
jnc a
ret
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, ~~13~~ ~~9~~ 8 bytes
```
EƛbĠṠ⁰≥a
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiRcabYsSg4bmg4oGw4omlYSIsIiIsIjFcbjAiXQ==)
A very neat little answer I'm very happy with.
## Explained
```
EƛbĠṠ⁰≥a
E∆õ # to each item in the range [1, 2 ** N)
bĠṠ # get the sums of consecutive digits of the binary representation of that number
⁰≥a # are any of those greater than K? This is essentially getting all consecutive runs of flips and getting there length. Works because there's only 1s and 0s
# the s flag sums that list.
```
[Answer]
# [Python](https://www.python.org), 55 bytes
```
f=lambda n,k:n>=k and 2*f(n-1,k)-(-1<<n>>-~k)-f(n+~k,k)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3zdNscxJzk1ISFfJ0sq3y7GyzFRLzUhSMtNI08nQNdbI1dTV0DW1s8uzsdOuAHKCodl02UBiq3SEtv0ghTyEzT6EoMS89VcPIQNOKS6GgKDOvRENLI02pGqhBRyFb08qsVkkBpDYbRa0m1ByYcwA)
Slightly longer than [@pxeger's Python answer](https://codegolf.stackexchange.com/a/248500/107561) but more efficient.
### How?
Uses the recurrence
\$f(n,k)=2f(n-1,k)+2^{n-k-1}-f(n-k-1,k)\qquad(n>k)\$
which is obtained by counting words that have k consecutive 1's somewhere in the first n-1 places, words that end in a 0 followed by k 1's and the overlap of these two groups.
[Answer]
# JavaScript (ES7), 59 bytes
Expects `(n)(k)`.
Fully bitwise because binary string manipulation in JS is too verbose.
```
(n,i=1<<n)=>g=k=>i--&&(h=m=>i&m^m?h(m*2):m<=i)(2**k-1)+g(k)
```
[Try it online!](https://tio.run/##dc9NDoIwEAXgvafoisygCB1@FEPxJiYEBSq0GDFeH1lAIBV2Tb6896bP7Jt1@Vu@Po5u74@@ED3ogxQ8STSKtBS1SKXjWBZUQg1PS93UtQJlE15UIiQC2XbtcNyXUGOft7prm8exaUsogHEED5G5LmO0@zc@GjeN5lywYlPOXzHa6vTn3GnFaKtzMH@rM1zsxSZGCMGIZ9PiORiQOcmX3/fiyOThonBapYj6Hw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES7), 38 bytes
*Saved 2 bytes thanks to @Neil*
Expects `(k)(n)`. Returns [*true* for *1*](https://codegolf.meta.stackexchange.com/a/9067/58563).
Uses [loopy walt's recursion formula](https://codegolf.stackexchange.com/a/248518/58563).
```
k=>g=n=>n>k?2*g(--n)-g(n-=k)+2**n:n==k
```
[Try it online!](https://tio.run/##ddFLDoMgEIDhvadgCRqqAz6bYM9irJIWA01ten3KQoxBuv7yk5nhOXyHdXw/Xh@qzX2ys7BK9FJo0ete3VgqMaWaUIk1FYpkLE31VQuh7Gj0apbpshiJsxkXBCMgBOU5QiwJEA4ISaRkG5ax0iMPkR0QYiXfsImV/N@z/IAQKyuPXail03rTNpZ2flHGI3eA/Q5FV4deOd/HYvXpyK3z0v9Adcobx3401gLYHw "JavaScript (Node.js) – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~21~~ 19 bytes
-2 bytes saved thanks to a suggestion by [coltim](https://codegolf.stackexchange.com/users/98547/coltim) on another answer.
Enumerates all binary length-n sequences and counts the ones with runs of at least k 1s.
```
{+/y<|/1(1+*)\!x#2}
```
[Try it online!](https://ngn.codeberg.page/k#eJw1jjESgzAMBHu/ggwNCQVIso2N+AnQ8oYwJHl77DPu9k6rkY756odz+QzUUf96bo93y19jzLGSjnvzaxhIGSkhl9YC0QqQqyClnYBcBVGpgrvdmNirzRwSxlJbzjrVM2P0OYo67LDHO1YDXnMYep2QAtEfipkyPg==)
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 40 bytes
```
k->g(n,r=k)=if(!r,2^n,n,g(n--,r--)+g(n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc5BCsIwEEDRq0RXGZwBk7S1LtqLlCjZpJRKCKEuvIngpiDimbyNSdNu8uaHBOb19SYM197Pb8uaz32yVP_4SG3PHYZmhGawfBdQXhw6jJdEGIjgEEeA9f3TeH97cMOoZT4MborjPsWeWW46qSGeQgMg6zqBRx0VKBIyl9xKJlQutZVKlLkqLBLnXGL9LxSWiwXWixWetF73m-fsHw)
A port of [@tsh's JavaScript answer](https://codegolf.stackexchange.com/a/248536/9288).
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 42 bytes
```
k->n->(y=1-x)/(y-=x)/(x+y/x^k)%x^(n+1)\x^n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc5BCoMwEEDRqwShkNQEO4lau9CL2FiysYgSglhIblLoRiilZ-ptaoxu5s1fDMzra9TY3e5mfreo_DymlhW_Y88qzSrsSmCWJNix0mNjl9imJwfbYB0DudpGbxdPZczgsEKsQmbs9LSskY8ItVjVXJJlgiSEoroGepKLQMHDQ_G9uEeEEnsJTxYqp6nnEgq2exA0W01psZrTs5Qk_DfPwT8)
According to OEIS, the generating function for column \$k\$ is \$\frac{x^k}{(1-\sum\_{i=1}^k x^i)(1-2x)}\$, which could be simplified to \$\frac{(1-x)}{(1-2x)(x+(1-2x)/x^k)}\$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
1xẇⱮSɓ2ṗ
```
[Try it online!](https://tio.run/##y0rNyan8/9@w4uGu9kcb1wWfnGz0cOf0/4eXO@hrRv7/H22oYxCrAyQNgaQRmG0EZRsBSWMw2xjKNgaSpmC2mY4JkLQEsw0h2gyNdUxBlImOBYgy0zGPBQA "Jelly – Try It Online")
\$k\$ on the left, \$n\$ on the right.
```
Ɱ For each
…ì2·πó sequence of n 1s and 2s,
ẇ does it contain as a sublist
1x k 1s?
S Sum.
```
[Answer]
# [Factor](https://factorcode.org/) + `sequences.repeating`, 58 bytes
```
[ "1"swap cycle swap 2^ iota [ >bin subseq? ] with count ]
```
[Try it online!](https://tio.run/##bZFBSwMxEIXv@RXP3l2a7HbbVViP4sWLeCoV0jDVYJtdkyyllP72Na3EzWpDCOGbN2@SmY1UvrH968vT8@MdPska2sLRV0dGkcsstSS9Nu/YSf9xObJWWkd2EEE61yiH1pL3h9Zq43HP2JEhrCPAgSlOwA1ua0AkmA@YRyxG6iLBiTpPsLhiko/U8wSLKyb5ef83mY29q8jL8KyBLyKuRvJCRHv@50fTqoyR/FxkqCDK2BxeBOOkZ7PflFB8ngQWnLMT65eY8InbyxbqoLaEy1W8QTdeYol6rQ1ctw4je8AKex1GqZouzGnVb37GV@9CRtZ/Aw "Factor – Try It Online")
---
Longer but much cooler:
# [Factor](https://factorcode.org/), 67 bytes
```
[| n k | n 2^ ""n [ dup k short tail* sum suffix ] times last - ]
```
[Try it online!](https://tio.run/##bZHBS8MwFMbZNX/F547CZEm7blXYVbx4EU9jQqgpK0vTmryCMve31xSJTd1CksPvfe97yXulLKix/evL0/PjPXRTSO1QSzrgqKxRGk59dMoUykE61xQOrVVEX62tDOGBsRODXyeAA0ucgRsstoCIMB8xD1hM1GmEI3USYXHFJJmo1xEWV0ySYV@arKbeeeCZf9bINwHnE3kqgj3/96NlnoVIMhQZK4gsNIen3jjq2eovxRdfR4EN5@zM@t03DI4YbvGG@Ww2N9jhvWs9dIfGEkhW@hauq/0py@oTe1BV@@Fp6QgL7Pvyd47bWra4638A "Factor – Try It Online")
\$2^n\$ minus the \$(n+k-1)\$th k-bonacci number.
Example:
\$n=6, k=4\$
The tetranacci sequence begins:
\$0, 1, 1, 2, 4, 8, 15, 29, \color{red}{56}\$
\$2^6-56=8\$
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~89~~ 88 bytes
```
m;r;a;b;c;f(n,k){for(c=b=1<<n;b--;c-=m<k)for(a=b,m=r=0;a;m=r>m?r:m)r+=a&1?:-r,a/=2;m=c;}
```
[Try it online!](https://tio.run/##bZJvb4IwEMbf71NcTFxAS6SIf0v1xbJPMc0CtTjDqKaQjIzw1ceOSo0uI@W4Pk/vl@sF4R2FaNucaRazhAmWOopkbp2etSN4wmkUKZZ4HhMez6PM7fSYJyTnmvtYgt9NvtXr3NVjHj/T7drTJJ7wAB3BmvakSsjjk3JcqJ8An04oZVG@q7c9cBRqSgBXYNfUrhmBOYEVuqhSFGiI77xhj5zMcnzD8S2NWhrG0ETfMJcEFncMWV2kKOXBUOprXWjqMFnYhK5MYRjgNvRX866pedfvDNNgSWlPFGdVlCA@Yj3CKEUm9RU82FWvwa5aveA7GxC4308HfTUOF5yuqZM6yArLfNanERSnb3lOHduuO@mF0U1hMB6b066BXcdtr6mQ1o/dnNmzBzuzdvavXaDd/RiQuY@GROM2wb@VF41HUmcwPBAYHsDbdHFY7BTev2MRKMhtSgXnct/Tm6em/RHpZ3wsWu/rFw "C (gcc) – Try It Online")
*Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
[Answer]
**C** (standard compliant), 78 bytes
`int f(int n,int k,int c){return n?n+c-k?k-c?f(n-1,k,0)+f(n-1,k,c+1):1<<n:1:0;}`
For the readable version:
```
int f(int n,int k,int c){
if(n==0)return 0; // no more coin flip left => no possible path
if(n==(k-c))return 1; // last coin flip and 1 tail is lacking
if(k==c)return 1<<n; // we have done k tails in a row, any path is a good path, and there are 2^n
return f(n-1,k,0) // possible paths if we get a head
+f(n-1,k,c+1); // possible paths if we get a tail
}
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 28 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{1⊥⍵≤⌈/∘(≢¨⊆⍨)⍤1⍉(⍺⍴2)⊤⍳2*⍺}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=ATsAxP97MeKKpeKNteKJpOKMiC/iiJgo4omiwqjiiobijagp4o2kMeKNiSjijbrijbQyKeKKpOKNszIq4o26fQ&f=e9Q39VHbBEMThTQFC65HYI4lkG0EZZuC2AA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Alternatively (same length): `{1⊥(∨/(⍵⍴1)⍷⊢)⍤1⍉(⍺⍴2)⊤⍳2*⍺}`
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 39 bytes
```
.+,(.+)
<$1*1>
"$+"+%`$
0$"1
<(.*)>.*\1
```
[Try it online!](https://tio.run/##K0otycxLNPz/X09bR0NPW5PLRsVQy9COS0lFW0lbNUGFy0BFyZDLRkNPS9NOTysGqNBUxwgA "Retina – Try It Online") No test suite due to the way the program uses history. Explanation:
```
.+,(.+)
<$1*1>
```
Replace the input with a string of `k` `1`s wrapped in `<>`s.
```
"$+"+
```
Repeat `n` times.
```
%`$
0$"1
```
Duplicate each row, appending `0` and `1` to each copy respectively.
```
<(.*)>.*\1
```
Count the number of rows where the binary portion contains `k` `1`s.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
TIã$×δåO
```
[Try it online](https://tio.run/##yy9OTMpM/f8/xPPwYpXD089tObzU//9/Yy4jAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaNj/kMjDiw0jDk8/t@XwUv//Ov@jow11DGJ1gKQhkDQCs42gbCMgaQxmG0PZxkDSFMw20zEBkpZgtiFEm6GxjimIMtGxAFFmOuaxsQA) or [try it step-by-step](https://tio.run/##RY9BSgQxEEX3c4pP47IHzLgTZBaCMCtl9AKZdI0pujtpUgmCF/EA4g28wey9UludcXATqur/9yBR7IFpnpunIh7m@hbN9uVudV6zJxw5SQaHqWSEJd1pem9TJmEbMKXYFZeX4PR54Qxs6Cot5KKOZ7xfWo1p9b3S6p4msrnWDHrYMZaQEY/IPJLACiQnDq/V/aHAQ0wg6/zfXa0VJpsGpoSBJbdwnlwPVotnQb8WfqcOZn1hVAwph3/1z/fpS@XPZWzx5ln12oklIZGUof7scTvPN6vNLw).
**Explanation:**
```
T # Push 10
I # Push the first input `n`
√£ # Take the cartesian product of the two, to create all possible n-sized strings
# containing 0s and 1s
$ # Push 1 and the second input `k`
√ó # Repeat the 1 `k` amount of times as string
δ # Map over the list we created earlier, using this "1"-string as argument:
å # Check if the "1"-string is a substring of the string we're mapping over
O # Sum to get the amount of truthy values
# (which is output implicitly as result)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 94 bytes
```
.+,(.+)
1$&$*0;$&$*11;$1$*,1,
+`1;1*,(((1)|,)*)
;$1$#3$*1,
+`^(1+)0
$1$1
r`\2;;(1*,)*(1*),$
1
```
[Try it online!](https://tio.run/##HcoxDsIwFAPQ3dcgoP@Tr6pO2gLKAbgEQmVgYGGoGLl7@OniJ9neXt/359mOclvbkEyGpGA4hTjWnmQNDNFoSCsro4kI9WcaFX06FD/18SFMOsIrYlvvuVbxt0ZPtQCwNdoIGpHdvJtR3LJbMLuLTbi67CcWm8HJLuBi5z8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+,(.+)
1$&$*0;$&$*11;$1$*,1,
```
Create `2‚Åø` in binary, `n+1` in unary, then a list of `k` `0`s and a `1`.
```
+`1;1*,(((1)|,)*)
;$1$#3$*1,
```
Repeat `n+1` times, drop the first element of the list, and append the sum of the remaining elements. This calculates the `n+1`th k-bonacci number.
```
+`^(1+)0
$1$1
```
Convert the `2‚Åø` from binary into unary.
```
r`\2;;(1*,)*(1*),$
```
Subtract the `n+1`th k-bonacci number from `2‚Åø`.
```
1
```
Convert to decimal.
Rather than trying to count the number of `n` coin tosses with at least `k` tails in a row, it's easier to consider the number of `n` coin tosses that do not have `k` tails in a row. By considering them grouped by the number of tails that they end with, it's possible to determine a recurrence relation for the number of rows. For example, with `k=3`:
* For `0` coin tosses, `1` ends in `0` tails, `0` end in `1` tails, and `0` end in `2` tails. Total `1` matching row.
* For `1` coin toss, `1` ends in `0` tails, `1` ends in `1` tails, and `0` end in `2` tails. Total `2` matching rows.
* For `2` coin tosses, `2` end in `0` tails, `1` ends in `1` tails, and `1` ends in `2` tails. Total `4` matching rows.
* For `3` coin tosses, `4` end in `0` tails, `2` end in `1` tails, and `1` ends in `2` tails. Total `7` matching rows.
* For `4` coin tosses, `7` end in `0` tails, `4` end in `1` tails, and `2` end in `2` tails. Total `13` matching rows.
* For `n` coin tosses:
+ The number that end in `0` tails is the total for `n-1` coin tosses, since the value is simply that plus an extra toss of heads.
+ The number that end in `1` tails is the number that end in `0` tails for `n-1` coin tosses, with each row having an extra toss of tails. However, this is also the total for `n-2` coin tosses.
+ The number that end in `2` tails is the number that end in `1` tails for `n-1` coin tosses, with each row having an extra toss of tails. Recursively, we see that this is also the total for `n-3` coin tosses.
+ The total is the sum of these which is also the total of the previous three totals. Thus, this forms a `3`-binacci sequence.
In general, the number of `n` coin tosses that do not have `k` tails in a row is a `k`-binacci sequence.
The number of `n` coin tosses with at least `k` tails in a row plus the number of `n` coin tosses that do not have `k` tails in a row is of course the total possible number of rows, `2‚Åø`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 39 bytes
```
k=>g=(n,r=k)=>r?n&&g(--n,--r)+g(n):2**n
```
[Try it online!](https://tio.run/##ddBNDoMgEAXgvadgZcBKFfC3CfYsxippNdBg0@tTFtJYoSsW33uTYR79u18HfX@@sFS30UzczLwTHMpU8xnxTl9lHAuIsUwx1ugkoEQXmiTSDEquahnPixJwgjmCgCAEsgwAGv0a2RmJ/B7drAj0nLGD0Z2RQI9tVgd67M9MtjMS6JXO2gMWFqsNm0CxdR@kLLKvdwHyvUDeVn6itInvXrSifqKxicJdvwyMqG3AbUgbQswH "JavaScript (Node.js) – Try It Online")
```
k=> // Number of tails required in a row
g=(
n, // Number of coins we will flip
r=k // Number of tails still required in a row
)=>
r? // Do we still require tails?
n&& // And we have more coins can flip?
g(--n,--r)+ // Luckily, tail this time
g(n): // Nope, head this time
2**n // We don't care what we get from remaining coins
```
[Answer]
# [R](https://www.r-project.org), ~~72~~ 68 bytes
*Edit: -4 bytes thanks to @Dominic van Essen.*
```
\(n,k)sum(sapply(1:2^n-1,\(x,r=rle(intToBits(x)>0))any(r$l*r$v>=k)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VdDPCoIwHAdwuvoKXQZ52ELB_VFnoIfoETpK4CFBNJOpoc_SxYIeqp4ml03cafDh-_vut90fYnim4attUpu_DzEsrRzV7QXWSVUVPcQ7ciptbMWws0QoijPMyuZ43WdNDTsUOQglZQ-FWWyFeYvCHCE0dX1Wa5BCbAHgoA0AdgQAMf6ClWApZJlhSuYMVUK0KbrM-EqINiWFalOu1hNI8kZiiriUYBlihBrj1vqSTuBJlP3u3EY8IpGNyOcnu7-gvMOfjWM8_dEwTOcX)
[Answer]
# BQN, 20 bytes
```
{+¬¥‚•ä‚஬¥¬®‚à߬¥Àò¬®ùï©‚ä∏‚Üאַ‚Üïùﮂ•ä2}
```
-1 byte thanks to @Razetime!
[Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyvCtOKliuKIqMK0wqjiiKfCtMuYwqjwnZWp4oq44oaVwqjihpXwnZWo4qWKMn0KCijigKJTaG93IEbCtCnCqCDin6gKIDHigL8wCiAx4oC/MQogMuKAvzAKIDLigL8xCiAy4oC/MgogM+KAvzEKIDPigL8yCiAz4oC/MwogNeKAvzIKIDbigL80CiA54oC/MgoxMuKAvzAKMTPigL81CjE04oC/OAoxNuKAvzcK4p+pCkA=)
## Explanation
* `‚Üïùﮂ•ä2` generate binary sequences of length *n*
* `ùï©‚ä∏‚Üאַ` convert each binary sequence to subsequences of length *k*
+ example: `1010` with *k*=3 becomes `101, 010`
* `∨´¨∧´˘¨` AND each subsequence, then OR each result
* `+´⥊` sum to get total number of 1s
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 14 bytes
```
0<1XbNTB_MS,Ea
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7IKlpSVpuhbrDGwMI5L8QpzifYN1XBMhglC5ZdGWOgpGMJUA)
Brute force, same concept as pxeger's Python answer.
-5 bytes thanks to DLosc
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 36 bytes
```
s11rzjCBg1{{gw:pd{-]g1>=}fl}fl}qL[IE
```
[Try it online!](https://tio.run/##TY7LCsIwEEX38xXzA4XeSdOHYBeKC8G9C3Ej1oJ00QelYOi3x7QNUcjmcO69mcfYN9XQjZU1JmbMw9RWdgD6z/t4qGFMPe3ap4nuNcr9/GqW111u55Odr41lMMfMUckstAA2ALEEk6zgjVpBQkwFk60gIeZAhZj@dQri1I1ulBMXQSWiCH//xkVKcBvaNyUVgivm/mLttJvKPObAFw "Burlesque – Try It Online")
```
s1 # Save k
1rz # [0, 1]
jCB # Combinations up to n
g1 # Get k
{ # Catch k == 0
{gw # Group with length ([1, 1, 0] -> [[2, 1], [1, 0]])
:pd # Filter for tails
{ # Filter
-] # Head
g1 # k
>= # Greater than or equal
}
fl # Count matches
}
fl # Count matches
}
qL[ # Length of combinations (when k == 0)
IE # If else
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
NθILΦX²N№⍘ι²×θ1
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMnNS@9JEPDLTOnBCgZkF8OJI10FJB1aGrqKDjnlwJ1OCUWpwaXADWna2TqKBgBxUMyc1OLNQp1FJQMlTTBwPr/fyMF0/@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Takes `k` as the first input and `n` as the second input. Explanation: Uses brute force, so takes exponential time in `n`.
```
Nθ Input `k` as an integer
² Literal integer `2`
X Raised to power
N Input `n` as an integer
Φ Filtered where
ι Current value
‚çò Converted to base
² Literal integer `2`
‚Ññ Count i.e. contains
1 Literal string `1`
√ó Repeated by
θ Input `k`
L Take the length
I Cast to string
Implicitly print
```
27 bytes for an efficient version (approximately linear time):
```
NθNη⊞υ¹F⊕θ⊞υ↨¹✂⮌υ⁰η¹I⁻X²θ⊟υ
```
[Try it online!](https://tio.run/##TY29DgIhEIR7n2LLJcFELLSw0@oKDdEnQFwDyR3c8XM@Pi6Fid3M5JsZ60yy0YytDWGu5VanJyVcxGnz7x17XbPDKkGxfscEOASbaKJQ6MUFAT/gbDKhkvAYvSW800qJgyok7CS4PiD6XPKh4MXkglcfakYdP/y0l7AwqePMjQ62pg5wbNt1/AI "Charcoal – Try It Online") Link is to verbose version of code. Takes `n` as the first input and `k` as the second input. Explanation:
```
NθNη
```
Input `n` and `k`.
```
⊞υ¹
```
Start with the zeroth term of the k-bonacci sequence.
```
F⊕θ⊞υ↨¹✂⮌υ⁰η¹
```
Calculate `n+1` additional terms.
```
I⁻X²θ⊟υ
```
Subtract the `n+1`th term from `2‚Åø`.
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 35 bytes
```
$b=<>;$_=grep/T{$b}/,glob"{H,T}"x$_
```
[Try it online!](https://tio.run/##K0gtyjH9/18lydbGzlol3ja9KLVAP6RaJalWXyc9Jz9JqdpDJ6RWqUIl/v9/Uy6jf/kFJZn5ecX/dQty/uv6muoZGBoAAA "Perl 5 – Try It Online")
[Answer]
# [MATLAB](https://www.gnu.org/software/octave/), 71 bytes
```
function f(n,k),sum(contains(string(dec2bin(0:2^n-1)),repmat('1',1,k)))
```
The binary representation of all numbers from 0-2^n-1 will give each combination of coin flips. From that, I can search the resulting string vector for repeated instances of 1 ( my choice for tails) that are at least k long and sum the logical array for the result.
[Try it online!](https://tio.run/##DcvBCoAgDADQX@nmBgvSYx8TmGmMcIaufn/17q8ljW82K48k5SZTAaELaTwVUhONLAOGdpYTjpzCzgLLGjaZPSL1fNeo4Lwj/y9Esw8 "Octave – Try It Online")
[Answer]
# Excel, 49 bytes
```
=COUNT(FIND(REPT(1,B2),BASE(SEQUENCE(2^A2)-1,2)))
```
Input for *n* is in `A2` and *k* is in `B2`.
* `SEQUENCE(2^A2)-1` creates an array from 0 to (2^n)-1.
* `BASE(~,2))` converts that array to binary.
* `REPT(1,B2)` creates a string of *k* 1s.
* `FIND(REPT(~),BASE(~))` tries to find that repeated string in each binary element in the array. This returns an array of integers (if it's found in that element) and errors (if it's not).
* `COUNT(FIND(~))` counts the numbers in that array.
[](https://i.stack.imgur.com/6MW1C.png)
] |
[Question]
[
# Summary
Write a program or function, which doesn't take any input, and outputs all the integer numbers, between -1000 and 1000 in ascending order, to the stdout, one per line, like this:
```
-1000
-999
-998
-997
...
```
And after that you need to print the time taken to print these numbers, or the time from the start of the program's execution in milliseconds (if necessary, it can also contain some other things, for example: time taken:xxxms is ok). It can be a float, or an integer (if you print an integer, you need to round down to the nearest).
# Example code
```
using System;
using System.Diagnostics;
class P
{
static void Main(string[] args)
{
Stopwatch st = Stopwatch.StartNew();
for (int i = -1000; i <= 1000; i++)
{
Console.WriteLine(i);
}
Console.WriteLine(st.ElapsedMilliseconds);
}
}
```
# Restrictions
Standard loopholes are not allowed
# Other infos
It's code golf, so the shortest submission wins.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
1e3t_y&:!DZ`*
```
[Try it online!](https://tio.run/nexus/matl#@2@YalwSX6lmpegSlaD1/z8A "MATL – TIO Nexus")
```
% Implicitly start timer
1e3 % Push 1000
% STACK: 1000
t_ % Duplicate, negate
% STACK: 1000, -1000
y % Duplicate second-top number
% STACK: 1000, -1000, 1000
&: % Two-input range
% STACK: 1000, [-1000, 999, ..., 1000]
! % Transpose into column vector
% STACK: 1000, [-1000; 999; ...; 1000]
D % Display
% STACK: 1000
Z` % Push timer value, say t
% STACK: 1000, t
* % Multiply
% STACK: 1000*t
% Implicitly display
```
[Answer]
# Octave, ~~46~~ ~~43~~ ~~36~~ ~~30~~ 23 bytes
```
tic;(-1e3:1e3)',toc*1e3
```
This will print:
```
ans =
-1000
-999
-998
-997
-996
-995
```
If you don't like the `ans =` , then we have to add an additional 6 bytes for `disp`:
```
tic;disp((-1e3:1e3)'),toc*1e3
```
Saved a lot of bytes thanks to a few reminders from rahnema1.
**Explanation:**
```
tic; % Starts timer
(-1e3:1e3)' % A vertical vector -1000 ... 1000
disp((-1e3:1e3)'), % Display this vector
toc*1e3 % Stop the timer and output the time in milliseconds
```
[Answer]
# JavaScript, 60 bytes
```
(c=console).time();for(i=~1e3;i++<1e3;c.log(i));c.timeEnd();
```
In order to get all the events logged, you should use the script from the developer console (otherwise the logs are erased after the certain amount of them).
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 18 bytes
```
es2001{1e3-n}/es\-
```
[Try it online!](https://tio.run/nexus/cjam#@59abGRgYFhtmGqsm1ern1oco/v/PwA "CJam – TIO Nexus")
### How it works
```
es Push the current time (milliseconds since epoch) on the stack.
2001{ }/ For each integer X from 0 to 2000:
1e3- Subtract 1000 from X.
n Print with a newline.
es Push the current time on the stack.
\- Swap and subtract.
```
[Answer]
# Python 3.5, ~~80~~ ~~77~~ 73 bytes
```
import time
*map(print,range(-1000,1001)),
print(time.process_time()*1e3)
```
Previous solutions involved using `timeit` and `time.time()`, they were larger.
Sadly, [`time.process_time()`](https://docs.python.org/3/library/time.html#time.process_time) was introduced in python 3.3.
Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for saving 4 bytes!
[Answer]
# Bash (+coreutils), ~~41~~, ~~49~~, ~~46~~, ~~44~~, 42 bytes
EDITS:
* Refactored to use Bash-builtin (time), to address @Dennis precision concerns;
* Reduced by 3 bytes, by utilizing Bash 4+ `|&` for stderr redirection;
* Saved 2 more bytes by replacing `seq -1000 1000` with `seq -1e3 1e3` (Thanks @Dennis !);
* -2 bytes by removing unnecessary backslash, and using default precision (Thx @Dennis !).
**Golfed**
```
TIMEFORMAT=%R*1000;(time seq -1e3 1e3)|&bc
```
[Try It Online !](https://tio.run/nexus/bash#@x/i6evq5h/k6xhiqxqkZWhgYGCtUZKZm6pQnFqooGuYaqwAxJo1aknJ//8DAA)
**Sidenote**
Using a coreutils "time" utility, instead of the Bash-builtin, results in a ~~41~~, 35 byte solution:
```
\time -f "%e*1000" seq -1e3 1e3|&bc
```
***"\"*** is here to make *bash* invoke the real command, instead of the builtin.
Unfortunately coreutils *time* precision is only 1/100s, which have raised concerns on if it is a valid solution.
[Answer]
## R, 42 bytes
```
system.time(cat(-1e3:1e3,sep="\n"))[3]*1e3
```
This will print
```
.
.
.
998
999
1000
elapsed
60
```
To remove `elapsed`, two additional bytes are necessary:
```
system.time(cat(-1e3:1e3,sep="\n"))[[3]]*1e3
```
[Answer]
# Bash + GNU utils, 43
* Saved 2 bytes thanks to @Dennis
* Saved 5 bytes thanks to @zeppelin
```
c=date\ +%s%3N
s=`$c`
seq -1e3 1e3
$c-$s|bc
```
The `date` command gives the number of seconds since the epoch concatenated with current nanoseconds. This command is run before and after. `bc` takes the difference and prints.
[Try it online](https://tio.run/nexus/bash#@59sm5JYkhqjoK1arGrsx1Vsm6CSnMBVnFqooGuYaqwAxFwqyboqxTVJyf//AwA).
---
I was hoping to do this for 17:
```
time seq -1e3 1e3
```
But the output of time gives more than we need:
```
real 0m0.004s
user 0m0.000s
sys 0m0.004s
```
[Answer]
# JavaScript (ES6), ~~63~~ 59 bytes
```
for(c=console.log,i=~1e3;i<1e3;c(++i));c(performance.now())
```
[Answer]
## R, 66 bytes
```
x=proc.time();for(i in -1e3:1e3)cat(i,"\n");(proc.time()-x)[3]*1e3
```
Probably not the shortest but it works.
[Answer]
# Mathematica, 51 bytes
```
p[1*^3#]&@@AbsoluteTiming@Array[p=Print,2001,-1*^3]
```
**Explanation**
```
Array[p=Print,2001,-1*^3]
```
Store the `Print` function in `p`. Print 2001 numbers, starting at -1000, incrementing by 1.
```
AbsoluteTiming@ ...
```
Find the total time elapsed in seconds.
```
p[1*^3#]&@@ ...
```
Multiply that by 1000 (seconds -> miliseconds) and `p` (`Print`) it.
[Answer]
# PHP, ~~110~~ 70 bytes
still a little long; but saved 38 with @AlexHowansky´s hint, and two more with `1e3` and `~1e3`.
```
for($t=($m=microtime)($i=~1e3);$i++<1e3;)echo"$i
";echo($m(1)-$t)*1e3;
```
prints float. Run with `-r`.
[Answer]
## Powershell, 27 Bytes
```
$1=date;-1e3..1e3;(date)-$1
```
Thanks to AdmBorkBork for pointing out that the verbose default output is acceptable in the challenge.
Outputs result like:
```
994
995
996
997
998
999
1000
Days : 0
Hours : 0
Minutes : 0
Seconds : 5
Milliseconds : 679
Ticks : 56799255
TotalDays : 6.57398784722222E-05
TotalHours : 0.00157775708333333
TotalMinutes : 0.094665425
TotalSeconds : 5.6799255
TotalMilliseconds : 5679.9255
```
for more contained result of just milliseconds, use original answer:
```
$1=date;-1e3..1e3;((date)-$1).TotalMilliseconds
```
Save time before as $1, print to stdout automatically, then get the time between the beginning and end of execution.
[Answer]
# [Perl 6](https://perl6.org), 45 bytes
```
.put for -($_=1e3)..$_;put (now -INIT now)*$_
```
[Try it](https://tio.run/nexus/perl6#@69XUFqikJZfpKCroRJva5hqrKmnpxJvDRLVyMsvV9D19PMMUQCyNLVU4v//BwA "Perl 6 – TIO Nexus")
## Expanded:
```
# print the values
.put # print with trailing newline ( method call on 「$_」 )
for # for each of the following
# ( temporarily sets 「$_」 to the value )
-(
$_ = 1e3 # store 「Num(1000)」 in 「$_」
)
.. # inclusive Range object
$_;
# print the time elapsed
put # print with trailing newline
(now - INIT now) # Duration object that numifies to elapsed seconds
* $_ # times 1000 to bring it to milliseconds
# The 「INIT」 phaser runs code (the second 「now」) immediately
# as the program starts.
# There is no otherwise unrelated set-up in this code so this is a
# reliable indicator of the amount of time it takes to print the values.
```
[Answer]
# [J](http://jsoftware.com/), 22 bytes
```
1e3*timex'echo,.i:1e3'
```
[Try it online!](https://tio.run/nexus/j#@2@paGVsHmugEA@CXKnJGfmxhqnGWiWZuakV6iCujl6mFVBE/f9/AA)
`timex` is a builtin that executes the string and returns the time it took to evaluate it in seconds. The string forms the range [-1000, 1000] using `i:`, then columinizes it using `,.`, and prints it using the builtin `echo`.
[Answer]
# [Pyth](http://pyth.herokuapp.com/), ~~18~~ ~~15~~ 14 bytes
```
j}_J^T3J;*.d1J
```
[Try it here!](http://pyth.herokuapp.com/?code=j%7D_J%5ET3J%3B%2a.d1J&debug=0)
**Explanation**
This is similar to my python answer.
```
J^T3 Set J to 1000
}_ J List ranging from -1000 to 1000
j Join the list with new lines and implicitly print it
;*.d1J Print time since execution of the program in milliseconds
```
**Edits**:
* Thanks to [fryamtheeggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for saving 3 bytes!
* Thanks to [busukxuan](https://codegolf.stackexchange.com/users/49362/busukxuan) for saving a byte.
[Answer]
# [Noodel](https://tkellehe.github.io/noodel/), ~~17~~ 13 [bytes](https://tkellehe.github.io/noodel/docs/code_page.html)
**13 bytes**
Tried a slightly different approach and saved 4 bytes.
```
ƇQjȥḶGQɱ⁻Ñ€Ƈ⁻
```
[Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%C6%87Qj%C8%A5%E1%B8%B6GQ%C9%B1%E2%81%BB%C3%91%E2%82%AC%C6%87%E2%81%BB&input=&run=true)
### How it works
```
Ƈ # Pushes on the amount of milliseconds passed since 01/01/1970.
Qjȥ # Pushes 2001 onto the stack.
Qj # Pushes on the string "Qj"
ȥ # Converts the string into a number as base 98.
ḶGQɱ⁻Ñ€ # Loops 2001 times printing -1000 to 1000.
Ḷ # Consumes the 2001 and loops the following code 2001 times.
GQ # Pushes on the string "GQ"
ɱ # Pushes on the current counter of the loop (i)
⁻ # Subtracts (i - "GQ") since i is a number, the "GQ" is converted to a number which will fail.
# So, Noodel will treat the string as a base 98 number producing (i - 1000).
Ñ # Consume what is on the top of the stack pushing it to the screen followed by a new line.
€ # The end of the loop.
Ƈ⁻ # Calculates the duration of execution.
Ƈ # Pushes on the amount of milliseconds passed since 01/01/1970.
⁻ # Pushes on (end - start)
```
---
**17 bytes**
```
ƇGQȥḋɲṡ×2Ḷñ⁺1€ÑƇ⁻
```
[Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%C6%87GQ%C8%A5%E1%B8%8B%C9%B2%E1%B9%A1%C3%972%E1%B8%B6%C3%B1%E2%81%BA1%E2%82%AC%C3%91%C6%87%E2%81%BB&input=&run=true)
### How it works
```
Ƈ # Pushes on the amount of milliseconds passed since 01/01/1970.
GQȥḋɲṡ×2 # Used to create the range of numbers to be printed.
GQ # Pushes on the string "GQ".
ȥ # Converts the string into number as if it were a base 98 number. (which is 1000)
ḋ # Duplicates the number and pushes it onto the stack.
ɲ # Since the item on top is already a number, makes the number negative (random thing I threw in at the very beginning when made the langauge and totally forgot it was there)
ṡ # Swaps the first two items on the stack placing 1000 on top.
×2 # Doubles 1000 producing... 2000
Ḷñ⁺1€Ñ # Prints all of the numbers from -1000 to 1000.
Ḷ # Consumes the 2000 to loop the following code that many times (now -1000 is on the top).
ñ # Prints the value on top of the stack followed by a new line.
⁺1 # Increment the value on top of the stack by 1.
€ # End of the loop.
Ñ # Since 1000 is still not printed, this consumes 1000 and prints it followed by a new line.
Ƈ⁻ # Calculates the number of milliseconds to execute program.
Ƈ # Pushes on the amount of milliseconds passed since 01/01/1970.
⁻ # Pushes on (end - start) in milliseconds.
# At the end, the top of the stack is pushed to the screen.
```
---
The snippet uses the values -4 to 4 in order to not take so long to complete.
```
<div id="noodel" code="ƇFȥḶAɱ⁻Ñ€Ƈ⁻" input="" cols="10" rows="10"></div>
<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
[Answer]
# TI-Basic, 22 bytes
```
startTmr
For(A,-ᴇ3,ᴇ3
Disp A
End
startTmr-Ans
```
* Many commands are represented by 1 or 2-byte tokens.
* Tested on an emulated TI-84 CSE.
[Answer]
# Matlab, ~~16~~ 23 Bytes
```
tic;(-1e3:1e3)'
toc*1e3
```
Edit: I realised I was violating several of this challenge's rules. That'll teach me to skim read the challenge late at night. I also now realise that the corrected answer is almost identical to the Octave solution, but such is life.
Prints each element in the created linear space array -1000:1000 (the lack of ; prints to console).
tic/toc records the time and toc prints the time to the console with or without the ; . 1e3 is needed to print in milliseconds.
[Answer]
# Groovy, ~~75~~ 73 bytes
```
t=System.&nanoTime
s=t()
(-1000..1e3).each{println it}
print((t()-s)/1e6)
```
Thanks to [jaxad0127](https://codegolf.stackexchange.com/users/56408/jaxad0127) for saving 2 bytes!
[Try it here !](http://ideone.com/PJYD74)
[Answer]
# [8th](http://8th-dev.com/), ~~61~~ 47 bytes
*Thanks to [8th\_dev](https://codegolf.stackexchange.com/users/64527/8th-dev) for nice improvement* (saved 14 bytes)
```
d:msec ( . cr ) -1000 1000 loop d:msec swap - .
```
This will print all the integer numbers between -1000 and 1000 in ascending order and the time taken (in milliseconds) to print these numbers
```
-1000
-999
-998
-997
...
997
998
999
1000
4
```
[Answer]
# Japt, 23 bytes
There are two equivalent solutions:
```
Oo(Ð -(A³òA³n @OpXÃ,йn
K=Ð;A³òA³n @OpXÃ;OoÐ -K
```
The first one basically does the following:
```
output(-(new Date() - (1000 .range(-1000).map(X => print(X)), new Date())));
```
That is, the numbers are printed in the middle of the subtraction to avoid having to store the time in a variable. However, it's not any shorter than the variable route, which is basically:
```
K = new Date(); 1000 .range(-1000).map(X => print(X)); output(new Date() - K);
```
In the latest version of Japt (newer than this challenge), `K` is set up to automatically return `new Date()`. This cuts the first solution down to 21 bytes:
```
Oo(K-(A³òA³n @OpXÃK)n
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.3&code=T28oSy0oQbPyQbNuIEBPcFjDSylu&input=)
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 34 bytes
```
d=timer[-z^3,z^3|?a]?z^3*(timer-d)
```
Uses the QBasic `TIMER` function, which returns seconds in decimal notation. Making it look pretty adds some bytes.
Explanation
```
d=timer Set 'd' to the current # seconds since midnight
[-z^3,z^3| FOR -1000 to 1000 -- Note that 'z' = 10 in QBIC, and z^3 saves a byte over 1000
?a Display the iterator
] Close the FOR loop
timer-d Take the current time minus the time at the start of the program -- 0.156201
?z^3*() Multiply by a thousand and display it 156.201
```
[Answer]
## C++ - 261
Just for a laugh I thought I'd post a C++ answer.
```
#include <iostream>
#include <chrono>
using namespace std::chrono; using c=std::chrono::system_clock; void p(){c::time_point n=c::now();for(int i=-1001;++i<1001;)std::cout<<i<<"\n";std::cout<<(duration_cast<milliseconds>(system_clock::now()-n)).count()<<"\n";}
```
I'll leave it as an exercise to determine what it is doing and how to call it - shouldn't be too difficult.
[Answer]
# Scala, 77 bytes
```
def t=System.nanoTime
val s=t
Range(-1000,1001)map println
println((t-s)/1e6)
```
[Answer]
# ForceLang, 124
```
set t timer.new()
set i -1000
label 1
io.writeln set i i+1
if i=1000
io.write math.floor 0.001.mult t.poll()
exit()
goto 1
```
Note: You should supress `stderr` when running this. I believe the consensus on meta is that this does not incur a byte count penalty.
[Answer]
# [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate), 92 bytes
What really killed me was the need to record the time.
```
{@callmicrotime intoX 1}{@for_ from-1000to1000}{@echol_}{@/}{@phpecho microtime(1)-$DATA[X]}
```
Since there's no math (yet), this makes things pretty hard, forcing me to write PHP directly.
**Ungolfed:**
```
{@call microtime into start_time true}
{@for i from -1000 to 1000 step 1}
{@echol i}{@// echoes a newline after}
{@/}
{@php echo microtime(true) - $DATA["start_time"];}
```
---
**Disclaimer:**
I've ran this with the commit [e118ae72c535b1fdbe1b80c847f52aa161854fda](https://github.com/ismael-miguel/SimpleTemplate/tree/e118ae72c535b1fdbe1b80c847f52aa161854fda), from 2017-01-13.
The latest commit was to fix something that is un-related to the code in here.
[Answer]
## C ~~134~~ 133 bytes
Thanks to @Thomas Padron-McCarthy for saving 1 byte.
```
f(){clock_t s,e;s=clock();for(int i=-1000;i<1001;i++)printf("%d\n",i);e=clock();printf("%lf",((double)((e-s))/(CLOCKS_PER_SEC))*1e3);}
```
Ungolfed version :
```
void f()
{
clock_t s,e;
s=clock();
for(int i=-1000;i<1001;i++)
printf("%d\n",i);
e=clock();
printf("%f",((double)((e-s))/(CLOCKS_PER_SEC))*1e3);
}
```
[Answer]
# [Gura](https://github.com/gura-lang/gura), 75 bytes
```
t=datetime.now();println(-1000..1000);print((datetime.now()-t).usecs/1000);
```
[Answer]
# Clojure, 94 bytes
```
(let[t #(System/currentTimeMillis)s(t)](doseq[n(range -1e3 1001)](println n))(println(-(t)s)))
```
I'm disappointed at how long this got, but I guess no one ever claimed Clojure was a good language to golf in.
Naïve solution that just records the starting time, loops, then prints the current time minus the starting time. Unless Clojure has a ms-time getter than I'm missing, I don't know how this could get any shorter. Maybe some kind of implicit loop?
```
(defn time-print []
(let [t #(System/currentTimeMillis) ; Alias the time-getter to "t"
start (t)] ; Record starting time
(doseq [n (range -1000 1001)] ; Loop over the range...
(println n)) ; ... printing the numbers
(println (- (t) start)))) ; Then print the current time minus the starting time.
```
] |
[Question]
[
[Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), the [Language of the Month](https://codegolf.meta.stackexchange.com/q/24222/), has the "collect" builtin as `BC`. Your task is to implement this builtin.
---
Consider a non-empty array, where each element is either:
* A positive digit between `1` and `9` inclusive, or
* A non-empty list of positive digits between `1` and `9`
For example, all the following such arrays meet this definition:
```
[1, 2, 3, 4, 5]
[7, [5, 3], 2]
[1, [2, 2], 3, [4, 4], 5]
[[1], 2, 3, [4], 5, [4], 2]
[[9, 4, 2]]
[[1], 2, 3, 4, 5, [6], 7]
[6, [1, 9, 4]]
```
Note that elements can be repeated, both the digits, the inner lists and the elements of the inner lists.
The `BC` builtin "collects" adjacent digits in the array, and groups them into a list, while leaving the existing lists untouched. Applying this to the above lists, the examples make this clear:
```
[[1, 2, 3, 4, 5]]
[[7], [5, 3], [2]]
[[1], [2, 2], [3], [4, 4], [5]]
[[1], [2, 3], [4], [5], [4], [2]]
[[9, 4, 2]]
[[1], [2, 3, 4, 5], [6], [7]]
[[6], [1, 9, 4]]
```
For example, with `[[1], 2, 3, 8, 9, [6], 7]`, we group the `2, 3, 8, 9` together, and the `7` to give `[[1], [2, 3, 8, 9], [6], [7]]`
You should take a ragged list as input, that meets the list format described above, and output a list of lists after the `BC` builtin has been applied to the input. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
```
[[9, 4, 2]] -> [[9, 4, 2]]
[6, [1, 9, 4]] -> [[6], [1, 9, 4]]
[7, [5, 3], 2] -> [[7], [5, 3], [2]]
[1, 2, 3, 4, 5] -> [[1, 2, 3, 4, 5]]
[1, [2, 2], 3, [4, 4], 5] -> [[1], [2, 2], [3], [4, 4], [5]]
[[1], 2, 3, 8, 9, [6], 7] -> [[1], [2, 3, 8, 9], [6], [7]]
[[1], 2, 3, [4], 5, [4], 2] -> [[1], [2, 3], [4], [5], [4], [2]]
[9, 8, 7, 6, [5, 4, 3], 2, 1] -> [[9, 8, 7, 6], [5, 4, 3], [2, 1]]
[[8, 2], 9, 5, 1, [6, 4], [4, 5]] -> [[8, 2], [9, 5, 1], [6, 4], [4, 5]]
[7, [5, 3], 2, [1, 2, 3], 9, 8, 7, 8, 9, [3, 4], [1], [2]] -> [[7], [5, 3], [2], [1, 2, 3], [9, 8, 7, 8, 9], [3, 4], [1], [2]]
```
[Answer]
# [R](https://www.r-project.org/), ~~76~~ ~~75~~ 71 bytes
Or **[R](https://www.r-project.org/)>=4.1, 64 bytes** by replacing the word `function` with a `\`.
*Edit: -1 byte thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
function(x){y[]=cumsum(c(T,y<-sapply(x,is.list))|y);tapply(x,y,unlist)}
```
[Try it online!](https://tio.run/##hVJNa8MwDL3vV/hWG7xB3HzS9l/sluZQAoFAm5YlgZpuvz2zZHm13cAukSzpSS9P@lq6w9LNQzv114HfxUPXzaGdL@N84S3/lHr/Pp5ut7Pmd9mPH@d@nIT41mI3uaiW84Dhn6Xj4NhPJVkqmRKCiR1rTxPf1DXFmuY4HIeNeKP6XDK0iWRQEUDyRrKaEjGuIFwm2VbALA9XAA4SYF8mmobK5JBO5sOCxAoKrYJZWIXPFDjHfXAs/KuxyAGqkFPc1bYWbnCJ/2p1McFirSuVwQv1Kf7paWkCR89Xq52RquXpvBf1Khxv1M@fC0hpB5Il0caplPaRupWYwlXWpRW3QrJO8dxK7OTOghMpSWaCoCok9toW46t5Hp@ykT/O3iq2HoHEOeFxRxdnz9ZJGvTEmyCGSaDw8gs "R – Try It Online")
### Explanation
```
function(x) # take x as input
{
y[]= # assign to elements of y (to preserve length of y)
cumsum( # cumulative sum of
c(T, # TRUE followed by
y<-sapply(x,is.list)) # which elements of x are lists themselves
# (assign this to y)
|y # or y
); # this creates a mask on the positions of lists or first non-list elements
tapply(x,y,unlist) # apply unlist to x splitted by y
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
```
lambda L:eval(re.sub("[^\d]{3,}","],[",`[[0,L,0]]`))[1:-1]
import re
```
Textually replaces every stretch of more than 2 non digit characters (i.e. everything that is not ", ") with "],[". A little trickery at the ends is required to guarantee balanced brackets.
[Attempt This Online!](https://ato.pxeger.com/run?1=bZLNTsJAEMcTj_sUk562yUJogfKR1Ise8QmGUUooYZNCm1IkxvgkXkiM8Zn0aezuDkKRU3dm_vObr75_FS_VKt-Eh49lPP3cVcvW8Ps-S9bzRQKTcfqcZLJM29vdXHr4OF3Qa1e9ecojhZ6aIXbURHWIZr6PwbgVkNDrIi8rKFNm3e1XOkshGAvQKocY1kkhDVaVyf5Jb4pdJf32tsh0JT1o3YLn-wKKUm8quZTaj-Pcd6jDz80D4khBT0FIZLRnpsBIAQYKjOcYjejcJ3BQm30FXTIpTjKgkw8tp9aHtW3BfVY1fU6EoaFYL_ZMgTM5ncJoySxAm2zjjje0zdlGBxfJHCUO1502U9FW5G94mUwcqCseX3a6kaXWi4jc3D1eh4LgtFJWUEOCVmN6GLrJRra82UTE07ntOAyLkFX0T9Y8hzsUd_7XAq-ny4kBj3H1dA0CNhB0hSGE-61-AQ)
#### Old [Python 2](https://docs.python.org/2/), 73 bytes
```
lambda L:[map(int,x[1::3])for x in re.findall("(?:.\d.)+",`L`)]
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZLNasJAEMehxzzFkNMuXQOJGjWQ9tBTwT7BuNQUDS7EJKSx2mfpRSilz9Q-Tfdj_Ij1lJ2Z3_znKx_f9Xu7qspo_5mns69Nm_fGP49Ftn5ZZDBNcJ3VTJWt2GGYJH3J86qBHagSmmWQq3KRFQXz2X0SzBYBv_XFfDrn0lPrumpazZDgw3aliiWEiQdKVJCCkV2-ZYVosu2zKutNy3jwWheqZT707sDn3IO60ZVZzhRP04o7qf3vzRPiRMBAQCSlYc9MD2MBGAownkM0luc-D0faHAroS5PikJE8-dDqaD7SthUeEtX1OQgjo2K9ODAFznB5CqNVJgBtso07vbFtzjY6ukimqKSw7rSbirYifaPLZEkBXfHwstNNrKpeROzmHtA6BISnlRIhOwhaxvQwdpNNbHmziZimc9txMgQhUfIf1j2HOxR1fmyB1tOnxJDGuHq6jgJ2JOQVDc9zv9Uf)
Just a stoopid regex that finds stretches of digits alternating with two arbitrary other characters (in the repr of the input).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~30~~ 27 bytes
```
##&@@@#&/@Split[#,#>0<#2&]&
```
[Try it online!](https://tio.run/##VY/NCoMwEITvvkYgpyk1/gut5BFaPBYPIkqFKqXY0xJf3e5GCu0lYWY/Znandrn3U7uMXbsN500pba1V@mjr52NcbgqqCk8q0o3eru@xX@zlNc7sH6rBqkavddfOKwVEJRJEziGgDGTA0osclCJ2PGJhECFmLt0FRWLHoITh3STjvgwoc8h/TRLKvz6tRIEcmRQkvgLG04WMSya5IZNkksa/ZbCvIphkFPyTCWE4QMqIDwnc9gE "Wolfram Language (Mathematica) – Try It Online")
```
Split[# ] group adjacent items which
,#>0<#2& are both positive (non-lists)
##&@@@#&/@ remove extraneous brackets
```
At times like this, it'd be nice if `@@`, `@@@` generalized to more `@`s...
[Answer]
# [J](http://jsoftware.com/), 22 19 bytes
```
<@;;.1~2+./\1,#@$&>
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/bRysrfUM64y09fRjDHWUHVTU7P5rcqUmZ@QrpCkYWhtZG1ubWJtamymYW1tYa@hYagIJQwNNa0NDiCJ1x7wUhdTE5AyF5NScHIXMYoW8/HKFRIWczOISPT09dYgqoKmEjPsPAA "J – Try It Online")
-3 thanks to Bubbler
This is a little tricky in J, which requires boxes for heterogeneous arrays. The task becomes to "collect" iff the box contents are atoms. Contents which are already lists (either 1 items or more) should remain as single boxes.
Our strategy is then to "cut" (start a new group) unless adjacent elements are both atoms.
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 46 bytes
```
:slice_when+:|%([~:*&0|:!=&0]*2)|:map+:flatten
```
[Try it online!](https://tio.run/##bZDRCoIwFIbve4p1kZQu0KlTBz7JYYSFUmEiZEQgvfrazmZ64dXYd85/zrfdj6/zRzWlEs/2dqlP72vdBWLc7eErfC8cxbb0QumzwygeVR@Ipq2Goe5UTxoAKChJKGFSErlBwimBiBLDZ5hpmFISS9M6Qd3FNMMB6ZICM21YgsTMWdYhklMuxzXANcjW6oBJd857C0xqJW6tEidGSTRPya1CgQOME7cigLKrD7MPZ/b2X@IkYxc3doDfpX4 "J-uby – Try It Online")
Today I learned about `slice_when`, and J-uby's `+`.
-4 from translating GB's idea.
# [Ruby](https://www.ruby-lang.org/), 49 bytes
```
->a{a.slice_when{_1*0!=0||_2*0!=0}.map &:flatten}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZBNCsJADIVx6ynixoVMpTP9sRUq3iMMpUqLghbRFpHqSdwU0UPpaZzJtNZFV5l5yUu-5P48lqtL_ciiV1lkVvDm1iKpkulpt12n8XmT5lXMJ_Yosq_XWNDjNt0nBxjPs11SFGl-M8bPYHmADBFDBi4DISXIISk-A-QMtN6JMyV6DBypS1tRVQmlUQPvX0WhyyiFru7zn0cuW19AY9BXwqwvj-RsYjc3JKdC8g2V24Ax4F2XwCCE1EAz-QYECbZ3MbO4ML_fkAbSaeyaDulc5pB1beIX)
-6 bytes from GB.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~6~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
If the sub-arrays in the input could be nested another level deep in the output then the last 3 bytes could be removed.
```
ó* mc
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8yogbWM&input=WzEsMixbOSwyXSwzLDQsNSxbNiw3LDgsOV0sNSw0LDMsMiwxLDgsOF0KLVE)
[Answer]
# [Factor](https://factorcode.org/) + `splitting.extras`, ~~43~~ 42 bytes
```
[ [ array? ] split*-when [ flatten ] map ]
```
[Try it online!](https://tio.run/##bVDBTsMwDL33K3xGWkTWla1w2HHiwmXiVPUQFY9VlCwkRmOK8u3FSQqdBIniWO/lPTs@qI5OdnzePz7t7kFZqy4OnBl6ol6/Cvwiqxy8odU4gMOPT9QdujkTL4gGjEWii7G9JngoCl8AL8@7hhUsIUCYkDs@MqEztuZTQcnI8heTnJf8qrpCPGPRq@RslRxmNvIhaTbsHusE9v3L@kmX77lezbp16q5iJvcir/SbVLlmVib3qPa5v3//8fODMDnnruQtSJmUOebJhLGBJo9@C20e/s3ifETN8GFQRJy18K4MtGOMDQghGEHVHcdv "Factor – Try It Online")
## Explanation
* `[ array? ] split*-when` Split on arrays (sublists) and keep the delimiters.
* `[ flatten ] map` Flatten each element. `flatten` doesn't touch arrays of depth 1 but otherwise decreases depth to 1.
```
! { 1 { 2 2 } 3 { 4 4 } 5 }
[ array? ] split*-when ! { { 1 } { { 2 2 } } { 3 } { { 4 4 } } { 5 } }
[ flatten ] map ! { { 1 } { 2 2 } { 3 } { 4 4 } { 5 } }
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 bytes
```
->l{l.chunk{|x|x*0}.flat_map{|a,b|a==0?[b]:b}}
```
[Try it online!](https://tio.run/##BcHhCsIgFAbQV@n3@BItNyuwHuRyCR3IIAuJBIf67HbON/t9BDuO91ijWLf8edVWWplkFyG63/PtUm0Ovjlr5YM833zvIx0CkcIJZ5BmzFhgQBdcGWQMlGbm8Qc "Ruby – Try It Online")
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 21 bytes
In order to do this I needed to add support for `Either` types to hgl.
I was planning on doing this eventually and I don't think knowledge of this challenge influenced the way things were implemented.
So this is *non-competing* for whatever that means to you.
```
fR p<tv(mst p)<+gB ø
```
This takes a `List (Either Int (List Int))` to represent a ragged array.
Surprisingly we can do flip the order of the `Either` at no cost to bytes.
```
fL p<tv(mst p)<+gB ø
```
## Relfections
There are some things here that could be improved.
* `m<mst` should get it's own command. It's not used here but if I had had it this could have been 1 byte shorter:
```
fR p<sQ<m2t p<+gB ø
```
where `m2t = m<mst`. (Implemented in [871c2406](https://gitlab.com/WheatWizard/haskell-golfing-library/-/commit/871c240698fa7d0420ccb4115b4e51619607587d))
* There needs to be a `Bitraversable` class. The whole reason we have `mst p` a very costly construct is that we need to massage the correct monoid instance onto the left hand side of the `Either`. If we had `Bitraversable`, the entire `tv(mst p)` could just be a `bisequence`.
* Other `Bifunctor` classes might have also helped here and are probably needed in the long run. `Either` isn't the only type that would benefit from this. We have other bifunctors like `(,)` and `These` which would benefit as well.
* Here I expressed ragged lists as lists of either the element or more lists. This works for ragged lists of max depth 2 fine, but it would also be possible to represent ragged lists more generally using the free monad combinator. If I had that I could have tried an approach with that, and even so I should probably have that for future challenges where the depth restriction might not exist.
Most of these basically boil down to "better bifunctor" support, so I think some of that is warranted.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes
```
ŒḊ€aJŒg⁸ṁF€
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7uh41rUn0Ojop/eHORodDW92A3P@H24EyO2f8/x9trqMQbaqjYByro2AEZBqCKRDPUkfBQkfBHEwC2dHGOgomsSAVIMIoNhYA "Jelly – Try It Online")
```
ŒḊ€ Depth of each (1 for lists, 0 for numbers)
aJ Replace each 1 with its index [0 0 1 0 1 1] -> [0 0 3 0 5 6]
Œg Group runs of equal elements [[0 0] [3] [0] [5] [6]]
⁸ṁ Reshape the original input to this list
F€ Flatten each element (turns entries like [[1 2]] back into [1 2])
```
This approach feels elegant in theory, but a lot of bytes are wasted on `€@µ€`, so there might be saves.
Jonathan Allan saved a byte! Thanks.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~84~~ 79 bytes
```
s=[]
for x in input()+[{}]:
if x>9:
if s:print s
s=x[:0];print x
else:s+=x,
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN_2LbaNjudLyixQqFDLzgKigtERDUzu6ujbWikshM02hws7SiosTyCi2KijKzCtRKObiLLatiLYyiLWGCFRwKaTmFKdaFWvbVuhAjIWavmBfdLRhrI6CkY6CsY5CtAmQaaqjYAllGsVCVAEA)
-5 bytes thanks to @ovs
[Answer]
# [Vyxal 2.7.1](https://github.com/Vyxal/Vyxal), 6 bytes
```
ƛf⁼;Ġ•
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGm2bigbw7xKDigKJ2ZiIsIiIsIls3LCBbNSwgM10sIDIsIDRdIl0=)
The link uses the latest version of vyxal (2.7.3 at the time of writing) which has a bug fix where molding no longer wraps singletons in lists, hence the extra `vf`.
## Explained
```
ƛf⁼;Ġ•
ƛf⁼; # For each item in the input, does the flattened version equal the item? For integers, this returns a list, which does not equal the item. For lists, this just returns the list - this wouldn't work if there wasn't any depth restriction.
Ġ # Group on consecutive items
• # and mold the input to that shape
```
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 6 bytes
```
L*~,BC
```
[Try it online!](https://tio.run/##S0xJKSj4/99Hq07Hyfn////R5grRpgrGsQpGsf/yC0oy8/OK/@tmAgA "Add++ – Try It Online")
~~Wow holy crap a challenge where Add++ will probably win.~~ Nevermind I tied myself with vyxal.
## Explained
```
L*~,BC
L*~, ; a lambda that dumps its arguments onto the stack and returns the entire stack that:
BC ; calls the built-in this challenge is all about.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Really not sure if this is optimal, it's just the first way I though of...
```
,⁻;ɗƝŻœṗ⁸F€
```
**[Try it online!](https://tio.run/##XVC7DcIwEO0zxQ1wjZ3EcUTPDujkkgZlAcrQ0EMRGjZgAKKUyEiMkSxizmcLoTS238/v7MO@644h4NJPm8/wvvvJX@dxWPrndjk9wuvMq7/M4433XQhUELUIFYJ2DgsyCKQQIiW4YVwjlC4aGLOmGUqizgRpESNLVQxmiZT7d7NqmGhWEok/79LB5ZZ9CCaVV7kfQUnWprpWYrHfpFKSmdZTpwfphH5XWzlTmZNxHJIfcF8 "Jelly – Try It Online")**
### How?
```
,⁻;ɗƝŻœṗ⁸F€ - Link: list, A
Ɲ - for each of the neighbours:
ɗ - last three links as a dyad, f(left, right):
, - pair them (e.g. [1,2] and 3 -> [[1,2],3]])
; - concatenate them (e.g. [1,2] and 3 -> [1,2,3])
⁻ - are these not equal? (i.e. was either left or right a list?)
Ż - prefix a zero
⁸ - use A as the right argument of...
œṗ - partition right at truthy indices of left
F€ - flatten each
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 34 bytes
```
(?<=^\[|], )[^][]+(?=, \[|]$)
[$&]
```
[Try it online!](https://tio.run/##XU@7DoJAEOz5ii3QQNyGAw5IJJR@xLhECwsbC2Lpv5@3e6eJVpd57cxtt@f9cQ276nQJ1XKc1zNewlRjFcihWmYmZcq6QLmXEICJqWNyIgU8ExomZRQOEfZMrahcqOIiMnufMJxKRqLTVFLQyMc72jn4SAy/CsydX70/mTuW@tTb5WqmRpNjqpospN0@FcLm/M1NH3EJfQ/nMW0O6hbEj78B "Retina 0.8.2 – Try It Online") Link includes test cases. Would be 32 bytes if I could be bothered to remove all of the spaces from the lists. Explanation: Simply matches sublists composed of non-lists that are between two lists or positioned at the start and/or end of the main list and wraps them in a list. Using lookarounds to anchor the match avoids having to explicitly capture the sublist thus saving a byte.
```
(?<=^\[|], )
```
Match at the beginning of the main list or after a list.
```
[^][]+
```
Match anything that isn't a list.
```
(?=, \[|]$)
```
Match at the end of the main list or before a list.
```
[$&]
```
Wrap the sublist in a list.
[Answer]
# [Python 3](https://docs.python.org/3/), 87 bytes
```
lambda L:[[*x]for t,g in groupby(L,type)for x in[g,[g]][t==int]]
from itertools import*
```
[Try it online!](https://tio.run/##bZHJjoJAEIbvPEVlTmBaE1FxSfAJfIOaOmAE7IQtTTuRp2d6KUdxPEHV/9VfS3eDvrbNaizS77HK6vMlg9MBcXanolWgRQmygVK1t@48hCehhy6PrHI3eSwFlkSo01Q2migoVFuD1LnSbVv1IOuuVXo2@i/0Qx/Y0ko2uXU18aLXF9kcAoAqL7QAJcurhhTqrAvzn6wSDl70XSV1@DU/fkWRYVXe3yqLFaEts6lOmQnCh5B6I8FkNCLuBawFxEQwP8JLGGAiAJcCbOahJvSaC3Brwo2AFdkSj2zpmUPnY/jYxM54w9Q05yGMrYvL4to2eMHpKaNzZgBdsdO9384N5wbdvhWzSiybSael6DryN34vJhZMx8ef227vXM0hEr/3ms8hYPk8KRM0QdAxdoad32zv2ttLJLydv463YQiZon/Y9Dn8Q/HkfyPweVZcuOQ1Pj7dxAEnFvTB4xc "Python 3 – Try It Online")
Group the list by type (int or list), then wrap the int groups in list.
I thought `groupby` would be great for this job, however the `itertools` import ended up costing too many characters.
# [Python 2](https://docs.python.org/2/), 84 bytes
```
def f(L,s=[]):t=s and[s];return L and[f(L[1:],s+L[:1]),t+L[:1]+f(L[1:])][L>[[]]]or t
```
[Try it online!](https://tio.run/##bZHbjoJADIbveYrGK4ijCaiobPAJeIOmFybCOgkiYcZNfHp2plMP7HoF/fv172H6uz1fu2wcT3UDTVwpUyIlhS0NHLsTGvoaansbOqg4dgSmBSkzr7BIKVE2/MwlkRBWB0Qiug5gR33pr4MFczdR44RWdzXozsdLY0@6KyKAtm6sgkF/ny2UcDn2cf1zbBXDS9O32sazxWGWJI4danNrPdbEvsxL/aA7@0yUwUiJMCLuFawVZESwOMBbGGGuAFMFXnlkc3rXIty6cKNgRb4kIFt6acg@js9czMYboaZagDDzLqzi2jd4w@mVRnYWALmY88Fvx8PxoNs/xZIlSbtJp6XIHeWb/S0mSbiOjz/ebs@u7hB52Hst51CQvk4qBE0QZMbPsAub7bm9v0Qu24XrBBuBUCj6h02fIzyUTP4cQc6zksJU1vj4dBMHnFjQB49f "Python 2 – Try It Online")
```
f=lambda L,s=[]:L and[f(L[1:],s+L[:1]),(s and[s])+L[:1]+f(L[1:])][L[0]>9]or s and[s]
```
[Try it online!](https://tio.run/##bZHbjoJADIbveYrGK4ijWdBFIcEn4A2aXrAR1kkQCcNu4tOzM516wPUK@vfr38P01/F06ZJpaoq2On8dKyiVKZDyEqruiE1YYpyTMssS85giFRrWDUVeWQoREZb4QYeMLgPcmEmf@8swgrmaoLF6q7sadOfitRmPussDgLZuRgWD/j6NUMC56sP6t2oVw2vTt3oMF6vDIoosO9Tmp3VYE7oyJ/WD7sZ7ovBGSoQJMVOwVZAQweoAT2GAqQKMFTjllk3pWQtwZ8NPBRtyJR7Z0UND9rF8YmM2/hRqrnkIE@fCKm5dgyecHmlkZwGQiznv/fY8HA@6eymWLEnaTjovRe4o3@S1mCRhO97@eLuMXe0hUr/3Vs6hIH6cVAiaIciMm2HvN8u4vbtEKtv563gbgVAo@ofNn8M/lEx@H0HOs5HCWNZ4@3QzB5xZ0BuPPw "Python 2 – Try It Online")
I tried to golf [@pxeger's answer](https://codegolf.stackexchange.com/a/240515/92237) by using recursive function, but wasn't able to save any bytes.
These 2 functions simply loop through each element. If the current element is a digit, accumulate it in the list `s`. If the current element is a list, add the accumulated elements (`s`) if not empty to the result, followed by the current element.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 57 bytes
```
a=>a.flatMap(c=n=>n[0]?c=[,n]:c[0]?c.push(n)&&[]:[c=[n]])
```
[Try it online!](https://tio.run/##fZLBboMwDIbve4qcKpAyOiiF0onuCfYElg8RK90mFNDo9vosMR6QkvVEZH/@bf/4U/2ovvr66K6Pun07D3U5qPKkorpR11fVBVWpy5OGJ3ypSpAajxW9o@67fw90uNkAHsGkNGI4VK3u2@YcNe0lqAOAQopUisSkwmex3YpF5OGGzaSAWAqbX@AZLsO3NblJ7qXYoVWcanKcw@DpZOQSk6VB9nOZG/ZVQWL7EAOpHcitx5kA6s0MeNSIHtsdaDvaNF@rMYBMmOXuaQHNxN/Eo4acMzP9vTwOFdTUuJuNTqbssRSx8ycZQocCwtZTHkZrChrQupmxPaPfky5zwCCuyHtXMF4LbzpNyBbvWCbmtf@7GEcEHBX0yAy/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.γd}€˜
```
[Try it online](https://tio.run/##yy9OTMpM/f9f79zmlNpHTWtOz/n/PzraMFbHSMdYx0THVCfaLFYn2jxWx0LHMhYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vXObU2ofNa05Pee/zv/oaEMdIx1jHRMd01gdhWhznWhTHeNYHSMQx1An2gjEMtaJNtExiYWoiDaMBWuIBgmASbDaaEugEUaxyCpMQPJmsTrmIEEzHaBxQDVYVUQDlVjoWMbGAgA).
**Explanation:**
```
.γ # Adjacent group-by:
d # Transform every integer into a 1 (with a >=0 check)
}€ # After the group-by: map over each group:
˜ # Flatten it
# (after which the list of lists is output implicitly as result)
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), ~~13~~ 11 bytes
```
{n!z?}gB)FL
```
[Try it online!](https://tio.run/##SyotykktLixN/V9dlPi/Ok@xyr423UnTzed/bXjO/2hDHQUjHQVjHQUTHQXTWK5ocx2FaFOgQCxQHMgFSkcbgZhgNdFARSaxEIXRhrEwrdFgMSgN0hVtCTbPKBZVnQlElRlQwBwoYwZkA80HqY2NBQA "Burlesque – Try It Online")
```
{
n! # Not for ints (if 0 then 1 else 0); most common element for lists
z? # Is zero
}gB # Group by is list
)FL # Flatten each resulting list (double groups those already as lists)
```
Since the lists are always non-zero we can get away with this hack.
An alternative is doing a list/int only op and then seeing if there's an error (e.g `tpis` transpose-iserr) unfortunately no single op I know can test for `is list`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
⊞υ⟦⟧FA¿⁺ι⟦⟧⊞⊞Oυι⟦⟧⊞§υ±¹ι⭆¹Φυλ
```
[Try it online!](https://tio.run/##JYwxD4IwEIV3fsWNd0kdAA0aJhcTBpXEsenQYJEmDZDSGv99bcvy3ru8790wSTss0oTQ@21Cz4ALaotxsYDdvHqHRKBHwN74DXWuCTKb5LkqK91i01DTPgZlNrUjV9fNb/VL7UN9pFNYEiWyLXqrZ4cvF@1zlyuWDG7aOJVfGSJqQ@AFb@LPE4NaMKhiLLOl68LgzKDJGjOvGRxFIpJUQhQiHL7mDw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⟦⟧
```
Push an empty list to the result in case the first element of the input is not a list.
```
FA
```
Loop through all of the elements of the input list.
```
¿⁼ι⟦⟧«
```
If adding the empty list to the element doesn't produce an empty list, then...
```
⊞⊞Oυι⟦⟧
```
... the element was a list, so push it to the result, plus another empty list in case the next element of the input is not a list, otherwise...
```
⊞§υ±¹ι
```
... append the element to the last list of the result.
```
⭆¹Φυλ
```
Filter out any empty lists (e.g. from consecutive lists in the input) and pretty-print the result.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 29 bytes
```
["[["|"], ["]"]]"L`\b[^][]+\b
```
[Try it online!](https://tio.run/##XU8xDsIwDNz7CisSEhJZkrZp8wIWfnA1KpUYWBgQI38PsR2QYLLOd@c7P67P2/0Sym5/XAsc4F6OPcGxY3anddlwZvBh2UoBsqfBU2TukKooeJKNwKnC0VPPQnfCxIpUPhpGFEqXGMRlDAJ/tLOeQ6qL6ZeBqtuU@1nVNTRZ7tCiPQVxzhaV1STZyQKhdf7q2iPR0PdwK9M3o3RBffwN "Retina – Try It Online") Link includes test cases. Explanation: Based on @loopywalt's idea. Would be 28 bytes if I could be bothered to remove all the spaces from the lists.
```
L`\b[^][]+\b
```
List all runs of digits and separators (but excluding `[]`s).
```
["[["
```
Precede the entire result with `[[`.
```
|"], ["
```
Separate each run with `], [`.
```
]"]]"
```
Suffix `]]` to the result.
[Answer]
# [Perl 5](https://www.perl.org/) & probable regex polyglot, 53 bytes
```
s/(?<!\]),\[|],(?!\[)/],[/g;s/^\[+(.*[^]])]+$/[[\1]]/
```
[Try it online!](https://tio.run/##DctBCsJAEATAtwQ87JrWIZKViEIe0tO5iQhiFtejb3e07lWvr0eJaJbmS@fKcH6ENHfObALtdm62OPu033KRsvqNkT5IFkFOOAgnFAzgEeN/jCjSd63v@/pssas/ "Perl 5 – Try It Online")
First change all "`],`" or "`,[`" to "`],[`"; then make sure it's all enclosed in "`[[`...`]]`".
I forgot the second bit on my first attempt, so it seemed a bit golfier than it turned out...
[Answer]
# [Julia 1.0](http://julialang.org/), 81 bytes
```
+(x,y=[])=x>[] ? x[1] isa Int ? x[2:end]+[[y...;x[1]]] : [y;[x[1]];+x[2:end]] : y
```
[Try it online!](https://tio.run/##bVHLboNADLzzFVZOILZIkIS8RHruoV9g@bBRqLQVohHQCr6e7nqdJpsmF@KZ8Xjs/fxujM7HeU7jUU0VUlKNRyR4hRFzAtNreGsHLot93Z4pRZyyLDs4mgj2gNMBuTikV42Dpzn6@OrAgGmhq/W5MW3dx0kE9qfVCSqof3STxe/1oLOL7vo6i/tLY4bYKFjAyxEWSeLll860Q9PGGqojpDoEU4tWcEoiO5iJGXGnYKWgsDmszV0ZYakAcwUOubIl3WMRbmy5VrAk1@IlG7phyD5WX9iajdeiCjEvwsK5MIorN@BOTjca2VkEyM3Me78th@Ogm4dmYUlomzRsRZ4o3@KxmYSwE6//eLsdu9pDlH7vlZxDQX47qSgokCBrXIat32zH490lStnOX8fbiAhFRf9k4XP4h5LkfxHkPEtpzGWNp08XOGBgQU88fgE "Julia 1.0 – Try It Online")
a recursive approach
# [Julia 1.0](http://julialang.org/), 82 bytes
```
f(;y=[])=y
f(x::Int,X...;y=[])=f(X...;y=[[y...;x]])
f(x,X...;y=[])=[y;[x];f(X...)]
```
[Try it online!](https://tio.run/##bVHLasMwELzrK5acZFANdhLnhXPvoffCsgeF2KBi3OC4xf56V491EqXRRdqZ2dmHvn4ao7Nhmmp5GEukpBxFLYf9/r3t1WeapozWcg5wdI@BKHHCRw2OBxzoEKQJTaL@7sCAaaGr9LkxbXWViQB7tDpBCdWvblL5UfU6vejuWqXyemlML42CBbwdYZEkQX7pTNs3rdRQHqGW2tnHDINQlnBKRNWePTthRs4I7U0CcadgpSAnBm@hwEIBZgocMrMFPWICNzZcK1iSSwmSDd0x9D5Wn9vYG6/n2hEWRJg7F4/iyhV4kNOdRu/MAvTJng9@W9@cb3TzlMwsMW07jVPRV@Q7f04mJmzF@eWn23lXu4gizL3idSjI7itlBUUS9BrXwzZMtvPl3SYKni5sJ9iwCFlF/2Txd4SP4s5vLfB6lpyY8Rgvvy5ywMiCXnj8AQ "Julia 1.0 – Try It Online")
the same idea, but with multiple dispatch
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes
```
⁽-ḊƛÞj∷ßw;Þf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigb0t4biKxpvDnmriiLfDn3c7w55mIiwiIiwiW1s4LCAyXSwgOSwgNSwgMSwgWzYsIDRdLCBbNCwgNV1dIl0=)
[Answer]
# [Arturo](https://arturo-lang.io), 37 bytes
```
$=>[chunk&=>[integer?&]|map=>flatten]
```
[Try it](http://arturo-lang.io/playground?ZYuhbd)
] |
[Question]
[
My dad is a retired teacher, and he used to give combined spelling and math quizzes, where the student would spell a word, and then 'score' the word by adding up the letters, where a=1, b=2, etc. (e.g. cat = 3+1+20=24). This made grading the quizzes easier, as he would just have to check for incorrect 'scores' rather than incorrectly spelled words, and had the added benefit of testing 2 skills at once.
He hired a friend of mine to write a program that would score words for him, so he could generate lengthy answer keys without error. This problem is inspired by that program.
Requirements:
1. Accept any word with uppercase and lowercase letters
2. Return an error for any special characters, i.e. spaces, hyphens, @^%# etc.
3. a=1, b=2,... and A=1, B=2,...
4. Print the score of the word
5. (Optional) check that the word is in a dictionary after scoring, and print a warning if it is not.
6. No importing an external letter->number dictionary. You must generate it yourself.
Any language is acceptable. This is similar to the '[digital root battle](https://codegolf.stackexchange.com/questions/1128/my-word-can-beat-up-your-word),' but much simpler.
[Answer]
## Ruby, 43 characters
```
$_=gets.upcase;p~/[^A-Z]/?_: $_.sum-64*~/$/
```
The error message this generates isn't exactly helpful, though.
Both solutions posted here assume the input has no trailing linebreak, so to test them, use `echo -n`.
## Ruby, 76 characters with dictionary check
```
l=STDIN.gets;$_=l.upcase;p~/[^A-Z]/?_: $_.sum-64*~/$/;[*$<].index(l)||$><<?W
```
The warning message consists of the single character "W". The path to the dictionary has to be supplied via ARGV. Example usage:
```
$ echo -n asd | ruby addletters.rb /usr/share/dict/words
24
W
$ echo -n cat | ruby addletters.rb /usr/share/dict/words
24
```
[Answer]
## Golfscript - 23 chars
```
0\{.31&.(.26%=@64///+}/
```
Ensure there are no trailing newlines in input (e.g. use `echo -n`).
[Answer]
# Python (65 64)
```
print sum(['',ord(i)-64]['@'<i<'[']for i in raw_input().upper())
```
This raises an error if the word contains non-letter characters, but not a helpful or informative one. (Edit: tip of the hat to st0le for the indexing trick.)
[Answer]
# Python 2.6 (72 Chars) Without dictionary check
```
print sum(map(" abcdefghijklmnopqrstuvwxyz".index, raw_input().lower()))
```
# Python 2.6 (178 Chars\*) With dictionary check
```
w=raw_input().lower()
print sum(map(" abcdefghijklmnopqrstuvwxyz".index, w))
if w not in open('/usr/share/dict/american-english').read().split():
print('Word not in dictionary')
```
\*Can be lowered to 156 with a less helpful error message. :-)
Thanks to all commenters for helping improve this.
[Answer]
## Python (80)
```
w=raw_input().lower()
s=0
for l in w:s+=range(97,123).index(ord(l))+1
print s
```
## Python v2 (65 but char ` will get accepted)
```
print sum(map(range(96,123).index,map(ord,raw_input().lower())))
```
## v3 (60 chars, @ will be accepted but not counted, thanks jloy)
```
print sum(map(range(64,91).index,map(ord,input().upper())))
```
[Answer]
## Scala: 59 chars, 7 of them payload, no dict:
```
(0/:"Payload".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
67
```
No dictionary so far. Negative result means: Negative!
```
(0/:"Pay!wall?".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
-1915
```
Handles German Umlaute gracefully, by the way:
```
(0/:"Müllrößchen".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
155
```
[Answer]
# Java + Google Guava libraries, 347 characters, with dictionary check
**Unreadable 1 long string version :-)**
```
import java.io.*;import com.google.common.base.*;import com.google.common.io.*;class C{public static void main(String[]a)throws Exception{int s=0;for(int c:a[0].toUpperCase().toCharArray()){assert(c>64&&c<91);s+=c-64;}String d=Files.toString(new File(a[1]),Charsets.UTF_8);if(StringUtils.containsIgnoreCase(d,a[0]))System.out.println("w");System.out.println(s);}}
```
**Human-readable version (sort of :-))**
```
import java.io.*;
import com.google.common.base.*;
import com.google.common.io.*;
class C {
public static void main(String[] a) throws Exception {
int s=0;
for(int c : a[0].toUpperCase().toCharArray()) {
System.out.println(c);
assert(c > 64 && c < 91);
s += c - 64;
}
String d = Files.toString(new File(a[1]), Charsets.UTF_8);
if (d.contains(a[0])) System.out.println("w");
System.out.println(s);
}
}
```
The dictionary path is now passed in via `a[1]`, for assertions to work you have to use the `-ea`flag (+3 more chars). As for the dictionary, the dict `/usr/share/dict/words` (should be available on most \*nix systems) has been used.
[Answer]
## Python 3, 95 chars with dictionary
```
d=input().lower()
print(d in open("d").read()and sum(['',ord(c)-96]['`'<c<'{']for c in d)or'f')
```
The dictionary has to be in a file called d.
### Python 3, 61 without dictionary, but stolen idea
```
print(sum(['',ord(c)-96]['`'<c<'{']for c in input().lower()))
```
[Answer]
# VB.NET, ~~84~~ ~~82~~ ~~73~~ 71
```
Console.Write(Console.ReadLine.Sum(Function(c)Asc(Char.ToUpper(c))-64))
```
**Edit:** With validation is:
```
Dim r=Console.ReadLine
Console.Write(If(r.All(AddressOf Char.IsLetter),r.Sum(Function(c)Asc(Char.ToUpper(c))-64),"Invalid input."))
```
129 characters. In which case:
# C#, 118
```
var r=Console.ReadLine();Console.Write(r.All(char.IsLetter)?r.Sum(c=>char.ToUpper(c)-64).ToString():"Invalid input.");
```
[Answer]
# Improving slightly on John's answer: Python (90)
```
s=0
for i in raw_input().lower():
s+=("abcdefghijklmnopqrstuvwxyz".index(i)+1)
print(s)
```
[Answer]
# **Erlang, 104**
```
a()->
a(string:to_lower(io:get_line([])),0).
a([_|[]],S)->
S;
a([C|R],S) when C<${, C>=$`->
a(R,S+C-$`).
```
[Answer]
## Perl (52) (48)
golfed even more thanks to [Timwi](https://codegolf.stackexchange.com/users/668/timwi)
`perl -lpe "($w=uc)=~/[^A-Z]/&¨$w=~s/./$_-=64-ord$&/ge"`
[Answer]
**Golfscript - 39 chars**
```
n%~{.96>{96}{64}if-..26>\0<|{0/}*}%{+}*
```
The error it throws is not exactly the best, but hey, it aborts execution.
[Answer]
## PYTHON ~~62~~ 68\* Characters
```
print sum(map(chr,range(65,91)).index(c)+1 for c in input().upper())
```
Requires user to input strings using quotes, and is not safe (`input` executes code), but, as I said in a comment to another post, "user-friendly" and "not a security risk" ain't in the spec!
---
\* I forgot about `print`, dammit.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 17 bytes
```
?osṁo%32c¹¨eŻ→¨Λ√
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8b99fvHDnY35qsZGyYd2HlqRenT3o7ZJh1acm/2oY9b///@jlZITS5R0lJwdQ4CkoZExkFRW1FKKBQA "Husk – Try It Online")
Returns 'error' for invalid input, score of word otherwise.
```
? Λ√ # if every element is a letter
os # return the string of
ṁ c¹ # the sum of all their ASCII values
o%32 # MOD 32
¨eŻ→¨ # otherwise, return the compressed string
# "error"
```
---
If it's acceptable to return '0' as the 'error' for invalid input, we can have a ~~11 byte~~ ~~10 byte~~ [9 byte](https://tio.run/##yygtzv6f@6ip8f@h5WoPdzaqGhudW5D7qGPW////o5WSE0uUdJScHUOAZKKhkTGQUlbUUooFAA) solution:
```
§&ṁ%32Πm√
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes
```
lvAyk>})D0åi0ëO
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/p8yxMtuuVtPF4PDSTIPDq/3//09OLAEA "05AB1E – Try It Online") Returns `0` on error.
```
lvAyk>})D0åi0ëO # full program
v # for y in...
# implicit input...
l # lowercased...
k # push 0-based index of...
y # y...
k # in...
A # the lowercase alphabet...
k # or -1 if not found...
> # plus 1
} # end loop
i # if...
0 # 0...
å # is in...
) # stack...
0 # push 0
ë # else...
O # push sum...
D # of stack
# implicit output
```
[Answer]
## Ruby 1.9, 69
```
w=gets.chop.upcase
w[/[^A-Z]/]&&fail
p w.bytes.inject(0){|s,b|s+b-64}
```
[Answer]
## Perl (71)
```
($a)=lc<>;$a=~/[^a-z]/i&¨$x+=ord$_ for split//,$a;die$x-96*length$a;
```
[Answer]
# GolfScript, 50(53)
Gives an error on bad characters, but not a very good one (50 characters):
```
);[{""123,97>+91,65>+?}/].-1?0<{{26%1+}%{+}*}{@}if
```
Gives "E" on error instead (53 characters):
```
);[{""123,97>+91,65>+?}/].-1?0<{{26%1+}%{+}*}{;"E"}if
```
The alphabet-generating snippet `123,97>+` is stolen from Ventero .
[Answer]
# J (55)
```
+/64-~-&32`]@.(<&97)`_:@.(<&65)`_:@.(>&122)"0,I.a.&e."0
```
This satisfies all the conditions except the dictionary one. As an error condition, it returns "infinity" (the underscore symbol in J) for words that contain anything but letters.
[Answer]
# Haskell (127)
(raises an error on weird characters)
(also: the space between `toUpper.` and `\x` is needed otherwise it parses it as`(toUpper)` `.\` `(x)`)
```
import Char
main=getLine>>=putStrLn.show.sum.(map$(-65+).ord.toUpper. \x->if x`elem`['A'..'Z']++['a'..'z']then x else error"")
```
# Haskell (70)
(does not raise an error, but 45% shorter)
```
import Char
main=getLine>>=putStrLn.show.sum.(map$(-65+).ord.toUpper)
```
[Answer]
## C++ (~~111~~ 107)
```
void main(){int a=0;s8*b=new s8[99];for(cin>>b;*b;)if(isalpha(*b))a+=tolower(*b++)-96;else return;cout<<a;}
```
---
The "set up"/etc:
```
#include <iostream>
#include <cstdio>
#include <cctype>
#ifdef _MSC_VER
typedef __int8 s8;
#else
typedef signed char s8;
#endif
```
---
["Undefined" behavior](http://meta.codegolf.stackexchange.com/q/21/761) (It's more 'bad practice' than 'undefined', but oh well):
* `void main()` That says it all.
* I'm using `new` without `delete`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes
```
ŒuØAiⱮoµS
```
[Try it online!](https://tio.run/##y0rNyan8///opNLDMxwzH21cl39oa/D///@VnBNLlAA "Jelly – Try It Online")
Seemingly, it turns out a byte shorter to actually error than to return 0.
```
Œu Uppercase the input,
i find the index (or 0 if not found)
Ɱ of each letter from the input
ØA in "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
o replace any 0 with the corresponding character of the input,
µS then take the sum.
```
Jelly errors if it attempts to add integers and strings together, and although two strings can be added together by `+`, this still errors in the case of a fully symbolic input because `S` is defined specifically as a reduce starting from zero.
[Answer]
## JavaScript 1.8, 80 chars
Surprisingly readable!
```
alert(Array.reduce(prompt().toLowerCase(),function(a,b)a+b.charCodeAt(0)-96,0))
```
[Answer]
## APL (34)
```
+/{⍵∊⍳26:⍵}¨{64-⍨A-32×96<A←⎕UCS⍵}⍞
```
Gives either the score, or a `VALUE ERROR` if there are non-alphabetic characters in the input.
Explanation:
* `⍞`: read a line of input
* `{`...`}`: function applied to every character of input
* `A←⎕UCS⍵`: store the ASCII value of the current character in `A`
* `A-32×96<A`: make character uppercase: from `A` is subtracted 32 if `96<A` (so, if it's uppercase), otherwise 0
* `64-⍨`: subtract 64 from this, giving A=1, B=2 ...
* `¨`: apply this function to every character:
* `⍵∊⍳26`: if the character is between 1 and 26...
* `:⍵`: then return ⍵ (and since there's no else clause there will be a `VALUE ERROR` if it's not between 1 and 26)
* `+/`: sum all the values together (and this value is automatically outputted because it's the final result).
[Answer]
# JavaScript, 60 bytes
```
s=>[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)
```
If the program **must** return an error on invalid inputs, then 80 bytes:
```
s=>/[^a-z]/i.test(s)?_:[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)
```
If an input is invalid, then the console will say that `_` is not defined (there must not already be a variable defined called `_`).
[Answer]
# Python 3, ~~58~~ 55
```
print(sum(ord(x)%32for x in input()if x.isalpha()or z))
```
without dictionary or stolen idea but still unhelpful error ;)
thx @Eᴀsᴛᴇʀʟʏ
Test [here](https://repl.it/CO5q/1).
[Answer]
# C, 98 bytes
```
int a(char *s){int b=0;while(*s){if(!isalpha(*s))throw 1;b+=(toupper(*(s++))-64);}printf("%d",b);}
```
[Answer]
# F# (no validation) 79 57 chars
```
let a w=w|>Seq.fold(fun a b->a+(int b)-65)0|>printfn"%i"
```
[Answer]
# C# with validation: 108 chars (with 12 for error message):
```
var s=Console.ReadLine();Console.Write(s.All(Char.IsLetter)?s.Sum(x=>x&'_'-'@').ToString():"Invalid input");
```
# C# without validation: 60 53 chars:
```
Console.Write(Console.ReadLine().Sum(x=>x&'_'-'@'));
```
] |
[Question]
[
# Definition
Given some string return an integer whose digits are the number ocurrences of a-z (case insensitive, in alphabetical order) in that string. Any character with 0 instances is skipped. Characters with 10 or more instances will define 2 or more digits of the returned integer. For example, aaaaaaaaaaaaaaaaaaaaaaaaaaad (27 a's followed by d) will return 271.
# Input
A single string with one or more letters
# Output
An integer or a string representing an integer
# Test Cases
| Input | Output |
| --- | --- |
| acfzzA | 2112 |
| Hello World! | 1113211 |
| ---!&\*#$ | invalid input, any result is acceptable |
| ---!&\*#$a | 1 |
| aaaaaaaaaaaaaaaaaaaaaaaaaaad | 271 |
| aaaaaaaaaad | 101 |
| cccbba | 123 |
| abbccc | 123 |
This is code-golf, so the shortest answer in bytes wins! Standard loopholes and rules apply. Tie goes to first poster.
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
f=lambda s,c=65:91/c*s and'%.d'%s.upper().count(chr(c))+f(s,c+1)
```
[Try it online!](https://tio.run/##dUzdCoIwGL3fU3zRj5t/8RkVCQbd9QZdxpqKwtrGnEi@vE277sC5OL/m4xqtsmmqC8nfr5JDF4vidMwvuBdhB1yVwTb17NLemMpSlgrdK0dFY6lgLKqpH0TIpqFpZQWYE2iViUH3zkABlg9Pr3vnh52RraMBJFcIGAFjW@Wgpj5mv/7ERT2Ot7mQIWbkXkmp4aGtLFeziYgHH5AkSVa7cL3hi0n4f5TL1xm/ "Python 2 – Try It Online")
[Answer]
# C, ~~137~~, ~~124~~, [90](https://tio.run/##DcrdCsIgGAbg8@6iVeKXfbB@CES6EvFA3qYT1god7CDq0rOdPjzgCNRarNbOPHwaJeg992noJPjYUrESt9hN6H2WROJ7PjmlTHjmxa8XA9atWZZScEK8chqnIJvdvTkUC0fmUyszr8V@s/WrH8LgY6k8/wE), ~~88~~ bytes
Thank you @AnttiP and @tsh for suggestions!
```
s[99];main(c){while(c-10)s[(c=getchar())&~32]++;for(c=64;c-90;)s[++c]&&printf("%d",s[c]);}
```
less golfed version:
```
s[99];
int main(c){
while(c-10)
s[(c=getchar())&~32]++;
for(c=64;c-90;)
s[++c]&&printf("%d",s[c]);
}
```
[Try it online!](https://tio.run/##DcrdCsIgGAbg8@6iVeKXfbB@CES6EvFA3qYT1god7CDq0rOdPjzgCNRarNbOPHwaJeg992noJPjYUrESt9hN6H2WROJ7PjmlTHjmxa8XA9atWZZScEK8chqnIJvdvTkUC0fmUyszr8V@s/WrH8LgY6k8/wE)
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 76 bytes:
```
lambda x:''.join(str(i)for a in range(97,123)if(i:=x.lower().count(chr(a))))
```
[Try it online!](https://tio.run/##dYqxDoIwFEV3v6JEY1@NkCiDSsLg5h@4uDxbKjW1jzxrRH6@MpkweLZ7zu0@saVQ7jtOtr4kj4@rQdFXUhZ3cgGekcEpSyxQuCAYw62Bw2692ZbKWXBV3Ree3g2DKjS9QgTdMqAaSR27cVuQqO0wHKVSs586Nd6TOBN7k01CnufZcjVf4MTif8x4TF8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
⭆α⪫↨№↥θιχω
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaCTqKHjlZ@ZpOCUWp2o455cCJUMLClKLkkH8Qk0dhUwgNjQAEuWamprW//97pObk5OsohOcX5aQocv3XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
α Predefined variable uppercase alphabet
⭆ Map over letters and join
‚Ññ Count of
ι Current letter in
‚Ü• Uppercased
θ Input string
↨ χ Convert to base 10
⪫ ω Join digits together
```
Charcoal's arbitrary base conversion returns an empty list for an input of zero, which is the easiest way to map zero to an empty string.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 44 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 5.5 bytes
```
Ǎ⇩sĠ@ṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyI9IiwiIiwix43ih6lzxKBA4bmFIiwiIiwiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhZCJd)
## Explained
```
Ǎ⇩sĊvtṅ
«ç # keep only letters of the alphabet
‚á© # and convert to lowercase
sĊ # sort that and get the counts of each letter - this returns [[letter, count of letter] for each letter
vt·πÖ # join the counts of letters on ""
```
[Answer]
# [PHP](https://php.net/), 66 bytes
```
<?=join(count_chars(preg_replace('~\W~','',strtolower($argn)),1));
```
[Try it online!](https://tio.run/##BcFBCoAgEADAt0SRGnroXNGtL3QJQkSyCHdZjW4@vW0GAzKP83TBGaWDJ@bdBUtJIvljJ4@3dV6Ksq1FaCF0ypThhteTbCwdUSndKzUwG2Oqtqsb@wHmE2Jis/w "PHP – Try It Online")
A rarely useful builtin function, but it turns out satisfying when it does
[Answer]
# [R](https://www.r-project.org/), ~~78~~ 69 bytes
Or **[R](https://www.r-project.org/)>=4.1, 62 bytes** by replacing the word `function` with `\`.
*Edit: -9 bytes inspired by [@Giuseppe's answer](https://codegolf.stackexchange.com/a/238567/55372).*
```
function(s)cat(table(utf8ToInt(gsub("[^a-z]","",tolower(s)))),sep="")
```
[Try it online!](https://tio.run/##dY49D4IwFEVn@RXlYUwxZagOujC46W7i4EfyKK1p0rSEthr58whsJHrXe3LubXtV9ipaEbSz1OcCAw1YGUljUPuzO9lAnz5WFK4PLLo7MAAWnHFv2Q74EOZlUwLkvaKAQnXdAfJsseF8k4wyuFnIk6E7SmMcubjW1OlIcM63AzWHiqJIV@tsOQLavtDommjbxMAI2g9ppY8mEO0JCiGb6ehvAU4T8w7/p54@73j/BQ "R – Try It Online")
Prints the resulting number like in [@Giuseppe's answer](https://codegolf.stackexchange.com/a/238567/55372).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~54~~ 52 bytes
```
""&@@@Array[ToString/@Counts@LetterNumber@#,26]<>""&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X0lJzcHBwbGoKLEyOiQ/uKQoMy9d38E5vzSvpNjBJ7WkJLXIrzQ3KbXIQVnHyCzWxg6o4X8AUFVJtLKuXZqDc0ZiUWIyUFWxg3KsWl1wcmJeXTWXUmJyWlWVo5IOl5JHak5OvkJ4flFOiiKIr6urq6impaySCOIk4gYpSly1/wE "Wolfram Language (Mathematica) – Try It Online")
```
LetterNumber@# a->1,...,z->26, others->0
Counts@ letter counts
Array[ ,26] for a,...,z
""&@@@ (don't include missing letters)
ToString/@ <>"" concatenate
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-p`, 23 bytes
```
s/\pl/$\.=s!$&!!gi/ge}{
```
[Try it online!](https://tio.run/##K0gtyjH9/79YP6YgR18lRs@2WFFFTVExPVM/PbW2@v9/j9ScnHyF8PyinBTFf/kFJZn5ecX/dQsA "Perl 5 – Try It Online")
---
# [Perl 5](https://www.perl.org/) + `-n`, 23 bytes
```
s/\pl/print s!$&!!gi/ge
```
[Try it online!](https://tio.run/##K0gtyjH9/79YP6YgR7@gKDOvRKFYUUVNUTE9Uz899f9/j9ScnHyF8PyinBTFf/kFJZn5ecX/dfMA "Perl 5 – Try It Online")
[Answer]
# bash, ~~64~~ 44 bytes
#### Original Solution (64 Bytes)
Fairly simple `tr`-based solution - `bash` probably isn't a good way to make a competitive answer, but I had fun doing it!
```
tr [A-Z] [a-z]|tr -dc [a-z]|grep -o .|sort|uniq -c|tr -dc [0-9]
```
Depending on how you want to count characters, it could be more than 64 when including the input to this. A very simple case would be:
```
echo my-input-string|tr [A-Z] [a-z]|tr -dc [a-z]|grep -o .|sort|uniq -c|tr -dc [0-9]
```
which really only adds six characters at best and eight if you have to single-quote the input string.
Explanation:
```
tr [A-Z] [a-z] # Convert all capitals to lowercase in the input stream
tr -dc [a-z] # Delete everything that isn't a lowercase letter
grep -o . # Output every character on its own line
sort | uniq -c # Get a two-column output of all unique characters and their frequencies
tr -dc [0-9] # Delete everything that isn't a digit
```
#### 44 Byte Solution (by @Digital Trauma)
```
grep -io [a-z]|sort -i|uniq -ci|tr -dc [0-9]
```
Among other improvements, this bash solution utilizes some case-insensitive options for utilities such as `sort` and `uniq`.
Here's @Digital Trauma's [Try It Online](https://tio.run/##dcsxC8IwEAXg/X7FtRYH4cBVnBwEBwdxEakdkku0gdDTtCKE/PcYF3HxTd@D97Qa@/zqnbcYrDJrNAKWe8G6OW4P@3ONCS/5FuwdyQm2imKXRglTqek5uAcSuzQFJMPYLmnV5c8djAw2K77GuIGd9V7wJMGbCoiomi9mzRcK1P8Y@DUza132WhfBGw)
[Answer]
# [Factor](https://factorcode.org/) + `spelling`, 56 bytes
```
[ >lower ALPHABET counts values [ present ] map-concat ]
```
The `counts` word postdates Factor build 1525, the one TIO uses, so here's a screenshot of running the above code in build 2101's listener:
[](https://i.stack.imgur.com/UHaVb.png)
## Explanation
```
! "acfzzA"
>lower ! "acfzza"
ALPHABET ! "acfzza" "abcdefghijklmnopqrstuvwxyz"
counts ! { { 97 2 } { 99 1 } { 102 1 } { 122 2 } }
values ! { 2 1 1 2 }
[ present ] map-concat ! "2112"
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), ~~30~~ 28 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{‚àæ‚Ä¢Fmt¬®√ó‚ä∏/+Àù(‚•äùï©-‚åú"aA")=‚åú‚Üï26}
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KIvuKAokZtdMKow5fiirgvK8udKOKlivCdlakt4oycImFBIik94oyc4oaVMjZ9Cgo+4ouI4p+cRsKoIOKfqCJhY2Z6ekEiCiJIZWxsbyBXb3JsZCEiCiItLS0hJiojJCIKIi0tLSEmKiMkYSIKImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWQi4p+p)
`‚Üï26` Range from 0 to 25.
`‚•äùï©-‚åú"aA"` Differences between each of the characters in the input and a or A.
`=‚åú` Equality table between those two vectors.
`+Àù` Sum the columns.
`√ó‚ä∏/` Keep the values with sign 1 (or: remove the zeros)
`∾•Fmt¨` Convert each value to a string and join.
A slightly different approach using *Bins Down* at 29 bytes:
```
{‚àæ‚Ä¢Fmt¬®√ó‚ä∏/¬ª1‚Üì/‚ź27‚Üï‚ä∏‚çã‚•äùï©-‚åú"aA"}
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KIvuKAokZtdMKow5fiirgvwrsx4oaTL+KBvDI34oaV4oq44o2L4qWK8J2VqS3ijJwiYUEifQoKPuKLiOKfnEbCqCDin6giYWNmenpBIgoiSGVsbG8gV29ybGQhIgoiLS0tISYqIyQiCiItLS0hJiojJGEiCiJhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFkIuKfqQ==)
[Answer]
# [R](https://www.r-project.org/), ~~75~~ 72 bytes
```
function(s,x=tabulate((y=utf8ToInt(s))%%32*(y>64),26))cat(x[!!x],sep="")
```
[Try it online!](https://tio.run/##dY6xDoIwGIRneYpSxLQEhoJBF0zcdDdxMA6/pU2aNIXQ1gAvj8Bmord@3@Wum2Q1SW@4U40hNu0rBy@vwQlChso7ebw1V@OIpTSOizwhw6nc0zQvKeXgSP8Iw/6ZWtFWGNNJEgxcjuMZ02iTM5YHi4QDTIMZXYTWDbo3na7DRWCMFbP05WRZFu6SaLtwZd6gVY2Uab1LEZgBdcJ67ZCyCDgX7fxVi599WAe@EPxPvf49sOkD "R – Try It Online")
Prints the result. For invalid input, prints nothing.
-3 bytes thanks to Dominic van Essen.
Test harness taken from [pajonk's answer](https://codegolf.stackexchange.com/a/238546/67312).
[Answer]
# JavaScript (ES6), 63 bytes
Expects an array of characters.
```
a=>a.map(c=>o[i=parseInt(c,36)]=-~o[i],o=[])|o.slice(10).join``
```
[Try it online!](https://tio.run/##dYuxCsIwFEV3v8JWkUSahyK4peCmX@AQAn2kaUmJeaUpDkX89ai7ueM55w74xGgmN84iUGtTJxPKGuGBIzOyJuXkiFO0tzAzU53OXEvx/lJdkVSavwiid8ay44HDQC40TTIUInkLnnrWMQUAJZpuWS6l5nz1x16t97S@0@TbItcIIYrdfrPFXID5tb9P@gA "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
a.map(c => // for each character c in a[]:
o[ // update o[]:
i = // let i be the result of
parseInt(c, 36) // c parsed in base-36
// which gives 0 to 9 for [0-9],
// 10 to 35 for [a-z] and [A-Z]
// and NaN for anything else
// (o[NaN] is not an entry of the array but
// an object property which will be ignored
] = // by join())
-~o[i], // increment it / set it to 1 if it's undefined
o = [] // initialize o[] to an empty array
) | // end of map()
o.slice(10) // ignore the first 10 entries
.join`` // join the remaining ones; undefined values are
// coerced to empty strings
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~56~~ 50 bytes
```
%{-join($_|% T*y|% *g|sort|group|? N* -m \w|% C*)}
```
Input comes from the pipeline.
[Try it online!](https://tio.run/##dY5NDoIwEIX3nmLAYqGxRA@gxrhxYVyZuFBj@BMwSEkLIUI5OxaJRBfOYjLfe5l5k7Ey4CIKkqRFIudxGgpYAHa8W1Wt8RTwVlkMjownvtYxpVSbkDH6np0OnP/l//pv9DzPdftF11WAR4gHokhyFT98IlujpncWpya6SgMO5Kk6CaVgPJchZ0UmV7AnQB9wLpW1IVbTzmzb/Fywd0Ea5hGdW9KodYwG44SuFwsDpUvo1D66F/WmfQE)
Try it in a PS console:
```
$strings = 'acfzzA', 'Hello World!', '---!&*#$', '---!&*#$a', 'aaaaaaaaaaaaaaaaaaaaaaaaaaad', 'aaaaaaaaaad', 'cccbba', 'abbccc'
$result = $strings |
%{-join($_|% T*y|% *g|sort|group|? N* -m \w|% C*)}
1..($strings.Length-1)|%{"'$($strings[$_])' --> '$($result[$_])'"}
```
*-5 by rearranging the first version `%{-join($_|% T*y|% *g|?{$_-match'\w'}|sort|group|% C*t)}`; moving the "match" filter after the "group" allows the use of the "<Property> <Operator> <Value>" syntax of Where-Object instead of using a FilterScript.*
*-1 by removing the unnecessary "t" from "% C\*t"*
## Explanation
**%{...}** "%" is an alias for the cmdlet "ForEach-Object", which accepts input from the pipeline and processes each incoming object inside the ScriptBlock {...}
**-join(...)** Unary operator which will join the all the character counts returned inside the expression
**% T\*y** takes the input string and calls its method "ToCharArray()", turning the string into an array of single characters.
**% \*g** takes the array of characters and turns them back to single-character strings by invoking ToString() (the only method matching "\*g"), because Group-Object is case sensitive for characters, but not for strings.
**sort** is an alias for Sort-Object, which will sort the characters.
**group** is an alias for Group-Object, which will group the characters, and return objects with a Count property for each character; returns GroupInfo objects.
**? N\* -m \w** "?" is an alias for "Where-Object", the rest expands to "-Property 'Name' -match '\w'" - this lets only objects pass where the Name property (which contains the grouped character) consists only of word (\w) characters. PS allows for partial named parameters, so -m will be identified as -match.
**% C\*** gets the property "Count" (the only one starting with C) of the GroupInfo objects.
All the counts will now be collected and joined to a single string; output is implicit.
## Ungolfed
```
ForEach-Object -Process {
-join ( # Will join the counts of all characters produced inside the brackets into a single string
$_ | # Input string
ForEach-Object -MemberName ToCharArray | # input string to single chars
ForEach-Object -MemberName ToString | # input chars to single-char strings
Sort-Object |
Group-Object | # group same characters
Where-Object -Property 'Name' -match '\w' | # let only word characters pass ("Name" contains the string/character used to group)
ForEach-Object -MemberName Count # get only the count of the grouped objects
)
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~11~~ ~~9~~ 8 bytes
*Edit: -2 bytes but +1 (bug fix) for a net -1 byte, all thanks to Razetime*
```
ṁosLk_f√
```
[Try it online!](https://tio.run/##yygtzv7//@HOxvxin@z4tEcds/7//@@RmpOTr6MQnl@Uk6IIAA "Husk – Try It Online")
Digits are in alphabetical order of each letter.
```
f‚àö # filter for only letters,
k_ # and group letters by lowercase value;
ṁo # now map to each group & combine the results:
L # get the length
s # and convert to a string
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
lDáêS¢J
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/x@XwwsOrgg8t8vr/3yM1JydfITy/KCdFEQA "05AB1E – Try It Online")
-2 bytes and fix thanks to @KevinCruijssen and @ovs
[Answer]
# Python3, ~~72~~ ~~70~~ ~~67~~ 87 bytes
```
lambda x:''.join(map(str,map((x:=x.lower()).count,sorted(filter(str.isalpha,set(x))))))
```
[Try it online](https://tio.run/##dYqxDsIgFEV3v6JGIw/TsriYJh3c/AMXl2eBFPMKBDBifx6rg0kHz3KTc49/pcHZw9GHortrIRxvEqvcMibuzlgY0UNMof4s5LbLgtxTBeBc9O5hUx1dSEqCNpRmPafCRCQ/YB1Vgsy/FB@MTaCBYa@n6cQ4X/3UWRG56uICyfXiaJpmvdtvtriw@B85h@UN)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ŒufØAṢŒɠ
```
[Try it online!](https://tio.run/##y0rNyan8///opNK0wzMcH@5cdHTSyQX/D7drRv7/r56YnFZV5aiuo@4BVJWvEJ5flJOiCOTq6uoqqmkpqyQC2Ym4QYo6AA "Jelly – Try It Online")
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ŒuċⱮØA¹Ƈ
```
[Try it online!](https://tio.run/##y0rNyan8///opNIj3Y82rjs8w/HQzmPt/w@3a0b@/6@emJxWVeWorqPuAVSWrxCeX5STogjk6urqKqppKaskAtmJuEGKOgA "Jelly – Try It Online")
Both as full programs, taking advantage of Jelly's automatic smash-printing behavior.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 64 bytes
```
s=>s.sort().join(o='').replace(/([a-z])\1*/gi,c=>o+=c.length)&&o
```
[Try it online!](https://tio.run/##dYtBDoIwEADvvkLQQIt2iQ8oiTd/4AE5bEpByKZLWuKhn6/xbuc6Myt@MBi/bLtyPNo06RR0FyCw34WElRcnWNe1BG83QmNFK3pUcZCvW9POy9Xoji/aAFk3729ZVZwMu8BkgXgWk@gBoEQzxXgvBykPf@zDEvHxyZ7GItcopYqqOZ0xF2Ce8fekLw "JavaScript (Node.js) – Try It Online")
Based off Arnauld's answer. Takes input as a character array.
Sort, join, match runs of one character and append that to `o`, and yield that at the end.
[Answer]
# APL+WIN, ~~48~~ 44 bytes
Prompts for string
```
10⊥((+/(48+m)∘.=n)++/(m←17+⍳26)∘.=n←⎕av⍳⎕)~0
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv6HBo66lGhra@homFtq5mo86ZujZ5mlqA/m5IEXm2o96NxuZQcWBIkDtiWVAMSCtWWfwH2gG1/80LvXE5LSqKkd1LiDTIzUnJ18hPL8oJwXM19XVVVTTUlZB4SSCeYm4QYo6AA "APL (Dyalog Classic) – Try It Online")
[Answer]
# Haskell, ~~120~~ ~~84~~ 73 bytes
```
f x=do(v,u)<-zip['a'..'z']['A'..];1:r<-[[1|k<-x,v==k||u==k]];show$sum$1:r
```
[Try it Online!](https://tio.run/##DcrNCoUgEEDhV4kQpiCDtqWL3iIQFxMVif2R2R3Cd/e6OXyLs6Kz87bFuGQkp7N4K18K/plLAUJdwwdaQZ@ku6a9BVeqCVZwql4pbQg@VevOreePOb@z9MQdzSGv2xwPW3LEkUbsiYYhj38)
-36 bytes thanks to Unrelated String
-11 bytes thanks to Wheat Wizard
[Answer]
# [Scala](http://www.scala-lang.org/), 64 bytes
```
s=>('A'to'Z').map(c=>s.count(_.toUpper==c)).filter(_>0).mkString
```
[Try it online!](https://tio.run/##dVHdSsMwGL3fU3yrxSaylnW7EMQUhgiCwmBDBG9GmqZSzZrYZDI29uw1bdoqMnMVzm97ohkVtJbpO2cGnrgxvLqTu9Jo4HvDy0zDQik4jkYAX1QAa7kbWJuqKN@AJMMNjrUmCQoWgZHBa4CjLVWIkURHrQdtIiOfleIVIQzjKC@ErUKbZGqVHy6kBjj1RXxPt0pwbYPX/BNZFMCjLD8cFh6ECXizOJ55E4c/cCEkvMhKZGPHxnE8t4peEIbh@PLqwnfkX5R2nh6n/5@sK78@I@64eDpwjLE07dNn88GSppb5gS2Km//OZWWXbiSoKNXOTOwKyr4LzzDchsMkrYIys7Mzke5FnAFb6tRFKLuoEaVbDqDIAfUe8itXe2j5iMFv/c0X@U7lAReaN/T9arVcnVHAmIDfB3ltTds/OtXf "Scala – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) 6+, ~~47~~ 46 bytes
*-1 byte thanks @Julian*
```
-join($args|?{$_-in'a'..'z'}|group{"$_"}|% c*)
```
[Try it online!](https://tio.run/##dZDPT4MwHMXv/Su62a2w0MWygycjxoueNHLYwRgCpUMWpNhCNPz427EdyKaL7/h57/te8i3EJ5fqjWdZj3bwGjY92Ys0t1AoE9XeNCggaY5DvF7jGndtIkVVNHMUzLt2AdnK7jsAPAsAx8Ih29X1LXawS6mLbYPuda@AWyGzeKYNSulGm4NHCJktVxdI89@AnpHQ3A4o/F@xmb46yxlML0fMGIuiQ527GYNRpOFEgA1buIANgFoozYuq9EuZ5okDEf8qOCt5rN@EgiEguaqyUoOl/p53Ej/YL0/@XaVK8f4Y7fXlqzfUGvkVY1wpUzV2EP5xnJhyzz8DY2wyHsyW4X9HO9D13w "PowerShell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 48 bytes
```
->s{((?A..?Z).map{|c|s.upcase.count(c)}-[0])*''}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664WkPD3lFPzz5KUy83saC6JrmmWK@0IDmxOFUvOb80r0QjWbNWN9ogVlNLXb32f4FCWrRSYnJaVZWjUqyygq6dgpGhoREXWNgjNScnXyE8vygnRREqaWhoaAxUAJZX19XVVVTTUlZJVIdKQrQl4gYpMDvMDf8DAA "Ruby – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 24 bytes
```
T`Llp`LL_
O`.
(.)\1*
$.&
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyTBJ6cgwccnnss/QY9LQ08zxlCLS0VP7f//xOS0qipHLo/UnJx8hfD8opwURS5dXV1FNS1lFTgjkSsRN0gBAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`Llp`LL_
```
Uppercase all letters and delete all other printable ASCII.
```
O`.
```
Sort the letters together.
```
(.)\1*
$.&
```
Get the lengths of all the runs.
[Answer]
# T-SQL, 168 bytes
```
SELECT STRING_AGG(c,'')WITHIN GROUP(ORDER BY
x)FROM(SELECT x,sum(1)c
FROM(SELECT substring(@,number,1)x FROM spt_values WHERE'P'=type)x
GROUP BY x)x WHERE x like'[a-z]'
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1531147/return-all-letter-counts-as-an-integer)**
This will work for input fewer than 2048 characters. The output is ordered according to the position of the letter in the alphabet
[Answer]
# [Lua](https://www.lua.org/), 94 91 84 bytes
```
for i=65,90 do _,c=(...):upper():gsub(string.char(i),"")io.write(c~=0 and c or"")end
```
[Try it online!](https://tio.run/##DcnBCoMwDADQXwmeUijBi4JCD/uS0aXVBUYr0TLw4K9H3/X9WjRbqoKEcfBTD6nC23NAInJz27as6OZ1bx/cD5WyEn@jojjfdU4q/VWOjHyFHmJJwFD1iVySmUVezvN1Aw "Lua – Try It Online")
[Answer]
# [Julia 1.7](https://julialang.org), 47 bytes
```
!x=join((c=count.('a':'z',lowercase(x)))[c.>0])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dY49TsQwEIVr-xSTBREbJcs6W4CQshIV3IACKCa2I3k1sqPEgSVXoUnBHmpvg1EQouFV8_e9eR_H_UgO5_k4xra8OV1lh3ofnBdC1zqMPq5FjvltPuUFhTfbaxysOEgpn_R6t3mRP9h9G3pw4Dz0Fg05bwchOSRhARZqGDpyUbgCVs9xtWy63vlIXiDUO8hQcuvNYjefPlG303THKqUq_mCJAjyGnkzGlFLbNOVlWWYXl2fnzPlXJGfS726MBaB_TxmGkSK4AVBr20VsyP4CyBTH_2VYdf33wDC1UVxr3TSJrLYcmyZ13-US9gs)
# [Julia 1.0](http://julialang.org/), 49 bytes
```
r='a':'z'
!x=join(([[email protected]](/cdn-cgi/l/email-protection)(in((r-32)r),x))[c.>0])
```
[Try it online!](https://tio.run/##dYvNisIwFIXXyVPcOmKToRVvuhCEiO7mDWahLm6TCJGYSlqh9OVrRRA3ntV3/i734An7cUw6p3yTDznPen1pfBTC6N2yvV/Fk1NZKZlk0Ut5MMvt6iTHc5PAg4@QHNngo2uF5DCJCnCgob0F3wlfwOzYzV7NLfnYhSgI9BYyktxFO5I5D8OeKUTF/1wIDfw3KdiMIWI1pbwsy2zx@zNnbyKGnL7LMrX@HFiGK@TGmLqenqriVNeTe@ID "Julia 1.0 – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 23 bytes
```
{,/$#'=x@<x:("a{"')__x}
```
[Try it online!](https://ngn.codeberg.page/k#eJx9kVFLwzAUhZ/Nr8iy4VpZ1rVFlEZB8UWffBF8GGNL03Qri8lMUuk29Leb0jIcdbsEAt89uZeckyf7UTDoD++rh7sq8RDdo6E/n1ffANhkP5huf3SSQwgrslBr4i1yWghSkS3R/qzWTBFl+W73iAiKwjBCsxo9cyEUfFdaZD3XCMMwds2mhzHuXV71BxARb9Jf+D3PP+IUkRFqtfR0ZfXCm46uxuGkxYyxNKU1ieJWmKYOHggIwMrajUmCgKmML5XIx8ZStuYVW1G55GOmPoLPkhtbKGmCKL69juNAc1tqiakQWHBrucZMldIaTN2RuJCWL7kG4M29g0/UcANe5Ka08AKeqNfSuj5orDwtqx0Gf83tSluvwcHmjqKQX1QUmbvdyhGkcgs1N6WwsDCQMsY3lqaCHybQf5aAc8nACxcMOAKdAZMQNOmc/qyLCDR5ndfU9QuXl7Wz)
* `_x` lowercase the input
* `("a{"')_` drop all non-letter characters
* `x@<x:` sort the characters
* `#'=` build a dictionary mapping the distinct characters to the number of times they appear
* `,/$` convert the counts to strings, then join them (and implicitly return)
] |
[Question]
[
*This question is probably harder than all of those "generate a sequence of numbers" tasks, because this requires TWO sequences working in unison.*
*Really looking forward to the answers!*
In his book "*Gödel, Escher, Bach: An Eternal Golden Braid*", Douglas Hofstadter has a quite few sequences of numbers inside, all of them rely on the previous term in some way. For information on all of the sequences, see [this Wikipedia page](https://en.wikipedia.org/wiki/Hofstadter_sequence).
One pair of sequences that's really interesting is the Female and Male sequences, which are defined like so:
[](https://i.stack.imgur.com/Q5bxO.png)
for `n > 0`.
Here's the [Female sequence](http://oeis.org/A005378) and the [Male sequence](http://oeis.org/A005379).
Your task is, when given an integer `n` as input, return a list of the Female sequence and the Male sequence, with the amount of terms equal to `n`, in two lines of output, with the Female sequence on the first line and the Male sequence on the second.
Sample inputs and outputs:
Input: `5`
Output: `[1, 1, 2, 2, 3]` `[0, 0, 1, 2, 2]`
Input: `10`
Output: `[1, 1, 2, 2, 3, 3, 4, 5, 5, 6]` `[0, 0, 1, 2, 2, 3, 4, 4, 5, 6]`
NOTE: The separation between lists signifies a line break.
This is code-golf, so shortest code in bytes wins. Also, put an explanation in as well for your code.
## Leaderboard
```
var QUESTION_ID=80608,OVERRIDE_USER=49561;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Julia, ~~52~~ 48 bytes
```
x->[n÷φ|(5n^2|4∈(2:3n).^2)for| =(+,-),n=1:x]
```
[Try it online!](http://julia.tryitonline.net/#code=MzUgfD4geC0-W27Dt8-GfCg1bl4yfDTiiIgoMjozbikuXjIpZm9yfCA9KCssLSksbj0xOnhdIHw-IGludCB8PiBwcmludA&input=)
### Background
In [On Hofstadter's married functions](http://iecl.univ-lorraine.fr/~Thomas.Stoll/hofstadter.ps), the author shows that

where **φ** denotes the [golden ratio](https://en.wikipedia.org/wiki/Golden_ratio),

and **Fn** denotes the **n**th [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number).
Furthermore, in [Advanced Problems and Solutions, H-187: Fibonacci is a square](http://www.fq.math.ca/Scanned/10-4/advanced10-4.pdf), the proposer shows that

where **Ln** denotes the **n**th [Lucas number](https://en.wikipedia.org/wiki/Lucas_number), and that – conversely – if

then **n** is a Fibonacci number and **m** is a Lucas number.
From this, we deduce that

whenever **n > 0**.
### How it works
Given input **x**, we construct a **2** by **x** matrix, where **|** is addition in the first column and subtraction in the second, and **n** iterates over the integers between **1** and **x** in the rows.
The first term of both **F(n - 1)** and **M(n - 1)** is simply `n÷φ`.
We compute **δ(n)** and **ε(n)** by calculating **5n² | 4** and testing if the result belongs to the array of squares of the integers between **2** and **3n**. This tests both for squareness and, since **1** is not in the range, for **n > 1** if **|** is subtraction.
Finally we add or subtract the Boolean resulting from `5n^2|4∈(2:3n).^2` to or from the previously computed integer.
[Answer]
# Python 2, ~~79~~ 70 bytes
```
a=0,;b=1,
exec"a,b=b,a+(len(a)-b[a[-1]],);"*~-input()*2
print b,'\n',a
```
Iterative rather than recursive, because why not. The first line has a trailing space - if that's not okay it can be fixed for an extra byte. -9 bytes thanks to @Dennis.
Here are some combined lambdas which didn't really help:
```
f=lambda n,k:n and n-f(f(n-1,k),k^1)or k
f=lambda n,k:[k][n:]or f(n-1,k)+[n-f(f(n-1,k)[-1],k^1)[-1]]
```
Both take `n` and a parameter `k` either 0 or 1, specifying male/female. The first lambda returns the nth element, and the second lambda returns the first n elements (with exponential runtime).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 23 bytes
```
1Oiq:"@XJth"yy0)Q)_J+hw
```
[**Try it online!**](http://matl.tryitonline.net/#code=MU9pcToiQFhKdGgieXkwKVEpX0oraHc&input=MTA)
### Explanation
This works iteratively. Each sequence is kept in an array. For each index *n* the new term of each sequence is computed and attached to the corresponding array. A `for` loop with *N*−1 terms is used, where *N* is the input number.
The update for sequence M needs to be done first. This is because sequence F is always greater than or equal to sequence M for the same index, so if we tried to update F first we would need a term of M not computed yet.
The two update equations are the same interchanging F and M. Thus the code for the updating is reused by applying a `for` loop with two iterations and swapping the sequences in the stack.
```
1 % Push 1: seed for F sequence
O % Push 0: seed for M sequence
iq: % Input N. Generate range [1 2 ... N-1]
" % For each (i.e. iterate N-1 times)
@ % Push current index, n (starting at 1 and ending at N-1)
XJ % Copy to clipboard J
th % Duplicate and concatenate. This generates a length-2 array
" % For each (i.e. iterate twice)
yy % Duplicate top two elements, i.e. F and M sequences
0) % In the *first* iteration: get last entry of M, i.e M(n-1)
Q) % Add 1 and index into F. This is F(M(n-1))
_J+ % Negate and add n. This is n-F(M(n-1)), that is, M(n)
h % Concatenate to update M
w % Swap top two elements, to bring F to top.
% In the *second* iteration the procedure is repeated to update F,
% and then the top two elements are swapped to bring M to top again,
% ready for the next iteration of the outer loop
% End for implicitly
% End for implicitly
% Display implicitly from bottom to top: first line is F, second is M
```
[Answer]
# J, 47 bytes
```
f=:1:`(-m@f@<:)@.*
m=:0:`(-f@m@<:)@.*
(f,:m)@i.
```
Uses the recursive definition. The first two lines define the verbs `f` and `m` which represent the female and male functions, respectively. The last line is a verb that takes a single argument `n` and outputs the first `n` terms of the female and male sequences.
## Usage
```
(f,:m)@i. 5
1 1 2 2 3
0 0 1 2 2
(f,:m)@i. 10
1 1 2 2 3 3 4 5 5 6
0 0 1 2 2 3 4 4 5 6
```
[Answer]
## JavaScript (ES6), 75 bytes
```
g=n=>--n?([f,m]=g(n),m=[...m,n-f[m[n-1]]],[[...f,n-m[f[n-1]]],m]):[[1],[[0]]
```
I could save 2 bytes if I was allowed to return the Male sequence first:
```
g=n=>--n?([f,m]=g(n),[m=[...m,n-f[m[n-1]]],[...f,n-m[f[n-1]]]]):[[1],[[0]]
```
[Answer]
## Haskell, 57 bytes
```
l#s=scanl(\a b->b-l!!a)s[1..]
v=w#1
w=v#0
(<$>[v,w]).take
```
Usage example: `(<$>[v,w]).take $ 5` -> `[[1,1,2,2,3],[0,0,1,2,2]]`
The helper function `#` builds an infinite list with starting value `s` and a list `l` for looking up all further elements (at index of the previous value). `v = w#1` is the female and `w = v#0` the male sequence. In the main function we take the first `n` elements of both `v` and `w`.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~22~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṙṪḢạL}ṭ
çƓḤ¤Ð¡1ṫ-Ṗ€G
```
[Try it online!](http://jelly.tryitonline.net/#code=4bmZ4bmq4bii4bqhTH3hua0Kw6fGk-G4pMKkw5DCoTHhuast4bmW4oKsRw&input=MjA)
### How it works
```
çƓḤ¤Ð¡1ṫ-Ṗ€G Main link. No user arguments. Left argument defaults to 0.
¤ Combine the two links to the left into a niladic chain.
Ɠ Read an integer from STDIN.
Ḥ Unhalve/double it.
ç С1 Call the helper link that many times. Return all results.
In the first call, the left and right argument are 0 and 1 resp.
After each iteration, the left argument is set to the return value
and the right argument to the prior value of the left one.
ṫ- Tail -1; keep the last two items of the list of results.
Ṗ€ Discard the last item of each list.
G Grid; format the pair of lists.
ṙṪḢạL}ṭ Helper link. Arguments: x, y (lists)
ṙ Rotate x k units to the left, for each k in y.
Ṫ Tail; extract the last rotation.
Ḣ Head; extract the last element.
This essentially computes x[y[-1]] (Python notation), avoiding
Jelly's 1-based indexing.
L} Yield the length of y.
ạ Take the absolute difference of the results to both sides.
ṭ Tack; append the difference to y and return the result.
```
[Answer]
## Python 2, 107 bytes
```
F=lambda n:n and n-M(F(n-1))or 1
M=lambda n:n and n-F(M(n-1))
n=range(input())
print map(F,n),'\n',map(M,n)
```
[Try it online](http://ideone.com/fork/H57Qef)
Larger input values cause a RuntimeError (too much recursion). If this is a problem, I can write a version where the error doesn't happen.
[Answer]
## Clojure, ~~132~~ 131 bytes
```
(fn [n](loop[N 1 M[0]F[1]](if(< N n)(let[M(conj M(- N(F(peek M))))F(conj F(- N(M(peek F))))](recur(inc N)M F))(do(prn F)(prn M)))))
```
Simply builds the sequences iteratively up from zero to n.
Ungolfed version
```
(fn [n]
(loop [N 1 M [0] F [1]]
(if (< N n)
(let [M (conj M (- N (F (peek M))))
F (conj F (- N (M (peek F))))]
(recur (inc N) M F))
(do
(prn F)
(prn M)))))
```
[Answer]
# Julia, 54 bytes
```
f(n,x=1,y=0)=n>1?f(n-.5,[y;-x[y[k=end]+1]+k],x):[x y]'
```
[Try it online!](http://julia.tryitonline.net/#code=ZihuLHg9MSx5PTApPW4-MT9mKG4tLjUsW3k7LXhbeVtrPWVuZF0rMV0ra10seCk6W3ggeV0nCgoyMHw-Znw-cHJpbnQ&input=)
[Answer]
# Pyth, 24 bytes
It is probably impossible to use `reduce` to reduce the byte-count.
Straightforward implementation.
```
L&b-b'ytbL?b-by'tb1'MQyM
```
[Try it online!](http://pyth.herokuapp.com/?code=L%26b-b%27ytbL%3Fb-by%27tb1%27MQyM&input=10&debug=0)
## How it works
```
L&b-b'ytb defines a function y, which is actually the male sequence.
L def male(b):
&b if not b: return b
-b else: return b-
'ytb female(male(b-1))
L?b-by'tb1 defines a function ', which is actually the female sequence.
L def female(b):
?b if b:
-by'tb return b-male(female(b-1))
1 else: return 1
'MQ print(female(i) for i from 0 to input)
yMQ print(male(i) for i from 0 to input)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 65 bytes
```
:{:1-:0re.}fL:2aw,@Nw,L:3aw
0,1.|:1-:2&:3&:?--.
0.|:1-:3&:2&:?--.
```
My attempt at combining both predicates for male and female into one actually made the code longer.
You could use the following one liner which has the same number of bytes:
```
:{:1-:0re.}fL:{0,1.|:1-:2&:3&:?--.}aw,@Nw,L:{0.|:1-:3&:2&:?--.}aw
```
**Note**: This works with the Prolog transpiler, not the old Java one.
### Explanation
Main predicate:
```
:{:1-:0re.}fL Build a list L of integers from 0 to Input - 1
:2aw Apply predicate 2 to each element of L, write the resulting list
,@Nw Write a line break
,L:3aw Apply predicate 3 to each element of L, write the resulting list
```
Predicate 2 (female):
```
0,1. If Input = 0, unify Output with 1
| Else
:1- Subtract 1 from Input
:2& Call predicate 2 with Input - 1 as argument
:3& Call predicate 3 with the Output of the previous predicate 2
:?- Subtract Input from the Output of the previous predicate 3
-. Unify the Output with the opposite of the subtraction
```
Predicate 3 (male):
```
0. If Input = 0, unify Output with 0
| Else
:1- Subtract 1 from Input
:3& Call predicate 3 with Input - 1 as argument
:2& Call predicate 2 with the Output of the previous predicate 3
:?- Subtract Input from the Output of the previous predicate 3
-. Unify the Output with the opposite of the subtraction
```
[Answer]
# Pyth, 23 bytes
```
jCuaG-LHtPs@LGeGr1Q],1Z
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=jCuaG-LHtPs%40LGeGr1Q]%2C1Z&input=20&debug=0)
### Explanation:
```
jCuaG-LHtPs@LGeGr1Q],1Z
u ],1Z start with G = [[1, 0]]
(this will be the list of F-M pairs)
u r1Q for each H in [1, 2, ..., Q-1]:
eG take the last pair of G [F(H-1), M(H-1)]
@LG lookup the pairs of these values:
[[F(F(H-1)), M(F(H-1))], [F(M(H-1)), M(M(H-1))]]
s join them:
[F(F(H-1)), M(F(H-1)), F(M(H-1)), M(M(H-1))]
tP get rid of the first and last element:
[M(F(H-1)), F(M(H-1))]
-LH subtract these values from H
[H - M(F(H-1)), H - F(M(H-1))]
aG and append this new pair to G
jC at the end: zip G and print each list on a line
```
Alternative solution that uses a function instead of reduce (also 23 bytes):
```
L?>b1-LbtPsyMytb,1ZjCyM
```
[Answer]
# Ruby, ~~104~~ ~~92~~ ~~97~~ 82 bytes
```
f=->n,i{n>0?n-f[f[n-1,i],-i]:i>0?1:0}
->n{[1,-1].map{|k|p (0...n).map{|i|f[i,k]}}}
```
**Edit:** `f` and `m` are now one function thanks to [HopefullyHelpful](https://codegolf.stackexchange.com/users/41316/hopefullyhelpful). I changed the second function to print `f` then `m`. The whitespace after `p` is significant, as otherwise the function prints `(0...n)` instead of the result of `map`.
The third function prints first an array of the first n terms of `f`, followed by an array of the first n terms of `m`
These functions are called like this:
```
> f=->n,i{n>0?n-f[f[n-1,i],-i]:i>0?1:0}
> s=->n{[1,-1].map{|k|p (0...n).map{|i|f[i,k]}}}
> s[10]
[1, 1, 2, 2, 3, 3, 4, 5, 5, 6]
[0, 0, 1, 2, 2, 3, 4, 4, 5, 6]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~45~~ 25 bytes
Anonymous tacit function. Requires `⎕IO←0`, which is standard on many APL systems.
```
1 0∘.{×⍵:⍵-(~⍺)∇⍺∇⍵-1⋄⍺}⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/w0VDB51zNCrPjz9Ue9WKyDW1ah71LtL81FHO5ACk1t1DR91twB5tY96N/9PA2p71NsHMaGr@dB640dtE4G84CBnIBni4Rn8P03BlCtNwdAAAA "APL (Dyalog Unicode) – Try It Online")
This works by combining *F* and *M* into a single dyadic function with a Boolean left argument which selects the function to apply. We use 1 for *F* and 0 for *M* so that we can use this selector as return value for *F* (0) and *M* (0). We then observe that both functions need to call themselves first (on the argument minus one) and then the other function on the result of that, so first we recurse with the given selector and then with the logically negated selector.
`⍳` **ɩ**ndices; zero through argument minus one
`1 0∘.{`…`}` outer (Cartesian) "product" (but with the below function instead of multiplication) using `[1,0]` as left arguments (`⍺`) and the indices as right arguments (`⍵`):
`×⍵` if the right argument is strictly positive (lit. the sign of the right argument):
`⍵-1` subtract one from the right argument
`⍺∇` call self with that as right argument and the left argument as left argument
`(~⍺)∇` call self with that as right arg and the logical negation of the left arg as left arg
`⍵-` subtract that from the right argument and return the result
`⋄` else:
`⍺` return the left argument
[Answer]
# ES6, ~~89~~ ~~85~~ 83 bytes
2 bytes saved thanks to [@Bálint](https://codegolf.stackexchange.com/users/49709/b%c3%a1lint)
```
x=>{F=[n=1],M=[0];while(n<x){M.push(n-F[M[n-1]]);F.push(n-M[F[n++-1]])}return[F,M]}
```
Naïve implementation.
Explanation:
```
x => {
F = [n = 1], //female and term number
M = [0]; //male
while (n < x) {
M.push(n - F[M[n - 1]]); //naïve
F.push(n - M[F[n++ - 1]]); //post-decrement means n++ acts as n in the calculation
}
return [F, M];
}
```
[Answer]
## Mathematica, ~~69~~ 62 bytes
*Thanks to Sp3000 for suggesting a functional form which saved 14 bytes.*
```
k_~f~0=1-k
k_~f~n_:=n-f[1-k,f[k,n-1]]
Print/@Array[f,{2,#},0]&
```
This defines a named helper function `f` and then evaluates to an unnamed function which solves the actual task of printing both sequences.
[Answer]
## Perl 5.10, ~~85~~ 80 bytes
Meh, dunno if I have more ideas to golf this down...
```
@a=1;@b=0;for(1..<>-1){push@a,$_-$b[$a[$_-1]];push@b,$_-$a[$b[$_-1]]}say"@a\n@b"
```
[Try it online !](https://ideone.com/pUSp9e)
I had to add `use 5.10.0` on Ideone in order for it to accept the `say` function, but it doesn't count towards the byte count.
It's a naive implementation of the algorithm, `@a` being the "female" list and `@b` the "male" list.
Crossed-out 85 is still 85 ?
[Answer]
# Java, 169 bytes total
```
int f(int n,int i){return n>0?n-f(f(n-1,i),-i):i>0?1:0;}void p(int n,int i){if(n>0)p(n-1,i);System.out.print(i==0?"\n":f(n,i)+" ");}void p(int n){p(n,1);p(0,0);p(n,-1);}
```
# F(), M() 56 bytes
```
int f(int n,int i){
return n>0?n-f(f(n-1,i),-i):i>0?1:0;
}
```
# recursive-for-loop and printing 77 Bytes
```
void p(int n,int i) {
if(n>0) {
p(n-1,i);
}
System.out.print(i==0?"\n":f(n,i)+" ");
}
```
# outputting the lists in two different lines 37 Bytes
```
void p(int n) {
p(n,1);
p(0,0);
p(n,-1);
}
```
input : p(`10`)
output :
```
1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9
```
[Answer]
# C, 166 Bytes
```
#define P printf
#define L for(i=0;i<a;i++)
f(x);m(x);i;c(a){L P("%d ",f(i));P("\n");L P("%d ",m(i));}f(x){return x==0?1:x-m(f(x-1));}m(x){return x==0?0:x-f(m(x-1));}
```
Usage:
```
main()
{
c(10);
}
```
Output:
```
1 1 2 2 3 3 4 5 5 6
0 0 1 2 2 3 4 4 5 6
```
Ungolfed (331 Bytes)
```
#include <stdio.h>
int female(int x);
int male(int x);
int i;
int count(a){
for(i=0;i<a;i++){
printf("%d ",female(i));
}
printf("\n");
for(i=0;i<a;i++){
printf("%d ",male(i));
}
}
int female (int x){
return x==0?1:x-male(female(x-1));
}
int male(x){
return x==0?0:x-female(male(x-1));
}
int main()
{
count(10);
}
```
[Answer]
# [8th](http://8th-dev.com/), 195 bytes
**Code**
```
defer: M
: F dup not if 1 nip else dup n:1- recurse M n:- then ;
( dup not if 0 nip else dup n:1- recurse F n:- then ) is M
: FM n:1- dup ( F . space ) 0 rot loop cr ( M . space ) 0 rot loop cr ;
```
**Usage**
```
ok> 5 FM
1 1 2 2 3
0 0 1 2 2
ok> 10 FM
1 1 2 2 3 3 4 5 5 6
0 0 1 2 2 3 4 4 5 6
```
**Explanation**
This code uses **recursion** and **deferred** **word**
`defer: M` - The word `M` is declared to be defined later. This is a ***deferred word***
`: F dup not if 1 nip else dup n:1- recurse M n:- then ;` - Define `F` ***recursively*** to generate female numbers according definition. Please note that `M` has not yet been defined
`( dup not if 0 nip else dup n:1- recurse F n:- then ) is M` - Define `M` ***recursively*** to generate male numbers according definition
`: FM n:1- dup ( F . space ) 0 rot loop cr ( M . space ) 0 rot loop cr ;` - Word used to print sequences of female and male numbers
] |
[Question]
[
*Title is an homage to [this classic challenge](https://codegolf.stackexchange.com/questions/113238/is-it-true-ask-jelly)*
In [Pip](https://github.com/dloscutoff/pip), the Scalar data type encompasses strings and numbers. A Scalar value is truthy in most cases. It is falsey only if:
* It is the empty string `""`; or
* It is some representation of the number zero.
A Scalar is considered to be a representation of zero if:
* It consists of one or more `0`s; or
* It consists of one or more `0`s plus a single `.` anywhere among them.
The decimal point can be in the middle, at the beginning, or at the end.
## Challenge
Given a string containing printable ASCII characters, determine whether it is a truthy Scalar or a falsey Scalar according to Pip.
The default allowable output formats for [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") apply: you may either output a truthy/falsey value in your language, with swapping allowed, or choose two consistent values, one representing truthy and the other representing falsey.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the goal is to minimize the size of your source code, measured in bytes.
## Examples
Falsey:
```
""
"0"
"000"
".0"
".00"
"0."
"00."
"0.00"
"0000000000000.00000000000000"
```
Truthy:
```
"abc"
"x"
"0001"
"0x00"
"0e0"
" 0"
"0 "
"+0"
"-0"
"."
"0.0.0"
"0.00000000000000000000000001"
```
## Reference implementation
This Python 3 code is adapted from the actual Pip interpreter:
```
import re
zeroRgx = re.compile(r"^(0+(\.0*)?|0*\.0+)$")
def truthy(value):
return value != "" and not zeroRgx.match(value)
```
[Try it online!](https://tio.run/##jY/PSsQwEMbvfYpx8NBsNUS8LRTx4gOIN/9A6M7aQpqEJJWt@O41nRRUPGggX2a@YWZ@8XPqnb1elmH0LiQIVL1TcPevJ2hzIjs3@sFQHfClVk39JNVO3HyoXQ4acY6iOtARUphSP9dv2kwk9hXkEyhNwQJbcNYCImh7AOsSbPPlqFPXb02LD4NNNd5pE2ne57lHF9ZuGCw8Il6gWq9aVRZhQ7LLujnfj/yRKXwubDpGyl/9ohbQtsCruV5YAvnARVEVQ1RbgA/c@YtSl/1X63NiGmAkyNKs0SWTF1j5B07e8U@aW2MgUUzQ6UgRfJ6HYvkE)
[Answer]
# [Python](https://www.python.org), 29 bytes
```
lambda s:s.strip("0")in"."!=s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhZ7cxJzk1ISFYqtivWKS4oyCzSUDJQ0M_OU9JQUbYsham7uLSjKzCvRiE7TyNRUSMsvUshUyMxT0FBS0uECqgYRBmBKD0pCxPQgMhAKJogM9FB4QGtjNblw2JQI1WwIpisghilAjFQAkdpgti7EAVAb9SBGQjyxYAGEBgA)
Outputs True for falsy and False for truthy.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 23 bytes
```
s=>/[^0.]/.test(s)|s!=0
```
[Try it online!](https://tio.run/##VY49DsIwDIV3nyJMTYTqmrlKN07BjxqVFopKU8UWYuDuwWUCy5a@J/s9@R6egbs0LlLO8dLnwWf2TXU4E54qlJ7FsnvzxlMW400LBEQEuLYiqtL58m/hnyII63oH9FI2emtgS1BqyOrVsBYljQ/rkJdpFFsc58LVIDjEtA/dzbLxjenizHHqcYpXO@hbztX5Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„+-₂‡{Ā
```
[Try it online](https://tio.run/##yy9OTMpM/f//UcM8bd1HTU2PGhZWH2n4/1/bAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Rw3ztHUfNTU9alhYfaThv87/aCUlHSUDEDYAkXoQAiygBxYFk1ARZKCHwgNKKyglQtQYgqgKsA4FsDYFIKENYumCTYcYCLYpOhZIpCXmFKcCaSOQBFiJAVi1QaqBUiwA).
**Explanation:**
```
‡ # Transliterate in the (implicit) input-string
„+- # all "+" and "-"
₂ # to "2" and "6" respectively
{ # Sort all characters in this string (based on codepoint)
Ā # 'Python-style' truthify this sorted string
# (which is output implicitly as result)
```
The new 05AB1E is built in Elixir.
With just `Ā`, the `0.` and `00.` test cases are incorrectly truthy instead of falsey and the `+0`, `-0`, and `0e0` test cases are incorrectly falsey instead of truthy. The sort `{` is to fix `0.`, `00.`, and `0e0` and the transliterate `„+-₂‡` to fix `+0` and `-0`.
---
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
…+- ₁‡{Ā
```
[Try it online](https://tio.run/##MzBNTDJM/f//UcMybV2FR02NjxoWVh9p@P/fINUAAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/Rw3LtHUVHjU1PmpYWH2k4b/O/2glJR0lAxA2AJF6EAIsoAcWBZNQEWSgh8IDSisoJULUGIKoCrAOBbA2BSChDWLpgk2HGAi2KToWSKQl5hSnAmkjkARYiQFYtUGqgVIsAA).
**Explanation:**
```
‡ # Transliterate in the (implicit) input-string
„+- # all "+", "-", and " "
₁ # to "2", "5", and "6" respectively
{Ā # Same as above
# (after which the result is output implicitly)
```
The legacy version of 05AB1E is built in Python 3.
With just `Ā`, the `0`, `0` , `+0`, `-0`, and `0e0` test cases are incorrectly falsey instead of truthy. The transliterate `…+- ₁‡` is to fix `0`, `0` , `+0`, and `-0`, and sort `{` is to fix `0e0` (thanks to *@JonathanAllan* for noticing a bug with this `0e0` test case).
---
# [2sable](https://github.com/Adriandmen/2sable/blob/master/Info.txt), ~~11~~ ~~10~~ 9 [bytes](https://en.wikipedia.org/wiki/Windows-1252#Codepage_layout)
```
'.Q«Ô0Þså
```
Outputs an inverted boolean.
[Try it online](https://tio.run/##MypOTMpJ/f9fXS/w0OrDUwwOzys@vPT/fz0A) or [verify all test cases](https://tio.run/##MypOTMpJ/V9Waa@k8KhtkoKSfaXLf3W9wEOrD08xODyv@PDS/zr/o5WUdJQMQNgAROpBCLCAHlgUTEJFkIEeCg8oraCUCFFjCKIqwDoUwNoUgIQ2iKULNh1iINim6FggkZaYU5wKpI1AEmAlBmDVBqkGSrEA).
**Explanation:**
```
'.Q '# Check if the (implicit) input is equal to "."
« # Append this 1 or 0 to the (implicit) input
Ô # Connected uniquify (uniquifies groups of adjacent equal characters)
0 # Push integer 0
Þ # Floatify and then stringify it: "0.0"
så # Check if the connected uniquify string is a substring of this
# (so one of "", "0", "0.", ".0", "0.0", or "."†)
# (which is output implicitly as result)
```
2sable is built in Python 3 as well, and is the oldest of the three versions and predecessor of the legacy 05AB1E version.
It lacks a lot of the builtins, including the `Ā` we use in the other two programs, so I had to find an alternative. I ended up using the connected uniquify builtin `Ô` and check whether the result is one of `""`, `"0"`, `"0."`, `.0"`, `"0.0"`. I do this by checking whether it's a substring of `"0.0"`.
† After which only the `"."` test case would incorrectly give a truthy instead of falsey result, which I've fixed by adding a leading `'.Q«`.
[Answer]
# Trivial [Pip](https://github.com/dloscutoff/pip) answers, 1 byte
Thanks to [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") defaults, the identity function/program is a solution in Pip, since it turns falsey inputs into falsey outputs and truthy inputs into truthy outputs. Therefore, either of these full programs will work when given input as a command-line argument:
```
a
g
```
This program will work when given input on stdin:
```
q
```
And this works as a function solution:
```
_
```
While we're at it, logically negating the input gives some two- and three-byte solutions:
```
!a
!q
\!_
```
I'm making this post as a community wiki to head off these obvious answers (and other trivial solutions such as `@g` or `{a}` that are basically the same thing but longer). You are encouraged to post your own *non*-trivial Pip solutions.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes
```
∧№.⁻θ0⁻.θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxL0XDOb8UyFLSU9JR8M3MKy3WKNRRUDJQ0tSE8cFShZqamtb//@v91y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Outputs `.` for truthy, nothing for falsy. Note: Due to bugs in Charcoal's input, you need to input an empty string using a blank line. Explanation: Port of @Albert.Lang's Python answer.
```
№ Count of
θ Input string
⁻ 0 With `0`s removed
. In literal string `.`
∧ Logical And
. Literal string `.`
⁻ θ With input string removed
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~16~~ 15 bytes
```
1`0\.|\.0
^0*$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3zDBIEavJkbPgIsrzkBL5f9/Ay4DAwMuPRACMvWAPCAGs5GBHgrPgCsRJG3IZVABZCsA1SpwaRtw6QINAenVMwAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
1`0\.|\.0
```
Delete at most one `.` adjacent to a `0`.
```
^0*$
```
Match any number of zeros.
[Answer]
# [Vyxal](//github.com/Vyxal/Vyxal), 11 bytes
```
`+- `₈ĿṅsEḃ
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgKy0gYOKCiMS/4bmFc0XhuIMiLCIiLCJcIiswXCIiXQ==)
Port of Kevin Cruijssen's 05AB1E (legacy) answer.
### Explanation
```
`+- `₈ĿṅsEḃ
Ŀ # Transliterate the (implicit) input,
`+- ` # Replacing the characters "+", "-" and " "
₈ # With the characters "2", "5" and "6" respectively
ṅ # Join the list created by nothing
s # Sort the string
E # Evaluate the string
ḃ # And convert to a boolean (Python-style)
```
[Answer]
# [Factor](https://factorcode.org) + `math.unicode`, 45 bytes
```
[ dup "0"without "."subseq? swap "."≠ and ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VU8xDsIwDNx5hdUVNQImBANsiIUFMSGG0KZqVUhD46ggxAN4A0sW-AAbP-nKS4gTBoiUu_jss-PbI-MJVrVtX6vlfDEbQSlqKXagBWoHByNkIjTsOebMyCKpUgGqFognVRcSYdw5QxRB1KPbI2QBvMC86vGr_B72F7n0hZrxUNYnOnoTeKfjqEuv2A8IPWnY5W4wi4dtvIbUKPpKU2BeGaQqbbZuiwnohiuK31cLXKawCaYnmqSEtdtPAYMNDLbFNGSsDfwB)
Returns `t` for falsey and `f` for truthy.
With zeros removed, is it a sub-sequence of `"."`? And is the original input not equal to `"."`?
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 75 bytes
```
i;f(char*s){return*s==48?i+=2,f(s+1):*s-46||i++&1?s=i!=1&!*s,i=0,s:f(s+1);}
```
[Try it online!](https://tio.run/##VYzdCoJAEIXv5ylMSHZdlTEkUll8kOpCzJ@FWsIxCtRn33brpoYZ@M7MmdPEfdMYo8qONUM9hsTnsZ0eow5JyuxQKSF3UcdIpLwIKc72y6KECNKKpNrINNiEFCmJERVfU7maW6004zO4PI@OeX4u4Tmoa8v6diJGnMN9VHrqmL@9nLQfeZ1blrAaBESExLXFxCo7H/6t5E8h1O6cAr4se9brgUCIbYj7TfAN "C (gcc) – Try It Online")
[Answer]
# [Go](https://go.dev), 106 bytes
```
import."regexp"
func f(s string)bool{return len(s)>0&&!MustCompile(`^(0+(\.0*)?|0*\.0+)$`).MatchString(s)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVHdTsIwFI63fYpDFdLCWOadWYKGGLwSIQPjhairs8XpWJetIyTIk3hDTHwovPRJ7Nb5l0CTnp6e0_N953x9fZvK9aaVsOCZTTnMWBgjFM4SmSobi5nCP5dMpWE8zfB7rkT7aPP0HU_5lC8SjEQeByBIBuYhvZcyWqZc5WkMEY9JRo-dRqPWzzN1KmdJGHHi3xKnRSa206QnL05TOy164FO7z1TwOCphdNnKMH7sfZYUw18KMri-qdwlkuB2YJREoSKZhScxpkjIFO4s7nZSFuvhJCwH0AGWJDx-IAMLPJ5ELODdKCLc8rFv-T6lK2SaRitkZio0IRSWSLAo41lBMyQ-xgg7xXYKaxtTBuwyWtoq8nfZ_24O9ilCKs1_cZmpOCyORVkPJQho0yq8dsll4G0DUA1aQJhRq1YrVQThFIVCC1DrmJTOwFALpwTBPc8beC5cdS_GcNY9H_VcqO_PoT7XGlrALZBUa7HawmL63kZSZHZxjL3LXRTVV6_X5vwC)
Port of the reference regexp.
[Answer]
# [R](https://www.r-project.org), 36 bytes
```
\(s)trimws(s,,0)%in%c("",".")&s!="."
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3VWI0ijVLijJzy4s1inV0DDRVM_NUkzWUlHSU9JQ01YoVbYE0VO2t5MQSDSW3xJzi1MqYPCVNrjSgOjBpAKUMoAw9OA2T0YOpgDEQUshAD4UHUsEFtjSkqLQkA25pIlynIZRVATctFcpQgAkoQGhtKF8X5jS4O0COhfhwwQIIDQA)
Port of [@Albert.Lang's answer](https://codegolf.stackexchange.com/a/256170/55372).
Uses the `whitespace` argument of the `trimws` function introduced in R 3.6.0.
[Answer]
# Regex (any), 16 bytes
```
^0*(0\.|\.0)?0*$
```
Falsy matches the regex, truthy doesn't.
# [Python 3](https://docs.python.org/3/), 46 bytes
```
import re;re.compile(r"0*(0\.|\.0)?0*$").match
```
[Try it online!](https://tio.run/##jZDBTsQgEEDv/YoJeihrl9DtraYaL1734sHE9YCVpiS0JYCNTfz3CkNN3OxBSZiBN4F5YBbfT2O1rmowk/Vg5W3XWMnaaTBKy9wSvsv5iX2dGKf3fHdNKBuEb/vV2w/fL9CAFsPbu4C5hnHy0OUzza7A8Rr4/s6VBbCQDgUcIy3PaLXRQ6IV0k4oXcBz5NUlP2bGqtHn5FFoJ5ea0KybLMxCgxrhhZCC8Dh5jCwFBAwpxo38Huxsx8lrnUEYwjkZPiU9NQ9NKDQNYGusJxcrjcUi3eRo9mP5hCcvLEXqX8b0iTaAShDCTVzt0TzJsj90Qo9/2jxoDV46D61w0oEJ9xG6fgM "Python 3 – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~16~~ 13 bytes
```
aRM0N'.&!aQ'.
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCJGYVtcbltcIlwiXVxuW1wiMFwiXVxuW1wiMDAwXCJdXG5bXCIuMFwiXVxuW1wiLjAwXCJdXG5bXCIwLlwiXVxuW1wiMDAuXCJdXG5bXCIwLjAwXCJdXG5bXCIwMDAwMDAwMDAwMDAwLjAwMDAwMDAwMDAwMDAwXCJdXG5bXCJhXCJdXG5bXCIwMDAxXCJdXG5bXCIweDAwXCJdXG5bXCIwZTBcIl1cbltcIiAwXCJdXG5bXCIwIFwiXVxuW1wiKzBcIl1cbltcIi0wXCJdXG5bXCIuXCJdXG5bXCIwLjAuMFwiXVxuXXtcblAoKFNUYSlXUlxcXCJcIlxcXCIpLlwiIC0+IFwiLltcIkZhbHNlXCI7XCJUcnVlXCJdQHsiLCJhUk0wTicuJiFhUScuIiwifVZhXG59IiwiXCIuMDAwLjAwXCIiLCIiXQ==)
-3 bytes thanks to @DLosc
Non-trivial pip answer, port of [@Albert.Lang's answer](https://codegolf.stackexchange.com/a/256170/110555)
[Answer]
# [Acc!!](https://www.python.org), 107 bytes
```
Count i while 1-_/4 {
_*524+N
53308230694/5^(_/131+2*0^(_%131-48)^2+0^(_%131-46)^2+_^130%131)%5+1
}
Write _
```
[Attempt This Online!](https://ato.pxeger.com/run?1=vVfbbuM2EH03-hEEA8OSFcl2LotsgPQl2LfCKLpF-5DEAivTMbsSKVDUxtkgX9KXvOz-U_sd_YDOkNKKXis3FC0B60IOzxmeGZOjP76Ut2at5MNf330SRam0IZrvk-q2GgyWfEV0LYNMLaFLyDI8HRBo-E7O7C2pylyYYHQpR6E_ZjSTVc4Mt5PdEN_wrMG6o4BWm_dGc1bQUxIovQyyNdMhWSlN8An4LOV96BzpEFmWnSOoc0bIJZcGKKf2NVeq_IXpCjourmxPeXvufLqgKZpR1408uZB8Xhf79gEJuawLrndJLNGK0D2KVmjd9WPbI7AUUcLqiwK8qbYGLfiZvV2c4jVBnzcBoIVXgx6rpEKwIPSppTI9vJmSRsiab6HAikh0Rmb-dId-Rug93UaAMafgdrcnJTrViJqUynerbU7hhJUll8uAEjpughJ9xYgItT7R3dmNbex7_AJkuuQ5grYU28A8r_juijQTFSfvb6Vhm3daKx3QH1CY4fKU1LJgJlvzJbmnZNgK2aHuIhagjObJqs5zOzXQ9FzV4FxwweJPVyG5WYuckyCJQnJ5R12Whd-qX-y6yTel5lUllASGjywXS8jId187gyK51qoug4OwR82VN30XGlsX1xZotovzjPp-XPE_9WoA6sTBAHrLhf7TR7DamX1p4q2qatl608Kq25sa2J5KDyFtIHxnvTTphdttEXksdP1O9WTYr1oYl1O9CWWV6k0qy_LCxJr1JFaD_FxyYXss7C9WiZZaSAMHgg6GVbgP2_LybDQKUfCOv9_Fx6OL7bURfqHH2F6bC26lTyn--FKei2N_XmD7lxHE2OAhuv23_a8iURlYFp6n_0MgOsk0N7WG2F9KmvyuhAycGE0Z0qM2CtHUCfTntkqprD7EKPKjra_8mEHl4UgqMldYeKzaJSe0qZRK3J7xtlULgCFsBxVn2u4FFwsyjd_CWZPOg3A8GS6i-Ap2Bc8fbHuk89UWDEwAcasxllosM1x3NUsjALrmvMm_5QXKeXp1eRO9lK2ocyNK2O9zbpALJagho3SVKTDGoooRrW6e8MFPpj0YMOQagnONCsOpnX1wkRHmlqgVYXlOBCasWImGTvLKoD2MlkxzWcWxhwd-EbPmbbBsFWvW4BFhEDrMTxS_1Oq3nBcVYRqzFyZo7oH8xMucZZxUayyjVYmVpAL2G2HWaCx0i_8RnAKBOs39iGsHE9AFyEvHY-9A7DWboNlk4pl1rswdOSMZSgJaXTcLlXxjiC3CuxR4mmaONF7ZDvkAewNGKPSom8Dh1MEAJEtTyQqeprb4TNMC0iFN6dZ3xGg0-lybVXzy5wdXP4mmcprF6eSI3A3S8fHBUTQfHB8eTk8ODqdv3h5NjhdBOpkdzqKD8RQeh_AYH52Ei4Ooe32Dr-lidjjF93B4HM0G9wN3gqYN5d_A3nxHwMrsZwOl-3SKvyleE3exHYnttdemx2_J1hsOM2cyw9vGTeB4JfaRwCXCp9hSONTE_z4Bn5rPIHCtS393OkLvvj0YSfw9GXkR8L_YotHl1BtzM0O39ocHd_8H)
Takes the input NULL-terminated, returns `chr(5)` for truthy and `chr(4)` for falsey.
`53308230694` encodes this table (minus 1, which is later added), which represents the transitions of a FSM for this language, and the rest of the code just converts the input to the correct format.
| State\Input | 0 | 1 | 2 | 3 |
| --- | --- | --- | --- | --- |
| 0 | 5 | 4 | 3 | 1 |
| 1 | 5 | 4 | 2 | 1 |
| 2 | 5 | 4 | 4 | 2 |
| 3 | 4 | 4 | 4 | 2 |
Where 0 is "null byte", 1 is "invalid character", 2 is ".", and 3 is "0". The state 4 is rejected, and 5 is accepted.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~73~~ ~~72~~ ~~67~~ ~~66~~ 64 bytes
```
lambda v:not re.match("^(0+(\.0*)?|0*\.0+)$",v)and""<v
import re
```
[Try it online!](https://tio.run/##jY7BagMhEIbvPsUw9KDZVCy9LV1KL32C3pIWbOKyC64rapcE8u4bHXNoKYUO@Dv@g/N//pyG2T2ufbdfrZ4@jxqW1s0JgpGTToeB4wdXDd9LtRHPF7XJTSPucLsI7Y6ITwsbJz@H8mH1YXSJ46u20ZxbFKyfAyzawuhgh7hFVY4qKquQIcklvTnfS/54KXxvGeTSMZqc2vO8X0DXAaXSqGIE4wMNBauGYLcG38JXGn4D6hr9UK4TgQDRQJamdPcEXTnl3yR5/T9BXqyFZGKCg44mgs@rUKxX "Python 3 – Try It Online")
Golfed reference implementation from @DLosc.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 31 bytes
```
"$args"-match"^0*(0\.|\.0)?0*$"
```
[Try it online!](https://tio.run/##dY7RTsMgFEDf@xWEENPOQfADFpss81XjfHNqEG9tls5OoHHJ1m@vICnp9HrfOPdwYN9@gbE1NA3XrYGBVYvjQJky75bynXK6ps9ylsuNOG2ELK7ljNGhz7Iyz4ifeZlTOiesUo2FIiGJMYlRgUM0INAqSv8pTEecnTBdBeZMd164Qugh3v9FAYEEE8lfdol4HGECyQkpJmZBTuSmNSula377ugXtyPHHZQ6s8xoc9h7CG1kQ9hI3BmzXOA/4R@vyC1ZFOb7xeLdedta1u1h7KmMuzLrTGqwNpVTl8DkGk/fgY0EK0QRXk3@Mt9PyfvzRNNVn/fAN "PowerShell Core – Try It Online")
Down to 31 bytes using [Bubbler's regex](https://codegolf.stackexchange.com/a/256389/97729)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
x"0."_S{
```
[Try it online!](https://tio.run/##K6gsyfj/v0LJQE8pPrj6/38gw0AJAA "Pyth – Try It Online")
Feels like there's gotta be something shorter but I couldn't find it.
Outputs 0 for falsy and -1 or 1 for truthy.
### Explanation
```
x"0."_S{Q # Implicitly add Q
# Implicitly assign Q = eval(input())
{Q # deduplicate
S # sort
_ # reverse (at this point we have either "", "0", or "0.")
x"0." # find in "0." (returns 0 for above, 1 for ".", -1 for all else)
```
[Answer]
# Google Sheets, ~~37~~ 34 bytes
`=regexmatch(A1,"^0*\.?0*$")*(A1<>".")`
Put the input in cell `A1` and the formula in `B1`. Outputs `1` for falsey and `0` for truthy.
Using [Bubbler's](https://codegolf.stackexchange.com/a/256389/119296) regex:
`=regexmatch(A1,"^0*(0\.|\.0)?0*$")`
Outputs `TRUE` for falsey and `FALSE` for truthy.
[Answer]
# [Uiua](https://www.uiua.org/), ~~33 bytes~~ 28 bytes (SBCS)
Edit: Using [Bubbler's improved regex](https://codegolf.stackexchange.com/a/256389/97729).
```
=0⧻regex"^0*(0\\.|\\.0)?0*$"
```
[Try it online!](https://www.uiua.org/pad?src=UGlwIOKGkCA9MOKnu3JlZ2V4Il4wKigwXFwufFxcLjApPzAqJCIKCiJGYWxzZXkiClBpcCAiIgpQaXAgIjAiClBpcCAiMDAwIgpQaXAgIi4wIgpQaXAgIi4wMCIKUGlwICIwLiIKUGlwICIwMC4iClBpcCAiMC4wMCIKUGlwICIwMDAwMDAwMDAwMDAwLjAwMDAwMDAwMDAwMDAwIgoKIlRydXRoeSIKUGlwICJhIgpQaXAgIjAwMDEiClBpcCAiMHgwMCIKUGlwICIwZTAiClBpcCAiIDAiClBpcCAiMCAiClBpcCAiKzAiClBpcCAiLTAiClBpcCAiLiIKUGlwICIwLjAuMCIKUGlwICIwLi4wIgo=)
Not much to explain here - it just matches the regex with the input string and checks that the number of matches is 0.
# Idiomatic Uiua, 39 bytes
```
(0;|(↥⊃'>⊢(<⊢⇌)∶1|1;)∊0∩/+⍉.∺="0.")>0⧻.
```
[Try it online!](https://www.uiua.org/pad?src=UGlwIOKGkCAoMDt8KOKGpeKKgyc-4oqiKDziiqLih4wp4oi2MXwxOyniiIow4oipLyvijYku4oi6PSIwLiIpPjDip7suCgoiRmFsc2V5IgpQaXAgIiIKUGlwICIwIgpQaXAgIjAwMCIKUGlwICIuMCIKUGlwICIuMDAiClBpcCAiMC4iClBpcCAiMDAuIgpQaXAgIjAuMDAiClBpcCAiMDAwMDAwMDAwMDAwMC4wMDAwMDAwMDAwMDAwMCIKCiJUcnV0aHkiClBpcCAiYSIKUGlwICIwMDAxIgpQaXAgIjB4MDAiClBpcCAiMGUwIgpQaXAgIiAwIgpQaXAgIjAgIgpQaXAgIiswIgpQaXAgIi0wIgpQaXAgIi4iClBpcCAiMC4wLjAiCg==)
**Explanation:**
```
(0;| )>0⧻. # If the length is 0 return 0. Otherwise:
∺="0." # Produce a matrix of matches with '0' and '.'
⍉. # Make a copy and transpose it
∩/+ # In both the original and transposed matrices, add up each row
( |1;)∊0 # If there is a 0 in the per character array
# (signifying a character other than '0' or '.'),
# return 1. Otherwise:
∶1 # Put a 1 on the stack and swap the top two items
⊃ # Apply both of the next functions to the same values
(<⊢⇌) # Reverse the array and check if 1 < the first value
# (This tests that the number of '.' chars is > 1)
'>⊢ # Check if 1 > the first value
# (This tests that the number of '0' chars is < 1)
↥ # Return the maximum of the two checks
# (This will return 0 if the number of '0' chars >= 1 AND the number of '.' <= 1)
```
[Answer]
# [Uiua](https://uiua.org), 18 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
<∩≍¬⊚.=@.⊃▽'△.≠@0.
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAgPOKIqeKJjcKs4oqaLj1ALuKKg-KWvSfilrMu4omgQDAuCgriipDiiLVmeyIiCiAgICAiMCIKICAgICIwMDAiCiAgICAiLjAiCiAgICAiLjAwIgogICAgIjAuIgogICAgIjAwLiIKICAgICIwLjAwIgogICAgIjAwMDAwMDAwMDAwMDAuMDAwMDAwMDAwMDAwMDAifQoK4oqQ4oi1ZnsiYSIKICAgICIwLi4wIgogICAgIjAwMDEiCiAgICAiMHgwMCIKICAgICIwZTAiCiAgICAiIDAiCiAgICAiMCAiCiAgICAiKzAiCiAgICAiLTAiCiAgICAiLiIKICAgICIwLjAuMCJ9Cg==)
Initially based on [chunes' Factor answer](https://codegolf.stackexchange.com/a/256185/78410), but it evolved a lot from it. Returns 1 if the input is falsy, 0 otherwise.
```
<∩≍¬⊚.=@.⊃▽'△.≠@0. input: a string S
≠@0. keep S and push its non-zero-digit mask
⊃▽ S with zeros filtered out
=@. is-dot mask of above
∩≍¬⊚. C1:is it the same as boolean negation of its nonzero indices?
(the length can be equal only if the mask is all ones, and the content equal only if
the length is zero or one, i.e. the array is [] or [1].
this tests if the input without zeros is either empty or a sole dot.
now we need to filter out the case where S = ".")
∩≍ ⊃ '△. C2:take the non-zero-digit mask, and test if it is the same
as its shape
(this test passes only if the array is [1])
< test if C1 is true and C2 is false
```
More explanation on the C1 condition:
The input is a boolean vector. `⊚` (where) on it collects the zero-based indices of ones, e.g. `[1, 0, 1, 1, 0, 0, 1]` becomes `[0, 2, 3, 6]`. The "logical negation" `¬` calculates `1-x` for each value `x` in the array, e.g. `[0, 2, 3, 6]` becomes `[1, -1, -2, -5]`.
For the input to equal its `¬⊚`, the following conditions need to be met:
* The lengths are equal. For a boolean vector input, `⊚` generates a vector whose length is the count of ones in the input. To meet the length requirement, the input vector must be all ones.
* The individual values are equal. Since the input is boolean, the output must be also boolean (either 0 or 1). `¬` maps 2 or higher to negative numbers, so the original input cannot contain a 1 at indices 2 or higher. This reduces the candidates to `[]`, `[1]`, and `[1,1]`.
Now we can do an exhaustive check:
```
input -> ⊚ -> ¬⊚
[] -> [] -> []
[1] -> [0] -> [1]
[1,1] -> [0,1] -> [1,0]
```
Therefore `≍¬⊚.` checks if the given boolean vector is either `[]` or `[1]`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 15 bytes
```
s=>-s!=0+s+'e0'
```
[Try it online!](https://tio.run/##VYyxDsIwDER3f0WYkqiqZeYq3fgLhkYlgaLSVHGE@vfBYQLLlt7pzvf0b89zXvbSb@kWanSV3djzyVHHnQ6ka1FOTUBARIBtBVGU3Jd/B/8UgW/2GegQVpJVQIGgI@ilqP1L4QEJJix5eRmLvK9LMfq6aTtAwZjyxc8Pw8qNak4bpzXgmu4mGrbWDvUD "JavaScript (Node.js) – Try It Online")
* If `s` is number, then `s==0` to make it false. `e0` avoids another `e` in number(`0e0`).
* If `s` is `.`, `x` or `o`, then `-s` is `NaN`
* If `s` is `0` or `0` , then `0+s+0` is NaN
Assumes double handle enough logrange
] |
[Question]
[
The English language and most programming languages are written and read from left-to-right, top-to-bottom, but that [needn't be the case](http://en.wikipedia.org/wiki/Writing_system#Directionality).
In fact for the block of text
```
ABC
DEF
```
I can think of eight related ways it might be read:
1. Left-to-right, top-to-bottom (LTR-TTB): `ABCDEF`
2. Top-to-bottom, left-to-right (TTB-LTR): `ADBECF`
3. Left-to-right, bottom-to-top (LTR-BTT): `DEFABC`
4. Bottom-to-top, left-to-right (BTT-LTR): `DAEBFC`
5. Right-to-left, top-to-bottom (RTL-TTB): `CBAFED`
6. Top-to-bottom, right-to-left (TTB-RTL): `CFBEAD`
7. Right-to-left, bottom-to-top (RTL-BTT): `FEDCBA`
8. Bottom-to-top, right-to-left (BTT-RTL): `FCEBDA`
# Challenge
Write a rectangular block of text that can be read in each of the eight ways above as eight **single line** programs in your language of choice. Each of these programs should output a different integer from one to eight.
It doesn't matter which reading direction outputs which number, they do not have to match the numbers above. For example, if your text block were still
```
ABC
DEF
```
then the program `ABCDEF` might output `5` and `FEDCBA` might output `2`, and the other six programs would output `1`, `3`, `4`, `6`, `7`, and `8` in some order.
**The text block may contain any characters except [line terminators](http://en.wikipedia.org/wiki/Newline#Unicode).**
Output should go to stdout or a similar alternative if your language doesn't have a proper stdout. There is no input. You may assume the programs are run in a REPL environment.
[Pietu1998](https://codegolf.stackexchange.com/users/30164/pietu1998) charitably wrote a [JSFiddle](http://jsfiddle.net/7s35c6yn/4/) that gives the 8 different single line programs when given a block of text. I've made it into a stack snippet:
```
<script>function f(n){n=n.split("\n");var e=n.map(function(n){return n.length}).sort()[n.length-1];n=n.map(function(n){return(n+Array(e+1).join(" ")).substring(0,e)});var t=n[0].split("").map(function(e,t){return n.map(function(n){return n[t]}).join("")});n=[n.join(""),n.reverse().join(""),t.join(""),t.reverse().join("")],n=n.concat(n.map(function(n){return n.split("").reverse().join("")})),document.getElementById("a").innerHTML=n.map(function(n,e){return document.getElementById("b").checked?n+" "+"LLTTRRBB"[e]+"T"+"RRBBLLTT"[e]+"-"+"TBLRBTRL"[e]+"T"+"BTRLTBLR"[e]:n}).join("\n")}</script><textarea onkeyup="f(this.value)" id="c" placeholder="Code"></textarea><br/><input type="checkbox" id="b" onchange="f(document.getElementById('c').value)" checked/> <label for="b">Show directions</label><br/><pre id="a"></pre>
```
You can still find [Martin's](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) CJam version [here](http://cjam.aditsu.net/#code=qN%2F%3AL%0ALz%0ALW%25z%0ALW%25%0ALW%25Wf%25%0ALW%25Wf%25z%0ALWf%25z%0ALWf%25%0A%5D%0A%7BM%2AN%2Bo%7D%2F).
# Scoring
Your score is the area of your block of text (the width times the height). The submission with the lowest score wins. (Essentially the smallest code wins, hence the [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") tag.) Tiebreaker goes to the earlier posted submission.
The example is 2 by 3 so its score is 6. A score less than 4 (2 by 2) is impossible because then some of the 8 programs would be identical and couldn't output two different values.
[Answer]
# J, 3 \* 3 = 9
```
1[2
+2+
2+2
```
Executing all directions:
```
". '1[2+2+2+2','2+2+2+1[2','1+2[2+2+2','2+2[2+1+2','2+2+2+2[1','2[1+2+2+2','2+2+2[2+1',:'2+1+2[2+2'
1 7 3 4 8 2 6 5
```
Explanation:
* In J execution goes from right to left and there is no operator precedence.
* The `[` (`left`) takes the left side of its two operand so it essentially cancels the whole right side of our expression e.g. `1+2[2+2+2` becomes `1+2[6` and then `1+2`.
* The left expressions are additions with a total of 1, 2, 3 and 4 operands. There are two of each `n`-operand expressions one with the number `1` and one with only `2`s. The additions with `1` generate the odd numbers and the others generate the even ones.
[Answer]
# [Befunge-98](http://esolangs.org/wiki/Befunge), ~~5x5 = 25~~ 5x3 = 15
```
1+4+2
$.@.$
3+4+4
```
I wrote a little script that found the correct numbers for me. It took a while, but hey, I just beat GolfScript! :D
The scripts I used are [here](http://jsfiddle.net/k49twwz2/5/) and [here](http://jsfiddle.net/631z2d06/1/), but I don't suggest looking at them since the code style is extremely carcinogenic.
## Subprograms
```
1+4+2$.@.$3+4+4 LTR-TTB 5
3+4+4$.@.$1+4+2 LTR-BTT 7
1$3+.+4@4+.+2$4 TTB-LTR 3
2$4+.+4@4+.+1$3 TTB-RTL 4
4+4+3$.@.$2+4+1 RTL-BTT 8
2+4+1$.@.$4+4+3 RTL-TTB 6
4$2+.+4@4+.+3$1 BTT-RTL 2
3$1+.+4@4+.+4$2 BTT-LTR 1
```
## Old version
```
1.6
3 @ 4
.@ @.
8 @ 7
2.5
```
### Subprograms
Output the numbers 1-8 respectively.
```
1.6 3 @ 4.@ @.8 @ 7 2.5 LTR-TTB
2.5 8 @ 7.@ @.3 @ 4 1.6 LTR-BTT
3.8 1 @ 2.@ @.6 @ 5 4.7 TTB-LTR
4.7 6 @ 5.@ @.1 @ 2 3.8 TTB-RTL
5.2 7 @ 8.@ @.4 @ 3 6.1 RTL-BTT
6.1 4 @ 3.@ @.7 @ 8 5.2 RTL-TTB
7.4 5 @ 6.@ @.2 @ 1 8.3 BTT-RTL
8.3 2 @ 1.@ @.5 @ 6 7.4 BTT-LTR
```
[Answer]
# [Brainfuck$](http://esolangs.org/wiki/Brainfuck$), 4x3 = 12
Brainfuck$ is very similar to [Brainfuck](http://esolangs.org/wiki/Brainfuck), but has some more commands, including a command to output the current cell value as numeric output, which was very useful for this challenge.
```
++:+
++
++++
```
One-line commands:
```
++:+ ++++++ LTR-TTB, outputs 2
++++ ++++:+ LTR-BTT, outputs 8
+ ++ +:+++++ TTB-LTR, outputs 4
+++:+++ ++ + TTB-RTL, outputs 3
++++++ +:++ RTL-BTT, outputs 7
+:++++ ++++ RTL-TTB, outputs 1
+++++:+ ++ + BTT-RTL, outputs 5
+ ++ +++:+++ BTT-LTR, outputs 6
```
[Answer]
# TECO, 3\*5 = 15
```
+4 5
+2=4
+1 \
```
`=` prints the value of the last numerical expression. `\` is used to read or write numbers from strings, but I use it only as a discard here.
* `+4 5+2=4 +1 \` 7
* `+ +2+4=1 4 5 \` 6
* `+ +2+1=4 4 \ 5` 3
* `+1 \+2=4 +4 5` 2
* `\ 1+ 4=2+5 4+` 5
* `\ 5 4 1=4+2+ +` 1
* `5 \ 4 4=1+2+ +` 4
* `5 4+ 4=2+\ 1+` 8
[Answer]
# piet - 12x12 = 144

Since a one line program can never terminate, assume it terminates after first output.
8 subprograms in a single image:

[Answer]
# GolfScript, 4x4 = 16
```
1})7
) }
} )
3)}5
```
Makes use of the good old "super comment": an unmatched `}` ignores the rest of the code (in fact, in this case a normal comment `#` would have worked just as well, since all the code is run as a single line). So from each corner there's either only a single number, or (in the other direction) that number incremented by 1, because execution terminates and the stack contents are printed. The 8 programs are
```
1})7) }} )3)}5 # LTR-TTB
1)}3} )) }7})5 # TTB-LTR
3})1) }} )5)}7 # BTT-LTR
3)}5} )) }1})7 # LTR-BTT
5})3) }} )7)}1 # RTL-BTT
5)}7} )) }3})1 # BTT-RTL
7})5) }} )1)}3 # TTB-RTL
7)}1} )) }5})3 # RTL-BTT
```
[Answer]
# Haskell, 26x26 = 676
Uses comments (`--`) to hide the backwards and sideways bits. This makes it terribly long
```
main=print 1--2 tnirp=niam
a a
i i
n n
= =
p p
r r
i i
n n
t t
3 4
- -
- -
5 6
t t
n n
i i
r r
p p
= =
n n
i i
a a
main=print 7--8 tnirp=niam
```
[Answer]
# [Prelude](http://esolangs.org/wiki/Prelude), 5x3 = 15
```
12 34
!
56 78
```
This assumes the [Python interpreter](http://web.archive.org/web/20060504072747/http://z3.ca/~lament/prelude.py), which prints values as numbers instead of character codes.
This doesn't beat Befunge$, but it does beat my GolfScript submission, and I like its simplicity. Note also that it uses only 9 non-space characters, ~~which is less than any other submission so far~~ (J strikes again :)). In Prelude, each digit is pushed onto the stack individually, and depending on the path, there's a different digit right before the `!`, which just prints the top stack element. The 8 programs are:
```
12 34 ! 56 78 LTR-TTB 4
56 78 ! 12 34 LTR-BTT 8
1 52 6 ! 3 74 8 TTB-LTR 6
4 83 7 ! 2 61 5 TTB-RTL 7
87 65 ! 43 21 RTL-BTT 5
43 21 ! 87 65 RTL-TTB 1
8 47 3 ! 6 25 1 BTT-RTL 3
5 16 2 ! 7 38 4 BTT-LTR 2
```
Alternatively, there's also
```
1 3
1+!+1
5 7
```
Which pushes the odd numbers on the vertical paths, and increments them by `1` on the horizontal paths:
```
1 3 1+!+1 5 7 LTR-TTB 4
5 7 1+!+1 1 3 LTR-BTT 8
1 1+5 ! 3+7 1 TTB-LTR 5
1 3+7 ! 1+5 1 TTB-RTL 7
7 5 1+!+1 3 1 RTL-BTT 6
3 1 1+!+1 7 5 RTL-TTB 2
1 7+3 ! 5+1 1 BTT-RTL 3
1 5+1 ! 7+3 1 BTT-LTR 1
```
[Answer]
# CJam - 7×7
Not impressive, but there was no CJam answer and I like the way it looks :)
```
8;];1
7 2
; 0 ;
] 0 0 ]
; 0 ;
6 3
5;];4
```
It mainly uses the fact that `];` clears the stack.
[Try it online](http://cjam.aditsu.net/#code=qN%2F%3AL%0ALz%0ALW%25z%0ALW%25%0ALW%25Wf%25%0ALW%25Wf%25z%0ALWf%25z%0ALWf%25%0A%5D%0A%7BM*_p~N%5Do%7D%2F&input=%208%3B%5D%3B1%20%0A7%20%20%20%20%202%0A%3B%20%200%20%20%3B%0A%5D%200%200%20%5D%0A%3B%20%200%20%20%3B%0A6%20%20%20%20%203%0A%205%3B%5D%3B4%20)
[Answer]
# R, 9x9
No white space, no comments.
```
75%%99299
99%%99699
%%299%%41
%%699%%06
995999997
11%%999%%
99%%799%%
39719%%99
59519%%16
```
I guess this could be expanded to whatever size you want. I thought the modulo operator was most the most flexible of available operators, since it prevents values from being too large regardless of data size, and there's no effect from having really large numbers in between.
```
75%%9929999%%99699%%299%%41%%699%%0699599999711%%999%%99%%799%%39719%%9959519%%16 LTR-TTB 2
59519%%1639719%%9999%%799%%11%%999%%995999997%%699%%06%%299%%4199%%9969975%%99299 LTR-BTT 3
79%%9193559%%91999%%265%%75%%999%%1199999979999%%999%%26%%999%%99409%%9199167%%96 TTB-LTR 4
99167%%9699409%%9126%%999%%99%%999%%999999799%%999%%11%%265%%7559%%9199979%%91935 TTB-RTL 1
61%%9159599%%91793%%997%%99%%999%%1179999959960%%996%%14%%992%%99699%%9999299%%57 RTL-BTT 5
99299%%5799699%%9914%%992%%60%%996%%799999599%%999%%11%%997%%9999%%9179361%%91595 RTL-TTB 6
69%%7619919%%90499%%999%%62%%999%%9999799999911%%999%%57%%562%%99919%%9553919%%97 BTT-RTL 7
53919%%9799919%%9557%%562%%11%%999%%997999999%%999%%99%%999%%6219%%9049969%%76199 BTT-LTR 8
```
[Answer]
# Ruby - 7x7
Not impressive either, same tactic as the Haskell answer.
```
p 1#2 p
3 7
# #
4 8
p 5#6 p
```
[Answer]
# [This](https://www.khanacademy.org/computer-programming/two-dimensional-programming-language/6252487852687360) Programming Language, 5 \* 9 = 45
```
1i;i2
2 2
+ +
i i
; ;
i i
+ +
2 2
5i;i6
```
Which translates into this:
```
1i;i22 2+ +i i; ;i i+ +2 25i;i6
5i;i62 2+ +i i; ;i i+ +2 21i;i2
12+i;i+25i i; ;i i22+i;i+26
22+i;i+26i i; ;i i12+i;i+25
6i;i52 2+ +i i; ;i i+ +2 22i;i1
2i;i12 2+ +i i; ;i i+ +2 26i;i5
62+i;i+22i i; ;i i52+i;i+21
52+i;i+21i i; ;i i62+i;i+22
```
Since `;` terminates the program, the above translates into this:
```
1i; - outputs 1
5i; - outputs 5
12+i; - outputs 3
22+i; - outputs 4
6i; - outputs 6
2i; - outputs 2
62+i; - outputs 8
52+i; - outputs 7
```
**Explanation:** any number from `0` to `9` pushes the corresponding digit onto the stack. `+` pops the top two values `x` and `y` off the stack and pushes `x + y` onto the stack. `i` outputs the stack as an integer.
] |
[Question]
[
Write a full program to find whether the binary representation of a number is palindrome or not?
```
Sample Input
5
Sample Output
YES
```
Print `YES` if binary representation is palindrome and `NO` otherwise.
[Answer]
## Python - 46 chars
```
n=bin(input())[2:]
print'YNEOS'[n!=n[::-1]::2]
```
[Answer]
## Golfscript -- 22 chars
```
~2base.-1%="YES""NO"if
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 85 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 10.625 bytes
*-6 bits thanks to @lyxal*
*-3 bits thanks to @the-thonnu*
```
bḂ≠`∨ȯno`½iN
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJBPSIsIiIsImLhuILiiaBg4oioyK9ub2DCvWlOIiwiIiwiMVxuMlxuM1xuNFxuNVxuNlxuN1xuOFxuOVxuMTBcbjExXG4xMlxuMTNcbjE0XG4xNSJd)
```
b # binary of input
Ḃ≠ # is not equal to its reverse (essentially: is not a palindrome?)
`∨ȯno` # compressed string `yesno`
½ # split into two strings of equal length
i # index that inequality (0/1) into that
N # case swapped to uppercase
```
[Answer]
## Ruby, 41 39
```
$><<%w(YES NO)[(n="%b"%$*)<=>n.reverse]
```
Thanks to Michael Kohl's "%b"%gets trick.
[Answer]
**C 84 81 74 Characters**
```
r;main(v,x){for(scanf("%d",&v),x=v;v;v/=2)r=r*2|v&1;puts(r-x?"NO":"YES");}
```
It does not use any function like string reverse.
[Answer]
## Javascript - 79 77 chars
```
alert((a=(prompt()*1).toString(2))-a.split("").reverse().join("")?"NO":"YES")
```
**More information**
`prompt()*1` : Quick trick to convert string to number.
`.toString(2)` : That's how you convert to binary in javascript.
`a.split("").reverse().join("")` : There is no native support to reverse string, so you have to convert string to array and array to string.
`("[part1]" - "[part 2]")?"YES":"NO"` : `-` is a replacement for `!=` to save 1 char.
[Answer]
# PHP - 41
```
<?=strrev($n=decbin(`cat`))==$n?@YES:@NO;
```
Test:
```
php 713.php <<< 5
YES
php 713.php <<< 6
NO
```
[Answer]
# Perl, 45 characters
```
$_=sprintf'%b',shift;
print reverse==$_?YES:NO
```
[Answer]
**Ruby, 43 characters**
```
puts((n="%b"%gets)==n.reverse ? "YES":"NO")
```
[Answer]
## Windows PowerShell, 67
```
('NO','YES')[($a=[Convert]::ToString("$input",2))-eq-join$a[64..0]]
```
[Answer]
# 05AB1E, ~~17~~ 12 bytes
```
‘NO…Ü‘#EbÂQè
```
*-5 bytes thanks to Adnan.*
[Try it online!](http://05ab1e.tryitonline.net/#code=4oCYTk_igKbDnOKAmCNFYsOCUcOo&input=NQ)
[Answer]
# JavaScript, 75 bytes 69 bytes
```
alert((a=[...(+prompt()).toString(2)]).some(x=>x-a.pop())?"NO":"YES")
```
[Try it online!](https://tio.run/##DcoxCoAwDADAt5gpRezgKFQnVx2cHIMWqagJbZD@vroed9JLaYtBtHl496XQ5aMiksNaIt@iaIxVXjSG58DW2CRXUAT4OfHtMbs@V46ssPx1gGmGDtZxAVPKBw)
A different approach from [HoLyVieR's](https://codegolf.stackexchange.com/users/54/holyvier) solution
**Explanation**
`+prompt()` : Converts string to number
`[...s]` : converts a string `s` to an array of chars
`.some((x) => x - a.pop())` : checks whether there is one element in the array that does not equal the last element of the array
**Edit**
69 chars, thanks to the suggestions by [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)
[Answer]
# [Arturo](https://arturo-lang.io), 47 bytes
```
print(=reverse<=as.binary do arg\0)?->'YES->'NO
```
[Answer]
## Python (51)
```
n=bin(input())[2:]
print'YES'if n==n[::-1]else'NO'
```
[Answer]
# Perl (73)
No string reverse:
```
print f(split//,sprintf'%b',shift);
sub f{@_<=1?YES:shift!=pop()?NO:f(@_)}
```
[Answer]
# Perl (127)
This one constructs all palindromes up to 2^32.
```
sub f{
my($x,$l)=@_;
$l+=2,f(($x<<$_)+1+(1<<$l-1),$l)?return 1:0 for 1..15-$l/2;
$x-$ARGV[0]?0:1
}
print f(0,1)+f(0,0)+f(1,1)?YES:NO
```
[Answer]
## Bash, 55 chars
```
C=`dc<<<$1\ 2op`;[ $C = `rev<<<$C` ]&&echo YES||echo NO
```
[Answer]
## J - 33 characters
```
13 : ';(]-:|.)#:y{''YES'';''NO'''
```
[Answer]
## J: 24
```
((-:|.)#:x){2 3$'NO YES'
```
eg:
```
((-:|.)#:5){2 3$'NO YES'
YES
((-:|.)#:12){2 3$'NO YES'
NO
((-:|.)#:125){2 3$'NO YES'
NO
((-:|.)#:63){2 3$'NO YES'
YES
```
[Answer]
## Haskell (79)
```
0?k=n;n?k=div n 2?(n`mod`2+k*2);f x|x==x?0="YES"|True="No";main=interact$f.read
```
[Answer]
## C (77 bytes)
```
r,t;main(n){for(t=n=atoi(gets(&n));n;r*=2,r|=n%2,n/=2);puts(r-t?"NO":"YES");}
```
[TEST](http://ideone.com/yFzEX)
[Answer]
## Pyth, 18 bytes
```
%2>"YNEOS"!qJ.BQ_J
```
Also 18 bytes:
```
@,"NO""YES"qJ.BQ_J
```
[Answer]
# PHP, not competing
I wanted to do it without using strings at all.
iterative solution, 78 bytes
```
for($x=log($n=$argv[1],2);$i<$x&($n>>$i^$n>>$x-$i^1);$i++);echo$i<$x/2?NO:YES;
```
recursive solution, 113 bytes
```
function p($n,$x=0){return$n<2?$n:is_pal(($n&(1<<$x=log($n,2)/2)-1)^$n>>$x+!is_int($x));}echo p($argv[1])?YES:NO;
```
If `n` is a binary palindrome, the upper half xor the lower half is also a binary palindrome and vice versa.
---
a port of the excellent [C answer from fR0DDY](https://codegolf.stackexchange.com/q/722#722), 58 bytes
```
for($x=2*$v=$argv[1];$x/=2;$r=$r*2|$x&1);echo$r-$v?NO:YES;
```
a binary reverse. Columbus´ egg.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes (non-competing)
```
BṚ⁼Bị“YES“NO
```
[Try it online!](https://tio.run/nexus/jelly#@@/0cOesR417nB7u7n7UMCfSNRhI@vn////fFAA "Jelly – TIO Nexus")
Explanation:
```
BṚ⁼Bị“YES“NO Main link. Arguments: z.
B Binary representation of z.
Ṛ Reversed.
B Binary representation of z.
⁼ Check if x is equal to y.
“YES“NO [['Y', 'E', 'S'], ['N', 'O']]
ị xth element of y (1-indexed).
```
Before printing, Python's `str` function is mapped through a list, and then the elements are concatenated, so you see `YES` or `NO`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes
```
If[PalindromeQ@IntegerDigits[#,2],"YES","NO"]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zMtOiAxJzMvpSg/NzXQwTOvJDU9tcglMz2zpDhaWccoVkcp0jVYSUfJz18pVu1/QFFmXomCQ3q0aez//wA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), [16 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
±î«Áýãf©¯tvf–ɉ2
```
[Try it!](https://zippymagician.github.io/Arn?code=IllFUyJeKD1cfDo7Yil8fCJOTw==&input=NQo3CjE0)
# Explained
Unpacked: `"YES"^(=\|:;b)||"NO`. Man that yes/no required output really killed my byte count
```
"YES" String
^ Repeated
( Begin expression
\ Fold with...
= ...equality
|: Bifurcate
_ Variable initialized to STDIN; implied
;b Binary representation
) End expression
|| Boolean OR
"NO String, ending quote implied
```
This works because empty strings are falsey.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
?q_K.BQK"YES""NO
```
[Try it online!](https://tio.run/##K6gsyfj/374w3lvPKdBbKdI1WEnJz///f1MA "Pyth – Try It Online")
```
?q_K.BQK"YES""NO
K.BQ // Assign binary input to K
?q_K K // Evaluate whether K and reversed K are equal
"YES""NO // Ternary output.
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 23 bytes ([SBCS](https://github.com/abrudz/SBCS))
```
'NO' 'YES'⊃⍨≡∘⌽⍨2⊥⍣¯1⊢⎕
```
-3 bytes from Bubbler, after fitting the question requirements.
Instead of performing an if-else like below, this program uses APL's representation of true as 1 and false as 0 to select from an array, where 'NO' is in the 0th index and 'YES' is in the first index.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tO4HvXOrdZ41LP3UefCR12LNI0edS191Lv40HpDIO9R71Yr9UjXYPVH3S3qfv7qtUC9/0EMBYhoV/Oj3hUgjR0zQCb0rkDVDVQMtOI/ZxqXKReQMDQAAA "APL (Dyalog Unicode) – Try It Online")
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 26 bytes ([SBCS](https://github.com/abrudz/SBCS))
```
{(⌽≡⊢)2(⊥⍣¯1)⍵:'YES'⋄'NO'}
```
## Explanation
```
{(⌽≡⊢)2(⊥⍣¯1)⍵:'YES'⋄'NO'}
{ } function wrapper
⍵ take the right argument
2(⊥⍣¯1) convert to base 2, and split into -1 groups(gets all digits)
(⌽≡⊢) reverse equals right expression?
:'YES'⋄'NO'} if the above is true, display 'YES', otherwise 'NO'
```
[Try it online!](https://tio.run/##AV0Aov9hcGwtZHlhbG9n//97KOKMveKJoeKKoikyKOKKpeKNo8KvMSnijbU6J1lFUyfii4QnTk8nff9m4oaQ4o2O4oqD4o2s4o20wq8z4oaR4o6VU1JD4o6VVEhJU/9mIDU "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Retina](http://github.com/mbuettner/retina), ~~80~~ 78 bytes
Byte count assumes ISO 8859-1 encoding.
```
.+
$*
+`(1+)\1
${1}0
01
1
^((.)*?).??((?<-2>.)*$)
$1¶$3
O$^`.(?=.*¶)
^(.*)¶\1
```
[**Try it online**](http://retina.tryitonline.net/#code=LisKJCoKK2AoMSspXDEKJHsxfTAKMDEKMQpeKCguKSo_KS4_PygoPzwtMj4uKSokKQokMcK2JDMKTyReYC4oPz0uKsK2KQoKXiguKinCtlwx&input=NQ)
Convert to unary. Convert that to binary. Cut the number in half and remove a middle digit if there is one. Reverse the first half. Match if both halves are equal.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
¢è¬?`y`u:"NO
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ouisP2B5g2B1OiJOTw&input=NQ)
] |
[Question]
[
Your task is to determine whether some arbitrary programming language has zero-indexed or one-indexed arrays based on sample inputs and outputs
### Inputs
* An array of integers with at least 2 elements
* A positive integer index
* The value of the array at that index
### Output
One of four distinct values representing:
* **One-indexed** if the language unambiguously has one-indexed arrays
* **Zero-indexed** if the language unambiguously has zero-indexed arrays
* **Unknown** if the given inputs aren't enough to determine whether the language is zero- or one- indexed because it is ambiguous.
* **Neither** if the language is not zero- or one-indexed because it is something else that may or may not make any sense.
## Example Test Cases
Formatted as `[array, elements][index] == value_at_index => output`
```
[2, 3][1] == 2 ==> one-indexed
[2, 3][1] == 3 ==> zero-indexed
[1, 2, 2, 3][2] == 2 ==> unknown
[4, 5][1] == 17 ==> neither
[-3, 5, 2][2] == 5 ==> one-indexed
[-744, 1337, 420, -69][3] == -69 ==> zero-indexed
[-744, 1337, 420, -69][3] == 420 ==> one-indexed
[-744, 1337, 420, -69][3] == -744 ==> neither
[42, 42, 42, 42, 42][2] == 42 ==> unknown
[42, 42, 42, 42, 42][1] == 56 ==> neither
```
## Rules and Scoring
* Use any convenient I/O methods
* Use any convenient representation for each of the four distinct categories as long as it is consistent and each possible category is mapped to exactly one value.
* You may assume that all array values are between \$-2^{31}\$ and \$2^{31} - 1\$, inclusive (i.e. the signed int32 range.)
* You may assume that arrays are no longer than \$65535\$ elements.
* You may assume that the index is in-bounds for both zero- and one-indexed semantics.
Shortest code wins. Happy golfing!
[Answer]
# [convey](http://xn--wxa.land/convey/), 47 bytes
Returns 0 for neither, 1 for one-based, 2 for zero-based and 3 for unknown.
```
{2+~`0
?;\2:!2[
v^<]`
?;\?+2
v^< v*+}
!>>>=?^
2
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiezIrfmAwXG4/O1xcMjohMltcbnZePF1gXG4/O1xcPysyXG52XjwgdiorfVxuIT4+Pj0/XlxuMiIsInYiOjEsImkiOiIyXG4xIDIgMiAzXG4yIn0=)
Run for `1 2 2 3` with index `2` and value `2`:
[](https://i.stack.imgur.com/3YXtw.gif)
On the left we split the input lines with `;\ ^<` into the three paths.
The first one pushes two zeroes after `length of path + index` time steps into the `+`. The second one path tries to push the array into `+` – if there are values waiting (the two zeroes), they get passed through unaltered. Otherwise, they get deleted `?]`. The two values then get pushed into `=`, where they are compared to the third input. The result are two boolean bits. The second one gets multiplied by 2, then they get added together.
[Answer]
# Brainfuck, 43 bytes
`,>,[->,<],<[->->-<<]>[[-]>>++<<]>[[-]>+<]>.`
Arguments are taken in this order: value\_at\_index, index, array values.
Outputs are: 0-unknown, 1-zero indexed, 2-one indexed, 3-neither.
## How it works
```
, read value_at_index into first cell
>, read index into second cell
[->,<] read the array till the one indexed element is found and store it into third cell
, store the zero indexed element into second cell
<[->->-<<] substract value_at_index from both saved elements
>[[-]>>++<<] if the zero indexed element isn't equal to zero then add 2 to result
>[[-]>+<] if the one indexed element isn't equal to zero then add 1 to result
>. print the result
```
[Answer]
# [Haskell](https://www.haskell.org/), 27 bytes
```
(l%i)n=[l!!j==n|j<-[i,i-1]]
```
[Try it online!](https://tio.run/##hZBNCsIwEIX3nmK6EBqYgE36g2CO4AlCkFBaTU1DMV16dmPaILqRwgTmve8RHnPT/t5ZG0Ju94Y4IW2WDUK453Ci0qChhVJh7vx8abXvPAiQuWQIXCEUCIwg/Gq@6gWss7jskyoRqpQqmtWgPDqRplCVvKaMuYLzBqFkBwRaHyPn67KRiGrrj0hSF7ag35dKlOw/jsWrmqhdL/I92Y3auHiNUU9nmB7GzSB7sGDAwRNyiwYdOdHv5VR4tb3VVx9oO01v "Haskell – Try It Online")
Outputs a two-element list like `True/False`.
**28 bytes**
```
(l%i)n=[l!!i==n,l!!(i-1)==n]
```
[Try it online!](https://tio.run/##hZBBCsIwEEX3nmJcFBKYgE1ai2CO4AlKkVBaDaYhmC49u3HaILoRISHz//uEz1xNvA3OpcRcYbnXrdturdYe6WVWlJzmLs1DnM@9iUMEDS1rJYLqEEoEyRG@tVr1AtazuPKdqhDqnCqb1RCKHKI5VGevqShXKtUgVHKHIPYH4mod/iRI/fuDSO4iF/R9c4lK/sZUvN7zbjNqVvDNZKynbUwmnCDcrZ@hHcGBBQ8PYA4ten4Un8116dmPzlxiEn0ILw "Haskell – Try It Online")
**28 bytes**
```
(l%i)n=(==n).(l!!)<$>[i,i-1]
```
[Try it online!](https://tio.run/##hZBdCsIwEITfe4oVFBLYiE36g2C8gScoRUJpNRhDMX307MY0QfRFChvYmW8Iw16Vu/XGeE/MRlMriZSWbolZrehhfWw0apa3furddO6U6x1IaEjDEUSLkCNwivCrRdQziDO7/JMqEMqUyutoMBGcQFOoTF5dhFwuRI1Q8B0Cq/aBi7gsJIJa@iOQ1IXP6PelEgX/j0PxsqJtNkiyodldaRuucVfjCcaHthM0AxjQYOEJxKBGSw/se7nWv7rBqIvzrBvHNw "Haskell – Try It Online")
**29 bytes**
```
n?i=map(==n).take 2.drop(i-1)
```
[Try it online!](https://tio.run/##hZBBCsIwFET3nuIvE/gRm7QWweIJPEEpEmrV0BiD6dKzG38bit2IkEBm3hCGuenQd9bG6A6mumvPqsrx9aD7DuT6/Hx4ZkTG49CF4dTq0AWooGa1RFANQoYgOcJSq0mPYDqjK@dUjlCkVFZOhlDkEE2hInllTrlMqRIhlxsEsd0RV9PjT4LUvz@IpC5yRMubSuTyN6bixZY3qwtYMOBoCkazcbu6azMq2u8I/mncAPWceQGzaNDxvfiO2MR3e7H6GqJovf8A "Haskell – Try It Online")
[Answer]
# JavaScript (ES6), 30 bytes
Returns **0** for *neither*, **1** for *0-indexed*, **2** for *1-indexed* or **3** for *unknown*.
```
(a,i,v)=>a[i]==v|2*(a[i-1]==v)
```
[Try it online!](https://tio.run/##nZHfDoIgFIfve4pzqQ0yAXVd2Iu0LpxiUQ6albXWu9tBa2vmny0GG4x9349zOCRVck5LdbpQbTJZ53HtJESRyo3XyUZt47h6srmDW@rbg1unRp9NIReF2Tm5s2EE@JaAT4C5LvQMzwMwWlKlM3mX2WyQ58P8Q5ZmSGCTm2k1rOcZVnDVR21uussKAkEb7ke96ZbVUl32suyylCOMcW1q8ItPFE4jgfE@5xEBwZYEaLhCF2821jZV@LAATx/Bfw/AGxSMFC@YZb5X2wbx6f5Y0/tY/IIg/GLfufUL "JavaScript (Node.js) – Try It Online")
or **28 bytes** by outputting a pair of Boolean values:
```
(a,i,v)=>[a[i]==v,a[i-1]==v]
```
[Try it online!](https://tio.run/##nZFNDoIwEEb3nmKWkExV2gJxgRchLIgUrZLWoKLx8jgVTYzyk0hoWtK8980M@7zJT5taH8/M2EK1ZdJ6OWps/GSd5qnOkqRB2lngTlm7seZkKzWv7NYrvZQjiAwhQOC@Dz3PYgFgjWLaFOqmitkgL4b5u6rtkMAlP1@n4T1lOMHFHIy9mm9WIoRdeBD3pjvWKH3eqfqbZYJgiutSw198onEWS4oPhIgRJF8isGhFLvE8ONtU48MC@noL/iuAbkgw0rzkjvlc3Rjke/pjQ@9j6ReE0Qf7ym0f "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
+.ịẹ⁵
```
[Try it online!](https://tio.run/##ASUA2v9qZWxsef//Ky7hu4vhurnigbX/w6fFkuG5mP//Mf9bMiwzXf8y "Jelly – Try It Online") or [see the test cases](https://tio.run/##y0rNyan8/19b7@Hu7oe7dj5q3Pr/4c5VEO6ORdVAIa7Dy5WOTnq4c8b//9FcnNHRRjrGsToKhrE6nJycygrRhrGcGvl5qQqZeSmpFakpmliUGAGVVKUW5aOoMdQx0oGoM4IbpQNSWZqXnZdfngdWZKJjimwQUDYvNbMkI7UILKtrrGMK1IJsAhbH6JqbmADNMDY211EwMTLQUdA1swTqAdqM0234tZBuCZq7TYxAipAx1A/YwwCbakNMg2P/A4MTGKSG5sBQAVqvA3IH2F1AXaZmAA) (slightly modified to run as a function)
Full program, takes input as `index`, `array`, `value` on the command line.
Outputs `[1]` for one-indexed, `[2]` for zero-indexes `[1, 2]` for unknown and `[]` for neither
## How it works
```
+.ịẹ⁵ - Main link. Takes index on left and array on right
. - Yield 0.5
+ - Add to index
ị - Yield [array[index], array[index+1]]
ẹ⁵ - Return the indices of the value in that array
```
[Answer]
# x86 (with MMX) machine code, 9 bytes
(Same machine code works in 64-bit and 32-bit modes; 16-bit mode doesn't have scaled-index addressing modes.)
2 boolean compare results from `array[index-1] == element` and `array[index] == element` can be concatenated to produce a 2-bit return value: one or the other set means we can tell that it's 0 (first) or 1 (second) indexed. Neither set means "neither", both set means "unknown". Apparently we don't consider it ambiguous if the expected element is also present somewhere else in the array; "neither" is only a fallback that we don't have to consider if 0-indexed or 1-indexed explains the observation.
So we only need to look at 2 elements at `index-1` and `index`, e.g. with a packed-compare of those 2 elements in parallel. That's exactly what [MMX `pcmpeqd mm1, mm2/m64`](https://www.felixcloutier.com/x86/pcmpeqb:pcmpeqw:pcmpeqd) does.
Array pointer in EDI/RDI, index in EDI/RSI, expected element in mm0 (in the low 32-bit element), retval in mm0
```
line offset machine NASM source
# code
1 compare_at_index:
2 00000000 0F62C0 punpckldq mm0, mm0 ; broadcast expected
3 00000003 0F7644B7FC pcmpeqd mm0, [rdi + rsi*4 - 4] ; compare integers at array[i-1, i]
4 00000008 C3 ret
size = 9 bytes
```
Return values, as a SIMD vector of 2 32-bit dword elements `[low, high]` (shown in memory order, not Intel's usual notation of highest element first):
* `[-1, 0]` means 0-indexed, only the first matched
* `[0, -1]` means 1-indexed
* `[-1, -1]` means "unknown"; both matched
* `[0, 0]` means "neither"; neither matched
(Untested but I'm confident this works, and writing a test harness would be significantly more work for asm. SIMD packed compares are a pretty normal thing to work with.)
If you wanted to compact that return value into a scalar integer bitmap, that costs 3 bytes for [`pmovmskb eax, mm0`](https://www.felixcloutier.com/x86/pmovmskb) (`0F D7 C0`) which would give you a `0x0F` / `0xF0` / `0xFF` / `0x00` result in EAX.
(If this was an XMM register, we could use `movmskps` to get 1 bit from each 4-byte element, instead of 4. Or `movmskpd` to get 2 bits total from a 16-byte vector. But SSE2 instructions on XMM registers are 1 byte longer than MMX, so even using 64-bit array elements wouldn't let us keep the code-size the same. Also, SSE2 would require a 16-byte memory operand to be aligned unless you use a separate `movups` load instruction, although AVX allows `vpcmpeqq xmm0, xmm0, [rdi+rsi*8-8]` with no alignment requirement.)
Most standard calling conventions expect you to use `emms` after using MMX registers, but I'm considering a hypothetical system where it's normal to pass around integers in MMX registers, never returning the FPU to x87 mode.
If you wanted the expected-element to arrive in an integer register, say EDX, you could use `0F 6E C2` `movd mm0, edx` before punpckldq. Unfortunately, `vpbroadcastd xmm0, edx` requires AVX512 with its longer EVEX encoding, and only works for 16-byte XMM registers not 8-byte MMX. If we took the element as a stack arg, `pshufw mm0, [rsp+8], 0b0100_0100` is 6 bytes total, same as movd+punpckldq. 2 register args with the rest on the stack is a pretty normal calling convention, especially for 32-bit mode (e.g. `__fastcall`, but that would want `ret 4` callee pops. So maybe `gcc -m32 -mregparm=2` with `[esp+4]`). Not that we need to justify our calling convention as being a standard one.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
xE,@QJE@QtJ
```
[Test suite](http://pythtemp.herokuapp.com/?code=xE%2C%40QJE%40QtJ&test_suite=1&test_suite_input=%5B2%2C3%5D%0A2%0A1%0A%5B2%2C3%5D%0A3%0A1%0A%5B1%2C+2%2C+2%2C+3%5D%0A2%0A2%0A%5B4%2C5%5D%0A17%0A1%0A%5B-3%2C+5%2C+2%5D%0A5%0A2%0A%5B-744%2C+1337%2C+420%2C+-69%5D%0A-69%0A3%0A%5B-744%2C+1337%2C+420%2C+-69%5D%0A420%0A3%0A%5B-744%2C+1337%2C+420%2C+-69%5D%0A-744%0A3%0A%5B42%2C+42%2C+42%2C+42%2C+42%5D%0A42%0A2%0A%5B42%2C+42%2C+42%2C+42%2C+42%5D%0A56%0A1&debug=0&input_size=3)
---
Takes input in the form:
```
list
value
index
```
Translation of [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)['s Jelly answer](https://codegolf.stackexchange.com/a/219851/78186).
[Answer]
# [R](https://www.r-project.org/), 26 bytes
```
function(a,i,n)a[0:1+i]==n
```
[Try it online!](https://tio.run/##hY7BCsIwDIbvPkWOLaawJu2K4p5EPIxBoZcKos9f02WIXhykkH7/R/gfLcPFtfyqy7Pcq5mxYLXzdTj7Y7lNU23ZLIYQ2CJ4BLKHX8AKerROx/TxAkJUzycljgX1fNXiBlMQ0zMnhEADghtPIrAuO4r8dq9IshWinn0/LRLoTy7142jbGw "R – Try It Online")
Inputs array `a`, index `i`, value `n`.
Outputs a boolean pair: `F T = 0`, `T F = 1`, `T T = unknown`, `F F = either`.
Full program for the same byte count, inputs in the order of `i n a` merged into a single vector:
## [R](https://www.r-project.org/), 26 bytes
```
a=scan();a[2:3+a[1]]==a[2]
```
[Try it online!](https://tio.run/##hY5LCsMgEED3PcUsHTqB6piEfjxJcCFCIBsL/axKz27HGELpogEF572HzC2PcGlgfKb4mK5JBZoo0T2G5FaGURUYEOGVgytS4TkM5sT7MGjvnZPB5/duVFEZAkYCTWDwB3AFRc2nYLN2lqCtne4raVhQ8XPWLrC3UmrmnsCaA0HTHSXg@thIZNr8RcyykCnu@9ZFrPnjZf22w/wB "R – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~15~~ 13 bytes
Saved 2 bytes thanks to Kamil Drakari
```
{⍵=⍺⍺[⍺,⍺+1]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71bbR/17gKiaCDWAWJtw9ja//@NFTQOrTc3MVEwNDY2VzAxMlA4tN7MUiFNE0I/6p2rEJValK@bmZeSWpGawmUEUm@sYKpgBFJjqoACQKr981LhioGGmxgpICOgHiAJUxual52XX56HXZ2pGVydX2pmSUZqEQA "APL (Dyalog Unicode) – Try It Online")
Call it with `index (array f) value)`. Returns `0 1` if it's zero-indexed, `1 0` if it's one-indexed, `1 1` if it's unknown, and `0 0` if it's neither.
```
{⍵=⍺⍺[⍺,⍺+1]}
[ ] ⍝ Index into
⍺⍺ ⍝ the array (the left operand)
⍺ ⍝ at the given index (the left argument) (one-indexed)
, ⍝ and (parentheses would have been better, but , saves a byte)
⍺+1 ⍝ index+1 (zero-indexed)
⍵= ⍝ Compare the value (right argument) to this 2-element vector
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
tQh)=
```
Inputs are: index, array, value. Outputs are `1 0` for one-indexed, `0 1` for zero-indexed, `1 1` for unknown, `0 0` for neither.
[Try it online!](https://tio.run/##y00syfn/vyQwQ9P2/39DrmgjHQXjWC4jAA) Or [verify all test cases](https://tio.run/##y00syfmf8L8kMEPT9r9LyH9DrmgjHQXjWC4jLjjTGMiJNtRRMAIjmJyJjoJpLJehOUhS1xjIAcrGcpkCVUfrmpsAZQ2Njc11FEyMDHQUdM0sY7mABG5JIAuPTqAoyBoTI5AoMgZpBDsGi4ypGQA)
(Also for 5 bytes: `FT+)=`).
### Explanation
```
t % Implicit input: index. Duplicate
Q % Add 1
h % Concatenate
) % Implicit input: array. Apply index
= % Implicit input: value. Test for equality. Implicit display
```
[Answer]
# [Perl 5](https://www.perl.org/) -`apl`, 40 bytes
```
$_=1*($F[$i=<>]!=($t=<>)).($F[$i-1]==$t)
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tZQS0PFLVol09bGLlbRVkOlBMjQ1NSDCOoaxtraqpRo/v9vpGDMZchlxAWhjblMjBSQEFDCxAhTzNTsX35BSWZ@XvF/XV9TPQNDg/@6iQU5AA "Perl 5 – Try It Online")
Input is on three lines:
```
Space separated list of numbers
index
target value
```
| Output | Meaning |
| --- | --- |
| 0 | Zero-indexed |
| 11 | One-indexed |
| 01 | Unknown |
| 1 | Neither |
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
```
gVôJ)®¥W
```
[Try it online!](https://tio.run/##y0osKPn/Pz3s8BYvzUPrDi0N//8/2lBHwQiMjGMhLAA "Japt – Try It Online") or [check all test cases](https://tio.run/##lU9LCsIwEN33FLMVJpBJ0hYpXsCdi5hCyMKFFATBhVfq1pUnqAeLkzZCrSIIyWPC@@TN6XC5xsJ21LiN7VTTMurGMsrY7R/37Wq4Db2L7dFFX3ivEHRAIEBQwACeUIaA75SeKIk0UcTq8SSBmnuzwCCU2Uv1y5xzhWaSLdlaLr4VtWE3aV0jGCURRLUOqcI4LYr8EPPzj2SmFjWNSqr5zYXNx7LflGn1spplFgHEefcE)
Outputs `[true, false]` for one-indexed, `[false, true]` for zero-indexed, `[true, true]` for unknown, and `[false, false]` for neither. Takes inputs in the order `array, index, value`.
Explanation:
```
gVôJ)®¥W
Vô # Create an array starting at input 2...
J) # ...And ending -1 integers later
g # Get the values from input 1 at those indices (0-indexed)
® # Replace each value with:
¥W # Is it equal to input 3?
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~42~~ 40 bytes
Saved 2 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!!
```
f(l,i,e)int*l;{e=l[i]==e|2*(l[i-1]==e);}
```
[Try it online!](https://tio.run/##jZRtj5swDMff8yksJCToBY1nyji2F9M@RYumioZbNMZVTaVV6/jqYwmJKWQ96RBExv@fY@o6bvyXphnH1u0II9Rj/WXTlTdadTtWVxX9E21cYfqhfPHKYTy5E0LECtyDmwXial/PIP3AqqAE9sxLeHpi3qTJ63QWYuvaDneONnHZZ5uA/dG2PQIyj1dagyXDfx5Y73qW2lQ6LpRfvnXBroYKbhGBeCgX/vANf6T8IYFoutdqrNSEQLryJ8rvx0IQYSst1VqeiLAwjnMCSRQQ8LNixWXv5PJ3clv9rZHUl8@KKt6msJIbjSpSl5VgHdGI0IjRSNBI0cjQyNHYolHc8ykP1/k4@01fW1en9T7o9w06CKyI0CRCk4hMIjKJ2CRik0hMIjGJ1CRSk8hMIjOJ3CRyk9iaxNYkCpMoPLPSbG551fVqjfGWHjOE3k@PAvKp8UULYjNO3Sk7Kc0WwfR6os2FHufwcNohWOQNlEcHNd8P541YafODnlWUvb9@jfbX4ot4UjkMFu@xrePuU6U/0qsIk7NlMp@xPvgt9wLNnmkESRqH1HwSOrGVPg0TUJdLHRjK7KFMUaYPZS5kHKZrpcdA/jiv/IVzbU0AJ@jOXux6Enl673@o3jlHUeYKnCP4n@Tq8H0vyswIUNFbZP4zeFVda73DYA3j36btDi989H/9Aw "C (gcc) – Try It Online")
Inputs a pointer to the array, the index, and the test element.
Returns \$2\$ for \$1\$-indexed, \$1\$ for \$0\$-indexed, \$3\$ for unknown, and \$0\$ for neither.
[Answer]
# Java, 44 bytes
```
a->i->v->a[i]==v?a[i-1]==v?1:2:a[i-1]==v?3:4
```
Returns:
* 1, if unknown
* 2, if zero-indexed
* 3, if one-indexed
* 4, if neither
[Try it online!](https://tio.run/##rY4/T8MwEMX3fIobE5Skyh@EZNMgFiQGxFAxRRlM6hS36TlyLqlClc8eTAntxIDgZOnePZ9/flvRi2C73k1q32hDsLVz2JGqw6rDkpTG8Io7TtO91qqEshZtC09C4dEBW7PdkiDbeq3WsLeX7oqMwk1egDCb1vva/ayHmXmrkPLCh0eks2X1CwozPDfSCNImy6BaTiLIVJD1QSZyVSyX/Z3tQXRSEYvZZUpYOvHzR4tFxKDDHeoDcogZvEujOSQMNEoOKQOUit6kOb9YDS3Jfag7Chsbnmp0q1A0TT24KA9wCnyM/WT0ZjeaxX1rk7ux5/H/YiW/ZkU@xKdzQcZ/jJf61z/Ei26@YaMzTh8)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 38 36 35 bytes
Takes three arguments: the array to index into, the index to test, and the number to test for. Outputs 0 or 1 for 0 or 1 based indexing, respectively, outputs 0 and 1 for unknown, and outputs nothing for neither.
```
param($a,$b,$c)0,1|?{$a[$b--]-eq$c}
```
[Try it online!](https://tio.run/##tZPRaoMwFIbvfYog2aY0lkZty5AwoWywm22svSulqEtZi1ZnlA2sz@6SqG0v5oSOBSXJye93/hw5SfxJU/ZOw7CCG6IAPooq8VIv0qCHoI9goI8QPtwV0FtC3zBWBv2AQVkJZanAjLJs5jHKAAGuJr93CzmJsd0neSYW4tDVTAQsHWFk6kcF/UpokNE3qcB1vET9CKsDMepHYARM@XCQ2emFX7ofZSMwFm7wtIPSjzAszuB2hJfx5XUxpjY3gy1rioBtjhAwJrc6spCYLq5UF5Sv/8Epj19cRdsUsPNX1NP@28/9gYnRePK7SUVX4II3BSMidOqPw1UhN0955NOU4LLOC2VSBFsUgethE1oP22CtTCnLw4zn0q7hBrhSVSeFLA8CyhhRG5HKm1Q9MtVaJF0NyPJlPstZFkfP/o4fr9ziRpzckDN7g4Ezb5At23kU@YhWG@a3UZdQg2tjF2/3KgKqvlJL/bhzXqWPkyHnvr3gma9SKZtiHR7iNPIyY@H5Ia2@AQ "PowerShell – Try It Online")
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 33 bytes
This version has completely unintuitive output, but still works. Outputs 1 for 0-based, 0 for 1-based, 0 and 1 for neither, and nothing for unknown
```
param($a,$b,$c)0,1|?{$c-$a[$b--]}
```
[Try it online!](https://tio.run/##tZNda8IwFIbv@ytCyWaLJ2I/VEYJK8gGu9nG9E5E2i4yxa81LRvU/naXpK16sdKhLLQkOefte56ckt32i8X8g61WBzynGhIjO@yCOFgbOAAcAo7MLlj7@wxHBAcTHBIyzQ9Sl2s4YTwZBpxxRJFvqK/9TE1yLDa7NJELmfQNG5BjggW2eVSw7x2LEvauFN0inkOzhVNjYTVbWIBs9Qgju5al2ccF1JMo1qDuOPAHGuIIG4EjWXqX94UMXMFjOc4AkGt3AZH@nQkOyOniTtWZivU/kIr4NY10bel3/sqWulf8318MLej1GyE1U8NjcS84lWVOV2R/k6nNc7oOWUytvCiNVV3AlRvFs04ZmnWqYKGMGU9XiShn3OI58pWqKIp5GkWMc6qXIp2wT/3oqRciRdWmk9fRMOXJdv0SLkV66mctmWnRM7x22xuVlpW39yTrUaMAFqfRJ9jAM7LcLjY6IN2c6rl53HlviuME5D1UBzzjyrW8bNb@cRuvg4SMg3DFDj8 "PowerShell – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes
```
E²⁼ζ§θ⁻ηι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDSEfBtbA0MadYo0pHwbHEMy8ltUKjUEfBNzOvtFgjQ0chUxMErP//j47WNTcx0VEwNDY211EwMTLQUdA1s4zVUTAG82L/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Output key:
```
Neither 0-indexed 1-indexed Unknown
- -
- -
```
Explanation:
```
² Literal `2`
E Map over implicit range (i.e. `0`, `1`)
η Second input
⁻ Subtract
ι Current value
§ Indexed into
θ First input
⁼ Equals
ζ Third input
Implicitly print
```
[Answer]
# [J](http://jsoftware.com/), 13 bytes
```
1 :'=u{~],<:'
```
[Try it online!](https://tio.run/##hY9BS8NAFITv@RWDl00hCdndpMHF9aDgSTyItxJKaF9ppSbSjSAK/vX4Nk0gpUVh9x1mvpl9@9pdJWIDayAQIYXhGye4f3586CSMsB/fP2V0Y0Q3C57uEixUBF0uZAlrocDzFmhqinf1mj5p3UOSSyy@6NCcyCkb9gLs1VVVixYt7fcD6htq2rVbOgQBrbYNxAu5lkFHznDmjara4b1yTgyA748NbxUqaGxmkEfdr8O6PtdHXvIYPDV29RlZIMyQT0LDIznCpeapJpnhneX8ms0iyyC1LpCptJeY0ycV3viHO/Z55E9QjoW8rML0nH0on19iZPcL "J – Try It Online")
Thanks to [user's APL answer](https://codegolf.stackexchange.com/a/219861/15469) for suggesting the idea of using a J adverb to emulate a 3-argument function
The solution is an adverb `f` that operates like this:
```
<expected value> (<array> f) <index>
```
Return value key:
```
1 0 = zero-indexed
0 1 = one-indexed
1 1 = can't tell
0 0 = neither
```
* `=` Does the expected value equal...
* `],<:` The index, catted with "index - 1"
* `u{~` Both taken from the given array? (In J, within an adverb definition, `u` is the canonical name given to "the noun or verb being modified")
[Answer]
# [Python 2](https://docs.python.org/2/), 32 bytes
```
lambda l,i,n:[l[i]==n,l[i-1]==n]
```
[Try it online!](https://tio.run/##hY9NCoMwEIXXeoosFUYwPyoVcpI0C0srBmwqYik9fTpOilho6SJk8t43bybTcxluXoReH8PYXU/njo3gwLdmNM5q7QHvgq@VDY/BjRfG2zQhBmbt/HRfsjxNptn5hfUZGTmwOWRGAJMWGAeGleE2T/eaRK0kLQJvJ1amRIZMBayKDbxBnbQCeyvkIl5t4UWjEOdSIqkERhT1wdIkLLZxvyl6/c8iJ26ixOruT9xJff7hG4U/qmrKeQE "Python 2 – Try It Online")
Outputs a two-element list of Booleans for whether 0-indexing and 1-indexing are consistent with the input.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~25~~ 24 bytes
```
Sign[#2[[#;;#+1]]-#3]^2&
```
[Try it online!](https://tio.run/##hY6xCsIwFEX3fkUg0MUXMC9pSylKP0FwDBGKWO3QDtIt5NvjS6KggwoJ5N5zCHce1ttlHtbpPIRxF47TdTEcjeFdxzfSWsGVPWEZDvdpWY3j3Iv9SAZwIGLLvu9d4RwCUx6YBIYePrJKOYJ0YosvSwOrsiWbVAhFTaJRqnLXaPKkUg0wjVtgom6Jq@fjp0Hp3x9E8haM6P3mERq/Yxpe1b7w4QE "Wolfram Language (Mathematica) – Try It Online")
Input `[index, array, value]`. Returns `{0,1}` for 1-indexed, `{1,0}` for 0-indexed, `{0,0}` for both, and `{1,1}` for neither.
[Answer]
# [jq](https://stedolan.github.io/jq/), 22 bytes
Inputs as: `[index, array, value]`.
Output key: `true,false` for 1-indexed, `false,true` for 0-indexed, `true,true` for unknown, `false,false` for 0-indexed.
```
.[1][.[0]|.-1,.]==.[2]
```
[Try it online!](https://tio.run/##yyr8/18v2jA2Wi/aILZGT9dQRy/W1lYv2ij2//9oQ51oIx0F41gdo1gA "jq – Try It Online") or [Try all testcases!](https://tio.run/##fU47DsMwCN17Cg7wjALYsTrkJIgLdOueuzu4qZQOVSRAvJ/g9R6DXcLZl9i5CDi2jV1jDBe4giyg8biAJVAkJv3UpVdQC0g/DcUSpiPQkrAkek2HmHVQ1QVU1mdgjhs5t9t0sue5qpP/7Rn@PvZHa2sc)
## Explanation
```
.[1] # Index the array by the indices:
[.[0] # * The index
|.-1,.] # * Prepended with the index - 1
== # Vectorizing equality:
.[2] # With the value
```
[Answer]
# [Rust](https://www.rust-lang.org/), 31 bytes
```
|a:&[_],i,v|(a[i]==v,a[i-1]==v)
```
[Try it online!](https://tio.run/##jZHfasIwFMav16c480IaSGVNqjKlgzF8Ar0rRYqmGFZTSVM3/PPs3UmEtU4HhsJJvu93Tr82uq5MsypVZWAxmy@WH@/z2XwC/cTvJ5KzlEJdyYOggAeSQoyOB7jQZhQ4@iEFRuityFvRIu6xFrviIwrDCx@OWzXgKCN3wYcdYxxhR8j5mELEXigEo1eEuNs8guHpoWnodEKyqUvJLHYrY/jhCOV06nm5gm0mlU/g6LBCGMghbk7ZpJ8sUyrp/uRniUzjeE@xBqHdkcay2G5LXmrwM/zjFPYEpOpczEAaoX0yWJU7Kda/L7Frm5nVBvK28eg9uZx5VlR4f64QiN9gp6UyhXr2e0pIsxG6h9mvWKPrv2ipRCDVWnyLdYtb7v7kg9Dlf/yd6bX6VOWXcuTZfdLZOzc/ "Rust – Try It Online")
Port of [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/219850/85922). Returns
```
(false, false) => "neither"
(false, true) => "one-indexed"
(true, false) => "zero-indexed"
(true, true) => "unknown"
```
I had to include the `:&[_]` part for the code to compile, but I have the feeling that it can be optimized somehow.
[Answer]
# [Julia](http://julialang.org/), 18 bytes
```
l*i*r=l[i:i+1].==r
```
[Try it online!](https://tio.run/##jVFLTsMwEN37FKOIRVImVRwnjUAye84QskDUFQbLqRJXVFwDiRWn4yJhJrVEC0XCsuWZ997M8@dp5@y93E@TW9jFoF1rr@2l7JZaD1PvDWhoJRadeDVDz0mBshM7/@z7F38gKffGhkczHHgSi2DGMHIq0rZEUB1KLDMAfQNAXY9QFVHuT7BEKOdJJAeRjYYkqBBqrpNNpKI3Ubkijmq4sj4xy5uK6qRSDUJVFgj56qpDhbSd2v8lpPh/DQn/da6qZNHx4hNWZ@52RiixXv3oSO@76QdIA5oMrIf5sQXQcGiRfyHMGUe3PizT@WuzGbMbhjWYOeOxHawPzqfJ58cbJAiBvaLauPGs8P1biJDchdTst@YhmDVcmCyJtX4teE1f "Julia 1.0 – Try It Online")
overloads the `*` operator, expecting `array*index*result`
Outputs `[1,0]` for one-indexed, `[0,1]` for zero-indexed, `[0,0]` for neither and `[1,1]` for unknown
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 11 bytes
```
~].~==\~(==
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/vy5Wr87WNqZOw9b2/39Dc4VoEwXTWAVDAA "GolfScript – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 30 bytes
```
->(a,i,v){[a[i]==v,a[i-1]==v]}
```
returns:
* `[true, false]`, if zero-indexed
* `[false, true]`, if one-indexed
* `[true, true]`, if unknown
* `[false, false]`, if neither
[Try it online!](https://tio.run/##lZDfCoIwFIfve4oD3SicRW5T6cJeRLywnCTFDEn7R8@@ztRIaF40Nraxfefjd5p2dzdlYtjWy7HCzn@meVplSdIh7Sywp@xlzl652uenk5dyBJEhBAjc98ExlgC1VqzShbqpYuEixSz5UE3tQK2tn7YAd6gJbfVR11c9oSRCOAiD2GkkSqvqclDNhGKCMFIMpvAXnA3IYknKQIgYQfI1Aos2VEX0B1tnPuA8SrcR/VtKL4Q6Q0puf0/XEFd@OutuqIui9obRlxpd5g0 "Ruby – Try It Online")
] |
[Question]
[
A number is a de Polignac number if and only if it is **odd** and *cannot* be represented in the form **p + 2n** where **n** is a non-negative integer and **p** is a prime integer.
# Task
Write some code that takes a positive integer and determines if it is a de Polignac number. You may output two distinct values one for true and one for false. You should aim to minimize your byte count.
# Test Cases
[For positive cases here's the OEIS](http://oeis.org/A006285)
```
1, 127, 149, 251, 331, 337, 373, 509, 599, 701, 757, 809, 877, 905, 907, 959, 977, 997, 1019, 1087, 1199, 1207, 1211, 1243, 1259, 1271, 1477, 1529, 1541, 1549, 1589, 1597, 1619, 1649, 1657, 1719, 1759, 1777, 1783, 1807, 1829, 1859, 1867, 1927, 1969, 1973, ...
```
Here are some negative cases:
```
22, 57
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~9~~ ~~14~~ 13 bytes
```
o!²mnU dj |Uv
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=byGybW5VIGRqIHxVdg==&input=MTI3) or [Find all de Polignac integers under 1000](http://ethproductions.github.io/japt/?v=1.4.5&code=MTAwMG8gZlV7IShVdiCqVW8hsm1uVSBkag==&input=).
Outputs `1` for falsy inputs and `0` for truthy.
### Explanation
```
o!² mnU dj |Uv
Uo!p2 mnU dj |Uv : Ungolfed
: Implicit: U = input integer (e.g. 9)
Uo : Create the range [0..U), and map each item X to
!p2 : 2 ** X. [1, 2, 4, 8, 16, 32, 64, 128, 256]
m : Map each of these powers of 2 by
nU : subtracting from U. [8, 7, 5, 1, -7, -23, -57, -119, -247]
d : Return whether any item in the result is
j : prime. (5 and 7 are, so `true`)
| : Take the bitwise OR of this and
Uv : U is divisble by (missing argument = 2).
: This gives 1 if U cannot be represented as p + 2^n or if U is even.
: Implicit: output result of last expression
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes
*Saved 1 byte thanks to @Dennis*
```
Ḷ2*³_ÆPS<Ḃ
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef//4bi2MirCs1/DhlDCrDvhuILhuqD///8xMjc "Jelly – Try It Online")
### How it works
```
Ḷ2*³_ÆPS<Ḃ Main link. Argument: n (integer)
Ḷ Lowered range; yield [0, 1, 2, ..., n-1].
2* Reversed exponentiation with 2; yield [1, 2, 4, ..., 2**(n-1)].
³_ Reversed subtraction with the input; yield [n-1, n-2, n-4, ..., n-2**(n-1)].
ÆP Replace each item with 1 if it is prime, 0 otherwise.
S Sum; yield a positive integer if any item was prime, 0 otherwise.
Ḃ Yield n % 2.
< Yield 1 if the sum is less than n % 2, 0 otherwise.
This yields 1 if and only if the sum is 0 and n is odd.
```
[Answer]
# JavaScript (ES6), ~~56 54~~ 53 bytes
Returns \$0\$ or \$1\$.
```
f=(n,p=1,x=y=n-p)=>n>p?y%--x?f(n,p,x):x!=1&f(n,p*2):n
```
[Try it online!](https://tio.run/##HYyxDsIgFEX3fgUOGp4ppHVs8tq4OujgaByaCg1KHgQaA1@PreM95@S@x@8Yp2D8Isi9VCkaOdUe2zphRhIesKfeD3kvRBr05uoEXdphe/iv4wk6KpOj6KyS1s28Yuxyv11lXIKh2ei8EcYeUspzCGPmbdM0ID8qRw5PqY1dVODEsGfrI8BaQwXlBw "JavaScript (Node.js) – Try It Online")
### How?
We start with \$p = 1\$. We test whether \$y = n - p\$ is composite and yield a boolean accordingly. The next test is performed with \$p \times 2\$.
As soon as \$p\$ is greater than \$n\$, we stop the recursion and return \$n\$.
The results of all iterations are AND'd together, coercing the boolean values to either \$0\$ or \$1\$.
Provided that all intermediate results were truthy, we end up with a bitwise test such as:
`1 & 1 & 1 & n`
This gives \$1\$ if and only if \$n\$ is odd, which is the last condition required to validate the input as a de Polignac number.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~60~~ ~~57~~ 56 bytes
```
f=lambda n,k=1,p=-1:k/n or(n-k&n-k-p%k>0)&n&f(n,k+1,p*k)
```
[Try it online!](https://tio.run/##FcoxDgIhEEDRGk4xjQQUIlhuwp5lMC5K0IGwNJ6eZYtf/Vf//VPoMUb03/B7vgKQzt7p6o1b8p2gNEkmi5mpl7xaJUhEOdFtomtWI5YGBImgBXpv0mlw1lq1cBb2fWsdcHKFp5BoUQM6VJyzFOEc07HaEnWgcQA "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*An alternative 10-byte Jelly submission to the one already posted.*
```
_ÆRBS€’×ḂẠ
```
A monadic link returning **1** for de Polignac numbers and **0** otherwise.
**[Try it online!](https://tio.run/##ASEA3v9qZWxsef//X8OGUkJT4oKs4oCZw5fhuILhuqD///8xMjc "Jelly – Try It Online")** or see [those under 1000](https://tio.run/##y0rNyan8/z/@cFuQU/CjpjWPGmYenv5wR9PDXQv@n9h@uB0oFPIfAA "Jelly, test suite – Try It Online").
### How?
```
_ÆRBS€’×ḂẠ - Link: number, n e.g. 1 3 5 6 127
ÆR - prime range [] [2] [2,3,5] [2,3,5] [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127]
_ - subtract from n [] [1] [3,2,0] [4,3,1] [125,124,122,120,116,114,110,108,104,98,96,90,86,84,80,74,68,66,60,56,54,48,44,38,30,26,24,20,18,14,0]
B - convert to binary [] [[1]] [[1,1],[1,0],[0]] [[1,0,0],[1,1],[1] [[1,1,1,1,1,0,1],[1,1,1,1,1,0,0],[1,1,1,1,0,1,0],[1,1,1,1,0,0,0],[1,1,1,0,1,0,0],[1,1,1,0,0,1,0],[1,1,0,1,1,1,0],[1,1,0,1,1,0,0],[1,1,0,1,0,0,0],[1,1,0,0,0,1,0],[1,1,0,0,0,0,0],[1,0,1,1,0,1,0],[1,0,1,0,1,1,0],[1,0,1,0,1,0,0],[1,0,1,0,0,0,0],[1,0,0,1,0,1,0],[1,0,0,0,1,0,0],[1,0,0,0,0,1,0],[1,1,1,1,0,0],[1,1,1,0,0,0],[1,1,0,1,1,0],[1,1,0,0,0,0],[1,0,1,1,0,0],[1,0,0,1,1,0],[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[1,0,1,0,0],[1,0,0,1,0],[1,1,1,0],0]
S€ - sum €ach [] [1] [2,1,0] [1,2,1] [6,5,5,4,4,4,5,4,3,3,2,4,4,3,2,3,2,2,4,3,4,2,3,3,4,3,2,2,2,3,0]
’ - decrement [] [0] [1,0,-1] [0,1,0] [5,4,4,3,3,3,4,3,2,2,1,3,3,2,1,2,1,1,3,2,3,1,2,2,3,2,1,1,1,2,-1]
Ḃ - n mod 2 1 1 1 0 1
× - multiply [] [0] [1,0,-1] [0,0,0] [5,4,4,3,3,3,4,3,2,2,1,3,3,2,1,2,1,1,3,2,3,1,2,2,3,2,1,1,1,2,-1]
Ạ - all truthy? 1 0 0 0 1
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes
-1 byte thanks to Emigna
```
Ýo-pZ¹È~
```
Outputs `0` for truthy inputs and `1` for falsy inputs.
[Try it online!](https://tio.run/##MzBNTDJM/f//8Nx83YKoQzsPd9T9/29oZA4A "05AB1E – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 99 bytes
```
lambda n:n&1-any(n-2**k>1and all((n-2**k)%j for j in range(2,n-2**k))for k in range(len(bin(n))-2))
```
[Try it online!](https://tio.run/##RclBDoIwEAXQq8wGM0PsohN0YSInYTMEqoX6IQ0bTl80IXH73rpv7wVawrMryT79YIQHLt4ZdobTup5bbxjIUuITpJooLJkmiqBseI2s17PkF/M/0gjuIxgiTkXKmiM2Dqx39c3tCwc "Python 2 – Try It Online")
-4 bytes thanks to Leaky Nun
-2 bytes thanks to Wondercricket
+8 bytes to fix a mistake
-1 byte thanks to Mr. Xcoder
-3 bytes thanks to Einkorn Enchanter
+12 bytes to fix a mistake
[Answer]
# Regex (ECMAScript), 97 bytes
This problem posed an interesting case for working around the problem of lacking non-atomic lookahead. And it's the only time so far that I've had a good reason to put both versions of the power of 2 test, `((x+)(?=\2$))*x$` and `(?!(x(xx)+)\1*$)`, in the same regex, and the only time so far I've needed to protect the prime test against matching 1, as `(?!(xx+)\1+$)xx`, when used in a larger regex.
`^(?!(xx)*$|(x+)((?!(xx+)\4+$).*(?=\2$)((x+)(?=\6$))*x$|(?!(x(xx)+)\7*$).*(?=\2$)(?!(xx+)\9+$)xx))`
[Try it online!](https://tio.run/##TY/LbsIwEEV/BaIIZpImJBGlKq5h1QUbFu2ytJIFJnFrHMs2kPL49tRRhcRuZs65Gt1vdmB2bYR2idViw82uVj/8tzVU8WPvjZevjQY40dkoar9g3oemwSi8QBMj/K8xrsZxiGkEc7oqQn/umJ8nIWLUeLfTupw3n6J785Z/9nnPsY1GJ0xd/e6MUCVgaqVYc5g8JGNEYmlGjpWQHEBSw9lGCsUBsU/VXko8l1SmVkvhYJgMkYgtgKJlKrkqXYWz4nIRdsmWIKhmxvKFclB@ZJ@IN8DvgZrl83zaYXSVqY/BQh2YFJueYark014QS7KtDRDxQjkRcYz@YdAEqeGaMwcC0x1z6woM4tkOBtpXctC1yIneO@uMV8j12mZJXjxmfw "JavaScript (SpiderMonkey) – Try It Online")
```
# For the purposes of these comments, the input number = N.
^
# Assert that N is not the sum of a prime number and a power of 2.
(?!
(xx)*$ # Assert that N is odd.
|
# Since we must cycle through all values for a number X and a corresponding number
# N-X, this cannot be in an atomic lookahead. The problem then becomes that it
# consumes characters. Thus we must let X be the larger of the two and N-X be the
# smaller, and do tests on X followed by tests on N-X. We can't just test X for
# being prime and N-X for being a power of 2, nor vice versa, because either one
# could be smaller or larger. Thus, we must test X for being either prime or a
# power of 2, and if it matches as being one of those two, do the opposite test on
# N-X.
# Note that the prime test used below, of the form (?!(xx+)\2+$), has a false match
# for 0 and 1 being prime. The 0 match is harmless for our purposes, because it
# will only result in a match for N being a power of 2 itself, thus rejecting
# powers of 2 as being de Polignac numbers, but since we already require that N is
# odd, we're already rejecting powers of 2 implicitly. However, the 1 match would
# break the robustness of this test. There can be de Polignac numbers of the form
# 2^M+1, for example 262145 and 2097153. So we must discard the 1 match by changing
# the prime test to "(?!(xx+)\2+$)xx". We only need to do this on the N-X test,
# though, because as X is the larger number, it is already guaranteed not to be 1.
(x+) # \2 = N-X = Smaller number to test for being prime or a power of 2;
# tail = X = larger number to test for being prime or a power of 2.
(
(?!(xx+)\4+$) # Test X for being prime.
.*(?=\2$) # tail = N-X
((x+)(?=\6$))*x$ # Test N-X for being a power of 2. Use the positive version
# since it's faster and doesn't have a false match of 0.
|
(?!(x(xx)+)\7*$) # Test X for being a power of 2. Use the negative version
# because the testing of X has to be in a lookahead, and
# putting the positive version in a positive lookahead would
# be worse golf. It doesn't matter that this can have a false
# match of 0, because X is guaranteed never to be 0.
.*(?=\2$) # tail = N-X
(?!(xx+)\9+$)xx # Test N-X for being prime. We must prevent a false match of
# 1 for the reason described above.
)
)
```
# Regex (ECMAScript + molecular lookahead), ~~53~~ 52 bytes
`^(?!(xx)*$|(?*xx+(((x+)(?=\4$))*x$))\2(?!(xx+)\5+$))`
```
# For the purposes of these comments, the input number = N.
^
# Assert that N is not the sum of a prime number and a power of 2.
(?!
(xx)*$ # Assert that N is odd.
|
(?*
xx+ # Force N - \2 to be > 1, because the prime test used
# below has a false match of 1, which would otherwise
# give us false negatives on de Polignac numbers of the
# form 2^M+1, such as 262145 and 2097153.
(((x+)(?=\4$))*x$) # Cycle through subtracting all possible powers of 2 from
# tail, so we can then test {N - {power of 2}} for being
# prime.
# \2 = the power of 2
)
\2 # tail = N - \2
(?!(xx+)\5+$) # Test tail for being prime. If it matches, this will fail
# the outside negative lookahead, showing that N is not a
# de Polignac number.
)
```
This version is not only much cleaner, but much faster, because instead of having to cycle through all possible ways that N is the sum of two numbers, it can just cycle through subtracting every power of 2 from N and test the difference for being prime.
The molecular lookahead can be easily converted to a variable-length lookbehind:
# Regex (.NET or ECMAScript 2018), ~~55~~ 54 bytes
`^(?!(xx)*$|xx+(((x+)(?=\4$))*x$)(?<=(?<!^\5+(x+x))\2))`
[Try it online! (.NET)](https://tio.run/##ZVBba9swFH7fr1BCIOfUF@ywC0xVOzB7KLR0LIU9LCtozmkqUGQjyZkap789U@y2LxUIJL7vnO9Su6xuLB2N3JJrZU1s@eQ8bfvOKbNhlaga4xpNfPzfUfD5T9p0WtrvobXknIoEXmvpHNv2zkuvarZr1JrdSGUYYL@TljnxbXq8h8sJhIBns0MICQCEBOFSrD7OEM/CLL7PRbyT@9WnJGIBcbVAPE75aYMVhv6xKE0BXL7s/jpvoyMoU5dfk9n4x2yB6YDftv5kKq@abas0rZGPXKb5Q2NBGc@MKDhoUcUscn2tDAHiRJhOa25Eib16AHNRYJX/ssrTSBhstELny1YrD/Nsjvy0S6XEP8SB9sXHxeJwmEQgv7NPP6R1BO3v4k/adJGK76HXsawcOYSvsjC9MjupY5VWmg19ZX3xPE01ctKOhlrDUMpybGIe5qnCt4j7GFGdC@IqSdKQiAhjdGnzK3cjff0Isd9Tzv27nHtR8jcLg2Z48Yj8eTjHIiu/fC7@Aw "C# (.NET Core) – Try It Online")
[Try it online! (ECMAScript 2018)](https://tio.run/##TY7BbsIwEER/BSIk7xJiJVG5JJiceuDCoT02RViJCVulTmobsAR8exoqVeKw0khvZna@5FnaylDvIt3VarAizo14U82r7@HdGdINN/KyH3ZQTMF7nM9u3ocA4EOEQpQvM8S5n416Jcab7splODKPWKaIw57blioFySJKEHOjfk5kFDCjZN2SVgx5NWqnNtopc5Cj9Uq6P7msN12lrOXW1aTvyDsN7C@xaMX62oiW274lByximNMBQIuGt0o37ojr9HYju5VbINFLYx/t0HzEn4j/QD0DvU6KJHtgdEfTXYKNPsuW6omRulHZJAjb/NAZyGklVE5hiOPDwAfcqH4cD4T8W7rqCAbx@jS8Ozl@MeQUgC1YqVnGGIaEuRVJfr/jEEdpuox/AQ "JavaScript (Node.js) – Try It Online")
```
# For the purposes of these comments, the input number = N.
^
# Assert that N is not the sum of a prime number and a power of 2.
(?!
(xx)*$ # Assert that N is odd.
|
xx+ # Force N - \2 to be > 1, because the prime test used
# below has a false match of 1, which would otherwise
# give us false negatives on de Polignac numbers of the
# form 2^M+1, such as 262145 and 2097153.
(((x+)(?=\4$))*x$) # Cycle through subtracting all possible powers of 2 from
# tail, so we can then test {N - {power of 2}} for being
# prime.
# \2 = the power of 2
(?<=
(?<!^\5+(x+x)) # Test tail for being prime. If it matches, this will fail
# the outside negative lookahead, showing that N is not a
# de Polignac number.
\2 # tail = N - \2
)
)
```
[Answer]
# Mathematica, 41 bytes
```
OddQ@#&&!Or@@PrimeQ[#-2^Range[0,Log2@#]]&
```
[Answer]
# [PHP](https://php.net/), 75 bytes
prints 1 for truthy and 0 for falsy
```
for($t=1&$argn;0<$d=$n=$argn-2**$i++;$d-1?:$t&=0)for(;--$d&&$n%$d;);echo$t;
```
[Try it online!](https://tio.run/##HctBCoAgFEXReauIeEkaQjbs@3EtkZVNVML9Gzm8B24OuVqXQ@477O8deTAD1Su9Ewob0YwWC8@I3EqvSuGZZ4LXxm0oghf5D6Q1vBCIIzxJOo@QUKjWDw "PHP – Try It Online")
[Try it online! Polignac Integers under 10000](https://tio.run/##Jcw9D4IwEAbgvb/CkJNQPhJqXPRoGAyDiy5uxpDGVmApzVEno38dG7jpvbzPnevdXNWudxtmiEZqybiR/GC75Ne0l@vtfGo4MlDUWRmJ/SFC9hrJqGefkLKdSUQuyjBcTQviH/a2k/EJ@BwGjnPQIculjAWWFdh1KXZpCkOWIehC1EfwsSz5orUEi0UBOo7BbkFjeAN@QXR/rNf4ZY4G69vgKfR/ "PHP – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes
```
n->n%2*prod(i=0,n,!isprime(n-2^i))
```
[Try it online!](https://tio.run/##DYpBCoAwDMC@UgWhkw263edTBEEnPdiV6v9nLzkk0cM43ToaVBiSNlnKqtZP5EpR4sSvGj8XSio7hzBaNxR/c4RMRBE8y@dqhrQ5Gkrw7Qc "Pari/GP – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~15~~ 13 bytes
```
/₂ℕ|>ṗ;?-₍ḃ+1
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X/9RU9Ojlqk1dg93Tre2133U1PtwR7O24f//hkYWAA)
[Output de Polignac numbers upto 1000.](https://tio.run/##SypKTM6ozMlPN/pvaGBg8Gj@supHbRseNTU96lhe83BXZ@3DrRP@64P4LVNr7B7unG5tr/uoqffhjmZtw///AQ)
Returns `false.` for de Polignac numbers and `true.` otherwise.
Based on @LeakyNun's deleted answer, with a few bugfixes (posted with their permission).
*(-2 bytes by using @Jonathan Allan's method to check if the number is a power of two.)*
The given number is not a de Polignac number if:
```
/₂ℕ It's an even number
|>ṗ Or there exists a prime number less than the input
;?-₍ which when subtracted from the input
ḃ gives a result that has a binary form
+ such that the sum of the bits
1 is 1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ÆRạl2=Ḟ$o/o‘Ḃ
```
[Try it online!](https://tio.run/##ASMA3P9qZWxsef//w4ZS4bqhbDI94bieJG8vb@KAmOG4gv///zEyNw "Jelly – Try It Online")
```
ÆRạl2=Ḟ$o/ Main link; argument is z
ÆR Generate all primes in the range [2..z]
ạ Absolute difference with z for each prime
l2 Logarithm Base 2
=Ḟ$ For each one, check if it's equal to its floored value (i.e. if it is an integer)
o/ Reduce by Logical OR to check if any prime plus a power of two equals the z
o‘Ḃ Or it's not an odd number. If it's not an odd number, then automatically return 1 (false).
```
Outputs `1` for false and `0` for true.
[Answer]
# [Perl 6](http://perl6.org/), 55 bytes
```
{so$_%2&&$_∉((1,2,4...*>$_) [X+] grep &is-prime,^$_)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/ujhfJV7VSE1NJf5RR6eGhqGOkY6Jnp6elp1KvKZCdIR2rEJ6UWqBglpmsW5BUWZuqk4cUKL2v7VCcWIlVCpNRyHO1MDA@j8A "Perl 6 – Try It Online")
* `(1, 2, 4 ... * > $_)` is a sequence of the powers of two until the input argument (Perl infers the geometric series from the provided elements).
* `grep &is-prime, ^$_` is the list of prime numbers up to the input argument.
* `[X+]` evaluates the sum of all elements of the cross product of the two series.
I could have done without the `so` for two bytes less, but then it returns two distinct falsy values (`0` and `False`).
[Answer]
# Axiom, 86 bytes
```
f(n:PI):Boolean==(~odd?(n)=>false;d:=1;repeat(n<=d or prime?(n-d)=>break;d:=d*2);n<=d)
```
test and results
```
(21) -> for i in 1..600 repeat if f(i) then output i
1
127
149
251
331
337
373
509
599
```
[Answer]
# Haskell, ~~104~~ 102 bytes
```
p x=[x]==[i|i<-[2..x],x`mod`i<1]
h k|even k=1>2|2>1=notElem k$((+)<$>(2^)<$>[0..k])<*>filter(p)[1..k]
```
**Explanation**
* p is a function that finds prime numbers (very inefficient!)
* Creating a list of `(+)` applied to 2^ partial function which is applied to a list [0..input]
* Applying the above to a list filtered 1 to input for primes
* Resulting cartesian product of every possible value is searched to ensure input does not exist in cartesian product
* Guarded to ensure that an even input is automatically false.
UPDATE: Shout out to Einkorn Enchanter for golfing two bytes!
[Answer]
# Common Lisp, 134 bytes
```
(lambda(x)(flet((p(x)(loop for i from 2 below x always(>(mod x i)0))))(or(evenp x)(do((j 1(* j 2))(m()(p(- x j))))((or(>= j x)m)m)))))
```
Return `NIL` when the argument is a Polignac number, `T` otherwise.
[Try it online!](https://tio.run/##XY3BDsIwDEN/xdrJRULqdmf/UmgnOrVLtVVsXPj1kXLEuSTys/NIcSsnk0jBJCsiplUyLKqgt9Zif4YFXKSCirl8946H4ZRCJUtb/7MD7iHJjgMu7e69cWQWr2c01qgoK8MrLAUa9kLO6HnBjEG9TKOtV6XnH9vg8abmYbJO0xmNgRdQf2ZXUdF9PDqtb@YX)
Ungolfed:
```
(lambda (n)
(flet ((prime? (x) ; x is prime
loop for i from 2 below x ; if for i in [2..n-1]
always (> (mod x i) 0))) ; is x is not divisible by i
(or (evenp n) ; if n is even is not a Polignac number
(do ((j 1( * j 2)) ; loop with j = 2^i, i = 0, 1,...
(m () (prime? (- n j)))); m = n - 2^i is prime?
((or (>= j n) ; terminate if 2^i ≥ n
m) ; or if n - 2^i is prime
m))))) ; not a polignac if n - 2^i is prime
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 bytes
```
⍱2∘|⍲0⍭⊢-2*…
```
[Try it online!](https://tio.run/##FY2xagJxDMb3PkXmwsE/@V/IZS6IToL2BYQ7u0jbwaEFB0EQEU50KDg7lC4i7SP4KHmR63dDvuSX5Etm74ui/pwt3l6K5mPZvNZN3cXhazCJ7ZGlsi7aX4ndeRXtX4r2GvtLIY@x/u7m2Ij2gOXROPab@y3H9gSaTp6gz8PRtJvff5hYjLh0EmXKuQ@jbJk0Oak7WWIyNarAlRl5UgSyOnnPDn9ih1SoGBYWzFm4P15miPY9A5YwsApQS37AfxFS@wc "APL (Dyalog Extended) – Try It Online")
Anonymous prefix tacit function. Returns 1 for truthy, 0 for falsy.
Largely based on [ETHProductions' Japt answer](https://codegolf.stackexchange.com/a/129174/74163).
Thanks to @Adám for helping with golfing my original answer, and for making Dyalog Extended for that matter.
### How:
```
⍱2∘|⍲0⍭⊢-2*… ⍝ Tacit prefix function; input will be called ⍵
… ⍝ Inclusive Range [0..⍵]
2* ⍝ 2 to the power of each number in the range
⊢- ⍝ Subtract each from ⍵
0⍭ ⍝ Non-primality check on each resulting number
⍲ ⍝ Logical NAND
2∘| ⍝ Mod 2
⍱ ⍝ Not any (bitwise OR reduction, then negated)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 98 bytes
```
lambda x:not(x%2<1or any((lambda x:x>1and all(x%j for j in range(2,x)))(x-2**i)for i in range(x)))
```
[Try it online!](https://tio.run/##XcrBCsIwDIDhu0@Ri5CMCWvBy1CfxEvGrGbUdJQesqev3UXB6//961ZeSX0N13uN/J5mBhs1FbSjv7iUgXVD/IrdHOsMHGMbFghtWEAUMuvzgb43IkI7@a4T2lF@uFP9a@480HiANYsWlD6gtOcD "Python 2 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
&%Q2!smP-^2dQl
```
[Try it!](https://pyth.herokuapp.com/?code=%26%25Q2%21smP-%5E2dQl&input=128&test_suite=1&test_suite_input=22%0A57%0A3%0A1%0A127%0A149%0A251%0A331%0A337%0A373&debug=0)
[Answer]
# [Julia 0.4](http://julialang.org/), 31 bytes
```
n->n%2*!any(ispow2,n-primes(n))
```
[Try it online!](https://tio.run/##FcpBCoAgAATAe6/YgsBCwTwG9RehBKM20SJ6vdl5Zrt3b7PDhEw1szV9bfkKn8L5GEkVoj/WJNh12Z0RLHEYB611BRTjtVNQooGa0Ui4f1Yrl/wB "Julia 0.4 – Try It Online")
[Answer]
# APL(NARS) 80 chars, 160 bytes
```
∇r←f w;n
r←¯1⋄→0×⍳(w≤0)∨w≥9E9⋄r←0⋄→0×⍳0=2∣w⋄n←r←1
→0×⍳w≤n⋄→3×⍳0πw-n⋄n×←2⋄→2
r←0
∇
```
The function 0π is the function that return its argument is prime or not. For me this function has not be recursive so it is a little more long... Test:
```
{1=f ⍵:⍵⋄⍬}¨1..1000
1 127 149 251 331 337 373 509 599 701 757 809 877 905 907 959 977 997
```
for input <=0 or input >=9E9 it return ¯1 (error)
```
f¨0 ¯1 ¯2 900000000001
¯1 ¯1 ¯1 ¯1
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 107 bytes
```
x=>{var r=Enumerable.Range(2,x);return x%2>0&r.All(p=>r.Any(d=>d<p&p%d<1)|r.All(n=>x!=p+Math.Pow(2,n-2)));}
```
[Try it online!](https://tio.run/##ZY7LDoIwFET3fMV1AWnDmy20iQvdmRA/wKRAK03w0hRQjPrtiLp0dyaTzJl6COtBL3EMxs9O6OwnrAuNY1D1fccVW2bGH1dhwbIdThdpRdXJ6CjwLEkWzDS3cpwswuxmPPFstO06YhhfAe@kYbwpjGfcpkjp81ci4/OGGf8gxjYq@9u6gmFGKc1fS@44qrdS1C35KDVohD9rGqRJklDqAGhFFNFfBCjtentN@fIG "C# (Visual C# Interactive Compiler) – Try It Online")
Not the most efficient code, but seems to work. My [original solution](https://tio.run/##ZU@7DoIwFN35iuuAaQOUx4pt4qCbCXFxMymkSBNszQUUUL8dkcnE7TyS8yiaoGj0FIZw85KzcfadKTbatH5ubS1KPvVcPO8SAfnOdFeFMq8VO0pzUSTxe5qiajs00LuJiNbITpVCRQYukG3rmoxcjIIPr8EdRUTpov2a/YoP3kG2FcvsYw4cg4RSmr6n1HFKi0oWFfm2a9AG/gbEfhxFc6wDoEtSEr1AgAznBzNLpw8) filtered for primes before testing them in the formula and it performed much better. The current version is 11 bytes shorter.
```
// input x is an integer
x=>{
// we need to generate several
// ranges. since this is verbose,
// generate 1 and keep a reference
var r=Enumerable.Range(2,x);
// this is the main condition
return
// input must be odd
x%2>0&
// generate all possible p's
// over our range and ensure that
// they satisfy the following
r.All(p=>
// either p is not prime
r.Any(d=>d<p&p%d<1)
|
// or there is no n that satisfies
// the formula: x=p+2^n
r.All(n=>x!=p+Math.Pow(2,n-2))
);
}
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed last year.
[Improve this question](/posts/57597/edit)
I hear *[somebody](https://codegolf.stackexchange.com/users/30525/beta-decay)* was very selfish on their birthday, [demanding cake from everyone](https://codegolf.stackexchange.com/questions/57277/its-my-birthday-d) and there were no plans to share! 🎂
It's bound to be somebody's birthday today, so why not bake them a cake. Use your favourite programming language to make a delicious cake, with a nice "Happy Birthday" message as the output. (Might I suggest [Chef](http://esolangs.org/wiki/chef)!)
Your cake should
* Mimic a real world recipe (if you can link to it, brilliant!)
+ a list of newline separated ingredients suitable for making a cake
+ a newline separated list of steps for the method
+ how many people it serves
* Stay as close to correct ingredient ratios as possible.
* Output minimally "Happy Birthday" when served.
The best cakes will be:
* **Delicious** - since this is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), the community will decide what is delicious
* **Personalised** - try baking a custom happy birthday message to somebody specific. (If you can't find a PPGC user, why not a celebrity?)
* **Balanced** - Try to use a suitable number of ingredients for the amount of servings the recipe prepares. `1000 eggs, serves 1` for one serving is probably just a *teensy bit* big, **huge**, # absolutely colossal!
* **Outlandish** - You can bake more than just a basic sponge, for example, include some icing, a drizzle, serve with sauce, decorations, etc.
* **Visually appealing** - images are good either in the source code as ascii or in the output. The first "byte" is with the eyes after all.
And don't forget, good bakers **don't cut corners** and do things properly. (*Don't just use no-op code to make it look like a recipe then print, make sure your code means something*) I encourage voters to view these recipes negatively.
## Happy Baking!
[](https://i.stack.imgur.com/i6O6p.jpg)
[Answer]
# ECMAScript 2015, serves 10
```
Don =([_])=> alert(_.replace(/^.*(?=, )/,'Happy Birthday'))
ReadMoreAbout =classic= victoria =sandwich= on =bbcgoodfood= ~`
âš Remember that OCR technologies aren't perfect, and that scanning old,
âš smudgy recipes does not always go as smoothly as we'd expect or hope.
âš This recipe is not wonderful, but please, thoroughly enjoy making it.
`
try/* to do this properly! */{
// Link to recipe:
bbcgoodfood.com/recipes/1997/classic-victoria-sandwich
'Makes 10 slices'
Ingredients:
ForThecake:
- 200 | grammes | castorSugar
- 200 | grammes | softenedButter
- 4 | whole | eggs
- 200 | grammes | self-raising_flour
- 1 | tsp | bakingPowder
- 2 | tbsp | milk
For_theFilling:
- 100 | grammes | butter, softened
- 140 | grammes | icing.sugar, sifted
- a | drop | vanilla- extract (optional)
- 240 | grammes | jar.good-quality_strawberryJam
- icingSugar, to.decorate
Method:
1. ^`Heat oven to 190C/fan 170C/gas 5. Butter two 20cm sandwich tins
and line with non-stick baking paper. In a large bowl,
beat all the cake ingredients together until you have a smooth, soft batter.`
2. ^`Divide the mixture between the tins, smooth the surface with a spatula
or the back of a spoon, then bake for about 20 mins until golden
and the cake springs back when pressed. Turn onto a cooling rack
and leave to cool completely.`
3. ^`To make the filling, beat the butter until smooth and creamy,
then gradually beat in icing sugar. Beat in vanilla extract if you’re
using it. Spread the butter cream over the bottom of one of the sponges,
top it with jam and sandwich the second sponge on top.
Dust with a little icing sugar before serving.
Keep in an airtight container and eat within 2 days.`
* HappyBirthdayǃ
} catch (cake) {
Don`t drop that! It's your cake, Uncle Chris! This cake is one day late – sorry about that.
`}
```
**Valid ES6 code; no corners cut!**
It works in Firefox Developer Edition.
>
> It is all valid code; the `try` only serves to catch the `ReferenceError` caused by the variables not being defined.
>
>
>
[Answer]
## BF
Inspired by mbomb007s answer, I've made them a cake.
I'm afraid I lost the recipe (it's around here somewhere, but I'd probably have to break my own rules on cutting corners to post it); here is the finished product.
```
+
[
(
) ) (
) (o) )
( (o) ) ,|, )
(o) ,|, |~\ ( (o)
,|, |~\ ( \ | (o) ,|,
\~| \ |----(o)->++|+\<]>,|, |+.
|`\-----|`\@@@-|-@@@@\.-@@@\~|[++>-\ |-
-\-|-o@@@\ |@@@<]>@@@@|.\@@@|.\@@@o+|+\++
++|+\@@@@@|+\@@@|+\@@@@\.|@@@\-[@@@@@\-|o--
->@\+|@@@@@\<|@@@]>|@@@@@@@@@@|+\@@@@@|+\@@o.
[->+|+\+@@@@@@@@@@|<]@@@@@@@@@@\>|@@@@@\+|+@@@.
+@@@@@@@@@@@@@@@@@\+|@@@@@@@@@@|+\@@@@@@@@++++.
@@++@@@@@@@@@@@@@@|+\@@@@@@@@@@@@@@@@@@@@+++++
+.@@@++@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@o@@.-@
--@@--@@-@@@@@@@@@@@@@@@@@@@@@@@@@@@@-@@-@@--@
--@@.-@@@@---.@@@@--@@@@@-.+[@@@@@o---@@@>+<:]
>::::::+::::::++@@.::@@@:::::@@@@:::::@@:::::%
%%::::::::::::@@::::::@:::::::@@::::::::::::%%
::%%%::::::::::@::::::::::::::@::::::::::%%%::
º# ::%::%%%%%%:::::::::::::::::::::::::%%%%%::%::##º
º### ::::::%%:::%:%%%%%%%%%%%%%%%%%%%%%:%:::%%::::: ###º
º##### ::::::%:::::%%::::::%%%%:::::%%::::%:::::::::: #####º
º###### `:::::::::::%:::::::%:::::::::%::::%:::::::::' ######º
º######## ``::::::::::::::::::::::::::::::::::::'' #########º
º########## ```::::::::::::::::::::::::::''' ###########º'
`º#########-[---->+<]>++.[-->+++<]>..+++++++. ###########º'
` º#################################################º '
` º#######################################º '
` º#################################º '
` º######################º '
```
Outputs:
```
happy birthday 007
```
So conveniently it works for James Bond, but not until 11th November.
[Answer]
# Python 2, serves 0
First of all, sorry, this isn't a REAL world cake.
However, it is in one of the [best games of all time, Portal.](https://en.wikipedia.org/wiki/Portal_(video_game))
This recipe is based on what the [Intelligence Core](http://theportalwiki.com/wiki/Core_voice_lines#Cake_core) says are the ingredients.
```
""" Happy Birthday, Chell!
* * * * * * * * * * * """
# Here are all the ingrediants for portal cake
candles = 1 # There is most certainly only one candle for her.
fish_shaped_dirt = 32 # There isn't an official amount of dirt to add, 32 seems like a nice number.
#Full of lies
lie = float('inf')
serves = None
# Show the tester the documentation on how to use this
print __doc__,
# Now, we are going to repeat these steps until chell stops lying.
while lie:
# She did it again, so now we need to do the whole thing once more.
print "\r",
# Check how many candles her cake will have
if candles:
# We had better take them away from her. Maybe it will stop her lying so much
candles = 0
else:
# Maybe if we give her a candle, she will listen
candles = 1
# See, her chances of lying go down when we give her candles!
lie -= candles
# Add the fish shaped dirt. But ONLY if we're giving her a candle.
print chr(fish_shaped_dirt)*candles,
# Add all the other rubbish
print __doc__[25:],
#Flush it into the relaxation vault
import sys
sys.stdout.flush()
# Wait and ask her if she liked it.
import time
time.sleep(1)
```
# Output
```
Happy Birthday, Chell!
* * * * * * * * * * *
```
Followed by
```
Happy Birthday, Chell!
* * * * * * * * * * *
```
Then repeats indefinitely
[Answer]
# Brainf\*\*\*
I like ice cream cake, which doesn't require baking. Also, it's my birthday, so don't tell me what kind of cake I can have.
```
Buy an ice cream cake:
+ + + + + +
| | | | | |
[-]-[------->+<]>-.[--->++++<]
|><>+.-[++>-----<]>..+++++++++
|><.-[---->+<]>++.+[->++<]>.-[
|><--->+<]>--.+++++++++.++.---
|><---------.----.---.+[--->+<
|><]>+++.-[---->+<]>+++---+++|
then serve it.
```
I like to pretend that the `>+<]>`'s are fish-shaped crackers.
[Answer]
# [Pip](http://github.com/dloscutoff/pip), serves 2
For those of us whose birthday tastes are a little more global...
```
Our dessert tonight: " Birthday " Dosa!
(adapted from vegrecipesofindia.com/masala-dosa-recipe-how-to-make-masala-dosa-recipe)
1 cup rice: ("mmm, rice")
1 cup ukda chawal: [don't know what that is but it sounds good]
1/2 cup urad dal: ["dal" means lentils in Hindi]
1/4 cup poha: ["poha" is another kind of rice]
1/4 tsp methi seeds: ("!")
salt to taste: ["Happy" time]
water as needed: [you'll need some water]
Are you ready to cook? Yes? OK then:
1. rinse the rice and urad dal separately first.:
2. soak the ukda chawal, rice and poha.
3. in another bowl soak the urad dal-methi in enough water.
4. grind the urad dal with methi to a fine and fluffy batter.
5. grind the rice and poha to a smooth batter.
6. mix both the rice and urad dal batter with salt.
7. cover and let the batter ferment for 8-9 hours.
is it Ready? Y(es) or N(o)
Answer should be: y.
take batter out and:
1. heat a flat cast-iron griddle and smear some oil on it.
3. spread the dosa batter in a circular way on the griddle; add some oil on top.
4. flip and cook the other side.
5. serve dosa hot with coconut chutney and sambar. (yum)
Recipe serves ___:
`(?<=2) ?`
Actually, it serves exactly 2--half feR "ME" and half feR:_" YOU"!
Yeah! Happy birthday !
```
### Output
```
Happy Birthday 2 YOU!
```
or, if you cook it:
[](https://i.stack.imgur.com/AqlVh.jpg)
Now I'm hungry.
[Answer]
# Chef, serves 16.
Based off of [this](http://www.tasteofhome.com/recipes/chocolate-truffle-cake). I couldn't find an interpreter online, so I closely followed the specs found [here](http://www.dangermouse.net/esoteric/chef.html).
## "Golfed" version
```
"Happy" Birthday Cake.
This recipe was recovered from an *erm* ANCIENT cave, in which the culture consumed enormous amounts of eggs and water, and did so through their caves. Modern ingredients have been added in an endevour to make the cake better.
Ingredients.
48 teaspoons 2% milk
1 cup butter
1 l semisweet chocolate
73 eggs
2 teaspoons vanilla extract
1 cup sugar
1 teaspoon baking soda
5 teaspoons salt
24 g happiness
3 teaspoons water
8 ml corn starch
32 g space
Cooking time: 25 minutes.
Pre-heat oven to 162 degrees Celsius.
Method.
Put 2% milk into the mixing bowl. Add happiness to the mixing bowl. Put eggs into the mixing bowl. Add happiness to the mixing bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add happiness to the mixing bowl. Add corn starch to the mixing bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add happiness to the mixing bowl. Add corn starch to the mixing bowl. Put 2% milk into the mixing bowl. Add happiness to the mixing bowl. Add happiness to the mixing bowl. Add happiness to the mixing bowl. Add sugar to the mixing bowl. Put space into mixing bowl. Put happiness into the mixing bowl. Remove water from the mixing bowl. Combine vanilla extract into the mixing bowl. Add happiness to the mixing bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add butter to the mixing bowl. Add happiness to the mixing bowl. Put space into the mixing bowl. Combine water into the mixing bowl. Remove water from mixing bowl. Remove water from mixing bowl. Add happiness to the bowl. Put space into the mixing bowl. Combine water into the mixing bowl. Remove water from mixing bowl. Remove semisweet chocolate from mixing bowl. Add happiness to the bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add happiness to the bowl. Put 2% milk into the mixing bowl. Add happiness to the mixing bowl. Add happiness to the mixing bowl. Add sugar to the mixing bowl. Put eggs into the mixing bowl. Add happiness to the mixing bowl. Put eggs in mixing bowl. Add happiness to the mixing bowl. Add happiness to the mixing bowl. Put happiness into the mixing bowl. Put happiness into the mixing bowl. Remove sugar from the bowl. Remove baking soda from the bowl. Put space into mixing bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add happiness to the mixing bowl. Add salt to the mixing bowl. Put eggs into the mixing bowl. Add happiness to the mixing bowl. Add butter to the mixing bowl. Add water to the mixing bowl. Put space into the mixing bowl. Add baking soda to the mixing bowl. Liquefy contents of the mixing bowl. Serves 16.
```
Output: `Happy Birthday, me!`.
Here is the explanation for each step:
```
"Happy" Birthday Cake.
This recipe was recovered from an *erm* ANCIENT cave, in which the culture consumed enormous amounts of eggs and water, and did so through their caves. Modern ingredients have been added in an endevour to make the cake better.
Ingredients.
48 teaspoons 2% milk
1 cup butter
1 l semisweet chocolate
73 eggs
2 teaspoons vanilla extract
1 cup sugar
1 teaspoon baking soda
5 teaspoons salt
24 g happiness
3 teaspoons water
8 ml corn starch
32 g space
Cooking time: 25 minutes.
Pre-heat oven to 162 degrees Celsius.
Method.
Put 2% milk into the mixing bowl. 48
Add happiness to the mixing bowl. +24= 72 (H)
Put eggs into the mixing bowl. 73
Add happiness to the mixing bowl. +24= 97 (a)
Put vanilla extract into the mixing bowl. 2
Combine vanilla extract into the mixing bowl. *2 = 4
Combine vanilla extract into the mixing bowl. *2 = 16
Combine salt into mixing bowl. *5 = 80
Add happiness to the mixing bowl. +24=104
Add corn starch to the mixing bowl. +8 =112 (p)
Put vanilla extract into the mixing bowl. 2
Combine vanilla extract into the mixing bowl. *2 = 4
Combine vanilla extract into the mixing bowl. *2 = 16
Combine salt into mixing bowl. *5 = 80
Add happiness to the mixing bowl. +24=104
Add corn starch to the mixing bowl. +8 =112 (p)
Put 2% milk into the mixing bowl. 48
Add happiness to the mixing bowl. +24= 72
Add happiness to the mixing bowl. +24= 96
Add happiness to the mixing bowl. +24=120
Add sugar to the mixing bowl. +1 =121 (y)
Put space into mixing bowl. 32 ( )
Put happiness into the mixing bowl. 24
Remove water from the mixing bowl. -3 = 21
Combine vanilla extract into the mixing bowl. *2 = 42
Add happiness to the mixing bowl. +24= 66 (B)
Put vanilla extract into the mixing bowl. 2
Combine vanilla extract into the mixing bowl. *2 = 4
Combine vanilla extract into the mixing bowl. *2 = 16
Combine salt into mixing bowl. *5 = 80
Add butter to the mixing bowl. +1 = 81
Add happiness to the mixing bowl. +24= 95 (i)
Put space into the mixing bowl. 32
Combine water into the mixing bowl. *3 = 96
Remove water from mixing bowl. -3 = 93
Remove water from mixing bowl. -3 = 90
Add happiness to the bowl. +24=114 (r)
Put space into the mixing bowl. 32
Combine water into the mixing bowl. *3 = 96
Remove water from mixing bowl. -3 = 93
Remove semisweet chocolate from mixing bowl. -1 = 92
Add happiness to the bowl. +24=116 (t)
Put vanilla extract into the mixing bowl. 2
Combine vanilla extract into the mixing bowl. *2 = 4
Combine vanilla extract into the mixing bowl. *2 = 16
Combine salt into mixing bowl. *5 = 80
Add happiness to the bowl. +24=104 (h)
Put 2% milk into the mixing bowl. 48
Add happiness to the mixing bowl. +24= 72
Add happiness to the mixing bowl. +24= 96
Add sugar to the mixing bowl. +1 = 97 (d)
Put eggs into the mixing bowl. 73
Add happiness to the mixing bowl. +24= 97 (a)
Put eggs in mixing bowl. 73
Add happiness to the mixing bowl. +24 = 97
Add happiness to the mixing bowl. +24 =121(y)
Put happiness into the mixing bowl. 24
Put happiness into the mixing bowl. +24= 48
Remove sugar from the bowl. -3 = 45
Remove baking soda from the bowl. -1 = 44 (,)
Put space into mixing bowl. 32 ( )
Put vanilla extract into the mixing bowl. 2
Combine vanilla extract into the mixing bowl. *2 = 4
Combine vanilla extract into the mixing bowl. *2 = 16
Combine salt into mixing bowl. *5 = 80
Add happiness to the mixing bowl. +24=104
Add salt to the mixing bowl. +5 =109 (m)
Put eggs into the mixing bowl. 73
Add happiness to the mixing bowl. +24=97
Add butter to the mixing bowl. +1 =98
Add water to the mixing bowl. +3 =101 (e)
Put space into the mixing bowl. 32
Add baking soda to the mixing bowl. +1 = 33 (!)
Liquefy contents of the mixing bowl. Converts the mixing bowl to characters
Serves 16. Outputs the contents of the first
16 bowls.
```
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/2922/edit).
Closed 7 years ago.
[Improve this question](/posts/2922/edit)
We all heard of testing compilers using randomly generated inputs. Your task is to write a program to generate a valid program (including no undefined behavior) in your favorite language. The generating program language doesn't have to be the same as the generated program language.
Your program will receive an integer as the argument which you can use as seed for your random number generator. The generated programs should be structurally different (given different seeds) not just different variable names or constants.
Examples:
```
$ ./generate 1
int main() { return 0; }
$ ./generate 2
#include <math.h>
int main() { return (int) pow(4, 3); }
```
Please include a couple of outputs in your answers.
The shortest solution wins. I will give a small bonus based on the number of votes, so please vote the most creative solutions.
[Answer]
## Python → Brainf\*ck (185 223 233 255 285 287 303 characters)
### Code
```
import random as r,sys
r.seed(int(sys.argv[1]))
c=list('<>.,+-')+['']
n=9/r.random()
def b():
global n
s=''
while n>0:n-=1;o=r.choice(c);s+=o if o else'[%s]'%b()
return s
print b()
```
* **303 → 287 Characters**: Removed `math.ceil` (it's not really necessary).
* **287 → 285 Characters**: Switched to an empty string to denote the branch operator.
* **285 → 255 Characters**: Condensed the if statement in the while loop.
* **255 → 233 Characters**: Implemented [JBernardo](https://codegolf.stackexchange.com/users/2212/jbernardo)'s suggestions from the comments.
* **233 → 223 Characters**: Implemented [tjko](https://codegolf.stackexchange.com/users/2345/tjko)'s suggestion from the comments.
* **223 → 185 Characters**: Implemented some whitespace reduction suggestions from the comments.
### Examples
```
$ python generate.py 1
-->,,+-<<-,-<,->[[<<,[.>.<>,,>>>,.<-,+>[[<.-+[.-+.+[-,+<>-.>,++.,,-,.,<<+[+]]]]]]]]
$ python generate.py 2
[<<--+.+++>]
$ python generate.py 3
,.++<<->>[,-,+>+[,-+<-+.<[,-[+[.-,[[<<>[,+.]]]]]]]]
```
Actually figuring out what the resulting BF programs *do* is left as an exercise to the reader.
[Answer]
**Python -> Piet, 385 345 char**
It's possible to generate any Piet program with this. I could've just stopped at random pixels, but I wanted to make "interesting" programs. The function `m` paints a pixel a color, and recursively steps into each of that pixels neighbors. There are better ways to draw random blobs, but this is tuned to terminate in a reasonable number of steps, so it's good enough for golf. The function `R(w,h,n)` draws *n* random blobs onto a (*w* x *h*) white image, and prints the result in PPM format.
I'm especially proud of how I generate the colors -- for a random choice of `0 <= c < 20`,
```
`[0,192,255][int(x)]`for x in'0002212220200101121100'[c:c+3]
```
is the decimal code for a valid color in the Piet palette by way of a [single-track Gray code](http://en.wikipedia.org/wiki/Gray_code#Single-track_Gray_code). That is, each color is represented by 3 adjacent bits, and every slice `'0003...0'[c:c+3]` represents a different color. Since this isn't the full list of 27 words on 3 letters, I really lucked out in finding the Gray code.
```
from random import*
r=randint
def R(w,h,n):
M=[6]*h*w
def m(x,y,c,d):M[y%h*w+x%w]=c;t=r(0,15)*(r(0,d)<2);t&8and m(x+1,y,c,d+1);t&4and m(x-1,y,c,d+1);t&2and m(x,y+1,c,d+1);t&1and m(x,y-1,c,d+1)
while n:m(r(0,w),r(0,h),r(0,19),0);n-=1
print"P3 %s %s 255 "%(w,h)+' '.join(`[0,192,255][int(x)]`for c in M for x in'0002212220200101121100'[c:c+3])
```
Sample output, generated by the command `R(30,40,500)`

Without the import, I can write it as a proper (semicolon-free) 1-liner, too:
```
import random
R=(lambda P,I,E,T:lambda w,h,n:E(w,h,I(w,h,n,lambda z,c,d,t:sum((((z,c),)*t*T(0,1)or m((z[0]+a,z[1]+b),c,d+1,T(0,d)>1)for a,b in((0,1),(1,0),(-1,0),(0,-1))),()))))(range,lambda w,h,n,m:dict(sum((m((T(0,w),T(0,h)),T(0,19),0,0)for _ in P(n)),())),lambda w,h,M:"P3 %s %s 255 "%(w,h)+' '.join(' '.join(`(x&1)*255+(x&2)*96`for x in map(int,'0001121110100202212200'[c:c+3]))for c in(M[z]if z in M else 6for z in((x,y)for y in P(h)for x in P(w)))),random.randint)
```
but it's *ridiculously* slow (and almost 100 characters longer)... though I'm not entirely sure why (and not terribly inclined to find out).
[Answer]
## Python -> Python, 135 chars
```
import random,sys
random.seed(int(sys.argv[1]))
R=range(9)
print'print 1'+''.join(random.choice('+*')+'%d'%random.choice(R)for x in R)
```
Generates little random expression evaluations, like this:
```
> ./genprogram.py 1
print 1+7*2+4*7+0*3*0+6+8
> ./genprogram.py 2
print 1*8+0*6*2*5*1+3*8*4
> ./genprogram.py 3
print 1+4+5*0+7+2*4*4*1*7
> ./genprogram.py 4
print 1+0+1+3*7*1*2+0+8*7
```
[Answer]
**Python -> HQ9+ : 108 chars**
```
import random
def g(): return ''.join([random.choice(['H','Q','9','+']) for x in range(random.randint(1,9))])
```
[Answer]
# PHP, 352 characters
Generates PHP code in PHP.
I decided I didn't care as much about length, but instead wanted an interesting and diverse set of solutions. This is my answer to that.
## Code
```
<?php mt_srand(0+$argv[1]);$r=mt_rand(1,100);$s="\$i=rand(1,$r);";while($r>0){$s.='$i';if(!($r%10))$s.='*=2;';if(!($r%9))$s.='++;';if(!($r%8))$s.='=pow($i,rand(1,$i));';if(!($r%7))$s.='--;';if(!($r%6))$s.='=substr($i,0,2);';if(!($r%5))$s.='/=2;';if(!($r%4))$s.='+=4;';if(!($r%3))$s.='*=-1;';$r-=mt_rand(1,5);}$s.='var_dump($i);';echo"<?php $s
";
```
### Ungolfed
```
<?php
mt_srand(0+$argv[1]);
$r = mt_rand(1,100);
$s = "\$i=rand(1,$r);";
while ($r > 0)
{
if (!($r%10)) $s .= '$i*=2;';
if (!($r%9)) $s .= '$i++;';
if (!($r%8)) $s .= '$i=pow($i,rand(1,$i));';
if (!($r%7)) $s .= '$i--;';
if (!($r%6)) $s .= '$i=substr($i,0,2);';
if (!($r%5)) $s .= '$i/=2;';
if (!($r%4)) $s .= '$i+=4;';
if (!($r%3)) $s .= '$i*=-1;';
$r -= mt_rand(1,5);
}
$s .= 'var_dump($i);';
echo "<?php $s
";
```
## Example
```
> php r.php 1
<?php $i=rand(1,58);$i*=-1;$i=pow($i,rand(1,$i));$i=substr($i,0,2);$i+=4;$i*=-1;$i=pow($i,rand(1,$i));$i=substr($i,0,2);$i+=4;$i*=-1;$i*=2;$i/=2;$i+=4;$i/=2;$i*=-1;$i*=2;$i/=2;$i=substr($i,0,2);$i*=-1;var_dump($i);
> php r.php 2
<?php $i=rand(1,57);$i*=-1;$i+=4;$i--;$i=substr($i,0,2);$i*=-1;$i*=-1;$i--;$i+=4;$i/=2;$i++;$i=substr($i,0,2);$i*=-1;$i=pow($i,rand(1,$i));$i+=4;$i--;$i=substr($i,0,2);$i+=4;$i*=-1;$i--;$i+=4;var_dump($i);
```
[Answer]
### scala: 1543 (scala => scala)
I have variables (x, y, z), functions (mul, add, neg, abs), values and balanced parenthesis.
```
<!--code:language-scala-->
object FormelBauer {
val fun = List (" mul10 (", " add1 (", " neg (", " abs (")
val ops = List (" * ", " + ", " - ", " / ")
def c(maxLen: Int, m: Int) : String = {
def f()= new StringBuffer (fun (r.nextInt (fun.length)))
def w()= new StringBuffer ("" + (r.nextInt (180) - 90))
def v()= new StringBuffer ("" + ('x' + r.nextInt (3)).toChar)
def o()= new StringBuffer (ops (r.nextInt (ops.length)))
def g(t: Int, b: Int, d: List [Char]) : StringBuffer ={
var a = d.filterNot (x => if (b > 0) x == '.' else x == ')')
if (b > m) a = a.filterNot (_ == 'k')
if (b > m) a = a.filterNot (_ == 'f')
if (t > maxLen) a = a.filterNot (_ == '+')
val elem = r.nextInt (a.length)
val start = a(elem)
start match {
case '.' => new StringBuffer ("")
case 'f' => f.append(g (t + 1, b + 1, List ('(', '8', 'x')))
case '(' => new StringBuffer ("(").append (g (t + 1, b + 1, List ('(', '8', 'x')))
case '8' => w.append(g (t + 1, b, List ('.', ')', '+')))
case 'x' => v.append(g (t + 1, b, List ('.', ')', '+')))
case ')' => new StringBuffer (") ").append (g (t + 1, b -1, List ('.', ')', '+')))
case '+' => o.append(g (t + 1, b, List ('f', '(', '8', 'x')))
}}
(g (0,0,List('f','(','8','x'))).toString
}
import util._
var r : Random = _
def main (as: Array [String]) : Unit = {
val s=as(0).toInt
r=new Random(s)
"xyz".map(c=>println("val "+c+"="+(c+r.nextInt(s))))
println("""def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
"""+c(45,5))}
}
```
As you see, it is not very golfed. Because, it will not get me close to the other solutions, but a problem is, that more variation costs more. 3 variables, 4 functions could be easily reduced to two, for example.
Generating some samples:
```
for i in {1..7} ; do scala FormelBauer $i; echo; done
val x=120
val y=121
val z=122
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
(y) / 79
val x=121
val y=121
val z=123
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
add1 ((((78 + neg (z * z) ) / x) ) ) + -23 - ((-83) * y)
val x=122
val y=123
val z=122
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
x / -71 - (y)
val x=122
val y=124
val z=125
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
x
val x=122
val y=123
val z=126
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
-24 + z
val x=121
val y=121
val z=124
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
abs (z)
val x=123
val y=126
val z=126
def mul10(i:Int)=10*i
def add1(i:Int)=i+1
def neg(i:Int)= -i
def abs(i:Int)=if(i<0)-i else i
add1 (-62 - 30 * (-68) / neg (x - 69 + 33 / 45 + x * x) - abs (-18 * (y + x) / neg (x) - y) * abs ((61) ) ) + (y)
```
Testing the longest one:
```
add1 (-62 - 30 * (-68) / neg (x - 69 + 33 / 45 + x * x) - abs (-18 * (y + x) / neg (x) - y) * abs ((61) ) ) + (y)
```
res6: Int = -5425
[Answer]
## Perl -> shell : 66 chars
```
@p=split(':',$ENV{PATH});
@c=`ls @p[@ARGV[0]]`;
print @c[rand($#c)];
```
Possibly a little off topic, but maybe so.
```
s153254@helios:/home/s153254/lab$ perl code.p 1
telnet
s153254@helios:/home/s153254/lab$ perl code.p 2
in.rlogind
s153254@helios:/home/s153254/lab$ perl code.p 2
df
s153254@helios:/home/s153254/lab$ perl code.p 3
svenv
```
[Answer]
## Ruby → Brainfuck (110 107 characters)
```
s="";m=%w:< > . , + -:;rand(99).downto(r=0){s<<(rand(40)==0? (r+=1)&&'[%s':'%s')%m.shuffle[0]};p(s<<']'*r)
```
### Usage
```
$ ruby bf.rb
```
Produces an executable brainfuck program.
Sort of a shameless ripoff of ESultanik's, so I will credit him for the idea.
* Changed .zero? to ==0
[Answer]
## Javascript -> Brainf\*ck: 119 chars
```
s=prompt();a=["+","-",">","<",".",",","[-]"];i=0;b="";while(i++<s*s){b+=a[Math.floor(((Math.random()*s)%1)*7)]}alert(b)
```
Sample I/O:
```
10
.--.+,-><->.<+.[-].->.>[-][-]<+,[-]>><-[-]>,,>>[-].-+<[-]+>,<[-][-]<<[-]<[-]+,+[-][-][-].-[-],[-]>.<<[-]-..<-.->.++,>+-[-],.[-]..+,<-[-].+-[-]
11
,..[-]--,[-].,[-]>[-]->..[-]<,<..>[-]<>++-.[-].,,<[-].<+<[-]>-->[-]+-[-]+>-[-][-]>-,[-]->>-,-..++<+,,-,.,[-]->[-]<,+[-][-]+.,-,>+->.[-],.>..,++,.[-],+[-]-,.,--.--,
```
The code could definitely be shorter, but some things would, IMHO, make it less interesting. But if someone else comes up with a shorter program, I'll cut down more.
[Answer]
## Python -> [Fractran](http://en.wikipedia.org/wiki/FRACTRAN) (117)
```
import random as r,sys
r.seed(int(sys.argv[1]))
z=r.randint
print','.join(`z(1,99)`+'/'+`z(1,99)`for q in[0]*z(1,99))
```
[Answer]
### Python -> Python, 148 chars
Longer than the other Python entries at the expense of being (subjectively) a little more interesting.
```
import sys as s,random as r
w,o=s.stdout.write,__builtins__
r.seed(s.argv[1])
w('print\\')
for i in'\n....':n=r.choice(dir(o));o=getattr(o,n);w(i+n)
```
This prints a deeply nested attribute of a built-in object.
```
$ python randprog.py 1
print\
round.__setattr__.__delattr__.__init__.__class__
```
[Answer]
## PowerShell, generating PowerShell – 43
In the spirit of Keith's solution:
```
-join(0.."$input"|%{'-','+'|random;random})
```
generates random expressions of additions and subtractions:
```
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
+2-0-0+3-7
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
-7+1+7+1-5+2+8
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
-1+7+7-0-6-0-2
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
+2-6-5+3-2+7
PS> -join(0..(random 9)|%{'-','+'|random;random 9})
-6
```
[Answer]
## Game Maker Language -> Arduino or Ti84-Basic, 63 characters
```
a=argument0;if a mod 2{return("void setup(){Serial.begin(9600);}void loop(){Serial.print"+string(a*random(9))+";delay("+string(floor(random(999)))+")}"}else{return(":Lbl A:Horizontal "+string(a*random(9))+":Goto A")}
```
Explanation:
`a=argument0` Puts the input into variable `a`
`if a mod 2` Basically, half the chance the program will be Arduino, half Ti-Basic 84
The Arduino program outputs random stuff at random intervals, randomly skipping random things.
The Ti-Basic Program draws horizontal lines like crazy.
Also, there is a bonus - the generated programs are already golfed! Not sure if that would be helpful...
[Answer]
**Perl -> HQ9+ (42 Characters)**
```
$a="HQ9+";for(1..<>%4){chop$a}print chop$a
```
Example input
```
4264532623562346
```
Output
```
Q
```
[Answer]
**JavaScript -> Javascript (44 characters)**
```
alert('alert("'+Math.random()*prompt()+'")')
```
And with **43** characters, it can execute the generated program instead of displaying it's source:
```
eval('alert("'+Math.random()*prompt()+'")')
```
Examples:
Seed: 5
Executed 3 times:
```
alert("2.335241624386981")
alert("0.4577956395223737")
alert("0.8359265828039497")
```
] |
[Question]
[
# Intro
Beauty lies in the eye of the beholder. Output lies in the choice of the compiler. There are some codes that give different outputs based on what language they are executed in. Take for instance, the code given below:
```
# include <stdio.h>
# define print(a) int main(){printf("C is better"); return 0;}
print("Python is better")
```
When executed in C, it prints "C is better". When using a python interpreter, it prints "Python is better".
# Challenge
The challenge is a modification of the FizzBuzz challenge. Write a code that gives different outputs based on language it is executed in. When executed with the first language, it prints all numbers from 1 to 1000 (both inclusive) which are not divisible by 2. If a number is divisible by 2, it outputs "FizzBuzz". When executed with the second language, if a number is not divisible by 3, it is printed. Else, the string "FizzBuzz" is printed.
# Example
Output when executed in language 1 would be
```
1 FizzBuzz 3 FizzBuzz 5 FizzBuzz 7 FizzBuzz 9 FizzBuzz ... (upto FizzBuzz 999 FizzBuzz)
```
Output when executed in language 2 would be
```
1 2 FizzBuzz 4 5 FizzBuzz 7 8 FizzBuzz 10 11 FizzBuzz 13 14 FizzBuzz ... (upto 998 FizzBuzz 1000)
```
# Optional Challenge
You can optionally allow the program to execute in more than 2 languages. For the ith language, every multiple of (i+1) is substituted with FizzBuzz. It isn't necessary, but at least 2 languages are compulsory.
# Constraints
Need to write a fully functioning code. For instance, a method/function/procedure alone (which could not independently execute) would not be acceptable
Can use only 1 file
All outputs to be printed to standard output (not to standard error)
All other standard rules of code-golf apply
**EDIT**: Fixed a loophole:
No taking of user inputs during execution
**Edit** I got a comment saying the question wasn't clear if a non-empty separator is mandatory between the numbers. Assume it's not mandatory
# Scoring
Total score = Number of bytes in the program.
# Winning
Consider different participation brackets (based on number of languages being used). Person with least characters in each bracket can be considered a winner.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) / [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b) / [2sable](https://github.com/Adriandmen/2sable), 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
3°Lv®dтнOÌyDrÖi"FizzBuzz"},
```
[2: Try it online in 2sable.](https://tio.run/##MypOTMpJ/f/f@NAGn7JD61IuNl3Y63@4p9Kl6PC0TCW3zKoqp9KqKqVanf//AQ)
[3: Try it online in 05AB1E.](https://tio.run/##yy9OTMpM/f/f@NAGn7JD61IuNl3Y63@4p9Kl6PC0TCW3zKoqp9KqKqVanf//AQ)
[4: Try it online in 05AB1E (legacy).](https://tio.run/##MzBNTDJM/f/f@NAGn7JD61IuNl3Y63@4p9Kl6PC0TCW3zKoqp9KqKqVanf//AQ)
**Explanation:**
Let's start with a bit of history of these three languages. The development of 05AB1E started at the start of 2016 (or actually, the very first git-commit was on December 21st, 2015). This new codegolf language was being built in Python as backend. Mid 2016 2sable was branched of the 05AB1E version (July 7th, 2016 to be exact), and the strength of 2sable in comparison to that old 05AB1E version was added: implicit inputs. Later on implicit input was also added to 05AB1E, and 2sable was basically a forgotten version right after it was created on that day July 7th, 2016.
Then in mid-2018, a new 05AB1E version was being started, this time completely rewritten in Elixir instead of Python, with loads of new builtins added and some builtins changed or even removed.
So, let's go over the code and see what it does in each of the three languages:
```
3° # Push 10^3: 1000 (NOTE: I'm unable to use builtin `₄` for
# 1000, since it wasn't available in 2sable yet)
Lv # Loop `y` in the range [1,1000] (NOTE: I'm unable to use
# builtin `E` for the [1,n] loop, since it wasn't available
# in 2sable nor the legacy version yet)
® # Push -1
d # 2sable: check if -1 only consist of digits (falsey / 0)
# 05AB1E (legacy): check if -1 is an integer (truthy / 1)
# New 05AB1E: check if -1 is non-negative ≥0 (falsey / 0)
т # 2sable: no-op, so does nothing
# 05AB1E (legacy) / new 05AB1E: push 100
н # Pop and push its first character
# 2sable: does this for the 0 of the `d` falsey result
# 05AB1E (legacy) / new 05AB1E: 100 → 1
O # Sum all values on the stack:
# 2sable: 0
# 05AB1E (legacy): 2 (1+1)
# New 05AB1E: 1 (0+1)
Ì # Increase it by 2
# 2sable: 2
# 05AB1E (legacy): 4
# New 05AB1E: 3
yD # Push the loop value `y` two times
r # Reverse the values on the stack
Öi } # If `y` is divisible by the value we calculated earlier:
"FizzBuzz" # Push string "FizzBuzz"
, # Pop and print the top value with trailing newline
```
Note: the `O` to sum the stack will also add the previous value that was divisible (since we've duplicated it with `D`, but only popped and printed `"FizzBuzz"`). But since we know it's divisible, the increased sum in that next iteration doesn't make a difference to the divisibility check.
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/)/[Ruby](https://www.ruby-lang.org/), ~~80~~ ~~79~~ 75 bytes
```
print&!1.upto(1e3)do|i|puts i%3<1?"
*,(i,'FizzBuzz',i=1,999,2)!"[7,8]:i
end
```
[Try it online!](https://tio.run/##S8svKilKzNNNT4Mw/v8vKMrMK1FTNNQrLSjJ1zBMNdZMya/JrCkoLSlWyFQ1tjG0V@LS0tHI1FF3y6yqciqtqlLXybQ11LG0tNQx0lRUijbXsYi1yuRKzUv5/x8A "Fortran (GFortran) – Try It Online") (Fortran), [Try it online!](https://tio.run/##KypNqvz/v6AoM69ETdFQr7SgJF/DMNVYMyW/JrOmoLSkWCFT1djG0F6JS0tHI1NH3S2zqsqptKpKXSfT1lDH0tJSx0hTUSnaXMci1iqTKzUv5f9/AA "Ruby – Try It Online") (Ruby)
The Fortran compiler just sees
```
print&
*,(i,'FizzBuzz',i=1,999,2)
end
```
(`!` is the comment character in Fortran). The Ruby interpreter sees the full program, but we hide the otherwise invalid (Fortran) syntax at the start of the second line by wrapping it in a string.
[Answer]
# [Python 2](https://docs.python.org/2/)/[Python 3](https://docs.python.org/3/), ~~81~~ ~~61~~ ~~57~~ 54 bytes
-20 with thanks to @KevinCruijssen
-4 with thanks to @dingledooper for the idea (prints from 1000 to 1)
-3 with thanks to @Ayxan by losing an unneeded `int`
```
x=1000
while x:print((x,'FizzBuzz')[x%(3/2*2)<1]);x-=1
```
Uses the differences of the `/` operator in Python 2 and 3. In Python 2 `3/2` is `1` (integer division) while in Python 3 it is `1.5`.
[Try it online (Python 2)!](https://tio.run/##K6gsycjPM/r/v8LW0MDAgKs8IzMnVaHCqqAoM69EQ6NCR90ts6rKqbSqSl0zukJVw1jfSMtI08YwVtO6QtfW8P9/AA "Python 2 – Try It Online")
[Try it online (Python 3)!](https://tio.run/##K6gsycjPM/7/v8LW0MDAgKs8IzMnVaHCqqAoM69EQ6NCR90ts6rKqbSqSl0zukJVw1jfSMtI08YwVtO6QtfW8P9/AA "Python 3 – Try It Online")
# [Python 2](https://docs.python.org/2/)/[Python 3](https://docs.python.org/3/), 81 bytes
```
import sys
print([(x,'FizzBuzz')[x%sys.version_info[0]<1]for x in range(1,1001)])
```
[Try it online (Python 2)!](https://tio.run/##Dck7DoAgDADQ3VOwGCExBpydHLwEIcbBTwdbUtAAl0ff@nyOF@FYK9yeOIqQQ@MZMEorU98tUMr8lNIpm9r/hnfnAIQr4EFWu8m4g1gkASh4w3OXpjdaG@VUrR8 "Python 2 – Try It Online")
[Try it online (Python 3)!](https://tio.run/##Dcm9CoAgEADgvadwiRQilNamhl5CJBr6uaE7OS3Ul7e@9fM5XoRjrXB74ihCDo1nwCitTH23QCnzU0qnbGr/G96dAxCugAdZ7SbjDmKRBKDgDc9dmt5obZRTtX4 "Python 3 – Try It Online")
Although it is longer, I am keeping the original as I think it is pretty cool the way the version numbers tie in with the the requirement for 2nd and 3rd elements :-)
[Answer]
# [Perl 4](https://www.perl.org/), ~~54~~ 48 bytes
```
for(;$i++<1e3;){print$i%(2+true)?$i:'FizzBuzz';}
```
[Try it online!](https://tio.run/##K0gtyjH5/z8tv0jDWiVTW9vGMNXYWrO6oCgzr0QlU1XDSLukqDRV014l00rdLbOqyqm0qkrduvb/fwA "Perl 4 – Try It Online")
# [PHP](https://php.net/), ~~54~~ 48 bytes
```
for(;$i++<1e3;){print$i%(2+true)?$i:'FizzBuzz';}
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVMrW1bQxTja01qwuKMvNKVDJVNYy0S4pKUzXtVTKt1N0yq6qcSquq1K1r//8HAA "PHP – Try It Online")
Simple: uses PHP's auto conversion from boolean `true` to integer `1` while PERL doesn't
EDIT: saved 3 bytes with a leading space separator instead of a trailing one
EDIT2: saved 6 bytes by removing the separator
[Answer]
# JavaScript/PHP 5.4+, ~~83~~ 81 bytes
This was a somewhat simple, but fun challenge.
The code is really simple (outputs to the console in JavaScript and to stdout in PHP with `-r`):
```
for($i=0;$i<1e3;)[console.log,'printf'][+![]]("%s\n",++$i%(2+![])?$i:'FizzBuzz');
```
For JavaScript, outputs FizzBuzz on even numbers, while in PHP outputs in multiples of 3.
---
The code picks which function to call to output the value based on `+![]` (previously `+!'0'`).
An empty array (`[]`) (previously was `'0'` - a string with 0) is a truthy value in JavaScript, but a falsy value in PHP.
An array is an object in JavaScript, and all objects are truthy in JavaScript.
Using this, one can do `![]` to detect if the code is in JavaScript (`false`) or PHP (`true`).
Since Javascript would coerce `false` to a string, the `+` is needed to ensure it is a numeric value.
Using this same value, one can just do `2+![]`, resulting in `3` for PHP (`2+!false` = `2+true` = `3`) and `2` for JavaScript (`2+!true` = `2+false` = `2`).
That value is then used to check if it is a multiple.
The `$i=0` is required because JavaScript will throw an `Uncaught ReferenceError: $i is not defined`.
The `\n` in the output can't be replaced because newlines are line terminators in JavaScript, causing a syntax error if replaced with an actual newline.
Without the `\n`, PHP would output `"12FizzBuzz45FizzBuzz[...]"`.
JavaScript's console ignores it just fine.
[Answer]
# [Zsh](https://www.zsh.org/) `+X`/[Bash](https://www.gnu.org/software/bash/), 58 bytes
```
for i in {1..1000};{ ((i%${#-}))&&echo $i||echo FizzBuzz;}
```
[Try it online!](https://tio.run/##qyrO@J@cWKJgp5CSmpuvYGOjoO7q76b@Py2/SCFTITNPodpQT8/QwMCg1rpaQUMjU1WlWlm3VlNTTS01OSNfQSWzpgbMcMusqnIqraqyrv0P1M/FlZRYnAE2kqsKyNCOALP/AwA "Zsh – Try It Online")
This uses the `$-` parameter, which holds some options used by the shell. By default, it is `569X` in Zsh, and `hB` in Bash. Unsetting the `-X` option in Zsh results in a parameter of `569`. Since `${#-}` is the length of that parameter in both Bash and Zsh, we `%2` in Bash and `%3` in Zsh.
---
# [Zsh](https://www.zsh.org/)/[Bash](https://www.gnu.org/software/bash/), 65 bytes
```
a=(2 3)
for i in {1..1000};{ ((i%a[1]))&&echo $i||echo FizzBuzz;}
```
Zsh: [Try it online!](https://tio.run/##qyrO@P8/0VbDSMFYkystv0ghUyEzT6HaUE/P0MDAoNa6WkFDI1M1MdowVlNTTS01OSNfQSWzpgbMcMusqnIqraqyrv3/HwA "Zsh – Try It Online")
Bash: [Try it online!](https://tio.run/##S0oszvj/P9FWw0jBWJMrLb9IIVMhM0@h2lBPz9DAwKDWulpBQyNTNTHaMFZTU00tNTkjX0Els6YGzHDLrKpyKq2qsq79/x8A "Bash – Try It Online")
Zsh arrays are one-indexed, Bash arrays are zero-indexed. The surrounding `{ }` in the loop are needed in Bash, not in Zsh.
---
Normally, [options count as different languages](https://codegolf.meta.stackexchange.com/a/14339/86147). However, there is potential for abuse where the options are visible in a parameter. (Ab)Using the `$-` parameter in Zsh allows for [a **50 byte** program runnable in 45 "languages"](https://tio.run/##ZZDbTsJAEIbv@xRf0krbIKQcPKQBL4igMSqejd41ZbENtmu6RbTAs9cWEGLczMXO/81M/plMBbnvpZwwEpGsZyqg08HsDwdmPpYJIda8Ua83HMdZ2pYV7hl6zbYrFeEHEiNcLFafQZhlvWmW5UWfppVDaj7muqZmappO3/MD5Jg0EEoQKry4CDUTyT7T2JdRJOKUVKKEcMuGa7o0XU0vh1UPDrf2fllry/6h9gbt9HITH@uiwA/M6HPKC/c0GTOgzTEtzrgh4A2PEQ5DjpjwyC0NzrnkmTueEHzyxTfvfJCQ0uPKnqMzkrGZMpPJxCUm4hWlUTz5kVa7hq@tko03qhh6Ady1uLqVUeQ7t8vNBf@o@Q8) (N = 2..46)
[Answer]
# [Perl 5](https://www.perl.org/), ~~60~~ 54 bytes
```
for(;$i++<1e3;){print$i%(-1**2+3+true)?$i:'FizzBuzz';}
```
[Try it online!](https://tio.run/##K0gtyjH9/z8tv0jDWiVTW9vGMNXYWrO6oCgzr0QlU1VD11BLy0jbWLukqDRV014l00rdLbOqyqm0qkrduvb/fwA "Perl 5 – Try It Online")
# [PHP](https://php.net/), ~~60~~ 54 bytes
```
for(;$i++<1e3;){print$i%(-1**2+3+true)?$i:'FizzBuzz';}
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVMrW1bQxTja01qwuKMvNKVDJVNXQNtbSMtI21S4pKUzXtVTKt1N0yq6qcSquq1K1r//8HAA "PHP – Try It Online")
# [Perl 4](https://www.perl.org/), ~~60~~ 54 bytes
```
for(;$i++<1e3;){print$i%(-1**2+3+true)?$i:'FizzBuzz';}
```
[Try it online!](https://tio.run/##K0gtyjH5/z8tv0jDWiVTW9vGMNXYWrO6oCgzr0QlU1VD11BLy0jbWLukqDRV014l00rdLbOqyqm0qkrduvb/fwA "Perl 4 – Try It Online")
Another answer, a bit longer with 3 languages!!!
still the same difference with `true` between PHP and PERL, but in PERL 5 and PHP `**` takes precedence over the opposite operator `-`, while the contrary in PERL 4
EDIT: saved 6 bytes by removing the separator
[Answer]
# R (various versions); 74,626 languages; 61 bytes
```
z=1:1000;z[z%%as.double(R.version$`svn rev`)==0]="fizzbuzz";z
```
This answer may be ruled to be illegal depending on whether different svn revisions count as different languages or not.
(Is there a more efficient way to convert text to numeric than `as.double` that will work with the oldest versions of R? I feel like there is, but I cannot remember it.)
This program will continue to work as long as R continues to release versions and the number of languages will increase. I ran this using R 3.5.0.
Haven't included 74,626 TIO links for obvious reasons. [here](https://tio.run/##K/r/v8rW0MrQwMDAuiq6SlU1sVgvJb80KSdVI0ivLLWoODM/TyWhuCxPoSi1LEHT1tYg1lYpLbOqKqm0qkrJuur/fwA) is one for a recent version of R, but it is not very interesting as it is >1000 in the list, so there are no actual instances of fizzbuzz.
[Answer]
# [Befunge-98](https://github.com/catseye/FBBI) / [Befunge-93](https://github.com/catseye/FBBI), 55 bytes
```
1+:.:"}"8*-!#@_5j$1+:.1+" zzuBzziF",,,,,,,,,:"}"8*-!#@_
```
[Try it in 98!](https://tio.run/##S0pNK81LT9W1tPj/31DbSs9KqVbJQktXUdkh3jRLBSRiqK2kUFVV6lRVlemmpAMDSOr@/wcA "Befunge-98 (FBBI) – Try It Online")
[Try it in 93!](https://tio.run/##S0pNK81LT9W1NNZNS0rK/P/fUNtKz0qpVslCS1dR2SHeNEsFJGKoraRQVVXqVFWV6aakAwNI6v7/BwA "Befunge-93 (FBBI) – Try It Online")
This is based on the introduction of `j`ump in Befunge 98. By jumping in 98 the part `1+:.` (add `1`, duplicate, print) is only executed in Befunge 93.
[Answer]
# [C 89 (gcc)](https://gcc.gnu.org/)/[C 99 (gcc)](https://gcc.gnu.org/) 64 bytes
```
i;main(){while(i++<1e3)printf(i%(2//**/
+1)?"%d":"FizzBuzz",i);}
```
[Try online (C 89)](https://tio.run/##S9ZNT07@/z/TOjcxM09Ds7o8IzMnVSNTW9vGMNVYs6AoM68kTSNTVcNIX19LS59L21DTXkk1RclKyS2zqsqptKpKSSdT07r2//9/yWk5ienF/3UT84ozAQ)
[Try online (C 99)](https://tio.run/##S9ZNT07@/z/TOjcxM09Ds7o8IzMnVSNTW9vGMNVYs6AoM68kTSNTVcNIX19LS59L21DTXkk1RclKyS2zqsqptKpKSSdT07r2//9/yWk5ienF/3WLS1Jsky0tAQ)
**Explanation:**
You can find an explanation on how this works [here](https://stackoverflow.com/a/12890117/10147399).
[Answer]
# [Io](http://iolanguage.org/)/[Erlang (escript)](http://erlang.org/doc/man/escript.html), 134 bytes
Outputs a string as a list of codepoints in Erlang. Halts with an error in Io.
```
1%1+1000 repeat(i,if((i+1)%2<1,"FizzBuzz",i+1)println)
main(_)->io:write([if I rem 3<1->"FizzBuzz";1<2->I end||I<-lists:seq(1,1000)]).
```
[Try it online! (in Io)](https://tio.run/##RY1BCsMgEADvfYUEAivR4qa3VDz0EPANpZRADSwkJlVLQPJ325x6HZgZWkrBGhtUSrHgVjckIEEjADXI61ajqHrK@fbJuRIHWwP5NHl@mgfy8OTS0NJtgZKDO43M/iozu2iU5i9eUbfSWOb8a9@tlhPFFLvo3oDiOPMHP5fyBQ)
[Try it online! (in Erlang)](https://tio.run/##RY1BCsIwEADvviIUCglNJFtvbejBg5A3iEjRrSyksSYRIfTv0Z68DswMBjf6h8J4C7SkUqCGBrTWLOCCY@IkaeKcGhB1a0BWJ8r5@M65khtbAvnkvNjNI3l@FWqgZ/cJlJCfaWL2V5nZwYAa/mIPplWDZejv62qNchRT7CK@OMjtLC5iX8oX "Erlang (escript) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 58 bytes
```
for(i=0;i++<1e3;)console.log(i%(2+(this>{}))?i:'FizzBuzz')
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/Lb9II9PWwDpTW9vGMNXYWjM5P684PydVLyc/XSNTVcNIW6MkI7PYrrpWU9M@00rdLbOqyqm0qkpd8/9/AA "JavaScript (Node.js) – Try It Online")
# [JavaScript (V8)](https://v8.dev/), 58 bytes
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPT1sA6U1vbxjDV2FozOT@vOD8nVS8nP10jU1XDSFujJCOz2K66VlPTPtNK3S2zqsqptKpKXfP/fwA "JavaScript (V8) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~136~~ ~~133~~ 130 bytes
Saved 3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Saved 3 bytes thanks to [Abhay Aravinda](https://codegolf.stackexchange.com/users/94904/abhay-aravinda)!!!
```
#define print(a)i;main(){for(;i++<1e3;)printf(i%3?"%d":"FizzBuzz",i);}
print(''.join(i%2and`i`or"FizzBuzz"for i in range(1,1001)))
```
[Try it online!](https://tio.run/##RYy7CsIwFIZ3nyJEQnNokabdjCA4@BwNJNFf8KSEOhjx2WPRwfm7zM/lmniodetDBAcxZ/CiHcHeHVjTK6asLdr2YMJo6YujhhqPUnm5l2eUcnqUIjuQfW9@edPsbmmtoQbHfsKU8l9chwICLLLjS9CmM31viKjWDw "Python 2 – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), ~~136~~ ~~133~~ 130 bytes
Saved 3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Saved 3 bytes thanks to [Abhay Aravinda](https://codegolf.stackexchange.com/users/94904/abhay-aravinda)!!!
```
#define print(a)i;main(){for(;i++<1e3;)printf(i%3?"%d":"FizzBuzz",i);}
print(''.join(i%2and`i`or"FizzBuzz"for i in range(1,1001)))
```
[Try it online!](https://tio.run/##RYy7CsIwFIZ3nyJESnNolcZuRhAcfI6GXMov9ESCLhGfPRYdnL@L283O1br1IYKDuGfwQ1mCWSxY0SumrAy67qTDaOiLo0IznmXj5VFeUcrlWYrsQea9@eVtu7@ltUZzsOwnTCn/xXUoIMAiW56D0r0eBk1EtX4A "C (gcc) – Try It Online")
[Answer]
# Bash/Perl, 96 bytes
```
eval 'for i in `seq 500`;do echo $((i*2-1))FizzBuzz;done;exit';print$_%3?$_:FizzBuzz for 1..1000
```
This is based on an old Perl trick to get a Perl program to run as Perl, if executed as it were a shell program. If executed in either language, it takes the argument to `eval`, and tries to execute it (Bash) or compile, then execute it (Perl). When run as Bash, it dutifully execute the code, printing the numbers, replacing every second number with FizzBuzz, then exits. Perl, OTOH, tries to compile the string, which fails. It then carries on the execute the second statement, printing out the numbers, replacing every third with FizzBuzz.
Since non-empty separators are allowed, when executed in Bash, there will only be newlines after each FizzBuzz, while when executed in Perl, no whitespace will be outputted at all.
[Try it online!](https://tio.run/##S0oszvj/P7UsMUdBPS2/SCFTITNPIaE4tVDB1MAgwTolXyE1OSNfQUVDI1PLSNdQU9Mts6rKqbSqCiiVl2qdWpFZom5dUJSZV6ISr2psrxJvBVOgADLOUE/P0MDA4P9/AA "Bash – Try It Online") (Bash)
[Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHQT0tv0ghUyEzTyGhOLVQwdTAIME6JV8hNTkjX0FFQyNTy0jXUFPTLbOqyqm0qgoolZdqnVqRWaJuXVCUmVeiEq9qbK8SbwVToAAyzlBPz9DAwOD/fwA "Perl 5 – Try It Online") (Perl)
[Answer]
# Perl -M5.010/C (gcc -w), 112 bytes
```
//;say$_*2-1,Fizzbuzz for 1..500;<<'}';
main(){for(int i=1;i<1001;i++){i%3?printf("%d",i):printf("FizzBuzz");}
}
```
[Try it online!](https://tio.run/##S9ZNT07@/19f37o4sVIlXstI11DHLbOqKqm0qkohLb9IwVBPz9TAwNrGRr1W3ZorNzEzT0OzGiihkZlXopBpa2idaWNoYACktLU1qzNVje0LioAyaRpKqilKOpmaVjAuyFAnoKFKmta1XLX///9LTstJTC/@r1sOAA "C (gcc) – Try It Online") (C)
[Try it online!](https://tio.run/##K0gtyjH9/19f37o4sVIlXstI11DHLbOqKqm0qkohLb9IwVBPz9TAwNrGRr1W3ZorNzEzT0OzGiihkZlXopBpa2idaWNoYACktLU1qzNVje0LioAyaRpKqilKOpmaVjAuyFAnoKFKmta1XLX////LLyjJzM8r/q/ra6pnYGgAAA "Perl 5 – Try It Online") (Perl)
This hides the Perl code behind a C++ style comment, and the C code inside a Perl here doc, using the final character of the C code as the here doc terminator. The C++ style comment marker looks like an empty regular expression to Perl, which happily executes it, to no visible effect. Just as the here doc which is in void context.
The C version does not print any whitespace, the Perl version prints a newline after each `FizzBuzz`.
[Answer]
# Befunge-93/Perl -M5.010, 125108 Bytes
```
# v .: <>
say $_*2-1,# >:1+:3%|
# >:8555***-|
@
,,,,,,,,"FizzBuzz" #<^
for 1..500
```
[Try it online!](https://tio.run/##S0pNK81LT/3/X1lBoUwBCehZKSjY2HEVJ1YqqMRrGeka6igr2FkZalsZq9ZwARXbWVmYmppqaWnp1nAh61Nw4NKBAiW3zKoqp9KqKiUFZZs4rrT8IgVDPT1TA4P//wE "Befunge-93 – Try It Online")
[Try it online!](https://tio.run/##K0gtyjH9/19ZQaFMAQnoWSko2NhxFSdWKqjEaxnpGuooK9hZGWpbGavWcAEV21lZmJqaamlp6dZwIetTcODSgQIlt8yqKqfSqiolBWWbOK60/CIFQz09UwOD////5ReUZObnFf/X9TXVMzA0AAA "Perl 5 – Try It Online")
This can probably easy golfed down further, but I'm far from a Befunge expert. This code cannot be separated into different pieces of code, where each language ignores the part written in the different language -- the `,,,,,,,,"FizzBuzz"` section is used by both Perl and Befunge.
To explain it further, what Perl sees, after removing the comments, is:
```
say $_*2-1,,,,,,,,,"FizzBuzz" for 1..500
```
and what Befunge sees is:
```
# v .: <>
>:1+:3%|
>:8555***-|
@
,,,,,,,,"FizzBuzz" #<^
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~132~~ ~~128~~ ~~101~~ ~~99~~ ~~84~~ ~~82~~ 81 bytes
```
main(){for(int i;i++<1e3;)__builtin_printf(i%(2+sizeof'a'%2)?"%d":"fizzbuzz",i);}
```
[Try it online!](https://tio.run/##DclBCoAgFAXAq4QgKdYi22XQUaRM40FZlG1@dHZrtuPqxbmctxFRyCfsp0BMBQyU6hvfGmntdGNNiPY4/woCXGh1gfweyrHkWg6Mz6xjAUTTTcQqSPPm/AE "C (gcc) – Try It Online")
# [C++ (gcc)](https://gcc.gnu.org/), ~~132~~ ~~128~~ ~~101~~ ~~99~~ ~~84~~ ~~82~~ 81 bytes
```
main(){for(int i;i++<1e3;)__builtin_printf(i%(2+sizeof'a'%2)?"%d":"fizzbuzz",i);}
```
[Try it online!](https://tio.run/##DclLCoAgFAXQrYQgKdYgm2XQUqRM40KZ9Jm8aO3WmR6XUr04l/M2Igr5hP0QiFcBA6X6xrdGWjvdWC9Em46/ggAXWp0gv4dyLLmWA@Mz61gA0XQTsQrSvDl/ "C++ (gcc) – Try It Online")
~~-27~~ -28 bytes from ceilingcat (plus another inspired by ceiling cat)
-15 bytes from Ayxan
[Answer]
# [JavaScript (Node.js)](https://nodejs.org) / [Ruby](https://www.ruby-lang.org/) / [Python 2](https://docs.python.org/2/) / [Python 3](https://docs.python.org/3/) / [Perl 5](https://www.perl.org/) / [PHP](https://php.net/) + `-d short_open_tag=on -d output_buffering=on` / [Bash](https://www.gnu.org/software/bash/), 311 bytes
```
s=0;f='FizzBuzz';0//1;'''=;y=/.__id__;eval"s+=1;puts s%3>0?s:f;"*1e3;%q}<?ob_end_clean();$i=+1;for(;$i<1e3;){print((++$i%(6+true)?$i:FizzBuzz)."
");};die;#?>";while(s<1e3)console.log(++s%2?s:f)//';for i in {1..1000};{ a=($f);echo ${a[((i%8))]:-$i};} #''';exec('s+=1;print(s if s%(5if 3/2>1else 4)else f);'*1000)
```
[Try them all online!](https://tio.run/##NVHbjpswEH3nK0YsyPYibkm3qjIhkaq2j/2BqkJchmCJ2hRDt0mab09tdvM0x6PxnMvUlenvI00DxCMBa3r9awTZAemOwQGSRrcE@z37@v0Lu5siw65g3@Tl8nm5XBhmaZojY6zAc5EmZSnbskT6Uw2@iYocx2U2YMLtITuaXYf@c05bDH/f9kddl6TashmoUlxgIIsox05P3MK9mxLXcZJq5jyKAhnyj9E8LSSOgdw92EXie77AG7aS8Ol48PG1lwNx4/6LRiujB0oGfbIrTLhxCkSaMscCEqSCa54keZZlN7xCVfCgE0jWPwTX6gfnMvwkxM9dHMgb3uDJmkT6Sw1nb85WccYlZUL@Yss23RxyGgzBB7EWu449u/3ibsPzvNcG4uYtUPQ8p2Kc9MkJUS7jaanPMJ7nXqvNe93Cehh/7EeIWzC9nuZSj6TKuToVWrmmXmabclkvXUdWk2v7UNujIrTaA1gd@YGj8tG@V/R@1n/QU9VCrGDzgo/ZJEkeGL1WK7r/Bw) (truncates to the first 25 lines of each language)
I know there's no benefit to adding more languages, but I enjoyed this so thought I'd have a try at adding a few. Overall I'd like to share more of the code if possible, but the different looping structures make it pretty tricky. I'm sure there's a way I could share the Python and Ruby code to reduce some bytes, so I'll play with that more next.
# [JavaScript (Node.js)](https://nodejs.org) (with comments and unused strings removed)
```
s=0;f='FizzBuzz';0
while(s<1e3)console.log(++s%2?s:f)
```
# [Ruby](https://www.ruby-lang.org/) (with comments and unused strings removed)
```
s=0;f='FizzBuzz';0//1;'''=;y=/.__id__;eval"s+=1;puts s%3>0?s:f;"*1e3;die;
```
`0//1;.../.__id__;`: this is `0` `/` `/1;.../.__id__` where `/1;.../` is a RegExp and the `__id__` property is just a short property that exists on the RegExp object that returns a number to prevent a type error. This uses string repetition and `eval` as it was slightly shorter (but a true Rubyist might be able to correct me!).
# [Python 2](https://docs.python.org/2/) / [Python 3](https://docs.python.org/3/) (with comments and unused strings removed)
```
s=0;f='FizzBuzz';0//1;exec('s+=1;print(s if s%(5if 3/2>1else 4)else f);'*1000)
```
This uses the classic floored integer division check for Python 2 vs. 3 and string repetition the same as Ruby because it was shorter (although, again, any Pythonistas please feel free to correct me!)
# [Perl 5](https://www.perl.org/) + `-M5.10.0` (with unused strings removed/truncated)
```
s=...=...=;y=...=...=+1;for(;$i<1e3;){print((++$i%(6+true)?$i:FizzBuzz)."
");};die;
```
This uses [Perl's `s///` and `y///` (`tr///`) operators](https://perldoc.perl.org/perlop.html#Quote-and-Quote-like-Operators) to ignore most of the code. This is the same code as is used for PHP and works because there's no `true` in Perl, so the bareword `true` evaluates to `0`.
# [PHP](https://php.net/) + `-d short_open_tag=on -d output_buffering=on` (with non-executed code removed)
```
<?ob_end_clean();$i=+1;for(;$i<1e3;){print((++$i%(6+true)?$i:FizzBuzz)."
");};die;#?>
```
A bit cheaty, but uses a pretty well known technique of the `output_buffering` option and [`ob_end_clean()`](https://www.php.net/manual/en/function.ob-end-clean.php) to discard the content before the first `<?`, then `die;#?>` before the rest of the program is parsed, basically 'hiding' the PHP program within strings and comments of the others. The majority of this code is shared with Perl.
# [Bash](https://www.gnu.org/software/bash/) (with comments and unused strings removed)
```
s=0;f='FizzBuzz';0//1;for i in {1..1000};{ a=($f);echo ${a[((i%8))]:-$i};}
```
Because of how variables are set in Bash (`var=value`) we can share `f='FizzBuzz'` from the JavaScript, Ruby, Python code, but it's pretty much just on its own. The useful thing with Bash is that `'''` isn't a syntax error, it's just concatenating an empty string and the start of a new string, so Bash pretty much just 'ignores' (executes and returns an error) all the code and it's relatively easy to find a space to drop it into.
[Answer]
# [Python 2](https://docs.python.org/2/) / [Python 3](https://docs.python.org/3/) / [Octave](https://www.gnu.org/software/octave/), 109 bytes
This is an add-on to @ElPedro's [answer](https://codegolf.stackexchange.com/a/204658/73613), adding Octave to his clever solution for Python 2 and 3.
```
x=1000;
while x>0%1:print((x,'FizzBuzz')[x%(3/2*2)<1]);x-=1;"""
printf('%d FizzBuzz %d ',x,x-1)
x-=3;
end%"""
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8LW0MDAwJqrPCMzJ1Whws5A1dCqoCgzr0RDo0JH3S2zqsqptKpKXTO6QlXDWN9Iy0jTxjBW07pC19bQWklJiQusNk1DXTVFAaZYAchW16nQqdA11OQCKjS25krNS1EFqv7/HwA "Python 2 – Try It Online") (Python 2)
[Try it online!](https://tio.run/##K6gsycjPM/7/v8LW0MDAwJqrPCMzJ1Whws5A1dCqoCgzr0RDo0JH3S2zqsqptKpKXTO6QlXDWN9Iy0jTxjBW07pC19bQWklJiQusNk1DXTVFAaZYAchW16nQqdA11OQCKjS25krNS1EFqv7/HwA "Python 3 – Try It Online") (Python 3)
[Try it online!](https://tio.run/##y08uSSxL/f@/wtbQwMDAmqs8IzMnVaHCzkDV0KqgKDOvREOjQkfdLbOqyqm0qkpdM7pCVcNY30jLSNPGMFbTukLX1tBaSUmJC6w2TUNdNUUBplgByFbXqdCp0DXU5AIqNLbmSs1LUQWq/v8fAA "Octave – Try It Online") (Octave)
] |
[Question]
[
The [Juggler sequence](https://en.wikipedia.org/wiki/Juggler_sequence) is described as follows. Beginning with an input \$a\_1\$, the next term is defined by the recurrence relation
$$a\_{k+1} = \begin{cases}
\left\lfloor a\_k ^ \frac 1 2 \right\rfloor,\text{ if } a\_k \text{ is even} \\
\left\lfloor a\_k ^ \frac 3 2 \right\rfloor,\text{ if } a\_k \text{ is odd} \\
\end{cases}$$
The sequence terminates when it reaches 1, as all subsequent terms would then be 1.
## Task
Given an input \$n\$ greater than or equal to 2, write a program/function/generator/etc. that outputs/returns the respective juggler sequence. The output can be in any reasonable form. You may not use a built-in that computes the juggler sequence, or any built-in that directly yields the result. You may assume that the sequence terminates in \$1\$.
## Test Cases
```
Input: output
2: 2, 1
3: 3, 5, 11, 36, 6, 2, 1
4: 4, 2, 1
5: 5, 11, 36, 6, 2, 1
```
This is a code golf. Shortest code in bytes wins.
[Answer]
# Julia, ~~64~~ ~~50~~ ~~48~~ ~~42~~ ~~32~~ 30 bytes
```
g(x)=[x;x<3||g(x^(x%2+.5)√∑1)]
```
This is a recursive function that accepts an integer and returns a float array.
We build an array by concatenating the input with the next term of the sequence, computed as *x* to the power of its parity plus 1/2. This gives us either *x*1/2 or *x*1+1/2 = *x*3/2. Integer division by 1 gets the floor. When the condition *x* < 3 is true, the final element will be a Boolean rather than a numeric value, but since the array is not of type `Any`, this is cast to have the same type as the rest of the array.
Saved 14 bytes thanks to Dennis!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
*BṪ×½Ḟµ’п
```
*Thanks to @Sp3000 for golfing off 1 byte!*
[Try it online!](http://jelly.tryitonline.net/#code=KkLhuarDl8K94biewrXigJnDkMK_&input=&args=Mw)
### How it works
```
*BṪ×½Ḟµ’п Main link. Input: n
*B Elevate n to all of its digits in base 2.
·π™ Extract the last power.
This yields n ** (n % 2).
√ó¬Ω Multiply with sqrt(n). This yields n ** (n % 2 + 0.5).
·∏û Floor.
µ Push the previous chain on the stack and begin a new, monadic chain.
п Repeat the previous chain while...
’ n - 1 is non-zero.
Collect all intermediate results in an array.
```
[Answer]
# JavaScript (ES7), ~~45~~ 33 bytes
```
f=n=>n<2?n:n+","+f(n**(.5+n%2)|0)
```
## Explanation
Recursive approach. Returns a comma-separated string of numbers.
```
f=n=>
n<2?n: // stop when n == 1
n // return n at the start of the list
+","+f( // add the rest of the sequence to the list
n**(.5+n%2)|0 // juggler algorithm
)
```
## Test
`**` not used in test for browser compatibility.
```
f=n=>n<2?n:n+","+f(Math.pow(n,.5+n%2)|0)
```
```
<input type="number" oninput="result.textContent=f(+this.value)" />
<pre id="result"></pre>
```
[Answer]
# Mathematica, ~~40~~ 39 bytes
*Thanks to Martin Büttner for saving 1 byte.*
```
NestWhileList[‚åä#^.5#^#~Mod~2‚åã&,#,#>1&]&
```
**Test case**
```
%[5]
(* {5,11,36,6,2,1} *)
```
[Answer]
# Pyth, ~~14~~ 12 bytes
```
.us@*B@N2NNQ
```
[Demonstration](https://pyth.herokuapp.com/?code=.us%40%2aB%40N2NNQ&input=3&debug=0)
We start with a cumulative reduce, `.u`, which in this case starts at the input and applies a function until the result repeats, at which point it outputs all of the intermediate results.
The function takes the previous value as `N`. It starts by taking its square root with `@N2`. Next, it bifurcates that value on multiplication by `N` with `*B ... N`. This creates the list `[N ** .5, (N ** .5) * N]`, the unfloored results for the even and odd cases. Next, the appropriate unfloored result is selected by indexing into the list with `@ ... N`. Since Pyth has modular indexing, no out-of-bounds errors are thrown. Finally, the result is floored with `s`.
[Answer]
# MATL, ~~13~~ 12 bytes
```
`tt2\.5+^ktq
```
[Try it online!](http://matl.tryitonline.net/#code=YHR0MlwuNSteWm90cQ&input=NQ)
Explanation
```
` % do...while loop
tt % duplicate top of stack twice, takes implicit input on first iteration
2\ % take a_k mod 2
.5+^ % adds 0.5, to give 1.5 if odd, 0.5 if even, and takes a_k^(0.5 or 1.5)
kt % Rounds down, and duplicates
q % Decrement by 1 and use for termination condition---if it is 0, loop will finish
```
Thanks Luis for saving a byte!
[Answer]
## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 25 bytes
```
ndN(d$7;r2%2*1+;YdNd1=,).
```
[Try it here!](http://play.starmaninnovations.com/minkolang/?code=ndN%28d%247%3Br2%252*1%2B%3BYdNd1%3D%2C%29%2E&input=3)
### Explanation
```
n Take number from input => n
dN Duplicate and output as number
( Open while loop
d Duplicate top of stack => n, n
$7 Push 0.5
; Pop b,a and push a**b => n, sqrt(n)
r Reverse stack => sqrt(n), n
2% Modulo by 2
2* Multiply by 2
1+ Add 1 => sqrt(n), [1 if even, 3 if odd]
; Pop b,a and push a**b => sqrt(n)**{1,3}
Y Floor top of stack
dN Duplicate and output as number
d1=, Duplicate and => 0 if 1, 1 otherwise
). Pop top of stack and end while loop if 0, then stop.
```
[Answer]
## TSQL, 89 bytes
Input goes in `@N`:
```
DECLARE @N INT = 5;
```
Code:
```
WITH N AS(SELECT @N N UNION ALL SELECT POWER(N,N%2+.5) N FROM N WHERE N>1)SELECT * FROM N
```
[Answer]
# APL, ~~28~~ ~~24~~ 16 bytes
```
{⌊⍵*.5+2|⎕←⍵}⍣=⎕
```
This is a program that accepts an integer and prints the successive outputs on separate lines.
Explanation:
```
{ }⍣=⎕ ⍝ Apply the function until the result is the input
⌊⍵*.5+2|⎕←⍵ ⍝ Print the input, compute floor(input^(input % 2 + 0.5))
```
[Try it online](http://ngn.github.io/apl/web/#code=%7B%u230A%u2375*.5+2%7C%u2395%u2190%u2375%7D%u2363%3D%u2395)
Saved 8 bytes thanks to Dennis!
[Answer]
## Java 7, ~~83~~ 71 bytes
```
void g(int a){System.out.println(a);if(a>1)g((int)Math.pow(a,a%2+.5));}
```
I originally used a typical `for` loop, but I had to jump through hoops to get it working right. After ~~stealing~~ borrowing [user81655's idea](https://codegolf.stackexchange.com/a/73138/14215) to recurse instead, I got it down twelve bytes.
[Answer]
# Haskell, 70 bytes
Haskell doesn't have integer `sqrt` built-in, but I think there may be something shorter than `floor.sqrt.fromInteger`.
```
s=floor.sqrt.fromInteger
f n|odd n=s$n^3|1<2=s n
g 1=[1]
g n=n:g(f n)
```
[Answer]
# Oracle SQL 11.2, 128 bytes
```
WITH v(i)AS(SELECT :1 FROM DUAL UNION ALL SELECT FLOOR(DECODE(MOD(i,2),0,SQRT(i),POWER(i,1.5)))FROM v WHERE i>1)SELECT i FROM v;
```
Un-golfed
```
WITH v(i) AS
(
SELECT :1 FROM DUAL
UNION ALL
-- SELECT FLOOR(POWER(i,0.5+MOD(i,2))) FROM v WHERE i>1
SELECT FLOOR(DECODE(MOD(i,2),0,SQRT(i),POWER(i,1.5))) FROM v WHERE i>1
)
SELECT * FROM v;
```
Adding MOD(i,2) to .5 is shorter but there is a bug with POWER(2,.5) :
```
SELECT POWER(4,.5), FLOOR(POWER(4,.5)), TO_CHAR(POWER(4,.5)) FROM DUAL
```
gives
```
2 1 1,99999999999999999999999999999999999999
```
[Answer]
# R, ~~54~~ 51 bytes
```
z=n=scan();while(n>1){n=n^(.5+n%%2)%/%1;z=c(z,n)};z
```
Saved 3 bytes thanks to plannapus.
[Answer]
# CJam, 18 bytes
```
ri{__2%.5+#i_(}g]p
```
[**Test it here**](http://goo.gl/qI5alq)
Similar to [David's MATL answer](https://codegolf.stackexchange.com/a/73131/36398).
[Answer]
# Python 3, ~~57~~, ~~45~~, ~~43~~, 41 bytes
Better Solution with suggestion from @mathmandan
```
def a(n):print(n);n<2or a(n**(.5+n%2)//1)
```
This method will print each number on a new line
Previous Solution: Cut down to 43 bytes after xnor's recommendation
```
a=lambda n:[n][:n<2]or[n]+a(n**(n%2+.5)//1)
```
You can call the above by doing `a(10)` which returns `[10, 3.0, 5.0, 11.0, 36.0, 6.0, 2.0, 1.0]`
The above will output the values as floats. If you want them as integers, then we can just add an extra 2 bytes for 43 bytes:
```
def a(n):print(n);n<2or a(int(n**(.5+n%2)))
```
[Answer]
## TI-Basic, 30 Bytes
```
Prompt A
Repeat A=1
Disp A
int(A^(remainder(A,2)+.5->A
End
1
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
λ∷d›½e⌊;İJ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu+KIt2TigLrCvWXijIo7xLBKIiwiIiwiNSJd)
[Answer]
# JavaScript ES6, ~~109~~ 102 bytes
```
s=>(f=n=>n==1?n:n%2?Math.pow(n,3/2)|0:Math.sqrt(n)|0,a=[s],eval("while(f(s)-1)a.push(s=f(s))"),a+",1")
```
I *know* this can be golfed. Returns a string of comma-separated numbers.
[Answer]
# C++, 122 bytes
```
#include <iostream>
void f(int n){int i;while(n^1){std::cout<<n<<',';for(i=n*n;i*i>(n%2?n*n*n:n);i--);n=i;}std::cout<<1;}
```
[Answer]
# Retina, 144 bytes
Input and output are in unary.
The 2nd-to-last line contains a space, and the two middle lines and the last line are empty.
```
{`(\b|)11+$
$&¶$&
m-1=`^(?=^(11)*(1?)).*$
$&,$2
(1+),1$
$1;,
1(?=1*;)
$%_
1+;
$%_
;|,
m-1=`^
1:
+`(1+):(11\1)
1 $2:
1+:$|:1+
-1=`(1+\b)
$#1
```
[**Try it online**](http://retina.tryitonline.net/#code=e2AoXGJ8KTExKyQKJCbCtiQmCm0tMT1gXig_PV4oMTEpKigxPykpLiokCiQmLCQyCigxKyksMSQKJDE7LAoxKD89MSo7KQokJV8KMSs7CiQlXwo7fCwKCm0tMT1gXgoxOgorYCgxKyk6KDExXDEpCjEgJDI6CjErOiR8OjErCgotMT1gKDErXGIpCiQjMQogCg&input=MTEx)
### Explanation
```
{`(\b|)11+$ # Loop, Duplicate last line
$&¶$&
m-1=`^(?=^(11)*(1?)).*$ # Append ,n%2 to that line (number modulo 2)
$&,$2
(1+),1$ # Cube that number if odd
$1;,
1(?=1*;)
$%_
1+;
$%_
;|, # (Last stage of cubing number)
m-1=`^ # Integer square root of that number,
1: # borrowed and modified from another user's answer
+`(1+):(11\1)
1 $2:
1+:$|:1+
-1=`(1+\b)
$#1
```
[Integer square root in Retina](https://codegolf.stackexchange.com/a/82632/34718), by Digital Trauma
[Answer]
# C, ~~64~~ ~~63~~ 61 bytes
```
t;q(n){for(;!t;n=pow(n,.5+n%2))printf("%d%c ",n,n^1?44:t++);}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~14~~ 12 bytes
```
U¬°o‚åä?^1.5‚àö%2
```
[Try it online!](https://tio.run/##yygtzv7/P/TQwvxHPV32cYZ6po86Zqka/f//3xQA "Husk – Try It Online")
## Explanation
```
U¡ȯ⌊?^1.5√%2
¬° iterate over the input infinitely, creating a list
ȯ with the following three functions:
take the previous result
%2 modulo 2
?^1.5 if truthy, raise to 3/2th power
‚àö else take square root
‚åä floor the result
U cut the list at fixed point
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Δ=DÉ·>;mï
```
-3 bytes thanks to *@ovs*.
Outputs each result on a separate line.
[Try it online](https://tio.run/##yy9OTMpM/f//3BQX28Odh7bbWeceXv//vzEA) or [verify some more test cases](https://tio.run/##yy9OTMpM/R8ZcnRHmZJnXkFpiZWCkn2lDpeSf2kJhKdT@f/cFFuXw52HtttZ5x5e/7/20Db7/wA).
**Explanation:**
```
Δ # Loop until the result no longer changes:
= # Print the current value with trailing newline (without popping)
# (which will be the implicit input-integer in the first iteration)
D # Duplicate the value
É # Pop the copy, and check if it's odd (1 if odd; 0 if even)
· # Double that
> # Increase it by 1
; # Halve it
m # Take the current value to the power this 1/2 or 3/2
ï # And then cast it to an integer to floor it
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
*Ḃ×½ḞµƬ
```
[Try it online!](https://tio.run/##y0rNyan8/1/r4Y6mw9MP7X24Y96hrcfW/D/cnvWocZ@OwsOda0EMKwXNyP//jXQUjHUUTHUUzAA "Jelly – Try It Online")
Basically Dennis' method, but updated to use the modern version of Jelly. I initially had [9 bytes](https://tio.run/##y0rNyan8/1/r4Y6mhzuWPGqY4XFs08Md8451HVvzX@dwe9ajxn06Cse6QLSVgmbk//9GOgrGOgqmOgpmAA), but switching to the `√ó¬Ω` method saved 2 bytes.
## How it works
```
*Ḃ×½ḞµƬ - Main link. Takes n on the left
µ - Group the previous links into a monad f(n):
Ḃ - Bit; n % 2
* - n ** (n % 2)
¬Ω - n ** (1 / 2)
√ó - n ** (n % 2 + 1 / 2)
·∏û - Floor
Ƭ - Repeatedly apply f(n), yielding [n, f(n), f(f(n)), ..., 1]
```
[Answer]
# [Factor](https://factorcode.org/), 52 bytes
```
[ [ 3 dupn . odd? 3/2 .5 ? ^ 1 /i dup 1 > ] loop . ]
```
[Try it online!](https://tio.run/##JYrBCsIwEAXv/Yr3BSkavCjYo3jxUjyVCkuSajBuwro96M/HqrdhZiZymqWe@@PpsMU1cBBK8U0aMz9xD8Ih4UF6Q5Gg@ioSWX/CTDO7/7ZrGlsHDLDwc2EYZO872HYNs0GHC1Zo47ctsMeIlHNZrrE6Sql@AA "Factor – Try It Online")
[Answer]
# [Lua](https://www.lua.org/), 49 bytes
```
b=...repeat a=b print(a)b=b^(.5+b%2)//1until a==b
```
[Try it online!](https://tio.run/##yylN/P8/yVZPT68otSA1sUQh0TZJoaAoM69EI1EzyTYpTkPPVDtJ1UhTX9@wNK8kMweowDbp////xgA "Lua – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 55 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 6.875 bytes
```
‚à∑.+e‚åä)‚Üî
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwi4oi3Litl4oyKKeKGlCIsIiIsIjMiXQ==)
## Explained
```
∷.+e⌊)↔­⁡​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌­
)↔ # ‎⁡Generate until fixed point, starting with the input:
∷.+ # ‎⁢ Add the bit parity of the argument to 0.5 (0.5 if even, 1.5 if odd)
e # ‎⁣ And raise the argument to that number
⌊ # ‎⁤ Floor it.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 7.5 bytes (15 nibbles)
```
`.$^^$^3%$~-2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWaxP0VOLiVOKMVVXqdI0gYlCppdFKxkqxUA4A)
```
`. # iterate while unique
$ # starting with input:
%$~ # result-so-far modulo-2
^3 # 3 to the power of that (so: 3 or 1)
^$ # result-so-far to the power of that
^ -2 # floor square-root
```
[Answer]
# TI BASIC, 43 bytes
I'm pulling a Thomas Kwa and answering this one on my mobile.
```
Input N
Repeat N=1
Disp N
remainder(N,2->B
If not(B:int(sqrt(N->N
If B:int(N^1.5->N
End
1
```
Replace `sqrt` with the actual symbol on your calculator. Displays a linefeed separated list of numbers, which is a reasonable format.
[Answer]
# JavaScript ES6, 76 bytes
Is a generator named `j`. To use, set `a = j(<your value>);`. To see the next value in the sequence, enter `a.next().value`.
```
function*j(N){for(yield N;N-1;)yield N=(N%2?Math.pow(N,3/2):Math.sqrt(N))|0}
```
Ungolfed:
```
function* juggler(N){
yield N;
while(N!=1){
N = Math.floor(N % 2 ? Math.pow(N,3/2) : Math.sqrt(N));
yield N;
}
}
```
] |
[Question]
[
You should write a program or function that receives a positive integer `N` as input and prints out the first `N` characters of your code. If `N` is larger than the length of your code you should continue output your code cyclically.
Reading your source code in any way and reading from file, stdio, etc. are disallowed.
## Examples
(assuming your code is `yourcode`)
Input => Output:
`5` => `yourc`
`10` => `yourcodeyo`
`22` => `yourcodeyourcodeyour`
## Clarification
Your program should be at least 1 byte long.
[Answer]
## Python 2, 61 bytes
```
def f(n):a='def f(n):a=%r;print(a%%a*n)[:n]';print(a%a*n)[:n]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0/TKtFWHYmtWmRdUJSZV6KRqKqaqJWnGW2VF6sOF4KJ/E/TMDTV5AILc6VpmCCxzQw1/wMA)
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 49 bytes
```
'3d*}r0ff+0i:&0(?.~~a*&"0"-+60.&~:?!;1-&:o}&" "0.
```
Half the code is converting the input from a string to an int. If we're allowed to use the code point of a single char read from STDIN instead, then this program would be much shorter at 21 bytes:
```
'3d*}ri:?!;1-&:o}&60.
```
## Explanation
I'll use the second program for the explanation.
`'` starts string parsing, pushing every char until a closing quote is found. Since the rest of the line has no `'` quote, every char except the initial `'` is pushed onto the stack.
But ><> is a toroidal 2D language, so after the line is over the instruction pointer wraps back to the start, hitting the `'` again and *stops* string parsing. The result is that we've pushed everything necessary except the initial quote, namely
```
3d*}ri:0=?;1-&:o}&60.
```
`'` is ASCII 39, so we push the initial quote by pushing `3d* = 3*13 = 39`. We then shift the stack right (`}`) and reverse (`r`), giving:
```
.06&}o:&-1;?=0:ir}*d3'
```
Now we're all set up to start printing. `i` reads in a char of input, but ><> chars are basically integers. In the first program, the `i` is replaced with a loop that converts a digit string from STDIN into an integer.
We then execute the following loop to print out the first N chars:
```
:?!; If the top of the stack (N) is 0, then terminate
Otherwise...
1- Subtract 1 from N
& Move N to the register temporarily
:o Output the next char in the program
} Shift the stack right
& Put N back on the stack
60. Repeat loop by jumping back to the first :
```
[Answer]
# CJam, ~~34 17~~ 16 bytes
This can be golfed a lot..
```
{`"_~"+ri_@*<}_~
```
**Code expansion**:
```
{`"_~"+ri_@*<}_~
{ }_~ "Put this code block on stack, take a copy and execute the copy";
` "When executed, this block will the top element on stack to a string";
"_~" "Then put this string on stack";
+ "Concat it to the the previous string on stack which ` created";
ri "Read an integer from STDIN";
_@ "Copy the integer and put the concatinated string on top of stack";
* "Repeat the string input number of times";
< "Take the first input number of characters from the repeated string";
```
Finally, anything on stack gets printed to STDOUT automatically
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# Python 2, 117 bytes
```
b=input();a=lambda x:(b*(2*(x+chr(34))+')'))[:b];print a("b=input();a=lambda x:(b*(2*(x+chr(34))+')'))[:b];print a(")
```
Life protip: don't execute `list(itertools.cycle(x))`. For some reason, I can't imagine why, it crashes the interpreter.
[Answer]
# JavaScript (ES6), ~~65~~ ~~52~~ ~~50~~ ~~47~~ ~~41~~ 39
```
q=n=>('q='+q).repeat(n/39+1).slice(0,n)
```
Uses ES6 `repeat()` to clone the code, then slices down. Uses a hardcoded length.
---
Old version (50):
```
q=n=>n>(l=(t='q='+q).length)?t+q(n-l):t.slice(0,n)
```
Creates a function `q`, taking a single parameter.
It stringifies the function text, and recursively calls the function if `n` is greater than the text's length. Otherwise, it returns a substring of the text.
Non ES6 version (65):
```
function q(n){return t=q+'',l=t.length,n>l?t+q(n-l):t.slice(0,n)}
```
[Answer]
# J - 24 char
Takes a single positive integer argument and spits out a string.
```
($],quote)&'($],quote)&'
```
J doesn't have any self-reference tricks, so we just do it the quine way. Explained by explosion:
```
],quote NB. right arg prepended to quotation of right arg (quine)
$ NB. cyclically take left-arg characters from that
( )&'($],quote)&' NB. preload right arg with ($],quote)&
```
The dyadic `$` operator in J cyclically takes items from its right argument to fit the dimensions specified on the left. When the dimension is a single number, this is a simple 1D list of characters, so we do exactly what the question asks.
Try it for yourself at [tryj.tk](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%28%24%5D%2Cquote%29%26%27%28%24%5D%2Cquote%29%26%27%2030).
[Answer]
# k2 - 7 char
```
{x#$_f}
```
In English, this is a function with argument `x` whose definition is "`x` take string self".
* *Self* (the noun `_f`) is the innermost currently executing function. Here it is the function `{x#$_f}`.
* *String* (monadic `$`) converts its argument to a string. In the case of a function, it creates a string with the function's original definition.
* *Take* (dyadic `#`) takes *left-arg* items form the list in *right-arg*. In the case of a string, the items are characters, so this is doing exactly what we want.
This *will not* work in the open-source Kona, because it seems to create black holes which eat all attempts to use them as arguments to anything. I am unsure of proper k3 semantics but they are probably not much kinder.
In Q, this is `{x#string .z.s}` and in k4 `{x#2_$.z.s}`. We have to use `2_` to drop two initial characters in k4, for reasons only a mother could love.
[Answer]
# Ruby, ~~66 64~~ 63 bytes
```
eval s=%q(puts"eval s=%q(#{s})".chars.cycle.take(gets.to_i)*'')
```
The same using a function to avoid calling `gets` is a bit longer (81 bytes):
```
def f(i);eval s=%q(puts"def f(i);eval s=%q(#{s});end".chars.cycle.take(i)*'');end
```
Lambda versions of the same are 69 and 65 bytes:
```
l=->i{eval s=%q(puts"l=->i{eval s=%q(#{s})}".chars.cycle.take(i)*'')}
->i{eval s=%q(puts"->i{eval s=%q(#{s})}".chars.cycle.take(i)*'')}
```
[Answer]
# Mathematica, 65 bytes
```
Print[StringTake[StringJoin @@ Table[ToString[#0], {#1}], #1]] &
```
All spaces is necessary to make this a proper quine, including the trailing one. This is a pure function, which you can use as follows:
```
Print[StringTake[StringJoin @@ Table[ToString[#0], {#1}], #1]] & [75]
```
which prints
```
Print[StringTake[StringJoin @@ Table[ToString[#0], {#1}], #1]] & Print[Stri
```
Unfortunately, applying `ToString` to a function doesn't yield exactly the way you entered the function, so I can't shorten this by removing whitespace, shortening `#1` to `#` or using prefix notation for function calls.
[Answer]
# MATLAB, ~~319~~ 141 characters
I managed to squeeze a few bytes from the original one:
```
function d=g(n);d='gvodujpo!e>h)o*<e>(<e>\e)2;2:*.2-e-e)2:;foe*.2^<e>e)2,npe)1;o.2-252**<';d=[d(1:19)-1,d,d(19:end)-1];d=d(1+mod(0:n-1,141));
```
[Answer]
# JavaScript, 34 bytes
```
f=n=>n&&('f='+f+f(n-1)).slice(0,n)
```
Recursive function that repeats the code `n` times, then slices the result.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 bytes
```
îî
```
[Try it online!](https://tio.run/##y0osKPn///C6w@v@/zcGAA "Japt – Try It Online")
The first `î` is a number method that takes one parameter, and repeats it to length `n`. Because it is the first method, `n` becomes the input. The second `î` gets cast into a string, and gets repeated.
This transpiles to:
`n.î("î")` -> Repeat `"î"` until it reaches length `n`
## 8 byte solution
```
îQi"îQi"
```
[Try it online!](https://tio.run/##y0osKPn///C6wEwlMPH/vykA "Japt – Try It Online")
`îQi"îQi"` transpiles to `n.î(Qi"îQi")`
```
n.î(Qi"îQi")
"îQi" // String "îQi" -> îQi
Qi // Insert " -> îQi"
n.î // Repeated to length n -> îQi"îQi"îQi" (n=12)
```
[Answer]
# R, 203 bytes
When N = 203, the code fully print itself.
```
(f <- function(N){
str <- paste0("(f <- function(N)", paste0(as.character(body(f)), collapse = "\n"), ")}(", N, ")")
cat(rep(str, floor(N/nchar(str))), sep = "")
cat(substr(str, 1, N%%nchar(str)))})(203)
```
When N = 50, the code trims itself.
```
(f <- function(N){
str <- paste0("(f <- function(N
```
When N = 300, the code partially repeats itself.
```
(f <- function(N){
str <- paste0("(f <- function(N)", paste0(as.character(body(f)), collapse = "\n"), ")}(", N, ")")
cat(rep(str, floor(N/nchar(str))), sep = "")
cat(substr(str, 1, N%%nchar(str))))}(300)(f <- function(N){
str <- paste0("(f <- function(N)", paste0(as.character(body(f)), collapse = "\
```
[Answer]
# Matlab (57)
```
function s=f(n);s=evalc('type f');s=s(mod(1:n,nnz(s))+1);
```
The initial `1` index (instead of `0`) in the last line is because Matlab's function `type` introduces an initial line-feed, which should be removed. Thanks to Dennis for his correction (last index) and for his suggestion (`nnz` shorter than `numel`).
[Answer]
# [Unary(1-8 version)](http://esolangs.org/wiki/Talk:Unary#Inefficient_conversion_to_number), 23855 bytes
Takes input as unary of '1's, and the code is 23855 '1's (`,[.,]`)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~40~~ 28 bytes
```
"îR+Q+V+Q+R+V"
îR+Q+V+Q+R+V
```
First time writing a quine, so this can probably be shortened quite a bit. On the other hand, I'm quite happy I got it to work at all.
Leading newline intentional, the second line is data and the rest of it unwraps the data, then repeats the whole resulting string until it reaches length equal to the input.
Shaved off a whopping 12 bytes thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver).
[Try it online!](https://tio.run/##y0osKPn/n0spSDtQOwyIg7TDFApCFUpCQpW4MMX@/zc0MAAA)
[Answer]
## C++, 305
```
int L=305;string s="int main(){string t=\"string s=\";int n;cin>>n;t+=s;t+=\"\";\";t+=s;while(n>0){if(n>L){cout<<t;n-=L;}else{cout<<t.substr(0,n);}return 0;}";
int main(){string t="int L=305;string s=\"";int n;cin>>n;t+=s;t+="\";";t+=s;while(n>0){if(n>L){cout<<t;}else{cout<<t.substr(0,n);}n-=L;}return 0;}
```
**Explanation**
Apart from the escape character all other characters are printed out.
The main method is inside the string s and inside main the full string is built and printed to stdout
[Answer]
## Pyth, ~~15~~ ~~13~~ 14 bytes
```
<jN*Q]"<jN*Q]"
```
[Try it online!](https://tio.run/##K6gsyfj/3ybLTyswVglK/f9vZAkA)
Modified version of the [standard Pyth quine](https://esolangs.org/wiki/Pyth#Quine).
[Answer]
## [Hoon](https://github.com/urbit/urbit), 185 bytes
```
=/(f "=/(f k |=(n=@ =+((trim 5 f) `tape`(scag n `tape`(zing (reap n :(weld p <f> (slag 1 q))))))))" |=(n=@ =+((trim 5 f) `tape`(scag n `tape`(zing (reap n :(weld p <f> (slag 1 q))))))))
```
Set `f` to the program's code as a tape, but with "k" for itself. Split the tape at character 5, setting variables `[p=left q=right]`. Weld together the strings `p`, the original string `f`, and everything after the 1st character of `q`. Repeat that string `n` times, then return the first `n` characters of it.
Doing this was *slightly* hampered by Hoon's stdlib not having a format function or find-and-replace...Also, I'm not sure why we need another cast after the `scag`, since it should keep type information. So it goes.
[Answer]
# [Jstx](https://github.com/Quantum64/Jstx), 7 [bytes](https://quantum64.github.io/Jstx/codepage)
```
/£↕:1Fn
```
[Try it online!](https://quantum64.github.io/Jstx/JstxGWT-1.0.2/JstxGWT.html?code=L8Kj4oaVOjFGbg%3D%3D&args=MTA%3D)
[Answer]
## [Perl 5](https://www.perl.org/) with `-pa`, 48 bytes
```
$_=q{$_=substr"\$_=q{$_}:eval"x"@F",0,"@F"};eval
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3rawGkgUlyYVlxQpxUD5tVapZYk5ShVKDm5KOgY6IKrWGiT0/7@l5b/8gpLM/Lzi/7oFiQA "Perl 5 – Try It Online")
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 12 bytes
```
"r2ssIFLko|;
```
[Try it online!](https://tio.run/##S8/PScsszvj/X6nIqLjY080nO7/G@v9/YwMA "Gol><> – Try It Online")
### How it works
```
"r2ssIFLko|;
"..." Push the chars in reverse order
r2ss Reverse the stack, then push `"`
IF...| Input n, and repeat the following n times...
L Push the loop counter (0 to n-1)
k Pop x and copy x-th from the top
o Pop and print as char
; Halt
```
`k` can wrap any number of times, so we don't need to duplicate the whole stack depending on the input.
[Answer]
# SmileBASIC, ~~106~~ 66 bytes
```
INPUT N?MID$(("+CHR$(34))*3,23,N)INPUT N?MID$(("+CHR$(34))*N,23,N)
```
[Answer]
# [KSFTgolf](https://github.com/KSFTmh/KSFTgolf) - 4 chars, 6 bytes
KSFTgolf if a language I've been attempting to design for code golf. I've been changing it a lot, so this probably shouldn't actually count.
```
☃\@2
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 24 bytes
```
"34bLNca*]$("34bLNca*]$(
```
[Run and debug it](https://staxlang.xyz/#c=%2234bLNca*]%24%28%2234bLNca*]%24%28&i=3%0A28&a=1&m=2)
Adaption of the `"34bL"34bL` quine.
[Answer]
# J, 41 Bytes
Now that was a brain teaser!
```
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~
```
### Explanation:
```
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ | Expression taking 1 argument
$~ | Reshape left argument to fit right, taking cyclically.
( ) | One large expression that evaluates to a string
'((,quote,'')$~''"_)' | String literal containing the code to the left of it
(,quote,'$)~'"_) | A 4-Hook:
'$)~'"_ | The string '$)~'
quote, | Appended to the quoted version of the string
, | Appended to the raw string
```
Examples:
```
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 10
((,quote,'
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 20
((,quote,')$~'"_)'((
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 30
((,quote,')$~'"_)'((,quote,'')
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 41
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 50
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~((,quote,
```
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 28 bytes
```
"r(34)<ns>l[p&:l,s]p<[>o<,]p
```
[Try it online!](https://tio.run/##y6n8/1@pSMPYRNMmr9guJ7pAzSpHpzi2wCbaLt9GJ7bg/38jAwA "Ly – Try It Online")
[Answer]
# Java 10, ~~193~~ 176 bytes
```
n->{var s="n->{var s=%c%s%1$c;s=s.format(s,34,s);for(int i=n;i>0;i/=176)s+=s;return s.substring(0,n);}";s=s.format(s,34,s);for(int i=n;i>0;i/=176)s+=s;return s.substring(0,n);}
```
**Explanation:**
[Try it online.](https://tio.run/##rZDBasMwEETv/ool1CARR7VJ0h6E8gfNpcfSg6I4Qam9Dtq1oQR/uyu7Kb20l5CL0O4wO7w52c4uTvuPwVWWCF6sx0sC4JHLcLCuhO04Arxy8HgEJ6ICKHVc9kl8iC17B1tAMDDgYnPpbAAys99v6lJKiwenyZA6NKG2LChbrjKSOo7TRW9Q@02u/aMpnp8kzQ3pUHIbEEhRu6MpXuRZjO5nd7s06JHh3O6qyHBF6Rq/hzr2IL6Z397BymsJn8RlrZqW1TlKXKFA5cRaTn38qf@vjM4iz2/3Rrpbveuf3D7phy8)
```
n->{ // Method with integer parameter and String return-type
var s="n->{var s=%c%s%1$c;s=s.format(s,34,s);for(int i=n;i>0;i/=176)s+=s;return s.substring(0,n);}";
// Unformatted source code
s=s.format(s,34,s); // Create the formatted quine
for(int i=n;i>0; // Loop `i` as long as it's not 0
; // After every iteration:
i/=176) // int-divide `i` by the hardcoded length of the source code
s+=s; // Exponentially enlarge the source code
return s.substring(0,n);}// Return the first `n` characters of the source code
```
[quine](/questions/tagged/quine "show questions tagged 'quine'")-part:
* The `var s` contains the unformatted source code.
* `%s` is used to input this String into itself with the `s.format(...)`.
* `%c`, `%1$c` and the `34` are used to format the double-quotes.
* `s.format(s,34,s)` puts it all together.
Challenge part:
* `for(int i=n;i>n;i/=176)` loops `ceil(n/176)` times, where `176` is the length of the source code.
* `s+=s;` exponentially increases the size of the source code String. (`ab` becomes `abab`; `abab` becomes `abababab`; `abababab` becomes `abababababababab`; etc.)
* `s.subtring(0,n);` takes the first `n` characters of the String.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~22~~ 19 bytes
```
'rd3*$:?!;1-$:o}50.
```
[Try it online!](https://tio.run/##S8sszvj/X70oxVhLxcpe0dpQV8Uqv9bUQO////@6ZcYWAA "><> – Try It Online")
Takes input through the `-v` flag.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 bytes
```
",:m",:m
```
[Run and debug it](https://staxlang.xyz/#c=%22,%3Am%22,%3Am&i=8)
] |
[Question]
[
*Inspired (with the explanation stolen from) [this](https://stackoverflow.com/q/45906747/7742131)*
## Background
Say you have two lists `A = [a_1, a_2, ..., a_n]` and `B = [b_1, b_2, ..., b_n]` of integers. We say `A` is **potentially-divisible** by `B` if there is a permutation of `B` that makes `a_i` divisible by `b_i` for all `i`. The problem is then: is it possible to reorder (i.e. permute) `B` so that `a_i` is divisible by `b_i` for all `i`?
For example, if you have
```
A = [6, 12, 8]
B = [3, 4, 6]
```
Then the answer would be `True`, as `B` can be reordered to be `B = [3, 6, 4]` and then we would have that `a_1 / b_1 = 2`, `a_2 / b_2 = 2`, and `a_3 / b_3 = 2`, all of which are integers, so `A` is potentially-divisible by `B`.
As an example which should output `False`, we could have:
```
A = [10, 12, 6, 5, 21, 25]
B = [2, 7, 5, 3, 12, 3]
```
The reason this is `False` is that we can't reorder `B` as 25 and 5 are in `A`, but the only divisor in `B` would be 5, so one would be left out.
## Your task
Your task is, obviously, to determine whether two lists (given as input) are potentially divisible. You may take input in any accepted manner, as with output.
Duplicates in the lists are a possibility, and the only size restrictions on the integers are your language. All integers in both lists will be larger than 0, and both lists will be of equal size.
As with all [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'")s the output values must be 2 distinct values that represent true and false.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins!
## Test cases
```
Input, input => output
[6, 12, 8], [3, 4, 6] => True
[10, 5, 7], [1, 5, 100] => False
[14, 10053, 6, 9] [1,1,1,1] => True
[12] [7] => False
[0, 6, 19, 1, 3] [2, 3, 4, 5, 6] => undefined
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Œ!%ḄẠ
```
Returns **0** for *True*, **1** for *False*.
[Try it online!](https://tio.run/##y0rNyan8///oJEXVhztaHu5a8P/wciP9yP//o7kUos10FAyNdBQsYnUUoo11FEx0FMxidYDihgY6CqY6CuYgcUMw09DAACJjAmabAlUDNVtCFUARRIURSNAczDYAqzK0BEsbg8SBtkEsMgXZxRULAA "Jelly – Try It Online")
### How it works
```
Œ!%ḄẠ Main link. Arguments: A, B (arrays)
Œ! Generate all permutations of A.
% Take each permutation modulo B (element-wise).
Ḅ Convert all resulting arrays from binary to integer.
This yields 0 iff the permutation is divisible by B.
Ạ All; yield 0 if the result contains a 0, 1 otherwise.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~7~~ ~~6~~ 5 bytes
Saved 2 bytes thanks to @Zgarb
```
▼▲‡¦P
```
Takes argents in reverse order and returns `1` for `True` and `0` for `False`.
[Try it online!](https://tio.run/##ASUA2v9odXNr///ilrzilrLigKHCplD///9bMyw0LDZd/1s2LDEyLDhd)
### Explanation
```
P -- Permutations of the first argument
‡ -- Deep zip (vectorises function) with second argument
¦ -- Does x divide y
▲ -- Get the maximum of that list, returns [1,1...1] if present
▼ -- Get the minimum of that list, will return 0 unless the list is all 1s
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
Input: takes lists B and A (reversed order)
Output: 1 when true, 0 otherwise
```
œvIyÖPM
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6OQyz8rD0wJ8//@PNtZRMNFRMIvlijbTUTA00lGwiAUA "05AB1E – Try It Online")
Explanations:
```
œvIyÖPM Complete program
œ Pushes all permutations of B as a list
v For each permutation
I Pushes last input on top of the stack
yÖ Computes a % b == 0 for each element of A and B
P Pushes the total product of the list
M Pushes the largest number on top of the stack
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~8~~ ~~7~~ 6 bytes
*1 byte off using an idea from Dennis' Jelly answer*
```
Y@\!aA
```
Inputs are `B`, then `A`. Output is `0` if divisible or `1` if not.
[**Try it online!**](https://tio.run/##y00syfmf8D/SIUYx0fG/S8j/aGMdBRMdBbNYrmgzHQVDIx0FCyDTUEfBFMgzMACxDcAcc7AwGIJYJmBpU6BuoDZLoAhY3igWAA)
### Explanation
```
Y@ % Implicit input: row vector B. Matrix of all permutations, each on a row
\ % Implicit input: row vector A. Modulo, element-wise with broadcast. Gives
% a matrix in which each row contains the moduli of each permutation of B
% with respect to A
!a % True for rows that contain at least a nonzero value
A % True if all values are true. Implicit display
```
[Answer]
# Mathematica, 52 bytes
```
Cases[Permutations@#2,p_/;And@@IntegerQ/@(#/p)]!={}&
```
*thanks @ngenisis for -5 bytes*
[Answer]
# JavaScript (ES6), ~~67~~ 63 bytes
Returns a boolean.
```
f=([x,...a],b)=>!x||b.some((y,i)=>x%y?0:f(a,c=[...b],c[i]=1/0))
```
### Test cases
```
f=([x,...a],b)=>!x||b.some((y,i)=>x%y?0:f(a,c=[...b],c[i]=1/0))
console.log(f([6, 12, 8],[3, 4, 6])) // true
console.log(f([10, 5, 7],[1, 5, 100])) // false
console.log(f([14, 10053, 6, 9],[1,1,1,1])) // true
console.log(f([12],[7])) // false
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~79~~ ~~74~~ ~~68~~ ~~62~~ 61 bytes
```
import Data.List
f a=any((<1).sum.zipWith rem a).permutations
```
[Try it online!](https://tio.run/##VY4/C8MgEMXn5lPc0CEBEc3fBpqtY/cO4iA0IdJoRM3Qfnlr7NJwHBzv/e7uzcK9xmUJQSqzWg834QW@S@ezCcQg9DvPr7TAblP4I81D@hnsqEAU2IxWbV54uWoXlJAaBniu2clYqT2cYWItAloiuHBWIagRtPzfpQRBg6DjjKaBEnL066Q1cTce6ncs1REqOesOCkk47WMjqDiLAX7fmz0AhC8 "Haskell – Try It Online")
*Saved 1 byte thanks to @nimi*
[Answer]
# [R](https://www.r-project.org/) + [combinat](https://cran.r-project.org/web/packages/combinat/combinat.pdf), ~~69~~ ~~66~~ 58 bytes
*-3 bytes thanks to Jarko Dubbeldam*
*another -8 bytes thanks to Jarko*
```
function(a,b)any(combinat::permn(b,function(x)all(!a%%x)))
```
oddly, R doesn't have a builtin for generating all permutations. Returns a boolean.
Additionally, with Jarko's second improvement, `any` coerces the list to a vector of `logical` with a warning.
[Try it online! (r-fiddle)](http://www.r-fiddle.org/#/fiddle?id=Os98W9XW&version=3 "R-fiddle")
[Answer]
# Mathematica, 42 bytes
```
MemberQ[Permutations@#2,a_/;And@@(a∣#)]&
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 191 bytes
```
#define F(v)for(i=0;i<v;++i){
#define X if(f(s,n,a,b))return 1
j;f(s,n,a,b,i)int*a,*b;{if(--n){F(n)X;j=i*(n%2);b[j]^=b[n];b[n]^=b[j];b[j]^=b[n];}X;}else{F(s)if(a[i]%b[i])return 0;}return 1;}}
```
[Try it online!](https://tio.run/##hZLbasMwDIbv8xQio2CnLsuxXeeF3fUZCiWDuHOGQ@eOJO3FQp4903JoXWhoCMLol/V/Et4vvvb7tn36lJnSEjbkTLNjQVTscvV25vO5orU1qltQGclIyTRLmaC0kNWp0OBZOb9kmaJKV07KHMFrLF8sNK03RNMtz2PlED3zKRe7PPmIxU4n/D/8H/PEzDZb3shDKfFmSbFLulPJTGAYPV3ejO68adrvVGlCrdoC/NAfUm@XQAz1koHnM3hp@EUSgxQwCBksDeUgNQql@pXHDDvA83h2Uq@v@jlVJYGMYCWDLqQew44U3sGuipO04RXsLEV0Gyi3rjx@b@q5DCIGK5NnlDrFc91Bu6XxTRp/kgZnFf5jmmCwDDvDCFeBi1qbUMEFavjvUgUmVTBJhf1F8JgqHDx9E2RIru76h6Z/OOmPY4rwsX/UW7ndNrx1N3dgsgwFuOT@8UTX93PLFZlc0SQX3hfRFFfT/gE "C (gcc) – Try It Online")
**Usage:** `f(int size, int size, int *a, int *b)`
returns `1` if divisable, `0` otherwise. See example usage on TIO.
(Gotta do permutations the hard way in C, so this is hardly competitive)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes
```
pᵐz%ᵛ0
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompkcdy5VKikpTlfRqQMy0xJziVKXa04vK/xc83DqhSvXh1tkG//9HR0eb6Rga6VjE6kQb65jomMUCGdGGBjqmOuZAliGQNjQwgAiagJimxjpmOpZgKTCESBkBSXMw0wAobWgJlDEG8ox0QGaagkyNBQA "Brachylog – Try It Online")
The predicate succeeds if the two lists are potentially divisible and fails if they are not.
```
pᵐ For some pair of permutations of the two input lists,
z for each pair of corresponding elements
%ᵛ0 the first mod the second is always zero.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Œ!ọẠ€1e
```
[Try it online!](https://tio.run/##ASwA0/9qZWxsef//xZIh4buN4bqg4oKsMWX///9bNiwgMTIsIDhd/1szLCA0LCA2XQ "Jelly – Try It Online")
Factorial complexity in the length of the list.
[Answer]
# Pyth - 11 bytes
```
sm!s%Vdvz.p
```
[Test Suite](http://pyth.herokuapp.com/?code=sm%21s%25Vdvz.p&test_suite=1&test_suite_input=%5B6%2C+12%2C+8%5D%0A%5B3%2C+4%2C+6%5D%0A%5B10%2C+12%2C+6%2C+5%2C+21%2C+25%5D%0A%5B2%2C+7%2C+5%2C+3%2C+12%2C+3%5D&debug=0&input_size=2).
[Answer]
# J, 27 bytes
```
0=[:*/(A.~i.@!@#)@]+/@:|"1[
```
[Try it online!](https://tio.run/##y/r/P03BVk/BwDbaSktfw1GvLlPPQdFBWdMhVlvfwapGyTCay89JTyGkqDSVKzU5I19Bw0zB0EjBQlMhTUHDWMFEwUwTrMAtMacYpsLQQMFUwRyswhDIMjQw0Pz/HwA)
Takes the first list as the left argument and the second list as the right.
[Answer]
# CJam, ~~20~~ 17 bytes
```
:A;e!{A\.%:+!}#W>
```
[Test Version](http://cjam.aditsu.net/#code=l~%3Ail~%3Ai%5C%7B%3AA%3Be!%7BA%5C.%25%3A%2B!%7D%23W%3E%7D~&input=%5B14%2010053%206%209%5D%0A%5B1%201%201%201%5D%0A)
Function that takes array B as the first argument and array A as the second argument. Note that in the test version I switch the order to A then B.
[Answer]
## JavaScript (ES6), 100 bytes
```
f=(a,b)=>!a[0]||a.some((c,i)=>b.some((d,j)=>c%d<1&f(e=[...a],d=[...b],e.splice(i,1),d.splice(j,1))))
```
Somewhat inefficient; an extra `&` would speed it up.
[Answer]
# [Python 2](https://docs.python.org/2/), 90 bytes
```
lambda a,b:any(sum(map(int.__mod__,a,p))<1for p in permutations(b))
from itertools import*
```
[Try it online!](https://tio.run/##LU5dC4JAEHzvV8xbZ2ziWWlJ9UdM5KSkA@@D83oI8bfbXQjL7Aw7s4z9@rfR@dLfHssgVPcUENRVQn/Z@FFMCcuk9mnbKvNsWxJkk@TKe@NgITXsy6mPF14aPbIuSTa9MwrSv5w3ZhghlTXO75YYCH9jpK4LAs8J54ZQHwhHQtFEXvOMcCKUUfA/5Vm2no5/cQr@EL@sjnVWSx5X2TTVBrAu1MZ2mgnTjP094DYNLZTwLBShPmLou/wA "Python 2 – Try It Online")
[Answer]
# PHP, ~~112 180~~ 178 bytes
I was thinking too short.
```
function($a,$b){for($p=array_keys($b);++$i<count($b);){foreach($b as$k=>$x)$f|=$a[$k]%$x;if($f=!$f)return 1;$p[$i]?[$b[$j],$b[$i],$i]=[$b[$i],$b[$j=$i%2*--$p[$i]],0]:$p[$i]=$i;}}
```
anonymous function takes two arrays, returns `NULL` for falsy and `1` for truthy.
Throws an error if second array contains `0`.
[Try it online](http://sandbox.onlinephpfunctions.com/code/00157e5748c09e70b7f1128bf8238538f7f84ac2).
[Answer]
# [Perl 6](https://perl6.org), 38 bytes
Actually @nwellnhof's answer seems to be too much readable, so I set out to follow the fine Perl tradition of write-only code :—).
1 byte saved thanks to @nwellnhof.
```
{min max (@^a,) XZ%% @^b.permutations}
```
[Try it online!](https://tio.run/##VY7RCoJAEEXf@4oLJRgsoWVWROA/9BJFwlZrDrm7su5iEn27peFDzMtwz5nhlsIUcSsbTDLs2pckBcmf8JOUsykOR89Dkl5mpTDSWW5Jq@rdVrzz/VPMEM4Z1meG04IhYojP0@1owGHAsGRYdTjs1zAI/oSoj5bf2@@rzc/r58@ad2A1RErXW4yx12i0w5V3hR8C2lnUuVCwuUBp9N1wiYwUVbm4gTIYpxSpO8hCusJSWQhYkqKatR8 "Perl 6 – Try It Online")
What does it do: It's an anonymous function that takes two list arguments. When we say `@^a`, we mean the first one, when `@^b`, it's the second one.
`(@^a,)` is a list containing the list `@^a`. `@^b.permutations` is the list of all the permutations of `@^b`. The "XZ%%" operator makes all possible pairs of that one list on the left and all the permutations on the right, and uses the operator "Z%%" on them, which is the standard "zip" operation using the divisibility operator %%.
The `max` operator gives the largest element of the list (in this case, it's the list that has the most `True`'s in it). We then reduce it using the logical AND operator to see if all elements of that "most true" list are true, and that's the result. It's nearly exact copy of what @nwellnhof wrote, just using obscure operators to shave off bytes.
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 49 bytes
```
[ <permutations> [ v/ [ ratio? ] ∄ ] with ∃ ]
```
[Try it online!](https://tio.run/##bVC7jsIwEOzzFXM/AEl4Ho/QgWiu4a5CFL5ghAWxI9sBnVAqKPhOfiRsYjiBYEda7axnRtauWGyVLn5m069JDwmz61qskl8hGa1FbNwqkyJWS@7IjpcW94IN15JvkWpu7V@qhbRgxigy9j3v4IHqQGgjCNFFTmMDTaI54V4fGEb41hn/lwc@WuhU8oCmwPcfDJV8zLbmQd8sNa0GBX/eXA6l6018WIk6T7/Aa3zuFXMMUq6TzDIrlDQR5tjVqemSj7DA5Xyivhd0i8v5iEWxcgeIEpaiVlwB "Factor – Try It Online")
* `<permutations> [ ... ] with ∃` Is there any permutation of the second input where...
* `v/` ...the quotient of the first input and the permutation...
* `[ ratio? ] ∄` ...contains no ratios? (In other words, are they all integers?)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
Ṗ$vḊvAa
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4bmWJHbhuIp2QWEiLCIiLCJbNiwgMTIsIDhdLCBbMywgNCwgNl1cblsxMCwgNSwgN10sIFsxLCA1LCAxMDBdXG5bMTQsIDEwMDUzLCA2LCA5XSwgWzEsMSwxLDFdXG5bMTJdLCBbN10iXQ==)
[Answer]
# [Python 2](https://docs.python.org/2/), 92 bytes
```
lambda a,b:any(all(x%y<1for x,y in zip(a,p))for p in permutations(b))
from itertools import*
```
[Try it online!](https://tio.run/##LY3LDoIwEEXX8hWzMbRmFhR5KBGX/ASyKIHGJtA2pSbgzyNFMpuZc@7NmMW9tYpXUb7WgY9tx4FjW3C1ED4MZD4vDya0hRkXkAq@0hCOhlLPjCemt@PHcSe1mkhLaSCsHkG63jqthwnkaLR1l7XrBVRbt6VFcDJWKucfYVg@QxQ7D4KK1BkCixFuDUJ9RUgQsoZ6wSKEFCH3gu0ri6JDJfuRbvmtfv8n9jl87FHe0PUH "Python 2 – Try It Online")
Yer basic implementation.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 56 bytes
```
->x,y{x.permutation.any?{|p|p.zip(y).all?{|a,b|a%b==0}}}
```
[Try it online!](https://tio.run/##bY5BC4JAEIXv/YqBCAqmZbdS87B26xd0Mw9rrSDotqgLbupvt02jLjEMDPO@93iVSe2YAb@O26hF27VEy6o0jWjyhyJC2VPX616TZ67XdkNEUbiHwLQXq5RzOgzDqCEj69hHYDuEY4IQ7xEOCH6ygSWP4FIZuZghRhE8hOANselklH6wsyjqL3eYFM8Fudxwxqf5k7l7y8GfFDq5WegWYZ9g7PrN1bxfO6PuMsuVvOPshVxBaeEmajm@AA "Ruby – Try It Online")
Fairly straightforward, exploits the fact that `permutation` exists.
[Answer]
# Scala, 60 Bytes
**Golfed:**
```
a=>b=>b.permutations exists(a zip _ forall(p=>p._1%p._2==0))
```
**Ungolfed:**
```
a=>b=> // Function literal taking 2 lists of integers, a and b.
b.permutations // All permutations of b.
exists( // Whether the given function is true for any element.
a zip _ // Zips a and the current permutation of b into a list of pairs.
forall( // Whether the given function is true for all elements.
p=> // Function literal taking a pair of integers.
p._1%p._2==0)) // If the remainder of integer division between the members of the pair is 0.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~12~~ 11 bytes
Outputs `true` or `false`.
```
Vá de@gY vX
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=VuEgZGVAZ1kgdlg=&input=WzYsMTIsOF0KWzMsNCw2XQ==)
---
## Explanation
Implicit input of arrays `U` & `V` (`A` & `B`, respectively)
```
Vá
```
Generate an array of all permutations of `V`.
```
d
```
Check if any of the elements (sub-arrays) return true.
```
e@
```
Check if every element in the current sub-array returns true when passed through the following function, with `X` being the current element and `Y` the current index.
```
gY
```
Get the element in `U` at index `Y`.
```
vX
```
Check if it's divisible by `X`.
] |
[Question]
[
Input a decimal number and round it to an integer, randomly rounding up or down with a probability based on its fractional part, so the expected value of the output equals to the input value.
If input \$x\$ is an integer, the program should output it as is. If \$x\$ is not an integer, the program has a \$x-\left\lfloor x \right\rfloor\$ probability to output \$\left\lceil x \right\rceil\$, and a \$\lceil x\rceil-x\$ probability to output \$\left\lfloor x \right\rfloor\$.
In the above formula, \$\left\lfloor i\right\rfloor\$ means rounding \$i\$ down to the nearest integer; \$\left\lceil i\right\rceil\$ means rounding \$i\$ up to the nearest integer.
## Examples
* For input 2.4, it has 60% probability to output 2, and 40% probability to output 3.
* For input 3.9, it has 10% probability to output 3, and 90% probability to output 4.
* For input 0.5, it has 50% probability to output 0, and 50% probability to output 1.
* For input -5.25, it has 75% probability to output -5, and 25% probability to output -6.
* For input 8, it has 100% probability to output 8, and 0% probability to output 7 or 9.
## Rules
* To make the challenge easier, reasonable errors in probability are allowed.
+ For any input \$-100<x<100\$, the probability error should be less than \$0.01\%\$.
* You may assume your language's built-in random number generator is perfectly balanced.
* You may assume the input / output value fits your languages decimal number types, as long as [this does not trivialize the challenge](https://codegolf.meta.stackexchange.com/a/8245/44718).
* As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). So shortest code wins.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 6 bytes [SBCS](https://github.com/abrudz/SBCS)
```
⌊?⍤≡+⊢
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9TTZf@od8mjzoXaj7oWAQA&f=e9Q7VyGoNE8hNTE5QyE5sThVwU@hJDM3tVghMS9FoTgjv1yhJCNVITm/NK9EIT8Noq4otbg0p4TLT@FR2wQFQwMg4ApJLS4Bc6urH/XuUtB41LnoUe9WzdpHPTvSDq3we9S7BcithSgz0jPhUleHsI31LOFsAz1TOPvQelM9IwTXAgA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
Add a random number in \$(0,1)\$ and floor.
[Answer]
# [R](https://www.r-project.org), 20 bytes
```
\(n)(n+runif(1))%/%1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ddHBasMgGMBxdt1TfFACShMb09gkY3uTXcw2WyGoJHros_SSQvsGe5Cd-zSLCCM7fB704N-fiJfrON8UvBb34FXRfr8TQ4nZjsFoRTil2S7jaevx9HOEN1DBfHhtzdKBG61jXvbDF0nzJJ0bzoS_8DKO_C_WVC0HlvF8JBWr6SYH7eEkJziUWXR62etB-zN4CzZ4FzxUOUjzCTUa7Nmi7Vm30jgeJ61DgzpqJRMrTaBxmTQ84FErBKvWXiOwvBAJrPDiEMX231vR29ukofsN2BE6lj52ntP6Cw)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~4~~ 3 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
ƒ-ü
```
Port of [*@ovs*' APL answer](https://codegolf.stackexchange.com/a/244212/52210).
-1 byte thanks to [*@nextwayup*'s 05AB1E answer](https://codegolf.stackexchange.com/a/244218/52210) by using \$ceil(input-random)\$ instead of \$floor(input+random)\$.
Make sure to upvote both of them as well!
[Try it online.](https://tio.run/##y00syUjPz0n7///YJN3De/7/N9Iz4TLWs@Qy0DPl0jXVMzLlsuDSNTQw4AJiAA)
**Explanation:**
```
ƒ # Random float in the range [0,1]
- # Subtract this from the (implicit) input-float
ü # Ceil it to an integer
# (after which the entire stack is output implicitly)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ ~~11~~ 9 bytes
*-2 bytes thanks to Kevin Cruijssen*
```
4°LΩ4°/-î
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f5NAGn3MrgaS@7uF1//8b6ZkAAA "05AB1E – Try It Online")
Does 05AB1E really not have a function for random(0,1)? Anyway, here's an answer.
Explanation:
```
4°L # create list of length 10000 (Ždt = 10000)
Ω # choose an integer from the list
4°/ # divide it by 10000 to get a random decimal number
- # subtract the random number from the input
î # round up
```
[Answer]
# [Lua](https://www.lua.org), 36 29 bytes
*-7 thanks to @Sisyphus*
```
print((...+math.random())//1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704pzRxwYKlpSVpuhZ7C4oy80o0NPT09LRzE0sy9IoS81LyczU0NfX1DTUhaqBKl0ab6pnGQjkA) Adds a random float between 0 and 1 to the input and then floors.
[](https://i.stack.imgur.com/arAzi.gif)
[Attempt This Online! (36 byte version)](https://ato.pxeger.com/run?1=m704pzRxwYKlpSVpuhY3VQqKMvNKNHITSzL00nLy84s09PT0tMHcosS8lPxcDU1NTYhaqJaV0aYgoGcaCxUAAA)
*insert furious clicking of the execute button*
[Answer]
# x86 machine code (32-bit), ~~18~~ 9 bytes
```
0F C7 F1 39 D1 83 D0 00 C3
```
Saved **9** bytes. Thanks to Peter Cordes.
### Disassembly
```
0: 0f c7 f1 rdrand ecx
3: 39 d1 cmp ecx,edx
5: 83 d0 00 adc eax,0x0
8: c3 ret
```
### Explanation
The function has the same behavior as `randRound` in the following C code.
```
#include <stdint.h>
static uint32_t rand_u32() {
uint32_t r;
__asm__ ("rdrand\t%0" : "=r"(r));
return r;
}
__attribute__((regparm(3)))
int32_t randRound(uint32_t hi, uint32_t lo) {
return hi + (rand_u32() < lo);
}
```
`rdrand` reads the hardware random number generator. The Intel manual states the validity of its result should be checked through the carry flag, but according to Peter Cordes, `rdrand` never fails on Ivy Bridge, so this code is always valid on Ivy Bridge, and mostly valid on other machines.
The single statement in `randRound` is all of the algorithm, but I have to explain how the data is represented.
Each fractional number is encoded in 64 bits. The high 32 bits is the integral part and the low 32 bits is the fractional part. The following list shows how each hex value is decoded to an actual value.
```
0000 0000 0000 0000 -> 0
7fff ffff 0000 0000 -> 0x7fff'ffff
8000 0000 0000 0000 -> -0x8000'0000
ffff ffff 0000 0000 -> -1
0000 0001 0000 0001 -> 1 + 1 / 0x1'0000'0000
ffff ffff 0000 0001 -> -1 + 1 / 0x1'0000'0000
ffff ffff ffff ffff -> -1 + 0xffff'ffff / 0x1'0000'0000
```
Such representation is common in fixed point arithmetic because the basic operations are very cheap. Here are some examples using 16/16-bit split, unlike the 32/32-bit split for the entry.
```
typedef uint32_t t_fix;
t_fix fix_add(t_fix x, t_fix y) {
return x + y;
}
t_fix fix_sub(t_fix x, t_fix y) {
return x - y;
}
t_fix fix_mul(t_fix x, t_fix y) {
return (uint64_t)x * y >> 16;
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 44 bytes
```
lambda i:(i+random())//1
from random import*
```
[Try it online!](https://tio.run/##Jcg9CoQwEAbQ3lN8ZaIx/oMKe5NtIhIcMJkwpPH0cWGrBy89@eI4Ff/5ltuF43SgXVEjLp4clNZdN1ReOOA/oJBYcl08CwgUMdrZYLKbQW8Xg3ax4491r4AkFLPyirQuLw "Python 3 – Try It Online")
-4 bytes by porting [ovs's APL answer](https://codegolf.stackexchange.com/a/244212/87681)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 18 bytes
```
->n{(n+rand).to_i}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWiNPuygxL0VTryQ/PrP2v6GBgV5JZm5qcXVNXk2BApAL5esl55fmlVSnRedpGegZGMba2hrW1v4HAA "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
+Ø%X÷¤Ḟ
```
A monadic Link that accepts a number and yields an integer.
Note: given an integer there is a one in \$2^{32}\$ chance of outputting an integer one greater than the input, this is within the \$0.01\%\$ specified.
**[Try it online!](https://tio.run/##y0rNyan8/1/78AzViMPbDy15uGPe////dU31jEwB "Jelly – Try It Online")**
### How?
```
+Ø%X÷¤Ḟ - Link: number, N
¤ - nilad followed by link(s) as a nilad:
Ø% - 4294967296
X - random integer from [1..4294967296]
÷ - divide by 4294967296
+ - N add that
Ḟ - floor
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), ~~32~~ 24 bytes
```
f(a)=(a+random()/2^31)\1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWO9I0EjVtNRK1ixLzUvJzNTT1jeKMDTVjDCHSN10LijLzSjTSNIz0TDQ1uWA8Yz1LJJ6BnikST9dUzwiZb6GpCTEMZicA)
-8, cheers to @alephalpha for the explanation on PARI/GP
[Answer]
# TI-Basic, 4 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541)
```
int(Ans+rand
```
the input is `Ans` (last value entered)
[](https://i.stack.imgur.com/sjCQ1m.jpg)
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 22 bytes
```
$_=int$_+($_/abs)*rand
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jYzr0QlXltDJV4/MalYU6soMS/l/39dUz0j03/5BSWZ@XnF/3V9TfUMDA3@6xYAAA "Perl 5 – Try It Online")
[Answer]
# [Vyxal 2.4.1](https://github.com/Vyxal/Vyxal/releases/tag/v2.4.1), 4 bytes
```
∆Ṙ+⌊
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%88%86%E1%B9%98%2B%E2%8C%8A&inputs=3.2&header=&footer=)
When rewriting Vyxal, we forgot `∆Ṙ`. It's not a feature, [it's a bug](https://github.com/Vyxal/Vyxal/issues/802).
Same as most other answers, adds a random float and floors.
This uses python's `random.random` which is a random 32-bit float in \$[0, 1)\$.
[Answer]
# [Julia 1.0](http://julialang.org/), 17 bytes
```
!x=ceil(x-rand())
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/X7HCNjk1M0ejQrcoMS9FQ1Pzf1p@kUKFQmaeQrSpnpGOgqmehY6CrrmeoY6CoQEQG@mZxnIpAAFIXSZInaGVoQFYBAQKijLzSnLyNBQrNMFiqXkpXMjixaW5QDmw5niYZoN4AwMDTX0YA0W9JhfQhP8A "Julia 1.0 – Try It Online")
the same as other answers here
[Answer]
# [Math++](https://esolangs.org/wiki/Math%2B%2B), 23 bytes
```
?>a
_a+!_($rand/(a-_a))
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 88 bytes
```
$
.
\.\d*
$&0000
(\.....).*
$1*_,10000*
L$@`(?<=(-?)(\d+)(_*),_+)((?!\3))?
$1$.($2*_$#4*
```
[Try it online!](https://tio.run/##FYqxCsJAEAX79xfiKrtrsuQuOVBQzs7GT1i4CElhYyH@/3mZZmCY7/p7f16hHvgxV4LBzRcFHYcG2G1DrJWgpQtbVTzpPnO@3rjPwr6chItKV5o573wUyW0nY4paaD9prdEmjHbBYAl9sphw/gM "Retina – Try It Online") Link includes test cases. Accurate to `0.01%` as required Explanation:
```
$
.
```
Append a decimal point in case the input is an integer.
```
\.\d*
$&0000
```
Ensure that there are at least 4 digits after the decimal point.
```
(\.....).*
$1*_,10000*
```
Multiply the decimal part of the input by `10,000` and convert it to unary, and separately add another `10,000` in unary.
```
L$@`(?<=(-?)(\d+)(_*),_+)((?!\3))?
```
Randomly match one `_` of the `10,000`, then test whether the random value was less than the decimal fraction.
```
$1$.($2*_$#4*
```
Keep the sign and increment the magnitude if it was.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 39 bytes
```
[Math]::Floor($args[0]+(random -ma 1.))
```
[Try it online!](https://tio.run/##bZExb8IwEIXn@FdYUaiSooSkW0EMVSukDu2AyoQY3MZAJMd2HVsMlN@e@hwDSYsXW3ffu/d0luJAVbOnjLXRdn5s129E7zfT6YIJoeKIqF2zzjfjWBFeihqnNcFFliTtCUXc1HiOH7LHGYqUMLyk5UraynnEM61YxXcxgMmVeREH3qO8kWe0NaR6JZdEV8JSroFT3BcnkyLL74s8v/BQPStsPR2OAUxowj5oo5uOcNrSqubwMBKuIst63M/oiIJIURDcRVsMOVBQbW0iKKb0e5gJWzxwI8fjGQpOmLKG3sRX0sNGdig6IRS@cmk0fjf1J1UYztRZhijsYi8Jx/7YzjWnBZbdXOwW6wEIAlq3B9ztBvqgHa5sZLGnL20IG2KxmzHpWcHKk1HP0P72JZGRf@2ge7HzX/HPzEOx1d@0WpCKWaduB94q7oGpFaYuaRK2vw "PowerShell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 65 bytes
```
import System.Random
f x=do n<-randomIO::IO Float;print$floor$n+x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRCG4srgkNVcvKDEvJT@XK02hwjYlXyHPRrcILODpb2Xl6a/glpOfWGJdUJSZV6KSlpOfX6SSp13xPzcxMw@omkshTcEUTOiRSxlCKEsQZQYkNAx0gXKapLP@AwA "Haskell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~53~~ 44 bytes
```
i;f(float n){i=n+((n>0)-.5)*rand()/(5<<30);}
```
[Try it online!](https://tio.run/##TY7RqsIwDIbvfYogCIlra9EzONLpi3i8GNsqBe1kLSiOvbq1duNob9L8@fiSip@qKgSjNOpzW3qw1JudzRDtXhIXOS270tZIK8yLYiNJDcFYD5fSWCToZxCfS4g3lwYlkUrZaPON8@5whB30a/HDYCO2DKTIGfBcrGP5HSa87QDfYmPr5h55qaZvAc48mlZjctFq6pZjqyDLEkdJM97ztT@axhsSdFT/8/cuF6fRS5/02sVc43yhge9hUf/ZOQPPwE3MMBvCs9Ln8uQCv70A "C (gcc) – Try It Online")
*Saved a whopping 9 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!!*
[Answer]
# R, 26/31 bytes
For anything that has *probability* in it there **has** to be at least one attempt in R.
Here we have a function in 31 bytes:
```
f=function(x)floor(x+runif(1))
```
and the same thing taking stdin input in 26 bytes:
```
floor(scan(n=1)+runif(1))
```
[Answer]
# [Desmos](https://desmos.com/calculator), 21 bytes
```
f(n)=ceil(n-random())
```
Press the randomize button at the top left (The icon next to the plus sign) to run the code again.
The simulation code will run the randomization automatically and keep track of the frequency and distribution (more details in the graph).
[Try It On Desmos!](https://www.desmos.com/calculator/yu38g3zxmh)
[Try It On Desmos! - Simulation](https://www.desmos.com/calculator/vtb6hkcq9m)
[Answer]
# [J](https://www.jsoftware.com/#/), ~~9~~ 7 bytes
-2 thanks to user ovs' comment:
```
<.@+?@0
```
Original:
```
(<.@+?)&0
```
Port of [@ovs' APL answer](https://codegolf.stackexchange.com/a/244212/18872)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
≧X²φI⌊⁺∕‽φφN
```
[Try it online!](https://tio.run/##FcqxCoMwEADQvV@R8QJpB3FzKi2FDi3BP7hq1IOYk0uin3/FN79hQRkYo@oHt3vONKee5qWA5yOIM40zk@0uXigVeGAu8IrMAj7WDE/aaQzQYxp5hcme15l32mr51vUXBOypU21urV73@Ac "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≧X²φ
```
Square the predefined value for `1,000`, so that the error will be less than `0.01%` as desired. (Unfortunately without this the error would be `0.1%`.)
```
I⌊⁺∕‽φφN
```
Divide a random integer between `0` and `1,000,000` by `1,000,000`, add it to the input, and floor the result.
[Answer]
# [Python 3](https://docs.python.org/3/), 57 bytes
```
lambda i:math.floor(i+random.random())
import random,math
```
[Try it online!](https://tio.run/##JcoxCoAwDEDR3VNkbDEGUQsqeBOXihQDtimhi6eviNOHx89PuSSNNWx7vX08Tg@8Rl8uCreIGm7Vp1Mi/THWNhyzaIEf8HtrEAUGTjDQhCMt2JPDztHgcF6zciomGLa2vg "Python 3 – Try It Online")
[Answer]
# Swift, 67 bytes
```
import Foundation
let f={(a:Double)in floor(a + .random(in:0..<1))}
```
[Try it online!](https://tio.run/##HcpBCsJADEDR/ZwiywRhqNJV0Z14DRlpA4FpUmJKF6VnH4t/@fjfTTj61mRezANetupYQkxTnQL4sWMZnrZ@6kSiwNXMscAFshcdbUbRocv5fiU6GpvDG87tLx3sCc4WFw1kvOWeKB3tBw)
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~45~~ 29 bytes
```
n=>Math.ceil(n-Math.random())
```
[Try it online!](https://tio.run/##VZDBTsMwEETv/oo9gGSTxriFSkUhvSFOCIlrFCnGODSVsZHt9pL628MmTStxmtFo94129/Iog/Ldb8yPm6EtB1tu32TccaU7Q20@eS/tl/uhjA1EORsiRN9JE6CEpRCiIKQiACv@uEB54E@jCL4eJV/z1WQ2pOat8y9S7aiFcgs9hmeYcgcbkdWnAjMcAmp0hA4jUaA8z3Xos4xNi5dVjzMttayYMwRVvsaQXv3pBIJBBstxJs2lzmhu3DdtPnQ4mBim1pvepmZCvX/utYpcWyzW4cxiPDgfKbteQSu/AFWz8Zh/TMjh1UXE@QSdRVVwf/nY3fixdAuunZOGYWNiwx8 "JavaScript (V8) – Try It Online")
I am an idiot, this is a much better way of doing it.
Here is my old solution:
```
n=>Math.random()>(n>0?n:-n)%1?~~n:n>0?-~n:~-n
```
[Try it online!](https://tio.run/##VZBBb4MwDIXv/AofVikZJQvtKnVl0NO00zRp1woJlsFKxZwppL1Q@OvMobTSTs95sr/n@JCf8kaZ6tcGp/VQxgPGyVtu98Lk@KV/GE8YJnKLmwD5LNz2PW7cOyDtAxw8pbGxYE2V1w3EEEopI8/beQAL8TgnWYonJ1KsnAQrsRiLtZeKUpuXXO0ZQpxAS@YFpvQRLbHaLiKPmoDVhYWKLBmRPE9xVPs@Hwevo4Z6SoY8mjwC7UxKJrvV5zNIDj6ErqebQnVdiFp/s@yjaI61bcbUuxa7bES9fx4KZUWBFFw0Fxa/rc92Zg4q5e4X/2AQwKu2xDEdVEiq4OF6qnt3qm4GupycjFNUx4c/ "JavaScript (V8) – Try It Online")
A bit convoluted to make it work for negatives, but essentially it checks whether the result from `Math.random()` is greater than the absolute value of the input. If it is, return the input rounded towards zero, otherwise away from zero.
] |
[Question]
[
Okey, we all know the normal way to throw a IllegalArgumentException in Java:
```
throw new IllegalArgumentException(); // 37 characters
```
But there must be a shorter (as in less characters) ways to do so.
How can we produce a java.lang.IllegalArgumentException with even less code?
* The code fragment has to compile and run in java 7.
* No imports/external packages (e.g. not using `java.util.Arrays.toString()` )
+ only exception: java.lang because it is automatically imported.
* You can add own
methods/classes.
* It must throw a java.lang.IllegalArgumentException
+ **Edit:** the error output (stacktrace) must name it java.lang.IllegalArgumentException, so no subclasses of it.
To have a base to start from:
```
class Titled {
public static void main(String[] args) {
throw new IllegalArgumentException();
}
}
```
[Answer]
These were all found by `grep`ping the source code in the package `java.lang`.
All of them result in a "pure" `IllegalArgumentException` (i.e. not a subclass of it).
The ones marked `*` only work if you add `" throws Exception"` (18 characters) to your `main` declaration, as they throw a checked exception of some kind.
## 12 (30?) characters\*
```
"".wait(-1);
```
This will result in:
```
java.lang.IllegalArgumentException: timeout value is negative
```
## 22 (40?) characters\*
```
new Thread().join(-1);
```
## 22 characters
```
Character.toChars(-1);
```
## 30 characters
```
Character.UnicodeBlock.of(-1);
```
[Answer]
Here's a nice short way to do it, in **~~17~~ 13 chars**:
```
new Long("");
```
It throws a `NumberFormatException`, which is an `IllegalArgumentException`. [This](http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html) and [this](http://ideone.com/5w3M9S) verify it.
Equivalently, one could do
```
new Byte("");
```
[Answer]
# 22 characters:
```
Character.toChars(-1);
```
[Running example](http://ideone.com/XrWA0t)
Javadoc: [java.lang.Character.toChars(int)](http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#toChars%28int%29)
**Some nice looking variants:**
```
Character.toChars(~4); // 22 characters, number can be any non-negative (and -0)
```
```
Character.toChars(1<<7); // 24 characters
```
`~i` is the same as `-1 * (i+1)` because it inverts the bits. So we will get a illegal parameter, because it is smaller then 0.
`1<<7` will create a too high number by shifting the 1 seven times. (same as multiply it 7 times with 2). The last accepted Value seems to be `1114111`, `1114112` will fail. *Note:* this might change depending on your environment, and could be not always reliable.
See the [Oracle Docs "Bitwise and Bit Shift Operators"](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html) and ["Primitive Data Types"](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)
# 28 characters:
And if you don't like using the character class in a character count competition\*:
```
Enum.valueOf(Enum.class,""); // 28 characters
```
*\*) Just to make this pun.*
[Answer]
# 21 characters:
```
System.getProperty("");
```
As per the documentation, `getProperty` and `setProperty` throw `IllegalArgumentException` if the key is empty.
[Answer]
# 25 Characters
Creates a vector with an invalid (negative) length:
```
new java.util.Vector(-1);
```
Displays:
```
Exception in thread "main" java.lang.IllegalArgumentException: Illegal Capacity: -1
at java.util.Vector.<init>(Vector.java:129)
at java.util.Vector.<init>(Vector.java:144)
at Titled.main(Titled.java:3)
```
[Answer]
Here's 24 characters:
```
System.out.printf("%z");
```
This will throw an `IllegalFormatException`, which is an `IllegalArgumentException`.
[Answer]
# 19 characters:
```
String.format("%");
```
Throws `java.util.UnknownFormatConversionException`, which inherits from `IllegalFormatException`, which, in turn, inherits from `IllegalArgumentException`;
[Answer]
# **14 Characters**
```
this.wait(-1);
```
# **17 Characters**
```
Thread.sleep(-1);
```
As far as code that directly throws IllegalArgumentException, these will do it.
```
From documentation:
Thread.sleep(int millis):
Throws:IllegalArgumentException - if the value of millis is negative
InterruptedException - if any thread has interrupted the current thread.
```
so direct code is 17 chars, if you're being a super stickler and counting the chars to add a throws clause for the interupted exception you can shorten it by just throwing the raw Exception class
] |
[Question]
[
### **Introduction:**
The [sine](http://en.wikipedia.org/wiki/Sine) of \$x\$ is given by the formula:
$$\sin(x) = x - \frac {x^3}{3!} + \frac {x^5}{5!} - \frac {x^7}{7!} + \frac {x^9}{9!} - \frac {x^{11}}{11!} + \cdots$$
The [cosine](http://en.wikipedia.org/wiki/Cosine#Sine.2C_cosine_and_tangent) of \$x\$ is given by the formula:
$$\cos(x) = 1 - \frac {x^2}{2!} + \frac {x^4}{4!} - \frac {x^6}{6!} + \frac {x^8}{8!} - \frac {x^{10}}{10!} + \cdots$$
### **Task:**
Given the value of \$x\$ and \$n\$, write a program (no functions, etc.) to output the value of \$\sin(x)\$ and \$\cos(x)\$ correct up to \$n\$ terms of the formula above. Assume that \$x\$ is in radians.
### **Input:**
```
x n
```
A decimal number \$x\$ (with up to 3 decimal places) and an integer \$n\$. Input must be on stdin or a prompt dialog box (iff your language doesn't support stdin)
### **Output:**
```
[sin(x)]
[cos(x)]
```
The value of both \$\sin(x)\$ and \$\cos(x)\$ should be rounded to 6 decimal places. If \$\sin(x)\$ is \$0.5588558855\$ (10 decimal digits), it should be rounded to \$0.558856\$ (6 decimal digits). The rounding must take place to the nearest, as described in the fifth column, "Round to nearest", of the the table in [this Wiki article](http://en.wikipedia.org/wiki/Rounding#Rounding_to_integer).
### **Constraints:**
```
1 <= x <= 20
1 <= n <= 20
```
### **Samples:**
```
----
5 3
10.208333
14.541667
----
8.555 13
0.765431
-0.641092
----
9.26 10
-3.154677
-8.404354
----
6.54 12
0.253986
0.967147
----
5 1
5.000000
1.000000
----
20 20
-5364.411846
-10898.499385
----
```
### **Notes:**
1. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are prohibited.
2. Built-in math functions and operators of trigonometry (sin, cos, tan, etc.), factorial, and exponentiation cannot be used. You are free to use a built-in rounding function for estimating the result of computing \$\sin(x)\$ and \$\cos(x)\$ to the 6-th decimal digit.
3. No need to handle wrong inputs.
4. Only ASCII characters can be used in the program, not the Chinese Unicode ones that allow code compression.
5. Your program must terminate, and display the output, within 3 seconds of input.
6. Your answer must accompany the ungolfed code, along with the explanation of the code (compulsory if the code is not immediately obvious to programmers-not-familiar-with-your-language, especially GolfScript, J, etc.).
7. Please include a link to an online compiler where your program can be tested.
### **Scoring:**
The answer with lowest code length in characters, including white space, tabs, etc. wins! Winner would be declared on 21 May 2014.
**EDIT**: 21/05/14
**Winner is [aditsu using CJam language](https://codegolf.stackexchange.com/a/27067/15037). Runner up follows [jpjacobs with J language](https://codegolf.stackexchange.com/a/27043/15037), and second runner up is [primo with Perl language](https://codegolf.stackexchange.com/a/27040/15037)**. Congrats all!
[Answer]
## Perl - 72 bytes
```
$~=<>=~$"+$'*2;$_=1-$_*$`/$~--/$~*$`for($,,$;)x$';printf'%f
%f',$`*$,,$;
```
Or, counting command line options as 1 byte each, in **70 bytes**:
```
#!perl -n
$-=/ /+$'*2;$_=1-$_*$`/$---/$-*$`for($,,$;)x$';printf'%f
%f',$`*$,,$;
```
Or, if you'll allow me Perl 5.8, in **63 bytes**:
```
#!perl -p
$.+=$'<</ /;$_=1-$_*$`/$.--/$.*$`for($_=$#='%f
',$\)x$';$_*=$`
```
but why would you.
***Edit**: Compliance with the new rules. `%f` rounds to 6 places by default, how convenient!*
---
**Algorithm**
Examining the Taylor series for *sin(x)*:

it can be seen that each term evenly divides every successive term. Because of this, it can be transformed rather effortlessly into a nested expression:

*cos(x)* transforms similarly, without the leading *x*, and denominator terms one smaller.
Additionally, this nested expression can be reformulated as a reverse recursive expression:

with *s∞ = 0* and *sin(x) = x·s1*, which is ultimately what is used.
---
**Ungolfed**
```
<> =~ m/ /; # read one line from stdin, match a space
# prematch ($`) is now x, postmatch ($') is now n
($x, $n) = ($`, $'); # reassign, for clarity
$i = 2*$n + 1; # counting variable (denominators)
for (($s, $c)x$n) { # iterate over $s and $c, n times each
# compute the next term of the recursive expression
# note: inside this loop $_ is not the _value_
# of $s and $c alternately, it _is_ $s and $c
$_ = 1 - $_ * $x**2 / $i-- / $i;
}
# formated output
printf("%f\n%f", $x*$s, $c);
```
---
**Sample Usage**
```
$ echo 5 3 | perl sin-cos.pl
10.208333
14.541667
$ echo 8.555 13 | perl sin-cos.pl
0.765431
-0.641092
$ echo 9.26 10 | perl sin-cos.pl
-3.154677
-8.404354
$ echo 6.54 12 | perl sin-cos.pl
0.253986
0.967147
$ echo 5 1 | perl sin-cos.pl
5.000000
1.000000
$ echo 20 20 | perl sin-cos.pl
-5364.411846
-10898.499385
```
If you want to test this online, I recommend using [compileonline.com](http://www.compileonline.com/execute_perl_online.php). Copy-Paste the code into `main.pl`, and the input into the `STDIN` box, then `Execute Script`.
[Answer]
# Python 3 (102) / Python 2 (104)
**Python 3 (102)**
```
x,n=map(float,input().split())
k=2*n
t=1
while k>1:k-=1;t=1+t*1j*x/k
print('%.6f\n'*2%(t.imag,t.real))
```
**Python 2.7 (104)**
```
x,n=map(float,raw_input().split())
k=2*n
t=1
while k>1:k-=1;t=1+t*1j*x/k
print'%.6f\n'*2%(t.imag,t.real)
```
Basically the same code. We save two characters from not needing parens for `print` but lose four from needing `raw_input`.
**Sample run**
You can run these [here](https://ideone.com/).
```
>>>
20 20
-5364.411846
-10898.499385
```
**Code explanation**
The main idea is to compute `2*n` terms of `e^(ix)`, and then take the imaginary and real part to get the `sin` and `cos` values approximated to `n` terms. We use the truncation of the Taylor series:
```
e^(ix)≈sum_{k=0}^{2n-1} (i*x)^k/k!
```
This is polynomial in i\*x, but rather than compute its value by summing each term, we use a modified [Horner's Method](http://en.wikipedia.org/wiki/Horner%27s_method) to compute the sequence (defined recursively in reverse)
```
t_{2n} = 1
t_k = 1 + t_{k+1}*i*x/k,
```
which gives `t_1` equaling the desired value.
Python string formatting operations are used to get the values to display rounded up to 6 decimal digits.
Edit: Changed to round to 6 digits as per new rules. No other changes were needed.
[Answer]
## J 98 70 69 58
Though this can probably be shortened quite a bit using more fancy functions ... comments are welcome:
```
exit echo 0j6":,.-/(($%&(*/)1+i.@[)"0~i.@,&_2)/".}:stdin''
```
note 2: input ends when receiving EOF (ctrl-D in linux).
Edit: join exponentiation and factorial into a nicer, more J-ish whole: `($ %&(*/) >:@i.@[ )`. This boils down to take an array of x replications of y and an array of the numbers from 1 to y. Multiply each and divide the result. This gets rid of the duplicate `*/`.
Thanks to algortihmshark, another 7 characters off.
Eliminated cut for getting rid of the trailing newline.
Longer version, for which knowing about forks is a must.
```
NB. recursive Factorial
f=: */@>:@i. NB. multiply all from 1 to n
NB. Exponential
e=: */@$ NB. replicate y x times, take the product.
NB. the x t y is the Nth (general) term without sign of the joint series
t=: (e % f@[)"0 NB. pretty straight forward: divide by (x!) on the exponential
NB. Piece the parts together, from right to left:
NB. read from stdin, cut the linefeed off , make the 2 n terms in 2 columns, which
NB. effectively splits out pair and odd terms, put in the minuses, put in rows
NB. instead of columns, echo, exit
exit echo 0j6&": ,. (-/) (i.@(,&_2)@{: t {.) , (". ;. _2) stdin''
```
There is no online J interpreter, but it's open source since a few years; installation is easy with these instructions:
<http://www.jsoftware.com/jwiki/System/Installation/J801>
On #jsoftware on irc.freenode.org, there is a J bot too.
stdin works only when ran from a file, from the commandline, else replace `stdin ''` with `'a b;'` where a and b are the numbers that would have been passed on the commandline.
[Answer]
# CJam - 42
```
rd:X;1_ri2*,1>{_2%2*(*/X*_}/;]2/z{:+6mO}/p
```
Try it online at <http://cjam.aditsu.net>
Explanation:
`r` reads a token from the input
`d` converts to double
`:X` assigns to the variable X
`;` pops the value from the stack
`1` puts 1 on the stack (the first term)
`_` duplicates the 1
`r` reads the next token (the n)
`i` converts to integer
`2*,1>{...}/` is a kind of loop from 1 to 2\*n - 1:
- `2*` multiplies by 2
- `,` makes an array from 0 to (last value)-1
- `1>` removes the first item of the array (0)
- `{...}/` executes the block for each item in the array
`_` duplicates the "loop variable" (let's call it k)
`2%2*(` converts from even/odd to -1/1:
- `2%` is modulo 2 (-> 0/1)
- `2*` multiplies by 2 (-> 0/2)
- `(` decrements (-> -1/1)
`*` multiplies, thus changing the sign every second time
`/` divides the term on the stack by k or -k; this is the "/k!" part of the calculation together with the sign change
`X*` multiplies by X; this is the "X^k" part of the calculation; we obtained the next term in the series
`_` duplicates the term to be used for calculating the following term in the next iteration
`;` (after the loop) pops the last duplicated term
`]` collects the terms on the stack in an array
At this point we have an array [1 X -X^2/2! -X^3/3! X^4/4! X^5/5! ...] containing exactly all the terms we need for cos(x) and sin(x), interleaved
`2/` splits this array into pairs
`z` transposes the matrix, resulting in the array with the terms for cos(x) and the array with the terms for sin(x), as "matrix rows"
`{...}/` again executes the block for each array item (matrix row):
- `:+` adds the elements of the matrix row together
- `6mO` rounds to 6 decimals
At this point we have the desired cos(x) and sin(x) on the stack
`p` prints the representation of the last item on the stack (sin(x)) followed by a newline
At the end of the program, the remaining contents of the stack (cos(x)) are printed automatically.
[Answer]
## Fortran: ~~89~~ ~~109~~ ~~125~~ ~~102~~ ~~101~~ 98 bytes
```
complex*16::t=1;read*,x,n;do k=2*n-1,1,-1;t=1+t*(0,1)*x/k;enddo;print'(f0.6)',aimag(t),real(t);end
```
I abuse implicit typing, but unfortunately no such implicit complex type exists, so I had to specify that & the complex `i`. ~~Gfortran cuts output at 8 decimal places naturally, so we're good on that spec.~~ Unfortunately, my original method of output, `print*,t`, did not meet specs so I had to add 16 characters to output the imaginary and real components & hit the required 8 decimal places.
Thanks to Ventero, I managed to save 23 bytes between output and the loop. And another character to get correct answers and formatted output. And 3 more on the `read` statement.
Ungolfed,
```
complex*16::t=1
read*,x,n
do k=2*n-1,1,-1
t=1+t*(0,1)*x/k
enddo
print'(f0.6)',aimag(t),real(t)
end
```
[Answer]
# Perl, ~~120~~ ~~108~~ ~~104~~ ~~89~~ 85
```
<>=~/ /;$c=$t=1;for(1..2*$'-1){$t*=$`/$_;$_%2?$s:$c+=$_&2?-$t:$t}printf"%f\n"x2,$s,$c
```
Ungolfed:
```
<> =~ / /;
$cosine = $t = 1;
for (1.. 2*$' - 1){
$t *= $` / $_;
($_%2 ? $sine : $cosine) += $_&2?-$t:$t
}
printf "%.6f\n" x2, $sine, $cosine
```
The first line reads the input and uses regex to find a space; this automatically puts the value before the space in $` and the value after it in $'.
Now we loop from 1 to `2*n-1`. `$t` is our term, which the loop repeatedly multiplies by `x` and divides by the loop's index (`$_`). The loop starts at 1 rather than 0 because the cosine is initialized to 1, which saved me having to deal with dividing by zero.
After updating `$t`, the trinary operator returns either `$sine` or `$cosine`, depending on whether the index is odd or even, and adds `$t`'s value to it. The magic formula `$_&2?-$t:$t` figures whether to add or subtract this value (basically using a bitwise-and on the index and 2 to generate the repeating sequence of "add, add, subtract, subtract").
You can test-run this code at [compileonline.com](http://www.compileonline.com/execute_perl_online.php).
[Answer]
# C, 120
```
double s,c,r,x;main(i,n){for(scanf("%lf %d",&x,&n),r=1;i<n*2;s+=r,r*=-x/i++)c+=r,r*=x/i++;printf("%.8lf\n%.8lf\n",s,c);}
```
To save a byte, the statements that update the sine value are placed inside the `for()` statement, but are actually executed after the statements following the closing parenthesis that update the cosine value. (I guess I could also save a couple more bytes by removing the final newline character in the program's output.)
The global variables `s`, `c`, `r` and `x` are implicitly initialized to zero, and `i` will have a value of 1 as long as there are no arguments provided on the command line. Unfortunately `printf()` defaults to 6 places of decimals, so the output format is a bit verbose.
### Ungolfed:
Here's the code with a bit of rearrangement to make the order in which things are done a bit clearer:
```
double s,c,r,x;
main(i,n) {
scanf("%lf %d",&x,&n);
r=1;
for(;i<n*2;) {
c+=r;
r*=x/i++;
s+=r;
r*=-x/i++;
}
printf("%.8lf\n%.8lf\n",s,c);
}
```
### Sample output:
```
$ echo 1.23 4 | ./sincos
0.94247129
0.33410995
```
### Try it online:
<http://ideone.com/URZWwo>
[Answer]
## Python >=2.7.3, ~~186~~ ~~184~~ ~~211~~ ~~200~~ ~~182~~ 170 characters
Kinda simple as hell. Uses formula from the question parameterized for sine and cosine.
Online interpreter can be found ~~[here](http://repl.it/)~~ [here](http://ideone.com/JsYNNK)
```
x,n=map(eval,raw_input().split())
f=lambda n:n<2and 1or n*f(n-1.)
for i in[1,0]:print"%.6f"%sum((1-j%2*2)*reduce(lambda o,p:o*p,[x]*(i+2*j),1)/f(i+2*j)for j in range(n))
```
**Edit:** Valid version with all the restrictions
**Edit2:** Changed online interpreter to ideone.com because of invalid `round` function output in Python 2.7.1
**Edit3:** Turned out that I used unnecessary inline lambda + changed rounding to string format (stolen from xnor :) )
**Edit4:** Replaced `join` with not functional main `for` loop
[Answer]
**JavaScript - 114 chars**
```
y=(z=prompt)().split(' ');for(x=l=s=+y[0],c=d=1;--y[1];c+=l*=-x/++d,s+=l*=x/++d);z(s.toFixed(6)+'\n'+c.toFixed(6))
```
Based on james' great answer. Same algorithm, first step avoided with initialization of c=1 and s=x. Using 2 vars instead of an array for output simplifies the loop.
**Ungolfed**
```
y = ( z = prompt)().split(' ');
for (
x = l = s = +y[0], /* init to value x, note the plus sign to convert from string to number */
c = d = 1;
--y[1]; /* No loop variable, just decrement counter */
c += (l *= -x / ++d), /* Change sign of multiplier on each loop */
s += (l *= x / ++d)
); /* for body is empty */
z(s.toFixed(6) + '\n' + c.toFixed(6))
```
[Answer]
# GNU bc, driven by bash, 128 bytes
Far too many bytes spent setting decimal places and to-nearest rounding. Oh well, here it is anyway:
```
bc -l<<<"m=1000000
w=s=$1
c=1
for(p=2;p/2<$2;s+=w){w*=-1*$1/p++
c+=w
w*=$1/p++}
s+=((s>0)-.5)/m
c+=((c>0)-.5)/m
scale=6
s/1
c/1"
```
Output:
```
$ ./trig.sh 5 3
10.208333
14.541667
$ ./trig.sh 8.555 13
.765431
-.641092
$ ./trig.sh 9.26 10
-3.154677
-8.404354
$ ./trig.sh 6.54 12
.253986
.967147
$ ./trig.sh 5 1
5.000000
1.000000
$ ./trig.sh 20 20
-5364.411846
-10898.499385
$
```
---
# Linux command-line tools, 97 unicode characters
*Unicode hack answer removed at OP's request. Look at the edit history if you interested.*
[Answer]
# JavaScript (ECMAScript 6 Draft) - ~~97~~ 96 Characters
A recursive solution:
```
f=(x,n,m=1,i=0,s=x,c=1)=>i<2*n?f(x,n,m*=-x*x/++i/++i,i,s+m*x/++i,c+m):[s,c].map(x=>x.toFixed(8))
```
Output:
```
f(0.3,1)
["0.29550000", "0.95500000"]
f(0.3,24)
["0.29552021", "0.95533649"]
```
[Answer]
# C,114
Insufficient reputation to comment, but further to Squeamish Offisrage's C [answer](https://codegolf.stackexchange.com/a/27039/15599), 7 byte reduction by using float for double and removing spaces, and combining declaration and init of 'r' gives
```
float s,c,r=1,x;main(i,n){for(scanf("%f%d",&x,&n);i<n*2;s+=r,r*=-x/i++)c+=r,r*=x/i++;printf("%.8f\n%.8f\n",s,c);}
```
try [here](http://ideone.com/jqyICw).
[Answer]
# Ruby, 336
Probably the longest one here, but I'm sure it could be made shorter :(
```
def f(n)
n==0 ? 1: 1.upto(n).inject(:*)
end
def p(x,y)
i=1
return 1 if y==0
y.times {i *= x}
i
end
def s(x,n)
a = 0.0
for k in 0...n
a += p(-1,k) * p(x.to_f, 1+2*k)/f(1+2*k)
end
a.round(8)
end
def c(x,n)
a= 0.0
for k in 0...n
a +=p(-1,k) * p(x.to_f, 2*k)/f(2*k)
end
a.round(8)
end
x = gets.chomp
n = gets.chomp.to_i
puts s(x,n), c(x,n)
```
[Answer]
# JavaScript (ES6) - 185 chars
```
i=(h,n)=>n?h*i(h,n-1):1;q=x=>x?x*q(x-1):1;p=(a,j,n)=>{for(c=b=0,e=1;c++<n;j+=2,e=-e)b+=e*i(a,j)/q(j);return b.toFixed(6)}
_=(y=prompt)().split(" ");y(p(_[0],1,_[1])+"\n"+p(_[0],0,_[1]))
```
Uses a function `q` for factorial, `i` for exponentiation, and `p` for performing both `sin` and `cos`. Run at jsbin.com.
Uses exactly the formula without any modification.
**EDIT**: Changed `8` decimal places to `6` decimal places. 15/May/14
**Ungolfed Code**:
```
/*Note that `name=args=>function_body` is the same as `function name(args){function_body} */
// factorial
function fact(x) {
return x > 1 ? x * fact(x - 1) : 1
}
// Exponentiation
function expo(number, power){
return power > 0 ? number * expo(number, power - 1) : 1;
}
function sin_and_cos(number, starter, terms) {
for (count = sum = 0, negater = 1;
count++ < terms;
starter += 2, negater = -negater)
sum += (negater * expo(number, starter)) / fact(starter);
// to 6-decimal places
return sum.toFixed(6);
}
input = (out = prompt)().split(" ");
out(sin_and_cos(input[0], 1,input[1])
+ "\n" +
sin_and_cos(input[0], 0, input[1]));
```
[Answer]
**JavaScript - 133 chars**
```
y=(z=prompt)().split(" "),s=[0,0],l=1;for(i=0;i<y[1]*2;i++){s[i%2]+=i%4>1?-1*l:l;l*=y[0]/(i+1)}z(s[1].toFixed(6));z(s[0].toFixed(6));
```
**Ungolfed**
```
var y = prompt().split(" ");
var out = [0,0]; // out[1] is sin(x), out[0] is cos(x)
var l = 1; // keep track of last term in series
for (var i=0; i < y[1] * 2; i++) {
out[i % 2] += (i % 4 > 1) ? -1 * l : l;
l *= y[0] / (i + 1);
}
prompt(out[1].toFixed(6));
prompt(out[0].toFixed(6));
```
[Answer]
# Mathematica, 96 chars
```
{{x,n}}=ImportString[InputString[],"Table"];Column@{Im@#,Re@#}&@Fold[1+I#x/#2&,1,2n-Range[2n-1]]
```
[Answer]
# Ruby - ~~160~~ ~~152~~ 140 Chars
Using recursion and the fact that for this recursive implementation sin(x, 2n + 1) = 1 + cos(x, 2n - 1), being sin(x, n) and cos(x, n) the series defined above for cos x and sin x.
```
p=->x,n{n<1?1:x*p[x,n-1]}
f=->n{n<2?1:n*f[n-1]}
c=->x,n{n<1?1:p[x,n]/f[n]-c[x,n-2]}
x,n=gets.split.map &:to_f
n*=2
puts c[x,n-1]+1,c[x,n-2]
```
Edit: Contributed by commenters (read below).
[Answer]
# APL(NARS), 109 chars
```
r←a F w;d;v;m;p
r←d←1+(2≠↑a)×w-1⋄m←w×wׯ1⋄p←2⊃a⋄v←0 1-2=↑a
→0×⍳0≥p-←1⋄r+←d×←m÷×/v+←2⋄→2
⍪{6⍕⍵a[2]F 1⊃a}¨⍳2⊣a←⎕
```
15+42+28+2+22=109
the last line call the function F that is a sin and cos function depend of first input on the left
(it is ≠2 is sin input =2 is cos). Some test:
```
⍪{6⍕⍵a[2]F 1⊃a}¨⍳2⊣a←⎕
⎕:
5 3
10.208333
14.541667
⍪{6⍕⍵a[2]F 1⊃a}¨⍳2⊣a←⎕
⎕:
8.555 13
0.765431
¯0.641092
⍪{6⍕⍵a[2]F 1⊃a}¨⍳2⊣a←⎕
⎕:
9.26 10
¯3.154677
¯8.404354
```
OT it would be possible to calculate the *exact* answer using rationals and input rational for example of 1r4 (0.25=1/4)
```
⍪{6⍕⍵a[2]F 1⊃a}¨⍳2⊣a←⎕
⎕:
1r4 10
0.247404
0.968912
{⍵○1r4}¨⍳2
0.2474039593 0.9689124217
{⍵○0.25}¨⍳2
0.2474039593 0.9689124217
1 10 F 1r4
8264318085745811128158727r33404146443928530321408000
2 10 F 1r4
17051609536099989115458551r17598710837038136237752320
```
these last 2 numbers both cut would be the decimals 0.2474039592 and 0.9689124217
] |
[Question]
[
Given an integer n, your task is to determine whether it is a perfect square that when reversed, is still a perfect square. You may assume n is always positive.
When numbers such as 100 (10x10) are reversed the result may have leading zeros (001) In this case, ignore the leading zeros and treat it as 1 (1x1).
## Test cases
```
1 => True
4 => True
9 => True
441 => True
1234567654321 => True
100 => True
3 => False
25 => False
1784 => False
18 => False
```
Shortest code wins!
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 6 bytes
```
¢B¢bÐ√
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6FqsPLXI6tCjp8IRHHbOWFCclF0PFF9xUNeQy4bLkMjEx5DI0MjYxNTM3MzUxNgLyDAy4jLmMTLkMzS1MIKoB)
```
¢B¢bÐ√
¢B Integer to decimal digits in the reverse order
¢b Decimal digits to integer
Ð Pair
√ Square root; fails if not a perfect square
```
`-e` checks if there is a solution.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
Â)ŲP
```
Prints `1` if the condition is met, `0` otherwise.
[Try it online!](https://tio.run/##yy9OTMpM/f//cJPm4dZDmwL@/zc0MjYxNTM3MzUxNjIEAA "05AB1E – Try It Online") Or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCvZLCo7ZJCkr2/w83aR5uPbQp4L/O/2hDHQUTHQVLIGkCZBoaGZuYmpmbmZoYG4G4BgY6CsY6CkamQLa5hUksAA).
### How it works
```
 # Implicit input: n. Push n and (digit-)reversed n
) # Concatenate stack into an array
Ų # Is square? Element-wise
P # Product of array. Implicit print
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `g`, ~~30~~ 27 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), ~~3.75~~ 3.375 bytes
```
Ṙ"∆²
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBZz0iLCIiLCLhuZhcIuKIhsKyIiwiIiwiMVxuNFxuOVxuNDQxXG4xMjM0NTY3NjU0MzIxXG4xMDBcbjNcbjI1XG4xNzg0Il0=)
## Explained
```
Ṙ"∆²
Ṙ" # the list [input, input reversed]
∆² # vectorise is square
# g flag takes the minimum which in this case is equivalent to checking if both items are truthy
```
[Answer]
# Extended Dyalog APL, 18 13 11 bytes
Thanks Adám for -5 bytes!
Takes input as a string.
```
≡∘⌊⍨∘√⍎,⍎⍤⌽
```
Explanation:
```
≡∘⌊⍨⍤√⍎,⍎⍤⌽
, ⍝ make a list of
⍎ ⍝ the input parsed as a number
⍎⍤⌽ ⍝ and the reversed input parsed as a number,
√ ⍝ take the square root of both,
≡∘⌊⍨ ⍝ is that list equal to itself after you floor it?
```
[Answer]
# [Factor](https://factorcode.org) + `math.unicode` `project-euler.037.private`, 46 bytes
-5 bytes thanks to @chunes
```
[ dup reverse-digits [ √ dup ⌊ = ] both? ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Lc6xTsMwEAbg_Z7iVJHRURw7TaGiHatKFQtiCh2MfWmMShK5dp8BIZ4Ali7wTln7JDgt46_7_l_3_Vsr7Tt3GjZPj-uH1R32rnsl7RmFPbk0E2XaO3tUnvBN-SYNrdWdIZwDOFKG7W1LB6zQkF7gNpoeTeh_gq_ZbEirMaCjI7kDMWN31o_4_P51OZw_P_A-tl463yxx-9-6GUcqnCSMC4NsgUl4bifxMdv6OuqclG6u9jQkHCTcgpQceC5kMS2nhRR5TFkGAvICeDmTV_0H)
* `[ ... ]` Quotation (anonymous function) taking a number
* `dup` Duplicate so number is on the stack twice
* `reverse-digits` Reverse the digits of the copy
* `[ ... ] both?` Apply the quotation to both and check if both return `t`:
* `√` Square root
* `dup` Push a copy
* `⌊` Round down
* `=` Are this and the original equal?
`√ dup ⌊ =` seems to be the shortest way to check if a number is a perfect square, since `√ integer?` doesn't work.
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `M`, 4 bytes
Requires v2.2.2: [Try it](https://Not-Thonnu.github.io/run?code=%E1%B8%B2%2C%C3%86%C2%B2&input=100&flags=M)
```
Ḳ,Ʋ
```
# [Thunno 2](https://github.com/Thunno/Thunno2) `G!`, 6 bytes
Works on old version of Thunno 2.
```
ḲNKƭ1%
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faFm0kruiUuyCpaUlaboWKx_u2OTnfWytoeqS4qTkYqjogrWGRsYmpmbmZqYmxkaGEEEA)
* `Ḳ` Bifurcate - duplicate and push reverse
* `N` Cast reversed to integer
* `K` The stack as a list
* `ƭ` The square root of each
* `1%` Each mod 1 (0 if integer, nonzero else)
* `G` flag - maximum, 0 [iff](https://en.wikipedia.org/wiki/If_and_only_if) both are integers
* `!` flag - logical not
This could be 4 bytes with `m` flag if we had an `is_square` built-in, or 5 bytes with same flag if we had an `is_int` built-in.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
↔;?~^₂ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HbFGv7urhHTU0Pt074/9/ExPA/AA "Brachylog – Try It Online")
### Explanation
```
↔;? The list [reversed(Input), Input]
~^₂ᵐ Each element must be the square of some number
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~63~~ ~~60~~ 58 bytes
Saved 5 bytes thanks to the comments of @Shaggy and @Dominic van Essen
---
Golfed version. [Try it online!](https://tio.run/##TU7LasMwELzrK7aHgkTB2HkVDDI05ySX0lPpYe1KjoosNWslUIq/3V270HouuzM7O0zfoMcx1h@mSXBEF@BbALwbCx0TidT2JTwR4dfrcyIX2jdVwktwCTQ7hbihB1seYmh1tY/RGwx6DLqSHaZz1l8oyaAeFiRL8TcoI3Mz1BsWpnel7osqH4Ehc7iG5DwUOUNlNpLB5iwd6GquN8FZkHdWOqXgk@OSD7zPt0GJeU7Vateerl1tiOsWq/Vmu3vcbTfrVXEQi5A/1yLsX2PnIAYx/gA)
```
n=>(math.sqrt(n)+math.sqrt(n.toString.reverse.toLong))%1>0
```
Ungolfed version. [Try it online!](https://tio.run/##XU89T8MwFNzzK65DJXuJkn4hRQpSmQtIICbE4KS2a@Ta4LiVEO1vD05cQoMnv7t7d/eammnWtrZ657XHPVMG3wmw5QL7MBDmZFNg7Rz7en32Thn5Rgu8GOVR9sqoFcQU2FgjA3lnrebMDDxwZBrNp/OPTkllwlAGc79LO4wY@k/1xI/cNXw7VqXexvzURT4AfWByWR8FTJFjUiLD6TT2/CX6pXPcJRkOxiuNPAuPpsI6zuodUShvhxuUAJkIoijFR6jhtQn/6HKp0PWvlHw47CvuQvl8Nl8sVzer5WI@yzfJlcmgujL7w5Ku2Dlp2x8)
```
object Main {
def main(args: Array[String]): Unit = {
def f(n: Long): Boolean = {
val sqrtOriginal = math.sqrt(n)
val sqrtReversed = math.sqrt(n.toString.reverse.toLong)
sqrtOriginal % 1 != 0 || sqrtReversed % 1 != 0
}
(0 until 10000).foreach(i => {
if (!f(i)) println(i)
})
val bigNumber = 1234567654321L
if (!f(bigNumber)) println(bigNumber)
}
}
```
[Answer]
# [R](https://www.r-project.org), ~~56~~ ~~55~~ 54 bytes
*Edit: -1 byte after looking at [pajonk's answer](https://codegolf.stackexchange.com/a/262370/95126), and -1 byte by rearranging*
```
\(x)(x^.5+(x%/%rev(z<-10^(0:log10(x)))%%10%*%z)^.5)%%1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3zWI0KjQ1KuL0TLU1KlT1VYtSyzSqbHQNDeI0DKxy8tMNDYDympqqqoYGqlqqVZpAhSAORPctxoeZaRppGoaamgVFmXklGkpuiTnFqUqaqUBSASoUUlQKFFFQVrC1UwCxucBaTEjXYkmGLSZkOM3QyNjE1MzczNTE2Igc7QYGpGsyJlYLWBqix8iUDE2G5hZEBz1YGhLTCxZAaAA)
Outputs zero (falsy) for reversed-squares, non-zero (truthy) for other numbers.
Based on the fact that there does not exist any pair of integers `x` and `y` that are not both squares, but for which `sqrt(x)+sqrt(y)` is an integer: [see here](https://math.stackexchange.com/questions/880081/the-sum-of-two-irrational-square-roots).
[Answer]
# [Raku](https://raku.org/), 23 bytes
```
{sqrt($_|.flip)!~~/\./}
```
[Try it online!](https://tio.run/##DcfdCkAwGAbgW3lpiRNs@zYUrkQtB1aKME7k59bHc/asg5u0n09EFo2/9s0dMTN3aqdxTYL3zbo0e/zenwiZQdPismDmCWEXh5qDUIGIgwtJShdakRT/8hwSQoEXJbX@Aw "Perl 6 – Try It Online")
`$_ | .flip` is an or-junction of the input number and its flipped string representation, which Raku treats as a number in nearly all contexts. `sqrt` applied to that or-junction produces another or-junction that contains the square roots of the two numbers above. Then the function returns whether it is not (`!`) the case that either of those square roots match (`~~`) the regular expression containing a period (`/\./`).
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
lambda n:n**.5%1+int(`n`[::-1])**.5%1>0
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMHiNNuYpaUlaboWN9VzEnOTUhIV8qzytLT0TFUNtTPzSjQS8hKirax0DWM1IYJ2BlDlNmn5RQqZCpl5CkWJeempGoYGQKCpHW1oZGxiamZuZmpibGQYa8WlkJmmkJdfopCmkalpVVAEMjNTE2LGggUQGgA)
Reversed squares, reversed output. Returns False if input is a square and reversed square, True if not.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 39 bytes
```
$
¶$`
O$^`\G.
.+
$*
%A`(^1|11\1)+$
^¶$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX4Xr0DaVBC5/lbiEGHc9Li49bS4VLS5VxwSNOMMaQ8MYQ01tFa44oJr//w25TLgsuUxMDLkMDSwsgYQBlzGXkSmXobmFCQA "Retina 0.8.2 – Try It Online") Link includes faster test cases. Explanation:
```
$
¶$`
```
Duplicate the input.
```
O$^`\G.
```
Reverse the first copy.
```
.+
$*
```
Convert to unary.
```
%A`(^1|11\1)+$
```
Delete square numbers.
```
^¶$
```
Check that both numbers were deleted.
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$8\log\_{256}(96)\approx\$ 6.585 bytes
```
!a%1mqw$
```
[Try it online!](https://fig.fly.dev/#WyIhYSUxbXF3JCIsIjQ0MSJd)
```
$ # Inupt reversed
w # Pair with the input (we now have [reversed(n), n])
mq # Square root of each one
%1 # Modulo 1
a # Any truthy (i.e. more than 0)
! # Logical NOT
```
[Answer]
# [Arturo](https://arturo-lang.io), 42 bytes
```
$->n[0=+%sqrt do reverse~"|n|"1(sqrt n)%1]
```
[Try it!](http://arturo-lang.io/playground?hqph7l)
```
$->n[ ; a function taking an argument n
0= ; is zero equal to
+ ; the sum between
%sqrt do reverse~"|n|"1 ; the square root of n reversed modulo one
(sqrt n)%1 ; and the square root of n modulo one
] ; end function
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
¬Σ﹪₂I⟦θ⮌θ⟧¹
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjftAooy80o0_PJLNIJLczV881NKc_I1ggtLE4tSg_KBos6JxSUa0YU6CkGpZalFxakahZqxmpo6CoaaQGC9pDgpuRhq1vJoJd2yHKXYJYYGFpYQIQA "Charcoal – Attempt This Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if a member of A061457, nothing if not. Explanation: Uses floating-point arithmetic, so will go wrong on large enough inputs.
```
θ Input as a string
θ Input as a string
⮌ Reversed
⟦ ⟧ Make into a list
I Cast to integer
₂ Take the square root
﹪ Modulo
¹ Literal integer `1`
Σ Take the sum
¬ Logical Not
Implicitly print
```
15 bytes for a theoretically correct version which actually has worse performance because it creates a list of length of the input:
```
Nθ¬⁻⟦θ⮌θ⟧X…·⁰θ²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDL79Ewzczr7RYI7pQRyEotSy1qDgVKB@roxCQXw5U6pmXnFNanFmWGpSYl56qYaCjUKipo2CkCQTW//8bGlhY/tctywEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ First input as a number
θ First input
θ First input
⮌ Reversed
⟦ ⟧ Make into a list
⁻ Set difference with
…· Inclusive range from
⁰ Literal integer `0` to
θ First input
X Vectorised raise to power
² Literal integer `2`
¬ Logical Not
Implicitly print
```
23 bytes for a version that imports Python's `math.isqrt`:
```
⬤I⟦θ⮌θ⟧⁼ιX▷math.isqrtι²
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjcDA4oy80o0HHNyNJwTi0s0ogt1FIJSy1KLilM1CjVjNXUUXAtLE3OKNTJ1FALyy1OLNFzLEnPCEos0lHITSzL0MosLi0qUdBQygSqNNIHAeklxUnIx1Pjl0Uq6ZTlKsUsMDSwsIUIA "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation:
```
θ Input as a string
θ Input as a string
⮌ Reversed
⟦ ⟧ Make into a list
I Cast to integer
⬤ All values satisfy
ι Current value
▷math.isqrt Integer square root
X Raised to power
² Literal integer `2`
⁼ Equals
ι Current value
Implicitly print
```
37 bytes for a version that uses the Babylonian method to find the integer square root and so will work with arbitrarily large integers in linear time on the number of digits:
```
⊞υI⟦θ⮌θ⟧W⁼¹№υ⌊υ⊞υE⌊υ÷⁺κ÷§⌈υλκ²⁼⌈υX⌊υ²
```
[Try it online!](https://tio.run/##VY09C8IwEIZ3f0XGC1SwToqTqEOHQnAVh9AeNDRNbJJr@@9jKn7Ug7vh7nnvqRrpKit1jIJ8A5Sxk/QBbn3Grjig8wg9v3N@WI2N0sjg0pPUHvIEWjJhTpTKqI46IJ6Kff6U8gG/S8YKE85qUDWC0OShXW6OoTA1TlDK6cvr1C1PY8tnvXAq2d72JSfsiO7P9ArEmG92@7ge9BM "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υI⟦θ⮌θ⟧
```
Start with the input and its reversal both as the target and the initial estimate.
```
W⁼¹№υ⌊υ
```
Repeat until the estimate converges.
```
⊞υE⌊υ÷⁺κ÷§⌈υλκ²
```
Get the next estimate.
```
⁼⌈υX⌊υ²
```
Check that the square of the final estimate gives the target.
[Answer]
**Java 8, 83 bytes**
```
n->Math.sqrt(n)%1==0&Math.sqrt(new Long(new StringBuilder(""+n).reverse()+""))%1==0
```
this lambda can be used for a functional interface such as IntPredicate
[Try It Online](https://tio.run/##ZU5NS8QwED23v2IoKAnLBhU8ST14E1wQ9igeZpuxpqaTmkwqIvvba7AexJ3LDG/e14AzbsNEPNi3ZZnywbsOOo8pwQ4dw1dd/YJJUMqag7MwlpfaS3TcPz0Dxj7pwoR/MxRvk8V585K5ExfY3LM8RrKuQyHwOB4stic6AN7e7lBeTXqPolifXbbtxfkfhD7gIXD/c6w17rLzlqJqmg1rE2mmmEjpTdPoVX6SclNX1f4zCY0mZDFTcRHPai1lhJKo6yutC@1YH5flGw)
[Answer]
# [R](https://www.r-project.org), ~~59~~ 58 bytes
```
\(n,t=10^(1:nchar(n)-1))n^.5%%1|(n%/%t%%10%*%rev(t))^.5%%1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3rWI08nRKbA0N4jQMrfKSMxKLNPI0dQ01NfPi9ExVVQ1rNPJU9VVLgCwDVS3VotQyjRJNTYgU1ISpaRqGmsoKtnYKIUWlqVxpGiYoPEtUORNUtYZGxiamZuZmpibGRmgyBgZIfKCAMYTrlphTDJI3MkXlG5pbmCCJQBy3YAGEBgA)
```
\(n,t=10^(1:nchar(n)-1))any(c(n,n%/%t%%10%*%rev(t))^.5%%1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3rWI08nRKbA0N4jQMrfKSMxKLNPI0dQ01NRPzKjWSgXJ5qvqqJaqqhgaqWqpFqWUaJZqacXqmQAFNqAlT0zQMNZUVbO0UQopKU7nSNExQeJaociaoag2NjE1MzczNTE2MjdBkDAyQ-EABYwjXLTGnGCRvZIrKNzS3MEESgThuwQIIDQA)
Outputs flipped TRUE/FALSE.
[Answer]
# Excel, 80 bytes
```
=LET(
a,LEN(A1),
b,HSTACK(A1,CONCAT(MID(A1,1+a-SEQUENCE(a),1)))^0.5,
AND(INT(b)=b)
)
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
‼°x°╓
```
[Try it online.](https://tio.run/##y00syUjPz0n7//9Rw55DGyoObXg0dfL//4ZcJlyWXCYmhlyGRsYmpmbmZqYmxkZAnoEBlzGXkSmXiQWXobmFCQA)
Or alternatively:
```
xαm°╓
```
[Try it online.](https://tio.run/##y00syUjPz0n7/7/i3MbcQxseTZ38/78hlwmXJZeJiSGXoZGxiamZuZmpibERkGdgwGXMZWTKZWLBZWhuYQIA)
**Explanation:**
```
‼ # Apply the next two operators separately on the current stack:
# (which will use the implicit input-integer)
° # Check if it's a perfect square
x # Reverse it
° # Check if this top reversed integer is a perfect square as well
╓ # Pop both, and get the minimum of the two
# (which will be truthy if both were truthy; or falsey if either/both were falsey)
# (after which the entire stack is output implicitly as result)
x # Reverse the (implicit) input-integer
α # Pair the top two values, which is the (implicit) input and the reversed input
m # Map over this pair:
° # Check for both whether it's a perfect square
╓ # Pop the square, and push its minimum
# (which will be truthy if both were truthy; or falsey if either/both were falsey)
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ṚƬḌ½ḞƑ
```
[Try it online!](https://tio.run/##y0rNyan8///hzlnH1jzc0XNo78Md845N/H@4XTPy//9oLkMdLhMdLksgaQJkGhoZm5iamZuZmhgbgbgGBjpcxjpcRqZAeQsg39wCqDgWAA "Jelly – Try It Online")
```
ṚƬ Reverse while unique.
Ḍ Vectorizing convert from decimal.
½ Vectorizing square root.
Ƒ Is the entire list of results unchanged by
Ḟ vectorizing floor?
```
[Answer]
# [Lua](https://www.lua.org/), 26 bytes
```
n=...a=n^.5&n:reverse()^.5
```
[Try it online!](https://tio.run/##yylN/P8/z1ZPTy/RNi9Oz1Qtz6ootSy1qDhVQxPI/f//v6GRsYmpmbmZqYmxkSEA "Lua – Try It Online")
Outputs using the exit code (`0` is true, `1` is false).
This works because Lua can't do bitwise operators on non-integer numbers. If either `n^.5` or `n:reverse()^.5` is not an integer, the program will error.
[Answer]
# Javascript, ~~43~~ ~~40~~ 42 Bytes
Thanks to @Arnauld for -3 Bytes (-2 from backticks (which I forgot), -1 from inverse output)
```
n=>[...n].reverse().join``**.5%1*n**.5%1>0
```
[TIO](https://tio.run/##fc5NCoMwEAXgfU8hQiEKHZOY@LPQi5SCQZKiSFISm@unlHZRKsxqFt97j1lVVGH2y2O/xC6ZIdlhvAKAvYHXUfugSQGrW@w0lSXIMyvt5440zc4Gt2nY3J0YkrO8KLKqynb/1Kc/E4j1WE9gq4zXQjZtI0XN0Rylv3rgvvmyUVs4tGsMucSUtZ1A/f11egE)
[Answer]
# [JavaScript (V8)](https://v8.dev/), 40 bytes
```
g=x=>x**.5%1||g([...x].reverse().join``)
```
[Try it online!](https://tio.run/##fdDdCoIwFAfwe59iCMEmNL/mF2EvEoEypiniYk4x0mc3Mwsx2Lna2e9/zsUp0y5tqCju8tiF05THfXzuDQN7B3sYcnjBGPdXLFjHRMMgwiUv6iRBU9bWVBa8BhnsEXhqYC4pHuvrXfkMp18nmGzFnE6rhn1@R0BTSW8AMrSZWnNStN@YNmoa5XXDK4YrnsMM6raOEDDNJbU3orBINUdUW23HJZ4f@B5xHWXOsrb6x5G/8nKIPbsqdDyV2kFItj69AA "JavaScript (V8) – Try It Online")
Throws as `true` and not throw as `false`.
Here assumes a reasonable stack(actually <1KB is enough, number is stored in heap) so it's allowed
# [C (gcc)](https://gcc.gnu.org/), 66 bytes
```
a;g(n){a=sqrt(n);a=a*a-n;}f(n){for(g(n);n;n/=10)a+=9*a+n%10;g(a);}
```
[Try it online!](https://tio.run/##XVDbboMwDH3vV3hIlQIEFXrRirLsZdpXDB6iNDC0NnRJpqFV/PqYoRTRRbblHPs4OZZRKWXXCVYS7V8Et5/GYcYEF4GINGuLHi9qQ/oGpple8ST2RcjTQIR6mcTIFD5ru0o7OIlKEx8uC8DTA05ZZ99y4HBJKGwppBi3mCZxTGFDYb3D/HGPlWSPnrRs4qrmrKRTh4k@t3huI0nW2jqQ78IEGJX8UObK9bLmdZ016Qv6zqMwv2@8kY0agfTvVvqgGqTFbEyfwFY/qi7I7Uf@agSCCWEQhkP3Tf20AZx03cJQztld1WL1oSDOv4cVwpP8/7yzwZaCeMsDRM@AcWkzjaocBUsn4ZZzlY9j2yEa5b6MRlmLtvuVxVGUtouOpy76/gM "C (gcc) – Try It Online")
Strongly pushed [Noodle9's](https://codegolf.stackexchange.com/a/262365/76323)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
->n{n**0.5%1+n.digits.join.to_i**0.5%1==0}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk9Ly0DPVNVQO08vJTM9s6RYLys/M0@vJD8@Eypja2tQ@79AQcNAT8/QwMBAU684NSc1uURDLU3zPwA "Ruby – Try It Online")
[Answer]
# [Racket](https://racket-lang.org) - 155 bytes
```
#lang racket
(define(m v)(let([r(string->number(list->string(reverse(string->list(number->string v)))))][? integer?])(and(?(sqrt v))(?(sqrt r)))))(m(read))
```
[Try it online!](https://tio.run/##PYw7DoMwEET7nMJSmnVBwZ80@CCIwok3lhVjifWG6zsYRKaaz9OQfn2QU7p7HaygI93A4NsFhEVsEjwyTASRyQVbjOG7PJHAu8jFeJZAuCFF/DN5hBO8mP0pa56UcIHRIqlZgg4GFMSVOO@XpQOFZf/VRsqUyqpu2q4fHkPftU1dlT8 "Racket – Try It Online")
---
## Explanation
On line one, we have Racket's required language statement, `#lang racket`, This just imports all of the statements/functions used in the language (like `define` and `read`, as well as wrapping our program into a `module`.
The second line is where the main program lies. We define a function named `m`. This function received an integer `v` as an argument. We then reverse the integer to obtain an integer named `r`. We take the square roots of both `v` and `r` and see whether they are integers or not. If both checks return true, then the number is a Reversed Perfect Square.
Here's the program in all its glory. In the shortened form, I embedded `reverse-number` as part of `main`'s local scope. But to make it easier to read and understand, I made it its own function:
```
#lang racket
(define (reverse-number value)
(string->number (list->string (reverse (string->list (number->string value))))))
(define (main value)
(let ([reversed-value (reverse-number value)])
(and (integer? (sqrt value))
(integer? (sqrt reversed-value)))))
(main (read))
```
As of right now, Racket doesn't have a `reverse-string` or `string-reverse` function. So, the only way I could reverse the number was to first convert the number to a string, then convert the string to a list, reverse the list, convert the list to a string, then convert the string to a number. But if we did have a `string-reverse` function, I would've written:
```
(string->number (string-reverse (number->string value)))
```
Also, while I could've used `quotient` and `remainder`, it ended up bumping the number of bytes up by a tad bit (I got 180).
---
Example usages of `main`:
```
;; An infinite loop that loops over all natural numbers [1..] and finds all RPSs
(for ([i (in-naturals)] #:when (main i))
(displayln i))
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~10~~ 9 bytes
*-1 byte by realizing that `v` automatically vectorizes*
```
sMI@R2v_B
```
[Try it online!](https://tio.run/##K6gsyfj/v9jX0yHIqCze6f9/JUMTEyUA "Pyth – Try It Online")
### Explanation
```
sMI@R2v_BQ # implicitly add Q
# implicitly assign Q = eval(input())
_BQ # bifurcate Q over reversal
v # eval (automatically vectorizes)
@R2 # map each to their square roots
I # check for invariance over
sM # converting the entire list into integers
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
[UUsÔ]m¬ev1
```
PD: Definitely can be golfed down
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=W1VVc9RdbaxldjE&input=MTIzNDU2NzY1NDMyMSAK)
---
# [Japt](https://github.com/ETHproductions/japt) [`-¡`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
¬v1 ©UsÔ¬v1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LaE&code=rHYxIKlVc9SsdjE&input=MTc4NAo)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-E!`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Based on [l4m2's solution](https://codegolf.stackexchange.com/a/262379/58974) but with correct output.
```
¬%1ªßUìÔ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LUUh&code=rCUxqt9V7NQ&input=MTc4NA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes
```
AtomQ@Tr@Sqrt@{#,IntegerReverse@#}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b737EkPzfQIaTIIbiwqMShWlnHM68kNT21KCi1LLWoONVBuVbtf5q@Q7WhjomOpY6JiaGOoZGxiamZuZmpibERkGdgoGOsY2SqY2huYVKrrx9QlJlX8h8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~75~~ ~~73~~ 67 bytes
```
b;f(n){b=sqrt(n);for(b=b*b-n;n;n/=10)b+=9*b+n%10;n=sqrt(b);b-=n*n;}
```
[Try it online!](https://tio.run/##ZVDbbsIwDH3nK7xKSGmbiobLBsqyl2lfMXggacqqQWBJplWr@uvrTFsq2HJxnGP7JD4q2SnVNJLnxISVFO7DevR4frREChnJxHCcE8HSUMZiFcnYjFnKTZcpQy4TYSLD66YwHg7bwpAQqhHgOANeO@9eNyCgYhTmFFZo5@iyNKUwozBdoP@wxAhb4mb9ec9qPpDo8qSV19nAc73S/6svVUfjPKi3rY3QavWubccQrMuX6bpcPeNeBBSu77Ogr0YFgJxfL0ymSyxLee8@giu@9TEnl3@Fkx6IBoRDHLfZFzEGQZCpE6UNb/hN1GH0Lic@vIU1woMIf@tOFlNyEowzSJ4A7ditDXblKTg6NO6E0Juetm6t1f7TGmxrVDc/Kt9vd65J9ocm@foF "C (gcc) – Try It Online")
*Saved ~~2~~ 8 bytes thanks to [c--](https://codegolf.stackexchange.com/users/112488/c)!!!*
] |
[Question]
[
You are to take a string representing a piece of brainfuck code and Explanations, containing only printable ASCII characters and newlines ( to `~`, ASCII 10 and 32 to 126) as input and output an explanation of that code, formatted to be compliant with Stack Exchange markdown.
That is, the explanation must satisfy:
* Each line has an additional leading space, or multiple if the line above has multiple characters of code, such that it remains aligned vertically
* All commands are on their own line, while any consecutive no-ops (anything that isn't one of `<>+-.,[]`) are grouped together on one line
* The "explanation" for each command are all aligned to a single column, one space after the code itself
* The entire thing is in a "code block".
+ Either the entire explanation has a preceding and trailing ````` line, or
+ The entire explanation has a preceding `<pre><code>` line and a trailing `</code></pre>`
+ Each line of the explanation has 4 leading spaces, in addition to any leading spaces it might already have.
+ You don't have to escape parts of the output that might break the markdown.
* The first line of code block is the BF input code.
For example, if the code is `+[]Loop`, the explanation (without "explanations") would be formatted as one of
```
+[]Loop
+
[
]
Loop
```
```
<pre><code>+[]Loop
+
[
]
Loop
</code></pre>
```
```
```
+[]Loop
+
[
]
Loop
```
```
### Explanations
The explanation for each character will be provided as input:
```
Move the pointer to the right
Move the pointer to the left
Increment the memory cell at the pointer
Decrement the memory cell at the pointer
Output the character signified by the cell at the pointer
Input a character and store it in the cell at the pointer
Jump past the matching ] if the cell at the pointer is 0
Jump back to the matching [ if the cell at the pointer is nonzero
No Operation
```
The input always contain 9 explanation strings.
Answers can choose how to associate each brainfuck command with each explanation.
You may use array.
We can now add these explanations to our sample code to get
```
+[]Loop
+ Increment the memory cell at the pointer
[ Jump past the matching ] if the cell at the pointer is 0
] Jump back to the matching [ if the cell at the pointer is nonzero
Loop No Operation
```
(using 4 leading spaces instead of backtick fencing or HTML tags).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Testcases
Input:
```
[]<>{}()++--..,,
Move the pointer to the right
Move the pointer to the left
Increment the memory cell at the pointer
Decrement the memory cell at the pointer
Output the character signified by the cell at the pointer
Input a character and store it in the cell at the pointer
Jump past the matching ] if the cell at the pointer is 0
Jump back to the matching [ if the cell at the pointer is nonzero
No Operation
```
Output:
```
[]<>{}()++--..,,
[ Jump past the matching ] if the cell at the pointer is 0
] Jump back to the matching [ if the cell at the pointer is nonzero
< Move the pointer to the left
> Move the pointer to the right
{}() No Operation
+ Increment the memory cell at the pointer
+ Increment the memory cell at the pointer
- Decrement the memory cell at the pointer
- Decrement the memory cell at the pointer
. Output the character signified by the cell at the pointer
. Output the character signified by the cell at the pointer
, Input a character and store it in the cell at the pointer
, Input a character and store it in the cell at the pointer
```
Input:
```
Brainfuck Power.
Move the pointer to the right
Move the pointer to the left
Increment the memory cell at the pointer
Decrement the memory cell at the pointer
Output the character signified by the cell at the pointer
Input a character and store it in the cell at the pointer
Jump past the matching ] if the cell at the pointer is 0
Jump back to the matching [ if the cell at the pointer is nonzero
No Operation
```
Output:
```
```
Brainfuck Power.
Brainfuck Power No Operation
. Output the character signified by the cell at the pointer
```
```
Input:
```
>++++++[{{<,.>-}}]
Move the pointer to the right
Move the pointer to the left
Increment the memory cell at the pointer
Decrement the memory cell at the pointer
Output the character signified by the cell at the pointer
Input a character and store it in the cell at the pointer
Jump past the matching ] if the cell at the pointer is 0
Jump back to the matching [ if the cell at the pointer is nonzero
No Operation
```
Output:
```
<pre><code>>++++++[{{<,.>-}}]
> Move the pointer to the right
+ Increment the memory cell at the pointer
+ Increment the memory cell at the pointer
+ Increment the memory cell at the pointer
+ Increment the memory cell at the pointer
+ Increment the memory cell at the pointer
+ Increment the memory cell at the pointer
[ Jump past the matching ] if the cell at the pointer is 0
{{ No Operation
< Move the pointer to the left
, Input a character and store it in the cell at the pointer
. Output the character signified by the cell at the pointer
> Move the pointer to the right
- Decrement the memory cell at the pointer
}} No Operation
] Jump back to the matching [ if the cell at the pointer is nonzero
</code></pre>
```
Input:
```
><+-.,NOP[]
Move
Move
Increment
Decrement
STD
STD
While
While
NOP
```
Output:
```
><+-.,NOP[]
> Move
< Move
+ Increment
- Decrement
. STD
, STD
NOP NOP
[ While
] While
```
Input:
```
-\
Blah
Blah
Blah
Decrement
Blah
Blah
Blah
Blah
Nothing happens here
```
Output:
```
-\
- Decrement
\ Nothing happens here
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~811~~ ~~775~~ ~~709~~ 701 bytes
```
>>-[-[--->]<<-]>--...<++++++++++.>>>>>>>>>>+[->>>>>>+<<,[[-<+<+>>]<----------[[-]->]-[+>-]<<<+[-<[-]>]<[-<+>>+<]++++++[->-------<]>>++++++[-<<++++++>>]>+<<-[<->>]>[<]<-[<------->>]>[<]<-[<-->>]>[<]<-[<-------->>]>[<]<--------------[<--->>]>[<]<--[<---->>]>[<]+++++[-<------>]<+[<----->>]>[<]<--[<------>>]>[<]<[-]<<+>[>>>-]<[>>>]<<<->>++++[->++++++++<]+>>>+>]<]+[<<<<<<]>>>>[.>>>>>>]>>>>-<<<<<<<<<<[<<<<<<]<<<<<.>>>+[->>>>>>>>>>>>>[>>>>>>]<<<<<[<[<<.<<<<]>>>>>>[>>>>>>]<<<<<.>>>>[>+>>>>>[<<<<.>>>>>+>>>>>]<<<<[>>>.>>>]>>>.>>>[.>>>>>>]>>[<<<<<<]<]<<<[>->>>+>[>>>.>>>]>>-<<<<<.<[<<<<<<]<[->>>>>>>[>>>>>>]+>>>>[>>>>>>]>>-<<<<<<[<<<<<<]<]>+[>>>>>>]+>>>>[.>>>>>>]>>[<<<<<<]<<<<]+<<<.>>]>]>[<<<<<<]<<<<<<...
```
[Try it online!](https://tio.run/##bVJNT8MwDL33r2TOL7BygQsSAomr5QNMGUxAW432NO23j5fESduBKzXO8/Pzh/J2ej32h3n/eb2GQIKPKCgzaSDy3rNr5kMzJ2QO806E2LELSKNmABVCJC4Q5BgZDAicxE6JWlShZCmsgA1jqwvRVIOEKbnCmv1iG@RveIE2luNLqNDtXqtbvqJtvpGq8hWRNJ4LgmXAS0cal8ooGK5uD@JpX4gqRLNp2qDYWvOFuFnl5L9f79xMLM/Y4PsmehP1BXEl0hADMifxvbXht221TjTzKCeu@KVpv3TcGq1NuPWlTbnoYrYN85/a6edK45o3v9oO453i@drbOZ955wNdLto9DTSM3UO/P8Xv2E/dfazeYzxM3cvx/WPqnsfYd3dfw08Ec5wBzBOOXw "brainfuck – Try It Online")
This could probably be golfed more, as this is, like, the second brainfuck program I've written.
## Explanation
I should really write a program to do this for me...
[Fullscreen Explanation](https://pastebin.com/raw/3qAzHtbm)
```
#####
# Execution will be divided into two phases: input and output.
# The input phase will input all characters and lay them out into memory with metadata.
# The output phase will then loop over the memory and print various segments of it, forming the explanation.
###############
# Input Phase #
###############
#####
# First, let's take a look at the memory layout.
# We'll divide the memory into 6-byte chunks.
# The chunks will be laid out in this format:
# - first header chunk, to denote the start
# - second header chunk, to denote the start
# - first source chunk
# - second source chunk
# - ...
# - last source chunk
# - primary separator chunk (in place of newline)
# - first chunk of first explanation
# - second chunk of first explanation
# - ...
# - last chunk of first explanation
# - separator chunk (in place of newline)
# - first chunk of second explanation
# - ......
# - last chunk of last explanation
# - eof chunk
# The first header chunk will have the following bytes:
# 0 10 96 0 0 0
# (10 is newline, and 96 is backtick)
# The second header chunk will consist entirely of zeroes.
#####
# Initialize the header chunks and output the initial code fence:
>> # Move to cell #2 (0-indexed).
-[-[--->]<<-]>-- # Set cell #2 to backtick (96) (pulled from https://esolangs.org/wiki/Brainfuck_constants).
... # Print it thrice (fine, there is a tiny bit of output in this phase).
<++++++++++. # Set cell #1 to newline (10) and print it.
>>>>>>>>>>+ # Move to cell #5 of the second header chunk and temporarily set it to 1.
#####
# Next, read the input into chunks and initialize them.
# Every non-header non-eof chunk will be initialized to the following format:
# #0: [char] (0 if separator)
# #1: [kind] (which operator the char is)
# #2: [mark] (currently 1; this will occasionally be temporarily set to 0 as a "bookmark")
# #3: 32 (the code for space, used for output)
# #4: [noop] (1 if no-op source chunk or non-primary separator, 0 otherwise)
# #5: [done] (currently 0, undone)
# During the initialization, some cells are used for temporary values.
[ # While the current cell (#5 of the preceding chunk) is non-zero (and thus known to be 1), loop over the input:
- # Subtract 1 from the cell, [done], returning it to 0 (undone)
> # Move to the active chunk.
# Cell #5 will be used for positioning the pointer after a branch ('alignment'):
>>>>>+ # Set cell #5 to 1
#####
# Next, we'll read a character.
<<, # Move to cell #3 and input a character into it (temp).
[ # If this character is non-zero (not eof):
[-<+<+>>] # Duplicate this character into cells #1 and #2 [temp], erasing this cell, #3.
<---------- # Move to cell #2 and subtract 10 (code for newline) from it.
# The chunk is now:
# #0: 0
# #1: char (temp)
# > #2: char - 10 (temp)
# #3: 0
# #4: 0
# #5: 1 (alignment)
#####
# Next, if char is newline (10), we'll set cell #1 to 0.
[[-]->] # If cell #2 (char - 10) is non-zero (the char is not a newline), set this cell to 255 and move to cell #3.
-[+>-] # Move to the first cell to the right set to 1 (cell #5), and set it to 0.
# (The above is done without any net change to other cells.)
<<<+ # Move to cell #2 and add one to it; this cell is now 1 if char is a newline, or 0 otherwise.
[-<[-]>] # If cell #2 is 1, set it back to 0, move to cell #1, clear it, and move back to cell #2.
# From now on, char will be 0 if the character was a newline.
# The chunk is now:
# #0: 0
# #1: char (temp)
# > #2: 0
# #3: 0
# #4: 0
# #5: 0
#####
# Next we'll inialize cell #0 [char] and put a copy of char into cell #2.
< # Move to cell #1.
[-<+>>+<] # Duplicate this value to cells #0 and #2, clearing this cell.
# The chunk is now:
# #0: [char]
# > #1: 0
# #2: char (temp)
# #3: 0
# #4: 0
# #5: 0
#####
# Next, we'll initialize cell #1 [kind] to a number denoting the 'kind' of the char is.
# The kind is an index from 0 to 8 matching the order "N+-<>[],." (where N stands for any no-op).
# The kind could be determined by directly checking if the character matches an operation (char == op).
# In BF, however, it's easier to check if something is not equal to X than if it is equal to X.
# We'll start cell #1 [kind] at the sum of the kind, 36 (1+2+3+4+5+6+7+8).
# For each operation, we'll check if the character does not match that operation, (char != op).
# To do so, we will use cell #2 for checking whether (char - op) is non-zero.
# If the character does not match that operation, we will subtract its kind from the sum.
# After doing so for all of the operations, the result will be the kind of the operation that the character matches.
# We'll do this not in kind order, but in op order: "+" (43), then "," (44), then "-" (45), etc.
#####
>>++++++[-<<++++++>>] # Set cell #1 to 36 and move to cell #3.
>+ # Set cell #4 to 1 to be used for alignment.
# The chunk is now:
# #0: [char]
# #1: 36 (sum of all kinds)
# #2: char (char - 0)
# #3: 0
# > #4: 1 (alignment)
# #5: 0
#####
# The next set of lines are based on using the following pattern for each of the operations:
# Subtract from cell #2 the difference between the char codes for this operation and the previous.
# If cell #2 is not zero (if char != op):
# Remove this kind from the sum by subtracting from cell #1 (kind_sum) the kind of this operation.
# Return to cell #2 (using cell #4 for alignment).
# The resulting chunk will be:
# #0: [char]
# #1: kind_sum
# > #2: char (char - op)
# #3: 0
# #4: 1 (alignment)
# #5: 0
# For '+', check 43:
<++++++[-<------->]<- # Subtract 43 (6 * 7 + 1) from cell #2, the difference between '+' and 0.
# The value in cell #2 is now char - 43.
[ # If the cell #2 is non-zero (char != 43; the character is not '+'):
<->> # Subtract from cell #1 the kind of '+', 1.
] # End if.
>[<]< # Return to cell #2 (using cell #4 for alignment).
# (For the remaining operations, the pattern will be shown in a condensed form.)
# For ',', check 44:
- # Subtract 1 (the difference between ',' and '+').
[<------->>]>[<]< # If not zero, remove 7 from kind_sum. Return to cell #2.
# For '-', check 45:
- # Subtract 1.
[<-->>]>[<]< # If not zero, remove 2 from kind_sum. Return to cell #2.
# For '.', check 46:
- # Subtract 1.
[<-------->>]>[<]< # If not zero, remove 8 from kind_sum. Return to cell #2.
# For '<', check 60:
-------------- # Subtract 14.
[<--->>]>[<]< # If not zero, remove 3 from kind_sum. Return to cell #2.
# For '>', check 62:
-- # Subtract 2.
[<---->>]>[<]< # If not zero, remove 4 from kind_sum. Return to cell #2.
# For '[', check 91
>+++++[-<------>]<+ # Subtract 29 (5 * 6 - 1).
[<----->>]>[<]< # If not zero, remove 5 from kind_sum. Return to cell #2.
# For ']', check 93
-- # Subtract 2.
[<------>>]>[<]< # If not zero, remove 6 from kind_sum. Return to cell #2.
#
[-] # Set cell #2 to zero.
# The chunk is now:
# #0: [char]
# #1: [kind]
# > #2: 0
# #3: 0
# #4: 1 (temp)
# #5: 0
#####
# Next, cell #4 [noop] will be initialized to 0 if char is not a no-op.
<<+ # Move to cell #0, adding 1 (temporarily, for alignment)
> # Move to cell #1.
[>>>-] # If cell #1 [kind] is non-zero (the char is not a no-op),
# move to cell #4 [noop] and subtract 1 to set it to 0.
<[>>>] # Move to cell #3, using cell #0 for realignment.
<<<- # Move to cell #0 and subtract 1 from it, returning it to char.
# The chunk is now:
# > #0: [char]
# #1: [kind]
# #2: 0
# #3: 0
# #4: [noop] (1 if no-op, 0 otherwise)
# #5: 0
#####
# Next, cell #2 [mark] will be initialized to 1 (unmarked) and cell #3 [space] will be initialized to 32 (code for space).
>>++++[->++++++++<] # Move to cell #2 and set cell #3 to 32 (4 * 8)
+ # Set #2 [mark] to 1 (unmarked)
>>>+ # Move to cell #5 and set it to 1 (temporarily, so the input loop continues; this will be unset in the next iteration).
> # Move to cell #0 of the next chunk.
] # End "if non-eof".
< # If at cell #0 of the next chunk (from the preceding branch for processing a source chunk), move to cell #5 of the current chunk;
# otherwise (at cell #3 after the source chunks), move to cell #2.
] # End input loop.
# Every non-header non-eof chunk is now:
# #0: [char] (0 if separator)
# #1: [kind] (which operator the char is)
# #2: [mark] (currently 1; this will occasionally be temporarily set to 0 as a "bookmark")
# #3: 32 (the code for space, used for output)
# #4: [noop] (1 if no-op source chunk or non-primary separator, 0 otherwise)
# #5: [done] (currently 0, undone)
# Since the loop ended, it reached eof, and the head is at cell #2 of the eof chunk.
################
# Output Phase #
################
#####
# First, we will return to the header chunks.
+ # Set cell #2 to 1 (used later to save a byte).
[<<<<<<] # Move left one chunk at a time until cell #2 is zero, reaching the second header chunk.
>>>> # Move to cell #0 of the first source chunk.
[.>>>>>>] # While cell #0 is non-zero, print it and move to the next chunk
# (this writes the first line of the explanation, the code verbatim).
# Now, the head is at cell #0 of the primary separator chunk.
>>>>-<<<< # Set its cell #4 to 0 (used later to break a loop).
<<<<<<[<<<<<<] # Move to the next 0-char chunk to the left (this is the second header chunk).
<<<<<. # Move to cell #1 of the first header chunk (newline) and output it (ending the first line).
#####
# As we go through each line of the explanation, we'll follow this psuedo-code:
# - Output a space for every source character marked as 'done'
# - Output the characters for the active operations (multiple if it's a chain of no-ops, only one otherwise)
# - Mark all active operations 'done'
# - Output a space for every source character after the active ones
# - Output a space followed by the associated explanation
# These steps will be expanded on later.
>>> # Move to cell #4 of the first header chunk.
+ # Set it to one to start the loop.
[ # Begin a loop to print subsequent lines:
#####
# First, we will find the first not done chunk.
- # Set this cell, #4 of the first header chunk, back to 0.
>>>>>>>>>>>>> # Move to cell #5 [done] of the first source chunk.
[>>>>>>] # Go to the first not done cell to the right (it might be the current chunk).
<<<<< # Go to cell #0 [char].
[ # If it's non-zero (if it's a source chunk):
#####
# Next, we will output the leading spaces and the first active character.
<[<<.<<<<] # Go to cell #5 of the first not done chunk to the left
# (this is the second header chunk), outputting spaces along the way.
>>>>>> # Go to cell #5 [done] of the next chunk.
[>>>>>>] # Move to cell #5 of the first non-done cell to the right.
<<<<<. # Move to cell #0 [char] of this chunk (the first active source chunk) and output it.
>>>> # Move to cell #4 [noop] of this chunk.
#####
# Next, the following branch will process a sequence of no-op chunks.
# This is handled differently from non-no-op chunks because sequential no-op characters are printed in one line.
[ # If it's non-zero (if this character is a no-op):
>+ # Set cell #5 [done].
#####
# First, we will output each subsequent active character and mark their chunks as done.
>>>>> # Move to cell #4 [noop] of the next chunk.
[ # While the current chunk is a no-op:
<<<<. # Move to cell #0 [char] and output it.
>>>>>+ # Move to cell #5 [done] and set it to 1.
>>>>> # Move to cell #4 [noop] of the next chunk.
# (Note that the primary separator has cell #4 [noop] set to 0 in order to break this loop)
] # End loop. Now the head is at the cell #4 [noop] of the first non-no-op chunk.
#####
# Next, we will output the trailing spaces and the no-op explanation.
<<<<[>>>.>>>] # Move to the primary separator chunk, outputting a space for each skipped chunk.
>>>.>>> # Move to cell #0 of the first chunk of the first explanation, outputting a space.
[.>>>>>>] # Move to the next non-explanation chunk, outputting each character.
>> # Move to cell #2 [mark].
[<<<<<<] # Move to cell #2 of the second header chunk.
< # Move to cell #1.
] # End if.
<<< # If at cell #1 of the second header chunk (from the preceding branch for processing a no-op), move to cell #4 of the first header chunk;
# otherwise, (still at the cell $4 [noop] of the current source chunk), move to cell #1 [kind].
#####
# Next, the following branch will process a non-no-op chunk.
# This is handled separately from no-op chunks because operators are printed on separate lines.
[ # If cell #1 [kind] is non-zero (if in a non-no-op source chunk):
#####
# First, we will output the trailing spaces and find the primary separator chunk.
>- # Move to cell #2 [mark] and set it to 0 (this marks the cell to return to later).
>>>+ # Move to cell #5 [done] and set it to 1.
>[>>>.>>>] # Move to the primary separator chunk, outputting a space for each skipped chunk.
>>- # Mark this chunk (the primary separator chunk).
<<<<<.< # Move to cell #2 [mark] of the previous chunk, outputting a space.
[<<<<<<] # Move to the first marked (mark == 0) cell to the left (the active source chunk).
< # Move to cell #1 [kind].
#####
# Next, we'll locate the correct explanation.
# We're at cell #2 [kind], which acts as an index to the explanation.
# The primary separator (which precedes the 0th (no-op) explanation) is marked.
[- # Continually decrement the kind:
# Each iteration will unmark the currently marked separator and mark the next separator.
>>>>>>>[>>>>>>] # Move to the first marked cell to the right.
+ # Unmark this chunk.
>>>> # Move to cell #0 of the next chunk.
[>>>>>>] # Move through the explanation chunks to the next separator chunk.
>>- # Mark this separator chunk.
<<<<<<[<<<<<<]< # Return cell #1 [kind] of the active source chunk (as it's marked).
] # End loop.
#####
# Next, we will output the explanation we have located.
>+ # Unmark the current source chunk.
[>>>>>>] # Move to the marked separator chunk.
+ # Unmark this chunk.
>>>> # Move to cell #0 [char] of the next chunk.
[.>>>>>>] # While cell #0 [char] is non-zero, output it and move to the next chunk.
>>[<<<<<<] # Return to the second header chunk.
<<<< # Move to cell #4 of the first header chunk.
] # End if.
# From either branch, we are now at cell #4 of the first header chunk.
+ # Set cell #4 to 1 (to continue the loop).
<<<. # Move to cell #1 (newline) and output it.
>> # Move to cell #3 (which is 0).
] # End if.
> # If at the first header chunk (from the preceding branch for processing a source chunk), move to cell #4 (which is 1, continuing the loop);
# otherwise (still at the primary separator), move to cell #1 (which is 0, ending the loop).
] # End loop.
#####
# Lastly, we will print the final code fence.
>[<<<<<<] # Move to cell #2 of the second header chunk.
<<<<<<... # Move to the first header chunk and output the backtick thrice.
#####
# Finally, we can enjoy the fruits of our efforts: https://pastebin.com/raw/C9yYHx3F.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `oj`, 69 bytes
```
:4$꘍,`([%^])`\\`><+-,.[]`f:→+∑%ṡ';:vL¦0pṪZƛ÷$꘍nh←=Tuw∨□ḣ∇‟İ„L›„↲p4$꘍∑
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=oj&code=%3A4%24%EA%98%8D%2C%60%28%5B%25%5E%5D%29%60%5C%5C%60%3E%3C%2B-%2C.%5B%5D%60f%3A%E2%86%92%2B%E2%88%91%25%E1%B9%A1%27%3B%3AvL%C2%A60p%E1%B9%AAZ%C6%9B%C3%B7%24%EA%98%8Dnh%E2%86%90%3DTuw%E2%88%A8%E2%96%A1%E1%B8%A3%E2%88%87%E2%80%9F%C4%B0%E2%80%9EL%E2%80%BA%E2%80%9E%E2%86%B2p4%24%EA%98%8D%E2%88%91&inputs=%3E%2B%2B%2B%2B%2B%2B%5B%7B%7B%3C%2C.%3E-%7D%7D%5D%0AMove%20the%20pointer%20to%20the%20right%0AMove%20the%20pointer%20to%20the%20left%0AIncrement%20the%20memory%20cell%20at%20the%20pointer%0ADecrement%20the%20memory%20cell%20at%20the%20pointer%0AOutput%20the%20character%20signified%20by%20the%20cell%20at%20the%20pointer%0AInput%20a%20character%20and%20store%20it%20in%20the%20cell%20at%20the%20pointer%0AJump%20past%20the%20matching%20%5D%20if%20the%20cell%20at%20the%20pointer%20is%200%0AJump%20back%20to%20the%20matching%20%5B%20if%20the%20cell%20at%20the%20pointer%20is%20nonzero%0ANo%20Operation&header=&footer=)
## Explained
```
`([%^])`
```
Push the string `"([%^])"` to the stack. This will serve as the basis for a
regular expression that groups on non-BF commands
```
\\
```
Push a backslash to the stack. This will serve to escape all the characters in
the BF character set (`[` and `]` need to be escaped, because they interfere with the range set)
```
`><+-,.[]`f
```
Push the string `"><+-,.[]"` to the stack, and turn it into a list of characters.
It's important it's turned into a list of characters because the backslash will
be prepended to each character using vectorised addition.
```
:‚Üí
```
But first, put the character set into the ghost variable for later storage -
there's no BF character set element in vyxal, so to save bytes, it needs to be
stored.
```
+‚àë
```
Prepend the backslash to each character just like I said I would, and convert it
back to a single string.
```
%
```
And place that into the regex pattern string from earlier using string formatting
```
·π°';
```
Split the input program on that regex, and keep only non-empty strings. This splits
the program into single bf chars and groups of NOPs.
```
:vL¦0pṪZ
```
Get the length of each group, get the cumulative sum of that, prepend a 0 and zip
with each group. This has the effect of calculating how many spaces to prepend to
each group.
```
∆õ
```
To each item `X = [spaces, character_group]` in that, do the following
```
√∑√∞*p
```
Prepend `spaces` spaces to `character_group`
```
nh‚Üê=Tuw‚à®
```
Get the index of `character_group` in the BF character set stored in the
ghost variable. This is basically a hacky version of `ḟ` because `ḟ` doesn't
work on the version the site uses (it's fixed in the 2.6 preleases, but I'm
sticking with 2.4.1)
```
‚ñ°·∏£
```
Wrap all inputs (program and explanation strings) into a single list and push
the program separately from the explanation strings.
```
∇‟İ
```
Do some weird stack manipulation to retrieve the corresponding explanation
string using the index generated by `nh‚Üê=Tuw‚à®`.
```
„L›„↲$+
```
Left justify the character group with the prepended spaces with extra spaces
to match the length of the input program + 1. And add that to the explanation
using some extra weird stack manipulation.
```
4√∞*p‚àë
```
Indent that 4 spaces, and convert into a single string.
```
;‚Åã
```
Join the entire list on newlines. The `j` flag would usually take care of this,
but 69 is a funny number.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~53~~ ~~52~~ 50 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.γ"><+-.,[]"©såN>*}DU¹g>j|VεXN>£JvÁ}Y®XNèkè«}¹š4ú»
```
-2 bytes thanks to *@ovs*.
Outputs the lines with four leading spaces.
[Try it online.](https://tio.run/##jdC/S8NAFAfwPX/Fo5OaHzg4lkxdWjCdlErIcLm@JmeTu3B3KVTN4J8iIlQEF3Gobhdc@y9F2qh0MOj43vd9eI8nFIkZNo23een5fdv1nDDqmUdVPwT@UTU4M@vEv7w537xOAt/cjxb1bXVhnidBvZrXK/NUmfXH3Un9Zt6bJoz6/nV1cGjbrut5jmOdigWCThEKwbhGCVrsSsmSVHemGc60NeRUYo5c71o55kIugWKWAdH7yBrgPwfHpS7KtkVTIgndrlQs4WzGcArxso1@kUO@hWSPET4FpYVEYBoY75SjMi@gIOrrOKJpyngCEbBZlwGm4LiFMaHz76f82PAPywW/QimsQMC4QEk0E/wT)
**Explanation:**
```
.γ # Group the first (implicit) input-string into parts:
"><+-.,[]" # Push the string "><+-.,[]"
© # Store it in variable `®` (without popping)
s # Swap to get the current character
å # Check if it's in the string
N>* # Multiply it by the 1-based index
# (this ensures all characters in that string become unique
# values, but all unknown characters map to the same value 0)
}DU # After the group-by, store a copy in variable `X`
¬πg # Push the length of the first input-string
> # Increase it by 1
j # Make all strings of that length by padding leading spaces
| # Push a list of all remaining input-lines
V # Pop and store it in variable `Y`
ε # Map over the parts:
X # Push the parts from variable `X`
N>£ # Leave the first map-index + 1 amount of parts
J # Join them together
v } # Pop and loop its length amount of times:
Á # Rotate the string once towards the right
XNè # Get the map-index'th part from variable `X`
® k # Get the index of that part from variable `®`
Y è # Use that to index into the list of lines `Y`
¬´ # Append the two strings together
}¹š # After the map: prepend the first input-string
4√∫ # Pad each string with 4 leading spaces
» # Join the list by newlines
# (after which the result is output implicitly)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~54~~ ~~48~~ 47 bytes
```
× ⁴PSFθ«⊞υ⌕><+-.,[]ι¿⁺²Σ✂υ±²↓P⊟υι»↑⸿↓≔E⁹SηEυ§ηι
```
[Try it online!](https://tio.run/##VY9Ba8MwDIXPza8QOSnM3aHssnYMCmGQQ7pAOnboegipmhgc24vtbjD22z072aAzWDzQ06entm/GVjXC@2rk0uKeD2QwhZTBXZZtktIJy/XUKqR2trZBdxhbZzUCvmfwlSwqZ3p0DJ64PGH6@HCzvGWHY2DwaFzwM2AlnMEVg9oNWAveUvTvqGss4SoLD0p1IVzn6kPGGRKG4Gp7pTS6iTYH5UF@J7Nev2gG6duYxsDXlK0xvJNYNhrvGfw/gEEfHDMgGkKcrS3kiT6xn4JnG@/nU3bP1eE4kedSyHakgaRNcvpT9T6f/mvPBf3WMOeXF/ED "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
√ó ‚Å¥
```
Indent by 4 spaces.
```
PS
```
Print the code without moving the cursor.
```
Fθ«
```
Loop over the characters in the code.
```
⊞υ⌕><+-.,[]ι
```
Push the index of the appropriate explanation to the predefined empty list. NOPs will have an index of `-1`, which will cyclically index to the last explanation, but is also useful for coalescing consecutive NOPs below.
```
¿⁺²Σ✂υ±²
```
If there are not two consecutive NOPs, then...
```
‚Üì
```
... move down a line, else...
```
P⊟υ
```
... discard one of the NOPs.
```
ι
```
Output the current character.
```
»↑⸿
```
Move to the start of the next column.
```
‚Üì
```
Move to the first row of explanations.
```
≔E⁹Sη
```
Read in the explanations.
```
Eυ§ηι
```
Print each appropriate explanation.
Today I discovered a bug in Charcoal's `Split` command which unintentionally results in partial regex support: `Split(<string>, <list>)` is supposed to split the string at any occurrence of any word in `<list>`, but due to the bug what actually happens is that `Split(<pattern>, [<string>])` escapes the string and splits it on the pattern. Unfortunately the original approach has since been golfed down from its original 54 bytes which this approach ties with, but that's still good going considering the duplication of the command characters:
```
× ⁴≔Φ⪪“ xMT¦T~≧_x”⟦S⟧ιθP⪫θωFθ⁺¶ι↑⸿↓≔E⁹SηEθ§η⌕><+-.,[]ι
```
[Try it online!](https://tio.run/##VY5Na8MwDEDv/RXGJ5k6O/WyrhQKoZBBu0A6dkhyCKnXGFzbcZx2h/13T4n3wQwSQpbeU9s1rjWNCiF3Uns4yasYgBLKyYqxp8VuGORFw14qLxwUVkkPtML3CWW92S4TXtYMh8tM29EXHiEXYDXjRGL0SDiMyks7w5@N1NBzcp/I78YR6BmJ3lyNqK00nRbxN3bXr5YTWjk6ccxNwDo1d/131qGx8MjJPzdqu1/ANIDCnc/0WXxAx8le6jPQ7WaZPODpUYfCEGLr@JKX9eyKKdOtE1eh/SIVP1VxSud466QS3xn3QnJTXw "Charcoal – Try It Online") Link is to verbose version of code. Note: Backslashes are not supported because this is relying on buggy Charcoal behaviour. Explanation:
```
√ó ‚Å¥
```
Indent by 4 spaces.
```
≔Φ⪪“ xMT¦T~≧_x”⟦S⟧ιθ
```
Extract command characters or runs of non-command non-backslash characters from the input.
```
P⪫θω
```
Print the code without moving the cursor.
```
Fθ⁺¶ι
```
Output each command on its own line, but increasing the indent as it goes.
```
↑⸿
```
Move to the start of the next column.
```
‚Üì
```
Move to the first row of explanations.
```
≔E⁹Sη
```
Read in the explanations.
```
Eθ§η⌕><+-.,[]ι
```
Find and output the appropriate explanation for each command, or the last explanation for non-commands.
[Answer]
# JavaScript (ES2022), 141 bytes
```
s=>a=>" "+s+s.replace(/(?:[^+-.<>[\]]+|.)(?=(.*))/g,(c,e)=>`
`+(c+e.replace(/.|$/g,' ')).padStart(s.length+5)+a.at('><+-.,[]'.indexOf(c)))
```
[Try it online!](https://tio.run/##jVPfb9MwEH4mf8XRIdVeWqca4oH1x4TgZROjk9hbVzTXuSTeEjuyL4Wy7m8vTrrBJjFBHiL5@@67@3x3vpFr6ZXTNQ2NTXGXHL6O4BAuSrvJdFmCzeCDc3JzIAkyZ6uWLIhqf5wkuaaiWQllq4TU2/dJ7WxtvSyHDktJeo1DbVL8oU0@rJAKmx7UtuzStlk@2nrjdF4QMMXhaHQ0gku5gg90q42HMyfaoPPTS/isFRqP4ZhE89UNKhIpZtrgRaiHjjascyhCebK0qXEAfUn9AdxFAGtZNngMWWMUaWtAEjM8MK8ADEzhXFIhyAW2hbdbGI1bSmfADExgxENUPAUqtBclmpyK53wrMTB7FsHBITXOQGP2PtNO8wC2gQuzHAdv94Pw@@40yVUZPAYb2CJomgrdHstk6TtQWZPpvHFPQ@/5OIqy6c5PZ3I660H4erGPvXBYl1IhS9jJ8eJbPBST2eJquYy3grOTKROHnCf5gKkB8unsOrqOmYrxj0ps3wS6D33ORS3TryQdscfbxe94LEVoY382CZkHi2VfdGOeZ2GOnO@CU29LFKXNWcZ6i@VkdnfPeBwPh0IMBj3OrqNzu8bQCYTaakPogGx37PbhRbbEjKJToxxWaKiDKqys24DCsKqSnoqiT/ifgfOG6mYPqUI6qdqSXudGZxpTWG321F@Up6YVyicyaVLwZB2CJtDmReVZU9VQS/9gTpIqwjOBZbtZL2hAexjthSupbh@b8lu7@IfWWPMTnY2@WJiHZyPb5xBdh@XXFePC16UOM70yYeh8vPsF "JavaScript (Node.js) – Try It Online")
```
f: (source_code: string) => (explain_array: string[]) => string
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~65~~ 60 bytes
```
OsX4FbPp:#_FIa^C X^Y"><+-.,[]"P[sX4pRXXsRA Uvbs(gU(y@?b)|9)]
```
The BF program and the nine explanation strings are taken as command-line arguments. Alternately, you can use the `-r` flag to take them from stdin. [Replit!](https://replit.com/@dloscutoff/pip) Or, here's a 61-byte equivalent in Pip Classic: [Try it online!](https://tio.run/##K8gs@P/fvzjCxC0poMBKOd7NMzHOWSEiLlLJzkZbV08nOlYpIBooXRAUEVEc5KitXZZUrJGura1R6WCfpFljqRn7/78BRKmff0B0rAFXUGZ6RgmXT2paCZdnXnJRam5qXgmXSyqM5V9aUlAKkgKR4RmZOalcQakFqYklXH75uvkF/3WLAA "Pip – Try It Online")
### Former explanation
New explanation pending... This is the explanation for the previous 65-byte solution.
```
Oi:sX4Pp:#_FIa^C X^Y"><+-.,[]"WpP[iPBsX#xx:POpsX#Jps(gU(y@?x)|v)]
```
First, the setup:
```
Oi:sX4Pp:#_FIa^C X^Y"><+-.,[]"
sX4 Space character, repeated 4 times
i: Assign to i (the indent)
O Output it without trailing newline
Y"><+-.,[]" Yank that string into y (BF commands)
^ Split into a list of chars
X Convert to a regex that matches any one of those chars
C Wrap the regex in a capture group
a^ Split the first program arg on that regex
(As in Python, splitting on a regex wrapped in a group
keeps the matches of the regex in the result list)
FI Filter that list on this function:
#_ Length of item
(This gets rid of empty strings while not getting rid
of "0", which is falsey in Pip)
p: Assign the result to p (the processed program)
P Print it with trailing newline
```
Then, the main loop:
```
WpP[iPBsX#xx:POpsX#Jps(gU(y@?x)|v)]
Wp While p is not empty:
P Print (with trailing newline)
[ ] this list, concatenated:
1. Indent:
x Last chunk (initially empty string)
# Length of the above
sX That many spaces
PB Push those onto the end of
i i (modifies i in-place)
2. Current chunk:
POp Pop the first item from p
x: Assign it to x
3. Padding:
p Remaining chunks
J Joined into a single string
# Length of the above
sX That many spaces
s 4. One more space before explanation
5. Explanation:
y@?x Index of current chunk in BF commands
(0 to 7, or nil if not found)
U( ) Increment (1 to 8, or nil)
| Logical OR
v Negative one (1 to 8, or -1)
(g ) Item in program args at that index
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 45 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
å☺m█Q╗½§ÄN!╢┼♫mù}Jt→v)╢+Θ☼î╔↓bÉü╡⌐CÇ-♠•¿♪FM¥2
```
[Run and debug it](https://staxlang.xyz/#p=86016ddb51bbab158e4e21b6c50e6d977d4a741a7629b62be90f8cc919629081b5a943802d0607a80d464d9d32&i=LBc4NtPY%7B%22%3E%3C%2B-.,%5B%5D%22XI%5Ei*%7D%2FzsFs%25Ntcaay%25%5E%28x_Iasn%40as%2B4NtPs%0AMove+the+pointer+to+the+right%0AMove+the+pointer+to+the+left%0AIncrement+the+memory+cell+at+the+pointer%0ADecrement+the+memory+cell+at+the+pointer%0AOutput+the+character+signified+by+the+cell+at+the+pointer%0AInput+a+character+and+store+it+in+the+cell+at+the+pointer%0AJump+past+the+matching+%5D+if+the+cell+at+the+pointer+is+0%0AJump+back+to+the+matching+%5B+if+the+cell+at+the+pointer+is+nonzero%0ANo+Operation)
Made this after Fmbalbuena's challenge in TNB. Will try to post something in Pip as well.
Found a nice save after Neil pointed out a mistake.
## Explanation
```
LBc4NtPY{"><+-.,[]"XI^i*}/zsFs%Ntcaay%^(x_Iasn@as+4NtPs
LBc4NtPY{" No Operation
> Move the pointer to the right
< Move the pointer to the left
+ Increment the memory cell at the pointer
- Decrement the memory cell at the pointer
. Output the character signified by the cell at the pointer
, Input a character and store it in the cell at the pointer
[ Jump past the matching ] if the cell at the pointer is 0
] Jump back to the matching [ if the cell at the pointer is nonzero
"XI^i*}/zsFs%Ntcaay%^(x_Iasn@as No Operation
+ Increment the memory cell at the pointer
4NtPs No Operation
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 46 bytes
```
®Ṭ€z0aḷżṚ⁸ṭṚŻ€4¡o⁶ð“><+-.,[]”iⱮxṠoŒQÄ©ŒQƲ$$ịŻ€
```
[Try it online!](https://tio.run/##jdAxTwIxFAfw/T7FGxg0wIXBkTC5YKLE0RCGUh5clWsvvZ4RjAkYNzdHo4m6GBMgaoxyOSfI@T3aL3IeoIZBolNf37@/tH372G53kmQy0uHAnA66BaLHb/G7Di9Nf6zDYVrEURpsTG6F6b9OH03vqlTM5u1ctWZ618w8jY50eCPii93p2eQhXT6eMxkdnc9VoqMXPb6b3mf2kqRaK5aOT9bWs9l83rZzOWtbHCIoB8ETjCuUoMR8K1nLUSvTNjaVVeZUootczVsuukJ2gKZ/AaKWkbWJ/zxYCZQXLFrUIZLQ2ZU@a3HWZNiAemcR/SLLfAbJEiO8Ab4SEoEpYHyl3ApcDzzifz2OKOow3oIasOYqA8yHwgLWCT34HsqPrf5hueBdlMLaEVDxUBLFBP8E "Jelly – Try It Online")
Program on the left and list of descriptions on the right. I suspect this can lose a few bytes fairly easily, but I'm posting it now in order to preserve one of the most hideous things I have ever written for posterity.
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `·π†`, ~~80~~ 79 bytes
```
Dð4×§,0$"<>+-.,[]"£([¥nc[⁰Lm-ꜝð×§¹,|n§1#x)4m+ð×§¥nḞꜝ:[#?Ḣin§⁰Lm-ð×§,0|n§1][ð§¹,
```
[Try it Online!](https://vyxal.github.io/latest.html#WyLhuaAiLCIiLCJEw7A0w5fCpywwJFwiPD4rLS4sW11cIsKjKFvCpW5jW+KBsExtLeqcncOww5fCp8K5LHxuwqcxI3gpNG0rw7DDl8KnwqVu4bie6pydOlsjP+G4omluwqfigbBMbS3DsMOXwqcsMHxuwqcxXVvDsMKnwrksIiwiIiwiKystLTw8Pj4uLiwsW1tdXWFhYmJjY34rKy0tPDwrKy0tPDw+Pi4uLCxbW11dYWFiYmNjfisrLS08PFxufmFhYWNcbjw8PDw8XG4+Pj4+PlxuKysrKytcbi0tLS0tXG4uLi4uLlxuLCwsLCxcbltbW1tbXG5dXV1dXSIsIjMuMy4wIl0=)
### Explanation:
Setup:
```
Dð4×§,0$"<>+-.,[]"£(­⁡​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁣​‎⁠⁠⁠⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁤​‎⁠⁠⁠⁠‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‏​⁡⁠⁡‌⁢⁢​‎⁠⁠⁠⁠⁠‏​⁡⁠⁡‌­
ð4×§ ## ‎⁡Print " " without newline
D , ## ‎⁢Print the first line of input with newline
"<>+-.,[]"£ ## ‎⁣Put "<>+-.,[]" in the register
0$ ## ‎⁢⁡Push the 0 in the stack (Swapped because the top of the stack is used for looping)
( ## ‎⁤Loop every char in the first line of input
```
Looping part:
```
[¥nc[⁰Lm-ꜝð×§¹,|n§1#x)4m+ð×§¥nḞꜝ:[#?Ḣin§⁰Lm-ð×§,0|n§1]­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁡⁡‏⁠‎⁡⁠⁣⁡⁢‏⁠⁠‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁡⁣‏⁠‎⁡⁠⁣⁡⁤‏⁠‎⁡⁠⁣⁢⁡‏⁠‎⁡⁠⁣⁢⁢‏⁠‎⁡⁠⁣⁢⁣‏⁠‎⁡⁠⁣⁢⁤‏⁠‎⁡⁠⁣⁣⁡‏⁠‎⁡⁠⁣⁣⁢‏⁠‎⁡⁠⁣⁣⁣‏⁠‎⁡⁠⁣⁣⁤‏⁠‎⁡⁠⁣⁤⁡‏⁠‎⁡⁠⁣⁤⁢‏⁠‎⁡⁠⁣⁤⁣‏⁠‎⁡⁠⁣⁤⁤‏⁠‎⁡⁠⁤⁡⁡‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁤⁡⁢‏⁠‎⁡⁠⁤⁡⁣‏⁠‎⁡⁠⁤⁡⁤‏⁠‎⁡⁠⁤⁢⁡‏⁠‎⁡⁠⁤⁢⁢‏‏​⁡⁠⁡‌­
[¥nc[ ## ‎⁡if the current character is in "<>+-.,[]"
⁰Lm-ꜝð×§¹, ## ‎⁢print that many spaces, then the second line of input, with newline.
|n§1#x) ## ‎⁣else print the current character and continue with the 1 in the top of the stack.
4m+ð×§ ## ‎⁤Print that many spaces
¥nḞꜝ ## ‎⁢⁡index of the current character (1 to 8, 0 if not found)
:[ ## ‎⁢⁢if the index of the current character is 1 or more
#?Ḣin§⁰Lm-ð×§,0 ## ‎⁢⁣Print that many spaces, then the right explanation, with newline, and push 0
|n§1] ## ‎⁢⁤else, print the current character, and push 1
```
Final part:
```
[ð§¹,­⁡​‎‎⁡⁠⁡‏⁠⁠⁠⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌­
[ ## ‎⁡If the top of stack is 1 or greater
## ‎⁢(I have no idea why that works)
ð§ ## ‎⁣print " " without newline
¹, ## ‎⁤Print the second line of input, with newline
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~191~~ 188 bytes
*-3 thanks to @[ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
*S="><+-.,[]";i;l;d;f(char*a,**e){for(i=5,l=printf(" %s \n",a);*a;printf("%*s%s\n",l-i,"",e[d?d-(int)S:8]))for(d=index(S,*a),printf("%*c",i++,*a);!d&!index(S,*++a);)i+=write(1,a,*a>0);}
```
[Try it online!](https://tio.run/##lZJBb9QwEIXv/RVTS4vixFl1D0gIN8uFS5Gghz2GHFx7kh2R2JHjpS2r/euEeLctqSoo@OZ57316tkbnulW2Gcd0U7D1ZZYvRVkxSbKVRtaJ3iqfKpGmyPe18wkVb0Vb9J5sqBMG01kM8NUyobhMlXwUFumwGOK4zUkwJrA0H0yeTCLfvH9XcR5ZpiBr8C7ZiFRx8TuqmaAsi0N5bt6cP5mybJpwyopbTwGTlZh6qfUFl4exU2QTvj@LhY6VQTuDKyiAldXlen9IeJbl@XIpBJMzF971q7KabKdoPOyz@44Qtgi9mxqhh@COV0/NNjDxurHF@pnvymqPHdpwVDvsnL8HjW0LKszz88xH/P/M9S70u5MaX6d07DRQY6kmNHBzf5L@DrmykaFmBGUNDMF5BApA9l8gn3ZdD70aHtqroLdkG6iA6j/FgQa4eMG4Ufrb47c@YcpXMNbZH@jdHPbFwXWPXgVy9mF@OO3BtOJxU8RxFbg8O4w/dd2qZhjz218 "C (clang) – Try It Online")
Assumes explanations are in the order `> < + - . , [ ] NOP`.
[Answer]
# [Perl 5](https://www.perl.org/) + `-nF -M5.10.0`, 93 bytes
Thanks to [@Fmbalbuena](https://codegolf.stackexchange.com/users/106959/fmbalbuena) for noticing I'd missed printing the unaltered string! Thanks to [@emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a) and [@Neil](https://codegolf.stackexchange.com/users/17602/neil)'s regex wizardry saving 14 (!!) bytes!
```
@@=<>;say$"x4,$_,map$"x(4+$-).$_.$"x(@F-($-+=y///c)).$@[index'><+-.,[]',$_],/[^]<>+-.[
]+|./g
```
[Try it online!](https://tio.run/##K0gtyjH9/9/BwdbGzro4sVJFqcJERyVeJzexAMjUMNFW0dXUU4nXA3Ec3HQ1VHS1bSv19fWTNYHCDtGZeSmpFep2Ntq6ejrRsepAnbE6@tFxsTZ2QJForljtGj399P//IQr8/AOiY7l888tSIYRnXnJRam5qXgmXSyqMFRziAsbhGZk5qVASqI/rX35BSWZ@XvF/3Ty3/7q@pnqGBnoGCgA "Perl 5 – Try It Online")
## Explanation
First `print` `4` `x` (string repetition operator) `$"` (which defaults to space), then store the length of the input (implicitly obtained via `-F` into `@F`) in `$=`, and store the explanations in `@@`. Then, `for` each matching piece of code (either one char from `-<>+.,[]`, or any number of any other chars) concatenate the following with `$\`: 4 + `$-` (which starts out as `0`) `x` `$"`, followed by the piece of code (`$_`), followed by the original length, minus `$-` (to which we add the current length of this code piece) `x` `$"` and finally, using the `index` function on the string `><+-.,[]`, the message associated to the current piece of code (`index` returns `-1` for missing index, for which Perl returns the last element of the list). `$_` is output followed by `$\` thanks to `-p` flag.
---
# [Perl 5](https://www.perl.org/) + `-F/([^]<>+-.[]+|.)/ -M5.10.0`, 92 bytes
The regex used in the above, can be provided via `-F` to save a byte.
```
$==y///c;@@=<>;say$"x4,$_,map/./&&$"x(4+$-).$_.$"x($=-($-+=y///c)).$@[index'><+-.,[]',$_],@F
```
[Try it online!](https://tio.run/##NYxLC4JAAITv/oxYfLAvAz35YA8idLCCgg7LJmILCb5QCYV@e9uWdZhhZuCbXg61rxSIooVSWgaMRWEcjMUCNrOHQI6aoqeEmqbutgcBdgjIyaeACNsAw5Vz9Mx41d7kbMUhxARxYWlcIJYqtS77w5ELI@secrVdWw6yke1kJPKfTufkq8u9quXPNWe8un6qunZUOKU2v4ow1o9cwCdxqMKZT7Yucd8 "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 118 bytes
```
c,*a=*$<
print" "*l=4,c
c.scan(/[^+-.\[\]<>\n]+|./){puts" "*l+$&+" "*(c.size+4-l+=$&.size)+a["><+-.,[]".index($&)||8]}
```
[Try it online!](https://tio.run/##jdDNboJAEADgO08xIYSAC9iDhx7UUy82aX0ApMm6jrIpzJJlaIo/z04RW@Ohpr3t/Hw7s2ubddt1KhrJ2cibOpXVxC64o2I2iZSjklpJCsbpm4iTVbrKpvMVZeKYjMND1XA9dArPF@dD0HfrPYpJXIiZ5w9BKGTqzqe9jtLMTTRt8DPw/PB4fMxOXZf2Fx5OQShEHCdJFDkv5gOBc4TK9IugBTZDaPUu57vVArfsLEhZLJF4SJVYGtuCwqIAybfIecJ/Ni4b7h85pFQurVTnkbXekd5q3MC6vZR@kQs6Q3nDJG2gZmMRNIOmu/K5KSuoZP29nGSVa9pBBnp7z4Cu4eEC11K9/3zK1aZ/WDK0R2ucVwPLCq1kbegL "Ruby – Try It Online")
#### Explanation
```
c,*a=*$< # assign 'c' to first line and 'a' to the rest of input
print" "*l=4,c # output code and assign 'l' to 4 at the same time
c.scan(/[^+-.\[\]<>\n]+|./) # for every match:
{puts" "*l+$&+" "*(c.size+4-l+=$&.size)+ # output the padded match, update 'l' to keep track of the spaces
a["><+-.,[]".index($&)||8]} # output the correct explanation
```
inspiration taken from [lonelyelk](https://codegolf.stackexchange.com/users/108388/lonelyelk)
[Answer]
# [Haskell](https://www.haskell.org/), 330 bytes
```
import Data.List
main=interact$unlines.f.lines
f(c:a)=(s 4++c):(map(p c.(a%)).tail.inits.t)c
t r|r==[]=[]|q x=[x]:t y|0<1=a:t b where(x:y)=r;(a,b)=span(not.q)r
q=(`elem`n)
p c(a,e)=s(4+(l.init)a)++last a++s(1+length c-l a)++e
s=(`replicate`' ')
n="><+-.,[]"
e%j=(j,e!!(n#last j))
l=length.concat
(s:z)#c|[s]==c=0|z==[]=1|0<1=1+z#c
```
[Try it online!](https://tio.run/##jZJRbxoxDMff8yncsqqJDiKQ@sRIn/rSaVs/wOkkQmq40DvnSMwGjH12Fg5t6sPQJkVKYvvnf2yntukNm@Z08m0XIsOTZas/@8SitZ6MJ8ZoHX/YUuMJk17qfhdL6aZWGZngoSicmsrWdrIDp6W9U0qz9Y325DlpVk4wxGM0pqzyOm5gZ8pdNWXYH8ezibH5tIDvNUaUu@lemfhR2uFCmdRZkhRYb1QUGyPn2GA7JyWyTo7AHCEfCnkRUlYVRWMTgy2KJCdFg7TiGtyogbMLRcoZInaNd5Zxfg/3SpC5fZwVIz0sq1uBd2sj10O8uZE06DOtlRKNuSTSLlAGhUzTgxq4Y5kqY5wZHw99XZO@lElxGLjTqaxmjz9@yqw6Gmk9HIov4RsC1whd6DsKHPpr9Kuar3obXLJ4JhexReLe1GIb4h5cHhlYfg@JJ/zPwJctd9uLydX2PN0smfyK/NLjKyz2F9dfyGc6g/YdZukVEoeI4Bk8XSU/bdsOunNP@8dZdrWnFVTgl9cY8AnGF3Bh3dvvpvxhy3@wFOiAMYivAV66/InZB/oF "Haskell – Try It Online")
#### Explanation:
```
import Data.List
main=interact$unlines.f.lines
f(c:a)=(s 4++c):(map(p c.(a%)).tail.inits.t)c
```
import Data.List `inits`(prefixes), this is used to keep track of the number of spaces
call `f` with lines of input, then output each line
f = `" " * 4 + code` +
`map` on each `prefix` of each command or noop:
select explanation and then pad with spaces
```
t r|r==[]=[]|q x=[x]:t y|0<1=a:t b where(x:y)=r;(a,b)=span(not.q)r
q=(`elem`n)
n="><+-.,[]"
```
`t` splits the code into commands or noop
`q` checks if a char is a command
`n` is the string `"><+-.,[]"`
```
p c(a,e)=s(4+(l.init)a)++last a++s(1+length c-l a)++e
s=(`replicate`' ')
e%j=(j,e!!(n#last j))
(s:z)#c|[s]==c=0|z==[]=1|0<1=1+z#c
```
`p` pads a (prefix, explanation)-pair with spaces
`s` returns n spaces
`%` creates said (prefix, explanation)-pair
`#` returns the index of the command in `n` or 8 if it's a noop
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~207~~ 205 bytes
```
*\K````
*\0G`
\G.
$& $&¶
m,-10T`_><+\-.,[]p`d`.$
(?<=^(.+¶)*.) 9¶(?=. 9)
+`^(.+¶)*(.)+ .¶(?!¶|(?<-2> )*(?(2)$))
$&
,-10P`.+
+`(\d)( *)(¶(.+¶)*¶)
$2$1*_$3
+`(_)+(¶(.+¶)*(?<-1>.*¶)+(.*))
$4$2
(¶.*){9}$
```
```
[Try it online!](https://tio.run/##RU/NagIxEL7PU6QQZCZxB3ftZUF3L4KU0lao4MHYjWhAQbdFpJe2r7UPsC@2nVSlgW@Y5PuZySmc9/U67TrjHr0cMG4w9eCmDLqndK9t4NhP0sHcV8XIuoT7y9WH33rWgOVo/IZs24YMk8rbBssxq5wArL8RyGQVR@qubb7FkmSFkucSM9JEcQjE/JlnKzZ0W0JlCMVxCRCAznRqKj2MgorsPxnz0oKjyCKbmHevMxCBXL7yHw3ypa6TzWXx55fZcgVP75/hUh7qzSkcQ32GSbh1r/PJHxa7/SFcq/h@AQ "Retina – Try It Online") Explanation:
```
*\K````
```
Output the leading fence.
```
*\0G`
```
Output the line of code.
```
\G.
$& $&¶
```
Split the line of code into characters. For each character, repeat it twice, joined with a space.
```
m,-10T`_><+\-.,[]p`d`.$
```
Transliterate the last character of each pair to a digit `1-8`, with unknown characters becoming `9`.
```
(?<=^(.+¶)*.) 9¶(?=. 9)
```
Join together all runs of unknown characters.
```
+`^(.+¶)*(.)+ .¶(?!¶|(?<-2> )*(?(2)$))
$&
```
(note trailing space) Align each run after the end of the previous run.
```
,-10P`.+
```
Pad all of the explanation lines to the same width.
```
+`(\d)( *)(¶(.+¶)*¶)
$2$1*_$3
```
Convert all of the transliterated digits to runs of underscores and move them to the end of the line.
```
+`(_)+(¶(.+¶)*(?<-1>.*¶)+(.*))
$4$2
```
Replace each run of underscores with the appropriate line of explanation.
```
(¶.*){9}$
```
```
Replace all of the explanations with the trailing fence.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~143~~ ~~142~~ 138 bytes
```
->i{c,*e=i.split ?\n;puts" "*(m=4)+c;c.scan(/[^<>+-.,\[\]]+|./){|b|r=" ".*c.size+5;r[m,z=b.size]=b;puts r+e["<>+-.,[]".index(b)||8];m+=z}}
```
[Try it online!](https://tio.run/##7ZOxTsMwEIb3PMWpU1snLlQgITUJC0uRaBlgco3kuNfWIrEjx0W0SZ69hARQByoYGfDku/u/89m/bLfJ7pBGhyBWpfSHGCla5KlycL3Qk3zrih70hv0suhgQOZG0kEL3R@wpjElA/QVbcE4qOhqUVVLZqNHSYSNSeySXE8syfx8lbcijpO0GliDrdTTjPar0El/7yaCqrvgkI9G@rg9KN8pziCAMp7P7xweP8TAu6/6AkCCg1Pe9O/OC4DYIuVHaoQVn2tCq9cadrKa4ct5US4sZatemMsyM3YHENAXhjiHvBn8pnG9dM2@bkhthhXw/slBrrVYKl5DsutI35PT9oiCOMKGXUDhjERoHlD5J3m6zHHJRfAwnnNwovQYOanWKAVXAWQcmQj5/PsoXy35gtdF7tMabGZjnaIVTRnudP61h4yPDYtIuVpahT@Ogrvm/ZX/LMi9l3Tfjn7sxP7wB "Ruby – Try It Online")
The function expects input to be lines separated by `\n`. It scans the program using regexp `/[^<>+\.,\[\]-]+|./`. It outputs to stdout instead of returning. Which is all there is to it.
Thanks to @Fmbalbuena for removing a space!
Saved 4 more bytes by re-reading ruby golfing tips :)
[Answer]
# [Haskell](https://www.haskell.org/), 235 231 bytes
```
import Data.List
main=interact$unlines.map(" "++).f"><+-.,[]".lines
f o(i:e)|let t=not.(`elem`o);p=(>>" ").concat;w((c:r):t)=(c:r++p t++' ':maybe(e!!8)id(lookup c$zip o e)):[p[c:r]++l|l<-w t];w[]=[]=i:w(groupBy(\x y->t x&&t y)i)
```
[Try it online!](https://tio.run/##jZLPbtswDMbvfgrWKFoJio0dByf2Yeilw7Y@gGegikLHRPQPNr3UXffsmZNsQw8LWoIHip9@oPhBnR52aO3hQC6GnuFOs86/0MCJ0@RL8oy9Nnw9ekseh9zpKFKYI1VK5m1arVSWL@omzU960kIQVKB8scjApQ@ci0e06B6DXMZSVFUKqcxN8Ebzci@EKXpZsCyPhVIRWKlbuC2cntYo8Orqo6SNsCHsxgjm@pkiBEApizrWM9EoZV/sKtsDN8t93ZRzUrEX2z6M8dMkvj/BlFUMTzc3DJMkeTjUzar6@UtIpbIszxeL5Gv4gcAdQgyndYHD6djTtuOLqsWWk3tvenTo@dRy6EI/gZn9BM2voeQO33nxYeQ4nlum00fr55EDbT21hBtYT2fpP@S9P4L6Fab9BgYOPQIxkL9Ifh5dhKiHP4/TbDryW2iA2ksM0AAfzuBam91fU/6x9RusD/4Z@5B8C/AQ5x/GFPxv "Haskell – Try It Online")
Old answer:
**[Haskell](https://www.haskell.org/), 235 bytes**
```
import Data.List
main=interact$unlines.map(" "++).f.lines
o="><+-.,[]"
t=not.(`elem`o)
p=(>>" ").concat
f(i:e)|let w((c:r):t)=(c:r++p t++' ':maybe(last e)id(lookup c$zip o e)):[p[c:r]++l|l<-w t];w[]=[]=i:(w$groupBy(\x y->t x&&t y)i)
```
[Try it online!](https://tio.run/##jZLBbtswDIbvegrCCFoJio2dvdiHopcW2/oAnoEqCh0TkSXBppe66549cxx06GHBRuhA/tQHUj/UmuGAzp1O1MXQM9wbNtkXGlh0hnxBnrE3llejd@RxyDoTZQJzJFqrrMkWVYQiKTc6zdZVnQgufOBMPqPD7jkoEQtZlgkkKrPBW8OikZSjenPIcJTS5r3KWRXnROsIrPUt3OadmbYonRkYUNFOuhAOYwS7eqUIYdZUXsVqZmqt3ZvbpEfg@vOxqov5UC6Pq30fxng3ye8vMKUlw8vNDcOkSJ1OVb0pf/6SSus0zbL1WnwNPxC4RYhheTJwWMqe9i1f7TpsWDx422OHnhepwy70E9jZUzD8ERL3@J8Xn0aO40WyrTnbP48caO@pIdzBdrq0/kI@@DNoPmDG72Dg0CMQA/mr5OPYRYhnt5flDNuW/B5qoOYaAzTApwu4NfbwbsoftvoH64N/xT6IbwGe4vzLmIL/DQ "Haskell – Try It Online")
*The answer is not final, will probably be golfed further.*
] |
[Question]
[
Here are the first 100 numbers of a sequence:
```
1,2,33,4,55,66,777,8,99,11,111,12,133,141,1515,1,11,18,191,22,222,222,2232,24,252,266,2772,282,2922,3030,31313,3,33,33,335,36,377,383,3939,44,441,444,4443,444,4455,4464,44747,48,499,505,5151,522,5333,5445,55555,565,5757,5855,59559,6060,61611,62626,636363,6,66,66,676,66,666,770,7717,72,737,744,7557,767,7777,7878,79797,88,888,882,8838,888,8888,8886,88878,888,8898,9900,99119,9929,99399,99494,995959,96,979,988,9999,100
```
**How does this sequence work?**
```
n: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
binary: 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000 10001
n extended: 1 22 33 444 555 666 777 8888 9999 1010 1111 1212 1313 1414 1515 16161 17171
1-bit digits: 1 2 33 4 5 5 66 777 8 9 9 1 1 1 11 12 13 3 141 1515 1 1 1
result: 1 2 33 4 55 66 777 8 99 11 111 12 133 141 1515 1 11
```
As you can see, the steps to get the output are as follows:
1. Convert integer \$n\$ to a binary-string.
2. Extend integer \$n\$ to the same length as this binary-string. (I.e. \$n=17\$ is `10001` in binary, which has a length of 5. So we extend the `17` to this same length of 5 by cycling it: `17171`.)
3. Only keep the digits in the extended integer \$n\$ at the positions of the `1`s in the binary-string.
4. Join them together to form an integer*†*.
## Challenge:
One of these options:
1. Given an integer \$n\$, output the \$n^{\text{th}}\$ number in the sequence.
2. Given an integer \$n\$, output the first \$n\$ numbers of this sequence.
3. Output the sequence indefinitely without taking an input ([or by taking an empty unused input](https://codegolf.meta.stackexchange.com/questions/12681/are-we-allowed-to-use-empty-input-we-wont-use-when-no-input-is-asked-regarding)).
## Challenge rules:
* *†*Step 4 isn't mandatory to some extent. You're also allowed to output a list of digits, but you aren't allowed to keep the falsey-delimiter. I.e. \$n=13\$ resulting in `[1,3,3]` or `"1,3,3"` instead of `133` is fine, but `"13 3"`, `[1,3,false,3]`, `[1,3,-1,3]`, etc. is not allowed.
* Although I don't think it makes much sense, with option 1 you are allowed to take a 0-based index \$m\$ as input and output the \$(m+1)^{\text{th}}\$ value.
* If you output (a part of) the sequence (options 2 or 3), you can use a list/array/stream; print to STDOUT with any non-digit delimiter (space, comma, newline, etc.); etc. Your call. If you're unsure about a certain output-format, feel free to ask in the comments.
* Please state which of the three options you've used in your answer.
* The input (with options 1 and 2) is guaranteed to be positive.
* You'll have to support at least the first \$[1, 10000]\$ numbers. \$n=\text{...},9998,9999,10000]\$ result in \$\text{...},9899989,99999999,10010]\$ (the largest output in terms of length within this range is \$n=8191 → 8191819181918\$).
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
*PS: For the [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) code-golfers among us, 4 bytes is possible.*
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 72 bytes
```
Pick[Flatten[(i=IntegerDigits)/@Table[#,s=Length[p=#~i~2]]][[;;s]],p,1]&
```
[Try it online!](https://tio.run/##BcHBCoMwDADQXxkIY0Khm1cp9DAGwg4yvIUcMgkxTIPYnP317r2NfOGNXGeqkuqo8w9eK7mzwU3TYM7Cx1NFvbQxT/RdGZpQ0ptNfIE9NaeeHSIC9H1BDHt44LWOh5pfYpaYP2TC0N2x1j8 "Wolfram Language (Mathematica) – Try It Online")
Here is the plot of the first 30.000 such numbers
[](https://i.stack.imgur.com/uf3rU.png)
And here is the Logarithmic plot
[](https://i.stack.imgur.com/aClD8.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
BTịD
```
[Try it online](https://tio.run/##y0rNyan8/98p5OHubpf///@bmgEA), code that computes the \$n\$th term of the sequence, or [check the first 100 terms!](https://tio.run/##y0rNyan8/98p5OHubpf/QYfbHzWtebij5/9/QwMDAA "Jelly – Try It Online")
How it works:
```
B convert number to binary, i.e. 5 -> [1, 0, 1]
T keep the indices of the Truthy elements, i.e. [1, 0, 1] -> [1, 3]
ị and then index safely into...
D the decimal digits of the input number
```
By "index safely" I mean that indices out of range are automatically converted into the correct range!
[Answer]
# [Python 3](https://docs.python.org/3/), ~~80~~ \$\cdots\$ ~~52~~ 53 bytes
Saved ~~a~~ 2 bytes thanks to [Jitse](https://codegolf.stackexchange.com/users/87681/jitse)!!!
Saved ~~7~~ 6 bytes thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!!
Added a byte to fix bugs kindly point out by [Jitse](https://codegolf.stackexchange.com/users/87681/jitse) and [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum).
```
lambda n:[c for c,d in zip(str(n)*n,f'{n:b}')if'0'<d]
```
[Try it online!](https://tio.run/##PYy9boMwGEX3PMVVFtvJ16ofP@FHpWOfoBthIIBbV6lBBoYW8ew0VpUOZzn36gzf00dvw00X5@1af13aGjYvG@jeoaEWxuLHDHKcnLTqYEmLxeaXVSijxZN4bqvNFcubm7t8Fuc5SDgUhNf6Ot5F1Ih152uGunutPLjavneSiVNVHcuUM66oZEJACENCRIhjwulESJKEkBKyjMDsYRAHN/yRI69ivp35b/etfyqV7zAWWhq1w@CMnaTeLyZf8fCCZVyxuNJLIR4/e2PlqFRRdNW6V9sv "Python 3 – Try It Online")
Returns the \$n^{\text{th}}\$ number in the sequence as a list of digits.
[Answer]
# [J](http://jsoftware.com/), ~~13~~ 10 bytes
```
#:##@#:$":
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/la2UlR2UrVSUrP5rcilwpSZn5CsYGgCRio6Ng0asdZqmkoGGoXamnqGBgeZ/AA "J – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
×IbÏ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8HTPpMP9//8bGhkDAA "05AB1E – Try It Online")
Yeah, I found the mysterious 4-byte 05AB1E answer :D
```
× expand the input digits (input 123 -> 123123123123123... )
Ib get the binary value of input (123 -> 1111011)
Ï keep only the digits where the corresponding binary digit is 1
```
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 7 bytes
```
⊤⌿≢∘⊤⍴⍕
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/R11LHvXsf9S56FHHDBC7d8uj3qn/Nbke9U0FyqcdWqHwqHezkcF/AA "APL (dzaima/APL) – Try It Online")
### How it works
```
⊤⌿≢∘⊤⍴⍕ ⍝ Input: n
≢∘⊤ ⍝ Length of base-2 digits
⍴⍕ ⍝ Repeat the digits of n (as a string) to the length of above
⊤⌿ ⍝ Take the digits where the corresponding base-2 digit is 1
```
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 bytes
```
⍕(∊⊢⊆⍴⍨∘≢)2∘⊥⍣¯1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HvVI1HHV2PuhY96mp71LvlUe@KRx0zHnUu0jQC0V1LH/UuPrTe8H/ao7YJj3r7HvVN9fR/1NV8aL3xo7aJQF5wkDOQDPHwDP6fdmiFwqPezUYGAA "APL (Dyalog Unicode) – Try It Online")
### How it works
```
⍕(∊⊢⊆⍴⍨∘≢)2∘⊥⍣¯1 ⍝ Input: n
2∘⊥⍣¯1 ⍝ Binary digits of n
⍕ ⍝ Stringify n
( ) ⍝ Inner function with the two args above
∘≢ ⍝ Length of binary digits
⍴⍨ ⍝ Cycle the string digits to the length
∊⊢⊆ ⍝ Filter the digits by the binary digits
```
[Answer]
# JavaScript (ES6), 55 bytes
```
n=>n.toString(2).replace(/./g,(d,i)=>+d?(n+=[n])[i]:'')
```
[Try it online!](https://tio.run/##HcvLDoJADAXQvV/RBYkzsQ7W92gGV36BS0IC4SWGdAwQN4Rvx2qTezf39JV9sj7vmvewZl@Uc@VmdhGbwT@GruFabbXpyneb5aUKTVijKrDRLloVN8UrF3Oi4ya5LJd6vsaEsEXYIewRDghHhBPCGcEi0EYiOwkgESSExJAg@imyslprz//@f8glC1P57p7lT8XgIsg9974tTetrlQYjT7COIBgrxXpKtZ6/ "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // n = input
n.toString(2) // convert n to a binary string
.replace( // replace:
/./g, // for each
(d, i) => // digit d at position i:
+d ? // if d is '1':
(n += [n]) // coerce n to a string (if not already done)
// and double its size to make sure we have enough digits
[i] // extract the i-th digit
: // else:
'' // discard this entry
) // end of replace()
```
[Answer]
# [Python 2](https://docs.python.org/2/), 52 bytes
```
lambda n:[c for c,i in zip(`n`*n,bin(n)[2:])if'0'<i]
```
[Try it online!](https://tio.run/##JcxBDsIgEEDRvaeYsCnY0QA7iPUitUlpFR2jAyHd6OWxjbu/ePn5szwS2xq7S32F93QNwL6fIaYCMxIQw5eyHHncM07EklVv/aAoNro50VA3yBsrge83adAa1f7bOafRaK2N8jvIhXgBRnE4CxTi@EzrLa4/VX8 "Python 2 – Try It Online")
**Input:** An integer \$n\$
**Output:** The \$n^{th}\$ numbers in the sequence, in the form of a list of digits.
**How:**
* `bin(n)` is the binary string of `n`, e.g `bin(2)` is `"0b10"`. Thus `bin(n)[2:]` is the binary string of `n` without the `0b`.
* ``n`*n` creates the n-extended string by repreating the decimal string of `n` n times. This is longer than needed, but that's ok because extra characters will be truncated later.
* `c,i in zip(`n`*n,bin(n)[2:])` takes each pair of corresponding characters `c,i` from the binary string and the n-extended string.
* `if'0'<i` checks if `i` is the character `"1"`, if so the corresponding character `c` is kept in the result list.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~101~~ \$\cdots\$ ~~96~~ 91 bytes
Save ~~a~~ 6 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
b;i;f(n){char s[n];for(b=1;i=n/b;b*=2);for(;b/=2;++i)b&n&&putchar(s[i%sprintf(s,"%d",n)]);}
```
[Try it online!](https://tio.run/##ZYxBDoIwEEX3nGLSBNIKhJQVZqwXQRa0ptqFI6G4Ipy9toorV3/mv3lj6psxIWh0aDmJ1dzHGXxPA9rnzLWS6BQ1GvVBteLToW5Ui2XphC6oKKbXkhzue5f7aXa0WO4rll9ZRWIQuIXH6IiLNYNkRw4OFEiMcQLZIaRXEDHsdnShPgOrnMDYWv7NH70QS/uW/d138igTsnyftvAG "C (gcc) – Try It Online")
Outputs the \$n^{\text{th}}\$ number in the sequence.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~25~~ 24 bytes
## Code
```
{b←2∘⊥⍣¯1⋄(b⍵)/(⍴b⍵)⍴⍕⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBNVJj9omGD3qmPGoa@mj3sWH1hs@6m7RSHrUu1VTX@NR71QQ41Hvlke9K4AkSLhWQUHB0hAA "APL (Dyalog Unicode) – Try It Online")
### Explanation
```
{ ⍝ Start function definition
b ← 2∘⊥⍣¯1 ⍝ Let b ← binary conversion function
⋄ ⍝ Start new clause
(b⍵) ⍝ Binary representation of ⍵ (input)
/ ⍝ Mask boolean list over following string
(⍴b⍵) ⍝ Length of boolean representation of ⍵
⍴ ⍝ Reshape
⍕⍵ ⍝ Stringify ⍵
} ⍝ End function definition
```
### Binary Conversion
This is all much longer than one would expect from *APL* and is due to the lack of a concise binary conversion function. Unfortunately, the above is the best we can do. Below is the breakdown:
* 'Power' (`⍣`) does an operation *n* times. So `f⍣¯1` calculates the inverse of `f`, if it can.
* 'Decode' (`⊥`) converts from an arbitrary base back to decimal; `2 ⊥ 1 1 0 1` returns `13`.
* 'Jot' (`∘`) can compose two functions as in `(f∘g) 3` or curry as in`(1∘+) 3`.
Together, `2∘⊥⍣¯1` denotes the inverse of the function that converts from binary to decimal.
(Two left-curried with the encoding function, `2∘⊥`, converts binary to decimal.)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 68 bytes
```
->n{n.to_s(2).gsub(/./).with_index{|b,i|b>?0?(n.to_s*n)[i]:""}.to_i}
```
[Try it online!](https://tio.run/##KypNqvyfpmCr8F/XLq86T68kP75Yw0hTL724NElDX09fU688syQjPjMvJbWiuiZJJ7Mmyc7ewF4DolIrTzM6M9ZKSakWxM2s/c9lqFdaUJKvYWiuqZCSr1CTV8OlAAQFCml6yYk5ORp5mlypeSn/AQ "Ruby – Try It Online")
Returns the **n**th number in the sequence.
---
I'm no expert golfer, so it's undoubtedly possible there's a better Ruby solution, but I'm (not altogether unpleasantly) surprised to see a challenge where Python and JavaScript both outperform Ruby. I guess python's list comprehensions are a perfect fit for this challenge, and JavaScript passing the index as a parameter to the `replace` method is very convenient.
[Answer]
# APL+WIN, 25 bytes
Prompts for integer n and outputs nth term
```
((b⍴2)⊤n)/(b←1+⌊2⍟n)⍴⍕n←⎕
```
[Try it online! Coutesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5raCQ96t1ipPmoa0mepj6Q0zbBUPtRT5fRo975eZpAqUe9U/OAgkBt/4Ea/qdxGXKlcRkBsTEQmwCxqQKQMAMR5kBsAcSWQGxoACIMQcKGINWGIOWGIPWGpiDCDESYK4AAAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 131 bytes
```
func[n][i: 0 remove-each _ t: take/part append/dup t: to""n n |:
length? s: find to""enbase/base to#{}n 2"1"|[s/(i: i + 1) =#"0"]t]
```
[Try it online!](https://tio.run/##HY1BCsIwFET3nmJIN4pIUpcB8Q5uQ5DY/Nig/oY0dWM9e6zdDMwbeJPJ1wt5YzdB1zBxZ9iaqKGQ6TW86UCu63FF0SjuQTK5XOBSIvbST2nlgxAMxqw3T@J76c8YNUJkv07ENzeS/MfSm8@XcRStmM0ot8tRxB7tDqdGKGGLrZkSubLoWqVgUo5cYBhCCwSwtfUH "Red – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~75~~ ~~86~~ ~~81~~ 73 bytes
```
for(;$i<strlen($d=decbin($a=$argn));$i++)if($d[$i])echo$a[$i%strlen($a)];
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVMm2KS4pyUvM0VFJsU1KTkzKBrERblcSi9DxNTaC0trZmZhpQMlolM1YzNTkjXyURyFSFaUrUjLX@/9/I4l9@QUlmfl7xf103AA "PHP – Try It Online")
Gives the nth number.
Original version didn't handle 0's in input correctly.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∍IbÏ
```
**[Try it online!](https://tio.run/##yy9OTMpM/f//UUdvcdLh/v//LQwtDQE "05AB1E – Try It Online")**
### How?
```
∍IbÏ - Full program expecting a single input e.g. 13 stack:
∍ - extend a to length b (stack empty so a=b=input) [1313131313131]
I - push the input [1313131313131, 13]
b - convert to binary [1313131313131, 1101]
Ï - a where b is 1 [133]
- implicit output 133
```
[Answer]
# [Perl 5](https://www.perl.org/) -n, 75 bytes
```
map{$i=0;@b=split//,sprintf"%b",$_;say@s=grep{$b[$i++]}split//,$_ x@b}1..$_
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saBaJdPWwNohyba4ICezRF9fp7igKDOvJE1JNUlJRyXeujix0qHYNr0oFagyKVolU1s7thamVCVeocIhqdZQT08l/v9/E6N/@QUlmfl5xf918/7r@prqGRgaAAA "Perl 5 – Try It Online")
Prints the first `n` numbers in the sequence
# [Perl 5](https://www.perl.org/) -nl, 60 bytes
```
@b=split//,sprintf"%b",$_;say@s=grep{$b[$i++]}split//,$_ x@b
```
[Try it online!](https://tio.run/##K0gtyjH9/98hyba4ICezRF9fp7igKDOvJE1JNUlJRyXeujix0qHYNr0otaBaJSlaJVNbO7YWplQlXqHCIen/fxOjf/kFJZn5ecX/dX1N9QwMDf7r5uUAAA "Perl 5 – Try It Online")
Shorter version that just prints the `n`th number
[Answer]
# [Rust](https://www.rust-lang.org/), ~~131~~ 129 bytes
```
|n|format!("{:b}",n).chars().zip(format!("{}",n).chars().cycle()).flat_map(|(b,c)|if'0'<b{Some(c)}else{None}).collect::<String>()
```
~~[Try it online!](https://tio.run/##VY5BCsIwFET3nuLbTf@HEuy2Wo/gpgeQNCQaSH5LGxea5Ow1giDOcmYeM8tjDZth8NIyEkRwOoDpt8TJTIuXYY9V7MZcNUxC3eWyIomXnfGX/mfqqZxGImGcDFcvZ0w4NoqSNTD2fd3WcZi8RkVZu1XHy8Q6F2xyTqvQdachLJZvZ6QN4LgDKEPAYBlaIfr2UASx2ABz6QXH3wtgkIk@QN7l7Q0 "Rust – Try It Online")~~
[Try it online!](https://tio.run/##VY5BDoIwFET3nOLLhv8T0sAW0SO44QCmNK02KR9S6kJLz441MTHOcmZeZvxjDbthmKRlJIjgdABz2jfezOwnGQ5Yxm5MZc0k1F36FUm87IK/9D9TT@U0EgnjZLhOcsENx1rRZk3VVP0Yh3nSqChpt@p4mVmnDM3OaRW6rh@Ct3w7I@0AxwIgzwCDZWiFOLVNFsRsAyy5Fxx/D4BBJvoAqUj7Gw "Rust – Try It Online")
Works according to option 1 and returns the \$n^{\text{th}}\$ number of the sequence as a string.
-2 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
## Explanation
```
|n| // Closure taking a parameter n
format!("{:b}",n) // Binary string of n
.chars() // Iterate over the chars
.zip( // Zip iterator with
format!("{}",n) // Decimal string of n
.chars().cycle() // Cycle over the chars
)
.flat_map( // Map with the following iterator-returning
// function and flatten the result
|(b,c)| // Closure taking the char pairs (b,c)
if'0'<b{Some(c) // If '1' then return an iterator yielding c
else{None} // Else return an empty iterator
)
.collect::<String>() // Evaluate into a string
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 79 bytes
```
V;M;r(n){M<=V?r(n/10?:(M*=2,V)),M/=2,M&V&&putchar(n%10+48):0;}f(n){M=1;r(V=n);}
```
[Try it online!](https://tio.run/##TVJLbuMwDN3nFEKBBHbDIqL1r2v0BN5m08micJMZA61bOMlmAp898@jamYp8FEmRFPVpHn43zfW6Leuyz7r8Uj9V22doG9bPj1l9XxW0zXOqN1Dq1Xa1@jqfmj@viFiyXtuYP@pyOIyZFaPEturycri23Ul9vLZdli8uC4Uhjn5/PL@fji87VamLYirIGLLkHHlPIQSKlBIxg4GCGMtsoTp2xONCJE5ILMAzDISlwmFCmSIEKBFIWDXaaDIMIiObjezIeDLYzkSYySSyFsyAzNZMCvqy1osWbCAbyaI7px2hHSaH8s6goEMkzoBBzgPBBXJRrORcIq@9Js8e3fsCRN4IkZdDC4dJkyvQAAfCEYLBhDaCQ7ngg9wPRAyRQgJRjGBBAZjZ@BZeRJh9Sa5VawjmBFmIMEmkTRYSjcLwhLqUokTLM2ithnJxe7wGqNSx/bv/PGTTS@ZqM3sQkk/Rh89eia1aJHCJ6amS9FKt120@hnz/iTE4a5E3W1898g7ZnaoqtXxT6mX5tvvV3dHt67TqQfGO1Jw0TFtmEf9i8v0sIu4b/pf7Ed3vT@e@U7pcDNd/ "C (gcc) – Try It Online")
Generates the nth number
[Answer]
# [Ruby](https://www.ruby-lang.org/), 58 bytes
```
->n{a=n.digits 2;([n]*n*m='').chars{|x|m<<x*(a.pop||0)};m}
```
[Try it online!](https://tio.run/##DcFBDoMgEADAO6/Ym0DSjXrpQelHmh5QtDWRhaAmNq5vR2fS1v3zCAby40WHNYRu@k7rAnUj3/TRpL0pCoX9z6bl4J192@5aWowhMpfqbPyZRYVbXIOsngpcACYWcIswYm/nWZISA7l8AQ "Ruby – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 87 bytes
```
x=$1$1$1$1
for((b=`dc<<<2o$1p`;b;)){ [ $[b] = $b ]&&printf ${x:0:1};x=${x:1};b=${b:1};}
```
[Try the test suite online!](https://tio.run/##NY7NCoMwEITvPsUgQfRQcXupMaYvIoKNP@glEfUgiM@erpbOwvAxh5k1n3X0g1tgMVkclKb0OpGTJEgp88skKGMFQOfYgL4dHR4WobDQb4R3uPbbFYR@14J@F3BvHBvddG1Zlk8naG6UUUlyoIKoTA0NYVBH0bxMdhsgjr3ICjoVdzAyGAZzwen/y@p@xPb@Cw "Bash – Try It Online")
Input \$n\$ is passed as an argument, and the \$n^\text{th}\$ number in the sequence is output on stdout.
How it works:
`x` is set to 4 copies of the input in a row, which is more than enough digits to match the binary equivalent of the input. (A number in base 2 can never be longer than 4 times its representation in base 10, since \$\log\_2(10)<4.\$)
`b` is initialized to the binary representation of the input.
The for loop repeats the following as long as `b` still has at least one `1` in it:
* If `b` doesn't start with a `0`, then the first character in `x` is printed.
* The first character is chopped off of `x` and `b`.
The golfiest trick is probably the way I check to see if `b` starts with a `1`: the expression `$[b]` means: `b` evaluated as an arithmetic expression. This will omit any initial 0s (except that it will keep a final 0 if all the characters in `b` are `0`). So `[ $[b] = b ]` is true iff `b` either starts with a `1` or is equal to `"0"`. But `b` can't equal `"0"` since the loop termination condition would have been true in that case, and the loop would have ended already.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 108 bytes
```
n->{var s=""+n;for(int b=n.highestOneBit(n),i=0;b>0;b/=2,i++)if((b&n)>0)System.out.print((s+=s).charAt(i));}
```
[Try it online!](https://tio.run/##dU7BTsMwDL3vK6xKoIR2oYwbWSoBJw6Iw46IQ9qlnUvrVok7CU379pJNPSFxsJ7tZ7/3Wnu063b/PWM/Dp6hjbOaGDtVT1QxDqTu9Gqcyg4rqDobArxbJDitAJZtYMsRjgPuoY@c2LFHaj6/wPomyOspwOtAYeqd374Ru8b5AmowM62L09F6CCZJUtL14AUSQ2lIHbA5uMAf5F6QBckMTa7LIta92WSYphJrIcpbkkUudz@BXa@GidUYzVmIkJogVXWw/pkFSqnPs74GiR5wNUEw8KAjbCPmeeyi5pIW4K9iLZKbx/0TJBmg1MtRrWxVufFioP/560gs3Hl1qfP8Cw "Java (JDK) – Try It Online")
## Credits
* -7 bytes thanks to Kevin Cruijssen
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
fḋ¹¢s
```
[Try it online!](https://tio.run/##AR8A4P9odXNr/23Cp2Vz4oKB4bijMTAw/2bhuIvCucKic/// "Husk – Try It Online") This function works according to option 1, outputting the term as a string.
### Explanation
```
fḋ¹¢s (Let X denote the argument.)
f Select the elements of
s the string representing X,
¢ cycled infinitely, corresponding to truthy values of
ḋ¹ the binary digits of X.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Came up with a few approaches but couldn't do better than 8 bytes.
With output as a digit array:
```
¤¬ðÍ£sgX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=pKzwzaNzZ1g&input=OTU)
With output as a string:
```
¤ËÍçEgUs
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=pMvN50VnVXM&input=OTU)
```
¤¬ðÍ£sgX :Implicit input of integer U
¤ :To binary string
¬ :Split
ð :Truthy indices when
Í : Converted to integer
£ :Map each X
s : Convert U to string
gX : Get digit at index X
```
```
¤ËÍçEgUì :Implicit input of integer U
¤ :To binary string
Ë :Map each D at index E
Í : Convert D to integer
ç : That many times repeat
Eg : Index E into
Uì : Digit array of U
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 17 bytes
```
₌SbL:‟*Ẏf?bZ't;vh
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=%E2%82%8CSbL%3A%E2%80%9F*%E1%BA%8Ef%3FbZ%27t%3Bvh&inputs=7&header=&footer=)
A mess.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 89 bytes
```
{for(f=b=1;$1>=b;e=e$1)c[d++]=and($1,b)/(b*=2);for(;d--;f++)c[d]?g=g substr(e,f,1):0}$0=g
```
[Try it online!](https://tio.run/##Fcq9DkAwEADgVzF0aLXCSQxcjgcRg9OfQUJSxCCeveKbv/leU3r8HqUnJkABPTE6cgLUMlqtJ5o3KwUYVqXknGqF/0ZbFOi1/tM0BArZcfFxRumMN6C66hUVhZSa9gM "AWK – Try It Online")
Not that short, but AWK doesn't have a `print` format to generate binary strings from integers, so it has to iterate to get that info...
At a high level, one loop uses bitwise `and` operations with a single bit moved one position to the left each time to built an array of "binary" settings. It also builds up a string composed of multiple copies of the `N` number while it's looping. AWK doesn't have a nice `string*number` operator either.
Then the second loop works backwards through that array and for each entry which is `1`, it appends the appropriate character to a "results" accumulator.
The final step just prints the accumulated string.
```
# Loop 1, build the "binary" array and string of duplicated "N" characters
for(f=b=1;$1>=b;e=e$1)c[d++]=and($1,b)/(b*=2);
(f=b=1; # Loop init, "f" is used in loop #2
$1>=b; # Exit test, goes until bit check > N
e=e$1) # End of loop, build "N dup string
c[d++]=and($1,b)/(b*=2); # Body, does a couple of things...
# d++ : increment bit position
# and($1,b) : extract bit
# /(b*=2) : normalize, then shift bit
# c[d++]= : add to "binary" array
# Loop 2, accumulate chars associated with set bits
for(;d--;f++)c[d]?g=g substr(e,f,1):0
d--; # Exit test, when all bits checked stop
f++) # End of loop, increment char pos in "N" dup str
c[d]? : # Ternary, code runs if bit is set
g=g substr(e,f,1) # Append current char to accumulator
0 # No-op "else" from ternary
# Print the result
$0=g # Typical AWK golf trick, assign "$0" to what you want to print w/o code block
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
⭆↨Iθ²⎇ι§θκω
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaDglFqdqOCcWl2gUauooGAFxSGpRXmJRpUamjoJjiWdeSmqFRqGOQjZQplxTU9P6/39D4/@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input as a string
I Cast to integer
↨ ² Convert to base `2`
⭆ Map over digits
ι Current digit
⎇ If non-zero
θ Input as a string
§ Cyclically indexed by
κ Current index
ω Else empty string
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
The `Ï<` ruins the consecutive word `bāsè`... (If you don't get it, the hex code 05AB1E converted to base64 would result in `base`.)
```
bāsÏ<è
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/6Uhj8eF@m8Mr/v@3MLQ0BAA "05AB1E – Try It Online")
# Explanation
```
b To base 2
ā Length-range to 1
s Prepend
Ï Keep all that's truthy
< -1 due to 0-based indexing ... that's terrible!
è Modular Indexing
```
] |
[Question]
[
**The Challenge**
The goal of this challenge is to determine whether a given String can be typed using only one line of a standard UK QWERTY keyboard.
This is `code golf`, so shortest solution in bytes wins!
---
**IO**
Input will be a single String of zero or more characters in the ASCII decimal range of 32-126 inclusive.
You may assume for this challenge that an empty String requires no typing and thus can be typed using a single line.
You may take the input as a String, list of characters, or equivalent form for your language.
Output should be a truthy value for any String that can be typed using a single line, or falsey for one that cannot.
---
**Keyboard layout**
To clarify any ambiguity over what the standard keyboard layout is below is a list of keys available on each line, including alternate upper keys (accessed using shift).
* *Line 1*
+ Standard: ``1234567890-=`
* *Line 2*
+ Standard: `qwertyuiop[]`
* *Line 3*
+ Standard: `asdfghjkl;'#`
+ Uppercase: `ASDFGHJKL`
+ Special: Caps Lock
* *Line 4*
+ Standard: `\zxcvbnm,./`
+ Alternate: `|<>?`
+ Uppercase: `ZXCVBNM`
+ Special: Shift
* *Line 5*
+ Special: Space Bar
Alternate upper keys can only be pressed if Shift is also on the same line, and uppercase keys can only be accessed through Caps Lock or Shift. You really can only use one keyboard line!
---
**Test cases**
```
-> true (empty string)
45-2=43 -> true (line 1)
qwerty -> true (line 2)
tryitout -> true (line 2)
Qwerty -> false (no shift or caps on line 2)
#sad -> true (line 3)
AsDf -> true (caps lock used)
@sDF -> false (no shift for alternate upper)
zxcvbn? -> true (line 4)
zxc vbn -> false (spacebar on separate line)
123abc -> false (multiple lines)
-> true (just space bar)
!!! -> false (exclamation marks cannot be printed by a single line)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~130~~ ~~123~~ ~~121~~ 115 bytes
```
lambda s:any(set(s)<=set(l+l.lower())for l in["`1234567890-=","eqwrtyuiop[]","ASDFGHJKL;'#","ZXCVBNM\,./|<>?"," "])
```
[Try it online!](https://tio.run/##hZJdT8IwFIbv/RUn44ItAsoYfjIQJWj8SoyJMQKJ3ehkWtrSduKM/312I@KQEXvTnPZ5z3t6enisJozaSeAOE4Km3hiBPEI0NiVWprRabrqTbVIjbI6FaVkBE0AgpAPjuW43nObe/sHhbtU1KgaezYWKo5DxwUiH3fte//zi8ur6uFzS4dPj2cPp7c2wUtv5arU7@gSMkZVwEVIFgVkuW7BcJYBqG5SIcBaaeMpVDFJp9sXaWkqcZtV2nUam/CshIcVQz8EzXb6KFy6FsJ2DlYhDxSKV4v/Cd2uZA0RkRpuUgZyEgQLdNR9xCYzCWoKSROOf5xe6NXJwV/aCTXDmQJj/BpHE45zoRPb6q6KCEtOfRURhQZHCEHGORS7F54f/7tHO5mY7qzBoOgf/@kmOfOwhkbZCYo5E6pZmyOn1ZCHPL27pNCIq5GShkTmRvlwO0d8KXyOpIHMGbW0l3w "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 111 bytes
```
lambda s:any({*s}<={*l+l.lower()}for l in["`1234567890-=","eqwrtyuiop[]","ASDFGHJKL;'#","ZXCVBNM\,./|<>?"," "])
```
[Try it online!](https://tio.run/##hZJrT8IwGIW/@yvewAc2BBQ2vDIQJWi8JcbEGIHEbnQyLV1pO3Eiv312w8Dkovv2rs85pz0tC@XAp0bkWt2IoKHdRyCOEA21SV5Ma9YkT7ZJifhjzDV96vocCHi0k3kuVwyzurd/cLhbtDKFDB6NuQwDz2ednhqb9632@cXl1fVxLqvGp8ezh9Pbm26htPNVqzfUH8j09Ihxj0rN1XI5XYf5lwUo1kHyACejhodMhiCkgl/0rbnGrBYrlmnMpMsa4lEM5RQ9UgeQ4U/OWrqSoiUPPekHMuH/pe9WvV1ERIJr1Acx8FwJqjoHMQE@hRWHrED9eQdr84wU3RQtdyOdZBDfeYNA4H5KdSJa7SXVml3GN4yIxJwiiSFgDPOUx@eH827Txh@dm79pUHiaXiQKhhxsIx73ITBDPM6LLVIG6o0h29lQ7DAg0mNkJhIplVpcvKflTb4GQkKSDSpcj74B "Python 3 – Try It Online")
-4 bytes, thanks to nedla2004
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~72~~ 71 bytes
```
`^([-=\d`]+|[][eio-rtuwy]+|(?i)[adfghjkls;'#]+|[\\bcnmvxz,./|<>?]+| *)$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyFOI1rXNiYlIVa7Jjo2OjUzX7eopLS8EsjVsM/UjE5MSUvPyMrOKbZWVwYpiYlJSs7LLauo0tHTr7GxsweKKWhpqvz/z2Viqmtka2LMVVieWlRSyVVSVJlZkl9awhUI4SsXJ6ZwORa7pHE5FLu4cVVVJJcl5dmDaAUgg8vQyDgxKZlLAQwA "Retina 0.8.2 – Try It Online") Explanation: Each alternation matches a different row of the keyboard. The `(?i)` in the middle of the pattern causes the entire rest of the pattern to be matched case-insensitively. Edit: Saved 1 byte thanks to @KirillL.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~66~~ 47 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žh…`-=«žS„[]«žTDu…;'#««žUDu"\,./|<>?"««ð)εISåP}O
```
Takes the input as a list of characters.
-19 bytes thanks to *@Emigna*. Completely forgot we had qwerty-keyboard constant builtins. :D
[Try it online](https://tio.run/##yy9OTMpM/f//6L6MRw3LEnRtD60@ui/4UcO86FgQK8SlFChsra58aDWIG@pSqhSjo6dfY2NnrwQSOrxB89xWz8NLA2r9//@PVjJR0lEyBWJdIDYCYlsgBokZK8UCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVhls/6hhnoKGfaW9kqbCo7ZJCkr2lcGh/4/uy3jUsCxB1/bQ6qP7goFKomNBrBCXUqCwtbryodUgbqhLqVKMjp5@jY2dvRJI6PAGzXNbIw4vDaj1/6/z38RU18jWxJirsDy1qKSSq6SoMrMkv7SEKxDCVy5OTOFyLHZJ43IodnHjqqpILkvKswfRCkAGl6GRcWJSMpcCl6KiIgA).
**Explanation:**
```
žh # Push "0123456789"
…`-= # Push "`-="
« # Merge them together
žS # Push "qwertyuiop"
„[] # Push "[]"
« # Merge them togeter
žT # Push "asdfghjkl"
Du # Duplicate, and toUppercase the copy
…;'# # Push ";'#"
«« # Merge all three together
žU # Push "zxcvbnm"
Du # Duplicate, and toUppercase the copy
"\,./|<>?" # Push "\,./|<>?"
«« # Merge all three together
ð # Push a space
) # Wrap all string in an array
ε } # Map each to:
I # Take the input (list of characters)
å # Check for each if it's in the current string of the map-iteration
P # Take the product (1 if all are truthy, 0 otherwise)
O # Take the sum (either 1 or 0, so truthy/falsey), and output implicitly
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 76 bytes
```
$_=/^( *|[\d`=-]+|[][wetyuio-r]+|(?i)[asdfghjkl;'#]+|[\\\/zxcvbnm,.|<>?]+)$/
```
[Try it online!](https://tio.run/##HYxdE4FAGEbv319RUzMkafRxRWI07t0Zu6FPIm3aTTL9divuznPmmVMmVW5zLh8d/TAURh3C8cnRfLVDPmoS1tYZ0ap@Dt1MQQGN0/PlestnA@l3wRjr71f0DIv7eNLNF66vKrLOOVi2ZjiWCY8mqViLfGBVmzFSM9j@DUg0iGFFvRSW1NvAfrfuIy70MaEHmBpmEEYggCiKH1KyjBSUa2X@BQ "Perl 5 – Try It Online")
The obvious regex approach.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, ~~86~~ 81 bytes
```
p /^( *|[\d`=-]+|[\]\[wetyuio-r]+|(?i)[asdfghjkl;'#]+|[\\\/zxcvbnm,.|<>?]+)$/?1:0
```
[Try it online!](https://tio.run/##JYzLDoIwFET39yuaYCKIiAJuVKwmxL1ripGn4oNiW0QM325FWc2Zk8mwKmqkLJF5UNGo9UlydI1A7yAgfp2KpsqpwTqh4lzzQ55kp/PlelsOlf@IEPP9ip9RcR9P2tUaB7o2MPFsMZUSnLlhuY4NjzplogHBmlzQSsC@7woPE9hyL4MN93bQ3@Bfog5gZtlhFAP60FLktODSKL4 "Ruby – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~99~~ ~~98~~ 95 bytes
```
x=>/^([-`=\d]+|[wetyuio-r[\]]+)$/.test(x)|/^([asdfghjkl;'#]+|[zxcvbnm,./<>?\\|]+| *)$/i.test(x)
```
[Try it online!](https://tio.run/##dc@9DoIwFIbh3asANRFUIKJOCGhC3J0BY4WiIFKllR/DvVeIcTGH9XnPN5wEFYgGefxgSkZCzCOTV6alHSVXOZle6M8at8SsfsVEyV3P92fyWFMZpkyq5KY7QzSMLtfklhqTUXf9roLinN3nqraxbM9rWhOm7Sj@rbgRkIySFKspuUiRNBzK8uDfVmtFN1dLKD1LnLMaKiyvY0ZeDGqH3tWIohDyHXUiyLfU2UP@fdzuSULboLTQl@gcQEWAUBTFjvkH "JavaScript (Node.js) – Try It Online")
-1 from the comment by @Kirill L. in the Retina answer.
-3 thanks @Ismael Miguel and @Arnauld for their combined effort.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~102 101~~ 100 bytes
*-1 byte thanks to nwellnhof!*
```
->\a{max map {a.comb⊆comb $_~.lc:},|<eqwrtyuiop[] ASDFGHJKL;'# ZXCVBNM\,./|<>?>,' ',"`-="~[~] ^10}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX9cuJrE6N7FCITexQKE6US85PzfpUVcbiFJQia/Ty0m2qtWpsUktLC8qqSzNzC@IjlVwDHZxc/fw8vaxVldWiIpwDnPy843R0dOvsbGzt9NRV1DXUUrQtVWqi66LVYgzNKj9X5xYqZCmoWRoZKykac0F5ZmY6hrZmiCLFJanAi1BEigpqswsyS8tQRIKRFejXJyYgsR1LHZJQ@I6FLu4IXGrKpLLkvLsUUUUgEJIIkBXJiYlIwkoKAA5/wE "Perl 6 – Try It Online")
Pretty standard implementation. There's probably a shorter regex based solution to this, but I don't know Perl 6's regex well enough to make an attempt.
[Answer]
# Java 10, ~~209~~ 208 bytes
```
s->{int l=0,t;for(var p:s){t=p.matches("[[0-9]`\\-=]")?1:"qwertyuiop[]".contains(p)?2:p.matches("(?i)[asdfghjkl;'#]")?3:"\\zxcvbnm,./|<>?ZXCVBNM".contains(p)?4:p.equals(" ")?5:9;l=l<1?t:l!=t?9:l;}return l<6;}
```
-1 byte thanks to *@TFeld*.
[Try it online.](https://tio.run/##bZLdbuIwEIXv@xSDuWgiSFp@diUS0uxPtXcgVUhVtQnSGmOoqXHSeMIuS7ntA/QR@yLUBFatxd5Ynm88xz5HXtAV9RbThx2TVGsYUKE2ZwBCIS9mlHEY7kuASZZJThUwZ4SFUPNkDNoNTWt7ZhaNFAWDISiIYKe9q40RABldNjGcZYWzogXkgXY3GOX@kiK759ohSXLp9ca/0tSLxsSNWwF5/M0LXJciy5Mx8Vmm0LxHO7kbt4MPg04s3ITq6Wx@v3iQ4Xl9P94JSJr@/cNWE7Vs@hdP/av4593322/Dga3UNUr8saTSCIGZ@xT0QhnJfivGQNYijHuBDLcFx7JQIPufw@0u3HvMy4k0Ho9WV5mYwtJovudB3UNUyDU6hFTp/Ku6ba8ddTs2PLi1GRZrgVmJNr35z8m6plObfNXXM5t80dc/bHIIKD6BYKgNW@0OnTCbgV3WajVy8gmqZKr@IRnzl/ISj9mM1hr50jcG/dw0USqHpIQ0qjMNs4XX5xcgDeUzp2K@zqWo4nSPN213bw)
**Explanation:**
```
s->{ // Method with String-array parameter and boolean return-type
int l=0, // Line-integer, starting at 0
t; // Temp integer
for(var p:s){ // Loop over the characters
t=p.matches("[[0-9]`\\-=]")?
// If it's a character from the first line:
1 // Set `t` to 1
:"qwertyuiop[]".contains(p)?
// Else-if it's a character from the second line:
2 // Set `t` to 2
:p.matches("(?i)[asdfghjkl;'#]")?
// Else-if it's a character from the third line
3 // Set `t` to 3
:"\\zxcvbnm,./|<>?ZXCVBNM".contains(p)?
// Else-if it's a character from the fourth line:
4 // Set `t` to 4
:p.equals(" ")? // Else-if it's a space from the fifth line:
5 // Set `t` to 5
: // Else (invalid character):
9; // Set `t` to 9
l=l<1? // If `l` is still 0:
t // Set it to `t`
:l!=t? // Else-if `t` is a different line than `l`:
9 // Set `l` to 9 (non-existing line)
: // Else (`t` is the same line as `l`):
l;} // Leave `l` the same
return l<6;} // Return whether `l` is not 9
```
[Answer]
# Powershell, 87 bytes
*Port of Neil's [Retina regex](https://codegolf.stackexchange.com/a/173780/80745).*
```
"$args"-cmatch"^([-=\d``]+|[][eio-rtuwy]+|(?i)[adfghjkls;'#]+|[\\bcnmvxz,./|<>?]+| *)$"
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 55 bytes
```
ØDW;Øq;Œu$€3,4¦;"“rɠ3“ݲ“¿µ|“aƲƘ0ÞḅzḂ»⁶ṭ
¢f€ẈṠSỊafƑ¢F¤$
```
[Try it online!](https://tio.run/##ddE9T8JAHAbwvZ/iKAyYQCK0TsS3hLAbBwfjcJSrFo@23F3VEgclMRo3nRiMIcQ46UKiARlMroHEj1G@SD2KShtLl3@a/p7nXlpHGLtB4HXKeyWv0yyN753MtP2i5FT@XJKnFw/kq6uIMR7xvhj8k7@diwkn/Uln1Xv0B1ctf9Dmo@nluz98lXhPF2n/48Yfdnf90S3UJ3e8V@FPmcC7Fl@CYF@S5RyIPOn8BmDEQeFLFjVs5gLKiGEerkiyupYvrqvKTyJOsWEiUBCoeYoIc39bE1BRIEZcg1kOm7MlaOdfkw4xDVXWtAA9MnQGLAI0aFNgmeAvmKawtjhWQrsi0DYt68tQ2Igt7Rg4FNUE3qLlShwnbEUXe4GYIWJChoBj24iIaOtMO6mam8svTZ0jIFQELfqpDTVUhWR2RIpsSGbts6TIFYoKrGrJV9RwMDNsPLdUYBD71fGd1B3KQLgSEEsJnEqlIjzSLB18Aw "Jelly – Try It Online")
The first line yields a list of the keyboard lines and the second one checks whether the program input is contained on a single (or zero) lines and that there are no characters that can't be typed (like `QWE!@#`).
[Answer]
# [C](http://clang.llvm.org/), 150 bytes
```
x;f(char*s){for(x=0;*s;x|="@ "[*s++-32]);return!(x&x-1);}
```
[Try it online!](https://tio.run/##hdG9TsMwEADg4TJYnfwIFyOQnRKpTWCyIorECzBTBjdtIBK4YLvgUvrswWmAqYazTv75TrqTXOf1k9IPXedlw@tHZTIrds3acF9NZGal/6zYDIDCkIAJYvIbQPt7LxQoHfIQ3xsQJAAJRaQkWJ@IJAQlQcICBGB3mR2P87K4F9Ks3MbolPszn0@F3HetdvisWs0F7kaILyY8NJydLueanWM4MSHkUbi4zIuqKKP@@r4ybhtlZ7atW29ctODEqmUUr@1NE8UPX78t9FXUEfFgR/H277Fn/zTG0Dnq06JUizrKaZr@zDX8E07kaN99AQ "C (clang) – Try It Online")
It won't win any prizes, but this is a fun approach: we map characters on the five rows of the keyboard to `4 8 16 32 64`, and every invalid character to `3`. We bitwise OR the value for each character in the string together, and check if the result satisfies `x&(x-1) == 0`, which is true when `x` is a power of 2 or zero, i.e. whenever `x` has at most one bit set.
[Answer]
# [LUA](https://www.lua.org), 282 262 259 270 bytes
```
s=io.read()l=0
t=0
for c in s:gmatch"."do
f=c.find
t=f(c,"[0-9%`-=]")or 0|(f(c,"[qwertyuiop%[%]]")or 0)*2|(f(c,"[aAsSdDfFgGhHjJkKlL:'@#~]")or 0)*4|(f(c,"[\\zxcvbnm,./|<>?ZXCVBNM]")or 0)*8|(f(c," ")or 0)*16
t=t==0 and 17or t
l=l<1 and t or l~=t and 17or l
end
print(l<17)
```
[Try it online!](https://tio.run/##yylN/P@/2DYzX68oNTFFQzPH1oCrBIjT8osUkhUy8xSKrdJzE0uSM5T0lFLyudJsk/XSMvNSgGrSNJJ1lKINdC1VE3RtY5U0gRoMajQgooXlqUUllaWZ@QWq0aqxUElNLSOYfKJjcXCKS5pbunuGR5ZXtneOj5W6g3IdXKEJTGFMTFVFcllSXq6Onn6NjZ19VIRzmJOfL1yhBVShAkzA0AzotBJbWwOFxLwUBUNzoGgJV45tjo0hWKBEASiQU2dbgpDO4UoF@qegKDOvRAOozFzz//@SotRyAA "Lua – Try It Online")
[Answer]
# PHP, 98 bytes
I´m a little sad that there´s nothing shorter than regex. It´s probably not the fastest solution.
```
<?=preg_match("%^([`\d=-]*|[wetyuio-r[\]]*|(?i)[asdfghjkl;'#]*|[\\\zxcvbnm,./|<>?]*| *)$%",$argn);
```
Run as pipe with `-F` or [try it online](http://sandbox.onlinephpfunctions.com/code/73e917278f07b7ced2d422001f6656774ae05cba).
---
Shortest non-regex solution I found (124 bytes; linebreak and tab for reading convenience):
```
foreach(["`1234567890-=","qwertyuiop[]","asdfghjkl;'#ASDFGHJKL","zxcvbnm,./\|<>?ZXCVBNM"," "]as$d)
trim($argn,$d)>""||die(1);
```
exits with code `1` for truthy, `0` for falsy. Run as pipe with `-R`.
Requires PHP 5.4 or later; for older PHP, use `array(...)` instead of `[...]` (+5 bytes)
```
foreach(split(_,"`1234567890-=_qwertyuiop[]_asdfghjkl;'#ASDFGHJKL_zxcvbnm,./\|<>?ZXCVBNM_ ")as$d)
trim($argn,$d)>""||die(1);
```
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~163~~ ~~119~~ 113 bytes
This is an AWK answer, returns a numeric 1 string for true, 0 string for false.
(Written as AWK invoke as awk -f file for interactive use.)
```
{print/^[-`1234567890=]*$/||/^[]qwertyuiop\[]*$/||/^[asdfghjkl;'#ASDFGHJKL]*$/||/^[zxcvbnm,.\/\|<>?ZXCVBNM]*$/||/^ *$/}
```
[Try it online!](https://tio.run/##SyzP/v@/uqAoM69EPy5aN8HQyNjE1MzcwtLANlZLRb@mBigaW1ieWlRSWZqZXxATDRdNLE5JS8/Iys6xVld2DHZxc/fw8vaBy1ZVJJcl5eXq6MXox9TY2NlHRTiHOfn5wuQVgHTt//95VRV6eUlVFUkVSVxRfnZ@zmW5OkBusk5Znl6UX0SyXp4eF9Dy/KLK/MrY6FguI2NLEzPLBMOEhARdkERlUV4al7lFVhlXYLgrAA "AWK – Try It Online")
However, does not handle TAB character as written (trivial extension) as not part of spec.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 119 bytes
Includes an echo to provide "readable" output. If you put a suitable wrapper of shell (your choice) around it to include print/output, then you can save 8 bytes. My reading of the challenge suggests the solution should output a suitable output indication so I stick with 119 bytes.
```
[[ "$@" =~ ^[asdfghjklASDFGHJKL\;\'#]*$|^[-\`0-9=]+$|^[]qwertyuiop\[]*$|^[zxcvbnm,./\|\<\>\?ZXCVBNM]*$|^\ *$ ]];echo $?
```
[Try it online!](https://tio.run/##S0oszvj/PzpaQUnFQUnBtk4hLjqxOCUtPSMrO8cx2MXN3cPL2yfGOkZdOVZLpSYuWjcmwUDX0jZWG8SJLSxPLSqpLM3ML4iJhshXVSSXJeXl6ujpx9TE2MTYxdhHRTiHOfn5gqVjFLRUFGJjrVOTM/IVVOz//w8EG/AfAA "Bash – Try It Online")
] |
[Question]
[
A family of sets is called [laminar](https://en.wikipedia.org/wiki/Laminar_set_family) if for any two sets \$A\$ and \$B\$ in the family one of the following is true:
* \$ A \subseteq B \$
* \$ A \supseteq B \$
* \$ A \cap B = \emptyset \$
Or less mathematical:
A laminar set is a list of lists that satisfies the following condition: If two elements of the top level list have at least one element in common, one of them has to be completely contained in the other one.
Examples:
```
laminar:
{}
{{1,2,3},{1,2},{1},{}}
{{1,2,3,4},{1,2,3},{1,2},{3},{4}}
{{1,2,3,4},{1,2},{3,4},{1},{3}}
{{1,2,3,4},{1,3},{2,4},{1},{2},{3},{4},{}}
{{1,2,3},{4,5},{7,8},{3},{5},{7}}
not laminar:
{{1,2},{2,3}}
{{1,2,3,4},{1,2,3},{1,2},{3,4}}
{{1,2,3,4},{1,2},{3,4},{2,3},{1},{2},{3},{4}}
{{1,2,3,4,5},{1,2,3},{4,5,6}}
```
Your goal is to write a program of function that takes a set of set as input and returns truthy if the set is laminar and falsey if is it not laminar.
Rules:
* You can take lists instead of sets as Input
* If you use lists as input you can assume that the lists (top-level and/or sub-lists) are sorted (in any convenient order) and each element appear only once
* Your solution should be able to handle Inputs lists with at least 250 distinct element values
* You are allowed to use any type to represent the elements of the list (as long as it has enough distinct values)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution (per language) wins.
[Answer]
# [Python](https://www.python.org), 50 bytes
```
lambda c:all(a&b in(a,b,a-a)for a in c for b in c)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3jXISc5NSEhWSrRJzcjQS1ZIUMvM0EnWSdBJ1EzXT8osUEoECCskKIGYSmKkJ0XmLsaukqLQko9I2OjpWR4ErutpQx0jHuFYHRIPIWp3i1BINzVgdmJSOCUQSSRGIZVKLqQQkBWGDFWEoAOkzgitAmIRuJUhQxxRImutYQBWBeSATY7m40hJziisVbBWiIerBhmKxDcXFOnjdC1WK4ihk5WDHIDlNxwzmFGD4ZoLCFxKoVlycBUWZeSUaaRqZmppI0mAnW3EpAAGSAkiULFgAoQE)
[Answer]
# Rust, 63 bytes
Port of [mousetail](https://codegolf.stackexchange.com/users/91213/mousetail)'s [python answer](https://codegolf.stackexchange.com/a/263630).
```
|s|s.iter().all(|a|s.iter().all(|b|a&b==*a||a&b==*b||a&b==a-a))
```
[Rust explorer](https://www.rustexplorer.com/b#%2F*%0A%5Bdependencies%5D%0Amaplit%20%3D%20%221.0.2%22%0A*%2F%0A%0Ause%20maplit%3A%3Ahashset%3B%0Ause%20std%3A%3Acollections%3A%3AHashSet%3B%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20f%3A%20for%3C%27a%3E%20fn(%26%5BHashSet%3Ci32%3E%5D)%20-%3E%20bool%20%3D%20%7Cs%7C%20%7B%0A%20%20%20%20%20%20%20%20s.iter().all(%7Ca%7C%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20s.iter()%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20.all(%7Cb%7C%20a%20%26%20b%20%3D%3D%20*a%20%7C%7C%20a%20%26%20b%20%3D%3D%20*b%20%7C%7C%20a%20%26%20b%20%3D%3D%20a%20-%20a)%0A%20%20%20%20%20%20%20%20%7D)%0A%20%20%20%20%7D%3B%0A%0A%20%20%20%20assert!(f(%26%5B%5D))%3B%0A%20%20%20%20assert!(f(%26%5B%0A%20%20%20%20%20%20%20%20hashset!%5B1%2C%202%2C%203%5D%2C%0A%20%20%20%20%20%20%20%20hashset!%5B1%2C%202%5D%2C%0A%20%20%20%20%20%20%20%20hashset!%5B1%5D%2C%0A%20%20%20%20%20%20%20%20hashset!%5B%5D%0A%20%20%20%20%5D))%3B%0A%20%20%20%20assert!(f(%26%5B%0A%20%20%20%20%20%20%20%20hashset!%20%7B1%2C2%2C3%2C4%7D%2C%0A%20%20%20%20%20%20%20%20hashset!%20%7B1%2C3%7D%2C%0A%20%20%20%20%20%20%20%20hashset!%20%7B2%2C4%7D%2C%0A%20%20%20%20%20%20%20%20hashset!%20%7B1%7D%2C%0A%20%20%20%20%20%20%20%20hashset!%20%7B2%7D%2C%0A%20%20%20%20%20%20%20%20hashset!%20%7B3%7D%2C%0A%20%20%20%20%20%20%20%20hashset!%20%7B4%7D%2C%0A%20%20%20%20%20%20%20%20hashset!%20%7B%7D%0A%20%20%20%20%5D))%3B%0A%0A%20%20%20%20assert!(!f(%26%5Bhashset!%20%7B1%2C2%7D%2C%20hashset!%20%7B2%2C3%7D%5D))%3B%0A%7D%0A)
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 8 bytes
```
ᵒ{ᵋ∩?Ø?=
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6Fusfbp1U_XBr96OOlfaHZ9jbLilOSi6Gyi24xagcHavAFR1tqGOkYxyrA6JBJBDHxsKEdUwgEkgKQCwTTBUgGQgbrAZdHqTLCC6PMAfZMpCAjimQNNexgCoA82AqwEZgGo3iOB18ToOqRHEAkmqw3Ugu0TGLjYUEFgA)
```
ᵒ{ᵋ∩?Ø?=
ᵒ{ For each pair of elements A, B in the input, check that:
ᵋ∩ Intersection of A and B
?Ø? Any of A, B, or the empty set
= Are they equal?
```
[Answer]
# JavaScript (ES6), 69 bytes
Expects a list of lists. Returns *false* for laminar, or *true* for not laminar.
Not the right tool for the job.
```
a=>a.some(x=>a.some(y=>(b=x.filter(v=>y.includes(v))+'')&&b!=x&b!=y))
```
[Try it online!](https://tio.run/##jY9NboMwEIX3PoWTRWKrU0tN0h81MruegnoxIaalcuwKCILTU4agFNpIycLPz543Hn9fWGGR5Nl3ee/D3rapblFHqIpwsKI@u0ZHYqdrlWautLmodNSozCfuuLeFqKS8Wy7lYrGb6ZqkkbJNgi@Cs8qFDzF3eMg85q9zuWUx4zw2QBo/wArWBmgn7ZYZV2Bzqo0y5DYXQ1Q8@T52IUK9q3Pk97U/U@kOHjt9hpch05@MYYapNORvmHwK5DriY8hUoJQdH5uQv3sfSv6Pf/gwTbsGDFdwh/CEaNrQw4zQ4Ok2lPYH "JavaScript (Node.js) – Try It Online")
### 41 bytes (ES11)
As one would expect, converting each sub-list to a BigInt bit-mask and applying bitwise logic is longer.
```
a=>(a=a.map(b=>b.map(v=>m|=1n<<v,m=0n)&&m)).some(x=>a.some(y=>y^(y&=x)&&x^y&&y))
```
[Try it online!](https://tio.run/##pVDRSsMwFH3PV4Q9lASy4ubU4XbzIPjgN9QM7mo7K00y2lIa8N9r0xZtdbAHA7k5yTk3yTkfWGMZF9m5Whr7lrQptAiSIWCo8cyOII89qEHqT1iZ/b4WGm4MDwLNeVhanbAGJA7IgXQH5gJoOr45uCBwnLexNaXNkzC3J7bIUWcGi8cF35GIUBop4Wu0Emtxq4Rffe2mmjJiM3ATjUebiyJPDriXXZD43vW35Oe2X6/6M3HX1QexHTX9TimiSJja4hnjd4YUJJ2aTNmYnieG/J6y04upuB87QmaJvBpjK/onl9GI/8W1IMSVGEbxzOm8oTc5sSzu/2ex/QI "JavaScript (Node.js) – Try It Online") (80 bytes)
But if we can take the list of sets directly as a list of bit-masks (as suggested by [@Cubic](https://codegolf.stackexchange.com/users/32454/cubic)), then we can just do:
```
a=>a.some(x=>a.some(y=>y^(y&=x)&&x^y&&y))
```
[Try it online!](https://tio.run/##tZDfaoMwFMbv8xSHXkgCp2Htuq2sjReDXewZXAqp1c6hSVEnCnt312Ol067QqwVycnK@7@TP79NUpgjz5FBOrdtFbaxao3wjC5dFvD5njfKbDW88VQvPqzeN5zVCtKGzhUsjmbo9n6QmS6zJnydixQIGEGikGMxwjvcaaaV4nHqo4OKkDTyULa6aSDzlne2KhXrnZ8vvaRe3Ug0fjvEJl72n22nNNJOxy19N@MENKB@Gn4y5kZk58C0JW5lHu68w4jxDqASVMviGmYX1Gl6S/ZsteSUQ7qygsWJsxOvdWlfCH2r9N@mNtzDhDUi9ecRh3NAhGADBx/8E0P4A "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ãε¯ªy`Ã.å}P
```
[Try it online](https://tio.run/##yy9OTMpM/f//8OJzWw@tP7SqMuFws97hpbUB//9HRxvqGOkY65jE6kBYEBpIglgmsbEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w4vPbT20/tCqyoTDzXqHl9YG/Nf5Hx0dq6MQHW2oY6RjHKsDokEkEMcixHVMIDJIKkAsEyxKQFIQNlgRhgKQPiO4AoRJKPaBRHRMgaS5jgVUBZgHVwI2xJiAC3Xwug@qFMURyMrB9iO5RscsNjYWAA).
**Explanation:**
```
ã # Cartesian product to get all pairs of the (implicit) input-list
ε # Map over each pair of lists:
¯ª # Append an empty list to the pair
y` # Push the lists of the pair separately to the stack
à # Pop both, and push a list with values that occurred in both lists
.å # Non-vectorized check if this list is in the earlier triplet of lists
}P # After the map: check if all are truthy
# (after which the result is output implicitly)
```
[Answer]
# [Raku](https://raku.org/), 47 bytes
```
{all cross @^a,@a,:with{$^x∩$^y≡∅|$x|$y}}
```
[Try it online!](https://tio.run/##hY5hCoJAEIWvMsgSuzEIuWohRN6h/8YSSoGiqZSi/gy8StfyIqYbpoXUn7fMvm/evMiNfbMNclh4sG0L4ftwjMMkAdsRaAu0buf0VBAna@oHcXJwL9emvpckK0leVW0iclCKnQdqICILlureTSsLyEGNumDKFPDCGChDoHSFGnKG/Su1EzYaqL@sCcJ7RMcZSJr6kMJnkD5FGxENJ3kfd@WX0ekaNwNjoJzflAzg/8rqv4oO6HeX6YqsMSmFJmPtEw "Perl 6 – Try It Online")
(The ageing version of Perl 6 on TIO does not understand the `≡` operator, added in 2020. I replaced it there with `eqv` for one additional byte.)
This anonymous function takes as input a list of sets in the variable `@^a`/`@a`. It computes the cross product of all of those sets with each other using the anonymous function in braces following `:with`. For each pair, that function returns a truthy value if the intersection (`∩`) of the two sets is identical to (`≡`) one of those sets or to the empty set (`∅`). The final result is a truthy value indicating whether `all` of those pairwise values are truthy.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 88 bytes
```
x=>x.some(a=>x.some(b=>g(a,b)&g(b,a)))
g=(a,b)=>/0,1|1,0/.test(a.map(i=>+b.includes(i)))
```
[Try it online!](https://tio.run/##fU7LboMwELznK3oqa3VjIEmbXMyxP9BjUykGDHLlAMUQUVF/O8XOoySVcvB6d2Z2Zz75geukllUzL8pUDBkbOhZ1VJd7AfzSxSzKgWNMHnOIkRNCZjlzAIv8AMOfEAOfNkI3wOmeVyBZ9BRTWSSqTYUGOW4MtfhqZS3Ay7RHaC14@iqVePsuEgjQa5ts4@BK8USAv@39HL33K8hY6GOEdKVks9sWO2c2Jk7KQpdKUFXmkIE4cAUdsaa9eZj1fYgLXBq0v63jM@YM4@pITAS2W/1XWObYO80tb7cWF/7vztTMAvg81jVuTgI3nRXuxPJ@OLwX7aS8CjBRO@9JEnwx5hc "JavaScript (Node.js) – Try It Online")
Return inversed
[Answer]
# [Factor](https://factorcode.org) + `math.unicode sets.extras`, 52 bytes
```
[ dup '[ _ [ diffs f like and and ] with ∃ ] ∃ ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owS0mttBgTz93K4Xi1JJivdSKkqLEYoXs1KK81BygUGFpal5yarFCbmJJhl5ZKkgLlFOal5mcn5KqUFCUWlJSWVCUmVeiYM3FVc2lAATVCrVQulrBUMFIwVihFsqC0CCyFkONCVwVqnoIzwSvDog6EyTzjfGoh5hohKIe3S5sLoTImYJpcwULJB0wMXQ9EJPxuQXTt8T7FKEXmw8wzTBFsxMkYgZWWbu0tCRN1-KmSbRCSmmBgnq0QrwCkJmZllaskKaQk5mdqpCYlwLGsQrlmSUZCo86moFMMAnRuzQ3sUBBD8JesABCAwA)
Output is inverted: outputs `f` for laminar and `t` for not laminar.
* `∃` alias for `any?` that is 1 byte shorter
* `dup '[ _ [ ... ] with ∃ ] ∃` Is there any pair of sets in the input that is true when `[ ... ]` is applied to them?
* `diffs` A lovely word that takes two sets as inputs and returns three outputs: the set difference between input 1 and input 2, the set difference between input 2 and input 1, and the intersection between input 1 and input 2. This word converts empty sets to `f` except for the intersection.
* `f like` Convert the intersection to `f` if it is empty; leave alone otherwise.
* `and and` Take the logical and of the three results.
[Answer]
# [Haskell](https://www.haskell.org/), ~~68~~ 63 bytes
Unfortunately `\\` is not in `Prelude`, and I couldn't figure out how to write it shorter without the `Data.List` functions (without the import it's ~~51~~ bytes).
(Shaved off 5 bytes by switching to list comprehension from nested `all`)
```
import Data.List
l s=and[a\\b==[]||b\\a==[]||a\\b==a|a<-s,b<-s]
```
[Try it online!](https://tio.run/##dY9Na8MwDIbv/hUitJCAW2iafVCWnXYphG2w3WwfHJrSsMQJscd6yH/PZDsbS5sdbEuvHr@STlJ/FFU1lHXbdAbei7NZv3alMscf6Ukauc5KbUgFOpXqwCTneZoy0fc559JHXpO9fFhpmuMlhuIMux0wtldGCFg9wv4FwoigrCGF1jWBoJJ1qWQXLnWE6lJzFUCoT80XoOCDBWDniBBSy1JZT2/kshQODQFoP82b6TIFQeb9AhSxExPjyzY0pltBwQaCsg0eMS3SZCwjB9RzwNyf5D/UETZzhtsZDCO0YPEvFDuQsuR6AqvSG7zv6P1IuQyxyY5cPTcGqumm42LWZnYK7@8hq81DY9H7XA58@cXN@mdyeovI8A0 "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
iƇⱮFf\€Ƒ
```
[Try it online!](https://tio.run/##y0rNyan8/z/zWPujjevc0mIeNa05NvH/4XbNyP//o7miY3W4oqsNdYx0jGt1QDSIBOJahLiOCUQGSQWIZYJFCUgKwgYrwlAA0mcEV4AwCcU@kIiOKZA017GAqgDz4ErAhhgTcKEOXvdBlaI4Alk52H4k1@iY1cZyxQIA "Jelly – Try It Online")
Relies on the whole family being sorted *descending by length*, incidentally coinciding with how the testcases are displayed.
```
ⱮF For each element of any of the sets,
iƇ filter the family to only sets containing it.
€Ƒ Is every one of those sub-families unchanged by
f\ cumulative intersection?
```
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes
```
fpḟpḟ@ðþF
```
[Try it online!](https://tio.run/##y0rNyan8/z@t4OGO@SDscHjD4X1u/w@3a0b@/x/NFR2rwxVdbahjpGNcqwOiQSQQ1yLEdUwgMkgqQCwTLEpAUhA2WBGGApA@I7gChEko9oFEdEyBpLmOBVQFmAdXAjbEmIALdfC6D6oUxRHIysH2I7lGx6w2lisWAA "Jelly – Try It Online")
*-1 remembering that I already made the link dyadic*
Outputs an empty list iff laminar. If output can't have reversed truthiness, slap a `Ṇ` on the end.
```
ðþ For every pair (dyadically) of sets:
p Take the Cartesian product of
f the intersection and
ḟ the difference one way
p and
ḟ@ the difference the other way.
F Flatten.
```
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
Œcµḟṭif/)P
```
[Try it online!](https://tio.run/##y0rNyan8///opORDWx/umP9w59rMNH3NgP@H2zUj//@P5oqO1eGKrjbUMdIxrtUB0SASiGsR4jomEBkkFSCWCRYlICkIG6wIQwFInxFcAcIkFPtAIjqmQNJcxwKqAsyDKwEbYkzAhTp43QdViuIIZOVg@5Fco2NWG8sVCwA "Jelly – Try It Online")
Direct approach everyone else is using.
```
Œcµ )P For every pair (as a list) of sets:
ṭ Append
ḟ the empty list;
i does that contain
f/ the intersection?
```
[Answer]
# [Scala](http://www.scala-lang.org/), 79 bytes
Port of [@corvus\_192's Rust answer](https://codegolf.stackexchange.com/a/263644/110802) in Scala.
---
Golfed version. [Try it online!](https://tio.run/##jY/NTgMhFIX3PMV1B8mExLYrDU10pQtXXTZdXKYQMQyMgI3259lH0EnsUBMNyU3O4XC/Q2zR4mC63ocEsQjeemtVm4x33HTdW0JpFX/A@LxSiRAvX/IlPKFxoN6TctsId30PB0LIDi3oG7pSr@sxv350abMRy3vvrULHQAxRLA@Rax/QWornQmaxwwB7gWBcUiEWkrzdC4HHY57yayLfGq0pslM5AwDGqEKiuoC56vr0McUzRqYhmjXAmKHXDcwamLPmwq2tqR5RBZFt9j9KA4tLUM2e/ZKqI5WuVyz@6vpT9uq77fTj513mrDw4keET)
```
s=>{s.forall(a=>{s.forall(b=>{var z=a intersect b;z==a||z==b||z==a.diff(a)})})}
```
Ungollfed version. [Try it online!](https://tio.run/##jY/NasMwEITvforpTQIjaJJTwIXm1B56yjHksLYlqiJLrqVCS@Nnd/0HdRRDCwJpP83uzPqCDHWdrmrXBPihEoUzRhZBOyt0VX0Eyo0UT@RfjzIkicvf@k@8kLaQn0Ha0uOxrvGdAP0ppYJifo@jfD/NTadnG85nvsfBOSPJIhvVgBfKNWQMI2QPM1vQfEkBEtoG2fjenuUcWQbC5bKC83VMotRKMeLzxHZ6jFc7pSfvZROYYn16Ias6fEU78EjExhGzht2n2KTY8vSGxui6nq0Gix7z/7mk2N0axd6bFVUsiep4xO6vrL9h76a014svs2z50NAmXfcD)
```
import scala.collection.immutable.HashSet
object Main extends App {
def f(s: Seq[HashSet[Int]]): Boolean = {
s.forall(a => {
s.forall(b => {
a.intersect(b) == a || a.intersect(b) == b || a.intersect(b) == a.diff(a)
})
})
}
assert(f(Seq.empty[HashSet[Int]]))
assert(f(Seq(
HashSet(1, 2, 3),
HashSet(1, 2),
HashSet(1),
HashSet.empty[Int]
)))
assert(f(Seq(
HashSet(1, 2, 3, 4),
HashSet(1, 3),
HashSet(2, 4),
HashSet(1),
HashSet(2),
HashSet(3),
HashSet(4),
HashSet.empty[Int]
)))
assert(!f(Seq(HashSet(1, 2), HashSet(2, 3))))
}
```
[Answer]
# [R](https://www.r-project.org), 64 bytes
```
\(x,`?`=all)?Map(\(A)?Map(\(B)any(?(p=A%in%B),?B%in%A,?!p),x),x)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3HWI0KnQS7BNsE3NyNO19Ews0YjQcYQwnzcS8Sg17jQJbR9XMPFUnTR17JxDDUcdesUBTpwKEIObcYpJL08jJLC7R0NRU4IIywYShjpGOsaYOjA1jQWlNTU1M1TomCPVY9MJETAhqhmlAiMGNIKAVZocRhlZMV-DxCUyNjimUZa5jgaYfLgMyAN0EuCsIOhhrQOmQEURIBuH0MXZD4Z5E87qOGVADJJksWAChAQ)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
⬤θ⬤θ№⟦ιλυ⟧⁻ι⁻ιλ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxJ0ejUEcBSjnnlwLFojN1FHJ0FEpjdRR8M/NKizUykRg5mmBg/f9/dHS0oY6RjrGOSawOkGUMJI0gbBALiEEiIH5sbOx/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for laminar, nothing if not. Explanation: Charcoal has no set intersection function, otherwise this would be a direct port of @mousetail's latest Python answer, but emulating list intersection using list difference does mean I get to use the predefined variable for an empty list.
```
θ Input list
⬤ All elements satisfy
θ Input list
⬤ All elements satisfy
ι Outer element
λ Inner element
υ Empty list
№⟦ ⟧ Includes
ι Outer element
⁻ List difference
ι Outer element
⁻ List difference
λ Inner element
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
.Am}@Fd+d.{Y*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72koLIkY8GCpaUlaboWa_Ucc2sd3FK0U_SqI7UgYlCpBTd1o6sNdYx0jHVManWALGMgaQRhg1hADBIB8otTSzQ0YyG6AA)
### Explanation
```
.Am}@Fd+d.{Y*QQ # implicitly add QQ
# implicitly assign Q = eval(input())
*QQ # cartesian product of Q and Q
m # map over lambda d
@Fd # intersection of the elements of d
} # is in
+d.{Y # d plus the empty set
.A # return whether all elements are true
```
[Answer]
# [Arturo](https://arturo-lang.io), 56 bytes
```
$->x[some? x'a->some? x'b->¬∨∨a=a--b[]=a--b[]=b--a]
```
[Try it!](http://arturo-lang.io/playground?bAgc1W)
Inverts the output; `false` for laminar and `true` for not laminar.
```
$->x[ ; a function taking a set of sets x
some? x'a-> ; is there some set a in x that
some? x'b-> ; is there some set b in x that
[]=b--a ; the empty set equals b diff a
∨ ; or
[]=a--b ; the empty set equals a diff b
∨ ; or
a=a--b ; a diff b is unchanged
¬ ; logical not (we have to do it this way to accommodate empty input)
] ; end function
```
[Answer]
# [C (GCC)](https://gcc.gnu.org), ~~199~~ 197 bytes
* *-1 bytes thanks to [@Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)*
* *-1 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
#define T int
#define A(p,z)*v){T b=0,i=0;for(;y;++i)b|=p;return b?z:!z;}
#define y v[i]
C(T x,T A(x==y,1)P(T z,T*s,T A(z-C(y,s),1)X(T*a,T*A(P(1,a,y)&P(1,y,a)&(P(0,a,y)|P(0,y,a)),0)f(T*A(!X(y,v),1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVNdTttAEFbVp_gUQxDRrnGQQ6FFOEmFuAAPfkCKUORs1rDUsS3v2uSHXKEX6AsvfazUS_QQ5TSdsR0nAoose3e__ebb-WbWP36JNMo1veNbIX6P2t0wldlMaa0K2b55-pmbsHv298_-VIYqluCDio21WV2w1Flyu-ArHyYD11ED1wuTjHkL7_BQ8cnjIPUyafIshsnX5fne0ls3sQsoRurGumQ-zB0fpeaDwcLp8SsElo5v6xJcdi_ZwtEcN66Zbwe4ccGuWM8JnAXv0GThBLyDkFtCjzQhiDsuDxmx965RoSCFyszzx-_7KhZRPpXQL6QwSTa0tojQZqqSXUQl2mQymA0taz-PMX3wLSvXKr6FOJhJnQZCAkZ5lmXkLI0Cg0FmkUraBX9o1fHQSbC2AZ7X77MtlhsHRBJrA1UyfX8InYLDymrhHvT70F61PauFhQUW5CYBZWAAxdFE3qqYcY_WewTIeIrLMnITaiuDoS0VAsOO7PI4ws0BDtAJ6-2Ja1rXrUPMs9ZoDi2Re7wBYMgs2HaV8tgk4zRBXGasNlEPZtiYIXqKicfyAYw9Ko60WkrG4RB6N5U9Rsp0h0D1N9se0E0iRylel034iO7OC4FG4Z4U7vs7FBK5L0VKldE9CRXVjCLXpffablqaJaFZQPWtcp8jT9wFGQh03nptUksqdAOAHQXa1Ok2KIU-3KlIAtMiiEPWPpgeCKx-Z46v4NSebq9qILVsDoMtUBZQ4DmU-6uyI87JSkvULQwZcXnZTXxwoFAazPT8HK9AVNIRPBKRDDLG60q0ZKQlNMe7Vd2Il-b6bjwJxDdWuqvOe9vnjtJqw-oOtwJz3tR9Xf2WT88feLdn9eAYPoELNNLXxaeBT-qNLYFmJ29R3GZekV4QCDpuCLtKO1QCTvH7Bc5qQrVqKG5NezfBd9PbUN3_uTndUaTV53K7Ktk_)
Takes input as a double pointer to int (`int **`) which is zero terminated on both levels (hence `0` cannot be used as an element).
Note that the solution is in C, while the full snippet is in C++ because I used vectors to store the data after parsing.
---
[ungolfed solution](https://ato.pxeger.com/run?1=nVK7asMwFIVu1ldcJxAkcCDpVOwk0D1j6FJKkW25CGzZWJJJXPwlXbJ0LHTo1_RrKsWPOhQayCB0X5xzro7ePqIi1dKe55co-nyczJOClRmXklds8nR81yqZ333ffE25iFIdM1hVLFJ5uUHTmCVcMHjAOwJSxb7fdla7DRqa99strjzYe1B4UBNI8hIw1SqHvQ8VgVfgCeCCQMmULgXUATR97NYBQoplRUqV4VWHggmaMTD4YZ6nEOVCUS4kNoFUsIOZoWnjk6aZxUdOJ-FgVMB6be8lQc2_yFKHkik8xpLLc2x5O4DblmF2Bz0mMW0PFpd4qFD8Kq4rqPR-4LCo9nnOWeiJ5NegsDUIOdYht5NJPQjN7Az6QugBbQt4tM0wNqqdJglBjtP5uwiQ06A-WwYXNkj-6B_baxhdu6MN-_doP2_3h4_d_QM) (in C++)
[Answer]
# [Julia 1.0](http://julialang.org/), 43 bytes
```
~x=all(A⊆B||B⊆A||A∩B==[] for A=x,B=x)
```
[Try it online!](https://tio.run/##hZHNagMhEMfP9SkmBEKEYSFp2uQi7C7kCdrb4sGDISmWhNVQD8seS8ib5LXyIlt17X7Q0oLOh/Nz/KtvZ3UQC9s0tWVCqXl2v37mVZU7l1VVdr/ccsYKDrtjCRmzmDNLmylsrXg/KUlSvT9@QP0izbwgD8EtcImPnGKfDpI@5JS4QabwKrXRxJRnsz9IDQxco4IjOBt7YWjirJucY1fAVVsaID5a/cb4WhsH6ifhdy47ou81PtIv4ZOza9xEJGSe4WQnlO7vEI/1u/4RjX9LjuxI1ogPigb68LnVkwqtZWnAfywkdffGFGazuDhJ6m/VtPkC "Julia 1.0 – Try It Online")
-2 bytes thanks to MarcMush: square brackets aren't needed for an array comprehension that is passed to a function
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~45~~ 43 bytes
```
->a{a.all?{|x|a.all?{|y|[[],x,y].any?x&y}}}
```
[Try it online!](https://tio.run/##KypNqvyfpmD7X9cusTpRLzEnx766pqIGxqqsiY6O1anQqYzVS8yrtK9Qq6ytrf2vrJCTmJuZl1hkxVVQWlKskKanER2riWBHG@oY6RjH6oBoEAnEsZjyOiYQFUgqQSwTPEpBSiBssGKcCkHmGMEVIkzG6g6QjI4pkDTXsYCqBPNASrmUFfLySxDeRdULtsWYSK/pEOUxqBYUV2PTBnYwkvN1zIDK/gMA "Ruby – Try It Online")
] |
[Question]
[
Write a function (or a whole program) that outputs (or prints) the following ASCII art:
### Output:
```
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
12345678987654321
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 3 2 1
1 2 3 2 1
1 2 1
1
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins!
#### Allowed:
* Any number of **trailing spaces** on each line
* An equal number of *additional* **leading spaces** on each line (meaning of additional: without counting the already mandatory leading spaces shown in the output above)
* *Additional* **newlines** at the beginning and/or at the end. These additional lines can contain any number of spaces
---
I'm late to the party, but as some of you may have recognized, this challenge is inspired by the bugged output in [*Carcigenicate*'s answer in Clojure](https://codegolf.stackexchange.com/a/109197/52210) for the [Print this diamond](https://codegolf.stackexchange.com/questions/8696/print-this-diamond) challenge.
This answer also led to a chain of 3 challenges from [*Kevin Cruijssen*](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) : [It was just a bug](https://codegolf.stackexchange.com/questions/129523/it-was-just-a-bug), [It was just an input-bug](https://codegolf.stackexchange.com/questions/129925/it-was-just-an-input-bug), and [I done did made a spaceship maw!](https://codegolf.stackexchange.com/questions/171679/i-done-did-made-a-spaceship-maw)
But i wanted to see something more "pulsar-y", as this is what i find most beautiful in the original answer!
I hope you will generate beautifully bugged ASCII arts while doing this challenge :)
[Answer]
# [Python 3](https://docs.python.org/3.8/), 80 bytes
```
i=8
while i+9:k=abs(i);print(f"{(' '*k).join(str((10**(9-k)//9)**2)):^41}");i-=1
```
[Try it online!](https://tio.run/##BcHdCkAwFADge08hN8458jNcGO1VFEWOadasJHn2@T77@O00TWddCKy66N74WGLOZK/VNF/AOFjHxsOavJDGKWks9pMNXN4BiIoIZK6xLCUS1Yj92IovwYFzJUL4AQ "Python 3.8 (pre-release) – Try It Online")
Uses the classic arithmetic trick where, for example,
```
(10**9//9)**2 == 111111111**2 == 12345678987654321
```
## [Python 3](https://docs.python.org/3.8/), 79 bytes
```
f=lambda k=8,c=1:(s:=[f"{(' '*k).join(str(c*c)):^41}"])[k:]or s+f(k-1,c*10+1)+s
```
[Try it online!](https://tio.run/##FchBDsIgEADAu6/Y9NJdqEaih4aElzQ1qSgRaRcCXIzx7ahznPSqj8inMeXWnFmX7XpbIJhxsEZpLNpMrntjD70IdHhGz1hqRisskb6c1aebaQp6jhmKdBj2arBCHaUiWZr77er5Dp7BIekdpOy54v@ofQE "Python 3.8 (pre-release) – Try It Online")
Recursive function that generates a list of lines when called with no inputs. The idea is to start with the center line, then repeatedly sandwich what we have between two copies of a new line.
## [Python 3](https://docs.python.org/3.8/), 79 bytes
```
f=lambda p=8*' ',c=1:(s:=f"{p.join(str(c*c)):^41}\n")+(p and f(p[1:],c*10+1)+s)
```
[Try it online!](https://tio.run/##BcFBCoMwEADArwQv7iYiXepBAnmJWkgjoYquS5JLKb49nZFv@Vz8HCXVGt3hz/fqlbhRt6rtgiML2brY/KTfr40hlwRBB0T7GuieuUEDojyvKoJMZJcuaHoYQpOxStq4QATE@gc "Python 3.8 (pre-release) – Try It Online")
Recursive function that generates the whole multiline string, with a trailing newline, when called with no input.
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 14 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
9Rƒıṅ8_ṣjⱮ;ⱮØC
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPTlSJUM2JTkyJUM0JUIxJUUxJUI5JTg1OF8lRTElQjklQTNqJUUyJUIxJUFFJTNCJUUyJUIxJUFFJUMzJTk4QyZmb290ZXI9JmlucHV0PSZmbGFncz0=)
~~Seems like the compressed list part (`¿qJŒḣ“ɲþẇɦɠ¿i`) could be golfed a bit with a formula, but I couldn't find it.~~
~~I found the formula \$(n-6)(n-5)\$ for the leading spaces.~~
I don't need that any more. Port of Kevin Cruijssen's 05AB1E answer.
*-5 by porting @KevinCruijssen's 05AB1E answer*
#### Explanation
```
9Rƒıṅ8_ṣjⱮ;ⱮØC # Full program
9Rƒ # Prefixes of [1..9]
ı ; # Map over:
ṅ8_ # 8 - iteration index
ṣj # Join by that many spaces
Ɱ # Palindromise
Ɱ # Palindromise
ØC # Center
# Implicit output
```
Old:
```
9RⱮı65d-pṣnRⱮn9_ṣj+ # Full program
9RⱮı # Map over [1,2,...,8,9,8,...,2,1]:
65d-pṣ # Push (n-6) * (n-5) spaces
nRⱮ # Push [1,2,...,n,...2,1]
n9_ṣj # Join by (9-n) spaces
+ # Prepend the leading spaces
# Implicit output, joined on newlines
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes
```
9ƛɾ9n-Ij;∞øṗ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCI5xpvJvjluLUlqO+KInsO44bmXIiwiIiwiIl0=)
Uses the strangely specific `øṗ` (Flip Brackets Vertical Palindromise, Center, Join on Newlines) builtin.
```
9ƛ ; for n in [1...9]:
ɾ9n-Ij join [1..n] by 9-n spaces
∞ palindromize the list
øṗ palindromize and center all the strings and join by \n
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~71~~ 69 bytes
Function outputting an array of lines. A synthesis of my old answer with [Level River St](https://codegolf.stackexchange.com/users/15599/level-river-st)'s [answer](https://codegolf.stackexchange.com/a/263151/52194) as per their suggestions.
-2 bytes by switching to Ruby 2.7+ (TIO is on 2.5.5)
```
->{(-8..8).map{([*1...x=9-k=_1.abs,*x.downto(1)]*(' '*k)).center 41}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsHiNNuYpaUlaboWN1117ao1dC309Cw09XITC6o1orUM9fT0KmwtdbNt4w31EpOKdbQq9FLyy_NK8jUMNWO1NNQV1LWyNTX1klPzSlKLFEwMa2shhq0uKC0pVkjTS07MyYGILFgAoQE)
# [Ruby](https://www.ruby-lang.org/), 77 bytes
Recursion, ahoy! Function outputting an array of lines.
```
f=->x=1{s=([*1...x,*x.downto(1)]*(' '*(9-x))).center 41;x<9?[s,*f[x+1],s]: s}
```
[Try it online!](https://tio.run/##BcFLDoMgEADQq7ATRphkEjdqsQchLOqHldHGgThN07PT964yf2pN3k3i6cteByBEFAuC63kf@dRkIuhGNaB7J8YYXLYjb5fqaJRH/wxsIQVpKVqOg@JffZfMKuHy2vf6Bw "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
E⁹⪫⮌…·¹⊕ι× ⁻⁸ι‖O¬
```
[Try it online!](https://tio.run/##DYxBCsIwEEX3nmLoagJx4U7tCRSKErxAiF8dSKclSXMqT@HFYt7yPXjh41NYfGztnkQLT37lk6XrIsoOFSmDLxrilqXCeX2DD5a6SZihBU8WYyw9ZEbmgQZLk@iW@Wiph864c3hFhHLrs9jv59/XjK21fY1/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
E⁹⪫⮌…·¹⊕ι× ⁻⁸ι
```
For `n` from `1` to `9`, output the numbers from `n` down to `1` joined with `9-n` spaces, but doing everything `0`-indexed.
```
‖O¬
```
Reflect both left and down to complete the diamond gone beautifully wrong.
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-l`, 23 bytes
```
QPZJ RZJ:R\,_JsX9-_M\,9
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSbo5S7IKlpSVpuhbbAwOivBSCorysgmJ04r2KIyx1431jdCwhslBFC6A0AA)
### Explanation
```
QPZJ RZJ:R\,_JsX9-_M\,9
\,9 ; Range from 1 to 9, inclusive
M ; Map this function to each:
\,_ ; Range from 1 to fn arg, inclusive
R ; Reversed
J ; Join on this string:
sX ; A number of spaces equal to
9-_ ; 9 minus fn arg
ZJ: ; Transpose list of strings, filling gaps with spaces
R ; Reverse list of lines
ZJ ; Transpose again
QP ; Quad-palindromize
; Autoprint, joining on newlines (-l flag)
```
Here's the step-by-step evolution, using size 5 instead of 9 and showing spaces using periods:
```
\,5
1
2
3
4
5
R\,_JsX5-_M
1
2...1
3..2..1
4.3.2.1
54321
ZJ:
12345
....4
...33
..2.2
.1.21
.....
..11.
R
..11.
.....
.1.21
..2.2
...33
....4
12345
ZJ
......1
..1...2
1..2..3
1.2.3.4
..12345
QP
......1......
..1...2...1..
1..2..3..2..1
1.2.3.4.3.2.1
..123454321..
1.2.3.4.3.2.1
1..2..3..2..1
..1...2...1..
......1......
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
9Rjạ9⁶xƊƊ€Uz⁶ZUŒBŒḄY
```
A full program that prints the diamond.
**[Try it online!](https://tio.run/##y0rNyan8/98yKOvhroWWjxq3VRzrOtb1qGlNaBWQExV6dJLT0UkPd7RE/v8PAA "Jelly – Try It Online")**
### How?
```
9Rjạ9⁶xƊƊ€Uz⁶ZUŒBŒḄY - Main Link: no arguments
9 - 9
€ - for each {i in [1..9]}:
Ɗ - last three links as a monad f(i):
R - range -> [1..i]
Ɗ - last three links as a monad f(i):
ạ9 - absolute difference with 9 -> 9-i
⁶ - space character
x - repeat -> ' '*(9-i)
j - join -> e.g. "1 2 3"
U - reverse each
z⁶ - transpose with space character as filler
Z - transpose
U - reverse each
ŒB - bounce each
ŒḄ - bounce
Y - join with newline characters
- implicit, smashing print
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 83 bytes
Updated per suggestion from @ValueInk
```
(-8..8).map{|i|puts (((-8+c=i.abs)..8-c).map{|j|"#{9-c-j.abs}"}*(" "*c)).center 41}
```
[Try it online!](https://tio.run/##KypNqvz/X0PXQk/PQlMvN7GguiazpqC0pFhBQwMoqp1sm6mXmFSsCZTWTYYqyKpRUq621E3WzQJJ1SrVamkoKShpJWtq6iWn5pWkFimYGNb@/w8A "Ruby – Try It Online")
# [Ruby](https://www.ruby-lang.org/), 86 bytes
```
(-8..8).map{|i|puts (((-8+c=i.abs)..8-c).map{|j|(9-c-j.abs).to_s}*(" "*c)).center(41)}
```
[Try it online!](https://tio.run/##KypNqvz/X0PXQk/PQlMvN7GguiazpqC0pFhBQwMoqp1sm6mXmFSsCZTWTYYqyKrRsNRN1s2CSJTkxxfXamkoKShpJWtq6iWn5pWkFmmYGGrW/v8PAA "Ruby – Try It Online")
[Answer]
# Swift, 156 bytes
`String(repeating:count)` is nice for practical code, but so long for code golf...
```
let f={(1...$0)+(1..<$0).reversed()}
f(9).map{n in print(.init(repeating:" ",count:(n-6)*(n-5))+f(n).map{"\($0)"+String(repeating:" ",count:9-n)}.joined())}
```
[Try it on SwiftFiddle!](https://swiftfiddle.com/ttgutsx66vdrfldkcc6dz3r2yy)
Port of @TheThonnu's various answers. `f` is a shorthand for counting from 1 to n and back. I put the joining spaces inside the `map` callback rather than passing them to `joined` because the latter would involve an extra argument label (`joined(separator:)`).
[Answer]
# [Scala](https://www.scala-lang.org/), 214 bytes
Port of [@Level River St's Ruby answer](https://codegolf.stackexchange.com/a/263151/110802) in Scala.
---
Golfed version. [Try it online!](https://tio.run/##pcxBDoIwEIXhvadoWM2IrUhc4AISD@DKE5SxwWIpjZ0YE8LZK8oR3L3F/71I2umUxrY3xOIizJuNv0VxDmECWQkeRYVq0GGydfPSTlBtlW7jJjytZ@cBMpFtoSwkLHlOyCNUknA1fd3ASZLsvwQVj1deWDer4bGunyZUzviO7/sS839uUEVnyUCxOx4Q5zmlDw)
```
object M extends App{(-8 to 8).map{i=>val c=i.abs
println((" "*(20-((-8+c)to(8-c)).map{j=>(9-c-j.abs).toString}.mkString(" "*c).length/2)+((-8+c)to(8-c)).map{j=>(9-c-j.abs).toString}.mkString(" "*c)).slice(0,41))}}
```
Ungolfed version. [Try it online!](https://tio.run/##XZA/T8MwFMT3fIpTJxva8EcMISJIjAxMFRNicB03dXCcKLZAUOWzh@c4garDk5K7n8/v7KQwYhzbXa2kx4vQFscEKNUeDf0w0Vcux1Pfi@@3re@1rd55jlerPYqJBNgmg2@R8bQRHY7QKB4nA/gUBpJAnYqdO9GMtopkFo5eQvJwnmXY0OeSUv@n0BX3waOpQxBPfRt3mYEhbT6iwFZY4YJiZqcj0RvLpLJe9Szcu8bdDY/@kMSZC88Q9Y1ha3zp0h9yPFvPF/GvdujRiXKrf0KViaQFXWqUrfxhQvSeLcRDgWuO@AbKOIV50wW4uuWcnsLRnDkUesJMGw/JOP4C)
```
object Main {
def main(args: Array[String]): Unit = {
(-8 to 8).map { i =>
val c = i.abs
val line = ((-8 + c) to (8 - c)).map { j =>
(9 - c - j.abs).toString
}.mkString(" " * c)
println(center(line, 41))
}
}
def center(s: String, width: Int): String = {
val padSize = width - s.length
if(padSize <= 0) s
else (" " * (padSize/2)) + s + (" " * (padSize - padSize/2))
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
9Lηε8N-ð×ýû}û.c
```
[Try it online.](https://tio.run/##ASAA3/9vc2FiaWX//zlMzrfOtThOLcOww5fDvcO7fcO7LmP//w)
**Explanation:**
```
9L # Push a list in the range [1,9]
η # Pop and push its prefixes: [[1],[1,2],[1,2,3],...]
ε # Map over each prefix:
8N- # Push 8 minus the 0-based map index
ð× # Pop and push a string of that many spaces
ý # Join the list with those spaces (or empty string for N=8) as delimiter
û # Palindromize this string
}û # After the map: palindromize the list of lines as well
.c # Join the list by newlines,
# and add leading spaces where necessary to centralize the lines
# (after which the result is output implicitly)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes
```
9ɾKėƛ÷$8εIj∞;∞øĊ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJqIiwiIiwiOcm+S8SXxpvDtyQ4zrVJauKInjviiJ7DuMSKIiwiIiwiIl0=)
Port of ~~my Thunno 2 answer~~ Kevin Cruijssen's 05AB1E answer.
*-1 thanks to @lyxal*
*-3 by porting @KevinCruijssen's 05AB1E answer*
#### Explanation
```
9ɾKėƛ÷$8εIj∞;∞øĊ # Full program
9ɾK # Prefixes of [1..9]
ėƛ ; # Enumerate and map over:
÷$8ε # Absolute difference between 8 and the iteration index
Ij # Join by that many spaces
∞ # Palindromise
∞ # Palindromise
øĊ # Center
# Implicit output
```
Old:
```
9ɾ∞ƛ65f-ΠInɾ∞n9εIj+ # Full program
9ɾ∞ƛ # Map over [1,2,...,8,9,8,...,2,1]:
65f-ΠI # Push (n-6) * (n-5) spaces
nɾ∞ # Push [1,2,...,n,...2,1]
n9εIj # Join by (9-n) spaces
+ # Prepend the leading spaces
# Implicit output, joined on newlines
```
[Answer]
# [Perl 5](https://www.perl.org/), 65 bytes
```
$a=-1-abs,print map/\D|0/?$":$_,map$a+10+abs()/$a,-20..20for-8..8
```
[Try it online!](https://tio.run/##K0gtyjH9/18l0VbXUDcxqVinoCgzr0QhN7FAP8alxkDfXkXJSiVeB8hXSdQ2NNAGKtHQ1FdJ1NE1MtDTMzJIyy/StdDTs/j//19@QUlmfl7xf90cAA "Perl 5 – Try It Online")
I'd count it `63+1` (instead of `65`), the `+1` for `-E` and `say` instead of `print`, can't figure out how to get it in TIO which also doesn't add 1 for `-l` switch. But it beats direct competitors anyway :), it's strange nobody used this strategy.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 102 bytes
A full program.
```
for(n=17;n--;print(s))for(q=n<9?n:16-n,x=9-q,i=s=''.padEnd(20-q*x);~q;)s+=`${++i>q?1+q--:i}`.padEnd(x)
```
[Try it online!](https://tio.run/##NcrBCsIwDADQnxHW2EWsB3WrcSf/Y8UhxEPWtGMURH@94sHr4z3DGvI9cVxwPdf6mJMRcicviD4mlsVkgJ8qyaUbpHdHlLZQh9oyZWqaXQzTTSZz2KNuC/iPesiWxs3LWr7q4Kwi9vwe/7FArV8 "JavaScript (V8) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), 116 bytes
*-1 thanks to [@c--](https://codegolf.stackexchange.com/users/112488/c)*
```
q;x;i;main(n){for(n=17;n--;i=!puts(""))for(q=n<9?n:16-n,x=9-q;~q;q-=i>q)printf("%*d",i>1?x:x+12-q*x+q,++i>q?1+q:i);}
```
[Try it online!](https://tio.run/##FcpBCsIwEADAtxgQkiZ7iAel3aZ5S4mkLOjabSsGRJ9u1PNMgimlWgULEl5HYs3mmW@L5uBPyABIYTfft1UrZcwfJHDfRu78EdiV0ILgW1Ag0CBmXoi3rNW@OStHg4@lK9YfQJpixVn7O9Fb6cjgq9ZPypdxWis8vg "C (gcc) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 107 bytes
```
R=range
for n in[*R(1,9),*R(9,0,-1)]:print((n-6)*(n-5)*' '+((9-n)*' ').join(map(str,[*R(1,n),*R(n,0,-1)])))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8i2KDEvPZUrLb9IIU8hMy9aK0jDUMdSUwdIW@oY6OgaasZaFRRl5pVoaOTpmmlqAUlTTS11BXVtDQ1L3TwwU1MvKz8zTyM3sUCjuKRIB2JGHtiMPKgZmpqa//8DAA "Python 3 – Try It Online")
Port of my Thunno 2 answer.
*-5 thanks to @Neil*
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 60 bytes
```
9*
$`;$'¶
v`( *;)( *)
$.1$2
P`.+
%`^.
$^$<'
L$`9
$>`$^$`
```
[Try it online!](https://tio.run/##K0otycxLNPz/n8tSS4FLgUslwVpF/dA2rrIEDQUta00gocmlomeoYsQVkKCnzaWaEKfHpRKnYqPO5aOSYMmlYpcA5CX8/w8A "Retina – Try It Online") Explanation:
```
9*
```
Insert 9 spaces.
```
$`;$'¶
```
Generate a `9×9` square of spaces, but with `;`s on the main diagonal.
```
v`( *;)( *)
$.1$2
```
Use the spaces before the `;` to generate the numbers from `n` down to `1` on the `n`th row, spaced using the spaces after the `;`.
```
P`.+
%`^.
$^$<'
```
Reflect horizontally.
```
L$`9
$>`$^$`
```
Reflect vertically (actually around the central `9` but it comes to the same thing).
92 bytes in [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d):
```
9$*
$`;$'¶
(?=( *;)( *)).
$.1$2
.+
$&12$*
(.(.{20})).*
$2$1
%20O^$`.
¶.+¶$
$&$`
9>O^$`
```
[Try it online!](https://tio.run/##FYqxDYQwEATzrcLBAraRTvgyhIAS6ACZgIDkgxfZ69tyAW7MmGSCmfme9/U5SsFIb2DAOLHLCXadrfGTq3BOQAlUSA@2Qd/TipWfDv8aPagMaHTYdkYBcpI@J9aXEePy2lIe "Retina 0.8.2 – Try It Online") Explanation:
```
9$*
```
Insert 9 spaces.
```
$`;$'¶
```
Generate a `9×9` square of spaces, but with `;`s on the main diagonal.
```
(?=( *;)( *)).
$.1$2
```
Use the spaces before the `;` to generate the numbers from `n` down to `1` on the `n`th row, spaced using the spaces after the `;`.
```
.+
$&12$*
(.(.{20})).*
$2$1
%20O^$`.
```
Reflect horizontally by prefixing each line with a copy of the 20 characters after the first and then reversing those 20 characters.
```
¶.+¶$
$&$`
9>O^$`
```
Reflect vertically by duplicating all the lines except the last and then reversing only the duplicates.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
9Lûε65S-Pð×yLûy9αð×ý«
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f0ufw7nNbzUyDdQMObzg8vRLIrbQ8txHEPrz30Or/tYd2/wcA "05AB1E – Try It Online")
Port of my Thunno 2 answer. Unfortunately 05AB1E doesn't have the "push n spaces" built-in that Thunno 2 and Vyxal have.
Output as a list of lines. TIO footer joins by newlines.
*-2 thanks to @KevinCruijssen*
#### Explanation
```
9Lûε65S-Pð×yLûy9αð×ý« # Implicit input
9Lûε # Map over [1,2,...,8,9,8,...,2,1]:
65S-P×J # Push (n-6) * (n-5) spaces
yLû # Push [1,2,...,n,...2,1]
y9αð×ý # Join by (9-n) spaces
« # Prepend the leading spaces
# Implicit output
```
[Answer]
# [Zsh](https://www.zsh.org/), 108 bytes
```
for c ({1..9} {8..1}){w=$[(10**c/9)**2];printf \\n%$[(5-c)*(6-c)]s
for x (${(s::)w})printf %-$[9-$#w/2]s $x}
```
[Try it online!](https://tio.run/##qyrO@P8/Lb9IIVlBo9pQT8@yVqHaQk/PsFazutxWJVrD0EBLK1nfUlNLyyjWuqAoM68kTSEmJk8VKGWqm6yppWEGJGOLuUBGVChoqFRrFFtZaZbXakLVquqqRFvqqiiX6xvFFiuoVNT@/w8A)
Adapted from @Donat's "[bash diamond](https://codegolf.stackexchange.com/a/263045/15940)" code and my "[spaceship maw](https://codegolf.stackexchange.com/a/216255/15940)" solution.
[Answer]
# [J](http://jsoftware.com/), 45 bytes
```
8({.~#-@+41-:@-#)@dlb@(9&-":1+]-|@i:)@-|@i:@8
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/LTSq9eqUdR20TQx1rRx0lTUdUnKSHDQs1XSVrAy1Y3VrHDKtNB3AlIPFf02u1OSMfIU0dfX/AA "J – Try It Online")
Meh.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 98 bytes
```
j;main(z,x){for(;z<10;putchar(x>20?10:x%z|(x=58-z-abs(x/z))<49?32:x))x=j%43-21,z=abs(j++/43-8)+1;}
```
[Try it online!](https://tio.run/##FcntCoMgFADQpwnuRSW1Bi1zPosT9iFsjVZwubVnt/bzcJK6p1RKdq/4fANLwvU2TuB4MNp9ljk94gR0sToY3VPFG5A/dYpVvH6BakYc2nNobE@I5HPVNsoayf7fWYj6cIfCuF8pOw "C (gcc) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 98 bytes
```
i,c=8;main(j){for(;--i/j?i=j=9-abs(c--):1;)printf("%*c",i-j?j-10:11*i-i*i-31,i-j?48+j-abs(i):10);}
```
[Try it online!](https://tio.run/##HcvBCoMwEEXRfxEKifWhQ11oQvBb7IDlDWhF3ZV@exQXd3PhKD6qObPS1MV55OLM/6bv5iLA2gYmSz3G9@4U8EGiXzcux@SKR6lFRdhgkCaIlASvXnLPtnvazXihxsd/zic "C (gcc) – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 98 bytes
I don't know if it's very polite to answer my own challenge, but here it is!
```
for(z of(z=9,s=(n=1,p="".padEnd(9-z))=>n<z?n+p+s(n+1,p)+p+n:z)())print("".padEnd((6-z)*(5-z))+s())
```
[Try it online!](https://tio.run/##RcsxDoMwDEbhqyCm3wSQGFoVhMvEQaIiJDoYK4kYfPmQTt3e8L6vv3z8hENTd71y3s8Aq84dxmMbGcJDq1zXvfptlQ1jZ0T8ltkWceoixJWBSspkBCINhyT8AZ5FNHj8XNmJcr4B "JavaScript (V8) – Try It Online")
---
This is the combined works of [*Donat*'s recent Javascript answer to the challenge "Print this diamond"](https://codegolf.stackexchange.com/a/263191/116582)
and [*The Thonnu*'s formula](https://codegolf.stackexchange.com/a/263139/116582): **(n−6)(n−5) for the leading spaces**.
[*@Donat*](https://codegolf.stackexchange.com/users/95987/donat), don't hesitate if you want to post this as your own answer, this is mostly your work after all :)
[Answer]
# Vyxal, 278 Bytes
```
»×ẏ∴⁺¢ɽƒ3∴ĿṘ€ȯLdd2)"lY∇λµ≠Ḟw⅛!ḋ₌₁ẊṘ?
‡₄¥D‹Ḣ€ɾȯḟǑLdẇm₁≤ɖ↵$hḭ«€X⇧0A2&/•p[₀‟₃5Ǔ≈Π>ḋṠßĠ-⋏↳ĖOUḃ`∑ß∨(V⋏⋎ṁ7Ż≥×h'D℅p×>¥D↲‛℅ddlʀɾ⌐D%₆₄⁋ŻṘġȧ₅ḣ'ɾp0Ḋ¢lǐ⟨6K⌊∵¶⟨Ḣ,g#;¬‛^4⟨β•qrṠg₅Þf⋎→__↑¢[ẏNcḟ≠H꘍C¼↔Π꘍∧≬ǏḭḞǔṄꜝ⌐ø₇µ`ʁȯ⁋√ÞVe↲ <†∧↔⊍n÷PḂė?ġ¦$₌$e⋎\]↵⇩ṁn€⋏+₀ǒ&Ċ⌐∩ṁṗ½VḃḞβ#WżL∵ṖðǓmẊOur,8‹»`1
23456789`τ
```
Compressed number converted to custom string base.
[Try it online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLCu8OX4bqP4oi04oG6wqLJvcaSM%20KItMS/4bmY4oKsyK9MZGQyKVwibFniiIfOu8K14omg4bied%20KFmyHhuIvigozigoHhuorhuZg/XG7igKHigoTCpUTigLnhuKLigqzJvsiv4bifx5FMZOG6h23igoHiiaTJluKGtSRo4bitwqvigqxY4oenMEEyJi/igKJwW%20KCgOKAn%20KCgzXHk%20KJiM6gPuG4i%20G5oMOfxKAt4ouP4oazxJZPVeG4g2DiiJHDn%20KIqChW4ouP4ouO4bmBN8W74omlw5doJ0TihIVww5c%20wqVE4oay4oCb4oSFZGRsyoDJvuKMkEQl4oKG4oKE4oGLxbvhuZjEocin4oKF4bijJ8m%20cDDhuIrComzHkOKfqDZL4oyK4oi1wrbin6jhuKIsZyM7wqzigJteNOKfqM6y4oCicXLhuaBn4oKFw55m4ouO4oaSX1/ihpHColvhuo9OY%20G4n%20KJoEjqmI1DwrzihpTOoOqYjeKIp%20KJrMeP4bit4biex5ThuYTqnJ3ijJDDuOKCh8K1YMqByK/igYviiJrDnlZl4oayIDzigKDiiKfihpTiio1uw7dQ4biCxJc/xKHCpiTigowkZeKLjlxcXeKGteKHqeG5gW7igqzii48r4oKAx5ImxIrijJDiiKnhuYHhuZfCvVbhuIPhuJ7OsiNXxbxM4oi14bmWw7DHk23huopPdXIsOOKAucK7YDEgXG4yMzQ1Njc4OWDPhCIsIiIsIiJd)
] |
[Question]
[
### About Zeckendorf Representations/Base Fibonacci Numbers
This is a number system which uses Fibonacci numbers as its base. The numbers consist of 0 and 1's and each 1 means that the number contains the corresponding Fibonacci number, and 0 means it does not.
For example, let's convert all natural numbers <=10 to base Fibonacci.
* 1 will become 1, because it is the sum of 1, which is a Fibonacci number,
* 2 will become 10, because it is the sum of 2, which is a Fibonacci number, and it does not need 1, because we already achieved the desired sum.
* 3 will become 100, because it is the sum of 3, which is a Fibonacci number and it does not need 2 or 1 because we already achieved the desired sum.
* 4 will become 101, because it is the sum of [3,1], both of which are Fibonacci numbers.
* 5 will become 1000, because it is the sum of 5, which is a Fibonacci number, and we do not need any of the other numbers.
* 6 will become 1001, because it is the sum of the Fibonacci numbers 5 and 1.
* 7 will become 1010, because it is the sum of the Fibonacci numbers 5 and 2.
* 8 will become 10000, because it is a Fibonacci number.
* 9 will become 10001, because it is the sum of the Fibonacci numbers 8 and 1.
* 10 will become 10010, because it is the sum of the Fibonacci numbers 8 and 2.
Let's convert a random Base Fibonacci number, 10101001010 to decimal:
First we write the corresponding Fibonacci numbers.
Then we compute the sum of the numbers under 1's.
```
1 0 1 0 1 0 0 1 0 1 0
144 89 55 34 21 13 8 5 3 2 1 -> 144+55+21+5+2 = 227.
```
Read more about Base Fibonacci numbers: [link](http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibrep.html), it also has a tool which converts regular integers to base Fibonacci. You can experiment with it.
### Now the Question:
Your task is to take a number in the Zeckendorf Representation, and output its decimal value.
Input is a string which contains only 0 and 1's (although you can take the input in any way you want).
Output one number in decimal.
Test cases: (in the format input->output)
```
1001 -> 6
100101000 -> 73
1000000000 -> 89
1001000000100100010 -> 8432
1010000010001000100001010000 -> 723452
```
This is code-golf, so the shortest answer in bytes wins.
Note: The input will not contain any leading 0's or consecutive 1's.
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), ~~1987~~ 1927 bytes
*-60 bytes due to the realization that linebreaks are optional.*
```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.[B]Switch to plan C if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 3 l.Pickup a passenger going to Narrow Path Park.Pickup a passenger going to Sunny Skies Park.Go to Zoom Zoom:n.Go to Sunny Skies Park:w 2 l.Go to Narrow Path Park:n 1 r 1 r 1 l 1 r.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan B.[C]1 is waiting at Starchild Numerology.1 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 3 l 3 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 4 l.[D]Pickup a passenger going to Addition Alley.Pickup a passenger going to Cyclone.Go to Addition Alley:n 2 r 1 r.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Multiplication Station.Go to Zoom Zoom:n.Go to Narrow Path Park:w 1 l 1 l 1 r.Switch to plan E if no one is waiting.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:e 1 r.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:n 1 r 2 l.Pickup a passenger going to Joyless Park.Go to Joyless Park:n 2 l 1 r 1 r.Go to Addition Alley:w 1 r 2 l 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Addition Alley.Switch to plan D.[E]Go to Addition Alley:w 1 l 1 r 1 l.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:n 1 r.Go to Joyless Park:e 1 r 2 l.Pickup a passenger going to Addition Alley.[F]Switch to plan G if no one is waiting.Pickup a passenger going to Addition Alley.Go to Fueler Up:w 1 l.Go to Addition Alley:n 3 l 1 l.Pickup a passenger going to Addition Alley.Go to Joyless Park:n 1 r 1 r 2 l.Switch to plan F.[G]Go to Addition Alley:w 1 r 2 l 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.
```
[Try it online!](https://tio.run/##tVXJboMwEP2V@QKU7ZRbdqlS06i0lyIOLjFgxbGRMaF8fWowThOHQNKqCGOwx7O8eTNI9EWOxxUHyWHDUwkvYUgCPM6hD1QNUc7OhgS7LAEECUpTzCIsIOKEReWpWcwTcDNcOFrL6XvMzHkY1Xq8qe/mRAZxKZhQxGAGJATGgTMMJIUcEan0thssAqrEjTn9VRmjMOxwdo2E4DlskIzVQ@xahd2MsQLcHcGpFtYWPzjfV48xq1dsQYXeQDmiN22TJ1iEgfgKOHyxayE2dbyZ3z8DC5AEVyIRxIRuYZ3tseCUR4Vzl1AdQcPWD6TVGChX2tCabLfKEmcwoVSR4fEM5lXUo5Imc/9fLF0eVPENdCIaqdTF@@eMSpJQEqBKpUKwnG9y5IoGpsIak7x4vCzeYgxT9IlpSNIYC5NZe1mT6/eRNW/WpB50YPbEC4rTi2o6X6oyYrqOaE5abgx1N6aWPtF11qKYlZ254y38m97d1zZfyQGLA8E5TAXZRsZNe1kD24QVvgtxKxBvaTfg1eNMs3Rq35YZpkroPdEY3Kq44ePgN/LEtNAyfiuipeOt/D9y595iOjnSqu3sx@pc/2rZqQkcj/1eT93lVb/1e98 "Taxi – Try It Online")
Because I don't return to the Taxi Garage at the end, my boss fires me, so it exits with an error.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~28~~ 23 bytes
```
{[+] (1,2,*+*...*)Z*$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzpaO1ZBw1DHSEdLW0tPT09LM0pLJb72f3FipUKahqGBgaFeWk5mgV5yfm6SpjUXQhgIDQywy0EBLo1gAGUZYldlCFMDx1ALUZT/BwA "Perl 6 – Try It Online")
Anonymous codeblock that takes a list of `1`s and `0`s in LSB ordering and returns a number.
### Explanation:
```
{ } # Anonymous codeblock
[+] # The sum of
(1,2,*+*...*) # The infinite Fibonacci sequence starting from 1,2
Z* # Zip multiplied by
$_ # The input list in LSB form
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
T‘ÆḞS
```
A monadic link accepting a list in Little-endian form (i.e. from the LSB at the left to MSB at the right).
**[Try it online!](https://tio.run/##y0rNyan8/z/kUcOMw20Pd8wL/v//f7SBDgQaQjGCh42Gq4wFAA "Jelly – Try It Online")**
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 32 29 28 bytes
```
Fibonacci[Range@Tr[#!]+1].#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y0zKT8vMTk5MzooMS891SGkKFpZMVbbMFZPWe1/WnRQallqUXFqdLWhjoKBjgKEREaGRLDhXBTB2tjY//91C4oy80oA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
a=b=0
for x in input():b+=a+x;a=b-a
print b
```
[Try it online!](https://tio.run/##K6gsycjPM/pfnpGZk6pgaJVakZqspKT0P9E2ydaAKy2/SKFCITMPiApKSzQ0rZK0bRO1K6yBsrqJXAVFmXklCkn/QeqjDXUUDMDIMJYLiYNEghCyHBaEqRUNYZU1RNZpiFsPHjYWp4IMBQA "Python 2 – Try It Online")
Takes input as a list. The update is a shorter version of `a,b=b+x,a+b+x`, which is like the Fibonacci update `a,b=b,a+b` if you ignore `x`.
---
# [Python 2](https://docs.python.org/2/), 45 bytes
```
f=lambda n,a=1,b=1:n and n%10*b+f(n/10,b,a+b)
```
[Try it online!](https://tio.run/##PYvBCgIxEEPvfsVchNYtOPG40I@ZYS1bWMciFfHrq9VqQkJ4kPKs69VOraW4yUUXIQsSETRiNhJbyPbgg07J2REcNMikvj3WvJ0Jc7llq5RctnKvzvsGZux6vc3c19AXfjQWOsOP/DOu/AI "Python 2 – Try It Online")
Takes input as decimal numbers.
[Answer]
# [Haskell](https://www.haskell.org/), 38 bytes
```
f=1:scanl(+)2f
sum.zipWith(*)f.reverse
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P83W0Ko4OTEvR0Nb0yiNK922uDRXryqzIDyzJENDSzNNryi1LLWoOPV/bmJmnm1BUWZeiUp6tKGOARACydj/AA "Haskell – Try It Online")
Takes input as a list of 1s and 0s.
## Explanation
---
```
f=1:scanl(+)2f
```
Makes a list of the Fibonacci numbers sans the first one, in variable `f`.
```
sum.zipWith(*)f.reverse
```
Takes the input list `reverse`s it the multiplies each entry by the corresponding entry in `f`, then `sum`s the results.
# [Haskell](https://www.haskell.org/), 30 bytes
```
f=1:scanl(+)2f
sum.zipWith(*)f
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P83W0Ko4OTEvR0Nb0yiNK922uDRXryqzIDyzJENDSzPtf25iZp5tQVFmXolKerSBjqGOARAaxv4HAA "Haskell – Try It Online")
If we take input in with the least significant bit first we don't need `reverse` so we can save 8 bytes.
[Answer]
# Pyth, 13 bytes
Most of this (8 bytes) is just generating the Fibonacci numbers.
```
s*V_m=+Z|~YZ1
```
[Try it out with this test suite!](http://pyth.herokuapp.com/?code=s%2aV_m%3D%2BZ%7C%7EYZ1&test_suite=1&test_suite_input=1%2C0%2C0%2C1%0A1%2C0%2C0%2C1%2C0%2C1%2C0%2C0%2C0%0A1%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%0A1%2C0%2C0%2C1%2C0%2C0%2C0%2C0%2C0%2C0%2C1%2C0%2C0%2C1%2C0%2C0%2C0%2C1%2C0%0A1%2C0%2C1%2C0%2C0%2C0%2C0%2C0%2C1%2C0%2C0%2C0%2C1%2C0%2C0%2C0%2C1%2C0%2C0%2C0%2C0%2C1%2C0%2C1%2C0%2C0%2C0%2C0&debug=0)
Explanation:
```
s*V_m=+Z|~YZ1QQ Autofill variables
m=+Z|~YZ1Q Generate the first length(input) Fibonacci numbers as follows:
Z Start with Z=0
~YZ And Y=[] (update it to Y=Z, return old Y)
| 1 if Y is [], then replace with 1
+ Sum Z and Y
= Replace Z with sum
m Repeat process
Q once for each element of the input
_ Reverse the order of the Fibonacci numbers
*V Vectorize multiplication
s Sum
```
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~110~~, ~~102~~, ~~96~~, ~~94~~, ~~78~~, 74 bytes
```
([[]]<>((()))){({}()<([({})]({}({})))>)}{}{}({<>{<{}><>({})(<>)}{}<><{}>})
```
[Try it online!](https://tio.run/##HYqxDYBADAPXsTu@j7LIK8VDA0KioI0ye0iwC@tO3t91Pec67kzMaSYKgBWHByiYtbSGWlIZHg2iLh5a//KQ34u2CmbmyK06Pg "Brain-Flak (BrainHack) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~24~~ 14 bytes
```
#.~2+&%&1~#-#\
```
[Try it online!](https://tio.run/##fZFdUoMwEMffOcWOO0Bi0iUJYG2mdTIewAtU9MHRUV98ZhCujkkLA7S1k1mS7P@3H2G/@xuC9AN2NgUJrQUF3nqkzogkTnSHK3zueRQ9PRIEDBSVW3KCxbbkccdW9sGGI5JMFKiJy8GmIqtvmew0kmm8rvmLZVuLNdfpBVDLrhL@09K/XEOB/CUmMtkcsUDBnGvJMYEN5TgQ1iF3zLfHl8lOQZ@plmqWySCdMq9GIF8QInOsJWnNZSIUqv3v9D1rEY8dm1kVL@7tILsqAA7dnifmgFyNn0TDKhF33A/sixzWaRS9v33@gIadL6KPl7vjxY9Yja51PvcNFsZ4UO83M3WxBr3IzUn8tJY@PcasTV6UU5Q@izjf1ZIcXqY2RblIc9X6Pw "J – Try It Online")
Golfed down the 24-byte version that uses the mixed base for Fibonacci.
### How it works
```
#.~2+&%&1~#-#\ Example input: y=1 0 0 1 0
#-#\ Length minus 1-based indices; 4 3 2 1 0
2 ~ Starting from 2, run the following (4,3,2,1,0) times:
+&%&1 Given y, compute 1 + 1 / y
The result is 13/8 8/5 5/3 3/2 2
#.~ Mixed base conversion of y into base above; 2+8=10
```
---
# [J](http://jsoftware.com/), 21 bytes
```
1#.|.*[:+/@(!~#-])\#\
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N9QWa9GTyvaSlvfQUOxTlk3VjNGOea/JpeSnoJ6mq2euoKOQq2VQloxF5efk55CmoKtlQJMiwaQEQvXgymPYiQXV2pyRj5QgSHQYgMFQzQumIRBVDEgjazYEEMhJm2AqpLrPwA "J – Try It Online")
Refined version of [Galen Ivanov's 25-byte solution](https://tio.run/##y/qfVmyrp2CgYKVg8L9GT1tfQU9LuVov2kpbX19POUZRv85ARznmvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagiFQs4GCIRoXTMIgqhiQRlZsiKEQkzZAVcn1HwA).
Uses the diagonal sum of Pascal's triangle, which is equivalent to the sum of binomial coefficients:
\$ F\_n = \sum\limits\_{i=0}^{n} {}\_{n-i}C\_{i} \$
### How it works
```
1#.|.*[:+/@(!~#-])\#\
Example input: 1 0 0 1 0
#\ Generate 1-based index; 1 2 3 4 5
[: \ For each prefix of above... (ex. 1 2 3)
#-] Subtract each element from the length (ex. 2 1 0)
(!~ ) Compute binomial coefficient (ex. 3C0 + 2C1 + 1C2)
+/@ Sum
The result is Fibonacci numbers; 1 2 3 5 8
|.* Multiply with mirrored self; 0 2 0 0 8
1#. Sum; 10
```
---
# [J](http://jsoftware.com/), 24 bytes
```
3 :'y#.~|.(1+%)^:(<#y)2'
```
[Try it online!](https://tio.run/##fZFBboMwEEX3nGJUi2DX7mAbaJpRUlk9QC4QpV1UrapuukYUrk7tBAQmSWUNxvPf/xrwd3@HkH3CjjJQ0BJo8NUXQFnNsPtFbmQqXolvWS1s1osk2b8gBANorLboJE@pEmnHH@iZwitDtdKgJy6Eyby@56ozDG3jdXOKJJ9psiugUd1R@keLN7kGA@nnk7lqcJzQwJxr0XHJGizYQJBjwnE/nojDlqBPqpWeJVmGS@bNSiYiQuaOt6jIXidu/dOJ8OKBBtkdA@CYO4iVTZKP968fMLDzoDkfHs8Hf2F6bK2LeW@ocBUn9WkzU6M16GVhF/5pxT0zeta2KKvJZS4cl7uOyeHL9Kasoph/q/8D "J – Try It Online")
Monadic explicit verb. Generates the mixed base that represents the Fibonacci base, and then feeds into base conversion `#.`.
### How it works
```
y#.~|.(1+%)^:(<#y)2 Explicit verb, input: y = Fibonacci digit array, n = length of y
(1+%) x -> 1 + 1/x
^:(<#y)2 Apply the above 0..n-1 times to 2
The result looks like 2/1, 3/2, 5/3, 8/5, 13/8, ...
|. Reverse
Now, if it is fed into #. on the left, the digit values become
...(8/5 * 5/3 * 3/2 * 2/1), (5/3 * 3/2 * 2/1), (3/2 * 2/1), 2/1, 1
which is ... 8 5 3 2 1 (Yes, it's Fibonacci.)
y#.~ Convert y to a number using Fibonacci base
```
---
## Alternatives
### [J](http://jsoftware.com/), 27 bytes
```
}.@(+#{.3#{.)^:(<:@#)@(,&0)
```
[Try it online!](https://tio.run/##fZFLTsMwEIb3OcUIK42NzcSPhFKrRRYH4AJVYYFAiA3rKCRXDzZJFDstlTV@zP/947H8NdwgFB9wsAUI6CxI8DF06CgnLRof7MXSvXWEOSo2kg0sy56fEIIHJNZ7dJzmtmZ5T@/sow1bgp4EuXAGbMHL5paKXhHUrdfVWJc0TBUXQCX6E/dTh/9yLQbyBykvxdRmoCDmrjwkLbYGfaVGyKiSJrhmXjUnLCF46WiHwurLRLioIdj7nhXP5451dIsXj3aS3SkAjrgj2@gse3/7/AYFBw@q8XA/HvyfyTm1NXFuivAVf@rDLlKTMemV0Sv/MtKcmj1bbap6cakzx/kqU3J6mdxVdVLmagy/ "J – Try It Online")
The idea:
```
1 0 0 1 0 1
-1 +1 +1
------------------
1 1 1 0 1
-1 +1 +1
------------------
2 2 0 1
-2 +2 +2
------------------
4 2 1
-4 +4 +4
------------------
6 5
-6 +6 +6 <- Add an imaginary digit that has value 1
---------------------
11 6
-11+11
---------------------
17 <- the answer
```
### [J](http://jsoftware.com/), 30 bytes
```
0.5<.@+(%:5)%~(-:>:%:5)#.,&0 0
```
[Try it online!](https://tio.run/##fZFNTsMwEIX3OcUIK42NzcR2EkpHLbI4ABeoCgsEQmxYRyG5erBJosRpqazxz7zvjcfyV3@DkH3AgTJQ0BJo8NFrrPboJE@pEmnH7@iRwpah2mgviyR5fkIINriOzlwBlMm8vuWqMwxt43UjXojvidXCZBdAo7qT9FOL/3INBvIHucxVM2CBgiXXouOSNViwkSDHhOO@PREXW4O@Uq30opJluGZerWQiImTueIuK7GUiXFQz7HzPRqZTx3ZxixePNMruFADH3FFsbJK8v31@g4GDB81wuB8O/tv0lNoWy9wY4Sv@1IfdQo3GqJeFXfnnEefM5NnaoqxmlzlznK86JseX6V1ZRWWuRv8L "J – Try It Online")
This one took the most effort to build. Uses the closed-form expression with rounding trick. In the expression, 0th and 1st values are 0 and 1 respectively, so the actual digit power must start with 2.
```
0.5<.@+(%:5)%~(-:>:%:5)#.,&0 0 Tacit verb.
,&0 0 Add two zeroes at the end
(-:>:%:5)#. Convert to a number using base phi (golden ratio)
(%:5)%~ Divide by sqrt(5)
0.5<.@+ Round to nearest integer
```
While the error (`((1-sqrt(5))/2)^n` terms) may build up, it never exceeds 0.5, so the rounding trick works up to infinity. Mathematically:
\$ \max(|error|) = \frac{1}{\sqrt{5}} \sum\limits\_{1}^{\infty} (\frac{1-\sqrt{5}}{2})^{2n} = \frac{1}{\sqrt{5}} \sum\limits\_{0}^{\infty} (\frac{1-\sqrt{5}}{2})^{n} = \frac{\sqrt{5}-1}{2\sqrt{5}} < \frac{1}{2} \$
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~8~~ 6 bytes
```
{î)f*+
```
[Try it online!](https://tio.run/##y00syUjPz0n7/7/68DrNNC3t//@jDXUMgNAwlivaAMKCYmQxZAgRNdRBqEbwUMSA6vDIInhIthiiqDbEQcNVxgIA "MathGolf – Try It Online")
## Explanation
```
{ Start block (foreach in this case)
î) Push loop index (1-based) and increment by 1
f Get fibonacci number of that index
* Multiply with the array value (0 or 1)
+ Add top two elements of stack. This implicitly pops the loop index the first iteration, which makes the addition become 0+a, where a is the top of the stack.
```
Saved 1 byte thanks to JoKing, and another byte thanks to LSB ordering.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ ~~9~~ 8 bytes
```
vyiNÌÅfO
```
[Try it online!](https://tio.run/##yy9OTMpM/f@/rDLT73DP4dY0////DYDAEAjBFAKDBQE "05AB1E – Try It Online")
Explanation:
```
v : For each character in input string (implicit) in LSB order
yi : If the current character is truthy (1)
NÌ : Add 2 to the current index
ÅfO : Add the fibonacci of this number to the stack
```
* *-2 bytes*: Thanks to @KevinCruijssen for pointing out small ways to shorten this code!
* *-1 byte*: Thanks to @JonathanAllan for pointing out LSB order for input!
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 23 bytes
```
0?
;
+`1;(1*);
;1$1;1
1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w38Cey5pLO8HQWsNQS9Oay9pQxdDakMvw/39DAwMgDSSA0MAAxIICiCAYQFmGBgA "Retina 0.8.2 – Try It Online") Link includes the faster test cases. Explanation:
```
0?
;
```
Insert separators everywhere and delete any zeros. For example, `1001` becomes `;1;;;1;`.
```
+`1;(1*);
;1$1;1
```
Repeatedly replace each `1` with a `1` in each of the next two places, as the sum of their values equals the value of the original `1`. `1`s therefore migrate and accumulate until they reach the last two places, which (due to the newly added separator) now both have value `1`.
```
1
```
Count the `1`s.
[Answer]
# [Python 3](https://docs.python.org/3/), 63 bytes
```
a=b=n=1
for i in input()[::-1]:n+=b*int(i);a,b=b,a+b
print(n-1)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9E2yTbP1pArLb9IIVMhMw@ICkpLNDSjrax0DWOt8rRtk7Qy80o0MjWtE3WSbJN0ErWTuAqKQEJ5uoaa//8bGhgAEQhAWYYGAA "Python 3 – Try It Online")
Takes input through STDIN as a string.
[Answer]
# [Red](http://www.red-lang.org), 142, 126 106 bytes
```
func[a][b: copy[1 1]reverse a s: 0 n: 1
until[s: b/1 * a/:n + s insert b b/1 + b/2(n: n + 1)> length? a]s]
```
[Try it online!](https://tio.run/##bY3BCsIwDIbve4r/qO6w1WMP@g5eSw7dFmthxNF2gk9fowiiyEcS8v2BJJ7qiSdHTbD1vMroPLnBYrwud2dgKPGNU2Z4ZIseYmGaVUqcne5DZ7CD76ygRUaUzKlgePlW@36j98/MbA@YWUK5HOEpU11SlIIA/dErhppf8y7lb/bh2@mk@gA "Red – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->n{a,b=0,1;n.digits.sum{|x|x*b=a+a=b}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOlEnydZAx9A6Ty8lMz2zpFivuDS3uqaipkIryTZRO9E2qbb2f7ShgYGhDogAQgMDEAsKIIJgAGUZgsQMYSJwDNVqEKuXm1gAMr9AIbpCJy26Ija29j8A "Ruby – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
çéC◘0â
```
[Run and debug it](https://staxlang.xyz/#p=878243083083&i=[0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,1])
```
:1F^|5+ #Full program, unpacked, implicit input as array
:1 #Get indicies of truthy
F #Use rest of program to loop through elements
^ #Increment current element
|5+ #Get n-th fib and Add
```
Pretty straight forward. LSB Ordering.
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack), 40 bytes
```
([]){{}([({}<>{})]({}{}))<>([])}<>({}{})
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fIzpWs7q6ViNao7rWxq66VjMWyABSmjZ2ICmgGIT///9/w/8GQGgIxUAIAA "Brain-Flak (BrainHack) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 63 bytes
Takes input as an array of `1`'s and `0`'s, along with the length of the array. This solution is a rather straight-forward backwards loop.
```
f(_,l,a,b,t)int*_;{a=b=1;for(t=0;l--;b=(a+=b)-b)t+=a*_[l];_=t;}
```
[Try it online!](https://tio.run/##ZZBRS8MwFIWf219RMoRkS6FZq3YLQfqgIA4E59s2SpImo1DraAMKpX/dmuLQxnEIuXzn3EOIDI9SDoOGOa4wxwIbVNZmntOOM8EI1e8NNCyiVRhSwSBfMIFCgcyC8Xm@qw40Z4b2w6xQuqxVkG239y@vUH2eUHBqbJOGIGtb1Zjgql3vDZhZC@xrgAM73IHnJ7AGD9njBiD/jZc1REHne3Yv4LuDxzqCIyvSY98TU3A@VqMlJ5aj0Sz@7f3JZeQnrn7j5CJ6eTtPsQXU985foCHHCWLsBk2ZwCvLbmMHSkwiS9OVQwtMxmyaxEuHK7xMx45lnFyPTj98SV3xYzuEH98 "C (gcc) – Try It Online")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 74 bytes
```
\D-->[X,Y],{D is 2*X+Y};[D];a,\D.
a,[A],[B]-->[X,Y,Z],{A is X+Y,B is X+Z}.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P8ZFV9cuOkInMlan2kUhs1jBSCtCO7LWOtol1jpRJ8ZFjytRJ9oxVifaKRaqUCcKqNQRpBSoUMcJwoiq1fv/vyCjKLE4VSMmQifaUMdAB4hjNfW4uAA "Prolog (SWI) – Try It Online")
Takes input as a list of integers 1 and 0 with the most significant bit first.
[Answer]
# Japt `-x`, 9 bytes
```
Ë*MgUÊa´E
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=yypNZ1XKYbRF&input=WzEsMCwxLDAsMSwwLDAsMSwwLDEsMF0KLXg=)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 41 bytes
A port of [xnor's answer](https://codegolf.stackexchange.com/a/173603/58563). Takes input as a BigInt literal.
```
f=(n,a=1n,b=a)=>n&&n%10n*b+f(n/10n,b,a+b)
```
[Try it online!](https://tio.run/##dc5NDsIgEAXgvafoxgYsCgP1b4F3gVpMTTMYa7w@0gZNDO2bTPI2X2bu5m2G5tk9Xlv01zYEpwkyowGZ1YbqC5YlrkHgxlaOII@NWWYqS0PjcfB9u@v9jTgCQgBSWiyF8@KwykkcIRZcJEeVm5R5FM3pPHdnSmrwj0dTK5kp@Jrfpn8nPn4nVb2X4QM "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 44 bytes
Takes input as an array of characters, in LSB-first order.
```
s=>s.map(k=>t+=k*(z=x,x=y,y+=z),x=t=0,y=1)|t
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1q5YLzexQCPb1q5E2zZbS6PKtkKnwrZSp1LbtkoTyCqxNdCptDXUrCn5n5yfV5yfk6qXk5@ukaYRraenp2RoYGCoFKupqYAL6OsrmHFh0WgA1GiATzdQo7kxDp0QgEsrUKeFJVadhmBbwRSUhWoESKeJsREuWw0hOg2RMFgQbAjIvUbGJqZG/wE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 8 bytes
```
;r⌐@░♂FΣ
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9@66FHPBIdH0yY@mtnkdm7x//@GOgZACCFhEFUMSAMA "Actually – Try It Online")
Input is taken as a list of bits in LSB-first order.
Explanation:
```
;r⌐@░♂FΣ
;r range(0, len(input))
⌐ add 2 to every element in range (range(2, len(input)+2))
@░ filter: take values in range that correspond to 1s in input
♂F Fibonacci number at index of each element in list (Actually uses the F(0)=F(1)=1 definition, which is why we needed to add 2 earlier)
Σ sum
```
[Answer]
# Powershell, 68 bytes
```
param($s)$b=1
$s[$s.Length..0]|%{$a,$b=$b,($a+$b)
$x+=($_-48)*$b}
$x
```
Test script:
```
$f = {
param($s)$b=1
$s[$s.Length..0]|%{$a,$b=$b,($a+$b)
$x+=($_-48)*$b}
$x
}
@(
,("1001", 6)
,("100101000", 73)
,("1000000000", 89)
,("1001000000100100010", 8432)
,("1010000010001000100001010000", 723452)
) | % {
$s,$e = $_
$r = &$f $s
"$($r-eq$e): $r"
}
```
Output:
```
True: 6
True: 73
True: 89
True: 8432
True: 723452
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 65 bytes
Pretty small for a Java answer to I'm happy with that. Takes input as a LSB-first ordered array of ints.
```
d->{int s=0,f=1,h=1;for(int i:d){s+=i>0?f:0;f=h+(h=f);}return s;}
```
[Try it online!](https://tio.run/##nVKxboMwEJ3LV5wyGRGQkTpUpaRqpW5tlnSLMrhgglNiI9skqSK@nR6YIFXtkhphjN@7e8933rEDC1XN5S7/7LKKGQNvTMizB1A3H5XIwFhm8SOk5bpgGYdlD04w7oMkOK83kPsJQq2H0xi1BAkpdHm4OPdEk9J5kcbzMo2TQuk@DMR97p9NkIoFfSzuaVKkZUDKtPCTVnPbaAkmabvE@@XooEQOezRLVlYLuUUDzAdbanU08HLKeG2Fks7s6stYvo9UY6MaubaSREaSZEoeuLbv6nX1TGYxpfHM94dDXBGCD6XXx43jP4LDGFfx9RniS/z0joeYUrXeX/3HAv9I5cqOSN1YH1yh@45WXG5tiX0fkMj9ktGjy6M5pjE8R5Lkx2HT0TaONV0OJNAExINDcRUEFyknJmTOT8gaRUMgIohHLZh01gNtM3nKSqafLBF@eHvnuK3n@MONu4QNtbjx2u4b "Java (OpenJDK 8) – Try It Online")
**Ungolfed**
```
d->{ // Lambda function that takes array of ints
int s=0,f=1,h=1; // Initialise sum and fibonacci vars
for(int i:d){ // Loop through each input integer
s+=i>0?f:0; // If it's 1 add current fibonacci number to sum
f=h+(h=f); // Increase fibonacci number
}return s; // return sum
}
```
[Answer]
# [Z80Golf](https://github.com/lynn/z80golf), 34 bytes
```
00000000: dde1 f1b7 2819 fe30 2812 4504 aff5 3cf5 ....(..0(.E...<.
00000010: d1f1 82d5 f510 f9c1 f17c 8067 2c18 e3dd .........|.g,...
00000020: e5c9 ..
```
[Example with input 1001-Try it online!](https://tio.run/##bZFfT8IwFMWf2ac44WWYkOZ2g22gkmjim8YHP8HoH7ZYNsI6FcJ3xztG0Ij3oT29uefXk3af0ap29nikc80RGyLYaWwQSzvlY9wdeyVZKQ2Z8ggWQiykWNBp4wp6gmRGqlSCmHiUKCOkidYw0kos0yiDnFmGEyscBNvFR2cfCUGjMyNihowmU9Akt10YxYvm22UWQXdhJNkZVIeEeGL3nbjUmRGfcvDtSRopyMzE0NpMoWa4roNYjU/m4/Ghacx66Xaw9Ra2rZQv6woqd26O0WvrN61HU9St01gahEl4E7DMx6DB4BZV6xy82a7LKvf1Nti0TYHcnkdCGfLMy9vj3z6Fl85/judfji4J9ka9c/@kfWF@cn6WvkBZccj7oeTPGApcZU56dhHk/C30FVPPzPjRCobqstm4fIetaVrngyJ3/hs "Z80Golf – Try It Online")
[Example with input 100101000-Try it online!](https://tio.run/##fVPRbtowFH2Ov@IIaYJKkWUTIIGtSKXrG9Me9gGVYztNupBEIalatH9n107oKibVD/b19Tnn3nMJp0Q81WV2PotxbaCybInIRhLZMrKIBF2HSA4PYriC863kW3E5tmxQkKTxEerp2iBKhECspQWBaFNiBQwCnCf8jzv4qDEnDSHW0pEiiIVMkKlEQq@8ZJxA6jTGXFjj@kg8lwv@yjkuGhFpLKKMSIYKJ9QXacQrGGPJmnT0RK6RuS5xPyi8uG1GSqPGgjQINcdiKRbjZDRtRpJuMjfOmtNdawnM@AOxv/HLGjWWpJHJWFMLK6qpyYuNjIFd6jWuF43hKfTs8/nueLSHtHxDVrfI@kp3RV1Bq7LcYPaz75q@wzGv@9IgtZjE0eSGvRJUBcFXqFsRourLEp1tD0WlurplTX/MyQUjhgoxlVMC/vi1u86L6XvmP8Yn2E8wVGf/oc716TzhZPVvwhUV@bqdSPch0SYmg0rOiq5Wj01bVN2GYD5Al1syeUhti6rQtnxjAaFtCMECjy/rutn4pA4hKfu9eCmMpVSwN9iFQ2Y/oIJjn@IuvKfouSUCvTxUhm5FpbEbsiPa0@jRsZRxDWrmg0jkfvwUkm90NdQXV/diNRhmkjIvalngfjDmlKtTiPeePS4NHcA7vRgJmrrxMoGfGf2lRE4X81yd8A/IclV2fwE "Z80Golf – Try It Online")
Assembly:
```
zeck: ; input=push on stack in MSB order (eg top is LSB) output=reg h
pop ix ; save return addr in ix
f:
pop af ; get next digit
or a
jr z, return ; if current digit==0, return
cp 0x30
jr z, skip ; if current digit=='0' (e.g. not '1'), skip loop
ld b, l ; find fib of counter
fib:
inc b ; 1-indexing for func to work
xor a ; set a to 0 (1st fibo num)
push af
inc a ; set a to 1 (2nd fibo num)
push af
fib_loop:
pop de
pop af
add d
push de
push af
djnz fib_loop
pop bc ; get the fibo num just calculated
pop af ; pop just to reset stack frame
ld a, h
add b ; add current fibo number to sum
ld h, a
skip:
inc l ; increment counter reg
jr f ; repeat loop
return:
push ix ; push the return addr to ret to it
ret
```
] |
[Question]
[
# Introduction
Yes, it's as simple as that. Download any file from the internet!
# Rules
You must use your language's API.
You must output the file you downloaded to STDOUT, the console, a file, etc.
Input should be empty, or the URL you wish to download, but the url must count to byte count..
Good luck!
[Answer]
# Bash, ~~21~~ ~~17~~ ~~11~~ ~~9~~ 7 bytes
```
curl ai
```
[Answer]
# [Röda](https://github.com/fergusq/roda), 29 bytes
```
{saveResource"http://ai","a"}
```
This is an anonymous function that creates a file `a` containing the HTML code of `http://ai`.
[Answer]
# MATL, 8 bytes
```
'v.ht'Xi
```
The URL provided to `Xi` (`urlread`) is prepended with `http://` if it isn't already. Additionally the output of `urlread` contains the contents of the response and this is implicitly printed when the program exits.
Unfortunately this does not work for the online compilers since loading data from an arbitrary URL is disallowed in online-mode, so here's a GIF.
[](https://i.stack.imgur.com/RCSil.gif)
[Answer]
# Bash, ~~45~~ 43 bytes
```
exec 3<>/dev/tcp/ai/80;echo GET />&3;cat<&3
```
opens a tcp socket with ai site on file descriptor 3, issues a get, and cats the result.
perhaps can be golfed further.
[Answer]
# PowerShell, 7 Bytes
Since we're all using `www.ai`...
```
irm ai.
```
uses `Invoke-RestMethod` - prints the result to StdOut
alternate answer, saves to file named 'a' in run directory, using `Invoke-WebRequest` and `-OutFile` param.
```
iwr ai. -OutF a
```
[Answer]
## Mathematica 18 Bytes
```
URLDownload@"v.ht"
```
[Answer]
## C#, 96 93 bytes
```
async()=>Console.Write(await new System.Net.Http.HttpClient().GetStringAsync("http://3.ly"));
```
[Answer]
# PHP, 22 bytes
If `allow_url_include=1` is in your ini file:
```
<?=include"http://ai";
```
[Answer]
# JS (ES6), ~~38~~ ~~36~~ ~~31~~ 29 bytes
```
fetch`//ai`.then(x=>x.text())
```
Depending on the promise consensus, (41 bytes)
```
fetch`//ai`.then(x=>x.text()).then(alert)
```
[Answer]
# C (Clang, ARMv7-a Linux/Android, AT&T Wireless), 162 bytes
Since we're hardcoding URLs, why not hardcode ISPs?
```
main(s){int b[500]={5<<28|2,**((int***)gethostbyname("ai"))[4]};connect(s=socket(2,1,0),b,16);write(s,"GET / HTTP/1.0\n\n",16);read(s,b,-1);read(s,b,-1);puts(b);}
```
I can't show a demo because none of the demos have online enabled :(
This abuses two things. One is that I assume `http://ai` is smaller than 2000 bytes and just casually read a max of 4GB onto the stack (what could possibly go wrong), and two is that I take advantage of how I discovered that AT&T Wireless converts `\n` to `\r\n` in HTTP requests for some reason (new data saving hack?).
Termux screenshot, showing how it works on data (AT&T via Cricket) but *not* on my Wi-Fi (Xfinity).

Ungolfed and commented:
**note**: I have removed the punning and buffer reusing for this.
```
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
// Look up the IP address of http://ai
// Note that I mess around with type punning and the documented
// layout of the structure in the golfed version.
struct hostent *ent = gethostbyname("ai");
// Extract the first IP address (already in network order)
uint32_t ip;
memcpy(&ip, ent->h_addr_list[0], sizeof(uint32_t));
// Create the sockaddr struct
struct sockaddr_in header = (struct sockaddr_in) {
.sin_family = AF_INET,
.sin_port = htons(80),
.sin_addr = { ip }
};
// Copy over to the pun
struct sockaddr_storage header_raw;
memcpy(&header_raw, &header, sizeof(header));
// Create an IPv4 socket
int soc = socket(AF_INET, SOCK_STREAM, 0);
// Connect the socket to the interwebs
connect(soc, (const struct sockaddr *)&header_raw, sizeof(header_raw));
// Send an HTTP GET request
// Note that because It Works‚Ñ¢ on AT&T, I use \n instead of the proper \r\n. Two newlines are still required though.
#ifdef ATT
const char get_request[] = "GET / HTTP/1.0\n\n";
#else
const char get_request[] = "GET / HTTP/1.0\r\n\r\n";
#endif
write(soc, get_request, strlen(get_request));
char buf[2000] = {0};
// Note: I use -1 to just read the entire thing. Hopefully it is all shorter than
// 1999 chars :P
#ifdef BUF_HACK
size_t len = -1;
#else
size_t len = sizeof(buf) - 1;
#endif
// Receive the HTTP response header
read(soc, buf, len);
// But ignore it because I don't care about parsing HTTP stuff
// Just read again for the real data
read(soc, buf, len);
// Print to stdout (assuming the HTTP header was shorter)
puts(buf);
// I don't actually bother closing the socket in the golfed code, sue me.
#ifndef RESOURCE_HOG
close(soc);
#endif
}
```
I just decided to see how painful this was, I knew before I started that it didn't have a chance. üòè
[Answer]
# R, 24 bytes
```
readLines('http://g.co')
```
prints the output to console in the usual R format -- vector of strings, one element per line of the site.
[Answer]
# Mathematica, 13 bytes
```
URLFetch@"ai"
```
[Answer]
# Python 2, ~~55~~ ~~49~~ 47 bytes
~~Not shorter but~~ I really thought I could go further.
```
from urllib import*
urlopen('http://ai').read
```
[Answer]
# Vim Ex command, 14 bytes
```
e http://3.ly/
```
Opens the URL as a new buffer. Netrw seriously suffers from a restrictive URL format.
[Answer]
## nc -v v.ht 80 < file - 31 bytes
Where file contains:
```
GET / HTTP/1.1\r\n
Host: v.ht\r\n
\r\n
```
I profess ignorance about how I should score this. The file is 31 bytes and contains the URL I want, the `-v` flag value decides if I get the file I want or an error response.
[Answer]
# Racket, 71 bytes
```
(require net/url)(port->string(get-pure-port(string->url"http://ai")))
```
[Answer]
# Kdb+, ~~34~~ 15 bytes
**KDB+ >= 3.4**
```
q).Q.hg`http://ai
```
from [here](http://code.kx.com/wiki/DotQ/DotQDothg).
**KDB+ < 3.4**
```
q)`:http://ai"GET / HTTP/1.0",4#"\n"
"HTTP/1.1 200 OK\r\nDate: Thu, 11 May 2017 21:45:01 GMT\r\nServer: Apache/1.3..
```
[Answer]
# [J](http://jsoftware.com/), 33 bytes
Sadly, this only works on the J shell.
[](https://i.stack.imgur.com/icQNs.png)
```
load 'web/gethttp'
gethttp 'g.co'
```
[Answer]
# HTML, 24 bytes
```
<iframe src="http://ai">
```
This technically fails as it renders the result...
[Answer]
# Vim, 2 + 12 = 14 bytes
```
gf
```
Expects the URL `http://3.ly/` as input. `gf` opens the current file under the cursor. Thanks to netrw, this works fine for URLs. I found this just now while trying to remember the command to open URLs in your browser (found it, it's [`gx`](https://stackoverflow.com/a/9459366/2093695)).
[Answer]
## PowerShell, 62 bytes
PowerShell 5
```
-join[char[]][net.webclient]::new().downloaddata('http://ai.')
```
66 bytes for more older versions of PowerShell
```
-join[char[]](new-object net.webclient).downloaddata('http://ai.')
```
[Answer]
# Python + requests, ~~55~~ ~~53~~ 50 bytes
```
from requests import*
print(get('http://ai').text)
```
-2 bytes by switching URLs
-3 bytes thanks to ovs
[Answer]
# [AHK](https://autohotkey.com/), 31 bytes
```
URLDownloadToFile,http://g.co,g
```
There's a built-in so it's not very exciting. Try to fashion, though, the function is fairly long.
[Answer]
## Bash + wget, 7 bytes
```
wget ai
```
Downloads the page at <http://ai>
[Answer]
## Ruby, 27 + 10 = 37 bytes
```
puts open('http://ai').read
```
+10 bytes for `-ropen-uri` flag (to require open-uri library)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 4 + 11 = 15 bytes
```
jk'z
```
With URL `http://v.ht` as input. Takes an URL string as input, downloads the file, and prints its content.
Explanation:
```
jk'z
z Get the input string (URL)
' Download the file from the URL, return a list of lines
jk Join the list on k which is the empty string
```
Note that we cannot use the function `s` for concatenating the list because of bytes types issues.
**Slightly cheating, 2 + 11 = 13 bytes** (it displays the list of the lines in the file instead of a single string for the whole file):
```
'z
```
You will need to install Pyth on your machine to test it (the online interpreter does not execute unsafe operations).
[Answer]
## C#, 76 bytes
```
Console.WriteLine(new System.Net.WebClient().DownloadString("http://3.ly"));
```
[Answer]
## MATLAB, 20 bytes
```
urlread('http://ai')
```
Nothing fancy here...
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
.w
```
Beats all other answers. Takes `ai` as input.
] |
[Question]
[
## Background
A ray of light is fired from the top left vertex of an `MxN` Chamber, where `M` a denotes the width and `N` denotes the height of the chamber. The ray of light advances one grid space per second. Given that `T` is the number of seconds to be simulated, calculate the number of reflections in this time frame.
For example, given `5 4 11` (ie. `M = 5, N = 4, T = 11`):
```
\/\ [
/\ \ [
\ \ \[
\/[
-----
There would be 4 reflections, so the output should be 4.
```
Note that a reflection only counts if the ray of light has already bounced off it, so for example, given `5 4 10`:
```
\/\ [
/\ \ [
\ \[
\/[
-----
There would only be 3 reflections, so the output should be 3.
```
## Your Task
* Sample Input: M, the width of the chamber, N, the height of the chamber, and T, the time frame. These are all numbers.
* Output: Return the number of reflections.
**Explained Examples**
```
Input => Output
1 1 10 => 9
Chamber:
\[
-
The ray will be reflected back and forth a total of 9 times.
```
```
Input => Output
5 1 10 => 9
Chamber:
\/\/\[
-----
The ray will be reflected back and forth a total of 9 times. It will first go left to right, then go backwards right to left.
```
```
Input => Output
4 5 16 => 6
Chamber:
\/\ [
/\ \[
\ \/[
\/\[
\/\/[
----
The ray will be reflected back and forth a total of 6 times.
```
```
Input => Output
100 100 1 => 0
Chamber:
\ ... [
... x100
-x100
The ray never touches a wall, and is never reflected, so output 0.
```
**Test Cases**
```
Input => Output
5 4 11 => 4
5 4 10 => 3
1 1 10 => 9
5 1 10 => 9
4 5 16 => 6
100 100 1 => 0
3 2 9 => 5
5 7 5 => 0
3 2 10 => 6
6 3 18 => 5
5 3 16 => 7
1 1 100 => 99
4 4 100 => 24
2398 2308 4 => 0
10000 500 501 => 1
500 10000 502 => 1
```
Bonus points (not really): Listen to DeMarco's song [Chamber of Reflection](https://www.youtube.com/watch?v=pQsF3pzOc54) while solving this.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins.
[Answer]
# [Python](https://www.python.org), 47 bytes
```
lambda M,N,T:len({*range(M,T,M),*range(N,T,N)})
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY9NTsMwEIX3PsWoK7sy4J84JJXCCZquumRjRFMspY4VwgIhTsKmEoLbcIDehvEPYjHSe9943pM_vsPr8jT58-fQ3X-9LMNVc7kZ7enh0ULPd3y_GQ-evq1n648H2vM97xkvDrd8x95ZObPDNMMWnIcp4I1gGwKOT9DB9vo5jG6hK-juYMUQI3QFol3nZycbqPMLp9Ez5GFGS9HwARkrRefLj4EKpIxpFUlaRK2JBFl0i_xfV4CujromUghIE60gGhS0UZok80VNatAgm8xN1On6tjTk2Jhb_TlVEaXbBpQWDdKUjStcmjSpThKT2xNSGeVf_QI)
### How?
Enumerates and counts all bouncing times using the Python set type for deduplication.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 58 bytes
```
g(a,b){a=b?g(b,a%b):a;}f(M,N,T){T=--T/M+T/N-T*g(M,N)/M/N;}
```
[Try it online!](https://tio.run/##VVBBboMwEDzjV6xSRbLDUiCEKKlL@gI4@db2YCBQpBYQgV4Qb6d2IAm9jHZm1jveTaw8ScYxpxJj1ssgfstpjHIdsxfJh4yGGKFgvQgsS9ihKezIEptcy8wO7YgP41NRJt9deobXS5sW1fPXiZCibMmPLEr6WxUpIz0xLm3TJS2oylAmhAgRguDEGEC@f0JwdXofYYfgugMumDMxV5UP5v9jqk0L@7nTcbSlYRI8hC3CcUluL/cISnAP96neYs6c8QjZLejWOx7UKM9RuLsH61R/gtsW828mcTuJzqA2R9jUnBAjqxqgtbqB5FBbp5CDadZMtdWNulVGV@v0o1whZFS7qHuiKwrG9Pvm3HZNCQ4nw/gH "C (gcc) – Try It Online")
Uses the formula:
\$ \lfloor \frac{T - 1}{M} \rfloor + \lfloor \frac{T - 1}{N} \rfloor - \lfloor \frac{T - 1}{lcm(M,N)} \rfloor\$
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 5 bytes
```
ᵒ÷u#←
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fqsebp10eHup8qO2CUuKk5KLocILbs6NNtUxiVUwNOSCMgy4og11DCEMUxjDRMcUyDADShkY6AAxkMMVbaxjFKtgCaVBqsx0jIEMC5A-Y6hyiAFgE0ygLCNjSwsdI2MDi1gFE7CBQCNNQUaaGoAcAbEAwjeCuBIA)
Takes input as `[m,n],t`.
```
ᵒ÷u#←
ᵒ÷ Generate a division table of [0,...,t-1] and [m,n]
u Uniquify
# Length
← Decrement
```
[Answer]
# [Python 3](https://docs.python.org/3/), 50 bytes
```
lambda x,y,t:len({(i//x,i//y)for i in range(t)})-1
```
[Try it online!](https://tio.run/##VU/LasMwELzrK7YnS@Amll9NAg700i/oLc3BieVW4MhGUiHG@NtdrZTWdEFidnZmVhpG@9WrbGmrj6Wrb5emhns8xvbQCUUnKrfbe@yukbW9BglSga7Vp6CWzeyZL/I29NqCGQ251A1U8FZ3RhAUd1IJ1LvZxthGqgMBV9qJcLQxQyctjapjxPxAtoA7NYOqgjSIsfxznOlWD1QqG4M@JeeHm7E/We8kbkz1iZ9X9urYlvqIlXSbrvBUQb8uwRo0@tuopdN9jmEa8bKzf890ndEx9XPE/pnCr9/1tyAuVvUWmZAb8qLXrgMrjDUw1MaI5iliSwE5cA7VEXLicYI4Ixz4A@8dv@IcXFciLglPEvAH24SQDFLYIy48DJaSlJAB3wW@QOztL48VIReD898uzUma7XeQZsnOsT7cjdyw8Mfv46QI6z2VeuoH "Python 3 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~49~~ 48 bytes
```
f=lambda M,N,T:(T:=T-1)and(T%M*(T%N)<1)+f(M,N,T)
```
[Try it online!](https://tio.run/##RVBBaoRAELzPKwoh6CRucBw1KjGQB@jJ28aDQSWCcUU9bF5vplt3d2Ckurqq2unpb/25jDqe5m3rsqH@/W5q5G7hlqlTpll5UrIeG6d8yp/Np5DvSr50Dgvk1l1mDP3Yoh9hWVaIAEoh@0AgGHuEtVBQB04M/8ABTBURjoTyPPCl0hNCw0dCOGS4WyIRQUPFOx8SZvvbMWLPpeDgVvmB8HUSw9debFgONy3TDPnyPCXCfTxTPlPmPa/LNPSrY3@NtkwFzOk7fu9e0GHFgozpQy/v3dxF4aI07XM/rs5VgjZ2pXXtxnOqq@oun1tKIuXRPanqEVYvSzuvuC0fWUYGMc1ksD@HAWu7mH@ZSNjYcvsH "Python 3.8 (pre-release) – Try It Online")
-1 byte thanks to c--
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḍƇⱮṖTL
```
A dyadic Link that accepts the dimensions on the left and the time on the right and yields the number of completed reflections.
**[Try it online!](https://tio.run/##y0rNyan8///hjt5j7Y82rnu4c1qIz/@jkx7unKFzeLl@1qOGOQq2dgqPGuZqRv7/Hx0dbaqjYBKro2BoGKvDpYDgGkC4hkAmEtcUlWuio2AK4ppBFRsYgOQMYsGqQCLGOgpGQJ4lCg@m20xHwRjEtYCbbYxsGMwqhF0myHwjY0sLoHnGBkDtIBmoA0BOMAU7wdQA5iWos6CiQCdwxQIA "Jelly – Try It Online")**
### How?
```
ḍƇⱮṖTL - Link: dimensions = [M, N, ...]; time = T
Ṗ - pop {T} -> Seconds=[1,2,3,...,T-1]
Ɱ - map {across S in Seconds} with:
Ƈ - keep {dimensions} that:
ḍ - divide {S}
T - truthy indices
L - length
```
---
Lots more sixes such as, [TIO](https://tio.run/##y0rNyan8///hzmmH21zSjrX7/D866eHOGTqHlzvoZz1qmKNga6fwqGGuZuT//9HR0aY6CiaxOgqGhrE6XAoIrgGEawhkInFNUbkmOgqmIK4ZVLGBAUjOIBasCiRirKNgBORZovBgus10FIxBXAu42cbIhsGsQthlgsw3Mra0AJpnbADUDpKBOgDkBFOwE0wNYF6COgsqCnQCVywA):
```
ṖÆDfƇL - Link: time = T; dimensions = [M, N, ...]
Ṗ - pop {T}
ÆD - divisors
Ƈ - keep those for which:
f - filter keep {dimensions}
L - length
```
`RmFQL’` [TIO](https://tio.run/##y0rNyan8/z8o1y3Q51HDzP9HJz3cOUPn8HIH/axHDXMUbO0UHjXM1Yz8/z86OtpUR8EkVkfB0DBWh0sBwTWAcA2BTCSuKSrXREfBFMQ1gyo2MADJGcSCVYFEjHUUjIA8SxQeTLeZjoIxiGsBN9sY2TCYVQi7TJD5RsaWFkDzjA2A2kEyUAeAnGAKdoKpAcxLUGdBRYFO4IoFAA)
`ḍẸ¥ⱮṖS` [TIO](https://tio.run/##y0rNyan8///hjt6Hu3YcWvpo47qHO6cF/z866eHOGTqHl@tnPWqYo2Brp/CoYa5m5P//0dHRpjoKJrE6CoaGsTpcCgiuAYRrCGQicU1RuSY6CqYgrhlUsYEBSM4gFqwKJGKso2AE5Fmi8GC6zXQUjEFcC7jZxsiGwaxC2GWCzDcytrQAmmdsANQOkoE6AOQEU7ATTA1gXoI6CyoKdAJXLAA)
`×ⱮFQ<S`, `×þFQ<S`, `ḍⱮṖṀƇL`, `ḍþṖṀƇL`, `ḍⱮṖṀ€S`, `ḍþṖṀ€S`, `ḍⱮṖẸ€S`, `ḍþṖẸ€S`, `ḍⱮṖẸƇL`, `ḍþṖẸƇL`, `Ḷ:€QL’`, `:þSṖṬS`, ...
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 36 bytes
*port of [user1609012's Python answer](https://codegolf.stackexchange.com/a/262876/112488)*
```
f=(M,N,T)=>--T&&!(T%M&&T%N)+f(M,N,T)
```
[Try it online!](https://tio.run/##TZDNbsIwEITvfortIZEtO@DfNFEV3gBOOSIVxySIKkoQVLx@8E@qcljrmxntjuQf@7QPd7/efotpPvfLMjR4zw6sJc2uKNo8/8Btts/zNjsQOqzR8nVCBjQIAc0OdGIeWCEBYuXa@/@swasycIkE5xAnSI6QAgl1YBMxrZSoBAWiSr4JHNc/14p0NxzWf0pqJFVdgVS88m487iMfmjixTyCT6qMlk3Xa3PvbaF2Pt/h4pgTe3u2F4W9mWcec/xQ3T4957DfjfMEDppbRjlFHCFle "JavaScript (Node.js) – Try It Online")
## Explanation
Start from the end of the ray \$(t = T)\$, and count the number of times it bounced in it's way, that is, anytime \$t \equiv 1 \pmod M \lor t \equiv 1 \pmod N\$. It's easier to see if you extend the chamber infinitely and have the ray cross the chamber walls.
---
# [C (gcc)](https://gcc.gnu.org/), 39 bytes
*port to C*
```
f(M,N,T){T=--T?!(T%M&&T%N)+f(M,N,T):0;}
```
[Try it online!](https://tio.run/##VVDLboMwEDzjr9ikIrLLUplXlNRN@gVw8q3NAUFokVpABHpBfDu1AyTkMtqZWe94N7G/kmQYMhpihJJ18mDb8n1FpRluNtKMmDVbr1z0w1NeJD9teoa3S5Pm5cv3kZC8aMhvnBf0r8xTRjpiXJq6TRpQlaFMCBEiBCmI0UP8cYLD1ekCBB/BcXpcMD4yR5V3Fjww1aaF7dTJubY0jIKH4CLsl2R@uUVQgrO7TfUWc6aMe4i/oK6336lRHlfo34J1ajDCvMX0m1F0R5H3anOE50oQYmRlDbRSN4gFVPYxFGBZFVNtVa1uldG1mX4Wa4SMahd1T3RFyZh@X5@bti6AC9IP/w "C (gcc) – Try It Online")
[Answer]
# [J](https://www.jsoftware.com), 18 bytes
```
<:@#@~.@(<.@%/~i.)
```
Uses the division table method used by others. Expects `M N f T`.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxycbKQdmhTs9Bw0bPQVW_LlNPEyJx86MmV2pyRr6CqYKJQpqCoSEKzwDCMwRCBM8UhWcC5AN5ZlCVBgZgDBQBC6irQ8SNFYyAYpbIHJgBZkA-kGcBM9wY2TioVXC7TJC5RsaWFkDCwAIoaAK3H2i7KdgFpgYwz0AcBRU0gnh8wQIIDQA)
```
<:@#@~.@(<.@%/~i.)
( ) NB. Dyadic hook
i. NB. 0..y-1
/~ NB. Table with flipped arguments, execute a u b for every a in x and b in y
<.@% NB. Divide then floor
<:@#@~.@ NB. Then uniquify, length, and decrement
```
# [J](https://www.jsoftware.com), 19 bytes
```
+`-/@(<.@%[,*./)~<:
```
Uses the closed form from [c--'s](https://codegolf.stackexchange.com/a/262883/110888) answer, so please go upvote!
Expects `M N f T`, where `M N` is a list.
The major form is two hooks, an inner and outer hook, `(H F)~ G`, which is equivalent to `(G y) H (F x)`, with `+`-/` tacked on at the end, where `x` and `y` are the left and right arguments, respectively.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxWTtBV99Bw0bPQTVaR0tPX7POxgoic_OjJldqcka-gqmCiUKagqEhCs8AwjMEQgTPFIVnAuQDeWZQlQYGYAwUAQuoq0PEjRWMgGKWyByYAWZAPpBnATPcGNk4qFVwu0yQuUbGlhZAwsACKGgCtx9ouynYBaYGMM9AHAUVNIJ4fMECCA0A)
```
+`-/@(<.@%[,*./)~<:
<: NB. Decrement T
( )~ NB. Flip the arguments for the inner hook
[,*./ NB. Append lcm(M,N) to the list of dimensions
<.@% NB. Divide T-1 by each item of the result then floor
+`-/@ NB. Then reduce by both + and -, i.e. +`-/ 6 3 1 = 6 + 3 - 1 = 8
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 33 bytes
```
@(M,N,T)nnz(union(1:M:T,1:N:T))-1
```
[Try it online!](https://tio.run/##Zc9LDoIwEAbgvSdpk1/S6QNpExIvACsuYFQSNsXEx8LL11IMBV3M5puZzt/x/Di9rqGvi6IIR9agRce9f7OnH0bPyDWuA7nWdZzvKVyG@431zECDiNe15rs1iUhqIQLNZFdTf6QRsYxU5kUhkCqqWFRBwkYxG0mv5dUSClRtpsxE04HDT7KUYx1Ef1Hmb0llK0glKuhNmDgYA5pUU0zK5@bwqSNTJ3wA "Octave – Try It Online")
Thanks to @Luis Mendo for -2.
### [Octave](https://www.gnu.org/software/octave/), 35 bytes
```
@(M,N,T)numel(union(1:M:T,1:N:T))-1
```
[Try it online!](https://tio.run/##Zc9NDoIwEAXgvSdpkyfp9AehCYkXgBUXMAoJiQKJ4vVrKYaCLmbzzUzndbi@Lu/GtUWSJO7MSlSoeT89mjub@m7oGdnS1iBb2ZrzI7lb9xxZyww0iHhRaH7YkvCkViLQQvlm6o80PKae0rgoBEJ5FasqSORezE7Ca3E1hQJluykz03zg9JMs5NgG0V@U8VtS5RmkEhn0Lowf9AFNqDkmxXNL@NCRoeM@ "Octave – Try It Online")
Port of @Albert.Lang's Python answer.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 46 bytes
```
M=>N=>g=(T,x,y)=>T--?!(x*y)+g(T,-~x%M,-~y%N):T
```
[Try it online!](https://tio.run/##TZDLbsIwEEX3/orpAsluHPAzTYqcfgGssqwExoSoVUQQoCrZ9NdTP6jaxYzO3NHcK82n/bI3d/243PPzcGznk5k3pt6aujO4oSOdiKmbPH97wuPzRLLOi/n3uNj4Pi225LWZ13ukQQHnYGpQiVlgiTjwB1de/2MFfioCF4gzBrHCyBCSIKAKrCOmkwIVIIGXSdeB4/nLIyL5BmP1OwmFhKxKEJKVXo3mfuWXOlbM40in@CiJJO2X1/bSW9fiFX4/ZgT@9VVH8Y5aeqDOP8YN59vQt8t@6PAJZ5bg7ODLEULmHw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Scala](https://www.scala-lang.org/), 156 bytes
Golfed version. [Try it online!](https://tio.run/##bZHBboJAEIbvPMVcmszEtdkVNUqLSdNTD3qpPZkeVgqUhmIDm0aCPjudBVKFlmT/yXw7888ARaBTXR/2H2FgYK2TDKr6LYwgwrX3lBnCTRM8ZBXdIX/F6le2LsatLRBHq74UZRupCUmE23tFYwVhWoTA6dH35elUspIace9YCTyOFN2sBZY2bqgp/f/qLj7XAHbsJ2@KOo8LDx7yXJe7Z5MnWfxKHrxkiQEfKgf4@dYpmLAwj7oIC6ZNMTZXADgTMBWgFIkBkReiOO2T2R/CLRbOr7qktCVWLtAVMBGwHIJrp7kAhmrRm@YOvLv5/QWmAzRxlwu2dyXrtLeY3WrWyvWbdxu3FxNqODlN@P2Ct9EhD3XwDhUEnANqAXsBAYG/6oy@@D@YNMMINeGeMBDAjpJaw7Njz9mpfwA)
```
def f(M:Int)(N:Int):(Int,Int,Int)=>Int={def g(T:Int,x:Int=0,y:Int=0):Int=if(T<1)-1 else if(x==0||y==0)1+g(T-1,(x+1)%M,(y+1)%N)else g(T-1,(x+1)%M,(y+1)%N);g}
```
Ungolfed version. [Try it online!](https://tio.run/##jVI9T8MwEN3zK96CdFZdFDdtRSMVCTExtAtlQgxucEJQSFESoUZtf3uwY7dNwsLgO997922Xkcxk0@y2nyqqsJJpjoMHvKsYMa1CPOUVo7XVIUgrjrNgWN4bjWUbY6MS2oTWYx860ueoL3cW9kKANAZtsDQUNmPhUJWVqqX2LYXjEbVzEhiZKhhDcMOPIBhusNJGfTbWrJvnn94nr1WJ565mnC@9EZJFUoZ4KApZvz5XRZonb3qMlzy9zvEjM1SqrB5lqUqNts7kmqAZx5RDCMYHiH9FdHuij8z@IDrEgPNOlO8bFyOuYMAx4VgMgW6mOYcGxV2vWjDI7er3G5gOoEmwuNPpA1/Laa8x09XMiu7krmNLTOzqmV39ZYO38a5QMvrAAZG2QZJjyxGZL@cSfet3qLKcYpKMtowibj6az85vac7Ja5pf)
```
object Main {
def f(M: Int)(N: Int): (Int, Int, Int) => Int = {
def g(T: Int, x: Int = 0, y: Int = 0): Int = {
if (T == 0) T-1
else if (x == 0 || y == 0) 1 + g(T - 1, (x + 1) % M, (y + 1) % N)
else g(T - 1, (x + 1) % M, (y + 1) % N)
}
g
}
def main(args: Array[String]): Unit = {
val testCases = Array(
(5, 4, 11),
(5, 4, 10),
(1, 1, 10),
(5, 1, 10),
(4, 5, 16),
(100, 100, 1),
(3, 2, 9),
(3, 2, 10),
(6, 3, 18),
(5, 3, 16),
(1, 1, 100),
(4, 4, 100),
(2398, 2308, 4),
(10000, 500, 501),
(500, 10000, 502)
)
testCases.foreach { case (a, b, c) =>
println(f(a)(b)(c, 0, 0))
}
}
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
≔…¹NθI№×﹪θN﹪θN⁰
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjdLHYuLM9PzNIIS89JTNQx1FDzzCkpL_Epzk1KLNDQ1dRQKNa25Aooy80o0nBOLgUR-KZAZkpmbWqzhm59SmpOvUYipCZcMUMoASFovKU5KLoY6YXm0km5ZjlLsMkMDBVMFE4ggAA) Link is to verbose version of code. Takes `T` as the first parameter. Explanation:
```
… Exclusive range from
¹ Literal integer `1` to
N First input as a number
≔ θ Save in variable
θ Saved range
﹪ Vectorised modulo
N Second input as a number
× Pairwise multiplied by
θ Saved range
﹪ Vectorised modulo
N Third input as a number
№ Count of
⁰ Literal integer `0`
I Cast to string
Implicitly print
```
[Answer]
# [Racket](https://racket-lang.org/), 210 bytes
```
(define(r M N T[R 0][X 0][Y 0][x 1][y 1])(let*([A(+ X x)][B(+ Y y)][a(or(< A 0)(> A M))][b(or(< B 0)(> B N))])(if(= T 0)R(r M N(- T 1)(if(or a b)(+ R 1)R)(if a(- X x)A)(if b(- Y y)B)(if a(- x)x)(if b(- y)y)))))
```
[Try it online!](https://tio.run/##dVFNb8IwDL3zKyztYm@q1JSWgdiH6B0OFQdQxSFA2CKqsoWitb@e2Y2EOIRWceP3/PVcp3dH01yfKl1/gfMO7s3B1gYdzGEBy7KAeFOuxKzFtKA2ZceGsDLNM5YzfIEVtLQpc76toeObxpPDN5hBTPjBnzkxuPVg7sEcFgwS2gO@w5KxwnfEiD3V4ycHGrbEVQtGCsFAMy/dZr23ZU865jeupfbGdNSRPFd06Ize072lwWA6hSjidubcwE6fzRnwz1YVnOqqgx9n6wa40kHbiiRwwIm/F@sMSkBk635jl9py9rfZHSNmdfUplfEeABaWQQpKEaT0gIsJhgFOycvcJJj3mEuFHRGMQjXj2B/irQdmHULCNSGjMCUtQ2VHzKpxOC8Tjsd5fShRdISFpJ5NQqtLhpMxm3jMixUxIa2sNOsP61Wh2fw6@pBEQq7@Z/0D "Racket – Try It Online")
---
## Explanation
For starters, this will definitely not win. Looking at the other answers, there seems to be a simpler algorithm to solving this. But I don't want to just copy things without having any understanding on how or why they work, so I decided to use a bruteforcing method of actually running the simulation.
Our function receives our three inputs `M`, `N` and `T`. It also receives a predefined state for the recursive loop.
```
(define (reflect M N T
[reflections 0]
[x-pos 0] [y-pos 0]
[dx 1] [dy 1])
...)
```
We then calculate the next `x` and `y` position, and see whether the next position are out-of-bounds (`-oob`).
```
(let* ([next-x-pos (+ x-pos dx)]
[next-y-pos (+ y-pos dy)]
[next-x-oob (or (< next-x-pos 0) (> next-x-pos M))]
[next-y-oob (or (< next-y-pos 0) (> next-y-pos N))])
...)
```
Once those values are calculated, we check whether our simulation time `T` is equal to zero. If it is, we return the resulting number of reflections. Otherwise we repeat the loop with a new set of configurations:
1. Same `M` and `N` sizes.
2. `T` - 1.
3. If the next X and Y positions are out of bounds, `reflections` + 1, else `reflections`.
4. If the next X position is out of bounds, recalculate the next position by flipping `dx`.
5. If the next Y position is out of bounds, recalculate the next position by flipping `dy`.
6. If the previously calculated `next-x-pos` is out of bounds, flip `dx`.
7. If the previously calculated `next-y-pos` is out of bounds, flip `dy`.
```
(define (reflect M N T
[reflections 0]
[x-pos 0] [y-pos 0]
[dx 1] [dy 1])
(let* ([next-x-pos (+ x-pos dx)]
[next-y-pos (+ y-pos dy)]
[next-x-oob (or (< next-x-pos 0) (> next-x-pos M))]
[next-y-oob (or (< next-y-pos 0) (> next-y-pos N))])
(if (= T 0)
R
(reflect M N (- T 1)
(if (or next-x-oob next-y-oob)
(+ reflections 1)
reflections)
(if next-x-oob
(- x-pos dx)
next-x-pos)
(if next-y-oob
(- y-pos dy)
next-y-pos)
(if next-x-oob
(- dx)
dx)
(if next-y-oob
(- dy)
dy))))
```
*Have an awesome weekend!*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
<Lsδ÷Ùg<
```
[Try it online](https://tio.run/##yy9OTMpM/f/fxqf43JbD2w/PTLf5/9/QkCvaVMckFgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCoZXF/218is9tObz98Mx0m/86/6OjDQ11ok11TGJjdRSiDQ1Q2YY6hkjiULaZTrSJjimEDVRiYKADxBAuklGWOtHGOkZgpilI1BxuEEzY0EIn2kzHGG6oKYxtgGKzAcg6iJkmOtFGxpYWOkbGBhYQkw0gLgAqMoW6wdTACGgUxFEgoVgA).
**Explanation:**
```
<L # Use the first (implicit) input, and push a list in the range [1,input-1]
s # Swap to push the second (implicit) input-pair
δ # Apply double-vectorized:
÷ # Integer-division
Ù # Uniquify this list of pairs
g # Pop and push the length
< # Decrease it by 1
# (after which the result is output implicitly)
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `L`, 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ėsȷ÷Uṫ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNCU5N3MlQzglQjclQzMlQjdVJUUxJUI5JUFCJmZvb3Rlcj0maW5wdXQ9MTElMEElNUI1JTJDNCU1RCZmbGFncz1M)
Port of alephalpha's Nekomata answer.
#### Explanation
```
ėsȷ÷Uṫ # Implicit input
ė # Push [1..t) to the stack
s # Swap so [m,n] is on top
ȷ # Outer product over:
÷ # Integer division
U # Uniquify the list
ṫ # Remove the last item
# Implicit output of length
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
tl{/R.Q
```
[Try it online!](https://tio.run/##K6gsyfj/vySnWj9IL/D/f0suYy4jAA "Pyth – Try It Online")
Port of [@alephalpha](https://codegolf.stackexchange.com/a/262899/73054)'s Nekomata answer.
Takes three inputs: time, width, height in that order.
### Explanation
```
tl{/R.QQ # implicitly add Q
# implicitly assign Q = eval(input()) and .Q to a list of the remaining input
/R.QQ # map division over range(Q) with .Q as the second argument, this automatically vectorizes
{ # deduplicate
l # take the length
t # subtract 1
```
] |
[Question]
[
Given a ragged list, e.g.
```
[[4, 7], [5, 3, [], [6, [2]]]]
```
Your challenge is to sort only the numbers in it. For example, with the above, the result would be
```
[[2, 3], [4, 5, [], [6, [7]]]]
```
The shape of the output should remain the same, only the numeric contents should change.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins!
All numbers will be unique positive integers. You may do input / output with strings.
## Testcases
```
[2, [3, [1, []]]] -> [1, [2, [3, []]]]
[6, 5, [[9]], 7] -> [5, 6, [[7]], 9]
[12, [43, 51], [[23, 4], 9, [22, []]]] -> [4, [9, 12], [[22, 23], 43, [51, []]]]
[9, 4, 2] -> [2, 4, 9]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
FṢṁ
```
[Try it online!](https://tio.run/##y0rNyan8/9/t4c5FD3c2/j/cfnTSw50zNCP//4/mio420VEwj9VRiDbVUTAGUiCmGRAbxQKBDle0EZANEjcEyUGEgNJAxdHRlkAeSC9XtCFIlQlQmakhSH@0EZBpAmRZggwyQugE8oHWGQGZsQA "Jelly – Try It Online")
## How it works
```
FṢṁ - Main link. Takes a ragged list R on the left
F - Flatten R
Ṣ - Sort the flattened R
ṁ - Mold the sorted flattened R into the same shape as R
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~51~~ 47 bytes
```
->l{eval"#{l}".gsub(/\d+/,'%d')%l.flatten.sort}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOrUsMUdJuTqnVkkvvbg0SUM/JkVbX0ddNUVdUzVHLy0nsaQkNU@vOL@opPZ/gUJadHS0iY6CeayOQrSpjoIxkAIxzYDYKBYE/gMA "Ruby – Try It Online")
-4 bytes thanks to Sisyphus
[Answer]
# [R](https://www.r-project.org), 29 bytes
```
\(l)relist(sort(unlist(l)),l)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZFNCsIwEIVx6ylCVwmki0z_LIoXmXYhYkEoFfpzBE_hpoIew4t4GmeaBtuiWSTD65tv3tDbve4fhdj5z64t_M0rk6WqT-W5aWVzqVvZVUNdKqVLZT3v1bWQVuUr1CJRWgx1pEUwlk6KxxcUn-3x0EpP-HuBCGTOtUACUB9ySWZMcjpZ5an1OAVGgiMbN2EBJJ2ZGDBswYiHGd_QKe1Dsaft9J3H83wt0lm3cRFCYkdGTUlAUkhK6vaEP_FoTSSTAV4U2Qa8PiMxMj8yk5l6YAaBQbPp7N_oe_t-AA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes
```
0#/.(i=0):>Sort[Flatten@#][[++i]]&
```
[Try it online!](https://tio.run/##PYzBCoMwEETv/oYgLU5bE6NiQemp54LH4CGIYqBakNyW@OvpFqF72Z03M7sYN4@LcXYwYWpCFt@uJ9tk53vbfTann2/j3Lg@4l7rNLV9n4TXZlen40s7MU32bjDrThGRQuVBBXIQ7xIkPQ8ikiBmgvGhSxQgqvmuflKwr3IUglskcyiPmsvyn6@hII9HEsJHPnwB "Wolfram Language (Mathematica) – Try It Online")
Also works if input numbers are not unique.
```
0# numbers become 0
/. 0 :> replace 0s (in order) with:
(i= ) Sort[Flatten@#][[++i]] the corresponding sorted value
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes
-2 bytes thanks to @att.
```
#/.Thread[#->Sort@#&@Flatten@#]&
```
[Try it online!](https://tio.run/##RYvBCsMgEER/ZWHBk2nQmpYcGjz1XGhv4kFaQwJJCrI38dvteurCMPOWmT3QEvdA6zvUGW4V@9NrSTF8HHbT85vIorD3LRDFw6IX9ZHWgxxCN8Hs0HsQ0FvIWUvIZ5ZiFT62i4SBLY@Nru2jWstwbVANs@ZoOI0MWv@XzEaCLqX@AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 5 bytes
```
N`\d+
```
[Try it online.](https://tio.run/##K0otycxLNPyvquGe8N8vISZF@///aCOdaGOdaEOd6Fgg4Io20zHViY62jI3VMQfyDIGyJsY6poaxQEEjYx2TWB1LnWgjI5hqSx0THaNYAA)
**Explanation:**
Sorts all numbers of 1 or more digits in the input in numerical order, and leaves every other character unchanged (including their positions).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 62 bytes
```
n=>n.replace(r=/\d+/g,_=>n.match(r).sort((a,b)=>a-b)[i++],i=0)
```
[Try it online!](https://tio.run/##HYzhDoIgHMRfhW/A/KdJVnMNX4RYQ0SjGTikXp@g@3R3v9u91FftOtgtHpyfTJp5cnxwdTDbqrQhgTf3qWoWeJT2raJ@kkDr3YdIiIKR8kEdRipsVUmw/EjT7AMi2rs9Iuu2T0R@RgKLC6AzICF6KQFdJQYsWpaL7pRBKwti2XbZ9TmwwmRWGfbQAZNYUlR@/Wrq1S9kJv9/Sm/pBw "JavaScript (Node.js) – Try It Online")
Probably defeats the purpose of the challenge, but it is valid. Takes in a stringified list and outputs a stringified list. Replaces the `i`-th number (via string replacement) with the `i`-th element of the list of sorted numbers.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"DdiI˜{¾è¼ë®δ.V"©.V
```
Unfortunately, a simple flatten and replace/transliterate doesn't work on nested lists apparently. So instead, the default recursive approach I've used in multiple other [ragged-list](/questions/tagged/ragged-list "show questions tagged 'ragged-list'") challenges have been used.
[Try it online](https://tio.run/##yy9OTMpM/f9fySUl0/P0nOpD@w6vOLTn8OpD685t0QtTOrRSL@z//2hDIx2FaBNjHQVTw1ggK9oIyDQBsiyBHCOQXCwQAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVL6H8ll5TMiNNzqg/tO7zi0J7Dqw@tO7dFL0zp0Eq9sP86eoe2/o@ONtKJNtaJNtSJjgUCHYVoMx1TnehoSyDbHMQ1BMqbGOuYGoI40UbGOiaxOpY60UZGcA2WOiY6RrGxAA).
**Explanation:**
```
"..." # Create the recursive string explained below
© # Store it in variable `®` (without popping)
.V # Evaluate and execute it as 05AB1E code
# (after which the result is output implicitly)
D # Duplicate the current item
# (which will be the implicit input-list in the first iteration)
di # If it's a (non-negative) integer:
I # Push the input-list
˜ # Flatten it
{ # Sort it
¾è # Get the `¾`'th value of this sorted list
¼ # Then increase `¾` by 1
ë # Else (it's a list instead):
δ # Map over each inner list:
® .V # Do a recursive call for each
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 89 bytes
```
def f(L):a=re.split('(\d+)',L);a[1::2]=sorted(a[1::2],key=int);return''.join(a)
import re
```
[Try it online!](https://tio.run/##TU1NboQgFN5zipfZCCljAurM6MSeYG5AWZiIKa0FA3Th6e1jtE1JXvL98i1reveuui1h20YzwUQfrBv6YMq4zDbRgr6NL6zgD3YflOg6qfvoQzIjPSj/NGtvXWL3YNJ3cEVRfnjr6MCI/VowCsFsB4prJJMPMIN1mZQxjdaVwQzjbJ2JlHUELPfQw3zsn@D8CidGYAk4Qi2fqGWMbEpyUBWewNP4cu5Jfo0sEnXh0CBRrdYcrnsKhUvWrllrMSRyp8ZSI3Q2JMI6e/k7@X@gRoKqkHsOPVkhzF3ViL9VjGBS7h35JK3@AQ "Python 3.8 (pre-release) – Try It Online")
I/O are strings.
## How
This simply ignores the nesting by picking out groups of digits sorting them and putting them back into the gaps.
[Answer]
# [Factor](https://factorcode.org/) + `sorting.human`, 93 bytes
```
[ find-numbers [ string? ] partition natural-sort [ present ] map 2array round-robin ""join ]
```
[Try it online!](https://tio.run/##TY2xCsJAEER7v2JIHVMIKmphKTY2YnVcscaNniZ7ce8O9OvjKQpWwzCPeQ3V0etw2G93myWC1@jkXF1SR4IQNZeAwPfEUnP47eiVA0sEqdLzD6j4EZUCnMeNVbjFajQqzKyclsYsrC3nthgMGiensaTuyBpgvp41LHrK/9F5gVBMSu34bczIT2jRUY/Jxwv1Kf@oPzpBUVx9DjvU1LYZdxKHFw "Factor – Try It Online")
## Explanation
```
! "[6,5,[[9]],7]"
find-numbers ! { "[" 6 "," 5 ",[[" 9 "]]," 7 "]" }
[ string? ] partition ! { "[" "," ",[[" "]]," "]" } { 6 5 9 7 }
natural-sort ! { "[" "," ",[[" "]]," "]" } { 5 6 7 9 }
[ present ] map ! { "[" "," ",[[" "]]," "]" } { "5" "6" "7" "9" }
2array ! { { "[" "," ",[[" "]]," "]" } { "5" "6" "7" "9" } }
round-robin ! { "[" "5" "," "6" ",[[" "7" "]]," "9" "]" }
""join ! "[5,6,[[7]],9]"
```
Here's a slightly longer version that works on native sequences:
```
[ [ flatten natural-sort ] keep 0 -rot [ dup real? [ drop 2dup nth [ 1 + ] 2dip ] when ] deep-map ]
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 19 bytes [SBCS](https://github.com/abrudz/SBCS)
```
∊{a⊣(∊a)←⍺[⍋∊a←⍵]}⊢
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9TRVZ34qGuxxqOOrkTNR20THvXuin7U2w3ignlbY2sfdS0CAA&f=S1N41DfVK9jfTz3aSEch2hiIDYE4FggU1LnSELJmOgqmQIloy9hYHQVzNElDkF4ToGZTw1iQIiMg0wTIsgRyjIywmgeUMtFRMAKJAgA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
A tacit function which takes a ragged array.
# Explanation
```
∊{a⊣(∊a)←⍺[⍋∊a←⍵]}⊢ Pass in:
⊢ The input as is on the right
∊ The flattened input on the left.
{a⊣(∊a)←⍺[⍋∊a←⍵]} and do the following:
a←⍵ assign right arg to 'a'
⍺[⍋∊ ] sort the flattened input
(∊a)← assign this result to 'a', preserving structure
a⊣ return modified 'a'
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 37 bytes
```
@a=sort{$a-$b}/\d+/g;s/\d+/shift@a/ge
```
[Try it online!](https://tio.run/##K0gtyjH9/98h0bY4v6ikWiVRVyWpVj8mRVs/3boYTBdnZKaVOCTqp6f@/x9taKSjEG1irKNgahgLZEUbAZkmQJYlkGMEkosFgn/5BSWZ@XnF/3V9TfUMDA3@6xYAAA "Perl 5 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 38 bytes
```
1N→_a`\d+`?λ←_a1+→_a`\d+`?Ẏ⌊s←_a iS;øṙ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxTuKGkl9hYFxcZCtgP8674oaQX2ExK+KGkl9hYFxcZCtgP+G6juKMinPihpBfYSBpUzvDuOG5mSIsIiIsImBbMTIsIFs0MywgNTFdLCBbWzIzLCA0XSwgOSwgWzIyLCBbXV1dXWAiXQ==)
Thanks @lyxal for helping me a lot in chat. I've never posted any Vyxal answers before.
This is a port of my JavaScript solution. Takes a stringified list (provided with backticks around a Python-like list syntax).
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 86 bytes
```
a->i=#l=[];t(b->l=setunion([b],l),a);t(b->l[i++],a)
t(g,a)=iferr([t(g,b)|b<-a],e,g(a))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY7RCsIgFIbvewpZN8r0YrZVo9xjdCMSDuYQZIm5i6I36WYQ0TP1Nh1rkHD8_8_zn4P3l9fBHns_PQwSzzEatn0fNGusWDoh1S7iljVOnLs4DvY0YNkq6gjVZO5Im-cKcBFxDyKs6ULAMlFLbu2eaUU72mNNyLz9qr13F6wRa5APdohgswQZMilGkZQcrhVUAaXggKwpqlKrTrRJL0VKlRCrCvUdAluCqwE4_08ClxRxpeYfTNNPPw)
## Explanation
Here is a helper function to traverse a ragged-list, since we need to traverse the input twice:
```
t(g,a)=iferr([t(g,b)|b<-a],e,g(a))
```
`t(g,a)` traverses the ragged-list `a` and replaces each number in it with `g(a)`.
When `a` is a number, the list comprehension `[t(g,b)|b<-a]` will throws an error. `iferr` will catch this error and return `g(a)`.
When `a` is a list, `[t(g,b)|b<-a]` doesn't have an error. It returns a list of `t(g,b)`, where `b` runs through `a`.
Now look at the main function:
```
a->i=#l=[];t(b->l=setunion([b],l),a);t(b->l[i++],a)
```
This is an anonymous function with argument `a`.
First it initializes `l` to `[]`, `i` to `#l` (the length of `l`, which is `0`).
Now it can do the first traversal: `t(b->l=setunion([b],l),a)`. For each number `b` in the list, it set `l` to the union of `[b]` and `l`. PARI/GP doesn't have a separated type for sets. A set is just a sorted list without duplicate elements.
Then it does the second traversal: `t(b->l[i++],a)`. For each number `b` in the list, it increments `i`, and replaces `b` with the `i`'th element in `l`. This gives the final result.
] |
[Question]
[
# Objective
Given two Chinese ideographs meaning basic colors, output the ideograph that means the color resulting from mixing them.
# Basic colors
The basic colors are:
* 靑(U+9751; blue)
* 赤(U+8D64; red)
* 黃(U+9EC3; yellow)
* 白(U+767D; white)
* 黑(U+9ED1; black)
# Mixed colors
* Mixing 靑(blue) and 赤(red) yields 靘(U+9758; purple).
* Mixing 赤(red) and 黃(yellow) yields 熏(U+718F; orange).
* Mixing 黃(yellow) and 白(white) yields 硅(U+7845; beige).
* Mixing 白(white) and 黑(black) yields 黻(U+9EFB; grey).
* Mixing 黑(black) and 靑(blue) yields 黯(U+9EEF; deep blue).
* Mixing 靑(blue) and 黃(yellow) yields 綠(U+7DA0; green).
* Mixing 黃(yellow) and 黑(black) yields 騮(U+9A2E; brown).
* Mixing 黑(black) and 赤(red) yields 紫(U+7D2B; wine red).
* Mixing 赤(red) and 白(white) yields 紅(U+7D05; pink).
* Mixing 白(white) and 靑(blue) yields 碧(U+78A7; sky blue).
*(This scheme of color terms is historical, and it doesn't reflect the modern usage of Chinese.)*
To summarize in Unicode points:
```
9751, 8D64, 9758
8D64, 9EC3, 718F
9EC3, 767D, 7845
767D, 9ED1, 9EFB
9ED1, 9751, 9EEF
9751, 9EC3, 7DA0
9EC3, 9ED1, 9A2E
9ED1, 8D64, 7D2B
8D64, 767D, 7D05
767D, 9751, 78A7
```
# Rules
I/O format is flexible. In particular, I/O in Unicode points is okay, and outputting trailing whitespace is permitted.
Mixing colors is commutative. It is assumed that the two inputted basic colors are different.
In any case, an input not fitting into your format falls in *don't care* situation.
# Examples
* Given 靑 and 白, output 碧.
* Given 赤 and 白, output 紅.
[Answer]
# [Python](https://www.python.org), 60 bytes
*-1 byte thanks to Neil*
```
lambda a,b:' 碧紅騮熏綠硅紫黯黻靘'[abs(a-b)%90%11]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3bXISc5NSEhUSdZKs1BWeL1r-fEvryxXrnrf1P9-24PnC1udbVr_cvf7l7t0v585Qj05MKtZI1E3SVLU0UDU0jIWYcYtRsSi1IMc2Olrp5dyJSjpKL7YuAZJADUqxOlzRMO7uZiAJNBciCOXO3AsiF7ZCBCHcl7sngsndMJVg7lyI4HqoIJQLNmTbAmQzoepXrEPWDnED0DPIToLavgXVdrDJwIBQio3l4krLLwIGjUKSjkKyQmaeAsifVlwKQFCUWqxgq5CmkV-UopGoqaMAopM0NcFyBUWZeSUaUG06IKWakJBasABCAwA)
Takes input in Unicode codepoints (integers), and returns a string.
### Explanation
Basically, the idea is to "hash" the 2 input values and index into a string of possible outputs. `abs(a-b)%90%11` resulted in 10 different indexes for the 10 possible inputs. [Generation script](https://ato.pxeger.com/run?1=XVLNSgMxEAaPeYohIuxClO5JK6wXH2NZZLtN3UiarPtT1KvoVbz5Q6GKfyDopXopvogvUPsWTpJdqOYwZL7MfDPzTW6f8uMq02oyeayrwfrW98rNoNBDSLWUPK2EViWIYa6LCnZ1rSpeEFLwXIZRRBfjS8roz8cD2sX4isaMRK07O0U7P79wYONefxl7d-ZA5y5ml9bO2kjrjh343oCNa0k-J8ucTfzL23K662E-fV1uqak-_VvdMs_vnxGMCRmFUdIrPV30vcSHdTCXnu_DQBeQMOgxSEEoMAJgNKWUmBdhsUTtcy9gQQePv00AT-oUg7DVzouO1sRa0LGERyZtFPs2VAxAcuU1GT7sQNdxmJMXQlWeYC0h-xPr20bIKgSbQRd7K2tZlYYb69RKHNYcRomseWmrVhmHoe7XUgPNkjKjRKi-SAU-h4DtGZJ_HRJpnhy0tzRrx4-JyTLLx1XjYnGNuDRcES4E5UexjbTEqpRmDCtxy3kicq9k0FZu5JKRDYiRMs0IcVNTunGghfIkzum-aPNT2x_7Cw)
[Answer]
# [Wenyan (文言)](https://github.com/wenyan-lang/wenyan), 237 bytes
-33 bytes thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh).
```
吾有一術名之曰色欲行是術必先得二數曰「甲」曰「乙」乃行是術曰加甲以乙除其以百六六所餘幾何除其以十一所餘幾何夫『靘黯碧熏硅硅紫紅黻綠』之其乃得矣是謂「色」之術也
```
Expects two code points.
Based on [@Arnauld's Javascript answer](https://codegolf.stackexchange.com/a/263413/9288), but uses `(a+b)%166%11` instead of `a*b%25%11`, because Wenyan is 1-indexed.
You can try it on [this Online IDE](https://ide.wy-lang.org/). Here is a full test program:
```
吾有一術名之曰色欲行是術必先得二數曰「甲」曰「乙」乃行是術曰加甲以乙除其以百六六所餘幾何除其以十一所餘幾何夫『靘黯碧熏硅硅紫紅黻綠』之其乃得矣是謂「色」之術也
有數三萬八千七百三十七。名之曰「靑」。
有數三萬六千一百九十六。名之曰「赤」。
有數四萬零六百四十三。名之曰「黃」。
有數三萬零三百三十三。名之曰「白」。
有數四萬零六百五十七。名之曰「黑」。
施「色」於「靑」於「赤」。書之。
施「色」於「赤」於「黃」。書之。
施「色」於「黃」於「白」。書之。
施「色」於「白」於「黑」。書之。
施「色」於「黑」於「靑」。書之。
施「色」於「靑」於「黃」。書之。
施「色」於「黃」於「黑」。書之。
施「色」於「黑」於「赤」。書之。
施「色」於「赤」於「白」。書之。
施「色」於「白」於「靑」。書之。
```
[Answer]
# JavaScript (ES6), 50 bytes
Expects two code points as `(a)(b)`.
```
a=>b=>"紫騮靘熏X綠黻紅硅黯碧"[a*b%25%11]
```
[Try it online!](https://tio.run/##dVJfS9tQFH/vpzhIpTfaRVssrQupVKxvwl6EwSrrTXLN7hpuQhKXlZInqU8DEfbgwIKOwQRBX6oIYV/GlyxP@wjdTdrGUNKXXHLP@Z3fn3M/4y/YUW1quW@YqZHJsTzBclORmyvh@C66vY9Gl@HZ@fvw6ToKgnA8DG@GUfAQ/vy98gGvKavV2mqlcjSRuoUD@pUyHaLRBVKMEyIAZhr8ffyFbKIJ0KfE0BxevUSH69v1WkMC68S2DCKIc2TaGwOj4BT1iWGYXorlMji2XmnsS2DamOkZbLY9hoc//iDvE3XJK/pmGKMbWzUJFEKz4EzzlDp2gNXeq@ogiFW393cl0G3Sz/KmvQk0NZ8iHxJkm2vWCLEgqYr5YeV5frqOVe@1NhNmwpZbzpF9ex@Tt6ptbtk2PbZU9@Ka@OoT2io37FFGIC7mLyon6XGS9N4mT9qirLc86MW0@KtKdtSqS@D0@vOwugXRJhZXS9DGbBIShQ7qeOud6aTM72wUv9nQy4A@lgGXQSmDKoDchEEBwCAu9@OADMcIiyp/9O9MytyWiwQBKQsXUoEjVJM5pkFEw9RRd6agOMB@wl0cKP6ctTjgg/3pAbIMKuxA6d/z@cvVd/4twVsovYy@lfwun@sLk/8 "JavaScript (Node.js) – Try It Online")
### How?
Short modulo chains exist for all simple commutative operations ([addition](https://tio.run/##dVLNattAEL77KYbg4F3sKomJa7dCLi5xboVeAoW41Ctpo24tVkJSqhqjU3BPhVDoIYUYkhBooJBc3FAQfZlcVJ36CO5KthVh5IsW7cw338/sB/KRuJrDbO8Jt3Q6O1JmRGmrSnsjuhxH03Echm@i@4t4chaHd9Hn0/jmNpr@jK5@bBwiUlXxZuPp5k797Uzul16xT4wbEE@@ItU8phgI1@Hvr2vkUB3DkFFTd0X1DB1UnzUbLRnsY8c2KZaWyKw3AcbhCRpS07T8DCvoBba509qXwXIIN3LYfHsCj77/Qf575tFH9OU4Qbd2GzKolOXBueY5deKAaINH1WGYqO7uv5TBcOgwz5v1ptDMfIa8S5FdoVmn1Ia0KhWHVeT5/iJRvdfZTpkpX2@5QPbNbULeqXeFZcfy@Vrdq2sSO05p68KwzziFpFi8qIKkp2nSe9siaZvxwfqgV9MS7yrdUacpgzsYLsPqlySH2kItRVuLSUjCPdTzq735pNzvYpS42TJqgN7VgNRArYGGQWnDqARgUk/4cUGBI0QkTTz71xbjXsdDGCN15UIuCYRmcdcyqWRaBuovFJRHJEi5yyM1WLKWR2JwMD9AUUCDF1D59/v04fyb@FbgOVQeJl8qQV/MDfDsPw), multiplication, [XOR](https://tio.run/##dVLNattAEL77KYbg4F3iKj80tVMhF5c4t0AvgULc1itpo24tVkJSqhijU3BPgVDoIYEaklJoIJBcnFAQfZlcFJ3yCO5KthVh5IsW7cw338/sF/KVuJrDbO8Ft3Q6PlDGRGmoSmMpHp5Fo@v46iYaDaJvp@/jMIzD2@hyEN1fRL/@LO0j8lHFy1u15fVXH8Zyp7TLjhg3IB5@R6p5SDEQrsPj3W/kUB1Dj1FTd0X1DO2tbNU26zLYh45tUizNkFlvAozDY9Sjpmn5GVaoENjaen1HBssh3Mhh8@0JPDr/h/zPzKPP6MtBgq6/3JRBpSwPzjVPqBMHROs@qw7DRHVr560MhkN7ed6sN4Vm5jPkbYpsCc06pTakVak4rCLP9xeJ6u3mWspM@WLLBbKvbhLy5kZLWHYsny/UPb8msfmUdkMY9hmnkBSLF1WQ9ChNentNJG0z3l0c9Hxa4l2lO2rWZHC7vVlYnZLkUFuopWh1OglJuI3a/kp7Min3Ox0lblaNKqBPVSBVUKugYVAa0C8BmNQTflxQ4AARSRPP/p3FuNf0EMZInbuQSwKhWdy1TCqZloE6UwXlPglS7nJfDWas5b4YHEwOUBTQ4A1Unv6ePvz8Ib4VeA2Vh@FJJeiIuQEe/wc) and even [OR](https://tio.run/##dVLNattAEL77KYbg4N3GUf6xWyEHlzi3Qi491aVeSRt1Y7ESkhLVuDoV9xQIhR5SqCEphQYCycUJAZGXyUXVqY/grmRbEUa@aNHOfPP9zB6RE@JqDrO9VW7pdHyojInSUJXGUnx1E309i@4vostBPDyPRtfRrz9xeBuHYTQaLL1D5LOKX2wv17aWN7bej@VO6Q37xLgB8fAbUs1jioFwHf7e/UYO1TH0GDV1V1TP0duVl7Wdugz2sWObFEszZNabAOPwC@pR07T8DCv0CGxto74vg@UQbuSw@fYEHv14RP5H5tFn9OUgQde3d2RQKcuDc80T6sQB0brPqsMwUd3afy2D4dBenjfrTaGZ@Qx5myJbQrNOqQ1pVSoOq8jz/UWieq@5njJTvthygeyrm4S8udkSlh3L5wt1z69JrDul3RSGfcYpJMXiRRUkPUqT3lsXSduMdxcHPZ@WeGLpjpo1GdxubxZWpyQ51BZqKVqbTkISbqO2v9KeTMr9TkeJmzWjCuhDFUgV1CpoGJQG9EsAJvWEHxcUOERE0sS7P7AY95oewhipcxdySSA0i7uWSSXTMlBnqqDcJ0HKXe6rwYy13BeDg8kBigIa7ELl38PZ08/v4luBV1B5Gp5Wgo6YG@Dxfw)). The benefit of using a multiplication is that no parentheses are required.
It's also interesting to note that we still have enough information when reducing both code points modulo 9:
```
a=>b=>"XX碧紫紅黯靘黻X綠X硅騮XX熏"[a%9^b%9]
```
[Try it online!](https://tio.run/##dVJPS@NAFL/3Uzyk0gl2oytK2w3p0sV6E7wsFKxrJ8mYnW2YhCSaLSUn6Z4EETwoWNBFWGFBL11ZCPtlvGRz8iPUSdrGUNJLhsx7v/f78@YbPsaOalPLfXdcHR/KYyzXFbm@1GqFP3@Fo9/haBAFj9HwMgqCVvh00wpvB9H9Ay//OFvaw8u1L8pybX8sdQo79DtlOkTDc6QYR0QAzDT4/@cO2UQToEeJoTm8eok@r9Qqm1UJrCPbMoggzpBpbwyMghPUI4ZheimWM3Js5X11WwLTxkzPYLPtMTy8@oe8r9Qlb@jbQYyubmxKoBCaBWeaJ9SxA6x231QHQay6uf1JAt0mvSxv2ptAU/Mp8jFBNrlmjRALkqqYH1ae56ebWPVWYy1hJmyx5RzZ9w8xeWO9yS3bpscW6p5fE198QrvODXuUEYiL@YvKSXqUJL21xpO2KOsuDno@Lf7kkh01KhI43d4srE5BtInF1RK0Op2ERKGN2t5KezIp8zsdxW9W9TKggzLgMihlUAWQ69AvABjE5X4ckOEQYVE1NbJrUuY2XCQISJm7kAocoZrMMQ0iGqaOOlMFxT72E@5iX/FnrMU@H@xPDpBlUOEjlF7@nj1fX/BvCT5A6Xl4WvI7fK4vjF8B "JavaScript (V8) – Try It Online") (53 bytes)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
α90%•MÚöć'wSlé∞‘cP₃$«¢Γå"α•5ô0šsè
```
I/O as codepoint integers.
Port of [*@SuperStormer*'s Python answer](https://codegolf.stackexchange.com/a/263400/52210).
[Try it online](https://tio.run/##AU0Asv9vc2FiaWX//86xOTAl4oCiTcOaw7bEhyd3U2zDqeKInuKAmGNQ4oKDJMKrwqLOk8OlIs6x4oCiNcO0MMWhc8Oo//8zODczNwozNjE5Ng) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W6WKvpKChZH@4HcjQVHjUNklByT7h/7mNlgaqjxoW@R6edXjbkXb18uCcwysfdcx71DAjOeBRU7PKodWHFp2bfHip0rmNQGWmh7cYHF1YfHjFf5hxy4GmKen8j45Wejl3opKO0outS5RidaLBtI7Sy93NYB6I1lF6PnMvmAeiQXIToXIgfSDdYB7YFFR9qCpRbUAzE2RKLAA).
**Explanation:**
```
α # Get the absolute difference of the two (implicit) input codepoint-integers
90% # Modulo-90
•MÚöć'wSlé∞‘cP₃$«¢Γå"α•
'# Push compressed integer 30887320053947029071321603078932043406874069938744
5ô # Split it into parts of size 5
0š # Prepend a dummy 0
s # Swap so the earlier abs(a-b)%90 is at the top of the stack
è # 0-based modular index it into this list
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•MÚöć'wSlé∞‘cP₃$«¢Γå"α•` is `30887320053947029071321603078932043406874069938744`.
---
Since I was curious: using the actual unicode characters would result in an 18-character program, but it would be 40 bytes in UTF-8 encoding:
```
α90%" 碧紅騮熏綠硅紫黯黻靘"è
```
Input as codepoint integers, output as Chinese character.
[Try it online.](https://tio.run/##AT0Awv9vc2FiaWX//86xOTAlIiDnoqfntIXpqK7nho/ntqDnoYXntKvpu6/pu7vpnZgiw6j//zM4NzM3CjM2MTk2)
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~31~~ 30 bytes (60 nibbles)
*Edit: -1 byte thanks to xigoi*
```
=%!=$@90:`D 40960 $ 1c179f3cec8cb05803cd69a25df3d95bf5d7758
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWN61tVRVtVRwsDawSXBRMDCzNDBRUFAyTDc0t04yTU5MtkpMMTC0MjJNTzCwTjUxT0oxTLE2T0kxTzM1NLSBGQE1aG21sYGxsrGNsYW5sHgsVBAA)
Port of [SuperStormer's Python answer](https://codegolf.stackexchange.com/a/263400/95126) - upvote that.
Input and output as Unicode points.
```
=%!=$@90:`D 40960 $
`D # interpret the appended data
40960 # in base 40960
# (so generates 10x 2-byte values);
: $ # append the input
= # and index into this list using
!= # absolute difference
$@ # of inputs
% 90 # modulo-90
```
---
# [Nibbles](http://golfscript.com/nibbles/index.html), 44 bytes (88 nibbles)
```
=%!=$@90.`/3`D256+' '$ c78287c79465c9888ec7666fc79680c78165c7948bc99b8fc99b9bc97d7858
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWN0NtVRVtVRwsDfQS9I0TXIxMzbTVFdRVFJLNLYwszJPNLU3MTJMtLSwsUpPNzczM0oAiZhYGQFlDoDhQ1iIp2dIyySINRFoC2eYp5hamFhDDoXZsjFZSfzl3orqSjpL6i61L1JVioRIA)
Input and output as Chinese characters.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~55~~ 51 bytes
```
F²⊞υ﹪﹪℅S³¹¦⁵℅I§⪪§⪪”)‴φ<ΦηA∧⌊✂⮌.\`P⁷⸿⁼DT⟦8'R&C”¶⌊υ⁵⌈υ
```
[Try it online!](https://tio.run/##XY5BCsIwEEX3niJ0NYEKaRNNiitx5UIU3HYTWrWBmJY0EfeewAN4Ek/kKeIgunEWf@a/gT/TdNo3vbYpHXtPoKRkF8cOYk42fRttD9@29a1x2sLaDTHsgzfuBJTmhBcoM0oXkx2yACvM0004eFjpMcAyrF17uMJ@sObfZbxkbCbYvKo4kwpFKVk7BEriSnBeCclqV1ZMFrws5jhzJYXIcpLVLsPDG@PMOZ4h0s8XCPT1B7AWKb0e98nreUvTi30D "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞υ﹪﹪℅S³¹¦⁵
```
Input the code points and reduce them modulo `31` and `5` to get them into the range `0-4`.
```
℅I§⪪§⪪”)‴φ<ΦηA∧⌊✂⮌.\`P⁷⸿⁼DT⟦8'R&C”¶⌊υ⁵⌈υ
```
Look up the resulting character in a compressed lookup table.
A port of @SuperStormer's method is also 51 bytes:
```
§ 碧紅騮熏綠硅紫黯黻靘﹪↔⁻℅S℅S⁹⁰
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjfrA4oy80o0HEs881JSKzSUFJ4vWv58S-vLFeuet_U_37bg-cLW51tWv9y9_uXu3S_nzlDSUfDNTynNyddwTCrOzyktSdXwzcwrLdbwL0rJzEvM0fDMKygtCS4BGpquoampo4BdHCRjaQCkrJcUJyUXQx2zPFpJtyxHKXb5y7kTuV7uboaIAgA "Charcoal – Attempt This Online") Link is to verbose version of code. (TIO unnecessarily quotes the string literal, costing three bytes.)
[Answer]
# [Scala 3](https://www.scala-lang.org/), 51 bytes
```
a=>b=>"黻綠黯熏紅紫硅碧騮靘"(a*b%6231%10)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sODkxJ9F4wU1bh9zEzDyFlNQ0BRBDQ9NKITQvs0TBVqGaS0GhLDFHIS0_30rBOSOxSMHWDkpBuQrVS0tL0nQtbhon2tol2dopvdy9-_m2BS93r3_e1v98S-vzLaufL2x9vmj5yxXrXs6doaSRqJWkamZkbKhqaKAJ0XqLsbFWQQFoU0FRZl5JTp4G0DYN9ZdzJ6praqi_2LpEXVPB1lYBKDBDXRNdFVgaqHh3M1QV0FZMVWBpDfXnM_fCVC1sxVQFlgYpngizcfdubGaB3QV2HlTVeiyqIK5Hcte2BTjdhWTjinU4bUSEBDBMcYYEkh-34PEj3PXAmAGqqoXExIIFEBoA)
Same modulo trick as [@SuperStormer](https://codegolf.stackexchange.com/users/70761/superstormer) but uses multiplication instead.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 53 bytes
```
->n{"紅熏紫 碧綠黯硅靘 黻騮"[n.sum%23%13]}
```
[Try it online!](https://tio.run/##VZHNasJAFIX3eYqLIrS0FX8qWoKFFGPpomjTZCUuGhwlaMcQCSKlK7Hb4q5dCFoKFQq6sW5CnyfNU6R3ZjILd@dycr97Tsbz7UncrcZnl/QpFe5m4ctruPuG8OMr3C@jYBuuZtHiDSAKgmi9SbVoduQ/ZgrFTL7Yfo7Tpn5vQtNoXBvareJCq9tKRYv5389nqn2KGkUUTIVGEb7/ogYcUEXBPBlQ4ZIcFnOxIpzpwWcCDIJ8SGOAtqJUbdJzqGLod9aNodegYZlNy1RkKkgD1jmyTi7KpYoKru@5A3KcVWRS9PEPoF/OV@oqDL0H2uN@kp75qxnzK@clFWziCDvpw/BBwPB6/UqFnkcmYpkX5O6WuzrCO4S4YA98wRe1GX@/ZPyaluMAQpPzkr/eMIJW0PG8NxwntmyHj8e3C3h@7FACHukk/WT@Hc9fy2F@16F9GV8ExIfn7bSyCqP@ROarEtpR4n8 "Ruby – Try It Online")
A function which Takes a string with the two input codepoints, finds a checksum (which for some reason is always even) and performs a mod-fold to hash it down to a number 0..12. This is then used as in index to look up in a string. The output is then returned as a single character.
The imperfect hash means there are 3 wasted spaces in the string, but that only counts as 3 bytes total (the Chinese characters on the other hand are 3 bytes each.)
[Answer]
# [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), 105 bytes
Port of [@SuperStormer's Python answer](https://codegolf.stackexchange.com/a/263400/110802) in Mathematica.
---
Golfed version, [Try it online!](https://tio.run/##XVFBS8MwGL3vV4ScIzg9aRkoA08KHnYLYSRdZgvrKl1vpSepV9lND4NNBAfCdqm7BH9P7K@oX5ZW2hbK63vhe@/la8BjTwY89l1ellPKx0SM2eXgJgqDoccj7sYyGoYTeTUKW5xi/f6p86zY7vTziz6s9SbT@Veh9oVSxeoVM0rvwsnxvRYLyk8EIxenjPT7jLEyko8zNEBJgovVEhOEf78/DJjJlKDkn6snAxBh5Zq//Rxhk1m54oUyXj0ED3yremRpnS2ofSXX3Boe1q2Aemi7a5pY56oa3LZVte6UdzrZHNgWTlOn1xtxMZOUw@XNDij1CYKNOEg0lTOjuE3l3CiQH8kFyFPa/R0c9g0@BHUPhD2w0/eRP48phz4ISokK3QrBGwwSSLuV84fYoyadpcwp/wA)
105 bytes, it can be golfed much more.
```
f[a_,b_]:=FromCharacterCode@ToCharacterCode["碧紅騮熏綠硅紫黯黻靘"][[Mod[Mod[Abs[a-b],90],11]]]
```
Ungolfed version. [Try it online!](https://tio.run/##ZVExa8JAGN3zKz5uUkihaadWHIrQqYUObschd/GsgjElZgtxKXYtbu0gaClUKOiiLkd/zzW/Iv2ul5Rop3ffO7733r0LeNyXAY8HPs/zHuUdF0SHwWUTHIDrKAxafR5xP5ZRK@xKiiS0w0OO6LcPvZ1mq7V@etb7hV5O9fYzU5tMqWz@QhiltdqVGFMOJyDY5DbsTuDiFOrmBBPPqzPGGo4TyYchNCFJSDafERfI9@7dgNFIXUj@ZvVoAM0sXc6vX7@wnFq6mDNltExuc1blyswqW1Cbgi5nK7hfHBiUS6t1VcQqF9Hw3QdRy0zbo0zWB3sjaYovb3MxlFhPE0wHlA5c8LASEFXmzDB@lTk3DPpHcox0jx5/DMfmUcf992PCXtjtu2gwiinHPIChRIF@gaiNAgm63cjRfdynxp2lrJHnPw)
```
f[a_, b_] :=
FromCharacterCode[
ToCharacterCode["碧紅騮熏綠硅紫黯黻靘"][[((Abs[a - b]~Mod~ 90 )~Mod ~11)]]];
repl = {{"靑", "赤", "靘"}, {"赤", "黃", "熏"}, {"黃", "白", "硅"}, {"白", "黑",
"黻"}, {"黑", "靑", "黯"}, {"靑", "黃", "綠"}, {"黃", "黑", "騮"}, {"黑",
"赤", "紫"}, {"赤", "白", "紅"}, {"白", "靑", "碧"}};
Table[a = repl[[i, 1]]; b = repl[[i, 2]]; c = repl[[i, 3]];
res = f[ToCharacterCode[a][[1]], ToCharacterCode[b][[1]]];
Print[a, " ", b, " ", c, " ", res], {i, Length[repl]}];
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 61 bytes
```
f(a,b){a=L" 碧紅騮熏綠硅紫黯黻靘"[abs(a-b)%90%11];}
```
[Try it online!](https://tio.run/##nZHNSsNAFIXXzlNcRwoz9Md2p6QRpOAqS13VUCbTjJ0QE0kigiUrqVvpTheCiqAg6Ka6CT5PzFPEhLaW/qn0LO7AuXO/c@Hy8hHnaSoIKxm0y1QNQ/zwFA96yfNrfHkVf9zF97148JJEb0kUJbfXuMkMn7CyQQvb1UKtpithuiEdbp@2TajbLme2WensoInnB@22KeY86eYWkk4Ax0w6hKIugpHOeId5rQAM5kve4q7ten5TBxU0nNz2v94fk@givvlMoj5W0JpvBsNcojVau5pWAtyoHOzvbWGqoB@mcD0geZrMOFUle@pAfHluumIqB8pQo7AJC1rNqq5AsSgpTFadw1tDvLUy3lqEH0uKLAXWVfj111gnXraRILhgcyhCXtW8Hjq49OfsSFMLSn21Oev/c2R0eyrIbPQsk2bnXYYJ0XInRGH6DQ "C (gcc) – Try It Online")
Port of [@SuperStormer's Python submission](https://codegolf.stackexchange.com/a/263400/108622)
Thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil) for knowing how to print multibyte characters, and to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for pointing out that my byte count was wrong.
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 32 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ṛ90%»æḳṫƈe:÷/ċWƊ&ıZbȥƙNỵ`@»Ṙ⁵0Ƥi
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPUMlRTIlODIlQUNoJUUxJUJBJUI4JmNvZGU9JUUxJUI5JTlCOTAlMjUlQzIlQkIlQzMlQTYlRTElQjglQjMlRTElQjklQUIlQzYlODhlJTNBJUMzJUI3JTJGJUM0JThCVyVDNiU4QSUyNiVDNCVCMVpiJUM4JUE1JUM2JTk5TiVFMSVCQiVCNSU2MCU0MCVDMiVCQiVFMSVCOSU5OCVFMiU4MSVCNTAlQzYlQTRpJmZvb3Rlcj1OREMlMkMmaW5wdXQ9JTVCJyVFOSU5RCU5MSclMkMlMjAnJUU4JUI1JUE0JyU1RCUwQSU1QiclRTglQjUlQTQnJTJDJTIwJyVFOSVCQiU4MyclNUQlMEElNUInJUU5JUJCJTgzJyUyQyUyMCclRTclOTklQkQnJTVEJTBBJTVCJyVFNyU5OSVCRCclMkMlMjAnJUU5JUJCJTkxJyU1RCUwQSU1QiclRTklQkIlOTEnJTJDJTIwJyVFOSU5RCU5MSclNUQlMEElNUInJUU5JTlEJTkxJyUyQyUyMCclRTklQkIlODMnJTVEJTBBJTVCJyVFOSVCQiU4MyclMkMlMjAnJUU5JUJCJTkxJyU1RCUwQSU1QiclRTklQkIlOTEnJTJDJTIwJyVFOCVCNSVBNCclNUQlMEElNUInJUU4JUI1JUE0JyUyQyUyMCclRTclOTklQkQnJTVEJTBBJTVCJyVFNyU5OSVCRCclMkMlMjAnJUU5JTlEJTkxJyU1RCZmbGFncz1W)
Port of @SuperStormer's Python answer. I/O as codepoints.
Just in case you're wondering:
## [Thunno 2](https://github.com/Thunno/Thunno2), 39 bytes (UTF-8)
```
-A90%" 碧紅騮熏綠硅紫黯黻靘"i
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPUMlRTIlODIlQUNoJUUxJUJBJUI4JmNvZGU9LUE5MCUyNSUyMiUyMCVFNyVBMiVBNyVFNyVCNCU4NSVFOSVBOCVBRSVFNyU4NiU4RiVFNyVCNiVBMCVFNyVBMSU4NSVFNyVCNCVBQiVFOSVCQiVBRiVFOSVCQiVCQiVFOSU5RCU5OCUyMmkmZm9vdGVyPSZpbnB1dD0lNUInJUU5JTlEJTkxJyUyQyUyMCclRTglQjUlQTQnJTVEJTBBJTVCJyVFOCVCNSVBNCclMkMlMjAnJUU5JUJCJTgzJyU1RCUwQSU1QiclRTklQkIlODMnJTJDJTIwJyVFNyU5OSVCRCclNUQlMEElNUInJUU3JTk5JUJEJyUyQyUyMCclRTklQkIlOTEnJTVEJTBBJTVCJyVFOSVCQiU5MSclMkMlMjAnJUU5JTlEJTkxJyU1RCUwQSU1QiclRTklOUQlOTEnJTJDJTIwJyVFOSVCQiU4MyclNUQlMEElNUInJUU5JUJCJTgzJyUyQyUyMCclRTklQkIlOTEnJTVEJTBBJTVCJyVFOSVCQiU5MSclMkMlMjAnJUU4JUI1JUE0JyU1RCUwQSU1QiclRTglQjUlQTQnJTJDJTIwJyVFNyU5OSVCRCclNUQlMEElNUInJUU3JTk5JUJEJyUyQyUyMCclRTklOUQlOTEnJTVEJmZsYWdzPVY=)
Input as codepoints, outputs the character.
#### Explanation
```
ṛ90%»...»Ṙ⁵0Ƥi # Implicit input
ṛ # Absolute difference
90% # Mod 90
»...»Ṙ # Compressed number
⁵ # Split into chunks of length 5
0Ƥ # With a 0 prepended
i # Index into the list
# Implicit output
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 33 bytes
```
ε90%»æ↲‡ẇf;ƈ0£Xġ'ɾ[c₆⟨OɖaA»S5ẇ0pi
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiQ8O3IiwizrU5MCXCu8Om4oay4oCh4bqHZjvGiDDCo1jEoSfJvltj4oKG4p+oT8mWYUHCu1M14bqHMHBpIiwi4oyKRENcIiIsIlsn6Z2RJywgJ+i1pCddXG5bJ+i1pCcsICfpu4MnXVxuWyfpu4MnLCAn55m9J11cblsn55m9JywgJ+m7kSddXG5bJ+m7kScsICfpnZEnXVxuWyfpnZEnLCAn6buDJ11cblsn6buDJywgJ+m7kSddXG5bJ+m7kScsICfotaQnXVxuWyfotaQnLCAn55m9J11cblsn55m9JywgJ+mdkSddIl0=)
Port of @SuperStormer's Python answer. I/O as codepoints.
#### Explanation
```
ε90%»...»S5ẇ0pi # Implicit input
ε # Absolute difference
90% # Mod 90
»...»S # Compressed number
5ẇ # Split into chunks of length 5
0p # With a 0 prepended
i # Index into the list
# Implicit output
```
[Answer]
# [Go](https://go.dev), 78 bytes
```
func(a,b rune)rune{return[]rune("紫騮靘熏X綠黻紅硅黯碧")[a*b%25%11]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BTcWCxOTsxPRUhdzEzDyuzNyC_KISPaW03BIlLq6yxCKFNNulpSVpuhY3_dJK85I1EnWSFIpK81I1QUR1UWpJaVFedCyIo6H0fMvqlyvWvZw743lbf8TzbQte7t79fEvr84WtL3evf75ouZJmdKJWkqqRqaqhYWwt1NT5IFPBdmtoKlRzFRRl5iYWZaYWK1jZKii9nDvxxdYlL3c3P5-59-XuiUpcaflFCvE6iSDJosQ8oKMR6quhkknYJTPTFBIVbZOArICizLySNA0l1eT3e7pBxFzV5Jg8JR0FoNd0FNJAPtTU5KoFQy6oMxcsgNAA)
Port of [@Arnauld's answer](https://codegolf.stackexchange.com/a/263413/77309).
] |
[Question]
[
Takuzu is a logic game in which you have to complete a grid with cells containing `0`s and `1`s. The grid must follow 3 rules:
1. No three horizontal or vertical consecutive cells can be the same.
2. There must be an equal number of `0`s and `1`s in each row and column.
3. No two rows can be the same, and no two columns can be the same.
Let's look at a finished grid:
```
0011
1100
0101
1010
```
As you can see, this board follows rule `1`, `2` and `3`. There are no three horizontal or vertical cells that are the same, all the rows and columns contain an equal number of `0`s and `1`s, and no two rows and no two columns are the same.
Let's look at a grid that isn't valid:
```
110100
010011
011010
101100
100011
001101
```
There's a bunch of problems with this grid. For example, row `5` has three `0`s in a row, and column `2` has three `1`s in a row, followed by three `0`s. Therefore, this is not a valid grid.
## Task:
Your task is to make a program which, given a 2D array of `n` \* `n` `0`s and `1`s, verifies the board to see if it's a valid, finished Takuzu board.
## Examples:
```
0011
1100
0101
1010
```
This board follows all the rules, and is therefore a valid Takuzu board. You must return a truthy value for this.
```
11
00
```
This is not a valid board - row `1` doesn't follow rule `2`. You must return a falsey value for this.
```
100110
101001
010101
100110
011010
011001
```
This is not a valid board, it fails (only) due to rule 3 - the first and fourth rows are the same.
```
110100
001011
010011
101100
100110
011001
```
This is not a valid board, it fails (only) due to rule 3 - the first and fourth columns are the same.
```
011010
010101
101100
010011
100110
101001
```
This is a valid board.
## Rules and Specs:
* You can assume that all boards are square of dimensions `n * n`, where `n` is a positive even integer.
* You can assume that all boards are finished.
* You may take input as a 2D array containing values signifying `0` and `1`, or as a string.
* You must output consistent truthy and falsey values for truthy and falsey boards, and the values representing "truthy" and "falsey" cannot be the same.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~20~~ 18 bytes
```
≠\≠,?¬{∋s₃=|∋ọtᵐ≠}
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1Hnghgg1rE/tKb6UUd38aOmZtsaIOPh7t6Sh1snAKVq//@PjjbQMdAx1DGM1YkGkkC2AZBlAGZBxMDs2Nj/AA "Brachylog – Try It Online")
### Explanation
```
≠ All rows are different
\ Transpose
≠ All columns are different
,? Append the list of rows to the list of columns
¬{ } It is impossible that:
∋ A row/column of the matrix…
s₃= …contains a substring of 3 equal elements
| Or that:
∋ọ The occurences of 1s and 0s in a row/column…
tᵐ≠ …are not equal
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~19~~ 18 bytes
```
S=‼(Tf§=LṁDum(ṁ↑2g
```
[Try it online!](https://tio.run/##yygtzv7/P9j2UcMejZBcjYc7Gx@1TTRK10w7tNzWB8hzKf3//390tIGOgY6hjmGsTjSQBLINgCwDMAsiBmbHxgIA "Husk – Try It Online")
1 byte saved thanks to H.PWiz!
The main idea is applying a series of transformations to the input that are identities for a valid board and checking if the final result is the same as the original input.
### Explanation
```
S=‼(Tf§=LṁDum(ṁ↑2g
m(ṁ↑2g in each line, take at most two items for each sequence of equal items
u remove duplicate lines
f§=LṁD keep only those lines where the sum of each element doubled is equal to the length of the line
T transpose the matrix (swap rows with columns)
‼ do all the previous operations again
S= check if the final result is equal to the original input
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
-*S;E3Ƥ€F$TȯQZµ⁺⁼
```
[Try it online!](https://tio.run/##y0rNyan8/19XK9ja1fjYkkdNa9xUQk6sD4w6tPVR465HjXv@//8fHW2gY6BjqGMYqxMNJIFsAyDLAMyCiIHZsbEA "Jelly – Try It Online")
-6 bytes thanks to [miles](https://codegolf.stackexchange.com/users/6710/miles) and [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
[Answer]
# Mathematica, 143 bytes
```
And@@Flatten@(((s=#;Equal@@(Count[s,#]&/@{0,1})&&FreeQ[Subsequences@s,#]&/@{{1,1,1},{0,0,0}})&/@#)&&(DeleteDuplicates@#==#)&/@{#,Transpose@#})&
```
**input**
>
> [{{0, 0, 1, 1}, {1, 1, 0, 0}, {0, 1, 0, 1}, {1, 0, 1, 0}}]
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), 127 bytes
```
a=input()
n=len(a)
b=zip(*a)
print[n/2]*n*2==map(sum,a+b)>len(set(a))==len(set(b))==n<'0, 0, 0'not in`a+b`>'1, 1, 1'not in`a+b`
```
[Try it online!](https://tio.run/##TYvBCsMgEETv@Qpvunah6rmbHwmBGAhUaDbSmEP783ZNKRSG4c0wk1/lvnGoNVLifBQDHdNjYROhm@mdsrFC@Zm4DHwNo2UbiNaYzX6sGC8z9G29L0UeQPQLcwt80w5Vk@atqMSTHKZee1RN/2Wtg3Ho0KMHNOLCTsid9O1OhvED "Python 2 – Try It Online")
Reads a list of *n* *n*-tuples as input.
I could output by exit code by writing `1/(…)` instead of `print…` but it feels scummy. Should I?
## Explanation
`n` is the size of the board; `b` is a list of columns (transpose of `a`). The rest is one long chained comparison:
* `[n/2]*n*2==map(sum,a+b)` checks rule 2. Each row and column should sum to n/2.
* `map(sum,a+b)>len(set(a))` is always true (list > int).
* `len(set(a))==len(set(b))==n` checks rule 3.
* `n<'0, 0, 0'` is always true (int < str).
* `'0, 0, 0'not in`a+b`>'1, 1, 1'not in`a+b`` checks rule 1. ``a+b`` is the string representation of all the rows and columns; for the example input on TIO it is
```
"[(0, 0, 1, 1), (1, 1, 0, 0), (0, 1, 0, 1), (1, 0, 1, 0), (0, 1, 0, 1), (0, 1, 1, 0), (1, 0, 0, 1), (1, 0, 1, 0)]"
```
The ``a+b`>'1, 1, 1'` in the center is always true since this string is guaranteed to start with `"["`, which is greater than `"1"`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~27~~ 25 bytes
```
Λ§&Λȯ¬VEX3§&Λ§=#0#1S=uSeT
```
Input is a list of lists and output is `1` for `True` and `0` for `False`
[Try it online!](https://tio.run/##yygtzv7//9zsQ8vVzs0@sf7QmjDXCGMw59ByW2UDZcNg29Lg1JD///9HRxvoGOgY6hjG6kQDSSDbAMgyALMgYmB2bCwA "Husk – Try It Online")
### Explaination
```
SeT Create a list with the input and itself transposed
Λ Is the following function true for all in the list
§& And the results of the following functions
Λȯ¬VEX3 Test for rule 1
§& The and of:
Λ§=#0#1 Test for rule 2
S=u Test for rule 3
```
### Test 1
```
Λȯ¬VEX3
Λ Is it True for all ...
V Are any of the ...
X3 Substrings of length 3 ...
E All equal
ȯ¬ Logical not
```
### Test 2
```
Λ§=#0#1
Λ Is it true for all that ...
§= The results of the two functions are equal
#0 Number of 0s
#1 Number of 1s
```
### Test 3
```
S=u
S= Is the result of the following function equal two its argument
u Remove duplicates
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~129~~ ~~89~~ 85 bytes
```
.+
$&,$&
O#$`.(?=.*,)
$.%`
.+
$&;$&
+`(01|10)(?=.*;)
1ms`(.)\1\1|\d,?;|(\D\d+\b).*\2
```
[Try it online!](https://tio.run/##HckxDoMwDEbh3ddoQHESWf67RhVL917AQ6hgYIChMObuacTy9KTvt17bMbcmkdyY3Eifhyvip5eExORkKHRT7hSLV1Qo35yZCPtZvLDBUG1JU67e3rZE@7IEe7amChCgSgrt1/sH "Retina – Try It Online") Outputs 0 for valid, 1 for invalid. Edit: Saved 4 bytes thanks to @MartinEnder. Explanation:
```
.+
$&,$&
```
Duplicate each row with `,` separators.
```
O#$`.(?=.*,)
$.%`
```
Transpose the first duplicate.
```
.+
$&;$&
```
Duplicate again, this time with `;` separators.
```
+`(01|10)(?=.*;)
```
Delete all matching pairs of digits that precede a semicolon.
```
1ms`(.)\1\1|\d,?;|(\D\d+\b).*\2
```
Check to see whether any column or row fails any of the rules; `(.)\1\1` checks for three identical digits in a row, `\d,?;` checks for an unpaired digit and `(\D\d+\b).*\2` checks for a duplicate.
[Answer]
# [Pyth](https://pyth.readthedocs.io), 31 bytes
Thanks a lot to [@Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun).
```
.Asm++mqy/k\0lQdm<hk3srL8d{Id,C
```
**[Verify all the test cases](https://pyth.herokuapp.com/?code=.Asm%2B%2Bmqy%2Fk%5C0lQdm%3Chk3srL8d%7BId%2CC&input=%5B%220011%22%2C%221100%22%2C%220101%22%2C%221010%22%5D&test_suite=1&test_suite_input=%5B%220011%22%2C%221100%22%2C%220101%22%2C%221010%22%5D%0A%5B%220011%22%2C%221100%22%2C%220101%22%2C%221010%22%5D%0A%5B%2211%22%2C%2200%22%5D%0A%5B%22110100%22%2C%22010011%22%2C%22011010%22%2C%22101100%22%2C%22100011%22%2C%22001101%22%5D&debug=0) or [Try it here!](https://pyth.herokuapp.com/?code=.Asm%2B%2Bmqy%2Fk%5C0lQdm%3Chk3srL8d%7BId%2CC&input=%5B%220011%22%2C%221100%22%2C%220101%22%2C%221010%22%5D&test_suite_input=%5B%220011%22%2C%221100%22%2C%220101%22%2C%221010%22%5D%0A%5B%220011%22%2C%221100%22%2C%220101%22%2C%221010%22%5D%0A%5B%2211%22%2C%2200%22%5D%0A%5B%22110100%22%2C%22010011%22%2C%22011010%22%2C%22101100%22%2C%22100011%22%2C%22001101%22%5D&debug=0)**
---
# [Pyth](https://pyth.readthedocs.io), ~~48 46 44~~ 42 bytes
This is the initial solution.
```
&{IQ&{I.TQ.Am&q/d\0/d\1!+/d*3\0/d*3\1sC,.T
```
**[Verify all the test cases](https://pyth.herokuapp.com/?code=%26%7BIQ%26%7BI.TQ.Am%26q%2Fd%5C0%2Fd%5C1%21%2B%2Fd%2a3%5C0%2Fd%2a3%5C1sC%2C.T&input=%5B%220011%22%2C%221100%22%2C%220101%22%2C%221010%22%5D&test_suite=1&test_suite_input=%5B%220011%22%2C%221100%22%2C%220101%22%2C%221010%22%5D%0A%5B%220011%22%2C%221100%22%2C%220101%22%2C%221010%22%5D%0A%5B%2211%22%2C%2200%22%5D%0A%5B%22110100%22%2C%22010011%22%2C%22011010%22%2C%22101100%22%2C%22100011%22%2C%22001101%22%5D&debug=0) or [Try it here!](https://pyth.herokuapp.com/?code=%26%7BIQ%26%7BI.TQ.Am%26q%2Fd%5C0%2Fd%5C1%21%2B%2Fd%2a3%5C0%2Fd%2a3%5C1sC%2C.T&input=%5B%220011%22%2C%221100%22%2C%220101%22%2C%221010%22%5D&test_suite_input=%5B%220011%22%2C%221100%22%2C%220101%22%2C%221010%22%5D%0A%5B%220011%22%2C%221100%22%2C%220101%22%2C%221010%22%5D%0A%5B%2211%22%2C%2200%22%5D%0A%5B%22110100%22%2C%22010011%22%2C%22011010%22%2C%22101100%22%2C%22100011%22%2C%22001101%22%5D&debug=0)**
```
&{IQ&{I.TQ.Am&q/d\0/d\1!+/d*3\0/d*3\1sC,.T Full program with implicit input.
{IQ Is the input invariant under deduplicating?
& {I.TQ And is its transpose invariant too?
.TQ Transpose.
Q The input.
sC, Zip the above, [^, ^^] (and flatten).
& And is the following condition met?
.Am All elements are truthy when mapping over ^^.
q/d\0/d\1 There are as many 0s as 1s.
& !+/d*3\0/d*3\1 And there are no runs of 3 equal elements.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 27 bytes
```
,G@?!]tEqts~w7BZ+|3<bXBSdvA
```
Input is a matrix containing `0` and `1`. Output is `0` for falsy, `1` for truthy.
[**Try it online!**](https://tio.run/##y00syfn/X8fdwV4xtsS1sKS4rtzcKUq7xtgmKcIpOKXM8f//aEMFQwUDMDawhjGApCGEA5WzhjKgyiCK4MrgCmMB) Or see test cases: [**1**](https://tio.run/##y00syfn/X8fdwV4xtsS1sKS4rtzcKUq7xtgmKcIpOKXM8f//aAMFAwVDBUNrEAFkGliD@QYQETAzFgA), [**2**](https://tio.run/##y00syfn/X8fdwV4xtsS1sKS4rtzcKUq7xtgmKcIpOKXM8f//aEMFQ2sFAwWDWAA), [**3**](https://tio.run/##y00syfn/X8fdwV4xtsS1sKS4rtzcKUq7xtgmKcIpOKXM8f//aEMFQwUDMDawhjGApCGEA5WzhjKgyiCK4MrgCmMB), [**4**](https://tio.run/##y00syfn/X8fdwV4xtsS1sKS4rtzcKUq7xtgmKcIpOKXM8f//aEMFQwUDMDawBhFQrqE1TBTCgYpClMHFIXoMYQKxAA), [**5**](https://tio.run/##y00syfn/X8fdwV4xtsS1sKS4rtzcKUq7xtgmKcIpOKXM8f//aAMFQyAEkQbWEAqCraFMEAmXAQtYI5ggGUOEXCwA).
### Explanation
```
, % Do twice. First iteration will use the input, second its transpose
G % Push input
@ % Push iteration index: first 0, then 1
? % If nonzero
! % Transpose
] % End
t % The top of the stack contains the input or its transpose. Duplicate
Eq % Convert to bipolar form, i.e. replace 0 by -1
t % Duplicate
s % Sum of each column
~ % Negate. If all results are true, condition 2 is fulfilled
w % Swap. Moves copy of bipolar input/transposed input to top
7B % Push [1 1 1], obtained as 7 converted to binary
Z+ % 2D convolution. Gives a matrix of the same size as the input
|3< % Is each entry less than 3 in absolute value? If all results are true,
% condition 1 is fulfilled
b % Bubble up. Moves copy of input/transposed input to top
XB % Convert each row from binary to a number
Sd % Sort, consecutive differences. If all results are nonzero, condition 3
% is fulfilled
v % Concatenate all results so far into a column vector
A % True if all entries are nonzero
% End (implicit). Display (implicit)
```
[Answer]
# [R](https://www.r-project.org/), ~~114~~ 107 bytes
*-7 thanks to Giuseppe, calling functions out of order and really compressing the conditions down*
```
function(x)any(f(x),f(t(x)))
f=function(x)c(apply(x,1,function(y)max(rle(y)$l)>2+mean(y)-.5),duplicated(x))
```
[Try it online!](https://tio.run/##ZU/LDsIgELz3Kzh42I3UtEQ9WW/@gNGzofSRJhQa0sb265GmKlRDYJnZZWYwtianmNhqUKJvtIIRuZqgcpVW0LuCGFVZ0BbAu05OMNKUfukJWz6CkaW7bSSe2bYt@UzHuwPSYuhkI3hfFrOerbUuHrnmppitW96bZgQBCU2c5LISuqDkjdxGSpTQMttTkk9GP7Pb9X7BKOdvrXQl9vOIBYPsb9C7eO8169MEiYIz/RgdMYpq8D9Eh3zEFWJoXw "R – Try It Online")
This just applies the rules to the columns of the matrix, then the columns of the transpose of the matrix.
Takes input in the form:
```
matrix(c(0,0,1,1,1,1,0,0,0,1,0,1,1,0,1,0), ncol=4)
```
Which is just how R takes 2D arrays.
Outputs TRUE for failures, FALSE for passes.
[Answer]
# [Perl 6](https://perl6.org), ~~100~~ 93 bytes
*Junctions FTW! They save 7 bytes.*
For the time being, this seems to be beating all the other submissions written in non-golfy languages. Yippie!
```
{!max (@(.map(*.join)).&{.repeated| |.map:{$_~~/000|111/|.comb(0)-.comb(1)}}for @^a,[Z] @^a)}
```
[Try it online!](https://tio.run/##VY3PDoIwDIfvPkVNiFkNju7iQZHwHBo1U0eCcULQg4bBq0/GxD@X9kv7/dpSVZe51U8IMljZeqzlA1jKuJYlm/JzkV8R@aTmlSqVvKuTAeN2izrYt21EREYIERl@LPSBEc48CGyarKgg3clws966jo1djm7SPWIsJiAQIJIw7mrH1BH15Gc9J4g/ES/@y8ORvr9DQ3wwvfc1P647b18 "Perl 6 – Try It Online")
**Explanation**: It's a block that takes the board as list of lists. We make a transpose with `[Z] @^a` (reduce the list of lists with zip operator). So `@^a,[Z] @^a` is a list of the board and its transpose. We loop over it with `for` which works exactly like `map`, just being 1 char cheaper in this case.
Inside, we first join the lists constituting rows into strings, so we have list of strings instead of list of lists (`@(.map(*.join))`). Then we use an anonymous block on it (`.&{...}`), where we actually evaluate the rules. We'll evaluate them only row-wise. (Since we do it for the original array and the transpose as well.)
To save quite some `!`'s, we use a bit of logic and instead of testing `(NO repeated rows) AND (NO 3 consecutive same symbols) AND (NOT different counts of 0 and 1)`, we test `NOT[ (repeated rows) OR (3 consecutive same symbols) OR (different counts) ]`. That's what we do in the anonymous block: `.repeated` gives all rows that occur more than once, then we map over the rows, try to match 3 consecutive symbols using a regex, and subtract the counts of 0's and 1's. These are OR'red with the `|`. (Actually it creates a very powerful thing called a *junction*, but we don't use any of its powers :)) After all of this, we get a list of 2 "bools" (uncollapsed junctions). We finally or them (using `max`) and negate (`!`), which gives the desired result.
[Answer]
# J, ~~40~~ ~~38~~ 55 bytes
```
0=[:([:+/^:_(3(0=3|+/)\"1 ]),:-.@~:,:#=[:+/"1+:@])|:,:]
```
[Try it online!](https://tio.run/##y/r/P03BVk/BwDbaSiPaSls/zipew1jDwNa4RltfM0bJUCFWU8dKV8@hzkrHStkWpELJUNvKIVazBigQy5UH0mwGhCoKhkBoAMYGcBomBpNB8JBVoqjlygUZaQKEKnBhQxRj4cZx5YOUGgEhzHYDrtTkjHyFPAiVppCn4Oekp1CckV@ak6KQlAqTz4XJ56LJG0Ik8mHy@ej6//8HAA)
Defines a function taking a square matrix as input.
~~At least it's beating Pyth (for now...)~~ (erroneously). I should go back to counting the emoji hidden in my code since J also lends itself well to that:
`[:` `/^:` `:1` `|:` `:]` `:-.@` `:#` `:@]` `:~@`
# Explanation (slightly outdated)
This looks different from my answer, and I may get to updating it. Parts of it are still the same -- I just was not checking for rule 3 for and improperly checking for rule 2 before.
Split into a few functions and ungolfed:
```
join_trans =. |: ,: ]
part_3 =. 3 (0 = 3 | +/)\"1 ]
f =. 1 - 2 * ]
main =. 0 = [: ([: +/^:_ part_3 , f) join_trans
```
# join\_trans
```
|: ,: ]
|: Transpose
,: Laminated to
] Input
```
This joins the transpose of the matrix to itself, creating an array of matrices.
# part\_3
```
3 (0 = 3 | +/)\"1 ]
] Input (matrix and transpose)
```
This checks the sum of partitions of 3 row-wise to see if it is 3 or 0 (since either of these means an invalid board), returning 1 if it is and 0 otherwise. It operates on both the matrix and its transpose since it's given both.
# f
```
1 - 2 * ]
```
For lack of a better name, I call this `f`. It replaces the 0s with \_1 and leaves the 1s unchanged. This is to allow me to eventually check if the number of 0s and 1s are equal in each row and column (the sum of each of the rows should be 0).
### main
```
0 = [: ([: +/^:_ part_3 , f) join_trans
join_trans Join transpose to input
part_3 , f Apply the validity checks and join them
+/^:_ Sum until it converges
0 = Equate to 0
```
Basically, I leverage the fact that I've set it up so that `f join_trans` and `part_3 join_trans` both should sum to 0 iff the board is valid. `part_3` should be all zeroes for a valid board and the entirety of `f` should sum to zero for a valid board, meaning that the sum of their sums is 0 only for a valid board.
[Answer]
# [Haskell](https://www.haskell.org/), ~~137~~ ~~136~~ 127 bytes
*9 bytes saved thanks to Lynn!*
```
import Data.List
j=isSubsequenceOf
l x=x==nub x&&and[sum y*2==length x&¬(j[0,0,0]y||j[1,1,1]y)|y<-x]
g x=l x&&l(transpose x)
```
[Try it online!](https://tio.run/##JYyxDsIgFEX3fgWDaVqDpjrL5mji4EgYqGJLpa@1PBJI@u9YMHc5ubnn9tJ@lDEx6nGeFiRXifJ40xaLgWn7cK1VX6fgqe7vwhDPPGPgWuLLUsKLWzeSsD8zZhR02KcaJqwG3tAtIqzrwE90iwj1Gi4HL4puOzFpaCpcJNh5sor4Oo5SA5sXDbjrePaTRrOevihvMv27zELEHw "Haskell – Try It Online")
[Answer]
# Java 8, ~~350~~ ~~326~~ ~~325~~ ~~312~~ ~~303~~ ~~299~~ ~~298~~ ~~259~~ 255 bytes
```
int r,z,c,p,i,j,k,d,u,v=1;int c(int[][]b){v(b);k=v-=u=1;v(b);return r;}void v(int[][]b){String m="",x;for(d=b.length;j<d|k<d;k+=u,j+=v,r=m.contains(x)|z!=0?1:r,m+=x)for(x="#",c=0,k*=u,j*=v;j<d&k<d;z+=i|i-1,c*=i^p^1,x+=p=i,r=++c>2?1:r,k+=v,j+=u)i=b[k][j];}
```
Returns `0` when it's a valid board; `1` if it's invalid for one or more of the three rules.
-95 bytes thanks to *@Nevay*.
**Explanation:**
[Try it here.](https://tio.run/##xVVNj5swEL3vr3BTqcJhgnCP9U77C3raI2IlMOzWED4EhtIk/PbUkDRiN@DmkKoHsOx58@bNhyEJ2mBTlHGeROlRbIO6Jt8Dme@PMlekgh0IKEFCAilE0ECLjA8WYem353t@SPetFVKeYrvBRlvHXRWrpspJxfu2kBFpJ@gnVcn8lWS4WkHHX4rKijB0tnH@qn7w5DE6pI8RT21sILGxhQozRxS50ppqq6OH3Qd0v7EvFWQ2dnRw73D1cQUCXUjXg9ca24Hn08Czs1Ee5IaBWKN8Lp8ZdDaWKDWtbYuvn0emdIijgzVUYuilvpf4vD/yB0LKJtxKQWoVKL2MqWRaiHXKwfNJQPcaRsjTr1rFmVM0yim1SW1zK49/jpW0qCPGzbkEJwdCLkd7F1xgwHq4suhTbXNnLO5omfcZbX1PKb@HtrMGYGCOOUWyWc1T1B@VYIx4XpeznGpbrtLluU3XMhd7izPomuCMui7KTv36X8P0N5/7DBNbKOwd@Q2tmTTG2N7ltpqabmK@cN8tz@mAmUb7/TAyQ6dnsYszcYU11/Sm6FdYQ/R32Nsu7A3RzR@Bq5obp20Ga56PN5X/l3du8oPoH/rjbw)
```
int r,z,c,p,i,j,k,d,u,v=1;
// Temp integers on class-level
int c(int[][]b){ // Method (1) with int-matrix parameter and int return-type
v(b); // Validate the rows
k=v-=u=1; // Switch rows with columns, and reset `u` to 1
v(b); // Validate the columns
return r; // Return the result
} // End of method (1)
void v(int[][]b){ // Separated method (2) with int-matrix parameter and no return-type
String m="",s; // Two temp Strings to validate uniqueness of rows
for(d=b.length; // Set the dimension of the matrix to `d`
j<d|k<d // Loop (1) as long as either `j` or `k` is smaller than `d`
; // After every iteration:
k+=u,j+=v // Increase the loop-indexes
r=m.contains(s) // If we've found a duplicated row,
|z!=0? // or if the amount of zeroes and ones on this row aren't equal
1:r, // Set `r` to 1 (invalid due to either rule 2 or 3)
m+=s) // Append the current row to the String `m`
for(s=",", // Set String `x` to a separator-character
c=0, // Reset the counter to 0
k*=u,j*=v, // Increase the loop-indexes
j<d&k<d // Inner loop (2) as long as both `j` and `k` are smaller than `d`
; // After every iteration:
z+=i|i-1, // Increase or decrease `z` depending on whether it's a 0 or 1
c*=i^p^1, // Reset `c` if current digit `i` does not equal previous `p`
s+=p=i, // Set previous `p` to current digit, and append it to String `s`
r=++c>2? // If three of the same adjacent digits are found:
1:r; // Set `r` to 1 (invalid due to rule 1)
k+=v,j+=u) // Increase the loop-indexes
i=b[k][j]; // Set `i` to the current item in the matrix
// End of inner loop (2) (implicit / single-line body)
// End of loop (2) (implicit / single-line body)
} // End of separated method (2)
```
[Answer]
# Python 3, 187 bytes
```
lambda m,c=lambda m:all([len({*m})==len(m),sum(~-("000"in x)*~-("111"in x)and x.count("1")==x.count("0")for x in m)==len(m)]):c(["".join(x[i]for x in m)for i in range(len(m[0]))])and c(m)
```
[Try it online!](https://tio.run/##hVBBbsMgELz7FYhLICLRot4skY8QDsRxWyqDI9uRHFXN191diK3eeoEZZoYduD2mzz69Ld6cl87Hy9WzqBqzwtp3nbBdm8T3Pv5IYwhGqcZ7FM@D4ADAQ2Kz3BPTWhfm05XNx6a/pwlPOeY2Bly@9wObGRrjdqGTdSMs58evPiQx2@D@mAgGgoNPH63ICQtOYooGNZhfpnacRmaYtdgJaygsg90UBw2Z4c6d@k/NGqwYNlMJQT4q/iLh@pKyVnIvz@bQ6yDnqooeQ2XpPbl0XbHbEPBriKnd4bRTPmMpl18 "Python 3 – Try It Online")
Takes input as a list of lines.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes
```
ø‚D€ÙQIDøì©O·IgQP®εŒ3ù€Ë_P}PP
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8I5HDbNcHjWtOTwz0NPl8I7Daw6t9D@03TM9MODQunNbj04yPrwTJNsdH1AbEPD/f3S0gY4CEBkCUayOQrQhmAkSA/EMYDyYHFQgNhYA "05AB1E – Try It Online")
**Explanation**
Rule: 3
```
ø‚ # pair the input with the zipped input
D # duplicate
€Ù # deduplicate each
Q # check for equality with the unmodified copy
```
Rule: 2
```
IDøì # prepend zipped input to input
© # store a copy in register for rule 1
O # sum each row/column
· # double
IgQ # check each for equality to length of input
P # product
```
Rule: 1
```
®ε # apply to each row/column in register
Œ3ù # get sublists of length 3
€Ë # check each if all elements are equal
_ # logical not
P # product
} # end apply
P # product
```
Then we take the product of the result of all 3 rules with `P`
[Answer]
# Dyalog APL, ~~64~~ ~~52~~ ~~51~~ ~~49~~ 48 bytes
Requires `⎕IO←0`
```
{⍲/{(∨/∊⍷∘⍵¨3/¨⍳2)∧((⊢≡∪)↓⍵)∧∧/(≢=2×+/)⍵}¨⍵(⍉⍵)}
```
[Try it online!](https://tio.run/##TY7BCoJAFEX38xXuHAsbM1q2VVr1DWIQgVDgKsStjMJIEFHb3CQtK2lvf3J/xN5Yi4bH3PfOfZeZYBvZy10QbVZ2GAVxvA67DuVxvkC2dxjzSBKou0g4ZC0gC6gX5BmqaeuJaGuoh2tBXjlHUSG/QN4sZAfyNaUSHHk1c9@nobCIpjrScKhcr6TM/z5Q9hjqCVW7YjQdkFJOBxij/9CWZ/iG6ThjOg4JNXSZ/2ZPtNV7eujlC3/UZF33AQ)
[Answer]
# PHP, 245+1 bytes
ew this is bulky. linebreaks are for reading convenience only:
```
$t=_;foreach($a=($i=str_split)($s=$argn)as$i=>$c)$t[$i/($e=strlen($s)**.5)+$i%$e*$e]=$c;
for(;$k++<2;$s=$t)$x|=preg_match("#000|111|(\d{"."$e}).*\\1#s",chunk_split($s,$e))
|($m=array_map)(array_sum,$m($i,$i($s,$e)))!=array_fill(0,$e,$e/2);echo!$x;
```
Takes a single string without newlines, prints `1` for truthy, nothing for falsy.
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/eac9d0ceb8dfae6fbcb1aebec4cb43a08b09ea41).
] |
[Question]
[
A string of characters repeats if it contains two consecutive substrings that are equivalent.
For example, `2034384538452` repeats as it contains `3845` twice, consecutively.
Therefore, your challenge is to decide whether a string contains a repeating substring. You may take the input as a string or an array of characters.
You will never receive an empty input, and the length of the substring (if it exists) may be 1 or more.
I use `1` and `0` here as my truthy and falsy values, but you may use different values, as long as they are truthy and falsy in your language.
## Examples:
```
abcab -> 0
bdefdefg -> 1
Hello, World! -> 1
pp.pp/pp -> 1
q -> 0
21020121012021020120210121020121012021012102012021020121012021020120210121020120210201210120210121020121012021020120210121020121012021012102012021020121012021012102012101202102012021012102012021020121012021020120210121020121012021012102012021020121012021020120210121020120210201210120210121020121012021020120210121020120210201210120210201202101210201210120210121020120210201210120210121020121012021020120210121020121012021012102012021020121012021020120210121020120210201210120210121020121012021020120 -> 0
```
(The last example was generated from the amount of ones between each zero in the Thue-Morse sequence)
[Answer]
# [Retina](https://github.com/m-ender/retina), 6 bytes
```
(.+)\1
```
[Try it online!](https://tio.run/##K0otycxL/P9fQ09bM8bw//@klNQ0IEoHAA "Retina – Try It Online")
Positive value for truthy; zero for falsey.
## How it works
Returns the number of matches of the regex `/(.+)\1/g`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
s~j
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7gu6/9/paSU1DQgSlcCAA "Brachylog – Try It Online")
```
s~j
s exists a sublist of input
~j which is the result of a juxtaposition of something
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes
```
Ẇµ;"f
```
This is a full program. TIO can't handle the last test case without truncating it.
[Try it online!](https://tio.run/##y0rNyan8///hrrZDW62V0v4/3L3lcPujpjWR//8nJiUnJnElpaSmAVE6lwdQZb6OQnh@UU6KIldBgV5BgX5BAVchl5GhgZGBIZA0NDKAsg3APFRxQyQ5fOoNcOgj13xDEu0jwXwA "Jelly – Try It Online") (last test case truncated to 250 digits)
### How it works
```
Ẇµ;"f Main link. Argument: s (string)
Ẇ Words; generate all substrings of s.
µ New chain. Argument: A (substring array)
;" Vectorized concatenation; concatenate each substring with itself.
f Filter; keep "doubled" substrings that are also substrings.
This keeps non-empty string iff the output should be truthy, producing
non-empty output (truthy) in this case and empty output (falsy) otherwise.
```
[Answer]
# Mathematica, 32 bytes
```
StringMatchQ[___~~x__~~x__~~___]
```
[Answer]
# Java, 27 bytes
```
a->a.matches(".*(.+)\\1.*")
```
Pretty much a duplicate of the [Retina answer](https://codegolf.stackexchange.com/a/125737/20198), but there's no way Java's getting any shorter.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
Œ2×åZ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6CSjw9MPL436/9/I0MDIwBBIGhoZQNkGYB6quCGSHD71Bjj0kWu@IYn20dv9BjT2H03cDwA "05AB1E – Try It Online")
Outputs 1 as truthy value and 0 as falsy value
### Explanation
```
Œ2×åZ
Œ # Substrings of input
2× # duplicate them (vectorized)
å # Is the element in the input? (vectorized)
Z # Maximum value from list of elements
```
[Answer]
# [Python](https://docs.python.org/2/), 38 bytes
```
import re
re.compile(r'(.+)\1').search
```
[Try it online!](https://tio.run/##vZK/DsIgEMZ3nuKcaGNTgdHE3TdwUAdowZLQclIWnx5L46CDJppUQo7ffcef7xLwFjs/iJRsjz5ECJqYXdB143u0TheBFvW6PHFa1qOWoelS1GMcYQdHKiWtgErVSJVBtdpM85J5r53zFRx8cO0qC9ccEGvEDWJmwZlgfIpcsAezOXvV@VPt03725tyv9/Mv3/u3f7Zwf4v4p2dCjA@QvxDYYV7HLYFpYLBDBOW9K0yR9bJMdw "Python 2 – Try It Online")
Yawn, a regex. Checks if the string contains a string of one of more characters `.+` followed by that same string that was just captured. The output search object is Truthy if there's at least one match, as can be checked by `bool`.
Using `compile` here saves over writing a lambda:
```
lambda s:re.search(r'(.+)\1',s)
```
---
# [Python](https://docs.python.org/2/), 54 bytes
```
f=lambda s:s>''and(s in(s*2)[1:-1])|f(s[1:])|f(s[:-1])
```
[Try it online!](https://tio.run/##vZKxDsIgEIb3PsU5AaYqMJLU2TdwaDqAFDXBgqWLie@O0HTQQRNNKiF3H//dwZGcvw0n1/EYTWXlRWkJQYQtQrLTOMC5w2HJSc3EijXkbnBIOMEoxaENQ4AKaiQlKgFJdZAqg9KtSfuYedda60rYu97qRRau2Xi/9n7jfWbOKKcsWcbpxHQ8versKfYpn76p@/V@9uV7/@6fzvy/WfpHTVEY10MeoTRpow@igLR8f@4GUM5ZbHDWa8FoQ0h8AA "Python 2 – Try It Online")
Searches for a substring that is composed two or more equal strings concatenated, as checked by `s in(s*2)[1:-1]` as in [this answer](https://codegolf.stackexchange.com/a/37855/20260). Substrings are generated recursively by choosing to cut either the first or last character. This is exponential, so it times out on the large test case.
Near misses:
```
f=lambda s,p='':s and(s==p)*s+f(s[1:],p+s[0])+f(s[:-1])
f=lambda s,i=1:s[i:]and(2*s[:i]in s)*s+f(s[1:])+f(s,i+1)
```
The first one doesn't use Python's `in` for checking substrings, and so could be adapted to other languages.
[Answer]
# Pyth - ~~10~~ ~~9~~ 8 bytes
```
f}+TTQ.:
```
Returns a list of all the repeating substrings (which if there aren't any, is an empty list, which is falsy)
[Try It](https://pyth.herokuapp.com/?code=f%7D%2BTTz.%3Az&input=abcdabcd1234&test_suite=1&test_suite_input=abcab%0Abdefdefg%0AHello%2C+World%21%0App.pp%2Fpp%0Aq&debug=0)
Explanation:
```
f}+TTQ.:
.: # All substrings of the input (implicit):
f # filter the list of substrings T by whether...
+TT # ...the concatenation of the substring with itself...
} Q # ...is a substring of the input
```
[Answer]
# [Cheddar](http://cheddar.vihan.org/), 60 bytes
```
n->(|>n.len).any(i->(|>i).any(j->n.index(n.slice(j,i)*2)+1))
```
[Try it online!](https://tio.run/##TcyxDsIwDATQna8ImWJog2CnM3/AnDQuuLJcExhA4t9DBBKKdMu9k268YkohF8aHmcyxSD@49yCeUcAHeTn6Av3K3NeJJOHTib8zjejmjmBzgO0eoGgmqTfOhjiGaGH1h5hwqrm0dkLmpTPnJXNat4OqV92ptnazUD4 "Cheddar – Try It Online")
[Answer]
# [PHP](https://php.net/), 32 bytes
```
<?=preg_match('#(.+)\1#',$argn);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwJWWX5SamJyhEc2llJiUnJikpKOsoGunYMCllJSSmgZE6VARQy4lj9ScnHwdhfD8opwURYRwQYFeQYF@QQFCpBBhipGhgZGBIZA0NDKAsg3APFRxQyQ5fOoNcOgj13xDEu2jt/sNaOw/mrhfSQEa@7GJxSqJRel5mtUK9nbABGdbUJSaHp@bWAJMcOrKGnramjGGyuo6EDXW/2v/AwA "PHP – Try It Online")
# [PHP](https://php.net/), 38 bytes
```
<?=preg_match('#(.+)(?(1)\1)#',$argn);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwJWWX5SamJyhEc2llJiUnJikpKOsoGunYMCllJSSmgZE6VARQy4lj9ScnHwdhfD8opwURYRwQYFeQYF@QQFCpBBhipGhgZGBIZA0NDKAsg3APFRxQyQ5fOoNcOgj13xDEu2jt/sNaOw/mrhfSQEa@7GJxSqJRel5mtUK9nbABGdbUJSaHp@bWAJMcOrKGnramhr2GoaaMYaayuo6EJXW/2v/AwA "PHP – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~73~~ 66 bytes
*-7 bytes thanks to @LeakyNun*
```
lambda s:any(2*s[j:i]in s for i in range(len(s))for j in range(i))
```
[Try it online!](https://tio.run/##vVLBbsIwDL33K7xTkqlA0t0qsTN/wAE4pGvKgkLqJbkgxLeXuEJiHEBiErMs6/nlJXakh4f03fuPoZuvB6f3Tash1tofePUeV7vabqyHCF0fwEKGQfut4c54HoUgdndlrRBDMjFFmMOK6eZLN6wE1rSmy7klvDDO9SUs@@DaNyJ@qCBOEWeIhCslK6lyVZW8YDl2t7z6dfZIL@/c@@v76sl5/72/fPH/XrI/2xQFeYnMQ3YaTVQXkAOD9Ymz4wkmn3A8sWnW7XXiJCkhGAy8GxuRYzgD "Python 3 – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), 11 bytes
```
{?/(.+)$0/}
```
[Test it](https://tio.run/##vVHLasMwELzrK7ZgGhnLtuRDDjVpeuwHFHrJxY9NMSj2xlJKg/GX9dYfcy07hebQQgopiGVnNDO7QoStXg4Hg/C6jIqU7Y5wWzZowsqGLRJmFlYwdOuYR4HvybgfRsWDReN4XdVouP/xHhnSleULCO9h4Ue7jO5c68XQgScFrANPQc/cmKfRmjLSWQ3BlJOybdOeIkcP31Q1HayADb4RFhZLHzoGUJmwRCR9hPP1@CT3BXzJBUwM64csL7LcZUqWl7gdz4tDij2i1o2A56bV5c1MEUVEMdGM9rMrUTKRaqwqkadeTuicV9/uftPLH3x/zVcXzvvv/eWV33eV/aef/wQ "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
? # Boolify the following
# (need something here so it runs the regex instead of returning it)
/ # a regex that implicitly matches against 「$_」
(.+) # one or more characters stored in $0
$0 # that string of characters again
/
}
```
[Answer]
# PHP, 32 bytes
```
<?=preg_match('#(.+)\1#',$argn);
```
Run as pipe with `-F`. Sorry Jörg, I hadn´t noticed You had [posted the same](https://codegolf.stackexchange.com/a/125741/55735).
**non-regex version, ~~84~~ 82 bytes**
```
for($s=$argn;++$e;)for($i=0;~$s[$i];)substr($s,$i,$e)==substr($s,$e+$i++,$e)&&die
```
exits with return code `0` for a repeat, times out (and exits with error) for none. Run as pipe with `-nr`.
assumes printable ASCII input; replace `~` with `a&` for any ASCII.
[Answer]
# JavaScript (ES6), 19 bytes
```
s=>/(.+)\1/.test(s)
```
[Answer]
# Pyth, 15 bytes
```
.E.nm.bqNYtdd./
```
[Try it!](https://pyth.herokuapp.com/?code=.E.nm.bqNYtdd.%2F&input=%22abcab%22&test_suite=1&test_suite_input=%22abcab%22%0A%22abcabc%22&debug=0)
[Answer]
# [V](https://github.com/DJMcMayhem/V), 6 bytes
```
ø¨.«©±
```
[Try it online!](https://tio.run/##K/v///COQyv0Dq0@tPLQxv//E5OSUwA "V – Try It Online")
[Test Suite!](https://tio.run/##K/v///ByPf3DOw6t0Du0@tDKQxv//09MSk5M4kpKSU0DonQuj9ScnHwdhfD8opwURa6CAr2CAv2CAq5CLiNDAyMDQyBpaGQAZRuAeajihkhy@NQb4NBHrvmGJNpHb/cb0Nh/NHE/AA "V – Try It Online")
The program outputs `0` for falsey values, and a positive integer for positive values.
(Note that there was a small bug, so I had to gain 1 byte. Now after the bugfix, I will be able to replace `.«` with `\x82`)
### Explanation
```
ø " This is a recent addition to V. This command takes in a regex
" and replaces the line with the number of matches of the regex
¨.«©± " The compressed regex. This decompresses to \(.\+\)\1
```
[Answer]
# Japt, 8 ~~+ 1~~ = ~~9~~ 8 bytes
```
f"(.+)%1
```
[Try it online](http://ethproductions.github.io/japt/?v=1.4.5&code=ZiIoLispJTE=&input=ImFiYWJkYyI=). Outputs `null` for falsy, and an array containing all the repeating strings for truthy.
# Explanation
```
f"(.+)%1
Uf"(.+)%1" # Implicit input and string termination
Uf # Find in the input
"(.+)%1" # a sequence followed by itself
f # and return the matched substring
# output the return value
```
[Answer]
## Cheddar, 16 bytes
```
@.test(/(.+)\1/)
```
This is a function. [Try it online!](https://vihan.org/p/tio/?l=cheddar&p=y0ktUUhTsFVw0CtJLS7R0NfQ09aMMdTX5OIqKMrMA8ppKKXnJ5aAsJImqlgSWOw/AA)
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 10 bytes
Takes input on stdin. Prints the index of the first repeated substring for truthy and `nil` for falsey.
```
p~/(.+)\1/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6eUuyCpaUlaboWqwrq9DX0tDVjDPUhAlDxBbeYZBKTkhOTuJJSUtOAKJ3LIzUnJ19HITy_KCdFkaugQK-gQL-ggKuQy8jQwMjAEEgaGhlA2QZgHqq4IZIcPvXo8ujmkGo-If2E3ENr91NqP6XhQ5b7IakEAA)
] |
[Question]
[
Given a positive integer, determine if it can be represented as a concatenation of two square numbers. Concatenated numbers may not begin with 0 (except for 0). Any leading zeros in input should be ignored.
Examples
```
11 -> true // because 1 and 1 are squares
90 -> true // because 9 and 0 are squares
1001 -> true // because 100 and 1 are squares
144100 -> true // because 144 and 100 are squares
151296561 -> true // because 15129 and 6561 are squares
164 -> true // because 1 and 64 are squares (also 16 and 4)
101 -> false // can't be 1+01 as a number may not begin with 0
016 -> false // leading 0 is ignored and 16 doesn't count
9 -> false // need two squares
914 -> false // need two squares (there are three)
```
Task
Given a positive integer return a value indicating if it is a concatenation of two squares.
This is code-golf the goal is to minimize the size of the source code as measured in bytes.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
~cĊ~^₂ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy75SFdd3KOmpodbJ/z/b2hqaGRpZmpmCAA "Brachylog – Try It Online")
### Explanation
```
~cĊ Deconcatenate into a couple of 2 elements Ċ
Ċ~^₂ᵐ Each element of Ċ must be the square of a number
```
[Answer]
# [R](https://www.r-project.org/), 42 bytes
```
function(x)x%in%outer(y<-(0:x)^2,y,paste0)
```
[Try it online!](https://tio.run/##bc1RCsMgDADQ0xQSSCEZpeDYrjIRsVAo6jQyPb3bAfb3/l6ZPkXv1KbD6ifZ@m6uhPqcR4tezxShY1/OuKSmocB4rMD3jq8bDcquamCc1eV8DfAgQoZJmIVk334QYtnJkJEN6W@E8ws "R – Try It Online")
Same horribly-inefficient approach as [my Husk answer](https://codegolf.stackexchange.com/a/242678/95126).
[R](https://www.r-project.org/)'s `%in%` function to search for an element in a vector conveniently appears to cast its arguments to the same type (here the numeric input `x` and the character vector of `paste`d-together squares), which was a nice surprise to me.
*Note:* After reading [Fatalize's comment](https://codegolf.stackexchange.com/a/242680/95126), I realise that this answer is also *very* close to [pajonk's answer](https://codegolf.stackexchange.com/a/242465/95126) to the "[Sum of two squares"](https://codegolf.stackexchange.com/q/242459/95126) challenge. Note though that that answer wasn't the shortest in [R](https://www.r-project.org/), so a small change to the challenge does seem to favour a completely different approach, which is also nice.
[Answer]
# Python 3.6 (with IO), 73 bytes
```
n=input();l=range(int(n));print(n in[f"{i*i}{j*j}"for i in l for j in l])
```
You could also use,
```
n=input();l=range(int(n));print({n}&{f"{i*i}{j*j}"for i in l for j in l})
```
But unfortunately it doesnt output booleon values rather it outputs, `{n}` for `True` and `set()` for `False`
[Try on Online](https://tio.run/##K6gsycjPM/7/P882M6@gtERD0zrHtigxLz1VIzOvRCNPU9O6oAjMUsjMi05Tqs7UyqytztLKqlVKyy9SyASKKuQogJhZYGas5v//AA)
slightly longer answer (By 2 bytes)
```
n=int(input());print(str(n)in[f"{(k//n)**2}{(k%n)**2}"for k in range(n*n)])
```
and without a loop
```
n=int(input());m=k=0;exec('m+=f"{(k//n)**2}{(k%n)**2}"==str(n);k+=1;'*n**2);print(m>0)
```
[Answer]
# [Julia](https://julialang.org/), ~~130~~ ~~122~~ ~~98~~ 91 bytes
```
!x=√parse(Int,x)%1
f(a,s="$a",l=length(s))=0∈1:~-l.|>i->s[l-i]<'1'||!s[i+1:end]+!s[1:i]
```
[Try it online!](https://tio.run/##JctBCoMwEAXQfU@h0mKCScm0MaBU9z2DZBGotilpEGMhC@naM/R4XsRGCsOfx2fm@TZagV/X2FfL/O3V4Fp0tSPx@AC7DiniqmSvEmIq09r7@EAO44ot8wzlh5rjVGtau8ZQLS8ppNMUu0ZnULb2JrNgKLVc@0Hb0Vj0Uj3ytO6Qx6QBIFHBSASMBQHnAWHncCpELrZKcBKdN4X4k/PtPjQMRPgOA1xivP4A)
Thanks to Sunda R we can save 8 bytes!
Thanks to MarcMush we can save ~~32~~ 39 bytes!
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
€s¹Σ´Ṫ+mos□ŀ
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@jpjXFh3aeW3xoy8Odq7Rz84sfTVt4tOH////RhoY6lgY6hgYGhjqGZiZAhqGOgaGZjqWOpaFJLAA "Husk – Try It Online")
Outputs nonzero for 'concats of two squares', zero for numbers that aren't.
Builds a list of 'concat of two squares' numbers, and then checks if the input is present. So not very efficient for large inputs...
```
€s¹Σ´Ṫ+
mos # get strings of
□ŀ # all squares up to input,
´Ṫ # combine all combinations
+ # by concatenation,
Σ # flatten the list-of-lists
€s¹ # and look for the input as a string
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~56~~ 53 bytes
2 byte from tsh
```
x=>(g=_=>x--&&x*x+'|'+g(),x+g).match(`^(${g()}){2}_`)
```
[Try it online!](https://tio.run/##FYzRCsIgFEC/ZRDbvalDYwQ@6I9EbWKbLdYcTUJY@3azp3M4D@dpPma173EJbPb3Pg0qRaXBqVbpyFhZxmMk1bciDpBG4rB@mWAf0N3gsOW243ba2w6T9fPqp76evIOLEFRyKjgXVJybLH9SSaVornmwQFC6KAYIiJh@ "JavaScript (Node.js) – Try It Online")
RegEx with many choices
[Answer]
# [Julia 1.0](http://julialang.org/), ~~47~~ ~~44~~ 37 bytes
```
~n="$(n^2)"
!a="$a"∈.~(r=0:a)'.*.~r
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/vy7PVklFIy/OSFOJSzERyE5UetTRoVenUWRrYJWoqa6npVdX9L8ktbikWMFWIdrQUEfB0kBHwdDAAMhSMDQz0VEwNjMECQAJA0MzoDQQGZrEchUUZeaV5OTpaUA069naKegpgtma/wE "Julia 1.0 – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 29 bytes
```
Jsuf{?sXXsm}0_+)up2CB)++jup~[
```
[Try it online!](https://tio.run/##SyotykktLixN/V9dlPnfq7g0rdq@OCKiOLfWIF5bs7TAyNlJU1s7q7SgLvp/bXjOf0NDLksDLkMDA0MuQxMTIM1laGpoZGlmagYUMDMByhhyGRiacVlyWRqaAAA "Burlesque – Try It Online")
```
J # Duplicate
su # Substrings of
f{ # Filter for
?s # Sqrt
XX # [floor, ceil]
sm # Same (i.e. is int)
} # -- Is square
0_+ # Append 0 to list
)up # Unparse each to str
2CB # Combinations of pairs
)++ # Mapped Concat
j # Reorder stack
up # Unparse input
~[ # Is in list
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~127~~ 125 bytes
```
i;r;q(n){for(r=i=n;i;--i)r=r&&i*i-n;i=!r;}t;h;m;f(n){for(t=h=0,m=1;n>9;n/=10,m*=10)n%10|m<2?h+=n%10*m,t|=q(n/10)*q(h):0;n=t;}
```
[Try it online!](https://tio.run/##XVFRb4IwEH7fr@hINAUhtg5N2Fn3sOxXTB9MLdJsVG2bjEz562OHIJkjx/X63Xdfe1eZ7KVsGg0WTtSE5/xgqRVaGNCQJDq0wo7HOtIJAuLRQu2hgBLyG9eLQrC4FBzMKgMzFRx3EfrQjDi7lMvZSzERbRyVsb8IPGSKyehEi/CZgREe6kYbT8qtNjQk5weCXwt45bx73xBBzpzHJGMx4YxhxNMUA1znfJYt5osWWqRttqWh8bSGQUZVRyW92vVKSLs31llfIQ/GeSKLrY3QK/mhbFcYrKu32brKXvGfBzH5u38K@mocCKHtodrsVIVlDPpwSZz@Voec3q4TTnsgGhAgk8mVHV7Fuknc2jCo1k3kStnAXdZhtn2Se1QhOrT/v@xokZLTYLQjyYqgH7m1wcZMTFw89O6EUJtetn6omx@Zf273rkm@fgE "C (gcc) – Try It Online")
*Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
[Answer]
# [Haskell](https://www.haskell.org/), ~~54~~ 51 bytes
```
f n|l<-show.(^2)<$>[0..n]=elem(show n)$(++)<$>l<*>l
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hrybHRrc4I79cTyPOSNNGxS7aQE8vL9Y2NSc1VwMkrpCnqaKhrQ2SyrHRssv5n5uYmadgq5CSz6VQUJSZV6KgopCmoGBoqKCggCJiaYAuYmhgYAgUwRA2M8FUiWGcgaEZmvkYFhqa/AcA "Haskell – Try It Online")
* Thanks to @ovs for saving 3 Bytes.
So much inefficient approach:
*l* is all numbers up to input squared and to string.
We search trough the powerset of *l* if there is a pair that form the input
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
Inefficient and somewhat boring approach.
```
lambda n:`n`in('%d'*2%(a*a,b*b)for a in range(1,n)for b in range(n))
```
[Try it online!](https://tio.run/##RY1BCsIwEEX3nmI2oUkYIVNCIQU9iYtOiNGCTkvoxtPHxI2rz3uL//bP8dxkrPlyqy9@x8Qg8yLLKnpQabCj0mwZo40mbwUYVoHC8rhrQvmp@FdiTO1KuiLC4JCcIyTv2yJNvnHDCQMG8vMJYC@rHC1FLsH5Ci0JCrQg5P5m6hc "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 77 bytes
Much more efficient and interesting.
```
f=lambda n,m=0,d=1:n and((m*10<d!=10)==n**.5%1+m**.5%1)|f(n/10,m+n%10*d,d*10)
```
[Try it online!](https://tio.run/##JY7BCoMwEETv/YrtQUx022ZFBaXpr4htGhpoNhLiodB/tymeHswMM7N80itws9kYPEyTXdMan9MEzi8hJlii45RVfiQXeLP6Pfu7mYHRa4VG08gwsxHCV6Su5qhJSa25qs5dQbXfKb9W8IUU@poLUpVBk9NysyECg2MgwkEhKUVIbZuJ1FEz9F2fhb7Nzp844EDteID9lShzl4HTDQpTQgGCEfKOlHL7AQ "Python 2 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-ap`, ~~69~~ 64 bytes
```
$_=grep{1<grep/^0$|^[^0]/&sqrt!~/\./,unpack$_."A*","@F"+0}A1..A9
```
[Try it online!](https://tio.run/##HYnLCsIwEEX38xeG4EJrMqOTQEDBbvwJNaVIEbG0Ma0rH59ujC4u53JOaGJrUpLV5hyb8KD1D9qjfPq9x6OeDrc4Tt76oHRx70J9uspKiXImCrHdiTm@SlKqdCkRgUMgRAJizgQytHTW2Cws50KAZMGBI4ZVtnn/w/zpw3jpuyEt6tB@AQ "Perl 5 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-nE`, ~~78~~ 61 bytes
```
say int=~/^((.+)(?(?{$+eq(0|$+)&(0|sqrt$+)**2==$+})|^))(?1)$/
```
[Try it online!](https://tio.run/##HY5BCsMgFET3/xRZSNFIGn@qggvJCXqFQBYWAsUkahelaY9e@@limOHNLGYL6W5qzfOzWWLxn37i/CwFH/n4YjLsXB1MihNZ3lOh2LaD90y@xTEJmqFgfa2I4BSgUgioNTmgwcFZYwlYTQ2CQgsOHGq4ECX9g9bwXbeyrDHXLjbd9Rbm8kjB06Mf "Perl 5 – Try It Online")
A whopping -17 bytes thanks to @kjs.
**Explanation**:
```
say int # convert input to number to remove leading 0s
=~ # and match it against the regex
/^( # match from the beginning of input
(.+) # match 1 or more digits
(? # evaluate a condition here
(?{ # the condition is the result of this code
$+ # the digits matched so far are in $+
eq # string equality check
(0|$+) # int($+) - golfy way of writing it
# if they're equal, no leading 0s here
&
(0|sqrt$+) # again, golfy form of int(sqrt($+))
**2==$+} # square that and compare to original number
) # if no leading zeroes and number is a square
# do nothing and move on
| # else
^ # add an impossible pattern here so regex match fails
)
)
(?1) # now do the same match again, for the second square
$ # and that should be the end of input
/x;
```
The trick is in exploiting regex "backtracking" mechanism.
Any time the part of the string we're looking at doesn't match
the conditions we want, we make the match fail deliberately
so that the regex engine chooses a different subset of the input string
for the /(.+)/, and automatically tries the match again.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 55 bytes
```
^0+
\B
$'¶$`;
A`;0.
\d+
$*
m`(^1|11\1)+;(1(?(2)1\2))*$
```
[Try it online!](https://tio.run/##DccxCoQwEAXQ/p8j4sSAzJcghBSijZcIEsEtttBisfRcHsCLZa0e7/c5v8daKplzWdQBaYKpn9vkiDFHbZE2B9Ngz7LwIhOti0IZpLNMnbWNKYVEUFCVoPevYO/fE8oeAYH@Dw "Retina 0.8.2 – Try It Online") Link includes faster test cases (a `^` after the `m`` would speed it up enough to be able to check `151296561` on TIO). Outputs the count of square concatenations, so for example `144100` can be split up as `144` and `100` or alternatively as `1` and `44100`, so the output would be `2` in that case. Explanation:
```
^0+
```
Delete leading zeros.
```
\B
$'¶$`;
```
Try splitting between every pair of digits.
```
A`;0.
```
Delete numbers with leading zeros.
```
\d+
$*
```
Convert to unary.
```
m`(^1|11\1)+;(1(?(2)1\2))*$
```
Match two square numbers. `(1(?(2)1\2))*` is a generalised match for a square number; `(^1|11\1)+` is a simplified special case for a non-zero square to be matched at the start (of a line).
[Answer]
# [Julia 1.0](http://julialang.org/), ~~38~~ 47 bytes
```
~a=string.(a.^2);!a=any(~(0:a)'.*~(0:a).=="$a")
```
[Try it online!](https://tio.run/##JY3BCgIxDETvfkV2EWylhERLQSX@iCjkILKylMVW0Mv@eq1bGIbHTMg83@Og/CllVkn5NcQHGsXbzp46FY1fMxs6qt3gtgGK9Gvtbcn3lBMIXJgdHMgBE1Xi4B3sAy/W0Pt/WRPiUE@r2F9XU93KY0TTHqGcAbuFbfkB "Julia 1.0 – Try It Online")
Based on [MarcMush](https://codegolf.stackexchange.com/a/242861/101725)’s answer (tnx for pointing out the error when squaring)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 92 bytes
```
f=lambda n,x=1:x<len(n)and all(e[0]!='0'and int(e)**.5%1==0for e in[n[:x],n[x:]])or f(n,x+1)
```
[Try it online!](https://tio.run/##FcxBCsMgEEDRq9hF0UlDcVoMjdSTiAtLlBbMRCQLc3prtg/@z8f@3ej5yqW1aJJfP4tnNFaDur5TIEHgaWE@JRGsdBfDJT/hR7sIMAx3dUVjZNwKCx0tWV3dSLZq56BjFH12Q2i5nEkUHBU@5klNyAHaHw "Python 3.8 (pre-release) – Try It Online")
-28 for @ophact's tip
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÝāsânJIå
```
Based on [my 05AB1E answer for the *Sum of two squares* challenge](https://codegolf.stackexchange.com/a/242461/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//8NwjjcWHF@V5eR5e@v@/pQEA) or [verify (almost) all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w3OPNBYfXpTnVXl46X@d/9GGhjqWBjqGBgaGOoYmJkBax9DMRMfYzBCEwQwTE6C0oY6SgaGZko6ljqWhSSwA) (`151296561` is omitted since it'll timeout).
**Explanation:**
```
Ý # Push a list in the range [0, (implicit) input]
ā # Push a list in the range [1,length] (without popping the list)
s # Swap so the [0,input] list is at the top
â # Cartesian product: create all possible pairs using these two lists
n # Square each inner integer
J # Join each pair together
Iå # Check if the input is in this list
# (after which the result is output implicitly)
```
We can't just use the range \$[0,input]\$ twice, since it would create a false positive with for example `"09"` and input `9`. We also can't just use the range \$[1,input]\$ twice, since it would fail with for example input `90`. Hence the use of the range \$[1,input+1]\$ with \$[0,input]\$ for the creation of pairs with the cartesian product instead.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 37 bytes
Probably can be golfed a *lot*, but this is too long for me.
So basically for every `i` in input `n`, it checks if both `n[:i]` and `n[i:]` are squares.
I think the time complexity is \$O(2\*\mathrm{len}(n)) \$
```
Lʁƛ?fnȯṅ:h⌊[⌊|3]∆²→?fẎṅ:h⌊[⌊|3]∆²←∧;a
```
Explanation:
```
Lʁƛ?fnȯṅ:h⌊[⌊|3]∆²→?fẎṅ:h⌊[⌊|3]∆²←∧;a
Lʁ Exclusive 0 range of length(n)
ƛ Map through range
?f Push stringified n
nȯṅ Slice from loop index to end
:h⌊[⌊|3] Duplicate slice, if int(head) = 0, push 3 (non-square) else int(slice)
∆²→ Set var to "is a perfect square?"
?f Push stringified n
Ẏṅ Slice from 0 to loop index
h⌊[⌊|3] Duplicate slice, if int(head) = 0, push 3 (non-square) else int(slice)
∆² Is it a perfect square?
← Get var
∧ Are both are squares?
;a End map, check if any element is true.
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJMyoHGmz9mbsiv4bmFOmjijIpb4oyKfDNd4oiGwrLihpI/ZuG6juG5hTpo4oyKW+KMinwzXeKIhsKy4oaQ4oinO2EiLCIiLCIxNDQxMDAiXQ==)
[Answer]
# MATL, 33 bytes
```
Vf3L)"GV@:&),tUV=A3MtX^kU=*w]*?T.
```
[Try it out](https://matl.suever.net/?code=Vf3L%29%22GV%40%3A%26%29%2CtUV%3DA3MtX%5EkU%3D%2aw%5D%2a%3FT.&inputs=016&version=22.4.0)
Outputs 1 for truthy, nothing for falsey.
```
V % take in number (ignoring initial 0s) and convert to string
f % get list of its indices (starting from 1)
3L) % remove the last index
" % for 1 to end-1
GV % get input as string again, say S
@ % get the current loop index i
: % form range 1:i
&) % split S[1:i] and S[i+1:end]
, % for each split part
t % duplicate it
U % convert to numeric
V % and back to string - this gets rid of initial 0s
=A % condition 1: did that give the same string back?
3M % get the numeric form N of the current part again
tX^kU % floor(sqrt(N))^2
= % condition 2: did that get the number back
% i.e. is it a square number
* % AND those conditions
w % swap the other part in to be checked
] % end
*? % if both parts satisfied the conditions
T % save True to output
. % break
% (implicit) end
% (implicit) end
% (implicit) convert to string and display
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
›₌ɾʁẊ²vṅ⌊c
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigLrigozJvsqB4bqKwrJ24bmF4oyKYyIsIiIsIjkwIl0=)
An 05AB1E port.
## Explained
```
›₌ɾʁẊ²vṅ⌊c
› # Increment the input
₌ɾʁ # The range [1, input + 1] and the range [0, input + 1)
Ẋ # Cartesian product of those ranges
² # Square each number in each pair
vṅ⌊ # Integer version of each pair concatenated into a single string
c # Does that contain the original input?
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
⊙…¹Iθ⊙…⁰Iθ⁼θ⪫X⟦ιλ⟧²ω
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxr1IjKDEvPVXDUEfBObG4RKNQU1NHASFsgCzsWliamFOsUaij4JWfmacRkF@eWqQRnamjkBOro2AEVFCuCQLW//8bmpgYGhj81y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string and outputs a Charcoal boolean, i.e. `-` for a concatenation of two squares, nothing if not. Explanation:
```
… Range from
¹ Literal integer `1`
θ To input
I Cast to integer
⊙ Does any satisfy
… Range from
⁰ Literal integer `0`
θ To input
I Cast to integer
⊙ Does any satisfy
θ Input as a string
⁼ Equals
⟦ιλ⟧ List of loop variables
X Vectorised to power
² Literal integer 2
⪫ ω Joined
```
] |
[Question]
[
Generate the following soccer team ASCII art with the least number of bytes possible.
```
|.| |.| |.| |.| |.| |.| |.| |.|
]^[ ]^[ ]^[ ]^[ ]^[ ]^[ ]^[ ]^[
/~`-'~\ /~`-'~\ /~`-'~\ /~`-'~\ /~`-'~\ /~`-'~\ /~`-'~\ /~`-'~\
{<| 8 |>}{<| 6 |>}{<| 1 |>}{<| 3 |>}{<| 7 |>}{<| 5 |>}{<| 4 |>}{<| 2 |>}
\|___|/ \|___|/ \|___|/ \|___|/ \|___|/ \|___|/ \|___|/ \|___|/
/ \ / \ / \ / \ / \ / \ / \ / \
/__|__\ /__|__\ /__|__\ /__|__\ /__|__\ /__|__\ /__|__\ /__|__\
| / \ | | / \ | | / \ | | / \ | | / \ | | / \ | | / \ | | / \ |
(/ \) (/ \) (/ \) (/ \) (/ \) (/ \) (/ \) (/ \)
|) (| |) (| |) (| |) (| |) (| |) (| |) (| |) (|
(.|,.,|,)(,|,.,|.)(.|,.,|,)(,|,.,|.)(.|,.,|,)(,|,.,|.)(.|,.,|,)(,|,.,|.)
```
Note that the players' feet alternate between `(.|,.,|,)` and its mirror, but their eyes all point the same direction ``-'`.
# Score
Least number of bytes wins!
# Rules
* Standard loop holes apply
* Any amount of trailing/leading white space legal.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~106~~ ~~95~~ ~~92~~ ~~91~~ ~~79~~ 77 bytes
```
”∨+!rþW∕oc σ
<7↗OKd↶!(⊞”«5βG◨“O
c∕)ÿ6T”‖B←→→→,F³‖MJ⁹¦³F6137542«ιM⁸→»↑F⁸«M⁸←←'
```
~~Try it online!~~ Edit: Saved 11 bytes by looping over the shirt numbers. Saved 3 bytes by working out how `J` worked. Saved a further byte by using separate mirror instructions. Saved 12 bytes thanks to @ASCII-only by compressing the half player string. Saved 2 bytes by repeating the mirror in a loop. Explanation:
```
”∨+!rþW∕oc σ
<7↗OKd↶!(⊞”«5βG◨“O
c∕)ÿ6T”
Print the right half of a player as a compressed string
‖B← Butterfly to create the left half of the player
→→→, Fix up the left foot
F³‖M Mirror three times to end up with 8 footballers
J⁹¦³F6137542«ιM⁸→»↑
Fix up the shirt numbers
F⁸«M⁸←←' Fix up the right eyes
```
Edit: The above code no longer works in current Charcoal; the string compression appears to have changed and the reflect command now accepts a multidirection and leaves the cursor in a different position. However it's possible to adapt the code to run in current charcoal for the same byte count. [Try it online!](https://tio.run/##TU7LisIwFF3rV1yymQRSZayP2gEXs5QRRHRlsJaSaqGTSIzCMKm/HpM@xNW59zzuudk5VZlMS2vXqhAao4Fh4rBnIjg@GGMiArOomEgSM2QCwFMmSTy4GUzDEQ/YLQNqKEHkq7/heckz/X3Tmqu8/MPxD8@1E1byzvGIQrwpTmdPdLU@lUsFOCTQpleFUlJhJyxvv5etxHMKYWdD089wNhmPEIH/fq@5UjixVzdEbw1VUxrvLl02qjMvY/tae6ReKaAP/1FlrQ3uNriWTw "Charcoal – Try It Online") Link is to verbose version of code. (Note that the deverbosifier tries to compress `6137542` for some reason although it's unnecessary.) It then becomes possible to golf a further byte off. [Try it online!](https://tio.run/##XU7LCsIwEDzrVyy5mECqaH1UBQ8eRUFETwarlFQLNZEYBTH112NT2x487c7OzM5El5OK5Cm1dq0SoTFqGyYOeya844cxJgIws4yJMDQdJgDcyYShG/kO5ncjbuActKmhBJFpcyWfHE@WPNb/YMPjlEd6/tCaqzh91USV7@yxVIB9AqV4lSglFc6JxeN620o8puBXMjTs@qNBv4cIvJuN35ckJxtFbEBhsknOF5eQlU12t8obFJ5aWDYpnxSQAmq5Rpm11nta755@AQ "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# Brainf\*\*k, ~~855~~ 852 bytes
That's *too* long...
```
+++++[>++++++>+++++++++>+++++++++>>+++++[<+++++>-]>++<<<<<<-]>++>+>+>-<<<<++++++++[>...>>>.<.>.<<<...<-]>>>>>>.<<<<[>>>++<<<-]++++++++[<...>>>>+.+.---.+<<<<...>-]>>>>.<<++<<++++++++[<.>>+.>.>++++.----<<--.------.+++++++>.>.<<<<.>-]>>>>.<<<<+++++[>+++<-]<[>+<-]>>>>>>>+++++++[<+++++++>-]<+[>+>+>+>+>+>+>+>+<<<<<<<<-]>++++++>++++>->+>+++++>+++>++<<<<<<<<<<<<<++++++++[>>>---.<-.>+.<<.>>>>>>.[-]<<[>+<-]<[>+<-]<[>+<-]<[>+<-]<[>+<-]<[>+<-]>>.>>.<++.->+.+<<<-]>>>>>.<<--<--------------<<++++++++[>.>>>.<.>+++...---<.<.<.<-]>>>>>.<<<<<++++++++[>..>.<...>>>.<<<..<-]>>>>>.<<<<<++++++++[>.>.>>+++..<.>..---.<<<.<-]>>>>>.<<<<<++++++++[>.>>.<<.>.<.>>>.<<<.>>.<<.<-]>>>>>.<<<<<++++++++[>.>-------.+++++++.<...>>>.<<------.++++++<.<-]>>>>>.<<<<<++++++++[>.>>.<------.<...>-.+++++++>.<<.<-]>>>>>.<<<-<++++++++<++++[>.>.>.<--.++.--.>.<.<+.-.>.>.<.++.--.>.<++.<+.-<-]
```
Explanation:
```
+++++[
>++++++ AT CELL1
>+++++++++ AT CELL2
>+++++++++ AT CELL3
>>+++++[ AT CELL5
<+++++>-
] CELL4 = 25
>++ AT CELL6
<<<<<<-
]
>++ CELL1 = 32
>+ CELL2 = 46
>+ CELL3 = 46
>- CELL4 = 124
CELL5 = 0
CELL6 = 10
<<<< AT CELL0
++++++++[
>...>>>.<.>.<<<...<- PRINT FIRST LINE*8
]
>>>>>>. AT CELL6
<<<<[ AT CELL2
>>>++<<<-
]
CELL2 = 0
CELL3 = 46
CELL4 = 124
CELL5 = 92
++++++++[ AT CELL2
<...>>>>+.+.---.+<<<<...>- PRINT SECOND LINE*8
]
>>>>. AT CELL6
NOW PRINT 47 126 96 45 39 126 92
<<++ CELL4 = 126
<< AT CELL2
++++++++[
<.>>+.>.>++++.----<<--.------.+++++++>.>.<<<<.>- PRINT THIRD LINE*8
]
>>>>. AT CELL6
NOW PRINT 123 60 124 32 NUMBER 32 124 62 125
CELL3 = 46
<<<<+++++ AT CELL2
[
>+++<-
]
CELL2 = 0
<[>+<-]>
CELL2 = 32
CELL3 = 61
CELL4 = 126
CELL5 = 92
>>>>> AT CELL7
> AT CELL8
+++++++[
<+++++++>-
]
AT CELL8
<+ CELL7 = 50
[>+>+>+>+>+>+>+>+<<<<<<<<-]
CELL7 = 0
CELL 8 9 10 11 12 13 14 15 = 50
>++++++>++++>->+>+++++>+++>++<<<<<<<
AT CELL7
<<<<<<
AT CELL1
CELL2 = 32
CELL3 = 61
CELL4 = 126
CELL5 = 92
++++++++[
PRINT 123 60 124 32 NUMBER 32 124 62 125
>>>---. AT CELL4
<-. AT CELL 3
>+. AT CELL4
<<. AT CELL2
PRINT 56 54 49 51 55 53 52 50
EACH TIME MOVES CELL2 TO CELL5
>>>>>>.
[-] CLEAR CELL8
<
<[>+<-] CELL6 TO CELL7
<[>+<-] CELL5 TO CELL6
<[>+<-] CELL4 TO CELL5
<[>+<-] CELL3 TO CELL4
<[>+<-] CELL2 TO CELL3
<[>+<-] CELL1 TO CELL2
AT CELL1
CELL3 = 32
CELL4 = 61
CELL5 = 126
CELL6 = 92
>>.>>.<++.->+.+<<<-
]
AT CELL9
CELL9 = 0
CELL10 = 32
CELL11 = 61
CELL12 = 126
CELL13 = 92
CELL14 = 10
>>>>>.
<<
--
CELL12 = 124
<
--------------
CELL11 = 47
<<++++++++[ AT CELL9
PRINT 32 92 124 95 95 95 124 47 32
>.>>>.<.>+++...---<.<.<.<-
]
>>>>>.
<<<<<++++++++[
PRINT 32 32 47 32 32 32 92 32 32
>..>.<...>>>.<<<..<-
]
>>>>>.
<<<<<++++++++[
PRINT 32 47 95 95 124 95 95 92 32
>.>.>>+++..<.>..---.<<<.<-
]
>>>>>.
<<<<<++++++++[
PRINT 32 124 32 47 32 92 32 124 32
>.>>.<<.>.<.>>>.<<<.>>.<<.<-
]
>>>>>.
<<<<<++++++++[
PRINT 32 40 47 32 32 32 92 41 32
>.>-------.+++++++.<...>>>.<<------.++++++<.<-
]
>>>>>.
<<<<<++++++++[
PRINT 32 124 41 32 32 32 40 124 32
>.>>.<------.<...>-.+++++++>.<<.<-
]
>>>>>.
<<<-
<++++++++
CELL10 = 40
CELL11 = 46
CELL12 = 124
<++++[
PRINT 40 46 124 44 46 44 124 44 41
>.>.>.<--.++.--.>.<.<+.
PRINT 40 44 124 44 46 44 124 46 41
-.>.>.<.++.--.>.<++.<+.-<-
]
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 127 bytes
```
i³ |.|
³ ]^[
/~`-'~\
\|³_|/
/³ \
/__|__\
| / \ |
(/³_\)
|)³_(| 8ä{3Go86137542Ó./{<| & |>}
Gï2i(.|,.,|,)hr.%lr,|4ä$
```
[Try it online!](https://tio.run/nexus/v#DYk/DoIwHEb3HsClyzf4B5LaRkBlMK4cwmodITExYeWTS3gFdgduQA9Wf9N7eS91ywxaKsH9cVNw43O/G72C5zIHOgU4eRJcCAxBhHDwoEImJ/hcSi6SEdB1nFZD2bzr06E8H6tCx691w4XYgtePauKv6DJLYw1Nrtvebl69YRWndUp/ "V – TIO Nexus")
As usual, here is a hexdump:
```
00000000: 69b3 207c 2e7c 0ab3 205d 5e5b 0a20 2f7e i. |.|.. ]^[. /~
00000010: 602d 277e 5c0a 205c 7cb3 5f7c 2f0a 2020 `-'~\. \|._|/.
00000020: 2fb3 205c 0a20 2f5f 5f7c 5f5f 5c0a 207c /. \. /__|__\. |
00000030: 202f 205c 207c 0a20 282f b35f 5c29 0a20 / \ |. (/._\).
00000040: 7c29 b35f 287c 2020 1b38 e416 7b33 476f |)._(| .8..{3Go
00000050: 3836 3133 3735 3432 1bd3 2e2f 7b3c 7c20 86137542.../{<|
00000060: 2620 7c3e 7d0a 47ef 3269 282e 7c2c 2e2c & |>}.G.2i(.|,.,
00000070: 7c2c 291b 6872 2e25 6c72 2c7c 34e4 24 |,).hr.%lr,|4.$
```
[Answer]
# [SOGL](https://github.com/dzaima/SOGL), ~~92~~ ~~88~~ ~~87~~ 85 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
T◄ηψΚc∆╗*≥ζ≠/βW;θ/8ž⅔┌*lη.7¾η┐ø┘<ΟpC1ΧB‘-”ο⁸z╗≠#▲ķOjξ³Y3²‘čŗ9n8*č x"⁴⁾Jχ“r"}▓v#Χ⁶‘+čŗ
```
Explanation:
```
...‘ push a compressed version of a soccer player
-” push "-"
...‘č push ".]^[/~`-'~\\{<x>}" chopped into an array
ŗ replace [in the player, "-", with each corresponding character]
9n split into an array with each line with the length 9
8* multiply 8 times horizonally
č join into a multi-line string
x push "x"
"...“r push 86137542 converted to string
"...‘+ append to that ".,,..,,..,,..,,."
č chop into an array of the chars
ŗ replace [in the multi-line string, "x", with corresponding chars from "86137542.,,..,,..,,..,,."]
```
The compressed string is
```
|-| --- ------- --| - |-- \\|___|/ / \\ /__|__\\ | / \\ | (/ \\) |) (| (x|,.,|x)
```
with dashes (because those could be compressed with boxstrings) in place of uncommon chars, which then get replaced and then split in lines to get
```
|.|
]^[
/~`-'~\
{<| x |>}
\|___|/
/ \
/__|__\
| / \ |
(/ \)
|) (|
(x|,.,|x)
```
[Answer]
# JavaScript (ES6), ~~196~~ ~~194~~ ~~214~~ ~~210~~ 204 bytes
Early morning golf on my phone again, so there's room for improvement.
Had to sacrifice a few bytes fixing the feet which I didn't notice were alternating.
```
_=>` |.|
]^[
/~\`-'~\\
{<| 0 |>}
\\|___|/
/ \\
/__|__\\
| / \\ |
(/ \\)
|) (|
(1|,.,|2)`.replace(/.+/g,x=>x.repeat(8)).replace(/\d/g,x=>`,.86137542`[x--?(z+=x)%2:++z],z=1)
```
---
## Try it
```
o.innerText=(
_=>` |.|
]^[
/~\`-'~\\
{<| 0 |>}
\\|___|/
/ \\
/__|__\\
| / \\ |
(/ \\)
|) (|
(1|,.,|2)`.replace(/.+/g,x=>x.repeat(8)).replace(/\d/g,x=>`,.86137542`[x--?(z+=x)%2:++z],z=1)
)()
```
```
<pre id=o>
```
---
## (Outdated) Explanation
We start with a string containing the characters for a single player with each line separated by an `n`, a `0` as the placeholder for the number and with `1` & `2` used as placeholders for the punctuation marks in the alternating feet.
We split the string to an array of the individual lines on `n`, map over that array replacing each element with itself repeated 8 time and then join the array to a string using a literal newline.
Finally, we replace each number in the string with either the required player number if the number is `0` or the necessary character to complete the player's feet if the number is `1` or `2`.
[Answer]
# Ruby, 161
```
puts"|.|+]^[+/~`-'~\\+{<| %d |>}+\\|___|/+/ \\+/__|__\\+| / \\ |+(/ \\)+|) (|+(.|,.,|,)(,|,.,|.)".split(?+).map{|i|(i.center(9)*8%[8,6,1,3,7,5,4,2])[0,72]}
```
Now with alternating feet. Internally it generates 8 double sets of feet (total 16). Some of these are then removed by truncating to 72 characters per line.
# Ruby, 144
```
puts"|.|+]^[+/~`-'~\\+{<| %d |>}+\\|___|/+/ \\+/__|__\\+| / \\ |+(/ \\)+|) (|+(.|,.,|,)".split(?+).map{|i|i.center(9)*8%[8,6,1,3,7,5,4,2]}
```
Fairly simple, prints line by line, 8 partial footballers at a time and uses the `%` operator (like `sprintf`) to substitute the shirt numbers (when the string does not contain `%d` they are ignored.)
[Answer]
# Java, 391 444 bytes
EDIT: Truly fixed. God, that really made the size go up
```
class a{static void l(String s){for(int i=0;i<8;i++)System.out.print(s);System.out.println();}static void q(){int[] a={8,6,1,3,7,5,4,2};l(" |.| ");l(" |.| ");l(" ]^[ ");l(" /~`-'~\\ ");for(int i:a)System.out.print("{<| "+i+" |>}");System.out.println();l(" \\|___|/ ");l(" / \\ ");l(" /__|__\\ ");l(" | / \\ | ");l(" |) (| ");for(int i=0;i<8;i++)if(i%2==1)System.out.print("(,|,.,|.)");else System.out.print("(.|,.,|,)");}}
```
**Expanded**
```
class a
{
static void l(String s)
{
for(int i=0;i<8;i++)
System.out.print(s);
System.out.println();
}
static void q()
{
int[] a={8,6,1,3,7,5,4,2};
l(" |.| ");
l(" |.| ");
l(" ]^[ ");
l(" /~`-'~\\ ");
for(int i:a)
System.out.print("{<| "+i+" |>}");
System.out.println();
l(" \\|___|/ ");
l(" / \\ ");
l(" /__|__\\ ");
l(" | / \\ | ");
l(" |) (| ");
for(int i=0;i<8;i++)
if(i%2==1)
System.out.print("(,|,.,|.)");
else
System.out.print("(.|,.,|,)");
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~126~~ ~~124~~ ~~108~~ ~~106~~ 110 bytes
Thanks to *Emigna* for saving 7 bytes!
```
•5n¯в•vð3×Ðy"|.|
]^[
/~`-'~\
{<| ÿ |>}
\|___|/
/ÿ\
/__|__\
| / \ |
(/ÿ\)
|)ÿ(|".C.B})øJ»"(.|,.,|,)"„()‡«4×»
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@/@oYZFp3qH1FzYBGWWHNxgfnn54QqVSjV4NV2xctAKXfl2CrnpdDFe1TY3C4f0KNXa1XDE18fHxNfpc@of3x3DpA5nx8TFcNQr6CjEKNVwaIFFNrhrNw/s1apT0nPWcajUP7/A6tFtJQ69GR0@nRkdT6XDTo4Z5GpogauGh1SaHpx/a/f8/AA "05AB1E – TIO Nexus")
[Answer]
## JavaScript (ES6), ~~198~~ 197 bytes
Includes a leading line break.
```
f=(x=792)=>x--?f(x)+(x%72?'':`
`)+` |.| ]^[ /~\`-'~\\ {<| ${"75428613"[x%8]} |>} \\|___|/ / \\ /__|__\\ | / \\ | (/ \\) |) (| (${x&1?".|,.,|,":",|,.,|."})`[9*(x/9>>3)+x%9]:''
```
### Demo
```
f=(x=792)=>x--?f(x)+(x%72?'':`
`)+` |.| ]^[ /~\`-'~\\ {<| ${"75428613"[x%8]} |>} \\|___|/ / \\ /__|__\\ | / \\ | (/ \\) |) (| (${x&1?".|,.,|,":",|,.,|."})`[9*(x/9>>3)+x%9]:''
o.innerHTML = f()
```
```
<pre id=o></pre>
```
[Answer]
# Python 2.7, 179 bytes
```
print"\n".join(s*8for s in" |.| * ]^[ * /~`-'~\ *{<| %s |>}* \|___|/ * / \ * /__|__\ * | / \ | * (/ \) * |) (| *(%s|,.,|%s)".split("*"))%tuple("86137942"+".,,."*4)
```
Encode one player as a single string with out-of-band characters to let us split it into a list, so that we can then multiply each layer by 8 and finally insert the required numbers and punctuations into the output.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~207~~ ~~197~~ ~~186~~ 201 bytes
```
b=[x*8for x in" |.| # ]^[ # /~`-'~\ ## \|___|/ # / \ # /__|__\ # | / \ | # (/ \) # |) (| ".split("#")]+["(.|,.,|,)(,|,.,|.)"*4]
for y in'86137542':b[3]+='{<| %s |>}'%y
print'\n'.join(b)
```
[Try it online!](https://tio.run/nexus/python2#HY5BDoIwFET3nuKnDWkLtURBJUa8CMUaFiYYAwRYQPxydfx0MZPJe5tZq7yYwuzV9jBB3TAAQIPUnFI@Cr/i5bkXiwXOwaJzDuNNx@Ss10ScIw1I0FJzkN6qjSlaEoGZofvUo2ScqTIqmDSojUatpPbDKBam5W57MtMTkZ0PyeWUHsW1KpIyysX3hhAMgPefCOZd19fNKGwjzLutG1mpdf0D "Python 2 – TIO Nexus")
Nothing very clever and way too long at ~~207~~ 197 ~~but as far as I can see, at least it prints the feet correctly~~.
**Edit** A bit better at 186
**Edit 2** Back to over 200 after spotting why the feet were not in fact right. Well hidden gotcha!
[Answer]
# PHP, 204 Bytes
```
<?=gzinflate(base64_decode(pdDLDcMwCAbgO1P8t9qS66jpIzlUWSRu6B6lmb3giAWKJawPDggAIFXQXwSk8drWoxQBYdjf59PeEAR9noIZsnwND8fFcXVMjrvj5hgNhCbMLAOC0BtphmbLhqA30obMtm0IBNGeTf8gCKnPlhGETqQZkvUOgVKVUouUnEpHzf9Vfg));
```
[Try it online!](https://tio.run/nexus/php#BcHbboIwGADg19E7FmcD2ZalHFTGWeQwbwyl7V8RWlCUhZdn37d8fn/BfJW8rUa2ItWDofcLZbWibNVT27frYLIwgegt1kdjSBFqendusyI9PpGJ2o5s4IoL76eaYhsAu7syKaf0ptN7of4S85c2fGvEzMFHQyr3/JBTaOt8V5d50NxfzVZAKCwS@DiyNHPsRUd8MeCNpkgwdpprhnt24jpYnoxbsXdOQ3K@vbIIci/P1DOTTn@YuZFzWK8/luUf "PHP – TIO Nexus")
## PHP, 205 Bytes
```
for(;$i++<11;)for($p=print"
";$c=_86137542[$p++];)echo str_pad(["|.|","]^[","/~`-'~\\","{<| $c |>}","\|___|/","/ \\","/__|__\\","| / \ |","(/ \)","|) (|",$p&1?"(,|,.,|.)":"(.|,.,|,)"][$i-1],9," ",2);
```
[Try it online!](https://tio.run/nexus/php#HY89b8IwEIZ3fsXpZFFbMYnMV1scmqFiYGkXtiQcKE1LFmKZbFzz18HJcnre5z2ddGnmLm5Se9968rVrfddc/2S/o6/vw/5zp@zjt/XSiiaKUmOsGpJwW@eba4cTtKLa0tvaLF5Xy3kuXBSVVtXVpYVb58mdf2SOHDNqLI95mEl/mr30RRHwnjKICvjjP4SCiYiTYQMAxj4JgmhEhgQKGK7IsVaDU4FkcMJNTYZSs441xwo3KOORtcIyF83MlPpdI6Ceh28eTw "PHP – TIO Nexus")
# PHP, 211 Bytes
```
for(;$i<11;)echo($p=str_pad)("
",73,$p(["|.|","]^[","/~`-'~\\","{<| ".join(" |>}{<| ",[8,6,1,3,7,5,4,2])." |>}","\|___|/","/ \\","/__|__\\","| / \ |","(/ \)","|) (|","(.|,.,|,)(,|,.,|.)"][+$i++],9," ",2));
```
[Try it online!](https://tio.run/nexus/php#HY3NDoIwEITvPkWzIbEbxhLwP6A@CGA1/gQ8SKPeXHl1LL1svp3JzBQH17jh3r10HrVFmuZ8uzSdjtzu/XlZd76ypglhPUfkdElihED1sfQ36U@zaV9VHr@FKDKPrn1qUrL/hR/lBiukmGONJRbIajbB9YFKrLWSjC1KqdCReMHagKISValxSQebR4096aAZgYGANQIYprqMozaOa2xBfjhjzofhDw "PHP – TIO Nexus")
[Answer]
# [Ook!](https://esolangs.org/wiki/Ook!), 8519 bytes
```
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook? Ook! Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook! Ook. Ook! Ook. Ook! Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook! Ook. Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook! Ook. Ook! Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook? Ook. Ook! Ook. Ook! Ook. Ook! Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook! Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook! Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook? Ook. Ook! Ook. Ook. Ook? Ook. Ook? Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook! Ook! Ook! Ook! Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook! Ook. Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook? Ook. Ook! Ook! Ook! Ook. Ook. Ook? Ook. Ook. Ook! Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook! Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook. Ook? Ook. Ook. Ook! Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook! Ook! Ook? Ook. Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook! Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook! Ook? Ook. Ook! Ook. Ook? Ook. Ook! Ook. Ook? Ook. Ook! Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook! Ook. Ook! Ook. Ook. Ook? Ook! Ook. Ook? Ook. Ook! Ook. Ook! Ook. Ook! Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook! Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook! Ook. Ook. Ook? Ook! Ook. Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook. Ook? Ook. Ook! Ook. Ook. Ook? Ook! Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook! Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook. Ook? Ook! Ook. Ook? Ook. Ook! Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook? Ook. Ook! Ook. Ook! Ook. Ook! Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook! Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook! Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook? Ook. Ook! Ook. Ook! Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook! Ook. Ook. Ook? Ook! Ook. Ook. Ook? Ook! Ook. Ook? Ook. Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook! Ook. Ook? Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook. Ook. Ook? Ook! Ook. Ook. Ook? Ook! Ook. Ook? Ook. Ook! Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook? Ook. Ook! Ook! Ook? Ook!
```
I had to.
Port of [tony200910041's brainf\*\*k answer](https://codegolf.stackexchange.com/a/119394/44998)
[Answer]
# C#, 420 bytes
Golf:
```
using System;using static System.Console;class Z{static void Main(){int[]a={8,6,1,3,7,6,4,2};int i=0;X(" |.| ");X(" ]^[ ");X(" /~`-'~\\ ");for(i=0;i<8;i++)Write("{<| "+a[i]+" |>}");WriteLine();X(" \\|___|/ ");X(" / \\ ");X(" /__|__\\ ");X(" | / \\ | ");X(" (/ \\) ");X(" |) (| ");for(i=0;i<8;i++)Write((i%2==0)?"(.|,.,|,)":"(,|,.,|.)");}static void X(String s){for(int i=0;i<8;i++)Write(s);WriteLine();}}
```
Expanded:
```
using System;
using static System.Console;
class Z
{
static void Main()
{
int[]a={8,6,1,3,7,6,4,2};
int i=0;
X(" |.| ");
X(" ]^[ ");
X(" /~`-'~\\ ");
for(i=0;i<8;i++)
Write("{<| "+a[i]+" |>}");
WriteLine();
X(" \\|___|/ ");
X(" / \\ ");
X(" /__|__\\ ");
X(" | / \\ | ");
X(" (/ \\) ");
X(" |) (| ");
for(i=0;i<8;i++)
Write((i%2==0)?"(.|,.,|,)":"(,|,.,|.)");
}
static void X(String s)
{
for(int i=0;i<8;i++)
Write(s);
WriteLine();
}
}
```
Inspired by Jesse M's Java answer, with a few edits to make it shorter
[Answer]
## Mathematica 282 bytes
```
d={" |.| "," ]^[ "," /~`-'~\\ ",StringRiffle[{8,6,1,3,7,5,4,2},{"{<| "," |>}{<| "," |>}"}]
," \\|___|/ "," / \\ "," /__|__\\ "," | / \\ | "," (/ \\) "," |) (| ", "(.|,.,|,)"};f[x_, y_] :=Table[Row@Table[d[[i]],8],{i,x,y}];Column@Flatten@Join[{f[1,3],d[[4]],f[5,11]}]
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 270 bytes
```
A |.|AKKKKKKK ¶A ]^[AJJJJJJJ NEEEEEEEE¶{<| 8H6H1H3H7H5H4H2 |>} N\|___|/GGGGGGG ¶MMMM NDDDDDDDDNCCCCCCCCNLLLLN|)A (|IIIIIII ¶BBBB
N
¶
M
AFAAFA
L
(F)A(F)A
K
AA|.|A
J
AA]^[A
I
A|)A (|
H
|>}{<|
G
A\|___|/
F
/A \
E
/~`-'~\A
D
/__|__\A
C
| / \ |A
B
(.|,.,|,)(,|,.,|.)
A
```
[Try it online!](https://tio.run/##Lc5NTsMwEAXg/TvF7EikEIuWli4Q0uSvTtr4AqSYLrpgwwKxY9pj5QC5WDrG@WRLT7L19H4uv1/f53kGk@TCh4imken08c5dRK5eTOPfq9DObu2TXdsXu7HPdkXydiU3iPdezD7Sil6RqxauXLijcpIyJdJG@rlQcJhGQg9uWA@OSJqUw8UBzGEgOg1hGVpw7IBFGBB2YQ9eZqCBYRpQw9w@Hx9uA6OC0RfvNZYQMjSQFhZIcsnyTLI0yf5DnoJBNM93 "Retina – Try It Online")
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~130~~ 117 bytes
```
00000000: a4c6 bb0d 4231 0c86 d1de 537c 1d89 1412 ....B1....S|....
00000010: f1a6 402c 42c0 ecc1 cf9d 1d5d 244f e053 ..@,B......]$O.S
00000020: 1d40 5d40 3206 3c5f 0f20 1963 2cef ed66 .@]@2.<_. .c,..f
00000030: 9964 639f 9bb8 a2fb 77cd 39b2 8b1c 2297 .dc.....w.9...".
00000040: c829 728c ecd7 604c b9bb 06c9 180c 6042 .)r...`L......`B
00000050: 36c6 7097 fb24 1b43 0c26 221b a30c 6056 6.p..$.C.&"...`V
00000060: b231 5481 2292 b1d2 d57a 53ab a5fd d3eb .1T."....zS.....
00000070: 6fe4 8900 00 o....
```
[Try it online!](https://tio.run/##fdFNSxxBEAbgu7/iRSQQkKK7@jt4WNZrIIcVb6JT1dNeDIoggeB/31SvI@RkMdRhoJ6uD3kTeVof334fj26LH1iiZoi4jsjBw2nN6L6vSKEofK8NPnoGyGLvZz68z3z2IXgzhl8yomM1Qx1WVQ8drVt56uAYB1aXwjR2l3s6xd3FLzpsBpvhe3RIMwV2GUHTgBvs4FsOYF3N6DmbsbvbMV3dE0gvicZmBDNayxE5tIEmUrHwEJSiHaEJo4pXMLdiRtdTE3@oWT7/nCWaoZUbCle1MXpBdlEhxsFltVVUp/Pf3Mf3V6t9@PkxzsN@M5IZIdtOi7OXhnCElxhssZztdS9YwslINkumF6ILuqZv59O43YxshsxrpFj9bJkhvjN6KovdZTEjjY4eVrE@/A3Navp7oP/uUszIY42ozTnY91U8z8Lj8R8 "Bubblegum – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 206 bytes
```
say$_ x 8 for' |.| ',' ]^[ ', " /~`-'~\\ ";print"{<| $_ |>}"for 8,6,1,3,7,5,4,2;say;say$_ x 8 for' \\|___|/ ',' / \\ ',' /__|__\ ',' | / \\ | ',' (/ \\) ',' |) (| ';say'(.|,.,|,)(,|,.,|.)'x4
```
[Try it online!](https://tio.run/##XYxNDoIwEIWvMmlMWpKhBQUlwXgDT2C1utCExAABFhhHjm4dys7N5P3M@9p798y972@vlYMRCng0nQQA0sRX4qzPl1PQIMBM11hO1oIo266qB/HeE/CSDh/BSyhwiylucIc5ZrgumVv@sa0l5xyZBW6YzLhgDMfO2aCJG84pGLV8RUsTsVFczGCpNKFGwkhhEDqSY@b9t2mHqql7Hx9znaTJDw "Perl 5 – Try It Online")
It's ugly and brute force, but it works.
[Answer]
# Deadfish~, 4964 bytes
```
{i}cc{ii}iiccc{{i}d}iic{{d}ii}iic{{i}dd}ddc{{d}i}ddcccccc{{i}d}iic{{d}ii}iic{{i}dd}ddc{{d}i}ddcccccc{{i}d}iic{{d}ii}iic{{i}dd}ddc{{d}i}ddcccccc{{i}d}iic{{d}ii}iic{{i}dd}ddc{{d}i}ddcccccc{{i}d}iic{{d}ii}iic{{i}dd}ddc{{d}i}ddcccccc{{i}d}iic{{d}ii}iic{{i}dd}ddc{{d}i}ddcccccc{{i}d}iic{{d}ii}iic{{i}dd}ddc{{d}i}ddcccccc{{i}d}iic{{d}ii}iic{{i}dd}ddc{{d}i}ddccc{dd}ddc{ii}iiccc{iiiiii}icicdddc{dddddd}icccccc{iiiiii}icicdddc{dddddd}icccccc{iiiiii}icicdddc{dddddd}icccccc{iiiiii}icicdddc{dddddd}icccccc{iiiiii}icicdddc{dddddd}icccccc{iiiiii}icicdddc{dddddd}icccccc{iiiiii}icicdddc{dddddd}icccccc{iiiiii}icicdddc{dddddd}iccc{dd}ddc{ii}iic{i}iiiiic{{i}dd}dc{ddd}c{ddddd}dcddddddc{{i}d}dddc{ddd}ddddc{dddddd}cc{i}iiiiic{{i}dd}dc{ddd}c{ddddd}dcddddddc{{i}d}dddc{ddd}ddddc{dddddd}cc{i}iiiiic{{i}dd}dc{ddd}c{ddddd}dcddddddc{{i}d}dddc{ddd}ddddc{dddddd}cc{i}iiiiic{{i}dd}dc{ddd}c{ddddd}dcddddddc{{i}d}dddc{ddd}ddddc{dddddd}cc{i}iiiiic{{i}dd}dc{ddd}c{ddddd}dcddddddc{{i}d}dddc{ddd}ddddc{dddddd}cc{i}iiiiic{{i}dd}dc{ddd}c{ddddd}dcddddddc{{i}d}dddc{ddd}ddddc{dddddd}cc{i}iiiiic{{i}dd}dc{ddd}c{ddddd}dcddddddc{{i}d}dddc{ddd}ddddc{dddddd}cc{i}iiiiic{{i}dd}dc{ddd}c{ddddd}dcddddddc{{i}d}dddc{ddd}ddddc{dddddd}cc{dd}ddc{{i}}{i}iiic{dddddd}dddc{iiiiii}iiiic{{d}i}ddc{ii}iiiic{dd}ddddc{{i}d}iic{dddddd}ddc{iiiiii}iiicddc{dddddd}dddc{iiiiii}iiiic{{d}i}ddc{ii}iic{dd}ddc{{i}d}iic{dddddd}ddc{iiiiii}iiicddc{dddddd}dddc{iiiiii}iiiic{{d}i}ddc{ii}dddc{dd}iiic{{i}d}iic{dddddd}ddc{iiiiii}iiicddc{dddddd}dddc{iiiiii}iiiic{{d}i}ddc{ii}dc{dd}ic{{i}d}iic{dddddd}ddc{iiiiii}iiicddc{dddddd}dddc{iiiiii}iiiic{{d}i}ddc{ii}iiic{dd}dddc{{i}d}iic{dddddd}ddc{iiiiii}iiicddc{dddddd}dddc{iiiiii}iiiic{{d}i}ddc{ii}ic{dd}dc{{i}d}iic{dddddd}ddc{iiiiii}iiicddc{dddddd}dddc{iiiiii}iiiic{{d}i}ddc{ii}c{dd}c{{i}d}iic{dddddd}ddc{iiiiii}iiicddc{dddddd}dddc{iiiiii}iiiic{{d}i}ddc{ii}ddc{dd}iic{{i}d}iic{dddddd}ddc{iiiiii}iiic{{d}i}dddc{dd}ddc{ii}iic{iiiiii}c{iii}iic{ddd}iccc{iii}dc{{d}ii}iiic{d}dddddcc{iiiiii}c{iii}iic{ddd}iccc{iii}dc{{d}ii}iiic{d}dddddcc{iiiiii}c{iii}iic{ddd}iccc{iii}dc{{d}ii}iiic{d}dddddcc{iiiiii}c{iii}iic{ddd}iccc{iii}dc{{d}ii}iiic{d}dddddcc{iiiiii}c{iii}iic{ddd}iccc{iii}dc{{d}ii}iiic{d}dddddcc{iiiiii}c{iii}iic{ddd}iccc{iii}dc{{d}ii}iiic{d}dddddcc{iiiiii}c{iii}iic{ddd}iccc{iii}dc{{d}ii}iiic{d}dddddcc{iiiiii}c{iii}iic{ddd}iccc{iii}dc{{d}ii}iiic{d}dddddc{dd}ddc{ii}iicc{i}iiiiic{d}dddddccc{iiiiii}c{dddddd}cccc{i}iiiiic{d}dddddccc{iiiiii}c{dddddd}cccc{i}iiiiic{d}dddddccc{iiiiii}c{dddddd}cccc{i}iiiiic{d}dddddccc{iiiiii}c{dddddd}cccc{i}iiiiic{d}dddddccc{iiiiii}c{dddddd}cccc{i}iiiiic{d}dddddccc{iiiiii}c{dddddd}cccc{i}iiiiic{d}dddddccc{iiiiii}c{dddddd}cccc{i}iiiiic{d}dddddccc{iiiiii}c{dddddd}ccc{dd}ddc{ii}iic{i}iiiiic{iiiii}ddcc{iii}dc{ddd}iccdddc{dddddd}cc{i}iiiiic{iiiii}ddcc{iii}dc{ddd}iccdddc{dddddd}cc{i}iiiiic{iiiii}ddcc{iii}dc{ddd}iccdddc{dddddd}cc{i}iiiiic{iiiii}ddcc{iii}dc{ddd}iccdddc{dddddd}cc{i}iiiiic{iiiii}ddcc{iii}dc{ddd}iccdddc{dddddd}cc{i}iiiiic{iiiii}ddcc{iii}dc{ddd}iccdddc{dddddd}cc{i}iiiiic{iiiii}ddcc{iii}dc{ddd}iccdddc{dddddd}cc{i}iiiiic{iiiii}ddcc{iii}dc{ddd}iccdddc{dddddd}cc{dd}ddc{ii}iic{{i}d}iic{{d}i}ddc{i}iiiiic{d}dddddc{iiiiii}c{dddddd}c{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{i}iiiiic{d}dddddc{iiiiii}c{dddddd}c{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{i}iiiiic{d}dddddc{iiiiii}c{dddddd}c{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{i}iiiiic{d}dddddc{iiiiii}c{dddddd}c{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{i}iiiiic{d}dddddc{iiiiii}c{dddddd}c{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{i}iiiiic{d}dddddc{iiiiii}c{dddddd}c{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{i}iiiiic{d}dddddc{iiiiii}c{dddddd}c{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{i}iiiiic{d}dddddc{iiiiii}c{dddddd}c{{i}d}iic{{d}i}ddcc{dd}ddc{ii}iic{i}ddc{i}dddc{d}dddddccc{iiiiii}c{ddddd}dc{d}icc{i}ddc{i}dddc{d}dddddccc{iiiiii}c{ddddd}dc{d}icc{i}ddc{i}dddc{d}dddddccc{iiiiii}c{ddddd}dc{d}icc{i}ddc{i}dddc{d}dddddccc{iiiiii}c{ddddd}dc{d}icc{i}ddc{i}dddc{d}dddddccc{iiiiii}c{ddddd}dc{d}icc{i}ddc{i}dddc{d}dddddccc{iiiiii}c{ddddd}dc{d}icc{i}ddc{i}dddc{d}dddddccc{iiiiii}c{ddddd}dc{d}icc{i}ddc{i}dddc{d}dddddccc{iiiiii}c{ddddd}dc{d}icc{dd}ddc{ii}iic{{i}d}iic{{d}ii}dddc{d}iccc{i}ddc{{i}dd}iiiic{{d}i}ddcc{{i}d}iic{{d}ii}dddc{d}iccc{i}ddc{{i}dd}iiiic{{d}i}ddcc{{i}d}iic{{d}ii}dddc{d}iccc{i}ddc{{i}dd}iiiic{{d}i}ddcc{{i}d}iic{{d}ii}dddc{d}iccc{i}ddc{{i}dd}iiiic{{d}i}ddcc{{i}d}iic{{d}ii}dddc{d}iccc{i}ddc{{i}dd}iiiic{{d}i}ddcc{{i}d}iic{{d}ii}dddc{d}iccc{i}ddc{{i}dd}iiiic{{d}i}ddcc{{i}d}iic{{d}ii}dddc{d}iccc{i}ddc{{i}dd}iiiic{{d}i}ddcc{{i}d}iic{{d}ii}dddc{d}iccc{i}ddc{{i}dd}iiiic{{d}i}ddc{dd}ddc{iii}ciiiiiic{{i}dd}ddc{{d}ii}ciicddc{{i}dd}c{{d}ii}cdddcdciiiic{{i}dd}c{{d}ii}ciicddc{{i}dd}c{{d}ii}iicdddddcdciiiiiic{{i}dd}ddc{{d}ii}ciicddc{{i}dd}c{{d}ii}cdddcdciiiic{{i}dd}c{{d}ii}ciicddc{{i}dd}c{{d}ii}iicdddddcdciiiiiic{{i}dd}ddc{{d}ii}ciicddc{{i}dd}c{{d}ii}cdddcdciiiic{{i}dd}c{{d}ii}ciicddc{{i}dd}c{{d}ii}iicdddddcdciiiiiic{{i}dd}ddc{{d}ii}ciicddc{{i}dd}c{{d}ii}cdddcdciiiic{{i}dd}c{{d}ii}ciicddc{{i}dd}c{{d}ii}iicdddddc{ddd}dc
```
[Try it online!](https://deadfish.surge.sh/#LHaS932yRoRaoEjeqSdWqSN++Sdb4AEjeqSdWqSN++Sdb4AEjeqSdWqSN++Sdb4AEjeqSdWqSN++Sdb4AEjeqSdWqSN++Sdb4AEjeqSdWqSN++Sdb4AEjeqSdWqSN++Sdb4AEjeqSdWqSN++Sdb4E++RaoEVVqJ+T/+oAEVVqJ+T/+oAEVVqJ+T/+oAEVVqJ+T/+oAEVVqJ+T/+oAEVVqJ+T/+oAEVVqJ+T/+oAEVVqJ+T/+oE++RapGqqSN+5P6T/7n/5I3v5P7/k//oRqqkjfuT+k/+5/+SN7+T+/5P/6EaqpI37k/pP/uf/kje/k/v+T/+hGqqSN+5P6T/7n/5I3v5P7/k//oRqqkjfuT+k/+5/+SN7+T+/5P/6EaqpI37k/pP/uf/kje/k/v+T/+hGqqSN+5P6T/7n/5I3v5P7/k//oRqqkjfuT+k/+5/+SN7+T+/5P/6E++SNsaqT/+/kVVqqSdb5FqqT7/kjeqT/++RVWqnk//v5FVaqknW+RapPvkjeqT/++RVWqnk//v5FVaqknW+Rb+T6qSN6pP/75FVaqeT/+/kVVqqSdb5FuT6kjeqT/++RVWqnk//v5FVaqknW+RaqT7+SN6pP/75FVaqeT/+/kVVqqSdb5FqT7kjeqT/++RVWqnk//v5FVaqknW+RaT6SN6pP/75FVaqeT/+/kVVqqSdb5Fvk+qSN6pP/75FVaqSdb+T75FqkVVpFapP6gRW5J1aqTv/hFVaRWqT+oEVuSdWqk7/4RVWkVqk/qBFbknVqpO/+EVVpFapP6gRW5J1aqTv/hFVaRWqT+oEVuSdWqk7/4RVWkVqk/qBFbknVqpO/+EVVpFapP6gRW5J1aqTv/hFVaRWqT+oEVuSdWqk7/5PvkWqEaqpO/+BFVaT/+gEaqpO/+BFVaT/+gEaqpO/+BFVaT/+gEaqpO/+BFVaT/+gEaqpO/+BFVaT/+gEaqpO/+BFVaT/+gEaqpO/+BFVaT/+gEaqpO/+BFVaT/+gT75FqkaqpFVvhFbk/qH5P/6EaqpFVvhFbk/qH5P/6EaqpFVvhFbk/qH5P/6EaqpFVvhFbk/qH5P/6EaqpFVvhFbk/qH5P/6EaqpFVvhFbk/qH5P/6EaqpFVvhFbk/qH5P/6EaqpFVvhFbk/qH5P/6E++RapI3qknW+Rqqk7/5FVaT/+kjeqSdb4SN6pJ1vkaqpO/+RVWk//pI3qknW+EjeqSdb5GqqTv/kVVpP/6SN6pJ1vhI3qknW+Rqqk7/5FVaT/+kjeqSdb4SN6pJ1vkaqpO/+RVWk//pI3qknW+EjeqSdb5GqqTv/kVVpP/6SN6pJ1vhI3qknW+Rqqk7/5FVaT/+kjeqSdb4SN6pJ1vkaqpO/+RVWk//pI3qknW+E++RapG+Rv5O/+BFVaT/7k6hG+Rv5O/+BFVaT/7k6hG+Rv5O/+BFVaT/7k6hG+Rv5O/+BFVaT/7k6hG+Rv5O/+BFVaT/7k6hG+Rv5O/+BFVaT/7k6hG+Rv5O/+BFVaT/7k6hG+Rv5O/+BFVaT/7k6hPvkWqSN6pJ1b+TqBG+SN+qpJ1vhI3qknVv5OoEb5I36qknW+EjeqSdW/k6gRvkjfqqSdb4SN6pJ1b+TqBG+SN+qpJ1vhI3qknVv5OoEb5I36qknW+EjeqSdW/k6gRvkjfqqSdb4SN6pJ1b+TqBG+SN+qpJ1vhI3qknVv5OoEb5I36qknW+T75FaKqkjfvknVop5I36SdWn5iqSN+knVop5I36SdWqf+YqqSN++SdWinkjfpJ1afmKpI36SdWinkjfpJ1ap/5iqpI375J1aKeSN+knVp+YqkjfpJ1aKeSN+knVqn/mKqkjfvknVop5I36SdWn5iqSN+knVop5I36SdWqf+T+4)
Wow, out-ungolfed everyone by 25x!
] |
[Question]
[
I don't like strings with more than three vowels in a row. Can you write a program that removes all the vowels I don't want from words?
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
Input is a string containing only printable ASCII character (0x20 to 0x7E, inclusive).
Output is a string containing only runs of at most 3 consecutive vowels. If there is a run of more than 3 consecutive vowels in the input string, your program should produce an output string including the first three vowels encountered in that run, discarding any further consecutive vowels.
Y is not a vowel for the purposes of this challenge.
This is code golf, so the shortest code (in bytes) wins.
### Test Cases
```
"Aeiou" => "Aei"
"screeeen" => "screeen"
"We're queueing up for the Hawaiian movie." => "We're queung up for the Hawaiin movie."
"Spaces break runs: aei iou." => "Spaces break runs: aei iou."
```
[Answer]
# [Unreadable](https://esolangs.org/wiki/Unreadable), 1647 bytes
>
> '"""""'""'""""""'"""'""""""'""'""'"""'""""""""""'"""""""""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'""""""""'"""'"""'"""'"""'"""'"""'"""'"""'"""'"""'"""'"""""""""'""'""'""'""'""""""'""'"""'""""""""'"""""""'""'"""'"'"""""""'""'""'"""'""""""'""'"""'""'"""""""'""'"""'""""'"'"""""""'""'""'"""'""""""'""'"""'""""""""'"""
>
>
>
# Explanation
This program is equivalent to pseudocode like this:
```
while (cp = (ch = read)) + 1 {
(
(cp -= 65) ? // A
(cp -= 4) ? // E
(cp -= 4) ? // I
(cp -= 6) ? // O
(cp -= 6) ? // U
(cp -= 12) ? // a
(cp -= 4) ? // e
(cp -= 4) ? // i
(cp -= 6) ? // o
(cp - 6) ? // u
0
: 1
: 1
: 1
: 1
: 1
: 1
: 1
: 1
: 1
: 1
) ? ((--vs)+4) ? print(ch) : (++vs) : {
print(ch)
vs = 0
}
}
```
with the following variable assignments:
```
0 (unused) (13 bytes)
1 cp ( 4 bytes; occurs 20× in the code)
2 vs ( 7 bytes; occurs 5× in the code)
3 ch (10 bytes; occurs 3× in the code)
```
As you can see, I avoided variable slot 0 because `0` is such a long constant to write.
So we read each character and store the value in both `cp` and `ch`. We will modify `cp` but keep `ch` around so that we can print it if necessary. We successively subtract numbers 65, 4, 4, 6, etc. from `cp` to check if it’s each of the 10 possible vowel characters in ASCII (note the very last one doesn’t need to be an assignment).
`vs` always contains 3 less than the number of vowels still allowed to be printed. It starts out at `0`, so 3 vowels can be printed. When it reaches `-3`, we stop printing vowels.
If we encounter a *non-vowel* (including the space), we execute `print(ch)` followed by `vs = 0`. As you have probably guessed, this resets the vowels counter.
If we encounter a *vowel*, we execute `((--vs)+4) ? print(ch) : (++vs)`. Let’s break this down:
* decrement `vs`;
* if the value is now `-4`, we’ve gone too far, so don’t print anything, but increment `vs` back to `-3` so we will *continue* to refuse to print vowels;
* otherwise, print the character.
[Answer]
## [Retina](https://github.com/mbuettner/retina), 25 bytes
```
i`([aeiou]{3})[aeiou]+
$1
```
[Try it online.](http://retina.tryitonline.net/#code=aWAoW2FlaW91XXszfSlbYWVpb3VdKwokMQ&input=QWVpb3UKc2NyZWVlZW4KV2UncmUgcXVldWVpbmcgdXAgZm9yIHRoZSBIYXdhaWlhbiBtb3ZpZS4KU3BhY2VzIGJyZWFrIHJ1bnM6IGFlaSBpb3Uu)
Fairly straightforward regex substitution. This also works for the same byte count:
```
Ri`(?<=[aeiou]{3})[aeiou]
```
[Answer]
# JavaScript (ES6), 42
As an anonymous function
```
s=>s.replace(/[aeiou]+/gi,v=>v.slice(0,3))
```
[Answer]
# Pyth, 21 bytes
```
sfg3=Z&}rT0"aeiou"hZz
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?test_suite=0&input=We%27re%20queueing%20up%20for%20the%20Hawaiian%20movie.&test_suite_input=Aeiou%0Ascreeeen%0AWe%27re%20queueing%20up%20for%20the%20Hawaiian%20movie.%0ASpaces%20break%20runs%3A%20aei%20iou.&code=sfg3%3DZ%26%7DrT0%22aeiou%22hZz) or [Test Suite](http://pyth.herokuapp.com/?test_suite=1&input=We%27re%20queueing%20up%20for%20the%20Hawaiian%20movie.&test_suite_input=Aeiou%0Ascreeeen%0AWe%27re%20queueing%20up%20for%20the%20Hawaiian%20movie.%0ASpaces%20break%20runs%3A%20aei%20iou.&code=sfg3%3DZ%26%7DrT0%22aeiou%22hZz)
### Explanation:
I iterate through all chars and keep track of how many vowels I passed using a counter. Every time I pass a char, which is not a vowel, I reset the counter to 0. I reomve chars, whenever the counter is > 4.
```
sfg3=Z&}rT0"aeiou"hZz implicit: z = input string
Z = 0
f z test every char T in z; keep chars, that return true:
rT0 convert T to lower
} "aeiou" test if T is a vowel
& hZ logical and with Z+1,
gives 0 if ^ is false, otherwise Z+1
=Z update Z with this value
g3 test if 3 >= Z
s sum up all remaining chars and print
```
[Answer]
# Perl, 27 characters
(26 characters code + 1 character command line option)
```
s/[aeiou]{3}\K[aeiou]+//gi
```
Not a big deal, just a rare occasion I remember `\K` exists.
Sample run:
```
bash-4.3$ perl -pe 's/[aeiou]{3}\K[aeiou]+//gi' <<< "
> Aeiou
> screeeen
> We're queueing up for the Hawaiian movie.
> Spaces break runs: aei iou."
Aei
screeen
We're queung up for the Hawaiin movie.
Spaces break runs: aei iou.
```
[Answer]
## APL, 40 chars
```
{⍵/⍨1↓4≠⊃+/(1-⍳4)⌽¨⊂'aeiouAEIOU'∊⍨' ',⍵}
```
In English:
* `'aeiouAEIOU'∊⍨' ',⍵`: find the vowels (and prepend a space to break on rotation);
* `(1-⍳4)⌽¨⊂`: rotate 0, 1, 2, 3 times (with wrap-around) pushing to the right the boolean vector;
* `⊃+/ sum`: the rotations and unbox
* `1↓4≠`: find the different than 4, and remove the first one (to cather for the space we prepended)
* `⍵/⍨`: in the argument, keep only the element where the sum was different than 4.
[Answer]
# C, 166 bytes
not the shortest answer by far but nicely golfed I think..
```
#define V v[1][i]!=
#define P printf("%c",v[1][i]),j
j;main(i,v)char**v;{for(i=0;V 0;i++)(V 97&V 'e'&V 'i'&V 'o'&V 'u'&V 65&V 69&V 73&V 79&V 85)?P=0:j>3?j++:P++;}
```
test case:
```
$ a.exe "We're queueing up for the Hawaiian movie."
We're queung up for the Hawaiin movie.
$ wc -c vowels.c
166 vowels.c
```
[Answer]
# Javascript ES6, 43 chars
```
s=>s.replace(/([aeiou]{3})[aeiou]*/gi,"$1")
```
Test:
```
f=s=>s.replace(/([aeiou]{3})[aeiou]*/gi,"$1")
;`"Aeiou" => "Aei"
"screeeen" => "screeen"
"We're queueing up for the Hawaiian movie." => "We're queung up for the Hawaiin movie."
"Spaces break runs: aei iou." => "Spaces break runs: aei iou."`
.replace(/"/g,"").split("\n").every(s=>f((s=s.split(" => "))[0])==s[1])
```
[Answer]
## Mathematica, 68 bytes
```
a=Characters@"aeiouAEIOU";StringReplace[#,b:a~Repeated~{3}~~a..:>b]&
```
The regex answer would be the same length, but who uses regex?
[Answer]
# Java, 115 bytes
```
class a{public static void main(String[] a){System.out.println(a[0].replaceAll("(?i)([aeiou]{3})[aeiou]*","$1"));}}
```
Expects input as program parameter.
Unit test output:
```
Aei
screeen
We're queung up for the Hawaiin movie.
```
[Answer]
# [Arturo](https://arturo-lang.io), 44 bytes
```
$=>[replace&{/(?i)([aeiou]{3})[aeiou]+}"$1"]
```
[Try it](http://arturo-lang.io/playground?3W9zNk)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 60 bits1, 7.5 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md)
```
⁽AḊƛAa[3Ẏ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJzPSIsIiIsIuKBvUHhuIrGm0FhWzPhuo4iLCIiLCJzY3JlZWFlaW91ZWVuIl0=)
[Answer]
# [Tcl](http://tcl.tk/), ~~82~~ 56 bytes
Saved 26 bytes thanks to the comment of @naffetS
---
Golfed version. [Try it online!](https://tio.run/##jY4xD4IwEIV3fsULmigmmhg3EzVu7g4OwFDIgY1YsKU6EH57hargYIg33b377t4r48yYQuYxEihUklKlI8xZlqGa7rg39RnxXIfVqvbe7azGWCEIlrUpdKngJ3D37cYNAaeTVCypKeGGvXaiiSTcNGniIoUukOQS5ZlwYA/GORO45ndOi@@jY8FiUogksQukFmqNJggawxZznNHHHputbd1W6uyt@pqE3fwfwp72@C@4Y9vPQ0ntryHAPAE)
```
proc f s {regsub -all {(?i)([aeiou]{3})[aeiou]*} $s \\1}
```
Ungolfed version. [Try it online!](https://tio.run/##jU9NSwMxEL3nVzzWgh@4QvFWUOhBqCcPIh7qIuky1mCarEmmPSz57Ws21trCWpzTzPvKS6h11zXO1nC0smt6XdsNaY/WR7QCaRwtPS9QSq1RlmjP5pKU5end/cNT1Y4vr@P5PnIRMUr2l3FMTs86bEMCO4PRFopCNBw85oePFtM@p6iAYdrXjtKYohrmn@nUET6ZmJRZghu8WYfwTpjJjVRKGiS9oqu/Ah4bWZPHwpH8gGPjJ0hfQyrVW4Q4@amIm9u8Fj20q5XR78tk5v@FsvVXPiTeafvkY01z1jFB130B)
```
proc remove_vowels {s} {
regsub -all -- {([aeiouAEIOU]{1,3})[aeiouAEIOU]*} $s {\1} result
return $result
}
puts [remove_vowels "Aeiou"]
puts [remove_vowels "screeeen"]
puts [remove_vowels "We're queueing up for the Hawaiian movie."]
puts [remove_vowels "Spaces break runs: aei iou."]
# "Aeiou" => "Aei"
# "screeeen" => "screeen"
# "We're queueing up for the Hawaiian movie." => "We're queung up for the Hawaiin movie."
# "Spaces break runs: aei iou." => "Spaces break runs: aei iou."
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
r"%v+"ȯ3
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIldisiyK8z&input=IkFlaW91Ig)
```
r"%v+"ȯ3 :Implicit input of string
r :Replace
"%v+" :RegEx /[aeiou]+/gi
È :Pass each match through the following function
¯3 : Slice to length 3
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `Ṡ`, 24 bytes
```
Oı"([%]+)"kWDL+%ḄıDhṃ?3ɱ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faHm00sOdC5RiFywtLUnTtdjvf2Sjkka0aqy2plJ2uIuPturDHS1HNrpkPNzZbG98cuOS4qTkYqjaBbuDCxKTU4sVkopSE7MVikrziq0UElMzFTLzS_UgSgA)
Feel like maybe I'm doing something wrong
## Explained
```
Oı"([%]+)"kWDL+%ḄıDhṃ?3ɱ
O # Split the input on spaces
ı # to each item in that:
"([%]+)"kWDL+%Ḅ # split on the regex ([AEIOUaeiou]+) - the () makes it so that the group is retained
ı # to each group:
Dhṃ? # if it starts with a vowel:
3ɱ # keep only the first three items
# Ṡ flag joins on spaces before printing
```
[Answer]
# [Perl 6](http://perl6.org), ~~36~~ 35 bytes
```
{S:g:i/(<[aeiou]>**3)<[aeiou]>+/$0/} # 36 bytes
```
```
$ perl6 -pe 's:g:i/(<[aeiou]>**3)<[aeiou]>+/$0/' # 34 + 1 = 35 bytes
```
usage:
```
$ perl6 -pe 's:g:i/(<[aeiou]>**3)<[aeiou]>+/$0/' <<< "
> Aeiou
> screeeen
> We're queueing up for the Hawaiian movie.
> Spaces break runs: aei iou."
```
```
Aei
screeen
We're queung up for the Hawaiin movie.
Spaces break runs: aei iou.
```
[Answer]
## C (205 bytes)
```
#include <stdio.h>
#define T(x)for(i=0;i<10;++i){if(v[i]==x){b=x;m=1;break;}}putchar(c);
main(b,c,i,m){char v[]="aeiouAEIOU";
while((c=getchar())!=EOF){if(!m){T(c);}else{if(b==c)continue;else{m=0;T(c);}}}}
```
(One line break added for clarity)
[Answer]
## Scala, 107 bytes
```
readLine.foldLeft("",0)((a,n)=>if(!"aeiou".contains(n|32))a._1+n->0 else if(a._2>2)a else(a._1+n,a._2+1))_1
```
[Answer]
## Seriously, 34 bytes
```
,;ù0╗`Ok"aeiou"Okd-Y;╜+*;╗4>`M@░εj
```
Hex Dump:
```
2c3b9730bb604f6b226165696f75224f6b
642d593bbd2b2a3bbb343e604d40b0ee6a
```
[Try it online](http://seriouslylang.herokuapp.com/link/code=2c3b9730bb604f6b226165696f75224f6b642d593bbd2b2a3bbb343e604d40b0ee6a&input=we%60re%20QuEuEiNg%20for%20the%20HaWaIiAn%20movie)
It uses the same algorithm as the Pyth answer, mapping over the string while keeping track of the length of the current run of vowels in a register, incrementing it whenever the current character is a vowel, and checking whether it has exceeded the allowed length, returning 0 if so, and then filtering the original string with this generated filter. It will be a lot shorter once we can use set subtraction on strings. (The `Ok` can be deleted and the `Okd` can be replaced with just `@`). I hear this feature is coming in the next update....
[Answer]
## [x86 MS-DOS .COM file](https://en.wikipedia.org/wiki/COM_file), ~~44 bytes~~ 36 bytes
.COM files are widely supported from MS-DOS 1 through the present---I'm running in dosemu, using 8086 commands only.
Reduced from 44 to 36 bytes by using REPNE SCASB to test for vowels instead of using a separate command to test each vowel.
```
Hex dump, reversible using `xxd -r -seek -256`:
0100: b3 03 43 b4 08 cd 21 88 c2 24 df b1 05 bf 1f 01 ..C...!..$......
0110: f2 ae 74 02 b3 05 4b 74 e9 b4 02 cd 21 eb e4 41 ..t...Kt....!..A
0120: 45 49 4f 55 EIOU
Unassembled using debug:
0100 B303 MOV BL,03 ; initialize counter to 3 (will increment by 1 to be 4)
0102 43 INC BX ; increment counter--runs each time it hits 0 so it never goes <0
0103 B408 MOV AH,08 ;
0105 CD21 INT 21 ; with AH=8, read 1 char without echo
0107 88C2 MOV DL,AL ; copy input for potential output
0109 24DF AND AL,DF ; make input uppercase for testing
010B B105 MOV CL,05 ; count of 5 vowels to test against
010D BF1F01 MOV DI,011F ; location of first vowel to test against
0110 F2AE REPNE SCASB ; test input against each vowel
0112 7402 JZ 0116 ; if input was not a vowel:
0114 B305 MOV BL,05 ; reset counter to 5 (will decrement by 1 to be 4)
0116 4B DEC BX ; decrement counter regardless
0117 74E9 JZ 0102 ; if hit 0 (fourth or later vowel): goto 102
0119 B402 MOV AH,02 ;
011B CD21 INT 21 ; with AH=2, print char
011D EBE4 JMP 0103 ; go to 103 for next character
bytes 011f-0123 contain the uppercase vowels AEIOU
```
[Answer]
# Matlab / Octave, 54 bytes
```
@(s)regexprep(s,'(?<=[aeiouAEIOU]{3})[aeiouAEIOU]','')
```
Example:
```
>> @(s)regexprep(s,'(?<=[aeiouAEIOU]{3})[aeiouAEIOU]','')
ans =
@(s)regexprep(s,'(?<=[aeiouAEIOU]{3})[aeiouAEIOU]','')
>> ans('We''re queueing up for the Hawaiian movie.')
ans =
We're queung up for the Hawaiin movie.
```
[**Try it at ideone**](http://ideone.com/cFiyjI).
[Answer]
# [V](https://github.com/DJMcMayhem/V), 21 bytes (noncompeting)
```
ñ[aeiou]ñÍãqû3}úsq*
```
[Try it online!](http://v.tryitonline.net/#code=w7FbYWVpb3Vdw7HDjcOjEnHDuzN9w7pzEnEq&input=IkFlaW91Igoic2NyZWVlZW4iCiJXZSdyZSBxdWV1ZWluZyB1cCBmb3IgdGhlIEhhd2FpaWFuIG1vdmllLiIKIlNwYWNlcyBicmVhayBydW5zOiBhZWkgaW91LiI)
Explanation:
```
ñ[aeiou]ñ "Assign the string `[aeiou]` to register 'q'
Íã "Search and replace on multiple lines (case insensitive):
<C-r>q "Register 'q'
û3} "Repeated 3 times
ús "Mark the following to be removed:
<C-r>q* "Register 'q' repeated any number of times
```
This is just barely shorter than the more straightforward solution:
```
Íã[aeiou]û3}ús[aeiou]*
```
(22 bytes)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes
```
ḟ€ØckŻḣ€4FḊ
```
[Try it online!](https://tio.run/##y0rNyan8///hjvmPmtYcnpGcfXT3wx2LgWwTt4c7uv4fbteM/P9fyTE1M79USUdBqTi5KBUI8kDs8FT1olSFwtLU0tTMvHSF0gKFtPwihZKMVAWPxPLEzMzEPIXc/LLMVD2Q4uCCxOTUYoWkotTEbIWi0rxiK4XE1EwFoLF6SgA "Jelly – Try It Online")
Copy-paste from [my answer to a similar challenge](https://codegolf.stackexchange.com/a/260594/85334), except somehow even worse. `e€Øc‘×¥\<4x@` is nicer for one more byte (check edit history for an explanation).
```
€ For each character of the input,
ḟ filter out
Øc vowels.
Ż Prepend a 0 to the input, and
k partition that after truthy (nonempty) positions in the original.
ḣ€4 Keep the first 4 elements of each slice,
F flatten the slices,
Ḋ and remove the 0.
```
[Answer]
# Ruby, 44 bytes
```
><<$<.read.gsub(/([aeiou]{3})[aeiou]+/i,'\1')
```
Example:
```
% ruby -e "$><<$<.read.gsub(/([aeiou]{3})[aeiou]+/i,'\1')" <<< "
Aeiou
screeeen
We're queueing up for the Hawaiian movie.
Spaces break runs: aei iou."
Aei
screeen
We're queung up for the Hawaiin movie.
Spaces break runs: aei iou.
```
] |
[Question]
[
A drug comes in 5mg, 2.5mg, and 1mg sized pills. The drug is taken once a day. The total daily dose will be only one of the following (all in mg):
1, 2, 3, ... 20, 22.5, 25, 27.5, 30, 32.5, 35, 37.5, 40, 42.5, 45, 47.5, 50
In words: any whole number less or equal to 20, then at 2.5mg increments up to 50.
Your task is to determine how many pills of each size the patient should take to get to their total dose, minimizing the total number of pills they have to take.
Input: the total daily dose
Output: the respective number of 5mg, 2.5mg, and 1mg the patient needs to take, in any consistent format.
This is code golf. Fewest number of bytes wins.
Examples: (output is number of 1, 2.5, and 5 mg pills)
```
1 => [1, 0, 0]
4 => [4, 0, 0]
7 => [2, 0, 1]
19 => [4, 0, 3]
22.5 => [0, 1, 4]
40 => [0, 0, 8]
```
*Irrelevant: this is based on a true story. The drug is prednisone and I wrote a program to automate the production of a calendar for patients to use to titrate their doses, which is a challenging task for many elderly patients to do safely even if you give them written instructions. This challenge was part of the programming task.*
[Answer]
# [R](https://www.r-project.org/), ~~53~~ 38 bytes
```
function(x)c(x%/%5,2*x%%1,(x<20)*x%%5)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjNZo0JVX9VUx0irQlXVUEejwsbIQBPENtX8n6ZhqMmVpmECIsxBhKEliDQy0jMFixto/gcA "R – Try It Online")
Output is in the order (5mg, 2.5mg, 1mg).
For the 2.5mg pills:
* if the dose is an integer, we need 0 such pills. Indeed, 1 pill of 2.5 mg would not give an integer, and 2 pills of 2.5 mg can be replaced by a single 5mg pill
* if the dose `x` is not an integer, we need exactly 1 such pill (similar argument), and then we call the function with the integer `x-2.5`.
The number of 5 mg pills is the integer division of the input by 5.
Note that because the input is restricted, the 1 mg pills are never needed when the input is ≥20. If the input is <20, the number of 1mg pills is given by taking the input modulo 5.
[Answer]
# [Python](https://docs.python.org/2/), 27 bytes
```
lambda x:[x//5,x%1*2,x*6%5]
```
[Try it online!](https://tio.run/##HcrBCoJAFIXhfU9xEISSWzrXGSuhXsRcGDEk1Cji4vb00x0XPxw@zvxb31Pg6G@P@Bm@z9cAaTspS0eSm4JJiiZ3ffTTAsEY0BkCE2qCJTjChXAlmEpTMI2mZNRYjfmkH06d06rV7GY2tZmr@naHeRnDCiFkx3tG8Hs5xD8 "Python 2 – Try It Online")
An improvement to [Manish Kundu's Python 3 solution](https://codegolf.stackexchange.com/a/210827/20260).
The new part is `x*6%5` for the last entry. The idea is to take the value mod 5 for whole `x`, but to give 0 for the non-integer doses, which are multiples of 2.5. To do this, we multiply by 6 before reducing mod 5. Because \$ 6 \equiv 1\$ modulo 5, multiplying by 6 leaves integers unchanged mod 5, but it turns multiples of 2.5 into multiples of 5, which then reduce to 0.
In the second entry, `x%1*2` could also be `x*2%2` as an equal-length alternative. This may be useful for porting, if a language's mod operation only works on whole numbers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-pgae)
```
d5ḞƑƇ;Ø.ṁ3
```
A monadic Link accepting the dosage which yields a list of numbers, `[#5, #1, #2.5]`
**[Try it online!](https://tio.run/##AR8A4P9qZWxsef//ZDXhuJ7GkcaHO8OYLuG5gTP///8yMi41 "Jelly – Try It Online")**
### How?
```
d5ḞƑƇ;Ø.ṁ3 - Link: dosage e.g. 22.5 OR 23
5 - five 5 5
d - div-mod [4, 2.5] [4, 3]
Ƈ - filter keep if:
Ƒ - is invariant under:
Ḟ - floor [4] [4, 3]
Ø. - [0, 1] [0, 1] [0, 1]
; - concatenate [4, 0, 1] [4, 3, 0, 1]
3 - three 3 3
ṁ - mould like [4, 0, 1] [4, 3, 0]
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 25 bytes
This defines a verb that takes as input the list of pills like `[2, 1, 4]` and outputs the sum of the pills milligrams. As this is Brachylog, we can then give an output like `24.5` an ask for a solution for the input.
```
Ṫℕᵐ<ᵛ⁵⁰;[1.0,2.5,5.0]\×ᵐ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HOVY9apj7cOsHm4dbZjxq3PmrcYB1tqGegY6RnqmOqZxAbc3g6UFb7//@o/0YmeqYA "Brachylog – Try It Online") (Note: you have to give the output as a float, e.g. `20.0`.) Or [try all possible inputs.](https://tio.run/##LY09CgIxEEavsmxhYwyZ/LiK4kV0C7XQQhBsFhEtFhHsbMTCG1jZbBHL9STJReJ8YPHC8OYNWezmy/V@s13pdKjyrDfJ8qpzipd3rOvwuR5Dc0vBv@L5ztM4NM/Wt340JamElk44qcrZ98G7bkp/q4RhLMNb0WcKZsAMGVJ4UBJSQkuICTUhJ/SEA8KFxoXGbxqJLngycAbOwBk4C2fhLJyFc@zK9AM)
### How it works
```
Ṫℕᵐ<ᵛ⁵⁰;[1.0,2.5,5.0]\×ᵐ+
Ṫ the input is a triplet [A, B, C]
ℕᵐ all elements are >= 0
<ᵛ⁵⁰ and less than 50 (just to give the search some bounds)
;[1.0,2.5,5.0] append the list of pill sizes
\ transpose: [[A,1.0],[B 2.5],[C,5.0]]
×ᵐ map multiplication over it
+ sum the result
```
Some notes: because Brachylog will try counting the trailing numbers up (`0 0 48, 0 0 49, 0 1 0, 0 1 1, …`), this guarantees that the first hit is also the solution with the fewest pills. `1,2.5,5` is not possible as otherwise the search will skip `A = 0, C = 0` for whatever reason. Also, some day I'll find a better way to constrain numbers in `0 … X` than `ℕᵐ<ᵛX` …
[Answer]
# [Rockstar](https://codewithrockstar.com/), ~~127~~ ~~120~~ ~~118~~ ~~110~~ 100 bytes
Borrowing [Robin's](https://codegolf.stackexchange.com/a/210823/58974) logic.
Output order is `1, 2.5, 5` separated by newlines
```
listen to N
let F be N/5
turn down F
let M be N
turn down M
let M be N-M
say N-M*5-F*5
say M*2
say F
```
[Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in)
```
listen to N :Read input string into variable N
let F be N/5 :Divide N by 5 and assign to variable
turn down F :Floor F
let M be N :Assign N to variable M
turn down M :Floor M
let M be N-M :Reassign N-M to M
say N-M*5-F*5 :Output N-M*5-F*5
say M*2 :Output M*2
say F :Output F
```
[Answer]
# [J](http://jsoftware.com/), 22 bytes
Returns in pill order `5 2.5 1`, based on [@Robin Ryder's answer](https://codegolf.stackexchange.com/a/210823/95594)
```
<.@%&5,(~:<.),5&|*20>]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/bfQcVNVMdTTqrGz0NHVM1Wq0jAzsYv9rcqUmZ@QraFinaSoZKGhk6hkZaOpoGBloG@mZamXqGRpr/gcA "J – Try It Online")
### How it works
```
<.@%&5,(~:<.),5&|*20>]
20>] x greater than 20?
5&|* multiply with x mod 5
(~:<.), prepend (x != floored x)
<.@%&5, prepend (divide x by 5 and floor)
```
[Answer]
# Excel, 64 bytes
```
=MOD(A1,5)-2.5*(A1<>INT(A1))&","&1*(A1<>INT(A1))&","&TRUNC(A1/5)
```
Input is in cell `A1`.
Working backwards:
`TRUNC(A1/5)` gives the max number of 5mg pills by dividing and truncating.
`1*(A1<>INT(A1))` gives the 2.5mg pill count as `1` if the dose is decimal and `0` if it isn't.
`MOD(A1,5)-2.5*(A1<>INT(A1))` gives the 1mg pill count by taking whatever's left from dividing by 5 and subtracting 2.5 if the dose is a decimal.
[](https://i.stack.imgur.com/tSoGC.png)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~68~~ ~~64~~ ~~57~~ ~~51~~ ~~43~~ ~~38~~ ~~36~~ ~~34~~ 32 bytes
```
lambda x:[x//5,x%1*2,(x<20)*x%5]
```
[Try it online!](https://tio.run/##HcrdCoJAEMXx@57iIAirTLk7un1I9SLmhRFLQqmIF9PTb6MXfzj8ONNveY9DGcPtET/d9/nqIHUjReFJUpczGbmyzXJJfRvDOEPQD2gcgQkloSJ4wplwITirKbijpuTUWI35oB9eO62rVKs2q9Y287atd5jmfliMEJL9PSEEI1kW/w "Python 3 – Try It Online")
Outputs in order (5, 2.5, 1).
Explanation: Uses as many 5 mg pills as possible, one pill of 2.5 mg if x % 5 = 2.5, otherwise none, and remaining sum is formed using 1 mg pills.
*-11 bytes thanks to Stef*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
5‰`D.ïD≠Š*)
```
Output is in the order `[5, 2.5, 1]`.
[Try it online](https://tio.run/##yy9OTMpM/f/f9FHDhgQXvcPrXR51Lji6QEvz/39DSwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/00cNGxJc9A6vd3nUueDoAi3N/zr/ow11THTMdQwtdYyM9Ex1TAxiAQ).
**Explanation:**
```
5‰ # Divmod the (implicit) input by 5: [input//5, input%5]
` # Pop and push both values separated to the stack
D # Duplicate the input%5
.ï # Check if it's an integer (1 if truthy; 0 if falsey)
D # Duplicate that
≠ # Check that it's NOT equal to 1 (1 becomes 0; 0 becomes 1)
Š # Triple swap the top three values on the stack: a,b,c → c,a,b
* # Multiply the top two
) # Wrap all three values on the stack into a list
# (after which it is output implicitly as result)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 37 bytes
```
#&@@{2,5,10}~FrobeniusSolve~⌊2#⌋&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1nNwaHaSMdUx9Cgts6tKD8pNS@ztDg4P6cste5RT5eR8qOebrX/AUWZeSXRyrp2aQ7KsWp1wcmJeXXVXIY6XCY6XOY6XIaWOlxGRnqmQL4BV@1/AA "Wolfram Language (Mathematica) – Try It Online")
Unfortunately, `NumberDecompose[8,{10,5,2}]` is `{0,1,3/2}`, not `{0,0,4}`.
The [documentation for `NumberDecompose`](https://reference.wolfram.com/language/ref/NumberDecompose.html) states that "For integers, `NumberDecompose` returns the last solution found by `FrobeniusSolve`", but this is evidently not the case. [Try it online!](https://tio.run/##y00syUjNTSzJTE78/98lP5oroCgzryTaqELXrtqvNDcptcglNTk/tyC/OBUoqFNtaKBjqmNUG6vjk1hc4uBWlJ@UmpdZWhycn1OWGg2T1TGqiAUq4aqu0DE0qI39/x8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# JavaScript (ES6), 31 bytes
Outputs an array in the order 5mg, 2.5mg, 1mg. Essentially the same logic as [@RobinRyder](https://codegolf.stackexchange.com/a/210823/58563).
```
v=>[x=v/5|0,v%1&&1,v-(v%1+x)*5]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/M1i66wrZM37TGQKdM1VBNzVCnTFcDyNKu0NQyjf2fnJ9XnJ@TqpeTn66RpqGgoGCoqamgr68QbaijYABEsVwYKkygKkxwqjCHqjACqzDEVGFoiWKGMboKIyM9U6gKkAE6CiaYZpgYIFQAkUXsfwA "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 27 bytes
A port of [@ManishKundu's answer](https://codegolf.stackexchange.com/a/210827/58563) suggested by @KevinCruijssen.
```
v=>[v/5|0,v%1*2,(v<20)*v%5]
```
[Try it online!](https://tio.run/##HcrLDoIwEIXhvU8xG8LFEZlCRYMlYeFTIAuC4CWkNUC68t1x6OKkzT/fp7Xt3E3v73LQ5tGvg1qtKmt7lL8ErUeRwMBeRRJG1pPNWoGCmhAEQoqQIUiEE0KOcEa4IFDC4zsxIBbEhNgQI2JFzIidYCdEzBexLd9@KbfUtXSbaxm3zLVsm2syaYrdrooHM93a7hVoUCV0Rs9m7OPRPDnswb8vPj9DoMMwLNY/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
NθI⟦÷θ⁵﹪⊗θ²﹪×⁶θ⁵
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RCPaM6/EJbMsMyVVo1BHwVRTR8E3P6U0J1/DJb80KSc1BaheR8EIIRySmZtarGGmowASN9WM1dS0/v/f2FzP9L9uWQ4A "Charcoal – Try It Online") Port of @xnor's solution, saving 3 bytes over a generic solution such as a port of the other solutions. Explanation:
```
Nθ
```
Input the dose.
```
I⟦
```
Output the result on separate lines.
```
÷θ⁵
```
Integer divide the dose by 5.
```
﹪⊗θ²
```
Modulo the doubled dose by 2.
```
﹪×⁶θ⁵
```
Modulo the sextupled dose by 5.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 [bytes](https://github.com/abrudz/SBCS)
```
|⌊0 ¯1 5|.2 1 6×⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@f9qhtQvX/mkc9XQYKh9YbKpjW6BkpGCqYHZ7@qHfr/9r/j7oWFWTm5BQDlWk86t1sZKCpY2SgbaRnClKw2dCIK@3QCgWwCgA "APL (Dyalog Unicode) – Try It Online")
```
|∘⌊÷∘5,¯1∘|,5|6∘×
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v@ZRx4xHPV2HtwNpU51D6w2BdI2OaY0ZkD48/X/ao7YJj3r7HnU1H1pv/Kht4qO@qcFBzkAyxMMz@P@jrkUFmTk5xUBFGo96NxsZaOoYGWgb6Zkeng7kGhpxpR1aoQBWAQA "APL (Dyalog Unicode) – Try It Online")
```
3↑0 1,⍨(⊢∩⌊)0 5⊤⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@f9qhtQvV/40dtEw0UDHUe9a7QeNS16FHHykc9XZoGCqaPupY86t36v/Y/ULQgMyenGKhc41HvZiMDTR0jA20jPdPD04FcQyOutEMrFMAqAA "APL (Dyalog Unicode) – Try It Online")
First two are the ports of [xnor's Python answer](https://codegolf.stackexchange.com/a/210858/78410) giving `5mg 2.5mg 1mg`, and the last is from [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/210841/78410) giving `5mg 1mg 2.5mg`. The first and third are full programs, and the second is a tacit function.
### How all these work
```
|⌊0 ¯1 5|.2 1 6×⎕ ⍝ Input: single number x
.2 1 6×⎕ ⍝ (x/5)(x)(6x)
0 ¯1 5| ⍝ (x/5)(x%-1)(6x%5); x%-1==-0.5 if x%1==0.5
|⌊ ⍝ Floor then abs
|∘⌊÷∘5,¯1∘|,5|6∘× ⍝ Input: single number x
5|6∘× ⍝ 6x%5
¯1∘| ⍝ x%-1
÷∘5 ⍝ x/5
|∘⌊ , , ⍝ Concatenate all and floor then abs
3↑0 1,⍨(⊢∩⌊)0 5⊤⎕ ⍝ Input: single number x
0 5⊤⎕ ⍝ (x//5)(x%5)
(⊢∩⌊) ⍝ Discard non-integers
0 1,⍨ ⍝ Append two numbers 0 1
3↑ ⍝ Take 3 from the head
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
/Q5*2%Q1*%Q5<Q20
```
[Try it online!](https://tio.run/##K6gsyfj/Xz/QVMtINdBQSzXQ1CbQyOD/fyNzPVMA "Pyth – Try It Online")
Same as my [Python solution](https://codegolf.stackexchange.com/a/210827/77516). Output contains 3 lines: number of 5 mg pills, 2.5 mg pills and 1 mg pills respectively.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 40 bytes
```
^\d+
$*
^(1{5})*(1)*(11.5)*$
$#1 $#3 $#2
```
[Try it online!](https://tio.run/##FcdBCsIwGETh/TuF0AhthJL5kzTtCbyEFAVduHEh7sSzxwTeMHzvx@f5utXjeL7W/XI/4Tz7qG/@TX5Un@Y8eYcbdHBDbLNahRFJZBYKKxsKSMhQRAlltKCCVrRhAbM5Y63SPgZid2x1p0DqTq3uHP4 "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation:
```
^\d+
$*
```
Convert the integer part of the dose to unary.
```
^(1{5})*(1)*(11.5)*$
```
Divmod by 5, then split the remainder into 1s and an optional 2.5 (if the original dose was not an integer).
```
$#1 $#3 $#2
```
Output the numbers of the pills in the order 5s, 2.5s, 1s.
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), [~~12~~ 11 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
Based off of [Manish Kundu](https://codegolf.stackexchange.com/a/210827/90265)'s and [xnor](https://codegolf.stackexchange.com/a/210858/90265)'s answers. Gives `[1mg, 5mg, 2.5mg]`
```
ê═]²*►U¦█–)
```
[Try it!](https://zippymagician.github.io/Arn?code=Wzp2LzU6KyUxXyo2JTU=&input=MQo0CjcKMTkKMjIuNQo0MA==)
# Explained
Unpacked: `[*6%5:v/5:+%1`
```
[ Begin sequence of elements
*6%5 Perform (_ times 6) mod 5
:v/5 Floor _ divided by 5
:+%1 Double _ mod 1
] End sequence, implied
```
Variable `_` is implied. Initialized to STDIN when a program begins.
[Answer]
# [Perl 5](https://www.perl.org/) -pl, 32 bytes
```
$_=join' ',int$_/5,0+/\D/,$_*6%5
```
[Try it online!](https://tio.run/##FcrBCgIhFIXh/XmKFsZAWXqvXp1ZtOsxAlctjMGRaZ4/U/jh8MGp732V1lR6fLZcptOkczlUMqLt1byeRqt0Cef@IDAcPAQBETMWkAURiEEO5EECCqAImkEL2IL5LuBe7Oss3LDrDXsLP@x7w2J/Wz3yVr7tVtc/ "Perl 5 – Try It Online")
[Answer]
# T-SQL, 31 bytes
```
SELECT @%5-@%1*5,@%1*2,str(@)/5
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1293422/how-many-of-each-pill-to-take-to-achieve-the-total-daily-dose)**
[Answer]
# [Go](https://golang.org/), 104 bytes
```
import ."math"
func f(x float64)(int,float64,int){return int(x/5),Ceil(x)-Floor(x),int(Min(20/x,1)*x)%5}
```
[Try it online!](https://tio.run/##bY7LCsIwEEXX5itCQJiR2Bet4lpwJ/gLoTQaTJMSUgiUfntNpSvj7tzD5c487TKI9i2eHe2FMoSofrDOUyZ7z5YtZKwX/sWIHE1LJQQqtRX@VCMo4/kWeGScXOdHZ2hkCHmD/NopDQGPN22ti7C24K4MVEUeeImHgPtmXr7L6wOAdCK7eDx7uFjVBiSUiL@qTtU5VeUldVWVNX/2itQ1q5uXDw "Go – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~72~~ ~~69~~ 67 bytes
```
y;f(float x){printf("%d,%d,%d",(y=x*10)/50,y=y%50==25,!y*(y=x)%5);}
```
[Try it online!](https://tio.run/##HYvBCoQgFEX3fYUJwnth5QguQvwYKYygnCiDHtG3OzVwN4dzbl/3s49jzmQDhPnrEzvxWrcppgBcDPI/LoHcWX0UtkZJciSMck4bWVL1GhQG7Z2fE1v8FBngVbAAHdr1SDtwjvZlrZunK@78Aw "C (clang) – Try It Online")
Saved 1 thanks to @ceilingcat
Saved 2 thanks to @rtpax
Output n#5mg, n#2.5, n#1
] |
[Question]
[
Given two inputs `q n` determine if `q` is a quadratic residue of `n`.
That is, is there an `x` where `x**2 == q (mod n)` or is `q` a square mod `n`?
**Input**
Two integers `q` and `n`, where `q` and `n` are any integers `0 <= q < n`.
**Output**
A truthy or a falsey.
Optionally, print any (or all) `x` that is `x**2 == q (mod n)`
**Examples**
```
>>> quadratic_residue(1, 5)
True
>>> quadratic_residue(3, 8)
False
>>> quadratic_residue(15, 22)
True
```
**Rules**
Your code must be a program or a function. The inputs can be in any order. This is code golf, so **shortest code in bytes wins.**
If anything is unclear or otherwise needs fixing, please let me know.
**Bonuses**
* 2-byte bonus if your function accepts `q` as any arbitrary integer.
## Catalogue
```
var QUESTION_ID=65329;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=47581;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"http://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<a>'+lang+'</a>').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang.toLowerCase(),user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw>b.lang_raw)return 1;if(a.lang_raw<b.lang_raw)return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}
```
```
body{text-align:left!important}#answer-list{padding:10px;width:290px;float:left}#language-list{padding:10px;width:290px;float:left}table thead{font-weight: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="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table>
```
[Answer]
## Mathematica, 25 bytes
```
AtomQ@PowerMod[#,1/2,#2]&
```
Mathematica, being Mathematica, naturally has a builtin for calculating modulo nth roots, via `PowerMod`. If a solution exists the smallest feasible solution is returned, otherwise the original expression (plus a message).
To get an actual truthy/falsy output we pass the result to `AtomQ`, which checks whether an expression can be broken down. Integers are atomic, returning `True`, whilst the non-atomic `PowerMod[q,1/2,n]` returns `False`
Thanks to @MartinBüttner for golf tips and function hunting with me.
[Answer]
# [Par](http://ypnypn.github.io/Par/), ~~11~~ 9 bytes
```
✶X[²x%)↔,
```
Each character uses just one byte; see [here](https://github.com/Ypnypn/Par/blob/gh-pages/README.md#the-encoding).
## Explanation
```
‚ú∂ ## Read two numbers
X ## Assign second to x
[ ## Map
² ## Square
x% ## Mod x
) ##
‚Üî ## Swap
, ## Count
```
Removed two bytes thanks to Jakube.
[Answer]
# Pyth, 9 bytes
```
}Em%*ddQQ
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?test_suite_input=5%0A1%0A8%0A3%0A22%0A15&input_size=2&test_suite=0&code=%7DEm%25%2AddQQ&input=5%0A1) or [Test Suite](http://pyth.herokuapp.com/?test_suite_input=5%0A1%0A8%0A3%0A22%0A15&input_size=2&test_suite=1&code=%7DEm%25%2AddQQ&input=5%0A1)
### Explanation:
```
}Em%*ddQQ implicit: Q = first input number
m Q map all numbers d of [0, 1, ..., Q-1] to:
*dd d*d
% Q mod Q
this gives the list of all quadratic residues
E read another input number
} check, if it appears in the list of quadratic residues
```
[Answer]
# LabVIEW, ~~16~~ 15 [Equivalent bytes](http://meta.codegolf.stackexchange.com/a/7589/39490)
Counted according to my [meta post](http://meta.codegolf.stackexchange.com/a/7589/39490).
[](https://i.stack.imgur.com/yAIVn.jpg)
[](https://i.stack.imgur.com/l8KKv.jpg)
[Answer]
# Haskell, 31 bytes
Saved 3 bytes thanks to Martin Büttner.
```
q#n=elem q[mod(x^2)n|x<-[1..n]]
```
[Answer]
# Matlab, 29
This function squares all numbers from 0 to n and checks whether a square minus q is zero mod n.
```
@(q,n)any(~mod((0:n).^2-q,n))
```
[Answer]
# Prolog (SWI), 34 bytes
**Code:**
```
Q*N:-between(0,N,X),X*X mod N=:=Q.
```
**Explanation:**
Checks if any square between **0** and **N** leaves **Q** when divided by **N**.
**Example:**
```
3*8.
false
15*22.
true
```
Try it online [here](http://swish.swi-prolog.org/p/fQGBdXGu.pl)
[Answer]
## CJam, 11 bytes
```
{_,2f#\f%&}
```
This unnamed block expects `q n` on the stack and leaves `[q]` on the stack as a truthy value or `""` as a falsy value.
[Test it here.](http://cjam.aditsu.net/#code=q~%0A%7B_%2C2f%23%5Cf%25%26%7D%0A~p&input=15%2022)
Credits to Sp3000 who also came up with this solution but "couldn't be bothered posting".
### Explanation
```
_, e# Duplicate n and turn into range [0 1 ... n-1]
2f# e# Square each element in the range.
\f% e# Take each element in the range modulo n.
& e# Set intersection with q to check if any square yields q (mod n).
```
[Answer]
# J, 9 bytes
```
e.]|i.^2:
```
Usage:
```
1 (e.]|i.^2:) 5
1
3 (e.]|i.^2:) 8
0
15 (e.]|i.^2:) 22
1
```
Explanation:
```
e.]|i.^2:
i. [0..N-1]
^ to the power of
2: 2 (constant 2 function)
]| mod N
e. contains Q? (0/1 result)
```
Some J mechanics trivia:
Functions are grouped by 3 iteratively from the right and if there is one left, as in our case (`e. (] | (i. ^ 2:))`), the grouped part is called with the right argument (`N`) and the left out function (`e.`, "contains") called with the original left argument (`Q`) and the result of the grouped part.
(`e.]|i.*i.` and `e.]|2^~i.` also solves the problem with the same length.)
[Try it online here.](http://tryj.tk/)
[Answer]
# Mathematica, 27 bytes
```
PowerModList[#,1/2,#2]!={}&
```
Usage:
```
In[1]:= PowerModList[#,1/2,#2]!={}&[1,5]
Out[1]= True
```
[Answer]
# Javascript ES6, 42 bytes
```
(q,n)=>[...Array(n)].some((x,y)=>y*y%n==q)
```
Credits to @apsilers for serious bytes saved!
[Answer]
## [Seriously](https://github.com/Mego/Seriously), 20 bytes
```
,;R@,;╗@%╝`ª╜@%╛=`MΣ
```
Takes input on two lines: `q`, then `n`. Outputs a `0` if `q` is not a quadratic residue of `n`, else a positive number representing how many `x` in `[1, q]` (inclusive) satisfy `x^2 = q (mod n)`.
[Try it online](http://seriouslylang.herokuapp.com/link/code=2c3b52402c3bbb4025bc60a6bd4025be3d604de4&input=) (permalinks are having more issues, but you can copy and paste the code into a [blank page](http://seriouslylang.herokuapp.com) in the meantime)
Explanation:
```
,;R get q input, duplicate, push range(1, q+1)
@,;‚ïó move the list to the back of the stack, get n input, dupe, save in reg 0
@%‚ïù calculate q mod n and save to reg 1
`ª╜@%╛=` push this function:
ª╜@% square top of stack, push reg 0 value (n), swap, and mod
‚ïõ= push reg 1 value (q mod n), compare equality (1 if equal else 0)
MΣ map the function across the range, add results
```
[Answer]
# Python 3, ~~41~~ 40 bytes
Takes `q` and `n` and determines if `q` is in a list of squares from `0` squared to `n-1` squared.
```
lambda q,n:q in[i*i%n for i in range(n)]
```
[Answer]
# Ruby, 33 31 bytes
Saved two bytes thanks to Vasu Adari.
```
->q,n{(1..n).any?{|e|e*e%n==q}}
```
As usual Ruby's not going to beat any of the golfing languages, but it makes a good showing here.
[Answer]
# Julia, 30 bytes
```
f(q,n)=q‚àà[i^2%n for i=0:n-1]
```
This is a function `f` that accepts two integers and returns a boolean.
Ungolfed:
```
function f(q::Integer, n::Integer)
# Generate an array of quadratic residues
x = [i^2 % n for i = 0:n-1]
# Determine whether q is one of these values
return q ‚àà x
end
```
[Answer]
# JavaScript (ES6), 43 bytes
```
(q,n)=>eval('for(x=n,r=0;x--;)r+=x*x%n==q')
```
## Explanation
```
(q,n)=>
eval(` // eval allows us to use a for loop without {} or return
for(x=n,r=0;x--;) // iterate over all possible values of x
r+=x*x%n==q // r = the number of matching x values
`) // implicit: return r
```
## Test
```
q = <input type="number" id="Q" /><br />
n = <input type="number" id="N" /><br />
<button onclick="result.innerHTML=(
(q,n)=>eval('for(x=n,r=0;x--;)r+=x*x%n==q')
)(+Q.value,+N.value)">Go</button><pre id="result"></pre>
```
[Answer]
# ùîºùïäùïÑùïöùïü, 13 chars / 25 bytes
```
⟦Ѧí]ĉ⇀_²%í≔î)
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=%5B3%2C8%5D&code=%E2%9F%A6%D1%A6%C3%AD%5D%C4%89%E2%87%80_%C2%B2%25%C3%AD%E2%89%94%C3%AE%29)`
[Answer]
# Japt, 10 bytes
```
Vo d_²%V¥U
```
My first official Japt golf ever! Thanks to @ETHProductions for saving a byte!
# Ungolfed / Explanation
```
Vo d_ ² %V¥ U
Vo dZ{Zp2 %V==U} // implicit: U,V = inputs
Vo // Create a range from 0 to n-1
dZ{ } // Check if any element Z in the range satisfies the condition:
Zp2 // Is Z squared...
%V // modulo n...
==U // equal to q?
// implicit output
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=MG9WIGRfsiVWpVU=&input=MTUgMjI=)
[Answer]
# C# 6 (.Net Framework 4.6) in LinqPad, 60 Bytes
```
bool b(int q,int n)=>Enumerable.Range(1,n).Any(y=>y*y%n==q);
```
[Answer]
# [Milky Way 1.0.2](https://github.com/zachgates7/Milky-Way), 41 bytes
```
:>&{~1-:2h<:>n>;:>;<<b?{_a0_^}~;?{_0_1}}!
```
This expects `q` and `n` to be solely on the stack. It outputs a `1` or `0` for the truth and false values, respectively.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 25 bytes
```
(q,n)->issquare(Mod(q,n))
```
[Try it online!](https://tio.run/##HYg5CoAwEEWv8rHKwKRQEWz0Bp5AUgQ3AkHHqBBPH5fqLWKD04ukGQ2S2nkl3brj2C8bJtVt478oWRF/qwjdQoJbz1ezLzIM1ns1MyIRo@9zRmVeKRn1x7xiFIUxlB4 "Pari/GP – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 33 bytes
```
q=>n=>f=(t=n)=>t&&f(t-1)|t*t%n==q
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/e9m@7/Q1i7P1i7NVqPENk/T1q5ETS1No0TXULOmRKtENc/WtvC/NVdyfl5xfk6qXk5@uoabhqGmhqmmhqYmurixpoYFNnFDoGojI7DMfwA "JavaScript (Node.js) – Try It Online")
Why no one do this
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~49~~ 48 bytes
*-1 byte thanks to ceilingcat*
```
f(q,n,i,a){for(i=n;i--;)a=i*i%n==q?:a;return a;}
```
[Try it online!](https://tio.run/##dclBCsIwEEDRfU4xVAqJTIRWCmKMXsRNSBod0KmN6ar07LHu9S//8/rmfSlRjshI6NQchyTJsiGtjXKWtlSztePl6Ezq85QYnFnKhtg/ptDD6Z0DDbv7WQjiDE9HLBXMAtZeaV1RVnW4coUQZYPQKWV@4x7h8BebDqFtv7yUDw "C (gcc) – Try It Online")
Does a simple for loop, brute forcing the squares.
] |
[Question]
[
## Statement of problem
Given a set of unique, consecutive primes (not necessarily including 2), generate the products of all combinations of first powers of these primes — e.g., no repeats — and also 1. For example, given the set { 2, 3, 5, 7 }, you produce { 1, 2, 3, 5, 6, 7, 10, 14, 15, 21, 30, 35, 42, 70, 105, 210 } because:
```
1 = 1
2 = 2
3 = 3
5 = 5
6 = 2 x 3
7 = 7
10 = 2 x 5
14 = 2 x 7
15 = 3 x 5
21 = 3 x 7
30 = 2 x 3 x 5
35 = 5 x 7
42 = 2 x 3 x 7
70 = 2 x 5 x 7
105 = 3 x 5 x 7
210 = 2 x 3 x 5 x 7
```
Note that if the cardinality of your input set is k, this will give you 2^k members in your output set.
## Rules/Conditions
1. You can use any language. Aim for the smallest character count of source code.
2. Your solution must be either a complete program or a complete function. The function can be anonymous (if your language supports anonymous functions).
3. Your solution should be able to support products up to at least 2^31. Don't worry about detecting or handling integer overflow if you are passed numbers whose product is too great to represent. However, please state the limits of your calculations.
4. You may accept either a list or a set and produce either a list or a set. You may assume the input is sorted but you are not required to produce sorted output.
## Background
When or why is this useful? One place it is very useful is in generating a table of *multipliers* to race in parallel in an integer factoring algorithm known as [Square Forms Factorization](http://en.wikipedia.org/wiki/Shanks'_square_forms_factorization). There, each odd multiplier you try decreases the probability of the algorithm failing (to find a factor) by approximately 50% on hard semiprimes. So with the set of generating primes { 3, 5, 7, 11 }, which produces a set of 16 trial multipliers to race in parallel, the algorithm fails approximately 2^–16 of the time on hard semiprimes. Adding 13 to the primes list produces a set of 32 trial multipliers, reducing the chance of failure to approximately 2^–32, giving a drastic improvement in outcome at no additional computational expense (because even with twice as many multipliers racing in parallel, on average it still finds the answer in the same total number of steps).
[Answer]
# Pure Bash, 32 bytes
```
eval echo \$[{1,${1// /\}*{1,}}]
```
Reads input list (single space separated) passed as a command-line arg.
Three different shell expansions are used:
1. `${1// /\}*{1,}` is a [parameter expansion](http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) that replaces spaces in `2 3 5 7` with `}*{1,` to give `2}*{1,3}*{1,5}*{1,7`. `\$[{1,` and `}]` are added to the start and end respectively to give `\$[{1,2}*{1,3}*{1,5}*{1,7}]`. The `\$[` is backslash-escaped to prevent attempts to do arithmetic expansion at this stage.
2. `\$[{1,2}*{1,3}*{1,5}*{1,7}]` is a [brace expansion](http://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html). Because [brace expansion typically happens before parameter expansion](http://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions), we use have to use`eval` to force the parameter expansion to happen first. The result of the brace expansion is `$[1*1*1*1] $[1*1*1*7] $[1*1*5*1] ... $[2*3*5*7]`.
3. `$[1*1*1*1] $[1*1*1*7] $[1*1*5*1] ... $[2*3*5*7]` is a list of [arithmetic expansions](http://www.gnu.org/software/bash/manual/html_node/Arithmetic-Expansion.html#Arithmetic-Expansion), which are then evaluated to give the list of numbers we require.
### Output:
```
$ ./comboprime.sh "2 3 5 7"
1 7 5 35 3 21 15 105 2 14 10 70 6 42 30 210
$
```
[Answer]
# CJam, 13 bytes
```
1aq~{1$f*+}/p
```
Reads an array (e.g., `[2 3 5 7]`) from STDIN. [Try it online.](http://cjam.aditsu.net/)
An anonymous function would have the same byte count:
```
{1a\{1$f*+}/}
```
### Example run
```
$ cjam <(echo '1aq~{1$f*+}/p') <<< '[]'
[1]
$ cjam <(echo '1aq~{1$f*+}/p') <<< '[2 3 5 7]'
[1 2 3 6 5 10 15 30 7 14 21 42 35 70 105 210]
```
### How it works
```
1a " Push R := [1]. ";
q~ " Read an array A from STDIN. ";
{ }/ " For each a ‚àä A: ";
1$f*+ " R += { ra : r ‚àä R } ";
p " Print. ";
```
[Answer]
# Haskell, 22
the solution is an anonymous function:
```
map product.mapM(:[1])
```
example usage:
```
*Main> map product.mapM(:[1]) $ [2,3,5]
[30,6,10,2,15,3,5,1]
```
**explanation:**
`(:[1])` is a function which given a number `x` returns the list `[x,1]`.
`mapM(:[1])` is a function which given a list of numbers maps the function `(:[1])` over them, and returns every possible way to choose an element from every list. for example, `mapM(:[1]) $ [3,4]` first maps the function to get `[[3,1] , [4,1]]`. then the possible choices are `[3,4]` (choosing the first number of both) `[3,1]` `[1,4]` and `[1,1]` so it returns `[[3,4],[3,1],[1,4],[1,1]]`.
then `map product` maps over all choices and returns their products, which are the wanted output.
this function is polymorphic in its type meaning that it can operate on all types of numbers. you could input it a list of `Int` and the result would be a list of `Int` but could also be applied on a list of type `Integer` and return a list of `Integer`. this means that overflow behavior is not specified by this function but by the input's type (yay Haskell's expressive type system :) )
[Answer]
## Mathematica, ~~18~~ 17 bytes
```
1##&@@@Subsets@#&
```
That's an anonymous function. Call it like
```
1##&@@@Subsets@#&[{2,3,5,7}]
```
[Answer]
# Update: C (function f), 92
Even as a function, this is still the longest entry here. It's the first time I've passed an array of unknown length as a function argument in C, and apparently there is no way for a C function to know the length of an array passed to it, as the argument is passed as a pointer (regardless of the syntax used). Hence a second argument is required to indicate the length.
I kept the output to stdout, because setting up an integer array and returning it would almost certainly be longer.
Thanks to Dennis for the tips.
See the function `f` (92 characters excluding unnecessary whitespace) in the test programs below.
**Output via printf**
```
j;
f(int c,int*x){
int p=1,i;
for(i=c<<c;i--;p=i%c?p:!!printf("%d ",p))p*=(i/c>>i%c)&1?1:x[i%c];
}
main(int d,char**v){
d--;
int y[d];
for(j=d;j--;)y[j]=atoi(v[j+1]);
f(d,y);
}
```
**Output via array pointer**
```
j,q[512];
f(int c,int*x,int*p){
for(int i=-1;++i-(c<<c);p[i/c]*=(i/c>>i%c)&1?1:x[i%c])i%c||(p[i/c]=1);
}
main(int d,char**v){
d--;
int y[d];
for(j=d;j--;)y[j]=atoi(v[j+1]);
f(d,y,q);
for(j=1<<d;j--;)printf("%d ",q[j]);
}
```
# C (program),108
excluding unnecessary whitespace.
```
p=1,i;
main(int c,char**v){
c-=1;
for(i=c<<c;i--;i%c||(printf("%d ",p),p=1))(i/c>>i%c)&1||(p*=atoi(v[i%c+1]));
}
```
Input from commandline, output to stdout. C isn't going to win here, but maybe I will try converting to a function tomorrow.
Basically we iterate through all `1<<c` combinations of primes, with each bit of `i/c` being associated with the presence or absence of a particular prime in the product. The "inner loop" `i%c` runs through the primes, multiplying them according to the value of `i/c.` When `i%c` reaches 0, the product is output, then set to 1 for the next "outer" iteration.
curiously, `printf("%d ",p,p=1)` does not work (it always prints a 1.) This is not the first time I have seen odd behaviour when a value is used in a `printf` and assigned later in the same bracket. It is possible in this case that the second comma is not being treated as an argument separator, but rather as an operator.
**Usage**
```
$ ./a 2 3 5 7
1 2 3 6 5 10 15 30 7 14 21 42 35 70 105 210
```
[Answer]
# Haskell, 27 bytes
This is a Haskell implementation of @sudo's CJam answer as an anonymous function. It won't beat the awesome Haskell solution of @proud haskeller, but I'll drop it here anyway.
```
foldr((=<<)(++).map.(*))[1]
```
**Explanation:** `foldr` takes in a binary function, a value, and a list. Then it replaces each cons cell in the list by an application of the function, and the end of the list by the value, like this: `foldr f v [a,b,c] == f a (f b (f c v))`. Our value is a one-element list containing `1`, and the binary function is `f = (=<<)(++).map.(*)`. Now, `f` takes a number `n`, makes a function `(n*)` that multiplies by `n`, makes from it a function `g = map(n*)` that applies that function to all elements of a list, and feeds *that* function to `(=<<)(++)`. Here, `(++)` is the concatenation function, and `(=<<)` is *monadic bind*, which in this case takes in `(++)` and `g`, and gives a function that takes in a list, applies `g` to a copy of it, and concatenates the two.
In short: start with `[1]`, and for each number `n` in the input list, take a copy of the current list, multiply everything by `n`, and append it to the current list.
[Answer]
## Python: 55 chars
```
f=lambda l:l and[x*l[0]for x in f(l[1:])]+f(l[1:])or[1]
```
Recursively generates the products by choosing to include or exclude each number in turn.
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), 26 bytes
```
v->divisors(factorback(v))
```
Longer versions include
```
v->divisors(prod(i=1,#v,v[i]))
```
(30 bytes) and
```
v->divisors(fold((x,y)->x*y,v))
```
(31 bytes).
Note that if the input was a *factorization matrix* rather than a set, 18 bytes could be saved using `divisors` alone. But converting a set to a factorization matrix seems to take more than 18 bytes. (I can do it in 39 bytes directly as `v->concat(Mat(v~),Mat(vectorv(#v,i,1)))` or 24 bytes by multiplying and re-factoring`v->factor(factorback(v))`, can anyone do better?)
[Answer]
# Sage – ~~36~~ 34
Essentially, the same as [Martin Büttner’s solution](https://codegolf.stackexchange.com/a/38052/11354), if I understand it correctly. As I mentioned it in a comment, I might as well post it as an answer.
```
lambda A:map(prod,Combinations(A))
```
This is an anonymous function, which can for example be called as follows:
```
(lambda A:map(prod,Combinations(A)))([2,3,5,7])
```
[Answer]
# J (20)
This turned out longer than I hoped or expected.Still: shorter than haskel!
```
*/@:^"1#:@i.@(2&^)@#
```
## Usage:
```
f=:*/@:^"1#:@i.@(2&^)@#
f 2 3 5 7
1 7 5 35 3 21 15 105 2 14 10 70 6 42 30 210
```
This works for any set of numbers, not just primes. Also, the primes can be of unlimited size, as long as the array has the postfix `x`: `2 3 5 7x`
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 2 bytes
```
√¶P
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w6ZQ&input=WzIgLDMsNSw3LDExLDEzLDE3LDE5LDIzLDI5XQ)
**Explanation**
```
√¶ # powerset
P # product
```
[Answer]
# R, 56 bytes
```
r=1;for(i in 1:length(s))r=c(r,apply(combn(s,i),2,prod))
```
I'm considering here that s is the set (and a list).
I'm sure it can be made even shorter. I'll see.
[Answer]
# PHP, 97 Bytes
```
<?for(;$i++<array_product($a=$_GET[a]);){$t=$i;foreach($a as$d)$t%$d?:$t/=$d;if($t<2)echo"$i\n";}
```
] |
[Question]
[
### Introduction
In this challenge your task is to generate the ISBN-10 code for books given its ISBN-13 code, assuming that such a code exists. Such an ISBN-13 code consists of several parts separated by `-`:
```
978-GG-PPPP-TTT-C
```
The letters `G` (group), `P` (publisher), `T` (title) and `C` (checksum) all stand for one digit. For the purpose of this challenge the grouping and the computation of `C` (see [this challenge](https://codegolf.stackexchange.com/questions/342/calculate-isbn-13-check-digit)) are not interesting and we'll drop all hyphens to make this task simpler.
An ISBN-10 number has a very similar layout:
```
GG-PPPP-TTT-c
```
The letters `G`,`P` and `T` are the same as for the 13 digits ISBN, however `c` is different (and is computed using a different algorithm). The digit `c` is chosen in a way such that the following equivalence holds (digits in order):
```
10*G + 9*G + 8*P + … + 3*T + 2*T + 1*c = 0 (mod 11)
```
### Example
Let us consider the ISBN number `9780345391803`: To get its corresponding ISBN-10 code we simply drop the leading `978` and the checksum `3` yielding `034539180`.
Next we need to compute the new checksum:
```
10*0 + 9*3 + 8*4 + 7*5 + 6*3 + 5*9 + 4*1 + 3*8 + 2*0 = 185
```
The next number divisible by `11` is `187`, so the new checksum is `2` and thus the resulting ISBN-10 code `0345391802`.
### Rules
* Your input will always have a corresponding ISBN-10 number (ie. it is exactly 13 digits long and starts with `978`)
* The input doesn't necessarily have to be a valid ISBN-13 (eg. `9780000000002`)
* You're guaranteed that the resulting ISBN won't end with `X`
* You may take input as an integer or string (with or without hyphens) however a precomputed list of digits are not allowed
* Your output must be a valid ISBN-10 number (with or without hyphens)
* Your output may be an integer or string (again no lists of digits)
### Testcases
```
9780000000002 -> 0000000000
9780201882957 -> 0201882957
9781420951301 -> 1420951300
9780452284234 -> 0452284236
9781292101767 -> 1292101768
9780345391803 -> 0345391802
```
Note the leading zeroes!
[Answer]
## [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~44~~ ~~39~~ 28 bytes
```
>,L3,-2`.+
.
$.>`**
_{11}
_
```
[Try it online!](https://tio.run/##PcqxDsIwDATQ3d8BEipt5LMdEi9dWfgEpKZDBxYGxFbx7aHN0FtOT3ef5ft6z6jh/LzcSx37h/aDlHClQKcwlq6jaQV@RFOtnjILI2fxmGgTTNgjlLGLLYpkE7W2iQsY6daerBbVsXXTkT8 "Retina – Try It Online")
### Explanation
Time to show off some new Retina features. :)
```
>,L3,-2`.+
```
We match the entire input with `.+`, return that match `L`, but select only the characters 3 (zero-based) to -2 (penultimate), inclusive. We also print the result without a trailing linefeed (`>`).
Now, subtracting things in Retina is a bit annoying. But luckily, we're working modulo 11, so we can just invert the coefficients of the linear combination (mod 11) and add everything up. In other words, if the constraint is:
```
10*G + 9*G + 8*P + … + 3*T + 2*T + 1*c = 0 (mod 11)
```
then we get:
```
c = 1*G + 2*G + 3*P + … + 8*T + 9*T (mod 11)
```
That simplifies things a lot here:
```
.
$.>`**
```
We replace each character with that thing at the bottom. `*` is Retina's repetition operator. It's right-associative and it has implicit operands `$&` on the left and `_` on the right, so the substitution is actually short for `$.>`*$&*_`. `$&*_` creates a string of **d** underscores, where **d** is the digit we're currently replacing. Then `$.>`` is the length of the string up to and including the match.1 Hence, the entire expression results in a unary representation of the **n**th term of our linear combination.
```
_{11}
```
Doing the actual modulo is trivial in unary: we just drop all complete sets of 11 underscores.
```
_
```
Finally, we count how many underscores remain and print the result, which completes the ISBN-10.
---
1 How does `$.>`` give the length of the string up to and including the match? You might be familiar with `$`` in regex substitutions, which gives you the string up to (but excluding) the match. By inserting a `>`, we can shift the context of the `$`` to the *separator* between the current match and the next (which is an empty string between the current digit and the next). That separator's `$`` will include the current match. So `$>`` is a shorter way to write `$`$&`. Finally, for all `$x`-type substitution elements, Retina lets you insert a `.` after the `$` to get its length.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ ~~15~~ ~~13~~ 12 bytes
```
¦¦¦¨DSƶO11%«
```
[Try it online!](https://tio.run/##MzBNTDJM/V9TVvn/0DIwXOESfGybv6Gh6qHV/yuVDu9X0LVTOLxfSee/pbmFgbGJqbGlIZDmAvGMDAwtLIwsTc1BPEMTIwNLU0NjA0OwnImpkZGFiZGxCVjOyNLI0MDQ3AysEmEKAA "05AB1E – Try It Online")
**Explanation**
```
¦¦¦ # remove the first 3 characters
¨ # remove the last character
D # duplicate
S # split to list of digits
ƶ # multiply each by its 1-based index
O # sum
11% # mod by 11
« # concatenate
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~96~~ 84 bytes
```
$y=-(([char[]]($x="$args"-replace'^978|.$')|%{--$a*[int]"$_"})-join'+'|iex)%11;$x+$y
```
[Try it online!](https://tio.run/##DcvRCoIwFADQfxlXtiU3GhYm4ZeMFUMuuRgqM2jS@vabT@fpLPOH0jpSjMyw9aiUHUafrHMKci/Ap@cqMNES/UDy3rXXcgSpS/VFBH@wYXo7AQ/x0/iawyRrWQJlXRlzg1zDxsz7OTXnS9OZ3T8 "PowerShell – Try It Online")
Takes input `"$args"`, does a regex `-replace` to get only the pertinent part, stores that into `$x` as a string. Then we cast that as a `char`-array and loop through each letter. Inside the loop, we pre-decrement `$a` (which defaults to `0`) and multiply out according to the checksum calculation. Note the cast to `int`, else this would use ASCII values.
We then `-join` those numbers together with `+` and pipe that to `iex` (`Invoke-Expression` and similar to `eval`). We take that `%11` and store that checksum into `$y`. Finally, we string concatenate `$x + $y`, and leave that on the pipeline. Output is implicit.
*Saved 12 bytes thanks to Emigna.*
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~46 41 39~~ 37 bytes
```
@(a)[c=a(4:12) 48+mod(7+c*(1:9)',11)]
```
[Try it online!](https://tio.run/##PYxBCsIwEEX3niIbSWIlzEwmTaZQ8B7iIlS7k26K149imszm83i82ZY9f15lnZ1z5WayvS9zNjwhWcVpeG9PE4flYnASq6@I9lFWoyUmaEfaqrPqCKfDE2BKJCFW3/HwyAQS0AP@fcfecyBKTJ5r33BsPQkhYBzr/46p9Z6DF/xt7RtS@QI "Octave – Try It Online")
The code takes input as a string, and returns a string.
The code breaks down as follows:
`@(a)` creates an anonymous function.
With `[c=a(4:12) ... ]` we extract the characters that form the main code, saving a copy to `c` for later use, and adding another copy to the final output string.
Based on @MartinEnter's clever way of swapping `10:-1:2` into `1:10`, we can easily generate that range and transpose it to get a column vector. `c*(1:10)'` does array multiplication of the row vector `c` and range column vector. This is equivalent to doing an element-wise multiplication then summing.
The checksum would normally be `mod(11-sum,11)` to calculate the number required for the sum to be a multiple of 11. However, because `c` was a character string, the sum will actually be larger than it should be by 2592 (48\*54) because we multiplied by numbers that were 48 larger than the actual value.
When we perform the modulo, it will automatically get rid of all but 7 of that 2592. As such, and accounting for the negation of the range, the actual calculation becomes `48+mod(7+sum,11)`. We add on 48 to the result to convert back to an ASCII character.
The checksum character is appended to the end of the result, and the value returned.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ṫ4ṖȮV€xJS%11
```
This is a full program that uses strings for I/O.
[Try it online!](https://tio.run/##ASwA0/9qZWxsef//4bmrNOG5lsiuVuKCrHhKUyUxMf///yc5NzgwMjAxODgyOTU3Jw "Jelly – Try It Online")
### How it works
```
ṫ4ṖȮV€xJS%11 Main link. Argument: s (string of length 13)
ṫ4 Tail 4; discard the first three characters.
Ṗ Pop; discard the last characters.
Ȯ Output; print the result to STDOUT and return it.
V€ Eval each; turn digit characters into digits.
J Indices; yield [1, ..., 13].
x Repeat the first digit once, the second digit twice, etc.
S%11 Take the sum, modulo 11.
(implicit) Print the checksum to STDOUT.
```
[Answer]
# JavaScript (ES6), ~~59~~ 56 bytes
```
s=>(s=s.slice(3,-1))+[...s].reduce(n=>n+s[i++]*i,i=0)%11
```
```
f=
s=>(s=s.slice(3,-1))+[...s].reduce(n=>n+s[i++]*i,i=0)%11
//s=>(s=s.slice(3,-1))+(n=0,[...s].map((c,i)=>n+=c*-~i),n)%11
//s=>(s=s.slice(3,-1))+(n=0,[...s].map(c=>n+=c*i++,i=1),n)%11
//s=>(n=0,[...(s=s.slice(3,-1))].map((c,i)=>n+=c*-~i),s+n%11)
//s=>(s=s.slice(3,-1,n=i=0))+eval(`for(c of s)n+=c*-~i++`)%11
console.log(...[
'9780000000002',
'9780201882957',
'9781420951301',
'9780452284234',
'9781292101767',
'9780345391803'
].map(f))
```
-3 bytes thanks to [@Shaggy's suggestion](https://codegolf.stackexchange.com/questions/153624/converting-isbn-13-to-isbn-10/153655#comment375454_153655).
[Answer]
# [Perl 5](https://www.perl.org/), 49 + 1 (`-p`) = 50 bytes
```
s/^...|.$//g;$\=(eval s/./"-$&0+".$i++*$&/ger)%11
```
[Try it online!](https://tio.run/##NYxNboMwFIT3PcUTdZOmCP887ICFuEWXUSUWDrFisIWddtOz1wWqzmY0M58mmMWpnCP7oJR@U8LY2JFL/2o@BweRUVZU5MDLghJblm/kwEaznF6EyCtF@@IyFx2xPe/gOd1shGm4mwg2wZdf7nD1C0wPl2xwBuwcHilSgPebgThMBka/shuT1uZYuSP4kKyfs25a/i982hJy0baoVbMlIZFrJWou9k0qxFZiLfcNNQoumvNO8lqqWovVf/6uY66C@wU "Perl 5 – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), 16 bytes
```
%s.e*ksbpP>Q3hT
```
**[Try it here!](https://pyth.herokuapp.com/?code=%25s.e%2ahksbpP%3EQ3hT&input=%229780345391803%22&debug=0)**
# [Pyth](https://pyth.readthedocs.io), 17 bytes
```
%s*VsMKpP>Q3SlK11
```
**[Try it here!](https://pyth.herokuapp.com/?code=%25s%2aVsMKpP%3EQ3SlK11&input=%229780345391803%22&debug=0)**
### Explanation
```
%s.e*hksbpP>Q3hT || Full program. Uses string for input and output.
Q || The input.
> 3 || With elements at indexes smaller than 3 trimmed.
P || Pop (remove the last item).
p || Print the result without a linefeed, but also return it.
.e || Enumerated map. For each (index, value), assign two variables (k, b).
sb || b converted to an integer.
*hk || And multiplied by k + 1.
s || Summation.
% || Modulo by:
T || The literal 10.
h || Incremented by 1.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~16~~ 15 bytes
Came up with this down the pub the other night and forgot all about it.
```
s3J
U+¬x_*°TÃuB
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=czNKClUrrHhfKrBUw3VC&input=Ijk3ODAzNDUzOTE4MDMi)
* 1 byte saved thank to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), ~~77~~ 61 bytes
```
,,,,'~'11=\.A&.=\./';"-'"{4.8}}\'.A.>.,<\'+'%!@}/=+'+{./&{{&/
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/18HCNTr1A0NbWP0HNX0gKS@urWSrrpStYmeRW1tjLqeo56dno5NjLq2uqqiQ62@rba6drWevlp1tZr@//@W5hYGxiamxpaGQBoA "Hexagony – Try It Online")
---
Colored:
[](https://i.stack.imgur.com/oI4fh.png)
---
Here is a larger version. There are some path crossings, but because all of those cells are `.` (no-op in Hexagony), you don't need to worry about them:
(I also tried to keep the old mirrors, but sometimes I need to change something)
[](https://i.stack.imgur.com/obLU6.png)
The linear command executed is:
```
,,,,'48}}
,
while memory > 0:
';"-'"{+'+{=A&=''A
if memory < 0:
undefined behavior
&{{&}
,
'"''+~'11='%!@
```
---
Explanation: Instead of keeping a counter and do multiplication at each digit, this program:
* keep a "partial sum" variable and "total sum" variable (`p` and `t`)
* for each digit read: add it to partial sum, and add the partial sum to total sum.
* print `(-p-t)%11`, where `%` always return positive results.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~29~~ ~~25~~ ~~24~~ 23 bytes
**Solution:**
```
x,$11!7+/(1+!9)*x:-1_3_
```
[Try it online!](https://tio.run/##y9bNz/7/v0JHxdBQ0VxbX8NQW9FSU6vCStcw3jheydLcwsDE1MjIwsTI2ETp/38A "K (oK) – Try It Online")
**Examples:**
```
x,$11!7+/(1+!9)*x:-1_3_"9780000000002"
"0000000000"
x,$11!7+/(1+!9)*x:-1_3_"9780345391803"
"0345391802"
x,$11!7+/(1+!9)*x:-1_3_"9781292101767"
"1292101768"
x,$11!7+/(1+!9)*x:-1_3_"9780452284234"
"0452284236"
```
**Explanation:**
Evaluation is performed right-to-left.
Two tricks taken from other solutions:
* multiply by 1 2 3... instead of 10 9 8...
* multiply ASCII values and then add 7 to the sum to balance out
Breakdown:
```
x,$11!7+/(1+!9)*x:-1_3_ / the solution
3_ / drop three items from the start
-1_ / drop one item from the end
x: / save this as variable x
* / multiply by
( ) / all this together
!9 / til, !9 => 0 1 2 3 4 5 6 7 8
1+ / add 1 => 1 2 3 4 5 6 7 8 9
7+/ / sum (+) over (/), start from 7
11! / mod by 11
$ / convert back to a string
x, / join with x
```
**Notes:**
* **-4 bytes** thanks to [Martin Enders's](https://codegolf.stackexchange.com/a/153631/69200) "*just invert the coefficients*" magic.
* **-1 byte** thanks to [Tom Carpenter](https://codegolf.stackexchange.com/a/153641/69200) for removing the need to convert to integers (by adding `7` to the sum)
* **-1 byte** start the accumulator at 7
[Answer]
# C (gcc), ~~96 95 87 86~~ 85 bytes
(-1 thanks to ceilingcat)
```
*f(s,r,c,d)char*s,*r;{for(d=13;--d;s+=*++s<48)r=d>8?c=3,s:r,c-=~d**s;*s=58-c%11;s=r;}
```
[Try it online!](https://tio.run/##jdDNTsQgFAXgvU9BJjFpaU/CvYClIvogxsWEZnQWjgbGVVNfvcLClTHhLmBzf06@iNcY912eujymMY5LH9@OSeZRJr@ePlK3BNIeWHweghyG/GBcn8Ly6J5i0GO@L0MI34uU2cscrEO8JfI5JL/t58tVvB/Pl64X640otYq6XeTnFxHEYZ6c@i0@ePH5dc1dCdL3Xmz/9LMi53i2U1s/GVazJa2ocb@xzM6wNo37eWZSNN015lHaWD1T@dv6oRQqT33ArTOMqoTChMZcIIMqhUIFar1jULVQuGBa7zCqGApZczZV1hc1FDb8ddv2Hw)
To be called as `f(s)`, where `s` is a pointer to the first element of a modifiable character array. Modifies the input array, returns a pointer into the input array.
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
lambda n:n[3:12]+`-sum(i*int(n[13-i])for i in range(2,11))%11`
```
[Try it online!](https://tio.run/##NY5BDoIwFETXeopuTFuFpP@3FUqCF0ESMIo2kQ9BXHj6CsbOZpJ5M8mMn/kxEIauPIdn21@uLaOCKl0A1ocmfb174feeZkEV6NTXshsm5pknNrV0vwlMAKTcATRhJbSSirssV1HIE/YLUEGeo7PZPwCDylnQCmLDWMTcoDaxgQ5BQXaME6WN1Q4W53Wx3YzT8oxRwssTTzpBMnwB "Python 2 – Try It Online")
Takes a string as input; and outputs a string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
ṫ4ṖµV€×JS%11;@
```
[Test suite!](https://tio.run/##y0rNyan8///hztUmD3dOO7Q17FHTmsPTvYJVDQ2tHYDC@0D8diAR@f9/tKW5hYGxiamxpSGQ1lEAcY0MDC0sjCxNzcFcQxMjA0tTQ2MDQ4isiamRkYWJkbEJRNbI0sjQwNDcDKIYYVQsAA "Jelly – Try It Online")
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṛḣ⁵µVD×JḊSN%11;ḊṚ
```
[Try it online!](https://tio.run/##y0rNyan8///hzlkPdyx@1Lj10NYwl8PTvR7u6Ar2UzU0tAYygHL///9XsjS3MDA2MTW2NATSSgA "Jelly – Try It Online") or [Test suite!](https://tio.run/##y0rNyan8///hzlkPdyx@1Lj10NYwl8PTvR7u6Ar2UzU0tAYygHJA@X2PmtYcbgcSkf//R1uaWxgYm5gaWxoCaR0FENfIwNDCwsjS1BzMNTQxMrA0NTQ2MITImpgaGVmYGBmbQGSNLI0MDQzNzSCKEUbFAgA "Jelly – Try It Online")
Takes input and outputs as a string.
[Answer]
# [ECMAScript 6](https://www.ecma-international.org/ecma-262/6.0/), ~~86~~ 67 bytes
```
a=>(c=a.substr(3,9))+([...c].map(v=>g+=--i*v,e=i=g=11)?(e-g%e)%e:0)
```
[Try it online!](https://tio.run/##bY5BDoIwEEX3noKNoVUonWmB1qR6EOOiYiUYBALI9dGFZdXZ/OTl5WVedrFTNTbDnHb9w61Ps1pzJpWxbPrcp3kkItGUHsmVMVbd2NsOZDHn@mjStDksiTONqQ0AvRCX1ntH9@7E6Vr13dS3jrV9TZ4k1qXi/jCmNMqyaAN8F7CRg1Ko89LbGwjYIJHrHASHv72BYFvmiEqikL7tQRFqo0bgUBb@kw2oUFvIXGj4rW97gOsX "JavaScript (Node.js) – Try It Online")
---
Thanks for [Arnauld's comment](https://codegolf.stackexchange.com/questions/153624/converting-isbn-13-to-isbn-10#comment375235_153645), switched from `reduce` to `map` and got rid of `return` keyword.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~72~~ 51 bytes
```
...(.*).
$1¶$1
r`.\G
$&$'
r`.\G
$*
1{11}
¶(1*)
$.1
```
[Try it online!](https://tio.run/##NYoxDsIwEAT7e4cBx8Xp9mxj3wvyiRRJQUFDEdEhvpUH5GOGWMo2u6PZ9fF@vpZ28ePcmNlzGJgc9s2B1pmnkdzV3c4ZCB/gS7RvHmEgx2jNSpUzSgepoFa1XA5CUrGMKOguZdWaNKbu1BSCcu9PiSlHw79/ "Retina 0.8.2 – Try It Online") Because I haven't learned Retina 1.0 yet. Explanation:
```
...(.*).
$1¶$1
```
Delete the unwanted characters and make a second copy of the appropriate digits.
```
r`.\G
$&$'
```
Suffix each digit in the second copy with its suffix. This effectively repeats each digit in the suffix by its position.
```
r`.\G
$*
```
Convert the digits in the second copy to unary thus adding them together.
```
1{11}
```
Reduce modulo 11. (There are only 9 digits in the first copy, so this can never affect it.)
```
¶(1*)
$.1
```
Convert the result back to decimal and remove the newline again.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~26~~ 24 bytes
```
∊⍕¨(⊢,11|⊢+.×⍳∘≢)3↓¯1↓⍎¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBI86uh71Tj20QuNR1yIdQ8MaIKWtd3j6o97NjzpmPOpcpGn8qG3yofWGQPJRb9@hFQrqluYWBjBgpM5FngFGBoYWFkaWpuZkGmBoYmRgaWpobGBIrgtMTI2MLEyMjE3IdYGRpZGhgaG5GbleMDA2MTW2NATS6gA)
Tacit prefix function. Takes input as string.
2 bytes saved thanks to @ngn.
### How?
```
∊⍕¨(⊢,11|⊢+.×⍳∘≢)3↓¯1↓⍎¨ ⍝ Main function.
⍎¨ ⍝ Execute each; turns the string into a vector of digits.
3↓¯1↓ ⍝ Drop (↓) the last (¯1) and the first 3 digits.
( ≢) ⍝ Tally; returns the number of digits in the vector.
⍳∘ ⍝ Then (∘) index (⍳) from 1
× ⍝ Multiply the resulting vector [1..9]
⊢+. ⍝ Dot product with sum with the original vector;
⍝ This will multiply both vectors, and sum the resulting vector.
11| ⍝ Mod 11
, ⍝ Concatenate
⊢ ⍝ With the original vector
⍕¨ ⍝ Format each; returns a vector of digits as strings.
∊ ⍝ Flatten to get rid of the spaces.
```
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~104~~ ~~102~~ 98 bytes
```
import StdEnv
$s#s=s%(3,11)
#i=sum[digitToInt d*p\\d<-s&p<-[10,9..]]+10
=s++[toChar(i/11*11-i+58)]
```
[Try it online!](https://tio.run/##VZFLU4MwFIXX8iuurTYgoCRAC05Z@ZjpjLs64wKyQKBtZkrCkODjz4upWLTZJN/NyTm5SbGvct7Xouz2FdQ54z2rG9EqWKvygb8ZF3IqE3lp@g7GljFliezqtGRbpp7Fiisor5osK5eunDVLN8WeE19fU2pjz0ikbadK3O3y1mQ3GF9h7DI7jCzar1XeKmMKm44XigkOCVxoVJVUUq9T48xMUbyIvOMgiDopGtFD1HJGEfFwFJE4XAyif/gnwgHx4hD7Hv4RjXjqFISERAHxg8HpiPMTJxIT7OHFfIgbMTpx8oPQj7GeB6cj6j4s44wahm7SnDyKFiYO402nnAlshQI0cdpKdnvNyIH3HSt2wOTtQbUxh50kEZ3SJ6wU3Ym2rQp1jqhOfWkF34JZfTS6VJWAqG0PSv0NyDrcDmUcWZBlYA6Z8OsES/f37WcwhBwqdd6AOf6QgI3Uyh8Z7b@KzT7fyt5dPfX3nzyvWaHh9Rs "Clean – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 83 bytes
```
i.drop(3).dropLast(1).let{it+(11-(it.mapIndexed{i,c->(10-i)*(c-'0')}.sum()%11))%11}
```
## Beautified
```
i.drop(3).dropLast(1).let {
it + (11 - (it.mapIndexed { i, c -> (10 - i) * (c - '0') }.sum() % 11)) % 11
}
```
## Test
```
data class Test(val input: String, val output: String)
fun f(i: String) =
i.drop(3).dropLast(1).let{it+(11-(it.mapIndexed{i,c->(10-i)*(c-'0')}.sum()%11))%11}
val tests = listOf(
Test("9780000000002", "0000000000"),
Test("9780201882957", "0201882957"),
Test("9781420951301", "1420951300"),
Test("9780452284234", "0452284236"),
Test("9781292101767", "1292101768"),
Test("9780345391803", "0345391802")
)
fun main(args: Array<String>) {
for (c in tests) {
val answer = f(c.input)
val good = answer == c.output
println("$good ${c.input} -> ${c.output} | $answer")
}
}
```
## TIO
[TryItOnline](https://tio.run/##dZLbaoQwEIbvfYpBtjRpVZKou7p0F3pZKPSifYHgYQl1o5jYA9ZntxpX24Kdi4R/8vPNMJPXUhdC9lbKNYek4ErBS6Y0euMFCFk1eg/Puhby5MCYKhv9K4ctK28k5EgsGThYvfDSuqyQj839yAccxV6R6VboW0Spi4T2zrx6kGn2kaWtcBL3iChxBb5BiXtNrnHnqeaM8BWleDy63hqr66EzBQcohNJPObLgEqZjO95FZA5mO2AvitjYWTEzQqOIxeHOmH/UmpkGjMQh9QkdzYv6hxyEjEUB8wNDntV2ncxiRgndbU0bi4rWyX4Q+jEdbkOeFbOxdVnGmQuJeH1Se7iva/55Ny3miKE1uLysASXDbqdpzukxxhFzqd6zephxjhLPfAD85/1UlunwOtsOkHjTn1hc1VBOFxLZG+PdtBdOB+7RqMnfwRdsJow9leisrv8G)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~69 68~~ 64 bytes
```
->n{v=n[3,9];c=11;v+"#{(c-v.chars.map{|i|i.to_i*c-=1}.sum)%11}"}
```
[Try it online!](https://tio.run/##TY/bboMwEETf8xWIqKIXsLxrE@xE9EeIVVHXafwQB4WLWgHfTh2ikO7L6IxGs5pL@/k7HfIpeXd9l7uCxVLtdA6w697Cdf@sk47oY3mpyams@sEOljTnD/uqkxxGUrenlyeAMRynYlVEMhMUKQiBMs2iOIj@kYpvAeBIZQqMwjWwEF0ClKeIgiPjc8OdNo8GlAgUss38YiHxaGA8ZRK8zg13wkitFDGlPvodsRmqtqmD0Dqv28Dfurfj3n2fb3TlQ2GVt8xPZXRjvrbeMp73zu/9Aw "Ruby – Try It Online")
[Answer]
# PHP, 64 bytes
Unfortunately, in PHP `(-$c)%11` is the same as `-($c%11)`; so I have to get the difference to at least the largest sum possible (55\*9 = 495 = 45\*11) instead of just using `-$c%11`.
```
for($f=11;--$f>1;print$d)$c+=$f*$d=$argn[13-$f];echo(495-$c)%11;
```
or
```
for($c=45*$f=11;--$f>1;print$d)$c-=$f*$d=$argn[13-$f];echo$c%11;
```
Run as pipe with `-nR` or [try them online](http://sandbox.onlinephpfunctions.com/code/9abfe74dde711b6a8f9eea6c49f2792ad60d2513).
[Answer]
# Java 10, 110 bytes
```
l->{var s=l+"";int c=0,i=3;for(;i<12;)c+=(13-i)*(s.charAt(i++)-48);return(l-(long)978e10)/10*10+(11-c%11)%11;}
```
Takes input and outputs as a `long` integer. Try it online [here](https://tio.run/##nZJBS8MwGIbP3a8IBSFZ7cyXdq6lVlBPgnrZUTzELm7RmI4kq4jst8@0aydeWyjpm4Sn7wfPO294/L76OGx3r0pWqFLcWvTIpUY/k0BqJ8wbrwS6X94@3dW6EcbvtEeBqvUaSfuqgeK/74QUk2A/CXqcddz5panlCn16KF46I/X6@QVxs7akA/1Ht5S/VKKDiq9/Gm6QLVUUhoWvhKqSnssyKd5qgwt5BawgVVRiSGJJptjOqg03Nw7LKCJxmpHCCLczGqu4K0ryRSaAkgugU6ARBoirMwDi32J/CAI/QLD8tk58zuqdm219Yac03vIV/ldu1g/vcXR42AMhUYhOmYZkDI5RyDKWzxc97pRH4SBlNJ9DQuGIO@WR7dI5Y1nKkrRvN@TLce1YzoDC4rIf9pSzce2SdJ7k4Ne@3ZBZOKhpZMOdGNw8GolaZqexOlrZb1uvYOed3/raSCW8Xkrotdtggq6Q18gfBO0tGtn20tE1ZLt/7Q@/).
Ungolfed version:
```
l -> { // lambda taking a long as argument
var s = l + ""; // convert the input to a String
int c = 0, // the check digit
i = 3; // variable for iterating over the digits
for(; i < 12 ;) // go from the first digit past 978 to the one before the check digit
c += (13 - i) * (s.charAt(i++) - 48); // calculate the check sum
return (l - (long) 978e10) // remove the leading 978
/10 *10 // remove the original check digit
+ (11 - c % 11) % 11; // add the new check digit
}
```
] |
[Question]
[
Given a 2D string as input, either as a string with newlines or a list of lines, output the coordinates `(x, y)` of all the hashes (`#`) in the list. The input will only contain hashes and spaces. (and newlines, if you choose to take input as a 2D string)
If there are no hashes, you can output anything.
Output should be unambiguous as to which numbers are paired with which.
Example:
```
##
```
Should output:
```
(0,0), (1,0)
```
That assumes 0-based indexing, starting from the top left. You may start from any corner, use 0 or 1-based indexing, and/or output `y` first. (e.g. in the form `y,x`).
More test cases (again, all using 0-based top-left `(x, y)` indexing):
```
#
#####
#
(4, 0), (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (0, 2)
# ###
### #
(0, 0), (2, 0), (3, 0), (4, 0), (0, 1), (1, 1), (2, 1), (4, 1)
```
Note that these test cases all list by rows, not by following the path.
You may assume the hashes will form a continuous trail, i.e. `# #` will never be the input. (probably won't matter, but in case somebody wants to regex this)
You also can output the coordinates in any order you want, i.e. vertical columns, horizontal rows, or just an unsorted list.
[Answer]
# [Slip](https://github.com/Sp3000/Slip), 2 + 1 = 3 bytes
+1 byte for the `p` flag. Code:
```
`#
```
Explanation:
The `p`-flag returns the position of each occurence of the following:
```
`# // The character '#'
```
[Try it here!](https://slip-online.herokuapp.com/?code=%60%23&input=%23%20%23%23%23%0A%23%23%23%20%23&config=p)
[Answer]
## [Grime](https://github.com/iatorm/grime), 5 bytes
```
pa`\#
```
[Try it online!](https://tio.run/nexus/grime#@1@QmBCj/P@/srICl4KyMgA "Grime – TIO Nexus")
The output format is a bit funky, but OP has stated that it's valid.
## Explanation
Grime is my 2D pattern matching language.
The part after ``` is the *pattern*, in this case a 1×1 square containing a `#`-character.
Grime will search the input grid for a match, and prints the first one it finds by default.
The part before ``` contains options, in this case signifying that all matches (`a`) should be printed, along with their positions and sizes (`p`).
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~7 6~~ 5 bytes
This is using 1-based indexing with `(1,1)` in the top left corner.
```
oo&fh
```
Explanation:
```
o % convert char to double
o % remainder mod 2 ('#' == 35, ' '==32) makes spaces falsy
&f % apply `find` with 2d-output
h % concatenate outputs to display x- and y-coordinates side by side
```
Thanks @DJMcMayhem and @LuisMendo for each -1 byte!
[Try it online!](https://tio.run/nexus/matl#@5@fr5aW8f9/tLoCECirW6srgwCIBgmoxwIA "MATL – TIO Nexus")
[Answer]
# [Python](https://docs.python.org/3/), 67 bytes
This is actually just a golf of my [Stack Overflow answer](https://stackoverflow.com/a/41430965/7089349) on a similar topic.
```
lambda a,e=enumerate:[[(i,j)for j,B in e(A)if'!'<B]for i,A in e(a)]
```
[**Try it online!**](https://tio.run/nexus/python3#JczBCsIwEATQu18xpofuQr5A7KH9jZDDihvY0sYSUn8/Rp3LwBuYljBhk/3xFIjXSfO5a5GqtxDI/MrpVbD6BZahNLOl8Trel/hl8/OfhWOT/qNv2cjycVZivhzFcqXUV27BARichxt6ft3BxQ8)
The loops through the 2D list, recording the hash characters, and returns the result. We save a byte by using `char > '!'` rather than `char == '#'`, because the input will only consist of hashes and spaces, and so hashes (`0x23`) will be the only characters larger than exclamation marks (`0x21`).
[Answer]
## JavaScript (ES6), ~~70~~ 67 bytes
```
s=>s.replace(/./g,(c,i)=>c>' '?[i%l,i/-l|0]+' ':'',l=~s.indexOf`
`)
```
Outputs a newline-and-space-separated list of coordinates, e.g.
```
4,0
0,1 1,1 2,1 3,1 4,1
0,2
```
You can get much shorter with a weird output format:
```
s=>s.replace(/#/g,(c,i)=>[i%l,i/-l|0]+c,l=~s.indexOf`
`)
```
This outputs
```
4,0#
0,1#1,1#2,1#3,1#4,1#
0,2#
```
for the second test case. It's still clear which numbers are paired with which...
[Answer]
## [J](http://jsoftware.com/), 12 bytes
```
$#:'#'I.@:=,
```
[Try it online!](https://tio.run/nexus/j#@5@mYGuloKJspa6s7qnnYGWr878EJGKsYKKgoqCurKwARApApKCszpWanJGvoO6ZV1BaAuWUQMX8S0sQgmkKJf8B "J – TIO Nexus")
## Explanation
```
$#:'#'I.@:=, Input is y.
, Flatten y
'#' = and form bit vector of equality with #.
I.@: Compute positions of 1s
#: and convert each to base
$ shape of y.
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM) 16.0, 5 chars = 9 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) or 6 chars = 8 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Gives list of (y,x) pairs from top left.
```
⍸⎕='#'
```
`⍸` where
`⎕` input
`=` equals
`'#'` this character\*
\* It is possible to save a character at the cost of one byte by replacing `'#'` with `⍕#` (format the root namespace)
[TryAPL online!](http://tryapl.org/?a=i%u2190%7B%28%2C%u2375%29/%2C%u2373%u2374%u2375%7D%20%u22C4%20%u22A2%u2206%u21903%205%u2374%27%20%20%20%20%23%23%23%23%23%23%23%27%20%u22C4%20i%20%u2206%3D%27%23%27%20%u22C4%20%u22A2%u2206%u21902%205%u2374%27%23%20%23%23%23%23%23%27%20%u22C4%20i%20%u2206%3D%27%23%27&run) Note that `⍸` has been emulated with `i` because TryAPL runs version 14.0.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
n⁶T€,€"J
```
[Try it online!](https://tio.run/nexus/jelly#@5/3qHFbyKOmNTpArOT1////aCUFIFBW0lFSBgEQDRJQigUA "Jelly – TIO Nexus")
Given a 2D array of characters (= a list of strings):
```
Implicit input (example):
[[' ', ' ', ' ', ' ', '#']
,['#', '#', '#', '#', '#']
,['#', ' ', ' ', ' ', ' ']]
n⁶ Not-equal to space (⁶).
[[0, 0, 0, 0, 1]
,[1, 1, 1, 1, 1]
,[1, 0, 0, 0, 0]]
T€ Indices of 1s in each row
[[5], [1,2,3,4,5], [1]]
,€"J Pair each, vectorizing, with y-indices
[[[5,1]], [[1,2],[2,2],[3,2],[4,2],[5,2]], [[1,3]]]
```
[Answer]
## JavaScript (Firefox 30-57), 61 bytes
```
s=>[for(c of(x=0,y=1,s))if(c<' '?(y++,x=0):(x++,c>' '))[y,x]]
```
Returns 1-based coordinates. Easily switchable between `[y, x]` and `[x, y]` ordering. Ungolfed:
```
function coords(s) {
var x = 0;
var y = 1;
for (Var c of s) {
if (c == "\n") {
y++;
x=0;
} else {
x++;
}
if (c == "#") {
console.log(y, x);
}
}
}
```
[Answer]
# Vim, 37 bytes
```
:%s/#/\=line('.').','.col('.').' '/g<cr>
```
Since V is mostly backwards compatible, you can [Try it online!](https://tio.run/nexus/v#@2@lWqyvrB9jm5OZl6qhrqeuqaeuo66XnJ8D5Sio66dz/f@vrKCsrMwFxArKAA)
A straightforward regex solution, where it replaces each '#' with the location it was found in (one-based indexing). I was a little bit worried while writing this that the location would change after substituting the first one on a line, but that doesn't seem to be an issue. TBH I'm pleasantly shocked by how simple this solution ended up being.
Unfortunately, vimscript is very verbose, so most of the bytes come from separating the results so that is still legible. Otherwise, we could do
```
:%s/#/\=line('.').col('.')/g
```
But this creates output that's pretty hard to interpret. Additionally, it will only work it the grid is always 9x9 or smaller.
This is a really fun solution because it shows each pair of coordinates *at the location* of the hash it represents. For example, the input
```
# ###
### #
```
outputs
```
1,1 1,3 1,4 1,5
2,1 2,2 2,3 2,5
```
Of course, if we were using V, we could remove the trailing newline, and compress the regex. Then it could simply be
```
Í#/½line('.').','.col('.').' '/g
```
(32 bytes)
But since this is the exact same approach and still painfully verbose, it doesn't seem worth it to use a golfing language.
[Answer]
## Haskell, 53 bytes
```
concat.zipWith(\y l->[(x,y)|(x,'#')<-zip[0..]l])[0..]
```
Input is taken as a list of strings. The output is a list of `(x,y)` pairs (0 indexed), e.g.
```
*Main> concat.zipWith(\y l->[(x,y)|(x,'#')<-zip[0..]l])[0..] $ ["# ###","### #"]
[(0,0),(2,0),(3,0),(4,0),(0,1),(1,1),(2,1),(4,1)]
```
[Answer]
## Lua, 141 bytes
```
w=io.read()x=w:sub(1,w:find("\n")-1):len()_,c=w:gsub("\n","")for i=0,x do for j=0,c+1 do if w:sub(c*x+i,c*x+i)=="#"then print(i,j)end end end
```
It's 2:30 AM, I'm in bed, on my phone. Why am I doing this?
[Answer]
## Mathematica, 12 bytes
```
Position@"#"
```
Operator form of [`Position`](http://reference.wolfram.com/language/ref/Position.html). Assumes a 2D array of characters. 1-indexed starting at the top left entry. Outputs a list of coordinates in the form `{row,column}`.
[Answer]
# PHP, 69 bytes
```
for(;$a=$argv[++$i];)for($j=0;""<$c=$a[$j++];)echo$c>" "?"$j $i,":"";
```
Uses 1-based indexing starting from the top left.
Use like:
```
php -r 'for(;$a=$argv[++$i];)for($j=0;""<$c=$a[$j++];)if($c>" ")echo"$j $i,";' ' #' '#####' '# '
```
Will output:
```
5 1,1 2,2 2,3 2,4 2,5 2,1 3,
```
[Answer]
# C, 113 bytes
```
i,j,k,l;f(char**p){i=strlen(*p);l=strlen(p);for(j=0;j<l;j++)for(k=0;k<i;k++)if(p[j][k]==35)printf("%d,%d ",k,j);}
```
Outputs from test cases:
```
0,0 2,0 3,0 4,0 0,1 1,1 2,1 4,1
4,0 0,1 1,1 2,1 3,1 4,1 0,2
```
[Try it online!](https://tio.run/nexus/c-gcc#NY07DoMwEET7nALZQvKCi0CUavFJEAUKseJPwDKkQpydrEPYat7OSG830konPWrxePWxKAKsRs1L9M9REKA/gbKeorDqirbxaMsSEjti1xh0xEaL0NqudZ1StzuEaMZFC5YPMh8yRhoLuO3v3owC1p8uVG2n1gvjGeecSQqcItvwaOujzejO9j9LL5qRsAIMn2UWjEHCOim@ "C (gcc) – TIO Nexus")
[Answer]
## RBX.Lua, 131 bytes
Has to assume input is valid (Z is the flat axis, whitespaces are `White` tiles, hashes can be any other color, top-left part is located at `0, 0, 0`) and all parts are part of the same model `M`, and the model is otherwise empty.
```
for k,v in pairs(workspace.M:GetChildren())do if v.BrickColor~=BrickColor.new("White")then print(v.Position.X,-v.Position.Y)end end
```
Sample input/output:
[](https://i.stack.imgur.com/l5Yih.png)
[Answer]
# [Perl 6](http://perl6.org/), 25 bytes (22 characters)
```
{^∞ZX@_».indices("#")}
```
Takes input as a list of lines.
Outputs one list per line, each containing (y, x) tuples for the coordinates.
[Try it online!](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS1Ow/V8d96hjXlSEQ/yh3XqZeSmZyanFGkrKSpq1/4sTKxXSFFTiFdLyixRUbNMy8zKLM/SSM/JzC/SKC3IySzSUYvJi8pQ0gaZBZbmUlbm4FIBAGcgCAi4gl0tZAcxSBtL/AQ "Perl 6 – TIO Nexus")
### How it works
```
{ } # A lambda.
{ @_» } # For each input line:
.indices("#") # get x-coordinates. (4) (0 1 2 3 4) (0)
^∞ # Range from 0 to Inf. 0 1 2 ...
Z # Zip with: (0 (4)) (1 (0 1 2 3 4)) (2 (0))
X # Cartesian product. ((0 4)) ((1 0) (1 1) (1 2) (1 3) (1 4)) ((2 0))
```
[Answer]
# Groovy, ~~80~~ 68 bytes
```
{y=0;it.each{it.eachWithIndex{x,i->print(x=='#'?"($i,$y)":"")};y++}}
```
Example input:
```
[# #,# #,#####]
```
Example Output:
```
(0,0)(4,0)(0,1)(4,1)(0,2)(1,2)(2,2)(3,2)(4,2)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 24 + 1 = 25 bytes
+1 byte for `-n` flag. Coordinates are 1-based, one number per line.
```
gsub(/#/){p$`.size+1,$.}
```
[Try it online!](https://tio.run/##KypNqvz/P724NElDX1lfs7pAJUGvOLMqVdtQR0Wv9v9/ZQVlZWUuIFZQ/pdfUJKZn1f8XzcPAA "Ruby – Try It Online")
[Answer]
# C, 80 bytes
```
x,y;f(char*s){for(x=y=0;*s;printf(*s-35?"":"%d,%d ",x,y),*s++==10?++y,x=0:++x);}
```
Requires input as newline-delimited char array, prints output to screen.
Ungolfed & usage:
```
x,y;
f(char*s){
for(
x = y = 0; //init coordinates
*s; //iterate until end
printf(*s-35 ? "" : "%d,%d ", x, y), //print coordinates or empty string
*s++==10 ? ++y, x=0 : ++x //advance to the right or the next line
);
}
main(){
f(" #\n#####\n# ");
puts("");
f("# ###\n### #");
}
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 2 bytes
```
⍸<
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HvDpv/aY/aJjzq7XvU1XxovfGjtomP@qYGBzkDyRAPz@D/QNo5Uj0lLa9YnSsls7hAIU0BKATUYqhg9Kh3i7oymrCxgilIWAEIlCEAxERTZARRpAxVoqCsDgA "APL (Dyalog Extended) – Try It Online")
I win. (Though it's technically tie because we don't count flags in bytes anymore...)
Basically works like [the existing APL answer](https://codegolf.stackexchange.com/a/105664/78410), but it doesn't test for equality with `'#'`; it tests if each char is non-blank.
] |
[Question]
[
*easy mode of [my previous challenge](https://codegolf.stackexchange.com/q/251270/78410)*
A perfect number is a positive integer whose sum of divisors (except itself) is equal to itself. E.g. 6 (1 + 2 + 3 = 6) and 28 (1 + 2 + 4 + 7 + 14 = 28) are perfect.
A **sublime number** (OEIS [A081357](http://oeis.org/A081357)) is a positive integer whose count and sum of divisors (including itself) are both perfect. E.g. 12 is a sublime number because:
* the divisors of 12 are 1, 2, 3, 4, 6, 12
* the count of divisors is 6 (perfect)
* the sum of divisors is 28 (perfect)
The next smallest known sublime number is
```
6086555670238378989670371734243169622657830773351885970528324860512791691264
```
which is a product of a power of 2 and six Mersenne primes
$$
2^{126}(2^3-1)(2^5-1)(2^7-1)(2^{19}-1)(2^{31}-1)(2^{61}-1)
$$
These two numbers are the only known sublime numbers as of 2022. The necessary and sufficient conditions for even sublime numbers have been found [in this paper (pdf)](https://web.archive.org/web/20200714113410/http://mathematicstoday.org/archives/V32_2016_5.pdf), but it remains unknown whether odd sublime numbers exist.
It is known that there are no other *even* sublime numbers before the number, but it is not known whether there are any *odd* ones.
## Task
Output the second even sublime number shown above. It is OK to only theoretically output this number in the following ways:
* the program outputs the correct number with probability 1 in finite time
* the program outputs the correct number given enough time and unlimited memory
* the program would output the correct number if the native number type had infinite precision
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 45 bytes
```
print(vecprod([4^i-2^i|i<-[3,5,7,19,31,61]]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN3ULijLzSjTKUpMLivJTNKJN4jJ1jeIyazJtdKONdUx1zHUMLXWMDXXMDGNjNTUhmqB6YWYAAA)
The number is \$\prod\_{i\in\{3,5,7,19,31,61\}}(4^i-2^i)\$. In fact, \$126=3+5+7+19+31+61\$.
Another interesting fact is that \$2^{126}\$ is just the sum of divisors of \$\prod\_{i\in\{3,5,7,19,31,61\}}(2^i-1)\$. This might be useful for some golfing language if there is a built-in for divisor sum.
[Answer]
# [Python 2](https://docs.python.org/2/), 37 bytes
```
print~-2**31*~-2**61*14448825433<<126
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM6@kTtdIS8vYUAtMmxlqGZqYmFhYGJmaGBvb2Bgamf3/DwA "Python 2 – Try It Online")
Writes out \$2^{31}-1\$, \$2^{61}-1\$, and the bit-shift \$2^{126}\$, and hardcodes the remaining product.
[Answer]
# [R](https://www.r-project.org/), ~~33~~ 32 bytes
*Edit -1 byte thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor).*
```
prod(8^42,2^c(3,5,7,19,31,61)-1)
```
[Try it online!](https://tio.run/##bY07DsMgEER7nwKJwiAtBdj5kMRdzoGECJFXclgEvj9BbpNimtG8eaVR3pFSFTVgjmmx1sqWC73E1c0GjAtighNcQFuYNJy1VFo2zjKVndGb@S3m1W89Y2U@d9KH9Tbg8sPdj9fZoTIOJeMfTHE4OnyoPx7AbmL8SX2IYaztCw "R – Try It Online")
Spells out the product.
[@alephalpha's approach](https://codegolf.stackexchange.com/a/251355/55372) lead to +1 byte for me, but [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) found a 32-byte version (see the footer of the TIO link above).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•w4н•foD<*P
```
-2 bytes thanks to *@alephalpha*.
[Try it online.](https://tio.run/##Dcq9DcIwEEDhVayUyEj2ne/HUsoMwAA0Jg4iBRjFBS2zZA92YAYWMa7eV7xS02VdGjtlImJxgIqiUWM3ihcMENBzZAAmUXQiiORVKYojUISg7MiDxH554GDNcEtbPs4lL9maVM1c7s@0rbU8hnP7vfdX@H56rmUaD6dm2x8)
**Explanation:**
```
•w4н• # Push compressed integer 3772545
f # Get its prime factors: [3,5,7,19,31,61]
o # Get 2 to the power for each of these integers
D # Duplicate the list
< # Decrease each by 1 in the copy
* # Multiply the values at the same positions in the two lists
P # Get the product of this list
# (after which the result is output implicitly)
```
[See this 05AB1E tips of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•w4н•` is `3772545`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~20~~ ~~19~~ ~~16~~ 15 bytes
```
*FsmtB^2dPC"9
```
[Try it online!](https://tio.run/##K6gsyfj/X8utOLfEKc4oJcBZyfLQhEON//8DAA "Pyth – Try It Online")
```
*FsmtB^2dPC"9
C"9 # compressed 3772545
P # prime factors (3, 5, 7, 19, 31, 61)
mtB^2d # map d: [2**d, 2**d - 1]
s # flatten
*F # reduce on multiplication
```
-3 bytes thanks to @CursorCoercer
-1 byte thanks to @isaacg
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~14~~ ~~13~~ 11 bytes
```
»;⟑L»ǐE:‹*Π
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCuzvin5FMwrvHkEU64oC5Ks6gIiwiIiwiIl0=)
-1 byte thanks to alephalpha and -2 bytes thanks to Mukundan314.
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 bytes
```
“¤¦¬Œþ=‘2*’æ«21P
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//4oCcwqTCpsKsxZLDvj3igJgyKuKAmcOmwqsyMVD//w "Jelly – Try It Online")
-1 byte thanks to xnor.
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, ~~40~~ 38 bytes
```
4 2 [ "=">array n^v ] bi@ v- Π .
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQWFSUWFmskJ1alJeao5CbWJKhV5qXmZyfkgrhlKWCVBcrFBSllpRUFhRl5pUoWP83UTBSiFZQYmZlF5a3VbIDG6KQF1emEKuQlOmgUKarcG6Bgt7//wA "Factor – Try It Online")
-2 bytes from porting @alephalpha's [PARI/GP answer](https://codegolf.stackexchange.com/a/251355/97916).
Note `"="` is a literal string that is equivalent to `{ 3 5 7 19 31 61 }`. You can only see the `=` since the rest are non-printable, but you can see the non-printable characters on TIO. This needs to be converted to an array because `n^v` is buggy otherwise. Still 4 bytes shorter than the sequence literal.
* `4 2 [ ... ] bi@` Apply `[ ... ]` to both 4 and 2.
* `{ 3 5 7 19 31 61 } n^v` Input raised to 3, input raised to 5, etc.
* `v-` Subtract two vectors.
* `Π` Take the product.
* `.` Print the result to stdout.
[Answer]
# Bash, 47 Bytes
```
echo "14448825433*(2^31-1)*(2^61-1)*(2^126)"|bc
```
[Try it online!](https://tio.run/##S0oszvj/PzU5I19BydDExMTCwsjUxNhYS8MozthQ11ATxDCDMQyNzDSVapKS//8HAA "Bash – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes
```
8^42##&@@(2^{3,5,7,19,31,61}-1)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yLOxEhZWc3BQcMortpYx1THXMfQUsfYUMfMsFbXUFPtf0BRZl5JdFp0bOx/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 51 bytes
*Thanks JoKing and Steffan for helping me golf some bytes*
```
?-X is(2^61-1)*14448825433*(2^31-1)*2^126,write(X).
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/3143QiGzWMMozsxQ11BTy9DExMTCwsjUxNhYCyhoDBY0ijM0MtMpL8osSdWI0NT7/x8A "Prolog (SWI) – Try It Online")
My very first Prolog answer :D, probably can be golfed a lot though.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
IΠEX²⁻E357COm℅ι⁴⁸×ι⊖ι
```
[Try it online!](https://tio.run/##HYm7CsMwDAB/xWRSwFmalhY6pmuIh/6AsAUV@BFkJ/l8tekNN9z5D4ovGFWdcG4wYW3gpITNN5hxBVcOErhYM3Pe6j914@0@LamzZpHAGSNw31tzfZx@c6IKbM2LvFCi3Cic/8dTVYc9fgE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
357COm Literal string `357COm`
E Map over characters
ι Current character
℅ ASCII code
⁻ Vectorised subtract
⁴⁸ Literal integer `48`
X Vectorised exponentiate with base
² Literal integer `2`
E Map over powers of `2`
ι Current power of `2`
⊖ Decremented
× Multiplied by
ι Current power of `2`
Π Take the product
I Cast to string
Implicitly print
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 15 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
357HT╟)]ó_(m*ε*
```
[Try it online.](https://tio.run/##y00syUjPz0n7/9/Y1Nwj5NHU@ZqxhzfHa@Rqnduq9f8/AA)
**Explanation:**
```
3 # Push 3
5 # Push 5
7 # Push 7
H # Push 19
T # Push 31
╟ # Push 60
) # Increase the 60 by 1
] # Wrap the stack into a list: [3,5,7,19,31,61]
ó # Calculate 2 to the power each of these integers
_ # Duplicate the list
( # Decrease each by 1
m* # Multiply the values at the same positions in the lists together
ε* # Product: reduce by multiplication
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~21~~ ~~19~~ ~~18~~ 14 bytes
```
3772545YfWtqhp
```
[Try it online!](https://tio.run/##y00syfn/39jc3MjUxDQyLbykMKPg/38A "MATL – Try It Online")
```
3772545YfWtqhp
3772545Yf # Prime factorize 3772545 (3, 5, 7, 19, 31, 61)
W # 2 ** elements
t # duplicate list
q # decrement elements in copy by 1
h # concatenate lists
p # product
```
-2 bytes thanks to @Luis Mendo
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~16 15~~ 12.5 bytes
```
`*.`D62*;^2$-$~ a8532dc3
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWOxK09BJczIy0rOOMVHRV6hQSLUyNjVKSjSHSUFUw1QA)
*-2.5 bytes thanks to Dominic van Essen*
Nibbles has no prime-related built-ins, so I had to resort to good old base conversion.
```
`*.`D62*;^2$-$~ a8532dc3
`* Product
. for each n in
`D62 convert from base 62
a8532dc3 2824023491
* multiply
^2 2 to the power of
$ n
; $ with itself
- ~ minus 1
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 33 bytes
```
{Jfc~]++==}s1r1f{fcsa%1!j++%1!&&}
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/2istuS5WW9vWtrbYsMgwrTotuThR1VAxS1sbSKqp1f7/DwA "Burlesque – Try It Online")
Given infinite time, should find sublime numbers
```
{ # IsPerfect function
J # Duplicate
fc # Factors
~] # Without self
++ # Sum
== # Equals self
}s1 # Store as "1"
r1 # Range 1..inf
f{ # Filter
fc # Factors
sa # Non-destructive Length
%1! # IsPerfect
j++ # Sum of factors
%1! # IsPerfect
&& # And
}
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~16~~ 13 bytes
```
₆¨*≬K₍L∑¨=∆Kc
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigobCqCriiaxL4oKNTOKIkcKoPeKIhktjIiwiIiwiIl0=)
half-Legitimate calculation ~~is~~ was shorter than hard coding lol. Given enough time and memory, this would eventually output the right number.
## Explained
```
₆¨*≬K₍L∑¨=∆Kc
₆¨*≬ c # From all multiples of 64 (which contains the target number), get the first where:
K₍L∑ # The list [len(factors), sum(factors)]
¨=∆K # Is invariant under sum of proper divisors
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁹Æs;ÆdÆṣƑƲ1#
```
A full program that will (eventually!) print the result.
[Don't Try it online!](https://tio.run/##AR4A4f9qZWxsef//4oG5w4ZzO8OGZMOG4bmjxpHGsjEj//8 "Jelly – Try It Online")
The `⁹` starts the search at 256, if one replaces it with `1` it'll find `12` - try that **[here](https://tio.run/##y0rNyan8/9/wcFux9eG2lMNtD3cuPjbx2CZD5f//AQ "Jelly – Try It Online")**.
---
Faster in 13:
```
“;Y,’Æf2*×’$P
```
Try it [here](https://tio.run/##y0rNyan8//9RwxzrSJ1HDTMPt6UZaR2eDmSpBPz/DwA "Jelly – Try It Online").
[Answer]
# Python, ~~49 46~~ 45 bytes
Did some google calculation.
```
print(2**126*14448825433*(2**31-1)*(2**61-1))
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 17 \log\_{256}(96) \approx \$ 13.99 bytes
```
3772545AF2@D1-z*P
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhYbjc3NjUxNTB3djBxcDHWrtAIg4lBpmDIA)
Port of [Kevin Cruijssen's 05AB1E answer](https://codegolf.stackexchange.com/a/251370/114446).
```
3772545AF2@D1-z*P
3772545 # Push 3772545 (there's no integer compression in Thunno)
AF # Prime factors of that ([3, 5, 7, 19, 31, 61])
2@ # 2 ** each one ([8, 32, 128, 524288, 2147483648, 2305843009213693952])
D1- # Duplicate and subtract one ([7, 31, 127, 524287, 2147483647, 2305843009213693951])
z* # Multiply ([56, 992, 16256, 274877382656, 4611686016279904256, 5316911983139663489309385231907684352])
P # Product of the list (6086555670238378989670371734243169622657830773351885970528324860512791691264)
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), ~~22~~ ~~17~~ 16 bytes
```
3772545ǰϼ2⇹^Đ⁻*Π
```
[Try it online!](https://tio.run/##AR8A4P9weXT//zM3NzI1NDXHsM@8MuKHuV7EkOKBuyrOoP// "Pyt – Try It Online")
```
3772545 push 3, 7, 7, 2, 5, 4, 5
ǰ ǰoin elements on stack with no delimiter
ϼ get unique ϼrime factors (casts to integer)
2⇹^ raise 2 to each power
Đ⁻ Đuplicate; decrement
* element-wise multiplication
Π product of list; implicit print
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 30 bytes
My first Jelly answer! Hope I'll get better in the future.
```
2*’
[3,5,7,19,31,61]ç
¢×/æ«126
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FjdVjbQeNczkijbWMdUx1zG01DE21DEzjD28nOvQosPT9Q8vO7Ta0MhsSXFScjFUy6LoWCgLAA)
[Answer]
# [J](https://www.jsoftware.com), 23 bytes
```
echo*/(,<:)2^q:3772545x
```
Same solution as most answers.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8GCpaUlaboW21OTM_K19DV0bKw0jeIKrYzNzY1MTUwrILJQRTDFAA)
```
echo*/(,<:)2^q:3772545x
3772545x NB. extended precision literal
q: NB. prime factors
2^ NB. raise 2 to each factor
(,<:) NB. monadic hook
<: NB. decrement
, NB. concat with hook input
*/ NB. product reduce
echo NB. print
```
] |
[Question]
[
You are trapped in this 5x5 labyrinth - each room is labelled from 1 to 25 and the exit is in room 1.
[](https://i.stack.imgur.com/3pa3s.png)
You are given as input the room you are currently in. Your task is to output the shortest sequence of moves (north, east, south, west) needed to reach room 1.
Moves can be output in any format you wish (list, string, array...) as long as you use the characters `n,w,e,s`.
**Here are all the test cases:**
```
1 => empty string/list
2 => w
3 => ww
4 => swwnw
5 => wswwnw
6 => seenwnw
7 => nw
8 => wnw
9 => wwnw
10 => swwnwnw
11 => eenwnw
12 => enwnw
13 => nwnw
14 => wnwnw
15 => wwnwnw
16 => enenwnw
17 => nenwnw
18 => wnenwnw
19 => nwnwnw
20 => wnwnwnw
21 => nenenwnw
22 => enwnenwnw
23 => nwnenwnw
24 => wnwnenwnw
25 => nwnwnwnw
```
Shortest answer in bytes wins!
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
def f(n):d=0x1211252b5375>>2*n-4&3;print"nwes"[d];f(n+d*3+d%2-5)
```
[Try it online!](https://tio.run/##JcvRCoIwFIDha/cUQyicJrSzVqDkXa/QTXRhbSshzuS4SJ9@mV3@8P39FJ4eIUZjHXcZisoct6MEKUHDTauDbhrIsdytVd1ThyHFjx3Si7nWsy5MrgqzglKL6Dxx5B1yavFhM7mBvahYskwsCTTN8S@Ov1ewxI532wd@bl9veyLytJB2GOIX "Python 2 – Try It Online")
A function that prints one direction per line, terminating with error.
The constant `0x1211252b5375` encodes in base 4 the direction `d` we travel from each room number as a number 0 through 3. The extraction digit `>>2*n-4&3` is also designed to give a negative shift error when `n=1`, terminating the code. We update the room number `n` via an offset that's computed from the direction `d` as `d*3+d%2-5`, which maps:
```
d d*3+d%2-5
0 -> -5
1 -> -1
2 -> 1
3 -> 5
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~95~~ 93 bytes
```
f=lambda n:n>1and Q[n]+f(n+[-5,5,1,-1]['nsew'.find(Q[n])])or''
Q=' wwswsnwwseenwwenwnwnenwn'
```
[Try it online!](https://tio.run/##FcpBCsMgEIXhdXOK2Y0SUzCQLgLJHbKWLCxqO9COQQPS01vD4/9W7/id78hjrWH52O/TWeCZV23ZwWZ474Pg3gyTmpRWg94NcvYF74HYiesgdxkTYrctCFBKLpmb3jdbbZdYQ0xAQAzJ8ssLrcaHnLvbkYhPIAVBkKx/ "Python 2 – Try It Online")
Could shave off ~~3~~ 2 bytes if 0-indexed room labeling is allowed.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~30~~ 29 bytes
*-1 byte thanks to a miraculous coincidence with prime numbers*
```
[Ð#•θzƶ‰`Ó•4вsè<DˆØ·5-+}'‹™¯è
```
[Try it online!](https://tio.run/##AU4Asf9vc2FiaWX/MjVFTj8iIC0@ICI/Tv9bw5Aj4oCizrh6xrbigLBgw5PigKI00LJzw6g8RMuGw5jCtzUtK30n4oC54oSiwq/DqP8swrQpXP8 "05AB1E – Try It Online")
```
[ } # infinite loop:
Ð # triplicate the room number (initially, the input)
# # break if room number == 1
•θzƶ‰`Ó•4в # compressed list 202232302231102210202010
sè # use the room number to index into that list
< # decrement
Dˆ # add a copy to the global array
Ø # nth prime (-1 => 0, 0 => 2, 1 => 3, 2 => 5)
· # double
5- # subtract 5
+ # add that to the room number
'‹™ # dictionary string "western"
¯ # push the global array
è # index (wraps around, so -1 => n, 0 => w, 1 => e, 2 => s)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~72~~ 62 bytes
```
f=->n{n<2?'':' en sw'[x=4*18139004[n]+6*4267088[n]-5]+f[n+x]}
```
[Try it online!](https://tio.run/##DcdBDsIgEADAr@xtLQgBpJUaqw/Z7EETuUkaa@Oatm9H5zav@f6tNQ/mUpZyDlfEE8KjAEwfJBmi8skfeuciFdadiqE7upT@MS3rTEULb3XnrQ1tY5@3cVllhXF@T0CyzyTMCsEAbvUH "Ruby – Try It Online")
### How?
The trick here is to use 2 constants to build the next step for each cell, then recursively solve the problem.
The 2 constants 18139004 and 4267088 are binary strings giving the direction of the next move, by extracting a single bit from both for each cell, we can get:
```
"n" = 4*0+6*0-5 = -5
"w" = 4*1+6*0-5 = -1
"e" = 4*0+6*1-5 = +1
"s" = 4*1+6*1-5 = +5
```
Easier than shifting around and masking a single big binary number IMHO.
When we get the direction, we extract the corresponding letter from the string " en sw":
```
1 5
| |
" en sw"
| |
-5 -1
```
And proceed recursively on the cell [n+x]
[Answer]
# JavaScript (ES7), ~~62~~ 58 bytes
Port of [xnor's answer](https://codegolf.stackexchange.com/a/192952/58563).
```
f=n=>--n?"nwes"[d=79459389361621/4**n&3]+f(n+d*3+d%2-4):''
```
[Try it online!](https://tio.run/##DYxRC4IwFEbf@xUXobZ5meGmltrqR/QYPQynUcidqNRD9NvXHj44HA7fy77t0s3PaZXkXR/CYMicpaRLQp9@SW7OHOqirPWx1lVeqXxfpCnt9B0HTuhSjW6rZCEaxsLgZ05gIG@B4GRAlREQBXw3AJ2nxY99NvoHjxUCYyKbrLuudl65EtEk0MQhxGch2s0v/AE "JavaScript (Node.js) – Try It Online")
[Answer]
# Perl 5 (`-n`), 94 bytes
-5 bytes thanks to Grimy
```
@A=map/./g,__wwswsnwwseenwwenwnwnenwn;%H=(n,-5,s=>5,e,1,w,-1);$_+=$H{$,=$A[$_]},say$,until$_<2
```
[TIO](https://tio.run/##FcRBCsIwEEDRy4ygOGlNIKs60u668QQioYsghToNnUoo4tUdI5//Ulwmr9p29BxSXdUPDCFnycLFGIvl0t9m19Oe0XgUuniMaDGjsYcGwpGgfwMSdDcI9w/KsAG@eB0nCGen6tx3Tus4s6hhNVdfnewP)
[Answer]
# [Perl 5](https://www.perl.org/), 79 bytes
```
say$,while$_+={n,-5,s=>5,e,1,w,-1}->{$,=substr _wwwswsnwwseenwwenwnwnenwn,$_,1}
```
[Try it online!](https://tio.run/##FcRBCoMwEEbhq7jIzn9KE8gy3sAzhBYGKkgUJzKU4NWdpjzet/OxRjN5fR30s6zs8phaAUVImiIYHgryF03NIcn5lnoMWVVFpXSZu/3eX7gMf5mFcG97XbYiRsVojo@n/wE "Perl 5 – Try It Online")
[Answer]
# JavaScript, ~~80~~ ~~73~~ 71 bytes
Adapted from [Chas' Python solution](https://codegolf.stackexchange.com/a/192950/58974) so please `+1` him, too.
```
f=n=>--n?(d=" wwswsnwwseenwwenwnwnenwn"[n])+f(n+~~{n:-4,s:6,e:2}[d]):``
```
[Try it Online!](https://tio.run/##FctBCsIwEIXhq4SsMkwjUtRFavQgpdDSJKKUiXTEBMRePUYe/7d7j@k98bzeny9N0flSgiV70ZquylkpUuLEVPW@Wqv7K3saAIMi3LYPGX1o2Jwab9pv7wYw41hCXFW2@y4jnttjB3MkjovfLfGmMkphhaz/DFB@)
1 byte saved thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~43~~ 40 bytes
```
NθW⊖θ«≔I§”)“⊞x⟧∧⎚⁵2”ιι§nwesι≧⁺⁻⁺﹪ι²×³ι⁵θ
```
[Try it online!](https://tio.run/##RU5BCsIwEDy3rwg9baAePOilp6KXHqxF/EBslzbQpjWbGEF8e0y0IMsMw8zOsu0gdDuL0ftKLdbUdrqhhjsvUjfIERkcsdU4oTLYBZuzV5qURLJXUJpKdfiEjJwjRyowYuCAMJGznEkeUaRJo6Uy8JUnsfxOXGQ/GGhGSzm7ygkJzhoOsw2LGeHarrEXBmHLg/7H6NZ4F/3479v7vd88xg8 "Charcoal – Try It Online") Link is to verbose version of code. Based on both @ChasBrown's and @xnor's answers. Explanation:
```
Nθ
```
Input the room.
```
W⊖θ«
```
Set the loop variable `i` to one less than the room number and repeat while it is non-zero.
```
«≔I§”)“⊞x⟧∧⎚⁵2”ιι
```
Extract the direction from the compressed string `0113130113220112010102010`. (The leading `0` is just a filler digit.)
```
§nwesι
```
Print the direction.
```
≧⁺⁻⁺﹪ι²×³ι⁵θ
```
Use @xnor's formula to calculate the new room number.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 29 bytes
```
“þ&ƊĿñ÷°e’b6Ḥ_5Ż⁸+ị¥ƬI‘ị“®ȯẹ»
```
[Try it online!](https://tio.run/##AVsApP9qZWxsef//4oCcw74mxorEv8Oxw7fCsGXigJliNuG4pF81xbvigbgr4buLwqXGrEnigJjhu4vigJzCrsiv4bq5wrv/O@KAnCAtPiDigJ07w4cKMjXDh@KCrFn/ "Jelly – Try It Online")
A monadic link taking the starting cell and returning a string with the directions.
I love the fact that Jelly’s dictionary has a word like ‘Kennesaw’ (a city northwest of Atlanta, Georgia), used here because indexing into it with `[5, 1, -5, -1] + 1` gives `nesw`!
## Explanation
```
“þ...e’ | Base-250 integer 1962789844189344852
b6 | Convert to base 6 (2, 2, 5, 2, 5, 0, 2, 2, 5, 3, 3, 0, 2, 2, 3, 0, 2, 0, 2, 0, 3, 0, 2, 0)
Ḥ | Double
_5 | Subtract 5
Ż | Prepend 0
⁸ ¥Ƭ | Using this as the right argument and the original link argument as the left argument, loop the following as a dyad until there is no change, collecting up results
+ | - Add the left argument to:
ị | - The left argument indexed into the right argument
I | Differences between consecutive numbers
‘ | Increment by 1
ị“®ȯẹ» | Index into "Kennesaw"
```
[Answer]
# [PHP](https://php.net/), 110 bytes
A solution which isn't a port of [Chas Brown's great answer](https://codegolf.stackexchange.com/a/192950/81663) or [xnor's great answer](https://codegolf.stackexchange.com/a/192952/81663). I know this is longer but I wanted to have a different solution!
```
for($n=$argn;$n>1;$n=ord($s[$n*2+1])%30)echo($s='0000w<w sEw"s)n w%w&s-e*e+n&w+w,e/n*w/n,w1n.e5n0w5n2')[$n*2];
```
[Try it online!](https://tio.run/##RY7NDoIwEITvPMWGFKFU5MdwKsWTvoRyMFqFy7ahJnswvrq1cHEOu5PJ7pexo/XdwY42ih5mhoxNoKCWEHanoGkXJwSHdwRB@jYaiJebHmK5Ruw6PzH8sEn6QMgYqjWSDPs6DGXme8bcmWHeiHrgyb7iCyZkKq2CqCNwR4odR6CENq7QuRa4IUFbXWJOJW6pxp1usaIWm5SvrEH6f6MLhjYf37RfY1@TQeeL0w8 "PHP – Try It Online")
I have created a mapping string which has 2 characters for every cell in the board. First character for each cell is a move (n/e/s/w) or `0` and the second character's ASCII code mod 30 will return another cell number which we should follow its move in recursive mode until we get to exit cell (`cell < 2`).
For example for input of 8:
* 2 characters for cell `8` are: `w%`
* It means print `w` and continue with moves for cell of `%`
* ASCII code of `%` is 37 which mod 30 will be 7, so next cell to follow is `7`.
* 2 characters for cell `7` are: `n` (last character is space, ASCII code = 32)
* It means print `n` and continue with moves for cell of 32 mod 30 which is `2`.
* 2 characters for cell `2` are: `w<` (last character ASCII code = 60)
* It means print `w` and continue with moves for cell of 60 mod 30 which is `0`.
* If cell number is less than `2`, loop stops!
* Final printed result: `wnw`
---
# [PHP](https://php.net/), 75 bytes
This version is written by [Grimy](https://codegolf.stackexchange.com/users/6484/grimy), it is 35 bytes shorter than my original answer because he/she is smarter! Grimy's comment: *"4 \* 25 < 256, so you only need 1 byte per cell, not 2"*
```
for($n=$argn;$n=ord("0\0~f;6o4R:s%ql&rup*@^tIDbx"[$n%25]);)echo news[$n%4];
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwMWVll@koKGSqWCrYGitAKRtbBWMTEEsbW1NhWouBSBITc7IV1ACqbFTULIGC6kkFqXnAfWoZFr/B5qgoZJnCxayBjLyi1I0lAxiDOrSrM3yTYKsilULc9SKSgu0HOJKPF2SKpSiVfJUjUxjNa01wSbnpZYXg4RMYq3/I6yLyQNaVfvfyPRffkFJZn5e8X9dNwA "PHP – Try It Online")
---
# [PHP](https://php.net/), 71 bytes
This port of [Arnauld's answer](https://codegolf.stackexchange.com/a/192961/81663) which is port of [xnor's answer](https://codegolf.stackexchange.com/a/192952/81663), but as a loop instead of recursive function, since it turns out to be shorter in PHP.
```
for($n=$argn;--$n;$n+=$d*3+$d%2-4)echo nwes[$d=79459389361621/4**$n&3];
```
[Try it online!](https://tio.run/##RU1LDoIwFNxzihfyNNCmMbSANqW68xLqwggKm9cGTFwYr24tbJzNTCbz8b0PzcH3PknuboQMB7BQGIjcWJDVrDjP4Z1ARHfrHaRzZg@pWSy8jg@KHRxMiAsZkl0sIwSSQeIWW6Y4tispynwZoFc3nbC1W11WWu20qotaFpuSMaS1upjwvzpTvPkEWX2dfw6OpiCOPw "PHP – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 81 bytes
```
v;f(p){p-1&&putchar(v="00wwswsnwwseenwwenwnwnenwn"[p])+f(p+=v%5?6-v%8:v%2?5:-5);}
```
[Try it online!](https://tio.run/##FYvRCoMgGIXvfYofwVCcUIFj5FwPsu0iWi5hc2JlF9GzO@NwvnP4f04v@k/n3ilFZahnmxdVUfhl7scu0KhxWa7rtE4ucxgys7MO4rt/Mp5HXEci27OI5NJEUreyEZKpPVk3w7ezjjLYkPkFehwsaKiUvepaKs4t2xD4kB8GKH448hI3wCfLFAJDj9hRGOYlOChzT38 "C (clang) – Try It Online")
Thanks to @Tommylee2k suggestion -8!
+ recursive call
# [C (clang)](http://clang.llvm.org/), 90 bytes
```
v;f(p){for(char*l="00wwswsnwwseenwwenwnwnenwn";p-1;p+=v%5?6-v%8:v%2?5:-5)putchar(v=l[p]);}
```
[Try it online!](https://tio.run/##FY1RC4MgFIXf/RUXQdA1oQLHyLl@yLaHaLmE5sTKHqLf7pTL/c7hHji35/3U2U@MQWrq2K5/nvZj50@TwmW5bfM228RhSEybJhNLxyvpChWIaC88kGsTSN2Khgvm1iUX0KCmh3sxeURjF/h2xlIGO8oP8sGAgkqam6qFLArDdgTOp0ADxU9L3vwO@GyYRKBplgP5YVm9hTL5@Ac "C (clang) – Try It Online")
Similar to all not compressed solutions.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~45~~ 43 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
õ?[Ð#.•DUo¢ê`Ω÷‰₂¡)R€ûK•¦sè©?Ž₁9₂в6-'€Ã®kè+
```
Port of [*@ChasBrown*'s Python 2 answer](https://codegolf.stackexchange.com/a/192950/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//8Fb76MMTlPUeNSxyCc0/tOjwqoRzKw9vf9Sw4VFT06GFmkGPmtYc3u0NlD60rPjwikMr7Y/ufdTUaAmUvbDJTFcdJN18aF324RXa//8bAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9k6upnr6Sga6egZO/3//BW@@jDE5T1HjUscgnNP7To8KqEcysPb3/UsOFRU9OhhZpBj5rWHN7tDZQ@tKz48IpDK@2P7n3U1GgJlL2wyUxXHSTdfGhd9uEV2v9rD22z/w8A).
**Explanation:**
```
õ? # Output an empty string
# (to overwrite the implicit output if the input is 1)
[ # Start an infinite loop:
Ð # Triplicate the top of the stack
# (which is the (implicit) input in the first iteration)
# # If it's exactly 1: stop the infinite loop
.•DUo¢ê`Ω÷‰₂¡)R€ûK•
# Push compressed string "a wwswsnwwseenwwenwnwnenwn"
¦ # Remove the first character
sè # Swap to get the number, and use it to index into the string
© # Store it in variable `®` (without popping)
? # Print it without trailing newline
Ž₁9 # Push compressed integer 22449
₂в # Convert to base-26 as list: [1,7,5,11]
6- # Subtract 6 from each: [-5,1,-1,5]
'€Ã '# Push dictionary string "news"
®k # Get the index in this string of character `®`
è # And use that to index into the integer-list
+ # And add it to the originally triplicated integer
```
[See this 05AB1E tip of mine (all four sections)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•DUo¢ê`Ω÷‰₂¡)R€ûK•` is `"a wwswsnwwseenwwenwnwnenwn"`; `Ž₁9` is `22449`; `Ž₁9₂в` is `[1,7,5,11]`; and `'€Ã` is `"news"`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 120 bytes
```
S=__wwswsnwwseenwwenwnwnenwn
N=n-5w-1s05e01
for((i=$1;$i>1;i+=$j)){ d=${S:$i:1};j=${N:`expr index $N $d`:2};printf $d; }
```
[Try it online!](https://tio.run/##FcdBCoMwEAXQvafIYhZKEZyCXSTEI2TjAbQlkY6LVJJCBMnZp1M@//H/65nfzLNdllJyyVEMQZRK/jbOxn4sPeZhDAM22ye1LVlAAzShoZuFvesu5S1cswbSWM0u2@k1nEdSFH04FTgFftX3ao5E8bvJM6oyMz5@ "Bash – Try It Online")
I toyed for a while with trying to bit-pack the string as nibbles, but the decoding would require more characters than the number saved.
### How it works:
```
S=__wwswsnwwseenwwenwnwnenwn
```
String $S holds a single character (n,w,s,e) for each room showing which direction to take to move one room towards the exit, skipping rooms 0 and 1.
```
N=n-5w-1s05e01
```
String $N has the delta to add to/subtract from the current room number for each direction change (n: -5, w: -1, s: +5, e: +1)
```
for((i=$1;$i>1;i+=$j)){ d=${S:$i:1};j=${N:`expr index $N $d`:2};printf $d; }
```
Start with $i equal to the room number given on the command line ($1). Assign the character at index $i in string $S to $d. Retrieve the delta value from $N for the direction to take to the next room, assigning it to $j.
Print the next direction to take in $d.
Add/subtract the delta in $j to/from $i.
Loop until we leave room #2 (while $i>1).
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 31 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
α-J╒Θ▀╣ô¥$v╞||T←]┬yΣ╨z§£sU╕τR"┌
```
[Run and debug it](https://staxlang.xyz/#p=e02d4ad5e9dfb9939d2476c67c7c541b5dc279e4d07a159c7355b8e75222da&i=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A22%0A23%0A24%0A25&a=1&m=2)
[Answer]
# [Kotlin](https://kotlinlang.org), 112 bytes
```
val d=" 113130113220112010102010"
fun p(r:Int):String=if(r>1)"nwes"[d[r]-'0']+p("046:"[d[r]-'0']-'5'+r)
else ""
```
[Try it online!](https://tio.run/##hVbvbxo5EP3OXzFFlQIKWbIkJA26RKp6Va8fqjtdK51OUT@YxcBeFpvaXght@rfn3oz3B3DVNdGytud5Zjx@ft4HG4rcPA@H9MZpFfSM5tZRWOaeMjvTtLDFnLKlKgptFnrSAXAZwtpPhkO2sznxQWUP@hEoQJLMroZfhunN6ObymuFvfabWGi41FWq6c7kJyxfUYdPftiTlYHNqvUbo3MTI48dxi6UzhmqVLclZuyLYYdNICLk6DKQULI3GpMyMkRxIP@aBgXAoc9JE4p2etX91@5QNT3BCNMJzgfYl3mN6qmeconvwjjOu8Fxj6BWeG3pKz@OMp2M03tGQIkaKGOkFHsRIfxojvQIKMdJXaN8gwZ/GGKV4EGOEGKNLtPdjHK1eYhAZfm3R0LHvD7ZmkW@0IcWlXJdBiisV3UU7Q7PSOW1CsQMm4Yngj/IPXH9sjC1DNZGxfmld0D6Q119KbTJNdk4ru9Geegam5QA77cNAsJiK/hbwPhmtZ9hwOHQtFbCtwH2Q6ZkyNNV1OGy8Mjvm8koFSXab@yWje0UO/@QDyLUYYA1O7ZIk6fMaC2sW/AaeoaWPtAWxncqCdp7MYDvQAy9xf9OoD9cIh0NwsrBMee3lnKR0e0d6tQ67KtqQQ7NlxJYtty6kJc1Lbvrt1khvLIameyVGrU3Vv@Z@bL4SZGzfRHexA0bWHquBmFHjJJU82u5FdFr1Liu/VXdcu676V3FuOzum1ParvNqBm9p97I/OmwDVQFp5aKaMmgTboTrJdqRJtB0at6HMlnjoY008ZfxWOybIdIcB8ML4F0L5t49rSAhIFncLFogP72uO0UfRRXCbkbPc6Szk1kzoq3ZWTBV7rdHSZdYKi8M22oXWrFFw6XQECcMT@gTNY6ja2HzmaaXD0s5ApKLw5NWGc5Fck85GFW1wuqUutCG9SC/O8Tsa4RcP/vm3e7imeWniJDlBoXRGlhaXykicw8azry6BeNYT@lPjjHsYGLgqUUWctBkvVWpU@2aR8EGrGZwxslCr6UwhbQBo7Wymve@xxwm9N6E/oY@x0LedDnSHMOP9vFUYlg/UDomsrNOsA7iMQo1Ue3XAklhCErHlc5IYdEdpPzqWCX9huo4C1s6c7ohLwUnw1jbguOPNuT8oh1w6LZTlrnVYUQf3lsVe81sv9J5jBPTlNLBbxrFPYVATKjnIWBUeNmsy3Mwm4EfCubgdG91imSwY92URfO2ia0DC7n2T3D1n//ns5Pzk82ldmGr6J1RQPVRqB1dSbZZc1PYQOc8XpROZbQuylRt8o4tDKEqA5S5svdC2Slt9iPyHKRVd6FlCb1SRlQWvlm@NA2TcGMsXB7MCPMwUy3Q8JkfYQFtbFjhJFu4jXI4RvdPhKNV9lY9fFXun4wDKJ7jeQgHNsRHt5EPwLtfFrF6/nc89M9DKJhr9eJREPGuvZ9V3UFtcvmcPkPs3LvtjYv/YJ84o60sd3Mt9dTZmQv@3AszEAZ2lDd3ncDqg9IgBldHnX3UUtHE9dpSlxX2a7I3VErA31D2/vJr8mKNnJ@OTU@72G3n4HTEcLvKoBnL1hvZ7D0fF2Brako1pLF8iU91yTGC68HXK3SiXHxQK2khl@yVcf/9GKVsB1VNu4Sf0mj8ffok6dtenb@LlVxWUFGZfdKvFyz6xWq2wgfIZ8VHHU61rqd5o0VoJj49pBsYPDsh7ZPCz3AO3/6v@ork9NxGljQne5vOeu0v7tTDcu0oN1r16H@qhWPx@h0uE4jxLTf@olsBas7be59MiktSj3H5dqF08LRWdhL5chjyc@L3LhYvPa@vFw4yKp0kyGvc7kSPQzML0ui@j9eW3dcT1v3f7ne/sm8v//C8 "Kotlin – Try It Online")
] |
[Question]
[
## Challenge:
Write a code that, when executed will output the source code of a second program that can be executed in another language. The second program should output the source code of a third program that can be executed in a third language and so on. The last program should output **`PPCG`** with an optional single trailing newline.
The winner will be the submission with the most languages. Code length of the first program will be the tie breaker.
**Important rules:**
1. No programs can be identical
2. Each language must only work on one of the source codes. It should be impossible to use the same language two places in the chain without breaking it(see examples).
* A shortened chain is not a broken chain. If you can use a language in a different place than intended and the end result is still PPCG then it's invalid
3. All versions of a language count as unique languages (but keep in mind rule number 2)
---
## Examples:
**An invalid submission:**
```
print("""print'disp("PPCG")'""")
```
* Python 3: `print("""print'disp("PPCG")'""")` prints `print'disp("PPCG")'`
* Python 2: `print'disp("PPCG")'` prints `disp("PPCG")`
* Octave : `disp("PPCG")` prints `PPCG`
This works properly, **but:** you can run both the first and the second code in Python 2 without breaking the chain, so this violates rule number 2.
**A valid submission with score 3:**
```
print("""print'disp("PPCG")'""")
```
* Python 3: `print("""print'disp("PPCG")'""")` prints `print'disp("PPCG")'`
* Perl : `print'disp("PPCG")'` prints `disp("PPCG")`
* Octave : `disp("PPCG")` prints `PPCG`
This is the exact same code as the invalid example. The difference is, we have chosen languages that adhere to rule number 2: You can't run the first code in Perl/Octave, the second code in Python 3/Octave nor the last code in Python 3/Perl. This is valid even though Python 2 can run the two first programs, because we haven't used Python 2 as one of the languages.
[Answer]
# 12 languages, 64 bytes
## [Charcoal](https://tio.run/nexus/charcoal#@/9@zwaNQo2Cosy8Eg11/Qp9MEu/QklJqUKh0MZeKSFTT0vJyt7ZI0hFw9hEU1spRj0gwNk9Rj1ByQ6oSF3L8P9/AA) -> [tinylisp](https://tio.run/nexus/tinylisp#@69RqFFQlJlXoqGuX6EPZulXKCkpVSgU2tgrJWTqaSlZ2Tt7BKloGJtoaivFqAcEOLvHqCco2QEVqWsZ/v8PAA) -> [Python 3](https://tio.run/nexus/python3#@69RUJSZV6Kgoa5foQ9m6lcoKSlVKBTa2CslZOppKVnZO3sEqShoGJtoKmgrxagHBDi7x6gnKNkBlalrGWpq/v8PAA) -> [///](https://tio.run/nexus/slashes#@69foV9QlJlXol@hpKRUoVBoY6@UkKmnpWRl7@wRpKKgYWyiqaCtpB4Q4OyunqBkB1T0/z8A) -> [Python 2](https://tio.run/nexus/python2#@19QlJlXoqSkBKYVCm3slRIy9bSUrOydPYJUFDSMTTQVtJXUAwKc3dUTlOyACv//BwA) -> [Perl](https://tio.run/nexus/perl#@19QlJlXolBoY6@UkKmnpWRl7@wRpKKgYWyiqaCtpB4Q4OyunqBk9/8/AA) -> QBasic -> [Pip](https://tio.run/nexus/pip#@5@QqafFpaQeEODsrp7w/z8A) -> [V](https://tio.run/nexus/v#@5@pp8WlpB4Q4Oyu/v8/AA) -> [Retina](https://tio.run/nexus/retina#@6@nxaWkHhDg7K7@/z8A) -> [Pyth](https://tio.run/nexus/pyth#@6@kHhDg7K7@/z8A) -> [GolfScript](https://tio.run/nexus/golfscript#@68eEODsrv7/PwA)
### Charcoal
```
P(q(print('/x/print/x"""x q<?"`i.*":?CHR$(34)+"\'PPCG\'`">"""'*1
```
Any run of printable ASCII is a string literal in Charcoal. `P` can be used for multidirectional printing, but in this case it simply prints the string going rightward.
### tinylisp
```
(q(print('/x/print/x"""x q<?"`i.*":?CHR$(34)+"\'PPCG\'`">"""'*1
```
The only reserved characters in tinylisp (as of this writing) are parentheses and whitespace. Any other run of characters is a token, even something like `+"\'PPCG\'`">"""'*1`. Parentheses define lists. The `q` (quote) builtin returns its argument unevaluated--in this case, the nested list `(print ('/x/print/x"""x q<?"`i.*":?CHR$ (34) +"\'PPCG\'`">"""'*1))`. (Missing parentheses at the end are autocompleted.)
### Python 3
```
(print ('/x/print/x"""x q<?"`i.*":?CHR$ (34) +"\'PPCG\'`">"""'*1))
```
Since `print` is a function in Python 3, we can wrap it in parentheses with no problem. In Python 2, where it's a statement, this is a syntax error. Unfortunately, Perl is fine with the parentheses, so we also do `*1` (string repetition in Python, cast to int and multiply in Perl).
### ///
```
/x/print/x"""x q<?"`i.*":?CHR$ (34) +"'PPCG'`">"""
```
`/x/print/` changes `x` to `print` in the rest of the program, which has no slashes and therefore is output with no further changes.
### Python 2
```
print"""print q<?"`i.*":?CHR$ (34) +"'PPCG'`">"""
```
No parentheses after `print`, doesn't work in Python 3. Perl doesn't like the triple quotes.
### Perl
```
print q<?"`i.*":?CHR$ (34) +"'PPCG'`">
```
Perl's various ways of quoting a string are helpful, and distinct from other languages. Here we use `q<...>`.
### QBasic
```
?"`i.*":?CHR$ (34) +"'PPCG'`"
```
A couple of print statements (abbreviated as `?`), using `CHR$(34)` to get a double quote.
### Pip
```
`i.*
"'PPCG'`
```
A single Pattern (regex) literal in backticks.
### V
```
i.*
"'PPCG'
```
Switch to insert mode, add some text.
### Retina
```
.*
"'PPCG'
```
Match anything and replace it with the second line.
### Pyth
```
"'PPCG'
```
Pyth quotes don't need to be matched (which makes this not a valid program in Pip).
### GolfScript
```
'PPCG'
```
[Answer]
# ~~14~~ ~~16~~ ~~17~~ 18 Languages: [Fueue](https://github.com/TryItOnline/fueue) > 05AB1E > APL (dzaima/APL) > Charcoal > Javascript (Node.js) > Go > C# > Emojicode > Java > C++ > LOLCODE > brainfuck > ruby > C > Python > /// > Fish > Befunge, 2139 Bytes
>
> [Fueue program that's 30410 bytes long](https://tio.run/##7V0LctwgDL3KHiEYYTs36EXSG@T8W@NNWxAg//gIr2Y6mWITDE/Sk1D4/P7@@v56Ps30gM8HzI/lP4NWDzM@jLYF87GW1bQ8U3/friVYayhbY6n97/HkVrJtrv/Qgxk9WFoif2V2P/F64NQwg@0NWT/WonIbcLqExqnCAbmgLOM1xOhn/NqkuxEOTLmf8gSUbE6nsX5JlKw/k4NNiHOBDz2AxBCMwpVncoTR5gZ6QLi7CCIfkQmLOifcAy4RkrVWpC4h4xnBov6hkQ0HOh9rH9nIsAV0qFsbH/SN0tecEeGzvAsVUaf7HxhXKF@NpT2lSSVUhtjndXo0W@KhGSv4lahyTrSG0YBFRwhpiW7Z0uceTsYag1TOQdBsEutu09ynPCcMyNfnySOAidD1GPLDpjLoc1xjHblp6rGtbZvDWFO2jchqwugSHsmCY37E42pYDESzGjIG4xUQLc9QpBBrYVx/ThFbIdyYrT9uob3TMsvS3DUj3faR9XDqnS9zRzNjRBQ34cuQISvEHkMIX/gJszf8S9lGzgiQItWzJT@6V8ciyA0qi2I4hyqY9JwLFKG@6k2hHQ8rkNoTYZ313R9lRUKUUjZ8SKnqzblOxMAhqWrPO@rDqQ/Shgl1QyXVUu4VTN8gJFyyNoQnGNKkagOyOY01ikeHRHRq21T3Qv6IhVswICUKz02id4B/D7x30/uodh4jJ3KUN8Rs/9iFQlNEhabf@noJMPWqfSXAUZs62SacHANcx4Xq56HxZe9nA6kk5VAC3Qu9PtXPQn3RRM/guhVn00/Vu0ae/XqVUnbLKcHl2ZihBJeXKEFxSauaX2ju42pLGq4zWBXOgpqMwqwEbFmYaV@aa@tZBHdqJLNIPEOva0exrGPaUxbXrc53ESWUQLcK8n3GPeoG9sB3/qfbaXmJfI/MZfLOhDnZdO1cbInoQmYTPGws0CWCpQ4wkS4wo@Wb4dGdeAtOuQsteT5ueb6OZlKntIC1zkuOrNXXoZ236CiDdb9M6f4ZA6eYqEOPx9p3SKwhf1OkJQ39/T2HWS4WuKwjYx2tlbf@XuIQiTw4Zif5IthhdrkQZ5VACWrOgQ61Aoz0RbhVuPW9ufV@K8caMh@z1Te67E4JZqtFoOyaheY5OfFV4qvEV4mvapFlhJpM23bVFbO5oWSbxMuIl5Fs01tnm26yZws6WfGS3ff3suKa9WxXX5dRlVKHe5Oa77DPvlu8bbbpljFKn9qjbrDOX8vaCoa5Snir3R6yLlbWxcq6WFkX2/jcH747HvieidBLNMP6VDpd3ANB73v8au/4u8nZRV2csFYlF1v4XDi@J1yUkHtHJwCqmvrZfH9OQ@vn5e3ljGs541rOuL6K2Rscv288GhmJOxNG72qK4H6DKXX8/v2UREcuwtN1T2J3PTndndSDxEVh888No@4H4Oeqi@DmUu/KMlN9JFRb0cpJAgyut/v/7tfz@Qc "Fueue – Try It Online")
>
>
>
Fueue outputs:
```
9109ç8592ç«39ç«65328ç«99ç«111ç«110ç«115ç«111ç«108ç«101ç«46ç«108ç«111ç«103ç«40ç«39ç«39ç«112ç«97ç«99ç«107ç«97ç«103ç«101ç«32ç«109ç«97ç«105ç«110ç«59ç«105ç«109ç«112ç«111ç«114ç«116ç«32ç«34ç«102ç«109ç«116ç«34ç«59ç«102ç«117ç«110ç«99ç«32ç«109ç«97ç«105ç«110ç«40ç«41ç«32ç«123ç«102ç«109ç«116ç«46ç«80ç«114ç«105ç«110ç«116ç«40ç«34ç«117ç«115ç«105ç«110ç«103ç«32ç«83ç«121ç«115ç«116ç«101ç«109ç«59ç«99ç«108ç«97ç«115ç«115ç«32ç«80ç«114ç«111ç«103ç«114ç«97ç«109ç«123ç«115ç«116ç«97ç«116ç«105ç«99ç«32ç«118ç«111ç«105ç«100ç«32ç«77ç«97ç«105ç«110ç«40ç«115ç«116ç«114ç«105ç«110ç«103ç«91ç«93ç«32ç«97ç«114ç«103ç«115ç«41ç«32ç«123ç«67ç«111ç«110ç«115ç«111ç«108ç«101ç«46ç«87ç«114ç«105ç«116ç«101ç«40ç«92ç«92ç«34ç«127937ç«32ç«127815ç«128512ç«32ç«128292ç«112ç«117ç«98ç«108ç«105ç«99ç«32ç«99ç«108ç«97ç«115ç«115ç«32ç«77ç«97ç«105ç«110ç«32ç«123ç«112ç«117ç«98ç«108ç«105ç«99ç«32ç«115ç«116ç«97ç«116ç«105ç«99ç«32ç«118ç«111ç«105ç«100ç«32ç«109ç«97ç«105ç«110ç«40ç«83ç«116ç«114ç«105ç«110ç«103ç«91ç«93ç«32ç«97ç«114ç«103ç«115ç«41ç«123ç«83ç«121ç«115ç«116ç«101ç«109ç«46ç«111ç«117ç«116ç«46ç«112ç«114ç«105ç«110ç«116ç«40ç«92ç«92ç«92ç«92ç«92ç«92ç«34ç«35ç«105ç«110ç«99ç«108ç«117ç«100ç«101ç«32ç«60ç«105ç«111ç«115ç«116ç«114ç«101ç«97ç«109ç«62ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«110ç«105ç«110ç«116ç«32ç«109ç«97ç«105ç«110ç«40ç«41ç«123ç«115ç«116ç«100ç«58ç«58ç«99ç«111ç«117ç«116ç«32ç«60ç«60ç«32ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«34ç«72ç«65ç«73ç«32ç«49ç«46ç«50ç«32ç«66ç«84ç«87ç«43ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«110ç«86ç«73ç«83ç«73ç«66ç«76ç«69ç«32ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«34ç«32ç«60ç«60ç«32ç«92ç«39ç«39ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«34ç«92ç«39ç«39ç«32ç«60ç«60ç«32ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«34ç«43ç«91ç«45ç«45ç«45ç«45ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«43ç«43ç«46ç«45ç«45ç«45ç«46ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«45ç«45ç«46ç«91ç«45ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«43ç«46ç«45ç«91ç«45ç«45ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«46ç«45ç«91ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«46ç«43ç«91ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«46ç«91ç«45ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«43ç«46ç«62ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«45ç«91ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«46ç«43ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«46ç«91ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«91ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«43ç«43ç«46ç«43ç«46ç«45ç«45ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«45ç«46ç«45ç«45ç«91ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«46ç«45ç«45ç«91ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«43ç«46ç«43ç«43ç«91ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«91ç«45ç«62ç«43ç«43ç«43ç«43ç«43ç«60ç«93ç«62ç«43ç«43ç«43ç«46ç«43ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«43ç«43ç«46ç«43ç«43ç«91ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«46ç«91ç«45ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«91ç«45ç«62ç«43ç«43ç«43ç«43ç«60ç«93ç«62ç«45ç«45ç«46ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«91ç«45ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«43ç«43ç«46ç«43ç«91ç«45ç«45ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«91ç«43ç«43ç«62ç«45ç«45ç«45ç«60ç«93ç«62ç«46ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«45ç«91ç«45ç«62ç«43ç«43ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«91ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«43ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«91ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«43ç«46ç«45ç«45ç«45ç«91ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«45ç«45ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«91ç«43ç«43ç«62ç«45ç«45ç«45ç«60ç«93ç«62ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«91ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«43ç«46ç«43ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«46ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«91ç«45ç«45ç«62ç«43ç«43ç«43ç«43ç«43ç«60ç«93ç«62ç«46ç«91ç«45ç«45ç«45ç«45ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«43ç«46ç«45ç«45ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«91ç«45ç«45ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«43ç«43ç«43ç«46ç«43ç«43ç«46ç«45ç«45ç«45ç«45ç«46ç«45ç«45ç«45ç«45ç«46ç«46ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«46ç«45ç«45ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«46ç«45ç«45ç«45ç«45ç«46ç«45ç«45ç«45ç«91ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«45ç«45ç«45ç«45ç«46ç«91ç«45ç«62ç«43ç«43ç«43ç«43ç«43ç«60ç«93ç«62ç«43ç«46ç«46ç«91ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«45ç«46ç«43ç«43ç«43ç«43ç«46ç«45ç«45ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«46ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«46ç«46ç«46ç«91ç«45ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«45ç«45ç«46ç«45ç«91ç«45ç«45ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«43ç«46ç«45ç«45ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«91ç«45ç«45ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«43ç«43ç«43ç«46ç«43ç«43ç«46ç«45ç«45ç«45ç«45ç«46ç«45ç«91ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«46ç«43ç«43ç«43ç«43ç«46ç«45ç«45ç«91ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«46ç«46ç«46ç«46ç«91ç«45ç«62ç«43ç«43ç«43ç«43ç«60ç«93ç«62ç«45ç«45ç«46ç«45ç«91ç«45ç«62ç«43ç«43ç«43ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«46ç«46ç«46ç«46ç«46ç«46ç«46ç«46ç«46ç«46ç«45ç«45ç«91ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«43ç«91ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«43ç«43ç«46ç«45ç«91ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«45ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«43ç«46ç«43ç«43ç«43ç«46ç«43ç«91ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«43ç«43ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«91ç«45ç«45ç«62ç«43ç«43ç«43ç«43ç«43ç«60ç«93ç«62ç«46ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«45ç«46ç«43ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«45ç«45ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«91ç«43ç«43ç«62ç«45ç«45ç«45ç«60ç«93ç«62ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«45ç«91ç«45ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«45ç«45ç«91ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«91ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«45ç«45ç«45ç«46ç«43ç«46ç«45ç«45ç«45ç«46ç«45ç«45ç«45ç«45ç«46ç«45ç«91ç«45ç«62ç«43ç«43ç«43ç«43ç«43ç«60ç«93ç«62ç«45ç«46ç«91ç«45ç«45ç«62ç«43ç«43ç«43ç«60ç«93ç«62ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«45ç«91ç«45ç«45ç«45ç«62ç«43ç«43ç«60ç«93ç«62ç«43ç«46ç«45ç«91ç«45ç«45ç«45ç«45ç«62ç«43ç«60ç«93ç«62ç«43ç«43ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«62ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«43ç«91ç«45ç«45ç«45ç«62ç«43ç«43ç«43ç«43ç«60ç«93ç«62ç«43ç«46ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«43ç«46ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«45ç«46ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«34ç«32ç«60ç«60ç«32ç«92ç«39ç«39ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«34ç«92ç«39ç«39ç«32ç«60ç«60ç«32ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«34ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«110ç«75ç«84ç«72ç«88ç«66ç«89ç«69ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«92ç«34ç«59ç«125ç«92ç«92ç«92ç«92ç«92ç«92ç«34ç«41ç«59ç«125ç«125ç«128292ç«10071ç«65039ç«127817ç«92ç«92ç«34ç«41ç«59ç«125ç«125ç«34ç«41ç«125ç«39ç«39ç«41ç«39ç«
```
05AB1E outputs:
```
⎕←'Pconsole.log(''package main;import "fmt";func main() {fmt.Print("using System;class Program{static void Main(string[] args) {Console.Write(\\"🏁 🍇😀 🔤public class Main {public static void main(String[] args){System.out.print(\\\\\\"#include <iostream>\\\\\\\\nint main(){std::cout << \\\\\\\\\\\\\\"HAI 1.2 BTW+\\\\\\\\\\\\\\\\nVISIBLE \\\\\\\\\\\\\\" << \''\\\\\\\\\\\\\\"\'' << \\\\\\\\\\\\\\"+[----->+++<]>++.---.[--->+<]>--.[-->+++<]>+.-[--->++<]>.-[->++<]>-..+[-->+<]>+.[-->+++<]>+.>++++++++++.-[------->+<]>+.++.---------.+++++.++++++.+[--->+<]>+.------.+.[->+++<]>.+++++.-----------.+++++++++.+++++++++.+[->+++<]>++.+.--[--->+<]>-.--[->++<]>.--[->++<]>-.+.++[->+++<]>++.+++++.++++++.[->+++++<]>+++.+[--->+<]>+++.++[->+++<]>.[-->+++<]>-.[->++++<]>--.-----.+++++.++++++.[---->+<]>+++.+[----->+<]>.------------.++++++++.+++++.++[++>---<]>.+.---------.-[->++++<]>-.[->+++<]>-.++.---------.+++++.++++++.+++[->+++<]>+.---[->+++<]>-.------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++[->+++<]>+.++.---------.+++++.++++++.+[--->+<]>+.-.++++++++.+[-->+++++<]>.[----->++<]>-.--------.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.----..++++.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.---[->++<]>-.----.[->+++++<]>+..[-->+<]>-.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.+++++....[-->+++<]>--.-[--->++<]>---.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.-[->+++<]>.++++.--[->+++<]>....[->++++<]>--.-[->+++++<]>-...........--[->++<]>-.+[-->+<]>+++.-[->++<]>-.-[--->+<]>++.+++.+[-->+<]>++++.-------------.+[-->+++++<]>.[--->+<]>-.++.-------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++++++.-[-->+++<]>-.--[->++<]>.-------------.[--->+<]>---.+.---.----.-[->+++++<]>-.[-->+++<]>.+++++++++++.-[--->++<]>+.-[---->+<]>+++.+++++++.>++++++++++.+[--->++++<]>+.+++++++++.----------.\\\\\\\\\\\\\\" << \''\\\\\\\\\\\\\\"\'' << \\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\nKTHXBYE\\\\\\\\\\\\\\";}\\\\\\");}}🔤❗️🍉\\");}}")}'')'
```
APL (dzaima/APL) outputs:
```
Pconsole.log('package main;import "fmt";func main() {fmt.Print("using System;class Program{static void Main(string[] args) {Console.Write(\\"🏁 🍇😀 🔤public class Main {public static void main(String[] args){System.out.print(\\\\\\"#include <iostream>\\\\\\\\nint main(){std::cout << \\\\\\\\\\\\\\"HAI 1.2 BTW+\\\\\\\\\\\\\\\\nVISIBLE \\\\\\\\\\\\\\" << \'\\\\\\\\\\\\\\"\' << \\\\\\\\\\\\\\"+[----->+++<]>++.---.[--->+<]>--.[-->+++<]>+.-[--->++<]>.-[->++<]>-..+[-->+<]>+.[-->+++<]>+.>++++++++++.-[------->+<]>+.++.---------.+++++.++++++.+[--->+<]>+.------.+.[->+++<]>.+++++.-----------.+++++++++.+++++++++.+[->+++<]>++.+.--[--->+<]>-.--[->++<]>.--[->++<]>-.+.++[->+++<]>++.+++++.++++++.[->+++++<]>+++.+[--->+<]>+++.++[->+++<]>.[-->+++<]>-.[->++++<]>--.-----.+++++.++++++.[---->+<]>+++.+[----->+<]>.------------.++++++++.+++++.++[++>---<]>.+.---------.-[->++++<]>-.[->+++<]>-.++.---------.+++++.++++++.+++[->+++<]>+.---[->+++<]>-.------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++[->+++<]>+.++.---------.+++++.++++++.+[--->+<]>+.-.++++++++.+[-->+++++<]>.[----->++<]>-.--------.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.----..++++.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.---[->++<]>-.----.[->+++++<]>+..[-->+<]>-.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.+++++....[-->+++<]>--.-[--->++<]>---.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.-[->+++<]>.++++.--[->+++<]>....[->++++<]>--.-[->+++++<]>-...........--[->++<]>-.+[-->+<]>+++.-[->++<]>-.-[--->+<]>++.+++.+[-->+<]>++++.-------------.+[-->+++++<]>.[--->+<]>-.++.-------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++++++.-[-->+++<]>-.--[->++<]>.-------------.[--->+<]>---.+.---.----.-[->+++++<]>-.[-->+++<]>.+++++++++++.-[--->++<]>+.-[---->+<]>+++.+++++++.>++++++++++.+[--->++++<]>+.+++++++++.----------.\\\\\\\\\\\\\\" << \'\\\\\\\\\\\\\\"\' << \\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\nKTHXBYE\\\\\\\\\\\\\\";}\\\\\\");}}🔤❗️🍉\\");}}")}')
```
Charcoal outputs:
```
console.log('package main;import "fmt";func main() {fmt.Print("using System;class Program{static void Main(string[] args) {Console.Write(\\"🏁 🍇😀 🔤public class Main {public static void main(String[] args){System.out.print(\\\\\\"#include <iostream>\\\\\\\\nint main(){std::cout << \\\\\\\\\\\\\\"HAI 1.2 BTW+\\\\\\\\\\\\\\\\nVISIBLE \\\\\\\\\\\\\\" << \'\\\\\\\\\\\\\\"\' << \\\\\\\\\\\\\\"+[----->+++<]>++.---.[--->+<]>--.[-->+++<]>+.-[--->++<]>.-[->++<]>-..+[-->+<]>+.[-->+++<]>+.>++++++++++.-[------->+<]>+.++.---------.+++++.++++++.+[--->+<]>+.------.+.[->+++<]>.+++++.-----------.+++++++++.+++++++++.+[->+++<]>++.+.--[--->+<]>-.--[->++<]>.--[->++<]>-.+.++[->+++<]>++.+++++.++++++.[->+++++<]>+++.+[--->+<]>+++.++[->+++<]>.[-->+++<]>-.[->++++<]>--.-----.+++++.++++++.[---->+<]>+++.+[----->+<]>.------------.++++++++.+++++.++[++>---<]>.+.---------.-[->++++<]>-.[->+++<]>-.++.---------.+++++.++++++.+++[->+++<]>+.---[->+++<]>-.------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++[->+++<]>+.++.---------.+++++.++++++.+[--->+<]>+.-.++++++++.+[-->+++++<]>.[----->++<]>-.--------.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.----..++++.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.---[->++<]>-.----.[->+++++<]>+..[-->+<]>-.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.+++++....[-->+++<]>--.-[--->++<]>---.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.-[->+++<]>.++++.--[->+++<]>....[->++++<]>--.-[->+++++<]>-...........--[->++<]>-.+[-->+<]>+++.-[->++<]>-.-[--->+<]>++.+++.+[-->+<]>++++.-------------.+[-->+++++<]>.[--->+<]>-.++.-------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++++++.-[-->+++<]>-.--[->++<]>.-------------.[--->+<]>---.+.---.----.-[->+++++<]>-.[-->+++<]>.+++++++++++.-[--->++<]>+.-[---->+<]>+++.+++++++.>++++++++++.+[--->++++<]>+.+++++++++.----------.\\\\\\\\\\\\\\" << \'\\\\\\\\\\\\\\"\' << \\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\nKTHXBYE\\\\\\\\\\\\\\";}\\\\\\");}}🔤❗️🍉\\");}}")}')
```
Node.js outputs:
```
package main;import "fmt";func main() {fmt.Print("using System;class Program{static void Main(string[] args) {Console.Write(\"🏁 🍇😀 🔤public class Main {public static void main(String[] args){System.out.print(\\\"#include <iostream>\\\\nint main(){std::cout << \\\\\\\"HAI 1.2 BTW+\\\\\\\\nVISIBLE \\\\\\\" << '\\\\\\\"' << \\\\\\\"+[----->+++<]>++.---.[--->+<]>--.[-->+++<]>+.-[--->++<]>.-[->++<]>-..+[-->+<]>+.[-->+++<]>+.>++++++++++.-[------->+<]>+.++.---------.+++++.++++++.+[--->+<]>+.------.+.[->+++<]>.+++++.-----------.+++++++++.+++++++++.+[->+++<]>++.+.--[--->+<]>-.--[->++<]>.--[->++<]>-.+.++[->+++<]>++.+++++.++++++.[->+++++<]>+++.+[--->+<]>+++.++[->+++<]>.[-->+++<]>-.[->++++<]>--.-----.+++++.++++++.[---->+<]>+++.+[----->+<]>.------------.++++++++.+++++.++[++>---<]>.+.---------.-[->++++<]>-.[->+++<]>-.++.---------.+++++.++++++.+++[->+++<]>+.---[->+++<]>-.------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++[->+++<]>+.++.---------.+++++.++++++.+[--->+<]>+.-.++++++++.+[-->+++++<]>.[----->++<]>-.--------.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.----..++++.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.---[->++<]>-.----.[->+++++<]>+..[-->+<]>-.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.+++++....[-->+++<]>--.-[--->++<]>---.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.-[->+++<]>.++++.--[->+++<]>....[->++++<]>--.-[->+++++<]>-...........--[->++<]>-.+[-->+<]>+++.-[->++<]>-.-[--->+<]>++.+++.+[-->+<]>++++.-------------.+[-->+++++<]>.[--->+<]>-.++.-------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++++++.-[-->+++<]>-.--[->++<]>.-------------.[--->+<]>---.+.---.----.-[->+++++<]>-.[-->+++<]>.+++++++++++.-[--->++<]>+.-[---->+<]>+++.+++++++.>++++++++++.+[--->++++<]>+.+++++++++.----------.\\\\\\\" << '\\\\\\\"' << \\\\\\\"\\\\\\\\nKTHXBYE\\\\\\\";}\\\");}}🔤❗️🍉\");}}")}
```
Go outputs:
```
using System;class Program{static void Main(string[] args) {Console.Write("🏁 🍇😀 🔤public class Main {public static void main(String[] args){System.out.print(\"#include <iostream>\\nint main(){std::cout << \\\"HAI 1.2 BTW+\\\\nVISIBLE \\\" << '\\\"' << \\\"+[----->+++<]>++.---.[--->+<]>--.[-->+++<]>+.-[--->++<]>.-[->++<]>-..+[-->+<]>+.[-->+++<]>+.>++++++++++.-[------->+<]>+.++.---------.+++++.++++++.+[--->+<]>+.------.+.[->+++<]>.+++++.-----------.+++++++++.+++++++++.+[->+++<]>++.+.--[--->+<]>-.--[->++<]>.--[->++<]>-.+.++[->+++<]>++.+++++.++++++.[->+++++<]>+++.+[--->+<]>+++.++[->+++<]>.[-->+++<]>-.[->++++<]>--.-----.+++++.++++++.[---->+<]>+++.+[----->+<]>.------------.++++++++.+++++.++[++>---<]>.+.---------.-[->++++<]>-.[->+++<]>-.++.---------.+++++.++++++.+++[->+++<]>+.---[->+++<]>-.------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++[->+++<]>+.++.---------.+++++.++++++.+[--->+<]>+.-.++++++++.+[-->+++++<]>.[----->++<]>-.--------.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.----..++++.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.---[->++<]>-.----.[->+++++<]>+..[-->+<]>-.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.+++++....[-->+++<]>--.-[--->++<]>---.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.-[->+++<]>.++++.--[->+++<]>....[->++++<]>--.-[->+++++<]>-...........--[->++<]>-.+[-->+<]>+++.-[->++<]>-.-[--->+<]>++.+++.+[-->+<]>++++.-------------.+[-->+++++<]>.[--->+<]>-.++.-------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++++++.-[-->+++<]>-.--[->++<]>.-------------.[--->+<]>---.+.---.----.-[->+++++<]>-.[-->+++<]>.+++++++++++.-[--->++<]>+.-[---->+<]>+++.+++++++.>++++++++++.+[--->++++<]>+.+++++++++.----------.\\\" << '\\\"' << \\\"\\\\nKTHXBYE\\\";}\");}}🔤❗️🍉");}}
```
C# outputs:
```
🏁 🍇😀 🔤public class Main {public static void main(String[] args){System.out.print("#include <iostream>\nint main(){std::cout << \"HAI 1.2 BTW+\\nVISIBLE \" << '\"' << \"+[----->+++<]>++.---.[--->+<]>--.[-->+++<]>+.-[--->++<]>.-[->++<]>-..+[-->+<]>+.[-->+++<]>+.>++++++++++.-[------->+<]>+.++.---------.+++++.++++++.+[--->+<]>+.------.+.[->+++<]>.+++++.-----------.+++++++++.+++++++++.+[->+++<]>++.+.--[--->+<]>-.--[->++<]>.--[->++<]>-.+.++[->+++<]>++.+++++.++++++.[->+++++<]>+++.+[--->+<]>+++.++[->+++<]>.[-->+++<]>-.[->++++<]>--.-----.+++++.++++++.[---->+<]>+++.+[----->+<]>.------------.++++++++.+++++.++[++>---<]>.+.---------.-[->++++<]>-.[->+++<]>-.++.---------.+++++.++++++.+++[->+++<]>+.---[->+++<]>-.------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++[->+++<]>+.++.---------.+++++.++++++.+[--->+<]>+.-.++++++++.+[-->+++++<]>.[----->++<]>-.--------.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.----..++++.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.---[->++<]>-.----.[->+++++<]>+..[-->+<]>-.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.+++++....[-->+++<]>--.-[--->++<]>---.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.-[->+++<]>.++++.--[->+++<]>....[->++++<]>--.-[->+++++<]>-...........--[->++<]>-.+[-->+<]>+++.-[->++<]>-.-[--->+<]>++.+++.+[-->+<]>++++.-------------.+[-->+++++<]>.[--->+<]>-.++.-------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++++++.-[-->+++<]>-.--[->++<]>.-------------.[--->+<]>---.+.---.----.-[->+++++<]>-.[-->+++<]>.+++++++++++.-[--->++<]>+.-[---->+<]>+++.+++++++.>++++++++++.+[--->++++<]>+.+++++++++.----------.\" << '\"' << \"\\nKTHXBYE\";}");}}🔤❗️🍉
```
Emojicode outputs:
```
public class Main {public static void main(String[] args){System.out.print("#include <iostream>\nint main(){std::cout << \"HAI 1.2 BTW+\\nVISIBLE \" << '\"' << \"+[----->+++<]>++.---.[--->+<]>--.[-->+++<]>+.-[--->++<]>.-[->++<]>-..+[-->+<]>+.[-->+++<]>+.>++++++++++.-[------->+<]>+.++.---------.+++++.++++++.+[--->+<]>+.------.+.[->+++<]>.+++++.-----------.+++++++++.+++++++++.+[->+++<]>++.+.--[--->+<]>-.--[->++<]>.--[->++<]>-.+.++[->+++<]>++.+++++.++++++.[->+++++<]>+++.+[--->+<]>+++.++[->+++<]>.[-->+++<]>-.[->++++<]>--.-----.+++++.++++++.[---->+<]>+++.+[----->+<]>.------------.++++++++.+++++.++[++>---<]>.+.---------.-[->++++<]>-.[->+++<]>-.++.---------.+++++.++++++.+++[->+++<]>+.---[->+++<]>-.------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++[->+++<]>+.++.---------.+++++.++++++.+[--->+<]>+.-.++++++++.+[-->+++++<]>.[----->++<]>-.--------.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.----..++++.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.---[->++<]>-.----.[->+++++<]>+..[-->+<]>-.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.+++++....[-->+++<]>--.-[--->++<]>---.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.-[->+++<]>.++++.--[->+++<]>....[->++++<]>--.-[->+++++<]>-...........--[->++<]>-.+[-->+<]>+++.-[->++<]>-.-[--->+<]>++.+++.+[-->+<]>++++.-------------.+[-->+++++<]>.[--->+<]>-.++.-------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++++++.-[-->+++<]>-.--[->++<]>.-------------.[--->+<]>---.+.---.----.-[->+++++<]>-.[-->+++<]>.+++++++++++.-[--->++<]>+.-[---->+<]>+++.+++++++.>++++++++++.+[--->++++<]>+.+++++++++.----------.\" << '\"' << \"\\nKTHXBYE\";}");}}
```
Java outputs:
```
#include <iostream>
int main(){std::cout << "HAI 1.2 BTW+\nVISIBLE " << '"' << "+[----->+++<]>++.---.[--->+<]>--.[-->+++<]>+.-[--->++<]>.-[->++<]>-..+[-->+<]>+.[-->+++<]>+.>++++++++++.-[------->+<]>+.++.---------.+++++.++++++.+[--->+<]>+.------.+.[->+++<]>.+++++.-----------.+++++++++.+++++++++.+[->+++<]>++.+.--[--->+<]>-.--[->++<]>.--[->++<]>-.+.++[->+++<]>++.+++++.++++++.[->+++++<]>+++.+[--->+<]>+++.++[->+++<]>.[-->+++<]>-.[->++++<]>--.-----.+++++.++++++.[---->+<]>+++.+[----->+<]>.------------.++++++++.+++++.++[++>---<]>.+.---------.-[->++++<]>-.[->+++<]>-.++.---------.+++++.++++++.+++[->+++<]>+.---[->+++<]>-.------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++[->+++<]>+.++.---------.+++++.++++++.+[--->+<]>+.-.++++++++.+[-->+++++<]>.[----->++<]>-.--------.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.----..++++.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.---[->++<]>-.----.[->+++++<]>+..[-->+<]>-.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.+++++....[-->+++<]>--.-[--->++<]>---.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.-[->+++<]>.++++.--[->+++<]>....[->++++<]>--.-[->+++++<]>-...........--[->++<]>-.+[-->+<]>+++.-[->++<]>-.-[--->+<]>++.+++.+[-->+<]>++++.-------------.+[-->+++++<]>.[--->+<]>-.++.-------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++++++.-[-->+++<]>-.--[->++<]>.-------------.[--->+<]>---.+.---.----.-[->+++++<]>-.[-->+++<]>.+++++++++++.-[--->++<]>+.-[---->+<]>+++.+++++++.>++++++++++.+[--->++++<]>+.+++++++++.----------." << '"' << "\nKTHXBYE";}
```
C++ outputs:
```
HAI 1.2 BTW+
VISIBLE "+[----->+++<]>++.---.[--->+<]>--.[-->+++<]>+.-[--->++<]>.-[->++<]>-..+[-->+<]>+.[-->+++<]>+.>++++++++++.-[------->+<]>+.++.---------.+++++.++++++.+[--->+<]>+.------.+.[->+++<]>.+++++.-----------.+++++++++.+++++++++.+[->+++<]>++.+.--[--->+<]>-.--[->++<]>.--[->++<]>-.+.++[->+++<]>++.+++++.++++++.[->+++++<]>+++.+[--->+<]>+++.++[->+++<]>.[-->+++<]>-.[->++++<]>--.-----.+++++.++++++.[---->+<]>+++.+[----->+<]>.------------.++++++++.+++++.++[++>---<]>.+.---------.-[->++++<]>-.[->+++<]>-.++.---------.+++++.++++++.+++[->+++<]>+.---[->+++<]>-.------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++[->+++<]>+.++.---------.+++++.++++++.+[--->+<]>+.-.++++++++.+[-->+++++<]>.[----->++<]>-.--------.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.----..++++.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.---[->++<]>-.----.[->+++++<]>+..[-->+<]>-.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.+++++....[-->+++<]>--.-[--->++<]>---.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.-[->+++<]>.++++.--[->+++<]>....[->++++<]>--.-[->+++++<]>-...........--[->++<]>-.+[-->+<]>+++.-[->++<]>-.-[--->+<]>++.+++.+[-->+<]>++++.-------------.+[-->+++++<]>.[--->+<]>-.++.-------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++++++.-[-->+++<]>-.--[->++<]>.-------------.[--->+<]>---.+.---.----.-[->+++++<]>-.[-->+++<]>.+++++++++++.-[--->++<]>+.-[---->+<]>+++.+++++++.>++++++++++.+[--->++++<]>+.+++++++++.----------."
KTHXBYE
```
LOLCODE outputs:
```
+[----->+++<]>++.---.[--->+<]>--.[-->+++<]>+.-[--->++<]>.-[->++<]>-..+[-->+<]>+.[-->+++<]>+.>++++++++++.-[------->+<]>+.++.---------.+++++.++++++.+[--->+<]>+.------.+.[->+++<]>.+++++.-----------.+++++++++.+++++++++.+[->+++<]>++.+.--[--->+<]>-.--[->++<]>.--[->++<]>-.+.++[->+++<]>++.+++++.++++++.[->+++++<]>+++.+[--->+<]>+++.++[->+++<]>.[-->+++<]>-.[->++++<]>--.-----.+++++.++++++.[---->+<]>+++.+[----->+<]>.------------.++++++++.+++++.++[++>---<]>.+.---------.-[->++++<]>-.[->+++<]>-.++.---------.+++++.++++++.+++[->+++<]>+.---[->+++<]>-.------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++[->+++<]>+.++.---------.+++++.++++++.+[--->+<]>+.-.++++++++.+[-->+++++<]>.[----->++<]>-.--------.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.----..++++.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.---[->++<]>-.----.[->+++++<]>+..[-->+<]>-.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.+.-----------.++.----.+++++....[-->+++<]>--.-[--->++<]>---.++++.--[--->+<]>.+++++.++++++++++.[--->+<]>++.+++++++++++.++++++.[--->++<]>+++.++.----.-[->+++<]>.++++.--[->+++<]>....[->++++<]>--.-[->+++++<]>-...........--[->++<]>-.+[-->+<]>+++.-[->++<]>-.-[--->+<]>++.+++.+[-->+<]>++++.-------------.+[-->+++++<]>.[--->+<]>-.++.-------.+++++++++.++++++++.+.------.--[--->+<]>-.+++++.++++++++++.[++>---<]>.---------.+++++++.-[-->+++<]>-.--[->++<]>.-------------.[--->+<]>---.+.---.----.-[->+++++<]>-.[-->+++<]>.+++++++++++.-[--->++<]>+.-[---->+<]>+++.+++++++.>++++++++++.+[--->++++<]>+.+++++++++.----------.
```
Brainfuck outputs:
```
if 1 == 1
print("#include <stdio.h>\nint main() {printf("+34.chr+"print('/x/'+chr(39)+'##'+chr(34)+'GCPP'+chr(34)+',,,,@'+chr(39)+'rv\\\\n ;!?lo</x')"+34.chr+");return 0;}")
end
```
Ruby outputs:
```
#include <stdio.h>
int main() {printf("print('/x/'+chr(39)+'##'+chr(34)+'GCPP'+chr(34)+',,,,@'+chr(39)+'rv\\n ;!?lo</x')");return 0;}
```
C outputs:
```
print('/x/'+chr(39)+'##'+chr(34)+'GCPP'+chr(34)+',,,,@'+chr(39)+'rv\n ;!?lo</x')
```
Python outputs:
```
/x/'##"GCPP",,,,@'rv
;!?lo</x
```
/// outputs:
```
'##"GCPP",,,,@'rv
;!?lo<
```
Fish (><>) outputs:
```
##"GCPP",,,,@
```
And Finally Befunge-93 outputs: PPCG
[Try it online!](https://tio.run/##tVXNitRAEH6VJh5mhqYL9LgZBhxZ2EGFhVlcpbOHmMmG1vyRnwUZBvQkHmQvgl5kLj7EPs@@gPMGYyfdSVfHUWRx6xA61VVffVXdVf3Gv/LLoBB5xdJsFe73QZaWWRxCnEXjUe4Hb/0oJIkvUlckeVZUxLlMKse9rNOgVY8nZC01cFqItBo7dSnSiCzflVWYuEHslyU5LbKo8JN1WfmVCMhVJlbkeeNZVtIn4hfEL6JSwjzRoc8LUYVjz3N22@sPZLf9/HG3/fZeLr78yOvXscRQwA0IWWsVRm95LS30taIEWV1B3lL1WnEeiDSI61VIpiKThEI/mXlaUmmmc5TkV0dHgfQm0ynxLHFOHi/IQ3hE5mfn1BtI@mKxXMyfHQ99WpjRQOmNDqBTzhqZUUqnF/IL8gd4q5H/at1tAlMbzU@zVisGQLm2p5Z5s9CiXBnr7VQkJaBMtCXlxqrbB96halvGBt4IQYOYlBpzk1L70yWBsmjcLS9MSm3oLYsjtfxQ/qxzUnU8kClnFgo39cH5mQR7b06phGRtOVAZGQpoKsb@VmuccmOEvP5Y3T6mXdbBEcj0DEsrPIr4j7cA8Lmak4D@7iLCGghzO0DNFB6prYOZmcNWJNUHers7Rhhc3R6aW3lYFw6AW1X@n5HVHgC@uAw3@n0W1O5qQNdPMcLtgwrCwIjVwRy1Ey7ogJ1laJWFsQM3bDbsonvoiX5GovZDUwoTRMOZqbBWNfv2tycmHsMzPM7xGFM2eGzrNjT92gMZQnd@e357zZ6enbycvzoemLkbvZi4m03zTN9@//rz5lq@3J@00plsRpP9/hc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Java](https://repl.it/FTjH/1) --> [C](https://repl.it/FTgJ/2) --> [Ruby](https://repl.it/FTgR/1) --> [///](https://repl.it/FThX/1) --> [Python 3](https://repl.it/FTh3/1) --> Batch --> [JavaScript](https://repl.it/FTi4/1) --> [BrainFuck](https://copy.sh/brainfuck/?c=LVstLS0-KzxdPi0tLS0tLi4tWy0tLS0tPis8XT4uKysrKy4$) (8 Languages)
---
Click the language names for the code through each execution, except for Batch, because I couldn't find an online interpreter for it.
---
```
class Main {public static void main(String[]args){System.out.println("int main(){printf(\"puts \\\"/code/print('echo console.log(\\\\\\\\'-[--->+<]>-----..-[----->+<]>.++++.\\\\\\\\\')')/code\\\"\");}");}}
```
Explanation:
```
Java outputs int main(){printf("puts \"/code/print('echo console.log(\\\\'-[--->+<]>-----..-[----->+<]>.++++.\\\\')')/code\"");}
C outputs puts "/code/print('echo console.log(\\'-[--->+<]>-----..-[----->+<]>.++++.\\')')/code"
Ruby outputs /code/print('echo console.log(\'-[--->+<]>-----..-[----->+<]>.++++.\')')/code
/// outputs print('echo console.log(\'-[--->+<]>-----..-[----->+<]>.++++.\')')
Python outputs echo console.log('-[--->+<]>-----..-[----->+<]>.++++.')
Batch outputs console.log('-[--->+<]>-----..-[----->+<]>.++++.')
JavaScript outputs -[--->+<]>-----..-[----->+<]>.++++.
BrainFuck outputs PPCG
```
[Answer]
# Java -> BotEngine -> Treehugger -> Loader -> Batch -> Thue -> Microscript II -> BF -> ForceLang -> Javascript, 10 languages
**Java program:**
```
public class ManyLang {
public static void main(String[]arg){
int m=120;
String e="++++++++[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++>+++++++++++++>++++++++++++++>+++++++++++++++>++++++++++++++++^^^^^^^^^^^^^^^^-]>>>>>>>>>>>>>>.^^^^^^^^^^^^^^>>>>>>>>>>>>>>++.--^^^^^^^^^^^^^^>>>>>>>>>>>>>+.-^^^^^^^^^^^^^>>>>>>>>>>>>>>--.++^^^^^^^^^^^^^^>>>>>>>>>>>>>>>----.++++^^^^^^^^^^^^^^^>>>>>>>>>>>>>--.++^^^^^^^^^^^^^>>>>.^^^^>>>>++.--^^^^>>>>>>>>.^^^^^^^^>>>>>>>>>>>>>---.+++^^^^^^^^^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>>>>>>.^^^^^^^^^^^^^>>>>>>>>>>>>>>-.+^^^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>>>>>+.-^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>---.+++^^^^^^^^>>>>>>>>>>>>>>>>--.++^^^^^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>--.++^^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>--.++^^^^^^>>>>++.--^^^^>>>>.^^^^>>>>>>+++.---^^^^^^>>>>>>++.--^^^^^^>>>>>>----.++++^^^^^^>>>>>>>---.+++^^^^^^^>>>>>>>.^^^^^^^>>>>>>----.++++^^^^^^>>>>>>>---.+++^^^^^^^>>>>>>>.^^^^^^^>>>>>>----.++++^^^^^^>>>>>>+++.---^^^^^^>>>>>>>----.++++^^^^^^^>>>>>>----.++++^^^^^^>>>>>>+++.---^^^^^^>>>>>>>----.++++^^^^^^^>++.--^>>>>>>>>>>>>>>.^^^^^^^^^^^^^^>>>>>>>>>>>>>>++.--^^^^^^^^^^^^^^>>>>>>>>>>>>>+.-^^^^^^^^^^^^^>>>>>>>>>>>>>>--.++^^^^^^^^^^^^^^>>>>>>>>>>>>>>>----.++++^^^^^^^^^^^^^^^>>>>>>>>>>>>>--.++^^^^^^^^^^^^^>>>>.^^^^>>>>++.--^^^^>>>>>>>>.^^^^^^^^>>>>>>>>>>>>>---.+++^^^^^^^^^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>>>>>>.^^^^^^^^^^^^^>>>>>>>>>>>>>>-.+^^^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>---.+++^^^^^^^^>>>>++.--^^^^>>>>.^^^^>>>>>>+++.---^^^^^^>>>>>>++.--^^^^^^>>>>>>----.++++^^^^^^>>>>>>>---.+++^^^^^^^>>>>>>>.^^^^^^^>>>>>>----.++++^^^^^^>>>>>>>---.+++^^^^^^^>>>>>>>.^^^^^^^>++.--^>>>>>>>>>>>>>>.^^^^^^^^^^^^^^>>>>>>>>>>>>>>++.--^^^^^^^^^^^^^^>>>>>>>>>>>>>+.-^^^^^^^^^^^^^>>>>>>>>>>>>>>--.++^^^^^^^^^^^^^^>>>>>>>>>>>>>>>----.++++^^^^^^^^^^^^^^^>>>>>>>>>>>>>--.++^^^^^^^^^^^^^>>>>.^^^^>>>>++.--^^^^>>>>>>>>.^^^^^^^^>>>>>>>>>>>>>---.+++^^^^^^^^^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>>>>>>.^^^^^^^^^^^^^>>>>>>>>>>>>>>-.+^^^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>++.--^^^^>>>>.^^^^>>>>>>+++.---^^^^^^>>>>>>++.--^^^^^^>>>>>>----.++++^^^^^^>>>>>>>+.-^^^^^^^>>>>>>>-.+^^^^^^^.";
for(int i=1;i<e.length();i++){
if(i==1){
System.out.print("v");
}
else if(i%m==1&&i>1){
System.out.println();
System.out.println(">eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev");
System.out.println("v <");
System.out.print(" ");
}
System.out.print(e.charAt(i-1));
}
System.out.println();System.out.print(">eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeP");
}
}
```
**BotEngine program:**
```
v++++++++[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++>+++++++++++++>++++++
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
++++++++>+++++++++++++++>++++++++++++++++^^^^^^^^^^^^^^^^-]>>>>>>>>>>>>>>.^^^^^^^^^^^^^^>>>>>>>>>>>>>>++.--^^^^^^^^^^^^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^>>>>>>>>>>>>>+.-^^^^^^^^^^^^^>>>>>>>>>>>>>>--.++^^^^^^^^^^^^^^>>>>>>>>>>>>>>>----.++++^^^^^^^^^^^^^^^>>>>>>>>>>>>>--.++
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^^^^^^^^^^^>>>>.^^^^>>>>++.--^^^^>>>>>>>>.^^^^^^^^>>>>>>>>>>>>>---.+++^^^^^^^^^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>>>>>>>.^^^^^^^^^^^^^>>>>>>>>>>>>>>-.+^^^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>>>>>+.-^^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>---.+++
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^^^^^^>>>>>>>>>>>>>>>>--.++^^^^^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>--.++^^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.-
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
--^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>-
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
-.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>---.+++^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.++
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
+^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>++
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
+.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>--.++^^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.--
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
-^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>---.++
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
+^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^>>>>>>--.++^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>--.++^^^^^^>>>>++.--^^^^>>>>.^^^^>>>>>>+++.---^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^^>>>>>>++.--^^^^^^>>>>>>----.++++^^^^^^>>>>>>>---.+++^^^^^^^>>>>>>>.^^^^^^^>>>>>>----.++++^^^^^^>>>>>>>---.+++^^^^^^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>>>>>.^^^^^^^>>>>>>----.++++^^^^^^>>>>>>+++.---^^^^^^>>>>>>>----.++++^^^^^^^>>>>>>----.++++^^^^^^>>>>>>+++.---^^^^^^>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>>>----.++++^^^^^^^>++.--^>>>>>>>>>>>>>>.^^^^^^^^^^^^^^>>>>>>>>>>>>>>++.--^^^^^^^^^^^^^^>>>>>>>>>>>>>+.-^^^^^^^^^^^^^>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>>>>>>>>>>>--.++^^^^^^^^^^^^^^>>>>>>>>>>>>>>>----.++++^^^^^^^^^^^^^^^>>>>>>>>>>>>>--.++^^^^^^^^^^^^^>>>>.^^^^>>>>++.--
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^^>>>>>>>>.^^^^^^^^>>>>>>>>>>>>>---.+++^^^^^^^^^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>>>>>>.^^^^^^^^^^^^^>>>>>>>>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>>>>-.+^^^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>---.+++^^^^^^^^>>>>++.--^^^^>>>>.^^^^>>>>>>+++.---^^^^^^>>>>>>++.
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
--^^^^^^>>>>>>----.++++^^^^^^>>>>>>>---.+++^^^^^^^>>>>>>>.^^^^^^^>>>>>>----.++++^^^^^^>>>>>>>---.+++^^^^^^^>>>>>>>.^^^^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^>++.--^>>>>>>>>>>>>>>.^^^^^^^^^^^^^^>>>>>>>>>>>>>>++.--^^^^^^^^^^^^^^>>>>>>>>>>>>>+.-^^^^^^^^^^^^^>>>>>>>>>>>>>>--.++^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^^^^^^^^^^^>>>>>>>>>>>>>>>----.++++^^^^^^^^^^^^^^^>>>>>>>>>>>>>--.++^^^^^^^^^^^^^>>>>.^^^^>>>>++.--^^^^>>>>>>>>.^^^^^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^>>>>>>>>>>>>>---.+++^^^^^^^^^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>>>>>>.^^^^^^^^^^^^^>>>>>>>>>>>>>>-.+^^^^^^^^^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>++.--^^^^>>>>.^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeev
v <
^^>>>>>>+++.---^^^^^^>>>>>>++.--^^^^^^>>>>>>----.++++^^^^^^>>>>>>>+.-^^^^^^^>>>>>>>-.+^^^^^^^
>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeP
```
**Treehugger program:**
```
++++++++[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++>+++++++++++++>++++++++++++++>+++++++++++++++>++++++++++++++++^^^^^^^^^^^^^^^^-]>>>>>>>>>>>>>>.^^^^^^^^^^^^^^>>>>>>>>>>>>>>++.--^^^^^^^^^^^^^^>>>>>>>>>>>>>+.-^^^^^^^^^^^^^>>>>>>>>>>>>>>--.++^^^^^^^^^^^^^^>>>>>>>>>>>>>>>----.++++^^^^^^^^^^^^^^^>>>>>>>>>>>>>--.++^^^^^^^^^^^^^>>>>.^^^^>>>>++.--^^^^>>>>>>>>.^^^^^^^^>>>>>>>>>>>>>---.+++^^^^^^^^^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>>>>>>.^^^^^^^^^^^^^>>>>>>>>>>>>>>-.+^^^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>>>>>+.-^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>---.+++^^^^^^^^>>>>>>>>>>>>>>>>--.++^^^^^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>--.++^^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>>>>>>>+++.---^^^^^^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>>>>----.++++^^^^^^^^>>>>>>>>>>>>---.+++^^^^^^^^^^^^>>>>>>>>--.++^^^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>+++.---^^^^^>>>>>+++.---^^^^^>>>>>>--.++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>---.+++^^^^^^>>>>>>--.++^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>--.++^^^^^^>>>>++.--^^^^>>>>.^^^^>>>>>>+++.---^^^^^^>>>>>>++.--^^^^^^>>>>>>----.++++^^^^^^>>>>>>>---.+++^^^^^^^>>>>>>>.^^^^^^^>>>>>>----.++++^^^^^^>>>>>>>---.+++^^^^^^^>>>>>>>.^^^^^^^>>>>>>----.++++^^^^^^>>>>>>+++.---^^^^^^>>>>>>>----.++++^^^^^^^>>>>>>----.++++^^^^^^>>>>>>+++.---^^^^^^>>>>>>>----.++++^^^^^^^>++.--^>>>>>>>>>>>>>>.^^^^^^^^^^^^^^>>>>>>>>>>>>>>++.--^^^^^^^^^^^^^^>>>>>>>>>>>>>+.-^^^^^^^^^^^^^>>>>>>>>>>>>>>--.++^^^^^^^^^^^^^^>>>>>>>>>>>>>>>----.++++^^^^^^^^^^^^^^^>>>>>>>>>>>>>--.++^^^^^^^^^^^^^>>>>.^^^^>>>>++.--^^^^>>>>>>>>.^^^^^^^^>>>>>>>>>>>>>---.+++^^^^^^^^^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>>>>>>.^^^^^^^^^^^^^>>>>>>>>>>>>>>-.+^^^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>---.+++^^^^^^^^>>>>++.--^^^^>>>>.^^^^>>>>>>+++.---^^^^^^>>>>>>++.--^^^^^^>>>>>>----.++++^^^^^^>>>>>>>---.+++^^^^^^^>>>>>>>.^^^^^^^>>>>>>----.++++^^^^^^>>>>>>>---.+++^^^^^^^>>>>>>>.^^^^^^^>++.--^>>>>>>>>>>>>>>.^^^^^^^^^^^^^^>>>>>>>>>>>>>>++.--^^^^^^^^^^^^^^>>>>>>>>>>>>>+.-^^^^^^^^^^^^^>>>>>>>>>>>>>>--.++^^^^^^^^^^^^^^>>>>>>>>>>>>>>>----.++++^^^^^^^^^^^^^^^>>>>>>>>>>>>>--.++^^^^^^^^^^^^^>>>>.^^^^>>>>++.--^^^^>>>>>>>>.^^^^^^^^>>>>>>>>>>>>>---.+++^^^^^^^^^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>>>>>>>>>.^^^^^^^^^^^^^>>>>>>>>>>>>>>-.+^^^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>>---.+++^^^^^>>>>>>>>>>>>+++.---^^^^^^^^^^^^>>>>++.--^^^^>>>>.^^^^>>>>>>+++.---^^^^^^>>>>>>++.--^^^^^^>>>>>>----.++++^^^^^^>>>>>>>+.-^^^^^^^>>>>>>>-.+^^^^^^^.
```
**Loader program:**
```
printf "@echo%ca%c%c=~%c+[----->+++<]>++.++++++.[->+++++<]>+++.[--->++<]>+++.-----.---------.+++++++++++.+++[->+++<]>.--[--->+<]>-.++.+[--->+<]>.+++++++++++.-------.+++++++++++++.++.+[--->+<]>+.-.+[->++<]>..-[----->+<]>.++++.+[-->+<]>+++.++.-------.%c." 32,58,58,34,34
printf "@echo%c%c%c=" 32,58,58
printf "@echo%c%c" 32,97
```
**Batch program:**
```
@echo a::=~"+[----->+++<]>++.++++++.[->+++++<]>+++.[--->++<]>+++.-----.---------.+++++++++++.+++[->+++<]>.--[--->+<]>-.++.+[--->+<]>.+++++++++++.-------.+++++++++++++.++.+[--->+<]>+.-.+[->++<]>..-[----->+<]>.++++.+[-->+<]>+++.++.-------.".
@echo ::=
@echo a
```
**Thue program:**
```
a::=~"+[----->+++<]>++.++++++.[->+++++<]>+++.[--->++<]>+++.-----.---------.+++++++++++.+++[->+++<]>.--[--->+<]>-.++.+[--->+<]>.+++++++++++.-------.+++++++++++++.++.+[--->+<]>+.-.+[->++<]>..-[----->+<]>.++++.+[-->+<]>+++.++.-------.".
::=
a
```
**Microscript II program:**
```
"+[----->+++<]>++.++++++.[->+++++<]>+++.[--->++<]>+++.-----.---------.+++++++++++.+++[->+++<]>.--[--->+<]>-.++.+[--->+<]>.+++++++++++.-------.+++++++++++++.++.+[--->+<]>+.-.+[->++<]>..-[----->+<]>.++++.+[-->+<]>+++.++.-------.".
```
**BF program:**
```
+[----->+++<]>++.++++++.[->+++++<]>+++.[--->++<]>+++.-----.---------.+++++++++++.+++[->+++<]>.--[--->+<]>-.++.+[--->+<]>.+++++++++++.-------.+++++++++++++.++.+[--->+<]>+.-.+[->++<]>..-[----->+<]>.++++.+[-->+<]>+++.++.-------.
```
**ForceLang program:**
```
io.write "alert('PPCG')"
```
**Javascript program:**
```
alert('PPCG')
```
[Answer]
# Befunge (5 versions)
We start with the most recent version, **Befunge-109** (run with `cfunge -s 109`):
```
1k!!k@"1k!k@#;>@,k>'"'""r;@;"'"::''\"@_,#:>"'""\''::"'":''\"1j#@0"'""\'':"'":''\"::''\"'"::''\"GCPP"'""\'':"'":''\"::''\"'"::''\">:#,_@"'""\''::"'":''\"@j1A"'"::''\">:#,_@"'"";@r"'qk,@
```
Which outputs the following **Befunge-98** code ([Try it online!](http://befunge-98.tryitonline.net/#code=ckA7IkBfLCM6PiInIiJBMWpAIiciOjonJ1wiQF8sIzo+IiciIlwnJzo6IiciOicnXCJQUENHIiciIlwnJzo6IiciOicnXCIwQCNqMSInIjo6JydcIj46IyxfQCInIiI7QDtyIic+ayxAPjsjQGshazE&input=)):
```
r@;"@_,#:>"'""A1j@"'"::''\"@_,#:>"'""\''::"'":''\"PPCG"'""\''::"'":''\"0@#j1"'"::''\">:#,_@"'"";@;r"'>k,@>;#@k!k1
```
Which output the following **Befunge-97** code ([Try it online!](http://befunge-97-mtfi.tryitonline.net/#code=cjtAOyJAXywjOj4iJyIiMWojQDAiJyI6OicnXCJHQ1BQIiciOjonJ1wiPjojLF9AIiciIkBqMUEiPjojLF9A&input=)):
```
r;@;"@_,#:>"'""1j#@0"'"::''\"GCPP"'"::''\">:#,_@"'""@j1A">:#,_@
```
Which output the following **Befunge-96** code ([Try it online!](http://befunge-96-mtfi.tryitonline.net/#code=QTFqQCJAXywjOj4iJyIiUFBDRyInIiIwQCNqMSI+OiMsX0A&input=)):
```
A1j@"@_,#:>"'""PPCG"'""0@#j1">:#,_@
```
Which outputs the following **Befunge-93** ([Try it online!](http://befunge.tryitonline.net/#code=MWojQDAiR0NQUCI+OiMsX0A&input=)):
```
1j#@0"GCPP">:#,_@
```
Which outputs the string: `PPCG`
Each program will only run in the version of Befunge that it is targetting. If you try to run them in another version, they will exit immediately without outputting anything.
Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis), nearly all versions of Befunge are now available online at [TIO](https://tio.run/). The only exception is Befunge-109, for which you'll need *cfunge*, which can be found [here](https://sourceforge.net/projects/cfunge/).
[Answer]
# 11 languages, 536 bytes
## Bash -> Python 3 -> Go -> Lua -> Rust -> Java -> C99 -> Python 2 -> JavaScript -> Ruby -> Batch
### Bash:
```
e="echo -n "
p(){
eval "for i in {1..$1}
do
$e'\'
done"
}
$e'import sys;print("package main\nimport \"fmt\"\nfunc main() {fmt.Printf(\"if 1 == 1 then print(\\\"fn main() {let s='
p 7
$e'"public class Main{public static void main(String[] args){System.out.println('
p 15
$e'"#include <stdio.h>'
p 16
$e'nint main() {printf('
p 31
$e'"print '
p 63
$e"\"alert('puts "
p 128
$e"'@echo PPCG"
p 128
$e"'');"
p 63
$e'"'
p 31
$e'");}'
p 15
$e'");}}\\\\\\\";println!(\\\\\\\"{}\\\\\\\", s);}\\\") end\")}") if sys.version_info[0]==3 else exit()'
```
The `p` function reduces the code size by 497 bytes compared to typing all backslashes manually.
### Python 3:
```
import sys;print("package main\nimport \"fmt\"\nfunc main() {fmt.Printf(\"if 1 == 1 then print(\\\"fn main() {let s=\\\\\\\"public class Main{public static void main(String[] args){System.out.println(\\\\\\\\\\\\\\\"#include <stdio.h>\\\\\\\\\\\\\\\\nint main() {printf(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"print \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"alert('puts \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'@echo PPCG\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'');\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");}\\\\\\\\\\\\\\\");}}\\\\\\\";println!(\\\\\\\"{}\\\\\\\", s);}\\\") end\")}") if sys.version_info[0]==3 else exit()
```
The obligatory Python 2/3 differentiation.
### Go:
```
package main
import "fmt"
func main() {fmt.Printf("if 1 == 1 then print(\"fn main() {let s=\\\"public class Main{public static void main(String[] args){System.out.println(\\\\\\\"#include <stdio.h>\\\\\\\\nint main() {printf(\\\\\\\\\\\\\\\"print \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"alert('puts \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'@echo PPCG\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'');\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\");}\\\\\\\");}}\\\";println!(\\\"{}\\\", s);}\") end")}
```
### Lua:
```
if 1 == 1 then print("fn main() {let s=\"public class Main{public static void main(String[] args){System.out.println(\\\"#include <stdio.h>\\\\nint main() {printf(\\\\\\\"print \\\\\\\\\\\\\\\"alert('puts \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'@echo PPCG\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'');\\\\\\\\\\\\\\\"\\\\\\\");}\\\");}}\";println!(\"{}\", s);}") end
```
Using `if 1 == 1 then` prevents Python compatibility.
### Rust:
```
fn main() {let s="public class Main{public static void main(String[] args){System.out.println(\"#include <stdio.h>\\nint main() {printf(\\\"print \\\\\\\"alert('puts \\\\\\\\\\\\\\\\'@echo PPCG\\\\\\\\\\\\\\\\'');\\\\\\\"\\\");}\");}}";println!("{}", s);}
```
### Java:
```
public class Main{public static void main(String[] args){System.out.println("#include <stdio.h>\nint main() {printf(\"print \\\"alert('puts \\\\\\\\'@echo PPCG\\\\\\\\'');\\\"\");}");}}
```
### C99:
```
#include <stdio.h>
int main() {printf("print \"alert('puts \\\\'@echo PPCG\\\\'');\"");}
```
### Python 2:
```
print "alert('puts \\'@echo PPCG\\'');"
```
### JavaScript:
```
alert('puts \'@echo PPCG\'');
```
### Ruby:
```
puts '@echo PPCG'
```
### Batch:
```
@echo PPCG
```
[Answer]
# 11 languages (102 bytes)
I'm going to add more soon.
## Jelly -> Ruby -> ><> -> /// -> Batch -> Python 3 -> JavaScript -> J -> FOG -> Jolf -> Stacked
```
“puts <<q
/!/@ECHO print("""console.log(`'"a Lq5(80::13-:4+)#:out"X'`)""")/!~
/0v
>:1+$0g:'~'=?;o
q
```
Jelly ([Try it online!](https://tio.run/nexus/jelly#@/@oYU5BaUmxgo1NIZe@or6Dq7OHv0JBUWZeiYaSklJyfl5xfk6qXk5@ukaCulKigk@hqYaFgZWVobGulYm2prJVfmmJUoR6giZQsaa@Yh2XvkEZl4KCnZWhtopBupV6nbqtvXU@V@H//wA "Jelly – TIO Nexus")) outputs:
```
puts <<q
/!/@ECHO print("""console.log(`'"a Lq5(80::13-:4+)#:out"X'`)""")/!~
/0v
>:1+$0g:'~'=?;o
q
```
Ruby ([Try it online!](https://tio.run/nexus/ruby#@19QWlKsYGNTyKWvqO/g6uzhr1BQlJlXoqGkpJScn1ecn5Oql5OfrpGgrpSo4FNoqmFhYGVlaKxrZaKtqWyVX1qiFKGeoAlUrKmvWMelb1DGpaBgZ2WorWKQbqVep25rb53PVfj/PwA "Ruby – TIO Nexus")) outputs:
```
/!/@ECHO print("""console.log(`'"a Lq5(80::13-:4+)#:out"X'`)""")/!~
/0v
>:1+$0g:'~'=?;o
```
[><>](https://fishlanguage.com/playground) (use this interpreter; it outputs spaces instead of null bytes for spaces) outputs:
```
/!/@ECHO print("""console.log(`'"a Lq5(80::13-:4+)#:out"X'`)""")/!
```
/// ([Try it online!](https://tio.run/nexus/slashes#@6@vqO/g6uzhr1BQlJlXoqGkpJScn1ecn5Oql5OfrpGgrpSo4FNoqmFhYGVlaKxrZaKtqWyVX1qiFKGeoAlUrKmv@P8/AA "/// – TIO Nexus")) outputs:
```
@ECHO print("""console.log(`'"a Lq5(80::13-:4+)#:out"X'`)""")
```
Batch outputs:
```
print("""console.log(`'"a Lq5(80::13-:4+)#:out"X'`)""")
```
Python 3 ([Try it online!](https://tio.run/nexus/python3#@19QlJlXoqGkpJScn1ecn5Oql5OfrpGgrpSo4FNoqmFhYGVlaKxrZaKtqWyVX1qiFKGeoAlUrPn/PwA "Python 3 – TIO Nexus")) outputs:
```
console.log(`'"a Lq5(80::13-:4+)#:out"X'`)
```
JavaScript ([Try it online!](https://tio.run/nexus/javascript-node#@5@cn1ecn5Oql5OfrpGgrpSo4FNoqmFhYGVlaKxrZaKtqWyVX1qiFKGeoPn/PwA "JavaScript (Node.js) – TIO Nexus")) outputs:
```
'"a Lq5(80::13-:4+)#:out"X'
```
J ([Try it online!](https://tio.run/nexus/j#S03OyFdQ0lPwcVPQ1atTMFCwUjD4r66UqOBTaKphYWBlZWisa2WiralslV9aohSh/l/zPwA "J – TIO Nexus")—only an approximation) yields:
```
"a Lq5(80::13-:4+)#:out"X
```
[FOG](https://github.com/RikerW/Fuzzy-Octo-Guacamole/issues) prints:
```
a Lq5(80::13-:4+)#:out
```
Jolf ([Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=YSBMcTUoODA6OjEzLTo0KykjOm91dA)) outputs:
```
(80::13-:4+)#:out
```
Finally, Stacked ([Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html)) outputs:
```
PPCG
```
[Answer]
# Windows Batch -> [Powershell](http://%C2%B4https://tio.run/nexus/powershell#@19elFmSqpuRX1yi4KDEVVBaUqxgY1PBVVCUmVeioaSklJiTWlSikVBQlJ9bUKKgrhQQ4OyupJ6gCZTS5KrgUnL4/x8A) -> [Ruby](https://tio.run/nexus/ruby#@19QWlKsYGNTwVVQlJlXoqGkpJSYk1pUopFQUJSfW1CioK4UEODsrqSeoAmU0uSq@P8fAA) -> [Python 3](https://tio.run/nexus/python3#@19QlJlXoqGkpJSYk1pUopFQUJSfW1CioK4UEODsrqSeoAmU0vz/HwA) -> JavaScript -> SQL -> [CJam](https://tio.run/nexus/cjam#@68UEODsrvT/PwA): 7 languages
## Windows Batch
```
@echo @"
@echo puts <<x
@echo print("""alert(`prompt '"PPCG"'`)""")
@echo x
@echo "@
```
## [Powershell](http://%C2%B4https://tio.run/nexus/powershell#@19elFmSqpuRX1yi4KDEVVBaUqxgY1PBVVCUmVeioaSklJiTWlSikVBQlJ9bUKKgrhQQ4OyupJ6gCZTS5KrgUnL4/x8A)
```
@"
puts <<x
print("""alert(`prompt '"PPCG"'`)""")
x
"@
```
## [Ruby](https://tio.run/nexus/ruby#@19QWlKsYGNTwVVQlJlXoqGkpJSYk1pUopFQUJSfW1CioK4UEODsrqSeoAmU0uSq@P8fAA)
```
puts <<x
print("""alert(`prompt '"PPCG"'`)""")
x
```
## [Python 3](https://tio.run/nexus/python3#@19QlJlXoqGkpJSYk1pUopFQUJSfW1CioK4UEODsrqSeoAmU0vz/HwA)
```
print("""alert(`prompt '"PPCG"'`)""")
```
## JavaScript
```
alert(`prompt '"PPCG"'`)
```
## SQL
```
prompt '"PPCG"'
```
## [CJam](https://tio.run/nexus/cjam#@68UEODsrvT/PwA)
```
"PPCG"
```
[Answer]
## [///](https://tio.run/nexus/slashes#@6@fpP@oYU6iflJOalGJhlJxak5qcol6QJCnX0iMkr1DQICze0KMkrqS5v//AA) to [Jelly](https://tio.run/nexus/jelly#@/@oYU5iTmpRiYZScWpOanKJekCQp1@Ikr1DQICze4KSupLm////AQ) to Javascript to MS-SQL to QBasic to QBIC, 39 bytes, 6 languages
```
/b/“a/blert("select'PRINT\"?@PPCG`\"'")
```
Explanation:
```
/// Replaces the one 'b' with '“a', returns
“alert("select'PRINT\"?@PPCG`\"'")
Jelly just sees everything as a string literal and prints it (shamelessly stole this trick from @ConoroBrien)
alert("select'PRINT\"?@PPCG`\"'")
Javascript posts this in a dialog window:
select'PRINT"?@PPCG`"'
MSSQL then selects:
PRINT"?@PPCG`"'")
QBasic puts this on the screen:
?@PPCG`
QBIC then prints 'PPCG'
```
QBIC and QBasic have many similarities. However, these lines of code are not cross-compatible: QBasic accepts the `?` as shorthand for `PRINT`, but does not know what to do with the `@` and the backtick. QBIC will interpret the `PRINT` line as a reference to 5 different string variables and `P$R$I$N$T$` is not a valid statement.
[Answer]
# 9 languages: Processing -> Java -> C -> Python 3 -> JavaScript (ES6) -> Octave -> Bash -> sed -> V, 160 bytes
```
print("class A{public static void main(String[]a){System.out.print(\"main(){printf(\\\"print(\\\\\\\"alert`disp('echo s/.*/iPPCG/')`\\\\\\\")#\\\");}\");}}");//
```
Right now my objective is to find and add languages where I don't need to escape quotes and stuff.
Processing outputs (note that the the Java program doesn't run in Processing and vice-versa)
```
class A{public static void main(String[]a){System.out.print("main(){printf(\"print(\\\"alert`disp('echo s/.*/iPPCG/')`\\\")#\");}");}}
```
Java outputs:
```
main(){printf("print(\"alert`disp('echo s/.*/iPPCG/')`\")#");}
```
C outputs:
```
print("alert`disp('echo s/.*/iPPCG/')`")#
```
Python 3 (note that the python program won't work in Processing because of the comment and vice-versa) outputs:
```
alert`disp('echo s/.*/iPPCG/')`
```
JavaScript outputs:
```
disp('echo s/.*/iPPCG/')
```
Octave outputs:
```
echo s/.*/iPPCG/
```
Bash outputs:
```
s/.*/iPPCG/
```
sed outputs:
```
iPPCG
```
V outputs:
[`PPCG`](https://tio.run/nexus/v#@58ZEODs/v8/AA)
[Answer]
# Jelly -> kavod -> BrainF\*\*\* -> PostScript -> Elixir -> Python 3 -> Haskell -> Haystack -> MY
Score - ~~4 5 6~~ 9
~~All~~ Almost all of these languages were chosen randomly.
I tried figuring out how to print something in the randomly chosen language unless:
1. I *really* didn’t want to do it,
2. It broke the rules,
3. It had bad documentation
End result (after a lot of going back and forth and back and forth):
```
“7Äỵ\T^HẈȮ⁺y?ƤṚÄȦṇŻ%ẠṠḄ®ọ?Ḥñ2XBBaȮÄȤ3ḃɗ¤ȧ:6Ẇİ/'ȯḅvịĊḥṬƬ¤]9½ỌỊf£x⁼ḃƑz@ỴiŒQƒ[Ḥḅ⁽d'ẉ'IiƒnP^j]ṂX8æ6ḣṢż¥ƈżḅ⁻0@dñ0ṡhṖ¹'¤5Ɠ6Ḍ×Q7ʂḣṚȤ)ẇ+ñ\ȮG$§Ḍ©M2ż°Q⁵)gŻCHḅWṃuḢ"h.ÐeṡḳƊkjĖẠ<ṣ⁸⁽ƭ¡(ĖZ,ḅẇr⁸J¡Sẹ⁼vĊƒ4ẋRuİ< ɦ¢DH#ḄrsßṆṇẊịȧṂ\ṀþTtkẠṙẉƘyƝƭĿ€hX¢ṅṣøɲbẆ>Ḋ]ẸN/ÐẒṭdṡÄѰĠ'-Ɓ&+ñȥUC-ƈ&Xỵ-ṚṾȧḋGẎcḥpḷị2ç¡ŀ7⁻ṁŻ0ḃƇ"Ċ Ṛɲịɠ9ẋ¿°ɓĿȯ^?_aß{ċK)ĠƑ^F½:¶ñFṛ2ɦ,ṭFT|dJɦȤẇ×jṭ⁻Ẹð8SCḃ⁼ⱮŀẸṙ⁺¶ḟṪbOḲ")^0ḣ7Ç7ȷẒʋQlḣ*ṡḢçĿ×{ḤẎʠṠṙieBȦyṃŻȷ8dẋiʋⱮ{ƭœŀ1ḣẉfw=w⁾ġṭ¬ ĿƁ*}⁼£ƤḊ⁶Ḃ;ɓ¥z÷µ}ḟM¿PẈ³y>A8ɼ½Ỵ[3IṁPẈ²Ḍṫ+ḣ ƤẈuxGḣȷƑḤŻċ⁼½XŻƇṀÑ9ṡ²"ỊẆj¥<Ọḃ⁸^ȮȥƓȯḌ<ĖẋẈė`Ẉy!=yḂṫẆæṇCQȷ°ḍ15(Ḟ³eọ¿ßẏJṭhœẆɓb4¿-Ṗ5>ç⁽?§>⁽fU8xlŻ,^ṣƒ@)Bị⁺cÑŻ²¡ṚƤ?ḣ&1yƁŻWÇut-ẒḂ5mṖḃŒṇ⁼ƙNḅẏḌṢḢṇṂİUþı¶5?Ḍḃı#¶©ḅGḋDṂȧṣɠḷ(%a_ʂ?_°=©⁷⁻⁼⁹×Ẏ¶@'ẒȮuȤrÆỊɱ⁼3ẹṪ¬ȥjɼ®Ṃ⁶O$ʂḌḍṠȷRʋȥ1\ġ÷ⱮṢėµḣṆḲṡḄ&⁶⁾Ṅi²ẈẉṛÐḞ⁹⁷"iṁṬñŀ,Ġc⁸fŻİċµ^ȤṠ2ß⁷ñBȥɼ>ÐV÷ṛ5ḅḃẠƙṣbɱCạṇṅṬ>Aø0ẏMẆṾƘIʋỤBIɠJṘ÷ṁḟȤkẹ)ġo8[ʠṂ²ḷ+§ḲP5Ɲu&ðß .ṇɓẠHỵ`ġÐJ©4(\ỴmZḃæ,ẸÄN(ẋṾ'!ð%ÐB#.d~IQ½N>°Ṙw£ḋ~-¢zƤḷḅBṃo5Ạŀ¢væḳBı€÷ạİ Vṫ⁻`ðßoĊŻBqƙPɠḶ_3ȤAŀ⁾ḄƝOM'ḄṢ⁶H,ḥ%ṙt¡ĿịƊ@ƤwƘ$*żḢGżĊ5ẓ⁷ẉ%°ŀḌWẈṣṾịÐxEėkḄh⁺dnð⁻ȯ(EÐŀ⁷.MṣⱮỊ⁹ḃœÐṄ%a¢F¡ṅ,ṆFѲḂ#ÐƓ'F3`Ȧ4SȤṭḋṢṖ-æʂ'ÄƁḞBṁ7øæỌFjẈTṣLtÑḞɦ½NḅḤƭVvİigPæÄ²ʂIẠẆdƬrạ⁸3ÇḤĊ.5%=TrĿẉḤḤ.Ȥ?©A7HġṆ6¹ÄṀ.ḋWṭ"B⁺ʋrñyS²ẏẆÐɦ§Ỵ?ṃjɱɼİXȥ\ṭ$Q¿¦ṭr⁹ækẏḞ2Ñ¥ÑṚ-wḋyƇȮḋḟƭ°£V£#cṁṪÑḞƙ4=AGĠ`ʂsƁÑȤ|⁴ɦġƬḟEÑ&ḃƊġ1ȤbṠ(5lḟ'C¿⁻DḌṚṭ®İċƈġ|Ṁ¢ẎĠ!³hɓ@ṭ7dW⁸Ỵʂƥ_ƒḋẋẸg,ʠS>ẒẉẓɦkĖỌ[ỵwÞdṪḂÑɱṅÞoḶṚṙ¹ị¦Ċ`Ṅ⁷¿Ḣ6c\Ƈ€açb½@HŒẏṾⱮ/]ḊḲṙ[/ı^ȤḷClAọẒZÑPƭƬmṣ Ba_¤Ẹ⁴Ḳ⁵hqÞ<⁵ṖṂ,ṪḊṾCB⁵ḋẇɲḢ]h@*?NLṁṾṚṆƭƑḞṁHẠḥ⁵ḍ^(,c³wÆç2Q/sGƤEt¬ȥÞ!Ƒ;gsṗṭɗḲzaeḍ7_Þ5ɲạṣẇNƲPøzĠɲ¢vỤȷ³qẎqḳẆıYṆȧ£⁽Ḅɦḟ31ẉỊ2µÑɲẎƙ;XĿØ=Kṁ÷oṭGŻʋẎðƘ°.}¬.®Ḳ[N_ẇrḂḂṡɲĠȥ1ẆĊ>§ÆœƓḃɗẒḄ÷µẈ¬þaḷ<ɗⱮʠỴƘU=.½@ṇQ:¹ØȯƝøaÐȤⱮÆƈN64Ṣṙ3ạĠṛ€QȤyıṖ0|ẠdƊɼuṪ"Ɱ)ḄyẉHẎḅ©Ṙ⁺ẹ5FɗµiȧĿṾ@ẹÇ£}5Aw⁷Tỵ^ḃlĿṇØṁĠ®Za½ėḥḥ²ṖⱮ7ßẋpḅỵI¹uọȥW6H¥qṂ#⁽Ḣ=Ʋ¿ɗỌJḃgM§"m⁾Ḣ!IuƒIn%H>[pẠgI$ẠPıTuKa,ƙƇ0¬ȧ÷=⁷aṪƇṙɲṀ°ṙṡa;]³²,\ẇUPl$¬SỊỴọÄ$×:@ṢZ!³O⁻rnṭBṠṾṆøɲṡ⁶&c½;⁴¢ėḞⱮ;ı⁻ĠÞœz⁽%⁶P÷Ṛḷ{Ññɠḟµ4¢ṣuı,¬ʠkẆḷUbḋɗḳHẏṾẓgsç76ƥ.ỌṁọḄU⁼ı*þạ½DE*ḷuœṬʠż~¢⁵Øɓȧ5ỊḲƓðƝƇÑ¥İcḥỴƈ&®Ẏỵ§4T¹ƥIÐkjI×?fFĿ#⁼JL)7ḅṁ&,hṄŀwßƈḂɱⱮX⁸6§⁺+(hɲ|Q€rɦẏ¢oḳ= ḳṭẉḋ\ỊMwĖṡ'Ȧ"Ƥ[⁹⁷ṚþṄzoỊẋ¹ɱɗVɓẋ5ġç¢ɲƙFÆDȯ5⁷Ạ|®HÑ*uPþṣ⁺ḟṗG)ḍvT¹/aỴƊʂṪ¡ÞER'œḢøŒẒ1w^ṀṀ|⁼¥ Ƒ3n³Ḍƭ⁾ị⁸IŒḊ¶ŻĿ²¶}⁼ṙBỌ{h.ɱœṚ"^Ẉɲ7+ċ.\ṙŀb+ġÄṬƁiFṄỤṾMÑƲṂ¬¢ṙoẈmƬ2°;®ṄqḢgḢġɱƇıọẒk⁹g$ẎɼƲ⁻Deç®⁻µḂẉAƁ¬PṬ¤Ṙịǹ#pɗ⁾œỵ(ȥ⁶⁻xė#ĿL1ė:¢&¢İLẇØṙHNṃƭƥ%³,1QV¡y⁺³1ḥċhbḣḳṂȯZM(ƇNØ®%LṂ:z=æØyNÇƤṗḲñ¢E⁵XŻ6ðO3ṃ⁸Ṣƥ|w_¶Ṅ¬&ṁ⁺ḷİṚ(ṙċƬƙæ4Ƈƈḳ0ỤȦḥ¥nɱ®®ß⁺Qwḷ!⁹k⁵×£ɼ¢ÆọMẆ¹ȷ⁹;dÞŻỴ:ṙµɼt)NWɲ&øɗ^ỵƑ.$ḷṬv¶ẇỤḊṙ¥¦^tQṅṆṫµḅeaɠ&#ḌÞAṢzÑ%dƝƭ¬ı2ÄƲṄḞ©¡⁾}ɦQzȮxḃ7Ɠ»
```
---
## Jelly (New!)
```
“7Äỵ\T^HẈȮ⁺y?ƤṚÄȦṇŻ%ẠṠḄ®ọ?Ḥñ2XBBaȮÄȤ3ḃɗ¤ȧ:6Ẇİ/'ȯḅvịĊḥṬƬ¤]9½ỌỊf£x⁼ḃƑz@ỴiŒQƒ[Ḥḅ⁽d'ẉ'IiƒnP^j]ṂX8æ6ḣṢż¥ƈżḅ⁻0@dñ0ṡhṖ¹'¤5Ɠ6Ḍ×Q7ʂḣṚȤ)ẇ+ñ\ȮG$§Ḍ©M2ż°Q⁵)gŻCHḅWṃuḢ"h.ÐeṡḳƊkjĖẠ<ṣ⁸⁽ƭ¡(ĖZ,ḅẇr⁸J¡Sẹ⁼vĊƒ4ẋRuİ< ɦ¢DH#ḄrsßṆṇẊịȧṂ\ṀþTtkẠṙẉƘyƝƭĿ€hX¢ṅṣøɲbẆ>Ḋ]ẸN/ÐẒṭdṡÄѰĠ'-Ɓ&+ñȥUC-ƈ&Xỵ-ṚṾȧḋGẎcḥpḷị2ç¡ŀ7⁻ṁŻ0ḃƇ"Ċ Ṛɲịɠ9ẋ¿°ɓĿȯ^?_aß{ċK)ĠƑ^F½:¶ñFṛ2ɦ,ṭFT|dJɦȤẇ×jṭ⁻Ẹð8SCḃ⁼ⱮŀẸṙ⁺¶ḟṪbOḲ")^0ḣ7Ç7ȷẒʋQlḣ*ṡḢçĿ×{ḤẎʠṠṙieBȦyṃŻȷ8dẋiʋⱮ{ƭœŀ1ḣẉfw=w⁾ġṭ¬ ĿƁ*}⁼£ƤḊ⁶Ḃ;ɓ¥z÷µ}ḟM¿PẈ³y>A8ɼ½Ỵ[3IṁPẈ²Ḍṫ+ḣ ƤẈuxGḣȷƑḤŻċ⁼½XŻƇṀÑ9ṡ²"ỊẆj¥<Ọḃ⁸^ȮȥƓȯḌ<ĖẋẈė`Ẉy!=yḂṫẆæṇCQȷ°ḍ15(Ḟ³eọ¿ßẏJṭhœẆɓb4¿-Ṗ5>ç⁽?§>⁽fU8xlŻ,^ṣƒ@)Bị⁺cÑŻ²¡ṚƤ?ḣ&1yƁŻWÇut-ẒḂ5mṖḃŒṇ⁼ƙNḅẏḌṢḢṇṂİUþı¶5?Ḍḃı#¶©ḅGḋDṂȧṣɠḷ(%a_ʂ?_°=©⁷⁻⁼⁹×Ẏ¶@'ẒȮuȤrÆỊɱ⁼3ẹṪ¬ȥjɼ®Ṃ⁶O$ʂḌḍṠȷRʋȥ1\ġ÷ⱮṢėµḣṆḲṡḄ&⁶⁾Ṅi²ẈẉṛÐḞ⁹⁷"iṁṬñŀ,Ġc⁸fŻİċµ^ȤṠ2ß⁷ñBȥɼ>ÐV÷ṛ5ḅḃẠƙṣbɱCạṇṅṬ>Aø0ẏMẆṾƘIʋỤBIɠJṘ÷ṁḟȤkẹ)ġo8[ʠṂ²ḷ+§ḲP5Ɲu&ðß .ṇɓẠHỵ`ġÐJ©4(\ỴmZḃæ,ẸÄN(ẋṾ'!ð%ÐB#.d~IQ½N>°Ṙw£ḋ~-¢zƤḷḅBṃo5Ạŀ¢væḳBı€÷ạİ Vṫ⁻`ðßoĊŻBqƙPɠḶ_3ȤAŀ⁾ḄƝOM'ḄṢ⁶H,ḥ%ṙt¡ĿịƊ@ƤwƘ$*żḢGżĊ5ẓ⁷ẉ%°ŀḌWẈṣṾịÐxEėkḄh⁺dnð⁻ȯ(EÐŀ⁷.MṣⱮỊ⁹ḃœÐṄ%a¢F¡ṅ,ṆFѲḂ#ÐƓ'F3`Ȧ4SȤṭḋṢṖ-æʂ'ÄƁḞBṁ7øæỌFjẈTṣLtÑḞɦ½NḅḤƭVvİigPæÄ²ʂIẠẆdƬrạ⁸3ÇḤĊ.5%=TrĿẉḤḤ.Ȥ?©A7HġṆ6¹ÄṀ.ḋWṭ"B⁺ʋrñyS²ẏẆÐɦ§Ỵ?ṃjɱɼİXȥ\ṭ$Q¿¦ṭr⁹ækẏḞ2Ñ¥ÑṚ-wḋyƇȮḋḟƭ°£V£#cṁṪÑḞƙ4=AGĠ`ʂsƁÑȤ|⁴ɦġƬḟEÑ&ḃƊġ1ȤbṠ(5lḟ'C¿⁻DḌṚṭ®İċƈġ|Ṁ¢ẎĠ!³hɓ@ṭ7dW⁸Ỵʂƥ_ƒḋẋẸg,ʠS>ẒẉẓɦkĖỌ[ỵwÞdṪḂÑɱṅÞoḶṚṙ¹ị¦Ċ`Ṅ⁷¿Ḣ6c\Ƈ€açb½@HŒẏṾⱮ/]ḊḲṙ[/ı^ȤḷClAọẒZÑPƭƬmṣ Ba_¤Ẹ⁴Ḳ⁵hqÞ<⁵ṖṂ,ṪḊṾCB⁵ḋẇɲḢ]h@*?NLṁṾṚṆƭƑḞṁHẠḥ⁵ḍ^(,c³wÆç2Q/sGƤEt¬ȥÞ!Ƒ;gsṗṭɗḲzaeḍ7_Þ5ɲạṣẇNƲPøzĠɲ¢vỤȷ³qẎqḳẆıYṆȧ£⁽Ḅɦḟ31ẉỊ2µÑɲẎƙ;XĿØ=Kṁ÷oṭGŻʋẎðƘ°.}¬.®Ḳ[N_ẇrḂḂṡɲĠȥ1ẆĊ>§ÆœƓḃɗẒḄ÷µẈ¬þaḷ<ɗⱮʠỴƘU=.½@ṇQ:¹ØȯƝøaÐȤⱮÆƈN64Ṣṙ3ạĠṛ€QȤyıṖ0|ẠdƊɼuṪ"Ɱ)ḄyẉHẎḅ©Ṙ⁺ẹ5FɗµiȧĿṾ@ẹÇ£}5Aw⁷Tỵ^ḃlĿṇØṁĠ®Za½ėḥḥ²ṖⱮ7ßẋpḅỵI¹uọȥW6H¥qṂ#⁽Ḣ=Ʋ¿ɗỌJḃgM§"m⁾Ḣ!IuƒIn%H>[pẠgI$ẠPıTuKa,ƙƇ0¬ȧ÷=⁷aṪƇṙɲṀ°ṙṡa;]³²,\ẇUPl$¬SỊỴọÄ$×:@ṢZ!³O⁻rnṭBṠṾṆøɲṡ⁶&c½;⁴¢ėḞⱮ;ı⁻ĠÞœz⁽%⁶P÷Ṛḷ{Ññɠḟµ4¢ṣuı,¬ʠkẆḷUbḋɗḳHẏṾẓgsç76ƥ.ỌṁọḄU⁼ı*þạ½DE*ḷuœṬʠż~¢⁵Øɓȧ5ỊḲƓðƝƇÑ¥İcḥỴƈ&®Ẏỵ§4T¹ƥIÐkjI×?fFĿ#⁼JL)7ḅṁ&,hṄŀwßƈḂɱⱮX⁸6§⁺+(hɲ|Q€rɦẏ¢oḳ= ḳṭẉḋ\ỊMwĖṡ'Ȧ"Ƥ[⁹⁷ṚþṄzoỊẋ¹ɱɗVɓẋ5ġç¢ɲƙFÆDȯ5⁷Ạ|®HÑ*uPþṣ⁺ḟṗG)ḍvT¹/aỴƊʂṪ¡ÞER'œḢøŒẒ1w^ṀṀ|⁼¥ Ƒ3n³Ḍƭ⁾ị⁸IŒḊ¶ŻĿ²¶}⁼ṙBỌ{h.ɱœṚ"^Ẉɲ7+ċ.\ṙŀb+ġÄṬƁiFṄỤṾMÑƲṂ¬¢ṙoẈmƬ2°;®ṄqḢgḢġɱƇıọẒk⁹g$ẎɼƲ⁻Deç®⁻µḂẉAƁ¬PṬ¤Ṙịǹ#pɗ⁾œỵ(ȥ⁶⁻xė#ĿL1ė:¢&¢İLẇØṙHNṃƭƥ%³,1QV¡y⁺³1ḥċhbḣḳṂȯZM(ƇNØ®%LṂ:z=æØyNÇƤṗḲñ¢E⁵XŻ6ðO3ṃ⁸Ṣƥ|w_¶Ṅ¬&ṁ⁺ḷİṚ(ṙċƬƙæ4Ƈƈḳ0ỤȦḥ¥nɱ®®ß⁺Qwḷ!⁹k⁵×£ɼ¢ÆọMẆ¹ȷ⁹;dÞŻỴ:ṙµɼt)NWɲ&øɗ^ỵƑ.$ḷṬv¶ẇỤḊṙ¥¦^tQṅṆṫµḅeaɠ&#ḌÞAṢzÑ%dƝƭ¬ı2ÄƲṄḞ©¡⁾}ɦQzȮxḃ7Ɠ»
```
[TIO](https://tio.run/##JVcJUxPZFv4ryI4iyhJwRHZlcQRhROWJgizK5ooigjhFYiRMgkpIlSG8JyQhSzkTYhKEdKdZqu7t3OrmXzR/xPednioFTe5yzvmWc@7koydP5n79Ol38Xw23G8re/d6BdiOzrMVPrZm5BhEy5A1u1yKG7MgqBUbGb8h@Q7KzuKF8ajCkEE9W9DU3D2lxLApVGtIH3ctCWvRytZFZUhMXirQfhvTxjaG4VKchhQ05JmIs9OA3dmgoK4bifMy2355aD7BPuOcbDeXnRHatR6z142TsO7UejhYZmb@KOibE2rPugckHhmzru8Qj1Ya0bcjB7AELi@XsgblUudg4ypMXDTkwbshfmVzEQhbhwcoV7u2pObGZWza0UImRcZzjyftavC2fRfE1@95ZgZMSPafWvZKxrNLSjvPuGvKHGUMK5o6X8dVHONSQdoVzalL9ihpcMeTtU6uE8MQOCxSrX@@VYgvOncan11nglpGRkdUb1SnWqoyM648ZNXElR4@w4NX2PFRv@hXfMuQl1NTIOFEbLYq87hvyIj/qfT1lFtmHtMX6nPgmdtTjU1tsvI8FDfkjLuaSnhpGdesNyfnAyEhdF/iqkVkz5J1RhMnt3M0Sqr/ovLAWIk0tfLvlvFgu7AO055G/IR/hNsnVZmQ@jwCRF4aURgQVPMoC2cUalNGQrVnlIiHiyFWdOdijp7BC9/@GTNgxS@ge9Vj7MdAwOMS33qmu30tUv3APtLLDy2yfJ1sN@b8VeqQU8bT2Loxe1yNaCJXh3kl8QsdnJJ64dKsFF6BEp8l4dhEfIWHwje0bEgrz9/BNQ0rllgwgiu0a7qjR0kjwxNXzBP8/a2IR5FH1mHvfEU8yn09MVsq@iUfNWmQOyGUVLX1pFPFOnLhwxTuxk/VkF8uJApm/Hs/WzZ5aj9QAAmKxHPVYWM@@RyxsG2yXnKdWRGGr1T0sPM/TbO89Yupkx90QBdudq2@6pB8Qe3/2V3agVObHKbDIkP85h/NzcEZmeeZtG/6tpYUbAWYV1UXHH/ZlFeEglN2/IQmWyoUAAOQkC18hNVBBpAEtroWFh2SzcoXI5sJxqvchfs6dqZtDZLgImzgpsqVHS7OEIX0qtxQb0ibbfQRVsmOQK/PlOrIbz3qwVPcMV7FjgP/VUs@jIG0Di9bj1@Pbl94@ySqlAyCVWGssaQbKAGGEu7MKSzGUZ0OEoPHtwvI5AU7c5Y6Z1@eJapLN8hTHIeIseOdAcsLXZSrgi1mJIAAicss2NXGbH6lJtm9poG@kD2oyj@2z71iMCrmuYgmRf1uHqaSLC4YGT2wNgyxRx76fWtNgC1HEKnMvQGb7jfCCNS0@o4Wm@RJqpyfxdSW0BsqwmBaeBDJxnAgEb@aT4HHhJzBDS/9x4tLC5ffVAE@DDghQ9bI90xCWwDSTUfZCbAMtDNk@AUAzy2AKqAxtSZsIAeHkTgBvOBhPZhdLVf8I0HoMbBOqi@0NgOSyv4JvYR1PNmth/aCer97haRxhocpIHyBr4UOqw3qyxcgEzPpAz7H6Ji5dROU6ARXUKdY7TlyGEmru0P3AcJ2OsIKCWgjGIJeogeeX@onvNmJd@hw5WKrbIr7NFPIE38opw7k6UPe3Q/APkfDqdfa9qvg@CPv0HqLgUCYUaO8qJmrJR0VneKKArzbnlY3@2dHDDrvqQSh5fZZtA54/z7PgPIkijRSaoavnFpycXWTBN@CftNusJmFNiDATUBM5d8BMQPaQ4niuOrNK80vh6yZk9wcrtVBTdpHKK9nFt5udRfgNGFDydlhnuADifc0C6jEoKJyNIjQr1vPPkrEH27IHqhPXelBZQFLAEjAMaeUuISQDwCNs4atvr6neKZw5DgKPPuMJxKH9KL7GV@nSdFknGTaAV6BumWjrAa6yvWCIBVuJ6B9hV0utcE7U1JbHV4WnqLXyoRapukW47qAURGr563keObEVcbsAIpsoiLWGS6iEstI6iXh6ccuN1xya34TXH5qKkEJi584bNTEx1s0j3M5SJ7YOMvjM0qiITaNwYFEld2Cd6iyzFNT1TqMIYB71v1CZFmpg35tq2smrlqqZjA4tL5YhHLSnndxmJHvimubJuVvE2C9kC6u4OQqwG4DWpJ7UD9REnxZGb9nJ74F5wzV2pklRkSlTrJsVSDqMkOWN87M4d044tDilK22htSXY9h22nTdi8v5vMzHhq6pralP9D09sr4SVu7XQwqn1px5RAyKGTde4u5Bah1MNlGuhYWii2ALX3ipqYcfA5KppDxtkvHESjlhWAwtICb0t81n1n2G747qnEV/XjN5FYZDHiU2EB8UahURWKI2Vnvhv1ZMJoUgZjx6ZgkkqK/1g@yzfRAf8Gwhyt54EqHzzObhn3udjMnjCIqrzIXAHJdgxuFU9cl84wOAhHh1mh43tcDMURT4CVS48QCswvcHXf0FNkr6ldMuTJhgsLr/H3d1iR8Tggts5zUODDKaPceAnNmCIGH/JN6/gN1mkbCs1Y3Li2JZm@pAycaClSsEH441nG7pumNU9MsNcwqFUZXzUTiyRwuaOTwPFpSNsd5Yv8WhFz4VXbSJ07TU5Ht88I9y1Y68M2Yui6V7cPz/0CBtqBvmmBZeQz6DnObpEqptL86pfT0G8sBc0jt2XKPpLyJhGteR/cLsWZZhrDqEjHfLeqiynIivOCraHiuKwz8JX24e@u173OyLk6ee4tC2rwK8yn3lCrLNE2XsWK4MJS6n@rkEaiKhhUc8K6CnVDw@mu5z1LMqXsh7hMedFs6PYqdVSL43xoyGU@oruBQowOuWnWL9dVwZ44Gw9l6GBde2H@MalIb6qhbCGL4nlruoqU6C@SrIiuON/gWqPFppTwYOvFxdQy1Hh1A9mgEUu9pTgwjkkhyJ/hkrRj@R1iAkGa2nFALs3oWG8ACiN@IQ72PZ7SxNGhnQvWDaAmJ/Qlw6@jiKofha/N8QOVS@Nt1IYQpS/4oYaasKuF2QByl4Hk2dAHC18t7qdhV@CFHlmmYN1fAmd9hg1UFau4@CxThbNfWraZPBMx4xY63hW0F7f/wLxj3Xk42e3muyd@X2oVPiE4yIYEOXpOgQ2hLxotPABJagpQfOjHBiqfcB2War0PoC43f0kn8Vu0cSh/EQs3J7PvZdR0@A9qO4mtDn9DGg2m4MUyLhEYybOgEMXjrDDWpCbBSnJTSRXC9@3Kqqfb2Y988ikAKu6qVFtALl33M2T5PpbbK@KhtbtGTVZymIn/inqcFL69jA0QFzdbf9XbtDx2CserakW4TIahKAHqEyy30Z7V5NnORYE2OHVa2exeQYjjYyzsgd/MrSPPb6ue7SohfKSUsIDFn4TDvI0NUHjLdFnuRCEBM7KHotW9TJZhDv46tRkB/c2PG5VjwHFwfUbJTUElWwtLMXrwZ5dnOVbYhnMxYyRjPfBi6oZRqfMueJxPbXQA3ZNQyKZLywIi9mtyyEVoU@QcbvQa52ds7AlOVCkRXJFqP/f@YFeUjRezD835z4Xk@HP3jvUrV0WdOooC@op4WvlS1e1Hxaz3fkXWLydu8/OdNPObaIoDcjeNhD40xvkcmGIMnRi2MEIFOCb1/4oQoEwHkvkZWvlsxjuFvFngQbQcI5wVz5juzBhsUMko3lP6sBKycn2Mcocg4z7NAqDP5gGV96Nl@lJKvhG7gC0qadqzqmuMjQTX3Zx@BxCttODzjqBmR9PR3TKo07uFikaTmKEvO85dj0VsQqWqKXJzA63CY7hrxrQk8IBcZpuOoX6jIHdn/UDkaIu8Qi1wPtToRnNhqI2CSuLdeMu@Ky8Tg3fweS8F7AI6xHCU/aKtbA5vSlvVW@eenyjXPVeZsFCMDZxgx4fUKqvvQstEf4aLmC7peU9d1hgjp4cu3gVhFXX@DCNg4SiTftxr7NYOLr4OosXwJ1tl@fr0LvX57q4g97D5LI8yYLXQD@M9NU8cbMSR1O/koMivDA7iHeMbGexQvDJhCytQpEbxQgCLS8mfDxSJRxEr92LZMUR8o3wMz3J4ixOI2SmB704fQZlmSKKe9k2JtsgzbyfaEpksobZWK4dhf4U4H@Z@tuefvC6pOuuniqEcr0DKIpwl@XT6CbH3iCgjIMQoj7kY2EWGXjdY46fGDn/oTJ/fDSk@wvz6LW82YQ85rm7YJRenyymJisw8aQIY7wxvjN4wtF7PdIzr8XfwrNqhIcpv379Hw).
Made with [this.](https://codegolf.stackexchange.com/a/70932/113599)
## kavod
```
43#43#91#45#45#45#45#45#45#62#43#60#93#62#45#45#45#46#45#45#45#91#45#62#43#43#60#93#62#45#46#43#43#43#43#43#43#46#45#45#45#91#45#62#43#43#43#43#60#93#62#45#45#46#43#43#91#45#45#45#45#45#62#43#60#93#62#46#43#43#43#43#43#46#45#46#45#46#43#91#45#45#45#45#62#43#60#93#62#43#43#43#46#43#43#46#43#43#43#91#45#62#43#43#43#60#93#62#43#46#43#43#46#45#45#45#45#45#45#45#45#45#46#43#43#43#43#43#46#43#43#43#43#43#43#46#43#91#45#45#45#62#43#60#93#62#43#46#91#45#45#45#45#45#45#62#43#60#93#62#46#46#45#91#45#62#43#43#43#43#43#43#60#93#62#46#91#45#45#45#62#43#43#60#93#62#43#46#45#45#45#45#45#45#45#45#45#45#45#45#46#43#43#43#43#43#43#43#43#46#43#43#43#43#43#46#45#91#45#62#43#43#43#43#43#60#93#62#45#46#45#91#45#62#43#43#60#93#62#45#46#43#91#45#45#62#43#60#93#62#43#46#91#45#45#62#43#43#43#43#43#43#43#60#93#62#46#43#43#43#43#43#46#45#46#45#45#45#91#45#62#43#43#43#60#93#62#46#91#45#45#45#62#43#60#93#62#43#43#43#46#45#45#46#91#45#45#62#43#43#43#43#43#60#93#62#43#43#43#46#45#91#45#62#43#43#43#60#93#62#45#46#46#46#46#46#46#45#91#45#62#43#43#43#43#43#43#60#93#62#46#45#45#45#91#45#62#43#43#43#60#93#62#45#46#46#46#46#46#46#46#46#46#46#46#46#46#46#45#91#45#62#43#43#43#43#43#43#60#93#62#46#45#45#91#45#45#62#43#43#43#60#93#62#46#43#43#43#43#43#43#43#43#46#91#45#62#43#43#43#43#60#93#62#43#46#91#45#45#45#45#45#62#43#43#60#93#62#43#43#46#46#46#46#91#45#62#43#43#43#43#43#43#60#93#62#45#46#45#91#43#43#62#45#60#93#62#45#45#45#46#91#45#45#45#62#43#60#93#62#46#43#43#43#43#43#43#43#43#46#91#45#62#43#43#43#43#60#93#62#43#46#91#45#45#45#45#45#62#43#43#60#93#62#43#43#46#46#46#46#91#45#62#43#43#43#43#43#43#60#93#62#45#46#45#91#43#43#62#45#60#93#62#45#45#45#46#45#45#91#45#62#43#43#43#43#60#93#62#45#46#45#46#43#43#91#45#62#43#43#43#43#60#93#62#43#46#91#45#45#45#45#45#62#43#43#60#93#62#43#43#46#46#46#46#91#45#62#43#43#43#43#43#43#60#93#62#45#46#45#91#43#43#62#45#60#93#62#45#45#45#46#91#45#45#45#62#43#60#93#62#43#46#43#43#43#43#43#43#46#43#91#45#62#43#43#43#43#60#93#62#43#46#91#45#45#45#45#45#62#43#43#60#93#62#43#43#46#46#46#46#91#45#62#43#43#43#43#43#43#60#93#62#45#46#45#91#43#43#62#45#60#93#62#45#45#45#46#43#43#91#43#43#62#45#45#45#
```
Made with some python code I wrote ([link](https://tio.run/##pVG7DoMwDPwVpA4ksuKlY1t@JGKrqtIhQUAl@vU0sZ0HHYsBoZzuzr54/CxP787btt4GN74XpS/jNLhFtacWX35wys7LpPx0V7PWDz81czO4Zu01BIbeNgBrqDq49l34Y/hsONERgSpjjEbYFhEKJzwMExoheoGVEUK24hKZdCAlC7GeCDF1JgtkGvNMVeKTDIuKYtSJbN1HnPcxUtjST/KENlmToEw1SLUft/YSQqpfojjnSaJ7ufR0K5IdokNtEDMCdEaWaPfLOeS12z3y8o@OVe/9T68wRjwZ8wU)). [TIO](https://HWj1dhhKsPGfj2539aiOdysQI9AXg0gETZDSCN9wsLOp2k1vO6IyvwYL8YP4p5PnYqQBOnVejRv0nHqmeRfNEZnPsjYP3wTA3P)
## Brainf\*\*\* (New!)
```
++[------>+<]>---.---[->++<]>-.++++++.---[->++++<]>--.++[----->+<]>.+++++.-.-.+[---->+<]>+++.++.+++[->+++<]>+.++.---------.+++++.++++++.+[--->+<]>+.[------>+<]>..-[->++++++<]>.[--->++<]>+.------------.++++++++.+++++.-[->+++++<]>-.-[->++<]>-.+[-->+<]>+.[-->+++++++<]>.+++++.-.---[->+++<]>.[--->+<]>+++.--.[-->+++++<]>+++.-[->+++<]>-......-[->++++++<]>.---[->+++<]>-..............-[->++++++<]>.--[-->+++<]>.++++++++.[->++++<]>+.[----->++<]>++....[->++++++<]>-.-[++>-<]>---.[--->+<]>.++++++++.[->++++<]>+.[----->++<]>++....[->++++++<]>-.-[++>-<]>---.--[->++++<]>-.-.++[->++++<]>+.[----->++<]>++....[->++++++<]>-.-[++>-<]>---.[--->+<]>+.++++++.+[->++++<]>+.[----->++<]>++....[->++++++<]>-.-[++>-<]>---.++[++>---<]>+..............-[->++++++<]>.+++[->+++<]>.-[--->+<]>++.[---->+++<]>-......-[->++++++<]>.---[->+++<]>-..-[->++++++<]>.+++++++.-------.+++++++.---------.-[->++<]>-.>++++++++++.-[------->+<]>++.++++.------------.+++++++++++.
```
Made with [this](https://codegolf.stackexchange.com/questions/5418/brainf-golfer/5440#5440).
[TIO](https://tio.run/##pVNbCgIxDDxQaE4gvUjxQwVBBD8Ez1/zmLSpiogbFelsZpI0s8f74XI7P07X3olasai021f5Z/k1OdmRyWJgjircJomRIx@HDVXIvuRMhdilPEBDBWM6kXNHzFHZJNjTPK@kgE4ITpaNkSdquQ6U1zFi2FkP80iZwQlopBa2WNvNWkiIeE2E8uhE1eelx61gdlKFLKAzEtWCJbZ1OZu0lt2zL39rW3nvf2pJG3oqxahfrjZbUB@NhTLc@vP63nTj5cgOTA5PtgujwTPJ4bDsZzfrg96f)
## PostScript (New!)
```
(IO.puts "print(\\"main = putStr \\\\\\"\\\\\\\\\\\\\\"08á\\\\'←08á\\\\'←76á\\\\'←17á\\\\'←\\\\\\\\\\\\\\"o|\\\\\\"\\")") =
quit
```
(That's a lot of backslashes!)
[TIO](https://tio.run/#%23K8gvLilOLsosKNGtKACy///X8PTXKygtKVZQKijKzCvRiIlRyk3MzFOwVQCKBpcUKcSAgVIMClAysDi8EMRQf9Q2AZltboZgG5oj2Gja82vgxippKmkq2HIVlmYCXQMA)
## Elixir
```
IO.puts "print(\"main = putStr \\\"\\\\\\\"08á\\'←08á\\'←76á\\'←17á\\'←\\\\\\\"o|\\\"\")"
```
[TIO](https://tio.run/##S83JrMgs@v/f01@voLSkWEGpoCgzr0QjRik3MTNPwVYBKBhcUqQQExOjFAMBSgYWhxfGxKg/apuAYJmbwViG5jAWTH1@DVi3kqbS//8A)
## Python 3
```
print("main = putStr \"\\\"08á\'←08á\'←76á\'←17á\'←\\\"o|\"")
```
[TIO](https://tio.run/##K6gsycjPM/7/v6AoM69EQyk3MTNPwVahoLQkuKRIIUYpJiZGycDi8MIY9UdtE@AMczMow9AcygCpy6@JUVLS/P8fAA)
## Haskell
```
main = putStr "\"08á'←08á'←76á'←17á'←\"o|"
```
[TIO](https://tio.run/##y0gszk7Nyfn/PzcxM0/BVqGgtCS4pEhBKUbJwOLwQvVHbRNgtLkZhDY0h9AxSvk1Sv//AwA)
## Haystack
```
"08á'←08á'←76á'←17á'←"o|
```
[TIO](https://tio.run/##y0isLC5JTM7@/1/JwOLwQvVHbRNgtLkZhDY0h9BK@TX//wMA)
## MY
```
08á'←08á'←76á'←17á'←
```
[TIO](https://tio.run/##y638/9/A4vBC9UdtE2C0uRmENjSH0P//AwA)
## MY output
```
PPCG
```
I’ll add some more later.
[Answer]
# Python 2 -> Bash -> MySQL -> PHP
### `int score = 4;`
---
```
print """echo "SELECT 'printf(\\"PPCG\\");';\""""
```
Even though this isn't code golf, the bytecount is 49.
---
Python outputs:
```
echo "SELECT 'printf(\"PPCG\");';"
```
Bash outputs:
```
SELECT 'printf("PPCG");';
```
MySQL outputs:
```
printf("PPCG");
```
PHP outputs:
```
PPCG
```
There you go!
[Answer]
New to codegolf, just trying to make an entry. Not trying to win. Am I doing this right?
## Bash -> Batch - 23 bytes
```
printf "echo PPCG">.bat
```
This will output "echo PPCG" to a .bat which can be executed in windows.
] |
[Question]
[
This is a simple one. Given the input of a number, return the name and reputation score of the Stack Overflow user with that **given ID**. Your program can assume that it is always given a valid and existent user ID.
For example: given the input `764357` (which is my userID on StackOverflow) the program would return `LegoStormtroopr 3,088` (approximately) it might change.
You get the URL: "<https://stackoverflow.com/users/>" or "<http://api.stackexchange.com/2.1/users/>" for free, so your score is `length of your program - 31 or 39`, **depending on which URL you use - but declare which it is**. This prevents people from abusing URL shorteners.
edit: And no calling a custom made API that query Stack Overflow, and returns just the name and score. ~~But if you know of an offical API, then that is totally legitimate.~~
edit2: If you need an example input: I've given my ID below, feel free to add your own ID, username and score below to help others out. Note again, this is for the main Stack Overflow site.
```
764357 returns LegoStormtroopr 3,088
```
[Answer]
# Shell script: ~~64~~ 51 characters
```
curl -sL http://stackoverflow.com/users/`cat`|grep -oPm2 'n">\K[0-9,]+|e">\K[^<]+'
```
Sample run:
```
bash-4.1$ curl -sL http://stackoverflow.com/users/`cat`|grep -oPm2 'n">\K[0-9,]+|e">\K[^<]+'
662504
manatwork
834
bash-4.1$ curl -sL http://stackoverflow.com/users/`cat`|grep -oPm2 'n">\K[0-9,]+|e">\K[^<]+'
764357
Lego Stormtroopr
3,087
```
(Note that you have to press `^D` after typing in the input interactively. Or just pipe it to the command.)
[Answer]
# Ruby: ~~84~~ 70 characters
```
s=open("http://stackoverflow.com/users/"+gets).read
puts s[/me">(.+)</,1],s[/n">([\d,]+)/,1]
```
Sample run:
```
bash-4.1$ ruby -ropen-uri -e 's=open("http://stackoverflow.com/users/"+gets).read;puts s[/me">(.+)</,1],s[/n">([\d,]+)/,1]' <<< '662504'
manatwork
834
bash-4.1$ ruby -ropen-uri -e 's=open("http://stackoverflow.com/users/"+gets).read;puts s[/me">(.+)</,1],s[/n">([\d,]+)/,1]' <<< '764357'
Lego Stormtroopr
3,087
```
[Answer]
# Python 2.7 - 119
### (150 - 31)
Without regex:
```
from urllib import*
s=urlopen("http://stackoverflow.com/users/%d"%input()).read()
p=str.split
print p(p(s,'r ')[1],' -')[0],p(p(s,'ore">')[1],'<')[0]
```
[Answer]
# Python 3, 117
`117 = 148 - 31`
I don't think searching in plain HTML source code will lead to strong solution. For example, some weird stuff in one's profile may break your solutions. So I'd like to search using CSS selectors.
```
from lxml.html import*
C=parse('http://stackoverflow.com/users/'+input()).getroot().cssselect
print(C('[id^=u]')[0].text,C('[class$=ore]')[0].text)
```
[Answer]
# Javascript 217
Heres a ungolfed Javascript Version using the official api with JSONP, to start with . Using the url would require XHR, which sould be quite verbose, if i find some time i'll try a more golfed version though.
```
d=document;function f(a){y=a.items[0];alert(y.display_name+" "+y.reputation)}x=d.createElement("script");x.src="https://api.stackexchange.com/2.1/users/"+prompt()+"?site=stackoverflow&callback=f";d.body.appendChild(x)
```
[Answer]
## Perl 5 (with Mojolicious), 87 - 31 = 56 bytes
```
say/h1.*>(.*)</,$/,/core">(.*?)</ for g("http://stackoverflow.com/users/".pop)->dom
```
Sample run:
```
$ perl -Mojo -E 'say/h1.*>(.*)</,$/,/core">(.*?)</ for g("http://stackoverflow.com/users/".pop)->dom' 764357
Lego Stormtroopr
3,103
```
Readable & clean: 128 - 31 = 97 bytes
```
say $_->at("#user-displayname")->text, ": ", $_->at(".reputation a")->text for g("http://stackoverflow.com/users/".pop)->dom
```
Sample run:
```
$ perl -Mojo -E 'say $_->at("#user-displayname")->text, ": ", $_->at(".reputation a")->text for g("http://stackoverflow.com/users/$ARGV[0]")->dom' 764357
Lego Stormtroopr: 3,103
```
[Answer]
## R: 150-31=119
```
f=function(i){S=function(x)strsplit(grep(x,scan(paste0("http://stackoverflow.com/users/",i),"",sep="\n"),v=T)[1],">|<")[[1]][3];cat(S("h1"),S("=re"))}
```
Quite simply picks the first lines containing `h1` (for the name) and `=re` (for the score) using `grep` with argument `value=TRUE` (here `v=T`) and then split the string (using `strsplit` at characters `>` and `<`. Inconveniently it queries the page twice (hence the two "Read n items" warnings) but that was shorter.
```
>f(1451109)
Read 917 items
Read 917 items
plannapus 6,566
```
[Answer]
## Tcl, (231 - 39) 192
not the shortest way, but using the official API
```
package r http
package r json
set d [lindex [dict get [json::json2dict [http::data [http::geturl http://api.stackexchange.com/2.1/users/$argv?site=stackoverflow]]] items] 0]
puts [dict get $d display_name]\ [dict get $d reputation]
```
And in spirit of the **original** question:
```
package r http
package r json
set c [dict get [json::json2dict [http::data [http::geturl http://api.stackexchange.com/2.1/users/?order=desc&sort=reputation&site=stackoverflow&min=$argv&max=$argv]]] items]
foreach d $c {puts "[dict get $d display_name] [dict get $d reputation]"}
```
Finds users with that reputation
[Answer]
# Shorter CoffeeScript: 143 characters (182 - 39)
This relies on the API always returning the object keys in the same order, but shaves off 7 characters.
```
f=(r)->u=Object.keys(items[0]);alert u[3]+' '+u[5]
d=document
j=d.createElement('script')
j.src="//api.stackexchange.com/2.1/users/"+prompt()+'?site=diy&jsonp=f'
d.body.appendChild j
```
# CoffeeScript: 150 characters (189 - 39)
```
f=(r)->u=r.items[0];alert u.display_name+' '+u.reputation
d=document
j=d.createElement('script')
j.src="//api.stackexchange.com/2.1/users/"+prompt()+'?site=diy&jsonp=f'
d.body.appendChild j
```
(Note that the program prompts you for "undefined" -- it's asking for the User ID.)
[Answer]
## R - 84
84 = 115 - 31
```
sub(".*\\/(.*)\\?.*>(.*)<.*","\\1 \\2",grep("b=r",scan(paste0("http://stackoverflow.com/users/",scan(n=1)),""),v=T)[1])
```
Simulation:
```
> sub(".*\\/(.*)\\?.*>(.*)<.*","\\1 \\2",grep("b=r",scan(paste0("http://stackoverflow.com/users/",scan(n=1)),""),v=T)[1])
1: 1201032
Read 1 item
Read 2976 items
[1] "flodel 31,093"
```
[Answer]
## 101 100 - CoffeeScript with jQuery
```
$.getJSON "http://api.stackexchange.com/2.1/users/#{prompt()}?site=stackoverflow",(d)->alert [d.items[0].reputation,d.items[0].display_name]
```
Here's a [fiddle](http://jsfiddle.net/brigand/txnfa/); just know that it prompts you when you first open the page, so have a ID ready, or press Run again.
Or we can be super hacky to save a whole character!
```
$.getJSON "http://api.stackexchange.com/2.1/users/#{prompt()}?site=stackoverflow",(d)->`with(d.items[0])alert([reputation,display_name])`;1
```
[Answer]
# Python 2.7 - 112
### 112 = 143 - 31
A newer, short version that uses some of the ideas from [Steven Rumbalski answer](https://codegolf.stackexchange.com/a/12728/8777), while still using Regex.
```
import urllib,re
r=re.findall('r (.*?) -|re">(.*?)<',urllib.urlopen("http://stackoverflow.com/users/%d"%input()).read())
print r[0][0],r[2][1]
```
### 133 = 164 - 31
Here is a base version for people to work from, but I'm sure people can get even shorter.
```
import urllib,re
u=input()
s=urllib.urlopen("http://stackoverflow.com/users/%d"%u).read()
r=re.findall('name.*?>(.*?)</h1|tion.?>(.*?)</a',s)
print r[0][0],r[1][1]
```
[Answer]
# GNU Awk: 217 characters
Just because GNU `awk` supports TCP natively: no module/library/external tool.
```
{RS="\r"
print h("/users/"$0,$0,"/",4),h($2,$2"\\?","<|>",3)}function h(p,m,r,f){d="stackoverflow.com"
g="/inet/tcp/0/"d"/80"
print"GET "p" HTTP/1.1\nHost:"d"\n"|&g
close(g,"to")
while(g|&getline)if($0~m){close(g,"from")
split($0,a,r)
return a[f]}}
```
Sample run:
```
bash-4.1$ awk '{RS="\r";print h("/users/"$0,$0,"/",4),h($2,$2"\\?","<|>",3)}function h(p,m,r,f){d="stackoverflow.com";g="/inet/tcp/0/"d"/80";print"GET "p" HTTP/1.1\nHost:"d"\n"|&g;close(g,"to");while(g|&getline)if($0~m){close(g,"from");split($0,a,r);return a[f]}}' <<< 662504
manatwork 854
bash-4.1$ awk '{RS="\r";print h("/users/"$0,$0,"/",4),h($2,$2"\\?","<|>",3)}function h(p,m,r,f){d="stackoverflow.com";g="/inet/tcp/0/"d"/80";print"GET "p" HTTP/1.1\nHost:"d"\n"|&g;close(g,"to");while(g|&getline)if($0~m){close(g,"from");split($0,a,r);return a[f]}}' <<< 764357
lego-stormtroopr 3,947
```
] |
[Question]
[
Write a program or function that:
1. takes in a string from stdio or arguments
2. replaces all occurrences of `true` with `false` and `false` with `true`
3. reverses it, but does not reverse `true` and `false`
4. returns or prints result
Examples (left side is input):
```
"true" "false"
"2false" "true2"
"true is false" "true si false"
"false,true,undefined" "denifednu,false,true"
"stressed-false" "true-desserts"
"falstrue" "falseslaf"
"true false true x" "x false true false"
```
Standard loopholes apply.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
### Leaderboard
```
var QUESTION_ID=63256,OVERRIDE_USER=20569;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]
# C# 6, 144 bytes
```
string R(string t)=>string.Concat(new System.Text.RegularExpressions.Regex("true|false").Replace(t,m=>m.Value[0]<'g'?"eurt":"eslaf").Reverse());
```
It uses a regular expression to match `true|false`, and if it matches `true` it will be replaced by `eslaf`, otherwise by `eurt`. `m.Value[0]<'g'` is a shorter way to say `m.Value[0]=="false"`, because the only possible values for `m.Value` are `"true"` or `"false"`, so if the char code of the first char is smaller than the char code of `'g'`, it's `"false"`.
### Old version, 95 bytes
This one had a bug, it didn't return correct output for `falstrue`.
```
string R(string t)=>string.Concat(t.Reverse()).Replace("eurt","false").Replace("eslaf","true");
```
[Answer]
# [TeaScript](https://github.com/vihanb/TeaScript), ~~36~~ ~~25~~ 24 bytes
```
xv¬°g("eurt|eslaf",#ln>4)
```
TeaScript is JavaScript for golfing.
Edits: Saved 11 bytes thanks to @V…™ ú·¥Ä…¥. Fixed for input `falstrue` and saved a byte.
Old version (Invalid):
```
xv¬°g("eurt",f)g(f.T¬°v¬°,t)
```
Explanation:
```
x // Input
v¬° // Reverse
g("eurt", // Global replace "eurt" with "false".
f) // f is predefined to false.
g(f.T¬°v¬°, // Convert false to string, then reverse.
t) // t is predefined to true.
```
[Answer]
## Bash+GNU, ~~45~~ ~~38~~ 73 bytes
**Edit:** works with both `trufalse` and `falstrue`
```
sed s/false/%eurt%/g\;s/true/%eslaf%/g|rev|sed "s/%\(true\|false\)%/\1/g"
```
**Old version**, 38 bytes (shortened, thanks to Digital Trauma):
```
rev|sed s/eurt/false/g\;s/eslaf/true/g
```
[Answer]
# JavaScript ES6, 59
As an anonymous function.
Note, replace is used just as a shorthand for match().map(). The replaced string is discarded, and the output string is made piece by piece backwards (so no need to reverse).
```
s=>s.replace(/false|true|./g,x=>s=(x[1]?x<'t':x)+s,s='')&&s
```
Test running the snippet below in an EcmaScript 6 compliant browser.
```
f=s=>s.replace(/false|true|./g,x=>s=(x[1]?x<'t':x)+s,s='')&&s
//test
console.log=x=>O.innerHTML+=x+'\n'
;[
["true","false"]
,["falstrue","falseslaf"]
,["1false","true1"]
,["true is false","true si false"]
,["false,true,undefined","denifednu,false,true"]
,["stressed-false","true-desserts"]
,["true false true x","x false true false"]
].forEach(t=>console.log(t[0]+' -> '+f(t[0])))
```
```
<pre id=O></pre>
```
[Answer]
# Windows Batch, ~~184~~ 213 bytes
Fixed the bug, `falstrue -> falseslaf` and `trufalse -> trueurt`
Probably one of the less popular languages:
```
setlocal enabledelayedexpansion
set /p Q=
set N=0
:L
call set T=%%Q:~%N%,1%%%
set /a N+=1
if not "%T%" equ "" (
set R=%T%%R%
goto L
)
set R=%R:eurt=false%
set R=%R:eslaf=true%
set R=%R:falstrue=falseslaf%
echo %R%
```
[Answer]
# Haskell, 94 bytes
Performs pattern matching on the input string, looking for "false" or "true" and appends the opposite to the result of applying the function on the remainder of the string. If true or false isn't found, it uses recursion to reverse the string in the same fashion.
```
f[]=[]
f('t':'r':'u':'e':s)=f s++"false"
f('f':'a':'l':'s':'e':s)=f s++"true"
f(x:s)=f s++[x]
```
[Answer]
# JavaScript ES6, ~~95~~ 93 bytes
Unnamed function. Add `f=` to the beginning to use it. Thanks Ismael! Also assumes that the input does not contain tabs.
```
x=>[...x[r="replace"](/false/g,"\teslaf")[r](/(\t)*true/g,"eurt")[r](/\t/g,"")].reverse().join``
```
[Answer]
# Pyth, 30 bytes
```
::_z"eurt""false""eslaf""true"
```
This reverses the input (`_z`), substitutes `"eurt"` for `"false"` and `"eslaf"` for `"true"`. Replacement is done using `:`.
[Try it online](https://pyth.herokuapp.com/?code=%3A%3A_z%22eurt%22%22false%22%22eslaf%22%22true%22&input=true+is+false&debug=0)
[Answer]
# [rs](https://github.com/kirbyfan64/rs), 56 bytes
```
\t
+(.*\t)(.)(.*)/\2\1\3
\t/
eurt/fals\t
eslaf/true
\t/e
```
[Live demo and test cases.](http://kirbyfan64.github.io/rs/index.html?script=%5Ct%0A%2B%28.*%5Ct%29%28.%29%28.*%29%2F%5C2%5C1%5C3%0A%5Ct%2F%0Aeurt%2Ffals%5Ct%0Aeslaf%2Ftrue%0A%5Ct%2Fe&input=true%0A1false%0Afalstrue%0Atrue%20is%20false%0Afalse%2Ctrue%2Cundefined%0Astressed-false%0Afalstrue)
[Answer]
# Julia, ~~59~~ ~~55~~ 46 bytes
```
s->replace(reverse(s),r"eurt|eslaf",i->i<"et")
```
This creates an unnamed function that accepts a string and returns a string. To call it, give it a name, e.g. `f=s->...`.
The input is reversed using `reverse`. We match on the regular expression `eurt|eslaf` which matches `true` or `false` backwards. To the match we apply a function that returns `true` if the match is lexicographically smaller than `et` (i.e. `eslaf`) and `false` otherwise. The boolean literals are converted to string in the output.
Saved 9 bytes and fixed an issue thanks to Glen O!
[Answer]
# Javascript, 135 Bytes
```
function(s){return s.split("").reverse().join("").replace(/eslaf/i,'‚ò∫').replace(/eurt/i,'‚òª').replace(/‚òª/g,!1).replace(/‚ò∫/g,!1)}
```
## Test:
`=>`"false is the opposite of true"
`<=`"true fo etisoppo eht si false"
*Thanks ProgramFOX and edc65 for pointing out a bug!*
[Answer]
# Java, ~~162~~ ~~98~~ 92 bytes
Thanks (and sorry!~) to @DanielM. for telling me about StringBuffer and the fact that we can use functions!
[Because, you know, Java.](https://codegolf.meta.stackexchange.com/a/5829/44713)
```
s->(""+new StringBuffer(s.replaceAll("false","eurt")).reverse()).replaceAll("eurt","false");
```
Returns the correct, reversed string.
Ungolfed Version:
```
s->new StringBuilder(
s.replaceAll("false","eurt"))
.reverse().toString().replaceAll("eurt","false");
```
Basically, I replace all instances of "false" with a backwards "true", then reverse the entire string, and then replace the now backwards versions of "true" (not the ones I just replaced) with "false". Easy peasy.
[Answer]
# Mathematica, 64 bytes
```
StringReverse@#~StringReplace~{"eurt"->"false","eslaf"->"true"}&
```
[Answer]
# Python 3, ~~68~~ 100 bytes
I'm still golfing it, but it's fixed to the bug, so `falstrue -> falselsaf` and `trufalse -> trueurt`
Pretty straightforward:
```
print(input()[::-1].replace("eurt","false").replace("eslaf","true").replace("falstrue","falseslaf"))
```
[Answer]
# Japt, 26 bytes
**Note:** This may be invalid, as it requires bug fixes made after this challenge was posted.
```
Uw r"eurt|eslaf",X=>X<"et"
```
Try it in the [online interpreter](https://codegolf.stackexchange.com/a/62685/42545)! (Arrow function requires ES6-compliant browser, such as Firefox.)
### How it works
```
// Implicit: U = input string
Uw r // reverse U, then replace:
"eurt|eslaf" // occurrences of either "eurt" or "eslaf"
X=>X<"et" // with "false" or "true", respectively
// Implicit: output last expression
```
Here's a version that worked before the bug fixes: (38 bytes)
```
Uw $.replace(/eurt|eslaf/g,X=>X<"et")$
```
[Answer]
## Gema, 43
```
*=@a{@reverse{*}};a:eurt=false;a:eslaf=true
```
([Gema](http://gema.sourceforge.net/new/index.shtml) is an obscure macro language.)
[Answer]
# Pyth, ~~28~~ 22
```
Amr`!dZ2jHjLGcR_Hc_z_G
```
6 bytes thanks to Jakube
Works correctly for `falstrue`, as shown in the suite below.
[Test suite](https://pyth.herokuapp.com/?code=Amr%60%21dZ2jHjLGcR_Hc_z_G&input=falstrue&test_suite=1&test_suite_input=true%0A2false%0Atrue+is+false%0Afalse%2Ctrue%2Cundefined%0Astressed-false%0Afalstrue%0Atrue+false+true+x&debug=0)
[Answer]
# Haskell, 102 bytes
```
h('t':'r':'u':'e':s)="eslaf"++h s
h('f':'a':'l':'s':'e':s)="eurt"++h s
h(x:s)=x:h s
h[]=""
r=reverse.h
```
The replacement of "true" by "false" and vice-versa is quite lengthy with the pattern-matching, but at least it deals correctly with "falstrue" and the like. And besides, I suspect that a correct regex-based version would be a bit longer.
[Answer]
## Python 3 - 108 92 bytes
```
import re
print(re.sub("eslaf|eurt",lambda m:repr(len(m.group(0))>4).lower(),input()[::-1]))
```
Uses a regex to match on "true" or "false" and uses a lambda to process matches and choose what to use as a replacement string. Using repr gets the string representation of (len(match)>4) which gives "True" when "false" is matched and vice versa (and use .lower() because repr(bool) gives a capitalized string) to get the inverse of the match and finish up by reversing the replacement and then the processed input using [::-1]
Managed to get the length down 16 bytes from TFelds suggestions.
Edit: Python is back in front of java, no need for alarm.
[Answer]
# ùîºùïäùïÑùïöùïü, 40 chars / 65 bytes
```
ô[…ïċ/false|true/g,⇏[…⬯+!שúa]ù⬮ø⬯)]ù⬮ø⬯)
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=falstrue&code=%C3%B4%5B%E2%80%A6%C3%AF%C4%8B%2Ffalse%7Ctrue%2Fg%2C%E2%87%8F%5B%E2%80%A6%E2%AC%AF%2B!%D7%A9%C3%BAa%5D%C3%B9%E2%AC%AE%C3%B8%E2%AC%AF%29%5D%C3%B9%E2%AC%AE%C3%B8%E2%AC%AF%29)`
Thanks to @feersum for pointing out a bug!
## 21 chars / 43 bytes, non-competitive
```
ôᴙ(ïċ/⊭|⊨⌿,↪ᴙ(⬯+!ë$⸩⸩
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=asdfoiansfoinqwoiefnasdonaonfitrueaosdifnofalse&code=%C3%B4%E1%B4%99%28%C3%AF%C4%8B%2F%E2%8A%AD%7C%E2%8A%A8%E2%8C%BF%2C%E2%86%AA%E1%B4%99%28%E2%AC%AF%2B!%C3%AB%24%E2%B8%A9%E2%B8%A9)`
[Answer]
# Prolog, 225 bytes
```
p(X):-string_to_list(X,L),reverse(L,B),q(B,C),string_to_list(Z,C),write(Z),!.
q([],[]).
q([101,117,114,116|T],[102,97,108,115,101|L]):-q(T,L).
q([101,115,108,97,102|T],[116,114,117,101|L]):-q(T,L).
q([H|T],[H|L]):-q(T,L).
```
Try it out online [here](http://swish.swi-prolog.org/)
Run by querying in the following way:
```
p("falstrue").
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Ôr`laf|e¨t`Èøf
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1HJgg2xhZnxlqHRgyPhm&input=WwoidHJ1ZSIKIjJmYWxzZSIKInRydWUgaXMgZmFsc2UiCiJmYWxzZSx0cnVlLHVuZGVmaW5lZCIKInN0cmVzc2VkLWZhbHNlIgoiZmFsc3RydWUiCiJ0cnVlIGZhbHNlIHRydWUgeCIKXS1tUg)
[Answer]
# Ruby, 55 bytes
```
->s{s.gsub(/true|false/){$&[?t]?:eslaf: :eurt}.reverse}
```
Test:
```
->s{s.gsub(/true|false/){$&[?t]?:eslaf: :eurt}.reverse}["false,true,undefined"]
=> "denifednu,false,true"
```
[Answer]
## Perl 5, 68 bytes
67 plus 1 for `-E` instead of `-e`
```
%a=(false,eurt,true,eslaf);say~~reverse<>=~s/false|true/$a{$&}/gr
```
[Answer]
# OpenSCAD, 178 bytes
(Note that this uses the [String Theory library](http://www.thingiverse.com/thing:526023), as OpenSCAD doesn't exactly have a standard library. Additionally, this is a function because the only allowed input is to hard-code it.
```
use <Strings.scad>;function f(a)=contains(g(a),"eurt")?replace(g(a),"eurt","false"):g(a);function g(a)=contains(reverse(a),"eslaf")?replace(reverse(a),"eslaf","true"):reverse(a);
```
[Answer]
## C#, 260 bytes
```
using System;class P{static void Main(){var y=Console.ReadLine();char[] n=y.ToCharArray();Array.Reverse(n);var s=new string(n);if(s.Contains("eslaf")){s=s.Replace("eslaf","true");}if(s.Contains("eurt")){s=s.Replace("eurt","false");}Console.WriteLine(s);}}
```
[Answer]
## PHP, 60 bytes
Simple, reverses the string first, then replaces the reversed versions with their respective swaps.
"falstrue" becomes "eurtslaf" becomes "falseslaf".
```
<?=strtr(strrev($argv[1]),{'eurt'=>'false','eslaf'=>'true'})
```
[Answer]
## Perl 5.10, 54 bytes
```
$_=reverse<>;s/(eurt)|(eslaf)/$1?"false":"true"/eg;say
```
Reverse, then replace. A different way of doing it besides the hash table used for the other Perl answer, which ends up being shorter!
[Try it online.](https://ideone.com/TZ7kPL)
[Answer]
# Pyth - 18 bytes
Can be golfed a lot more.
```
Amr`!dZ2::_z_GH_HG
```
[Test Suite](http://pyth.herokuapp.com/?code=Amr%60%21dZ2%3A%3A_z_GH_HG&test_suite=1&test_suite_input=true%0A1false%0Atrue+is+false%0Afalse%2Ctrue%2Cundefined%0Astressed-false&debug=0).
] |
[Question]
[
The process of Reversal-Addition is where a number is added to it's reverse until the number created is a palindrome. For example, if we start with 68, the process would be:
$$68 + 86 \to 154 + 451 \to 605 + 506 \to 1111$$
As you can see, this took 3 additions to get to a palindromic number. If we were to start with \$89\$, we would need 24 steps (which you can see the breakdown [here](http://www.jasondoucette.com/pal/89)).
The world record for the most steps taken before a palindrome is reached is \$261\$, which occurs for the number \$1186060307891929990\$, producing a number larger than \$10^{118}\$. However, there have been quite a few numbers which we have not been able to get a palindrome. These are called [Lychrel numbers](https://en.wikipedia.org/wiki/Lychrel_number).
Since we are working in base 10, we can really only call them candidates, because there exists no proof that these numbers never reach a palindrome. For example, the smallest base-10 Lychrel candidate is \$196\$, and has gone through well over a billion iterations. If the palindrome does exist, it is much larger than \$10^{10^{8.77}}\$. As comparison, if that many 1s was inscribed on atoms, we would need \$2.26772×10^{588843575}\$ universes worth of atoms to write it out, assuming it exists.
# Your Task
Create a program or function that takes an integer input and returns or prints the number of steps required to reach a palindrome. You will not be required to deal with Lychrel candidates (i.e. Your program, when given a Lychrel candidate, is allowed to either throw an error or run forever).
# Test Cases:
```
f(0) => 0
f(11) => 0
f(89) => 24
f(286) => 23
f(196196871) => 45
f(1005499526) => 109
f(1186060307891929990) => 261
```
# Rules
1. [No standard loopholes.](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
# Bonuses
1. If you print out each addition step, formatted `n + rev(n) = m`, you may multiply your score by **0.75**. The sums should print out before the number of steps.
2. If your code can detect if a number is a Lychrel candidate, you may multiply your score by **0.85**. In this case it is sufficient to assume anything that takes more than 261 iterations is a Lychrel candidate. Either return nothing, or anything that is not a number that can be mistaken for a correct answer (etc: any string or a number not in the range 0-261). Any error does not count as valid output (ex. maximum recursion depth exceeded) and can not be used in the detection.
3. If you complete both bonuses, multiply by **0.6**.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least number of bytes wins.
---
This code snippet shows an example solution in Python 3 with both bonuses.
```
def do(n,c=0,s=''):
m = str(n)
o = m[::-1]
if c > 261:
return "Lychrel candidate"
if m == o:
print(s)
return c
else:
d = int(m)+int(o)
s+="%s + %s = %s"%(m,o,str(d))
return do(d,c+1,s)
```
[Answer]
## Python, 51
```
def f(n):r=int(str(n)[::-1]);return n-r and-~f(n+r)
```
For Python 2, backticks can't replace `str()` because of the `L` attached to `long` literals.
Here's an alternate version with score 64 \* 0.85 = **54.4**:
```
def f(n,c=262):r=int(str(n)[::-1]);return c*(n-r)and-~f(n+r,c-1)
```
And an alternate version for **Python 3** with score 88 \* 0.6 = **52.8**:
```
def f(n,c=262):r=int(str(n)[::-1]);return c*(n-r)and-~f(n+r,print(n,'+',r,'=',n+r)or~-c)
```
[Answer]
# Pyth, 12 bytes
```
f_I`~+Qs_`Q0
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=f_I%60~%2BQs_%60Q0&input=89&debug=0) or [Test harness](https://pyth.herokuapp.com/?code=QFQ.Qs%5B%22f(%22Q%22)+%3D%3E+%22%0Af_I%60~%2BQs_%60Q0&input=%22Test-cases%3A%22%0A0%0A11%0A89%0A286%0A196196871%0A1005499526%0A1186060307891929990&debug=0)
This uses a quite new feature (only 17 hours old).
### Explanation
```
implicit: Q = input number
f 0 repeat the following expression until it
evaluates to true and return the number of steps
`Q convert Q to string
_ reverse the digits
s convert to int
+Q add Q
~ assign the result to Q
(this returns the old value of Q)
` convert the old value of Q to a string
_I and check if it's invariant under the operation reverse
```
### edit:
Changed the code a little bit. The old version was
```
fqKs_`Q~+QK0
```
Same byte count, but the new one is way cooler.
[Answer]
# CJam, ~~23~~ ~~22~~ 20.4 bytes
```
ri{__sW%i+}261*]{s_W%=}#
```
The code is 24 bytes long and prints **-1** for Lychrel candidates.
[Try it online.](http://cjam.aditsu.net/#code=ri%7B__sW%25i%2B%7D261*%5D%7Bs_W%25%3D%7D%23&input=196)
### How it works
```
ri e# Read an integer from STDIN.
{ }261* e# Do the following 261 times:
__ e# Push two copies of the integer on the stack.
sW%i e# Cast to string, reverse and cast back to integer.
+ e# Add the copy and the reversed copy of the integer.
] e# Wrap all 262 results in an array.
{ }# e# Push the index of the first element such that:
s e# The string representation equals...
_W%= e# the reversed string representation.
```
If `{}#` is successful, the index is also the number of steps. If, on the other hand, the array does not contain a palindrome, `{}#` will push **-1**.
[Answer]
# Java, 200\*0.6 = 120
```
import java.math.*;int f(BigInteger a){int s=-1;for(String b,c;(b=a+"").equals(c=new StringBuffer(b).reverse()+"")!=s++<999;)System.out.println(b+" + "+c+" = "+(a=a.add(new BigInteger(c))));return s;}
```
This is a simple loop that does just what it says on the box, but with some golf added. Returns `1000` for Lychrel candidates to get the detection bonus. Turns out I was able to print for not *too* many characters (for Java at least) and snag that bonus as well. The best I could do without bonus code was 156, so it was well worth it.
With some line breaks:
```
import java.math.*;
int f(BigInteger a){
int s=-1;
for(String b,c;(b=a+"").equals(c=new StringBuffer(b).reverse()+"")!=s++<999;)
System.out.println(b+" + "+c+" = "+(a=a.add(new BigInteger(c))));
return s;
}
```
---
**Old Answer: 171\*0.85 = 145.35 bytes**
```
import java.math.*;int f(BigInteger a){int s=-1;for(String b,c;(b=a+"").equals(c=new StringBuffer(b).reverse()+"")!=s++<262;)a=a.add(new BigInteger(c));return s>261?-1:s;}
```
---
[Answer]
# Ruby, (80+2)\*0.6 =~ 49.2
With flags `-nl`, run
```
p (0..261).find{$_[b=$_.reverse]||puts($_+' + '+b+' = '+$_="#{$_.to_i+b.to_i}")}
```
Output looks like
```
$ ruby -nl lychrel.rb
89
89 + 98 = 187
187 + 781 = 968
968 + 869 = 1837
1837 + 7381 = 9218
9218 + 8129 = 17347
17347 + 74371 = 91718
91718 + 81719 = 173437
173437 + 734371 = 907808
907808 + 808709 = 1716517
1716517 + 7156171 = 8872688
8872688 + 8862788 = 17735476
17735476 + 67453771 = 85189247
85189247 + 74298158 = 159487405
159487405 + 504784951 = 664272356
664272356 + 653272466 = 1317544822
1317544822 + 2284457131 = 3602001953
3602001953 + 3591002063 = 7193004016
7193004016 + 6104003917 = 13297007933
13297007933 + 33970079231 = 47267087164
47267087164 + 46178076274 = 93445163438
93445163438 + 83436154439 = 176881317877
176881317877 + 778713188671 = 955594506548
955594506548 + 845605495559 = 1801200002107
1801200002107 + 7012000021081 = 8813200023188
24
```
If given 196, it prints the first 261 addition steps and then `nil`.
Nothing too tricky here. We check whether `$_` (which is initialized to the input) contains its reverse, which is only possible if they're equal since they're the same size. If it is, we print the step number and exit, otherwise, we display and execute the addition step, storing the new value in `$_` (I unfortunately can't just `eval` the string I'm displaying because it interprets a reversed number with a trailing 0 as an octal literal). `puts` returns a falsey value so the loop continues.
[Answer]
# Pyth - 19 bytes
Uses while loop and a counter. There is probably a smaller algorithm than this, but this is pretty short.
```
Wnz_z=z`+szs_z=hZ;Z
```
[Try it online here](http://pyth.herokuapp.com/?code=Wnz_z%3Dz%60%2Bszs_z%3DhZ%3BZ&input=1186060307891929990&debug=0).
[Answer]
# K, 25 bytes
```
#1_{~x~|x}{$. x,"+",|x}\$
```
Not very elegant. The overall form (`{monad 1}{monad 2}\x`) is K's equivalent of a general "while" loop, where the first monad is the halting condition and the second is an iteratively applied function to the argument `x`. The first monad (`{~x~|x}`) is the negation of the classic "is x a palindrome" phrase. The second monad concatenates together a string representing x plus the reverse of x, evaluates it and then casts the result back into a string with `$`.
A sample run showing intermediate results:
```
{~x~|x}{$. x,"+",|x}\$68
("68"
"154"
"605"
"1111")
```
Doing formatted output as requested for the bonus would be very clumsy and add a significant amount of code.
[Answer]
# CJam, 23 bytes
```
Wl{\)\__W%_@#\i@i+s\}g;
```
Still only a few days into CJam, so I'm fairly happy to be at least in the same range as some of the pros. :) I did use Martin's string comparison trick that he also posted in the CJam hints. I also peeked at Dennis' solution to figure out how to reverse a string.
Explanation:
```
W Initialize counter, will keep this at bottom of stack.
Start counting at -1 because the counter will be incremented in the
last pass through the loop, when the palindrome is detected.
l Get input.
{ Start block of while loop.
\)\ Increment counter. Need to swap before/after because it's one below top of stack.
__ Copy current value twice. Need 3 copies in total:
* one for reversal
* one for comparison
* one for addition with reverse
W% Reverse value.
_ Copy the reverse value once because we need 2 copies:
* one for comparison
* one for addition with original value
@ Rotate one copy of original value to top.
# Test for non-equality with reverse, using Martin's trick.
\i Swap reverse value to top, and convert it to int.
@i Rotate remaining copy of original value to top, and convert it to int.
+s Add the values, and convert result to string.
\ Swap, so that comparison result is at top of stack for while loop test.
}g End of while loop.
; Current value sits at top of stack. Pop it, leaving only counter.
```
[Test it online](http://cjam.aditsu.net/#code=Wl%7B%5C)%5C__W%25_%40%23%5Ci%40i%2Bs%5C%7Dg%3B&input=89)
[Answer]
# Julia, ~~129~~ 120 bytes \* 0.6 = 72
```
i->(i=big(i);n=0;d=digits;while d(i)!=reverse(d(i))&&n<262 t=BigInt(join(d(i)));println(i," + ",t," = ",i+=t);n+=1end;n)
```
This creates an unnamed function which takes an integer as input and returns an integer, meanwhile printing each step. Lychrel candidates have a return value of 262. To call this, give it a name, e.g. `f=i->...`.
Note that omitting code relating only to the bonuses, this solution would be 84 bytes.
Ungolfed + explanation:
```
function f(i)
# Convert the input to a big integer
i = big(i)
# Initialize a step counter to 0
n = 0
# While the number is not a palindrome and we haven't exceeded 261 steps...
while digits(i) != reverse(digits(i)) && n < 262
# Get the reverse of the integer
# Note that we aren't using reverse(); this is because digits()
# returns an array of the digits in reverse order.
t = BigInt(join(digits(i)))
# Print the step and increment i
println(i, " + ", t, " = ", i += t)
# Count the step
n += 1
end
# Return the number of steps or 262 for Lychrel candidates
n
end
```
Examples:
```
julia> f(286)
286 + 682 = 968
968 + 869 = 1837
1837 + 7381 = 9218
9218 + 8129 = 17347
17347 + 74371 = 91718
91718 + 81719 = 173437
173437 + 734371 = 907808
907808 + 808709 = 1716517
1716517 + 7156171 = 8872688
8872688 + 8862788 = 17735476
17735476 + 67453771 = 85189247
85189247 + 74298158 = 159487405
159487405 + 504784951 = 664272356
664272356 + 653272466 = 1317544822
1317544822 + 2284457131 = 3602001953
3602001953 + 3591002063 = 7193004016
7193004016 + 6104003917 = 13297007933
13297007933 + 33970079231 = 47267087164
47267087164 + 46178076274 = 93445163438
93445163438 + 83436154439 = 176881317877
176881317877 + 778713188671 = 955594506548
955594506548 + 845605495559 = 1801200002107
1801200002107 + 7012000021081 = 8813200023188
23
julia> f(1186060307891929990)
(steps omitted)
261
julia> f(196)
(steps omitted)
262
julia> f(11)
0
```
Saved 2 bytes thanks to Geobits!
[Answer]
# CJam, 24 bytes
```
0q{__W%#}{_W%~\~+s\)\}w;
```
[Test it here.](http://cjam.aditsu.net/#code=0q%7B__W%25%23%7D%7B_W%25~%5C~%2Bs%5C)%5C%7Dw%3B&input=1186060307891929990)
## Explanation
```
0q e# Push a zero (the counter) and read input.
{ e# While this block leaves something truthy on the stack...
__ e# Make two copies of the current number (as a string).
W% e# Reverse the second copy.
# e# Check that they are not equal.
}{ e# ... run this block.
_W% e# Make a copy of the current number and reverse it.
~\~ e# Evaluate both N and its reverse.
+s e# Add them and turn the sum into a string.
\)\ e# Pull up the counter, increment it, and push it back down again.
}w
; e# Discard the palindrome to leave the counter on the stack.
```
For more information about why `#` can be used to check string inequality, [see this tip](https://codegolf.stackexchange.com/a/51848/8478).
[Answer]
# Haskell, ~~66~~ 53 bytes
```
r=reverse.show
f x|show x==r x=0|1<2=1+f(x+read(r x))
```
Usage example:
```
*Main> map f [0,11,89,286,196196871,1005499526,1186060307891929990]
[0,0,24,23,45,109,261]
```
[Answer]
## Clojure, 94 bytes
```
(fn[x](#(let[r(bigint(apply str(reverse(str %1))))] (if(= %1 r)%2(recur(+ %1 r)(inc %2))))x 0))
```
This is my first attempt to code golf, so please tell me if I'm doing anything wrong.
With some spaces:
```
(fn [x]
(#(let [r (bigint (apply str (reverse (str %1))))]
(if (= %1 r) %2 (recur (+ %1 r) (inc %2)))) x 0))
```
Simple recursion of the inner function. It takes two arguments, the integer `%1` and an index `%2`. If `%1` is a palindrome, the index gets returned. Otherwise, the function calls itself with the sum and the incremented index. The outer function initializes the index with zero.
A sample:
```
repl=> ((fn[x](#(let[r(bigint(apply str(reverse(str %1))))](if(= %1 r)%2(recur(+ %1 r)(inc %2))))x 0)) 1186060307891929990)
261
```
[Answer]
# Boost.Build, 304 bytes
Not really a language. Still cool.
```
import sequence ;
import regex ;
rule r ( n ) {
m = "([0-9]?)" ;
return [ sequence.join [ sequence.reverse [ regex.match "$(m)$(m)$(m)$(m)$(m)$(m)$(m)$(m)$(m)" : $(n) ] ] : "" ] ;
}
rule x ( n ) {
i = 0 ;
while $(n) != [ r $(n) ] {
n = [ CALC $(n) + [ r $(n) ] ] ;
i = [ CALC $(i) + 1 ] ;
}
echo $(i) ;
}
```
Pretty straightforward, other than the elaborate regex-based hack I used to reverse the string.
[Answer]
# Ruby, 44
```
f=->n{n==(r=n.to_s.reverse.to_i)?0:f[n+r]+1}
```
Needs Ruby 1.9 or higher for `->` lambda syntax.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ṚḌ+ƊŒḂ¬$пL’
```
[Try it online!](https://tio.run/##ASUA2v9qZWxsef//4bma4biMK8aKxZLhuILCrCTDkMK/TOKAmf///zY4 "Jelly – Try It Online")
Jelly *really* needs an "until" builtin
# How it works
```
ṚḌ+ƊŒḂ¬$пL’ - Main link. Takes n on the left
п - While loop, gathering each step into a list to return:
$ - Condition:
ŒḂ - Is palindrome?
¬ - Not
Ɗ - Body:
Ṛ - Reverse
Ḍ - Cast back to integer
+ - Add
L - Count number of steps
’ - Decrement to account for the final step
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
L↑S≠↔¡S+↔
```
[Try it online!](https://tio.run/##yygtzv7/3@dR28TgR50LHrVNObQwWBtI/f//38ISAA "Husk – Try It Online")
## Explanation
```
L↑S≠↔¡S+↔
¡ apply the following infinitely:
S+↔ number + its reverse
↑ take the longest prefix of items where
S≠↔ number ≠ its reverse
L return its length
```
] |
[Question]
[
To each of these nine [confusingly similar](http://en.wikipedia.org/wiki/Semantic_satiation) words, assign a number 1-9 in any way you like:
```
though
through
thorough
Thoreau
throw
threw
trough
tough
troll
```
Write a program that takes in a string. If the input is one of these nine words, output the number you assigned to it. If the input is not one of the words above, the program may do anything (including error or loop forever).
The words are case sensitive, e.g. `Thoreau`, should produce a number from 1-9 but `thoreau` will not necessarily do the same.
## Example
Suppose you assign the numbers as follows:
```
though 9
through 2
thorough 7
Thoreau 6
throw 3
threw 5
trough 4
tough 1
troll 8
```
Then when `tough` is input, `1` should be output.
When `through` is input, `2` should be output.
When `throw` is input, `3` should be output.
. . .
When `though` is input, `9` should be output.
All other inputs may do anything.
## Details
* Take the input string via stdin or the command line and output to stdout.
* The output may contain a single trailing newline.
* Instead of a program, you may write a function that takes in a string and prints the result normally or returns it.
* **The shortest submission in bytes wins[.](https://www.youtube.com/watch?v=WjzyAHKYJ8M&feature=youtu.be&t=22s)**
[Answer]
# CJam, ~~11 9~~ 7 bytes
```
q1b2+B%
```
**How it works**:
We are making use of the fact that the sum of the ASCII codes + 2 moded with 11 gives very nice order of 1 through 9 and then 10 for the nine concerned words. Here is the ordering:
```
through -> 1
thorough -> 2
tough -> 3
Thoreau -> 4
throw -> 5
threw -> 6
trough -> 7
though -> 8
troll -> 9
```
**Code explanation**:
```
q e# Read the input
1b e# Sum the ASCII code values of all characters in this word
2+ e# Increment the sum by 2
B% e# Mod by 11 and automatically print the mod result at the end
```
*4 bytes saved thanks to user23013*
[Try it online here](http://cjam.aditsu.net/#code=q1bB%25)9e%3C&input=thorough)
[Answer]
# Pyth, 8 chars
```
e%Cz8109
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=e%25Cz8109&input=thorough&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=zFz.zp%22%20%3D%3E%20%22ze%25Cz8109&input=%22Test%20Cases%22%0Athough%0Athrough%0Athorough%0AThoreau%0Athrow%0Athrew%0Atrough%0Atough%0Atroll&debug=0)
I'm using the assignment:
```
though 5
through 9
thorough 4
Thoreau 7
throw 3
threw 2
trough 8
tough 6
troll 1
```
### Explanation:
```
z input()
C convert to int (convert each char to their ASCII value
and interprete the result as number in base 256)
% 8109 modulo 8109
e modulo 10
```
Btw, I found the magic number 8109 by using this script: [`fqr1 10Sme%CdT.z1`](https://pyth.herokuapp.com/?code=fqr1+10Sme%25CdT.z1&input=though%0Athrough%0Athorough%0AThoreau%0Athrow%0Athrew%0Atrough%0Atough%0Atroll&debug=0).
[Answer]
# Python 2, ~~92~~ 54 bytes
```
print'K{7j)yE<}'.find(chr(hash(raw_input())%95+32))+1
```
The index string is created with `for word in words: print chr(hash(word)%95+32),`. As pointed out in Jakube's answer, the hash function will give different results depending on Python version. This index string is computed on 64 bit Python 2.7.6.
Longer (92 bytes) but less cryptic answer:
```
print'though through thorough Thoreau throw threw trough tough troll'.find(raw_input())/7+1
```
The programs returns 1-9 for *though through thorough Thoreau throw threw trough tough troll* in that order. When the input is not found, find will return a -1 which conveniently turns into a zero after the `+1`.
[Answer]
# Python 2.7.9 32 bit version, 22 bytes
```
lambda x:hash(x)%78%10
```
Notice, the version is really important here. You will get different results if your using a 64 bit version of Python. Since the `hash` method will compute 64 bit hash values instead of 32 bit.
The assignment is:
```
though => 5 through => 6 thorough => 8
Thoreau => 7 throw => 3 threw => 1
trough => 9 tough => 4 troll => 2
```
Try it online: <http://ideone.com/Rqp9J8>
[Answer]
# Pyth, 7 bytes
```
et%Cz31
```
I am using the following asignment:
```
though 8
through 3
thorough 1
Thoreau 5
throw 4
threw 7
trough 6
tough 2
troll 9
```
`Cz` interprets the input as a base 256 number. Then, we take this mod 31, subtract 1, and take the result mod 10. Equivalent pseudocode:
```
((base_256(input()) % 31) - 1) % 10
```
[Demonstration](https://pyth.herokuapp.com/?code=et%25Cz31&input=Thoreau&debug=0), [test harness](https://pyth.herokuapp.com/?code=Fz%2Bz.zet%25Cz31&input=though%0Athrough%0Athorough%0AThoreau%0Athrow%0Athrew%0Atrough%0Atough%0Atroll&debug=0).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
C∑⇧11%
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=C%E2%88%91%E2%87%A711%25&inputs=threw&header=&footer=)
Cjam port.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 bytes
```
nH %BÉ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bkggJULJ&input=InRob3VnaCI) | [Test all words](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bkggJULJ&footer=VmdXKfo5ICsiPSAiK1U&input=WwoidGhvdWdoIgoidGhyb3VnaCIKInRob3JvdWdoIgoiVGhvcmVhdSIKInRocm93IgoidGhyZXciCiJ0cm91Z2giCiJ0b3VnaCIKInRyb2xsIgpdLW1S)
---
## Explanation
Takes advantage of the fact that, when parsing a base-`n` string to an integer, JavaScript will stop parsing if it encounters a digit greater than `n` and return the result up to that point. By using base-32 here (digits `0-v`) the `w`s in "threw" and "throw" are, essentially, ignored.
```
nH :Convert from base-32
%B :Modulo 11
É :Subtract 1
```
Here's a breakdown of the formula applied to each word:
| Input | `nH` | `%B` | `É` |
| --- | --- | --- | --- |
| through | 31738067473 | 2 | 1 |
| tough | 31226385 | 3 | 2 |
| troll | 31318709 | 4 | 3 |
| trough | 1002207761 | 5 | 4 |
| though | 991722001 | 6 | 5 |
| thro*w* | 968568 | 7 | 6 |
| thre*w* | 968558 | 8 | 7 |
| thorough | 1015520459281 | 9 | 8 |
| Thoreau | 31735003486 | 10 | 9 |
---
## JavaScript, 22 bytes
A direct translation - doesn't seem worth posting it separately.
```
f=
U=>parseInt(U,32)%11-1
o.innerText=["through","tough","troll","trough","though","throw","threw","thorough","Thoreau"].map(s=>f(s)+": "+s).join`\n`
```
```
<pre id=o><pre>
```
[Answer]
# Python 2, 27 bytes
```
f=lambda w:int(w,34)%444/46
```
With this assignment:
```
>>> for w in "though through thorough Thoreau throw threw trough tough troll".split(): print f(w),w
...
9 though
7 through
3 thorough
8 Thoreau
2 throw
5 threw
6 trough
1 tough
4 troll
```
Several variations are possible, e.g.
```
f=lambda w:int(w,35)/159%10
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 66 bytes
```
h,k;f(char*s){for(h=33;*s;)h^=*s++;h=strchr(k="(Z5qW]2@H",h)-k+1;}
```
[Try it online!](https://tio.run/##PY7LasMwEEXX0lcMAoNkKZAHWbSKoMt@QKGQxAEjxxljx2olhyyMv91RHs7qHLiXmWtnJ2vHEVWtS24x92kQfek8R7Na6TRogQeTBik1mtB5i57XhvHt@v83W359M4ViVsuFHsaq7eCcVy0XtKfkfgrSq/NF2GWmZx26ywmZiuLf5ib9iXrML6/4@uTxwXd7ondNwwZNCSVxJ/D73woMzHXEBj4ipBSUkD8fo5KzJHxCUuxbpuC5p8oUlHxyITQdxhs "C (gcc) – Try It Online")
[Answer]
# Java 8, ~~53~~ 25 bytes
```
s->(s.chars().sum()+2)%11
```
or
```
s->-~-~s.chars().sum()%11
```
Port of *@Optimizer*'s CJam answer, because it (most likely) cannot be done any shorter in Java..
[Try it online.](https://tio.run/##jc@xDsIgEAbgvU9xaWICMZLUtdE3sItuxuFEtCiFhgONMX32itrZkMDA3cf9cMU7Llyv7PV0G6VBItigtq8CQNug/BmlguZz/BZAsm3w2l6AeJ2KQ9ppUcCgJTRgYQUjLdaMhGzRE@OCYsf4fMlnVTXWP97Ho0l8unV3@gRdCp1G7w/If4HbJwXVCReD6FMnGMuskKwMrXfx0pb8@4Z/zmXCLLVL4xTGjFjvHjlKZajsn2Yx74yZ1FAM4xs)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
OS+2%11
```
[Try it online!](https://tio.run/##y0rNyan8/98/WNtI1dDw////SiUZRfml6RlKAA "Jelly – Try It Online")
Boring Jelly port of the fantastic CJam answer.
] |
[Question]
[
*Please note the special scoring for this challenge.*
Given a non-empty string made of `a-z`, output the string immediately before it in the [shortlex order](https://en.wikipedia.org/wiki/Shortlex_order).
**Shortlex order**
We enumerate strings in shortlex order by first listing the strings of length 0, then those of length 1, then length 2, and so on, putting them in alphabetical order for each length. This gives an infinite list of all strings. Said a bit differently, this sorts strings by length, tiebroken alphabetically.
For strings `a-z` as used in the challenge, this list goes (abridged):
```
(empty string)
a
b
c
...
z
aa
ab
...
az
ba
bb
...
zy
zz
aaa
aab
...
```
**Scoring**
Answers will be compared in shortlex order, with earlier being better.
Like in code golf, fewest bytes wins, but there's a tiebreak for same-length answers in favor of coming first alphabetically. This means that you'll want to further "golf" your answer to use characters with lower code points where this doesn't hurt its length. Characters nearer to the start are more important.
For non-ASCII languages, answers are treated as a sequence of bytes. Use the byte order of the code page to compare characters, not their UTF encoding.
For your answer's header, you can just put the code's length and say when you've outgolfed a same-length answer in the same language. You could also put the code's position in shortlex order if that number is not too long.
**Input and output**
The input string will be between 1 and 10 characters long, and consist only of letters `a-z`. As per site defaults, you may do I/O with strings as lists of characters or code points. The letters should be lowercase (code points 97-122).
**Test cases**
The first output is the empty string.
```
a ->
c -> b
z -> y
aa -> z
az -> ay
ba -> az
aaa -> zz
zaa -> yzz
golf -> gole
bzaaaaaaaa -> byzzzzzzzz
zzzzzzzzzz -> zzzzzzzzzy
```
**Related:** [Smaller Strings in Printable ASCII base](https://codegolf.stackexchange.com/q/200967/20260), [Counting in bijective base 62](https://codegolf.stackexchange.com/questions/79304/counting-in-bijective-base-62)
[Answer]
# [Haskell](https://www.haskell.org/), ~~64~~, ~~63~~, ~~56~~, 55 bytes
* `c` is an infinite list of all strings composed of `97..122` in shortlex order.
* `\x y -> last$fst$span(/=x)y` gives the predecessor of `x` in `y`
```
a b=last$fst$span(/=b)c
c=[]:[d++[e]|d<-c,e<-[97..122]]
```
[Try it online!](https://tio.run/##TY3LasQwDEX38xUizCJmkpTOprSMN6X9CuOFktitqR/BdhYJ/fdUTmEyCyHOuVfoG9OPsnYzbgoxwwdm7N6Nnv2QQ4S2Ba/UqEbQRFmlnDaEnltM@axp0oS@fuI9G04DF/JNjJeLUPJ3vLVDo26teH3puufrVcrNofHAYYrGZzifANBaqOnRHOMCNecMOtAmpgy1wwly@PSzI4c0RegYXFGM7ecC6gqrpqoYQUMwEPR3WomWO2FprgeWFI@4LzE@5P/9Q6y7WB7MV7CaFC21O7n9AQ "Haskell – Try It Online")
* 1 byte saved by using code points: `[97..122]` vs. `['a'..'z']`
* 9 bytes saved by [ovs](https://codegolf.stackexchange.com/users/64121/ovs)
* 1 bytes saved by [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni)
## Shortlex optimality
To get the lowest-ordered version of this code:
* Each variable is chosen to be the smallest, front-to-back
* The two lines are sorted (`' ' < '='`)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
ef!-TGrN
```
[Try it online!](https://tio.run/##K6gsyfj/PzVNUTfEvcjv/3@lxEQlAA "Pyth – Try It Online")
Throws an error for input `a`, but outputs nothing to STDOUT, which is technically the correct output.
**Explanation**
```
ef!-TGrN
rN Build a string range from the string '"' to the implicit input
f Filter for strings of this range satisfying:
! - the string becomes empty...
-TG - ...when all lowercase letters are removed
e Take the last element
```
*Note*: `N` was used to start the range rather than `d` or `k` since it has a lower codepoint.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-pl`, ~~29~~ 13 bytes
```
*,$_=*?a...$_
```
[Try it online!](https://tio.run/##KypNqvz/X0tHJd5Wyz5RT09PJf7//0SuZK4qrsRErsQqriQgCWRVAXF6fk7av/yCksz8vOL/ugU5AA "Ruby – Try It Online")
Ironically, this task is essentially the opposite of Ruby's `next` (or alternatively `succ`) method on strings, however this potential `previous` method is not available out of the box. Therefore, to take advantage of existing functionality we have to loop through the range of strings (which is constructed using `succ`) from `"a"` all the way to the input (non-inclusive), and take the last position. Obviously, this will be too slow for the longer test cases.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~67~~ 65 bytes
*Thanks @xnor for helping me get my shortlex score down!*
```
A=lambda B:(C:=B.pop())>97and B+[C-1]or A(B)+[122]if B>[97]else[]
```
[Try it online!](https://tio.run/##TU7dboMgFL6WpyBcYaom7S66mmiifQzjBSquLAgEWDJs@uwO0C37Ljjf3zlBOfuQ4u1d6W1rKk6WYSJJW@J7WbWFkgqnaX27EjEl7am75@de6qTBbXrqzpdLz@akrbvbtafc0K7f2KKkttA4A2apIWeCQiaCLoydmCgBNBmk34qOFlZwIQobq32mmcpivTCKM4tRXqM09W3f4sxYHKpST5kJrqbmi4cDDTb/JULFp2QilseHzo4krCjNhMUzeu7WC3bP37Xq@NCrR@lGYF5DMIZ3AGsYDpBoroBETRwYokG8c0QrWHfmPP2QfA7cTwrB4JMd8aYv7ADrH/YTB9wP "Python 3.8 (pre-release) – Try It Online")
A recursive function that takes in a list of code points, and returns a list of code points.
Note that all spaces are replaced with tabs for smaller shortlex score.
Let `C` be the last character of the string, and `B` be the prefix. If `C == "a"`, then the result is `A(B) + "z"`. If `C != "a"`, then the result is `B + "{C-1}"`.
The base case is when the string is `""` or `"a", in which case the function returns the empty string.
---
Same idea, but this function takes in and returns proper strings.
# [Python 3.8](https://docs.python.org/3.8/), ~~73~~ 72 bytes
```
A=lambda B:B>"a"and[B[:-1]+chr(C:=ord(B[-1])-1),A(B[:-1])+"z"][97>C]or""
```
[Try it online!](https://tio.run/##PUzLasMwEDx3v2LRSSJ2IPTQ1mCDnc8wPsiPNAJbEpIClUK@3ZUtt3PYnRejvbsr@f6pzbrW5cyXfuRvTdFUhBMux7Zpi/zSnYa7odeiVGakTRsNll9YVtOUshMJpGu/Pqprpwwhq1i0Mg6tt3BTBmchJxRy02frRiELQJvh9KOnwWGJC9fUOhMzI3S2189Wz8JRkleEMUAz2ce8VWtqo9RGSEdv5Jn8F7bPv0Z5zL46wlaOeYUwbLeHsD0PfDcD8F1zD/1u8OgcUYCQmI/0W823jcc/IfQxSdg3YyEBwj/SxAH/Cw "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 22 bytes
```
(?=a+$)^a
T`l`zl`.a*$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX8PeNlFbRTMukYsrJCEnoSonQS9RS@X//0SuZK4qrsRErsQqriQgCWRVAXF6fk4aVxKQBQFcVXAAAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
(?=a+$)^a
```
Remove one of the `a`s if all of the letters are `a`s. The lookahead is naturally placed before the anchor as it has a lower ASCII code.
```
T`l`zl`.a*$
```
Cyclically decrement any the trailing `a`s and the previous letter.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes
```
LØaṗṪṖṭƊði’ị⁸
```
[Try it online!](https://tio.run/##y0rNyan8/9/n8IzEhzunP9y56uHOaQ93rj3WdXhD5qOGmQ93dz9q3PH/4e4th9sfNa2J/P8/kSuZq4orMZErsYorCUgCWVVAnJ6fk8aVBGJVAQEA "Jelly – Try It Online")
*-1 byte thanks to Jonathan Allan reminding me of the Cartesian power builtin.*
A ~~new~~ different approach using raw enumeration instead of math. `LØaṗṖL¦ði’ị⁸` is a byte shorter, but doesn't correctly produce the empty string for some reason. It's not quite so efficient as the first solution, so I've abridged the longer test cases...
```
Øaṗ Take the Cartesian product of the lowercase alphabet with itself
L a number of times equal to the length of the input.
Ṫ Take the last element of the product (e.g. "zzzz"),
Ṗ remove its last element ("zzzz" -> "zzz"),
ṭƊ and re-append it to the product.
ð Given that product and the original input,
i find the input's index in the product,
’ subtract 1,
ị⁸ and index back into the product.
Since Jelly uses modular 1-indexing, if the input is the least
string of its length, its index of 1 will decrement to 0, which
then maps it back to the end of the enumeration, which has been
truncated appropriately.
```
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
O_96µJṚ’26*×µS’ḃ26ịØa
```
[Try it online!](https://tio.run/##y0rNyan8/98/3tLs0FavhztnPWqYaWSmdXj6oa3BQObDHc1GZg93dx@ekfj/4e4th9sfNa2J/P8/kSuZq4orMZErsYorCUgCWVVAnJ6fk8aVBGRBAFcVHAAA "Jelly – Try It Online")
There's probably a shorter conversion from bijective base 26 out there, but I figured I may as well write my own before taking someone else's.
[Answer]
# [Factor](https://factorcode.org/), 115 bytes
```
: а ( s -- s ) >array [ 96 - ] map reverse
dup length [0,b] [ 26 swap ^ ] map [ * ] 2map
sum 1 - bijective-base26 ;
```
A naive implementation using `bijective-base26` which does half the work. This solution doesn't work in TIO, because it apparently doesn't include the `html-help` dictionary.
Here's a screenshot from my desktop Factor Listener:
[](https://i.stack.imgur.com/Ju3BI.png)
[Answer]
# JavaScript (ES6), ~~65 64~~ 62 bytes
I/O: array of code points
```
$=>$.reduceRight((A,B,C)=>!C&($=$&&--B<97)?A:[$*26+B,...A],[])
```
[Try it online!](https://tio.run/##XY/BToQwFEX38xW1aZhWoZO40GgsBvgDXRIWpVMYJgydlGoCP491aEG5u3fuu/flnfk374Vuribq1FFOFZsQixHV8vgl5EdTnwzGSZiGGWHxXRZgxFAQRFH69vJM3pPXHN0/Pj2kIaU0KcK8IJORvQEM9IDFQKiuV62krapxhXO71Bf0wq9Y3FwqTlxn9mxiMCFkdT6NbrqaVlpdMreChV04q6bD@z0hu93vGQw5BF4EHA7AYbHBpePjhg@@Zu258dHz8T/nPlBuAnxJrFVzkzfGjTEsTq3aCv5x7Cz9I6WNzYLzIzY2y9cugu6e0zD9AA "JavaScript (Node.js) – Try It Online")
### Commented
```
$ => // $[] = input array, reused for the carry
$.reduceRight( // for each
(A, B, C) => // code point B at position C, using A[] as the accumulator:
!C & // is it the leading 'digit'?
( $ = $ && --B // if the carry is set, decrement B
< 97 ) // and set it again if the result is 96 (just below 'a')
? // if this is the leading 'digit' and the carry is set:
A // leave A[] unchanged
: // else:
[ $ * 26 + B, // prepend B if there's no carry or B + 26 otherwise
...A ], // (which gives 122, or 'z')
[] // initialize the accumulator to an empty array
) // end of reduceRight()
```
[Answer]
# [Python 2](https://docs.python.org/2/), 81 bytes
```
A="";B=1
for C in input()[::-1]:A=chr((ord(C)-97-B)%26+97)+A;B*=C<"b"
print A[B:]
```
[Try it online!](https://tio.run/##PU3BDoIwDL3vKxoSsyHhAAeN0x0G0asXb8YDjClEwpZmROXnccPEl772vbZp7ce1ZshnZRotKKWzFFG0L0RG7gahhG7wYUfH4ivnaXbjUqgWGTPYsDJOd9u0iFf5Jtlt40Tui7UoD1EdEYvd4EBeC36b/VVCXm3Xa7jgqDkBcPgJBUC/tYLwmwSttHVwPJ@OiAZ/CzXq6jnTihKqPCfPKpgqqHpRi5@W/DD9PfS9@yFM/qBf "Python 2 – Try It Online")
72 bytes with lists of code points as input and output:
```
A=[];B=1
for C in input()[::-1]:A=[(C-97-B)%26+97]+A;B*=C<98
print A[B:]
```
[Try it online!](https://tio.run/##lU09D4IwFNz7K95iQJGEYiK0yABEVxe3poNiDUQDpClRfj2@xo@wOJj0Xa9313vdYKq2CceyPavUcZwxS4VM8pSSS6uhgLrB0/XGnQvOfSo5@m7hs8jP57Nw7bFIelmSL9Jiw2LS6boxkImcyxHLCLlX9U3BQfeKEwCjB3sBqIcqwa4klpeqM7Dd77Zat/oVOGl1vI4C24lgDIGGoaXREl4akrcUT6Svj970FawwTilCEFv4fJzEfs2n7A@QTw "Python 2 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~39~~ ~~36~~ ~~35~~ ~~31~~ 26 bytes
*-5 when using codepoints*
```
*/@:=&97}.<:&.(26#.2,-&97)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tfQdrGzVLM1r9Wys1PQ0jMyU9Yx0dIECmv81/6cpGKuVAnUlqnPBmMkIZhWCmYikIhFJPAlZHFlRFTInPT8nDUkPUA4CkJTDgboCAA "J – Try It Online")
### How it works
```
*/@:=&97}.<:&.(26#.2,-&97)
-&97 a->0,b->1,..
26#.2, append 2 and convert from base 26
<:&.( ) execute right side, then decrement,
then inverse of right side
26#.2, convert to base 26 and drop the 2
-&97 convert back to string
*/@:=&97 does input string only contain a's?
}. drop 0 or 1 letters
```
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
a.b.a
a=reverse
b"a"=""
b('a':a)='z':b a
b(a:b)=pred a:b
```
[Try it online!](https://tio.run/##VY5NCsIwEIX3PcUQhLZQe4BC3HgBl4KKvNRUxVglFdEe3jhNSqNvk3xv3vyc0F20Ma473ezD6Nf@bvWBJG0dSlUigbT6qW2nEyUgpBCJylKkFXKZ9mmlCGygUrn0jfxzV5xbnnC35/ZBM4IxlG0zFCqn@YL@F4GkJC4kRBvKeENBQuRMBVM9kJqwH/A9IXy4j@zriAHlA/hJjC3R6YPz/rGON9MMHr86juJgkD@J80Fx0KSwYVQ4Zuc@dWNw7Nx8vVytvg "Haskell – Try It Online") The identifier names are a bit confusing (i.e. `a` appears as the current character, the rest of the string, and as shorthand for `reverse`) in order to use low code points.
Currently beats the [other Haskell](https://codegolf.stackexchange.com/a/206036/56433) answer, though I already submitted an one byte improvement there which will put it into the lead again.
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 35 bytes
```
{`c$97+1_26\-1+26/2,{(~+/x)_x}x-97}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqjohWcXSXNsw3sgsRtdQ28hM30inWqNOW79CM76itkLX0rz2f3WFjpKCrp2Ckk6aQ0WtuoaOlVKikjWQTAaTVUrWSomJIALESgKzwPwqMJmen5MGEgfyIAAkAwdKmlz/AQ "K (ngn/k) – Try It Online")
Strongly inspired by @xash's [J solution](https://codegolf.stackexchange.com/a/206039/75681) - don't forget to upvote it!
[Answer]
# [PHP](https://php.net/), 35 bytes
```
for($a=a;$a!=$argn;$b=$a++);echo$b;
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFQSbROtVRIVbVUSi9LzrFWSgAxtbU3r1OSMfJUk6///0/Nz0v7lF5Rk5ucV/9d1AwA "PHP – Try It Online")
who knew strings incrementing would serve one day? Too bad decrementing doesn't work..
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
āAδã˜s¡нθJ
```
[Try it online](https://tio.run/##AR8A4P9vc2FiaWX//8SBQc60w6PLnHPCodC9zrhK//9iemFh) or [verify all (short) test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/I42O57YcXnx6TvGhhRf2ntvh9V/nf7RSopKOUjIQVwFxIoiTCGIlgVlgfhWYTM/PSQOJQ3hVQKAUCwA). (Times out for any test cases with a length above 5 due to the `ã` builtin.)
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length] (without popping)
A # Push the lowercase alphabet
δ # Apply double-vectorized:
ã # Take the cartesian product
˜ # Flatten this list of lists
s # Swap so the input is at the top of the stack
¡ # Split this list of strings on the input
н # Only leave the first list
θ # And leave the last string of that first list
J # Join (for the edge case 'a', which will result in an empty list [])
# (after which it is output implicitly as result)
```
NOTE: In this solution I'm alternatively able to change the `н` to `ć`/`¬`; `θ` to `¤`; and/or `J` to `»` without changing the functionality. However, all of those would only negatively effect the score, since `нθJ` are earlier in the [05AB1E encoding](https://github.com/Adriandmen/05AB1E/wiki/Codepage).
[Answer]
# SimpleTemplate, 25 bytes
I loved PHP's feature where incrementing `'a'` woud give `'b'`, and incrementing `'z'` would give `'aa'`.
So, since very early in the creating, I've decided to emulate that functionality, but PHP doesn't support *decrementing*.
That had to be implemented manually, a long time ago...
---
Anyway, this is the code for the task:
```
{@incby-1argv}{@echoargv}
```
The code is incredibly simple: Increment all values in `argv` by -1 (decrement) and output it (without a separator).
An ungolfed version of the code isn't much different:
```
{@inc by -1 argv}{@echo argv}
```
(Note: `argv` is the default variable that contains all arguments passed, both to the script as well as to a function. Converting to a function is trivial.)
---
You can try it on: <http://sandbox.onlinephpfunctions.com/code/05d4f13a1d27480d119e516c446b9d001d1111d8>
[Answer]
# perl -M5.010 -nl, 46 bytes
```
$"=a;say/^$"$/?"":do{{$,=$"++;/^$"$/||redo}$,}
```
[Try it online!](https://tio.run/##K0gtyjH9/19FyTbRujixUj9ORUlF315JySolv7paRcdWRUlb2xoiWlNTlJqSX6uiU/v/f2IiVyJXRWUVV0FhYuK//IKSzPy84v@6vqZ6BoYG/3XzcgA "Perl 5 – Try It Online")
Very slow. Starting with `a`, it iterates over all the strings consisting of lower case letters, in shortlex order. If it matches the input, it prints the previous string. Some bytes are wasted to deal with the input of `a`, which should return the empty string.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes
```
{{∧Ẓ∋}ᵐ|b↰}ᶠs[?,.]∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7OmtPL/pfXf2oY/nDXZMedXTXPtw6oSYJKFv7cNuC4mh7Hb1YoNz//9FKiUo6SslAXAXEiSBOIoiVBGaB@VVgMj0/Jw0kDuRBAEgGDpRiAQ "Brachylog – Try It Online")
I expect to be able to outgolf this.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 85 bytes
Works backwards from the end, overwriting the string as it goes along. If the previous digit borrowed (which the first character processed always does), then decrement the current digit, wrapping if required. If the final digit processed wrapped, then return the next character in the string.
```
A,B,C;D(char*E){for(A=1,B=strlen(E);B--;E[B]=(A=C<97)?B?122:0:C)C=E[B]-A;return E+A;}
```
[Try it online!](https://tio.run/##VU5BasMwELzrFYtLipTKJcmlNIodbMevKD3IsuQIHDlo7RYc8vW6EpRAB3aZnVmGUWmn1LIUvOSVOFF1ln5ds5sZPC2yLS8zHH2vHa2ZKNNU1B/lZxac6vD@xo7lcbvb7Tf7ilVZdNJCeD1O3kH9Uoj78mSd6qdWwwHH1g6v55z8k3rbRI1YN8JFWke/BtsyuBGAWATWKEjgsYwAg0o6Q2OS45CsLphweEaWbwRcpxHpiSJj3HitI4GrD7GGJiuELIfwi0yQ@yKJIjORksiZNGEHNofpht7E4w@kmR90fuBHmV52uKTfvw "C (gcc) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 42 bytes
-1 byte, thanks to [@Abigail](https://codegolf.stackexchange.com/users/95135/abigail)!
```
s/(.)(a*)$/$1=~y!b-za!a-y!dr.$2=~y!a!z!r/e
```
[Try it online!](https://tio.run/##PYg7CoAwEAX7vcVCChWSoGDpYTb@EIIJiY1beHTXiODAPIYX5@R7kWwrU1fU1MqqdrhOdJoJSZ84JaO69yFkTHYWIRiBgQiIwZUtxcU1@AVcqQ/gH7hDPLawZ9HRPw "Perl 5 – Try It Online")
## Explanation
Mostly just using Regex here. First, match any character followed by a (greedy match of `0` or more) `a`s. In the replacement, return `$1`, `tr///`anslating (`y///`) chars to those directly preceding them (`/d`eleting any `a`s), followed by `$2`, translating `a`s to `z`s.
This should work for any length input.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
→←xṁOmπ…'a'zΘN
```
[Try it online!](https://tio.run/##yygtzv6fm18enPqoqfH/o7ZJj9omVDzc2eife77hUcMy9UT1qnMz/P7//x@tlKiko5QMxFVAnAjiJIJYSWAWmF8FJtPzc9KUYgE "Husk – Try It Online") Uses a strategy similar to the one in [Kevin Cruijssen's answer](https://codegolf.stackexchange.com/a/206123).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
≔⪪S¹θW›θ⟦a⟧«≔⊟θι←§β⊖⌕βι¿›ιa«↑θ≔υθ
```
[Try it online!](https://tio.run/##RY7BCoMwDIbP@hTFUwrdYdftJIwNYQdBdho7dBo10NVa6zYYPnvXobJADgl/vi9lK23ZSeV9OgzUaCiMIgeZNqMrnCXdABdsG7rn@/jVkkIGJ4vSoYVesGsikxvn7BNHCyDvDPQhTyEf5YHgYHfG2gmWukxX@Ia7YAcsLT5QO6zgSLr67YiHCjdU/w0kWBDM/BV2MfMz0Wocl3mKJ@@llH7zVF8 "Charcoal – Try It Online") Link is to verbose version of code. Vaguely based on @SurculoseSputum's answer. Explanation:
```
≔⪪S¹θ
```
Split the input into characters.
```
W›θ⟦a⟧«
```
Repeat until we only have `a` or nothing left.
```
≔⊟θι
```
Get the last remaining letter.
```
←§β⊖⌕βι
```
Print its cyclic decrement leftwards.
```
¿›ιa«
```
If there is no borrow, ...
```
↑θ
```
... print the remaining list in reverse, ...
```
≔υθ
```
... and clear the list to exit the loop.
] |
[Question]
[
**Story**
So I have a book that I want to separate from my table with nothing but other books. I want to know how many books do I need to achieve this with \$n\$ book lengths.
Here's a visualization that my friend at Wolfram drew for me:

More information about the topic in [Wolfram](http://mathworld.wolfram.com/BookStackingProblem.html) and [Wikipedia](https://en.wikipedia.org/wiki/Block-stacking_problem?wprov=sfla1).
**Challenge**
Given an integer input \$n\$, output how many books needed for the top book to be \$n\$ book length away from the table horizontally.
*or*
Find the smallest integer value of \$m\$ for input \$n\$ in the following inequality.
$$\sum\_{i=1}^{m}\frac{1}{2i} \geq n$$
***Edit:*** for fractions use at least a IEEE single-precision floating point. sorry for editing challenge after posting
([OEIS A014537](https://oeis.org/A014537))
**Test cases**
```
1 4
2 31
3 227
5 12367
10 272400600
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~41~~ ~~40~~ 33 bytes
*1 byte saved thanks to @Dennis*
```
@(n)find(cumsum(.5./(1:9^n))>n,1)
```
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI08zLTMvRSO5NLe4NFdDz1RPX8PQyjIuT1PTLk/HUPN/moap5n8A)
### Explanation
This uses the fact that harmonic numbers can be lower-bounded by a logarithmic function.
Also, the `>=` comparison can be replaced by `>` because harmonic numbers cannot be even integers (thanks, @Dennis!).
```
@(n) % Anonymous function of n
1:9^n % Range [1 2 ... 9^n]
.5./( ) % Divide .5 by each entry
cumsum( ) % Cumulative sum
>n % Is each entry greater than n?
find( ,1) % Index of first true entry
```
[Answer]
# [Python 3](https://docs.python.org/3/), 35 bytes
```
f=lambda n,k=2:n>0and-~f(n-1/k,k+2)
```
[Try it online!](https://tio.run/##VYtBC4IwGEDP@Su@m84mpeJFKIggGJWH8tJJTCcN9Zts6xBif93EDtHxPd7rXuYhMRwrJVtQXMunKjiItpPKgGvNWr/0z1iaG9WIVhjncmJnlmbXdLc/UpgxY8mBJSy9UfhDQuaPF0@lhcTvH7hu6IMHPhmrTZO39zIHpPUmiHG7zrH03pWDnr@qab0MpkYqQBAIjk8hoBBSiEhsLTol0DiV3eMA3hb6aSJxNNhk/AA "Python 3 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
V≥⁰∫m\İ0
```
[Try it online!](https://tio.run/##yygtzv7/P@xR59JHjRsedazOjTmyweD////GAA "Husk – Try It Online")
Since Husk uses rational numbers when it can, this has no floating point issues
### Explanation
```
İ0 The infinite list of positive even numbers
m\ Reciprocate each
∫ Get the cumulative sum
V Find the index of the first element
≥⁰ that is greater than or equal to the input
```
[Answer]
# JavaScript, 30 bytes
A recursive function so it'll crap out pretty early.
```
f=(n,x=0)=>n>0?f(n-.5/++x,x):x
```
[Try it online](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjT6fC1kDT1i7PzsA@TSNPV89UX1u7QqdC06rif3J@XnF@TqpeTn66RpqGiabmfwA)
[Answer]
# Haskell, 38 bytes
```
k!n|n<=0=0|x<-n-1/(2*k)=1+(k+1)!x
(1!)
```
[Answer]
# [Swift](https://swift.org), 65 bytes
```
func f(n:Double){var i=0.0,s=i;while s<n{i+=1;s+=0.5/i};print(i)}
```
[Try it online!](https://tio.run/##Ky7PTCsx@f8/rTQvWSFNI8/KJb80KSdVs7ossUgh09ZAz0Cn2DbTujwjMydVodgmrzpT29bQulgbKGOqn1lrXVCUmVeikalZ@x@k2VCTC0QZQShjCGUKoQwNNP8DAA)
### Ungolfed
```
func f(n:Double) {
var i = 0.0, s = 0.0
while s < n {
i += 1;
s += 0.5 / i
}
print(i)
}
```
[Answer]
# [R](https://www.r-project.org/), 39 bytes
```
function(n){while((F=F+.5/T)<n)T=T+1;T}
```
[Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9PI0@zujwjMydVQ8PN1k1bz1Q/RNMmTzPENkTb0Dqk9n@ahqGB5n8A "R – Try It Online")
Brute Force!
[Answer]
# Javascript (ES6), 34 bytes
```
n=>eval("for(i=0;n>0;n-=.5/i)++i")
```
### Ungolfed
```
n => {
for(i = 0; n > 0; ++i)
n -= .5 / i
return i;
}
```
### Test Cases
```
f=n=>eval("for(i=0;n>0;n-=.5/i)++i")
```
```
<button onclick="console.log(f(1))">Run for n = 1</button>
<button onclick="console.log(f(2))">Run for n = 2</button>
<button onclick="console.log(f(3))">Run for n = 3</button>
<button onclick="console.log(f(5))">Run for n = 5</button>
<button onclick="console.log(f(10))">Run for n = 10</button>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
RİSH:ð1#
```
This is *very* slow.
[Try it online!](https://tio.run/##y0rNyan8/z/oyIZgD6vDGwyV/1srHW5/1LTG/f9/Qx0FIx0FYwA "Jelly – Try It Online")
[Answer]
# Haskell, ~~71~~ ~~49~~ 48 bytes
```
f x=length.fst.span(<x).scanl(+)0$(0.5/)<$>[1..]
```
@BMO saved me a whopping 22 bytes!
[Answer]
# [Julia 0.6](http://julialang.org/), ~~30~~ 27 bytes
```
<(n,i=1)=n>0?n-.5/i<i+1:i-1
```
[Try it online!](https://tio.run/##DcxdCkBAGAXQd6u4ycNMZjA0HuRnIfKgUJ90Sax/OAs4@3vIXIfQKhrpnO7YFwNt5nNpJXWNWBe28wYhxOgMSoPKwE8RcN3C56CKE8L2SNSfaB3raOUSPg "Julia 0.6 – Try It Online")
Only works up to `n = 6`, because Julia has no tail call optimization.
-3 bytes thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis).
[Answer]
# TI-BASIC, 27 bytes
Prompts user for input and displays output on termination. Note: `⁻¹` is the -1 (inverse) token.
```
Input N
1
Repeat 2N≤Σ(I⁻¹,I,1,Ans
Ans+1
End
Ans
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
XµN·zODI›}N
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/4tBWv0Pbq/xdPB817Kr1@//fFAA "05AB1E – Try It Online")
**Explanation**
```
Xµ } # loop until counter is 1
N·z # push 1/(2*N)
O # sum the stack
DI› # break if the sum is greater than the input
N # push N
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
f!>Qsmc1yh
```
[Try it online!](https://tio.run/##K6gsyfj/P03RLrA4N9mwEsg2BgA "Pyth – Try It Online")
Extremely slow.
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
fgscL1STyQ
```
[Try it online!](https://tio.run/##K6gsyfj/Py29ONnHMDikMvD/f2MA "Pyth – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 bytes
The same length as, but slightly more efficient than, the recursive option.
```
@T¨(Uµ½÷X}a1
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=QFSoKFW1vfdYfWEx&input=OA==)
---
## Explanation
```
@T¨(Uµ½÷X}a1
:Implicit input of integer U
@ }a1 :Return the first number X >=1 that returns truthy when passed through the following function
T :Zero
¨ :Greater than or equal to
Uµ :Decrement U by...
½÷X :0.5 divided by X
```
[Answer]
# J, 22 bytes
*-6 bytes thanks to frownyfrog*
```
I.~0+/\@,1%2*1+[:i.9&^
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/PfXqDLT1Yxx0DFWNtAy1o60y9SzV4v5rcnGlJmfkK6QpGMEYxjCG6X8A "J – Try It Online")
## original answer
Luis's answer in J:
```
1+]i.~[:<.[:+/\1%2*1+[:i.9&^
```
## Ungolfed
```
1 + ] i.~ [: <. [: +/\ 1 % 2 * 1 + [: i. 9&^
```
Mostly curious to see if it can be drastically improved (*cough* paging miles)
## Explanation
```
1 + NB. 1 plus...
] i.~ NB. find the index of the arg in...
[: <. NB. the floor of...
[: +/\ NB. the sumscan of...
1 % NB. the reciprical of...
2 * NB. two times...
1 + NB. 1 plus...
[: i. NB. the integers up to
9&^ NB. 9 raised to the power of the arg
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DbVjM/Xqoq1s9KKttPVjDFWNtAy1o60y9SzV4v5rcnGlJmfkK6QpGMEYxjCG6X8A "J – Try It Online")
[Answer]
# PHP, 35 bytes
```
while($argv[1]>$s+=.5/++$i);echo$i;
```
Run it using the CLI:
```
$ php -d error_reporting=0 -r 'while($argv[1]>$s+=.5/++$i);echo$i;' 5
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
```
⌈x/.NSolve[HarmonicNumber@x==2#,x]⌉&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@/9RT0eFvp5fcH5OWWq0R2JRbn5eZrJfaW5SapFDha2tkbJOReyjnk61/y750QFFmXkl0Xk6CkoKunYKSjoKadF5sbE6CtVAIUMgMqiN/Q8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Java 8, 49 bytes
```
n->{float r=0,s=0;for(;s<n;)s+=.5f/++r;return r;}
```
**Explanation:**
[Try it online.](https://tio.run/##LY/NbsIwDMfvewqLU6KMrBx2mcneYFw4Ig6hpJNZ61RJyjShPntx20m2rL8/f775u9/GPvDt@jPVrc8Zvjzx4wWAuITU@DrAYZYATRt9gVpJAVij5EZxsQMwOJh4@/lYe5KrXrOrsIlJYd4z6mycfW/ejEmYQhkSQ8JxwnW@Hy4t1ZCLLxLuka7QCYQ6lkT8fTp7vQLMZNDJKQ6/i1ALhZDJnZmK3A5p73YVkjF6KQEc/3IJnY1Dsb3sKy0rMpsP2JjOspV39P8v4/QE) (Times out for test cases above `n=7`.)
```
n->{ // Method with integer parameter and float return-type
float r=0, // Result-float, starting at 0
s=0; // Sum-float, starting at 0
for(;s<n;) // Loop as long as the sum is smaller than the input
s+=.5f/++r; // Increase the sum by `0.5/(r+1)`,
// by first increasing `r` by 1 with `r++`
return r;} // Return the result-float
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 98 bytes
```
(load library
(d _(q((k # N D)(i(l N(* D # 2))(_(inc k)#(+(* N k)D)(* D k))(dec k
(q((#)(_ 1 # 0 1
```
The last line is an unnamed lambda function that takes the number of book-lengths and returns the number of books needed. [Try it online!](https://tio.run/##FYwxDoMwFEN3TmEpiz8sTdUTIOZcAYWmw1dSoJSF04efzfJ79qnrVfS/18qyxYSiyxGPq2PCzB@Z4RAwCZUFgT0mK54inKnrG1kcB2uDJZMazgbTx1D7GNuHMxvedg/4ym/cMYL@3PASqTc "tinylisp – Try It Online")
### Explanation
The only numeric data type tinylisp has is integers, so we calculate the harmonic series as a fraction by keeping track of the numerator and denominator. At each step, `N` is the numerator, `D` is the denominator, and `k` is the sum index. We want the new partial sum to be `N/D + 1/k`, or `(N*k + D)/(D*k)`. Thus, we recurse with a new numerator of `N*K + D`, a new denominator of `D*k`, and a new index of `k+1`.
The recursion should halt once the partial sum is greater than or equal to `#`, the desired number of book-lengths. At this point, we've gone one book too far, so we return `k-1`. The condition is `1/2 * N/D < #`; multiplying out the denominator, we get `N < D*#*2`, which is the golfiest way to write it.
The recursive helper function `_` does all these calculations; the main function is merely a one-argument wrapper that calls `_` with the correct starting values for `k`, `N`, and `D`.
] |
[Question]
[
# BCD difference
Given an integer n, convert it to BCD ([binary-coded decimal](https://en.wikipedia.org/wiki/Binary-coded_decimal#Basics)) by replacing each decimal digit with its 4-digit binary representation
```
234 -> 0 0 1 0 0 0 1 1 0 1 0 0
```
Then rotate the list of binary digits in order to find the largest and smallest numbers, representable by this list without other rearrangements.
```
max: 1 1 0 1 0 0 0 0 1 0 0 0 (the entire list rotated left 6 times)
min: 0 0 0 0 1 0 0 0 1 1 0 1 (the entire list rotated right 2 times)
```
Convert these numbers back to decimal, treating the list of bits as regular binary and subtract the smallest from the largest:
```
1 1 0 1 0 0 0 0 1 0 0 0 -> 3336
0 0 0 0 1 0 0 0 1 1 0 1 -> 141
3336 - 141 -> 3195
```
The output is the difference of the largest and smallest numbers found.
Test cases:
```
234 -> 3195
1234 -> 52155
12 -> 135
975831 -> 14996295
4390742 -> 235954919
9752348061 -> 1002931578825
```
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~89~~ 88 bytes
*Thanks to Jenny\_mathy for saving 1 byte.*
```
i=IntegerDigits;Max@#-Min@#&[#~FromDigits~2&/@NestList[RotateRight,Join@@i[i@#,2,4],#]]&
```
[Try it online!](https://tio.run/##JcqxCsIwEIDhVwkEgkKkUFyKCCcUwWJFuoYMh4T0hiSQ3FCXvHosOP3D9wfk1QVk@mB7Z4osOhCHRtdHZOddHskTl8uMG8jTTBGkMrLecwp/qb3q4OUKP6mwWRIju4X8ynpK@w1kCKTu9dlqaa1qR1HFLWf87h2G9gM "Wolfram Language (Mathematica) – Try It Online")
This is terribly inefficient, because it generates **n** rotations of the BCD of **n**, which is way more than we need. We can make this is a bit more efficient by saving the result of the `Join@@` in `k` and replacing the `#` at the end with `Length@k`. That lets us generate a scatterplot quite easily:
[](https://i.stack.imgur.com/ejAnA.png)
I'm really intrigued by the contrast of local structure and overall chaos.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
Dd4d2FṙJ$ḄṢIS
```
[Try it online!](https://tio.run/##y0rNyan8/98lxSTFyO3hzpleKg93tDzcucgz@P/RPYfbHzWtcf//38jYREfBEErqKFiam1oYG@oomBhbGpibQASAkhYGZoYA "Jelly – Try It Online")
### How it works
```
Dd4d2FṙJ$ḄṢIS Main link. Argument: n
D Decimal; convert n to base 10 (digit array).
d4 Divmod 4; map each digit d to [d/4, d%4].
d2 Divmod 2; map each [d/4, d%4] to [[d/8, d/4%2], [d%4/2, d%2]].
F Flatten the resulting 3D binary array.
ṙJ$ Take all possible rotations.
Ḅ Convert each rotation from binary to integer.
Ṣ Sort the resulting integer array.
I Take the forward differences.
S Take the sum.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~115~~ 108 bytes
*thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) for -7 bytes*
```
k=''.join(f'{int(i):04b}'for i in input())
v=[int(k[i:]+k[:i],2)for i in range(len(k))]
print(max(v)-min(v))
```
[Try it online!](https://tio.run/##PY3LCoMwFET3@Qpxk3v7Qk3qC/yS4MLa2KapiYgVS@m3p7GFwjAwzGFmeE5Xa5hr7VlWYRg6XVF6uFlloKMvZSZQWEb89KadHQMVKOM1PCZAJHMlVkALVdZbLUpV7xL8Y2NjLhLu0oBGrMkwrmzfLDDjvvfzM6Lzh0QusoX1fpOiSxgn8c9IkR1zFhPOiijj3@iLPErjDw "Python 3 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 153 bytes
```
$b=[char[]]-join([char[]]"$args"|%{[convert]::toString(+"$_",2).PadLeft(4,'0')})
($c=$b|%{$x,$y=$b;[convert]::ToInt64(-join($b=$y+$x),2)}|sort)[-1]-$c[0]
```
[Try it online!](https://tio.run/##TY3RCoIwGEbve4zxhxtqqJmV4QMEXQR1N0boWmrIFnOUkj77EiLo7vsuzjkP9RK6rUTTWAtFRnmVa8qYf1e1xL@HINdli4b5m3Iln0IblqZGnYyuZYldBBfkRWRxzK8HcTM49pzAISOZYeAZFBMGnQf9NHd//FntpUli/E1Nbehd6MgkGodWaUOoHzIfOA2YtXa7XkXLeBMk4Qc "PowerShell – Try It Online")
Stupid lengthy .NET calls to convert to/from binary really bloats the length here. ;-)
We take input as `$args`, wrap it in a string, then cast it as a `char`-array. We loop over each digit, `convert`ing the digit `toString` in base `2` (i.e., turning the digit into a binary number), then `.padLeft` to make it a four-digit binary number. That resulting array of strings is then `-join`ed into a single string and re-cast as a `char`-array before being saved into `$b`.
Next, we loop over `$b`, which just makes sure we loop enough times to account for every rotation. Each iteration, we peel off the first character into `$x` and the remaining characters into `$y` using multiple assignment. Then, we merge them back together into `$b=$y+$x` to move the first element to the end, i.e., effectively rotating the array by one. That's `-join`ed into a string, which is used as the input to the `convert` call to turn the string from binary base `2` into an `Int64`. We then `sort` all of those resultant numbers and store them into `$c`. Finally, we take the biggest `[-1]` and subtract the smallest `[0]`. That's left on the pipeline and output is implicit.
[Answer]
# [Ohm v2](https://github.com/MiningPotatoes/Ohm), 15 bytes
```
€b4Ü. 0\;Jγó↕]a
```
[Try it online!](https://tio.run/##y8/INfr//1HTmiSTw3P0FAxirL3ObT68@VHb1NjE//@NjE0A "Ohm v2 – Try It Online")
Explanation:
```
€b4Ü. 0\;Jγó↕]a Main wire, arguments: a (integer)
€ ; Map the following over each digit of a...
b Convert to binary
4Ü Right-justify w/ spaces to length 4
. 0\ Replace all spaces with zeroes
J Join together binary digits
γó Get all possible rotations and convert back to decimal
↕ Find the minimum *and* maximum rotation
]a Flatten onto stack and get the absolute difference
```
[Answer]
## JavaScript (ES6), ~~118~~ ~~100~~ 99 bytes
```
f=
n=>(g=m=>Math[m](...[...s=(`0x1`+n-0).toString(2)].map(_=>`0b${s=0+s.slice(2)+s[1]}`)))`max`-g`min`
```
```
<input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>
```
Edit: Saved 11 bytes thanks to @RickHitchcock. Saved 1 byte thanks to @ETHproductions. Explanation: The `0x1` prefix causes the input to get reparsed as a hexadecimal number, whose binary is the same as the BCD of the original number with a 1 prefix (I think this is golfier than any other way of padding to a multiple of 4 digits). Excluding the prefix, which is changed from 1 to 0, the resulting string is then rotated at each possible position and converted from binary back to decimal. Finally the maximum and minimum are subtracted.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~115~~ 113 bytes
* Saved some bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).
* Saved two bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).
```
b="".join(format(int(n),"04b")for n in`input()`)
b=[int(b[s:]+b[:s],2)for s in range(len(b))]
print max(b)-min(b)
```
[Try it online!](https://tio.run/##LY7BjoMgEIbvPgWZE2RtIyBVbNxLH8M1Vla6ZaNokKbdp3eh7WUy3@Sb@Wf589fZsm3QF2TscvOYVEPddWZaZue7DoO6mdEbuwLZu/7evaX9uozGY0C7TwTkuDhjPRoa2qbwZesa0qPT/uZsOOrx0GQtSU41AGwq1P3vbCy@zG7qPY6CJSlkuQISZijunN8xZ5KouomKataq/VBNtbYpe3pr8JDr7Y/Go7ZYEdImrz@m/hFwN5k43ULqUT/0N9yvZtToVEVAJ9gYz@P7nEqR0DcIRkWk2FMuElmIktMn5VIeWFBzLrMifxqMCylySWX0woUyO7zcLGOSU1GUJRP/ "Python 2 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 29 bytes
```
Ksm.[\04.Bsd`Q-eJSmi.<Kd2lKhJ
```
[Try it here!](https://pyth.herokuapp.com/?code=Ksm.%5B%5C04.Bsd%60Q-eJSmi.%3CKd2lKhJ&input=234&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0) or [Check out the test suite.](https://pyth.herokuapp.com/?code=Ksm.%5B%5C04.Bsd%60Q-eJSmi.%3CKd2lKhJ&input=234&test_suite=1&test_suite_input=234%0A1234%0A12%0A975831%0A4390742%0A9752348061&debug=0)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 18 bytes
```
§-▼▲mḋUMṙNṁȯtḋ+16d
```
[Try it online!](https://tio.run/##yygtzv6vcGhbrkawzqOmxv@Hlus@mrbn0bRNuQ93dIf6Ptw50@/hzsYT60uAXG1Ds5T///9HGxmb6BhCCB1Lc1MLY0MdE2NLA3MTMBcoYWFgZhgLAA "Husk – Try It Online")
There should be a shorter way to convert a digit into its 4-bit binary representation...
### Explanation
```
§-▼▲mḋUMṙNṁȯtḋ+16d
d Get the list of digits of the input
ṁȯ For each digit...
+16 add 16
ḋ convert to binary
t drop the first digit
MṙN Rotate the list by all possible (infinite) numbers
U Get all rotations before the first duplicated one
mḋ Convert each rotation from binary to int
§-▼▲ Subtract the minimum from the maximum value
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 31 bytes
Full program body. Prompts for number from STDIN. Prints result to STDOUT.
```
(⌈/-⌊/)2⊥¨(⍳≢b)⌽¨⊂b←,⍉(4/2)⊤⍎¨⍞
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qQMCjtgmG5gqPeucqFBRl5pUoADnFmel5mWmZyYlAbkpmemZJsYJGVmlxiUIikFtckJNYqZBZXFyaqsn1qKM97b/Go54Ofd1HPV36mkaPupYeWqHxqHfzo85FSZqPevYeWvGoqykJaInOo95ODRN9I81HXUse9fYBxXvn/Qfq/68ABmlcRsYmXDC2ISoHzrQ0N7UwNoRzTYwtDcxNUKSBGi0MzAwB "APL (Dyalog Unicode) – Try It Online")
`⍞` prompt for line of text from STDIN
`⍎¨` execute (evaluate) each (character)
`(`…`)⊤` encode (anti-base) in the following number system:
`4/2` four binary bits
`⍉` transpose
`,` ravel (flatten)
`b←` store in `b` (for *b*inary)
`⊂` enclose (so that we will use this entire list for each rotation)
`(`…`)⌽¨` rotate (left) by each of the following amounts:
`≢b` length of `b`
`⍳` **i**ndices of that
`2⊥¨` decode each from base-2.
`(`…`)` apply the following tacit function to that
`⌈/` the max(-reduction)
`-` minus
`⌊/` the min(-reduction)
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~37~~ 34 bytes
```
{(⌈/-⌊/)2⊥¨(⍳⍵)∘.⌽⊂,↑(4⍴2)∘⊤¨⍎¨⍕⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqjUc9Hfq6j3q69DWNHnUtPbRC41Hv5ke9WzUfdczQe9Sz91FXk86jtokaJo96txiBBB91LTm04lFvH4iYClRYCzRI4dAKBSNjEwVDCKFgaW5qYWwIAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
DB0;$4¡€ṫ€-3FṙJ$ḄµṀ_Ṃ
```
[Try it online!](https://tio.run/##y0rNyan8/9/FycBaxeTQwkdNax7uXA0kdY3dHu6c6aXycEfLoa0PdzbEP9zZ9P//fyNjEwA "Jelly – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~96~~ 91 bytes
```
->n{r=""
n.digits.map{|d|r="%04b"%d+r}
s=r.chars.map{(r=r[1..-1]+r[0]).to_i 2}
s.max-s.min}
```
[Try it online!](https://tio.run/##LY7LboMwEEX3/grLUaRWAcvPgBfOjyBUESCJF6VocKRUxt9OjdPNaO69Zx7wvP5uN7uVlymAJQRNdHB35xf63c1hHdZkHpm6kuNwgogWC7R/dPCOP8BCwykteXuChrWf1P98OSwSl/JXmaqb4ubHxS/Y4oCEVNhesORGF4j/Ky24znIXXKbWVLqWPEtlzFnstJKGVSozQmqjleEmk2lLzc5vmjFhJNdVXYs0ElG@TMeuf@Cw@gJWPD/TK@QQfNwHDuHW@DYWeHzNY@/ddE8WRILj9gc "Ruby – Try It Online")
* Saved 5 bytes thanks to displayname
[Answer]
# Mathematica, ~~110~~ 99 bytes
```
Max@#-Min@#&[#~FromDigits~2&/@Partition[s=Join@@Tuples[{0,1},4][[IntegerDigits@#+1]],Tr[1^s],1,1]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@983scJBWdc3M89BWS1auc6tKD/XJTM9s6S4zkhN3yEgsagksyQzPy@62NYrH6jIIaS0ICe1OLraQMewVsckNjraM68kNT21CKLJQVnbMDZWJ6Qo2jCuOFbHUAfIU/sfUJSZV@KQFm1pbmpkbGJhYGYY@x8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Python 3, 141 bytes
```
def f(a):a=''.join([format(int(i),'#010b')[-4:]for i in str(a)]);b=[int(''.join(a[-i:]+a[:-i]),2)for i in range(len(a))];return max(b)-min(b)
```
[Try it online](https://repl.it/@alaricwhitehead/BCD)
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~96~~ 89 bytes
```
.
@@@$&
@(?=@@[89]|@[4-7]|[2367])
_
T`E`@
\d
_
.
$&$'$`¶
O`
_
@_
+`_@
@__
s`(_+).*\W\1
_
```
[Try it online!](https://tio.run/##K0otycxL/P9fj8vBwUFFjctBw97WwSHawjK2xiHaRNc8tibayNjMPFaTK54rJME1wYErJgXI1ONSUVNRV0k4tI3LPwHId4jn0k6IdwDS8VzFCRrx2pp6WjHhMYZcXPH//xsaAQA "Retina – Try It Online") Somewhat slow, so link only includes a small test case. Edit: Saved 7 bytes thanks to @MartinEnder. Explanation:
```
.
@@@$&
```
Prefix three `@`s to each digit. (These represent the `0`s of the BCD, but are golfier.)
```
@(?=@@[89]|@[4-7]|[2367])
_
```
Change the `@`s to `_`s (representing the `1`s of the BCD) where appropriate.
```
T`E`@
\d
_
```
Fix up the last digit of the BCD.
```
.
$&$'$`¶
```
Generate all of the rotations.
```
O`
```
Sort them into ascending order.
```
_
@_
+`_@
@__
```
Convert them to unary.
```
s`(_+).*\W\1
_
```
Subtract the first from the last number, ignoring intermediate numbers, and convert to decimal.
[Answer]
# [Haskell](https://www.haskell.org/), 130 bytes
```
r=foldl1
f x=max#x-min#x
f#x|s<-show x=r((+).(2*)).r f.take(sum$4<$s).iterate(drop<>take$1)$do d<-s;mapM(pure[0,1])[1..4]!!read[d]
```
[Try it online!](https://tio.run/##RY7Pb4MgHMXv/BXf/jjAOo2otKWzvWw7LFlPOzbNQiK2pgoGaWay7W93oCa7AO@9z3vhKtqbrKq@rBttLLwIK8KjVrrMAQPODgRIb/aFrvKKogK6fS26RRfUpVp0qFh0P20WtFf95RKD8YqEOH4gJDRQhFbcJG7v9TLNli0JSyuNsBLnRjfZwYdLSpa5htwtPNWiOeLmbuQpeqRncqJhmJ5nMyNFfsrPfS1KBXvw1Cc4zn5Y864ghIt2h6eIu6tSyRb2WQYXaZ@1slLZFiHH7Hbw5uRFGggO4Mqlunjfjw7fV7BawdyHc/8aPFyAIgh9B/DaibqpZLtDCADiJPVgQjnzkk6axZRNhpc0GQTfsG1CByPlfB2PnTTh0SYduDhhnKWc8ol2a9toPTaiKOYJZZvtNmYo@O1dhuh4ABqX0TSF/qt/ "Haskell – Try It Online")
## Explanation / Ungolfed
Since we're going to use `foldl1((+).(2*))` to convert from binary to decimal, we might as well not use `maximum` and `minimum` but rather `foldl1 max` (or same with `min` respectively) and use a short `r = foldr1`.
Now, let us define an operator `f#x` which converts `x` to BCD, generates all rotations, reduce these using `f` and convert it to decimal:
```
f # xs
| s <- show xs
= foldr1 ((+).(2*)) -- convert from binary to decimal
. foldr1 f -- reduce by either max or min
. take (4 * length s) -- only keep 4*length s (ie. all "distinct" rotations)
. iterate (drop<>take $ 1) -- generate infinite list of rotations
$ do d<-s; mapM (pure[0,1]) [1..4] !! read [d] -- convert to BCD
```
Now it's only a matter of using this operator once with `max` and once with `min` and subtracting their results:
```
f x = max#x - min#x
```
[Answer]
# PHP, ~~156~~ 153 bytes
```
<?foreach(str_split($argv[1])as$n)$s.=str_pad(decbin($n),4,0,0);for(;$i<$a=strlen($s);)$r[]=bindec(substr($s,$i).substr($s,0,$i++));echo max($r)-min($r);
```
[Try it online!](https://tio.run/##RYzLDoIwFER/xcVd9IZCiuIrhfghhJgCVZpA27Ro/HrrZeVy5pwZP/mU6tvDBa2GicU13KOfzcpAhee7LTtUESxCLJqNeTWyUQ@9sYxaXnHBBUpaMwmmBrVJsyYYUSKEtmtIpQGLr54Q9RwMFv8kKGcZotTD5HaL@jAImC/bf0CZUrqej/tDdRGn8uv8apyNKbc/)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-x`, 20 bytes
```
®¤ùT4쬣ZéY ì2Ãn äa
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=rqT5VDTDrKyjWulZIOwyw24g5GE=&input=WzksNyw1LDIsMyw0LDgsMCw2LDFdCi14)
Input as an array of digits.
Explanation:
```
®¤ #Map each digit to base 2
ùT4Ã #Pad each one to 4 places
¬ #Join them to a single binary string
¬ #Split them to an array of single characters
£ Ã #For each index Y in that array:
ZéY # Get the array rotated Y times
ì2 # Convert the array from binary to decimal
n #Sort the results
äa #Get the absolute difference between each element
#Implicitly output the sum
```
[Answer]
# Pyth, 24/26 bytes
```
s.+Smi.>Gd2l=Gsm.[\04.Bs
```
Takes input as a quoted string. 26 bytes if it needs to take input as an integer; append `dz` in that case.
[Test Cases (input as strings, 24 bytes)](http://pyth.herokuapp.com/?code=s.%2BSmi.%3EGd2l%3DGsm.%5B%5C04.Bs&input=%22234%22&test_suite=1&test_suite_input=%22234%22%0A%221234%22+%0A%2212%22%0A%22975831%22%0A%224390742%22%0A%229752348061%22&debug=0)
[Test Cases (input as numbers, 26 bytes)](http://pyth.herokuapp.com/?code=s.%2BSmi.%3EGd2l%3DGsm.%5B%5C04.Bsdz&test_suite=1&test_suite_input=234%0A1234+%0A12%0A975831%0A4390742%0A9752348061&debug=0)
[Answer]
# J, 43 bytes
```
3 :'(>./-<./)#.(i.@#|."0 1]),}.#:8,"."0":y'
```
[Try it online!](https://tio.run/##y/r/P03BVk8h2krDTk9f10ZPXzPaSlnPQSNTz0G5Rk/JQMEwFiii41AL5FtZ6CgBhRyUrLhSkzPyFdIUjIxNYExDFDaMZWluChS3MDAz/P8fAA)
Sometimes tacit style makes things difficult. But there's probably a way to do it tacit style that's a lot more concise than this. I think I remember a better way to split a number to digits other than `"."0@":` but I can't seem to recall it...
### Explanation
```
3 :'(>./-<./)#.(i.@#|."0 1]),}.#:8,"."0":y'
y the input (integer)
": convert to string
"."0 evaluate each char (split to digits)
8, prepend 8
#: debase 2
}. behead (remove the 8)
, ravel (flatten)
(i.@#|."0 1]) create a list of rotations
|. ] rotate the list
"0 1 for each number on the left
i.@# range 0 ... length - 1
#. convert rotations back to base 10
(>./-<./) max minus min
```
The prepending and removing 8 is to ensure that the right number of zeroes are present (J will reshape its arrays to be the size of their maximum length element, and 8 is 4 digits in binary so it is used).
[Answer]
# APL(NARS), 34 chars, 68 bytes
```
{(⌈/-⌊/)2⊥¨{⍵⌽a}¨⍳≢a←∊⍉(4⍴2)⊤⍎¨⍕⍵}
```
some little test:
```
h←{(⌈/-⌊/)2⊥¨{⍵⌽a}¨⍳≢a←∊⍉(4⍴2)⊤⍎¨⍕⍵}
h 9752348061
1002931578825
h 0
0
```
[Answer]
# [Perl 5](https://www.perl.org/), ~~97~~ ~~91~~ 89 + 2 (`-F`) = ~~99~~ ~~93~~ 91 bytes
```
$a=sprintf"%04b"x@F,@F;@r=sort{$b<=>$a}map{oct"0b".($a=(chop$a).$a)}(@F)x4;say$r[0]-pop@r
```
[Try it online!](https://tio.run/##DcxBDoIwEEDRq0ywJpAIqQorxHTFzhMYF4VUrYFOMx0SDOHqVhZ/@b43NFRRUZNm9e4zBYYnEpAJhtm6FzACTQ7GaWDrBwNsAgewDtAZeGEUugmerONnspdll8yqPai23oYBiRfRXZqr0Ouo/YI9J7JLinQzaf9GL3RWbK2parO5rIP@CrrLR@7RK4rxdC5/6NmiCzG/VYU8ypi3fw "Perl 5 – Try It Online")
] |
[Question]
[
For the purposes of this challenge, a *polyphthong* is defined as a contiguous slice of a String, that only contains vowels, and has length at least 2. Given a non-empty String as input, your task is to output all the polyphthongs it contains.
For example, `"abeoic"` has the following contiguous slices (space-separated):
```
a b e o i c ab be eo oi ic abe beo eoi oic abeo beoi eoic abeoi beoic abeoic
```
Removing those that contain anything other than vowels, or have length smaller than 2, we get our desired polyphthongs:
```
eo oi eoi
```
---
Your submissions must abide by the following rules:
* You can choose either lowercase or uppercase for I/O, but the output case must match the input case.
* The vowels are `aeiou` (for lowercase) and `AEIOU` (for uppercase). `y` / `Y` is not considered a vowel.
* The input will only contain printable ASCII.
* If a polyphthong appears multiple times, you may choose to output it only once or output all its occurrences.
* Any reasonable I/O format and [method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) is allowed (lists of characters are also fine, for both input and output).
## Test Cases
```
Input -> Output (lowercase)
r67^^()*6536782!87 -> []
programming puzzles and code golf -> []
aaand... i won! -> ['aa', 'aa', 'aaa']
abeoic -> ['eo', 'oi', 'eoi']
yah eioo ala -> ['ei', 'io', 'oo', 'eio', 'ioo', 'eioo']
@yabeeeayio__e -> ['ee', 'ee', 'ea', 'io', 'eee', 'eea', 'eeea']
0ioen0aaiosnjksd -> ['io', 'oe', 'aa', 'ai', 'io', 'ioe', 'aai', 'aio', 'aaio']
```
Note that for test cases 3 and 6, you may output `'aa'` and `'ee'` respectively only once (See the fourth rule).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest submission in bytes in every language wins!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~102~~ 97 bytes
*thanks to @JonathanFrech for -5 bytes*
```
w=input();l=range(len(w)+1)
print{w[a:b]for a in l for b in l if b-a>1<set(w[a:b])<=set('aeiou')}
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9w2M6@gtERD0zrHtigxLz1VIyc1T6NcU9tQk6ugKDOvpLo8OtEqKTYtv0ghUSEzTyFHAcRMgjAz0xSSdBPtDG2KU0s0IAo1bWxBHPXE1Mz8UnXN2v//lRKTUvMzk5UA "Python 2 – Try It Online")
lowercase I/O
[Answer]
# JavaScript (ES6), ~~77~~ 75 bytes
Expects input in lowercase. Outputs unique polyphthongs without repeating.
```
w=>(r=[],g=s=>w.match(s)&&[...'aeiou'].map(c=>g(s+c),s[1]&&r.push(s)))``&&r
```
### Test cases
```
let f =
w=>(r=[],g=s=>w.match(s)&&[...'aeiou'].map(c=>g(s+c),s[1]&&r.push(s)))``&&r
console.log(JSON.stringify(f("r67^^()*6536782!87")))
console.log(JSON.stringify(f("programming puzzles and code golf")))
console.log(JSON.stringify(f("aaand... i won!")))
console.log(JSON.stringify(f("abeoic")))
console.log(JSON.stringify(f("yah eioo ala")))
console.log(JSON.stringify(f("@yabeeeayio__e")))
console.log(JSON.stringify(f("0ioen0aaiosnjksd")))
```
### How?
We recursively build the tree of all possible polyphthongs, pruning branches as soon as the current node is not contained in the input anymore, and saving all matching nodes of at least 2 characters.
```
w => ( // given the input w
r = [], // r = array of results
g = s => // g = recursive function taking s
w.match(s) && // if w contains s:
[...'aeiou'].map(c => // for each vowel c:
g(s + c), // do a recursive call with s + c
s[1] && // if s is at least 2-character long:
r.push(s) // push it into r
) // end of map()
)`` // initial call to g() with s = ''
&& r // return r
```
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~23~~ 20 bytes
```
M!&`[aeiou]+
r!&`..+
```
[Try it online!](https://tio.run/##DccxDoJAEAXQfm5BoUFJNkTjLqWdlScwAl@Z4GDYMYMWe/qV1z3jr0TkTXnp87XY9jew6O9eka1xrsrZfGjbcrf3p6MPzaFoAn1MR8M8SxwJQBycc4QHqzwp4UXntIYZSbTrmGpRjjUgusTpvQx/ "Retina – Try It Online")
This prints all occurrences of a polyphthong.
### Explanation
Retina does have a way to get all *overlapping* matches, but what this really means is that it will look for one match from each position. So if there are multiple matches from the same position, this will only return one of them. The only way to really get all overlapping matches is to use this feature twice, once matching left to right and once right to left (so that we first get the longest possible match from each possible starting position, and then we also get all matches for the possible ending positions).
So the actual program:
```
M!&`[aeiou]+
```
Get all overlapping runs of vowels. What this really means is to get all suffixes of all vowel runs.
```
r!&`..+
```
Now get all prefixes which are at least of length 2, by matching from right to left. The `M` is implicit here, because it's the final line of the program.
[Answer]
# [QuadS](https://github.com/abrudz/QuadRS), 20 + 1 = 21 bytes
```
⊃,/⍵
[aeiou]+
1↓,\⍵M
```
with the `o` flag
[Try it online!](https://tio.run/##KyxNTCn@//9RV7OO/qPerVzRiamZ@aWx2lyGj9om68QAhXz//weL/c8HAA "QuadS – Try It Online")
In order of things happening:
`[aeiou]+` on each match of this PCRE
`,\⍵M` prefixes of the Match
`1↓` drop the first one (which has one one vowel)
`,/⍵` concatenate all the lists of prefixes
`⊃` disclose (because reductions `/` enclose)
---
This is equivalent to the Dyalog APL tacit function:
```
{⊃,/⍵}'[aeiou]+'⎕S{1↓,\⍵.Match}⍠'OM'1
```
[Try it online!](https://tio.run/##Jc49CsJAEAXg3lOM1fobjWKS0guIhaV/jMkmrq47IVEkipWQQogIYu8lvNBeRJfYPb43Aw9j2Q4ylBR9v6HOH2d9u7Y6uvhc2BS5oMO8yfT9NTnbOn@2ZqawRrj31xddvNl4xGzzBixx3MWiVm84g77jer2q57KK4TihKMHdTqgI4sPpJHkKqALwKeAQkQzLK0RjlmWBgCOp6t9WnIRfxgzXYIYQoMQShplpOcdM0HLJS@oK4qqLKChVm20asB8 "APL (Dyalog Unicode) – Try It Online")
[Answer]
# Mathematica, 92 bytes
```
Select[Join@@Partition[r,i,1]~Table~{i,2,Length[r=(S=Characters)@#]},SubsetQ[S@"aeiou",#]&]&
```
[Try it online!](https://tio.run/##BcGxCsIwEADQXwkpFIUM1T0QcBOHStxChmu8mtM2geQ6if31@N4KHHEFpgBtFlo0iwsGdtdMyZgRChNTTq4oUie/P2BacP@SOqsbphdHV/TB6kuEAoGx1KPp/E/ZbarId2eNBKS8SdX53vdtLJRYmNnJgTKmAYByTe9PfUrf/g "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~138~~ ~~135~~ 134 bytes
```
s->{String e,x="";for(int i=0,j,y=s.length();i<=y;i++)for(j=y;j>i;x+=e.matches("[aeiou]{2,}")?e+" ":"")e=s.substring(i,j--);return x;}
```
[Try it online!](https://tio.run/##NY8xb4MwEIX3/IqTJ7uAVXWsA926dcoYZTDESc4BG@FzBEL8duom9JY7vft0957VD1343jh7vq/Y9X4gsEmTkbCVl@gaQu/km@pj3WIDTatDgB@NDuZdIE1J@96o/YEGdNccXr2CEUpYQ1HNLwFMPpaMqYsfODoCLN9zm09lkK1xV7pxoXBfTgqzTPwxNs22QjVmpZGdpuZmAmdHbdDH0/yRL0x8mYwB@2RMmHQmxDo8P3HMbVEINRiKg4NRLet/gM3zw@MZuhSDv7wdT6BFigRbHaZAppM@kuzTnvgodd@3E2e6Nh4bJoR6wstuWX8B "Java (OpenJDK 8) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~34~~ 29 bytes
```
(*/@e.&'aeoui'*1<#)\\.#&,<\\.
```
[Try it online!](https://tio.run/##RYpBCoMwEADvfcUWwaiU1LZUPVjwIaJsdRNjNSuKB/182kvxNDAzvXPqJSGIrgVJXyDxakR0y72wLKXnX/IfHDUdgwIxJ2lVBWGUPB9Jmt3PWSpO/zbNrGccR2M1TOu@D7QA2hYabgk0D@pYN@yADDPggIctNnwTEW6G65oOHxsmGyMaXmz/WVrhvg)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ẆḟÐḟØcḊÐf
```
[Try it online!](https://tio.run/##y0rNyan8///hrraHO@YfngAiZiQ/3NF1eELa/8Ptkf//Jyal5mcmAwA "Jelly – Try It Online")
# Explanation
```
ẆḟÐḟØcḊÐf Main Link
Ẇ Get all (contiguous) sublists
Ðḟ Filter; remove all elements where the result is truthy:
ḟ Øc Filter; remove all vowels; if it's truthy, then it contains non-vowels
Ðf Filter; keep elements where the result is truthy:
Ḋ Dequeue; return all but the first element (truthy if the length was at least 2)
```
-4 bytes thanks to Mr. Xcoder
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 104 bytes (99 bytes with lowercase only or uppercase only)
Yeah, it leaks - so what?
```
#include<string.h>
a;f(char*s){*s&&f(s+1);for(a=strspn(s=strdup(s),"AEIOUaeiou");a>1;)s[a--]=0,puts(s);}
```
[Try it online!](https://tio.run/##dc/BToNAEAbge59iikmzi4VQjdAE2@jBgydPnmrbjMsCq7BLdiCGNn12XPSgF24z@b@ZzIigEGIYrpQWVZfJe2qt0kVYbmeY5kyUaH3iZ58Wi5zR9YqnubEMN45RoxmNRdY1jPjSe3x6fnlFqUzn8RS3q5TTDoNgv4mWTdeSM@llULqFGpVmfHaeAcBP4u3cxNjlzLNxcjgw7sd3t3GyvpmvE5f9qv2b/gcbawqLde3OdVtOp0oSoM5AmExCYap8Yg7RqTAMQcGX0fMp9S6NEhNhjyW4Pw1ghRPkoXcbpMRemeNRTqBIGakjRGVIf3xS9sdGcxm@AQ "C (gcc) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 137 bytes
*outgolfed by [Mark](https://codegolf.stackexchange.com/a/147847/67312)!*
```
function(S)(x=unlist(sapply((s=el(strsplit(S,"[^aeiou]")))[nchar(s)>1],function(x)substring(x,1:(n=nchar(x)),rep(n:1,e=n)))))[nchar(x)>1]
```
[Try it online!](https://tio.run/##RcxBCsIwEEDRvacoWc1AXHRbjJfosihMa2oDcRIyCaSnjxVB9/@/1LybE6UdXjZv4SF4WrvLua2Fl@wCw4hQTWHvJINQjH4HEGM9SE4SvcswajXdybpQbgoRJ142SiB47W/6x1SUMh@L4ydU3Q/A5ttVRJ1sBB56bQ0j/on6IdoKaqetO/zQkSeF7Q0 "R – Try It Online")
```
function(S){
s <- el(strsplit(S,"[^aeiou]")) # split on non-vowels
s <- s[nchar(s)>1] # vowel groups of length at least 2
p <- function(x){ # generates all substrings of inputs
n <- nchar(x)
start <- 1:n
stop <- rep(n:1, n) # this will generate dups
substring(x, start, stop)
}
q <- unlist(sapply(s, p)) # all substrings
q <- q[nchar(q)>1] # all length-2 or more substrings
}
```
[Answer]
# Perl 5, 53 +1 (-p)
```
/[aeiou]{2,}(?{$h{$&}++})(?!)/g;$_=join$",sort keys%h
```
[Try It Online](https://tio.run/##K0gtyjH9/18/OjE1M780ttpIp1bDvlolo1pFrVZbu1ZTw15RUz/dWiXeNis/M09FSac4v6hEITu1slg14/9/h8rEpNTU1MTKzPz4@NR/@QUlmfl5xf91CwA)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~93~~ 88 bytes
```
param($a)0..($b=$a.count-1)|%{($i=$_)..$b|%{-join$a[$i..$_]}}|?{$_-match'^[aeiou]{2,}$'}
```
[Try it online!](https://tio.run/##DcjRCoMgFADQf4k7UpjS9h77EHFyc4K28oYWezC/3fV4zkY/l7J3y9LahglXBsgHKRlMI6C0dMRdPPh5KwzCCIZLCdMlMVOIgArCFUbXer4KGLHibn3/VugCHbo87xX62lpjynpMSutuCOTigBgox/mbPx3/Aw "PowerShell – Try It Online")
Uses lowercase or uppercase I/O (or a mix!).
Borrows code from my answer on [Exploded Substrings](https://codegolf.stackexchange.com/a/78712/42963) to get all the substrings, then pulls out those that regex `-match` against `^[aeiou]{2,}$` -- i.e., those that are at least two vowels in length and only vowels. Those strings are left on the pipeline and output is implicit.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
Œʒg≠}ʒžMм_
```
[Try it online!](https://tio.run/##ASkA1v8wNWFiMWX//8WSypJn4omgfcqSxb5N0Lxf//9AeWFiZWVlYXlpb19fZQ "05AB1E – Try It Online")
**Explanations:**
```
Œʒg≠}ʒžMм_
Œ Push all substrings (abeoic => a, b, e, ..., eoi, eoc, ... abeioc)
ʒ } Filter elements for which result is 1
g≠ Push 1 if length is != 1, 0 otherwise
ʒ Filter elements for which result is 1
žMм Remove all occurences of 'aeiou' from element
_ Negative bool: push 1 if length == 0, 0 otherwise
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~148~~ ~~137~~ ~~130~~ ~~123~~ 118 bytes
*Thanks to @Laikoni for -11 bytes, further -7 bytes by pointing me to golfing tips, another -7 bytes, and yet another -5 bytes, for a total of whopping -30 bytes.*
~~This looked like a good fit for Haskell but the result doesn't seem to agree.~~ I guess Haskell was an OK-ish choice after all. I'm still annoyed by the way `subsequences` works though.
```
import Data.List
v=(`elem`"aeiou")
p s=nub$do x<-groupBy((.v).(&&).v)s;[y|y@(c:_:_)<-subsequences x,v c,y`isInfixOf`x]
```
[Try it online!](https://tio.run/##FY/BaoNAFEX38xWTUIKWZAgt1ZBGCaWbQqAfUBp96tO8RudNHbVO6L9buzrcs7hwLmCvWNfTRI3htpOv0IE6ke3EEHkp1tikS0DifukLI22k@@yuYDkeNlXLvXlxnqcGX3mrlT/TPn@4X3f08n2yT/zDxvaZxe8edY5WjutB5muXkn3TJY3vZTp@Tg2QjirsTqQxjiPTku6UieN/P7VBeD57/n3w9BiEu4fFLhSm5aqFpiFdSdPfbvV8DLqQORcoK65LATBvpZQk@cN6ISBDplw4uMi5gyXUII5utojgiJMExZYY9RaA2Oqvqy3@AA)
[Answer]
# Perl, 45 bytes
```
local $,=" ";print $_=~/(?=([AEIOU]{2,}))/ig;
```
[Answer]
# [R](https://www.r-project.org/), ~~120 bytes~~ 110 bytes
```
function(x){k=nchar(x);i=k:1;e=expand.grid(i,i[-1]);grep("^[aeiou]+$",mapply(substr,x,e[,2],e[,2]+e[,1]),v=T)}
```
[Try it online!](https://tio.run/##bY/BboMwEETv/QrH6sFuDEpSFaIipH5EbwiiDSxkC9iWgRZS9dupq165jHY1b6QZt9bpWk@6HMloMcvvNtXlDZw/E0rb12OCKc4WdBU2jipBirLgmMukcWgFLzJAMlO@f@SqB2u7RQzTdRidmhVm6pT/696rD6nP9F3@rLXgLoqLQsin6OU5is@n3Tnm8sE60qPgQRD4x0PWmcZB35NumJ3u9w4H5ouw0lTIGtPVGxmAv6phyIh9Gb3bIq5oqNwwFrgxP8Yw6GDDflt8EhEWMpcLbgAHMqgPAGQG/dEOFZfrLw "R – Try It Online")
How it works
```
function(x){ #initalize the anonymous function where input is stored in x
k=nchar(x) #set k to the number of characters in x
i=k:1 #create vector of integers from k to 1
e=expand.grid(i,i[-1]) #create matrix of full outer join on i
#except in the second column, limit i to being less than k
grep("^[aeiou]+$", #search for strings made of only vowels
mapply(substr, #map the substring function
x, #with x as the string to subset
e[,2], #start at the second column of the outer join
e[,2]+e[,1] #end at the sum of the sum of the first and second columns
),
v=T #if a match is found, return it's value
)
} #by default, R returns the last line of a function
```
[Answer]
# C, 119 bytes
```
f(char*s){*s&&f(s+1);char*t,*b=calloc(strlen(s),1);for(t=b;*s==65|*s==69|*s==73|*s==79|*s==85;b[1]&&puts(b))*t++=*s++;}
```
[Try it online!](https://tio.run/##fdBdT4MwFAbg@/2KjgvSlkGcCx@GkFhHnVVGF4gxzLkFiOgSBEPxau63Ix9emeDVm573OeeiqfqWpk2TwfQ9rrBAJyxkOYNCmSO7H9UznDhpnOdlCkVd5a8FFGjWtllZwdpJbCwcx9C/@7jqw1wMMbws3U6e5y@y/PlVC5gghGtFcbBQFPvcHIsafMTHAqLJaQIA6I2kququkJDdTTIoBYa530OEDX1hmNbl1DLbbpC74o/dBHwVkPWa@SuwedxuPRoC4rtgyV0KVty7HV8lpIWapgEGnrg//QfeUM6W431E7gBlnAPikXF1HbV3KCUR44cDHXcXjFO/JITx0L9/CN1OVu2/Zb@2k@fmBw)
[Answer]
# JavaScript (ES6), 105 bytes
```
s=>eval('a=[];l=i=s.length;while(i--){j=l;while(j--)if(/^[aeiou]{2,}$/.test(t=s.slice(i,j)))a.push(t)}a')
```
Probably has a lot of golfing left to do.
```
let f=
s=>eval('a=[];l=i=s.length;while(i--){j=l;while(j--)if(/^[aeiou]{2,}$/.test(t=s.slice(i,j)))a.push(t)}a')
console.log(JSON.stringify(f('r67^^()*6536782!87')))
console.log(JSON.stringify(f('programming puzzles and code golf')))
console.log(JSON.stringify(f('aaand... i won!')))
console.log(JSON.stringify(f('abeoic')))
console.log(JSON.stringify(f('yah eioo ala')))
console.log(JSON.stringify(f('@yabeeeayio__e')))
console.log(JSON.stringify(f('0ioen0aaiosnjksd')))
```
[Answer]
# [Perl 5](https://www.perl.org/), 44 + 1 (`-n`) = 45 bytes
```
map{say}/(?=([aeiou]{$.}))/g while$.++<y///c
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saC6OLGyVl/D3lYjOjE1M780tlpFr1ZTUz9doTwjMydVRU9b26ZSX18/@f9/h8rEpNTU1MTKzPz4@NR/@QUlmfl5xf91fU31DAwN/uvmAQA "Perl 5 – Try It Online")
[Answer]
# C, ~~105~~ 75 bytes
A function accepting a pointer to lowercase input, and producing space-separated strings on standard output:
```
i;f(char*p){for(i=strspn(p,"aeiou");i>1;)printf("%.*s ",i--,p);*p&&f(p+1);}
```
### Test program
```
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 1; i < argc; ++i) {
char *in = argv[i];
printf("'%s' -> [ ", in);
f(in);
puts("]");
}
}
```
### Demo
```
'r67^^()*6536782!87' -> [ ]
'programming puzzles and code golf' -> [ ]
'aaand... i won!' -> [ aaa aa aa ]
'abeoic' -> [ eoi eo oi ]
'yah eioo ala' -> [ eioo eio ei ioo io oo ]
'@yabeeeayio__e' -> [ eeea eee ee eea ee ea io ]
'0ioen0aaiosnjksd' -> [ ioe io oe aaio aai aa aio ai io ]
```
### Explanation
```
#include <string.h>
#include <stdio.h>
void find_polyphthongs(char *p)
{
/* from longest polyphthong substring down to 2 */
for (int i = strspn(p,"aeiou"); i >= 2; --i) {
/* print exactly [p .. p+i] */
printf("%.*s ", i, p);
}
/* tail-recurse to next char */
if (*p) {
find_polyphthongs(p+1);
}
}
```
Using GCC on Debian Linux, I seem to get away with the incompatible implicit declarations of `strchr()` and `printf()`. Other platforms may require `<stdio.h>` and `<string.h>` to be included.
[Try it online](https://tio.run/##XVDbTsMwDH3vV3hFsKRbKgpiQyqb@Ase0EAmTTtDm0RJB9qm/TohHTeBX@LjnGMfW4pGyhCorJlco8ss39fGMVr43nmrmZ2mqMhsUl7Ssii5daT7mqWneeYhnZIQU8vLzJ6d1cxOCl4ewglp2W4qBTe@r8jk62WSJFEFHZJmQ4KukVMY5kGWRfDKk30CMeJoODIIFlCUEN@bIzumkwlx@KQN8akmHYlDh3talT9/3ybHp34MYgn30SmQ5r@Mmv2BdtN7lq7Sr9IhOYTgZvOHB8az2dXlbH59MbqeB@tM47DrSDdRstu1ygPqCqSJ2zamrQNixHmeR@NvRo8CPilDMmxxDfGKBrDFcLuNVaVwS@bxUYVzMkqfI5Lx@vnFV@@ybrHxQcTrLWRRBNGhk@uFxp5eVRB32gjqbEuSehH3/FepN1r2ZLSolGzR4ZB/AA "C (gcc) – Try It Online") (requires Javascript).
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 53 bytes
This is a `Dfn` (**d**irect **f**unctio**n**). Usage is `p '<argument>'`. Fair warning: this is not very efficient and times out for `input > 8 characters` on TIO, but works normally when given enough time.
```
p←{(G∊⊃,/⌽,\∘⌽¨,\⌽⍵)/G←⊃,/{(,v∘.,⊢)⍣⍵⊢v←'aeiou'}¨⍳≢1↓⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v@BR24RqDfdHHV2Pupp19B/17NWJedQxA0gfWgFk9ex91LtVU98dqAosX62hUwaU1tN51LVI81HvYqAskFUGlFZPTM3ML1WvPbTiUe/mR52LDB@1TQbK1gKtUE9MSs3PTFYHAA "APL (Dyalog Unicode) – Try It Online")
Thanks to @Adám for 16 bytes!
### How it works:
This is easier to understand if we break the code in smaller portions:
* Part 1 - `G←⊃,/{(,v∘.,⊢)⍣⍵⊢v←'aeiou'}¨⍳≢1↓⍵`: This part of the function takes the length of the (right) argument and mixes the vector `aeiou` to itself that many times, yielding every possible combination of `[2, length(right arg)]` vowels.
* Part 2 - `(G∊⊃,/⌽,\∘⌽¨,\⌽⍵)/`: This part checks which element(s) of G are members of the substrings of the input. This returns a boolean vector, with `1`'s at the indices of the vowel combinations that are present in the input and `0`'s where they're not. The resulting vector is then mapped (`/`) over `G`, returning the elements corresponding to the truthy values.
The whole thing is then assigned to `p`. `p←` is not included in the byte count because it's not *necessary*, it just makes using the function easier.
[Answer]
# [Haskell](https://www.haskell.org/), 74 bytes
```
f[]=[]
f(h:t)=filter(all(`elem`"aeiou"))[h:take i t|i<-[1..length t]]++f t
```
[Try it online!](https://tio.run/##HY5dTsMwEITfOcXWTzalVgGRVKiRuAAnsNx2adbJEv9EiSuUiruHhLeZb0aaaXHsyPt5dsZWxj442b5nVTn2mQaJ3ssLeQoXgcTpJpQyS44dAUP@5ePOPGvtKTa5hWztdusgzwE5QgUB@0@Q/cAxgwanwIihKE8nqR6Lt9eiPLxsDqV4AtEPqRkwBI4N9Lf73dMIGGu4ppqgSd6tJcQFaa2X4Z8UN//oixJfVzVhC8u/BOhx9R/TkhHhxOl8ppXsOVHcI3Ia43c31sLOfw "Haskell – Try It Online")
[Answer]
# Ruby 2.4, 100 bytes
```
(2..(b=(a=gets).size-1)).to_a.flat_map{|i|(0..(b-i)).to_a.map{|j|a[j,i]}}.select{|k|k=~/^[aeiou]+$/}
```
This is my first attempt at golfing, and I'm sure there are lots of ways to shorten this code.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 80 bytes
```
->s{[*0..z=s.size-2].product([*2..z]).map{|v|s[*v][/[aeiou]{2,}/]}.uniq.compact}
```
[Try it online!](https://tio.run/##fZLLcuJADEX3fIVSszBQTociFciG1HzE7FxOSrQF1mC3PO42xDy@nbQfJMwkGS/kUl/dI/WjrJb1ebU43z7ZQzSeKLVfWGV5T7fTWBWlJJV2w2g89UI8UjkWh@P2aKPxNo7uIiSWKj5Mw9NdfFKV4T9KS16gdqfzYQAQlLP58/NwNJ493M/mj9Obx3kA/3yLJ4jisCn23dYl5jmbNRTVfp@RBTQJaEkI1pKtgqtiRC8ppYBhJ@bmE7Yn@7oghPeIQe9ekrD@yvS3m6TxCTfRO3p3jSn4nQtghsH/3K2PO0YbqUv4PZMe@bP2IxFhzfLyQsH3SGqNXcQPPF0E7LPLTicsZCaILNb83tgk@AbcT0lXp3U1PV8E7hTps3b800AR6hQSgeMm3B592wJW0SYekEkGP@BXSrCqjHYsBkrKZesvNqmKjDU6siFYAXaQYw1Gmr/zMHr1ryirYccuBecJ9FqQdpR4gq0yZ2FYGf9CbCte1rqiKzg4gSX1XZMQ2MAuZc/XaKnpuuMsG6nzGw "Ruby – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
f&tT!-T"aeoi".:
```
[Try it online!](https://tio.run/##K6gsyfj/P02tJERRN0QpMTU/U0nP6v9/pcrEDIXUzPx8hcScRCUA "Pyth – Try It Online")
Definitely golfable, I want to get it better before writing out explanation.
---
[Answer]
# T-SQL (SQL Server 2014), 281 bytes
```
;with s as(select substring(@,1,1)C,stuff(@,1,1,'')D,1 R union all select substring(D,1,1),stuff(D,1,1,''),R+1from s where len(D)>0),c as(select R i,C w from s where C LIKE'[aeiou]'union all select R,w+C from c join s ON i+1=R where s.C LIKE'[aeiou]')select w from c where len(w)>1
```
Input give by
```
declare @ varchar(max) = 'abeoic'
```
Uses a common table expression `s` to blow the input apart into ordered individual letters, and then a second common table expression `c` to generate all ordered combinations, throwing out non vowels.
[SQL Fiddle](http://sqlfiddle.com/#!6/9eecb7db59d16c80417c72d1e1f4fbf1/11226)
[Answer]
# PHP, 139 bytes
```
function y($s){$p=[];$l=strlen($s);for($i=2;$i<=$l;$i++)for($j=0;$j<=$l-$i;$j++)strspn($a=substr($s,$j,$i),'aeiou')==$i&&$p[]=$a;return$p;}
```
[Online demo](http://sandbox.onlinephpfunctions.com/code/c66cbf34f38a032ecb4b4cd355d79c550afdcd80)
```
function yreadable($s)
{
$p = [];
$l = strlen($s);
for($i=2; $i<=$l; $i++)
for($j=0; $j<=$l-$i; $j++)
strspn($a=substr($s,$j,$i),'aeiou')==$i
&& $p[] = $a;
return $p;
}
```
## How it works
Select sub-strings (beginning with the length of 2) consisting of adjacent characters and move along string.
Collect any sub-strings that only contain vowels. Repeat with longer sub-strings.
For string 'abcdef' these are the substrings generated and checked:
```
'ab','bc','cd','de','ef'
'abc','bcd','cde','def'
'abcd','bcde','cdef'
'abcde','bcdef',
'abcdef'
```
[Answer]
# [Vyxal 2.6.0pre1](https://github.com/Vyxal/Vyxal/releases/tag/v2.6.0pre1) , 6 bytes
```
K~Ḣ'AA
```
No TIO link yet.
```
K # Substrings
~Ḣ # Filtered by a[:1] exists (len(a) > 1)
' # Filtered by...
A # All...
A # Are vowels.
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
K'Ḣ;'kv↔=
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=K%27%E1%B8%A2%3B%27kv%E2%86%94%3D&inputs=abeoic&header=&footer=)
```
K # Substrings
' ; # Filtered by...
Ḣ # a[1:] is nonempty
' # Filter again by...
↔ # Removing everything but...
kv # Vowels
= # Leaves it identical to the original.
```
] |
[Question]
[
Continuing my [*It was just a bug*](https://codegolf.stackexchange.com/questions/129523/it-was-just-a-bug) challenge:
### Input:
A string consisting of printable ASCII characters without white-spaces nor new-lines.
### Output:
First turn the input into a palindrome by reverting the input, and adding it before itself, excluding the middle character (i.e. with an input `1234567890`, it will becomes `0987654321234567890`).
And then output this text:
```
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0987654321234567890
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
```
(From the middle outward in both directions, each character is separated by one more space than the previous line.)
## Challenge rules:
* You need to print twice the length of the input, minus 3 lines. So with the input `1234567890`, the output displayed above is 17 lines (length 10 \* 2 - 3).
* The input will only contain printable ASCII (excluding space, tab and new-line).
* Trailing spaces are optional.
* A single trailing new-line is optional.
* (Additional) leading spaces or leading new-lines are not allowed.
* You can assume the input will always be at least four characters long.
* Unlike my *It was just a bug* challenge, both the input and output formats are flexible. So you are allowed to output the result as a String-array, String-list, etc.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
## Test cases:
```
Input: 1234567890
Output:
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0987654321234567890
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
Input: ABCD
Output:
D C B A B C D
D C B A B C D
DCBABCD
D C B A B C D
D C B A B C D
Input: =>)}]
Output:
] } ) > = > ) } ]
] } ) > = > ) } ]
] } ) > = > ) } ]
]})>=>)}]
] } ) > = > ) } ]
] } ) > = > ) } ]
] } ) > = > ) } ]
Input: XXxxXX
Output:
X X x x X X X x x X X
X X x x X X X x x X X
X X x x X X X x x X X
X X x x X X X x x X X
XXxxXXXxxXX
X X x x X X X x x X X
X X x x X X X x x X X
X X x x X X X x x X X
X X x x X X X x x X X
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~22~~ 21 bytes
```
¬Å£¬qYîÃy w ê y w ê ·
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=rMWjrHFZ7sN5IHcg6iB5IHcg6iC3&input=ImFiY2RlIg==)
### Explanation
The first 8 bytes generate the bottom-right quadrant of the pattern:
```
¬ Å £ ¬ qYîÃ
Uq s1 mXY{Uq qYî}
Uq : Split the input into characters.
s1 : Slice off the first.
mXY{ } : Map each item X and index Y to
Uq : the input split into chars,
q : joined with
Yî : Y spaces.
```
At this point we have an array of e.g. `["ABCD", "A B C D", "A B C D"]`. Unfortunately, it takes 13 bytes to square this:
```
y w ê y w ê ·
y w ê y w ê qR
y : Pad each line to the same length with spaces and transpose.
w : Reverse the array, and
ê : palindromize. Now we have the bottom half of the output transposed.
y : Transpose back.
w ê : Reverse and palindromize again, giving the full output.
qR : Join with newlines.
: Implicit: output result of last expression
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~149 141~~ 95 bytes
```
def f(s):l=len(s)-1;[print((' '*abs(i)).join(s[:0:-1]+s).center(2*l*l+1))for i in range(1-l,l)]
```
[Try it online!](https://tio.run/##VYxLDoIwFAD3nKK7vgdCKPjFuPBziCaEBWirNS@FtCzw9LWJK3eTmWSmz/wabR3CQ2mmwWNDJ1I2Qi6O7eSMnQE442k/eDCIxXs0sbZN2eSiyzwWd2Vn5aBKKaVMIOrRMcOMZa63TwUipxVhFzTw8@V645j8pphEI@WySPnvRFWvN9vd/lByDF8 "Python 3 – Try It Online")
Thanks to @KevinCruijssen and @ETHproductions for saving some bytes
***Special thanks to @notjagan for saving 46 bytes!***
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
g<F¹RSðN×ýû})Rû.c
```
[Try it online!](https://tio.run/##ASsA1P8wNWFiMWX//2c8RsK5UlPDsE7Dl8O9w7t9KVLDuy5j//8xMjM0NTY3ODkw "05AB1E – Try It Online")
-1 thanks to [kalsowerus](https://codegolf.stackexchange.com/users/68910/kalsowerus).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
E⁻Lθ¹⪫θ× ι‖O←↑
```
[Try it online!](https://tio.run/##ATkAxv9jaGFyY29hbP//77yl4oG777yszrjCueKqq864w5cgzrnigJbvvK/ihpDihpH//zEyMzQ1Njc4OTA "Charcoal – Try It Online")
AST:
```
Program
├Print
│└E: Map
│ ├⁻: Difference
│ │├L: Length
│ ││└θ: Identifier θ
│ │└1: Number 1
│ └⪫: Join
│ ├θ: Identifier θ
│ └×: Product
│ ├' ': String ' '
│ └ι: Identifier ι
└‖O: Reflect overlap
└Multidirectional
├←: Left
└↑: Up
```
[Answer]
# [JavaScript (ES6)](https://babeljs.io/), 159 136 129 127 bytes
```
f=(i,x=1-(l=i.length-1),y=x<0?-x:x,[,...b]=i)=>l>x?''.padEnd(l*(l+~y))+[...b.reverse(),...i].join(''.padEnd(y))+`
`+f(i,x+1):''
```
[Try it online!](https://tio.run/##bY1dC4IwGEbv@yPbm9vQvpOm9PUfhBDSnDYZm6jIvKi/bnkVhLfnnIenTLqkedSyammapEJRbTIxDDnHkljuUay4ZEroon1SD0jP7cENqfUtuRHGWBpzCTxQgQ0RYlWSXXWG1Rwr590DOLcxYbXoRN0IDONCxqw0UuNfPob32d3Jx0vHAx@h4WF0Y5RgyhQ4x8hbLFfrzXa3dxHA7E8eT@fLBOYBvOIJHkXWRtFXDB8 "JavaScript (ES6) – Try It Online") Explanation below
```
// This is a recursive function
// First, inputs and various variable initializations
// by using defaults
let func = (
// Text input, will not be modified through recursion
input,
// Current line, for the first function call we start from -lines to +lines
// It's roughly equivalent to lines*2 but this helps us computing the spacing
// Also computing the total amount of lines
currentLine = 1 - (totalLines = input.length - 1),
// Getting the absolute value of the current line (like Math.floor)
absCurrentLine = currentLine < 0 ? -currentLine : currentLine,
// Getting the input without it's first letter, useful for the palidrome of the input
[,...slicedInput] = input
// Base case, stopping the recursion if the current line
// is still below the total amount of lines
) => totalLines > currentLine
// Leading spacing
? ''.padEnd(totalLines * (totalLines + ~absCurrentLine)) +
// Putting together the palindrome version and adding spaces between the chars
[...slicedInput.reverse(), ...input].join(''.padEnd(absCurrentLine)) + `
// Line return + recursion call
` + f(input, currentLine + 1)
: ''
```
First entry to codegolf, I apologise in advance for any obvious mistakes.
Thanks to Justin Mariner for saving 23 bytes!
Thanks to Craig Ayre for saving 11 bytes and for the bug report.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~22~~ 18 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
ā,⁄H{,čFH@*∑Κ}▓±╬-
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTAxJTJDJXUyMDQ0SCU3QiUyQyV1MDEwREZIQColdTIyMTEldTAzOUElN0QldTI1OTMlQjEldTI1NkMt,inputs=JTNEJTNFJTI5JTdEJTVE)
Explanation:
```
ā push an empty array - canvas
,⁄H{ } input length-1 times do
, push the input
č chop it into chars
FH@* get the current iteration-1 amount of spaces
∑ join the chopped input with the spaces
Κ prepend it to the array
▓ space to a square
± reverse each string in that list
╬- quad-palindromize with 1 X and 1 Y overlap and without swapping characters
```
[Answer]
# PHP, ~~145~~ 131 bytes
It took some thinking to golf that additional byte; but it was worth it.
```
while($y<=2*$e=strlen($a=$argn)-1)echo($p=str_pad)("
",$e*($e-$d=abs($y++-$e))+1),chunk_split($a.substr(strrev($a),1),1,$p("",$d));
```
prints a leading newline. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/5d070ffdde85d82aefcb56f98bb115c08b6a5db5).
**breakdown**
```
while($y<=2*$e=strlen($a=$argn)-1) # $e=length-1, loop through rows
# 1. print linebreak and left padding
echo($p=str_pad)("\n",$e*($e-$d=abs($y++-$e))+1),
chunk_split(
$a.substr(strrev($a),1) # 2. palindromize input
,1,$p("",$d)); # 3. insert $e..0..$e spaces between characters
```
**alternative solution**, same length:
```
for($d=-$e=strlen($a=$argn)-1;$d<$e;)echo($p=str_pad)("
",$e*($e-$b=abs($d++))+1),chunk_split($a.substr(strrev($a),1),1,$p("",$b));
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 11 bytes
```
ṪẏṘ∞ƛ?Ṙ∞$Ij
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJDIiwiIiwi4bmq4bqP4bmY4oiexps/4bmY4oieJElqIiwiIiwiPT4pfV0iXQ==)
## Explanation
```
ṪẏṘ∞ƛ?Ṙ∞$Ij
Ṫ # Remove the last element (removing the first element would be fine too)
ẏ # Make a range [0, length)
Ṙ # Reverse
∞ # Palindromize, a + a[::-1][1:]
ƛ # Map, and for each:
?Ṙ # Push the input reversed
∞ # Palindromize that (call this X)
$ # Swap so the current item is at the top
I # Push that many spaces
j # Join the characters of X by that
# C flag centers and joins on newlines
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 37 bytes
Requires `⎕IO←0` which is default on many systems.
```
{⍉m(2-d)↓⍉(m←⊖⍪1↓⊢)↑∊¨(1↓⍳d←≢⍵)↑¨¨⊂⍵}
```
`{`…`}` anonymous function where the argument is represented by *⍵*
`(`…`)↑¨¨⊂⍵` for each (`¨`) of the following numbers take (`↑`) that many characters from each (`¨`) of the entire (`⊂`) argument, padding with spaces as necessary:
`≢w` the number of characters in the argument
`d←` store that in *d*
`⍳` that many **ɩ**ndices (0 … *d* − 1)
`1↓` drop one (the zero)
`∊¨` **ϵ**nlist (flatten) each
`↑` raise the rank (convert the list of lists into a matrix)
`(m←`…`)` apply the following tacit function *m*, defined as:
`⊖` the upside-down argument
`⍪` on top of
`1` one [row]
`↓` dropped from
`⊢` the argument
`⍉` transpose
`(`…`)↓` drop:
`2-d` = −(*d* − 2), i.e. *d* − 2 rows from the bottom
`m` apply *m*
`⍉` transpose
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZPWj3s5cDSPdFM1HbZOBbI1coOCjrmmPelcZgkS6FgElJj7q6Dq0QgMs0Ls5BaSic9Gj3q0gqUMrDq141NUE5NX@/5@moG5oZGxiamZuYWmgzgXkOjo5u4AZtnaatbFgVkRERUVEhDoA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~201~~ 196 bytes
```
s->{for(int l=s.length()-1,i=-l,x=0;++i<l;x+=i<0?l:-l)System.out.printf("%1$"+(x<1?"":x)+"s"+s.join("%1$"+(i<0?-i:i>0?i:"")+"s",(new StringBuffer(s.substring(1)).reverse()+s).split(""))+"%n","");}
```
[Try it online!](https://tio.run/##XVDLbsIwELzzFSurSLaSWKTvJgRUaI89cUQcQnDA1DiR14FUKN9OnYdUqT54VzOe8c4e03MaFKXQx933ray2SmaQqRQRvlKp4ToCGFC0qXXlXMgdnBxHV9ZIvV9vIDV7ZGAPprggfNaZKK0sei3A0X3AKysVzyudtQRfFhqrkzDT3mEGJrlhMLvmhaFSW1AJciX03h4oC0JfJoHy62QSe56cqrj2EjmdzFUUKLb6QStOvKgsL52VzSkZh3fEo/U0nBMS1cwjSDzkx8INPHCtOpCRnE3mMiKke@JTLS7Qz7Oo8lwYihyrLXYIDRnjRpyFQUGZh4xjqaSlTuzUY01818XNDboTd7nbML0fYAR/7uvNlYT3D49Pzy@vbxOnfF8sP1xJZqzZkIYNawMwPM3aVVJk8QD9j6s0HbhmNGqv5vYL "Java (OpenJDK 8) – Try It Online")
It's the same idea as [the one I used for the previous challenge](https://codegolf.stackexchange.com/a/129550/16236), except that the generator string is now a tad longer and with more hard to handle cases.
```
%1$Ns0%1$Ns9%1$Ns8%1$Ns7%1$Ns6%1$Ns5%1$Ns4%1$Ns3%1$Ns2%1$Ns1%1$Ns2%1$Ns3%1$Ns4%1$Ns5%1$Ns6%1$Ns7%1$Ns8%1$Ns9%1$Ns0%n
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~134~~ 124 bytes
```
f=lambda s:'\n'.join([' '*(len(s)-1)*abs(len(s)-abs(i)-2)+(' '*abs(i)).join(s[::-1]+s[1:]) for i in range(2-len(s),len(s)-1)])
```
[Try it online!](https://tio.run/##VYzLDoIwFET3fkV37QVrLPhsgomPj2iCXZQIWoMXQlngwm@vEiIJuzknM1O/20eFsfdFUppXdjPESXpFunhWFllKCQ1YmSNzwAUEJnN/6qMFHkHI@tKAMMxcKiUXOnSpkBpIUTXEEoukMXjPWcSHi/n4q8HXjcWWFYyKKF6tN9vdfkkBZqM@ns6XiUgO8NETo1TXKfVT/gs "Python 3 – Try It Online")
First post to PPCG after lurking for a while. Looking for any suggestions/advice!
---
Thanks to @LyricLy and @Łukasz Rogalski for improvements!
[Answer]
# Haskell, ~~177~~ 163 bytes
```
import Data.List
k n=[1..n]>>" "
f s=let n=length s in map(\x->(k(((n-1)*(n-(abs x)))))++(intercalate (k(abs x))$map(\z->[z])$((++)=<<reverse.tail) s))[n,n-1.. -n]
```
The function `f` is the challenge function and returns a list of strings (`[String]`), using `unlines` on it should provide the same visual output as the test cases (`main = putStr $ unlines $ f "test string"` to compile it).
[Try it online!](https://tio.run/##LU27bsMwDNz9FYThgYproc6jbYDYU8duHR0PTMA0gmXWkJggyM@7apAbDoc78u5McWDv59mN029Q@CQl@@WiZgNI09XWSt@2OeTZCWLjWZPrWX70DBGcwEgT7m9ViwMiSlWbRWKkQ4Sb@UdZohPlcCRPypDOnlnx@LxXbXfvTYFYlqbZ7QJfOUS2Ss4biMZ08pJarYVK@iwbKU02MF30WwMUcBHvhGNSJ8jr5Wq9eXv/2L7m8/wH)
-14 bytes thanks to @nimi
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `N`, 14 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ḣı$ṅṣj;ðƬrⱮṬrⱮ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMSVCOCVBMyVDNCVCMSUyNCVFMSVCOSU4NSVFMSVCOSVBM2olM0IlQzMlQjAlQzYlQUNyJUUyJUIxJUFFJUUxJUI5JUFDciVFMiVCMSVBRSZmb290ZXI9JmlucHV0PSUyMjEyMzQ1Njc4OTAlMjImZmxhZ3M9Tg==)
I have *absolutely* no idea why this works, but it does.
#### Explanation
```
ḣı$ṅṣj;ðƬrⱮṬrⱮ # Implicit input
ḣı ; # len(input) - 1 times:
$ j # Join the input by...
ṅṣ # ...loop index spaces
ðƬ # Transpose with filler space
rⱮ # Reverse and palindromise
Ṭ # Tranpose it
rⱮ # Reverse and palindromise
# Implicit output, joined on newlines
```
I did quite a bit of experimenting, producing a lot of buggy outputs. Here's my favourite:
```
0987654321234567890
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 0
0987654321234567890
```
[Answer]
# Mathematica, 141 bytes
```
Column[Join[Reverse@(s=Row/@Table[Riffle[Reverse@Rest@b~Join~b,""<>Table[" ",i]],{i,0,Length[b=Characters@#]-1}]),Rest@s],Alignment->Center]&
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÊÆÔ¬qXç)êÃÔÅê û
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=ysbUrHFY5ynqw9TF6iD7&input=IkFCQ0Qi)
```
ÊÆÔ¬qXç)êÃÔÅê û :Implicit input of string
Ê :Length
Æ :Map each X in the range [0,length)
Ô : Reverse U
¬ : Split
q : Join with
Xç : X spaces
) : End join
ê : Palindromise
à :End map
Ô :Reverse
Å :Slice off first element
ê :Palindromise
û :Centre pad each element with spaces to the length of the longest
:Implicit output joined with newlines
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~100~~ 90 bytes
```
s->(l=length(s)-2;[' '^(-~l*(l-j))*prod(s[abs(i)+1]*' '^j for i=~l:l+1) for j=abs.(-l:l)])
```
[Try it online!](https://tio.run/##RY3LDoIwFETX9isaNtwLllh8a@p3NCGYYAAtaQqhNWHFr9fiQndzJmcy3Vurik@@pYJ6y26ghW7M073AIsuvRUzjO7BZJ6BZh5gMY1@DLaqHBYUpL5NF6Gjbj1SJWV90yvFLnQhOBixUWKJ3jXXhoiCRlNMkZbQmEc@3u/3heDpvIlISsqwcVYYuLlkNozJOG3D4yxm0Af8MSBpT@w8 "Julia 1.0 – Try It Online")
-10 bytes thanks to @KevinCruijssen
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 14 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
L╷rH ×⁸;*∔}↔↕┼
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjJDJXUyNTc3JXVGRjUyJXVGRjI4JTIwJUQ3JXUyMDc4JXVGRjFCJXVGRjBBJXUyMjE0JXVGRjVEJXUyMTk0JXUyMTk1JXUyNTND,i=QUJDRA__,v=8)
## Explanation
```
L|rH ×⁸;*∔}↔↕┼
L length of input
|r decrement, make range [0..n-1]
H create an empty art object, start a loop with i
× repeat space i times
⁸; swap with the input
* join input with i spaces
∔ add to the bottom of the previous iteration
} close the loop
↔↕ mirror horizontally and vertically
┼ quad palindromize with 1 character overlap
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¦ε\RðN×ýû}Rû.c
```
Input as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f//0IpzW2OCDm/wOzz98N7Du2uDDu/WS/7/P1rJUUlHyQmInYHYRSkWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VQGH1r5/9CKc1sPrQs6vMHv8PTDew/vrg06vFsv@b/OoW32/6OVHJ2cXZR0lGztNGtjgXREREVFRASQYWhkbGJqZm5hqRQLAA).
**14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative:**
```
ā¨RjJíðδÜ€ûû.c
```
Also takes a list of characters as input.
[Try it online](https://tio.run/##yy9OTMpM/f//SOOhFVleh9ce3nBuy@E5j5rWHN4ddHi3XvL//9FKjko6Sk5A7AzELkqxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VQGu/w/0nhoRVCW1@G1hzec23J4zqOmNYd3H96tl/xf59A2@//RSo5Ozi5KOkq2dpq1sUA6IqKiIiICyDA0MjYxNTO3sFSKBQA).
**Explanation:**
```
¦ # Remove the first item of the (implicit) input-list
# (could have removed the last as alternative as well)
ε # Map over each character:
\ # Discard the character
R # Reverse the (implicit) input-list
N # Push the 0-based map-index
ð × # Repeat a space character that many times as string
ý # Join the reversed input-list with this spaces-string as delimiter
û # Palindromize the entire string
}R # After the map: reverse the resulting list
û # Palindromize this entire list
.c # And centralize it, which also implicitly joins by newlines
# (after which the result is output implicitly)
ā # Push a list in the range [1, (implicit) input-length]
¨ # Remove the last item to make the range [1, input-length)
R # Reverse the list to (input-length, 1]
j # Pad each character in the (implicit) input-list with leading spaces so
# the string lengths become equal to the current integer
J # Join each inner list of strings together to a single string
í # Reverse each string
δ # Map over each string:
ð Ü # And remove all trailing spaces
€û # Palindromize each string
û # Palindromize the entire list
.c # And centralize it, which also implicitly joins by newlines
# (after which the result is output implicitly)
```
[Answer]
# [Zsh](https://www.zsh.org/), ~~117~~ ~~113~~ ~~109~~ 112 bytes
```
b=`rev<<<$1`${1:1};j=$#1
for c ({$j..1} {2..$j}){printf %$[(j-1)*(j-c)]s
for x (${(s::)b})printf %-$c\s $x;echo}
```
[Try it online!](https://tio.run/##NcrBCsIwDADQu18RMEIrrBCPXfclKoyVjtmD03boNOTbowhe3um966Q6dH1JjxACUo9MnqTNHW5pM84FIhjG7BwJ8ME5zGL5Vi7XZYQdHk1uyO6/Rnuuv7@CQTbVezuI/ccG46kCrm2K0yyqen@msrw@)
~~[109b invalid](https://tio.run/##qyrO@P8/yTahKLXMxsZGxTBBpdrQyrDWOstWRdmQKy2/SCFZQaNaJUtPz7BWodpIT08lq1azoCgzryRNISYmT1UlWiNL11BTC0gma8YWq6mBtFQoaKhUaxRbWWkmwRWr6qokxxQrqFT8//@/sDy1qKQSAA)~~
~~[113b](https://tio.run/##PcpBDsIgEADAu6/YxG0DGoh7RfoSStKUtFEOVaHRKuHta7w45/nkC/PYDWl6WmuRBixkqJ5jhw73pMjv5luCAKJg1PpUoZDWGKu8p@uyztD3S4MuHkRUQfrctr@@gcAisjFy/MdGoQtH8hlwY@bHa0rr@ws)~~
~~[117b](https://tio.run/##LcvdCsIgGAbg865C2DvQwsF36vRKnDD2R3mwmo5aidduEJ0/zydeSxlMH@an1hrUI5Gi3HoDi4okudNyD2xkPEn4poHPIk0Gaaxkbh/htu4L67q1hvVn7uUkXPyNg3EkHpUSQxZ/V0vY6UIuMhy5lLK95rC/vw)~~
`b` is the palindrome; `j` is the length of input string `$1`. Iterate `c` over the range `{j..1..j}`. For each `c`, print a prefixed number of spaces. For every character `x` in `b`, print `x` with `c` spaces between each.
] |
[Question]
[
When studying [numerology](https://en.wikipedia.org/wiki/Numerology), you can say two words (strings consisting entirely of letters) are compatible if they produce the same number under the following operation (let's use the string `hello` as an example):
* Map each letter to a number according to the following, ignoring case:
```
1 2 3 4 5 6 7 8 9
a b c d e f g h i
j k l m n o p q r
s t u v w x y z
```
The number at the top of the column a letter is in is its mapped value (e.g. `a -> 1`, `x -> 6`)
`hello -> [8, 5, 3, 3, 6]`
* Take the sum of these numbers. `hello -> 25`
* Repeatedly take the [digital sum](https://en.wikipedia.org/wiki/Digit_sum) until it reaches a single digit (i.e. it's digital root). `hello -> 2+5 = 7`
For example, `hello` and `world` are not compatible (they yield `7` and `9` respectively), whereas `coding` and `sandbox` are (both `7`).
---
You are to write a program which will take two strings as input and output two distinct consistent values which indicate whether the strings are compatible or not
* The inputs will only consist of letters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ` or `abcdefghijklmnopqrstuvwxyz`) in a consistent case
* You may choose the case of the inputs, so long as it is consistent across inputs and runs
* You may take input as a delimited string (e.g. space separated), so long as the delimiter is non-empty and consists of entirely non-letter characters of your chosen case (i.e. if you input in uppercase, the delimiter may contain lowercase letters, but not uppercase letters)
* Otherwise, you may input and output in [any convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
## Test cases
```
a, b -> out
"hello", "world" -> 0
"raahyjc", "mvj" -> 0
"mpqtjmjd", "bwkhrh" -> 0
"VZZLCZTH", "DOJEIV" -> 0
"coding", "sandbox" -> 1
"vhw", "wl" -> 1
"HMCZQZZRC", "SIQYOBXK" -> 1
"a", "j" -> 1
```
[These](https://tio.run/##y0rNyan8///opJy0R01rDs9IPLTVX9tY1TLf8uGOHk2XQ8tVDk/wceUyNAhSqDA0UHi4q0vv4e5uhUNbFQ7PcFSoAAkoPNzZqKAJJFuAJigcbld41LgdxOM6tOjQwoc7ZwO5//8bGhgAAA) [two](https://tio.run/##y0rNyan8///opJy0R01rDs9IPLTVX9tY1TLf8uGOHk2XQ8tVDk/wceUyNAhSqDA0UHi4q0vv4e5uhUNbFYBqFSpAAgoPdzYqaALJFqAJCofbFR41bgfxuA4tOrTw4c7ZQO7//4YGBgA) programs can generate more test cases
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
O’§%9E
```
[Try it online!](https://tio.run/##y0rNyan8/9//UcPMQ8tVLV3///8freTs7@Lp566ko6AU7Ojn4uQfoRQLAA "Jelly – Try It Online") [All Tests.](https://tio.run/##y0rNyan8/9//UcPMQ8tVLV3/H25/1LTm///oaCUPVx8ffyUdBaVw/yAfF6VYHa5opSBHR49IL2eQqG@YF0TMNyAwxMvXywUk6BTu7RHkAREPi4rycY4K8QCJu/h7uXqGQcSd/V08/dxBosGOfi5O/hFQ5R7hYMt8IFwPX@eowKioILBdwZ6Bkf5OEd5KsbEA "Jelly – Try It Online")
We take input in capital letters. The key insight here is to note (ref. [en.wikipedia.org/wiki/Digital\_root](https://en.wikipedia.org/wiki/Digital_root#Congruence_formula) that the digital root of \$n>0\$ is \$n\mod 9\$ except if \$n\$ is a multiple of 9, at which case it is 9. However, we only care if the digital roots are equal, so we can treat the digital root as \$n\mod 9\$ in all cases.
```
O’§%9E
O # Character values A→65,...
’ # minus 1, A→64...
§ # take the sum of each word
%9 # modulo 9 (∑{A...} = ∑{1...})
E # are the two words' sums equal?
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~10~~ 9 bytes
```
=/9!+/'3+
```
[Try it online!](https://tio.run/##Lc3LDoIwEAXQvV@BswECBo0rbfyY0oKlD0YK4dGFv15LMXc1505y1QWV9@3zVT3ORZXeC39Njtz@@SZtmmUgGq0RCCxoNYecZGApFZtkwcwso5jPMEkjeaB6UcKKqLNzmrlJBOUom26OypB3/TvYSHte43q8imWf0PEQhrnBObsvjN2wYb2qvSiBAikhTOYn/wM "K (oK) – Try It Online")
Another port of [fireflame241's answer](https://codegolf.stackexchange.com/a/215456/58563).
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~11~~ 8 bytes
-7 bytes after looking at fireflame241's [answer](https://codegolf.stackexchange.com/a/215456/95792)
-3 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)
```
Ëo%9ṁo←c
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f/h7nxVy4c7G/MftU1I/v//f3S0koerj4@/ko5SuH@Qj4tSrE60UlhUlI9zVIgHUNDF38vVMwws6uzv4unnDhQLdvRzcfKPAAt6@DpHBUZFBTmDxD0DI/2dIryVYmMB "Husk – Try It Online")
Needs the input a list of uppercase words.
```
Ëo%9ṁo←c
ṁ Map each word and sum the results
c Get integer value of character
o← And decrement
ȯ%9 Take that modulo 9
Ë Check if they're equal
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~32~~ 27 bytes
```
9∣(#-#2&@@FromDigits/@#)&
```
[Try it online!](https://tio.run/##Jc1JCsIwAIXhvaeQBoqCRXDnQim2SuuAI6IRF@mY1KbRGKwidu09vJkXqY1Zvu8tfooEDikSxEdl1Cu73/enAQzQ0U1zxBm1SUzEtW2Cpl4uOMnEARj9yARHvVj7KCuetaeGwzRlWquu5YyngfZqVcYRwo/El0pviTJ6voiEJoFELz9hjpVvIZxacONIt@fjobtV7rOAZLHUK8oCj90V33D@j6VqOjMLLiFcWRLX7nI/H@wm6kKSqnjtVf4A "Wolfram Language (Mathematica) – Try It Online")
Takes a list containing two strings.
Inspired by Neil's Charcoal solution: [`FromDigits`](https://reference.wolfram.com/language/ref/FromDigits.html) still recognizes `a`=10, `b`=11, etc., even if those digits are not present in the base (by default, it interprets its input base 10).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes
Takes input as lists of lists of characters.
-1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
```
ÇÌ9%>ΔO€S}Ë
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cPvhHktVu3NT/B81rQmuPdz9/390tFKyko6CUj6ISAERmSAiD0SkK8XqKEQrFYPYiXBRsKIkuJ4KpdhYAA "05AB1E – Try It Online")
**Commented:**
```
ۂ # convert both words to codepoint lists a->97, b->98, ...
Ì # add 2 to each number a->99, b->100, ...
9% # modulo 9 a->0, b->1, ...
> # increment a->1, b->2, ...
Δ } # execute until the reult doesn't change:
O # sum each list
€S # split the results into lists of digits
Ë # are both lists equal?
```
---
A port of [fireflame's excellent Jelly answer](https://codegolf.stackexchange.com/a/215456/64121) comes in at 6 bytes as well (provided by [Kevin](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)):
```
Ç<O9%Ë
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cLuNv6Xq4e7//6OjlZyVdJT8gdgFiD2B2A@I3ZVidaKVgoEsR6gISNYJqjJCKTYWAA "05AB1E – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~31~~ 30 bytes
```
+T`_l`dl
.
$*
1{9}|(1*)¶\1
^$
```
[Try it online!](https://tio.run/##BcFRCoIwGADg9/8cBmYj8LHXLNAyxBSpEbXppLmmqyWuqK7VAbrY@j5d901H7cjNCIKcxETaSU5OkjAJU3A88F@zz9v1vfHve/ABjo61vJZSIaO0ZKAp5U9RoXYQ0F5vvWgFQ6W5cM2hwDgOcB6iRbJaRgVUijXdGd1px0r1gIEbZCSEmwCnGG8DlEXpPpnv1n8 "Retina 0.8.2 – Try It Online") Takes input on separate lines, but link includes header which lowercases the test suite and splits on `,` for convenience. Explanation:
```
+T`_l`dl
```
Retina 0.8.2 doesn't have `Y`, but fortunately we can just repeatedly transliterate 9 digits at a time, shuffling the letters back 9 places in the alphabet.
```
.
$*
```
Convert all of the digits to unary.
```
1{9}|(1*)¶\1
```
Take the difference modulo 9.
```
^$
```
Check that the result is zero.
[Answer]
# [J](http://jsoftware.com/), 15 bytes
Based on fireflame241's Jelly answer.
```
=&(9|1#.3+3&u:)
```
[Try it online!](https://tio.run/##Tc69DoIwHATwnaf4RxMKEYmGyRomEycn3wBasJSWSkE@Gt@9OohluOV@ueS43cSohBQDgggOgL/Zx3C536429YPT@7iNk13iv3BoQ88rCFOAWCGEQhBE@FyGgEalBUU/01nGZk6cyoEvJp9tzyWnDvOxZpotPhgjiOmZc6p4UQ2LE0Wr5uG0yxqaq@k/Z@PqlFhqJolpjdGrT13VziqfauTZDw "J – Try It Online")
### Original approach: [J](http://jsoftware.com/), 29 bytes
*-2 after reading ovs' answer: `(x-97)|9 = (x+2)|9`*
```
=&(1(,.&.":@#.^:_)1+9|2+3&u:)
```
[Try it online!](https://tio.run/##Tc5LDoIwGATgPaf4gwmFgI3oyhoSExNXrjyABlqwlELlIY/Gu6MLERazmS@TjBhNjBIICCDwYAPkmzWG0/VyHgPL9m0PW9gkxxW@kbvju/v31t1ZL@KMjmHElCtAPJZSIbA9ckgcQJ2qJEM/q8KQD4LOmrdisvxZNiIXbMaoy3jFJ2@1llQ3fHamRJy2k1PF0uIxax0WLFL9f867xSk51TynutS6Wnyq03JQUZ8hY/wA "J – Try It Online")
```
=&(1(,.&.":@#.^:_)1+9|2+3&u:)
f&( g ) call g on both arguments, then call f
3&u: convert string to code points
2+ 'a' -> 99, 'b' -> 100 …
9| mod 9
1+ plus 1
1( f )^:_ execute 1 f (list of digits)
until the result does not change
@#. sum digits and
&.": convert the sum to a string and
,. itemize the characters
&.": convert the characters back to digits
=& are the digital roots equal?
```
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=sum -p`, 61 bytes
```
y/a-z/1-91-91-8/;s|\d+|sum$&=~/./g|ge while/\d\d/;$_=/(.) \1/
```
[Try it online!](https://tio.run/##K0gtyjH9/79SP1G3St9Q1xKMLPSti2tiUrRriktzVdRs6/T19NNr0lMVyjMyc1L1Y1JiUvStVeJt9TX0NBViDPX//0/OT8nMS1coTsxLScqv@JdfUJKZn1f8X9fXVM/A0ABI@2QWl1hZhZZk5tgCzfyvWwAA "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~61~~ \$\cdots\$ ~~53~~ 51 bytes
Saved a byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
Saved 2 bytes thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)!!!
```
lambda t:len({sum(ord(c)+3for c in w)%9for w in t})
```
[Try it online!](https://tio.run/##NZBNbsMgEIX3PsUIKQoodFFn00RyN2lPUXdhAyl2sLEx9Q9Vz@56QsoIpPcNvIemW7y2bbpes3w1RVPKAvzZqJb@DN8NtU5SwQ7Hq3UgoGphYrsTigmF/2WrV4MfIANKiVbGWMLJZJ2RhHGgxBWFXmpBOJBmrCNrut7XTS0RltNNOx35GIIRwWvk0taqGiMXVlbtF9KhaGVp58d1PSGbTJS6EaEPwd2zhqpfbDnfYqtAtIWzRM2dEl5J/G/KYz3HYonQStyUwx7J5/c0n09v@fxywdcPfdn2kbAEJ@C5whmEqqP3GXD4d2fnBLaFTlfq2V10rmo97MluQLvthKfX/c5zcBwewR8uy9Tn@gc "Python 2 – Try It Online")
Inputs a tuple of two strings in lowercase and returns \$1\$ if they are compatible or \$2\$ otherwise.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~203~~ 145 bytes
-58 bytes thanks to @caird coinheringaahing
```
def f(a):
x,y=[sum((ord(i)-97)%9+1for i in z)for z in a]
g=lambda t:sum(int(i)for i in str(t))
while x>9:x=g(x)
while y>9:y=g(y)
return x==y
```
[Try it online!](https://tio.run/##PdBNa8MwDAbge36FMAxslo2VHUYC2WHdoN0HpesoW0IOTp3Uzpy4c90m7p/P7BxyEEgPkg7vwRqu2vthYGUFFaYkDqAPbZIdTw3GSjMsyE30QK6i61mlNAgQLVyIby@@pXkA@0TSpmAUTOyvRGvc0bR8NBobQgLouJAl9I9R3Cd73E9inVgn1okuzUm30CeJHaYPGUa8lFKhEHVKS4ZIiJGmlNt6h0JAzbkeqTn8mbqpmbei@@Waj7xN0/d5@rXw/Lx6fVluR94pJtq9xyNtWaH6Uc@889TJcVp8zNN1mn7OvW2W65/V0/cbIrkLSUACIrvLb6XqSo1JKLLZNARw0GMMrioXBiHDPw "Python 3 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 31 bytes
```
Y`l_`1-9
{`\d
*
)`_+
$.&
(.) \1
```
[Try it online!](https://tio.run/##BcFBDoMgEADA@75iD22jbWrisS/oG5qYCALpgiCKBJQ@ns4EFfXC@3pt3qx@mB1Z/3zBjw0S7tCy8QGX7gZN1@LQ10rKWo/ZByshcE6nEeiSAbdu0TgjccozBYJUihUlEkpvlE4gvNTLF3e@yMkfkChjtkBOlK2UIHDX2@mnY/4D "Retina – Try It Online")
A direct implementation of the given algorithm. Outputs 0/1 indicating incompatible/compatible taking the argument in lower case.
### Explanation
```
Y`l_`1-9
```
Transliterate cyclically the sets `a-z_` to `1-9`. Here, the underscore is not a real character but a dummy, not that it particularly matters. To cyclically transliterate we extend both sequences infinitely, then each time we encounter a character in the input in the first set we output the corresponding character in the same location in the second set. This behaviour requires the dummy character to map to 9 after `z` is mapped to `8`, as otherwise the second occurrence of each character will be off by one, the third occurrence off by two, etc.
```
{`\d
*
)`_+
```
Here we loop until a fixed point over these two stages, indicated by `{` and `)`. The first stage converts each individual digit to a corresponding number of `_` characters, while the second converts each chain of `_` characters to a number equal to the length of the chain. This reaches a fixed point naturally only at single digit numbers.
```
(.) \1
```
Count if the remaining digits are the same, so the total is zero if they are not the same and one if they are.
[Answer]
# Scala, 27 bytes
Uses fireflame241's [approach](https://codegolf.stackexchange.com/a/215456/95792).
```
_.map(_.map(3+).sum%9).size
```
[Try it online!](https://scastie.scala-lang.org/iMg86eC9T3ylIxvbpvVvSA)
Accepts input as a `Set` of lowercase strings. Returns 2 if inputs are not compatible, 1 if they are. I'll probably go to hell for my abuse of the rules here.
[Answer]
# [Haskell](https://www.haskell.org/), 44 bytes
```
a#b=o a-o b
o s=sum[fromEnum c-1|c<-s]`mod`9
```
[Try it online!](https://tio.run/##TZDRTsIwFIbv9xR/qhcQGFHvTJgXDhJQCEGU6JZFug3sxrrOtmOY8O5zRV28OWm/7@85OWVU7bdZVie8EFJjRDUduIxK6z@YJUoPVkWW6JpehI4AtQVCS0A5quT@Tgo@zkuOyL4@RUNbBRsu4s1tzWmSwwGnxfwdRalXWs5yWPChmKhwRK8HAvuuKc3pzDpoJsBxcIUuThbQpIY2Ilbme7XY4QaXph86pmjxUhRb2YVvgiCs2USQPkglZBYT9H@wpJR9pZER/JC2mBefOuVpbHhY7Zlk5NesPW/mes8TY0aLh/F03T6KRJzkH0YomsehOLbmwKrz6Oyvy2TuekvPe3INXk2Xb4v718c2Tg1NibkEZ5RtNXzaD4Pmx44Wgvob "Haskell – Try It Online")
* Infix function expecting two UPPERCASE strings: returns `0` if compatible or any value if not.
* Inspired by @fireflame241 insights: <https://codegolf.stackexchange.com/a/215456/84844>
[Answer]
# [Ruby 2.7](https://www.ruby-lang.org/), ~~89~~ \$\cdots\$ ~~55~~ ~~52~~ 41 bytes
*Saved a whooping 34 bytes, thanks to [fireflame241](https://codegolf.stackexchange.com/a/215456/83605)'s answer!*
*Saved extra 11 bytes, thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)!*
```
->w{!w.map{|s|s.bytes.sum{_1-6}%9}.uniq!}
```
[Try it online!](https://tio.run/##Zc47coMwEIDh3qdY8GRogEmazKSIL@JxISQ5QuiFHsgIODsxTuIitPt/s7s2NON6/VyrU5yyWEtkptnNrm5GT13tgpxmPOPqfXn5WOqg2j5b1iMgIaBVJngHyFLwqKPqPgCio8LI0RJ08PcMAxKB/iAXkTGUZIeDgev5nDMqhM5LyKO2guSXCxyhOsHbb5am91xysokmdsyyHRlSEjh5thGiOW2HHbEIsZHjTciB7zLWpFVfW3VIkUbfnuL17waLjx/FrjCJU5@SfSx3bT/q5tb9VwUqSih48Ryv3w "Ruby – Try It Online")
This outputs with the boolean values swapped!
In Ruby 2.7, we can use `_1` in place of `|c|c` to save 2 bytes.
[Answer]
# Java 8, 50 bytes
```
a->b->a.map(v->v-1).sum()%9==b.map(v->v-1).sum()%9
```
Inputs in uppercase as character-Streams.
Port of [*@fireflame241*'s Jelly answer](https://codegolf.stackexchange.com/a/215456/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##nZFbT4NAEIXf@ys2m5hCKJv46KUkXKpAoVhoesH6MFCqVG4pC0lj@tsRkFgxPvl2cr6Z3TMzByiBP@zeKz@CPEcmhMnHAKGcAg19dKgpKWgYkX2R@DRME/LQifsLy@kxgJhoCXVaNfp3n5SmUQCJIKA9GlfACx4vAIkhY0peKPlrluRFzLBXN@Ox95dd3Q3q8FnhRXX4boYyDXcorudi6l/C5PX5BQHbzIgQDXLKYHViGBYeIbyybEPB7N0PZouiutHlhppLvc/Mp/lCN3WlgdJqqtpqny9d15DdhdpwxdIn2rLPZUvRZo8NdcSZIlnrX@3qqg1l9G3VlN2569ptJkebbyxpPe2XiA3qwp4Hl2u2m2hLvjaBYNQJr1uIc8ppEJO0oCSrAY0SZoiHHHB4W7@5xZjzGnmLMLcnkGXRiQHiv8ExZ1i2M7xvowtwrj4B)
**Explanation:**
```
a->b-> // Method with two IntStream parameters & boolean return-type
a.map(v-> // Map over the characters of the first input:
v-1) // Decrease each value by 1
.sum() // Then sum them all together
%9 // And take modulo-9 on that
==b.map(v->v-1).sum()%9 // Do the same for the second input,
// and check if they're equal to one another
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `a`, 7 bytes
```
C‹v∑9%≈
```
Another port of [fireflame241's Jelly solution](https://codegolf.stackexchange.com/a/215456/80050). Takes input as newline-separated strings. [Try it Online!](http://lyxal.pythonanywhere.com?flags=a&code=C%E2%80%B9v%E2%88%919%25%E2%89%88&inputs=CODING%0ASANDBOX&header=&footer=)
```
C‹v∑9%≈
C Convert the input from a list of strings to a list of lists of their codepoints
‹ Decrement every number
v∑ Sum each sublist
9% Mod 9 both sums
≈ Check if both sums are equal
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~13~~ 10 bytes
```
¬﹪⁻⍘Sχ⍘Sχ⁹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMvv0TDNz@lNCdfwzczr7RYwymxODW4BCiXruGZV1BaAmVr6igYGgAJvNJA0lJTU9P6///k/BSgsEJxYl5KUn7Ff92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input in lower case. Outputs a Charcoal boolean, i.e. `-` for compatible, nothing if not. Edit: Saved 3 bytes via inspiration from @att's Mathematica solution, which only seems fair. Explanation:
```
S First input string
⍘ χ Interpret as "base 10"
⁻ Subtract
⍘Sχ Second input string as "base 10"
﹪ ⁹ Reduced modulo 9
¬ Equals zero?
Implicitly print
```
Like Mathematica, Charcoal interprets interprets `a=10`, `b=11` ... `z=35` even in bases which don't actually go up that high. Obviously it also interprets `aa=110` which has a digital root of 2 etc.
[Answer]
# JavaScript (ES6), ~~80 79 65~~ 63 bytes
*Saved 14 bytes by using [@fireflame241's insight](https://codegolf.stackexchange.com/a/215456/58563)*
*Saved 2 more bytes thanks to @Neil*
Expects `(a)(b)`. Returns a Boolean value.
```
a=>b=>(g=s=>[...s].map(c=>t+=parseInt(c,36),t=0)&&t%9)(a)==g(b)
```
[Try it online!](https://tio.run/##hc9dS8MwFIDhe3/FKDgSNrOJIHiRXliF1Q/GVIZGvDhNumYxTWoTWvfrq5EKUjY81897OEdBA47X28qfGCvybkM7oHFGY1RQR@NXQoh7IyVUiNPYT2gFtctT4xGfnp3jqadzPB774wuMAFNaoAx33BpndU60LdAGRTLX2kYYRa2ttYgwHvUzm43mRwNcA8id4oGXjfoHl9WHV6USQWftu6xlH@zDa8buEva0CPhqeXOdrg9hPEy5FVtThNCBEZn9/L3rOz0d4ka2P8/qP8cfxIv7hK0Ye0hC8piuXpaXz7ch3IchIDVc22/uvgA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 66 bytes
```
SameQ@@(Tr@*IntegerDigits~FixedPoint~Tr@#&/@LetterNumber@#~Mod~9)&
```
[Try it online!](https://tio.run/##Hc1fa8IwFIfhryIRxA3Bay@EsLph/TPtFNkydpE2hyS1abY0s47SfvUsyeV5zgs/Ra0ARa0sqONLd6IKMoynZ4Mf09oCB7OSXNpmeJF3YEctazv453gyxzuwFszrr8rBw7DXbFg8TNzR@Abzz0RQQwtfNHM8/vL9qOuQgKrSaDZCrTYVQ/2sQ4ZS8VcWAdWtjKS@f2ypShYsb6/CiMgXQnYJOa8Drw6b5/QSudBM1jxgQ2uW63vUm2jjThWv9T4hGSFvSbBTmn0cnt63qO@d@wc "Wolfram Language (Mathematica) – Try It Online")
thanks @att
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 67 bytes
Takes two lowercase strings and returns `0` if they match, non-zero otherwise. Uses the method from @fireflame241's answer.
```
i;g(char*s){for(i=0;*s;i+=(2+*s++)%9+1);s=i%9;}f(s,t){s=g(s)-g(t);}
```
[Try it online!](https://tio.run/##VY/BcoMgEIbvPsU2HTOgpjW9Zah5kl4QVNagJEA1MZNXr0XTSw87fPvP/v8uYtcIMc/IGiIUt4mj99pYgkXOEscwLchHmrg0pfEh3VPmCowP7FETl3l6d0VDHN01xFP2mF@xF/pbVvDpvETzpo7RP0ljuWgR9h46jj0ZDEoK9whgWQ2JyyDxLLTLBLIo0HILAyd4X5NN3DlYS371mwy2YX7rQyE95gxqW1XhmuwJntJgBzjbELZ4HZBY0ve/F4pjiFlxzQpRzWr2C/gAL88/ZoCURY9ZVVobGI3VEvLIcq5urYBuaEPXnS@@7VoJ5XhSVgVlmCYtJq9AmrbCISjCSOwbcLyXpbnCPhrUCKMOoDoxXabJCnB4uZnyegoihxb2P6LWvHHzbvwF "C (gcc) – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 14 bytes
```
S%{:i:(:+9%}/=
```
[Try it online!](https://tio.run/##BcG7CsIwFADQ/X7FXQKCg7MBhzyKN2keJi1Jm604KQg6l357POf53j79F9jeJ7bzFz/x85Udl1v/Hgw6Dc5FrDE7DVkIWq1CXyz4R5qttxplHSkTlNacajOhjnYwBVTUJtxxEkHLuEChitUBedVSa1nhZNIa5TKCQPsH "CJam – Try It Online")
First attempt at CJam. Using [Fireflame241's](https://codegolf.stackexchange.com/a/215456/91386) solution.
```
S% # Split on spaces
{
:i # Convert each to int
:( # Decrement each
:+ # Sum list
9% # Modulo 9
}/ # For each word (push to stack)
= # Are equal
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 18 bytes
```
WDm{{**-.}ms9.%}sm
```
[Try it online!](https://tio.run/##BcG7DoIwFADQ/X7FXVxIZHcVTMBHCGpQr1OhxFpbKq1QDeHb6zn1YFXr@qENqpuIwiXV0xRFy3jWbhUvZqfDrO9lEK1SBr2xioNlTPxkg3qUoN/9R2rJsfYvYQVURPuEzhmmxXaTV9AY/uwe6FjHa/OFUXj0CrJDQiXRMcFTXt6K9XUHDOUf "Burlesque – Try It Online")
```
WD # Split into words
m{ # Map over words
{** # To int
-. # Decrement
}ms # Map sum
9.% # Modulo 9
}
sm # Are the same
```
Using [Fireflame241's](https://codegolf.stackexchange.com/a/215456/91386) solution.
# [Burlesque](https://github.com/FMNSSun/Burlesque), 36 bytes
```
WDm{{**2.-9.%+.}ms{XX++}{ln1!=}w!}sm
```
[Try it online!](https://tio.run/##BcHNDoIgAADgO0@Bhy663OrWoUvapv3MWc2MTiguIpCElBrj2en7mlHxTg9j53lvEfLXVFgbhst4vopnUeyEtnUdRc7yfhGsnQmcFt6Je@lpx7mERipOgMKY/lgLxcSAeA8fJhiBjXlRRUGF0CFBlwymxW6bV6CV5Nk/oMY9aeQXTNRAw0F2TFCJ0CmB57y8FZt6DzBkfw "Burlesque – Try It Online")
Full solution. Saving a byte using `2.-` rather than `65.-` having looked at some other answers. Otherwise much the same as other answers.
```
wd # Split into words
m{ # For each word
{
** # ord(a)
2.+9.%+. # ((x+2)%9)+1
}ms # Map each letter then sum result
{
XX # XXplode into digits
++ # Sum digits
}
{ln # Number of digits
1!= # Not equal 1
}w! # While
}
sm # Are all the same
```
[Answer]
# TI-Basic, 92 bytes
```
Prompt Str1,Str2
"BCDEFGHIJKLMNOPQRSTUVWXYZ→Str3
"fPart(1/9sum(1+seq(9fPart(inString(Str3,sub(Ans,I,1))/9),I,1,length(Ans→u
Str1
u→S
Str2
u=S
```
Output is stored in `Ans` and displayed. Outputs `0` for incompatible numbers and `1` for compatible ones.
] |
[Question]
[
## Challenge:
### Input:
A sorted list of positive integers.
### Output:
The amount of integers which are still at the exact same index, after rotating the digits in each integer its index amount of times towards the left and sorting the modified list again.
**Example:**
Input: `[8,49,73,102,259,762,2782,3383,9217,37846,89487,7471788]`
Output (0-based indexing): `6`
Output (1-based indexing): `5`
*Why?*
0-based indexing:
```
After rotating each: [8,94,73,102,592,276,8227,3338,9217,63784,89487,7887471]
Sorted again: [8,73,94,102,276,592,3338,8227,9217,63784,89487,7887471]
Input indices: 0 1 2 3 4 5 6 7 8 9 10 11
Original input-list: [8,49,73,102,259,762,2782,3383,9217,37846,89487,7471788]
Modified list: [8,73,94,102,276,592,3338,8227,9217,63784,89487,7887471]
Modified indices: 0 2 1 3 5 4 7 6 8 9 10 11
Equal indices: ^ ^ ^ ^ ^ ^
So the output is: 6
```
1-based indexing:
```
After rotating each: [8,49,37,021,925,762,2278,3383,2179,37846,94878,8874717]
Sorted again: [8,(0)21,37,49,762,925,2179,2278,3383,37846,94878,8874717]
Input indices: 1 2 3 4 5 6 7 8 9 10 11 12
Original input-list: [8,49,73,102,259,762,2782,3383,9217,37846,89487,7471788]
Modified list: [8,21,37,49,762,925,2179,2278,3383,37846,94878,8874717]
Modified indices: 1 4 3 2 6 5 9 7 8 10 11 12
Equal indices: ^ ^ ^ ^ ^
So the output is: 5
```
## Challenge rules:
* The input-list is guaranteed to only contain positive integers.
* The input-list is guaranteed to be sorted from lowest to highest.
* The input-list is guaranteed to contain at least two items.
* As you can see above, both 0-based and 1-based indexing is allowed. **Please state in your answer which of the two you've used, since outputs can differ accordingly!**
* Leading `0`s after rotating are ignored, which can be seen with the 1-based example above, where the integer `102` becomes `021` after rotating, and is then treated as `21`.
* Integers are guaranteed unique in the input-list, and are guaranteed to remain unique after the rotations are completed.
* Note that we only look at the positions of the rotated integers in correlation with the positions of the input, not with the values of the input-list. To clarify what I mean by this: with the input-list `[1234,3412]` and 1-based indexing, the list becomes `[2341,1234]` after rotating each integer it's index amount of times, and then when sorted becomes `[1234,2341]`. Although both the original input-list and the rotated list contains the integer `1234` at the leading position, they aren't the same! The rotated `1234` was `3412` before. The 1-indexed output for this input-list is therefore `0`, since the two integers have swapped their positions.
* Input is flexible. Can be a list/stream/array of integers/strings/digit-arrays, etc. Please state what you've used if you don't take the inputs as integers.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input: [8, 49, 73, 102, 259, 762, 2782, 3383, 9217, 37846, 89487, 7471788]
0-based output: 6
1-based output: 5
Input: [1234, 3412]
0-based output: 2
1-based output: 0
Input: [2349, 2820, 17499, 21244, 29842, 31857, 46645, 56675, 61643, 61787]
0-based output: 3
1-based output: 0
Input: [4976, 11087, 18732, 22643, 52735]
0-based output: 2
1-based output: 3
Input: [4414, 5866, 7175, 8929, 14048, 16228, 16809, 19166, 24408, 25220, 29333, 44274, 47275, 47518, 53355]
0-based output: 4
1-based output: 4
Input: [11205, 16820, 63494]
0-based output: 1
1-based output: 3
```
Feel free to generate more random test cases with (or draw inspiration from) [this ungolfed 05AB1E program](https://tio.run/##yy9OTMpM/f9f6Ujj4R0u57YeafdT0Is/uvDw@tpziy/srX3UMOvwjnNbHzWtObfjcHetv5JyKJeSZ15BaYmVgpL94f0@57Ye3efhc25lbfWhlTpcSga6SYnFqSkK@aUlUDWH1kV46YUBpQyxSanbHd4LlP3/39AAAA), where the input is the size of the random list (NOTE: the output of this generator might not comply with the rule "*Integers are guaranteed unique in the input-list, and are guaranteed to remain unique after the rotations are completed*", so keep that in mind when using it.)
[Answer]
# [R](https://www.r-project.org/), ~~114~~ 107 bytes
-5 bytes thanks to Giuseppe.
[Outgolfed](https://codegolf.stackexchange.com/a/186219/86301) by digEmAll.
```
function(l){for(j in seq(l))l[j]=rep(l[j]%/%(e=10^(b=nchar(l[j]):1-1))%%10,j+1)[j+0:b]%*%e
sum(sort(l)==l)}
```
[Try it online!](https://tio.run/##NY/RbsIwDEXf@Yq8VEpGpsWOEztI/RLEpIFajaorW4Gnad/eORU8Xfvq@tiel75d@vt0up0vkx3db3@Z7WDOk7l2P9q7cT8c2rn7trVo3hrbtRDe7bGdTp8f8@q6HbyCc00DwQ9bcPthG3bHQ/PSdJvr/cteL/NNUW07ur@ltycrnorn6CGgx6RlVmVBH6NEXxDYRxbKXgoJeyYGFnFuU4cBI3kTCfBhaF@8QcHgDTCV2gCShrAIoWZBEntDOVPyJuXMKhkyxSos/ABR4awICLrTgHDUWcQ1lpBjesYIlJ0ka1gPU5YU1KVAgUQlI64ioZoFak7PCWpiwnollhgVSoSsJGKsEOIEGkkxpucmAAxpRdWprH@Sc8s/ "R – Try It Online")
0-indexed.
Ungolfed version:
```
function(l) {
n = length(l) # size of input
for (j in 1:n) {
b = nchar(l[j]) -1 # number of digits in l[j] -1
e = 10 ^ (b:0)
d = l[j] %/% e %% 10 # convert to vector of digits
l[j] = rep(d, j + 1)[j + 0:b] %*% e # rotate digits and convert back to an integer
}
sum(sort(l) == l) # number of integers which are in the same position
}
```
To rotate the `b` digits of an integer by `j` positions, the code repeats the digits many times, then takes the digits in positions `j+1` to `j+b`. For instance, to rotate `102` 4 times, keep the values marked with an `x` (positions 5 to 7):
```
102102102102
xxx
```
so the result is `021`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
ΣN._ï}-_O
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3GI/vfjD62t14/3//4@20DGx1DE31jE0MNIxMgUyzYC0uYWRjrGxhbGOpZGhuY6xuYWJmY6FpYmFuY65ibmhuYVFLAA "05AB1E – Try It Online")
Uses 0-based indexing.
Explanation:
```
Σ } # sort the input by
N._ # each number rotated its index to the left
ï # then cast to int (otherwise the sort is alphabetic)
- # subtract the input from the result
_O # then count the 0s
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~10~~ 9 bytes
0-based
```
í¶UñÈséYn
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=7bZV8chz6Vlu&input=WzgsNDksNzMsMTAyLDI1OSw3NjIsMjc4MiwzMzgzLDkyMTcsMzc4NDYsODk0ODcsNzQ3MTc4OF0)
```
í¶UñÈséYn :Implicit input of integer array U
í :Interleave with
Uñ :U sorted by
È :Passing each integer at 0-based index Y through the following function
s : Convert to string
é : Rotate right by
Yn : Y negated
¶ :Reduce each pair by testing for equality
:Implicit output of sum of resulting array
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Dṙ"JḌỤ=JS
```
[Try it online!](https://tio.run/##y0rNyan8/9/l4c6ZSl4Pd/Q83L3E1iv4////0RY6JpY65sY6hgZGOkamQKYZkDa3MNIxNrYw1rE0MjTXMTa3MDHTsbA0sTDXMTcxNzS3sIgFAA "Jelly – Try It Online")
Monadic link that takes a list of integers and returns an integer indicating the number of integers that remain in place after performing the rotation using 1-indexing.
### Explanation
```
D | Convert to decimal digits
ṙ"J | Rotate left by index
Ḍ | Convert back to integer
Ụ | Index in sorted list
=J | Check if equal to index in original list
S | Sum
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~104~~ ~~100~~ ~~97~~ 93 bytes
```
b=[int((s*-~i)[i:i+len(s)])for i,s in enumerate(input())]
print map(cmp,b,sorted(b)).count(0)
```
[Try it online!](https://tio.run/##LVDBboMwDL33KxCXko1NsePESaV9CeLQdkyN1AICqm2X/XoHdi/Js/P83ovH3@Uy9Pj4vuRrV8Ch@@nO@/3@cfpocr9U1fzy9pdNkw/59dr11Wxa8zVMRa7nIvdF199v3XRcuir3432pjGl347QOFrfjWJ1vY32q52Faus/qZMz7ebivmtY8NoemjGVdlJS2k912gsXtQq@9oBVHuZ2LQkoILDVHChuIiaJ0mBg4xrLdNSWgI2ERoDTWWlQxohUvpqQNQBIqpkjqBNGLIIVAfgM@BBYQIJBTwKvpJkyJJQaA1RgQ2WlyfJI9svNKJhAvH4MMrYG9/gElDJAlWQsExCeIVp8S6Mwa10bdE@pfMDknRkTIok@MKkzsQcjeOa8ZAND6p7TOh3U3VLb/ "Python 2 – Try It Online")
0-based indexing.
First rotates each number, and then compares the result with result, but sorted.
---
Saved:
* -3 bytes, thanks to Erik the Outgolfer
* -4 bytes, thanks to Kevin Cruijssen (and his rule-change)
[Answer]
# [R](https://www.r-project.org/), ~~90~~ ~~88~~ 85 bytes
```
function(x)sum(rank(as.double(substr(strrep(x,L<-sum(x|1)),y<-1:L,y+nchar(x)-1)))==y)
```
[Try it online!](https://tio.run/##NY9NbgIxDEb3PcUsE9VU8U9ip4IbcAmgoFalQzXDSIPUu08dBIvoS6znZ2dYTpvlNPWH69elD3Mcp58w7PrvsBvfPi7T/nwM47Qfr0PwMxx/wwzb9apR8x/GCLf1Ct@3cHvtD5@7wQUrr8bN5haXUzgEA6mgDJgIKPu1eKoRMBtDJVRgNSlgVUxBRVHNYnxpzUgs0LEgPQr@rtCRUYIOVWp7IIlDVE3IWbSs0EkpkqHLpahHwSLcQk0fIqlaXIHJZ3Zoyt5LdMcyKecnJujubMVhX8xdVsmHoiQxj0J0D0utWLFxvk7yImVqW1JldqkIqZtEqUlEMzqSmfNzEiKlfFe1ruL/lBiXfw "R – Try It Online")
* 0-indexed rotation
* rotation strategy inspired by [@RobinRyder's answer](https://codegolf.stackexchange.com/a/186173/41725)
* -5 bytes thanks to @Giuseppe
### Unrolled code with explanation :
```
function(x){
L=sum(x|1) # store the length of x
R=strrep(x,L) # repeat each string of vector x L times
S=substring(R,1:L,1:L+nchar(x)-1)) # for each string of R, extract a substring of the same
# length of the original number starting from index 1
# for the 1st element, index 2 for the 2nd and so on
# (this basically rotates the strings )
Y=as.double(S) # convert the strings to numbers
sum(rank(Y)==1:L) # return the number of times the ranks of Y
# match with their original positions
}
```
[Answer]
# [J](http://jsoftware.com/), ~~28~~ 26 bytes
-2 bytes thanks to Jonah
```
1#.i.@#=[:/:#\".@|.&>":&.>
```
[Try it online!](https://tio.run/##TU/LSgNBELznK4osJAg6Tr97FhICgidPXvUmBvXiD/jvaycL4mF6mqKquupr2bb9GYcZe9yiY6531/Dw/PS40NQ@22k6vMz38/S6baeftjtu5107LjcbbN7fPr5hOOCMhA6EgDqDrVavP5IhkoLBFJBIdeTQDIQGRebq0K8OxKIQJf4PFjbAyR0UOmolVgWP1HKmtIC6q8Hcw@DkKjUjYzWRq4mOcBD1uksZUsH4wjMOsZWnK09JYemOCmeVlAdIuybImS8zeyGDilExelZTrmg8RKTUHAoNLqmGUcJEzP6CVEPibheX0ngV0@UX "J – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~11~~ 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ìát'óJ♣á◄·
```
[Run and debug it](https://staxlang.xyz/#p=8da07427a24a05a011fa&i=[%228%22,+%2249%22,+%2273%22,+%22102%22,+%22259%22,+%22762%22,+%222782%22,+%223383%22,+%229217%22,+%2237846%22,+%2289487%22,+%227471788%22]%0A[%221234%22,+%223412%22]%0A[%222349%22,+%222820%22,+%2217499%22,+%2221244%22,+%2229842%22,+%2231857%22,+%2246645%22,+%2256675%22,+%2261643%22,+%2261787%22]%0A[%224976%22,+%2211087%22,+%2218732%22,+%2222643%22,+%2252735%22]%0A[%224414%22,+%225866%22,+%227175%22,+%228929%22,+%2214048%22,+%2216228%22,+%2216809%22,+%2219166%22,+%2224408%22,+%2225220%22,+%2229333%22,+%2244274%22,+%2247275%22,+%2247518%22,+%2253355%22]%0A[%2211205%22,+%2216820%22,+%2263494%22]&a=1&m=2)
This program uses 0-based indexing and takes input as an array of strings. I saved a byte by taking opportunity of the new input clarificatinos.
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, 80 bytes
```
map$d{$_.substr$_,0,$b%y///c,''}=$b++,@F;$\+=$d{$_}==$r++for sort{$a-$b}keys%d}{
```
[Try it online!](https://tio.run/##HcpNC8IgGADgv@LhHTuoU9ccRQiduvUPgqFtwehDUTsM8a/3Bj3nJyzxqRFfNsBcYOrSx6UcYWKSgWs2IcSNtW014Chlp/MRrtT8ZzUGIqV3H0nyMRewHFx9LFtq5loQleqlJmrc95KMu@EwfH3Iq38n5BfdSSWR2/AD "Perl 5 – Try It Online")
Takes input as space separated numbers on STDIN; gives 1-based result.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
sqVSJ.ev.<`bkQJ
```
[Try it online!](https://tio.run/##HYxBCkIxDAWvkgOET5O8NC14gr/7CG5EEEEQ3CiK4Olr6mpgGObxfd/GeD0P@3W5fpbd@XLf1jGOgIDJW61MIeFMrWtnEhS0RFX9o5Upu8xOgZJSXbUkupkxARp5QuicIFwycTP30w8 "Pyth – Try It Online") Uses 0-based indexing.
```
sqVSJ.ev.<`bkQJ Implicit: Q=eval(input())
.e Q Map elements of Q, as b and with index k, using:
`b Convert b to string
.< k Rotate the above left k places
v Convert back to integer
J Store the above as J
S Sort the above
qV J Vectorised equality check with the unsorted list
s Sum, implicit output
```
[Answer]
# APL+WIN, ~~23, 21~~ 19 bytes
2 bytes saved by inputting the integers as a nested vector of characters
```
+/i=⍋⍎¨(i←⍳⍴v)⌽¨v←⎕
```
1 indexed.
```
v←⎕ prompt for input.
(i←⍳⍴v)⌽¨ rotate each set of characters by input indices.
⍋⍎¨ convert characters to integers and get sorted indices.
+/i= sum where original and sorted indices are the same.
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##JY9BSgRBDEX3fQp3rchgJZVUUgtvoIdoRkYaGhQGBryACtqNm7nD7HXrZo5SF2mTuMmv/Ererxqep83DyzA9PW6207Dfj9u1Lcf7u/b6lbv2/rZbr2/G2zZ/tHk5ny5H89v83eafw1X7/D2fDm4sx9VG113Xa3/RU7Ui2QoktIocRomzqEvO6vcVQbwTpWKqldR7IQFR7TsDYg4cKiYHCtVoAYlcq1LwQNk3qRRiUy5FXAsUyqFiZOcRgS@yFk@0HI5gdCpQIv8AFMR/1RR@hZi2zKTxIYzXYM3Z6UQoDiXBwJEw@BznzNz/AQ "APL (Dyalog Classic) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~107~~ ~~99~~ 95 bytes
-8 bytes Thanks @Shaggy for accepting array of strings instead. Further golfed 4 bytes from this. Will not trigger memory error this time.
```
a=>[...b=a.map(F=(x,i)=>i--?F(x.slice(1)+x[c=0],i):x)].sort((p,q)=>q-p).map(x=>c+=x==b.pop())|c
```
[Try it online!](https://tio.run/##bVDBbsIwDL3vK3pMRBrVjhOnm8Ju/ARCousAdWK0UDT1sH/vHKZdpl7i2M9@79kfzVcztrduuJeX/v0wH1OT1ifV2M9mUFNaT6v9XuunU5qlvrXWvqVfbJPUZDqd1l1Zvm7UZMdz1x4U6NW0bVO1E@x50js79re7UoO5Suu1HPQfcbtKU0pvdugHpfV3O7@0/WXszwd77k/qqLbRFFSbgp0poEJToM9ZyD@O8joXBaoRWP4cKZgi1hQlY2LgGHfi@z8poCNpJ8AlVEDRwIiVaDLVOQEkmcA6UtaE6EWAQiBvCh8CSwgQyOXAkZdYqWbxBlBlbxDZ5RXwMeORnV@cIRBVH4NMyjI@74ZiB6giOQwExEeIVS7WkPvEaBXznTD7x9o5USBCFiZizCTEHqTFO@cXZQGw8g/eTBHkHCRt8w8 "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), ~~111~~ 107 bytes
-4 bytes Thanks @Arnauld!
```
a=>[...b=a.map((x,i)=>"".padEnd(x+i,x+=c='').substr(i,x.length))].sort((p,q)=>q-p).map(x=>c-=x==b.pop())|-c
```
[Try it online!](https://tio.run/##bVC5bsMwDN37FUaWSKgsmBQlyiiUrV8RZHCcoylS24ndwkP/3aUyFllE8XgH@dn8NGN7vwxT2fWH43JKS5M2W2vtPjX2qxmUms1Fp81qZYfm8N4d1Px6MfNratN6re34vR@nu5KKvR678/Sh9c6O/X1SajA3wd3KQT945rRpyzSntLdDPyitf8t2eWv7buyvR3vtz@qkttEUVJuCnSmgQlOgz1nIP47yOhelVSOw/DlSMEWsKUrGxMAx7rR@@U8K6EjGCfBZV5qigREr0WSqcwJIgsA6UtaE6EWAQiBvCh8CSwgQyOXAkZ@xUs3iDaDK3iCyyyvgA@ORnX@KIRBVH4MgZRmfd0OxA1SRHAYC4iPEKhdryHNitIr5Tpj9Y@2cKBAhCxMxZhJiDzLinfNPZQGw8g/eTBHkHCRjyx8 "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), ~~113~~ 111 bytes
```
a=>[...b=a.map((x,i)=>"".padEnd(x+i,x).substr(i,`${x}`.length))].sort((p,q)=>p-q).map((x,i)=>x-b[i]||c++,c=0)|c
```
[Try it online!](https://tio.run/##bVDNboMwDL7vKVC1A1HTCDtOHDTR256iqlRKf8bUAS1sQlr37MzpaZq4xHbs78d@L7/KvrrV3bBq2sNxOhVTWaw3xph9UZqPskvTUdeqWC8WpisPr80hHZe1HpXpP/f9cEtrvXv@Hn925nJszsObUlvTt7chTTt9FVi3uqq/NONqv6m393u1XOqqyNS9ml6qtunby9Fc2nN6SjdBJ5TrhK1OIEOdoIuVjxkHea0N0soRWHIO5HUScgpSMTFwCFulnv6TAlqScQKc60pTNDBgJppMeSwASRCYB4qaEJwIkPfkdOK8ZwkePNkYOPAcK@Us3gCy6A0C27gCPjAO2bpZDIGouuAFKcu4uBuKHaCM5DDgER8hZPEzhzgnRrMQ74TRP@bWigIRsjARYyQhdiAjzlo3KwuAmXvwRgov5yAZm34B "JavaScript (Node.js) – Try It Online")
0-indexed. May trigger memory error for very large entries.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 50 bytes
```
{sum ^$_ Z==sort {+[~] rotate .[$^i].comb,$i},^$_}
```
[Try it online!](https://tio.run/##HY/BasMwDIbvfQodwkiYKZYsW/IhL7LSlm60UFjISLJDKd2rZ1Iuln/r96dfP9fpu6zDA95u0K/P@XeAU3OGj76fx2mB5/vh7wjTuFyWK@wPzel@3H@Nw2do7q9gxtc6Xx5wa5tzB7dx2rUagGsASQEwUgDKrorfRO1MSa1VCcXuolwCaGU1JSwoql3YtUiJrc1IrkwYg5SiMYWrCyQ2B1VlZ6JmA3ApnAPkUsRKwcLJi6g4havYLMTos1AleSTaPJkk5c3DaNSsxZwWJns2snHIkW0xLERb0eiPFd1nQaL6nuT5qKZkRGYSI7GQQ1gymiWnlLcxiBTzxvEvxdbjLqz/ "Perl 6 – Try It Online")
0-based indexing. Also exposed a [Rakudo bug](https://github.com/rakudo/rakudo/issues/2937).
### Explanation
```
{ } # Anonymous block
sort ^$_ # Sort indices 0..n
{ }, # by
.[$^i] # element at index i
.comb # split into chars
rotate ,$i # rotated i times
[~] # joined
+ # converted to number
^$_ Z== # Pairwise equal to original indices 0..n
sum # Sum of equal indices
```
[Answer]
# [PHP](https://php.net/), ~~159~~ ~~141~~ ~~134~~ 130 bytes
```
function($a){foreach($a as$x){for($j=$i;$j--;$x=substr($x,1).$x[0]);$b[$x]=$i++;}ksort($b);foreach($b as$z)$y+=++$j==$z;return$y;}
```
[Try it online!](https://tio.run/##ZVJNa9tAEL37VyxhQRJSimZ29kNVRQ@l0EOhuRsRbFfGcUEylgxKgn@7O7N2fMllvvbNm8fMHnaHy7fvh91B6a1qLttTv5lehj7Vq@x9Oxy71WbHsVqNeo6FVO8b/VLr/eNjredmPK3HiYtzAdkXPS/LNqv1eqnnllF5Xp//jcNxSvU6q@9sa2F7y/Rr3uQ50zX6rT520@nY69f6fKkXCz114zSqRi0XSi2TkBQJVWy8YQMlskUbCy7GPogzJsh7heAl84Ec@1BRkNyTBx9C0haRE9CQoAjwo8QV4cSApYzxVMUUkASJVaA4BYIVPnKOLHvrnBfvwJGJ3vO8GyVVXjQAlFEDBG@iYLxiLXpj71gCmWODkxYWa6N6FBFAJckWwCFefShjvYKIZolliFvBKB4rY2QAEXohJY@RjrwFwVlj7H0wAJb2ShqbHe@BknbR8iVuR1Oput1kNXKkMvXOrd1mN6j9OPTPXb8Z/nZpfCrU06@n559/ftcfkIcfw6mfvqqHgj/ZJ9D58h8 "PHP – Try It Online")
Zero-based indexing.
***Ungolfed:***
```
function( $a ) {
// iterate through digits
foreach( $a as $x ) {
// rotate the digits the number of times based on their index
for( $j = $i; $j--; ) {
// move first digit to last digit
$x = substr( $x, 1 ) . $x[0];
}
// the new number is used as key for sort, value is the original index
$b[ $x ] = $i++;
}
// sort by the new numbers
ksort( $b );
// iterate sorted array
foreach( $b as $z ) {
// if new index matches original index, increment count ($y)
if ( ++$j == $z ) {
$y++;
}
}
return $y;
}
```
* -4 bytes taking input as array of strings, thx to @KevinCruijssen for pointing that out.
[Answer]
# [K (Kona)](https://github.com/kevinlawler/kona), ~~25~~ 21bytes
-4 bytes thanks to ngn!
```
{+/t=<.:'(t:!#x)!'$x}
```
[Try it online!](https://tio.run/##DcZNCoAgEAbQq3xSUBH96FgzSh2mjRuhNi6E6Ozm6r04xee@Sgn@HZd0HrPv@uRVkwfVtfkrAQLrwAS9Gpitdq@yGBAJwRnNIBa7Q5wVBlvWLFJ@ "K (Kona) – Try It Online")
[Answer]
# T-SQL query, 99 bytes
Sql has no rotating method, so I had to implement my own syntax, since this is a query, it had to be done without looping.
0-based indexing.
Using a table variable as input.
```
SELECT-sum(1/~(z*3))FROM(SELECT~i+rank()over(order by
substring(n+n,i%len(n)+1,len(n))*1)z FROM @)c
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1064982/rotated-position-of-integers)**
[Answer]
# [Icon](https://github.com/gtownsend/icon), 141 bytes
```
procedure f(l)
n:=0
b:=[]
t:=l[k:=1to*l]&m:=k%*t&t:=t[m+1:0]||t[1:m+1]&put(b,[+t,l[k]])&\x
l[i:=1to*l]=sortf(b,1)[i,2]&n+:=1&\x
return n
end
```
[Try it online!](https://tio.run/##ZVHLbsMgELz7K7jUshsO7LKwiyV/CfWhD0eymjiVS9Qe8u/pEqlSlXIZ2J2ZHWB5Pa3X68d2ep3fztts9t2hb9ZhdM3LMOapKcN4yO/DCOX0eJja4zC@PzyWVsslH3cwuOlyKRkG3U/tx7l0LzbvilXNNPXt03dzyMuvevw8bWWvDOjzYnFq1522lGSabS7nbTVrM69vf9Icn5e16xuj62tbytztuyyWkmVvwaHFoNuoyILWe/E2IbD1LBStJBK2TAwsMvV3NoCerPEE@K@lnWQNCjprgCnVAyApHZMQqgoksDUUIwVrQoysECGSr8DC/ywpcVQzcJrIgLBXF8SbICD7oAJzpyDQgUGi6vQGOkASahIgR6IQEW8grhYTVJ5mdFrEgDU6Ju/VnwhZnYixmhAHUErwPoT7lCYDoAs312oQ9R2okuqn/AA "Icon – Try It Online")
1-based indexing
[Answer]
# [Perl 5](https://www.perl.org/), 104 bytes
```
sub f{my$i;grep/\d+$/&&$i++==$&,sort{$a<=>$b}map{my$n=shift;map$n=~s/(.)(.+)/$2$1/,1..$_;"$n.$_"}0..$#_}
```
[Try it online!](https://tio.run/##bUzbToQwEH3fr5jUCYEwoVvK0mKt@iEmGzbCSpRLaI3ZbPDXsWyMT87LmXOdmvnjsK7u8wTttb9gZ85zM/GX1xR5FGGXptZiRG6c/RXrB/uIp6Wvpy06WPfWtd4EGv5vx@MsibM04Zij4CSyDI@G4RCALfvA7o7L2l/g2TfO21hTUZGSJPY55YfwlgGVzklKLanKhSKpdFGSrgqtSBVKKK0TswsTeB49WGjj21bQprkb/B8Ha6Hcwe2egI3vBF918EvYeluZ/br3wIYg/Zcw6w8 "Perl 5 – Try It Online")
0-based indexing in Perl. Ungolfed and commented:
```
sub f {
my $i; #index counter
grep /\d+$/ && $i++==$&, #keep/return elems where $i matches original index stored as decimals
sort { $a<=>$b } #sort rotated elems numerically (<=> is the numerical comparison op
map { #loop through input
my $n = shift; #shift(@_) got elem from input array @_
map $n=~s/(.)(.+)/$2$1/, 1..$_; #rotate left times current index
"$n.$_" #use rotated number with original index number as decimals (to dont affect sort)
}
0..$#_
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-ap`, 77 bytes
1-indexed. Was temp deleted earlier because I missed part of the spec.
`-p` reads a line of STDIN, and outputs `$_` at the end. `-a` splits that read line by spaces and saves it as `$F`.
```
i=0
$_=$F.zip($F.sort_by{|s|s.chars.rotate(i+=1).join.to_i}).count{|a,b|a==b}
```
[Try it online!](https://tio.run/##Dca7DoMgFADQvV9xBwdNWyKPeq8Da3/DgGlSOggBHKz466VO58TVbrU63V@aSTdP9nWhPUk@5slue0klsfltYmLRZ5Nfrbtq3rGPdwvLfnJHx2a/Lnkv5maL0doetRKoEVAC7wWIx9nhFEmAlCRhFBxBIqkBaFSEgAo5Ev18yM4vqd5N@AM "Ruby – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 65 bytes
```
o=Ordering
g=Count[o@MapIndexed[FromDigits@*RotateLeft,#]-o@#,0]&
```
[Try it online!](https://tio.run/##LY6xCsIwFAB3v6JQcJAnbZPYlw6FgCIUFMW1dAg2xgxNJD5BEL89dnC6G264SdPdTJrcVacU2lMcTXTeLmy7DS9PfVBH/ej8aN5m7PcxTDtnHT3V6hJIkzmYG0E@rIPKoRyWyarOk7Em/rOPBNEAcqhKBmwzaz0TJQPOJYeGVQgcpahBNkIioMAKpfxmRZGd5xFKPw "Wolfram Language (Mathematica) – Try It Online")
1-based. We take the input as a list of digit lists, which works because Mathematica orders lists by length, then lexicographically, i.e. just like the original numbers.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 204 201 bytes
The only interesting thing here (possibly) is the use of `eval`. The algorithm is also clunky in that it creates a sorted list then reads it in order to determine changed index/indices.
1-based solution. My thanks to @RobinRyder for the helpful rotation algorithm.
```
for((i=1;i<$#+1;i++));do eval s=\${$i};for((j=0;j<i;j++));do eval s=${s}\${$i};done;eval n=\${s:$i:\${#$i}};echo $n $i;done|sort -nk1,1|{ i=1;c=0;while read d j;do((i==j))&&((c++));((i++));done;echo $c; }
```
[Try it online!](https://tio.run/##XY5BCoMwEEWvMmAQxQpGrVpHb9KNTVJMKgZMaRfq2dMYXHU18OfN/PcYzGiNeEOaQnmrK6A0a2qgTV3kkOdVWcA1r4urfeolimRPUXYkSNxIkjhGrkF8hglMfycrkTt6TPUZqk6i@mPIavaT43oW6OP5ODUtka2bgdvtKNiogcxApOc2oxcnOL/ohW4rHBLMNXxHOQlYxMCBg3Lk4derOA7DKGK@2iWnwtHmvzKE3Vr7Aw "Bash – Try It Online")
Revised code following Kevin's comments;
[Try it online!](https://tio.run/##VY5BCoMwEEWvMmAQxQpGrbGOuUk3VlNMKgZMaRfq2dMY3HQ18OfN/PfozGiNeEOaQnljFVCa1QxozYoc8rwqC7jmrLjap16iSPIMk0S2nAQYxzhoEJ9uAsPvZCVyRw8pB6lWokqSP4asZj@5Qc8CfTwfp6YhsnEzcLsdRT9qIDMQ6bnN6MXpzS96odsKklPsXcN3lJOARXQDDKAcedhxFcdhGEW9r3bJqXC0@a897tbaHw "Bash – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), ~~200~~ 160 bytes
```
def f(a:Seq[String])=
a.zipWithIndex
.map(x=>{val r=x._2%x._1.size;x._1.drop(r)+x._1.take(r)->x._2})
.sortBy(_._1.toInt)
.zipWithIndex
.filter(x=>x._1._2==x._2)
.size
```
[Try it online!](https://tio.run/##VU7BSsQwEL3vV4TCQoIabFo3aSULetvzIh5EyrhNd6PdtKZBulv67TXJQfDyZt68mTdvOEALS/fxqQ4OjWha1apBZ9AGgz0OJXqyFi5ve2e1Ob6TEr0Y7ZBE0xL2GgzlXn3/yRLoVfev2p12plYjPUOPR7mdfqBFVo60YmsPKR30VT3GrrZdjy25icTBl/Lkbhs2Z0KHzrrnC66i1u2MI//tG906ZcOHeF4xGX@Q6L/0PpNrDfYpfUaciOQ2yQsPPPOQ3jOP7CEONrHnIpQsE0EvWMoD4yLf@CqKXATOc55yIRJCEFnN8/IL "Scala – Try It Online")
0-indexed. 160 chars after removing indentation and newlines. This prints 6:
```
println( f(Seq("8","49","73","102","259","762","2782","3383","9217","37846","89487","7471788")) )
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 12 bytes
```
µ¥Ǔ&›₀β;=';L
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C2%B5%C2%A5%C7%93%26%E2%80%BA%E2%82%80%CE%B2%3B%3D%27%3BL&inputs=%5B8%2C49%2C73%2C102%2C259%2C762%2C2782%2C3383%2C9217%2C37846%2C89487%2C7471788%5D&header=&footer=)
```
µ ; # Sort by...
¥ # Register
Ǔ # Shift right by
&› # Increment register
₀β # Cast to int
=';L # Find those where they're equal
```
] |
[Question]
[
Consider an array of integers:
```
[1, 0, 9, 1, 3, 8]
```
There are a lot of ways to partition this list into consecutive sublists. Here are three:
```
A: [[1, 0, 9], [1, 3, 8]]
B: [[1], [0, 9], [1, 3], [8]]
C: [[1, 0], [9, 1], [3, 8]]
```
We will call a partition *Y* and refinement of another partition *X* if *X* can be obtained from *Y* by joining some of its sublists back together.
So `B` is a refinement of `A`: if we join the first two and the last two sublists back together, we obtain `A`. But `C` is *not* a refinement of `A`: we'd have to split up the `9` and the `1` in order to recover `A` from it. Also, any partition is trivially a refinement of itself.
Note that we're not allowed to rearrange any sublists or elements at any point.
## The Challenge
Given two partitions (lists of lists of integers) `X` and `Y`, determine whether `Y` is a refinement of `X`.
You may assume that the partitions will only contain integers from `0` to `9`, inclusive. You must not assume that `X` and `Y` are partitions of the same list (if they aren't, they also are not refinements of each other). `X` and/or `Y` may be empty but will never contain empty sublists.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
Input may be taken in any convenient string or list format. Since the elements will only be single-digit integers, you may choose to omit a delimiter within the sublists, but make sure that leading `0`s are possible. You may choose to take `X` and `Y` in opposite order.
Output should be [truthy](http://meta.codegolf.stackexchange.com/a/2194/8478) if `Y` is a refinement of `X` and [falsy](http://meta.codegolf.stackexchange.com/a/2194/8478) otherwise.
Your code must be able to solve each of the test cases below in 1 second on a reasonable desktop machine. (This is merely a sanity check to avoid simple brute force solutions.)
This is code golf, so the shortest answer (in bytes) wins.
## Test Cases
Each test case is on its own line, written as `X Y`. I'm using GolfScript/CJam-style array notation to save some horizontal space:
Truthy:
```
[] []
[[0]] [[0]]
[[1 0 9 1 3 8]] [[1 0 9] [1 3 8]]
[[1 0 9 1 3 8]] [[1 0 9 1 3] [8]]
[[1 0 9 1 3 8]] [[1] [0] [9] [1] [3] [8]]
[[1 0 9] [1 3 8]] [[1 0 9] [1 3 8]]
[[1 0 9] [1 3 8]] [[1] [0 9] [1 3] [8]]
[[9 8 8 5 8 2 7] [5] [1 4] [2 0 0 6 0 8 4 2 6 4 2 3 7 8 7 3 9 5 7 9 8 2 9 5] [3 9 8] [7 1 4 9 7 4 5 9] [3 3 3] [9 0 7 8] [3 9 4 7 2 7 8 0 3 0] [8 2 2 7 3 9 3 2] [2 9 0 8 5 4 1 8 5 5 6 2 0 9 2 7 7 9 2 7] [3 6] [1 2 7 7 4 4 2 9]] [[9 8] [8] [5 8 2] [7] [5] [1 4] [2] [0 0 6] [0] [8 4 2] [6 4] [2] [3] [7 8] [7 3] [9] [5 7 9] [8 2] [9 5] [3] [9 8] [7 1 4] [9 7] [4 5 9] [3 3] [3] [9 0] [7 8] [3] [9] [4] [7 2] [7 8] [0] [3 0] [8 2] [2] [7 3] [9 3] [2] [2] [9] [0] [8 5 4] [1 8] [5 5] [6] [2 0] [9] [2] [7 7 9] [2 7] [3 6] [1 2] [7 7] [4 4 2] [9]]
```
Falsy:
```
[[0]] []
[[0]] [[1]]
[[1 0 9]] [[1 0 9] [1 3 8]]
[[1 0 9] [1 3 8]] [[1 0 9 1 3 8]]
[[1 0 9] [1 3 8]] [[1 0 9]]
[[1 0 9] [1 3 8]] [[1 0] [9]]
[[1 0 9] [1 3 8]] [[1 0] [9 1] [3 8]]
[[1] [0 9] [1 3] [8]] [[1 0 9] [1 3 8]]
[[9 8 8 5 8 2 7] [5] [1 4] [2 0 0 6 0 8 4 2 6 4 2 3 7 8 7 3 9 5 7 9 8 2 9 5] [3 9 8] [7 1 4 9 7 4 5 9] [3 3 3] [9 0 7 8] [3 9 4 7 2 7 8 0 3 0] [8 2 2 7 3 9 3 2] [2 9 0 8 5 4 1 8 5 5 6 2 0 9 2 7 7 9 2 7] [3 6] [1 2 7 7 4 4 2 9]] [[9 8] [8] [5 8 2] [7] [5 1] [4] [2] [0 0 6] [0] [8 4 2] [6 4] [2] [3] [7 8] [7 3] [9] [5 7 9] [8 2] [9 5] [3] [9 8] [7 1 4] [9 7] [4 5 9] [3 3] [3] [9 0] [7 8] [3] [9] [4] [7 2] [7 8] [0] [3 0] [8 2] [2] [7 3] [9 3] [2] [2] [9] [0] [8 5 4] [1 8] [5 5] [6] [2 0] [9] [2] [7 7 9] [2 7] [3 6] [1 2] [7 7] [4 4 2] [9]]
```
## 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
```
```
<script>site = 'meta.codegolf'; postID = 5314; isAnswer = true; QUESTION_ID = 51719</script><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script>
```
## Related Challenges
* [Compute the Join and Meet of Partitions](https://codegolf.stackexchange.com/q/43177/8478)
[Answer]
# Pyth, 19 bytes
```
&gF_m{.u+NYdYQqFsMQ
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=%26gF_m%7B.u%2BNYdYQqFsMQ&input=%5B%5B1%2C0%2C9%2C1%2C3%2C8%5D%5D%2C%5B%5B1%2C0%2C9%5D%2C%5B1%2C3%2C8%5D%5D&debug=0) or [Test harness](https://pyth.herokuapp.com/?code=QFQ.Qp%22+%3D%3E+%22Q%0A%26gF_m%7B.u%2BNYdYQqFsMQ&input=%22Test-Cases%22%0A%5B%5D%2C%5B%5D%0A%5B%5B0%5D%5D%2C%5B%5B0%5D%5D%0A%5B%5B1%2C0%2C9%2C1%2C3%2C8%5D%5D%2C%5B%5B1%2C0%2C9%5D%2C%5B1%2C3%2C8%5D%5D%0A%5B%5B1%2C0%2C9%2C1%2C3%2C8%5D%5D%2C%5B%5B1%2C0%2C9%2C1%2C3%5D%2C%5B8%5D%5D%0A%5B%5B1%2C0%2C9%2C1%2C3%2C8%5D%5D%2C%5B%5B1%5D%2C%5B0%5D%2C%5B9%5D%2C%5B1%5D%2C%5B3%5D%2C%5B8%5D%5D%0A%5B%5B1%2C0%2C9%5D%2C%5B1%2C3%2C8%5D%5D%2C%5B%5B1%2C0%2C9%5D%2C%5B1%2C3%2C8%5D%5D%0A%5B%5B1%2C0%2C9%5D%2C%5B1%2C3%2C8%5D%5D%2C%5B%5B1%5D%2C%5B0%2C9%5D%2C%5B1%2C3%5D%2C%5B8%5D%5D%0A%5B%5B9%2C8%2C8%2C5%2C8%2C2%2C7%5D%2C%5B5%5D%2C%5B1%2C4%5D%2C%5B2%2C0%2C0%2C6%2C0%2C8%2C4%2C2%2C6%2C4%2C2%2C3%2C7%2C8%2C7%2C3%2C9%2C5%2C7%2C9%2C8%2C2%2C9%2C5%5D%2C%5B3%2C9%2C8%5D%2C%5B7%2C1%2C4%2C9%2C7%2C4%2C5%2C9%5D%2C%5B3%2C3%2C3%5D%2C%5B9%2C0%2C7%2C8%5D%2C%5B3%2C9%2C4%2C7%2C2%2C7%2C8%2C0%2C3%2C0%5D%2C%5B8%2C2%2C2%2C7%2C3%2C9%2C3%2C2%5D%2C%5B2%2C9%2C0%2C8%2C5%2C4%2C1%2C8%2C5%2C5%2C6%2C2%2C0%2C9%2C2%2C7%2C7%2C9%2C2%2C7%5D%2C%5B3%2C6%5D%2C%5B1%2C2%2C7%2C7%2C4%2C4%2C2%2C9%5D%5D%2C%5B%5B9%2C8%5D%2C%5B8%5D%2C%5B5%2C8%2C2%5D%2C%5B7%5D%2C%5B5%5D%2C%5B1%2C4%5D%2C%5B2%5D%2C%5B0%2C0%2C6%5D%2C%5B0%5D%2C%5B8%2C4%2C2%5D%2C%5B6%2C4%5D%2C%5B2%5D%2C%5B3%5D%2C%5B7%2C8%5D%2C%5B7%2C3%5D%2C%5B9%5D%2C%5B5%2C7%2C9%5D%2C%5B8%2C2%5D%2C%5B9%2C5%5D%2C%5B3%5D%2C%5B9%2C8%5D%2C%5B7%2C1%2C4%5D%2C%5B9%2C7%5D%2C%5B4%2C5%2C9%5D%2C%5B3%2C3%5D%2C%5B3%5D%2C%5B9%2C0%5D%2C%5B7%2C8%5D%2C%5B3%5D%2C%5B9%5D%2C%5B4%5D%2C%5B7%2C2%5D%2C%5B7%2C8%5D%2C%5B0%5D%2C%5B3%2C0%5D%2C%5B8%2C2%5D%2C%5B2%5D%2C%5B7%2C3%5D%2C%5B9%2C3%5D%2C%5B2%5D%2C%5B2%5D%2C%5B9%5D%2C%5B0%5D%2C%5B8%2C5%2C4%5D%2C%5B1%2C8%5D%2C%5B5%2C5%5D%2C%5B6%5D%2C%5B2%2C0%5D%2C%5B9%5D%2C%5B2%5D%2C%5B7%2C7%2C9%5D%2C%5B2%2C7%5D%2C%5B3%2C6%5D%2C%5B1%2C2%5D%2C%5B7%2C7%5D%2C%5B4%2C4%2C2%5D%2C%5B9%5D%5D%0A%5B%5B0%5D%5D%2C%5B%5D%0A%5B%5B0%5D%5D%2C%5B%5B1%5D%5D%0A%5B%5B1%2C0%2C9%5D%5D%2C%5B%5B1%2C0%2C9%5D%2C%5B1%2C3%2C8%5D%5D%0A%5B%5B1%2C0%2C9%5D%2C%5B1%2C3%2C8%5D%5D%2C%5B%5B1%2C0%2C9%2C1%2C3%2C8%5D%5D%0A%5B%5B1%2C0%2C9%5D%2C%5B1%2C3%2C8%5D%5D%2C%5B%5B1%2C0%2C9%5D%5D%0A%5B%5B1%2C0%2C9%5D%2C%5B1%2C3%2C8%5D%5D%2C%5B%5B1%2C0%5D%2C%5B9%5D%5D%0A%5B%5B1%2C0%2C9%5D%2C%5B1%2C3%2C8%5D%5D%2C%5B%5B1%2C0%5D%2C%5B9%2C1%5D%2C%5B3%2C8%5D%5D%0A%5B%5B1%5D%2C%5B0%2C9%5D%2C%5B1%2C3%5D%2C%5B8%5D%5D%2C%5B%5B1%2C0%2C9%5D%2C%5B1%2C3%2C8%5D%5D%0A%5B%5B9%2C8%2C8%2C5%2C8%2C2%2C7%5D%2C%5B5%5D%2C%5B1%2C4%5D%2C%5B2%2C0%2C0%2C6%2C0%2C8%2C4%2C2%2C6%2C4%2C2%2C3%2C7%2C8%2C7%2C3%2C9%2C5%2C7%2C9%2C8%2C2%2C9%2C5%5D%2C%5B3%2C9%2C8%5D%2C%5B7%2C1%2C4%2C9%2C7%2C4%2C5%2C9%5D%2C%5B3%2C3%2C3%5D%2C%5B9%2C0%2C7%2C8%5D%2C%5B3%2C9%2C4%2C7%2C2%2C7%2C8%2C0%2C3%2C0%5D%2C%5B8%2C2%2C2%2C7%2C3%2C9%2C3%2C2%5D%2C%5B2%2C9%2C0%2C8%2C5%2C4%2C1%2C8%2C5%2C5%2C6%2C2%2C0%2C9%2C2%2C7%2C7%2C9%2C2%2C7%5D%2C%5B3%2C6%5D%2C%5B1%2C2%2C7%2C7%2C4%2C4%2C2%2C9%5D%5D%2C%5B%5B9%2C8%5D%2C%5B8%5D%2C%5B5%2C8%2C2%5D%2C%5B7%5D%2C%5B5%2C1%5D%2C%5B4%5D%2C%5B2%5D%2C%5B0%2C0%2C6%5D%2C%5B0%5D%2C%5B8%2C4%2C2%5D%2C%5B6%2C4%5D%2C%5B2%5D%2C%5B3%5D%2C%5B7%2C8%5D%2C%5B7%2C3%5D%2C%5B9%5D%2C%5B5%2C7%2C9%5D%2C%5B8%2C2%5D%2C%5B9%2C5%5D%2C%5B3%5D%2C%5B9%2C8%5D%2C%5B7%2C1%2C4%5D%2C%5B9%2C7%5D%2C%5B4%2C5%2C9%5D%2C%5B3%2C3%5D%2C%5B3%5D%2C%5B9%2C0%5D%2C%5B7%2C8%5D%2C%5B3%5D%2C%5B9%5D%2C%5B4%5D%2C%5B7%2C2%5D%2C%5B7%2C8%5D%2C%5B0%5D%2C%5B3%2C0%5D%2C%5B8%2C2%5D%2C%5B2%5D%2C%5B7%2C3%5D%2C%5B9%2C3%5D%2C%5B2%5D%2C%5B2%5D%2C%5B9%5D%2C%5B0%5D%2C%5B8%2C5%2C4%5D%2C%5B1%2C8%5D%2C%5B5%2C5%5D%2C%5B6%5D%2C%5B2%2C0%5D%2C%5B9%5D%2C%5B2%5D%2C%5B7%2C7%2C9%5D%2C%5B2%2C7%5D%2C%5B3%2C6%5D%2C%5B1%2C2%5D%2C%5B7%2C7%5D%2C%5B4%2C4%2C2%5D%2C%5B9%5D%5D&debug=0)
I'm using Pyth's tuple/list format as input. Simply replace the spaces of the test cases with commas.
### Explanation:
```
implicit: Q is the evaluated input
m Q map each input list d to:
.u dY reduce with intermediate states over d, initial value = []
+NY update initial value N with sum of N and Y (current element of d)
{ generate a set
_ invert
gF check, if the first element is >= (superset) than the second
& and
sMQ check, if the joined lists of the input
qF are equal
```
Since the pseudo-code is still a little bit confusing, I'll demonstrate the algorithm using an example input.
```
Input: [[1,0,9],[1,3,8]],[[1],[0,9],[1,3],[8]]
```
The `.u+NYdY` part computes all continuous sublists, that contain the first element.
```
[[1,0,9],[1,3,8]] => [[], [1,0,9], [1,0,9,1,3,8]]
[[1],[0,9],[1,3],[8]] => [[], [1], [1,0,9], [1,0,9,1,3], [1,0,9,1,3,8]]
```
`B` is a refinement of the `A`, iff each continuous sublist of `A` is also a continuous sublist of `B` (there's only one exception).
So I simply check, if the set of continuous sublists of `A` is a subset of the set of continuous sublists of `B` (`gF_m.u+NYdYQ`).
The only exception is, if the first input list contains less elements than the second input list. For instance `<Fm.u+YdYQ` would return `True` for the input `[[1]],[[1],[2]]`.
Therefore I also check if the joined lists are also equal `&...qFsMQ`.
[Answer]
# CJam, ~~13~~ ~~10~~ 9 bytes
```
lr.-F-U-!
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=ll.-F-U-!&input=1%3B0%3B9%2C1%3B3%3B8%0A1%2C0%3B9%2C1%3B3%2C8).
*Thanks to @MartinBüttner for suggesting [@edc65's ingenious input format](https://codegolf.stackexchange.com/a/51749).*
*Thanks to @jimmy23013 for improving the input format and golfing off 3 additonal bytes.*
### I/O
**Input**
Sublists are separated by `;` and from each other by `,`:
```
1;0;9,1;3;8
1,0;9,1;3,8
```
**Output**
```
1
```
### How it works
```
lr e# Read line and a whitespace-separated token from STDIN.
.- e# Vectorized difference. Pushes the differences of corresponding code points.
F- e# Remove all occurrences of 15 (';' - ',') from the array.
U- e# Remove all occurrences of 0 from the array.
! e# Push 1 if the resulting array is empty and 0 if not.
```
For strings of different length, `.-` will leave characters in the array, which cannot be equal to the integers 0 or 15.
[Answer]
# JavaScript (*ES6*), 67 ~~70~~
**Edit** 3 bytes saved thx @apsillers
Run the snippet below in Firefox to test
```
f=(a,b)=>a+''==b // same values in the lists ?
&![...a.join(' ')].some((c,p)=>c<','&b.join(c)[p]>c) // splits in a are present in b?
// TEST
out=x=>O.innerHTML += x+'\n';
OK=[
[[],[]],
[[[0]],[[0]]],
[[[1,0,9,1,3,8]],[[1,0,9],[1,3,8]]],
[[[1,0,9,1,3,8]],[[1,0,9,1,3],[8]]],
[[[1,0,9,1,3,8]],[[1],[0],[9],[1],[3],[8]]],
[[[1,0,9],[1,3,8]],[[1,0,9],[1,3,8]]],
[[[1,0,9],[1,3,8]],[[1],[0,9],[1,3],[8]]],
[[[9,8,8,5,8,2,7],[5],[1,4],[2,0,0,6,0,8,4,2,6,4,2,3,7,8,7,3,9,5,7,9,8,2,9,5],[3,9,8],[7,1,4,9,7,4,5,9],[3,3,3],[9,0,7,8],[3,9,4,7,2,7,8,0,3,0],[8,2,2,7,3,9,3,2],[2,9,0,8,5,4,1,8,5,5,6,2,0,9,2,7,7,9,2,7],[3,6],[1,2,7,7,4,4,2,9]],[[9,8],[8],[5,8,2],[7],[5],[1,4],[2],[0,0,6],[0],[8,4,2],[6,4],[2],[3],[7,8],[7,3],[9],[5,7,9],[8,2],[9,5],[3],[9,8],[7,1,4],[9,7],[4,5,9],[3,3],[3],[9,0],[7,8],[3],[9],[4],[7,2],[7,8],[0],[3,0],[8,2],[2],[7,3],[9,3],[2],[2],[9],[0],[8,5,4],[1,8],[5,5],[6],[2,0],[9],[2],[7,7,9],[2,7],[3,6],[1,2],[7,7],[4,4,2],[9]]]
];
KO=[
[[[0]],[]],
[[[0]],[[1]]],
[[[1,0,9]],[[1,0,9],[1,3,8]]],
[[[1,0,9],[1,3,8]],[[1,0,9,1,3,8]]],
[[[1,0,9],[1,3,8]],[[1,0,9]]],
[[[1,0,9],[1,3,8]],[[1,0],[9]]],
[[[1,0,9],[1,3,8]],[[1,0],[9,1],[3,8]]],
[[[1],[0,9],[1,3],[8]],[[1,0,9],[1,3,8]]],
[[[9,8,8,5,8,2,7],[5],[1,4],[2,0,0,6,0,8,4,2,6,4,2,3,7,8,7,3,9,5,7,9,8,2,9,5],[3,9,8],[7,1,4,9,7,4,5,9],[3,3,3],[9,0,7,8],[3,9,4,7,2,7,8,0,3,0],[8,2,2,7,3,9,3,2],[2,9,0,8,5,4,1,8,5,5,6,2,0,9,2,7,7,9,2,7],[3,6],[1,2,7,7,4,4,2,9]],[[9,8],[8],[5,8,2],[7],[5,1],[4],[2],[0,0,6],[0],[8,4,2],[6,4],[2],[3],[7,8],[7,3],[9],[5,7,9],[8,2],[9,5],[3],[9,8],[7,1,4],[9,7],[4,5,9],[3,3],[3],[9,0],[7,8],[3],[9],[4],[7,2],[7,8],[0],[3,0],[8,2],[2],[7,3],[9,3],[2],[2],[9],[0],[8,5,4],[1,8],[5,5],[6],[2,0],[9],[2],[7,7,9],[2,7],[3,6],[1,2],[7,7],[4,4,2],[9]]]
];
dump=l=>l.map(x=>'['+x+']').join(',');
out('YES');
OK.forEach(l=>out(f(l[0],l[1])+' a['+dump(l[0])+'] b['+dump(l[1])+']'));
out('NO');
KO.forEach(l=>out(f(l[0],l[1])+' a['+dump(l[0])+'] b['+dump(l[1])+']'));
```
```
<pre id=O></pre>
```
[Answer]
# C, 69 ~~75~~
A function with 2 string parameters, returning 0 or 1.
Parameter format: sublist separated with spaces (`' '`), list elements separated with commas.
Example: `"1,0,9 1,3,8"` `"1,0 9,1,3,8"`
```
f(char*a,char*b){for(;*a-44?*a&&*b==*a:*b<48;a++)b++;return!(*b|*a);}
```
*Less golfed*
```
int f(char *a, char *b)
{
// expected in a,b: digit,separator,digit... with separator being ' ' or ','
for(; *a; a++,b++)
// ' ' or digit in a must be the same in b
// comma in a must be comma or space in b
if (*a != ',' ? *b != *a : *b > *a) return 0;
return !*b; // must have a null in *b too
}
```
**Test** [Ideone](http://ideone.com/ao3uti) (outdated)
[Answer]
# Haskell, 76 bytes
```
[]#[]=1<2
[x]#[y]=x==y
x@(a:b)#(c:d:e)|a==c=b#(d:e)|1<2=x#((c++d):e)
_#_=2<1
```
Returns `True` or `False`. Example usage: `[[1,0,9],[1,3,8]] # [[1,0],[9]]` -> `False`.
Simple recursive approach: if the first elements match, go on with the tails, else start over but concatenate the two elements at the front of the second list. Base cases are: both lists empty -> `True`; both lists with a single element -> compare them; only one list empty -> `False`.
[Answer]
# CJam, 19 bytes
```
q~]{_,,\f>:sS.+}/-!
```
[Try it online.](http://cjam.aditsu.net/#code=q~%5D%7B_%2C%2C%5Cf%3E%3AsS.%2B%7D%2F-!&input=%5B%5B1%200%209%5D%20%5B1%203%208%5D%5D%20%5B%5B1%5D%20%5B0%209%5D%20%5B1%203%5D%20%5B8%5D%5D)
### I/O
Input
```
[[1 0 9] [1 3 8]] [[1] [0 9] [1 3] [8]]
```
Output
```
1
```
### Idea
Each partition can be uniquely identified by observing the following two properties:
* The list formed by concatenating all sublists.
* The "cutting points", including the extremes of the list.
We can combine both criteria into one by replacing each cutting point with the sublist of elements from the cutting point to the end of the list.
To verify that a given partition is finer than another, we only have to verify if the coarser partition, represented as above, is a subset of the finer one and that the largest lists of both partitions match.
### Code
```
q~] e# Read from STDIN and evaluate.
{ e# For each array P from the input:
_,, e# Push [0 ... L], where L == length(P) - 1.
\f> e# Push [P[0:] ... P[L]].
:s e# Stringify each P[k:] (flattens).
S.+ e# Vectorized concatenation. This appends a space to the first element.
}/ e#
-! e# Push the logical NOT of the difference A-B to check if A is a subset of B.
```
For the input form the I/O example, the stack holds
```
["109138 " "138"] ["109138 " "09138" "138" "8"]
```
before executing `-!`.
Note that the first element of each array has a trailing space. This makes sure we compare the full list of the first input with the full list of the second.
[Answer]
# CJam, 24 bytes
```
l~L\{+_a2$1<={;1>L}&}/+!
```
**Algorithm**
Here we simply use a greedy algorithm to see if first `N` sub-lists of the second list can be merged together to form the first sub-list of the first list. Once such `N` is found, we remove the first `N` sub-lists from second list and the first sub-list from the first list and repeat the process.
Ideally, if the second list was a refinement of the first, we should be left with 2 empty lists on stack. We just check for that and print `1` if that is the case. In any other combination, after fully iterating over sub-lists of second list, we won't end up with 2 empty lists. Thus a `0` will be printed for such cases.
**Code expansion**
```
l~L\{+_a2$1<={;1>L}&}/+!
l~L\ e# Read the line, evaluate the two lists and put an empty list
e# between them
{ }/ e# Iterate over all sub-lists of the second list
+ e# Append the current sub-list to whatever is on stack. Originally
e# an empty array, but eventually the sum of first N sub-lists
_a e# Copy this and wrap it in an array
2$ e# Copy the first list on top of stack
1< e# Get only its first element wrapped in an array. This approach
e# is exception safe in case the array was already 0 length
={ }& e# If we have a match, remove both first sub-lists
; e# Remove the first N sub-lists array
1> e# Remove the first element from the first array
L e# Put an empty array on stack to repeat the process
+! e# If we are left with two empty arrays, sum them and do logical
e# not to get 1. If any of the arrays is non-empty, logical not
e# gives 0
```
[Try it online here](http://cjam.aditsu.net/#code=l%7EL%5C%7B%2B_a2%241%3C%3D%7B%3B1%3EL%7D%26%7D%2F%2B!&input=%5B%5B1%200%209%5D%20%5B1%203%208%5D%5D%20%5B%5B1%200%209%201%203%208%5D%5D) or [run the complete test suite here](http://cjam.aditsu.net/#code=17%7Bl%7EL%5C%7B%2B_a2%241%3C%3D%7B%3B1%3EL%7D%26%7D%2F%2B!N%7D*&input=%5B%5D%20%5B%5D%0A%5B%5B0%5D%5D%20%5B%5B0%5D%5D%0A%5B%5B1%200%209%201%203%208%5D%5D%20%5B%5B1%200%209%5D%20%5B1%203%208%5D%5D%0A%5B%5B1%200%209%201%203%208%5D%5D%20%5B%5B1%200%209%201%203%5D%20%5B8%5D%5D%0A%5B%5B1%200%209%201%203%208%5D%5D%20%5B%5B1%5D%20%5B0%5D%20%5B9%5D%20%5B1%5D%20%5B3%5D%20%5B8%5D%5D%0A%5B%5B1%200%209%5D%20%5B1%203%208%5D%5D%20%5B%5B1%200%209%5D%20%5B1%203%208%5D%5D%0A%5B%5B1%200%209%5D%20%5B1%203%208%5D%5D%20%5B%5B1%5D%20%5B0%209%5D%20%5B1%203%5D%20%5B8%5D%5D%0A%5B%5B9%208%208%205%208%202%207%5D%20%5B5%5D%20%5B1%204%5D%20%5B2%200%200%206%200%208%204%202%206%204%202%203%207%208%207%203%209%205%207%209%208%202%209%205%5D%20%5B3%209%208%5D%20%5B7%201%204%209%207%204%205%209%5D%20%5B3%203%203%5D%20%5B9%200%207%208%5D%20%5B3%209%204%207%202%207%208%200%203%200%5D%20%5B8%202%202%207%203%209%203%202%5D%20%5B2%209%200%208%205%204%201%208%205%205%206%202%200%209%202%207%207%209%202%207%5D%20%5B3%206%5D%20%5B1%202%207%207%204%204%202%209%5D%5D%20%5B%5B9%208%5D%20%5B8%5D%20%5B5%208%202%5D%20%5B7%5D%20%5B5%5D%20%5B1%204%5D%20%5B2%5D%20%5B0%200%206%5D%20%5B0%5D%20%5B8%204%202%5D%20%5B6%204%5D%20%5B2%5D%20%5B3%5D%20%5B7%208%5D%20%5B7%203%5D%20%5B9%5D%20%5B5%207%209%5D%20%5B8%202%5D%20%5B9%205%5D%20%5B3%5D%20%5B9%208%5D%20%5B7%201%204%5D%20%5B9%207%5D%20%5B4%205%209%5D%20%5B3%203%5D%20%5B3%5D%20%5B9%200%5D%20%5B7%208%5D%20%5B3%5D%20%5B9%5D%20%5B4%5D%20%5B7%202%5D%20%5B7%208%5D%20%5B0%5D%20%5B3%200%5D%20%5B8%202%5D%20%5B2%5D%20%5B7%203%5D%20%5B9%203%5D%20%5B2%5D%20%5B2%5D%20%5B9%5D%20%5B0%5D%20%5B8%205%204%5D%20%5B1%208%5D%20%5B5%205%5D%20%5B6%5D%20%5B2%200%5D%20%5B9%5D%20%5B2%5D%20%5B7%207%209%5D%20%5B2%207%5D%20%5B3%206%5D%20%5B1%202%5D%20%5B7%207%5D%20%5B4%204%202%5D%20%5B9%5D%5D%0A%5B%5B0%5D%5D%20%5B%5D%0A%5B%5B0%5D%5D%20%5B%5B1%5D%5D%0A%5B%5B1%200%209%5D%5D%20%5B%5B1%200%209%5D%20%5B1%203%208%5D%5D%0A%5B%5B1%200%209%5D%20%5B1%203%208%5D%5D%20%5B%5B1%200%209%201%203%208%5D%5D%0A%5B%5B1%200%209%5D%20%5B1%203%208%5D%5D%20%5B%5B1%200%209%5D%5D%0A%5B%5B1%200%209%5D%20%5B1%203%208%5D%5D%20%5B%5B1%200%5D%20%5B9%5D%5D%0A%5B%5B1%200%209%5D%20%5B1%203%208%5D%5D%20%5B%5B1%200%5D%20%5B9%201%5D%20%5B3%208%5D%5D%0A%5B%5B1%5D%20%5B0%209%5D%20%5B1%203%5D%20%5B8%5D%5D%20%5B%5B1%200%209%5D%20%5B1%203%208%5D%5D%0A%5B%5B9%208%208%205%208%202%207%5D%20%5B5%5D%20%5B1%204%5D%20%5B2%200%200%206%200%208%204%202%206%204%202%203%207%208%207%203%209%205%207%209%208%202%209%205%5D%20%5B3%209%208%5D%20%5B7%201%204%209%207%204%205%209%5D%20%5B3%203%203%5D%20%5B9%200%207%208%5D%20%5B3%209%204%207%202%207%208%200%203%200%5D%20%5B8%202%202%207%203%209%203%202%5D%20%5B2%209%200%208%205%204%201%208%205%205%206%202%200%209%202%207%207%209%202%207%5D%20%5B3%206%5D%20%5B1%202%207%207%204%204%202%209%5D%5D%20%5B%5B9%208%5D%20%5B8%5D%20%5B5%208%202%5D%20%5B7%5D%20%5B5%201%5D%20%5B4%5D%20%5B2%5D%20%5B0%200%206%5D%20%5B0%5D%20%5B8%204%202%5D%20%5B6%204%5D%20%5B2%5D%20%5B3%5D%20%5B7%208%5D%20%5B7%203%5D%20%5B9%5D%20%5B5%207%209%5D%20%5B8%202%5D%20%5B9%205%5D%20%5B3%5D%20%5B9%208%5D%20%5B7%201%204%5D%20%5B9%207%5D%20%5B4%205%209%5D%20%5B3%203%5D%20%5B3%5D%20%5B9%200%5D%20%5B7%208%5D%20%5B3%5D%20%5B9%5D%20%5B4%5D%20%5B7%202%5D%20%5B7%208%5D%20%5B0%5D%20%5B3%200%5D%20%5B8%202%5D%20%5B2%5D%20%5B7%203%5D%20%5B9%203%5D%20%5B2%5D%20%5B2%5D%20%5B9%5D%20%5B0%5D%20%5B8%205%204%5D%20%5B1%208%5D%20%5B5%205%5D%20%5B6%5D%20%5B2%200%5D%20%5B9%5D%20%5B2%5D%20%5B7%207%209%5D%20%5B2%207%5D%20%5B3%206%5D%20%5B1%202%5D%20%5B7%207%5D%20%5B4%204%202%5D%20%5B9%5D%5D)
[Answer]
# C, ~~120~~ 114 bytes
```
#define C(x),x+=(*x/93)*(1+!!x[1])|1
o;R(char*s,char*t){for(o=1;*s;o&=*s==t[2*(*t==93&&93>*s)]C(s)C(t));return o;}
```
I haven't golfed much recently, so I thought I'd try this one out.
We define a function `R(char* s, char* t)` which returns `1` if `t` is a refined partition of `s`, and `0` otherwise. `s` and `t` are expected to be in the format `[DDDD...][DDDD...]...` Where each `D` is another single-digit element.
Testing code:
```
#include "stdio.h"
int main(int argc, char** argv) {
char* str1, *str2;
str1 = "[109][138]";
str2 = "[1][09][13][8]";
printf("Input: %s, %s --> %d\n", str1, str2, R(str1, str2));
str1 = "[109][138]";
str2 = "[1][19][13][8]";
printf("Input: %s, %s --> %d\n", str1, str2, R(str1, str2));
str1 = "[109][138]";
str2 = "[10][91][3][8]";
printf("Input: %s, %s --> %d\n", str1, str2, R(str1, str2));
}
```
The above prints the following:
```
Input: [109][138], [1][09][13][8] --> 1
Input: [109][138], [1][19][13][8] --> 0
Input: [109][138], [10][91][3][8] --> 0
```
It seems to work, at least.
[Answer]
# Haskell, ~~52~~ ~~50~~ 53 bytes
```
x#y=and$zipWith(\a b->a==b||a==',')(x++"..")(y++"..")
```
Completely different from my [other solution](https://codegolf.stackexchange.com/a/51726/34531). Uses the same clever input format as [@edc65's answer](https://codegolf.stackexchange.com/a/51749/34531), i.e. elements are separated with `,` and lists with .
Usage example: `"1,0,9,1,3,8" # "1,0,9 1,3,8"` -> `True`.
The second parameter is a refinement of the first, if they have either equal elements at every position or the first one is `,`. I have to append a unique end token (->`..`) to both parameters, because `zipWith` truncates the longer parameter and for example `"1,2,3" # "1,2"` would also be `True`.
[Answer]
# Mathematica, 65 bytes
```
f@__=1<0;{}~f~{}=1>0;{a_,b___}~f~{c__,d___}/;a==Join@c:={b}~f~{d}
```
[Answer]
Maths with regular expressions is fun!
# ES6 Javascript, 53 chars
```
(a,b)=>RegExp('^'+a.replace(/,/g,'[ ,]')+'$').test(b)
```
# Vintage Javascript, 70 chars
```
function f(a,b){return RegExp('^'+a.replace(/,/g,'[ ,]')+'$').test(b)
```
Uses the same input format as [edc65's answer](https://codegolf.stackexchange.com/a/51749/15365).
[Full demo including all test cases here.](http://repl.it/sib)
[Answer]
# Mathematica, 55 bytes
```
Equal@@Join@@@#&&SubsetQ@@(Accumulate[Length/@#]&)/@##&
```
This defines an unnamed function, [taking the two partitions in a single list](https://codegolf.meta.stackexchange.com/a/5439/8478), in reverse order (i.e. `Y` first, `X` second).
## Explanation
```
Equal@@Join@@@#
```
This checks that both partitions are actually partitions of the same list.
```
SubsetQ@@(Accumulate[Length/@#]&)/@##
```
This is a golfed form of my approach in [this question over on Mathematica.SE](https://mathematica.stackexchange.com/a/77328/2305), which inspired this challenge. Basically, a partition is defined as a number of indices where splits are inserted, and this checks that all the splitting positions in `X` also appear in `Y` by accumulating the lengths of the sublists.
[Answer]
# Python 2, ~~68~~ 51 bytes
Thanks to xnor for some considerable byte-savings!
Anonymous function that takes two strings of the form `"1,0,9 1,3,8"` (taken from [edc65's C answer](https://codegolf.stackexchange.com/a/51749/16766)) and returns `True` or `False`. New version with `map(None)` no longer works in Python 3.
```
lambda a,b:all(i in[j,","]for i,j in map(None,a,b))
```
Test suite:
```
>>> def runTests(f):
assert f("1,0,9 1,3,8","1 0,9 1,3 8")
assert not f("1,0,9 1,3,8","1,0 9,1 3,8")
assert f("1 0,9 1,3 8","1 0,9 1,3 8")
assert not f("1 0,9 1,3 8","1,0,9 1,3,8")
assert not f("1 0,9 1,3 8","1 0,9 1,3")
assert not f("1 0,9 1,3,8","1 0,9 1,3")
print("All tests pass.")
>>> runTests(lambda a,b:all(i in[j,","]for i,j in map(None,a,b)))
All tests pass.
```
Previous 92-byte solution that takes input as `"109 138"`:
```
def R(a,b):
r=1
for i in b.split():r&=a.find(i)==0;a=a[len(i):].strip()
return r and""==a
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 5 bytes
```
O_/²Ƒ
```
[Try it online!](https://tio.run/##y0rNyan8/98/Xv/QpmMT/x9uf9S05v//aC7OaCVDXQNdSx1DXWNdCyUdBSVDHShXx0IpVgesAEkEpABJPVBBLAA "Jelly – Try It Online")
This implements [Dennis' string-based algorithm](https://codegolf.stackexchange.com/a/51774/66833), with a slight modification to the input format. Sublists are separated by `-` and from each other by `,` (e.g. `[[1], [0, 9], [1, 3], [8]] -> 1,0-9,1-3,8`). If this is too much of a stretch, Dennis' input format is [9 bytes](https://tio.run/##y0rNyan8/98/Xv/hjvkGOoamD3e2/T/c/qhpzf//0Vyc0UqG1gbWljqG1sbWFko6CkqGOlCujoVSrA5YAZIISAGSeqCCWAA)
A pure array based method comes out at ~~10~~ 6 bytes.
```
ŒbF€€i
```
[Try it online!](https://tio.run/##y0rNyan8///opCS3R01rgCjz/@HlSv//R3NxRsfqAIlog1gIbaijYKCjYBmrowBiGusoWKBK6CiAhEHScAkQxwBEQHSBCFQFOI0E60SSguuCO8uQJGdhCCPxIA5E4wO1gZ2LqRHVoljcIYXDZtKEcfoLTQLZfgOcXiXBQPIkcMZbLAA "Jelly – Try It Online")
This takes inputs reversed (i.e. `X` on the right and `Y` on the left), and outputs a non-zero integer for truthy and zero for falsey. It's 2 bytes longer (`ŒbF€€iɗ@`) to take input the normal way around. This does time out on TIO for the 2 longest inputs however.
## How they work
The 5 byter is simply an adaptation of of Dennis' CJam answer into Jelly:
```
O_/²Ƒ - Main link. Take the pair [X, Y] on the left
O - Convert everything to ordinals
_/ - Element-wise subtraction
- This results in:
- A list entirely containing 0s and 1s for truthy outputs
- A list consisting of at least one non-0 or 1 element for falsey outputs
²Ƒ - All elements are unchanged when squaring, i.e. all elements are 1 or 0
```
The 7 byter works as follows:
```
ŒbF€€i - Main link. Takes Y on the left and X on the right
Œb - Generate all partitions of Y, yielding [[]] if Y is empty
€ - Over each:
F€ - Flatten each sub-partition
- This has the effect of generating all possible concatenations of Y
i - Index of X in these concatenations, or 0 if not found
```
] |
[Question]
[
In this challenge you will take as input a non-empty list of binary values (these can be booleans or integers on the range 0-1), you should output all the ways to partition the list into non-empty sections such that no two adjacent equal values in the initial list are separated into different sections.
For example if the input is `[1,1,0,0,1]` then `[1,1],[0,0,1]` is a valid partition but `[1,1,0],[0,1]` is not since the adjacent `0`s are divided.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes.
## Test cases
```
[1,0] ->
[ [[1,0]]
, [[1],[0]]
]
[1,1,1,1] ->
[ [[1,1,1,1]]
]
[1,1,0,0,1] ->
[ [[1,1,0,0,1]]
, [[1,1],[0,0,1]]
, [[1,1,0,0],[1]]
, [[1,1],[0,0],[1]]
]
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes
```
{(&'+1,!2-1_=':x)_\:x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rWUFPXNtRRNNI1jLdVt6rQjI+xqqjl4uJKczBUMACTYAhlGQChIQBVpwuO)
`1_=':x` For pairs of adjacent values: are they equal?
`2-` 2 minus that. Gives 2s for the lines between sections and 1s in sections.
`!` odometer. Returns a matrix with all binary patterns bounded by the vector.
`+1,` prepend a 1 and transpose to have the binary patterns with leading 1s in the rows.
`&'` Get indices of 1s for each row.
`(...)_\:x` For each of those integer vectors, split the input at those indices.
[Answer]
# [Factor](https://factorcode.org) + `math.combinatorics math.unicode`, 81 bytes
```
[ dup 2 clump [ Σ 1 = ] arg-where 1 v+n all-subsets [ split-indices ] with map ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PU4xTsQwEOzvFdOjWAcVAiHRIRokhKiiFD5nL1mR2MZe34EQD0E0kRC8gHfQ329wznDaYnZ2dmfn_Wutjbgw7d7u765vrs7wQMHSgC645Nl2GLX0Klk2riVEekxkDUVFTxJ0LOqGZos_Yty4YqvzgE1E9AOLzD6HU_hAIs8-sBWcLxYvOMYSr3ss9d8vc2X2mWRdne5ua7TJ4wRmSKNHjZ-PrF6ggQ5dte0pUOabIws9DFVMq0gS89o-QsW25fl5gy1Ln6N6NMX4u4ZSKgs5uXeRIIEvizRNBX8B)
* `dup 2 clump [ Σ 1 = ] arg-where 1 v+n` get the indices of rising and falling edges
* `all-subsets` take all the subsets of that
* `[ split-indices ] with map` split the input according to each of these
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ITŒP‘œṖ€
```
A monadic Link that accepts a list of ones and zeros and yields a list of the valid partitions.
**[Try it online!](https://tio.run/##y0rNyan8/98z5OikgEcNM45Ofrhz2qOmNf8Ptx@d9HDnDCAz8v//aEMdQx0DIDREggaxAA "Jelly – Try It Online")**
### How?
```
ITŒP‘œṖ€ - Link: list, B e.g. [0, 0, 1, 1, 0, 1]
I - deltas (of B) [ 0, 1, 0,-1, 1]
T - truthy indices [ 2, 4, 5]
ŒP - powerset [[],[2],[4],[5],[2,4],[2,5],[4,5],[2,4,5]]
‘ - increment [[],[3],[5],[6],[3,5],[3,6],[5,6],[3,5,6]]
€ - for each:
œṖ - partition (B) at [[[0,0,1,1,0,1]],[[0,0],[1,1,0,1]],[[0,0,1,1],[0,1]],[[0,0,1,1,0],[1]],[[0,0],[1,1],[0,1]],[[0,0],[1,1,0],[1]],[[0,0,1,1],[0],[1]],[[0,0],[1,1],[0],[1]]]
```
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 40 bytes
```
f(a++b:c:d)|b/=c=(a++[b]):f(c:d)
f a=[a]
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NI1FbO8kq2SpFsyZJ3zbZFsSPTorVtErTAAlypSkk2kYnxv7PTczMU7BVSFOINtQx1DEAQsPY/wA "Curry (PAKCS) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
ĠøṖvvf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQQSIsIiIsIsSgw7jhuZZ2dmYiLCIiLCJbMSwwXVxuWzEsMSwxLDFdXG5bMSwxLDAsMCwxXSJd)
Port of @UnrelatedString's Brachylog answer.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 (or 4?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
γ.œ€€˜
```
[Try it online](https://tio.run/##yy9OTMpM/f//3Ga9o5MfNa0BotNz/v@PNtQx1DEAQsNYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c5v1jk5@1LQGiE7P@a/zPzraUMcgVgdIgiGUZQCEhrGxAA).
If we can use strings as I/O, this could be 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead by replacing `€€˜` with `J`:
[Try it online](https://tio.run/##yy9OTMpM/f//3Ga9o5O9/v83NDQwMAQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c5v1jk72@q/zP9rQQMcQCICEgYFhLAA).
**Explanation:**
```
γ # Split the (implicit) input-list into groups of equal adjacent values
.œ # Get all partitions of these groups
€ # For each partition:
€ # For each part of groups within a partition:
˜ # Flatten the part of groups to a single list
# (or alternatively:)
J # Join each list/part of groups within each partition together
# (after which the result is output implicitly)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
ḅ~ccᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/w93tNYlJ4NY/6OjDXUMYnWAJBhCWQZAaBgbCwA "Brachylog – Try It Online")
Takes a list through the input variable and [generates](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) a list of lists of lists through the output variable.
```
ḅ Partition into runs of consecutive equal elements.
~c Take an arbitrary partition of the list of runs,
cᵐ and concatenate each slice.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes
```
Ė!|ḅa₀cPl;?b₍↰;Pgᵗ↔c
```
A predicate that takes a list of 0's and 1's as input and outputs each possible partition [one after another](https://codegolf.meta.stackexchange.com/a/9134/16766).
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh7s6H3Ut/X9kmmLNwx2tiY@aGpIDcqztkx419QIVWAekP9w6/VHblOT//6MNdQx1DIDQMBYA "Brachylog – Try It Online")
### Explanation
This seems way too long.
```
Ė!|ḅa₀cPl;?b₍↰;Pgᵗ↔c
Ė! Either the input is an empty list (in which case return empty list)
| Or, take the input and...
ḅ Partition into blocks of equal elements
a₀ Get a prefix of that list of blocks
c Flatten it
P Call that list P
l Take its length
;?b₍ The original input with that many elements removed from the front
↰ Recurse (returns a list of lists)
;P Pair with P
gᵗ wrapped in a list
↔ Reverse the order of the pair
c Flatten once
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 65 bytes
```
Q+[E|F]:-append(A,[B,C|D],Q),B\=C,append(A,[B],E),[C|D]+F.
Q+[Q].
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P1A72rXGLdZKN7GgIDUvRcNRJ9pJx7nGJVYnUFPHKcbWWQdJIlbHVVMnGiSr7abHBdQaGKv330pXIS2/KDEnRyPaUMdQxwAIDWO1g3QUyosyS1Jz8jSCNDX1/gMA "Prolog (SWI) – Try It Online")
Similar to @alephalpha's Curry answer. Outputs as a list of choicepoints.
[Answer]
# [J](http://jsoftware.com/), 27 bytes
```
<;.1~1,.[:(#:[:i.*/)2-2=/\]
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/baz1DOsMdfSirTSUraKtMvW09DWNdI1s9WNi/2tycaUmZ@QrpCkYKhggmGAI5@oY6hgAoeF/AA "J – Try It Online")
*-1 bytes thanks to the "2 minus" trick stolen from ovs's answer*
Say we have, eg, `1,1,0,0,1` -- then we have 2 "change points" and 4 possible combos. This is *essentially* just the problem of listing:
```
0 0
0 1
1 0
1 1
```
except we want that that list to be embedded in the `X`s of this list:
```
0 X 0 X
```
The key insight is that this is 0..3 converted using the *mixed base* number `1 2 1 2`. After that we just cut the original input using our 4 lists, with a 1 prepended to each.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Ir0Œpk€
```
[Try it online!](https://tio.run/##y0rNyan8/9@zyODopILsR01r/h9uPzrp4c4ZQObDnYsi//@PNtQx1DEAQkMkaBALAA "Jelly – Try It Online")
Inspired by [Jonathan Allan's solution](https://codegolf.stackexchange.com/a/252314/85334).
```
I Get the forward differences of the list.
k Partition the list after each truthy position
€ of each element of
Œp the Cartesian product of
r0 the ranges from each difference to 0 inclusive.
```
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ŒgŒṖẎ€€
```
[Try it online!](https://tio.run/##y0rNyan8///opPSjkx7unPZwV9@jpjVA9P9wO0hgBpD5cOeiyP//DXUMdQyA0BAJGgAA "Jelly – Try It Online")
Port of my Brachylog solution.
```
Œg Partition into runs of consecutive equal elements.
ŒṖ Generate every partition of the runs,
Ẏ€€ and concatenate the runs in each slice.
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes
```
(.),(?!\1)
$1#
+%1`#
;$'¶$`,
```
[Try it online!](https://tio.run/##K0otycxL/H9oG9ehbYe2/dfQ09TRsFeMMdTkUjFU5tJWNUxQ5rJWUT@0TSVB5/9/Qx0DLkMdMATTBkBoCAA "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs semicolon-delimited lists. Explanation:
```
(.),(?!\1)
$1#
```
Find all acceptable cutting points.
```
+
```
Loop until each cutting point has been processed.
```
%
```
Loop over each partially cut list.
```
1`
```
Only process the first remaining cutting point on each pass.
```
#
;$'¶$`,
```
Create two lists, one cut at that point, one not cut at that point.
[Answer]
# [Perl 5](https://www.perl.org/), 80 bytes
```
sub{@p=pop=~/0+|1+/g;$s="@p";map$s=~s, ,$r=$_%2?$&:'';$_/=2;$r,ger,0..2**@p/2-1}
```
[Try it online!](https://tio.run/##VY9RT8IwFIWf3a84aQpjUFiZ4YWmshefTXhVQjTZyFS22s5Eg/DX5@02QPvQfPeec09vTWbfF83@GzzXjft8OaRGm8roUywnP/NJvFPcaZYapvbPhvDkBAS3mm8HyYoPl2Go@DbWieJW7DIr5GyWjMepiZPp/NioIK8sfHqduRqjAMAjEM5lSAR916KgG9TZiItOJ@z1Dv35q0tJ3U736CMo40xS4tojxCaIDn6YdhnxojQizb5MpNN2L9UrSHdVDY0hz1tTdBE4uV1t9WtVlD63Hb@qNPZfpUanGluUdQ42mC4cKHKJlgCa93wrfUF2KtxTyURw07@F7OMcjBVY9cawBLtfrx/Wrct/4mL21HlVcGx@AQ "Perl 5 – Try It Online")
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang) (v2), 125 bytes
```
;=lL=p+=a@P;W=l-lT|?Gp lT Gp-lT1=a+a,l;=n^2LaW+1=n-nT;=x!=b+=o@p;=kLa;W+=k-kT1&%/n^2k 2;=o+o,GbF=d+~x=x[Ga kT=bSbFd@;D+o,bO''
```
[Try it online!](https://knight-lang.netlify.app/v2#WyI7PWxMPXArPWFAUDtXPWwtbFR8P0dwIGxUIEdwLWxUMT1hK2EsbDs9bl4yTGFXKzE9bi1uVDs9eCE9Yis9b0BwOz1rTGE7Vys9ay1rVDEmJS9uXjJrIDI7PW8rbyxHYkY9ZCt+eD14W0dhIGtUPWJTYkZkQDtEK28sYk8nJyIsIjExMDAxIl0=)
Input as a binary string. Outputs each partition on a separate line.
This probably is not even the golfiest strategy lol, but whatever. The general strategy is to construct a list `a` that contains the possible indexes that can be cut at (the easy part), then enumerate over all possible combinations of cuts using `a` (the annoying as f\*\*\* part).
[Answer]
# [Haskell](https://www.haskell.org/), 94 bytes
```
import Data.List
f l=nub[w|w<-subsequences[id=<<x|x<-tails=<<(inits.group)l,x>[]],(w>>=id)==l]
```
[Try it online!](https://tio.run/##jYqxDoIwFEV3vuKFOEACBPeWyZHNselQpOiLpUD7Ghj490p0cjHmDDcn9zyUf2pjYsRxnhzBRZGqWvSUDGC4DZ1Y95WVPnReL0Hbm/YCe87Ytm@sJIXGH5KhRfLV3U1hzk2xNULKIlubhmOfc25kHBVa4NBPCcwOLcEJBnEuanl4oCu51kKafp9vfgf1wT/JZ2V8AQ "Haskell – Try It Online")
Corrected as x specifications.
Thanks to @Wheat Wizard for saving some bytes using *id=<<x* instead of concat.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes
```
⊞υ⟦A⟧FυF…ι¹F²F⁺¹⌕A⪫κω⁺Iλ¬λ⊞υ⁺⟦…κμ✂κμ⟧ΦιξEυ⭆¹ι
```
[Try it online!](https://tio.run/##RU7LCsIwELz3K3LcQATjtScpCApKoceQQ4jVBtekpImPr49Jrbh7GGZ3Z2b1oLx2ClNq4zRAZETs7RgDUEnr6uI8gUjJjM1bY98MbgTDCKfLdLNgi3ECzsjO2PMWEQ7OWLgx8qSMzLtGTQEws5MrWIr8MucD8Q/Iunu@7NDo/ktkccbQ@xL@ytq6ar2xAY5qLA5dyOxaSP7BlH1KQnDG2To3lzKtHvgB "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⟦A⟧
```
Start with the original list, which is always a valid partition.
```
Fυ
```
Loop over the partitions found so far.
```
F…ι¹
```
Loop over the lists in the current partition, but stop after the first. (This is a sneaky way of getting the first list into a variable.)
```
F²
```
Loop over the possible first bits of a cutting point.
```
F⁺¹⌕A⪫κω⁺Iλ¬λ
```
Loop over all of the possible cutting points that start with that bit. The cutting point is in between the bits, thus the extra `1` added to the positions. (`Incremented` works on empty lists in the newer version of Charcoal on ATO which would save a byte.)
```
⊞υ⁺⟦…κμ✂κμ⟧Φιξ
```
Cut the first list of the partition at that point and push the resulting partition to the list of partitions where it will be reevaluated for cutting.
```
Eυ⭆¹ι
```
Pretty-print all of the found partitions.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 10 bytes
```
mmrk9d./r8
```
[Try it online!](https://tio.run/##K6gsyfj/Pze3KNsyRU@/yOL/f3VDQwMDQ3UA "Pyth – Try It Online")
### Explanation
```
r8 length encode the implicitly evaluated input
./ get all partitions
mmrk9d map length decoding to each partition element
```
[Answer]
# [Python](https://www.python.org), 230 bytes
```
from itertools import*
import re
def f(M):L=re.split(r'((.)\2*)',''.join(map(str,M)))[1::3];l=len(L);I=[*range(1,l)];return[[M]]+[[[int(c)for c in''.join(L[i:j])]for i,j in pairwise([0,*P,l])]for s in I for P in combinations(I,s)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NZBBTsQwDEX3c4rsapdQTWGDWvUAlVpp9iGLUlJwlSaRkxHiLGxmA6fgIlyAc9BqqLzwl5_lb_vjK7ynV-8ul89zmm4ffn4n9ougZDh5b6OgJXhO-eGaBZvDs5nEBD1WXcOmiMFSAs4ACny8yzGTWVbMnhwsQ4CYWPaIqMqqute1baxx0GHdNirnwb0YKKVFXbNJZ3ZK9VrfKKXIJRhx8ixGQW4f2CmqZo16q5OcVyLCQPxG0YA6yvwk7T-NG2vFJk-bHP3yRG5I5F2EVkbU12u_Vb5tGXg1lBOoUpbyuEapcW_ZH_MH)
Python 3.10+ required for `pairwise`.
for `[1,1,0,0,1]` returns:
```
[[[1, 1, 0, 0, 1]],
[[1, 1], [0, 0, 1]],
[[1, 1, 0, 0], [1]],
[[1, 1], [0, 0], [1]]]
```
ungolfed:
```
from itertools import *
import re
def f(M):
# produce ['11', '00', '1'] by splitting on regex which checks 2 consecutive duplicates
L = re.split(r'((.)\2*)',''.join(map(str,M)))[1::3]
l = len(L)
indexes = [*range(1,l)]
return [[M]]+[
# wrap list for each consequtive pair of index combos and convert back from string
[[int(c) for c in ''.join(L[i:j])]
for i,j in pairwise([0,*partition_indexes,l])]
for partition_size in indexes
for partition_indexes in combinations(indexes,partition_size)
]
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes
```
ĉJᵐj
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FsuPdHo93Doha0lxUnIxVGzB7mhDHYNYLiAJhlCWARAaxkKUAAA)
A port of [@Unrelated String's Brachylog answer](https://codegolf.stackexchange.com/a/252326/9288).
```
ĉ Partition into runs of consecutive equal elements.
J Take an arbitrary partition of the list of runs,
ᵐj and concatenate each slice.
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 71 bytes
```
f=([x,...y],z='')=>x?f(y,z+x)|f(y,[z,x]):/^,|1,1|0,0/.test(z)||print(z)
```
[Try it online!](https://tio.run/##FcZBCoAgEADAex/RpU3dWxTWQ6IgIqEOESVisn83nNOca1jf7Tlu34Q2Z2flFFEp9c2YrBBghzg6@WGqI3DJlDDO0OkFmZDYoNHK76@XCZjv57jKcl85KYiMIQH5Bw "JavaScript (V8) – Try It Online")
Seems they look same
# [JavaScript (V8)](https://v8.dev/), 72 bytes
```
f=([x,...y],z='')=>x?f(y,z+x)|f(y,z+[,x]):/^,|1,1|0,0/.test(z)||print(z)
```
[Try it online!](https://tio.run/##JcZBCoAgEADAex/Rpc3cWxTWQ6JAIsEOESVhsn83ojnNZm97Lac/QnU3OTsjx4hKqWfCZIQA08fByQdTGYH/jBgnaOsZmZBYo65VWK8gEzAfp9@/5a5wUhBpTQLyCw "JavaScript (V8) – Try It Online")
] |
[Question]
[
Given a non-negative integer `n`, print the result of `P(P(...P({})))`, where the number of `P`'s is `n` (`P` is the power set function).
```
0 => {}
1 => P({})
2 => P(P({}))
3 => P(P(P({})))
n => P(f(n-1))
```
```
input result
0 {}
1 {{}}
2 {{},{{}}}
3 {{},{{}},{{{}}},{{},{{}}}}
...
```
The result should only contain parentheses/brackets/braces and commas, spaces and newlines are allowed.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 3 bytes
```
ŒP¡
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FkuPTgo4tHBJcVJy8fJDi45OerhzBkRiwUJjCAMA)
Using [standard I/O rules](https://codegolf.meta.stackexchange.com/q/2447); takes input from STDIN
Explanation:
```
¬° repeatedly apply
ŒP the power set
to nothing
which defaults to 0
which is turned into the range [1..0]
which is []
```
---
If you insist on the `{{},{{}}}` formatting:
## [Jelly](https://github.com/DennisMitchell/jellylanguage), 12 bytes
```
ŒP¡ŒṘ“[{]}”y
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FluPTgo4tPDopIc7ZzxqmBNdHVv7qGFu5ZLipORiqIoFC40hDAA)
This could probably be shorter, but I'm not too interested in golfing boring formatting code.
Explanation:
```
ŒP¡ŒṘ“[{]}”y
¬° repeatedly apply
ŒP the power set
ŒṘ convert to string representation
y translate
“[{]}” square brackets to curly braces
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 8 bytes
```
{}1qR@C~
```
[Try it online!](https://tio.run/##SyotykktLixN/V9W9r@61rAwyMG57n9whkN0dVGdQ2xtUV3gfwA "Burlesque – Try It Online")
```
{} # Empty block
1 # Continuation takes top 1 elements of stack
qR@ # Quoted powerset
C~ # Continuation forever, printing all powersets
```
If you insist on getting a particular N
# [Burlesque](https://github.com/FMNSSun/Burlesque), 11 bytes
```
{}1qR@C~j!!
```
[Try it online!](https://tio.run/##SyotykktLixN/V@U@b@61rAwyMG5LktR8X9whkN0dVGdQ2xtUV3gf2MA "Burlesque – Try It Online")
```
j!! # Reorder stack, get from block
```
And if you insist on comma-separated formatting add 8 bytes for
```
up' ',r~
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes
```
Nest[Subsets,{},#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98vtbgkOrg0qTi1pFinulZHOVbtv0t@dEBRZl5JdJ6Crp1CWnRebKyOQnWejoKBjoJJbex/AA "Wolfram Language (Mathematica) – Try It Online")
In the notebook interface, the results are printed without spaces. But in TIO or the text-based interface, spaces are automatically added.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
or 12
```
¾?(ṗ
```
## Explanation
```
¾?(ṗ
¾ Global array, empty at the start
? Get input n
( Start loop n times
·πó Powerset
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCvj8o4bmXIiwiIiwiMyJd)
## 12 bytes with the curly braces formatting:
(thanks to [@lyxal](https://codegolf.stackexchange.com/users/78850/lyxal))
```
¾?(ṗ)S¾S‛{}Ŀ
```
```
¾?(ṗ)S¾S‛{}Ŀ
¾?(ṗ) The boring stuff
S Stringify the power-setted list
¾ Empty list -> `[]`
‚Äõ{} Curly braces
ƒø Transliterate, replace `[]` with the curly braces
```
The `P` prints the list with its python representation.
[Try it online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwiwr4/KOG5lylTwr5T4oCbe33EvyIsIiIsIjMiXQ==)
[Answer]
# [Python](https://www.python.org), 96 bytes
```
from itertools import*
f=lambda n:n and(chain(*(combinations(f(n-1),r)for r in range(n+1))))or()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY5LCsJAEET3OUUve9QsgggSyF2cfMY0ZLqHTgfiWdxko3fyNkaJ-HYFr6i6P9PNeuFleUwW8vPrElQikHVqIsMIFJOo7bJQDT7WrQcuGTy32PSeGHfYSKyJvZHwiAE5L9xBXRAFBWJQz9cOeV-4FVF0287xY9DfOLkyg5UZKghI7huSEhvalIYOZ7dVf1ff)
[Answer]
# [Haskell](https://www.haskell.org/), 53 bytes
```
f=(!!)$iterate(\l->init l++[','|l/="{}"]++l++"}")"{}"
```
[Try it online!](https://tio.run/##FchBDoIwEAXQq3waEtpUi4nregJ3LpFFQ4bYODQIwwo4e5Hle58wf4k5597rojBlFJqCkH7z9RFTFLC1TXWpNq69WnfVWvsftStzKg8hJnjM9FsodYQSQxihx0VeMj0THHqD5ubcvc0H "Haskell – Try It Online")
My first golf. Nothing particularly clever, uses the Fokker trick to deal with the base case.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 3 or ~~17~~ 11 bytes
```
yFY
```
[Try it online!](https://tio.run/##K6gsyfj/v9It8v9/YwA "Pyth – Try It Online")
`F` - Repeat *Q* times, where *Q* is the implicit input:
`y` - powerset of
`Y` - empty list
### With formatting
```
X`yFYQ"[]}{
```
[Try it online!](https://tio.run/##K6gsyfj/PyKh0i0yUCk6trb6/39jAA "Pyth – Try It Online")
`X..."[]}{` - convert each occurrence of `[` to `{` and each occurrence of `]` to `}`
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 4 or 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Regular I/O using `[]` instead of `{}` and spaces after the commas would be 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage):
```
¯IFæ
```
[Try it online](https://tio.run/##yy9OTMpM/f//0HpPt8PL/v83BgA) or [verify the first few test cases](https://tio.run/##yy9OTMpM/W9ybJKfvZLCo7ZJCkr2/w@t93M7vOx/rc5/AA).
Strict I/O format is 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage):
```
¯IFæ}"ÿ"„[]„{}‡ðK
```
[Try it online](https://tio.run/##MzBNTDJM/f//0HpPt8PLapUO71d61DAvOhZIVNc@alh4eIP3///GAA) or [verify the first few test cases](https://tio.run/##MzBNTDJM/W9ybJKfvZLCo7ZJCkr2/w@t93M7vKxW6fB@pUcN86JjgUR17aOGhYc3eP/X@Q8A).
**Explanation:**
`"ÿ"` on lists only works in the legacy version of 05AB1E (built in Python), and unfortunately not in the new 05AB1E version (built in Elixir). I'm not sure how to do this challenge in the new version of 05AB1E, which lacks any form of `toString` builtin on lists..
```
¯ # Push an empty list: []
IF # Loop the input amount of times:
√¶ # Pop the current list, and push its powerset
# (after the loop, the result is output implicitly)
¯IFæ # Same as above
} # Close the loop
"ÿ" # Convert the (nested) list to a string
„[]„{}‡ # Transliterate all "[" to "{" and "]" to "}"
√∞K # Remove all spaces
# (after which the result is output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 71 bytes
```
f=lambda n,k=1:n and f(n-1,1<<k)or[f(0,i+1)for i in range(k)if~-k>>i&1]
```
[Try it online!](https://tio.run/##BcHBDkAwDADQX@lJ2phEw0nwI@IwoTSjk8XFxa/Pe/f7HNGanGU4/bWsHsyFgTsDbysIWsWO@z5QTJNg7bRkkphAQQ2St33DQCpfFcZRC57zndQeFGyJ8g8 "Python 3 – Try It Online")
Adapts [pxeger's Python answer](https://codegolf.stackexchange.com/a/248716/) to [Enumerate all pure sets](https://codegolf.stackexchange.com/q/248715/).
Computes the pure set corresponding to \$^n2-1\$ in the binary-encoding enumeration, which consists of the \$^{n-1}2\$ distinct sets with rank less than \$n\$.
[Answer]
# JavaScript (ES10), 95 bytes
Assuming a strict output format:
```
f=(n,a=[])=>n?f(n-1,a.reduce((a,x)=>a.flatMap(y=>[y,[...y,x]]),[[]])):(g=a=>`{${a.map(g)}}`)(a)
```
[Try it online!](https://tio.run/##ZcpBCoMwEEDRfc/RxQyMQ213hdgTeIIQcNBEWmwiaotBPHuabXHzF4//kq/M7fQcl8KHzqbkFHgSpQ2qyj8c@KIk4cl2n9YCCK3Zhd0gSy0jRFXpSJqZI63GIGmdi3folaiq2c6b8Dt/Pe57gyCY2uDnMFgeQg8OLoinfykPcj3IDTH9AA "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES10), 71 bytes
Returning an array of arrays:
```
f=(n,a=[])=>n?f(n-1,a.reduce((a,x)=>a.flatMap(y=>[y,[...y,x]]),[[]])):a
```
[Try it online!](https://tio.run/##ZcjBCsIwDADQu1@SQBac3oTOL/ALQg@ha0Up6dimrF9fd5Vd3uG99atLmF/T2lkZY2vJgZE68egGuyewriflOY6fEAGUtv2VU9b1oRNUN0glYeZKm/dIIrt40xaKLSVHzuUJCc6Ip//pD3M5zBWx/QA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics`, 72 bytes
```
[ { } [ all-subsets ] repeat unparse " "without "}{""},{"replace write ]
```
[Try it online!](https://tio.run/##HcyxCsIwEIfxvU/xJ7O6uOkDiIuLOEmHazjbwzQJlytFS589FtePH9@LvCWtj/v1djlhJBsOPo2dRNqy@IKeIysF@ZJJigVZ2eyTVaKhsBWUHMRMYg9JeLNGDjg3zbGpTyxY8QSFsC9T99ctlDOTYYqZtDAc3Cw2pMng1sW5dbe4jQTyjFnFGG3126H@AA "Factor – Try It Online")
As written.
---
# [Factor](https://factorcode.org/) + `math.combinatorics`, 30 bytes
```
[ { } [ all-subsets ] repeat ]
```
[Try it online!](https://tio.run/##DcgxDsIwDAXQPaf4F6ALGxwAsbAgpqqDGxmwSJ3IdgdAnD30je9OOar12/V8OR2wUDyHXJdZlLaW7HiwslGRD4VUdTTjiHcz0cCLTbngmNI@9RFf/DCCStn5OjuHY4JxYwpMPW@Pof8B "Factor – Try It Online")
With standard I/O rules.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 206 bytes
```
#define P putchar
f(i,s,c){P(123);for(s=0;i;++s,i>>=1)if(i&1){f(s);if(i>1)P(44);}P(125);}s,i;main(c,v)char**v;{sscanf(v[1],"%d",&c);for(s=!!c--;c>0;--c)s=1<<s;P(123);for(;i<s;){f(i++);if(s>i)P(44);}P(125);}
```
[Try it online!](https://tio.run/##XY7NCsIwEITvPoVWlGyTgPHntG2eoXfxUFaje7BKV3spPntMBEE8DQMz8w3ZM1GM8@MpcHeaNtP780GXtp8ExUYMwdgot94AhluvpF4ho9Zi2PvaAafQ0sEYlABm4x00arsFfOXWLmmK4rXlTpEZIA@X5YCjCLVdUMPeHUyxOBZmSV/CbEbWIvkVWksgtasqwZ8PyMlnJGv9gYrnf2iMcfMG "C (gcc) – Try It Online")
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 5 bytes
```
√ò·∂¶{Sa
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FisOz3i4bVl1cOKS4qTkYqggTBIA)
```
√ò·∂¶{Sa
√ò Empty list
·∂¶{ Iterate
Sa All subsets
```
Since Nekomata is a non-deterministic language, the built-in `S` (`\subset`) returns any subset non-deterministically instead of all subsets in a list. This is helpful for many other challenges, but not this one. We have to add an `a` (`\allValues`) to get the power set.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
*Ties [pxeger's Jelly answer](https://codegolf.stackexchange.com/a/248448) and [math junkie's Pyth answer](https://codegolf.stackexchange.com/a/248457) for #1.*
```
ćFæ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//SLvb4WX//0cbxwIA "05AB1E – Try It Online") Takes input as a singleton list, and outputs with square brackets.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
F⊕N≔EX²Lυ⪫{}⪫Φυ﹪÷κX²ν²,υ⊟υ
```
[Try it online!](https://tio.run/##PY1BCsIwEEX3niJkNQNxU5ddCSIorfQKMY1tMJ2ENKkL8ewxAXEz8/j8eaNmGZSTNueHCwwupIJeNEU9FvYp3tJy1wEQkR3X1UwEvfQwuFcJG8E6TVOcISEKdnWGgL8//IdnY2NpJcF6NybrijCezGZGDU/B/gqqt00dXHCsO2G7G4KhWP746m5zPuT9Zr8 "Charcoal – Try It Online") Link is to verbose version of code. Extremely inefficient; do not try `n=4` unless you have a lot of patience (will time out on TIO). Explanation:
```
F⊕N
```
Repeat `n+1` times...
```
≔EX²Lυ⪫{}⪫Φυ﹪÷κX²ν²,υ
```
... replace the predefined empty list with its formatted powerset.
```
⊟υ
```
Output the last element.
21 bytes using Python list formatting:
```
FN≔EX²LυΦυ﹪÷κX²ν²υ⭆¹υ
```
[Try it online!](https://tio.run/##PYzBCsIwEETvfsUedyEerMeeBBEEKwW/IG1jGoxJSXfr56fJxcsMPObNOOs0Ru1zfscEeA@L8FO@g0lIBJd1dTZgpxfs46@wRsHDBMszCpGCm/NcqCjo4iQ@Fp@vbnOTwY@CvxLqtqGaQu2hTy4wvriUrdeniqnN@ZyPm98B "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FN
```
Repeat `n` times...
```
≔EX²LυΦυ﹪÷κX²ν²υ
```
... replace the predefined empty list with its powerset.
```
⭆¹υ
```
Pretty-print the list.
[Answer]
# [R](https://www.r-project.org), 205 bytes
```
\(n,z=paste0,b=\(x)z('{',x,'}'),p=\(x,e=el(strsplit(x,',')),l=lapply(e,\(i)c(i,NA)),g=do.call(expand.grid,l),d=\(v)z(na.omit(v),collapse=','),a=apply(g,1,d))d(b(a))){s='';for(i in seq_len(n)){s=p(s)};b(s)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY9BasMwEEWv4kVBMzA1CXRRGmbRC_QEhiJbshFMZUVSgxOTk3TjFnqcHqC3qZy03cwwfz6P_9_e4_LR8-dr7m_vv78a8HTioFO2G2q5gQlPoGZFE6mzQgqrRJatQMoxBXG53IoUIgmLDkGOYKkBhx04enos-sBmrDstAnYK2pt6iM6QIJkCOxS-1_X4UkAHpG6UAkmWVyRpvgIH2pJBNNCCRsQ5sVK7fozgKuerZPfPYj34yydAwvOuXedvqZt_5-bhDucQnc9wqVgSVn2Jin_eZbnuHw)
A naive implementation of powerset for comma-delimited strings in R, using `seq_len` instead of `1:n` to handle the n = 0 case correctly.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 34 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⎕json{⌿∘⍵¨↓⌽⍉2⊥⍣¯1⊢¯1+⍳2*≢⍵}⍣⍵⊢⍬}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37UNzWrOD@v@lHP/kcdMx71bj204lHb5Ec9ex/1dho96lr6qHfxofWGj7oWAUntR72bjbQedS4CKqsFSgApoMSj3jW1AA&f=e9Q39VHbhDQFYwA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Marked as community wiki because the power set function has been taken from APLCart.
[Answer]
# BQN, 17 bytes
```
{(‚•ä(‚Üï2Àò)/¬®<)‚çüùï©‚ü®‚ü©}
```
[Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyjipYoo4oaVMsuYKS/CqDwp4o2f8J2VqeKfqOKfqX0KRiAz)
Powerset composed x times on empty set.
---
# BQN, 42 bytes
```
{{'‚ü®':'{';'‚ü©':'}';ùï©}¬®‚Ä¢Repr(‚•ä(‚Üï2Àò)/¬®<)‚çüùï©‚ü®‚ü©}
```
[Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge3sn4p+oJzoneyc7J+KfqSc6J30nO/Cdlal9wqjigKJSZXByKOKliijihpUyy5gpL8KoPCnijZ/wnZWp4p+o4p+pfQpGIDM=)
Strictly formatted variant.
If `‚ü®‚ü©` count as valid brackets, then simply remove `{'‚ü®':'{';'‚ü©':'}';ùï©}¬®` for a 22-byte solution.
] |
[Question]
[
**This question already has answers here**:
[Code Golf Christmas Edition: How to print out a Christmas tree of height N](/questions/4244/code-golf-christmas-edition-how-to-print-out-a-christmas-tree-of-height-n)
(116 answers)
Closed 4 years ago.
Given an integer `n>0`, write a program that will output an "isosceles" Triangle out of #'s of height `n`.
Examples:
`n=3`
```
#
###
#####
```
`n=1`
```
#
```
`n=5`
```
#
###
#####
#######
#########
```
This would be invalid:
```
#
###
#####
#######
#########
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes
```
G↗↘N#
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT9Pwyq0ICgzPaNER8HKJb88D8r2zCsoLfErzU1KLdLQ1FFQUlbStP7/3/S/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The `G` draws a filled polygon, where the `↗↘` specifies the sides to follow (the polygon is automatically closed) and the `N` inputs the size and the `#` specifies the fill character. Using `G↖↙N#` also works of course.
Alternate solution, also 5 bytes:
```
G^N#⟲
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT9PwypOR8Ezr6C0xK80Nym1SENTR0FJWUnTmisovySxJFVD0/r/f9P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The `^` is a shortcut for two diagonal directions `↘↙` (sadly there is no shortcut for the above diagonals in the required order as `<` is `↘↗` and `>` is `↙↖`) so the triangle has to be rotated into position using `⟲`.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 36 bytes
```
"$args"..1|%{" "*--$_+"#"*++$i;$i++}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0klsSi9WElPz7BGtVpJQUlLV1clXltJWUlLW1sl01olU1u79v///yYA "PowerShell – Try It Online")
Loops from input `$args` down to `1`, each iteration constructing a string consisting of the appropriate number of spaces plus a number of `#` marks that starts at `1` and increments by 2 every iteration. Those strings are left on the pipeline, and implicit output gives us newlines for free.
[Answer]
# [Python 2](https://docs.python.org/2/), 46 bytes
```
def f(n,i=1):1/n;print" "*~-n+"#"*i;f(n-1,i+2)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI08n09ZQ08pQP8@6oCgzr0RJQUmrTjdPW0lZSSvTGiiva6iTqW2k@T9NIzOvoLREQ1PzvykA "Python 2 – Try It Online")
Basically the same solution as [Jonathan Allan](https://codegolf.stackexchange.com/a/199092/20260), but a function that prints and terminates with error, if that's allowed here. The `1/n` is used to halt execution where `n=0`. Maybe there's a way to do that shorter by stuffing in a `/n` or `%n` somewhere.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Multiple 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) programs are possible:
* `·ÅÉ'#×.c`: [Try it online](https://tio.run/##yy9OTMpM/f//0PbDrYc71ZUPT9dL/v/fFAA) or [verify all test cases](https://tio.run/##yy9OTMpM/R9yuPVwZ5mSZ15BaYmVgpJ9pQ6Xkn9pCYSnU/n/0HaQAnXlw9P1kv/rHNpm/x8A).
* `L'#×€û.c`: [Try it online](https://tio.run/##yy9OTMpM/f/fR1358PRHTWsO79ZL/v/fFAA) or [verify all test cases](https://tio.run/##yy9OTMpM/R9yuPVwZ5mSZ15BaYmVgpJ9pQ6Xkn9pCYSnU/nfR1358PRHTWsO79ZL/q9zaJv9fwA).
* `L·<'#×.c`: [Try it online](https://tio.run/##yy9OTMpM/f/f59B2G3Xlw9P1kv//NwUA) or [verify all test cases](https://tio.run/##yy9OTMpM/R9yuPVwZ5mSZ15BaYmVgpJ9pQ6Xkn9pCYSnU/nf59B2G3Xlw9P1kv/rHNpm/x8A).
* `'#×ηj€û»`: [Try it online](https://tio.run/##yy9OTMpM/f9fXfnw9HPbsx41rTm8@9Du//9NAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/R9yuPVwZ5mSZ15BaYmVgpJ9pQ6Xkn9pCYSnU@nyX1358PRz27MeNa05vPvQ7v86h7bZ/wcA).
**Explanations:**
```
· # Double the (implicit) input-integer
# i.e. 3 → 6
ÅÉ # Pop and push a list of all positive odd values below this doubled value
# → [1,3,5]
'#× '# Repeat "#" that many times as string
# → ["#","###","#####"]
.c # Centralize this list (which implicitly joins by newlines)
# → " #\n ###\n#####"
L # Push a list in the range [1, (implicit) input-integer]
# i.e. 3 → [1,2,3]
'#× '# Repeat "#" that many times as list
# → ["#","##","###"]
€û # Palindromize each
# → ["#","###","#####"]
.c # Centralize this list (which implicitly joins by newlines)
# → " #\n ###\n#####"
L # Push a list in the range [1, (implicit) input-integer]
# i.e. 3 → [1,2,3]
· # Double each value
# → [2,4,6]
< # Decrease each by 1
# → [1,3,5]
'#×.c '# Same as the first answer above
'#× '# Repeat "#" the (implicit) input-integer amount of times as string
# i.e. 3 → "###"
η # Take the prefixes of that string
# → ["#","##","###"]
j # Pad spaces to each to make the total length equal to the (implicit) input
# i.e. 3 → [" #"," ##","###"]
€û # Palindromize each
# → [" # "," ### ","#####"]
» # Join by newlines
# → " # \n ### \n#####"
```
For each of these programs the resulting string is then output implicitly (with trailing newline).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~104~~ \$\cdots\$ ~~72~~ 71 bytes
Saved ~~5~~ 11 bytes thanks to [S.S.Anne](https://codegolf.stackexchange.com/users/89298/s-s-anne)!!!
Saved 6 bytes thanks to [gastropner](https://codegolf.stackexchange.com/users/75886/gastropner)!!!
Saved a byte thanks to [Stephen](https://codegolf.stackexchange.com/users/65836/stephen)!!!
```
i;j;f(n){for(i=0;i++<n;)for(j=0;j<i*2;)printf(j++?"#":"\n%*s",n-i,"");}
```
[Try it online!](https://tio.run/##JclBCoMwEEDRvacII4UZo2Bb3HSUXsSNBCMT6LREuxLPnhq6eny@axbnUhIO7FFp9@@IMrQs1vbKlDOcGXqpbkyfKLp5DNY@oYQHjHqpVqi1kRqA@EjnNq9JFMnshfF4Jc7c/3SZOG/fqKbl4kg/ "C (gcc) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~46~~ 43 bytes
```
f=->g{g.times{|n|puts" "*(g-n)+?#*(2*n+1)}}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y69Ol2vJDM3tbi6Jq@moLSkWElBSUsjXTdPU9teWUvDSCtP21CztvZ/ml5yYk6OhqnmfwA "Ruby – Try It Online")
* -3 thanks to IMP1
[Answer]
# [J](http://jsoftware.com/), ~~19~~ 18 bytes
```
' #'(#~|.,.1++:)i.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RWU1TWU62r0dPQMtbWtNDP1/mtycaUmZ@QrpCkYQxjq6jAB0/8A "J – Try It Online")
*-1 byte thanks to FrownyFrog*
Let's do 3:
* `i.` Produces:
```
0 1 2
```
* `|.,.1++:` - Reverse `|.` produces `2 1 0` and `1 +` the double `+:` produces `1 3 5`. Then we zip `,.` those together:
```
2 1
1 3
0 5
```
* `' #'#~` copies each character in the 2-character string `#` (space and pound) according to the mask specified above, and pads the end of the first two rows with spaces, so every row is 5 characters:
```
#
###
#####
```
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 18 bytes
```
|
&@ (n-$)~@#(2$-1
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/v4ZLzUFBI09XRbPOQVnDSEXX8P9/UwA "cQuents – Try It Online")
## Explanation
```
|
terms in sequence are separated by newline
& output first n terms in sequence
each term is:
@ " " *
(n-$) n - index
~ concat
@# "#" *
(2$-1 2 * index - 1
```
[Answer]
# APL+WIN, 23 bytes
Prompts for integer:
```
(-⌽⍳n)⌽⊃(1+2×⍳n←⎕)⍴¨'#'
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv4buo569j3o352mC6K5mDUNto8PTQQJANUC1mo96txxaoa6s/h@o/H8alzFXGpcpAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
:&<~P2&ZvZc
```
[**Try it online!**](https://tio.run/##y00syfn/30rNpi7ASC2qLCr5/39TAA "MATL – Try It Online")
### How it works
Consider input `3` as an example.
```
: % Implicit input. Range
% STACK: [1 2 3]
&< % Pairwise less-than comparison
% STACK: [0 0 0;
1 0 0
1 1 0]
~ % Negate, elementwise
% STACK: [1 1 1;
0 1 1;
0 0 1]
P % Flip vertically
% STACK: [0 0 1;
0 1 1;
1 1 1]
2&Zv % Reflect horizontally, without repeating last column
% STACK: [0 0 1 0 0;
0 1 1 1 0;
1 1 1 1 1]
Zc % Replace nonzeros by '#' and zeros by ' '
% STACK: [' # '
' ### ';
'#####']
% Implicit display
```
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
n=input();v=1
while n:n-=1;print' '*n+'#'*v;v+=2
```
**[Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERD07rM1pCrPCMzJ1UhzypP19bQuqAoM69EXUFdK09bXVldq8y6TNsWqMMYAA "Python 2 – Try It Online")**
---
A fun **49** with an extra space of padding is:
```
s=' '*input()+'#'
while'#'>s:print s;s=s[1:]+'##'
```
[Try that](https://tio.run/##K6gsycjPM/r/v9hWXUFdKzOvoLREQ1NbXVmdqzwjMycVyLArtiooyswrUSi2LrYtjja0igVKK6v//28MAA "Python 2 – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), ~~78~~ 76 bytes
```
func[n][s: copy"#"repeat i n[print pad/left s n + i - 1 append s"##"take s]]
```
[Try it online!](https://tio.run/##LcsxCoAwDAXQ3VN82lFEHFw8hmvIUGwKosTQ1sHTVwfnx8sS2yqRuEsLWrp1I2UqC7bLHuddFpNQsUPJ8q4VFuJ4SqooUPQfDJgQzEQjivPe1XAICnP7q2KmBOX2Ag "Red – Try It Online")
## Alternative using [Red](http://www.red-lang.org)'s `parse`:
# [Red](http://www.red-lang.org), 77 bytes
```
func[n][s: to""pad/left"#"n loop n[parse s[(print s take s)to"#"insert"##"]]]
```
[Try it online!](https://tio.run/##DcqxCgIxDIDhvU8R0kUnORGRewzXkKHYBA6PtDT1@WuGb/jhH1LXWypx0h2W/uxDxuQ7zIbYS72dohMzGpytdTDqZbiA06WPwyY4zPKNvsaf8TCXEXtGZl4KW1K4h0d4he2Z1h8 "Red – Try It Online")
[Answer]
# [Rule 222](https://www.wolframalpha.com/input/?i=rule+222), 1 byte (noncompeting)
```
#
```
[Wolfram codes](https://en.wikipedia.org/wiki/Wolfram_code) describe a family of celular automata. While most behave in very simple ways, some of them show very complex behaviour. [Rule 110](https://en.wikipedia.org/wiki/Rule_110) is even Turing complete.
Rule 222 is one of the "simple" ones. After n generations, it produces a triangle of n levels, as specified in the challenge. A synonymous cellular automata in this case is Rule 254.
[Answer]
# k4 23 bytes
-6 thanks to streetster!
```
{(-x+!x)$(1+2*!x)#'"#"}
```
29 bytes previous solution+explanation:
```
{(-x+!x)$|:'x#x("##",)\"# "}
{ } /lambda with implicit arg `x`
x("##",)\"# " /function composition - cumulatively join (,) "##" to "# " x times and return intermediate results ("# ";"### ";"##### ") etc
x# /take x items
|:' /reverse each
(-x+!x) /enumerate x and subtract x from each (x=3 -> -3+0 1 2)
$ /pad, left-pads when left arg is negative
```
[Answer]
# [Python 3](https://docs.python.org/3/), 58 bytes
```
def f(n,i=1):print((n-i)*' '+(2*i-1)*'#');n>i and f(n,i+1)
```
[Try it online!](https://tio.run/##JcoxDoAgDADArzRxoEUYKnHB6F9MkNilEMLi69HE7YarT7@LhjHSlSGjOtmZYm2iHVG9kDVgZlyseP48Gdr0EDg1/XtmGrk0EBAFdsGtMaPQeAE "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
>þ`UŒBị⁾ #Y
```
[Try it online!](https://tio.run/##y0rNyan8/9/u8L6E0KOTnB7u7n7UuE9BOfL////GAA "Jelly – Try It Online")
A full program that takes an integer argument and prints a triangle. If a monadic link returning a list of Jelly strings is acceptable, the final byte can be saved for 10 bytes.
## Explanation
```
>þ` | Outer table using greater than and 1..n as both left and right argument
U | Reverse order of inner lists
ŒB | Bounce inner lists (i.e. repeat each one in reversed order without duplicating the final character)
ị⁾ # | Index into [" ", "#"]
Y | Join with newlines
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 30 bytes
```
2|*J' j|*iSj'#j|*iT2enq\[Z[unQ
```
[Try it online!](https://tio.run/##SyotykktLixN/f/fqEbLS10hq0YrMzhLXRlEhxil5hXGREdFl@YF/v9vCgA "Burlesque – Try It Online")
Not left aligned, but functionally an isosceles triangle. Takes input as `N`.
```
2|* # N*2
J # Duplicate this number
' j|* # 2N spaces
iS # [2N..1] spaces as list
j # Swap back
'#j|* # 2N hashes
iT # [1..2N] hashes as list
2en # Take each odd
q\[Z[ # Zip together, and concatenate
un # Add new lines between each element
Q # Pretty print
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~75~~ 70 bytes
```
i,m;f(n){m=n*2;for(i=m*n;i--;)putchar(i%m?abs(i%m-n)<n-i/m?35:32:10);}
```
[Try it online!](https://tio.run/##bYtBCoMwEADP5hVFKOyKS1uDF7fiW9JA2j3stlR7Et8ezb2nYQYm0jPGnKVVTmC46mhNx@n9BRm1MRYixs9via9wpLNO4TEXkuHdSC46@X7w3XC7Im9ZbDlpEAN0q6sSeGRXHfcMNRHVxRL0/2L53ZZ3 "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 54 bytes
```
n,i=input(),1
exec"print(n-i)*' '+(2*i-1)*'#';i+=1;"*n
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P08n0zYzr6C0RENTx5ArtSI1WamgKDOvRCNPN1NTS11BXVvDSCtT1xDIVla3ztS2NbRW0sr7/98UAA "Python 2 – Try It Online")
Based on [Jitse's Python 3 solution](https://codegolf.stackexchange.com/a/199072/65836).
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
õî'# mê û
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9e4nIyBt6iD7&input=NQ)
Or 7 bytes if we can choose which character to use.
```
õ_î¬êÃû
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9V/urOrD%2bw&input=NQ)
[Answer]
# [Haskell](https://www.haskell.org/), 57 bytes
```
r=replicate
f x=unlines[r(x-n)' '++r(2*n-1)'#'|n<-[1..x]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v8i2KLUgJzM5sSSVK02hwrY0LyczL7U4ukijQjdPU11BXVu7SMNIK0/XUFNdWb0mz0Y32lBPryI29n9uYmaegq1CQWlJcEmRT56CikKagul/AA "Haskell – Try It Online")
The `unlines` function is often helpful for ASCII art problems.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÇÑÄ ç'#
û
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=x9HEIOcnIwr7&input=Mw)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~18~~ 17 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
╒_'#*mñ\x *^my ═n
```
[Try it online.](https://tio.run/##y00syUjPz0n7///R1Enx6spauYc3xlQoaMXlVio8mjoh7/9/Qy5jLlMuQ0MA)
**Explanation:**
```
╒ # Push a list in the range [1, (implicit) input-integer]
# 3 → [1,2,3]
_ # Duplicate this list on the stack
'#* '# Repeat "#" the values amount of time as string
# → ["#","##","###"]
mñ # Palindromize each
# → ["#","###","#####"]
\ # Swap to get the duplicated [1, input] list at the top again
x # Reverse this to [input, 1]
# → [3,2,1]
* # Repeat a space the values amount of time as string
# → [" "," "," "]
^ # Zip the two lists together
# → [["#"," "],["###"," "],["#####"," "]]
my # Join each inner pair together
# → ["# ","### ","##### "]
═ # Pad leading spaces to each string to make them all of equal length
# → [" # "," ### ","##### "]
n # And join this list by newlines
# → " # \n ### \n##### "
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas/wiki), 6 [bytes](https://github.com/dzaima/Canvas/blob/master/main.js)
```
{#×]±│
```
[Try it online.](https://dzaima.github.io/Canvas/?u=JXVGRjVCJTIzJUQ3JXVGRjNEJUIxJXUyNTAy,i=NQ__,v=2)
**Explanation:**
```
{ # Map over the range [1, input]:
#× # Repeat "#" the value amount of times
]± # After the map: interpret the array as a 2D string, and reverse it
│ # And palindromize it horizontally with 1 overlap
# (after which it is output implicitly as result)
```
[Answer]
# [Icon](https://github.com/gtownsend/icon), 73 bytes
```
procedure f(n,i)
/i&i:=1
write(right(repl("#",i),n+i))
n>1&f(n-1,i+2)
end
```
[Try it online!](https://tio.run/##y0zOz/v/v6AoPzk1pbQoVSFNI08nU5NLP1Mt08rWkKu8KLMkVaMoMz2jRKMotSBHQ0lZCSivk6edqanJlWdnqAbUoGuok6ltpMmVmpeCZFJuYmaehiaXAhCkaZhCZAE "Icon – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax/blob/master/docs/instructions.md), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é─C:UÅ≤┘.
```
My first Stax answer. :)
[Try it online](https://staxlang.xyz/#p=82c4433a558ff3d92e&i=5&a=1) or [try it online unpacked (**10 bytes**)](https://staxlang.xyz/#c=%27%23*%7C%5B%7C%3Em%7Cp&i=5&a=1).
**Explanation (of the unpacked version):**
```
'#* '# Repeat "#" the (implicit) input-integer amount of times as string
# i.e. 3 → "###"
|[ # Get the prefixes of this string
# → ["#","##","###]
|> # Padding leading spaces up to a length equal to the longest string
# → [" #"," ##","###"]
m # Map over each line:
|p # Palindromize the line
# → [" # "," ### ","#####"]
m # And the map also prints each line with trailing newline afterwards
# → " # \n"
# " ### \n"
# "#####\n"
```
[Answer]
# [PHP](https://php.net/), ~~65~~ ~~64~~ 62 bytes
```
for($j=$argn+$i=1;--$j;$i+=2)printf("%{$j}s%'#{$i}s\n",'','');
```
[Try it online!](https://tio.run/##DcQxDoAgDADAv2AJEGTAFYmbr3BxQcsADbAZvi6aXI5uGutG/yEXCdHDWa6kAb11xkB0gNovigqmFiTjD8ReuZgewF6PxGYhfsqNYe2bqWFOdZj9Aw "PHP – Try It Online")
Muuuuch better version with string formatting. I knew there was something, PHP is a templating language after all.. It couldn't be that bad for this kind of job!!
EDIT: saved 1 byte and removed the extra leading space by moving `$i++` to the `printf`
EDIT2: saved 2 bytes with new strategy by @GuillermoPhillips (thanks!)
**ORIGINAL NAIVE ANSWER:**
# [PHP](https://php.net/), 104 bytes
```
for($t='#';$i++<$argn;$s.=' ',$t="#$t#"){$r[$i*2]="$t\n";$r[($argn-$i)*2+1]=$s;}ksort($r);echo join($r);
```
[Try it online!](https://tio.run/##HYpBCsMgFAWvEvSBGpuC2RrJrpdIsyilbWzBL@qu9Oo1ks3AMBO3WKc5Nj4pSRQnuLDwWk@4pVewyGcnOnFqhXEUztQXaYHvx9UxlGtgtrk85gFe9aM2q0O2v0@mVCSSso/7Rt2bfDisVmP@FIunkOtw2QE "PHP – Try It Online")
[Answer]
# Java 8, ~~151~~ 128 bytes
`p->{for(int c=1;p>0;c+=2)System.out.println(new String(new char[p--]).replace('\0',' ')+new String(new char[c]).replace('\0','#'));}`
[TIO](https://tio.run/##bZDBbgIhEIbvPsWf9ABku8Q26QnXN6gXj@qBIlZ0ZQmLNo3ZZ18HtKfKYWDmnzD/Nwd90fVhexxNq/sen9r56wRwPtm408ZikVPg0rktEqc6glBUGiYUFvBoMIZ6ft11saimeVNhPlWmat7F8rdP9iS7c5Ihktp67u0PlomS7/I0ex1Xoa43QkYbWprI2XrKXhmYqJ71mn@dL0wINYwqGwrnr9YZ9EknuorpEyHx@y@rDbS48/zZdWQXbvZBoaoeGpCn5VVwIb0k6kKczxOghzaUnQzjDQ)
See also [JDK 13 answer](https://codegolf.stackexchange.com/a/199117/62289)
[Answer]
# [Haskell](https://www.haskell.org/), 52 bytes
```
f x=do n<-[1..x];'\n':([n..x]>>" ")++([2..2*n]>>"#")
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwjYlXyHPRjfaUE@vItZaPSZP3UojOg/EsbNTUlDS1NbWiDbS0zPSygMJKCtp/s9NzMxTsFUoKC0JLilSUFFIUzD9DwA "Haskell – Try It Online")
[Answer]
# Haskell, ~~91~~ ~~[72](https://tio.run/##DclBCoMwEAXQvaf4RCGGSaUWupwbdOe2UEKJGpoOMo3nT7N78Pbw@8Sca1XWeOT0DiV26/jyV8fGNCUvjhUCC0ukSLB9g3mKIWpNNy@X2XUbr9Po3Vy/IQkYx1mWog/BgA33@gc)~~ 62 bytes
```
(1!)
_!0=""
i!n=r n ' '++r i '#'++'\n':(i+2)!(n-1)
r=replicate
```
*-10 bytes* thanks to @Laikoni.
You can [try it online](https://tio.run/##DczBCgIhEADQu18xbsEostAGXQL/oFvXhRAxG7JBZu33m/b2Tu@VtndpTStEWNUt1puHPcVpMmQ5CjAgYAgCBHjYgSvj1VE4e@t4XryRKKU3ymkU/STi/enfcR9yYzhChYv@8rOluumce/8D)!
] |
[Question]
[
# The Challenge
Given 3 numbers `X`, `Y` and `Z` in base `B`, find a `B`ase in which the addition of `X` and `Y` yields `Z`. The inputs `x = 20`, `Y = 12` and `Z = 32` could yield `5` because `20 + 12 = 32` in base 5.
* You may assume that there will always be a base in which the addition is correct (there are cases where no base exists, thanks to @[MasonWheeler](https://codegolf.stackexchange.com/users/16637/mason-wheeler) and @[Not that Charles](https://codegolf.stackexchange.com/users/13950/not-that-charles) for some examples of that).
* The lowest possible base is 1. You may use 1s or 0s as the digits in unary, but you may not mix those.
# I/O
* The digits of the input numbers will be non-negative integers.
* You may assume that the input numbers contain leading zeros, so the have a specific (or all the same) length.
* You may take the numbers in the most convenient format, as long as it's not preprocessed. This includes the overall format of the three input numbers and the format of the digits of each of those numbers. Please make it clear which format you use.
* If there are multiple possible bases, you can output all or just one of them.
* You may assume that the base and the input numbers will be within the numerical limits of your language.
# Rules
* Function or full program allowed.
* [Default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission.
# Test cases
Input format here is a list of integers to represent each number. The three lists are separated by commas.
Note that there are sometimes multiple bases possible. Only one (random) solution is outputted here.
```
[12, 103],[4, 101],[16, 204] -> 349
[4, 21, 25],[5, 1, 20],[9, 23, 17] -> 28
[16, 11],[25, 94],[41, 105] -> 147
[2, 140],[21, 183],[24, 100] -> 223
[8, 157],[1, 28],[9, 185] -> 227
[2, 158],[88],[3, 12] -> 234
[8, 199],[1, 34],[9, 233] -> 408
[3, 247],[7, 438],[11, 221] -> 464
[3, 122],[3, 2],[6, 124] -> 480
[6, 328],[3, 31],[9, 359] -> 465
[2, 1, 0, 0, 0, 0],[1, 2, 0, 0, 1, 0, 1, 0],[1, 2, 2, 1, 1, 0, 1, 0] -> 3
[16, 105],[16, 120],[33, 84] -> 141
[15, 60],[9, 30],[24, 90] -> 268
[2, 0],[1, 2],[3, 2] -> 5
[1, 3, 3, 7],[1, 2, 3],[1, 4, 6, 0] -> 10
[0],[1, 12, 8],[1, 12, 8] -> 16
[1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1],[1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1],[1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0] -> 2
[1],[1],[1,1] -> 1
```
You can generate additional test cases with [this Pyth program](http://pyth.herokuapp.com/?code=JEKE%2B%2Bj%5C%2C%5BjJQjKQj%2BJKQ%29%22%20-%3E%20%22Q&input=5%0A10%0A7&debug=0). Enter a base on the first line and the decimal values for `X` and `Y` on the following two lines.
Also you can use [this Pyth program](http://pyth.herokuapp.com/?code=VQJO5000KO5000%3DHO500%2B%2Bj%5C%2C%5BjJHjKHj%2BJKH%29%22%20-%3E%20%22H&input=10&debug=0) to create multiple test cases at once by using random values. Just enter the desired amount of test cases in the input.
**Happy Coding!**
[Answer]
# Jelly, ~~16~~ ~~11~~ 7 bytes
```
_/N,‘FṀ
```
This approach is heavily based on [@beaker's Octave answer](https://codegolf.stackexchange.com/a/76224).
Input format is **Z, Y, X**, with little-endian digit order, using the digit **0** for unary.
[Try it online!](http://jelly.tryitonline.net/#code=Xy9OLOKAmEbhuYA&input=&args=WzE3LCAyMywgOV0sIFsyMCwgMSwgNV0sIFsyNSwgMjEsIDRd) or [run all test cases](http://jelly.tryitonline.net/#code=Xy9OLOKAmEbhuYAKw4figqw&input=&args=W1tbMjA0LCAxNl0sIFsxMDEsIDRdLCBbMTAzLCAxMl1dLCBbWzE3LCAyMywgOV0sIFsyMCwgMSwgNV0sIFsyNSwgMjEsIDRdXSwgW1sxMDUsIDQxXSwgWzk0LCAyNV0sIFsxMSwgMTZdXSwgW1sxMDAsIDI0XSwgWzE4MywgMjFdLCBbMTQwLCAyXV0sIFtbMTg1LCA5XSwgWzI4LCAxXSwgWzE1NywgOF1dLCBbWzEyLCAzXSwgWzg4XSwgWzE1OCwgMl1dLCBbWzIzMywgOV0sIFszNCwgMV0sIFsxOTksIDhdXSwgW1syMjEsIDExXSwgWzQzOCwgN10sIFsyNDcsIDNdXSwgW1sxMjQsIDZdLCBbMiwgM10sIFsxMjIsIDNdXSwgW1szNTksIDldLCBbMzEsIDNdLCBbMzI4LCA2XV0sIFtbMCwgMSwgMCwgMSwgMSwgMiwgMiwgMV0sIFswLCAxLCAwLCAxLCAwLCAwLCAyLCAxXSwgWzAsIDAsIDAsIDAsIDEsIDJdXSwgW1s4NCwgMzNdLCBbMTIwLCAxNl0sIFsxMDUsIDE2XV0sIFtbOTAsIDI0XSwgWzMwLCA5XSwgWzYwLCAxNV1dLCBbWzIsIDNdLCBbMiwgMV0sIFswLCAyXV0sIFtbMCwgNiwgNCwgMV0sIFszLCAyLCAxXSwgWzcsIDMsIDMsIDFdXSwgW1s4LCAxMiwgMV0sIFs4LCAxMiwgMV0sIFswXV0sIFtbMCwgMSwgMCwgMCwgMSwgMSwgMSwgMSwgMCwgMSwgMSwgMCwgMCwgMV0sIFsxLCAwLCAwLCAxLCAxLCAxLCAwLCAxLCAwLCAwLCAxXSwgWzEsIDAsIDAsIDEsIDEsIDEsIDAsIDAsIDAsIDEsIDAsIDAsIDAsIDFdXSwgW1swLCAwXSwgWzBdLCBbMF1dXQ).
### How it works
Rather than incrementally testing potential bases, this solves the polynomial that corresponds to the array **P := X + Y - Z**. This returns either the largest coefficient of **P ≠ 0** – which has to be a root, since there is at least one valid base – or the highest digit of **X**, **Y** and **Z**, incremented by **1**.
```
_/N,‘FṀ Main link. Argument: [Z, Y, X]
_/ Reduce by subtraction; yield Z - X - Y.
This works since Z must have at least as many digits as X and Y.
N Negate to yield X + Y - Z.
‘ Yield [Z, Y, X], with all digits increments by 1.
, Pair the results to the left and to the right.
F Flatten the resulting, nested list.
Ṁ Compute the maximum.
```
[Answer]
# Pyth, 13 bytes
```
f!-FiRTQheSsQ
```
Expects Z, followed by X and Y.
[Test suite](https://pyth.herokuapp.com/?code=f%21-FiRTQheSsQ&input=%28%5B9%2C+23%2C+17%5D%2C+%5B5%2C+1%2C+20%5D%2C+%5B4%2C+21%2C+25%5D%29&test_suite=1&test_suite_input=%28%5B16%2C+204%5D%2C+%5B4%2C+101%5D%2C+%5B12%2C+103%5D%29%0A%28%5B9%2C+23%2C+17%5D%2C+%5B5%2C+1%2C+20%5D%2C+%5B4%2C+21%2C+25%5D%29%0A%28%5B41%2C+105%5D%2C+%5B25%2C+94%5D%2C+%5B16%2C+11%5D%29%0A%28%5B24%2C+100%5D%2C+%5B21%2C+183%5D%2C+%5B2%2C+140%5D%29%0A%28%5B9%2C+185%5D%2C+%5B1%2C+28%5D%2C+%5B8%2C+157%5D%29%0A%28%5B3%2C+12%5D%2C+%5B88%5D%2C+%5B2%2C+158%5D%29%0A%28%5B9%2C+233%5D%2C+%5B1%2C+34%5D%2C+%5B8%2C+199%5D%29%0A%28%5B11%2C+221%5D%2C+%5B7%2C+438%5D%2C+%5B3%2C+247%5D%29%0A%28%5B6%2C+124%5D%2C+%5B3%2C+2%5D%2C+%5B3%2C+122%5D%29%0A%28%5B9%2C+359%5D%2C+%5B3%2C+31%5D%2C+%5B6%2C+328%5D%29%0A%28%5B1%2C+2%2C+2%2C+1%2C+1%2C+0%2C+1%2C+0%5D%2C+%5B1%2C+2%2C+0%2C+0%2C+1%2C+0%2C+1%2C+0%5D%2C+%5B2%2C+1%2C+0%2C+0%2C+0%2C+0%5D%29%0A%28%5B33%2C+84%5D%2C+%5B16%2C+120%5D%2C+%5B16%2C+105%5D%29%0A%28%5B24%2C+90%5D%2C+%5B9%2C+30%5D%2C+%5B15%2C+60%5D%29%0A%28%5B3%2C+2%5D%2C+%5B1%2C+2%5D%2C+%5B2%2C+0%5D%29%0A%28%5B1%2C+4%2C+6%2C+0%5D%2C+%5B1%2C+2%2C+3%5D%2C+%5B1%2C+3%2C+3%2C+7%5D%29%0A%28%5B1%2C+12%2C+8%5D%2C+%5B1%2C+12%2C+8%5D%2C+%5B0%5D%29%0A%28%5B1%2C+0%2C+0%2C+1%2C+1%2C+0%2C+1%2C+1%2C+1%2C+1%2C+0%2C+0%2C+1%2C+0%5D%2C+%5B1%2C+0%2C+0%2C+1%2C+0%2C+1%2C+1%2C+1%2C+0%2C+0%2C+1%5D%2C+%5B1%2C+0%2C+0%2C+0%2C+1%2C+0%2C+0%2C+0%2C+1%2C+1%2C+1%2C+0%2C+0%2C+1%5D%29&debug=0)
Essentially, we test every possible base, starting at one more than the largest digit. The test is that we convert each number to the base in question, then fold subtraction over the numbers, and logically negate the result.
[Answer]
# Octave, ~~67~~ ~~75~~ ~~38~~ 32 bytes
Because "loop over ALL the things" is too much work.
```
@(x,y,z)max([m=max(x+y-z) z])+~m
```
Requires 0 padding to make the input arrays the same size, e.g.:
```
[2, 158],[88],[3, 12]
becomes
[2, 158],[0, 88],[3, 12]
```
Since `0` is used for padding, `1` is used as the token for unary.
(Thanks to [@DenkerAffe](https://codegolf.stackexchange.com/users/49110/denkeraffe) for clarification in the question.)
Sample run on [ideone](http://ideone.com/b2ypOu).
---
**Short Explanation:**
Take a case involving no carries:
```
[ 8, 199]
+ [ 1, 34]
-------------
9, 233
- [ 9, 233]
-------------
0, 0 --- no carries
```
In this case there are no restrictions on base as long as it's greater than any "digit". Simply take the max element of `z` (as `z >= x,y`) and add 1 (or any positive integer).
In the case of a carry-out (with no carry-in), we've exceeded the base in one of the columns and the difference between `x+y` and `z` is the base:
```
[ 2, 140]
+ [21, 183]
--------------
23, 323
- [24, 100]
-------------
-1 223
^ ^------ base
|---------- carry in
```
If the second column's sum also exceeded the base, requiring a carry-out as well as the carry-in, its value would be `base+(-1)`. We will have had a column somewhere to the right with a carry-out and no carry-in that has the correct (greater) base value.
[Answer]
## Haskell, ~~90~~ 73 bytes
```
f l=[b|b<-[1..],all(<b)$id=<<l,[x,y,z]<-[foldl((+).(b*))0<$>l],x+y==z]!!0
```
Usage example: `f [[3, 247],[7, 438],[11, 221]]` -> `464`.
Simply try all bases `b` (where `b` is greater than the maximum of the digits). Pick the first one where `x+y==z`.
Edit: @xnor saved many bytes by primarily getting rid of the `import Data.Digits`.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 20 bytes
```
`GY:@XJZQ2:"wJZQ-]]J
```
Input is in the format (note outer curly braces):
```
{[4, 21, 25],[5, 1, 20],[9, 23, 17]}
```
This works in [current version (15.0.0)](https://github.com/lmendo/MATL/releases/tag/15.0.0).
[**Try it online!**](http://matl.tryitonline.net/#code=YEdZOkBYSlpRMjoid0paUS1dXUo&input=e1s0LCAyMSwgMjVdLFs1LCAxLCAyMF0sWzksIDIzLCAxN119)
### Explanation
```
` % do...while index
G % push input. First time pushed nothing but asks for input implicitly
Y: % unpack the cell array, pushing the three numeric arrays
@ % loop index: candidate base
XJ % copy into clipboard J
ZQ % evaluate polynomial: interpret third array in that base
2:" % for loop: do this twice (subtract the other numbers from the third)
w % swap, to process another array
J % push base
ZQ % evaluate polynomial: interpret array in that base
- % subtract
] % end for loop. A result 0 indicates a solution has been found
] % end do....while loop. Exit if top of stack is 0
J % push found base. Implicitly display
```
[Answer]
# MATL, ~~13~~ 12 bytes
```
--X>t~1G+hX>
```
Translation of my [Octave answer](https://codegolf.stackexchange.com/a/76224/42892) into MATL. (My first MATL answer!)
* Input order is `Z, X, Y` (or `Z, Y, X` if you prefer, I'm easy)
* Input arrays are zero-padded to equal lengths
* Takes unattractives as 1
[Try it online!](http://matl.tryitonline.net/#code=LS1YPnR-MUcraFg-&input=WzExLCAyMjFdClszLCAyNDddCls3LCA0MzhdCg)
### Explanation
```
--X>t~1G+hX>
-- % M = Z - X - Y
X> % P = max(M)
t~ % Duplicate and negate
1G % Push 1st argument (Z)
+ % ~P + Z
h % Concatenate [P (~P + Z)]
X> % Return max
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~28~~ 27 bytes (SBCS)
Saved 1 byte thanks to @[Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)
```
{⍺←1+⌈/∊⍵⋄0=-/⍺⊥⍵:⍺⋄⍵∇⍨⍺+1}
```
[Try it online!](https://tio.run/##TYw9CsJQEIR7TzG9hLyfxKhgZaOt8QIBiU1AWxErQ4yJL2jhEQQ7G20sPcpe5LkPItjs7nwzO8k68xabJFstrd2SeVNxll06lT6VFZkX1bkYeb4zqhvrobvq3DnlgcydZVfubMpvZBqq9p@HpuJCzTWejXnOJ9PYpiBz1FBkngoCfEFCdVqsGQdQTEIMoDRkhNAFxC8RcELym0bEPECPS4RLQP@XiBZLhX67vg "APL (Dyalog Unicode) – Try It Online")
Takes a matrix with columns `x z y`, with all of them padded with zeroes to have the same number of digits.
Explanation:
```
{
⍺←1+⌈/∊⍵ ⍝ First base
∊⍵ ⍝ Flatten the input into a single vector of digits
⌈/ ⍝ Maximum digit (reduce with max)
1+ ⍝Add one to that to get the lowest possible base
0=-/⍺⊥⍵ ⍝If this base works
:⍺ ⍝Return it
⍺⊥⍵ ⍝Convert to base ⍺
-/ ⍝Reduce with subtraction (x - (z - y)) = x + y - z
0= ⍝Check if it's 0 (the equation works)
⍵∇⍨⍺+1 ⍝Otherwise, call itself (∇) with the next base
}
```
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ζÆ(I>M
```
Port of [*@Dennis*'s Jelly answer](https://codegolf.stackexchange.com/a/76232/52210), so make sure to upvote him as well! The I/O is also in the same format, except with the input wrapped inside a list instead of three loose inputs: \$[Z,Y,X]\$, with little-endian digit order, using the digit \$0\$ for unary.
[Try it online](https://tio.run/##MzBNTDJM/f//3LbDbRqedr7//0dHGxrpGMfqRFtYAAlDUwsdo9hYAA) or [verify all test cases](https://tio.run/##dVHLTcUwEGwleieQ5rAfO7EvvAqoIOQAEi0gpYFXAMXQAHeKoJGwu7ajd0ErK6sZ78ysQ/n1jd@Pj/16mX5vn9Pluh8/X9@3h/3p@cDjy7Guq1ACzxtWJkaKr4Jl2zCtKy8QRTVUCIzsTYb4xcZTRmJDa4I4y@xinSNICBa1EW@SIZ0suckWBJMXlM4I1JBSAi5jQLTl0NQGah0DYnHYsaQFi2umxSS6WILv1jRZZBCaa5PjYNRy9Ni@px@GWLnuQMhqIK14pCsJ2hxoPGY@H6L2d1AKy9mu5B49zIemjAAz2pLa7WwdK@5W9nMCPRu6D96i87lEIB7ojqN/cTo5Gn7Whkf4bH8).
The new 05AB1E version would require an additional leading `0` to overwrite the default space-filler of `ζ`. In the legacy 05AB1E version built in Python, the spaces are counted as 0 when we reduce by subtracting with `Æ`, though. Which would have given [an error in the new version](https://tio.run/##yy9OTMpM/f//3LbDbRqedr7//0dHGxrpGMfqRFtYAAlDUwsdo9hYAA), which is built in Elixir.
**Explanation:**
```
# i.e. input = [[12,3],[88],[158,2]]
ζ # Zip/transpose the (implicit) input-matrix, swapping rows/columns,
# using a space filler by default if the rows doesn't have matching lengths
# STACK: [[12,88,158],[3," ",2]]
Æ # Reduce each inner-most list by subtracting, counting the spaces as 0
# STACK: [-234,1]
( # Negate each
# STACK: [234,-1]
I> # Push the input again, and increase each value by 1
# STACK: [234,-1],[[13,4],[89],[159,3]]
M # Push the largest value on the stack, which also looks inside (nested) lists
# STACK: [234,-1],[[13,4],[89],[159,3]],234
# (after which this top value is output implicitly as result)
```
] |
[Question]
[
From [Wikipedia](https://en.wikipedia.org/wiki/Gabriel%27s_Horn), Gabriel's Horn is a particular geometric figure that has infinite surface area but finite volume. I discovered this definition in [this Vsauce's video](https://www.youtube.com/watch?v=ffUnNaQTfZE&t=22s) (starting at 0:22) where I took the inspiration for this problem.
You begin with a cake (a cuboid) of dimension \$x \times y \times z\$. In your first slice of the cake, you will end up with two smaller cakes of dimension \$\frac{x}{2} \times y \times z\$. Next, you will slice **only one** of the two pieces of cake you sliced previously, and so on. The picture below illustrates this:
[](https://i.stack.imgur.com/5yl7W.png)
# Task
I cannot believe that the surface area can grow infinitely even if the volume of the cake stays the same and your task is to prove me that! However, I trust you and if you show me that the first 10 slices of the cake that the surface area is really growing, I will believe you.
You will receive the initial \$x \times y \times z\$ dimension of the cake as input and will output a list of 10 values referring to the total surface area of all cuboids after each consecutive slice.
# Specs
* The cake will always be sliced in half and it will always be sliced in the same dimension.
* The surface area \$S\$ of a cuboid of dimension \$x \times y \times z\$ is: \$S = 2xy + 2xz + 2yz\$
* The outputted list should first start with the surface area after no slices (that is, the cuboid original surface area), then 1 slice and so on.
* The slices are going to be done in the \$x\$ dimension and the test cases below will assume this.
* The surface area you have to calculate includes all pieces of cake sliced in previous iterations.
* Input is flexible, read it however you see fit for you.
* Standard loopholes are not allowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
# Test Cases
```
Format:
x, y, z --> output
1, 1, 1 --> [6, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0, 22.0, 24.0]
1, 2, 3 --> [22, 34.0, 46.0, 58.0, 70.0, 82.0, 94.0, 106.0, 118.0, 130.0]
3, 2, 1 --> [22, 26.0, 30.0, 34.0, 38.0, 42.0, 46.0, 50.0, 54.0, 58.0]
7, 11, 17 --> [766, 1140.0, 1514.0, 1888.0, 2262.0, 2636.0, 3010.0, 3384.0, 3758.0, 4132.0]
111, 43, 20 --> [15706, 17426.0, 19146.0, 20866.0, 22586.0, 24306.0, 26026.0, 27746.0, 29466.0, 31186.0]
1.3, 5.7, 21.2 --> [311.62, 553.3, 794.98, 1036.6599999999999, 1278.3400000000001, 1520.02, 1761.6999999999998, 2003.38, 2245.06, 2486.74]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
ṙ1׿.Ɱ⁵Ḥ
```
[Try it online!](https://tio.run/##TZG9TgMxDMf3PsU9QBsljhPnFt4CJIQ6sqBObGwtCzsMgARCAtQJISEBasV46oPkXuTwR6GN7izf2f7Zf@fsdDa7GIa6vg/dbbd0/cd7v/iqq9dhc1PXL/38oZlMDpp@/lhXz3X11C@@jw67q255Dpvrur4b1Z/P7qq/fDsehjBu5NGCkzxuivP86dWCWlSb1WoUNAoaBY5OR0yAcRMNAuJqEWpR0iLSoqJFrSG9MQ0aohdSVFLYkUCTolYbNWo@wl4HjSb86zYdkXD5JQNRzvIDTVbaSirF5EA2KTlue5n8GIv1I1OAIYKKFTLKoN7oIZEXPqENG9pgc4Ev2RxIxRyMphqyt2Qg2ia3aMmRN5K1keMmybEWCA6sFwdd5rWkFCVKvMq2yC559pza3ZHro@Ii@v8jC0lyebJhygzayy8yrmeoOIDJiSRAnoRw@gs "Jelly – Try It Online")
Takes input as `[z, y, x]` as [allowed by OP](https://codegolf.stackexchange.com/questions/226022/convince-me-gabriels-horn-is-possible#comment522510_226022).
-1 byte thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy)
We calculate
$$2\left( \begin{matrix} z\times y \\ y\times x \\ x\times z\end{matrix} \right) \cdot \left( \begin{matrix} i \\ 1 \\ 1 \end{matrix} \right) = 2(yzi + yx+xz)$$
for each \$1 \le i \le 10\$
## How it works
```
ṙ1׿.Ɱ⁵Ḥ - Main link. Takes [z, y, x] on the left
ṙ1 - Rotate once left; [y, x, z]
× - Product; [yz, xy, xz]
⁵ - Yield 10
Ɱ - For each integer 1 ≤ i ≤ 10:
æ. - Dot product. Pad to [i, 1, 1] and calculate
[yz, xy, xz] . [i, 1, 1] = yzi+xy+xz
Ḥ - Double each
```
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
```
(x#y)z=[2*(x*y+x*z+n*y*z)|n<-[1..10]]
```
[Try it online!](https://tio.run/##TZFNb9swDIbv/hVCFyCyY2sS9eks6WnH3XcwfHARbzWWOEaSAomx/55JZLrWsAnKJB/ypV67859@v7/f@fXLLZ@3DRT8WtxW12JejcWtmPO/46ZqlBBKtu390A3jdnfMGB/KY76pfh26ie9Ox4npXJynbuRft8tqmW8Wz7/7y49h7DO27y/NtbyVc7s99d1usWyW62G1emqf1uvm@/HtZd@33zqMsUieTsN44Xyj@krJCH07LLqXcwTOw/RzuLzyKu84TZuXyC0fp4yl8e6qZOllVfXMGleyIGQ8SrSA1qB1aDEKGAWMQoy2WSRAyTRBILlYZLDIYpHHooBFNSElMQmqtEwkjST1QQJM0lhNVI35Bj51wKg1793azCdu/DyBvHPphyFZ9iEpBJIDjqQ4/ehF8rUO1M@TAqM0oNhENmlQSXRlvUx8b2hYVSuaC2Rw5IAN5BhNqsFJSgbvH8m1oWQdN@KwkYhNrIhaQAmgXjEoXFyLtTpFfVxlHdIu4@zO1h9Puj4fhDby/5MWYtPlpQ17F0Gf8kMaV0ZocsBYkSSBiZN40/4D "Haskell – Try It Online")
The relevant function is `(#)`, which takes as input `x`, `y`, `z` in this order and outputs the areas of the first 10 iterations.
[Answer]
# [R](https://www.r-project.org/) >= 4.1.0, ~~39~~ 28 bytes
```
\(x,y,z)2*(1:10*y*z+x*y+x*z)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQqdSp0rTSEvD0MrQQKtSq0q7QqsSiKs0/6dpmOsoGBoCsbnmfwA "R – Try It Online")
Note the TIO link has `function` in place of `\` since TIO is running an older version of R. However, the functionality is identical.
A function taking `x`, `y` and `z` and returning a vector of the surface areas.
Saved 11 bytes by looking at [Delfad0r’s Haskell answer](https://codegolf.stackexchange.com/a/226024/42248) (and so using a much similar formula with no non-operator functions!)
[Answer]
# [Zsh](https://www.zsh.org/), 43 bytes
```
eval '<<<$[2*($1*$2+$1*$3+$2*$3*'{1..10}\)]
```
[Try it online!](https://tio.run/##qyrO@F@cWqJgrmBoqGBo/j@1LDFHQd3GxkYl2khLQ8VQS8VIG0Qaa6sYAUkt9WpDPT1Dg9oYzdj//wE "Zsh – Try It Online")
`eval '...'{1..10}\)]`: evaluate the command `<<<$[2*($1*$2+$1*$3+$2*$3*N)]` repeated with `1` to `10` in place of `N`. No semicolons needed, because `<<<` can be chained implicitly.
[Answer]
# [Factor](https://factorcode.org/), 56 bytes
```
[ 3dup [ * ] 2tri@ 10 [1,b] [ 4dup * + + 2 * nip ] map ]
```
[Try it online!](https://tio.run/##bVJNT8MwDL3vV5grH1HifBYkxA1x4YI4TTuU0kHF6EpbDmjabx@OXUYlSCQ38nPes1@zLqtx2x8eH@7uby/hre7begPv5fiq@rJ9qQfYbKtyM8BQf3zWbUWJDELX1@P41fVNO8LVYrFbAK0dGN57mNYJXFxTNgAkpQGM5ogcHcfAkVFkFBnFjO6PpAj2DykigGUSxySeSSKTJCYpREKLhogYq2fMlpjNv8zIl7h4UrF83@FMkVHvjuo/tJHUwMQf4ok2hpDbcGKCnwxISYbHIIMHOymLWdYmUY8ynzMW59aQkKMptGhNSsZHnbWikzFMYaRj1CnIAX2Sg7PiDwYtxRjjVFw4KbbkXZiLKgteRUCjkHQnUapSgZzz3hIOkdwvUrafBgq@@F35BcSkrNPHZbIh@f9j7joQ0aw@5b41keYDOq/ybOiopeiop/1hCfb5s4MlnMIKcOybG1KFpTl/WlHSZewUzmgjfdumo6r3kiJdXDf9MFpK0HvutkPNwDCW1ZuCalOX/eEb "Factor – Try It Online")
*Data flow combinator version thanks to @Bubbler*
The interesting thing about Factor is you generally have four ways to approach golf: dataflow combinators, stack shuffling, local variables, and "sequence-y" (making heavy use of `math.vectors` and other sequence words). The thing about dataflow combinators is that despite keeping the data stack static and easier to reason about, they're almost always longer than the other three methods. However, once in a while they will win out over the others for some reason, and it's not always clear which will win until you give them all a try.
# [Factor](https://factorcode.org/), 57 bytes
```
[| x y z | 10 [1,b] [ y z * * x z * x y * + + 2 * ] map ]
```
[Try it online!](https://tio.run/##bZJNT8MwDIbv@xXmOiBKnM@CxBVx4YI4TTuUqYNpoxttkTa2/fbh2GVUgkRKo9h5H/tt5uWsWzen56eHx/sbWFZNXa3gvezeVFPWr1ULq/WsXLXQVh@fVT2jgxyETVN13W7TLOoObkej/Qho7MHwPEI/LuD6jk4DQFIawGhekVfHa@CVo8hR5Cjm6PEsimD/iCICWBZxLOJZJLJIYpFCEFoYAjFWD5QtKZt/lZEvcXJPsXzf4YDIUe/O9B/ZSDQw8Ue4l40h5DKcmOB7A1KS5jFI48H2ZDHL2iT0KP05Y3FoDYEcdaGF1ZOMjzqzopM2TGGkYtQpyAZ9ko2z4g8GLckYY59cOEm25F0YQpUFryKgUUjcHkpZKpBz3luKQyT3i5Ttp4aCL35HfgExKev0eZhsSP7/mKsOJDTIT7luTaJ5g86r3Bs6Kik6qul4mhxgCzv4ggPRYGKuXqYw4YMxzS1/c8IYLmkifaf0iDcwPU1gvmjaztIBPejNuq040HblbKlO3w "Factor – Try It Online")
*Locals*
# [Factor](https://factorcode.org/), 60 bytes
```
[ 10 [1,b] [ '[ 1 _ 1 ] over 1 rotate v* v. 2 * ] with map ]
```
[Try it online!](https://tio.run/##bVLLbhsxDLz7K9hTAKMVJOq5CZBrkEsvRU@GUWwNJTEcPyKrbg3D3@5S5MZZoOViCUqkZsiRnvpF3ZbL92@PXx9uYd3XF1X6zXPew1M5wiqXTX6FfX77lTcL2rxGKv@ppd/LiUNuILKAXcm1HndlualwN5mcJkB2AsPfGQb7BF/uaTcAJKUBjGaP7B37wJ6zyFnkLLbs@QqKYP8BRQSwDOIYxDNIZJDEIJ1QaOEQEmP1CNkSsvkvMvIhLh5YLJ93OGLkrHdX9nfYSGxg4jvwABtDaG04EcEPAqQkw2OQwYMdmEUsa5OwR5nPGYtjaYjI0RRauAYm46NuXNHJGKYz0jHqFCRAnyRwVvTBoKUYYxyKOyfFlrQLY1JlwasIaBQS70BKVSqQct5bykMk9bvU5KeBgu8@rL2AmJR1@mqmCdLuH1vXgYBG9an1rQm0Bei8arOho5aio57OlxmRwMx8/jmHGdzQCn7QP4ftIRcKyrb2NcNhCgdF9z2lzO8lPeF1v4P5pfl97RcrdfkL "Factor – Try It Online")
*"Sequence-y"*
[Answer]
# [Mathematica](https://www.wolfram.com/mathematica/), 29 bytes
```
2*(#*#2+#*#3+#2*#3*Range@10)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6ZgqxDz30hLQ1lL2UgbSBhrKxsBSa2gxLz0VAdDA021/wFFmXkl0WnRhjpGOsaxsf8B)
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 48 bytes
```
(x,y,z)=>{for(i=22;i-=2;)print(2*x*(y+z)+i*y*z)}
```
[Try it online!](https://tio.run/##BcFBCoAgEADAr3TcVYPcuoX9JUphi1QsIo3ebjPbfM/nkjhe7Rl5tekIfre5OlPhUVkVNNPrQgI2RCO3hkaMif0FJB4BWRaULLIo@FUHWmvVDL1qqMP6Aw "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# JavaScript, 53 bytes
Output is a space delimited string with a leading space.
```
x=>y=>g=(z,n=11)=>--n?g(z,n)+` `+(n*y*z+x*y+x*z)*2:``
```
[Try it online!](https://tio.run/##FcdBCoAgEADAr3Tc1QysW7D2FaNUilijItLPWx3mMOt4j@d0LPulOM6ueCoPmUQmEOSaSWskoxQP4S9KW1kJLJLI8hHpk1G0vbVlinzGzTVbDOChQ2gRNGJ5AQ)
Or 52 bytes using commas instead of spaces:
```
x=>y=>g=(z,n=11)=>--n?g(z,n)+[,(n*y*z+x*y+x*z)*2]:[]
```
[Try it online!](https://tio.run/##FcdLCoAgEADQ68xYBtYuGDuIuIg@UsQYGaFe3mrxFm8fnzFM13bekv28lJVKJJ1IO4JcMymFpKXkwf3FytTAIolcRZE@GUVre2PL5Dn4Y2kO72CFDqFFUIjlBQ)
[Answer]
# [J](http://jsoftware.com/), 23 bytes
```
(2*+/+i.@10*1&{)@:*1&|.
```
[Try it online!](https://tio.run/##bY9NigJBDIX3niK4UFvbmJ@qVHXDgDDgypVXkGlGNx5A796mSlEXBsILrx5fUudxivMBfnqYQwsEvfca4few340LWa42qxNumZY8uzbb3uWGYzP5O/5fYIDUArN3ehiLZFacQEiukUPVnHNREZOqplZUiWtONdecplhzgdVzDaz7LxuUGU1aiFFRW0hdwC77OznTYvcu9yRl1ECvKpwovlMK0Bz0kXeIEDm0DBIikn9FQjZM4XkLl40R/SRhlPEO "J – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 55 bytes
```
(x,y,z)=>[...Array(10)].map((_,i)=>2*(++i*y*z+x*y+x*z))
```
[Try it online!](https://tio.run/##DcnLCoAgEEDR3xl1GnqsC/qOiJBeGOaERaQ/by7u5txDv/qevbmewvGypq1N8GHAKNpuIKLeex2gKsVIp74AJjT51BKUMjLIqD4ZclGINLO72a5keYcNKqyxyfoD "JavaScript (Node.js) – Try It Online")
Someone will probably outgolf me with recursion, but I have not yet found a suitable way to do so yet. This is essentially just a port of most people's answers.
---
# [JavaScript (Node.js)](https://nodejs.org), 53 bytes
```
(x,y,z)=>[...Array(i=10)].map(_=>2*(x*y+x*z+y*z*i--))
```
[Try it online!](https://tio.run/##DchbCoAgEADA66ybLj2@DTpHREhpGJWhEerlrfmcXb0qLN7ej7jcqouRBSJPPDPZj0Q0eK8SWNnUbKJT3TDLvkWImKqIuUqY0QrBWFncFdyh6XAbGGh4y7t/Pw "JavaScript (Node.js) – Try It Online")
Outputs in reverse order
[Answer]
# [Python 3](https://docs.python.org/3/), 51 bytes
```
lambda x,y,z:[2*(x*y+x*z-~n*y*z)for n in range(10)]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp1KnyiraSEujQqtSu0KrSrcuT6tSq0ozLb9IIU8hM0@hKDEvPVXD0EAz9n9BUWZeiUaahqEOEGpq/gcA "Python 3 – Try It Online")
-1 byte thanks to @dingledooper
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~70~~ 69 bytes
Saved a byte thanks to [EliteDaMyth](https://codegolf.stackexchange.com/users/100752/elitedamyth)!!!
```
f(x,y,z,i)float x,y,z;{for(;++i<11;)printf("%f ",2*(x*y+x*z+i*y*z));}
```
[Try it online!](https://tio.run/##jVPtbpswFP2fp7CQhoA4DH/D6PZn6lMsVRVR06J1pEoiDYjy6suufUnImrUqsi2be3zOubZvtXisquOxjjra04E2cf28Xu2IX5X7er2Jyvm8uWGsjF82Tburo@BTTQLKk6hL@nmXDPMm6ZMhjsvDEeLk16ppo3i2nxH4kGxnt7v77scd@Ur2jBJoghIDE@ZWqTiUr8H9Gcx9c0AJm1RqrsHDGSw8OQNqnkFnKR/R1dNqkxDbvdhqZx8QH2hK8hRwLPMj96P0o/ajj3If5T7KIRpQEnCwJDxSeqTySOORuUcWyJMhETIxkU3buY8IvwWphAdJfkHro0qeJNxeo7UjlOhZjX7zHL1yjT61GOkxNyFylDDoVDLBkY4pkzlCI9EQKxhq8yzXOOEqx4kUmA7XGYK5MSO4kAgWkKpGZpimGhJVSqTuuuFEitwdCVjTqpg@d/QmT4XMzp@7ROUO3l290UB0gc@duQxI3YRLlboEuARdI4N/7rt6stVPu4HrJv7Cl90tX3bFd@jKWbxYi9NOePEkcu@4aR9sB9uycpzekG0z2HUdnZ5R/Hn8kZz/lASKxaFjggUwPVXHNRaCR9yVrwD9CdC/ARhOgOEKMJUmJdjJ4htUKdQx6SkZ4gsurPSLP2NxAPu5QP5vwGbUMmo5tYJaSa2iVlNrqM2pLSbwdlutWjgmOOHJz0c6@A1BIwSREFRCkAlBJwShEJRCkApBK7RFfJ36sr0d3X9x6b/dli3ovJvKyH6YHY5/qvp59bg9Ln7/BQ "C (gcc) – Try It Online")
Prints out the surface areas starting at the beginning.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 41 bytes
```
{(A[1]×⍳10)++/1↓A←2×⍵×1⌽⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rDMdow9vD0R72bDQ00tbX1DR@1TXZ81DbBCCS29fB0w0c9e4GM2v9pQMFHvX2Pupof9a551Lvl0HrjR20TH/VNDQ5yBpIhHp7B/9MUDEGQK03BSMEYTJvqmSsYGeoZKRjqGQMA "APL (Dyalog Unicode) – Try It Online")
* my 1st Apl answer, footer stolen.. Honestly I still can't completely understand it because haven't seen yet the SRC and THIS commands.
* input as Y Z X vector `⍵`.
```
A←2×⍵×1⌽⍵ U store in A input rotated once and multiplied by input and then doubled
Obtaining total a,b,c planes surfaces
+/1↓A U sum of b,c planes which remains always the same
(A[1]×⍳10)+ U added to a plane multiplied by [1..10]range
```
[Answer]
# [Julia 1.x](http://julialang.org/), 32 bytes
```
(x,y,z)->2(x*y.+x*z.+(1:10)*y*z)
```
[Try it online!](https://tio.run/##VYvRCoMwDEXf/Yqwp6TWYOuGMJj/ImMyRXRIB7U/36VlgxmSkJx77/Sex974OMAtote7DlR1Fr3aufQqcInmampSuwoUh3V79PcnOqg6eG3j4uYFp3Vc0Gk4SZMMVCLKM6BjZiJdgBTmnS@jIfVX@CGroflHTUYHVyt/SraHaELn5K4PmAVdWCLWsKUsUEHxAw "Julia 1.0 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
IEχ⊗⁺Σ∕Πθθ×ιΠ…θ²
```
[Try it online!](https://tio.run/##Nck9C8IwEIDhv5LxAifYOjqmqxDQrXSISaAHV9N8Ffz1p4O@w7O8fnXFJ8cittCrgXG1wc3tMJxRTak/OQaw3Cvc@wYTHRQi2JJC9w2yRpX1lwdtsQKh@h/z9hzNmnbIqEb96yoyzwOOeFkWOR38AQ "Charcoal – Try It Online") Link is to verbose version of code. Takes an array `[z, y, x]` as input. Explanation:
```
χ Predefined variable `10`
E Map over implicit range
Σ∕Πθθ Half-area of initial cuboid
⁺ Plus
ι Number of cuts
× Multiplied by
Π…θ² Half-area of each cut
⊗ Doubled
I Cast to string
Implicitly print
```
[Answer]
# Ruby 2.7+, 39 bytes
```
->x,y,z{(1..10).map{2.*_1*y*z+x*y+x*z}}
```
Requires ruby 2.7+ for numbered arguments to work.
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), [63 bytes](https://tio.run/##K0gtyjH7n1upoJKmYPu/WiPO0EDh0G6tQ7s1orViFRziow11jGI1gULah3ZHa4NFDHQMdAxjo7QgklBpoA6j2v/WXCppGuY6hoY6huaaesWJlf8B "Perl 6 – Try It Online")
```
{(^10 »*»([*] @_[1,2]) »+»[+] @_[0,0,1]Z*@_[1,2,2]) »*»2}
```
Hyper-operators galore here leveraging constant difference between consecutive slicings of `2*y*z`:
* `^10` generates `0..9` ...
* `»*»` multiplies each integer in the sequence by ...
* `[*] @_[1,2]` is `y*z`
* `»+»` then adds to each of element in the sequence ...
* `[+] @_[0,0,1] Z* @_[1,2,2]`, which computes `x*z + x*y + y*z`
* `»*»2` then multiplies the resultant list by 2
[Answer]
# [Desmos](https://desmos.com/calculator), 28 bytes
```
f(x,y,z)=2(xz+xy+[1...10]yz)
```
[Try It On Desmos!](https://www.desmos.com/calculator/d92yz3mog8)
[Try It On Desmos! (Prettified)](https://www.desmos.com/calculator/4qmba5qr9s)
] |
[Question]
[
### Input:
A matrix containing integers in the range **[0 - 9]**.
### Challenge:
Determine if all non-zero elements are connected to each other vertically and/or horizontally.
### Output:
A [truthy value](https://codegolf.meta.stackexchange.com/a/2194/31516) if all are connected, and a [falsy value](https://codegolf.meta.stackexchange.com/a/2194/31516) if there are non-zero elements/groups that aren't connected to other elements/groups.
### Test cases:
Test cases are separated by line. Test cases can be found in more convenient formats [here](https://tio.run/##TU9BEoIwDLzvK3JAB4FhqFAQeQbesEw9ePCgB/WmfssH@DFMAo5Mps1ms9mm1@P9dDkMnzcatL5psAhDzkNPEToEcNjfYiSE82rr0xhdsHSIdr5z/vGCSyhFQ@jTpwswtD4YMiAjvgxxCBwLSX/KYOyMoTgny23BIl6ryCjO@S5RKSeVaDZclXzqmY8VUxn6vT45sxtmCk5MmNEOlg3XPGWpEgRt5JPakFUsa9fKFSquSUL4YtpXP/gF) ([Kudos to Dada](https://codegolf.stackexchange.com/a/129148/31516)).
The following are all connected and should return a truthy value:
```
0
---
0 0
---
1 1 1
0 0 0
---
1 0 0
1 1 1
0 0 1
---
0 0 0 0 0 0
0 0 3 5 1 0
0 1 0 2 0 1
1 1 0 3 1 6
7 2 0 0 3 0
0 8 2 6 2 9
0 0 0 0 0 5
```
The following are all not-connected, and should return a falsy value:
```
0 1
1 0
---
1 1 1 0
0 0 0 2
0 0 0 5
---
0 0 5 2
1 2 0 0
5 3 2 1
5 7 3 2
---
1 2 3 0 0 5
1 5 3 0 1 1
9 0 0 4 2 1
9 9 9 0 1 4
0 1 0 1 0 0
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission in each language wins. **Explanations are encouraged!**
---
Inspired by [this challenge](https://codegolf.stackexchange.com/q/154306/31516).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 7 bytes
```
4&1ZI2<
```
This gives a matrix containing all ones as [truthy](https://codegolf.stackexchange.com/a/95057/36398) output, or a matrix containing at least a zero as [falsy](https://codegolf.stackexchange.com/a/95057/36398). [Try it online!](https://tio.run/##y00syfn/30TNMMrTyOb//2gDBTi0BlPGCqYKhhAOkFIwAtHWQKYhWM5QwcxawRwsCuKClVkAuWZAbGmtgDBMwTQWAA)
You can also verify truthiness/falsiness adding an `if`-`else` branch at the footer; [try it too!](https://tio.run/##y00syfn/30TNMMrTyOa/vQIcqCp4pnGplxSVlmRUqoP5AaXFGQolGZnFCsUlRZl56Vy1yKpdc4pTudTTEnOKwcqxqP8fbaAAh9ZgyljBVMEQwgFSCkYg2hrINATLGSqYWSuYg0VBXLAyCyDXDIgtrRUQhimYxgIA)
Or [verify all test cases](https://tio.run/##bU@xjsIwDN3zFV6gW9WUFqiCxAIDGwPToUpUupZGCi0iQYiBby@2c4VWuliJ/Z6fHftSONOd4HMmsGnDMHzU2pRdMpU/u3jVrYf5XSUCd7u7@hkw3t9tDa7WFqy76eYsXkP11thSBFVhLMv/0@cjffMLuhKb0UTaXk3x/MPiMJqmqXSjXQk8MZi2vXbHKBfHCOiVgKYggh6iVzBgpZf25skZpKhgQBUxeV9FOQlzBQtmCbJsiXCON1PwbQYpN@fSzzD9H9hWjWToiZK@sUI0w1BSsKCQG8T0IUlJmDLgVTJmE1@QsVEm6VfgxfM3).
### Explanation
```
4 % Push 4 (defines neighbourhood)
& % Alternative input/output specification for next function
1ZI % bwlabeln with 2 input arguments: first is a matrix (implicit input),
% second is a number (4). Nonzeros in the matrix are interpreted as
% "active" pixels. The function gives a matrix of the same size
% containing positive integer labels for the connected components in
% the input, considering 4-connectedness
2< % Is each entry less than 2? (That would mean there is only one
% connected component). Implicit display
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~80~~ ~~77~~ 74 bytes
```
T`d`@1
1`1
_
+m`^((.)*)(1|_)( |.*¶(?<-2>.)*(?(2)$))(?!\3)[1_]
$1_$4_
^\D+$
```
[Try it online!](https://tio.run/##K0otycxL/P8/JCElwcGQyzDBkCueSzs3IU5DQ09TS1PDsCZeU0OhRk/r0DYNextdIzugqIa9hpGmiqamhr1ijLFmtGF8LJeKYbyKSTxXXIyLtsr//4YKRgrGCgZAaMplqGAKZhsqGHJZgsVMgLIgNgiCxE24QCQEGwAA "Retina 0.8.2 – Try It Online") Edit: Saved 1 byte thanks to @FryAmTheEggman. Explanation:
```
T`d`@1
```
Simplify to an array of `@`s and `1`s.
```
1`1
_
```
Change one `1` to a `_`.
```
+m`^((.)*)(1|_)( |.*¶(?<-2>.)*(?(2)$))(?!\3)[1_]
$1_$4_
```
Flood fill from the `_` to adjacent `1`s.
```
^\D+$
```
Test whether there are any `1`s left.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 54 bytes
Saved 2 bytes thanks to user202729.
```
Max@MorphologicalComponents[#,CornerNeighbors->1<0]<2&
```
[Try it online!](https://tio.run/##RY7LCoMwEEX3/Qqh0FUKjq9WsKXg2tK9uEhLfIAmErMoiN@eTkaxDJPh3LnczMBNKwZuug@3tXfzbMG/j0LpsVW9alDtczWMSgpppvLIcqWl0E/RNe1b6el8h8yvsuBkX7qTpqzLefbZXgsjClnMYCOcLMAGJCAK8U2QLqQ7Xp1X5AQ73VLWipelqg7/3wAd4bZxiTERUH5KeoSOlVy5XbRfAnQlJtof "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# JavaScript (ES6), ~~136~~ 135 bytes
Returns a boolean.
```
m=>!/[1-9]/.test((g=(y,x=0)=>1/(n=(m[y]||0)[x])&&!z|n?(m[y++][x]=0,z=n)?g(y,x)&g(--y-1,x)&g(y,x+1)||g(y,x-1):g(m[y]?y:+!++x,x):m)(z=0))
```
### Test cases
```
let f =
m=>!/[1-9]/.test((g=(y,x=0)=>1/(n=(m[y]||0)[x])&&!z|n?(m[y++][x]=0,z=n)?g(y,x)&g(--y-1,x)&g(y,x+1)||g(y,x-1):g(m[y]?y:+!++x,x):m)(z=0))
console.log('[Truthy]')
console.log(f([
[0]
]))
console.log(f([
[0,0]
]))
console.log(f([
[1,1,1],
[0,0,0]
]))
console.log(f([
[1,0,0],
[1,1,1],
[0,0,1]
]))
console.log(f([
[0,0,0,0,0,0],
[0,0,3,5,1,0],
[0,1,0,2,0,1],
[1,1,0,3,1,6],
[7,2,0,0,3,0],
[0,8,2,6,2,9],
[0,0,0,0,0,5]
]))
console.log('[Falsy]')
console.log(f([
[0,1],
[1,0]
]))
console.log(f([
[1,1,1,0],
[0,0,0,2],
[0,0,0,5]
]))
console.log(f([
[0,0,5,2],
[1,2,0,0],
[5,3,2,1],
[5,7,3,2]
]))
console.log(f([
[1,2,3,0,0,5],
[1,5,3,0,1,1],
[9,0,0,4,2,1],
[9,9,9,0,1,4],
[0,1,0,1,0,0]
]))
```
### Commented
The recursive function **g()** first looks for a non-zero cell (as long as the globally-defined flag **z** is set to **0**) and then starts flood-filling from there (as soon as **z != 0**).
```
m => // given the input matrix m
!/[1-9]/.test(( // test whether there's still a non-zero digit
g = (y, x = 0) => // after recursive calls to g(), starting at (x=0,y=0):
1 / (n = (m[y] || 0)[x]) && // n = current cell; if it is defined:
!z | n ? ( // if z is zero or n is non-zero:
m[y++][x] = 0, // we set the current cell to zero
z = n // we set z to the current cell
) ? // if z is non-zero:
g(y, x) & // flood-fill towards bottom
g(--y - 1, x) & // flood-fill towards top
g(y, x + 1) || // flood-fill towards right
g(y, x - 1) // flood-fill towards left
: // else:
g(m[y] ? y : +!++x, x) // look for a non-zero cell to start from
: // else:
m // return the matrix
)(z = 0) // initial call to g() + initialization of z
) // end of test()
```
[Answer]
# C, 163 bytes
*Thanks to @user202729 for saving two bytes!*
```
*A,N,M;g(j){j>=0&j<N*M&&A[j]?A[j]=0,g(j+N),g(j%N?j-1:0),g(j-N),g(++j%N?j:0):0;}f(a,r,c)int*a;{A=a;N=c;M=r;for(c=r=a=0;c<N*M;A[c++]&&++r)A[c]&&!a++&&g(c);return!r;}
```
Loops through the matrix until it finds the first non-zero element. Then stops looping for a while and recursively sets every non-zero element connected to the found element to zero. Then loops through the rest of the matrix checking if every element is now zero.
[Try it online!](https://tio.run/##hVPdboIwFL73KToTCbU1AQQUu87wAPICzgvSiZFkbOnYFeHZWX9A56AdOcF6fr7zna8Htrow1nXLFGf4QC5uCZvyhXpO@ZwtD46THsvTXr6oh0UQZVD@LLJ9ufJ3nvqzUj6ElFf4dh5pCzfHHDN4replTpqU5iSjjBwoJ8UHdxnlNKceYbIJSY8MoZPjIMShOIvTU46Q41xcBgk/19@8euKk7QQYeM@vlQtnzQyIRzrq81ftH0@AgsZriXJ/chEo3Pni7bWaY1C4KgcDaRCS2UNt0NdiYC0PVHkwKl/rchGTCFjF/jx958mYKgK@rfMaA2mjzuGt8z/o1rlCMdQUenSX5cHMbQTJSHExJmmRAj2yRSoNJg7xZNJmwNB5xnZblRerd2LTZ7DIJpSYTTSOR0LFN6GMI1kvQPMbL9bm8Xqt0itVrWHraBulYziisP29A5Gph3@/jqlwpMADkzxaVplhYyiuMpximNxECvpd0FQNPKMhyfjFJANGaOGc4N40Umjfd9/wEYrhQD9eoqip3Wq7Hw)
**Unrolled:**
```
*A, N, M;
g(j)
{
j>=0 & j<N*M && A[j] ? A[j]=0, g(j+N), g(j%N ? j-1 : 0), g(j-N), g(++j%N ? j : 0) : 0;
}
f(a, r, c) int*a;
{
A = a;
N = c;
M = r;
for (c=r=a=0; c<N*M; A[c++] && ++r)
A[c] && !a++ && g(c);
return !r;
}
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~36~~ 22 bytes[SBCS](https://github.com/abrudz/SBCS)
```
~0∊∨.∧⍨⍣≡2>+/|↑∘.-⍨⍸×⎕
```
[Try it online!](https://tio.run/##TVDBCsIwDL33K3pckela181d/JeBTARhXgXxOKsw0YPoVTwofoF3/yQ/MpOUzRFK897LS9Lmq2U4W@fLct7A8bIooTpFAtyuaLYRuAO41xDcE@oX1A/Y3810MNpAdQZ3G4bMfr5XNDZoaQoB9TsSdO0pk5xX50BLDBUgISPVcQT6km4lrvPhlbG0WMaAbIaL2UqalokKUmYJctkEYYInU71uVomwG8ENetvodgKFaRPb38kSr/0gFVicZaiNlSml/1aGtmAzAsuAH5kxG3tXJilIidt3@S8R4Q8 "APL (Dyalog Unicode) – Try It Online")
thanks @H.PWiz
`⍸×⎕` coordinates of non-zero squares
`2>+/|↑∘.-⍨` [adjacency matrix](https://en.wikipedia.org/wiki/Adjacency_matrix) of the neighbour graph
`∨.∧⍨⍣≡` [transitive closure](https://en.wikipedia.org/wiki/Transitive_closure)
`~0∊` is it all 1s?
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
FJṁa@µ«Ḋoµ€ZUµ4¡ÐLFQL<3
```
[Try it online!](https://tio.run/##y0rNyan8/9/N6@HOxkSHQ1sPrX64oyv/0NZHTWuiQg9tNTm08PAEH7dAHxvj/4fbgYL//0dzRUcbxMbqgCgdBSjLUEcBhGJ1FMCCyOJgDlAcQ4khwhBkhFBgrKNgCtYEE4OYZgTVDTcTohTIMAOJmcNUQIRhei3AwmZg0hLJnTBkCncNzGRUr6G4DOQKFJ4psl9MobKGcJeAeKZg5xhBzQfyzCECcFuMIO6FmgfRbwoTgwWdJUyFCcIsoBgEQdSZoIQWLAZiuWIB "Jelly – Try It Online")
---
## Explanation.
The program labels each morphological components with a different numbers, then check if there are less than 3 numbers. (including `0`).
Consider a row in the matrix.
```
«Ḋo Given [1,2,3,0,3,2,1], return [1,2,3,0,2,1,1].
« Minimize this list (element-wise) and...
Ḋ its dequeue. (remove the first element)
So min([**1**,**2**,3,**0**,3,2,**1**],
[2,3,**0**,3,**2**,**1**] (deque)
) = [1,2,0,0,2,1,1].
o Logical or - if the current value is 0, get the value in the input.
[**1**,**2**,0,0,**2**,**1**,**1**] (value)
or [1,2,**3**,**0**,3,2,1] (input)
= [1,2,3,0,2,1,1]
```
Repeatedly apply this function for all row and columns in the matrix, in all orders, eventually all morphological components will have the same label.
```
µ«Ḋoµ€ZUµ4¡ÐL Given a matrix with all distinct elements (except 0),
label two nonzero numbers the same if and only if they are in
the same morphological component.
µ«Ḋoµ Apply the function above...
€ for **€**ach row in the matrix.
Z **Z**ip, transpose the matrix.
U **U**pend, reverse all rows in the matrix.
Together, **ZU** rotates the matrix 90° clockwise.
4¡ Repeat 4 times. (after rotating 90° 4 times the matrix is in the
original orientation)
ÐL Repeat until fixed.
```
And finally...
```
FJṁa@ ... FQL<3 Main link.
F **F**latten.
J Indices. Get `[1,2,3,4,...]`
ṁ **ṁ**old (reshape) the array of indices to have the same
shape as the input.
a@ Logical AND, with the order swapped. The zeroes in the input
mask out the array of indices.
... Do whatever I described above.
F **F**latten again.
Q uni**Q**ue the list.
L the list of unique elements have **L**ength...
<3 less than 3.
```
[Answer]
# [Haskell](https://www.haskell.org/), 132 bytes
```
\m->null.snd.until(null.fst)(\(f,e)->partition(\(b,p)->any(==1)[(b-d)^2+(p-q)^2|(d,q)<-f])e).splitAt 1.filter((/=0).(m!)).indices$m
```
extracted from [Solve Hitori Puzzles](https://codegolf.stackexchange.com/questions/154306/solve-hitori-puzzles/154734#154734)
`indices m` lists the `(line,cell)` locations of the input grid.
`filter((/=0).(m!))` filters out all locations with non-zero values.
`splitAt 1` partitions off the first member into a singleton list next to a rest list.
`any(==1)[(b-d)^2+(p-q)^2|(d,q)<-f]` tells if `(b,p)` touches the frontier `f`.
`\(f,e)->partition(\(b,p)->touches(b,p)f)e` splits off touchers from not[yet]touchers.
`until(null.fst)advanceFrontier` repeats this until the frontier can advance no further.
`null.snd` looks at the result whether all locations to be reached were indeed reached.
[Try it online!](https://tio.run/##ZU5BbsMgELz7FVTKYVfFNCS1k0hxpEg99geOK5HaVlGBECCHSP27C/iSqkLszszC7HwJ/z0oNUltLy6QNxEEOzon7sWj8i59KLSQprFOmrDQwsJETro8mJtSzJue3UyQCjIdfUA4wUgHLA9WuCCDvJionKmNijB3aBqOLZzLHj9Wz2DLa@w/0NMr7suxwwGZt0qGYyCcjVKFwQG8NEtkoJ8QmTS9/Bz8Qk@kVTFbTgzAKUcKG1ojtkv696xpRXlGqa5y5xmvY63pJmuJpbqNrI539@BQdbQghPzbV@V9PL6e/6Y9VcbJf3Z4jdOEd5nzyOccOVHXTb8 "Haskell – Try It Online")
[Answer]
# Perl, ~~80~~ ~~79~~ ~~78~~ ~~73~~ 70 bytes
Includes `+2` for `0a`
Give the input matrix without spaces on STDIN (or in fact as rows separated by any kind of whitespace)
```
perl -0aE 's%.%$".join"",map chop,@F%seg;s%\b}|/%z%;y%w-z,-9%v-~/%?redo:say!/}/'
000000
003510
010201
110316
720030
082629
000005
^D
```
Easier to read if put in a file:
```
#!/usr/bin/perl -0a
use 5.10.0;
s%.%$".join"",map chop,@F%seg;s%\b}|/%z%;y%w-z,-9%v-~/%?redo:say!/}/
```
[Answer]
# [Grime](https://github.com/iatorm/grime), 37 bytes
```
C=[,0]&<e/\0{/e\0*0$e|CoF^0oX
e`C|:\0
```
Prints `1` for match and `0` for no match.
[Try it online!](https://tio.run/##Sy/KzE39/9/ZNlrHIFbNJlU/xqBaPzXGQMtAJbXGOd8tziA/gis1wbnGKsbg/38DMOAyMDA2NQRShgZGBoZchoYGxoZmXOZGQGGgoIWRmZElF1ihKQA "Grime – Try It Online")
## Explanation
The nonterminal `C` matches any nonzero character that is connected to the first nonzero character of the matrix in the English reading order.
```
C=[,0]&<e/\0{/e\0*0$e|CoF^0oX
C= A rectangle R matches C if
[,0] it is a single character other than 0
& and
< it is contained in a rectangle S which matches this pattern:
e/\0{/e\0*0$e R is the first nonzero character in the matrix:
e S has an edge of the matrix over its top row,
/0{/ below that a rectangle of 0s, below that
e\0*0$e a row containing an edge, then any number of 0s,
then R (the unescaped 0), then anything, then an edge.
|CoF^0oX or R is next to another match of C:
CoF S is a match of C (with fixed orientation)
^0 followed by R,
oX possibly rotated by any multiple of 90 dergees.
```
Some explanation: `e` matches a rectangle of zero width or height that's part of the edge of the input matrix, and `$` is a "wildcard" that matches anything.
The expression `e/\0{/e\0*0$e` can be visualized as follows:
```
+-e-e-e-e-e-e-e-+
| |
| \0{ |
| |
+-----+-+-------+
e \0* |0| $ e
+-----+-+-------+
```
The expression `CoX^0oX` is actually parsed as `((CoF)0)oX`; the `oF` and `oX` are postfix operators and concatenation of tokens means horizontal concatenation.
The `^` gives juxtaposition a higher precedence then `oX`, so the rotation is applied to the entire sub-expression.
The `oF` corrects the orientation of `C` after it is rotated by `oX`; otherwise it could match the first nonzero coordinate in a rotated English reading order.
```
e`C|:\0
e` Match entire input against pattern:
: a grid whose cells match
C C
| or
\0 literal 0.
```
This means that all nonzero characters must be connected to the first one.
The grid specifier `:` is technically a postfix operator, but `C|:\0` is syntactic sugar for `(C|\0):`.
[Answer]
# Java 8, ~~226~~ ~~219~~ ~~207~~ ~~205~~ 201 bytes
```
int[][]M;m->{int c=0,l=m[0].length,i=m.length*l;for(M=m;i-->0;)c+=m[i/l][i%l]>0?f(i/l,i%l):0;return c<2;}int f(int x,int y){try{M[x][y]*=M[x][y]>0?f(x+f(x,y+f(x-f(x,y-1),y)),y)-1:1;}finally{return 1;}}
```
-2 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##pVPBcpswEL3nK/aSGYgFBicktSnuLTfnktwYDjIRsVIhMiBSMwzf7qxk0oCbaaZlNMLap923u0/rZ/pKnefHn4dU0KqCDeUS2jMALhUrM5oyuNMmwLYoBKMSUguv4iROcjvEiw730V1jmxDmc5gtYdsoVoEqQO2YMZy0qKVCzzuQEMEhd9YtBkEaeUREeewlrmDySe0Ij/L@eCHCrCitTZSH3HHWXminM3Tlc5HE/Fwka@9HZqFF0LBXXlgyVZdY4fdF2IWaPNO1wp7ob2O3qmzaTbxP4ia5iPqD4djPcJNGfx1zcnybNLbejr/ywy7jkgrRtH0GRLoDwEu9FTyFSlGFP68Ff4Qc9bPuVcnlU5wAtY/aGVVzbFuyX8awjHagxXooa7VrVsa8byrFcreolfuCFEpIK3elm1o6rpf4yAjQep05dXbP9W/BZFK4T3B1ZMA2lU8TkL/Q@xO7fV9j1ksSYKoRqEtZmISjcrSvT64/wBvjpeFR@DeEr3EvT9QxK/i6if7mfTpuqajYf03HuIHpr30qHap0CgRT3ygYcvpHgT@AALVeDNsKyI2GprW20C9oih9kDgw4GsKl8boaV7AkemnPq9MZ8qf@Jz4d2U@eok/2hdcfXP5vaFhjd9Yd3gA)
**Explanation:**
```
int[][]M; // Integer-matrix on class-level, uninitialized
m->{ // Method with integer-matrix parameter & boolean return
int c=0, // Amount of non-zero islands, starting at 0
l=m[0].length, // Amount of columns in the matrix
i=m.length*l; // Index integer
for(M=m; // Set the class-level matrix to the input
i-->0;) // Loop over the cells
c+= // Increase the count by:
m[i/l][i%l]>0? // If the current cell is not 0:
f(i/l,i%l) // Flood-fill the matrix with a separated method
// And increase the count by 1
: // Else:
0; // Leave the count the same
return c<2;} // Return whether 0 or 1 islands are found
// Separated recursive method with cell input & integer return
int f(int x,int y){
try{m[x][y]*=M[x][y]>0?
// If the current cell is not 0:
f(m,x,y-1) // Recursive call west
f(m,x-...,y) // Recursive call north
f(m,x,y+...) // Recursive call east
f(m,x+...,y) // Recursive call south
-1:1;} // Empty the current cell
}finally{ // Catch and swallow any ArrayIndexOutOfBoundsExceptions
// (shorter than manual if-checks)
return 1;} // Always result in 1, so we use it to our advantage
// to save bytes here by nesting, instead of having four
// loose calls to each direction)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~211~~ ~~163~~ 150 bytes
```
m,w=input()
def f(i):a=m[i];m[i]=0;[f(x)for x in(i+1,i-1,i+w,i-w)if(x>=0==(i/w-x/w)*(i%w-x%w))*a*m[x:]]
f(m.index((filter(abs,m)or[0])[0]))<any(m)<1>q
```
[Try it online!](https://tio.run/##bVBNc4IwEL3zK3accUwUKxGhFcWbPbaX3hgOqGHMVD4a4wC/noZEaFo7s9mv93bzkrIR5yJftsfiRMPRaNRmdhWyvLwJhK0TTSFFDAdJmEUs3nQudDZRimqcFhxqYDliM2KzuTyzSsYKM4nuQicMEVtU83pR4SliY5mNK4ynyTSL6iCOrRRlTyw/0RqhlF0E5Sg5XO0MFzxyYtwdvE3yBmV4S3ZfrZRmVWd2ofDBbzSwAARvugBAa3qETr@qSs5yAZM0uVybidWhR1oKeEsyuue84IHJEvwmziZt//5qsA6cJp@t1GIDsSLHhi5bWhGRtTJHm@y6qqvrPzDRsDPQf5trg2eylV8@LHJV4tvw3KO6qZMX1fSVXz9c4UkFvlJwX/f/M4ybf@ZWvXJPYcRgeEqAbnpKWFfqGc1zDSrpBwYZg9BVv2Xdm@asjB8hw1f73w "Python 2 – Try It Online")
Output is via exit code. Input is as an 1d list and the width of the matrix.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~115~~ 102 bytes
```
A=>w=>(A.find(F=(u,i)=>u&&[-w,-1,1,w].map(v=>v*v>1|i%w+v>=0&i%w+v<w&&F(A[v+=i],v),A[i]=0)),!+A.join``)
```
[Try it online!](https://tio.run/##VVDdbsIgGL3nKdjFGpgUi1qd2SDpxbzcC3RN6LRVTG1NrdQY370DWjeXL8D5DuccfvapTk/rWh0bv6w2WZfzLuKi5QJFNFflBq04OhOFuTh7Xuy3xGeEkTahh/SINBf6RQt2U8/tSAseeA68t563QlGsR1wlRGMSxSrhAcbkaRTRfaVKKXH3BnRaw4bLAPi@DwLYrwyast1vb9Efy@7qezk8haFRWGz1E6djDk/NPAcLx9nOal5NNzdj@ZATDrnW93CTId9kgv86gwzH@lwQmuSJ8YZwYdHgn9jznIfB0GH7iqXjZk6/hLYsPxvu7t4r6elYqEa6HOn@@sJFfOlpNIa3r3K8xW7j83z4zmpMLnePjINkwFDSIiu3zS7BoKF5VX@k6x26crGuylNVZLSotihHV@PAZmYJxrj7AQ "JavaScript (Node.js) – Try It Online")
Receive input as `(1d-array)(width)`. Rewrites all entries in one of the connected non-zero regions with 0 and checks whether the resultant array is a zero matrix. The matrix will become zero if there is zero or one connected non-zero region.
```
A=> // all rows are concatenated into an 1-d array
w=> // width of the original matrix
(
A.find( // find the first non-zero entry
F=( // helper function
u, // value of the entry
i // index of the entry
)=>
u // return 0 if value is 0 or out of range
&&[-w,-1,1,w].map( // return an array otherwise, and find the neighbors
v=> // for each neighbor
v*v>1 // if y-coord change: let go anyway
|i%w+v>=0&i%w+v<w // if x-coord change: let go only if on the same row
&&F(A[v+=i],v), // recurse on the neighbor
A[i]=0 // before recursing change the current entry to 0
)
), // if all entries were 0, no change is made
!+A.join`` // return whether all entries are now 0
) // if all entries are 0, then +A.join`` == 0
```
>
> **Tip:** Use `Array.prototype.find` if you want to map through an array with a function that the return values can be ignored but to stop once the function is executed.
>
>
> In this case, I want to map through the array to change only the first connected non-zero region found, but not the other regions (otherwise the array will become a zero matrix no matter what the original input is), so `find` is used here to save some bytes.
>
>
>
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 96 bytes
```
f=(A,P,Q)=>!A.map((B,i)=>B.map((C,j)=>(P-i)**2+(Q-j)**2-1|!C||f(A,i,j,A[i][j]=0,P=0+[P])))|P>'0'
```
[Try it online!](https://tio.run/##VVBRb4IwGHzvr6hPFm0RUHRkKQmavS74zExgDBwExQAjxvDf2fcVnC5fgLvr3dE2j9qojqvs0ohz@ZX0fSqZx32@16Q78fRTdGFsyzNg24HseA6E@SLTZjNrzvYiRyDMbrLruhTCGc@5F2SHID9Ig/vSmAf@QdO0znenxrR/JW1U0UaGBhFCEIMOX5PCIPvjiB6qeXffR@EltcGBGP2W8pkKL@G9JhulIUPPC7A1PM5Tjz32Yu5pJ2M/dJL/PkCgmUMvsaHZgqxNN4jGvIX/UxmT2grjKRylrZTfoTior8a9q/OGen0psiZUPaG68Kt0r4PKFh/nxVFTaivddvTSwff@c/pMKrhm0uhpWb1F8Te7STcuz3VZJHpRHlnKbrDe/wI "JavaScript (Node.js) – Try It Online")
`P` = `0` if 1 chunk, `00` if 2 chunk, to allow call inside
[Answer]
# [Uiua](https://www.uiua.org/), 31 bytes
```
/×♭⍥'∺'/↥↧.⧻.⊠(≤1/+⌵-).▽♭∶/⊂⇡△.
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAgL8OX4pmt4o2lJ-KIuicv4oal4oanLuKnuy7iiqAo4omkMS8r4oy1LSku4pa94pmt4oi2L-KKguKHoeKWsy4KZiBbWzIgMyAwXSBbMSAwIDBdXQpmIFtbMSAxIDBdIFsxIDAgMV1dCmYgW1swIDBdXQ==)
The same approach as [ngn's APL answer](https://codegolf.stackexchange.com/a/154407/78410).
```
∧↧1♭⍥'∺'/↥↧.⧻.⊠(≤1/+⌵-).▽♭∶/⊂⇡△. input: a matrix(n,m)
▽♭∶/⊂⇡△. collect coordinates of positive numbers:
⇡△ coordinates of each position in the matrix (n,m,2)
/⊂ reduce by join; flatten the first two dimensions
♭∶ . original matrix flattened
▽ keep: for each number n in the matrix, get n copies of its coords
⊠(≤1/+⌵-). create adjacency matrix:
⊠( ). self cross product over the coordinates:
≤1/+⌵- sum of absolute difference is 1 or less?
⍥'∺'/↥↧.⧻. get transitive closure:
⍥ ⧻. run <length of the array> times:
'∺'/↥↧. self matrix product, using min as product and max as sum
/×♭ test if it is all ones
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ā©˜ƶ®gäΔ2Fø0δ.ø}2Fø€ü3}®*εεÅsyøÅs«à]˜0KÙg!
```
Input as a matrix of integers; output as a 05AB1E truthy/falsey value (only \$1\$ is truthy in 05AB1E, so if the result is \$\geq2\$ it's falsey).
[Try it online](https://tio.run/##yy9OTMpM/f//SMOhlafnHNt2aF364SXnphi5Hd5hcG6L3uEdtSDmo6Y1h/cY1x5ap3Vu67mth1uLKw/vAJKHVh9eEHt6joH34Znpiv//R0cb6MBhrA6YZ6xjqmMI5QFpHSMgNgTyDME8YyBpBuSZg8VBfIhKCyDfDIgtoaZAoGlsLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU3lotw6XkmNySWliDlzUvvLQSlsuJf/SEihf6f@RhkMrT885tu3QuvTDS85NMXI7vMPg3Ba9wztqQcxHTWsO7zGuPbRO69zWc1sPtxZXHt4BJA@tPrwg9vQcA@/DM9MV/yvphbnYZyopaJQUlZZkVGoqHV4N5KQl5hSnAjm1Ooe22f@Pjo42iI3VUQBSOlCGoQ4QxuqABBBCIKYOipQhXBsMQiWMdUyByiA8kEYjsGKIZpCsoY4ZkGcOFgfxISotgHwzILaE2QyGpjBLIAYguxBuH9AGOMsU4ShTsLAhxBogyxRolRHYHFMdcxAbZpYRyA1gvSDlpmAexJuWYHETqDZLHRAEyZnA/QYJmNhYAA).
**Explanation:**
Uses the same flood-fill algorithm I've used in multiple other challenges.
```
Ā # Convert each positive integer in the (implicit) input-list to 1s
© # Store this matrix in variable `®` (without popping)
˜ # Flatten it to a single list
ƶ # Multiply each by its 1-based index to make all values unique
®gä # Convert it back to a matrix with the dimensions of `®`
Δ # Loop until it no longer changes to flood-fill:
2Fø0δ.ø} # Add a border of 0s around the matrix:
2F } # Loop 2 times:
ø # Zip/transpose; swapping rows/columns
δ # Map over each row:
0 .ø # Add a leading/trailing 0
2Fø€ü3} # Convert it into overlapping 3x3 blocks:
2F } # Loop 2 times again:
ø # Zip/transpose; swapping rows/columns
€ # Map over each inner list:
ü3 # Convert it to a list of overlapping triplets
®* # Multiply each 3x3 block by the value in matrix `®`
# (so the 0s remain 0s)
εεÅsyøÅs«à # Get the largest value from the horizontal/vertical cross of each 3x3
# block:
εε # Nested map over each 3x3 block:
Ås # Pop and push its middle row
y # Push the 3x3 block again
ø # Zip/transpose; swapping rows/columns
Ås # Pop and push its middle rows as well (the middle column)
« # Merge the middle row and column together to a single list
à # Pop and push its maximum
] # Close the nested maps, flood-fill loop, and outer loop
˜ # Flatten the resulting flood-filled matrix
0K # Remove all 0s
Ù # Uniquify the values of each island
g # Pop and push its length (which is 1 if it was a single island)
! # Factorial to convert 0 to 1 (and 1 remains 1), since 0 is also truthy
# (after which the result is output implicitly)
```
[Answer]
# [Perl 5](https://www.perl.org/), ~~131~~ 129 + 2 (`-ap`) = 133 bytes
```
push@a,[@F,0]}{push@a,[(0)x@F];$\=1;map{//;for$j(0..$#F){$b+=$a[$'][$j+$_]+$a[$'+$_][$j]for-1,1;$\*=$b||!$a[$'][$j];$b=0}}0..@a-2
```
[Try it online!](https://tio.run/##PUzbCoJAFHz3KzY6kOZt1/RBZGGf9idsiRWKkspFCwL119vOGsUwnJk5w5hjfy2sNc/hLHRUCxlRNY8/69PgJaSqYM9ZddNmTNPq1PXQ@jRJYC2DEZqQg65ho2poQziocHFOYaCwHLOI4cCWQzNNq38XRxtO5xmHhI4zaxlhZEcoovAYKRaNmVfiLUlOskU7uGbuue@X9N2Zx6W7DzbW5gM "Perl 5 – Try It Online")
] |
[Question]
[
Starting with a binary list (just `1`s and `0`s) we are going to roll a ball over it. The ball has a position and a direction. At every step the ball does the following:
* If the number at it's position is `1`, then flip the direction. It "bounces".
* Flip the number, if it's `0` replace it with `1`, if it's `1` replace it with `0`.
* Move 1 step in the direction.
We start execution with the ball at the first position heading to the right. When the ball is out of the range of the list either to the left or the right we stop execution.
For an example here is each step being run with `[0,0,0,1,0]` to start.
```
[0,0,0,1,0]
^>
[1,0,0,1,0]
^>
[1,1,0,1,0]
^>
[1,1,1,1,0]
^>
[1,1,1,0,0]
<^
[1,1,0,0,0]
^>
[1,1,0,1,0]
^>
[1,1,0,1,1]
^>
```
## Task
Given a starting list as input output the list after the ball has rolled over it.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the goal is to minimize the size of the source code as measured in bytes.
## Test cases
```
[0,0,0,0,0] -> [1,1,1,1,1]
[0,0,0,1,0] -> [1,1,0,1,1]
[0,0,1,1,0] -> [1,0,0,1,1]
[0,1,0,1,0] -> [0,1,0,1,1]
[1,1,1,1,1] -> [0,1,1,1,1]
[1,0,1,0,0] -> [0,0,1,0,0]
[0,1,0,1] -> [0,1,0,1]
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~130~~ ~~118~~ 98 bytes
```
(load library
(d B(q((L R)(i R(i(h R)(reverse(B(c 0(t R))L))(B(c 1 L)(t R)))(reverse L
(q((L)(B()L
```
[Try it online!](https://tio.run/##XYwxDoMwEAR7XrHlXoe/QEF1FT8gwRInWZAYFInXOxgQiqNtbvZGu9q0BVteKTHM/YBgj9jHreKAhm9S0QkNHY1jPqP/@Lh4Nnyi5rpXoiIHOqicza1B81B7DGVJNLHFjjWuVL/sCnYFu@LvcOXm0/jz0xc "tinylisp – Try It Online")
-12 bytes thanks to Razetime. See the edit history for a `library`-less version.
-20(!) bytes thanks to DLosc. Maybe I'm not very good at golfing in tinylisp...
`B` does the rolling.
```
(def roll_ball
(lambda (Left Right Dir) ; takes left, right direction
(if (equal? Dir 1) ; if direction is 1,
(reverse (roll_ball Right Left 0)) ; reverse the result of roll_ball with left and right lists flipped
(if (nil? Right) ; if we're at the end of the list,
(reverse Left) ; reverse the left list and return
(if (equal? (head Right) 1) ; otherwise, if the head is 1
(roll_ball Left (cons 0 (tail Right)) 1) ; recurse, flipping the direction and changing the first element of Right to 0
(roll_ball (cons 1 Left) (tail Right) 0) ; otherwise, recurse on L, and add 1 to the Left
)))))
```
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~69~~ 62 bytes
```
(load library
(d F(q((L)(i(h L)(c 0(t L))(concat(map not(t L))(q(1
```
[Try it online!](https://tio.run/##XYo9DoAgFIN3TvHGuvEu4eQlEAZJkD9ZOD2SSIyYDu3Xtlhfnb1ia3BBGXJ2zypXAUMrErAtsDiomyaJ0kNPwWtVcKpIPpRRJnDDSt0lDYkv88Q8MU8709DLz@P3bzc "tinylisp – Try It Online")
Port of [tsh's answer](https://codegolf.stackexchange.com/a/242700/67312).
[Answer]
# x86-64 machine code, 19 bytes
```
6A 01 58 99 80 34 17 01 75 02 F7 D8 01 C2 39 F2 72 F2 C3
```
[Try it online!](https://tio.run/##jVJLj9MwED57fsUQtLvONq0aWBBq6R5YcURCqz0santwbac1Sp1gO5AS5a9TJmlpKSdkKdbM95hHLMtyuJZyvxd@ixwfIw6jdV6sRI4ZZBNWVn6DKbCyKNGJGphU38BNWF04/PDl6SN@fnrEuVNm4FS9TDrqV/sTPTCr16hJ4SdMKIVa1UkfM7ktj5E3xF6hA@Z0gDjCeAq6DtpZjB4ibL4XRmHG5UY4vM0TNDagjactwEtjZV4pje99UKYYbe4BfBDBSPTBVTJg0D5I4TU2vWqKvYuYv1uS/g/o50ucYQPNm6QZJ8fTtslfifQykV4m0ktGmhzPOXHgHBh3J0nbQjuFrrOtMJbH0ADLaKVcVKHA64CT0wA@BkboAe4UhloeT@l6McMwosnMYEAcxkpHcMajK4NRQpCYmyVt9AwM76M@zjiBHcMewv92xivzj3MVur3ym4W96RItMDixF/aTkBtjNcpC6UlfuytTd2US3FGoCmzO5uNXz2S/m3FeWW/WVqv@r93GWTyvBwMq2eKPjck18l3X47h@eN2Znhw4jb7a0ebihSWnmsB2v/8ls1ys/X64fXtHH3rpM@Lr/Dc "C++ (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI the address of an array of 8-bit integers and its length in RSI, and modifies it in place.
In assembly:
```
f: push 1 # Push 1 onto the stack.
pop rax # Pop it into RAX.
cdq # Sign extend EAX into EDX, making EDX 0.
# EDX will hold the current index into the array
# and EAX will hold the current direction (±1).
r: xor BYTE PTR [rdi+rdx], 1 # Flip the current number.
jnz s # Jump if the new value is not 0.
neg eax # Otherwise, the old value was 1; invert the direction.
s: add edx, eax # Advance in the current direction.
cmp edx, esi # Compare the current index with the length.
jb r # Jump back if the index is lesser, as unsigned integers;
# this will stop if it goes off either end,
# equaling the length or overflowing to all 1s.
ret # Return.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 36 bytes
```
i=>i.map((n,j)=>i[0]?j>0&n:i[j+1]^1)
```
[Try it online!](https://tio.run/##dY5BCoMwEEX3PUVWJaGpzmwF7UHCFIJVSbCJaOn100IVDXT4qxkej@ft2y7t7KbXNcRHl/o6ubpxxdNOUgbt1fcwQDffwDlUzvgL0h1VamNY4tgVYxxkLw3odaSUKEthUK@j018UcxRYFHMUWBRzK7DWPe2AIoP@NAfr9mACSIg8gNIH "JavaScript (Node.js) – Try It Online")
I don't have any proof of its correctness. It just passed all testcases. So it works.
[Answer]
# [R](https://www.r-project.org/), ~~69~~ ~~68~~ 66 bytes
Or **[R](https://www.r-project.org/)>=4.1, 59 bytes** by replacing the word `function` with a `\`.
*Edit: -1 byte thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).*
```
function(v,a=0){while((F=F+(T=(-T)^a))&&!is.na(a<-v[F]))v[F]=!a;v}
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jTCfR1kCzujwjMydVQ8PN1k1bI8RWQzdEMy5RU1NNTTGzWC8vUSPRRrcs2i1WUxNE2iomWpfV/k/TSNYw0IFCTU1lBV07hWhDHSiM5ULIG6LKG6DKG6LKG6DKG6LqN0DVD7cOWd4QWR6iAUk/VADFfDTTY/8DAA "R – Try It Online")
The `T=(-T)^a` trick abuses the fact that going left may only last for one step.
---
# [R](https://www.r-project.org/), 41 bytes
Or **[R](https://www.r-project.org/)>=4.1, 34 bytes** by replacing the word `function` with a `\`.
```
function(v)"if"(v,c(0,v[-1]),c(!v[-1],1))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jTFMpM01Jo0wnWcNApyxa1zBWE8hUBLN0DDU1/6dpgGSgUFNTWUHXTiHaUAcKY7kQ8oao8gao8oao8gao8oao@g1Q9cOtQ5Y3RJaHaEDSDxVAMR/N9Nj/AA "R – Try It Online")
Port of [@tsh'sanswer](https://codegolf.stackexchange.com/a/242700/55372) (with explanation by [@Jonah](https://codegolf.stackexchange.com/a/242708/55372)).
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
{.{(1-0,~}.),:0,}.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/q/WqNQx1DXTqavU0dawMdGr1/mtypSZn5CsYwqGCrpVCGlAPFCKkDTCkDRHSBhjShghpAwzdhsi6DdDshrsFJm0AtQAmDeWjGo5i9H8A "J – Try It Online")
Based on [tsh's JS answer](https://codegolf.stackexchange.com/a/242700/15469).
## how
* `{.{...,:...` If the input begins with 1...
* `0,}.` Change the 1 to a 0 (we're just bouncing off the first element and halting)
* `1-0,~}.` Otherwise, remove the first element, append a 0, and then, for each element, return the opposite of its right neighbor.
## why does this work?
This is an induction argument suggested by alephalpha in the comments of tsh's answer.
* Consider the 1 element case. Clearly, a 1 becomes 0 and a 0 becomes 1. Also note that in the 0 case we're traveling right when we halt, and in the 1 case we're traveling left. Let's go ahead and add "begins with 0 exits right" to our induction hypothesis.
* Assuming the hypothesis, consider the two cases:
+ `1 [n element input]` Clearly true as we bounce off first element.
+ `0 [n element input]` We now consider the two cases for the `n element input`:
```
Begins with 1:
>
0 1 ...
>
1 1 ...
<
1 0 ...
>
0 0 ... By induction, this will exit right,
so the initial element is proven 0, as needed.
Begins with 0:
>
0 0 ...
>
1 0 ... By induction, this will exit right,
so the initial element is proven 1, as needed.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 57 bytes
*-13 bytes thanks to `Wheat Wizard`, -5 thanks to `ophact`, -2 thanks to `loopy walt` and -1 thanks to `pxeger`*
```
def f(x):
i=c=0
while-~i*x[i:]:c^=x[i];x[i]^=1;i+=1-2*c
```
[Try it online!](https://tio.run/##TY7BCsMgEETv@Yq9RVOF2N4U@yNiLkbJgpgQAk0v/XVrW5HuwPKYmcNsz2NZ0y3n2QcI5KSyA9ROjx08Foyev3A4DUor3aQLWPV5kxYKL1rw6@ByWHeIgAmMGVmVZZVFY9FYNF@wqi//kr@OtWVNuW3HdJDIwKdZ98Dv0FMVSKSqJjS/AQ "Python 3 – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 90 bytes
```
(([]){(){}((()[{}])<{{}(<>)}{}>)<>([])}()){({}({})([{}()]))}{}{{}<>([]){{}({}<>)<>([])}}<>
```
[Try it online!](https://tio.run/##PcqxCoAwDATQX@l4Nwh1D/2R0qEOglgcXEO@PaYKkuVy97a7H9eyj366A7VRQTUArGqNovFIoakVSpnAwEBRqxGBwMa5h/yAvpv8PqJ7TvPWlB8 "Brain-Flak – Try It Online")
36 bytes to simulate the ball rolling, and 54 to ensure that the input is in the right direction.
[Answer]
# [Python 3](https://docs.python.org/3/), 84 bytes
Not a great score, but somewhat interesting.
This takes a list of bits encoded as an integer and a length argument and outputs a new list of bits encoded as an integer. It’s a literal implementation, not induction based.
Improvements are welcome, I haven’t gotten any of my attempts to make it smaller working. Maybe c would be a better language to port this answer to.
Thanks to pxeger for -5!
```
def f(x,l,b=1,d=1):
a=1<<l;c=a>>b;d*=x&c<1or-1
return f(x^c,l,b+d,d)if c&a-1else x
```
[Try it online!](https://tio.run/##JY3LCoMwEEX3fsWsamJHaCp2UY0/UlrQPGggjJJaSL8@VTOLw9w5XGb5re@ZmpS0sWBZRI@TFKil4PcCRin63ndKjsMwdbqS8aR6MYdaFBDM@g20d15qb501au4sqNNYC@M/BmKycwAPjuDBLthyZNeDt4MinxqRTU7txuf2eZuIJP2xLcHRyggnRyxyBENallAPUPIuu91YVnnOefoD "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[ā<¾å_#D¾è©_¾ǝ®XαDUi¼ë.¼
```
[Try it online](https://tio.run/##yy9OTMpM/f8/@kijzaF9h5fGK7sAqRWHVsYf2nd87qF1Eec2uoRmHtpzeLXeoT1AZQY6IGioYxALAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/@gjjTaH9h1eGq/sAqRWHFoZf2jf8bmH1kWc2@gSmnloz@HVeof2/FfSC9PRO7TVMPR/dLSBDhTG6ihAOYYIjiGCY4iQMdSBQggHIoesLDYWAA).
**Explanation:**
```
[ # Start an infinite loop:
ā< # Push a list in the range [0,length) (without popping the list)
# (which will use the implicit input-list in the first iteration)
¾å_ # If this list does not contain value `¾` (so we're out of bounds):
# (`¾` is 0 by default)
# # Stop the infinite loop
D # Duplicate the current list
¾è # Get the value at index `¾`
© # Store it in variable `®` (without popping)
_ # Invert the bit (with an ==0 check)
¾ǝ # Insert it back into the list at the same position `¾`
®Xα # Get the absolute difference between `®` and `X`
# (`X` is 1 by default)
DU # Store this as new value `X`
i # If this absolute difference `X` is 1:
¼ # Increment `¾` by 1
ë # Else:
.¼ # Decrement `¾` by 1 instead
# (after which the list is output implicitly as result)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 55 bytes
```
f=(n,d=1,a=0,C=n[a])=>C<2?f((n[a]^=1,n),d=C?-d:d,a+d):n
```
[Try it online!](https://tio.run/##VY8/b8MgEMV3PsVtBoVY0DEuyeCtQzJ0dF0FGYioLLBsEqWq@tld/EfI1S0/3r3j7n3Jhxya3nZh77zS42gEdlQJTqVgtBSukjURx/L15WQwnl6fsedItJSnvTooKneKHNzYeDcEsK67BxBwrRhdq0Yr88Q8MU86p2vNvHRYfc2HrrUBZx8uIwValuhnp5ug1eUelm3VZprOzBKzxGyjs42fpW11gVCrY4r4JyuQ8T3glAu8WeIR@EEwyb7VeetvOFsPif6MTh4KmR0iGqwfssVRISRqIJ1Kx4Nfhmbj2/vlnA@ht@5mzTf@H7CyNYnZ41U7ARz9jn8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~59~~ 58 bytes
```
f(a,l)int*a;{for(int i=0,d=1;i<l+0u;)i+=d*=(a[i]^=1)*2-1;}
```
[Try it online!](https://tio.run/##lVDRboMgFH2Wr2BdmkKlTpYtWULpjziXENT1Nk4XwZcZvt2Bbe3q28LDhXPPPfdw9O5T63GsiGI1hcZulRiqtiP@ikGmrJBcwL6O015QiGWxlURlkH9ITrfPOy7c@AiNrvuixHtjC2iT4wEhY5UFjY3tem2xLY3VypR4CKqNwKGo7C0XDl17JsuxxAMaXtmQsstxjv0B@D3A7wF@z@Dscm7AmXNmvMwjziEnUHD0paAhFA0o8gHgKYGT95QKXx4kNvBTthWZDdOnJZKlOfXkOKYo8irR8vvWq93Ip1x4zrwKzqsgrLJJCGnSiaLvzrcrsloDXjHfCvHTMHpt7A6r6e2dJCowGvo/ZbyGhXJv9VF1ZPPebALgIxp/AQ "C (gcc) – Try It Online")
-1 thanks to l4m2, making the numbers unsigned for the bounds check.
[Answer]
# JavaScript (ES6), 48 bytes
```
f=(a,d,i=0)=>1/a[i]?f(a,d^=!(a[i]^=1),i+1-2*d):a
```
[Try it online!](https://tio.run/##dY7BCsIwEETvfkW8ZXVrsh6F6IeELYSmkUhpxIq/HylWbMAwpxkej7m5l5u6R7w/mzH5PudgpEOP0WgwZ1LORr6EeWrNVs6tNQQY99Qcdx5OLndpnNLQH4Z0lUFajUsYQCglLOES3vxFqUR1FaUS1VWUSquuWn/XVihV0I9mZf0OlQMsRHmA8xs "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
If[#>0,{0,##2},1-{##2,0},{}]&@@#&
```
[Try it online!](https://tio.run/##TYsxC4AgEIX/ysGB00Vee@La1i4OEkUNNYSb3G83QcF4w@Pje@8O8dzvEK8t5APmvBwOjaakCXES4iGVJi2UxCtrUeX1vZ7oEAYDZes9KBgtpPJoEYIG3IE7cDdMLRWq@89E8gc "Wolfram Language (Mathematica) – Try It Online")
A port of [@tsh's JavaScript answer](https://codegolf.stackexchange.com/a/242700/9288).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ݬ;1ƊḢ?
```
[Try it online!](https://tio.run/##y0rNyan8///o7kNrrA2PdT3cscj@/@H2o5Me7pyhGfn/f7SBDhTG6kDZhnC2IZxtCBc31IFCMBsig6QmFgA "Jelly – Try It Online")
Port of [Jonah's excellent J solution](https://codegolf.stackexchange.com/a/242708/85334).
```
Ḣ Remove the first element of the input.
Ż ? If it's 1, prepend 0 to the remaining elements, else
¬ negate the remaining elements
;1Ɗ and append a 1.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ḢCɓŻṙ⁹^
```
[Try it online!](https://tio.run/##y0rNyan8///hjkXOJycf3f1w58xHjTvj/h9uPzrp4c4ZmpH//0cb6EBhrA6UbQhnG8LZhnBxQx0oBLMhMkhqYgE "Jelly – Try It Online")
Another port of tsh's idea:
```
ḢC h = 1 - input.pop(0)
ɓŻ input.prepend(0)
ṙ⁹ .rotate_left(h)
^ .xor(h)
```
I've rearranged it a bunch of ways looking for a 6-byte formulation, but I can't find one.
In J, this is something like `{.(-.@[|.=)0,}.` (15 bytes).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~35~~ 24 bytes
```
1T`d`10`0.*|1
^1(.*)
$+1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3zAkISXB0CDBQE@rxpArzlBDT0uTS0Xb8P9/AxDgAmJDEGkIIg1BbEMQ4AIxISIA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Uses @tsh's method (see @Jonah's explanation).
```
1T`d`10`0.*|1
```
Invert the first bits, or all of the bits if the first bit is a `0`.
```
^1(.*)
$+1
```
If the first bit is now a `1` then move it to the end.
Previous 35-byte version actually performed the steps given in the question:
```
^
>
{`>0
1>
>1
<0
0<
<1
}`1<
0>
\D
```
[Try it online!](https://tio.run/##JYgxCoBADAT7@Ydgme1DKsFPiJyFhc0VYie@PRoc2GHYc7@OvuUwzi1XgruFoSCEG@a4eJocC5aJTCv4prLKqlZB5f@8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
^
>
```
Mark the initial position and direction of the ball.
```
{`
}`
```
Repeat until the ball goes out of range.
```
>0
1>
>1
<0
0<
<1
1<
0>
```
Flip the number at the current position and update the position and direction of the ball. (I don't know any shorter way of describing this in Retina; even `T`>1<`<0>`>1|1<` is three bytes longer than replacing `>1` and `<1` manually.)
```
\D
```
Delete the marker.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 49 bytes
```
a->i=d=1;while(i>0&&i<=#a,i+=d=-d+2*a[i]=!a[i]);a
```
[Try it online!](https://tio.run/##TYpRCsIwEESvslYoiU2g62/dXCTkY6FWF4osRRBPH1NSiAwM82ZGeRP/0LwAZfZBaCacPk9Z70bC2PdyozM7GUrv5@F64SiJTrvbiTOrrl/D4APoJq93id0OHSyGrXUQ4@gOpUI1YgNsgG1Bd6hC3f5vKdn8Aw "Pari/GP – Try It Online")
---
## [Pari/GP](http://pari.math.u-bordeaux.fr/), 48 bytes, does not work for empty input
```
a->i=d=1;until(i<1||i>#a,i+=d=-d+2*a[i]=!a[i]);a
```
[Try it online!](https://tio.run/##TYrBCoQwEEN/ZVYv7drCzl7d9kdKDwPiMiAyiB4E/71WKlQCIS@J0ML2L2kEl8h6doPDfptXnhT/8DjYt2S4y7Uduu@bAkf3ulz3lEhk2hWB9SALz2uOzQUNjIq0NhDCx9yKmUrEClgB64LmVoGyPW8x6nQC "Pari/GP – Try It Online")
---
## [Pari/GP](http://pari.math.u-bordeaux.fr/), 44 bytes, does not work for empty input
```
a->if(a[1],a[1]=0;a,[!a[i%#a+1]|i<-[1..#a]])
```
[Try it online!](https://tio.run/##TY3BCoNADER/JVUEl2bFnFv9kZBDLkqglCC9FPrv6y4rbBkI85hh4npY3D1tsCSNq22jMgmWs8wPRb4p29DrneRnz8g0Tb2KhKTur@@oEFfww96fbLsCHeSJEBCYZ7wkmaqlBtSAWkJ4qULN/mvl9wk "Pari/GP – Try It Online")
A port of [@tsh's JavaScript answer](https://codegolf.stackexchange.com/a/242700/9288).
[Answer]
# [Python 3](https://en.wikipedia.org/wiki/Python_(programming_language)), 172 bytes
```
d=1
c=0
l=[int(i)for i in input()]
while c>-1 and c<len(l):
(d:=not(d))if(l[c]==1)else(d:=d)
l[c]=not l[c]
if d==1:
c+=1
else:
c-=1
print(l)
```
I just passed all of the test cases
And if a bit gets changed, it becomes a boolean (False is 0 and True is 1)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
I⎇§θ⁰Eθ∧κι⊞O⁻¹Φθκ¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyS1KC@xqFLDscQzLyW1QqNQR8FAU0fBN7EAxHTMS9HI1lHI1AQKBZQWZ/gXpBYlluQXafhm5pUWaxjqKLhl5pSkFoHUZoMUGWoCgfX//9HRBkAO0CwIGRv7X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @tsh's method (see @Jonah's explanation).
```
θ Input array
§ ⁰ First element
⎇ If nonzero then
θ Input array
E Map over elements
κ Current index
∧ Logical And
ι Current element
Else
¹ Literal integer `1`
⁻ Vectorised subtract
θ Input array
Φ Filtered by
κ Current index
⊞O ¹ Append literal integer `1`
I Cast to string
Implicitly print
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.