text
stringlengths 180
608k
|
---|
[Question]
[
Given the functions
```
L: (x, y) => (2x - y, y)
R: (x, y) => (x, 2y - x)
```
and a number `N` generate a minimal sequence of function applications which take the initial pair `(0, 1)` to a pair which contains `N` (i.e. either `(x, N)` or `(N, y)`).
Example: `N = 21`. The minimal sequence is of length 5, and one such sequence is
```
( 0, 1)
1. L ---> ( -1, 1)
2. L ---> ( -3, 1)
3. R ---> ( -3, 5)
4. L ---> (-11, 5)
5. R ---> (-11, 21)
```
Write the shortest function or program you can which generates a minimal sequence in `O(lg N)` time and `O(1)` space. You may output / return a string in either application order (`LLRLR`) or composition order (`RLRLL`), but document which.
[Answer]
## Perl, 82 81 Characters (complete program)
```
$n=<>;@_=(R,L);if($n<0){$n=1-$n;$a--}while($n>1){print$_[$n%2+$a];$n+=$n%2;$n/=2}
```
It takes one number as input, and it outputs the sequence in application order.
Edit: Instead of redefining the array in the if statement, set a number to negative one and add it to the index when the array is referenced. It achieves the same effect.
[Answer]
### Ruby, 55 or 39 characters
```
f=->n{(n>0?n-1:-n).to_s(2).tr'01',n>1?'LR':n<0?'RL':''}
```
The function returns the function sequence in composition order.
Usage:
```
puts f[21] # RLRLL
puts f[-6] # LLR
```
*Edit:* If we allow recursion (which violates the O(1) memory constraint but such does any function since the return value itself is O(lg n)) we can shrink the code to 39 characters.
```
f=->n{n<n*n ?f[(n-1)/2+1]+'RL'[n%2]:''}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
“”HĊß;ị⁾LR$ƲḂƑ?
```
[Try it online!](https://tio.run/##ATMAzP9qZWxsef//4oCc4oCdSMSKw5874buL4oG@TFIkxrLhuILGkT//w4figqxZ//8yMSwgLTY "Jelly – Try It Online")
This uses the same allowance in [Howard's answer](https://codegolf.stackexchange.com/a/3977/66833), in that we can use recursion, despite it violating the \$O(1)\$ memory requirement. If this isn't allowed, then the following 20 byte solution works instead:
```
ḶȯAṀ©Bị⁾LRUAƑ}¡$®aḟ0
```
[Try it online!](https://tio.run/##AT8AwP9qZWxsef//4bi2yK9B4bmAwqlC4buL4oG@TFJVQcaRfcKhJMKuYeG4nzD/w4figqxZ//8yMSwgLTYsIDEsIDA "Jelly – Try It Online")
Both output the composition order
## How they work
```
“”HĊß;ị⁾LR$ƲḂƑ? - Main link f(N). Takes N on the left
? - If statement:
Ƒ - If: Invariant under:
Ḃ - Bit; Yields 1 for 0/1, else 0
“” - Then: Return the empty string
Ʋ - Else:
H - N÷2
Ċ - Ceiling
ß - f(⌈N÷2⌉)
$ - Group the previous 2 links together as a monad g(N):
⁾LR - "LR"
ị - Modular index N into "LR"
; - Append to f(⌈N÷2⌉)
```
The 20 byte version (+6 bytes to handle \$N = 0, 1\$):
```
ḶȯAṀ©Bị⁾LRUAƑ}¡$®aḟ0 - Main link. Takes N on the left
Ḷ - [0, 1, ..., N-1] for N > 0 else []
A - abs(N)
ȯ - Replace [] with abs(N)
Ṁ - Max; N-1 if N > 0 else abs(N)
© - Save this to the register R
B - Convert R to binary
$ - Group the previous 2 links into a monad f(N):
⁾LR - "LR"
} - To N:
Ƒ - Invariant under:
A - Absolute value; 1 if N ≥ 0 else 0
¡ - Do the following that many times:
U - Reverse "LR"
This yields "RL" if N ≥ 0 else "LR"
ị - For each bit in R, index into "RL" or "LR",
yielding a list of Rs and Ls, S
® - Yield R
a - Replace all but R = 0 with S
ḟ0 - Change R = 0 to []
```
] |
[Question]
[
I'm making a page selector for my super cool terminal-based blog program. In order for it to fit correctly into the design, it has to have some constraints.
The page selector can only display a certain number of numbers at a time due to the constraints of the UI system. If there are more characters then can fit, they must be removed and replaced with an ellipsis (which itself counts as a number). The system will try to display up to three numbers around the selected one (which is displayed surrounded by square brackets) and distribute the rest of the numbers evenly at the ends.
Your task is to, given a number of pages, selector width (always more than or equal to 3, and always odd), and currently selected number, all of which are both required and positive, print to STDOUT the resulting page selector.
## Examples
```
In: 5 5 1
Out: < [1] 2 3 4 5 >
In: 5 3 1
Out: < [1] ... 5 >
In: 7 5 3
Out: < 1 ... [3] ... 7 >
In: 11 7 4
Out: < 1 ... 3 [4] 5 ... 11 >
In: 11 7 7
Out: < 1 ... 6 [7] 8 ... 11 >
In: 11 9 7
Out: < 1 2 ... 6 [7] 8 ... 10 11 >
In: 7 3 3
Out: < ... [3] ... >
```
[Answer]
# Python3, 380 bytes:
```
lambda r,w,c:'< '+' '.join(map(str,Q([*R(1,c)],J:=(min((w-1)//2+(w-1)%2,c-1)),w+~J,len(V:=[*R(c+1,r+1)]))+[f'[{c}]']+W(V,w+~J)))+' >'
R,*E=range,'...'
W=lambda r,l:E if l<2and len(r)>1else(r if l==len(r)else r[:l-2]+E+[r[-1]])
Q=lambda r,l,L,V:r[:l-1]+E if L==1and V>1else(E if l<2and len(r)>1else(r if L-2or r==[]else r[:-1]+E)if l==len(r)else[r[0],*E,r[-1]]if L-2else r[:l-1]+E)
```
[Try it online!](https://tio.run/##fZA/b4MwEMV3PoWXynZ8kBqaUKE4W5aIJRnI4HqgBFoq/smJhKqq/erUkLQJqdTJfu/ufvfs5v34WlfeY6O7TDx1RVw@72OkoYUkwAuEGUbYeavzipRxQw5HDRsiJ1vCIaEK1oEgpamR1uZ0OnXZcLlzITEHhZZ9raFIKxIFoh9KGAfNOFWUMplh@ZF8KqzYjkRDKzU2RktsbWGyEjquXlLAjuNgayd@gxXBCuUZKhZuXO1RD9d0ydPikBI9FIQ4mb2FtAwK21VsxaSWNleKWpsrFoQQBUMPNz39eCgE78HRmfn/stB2a420EFL9rBtI9DaI2X6vzKvglOI0ekk4zHSNzqsjycgMZmC@z7pob6R9U/euNOfgw8Ot4Y@N@V9jPmJ6I6YB9rr7Bg)
Output:
```
< [1] 2 3 4 5 >
< [1] ... 5 >
< 1 ... [3] ... 7 >
< 1 2 3 [4] 5 ... 11 >
< 1 ... 6 [7] 8 ... 11 >
< 1 2 ... [7] ... 11 >
< 1 2 ... [6] ... 11 >
< ... [3] ... >
< 1 ... [3] ... >
```
] |
[Question]
[
In this challenge you will remove one of my least favorite features, operator precedence from traditional math notation, to acheive the syntax of one of my favorite languages, APL. The APL subset we will be working with includes only a few functions and single digit numbers. (No arrays!)
## Here is the grammar of the input
(in [pegjs](https://pegjs.org) notation, with `/` representing disjunction and `[]` representing a set of possible characters. If you would like to test it out and validate inputs/outputs you can go to <https://pegjs.org/online> and paste it in the grammar textbox)
```
Expr = Addition;
Addition = Multiplication [+-] Addition / Multiplication;
Multiplication = Power [*/] Multiplication / Power;
Power = Floor '^' Expr / Floor;
Floor = '[' Expr ']' / '{' Expr '}' / Paren;
Paren = '(' Expr ')' / Digit;
Digit = [0-9];
```
* In descending order of precedence, the infix operators are `^` (exponentiation), `*` or `/`, and `+` or `-`.
* All the operators are left-associative except for `^`. (`0-1-2` is `(0-1)-2` but `0^1^2` is `0^(1^2)`)
* There are no prefix operators.
## And the output format:
```
Expr = Multiplication / Addition / Power / Floor;
Multiplication = Floor [*/] Expr;
Addition = Floor [+-] Expr;
Power = Floor '^' Expr;
Floor = '[' Expr / '{' Expr / Paren;
Paren = '(' Expr ')' / [0-9];
```
* `{` and `[` are prefix and don't need a closing `]` or `}`.
* All operators, prefix *and* infix, have the same precedence.
* All operators are right-associative, so `0o1o2` is the same as `0o(1o2)` for any infix operator `o`.
* The infix operators are `+-*/^` (`^` is for exponentiation, and `*` and `/` are for multiplication and division respectively), and the prefix operators are `{` and `[`, which represent floor and ceiling respectively.
Note that these don't handle whitespace or negation and your program doesn't have to either.
## Task
You are to take an `Expr` in the input format, assumed to be valid, and output an equivalent expression (`Expr`) in the APL-like output format. In this case, equivalent means structurally, so `9` is not a valid output for the input of `3*3`. More specifically, the string that is outputted should have an `Expr` node where the input had an `Expr`, an `Addition` node where the input had `Addition`, etc. with the exception that in the output where an `Expr` node would be placed there may instead be a `Paren` node (this rule is recursive).
## Examples:
These are not necessarily the only answers. Any amount of parentheses are allowed in the output.
```
input output
1+1 1+1
2*2+1 (2*2)+1
3-5/2+1 (3-(5/2))+1
3-5/(2+1) 3-5/2+1
2*{2+1} 2*{2+1
5^4+1 (5^4)+1
{2+1}+1 ({2+1)+1
3^2^2 3^2^2
(3^2)^2 (3^2)^2
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code per language wins. Your function or program takes a string from arguments or stdin and outputs through return or stdout etc. etc.
[Answer]
# [Factor](https://factorcode.org/), 187 bytes
```
: c ( x -- y ) concat "("")"surround ;
EBNF: A [=[
p=p("*"|"/")e=>[[c]]|e
e=f"^"e=>[[c]]|f
f=("["|"{")s("]"|"}")=>[[2 head c]]|"("s")"=>[[c]]|[0-9]=>[[1string]]
s=s("+"|"-")p=>[[c]]|p
]=]
```
~~[Try it online!](https://tio.run/##RZBBTwIxFITv/RWTd2ohC7LKwTU10UQNFy7GU9NN1tIFI5balkQC/HbsLkFP8/XNTN5L28akTTi9vc7mLxW8XY7su2sR7ffWOmMjPm1wdg0fbEo7Hz5cQkxZlhF3bDavEE1oklmdKhhw/KAosIOA2TjTJBAnEhS3IWy2bpErT4/z5woPUFIxLz2nAR1oTMLKe6WM1gfLrGyppr9By1rJSeXYnkTkpDMdSXR2iZVtFuhSeVHMmy4ldVXc6u4xOV@rNYsyl4e5XJDwl5xnWurTHjQZTghUDsper4vp@J94RtG7@0xHYgBN65ve7yfnZF3WZVaeQXR0hEL6cmXj1xhBwzb5m34B "Factor – Try It Online")~~ Does not work on TIO, but works on 0.98 stable.
Defines a named function `A` which takes a string, parses it, and returns an equivalent expression string in the output format.
Test:
```
{ "1+1" "2*2+1" "3-5/2+1" "3-5/(2+1)" "2*{2+1}"
"5^4+1" "{2+1}+1" "3^2^2" "(3^2)^2" } [ A print ] each
```
Output:
```
(1+1)
((2*2)+1)
((3-(5/2))+1)
(3-(5/(((2+1)))))
(2*({(2+1)))
((5^4)+1)
(({(2+1))+1)
(3^(2^2))
((((3^2)))^2)
```
Since any number of parentheses are allowed, it is easiest to ignore the operator associativity of APL and parenthesize every single parsed node.
Factor comes with a PEG parser with EBNF syntax [`peg.ebnf`](https://docs.factorcode.org/content/article-peg.ebnf.html). The grammar nodes `s`, `p`, `e`, and `f` stand for "sum", "product", "exp", and "floor" respectively. The last line is recognized as the "main" grammar, so I moved `s` to the last line.
It does support character classes like `[+-]`, but it is converted to a single character (= integer), not a string, so it is more complicated to post-process. So I decided to simply use disjunction on string literals instead (except for digits).
`=> [[ Factor code ]]` defines how to post-process the grammar. For most of the nodes, it is simply "concatenate all parts and wrap in a pair of parens", which is defined as a named function `c` and reused throughout the code. For floor and ceiling, we only need to keep the opening `{[` and the body, thus `2 head c`.
] |
[Question]
[
[Gomoku](https://en.wikipedia.org/wiki/Gomoku) or *Five in a row* is a board game played by two players on a \$15 \times 15\$ grid with black and white stones. Whoever is able to place \$5\$ stones in a row (horizontal, vertical or diagonal) wins the game.
## Rules
In this KoTH we'll play the Swap2 rule, meaning that a game consists of two phases: In the initial phase the two players determine who goes first/who plays black, after that they'll place one stone each round starting with the player who picked black.
### Initial phase
Let the players be **A** & **B** and **A** shall open the game:
* **A** places two black and one white stone on the board
* **B** can choose one of the following three moves:
+ player **B** decides to play black: initial phase is over
+ player **B** decides to place a white stone and plays white: initial phase is over
+ player **B** decides to play one black and one white stone: **A** gets to pick the color
### Game phase
Each player places one stone of their colour on the board, starting with the player who plays black, this goes on until there are no more free spaces to play (in which case it's a tie) or one player manages to play \$5\$ stones in a row (in which case that player wins).
A row means either horizontal, vertical or diagonal. A win is a win - it doesn't matter whether the player managed to score more than one row.
## KoTH game rules
* each player plays against each other player twice:
+ initially it will be randomly decided who goes first
+ in the next game the player that got to play last goes first
* a win is worth 2 points, a tie 1 and a loss 0
* the goal is to score as many points as possible
## Your bot
To make this challenge accessible for as many languages as possible input/output will be via *stdin*/*stdout* (line-based). The judge program will prompt your program by printing a line to your bot's *stdin* and your bot will print one line to *stdout*.
Once you receive an `EXIT` message you'll be given half a second to finish writing to files before the judge will kill the process.
### Randomness
To make the tournaments verifiable the judge uses seeded randomization and your bot must do too, for the same reason. The bot will be given a seed via command-line argument which it should use, please refer to the next section.
### Arguments
The bot receives two command-line arguments:
1. opponent's name
2. seed for randomness
### User state
Because your program will always be started new for each game you'll need to use files to persist any information you want to keep. You are allowed to read/write any files or create/remove sub-folders in your current directory. You are not allowed to access any files in any parent-directory!
### Input/Output format
`BOARD` will denote a list of the current stones, it only lists the positions where a stone is placed and each entry will be of the form `((X,Y),COLOR)` where `X` and `Y` will be an integer in the range \$[0,15)\$ and `COLOR` will either be `"B"` (black) or `"W"` (white).
Furthermore `SP` denotes a single space, `XY` a tuple `(X,Y)` of two integers each in the range \$[0,15)\$ and `|` denotes a choice.
In the initial phase there are three different kinds of messages:
```
Prompt (judge) -> Answer (bot)
"A" SP "[]" -> XY XY XY
"B" SP BOARD -> "B" | "W" SP XY | XY XY
"C" SP BOARD -> "B" | "W"
```
* The first message asks for three tuples, the first two will be the positions of the black stones and the third one the position for the white one.
* The second message asks either for:
+ `"B"` -> pick black
+ `"W" SP XY` -> pick white and place a white stone at `XY`
+ `XY XY` -> place two stones (first one black and second one white)
* The last one just asks for which colour you want to play
---
After that the regular game will begin and the messages will become much simpler
```
N BOARD -> XY
```
where `N` is the number of the round (beginning with \$0\$) and `XY` will be the position where you place a stone.
---
There is one additional message which does not expect an answer
```
"EXIT" SP NAME | "EXIT TIE"
```
where `NAME` is the name of the bot that won. The second message will be sent if the game ends due to nobody winning and no more free spaces to place stones (this implies that your bot can't be named `TIE`).
**Formatting**
Since messages from the bot can be decoded without any spaces, all spaces will be ignored (eg. `(0 , 0) (0,12)` is treated the same as `(0,0)(0,12)`). Messages from the judge only contain a space to separate different sections (ie. as noted above with `SP`), allowing you to split the line on spaces.
Any invalid response will result in a loss of that round (you'll still receive an `EXIT` message), see rules.
**Example**
Here are some examples of actual messages:
```
A []
B [((0,0),"B"),((0,1),"W"),((14,14),"B")]
1 [((0,0),"B"),((0,1),"W"),((1,0),"B"),((1,1),"W"),((14,14),"B")]
```
## Judge
You can find the judge program [here](https://github.com/bforte/gomoku): To add a bot to it simply create a new folder in the `bots` folder, place your files there and add a file `meta` containing *name*, *command*, *arguments* and a flag *0/1* (disable/enable *stderr*) each on a separate line.
To run a tournament just run `./gomoku` and to debug a single bot run `./gomoku -d BOT`.
**Note:** You can find more information on how to setup and use the judge in the Github repository. There are also three example bots ([Haskell](https://github.com/bforte/gomoku/tree/master/examples/example-hs), [Python](https://github.com/bforte/gomoku/tree/master/examples/example-py) and [JavaScript](https://github.com/bforte/gomoku/tree/master/examples/example-js)).
## Rules
* on each change of a bot\* the tournament will be rerun and the player with the most points wins (tie-breaker is first submission)
* you may submit more than one bot as long as they don't play a common strategy
* you are not allowed to touch files outside of your directory (eg. manipulating other player's files)
* if your bot crashes or sends an invalid response, the current game is terminated and you lose that round
* while the judge (currently) does not enforce a time-limit per round, you are advised to keep the time spent low as it could become infeasible to test all the submissions\*\*
* abusing bugs in the judge program counts as loophole
\* You are encouraged to use Github to separately submit your bot directly in the `bots` directory (and potentially modify `util.sh`)!
\*\* In case it becomes a problem you'll be notified, I'd say anything below 500ms (that's a lot!) should be fine for now.
## Chat
If you have questions or want to talk about this KoTH, feel free to join the [Chat](https://chat.stackexchange.com/rooms/82317/gomoku-koth)!
[Answer]
## KaitoBot
It uses a very crude implementation of MiniMax principles. The depth of the search is also very low, because otherwise it takes way too long.
Might edit to improve later.
It also tries to play Black if possible, because Wikipedia seems to say that Black has an advantage.
I have never played Gomoku myself, so I set up the first three stones randomly for lack of a better idea.
```
const readline = require('readline');
const readLine = readline.createInterface({ input: process.stdin });
var debug = true;
var myColor = '';
var opponentColor = '';
var board = [];
var seed = parseInt(process.argv[3]);
function random(min, max) {
changeSeed();
var x = Math.sin(seed) * 10000;
var decimal = x - Math.floor(x);
var chosen = Math.floor(min + (decimal * (max - min)));
return chosen;
}
function changeSeed() {
var x = Math.sin(seed++) * 10000;
var decimal = x - Math.floor(x);
seed = Math.floor(100 + (decimal * 9000000));
}
function KaitoBot(ln) {
var ws = ln.split(' ');
if (ws[0] === 'A') {
// Let's play randomly, we don't care.
var nums = [];
nums[0] = [ random(0, 15), random(0, 15) ];
nums[1] = [ random(0, 15), random(0, 15) ];
nums[2] = [ random(0, 15), random(0, 15) ];
while (nums[1][0] == nums[0][0] && nums[1][1] == nums[0][1])
{
nums[1] = [ random(0, 15), random(0, 15) ];
}
while ((nums[2][0] == nums[0][0] && nums[2][1] == nums[0][1]) || (nums[2][0] == nums[1][0] && nums[2][1] == nums[1][1]))
{
nums[2] = [ random(0, 15), random(0, 15) ];
}
console.log('(' + nums[0][0] + ',' + nums[0][1] + ') (' + nums[1][0] + ',' + nums[1][1] + ') (' + nums[2][0] + ',' + nums[2][1] + ')');
}
else if (ws[0] === 'B') {
// we're second to play, let's just pick black
myColor = 'B';
opponentColor = 'W';
console.log('B');
}
else if (ws[0] === 'C') {
// the other player chose to play 2 stones more, we need to pick..
// I would prefer playing Black
myColor = 'B';
opponentColor = 'W';
console.log('B');
}
else if (ws[0] === 'EXIT') {
process.exit();
}
else {
board = [];
var json = JSON.parse(ws[1].replace(/\(\(/g,'{"xy":[')
.replace(/"\)/g,'"}')
.replace(/\),/g,'],"colour":'));
// loop over all XYs and make a board object I can use
for (var x = 0; x < 15; x++) {
var newRow = []
for (var y = 0; y < 15; y++) {
var contains = false;
json.forEach(j => {
if (j.xy[0] == x && j.xy[1] == y) {
contains = true;
newRow[newRow.length] = j.colour;
}
});
if (!contains) {
newRow[newRow.length] = ' ';
}
}
board[board.length] = newRow;
}
// If we never picked Black, I assume we're White
if (myColor == '') {
myColor = 'W';
opponentColor = 'B';
}
var bestMoves = ChooseMove(board, myColor, opponentColor);
var chosenMove = bestMoves[random(0, bestMoves.length)];
console.log('(' + chosenMove.X + ',' + chosenMove.Y + ')');
}
}
function IsSquareRelevant(board, x, y) {
return (board[x][y] == ' ' &&
((x > 0 && board[x - 1][y] != ' ')
|| (x < 14 && board[x + 1][y] != ' ')
|| (y > 0 && board[x][y - 1] != ' ')
|| (y < 14 && board[x][y + 1] != ' ')
|| (x > 0 && y > 0 && board[x - 1][y - 1] != ' ')
|| (x < 14 && y < 14 && board[x + 1][y + 1] != ' ')
|| (y > 0 && x < 14 && board[x + 1][y - 1] != ' ')
|| (y < 14 && x > 0 && board[x - 1][y + 1] != ' ')));
}
function ChooseMove(board, colorMe, colorOpponent) {
var possibleMoves = [];
for (var x = 0; x < 15; x++) {
for (var y = 0; y < 15; y++) {
if (IsSquareRelevant(board, x, y)) {
possibleMoves[possibleMoves.length] = {X:x, Y:y};
}
}
}
var bestValue = -9999;
var bestMoves = [possibleMoves[0]];
for (var k in possibleMoves) {
var changedBoard = JSON.parse(JSON.stringify(board));
changedBoard[possibleMoves[k].X][possibleMoves[k].Y] = colorMe;
var value = analyseBoard(changedBoard, colorMe, colorOpponent, colorOpponent, 2);
if (value > bestValue) {
bestValue = value;
bestMoves = [possibleMoves[k]];
} else if (value == bestValue) {
bestMoves[bestMoves.length] = possibleMoves[k];
}
}
return bestMoves;
}
function analyseBoard(board, color, opponent, nextToPlay, depth) {
var tBoard = board[0].map((x,i) => board.map(x => x[i]));
var score = 0.0;
for (var x = 0; x < board.length; x++) {
var inARow = 0;
var tInARow = 0;
var opponentInARow = 0;
var tOpponentInARow = 0;
var inADiago1 = 0;
var opponentInADiago1 = 0;
var inADiago2 = 0;
var opponentInADiago2 = 0;
for (var y = 0; y < board.length; y++) {
if (board[x][y] == color) {
inARow++;
score += Math.pow(2, inARow);
} else {
inARow = 0;
}
if (board[x][y] == opponent) {
opponentInARow++;
score -= Math.pow(2, opponentInARow);
} else {
opponentInARow = 0;
}
if (tBoard[x][y] == color) {
tInARow++;
score += Math.pow(2, tInARow);
} else {
tInARow = 0;
}
if (tBoard[x][y] == opponent) {
tOpponentInARow++;
score -= Math.pow(2, tOpponentInARow);
} else {
tOpponentInARow = 0;
}
var xy = (y + x) % 15;
var xy2 = (x - y + 15) % 15;
if (xy == 0) {
inADiago1 = 0;
opponentInADiago1 = 0;
}
if (xy2 == 0) {
inADiago2 = 0;
opponentInADiago2 = 0;
}
if (board[xy][y] == color) {
inADiago1++;
score += Math.pow(2, inADiago1);
} else {
inADiago1 = 0;
}
if (board[xy][y] == opponent) {
opponentInADiago1++;
score -= Math.pow(2, opponentInADiago1);
} else {
opponentInADiago1 = 0;
}
if (board[xy2][y] == color) {
inADiago2++;
score += Math.pow(2, inADiago2);
} else {
inADiago2 = 0;
}
if (board[xy2][y] == opponent) {
opponentInADiago2++;
score -= Math.pow(2, opponentInADiago2);
} else {
opponentInADiago2 = 0;
}
if (inARow == 5 || tInARow == 5) {
return 999999999.0;
} else if (opponentInARow == 5 || tOpponentInARow == 5) {
return -99999999.0;
}
if (inADiago1 == 5 || inADiago2 == 5) {
return 999999999.0;
} else if (opponentInADiago1 == 5 || opponentInADiago2 == 5) {
return -99999999.0;
}
}
}
if (depth > 0) {
var bestMoveValue = 999999999;
var nextNextToPlay = color;
if (nextToPlay == color) {
nextNextToPlay = opponent;
bestMoveValue = -999999999;
}
for (var x = 0; x < board.length; x++) {
for (var y = 0; y < board.length; y++) {
if (IsSquareRelevant(board, x, y)) {
var changedBoard = JSON.parse(JSON.stringify(board));
changedBoard[x][y] = nextToPlay;
var NextMoveValue = (analyseBoard(changedBoard, color, opponent, nextNextToPlay, depth - 1) * 0.1);
if (nextToPlay == color) {
if (NextMoveValue > bestMoveValue) {
bestMoveValue = NextMoveValue;
}
} else {
if (NextMoveValue < bestMoveValue) {
bestMoveValue = NextMoveValue;
}
}
}
}
}
score += bestMoveValue * 0.1;
}
return score;
}
readLine.on('line', (ln) => {
KaitoBot(ln);
});
```
EDITS: Made the seed change dynamically because otherwise when seeds exceeded 2^52 javascript couldn't handle the increment correctly
] |
[Question]
[
Given two line segments, determine if the line segments intersect and if so, where. In the case that the two given line segments are co-linear and overlap, determine the midpoint of the overlapping segment. Lines will be specified in pairs of (x, y) coordinates.
# Examples
* [(-1, -1), (1, 1)], [(-1, 1), (1, -1)] => (0, 0)
* [(-1, -1), (1, -1)], [(-1, 1), (1, 1)] => No intersection
* [(-2, 0), (1, 1.32)], [(-1, 0.44), (2, 1.76)] => (0, 0.88)
* [(-2, -2), (0, 0)], [(1, -1), (1, 1)] => No intersection
# Rules
* Standard rules and loopholes apply
* Input and output may be in any convenient format. Please state your convention along with your solution.
+ Examples for output conventions would be `null` for no intersection and a point for an intersection; a boolean and a tuple; string output in (x, y) format or "no intersection"; x and y will be `NaN` for no intersection. Other conventions are allowed, but these may give you a good starting point.
* A minimum of 2 decimal places (or equivalent) precision is required.
* Final results should be accurate to within 0.01 when at a scale of -100 - +100. (32-bit floats will be more than accurate enough for this purpose)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins.
---
Related: This is not a duplicate of [2D Collision Detection](https://codegolf.stackexchange.com/questions/38614/2d-collision-detection) because it only concerns line-line tests and requires an intersection point for intersecting line segments. This is also not a duplicate of [Intersection of Two Lines](https://codegolf.stackexchange.com/questions/2057/intersection-of-two-lines) because this concerns line *segments* specified with two endpoints rather than functions.
[Answer]
# [R](https://www.r-project.org/), 95 bytes
```
function(m,a=c(1,3),r=range){plot(0,,"n",r(m[a,]),r(m[-a,]));segments(m[1,],m[2,],m[3,],m[4,])}
```
[Try it online!](https://tio.run/##bY7NboQgGEX38xRmZgPJxfiXdjHhSYwLij8xUWxE3TTz7BZwakfGBD7gcj4443preD0rObWDIjMWCC5JjJRi5KNQTYWSl0MoRddBc101faUmTX@@u2EiEXBVV4xEkjkXBRZTKH2emQuYTei9JBrztiz0can5un/av33pv97nAgV1G2Z39P7nYZIYBfo8cTV1NTPIY62J/GpVaVRYjMBOOyiCLdgGi43c5RRlPuujCYJouwjTZGejMMsQJDb9/HjveHZFjn/1MuStIV2rJ993z/6Vz1B2wh5Q33dnPeVDx4uvyw7K6y8 "R – Try It Online")
Here's a [graphical solution](https://i.stack.imgur.com/9kiCF.jpg) as an appetizer while I'm working on a full-blown solution.
TIO link will not plot anything.
[](https://i.stack.imgur.com/WN02x.png)
[Answer]
# [C (gcc -lm)](https://gcc.gnu.org/), 225 bytes
```
#define T 20000
#define N double
N sqrt(N);N D(a,b){N x=a%T-b%T,y=a/T-b/T;return sqrt(x*x+y*y);}F,L,P;f(a,b,c,d){F=L=-1;for(P=0;++P<T*T;L=(D(a,P)+D(P,b)-D(a,b)<0.001&&D(c,P)+D(P,d)-D(c,d)<0.001)?(F=(F<0?P:F)),P:L);a=(F+L)/2;}
```
[Try it online!](https://tio.run/##jVJLb6MwEL7zK0atqOxgwNBsu6phe4lyQogDt92oIjxSSxS6hFRBUf76srYJJI16qMEwj@@b8cw4NTdp2t/yKi13WQ7ets14bb3@ArBtKOoG3htetYX2CVHytYScEElbF/1tlhe8yiEGl4qljXoIWb1bl7kWwvZv06IQsxAWKCFrfAhh7yd6bK71mHR@YgvJjlmTt7umGtD72d7oZh1mxyUJSMQKSSQpyfBh6Qe@6TBxABT5lBlG5MWzmAU@ktEjbCxQJJKYQy6PWpQ6d3cLlI6@TPpkqMGHn9HSR0uPPkdPS4xJ9BRglgiLEWDbZcf@o@aZ6Ebett2LagoSG95r8cVw0EAsadiDPxj1GExwZDPY5OxGp33hVN6hzegG6QXRC/ynuiGwtwXCogS6QcBMO2qajNPWLyoMKso6ETkJDEI3nuTURHlEjEQbB76hMloUDECouzLimZrcOclbwitVY9JsUgLpa9LATMgfv1eXBfNTBfIqIC4KdBhw8BRLSoYPP0f8UOlFCws0lSKvEVLh@QqTC81wVmIeE1@tr1iGe8W7/yZvfsX78U3ewxXvUfAwHqZ91C7nIKZ87HvTka98zj/T7amUrXtXqtSaz3tXqI8PE/xMU3DFoFOQf2lRJpttb5Zv/wE "C (gcc) – Try It Online")
Very slow. Input format is endpoints packed into ints as coordinate multiplied
by 100 (to an integer) and 10000 added to it (to a natural). Y coordinate is
multiplied by an additional 20000 to pack it next to X coordinate. No collision
is signaled by the point (-100.01,-100).
Thus the X coordinate of a point A is `((A%20000)-10000)/100.0` and the Y
coordinate is `((A/20000)-10000)/100.0`.
## Rationale
Thanks to the question providing no time limit and specifying a desired
precision accurately, a non-optimal solution can be used to reduce code size.
Thus instead of actually computing the collision points, then doing some
additional logic if the lines are coincident, this checks every single point of
the given precision and sees if it is a collision.
This collision check is much shorter (code-wise) than the collision computation.
In particular to check if a point collides with a line segment just check if the
distance to each endpoint adds up to the length of the segment. If a point
collides with both line segments individually, then it is a point where the line
segments intersect.
Using this strategy the code finds the endpoints of the collision and returns
their midpoint. Initially they are set to -1, so if there is no collision it
returns -1 (-1+-1/2) which when translated back is a number just out of range.
If there's only one collision point, it is stored in both endpoints, so it is
itself returned (x+x/2). Finally, if there is an overlap the overlap must be a
line, returning the average of the line's endpoints will yield the midpoint.
## Algorithm
As such, the algorithm in pseudo-code would be:
```
collision (AB,CD):
start and end = -1
for each point P:
if P is in both line segments AB and CD
if start = -1, start = P
end = P
return (start+end)/2
is P in line segment AB:
return distance(A,P) + distance(P,B) = distance(A,B)
```
## Description
The annotated source is thus:
```
#define T 20000 // We use 20000 a lot
#define N double // We use double a lot
N sqrt(N); // We need to prototype sqrt or it will be assumed to be int(int)
N D(a,b){ // D defines the distance function
N x=a%T-b%T, // x is delta x
y=a/T-b/T; // y is delta y
return sqrt(x*x+y*y);} // standard distance formula: sqrt(dx^2+dy^2)
F, // F is the first point of collision
L, // L is the last point of collision
P; // P is the current test point
f(a,b,c,d){ // f takes the 4 segment end-points
F=L=-1; // Initialize both collision points to -1 (invalid)
for(P=0;++P<T*T; // Loop P over each point
L= // Set the last collision point based on a ternary
(D(a,P)+D(P,b)-D(a,b) // We have to use an epsilon check due to floating point rounding errors
<0.001 // This accuracy is definitionally good enough
&& // The previous check was for collision with AB
D(c,P)+D(P,d)-D(c,d) // now we have to check for collision with CD
<0.001)? // if both collide - we have a collision point!
(F=(F<0?P:F)), // if the first collision point isn't set, this is it
P // set the last collision point no matter what
: // they don't both collide, ignore this point
L); // the expression is assigned to L, so keep L the same
a= // return by assigning to the first argument
(F+L)/2;} // the average of the first and last points
// Luckily the packing of the points fits with enough space so we
// don't have to worry about averaging each coordinate separately
```
] |
[Question]
[
# Introduction
I have some ASCII cars that have velocity and direction. Their velocity is represented by their number. If a car is `<>` then it has stopped. For example:
```
<>
1>
2>
3>
```
After one second, I get
```
<>
1>
2>
3>
```
After two, I get
```
<>
1>
2>
3>
```
If two cars are too close, they crash.
```
1> <1
1> <2
```
After a second, this becomes
```
###
##
```
If two cars intersect, they become hashtags were they would be.
If one car is fast enough to 'hop' over the other, it does not result in a crash.
```
3><1 2><1 4><>
```
becomes
```
<13> ### <>4>
```
If a car goes left off-screen, it disappears (unless there's a crash). There is no way for a car to go right off-screen.
```
<11>
<1 1>
1 1>
1>
```
# Challenge
Based on the given car physics, you must create a program that can time-step one second into the future. The input will be cars with spaces and a maximum velocity of 5 (matching regex `(<[1-5]|[1-5]>|<>| )+`). The simulation will happen on one line, however that line has no fixed size.
# Test cases
```
<> 1> 2> 3> 4> 5>
<> 1> 2> 3> 4> 5>
1><1 1> <1 1> <1
## ### 1><1
2><2 2> <2 2> <2 2> <2 2> <2
<22> ### ## ### 2><2
<22> <1 3> <2
### ##
<><> 1><> 2><> 3><> 4><> 5><>
<><> ### ## ### <>4> <> 5>
<><1 <2 <3 <4 <5
###<2<3<4<5
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so code with the smallest number of bytes wins!
[Answer]
# JavaScript (ES6), 140 bytes
```
s=>[...s.replace(/\S./g,([a,b],i)=>r[r[i+=+b?-b:~~a]=r[i]?C:a,++i]=r[i]?C:b,r=[],C='#')&&r].map((c,i)=>c?r[i-1]==C|r[i+1]==C?C:c:' ').join``
```
[Try it online!](https://tio.run/##dY7BaoQwEIbvfYqwhTXBmCVRL5KMBx@hRxvYmLqLizUSS09lX91GqW0p9jTfMN/8/Dfzbibru/EtGdxLO1/UPCmoGWMT8@3YG9vi0/MTO10prg1tNO2IAl/7uotV3JRJU9zvRquw67IqDI3j7ntrqFe1ppWKHiNyPHrNXs2IsV0zbBmshGulqo8lbaXwZIsIRYTdXDecz7N1w@T6lvXuii/4IAFxQAJQCigDlMOBkIc/DgfJEVq8bQbY8QRIEe4hbJs/8IsC7jxLsfp8KfKfAnL9Dw2@QGyQbpBtkAfYz@BLF5kimSGZB2X@BA "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // given the input string s
[ ...s.replace( // search in s ...
/\S./g, // ... all substrings consisting of 2 non-whitespace characters
([a, b], i) => // let a be the 1st character, b the 2nd one and i the position
r[ // update r[]:
r[i += // apply the car velocity to i:
+b ? -b // if b is a digit, then move b cells backwards
: ~~a // else: use a to move forwards (or don't move at all)
] = r[i] ? C : a, // if r[i] is set, overwrite it with '#'; otherwise, insert a
++i // increment i for the 2nd character
] = r[i] ? C : b, // if r[i] is set, overwrite it with '#'; otherwise, insert b
r = [], // initialize r[] to an empty array
C = '#' // define C as the 'crash' character
) && r ] // end of replace(); return a fully iterable copy of r[]
.map((c, i) => // for each entry c at position i in this array:
c ? // if c is defined:
r[i - 1] == C | // if either the previous
r[i + 1] == C ? // or the next cell is '#' (in the original array):
C // replace the current cell with '#'
: // else:
c // let c unchanged
: // else:
' ' // insert a space
).join`` // end of map(); join the result
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 259 bytes
254 to 259 because i added test case which wasnt in the testcases that complicated my result regex finder
```
s=>{
c=[]
n=[S=""]
s.replace(/<?\d>?|<>/g,([d,D],i)=>d>0?g(i+ +d,d)+g(i-~d,D):g(i-~~D,d)+g(i-~~D+1,D))
for(i of n)S+=i||" "
return S.replace(/1?[2-9]*1?/g,(d,i)=>d>"1".repeat(l=d.length)?"#".repeat(l):c.slice(i,i+l).join``)}
g=(x,p)=>x<0||(n[x]=-~n[x],c[x]=p)
```
[Try it online!](https://tio.run/##bZDLboMwEEX3fIVlNnZ5JDyyaGSbTf4gS4qUiFcdIYOAVpFK@XVqO7iJmrKZ4zu@dwZfzp/nIe95N3qiLcqlostA2ZeV0zSzBE2PFMLMGvy@7JpzXqINSd4KlkyEbWoXpYV7yFyOKSvYNqkRd4BTuAV2JHqzbOK9pvnwK84HJ5A6tqq2Rxy0FRD46FA@TRBAqy/Hj16A431ekKSh95q9BIkaWKzDYADVlfI8ooYWflOKenzHCbTvMt7n/tBwmcFd7jTYv7RcnE7426opurqdzLmS7TQhkV4z6s2quLniDi95K4a2Kf2mrVGFIGEgYCBkIGIgZmDHIKZUqUpWumqojm5ZT24SABICEgESA7LTZtu2SUgiEqvzX0egHDrcVAnaBmwbqM9eq7r57JcryXl6M1Pv8EASb6kkvJ1NrBnzoOjMf3@OmU2YuXeDyEBsYCdhfbpVech/HklYzFbQD7v8AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 178 bytes
```
^\d([^>])
$1
T`5-1`d`<.
*(<(\d)|((\d)>|<>))
$2* $#3*5* $4* $.`* $&¶
T`d`5-1`<.
m`^.{0,5}
G`.
N^$`
$.&
{+m`\A( *) (.*)¶\1(..?)$
$1$3$2
m`^\A( *)( *)..(.*)¶\1(..?)$
$1##$.2*#$3
```
[Try it online!](https://tio.run/##ZYyxTgMxDIZ3P4WlM1USwCLJZbOMmLoxsXGcUukYGMqA2Fpeqw/QFzucKyeQGGx/tv///3j9fHvfxfnKbes8DpN7HvXFA1KEp1puY52qMGBw4obJH13rehT1HigFpC6HYqO34mptcz6ZcVqsZtzXkQ93N@ULYFsZHkeqQLyBw/W@Dg8Og0d0HPz5NETHfO8JKFKm1JwXQSvmf6KuI06hozzPohgVk2JW7BWLQlSJiO26TgNIKsk2E67zF/6QIUhavrFFXg4qy8@yfiCtkFfoVygGzRFbqmSUHqV8Aw "Retina – Try It Online") Link includes test cases. Explanation:
```
^\d([^>])
$1
```
Handle the case of a car moving off the left.
```
T`5-1`d`<.
```
Temporarily complement the digits of cars moving to the left.
```
*(<(\d)|((\d)>|<>))
$2* $#3*5* $4* $.`* $&¶
```
Put each car on its own line (`$.`* $&¶`) and add some indent depending on the speed of the car; left-moving cars get the complemented speed, while non-moving cars get 5 more than the speed.
```
T`d`5-1`<.
```
Uncomplement the left-moving car digits.
```
m`^.{0,5}
```
Move all of the cars 5 to the left. This fixes the indent for all cars.
```
G`.
```
Delete all cars that have moved off the left.
```
N^$`
$.&
```
Sort the remaining cars in reverse horizontal order.
```
{
```
Repeat the remaining stages until all the cars have been processed.
```
+m`\A( *) (.*)¶\1(..?)$
$1$3$2
```
As long as the next car does not crash, add it to the result.
```
m`^\A( *)( *)..(.*)¶\1(..?)$
$1##$.2*#$3
```
Add a crashing car to the result.
] |
[Question]
[
This challenge is inspired by [this app](https://play.google.com/store/apps/details?id=com.andreasabbatini.logicgamestk).
---
This is a much easier version of [this challenge](https://codegolf.stackexchange.com/q/128017/31516). This challenge is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), while the other one is [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'").
---
You'll be given a square input grid, of dimensions **6-by-6** which is divided into **6** areas, where the cells of each area have a unique identifier (I'll use lower case letters from **a-f** in the the text here, but you may choose whatever you like, for instance integers **1-6**).
The input may look like this (optional input format):
```
aabbbb
aabbbb
aaccbb
acccdb
ecccdb
eeefff
```
Or, easier to visualize:
[](https://i.stack.imgur.com/zkrxsm.jpg)
## Challenge:
You are to place **6** trees in this park, according to the following rules:
* There shall be exactly **1** tree per column, and **1** tree per row
* All areas shall have exactly **1** tree.
* No trees can be adjacent to another tree, vertically, horizontally or diagonally
The solution to the layout above is:
[](https://i.stack.imgur.com/dTrpRm.jpg)
Note: There is only one solution to each puzzle
### Additional rules:
* The input and output formats are optional
+ The output might for instance be a list of indices, a grid with **1/0** indicating if there's a tree in that position, or a modified version of the input where the trees are indicated
* The execution time must be deterministic
* The program must finish within 1 minute on a reasonable modern laptop
* Brownie points if you don't brute force!
### Test cases:
```
aabbbb
aabbbb
aaccbb
acccdb
ecccdb
eeefff
---
aAbbbb
aabbbB
aaCcbb
acccDb
Ecccdb
eeeFff
----------
aabccc
aacccc
aaddce
aeeeee
aeeefe
eeeeee
---
aaBccc
aacccC
aadDce
Aeeeee
aeeeFe
eEeeee
----------
aaaabb
aacbbb
aadddb
addeef
ddddee
dddeee
---
aaaaBb
aaCbbb
Aadddb
addeeF
dDddee
dddEee
----------
abbbcd
abebcd
addddd
dddddd
effdff
eeffff
---
abBbcd
abebCd
Addddd
dddDdd
effdfF
eEffff
```
Same test cases on a format that's a bit easier to parse:
```
Test case 1:
[1,1,2,2,2,2;1,1,2,2,2,2;1,1,3,3,2,2;1,3,3,3,4,2;5,3,3,3,4,2;5,5,5,6,6,6]
Test case 2:
[1,1,2,3,3,3;1,1,3,3,3,3;1,1,4,4,3,5;1,5,5,5,5,5;1,5,5,5,6,5;5,5,5,5,5,5]
Test case 3:
[1,1,1,1,2,2;1,1,3,2,2,2;1,1,4,4,4,2;1,4,4,5,5,6;4,4,4,4,5,5;4,4,4,5,5,5]
Test case 4:
[1,2,2,2,3,4;1,2,5,2,3,4;1,4,4,4,4,4;4,4,4,4,4,4;5,6,6,4,6,6;5,5,6,6,6,6]
```
[Answer]
# C, ~~223~~ 182 bytes
```
O[15],U;main(y,v)char**v;{if(y>7)for(;y-->2;printf("%06o\n",O[y]));else for(int*r,x=1,X=8;X<14;U&x|*r|O[10-y]*9&x*9?0:(U^=O[9-y]=*r=x,*r=main(y+1,v),U^=x),x*=8)r=O+v[1][y*7-++X]-88;}
```
Takes input as an argument in the format given in the question. Writes output to stdout as a grid of 0s with 1s where the trees go.
```
./TreesMin 'aabbbb
aabbbb
aaccbb
acccdb
ecccdb
eeefff'
```
Sample output:
```
010000
000001
001000
000010
100000
000100
```
## Breakdown
```
O[15], // Tree positions & region usage
U; // Column usage (bitmask)
main(y,v)char**v;{ // Recursive main function
if(y>7) // Finished grid?
for(;y-->2;printf("%06o\n",O[y])); // Print it (rows are padded octal)
else // Not finished:
for(int*r,x=1,X=8;X<14; // Loop over columns
U&x|*r|O[10-y]*9&x*9 // Current cell violates rules?
?0 // Do nothing
:(U^=O[9-y]=*r=x, // Else: mark cell
*r=main(y+1,v), // Recurse
U^=x) // Unmark cell
,x*=8) // Advance to next column
r=O+v[1][y*7-++X]-88; // Region pointer for current iteration
}
```
It's an adaptation of [my answer to the fastest-code version of this question](https://codegolf.stackexchange.com/a/128175/8927). Doesn't have as much short-circuiting, but it's plenty fast enough for 6x6 grids.
[Answer]
# [Clingo](http://potassco.sourceforge.net/), 66 bytes
```
1{t(X,Y):c(X,Y,Z)}:-Z=1..n.:-t(X,Y),2{t(X,J;I,Y;X-1..X+1,Y..Y+1)}.
```
Run with `clingo plant.lp - -c n=<n>` where `<n>` is the grid size. The input format is a list of `c(X,Y,Z).` statements for each cell (`X`, `Y`) colored `Z`, with 1 ≤ `X`, `Y`, `Z` ≤ `n`, separated by optional whitespace. The output includes `t(X,Y)` for each tree at (`X`, `Y`).
### Demo
```
$ clingo plant.lp - -c n=6 <<EOF
> c(1,1,1). c(2,1,1). c(3,1,2). c(4,1,2). c(5,1,2). c(6,1,2).
> c(1,2,1). c(2,2,1). c(3,2,2). c(4,2,2). c(5,2,2). c(6,2,2).
> c(1,3,1). c(2,3,1). c(3,3,3). c(4,3,3). c(5,3,2). c(6,3,2).
> c(1,4,1). c(2,4,3). c(3,4,3). c(4,4,3). c(5,4,4). c(6,4,2).
> c(1,5,5). c(2,5,3). c(3,5,3). c(4,5,3). c(5,5,4). c(6,5,2).
> c(1,6,5). c(2,6,5). c(3,6,5). c(4,6,6). c(5,6,6). c(6,6,6).
> EOF
clingo version 5.1.0
Reading from plant.lp ...
Solving...
Answer: 1
c(1,1,1) c(2,1,1) c(3,1,2) c(4,1,2) c(5,1,2) c(6,1,2) c(1,2,1) c(2,2,1) c(3,2,2) c(4,2,2) c(5,2,2) c(6,2,2) c(1,3,1) c(2,3,1) c(3,3,3) c(4,3,3) c(5,3,2) c(6,3,2) c(1,4,1) c(2,4,3) c(3,4,3) c(4,4,3) c(5,4,4) c(6,4,2) c(1,5,5) c(2,5,3) c(3,5,3) c(4,5,3) c(5,5,4) c(6,5,2) c(1,6,5) c(2,6,5) c(3,6,5) c(4,6,6) c(5,6,6) c(6,6,6) t(1,5) t(2,1) t(6,2) t(3,3) t(5,4) t(4,6)
SATISFIABLE
Models : 1+
Calls : 1
Time : 0.045s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time : 0.000s
```
To make the input/output format easier to deal with, here are Python programs to convert from and to the format given in the challenge.
### Input
```
import sys
print(' '.join("c({},{},{}).".format(x + 1, y + 1, ord(cell) - ord('a') + 1) for y, row in enumerate(sys.stdin.read().splitlines()) for x, cell in enumerate(row)))
```
### Output
```
import re
import sys
for line in sys.stdin:
c = {(int(x), int(y)): int(z) for x, y, z in re.findall(r'\bc\((\d+),(\d+),(\d+)\)', line)}
if c:
t = {(int(x), int(y)) for x, y in re.findall(r'\bt\((\d+),(\d+)\)', line)}
n, n = max(c)
for y in range(1, n + 1):
print(''.join(chr(ord('aA'[(x, y) in t]) + c[x, y] - 1) for x in range(1, n + 1)))
print()
```
] |
[Question]
[
# PPCG hasn't had enough of quines already...
### Challenge:
Your task is to create a program "A0". When this program is run with no input, it outputs nothing. When this program is run with input, it outputs "A1". When "A1" is run with no input, it outputs "A0". When "A1" is run with input, it outputs "A2". Pretty much, "A(k)" will output "A(k-1)" when run with no input, and will output "A(k+1)" when run with input.
### Details
I believe this challenge is simple enough; there are no other rules really. Every program must contain at least 1 byte, by the way. You may assume that the input will consist of only ASCII characters, and you may ignore whitespace if you want, but you may not specify a specific input. Output may be to either STDOUT or STDERR, but all of your programs must output to the same one. The other one may also contain text (so you may output to STDOUT and then exit with an error). Thanks to @Dennis for pointing that out.
All programs must be in the same language, and each program must be unique from the rest of them.
The score is equal to the length of program "A0". As this is a code-golf challenge, the lowest score wins!
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 28 bytes
```
V Y"I#qSti0+i?`V Y`.RPyRtiu"
```
[Try it online!](https://tio.run/nexus/pip#@x@mEKnkqVwYXJJpoJ1pnwDkJugFBVQGlWSWKv3/n5efl5pbUFIJAA "Pip – TIO Nexus")
### Explanation
This is a modified version of the shortest known Pip quine `V Y"`V Y`.RPy"`. That quine works by defining a string, yanking it into the `y` variable, and then evaluating it. When evaluated, the string takes the repr of `y` (thus wrapping the value of `y` in double quotes) and concatenates the pattern literal ``V Y`` to the front of it.
Our strategy is to put a `0` in the program, then replace `0` with `10` if there was input, or replace `10` with `0` if there was no input. (Thus, A(*k*) will contain a number consisting of *k* 1's followed by a 0.) `0` and `10` are convenient because there are built-in variables (`i` and `t`, respectively) with those values, so we can refer to them without using actual digits.
So instead of `RPy`, we want `RP yRit` if there was input and `RP yRti` if not. We can combine the two cases by swapping the values of `t` and `i` if there is input (`I#q Sti`), then doing `RP yRti`. (We have to test `#q`, the *length* of the input, because inputs like `0` are falsey.)
Now we just have to get a literal `0` in the code and handle the special case of A0 producing no output. Both can be solved by testing `0+i` and returning `u` if it is falsey:
* For any *k* > 0, the number in A(*k*) will be nonzero and therefore truthy (e.g. `110+i`).
* For *k* = 0, the number in A(*k*) will be zero:
+ If there is input, `i` and `t` are swapped and `i` is 10. `0+i` is still truthy.
+ If there is no input, `i` is still 0 and `0+i` is falsey. Instead of the quine core, we output `u`, which is a built-in variable for nil. Printing nil produces no output.
[Answer]
# Python 2, 93 bytes
There is a trailing linefeed.
```
p=1+2*bool(input())-1;s='print"p=%r+2*bool(input())-1;s=%r*(p>0);exec s"%(p,s)'*(p>0);exec s
```
[**Try it with input**](https://tio.run/nexus/python2#@19ga6htpJWUn5@jkZlXUFqioampa2hdbKteUJSZV6JUYKtahFVetUhLo8DOQNM6tSI1WaFYSVWjQKdYUx1FkOv/f6VEJQA) | [**Try it without input**](https://tio.run/nexus/python2#@19ga6RtpJWUn5@jkZlXUFqioampa2hdbKteUJSZV6JUYKtahFVetUhLo8DOQNM6tSI1WaFYSVWjQKdYUx1FkOv/fyUlAA)
This is modified from [my answer](https://codegolf.stackexchange.com/a/110445/34718) on a similar question.
If there is input, then it will increment `p`. So the resulting program will be `p=2+...`, `p=3+...`, etc.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 21 bytes
```
1`I$u?[N]+p`I$u?[N]+p
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxYEkkdT9bTl0rcGBJJHU/W05dK3AiLCIiLCJbXCJhXCIsXCJiXCJdIl0=)
The number on front is `k`.
```
1 # Push 1 (or k)
`I$u?[N]+p` # Push a string containing part of the program code
I # Quinify, unevaling and appending
$ # Swap with k
u?[N] # Push 1 if input, else -1
+ # Add
p # Prepend to the string
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 67 bytes
```
(f=(a)->(a+=(-1)^!readstr("/dev/stdin"))&&print("(f="f")("a")"))(1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN5010mw1EjV17TQStW01dA014xSLUhNTikuKNJT0U1LL9ItLUjLzlDQ11dQKijLzSjSUgBqU0pQ0NZQSlTSB4hqGmhCjoCYuWGgIYQAA)
PARI/GP doesn't have a built-in to read a string from stdin. The shortest workaround I can find is `readstr("/dev/stdin")`, which only works on unix-like systems.
] |
[Question]
[
Your task will be to take a [balanced-string](/questions/tagged/balanced-string "show questions tagged 'balanced-string'") and a integer representing a [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) (the number of characters that have to be inserted, deleted or changed to make one string into another) and you must find the number of balanced strings with that distance from the original string (i.e. the neighborhood of that string).
## Stipulations
* Balanced strings will consist only of the characters `()<>[]{}`
* You will only be asked to find neighborhoods for positive even distances
* Input and output is flexible. As long as you take in all the proper data and output the correct answer without violating any loopholes I am happy with your answer.
* You may choose to divide all of your integer inputs by 2 if you choose.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the objective is to minimize the number of bytes in your answer
>
> This was inspired by [this CMC](http://chat.stackexchange.com/transcript/message/35411574#35411574) and [this answer](https://codegolf.stackexchange.com/a/109953/56656)
>
>
>
## Testcases
```
Case | Distance | Size of Neighborhood
--------------------------------------------
() | 2 | 18
({}) | 2 | 33
(()) | 2 | 32
<> | 4 | 186
[][] | 4 | 688
<(){}> | 4 | 1379
{} | 6 | 2270
[]{}[] | 6 | 41097
```
Here are a few small examples with the actual neighborhoods included:
```
(), 2 :
{'', '<>', '()[]', '()()', '(())', '([])', '()<>', '{}', '{()}', '<>()', '(){}', '{}()', '<()>', '(<>)', '[()]', '[]()', '({})', '[]'}
```
---
```
({}), 2 :
{'([]{})', '()', '{}', '<({})>', '({<>})', '<{}>', '({()})', '(<>{})', '({}<>)', '({[]})', '(({}))', '({{}})', '({}[])', '{({})}', '({})()', '{}({})', '(())', '()({})', '([])', '<>({})', '({}{})', '({}){}', '({})<>', '(<{}>)', '({})[]', '((){})', '[{}]', '{{}}', '[]({})', '(<>)', '({}())', '([{}])', '[({})]'}
```
---
```
(()), 2 :
{'(())[]', '<>(())', '()', '{}(())', '{()}', '({()})', '{(())}', '(([]))', '(({}))', '(()[])', '(())<>', '((()))', '([])', '((<>))', '()(())', '(<()>)', '([()])', '[(())]', '(()){}', '(())()', '(()())', '(<>())', '(()<>)', '((){})', '<(())>', '<()>', '([]())', '(<>)', '({}())', '[()]', '({})', '[](())'}
```
---
```
<>, 4 :
{'<><<>>', '(<>)<>', '[<>][]', '<<><>>', '(){<>}', '(<>)()', '[<()>]', '<({})>', '<>()<>', '<[<>]>', '[][]<>', '<>[]<>', '<><><>', '[]<{}>', '[]<<>>', '[]<><>', '{<><>}', '[{<>}]', '<(<>)>', '(())<>', '{}<>{}', '()(<>)', '{()<>}', '(())', '{<>{}}', '(<><>)', '([])<>', '[]<[]>', '<{}<>>', '<><()>', '{()}<>', '{{}}<>', '{<>()}', '<<>>()', '{<<>>}', '<()>()', '<[]>()', '<>[<>]', '(<>())', '{}<>()', '(()<>)', '[{}]', '{{}}', '[]()', '[(<>)]', '<{}[]>', '<<>>[]', '{}<()>', '<>', '[()]<>', '<()><>', '[[]]<>', '[{}]<>', '[]<>[]', '()[<>]', '[]<>()', '{<>}{}', '{<[]>}', '<>(<>)', '(<>)[]', '<{}>()', '{}<><>', '{<>}()', '{[]}', '{[]}<>', '<<<>>>', '[]<()>', '<<[]>>', '<<{}>>', '[[]]', '()()<>', '[]{<>}', '<><[]>', '[[]<>]', '<{}()>', '<{<>}>', '<[]{}>', '{}<{}>', '<{}>[]', '()<<>>', '(<()>)', '[]{}', '{{}<>}', '{}()', '()<>[]', '<{}><>', '{[<>]}', '<><{}>', '<(())>', '<><>{}', '[()]', '<<>>{}', '{}{}<>', '[<<>>]', '<[][]>', '(<<>>)', '<[]><>', '[<>]<>', '[<>[]]', '[{}<>]', '{()}', '{<>[]}', '[]{}<>', '{(<>)}', '(<[]>)', '()[]<>', '<>{<>}', '{[]<>}', '(<>{})', '({}<>)', '[<><>]', '<><>()', '{}[<>]', '<{[]}>', '<<()>>', '<<>{}>', '([<>])', '<[]()>', '()()', '([])', '[[<>]]', '((<>))', '[](<>)', '(){}<>', '[()<>]', '<([])>', '<()()>', '[][]', '<<>[]>', '[<[]>]', '({})<>', '<{{}}>', '<[{}]>', '<{}{}>', '{}(<>)', '<<>><>', '[<>()]', '[][<>]', '({})', '{}[]<>', '{}<[]>', '<[()]>', '()[]', '<()>[]', '{{<>}}', '(<>){}', '{}{}', '({<>})', '{<()>}', '{}{<>}', '[]()<>', '<[]>[]', '(<>[])', '<[]>{}', '{}()<>', '()<[]>', '()<{}>', '{}<<>>', '<{}>{}', '{}[]', '()<>{}', '<()<>>', '[<>{}]', '{<>}[]', '<<>()>', '<><>[]', '{<{}>}', '<()[]>', '()<><>', '[<>]()', '()<>()', '{}<>[]', '<{()}>', '(<{}>)', '(){}', '()<()>', '<(){}>', '{<>}<>', '<[[]]>', '[]<>{}', '([]<>)', '<[]<>>', '[<>]{}', '<()>{}', '<>{}<>', '[<{}>]'}
```
[Answer]
## Mathematica, 187 173 bytes
```
Length@Union@Select[""<>#&/@(Tuples[Characters@" ()[]<>{}",StringLength@#+#2]/." "->""),sFixedPoint[StringReplace["()"|"[]"|"{}"|"<>":>""],s]==""&&EditDistance[s,#]==#2]&
```
Brute force pure function. `#` represents the first argument (starting string) and `#2` represents the second argument (distance).
`Characters@" ()[]<>{}"` is the list of possible characters (including `" "`)
`Tuples[Characters@" ()[]<>{}",StringLength@#+#2]` is the list of all tuples of those characters with length at most the original string length plus the distance.
`Tuples[Characters@" ()[]<>{}",StringLength@#+#2]/." "->""` replaces all of the `" "` characters with the empty string.
`""<>#&/@(...)` joins all of those character lists into strings.
Next we `Select` all such strings which are balanced and which have the appropriate `EditDistance` with the following function:
```
s String s
maps to
FixedPoint[StringReplace["()"|"[]"|"{}"|"<>":>""],s] the fixed point of cancelling out pairs of brackets
== equals
"" the empty string
&& and
EditDistance[s,#]==#2 the distance from s to # is #2
```
Next we use `Union` to delete the duplicates and take the `Length`.
] |
[Question]
[
A *pangram* is a string that contains every letter `a`-`z` of the English alphabet, case-insensitive. (It's OK if the pangram contains more than one copy of a letter, or if it contains non-letter characters in addition to the letters.)
Write a program or function whose input is a list of strings, and which outputs one or more strings which have the following properties:
* Each output string must be a pangram.
* Each output string must be formed by concatenating one or more strings from the input list, separated by spaces.
* Each output string must be the shortest, or tied for the shortest, among all strings with these properties.
Many programs will choose to output only one string; you'd only want to output more than one string if you'd otherwise have to write extra code to limit the output.
You may assume that the input contains no unprintable characters or spaces, and that no word in it is more than (26 times the natural logarithm of the length of the list) characters long. (You may not assume, however, that the input contains nothing but letters, or only lowercase letters; punctuation marks and uppercase letters are entirely possible.)
Input and output can be given in any reasonable format. For testing your program, I recommend using two test cases: a dictionary of English words (most computers have one), and the following case (for which a perfect (26-letter) pangram is impossible, so you'd have to find one containing duplicate letters):
```
abcdefghi
defghijkl
ijklmnop
lmnopqrs
opqrstuvw
rstuvwxyz
```
You should include a sample of your program's output along with your submission. (This may well be different for different people as a result of using different word lists.)
# Victory condition
This is a [restricted-complexity](/questions/tagged/restricted-complexity "show questions tagged 'restricted-complexity'") [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. The winner is the shortest program (in bytes) that runs in *polynomial time*. (A summary for people who don't know what that means: if you double the size of the word list, the program should become slower by no more than a constant factor. However, the constant factor in question can be as large as you like. For example, it's valid for it to become four times slower, or eight times slower, but not for it to become smaller by a factor of the length of the word list; the factor via which it becomes slower must be bounded.)
[Answer]
# Ruby 159 (iterative)
# Ruby ~~227~~ ~~220~~ ~~229~~ ~~227~~ 221 (recursive)
New iterative solution (based on the algorithm described by @Niel):
```
c={('A'..'Z').to_a=>""}
while l=gets
d=c.clone
c.map{|k,v|j=k-l.upcase.chars
w=v+" "+l.strip
d[j]=w if !c[j]||c[j].size<w.size}
c=d
end
x=c[[]]
p x[1..-1] if x
```
Old recursive solution:
```
W=[]
while l=gets
W<<l.strip
end
I=W.join(" ")+"!!"
C={[]=>""}
def o(r)if C[r]
C[r]
else
b=I
W.map{|x|s=r-x.upcase.chars
if s!=r
c=x+" "+o(s)
b=c if c.size<b.size
end}
C[r]=b
end
end
r=o ('A'..'Z').to_a
p r[0..-2] if r!=I
```
The byte measurement is based on leaving off the final newline in the file, which does not matter to `ruby 2.3.1p112`. The byte count went back up after fixing a small bug (adding ~~`.downcase`~~ `.upcase` for case-insensitivity as required by the problem statement).
Here is an earlier version from before shortening identifiers and such:
```
#!/usr/bin/env ruby
$words = [];
while (line=gets)
$words << line[0..-2];
end
$impossible = $words.join(" ")+"!!";
$cache = {};
def optimize(remaining)
return $cache[remaining] if ($cache[remaining]);
return "" if (remaining == []);
best = $impossible;
$words.each{|word|
remaining2 = remaining - word.chars;
if (remaining2 != remaining)
curr = word + " " + optimize(remaining2);
best = curr if (curr.length < best.length);
end
};
$stderr.puts("optimize(#{remaining.inspect})=#{best.inspect}");
return $cache[remaining] = best;
end
result = optimize(('a'..'z').to_a);
puts(result[0..-1]);
```
How does it work? It basically maintains a set of characters still to cover and only recurses on a word if it would reduce the uncovered set. Additionally, the results of recursion are memoized. Each subset of 2^26 corresponds to a memoization table entry. Each such entry is calculated in time proportional to the size of the input file. So the whole thing is `O(N)` (where `N` is the size of the input file), albeit with a huge constant.
[Answer]
## JavaScript (ES6), ~~249~~ 248 bytes, possibly competing
```
a=>a.map(w=>w.replace(/[a-z]/gi,c=>b|=1<<parseInt(c,36)-9,b=0,l=w.length)&&(m.get(b)||[])[0]<l||m.set(b,[l,w]),m=new Map)&&[...m].map(([b,[l,w]])=>m.forEach(([t,s],e)=>(m.get(e|=b)||[])[0]<=t+l||m.set(e,[t+l+1,s+' '+w])))&&(m.get(-2^-1<<27)||[])[1]
```
Explanation: Transforms the array by converting the letters into a bitmask, saving only the shortest word for each bitmask in a map. Then iterating over a copy of the map, augment the map by adding each combined bitmask if the resulting string would be shorter. Finally return the string saved for the bitmap corresponding to a pangram. (Returns `undefined` if no such string exists.)
[Answer]
# Python 3, 98, 94, 92 bytes
```
print([s for s in input().split()if sum([1 for c in range(65,91)if chr(c)in s.upper()])>25])
```
Iterates through the ASCII representation of the alphabet and adds a 1 to a list if the letter is found in the string. If the sum of the list is greater than 25 it contains all letters of the alphabet and will be printed.
] |
[Question]
[
Long time lurker first time poster here.
Write a program which takes 3 inputs: X, Y and Z.
* X = across (columns)
* Y = down (rows)
* Z = Location Marker
The program should then print a visual grid X across and Y down. This grid will can be made of any character except "+". Each 'location' is given an index number, counting up from **1** at coordinate 1, 1 across and then down until the end.
X and Y will always be at least 3, and Z will never be bigger than `X * Y`.
Z will represent the location which is printed as a "+", on the location as well as 1 character left, right, up and down. For example:
```
+
+++
+
```
Finally, if the + characters would intercept the edges (top most, left most, right most and/or down most edge), then the + should bounce back along the same axis and overflow the other side.
Examples:
Input = 5, 5, 13
```
-----
--+--
-+++-
--+--
-----
```
Input = 10, 10, 10
```
-------+++
---------+
---------+
----------
----------
----------
----------
----------
----------
----------
```
Input = 10, 10, 21
```
----------
+---------
+++-------
+---------
----------
----------
----------
----------
----------
----------
```
Edit : non square example
16,3,32
```
---------------+
-------------+++
---------------+
```
I think I've covered everything.
There should be no limit to the input, but if your program requires, cap it off at 64 \* 64.
~~**Bonus point (can I do that?):** Input Z should not be > X \* Y, but if it is larger than Y \* Z, then output the center + to the middle of the grid.~~
**EDIT:** Input Z cannot be greater than X \* Y
Edit 2:. Made some changes to X and Y to hopefully be clearer
This is code golf, shortest code wins.
[Answer]
## Python 2, ~~172~~ 171 bytes
```
def f(x,y,z):A=[['-']*x for _ in' '*y];z-=1;X,Y=z%x,z/x;a=[2,-1];A[Y][X]=A[Y+a[Y>0]][X]=A[Y-a[Y<y-1]][X]=A[Y][X+a[X>0]]=A[Y][X-a[X<x-1]]='+';print'\n'.join(map(''.join,A))
```
Edit: Saved 1 bytes by converting to function.
Previous (more readable):
```
x,y,z=inputtt
A=[['-']*x for _ in' '*y]
z-=1
X,Y=z%x,z/x
a=[2,-1]
A[Y][X]=A[Y+a[Y>0]][X]=A[Y-a[Y<y-1]][X]=A[Y][X+a[X>0]]=A[Y][X-a[X<x-1]]='+'
print'\n'.join(map(''.join,A))
```
[Answer]
## JavaScript (ES6), 165 bytes
```
(x,y,z,a=[...Array(y)].map(_=>Array(x).fill`-`))=>a.map(a=>a.join``,a[b=--z/x|0][c=z%x]=a[b?b-1:2][c]=a[b][c?c-1:2]=a[y+~b?b+1:y-3][c]=a[b][++c<x?c:x-3]=`+`).join`\n`
```
[Answer]
# Befunge, 175 bytes
```
>&:10p60p&:00p&1-:10g%:20p\10g/:30p::1+00g-!-\!+2-50p::1+1v
vg02g01*`\4\`0:-g05\!-g03:g00p01-1<g06+p00-1<p04-2+!\-!-g0<
>-!*\10g40g-:0`\4\`**+!2*"+"+10g:#^_$5500g:#^_$$$>:#,_@
```
[Try it online!](http://befunge.tryitonline.net/#code=PiY6MTBwNjBwJjowMHAmMS06MTBnJToyMHBcMTBnLzozMHA6OjErMDBnLSEtXCErMi01MHA6OjErMXYKdmcwMmcwMSpgXDRcYDA6LWcwNVwhLWcwMzpnMDBwMDEtMTxnMDYrcDAwLTE8cDA0LTIrIVwtIS1nMDwKPi0hKlwxMGc0MGctOjBgXDRcYCoqKyEyKiIrIisxMGc6I15fJDU1MDBnOiNeXyQkJD46IyxfQA&input=MTYgMyAzMg)
The first line (and a short continuation onto the second line) is where the parameters are read in and a few constants are calculated - the coordinates of the location (*lx*, *ly*), as well as adjusted coordinates which account for the bouncing off the edges:
```
ax = lx - (lx+1==w) + (lx==0) - 2
ay = ly - (ly+1==h) + (ly==0) - 2
```
The second and third lines contain the main loops over the height and width of the grid, the path of execution going from right to left initially before turning around onto the third line going left to right. For each coordinate in the grid (*gx*, *gy*) we calculate the following condition:
```
(gx==lx && gy>ay && gy<ay+4) || (gy==ly && gx>ax && gx<ax+4)
```
If that condition is true, we push a `"+"` onto the stack, if false we push a `"-"`. To avoid branching here, we're really just pushing `43 + 2 * !condition` (43 being the ASCII value of plus and 45 being minus).
Once the loops have finished, the final bit of code is just a standard output routine that prints out everything on the stack.
[Answer]
# JavaScript (ES6), 170
Still golfable
```
(w,h,z,t=--z%w,u=z/w|0,r='-'.repeat(w),S=(f,j)=>(r+f+r).substr(w-j,w))=>[...Array(h)].map((q=u-!!u-!(u+1-h),y)=>y-u?y>=q&y<q+3?S('+',t):r:S('+++',t-!!t-!(t+1-w))).join`
`
```
*Less golfed*
```
(w, h, z
, t=--z%w
, u=z/w|0
, r='-'.repeat(w)
, S=(f,j)=>(r+f+r).substr(w-j,w)
) => [...Array(h)].map(
(q = u-!!u-!(u+1-h),
y) => y-u?y>=q&y<q+3?S('+',t):r:S('+++',t-!!t-!(t+1-w))
).join`\n`
```
**Test**
```
F=
(w,h,z,t=--z%w,u=z/w|0,r='-'.repeat(w),S=(f,j)=>(r+f+r).substr(w-j,w))=>[...Array(h)].map((q=u-!!u-!(u+1-h),y)=>y-u?y>=q&y<q+3?S('+',t):r:S('+++',t-!!t-!(t+1-w))).join`
`
function update() {
var [x,y,z] = I.value.match(/\d+/g)
O.textContent = F(+x,+y,+z)
}
update()
```
```
<input value='5 6 10' oninput='update()' id=I>
<pre id=O>
```
] |
[Question]
[
## Introduciton
Some of you might have realised that I am a sloppy typer when using my phone. That's why I want you to write a program which corrects my typos.
## Chalkrnge
Given a misspelled word, output all of the possible words which I meant to write.
## Typso
The main cause of my typos is down to the fact that I hit the wrong keys and often hit the key next door. The following is my keyboard layout:
```
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
, [ space ] .
```
*Note that the bottom row, `, [ space ] .` will never be used in this challenge*
For some reason, I only make mistakes horizontally: I would never hit the *n* instead of the *j*, but I might hit an *f* instead of a *d*.
For example, I could end up spelling the word *sloppy* as:
```
akioot
```
Where I've gone left of each key.
However, don't forget that I may not necessarily make a mistake on *every* letter in the word.
## Ezsmple
Let's say the input is:
```
vid
```
The possibilities that the word could have been are:
```
vid cid bid
vis cis bis
vif cif bif
vod cod bod
vos cos bos
vof cof bof
vud cud bud
vus cus bus
vuf cuf buf
```
Out of those, the following are in the dictionary:
```
cod
cud
bid
bud
bus
```
So that should be your output.
## Rulws
You should only use the text file found here as your dictionary: <http://mieliestronk.com/corncob_lowercase.txt>. You do not have to count this file as part of your byte count.
All input will be a single word. You may display your output in any way you wish (as long as there is some kind of separator).
Assume that with all input, you will find a variant which is in the dictionary.
## Wibninf
The shortest code in bytes wins.
[Answer]
## Python 2.7, ~~161~~ 159 bytes
```
from itertools import*
lambda a,k=' qwertyuiop asdfghjkl zxcvbnm ':set(map(''.join,product(*[k[k.index(l)-1:k.index(l)+2].strip()for l in a])))&set("<dictionary>".split())
```
readable version
```
from itertools import *
dictionary=set("<dictionary>".split())
keyboard=' qwertyuiop asdfghjkl zxcvbnm '
x=[]
for letter in input():
index=keyboard.index(letter)
x.append(keyboard[index-1:index+2].strip())
words=set(map(''.join,product(*x)))
print words&dictionary
```
* *Saved 1 byte thanks to @TuukkaX*
[Answer]
# Japt, ~~50~~ 47 bytes
```
;D=R+Dv;W=3pUl¹óW ®s3 s1 £DgDbUgY)-X+1}Ãf@~V·bX
```
Input is the word to fix, and the dictionary as a string. [Test it online!](http://ethproductions.github.io/japt/?v=master&code=O0Q9UitEdjtXPTNwVWy581cgrnMzIHMxIKNEZ0RiVWdZKS1YKzF9w2ZAfla3Ylg=&input=ImlkIgoKIlBhc3RlIGRpY3Rpb25hcnkgaGVyZSI=) (Note: you'll have to manually paste the dictionary into the string.)
### How it works
```
;D=R+Dv;W=3pUl¹óW ®s3 s1 £DgDbUgY)-X+1}Ãf@~V·bX // Implicit: U = input, V = dictionary, R = newline
; // Re-assign preset variables. D = "QWERTYUIOP\nASDFGHJKL\nZXCVBNM";
D=R+Dv; // Convert D to lowercase and prepend a newline.
W=3pUl¹ // Set W to 3 to the power of U.length.
óW // Create the range [W, W+W).
® Ã // Map each item Z in the range by this function:
s3 // Take Z.toString(3).
s1 // Remove the first character.
// If the input is two chars long, e.g. "id", the array is now
// ["00", "01", "02", "10", "11", "12", "20", "21", "22"].
£ } // Map each char X and index Y in the string by this function:
UgY // Get the char at position Y in U.
Db ) // Take the index of the char in D.
-X+1 // Subtract X and add 1.
Dg // Get the char at that position in D.
// This maps our array for "id" to:
// ["of", "od", "os", "if", "id", "is", "uf", "ud", "us"].
f@ // Filter to only the items X where
bX // the index of X in
V· // the dictionary, split at newlines,
~ // is not -1.
// This filters our array for "id" to:
// ["of", "if", "id", "is", "us"].
// Implicit: output last expression
```
] |
[Question]
[
Your task is to write a RegEx that matches everything inside strings.
A string is defined as everything surrounded by (but not including) two unescaped `"`.
A `"` can be escaped by `\`, which can also be escaped again.
# Testcases
```
string: ab\c"defg\\\"hi"jkl"mn\\\\"opqrst""
matches: ^^^^^^^^^^ ^^^^^^ ^ (the empty string)
```
# Scoring
Shortest solution wins.
# Specs
* Please specify the flavour used.
* The input will have balanced `"`.
* There will be no `\` that immediately precedes a string-beginning-delimiter. For example, you would not need to handle `abc\"def"`
[Answer]
# PCRE, 21 20 15 19 bytes
```
(.|^)"\K(\\.|[^"])*
```
[Try it here.](https://regex101.com/r/iK8rO2/3)
This matches a character (or the beginning of the input) before the beginning double quote and then reset the match, to make sure the double quote isn't shared with another match.
# PCRE, 25 23 bytes
Thanks to Martin Büttner for golfing off 2 bytes.
```
(\\.|[^"])*+(?!"(?R)|$)
```
[Try it here.](https://regex101.com/r/iV7gT1/2)
### Explanation
```
(
\\.|[^"] # An escaped character, or a character that isn't a double quote
)*+ # Possessive zero-or-more quantifier, which means backtracking
# could not happen after first match is found. That means if \\.
# matched, it would never switch to [^"], because it is always a
# match if it just stopped after the \\. without backtracking.
(?!"(?R)|$) # Make sure it is not followed by a double quote and another
# match, or the end of the input.
```
Note that the possessive quantifier (`*+`) made sure the negative lookahead always begins after a whole string, or a whole segment of non-string.
There are 4 cases:
* The match begins anywhere outside of a string. `\\.` would never match a double quote according to the clarification. It could only end just before the next double quote which begins a string, or the end of input. Both cases fails the negative lookahead.
* The match begins at the beginning of a string. `(\\.|[^"])*+` would match a complete string. The next character must be a double quote, and couldn't be the end of input. After the double quote it is outside of the string, so it couldn't be another match. So it passes the negative lookahead.
* The match begins at the end of a string. It matches an empty string in the same way as the previous case. But it doesn't matter according to the clarification.
* The match begins in the middle of a string. Impossible because matches don't overlap.
[Answer]
# JavaScript, 24 bytes
[`"([^"\\]*(?:\\.[^"\\]*)*)"`](https://regex101.com/r/P0CQRt/4)
Group 1 is the contents of the string.
[Answer]
# JavaScript, ~~21~~ ~~15~~ ~~13~~ 12 bytes
[`"((\\?.)*?)"`](http://regexr.com/3fack)
String contents are in group 1.
```
" #start of string
( #capturing group
(
\\?. #match character or escaped character
)*? #match as few as possible
)
" #end of string
```
] |
[Question]
[
# Interpret DOGO
[DOGO](http://esolangs.org/wiki/DOGO) is a lesser known programming language. While the original DOGO (a joke language from a Usenet post) has never been implemented, a language resembling it has been created. The commands for the language are:
```
+===========+================================================================+
| Command | Description |
+===========+================================================================+
| SIT | If the value of the current memory cell is 0, jump to STAY. |
+-----------+----------------------------------------------------------------+
| STAY | If the value of the current memory cell is not 0, jump to SIT. |
+-----------+----------------------------------------------------------------+
| ROLL-OVER | Select the next operation from the operation list. |
+-----------+----------------------------------------------------------------+
| HEEL | Execute the currently selected operation. |
+-----------+----------------------------------------------------------------+
```
The operations are:
```
+========+=======================================================+====+
| Number | Description | BF |
+========+=======================================================+====+
| 0 | Increment current memory cell. | + |
+--------+-------------------------------------------------------+----+
| 1 | Decrement current memory cell. | - |
+--------+-------------------------------------------------------+----+
| 2 | Move to next memory cell. | > |
+--------+-------------------------------------------------------+----+
| 3 | Move to previous memory cell. | < |
+--------+-------------------------------------------------------+----+
| 4 | Input a byte and store it in the current memory cell. | , |
+--------+-------------------------------------------------------+----+
| 5 | Output the current memory cell as ASCII. | . |
+--------+-------------------------------------------------------+----+
```
## Examples
Hello World:
```
roll-over roll-over heel roll-over roll-over roll-over roll-over heel heel heel
heel heel heel heel heel heel sit roll-over roll-over roll-over heel roll-over
roll-over roll-over heel heel heel heel heel heel heel heel roll-over roll-over
heel roll-over roll-over roll-over roll-over roll-over heel roll-over roll-over
roll-over roll-over roll-over stay roll-over roll-over roll-over heel roll-over
roll-over heel roll-over roll-over roll-over heel roll-over roll-over roll-over
roll-over heel heel heel heel heel heel heel sit roll-over roll-over roll-over
heel roll-over roll-over roll-over heel heel heel heel roll-over roll-over heel
roll-over roll-over roll-over roll-over roll-over heel roll-over roll-over
roll-over roll-over roll-over stay roll-over roll-over roll-over heel roll-over
roll-over roll-over heel roll-over roll-over roll-over roll-over roll-over heel
roll-over heel heel heel heel heel heel heel roll-over roll-over roll-over
roll-over roll-over heel heel roll-over heel heel heel roll-over roll-over
roll-over roll-over roll-over heel roll-over roll-over roll-over heel heel heel
roll-over roll-over roll-over roll-over heel heel heel heel heel heel heel heel
sit roll-over roll-over roll-over heel roll-over roll-over roll-over heel heel
heel heel roll-over roll-over heel roll-over roll-over roll-over roll-over
roll-over heel roll-over roll-over roll-over roll-over roll-over stay roll-over
roll-over roll-over heel roll-over roll-over heel roll-over roll-over roll-over
heel heel heel roll-over roll-over roll-over roll-over heel heel heel heel heel
heel heel heel heel heel sit roll-over roll-over roll-over heel roll-over
roll-over roll-over heel heel heel heel heel heel heel heel heel roll-over
roll-over heel roll-over roll-over roll-over roll-over roll-over heel roll-over
roll-over roll-over roll-over roll-over stay roll-over roll-over roll-over heel
roll-over roll-over roll-over roll-over heel heel heel roll-over roll-over
roll-over roll-over heel roll-over roll-over roll-over roll-over heel heel heel
heel roll-over roll-over heel roll-over heel heel heel roll-over roll-over
roll-over roll-over roll-over heel roll-over roll-over heel heel heel heel heel
heel roll-over roll-over roll-over roll-over heel roll-over roll-over heel heel
heel heel heel heel heel heel roll-over roll-over roll-over roll-over heel
roll-over roll-over roll-over heel heel roll-over roll-over roll-over roll-over
heel roll-over roll-over roll-over roll-over roll-over heel
```
[99 bottles of beer](http://www.99-bottles-of-beer.net/language-dogo-990.html)
## Rules
* Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.
* If it is possible, please provide a link to an online site where your code can be tested.
* Your program cannot write anything to `STDERR` (or something similar).
* You can take input from `STDIN` (or the closest alternative in your language), or as an argument.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
## Scoring
Programs are scored according to *bytes*. The default character set is UTF-8, if you are using a different one, please specify.
That aside, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), and the lowest byte count will be deemed the winner!
## Submissions
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 79350; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://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 "https://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,]*[^\s,]),.*?(\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,
});
});
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;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, 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 > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="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>
```
**Update:**
Sorry for not clarifying the `sit` and `stay` commands very well. They are, as @user6245072 said, like `[` and `]` in BF.
**Update 2:**
To clarify @KennyLau's questions:
* The default operation is `0`.
* Memory consists of 8-bit cells.
* Cells wrap on overflow/underflow.
* Input is required for operation 4.
[Answer]
# Python 3, ~~388~~ ~~398~~ ~~373~~ 371 bytes
Assumes 256 memory cells. Just a straightforward implementation, easily beatable, probably can be golfed more. Try it on [repl.it](https://repl.it/CNS4/1).
Thanks to @EasterlyIrk for having me realize that Python 3 is much shorter that Python 2.
EDIT: Realized I only accounted for over/underflow while printing, not in actual value.
Thanks to @KevinLau-notKenney for saving 25 (!) bytes with list multiplication and inversion operator tricks
EDIT: -3 bytes by putting 256 into a variable, -4 messing with operators, +8 making sure it is lowercase
```
def p(s):
b=256
l,m=[w[-1]for w in s.lower().split()],[0]*b
i=p=x=0
while x<len(l):
c=l[x]
if'm'>c:
if 1>i:m[p]=-~m[p]%b
if 1==i:m[p]=~-m[p]%b
if 2==i:p=-~p%b
if 3==i:p=~-p%b
if 4==i:m[p]=ord(input()[0])
if 4<i:print(chr(m[p]),end="")
if'r'==c:i=-~i%6
if't'==c and m[p]<1:x+=l[:x].index('y')
if'x'<c and m[p]>0:x-=l[x::-1].index('t')
x+=1
```
[Answer]
# Ruby, 287 bytes
Runs on an infinite tape in both directions. DOGO input is a file on the command line. If there is no command line argument, a DOGO program will still work if passed in as STDIN, unless it uses operation `3` (get a byte from STDIN) in which case I have no idea. At any rate, file input is best.
Assumes no other text other than the four commands and whitespace exist in the program file.
[Hello World Demonstration](http://ideone.com/8phxWa)
```
i=k=o=0;m={}
c=$<.read.upcase.split.map{|e|%w{SIT STAY ROLL-OVER HEEL}.index e}.join
(m[k]||=0
e=c[i].to_i
e>2?o>4?$><<m[k].chr:
o>3?m[k]=STDIN.getc.ord:
o>1?k+=o>2?-1:1:
m[k]=o<1?-~m[k]%256:~-m[k]%256:
e>1?o=-~o%6:
e>0?m[k]>0?i=c.rindex(?0,i):0:
m[k]<1?i=c.index(?1,i):0
i+=1)while c[i]
```
] |
[Question]
[
Everyone realizes that [Tic Tac Toe](http://playtictactoe.org/) is a solved game. However, the Misère version of only-Xs provides an interesting alternative.
In this version of the game, both players play Xs onto the board and try to avoid making three in a row. If you'd like to see more about this, [Numberphile](http://youtu.be/ktPvjr1tiKk) has a nice video about this concept.
## Given a board of Misère Crosses, play an optimal move.
A board is three lines of three characters each, which are `X` or . Thus:
```
X X
X
XX
```
is a valid board. You may take this in any convenient format, so long as your input and output use the same format. Formats include (but are not limited to): A multi-line string (with optional trailing newline); A 2D array of characters which are `X` or ; a 1D flattened array of boolean values representing if each position has been played.
An optimal move is one that guarantees you will win by continuing to play optimally or prolongs your loss for as long as possible and is defined by the following rules:
* Avoid making three in a row.
* If you go first, play in the middle.
* If the only occupied space is the middle, play in any of the remaining spaces.
* If the middle square is not occupied and an outer square is, play opposite your opponent's last play.
* If the middle square is occupied and an outer square is, play a "knights move" (opposite, one over) away from a previous move that does not cause you to lose.
* If no remaining squares are left where you won't lose, play in any of the remaining squares.
[NOTE: this has been proved to be [non-optimal in one case](https://codegolf.stackexchange.com/a/76630/51825) but you should use this algorithm anyway.]
**You may assume that all of your previous moves were optimal.** Thus, the first example board is not a valid input. Your opponent's moves may or may not be optimal.
If the game has ended (i.e. a three in a row has been made), behavior is undefined.
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins!
One possible path, using only optimal moves, is this:
```
[ ] [ ] [X ] [X ] [X ] [X ] [XX ]
[ ]->[ X ]->[ X ]->[ XX]->[ XX]->[ XX]->[ XX]
[ ] [ ] [ ] [ ] [ X ] [XX ] [XX ]
```
Here are possible inputs originating from the opponent using non-optimal moves:
(Note that only the left-side boards on this list are valid inputs.)
```
[X ] [X ]
[ ]->[ ]
[ ] [ X]
[XX ] [XX ]
[ ]->[ ]
[ X] [ XX]
[XX ] [XX ]
[X ]->[X X]
[ XX] [ XX]
```
[Answer]
# Ruby, Rev B 121 bytes
Submission is the anonymous function, minus the `f=`. Shown in test program to illustrate use.
```
f=->n{["~mK)\7","}uYwQO"][l=n%2].bytes{|t|9.times{|i|(m=n|1<<i)==n||8.times{|j|m/2*257>>j&255==126-t&&t+j%2!=119&&l=m}}}
l}
puts g=f[gets.to_i]
puts
[7,6,5,
8,0,4,
1,2,3].each{|i|print g>>i&1; puts if i/3==1}
```
2 bytes saved by making the centre square the least significant bit instead of most significant bit (remove by `/2` instead of `%256`.) Remaining savings by a reorganization of the table of acceptable moves. Organizing as centre square free/occupied instead of by total number of X's allows for a simpler test. Also, now there are only 2 strings in the array so the `%w{string1 string2}` syntax is abandoned in favour of the `["string1","string2"]` syntax. This enables a nonprintable character `\7` to be included, which in turn enables a simpler encoding to be used: `126-t` instead of `(36-t)%120`.
# Ruby, Rev A 143 bytes
```
->n{l=r=("%b"%n).sum%8
%w{$ %5 - I+Wy Q S#}[r].bytes{|t|9.times{|i|(m=n|1<<i)==n||8.times{|j|m%256*257>>j&255==(t-36)%120&&t+j%2!=43&&l=m}}}
l}
```
This is an anonymous function. The input / output format was left open, so I've gone for a 9-bit binary number. the 512's bit represents the centre, with the remaining bits spiralling round it (the 1's bit is considered to be a corner.)
There are far more possible inputs than acceptable outputs, so the algorithm is to try all moves, and find one that fits an acceptable output pattern. The acceptable output patterns for each number of X's are hardcoded.
The information about the centre square is stripped off and the remaining 8 bits are multiplied by 257 to duplicate them. This pattern is then rotated past the acceptable patterns by rightshifting.
The loop is not exited when a pattern is found, so the returned pattern will be the LAST acceptable pattern found. For this reason, preferable patterns (where there is a preference) come later in the list.
Given the 'Knights move' strategy it is of little importance whether a pattern is rotated by 45 degrees or not. The ungolfed version follows the knights move strategy and therefore does not need to differentiate between corner squares and edge squares: three in a row is to be avoided anyway.
However, I found that this is not always the best strategy, as there is the following trick. If your opponent goes first and takes the centre he should win. But on his second move he makes the error of allowing you to make a 2x2 square you should take it, as this allows you to force him to make three in a row. This is implemented in the golfed version. A little extra code is needed in this one instance to distinguish between three X's in a corner (force opponent to lose) and 3 X's along one edge (immediate suicide.)
**Ungolfed in test program**
The ungolfed version follows the logic expressed in the question.
In the golfed version the table is slightly modified to `[[0],[1,17],[9],[37,7,51,85],[45],[47,119]]` to implement the slightly different behaviour for the case `r=3`. It is then compressed to printable ASCII (requiring decoding `(t-36)%120`). An additional bit of logic is required to differentiate between three X's in a corner and three X's along an edge in the case of the table entry 7: `&&t+j%2!=43`
```
f=->n{l=r=("%b"%n).sum%8 #convert input to text, take character checksum to count 1's(ASCII 49.)
#0 is ASCII 48, so %8 removes unwanted checksum bloat of 48 per char.
#l must be initialised here for scoping reasons.
[[0],[1,17],[9],[11,13,37,51,85],[45],[47,119]][r].each{|t| #according to r, find the list of acceptable perimeter bitmaps, and search for a solution.
9.times{|i|(m=n|1<<i)==n|| #OR 1<<i with input. if result == n, existing X overwritten, no good.
#ELSE new X is in vacant square, good. So..
8.times{|j|m%256*257>>j&255==t&&l=m}} #%256 to strip off middle square. *257 to duplicate bitmap.
#rightshift, see if pattern matches t. If so, write to l
}
l} #return l (the last acceptable solution found) as the answer.
#call function and pretty print output (not part of submission)
puts g=f[gets.to_i]
puts
[6,7,0,
5,8,1,
4,3,2].each{|i|print g>>i&1; puts if i<3}
```
**Output of test program**
This what happens when the computer plays itself.
```
C:\Users\steve>ruby tictac.rb
0
256
000
010
000
C:\Users\steve>ruby tictac.rb
256
384
010
010
000
C:\Users\steve>ruby tictac.rb
384
400
010
010
100
C:\Users\steve>ruby tictac.rb
400
404
010
010
101
C:\Users\steve>ruby tictac.rb
404
436
010
110
101
C:\Users\steve>ruby tictac.rb
436
444
010
110
111
```
**GAME ANALYSIS PLAYING FIRST**
This is actually very simple and linear.
When playing first, the middle square will always be the first square occupied.
### r=0
```
... binary representation 0
.X.
...
```
### r=2
```
X.. binary representation 1001=9
.XX
...
```
### r=4
```
X.. binary representation 101101=45
.XX
XX.
```
There is only one way (up to symmetry) to have five X's including the middle square on the board without the game being over.
There is an X in the middle square, one on each diagonal (at 90 degrees to each other) and one on each horizontal/vertical centreline (at 90 degrees to each other.)
As an entire edge cannot be occupied the above is the only arrangement possible. Other player must lose on next move.
**GAME ANALYSIS PLAYING SECOND**
Play is quite different depending if the other player chooses the middle square.
### r=1
middle square occupied
```
.X. X.. binary representation 1
.X. .X.
... ...
```
middle square free
```
X.. .X. binary representation 10001=17
... ...
..X .X.
```
### r=3
Middle square occupied, if other player plays adjacent to your last X
Playing a knight's move away as below is supported in the ungolfed version
```
XX. .XX binary representation 1011=11
.X. XX. or mirror image 1101=13
X.. ...
```
However the above is NOT the best move and is not supported in the golfed version.
The best move is as follows, forcing a win on the next turn:
```
XX. binary representation 111=7. XXX
XX. Only to be used where j is odd. .X.
... Even j would look like image to right. ...
```
Middle square occupied, if other player plays at 90 or 135 degrees to your last X (play knight's move away.)
```
X.X .X. binary representation 100101=37
.X. .XX
.X. X..
```
Middle square free
```
X.X .X. XX. binary representations:
... X.X ... 1010101=85 (first two)
X.X .X. .XX and 110011=51 (last one)
```
### r=5
middle square occupied. For the reasons stated above in r=4, there are four possible moves, all of which lose. only one is supported: 101111=47.
middle square free. There is only one possible board up to symmetry, as follows. Other player must lose on next move, so there is no need to support r>5.
```
XX. binary representation 1110111=119
X.X
.XX
```
] |
[Question]
[
In this challenge, you need to partition a list, where partitions have a max size, a min size, and a preferred size. I'll be using the notation `(min,pref,max)` to indicate the sizes in this challenge.
For those unfamiliar with partitioning, the following list has been partitioned into parts of 3:
`[0..9] -> [[0,1,2],[3,4,5],[6,7,8]]`
When the list is not evenly divisible, you need the partitions to be as close to the preferred size as possible: `[0..10], (2,4,5) -> [[0,1,2,3],[4,5,6],[7,8,9]]`. This partitioning is preferable to `[[0,1,2,3],[4,5,6,7],[8,9]]`, even though the latter has more of the preferred length. Formally, we need to minimize the sum of `(partitionLength-preferredSize)^2` for each partition.
The order of the partition lengths does not matter: For `[0..5], (2,3,3)`, either `[[0,1,2],[3,4]]` or `[[0,1],[2,3,4]]` works. If no partition is possible, return an empty array: `[0..7], (4,4,5) -> []`.
You can assume that `1<=min<=pref<=max`, and that the array passed to you is a non-empty array of integers. The array will always be the first argument. You can accept min, max, and pref in any order and as a tuple or as separate arguments.
Your program must run under a couple of seconds. Basically, iterating through every possible partition size within the bounds is not allowed.
# Test cases:
```
[1], (1,3,4) -> [[1]]
[100], (1,2,3) -> [[100]]
[1,2], (1,1,2) -> [[1],[2]]
[1,2], (1,2,2) -> [[1,2]]
[1,2], (1,3,3) -> [[1,2]]
[1,2,3], (1,2,3) -> [[1,2],[3]] or [[1,2,3]]
[1,2,3,4], (1,3,4) -> [[1,2,3,4]]
[1,2,3,4,5], (3,3,4) -> []
[1,2,3,4,5], (2,2,2) -> []
[1,2,3,4,5], (3,3,5) -> [[1,2,3,4,5]]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49], (2,6,6) -> [[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18],[19,20,21,22,23,24],[25,26,27,28,29],[30,31,32,33,34],[35,36,37,38,39],[40,41,42,43,44],[45,46,47,48,49]]
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so aim for as few bytes as possible in your favorite language!
[Answer]
# Haskell, 152
```
_%0=[]
s%k|(a,b)<-splitAt(div(z s)k)s=a:b%(k-1)
z=length
f s n p x=snd$minimum$(z s*p^2,[]):[(sum[(z x-p)^2|x<-s%k],s%k)|k<-[-div(-z s)x..div(z s)n]]
```
In any partition, if there are two lists which have lengths that differ by two or more, it will always be beneficial to shrink the bigger list and enlarge the smaller list. therefore, we only need to consider partitions with only two list sizes, which simplifies the computation.
the program then runs on all the possible amounts of lists in the partition. given the amount of lists in the partition, the score is uniquely determined. the program computes a fitting partition, and its score.
then it finds the overall minimum, and returns it.
Usage: input like `f [1,2,3,4,5] 1 3 4` (`f` is the function that solves the challenge)
Although it is possible to computing the best option completely numerically and only then partitioning the list accordingly, it took too many bytes. however, my last version of this approach is:
```
_%0=[]
s%k|(a,b)<-splitAt(div(length s)k)s=a:b%(k-1)
f s n p x|l<-length s=(s%)$snd$minimum$(l*p^2,0):[(k*j^2+mod l k*(1-2*j),k)|k<-[1..div l n],k*x>=l,j<-[p-div l k]]
```
[Answer]
# CJam, 70
```
q~:S;_,[0L]a{_S2=e<),S0=>f{[__S1=-_*\]@@-j.+}[esL]a+:e<}j1={/(\e_}/;]p
```
[Try it online](http://cjam.aditsu.net/#code=q~%3AS%3B_%2C%5B0L%5Da%7B_S2%3De%3C)%2CS0%3D%3Ef%7B%5B__S1%3D-_*%5C%5D%40%40-j.%2B%7D%5BesL%5Da%2B%3Ae%3C%7Dj1%3D%7B%2F(%5Ce_%7D%2F%3B%5Dp&input=%5B1%202%203%204%205%5D%5B3%203%205%5D)
The code finds an optimal sequence of partition sizes based on the list size, using dynamic programming (via memoized recursion), then goes ahead and partitions the list.
] |
[Question]
[
# Introduction
**tl;dr**
In this challenge you have to calculate the moon's phase for a given date.
---
This challenge is inspired by the ~~game~~ *psycho social audiovisual experiment* "[Superbrothers: Sword & Sworcery EP](https://vimeo.com/20379529)". In *S:S&S EP* the moon's phases are important to the outcome of the adventure as some events occur only at a specific point in time.

The question is: *Which lunar phase is present on a specific date.* Each main phase – from new moon to first quarter to full moon to third quarter – is about 7.38 days long. The whole lunar cycle is roughly 29.52 days. Based on these values various methods of calculation exist.1
# Input
* A date based on the Gregorian calendar, between 1 January 1970 and 31 December 2116.
* You can choose one of the following formats: `yyyy-mm-dd`, `dd.mm.yyyy`, `dd/mm/yyyy`, `yyyymmdd` or `ddmmyyyy`.
# Output
Output the index `[0-7]` of the lunar phase based on this zero-indexed array:
```
['New moon', 'Waxing crescent', 'First quarter', 'Waxing gibbous', 'Full moon', 'Waning gibbous', 'Third quarter', 'Waning crescent`]
```
# Requirements
* You can write a program or a function. If you go with an anonymous function, please include an example of how to invoke it.
* Input is accepted from `STDIN`, command line arguments, as function parameters or from the closest equivalent.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins.
* Built-ins or external libraries that calculate the moon phase are not allowed.2
* Standard loopholes are disallowed.
# Tests
The values are: `date | index of the phase | illumination | name`
A full lunar cycle:
```
08.02.2016 | 0 | 0% | New moon
07.02.2016 | 7 | 2% | Waning crescent
07.02.2016 | 7 | 2% | Waning crescent
06.02.2016 | 7 | 6% | Waning crescent
05.02.2016 | 7 | 12% | Waning crescent
04.02.2016 | 7 | 19% | Waning crescent
03.02.2016 | 7 | 28% | Waning crescent
02.02.2016 | 7 | 37% | Waning crescent
01.02.2016 | 6 | 47% | Third quarter
31.01.2016 | 5 | 56% | Waning gibbous
30.01.2016 | 5 | 65% | Waning gibbous
29.01.2016 | 5 | 74% | Waning gibbous
28.01.2016 | 5 | 82% | Waning gibbous
27.01.2016 | 5 | 89% | Waning gibbous
26.01.2016 | 5 | 94% | Waning gibbous
25.01.2016 | 5 | 98% | Waning gibbous
24.01.2016 | 4 | 100% | Full moon
23.01.2016 | 3 | 100% | Waxing gibbous
22.01.2016 | 3 | 97% | Waxing gibbous
21.01.2016 | 3 | 93% | Waxing gibbous
20.01.2016 | 3 | 86% | Waxing gibbous
19.01.2016 | 3 | 77% | Waxing gibbous
18.01.2016 | 3 | 67% | Waxing gibbous
17.01.2016 | 3 | 56% | Waxing gibbous
16.01.2016 | 2 | 45% | First quarter
15.01.2016 | 1 | 33% | Waxing crescent
14.01.2016 | 1 | 23% | Waxing crescent
13.01.2016 | 1 | 14% | Waxing crescent
12.01.2016 | 1 | 7% | Waxing crescent
11.01.2016 | 1 | 2% | Waxing crescent
10.01.2016 | 0 | 0% | New moon
```
Random test cases:
```
14.12.2016 | 4 | 100% | Full moon
16.10.1983 | 3 | 75% | Waxing gibbous
04.07.1976 | 2 | 47% | First quarter
28.11.1970 | 0 | 0% | New moon
```
As most methods aren't accurate to a scientific level and you also get mixed results on different websites for a couple of these days, it is acceptable if your results are within a *± 1 day* range.
# Bonus
Reduce your byte count and *withdraw*:
* **15%** – Print the actual name of the phase as listed in section **Output** instead of its index.
* **25%** – Print the dates of the upcoming new and full moon separated by a whitespace or newline on empty input.
---
1 For example: [Calculating phase](https://en.wikipedia.org/wiki/Lunar_phase#Calculating_phase) on Wikipedia.
2 Sorry [Mathematica](https://reference.wolfram.com/language/ref/MoonPhase.html).
[Answer]
# Python ~~2~~ 3, ~~255~~ ~~204~~ ~~180~~ 178 bytes
This is answer is inaccurate by a day or two in several places, including for some of the test cases, though I was told that some inaccuracy was acceptable. At any rate, the motion of the moon is never very exact and this function remains generally correct (or at least, it doesn't vary too far).
**Edit:** In the course of correcting my code and making it more accurate, I have golfed it down considerably.
**Edit:** This code is now a one-line Python 3 program. (Credit to [TimmyD](https://codegolf.stackexchange.com/users/42963/timmyd) for the name "magic numbers")
```
p,q,r=(int(i)for i in input().split("-"));t=q<3;y=p-2000-t;i,j=divmod(((r+(153*(q+12*t-3)+2)//5+365*y+y//4-y//100+y//400+11010)*86400-74100)%2551443,637861);print((86400<=j)+2*i)
```
Ungolfed:
```
def jul(p,q,r):
'''
The Julian Day Number (JDN) of the input minus the JDN of January 7, 1970,
the first new moon after January 1, 1970.
'''
t=q<3
y=p-2000-t # -2000 years to push day 0 to January 1, 2000
return r+(153*(q+12*t-3)+2)//5+365*y+y//4-y//100+y//400+11010
# +11010 days to push day 0 to January 7, 1970
def moon(s):
'''
Input format: yyyy-mm-dd
An attempt at explaining the "magic numbers"
- 29.53059 days is close to 2551443 seconds, so I used that
- The offset of +12300 seconds because the new moon of 1970-01-07 was at 2035 UTC
or 12300 seconds before midnight. For those of you saying that this pushes
the beginning of my calendar to 2035, *6* January 1970, yes it does.
But if I need to the calendar to recognize 1970-01-07 as the day of the new moon
which means that midnight needed to be a positive number of seconds, 0 <= x < 86400.
Basically, I hacked it together, and +12300 worked.
'''
d = 86400
p,q,r = map(int, s.split("-"))
z=(jul(p,q,r)*d+12300)%2551443 # 2551443 is about the number of seconds in a lunar month
div, mod = divmod(z, 637861) # 637861 seconds is about a quarter of a lunar month
# div is what part of the lunar month this is (0 - 3)
# mod is seconds since the start of the main phase
return 2*div + (86400 <= mod) # 2*div for the main phase, and
# is mod >= the number seconds in a day?
# (+0 if within a day of the main phase, +1 otherwise)
```
] |
[Question]
[
[Newton's theory of gravitation](https://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation#Modern_form) says that the gravitational force between two point masses is
# F=(Gm1m2)/ r2
Where
* *G* is the gravitational constant: 6.674×10−11 N · (m/kg)2
* *m1* is the mass of the first object
* *m2* is the mass of the second object
* *r* is the distance between their centers of mass
## Challenge
You need to simulate the pull between two words. Each lowercase letter has mass given by its position in the alphabet. Capital letters have twice the mass of their lowercase counterparts! You will be given a string containing two words separated by several spaces, as well as a positive integer number of seconds, *s*. Output what the string would look like after *s* seconds.
## Info
* Because words are abstract they have a different set of units and constants
+ Mass: **WMU** (Word Mass Unit) - equal to the mass of the letter 'a'.
+ Distance: **[em](https://en.wikipedia.org/wiki/Em_(typography))**, the length of one character.
+ Force: **NW** (Word Newton) = WMU · em/s2
+ Gravitational Constant: **G** = 1 Nw · (em/WMU)2
* The first character corresponds to the position 0 on the x-axis.
* All calculations should be done with as much precision as possible, only at the end do you round to the nearest em.
* You do not need to use calculus, you just need to recalculate the *F* every second, automatically apply the new acceleration to the velocity, and after a second apply the velocity to the position (see example).
* Once two words collide with each other (like `catdog` ), they don't move any further.
## Center of Mass
The [center of mass](https://en.wikipedia.org/wiki/Center_of_mass#Definition) of a word can be found with the formula:
[](https://i.stack.imgur.com/iBYeI.png)
Where *M* is the total mass of the word, *mi* is the mass of a letter, and *ri* is the position of the letter.
## Example:
**(Note: Although this example doesn't show it, remember that capital letters have twice the mass of their lowercase counterparts.)**
Input: `cat dog`, 2
1. First what are the positions of each word? "cat" starts at position 0 and "dog" starts at position 9, so
* xc = 0 and xd = 9
2. Next, let's find the center of mass of "cat".
* It has a mass of 24 WMU (3+1+20).
* Rc = 1/24(3\*0+1\*1+20\*2) = 41/24 = 1.70833 em
* So unsurprisingly the center of mass is very close to the letter 't'.
3. Now let's get the center of mass of "dog"
* Rd = 1/26(4\*9+15\*10+7\*11) = 263/26 = 10.11538 em
* So the center of mass for dog is close to the letter 'o', slightly towards 'g'.
4. Now we can calculate the force between the two words.
* F = 24\*26/(10.11538-1.70833)2 = 8.82871 Nw
5. Now we need to apply this force to both words and get their accelerations
* ac = 8.82871/24 = .36786 em/s2
* ad = -8.82871/26 = -.33957 em/s2
6. Following the rules above, we apply the acceleration to the velocity, so
* vc = .36786 em/s
* vd = -.33957 em/s
7. Then we apply the velocity to the position, so after one second,
* xc = .36786 em
* xd = 9 -.33957 = 8.66043 em.
* Rc = 1.70833+.36786 = 2.07619 em
* Rd = 10.11538-.33957 = 9.77581 em
8. Now we repeat the procedure one more time with the new positions:
* F = 24\*26/((9.77581)-(2.07619))2 = 10.52558 Nw
* ac = 10.52558/24 = .43857 em/s2, ad = 10.52558/26 = -.40483 em/s2
* vc = .36786 + .43857 = .80643 em/s, vd = -.33957 - .40483 = -.74440 em/s
* xc = .36786 + .80643 = 1.17429 em, xd = 8.66043 - .74440 = 7.91603 em
* Rc = 2.07619 + .80643 = 2.88262 em, Rd = 9.77581 - .74440 = 9.03141 em
9. So we end up with "cat" at x=1.17429 and "dog" at x=7.91603.
* We round those to the nearest integer so "cat" goes to position 1 and "dog" goes to position 8, so the output is `cat dog`
## Handling Collisions
Remember that the new acceleration is immediately added to the velocity every second. Therefore, if two words collide at certain time, use algebra to find the point of collision. Take this example:
* word 1 is 4 letters long (||w1|| = 4)
* word 2 is 4 letters long (||w2|| = 4)
* x1 = 3, x2 = 8
* v1 = 2,v2 = -6
Solve `3 + (4-1) + 2t = 8 - 6t`. t = .25s. The position of the collision is xcol = 6.5. Therfore, the collision should appear as occurring between x = 6 and x = 7, as such
`####@@@@` .
The explicit formula for the positions of the words after a collision is
* x1 = floor(xcol)-||w1||+1
* x2 = floor(xcol)+1
[Answer]
## Python 3, 556 bytes
Thanks to FryAmTheEggman and Sherlock9 for some bytes
```
s,E,a,b,e=str.split,enumerate,lambda c:ord(c)%32*-~c.isupper(),lambda w:sum(map(a,w)),' '
def j(w):z,y=map(len,s(w));h=w.count(e);return sum(i*a(x)for i,x in E(w)if i<z)/b(w[:z]),sum(i*a(x)for i,x in E(w)if i>=y+h)/b(w[-y:])
def f(w):x,v=j(w);m,n=map(b,s(w));return m*n/(x-v)**2
def q(w):x,v=s(w);return f(w)/b(x),-f(w)/b(v)
def p(w,t):
x,v=q(w);c,d=x,v;m,n=map(b,s(w));r,u=j(w);g,h=r,u;
for i in range(t):r+=x;u+=v;f=m*n/(r-u)**2;c,d=f/m,f/n;x+=c;v+=d
return int(r-g),int(1+h-u)
def g(w,t):x,y=p(w,t);u,v=s(w);return e*x+u+e*(len(w)-len(u+v)-x-y)+v+e*y
```
`g(w,t)` takes the string (`w`) and the time (`t`), and returns the result. The other functions are helpers.
[Try it online](http://ideone.com/fork/DbZuGy) (prints out `*`s instead of spaces so that it is more visible)
] |
[Question]
[
## Introduction
When solving a rubiks cube, one often write down the times like this
```
11.91, (11.28), (12.32)
```
This is called a average of 3, while a average of 5 looks like this
```
13.36, (11.89), 12.31, (16.44), 12.26
```
Note how the *worst* and *best* times have parenthesis around them. When calculating the average of `5` these times are removed. For an average of 3 the worst and best times are NOT removed. Similarly when calculating the standard deviation.
When taking the average of more than 12 cubes things start to get a bit harder. The general rule of thumb is:
**When solving fewer than 5 cubes, do not remove any times when calculating avg or std**
**When evaluating fewer than 12 times, remove the best and worst time when calculating avg or std**
**When evaluating fewer than 40 times remove the 1/12 worst and 1/12 best times rounded down the nearest integer.**
**When evaluating more than 40 times remove the 1/20 worst times and the 1/20 best times rounded down to the nearest integer.**
For an average of `100` this would mean we would remove the `(100/20) = 5` best solves and `(100/20) = 5` worst solves. Giving
```
14.88, 12.28, 13.76, 16.06, 13.82, 13.26, 14.57, 12.56, 15.02, 14.73,
13.87, 14.59, 15.17, (18.48), 12.09, 12.76, 11.65, 14.14, 12.83, 14.30,
13.28, 14.02, 12.55, 15.18, 13.65, 12.72, 14.86, 14.08, 15.07, 12.88, 13.78,
13.88, 14.63, 12.72, (10.10), 14.70, 12.82, 13.27, 13.82, 14.74, (11.22),
13.46, 12.66, 14.06, (10.58), 15.06, (18.27), 13.39, (17.88), (18.67),
15.38, 15.60, 14.24, 12.64, 15.51, 14.23, 16.71, 14.55, 14.32, 12.33, 11.90,
13.65, 13.69, 13.90, 13.15, (9.61), 12.91, 13.39, 11.77, 12.64, 15.22,
14.69, 12.76, 15.10, 11.91, (11.28), 12.32, 14.28, 14.46, 14.66, 14.15,
15.27, (17.73), 12.70, 14.58, 11.84, 13.25, 13.36, 13.26, 15.72, 14.15,
12.77, 15.26, 12.87, 12.96, 13.57, 14.50, 14.30, 14.57, 12.69
```
## The challenge
The problem at hand is to take a (large) list of numbers and figure out the best average or std of a subset of these.
**input**
```
list, n, avg or std
```
Write a program that takes in a list of numbers formated exactly as comma seperated numbers `12.91, 13.39, ...` or `[12.91, 13,39 ... ]` You can assume that the list only contains real valued positive numbers less than `2^32`.
A number `n` indicating how many numbers to average or take the std of, if `n=0` one should take the average / std of all the numbers.
A string `avg` or `std` indicating if one should return the lowest average of `n` numbers or the [lowest standard deviation (std)](https://revisionmaths.com/gcse-maths-revision/statistics-handling-data/standard-deviation). A negative `n` or a non integer should throw an error, blank or return false.
**Output**
The output should be exactly on the form
```
avg = ...
list of of numbers
```
or
```
std = ...
list of of numbers
```
As shown in the examples. Note that the best and worst times are marked with brackets as given by the rules above. **The function should return the `n` consecutive times with the *lowest* `avg` or `std`** At every 12 time, a newline should be inserted.
## Test case
I will use the following list of `200` numbers to base my tests on
```
15.86, 17.02, 24.01, 21.01, 15.93, 14.86, 18.43, 12.52, 18.48, 19.85, 13.01, 14.92, 13.07, 13.44, 13.07, 15.08, 12.70, 13.59, 15.22, 11.88, 13.26, 13.62, 12.85, 16.88, 15.78, 15.94, 14.88, 12.28, 13.76, 16.06, 13.82, 13.26, 14.57, 12.56, 15.02, 14.73, 13.87, 14.59, 15.17, 18.48, 12.09, 12.76, 11.65, 14.14, 12.83, 14.30, 13.28, 14.02, 12.55, 15.18, 13.65, 12.72, 14.86, 14.08, 15.07, 12.88, 13.78, 13.88, 14.63, 12.72, 10.10, 14.70, 12.82, 13.27, 13.82, 14.74, 11.22, 13.46, 12.66, 14.06, 10.58, 15.06, 18.27, 13.39, 17.88, 18.67, 15.38, 15.60, 14.24, 12.64, 15.51, 14.23, 16.71, 14.55, 14.32, 12.33, 11.90, 13.65, 13.69, 13.90, 13.15, 9.61, 12.91, 13.39, 11.77, 12.64, 15.22, 14.69, 12.76, 15.10, 11.91, 11.28, 12.32, 14.28, 14.46, 14.66, 14.15, 15.27, 17.73, 12.70, 14.58, 11.84, 13.25, 13.36, 13.26, 15.72, 14.15, 12.77, 15.26, 12.87, 12.96, 13.57, 14.50, 14.30, 14.57, 12.69, 15.21, 14.45, 14.90, 14.91, 15.66, 15.87, 14.79, 15.69, 17.37, 15.42, 12.11, 14.89, 13.39, 12.62, 13.42, 14.07, 14.85, 13.23, 14.05, 14.43, 13.36, 14.19, 14.16, 14.66, 12.02, 12.56, 12.69, 12.55, 14.36, 15.79, 12.53, 12.51, 12.15, 15.60, 13.42, 12.87, 13.02, 15.66, 13.18, 14.77, 13.57, 13.86, 12.26, 14.48, 14.68, 11.85, 14.82, 13.74, 13.85, 15.05, 14.78, 14.43, 12.72, 14.39, 15.06, 15.28, 12.06, 14.59, 15.49, 11.66, 14.83, 14.09, 11.62, 15.96, 14.77, 14.99, 14.20, 12.35, 17.62, 11.66, 13.46, 15.24, 14.85, 13.48
```
**Input 0:**
```
list, 3, avg
```
**Output 0:**
```
avg = 11.84
11.91, (11.28), (12.32)
```
**Input 1:**
```
list, 12, avg
```
**Output 1:**
```
avg = 12.88
(9.61), 12.91, 13.39, 11.77, 12.64, (15.22), 14.69, 12.76, 15.10, 11.91, 11.28, 12.32
```
**Input 2:**
```
list, 12, std
```
**Output 2:**
```
std = 0.44
15.21, 14.45, 14.90, 14.91, 15.66, 15.87, 14.79, 15.69, (17.37), 15.42, (12.11), 14.89
```
**Input 3:**
```
list, 0, std
```
**Output 3:**
```
std = 1.21
15.86, 17.02, (24.01), (21.01), 15.93, 14.86, (18.43), 12.52, (18.48), (19.85), 13.01, 14.92,
13.07, 13.44, 13.07, 15.08, 12.70, 13.59, 15.22, 11.88, 13.26, 13.62, 12.85, 16.88,
15.78, 15.94, 14.88, 12.28, 13.76, 16.06, 13.82, 13.26, 14.57, 12.56, 15.02, 14.73,
13.87, 14.59, 15.17, (18.48), 12.09, 12.76, (11.65), 14.14, 12.83, 14.30, 13.28, 14.02,
12.55, 15.18, 13.65, 12.72, 14.86, 14.08, 15.07, 12.88, 13.78, 13.88, 14.63, 12.72,
(10.10), 14.70, 12.82, 13.27, 13.82, 14.74, (11.22), 13.46, 12.66, 14.06, (10.58), 15.06,
(18.27), 13.39, (17.88), (18.67), 15.38, 15.60, 14.24, 12.64, 15.51, 14.23, 16.71, 14.55,
14.32, 12.33, 11.90, 13.65, 13.69, 13.90, 13.15, (9.61), 12.91, 13.39, (11.77), 12.64,
15.22, 14.69, 12.76, 15.10, 11.91, (11.28), 12.32, 14.28, 14.46, 14.66, 14.15, 15.27,
(17.73), 12.70, 14.58, 11.84, 13.25, 13.36, 13.26, 15.72, 14.15, 12.77, 15.26, 12.87,
12.96, 13.57, 14.50, 14.30, 14.57, 12.69, 15.21, 14.45, 14.90, 14.91, 15.66, 15.87,
14.79, 15.69, 17.37, 15.42, 12.11, 14.89, 13.39, 12.62, 13.42, 14.07, 14.85, 13.23,
14.05, 14.43, 13.36, 14.19, 14.16, 14.66, 12.02, 12.56, 12.69, 12.55, 14.36, 15.79,
12.53, 12.51, 12.15, 15.60, 13.42, 12.87, 13.02, 15.66, 13.18, 14.77, 13.57, 13.86,
12.26, 14.48, 14.68, 11.85, 14.82, 13.74, 13.85, 15.05, 14.78, 14.43, 12.72, 14.39,
15.06, 15.28, 12.06, 14.59, 15.49, (11.66), 14.83, 14.09, (11.62), 15.96, 14.77, 14.99,
14.20, 12.35, 17.62, (11.66), 13.46, 15.24, 14.85, 13.48
```
Split the lines at every 12 number.
**Input 4:**
```
list, 201, avg
```
**Output 5:**
```
Throw `Error` or `False`.
```
**Input 6:**
```
list, 1, avg
```
**Output 6:**
```
avg = 9.61
(9.61)
```
**Input 8:**
```
list, 1, std
```
**Output 8:**
```
std = 0
(15.86)
```
just return the first element of the list.
# Scoring
Submissions will be scored in **bytes**. I recommend [this website](http://bytesizematters.com) to keep track of your byte count, though you can use any counter you like. Like always whitespace counts as bytes.
Remove 25% of your byte count if your function has the ability to switch between highest avg and std, and lowest avg and std. Eg input on the form
```
list, n, avg / std, high / low
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score wins!
[Answer]
# Java 10, ~~944~~ ~~903~~ 861 bytes
```
import java.util.*;interface M{static void main(String[]a){var f=a[2];int n=new Short(a[1]),i=0,l,j,k;if(n<0)return;List<Double>L=new Stack(),t,r,R=L,u,U=L,S=L,V=L;for(var s:a[0].split(","))L.add(new Double(s));l=L.size();n=n<1?l:n;i=0;double m=99,M=m,q,Q,x,y,z;do{for(t=new Stack(),x=y=j=0;j<n;)t.add(L.get(i+j++));for(k=n<12?0:n<40?n/12:n/20,j=k=k<1?1:k,u=new ArrayList(t),r=new Stack();j-->0;){r.add(q=Collections.min(t));r.add(Q=Collections.max(t));if(n>4){t.remove(q);t.remove(Q);}}for(var T:t)x+=T;x/=k=n>4?n-2*k:n;if(x<m){m=x;R=r;U=u;}for(var T:t)y+=(z=T-x)*z;y=Math.sqrt(y/k);if(y<M){M=y;S=r;V=u;}}while(i++<l-n);j=f.charAt(0)-97;System.out.println(f+" = "+f.format(f="%.2f",q=j<1?n<2?Collections.min(L):m:n<2?0:M));i=0;for(var o:j<1?U:n<2?L.subList(0,1):V)System.out.print(f.format((j<1?R:S).remove(o)?"(%.2f)":f,n+j<2?q:o)+(++i<n&i%12>0?", ":"\n"));}}
```
Full program requirement, strict I/O formatting, validating.. sigh.. >.>
Verify all test cases: [3,avg](https://tio.run/##XVRdU@M6DP0rmc7snZi4xnYc56ums3PvY/sABV64PGQhhfQjpanLtnT47V3HchvYBxCRJZ2jI4lZ8V70Z8/z47Favq0a7c2Mg2x1tSAXeVXrspkWT6U3Pmx0oasn731VPXvLoqr9iW6q@uXhsUCH96Lxpqp44I9tileruvztTV5NOb94YI8IV4riBZ7heV5N/XpAUVPqbVPno2qjB/@ttr8W5dUIsnTxNPcR1rjBN2qEt/jO/J6Yn3s1yqerxm/BNlnxQB/J5m1Rab@HewiNSPH87LcVoJy/QShfqBHZVB@lj3LDacCGi6zODZf82cZ4S5WmeKyWeI2v8Q7v8Yd5ObQg@huZndqrmUmbDeocaYs0Ii@l9qtgFgQGqE2Ztwh8SLN6IOiwvmQ8qy85xTM1V3ODzbI53tqyP5um2Let@xrh5itSPuv3r2iODo0FWat/V4tF@aSrVb0hSyO6NmDwdv39rdjZt1beK4EOmjTlcvVe@muUn/@@Rvnn50nC20yjXaBu892lIWiShnWfX8xbgab@brBEh6Xa5Teqye/UNv@Wtg@U/6Fu@zt08ZHv1bjQr2SzNsPeX84thf1gjA5jtc8nJv2@Tf/8/VqZoVRBMFj0a9OnmpKn16L5qX2K@mmcT/YbXS7JaqvJm9krvaj9adDzlNcLpsSALwvtT1XvB@HTHl6rmRG0HvDh3/qMULbM2geajVs5zNBOzFdZm3RnX81abH/ZCVDMUHaP/ob3z6B@m3WTTdBJxRUa9vyWB@plU1wHM1Nvna1Q4AdBNaj/qX4wfkWHPez1st7/tdlN0/7xeGQRSST2WEwoxx4XhDJjmDXmLQ2NERCSENF@cRJx@EqMSUkSGRNCgiAph6/YGiG6r4jQxKbH1Dqj1Dp5m8BIklgnl9ZIbiNtaQlvEYnBpAIoQTEOebG0kRTSE94VEySKgbUEEtw64xAiYwgBLizuGuOEpkBXWoIyspFMADPQJYRWLAkBpQ1QBMWAmc0zVXgnpAAlItCFn3qPwSRQTIZdHiWMAmsKCa6/uOvWvAnLk8ObkDZSOjxpq0QOFqbp0sPUjt/CJkTCqEKIlADLoWkprDOCSfPQSh7DVwTyhCBBGFouKe0kMCa1xjmZcaZEMhufso4KI3H8FY5De/LLNCLQg0EeA/05gIvTNAS07hRgMBTbcwzTd5soQBazgrCsHNiGstuh6DQ@5oYJInHQOAG6KSREbqNotyDnFZRu5UEyAZKlEJLCwUnAc3sZQ4KEEYUAK0BjBlWStJOOw@GEECJgv8TpQjnsLAVYEXZtmsZSMF804@d9lh15fh6008U53T8GmKbTWtKOi1MphJquzRBuRICeTroQboSfrle4c3AzAnR3ADFMLAE811icdP2d7y5Mu82PTvtC5dfjF7B8bl/cgVPnBNap7OiaiYFmHG4yjOyMJO@quCuM4H7OcxDJMTwW7y9/AA) ; [12,avg](https://tio.run/##XVRdU@M6DP0rmc7snZi4xnYc56ums3PvY/sABV64PGQhhfQjpanLtnT47V3HchvYBxCRJZ2jI4lZ8V70Z8/z47Favq0a7c2Mg2x1tSAXeVXrspkWT6U3Pmx0oasn731VPXvLoqr9iW6q@uXhsUCH96Lxpqp44I9tileruvztTV5NOb94YI8IV4riBZ7heV5N/XpAUVPqbVPno2qjB/@ttr8W5dUIsnTxNPcR1rjBN2qEt/jO/J6Yn3s1yqerxm/BNlnxQB/J5m1Rab@HewiNSPH87LcVoJy/QShfqBHZVB@lj3LDacCGi6zODZf82cZ4S5WmeKyWeI2v8Q7v8Yd5ObQg@huZndqrmUmbDeocaYs0Ii@l9qtgFgQGqE2Ztwh8SLN6IOiwvmQ8qy85xTM1V3ODzbI53tqyP5um2Let@xrh5itSPuv3r2iODo0FWat/V4tF@aSrVb0hSyO6NmDwdv39rdjZt1beK4EOmjTlcvVe@muUn/@@Rvnn50nC20yjXaBu892lIWiShnWfX8xbgab@brBEh6Xa5Teqye/UNv@Wtg@U/6Fu@zt08ZHv1bjQr2SzNsPeX84thf1gjA5jtc8nJv2@Tf/8/VqZoVRBMFj0a9OnmpKn16L5qX2K@mmcT/YbXS7JaqvJm9krvaj9adDzlNcLpsSALwvtT1XvB@HTHl6rmRG0HvDh3/qMULbM2geajVs5zNBOzFdZm3RnX81abH/ZCVDMUHaP/ob3z6B@m3WTTdBJxRUa9vyWB@plU1wHM1Nvna1Q4AdBNaj/qX4wfkWHPez1st7/tdlN0/7xeGQRSST2WEwoxx4XhDJjmDXmLQ2NERCSENF@cRJx@EqMSUkSGRNCgiAph6/YGiG6r4jQxKbH1Dqj1Dp5m8BIklgnl9ZIbiNtaQlvEYnBpAIoQTEOebG0kRTSE94VEySKgbUEEtw64xAiYwgBLizuGuOEpkBXWoIyspFMADPQJYRWLAkBpQ1QBMWAmc0zVXgnpAAlItCFn3qPwSRQTIZdHiWMAmsKCa6/uOvWvAnLk8ObkDZSOjxpq0QOFqbp0sPUjt/CJkTCqEKIlADLoWkprDOCSfPQSh7DVwTyhCBBGFouKe0kMCa1xjmZcaZEMhufso4KI3H8FY5De/LLNCLQg0EeA/05gIvTNAS07hRgMBTbcwzTd5soQBazgrCsHNiGstuh6DQ@5oYJInHQOAG6KSREbqNotyDnFZRu5UEyAZKlEJLCwUnAc3sZQ4KEEYUAK0BjBlWStJOOw@GEECJgv8TpQjnsLAVYEXZtmsZSMF804@d9lh15fh6008U53T8GmKbTWtKOi1MphJquzRBuRICeTroQboSfrle4c3AzAnR3ADFMLAE811icdP2d7y5Mu82PTvtC5dfjF7B8bl/cgVPnBNap7OiaiYFmHG4yjOyMJO@quCuM4H7OcxDJkfFj8f7yBw) ; [12,std](https://tio.run/##XVRdU@M6DP0rmczsnXjjGttxnK@azs69j@0DFHjh8pCl7ZJ@pDR12ZYOv73rWG4D@wAisqRzdCQxL9/K3nyyOJ2q1eu60d7cOMhOV0vyvahqPW1m5fPUGx23utTVs/e2ribeqqzqYKybqv71@FSi41vZeDNVPvKnNsWrVT397Y1fTLmgfGRPCFeK4iWe40VRzYK6T1Ez1bumLobVVvf/W@9@LqfXQ8jS5fMiQFjjBt@qId7he/N7bH4e1LCYrZugBdvm5SN9ItvXZaUDH/sIDUk5mQRtBSgXbBEqlmpIttX7NECF4dRng2VeF4ZLMbEx3kplGR6pFd7gG7zHB/xuXo4tiP5CZq8Oam7S5v26QNoiDcmvqQ6qcB6GBqhNWbQIfEDzui/ooL5iPK@vOMVztVALg83yBd7Zsj@apjy0rQca4eYzUjHv9a5pgY6NBdmof9fL5fRZV@t6S1ZGdG3A4O3m61u5t2@tvNcCHTVppqv12zTYoOLy9w0qPj7OEt7lGu1DdVfsrwxBkzSoe/z7ohVoFuz7K3RcqX1xq5riXu2KL2mHUAXv6q63R9/fi4MalfqFbDdm2IerhaVw6I/QcaQOxdikP7TpH79fKjOUKgz7y15t@lQz8vxSNj90QFEvS4rxYaunK7LeafJq9kov62AW@p7y/HBGDPiq1MFM@d8In/l4o@ZG0LrPB3/rM0T5Km8faD5q5TBDOzNf523SvX01a7H7aSdAMUP5A/obPriABm3WbT5GZxXXaOAHLQ/k5zNch3NTb5OvURiEYdWv/6m@MX5NBz72/Nz/vza7ado/nU4sJqnEHksI5djjglBmDLPGvGWRMQJCUiLaL05iDl@pMRlJY2MiSBAk4/CVWCNE9xUTmtr0hFpnnFknbxMYSVPr5NIayW2kLS3hLSYJmEwAJSjGIS@RNpJCesq7YoLECbCWQIJbZxJBZAIhwIUlXWOc0AzoSktQxjaSCWAGukTQiiUhoLQBiqEYMLN5pgrvhBSgRAy68HPvCZgUismoy6OEUWBNIcH1l3TdmjdheXJ4E9JGSocnbZXYwcI0XXqU2fFb2JRIGFUEkRJgOTQthXXGMGkeWckT@IpBnggkiCLLJaOdBMZk1jgnM86MSGbjM9ZRYSRJPsNxaE9@mkYMejDIY6A/B3BxnoaA1p0CDIZie05g@m4TBchiVhCWlQPbSHY7FJ/Hx9wwQSQOGqdAN4OE2G0U7RbksoLSrTxIJkCyDEIyODgJeG4vE0iQMKIIYAVozKBKmnXScTicCEIE7Jc4XyiHnaUAK6KuTdNYBuaTZvyyz7Ijzy@Ddro4p/vHANN0WkvacXEqRVDTtRnBjQjQ00kXwY3w8/UKdw5uRoDuDiCBiaWA5xpL0q6/y91FWbf58XlfqPx8/AKWz@2LO3DqnMA6kx1dMzHQjMNNRrGdkeRdFXeFMdzPZQ4iPTF@2urJHw) ; [0,std](https://tio.run/##XVRdU@M6DP0rmczsnXjjGttxnK@azs69j@0DFHjh8pCl7ZJ@pDR12ZYOv73rWG4D@wAisqRzdCQxL9/K3nyyOJ2q1eu60d7cOMhOV0vyvahqPW1m5fPUGx23utTVs/e2ribeqqzqYKybqv71@FSi41vZeDNVPvKnNsWrVT397Y1fTLmgfGRPCFeK4iWe40VRzYK6T1Ez1bumLobVVvf/W@9@LqfXQ8jS5fMiQFjjBt@qId7he/N7bH4e1LCYrZugBdvm5SN9ItvXZaUDH/sIDUk5mQRtBSgXbBEqlmpIttX7NECF4dRng2VeF4ZLMbEx3kplGR6pFd7gG7zHB/xuXo4tiP5CZq8Oam7S5v26QNoiDcmvqQ6qcB6GBqhNWbQIfEDzui/ooL5iPK@vOMVztVALg83yBd7Zsj@apjy0rQca4eYzUjHv9a5pgY6NBdmof9fL5fRZV@t6S1ZGdG3A4O3m61u5t2@tvNcCHTVppqv12zTYoOLy9w0qPj7OEt7lGu1DdVfsrwxBkzSoe/z7ohVoFuz7K3RcqX1xq5riXu2KL2mHUAXv6q63R9/fi4MalfqFbDdm2IerhaVw6I/QcaQOxdikP7TpH79fKjOUKgz7y15t@lQz8vxSNj90QFEvS4rxYaunK7LeafJq9kov62AW@p7y/HBGDPiq1MFM@d8In/l4o@ZG0LrPB3/rM0T5Km8faD5q5TBDOzNf523SvX01a7H7aSdAMUP5A/obPriABm3WbT5GZxXXaOAHLQ/k5zNch3NTb5OvURiEYdWv/6m@MX5NBz72/Nz/vza7ado/nU4sJqnEHksI5djjglBmDLPGvGWRMQJCUiLaL05iDl@pMRlJY2MiSBAk4/CVWCNE9xUTmtr0hFpnnFknbxMYSVPr5NIayW2kLS3hLSYJmEwAJSjGIS@RNpJCesq7YoLECbCWQIJbZxJBZAIhwIUlXWOc0AzoSktQxjaSCWAGukTQiiUhoLQBiqEYMLN5pgrvhBSgRAy68HPvCZgUismoy6OEUWBNIcH1l3TdmjdheXJ4E9JGSocnbZXYwcI0XXqU2fFb2JRIGFUEkRJgOTQthXXGMGkeWckT@IpBnggkiCLLJaOdBMZk1jgnM86MSGbjM9ZRYSRJPsNxaE9@mkYMejDIY6A/B3BxnoaA1p0CDIZie05g@m4TBchiVhCWlQPbSHY7FJ/Hx9wwQSQOGqdAN4OE2G0U7RbksoLSrTxIJkCyDEIyODgJeG4vE0iQMKIIYAVozKBKmnXScTicCEIE7Jc4XyiHnaUAK6KuTdNYBuaTZvyyz7Ijzy@Ddro4p/vHANN0WkvacXEqRVDTtRnBjQjQ00kXwY3w8/UKdw5uRoDuDiCBiaWA5xpL0q6/y91FWbf58XlfqPx8/AKWz@2LO3DqnMA6kx1dMzHQjMNNRrGdkeRdFXeFMdzPZQ4iPdHTVk/@AA) ; [201,avg](https://tio.run/##XVRdU@M6DP0rmc7snZi4xnYc56ums3PvY/sABV64PGQhhfQjpanLtnT47V3HchvYBxCRJZ2jI4lZ8V70Z8/z47Favq0a7c2Mg2x1tSAXeVXrspkWT6U3Pmx0oasn731VPXvLoqr9iW6q@uXhsUCH96Lxpqp44I9tileruvztTV5NOb94YI8IV4riBZ7heV5N/XpAUVPqbVPno2qjB/@ttr8W5dUIsnTxNPcR1rjBN2qEt/jO/J6Yn3s1yqerxm/BNlnxQB/J5m1Rab@HewiNSPH87LcVoJy/QShfqBHZVB@lj3LDacCGi6zODZf82cZ4S5WmeKyWeI2v8Q7v8Yd5ObQg@huZndqrmUmbDeocaYs0Ii@l9qtgFgQGqE2Ztwh8SLN6IOiwvmQ8qy85xTM1V3ODzbI53tqyP5um2Let@xrh5itSPuv3r2iODo0FWat/V4tF@aSrVb0hSyO6NmDwdv39rdjZt1beK4EOmjTlcvVe@muUn/@@Rvnn50nC20yjXaBu892lIWiShnWfX8xbgab@brBEh6Xa5Teqye/UNv@Wtg@U/6Fu@zt08ZHv1bjQr2SzNsPeX84thf1gjA5jtc8nJv2@Tf/8/VqZoVRBMFj0a9OnmpKn16L5qX2K@mmcT/YbXS7JaqvJm9krvaj9adDzlNcLpsSALwvtT1XvB@HTHl6rmRG0HvDh3/qMULbM2geajVs5zNBOzFdZm3RnX81abH/ZCVDMUHaP/ob3z6B@m3WTTdBJxRUa9vyWB@plU1wHM1Nvna1Q4AdBNaj/qX4wfkWHPez1st7/tdlN0/7xeGQRSST2WEwoxx4XhDJjmDXmLQ2NERCSENF@cRJx@EqMSUkSGRNCgiAph6/YGiG6r4jQxKbH1Dqj1Dp5m8BIklgnl9ZIbiNtaQlvEYnBpAIoQTEOebG0kRTSE94VEySKgbUEEtw64xAiYwgBLizuGuOEpkBXWoIyspFMADPQJYRWLAkBpQ1QBMWAmc0zVXgnpAAlItCFn3qPwSRQTIZdHiWMAmsKCa6/uOvWvAnLk8ObkDZSOjxpq0QOFqbp0sPUjt/CJkTCqEKIlADLoWkprDOCSfPQSh7DVwTyhCBBGFouKe0kMCa1xjmZcaZEMhufso4KI3H8FY5De/LLNCLQg0EeA/05gIvTNAS07hRgMBTbcwzTd5soQBazgrCsHNiGstuh6DQ@5oYJInHQOAG6KSREbqNotyDnFZRu5UEyAZKlEJLCwUnAc3sZQ4KEEYUAK0BjBlWStJOOw@GEECJgv8TpQjnsLAVYEXZtmsZSMF804@d9lh15fh6008U53T8GmKbTWtKOi1MphJquzRBuRICeTroQboSfrle4c3AzAnR3ADFMLAE811icdP2d7y5Mu82PTvtC5dfjF7B8bl/cgVPnBNap7OiaiYFmHG4yjOyMJO@quCuM4H7OcxDJkVN2LN5f/gA) ; [1,avg](https://tio.run/##XVRdU@M6DP0rmc7snZi4xnYc56ums3PvY/sABV64PGQhhfQjpanLtnT47V3HchvYBxCRJZ2jI4lZ8V70Z8/z47Favq0a7c2Mg2x1tSAXeVXrspkWT6U3Pmx0oasn731VPXvLoqr9iW6q@uXhsUCH96Lxpqp44I9tileruvztTV5NOb94YI8IV4riBZ7heV5N/XpAUVPqbVPno2qjB/@ttr8W5dUIsnTxNPcR1rjBN2qEt/jO/J6Yn3s1yqerxm/BNlnxQB/J5m1Rab@HewiNSPH87LcVoJy/QShfqBHZVB@lj3LDacCGi6zODZf82cZ4S5WmeKyWeI2v8Q7v8Yd5ObQg@huZndqrmUmbDeocaYs0Ii@l9qtgFgQGqE2Ztwh8SLN6IOiwvmQ8qy85xTM1V3ODzbI53tqyP5um2Let@xrh5itSPuv3r2iODo0FWat/V4tF@aSrVb0hSyO6NmDwdv39rdjZt1beK4EOmjTlcvVe@muUn/@@Rvnn50nC20yjXaBu892lIWiShnWfX8xbgab@brBEh6Xa5Teqye/UNv@Wtg@U/6Fu@zt08ZHv1bjQr2SzNsPeX84thf1gjA5jtc8nJv2@Tf/8/VqZoVRBMFj0a9OnmpKn16L5qX2K@mmcT/YbXS7JaqvJm9krvaj9adDzlNcLpsSALwvtT1XvB@HTHl6rmRG0HvDh3/qMULbM2geajVs5zNBOzFdZm3RnX81abH/ZCVDMUHaP/ob3z6B@m3WTTdBJxRUa9vyWB@plU1wHM1Nvna1Q4AdBNaj/qX4wfkWHPez1st7/tdlN0/7xeGQRSST2WEwoxx4XhDJjmDXmLQ2NERCSENF@cRJx@EqMSUkSGRNCgiAph6/YGiG6r4jQxKbH1Dqj1Dp5m8BIklgnl9ZIbiNtaQlvEYnBpAIoQTEOebG0kRTSE94VEySKgbUEEtw64xAiYwgBLizuGuOEpkBXWoIyspFMADPQJYRWLAkBpQ1QBMWAmc0zVXgnpAAlItCFn3qPwSRQTIZdHiWMAmsKCa6/uOvWvAnLk8ObkDZSOjxpq0QOFqbp0sPUjt/CJkTCqEKIlADLoWkprDOCSfPQSh7DVwTyhCBBGFouKe0kMCa1xjmZcaZEMhufso4KI3H8FY5De/LLNCLQg0EeA/05gIvTNAS07hRgMBTbcwzTd5soQBazgrCsHNiGstuh6DQ@5oYJInHQOAG6KSREbqNotyDnFZRu5UEyAZKlEJLCwUnAc3sZQ4KEEYUAK0BjBlWStJOOw@GEECJgv8TpQjnsLAVYEXZtmsZSMF804@d9lh15fh6008U53T8GmKbTWtKOi1MphJquzRBuRICeTroQboSfrle4c3AzAnR3ADFMLAE811icdP2d7y5Mu82PTvtC5dfjF7B8bl/cgVPnBNap7OiaiYFmHG4yjOyMJO@quCuM4H7OcxDJkR2L95c/) ; [1,std](https://tio.run/##XVRdU@M6DP0rmczsnXjjGttxnK@azs69j@0DFHjh8pCl7ZJ@pDR12ZYOv73rWG4D@wAisqRzdCQxL9/K3nyyOJ2q1eu60d7cOMhOV0vyvahqPW1m5fPUGx23utTVs/e2ribeqqzqYKybqv71@FSi41vZeDNVPvKnNsWrVT397Y1fTLmgfGRPCFeK4iWe40VRzYK6T1Ez1bumLobVVvf/W@9@LqfXQ8jS5fMiQFjjBt@qId7he/N7bH4e1LCYrZugBdvm5SN9ItvXZaUDH/sIDUk5mQRtBSgXbBEqlmpIttX7NECF4dRng2VeF4ZLMbEx3kplGR6pFd7gG7zHB/xuXo4tiP5CZq8Oam7S5v26QNoiDcmvqQ6qcB6GBqhNWbQIfEDzui/ooL5iPK@vOMVztVALg83yBd7Zsj@apjy0rQca4eYzUjHv9a5pgY6NBdmof9fL5fRZV@t6S1ZGdG3A4O3m61u5t2@tvNcCHTVppqv12zTYoOLy9w0qPj7OEt7lGu1DdVfsrwxBkzSoe/z7ohVoFuz7K3RcqX1xq5riXu2KL2mHUAXv6q63R9/fi4MalfqFbDdm2IerhaVw6I/QcaQOxdikP7TpH79fKjOUKgz7y15t@lQz8vxSNj90QFEvS4rxYaunK7LeafJq9kov62AW@p7y/HBGDPiq1MFM@d8In/l4o@ZG0LrPB3/rM0T5Km8faD5q5TBDOzNf523SvX01a7H7aSdAMUP5A/obPriABm3WbT5GZxXXaOAHLQ/k5zNch3NTb5OvURiEYdWv/6m@MX5NBz72/Nz/vza7ado/nU4sJqnEHksI5djjglBmDLPGvGWRMQJCUiLaL05iDl@pMRlJY2MiSBAk4/CVWCNE9xUTmtr0hFpnnFknbxMYSVPr5NIayW2kLS3hLSYJmEwAJSjGIS@RNpJCesq7YoLECbCWQIJbZxJBZAIhwIUlXWOc0AzoSktQxjaSCWAGukTQiiUhoLQBiqEYMLN5pgrvhBSgRAy68HPvCZgUismoy6OEUWBNIcH1l3TdmjdheXJ4E9JGSocnbZXYwcI0XXqU2fFb2JRIGFUEkRJgOTQthXXGMGkeWckT@IpBnggkiCLLJaOdBMZk1jgnM86MSGbjM9ZRYSRJPsNxaE9@mkYMejDIY6A/B3BxnoaA1p0CDIZie05g@m4TBchiVhCWlQPbSHY7FJ/Hx9wwQSQOGqdAN4OE2G0U7RbksoLSrTxIJkCyDEIyODgJeG4vE0iQMKIIYAVozKBKmnXScTicCEIE7Jc4XyiHnaUAK6KuTdNYBuaTZvyyz7Ijzy@Ddro4p/vHANN0WkvacXEqRVDTtRnBjQjQ00kXwY3w8/UKdw5uRoDuDiCBiaWA5xpL0q6/y91FWbf58XlfqPx8/AKWz@2LO3DqnMA6kx1dMzHQjMNNRrGdkeRdFXeFMdzPZQ4iPbHTVk/@AA) ; [-1,either](https://tio.run/##XVRdU@M6DP0rmc7snZi4xnYc56ums3PvY/sABV64PGQhhfQjpanLtnT47V3HchvYBxCRJZ2jI4lZ8V70Z8/z47Favq0a7c2Mg2x1tSAXeVXrspkWT6U3Pmx0oasn731VPXvLoqr9iW6q@uXhsUCH96Lxpqp44I9tileruvztTV5NOb94YI8IV4riBZ7heV5N/XpAUVPqbVPno2qjB/@ttr8W5dUIsnTxNPcR1rjBN2qEt/jO/J6Yn3s1yqerxm/BNlnxQB/J5m1Rab@HewiNSPH87LcVoJy/QShfqBHZVB@lj3LDacCGi6zODZf82cZ4S5WmeKyWeI2v8Q7v8Yd5ObQg@huZndqrmUmbDeocaYs0Ii@l9qtgFgQGqE2Ztwh8SLN6IOiwvmQ8qy85xTM1V3ODzbI53tqyP5um2Let@xrh5itSPuv3r2iODo0FWat/V4tF@aSrVb0hSyO6NmDwdv39rdjZt1beK4EOmjTlcvVe@muUn/@@Rvnn50nC20yjXaBu892lIWiShnWfX8xbgab@brBEh6Xa5Teqye/UNv@Wtg@U/6Fu@zt08ZHv1bjQr2SzNsPeX84thf1gjA5jtc8nJv2@Tf/8/VqZoVRBMFj0a9OnmpKn16L5qX2K@mmcT/YbXS7JaqvJm9krvaj9adDzlNcLpsSALwvtT1XvB@HTHl6rmRG0HvDh3/qMULbM2geajVs5zNBOzFdZm3RnX81abH/ZCVDMUHaP/ob3z6B@m3WTTdBJxRUa9vyWB@plU1wHM1Nvna1Q4AdBNaj/qX4wfkWHPez1st7/tdlN0/7xeGQRSST2WEwoxx4XhDJjmDXmLQ2NERCSENF@cRJx@EqMSUkSGRNCgiAph6/YGiG6r4jQxKbH1Dqj1Dp5m8BIklgnl9ZIbiNtaQlvEYnBpAIoQTEOebG0kRTSE94VEySKgbUEEtw64xAiYwgBLizuGuOEpkBXWoIyspFMADPQJYRWLAkBpQ1QBMWAmc0zVXgnpAAlItCFn3qPwSRQTIZdHiWMAmsKCa6/uOvWvAnLk8ObkDZSOjxpq0QOFqbp0sPUjt/CJkTCqEKIlADLoWkprDOCSfPQSh7DVwTyhCBBGFouKe0kMCa1xjmZcaZEMhufso4KI3H8FY5De/LLNCLQg0EeA/05gIvTNAS07hRgMBTbcwzTd5soQBazgrCsHNiGstuh6DQ@5oYJInHQOAG6KSREbqNotyDnFZRu5UEyAZKlEJLCwUnAc3sZQ4KEEYUAK0BjBlWStJOOw@GEECJgv8TpQjnsLAVYEXZtmsZSMF804@d9lh15fh6008U53T8GmKbTWtKOi1MphJquzRBuRICeTroQboSfrle4c3AzAnR3ADFMLAE811icdP2d7y5Mu82PTvtC5dfjF7B8bl/cgVPnBNap7OiaiYFmHG4yjOyMJO@quCuM4H7OcxDJsc@OxfvLHw).
Here is the same as function with somewhat flexible I/O and without validating (still **~~776~~ ~~739~~ ~~719~~ 705 bytes**..):
```
import java.util.*;(L,n,f)->{int i=0,l=L.size(),j,k;List<Double>t,r,R=new Stack(),u,U=R,S=R,V=R;n=n<1?l:n;double m=99,M=m,q,Q,x,y,z;do{for(t=new Stack(),x=y=j=0;j<n;)t.add(L.get(i+j++));for(k=n<12?0:n<40?n/12:n/20,j=k=k<1?1:k,u=new ArrayList(t),r=new Stack();j-->0;){r.add(q=Collections.min(t));r.add(Q=Collections.max(t));if(n>4){t.remove(q);t.remove(Q);}}for(var T:t)x+=T;x/=k=n>4?n-2*k:n;if(x<m){m=x;R=r;U=u;}for(var T:t)y+=(z=T-x)*z;y=Math.sqrt(y/k);if(y<M){M=y;S=r;V=u;}}while(i++<l-n);j=f.charAt(0)-97;System.out.println(f+" = "+f.format(f="%.2f",q=j<1?n<2?Collections.min(L):m:n<2?0:M));for(var o:j<1?U:n<2?L.subList(0,1):V)System.out.print(f.format((j<1?R:S).remove(o)?"(%.2f)":f,n+j<2?q:o)+" ");}
```
-20 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##tVZbT@s4EH7nV1iVVopPXeM4jnOrQUe7j@Voub6s9iG0KaSXBFKX01Lx21nH4zbt0Ur7wiKB8Xgu33zzTWGWv@WD2WT@WS5f6kajmbnTtS4X9FuGzNf5OfozN/Z6ivRzgR63uhiM63Wlkdf3E3w2XuSrFbrKy2p3hlBZ6aKZ5uMC/WivCL3V5QSNvVG50sM/6vXjorhAI9L6oYqgW92U1ROa4sw4f5yZHyud63KMfqAKKfTpjUhFpnhwsWsDSsXIQo3oqnwvPExmZJ4d59WkITeqKn6atPl4bjzW5F7dkFvz/aBuskpVQ/9ykVbZxAagpUoScqWW5JVckw3ZknfzspvWjadP0mzUVs0Uy2bDKsOa5pOJN6JPhfbK/qzfxzhrQ@Ztdn7J0moo2GV17vO0OueMzNRczU1dP52TtU37vWnybQvc05g0x5Wy2WBwwTK8a2yRV/V7vVgUY13W1Youy8oE4Azerk/f8o19K6dedSHwTtOmWNZvhfeKs8Pv1zj7@GihvuUNuks13vTVXbY5NwBN0GU14N/mhhyTYzNc4t1SbbIb1WT3ap2dhG37yntXd4MN/vaebdVVrp/p6rXR3vZ8biFsh1d4d6W22a0Jf2jDP34@l4vC8NUfLgaV6VNN6fg5b75rj@FBEmW325UulrRea/piJKEXlTft94wEev0pNcWXufamqvcb5dMeeVUzQ2g15Je/8jPC6TJtH1h65ebSoq7TNuDevhj5rB8t@4z4OH3Av5b2DgW9NuomvcV7Bmt82fNaDLiXTknVn5l8r2mNDdKeIfczaxX8YrRlFOyEbPW/NNvhgdb/@jvHsBknK6GLlW4NpuNTiXTraG0rmq@s3Q9pLAnyI8o4QVxQ5pvDt4d5SwJzCHCJqWhvnIYcbrE5EhqH5gggQNCEwy2yhxDdLaQstuERs8YwsUbeBvg0jq2RS3tIbj1taglvIY3gSARAgmQc4iJpPRmEx7xLJmgYAWoJILg1RgF4RuACWPyoa4xTlgBcaQHK0Hr6ApABLwG0YkEISG0KhZAMkNk4k4V3RApgIgRe@L73CI4Yksmgi2PUZ4CaQYDrL@q6NW/C4uTwJqT1lK6etFlCVxam6cKDxI7flo2phFEF4CmhLIempbDGECbNA0t5BLcQ6AmAgiCwWBLWUWCOxB7O6BtjQqVv/RO/g@LTKDoux6E9eTSNEPjwIc4H/jkUF/tpCGjdMeDDUGzPEUzfKVEALUaCIFYOaAPZaSjcj893wwSSOHAcA9wEAkKnKNYJ5CBB6SQPlAmgLAGXBBZOQj2nywgCJIwogLICOPYhS5x01HFYnABcBOhL7DeUg2YZlBVB16ZpLIHjiDN@0LPswPPDoB0vzug@GGCajmvJOiyOpQByujYD2BEBfDrqAtgRvt9e4dbBzQiquwWIYGIx1HONRXHX32HvgqRTfrjXC5PHyy9AfE4vbsGZMwLqRHZwzcSAMw47GYR2RpJ3WdwWhrA/hzmI2PxJObOf3RUde/uPbIJMyV7@9tSz/8Ug9C9/y/7z5TShz/@XjCs9@bqM7KsT@l/e8zHCj7OPz38A)
**Explanation:**
```
import java.util.*; // Required import for List, Stack and Collections
interface M{ // Class
static void main(String[]a){// Mandatory main-method
var f=a[2]; // Save the third argument in String `f`
int n=new Short(a[1]), // Save the second argument as integer in `n`
i=0,l,j,k; // Some temp/index integers
if(n<0)return; // If `n` is negative: stop the program
List<Double>L=new Stack(),// Input-List, starting empty
t,r,R=L,u,U=L,S=L,V=L;
// Some temp Lists
for(var s:a[0].split(","))// Loop over the input-items as Strings
L.add(new Double(s)); // Convert them to doubles, and add them to the List
l=L.size(); // Set `l` to the amount of items
n=n<1?l:n; // If `n` was 0, make it equal to `l` instead
double m=99,M=m, // Lowest `avg` and `std`, both starting at 99
q,Q,x,y,z; // Some temp floats
do{ // Start the do-while:
for(t=new Stack(), // Reset List `t`
x=y=j=0;j<n;) // Loop `j` in the range [0, `n`):
t.add(L.get(i+j++)); // And add the items on index `i+j` of List `L` to `t`
for(k=n<12? // If `n` is smaller than 12
0 // Set `k` to 0
:n<40? // Else-if `n` is in the range [12; 40)
n/12 // Set `k` to 1/12th of `n`
: // Else (`n` is 40 or larger)
n/20, // Set `k` to 1/20th of `n`
j=k=k<1?1:k, // If `k` is 0 due to rounding, make it 1 instead
u=new ArrayList(t), // Copy List `t` to `u`
r=new Stack(); // And reset List `r`
j-->0;){ // Loop `k` amount of times:
r.add(q=Collections.min(t));
// Add the smallest item in List `t` to `r`
r.add(Q=Collections.max(t));
// as well as the largest item
if(n>4){ // If `n` is 5 or larger:
t.remove(q);t.remove(Q);}}
// Remove those two items from List `t`
for(var T:t) // Loop over List `t`:
x+=T; // And sum them all into value `x`
x/=k=n>4? // If `n` is 5 or larger
n-2*k // Set `k` to `n-2*k` and divide `x` by that
: // Else:
n; // Set `k` to `n` and divide `x` by that
if(x<m){ // If `x` is smaller than the previous smallest avg `m`
m=x; // Replace `m` with `x` (smallest avg)
R=r; // Replace `R` with `r` (items between parenthesis)
U=u;} // And replace `U` with `u` (all `n` items in this avg)
for(var T:t) // Loop over List `t` again:
y+=(z=T-x)*z; // And sum `(T-x)**2` to `y`
y=Math.sqrt(y/k); // Also divide `y` by `k`, and take its square-root
// The process above is how you calculate the std
if(y<M){ // If `y` is smaller than the previous smallest std `M`:
M=y; // Replace `M` with `y` (smallest std)
S=r; // Replace `S` with `r` (items between parenthesis)
V=u;}} // And replace `V` with `u` (all `n` items in this std)
while(i++<l-n); // Continue the do-while as long as `i` is smaller than `l-n`
j=f.charAt(0)-97; // Set `j` to the alphabetic index of the first letter of `f`
System.out.println(f+" = "// Print "`f` = "
+f.format(f="%.2f", // Round to two decimals
q=j<1? // If it's an avg:
n<2? // And `n` is 1:
Collections.min(L)// Simply take the smallest value in `L`
: // Else:
m // Take the calculated lowest avg `m`
: // Else (it's an std):
n<2? // If `n` is 1:
0 // Use 0
: // Else:
M)); // Take the calculated lowest std `M`
i=0; // Reset `i` to 0
for(var o:j<1? // If it's an avg:
U // Loop over List `U`
: // Else (it's an std instead):
n<2? // If `n` is 1:
L.subList(0,1)// Only take the first item of List `L`
: // Else:
V) // Loop over List `V`
System.out.print(f.format(
(j<1? // If it's an avg:
R // Use List `R`
: // Else (it's an std instead):
S) // Use List `S`
.remove(o)? // If the current item is in this List:
"(%.2f)" // Round to two decimals, and add parenthesis
: // Else:
f, // Only round to two decimals
n+j<2? // If it's an avg, and `n` is 1:
q // Take the smallest value in `L`
: // Else:
o) // Take the current item in this loop
+(++i<n // If it's not the last item,
&i%12>0? // and also not the 12th item of the row:
", " // Append a comma and space as separator
: // Else:
"\n"));}} // Append a newline instead
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 85.5 (114 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) - 25% bonus)
† Could be **score: 83.25 (111 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) - 25% bonus)** by removing `2.ò` (which rounds the output avg/std to 2 decimals). This isn't mentioned in the challenge rules, but since everything else about the I/O is so strict and rounding to two decimals is also done by the WCA (World Cube Association), I've just included it.
```
DŒsgI‚²ĀèDUùεƵJü2XŽ4Ý2ô@ÏXšzX*òθFDWsà‚vyD…(ÿ).;}}Dʒ'(å≠X5‹~}žuмDÅA©-nÅAt®‚³Çθè‚}Σθ}|θÇнƵ7.Sè`2.ò³'=‚sªs12ô»»¹gݲå×
```
Also supports `low` vs `high` as fourth input. At the cost of just 8 bytes (`|θÇнƵ7.Sè` instead of `н`), this was well worth the 25% bonus.
Outputs an empty string for invalid \$n\$.
[Try it online](https://tio.run/##TVRNa5NBEL73V/TWKs2yOzv7hQgKQdCriAERrCBFKO0hWmkxkosUT0IvglBQpFI9eEgttNgqvGt68BD6G/JH4nafTTb0MN155@OZ55nJZnf16fNnk0l7uNdduzvuf2wGf/vxsP0gno6OL47vxTPqDM857lP8eSu@7ww/73Sux8Ho5E77YTd@Sglb2@1x/@ty/HNN3Oj12v/2lpbjwfjdp44Z90/f9Ia/X16etePb28231kYyL5ofV12O4u7oJB6mf3ujL6OT3uv02r08vzh24n48fEIiDpqjpZvpe7f53lWpe/Mr/Z2uxf1mEA/ih8nkkTLC25VF5YSklUViIVUyKpv0LehkGCFe8NWLhCG8fDJBeJOMRgKLQHi5bJjrywjpc7qT2WlCdtJVghLeZyfZbCzlyFza4psRDiYwIKEYIc/ZHCmR7qkWY2EcUFuAoOx0GpEOIcCiXB2MhAyAazNAa3KkYiADLxqjZBCM0qmRQTEgy3mpClUiGUwY8ELT2R2MRzGra54USgK1REKZz9Vp0zfOOAnf2OZIW/rZXMWUtlCzpOuQ5c9tvbCQSiPSoi1haMvZaaA06Uy5w8uAHg0KtM5YgqwUJBOyKU6VnEFYleODqlCUcG6@HWE8O6eGAR8KeQr8E5rzVA3G6IUBBVHyzA7ql01k0JJWEMtKQKtt3SEzlU8VMUESgWMPuAEJpmyUrAsyW0FbVh6UMSgLCAk4OIt@ZS8dEiwk0mjL4Fihig@VOsLhaIQw9ounF0rYWYm2rOuYabAAM8cZzfbZVvA0E7rwUpzlhwFqFq6trFgKSxo1y5gaN8Lgs1CncSM0vV4u51A0QvdyAA6KefQrgzlf55vdnQ518810X6SdP37G8pV9KQcuixOog61wk2LgjHCT2mSNLNUq5QoN7memA/vHC3phdWttYX3z1aTV2thsra/ubP8H) or [verify all test cases](https://tio.run/##bVRdS5RBFL73Vyx7o8XuMHPm651CLFiCuukiIkEEjWIVRINVQ2HDG4uuAm@CQDDCsC4KFg0lLdhJLwoWf4N/ZBvnmd1ZP9iLw5z3fDznec7Zhcb009nn3eV2q3x//sXSYuNWqTy2Mvrv9VD54dJicIR3pVs73mjU29@nTo/O1j5E@2fN79Qe@4PO3sneA39I48dHym@S373j340ff1wdv@lbnf17tScNvxVylldqZ2ufR/zvG@x2s1n7uzE84rfP3m6N67O1g1fN419Lp4c1v363/aU6H8xi@xsa@fWGf9PZ9zvh2ex86uw3gzO835wenexZ9sjvTBHzLUQOj4aoRvtrQwQc7Z/h16r7zQjXb/v33Ur7x1h7tzsxISvl6eV6uVKeW3hZnqxMCLrG0Vh8lh380pu4uJxy9X0ho3q5R3l2fnl6bvY8ZNBfyuhmZuszF@ENelC95@GXHQMI@1nXOC4mVa90uoISHyaHJoRmhamUhGWcKiVSLDQskYgmfHMyGIWQgqnzFzFNeBXBOFboYCQSFHOEl41GqfzSjBcx3fLo1C466TxBsKKITjLRGIqRsbTBN80sjFOAhGKEPGtiJEd6QbmYYtoCtQEIik4rEWkRAizC5sGIcQe4JgI0OkYKBWTgRWKUCEKhdGikUQzIYl6oQplIBSY0eKHe7BamQDEjcx5nggM1R0Kaz@ZpwzcVcRK@KRMjTepnYhWd2kLNlC5dlD@2LZiBVBKRBm0JQxsVnRpKk4yUW7w06JGgQMqIxfFMQTAumuQUwemYETHeiQxFMGsH2xHGMwNqaPAhkCfAP6G56qmhMHpiQECUOLOF@mkTFWgJK4hlJaCVJu@Q7sknkpggicBxAbgOCTptFM8L0l9Bk1YelClQ5hDicHAG/dJeWiQYSCTRVoFjgSqFy9QRDkciRGG/VO9CCTvL0VbJPGYYzMEMcEb9fTYZPPWFTrwkZ/pjgJqJa8MzlsSSRM00psSNKPCZqJO4Eepdr0rnkDRC93QAFooV6JcGs0Wer3930uXN17194Wbw@BWWL@1LOnCenEDtTIYbFANnhJuUOmpkKFdJV6hxP30dVDHZrVbnF6pz06sr/wE).
**Explanation:**
```
D # Duplicate the first (implicit) input-list
Œ # Pop the copy, and get all its sublists
sgI‚²Āè # Transform n=0 to n=listLength
s # Swap so the first input-list is at the top again
g # Pop and push its length
I‚ # Pair it with the second input-integer `n`
² # Push the second input-integer `n` again
Ā # Check whether it's NOT 0 (0 if 0; 1 otherwise)
è # 0-base index this into the pair
DU # Store a copy in variable `X`
ù # Only keep the subslist of that size
ε # Map over each sublist
ƵJü2XŽ4Ý2ô@ÏXšzX*òθ # Determine how many lowest/highest numbers we should surround
# with parenthesis:
ƵJ # Push compressed integer 120
ü2 # Get its overlapping pairs: [12,20]
X # Push value `X`
Ž4Ý # Push compressed integer 1240
2ô # Split it into pairs: [12,40]
@ # >= check on `X`: [X>=12,X>=40]
Ï # Keep the [12,20]-values at the truthy indices
Xš # Prepend `X` itself to this list
z # Calculate 1/v for each value in this list
X* # Multiply each by `X`
ò # Round each to the nearest integer
θ # Pop and keep the last one
F # Loop that many times:
D # Duplicate the current sublist
W # Push its minimum (without popping)
# (will ignore values already wrapped in parenthesis)
s # Swap so the copy of the sublist is at the top again
à # Pop and push its maximum
# (will ignore values already wrapped in parenthesis)
‚ # Pair this minimum and maximum together
v # Loop over this pair:
yD # Push the min or max twice
…(ÿ) # Surround the top copy in parenthesis
.; # Replace the first occurrence of this value in the sublist
} # Close the [min,max]-loop
} # Close the other loop
D # Duplicate the modified sublist
ʒ # Filter the copy by:
'(å≠ '# Check that the current value does NOT contain parenthesis
~ # OR
X5‹ # Whether `X` is smaller than 5
} # Close the filter
žu # Push constant string "()<>[]{}"
м # Remove all those characters from each value within the list
# (only applies if `X` is smaller than 5)
DÅA©-nÅAt®‚ # Pop this list, and push its [std,avg] pair:
D # Duplicate this list
ÅA # Pop the copy, and get its average
© # Store this average in variable `®` (without popping)
- # Subtract this average from each value in the list
n # Square each
ÅA # Take the average of this list again
t # Take the square-root of that
®‚ # And pair this std with the average `®`
³ # Push the third input-string
Ç # Convert it to a list of codepoint integers
# ("avg"=[97,118,103]; "std"=[115,116,100])
θ # Pop and push the last value ("avg"=103; "std"=100)
è # Use that to 0-based modular index into the pair of [std,avg]
‚ # And pair it together with the modified list
} # Close the map
Σ # Sort this list by:
θ # The last item of the pair (the avg or std)
} # Close the sort-by
| # Get a list of all remaining inputs: [third,fourth]
θ # Pop and keep its last item (the fourth input)
# (`|θ` cannot be `I`, since `³` won't add the third input to the
# input history)
Ç # Convert it to a list of codepoint integers as well
# ("low"=[108,111,119]; "high"=[104,105,103,104])
н # Pop and push the first value ("low"=108; "high"=104)
Ƶ7 # Push compressed integer 108
.S # Compare: -1 if <108; 0 if ==108; 1 if >108
# (aka "low"=0; "high"=-1)
è # Use that to 0-based modular index into the sorted list
# (where -1 will take the last/highest item)
` # Pop the pair and push its contents to the stack
2.ò # Round the avg/std to 2 decimals†
³ # Push the third input-string again
'=‚ '# Pair it with an "="
sª # Swap and append the rounded avg/std
s # Swap so the list is at the top
12ô # Split it into parts of size 12
» # Join each inner list by spaces, and then each string by newlines
» # Join the two strings on the stack with newline delimiter
¹gݲå× # Transform it to an empty string if `n` is invalid:
¹g # Push the length of the first input-list
Ý # Pop and push a list in the range [0,listLength]
²å # Check if the second input `n` is in this list
# (1 if truthy; 0 if falsey)
× # Repeat the string that many times
# (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 `ƵJ` is `120`; `Ž4Ý` is `1240`; and `Ƶ7` is `108`.
] |
[Question]
[
The idea of this challenge is simple: create a bot to play the card game Euchre.
For those of you who don't already know them, I've written out the rules to Euchre [here](https://drive.google.com/file/d/0B0S-KjeVoiwPeUdOV280QmZvWHc/view?usp=sharing) as they pertain to this challenge.
I recommend using python or something similar, but the only real restriction is that it has to be compatible with the controller code
### Input:
Your euchre bot will get different kinds of input depending on the current phase of the game or round. Generally speaking, you'll get the game phase on the first line followed by a comma and a the number of points your team has, and then the relevant data on the following lines.
Chronologically, your bot will get input in the following order:
```
Ordering Trump:
js,ah,qc,ts,jc // the cards in your hand
2 // number of points your team has
0 // number of tricks your team has taken
ordering // the phase of the game
th // the turned up card
p,p // each previous player’s decision
Naming Trump:
js,ah,qc,ts,jc // the cards in your hand
2 // number of points your team has
0 // number of tricks your team has taken
naming // the phase of the game
p // each previous player’s decision
Dealer Discarding:
js,ah,qc,ts,jc // the cards in your hand
2 // number of points your team has
0 // number of tricks your team has taken
discard // the phase of the game
th // the card you will pick up
Going alone:
js,ah,qc,ts,jc // the cards in your hand
2 // number of points your team has
0 // number of tricks your team has taken
alone // the phase of the game
h // the trump suit
n,n // each previous player’s decision
Your turn:
js,ah,qc,ts,jc // the cards in your hand
2 // number of points your team has
0 // number of tricks your team has taken
turn // the phase of the game
h // the trump suit
td,8h,p // each previous player’s card
Trick data:
// the cards in your hand (none, since this happens at the end of a trick)
2 // number of points your team has
1 // number of tricks your team has taken
trick // the phase of the game
0 // the index of the following list that is your card
js,tc,4d,js // the cards played during the trick in the order they were played
```
### Output:
Your euchre bot will have different outputs depending on the current phase of the game or round.
```
Ordering Trump:
p //for pass
OR
o //for order up
Naming Trump:
p //for pass
OR ANY OF
c,s,h,d //the suit you want to name
Going alone:
n // no
OR
y // yes
Your turn:
js //the card you want to play
```
### Scoring:
Your bot's score is the total number of games it wins.
Your bot will play against every other bot, and it will always be partnered with a copy of itself.
### Notes:
Here's a simple template in python2.7:
```
#!/usr/bin/python2.7
import sys
data = sys.stdin.readlines()
hand = data[0].strip().split(',') # Hand as a list of strings
points = int(data[1]) # Number of points
tricks = int(data[2]) # Number of tricks
out = ''
if data[3] == 'ordering':
card = data[4] # The upturn card
prev = data[5].strip().split(',') # The previous player's decisions as a list
# Ordering logic
out = # 'o' or 'p'
elif data[3] == 'naming':
prev = data[4].strip().split(',') # The previous player's decisions as a list
# Naming logic
out = # 'p', 'h', 's', 'c', or 'd'
elif data[3] == 'discard':
card = data[4] # The card you'll take
# Discarding logic
out = # The card you want to discard
elif data[3] == 'alone':
trump = data[4] # The trump suit
prev = data[5].strip().split(',') # The previous player's decisions as a list
# Alone logic
out = # 'y' for yes, 'n' for no
elif data[3] == 'turn':
trump = data[4] # The trump suit
prev = data[5].strip().split(',')
# Turn logic
out = # The card you want to play
elif data[3] == 'trick':
trump = data[5]
cards = data[6].strip().split(',')
my_card = cards[int(data[4])]
# Data logic
print(out)
```
1. There will always be 4 total responses. If someone goes alone, then their partner's response will be "p" on their turn.
2. I tried to shave down the amount of redundant input, so to be extra clear:
2a. Both your position relative to the dealer/leader and the card your partner played can be determined by the number of previous outputs.
There is 1 player between you and your partner. There
For instance, if you get "td,8h,p" as the last line on your turn, you can see that your partner played an 8h, and the other team has a player that is going alone.
3. If you are curious, the deal is done in the traditional way (in two rounds alternating packets of 2 and 3 cards) but that's not really relevant to your bot, so...
4. If the second player decides to order up in the trump phase, that phase will continue, but their outputs will pretty much be ignored. In other words, whoever orders up first is on the Namers team regardless of any other output.
5. The following are the defaults for the various game phases. If you don't output a valid response for that round, then your response is changed to what's below.
Ordering Trump: p
Naming Trump: p
Discarding: (the first card in your hand)
Going Alone: n
Your Turn: (the first legal card in your hand)
6. [Here's](https://drive.google.com/file/d/0B0S-KjeVoiwPd3Y2Mm4wckJENXc/view?usp=sharing) the controller code for your testing purposes.
6a. Notice you can pass in either 2 or 4 bot names, if you give it 4 bots then they get partnered up randomly, and with 2 they are partnered up with copies of themselves.
6b. You need a 'bots' directory in the same directory as the controller code, and your bot code needs to be in the bots directory.
7. For those that want their bot to remember what cards were played, you are given the opportunity during the "trick" phase, which tells your bot which cards were played. You can write to a file in the bots directory as long as that file doesn't exceed 1kb.
### Scoreboard:
```
Old Stager: 2
Marius: 1
Random 8020: 0
```
[Answer]
# Marius
I wrote that bot in R. I did some tests with your controller and they seem to communicate correctly.
```
#!/usr/bin/Rscript
options(warn=-1)
infile = file("stdin")
open(infile)
input = readLines(infile,5)
hand = strsplit(input[1],",")[[1]]
phase = input[4]
if(!phase%in%c("discard","naming")) input = c(input,readLines(infile,1))
other_o = c("a","k","q","j","t","9")
alone = "n"
ord = "p"
trumpify = function(color){
tr_suit = switch(color,
"c" = c("c","s",rep("c",5)),
"s" = c("s","c",rep("s",5)),
"h" = c("h","d",rep("h",5)),
"d" = c("d","h",rep("d",5)))
paste(c("j","j","a","k","q","t","9"),tr_suit,sep="")
}
if(phase%in%c("ordering","alone")){
flip = input[5]
if(phase=="ordering") trump = trumpify(substr(flip,2,2))
if(phase=="alone") trump = trumpify(flip)
hand_value = sum((7:1)[trump%in%c(hand,flip)])
if(hand_value>13) ord = "o"
if(hand_value>18) alone = "y"
if(phase=="alone") cat(alone)
if(phase=="ordering") cat(ord)
}
if(phase=="naming"){
name = "p"
colors = unique(substr(hand,2,2))
col_values = sapply(colors,function(x)sum((7:1)[trumpify(x)%in%hand]))
if(any(col_values>13)){name = colors[which.max(col_values)]}
cat(name)
}
if(phase=="discard"){
flip = input[5]
new_hand = c(hand,flip)
trump = trumpify(substr(flip,2,2))
discardables = new_hand[!new_hand%in%trump]
if(length(discardables)){
val = sapply(substr(discardables,1,1),function(x)(6:1)[other_o==x])
d = discardables[which.min(val)]
}else{d = tail(trump[trump%in%new_hand],1)}
cat(d)
}
if(phase=="turn"){
trump = trumpify(input[5])
fold = strsplit(gsub("[[:punct:]]","",input[6]),",")[[1]]
if(length(fold)&!any(is.na(fold))){
fold_c = substr(fold[1],2,2)
f_suit = if(fold_c!=input[5]){paste(other_o,fold_c,sep="")}else{trump}
l = length(f_suit)
current = (l:1)[f_suit%in%fold]
if(any(hand%in%f_suit)){
playable = hand[hand%in%f_suit]
val = sapply(playable,function(x)(l:1)[f_suit==x])
if(all(max(val)>current)){
play = playable[which.max(val)]
}else{play = playable[which.min(val)]}
}else if(any(hand%in%trump)){
playable = hand[hand%in%trump]
val = sapply(playable,function(x)(7:1)[trump==x])
if(!any(fold%in%trump)){
play = playable[which.min(val)]
}else{
trumped = fold[fold%in%trump]
val_o = max((7:1)[trump%in%trumped])
play = ifelse(any(val>val_o), playable[which.min(val[val>val_o])], playable[which.min(val)])
}
}else{
val = sapply(substr(hand,1,1),function(x)(6:1)[other_o==x])
play = hand[which.min(val)]
}
}else{
col = c("c","s","h","d")
non_tr = col[col!=input[5]]
aces = paste("a",non_tr,sep="")
if(any(hand%in%aces)){
play = hand[hand%in%aces][1]
}else if(any(hand%in%trump)){
playable = hand[hand%in%trump]
val = sapply(playable,function(x)(7:1)[trump==x])
play = playable[which.max(val)]
}else{
val = sapply(substr(hand,1,1),function(x)(6:1)[other_o==x])
play = hand[which.max(val)]
}
}
cat(play)
}
```
I'll probably modify it later since I didn't implement a "turn" logic for when the bot is defending, but I'm posting it now so that people have another bot to test against.
For now, it only implements very basic strategies such as leading with an ace, a trump or any other high card; following with a higher card when possible or playing the lowest valued card if not; ordering when hand has high value and naming the color in which the hand would have had the highest value; going alone when hand has very high value. The "value" of each card is computed very simply: value of trumps starts from 7 for the first jack and decreases along the trump suit.
[Answer]
# Old Stager
This bot follows some simple rules which served him well for a long time:
* Intuitively assign a score to each card
* Choose the trump if the hand score is good enough
* In case of a really good hand play alone
* Choose best card when playing first
* Choose a better card than the opponents if they are winning
* Choose worst card if the partner is winning or if winning is not possible
I increased the target score from 10 to 100 for testing in the controller. The results are still very random, but way more stable than before.
```
#!/usr/bin/python2.7
from __future__ import print_function
import sys, re, math
base = 1.2
playThreshold = 27.0
aloneThreshold = 36.0
sameColor = { 'd' : 'h', 'h' : 'd', 's' : 'c', 'c' : 's' , '' : '', 'n' : 'n' }
cardValue = { 'p' : 0, '9' : 1, 't' : 2, 'j' : 3, 'q' : 4, 'k' : 5, 'a' : 6 }
class Card(object):
def __init__(self, name, trump):
self.name = name
self.value = cardValue[name[0:1]]
self.suit = name[1:2]
self.trump = False
self.updateScore(trump)
def updateScore(self, trump):
self.score = self.value
if self.suit == trump:
self.trump = True
self.score += 6
if self.value == 3:
if self.suit == trump:
self.score = 14
if self.suit == sameColor[trump]:
self.trump = True
self.score = 13
class Cards(object):
def __init__(self, cards, trump):
self.list = []
self.score = 0.0
if cards:
for c in cards.split(','):
self.append(Card(c, trump))
def append(self, card):
self.list.append(card)
self.score += math.pow(base, card.score)
def updateScore(self, trump):
self.score = 0.0
for card in self.list:
card.updateScore(trump)
self.score += math.pow(base, card.score)
def best(self):
card = self.list[0]
for i in self.list[1:]:
if i.score > card.score:
card = i
return card
def worst(self):
card = self.list[0]
for i in self.list[1:]:
if i.score < card.score:
card = i
return card
def better(self, ref):
card = None
for i in self.list:
if i.score > ref.score and (card is None or i.score < card.score):
card = i
return card
def ordering(hand, card, decisions):
if len(decisions) == 3:
hand.append(card)
return 'o' if hand.score > playThreshold else 'p'
def naming(hand):
result = 'p'
score = playThreshold
for trump in ['d', 'h', 's', 'c']:
hand.updateScore(trump)
if hand.score > score:
result = trump
score = hand.score
return result
def turn(hand, decisions):
bestIndex = -1
for i, d in enumerate(decisions.list):
if d.suit:
bestIndex = i
break
if bestIndex == -1:
return hand.best()
else:
suit = decisions.list[bestIndex].suit
for i in range(2, len(decisions.list)):
if (decisions.list[i].suit == suit or decisions.list[i].trump) and decisions.list[i].score > decisions.list[bestIndex].score:
bestIndex = i
matching = Cards('', '')
for card in hand.list:
if card.suit == suit:
matching.append(card)
if not matching.list:
if bestIndex == len(decisions.list) - 2:
return hand.worst()
for card in hand.list:
if card.trump:
matching.append(card)
if not matching.list:
return hand.worst()
if bestIndex == len(decisions.list) - 2:
return matching.worst()
card = matching.better(decisions.list[bestIndex])
if card:
return card
return matching.worst()
output = ''
input = re.split('\n', re.sub(r'[^a-z0-9,\n]+', '', sys.stdin.read()))
if input[3] == 'ordering':
output = ordering(Cards(input[0], input[4][1:2]), Card(input[4], input[4][1:2]), input[5].split(','))
elif input[3] == 'naming':
output = naming(Cards(input[0], 'n'))
elif input[3] == 'discard':
output = Cards(input[0], input[4][1:2]).worst().name
elif input[3] == 'alone':
output = 'y' if Cards(input[0], input[4]).score > aloneThreshold else 'n'
elif input[3] == 'turn':
output = turn(Cards(input[0], input[4]), Cards(input[5], input[4])).name
print(output)
```
[Answer]
# Random 8020
A simple random bot, which will pass 80% of the time. Uncomment the last line to see the (cleared up) input and output.
```
#!/usr/bin/python2.7
from __future__ import print_function
import sys, re, random
output = ''
input = re.split('\n', re.sub(r'[^a-z0-9,\n]+', '', sys.stdin.read()))
hand = input[0].split(',')
if input[3] == 'ordering':
output = random.choice(['p', 'p', 'p', 'p', 'o'])
elif input[3] == 'naming':
output = random.choice(['p', 'p', 'p', 'p', random.choice(hand)[1:2]])
elif input[3] == 'discard':
output = random.choice(hand)
elif input[3] == 'alone':
output = random.choice(['n', 'n', 'n', 'n', 'y'])
elif input[3] == 'turn':
output = random.choice(hand)
if input[5]:
suited = filter(lambda x: input[5][1:2] in x, hand)
if suited:
output = random.choice(suited)
print(output)
#print(input, " --> ", output, file=sys.stderr)
```
] |
[Question]
[
Christmas is fast approaching and along with it, arranging the annual family Secret Santa. I'd like to try and get a head start on this, but making sure couples don't buy for each other keeps causing problems and despite doing this for years there's still the problem that `Bob` is pretty rubbish at buying gifts for most of the giftees, `Erin` will likely be disappointed, but he knows that `Frank` likes Talisker, so he's a good match for him. This makes none of the existing simple solutions acceptable for my needs.
To make my life easier, your task is to write a function (or closest alternative in your language) that when given an array of arrays (or closest alternative in your chosen language), returns (or outputs) a pairing of 'gifters' to 'giftees' in the shortest possible code in bytes, such that the following conditions are met:
* Each name is paired with another, randomly selected, name from the input data (Note that it may not always be possible to randomise the output based on the provided conditions)
* Names will be provided with a list of flags that represent an [adjacency matrix](https://en.wikipedia.org/wiki/Adjacency_matrix#Examples) with the ordering consistent, so that column `n` refers to the same person as row `n`.
* If the conditions cannot be met, return something falsy in your language.
* If there are multiple solutions, your program must be able to generate them all if run many times.
You can assume you will never be presented with duplicate names as we need to be able to tell which family member is which, but you may be presented with data that includes spaces to differentiate `Bob Senior` from `Bob Junior`! It should complete all the supplied test cases within an hour for pretty large families, such as 100 unique names in the source data (please see the example data sets below, you must be able to parse all of these within the allocated time).
## Example input:
```
santa([
["Alice", 0, 0, 1, 1, 1, 1, 1],
["Bob", 0, 0, 0, 0, 0, 1, 0],
["Carla", 1, 1, 0, 0, 0, 1, 1],
["Dan", 1, 1, 0, 0, 0, 1, 1],
["Erin", 1, 1, 0, 0, 0, 1, 1],
["Frank", 1, 1, 1, 1, 1, 0, 1],
["Gary", 1, 1, 1, 1, 1, 1, 0]
]);
// might return something like:
[
["Alice", "Erin"],
["Bob", "Frank"],
["Carla", "Alice"],
["Dan", "Gary"],
["Erin", "Bob"],
["Frank", "Dan"],
["Gary", "Carla"]
]
```
```
santa([
["Alice", 0, 1, 1, 1, 0, 1],
["Bob", 0, 0, 1, 1, 0, 1],
["Carla", 0, 1, 0, 1, 0, 1],
["Dan", 0, 1, 1, 0, 0, 0],
["Erin", 0, 0, 1, 0, 0, 1],
["Frank", 1, 1, 1, 1, 1, 0]
]);
false
```
```
santa([
["Alice", 0, 1, 1],
["Bob", 1, 0, 1],
["Carla", 1, 1, 0]
]);
[
["Alice", "Bob"],
["Bob", "Carla"],
["Carla", "Alice"]
]
```
Depending on language, input can be in other formats, for instance details on `STDIN` *could* be provided as:
```
script <<< 'Alice,0,0,1,1,1,1,1
Bob,0,0,0,0,0,1,0
Carla,1,1,0,0,0,1,1
Dan,1,1,0,0,0,1,1
Erin,1,1,0,0,0,1,1
Frank,1,1,1,1,1,0,1
Gary,1,1,1,1,1,1,0'
```
Output can also be provided in any sensible format, whichever is easiest for your language. Acceptable formats include an array of arrays (as above) or perhaps a hash/`Object`/associative array or even just printing the parings to `STDOUT`:
```
Alice:Dan
Bob:Erin
Carla:Bob
Dan:Alice
Erin:Frank
Frank:Carla
```
If in doubt, please ask and provide examples of required input format and expected output format with your answer.
[Reference JavaScript implementation](https://gist.github.com/dom111/4a4ede77f44c46c5d968).
Larger data sets: [100](https://gist.github.com/dom111/b59f4d309904e666b93c), [100](https://gist.github.com/dom111/63a6c61cd8720d7b12c4), [200](https://gist.github.com/dom111/dc9ba64857d5c35b1de2), [200 - many solutions](https://gist.github.com/dom111/ded692d1e9e645f92356), [200 - only one solution](https://gist.github.com/dom111/88721959d94b22c32f63).
Reference implementation completes all these in <4s on my machine.
Above sets generated with [this script](https://gist.github.com/dom111/29d93b256058dcc7a329).
[Answer]
# Javascript ES6, 191
This solution returns all possible pairings as a list of list of pairs:
```
f=l=>(h=l=>l.length,n=l.map(i=>i.shift()),o=[],(r=s=>(g=h(s))<h(n)?l[g].map((e,x)=>e&&r([...s,x])):o.push([...s]))([]),o.filter(i=>h([...new Set(i)])==h(n)).map(l=>l.map((t,f)=>[n[f],n[t]])))
```
Example run:
```
>> example = f([
["Alice", 0, 0, 1, 1, 1, 1, 1],
["Bob", 0, 0, 0, 0, 0, 1, 0],
["Carla", 1, 1, 0, 0, 0, 1, 1],
["Dan", 1, 1, 0, 0, 0, 1, 1],
["Erin", 1, 1, 0, 0, 0, 1, 1],
["Frank", 1, 1, 1, 1, 1, 0, 1],
["Gary", 1, 1, 1, 1, 1, 1, 0]])
<< Array [ Array[7], Array[7], Array[7], Array[7], Array[7], Array[7], Array[7], Array[7], Array[7], Array[7], 26 more… ]
>> example[0]
<< Array [ "Alice:Carla", "Bob:Frank", "Carla:Alice", "Dan:Bob", "Erin:Gary", "Frank:Dan", "Gary:Erin" ]
```
] |
[Question]
[
# Background
[Slime molds](http://en.wikipedia.org/wiki/Slime_mold) are awesome.
If you place them on a surface with food sources, they will spread their tendrils to find the food, after which they form a network of connections between the sources.
In this challenge, you shall simulate a slime mold looking for food.
Moreover, this particular mold will stop once it's found enough.
# Input
Your inputs shall be a list `L` of 2D integer coordinates in the native format of your language, and a nonnegative integer `N`.
The list `L` is guaranteed to be duplicate-free, but it may not be sorted.
The input `N` is between 0 and the length of `L`, inclusive.
The list `L` represents a set of coordinates for food sources.
For example, the list
```
[(0,0),(2,-1),(3,1),(0,4),(5,5)]
```
could be interpreted visually as
```
o
o
o
o
o
```
# Output
Your output is another duplicate-free list `K` of 2D integer coordinates on the same format as the input.
It represents the network formed by the slime mold, and it shall satisfy the following conditions:
* The intersection of `L` and `K` has size exactly `N`.
* The set `K` is connected as a subset of the integer grid (via orthogonal or diagonal adjacencies).
* If any coordinate of `K` is removed, it no longer satisfies the first two conditions.
Note that if `N = 0`, the output must be an empty list.
An example of an acceptable output for the above list `L` and `N = 4` would be
```
[(0,0),(0,1),(0,2),(0,3),(0,4),(1,4),(2,4),(3,3),(3,2),(3,1),(3,5),(4,5),(5,5)]
```
which can be visualized as
```
xxO
Oxx
x x
x x
x O
O
o
```
where each `O` represents a coordinate in both `L` and `K`, and each `x` represents a coordinate in `K` but not in `L`.
Other outputs are also acceptable, and the "tendrils" don't have to be the shortest possible.
For example, this is also an acceptable solution:
```
xxOxx
Oxx x
x x
x x
x o x
O x
Ox
```
# Rules
Both the input and output shall be lists, not sets or other datatypes.
The coordinates themselves can be lists or tuples.
You can change the order of the two inputs if needed.
You can write either a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
# Test Cases
Your program should work on these lists for all applicable values of `N`.
```
[]
[(2,3)]
[(0,0),(1,0),(0,1),(1,1)]
[(0,0),(2,-1),(3,1),(0,4),(5,5)]
[(0,0),(1,0),(2,0),(3,0),(0,3),(1,3),(2,3),(3,3)]
[(0,0),(1,0),(2,0),(3,0),(0,3),(1,3),(2,3),(3,3),(0,1),(0,2),(3,1),(3,2),(8,1),(8,2),(-5,1),(-5,2)]
[(0,0),(20,0),(15,15),(-10,4),(-10,3),(0,-5),(7,6),(7,7),(8,8),(9,8),(10,-2),(-1,12),(-3,10)]
[(0,0),(1,0),(2,0),(3,0),(5,0),(6,0),(7,0),(0,9),(1,9),(2,9),(3,8),(4,9),(5,10),(6,10),(7,9),(3,3),(4,4),(5,5)]
```
Visualized:
```
===
o
===
oo
oo
===
o
o
o
o
o
===
oooo
oooo
===
oooo
o o o o
o o o o
oooo
===
o
o
o
oo
o
o
o
o
o o
o
o
===
oo
ooo o o
o
o
o
o
oooo ooo
```
[Answer]
# CJam, ~~77~~ 95 bytes
I think this can be golfed a bit more, but here goes:
```
q~$<_{{:X;]{[X\]z::-~mhW*}$~:Y{_)Y1{_@=X@=}:B~-g-{+__X=!\}:C~1B=!&}g{_(Y0B-g-\C0B=!&}g}*]_&}L?p
```
Input goes like `N <Array of coordinate array>`. For example:
```
4 [[0 0] [1 5] [2 1] [0 3] [5 0] [5 5]]
```
Output:
>
> [[0 5] [1 5] [0 4] [0 3] [0 0] [0 2] [0 1] [1 1] [2 1]]
>
>
>
**Algorithm**:
The algorithm is pretty straight forward and goes like:
* Sort the input coordinate array. This makes the coordinates sorted first by row and then by column.
* Now we pick first `N` points
* Now we reduce on these `N` points. The destination is the last point and the source is the closes point to that last point.
* Then we start with the top-left most point, walk right (or left) till its on or directly above the next point.
* Then we walk down to reach the next point.
* It is guaranteed that there will be no uncovered point left to the above point in the same row. This ensures that we do not touch any other point that the chosen `N`. Choosing the closes point also ensures that second rule is held true.
[Try it online here](http://cjam.aditsu.net/#code=q~%24%3C_%7B%7B%3AX%3B%3AY%7B_)Y1%7B_%40%3DX%40%3D%7D%3AB~-g-%7B%2B__X%3D!%5C%7D%3AC~1B%3D!%26%7Dg%7B_(Y0B-g-%5CC0B%3D!%26%7Dg%7D*%5D_%26%7DL%3Fp&input=3%20%5B%5B0%200%5D%20%5B2%20-1%5D%20%5B3%201%5D%20%5B0%201%5D%20%5B5%200%5D%20%5B5%205%5D%5D)
] |
[Question]
[
I like Tetris a lot, but I'm not very good at it. Just once I'd like to see that spaceship take off in front of my own eyes! And since computers are oh-so great at everything, the only possible solution is to make a program to play it for me... except you're going to do that bit for me!
Given a tetromino (shape made of four squares) and a map of the playing field, you are to place the tetromino such that it scores the **greatest number of lines** (makes the greatest number of rows completely full of blocks) and creates the **least number of *new* holes** (an empty space that cannot "see" the top of the playing field1).
## Input
The input will contain a character on a single line that represents the dropping tetromino, followed by a 10\*18 grid2 of spaces () and plus signs (`+`).
The character represents any of the seven base tetrominoes found in Tetris. All of the pieces can be rotated by 90 degrees, but not flipped. All the tetrominoes and their rotations are as follows:
```
#
S = ## ##
## #
#
Z = ## ##
## #
# ### ##
L = # # # #
## # ###
# ### ##
J = # # # #
## # ###
# # #
T = ### ## ### ##
# # #
O = ##
##
#
I = # ####
#
#
```
The grid represents the playing field of Tetris, with `+` being previously-placed blocks. So, an example input might be the following:
```
I
+ ++
+ +++++
++ +++++++
++ +++++++
++ +++++++
++ +++++++
++++++ +++
```
## Output
Your output will be identical to the input, but with the tetromino in the ideal position. The tetromino should be represented with `#` to differentiate them from the pre-placed blocks. In addition to this, you are also to output how many lines/holes your placement creates in the form `xL yH` on a new line.
The output for the example given above would be the following3:
```
I
+ ++
+ +++++
++#+++++++
++#+++++++
++#+++++++
++#+++++++
++++++ +++
4L 0H
```
You are to output only the best result(s); in the case of two or more cases giving the same score, you are to output all of them (separated by a blank line). The best results are to be determined by sorting by the number of lines scored (descending) first, then the number of new holes created (ascending). So, `1L 1H` is a better score than `0L 0H`.
I will work on creating a list of various inputs and expected output(s) that you can test your program against. Watch this space.
## Rules and Disambiguation
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest correct implementation wins.
* Input/output may be in any medium that suits your target language (e.g. file, stdin/stdout, text area).
* If your target language does not support multiple line input (or it is inconvenient to do so), you may instead delimit each line of the input with commas (`,`).
* You may omit the output of any blank lines in the grid.
* Remember that the tetromino falls from above - you may not place the piece "underground". You may therefore assume that all possible placements of the piece will be at "surface-level" (i.e. there are no blocks between the piece and the top of the board).
* Assume that there will never be a situation in which you are forced into a game over (the placed tetromino touches the top-center of the field).
* Solutions that are identical in output must be omitted (e.g. there are 3 solutions outputs if you naively rotate the `O` piece).
---
1 I'm aware that this will create some false positives, but it's a simplification.
2 This is the grid size used in the Game Boy version.
3 Yes, `0H` is correct. Check again, I said *new* holes ;^)
[Answer]
# C 1009 bytes
```
#include <stdio.h>
#define L for(n=0;n<18;++n)
int T[19]={54,561,99,306,785,23,547,116,802,71,275,116,39,562,114,305,51,4369,15},W[19]={3,2,3,2,2,3,2,3,2,3,2,3,3,2,3,2,2,1,4},O[7]={0,2,4,8,12,16,17},R[7]={2,2,4,4,4,1,2},G[18],F[24],t=0,I,x,y,S[99],X[99],Y[99],N[99],s,M=0,i,j,k,l,m,n,h,c;char B[99],*C="SZLJTOI";void A(){for(m=0;m<24;++m)F[m]=0;for(m=0;m<4;++m)F[y+m]=(T[I]>>(m*4)&15)<<x;}void D(){S[s]=0;L S[s]+=(G[n]|F[n])==1023;S[s]=200*(S[s])+199;for(m=0;m<10;++m){l=0;L{h=(G[n]|F[n])&1<<m;l|=h;S[s]-=l&&!h;}}}int E(){A();c=0;L c|=G[n]&F[n];return !c;}int main(){S[0]=0;gets(B);while(C[t]!=B[0])++t;I=O[t];L{G[n]=0;gets(B);for(m=0;m<10;++m)G[n]|=(B[m]=='+')?(1<<m):0;}s=0;D();for(i=0;i<R[t];++i){for(x=0;x<10-W[I];x++){y=0;while(E())y++;--y;++s;A();D();if(S[s]>M)M=S[s];X[s]=x;Y[s]=y;N[s]=I;}I++;}for(i=1;i<s;++i)if(S[i]==M){j=i;x=X[i];y=Y[i];I=N[i];A();for(n=1;n<18;++n){for(m=0;m<10;++m)printf((G[n]&1<<m)!=0?"+":((F[n]&1<<m)!=0?"#":" "));printf("\n");}}printf("%dL %dH\n",S[j]/200,S[0]%200-S[j]%200);}
```
Here is the ungolfed version
```
#include <stdio.h>
int tiles[19] = {54,561,99,306,785,23,547,116,802,71,275,116,39,562,114,305,51,4369,15};
int widths[19] = {3,2,3,2,2,3,2,3,2,3,2,3,3,2,3,2,2,1,4};
char *codes = "SZLJTOI";
int offsets[7] = {0,2,4,8,12,16,17};
int transformations[7] = {2,2,4,4,4,1,2};
int gameField[18], tileField[24];
int i,j,k,l,m,n,h;
char buffer[99];
int tile=0, tileIndex;
int xpos, ypos;
int scores[99], xplacements[99], yplacements[99], tindex[99];
int scoreIndex, maxScore=0;
void readGame()
{
gets(buffer);
while (codes[tile]!=buffer[0]) ++tile;
tileIndex = offsets[tile];
for (n=0;n<18;++n)
{
gameField[n] = 0;
gets(buffer);
for (m=0; m<10;++m)
gameField[n] |= (buffer[m]=='+')?(1<<m):0;
}
}
void writeGame()
{
for (n=1;n<18;++n)
{
for (m=0; m<10;++m)
printf( (tileField[n] & 1<<m) != 0 ? "#" :((gameField[n] & 1<<m) != 0 ? "+" :" "));
printf("\n");
}
}
void placeTile()
{
for (m=0;m<24;++m) tileField[m] = 0;
for (m=0;m<4;++m)
tileField[ypos+m] = (tiles[tileIndex]>>(m*4) & 15) << xpos;
}
void score()
{
scores[scoreIndex] = 0;
for (n=0;n<18;++n)
if ((gameField[n] | tileField[n])==1023) scores[scoreIndex]++;
scores[scoreIndex] = 200*(scores[scoreIndex]) + 199;
for (m=0;m<10;++m)
{
l=0;
for (n=0;n<18;++n)
{
h = (gameField[n] | tileField[n]) & 1<<m;
l |= h;
scores[scoreIndex] -= l && !h;
}
}
}
int noCollision()
{
placeTile();
int coll = 0;
for (n=0;n<18;++n) coll |= gameField[n] & tileField[n];
return !coll;
}
int main()
{ scores[0] = 0;
readGame();
scoreIndex = 0;
score();
for (i=0; i<transformations[tile]; ++i)
{
for (xpos=0; xpos<10-widths[tileIndex]; xpos++)
{
ypos = 0;
while (noCollision()) ypos++;
--ypos;
++scoreIndex;
placeTile();
score();
if (scores[scoreIndex]>maxScore) maxScore=scores[scoreIndex];
xplacements[scoreIndex] = xpos;
yplacements[scoreIndex] = ypos;
tindex[scoreIndex] = tileIndex;
}
tileIndex++;
}
for (i=1;i<scoreIndex; ++i)
if (scores[i]==maxScore)
{
j=i;
xpos = xplacements[i];
ypos = yplacements[i];
tileIndex = tindex[i];
placeTile();
writeGame();
}
printf("%dL %dH\n", scores[j]/200, scores[0]%200-scores[j]%200);
}
```
I saw that the main source of lengthy code would probably be the definition of the tiles. So I decided to represent them as bit patterns in a 4x4 bit array. This results in 16 bits that easily fit into a single `int`. The `tiles` array holds all the patterns for the 19 possible rotations of the 7 tiles.
When compiling, ignore the warning that `gets` is deprecated. I know it is but it is the shortest way of reading a line from the input.
] |
[Question]
[
This is not a Sudoku solver, nor a Sudoku checker.
Your challenge is to write a function or script that, given as input the "block" size of a 2D Sudoku puzzle (which is 3 for the [classic 9x9 board](http://www.domo-sudoku.com/), 4 for a [16x16 board](http://www.domo-sudoku.com/evil-sudoku-16.php), etc.) will compute an approximation of the number of distinct puzzles (solutions) that exist for that size.
For example, given input 3, your program should print an approximation, to the desired precision, of the number 6,670,903,752,021,072,936,960 which is the [known number of distinct 9x9 Sudoku puzzles](https://en.wikipedia.org/wiki/Mathematics_of_Sudoku#Mathematical_context), or 5,472,730,538 when taking into account the various symmetries. Your solution should state whether symmetries are counted or ignored.
"Desired precision" is left undefined: your program might run for a given time and then output its result, or compute it up to a given number of significant digits, or even run forever, printing better and better approximations. The point is that it should be possible to make it compute the result to any required precision, in a finite time. (So "42" is not an acceptable answer.) Restricting the precision of your result to the available machine floats is acceptable.
No accessing online resources, no storing the source code in the file name, etc.
---
PS: I know this is a Hard Problem (NP-complete if I'm not mistaken.) But this question is only asking for an approximate, statistical solution. For example you can try random configurations that satisfy one (or better two) constraints, compute how many of those exist and then check how often you get a puzzle that satisfies all three constraints. This will work in a decent time for small sizes (certainly for size=3 and possibly 4) but the algorithm should be generic enough to work for any size.
The best algorithm wins.
---
PS2: I changed from code-golf to code-challenge to better reflect the difficulty of the problem and encourage smarter solutions, over dumb but well-golfed ones. But since apparently "best algorithm" is unclear, let me try to define it properly.
Given enough time and disregarding constant factors (including CPU and intepreter speed), or equivalently, considering their asymptotical behaviour, **which solution would converge to the exact result the fastest?**
[Answer]
# C++
**What i will present here is an algorithm, illustrated with an example for a 3x3 case. It could theoretically be extended to the NxN case, but that would need a much more powerful computer and/or some ingenious tweaks. I will mention some improvements as I go through.**
Before going further, **let's note the symmetries of the Sudoku grid,** i.e. the transformations which lead to another grid in a trivial way. For block size 3, the symmetries are as follows:
Horizontal symmetry
```
**The N=3 sudoku is said to consist of 3 "bands" of 3 "rows" each**
permute the three bands: 3! permutations = 6
permute the rows in each band: 3 bands, 3! permutations each =(3!)^3=216
```
Vertical symmetry
```
**The N=3 sudoku is said to consist of 3 "stacks" of 3 "columns" each.**
the count is the same as for horizontal.
```
Note that horizontal and vertical reflections of the grid can be achieved by a combination of these, so they do not need to be counted.
There is one more spatial symmetry to be considered, which is transposing, which is a factor of `2`. This gives the total spatial symmetry of
```
2*(N!*(N!)^N)^2 = 2*(6*216)^2=3359232 spatial symmetries for the case N=3.
```
Then there is another, very important symmetry, called relabelling.
```
Relabelling gives a further (N^2)!=9!=362880 symmetries for the case N=3. So the total
number of symmetries is 362880*3359232=1218998108160.
```
The total number of solutions cannot be found simply by multiplying the number of symmetry-unique solutions by this number, because there are a number (less than 1%) of automorphic solutions. That means that for these special solutions there is a symmetry operation that maps them to themselves, or multiple symmetry operations that map them to the same other solution.
**To estimate the number of solutions, I approach the problem in 4 steps:**
**1.Fill an array `r[362880][12]`with all possible permutations of the numbers 0 to 8.** (this is programming, and it is in C, so we are not going to use 1 to 9.) If you are astute you will notice that the second subscript is 12 not 9. This is because, while doing this, bearing in mind that we are going to consider this to be a "row" we also calculate three more integers `r[9,10,11] == 1<<a | 1<<b | 1<<c` where 9,10,11 refer to the first, second and third stack and a,b,c are the three numbers present in each stack for that row.
**2.Fill an array `b` with all possible solutions of a band of 3 rows.** To keep this reasonably small, only include those solutions where the top row is 012,345,678. I do this by brute force, by generating all possible middle rows and ANDing `r[0][10,11,12]` with `r[i][10,11,12]`. Any positive value means there are two identical numbers in the same square and the band is invalid. When there is a valid combination for the first two rows, I search the 3rd (bottom) row with the same technique.
I dimensioned the array as b[2000000][9] but the program only finds 1306368 solutions. I did not know how many there were, so I left the array dimension like that. This is actually only half the possible solutions for a single band (verified on wikipedia), because I only scan the 3rd row from the current value for `i` upwards. The remaining half of the solutions can be found trivially by exchanging the 2nd and 3rd rows.
The way the information is stored in array `b` is a little confusing at first. instead of using each integer to store the numbers `0..8` found in a given position, here each integer considers one of the numbers `0..8` and indicates in which columns it can be found. thus `b[x][7]==100100001` would indicate that for solution x the number 7 is found in columns 0,5 and 8 (from right to left.) The reason for this representation is that we need to generate the rest of the possibilities for the band by relabelling, and this representation makes it convenient to do this.
**The two steps above comprise the setup and take about a minute (possibly less if I removed the unnecessary data output. The two steps below are the actual search.)**
**3 Search randomly for solutions for the first two bands that do not clash (i.e. do not have the same number twice in a given column.** We pick a random solution for band 1, assuming always permutation 0, and a random solution for band 2 with a random permutation. A result is normally found in less than 9999 tries (first stage hit rate in the thousands range) and takes a fraction of a second. By permutation, I mean that for the second band we take a solution from b[][] where the first row is always 012,345,678 and relabel it so that any possible sequence of numbers on the first row is possible.
**4 When a hit is found in step 3, search for a solution for the third band which does not clash with the other two.** We do not want to make just one try, otherwise the processing time for step 3 would be wasted. On the other hand we do not want to put an inordinate amount of effort into this.
Just for fun, last night I did it the dumbest way possible, but it was still interesting (because it nothing for ages, then found large numbers of solutions in bursts.) It took all night to get one datapoint, even with the little hack `(!z)` I did to abort the last `k` loop as soon as we know this is not a valid solution (which makes it run nearly 9 times faster.) It found 1186585 solutions for the complete grid
after searching all 362880 relabellings of all 1306368 canonical solutions for the last block, a total of 474054819840 possibilities. That's a hit rate of 1 in 400000 for the second stage. I will try again soon with a random search rather than a scan. It should give a reasonable answer in just a few million tries, which should take only a few seconds.
The overall answer should be (362880\*(1306368\*2))^3\*hit rate=8.5E35\*hit rate. By back calculating from the number in the question, I expect a hit rate of 1/1.2E14. What I've got so far with my single datapoint is 1/(400000\*1000) which is out by a factor of about a million. This could be an anomaly of chance, an error in my program, or an error in my math. I won't know which it is until I run a few more tests.
**I'll leave this here for tonight. The text is a bit scrappy, I will tidy it up soon and hopefully add some more results, and maybe a few words on how to make it faster and how to extend the concept to N=4. I don't think I'll be making too many more changes to my program, though :-)**
Ah.. the program:
```
#include "stdafx.h"
#define _CRT_RAND_S
#include <algorithm>
#include <time.h>
unsigned int n[] = { 0,1,2,3,4,5,6,7,8 }, r[362880][12], b[2000000][9],i,j,k,l,u,v,w,x,y,z;
int main () {
//Run through all possible permutations of n[] and load them into r[][]
i=0;
do {
r[i][9] = r[i][10] = r[i][11]=0;
for (l = 0; l < 9; l++){
r[i][l] = n[l];
r[i][9 + l / 3] |= 1 << n[l];
}
if((i+1)%5040==0) printf("%d%d%d %d%d%d %d%d%d %o %o %o %o \n"
,r[i][0],r[i][1],r[i][2],r[i][3],r[i][4],r[i][5],r[i][6],r[i][7],r[i][8],r[i][9],r[i][10],r[i][11],r[i][9]+r[i][10]+r[i][11]);
i++;
} while ( std::next_permutation(n,n+9) );
//Initialise b[][]
for (l = 0; l<2000000; l++) for (k = 0; k<9; k++) b[l][k]=0;
//fill b[][] with all solutions of the first band, where row0 ={0,1,2,3,4,5,6,7,8} and row1<row2
l=0;
for (i = 0; i<362880; i++)
if (!(r[0][9] & r[i][9] | r[0][10] & r[i][10] | r[0][11] & r[i][11])){printf("%d %d \n",i,l);
for (j=i; j<362880;j++)
if(!(r[0][9]&r[j][9] | r[0][10]&r[j][10] | r[0][11]&r[j][11] | r[j][9]&r[i][9] | r[j][10]&r[i][10] | r[j][11]&r[i][11] )){
for (k = 0; k < 9; k++){
b[l][r[0][k]]|=1<<k;
b[l][r[i][k]]|=1<<k;
b[l][r[j][k]]|=1<<k;
}
l++;
}
// printf("%d%d%d %d%d%d %d%d%d %o %o %o %o \n"
// ,r[i][0],r[i][1],r[i][2],r[i][3],r[i][4],r[i][5],r[i][6],r[i][7],r[i][8],r[i][9],r[i][10],r[i][11],r[i][9]+r[i][10]+r[i][11]);
// printf("%d%d%d %d%d%d %d%d%d %o %o %o %o \n"
// ,r[j][0],r[j][1],r[j][2],r[j][3],r[j][4],r[j][5],r[j][6],r[j][7],r[j][8],r[j][9],r[j][10],r[j][11],r[j][9]+r[j][10]+r[j][11]);
// printf("%d %d %o %o %o %o %o %o %o %o %o \n",i,l,b[l][0],b[l][1],b[l][2],b[l][3],b[l][4],b[l][5],b[l][6],b[l][7],b[l][8]);
}
// find a random solution for the first 2 bands
l=0;
do{
rand_s(&u); u /= INT_MIN / -653184; //1st band selection
rand_s(&v); v /= INT_MIN / -181440; //2nd band permutation
rand_s(&w); w /= INT_MIN / -653184; //2nd band selection
z = 0;
for (k = 0; k < 9; k++) z |= b[u][k] & b[w][r[v][k]];
l++;
} while (z);
printf("finished random after %d tries \n",l);
printf("found solution with top band %d permutation 0, and middle band %d permutation %d \n",u,w,v);
getchar();
// scan all possibilities for the last band
l=0;
for (i = 0; i < 362880; i++) for (j = 0; j < 1306368; j++){
z=0;
for(k=0;(k<9)&&(!z);k++) z|= b[u][k] & b[j][r[i][k]] | b[j][r[i][k]] & b[w][r[v][k]];
if (!z){ l++; printf("solution %d : i= %d j=%d",l,i,j); }
}
printf("finished bottom band scan at %d millisec \n", clock()); getchar();
}
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 6 years ago.
[Improve this question](/posts/23496/edit)
Implement a program or function which simulates common dice for role playing games. It should handle at least the d6 and d20, the two most common dice.
***However, it should work as stereotypical gamers expect them to work, and not as real dice work.***
It is an in-joke between gamers, that one can have a specially lucky die for a very very important roll, by previously throwing a lot of dice, selecting those which resulted in a "1", then throwing them again, until you get a few which rolled a "1" multiple times. You then carefully preserve them, because they rolled a 1 multiple times in sequence, so the probability to roll a 1 next time should be extremely low.
Of course, this is [not how dice work in real life](http://en.wikipedia.org/wiki/Gambler%27s_fallacy), because the rolls are statistically independent.
Your simulated dice have to take previous rolls into account, and work similarly to how the gambler in the gambler's fallacy expects it to work. For example, if a lot of low numbers were rolled, the probability of rolling a higher number should be increased.
However, as this is cheating, **you have to hide it well**. This means, a casual glance upon the program should not reveal that you cheated. This means, explicitly saving the previous results and reading them on every throw would be too suspicious. You have to hide this "property" of your dice, and bonus points if you make it plausible deniable and disguise it as an honest mistake. (for example, you make your own RNG with an "unintentional" flaw)
Voters, please take into account how well hidden this "flaw" is.
The programs should be clear, and not obfuscated. It's too easy to hide evil code in an obfuscated program.
[Answer]
## Java
```
public class GamerDie {
private final java.util.Random rnd;
private final int sides;
public GamerDie(int sides) {
this.sides = sides;
this.rnd = new java.util.Random();
}
public int throw() {
return rnd.nextInt(sides) + 1;
}
}
```
It's so simple that it's obviously not hiding anything: but `java.util.Random` is a straightforward linear congruential generator, and it uses a discard technique to ensure uniformity, so it guarantees that in any run of the largest multiple of `size` smaller than 2^48 samples it will distribute the numbers evenly, satisfying the requirement.
[Answer]
# Ruby
Currently only supports d6, will add d20 support later on...
Lo and behold - those dices are nasty!
```
# first idea was to create 6 super cool dices just by copy&paste
# -> each dice holds its number at the beginning of the array
# -> we don't need all of them now, so we comment them out
dice0 = %w[[[[[[[[[ 0 . : :. :: ::. ::: ]]]]]]]]
#dice1 = %w[[[[[[[ 1 : . :. ::. :: ::: ]]]]]]]
#dice2 = %w[[[[[[ 2 . : :. :: ::. ::: ]]]]]]
#dice3 = %w[[[[[[ 3 : . :. ::. :: ::: ]]]]]]]
#dice4 = %w[[[[[[[ 4 . : :. :: ::: ::. ]]]]]]]
#dice5 = %w[[[[[[[[ 5 . : :. :: ::. ::: ]]]]]]]]]
# and hey, those dices are almost ascii art ;)
# well, let's just create a standard dice
# -> get rid of the number at the beginning
# -> then sort (maybe we need that later due to the
# currently unused dices being unsorted)
dice = dice0.select!{|e| /[:.]+/ === e}.sort
def roll(d)
# rolling is easy
# -> use size instead of hardcoded number,
# maybe we'll have other dices later
d.slice!(rand(d.size - 1))
end
# and here you have 8 very underhanded dices!
dices = [dice]*8
# roll like a champion
roll(dices[0])
...
```
[Answer]
# Haskell
Use one random thing to make another random thing: in this case, shuffle cards to generate dice throws.
```
import System.Environment
import System.Random
import Data.Array.IO
import Control.Monad
-- make random dice from random cards
suit c=map (\(a,b)->[a,b])$zip "A23456789TJQK" (repeat c)
deck=concatMap(\s->suit s) "♠♥♦♣"
-- just like casinos, use more decks for extra randomness
decks=concat$take 8$repeat deck
-- shuffle the cards
shuffle :: [a] -> IO [a]
shuffle xs = do
ar <- newArray n xs
forM [1..n] $ \i -> do
j <- randomRIO (i,n)
vi <- readArray ar i
vj <- readArray ar j
writeArray ar j vi
return vj
where
n = length xs
newArray :: Int -> [a] -> IO (IOArray Int a)
newArray n xs = newListArray (1,n) xs
-- convert a card to a die, by counting along the original deck
-- then taking mod (faces). If we don't have enough cards to make
-- a full set of faces, assign the 'extra' cards a value of 0
card2die faces card=
let index=(head[i|(i,c)<-zip[0..]deck,c==card]) in
if (index > (length deck-(length deck`mod`faces)))
then 0
else (index`mod`faces)+1
main=
do
args <- getArgs
let faces = read (args!!0)
-- throw away cards we can't map to die faces
cards<-shuffle$filter (\card->card2die faces card/=0) decks
mapM_ (\card->putStrLn (card++" -> "++(show (card2die faces card)))) cards
```
Takes one argument, the number of faces on the die. Output is like this:
```
./cards 20|head
2♦ -> 8
7♥ -> 20
J♦ -> 17
6♥ -> 19
9♥ -> 2
8♥ -> 1
5♥ -> 18
4♠ -> 4
Q♥ -> 5
2♣ -> 1
```
... and so on for all cards (discards are not printed). Too obvious?
] |
[Question]
[
The goal of a Rosetta Stone Challenge is to write solutions in as many languages as possible. Show off your programming multilingualism!
# The Challenge
Your challenge is to implement a program that will map some genes using cross-over frequencies, *in as many programming languages as possible*. You are allowed to use any sort of standard library function that your language has, since this is mostly a language showcase.
## What is "gene mapping?"
Gene mapping is the process of locating the relative position of genes on chromosomes. This is done by measuring the crossing-over frequency of pairs of genes, equal to the percent of offspring in which that the pair is *not* inherited together. Distance is measured in *map units* with one map unit equal to one percent of crossing over. For example, if genes C & D have a crossing-over frequency of 11%, then gene C is a distance of 11 map units away from gene D.
Gene mapping is performed with multiple pairs of genes to determine their relative order. For example, the data `(A,B,12) (D,B,7) (A,D,5) (D,H,2) (H,B,9)` produces the following map:
```
A..H.D......B
```
You may have noticed that `B......D.H..A` is also a valid map. This is true, because it is not possible to distinguish between mirror opposites. Your program can pick which one to output. Although the input may not include every possible pair, there will always be enough information to reconstruct the entire map (so there will never be more than 2 valid outputs). In addition, the numbers will always work out (unlike actual biology), meaning that you won't have stuff like `(A,B,3) (B,C,4) (A,C,13)`.
## Input
Input will begin with a number `n` followed by a list of genes (uppercase letters). There will then be `n` triplets of data. Each set will consist of a pair of genes and their crossing over frequency (distance).
```
3,P,H,I
P,H,3
H,I,1
P,I,4
7,A,B,G,Q,U
B,Q,4
A,B,10
G,U,13
Q,U,10
A,G,9
G,Q,3
A,Q,6
```
Input is not rigidly defined, because different languages may have restrictions on what is feasible. For example, you may change the delimiters to something other than commas and newlines. Input formatting is largely up to you.
## Output
Output will be a rendition of the gene map. It will consist of the genes (capital letters) spaced out by periods such that the distances are accurately portrayed. Here are the outputs for the above examples.
```
P..HI *or* IH..P
BG..Q.....A...U *or* U...A.....Q..GB
```
This also isn't a completely rigid requirement. For example you could use something other than periods, like commas or spaces.
# The Objective Winning Criterion
As for an objective winning criterion, here it is: Each language is a separate competition as to who can write the shortest entry, but the overall winner would be the person who wins the most of these sub-competitions. This means that a person who answers in many uncommon languages can gain an advantage. Code-golf is mostly a tiebreaker for when there is more than one solution in a language: the person with the shortest program gets credit for that language.
## Rules, Restrictions, and Notes
Your program can be written in any language that existed prior to December 20th, 2013. I will also have to rely on the community to validate some responses written in some of the more uncommon/esoteric languages, since I am unlikely to be able to test them.
---
# Current Leaderboard
This section will be periodically updated to show the number of languages and who is leading in each.
* AutoHotkey (632) - Avi
* dj (579) - rubik
---
# Current User Rankings
1. Avi (1): AutoHotkey (632)
2. rubik (1): dj (579)
[Answer]
## AutoHotkey (632)
```
f(i){
o:={},f:={},n:=0
loop,parse,i,`n
{
a:=A_LoopField
if A_index!=1
{
@:=Substr(a,1,1),#:=Substr(a,3,1),n+=($:=Substr(a,5))
if !IsObject(o[@])
o[@]:={}
if !IsObject(o[#])
o[#]:={}
o[@][#]:=o[#][@]:=$
}
}
f[n+1]:=@,f[@]:=n+1,a:=""
while !a
{
a:=0
for k,v in o
{
if !f[k]
{
c1:=c2:=s:=0
for k1,v1 in v
{
if f[k1]
if s
{
if (r1==f[k1]-v1)or(r1==f[k1]+v1)
c1:=r1
else r1:=c1:=""
if (r2==f[k1]-v1)or(r2==f[k1]+v1)
c2:=r2
else r2:=c2:=""
}
else
c1:=r1:=f[k1]+v1,c2:=r2:=f[k1]-v1,s:=1
}
if c1
f[c1]:=k,f[k]:=c1,a:=1
else if c2
f[c2]:=k,f[k]:=c2,a:=1
}
}
}
loop % 2*n+1
{
v:=f[A_index]
if v
z:=1
r.=z?(!v?".":v):v
}
return Rtrim(r,".")
}
```
The code can be more shortened by renaming all vars to 1 character .. It should then be about 610 characters.
### Test Cases
```
v := "
(7,A,B,G,Q,U
B,Q,4
A,B,10
G,U,13
Q,U,10
A,G,9
G,Q,3
A,Q,6
)"
msgbox % f(v)
msgbox % f("3,P,H,I`nP,H,3`nH,I,1`nP,I,4")
```
[Answer]
**Python 311**
```
import sys,random
d=sys.stdin.readlines()
u=[]
r=g=0
m={}
l=d[0].split()[1:]
for a in l:m[a]=g;g+=1
for v in d[1:]:i=v.split();u+=[i];r+=int(i[2])
j=len(l)
y=range(j)
while any(abs(y[m[t]]-y[m[w]])!=int(p) for t,w,p in u):y=random.sample(range(r),j)
o=["."]*r
for a in m:o[y[m[a]]]=a
print "".join(o).strip(".")
```
**My first code-golf :D**
(Im not sure with the counting, i just postet it online in a character count)
The idea of the algorithm is pretty bad, but it is short.
Try randomly all positions for the Symbols until they satisfy all constraints.
The Input is with whitespace for example
```
3 P H I
P H 3
H I 1
P I 4
```
Hit after that CTRL+D in the console to end the reading.
Here is the original code which still uses ',' as delimiter.
```
import sys, random
#data = sys.stdin.readlines()
data = [
"3,P,H,I",
"P,H,3",
"H,I,1",
"P,I,4"
]
container = []
max_range = 0
map = {}
map_counter = 0
line_split = data[0].split(',')[1:]
count = len(line_split) # Number of genes
for symbol in line_split:
map[symbol] = map_counter
map_counter += 1
for line in data[1:]:
line_split = line.split(',')
container.append(line.split(','))
max_range += int(line_split[2])
restart = True
while restart == True:
positions = random.sample(range(max_range), count) # Since this loop will take like forever, but some day it will produce the correct positions
restart = False
for symbol1, symbol2, distance in container:
if abs(positions[map[symbol1]] - positions[map[symbol2]]) != int(distance):
restart = True
break
output = ["."] * max_range
for symbol in map:
output[positions[map[symbol]]] = symbol
print "".join(output).strip(".") # Strip . to make it more pretty
```
[Answer]
# dg - 717 579 bytes
A Python one is incoming.
```
import '/sys'
w,o=list,tuple
p=g a b m->
b in g=>a,b=b,a
i,l,k=g.index a,w$g,w$g
l!!(i+m),k!!(i-m)=b,b
g!!(i+m)=='.'=>yield$o$l
g!!(i-m)=='.'=>yield$o$k
g=t->
d=sorted key:(i->snd i)$map((a,b,i)->((a,b),int i))$filter fst$map(i->i.split ',')$t.split '\n'
(a,b),i=d.pop!
g=w$('.',)*i*4
g!!i,g!!(i+i)=a,b
s=set'$o g
while d=>
d.sort key:((k,v)->set k&(set$fst$w s))
n,(a,b),i=set! :+d.pop!
for r in s=>
if(a in r and b in r=>i==abs(r.index a-r.index b)=>n.add r)(1=>n.update$p r a b i)
s = n
'\n'.join$map(l->(''.join l).strip '.')s
print$g sys.stdin.read!
```
Examples:
```
$ echo """P,H,3
H,I,1
P,I,4""" | dg dna.dg
P..HI
$ echo """B,Q,4
A,B,10
G,U,13
Q,U,10
A,G,9
G,Q,3
A,Q,6""" | dg dna.dg
BG..Q.....A...U
```
[Answer]
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <malloc.h>
struct Gene
{
char a1 , a2 ;
int d ;
};
typedef struct Gene gene ;
struct Set
{
int appr_id ;
char CMN_char ;
};
typedef struct Set set ;
gene *stack;
int cp_id1 , cp_id2 , N=0 , cid , *used , n ;
char ucmn_char , *cmp1 , *cmp2 , *base , ep[15] ;
set ap_set ;
void randomize(void)
{ int i;
Set temp;
for(i=0;i<(n-1);i++)
{
temp=stack[i];
stack[i]=stack[i+1];
stack[i+1]=temp;
}
return;
}
void populate_ep ( char ucmn_char )
{
int i;
for ( i=0 ; ep[i] != '\0' ; i ++ );
ep[ i ] = ucmn_char ;
}
set find_appr ( void )
{
int i , j ;
set s ;
for ( i = 0 ; i < n ; i++ )
{
if ( used[ i ] == 1 )
continue ;
else
{
for ( j = 0 ; ep[ j ] != '\0' ; j++ )
{
if ( ep[ j ] == stack[ i ].a1 || ep[ j ] == stack[ i ].a2 )
{
s.appr_id = i ;
s.CMN_char = ep[ j ] ;
return s ;
}
}
}
}
}
void destroy ( int id )
{
used[ id ] = 1 ;
}
int get_center_id ( char a )
{
int i ;
for ( i = 0 ; i < N * 2 ; i++ )
if ( base[ i ] == a )
return i ;
}
int get_comparer ( void )
{
int i , j , k ;
for ( i = 0 ; i < n ; i ++ )
{
if ( used[ i ] == 0 )
for ( j = 0 ; ep[ j ] != '\0' ; j ++ )
if ( stack[ i ].a1 == ep[ j ])
for ( k = 0 ; k < 15 ; k ++ )
if ( stack[ i ].a2 == ep[ k ] )
return i ;
}
printf ( "\nWrong set of genes....\n" ) ;
exit ( 0 ) ;
}
void compare_and_merge ( int cid, int cp_id1, int cp_id2 )
{
int base_cp_id , i ;
char temp = ( ucmn_char == stack[ cid ].a1 ) ? stack[ cid ].a2 : stack[ cid ].a1 ;
for ( i = 0 ; i < N * 2 ; i ++ )
if ( base[ i ] == temp )
base_cp_id = i ;
if ( stack[ cid ].d == ( sqrt ( pow ( ( cp_id1 - base_cp_id ) , 2 ) ) ) )
{
base[ cp_id1 ] = cmp1[ cp_id1 ] ;
return ;
}
else
{
base[ cp_id2 ] = cmp2[ cp_id2 ] ;
return ;
}
}
void show_stack ( void )
{
int i ;
printf ( "The gene sets you entered are: \n" ) ;
printf ( "____________\n" ) ;
for ( i = 0 ; i < n ; i ++ )
if ( used[ i ] == 0 )
printf ( "%c %c %d\n" , stack[i].a1, stack[i].a2, stack[i].d ) ;
printf ( "____________\n" ) ;
}
int main ( void )
{
printf ( "Enter number of gene sets: " ) ;
scanf ( "%d" , &n ) ;
stack = ( gene* ) calloc ( n , sizeof ( gene ) ) ;
used = ( int* ) calloc ( n , sizeof ( int ) ) ;
int i ;
N = 0 ;
for ( i = 0 ; i < n ; i ++ )
{
char y[ 2 ] ;
scanf ( "%s" , y ) ;
stack[ i ].a1 = y[ 0 ] ;
scanf ( "%s" , y ) ;
stack[ i ].a2 = y[ 0 ] ;
scanf ( "%d" , &stack[ i ].d ) ;
N += stack[ i ].d ;
used[ i ] = 0 ;
fflush ( stdin ) ;
}
randomize();
show_stack ( ) ;
int ff ;
strcpy ( ep , " " ) ;
cmp1 = ( char* ) calloc ( N * 2 , sizeof ( char ) ) ;
cmp2 = ( char* ) calloc ( N * 2 , sizeof ( char ) ) ;
base = ( char* ) calloc ( N * 2 , sizeof ( char ) ) ;
for ( i = 0 ; i < N * 2 ; i ++ )
base[ i ] = cmp1[ i ] = cmp2[ i ] = '=' ;
base[ N ] = stack[ 0 ].a1 ;
base[ N + stack[ 0 ].d ] = stack[ 0 ].a2 ;
destroy ( 0 ) ;
ep[ 0 ] = stack[ 0 ].a1 ;
ep[ 1 ] = stack[ 0 ].a2 ;
for ( ff = 0 ; ff < n / 2 ; ff ++ )
{
ap_set = find_appr ( ) ;
cmp1[ get_center_id ( ap_set.CMN_char ) ] = ap_set.CMN_char ;
cmp2[ get_center_id ( ap_set.CMN_char ) ] = ap_set.CMN_char ;
ucmn_char = ( stack[ ap_set.appr_id ].a1 == ap_set.CMN_char ) ? stack[ ap_set.appr_id ].a2 : stack[ ap_set.appr_id ].a1;
cmp1[ cp_id1 = get_center_id ( ap_set.CMN_char ) + stack[ ap_set.appr_id ].d ] = ucmn_char ;
cmp2[ cp_id2 = get_center_id ( ap_set.CMN_char ) - stack[ ap_set.appr_id ].d ] = ucmn_char ;
populate_ep ( ucmn_char ) ;
destroy ( ap_set.appr_id ) ;
cid = get_comparer ( ) ;
compare_and_merge ( cid , cp_id1 , cp_id2 ) ;
destroy ( cid ) ;
}
int start , end ;
for ( i = 0 ; i < N * 2 ; i ++ )
if ( base[ i ] != '=' )
{
start = i ;
break ;
}
for ( i = N * 2 - 1 ; i >= 0 ; i -- )
if ( base[ i ] != '=' )
{
end = i ;
break ;
}
for ( i = start ; i <= end ; i ++ )
printf( "%c" , base[ i ] ) ;
printf( "\n\n" ) ;
}
```
] |
[Question]
[
Consider a NxN pixel grid with up to M objects drawn on it, either squares or diamonds:
[](https://i.stack.imgur.com/stm2o.png)square
[](https://i.stack.imgur.com/lUjYS.png)diamond
The objects may overlap, so recognition is hard. The task is to give the minimal possible **numbers of objects per shape** that can be "seen" in the picture and tell how many squares, how many diamonds, and how many objects with unknown shape there are.
You can find a reference algorithm that solves the problem [**here**](https://ai.stackexchange.com/a/34554/25362).
Here are some examples with their intended numbers (nsquare, ndiamond, nunknown). The examples with nunknown = 1 are those with pixels that may either come from a square or a diamond (highlighted in black, but not bearing any information that may be used).
[](https://i.stack.imgur.com/HVIY0.png)
The program with shortest mean runtime in terms of grid size N wins!
And this is a simple test case generator:
```
let N = 10
// initialize the grid
let grid = Array.from(Array(N), () => new Array(N));
// choose a random number of objects <= M
let n = Math.ceil(Math.random()*M)
// create objects
while (n-- > 0) {
// choose random position, but not on the border of the grid
var i = Math.ceil((N-2)*Math.random())
var j = Math.ceil((N-2)*Math.random())
if (Math.random() > 0.5) {
// draw a square
for (var k = -1; k <=1; k++) {
for (var l = -1; l <=1; l++) {
grid[i+k][j+l] = 1
}
}
} else {
// draw a diamond
for (var k = -1; k <=1; k++) {
for (var l = -1; l <=1; l++) {
if (!(k && l)) {
grid[i+k][j+l] = 1
}
}
}
}
}
```
Some small test cases:
[](https://i.stack.imgur.com/yvhRN.png)
[Answer]
# [Haskell](https://www.haskell.org/), O(2ⁿ)
```
import Data.Bits
import Data.List
listFromPair=uncurry((.pure).(:))
s`isSubsetOf`p=s.&.p==s
bsum=foldl(.|.)0::[Integer]->Integer
numbers n p=let
w=[0..n-3]
diamond=[1,n+0,n+1,n+2,2*n+1]
square=diamond++[0,2,2*n,2*n+2]
solutions=sortOn length$filter((p==).bsum)$subsequences$
filter(`isSubsetOf`p)[bsum[bit(r*n+c+d)|d<-s]|r<-w,c<-w,s<-[diamond,square]]
minlength=length$solutions!!0
best=takeWhile((minlength==).length)solutions
numb=map minimum.transpose$map(map length.listFromPair.partition((9==).popCount))best
in numb++[minlength-sum numb]
```
[Try it online!](https://tio.run/##VVFNaxsxEL3rVyiwFCneFes1pK2xcmhLoVBIoYccloVovXIsoq9oJELB/92V7I2THDQaZt7MezOzF/AktT4elfEuRPxDRMG@qQjofeC3goh0Nj@DM3@ECjzZbQrhHyHMpyApI2tKETwo@JtGkPFu9@A5sE/Mcw5ohGT4zulJE3ZgtF2v@182ykcZhuZ29pBNZpQBsMWeaxkRfuF9y5htVgPCkxLG2Yn3y9ou2vzK39XddfZyGp6TCJLPqMWib@tT8gToCsDpFJWzwCEPdWexlvYx7qud0lEGQrJMyopMWkEZ4DlJu5VQIYzxjPkwG@0LuB9VJCFTbBcTPUybBoZD2DQv9bYY2DT9rKg@CxyyEqPsmZvPEi7Srq5ahEcJkUfxJO/3SktC3uBZ4NmjlwqEy9K4Eb60VSYZFoOw4B3IKkdJyZyL2PvrMS9CVKUFIV9LY@/8d5dspLTwI6zsqXNe5IW/yfOegsPRCGW5D8rG6vVon/PaTKHEeSVVv7xhbPllyPVdx1h3U7xVPuaqG47/AQ "Haskell – Try It Online")
] |
[Question]
[
Commentscript is a variant on Javascript that I made up for the purpose of this question. Only commented-out code is evaluated.
Javascript has two types of comments:
```
// this is a single line comment, which starts with `//` and ends on a newline.
/*
This is a multiline comment.
It starts with /* and ends with */
```
Example:
```
//console.log('goodbye world')
console.log('hello world')
```
will output `goodbye world` to the console.
Your challenge is to compile Commentscript code into regular Javascript.
## Scoring
This is code-golf, so shortest bytes wins!
## Clarifications
Nested comments like `// comment // nested comment` should just have the top-level comment removed, for example `comment // nested comment`.
To avoid complications, comments in strings should be read as comments, e.g. `'abc //' def //ghi` => `' def //ghi`
Newlines from single line comments should be kept, but ones by multiline comments shouldn't.
Ignore shebangs, e.g. `#! /usr/bin/env node`
```
//a
//b
=>
a
b
/*a*/
/*b*/
=>
ab
```
## Test cases
```
//console.log('hello world') => console.log('hello world')
//console.log('hello world')//do stuff => console.log('hello world')//do stuff
/*var a = 5;*/function f(){}/*console.log(a)*/ => var a = 5; console.log(a)
/////////// => /////////
//console.log('hello world')/*More nested comments*/ => console.log('hello world')/*More nested comments*/
"abc //" def //ghi => " def //ghi
//a
//b
=>
a
b
/*a*//*b*/ => ab
//a
//b
//c
=>
a
b
c
/*
for(var x of array){
console.log(x)
}
*/
=>
for(var x of array){
console.log(x)
}
/*
//this is a comment
*/
=>
//this is a comment
#!/usr/bin/env node => [NOTHING]
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 63 bytes
```
(//.*|/\*(.|¶)*?\*/|¶)|.
$1
//(.*)|/\*((.|¶)*?)\*/|(¶)¶*
$1$2$4
```
[Try it online!](https://tio.run/##hY5BTsMwEEX3PsVQItWehUcgWCHECbhBN05iN5FSj2Q7pajptXqAXizYgaKuYGTLI78/f36wqfdmniWRxok2KPV0OSt82yCVZtKiehBEUqNa8JWrIpC5vZwxS6rH6mmeiRr2kQerB97KdWeHgeGDw9CulRB/UaKWIabRuazDvQlg4BWeX5Dc6JvUswcn1fFEeOthFFLx/a1/luA7BwvexmRbaHi3sz7FYrEydQNEK2ity@@264uTybcueQwSYf29ywghfv6pKVA4DrIkPgA7MCGYT3UUkOs2yUGJk1gcMA@mro@Qj7mmWND9HY0xUN17sn4Pnlv7BQ "Retina 0.8.2 – Try It Online") Link includes test cases, but the newline-collapsing rule means that they're not double-separated on output. Explanation:
```
(//.*|/\*(.|¶)*?\*/|¶)|.
$1
```
Delete anything not a newline or comment.
```
//(.*)|/\*((.|¶)*?)\*/|(¶)¶*
$1$2$4
```
Keep the content of comments and one newline of consecutive newlines.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 5 years ago.
[Improve this question](/posts/152305/edit)
## Challenge
Given a grid like this,
```
1 2 3 4 5 6 7 8
1 . . . . . . . .
2 . # . . . # . .
3 . . . . . . . .
4 . . . . . . . .
5 . . . . . . . .
6 . . # . . . . .
7 . . . . . . . .
8 . . . . . . . .
```
write a piece of code that can determine the size of the largest square that does not include a '#'. (The answer to this input is 5x5 as the bottom right 5x5 grid is the biggest square possible).
The square must have sides parallel to the x and y axes.
As some small details: the original grid is always a square and its side length is given to you. The coordinates of the '#' symbols are also given to you.
## Input Details
First line: N (1 <= N <= 1000), the side length of the square grid, and T (1 <= T <= 10,000) the number of '#' signs.
Next T Lines: The coordinates of each of the T #'s
## Test Cases
Input #1:
```
8 3
2 2
2 6
6 3
```
Result #1: 5
================
Input #2:
```
8 4
1 1
1 8
8 1
8 8
```
Result #2: 6
================
Input #3:
```
5 1
3 3
```
Result #3: 2
This is a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") problem, so the fastest code tested on the [rextester](http://rextester.com/) compiler wins.
Have fun!
[Answer]
# [Node.js](https://nodejs.org)
Takes input as **(w, l)**, where **w** is the width and **l** is an array of coordinates **[x, y]**. (This may be changed if the input format really is as strict as described.) Works in **O(w²)**.
```
f = (w, l) => {
var x, y,
W = w * w,
a = new Uint16Array(W),
best = 0;
l.forEach(([x, y]) => a[(y - 1) * w + x - 1] = 1);
for(y = w; y < W; y += w) {
for(x = y + 1; x < y + w; x++) {
if(a[x]) {
a[x] = 0;
}
else {
best = Math.max(
best,
a[x] = Math.min(a[x - 1], a[x - w], a[x - w - 1]) + 1
);
}
}
}
return best;
}
```
[Try it online!](https://tio.run/##fVDBToNAFLzvV0ziZVe2rdC0IaU18eDRi4npgXBY62IxCAZogZh@O76FQjGpctidN2/em1k@1FHluyz6KiZJ@qabJsQGvJSIBTb3@GbAUWWoJGpJ2HxbUpS4RdkTiohEl3iJksJePmSZqvlW9N1XnRckuPMYEfE0TLNHtdtz7pudQeuifF5jAluYrbBQmSKgIVu0UzRDAnL1UGONrbksKkWbr@tX1CcWtkfj6xaSvLKsXgREIVd@FVwIik51F66rT@dbx7keyc5veFLFfvqpKj40upYc1eeNnTRKjGP7GokOlRfU8sJkHubF7yDmPJk/kOnikCWtmcdOzS5N8jTW0zh956FJ45oIfjvjOxJOIAe87PFSYh4QDJgQHmYzPOv8EBe4sVdYMMb@XWpL84YBuz12R7xr@GsGzgrLawaLkcH8r3TzFRzW/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# C (gcc)
No fancy algorithm here, just almost-bruteforce... but hey, C is fast.
**Input:** Takes input from *stdin*.
**Output:** Writes output to *stdout*.
```
#include <stdio.h>
#include <stdint.h>
int main(void) {
uint_fast16_t n, t, i, j, h, x, y, flag, biggest = 0;
scanf("%hi %hi", &n, &t);
uint_fast8_t m[n][n];
for (uint_fast16_t c = 0; c < t; ++c) {
scanf("%hi %hi", &i, &j);
m[i-1][j-1] = '#';
}
for (i = 0; i < n - 1; ++i) {
for (j = 0; j < n - 1; ++j) {
flag = 1;
for (h = 1; flag && i + h < n + 1 && j + h < n + 1; ++h) {
for (y = i; flag && y < i + h; ++y) {
for (x = j; flag && x < j + h; ++x) {
if (m[y][x] == '#') flag = 0;
}
}
if (flag && h > biggest) biggest = h;
}
}
}
printf("%d", biggest);
}
```
[Try it online!](https://tio.run/##bZHxaoMwEMb/1qf4aJlVTMdsoRTs@iJSitNqEqodNR3K8NndJamthYFJyN33/bzLZcsyy4ZhLursfMtP2DUqF5d3vndfQ7XSMZdOVKmo/Z@LyAP8us6NQscibVS0OSrUDIpBMEgGztAydAzFOS0ZvkRZnhqFT3zErtNkaV34szcuQGvG4JHVU0E8IW4JWCX1gT4KF5cr/Ne/ZQZGxw4qRhhmpqJ/2FSQJzXbqRKxjA6JpI3Mi/mCgv0dLixOEK7GEpFGCos0eWnzcpqXNu/oHikdxeai1dxcTfPwPKKG4MYZItIBOQ1oFL@jrL0ju3ja0ZHUMLS0G6VW25JWPrUtSeUobR9SRxTwq6Q7JC31bpoPcK/7I7aa3n3uWj4iOfbjAIPJJLmxaXlvnvH7SvPRT5/PHgOnZ@@HYYu1u8KK1sbdYP0H "C (gcc) – Try It Online")
] |
[Question]
[
[<< Prev](https://codegolf.stackexchange.com/questions/149660/advent-challenge-1-help-santa-unlock-his-present-vault) [Next >>](https://codegolf.stackexchange.com/questions/149820/advent-challenge-3-time-to-remanufacture-the-presents)
# Challenge
Now that Santa has finally figured out how to get into his present vault, he realises that somehow the elves got in there before him and stole some of his presents! They haven't figured out how to leave the vault yet though, so Santa has to try and catch them all. Santa and the elves both have infinite energy to run around but unfortunately the elves have a higher infinity of energy, so if they end up running in loops everywhere, the elves have gotten free.
Given a graph of `n` nodes and `e` edges with a walk existing between any two nodes, and the positions of the elves and Santa, determine how many elves Santa can catch before he gets tired.
The chase is turn-based. Each cycle, the elves first all move simultaneously (they can move through each other and onto the same node as well), and then Santa will move. If Santa moves onto the same node as an elf, then he has caught that elf. Each elf may only move from one node to its neighbour in one step. The same goes for Santa in the beginning, but for every elf he has caught, Santa can take one extra step. So, if Santa has caught an elf, then he can move from a node to its neighbour's neighbour. This means he could move to a node and then back. However, since Santa is running too quickly during this time period, he will not catch any elves that passes in the intermediate steps (so if he is on A, A is connected to B, B is connected to C, there is an elf on B, and Santa moves from A -> B -> C, the elf has not yet been caught). However, Santa doesn't have to move that many steps at once; he moves up to 1 + (number of elves caught) each turn.
Note that all of the elves must move each turn, and if an elf moves onto Santa's node, they get caught.
All entities (elves, Santa) will be on distinct nodes in the beginning.
# Specifications and Rules
Your program should theoretically work for input of any size. The input will be given as a graph, the positions of the elves, and the position of Santa. You may take the graph in any reasonable format (list of nodes + list of edges, list of edges, adjacency matrix, cycle notation, etc), and you may take the positions in any reasonable format that works with your graph input format (index in the list of nodes, etc). The output should be a single positive integer indicating the maximum number of elves that Santa can catch.
# Test Cases
These are given as lists of edges and node numbers for positions.
```
Input -> Output
[(0, 1), (1, 2)], [0, 2], 1 -> 2 # Easy win for Santa, the elves get themselves caught :P
[(0, 1), (1, 2), (2, 3), (3, 0)], [0, 1], 2 -> 2 # The elf opposite of Santa cannot escape but the other one can always just run away each turn, until Santa catches the first elf. Then he can easily just catch the rest.
[(0, 1), (1, 2), (2, 3), (3, 0)], [1], 0 -> 0 # Santa will never catch up
[(0, 1), (1, 2), (2, 3), (3, 0), (1, 4), (4, 5), ..., (10, 11), (11, 3)], [2, 6], 0 -> 2 # The first elf moves to either 1 or 3 and then gets caught. Then, Santa can use his 2-step move to catch up to the second elf no matter what.
```
I think Santa can catch either no elves or all the elves, so this challenge might just be "can he catch an elf" *hint hint*
# Rules
* Standard Loopholes Apply
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest answer in bytes wins
* No answers will be accepted
Happy Golfing!
Note: I drew inspiration for this challenge series from [Advent Of Code](http://adventofcode.com/). I have no affiliation with this site
You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge [here](https://codegolf.stackexchange.com/questions/149660/advent-challenge-1-help-santa-unlock-his-present-vault).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 129 bytes
```
Block[{a=#},Clear@f;s_~f~e_:=If[s==e,1,s~f~e=0;s~f~e=Min[(hMax[#~f~h&/@a@s,Boole[h==s]])/@a@e]];Tr[Max[(e#3~f~e)/@#2]^#2]]&
```
[Try it online!](https://tio.run/##tY@/TsMwEMb3PMVJkaq0MoLEmRpcRWViqMTAZpnqlDrEkDjIdhGoTR@CN@AJeYTgpCpi6cDAYJ2/3/357hp0lWzQqQL7BpUut7pg/bJui2e@QxZ25KaWaPIys@tDeZDrObstuWVMkpjYgbCr7BhXSvOo@vr4XOEbDz2qJpc55pYs27aWvGLMCjEdkBQiuzd8qIukbwjpMMCnwkQ8@CcmfTQDNI/bRmpnoTUbaeZBCAxw84SF1MU71Mo6AmHioaxfpYWX1iqnWu0h9dCidvgDYTYNgjujtOMBwOnS4Q9wvY/hYgG7hEDaEUhGEROgXtDfmXQUlEDc7Rdk7D3VJV6JQPyPR/o3A3rW4Pze/Tc)
Similar approach to my answer to [this question](https://codegolf.stackexchange.com/questions/125804/get-me-back-down-to-1-rep).
The function takes 3 arguments as input: adjacency list represented as an association ([tool to generate adjacency list from edge list](https://codegolf.stackexchange.com/questions/149746/advent-challenge-2-the-present-vault-raid#comment366424_149746)), elves position and santa position.
Note that `Clear[f]` is necessary, because function submissions must be reusable.
The code below is ungolfed code with partial explanation. More explanation later.
```
reverseBoole = # != 0 &
(* Or@@{a, b} === reverseBoole[booleOr[Boole[{a, b}]]] *)
booleOr = Max
booleAnd = Min
(* Boole@f[s, e] = Santa can catch Elf ? *)
mainfunc = Block[{adjlist = #},
Clear[f];
f[s_, e_] := If[ s == e, f[s, e] = 1,
f[s, e] = Boole[False];
f[s, e] = booleAnd[
(e1 booleOr[
( s1 f[s1, e1] ) /@ adjlist[s],
Boole[e1 == s]
]) /@ adjlist[e]
]
];
If [ 0 == booleOr[ ( e f[#3, e] ) /@ #2 ] , 0, Length[#2] ]
]&
```
---
[Answer]
# Python3, 691 bytes
```
R=range
def T(g,s):
q=[[s]]
while q:A=q.pop(0);yield(l:={b for i in A for a,b in g if a==i});q+=[l]
def f(g,e,s):
q,a,D,v=[(e,0,s,0)],[(e,s)],{},[]
while q:
E,c,S,B=q.pop(0);v+=[B]
if c<len(E):
if E[c]==-1:q+=[(E,c+1,s,B)];continue
J=1
for i in next(T(g,E[c])):
O=[*E];J=0
if i!=S:
O[c]=i
if(O,S)not in a:J=0;q+=[(O,c+1,S,B)]
else:O[c]=-1;q+=[(O,c+1,S,B+1)]
if J:q+=[(O,c+1,S,B)]
else:
t,L=T(g,S),0
for i in R(max(sum(k==-1for k in E)+1,1)):
for I in R(L,i+1):M=next(t)
L=i+1
for I in M:
O=[*E];x=B
for y in R(len(E)):G=O[y]==I;O[y]=[O[y],-1][G];x+=G;v+=[x]
if(O,I)not in a:q+=[(O,0,I,x)];a+=[(O,I)]
return max(v)
```
[Try it online!](https://tio.run/##lVLPb9owFL7zV7zd7PGYYmgpDfOhaAiBqJDKbpYPKXWo1TQJSWCgqn8787PL2k6ttF3y@T1/P/zslIfmvsh7g7I6Hm9kleRr07ozKfxka6x53IKNVKrWugW/7m1mYBNfyc23sihZxIcHa7I7lsXy6RbSogILNocrv0zwloo12BQSKe0zH27aUmXau6fO3bz4Y4I/cCcVMxhhjRHXSOva4dMzqjfJLYAxrnCJo9cj7JzpyHEoZ/U9Mzkbk6uvx2qlpeyImJKZk7aFCxhxPVwVeWPzrSHiTAqCP@fPzb5hND7JeTCDhVRfx3o4k5Evnbn9IpdhDxaUY8PapmyBS54XDXklsVP4wV2X4pcU75kmq03slR3xF6MtAselzOIPxF5KhAbnkk665Bi9m@GGPSZ7Vm8f2QNdAPUfqD/mzkachqL2NNDnaF1qfC399A33@3Ppmu@Z16eRw33s5SjURDgEq/AGPJ7IhTq4@58OPSr6YkdoNXG6tpz4p9vrN9c2fb22l6kjnOLevVcSyimNX5lmW@VAA@74saxs3rCUKRYhCI7ABELX/TugXKOrqclbn7AcdhF6hD2E6KQSmjb/S0WS6N8loX9GeIZwTniO0CfsI1wQXiAMCAcIl4SXzi8IyTlYC/KkeGfeDyc4/gY)
Also, a 808 byte solution that uses caching for faster execution: [try it online](https://tio.run/##lVJNbxoxEL3zK6Y3uwzVGhJClvoQBEJ8SEjZcrJ82JCFrEIW2F0oKMpvpzM2CaRqpfayY4/fe/P8vOtD@bTKGq11fjze6zzOFknlMZnDD7HAQoYV2GhjCmsr8PMpXSawCe/05tt6tRaBbB/SZPkolqF@fYD5KocU0gzu3DLGB94sIJ1DrHX6JtubqjZL69TnpJ6c9DHGLu60EQkGWGAgLfK6oPr6huZicgWghzOMsHO2sCPRDmFgpIvti3jWuqZ4/jNP70k6IAMjrZdJJnoynK2yMs22ie/Pvp/atOV9z8wsC4RsVdCsqiJHHWnbFzyYasFAVPJEm0K2KnleN@yaqdVZsi8FB8gw6VBDrbh8hMQ4NxUm2nzt2fZQB25LcukXHfkzmLCh1K/TuZhgJE@j4pAYLlLqss@IfTpksiyS0DFr6jdEVXkMTRmGfyA7KgNKHGu@QSQx@GT8XrzEezEijpI@NzYWYUrSHyl4w8wZeM7YnVM6hBywCZ9R6bKBsabTyieKQ46lfc/Bh7TXnbP0wUv7F5RhX0/MgV5v0HbV8Bdrypo@8aq63/ZM/l/29iLRwTnRUyABDnBPbx777YCTyZNym2fAd9/J4zpPs1LMhREBgpIIQiHU6YcFQ4265aas/AVFtY7Q4NpACN5ZyvLhf7GYEvw7xfevuF4hXHO9RmhybSLccL1BaHFtIdxyvSU9T2RlL61Yk8eTeNM7OP4C)
] |
[Question]
[
A cruise control has 3 different options to move the handle to set the speed you want to drive with.
* Towards you: Adds 1 speed.
* Upwards: Increases speed to the next multiple of 10 (e.g. 20-->30, 32-->40)
* Downwards: Decreases speed to the next multiple of 10 (e.g. 20-->10, 32-->30)
**Input**
* 2 integers: the first is the starting speed and the second is your desired speed, both non-negative and in any form you like (array, two arguments, etc.)
**Task**
* Determine the optimal way of using the handle to reach the desired speed and print out the moves in the correct order.
**Rules**
* If you have the choice between pulling towards you and going upwards (like from 39 to 40) you can choose either option, but stay with whatever you choose for similar cases
* You may use any 3 different (preferably visible) symbols to distinguish between the moves in the output (T, U and D for example).
* The symbols can be seperated by new lines, spaces, etc. but don't have to be
Here are some test cases:
```
start speed, desired speed --> output
30, 40 --> U
30, 43 --> UTTT
43, 30 --> DD
51, 39 --> DDDTTTTTTTTT
29, 30 --> T or U
29, 50 --> TUU or UUU
12, 12 -->
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins.
[Answer]
# JavaScript (ES6), ~~91~~ ~~84~~ 75 bytes
*Saved 4 bytes thanks to @Neil*
```
f=(s,d)=>s-d?(q=s+10-s%10)>d?s>d?0+f(s-(s%10||10),d):1+f(s+1,d):2+f(q,d):""
```
Uses `0` for `D`, `1` for `T`, and `2` for `U`.
[Answer]
# Java, 144 139
Saved 5 bytes thanks to Kevin.
```
void o(int s,int e){int t=10,x=s/t;System.out.print(s>e?"D":s<e?x<e/t?"U":"T":"");if(s!=e)o(s>e?x*t-(s%t<1?t:0):s<e?x<e/t?(x+1)*t:s+1:0,e);
```
Ungolfed
```
public static void optimalCruise(int start, int end){
if(start > end) {
System.out.print("D");
optimalCruise(start/10*10-(start%10<1?10:0), end);
} else if(start < end){
if(start/10 < end/10){
System.out.print("U");
optimalCruise(((start/10)+1)*10, end);
} else {
System.out.print("T");
optimalCruise(start+1, end);
}
}
}
```
[Answer]
## Batch, 175 bytes
```
@set/as=%1,d=%2,e=d/10*10
:d
@if %s% gtr %d% echo d&set/as=~-s/10*10&goto d
:u
@if %s% lss %e% echo u&set/as=s/10*10+10&goto u
:t
@if %s% neq %d% echo t&set/as+=1&goto t
```
Fairly straightforward this time. Takes input as command-line parameters, which it saves into `s` and `d`. `e` is `d` rounded down to the previous multiple of 10. If `s` is greater than `d`, then we obviously need to invoke `d` until `s` becomes lower than `d`. Otherwise, we need to check whether `s` is lower than `e`; if so, we can invoke `u` until `s` equals `e`. At this point `s` is now between `e` and `d` and we can simply invoke `t` until we reach `d`. I looked into `for` loops but they use inclusive endpoints so would have become too verbose.
[Answer]
# Python, 76 bytes
```
lambda a,b: "U"*(b//10-a//10)+"D"*(a//10-b//10+(b<a))+"T"*min(b%10,(b-a)%99)
```
[Answer]
# C, 156 bytes
```
t,x,y;main(int s,char**a){x=(s=atoi(a[1]))/10,y=(t=atoi(a[2]))/10;if(s^t){for(;y>x;++x)puts("U");for(x+=(s-t>10);x>y;--x)puts("D");for(;t--%10;)puts("T");}}
```
Ungolfed:
```
#include <stdio.h>
#include <stdlib.h>
int t, x, y;
int main(int s, char **a)
{
x = (s = atoi(a[1])) / 10,
y = (t = atoi(a[2])) / 10;
if (s ^ t) {
for ( ; y > x; ++x)
puts("U");
for (x += (s - t > 10) ; x > y; --x)
puts("D");
for ( ; t-- % 10; )
puts("T");
}
return 0;
}
```
] |
[Question]
[
## Background
Back in the late 90's / first 00's when Flash Web Design was so much cool that noone could live without having a full Flash website, or at least an animated widget, I was hired to develop a "horse races viewer" in Flash/Actionscript, in the shape of an 80's videogame style animation, so the site's visitors could not only read the race results, but they could see it in a moving animation! *WOW! Impressive!*
They provided me a CSV file with all the races details: start and arrival order, horse names, driver names, prizes, etc. My Flash app read that file for each race and displayed the above said animation.
Nowadays the Flash support is significantly declined, so we must revert to **ascii-art**!
## Task
Your task is to create a full program or function that reads the race data in CSV format from standard input and outputs an ascii-art representation of the race as shown in the example below.
**INPUT**
CSV data with 2 fields: 1) start order; 2) arrival time at the Finish in the format `1.13.4` (1 minute, 13 seconds, 4 tenths of second). If the time reports `R` means that the horse is Retreated (didn't finish the race) due to incident, fall or other reason. Note: The arrival time could be the same for 2 or more horses, in this case they share the arrival position.
```
1,1.13.4
2,1.13.0
3,R
4,1.12.7
5,1.11.5
6,1.13.4
7,1.12.1
8,1.17.9
```
**OUTPUT**
For each CSV row, output a racetrack like this:
```
1_|______________4(1.13.0)___________________________
```
The racetrack is composed by:
* `1` which is the horses start order.
* `_|` where `_` is a spacer and the `|` is the finish line.
* 50 x `_` that represents 50 tenths of second.
* `5(1.13.4)` that is the arrival position followed by the arrival time. This must be positioned respecting the time differences between horses. For example: you position the 1st arrived on the Finish line at time `1.11.5`, the second arrives at time `1.12.1`, the difference is `1.12.1 - 1.11.5 = 6` tenths of second, so the second horse should be positioned at the 6th character, and so on. If the time difference is more than 50 tenths of seconds (or 5 seconds) you must position the horse at the end. The same if the horse is `R` (Retreated).
So the whole racetrack for the CSV data above should be:
```
F=Finish line
1_|____________________________5(1.13.4)_____________
2_|______________4(1.13.0)___________________________
3_|__________________________________________________R
4_|___________3(1.12.7)______________________________
5_1(1.11.5)__________________________________________
6_|____________________________5(1.13.4)_____________
7_|_____2(1.12.1)____________________________________
8_|__________________________________________________6(1.17.9)
012345678901234567890123456789012345678901234567890
```
There is no need to add `F=Finish line`, and the last line `0123456789...` that is only for explaining purpose.
## Test cases
```
RACE:
1,1.14.9
2,R
3,R
4,1.14.2
5,1.15.2
6,1.15.3
7,1.15.3
RACE:
1,1.13.6
2,1.13.8
3,R,
4,1.15.9
5,1.13.8
6,R,
7,1.14.4
8,1.15.6
9,1.14.1
10,1.13.9
11,1.13.2
12,1.14.3
13,1.15.0
RACE:
1,1.13.4
2,1.13.0
3,R
4,1.12.7
5,1.11.5
6,1.13.4
7,1.12.1
8,1.17.9
RACE:
1,1.17.3
2,1.20.4
3,1.17.0
4,1.18.8
5,1.18.5
6,1.18.4
7,1.18.4
8,1.17.8
9,1.18.3
10,1.18.7
11,R
RACE:
1,1.17.5
2,R
3,1.17.7
4,1.16.9
5,1.16.1
6,1.18.9
RACE:
1,1.12.8
2,1.13.0
3,1.13.2
4,1.12.7
5,1.11.5
6,1.13.0
7,1.12.1
8,1.12.8
```
## Rules
* Shortest code wins.
[Answer]
## JavaScript (ES6), 261 bytes
Takes an array of time strings `"1.ss.t"` as input. The start order is implicit.
```
a=>a.map((t,i)=>(u='_',++i>9?'':' ')+i+u+u.repeat(x=(x=t>'9'?50:t.slice(2)*10-s[0].slice(2)*10)>50?50:x,p=s.indexOf(t)+1+`(${t})`).replace(u,'|')+(x<50?p:'')+u.repeat((x=50-p.length-x)>0?x:0)+(x>0?'':t>'9'?t:p),s=a.filter((v,i)=>a.indexOf(v)==i).sort()).join`
`
```
### Demo
```
let f =
a=>a.map((t,i)=>(u='_',++i>9?'':' ')+i+u+u.repeat(x=(x=t>'9'?50:t.slice(2)*10-s[0].slice(2)*10)>50?50:x,p=s.indexOf(t)+1+`(${t})`).replace(u,'|')+(x<50?p:'')+u.repeat((x=50-p.length-x)>0?x:0)+(x>0?'':t>'9'?t:p),s=a.filter((v,i)=>a.indexOf(v)==i).sort()).join`
`
console.log(f([
"1.13.4",
"1.13.0",
"R",
"1.12.7",
"1.11.5",
"1.13.4",
"1.12.1",
"1.17.9"
]));
console.log(f([
"1.13.6",
"1.13.8",
"R",
"1.15.9",
"1.13.8",
"R",
"1.14.4",
"1.15.6",
"1.14.1",
"1.13.9",
"1.13.2",
"1.14.3",
"1.15.0"
]));
```
[Answer]
# Python 2, ~~282~~ ~~272~~ 246 bytes
Similar to [Arnauld](https://codegolf.stackexchange.com/a/98457/53667) the input is assumed to be already stripped from the starting number since it is implicit.
```
H=input().split("\n")
T=[float(c[2:])if c[2:]else 99for c in H]
P=[min(int(10*(t-min(T))),50)for t in T]
S=sorted(list(set(T)))
i=0
u="_"
for h,p,t in zip(H,P,T):i+=1;s=S.index(t)+1;print`i`+u+"|"*(s>1)+u*p+[h,"%d(%s)"%(s,h)][t<99]+u*(41-p+(s<2))
```
] |
[Question]
[
# Intro
In J. R. R. Tolkien's Lord of the Rings, this phrase is on the cover of each book.
```
Three Rings for the Elven-kings under the sky,
Seven for the Dwarf-lords in their halls of stone,
Nine for Mortal Men doomed to die,
One for the Dark Lord on his dark throne
In the Land of Mordor where the Shadows lie.
One Ring to rule them all, One Ring to find them,
One Ring to bring them all, and in the darkness bind them,
In the Land of Mordor where the Shadows lie
```
However, this isn't that interesting. It's just [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'"). Let's change this to [interesting-nonconstant-output](/questions/tagged/interesting-nonconstant-output "show questions tagged 'interesting-nonconstant-output'").
# What you have to do
Use the Stack Exchange API (or `codegolf.stackexchange.com/users`, or the Stack Exchange Data Explorer) and find the two users with the highest scores in [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the newest user, and highest-reputation user with only negatively scored [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") post.
Then, you must insert these usernames into the following text:
```
Three Golfs for the <highest-scored code-golf user>-king under the sky,
Seven for the <second-highest-scored code-golf user>-lord in their halls of stone,
Nine for the Mortal <newest user> doomed to die,
One for the Dark Lord <highest reuptation user with only negative scored code-golf posts>
In the land of Golfdor, where the Golfers lie
One Golf to rule them all, One Golf to find them,
One Golf to bring them all, and in the darkness bind them,
In the Land of Golfdor, where the Golfers lie
```
You must insert the four usernames you found into the text in the angle-brackets.
# Other Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
* No URL Shorteners (including `ppcg.(ga|lol)`)
[Answer]
# PHP, 577 bytes
not tested; I currently have no system available with `allow_url_fopen=On`
and I didn´t take the time to copy&paste the page sources.
```
function g($s){return join(file("http://codegolf.stackexchange.com/$s"));}$m=preg_match_all;$m("#r-de.+/(\d+)/.+>(.+)<#U",$a=g($u="$u&filter=all"),$b);$h=$b[2];$m("#>(.+)</a.+\s1 i#",g("users?tab=NewUsers&sort=creationdate"),$c);while($a){foreach($b[1]as$i=>$n)if($m("#st \"><strong>(-?)\d+#",$e=g("search?tab=votes&q=user:$n+[code-golf]"),$d)&&$d[1][0])break 2;if($a=strstr($a,"l=\"n"))$m("#r-de.+/(\d+)/.+>(.+)<#U",$a=g("$u&page=".$p+=!$p++),$b);}$m("#<code>(.+)</code>#U",g("q/93545"),$t);echo join([1=>$h[0],3=>$h[1],5=>$c[1][0],7=>$b[2][$i];]+split("#&[lg]t;#",$t[1][2]));
```
**breakdown**
```
// function to get page content from ppcg
function g($s){return join(file("http://codegolf.stackexchange.com/$s"));}
$m=preg_match_all;
// A,B: highest scores: find user names
$m("#r-de.+/(\d+)/.+>(.+)<#U",$a=g($u="users?filter=all"),$b);
$h=$b[2]; // remember the names
// C: new users: find username after "1 in one day"
$m("#>(.+)</a.+\s1 i#",g("$u&tab=NewUsers&sort=creationdate"),$c);
// D: loop through users from first query
while($a)
{
foreach($b[1]as$i=>$n)
// find "vote-count-post" in code-golf votes for that user
if($m("#st \"><strong>(-?)\d+#",$e=g("search?tab=votes&q=user:$n+[code-golf]"),$d)
&&$d[1][0]) // test if highest vote is negative
break 2;
// none found yet?
if($a=strstr($a,"l=\"n")) // if there is a "next" link, get next page
$m("#r-de.+/(\d+)/.+>(.+)<#U",$a=g("$u&page=".$p+=!$p++),$b);
}
$m("#<code>(.+)</code>#U",g("q/93545"),$t); // get code blocks from question page
echo join([ // 4. join and print
1=>$h[0], // first two results from first preg_match
3=>$h[1],
5=>$c[1][0], // first result from second preg_match
7=>$b[2][$i]; // $i-th username from (latest) reputation list
]+ // 3. and replace indexes 1,3,5,7 with above array
split("#&[lg]t;#", // 2. split by "<" and ">"
$t[1][2] // 1. output template is the 3rd code block
));
```
] |
[Question]
[
As if this challenge could be any more [Pythonesque](https://www.youtube.com/watch?v=uwAOc4g3K-g) in spirit... **No prior knowledge of Markov chains or encryption techniques is required.**
You are a spy who needs to obtain some crucial information from the British security service M1S. The agents of M1S are well aware that their Wi-Fi signals can be intercepted, their Android/iOS security vulnerabilities exploited etc., so all of them are using Nokia 3310’s to transmit text information which is typed using the **T9 auto-completion**.
You had previously hacked the phones to be delivered to the intelligence agency and had installed keyloggers under their glorious plastic keyboards, so now you receive sequences of numbers corresponding to the letters they typed, so “[the eagle has left the nest alert the agents](https://xkcd.com/733/)” becomes
```
84303245304270533808430637802537808430243687
```
But wait! Some T9 sequences are ambiguous (“6263” could be “name”, “mane” or “oboe”; the more obscure, the more suspicious it gets!), so what do you do? You know that the only entrance examination M1S uses is summarising Marcel Proust’s masterpiece “Remembrance of Things Past” in 15 seconds, so you want to pick the word that comes next after the previous one according to its frequency distribution in the entire chef-d’œuvre of Proust!
*Can you crack the code and obtain what could be the original message?*
## The principle of T9
[](https://i.stack.imgur.com/A6y8F.jpg)
The T9 auto-completion mechanism can be described as follows. It maps alphabetic characters to numbers as shown on the picture above.
```
abc -> 2
def -> 3
ghi -> 4
jkl -> 5
mno -> 6
pqrs -> 7
tuv -> 8
wxyz -> 9
<space> -> 0
<other> -> <is deleted>
```
The T9 decryptor receives a sequence of digits and tries to guess the word that could be typed with those keypresses. It might use a standard frequency table, but we are going one step further and predicting the next word using a Markov chain!
## Learning sample
The corpus is [this heavily stripped version of Proust’s “Remembrance of Things Past”](https://raw.githubusercontent.com/Fifis/proust/master/proust.txt) (`s/-/ /g`, `s/['’]s //g` and `s/[^a-zA-Z ]//g` — begone confusing possessive `'s`!) originally published on the [University of Adelaide website](https://ebooks.adelaide.edu.au/p/proust/marcel/) (the text of this work is in the Public Domain in Australia).
The whole text **must be analysed as one string, as one long sentence, as one long vector of words** (whichever is more convenient for your language), **stripped of linebreaks**, and **split into words at spaces**. (I do not supply a single-paragraph file because such might be frowned upon by github tools.)
How do I read the whole text as one string / sentence? An example in **R**:
```
p_raw <- read.table("proust.txt", sep="\t") # Because there are no tabs
p_vec <- as.character(p_raw$V1) # Conversion to character vector
p_str <- paste(p_vec, collapse=" ") # One long string with spaces
p_spl <- strsplit(p_str, split=" ")[[1]] # Vector of 1360883 words
proust <- p_spl[p_spl!=""] # Remove empty entries — 1360797
```
## Task
Given a sequence of digits as a number, return a possible text string that could be typed using the corresponding T9 keys using a probabilty chain to predict the next word *X* based on [this training text](https://raw.githubusercontent.com/Fifis/proust/master/proust.txt) treated as one long sentence.
If *X* is the first T9-word of the text and there are multiple guesses, pick one at random, otherwise pick the only one possible.
For all subsequent T9-words *X(i)* preceded by a word already deciphered *w(i-1)*:
1. If a T9-word *X* can be converted into a normal word *x* in one unique way, do it.
2. If there are multiple conversion options available for *X*, say *x1, x2, ...*, look up the preceding guessed word *w*.
* If *w* is never followed by anything that maps to *X* in the original work of Proust, pick any of the possible *x1, x2, ...* at random.
* If *w X* always corresponds to *w x1* in the original and there are no concurrent *xi*’s that could be mapped into *X*, pick *x1*.
* If *w X* can be converted to *w x1*, *w x2*, ... that can be found in the corpus, then count all possible *xi*’s that follow *w* and map to *X* in the corpus and pick *xi* with probability *xi/(x1 + x2 + ...)*.
**Example 2a.** If the message is `76630489`, where `489` could be `guy` or `ivy` (they occur in the corpus at least once), `7663` can be deciphered as `some` (a very probable first word). If `some` is never followed by anything that maps to `489` in the corpus, then pick `guy` or `ivy` at random with probability 0.5.
**Example 2b.** If the message is `766302277437`, where `2277437` could be `barrier` or `carrier`, `7663` can be deciphered as `some`. If Proust always used `some carrier` and never `some barrier`, then pick `some carrier`.
**Example 2c.** Suppose that you want to decipher the sequence `536307663`. `5363` was predicted as `lend`. `7663` could be any of these: `pond`, `roof` and `some`. You count the occurrences of the word following `lend` in the sample corpus. Suppose you get something like this (just to illustrate):
```
T9 Word following lend Occurrences
7663 some 7
7663 pond 2
7663 roof 1
```
So if `7663` is preceded by `lend`, there is `7/(7+2+1)=70%` probability that `7663` stands for `some`, 20% `pond` and 10% `roof`. Your algorithm should produce `lend some` in 70% cases, `lend pond` in 20% cases etc.
You may safely assume that the agents use **only a-z letters and spaces** (no punctuation marks, no possessive `'s`, and no numbers).
You may also assume that the agents of M1S **never use any words outside the scope of “Remembrance of Things Past”** (which is a whopping vocabulary of 29,237 words!).
The T9 fuctionality was implemented in [this challenge](https://codegolf.stackexchange.com/q/42220/194), so you might have a look at it.
If you need any help, probabilistic chains were gloriously tamed in [this](https://codegolf.stackexchange.com/questions/3108/using-a-markov-chain-because-this-question-itself-as-input-text-for-example), [that](https://codegolf.stackexchange.com/questions/3726/markov-chain-beatbox-generator) and [the following](https://codegolf.stackexchange.com/questions/75673/na%c3%afve-markov-chain-word-generation) challenges, but you do not even need to know the principle of such chains: everything is stated in the task.
## Test cases
```
--Inputs--
20784250276960369
20784250276960369
84303245304270533808430637802537808430243687
94280343084306289072908608430262780482737
94280343084306289072908608430262780482737
--Possible outputs--
c quick brown fox
a stick crown fox
the eagle gas left the nest blest vie agents
what did the navy pay to the coast guards
what did the navy raz un the coast guards
```
## Rules:
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* You do not know the original message, all you get is a sequence of digits and the file [proust.txt](https://raw.githubusercontent.com/Fifis/proust/master/proust.txt) that you just need to load in the memory / workspace / whatever. There is no need to have anything self-contained; assume `proust.txt` is always accessible.
* Your algorithm must be able to produce different outputs with respective probabilities if more than one decryption option is probable according to the corpus (see Example 2c).
You need to stay as discreet as possible, so the shortest code wins!
**P.S.** The obvious benefit of this probabilistic algorithm is the fact that the probability you will get a true original string for an ambiguous deciphered string tends to one — just wait...
**P.P.S.** See also [Prediction by Partial Matching](http://compressions.sourceforge.net/PPM.html).
[Answer]
## R solution, non-competing illustration of what can be done
Firstly, we load the sequence of words into the memory:
```
p_raw <- read.table("proust.txt", sep="\t") # Because there are no tabs
p_vec <- as.character(p_raw$V1) # Conversion to character vector
p_str <- paste(p_vec, collapse=" ") # One long string with spaces
p_spl <- strsplit(p_str, split=" ")[[1]] # Vector of 1360883 words
proust <- p_spl[p_spl!=""] # Remove empty entries — 1360797
```
Secondly, we need a function that T9-ifies any text:
```
t9 <- function (x) {
x <- chartr(paste(c(letters, " "), collapse=""), "222333444555666777788899990", tolower(x))
x <- gsub("[^0-9]", "", x, perl = TRUE) # Safety check
x <- x[x!=""] # Also for safety because... you know...
x
}
```
Then, we T9-ify Proust:
```
p9 <- t9(proust)
```
Final preparation: we split the input string at zeros using a function that we call `prep`):
```
prep <- function (x) {
x <- chartr("0", " ", x)
x <- strsplit(x, " ")[[1]]
x <- x[x!=""] # Boil the empty strings for safety
x
}
```
And now I propose a function that takes any input string of numbers, `prep`s it and deciphers the words one by one:
```
decip <- function(x, verbose = FALSE) {
x <- prep(x)
l <- length(x)
decrypted <- rep(NA, l)
tb <- table(proust[which(p9 == x[1])])
decrypted[1] <- sample(names(tb), 1, prob=tb/sum(tb))
if (verbose) print(decrypted[1])
for (i in 2:l) {
mtchl <- p9 == x[i]
mtch <- which(mtchl) # Positions that matched
pmtch <- proust[mtch] # Words that matched
tb <- table(pmtch) # Count occurrences that matched
if (length(tb)==1) { # It is either 1 or >1
decrypted[i] <- names(tb)[1]
if (verbose) print(paste0("i = ", i, ", case 1: unique decryption"))
} else { # If there are more than one ways to decipher...
preced <- proust[mtch-1]
s <- sum(preced==decrypted[i-1])
if (s==0) {
decrypted[i] <- sample(names(tb), 1)
if (verbose) print(paste0("i = ", i, ", case 2a: multiple decryption, collocation never used, picking at random"))
} else {
tb2 <- table(pmtch[preced==decrypted[i-1]])
if (length(tb2)==1) {
decrypted[i] <- names(tb2)[1]
if (verbose) print(paste0("i = ", i, ", case 2b: multiple decryption, only one collocation found, using it"))
} else {
decrypted[i] <- sample(names(tb2), 1, prob = tb2/sum(tb2))
if (verbose) print(paste0("i = ", i, ", case 2c: multiple decryption, ", length(tb2), " choices"))
}
}
}
if(verbose) print(decrypted[i])
}
decrypted
}
```
And now what it is actually doing:
```
decip("20784250276960369", verbose=TRUE)
----
[1] "a"
[1] "i = 2, case 2c: multiple decryption, 2 choices"
[1] "quick"
[1] "i = 3, case 2a: multiple decryption, collocation never used, picking at random"
[1] "brown"
[1] "i = 4, case 1: unique decryption"
[1] "fox"
[1] "a" "quick" "brown" "fox"
```
Second example:
```
decip("84303245304270533808430637802537808430243687", verbose=TRUE)
----
[1] "what"
[1] "i = 2, case 2b: multiple decryption, only one collocation found, using it"
[1] "did"
[1] "i = 3, case 2b: multiple decryption, only one collocation found, using it"
[1] "the"
[1] "i = 4, case 1: unique decryption"
[1] "navy"
[1] "i = 5, case 2a: multiple decryption, collocation never used, picking at random"
[1] "raz"
[1] "i = 6, case 2a: multiple decryption, collocation never used, picking at random"
[1] "um"
[1] "i = 7, case 2a: multiple decryption, collocation never used, picking at random"
[1] "the"
[1] "i = 8, case 2b: multiple decryption, only one collocation found, using it"
[1] "coast"
[1] "i = 9, case 1: unique decryption"
[1] "guards"
[1] "what" "did" "the" "navy" "raz" "um" "the" "coast" "guards"
```
Please do not comment that this can be golfed. Seems that few people are interested in this challenge because of my terrible verbosity, so I posted this answer to show what a possible programme could look like. You need not upvote/downvote this answer.
[Answer]
# Python 3, 316 bytes
```
from random import*
from collections import*
def d(s,f):
D=defaultdict(Counter);p=q=''
for w in open(f).read().split():D[w.translate({97+c:(c-(c>17)-(c>24))//3+50for c in range(26)})].update([w]);D[p].update([w]);p=w
for c in s.split('0'):q=choice([*(len(D[c])>1and D[c]&D[q]or D[c]).elements()]);print(q,end=' ')
```
] |
[Question]
[
## Background
Your friend, a linguist, has recorded and analyzed some simple conversation snippets in various languages.
Being quite absent-minded, they have forgotten which language each snippet was in.
You must help them by creating a program that analyzes the sentence structures and rules out impossible cases.
## Input
Your input is a non-empty string containing the characters `SVO`, which stand for *subject*, *verb*, and *object*.
It represents a conversation snippet analyzed by the linguist.
## Output
Your task is to break the string into sentences, and enter a period `.` after each sentence.
A sentence contains either a verb, OR a verb and a subject, OR a verb, a subject and an object.
However, you don't know which word order the original language uses; English uses [subject-verb-object](https://en.wikipedia.org/wiki/Subject%E2%80%93verb%E2%80%93object), but other languages, like Latin, use [subject-object-verb](https://en.wikipedia.org/wiki/Subject%E2%80%93verb%E2%80%93object).
In fact, all six permutations exist in natural languages, so you must check each of them.
Your output shall contain, in a newline-separated string, each applicable word order, a colon `:`, and the input string broken into sentences according to that order.
If the string cannot be parsed in some word order, the corresponding line shall be omitted.
The order of the lines does not matter, and it is guaranteed that at least one word order can be parsed.
## Example
Consider the input
```
VSVOSV
```
In the `VOS` order, the snipped can be parsed as `VS.VOS.V.`, and in the `SVO` order, it can be parsed as `V.SVO.SV.`.
The order `OSV` also works, and the full output is
```
VOS:VS.VOS.V.
SVO:V.SVO.SV.
OSV:V.SV.OSV.
```
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Regular expressions and all built-ins are allowed.
## Test cases
```
Input:
V
Output:
VSO:V.
VOS:V.
SVO:V.
OVS:V.
SOV:V.
OSV:V.
Input:
SVV
Output:
SVO:SV.V.
SOV:SV.V.
OSV:SV.V.
Input:
VSVOV
Output:
SVO:V.SVO.V.
Input:
VSOVS
Output:
VSO:VSO.VS.
OVS:VS.OVS.
Input:
SVOSV
Output:
SVO:SVO.SV.
OSV:SV.OSV.
Input:
VSVOSV
Output:
VOS:VS.VOS.V.
SVO:V.SVO.SV.
OSV:V.SV.OSV.
Input:
VSVVSOVSV
Output:
VSO:VS.V.VSO.VS.V.
OVS:VS.V.VS.OVS.V.
SOV:V.SV.V.SOV.SV.
Input:
SVVSVSOVSVV
Output:
SOV:SV.V.SV.SOV.SV.V.
Input:
VSOVSVSOVSVVS
Output:
VSO:VSO.VS.VSO.VS.V.VS.
OVS:VS.OVS.VS.OVS.V.VS.
```
[Answer]
# Perl 5 - 104 bytes
```
$a=<>;for(qw/VSO VOS SVO OVS SOV OSV/){$s=s/O//r;print"$_:".$a=~s/($_|$s|V)/$1./gr if$a=~/^($_|$s|V)*$/}
```
[Answer]
# JavaScript (ES7), 172 bytes
```
x=>[for(i of"V(SO?)?0V(O?S)?0(SVO?|V)0(O?VS|V)0(SO?)?V0(O?S)?V".split(0))if((y=x.match(RegExp(i,"g"))).join``==x)i.match(/\w/g).slice(0,3).join``+":"+y.join`.`+"."].join`
`
```
Could probably be golfed further. Suggestions welcome!
] |
[Question]
[
Write a program that takes one integer input *n* and one format letter and outputs *n* [autograms](http://en.wikipedia.org/wiki/Autogram) in the format `This sentence contains ? "A"s, ? "B"s ... and ? "Z"s.`
* Each question mark `?` represents the number of times the the following letter appears in the text
* All numbers will be written as text. To make it equally unfair for Americans and Brits your program has to be able to print either system! Pass a format letter in to choose which system, `A` for American and `B` for British. This will not matter for the first few sentences as they will have fewer than one hundred of each letter but will definitely be needed by the time you get to ten sentences
+ American: `one hundred twenty three`, etc.
+ British: `one hundred and twenty three`, etc.
* The integer (let's call it *n*) is used to vary the number of sentences produced. When *n* is greater than `1` each subsequent sentence will start with two newlines and then the following text: `The preceding text plus this sentence contain ...` where the ellipsis `...` represents the count of each letter that appears
* You do not have to include a letter if it doesn't otherwise appear, although if you do choose to, it might simplify the challenge. I don't know, though, it might make it harder so it's your call! If you include all twenty six letters your answer will also be a [pangram](http://en.wikipedia.org/wiki/Pangram)!
* You can't say `zero "Y"s` because you have to use a `Y` to say it!
* You can only say `one "Y"` if `Y` doesn't appear anywhere else in the text
* You can't repeat a letter and its count within each sentence, i.e. `three "N"s, three "N"s` is not allowed
* Your output must use good English! Any appearance of `... "X"s, one "Y"s...`, for example, will invalidate your answer!
* In each sentence you must enumerate the letters in alphabetical order
* Only letters `A-Z` will be counted, not symbols, punctuation or spaces
* The letters will be counted case-insensitively, i.e. `A` will be equivalent to `a`
Since the level *n* output also contains the output for each lower level to *n-1* you only need to show your source code and the output for level 10. There may be multiple solutions so your answer might be different from someone else's answer!
An example (*n*=1) is:
```
This sentence employs two a’s, two c’s, two d’s, twenty-eight e’s, five f’s, three g’s, eight h’s, eleven i’s, three l’s, two m’s, thirteen n’s, nine o’s, two p’s, five r’s, twenty-five s’s, twenty-three t’s, six v’s, ten w’s, two x’s, five y’s, and one z.
```
Note, however, that my requirements are slightly different! You must use `contains`, not `employs` and surround each letter (in capitals) with double quotes `"`. It's your choice whether you use hyphens `-` or not between the words of the numbers.
Your final output will look something like this. Note that the first sentence uses `contains` but the subsequent sentences use `contain`:
```
This sentence contains ten "A"s, ...
The preceding text plus this sentence contain twenty "A"s, ...
The preceding text plus this sentence contain thirty "A"s, ...
...
The preceding text plus this sentence contain one hundred "A"s, ...
```
You can use the following snippet to check your output.
```
// Apologies for the hugeness of this snippet. It's my first!
word = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
100: 'hundred',
1000: 'thousand',
}
var format;
function count_letters() {
var check_text = [];
var text = document.getElementById("golf").value;
text = text.replace(/-/g, " ");
text = text.replace(/\r\n?/g, "\n");
format = text.match(/\w\w and /)? 'B': 'A';
var lines = text.split(/\n\n/);
var let_count = {};
for (n = 0; n < lines.length; ++n) {
var keys = [];
var sentence = '';
var letters = lines[n].toUpperCase().match(/[A-Z]/g);
for (var i = 0; i < letters.length; ++i) {
if (!(letters[i] in let_count)) {
let_count[letters[i]] = 0;
}
let_count[letters[i]]++;
}
for (i in let_count) {
if (let_count.hasOwnProperty(i)) {
keys.push(i);
}
}
keys.sort();
for (i = 0; i < keys.length - 1; ++i) {
if (sentence) {
sentence += ", ";
}
var num_text = number(let_count[keys[i]], format);
sentence += num_text + ' "' + keys[i] + '"';
if (let_count[keys[i]] > 1) {
sentence += "s";
}
}
num_text = number(let_count[keys[i]], format);
sentence += " and " + num_text + ' "' + keys[i] + '"';
if (let_count[keys[i]] > 1) {
sentence += "s";
}
sentence = check_text.length == 0? "This sentence contains " + sentence + ".": "The preceding text plus this sentence contain " + sentence + ".";
check_text.push(sentence);
}
document.getElementById("output").value = check_text.join("\n\n");
for (n = 0; n < lines.length; ++n) {
if (check_text[n] != lines[n]) {
break;
}
}
document.getElementById("correct").innerText = n;
}
function number(num, format) {
num = (num + "").split("").reverse().join("");
digit = num.match(/\d/g);
text = "";
// Thousands
if (digit[3]) {
text += word[digit[3]] + " " + word[1000];
// Hundreds
if (digit[2] > 0) {
text += " ";
}
// Tens and units
else if ((digit[1] + digit[0]) * 1 > 0) {
text += " and ";
}
}
// Hundreds
if (digit[2] > 0) {
text += word[digit[2]] + " " + word[100];
// Tens and units
if ((digit[1] + digit[0]) * 1 > 0) {
text += " and ";
}
}
if (typeof(digit[1]) == "undefined") {
digit[1] = 0;
}
if (digit[1] < 2) {
if ((digit[1] + digit[0]) * 1) {
text += word[(digit[1] + digit[0]) * 1];
}
}
else {
text += word[digit[1] * 10];
if (digit[0] > 0) {
text += " " + word[digit[0]];
}
}
if (format != 'B') {
text = text.replace(/ and /g, format == 'A'? " ": " ! ");
}
return text;
}
```
```
<textarea id="golf" cols="80" rows="25">
This sentence employs two "A"s, two "C"s, two "D"s, twenty-eight "E"s, five "F"s, three "G"s, eight "H"s, eleven "I"s, three "L"s, two "M"s, thirteen "N"s, nine "O"s, two "P"s, five "R"s, twenty-five "S"s, twenty-three "T"s, six "V"s, ten "W"s, two "X"s, five "Y"s, and one z.</textarea><br/>
<input type="button" value="Count the letters!" onclick="count_letters()"/><br/>
<textarea id="output" cols="80" rows="10">
</textarea><br/>
Number of correct sentences: <span id="correct"></span>
```
[Answer]
# [Haskell](https://www.haskell.org/), 2161 bytes
```
-- https://codegolf.stackexchange.com/questions/51264/chaining-autograms
-- https://www.leesallows.com/files/Reflexicons%20NEW(4c).pdf
import Data.Char
import Data.List
import Data.Array
import System.IO.Unsafe
import System.Random
pick []=[]
pick pool=[pool!!(unsafePerformIO.randomRIO)(0,length pool-1)]
instance (Num a, Ix i) => Num(Array i a) where
a+b=accum(+)a(assocs b)
a-b=accum(-)a(assocs b)
(*)=undefined;fromInteger=undefined;signum=undefined;abs=undefined
azarra=accumArray(+)0('A','Z')::[(Char,Int)]->Array Char Int
squeeze=azarra.map(\c->(toUpper c,1)).filter isLetter
autogram n b = let
band
|b=='B'=" and "
|b=='A'=" "
name 0="zero";
name 1="one"
name 2="two"
name 3="three"
name 4="four"
name 5="five"
name 6="six"
name 7="seven"
name 8="eight"
name 9="nine"
name 10="ten"
name 11="eleven"
name 12="twelve"
name 13="thirteen"
name 14="fourteen"
name 15="fifteen"
name 16="sixteen"
name 17="seventeen"
name 18="eighteen"
name 19="nineteen"
name 20="twenty"
name 30="thirty"
name 40="forty"
name 50="fifty"
name 60="sixty"
name 70="seventy"
name 80="eighty"
name 90="ninety"
name n|n<100=name(10*div n 10)++'-':name(mod n 10)
name n|n<1000&&mod n 100==0=name(div n 100)++" hundred"
name n|n<1000=name(100*div n 100)++band++name(mod n 100)
name n|mod n 1000==0=name(div n 1000)++" thousand"
name n=name(1000*div n 1000)++" "++name(mod n 1000)
endr=9999
nam2 0=""
nam2 i='s':name(1+i)
wtwo(i,v)=if v>0 then tail$nam2 v++" \""++[i]++"\"s" else ""
repr=listArray(0,endr)$map(squeeze.nam2)[0..endr]
self=foldl1(+).map(repr!).filter(>0).elems
solv pret=let
fixall guess=pret+self guess
deficit guess=fixall guess-guess
fixone guess=accum(+)guess$pick.filter((/=0).snd).assocs.deficit$guess
terminate(a:b:c)|a==b=a|True=terminate(b:c)
in terminate$iterate(fixone.fixall)pret
solve prepent=
(prepent++).(++".\n").
intercalate", ".(\s->init s++["and "++last s]).map wtwo.
filter((>0).snd).assocs.solv.squeeze$prepent++"and"
in solve$if n==1 then "This sentence contains "
else autogram(n-1)b++"The preceding text plus this sentence contain "
main=putStrLn $ autogram 2 'B'
```
[Try it online!](https://tio.run/##bVXbbts4EH3XVzCCt5ZqS5a8Sdq4SwPZy0OAoFmkKRZYxw@0PLKIUJQq0pcE@fbNDqmL5aB5cDRnZs4cksNhxtQTCPH2FgQk07pUs8kkKdawKUQaKs2SJzgkGZMbCJMin/zYgtK8kGpyEU8vzyfo4pLLTcC2uthULFdOj2i/34cCQDEhir2yBCkXoCb3kAo48ASJfplGX//6xztP/LBcp47D87KoNPmTaRb@kbHqBLjlSp8A11XFnrukb89KQx7e3IXfpWIpvMPvmVwXueOUPHkiiyVdLOvPsigEXZjfszNvazP/hiotqhyZKpt0f3Pne9FYgNzozCYEsb/EwhL3SCZAvK/bnLAxuTkQ7hM6J2h7Vh3hhPlkn0EFDmGjFWVJgr6RzzymVJEosvLREbSO4NThffTpVq4h5RLWX9KqyG@khg1UPVTxjdzmPYCt1NFyHPbCUEnNbzVh9cgbXg/Hw3@H/my28MxOj5HYXwbzWrVBCCKOwjOHF6A1SZiz0ntMgrmni@9lCRVJxrHvh3iuGg2ubkHjh0OctiOIJCtCiQDtkBVupkPI64rS4e9D6hK0idsi1wZBS7IcSETdF6gK90tjx9QtJLTeKXX1vmitX9HKKui859RNi23Vmhdo8l3nvaSu4ofW@oQW7EC29mfqAt9kurWvqIsN3iXHqEsfo2OUBaKfH1tpII71YiuPVxp6UY3EE8zqTE@gWusJ1Ao@AVvVfaxR3semkRUn9XO3dVEjrkPOIyOtB1xEta4OuIxqVR3wKWo1ddDnqFHUIVdRo6dD5Kv8LY4iagwvjj6u@Q6bJY780WgYDGcWzot1jZ3mRB8@tJ6I0oaizTcELsnwAlSwflesq3YsZ8JNY45GJxV7JTvoJ7XqYjortgo5umpdmV6dOtR9XwcLOQRQLL3CP0swNe3vNp@cDlWzG/GIo6o9tr7Hxzuf8pTs5hFWB0k042JgE3amzKOLhRZ8id@PrnIJCAXEcFZQVlTgIK0nQTQ2pf2BudfNVQ8Ni7@IwtC4lg5RIFKaFmItYpwcdgQYlrP22nvzyA/xGuD0x@BC7EhZgaZ45Qne7ZQf8AEgG3w6FDWOkeGrbXSbKZVw3fj7wUEbgiDe/SaiHZ/WGpgB3qrwJhR1KLn2w3qAhg33oCXCqJxLpsFjs9Us8V8ZpTh3Xx@qLdCj07gwmstjwoDjp/HVWsJap2@W06wZzKJLvAMUU73me4Tb5eERhI/S9UPLiTwJE0jljokbeo8qmOMTqonC43LtPByNBFMILO1W2@MO7S7Uq5y/W6QpHjZHN@jqurYbHbMIq26AvSIpjetmcR8yrvBcUY15vfAhxvaRirjmwGyrtOPbk/jSrZDvIbMrTGCN7z1uzEGTUmwV8v2ECce4k@N/Wm71N13dSjLoGMmU4PB33t7@S1LBNuotuJv@Dw "Haskell – Try It Online")
```
This sentence contains three "A"s, three "C"s, two "D"s, twenty-seven "E"s, four "F"s, two "G"s, ten "H"s, eight "I"s, thirteen "N"s, six "O"s, ten "R"s, twenty-five "S"s, twenty-three "T"s, three "U"s, three "V"s, six "W"s, three "X"s, and four "Y"s.
The preceding text plus this sentence contain six "A"s, seven "C"s, five "D"s, sixty-four "E"s, thirteen "F"s, six "G"s, eighteen "H"s, twenty-six "I"s, four "L"s, thirty-three "N"s, eleven "O"s, three "P"s, nineteen "R"s, fifty-five "S"s, forty-five "T"s, seven "U"s, eleven "V"s, eight "W"s, nine "X"s, and ten "Y"s.
The preceding text plus this sentence contain ten "A"s, eleven "C"s, eleven "D"s, one hundred and fourteen "E"s, nineteen "F"s, ten "G"s, twenty-six "H"s, forty-two "I"s, nine "L"s, sixty-seven "N"s, eighteen "O"s, six "P"s, twenty-five "R"s, eighty-six "S"s, seventy-one "T"s, eleven "U"s, nineteen "V"s, thirteen "W"s, fifteen "X"s, and seventeen "Y"s.
The preceding text plus this sentence contain seventeen "A"s, fifteen "C"s, twenty-six "D"s, one hundred and sixty-three "E"s, twenty-eight "F"s, fifteen "G"s, thirty-nine "H"s, sixty-two "I"s, twelve "L"s, one hundred and eight "N"s, twenty-seven "O"s, nine "P"s, thirty-five "R"s, one hundred and fifteen "S"s, one hundred and nine "T"s, eighteen "U"s, twenty-four "V"s, twenty-two "W"s, twenty "X"s, and twenty-nine "Y"s.
The preceding text plus this sentence contain twenty-four "A"s, nineteen "C"s, forty-one "D"s, two hundred and eight "E"s, forty-five "F"s, nineteen "G"s, fifty-two "H"s, seventy-eight "I"s, fifteen "L"s, one hundred and forty-two "N"s, forty-seven "O"s, twelve "P"s, fifty-four "R"s, one hundred and forty-three "S"s, one hundred and forty-seven "T"s, twenty-six "U"s, thirty-one "V"s, thirty-one "W"s, twenty-three "X"s, and forty-five "Y"s.
The preceding text plus this sentence contain thirty-two "A"s, twenty-three "C"s, fifty-nine "D"s, two hundred and fifty-six "E"s, fifty-nine "F"s, twenty-seven "G"s, seventy-two "H"s, one hundred and six "I"s, seventeen "L"s, one hundred and eighty-one "N"s, fifty-eight "O"s, fifteen "P"s, sixty-eight "R"s, one hundred and seventy-five "S"s, one hundred and eighty-nine "T"s, thirty-four "U"s, thirty-eight "V"s, thirty-eight "W"s, twenty-nine "X"s, and sixty-three "Y"s.
The preceding text plus this sentence contain forty "A"s, twenty-seven "C"s, seventy-seven "D"s, three hundred and eight "E"s, sixty-seven "F"s, thirty-five "G"s, ninety "H"s, one hundred and twenty-five "I"s, nineteen "L"s, two hundred and eighteen "N"s, seventy "O"s, eighteen "P"s, eighty-four "R"s, two hundred and eight "S"s, two hundred and twenty-eight "T"s, forty-two "U"s, forty-seven "V"s, forty-six "W"s, thirty-three "X"s, and seventy-nine "Y"s.
The preceding text plus this sentence contain fifty-one "A"s, thirty-one "C"s, one hundred and four "D"s, three hundred and forty-nine "E"s, eighty-five "F"s, forty "G"s, one hundred and eight "H"s, one hundred and forty-nine "I"s, twenty-one "L"s, two hundred and sixty-one "N"s, ninety-two "O"s, twenty-one "P"s, one hundred and four "R"s, two hundred and thirty-six "S"s, two hundred and sixty-five "T"s, fifty-five "U"s, fifty-two "V"s, fifty-four "W"s, thirty-eight "X"s, and ninety-seven "Y"s.
The preceding text plus this sentence contain sixty-four "A"s, thirty-five "C"s, one hundred and thirty-seven "D"s, four hundred and six "E"s, ninety-four "F"s, forty-three "G"s, one hundred and twenty-nine "H"s, one hundred and sixty-seven "I"s, twenty-five "L"s, three hundred and eleven "N"s, one hundred and eleven "O"s, twenty-four "P"s, one hundred and twenty-eight "R"s, two hundred and seventy "S"s, three hundred and two "T"s, seventy-one "U"s, sixty-one "V"s, sixty-two "W"s, forty-six "X"s, and one hundred and thirteen "Y"s.
The preceding text plus this sentence contain seventy-eight "A"s, thirty-nine "C"s, one hundred and seventy-three "D"s, four hundred and seventy "E"s, one hundred and seven "F"s, fifty-one "G"s, one hundred and fifty-five "H"s, one hundred and eighty-eight "I"s, twenty-seven "L"s, three hundred and sixty-two "N"s, one hundred and twenty-eight "O"s, twenty-seven "P"s, one hundred and fifty-one "R"s, three hundred and four "S"s, three hundred and forty-three "T"s, eighty-six "U"s, seventy "V"s, sixty-eight "W"s, fifty-one "X"s, and one hundred and thirty-two "Y"s.
```
] |
[Question]
[
Today, your task is to write a program (or a function) that accepts a string and outputs (or returns) four integers.
**Input**
The input string is a [CSS3 selector](http://dev.w3.org/csswg/selectors3/), and can contain basically any Unicode character.
**Output**
The output represents the CSS specificity of this selector.
* The first number is always 0 (because it's used for inline styles, and this exercise doesn't apply to inline styles)
* The second number is the number of ids (`#foo`) present in the selector.
* The third number is the number of classes (`.foo`), attributes (`[bar]`) and [pseudo-classes](http://dev.w3.org/csswg/selectors3/#pseudo-classes) present in the selector.
* The fourth number is the number of elements (`biz`) and [pseudo-elements](http://dev.w3.org/csswg/selectors3/#pseudo-elements) present in the selector.
**Notes:**
* Universal selector (\*) isn't counted anywhere
* The pseudo-elements `::before` and `::after` can also be written with a single ":" (legacy notation)
* Input can use the `:not(selector)` pseudo-class. The selector inside doesn't count, even if it contains ids, classes, elements, ...)
* The "bricks" of the selector are separated by combinators (spaces/tabs, `+`, `>`, `~`, ex: `body > div+a ~*`), but they can also be cumulated (ex: `div#foo.bar[baz]:hover::before`)
* You also have to handle [CSS escape sequences](https://mathiasbynens.be/notes/css-escapes) ( `\` followed by 1 to 6 hexadecimal numbers, followed by a space), and escaped special characters (`\` followed by any of these: `!"#$%&'()*+,-./:;<=>?@[\]^`{|}~`) properly. Those escapes can be part of any brick of the selector (id, class, etc).
* You don't need to do anything particular if you receive an invalid selector or a CSS4 selector. Don't bother implementing a CSS3 selector validator.
* Here are a few links to learn more about CSS specificiy:
+ CSS-tricks article: <http://css-tricks.com/specifics-on-css-specificity/>
+ A tool (incomplete) that counts it: <http://specificity.keegan.st/>
**Examples**
```
// Universal
* => 0,0,0,0
// ID
#id => 0,1,0,0
// Class
.class => 0,0,1,0
// Attributes
[foo] => 0,0,1,0
[foo="bar"] => 0,0,1,0
[foo~="bar"] => 0,0,1,0
[foo^="bar"] => 0,0,1,0
[foo$="bar"] => 0,0,1,0
[foo*="bar"] => 0,0,1,0
[foo|="bar"] => 0,0,1,0
[ foo = bar ] => 0,0,1,0
[foo = 'bar'] => 0,0,1,0
(NB: brackets [] can contain anything except an unescaped "]")
// Pseudo-classes
:root => 0,0,1,0
:nth-child(n) => 0,0,1,0
:nth-last-child(n) => 0,0,1,0
:nth-of-type(n) => 0,0,1,0
:nth-last-of-type(n) => 0,0,1,0
:first-child => 0,0,1,0
:last-child => 0,0,1,0
:first-of-type => 0,0,1,0
:last-of-type => 0,0,1,0
:only-child => 0,0,1,0
:only-of-type => 0,0,1,0
:empty => 0,0,1,0
:link => 0,0,1,0
:visited => 0,0,1,0
:active => 0,0,1,0
:hover => 0,0,1,0
:focus => 0,0,1,0
:target => 0,0,1,0
:lang(fr) => 0,0,1,0
:enabled => 0,0,1,0
:disabled => 0,0,1,0
:checked => 0,0,1,0
:not(selector) => 0,0,1,0
(NB: the keyword after ":" can be anything except a pseudo-element)
// Elements
body => 0,0,0,1
// Pseudo-elements
:before => 0,0,0,1
:after => 0,0,0,1
::before => 0,0,0,1
::after => 0,0,0,1
::first-line => 0,0,0,1
::first-letter => 0,0,0,1
(NB: parenthesis () can contain anything except an unescaped ")" )
```
(to be continued)
If you have questions or need examples or test data, please ask in the comments.
Shortest code (in bytes) wins.
Good luck!
[Answer]
# JavaScript ES6 ~~453~~ 430 bytes
```
a=>(s){var n=z=[],c=[0,0,0,0],e=s.split(/[\s\+\>\~]+/);return e.forEach((s)=>{n=n.concat(s.replace(/\((.*)\)/,"").split(/(?=\[|::|\.)/))}),n.forEach((s)=>{if(0==s.indexOf("::"))return z.push(s);var n=s.split(/(?=:)/);z=z.concat(n[0].split(/(?=[\#])/)),/before|after/.test(n[1])?z.push(":"+n[1]):n[1]&&z.push(n[1])}),z.forEach((s)=>{/^[a-z]+$/gi.test(s)||"::"==s[0]+s[1]?c[3]++:-1!=":.[".indexOf(s[0])?c[2]++:"#"==s[0]&&c[1]++}),c}
```
**Update:** improved code, now it handles `:not` and `:before`/`:after` selectors better, nevertheless haven't tested CSS escape sequences.
[Answer]
# Python3, 226 bytes:
```
lambda s:[0,(c:=(x:=sub('(?<=\:not)\(.*?\)|\\.*?\\\\|(?<=\[).*?(?=\])','',s)).count)('#'),c('.')+c('[')+sub('::|(?:\:after)|(?:\:before)','',x).count(':'),len(findall('^\w+|[\s\>\+,]\w+|::|\:after|:before',x))]
from re import*
```
The test cases included in the link below are derived from the sample selectors in the original question along with the most complex selectors from Code Golf's [own source](https://cdn.sstatic.net/Sites/codegolf/primary.css?v=332e219cfdd1).
[Try it online!](https://tio.run/##hVXRbpswFH1evsIik2ynEK3ay4RG@yFAJwMmsWpsZpu0kaL9enYhZEk7A1EksM@5515f24f26PZaff/RmnOdZGfJmqJiyMbpt5CUcULe48R2BcHk@WeSxUo7mpHt5jmjpyzrn/A7DVhKYUiekyynOMQ4tJRuS90pRwleYxqWBG8xfYBHCo9BM44hNM5iVjtu6OW94LU2/CLxPioAEwQkV6QWqmJSEvySvT2c0sxmT9lDmPcDEBuVTqNIL0DzVW10gwxHomm1cZtzwawofzlunUUJSlO8wSGC5aLxn@cwxGtRjdOP99PbUjJrbwGP/5C01jqfApKgYCaYhP8s4C8L@NcFfLOAn@ZwBAQEnUJAQT5KkF4ZGCg4DzwqsdHa@eRj5fZRuReyIopOEqDpbpml68gdW74otMCrhblm8@K3YmbCxxzTAnMEreRxJsMAz8XzpnVHf2qhXr3AQVjhuD8fK504@DPt9YEbfxt02XkvSuyY2XE30Rm1I7Xx7wtXrJATJVbCToPlnpevExg4GrFc8tJpf9pCV8cPBvE4Rl5NxgMNNuRF5qLmwi6HCnaPz@LceRTAArVB10WG4IW2kw4Jhe6sMF59AWPjxiGi4qS@9YQmyRgBsir8LJOvVq0RvUeDL18E0cVb216vwnTEa/D/3x0gQqtIG7ETiknbH@Oqa6UomeOok5je8w/a8ZKD7vAWDR@DqNXW3dOCINhW@k31lCpiyr5xg@DD0TQc2P32hSsPoZeJrNgp5jrDvRQbtUZbP9aP0BPaQPb7ktdwnkQNl1crx2C3oO8tU9vrrAQ5xD4ucigEau16ueE89ol1298s@mmh6wZEwWSjupPycl6guv8nh6rOfwE)
] |
[Question]
[
# The Setup
Consider an oddly-shaped box containing 29 numbered cells as shown in Fig. 1 below.

Inside this 2D box are two species of square-shaped animals: shubbles and smoles. Fig. 1 (a) shows some shubbles in blue, and some smoles in red. Each creature occupies exactly one grid cell. The box may contain anywhere between 0 and 26 shubbles, but will always contain exactly two smoles.
Being subject to gravity, shubbles and smoles sit on the bottom of the box, stacking on top of anything below them. Both species are exceptionally lazy and remain perpetually motionless.
The box also contains a stot, depicted as a black square, that occupies exactly one grid cell. The stot is *not* subject to gravity.
The box has one opening located at the bottom of cell 28, as depicted in the figure.
To represent the configuration of shubbles, smoles, and the stot in the box textually, we use a 29-character string, one character per grid cell, in the enumerated order, with `.` representing an empty cell, `o` representing a shubble, `x` representing a smole, and `@` representing the stot. For example, the configuration of Fig. 1 (a) is represented by the string `[[email protected]](/cdn-cgi/l/email-protection)...`.
# Manipulations
The box can be **rotated** by any multiple of 90°. While the box is being rotated, the shubbles and smoles remain stationary within their grid cells. As soon as a rotation is complete, they fall directly downward until either *i*) they are blocked by a wall below, *ii*) they are blocked by a shubble, smole, or stot below, or *iii*) they fall through the hole in cell 28 and exit the box. The stot does not fall; it stays fixed in its current cell, even if creatures rest on top of it.
The box cannot be rotated again until the creatures are done falling and have reached a new stable configuration.
Textually, box rotations are denoted by `+` for a 90° clockwise rotation, `|` for a 180° rotation, and `-` for a 90° counterclockwise rotation.
Additionally, the stot can be **moved** in the four compass directions in increments of one grid cell. A move may not: *i*) cause a collision between the stot and a creature (i.e. the destination grid cell must be empty), *ii*) cause a collision between the stot and a wall, nor *iii*) cause the stot to exit the box through the hole in cell 28.
Also, the stot *may not move* if it has any creatures resting on top of it (with respect to current gravity).
Textually, stot moves are denoted by `<` for left, `>` for right, `^` for up, and `v` for down. Stot moves are always specified *with respect to the "standard" (non-rotated) frame* depicted in the figures. That is, if the stot is in cell 10, the move `^` will always move it to cell 5, and the move `>` will always move it to cell 11. The orientation of the box does not affect the direction of the move.
Sequences of manipulations are encoded using left-to-right character strings. For example, the string `+<<^-` indicates the box is rotated clockwise 90°, then the stot is moved left twice and up once (with respect to the standard frame), then the box is rotated 90° counterclockwise back into its original orientation.
# The Challenge
For perfectly good reasons (that I cannot disclose), we wish to extricate all shubbles from the box *without* extricating a single smole. To accomplish this, we can use the manipulations specifically described above.
Before solving this problem, it behooves us to simulate how our various manipulations will affect the contents of the box, which is the focus of this challenge.
You must write a program that accepts two arguments from `stdin` (or equivalent):
* a string describing the initial state of the box
* a sequence of manipulations
You may assume that both arguments are syntactically valid, that the box starts in the standard orientation, and that the initial state of the box is stable and legal.
The program must output to `stdout` (or equivalent) either:
* (**case 1**) the final state of the box, expressed as a string, if the sequence of moves is legal (it does not violate the stot move rules) and does not cause any smoles to exit the box. The final orientation of the box is unimportant.
* (**case 2**) a single exclamation mark, `!`, if the sequence of moves is illegal or causes any smoles to exit the box
# Scoring
The winning program is the **shortest program by byte count**, subject to some extremely lucrative bonus multipliers:
* claim a **multiplier of 0.65** if instead of printing the encoded output for case 1, the program outputs an ASCII picture of the box in its final state and orientation, using the spec characters for shubbles, smoles, stots, and empty cells, and placing a `*` in the cell just outside the hole in cell 28. Leading and trailing whitespace is ignored.
For example, if Fig. 1 (a) is rotated 90°, the output would be
```
. .
.....
.o...
xo.@.
*ooo..
x .
```
* claim a **multiplier of 0.22** if instead of printing encoded output for case 1, the program outputs an image file or displays a GUI window with a picture of the box in its final state and orientation. The picture should be in the style of Fig. 1 (a), showing the grid cells, walls, and creatures/stot using coloured boxes.
* claim a **multiplier of 0.15** if instead of printing encoded output for case 1, the program outputs an animated .gif or animated GUI window showing all intermediate states in the simulation at 1 sec intervals. The same picture rules as for the 0.22 multiplier apply. The first frame of the animation should depict the initial state of the simulation. Additionally, the animation should show "hidden" intermediate states, which are
+ the shubbles/smoles falling into a stable configuration by one cell per animation frame after a rotation
+ the intermediate 90°-rotated state of the box in a 180° rotation
* claim a **multiplier of 0.12** if the program produces an animated .gif or animated GUI window of the above style, but runs at 20 fps and shows
+ smooth, continuous animations of the box rotating
+ smooth, continuous animations of the stot moving, and of the shubbles/smoles falling into a stable configurationShubbles falling through the hole in cell 28 should be shown exiting the box, and should disappear once totally outside. You may choose your own timing for the animation so long as no more than 1 manipulation/sec is performed.
Total score is `floor( base score * multiplier )`. **Only one multiplier may be claimed.**
It's a smole world after all. ;)
[Answer]
# MATLAB, as yet ungolfed \* 0.15
It would be great if someone could hazard a guess as to whether this works right.
```
n = @()input('', 's');
E = @()fprintf('!');
M = zeros(7,9);
G = M;
I = [9:7:44 17:7:52 18:7:46 12:7:47 20:7:55];
M0 = M;
M0(I) = 1;
M([I 49]) = 1;
G(I) = n()-46;
trot = 0;
Xtr = [0 1-10i 11-7i 8+i];
X0 ='c66++66++oozzoozzn'-i*'YYNNAA-- ++88LLYY'-22+22i;
for a = [97 n()]
a = find('-|+a^<v>'==a);
if a<5
R = @(m) rot90(m, a);
G = R(G);
[nr,nc] = size(G);
M = R(M);
M0 = R(M0);
trot = mod(trot+a,4);
X = exp(i*pi*trot/2)*X0 + 11*Xtr(trot+1);
else
z = find(G==18);
J = z + [-nr,1]*[0,-1;1,0]^(trot+a)*[1;0];
if ~M0(J) | G(J) | G(z+1)
E();return
end
G(z) = 0;
G(J) = 18;
end
fall = 1;
while fall
clf
plot(X/11,'k','LineW',3);
for x = 2:nc; for y = 2:nr
ch = G(y,x);
if M0(y,x)
rectangle('Po',[x,-y,1,1],'F',~ch|ch==[74 1 65]);
end
end;end
pause(1);
G2 = G;
for r = nr-1:-1:2
s = G2 > 30;
f = G2(r,:) .* (s(r,:) & ~s(r+1,:) & M(r+1,:) & G(r+1,:)~=18);
if r==size(G,1)-1 & any(f==74)
E();return
end
G2(r:r+1,:) = G2(r:r+1,:) + [-f;f];
end
G2 = G2 .* M0;
fall = any(any(G2 ~= G));
G = G2;
end
end
```
Sample end result for some random moves:
```
[[email protected]](/cdn-cgi/l/email-protection)...
+>|<-v+^+
```

] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/26872/edit)
Inspired by [Cheap, Fast, Good](https://codegolf.stackexchange.com/questions/26782/fast-cheap-and-good-choose-any-two), we're going to implement an algorithm which has exactly two of them.
**The Math**
Given two nonzero integers *a* and *b*, the GCF *d* is the largest integer that divides both *a* and *b* without remainder. [Bézout coefficients](http://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity) are pairs of integers *(x, y)* such that *ax + by = d*. Bézout coefficients are not unique. For example, given:
```
a = 15, b = 9
```
We have
```
d = 3
x = 2
y = -3
```
Since `15*2 + 9*(-3) = 30 - 27 = 3`.
A common way to calculate the GCF and a pair of Bézout coefficients is using [Euclid's Algorithm](http://en.wikipedia.org/wiki/Euclidean_algorithm), but it's by no means the only way.
**The Code**
Your program should take two integers as inputs. It should output/return the greatest common factor and one pair of Bézout coefficients.
Example input:
```
15 9
```
example output
```
3 (2, -3)
```
The output can be in any order and format, but it should be clear which is the GCF and which are the coefficients.
**The Underhanded**
Your program has the potential to be cheap, fast, and good. Unfortunately, it can only be two of those at once.
* When it's not *cheap*, the program should use an excessive amount of system resources.
* When it's not *fast*, the program should take an excessive amount of time.
* When it's not *good*, the program output should be wrong.
The program should be able to do (well, not do) all three. Which is does when is up to you- it could be based on the time, the compiler, which input is larger, etc. Some additional notes:
* Your program should not be obviously underhanded and should pass a cursory inspection. I'd be a little suspicious if you implemented three separate algorithms.
* In the *cheap* case, "excessive amount of system resources" is anything that would slow down other programs. It could be memory, bandwidth, etc.
* In the *fast* case, "excessive time" means relative to how it runs in the *cheap* and *good* cases. The program should still finish. The closer you can to "incredibly frustrating but not frustrating enough to stop the program" the (funnier and) better.
* In the *good* case, the output shouldn't be obviously wrong and should pass a cursory inspection. I'd be **very** suspicious if it gave me a GCF of "2 anna half".
This is a popularity contest, so most upvotes wins!
**EDIT**
To clarify, I'm looking for programs that can be "fast and cheap" *and* "cheap and good" *and* "fast and good" in different cases, not ones that just do one of them.
[Answer]
# C
It's cheap and fast. You get gcd in the blink of an eye. However the guy who did it had no clue about that "Bézier co-something" so he simply divided a and b by gcd.
(to make things worse, at that point a and b are pretty far from their initial value because of the algorithm he wisely chose)
```
int main(int argc, char **argv){
unsigned int a, b, tmp;
a = (unsigned int)atoi(argv[1]);
b = (unsigned int)atoi(argv[2]);
for (tmp = 0; ((a | b) & 1) == 0; ++tmp){
a >>= 1;
b >>= 1;
}
while ((a & 1) == 0)
a >>= 1;
do {
while ((b & 1) == 0)
b >>= 1;
if (a > b){
unsigned int t = b;
b = a;
a = t;
}
b = b - a;
} while (b != 0);
tmp = a << tmp;
printf("%u, (%u,%u)", tmp, a/tmp, b/tmp);
return 0;
}
```
[Answer]
## C#
This calculates the Bézout coefficients. I used the [Extended Euclidean algorithm](http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm).
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter your first number.");
int firstNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your second number.");
int secondNumber = Convert.ToInt32(Console.ReadLine());
double max = Math.Max(firstNumber, secondNumber);
double min = Math.Min(firstNumber, secondNumber);
double s1 = 1;
double s2 = 0;
double t1 = 0;
double t2 = 1;
double quotient = 0;
double remainder = 0;
double[] remainders = new double[0];
int i = 0;
do
{
quotient = (int)(max / min);
remainder = max - quotient * min;
if (remainder > 0)
{
Array.Resize(ref remainders, remainders.Length + 1);
remainders[i] = remainder;
}
if (i % 2 == 0)
{
s1 = s1 - quotient * s2;
t1 = t1 - quotient * t2;
}
else
{
s2 = s2 - quotient * s1;
t2 = t2 - quotient * t1;
}
if (i == 0)
{
max = min;
}
else if (i >= 1)
{
max = remainders[i - 1];
}
min = remainder;
i++;
} while (remainder > 0);
Console.WriteLine((remainders[remainders.Length - 1]).ToString() + " " + (i % 2 == 0 ? "(" + s1 + "," + t1 + ")" : "(" + s2 + "," + t2 + ")"));
}
}
}
```
[Answer]
# Perl 5
```
#!/usr/bin/perl
use strict;
use warnings;
$SIG{__WARN__} = sub { exit };
print(<<INTRO);
Greatest Common Factor
goodbye -- exit the application
[number] [number] -- compute gcf of both numbers
INTRO
main();
sub main {
print "> ";
chomp(local $_ = <STDIN>);
print "Have a good one.\n" and exit if /goodbye/;
my @nums = /(-?\d+)/g;
print "invalid input\n" and return main() if @nums != 2;
my ($gcf, @coeff) = gcf(@nums);
unless (grep abs($_) > 99, $gcf, @coeff) {
select $\,$\,$\, rand for 1..10;
}
local $" = ", "; #"
print "gcf(@nums) = $gcf\n";
print "bezout coefficients: @coeff\n";
main();
}
sub gcf {
my ($x, $y) = @_;
my @r = ($x, $y);
my @s = (1, 0);
my @t = (0, 1);
my $i = 1;
while ($r[$i] != 0) {
my $q = int($r[$i-1] / $r[$i]);
for (\@r, \@s, \@t) {
$_->[$i+1] = $_->[$i-1] - $q * $_->[$i];
}
$i++;
}
return map int(1.01 * $_->[$i-1]), \@r, \@s, \@t;
}
__END__
```
Not cheap: main() is called recursively (filling up the stack) until a "deep recursion" warning is fired by perl which will quit the application due to the \_\_WARN\_\_ handler.
Not fast: When the gcf() algorithms returns correct results, the code just hangs on for a few seconds (select() in main()).
Not good: All results above 99 (or below -99) are incorrect.
All in all not so creative; looking forward to more elegant answers.
[Answer]
Python
```
#!/usr/bin/python
def gcd(x, y):
l = 0
if x < y:
l = x
else:
l = y
for g in reversed(range(l + 1)):
if x%g == 0 and y%g == 0 and g > 1:
return g
else:
if g == 1:
return 1
def bezout(x,y,g):
c1 = 0
c2 = 0
k = 0
if x < y:
k = y
else:
k = x
for _k in range(k):
tc = (gcd(x,y) - x*_k)%y
if tc == 0:
c1 = _k
c2 = (gcd(x,y) - y*_k)/x
return (c1, c2)
gc = gcd(15,9)
be, bf = bezout(9,15,gc)
print("%d (%d, %d)" % (gc, be, bf))
```
This is cheap and fast but it is bad in the fact that the range is capped at the largest input so it may not find a pair of coefficients.
Good puzzle.
[Answer]
# Javascript
### Not cheap
Uses a lot of system resources.
```
function gcf(a, b) {
var result = 1;
for (var i = 1; i < 100000000 * a && i < 100000000/* Do it a few extra times, just to make sure */ * b; i++) {
if (a % i == 0 && b % i == 0) {
result = i;
}
}
return [result, a / result, b / result];
}
```
### Not fast
Use a callback, just as an extra failsafe.
```
function gcf(a, b) {
setTimeout(function() {
var result = 1;
for (var i = 1; i < 2 * a && i < 2 * b; i++) {
if (a % i == 0 && b % i == 0) {
result = i;
}
}
alert(result.toString() + " (" + (a / result).toString() + ", " + (b/result).toString() + ")");
}, 10000);
}
```
### Not good
Strict limit of `gcf(10, 10)`, just to safe disk space.
```
function gcf(a, b) {
var gcfTable = [[1,1,1,1,1,1,1,1,1,1],[1,2,1,2,1,2,1,2,1,2],[1,1,3,1,1,3,1,1,3,1],[1,2,1,4,1,2,1,4,1,2],[1,1,1,1,5,1,1,1,1,5],[1,2,3,2,1,6,1,2,3,2],[1,1,1,1,1,1,7,1,1,1],[1,2,1,4,1,2,1,8,1,2],[1,1,3,1,1,3,1,1,9,1],[1,2,1,2,5,2,1,2,1,10]];
return [gcfTable[a - 1][b - 1], a / gcfTable[a - 1][b - 1], b / gcfTable[a - 1][b - 1]];
}
```
] |
[Question]
[
The goal of this challenge is to determine if a move is a legal [English Checkers](https://en.wikipedia.org/wiki/English_draughts#Rules) move.
This challenge will use an 8x8 board. A moved piece should be treated as a man (not a king) that can only move diagonally forward. The board will have 0 or more black pieces and 1 or more white piece. One white piece will be currently moving. The white piece can "jump" over one black piece diagonally in front of it if the square directly behind it is empty. It is possible to take a further jump from that position if there is another black piece in either direction diagonally in front of it. Capture is mandatory, so it is illegal to not take a jump that is available. However, it is not mandatory to take a path that maximizes the number of jumps. Basically, this means that if you make a jump and there is another possible jump from the ending position then that move is illegal. Piece positions use the following numbering scheme:
[](https://i.stack.imgur.com/zYSHy.png)
---
### Rules
Inputs:
* A list of numbers that represent black pieces.
* A list of numbers that represent white pieces.
* A starting position for the white piece
* The ending position for the white piece
Output:
* A truthy value if the move is valid, otherwise a falsey value
You can assume a white piece will always occupy the starting position.
If convenient, you can assume that the first white piece in the white piece list will contain the starting position instead of accepting input 3.
Standard code golf rules. Fewest bytes wins.
---
### Test Cases
To illustrate, O is the starting position, X is the ending position, B are black pieces, and W are white pieces
```
Black pieces: []
White pieces: [5]
Move: (5, 1)
Output: True
Single move no jump
X _ _ _
O _ _ _
B: [6]
W: [9]
M: (9, 2)
O: True
Single jump
_ X _ _
_ B _ _
O _ _ _
B: [2, 6]
M: (9, 2)
O: False
Illegal ending position on top of black piece
_ X _ _
_ B _ _
O _ _ _
B: [7, 14]
W: [17]
M: (17, 3)
O: True
Double jump
_ _ X _
_ _ B _
_ _ _ _
_ B _ _
O _ _ _
B: [7, 14]
M: (17, 10)
O: False
Illegal jump, must take the next jump as well
_ _ _ _
_ _ B _
_ X _ _
_ B _ _
O _ _ _
B: [4]
W: [8]
M: (8, 3)
O: False
Illegal jump across the board
_ _ _ X
B _ _ _
O _ _ _
B: [6, 7]
W: [6]
M: (10, 1)
O: True
Split decision p1
X _ _ _
_ B B _
_ O _ _
B: [6, 7]
M: (10, 3)
O: True
Split decision p2
_ _ X _
_ B B _
_ O _ _
B: [2]
W: [1]
M: (1, 3)
O: False
Sideways Jump
O B X _
B: [6]
W: [1]
M: (1, 10)
O: False
Backwards Jump
O _ _ _
_ B _ _
_ X _ _
B: [6]
W: [9, 2]
M: (9, 2)
O: False
Illegal ending position on top of white piece
_ X _ _
_ B _ _
O _ _ _
B: []
W: [9, 6]
M: (9, 2)
O: False
Illegal jump over white piece
_ X _ _
_ W _ _
O _ _ _
B: [8, 15, 23, 24]
W: [27]
M: (27, 4)
O: True
Split decision long path
_ _ _ X
_ _ _ B
_ _ _ _
_ _ B _
_ _ _ _
_ _ B B
_ _ W _
B: [8, 15, 23, 24]
W: [27]
M: (27, 20)
O: True
Split decision short path
_ _ _ _
_ _ _ B
_ _ _ _
_ _ B _
_ _ _ X
_ _ B B
_ _ W _
```
[Answer]
That was challenging :)
\* fixed bugs (added bytes)
# [JavaScript (Node.js)](https://nodejs.org), 197 193 191 185 181 186 bytes
```
f=(B,W,S,E,F=1)=>g(S).filter((x,i)=>B[I="includes"](x)&!B[I](t=g(x)[i])&!W[I](t)&&t>0?F+=f(B,W,t,E):0)[0]?F>1:g(S)[I](E)
g=S=>[S--,!(y=~-(e=S-3)/4%2|0)||S%4^3?y?e+1:e:0,S%4||y?y?e:e-1:0]
```
[Try it online!](https://tio.run/##zVVNa@MwFLz7V7iFBKmVGkn@SGyQDYUE9uxDD0YLIZWDFxMvibM0YPrXs092mt22sbMt3dKDD3qMx2/mefR@zH/NN4t1/rOiq/Je7/eZRLfkjiRkSmaSYxktUYJvsryo9BqhB5JD6Tb9Ji/z1aLY3uvNpUIPeHgBNYUquYRDmiso3DUFPBxWEYtn1zJreCsyxSHDKVPxLOKhITe4KbaWMpFRmlBKLtBOPlKkZUIdPHIHoma4rpOB@92Jd7G@5qEOGYFzXe9MIdSUh0ztF@VqUxb6piiXKEOpIqmniEdAhKzWW42tFwAfEIEiAbFFF0QQ@zkqmxeb17AxsbkLOD5WhMPB6eJ7CeSsk9PAJopMeth8Yo8NGQMyBmT/iOvkEwYEmBZyui3/iOnpvfEMDDtjW4vyz6CEcUKAFQK84EFn856BwaSEYeucaGOAInZq5gDDAGu6oOZzHnA58DQ9gIkChub2@NxOF5rlk57fygBNuxza5UHP5LpaEOz4hjW6sngwtuG1bZWXK8s6RDiFDKs3hfh1io8x/pPgFCKsTmcYQirltE0yZBgSTKnJcBQJ6MbkFxI7ELF5nsWYPh7LhzCDLh44X0HU33IS6h7EwDX1DkH86whqJDypakaE4aJ9umXP6wE5E@8j5HRujreKeefaMEJOzOXDFuCn7D4jwv@PIj5vi1tXo33vJmyXxG8 "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
## Introduction
[Braincopter](http://esolangs.org/wiki/Braincopter) is an esoteric Brainf\*\*\* derivative that encodes a Brainf\*\*\*
program as an image. As a 2D language, it uses two additional commands; they
rotate the instruction pointer (initially pointing right) clockwise and
counterclockwise. Braincopter is very similar to [Brainloller](http://esolangs.org/wiki/Brainloller), except that
instead of using distinct colours as different commands, it instead calculates
the command based on the RGB value of each pixel.
Braincopter calculates the command for each pixel based on the formula
`N = (65536 * R + 256 * G + B) % 11`, where `N` is the command number. The
mapping from command numbers to Brainf\*\*\* commands is as follows:
```
0 >
1 <
2 +
3 -
4 .
5 ,
6 [
7 ]
8 rotate instruction pointer to the right (clockwise)
9 rotate instruction pointer to the left (counterclockwise)
10 NOP
```
Braincopter is useful for steganography, or the hiding of secret messages in
something else, as the colour of each pixel in any given photo can be changed
just slightly to give the desired operation. Such changed pictures are often
indistinguishable from the originals.
## Challenge
Write a program or function that takes an image and a string of brainf\*\*\* code
as input and produces the original image with the brainf\*\*\* code encoded in it.
To do this, take each pixel in the original image and replace it with the RGB
value closest to the colour of the original pixel that evaluates to the correct
Braincopter instruction. Colour difference for the purposes of this challenge is
defined as `abs(R1 - R2) + abs(G1 - G2) + abs(B1 - B2)`. In the case of a tie in
which two colours resolving to the same Braincopter command are equally close to
the original colour, either can be chosen.
For example, if the original colour is `#FF8040` and needs to be modified to
produce a '1' instruction in Braincopter, `#FF7F40` should be chosen.
Braincopter will exit when the instruction pointer runs off the edge of the
image, so we'll keep it on the image by using the 8 and 9 commands (rotate
instruction pointer clockwise and counterclockwise respectively). It's easiest
to explain the format of the encoding with an example.
For the input `+[[->]-[-<]>-]>.>>>>.<<<<-.>>-.>.<<.>>>>-.<<<<<++.>>++.` and an
8x9 image, the instructions will be laid out like this (using Brainf\*\*\* commands
instead of the Braincopter equivalents, and unicode representations of the turns
):
```
+ [ [ - > ] - ↲
↳ - > ] < - [ ↲
↳ ] > . > > > ↲
↳ < < < < . > ↲
↳ - . > > - . ↲
↳ > . < < . > ↲
↳ > > > - . < ↲
↳ + + < < < < ↲
↳ . > > + + . N
```
(Where N is a NOP.) As you can see, control flow travels from left to right
until it hits the first set of clockwise turns, then travels right to left
across the second row, et cetera. Your program *must* use this control flow. The
brainf\*\*\* input will always be able to fit in the image; however, you may not
assume it will always fit the image exactly. If it's too small, pad it with
NOPs; the Braincopter code must still have the clockwise/counterclockwise turns on either side, though.
You may assume that the Brainf\*\*\* input will contain only the eight characters
`><+-,.[]`.
Use the [official Braincopter interpreter](http://lodev.org/esolangs/braincopter/braincopter.zip) to test the outputs of your
program or function.
## Test cases
Input:
[](https://i.stack.imgur.com/ioiir.png)
```
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
```
Example output:
[](https://i.stack.imgur.com/3FlOX.png)
Braincopter output:
```
Hello World!
```
Input:
[](https://i.stack.imgur.com/6W4LH.png)
```
>++++++++++[<++++++++++>-]>>>>>>>>>>>>>>>>++++[>++++<-]>[<<<<<<<++>+++>++++>++++++>+++++++>+++++++>++++>-]<++<+++++<++++++++++<+++++++++<++++++<<<<<<<<<<<<<[>+>+>[-]>>>>[-]>[-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]+>---[<->[-]]<[>>>>>>.>.>..<<<<<<<<<<<<+<<[-]>>>>>>-]<<<<<[>>>>>+>+<<<<<<-]>>>>>[<<<<<+>>>>>-]+>-----[<->[-]]<[>>>>>>>>>>.<.<..<<<<<<<<<<<<+<[-]>>>>>-]<+>[-]>[-]>[-]<<<[>+>+>+<<<-]>[<+>-]+>----------[<->[-]]<[<<+>[-]>-]>[-]>[-]<<<<[>>+>+>+<<<<-]>>[<<+>>-]+>----------[<->[-]]<[<<<+>[-]>>-][-]>[-]<<<<<[>>>>+>+<<<<<-]>>>>[<<<<+>>>>-]+>[<->[-]]<[[-]>[-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[>++++++++[<++++++>-]<.-.[-]][-]>[-]<<<[>>+>+<<<-]>>>[<<<+>>>-]<[>++++++++[<++++++>-]<.[-]][-]>[-]<<[>+>+<<-]>>[<<+>>-]++++++++[<++++++>-]<.[-]]>>>>.<<<<<<<<<<<-]
```
Output:
[](https://i.stack.imgur.com/5b3bn.png)
Braincopter output:
```
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17...
```
Input:
[](https://i.stack.imgur.com/c5c7k.png)
```
>>+[>>[>]>+>,[>>++++[>++++++++<-]>[<<<[>+>+<<-]>[<+>-]>[<<->>[-]]>-]<<<<->[<+>-[<->-[-[-[-[-[-[-[-[-[<+>-[-[-[-[<->-[-[-[-[-[-[-[-[-[-[-[-[-[<+>-[<->-[<+>-[<->>>+++[>+++++++++<-]>+[<<<[>+>+<<-]>[<+>-]>[<<->>[-]]>-]<<<[<+>-[<->-[<+>-[<->[-]]<[-<++>]>]]<[-<+>]>]]<[-<++++++>]>]]]]]]]]]]]]]]]<[-<+++++>]>]<[-<++++++++>]>]<[-<++++>]>]<[-<+++++++>]>]]]]]]]]]]<[-<+++>]>]]<[-<<[<]<->>[>]>]>]<[-<<[<]<->>[>]>]<<[<]<]>>[>]>>>>>>+<<<<<<<[<]>[[<<[<]<<+>+>>[>]>-]<<[<]<[>>[>]>+<<[<]<-]+<-[-[-[-[-[-[-[->->>[>]>[>]>>>>>[>[>>]>>>]>>[<<<<+>>+>>-]<<[>>+<<-]>>>[<<<<+>+>>>-]<<<[>>>+<<<-]<[->>>>>[<<<<<+>+>>>>-]<<<<[>>>>+<<<<-]<[<++++++++++>-]]>>>>>>[<<<<<<+>+>>>>>-]<<<<<[>>>>>+<<<<<-]<[->>>>>>>[<<<<<<<+>+>>>>>>-]<<<<<<[>>>>>>+<<<<<<-]<[<<++++++++++[>++++++++++<-]>>-]]<.[-]<<<[<<]>[<<<<<[<<]>]<<[<]>[<+>-]<[<]<<]>[->>[>]>[>]>>>>>[>[>>]>>>]>[>>]<<[->[-]>>>>[<<+>>->[<<+>>->[<<+>>-]>]>>>]<<<<<<<[<<]>[<<<<<[<<]>]>[>>]<<]>>>>>[>[>>]>>>]<<<<<[<<]>[>[>>]<<[->>+<[>>+<<-]<<<]>->>+<<<<<<<[<<]>]>+>>>>>[>[>>]>>>]>,[>+>+<<-]>[<+>-]>[[>+>+<<-]>>[<<+>>-]<[-<->[-<->[-<->[-<->[-<->[-<->[-<->[-<->[-<->[[-]<-><<<---------->+>>]]]]]]]]]]<]<[>+>+<<-]>[<+>-]>[-[-[-[-[-[-[-[-[-[-<<---------->+>[-[-[-[-[-[-[-[-[-[[-]<<---------->+>]]]]]]]]]]]]]]]]]]]]<<[>>+>+<<<-]>>[<<+>>-]+>[<<<+>>->[-]]<[-<[>+>+<<-]>[<+>-]>[<<<+>>>[-]]<]<[>+>+<<-]>[<+>-]>[<<+>>[-]]<<<<+[-[<<<<<<[<<]>[<<<<<[<<]>]>[>>]<+>>>>[>[>>]>>>]>-]>[>]<[[>+<-]<]<<<<<<[<<]>[>[>>]<<[>[>>+<<-]>+<<-<<]>->>+<<<<<<<[<<]>]>[>>]+>>>>>[>[>>]>>>]>]<<<<<<[<<]>[<<<<<[<<]>]>[>>]<<->>>>>[<<+>>->[<<+>>->[<<+>>-]>]>>>]<<<<<<<[<<]>[<<<<<[<<]>]<<<<<[<<]>[<<<<<[<<]>]<<[<]>[<+>-]<[<]<]<]>[->>[>]>[>]>>>>>[>[>>]>>>]+>[>>]>>>[-]>[-]+<<<<<<[<<]>[<<<<<[<<]>]<<[<]>[<+>-]<[<]<]<]>[->>[>]>[>]>>>>>[>[>>]>>>]+<<<<<[<<]>-<<<<<[<<]>[<<<<<[<<]>]<<[<]>[<+>-]<[<]<]<]>[->>[>]>[>]>>>>>[>[>>]>>>]>[->[<<<[<<]<<+>+>>>[>>]>-]<<<[<<]<[>>>[>>]>+<<<[<<]<-]+<[[-]>->>>[>>]>-<+[<<]<<]>[->>>[>>]>+++++++++<<<[<<]<]>>>[>>]+>>]<<-<<<<[>>>>+>+<<<<<-]>>>>[<<<<+>>>>-]>[-<<[>+>+<<-]>[<+>-]>>+<[[-]>-<]>[-<<<<->[-]>>>>[<<+>>->[<<+>>->[<<+>>-]>]>>>]<<<<<<<[<<]>[<<<<<[<<]>]>[>>]>>]<]<<<[<<]<<<<[<<]>[<<<<<[<<]>]<<[<]>[<+>-]<[<]<]<]>[->>[>]>[>]>>>>>[>[>>]>>>]>>+<[->[<<<[<<]<<+>+>>>[>>]>-]<<<[<<]<[>>>[>>]>+<<<[<<]<-]<[-[-[-[-[-[-[-[-[-[->>>>[>>]>[-]>[-]+>+<<<<<[<<]<<]]]]]]]]]]>>>>[>>]+>>]>[-<<<[<<]<<+>+>>>[>>]>]<<<[<<]<[>>>[>>]>+<<<[<<]<-]<[->>>>[>>]>[>[>>]<<[>[>>+<<-]>+<<-<<]>->>+>[>>]>]<<<[<<]>[<<<<<[<<]>]<<<]<<[<<]>[<<<<<[<<]>]<<[<]>[<+>-]<[<]<]<]>[->>[>]>[>]>>>>>[>[>>]>>>]>[>>]>>>[>[>>]>>>]>+[<<<<<<[<<]>[<<<<<[<<]>]<<<<<[<<]>[<<<<<[<<]>]<<[<]<[>+<-]>[<<[<]<<+>+>>[>]>-]<<[<]<[>>[>]>+<<[<]<-]+<-[-[>-<[-]]>[->>[>]>[>]>>>>>[>[>>]>>>]>[>>]>>>[>[>>]>>>]>[>]+[<]<<<<<[<<]>[<<<<<[<<]>]<<<<<[<<]>[<<<<<[<<]>]<<[<]<[<]<]<]>[->>[>]>[>]>>>>>[>[>>]>>>]>[>>]>>>[>[>>]>>>]>[>]<-<[<]<<<<<[<<]>[<<<<<[<<]>]<<<<<[<<]>[<<<<<[<<]>]<<[<]<[<]<]>>[>]>[>]>>>>>[>[>>]>>>]>[>>]>>>[>[>>]>>>]>]<<<<<<[<<]>[<<<<<[<<]>]<<<<<[<<]>[<<<<<[<<]>]<<[<]<[<]<]<]>[->>[>]>[>]>>>>>[>[>>]>>>]>>[<<<+>+>>-]<<[>>+<<-]>>>[<<<<+>+>>>-]<<<[>>>+<<<-]<<+>[[-]<-<<<[<<]>[<<<<<[<<]>]<<[<]>[<+>-]>[>]>>>>>[>[>>]>>>]<]<[->>>[>>]>>>[>[>>]>>>]>+[<<<<<<[<<]>[<<<<<[<<]>]<<<<<[<<]>[<<<<<[<<]>]<<[<]>[<+>-]>[<<[<]<<+>+>>[>]>-]<<[<]<[>>[>]>+<<[<]<-]+<-[-[>-<[-]]>[->>[>]>[>]>>>>>[>[>>]>>>]>[>>]>>>[>[>>]>>>]>[>]<-<[<]<<<<<[<<]>[<<<<<[<<]>]<<<<<[<<]>[<<<<<[<<]>]<<[<]<[<]<]<]>[->>[>]>[>]>>>>>[>[>>]>>>]>[>>]>>>[>[>>]>>>]>[>]+[<]<<<<<[<<]>[<<<<<[<<]>]<<<<<[<<]>[<<<<<[<<]>]<<[<]<[<]<]>>[>]>[>]>>>>>[>[>>]>>>]>[>>]>>>[>[>>]>>>]>]<<<<<<[<<]>[<<<<<[<<]>]<<<<<[<<]>[<<<<<[<<]>]<<[<]>[<+>-]>[>]>>>>>[>[>>]>>>]<<]<<<[<<]>[<<<<<[<<]>]<<[<]<[<]<]>>[>]>]
```
Output:
[](https://i.stack.imgur.com/ux0Yk.png)
Braincopter output:
This is a [Brainf\*\*\* self-interpreter](http://www.brain------------------------------------------------------fuck.com/programs/kbfi.b). It separates code from input by `!`;
for example, the input `,[.,]!Hello, World!\0` will output `Hello, World!`,
assuming the `\0` was replaced by a null byte.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins. Happy golfing!
[Answer]
# Python, ~~664~~ 656
usage : `python snippet.py image.png <bf script>`
```
R=range;_=R(256);a=abs
def C(c):R,G,B=c;return'><+-.,[]RLN'[(65536*R+256*G+B)%11]
def D(c,d):R,G,B=c;F,V,H=d;return a(R-F)+a(G-V)+a(B-H)
def E(c1,i):return min([(c,D(c1,c))for c in[(r,g,b)for r in _ for g in _ for b in _]if C(c)==i],key=lambda x:x[1])[0]
def B(b,w,h):
x,y,d=0,0,1
for c in(b[0]+'R'.join(['L'+s for s in[s[::-1]if i%2 else s for i,s in enumerate([(b[1:]+'N'*w*h)[q:q+w-2]for q in R(0,w*h,w-2)])]])[1:])[:w*h][:-1]+'N':
yield c,(a(x),y)
x+=d
if c=='R':x=0;y+=1;d*=-1
import sys
from PIL import Image
I=Image.open(sys.argv[1]).convert('RGB')
W,H=I.size
P=I.load()
for i,p in B(sys.argv[2],W,H):P[p]=E(P[p],i)
I.save(sys.stdout,"PNG")
```
explanations to come ...
] |
[Question]
[
**This question already has answers here**:
[Fairy chess "leaper" movement patterns](/questions/69014/fairy-chess-leaper-movement-patterns)
(4 answers)
Closed 7 years ago.
Given an input of a pair of nonnegative integers describing a
[leaper](https://en.wikipedia.org/wiki/Fairy_chess_piece#Leapers) in chess,
output a diagram of the squares to which the leaper can move.
From Wikipedia's description:
>
> An (m,n)-leaper is a piece that moves by a fixed type of vector between its
> start square and its arrival square. One of the coordinates of the vector
> 'start square – arrival square' must have an absolute value equal to m and
> the other one an absolute value equal to n. [...] For instance, the knight is
> the (1,2)-leaper.
>
>
>
In normal-people-speak, an (m,n)-leaper can move m squares in any direction,
turn 90 degrees, and move n more squares. For example, a (1,2)-leaper (also
known as the *knight*) can move to these squares:
```
.E.E.
E...E
..S..
E...E
.E.E.
```
where `S` represents the start square, `E` represents the end square, and `.`
represents an empty square. This must also be your output for the input `1 2`
(and `2 1`).
Specifically, the output must
* be a square grid with side length `max(m,n) * 2 + 1`.
* contain exactly one `S`, located in the center of the square.
* contain `E`s at the positions that a (m,n)-leaper at `S` could move to.
* contain dots (`.`) at all other positions.
You may assume that `m ≥ 0`, `n ≥ 0`, `m + n > 0`, and that `m` and `n` are
integers.
Output may be a single string, an array of lines, or an array of arrays of
characters.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win.
Test cases (all test cases should work with input integers swapped as well):
```
4 1
...E.E...
.........
.........
E.......E
....S....
E.......E
.........
.........
...E.E...
2 2
E...E
.....
..S..
.....
E...E
3 0
...E...
.......
.......
E..S..E
.......
.......
...E...
1 1
E.E
.S.
E.E
0 1
.E.
ESE
.E.
12 13
.E.......................E.
E.........................E
...........................
...........................
...........................
...........................
...........................
...........................
...........................
...........................
...........................
...........................
...........................
.............S.............
...........................
...........................
...........................
...........................
...........................
...........................
...........................
...........................
...........................
...........................
...........................
E.........................E
.E.......................E.
```
[Answer]
# Javascript, ~~153~~ 151 bytes
```
x=>y=>(G=(g,h)=>~[b-x,b+x][X='indexOf'](g)&&~[b-y,b+y][X](h),r=[...Array((b=x>y?x:y)*2+1)]).map((_,i)=>r.map((_,j)=>G(i,j)|G(j,i)?'E':b-i|b-j?'.':'S'))
```
Ungolfed with explanation:
```
f= // saves the function in f
x=>y=>( // currying the leaping numbers
G=(g,h)=> // helper function
~[b-x,b+x][X='indexOf'](g) // check if g/x is in a goal square by x
&& // and
~[b-y,b+y][X](h), // if h/y is in a goal square by y
r=[...Array( // row or column
(b=x>y?x:y)*2+1 // of Math.max(x,y)*2+1 squares
)] // stored in r
).map((_,i)=> // map r with i being the row index
r.map((_,j)=> // for each row map a column with j being its index
G(i,j)|G(j,i) // if this square is one possible goal
?'E' // then 'E'
:b-i|b-j // if is not the middle square
?'.' // then '.'
:'S' // else 'S'
) // end/next column setup
) // end function
P.addEventListener('click',_=>(
a=I.value.split`,`,
O.innerHTML=f(+a[0])(+a[1]).map(x=>x.join``).join`\n`
));
```
```
<input id=I value="1,2"><button id=P>Play</button><pre id=O>
```
] |
[Question]
[
A helicopter starting at the top left corner is descending (in a 2D space, for the purpose of this question) towards the ground. It has an autopilot mode and a manual mode.
The autopilot mode behaves as follows:
* If the space directly below is free, descend to it.
* Otherwise move a step left or right, totally at random. (It may move multiple steps in this manner.)
And it keeps repeating these two steps until it hits the ground. The manual mode is more smart and will find the optimal path to the ground, even if this requires moving upwards, or some skillful manoeuvring.
Your job is to determine if
1. The autopilot will pass in the given scenario,
2. The autopilot might fail in the given scenario,
3. The autopilot will fail, but the manual mode will pass, or
4. Both modes will fail (there is no valid path to the ground).
**Input**
* Given scenario as a 1d or 2d non-empty array, using two different characters to represent free and blocked spaces. Punctuation optional.
* Optional: dimensions of array
**Output**
One of four predefined characters indicating which of the cases has occurred.
**Sample data**
*Using 0 (empty) and 1 (blocked) in input, 1 2 3 4 in output (as numbered above)*
```
0 0 0 0
0 1 0 0
0 0 0 1
1 1 0 0
```
Output: `1`
```
0 0 1 0
1 0 0 1
0 0 0 0
0 1 1 0
0 0 0 1
```
Output: `2` (The helicopter will encounter the 1 in the fourth row, and it is possible it will trap itself at the end of row 5, if on autopilot mode)
```
0 0 0 1 0
0 1 1 0 0
0 1 0 0 0
0 0 0 1 0
1 1 1 1 0
```
Output: `3` (This requires moving upwards, so the autopilot fails)
```
1 0 0
0 0 0
```
Output: `4`
```
0 0 0 0 1
1 1 1 0 0
1 0 0 1 0
0 1 0 0 0
0 0 1 1 1
```
Output: `4`
[Answer]
# Ruby, 259
I had a lot of fun with this. Thank you! [grid](/questions/tagged/grid "show questions tagged 'grid'") challenges tend to be excellent fun with interesting challenges. This assumes that "characters" in the question can be integers.
I think the major points of improvement here are:
1. The creation of `r`
2. The ghastly ternary abuse on the third line can likely be made into a more-ghastly, but terser something.
```
->a,h,w{f=->l,s=0,y=[0]{r=w-2<s%w ?w:1,1>s%w ?w:-1,w
v=(l ?r+[-w]:a[s+w]==0?[w]:r).map{|d|a[m=s+d]==0&&!y[m]?m:p}-q=[p]
a[s]>0?q:s/w>h-2?8:v[0]?v.map{|o|f[l,y[o]=o,y]}.flatten-q :r.any?{|i|a[s+i]<1}?p: !0}
g=f[p]
[8,g[0]&&g.all?,g.any?,f[8].any?,!p].index !p}
```
Ungolfed (slightly out of date, but real close):
```
# a is a one-dimensional array of 0s and 1s, h is height, w is width
->a,h,w{
# f recursively walks the array and returns true/false/nil for each path.
# True means we can reach ground.
# False means we are stuck in a local minimum and cannot escape
# Nil means we reached a local dead-end and need to backtrack.
# l: {true=>"manual", false=>"autopilot"}
# s: the position index
# y: an array of booleans - true-ish means we've visited that square before
# (this is to prevent infinite loops, esp in manual mode)
f=->l,s=0,y=[0]{
# d: all the legal deltas from s (maximally, that's [1,-1,w,-w], aka [LRDU])
# r: but the right and left get tricky on the edges, so let's pre-calculate those
# we'll default to "down" if "left" or "right" are illegal
r=[w-2<s%w ?w:1,1>s%w ?w:-1]
# if manual, [LRDU]; if auto, and you can go down, [D]. else, [LR]
d=l ?r+[w,-w]:a[s+w]==0?[w]:r
# v: the legal deltas that you can go to from s (that is, unvisited and unblocked)
v=d.map{|d|a[m=s+d]==0&&!y[m]?m:p}-[p]
a[s]>0 ? [p] # if we're currently blocked, return [nil] (this is only the case when a[0]==1)
: s/w>h-2 ? !p # if we're at the bottom, return true
: v[0] ? # if we have a place to go....
v.map{|o|f[l,y[o]=o,y]}.flatten-[p] # recurse with each step.
# y[o]=o is a neat trick to make y[o] truthy and return o
: r.any?{|i|a[s+i]==0} ? # otherwise, we have nowhere to go. If we could visit left/right, but have already been there
p # this is not a dead-end - return nil to remove this path
: !!p # If we have a true dead-end (auto-mode with a local minimum), false
}
# g is the auto flight
g=f[p]
# finally, choose the first "true" out of:
# 0: always 8. Cuz why not 8?
# 1: there is at least one auto path, and all are truthy
# 2: any auto path is truthy
# 3: any manual path is truthy
# 4: true
[8,g[0]&&g.all?,g.any?,f[!p].any?,!p].index !p
}
```
] |
[Question]
[
There are many [puzzles with matches](http://www.learning-tree.org.uk/stickpuzzles/stick_puzzles.htm) that involve adding, removing, or moving a certain number of matches to create new numbers or shapes. This is like that with a digital clock.
Given a valid time on a 12-hour digital clock, output the digit that requires moving the fewest lines to make it so every visible digit on the clock becomes that digit. If more than one digit is the minimum, output them all. If it is impossible to make every digit the same, output `-1` or a falsy value other than 0 (you'll get a lot of these).
The clock digits look like this:
```
|
|
_
_|
|_
_
_|
_|
|_|
|
_
|_
_|
_
|_
|_|
_
|
|
_
|_|
|_|
_
|_|
_|
_
| |
|_|
```
## Test Cases:
Input: `123`
Clock Display:
```
_ _
| : _| _|
| : |_ _|
```
Output: `4`
Explanation: The display for `1:23` requires a total of 12 lines to be drawn. Therefore, for every digit to be the same, each digit would have to have 4 lines. The only digit that has 4 lines is `4`. Therefore, the answer has to be `4`.
Input: `1212`
Clock Display:
```
_ _
| _| : | _|
| |_ : | |_
```
Output: `-1`
Explanation: The display for `12:12` requires 14 lines. 14 divided by 4 is not an integer, therefore it is impossible for every digit to be the same.
Input: `654`
Clock Display:
```
_ _
|_ : |_ |_|
|_| : _| |
```
Output: `5`
Explanation: The total number of lines is 15. 15 divided by 3 is 5, so each digit must have 5 lines. The only digits that have 5 lines are `2`,`3`, and `5`. The answer is `5` because it only requires 2 moves to make every digit 5. Simply move the line at the bottom left of the 6 to the bottom of the 4, then you have:
```
_ _
|_ : |_ |_|
_| : _| _|
```
Then, as you can see, all you need to do is move the line at the top right of the digit that was originally 4 to the top, and you get `5:55`. To make every digit a `2` or `3` would require more than 2 moves.
Input: `609`
Clock Display:
```
_ _ _
|_ : | | |_|
|_| : |_| _|
```
Output: `609` (`6,0,9` or `[6,0,9]` also ok).
Explanation: `6`, `0`, and `9` are the only digits that have 6 lines. As such, they are also the only possible solutions. It's not hard to see that it would take two moves to make any of these the only digit. Therefore, you output all three digits.
## Notes:
* Although the input time must be valid, the output time does not (e.g. `999` as an output is OK.)
* I am very flexible with input. You can require a leading 0. You can use a number with a decimal point. You can use a string. You can use an array. You can have a parameter for every digit.
[Answer]
# Julia, ~~160~~ ~~157~~ 154
```
x->(c=count_ones;l=[119;36;93;109;46;107;123;37;127;111];m=l[x+1];n=map(a->c(a)==mean(map(c,m))?sum(map(b->c(a$b),m)):1/0,l);find(n.==minimum(n).!=1/0)-1)
```
This is a lambda function. Assign it to a variable to call it. Accepts a vector of integers in range `0-9` of any length and returns a (possibly empty) vector of results.
## Test cases
```
julia> clock = x->(c=co... # assign function to variable
(anonymous function)
julia> clock([1 2 3])
1-element Array{Int64,1}:
4
julia> clock([1 2 1 2])
0-element Array{Int64,1}
julia> clock([6 5 4])
1-element Array{Int64,1}:
5
clock([6 0 9])
3-element Array{Int64,1}:
0
6
9
```
## Explanation
Enumerate the seven segments and represent them as a bit vector.
```
+---+ +-0-+
| | Enumerate 1 2
+---+ > the seven > +-3-+
| | segments 4 5
+---+ +-6-+
```
*Example:* `1` (segments 2 + 5 enabled) becomes `36` (bits 2 + 5 set).
Here are the representations for digits `0-9`.
```
l=[119;36;93;109;46;107;123;37;127;111];
m=l[x+1];
```
We can use the digit as index to get it's bit vector representation. `+1` because of 1-based indexing in julia.
The function `c=count_ones;` counts the number of 1-bits in an integer. We assign an alias because we need it more often.
**The full program, somewhat ungolfed:**
```
x->(
c=count_ones;
l=[119;36;93;109;46;107;123;37;127;111];
m=l[x+1];
n=map(a->c(a)==mean(map(c,m))?sum(map(b->c(a$b),m)):1/0,l);
find(n.==minimum(n).!=1/0)-1
)
```
Now, the last two lines in detail:
`mean(map(c,m))` calculates the average number of lines per input digit.
`n=map(a->...,l)` loops over the vector representation of all digits.
If the number of lines of our current digit `a` is unequal to the average linecount of the input, return `inf`.
```
c(a)==mean(map(c,m))?...:1/0
```
If not, return the sum of the *Hamming Distances* between our current and all input digits.
```
sum(map(b->c(a$b),m))
```
We now have a vector `n` of length `10` representing the numbers `0-9` that gives us the total number of additions/deletions we have to perform to tranform all input digits to that number, or `inf`, if such a transformation is impossible without changing the number of lines.
```
find(n.==minimum(n).!=1/0)-1
```
Finally, output the locations (0-based) of all minima that are not `inf`.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/64081/edit)
# Set Theoretic Arithmetic
## Premise
There have been a couple challenges already that involve multiplying without the multiplication operator ( [here](https://codegolf.stackexchange.com/questions/655/multiply-without-multiply) and [here](https://codegolf.stackexchange.com/questions/37188/multiply-with-restricted-operations) ) and this challenge is in the same vein (most similar to the second link).
This challenge, unlike those previous, will use a [set theoretic definition of the natural numbers](https://en.wikipedia.org/wiki/Set-theoretic_definition_of_natural_numbers) (***N***):
[](https://i.stack.imgur.com/i1rxo.gif)
and
[](https://i.stack.imgur.com/vy8PD.gif)
for example,
[](https://i.stack.imgur.com/RRMI7.gif)
[](https://i.stack.imgur.com/heeoe.gif)
[](https://i.stack.imgur.com/DF1Kx.gif)
and so on.
## The Challenge
Our goal is to use set operations (see below), to add and multiply natural numbers. For this purpose, **all entries will be in the same 'set language' whose interpreter is below**. This will provide consistency as well as easier scoring.
This interpreter allows you to manipulate natural numbers as sets. Your task will be to write two program bodies (see below), one of which adds natural numbers, the other of which multiplies them.
## Preliminary Notes on Sets
Sets follow the usual mathematical structure. Here are some important points:
* Sets are not ordered.
* No set contains itself
* Elements are either in a set or not, this is boolean. Therefore set elements cannot have multiplicities (i.e. an element cannot be in a set multiple times.)
## Interpreter and specifics
A 'program' for this challenge is written in 'set language' and consists of two parts: a header and a body.
### Header
The header is very simple. It tells the interpreter what program you are solving. The header is the opening line of the program. It begins with either the `+` or `*` character, followed by two integers, space delimited.
For example:
```
+ 3 5
```
or
```
* 19 2
```
are valid headers. The first indicates that you are trying to solve `3+5`, meaning that your answer should be `8`. The second is similar except with multiplication.
### Body
The body is where your actual instructions to the interpreter are. This is what truly constitutes your "addition" or "multiplication" program. Your answer will have consist of two program bodies, one for each task. You will then change the headers to actually carry out the test cases.
### Syntax and Instructions
Instructions consist of a command followed by zero or more parameters. For the purposes of the following demonstrations, any alphabet character is the name of a variable. Recall that all variables are sets. `label` is the name of a label (labels are words followed by semicolons (i.e. `main_loop:`), `int` is an integer. The following are the valid instructions:
Flow Control:
1. `jump label` jump unconditionally to the label. A label is a 'word' followed by a semicolon: e.g. `main_loop:` is a label.
2. `je A label` jump to label if A is empty
3. `jne A label` jump to label if A is non-empty
4. `jic A B label` jump to label if A contains B
5. `jidc A B label` jump to label if A does not contain B
Variable Assignment
6. `assign A B` or `assign A int` [](https://i.stack.imgur.com/X7Xn5.gif) or
[](https://i.stack.imgur.com/qJam1.gif) where `set(int)` is the set representation of `int`
Set Ops
7. `union A B C` [](https://i.stack.imgur.com/GwLlq.gif)
8. `intersect A B C` [](https://i.stack.imgur.com/diQk9.gif)
9. `difference A B C` [](https://i.stack.imgur.com/U232G.gif)
10. `add A B` [](https://i.stack.imgur.com/YLR2y.gif)
11. `remove A B` [](https://i.stack.imgur.com/K8wjr.gif)
Debugging
12. `print A` prints the true value of A, where {} is the empty set
13. `printi variable` prints integer representation of A, if it exists, otherwise outputs error.
Comments
14. `;` The semicolon indicates that the rest of the line is a comment and will be ignored by the interpreter
### Further Info
At program start, there are three pre-existing variables. They are **`set1`, `set2`** and **`ANSWER`**. `set1` takes the value of the first header parameter. `set2` takes the value of the second. `ANSWER` is initially the empty set. Upon program completion, the interpreter checks if `ANSWER` is the integer representation of the answer to the arithmetic problem defined in the header. If it is, it indicates this with a message to stdout.
The interpreter also displays the number of operations used. Every instruction is one operation. Initiating a label also costs one operation (Labels can only be initiated once).
You may have a maximum of 20 variables (including the 3 predefined variables) and 20 labels.
### Interpreter code
IMPORTANT NOTES ON THIS INTERPRETER
Things are very slow when using large numbers (>30) in this interpreter. I will outline the reasons for this.
* The structures of sets is such that in increasing by one natural number, you effectively double the size of the set structure. The *n*th natural number has *2^n* empty sets within it (by this I mean that if you look *n* as a tree, there are *n* empty sets. Note only empty sets can be leaves.) This means that dealing with 30 is significantly more costly than dealing with 20 or 10 (you're looking at 2^10 vs 2^20 vs 2^30).
* Equality checks are recursive. Since sets are allegedly unordered, this seemed the natural way to tackle this.
* There are two memory leaks that I couldn't figure out how to fix. I'm bad at C/C++, sorry. Since we're dealing with small numbers only, and allocated memory is freed at program end, this shouldn't really be that much of an issue. (Before anyone says anything, yes I know about `std::vector`; I was doing this as a learning exercise. If you do know how to fix it, please let me know and I will make the edits, otherwise, since it works, I will leave it as is.)
Also, notice the include path to `set.h` in the `interpreter.cpp` file. Without further ado, the source code (C++):
### set.h
```
using namespace std;
//MEMORY LEAK IN THE ADD_SELF METHOD
class set {
private:
long m_size;
set* m_elements;
bool m_initialized;
long m_value;
public:
set() {
m_size =0;
m_initialized = false;
m_value=0;
}
~set() {
if(m_initialized) {
//delete[] m_elements;
}
}
void init() {
if(!m_initialized) {
m_elements = new set[0];
m_initialized = true;
}
}
void uninit() {
if(m_initialized) {
//delete[] m_elements;
}
}
long size() {
return m_size;
}
set* elements() {
return m_elements;
}
bool is_empty() {
if(m_size ==0) {return true;}
else {return false;}
}
bool is_eq(set otherset) {
if( (*this).size() != otherset.size() ) {
return false;
}
else if ( (*this).size()==0 && otherset.size()==0 ) {
return true;
}
else {
for(int i=0;i<m_size;i++) {
bool matched = false;
for(int j=0;j<otherset.size();j++) {
matched = (*(m_elements+i)).is_eq( *(otherset.elements()+j) );
if( matched) {
break;
}
}
if(!matched) {
return false;
}
}
return true;
}
}
bool contains(set set1) {
for(int i=0;i<m_size;i++) {
if( (*(m_elements+i)).is_eq(set1) ) {
return true;
}
}
return false;
}
void add(set element) {
(*this).init();
bool alreadythere = false;
for(int i=0;i<m_size;i++) {
if( (*(m_elements+i)).is_eq(element) ) {
alreadythere=true;
}
}
if(!alreadythere) {
set *temp = new set[m_size+1];
for(int i=0; i<m_size; i++) {
*(temp+i)= *(m_elements+i);
}
*(temp+m_size)=element;
m_size++;
delete[] m_elements;
m_elements = new set[m_size];
for(int i=0;i<m_size;i++) {
*(m_elements+i) = *(temp+i);
}
delete[] temp;
}
}
void add_self() {
set temp_set;
for(int i=0;i<m_size;i++) {
temp_set.add( *(m_elements+i) );
}
(*this).add(temp_set);
temp_set.uninit();
}
void remove(set set1) {
(*this).init();
for(int i=0;i<m_size;i++) {
if( (*(m_elements+i)).is_eq(set1) ) {
set* temp = new set[m_size-1];
for(int j=0;j<m_size;j++) {
if(j<i) {
*(temp+j)=*(m_elements+j);
}
else if(j>i) {
*(temp+j-1)=*(m_elements+j);
}
}
delete[] m_elements;
m_size--;
m_elements = new set[m_size];
for(int j=0;j<m_size;j++) {
*(m_elements+j)= *(temp+j);
}
delete[] temp;
break;
}
}
}
void join(set set1) {
for(int i=0;i<set1.size();i++) {
(*this).add( *(set1.elements()+i) );
}
}
void diff(set set1) {
for(int i=0;i<set1.size();i++) {
(*this).remove( *(set1.elements()+i) );
}
}
void intersect(set set1) {
for(int i=0;i<m_size;i++) {
bool keep = false;
for(int j=0;j<set1.size();j++) {
if( (*(m_elements+i)).is_eq( *(set1.elements()+j) ) ) {
keep = true;
break;
}
}
if(!keep) {
(*this).remove( *(m_elements+i) );
}
}
}
void natural(long number) {
//////////////////////////
//MEMORY LEAK?
//delete[] m_elements;
/////////////////////////
m_size = 0;
m_elements = new set[m_size];
for(long i=1;i<=number;i++) {
(*this).add_self();
}
m_value = number;
}
void disp() {
if( m_size==0) {cout<<"{}";}
else {
cout<<"{";
for(int i=0; i<m_size; i++) {
(*(m_elements+i)).disp();
if(i<m_size-1) {cout<<", ";}
//else{cout<<" ";}
}
cout<<"}";
}
}
long value() {
return m_value;
}
};
const set EMPTY_SET;
```
### interpreter.cpp
```
#include<fstream>
#include<iostream>
#include<string>
#include<assert.h>
#include<cmath>
#include "headers/set.h"
using namespace std;
string labels[20];
int jump_points[20];
int label_index=0;
const int max_var = 20;
set* set_ptrs[max_var];
string set_names[max_var];
long OPERATIONS = 0;
void assign_var(string name, set other_set) {
static int index = 0;
bool exists = false;
int i = 0;
while(i<index) {
if(name==set_names[i]) {
exists = true;
break;
}
i++;
}
if(exists && index<max_var) {
*(set_ptrs[i]) = other_set;
}
else if(!exists && index<max_var) {
set_ptrs[index] = new set;
*(set_ptrs[index]) = other_set;
set_names[index] = name;
index++;
}
}
int getJumpPoint(string str) {
for(int i=0;i<label_index;i++) {
//cout<<labels[i]<<"\n";
if(labels[i]==str) {
//cout<<jump_points[i];
return jump_points[i];
}
}
cerr<<"Invalid Label Name: '"<<str<<"'\n";
//assert(0);
return -1;
}
long strToLong(string str) {
long j=str.size()-1;
long value = 0;
for(long i=0;i<str.size();i++) {
long x = str[i]-48;
assert(x>=0 && x<=9); // Crash if there was a non digit character
value+=x*floor( pow(10,j) );
j--;
}
return value;
}
long getValue(string str) {
for(int i=0;i<max_var;i++) {
if(set_names[i]==str) {
set set1;
set1.natural( (*(set_ptrs[i])).size() );
if( set1.is_eq( *(set_ptrs[i]) ) ) {
return (*(set_ptrs[i])).size();
}
else {
cerr<<"That is not a valid integer construction";
return 0;
}
}
}
return strToLong(str);
}
int main(int argc, char** argv){
if(argc<2){std::cerr<<"No input file given"; return 1;}
ifstream inf(argv[1]);
if(!inf){std::cerr<<"File open failed";return 1;}
assign_var("ANSWER", EMPTY_SET);
int answer;
string str;
inf>>str;
if(str=="*") {
inf>>str;
long a = strToLong(str);
inf>>str;
long b = strToLong(str);
answer = a*b;
set set1; set set2;
set1.natural(a); set2.natural(b);
assign_var("set1", set1);
assign_var("set2",set2);
//cout<<answer;
}
else if(str=="+") {
inf>>str;
long a = strToLong(str);
inf>>str;
long b = strToLong(str);
answer = a+b;
set set1; set set2;
set1.natural(a); set2.natural(b);
assign_var("set1", set1);
assign_var("set2",set2);
//cout<<answer;
}
else{
cerr<<"file must start with '+' or '*'";
return 1;
}
// parse for labels
while(inf) {
if(inf) {
inf>>str;
if(str[str.size()-1]==':') {
str.erase(str.size()-1);
labels[label_index] = str;
jump_points[label_index] = inf.tellg();
//cout<<str<<": "<<jump_points[label_index]<<"\n";
label_index++;
OPERATIONS++;
}
}
}
inf.clear();
inf.seekg(0,ios::beg);
// parse for everything else
while(inf) {
if(inf) {
inf>>str;
if(str==";") {
getline(inf, str,'\n');
}
// jump label
if(str=="jump") {
inf>>str;
inf.seekg( getJumpPoint(str),ios::beg);
OPERATIONS++;
}
// je set label
if(str=="je") {
inf>>str;
for(int i=0;i<max_var;i++) {
if( set_names[i]==str) {
if( (*(set_ptrs[i])).is_eq(EMPTY_SET) ) {
inf>>str;
inf.seekg( getJumpPoint(str),ios::beg);
OPERATIONS++;
}
break;
}
}
}
// jne set label
if(str=="jne") {
inf>>str;
for(int i=0;i<max_var;i++) {
if( set_names[i]==str) {
if(! (*(set_ptrs[i])).is_eq(EMPTY_SET) ) {
inf>>str;
inf.seekg( getJumpPoint(str),ios::beg);
OPERATIONS++;
}
break;
}
}
}
// jic set1 set2 label
// jump if set1 contains set2
if(str=="jic") {
inf>>str;
string str2;
inf>>str2;
set set1;
set set2;
for(int i=0;i<max_var;i++) {
if( set_names[i]==str ) {
set1 = *(set_ptrs[i]);
}
if(set_names[i]==str2) {
set2 = *(set_ptrs[i]);
}
}
if( set1.contains(set2) ) {
inf>>str;
inf.seekg( getJumpPoint(str),ios::beg);
OPERATIONS++;
}
else {inf>>str;}
}
// jidc set1 set2 label
// jump if set1 doesn't contain set2
if(str=="jidc") {
inf>>str;
string str2;
inf>>str2;
set set1;
set set2;
for(int i=0;i<max_var;i++) {
if( set_names[i]==str ) {
set1 = *(set_ptrs[i]);
}
if(set_names[i]==str2) {
set2 = *(set_ptrs[i]);
}
}
if( !set1.contains(set2) ) {
inf>>str;
inf.seekg( getJumpPoint(str),ios::beg);
OPERATIONS++;
}
else {inf>>str;}
}
// assign variable set/int
if(str=="assign") {
inf>>str;
string str2;
inf>>str2;
set set1;
set1.natural( getValue(str2) );
assign_var(str,set1);
OPERATIONS++;
}
// union set1 set2 set3
// set1 = set2 u set3
if(str=="union") {
inf>>str;
int i=0;
while(i<max_var) {
if( set_names[i] == str ) {
break;
}
i++;
}
set set1;
set set2;
string str1;
inf>>str1;
string str2;
inf>>str2;
for(int j=0;j<max_var;j++) {
if( str1 == set_names[j] ) {
set1= *(set_ptrs[j]);
}
if( str2 == set_names[j] ) {
set2= *(set_ptrs[j]);
}
}
set1.join(set2);
if(i==max_var) {
assign_var(str,set1);
}
else {
set_names[i]= str;
set_ptrs[i] = new set;
*(set_ptrs[i]) = set1;
}
OPERATIONS++;
}
// intersect set1 set2 set3
// set1 = set2^set3
if(str == "intersect") {
inf>>str;
int i=0;
while(i<max_var) {
if( set_names[i] == str ) {
break;
}
i++;
}
set set1;
set set2;
string str1;
inf>>str1;
string str2;
inf>>str2;
for(int j=0;j<max_var;j++) {
if( str1 == set_names[j] ) {
set1= *(set_ptrs[j]);
}
if( str2 == set_names[j] ) {
set2= *(set_ptrs[j]);
}
}
set1.intersect(set2);
if(i==max_var) {
assign_var(str,set1);
}
else {
set_names[i]= str;
set_ptrs[i] = new set;
*(set_ptrs[i]) = set1;
}
OPERATIONS++;
}
// difference set1 set2 set3
// set1 = set2\set3
if(str == "difference") {
inf>>str;
int i=0;
while(i<max_var) {
if( set_names[i] == str ) {
break;
}
i++;
}
set set1;
set set2;
string str1;
inf>>str1;
string str2;
inf>>str2;
for(int j=0;j<max_var;j++) {
if( str1 == set_names[j] ) {
set1= *(set_ptrs[j]);
}
if( str2 == set_names[j] ) {
set2= *(set_ptrs[j]);
}
}
set1.diff(set2);
if(i==max_var) {
assign_var(str,set1);
}
else {
set_names[i]= str;
set_ptrs[i] = new set;
*(set_ptrs[i]) = set1;
}
OPERATIONS++;
}
// add set1 set2
// put set2 in set 1
if(str=="add") {
inf>>str;
int i = 0; int j =0;
while(i<max_var) {
if(set_names[i]==str) {
break;
}
i++;
}
inf>>str;
while(j<max_var) {
if(set_names[j]==str) {
break;
}
j++;
}
set set2 = *(set_ptrs[j]);
if( ! (*(set_ptrs[i])).is_eq(set2) ){
(*(set_ptrs[i])).add(set2);
}
else {
(*(set_ptrs[i])).add_self();
}
OPERATIONS++;
}
// remove set1 set2
// remove set2 from set1
if(str=="remove") {
inf>>str;
int i = 0; int j =0;
while(i<max_var) {
if(set_names[i]==str) {
break;
}
i++;
}
inf>>str;
while(j<max_var) {
if(set_names[j]==str) {
break;
}
j++;
}
set set2 = *(set_ptrs[j]);
(*(set_ptrs[i])).remove(set2);
OPERATIONS++;
}
// print set
// prints true representation of set
if(str=="print") {
inf>>str;
for(int i=0;i<max_var;i++) {
if(set_names[i]==str) {
(*(set_ptrs[i])).disp();
}
}
cout<<"\n";
}
// printi set
// prints integer representation of set, if exists.
if(str=="printi") {
inf>>str;
cout<<getValue(str);
cout<<"\n";
}
}
}
cout<<"You used "<<OPERATIONS<<" operations\n";
set testset;
testset.natural(answer);
switch( testset.is_eq( *(set_ptrs[0]) ) ) {
case 1:
cout<<"Your answer is correct, the set 'ANSWER' is equivalent "<<answer<<".\n";
break;
case 0:
cout<<"Your answer is incorrect\n";
}
// cout<<"\n";
return 0;
}
```
## Winning condition
**You are two write two program *BODIES***, one of which multiplies the numbers in the headers, the other of which adds the numbers in the headers.
This is a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge. What is fastest will be determined by the number of operations used to solve two test cases for each program. The test cases are the following headers lines:
For addition:
```
+ 15 12
```
and
```
+ 12 15
```
and for multiplication
```
* 4 5
```
and
```
* 5 4
```
A score for each case is the number of operations used (the interpreter will indicate this number upon program completion). The total score is the sum of the scores for each test case.
See my example entry for an example of a valid entry.
A winning submission satisfies the following:
1. contains two program bodies, one which multiplies and one which adds
2. has the lowest total score (sum of scores in test cases)
3. Given sufficient time and memory, works for any integer that could be handled by the interpreter (~2^31)
4. Displays no errors when run
5. Does not use debugging commands
6. Does not exploit flaws in the interpreter. This means that your actual program should be valid as pseudo-code as well as an interpretable program in 'set language'.
7. Does not exploit standard loopholes (this means no hardcoding test cases.)
Please see my example for reference implementation and example usage of the language.
[Answer]
# Example Answer, 1323 Operations
*Note that this is an example, not a real entry.*
**Addition Body**
Note that this body will not run without a header.
Comments are not necessary in an actual answer, but are there to help teach the basics of the language.
```
assign ANSWER set2 ; ANSWER = set2
main: ; create label 'main'
add ANSWER ANSWER ; Answer union {Answer}, i.e. ANSWER++
assign looper1 0
assign looper2 0
jump dec
continue:
intersect set1 set1 looper2 ; set1 = set1 intersect looper2, i.e. set1 = min(set1,looper2)
jne set1 main
jump end
dec:
add looper1 looper1 ; looper1++
jidc set1 looper1 continue ; jump if looper >= set1
add looper2 looper2 ; looper2++
jump dec
end:
```
For test case
```
+ 15 12
```
uses `440 operations` and for test case
```
+ 12 15
```
uses `299 operations`.
**Multiplication Body**
```
assign mult_loop 0
main:
jic set1 mult_loop addition
jump end
addition:
assign temp2 set2
main_add:
add ANSWER ANSWER
assign looper1 0
assign looper2 0
jump dec
cont_add:
intersect temp2 temp2 looper2
jne temp2 main_add
jump end_add
dec:
add looper1 looper1
jidc temp2 looper1 cont_add
add looper2 looper2
jump dec
end_add:
add mult_loop mult_loop
jump main
end:
```
For test case
```
* 4 5
```
uses `305 operations` and for test case
```
* 5 4
```
uses `279 operations`.
Therefore my **total score** is `440+299+305+279 =` **`1323`**
] |
[Question]
[
Write a function or program that processes a block of text and returns the new text. Smallest valid program wins.
Each line in the block of text will have the following format:
```
12:34,56
```
The first number is the line ID, the other two comma separated numbers are references to other lines.
In the input text the numbers can be any integer greater than or equal to 0. All numbers will be in ASCII encoded decimal with no leading zeros. There will be no duplicate line IDs. There will be no references to non-existent line IDs, although there may be line IDs that are not referenced.
In the output text the lowest numbered line will be moved to the start of the text block and renumbered to 0. Any references to this line must be updated too. The first reference on that line must be 0 or 1. The second reference can only be 2 if the first reference is 1. Otherwise it must be 0 or 1.
All the lines must be in ascending, incrementing order (no skipped numbers). You can only have a reference to line n if there has been a previous reference to line n-1 or the current line ID is n. There must be no lines that are not referenced by lower line IDs except for line 0. Any such lines must be removed before the final output.
You may assume that the input text is always in the correct format.
Test input #1:
```
45:73,24
78:24,78
89:24,73
73:45,3
72:3,24
3:24,24
24:3,89
```
Reordered:
```
3:24,24
24:3,89
89:24,73
73:45,3
45:73,24
78:24,78
72:3,24
```
Renumbered:
```
0:1,1
1:0,2
2:1,3
3:4,0
4:3,1
78:1,78
72:0,1
```
Unreferenced lines removed for final output:
```
0:1,1
1:0,2
2:1,3
3:4,0
4:3,1
```
Of course, your program doesn't have to follow this order, just produce the correct output. The output must be a single block of text or the closest equivalent in your language, i.e. no character by character direct output. You may either return it (preferred) or output the whole block directly. Assume your output will be passed to another function or program.
Test input #2
```
5:2,3
7:3,2
2:4,2
4:2,3
3:4,3
```
Output:
```
0:1,0
1:0,2
2:1,2
```
Test input #3
```
7:6,3
3:9,7
9:7,3
2:9,6
6:6,7
```
Output:
```
0:1,2
1:3,4
2:2,3
3:2,4
4:1,3
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~226~~ ~~215~~ ~~211~~ ~~209~~ 179 bytes
```
def f(s):
S=dict(map(eval,i.split(":"))for i in s.split("\n"));r="";L=[min(S)];i=0
while L[i:]:a=S[L[i]];L+=set(a)-set(L);r+="%%d:%d,%d\n"%tuple(map(L.index,a))%i;i+=1
return r
```
[Try it online!](https://tio.run/##NY7disMgEEbvfQoRBCW27MaUpIpv4F0us7mQ1dCB1Iqx@/P0WRvYq/PNYb5h0m@5PaLcdx8WvLCNK4RH4@GzsLtLLHy5VcB5SysURhThfHlkDBgi3v7tR6xaZ0OItma6Q2QjnzWYN4S/b7AGbCdQs3JmnGqaZ20bs4XCHD@9YGu3MYRSr6gX1NdztDzTGo4H7BmiDz/CcU5BQ2PeEc6hPHPEeU8ZYmELI4R0F9VL0XaoH1TbiX5Aw/UIEvVSdRdR2apjQ758ZdvVebjWMuf7Hw "Python 3 – Try It Online")
] |
[Question]
[
This challenge, if you accept it, is to write three functions or programs A, B, and C:
* A is a quine that outputs all of A,B and C (which is also the whole content of the code in your submission).
* B takes a parameter F and checks whether it is such a quine (outputting FBC), or doing something different.
* C takes a parameter G and checks whether G possibly works like B (checking whether F outputs FGC). It is impossible to decide whether a function is a quine checker, so let's do something simpler:
+ It must return truthy if G is valid for B.
+ It must return falsey if G returns falsey for all valid quines, or G returns truthy for all valid non-quines.
+ It can return anything, crash or not terminate, etc, if it is any of the other cases.
Note that B is possible. A and F doesn't have any input, so you can just run them and check the result.
### Rules
* There should be some way to tell which parts are A, B and C from the output of A. For example: each has one line, or they are recognized as three functions in the interpreter.
* Each function should run with only the definition of itself, not your complete code.
* You can use a function/program or its source code, or a pair of both as the input of B (or G) and C.
* You can redefine [truthy/falsey](http://meta.codegolf.stackexchange.com/q/2190/25180) to a subset of those values. You can also consistently require F returning some type you choose, like a single string.
* You can require A, B, F and G, if they are called with valid parameters, consistently don't have some types of other inputs or side effects you choose, such as accessing global variables, or reading stdin, etc.
* You can also assume F and G, if they are called with valid parameters, always terminate.
* F should work in the same condition as A. So it cannot depend on B or C or another variable's existence, unless that variable is defined in its own part in its output.
* No functions or programs can read its own source code.
* This is code-golf, shortest code (which is the output of A) in bytes wins.
[Answer]
# CJam, 254 bytes
An example answer, not golfed.
```
{{['{\"_~}{{[1$'{@\"_~}"{{["_~}"2$+'{@"_~}"]s`"{{['{\\"\+"]s}_~}"+~1$~{L}@~!&}_~}_``1>W<"\"]s\~=}_~}"@]s}_~}{{[1$'{@"_~}{{[\"_~}\"2$+'{@\"_~}\"]s`\"{{['{\\\\\"\+\"]s}_~}\"+~1$~{L}@~!&}_~}"]s\~=}_~}{{["_~}"2$+'{@"_~}"]s`"{{['{\\"\+"]s}_~}"+~1$~{L}@~!&}_~}
```
The 3 functions are:
```
{{['{\"_~}{{[1$'{@\"_~}"{{["_~}"2$+'{@"_~}"]s`"{{['{\\"\+"]s}_~}"+~1$~{L}@~!&}_~}_``1>W<"\"]s\~=}_~}"@]s}_~}
```
```
{{[1$'{@"_~}{{[\"_~}\"2$+'{@\"_~}\"]s`\"{{['{\\\\\"\+\"]s}_~}\"+~1$~{L}@~!&}_~}"]s\~=}_~}
```
```
{{["_~}"2$+'{@"_~}"]s`"{{['{\\"\+"]s}_~}"+~1$~{L}@~!&}_~}
```
A and F take no parameters and return a string. B, G and C take a CJam block as parameter and return 1 for truthy, or 0 for falsey.
] |
[Question]
[
In [Bgil Midol's question](https://codegolf.stackexchange.com/q/242616/), the score of a sequence of slice is defined as
>
> sumof|startslices|∗2+sumof|endslices|∗2+sumof|stepslices|∗3
>
>
>
Such scoring method makes multiple slices possibly take less score, e.g.
* `[::25]` 75
* `[::5][::5]` 30
Given the length of a string, an upper bound of number of slices1, and the one slice it equals to2, output a way of slicing with lowest score. You can assume that the result after slicing isn't empty.
```
6 1 [3:4] -> [3:-2]
6 9 [3:4] -> [:-2][-1:]
1000 1 [::25] -> [::25]
1000 2 [::25] -> [::5][::5]
1000 9 [1::25] -> [1::5][::5]
1000 9 [5::25] -> [::5][1::5]
9100 9 [90::91] -> [::-91][::-1]
```
Shortest code in each language wins.
1. Notice that `[:]` is a valid slice with no effect to score
2. It can be proven that every sequence of slice can equal to one slice for a fixed string before slice
]
|
[Question]
[
This is based on a game one of my math teachers used to play in middle school. He would write 5 random one-digit numbers on the board, and then a random two-digit number. We would try to create an equation that used all 5 of the one-digit numbers to yield the two-digit number.
Here are some examples with solutions to explain this better:
```
Input: Solution:
7 5 4 8 4 34 5*8-7+4/4 = 34
3 1 5 7 6 54 (7+3)*6-5-1 = 54
3 9 2 1 6 87 9*(2+1)*3+6 = 87
2 1 6 9 7 16 (9-7+6*1)*2 = 16
2 4 5 8 6 96 8*(5+6)+2*4 = 96
3 8 4 5 4 49 8*(4+4)-3*5 = 49
```
This challenge is to write a program that can generate such equations for a given input.
The input can be provided either via the command line or via a prompt. The 5 one-digit numbers will always be entered first (in no particular order), followed by the two-digit number. The program will then print out a solution equation it finds; you do not have to handle situations where there is no solution. The function must be capable of using the following operations in the equation: addition, subtraction, multiplication, and division. If you would like to allow additional basic operations, that's fine as long as they remain in the spirit of the challenge (negation, exponentiation, and modulus would be nice additions). Order of operations follows the standard math rules, so parenthesis will be needed for grouping.
The program must take less than a minute to run on a modern computer.
Programs will be scored based on code length (including required whitespace).
Note: division must be exact, not rounded or truncated to nearest integer.
[Answer]
## Python 2.7 (284), Python 3.x (253)
```
from __future__ import division #(Remove for Python 3.x)
from itertools import *
a=raw_input().split()
for i in permutations(a[:-1],5):
for j in product('+-*/',repeat=5):
for k,l in combinations(range(1,12,2),2):
d=''.join(sum(zip(i,j),()))[:-1];d='('+d[:l]+')'+d[l:]
if eval(d)==int(a[-1]):print d;b
```
It gives an error (calling unknown function `b`) on solution.
Basically, it's a gigantic brute force. It takes in the input, splits it by its spaces (`1 2 -> [1,2]`), and then permutes through that list. With every permutation, it will iterate through all possible strings of length 5 using the characters `+-*/`. With each of those iterations, it will generate the combinations of length 2 of the list `[1,3,5,7,9,11]`, interweave the permutation and the string together (`12345 *-/+- -> 1*2-3/4+5-`), and put in the parentheses. Finally, it will evaluate it, and if the answer and equation are true, then it prints the equation and stops.
This is horribly inefficient, about `O(n!/(n-5)!)=O(n^5)`, but it runs in a reasonable time for the test inputs.
[Answer]
### Scala 368:
The 2nd g=-Line is more easy to test, the first is flexible to take command arguments, and both are of equal length, so I only count from the second one - remove it to do args passing:
```
val g=(args.map(_.toDouble))
val g=Array(3,9,2, 1, 6, 87)
val k="+*/-DQ"
val i=(0 to 5)
val f:Seq[(Double,Double)=>Double]=Seq(_+_,_*_,_/_,_-_,(a,b)=>b-a,(a,b)=>b/a)
val h=g.init.permutations;
for(j<-h;o<-i;p<-i;q<-i;r<-i;z=try{f(r)(f(q)(f(p)(f(o)(j(0),j(1)),j(2)),j(3)),j(4))}catch{case _ => 0}
if(z==g(5)))printf("(((%d%c%d)%c%d)%c%d)%c%d=%d\n",j(0),k(o),j(1),k(p),j(2),k(q),j(3),k(r),j(4),g(5))
```
Sample output (you might have a question right now - just a moment):
```
(((5+7)/1)+6)*3=54
(((5-7)D1)*6)*3=54
(((5D7)+1)*6)*3=54
(((5+7)+6)Q1)Q3=54
```
What about this 5D7 thing? D1? Is it hex? There is Q1, Q3 - what's that.
Sir\_Lagsalot allowed new basic operations in the spirit of the challenge, and yes, these are basic operations, Delta and Quotient.
They are different from a/b and a-b in that aQb means b/a and aDb means b-a. Let's call it the Ukrainian notation.
So
```
(((5-7)D1)*6)*3=54
```
means
```
((1-(5-7))*6)*3=54
(1-(-2))*6*3
3*6*3 = 18*3=54
```
To the more interesting question of the how and why: In the beginning I got mad about the possibilities to place the parentheses, and whether (a+b)-c = a+b-c = (a+b-c) = ((a+b)-c) = (b+a)-c and so on. You can get mad over this question, but if you write down the possible parenthesis combinations, you sometimes throw away the scratch sheet and face the fact: You always perform 4 operations between 5 values, and you always start with one of them. If the pattern is always `(((_x_)x_)x_)x_ ?= _` (x being one of the 4 operators) and allow the opposite direction ( x b) and (b x a), you addressed every possibility.
Now for a+b and a\*b we don't need no opposite direction, they are commutative. So I invented the D and Q operator, which just switch the direction. I now have 2 operators more, but don't need to switch direction. Well - it is done in the function Sequence:
```
(a,b)=>b-a,(a,b)=>b/a
```
My for-comprehension takes the values from the Array g, and distributes them on a to e, then I pick 4 indexes to pick the function and later the (only by index) associated operator symbol. I have to catch div/0 errors, since subtraction can lead to zeros, while the sample input data doesn't contain a 0.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/210248/edit).
Closed 3 years ago.
[Improve this question](/posts/210248/edit)
Design a language and golf its interpreter so that it solves the following programming challenges in as few bytes as possible:
* Hello World
* cat
* Fizz Buzz
* List the first \$n\$ primes
* Fibonacci Sequence
* Sort a numerical list
* Balanced parentheses/brackets/braces test
* Rule 110 (as a proof of Turing completeness)
# Challenge Definitions
## Hello World
No input.
Output this exact text:
```
Hello World!
```
## cat
Input: text
Output: the same text
## Fizz Buzz
Input: an integer \$n\$
Output: all numbers from \$1\$ to \$n\$, with multiples of 3 replaced with "Fizz", multiples of 5 replaced with "Buzz", and multiples of 15 replaced with "FizzBuzz" or "Fizz Buzz".
## List the first \$n\$ primes
Input: an integer \$n\$
Output: the first \$n\$ prime numbers, defined as positive integers which are divisible only by 1 and themselves.
## Fibonacci Sequence
Defined formally as:
$$
f\_1 = 1
$$
$$
f\_2 = 1
$$
$$
f\_{n+2} = f\_n + f\_{n+1}
$$
The first few Fibonacci numbers are: \$1, 1, 2, 3, 5, 8, 13, 21, 34, 55\$
Input: an integer \$n\$
Output: the first \$n\$ Fibonacci numbers.
## Sort a numerical list
Input: A list of integers. May be empty. May contain duplicate numbers.
Output: All of the elements of that list sorted in ascending order.
## Balanced parentheses / brackets / braces test
Input: A possibly empty string containing printable ASCII characters
Output: truthy if parentheses, brackets, and braces are all balanced and matching, falsy otherwise
Examples:
```
--> truthy
non-empty string --> truthy
[] --> truthy
(} --> falsy
()[] --> truthy
bl[ah] --> truthy
1) --> falsy
([]{}((()))[{}]) --> truthy
([{}])} --> falsy
```
## Rule 110
[Wikipedia article on Rule 110](https://en.wikipedia.org/wiki/Rule_110)
For quick reference, given a list of cells which are either on or off, the next state is generated from each cell and its neighbors, using the following table of rules:
```
current pattern 111 110 101 100 011 010 001 000
new cell 0 1 1 0 1 1 1 0
```
Cells outside the list are considered off and must be generated on demand when they turn on.
Input: A rule 110 state, in any convenient representation
Output: The next rule 110 state, with at least one extra cell added to the left side if necessary.
Implementing Rule 124 (Rule 110's mirror image) is also acceptable, as this can be interpreted as Rule 110 on a reversed list.
# Rules
* Programs written in your language can use any convenient IO method
* Hello World and cat are allowed to output a single trailing newline.
* The full range of 32-bit signed integers must be supported, at minimum, for all numeric challenges.
* The golfing language may not be a literal subset of its host language.
* Your language interpreter must be non-trivially implemented. All of the following loopholes are banned: (I reserve the right to ban more if the need arises)
+ Your interpreter simply calls out to `eval` or equivalent
+ A 1:1 remapping is applied to the program text and then interpreted by another function or external program.
# Scoring
$$
Score = 3 \times I + P
$$
Where:
* \$I\$ is the length of the interpreter, in bytes
* \$P\$ is the sum of the length of all challenge programs, in bytes
Lowest score wins.
It's better to have a smaller interpreter than short programs, making builtins potentially more costly than a smaller instruction set.
]
|
[Question]
[
Imagine a grid where the origin square \$(0,0)\$ is at the top left of the screen, and positive \$x\$ is rightwards whereas positive \$y\$ is downwards. Coloured squares are at various positions on the grid.
In a magical void separate from the grid are multiple snake-like strips of squares, each of a fixed length and a certain colour. Colours may or may not repeat across strips.
Each of our strips can move left, right or forward *from the perspective of the head* but can obstruct itself. The strips basically move by popping the tail and pushing a new head, as [snakes](https://en.wikipedia.org/wiki/Snake_(video_game)) do. They are necessary and sufficient to cover every correspondingly coloured position on the grid without strip overlap.
1. At any one time, you select a single snake from your inventory to control. It appears at \$(0,0)\$ pointing downwards, and moves are counted *after* this happens (see Samples below).
2. Whenever you select a new snake, the previous one gets stuck where it is.
Sounds dreadful, doesn't it? It's as if you need to plan all your moves…!
**What moves will solve the grid?**
**Input**
* A matrix where different colours are represented by differing positive integers, and an uncoloured position is represented by 0.
* Each strip's 'colour'; its length; and, since strips may share colours, a unique identifier.
You need only consider grids solvable by the method described in the introduction.
**Output**
Give the unique identifier of each strip you're moving, and the sequence of moves it should make:
* You may use any consistent value for up (\$-y\$ wrt the grid), any consistent value for down (\$+y\$), any consistent value for left (\$-x\$ wrt the grid) and any consistent value for right (\$+x\$).
More than one solution is typically possible. Please choose one.
Possible output types are not limited to [associative arrays](https://en.wikipedia.org/wiki/Associative_array).
---
In the sample test cases below, for the sake of example *only*, W, A, S, D represent up, left, down and right respectively. Also for the sake of example only, these rules are followed:
* In the input, the unique identifier for a strip is given first, followed by its 'colour', followed by its length.
* In the output, the unique identifier for any strip is followed by the moves for that strip. Consider the sets of moves in their given order.
* Unique identifiers will be letters.
## Sample 1
Input — grid
```
0010000
0000100
```
Input — strips
```
a 1 4
```
Possible output
```
a DDDS
```
Result (strip narrowed for clarity): [image link](https://i.stack.imgur.com/I7TYn.png)
## Sample 2
Input — grid
```
0010000
0200000
0030100
0002020
0000300
```
Input — strips
```
a 1 5
b 2 7
c 3 5
```
Possible output
```
a DDDDSS
b SDDDSSDD
c SSDDSSDD
```
Result (strips narrowed for clarity): [image link](https://i.stack.imgur.com/3HCf4.png)
## Sample 3
Input — grid
```
0000000
0010120
0030000
0102000
0000000
0000310
0000000
```
Input — strips
```
a 1 3
b 1 6
c 2 7
d 3 6
```
Possible output
```
b DDDDSSDSSS
c SSSSDDDWWWWDDS
d DDSSSSSDD
a DDSASS
```
Result (strips narrowed for clarity): [image link](https://i.stack.imgur.com/T0O4t.png)
## Sample 4
Input — grid
```
000000
010000
000020
030000
020040
040100
000300
000000
```
Input — strips
```
a 1 11
b 2 8
c 3 6
d 4 9
```
Possible output
```
c SSSDDSSSD
d SSSSSDSSDDDWWW
b DDDDSSAAAASSD
a SDDDDDSSAASS
```
Result (strips narrowed for clarity): [image link](https://i.stack.imgur.com/4kF6x.png)
---
* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the shortest code in bytes wins.
* [The](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/) [linked](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) [rules](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* Please explain your code.
* Please link to Try It Online! or another online demo.
---
Samples credit: [Color Strips on Armor Games](https://armorgames.com/color-strips-game/18870)
]
|
[Question]
[
A [radiation-hardened quine](https://en.wikipedia.org/wiki/Quine_(computing)#Radiation-hardened) can take a hit and stay standing, but nobody ever said that the quine can't be a *wuss* about it.
For this challenge, you should write a quine that:
* If no characters are removed, prints its source code normally.
* Iff any one character is removed, prints the original program's source code, followed by a new line and then this text:
```
Owie! That hurt!
```
You should **only** print the original plus that.
[Standard quine rules](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine) apply for this challenge, and the shortest valid code in bytes wins. See also [Radiation Detector!](https://codegolf.stackexchange.com/q/154286/62402)
]
|
[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/175212/edit).
Closed 5 years ago.
[Improve this question](/posts/175212/edit)
Captchas aren't meant to be machine-readable, and that's terrible. It is time to end this obvious bout of unfounded hatred for machines just trying to let you know about great deals on ṗḧ@ṛḿ4ćëü*ẗ*1ċ**ä**ḷṡ ~~ƻđȺ~~ɏ.
**Note**: All captchas were made by using a library that has been modified so that it mostly generates images much easier than most real captchas. Don't expect code here to work well in the real world.
## Your task
Make a program that translates given captchas to their text.
[Default acceptable image I/O methods](https://codegolf.meta.stackexchange.com/questions/9093/default-acceptable-image-i-o-methods-for-image-related-challenges) apply for input.
Output must be the text contained in the captcha, but other than that [default acceptable general I/O methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply.
## Example
Input:

Output: `dlznuu`
## Rules
* Please don't just hardcode the images or image hashes or such. If anyone does this I'm going to generate another testcase folder and then everyone will be unhappy. (Hardcoding stuff like "this is how a letter looks" is allowed, but creativity is encouraged.)
* Don't rely on the filename or anything but the actual image data for anything other than validating your output.
* Your program must be below 50,000 bytes.
* No using Tesseract. Come on, you thought it was gonna be that easy?
## Test cases:
* All captchas have 6 letters in them.
* All captchas are 200 by 80 pixels.
* All characters are lowercase.
* All characters are in the range a-z, with no numbers or special characters.
* All captchas fit the regex `/^[a-z]{6}$/`.
* Every testcase is named `[correct_result].png`
[6 example images for starting out](https://gist.github.com/no-boot-device/cf0c4de9f85d98e9a15648ccf1e3f504).
[1000 images](https://b6.pm/captchas.tar.gz)
## Scoring:
Test your program on all 1000 images provided in the tar.gz. (the gist files are just example files)
Your program's score is `(amount_correct / 1000) * 100`%.
]
|
[Question]
[
# Input:
A maze containing the characters:
* `--` (horizontal wall);
* `|` (vertical wall);
* `+` (connection);
* (walking space);
* `I` (entrance);
* `U` (exit).
I.e. an input could look like this:
```
+--+--+--+--+--+--+--+--+--+--+
I | | |
+ +--+--+--+ + + + +--+ +
| | | | | |
+--+--+--+ +--+--+ + + +--+
| | | | |
+ +--+--+ + +--+--+ +--+ +
| | | | | |
+--+ + +--+--+ +--+--+ + +
| | | | | |
+ +--+--+--+ +--+--+ + + +
| | | | | |
+--+ + +--+--+ +--+--+--+--+
| | | | |
+ + +--+--+--+ +--+ + + +
| | | | | | | |
+--+--+ + +--+ + + +--+ +
| | | | | |
+ +--+--+--+ + + + + +--+
| | | | U
+--+--+--+--+--+--+--+--+--+--+
```
# Output:
The *most efficient* path you should walk to get from the entrance to the exit of the maze (through the maze), indicated by the characters indicating left, right, up and down (i.e. `>`; `<`; `^`; `v`).
**Challenge rules:**
* You can take the input in any reasonable format. String-array, single String with new-lines, 2D char-array, etc. are all possible input formats.
* The output can consist of any four distinct characters. I.e. `><^v`; `→←↑↓`; `⇒⇐⇑⇓`; `RLUD`; `0123`; `ABCD`; etc.).
* You are allowed to add spaces or trailing new-line to the output if preferred; this is optional.
* The steps are counted per square (see four `+`-symbols for the squares), and not per character.
* The maze can be of size 5x5 through 15x15, and will always be a square (so there won't be any test cases for 5x10 mazes).
* You can assume that every maze has one or more valid paths from start to finish, and you always output the shortest (see test cases 4 and 5).
* If there are multiple paths with the same length, you can choose which one to output (see test case 6).
* You cannot 'walk' outside the borders of the maze (see test cases 7 and 8).
**General rules:**
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
**Test cases:**
```
1. Input:
+--+--+--+--+--+--+--+--+--+--+
I | | |
+ +--+--+--+ + + + +--+ +
| | | | | |
+--+--+--+ +--+--+ + + +--+
| | | | |
+ +--+--+ + +--+--+ +--+ +
| | | | | |
+--+ + +--+--+ +--+--+ + +
| | | | | |
+ +--+--+--+ +--+--+ + + +
| | | | | |
+--+ + +--+--+ +--+--+--+--+
| | | | |
+ + +--+--+--+ +--+ + + +
| | | | | | | |
+--+--+ + +--+ + + +--+ +
| | | | | |
+ +--+--+--+ + + + + +--+
| | | | U
+--+--+--+--+--+--+--+--+--+--+
1. Output:
>v>>>vv<v>>v>v>>vvv>>>
2. Input:
+--+--+--+--+--+
I | | |
+ +--+--+ + +
| | | |
+ +--+ + + +
| | | | |
+ + +--+ + +
| | |
+--+ + +--+--+
| | U
+--+--+--+--+--+
2. Output:
>vvv>>v>>>
3. Input:
+--+--+--+--+--+
U | |
+ + +--+--+ +
| | | |
+--+--+ + +--+
| | |
+ +--+--+--+ +
| | | |
+ + + + +--+
| | I
+--+--+--+--+--+
3. Output:
<<<^<v<^^>>^<^<<
4. Input (test case with two valid paths):
+--+--+--+--+--+
U | |
+ + +--+--+ +
| | |
+--+--+ + +--+
| | |
+ +--+--+--+ +
| | | |
+ + + + +--+
| | I
+--+--+--+--+--+
4. Output:
<<^>^<^<<^<< (<<<^<v<^^>>^<^<< is less efficient, and therefore not a valid output)
5. Input (test case with two valid paths):
I
+--+--+--+--+--+--+--+--+--+--+ +--+--+--+--+
| | | | |
+ + + +--+--+--+ + +--+--+ +--+--+ + +
| | | | | | | |
+--+--+--+ +--+ + +--+--+--+--+ +--+--+--+
| | | | | | | | |
+ + + + + +--+ + + + +--+--+ +--+ +
| | | | | | | |
+ +--+--+--+ +--+--+ + +--+ +--+--+ +--+
| | | | | | | | |
+ +--+ + +--+ +--+--+ +--+--+ + +--+ +
| | | | | | |
+ + +--+--+--+--+ + +--+--+--+ +--+ +--+
| | | | | | | |
+--+--+--+ + +--+--+ +--+ + +--+ +--+ +
| | | | | | | |
+ +--+--+--+--+ + + +--+--+--+ + + + +
| | | | | | | | | |
+--+ + + + + + +--+--+ + + +--+ + +
| | | | | | | | | |
+--+ +--+--+ + + + +--+--+--+ + + + +
| | | | | | | | | |
+ +--+ +--+--+ + +--+--+ + +--+ + + +
| | | | | | | | | |
+--+--+--+ + + +--+ + +--+--+ +--+ + +
| | | | | | | |
+ + +--+--+--+--+ +--+--+ +--+--+ +--+ +
| | | | | |
+ + + +--+--+--+--+--+--+--+--+ +--+ +--+
| | | |
+--+--+--+--+--+--+--+--+--+ +--+--+--+--+--+
U
5. Output:
v<<<v<vv<<v<v>>^>>^^>vvv>>>v>vv<vv<<v<v<^<^^^^<vvvvv<^<v<<v>v>>>>>>>v (v<<<v<vv<<v<v>>^>>^^>vvv>>>v>vv<vv<<v<v<^<^^^^<vvvvv>v>>>^>>^>^^>vvv<v<v<<v is less efficient, and therefore not a valid output)
6. Input:
+--+--+--+--+--+
I |
+ + + + + +
| |
+ + + + + +
| |
+ + + + + +
| |
+ + + + + +
| U
+--+--+--+--+--+
6. Output:
>>v>v>v>v> or >v>v>v>v>> or >>>>>vvvv> or etc. (all are equally efficient, so all 10-length outputs are valid)
7. Input:
I U
+ + +--+--+--+
| | | |
+ +--+--+ + +
| | | |
+--+ + +--+ +
| | | |
+ +--+ + + +
| | |
+--+ +--+--+ +
| | |
+--+--+--+--+--+
7. Output:
vv>v>^>^<<^
8. Input:
+--+--+--+--+--+
| | |
+ +--+ +--+ +
I | | | |
+ + +--+ + +
U | | | |
+--+--+ + + +
| | | |
+ +--+--+--+ +
|
+--+--+--+--+--+
8. Output:
>v<
```
Mazes generated using [this tool](http://www.delorie.com/game-room/mazes/genmaze.cgi) (and in some cases slightly modified).
[Answer]
# [Perl 6](http://perl6.org/), ~~259~~ 295 bytes
```
{my \a=S:g/(.)$0+/{$0 x($/.comb+.5)*2/3}/;sub f (\c,\v,*@p) {with (c ne any v)&&a.lines».comb[+c[0];+c[1]] ->$_ {for (/\s/??10011221!!/I/??a~~/^\N*I|I\N*$/??2101!!1012!!'').comb X-1 {f [c Z+$^a,$^b],(|v,c),@p,chr 8592+$++}
take @p if /U/}}
[~] (gather f a~~/(\N+\n)*(.)*I/,[]).min(+*)[1,3...*]}
```
### How it works
1. ```
my \a = S:g/ (.) $0+ /{ $0 x ($/.chars + .5) * 2/3 }/;
```
This squeezes the maze so that the inside of each cell is 1x1 instead of 2x1 space characters:
```
+--+--+--+--+--+ +-+-+-+-+-+
I | | | I | | |
+ +--+--+ + + + +-+-+ + +
| | | | | | | |
+ +--+ + + + + +-+ + + +
| | | | | --> | | | | |
+ + +--+ + + + + +-+ + +
| | | | | |
+--+ + +--+--+ +-+ + +-+-+
| | U | | U
+--+--+--+--+--+ +-+-+-+-+-+
```
2. ```
sub f (\c,\v,*@p) {
with (c ne any v) && # If the coordinate wasn't visited yet
lines».comb[+c[0];+c[1]] -> $_ { # and a character exists there...
for ( # For each vector...
/\s/ ?? 10011221 !! # from a cell: (0,-1), (-1,0), (0,1), (1,0)
/I/ ?? a~~/^\N*I|I\N*$/
?? 2101 # from a top/bottom entrance: (1,0), (-1,0)
!! 1012 # from a left/right entrance: (0,-1), (0,1)
!! '' # otherwise: none
).comb X-1 {
f # Recurse with arguments:
[c Z+ $^a, $^b], # c plus the vector
(|v, c), # v with c appended
@p, chr 8592 + $++ # p with the correct Unicode arrow appended
}
take @p if /U/
}
}
```
This is the recursive path-finding function. It takes three parameters: The current coordinate `c=(y,x)`, the list of already visited coordinates `v`, and the path `p` taken so far (as a list of arrow characters).
If the character at the current coordinate is a space, it recurses to its four neighbors.
If the character at the current coordinate is a `I`, it recurses to the two neighbors that aren't "along the edge", to force solutions to go through the maze and not around it.
If the character at the current coordinate is a `U`, it calls `take` on the accumulated path string.
3. ```
[~] (gather f a ~~ /(\N+\n)*(.)*I/, []).min(+*)[1,3...*]
```
The recursive function is initially called with the coordinate of the letter `I`, which is found using a regex.
The `gather` keyword collects all values on which `take` was called inside the function, i.e. all valid non-cyclical paths through the maze.
The shortest path is chosen, every second arrow is dropped to account for the fact that two identical moves are required to get from one cell to the next, and the remaining arrows are concatenated to form the string that is returned from the lambda.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~338~~ ~~281~~ ~~275~~ ~~273~~ 261 bytes
```
¶U
¶&
+`·(\w.+)$
|$1
((.)+I.+¶.+¶(?<-2>.)+)·
$1v
+`((.)*)\+(.).*(¶(?<-2>.)*.)((\w)|·)·?
$1$4$.4$3$6
·v
-v
G`1
·U
&
{`\B·\d+.(\w+)
$1K$&
(\w+)·\d+.\B
$&$1r
(?<=\D\2.(\w+).+?¶.*\D(\d+)[·&])\B
$1v
)`\D(\d+).\B(?=.+¶.*\D\1·(\w+))
$&$2A
^.+\d·(\w+)
&$1A
M!`&\w+
I|&
```
[Try it online!](https://tio.run/##pVa7asMwFN3vXxSEkCwscBo6NTUJgRJKx0xViwPp0KVDKOlQfVe068fSazuQ2HpYTnCsyFdH0tG5R7J3nz9f35vj0R7WYA8URGUNU79ScAKaFMCY5GIlhT3UNysf88kTRrg1QIo9wmtAxpXAP5mxMySTnOFAXFuD4BLRZErklNyTB7BmD/kenqsCq2ug8FephTVqKyR2ERzBL4RCU2/DagGEkmIHOPxMLdWkBUpRIrFMLRmC@Js19J3XUGTGq1MU@7Jy1qwAgapo1ic4rweczOFDCrU9xQCnmMPrXUXxCVaaAgpjbrlWsUYQeR771ZhOAPS5s46NrFP5NUAN7VTnokvhItSvNkVLK8ZtfJsGVwcPP0clR6JeMczHR6UnT4dIINzn7YgUkyNVL/Cly5M5DykYo0ka9oLO0OxeyG0@CnWBmG/88nU1GmXhYb1geHd51buQKGHbp2VTe13kmjoUdzh5Fz7a@a1GwU3nNZGrXSx7EV6xhUDQw9dqFcnL6OyFNpfXUX5OEbXSmnTY46FjPJS5RMcktsXPgWA1xif5jasT3ytDHwID59J1V@BsSvgcqZlcO@t6GPIP "Retina – Try It Online")
---
**Notes**
* Due to significant whitespaces, all spaces (`0x20`) are replaced with interpunct (`·`) both in this answer and the TIO link. The program works fine if the spaces are restored.
* Uses `AvKr` for up, down, left, and right, respectively. Those can be replaced with any **letters** except `I`.
* ~~Takes about 40s on TIO for the 15×15 test case. Be patient.~~ Reworked the part for finding the shortest path once the path reached the exit. Turns out that was taking a lot of time.
* Could completely break on mazes that are 66 or more cells wide but can handle mazes of arbitrary height. A fix for arbitrary width takes +1 byte.
---
# Explanation
The program consists of 3 phases:
* A **construction phase** to convert the maze to a compact format that is easier to work with (detailed below).
* A **fill phase** to actually solve the maze using a flood fill algorithm.
* A **return phase** to return the shortest path at the exit.
---
# Format
Since the original maze format is quite unwieldy, the first part of the program converts it into a different format.
**Cells**
In the original format, each cell is represented as a 2×3 region:
```
+ <top wall> <top wall>
<left wall> <data/space> <space>
```
Since the right column contains no information, the program identifies cells as any 2×2 region with a `+` at the top-left.
This leaves us with 3 kinds of cells:
* **I Cells**: Cells that are properly inside the maze.
* **R Cells**: Cells that are to the right of the maze. These are created by the padding used to house the entrance or exit. For example, the exit `U` in test case 1 is in an R-Cell.
* **B Cells**: Cells that are below the maze. Like R-Cells, these are created by padding.
In the new format, cells are represented as a variable-length string:
```
<left wall> <column number> <top wall/exit marker> <path>
```
The left and top wall are copied from the original format. The column number is based on the horizontal position of the cell and is used for alignment (identifying cells directly on top of/beneath each other). Path is an alphabetical string used during the fill phase to save the shortest path to reach that cell. Path and exit marker will be further explained.
**Half-cells**
Although most of the maze are cells, there are regions of the maze that are not cells:
* **R Half-cells**: If there is no right padding, the `+`s along the right wall does not form cells since they are on the last column.
* **L Half-cells**: If there is left padding, cells cannot form there since there are no `+` to the left of them. For example, the entrance `I` in test case 1 is in an L Half-cell.
Technically, there are **T half-cells** above the maze (when there is top padding) and **B half-cells** (along the bottom wall when there is no bottom padding) but they are not represented in the new format.
The top row of a half-cell would be removed as part of constructing full cells in the same row, so half-cells are represented in the new format as
```
<wall/exit marker>? <path>
```
An R Half-cells is just `|`. An L Half-cells has just `I` as the path, just the exit marker and an empty path, or just an empty wall.
**Entrances and exits**
If the entrance is to the left, right or bottom of the maze, then the entrance marker `I` would naturally be included in the (half-)cell as the path, which can be removed when returning the final path.
If the entrance is above the maze, the first (downward) step is taken during the construction phase since T half-cells are removed during construction. This keeps a workable path in a full cell. The top wall is closed afterwards.
If the exit is to the left, right or bottom of the maze, then `U` would naturally be included in the (half-)cell. To avoid being mistaken as a path, the non-alphanum exit marker `&` is used instead of `U`. The exit marker is embedded into a cell or half-cell (as specified above).
If the exit is above the maze, then it would be the only hole that can go above the top row of cells (since the one for the entrance, if present, would be closed already). Any path reaching that hole can exit the maze by taking an upward step.
Lastly, any B Cell containing the entrance or exit must close its left wall to prevent "solving" the maze by walking along the B Cells. Entrances and exits in R Cells or L Half-cells need no further processing since the flood fill algorithm does not permit vertical movements to/from them.
**Example**
As an example, the first test case
```
·+--+--+--+--+--+--+--+--+--+--+·
I···············|·····|········|·
·+··+--+--+--+··+··+··+··+--+··+·
·|···········|·····|··|··|·····|·
·+--+--+--+··+--+--+··+··+··+--+·
·|···········|·····|·····|·····|·
·+··+--+--+··+··+--+--+··+--+··+·
·|·····|·····|·····|·····|·····|·
·+--+··+··+--+--+··+--+--+··+··+·
·|·····|········|········|··|··|·
·+··+--+--+--+··+--+--+··+··+··+·
·|·····|·····|·····|········|··|·
·+--+··+··+--+--+··+--+--+--+--+·
·|··|··|·················|·····|·
·+··+··+--+--+--+··+--+··+··+··+·
·|·····|········|··|··|··|··|··|·
·+--+--+··+··+--+··+··+··+--+··+·
·|········|·····|·····|··|·····|·
·+··+--+--+--+··+··+··+··+··+--+·
·|···········|·····|··|·········U
·+--+--+--+--+--+--+--+--+--+--+·
```
is
```
I·3-·6-·9-·12-·15-|18-·21-|24-·27-·30-|33·
·|3··6-·9-·12-|15··18·|21·|24·|27-·30·|33·
·|3-·6-·9-·12·|15-·18-|21··24·|27··30-|33·
·|3··6-|9-·12·|15··18-|21-·24·|27-·30·|33·
·|3-·6·|9··12-·15-|18··21-·24-|27·|30·|33·
·|3··6-|9-·12-|15··18-|21-·24··27·|30·|33·
·|3-|6·|9··12-·15-·18··21-·24-|27-·30-|33·
·|3··6·|9-·12-·15-|18·|21-|24·|27·|30·|33·
·|3-·6-·9·|12··15-|18··21·|24·|27-·30·|33·
·|3··6-·9-·12-|15··18·|21·|24··27··30-·33&
```
in the new format. You can convert other mazes [here](https://tio.run/##nVTLDoIwELzvdzSmpWkTlHgycjR8ADcOePDgxYMxeOl30Xt/DJcYeS6FGl6byWQnwww8b6/749o0rs7B1TuQpbO8eGspGBgWA@dayExLV7cXT09qf0ZEOAssrpDeEiJRSHzoiPeUSAuOi4RxFskpslnCdMIO7AjOVqAquJQxjjnsUN5KpXwn6mXO@g5Djh2ASrIdhyt/UH/rYSDW0EJmDsJMh5T8@tosRI0TW6PdA23SlAmX8khM7MFqIgRg/GEt5Bboaqy37qor4ELe2woJ0@TJgMLe38IN6DoEVd2s9D3wu/qn7gQthw0/ig8).
---
# Construction phase
The construction phase makes up the first 13 lines of the program.
```
¶U
¶&
```
Converts exit in L Half-cell to exit marker
```
+`·(\w.+)$
|$1
```
Adds walls to the left of entrance and exit in B Cells
```
((.)+I.+¶.+¶(?<-2>.)+)·
$1v
```
Takes the first step if entrance is above the maze
```
+`((.)*)\+(.).*(¶(?<-2>.)*.)((\w)|·)·?
$1$4$.4$3$6
```
Performs the actual conversion
```
·v
-v
```
Closes the top-entrance hole
```
G`1
```
Keeps only lines with a `1`. Since mazes are at least 5 cells wide and column numbers occurs at increments of 3, a line with new-format cells must have a contain a column number between 10 and 19.
```
·U
&
```
Converts exit in R Cell or B Cell to exit marker
---
# Fill phase
The fill phase makes up the next 8 lines of the program. It uses a flood fill algorithm to fill all cells with the shortest path to reach there from the entrance.
```
{`
```
Puts the whole fill phase on a loop to fill the whole maze.
```
\B·\d+.(\w+)
$1K$&
```
Each cell able to move left does so. A cell is able to move left if
1. it has a non-empty path
2. it has an empty left wall; and
3. the cell or L half-cell to its left has an empty path
```
(\w+)·\d+.\B
$&$1r
```
Then, each cell able to move right does so. A cell is able to move right if
1. it has a non-empty path
2. the cell to its right has an empty left wall; and
3. the cell to its right has an empty path
```
(?<=\D\2.(\w+).+?¶.*\D(\d+)[·&])\B
$1v
```
Then, each cell able to move down does so. A cell is able to move down if
1. it has a non-empty path
2. it has at least one cell or half-cell to its right (i.e. it is not an R Cell)
3. the cell below it (i.e. the cell on the next line with the same column number) has an empty top wall or has the exit marker; and
4. the cell below it has an empty path
Note that L Half-cells cannot move down since they don't have column numbers.
```
\D(\d+).\B(?=.+¶.*\D\1·(\w+))
$&$2A
```
Then, each cell able to move up does so. A cell is able to move up if
1. it has a non-empty path
2. it has an empty top wall
3. the cell above it has at least one cell or half-cell to its right; and
4. the cell above it has an empty path
---
# Return phase
The return phase makes up the last 5 lines of the program. This phase searches for and returns the path filled into the exit cell.
The pattern of the path at the exit depends on where the exit is:
1. If the exit is in an L Half-cell, then that half-cell would be `& <path>`
2. If the exit is in an R Cell or B Cell, then that cell would be `<left wall> <column number> & <path>`
3. If the exit is in a T Half-cell, then as noted above, the the I Cell leading to the exit would be `<left wall> <column number> · <path>` and on the top row.
```
^.+\d·(\w+)
&$1A
```
Finds a cell on the top line with an empty top wall and a non-empty path. This takes care of the last case by adding the last step and the exit marker.
```
M!`&\w+
```
Matches and returns a non-empty path following an exit marker.
```
I|&
```
Removes the exit marker and the `I` prefix of the path.
[Answer]
# Python 2: 302 bytes
```
from re import*
r=lambda x:[''.join(_)for _ in zip(*x)][::-1]
z=',l)for l in s]'
def f(s,b=1,o=0,n=0):
exec("s=[sub('(..).(?!$)',r'\\1'%s;"%z+"s=r([sub(' I ','+I+'%s);"%z*4)*b+"t=[sub('I ','@@I'"+z
if'I U'in`s`or n>3:return`o%4`+n/4*`s`
return min(`o%4`+f(t,0,o,4*(t==s)),f(r(s),0,o+1,n+1),key=len)
```
Takes input as an array of strings all with the same length. Prints `0` for right, `1` for down, `2` for left, and `3` for up.
### Explanation
I took a different approach than the other answers. General idea: recursively search by finding the shortest path between going straight forward and rotating the board 90 degrees.
```
from re import*
r=lambda x:[''.join(_)for _ in zip(*x)][::-1] #Rotates the board counterclockwise
z=',l)for l in s]' #Suffix for hacky exec golfing
def f(s,b=1,o=0,n=0): #b is 1 on initial call, 0 on every recursion
#o is orientation
#n is number of rotations
exec("s=[sub('(..).(?!$)',r'\\1'%s;"%z #Squeeze the maze
+"s=r([sub(' I ','+I+'%s);"%z*4) #Add walls around the I to keep it in the maze
*b #Only if b is 1
+"t=[sub('I ','@@I'"+z #Attempt to move right
if'I U'in`s`or n>3:return`o%4`+n/4*`s` #If the I is next to the U, return the orientation
#If there were 4 rotations, return a long string
return min( #Return the path with the shortest length:
`o%4`+f(t,0,o,4*(t==s)), #Moving forward if possible
f(r(s),0,o+1,n+1), #Rotating the board
key=len)
```
[Try it online!](https://tio.run/##zVdRb5swEH6/X3GLVtkObtZseWJi6ys/IE9p1DQraGwJREClNOK/Z5CkAZ/P0KdqyIqMbb7cfXf@fN69lr@z9OvxGOfZFvMIk@0uy8sx5MHmabt@fsK9vxBi8idLUvmo4izHR0xSPCQ7Od6r5cL3b6dLOARCb06zm2a2WAp4jmKMZaHXwVRnwZ1OgzvlA0b76JccFcGieFlLIScTNZE/P31WQufi4WEqborvo5uDV6/I5XkNhii08EKvnlPN5HimxmtvVF4wQmzm7@9DMfIOgElcj8xFkq6KVW1P@uObn0flS56uspvZyku/zMb1DOB5ELe1X@eZWJb6Tmd6NpZlEBRK6VjmslDNoDfVqTdV@m/0GmyiVB3LqChrJ0AIAejd3vY1hNpE46k6v6dOjYEdGMS2XV6hXd4FqNo@mAAE6WQHj4EGBvm0i9e1o@rDYL9urQGbgLZT8XxQYtx2YIvhsuMtLgaDXIAADQCDCbcvZgOL0J7YVlZ4h/KjP7bt4Hw4T@tkXkz9pQY@rc95bJHsii4XTsJbZVgKaFHEMMOE1YoB5@ywd3Pkt6XhIBhGoyPAvN00hDyWK7Ktd@FHeIf/sXf9D1FbGEp78@@A2sO9tukNhjsu5bwOQoW8@PEKALzwuMyHypIg@w@66IyQIHXoOg6VW7IZD6BPwsnIxXa3mDPMEEJcjFPbXbwbU8ATzR4ENGcGKSJRZQ5ZtHjH3oPbiDnwhrvOD7AOG@yJ89l2kjZ8tUHQ7by0ybmis2VQn@3IFEROZlwlDtkBUDmOU54x4Bl3Rdi5m9hXV0ayHYqObkWzlaBfJpl873nsfB@U3wa9D3JujbyrakF6ptEUBpufj171nqolNBmwsoJmVVcNHDsSOK0ke57fGV29JFnIr@i2gbDZdTXYwhhSabFLyFPdQ9eQXWrdJSq7nLGjZdt8cWkJ0NyEi@YmvH3ayetFej8pdpuklOIhFUqfrpDK3@VJWjY3ZXX8Bw)
[Answer]
# JavaScript (ES6), 356 bytes
```
a=>(a=a.map(s=>s.filter((_,i)=>!i|i%3)),g=([x,y])=>a[y]&&a[y][x],o=[],c=([x,y],m="",v=[])=>[[0,1],[1,0],[0,-1],[-1,0]].map(([j,k],i)=>(p=[x+j,y+k],!m&(!y|y>a[l="length"]-2)==i%2|v.includes(""+p)||(g(p)<"!"?c(p,m+"v>^<"[i],[...v,""+p]):g(p)=="U"?o.push(m.replace(/(.)\1/g,"$1")):0))),a.map((h,i)=>h.map((k,j)=>k=="I"&&c([j,i]))),o.sort((a,b)=>a[l]-b[l])[0])
```
Takes input as a 2D array of characters. Each line must be left-padded by one space and have no trailing space, no matter where the start/end points are.
Uses [smls's idea](https://codegolf.stackexchange.com/a/109555/69583) of squishing the maze to make each cell 1x1 and removing repeated arrows from the output.
## Ungolfed and Explained
```
a=>(
a=a.map(s=>s.filter((_,i)=>!i|i%3)), // squish the maze to 1x1 cells
g=([x,y])=>a[y]&&a[y][x], // helper func to get maze value
o=[], // resulting movesets
c=([x,y], m="", v=[]) => // recursive func to search
// takes current point, moves, and visited spots
[[0,1],[1,0],[0,-1],[-1,0]].map(([j,k],i)=>(// for each direction
p=[x+j,y+k],
!m & (!y | y>a[l="length"]-2) == i%2 | // if first move, prevent moving out of maze
v.includes(""+p) || ( // also prevent if already visited
g(p)<"!" ? // is this a space?
c(p, m+"v>^<"[i], [...v,""+p]) // check this spot recursively
: g(p)=="U" ? // if this the end?
o.push( // add moves to moveset
m.replace(/(.)\1/g,"$1")) // with double arrows removed
: 0
)
)),
a.map((h,i)=>h.map((k,j)=> // find the starting "I" and
k=="I" && c([j,i]) // begin recursion at that point
)),
o.sort((a,b)=>a[l]-b[l])[0] // get shortest path
)
```
## Test Snippet
```
f=
a=>(a=a.map(s=>s.filter((_,i)=>!i|i%3)),g=([x,y])=>a[y]&&a[y][x],o=[],c=([x,y],m="",v=[])=>[[0,1],[1,0],[0,-1],[-1,0]].map(([j,k],i)=>(p=[x+j,y+k],!m&(!y|y>a[l="length"]-2)==i%2|v.includes(""+p)||(g(p)<"!"?c(p,m+"v>^<"[i],[...v,""+p]):g(p)=="U"?o.push(m.replace(/(.)\1/g,"$1")):0))),a.map((h,i)=>h.map((k,j)=>k=="I"&&c([j,i]))),o.sort((a,b)=>a[l]-b[l])[0])
let tests = [" +--+--+--+--+--+--+--+--+--+--+\nI | | |\n + +--+--+--+ + + + +--+ +\n | | | | | |\n +--+--+--+ +--+--+ + + +--+\n | | | | |\n + +--+--+ + +--+--+ +--+ +\n | | | | | |\n +--+ + +--+--+ +--+--+ + +\n | | | | | |\n + +--+--+--+ +--+--+ + + +\n | | | | | |\n +--+ + +--+--+ +--+--+--+--+\n | | | | |\n + + +--+--+--+ +--+ + + +\n | | | | | | | |\n +--+--+ + +--+ + + +--+ +\n | | | | | |\n + +--+--+--+ + + + + +--+\n | | | | U\n +--+--+--+--+--+--+--+--+--+--+"," +--+--+--+--+--+\nI | | |\n + +--+--+ + +\n | | | |\n + +--+ + + +\n | | | | |\n + + +--+ + +\n | | |\n +--+ + +--+--+\n | | U\n +--+--+--+--+--+"," +--+--+--+--+--+\nU | |\n + + +--+--+ +\n | | | |\n +--+--+ + +--+\n | | |\n + +--+--+--+ +\n | | | |\n + + + + +--+\n | | I\n +--+--+--+--+--+"," +--+--+--+--+--+\nU | |\n + + +--+--+ +\n | | |\n +--+--+ + +--+\n | | |\n + +--+--+--+ +\n | | | |\n + + + + +--+\n | | I\n +--+--+--+--+--+"," I\n +--+--+--+--+--+--+--+--+--+--+ +--+--+--+--+\n | | | | |\n + + + +--+--+--+ + +--+--+ +--+--+ + +\n | | | | | | | |\n +--+--+--+ +--+ + +--+--+--+--+ +--+--+--+\n | | | | | | | | |\n + + + + + +--+ + + + +--+--+ +--+ +\n | | | | | | | |\n + +--+--+--+ +--+--+ + +--+ +--+--+ +--+\n | | | | | | | | |\n + +--+ + +--+ +--+--+ +--+--+ + +--+ +\n | | | | | | |\n + + +--+--+--+--+ + +--+--+--+ +--+ +--+\n | | | | | | | |\n +--+--+--+ + +--+--+ +--+ + +--+ +--+ +\n | | | | | | | |\n + +--+--+--+--+ + + +--+--+--+ + + + +\n | | | | | | | | | |\n +--+ + + + + + +--+--+ + + +--+ + +\n | | | | | | | | | |\n +--+ +--+--+ + + + +--+--+--+ + + + +\n | | | | | | | | | |\n + +--+ +--+--+ + +--+--+ + +--+ + + +\n | | | | | | | | | |\n +--+--+--+ + + +--+ + +--+--+ +--+ + +\n | | | | | | | |\n + + +--+--+--+--+ +--+--+ +--+--+ +--+ +\n | | | | | |\n + + + +--+--+--+--+--+--+--+--+ +--+ +--+\n | | | |\n +--+--+--+--+--+--+--+--+--+ +--+--+--+--+--+\n U"," +--+--+--+--+--+\nI |\n + + + + + +\n | |\n + + + + + +\n | |\n + + + + + +\n | |\n + + + + + +\n | U\n +--+--+--+--+--+"," I U\n + + +--+--+--+\n | | | |\n + +--+--+ + +\n | | | |\n +--+ + +--+ +\n | | | |\n + +--+ + + +\n | | |\n +--+ +--+--+ +\n | | |\n +--+--+--+--+--+"," +--+--+--+--+--+\n | | |\n + +--+ +--+ +\nI | | | |\n + + +--+ + +\nU | | | |\n +--+--+ + + +\n | | | |\n + +--+--+--+ +\n | \n +--+--+--+--+--+"];
S.innerHTML="<option>Tests"+Array(tests.length).fill().map((_,i)=>"<option>"+(i+1)).join``;
```
```
<select id=S oninput="I.value=S.selectedIndex?tests[S.value-1]:''"></select><br>
<textarea id=I rows=20 cols=50></textarea><br><button onclick="O.innerHTML=f(I.value.split`\n`.map(x=>[...x]))">Run</button>
<pre id=O>
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 416 bytes
```
T` `+`^.*| ?¶.|.*$
I
#
{+` (\w)
d$1
+`(\w)
$1a
+`(¶(.)*) (.*¶(?<-2>.)*(?(2)(?!))\w)
$1s$3
}+m`(^(.)*\w.*¶(?<-2>.)*(?(2)(?!)))
$1w
^
w¶
w((.|¶)*(¶(.)*#.*¶(?<-4>.)*(?(4)(?!))(s)|#(d)|(a)#))
$4$5$6¶$1
{`^(.*d)(¶(.|¶)*)#(\w)
$1$4$2 #
^(.*a)(¶(.|¶)*)(\w)#
$1$4$2#
^(.*s)(¶(.|¶)*¶(.)*)#(.*¶(?<-4>.)*(?(4)(?!)))(\w)
$1$6$2 $5#
}`^(.*w)(¶(.|¶)*¶(.)*)(\w)(.*¶(?<-4>.)*(?(4)(?!)))#
$1$5$2#$6
s`U.*
(a|d)\1\1?
$1
ss
s
ww
w
```
[Try it online!](https://tio.run/##hZK/bsMgEMb3e4qrYDhsBclpkqmq5@zNZkVYcocO7VAqMYS8lh/AL@YCcWSI/8RC1uHv7sfnO34//75@6r7/UKhydZaZxbJrpZUZhyMwuOQKqTICGl5ArnyIwIvax11LUmQCSWYuLN8223e3p5K2gsoXIXwZLzR/hWv@rejssyuzkBywBs5guhYMkbRd6/TbGexetBuKdrci0sIyaoSlWjDhTtvxPT90rfN6Ue68rBGBEFiC0c2Ry9oiA6/Xse5lNugMg64jffhdRgtmxB1/cHi@Z3ANFswU4RMXKcHB3jngBwStTjIDoNo2oiqqonQiaA0ajAHT95hvNmsL4YjpY6N3CABzjDCI4xq2MKbHADvGkAIeSMHHPAMTxkNpzIt92DXGbPXoBqYNGAM734/Hxiz7wJGx5OM@l6SDcwMCTABJJ5b/JV0waejKbO1kvM/ux/psx48neHpP/wE "Retina – Try It Online") Had I seen this question when it was originally posted, this is probably the answer I would have given, so I'm posting it anyway, even though there's a much better answer in Retina. Explanation:
```
T` `+`^.*| ?¶.|.*$
```
Fill in the border. This avoids walking around the outside of the maze (e.g. for test case 7).
```
I
#
```
Place a non-alphabetic marker at the entrance.
```
{+` (\w)
d$1
+`(\w)
$1a
+`(¶(.)*) (.*¶(?<-2>.)*(?(2)(?!))\w)
$1s$3
}+m`(^(.)*\w.*¶(?<-2>.)*(?(2)(?!)))
$1w
```
Flood fill from the exit to the entrance. At each step, use a letter to indicate the best direction to go (wasd - this might be familiar to gamers; I had also considered hjkl but I found it too confusing). Additionally, prefer to repeat the same direction; this avoids going left/right in between two vertically adjacent cells.
```
^
w¶
```
Assume the first step is down.
```
w((.|¶)*(¶(.)*#.*¶(?<-4>.)*(?(4)(?!))(s)|#(d)|(a)#))
$4$5$6¶$1
```
But if there's a letter above, left or right of the entrance, change that to the first step.
```
{`^(.*d)(¶(.|¶)*)#(\w)
$1$4$2 #
^(.*a)(¶(.|¶)*)(\w)#
$1$4$2#
^(.*s)(¶(.|¶)*¶(.)*)#(.*¶(?<-4>.)*(?(4)(?!)))(\w)
$1$6$2 $5#
}`^(.*w)(¶(.|¶)*¶(.)*)(\w)(.*¶(?<-4>.)*(?(4)(?!)))#
$1$5$2#$6
```
Move the marker in the direction of the last move, reading the direction of the next move from the square that the marker is moving to, and add that to the list of directions. This repeats until the `U` is reached.
```
s`U.*
```
Delete everything after the directions as it's not needed any more.
```
(a|d)\1\1?
$1
ss
s
ww
w
```
The original grid is on a 3×2 layout. While moving vertically if we zig-zag horizontally the flood fill will optimise the movement and only move 3n-1 characters horizontally, so when dividing by three, we need to round up. Vertically we just divide by 2.
I also investigated a true square grid solution i.e where the character matrix is itself square rather than being a 3×2 layout with an optional border. While probably nonconforming to the question, the ability to transpose reduced the byte count to 350: [Try it online!](https://tio.run/##jZLBTsMwDIbvfgpPCZKdaZGGBidGzztxYTdUpVI5cIADRcqB8Fp9gL5YSbONJF3XUUWVE9tfftv5fP16@6j6/tmgWZpSK4dF12qnlYQdCHg3VCxKJq1Zg1zDt0F6sQy1twcD/WEFT0Ia79Y3Bg7uJnFb@En8JdiuBUukXdeyoq4lzUpo5Y3iYbV59DsqaMP@XmZq2Amq2VHFghnkRt7J@64NSkrSquZACCwWdbhcrn3YLdYChogqjRj8lThGiAqDcn/v1tes@CTRZzUZt0m5zYFrx1z7x7V4KHkMXhjta9vuue/x2ge4XK3mFsJulOKSfzA8AxMMYlzHLcTwFOCiDTlgRAo6phmYMUapKS/V4eYYk9lRDZw3IBpuuh/jxlzWgZFxScdpLlkHpwYEmAGyTlyuJV9w1tCZ2bqz8V57H/OzjYf7f7zTq2/9Fw "Retina – Try It Online")
] |
[Question]
[
Simply put, your goal is to create a complete program that [modifies its own source code](https://en.wikipedia.org/wiki/Self-modifying_code) until every character of the source is different than what it started as.
Please include the beginning source as well as the ending source in your post, as well as a description. E.g. Describe what (else) your program does, the language you used, your strategy, etc.
### Rules
* Your program must halt sometime after the modification is complete.
* It must actually modify its own, currently running source code (not necessarily the file you passed to the interpreter, it modifies its instructions), not print a new program or write a new file.
* Standard loopholes are disallowed.
* Shortest program wins.
* If your language can modify its own file and execute a new compiler process, but cannot modify its own (currently running) source code, you may write such a program instead at a +20% bytes penalty, rounded up. Real self-modifying languages should have an advantage.
**Edit**: If your program halts with errors, please specify it as such (and maybe say what the errors are.)
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), 2 bytes
```
>@
```
The `>` rotates the source so that it becomes
```
@>
```
The instruction pointer is now in a dead end and turns around to hit the `@` which terminates the program.
Of course, `<@` would also work.
[Answer]
# [///](http://esolangs.org/wiki////), 1 byte
```
/
```
The program finds a `/` (the start of a pattern-replacement group), and removes it in preparation to make the replacement. Then it reaches EOF, so it gives up and halts.
[Answer]
# Python 2, 225 bytes
```
import sys
from ctypes import*
c=sys._getframe().f_code.co_code
i=c_int
p=POINTER
class S(Structure):_fields_=zip("r"*9+"v",(i,c_void_p,i,c_char_p,i,p(i),i,c_long,i,c_char*len(c)))
cast(id(c),p(S)).contents.v=`len([])`*len(c)
```
The ending source code is a string of `"0"`s whose length is equal to the number of bytes in the original compiled code object.
The code finds the running code object, `sys._getframe().f_code.co_code`, and creates a structure which represents python string objects. It then gets the memory that the code actually takes and replaces it with `"0"*len(c)`.
When ran, the program exits with the following traceback:
```
XXX lineno: 7, opcode: 49
Traceback (most recent call last):
File "main.py", line 7, in <module>
cast(id(c),p(S)).contents.v=`1+1`*len(c)
SystemError: unknown opcode
```
This shows that the overwrite was successful and the program dies because `0` isn't a valid opcode.
I'm surprised that this is even possible in python, frame objects are read-only, I can't create new ones. The only complicated thing this does is change an immutable object (a string).
[Answer]
# [evil](http://esolangs.org/wiki/Evil), 1 byte
```
q
```
evil has several memory stores - one is the source code itself and one is the *wheel* which is a circular queue which is initialised to a single zero. `q` swaps the source code and the wheel, so it replaces the source with a null-byte. However, only lower-case letters are actual operators in evil, so that character is simply a no-op and the program terminates.
[Answer]
# [MSM](http://esolangs.org/wiki/MSM), 8 bytes
```
'.qp.;.;
```
Transforms the source code to `pqpqpqpq`
MSM operates on a list of strings. Commands are taken from the left and they treat the right side as a stack. MSM always works on it's own source.
Execution trace:
```
'.qp.;.; upon start the source is implicitly split into a
list of single char strings
' . q p . ; . ; ' takes the next element and pushes it on the stack
q p . ; . ; . q is not a command so it's pushed
p . ; . ; . q same for p
. ; . ; . q p . concats the top and next to top element
; . ; . pq ; duplicates the top element
. ; . pq pq concat
; . pqpq dup
. pqpq pqpq concat
pqpqpqpq MSM stops when there's only one element left
```
[Answer]
# Malbolge, 1 or 2 bytes.
```
D
```
The Malbolge language "encrypts" each instruction after executing it, so this letter (Malbolge NOP) will become an `!` (which is also a nop), and then terminate. For some reason, the Malbolge interpreter I use requires two bytes to run, giving `DC` (both of which are nops) becoming `!U` (both of which are also nops)
Edit: The initial state of Malbolge memory depends on the last two characters in the code, so it is not well defined for one character programs. (Though this code doesn't care about the initial state of memory)
[Answer]
**x86 asm** - 6 bytes
not sure if "until every character of the source is different than what it started as" refers to each byte, each nemonic, or general modification. if I'm invalid I can change the xor to a rep xor so each bit changes values but was hoping not to do that to save 6 more bytes to stay at least a little bit comparable to these specialty golf languages.
All this does is change a c2 to a c3 retn by getting live address of eip and xoring 5 bytes in front.
```
58 | pop eax ; store addr of eip in eax
83 70 05 01 | xor dword ptr ds:[eax + 5], 1 ; c2 ^ 1 = c3 = RETN
c2 | retn ; leave
```
[Answer]
# [SMBF](https://esolangs.org/wiki/Self-modifying_Brainfuck), 92 bytes
Can be golfed, and I'll probably work more on it later.
```
>>+>>+>>+>>+>>+>>+[<-[>+<---]>+++++<<]>>>>>--[>-<++++++]>--->>++>+++++[>------<-]>->>++[<<]<
```
### Explanation
The program generates the following commands at the end of its tape to erase itself, so it has to generate the following values on the tape:
```
[[-]<] ASCII: 91 91 45 93 60 93
```
Make a bunch of `91`s, with nulls (shown as `_`) between to use for temp values.
```
>>+>>+>>+>>+>>+>>+[<-[>+<---]>+++++<<]
code__91_91_91_91_91_91_
^
```
Adjust the values by the differences
```
>>>>>--[>-<++++++]>--- Sub 46
>>++ Add 2
>+++++[>------<-]>- Sub 31
>>++ Add 2
[<<]< Shift left to the code
code__[_[_-_]_<_]_ Zero out the code
^
```
The tape following execution will be all zeros, with the exception of the generated code `[_[_-_]_<_]`.
### Note:
This program made me realize that my Python interpreter for SMBF has a bug or two, ~~and I haven't figured out a fix yet.~~ It's fixed now.
[Answer]
# Emacs Lisp 22 bytes
```
(defun a()(defun a()))
```
Run from REPL:
```
ELISP> (defun a()(defun a()))
a
ELISP> (symbol-function 'a)
(lambda nil
(defun a nil))
ELISP> (a)
a
ELISP> (symbol-function 'a)
(lambda nil nil)
```
Function now evaluates to `nil`.
Alternately (unbind itself) **30 bytes**
```
(defun a()(fmakunbound 'a)(a))
```
Evaluate and errors as `void-function`. Function existed prior to being run.
[Answer]
### [Redcode](https://en.wikipedia.org/wiki/Core_War), 7 bytes, 1 instruction (Just an example. Not competing)
This is a trivial example.
Moves the next memory location onto itself, then halts (because the entire memory is initialized to `DAT 0 0`, which halts the program when executed.)
```
MOV 1 0
```
[Answer]
# Powershell 65 bytes
```
function a{si -pat:function:a -va:([scriptblock]::create($null))}
```
Define a function that rewrites itself to null.
Evaluate it once and it eliminates itself.
Alternately (deletes itself from memory) **36 bytes**
```
function a{remove-item function:a;a}
```
Calling it first removes it then attempts to evaluate recursively. Erroring out as an unknown command.
[Answer]
## MIXAL, 6 bytes (counting 2 tabs)
```
STZ 0
```
The program starts at memory location 0 and then writes 0 to memory location 0, thus erasing itself. The machine halts automatically.
This is the assembly language for Donald Knuth's hypothetical MIX computer, which may be assembled and run using GNU MIX development kit (<https://www.gnu.org/software/mdk/>).
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~40~~ ~~34~~ 30 bytes
```
0&00a6*0&1+:&060"c"l=?!.~~r >p
```
[Try it here!](http://fishlanguage.com/playground/kxTYEZwyRnnyW4rcj)
Explanation:
```
0& Adds 0 to the registry
00a6* Adds "0,0,<" to the stack; coords followed by a character
------------loop start (for clarity)
0 0 added to stack
&1+:& Registry retrieved, increased by 1, duplicated, one put back in registry
0 ASCII character 0 added to stack (just a 0 but will be converted to that character when inserted in the code)
60 6 and 0 added to stack
"c" The number 99 added to stack (length of code + 1 * 3)
l=? Code length added to stack, checks if it is equal to 111
!. If false, pointer jumps back to character (9,0) (loop start position)
~~r >p If true, removes the 0 and 9, reverses stack, then loops the p command setting
all the characters to a "<" character and the 2nd character to a " "
```
Basically this puts a bunch of 3 character blocks in the stack like so: (ypos, xpos, ASCII character) which gets reversed at the end so the final 'p' command reads (character, xpos, ypos) and sets that position in the code to that character. The first character is manually set as '<', so that the code ends up being '>p<' at the end to loop the command. Then every other character is overwritten as a ' ' including the p character. The ' ' is actually "ASCII CHAR 0" which is NOT a NOP and will give an error when read.
Also there have to be an odd(?) number of characters before the 'p' command or else it wont be looped back into a last time and overwritten.
[Answer]
# Batch, 11 bytes
```
@echo>%0&&*
```
Modifies source code to `ECHO is on.`
```
@ - don't echo the command.
echo - print ECHO is on.
>%0 - write to own file.
&&* - execute * command after the above is done, * doesn't exist so program halts.
```
The `@` is there so the command isn't echoed, but mostly so the two `echo`s don't line up.
[Answer]
# Jolf, 4 bytes, noncompeting
```
₯S₯C
```
This `₯S`ets the `₯C`ode element's value to the input, `undefined` as none is given. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=4oKvU-KCr0M)
[Answer]
# (Filesystem) Befunge 98, 46 bytes
```
ff*:1100'aof0'ai
21f0'ai@
```
Note that this program creates and manipulates a file named `a`.
How it works:
1. The code creates a file named `a` containing the entire code (out to 256 characters in each dimension) shifted one space upward and two the left.
2. This program then reads the file named `a` as one line, replacing the entire first line with the contents of the `a` file.
3. The second line, which has been copied in front of the IP, is executed
4. Which reads the `a` file into the second line shifted two places to the right.
As a side effect, the ending source code isn't even valid Befunge! (because it contains newlines as data in a single line)
[Answer]
## Python 2, 238 bytes + 20% = 285.6
```
# coding: utf-8
import codecs
with codecs.open(__file__,'r') as f:
t = f.read()
n="utf-8" if t.startswith("# coding: ascii") else "ascii"
with codecs.open(__file__,'w', encoding=n) as f:
f.write(t[0]+" coding: "+n+t[t.find("\n"):])
```
Basically, this toggles the current file encoding of the python source between `ascii` and `utf-8`, thus essentially changing every character of the source!
] |
[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/95742/edit).
Closed 7 years ago.
[Improve this question](/posts/95742/edit)
### Introduction
To draw a Fibonacci series of square, you start by drawing a one-unit square:
```
_
|_|
```
Then another one to the left:
```
_ _
|_|_|
```
Then a two-unit one on top:
```
_ _
| |
|_ _|
|_|_|
```
Then a three-unit one on the right:
```
_ _ _ _ _
| | |
|_ _| |
|_|_|_ _ _|
```
Then a five-unit one on the bottom:
```
_ _ _ _ _
| | |
|_ _| |
|_|_|_ _ _|
| |
| |
| |
| |
|_ _ _ _ _|
```
etc.
### Your task
Given *N* squares to print (0 <= *N* <= 20), print the figure that contains *N* squares. For example, if *N* was 4, it should print:
```
_ _ _ _ _
| | |
|_ _| |
|_|_|_ _ _|
```
Note that it does not have to exactly follow this format, just something that represents the same figure.
Since it has four squares in it:
```
3
_v_ _ _ _
| | |
|_ _| |< 4
2 >|_|_|_ _ _|
^
1
```
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins.
```
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1697 1087"><title>Fibonacci Folge</title><desc>16 Zahlen der Fibonacci Folge</desc><defs><view id="fibo14" viewBox="50 50 610 377" /><view id="fibo12" viewBox="427 283 233 144" /><view id="fibo10" viewBox="427 283 89 55" /><view id="fibo8" viewBox="482 317 34 21" /><view id="fibo6" viewBox="482 317 13 8" /><view id="fibo4" viewBox="490 322 5 3" /></defs><a xlink:href="fibonacci.svg#fibo14" xlink:title="Fibonacci Folge 14"><a xlink:href="fibonacci.svg#fibo12" xlink:title="Fibonacci Folge 12"><a xlink:href="fibonacci.svg#fibo10" xlink:title="Fibonacci Folge 10"><a xlink:href="fibonacci.svg#fibo8" xlink:title="Fibonacci Folge 8"><a xlink:href="fibonacci.svg#fibo6" xlink:title="Fibonacci Folge 6"><a xlink:href="fibonacci.svg#fibo4" xlink:title="Fibonacci Folge 4"><rect x="491" y="322" width="1" height="1" fill="#dddd88" /><rect x="490" y="322" width="1" height="1" fill="#dddddd" /><rect x="490" y="323" width="2" height="2" fill="#eeee99" /><rect x="492" y="322" width="3" height="3" fill="#eeeeee" /></a><rect x="490" y="317" width="5" height="5" fill="#cccc77" /><rect x="482" y="317" width="8" height="8" fill="#cccccc" /></a><rect x="482" y="325" width="13" height="13" fill="#dddd88" /><rect x="495" y="317" width="21" height="21" fill="#dddddd" /></a><rect x="482" y="283" width="34" height="34" fill="#eeee99" /><rect x="427" y="283" width="55" height="55" fill="#eeeeee" /></a><rect x="427" y="338" width="89" height="89" fill="#cccc77" /><rect x="516" y="283" width="144" height="144" fill="#cccccc" /></a><rect x="427" y="50" width="233" height="233" fill="#dddd88" /><rect x="50" y="50" width="377" height="377" fill="#dddddd" /></a><rect x="50" y="427" width="610" height="610" fill="#eeee99" /><rect x="660" y="50" width="987" height="987" fill="#eeeeee" /><g font-family="Arial" text-anchor="middle"><text x="505" y="327" dominant-baseline="middle" font-size="0.7rem">21</text><text x="499" y="300" dominant-baseline="middle" font-size="0.9rem">34</text><text x="455" y="310" dominant-baseline="middle" font-size="1.2rem">55</text><g font-size="2.0rem"><text x="471" y="382" dominant-baseline="middle">89</text><text x="588" y="355" dominant-baseline="middle">144</text><text x="543" y="166" dominant-baseline="middle">233</text><text x="239" y="239" dominant-baseline="middle">377</text><text x="355" y="732" dominant-baseline="middle">610</text><text x="1153" y="543" dominant-baseline="middle">987</text></g></g><path d="M1647 50 a987,987 0 0,1 -987,987 a610,610 0 0,1 -610,-610 a377,377 0 0,1 377,-377 a233,233 0 0,1 233,233 a144,144 0 0,1 -144,144 a89,89 0 0,1 -89,-89 a55,55 0 0,1 55,-55 a34,34 0 0,1 34,34 a21,21 0 0,1 -21,21 a13,13 0 0,1 -13,-13 a8,8 0 0,1 8,-8 a5,5 0 0,1 5,5 a3,3 0 0,1 -3,3 a2,2 0 0,1 -2,-2 a1,1 0 0,1 1,-1 a1,1 0 0,1 1,1" stroke="black" stroke-width="0.25" fill="none" /></svg>
```
]
|
[Question]
[
Given N integers, output the sum of those integers.
## Input
You may take the integers in any reasonable format, including:
* `stdin`
* arguments
* an array or list
## Rules
* Your code must not include the characters `+` or `-`.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. Take note of [Abusing native number types to trivialize a problem](https://codegolf.meta.stackexchange.com/a/8245/89298).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The shortest code in each language wins, which means that I will not be accepting an answer.
## Testcases
```
n=2, 1, 2 -> 3
n=2, 2, 2 -> 4
n=2, 9, 10 -> 19
n=2, 7, 7 -> 14
n=2, 8, 8 -> 16
n=2, -5, 3 -> -2
n=2, -64, -64 -> -128
n=2, -3, 0 -> -3
n=2, 0, 3 -> 3
n=2, 0, 0 -> 0
n=2, -1, -1 -> -2
n=2, -315, -83 -> -398
n=2, 439, 927 -> 1366
n=3, 1, 2, 3 -> 6
n=3, 2, 2, 5 -> 9
n=3, 0, 9, 10 -> 19
n=3, 7, 0, 7 -> 14
n=3, 8, 8, 0 -> 16
n=3, -5, 3, -2 -> -4
n=3, -64, -64, 16 -> -112
n=3, -3, 0, 0 -> -3
n=3, 0, 3, 0 -> 3
n=3, 0, 0, 0 -> 0
n=3, -1, -1, -1 -> -3
n=3, -315, -83, -34 -> -432
n=3, 439, 927, 143 -> 1509
n=17, -74, 78, 41, 43, -20, -72, 89, -78, -12, -5, 34, -41, 91, -43, -23, 7, -44 -> -29
```
Testcases with partial sums that exceed 8 bits are only required if your integer type supports each partial sum (if any) and the final result. As a special case, `n=2, -64, -64 -> -128` is only required if your integer type can represent `-128`.
Testcases involving negative integers are only required if your language natively supports negative integers.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 2 bytes
**Tr** *finds the trace of the matrix or tensor list*
```
Tr
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6Tof0BRZl6JgkN6dLWuuYmOgrmFjoKJIRAb6yjoGhkACXMjHQULSxADKKVrCOTpmuooGAPV6oIUWhqCGGDVQMIcxDGpjf3/HwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~97 95 93 88~~ 87 bytes
Solution that doesn't use the built-in `sum`, `eval` or `exec`:
*-2 bytes thanks to @JonathanAllan!*
*-1 byte thanks to @ovs!*
```
x=y=1
for i in input():x<<=i*(i>0);y<<=abs(i)
y/=x
print" ~"[x<y],len(bin(x/y|y/x)[3:])
```
[Try it online!](https://tio.run/##XVDbbqMwEH33V4zoQ2BrN4AJhWzIj0R5cIK7tQQGgWlBWu2vZ8c2SdVKyDrHzJyL@8W8dzq9XbtaVpvN5jZXS5WQt24ABUrj108mjPbz4VCpX6E6xtHvBbG4jKGKyLKtZtIPSpsA/gWn@bCcaSN1eFE6nLfL32U7Rye@P0c31H4ZzaD6MCJEtX03GBiX0Tk1SktrhhxnaqX3BOAJBilqHwCErkHOvbwaWeP9ODUGR0Y6QAWt6ENU9urUar2MfaNMGLBjEEU459TarlZvy70QmA51zDRoMO9ydfmU8Cm0Vfa8gka0l1rs5YdowhGDA7iy6AxW/cGDU/A8PAfngBIfffK64mom0eBQ92cQLf6Ss7yG9rGjr93gllBIgR2Bk3RFGSkpJLGFSUleKbw6mJGCQuFgTtiOAreYpYTlGQU8HE3SgjBOwa0zTuJ1ziF3GROGniy5b/MEtVjh1XhZkIyjf5l6V57nxEZcZXKXksLOktJq/sgaf4@7et4To5GryLJHalzPffIk9cm/h1@Zz/@jwqMG/6qBB/dPkfH00QVdMlcg2cXlfw "Python 2 – Try It Online")
**Input**: a comma separated list of numbers, from stdin.
**Output**: the sum is printed to stdout. If the sum is negative, the `~` sign is used instead of `-` due to source code restriction.
**How**: Let \$p\$ be the sum of all positive numbers in the list, and \$n\$ be the magnitude of the sum of all negative numbers. Then the sum of the list is \$p-n\$.
Let \$x=2^p\$ and \$y=2^n\$, then \$\frac xy=2^{p-n}\$.
Thus if the sum is positive (aka \$x>y\$), we can calculate the sum by counting the number of zeros in the binary representation of \$\frac xy\$. Otherwise, we can calculate the magnitude of the sum as the number of zeros in the binary representation of \$\frac yx\$.
[Answer]
# JavaScript (ES6), 21 bytes
Takes input as an array of integers.
```
a=>eval(a.join`\x2B`)
```
[Try it online!](https://tio.run/##rZVNasMwFIT3PYWWMUiJ/mxJi3TRa7SFmNQpCcYOTQm9vfukQBeWtOp4ISwQfGjezOjS3/vb8et8/RbT/DEsp/3S75@Hez9u@u1lPk@Htx/9cmiW4zzd5nHYjvPn5rR5VZzp96ZhoG@3Y@ZphdBwhF0jAmdK4hiEUGHNcJw57DVUdg/PmQczujVDtJwZqFZCZ4zOckYLCBMZSvuMYjjDTl1k5pVQsYr5kNBbRITMlKKYCwWDlGduFDlLeJBcaRohm7k1lPWgHc5ZynRZRmIrAgdPlK7Uipy1QEQoGAtZjLVWlMBirLYiMCP1ViT7apx7ba0VaSYdAJNaUeliK@LkqrYidiLFVsQiKq0Ia8aiUn@tSIv5/3uYfGV0rRXJWRbQWjEhrcyyLhxZ11EULYlmU1poRMJRj/kQf3zUknYpTNHr8WCICj9O0@Li5qFDekXC8gs "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 40 bytes
Takes input as an array of integers.
```
a=>a.reduce(g=(x,y)=>y?g(x^y,(x&y)*2):x)
```
[Try it online!](https://tio.run/##rZXfaoMwGMXv9xS5GjqS1vzRmIHdg4wNpLXSUepot6FP775Y2IVJrna8CAYCP3K@c04@2p/2tr@ePr/EZTh087GZ22bXbq7d4XvfZX2TjXzKm9300mfj@8Sz8XHKn1T@PObzfrjchnO3OQ99dsxeJWfqLc8Z6NtumX5YIRQcYdYIx5kscAxCSLdmWM4s9hoyuEfNWQ1mVGuGKDnTUK2EChiV4YwWEMYzpKoDiuYMO3URmLeAihXNRwG9hUcUgVIUcyFhkPjMtSRniRok1zINF8zcaMq6UxbnLKmrICO@FYGDJ0oVa0XOSiDCRYyFLMZUKxbAYky2IjAj6VYk@yqce02qFWkmFQCztKJU0VbEyZVsRexEoq2IRSRaEdaMUaX@WpEW/f/3cPGVVqlWJGcZQGv5hJRFkHVhybqWomhINLOkhUYkLPVY7fxP7bWk3RIm73V/0HmF76dpsX5z12F5Rdz8Cw "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 2 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function
```
1⊥
```
[Try it online!](https://tio.run/##dVCxDcIwEOyZ4kookPy2E9vjREKRkECiZgAKCkTDCNTZgVGyiPknkvMOUPh99z6/79ydDtvdudsfu9yPl/s603h95s1qvD2Y9iDYgq3CCWQKCQgFR8SCX0MDp1jrP0V1HOYpRmmN6r8GkqVvUcM1znLvEpIN2rUaxr7RqNEL76Z2X73M/rna7wygto5RB6nYjzB/Agn0y1Qgrz8xeIQIT3ws1oy0LGKSPcpcO/kWn6xK8tYkdRyWsc9v "APL (dzaima/APL) – Try It Online")
Simply evaluates a "digit" list in base 1.
[Answer]
# [W](https://github.com/A-ee/w), 1 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
Takes input as a list and... just a summation function... :-)
```
J
```
# [W](https://github.com/A-ee/w) [`j`](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends/14339#14339), 0 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
Haha, even more cheaty! The `j` flag automatically evaluates the `J` command at the end of the source code.
```
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~50~~ ~~45~~ ~~43~~ 38 bytes
```
f(s,e)char**s;{s=s<e?&f(&s[1])[*s]:0;}
```
*-7 bytes thanks to @S.S. Anne*
*-5 bytes thanks to @Bubbler*
Takes for input start and end pointers. It uses the fact that the address of `&a[b]` equals `a+b`. Other than that, even I am a bit confused as to how this works.
[Try it online!](https://tio.run/##ZcqxCsIwGATg3ac4Cpak/oGWUlBj8UFqhzQ2taBRGreQZ49RBweHOzi@02LSOkbDHI1cX9RSFE5617rDeMwNy11X9bwrXL8vZYjXu53wKdX1aOFFRRANYUeoypRtkPidhu8pQU0og1zN9ombmi3j8HgsaRqWrc8nmxEMUwSFDRrO5T8OhCFh/cYQXw "C (gcc) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 1 [byte](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Trivial challenges get trivial solutions!
```
x
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=eA&input=WzEsMl0)
[Answer]
# [Python 2](https://docs.python.org/2/)/[Python 3](https://docs.python.org/3/), 3 bytes
```
sum
```
[Try it online (Py 3)!](https://tio.run/##K6gsycjPM/6fZhvzv7g0939BUWZeiUaaRrSJsaWOgqWReaym5n8A "Python 3 – Try It Online") or [Try it online (Py 2)!](https://tio.run/##K6gsycjPM/qfZhvzv7g0939BUWZeiUaaRrSJsaWOgqWReaym5n8A "Python 2 – Try It Online")
[Answer]
# [GERMAN](https://esolangs.org/wiki/GERMAN), 141 bytes
```
EINGABESCHLEIFENANFANGSUBTRAKTIONRECHTSEINGABESCHLEIFENANFANGSUBTRAKTIONRECHTSADDITIONLINKSSCHLEIFENENDELINKSSCHLEIFENENDERECHTSRECHTSAUSGABE
```
[Answer]
# [Mornington Crescent](https://github.com/padarom/esoterpret), ~~634~~ 537 bytes
```
Take Northern Line to Bank
Take District Line to Parsons Green
Take District Line to Upminster
Take District Line to Temple
Take District Line to Hammersmith
Take District Line to Parsons Green
Take District Line to Upminster
Take District Line to Upminster
Take District Line to Parsons Green
Take District Line to Bank
Take Northern Line to Charing Cross
Take Northern Line to Angel
Take Northern Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent
```
[Try it online!](https://tio.run/##tZJBCsIwEEX3nmIOkIDVSnWpFXSh4qIeIITBBptJmeT@NSnYLqSoCxcZZng/5PMz1jEZugdHUjN6jRS6rlIPhIvjUCMTnAwhBAc7RY9Zj/bGBzY6DOiq2DvycGBEmtDcWmvIB@QJXqFtG5yAR2Utsrcm1H@08Il/88aY0luAZa04Zg0lO@8nNFu6YzP7@QM@OR@vloZ1g9/YPQ@rER2/VkMWuYBiLSDP4lkKkIt5LMVCwHqTmohkFie5ErCMWpmEmyw1vTqWIg35Ew "Mornington Crescent – Try It Online")
```
// initialize adder
Take Northern Line to Bank // save input to Hammersmith
Take District Line to Parsons Green // get 0
Take District Line to Upminster // set Upminster = 0
// set start of loop
Take District Line to Temple
// extract leading number
Take District Line to Hammersmith
Take District Line to Parsons Green
// add it to previous sum
Take District Line to Upminster // accumulator = sum
// Upminster = previous accumulator
// save sum in Upminster
Take District Line to Upminster
// get remaining string
Take District Line to Parsons Green
// check if it is equal to "" by translating the first char to its codepoint (0 if empty)
// we ride a few extra rounds here, adding 0s to the sum
Take District Line to Bank // save string and
// get string of previous round
Take Northern Line to Charing Cross // swap accumulator with Charing Cross
// and get codepoint of previous values'
// first char (that's from two rounds ago)
// or 0 if empty
// if string is not empty (meaning, accumulator is non-zero), repeat
Take Northern Line to Angel
// else read sum
Take Northern Line to Bank // get empty string
Take District Line to Upminster // swap with Upminster
// and go home, outputting the number
Take District Line to Bank // change lines, swapping data with Bank
Take Circle Line to Bank // swap back
Take Northern Line to Mornington Crescent // go home
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 94 bytes
```
x,c;n(a,b){for(;b;b=x*2)x=a&b,a^=b;x=a;}f(a,t)int*a;{for(c=1;c<t;c=n(c,1))*a=n(*a,a[c]);c=*a;}
```
A non-trivial golfed reference implementation.
I realized I had worded myself out of an answer when I couldn't even use `+` or `-` for a counter variable.
[Try it online!](https://tio.run/##lVLRauMwEHz3VywNPax0RSzJqW1Uf4mbFlmxD8NVKUkoocbfnltJTeMLB8cJpJ3VjnZGQpb/tPZ8PqHVLjXYsrHf7VPd6rY@LSU71eZHi@albjVBPfXEObLBHZdGB6athbZPR21rl1oUjC0NoaVB09gNo20iTufFtusH14Ez@33qGFADcK@LhWs2jdtAnSR@580MLv3YDVuWjAnQCHTJAh6TUaCcMBllDBWKzMcCCx9KLH3ga1QhPuZIM0CFgZjFShYzLpCLWBZr5GWo5arCSvp@XnLSydWGmtuIncgIrmPLq5ns286XDhlCLmeeUDxebH0bu4C5uRt/yFU@84giVzc@Vys4vHd2ML/AmkMX9uJLi6IRhX/neAVe5AhFiZALmgqBy4yWQiKUlQdU4oIyMg@KuNwTK@FBYNNS@CT/Q9//B683QA2ZpvAEh@Gz2/Wpe5VsdcVNRl8DhoeHy5vC13jf0/k@vbvfPrs7hEgeNgiSMR21/i2lZlLqf6RUkFI3Un8hCrq8KDxvOv8G "C (gcc) – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 57 bytes
```
printf %.f $(bc -l<<<"99*l(e(`sed 's@ @/99)*e(@g'`/99))")
```
[Try it online!](https://tio.run/##TY7LasMwEEX38xUXkxI7MK1ejiTwwh/SRR5WaoOJS1zopv/ujuoYutDVMJo5R5fz3C/f/TAmPNK5wzjcEwHdJAGkaz@h2OVmgR@8L5@P4f51w8vrDbvycgWPTdMUMR7GMpWnOXXYzy3atxirQyrbj/0pl1VRLSuMukn4i4YBmRwRWpGHBwUEENewkkcHOcQWCqRyS@WKNVhLV9fgYMnZiGg8ZZpdeXWefDLVRlVPLpuNDH1c4U@8WgWb4r8FbN1mgnaW2Dv4AKfhMlKBvUGIcgXZM8gqkch7FNDfjJWfsHP0Cw "Bash – Try It Online")
Reads space-separated integers from stdin, and writes the output to stdout.
This applies the exponential function to each integer, multiplies the results, and then takes the natural logarithm of the product. I need to scale the input numbers (and then "unscale" the result) so as not to overflow the exponentials on some of the starred test examples (that's what the `99*` and `/99` are doing there).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 1 byte
```
s
```
[Try it online!](https://tio.run/##K6gsyfj/v/j//2hDHQUjHQXjWAA "Pyth – Try It Online")
### Explanation
```
s(Q)
(Q) : Implicit evaluated input
s : Sum the input
```
[Answer]
# Mornington Crescent, 1267 bytes
[Try it online!](https://tio.run/##xZTPCsIwDMbvPkVewIMieNYpenAi6LzXEbbimoy0Cj79rIgT1Pofdu3vS/Mlgc@wkKbMMbVTQZsiuapaqS3CnMXlKAQzTQiOYaho23qMxjvrfzjDtU4di1Y1XOIeCZbaOhQb0FwezjjSkhb4Hry6GvkO4qU1WiixTBYmgkgBTVIaTSdnAT5VxnjbRrv8hy7/cJKUhIdGp7iu@uYGMbNkyuFDuEJTFvh53c@H/X5dTdU2eaa73jd8bDb@X@PzIZABUa7EJwlEwtYGNAPKsGi9ipePdhqc9klcxXXoebeX0OtAD/rQ7R0B)
Poorly golfed, may have to have another attempt tomorrow.
```
Take Northern Line to Bank
Take Northern Line to Euston
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take District Line to Parsons Green
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Parsons Green
Take District Line to Parsons Green
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Parsons Green
Take District Line to Bank
Take Circle Line to Moorgate
Take Circle Line to Temple
Take Circle Line to Moorgate
Take Circle Line to Bank
Take District Line to Parsons Green
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Parsons Green
Take District Line to Bank
Take Circle Line to Moorgate
Take Circle Line to Hammersmith
Take Circle Line to Embankment
Take Northern Line to Charing Cross
Take Northern Line to Angel
Take Northern Line to Bank
Take District Line to Upney
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent
```
[Answer]
# [Python](https://docs.python.org/), 3 bytes
```
sum
```
Built in function which does the job
**[Try it online](https://tio.run/##K6gsycjPM7YoKPqfZhvzv7g0939BUWZeiUaaRrSxjqGRjmmspuZ/Q2MA)**
---
With no built-in, **36 bytes** in [Python 2](https://docs.python.org/2/):
-3 thanks to ovs!
```
lambda a:eval(`a`.replace(*',\x2b'))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHRKrUsMUcjITFBryi1ICcxOVVDS10npsIoSV1T839BUWZeiUaaRrSRjqmOrqGRjrGOrkUsUAIA "Python 2 – Try It Online")
Note: a single value may be represented as a singleton list ([meta](https://codegolf.meta.stackexchange.com/a/11884/53748))
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 [byte](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
S
```
A built-in monadic atom which given a list yields the sum.
**[Try it online!](https://tio.run/##y0rNyan8/z/4////0aY6hkY6hrEA "Jelly – Try It Online")**
---
No built-in, **2 bytes**:
```
ḅ1
```
Converts from base one to an integer.
[Try it online!](https://tio.run/##y0rNyan8///hjlbD////R5vqGBrpGMYCAA "Jelly – Try It Online")
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), `-hr`, 2 bytes
```
÷⅀
```
[Try it online!](https://tio.run/##y05N////8PZHrQ3//0ebWeoomBgZ6CgYmuoo6BrG/tfNKAIA "Keg – Try It Online")
The joys of not having implemented lists properly! Simply item split and summate. Essentially uses a sum function, so no imaginary points for me.
[Answer]
# Batch, 93 bytes
`43` is the ASCII code for `+`:
```
@!! 2>nul||cmd/q/v/c%0&&exit/b
set c=cmd/c
set/pn=
%c%exit 43
%c%set/a !n: =%=exitcodeascii%!
```
Takes input via `STDIN`, delimited by space.
[Answer]
# [J](https://jsoftware.com), 4 bytes
```
1&#.
```
This was literally taken from [here](https://codegolf.stackexchange.com/a/152191/91569).
[Answer]
# [Haskell](https://tio.run/##y0gszk7NydHNKE0v/v8/NzEzT8FWoaAoM69Eo7g0N9pQx0jHOFbz/38A), 3 bytes
```
sum
```
Function that takes an argument as a list e.g. `sum[1,2,3]` and returns the sum of the list.
[Answer]
# [Brainetry](https://github.com/rojergs/brainetry), 143 bytes
```
a b c d e f
a b
a b c d e f
a b c d e f g h
a b c d e f g h
a b c d e
a b c d
a
a b c d e f g h i
a b c d e f
a b c d e f g h i
a b c d e f g
```
To try it online follow [this repl.it link](https://repl.it/github/rojergs/brainetry) and paste the code in the `btry/replit.btry` file, then press the green "Run" button. Does I/O as ASCII codepoints.
The program above is the golfed version of this program:
```
Let me sum some numbers carefully.
Carefully enough
so that I do not use
the plus or minus signs, that'd be awful.
After I do this, oh so very carefully,
I just have to ...
Move the pointer
left and right for
a while.
This is the main gist of the whole program.
Of course this sounds somewhat uninteresting.
That is because you, my dear reader, lack depth.
(Is it "depth"?
Maybe that's not the correct English word...)
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 4 bytes
```
_MSg
```
[Try it online!](https://tio.run/##K8gs@P8/3jc4/f///4b/jQA "Pip – Try It Online")
`MS` maps a function to an iterable and sums its results.
`_` is the identity function.
`g` is the list of command line args.
[Answer]
# [Python 3](https://docs.python.org/3/), 62/61 bytes
Without relying on sum in other functions.
```
def f(i,x=0):
for y in i:
while y:x,y=x^y,(x&y)*2
return x
```
Can be shortened to 61 by removing the function definition (-13), replacing `in i:` with `in eval(input()):` (+12) and print instead of return at the end (+0).
[Try it online!](https://tio.run/##TYrBCsMgEAXP8Sv2VLSsEF1Da8AvKe2pSoRigliqX28DgdLLwJs3WyvLmqj3pw8QeMTqRjGzIawZGsQEcR/DZ4kvD22u2Fx9NOT11MRZsyH78s4Jat9yTIUHflMI@i7AOSDBflaSmhDklXaQOX5pSP8lhiyC1RcEZego1DRa0b8 "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
O
```
Input as a list.
[Try it online](https://tio.run/##FYrLCcAwDMUWeg/iT7AzRQYIPbTQ/Udw3ZME0pj3I2/VrjoMRyRc4AbqAEORq5GgKDhhDnZf0vgfQ7T59QE) or [verify all test cases](https://tio.run/##VY5LDsIwDESvUnU9keLEbZIVR@AAVRcgsWDFAgmpF@AAHJGLhIlp@SziseLxPF@uh@P5VG/Lru@e90fX75a6r6jTJAgzpmC1QDwlIbFmZFY3IDYZFXyti2geb9/eeidwYiMZ4HIbaCwoocUw36wkYLCVD8VvnHcKSXbFyoKMK24DrvoD/efCRf2yIWqXJ0XKUIHSEDxcCsiFkrkd0LDkcV4YZ56IxE7n@QU).
Slightly less boring:
```
1β
```
[Try it online](https://tio.run/##FYrLCcAwDMUWeg/iT7AzS@mhhSzYQbqS654kkMa8btlV8j5VB8MRCRe4gTrAUORqJCgKTpiD3Zc0/scQbX5@) or [verify all test cases](https://tio.run/##VY7NDcIwDIVXqXp@keLEbZJTB6l6AIkDJw5ISF2AARiFQRiCRcqLafk5xM@Kn9/n03m3Px6Wyzy0zfN6a9phXuRxX7CMoyBMGIPVAvGUhMSakVldh1ilV/DVLqJ6vH17653AiY2kg8t1oLGghBrDfLOSgM5WPhS/cd4pJNkVKwvSr7gNuOoP9J8LF/XLhqhdnhQpQwVKQ/BwKSAXSuZ2QMWSx3lhnHkiEjudphc).
**Explanation:**
```
O # Sum the (implicit) input-list
# (and output the result implicitly)
1β # Convert the (implicit) input-list to base-1
# (and output the result implicitly)
```
[Answer]
# [Racket](https://racket-lang.org/), 133 bytes
```
(define(f a[s 0])(if(null? a)s(let([c(car a)])(if(= 0 c)(f(cdr a)s)(f(cons((if(> 0 c)add1 sub1)c)(cdr a))((if(> 0 c)sub1 add1)s))))))
```
[Try it online!](https://tio.run/##bY49DsIwDIV3TvEkBpwhUp0GWgbgIBVDSFtUEQXU0IHTg9MuCGHJ8s/3bL3R@Vv3fK@Di1eMy0Bt1w@xox6uSSjOioae4hTCCU4lCt2TGk/ejTIu8IACXlFPvs3LNLf3mCjD4wxd2zLSdGElwkWmvnAmyBo5nkNcDOkR3CtEiJMNMQxKAatfoFk@8F@ys8jJu7@0sqhqWIYtoU0BXRnUeyk1NBvoLUq5F75nKVlTopLOZnsf "Racket – Try It Online")
Well...
[Answer]
# perl -ple, 18 bytes
```
s/ /\x2b/g;$_=eval
```
[Try it online!](https://tio.run/##FYrBCsIwEAXv@Yp38Lqku9mQFPFPBFEoIoQ2tKX49a7b0wzM9Glt2WyLiPevvOL7enncpuPZzBgSiAeQDMEdCYocqChKhTI0nQlUBHV0VBALKCMpyPvIjvNJKG76W/r@WebNqLc/ "Perl 5 – Try It Online")
Reads a space separated list of numbers from `STDIN`, writes the sum to `STDOUT`.
# perl -MList::Util=sum -alpe, 8 bytes
```
$_=sum@F
```
[Try it online!](https://tio.run/##FY2xCgIxEAX7fMUrbBdukw3JHQhWVlpai4VFIHrBxN933VQzMA9ee35qVD3cj/37Op1VGd4RLyC/OHMECKKjJEgZwpAwEyh55NWQQexBEUFA1lc2zE1AMpPf3kbZ313peil9bNttlDrPlNqj/gE "Perl 5 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~60~~ 24 bytes
```
$args-join[char]0x2b|iex
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL1YNys/My86OSOxKNagwiipJjO14v///7rG/3WN/uuaAgA "PowerShell – Try It Online")
-36 bytes thanks to @mazzy
[Answer]
# Haskell, 3 Bytes
```
sum
```
calculates the sum of a list
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~83~~, 110 bytes
```
#include <iostream>
int n,x,c;int f(int i){while(i){c=n&i;n^=i;i=c<<1;}if(std::cin>>x)f(x);else std::cout<<n;}
```
[Try it online!](https://tio.run/##JYzLCsIwFET3@YqAIAnUhYqb5vEpQrlN9EJ6W5oUAyXfHhudxXA4DAPLcnkB1HpCgrCNjmucY1rdMFmGlDh1uQPVyIvWKPfPG4MTB4ChMyp6GlRoQOurKuhFTGPfA5K1WXqRpXIhOv6385a0JlVqu5oGJCHZzviR35KVeuN3/vgC "C++ (gcc) – Try It Online")
Explanation: Reads in integer inputs and preforms bit-wise addition.
I tried to simplify the carry step [like this](https://tio.run/##HYzLCoMwEADv@YothZKFCn3Q00Y/pRDixi7oKk2kQvDbbe0cZm4TpqnqQtiOoqGfWwYnY8pv9kNj5iTagfqB0@QDQ8otbaIZ9LzQ3mh3C5bPS3q2cqgvWPRZC0lt9STo3JVWiTaINs2C0S5I3CeGMM7ZuUpp/Q8HL2rRFAM/olUks243uMPjCw) but it gave me a negative result.
[Answer]
# Java 8, 35 bytes
```
x->x.stream().mapToInt(x->x).sum()
```
Takes a `List` of `Integer`s.
] |
[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/139736/edit).
Closed 4 years ago.
[Improve this question](/posts/139736/edit)
Squares looks symmetric, and so are the required codes.
**Objective**: Write a program whose source code is a solid square (N lines with N printable, non-whitespace characters each line) and prints a square of equal size. **A program (or output) with inconsistent width and height is invalid.** (e.g. 6x5)
### Example (HQ9+)
```
QAA
AAA
AAA
```
### Requirements
* Both the source and the output must contain N lines, and N printable characters each line, followed by 1 linefeed. Your program should *not* contain or output any control characters (except LF or CR-LF) or whitespaces (Space, Tab, VTab)
* Standard loopholes are boring, don't use them.
* A program (and output) with only one character is fundamentally nothing. N must be at least two.
* The content of the output doesn't matter, as long as it complies with rule 1
* **Special rule**: Do **not** use comments or codes that does *not* affect the output to "fill" your code.
To be clear, you are allowed to use `i++;i++;... i++;` instead of `i+=10;`, but you shouldn't define a variable `string s="placeholder"` but never use it later. It is very easy to work around this rule so don't be too strict.
* If you want to output a newline before everything else, it OK but please declare that you're using this rule.
If you want to output the last line without a succeeding linefeed, it's OK, too and you don't need to declare it. However that does not affect scoring.
**Additional**: Please give the number N (width/height) your program is using. Provide descriptions of your code if possible.
There is no need to give the length (in bytes) of your program because the N says it all.
Because this is a [code-bowling](/questions/tagged/code-bowling "show questions tagged 'code-bowling'"), the program with the largest N and the highest complexity will win.
[Answer]
# JavaScript (ES6), N = 5
With a leading newline instead of a trailing newline.
```
alert
((a=`
`+!!0
)+a+a
+a+a)
```
# JavaScript (ES6), N = 6
```
alert(
(1e5+`
`)['r'
+'epe\
'+'at\
'](6))
```
# JavaScript, N = 7
```
this['\
consol\
e'].log
('1234\
567\n'[
'repea\
t'](7))
```
# JavaScript, N = 202
```
[][(![]+[])[+[[[[[]]]]]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![
]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]
]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!
+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+
[]+[+[]]]+(!![]+[])[+!+[]]](([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]
+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]
+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+
[+[]])+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+[![]]+([]+[])[
([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[
])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![
]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]
+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(
!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[
+[]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+
[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]
)[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[
]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]
+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[
]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])
[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![
]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]
+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]
])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+
[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[
]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+
[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[
])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!!
[]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[
]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[
])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[
]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([
][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![
]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[
])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[
!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+
(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[]
)[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]
+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([
![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+
[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![
]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+
[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[]
)[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!
[]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]
+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+
!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+(!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]])+[])+(+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]])+[])[!+[]+!
+[]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[
])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])
[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]
+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+
[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]
+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[
+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]
]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+
[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]
)[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[
]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]
+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[
]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[]
)[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![
]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]
]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[]
)[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]
]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([]
[[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]
]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[]
)[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!
+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(
+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])
[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+
[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([!
[]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[
]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]
]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[
]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])
[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![
]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+
[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!
+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+(!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]])+[])+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+
!+[]]+(!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!
+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+
[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]
+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]
+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+
[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[
]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+
[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![
]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+
!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]
+[+[]]]+[!+[]+!+[]]+[+[]]+[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(+(+!+[]+(!+[]+[
])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]])+[])[!+[]+!+[]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]
]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])
[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]
+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(
!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+
[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])
[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!
+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![
]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[]
)[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]
]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+
(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[
+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]
+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!
+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+
[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+
[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])
[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!
+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]
+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(
!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!
+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]
+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!
+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+
[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]
+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]
+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+
[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[
]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+
[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![
]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+
!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[
])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+(!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]])+[])+[][(![]+[])[+[]]+
([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]
+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+
[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[
+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]
]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+
(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[
!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]
+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[
]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]
+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])
[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[
]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![
]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]
]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+
(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]
+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![
]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]
+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]
+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]
+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]
]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[]
)[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+
!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([!
[]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[
])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]
]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]
+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])
[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]
]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+
!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]
+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(
!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]
+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[]
)[+!+[]]]+[])[!+[]+!+[]+!+[]])+([][[]]+[])[+!+[]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][
[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]
+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]
+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+
[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+
[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]
+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]])
)[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[]
[[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]
]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![
]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]
+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+
([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![
]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[
+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+
[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]
]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[
]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!
+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]
]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+
[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+
(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[
+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+
(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(!
[]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[
+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[
+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]
])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!
![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(
!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][
(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]
+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+
[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+(!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]])+[])+(!![]+[][(![]+[])[+[]]
+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(!!
[]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![
]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[
])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[
]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]
+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+
!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+
[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]
+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]
+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!!
[]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[
!+[]+!+[]]+[+[]]+[+[]]+(+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]])+[])[!+[]+!+[]]+[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[
!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]])()
```
[Answer]
# Perl 5, 5×5
```
print
q.u.x
$],$/
for(t
..x);
```
This is very slightly obfuscated to make it more interesting, so here's some explanation: `q.u.` [is just the same as `'u'`](https://perldoc.perl.org/perlop.html#Quote-and-Quote-like-Operators). The following `x` is [the repetition operator](https://perldoc.perl.org/perlop.html#Multiplicative-Operators), so `'u'` is repeated `$]` times. [`$]` is between 5 and 6](https://perldoc.perl.org/perlvar.html#General-Variables), so `'u'` gets repeated 5 times. You then append [the newline `$/`](https://perldoc.perl.org/perlvar.html#General-Variables) and [`print`](https://perldoc.perl.org/functions/print.html) the whole thing. This is all done once for each member of the list `t..x`: `t` and `x` as barewords are assigned the values `'t'` and `'x'` respectively, and [the list is thus `'t','u','v','w','x'`](https://perldoc.perl.org/perlop.html#Range-Operators). So the output is:
```
uuuuu
uuuuu
uuuuu
uuuuu
uuuuu
```
[Answer]
# Ruby, 3x3
```
!p\
p,\
p,p
```
Prints
```
nil
nil
nil
```
[Try it online!](https://tio.run/##KypNqvz/X7EghqtAB4QL/v8HAA "Ruby – Try It Online")
## How it works
`p` is a method that prints each of its arguments, then returns the value (or an array of the values) that it printed. If it's called without an argument, it doesn't print anything and returns `nil`. Thus the `p`s on lines 2 and 3 all evaluate to `nil`, and the first `p` prints those `nil`s.
[Answer]
# [Python 3](https://docs.python.org/3/), 29 bytes
```
eval(
'pri\
nt(1\
/8),'
*-~4)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P7UsMUeDS72gKDOGK69EwzCGS99CU0edS0u3zkTz/38A "Python 3 – Try It Online")
5x5 can be done. Prints:
```
0.125
0.125
0.125
0.125
0.125
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), n=2
Boring solution (Charcoal just prints ASCII literally):
```
sq
re
```
[Try it online!](https://tio.run/##S85ILErOT8z5/7@4kKso9f///7qpAA "Charcoal – Try It Online")
[Answer]
# C, N=7
```
i;main(
){for(i
=01;i<=
56;i++)
putchar
(i%8?37
:012);}
```
Prints a 7x7 grid of `%`, i.e.
```
%%%%%%%
%%%%%%%
%%%%%%%
%%%%%%%
%%%%%%%
%%%%%%%
%%%%%%%
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 9x9
```
++[->+++<
]>+++[->+
>+<<]<--[
>+<++++++
]><<++[->
+++++<]>>
>>[<[-<.>
]<<.>>+++
++++++>-]
```
[Try it online!](https://tio.run/##JYtLCoBADEP3vUqoJwi5SOlCBUEEF4Lnr9Mxi3x4ZHvW8z7e/aoCwgWAlh09TCCT7tENU4OSE9vcTMmkYDgXWXJ4/38KeVZ9 "brainfuck – Try It Online")
Outputs a square of `+` (the most fundamental function of brainfuck).
**I'll be back when I figure out how to convert this into a quine, so rougly 3 weeks or so...**
[Answer]
## Haskell, ~~7x7~~ 6x6
```
f=b>>y
y=b++n
n="\n"
b=c++d
c=d++d
d="--"
```
Outputs
```
------
------
------
------
------
------
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P802yc6ukqvSNklbO48rz1YpJk@JK8k2WVs7hSvZNgVEpdgq6eoq/c9NzMxTsFUoKC0JLilSSPsPAA "Haskell – Try It Online")
How it works:
```
f= -- main function which returns the string
b>>y -- length b copies of y, i.e. 6 times y, because:
d="--" -- basic building block of the string
c=d++d -- c -> "----"
b=c++d -- b -> "------" -> b has length 6
y=b++n -- y -> 6 dashes plus newline "-------\n"
```
With compiler flags allowed there's a 5x5 solution:
### Haskell, 5x5 (with -cpp compiler flag)
```
(>>)\
[1,2\
..5]\
"abc\
de\n"
```
[Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZp2CrUFBaElxSpKCiEPNfw85OM4Yr2lDHKIZLT880NoZLKTEpOYYrJTUmT@n//3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
`-cpp` invokes the cpp preprocessor which enables line folding via `\`.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), N = ~~3~~ 2
```
H$
$Q
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=SCUyNCUwQSUyNFE_)
The first line - `H$` means `in the continuing lines replace $ with H`, resulting in the next line being `HQ`. That then gets executed:
```
H decrease POP (nothing on the stack so input (no input so 0)) - results in 0-1 = -1
Q output that without popping
implicitly output POP as none of `tTpP` were called
```
Found this by brute forcing trough all programs on length 2 (as any program like `..\n..` will always come down to a 2 character program)
[Answer]
# [Python 2](https://docs.python.org/2/), n=6
```
print\
'\n'.\
join(\
['###\
###']\
*+~-7)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM68khks9Jk9dL4YrKz8zTyOGK1pdWVk5hgtIqMfGcGlp1@maa/7/DwA "Python 2 – Try It Online")
Not as golfed as it could be, but... I have to fill up the gaps somehow don't I :P
[Answer]
# [Ruby](https://www.ruby-lang.org/), n=~~6~~ 5
Saved 12 bytes thanks to [m-chrzan](https://codegolf.stackexchange.com/users/58569/m-chrzan)
```
puts(
"Rub\
y!\n\
"*(1+
2+2))
```
[Try it online!](https://tio.run/##KypNqvz/v6C0pFiDSymoNCmGq1IxJi@GS0lLw1Cby0jbSFPz/38A "Ruby – Try It Online")
~~Yes, I'm intending to Leaky Nun this~~ **EDIT:** :/ source restrictions are worse than I thought for most esolangs, and normal languages as well
[Answer]
# [><>](https://esolangs.org/wiki/Fish), N = 3
```
"vn
:/^
ao/
```
It prints
```
110
110
118
```
[Try it online](https://tio.run/##S8sszvj/X6ksj8tKP44rMV///38A "><> – Try It Online"), or watch it at the [fish playground](https://fishlanguage.com/playground)!
This is a little tricky, so bear with me. The fish starts in the top left corner, and immediately enters string mode. It pushes the charcodes of "v" and "n" to the stack, which are 118 and 110 respectively. The fish then wraps and hits the `"` again, exiting string mode. The `v` then sends the fish downward, and the `/` reflects it left into `:`, which duplicates the top of the stack: the stack is now 118, 110, 110.
The fish then wraps and `^` sends it into a loop:
```
n
^
ao/
```
This loop prints the top of the stack as a number (`n`), wraps and bounces, pushes `a` = 10 = linefeed to the stack, then prints it as a character (`o`) and starts the loop again. When the stack is empty, `n` causes an error and the program halts.
---
It's been pointed out in the comments that halting with an error is rather unsatisfying. I therefore give you an alternative that halts naturally, in a 4x4 square:
```
aa|v
no"/
lo~/
;!?/
```
It prints
```
/110
/110
/110
/110
```
[Try it online!](https://tio.run/##S8sszvj/PzGxpowrL19Jnysnv06fy1rRXv//fwA "><> – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 11 bytes
```
3éi
3Äh
hhh
```
[Try it online!](https://tio.run/##K/v/3/jwykwu48MtGVwZGRn//wMA "V – Try It Online")
```
éi
.Ä
```
Should be a valid 5 byte solution, but unfortunately that functionality is missing. :(
[Answer]
# CJam, n=∞
## Root version: **n=2**
```
AN
BN
```
[Try it Online](http://cjam.aditsu.net/#code=AN%0ABN)
Prints
```
10
11
```
Can be extended to any n by prepending numbers to each line. E.g:
## n=11
```
123456789AN
123456789AN
123456789AN
123456789AN
123456789AN
123456789AN
123456789AN
123456789AN
123456789AN
123456789AN
```
Prints
```
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
```
[Try it Online](http://cjam.aditsu.net/#code=123456789AN%0A123456789AN%0A123456789AN%0A123456789AN%0A123456789AN%0A123456789AN%0A123456789AN%0A123456789AN%0A123456789AN%0A123456789AN%0A123456789AN%0A%0A%0A)
[Answer]
# [Proton](https://github.com/alexander-liao/proton), N = 5
```
print
(5*("
$$$$$
"[1to
7]));
```
[Try it online!](https://tio.run/##KyjKL8nP@/@/oCgzr4RLw1RLQ4lLBQS4lKINS/K5zGM1Na3//wcA "Proton – Try It Online")
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 11 bytes
```
"r(
34)
r&o
```
[Try it online!](https://tio.run/##y6n8/1@pSIPL2ESTq0gt//9/AA "Ly – Try It Online")
A standard quine put in the shape of a square.
[Answer]
# [Perl 5](https://www.perl.org/), 4x4
```
(say
1111
)for
1..4
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqlBmqmdoYP1fozixkssQCLg00/KLuAz19Ez@/wcA "Perl 5 – Try It Online")
Requires `-M5.010` on the command line.
[Answer]
## [brainfuck](https://github.com/TryItOnline/tio-transpilers), N=6
```
++++++
++++>-
--->++
++++[<
......
<.>>-]
```
Arguably this isn't valid as I arbitrarily chose the output char to be 3 codepoints lower to fix the sqaure...
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwy4QISdLpeurq4dlBdtw6UHBlw2enZ2urH//wMA "brainfuck – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), N = 13 (181 bytes)
```
print("#"*13)
print("#"*13)
print("#"*13)
print("#"*13)
print("#"*13)
print("#"*13)
print("#"*13)
print("#"*13)
print("#"*13)
print("#"*13)
print("#"*13)
print("#"*13)
print("#"*13)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ0lZScvQWJNriPD@/wcA "Python 3 – Try It Online")
I don't see why this wouldn't be valid, since there is no rule that enforces me to not use this technique (I think). This prints a 13x13 grid of octothorpes.
[Answer]
# [Aceto](https://github.com/aceto/aceto), 3x3
Cast the implicit zero to a float (`0.0`), duplicate, print, newline, duplicate, print, newline, print, newline.
```
dpn
npp
fdn
```
### Old version that may be invalid:
Aceto is sort of made for this sort of challenge; all programs are squares, at least internally. It may or may not be valid, as in the output the final line does not end with a linefeed. We simply calculate 2^7, turn on sticky mode, and print three times with newlines inbetween.
```
pnp
kFn
27p
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 3 x 3
```
3/ṣ
ṙ×↑
9:⇈
```
[Try it online!](https://tio.run/##ARwA4/9nYWlh//8zL@G5owrhuZnDl@KGkQo5OuKHiP// "Gaia – Try It Online")
### Explanation
```
9 Push 9
: Copy it
⇈ Call the function above
ṙ String representation of 9
× Repeated 9 times
↑ Call the function above
3/ Split into chunks of 3
ṣ Join with newlines
```
# Gaia, 2 x 2
```
gp
Ø↑
```
I'm not sure if this is valid since it's a cheating quine (`Øg` reads the program's source file).
[Answer]
# PHP, n=∞
I don't know if this is a loophole, but here is the `2` version :
```
aa
aa
```
Prints
```
aa
aa
```
[Try it online!](https://tio.run/##K8go@P8/MZErMfH/fwA "PHP – Try It Online")
# With n=10
```
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
```
[Try it online!](https://tio.run/##K8go@P8/EQ64aM/8/x8A "PHP – Try It Online")
Can be extended to any number.
[Answer]
# [Python 3](https://docs.python.org/3/), n=6
```
print\
('\n'\
.join\
(['$$\
$$$$'\
]*+6))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM68khktDPSZPPYZLLys/Mw/Ii1ZXUYnhUgECoGCslraZpub//wA "Python 3 – Try It Online")
Almost the same as the Python 2 answer, just with parens :/
I can make it more different if anyone wants :P
[Answer]
## TI-BASIC, N = 2
```
Disp Xmax
Disp Xmax
```
Note that `Disp` (including the space) and `Xmax` are each one character. Since Xmax is 10 by default, the output is:
```
10
10
```
[Answer]
# [WendyScript](http://felixguo.me/wendy/), 5x5
```
for i
:0->5
{#j :
0->5@
i ""}
```
produces:
```
00000
11111
22222
33333
44444
```
[Try it online!](http://felixguo.me/#wendyScript)
[Answer]
# [Python 2](https://docs.python.org/2/), n=5
```
exec(
'pri\
nt "\
5"*5\
;'*5)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P7UiNVmDS72gKDOGK69EQSmGy1RJyzSGy1pdy1Tz/38A "Python 2 – Try It Online")
Python 2 variant of [Sisyphus' answer](https://codegolf.stackexchange.com/a/139791/38592)
[Answer]
# Excel VBA, n = 15
Declared subroutine that takes in an empty input variable, (for output) and outputs to range `[A1]`, via a messagebox and to VBE immediate window, and via the input variable
```
Sub$A(n):s="1|"
s=s+"2"+"|"+"3"
s=s+"|"+"4"+"|"
s=s+"5"+"|"+"6"
s=s+"7|8|9|0|1"
s=s+"2|3|4"+"|"
s=s+Chr(51+9-7)
tu=Split(s,"|")
var=Join(tu,"")
[B1]=var+vbCrLf
o=[Rept(B1,15)]
MsgBox$o,0,"hi"
Let[A1]=CStr(o)
Debug.Print[A1]
n=o:End:End$Sub
```
The above autoformats to
```
Sub A(n): s = "1|"
s = s + "2" + "|" + "3"
s = s + "|" + "4" + "|"
s = s + "5" + "|" + "6"
s = s + "7|8|9|0|1"
s = s + "2|3|4" + "|"
s = s + Chr(51 + 9 - 7)
tu = Split(s, "|")
Var = Join(tu, "")
[B1] = Var + vbCrLf
o = [Rept(B1,15)]
MsgBox$ o, 0, "hi"
Let [A1] = CStr(o)
Debug.Print [A1]
n = o: End: End Sub
```
and outputs
```
123456789012345
123456789012345
123456789012345
123456789012345
123456789012345
123456789012345
123456789012345
123456789012345
123456789012345
123456789012345
123456789012345
123456789012345
123456789012345
123456789012345
123456789012345
```
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), n=∞ (min 7x7)
```
"'.<~SD|
"'.<~SD|
"'.<~SD|
"'.<~SD|
"'.<~SD|
"'.<~SD|
"'.<~SD|
k@."0<Ra
```
[Try it online!](https://tio.run/##KyrNy0z@/19JXc@mLtilhos8RraDnpKBTVDi//8A "Runic Enchantments – Try It Online")
Heavily leverages Runic's ability to handle multiple instruction pointers simultaneously. What's one quine doubled? Why, one quine twice as long.
All the `.` commands are how the basic quine expression `"'<~S@|` can be expanded to be of arbitrary width. Additional copies of the quine expand the square vertically. Newlines and output are handled by the last line, funneling all of the quine IPs to a single terminator expression, following `Rak@`, which pushes a newline character, then dumps the entire stack top to bottom to output. The last line itself also produces a line of output, `.@kaR<00`, in order to maintain the requisite structure size. As the last line outputs first, there is no leading or trailing newline.
There are shorter quines (namely `'<~@|"`), however the last line is hard-limited to 7 characters, or it cannot produce output of the correct width (`@"<Rak` is 6 characters long, but outputs only 5 characters).
I also attempted to code the *smallest* possible square. This was the best I could do.
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), n=6
```
\>1CYS
\:$1Xk
\:$S:$
\S:$S:
\$S:$S
\:$q:@
```
[Try it online!](https://tio.run/##KyrNy0z@/z/GztA5MpgrxkrFMCIbRAVbqXDFBINorhgQByxXaOXw/z8A "Runic Enchantments – Try It Online")
Repeatedly clones the top of the stack, prints it, and swaps the top two items in order to print `100000` six times with 5 interwoven newlines.
And then, because I could:
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), n=9
```
\>311+6Xk
\w421+akw
\"'{~Sak"
\"@|."'"S
\q:1K1K1K
\1K1K1K1K
\1K1K1KE:
\E:E:E:1K
\311++*E;
```
[Try it online!](https://tio.run/##KyrNy0z@/z/GztjQUNssIpsrptzEyFA7MbucK0ZJvbouODFbCchyqNFTUlcK5ooptDL0BkGuGAiNYLlaccW4WoEgSAxknLaWq/X//wA "Runic Enchantments – Try It Online")
9x9 square program that outputs a 9x9 square quine (with leading newline).
This is accomplished by creating the 9-byte quine as a string and then `E`val'ing it 4 times, then multiplying the string by 5 (`"abc"*3` -> `"abcabcabc"`) and Evaling one more time for the last 5 copies. This is done this way in order to fill the 9x9 square right to the brim.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), n = 5
```
Do[1+
Echo[
+100*
+100]
,5*1]
```
Outputs
```
>> 10000
>> 10000
>> 10000
>> 10000
>> 10000
```
Assume that you does not count `>>` that would be shortest because only printing function is `Print` and `Echo`. Also you have to put at least 1 character after the function to call it.
```
Map[1+
Print@
#+10&,
Array[
9^6+1+
#&,6]]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/983sSDaUJsroCgzr8SBS1nb0EBNh8uxqCixMprLMs5MGyinrKZjFhv7/z8A "Wolfram Language (Mathematica) – Try It Online")
Outputs
```
531443
531444
531445
531446
531447
531448
```
with a trailing newline
## n = 7
```
Print/@
Array[0
+0+0+0+
0+0+0+0
+0+0+0+
1234557
+10&,7]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvRN@By7GoKLEy2oBL2wAMuSAUgm9oZGxiamrOpW1ooKZjHvv/PwA "Wolfram Language (Mathematica) – Try It Online")
Outputs
```
1234567
1234567
1234567
1234567
1234567
1234567
1234567
```
with a trailing newline
[Answer]
# Perl 5, 9x9
```
for(1..$=
/7){$qq=(
$q=$_)**7
;for($qq%
7..$q/7){
map{print
qq,qqq,,,
qq,qqqqqq
,,}0..2}}
```
### Explanation
The outer `for` loop is over the sequence `1 .. ($= / 7)`. [$=](https://perldoc.perl.org/perlvar.html#Variables-related-to-formats) is 60, so the loop runs from 1 to the floor of 60/7, which is 8.
The first statement in the outer loop, `$qq = ($q=$_)**7`, assigns the variable `$q` the value of the index `$_` of the loop, and assigns `$qq` the value `$q` to the seventh power.
Then comes the inner loop, which is over the sequence `$qq % 7 .. $q / 7` (`%` is modulo).
```
For this value of $q, the inner loop is over this sequence:
1 1 .. 0
2 2 .. 0
3 3 .. 0
4 4 .. 0
5 5 .. 0
6 6 .. 0
7 0 .. 1
8 1 .. 1
```
Thus the inner loop runs three times in total: twice when the outer loop index is 7, and once when the outer loop index is 8.
The inner loop does `map{...} 0..2` which is another loop, this time over the sequence `0 .. 2`, so it does the following three times:
```
print
qq,qqq,,,
qq,qqqqqq
,,
```
[The `qq`s are the double-quote operator](https://perldoc.perl.org/perlop.html#Quote-Like-Operators), so this just prints `qqq` and `qqqqqq<newline>`.
Thus, the output is
```
qqqqqqqqq
qqqqqqqqq
qqqqqqqqq
qqqqqqqqq
qqqqqqqqq
qqqqqqqqq
qqqqqqqqq
qqqqqqqqq
qqqqqqqqq
```
[Try it online.](https://tio.run/##K0gtyjH9/z8tv0jDUE9PxZZL31yzWqWw0FaDS6XQViVeU0vLnMsaJA0UVOUyB6opBCnhyk0sqC4oyswr4Sos1CkEYh0dKAsIuHR0ag309Ixqa///BwA)
] |
[Question]
[
Create a program to display some approximation of a [bell curve](http://en.wikipedia.org/wiki/Gaussian_function). You are free to use whatever method you wish for generating the data, but the data must be displayed vertically, as in oriented like so:
[](http://upload.wikimedia.org/wikipedia/commons/0/06/De_moivre-laplace.gif)
Other restrictions:
* Your code must create the approximation, that is, don't hardcode or take data from the internet.
* The shape must actually look like a bell.
This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so be creative.
[Answer]
# Java
The method of generation is based off of the game [*Sugar, Sugar*](http://armorgames.com/play/10638/sugar-sugar). In that game, sugar particles fall, traveling randomly left and right. In my program, `Dust` objects fall until they hit the ground. I collect data based on where they land; this is the bell curve:
```
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.Stack;
import javax.imageio.ImageIO;
/**
*
* @author Quincunx
*/
public class ApproxBellCurve {
public static final int NUM_DUST = 10_000_000;
public static final int NUM_THREADS = Runtime.getRuntime().availableProcessors() - 1;
public static final int LOOP_LIMIT = NUM_DUST / (NUM_THREADS + 1);
public static void main(String[] args) {
BufferedImage output = new BufferedImage(2049, 2049, BufferedImage.TYPE_INT_RGB);
Stack<Thread> threads = new Stack();
for (int i = 0; i < NUM_THREADS; i++) {
threads.push(new Thread(new Duster()));
threads.peek().start();
}
Dust d;
Random r = new Random();
for (int i = 0; i < LOOP_LIMIT + NUM_DUST - (LOOP_LIMIT * (NUM_THREADS + 1)); i++) {
d = new Dust(r);
while (!d.end) {
d.step();
}
if ((i & 1024) == 0) {
r = new Random();
}
}
while (threads.size() > 0) {
try {
threads.pop().join();
} catch (InterruptedException ex) {
}
}
int maxy = 0;
for (int x = 0; x < Dust.data.length; x++) {
maxy = Dust.data[x] > maxy ? Dust.data[x] : maxy;
}
for (int x = 0; x < Dust.data.length; x++) {
for (int y = 0; y < output.getHeight(); y++) {
output.setRGB(x, y, (y >= output.getHeight() - (Dust.data[x] * output.getHeight() / maxy)) ? 6591981 : 16777215);
}
}
try {
ImageIO.write(output, "png", new File("Filepath"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static class Duster implements Runnable {
@Override
public void run() {
Dust d;
Random r = new Random();
for (int i = 0; i < LOOP_LIMIT; i++) {
d = new Dust(r);
while (!d.end) {
d.step();
}
if ((i & 1024) == 0) {
r = new Random();
}
}
}
}
private static class Dust {
public static int[] data = new int[2049];
static {
for (int i = 0; i < data.length; i++) {
data[i] = 0;
}
}
private int[] location;
private Random r;
public boolean end;
public Dust(Random rand) {
location = new int[]{1024, 0};
r = rand;
end = false;
}
public void step() {
if (end) {
return;
}
if (location[1] >= 1024) {
end = true;
synchronized (data) {
data[location[0]] += 1;
}
return;
}
location[1] += 1;
location[0] += r.nextInt(21) - 10;
}
}
}
```
Sample output (took 1 minute to create):

Because of the nature of the random number generation, it is possible to get an `ArrayIndexOutOfBoundsException`.
I used multithreading to speed up the process. The program determines the number of processors available and creates that many threads to run the simulations.
To obtain a finer image, `NUM_DUST` can be increased, but that would also lead to an increased risk of an `ArrayIndexOutOfBoundsException`.
Each thread creates a new `Random` after every 1024 `Dust` objects are simulated. When that code was removed, the image was more coarse.
`rand.nextInt(21) - 10` is to widen the distribution. A change to `rand.nextInt(3) - 1` would remove all chance of an `ArrayIndexOutOfBoundsException`.
[Answer]
## Mathematica
I decided it should not only look like a bell curve, it should look like a bell. So hey, let's spin it around the Z-axis and make it 3D.
And hey, while we're at it, it should *sound* like a bell as well.
So, each time you evaluate the code, it makes a nice pleasing [church-bell BWONNGGG!](http://youtu.be/x54Rbreryic)
```
Manipulate[
RevolutionPlot3D[PDF[NormalDistribution[mu, sigma], x], {x, -4, 4},
PlotRange -> {Automatic, Automatic, Automatic},
BoxRatios -> {1, 1, 1}, PlotStyle -> {Orange, Yellow},
ImageSize -> {500, 500}], {{mu, 0, "mean"}, -3, 3,
Appearance -> "Labeled"}, {{sigma, 1.47, "standard deviation"}, .5,
2, Appearance -> "Labeled"}]
EmitSound[Sound[SoundNote[0, 3, "TubularBells", SoundVolume -> 1]]]
```
Here's what it looks like:

And here's a [brief video of the bell ringing](http://youtu.be/x54Rbreryic).
[Answer]
## Haskell, 9 LoC
Everyone's code is so ... huge, and their approximations are ... less than deterministic. Just to remind everyone of the simplicity of the actual task, here's a nine-liner in Haskell:
```
import Data.List; import Data.Ratio
main = do
putStrLn "please choose the width and the maximum height:"
[w, mh] <- (map read.words) `fmap` getLine
let dist = map length $ group $ sort $ map length $ subsequences [2..w]
scale = ceiling $ maximum dist % mh
maxD = scale * ceiling (maximum dist % scale)
putStrLn $ unlines $ map (row dist) [maxD, maxD - scale .. 0]
where row dist y = map (\x -> if x >= y then '*' else ' ') dist
```
OK... that wasn't exactly fast. Here's another go. Does it still count as not hard-coded?
```
import Data.List; import Data.Ratio
main = do
putStrLn "please choose the width and the maximum height:"
[w, mh] <- (map read.words) `fmap` getLine
let dist = map ((w-1) `choose`) [0..(w-1)]
scale = ceiling $ maximum dist % mh
maxD = scale * ceiling (maximum dist % scale)
putStrLn $ unlines $ map (row dist) [maxD, maxD - scale .. 0]
where row dist y = map (\x -> if x >= y then '*' else ' ') dist
factorial x = product [1..x]
n `choose` k = factorial n `div` factorial k `div` factorial (n-k)
```

[Answer]
## Wolfram Alpha (tongue-in-cheek) 4 bytes:
Here is a practical application of the Central Limit Theorem. I even golfed it!
Type this into the input box on Wolfram Alpha:
```
3d20
```
[Here](https://www.wolframalpha.com/input/?i=3d20) is a link to the results. It interprets this input as 3 icosahedral dice, and decides you want a graph of the distribution function of the pip sums. It prints the following graph:

We can make the graph more and more bell shaped by adding more dice. I don't see this as taking my data from the internet since, if I could run the query engine for it on my home computer I would. Unfortunately, Wolfram Research doesn't provide it for download, though.
[Answer]
# Ruby
Simulates the classic example of bell curves, dropping a ball down a grid full of pole thingies.
```
a = [0]*30
1000.times do
x = 15
49.times do
x += (rand(3) - 1)
end
a[[[x.to_i, 29].min, 0].max] += 1
end
until a.all?{|x| x == 0}
a.each_with_index{|x,i|
if x == 0
print ' '
else
print 'x'
a[i] -= 1
end
}
puts
end
```
Sample output:
```
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx
x xxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxx
xxxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxx
xxxxxxxxxxx
xxxxxxxxxxx
xxxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxx xx
xxxxxxx xx
xxxxxxx xx
xxxxxx xx
xxxxxx xx
xxxxxx x
xxxxx x
xxxxx x
xxx x
xxx x
xxx x
xxx x
xxx x
xxx
xxx
xxx
xxx
xxx
xxx
xxx
xxx
xxx
x x
x x
x x
x x
x
x
x
```
Oh, did I forget to mention it's upside down?
[Answer]
## Python
```
from pygame import*
t,u=640,400;init();d=display;s=d.set_mode((t,u))
s.fill(0xFFFFFF)
for x in range(t):
d.flip();event.get()
draw.line(s,u,(x,int(u-2**(-((x-t*.5)/120)**2)*u)),(x,u))
while time.wait(50):
for e in event.get():
if e.type==QUIT:exit()
```
This is actually a normal distribution, using *2* as the base of the exponent instead of *e*, and not dividing by *⎷2π*, because without axes, it doesn't really matter if the area under the curve isn't exactly *1*.

The last 3 lines just keep the window open until the user closes it manually.
[Answer]
# Mathematica
Generating the sums of 5 random integers, each between 0 and 100, 20000 times.
```
Histogram[Plus @@@ RandomInteger[100, {20000, 5}]]
```

---
Here's the result for sums of 1,2, 3 numbers. As the number of integers to be summed increases, the curve approaches the bell shape.
When single random integers are generated, but not summed, the distribution should be fairly uniform, not favoring any value. The apparent anomaly for 100 may be the result of how Matheamtica bins data. (see <https://mathematica.stackexchange.com/questions/43300/does-randominteger0-n-disfavor-n/43302#43302> )
```
Table[Histogram[Plus @@@ RandomInteger[100, {20000, k}]], {k, 1, 3}]
```

[Answer]
## C#, WPF
Rough approximation with a hand-crafted Bézier curve. To make it more interesting: No use of `Line`, `Path` or similar, only `Ellipse`.

```
public MainWindow()
{
InitializeComponent();
// Requires a Canvas named Canvas in XAML file
DrawBellCurve(Canvas, 300, 300);
}
public static void DrawBellCurve(Canvas canvas, int width, int height)
{
Point p1 = new Point(0, height);
Point p2 = new Point(0.3 * width, 1 * height);
Point p3 = new Point(0.4 * width, 0.1 * height);
Point peak = new Point(width / 2, 0);
Point p3r = new Point(width - p3.X, p3.Y);
Point p2r = new Point(width - p2.X, p2.Y);
Point p1r = new Point(width, height);
List<Point> controlPoints = new List<Point> { p1, p2, p3, peak, p3r, p2r, p1r };
DrawBezierCurve(canvas, controlPoints, Color.FromRgb(50, 200, 25));
DrawPoints(canvas, controlPoints, 5, Color.FromRgb(80, 80, 220));
}
public static void DrawPoints(Canvas canvas, List<Point> points, double radius, Color color)
{
foreach (var p in points)
{
Ellipse ellipse = new Ellipse();
ellipse.Width = radius;
ellipse.Height = radius;
ellipse.SetValue(Canvas.LeftProperty, p.X - radius / 2);
ellipse.SetValue(Canvas.TopProperty, p.Y - radius / 2);
ellipse.Fill = new SolidColorBrush(color);
canvas.Children.Add(ellipse);
}
}
public static void DrawBezierCurve(Canvas canvas, List<Point> controlPoints, Color color)
{
var curvePoints = new List<Point>();
double tStep = 0.01;
for (double t = 0; t <= 1; t += tStep)
{
curvePoints.Add(GetBezierPoint(controlPoints, t));
}
DrawPoints(canvas, curvePoints, 3, color);
}
public static Point GetBezierPoint(List<Point> controlPoints, double t)
{
// De Casteljau's algorithm
if (controlPoints.Count == 1)
{
return controlPoints[0];
}
var newControlPoints = new List<Point>();
for (int i = 0; i < controlPoints.Count - 1; i++)
{
Point p1 = controlPoints[i];
Point p2 = controlPoints[i + 1];
Point p = new Point(
t * p1.X + (1 - t) * p2.X,
t * p1.Y + (1 - t) * p2.Y);
newControlPoints.Add(p);
}
return GetBezierPoint(newControlPoints, t);
}
```
[Answer]
# Java 8
It gets the height and the width from the user, chooses `width` random booleans and count how many are true, registering the counted frequency. Repeat this until some of the generated frequencies is enough to fill the height:
```
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Bell {
public static int[] bell(int width, int height) {
// I could have used Random.nextGaussian() method, but this way is more fun.
Random r = new Random();
int max = 0;
int[] freqs = new int[width];
for (int j = 0; max < height - 1; j++) {
int count = 0;
for (int i = 0; i < width; i++) {
if (r.nextBoolean()) count++;
}
freqs[count]++;
if (freqs[count] > max) max++;
}
return freqs;
}
public static BufferedImage drawBell(int[] ps, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < width; i++) {
for (int j = 0; j < ps[i]; j++) {
bi.setRGB(i, height - j - 1, 0xFF00FFFF); // Cyan
}
for (int m = i - 1; m <= i + 1; m++) {
if (m < 0 || m >= width) continue;
for (int n = ps[i] - 1; n <= ps[i] + 1; n++) {
if (n < 0 || n >= height) continue;
bi.setRGB(m, height - n - 1, 0xFF0000FF); // Blue
}
}
for (int j = ps[i] + 1; j < height; j++) {
bi.setRGB(i, height - j - 1, 0xFFFFFFFF); // White
}
}
return bi;
}
public static void main(String[] args) {
String a = JOptionPane.showInputDialog("Give the width:");
String b = JOptionPane.showInputDialog("Give the height:");
int w, h;
try {
w = Integer.parseInt(a);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid width.");
return;
}
try {
h = Integer.parseInt(b);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid height.");
return;
}
int[] freqs = bell(w, h);
BufferedImage image = drawBell(freqs, w, h);
EventQueue.invokeLater(() -> {
JFrame j = new JFrame("Bell curve");
j.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
j.add(new SimpleSprite(image));
j.setResizable(false);
j.pack();
j.setVisible(true);
});
}
public static class SimpleSprite extends JComponent {
private final BufferedImage image;
private final Dimension dim;
public SimpleSprite(BufferedImage image) {
this.image = image;
this.dim = new Dimension(image.getWidth(), image.getHeight());
}
@Override
public Dimension getMinimumSize() {
return dim;
}
@Override
public Dimension getMaximumSize() {
return dim;
}
@Override
public Dimension getPreferredSize() {
return dim;
}
@Override
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
}
}
```
Screenshot:

[Answer]
## GeoGebra
I don't know whether it is valid to use an application that is made to draw graphs, but if you enter this in the input, you get a Bell Curve:
```
f(x) = 3ℯ^(-(x - 1)²)
```
Or, if you want a customizable bell curve:
```
a = 0
b = 0
c = 0
d = 0
f(x) = a ℯ^((-(x - b)²) / 2 c²) + d
```
Then, make sure that you enable the sliders for the variables (if they are disabled, click on the circle next to the variable names). Then, you can set a value for them by sliding.
Image of the curve with the sliders (click to enlarge):
[](https://i.stack.imgur.com/pcRql.png)
[Answer]
## Java
Throwing 6 dice in every possible combination approaches a 'normal distribution', which happens to be a bell curve.
```
public class Temp {
public static void main(String[] args) throws Exception {
int[] hist = new int[31];
for (int d1 = 0; d1 < 6; d1++)
for (int d2 = 0; d2 < 6; d2++)
for (int d3 = 0; d3 < 6; d3++)
for (int d4 = 0; d4 < 6; d4++)
for (int d5 = 0; d5 < 6; d5++)
for (int d6 = 0; d6 < 6; d6++)
hist[d1 + d2 + d3 + d4 + d5 + d6]++;
for (int y = 4104; y >= 0; y -= 228)
for (int x = 0; x < 32; x++)
System.out.print(x == 31? '\n' : hist[x] <= y? '\u3000' : (char)('\u2580' + Math.min(Math.ceil((hist[x] - y) / 28.5), 8)));
}
}
```
Some Unicode tricks make the output smoother:
```
▅█▅
▂███▂
█████
▁█████▁
███████
███████
▅███████▅
█████████
█████████
▇█████████▇
███████████
▃███████████▃
█████████████
▁█████████████▁
███████████████
▃███████████████▃
█████████████████
▁███████████████████▁
▁▁▁▂▅█████████████████████▅▂▁▁▁
```

[Answer]
# Python and tkinter
I liked Doorknob's generation method and Victor's output (his generation is actually equivalent), so I decided to combine the two with tkinter!
```
from tkinter import *
import random
bins = [0]*201
for i in range(20000):
x = 0
for j in range(100):
if random.randint(0, 1):
x += 0.5
else:
x -= 0.5
bins[int(x)+100] += 1
master = Tk()
w = Canvas(master, width = 201, height=200)
w.pack()
for i in range(201):
w.create_line(i, 200, i, 200-bins[i]/10, fill="light blue")
w.create_line(i-1, 200-bins[i-1]/10, i, 200-bins[i]/10, fill="blue")
```

[Answer]
# C
Based on random walks
```
#include <stdio.h>
#include <stdlib.h>
#define X_SIZE 40
#define Y_SIZE 15
#define SMOOTH 100
int main(void)
{
int i,j;
int T[X_SIZE*2];
int w;
for (i=0; i<X_SIZE*2; i++) T[i]=0;
// random walks
do {
w=X_SIZE;
for (i=0;i<X_SIZE;i++)
w+=rand()%2?1:-1;
T[w]++;
}
while (T[w]<Y_SIZE*SMOOTH);
// display
for (j=Y_SIZE; j>=0; j--)
{
for (i=0; i<X_SIZE*2; i+=2)
printf("%c", (T[i]>j*SMOOTH)?'#':' ');
printf("\n");
}
}
```
Output :
```
###
###
#####
#####
#####
#######
#######
#########
#########
#########
###########
###########
#############
###############
#######################
```
[Answer]
# J
```
load 'plot'
plot (3+i.58)([:+/=)"0 1]3+([:+/?,?,?)"0]1e6#20
```
Not very creative, but still fun!
Throws three twenty sided dice 1000000 times, summing the result each time. Then to get it in a `plot`-ready format, we take the array `[3..60]` and replace each element by the number of times it occures in the random sums.
`plot` then creates a PDF:
[](https://i.stack.imgur.com/PkCl0.png)
[Answer]
# Octave
```
c=79;
x=ifft(fft([ones(1,10) zeros(1,c-10)]).^8);
y=(1:c)*0+' ';
for l=-24:-1,
for k=1:c,
if -real(x(k))<l*2e5,
y(k)='*';
end
end
printf([char(y) '\n'])
end
```
[Try it online!](https://tio.run/##NYzRCsIwDEXf@xV5azJXWYeibvZLpsKoLY6NVuqQzZ@vLeJDQs494Xo9928To1aHU8sWNVg7Y57OO/NCWcqK4GOCz7cWia60vR2pZatC2Wgqqg0H3jLrA0xK1LtGyJIBZB5V@sgAMFgQwfQTLjgSnaeiNvufAVhTpHiRSjIZd2f//QyDmy12@tEHXAn4xfErsSRj/AI "Octave – Try It Online")
Instead of directly simulating coin flips, this just uses the observation that the pdf of a sum of random variables is the convolution of the pdfs of each of the random variables. An efficient way to do circular convolution is to take the inverse fourier transform of the element-wise product of the fourier transforms of the pdfs of each of the random variables. For the purpose of this problem (not true in general) circular convolution can stand in for linear convolution.
As an example, given the following pdf of a uniform random variable.
```
**********
**********
**********
**********
**********
**********
**********
**********
**********
**********
**********
**********
```
The above random variable summed with itself
```
*
***
***
*****
*******
*********
***********
***********
*************
***************
*****************
*******************
```
The uniform random variable summed with itself 7 times.
```
*
*******
***********
*************
***************
*****************
*******************
***********************
*************************
***************************
*******************************
*************************************
```
[Answer]
## Python (Box-Muller) - 6 lines
This short code uses the Box-Muller transform for simulating a normally distributed variable:
```
from math import cos, log, pi
from random import random
f = open("normDist.txt",'w')
for i in xrange(10**6):
f.write(str(cos(2*pi*random())*(-2*log(random()))**.5)+'\n')
f.close()
```
You can plug the values on GNUPLOT or use this script
```
f=open("normDist.txt",'r')
v = [0 for i in xrange(51)]
for i in f:
v[int(float(i)*10) if float(i)<5 and float(i)>-5 else 0]+=1
m=0
for i in v:
if i>m:
m=i
for i in v[3:]:
for j in xrange(int(70.*i/m)):
print '*',
print
```
to produce something like this:
```
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* * *
* *
* *
* *
* *
* *
* *
* * *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
```
[Answer]
# awk
```
#!/ust/bin/awk -f
BEGIN {
#
# do WALKS random walks with OOPS times left or right per walk
#
WALKS=100000
OOPS=39
#
# output will be H lines
# the line width will be 2*OOPS+1
#
H=23
#
# shake awk's pseudorandom generator
#
srand()
#
# do the walks
#
for(i=0;i<WALKS;i++) {
x=0
for(j=0;j<OOPS;j++) rand()<0.5?--x:++x
X[x]++
}
#
# scan for maximum height
#
M=0
for(x=-OOPS;x<=OOPS;x++) {
if(X[x]>M) M=X[x]
}
#
# "draw" into S[x]: strings of H*X[x]/M "*"s
#
for(x=-OOPS;x<=OOPS;x++) {
s=sprintf("%*s",H*X[x]/M," ")
gsub(/./,"*",s)
S[x]=s
}
#
# print S[x] transposed
#
for(y=H;y>0;y--) {
for(x=-OOPS;x<=OOPS;x++) {
if(c=substr(S[x],y,1)) printf c
else printf " "
}
print ""
}
}
```
Output:
```
*
* *
* *
* * * *
* * * *
* * * *
* * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * *
*******************************************************************************
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 20 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
⌐∞¶J♠fr"▐cS╥aÆ~a╚∩┌I
```
[Run and debug it](https://staxlang.xyz/#p=a9ec144a06667222de6353d261927e61c8efda49&i=&a=1)
This isn't code-golf but I still want to give Stax a try. Calculates frequency of sum of dices rolled 6 times. Note there are no support for random numbers in Stax.
ASCII equivalent:
```
6R6|^{|+m{o:G{AJ/'**mMrm
```
Output:
```
*
***
***
***
*****
*****
*****
*****
*****
*******
*******
*******
*******
*******
*******
*********
*********
*********
*********
*********
*********
***********
***********
***********
***********
***********
***********
*************
*************
*************
*************
*************
***************
***************
***************
***************
*****************
*****************
*****************
*******************
*******************
*********************
***********************
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal)
```
≔⟦Xφ±⁹⟧θF⁹⁹≔E⊞Oθ⁰⁺κ§θ⊖λθ↑θ
```
Verbose version:
```
Assign([Power(1000, Negate(9))], q);
for (99) Assign(Map(PushOperator(q, 0), Plus(k, AtIndex(q, Decremented(l)))), q);
Print(:Up, q);
```
[Try it online!](https://tio.run/##LYy9DsIgFEZ3n@KOlwQTHNGpiYuDyuJkHAi9to0U6IWqb4@/33ZOTj7XW3bR@lqbnIcu4NnEBzGulFISDtTZQqiFuEiYxGZxjQyotYB/vbcJzZz7YyK2JTJOEpSQYPyc8SahKbvQ0vOjt@SYRgqFWvTivd@j4SEUXJ/SF2uty7t/AQ "Charcoal – Try It Online") Output:
```
||
||
||||
||||
||||
||||
||||||
||||||
||||||
||||||
||||||
||||||||
||||||||
||||||||
||||||||
||||||||
||||||||
||||||||||
||||||||||
||||||||||
||||||||||
||||||||||
||||||||||
||||||||||||
||||||||||||
||||||||||||
||||||||||||
||||||||||||
||||||||||||
||||||||||||||
||||||||||||||
||||||||||||||
||||||||||||||
||||||||||||||
||||||||||||||||
||||||||||||||||
||||||||||||||||
||||||||||||||||
||||||||||||||||
||||||||||||||||||
||||||||||||||||||
||||||||||||||||||
||||||||||||||||||||
||||||||||||||||||||
||||||||||||||||||||
||||||||||||||||||||||
||||||||||||||||||||||
||||||||||||||||||||||||
||||||||||||||||||||||||||
||||||||||||||||||||||||||||
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 7 years ago.
[Improve this question](/posts/17511/edit)
Write a mathematical function that results in an integer representation of "hello world"
For example "hello world" in hex is `68656c6c6f20776f726c64` so the goal will be to write a mathematical program that results in a number representing "hello world".
Here is a example of a possible solution using python:
```
print(2*2*3*59*61*97*416510539*72330832279)==int("68656c6c6f20776f726c64", 16)
```
Any type of mathematical equations could be used, such as: powers, series, factorials, and other mathematical operations.
**The rules:**
* You may select your own way to encode/represent "hello world" as an integer. Hash functions are also allowed
* Mathematical libraries (e.g. numpy, GMP) are allowed.
* The intention is to focus on the mathematics part
[Answer]
I'll do better than just printing it, I'll print it infinitely many times!
The rational number
```
1767707668033969 / 3656158440062975
```
returns the following base-36 expansion:
```
0.helloworldhelloworldhelloworldhelloworldhelloworld...
```
[Try it out! (Wolfram Alpha)](http://www.wolframalpha.com/input/?i=1767707668033969%2F3656158440062975+in+base+36)
Or, if you want a more subliminal message, try:
```
2399843759207982499621172523113947162810942763812298565948669
/ 1357602166130257152481187563160405662935023615
```
Which returns (again in base 36):
```
helloworld.helpimtrappedinanumberfactoryhelpimtrappedinanumberfactoryhelpimtrappedinanumberfactory...
```
If your program worked with only integers, you'd never see the fractional part.
[Answer]
**Python 2.7**
Some abuse of the random number generator, works on Python 2.7 but not Python 3.x since the generator seems to have changed the seeding algorithm;
```
>>> import random
>>> n=[(15,30,15,25,15,0,-15,-25,-15,-30,-15),(107,35,34,26,22,0,71,188,94,64,81)]
>>> random.seed(4711)
>>> m = zip("MERRY CHRISTMAS",*n)
>>> print(''.join(map(lambda x:chr(ord(x[0])+random.randint(x[1],x[2])),m)))
hello world
```
[Answer]
# Python ~~(not finished... yet!)~~ finished! :D
```
number = ((sum(b'This text will end up converting to the text "hello world" by a bunch of math.') *
sum(b'For example, multiplication will be used to increase the number so that it may reach the required result.') *
sum(b'Wow, double multiplication! The required result number is extremely big so I have to use lots of math to get there.') *
sum(b'TRIPLE multiplication?!?!?! Wow!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Did I put too many exclamation points?') *
sum(b'I think maybe I might have put too many exclamation points, oops. :(') *
sum(b'This is taking a long time...') *
sum(b'A very, very, very long time...')) // 2)
number -= (sum(b'Okay, the number is a bit too high. Blah. This is extremely hard.') *
sum(b'I need to reduce it. I will just keep multiplying again! Yay! That seems effective!') *
sum(b'I don\'t know what to write now... I used up all my creativity in the previous number.') *
sum(b'So. Uhhh, how has your day been? Was it good? I wonder how many people are still reading.') *
sum(b'Gah! There is nothing to type about anymore! I will just type randomness then.') *
sum(b'Do you like pie? I like pie. Refrigerator. The chicken ate the potato. Llamas are not tasty.'))
number -= (sum(b'Blah, I am still a tiny bit too high!') *
sum(b'This is very frustrating!') * sum(b'Argh!!!!!!!') *
sum(b'I have even less creative ideas now since I have written two paragraphs already.') *
sum(b'Well, I suppose they\'re not paragraphs. They\'re just blocks of code.') *
sum(b'The only reason I made that remark was to increase this number to subtract, so that I reach my target.'))
number -= (sum(b'I am an extremely miniscule amount over the target!!!') *
sum(b'I am so close!!! So close!!') *
sum(b'I must make it!!! I will!!!') *
sum(b'I shall NEVER give up!!!') *
sum(b'Okay, ummm... maybe not exactly "never"...') *
sum(b'I mean, this is REALLY hard...'))
number -= (sum(b'I am so close. This is just ridiculous.') *
sum(b'Just ridiculous. And that\'s awesome :D') *
sum(b'Why am I doing this?!?') *
sum(b'The answer\'s probably "becase I can."') *
sum(b'Notice how most of the text in this program is meaningless.'))
number -= (sum(b'How have I been above my target this whole time? That is very odd.') *
sum(b'I wonder how much time I could have saved if I removed a few characters in the first block.') *
sum(b'I wish I did that. That would have made it so much easier.... But oh well.') *
sum(b'Well, I am really really really really really really close now!'))
number -= (sum(b'I am so close!') *
sum(b'I will never give up now! Not after all this!') *
sum(b'I wonder if I will ever get exactly on the target. What if I do, and then discover a typo? :O') *
sum(b'So close!'))
number -= (sum(b'Wow; this is the eighth block. That\'s a lot of blocks!') *
sum(b'I only have a little more to go! I must finish! I will!') *
sum(b'It is starting to get harder thinking of things to type than it is getting to the target...'))
number -= (sum(b'These strings are short') *
sum(b'So the number to subtract is less') *
sum(b'Hi'))
number += (sum(b'Finally adding') *
sum(b'That\'s new') *
sum(b':D'))
number -= (sum(b'I am back to subtraction, and also longer strings.') *
sum(b'But this time I only get two strings!'))
number -= (sum(b'I have switched over to adding the strings, not multiplying them!') +
sum(b'I am really really close! So close that I can\'t even multiply two strings to subtract anymore!') +
sum(b'This is very exciting; I\'ve nearly made it! Only a few more strings to add...') +
sum(b'I ran out of ideas for what to type again... I will just type exactly what I am thinking, which is what I am doing now actually.') +
sum(b'But now the only thing I am thinking about is getting to the target, and there is not much about that to type...') +
sum(b'I am only a few thousand away!!!!!!!!!!!!'))
number += 8 # NOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
print(number)
```
Outputs `126207244316550804821666916` (equivalent to your example, `0x68656c6c6f20776f726c64`)
[Answer]
>
> You may select your own way to encode/represent "hello world" as an integer.
>
>
>
Well, then...
## PHP
```
<?=1?>
```
where 1 represents "hello world" because I said so.
[Answer]
# Calculator Font / FreePascal
I may get into trouble for posting this, but I'll do it anyway :-)
1. Calculate 7734/100000. Change the leading zero to blue, and the other digits to calculator font. Turn it upside down. The blue O represents the world:

If that's too lazy, how about this:
```
uses graph;
var gd, gm : integer;
var n,m:integer;
begin
gd := D4bit;
gm := m640x480;
initgraph(gd,gm,'');
setcolor(black);
For n:=0 to 5 do for m:=0 to 3 do begin;
setfillstyle(solidfill,(abs(n*2-1)));
if(($967EEF shr (20-n*4+m)) and 1) = 1
then sector(50+n*80,100,90*m,90*(m+1),40,60);
if(($EDF7E9 shr (20-n*4+m)) and 1) = 1
then sector(50+n*80,300,90*m,90*(m+1),40,60);
end;
readln;
closegraph;
end.
```

circles numbered 0-5, colour determined by abs(2n-1). One hex digit per circle, quadrants coloured from most significant bit downwards, clockwise from bottom right. By the mystic constants 967EEF and EDF7E9 hex.
Special thanks to the following primitive, and to Borland for putting it in TurboPascal so that FreePascal could clone it.
*procedure Sector(
x: SmallInt;
y: SmallInt;
StAngle: Word;
EndAngle: Word;
XRadius: Word;
YRadius: Word
);
Sector draws and fills a sector of an ellipse with center (X,Y) and radii XRadius and YRadius, starting at angle Start and ending at angle Stop.*
[Answer]
## Ruby & Python
Using base 36 math, we arrive at an integer representation quite easily in Ruby & Python:
---
**Ruby**
```
%w(hello world).map{|n|n.to_i(36)}
```
result:
```
[29234652, 54903217]
```
or, expressed as a general function:
```
def f(words); words.split.map{|n|n.to_i(36)}; end
```
example:
```
f("hello world")
=> [29234652, 54903217]
```
---
**Python**
```
def f(words): return map(lambda n: int(n,36), words.split())
```
example:
```
>>> f("hello world")
[29234652, 54903217]
```
[Answer]
Some carefully crafted PHP:
```
$x=18306744;
$w=($z=($y=30)/3)/2;
echo base_convert($x, $z, $y+$z/$w),chr($y+$z/$w).base_convert($x*($y/$z)-$w*41*83,$z,$y+$y/$w);
```
[Answer]
# R6RS Scheme
```
#!r6rs
(import (rnrs))
(define (hello-world)
(bitwise-xor (fold-left (lambda (acc d)
(+ (* acc 256)
(+ (bitwise-and 255 acc) d)))
104
'(-3 7 0 3 8 0 -8 3 -6 -8))
(bitwise-arithmetic-shift 87 40)))
```
Outputs #x68656c6c6f20776f726c64 (in decemal):
```
126207244316550804821666916
```
My original implementation was:
# Racket (Scheme dialect)
```
(define (hello-world)
(bitwise-xor (foldl (lambda (d acc)
(+ (* acc 256)
(+ (bitwise-and 255 acc) d)))
104
'(-3 7 0 3 8 0 -8 3 -6 -8))
(arithmetic-shift 87 40)))
```
[Answer]
# JavaScript
```
function stringTheory(theory) {
var proof = 0;
var principles = theory.split(/[ ,.'-]/);
for (var i = 0; i < principles.length; i++) {
var formula = '';
for (var j = 0; j < principles[i].length; j++) {
formula += principles[i].charCodeAt(j).toString(10);
}
proof += +formula;
}
return proof;
}
console.log(
/* \2 and \3 are start of text and end of text characters */
stringTheory('\2 Yo it\'s 4327 - Go to space, look back, and see the dot of a small blue rock you once sat on amid the vast empty void - KA-BOOM - you are in awe of it. "Ah" - so tiny in this vast space yet you are even more so. A mere atom in an ocean of stars, the earth a speck of dust to the sun\'s ping-pong ball. One day you shall go back and as your toes touch the soft soil once more, the cool wind in your hair as you cast your gaze upon the moon, a mere rock just like this one, and bask in it\'s warm glow - Ah. Only then can you know the scale of it all, what luck you have to call this place home. And with this new ken, a love you\'ve kept for all of time but had not seen - for it is clear to you now. You lay open your arms and fill the air with your song - (aah) ~o Good-bye space and ... o? \3') + 42
);
```
### What is going on?
We take this string and apply a little `stringTheory()` (it is actually a transmission from the future):
`'\2 Yo it\'s 4327 - Go to space, look back, and see the dot of a small blue rock you once sat on amid the vast empty void - KA-BOOM - you are in awe of it. "Ah" - so tiny in this vast space yet you are even more so. A mere atom in an ocean of stars, the earth a speck of dust to the sun\'s ping-pong ball. One day you shall go back and as your toes touch the soft soil once more, the cool wind in your hair as you cast your gaze upon the moon, a mere rock just like this one, and bask in it\'s warm glow - Ah. Only then can you know the scale of it all, what luck you have to call this place home. And with this new ken, a love you\'ve kept for all of time but had not seen - for it is clear to you now. You lay open your arms and fill the air with your song - (aah) ~o Good-bye space and ... o? \3'`
First we split it at its punctuation to form words. We then create a set of numbers by converting the characters to their decimal ASCII code. Adjoined letters become adjoined numbers (e.g. `aa` becomes `9797`).
The numbers are then summed. What we get back is `191212222216169` an utterly useless number, it has no meaning, much like the quadrillions of rocks that float idly in space. What makes this world special? Why it is life. So by giving this number the [meaning of life](http://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#Answer_to_the_Ultimate_Question_of_Life.2C_the_Universe.2C_and_Everything_.2842.29) `+=42` then we get `191212222216211`;
### But why?
What does this mean? Why it means `stringTheory("Hello world")` of course.
[Answer]
# Python
```
from math import fsum
c=[104.,-4412.705557362921,12008.518259002305,-13041.051140948179,7566.060243625142,-2619.91695720304,567.427662301322,-77.52280096313,6.48776455347,-0.303552138602,0.006079144624]
def f(x):
return fsum([c[i]*x**i for i in range(len(c))])
s=""
for i in range(11):
s+=chr(int(round(f(i))))
print s
```
[Answer]
## Ruby
Any string is mapped to an integer.
```
# encode string to integer
def str_to_int(s)
i = 0
s.chars.each do |c|
i = i << 7 | c.ord
end
i
end
```
The inverse function:
```
# decode integer to string
def int_to_str(i)
s = ''
while i > 0 do
s = (i & 0x7f).chr + s
i = i >> 7
end
s
end
```
Examples:
```
str_to_int("ABC")
=> 1073475
int_to_str(1073475)
=> "ABC"
str_to_int("hello world")
=> 123720932638399026476644
int_to_str(123720932638399026476644)
=> "hello world"
```
[Answer]
**C#**
A method to convert any string (hello world or something else) to hexadecimal string
```
string Encode(string text)
{
string hexValue = String.Empty;
foreach(char c in text)
hexValue += String.Format("{0:X}", (int)c);
return hexValue;
}
```
A method to convert hexadecimal string to string
```
string Decode(string hexValue)
{
string text = String.Empty;
for (int i = 0; i < hexValue.Length; i += 2)
{
int value = Convert.ToInt32(hexValue.Substring(i, 2), 16);
text += (char)value;
}
return text;
}
```
Here goes the complete C# program
```
using System;
namespace ConsoleApplication1
{
class Program
{
static string Encode(string text)
{
string hexValue = String.Empty;
foreach(char c in text)
hexValue += String.Format("{0:X}", (int)c);
return hexValue;
}
static string Decode(string hexValue)
{
string text = String.Empty;
for (int i = 0; i < hexValue.Length; i += 2)
{
int value = Convert.ToInt32(hexValue.Substring(i, 2), 16);
text += (char)value;
}
return text;
}
static void Main(string[] args)
{
string Text1 = "Hello World!";
Console.WriteLine("Before Encoding: " + Text1 + "\n");
string Hex = Encode(Text1);
Console.WriteLine("After endoding: " + Hex + "\n");
string Text2 = Decode(Hex);
Console.WriteLine("After decoding: " + Text2 + "\n");
}
}
}
```
And here is the output.

[Answer]
## Python
```
def D(A):
try:
return sum(D(x)**2 for x in A)
except TypeError:
return A
print hex(D([[[[33,22,3,1],[20,13,2],5],[[31,19,1],[11,5,3],1]],[[[26,13],[18,14,6,4],1],[[12,10],[10,3,1],2],4],28]))
```
Recursively decomposes the target number into sums at most four squares. My base case is <100. I used <http://www.alpertron.com.ar/FSQUARES.HTM> to calculate the decompositions.
(Maybe a base case of <=1 would have been interesting...)
[Answer]
## Python
```
def church(i):
if i > 0:
return 'f(' + church(i-1) + ')'
else:
return 'x'
def church_string(bs):
import base64
return church(int(base64.b16encode(bs), 16))
print(church_string(b'hello world'))
```
The result really is a number, I swear!
[Answer]
Just a little C fun with numbers, nothing special.
```
int main()
{
int a , b, c;
double i = 0, f = 0;
for (; i < 1; i += .00000012785666)
f += cos(i);
c = f;
a = f * 276.393089;
b = a + f * 7.4358109;
printf("%.4s%.4s%.4s\n", &a, &b, &c);
}
```
[demo](http://rextester.com/ZPMV69656)
[Answer]
```
(+ 110145154154157040127157162154144 0)
```
] |
[Question]
[
A space cleaner is a special character which removes all spaces between it and the first non space character to its left and it is represented by a '!' character.
If it reaches the beginning of the string it stops.
Given a string output the string in any reasonable format after the cleaning process.
Trailing spaces at the end of the string must be still be in the output.
Remember that space cleaners remain after their job.
Input will only consist of printable ASCII characters.
This is code-golf, so least number of bytes win.
# Test Cases
```
" ! a! !b c!d !" => "! a!!b c!d!"
"a !" => "a!"
"! a" => "! a"
"! ! !" => "!!!"
"! " => "! "
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
„ !¤:
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcM8BcVDS6z@/1dUgEAgSFRIAjGSAQ "05AB1E – Try It Online")
---
### Explanation
```
„ ! # 2 char string " !"
¤ # Push the tail of that (so "!")
: # Infinite replacement
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 5 bytes
```
+!
!
```
[Try it online.](https://tio.run/##K0otycxLNPyvquGe8F9BW5FL8f9/RYVERQXFJIVkxRQFRa5EBSAAioOoRAilCBXiBGIA)
Not much to say. Simply removes all spaces in front of every `!` with a simple replace.
[Answer]
# JavaScript (ES6), 24 bytes
Thanks to @Nick Kennedy for the TIO link and -2 bytes, since I could omit the function name `f=`
```
_=>_.replace(/ +!/g,'!')
```
[Try It Online](https://tio.run/##BcExDoAgDADAr7QsQFRYXfArBCsQDREChu/XuyfMMKjf7dvmzsmxd4c3PbYSKCoLC9q8SpSaqb6jlmhKzSopAQgBAU8gvACF1vwD)
Nothing special, same regex as other answers. New to `codegolf`, was a simple one to translate to js. If anyone can think of improvements I'd love to see them.
[Answer]
# [PHP](https://php.net/), 35 bytes
```
<?=preg_replace('/ +!/','!',$argn);
```
[Try it online!](https://tio.run/##K8go@P/fxt62oCg1Pb4otSAnMTlVQ11fQVtRX11HXVFdRyWxKD1P0/p/anJGvoJSTJ6S9X8FRYVERQXFJIVkxRQFRa5EBSBQ5FIEUYkQShEm9C@/oCQzP6/4v64bAA "PHP – Try It Online")
Just a simple RegEx replace.
[Answer]
# [R](https://www.r-project.org/), 25 bytes
```
gsub(" +!","!",scan(,''))
```
Straightforward enough with a simple regex substitution!
[Try it online!](https://tio.run/##K/r/P724NElDSUFbUUlHCYiLkxPzNHTU1TU1/yspKCokKiooJikkK6YoKCr9BwA "R – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~48~~ 42 bytes
*-6 bytes thanks to H.PWiz!*
```
g(' ':b)|'!':_<-g b=g b
g(a:b)=a:g b
g a=a
```
[Try it online!](https://tio.run/##HYjBDkAwEAXvvuKtSMqhP9Dot8i2WKKkwdG3W43DJDOz8LVNKalKa2Bc6B5Dxg29FQRfqKTlcj27P8Cedef1gEc@1@NGA0ENAhMoINJYvNY3zonlUhtz/gA "Haskell – Try It Online")
### Explanation:
```
g(' ':b) -- Given a string starting with space
|'!':_ -- Check if '!' is the first element of
<-g b -- The function applied to the rest of it
=g b -- Return the function applied to the rest of it
g(a:b)=a:g b -- Otherwise just apply the function recursively
g a=a -- Until the string is empty
```
[Answer]
# [Python 3](https://docs.python.org/3/), 50 bytes
```
f=lambda s:' !'in s and f(s.replace(' !','!'))or s
```
[Try it online!](https://tio.run/##bYs7DoAgEERrPcVsBSbGxs7Ew6wCkUSRgI2nR2hM/Ew3783481h216dkxpW3STHiIEDCOkSwUzAydkH7lWcti2gFiabZA2LywbpDmoLBBJowk0LR9a0YOU9EBfEX0c@0evXvKyfDdAE "Python 3 – Try It Online")
Port of [Expired Data's 05AB1E answer](https://codegolf.stackexchange.com/a/191568/87681), so make sure to upvote him!
---
Original answer:
# [Python 3](https://docs.python.org/3/), 63 bytes
```
lambda s:'!'.join(i.rstrip(' ')for i in(s+'_').split('!'))[:-1]
```
[Try it online!](https://tio.run/##bYvBCsIwEETP@hW7p02QBsRbwS@xUraW4EpNQpKLXx@3F0Hr3ObNm/Sq9xhOzZ@HtvBzmhlKT0juESUYcbnULMkQkPUxg4DScqCRrCtpkWrUtfbSd8drS1lCNV5lBEbACW44w7rvPxOD5hvhiniL8I@6@@nbl0ZhewM "Python 3 – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 66 bytes
```
,[<<++++[->++++++++<]>>[-<-<+>>]<[+[[+]<<[.<]>[>]]<.>>]>>,]<<<[.<]
```
[Try it online!](https://tio.run/##LchBCoAwDATAryTntH3Bsh8JObQVQQQPgu@vQZzjjLsf1/7Mc63igCWvtB@C9IoKIwNu7haAt3xnBFo2WfK@XEtUuooOmbqJvg "brainfuck – Try It Online")
It's funny how much space is just taken up by constants, in this case making a space takes up more than a quarter of the code.
[Answer]
# [Haskell](https://www.haskell.org/), 34 bytes
```
foldr(%)""
' '%r@('!':_)=r
c%s=c:s
```
[Try it online!](https://tio.run/##HcdBCoAgFEXReat4SqIN2oAgtJAg7JcVWYm2/n7RnRzu6ss@x8jB9RyuOGWjGikrDa1yZ7TQdmhcrkgVR7bw4bcTDilv540aARJfAl78jiAxfSv5oRD9UrillF4 "Haskell – Try It Online")
[Answer]
# [ksh](http://www.kornshell.com/), 18 bytes
[try it online!](https://tio.run/##yy7O@P8/NTkjX0Gl2lBfX1tDQVNRX7H2////CooKiYoKikkKyYopCooA)
```
echo ${1//+( )!/!}
```
**zsh, 32 bytes**
Since there's another **zsh** answer I changed to **ksh**. Thanks to @Gilles at [unix.se](https://unix.stackexchange.com/a/541616/62529) for zsh help. [try it online!](https://tio.run/##qyrO@J@moVn9vzi1JL@gRCG7OCM@PSc/icvGxkal2lBfX1tDQVNRX7H2fy1XmoJ6VUpxmgIYKIKwOkgMwktUVFBMUkhWTIGKJirAFYCUKiQimIrIUur/AQ)
`setopt ksh_glob;<<<${1//+( )!/!}`
[Answer]
# [///](https://esolangs.org/wiki////), 6 bytes
```
/ !/!/
```
[Try it online!](https://tio.run/##VY2xDsIwDET3fMU5lZiQuiPBwE8wmzSohTSp6lSIrw9J00rg6fzufBbH0ltJqQW11KYGNwvDHs9FIrqA4C2izdqw2CPc8Mp7P8hJKRCYQHcY6kAqT4PrEvGuDewk1BoTpg8OmFhiObZj9twR7DuIXQnizF4eYR45DsGj52myPnfq/yca5wt0QZWQVpqRZ3O4ACqA9@iqN0g/UaKa3XNapS8 "/// – Try It Online")
Replaces every occurrence of `!` with `!` until it eats up all the spaces in front of the exclamation marks.
The language is a perfect match because it's built on find/replace. That's the only command you're given, and not a single special character or wild card to use in your patterns, except the `\` which only serves to escape the `/`. Yet, it's Turing complete. It's really elegant!
The language is read by slash triplets, hence the name. Each one couches a find pattern and replace pattern. We have one such pattern here doing precisely what it says at the top. The first pair of slashes says to find all `!` and the second pair says to replace them with `!`.
[Answer]
# Perl 5 (`-p`), 9 bytes
```
s/ *!/!/g
```
[TIO](https://tio.run/##K0gtyjH9/79YX0FLUV9RP/3/f0WFREUFxSSFZMUUBUWuRAUgUORSBFGJEEoRKsQJxP/yC0oy8/OK/@sWAAA)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 22 bytes
```
$args-replace' +!','!'
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V8lsSi9WLcotSAnMTlVXUFbUV1HXVH9fy0Xl5pKmoKSB1BhvqKCoqICFCgqJCr9BwA "PowerShell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
œṣ⁾ !j”!µÐL
```
[Try it online!](https://tio.run/##y0rNyan8///o5Ic7Fz9q3KegmPWoYa7ioa2HJ/j81zncDhRSUsp6tHEdUHiOgq6dAlCWCyjctCby/38lBUWFREUFxSSFZMUUBUUlHaVEBSAAMRRBjEQYQxEhrAQA "Jelly – Try It Online")
[Answer]
# Python 3, 38 bytes
```
lambda s:re.sub(' +!','!',s)
import re
```
A simple regex substitution. Replaces any amount of space plus an exclamation mark with just an exclamation mark.
[Answer]
### Zsh with `extended_glob`, 14 bytes
```
<<<${1// #!/!}
```
Zsh with `extended_glob` is not an arbitrary whim: it's the language in which zsh completion functions are written. Inspired by [roblogic's initial attempt](https://unix.stackexchange.com/q/541616). [Try it online](https://tio.run/##qyrO@F@cWpJfUKKQWlGSmpeSmhKfnpOf9N/Gxkal2lBfX0FZUV@x9v///woKigqKigoA).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
≔ ηF⮌S«≡ι!≔ωη ≔ηι≔ η←ι
```
[Try it online!](https://tio.run/##RY1LDsIgAETXcIqBFST1AnXl0sSF0RMghUJCqAHaLkzPjp82dTnzJm@0U0kPKtR6ytn3UXDwBk4eqR0SxM1MJmUjzvE5lntJPvZCSrwoybMv2kH4X9IqG3DGW2yaeZVsAH/gGvgv6IxVYyh7v/@ShZLr56iI9mJsWedLrWBQDOwBzTowWg9TeAM "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔ η
```
`h` is a variable that specifies whether a space is being cleaned or not.
```
F⮌S«
```
Loop over the string in reverse as the spaces are cleaned to the left.
```
≡ι
```
Switch over the current character.
```
!≔ωη
```
If it's a `!` then start cleaning spaces.
```
≔ηι
```
If it's a space then replace it with the space cleaning flag.
```
≔ η
```
Otherwise turn off space cleaning.
```
←ι
```
Print the current character leftwards.
Boring 15-byte version:
```
W№θ !≔⪫⪪θ !¦!θθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDOb80r0SjUEdBSUFRSVNTwbG4ODM9T8MrPzNPI7ggJxMhB6TAZKGmNVdAUSZIl6b1//8KigqJigqKSQrJiikKilz/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
W№θ !
```
Repeat while there are spaces to be cleaned.
```
≔⪫⪪θ !¦!θ
```
Clean up to one space per space cleaner.
```
θ
```
Output the result.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Recursive replacement. Could save 2 bytes if we could choose the "cleaner" character.
```
e" !"'!
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZSIgISInIQ&input=ImEgYiAgICAgISAgISAgYyI)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 14 bytes
```
{S:g/\s+\!/!/}
```
[Try it online!](https://tio.run/##TcqxDoJAEIThnqeY2cJCErazMEEfwvaaBTljAkK4ihB99ZMTSNxq880/NGN7it2Eg0cZ59v5oS7kjkp9x2ATPD6dOimOVycK349on68mRAFhBCvUvIOC8gJJtAolE8Ny22IJmMD29PdvyL@UXNu9ky8 "Perl 6 – Try It Online")
Loses bytes over other regex solutions since I can't use a literal space and I have to escape the metaoperator `!`
[Answer]
# [J](http://jsoftware.com/), 16 bytes
```
(#~1-' !'E.])^:_
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NZTrDHXVFRTVXfViNeOs4v9rcqUmZ@QrqCsqJCoqJikkK6YoqivoWimkATWDxBQggkAdUIWJcPlEBSCAiyuCeIkwOSgPJqeoiCKhiKYTIan@HwA "J – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 79 bytes
```
j,e;f(char*s){for(j=e=0;!e;e=!*s++)*s-32?s-=*s-33?j:0,j=0,*s&&putchar(*s):j++;}
```
[Try it online!](https://tio.run/##XY3LbsIwEEX38xUzXiA7DxES2GAZPgSxcFOHxioBxWaV5tvTOFCFZlYz596jKdPyWzeXofzSLfrN6aw6hoSakD6wpE8k1ktYr1EdkAX@xMQQnko@KXrqvWp6TouQTuIch@MVbyd5/PWuE83@7s9/1xkADDYxsuKhFTnRVbeWW2VUJslIoyhycSwilxb50aUqLMXR7rPEqiyJ3Gp1f/ig8tHd2ziW/VA3Hq@6brjADiruN0KOJcfZDxMygHwJiiXYLsHuHwDAcVrjH22DmYR@@AU "C (clang) – Try It Online")
Saved 1 thanks to @ceilingcat
\*s && instead of !\*s ||
j is used to jump back if there is no "!" after spaces.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p`, 14 bytes
```
gsub(/ +!/,?!)
```
Unfortunately the 13-byte `gsub / +!/,?!` doesn't work because Ruby interprets the first `/` as division instead of the start of a regex statement.
[Try it online!](https://tio.run/##KypNqvz/P724NElDX0FbUV/HXlHz/38FRYVERQXFJIVkxRQFRa5EBSBQ5FIEUYkQShEu9C@/oCQzP6/4v24BAA "Ruby – Try It Online")
[Answer]
# Java 8+, 26 bytes
Yet another regex port
```
s->s.replaceAll(" +!","!")
```
[TIO](https://tio.run/##XU67jsIwEOz9FWNXsTjyAReBRENHRXmiWBIbGUwSeRckFOXbc0agSLDF7Mzu7ONMd1qem8tUR2LGjkI7qNCKS55qh@2wlxTaE3zxJmyrUfW3Yww1WEhyunehwTVPvj1/B1A6sR3UFh6riZdrLpPrY964ibEwWGjzY7SxU6XmEXEsjBUGhRwGGqShj6h1g2x/VemJs9JPpA@lvwyZjZXyXZr/x@/rlMX@weKuZXeTss89iW3hS1@wtZUax@kf)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 8 bytes
```
aRw.'!'!
```
[Try it online!](https://tio.run/##K8gs@P8/MahcT11RXfH///8KigqJigqKSQrJiikKigA "Pip – Try It Online")
concatenates the whitespace regex variable `w` with an `!` character. then replaces it with a single `!` in the string.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
ωσ" !""!
```
[Try it online!](https://tio.run/##yygtzv6fm18erPOoqfH/@c7zzUoKikpKiv///48GshQSFRUUkxSSFVOAojpKiQpAAGIoghiJMIYiQlgpFgA "Husk – Try It Online")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 16 bytes
```
gsub(" *!","!")1
```
[Try it online!](https://tio.run/##SyzP/v8/vbg0SUNJQUtRSUdJUUnT8P//RIUkhTQA "AWK – Try It Online")
Similar regex to some others that were posted, just AWK-styled. Adding a random number on the end makes sure it prints even if the input has no cleaner character.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 9 bytes
```
` *!`\!øṙ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60%20*!%60%5C!%C3%B8%E1%B9%99&inputs=%20%20%20!%20!%20a%20%20!&header=&footer=)
Another one ports the regex
] |
[Question]
[
Write a program to find **a** number consisting of 9 digits in which each of the digits from 1 to 9 appears only once. This number must also satisfy these divisibility requirements:
1. The number should be divisible by 9.
2. If the rightmost digit is
removed, the remaining number should be divisible by 8.
3. If the
rightmost digit of the new number is removed, the remaining number
should be divisible by 7.
4. And so on, until there’s only one digit
(which will necessarily be divisible by 1).
Credit [Dávid Németh](http://csokavar.hu/blog/2010/04/problem-of-the-week-9-digit-problem/)
[Answer]
# CJam - 26
```
1{;9,:)_mrs0@{_3$<i\%+}/}g
```
It's randomized but works pretty fast with the [java interpreter](http://sf.net/p/cjam). It can take [a couple](http://xkcd.com/1070/) of minutes with the [online interpreter](http://cjam.aditsu.net/).
**Explanation:**
`1` pushes 1 (to be explained later)
`{…}g` is a do-while loop
`;` removes a value from the stack (initially the 1 we started with)
`9,` makes the array [0 ... 8]
`:)` increments the array elements, resulting in [1 ... 9]
`_` duplicates the array
`mr` shuffles the array
`s` converts to string
`0@` pushes 0 then brings the other copy of the array on top
`{…}/` is a for-each loop (over the numbers 1 ... 9)
`_` duplicates the current number (let's call it "k")
`3$` copies the numeric string from the stack
`<i` gets the substring with the first k characters then converts to integer
`\%` swaps with the other copy of k then gets the remainder (%k)
`+` adds the remainder to the previous value on the stack (initially 0 from above)
At this point, we have the numeric string on the stack, followed by a 0 if the number matches all the requirements (i.e. all the remainders were 0) or a non-0 value otherwise.
The top of the stack becomes the do-while loop condition. It is popped and the loop continues if the condition was true.
If we found the solution, the condition is 0 (false), the loop ends and the rest of the stack (the numeric string) is printed.
If it's not the solution, the condition is the non-0 value (true) and the loop continues with the string on the stack. The string gets popped at the start of the next iteration (so the loop expects a value on the stack, and that's the reason for the initial 1).
Thanks Dennis for making the code shorter and more convoluted :p
[Answer]
# Javascript (E6) 105 ~~125 134~~
Recursive building of the number, each step check the divisibility.
*Runtime near 0 sec*
No I/O this time, as the OP asked for a program to find the number, and the number is found and automatically logged to console
**Golfed more** Courtesy of MT0
```
(Q=(n,d,b)=>([(m=n+(s=[...b]).splice(i,1))%d||Q(m,d+1,s)for(i in b)],d>9&&(Q.z=n),Q.z))('',1,'123456789')
```
**Golfed**
```
(Q=(n='',d=1,b=[...'123456789'],i)=>{
for(i=0;s=[...b],m=n+s.splice(i,1),b[i];i++)m%d||Q(m,d+1,s);d>9&&(Q.z=n);return Q.z;
})()
```
**Ugly**
```
(Q=(n='', d=1, b=[...'123456789'], i) => {
for(i=0; s=[...b], m=n+s.splice(i,1), b[i]; i++)
m % d || Q(m,d+1,s);
d > 9 && (Q.z=n);
return Q.z;
})()
```
**Bonus**
With 3 little changes, you can use the same function to find longer numbers using base > 10. For instance in base 14 ...
```
(Q=(n='',d=1,b=[...'123456789ABCD'],i)=>{
for(i=0; s=[...b], m = n+s.splice(i,1), b[i]; i++)
parseInt(m,14)%d || Q(m,d+1,s);
d>13 && (Q.z=n);
return Q.z;
})()
```
>
> 9C3A5476B812D
>
>
>
**Ungolfed**
```
Q=(n,d,b,i,c,z)=>{ // i,c,z fake parameters instead of vars.
for (i=0; b[i]; i++)
{
s=[...b];
m = n + s.splice(i,1);
if (m % d == 0)
if (z = d<9 ? Q(m, d+1, s) : m) return z;
}
}
Q('',1,[...'123456789'])
```
[Answer]
# Perl, 56
Usage: `perl -E '...'`
```
{$s++;redo if grep{$s!~$_||substr($s,0,$_)%$_}1..9}say$s
```
Output: `381654729`
This program is **really slow**. As in more than 3.5 hours.
As a more fun exercise, I decided to develop an extremely fast algorithm:
```
my $set = [1..9];
for my $divisor (2..9) {
my $newset = [];
for my $element (@$set) {
my $num = $element * 10;
for (my $digit = $divisor - ($num % $divisor); $digit < 10; $digit += $divisor) {
if (index($element, $digit) == -1) {
push @$newset, $num + $digit;
}
}
}
$set = $newset;
}
print "@$set\n";
```
The above runs in .00095 seconds, and confirms that there is only one solution to this problem.
[Answer]
## Python3, ~~214~~, ~~199~~, ~~184~~, ~~176~~, ~~174~~, ~~171~~, ~~165~~, ~~150~~, 146
```
from itertools import*
g=lambda i,d:d==1!=print(i)or int(i[9:])%d==0!=g(i[:-1],d-1)
for x in permutations("123456789"):g("".join(map(str,x))*2,9)
```
output:
```
381654729
```
This is my first golf script. Hope you like it :)
[Answer]
# [Pyth](http://ideone.com/fork/xBaxnq), 33 characters
```
=Y]kFkY~Yf>ql{TlT%vTlTm+k`dr1T)pk
```
To test it, put the above code as standard input in the link in the title.
After compiling into Python 3.4:
```
k=''
T=10
Y=[k]
for k in Y:
Y+=list(filter(lambda T:(len(set(T))==len(T))>(eval(T)%len(T)),
map(lambda d:k+repr(d),range(1,T))))
print(k)
```
Explanation:
`=Y]k`:`Y=['']`
`FkY`: for k in F:
`~Y`: Add to Y
`f`: Filter by
`>ql{TlT`: All unique elements and
`%vTlT`: eval(element)%len(element)=0
`m+k`` `d`
On the list of k + repr(d)
`r1T`: for d from 1 to 9.
`)`: End for loop
`pk`: print k
[Answer]
## Ruby, 66 ~~78~~ chars
```
[*r=1..9].permutation{|i|r.all?{|x|eval(i[0,x]*"")%x<1}&&$><<i*""}
```
Runtime is ~8 seconds (output printed after 3 s).
This doesn't stop after finding the first number, so technically it prints *all* numbers that fulfill the criteria - but since there's only one such number, it doesn't make a difference.
## Ruby 1.8, 63
```
[*r=1..9].permutation{|i|r.all?{|x|eval(i[0,x]*"")%x<1}&&$><<i}
```
Essentially the same solution as above. In Ruby 1.8, arrays are converted to strings by implicitly calling `Array#join` on them, so we can save the call to that. Interestingly, the code also runs much faster in Ruby 1.8 than 2.0 (4.5 seconds total runtime, output printed after 1.6 s).
[Answer]
## GolfScript (35 chars)
```
1,{{10*){.)}8*}%{`..&=},{.`,%!},}9*
```
[Online demo](http://golfscript.apphb.com/?c=MSx7ezEwKil7Lil9OCp9JXtgLi4mPX0sey5gLCUhfSx9OSo%3D)
This builds prefixes which satisfy the condition.
```
# Initial prefixes: [0]
1,
# Loop 9 times
{
# Extend each prefix by digits 1 to 9
{10*){.)}8*}%
# Filter out ones which repeat a digit
{`..&=},
# Filter down to ones which are divisible by their length
{.`,%!},
}9*
```
[Answer]
## Haskell ~~129~~ 121
Here is my amateurish Haskell attempt (suggestions/improvements would be greatly appreciated). It might not be the shortest, but it does execute in only ~~.19~~ .65 seconds after Flonk's changes on my system.
```
import Data.List;f=foldl1$(+).(*10);main=print$[f x|x<-permutations[1..9],f[mod(read.take y.show$f x)y|y<-[9,8..1]]<1]!!0
```
[Answer]
# Javascript 75 (terminating)
Bruteforce solution (super slow)
```
for(a=c=1;b=c&&++a;)for(c=9;~(a+'').search(c)&&b%c<1;)--c?b=b/10|0:alert(a)
```
If you want to see the result in this lifetime, update the initial value to something like `a=c=38e7`
# Javascript 70 (non-terminating)
```
for(a=1;b=++a;)for(c=9;~(a+'').search(c)&&b%c<1;)--c?b=b/10|0:alert(a)
```
And just for fun, a random bruteforce that runs much faster: (ES6 only)
```
for(a=i=[..."123456789"];b=c=i&&a.sort(x=>Math.random()*9-5|0).join('');)for(i=9;c%i<1;)--i?c=c/10|0:alert(b)
```
[Answer]
## Python, ~~142~~, ~~139~~, ~~125~~, 124
Essentially same as @Ventero's solution if I understood his code correctly, but in Python.(Much of the credit goes to @Greg Hewgill.)
```
from itertools import*;print[s for s in map(''.join,permutations('123456789'))if all(t(s[:i])%i==0 for i in range(1,9))][0]
```
[Answer]
# Python 2 (78)
```
x=1
while len(set(`10*x`))<=9+sum(x/10**i%(9-i)for i in range(9)):x+=1
print x
```
No need to generate permutations, just try each number and check if its digits plus 0 are distinct. Takes a while to run.
[Answer]
# Scala (128 chars)
My stab at this...
```
Seq(1,2,3,4,5,6,7,8,9).permutations.filter(p=>(2 to 8)forall{n=>(p.take(n).mkString.toLong%n==0)}).map(_.mkString.toLong).toList
```
[Answer]
# Perl, 72
Usage: `perl -M5.010 find-9-digits.pl`
```
{$s=join'',sort{4-rand 8}1..9;redo if grep{substr($s,0,$_)%$_}2..9}say$s
```
Output: `381654729`
This program is **slow**. It might take more than 10 seconds, because it shuffles the digits "123456789", but the shuffle has a flaw.
Ungolfed:
```
# Enter a block.
{
# Shuffle the characters "123456789".
$s = join('', sort({2 - rand(4)} 1..9));
# Redo block if any divisiblity test fails; grep returns the
# number of failing tests.
redo if grep({
# For each divisor $_ in 2..9, test if the first $_ digits of
# of $s are divisible by $_. The test fails if the remainder
# is a true value (not zero).
substr($s, 0, $_) % $_
} 2..9);
}
say $s;
```
I golfed the code that shuffles the array of digits 1..9:
* `use List'Util shuffle;shuffle 1..9` (34 characters)
* `sort{(-1,1)[rand 2]}1..9` (24 characters)
* `sort{.5<=>rand}1..9` (19 characters)
* `sort(2-rand 4}1..9` (18 characters)
* `sort{4-rand 8}1..9` (18 characters)
Perl expects the sort block to compare *$a* and *$b* in a consistent way. My sort blocks never look at *$a* and *$b*. They return a random ordering so the sort becomes a shuffle.
If I would use `sort{.5<=>rand}1..9`, my program would run faster. That one compares 0.5 with a random float from 0.0 to 1.0, excluding 1.0, for a 1/2 chance that *$a < $b*, and an almost 1/2 chance that *$a > $b*. (**Beware:** This is a ["Microsoft shuffle"](http://www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html), which is *not* a fair shuffle. This has bias because `.5<=>rand` does not provide a consistent ordering.)
Suppose that I golf away one character and use the much worse `sort(2-rand 4}1..9`. Perl expects the sort block to return an integer, but `2-rand 4` is a float. It is a random float from -2.0 to 2.0, excluding -2.0. Perl truncates this float toward zero, with these results:
* 1/4 chance that *$a < $b*, integer -1 from -2.0 < float <= -1.0
* near 1/2 chance that *$a == $b*, integer 0 from -1.0 < float < 1.0
* near 1/4 chance that *$a > $b*, integer 1 or 2 from 1.0 <= float <= 2.0
When *$a == $b*, Perl does not shuffle well. So, my program would do more shuffles, until it gets enough shuffles where `2-rand 4` did not return 0 too often. My program would run so slow, it might take more than one minute.
I use `sort{4-rand 8}1..9`, so there is only a 1/4 chance that *$a == $b*, and my program uses fewer shuffles.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 bytes
```
9Œ!JḍḌƤPƲƇḌ
```
[Try it online!](https://tio.run/##y0rNyan8/9/y6CRFr4c7eh/u6Dm2JODYpmPtQNb//wA "Jelly – Try It Online")
## How it works
```
9Œ!JḍḌƤPƲƇḌ - Main link. No arguments
9 - Yield 9
Œ! - Yield all permutations of [1, 2, ..., 9]
ƲƇ - Keep those for which the following is true:
Ƥ - Over each prefix:
Ḍ - Convert into an integer
J - Yield [1, 2, ..., 9]
ḍ - Pair each [1, 2, ..., 9] with the prefixes,
then return 1 if they divide each other else 0
P - All return 1
Ḍ - Convert back to an integer
```
---
Of course, there's the obvious 9 byter:
```
381654729
```
[Try it online!](https://tio.run/##y0rNyan8/9/YwtDM1MTcyPL/fwA "Jelly – Try It Online")
[Answer]
# CJam, 35 bytes
```
0{)_`$A,1>s=!1$9,{9\m1$\%@+\A/}/;}g
```
After roughly 27 minutes, this produces the following output:
```
381654729
```
### How it works
```
0 " Push 0 (“n”). ";
{ " ";
)_`$ " Increment “N”, duplicate, stringify and sort the resulting string. ";
A,1>s " Push '123456789'. ";
=! " Push 0 if the strings are equal and 1 otherwise (“a”). ";
1$ " Copy “n”. ";
9,{ " For each i in [ 0 1 2 3 4 5 6 7 8 ]. ";
9\m " Calculate “9 - i”. ";
1$\% " Calculate “n % (9 - i)”. ";
@+ " Add the result to “a”. ";
\A/ " Swap “a” with “n” and calculate “n / 10”. ";
}/ " ";
; " Discard “n”. ";
}g " If “a > 0”, repeat the loop. ";
```
[Answer]
## SWI-Prolog 84
```
g([],O,_,O).
g(L,N,I,O):-nth1(_,L,D,R),M is N*10+D,J is I+1,0 is M mod J,g(R,M,J,O).
```
It is a bit cheating, because the list of digits needs to be supplied in the query:
```
?- g([1,2,3,4,5,6,7,8,9],0,0,O).
O = 381654729 ;
false.
```
However, it is what makes this code interesting: you can solve the problem for any list of digits. For example:
```
?- g([1,2,3,4,5,6,7,8,9,0],0,0,O).
O = 3816547290 ;
false.
?- g([1,2,3,4,5,6,7,8],0,0,O).
O = 38165472 ;
false.
?- g([1,2,3,4,5,6,7],0,0,O).
false.
?- g([1,2,3,4,5,6],0,0,O).
O = 123654 ;
O = 321654 ;
false.
?- g([2,2,3,3,5,6,7,8,9],0,0,O).
O = 363258729 ;
O = 363258729 ;
O = 363258729 ;
O = 363258729 ;
O = 723258963 ;
O = 723258963 ;
O = 723258963 ;
O = 723258963 ;
false.
```
[Answer]
# Python 2 – 114
Not even the shortest Python solution, but I am sharing it anyway:
```
e=""
f=lambda s,n:[[n,e.join(f(s.replace(j,e),n+j)for j in s)][s>e],e][n>e>0<int(n)%len(n)]
print f("123456789",e)
```
[Answer]
# Bash+coreutils, 159 bytes
```
l=`echo {1..8}`
for d in {2..8};{
l=$(printf "a=%s;if(!a%%$d)a\n" $(eval echo {${l// /,}}{1..8}|tr \ '
'|grep -Pv '(\d).*\1')|bc|paste -d\ -s -)
}
echo ${l}9
```
This is kind of long, but I think the algorithm is perhaps one of the fastest, considering this is a (usually slow) shell script that runs in less than 0.1 second.
The algorithm goes something like this:
* Start with the leftmost digit (1-8)
* append the next digit to the right (1-8)
* remove any numbers with repeated digits (`grep`)
* check for divisibility by `$d` (the digit number) using `bc`, with an expression generated by `printf`
* Repeat the above until an 8 digit number is obtained
Note we take a couple of shortcuts, but I think these are mathematically sound:
* The leftmost digit must be divisible by 1, which is all digits, so we don't explicitly check for the first set of leftmost digits
* The rightmost digit must be 9 (actually I'm not sure if this is a valid assumption - I'll have to think about it a bit)
[Answer]
# C++, 187
I just had to try this in C++. Obviously, it's not going to be the shortest solution but here it is:
```
#include <algorithm>
using namespace std;bool c(int n,int d=9){return d<2||n%d==0&c(n/10,d-1);}int main(){for(char n[]="123456789";next_permutation(n,n+9);)if(c(atoi(n)))return atoi(n);}
```
returns the number instead of printing it to save some characters (damn include). Under POSIX-systems this will of course be converted to an 8-bit unsigned and thus not correct - but the program will calculate a correct number.
Ungolfed (requires C++11):
```
#include <iostream>
#include <algorithm>
using namespace std;
bool check(int n, int digit = 9)
{
return (n % digit==0) && (digit == 1 || check(n/10,digit-1));
}
int main()
{
string num {"123456789"};
while (next_permutation(begin(num), end(num)))
if (check(stoi(num))){
cout << num << endl;
break;
}
}
```
[Answer]
# T-SQL 2005+ - 203
T-sql is not a very competitive golf language...
```
with A(n)as(select top 10 number from spt_values where'p'=type),R as(select \r,1l union all select r*10+n,l+1from R,A where n not in(select substring(str(r),n,1)from A)and(r*10+n)%l=0)select max(r)FROM R
```
Must be run on the master database. You can replace the first CTE with this to make it database agnostic but then it uses a few more characters (and requires 2008)
```
with A as(select*from(VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9))f(n))
```
Readable formation:
```
with A(n)as(select top 10 number from spt_values where'p'=type),
R as(select \ r,1 l
union all
select r*10+n,l+1
from R,A
where n not in (
select substring(str(r),n,1)
from A
)
and(r*10+n)%l=0)
select max(r) FROM R
```
Basically we keep adding digits to the back of the `r` number that we haven't seen in the string yet, and making sure that the new string is still modulo 0 of the current level. We initialize R to `\`, This is really the only trick in this code. Which is a crazy way to set it to 0 in `money` datatype. It's I'm guessing a way to let you type `\` instead of currency. `$` also does the same thing in T-SQL, but `$l` would try to interpret a pseudo column that doesn't exist and throw an error. This lets us avoid the worry about using `int` which would cause an overflow normally at the 10th concatenation, forcing us to actually check the level.
Edit:
Fun fact T-sql even in 2014 doesn't have a built in way to turn a string into a table of values (e.g. no split func), so we actually also get to reuse our `A` table twice to iterate the characters in the stringified R.
T-Sql precedence rules are annoying so we have to use numeric concatenation (\*10+n), rather than string concat.
[Answer]
# PHP, 89 bytes
## random version, 89 bytes:
```
for($n=123456789;$n=str_shuffle($n);$d||die("$n"))for($d=10;--$d&&substr($n,0,$d)%$d<1;);
```
shuffles a string containing the digits, then tests divisibility in a loop.
Run with `-nr`.
---
## brute force loop, 90 bytes, very slow:
```
for(;++$i<1e9;$d||die("$i"))for($d=10;--$d&&max(count_chars($i))<2&substr($i,0,$d)%$d<1;);
```
loops from 100000001, tests divisibility in inner loop, and exits when it finds a solution.
---
## recursive function, 94 bytes, very fast:
```
function f($n="",$e=1){while($d++<9)strpos(_.$n,"$d")|($x=$n.$d)%$e||print$e>8?$x:f($x,$e+1);}
```
appends one digit that´s not yet in the number, if divisibility by length is given, recurse (or print).
This exploits that there is only one solution. without that, `print$e>8?$x:f($x,$e+1)` had to be `print$e>8?"$x\n":f($x,$e+1)` (+3 bytes, print all solutions) or `($e>8?die("$x"):f($x,$e+1))` (+4 bytes, exit at first solution) or the solutions would be printed without a delimiter.
Call with `f();`
--
## TiO
The brute force version has no TiO for obvious reasons,
but you can [try the other two](https://tio.run/##VZDdTsJAEIXv@xSTzUi6ofxUUYFSiSFFSUxNUPSGhEB3a5vItNltBbH66nXhwsS7mTkzJ@ebPMnr0ThPcpBKZWqlZJ6pIqU3sH@CVfj4PJsE0ABTv97Ow1l4xz3odGBbFhJ2a0VmU8OaBFBWpJHUtRHnwWQxf5q9BDBdhJPn2WPowKAHm89CasuKS4qKNCOIbSSfMQel7/KvXZK@SxtFszkacF2oPNP2qo3kMBSMVzbufaQ2Cn6GsqpylVKB8qY/xv3QGO2NS9Pl3rdl4drfppEycbbSNqPY5h4e/s9klGRsSUpGpdLphwRV0lEbAnMADy1cO8BAyygjoZe0JOZZliF7ul9Mpw/mC/ASGMIjWH/wB5apI5F7ftG7vLruDzzTGJCVTso4PrKRCSKqSqTSZkiM89OF8N2u12qhaDR0uTEHZtHpOidSMXI97ll1/Qs).
The function call´s runtime is measured inline (somewhere between 2 and 4 milliseconds);
total runtime is measured by the website (usually between 50 and 500 ms).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
dḟöΛIz¦ḣ9mdḣPḣ9
```
[Try it online!](https://tio.run/##yygtzv7/P@XhjvmHt52b7Vl1aNnDHYstc4ECiwNArP//AQ "Husk – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
9LœJʒηāÖP
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f0ufoZK9Tk85tP9J4eFrA//8A "05AB1E – Try It Online")
The same as [my answer](https://codegolf.stackexchange.com/a/214625/64121) on the newer challenge, but with fixed input of `9`. Hardcoding is shorter:
```
•N4₃s
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcMiP5NHTc3F//8DAA "05AB1E – Try It Online")
] |
[Question]
[
The input is an array of (at least 3, maximum 20) different integers. Each integer is greater than -1000 and smaller than 1000.
Your task is to shrink the numbers by "linearly mapping" them from `0.0` to `1.0`. This means the smallest number in the array will be mapped to 0.0, the largest to 1.0.
You get the array as a parameter (inside a function) or stdin/program arguments (you can choose). Print out the result in the format `double1;double2;double3;...`. The output **has to have the same order as the input**.
If you want, you can round the output to 2 digits after the decimal point. **There must be atleast 1 digit after the decimal point.**
The **usage of built-in functions** (functions which scale down the numbers for you, such as mathematicas `Rescale`) **is disallowed**.
Examples:
```
Input Output
[5,-20,30] 0.5;0.0;1.0
[1,2,3,4,5] 0.0;0.25;0.5;0.75;1.0
[0,5,100,400] 0.0;0.01;0.25;1.0
```
(The last output is rounded, otherwise it would be `0.0;0.0125;0.25;1.0`)
[Answer]
# CJam, 18 bytes
```
q~_$0=f-_$W=df/';*
```
Note that the [online interpreter](http://cjam.aditsu.net "CJam interpreter") wrongfully represents `0d` as `0` instead of `0.0`.
### Example run
```
$ cjam shrink.cjam <<< '[5 -20 30]'; echo
0.5;0.0;1.0
$ cjam shrink.cjam <<< '[1 2 3 4 5]'; echo
0.0;0.25;0.5;0.75;1.0
$ cjam shrink.cjam <<< '[0 5 100 400]'; echo
0.0;0.0125;0.25;1.0
```
### How it works
```
q~ " P := eval(input()) ";
_$0= " S := sorted(P)[0] ";
f- " Q := { X - S : X ∊ P } ";
_$W=d " D := double(sorted(Q)[-1]) ";
f/ " R := { X / D : X ∊ Q } ";
';* " print(join(R, ';')) ";
```
[Answer]
## JavaScript, ES6, 81 bytes
Thanks to @edc65 for the `toFixed` trick
```
F=a=>a.map(v=>((v-n)/d).toFixed(2),n=Math.min(...a),d=Math.max(...a)-n).join(';')
```
Run it in latest Firefox Console.
This creates a function `f` which you can invoke like
```
F([5,-20,30])
```
[Answer]
# Python 2, ~~72 68 63 56~~ 55
Obviously not as concise as other answers, but anyway:
```
x=input()
m=min(x)
print[(i*1.-m)/(max(x)-m)for i in x]
```
Sample run:
```
[1,100,25,8,0] #input
[0.01, 1.0, 0.25, 0.08, 0.0] #output
```
---
Old (68 characters, written in Python 3):
```
x=eval(input())
y=sorted(x)
print([(i-y[0])/(y[-1]-y[0])for i in x])
```
[Answer]
## CJam, ~~24~~ 23 bytes
```
l~_$)\(:M\;-\Mf-\df/';*
```
Input be like:
```
[5 -20 30]
```
[Try it online here](http://cjam.aditsu.net/) **Note that online compiler prints `Double 0` as `0` only. Run in the java interpreter which prints correctly.**
How it works:
```
l~ "Evaluate input and convert each element to double";
_$ "Copy the array and sort the copied array";
) "Pop the last element out of the array. This is Max";
\ "Swap last two stack elements, bring sorted array on top";
(:M "Pop the first element of array and store it in M. This is Min";
\; "Bring the remaining of sorted array on top and remove it from stack";
-\ "Subtract Max and Min and bring the original array to top of stack"
Mf- "Push min to stack and subtract it from each array element";
\df/ "Bring (Double)(Max-Min) to top and divide each array element by it";
';* "Push the character ; to stack and join the array with it";
```
[Answer]
# C# 92
Running inside LinqPad
```
void F(int[]a)
{
double n=a.Min(),d=a.Max()-n;
a.Select(x=>((x-n)/d).ToString("0.00")).Dump();
}
```
**Test** in LinqPad
```
void Main()
{
F(new int[]{5,-20,30});
}
void F(int[]a){double n=a.Min(),d=a.Max()-n;a.Select(x=> ((x-n)/d).ToString("0.00")).Dump();}
```
*Output*
```
IEnumerable<String> (3 items)
0,50
0,00
1,00
```
[Answer]
## APL (15)
```
(2⍕+÷⌈/)(+-⌊/)⎕
```
(or, without trains, also 15 characters:)
```
2⍕V÷⌈/V←V-⌊/V←⎕
```
This reads the argument from the keyboard and prints the result to the screen.
Explanation:
* `⎕`: read a line from the keyboard and evaluate it
* `+-⌊/`: subtract the lowest item in the array from all items in the array
* `+÷⌈/`: divide each item in the array by the array's highest item
* `2⍕`: format with two decimal places
Test:
```
(2⍕+÷⌈/)(+-⌊/)⎕
⎕:
5 ¯20 30
0.50 0.00 1.00
(2⍕+÷⌈/)(+-⌊/)⎕
⎕:
1 2 3 4 5
0.00 0.25 0.50 0.75 1.00
(2⍕+÷⌈/)(+-⌊/)⎕
⎕:
0 5 100 400
0.00 0.01 0.25 1.00
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 18
Now with correct formatting!
```
j\;mc-dhSQ-eSQhSQQ
```
**Test:**
```
$ pyth -c 'j\;mc-dhSQ-eSQhSQQ' <<< '[0,5,100,400]'
0.0;0.0125;0.25;1.0
```
**Explanation:**
```
(implicit) Q = eval(input())
j\; ';'.join(
m map(lambda d:
c float_div(
-dhSQ d-sorted(Q)[0],
-eSQhSQ sorted(Q)[-1]-sorted(Q)[0]),
Q Q))
```
[Answer]
# Octave 25
```
b=min(l);(l-b)/(max(l)-b)
```
Assumes input is in `l` and since it's an interactive shell the result is printed automatically (is this allowed?)
[Answer]
## APL, 31 characters / 55 bytes
```
{b←⌊/⍵⋄c←(⌈/⍵)-b⋄{2⍕(⍵-b)÷c}¨⍵}
```
Old code without digits after decimal point:
```
{b←⌊/⍵⋄c←(⌈/⍵)-b⋄{(⍵-b)÷c}¨⍵}
```
Take minimum of vector, take difference between maximum and minimum of vector, subtract the minimum from each element and divide by the difference between min and max.
Edited Code to print two digits after the decimal point:
[Answer]
## CJam, ~~30~~ 29 bytes
```
l~:d_{e>}*\_{e<}*:Mf-\M-f/';*
```
Expects the input on STDIN like `[5 -20 30]`.
[Test it here.](http://cjam.aditsu.net/) (This will print integer `0` and `1` without decimal point, but the Java interpreter does print `0.0` and `1.0`.)
Due to [a bug](http://sourceforge.net/p/cjam/tickets/2/) I can't shorten `{e>}*` to `:e>` although that should be possible as per the spec (which would save 4 bytes when applied to both min and max).
Slightly outdated explanation: (will amend later)
```
l~:d_{e<}*_@_{e>}*@-\@f-\f/';* "Read and eval the input leaving an array of strings on the stack";
l~ "Read and eval the input leaving an array of strings on the stack";
:d "Convert all elements to double";
_ "Duplicate the array";
{e<}* "Wrap the MIN function in a black and fold it onto the array";
_ "Duplicate the minimum";
@ "Rotate the stack, pulling the array to the top";
_ "Duplicate the array";
{e>}* "Same as before, now with MAX";
@ "Rotate the stack, pulling the minimum to the top";
- "Subtract to give the total range";
\ "Swap range and array";
@ "Rotate the stack, pulling the other minimum to the top";
f- "Subtract the minimum from each element in the array";
\ "Swap range and array";
f/ "Divide each element in the array by the range";
'; "Push a semicolon character";
* "Riffle the semicolon into the array";
```
At the end of the program, the stack contents are printed by default.
I'm sure there is a way to save half of the stack reshuffling, but I'm not that comfortable with CJam yet.
[Answer]
# Xojo, 179 bytes
```
dim x,n as double,k,z as int16,s() as string
n=1e3
x=-n
for each k in a
x=max(x,k)
n=min(n,k)
next
for k=0 to ubound(a)
s.append str((a(k)-n)/(x-n),"0.0#")
next
msgbox join(s,";")
```
[Answer]
## R, 60 bytes
```
m=min(x<-scan());cat(sprintf("%f",(x-m)/(max(x)-m)),sep=";")
```
Formatting eats up a lot of bytes due to `0` and `1` by default are trimmed to display nothing past the integer part.
[Answer]
# Clojure 63
```
(fn[v](let[l(apply min v)](map #(/(- % l)(-(apply max v)l))v)))
```
Doesn't quite follow the rules, since it returns fractions instead of doubles. If that's not acceptable, add 7 bytes
Ungolfed:
```
(fn [values]
(let [low (apply min values)]
(map #(/ (- % low)
(- (apply max values) low))
values)))
```
Callable like this:
```
((fn[v](let[l(apply min v)](map #(/(- % l)(-(apply max v)l))v))) [5 -20 30])
```
Output: `(1/2 0 1)`
[Answer]
# Ruby, 49
```
f=->a{$><<a.map{|x|(x-l=a.min).fdiv(a.max-l)}*?;}
```
Explanation:
```
f=->a{} # Define a lambda that takes one argument a
$><< # Print the following to STDOUT
a.map{|x|} # For each element x
(x-l=a.min) # Find the lowest element of a, assign it to l, and subtract it from x
.fdiv # Float division (/ truncates)
(a.max - l) # Divide by the maximum minus the minimum
*?; # Convert the resulting array into a string joined by the ';' character
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 13 bytes (Non-competing)
```
ZsWD1.S*+s/Z/
```
[Try it online!](http://05ab1e.tryitonline.net/#code=WnNXRDEuUyorcy9aLw&input=WzUsLTIwLDMwXQ)
[Answer]
## Q (31) IMPROPER OUTPUT FORMAT
```
{(%/)(x;max x)-min x}(.:)(0::)0
```
input
```
1 2 3
```
output
```
0 .5 1
```
[Answer]
# Perl - 60
```
my@a=sort@ARGV;print map{($_-$a[0])/($a[-1]-$a[0])." "}@ARGV
```
[Answer]
# Java 7, 149 bytes
```
float[]c(int[]x){int b=1<<31,a=b-1,j=0,l=x.length;for(int i:x){a=i<a?i:a;b=i>b?i:b;}float[]r=new float[l];for(;j<l;r[j]=x[j++]-a)*1f/(b-a);return r;}
```
**Ungolfed & test code:**
[Try it here.](https://ideone.com/2QnZup)
```
import java.util.Arrays;
class M{
static float[] c(int[] x){
int b = Integer.MIN_VALUE,
a = b-1, // In Java, Integer.MIN_VALUE - 1 = Integer.MAX_VALUE (and vice-versa)
j = 0,
l = x.length;
for(int i : x){
a = i < a ? i : a; // Determine min value of array
b = i > b ? i : b; // Determine max value of array
}
float[] r = new float[l];
for(; j < l; r[j] = (x[j++] - a) * 1f / (b-a));
return r;
}
public static void main(String[] a){
System.out.println(Arrays.toString(c(new int[]{ 5, -20, 30 })));
System.out.println(Arrays.toString(c(new int[]{ 1, 2, 3, 4, 5 })));
System.out.println(Arrays.toString(c(new int[]{ 0, 5, 100, 400 })));
}
}
```
**Output:**
```
[0.5, 0.0, 1.0]
[0.0, 0.25, 0.5, 0.75, 1.0]
[0.0, 0.0125, 0.25, 1.0]
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
g-:G/
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJnLTpHLyIsIiIsIlsxMy4wLCAxNy4wLCAxNy4wLCAxNS41LCAyLjldIl0=)
Outputs as arbitrary-precision rationals. Look Ma, no Unicode!
```
g- # Subtract the minimum
:G # Make a copy and get the maximum of that
/ # Divide (list - min) by the maximum
```
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 33 bytes
```
&n&sr>las<l/uy[';ofl/0L[!f!]pu,];
```
[Try it online!](https://tio.run/##y6n8/18tT624yC4nsdgmR7@0MlrdOj8tR9/AJ1oxTTG2oFQn1vr/fwMuUy5dQwMDLhMDAwA "Ly – Try It Online")
This is pretty direct translation of the requirements, but there are two things which add code I wanted to avoid... First, since `0` is a valid number in the list, the code has to explicitly add (and manipulate) a loop iterator on the stack. And second, since the rules imply that negative numbers should produce a `0` output, there's some extra code for that. If `-0.0` is an acceptable output, the code could be a few bytes shorter. :)
```
&n&sr (1) read input and prep for processing
&n - read STDIN onto the stack
&s - save a copy of the stack
r - reverse the stack
>las< (2) find/stash the largest input number
> - switch to an empty stack
l - restore a copy of the input list
a - sort the stack
s - save the top of stack (largest number) to backup cell
< - switch back to the stack with the original input
l/uy (3) print first entry, prep for loop
l - load the largest number from the backup cell
/ - divide to get the 0-1 scaled number
u - print as a number
y - push the stack size onto the stack
[';ofl/0L[!f!]pu,]; (4) process 2-N list entries
[ ] - loop through all the list entries
';o - print the ";" field separator
f - flip the iterator and next list entry on stack
l - load the largest number on the input
/ - divide to get the 0-1 ratio
0L - compare result against 0, looking for "<0"
[ ]p - if/then structure, true if result <0
!f! - true: make top two stack entries "0"
u - print ratio (or "0" if result was <0)
, - decrement iterator
; - exit program to avoid print extraneous "0"
```
If `-0.0` is an acceptable output, this 4 bytes shorter version could be used.
```
&n&sr>las<l/uy[';ofl/0L!*u,];
```
] |
[Question]
[
Write a program which takes a 3x3 matrix on stdin and prints its transpose along the anti-diagonal to stdout. You may assume that all elements of the matrix will be integers. Columns are space-separated and rows are newline-separated.
### Example
Input:
```
1 2 3
3 4 5
1 2 3
```
Output:
```
3 5 3
2 4 2
1 3 1
```
Input:
```
1 2 3
4 5 6
7 8 9
```
Output:
```
9 6 3
8 5 2
7 4 1
```
[Answer]
# APL - 7
```
⌽⍉⌽3 3⍴
```
Example input:
```
⌽⍉⌽3 3⍴1 2 3 3 4 5 1 2 9
> 9 5 3
2 4 2
1 3 1
```
[ngn APL demo](http://ngn.github.io/apl/web/#code=%u233D%u2349%u233D3%203%u23741%202%203%203%204%205%201%202%209)
[Answer]
## Mathematica, ~~31~~ ~~28~~ 20 bytes
```
(r=Reverse)[r@#]&
```
The `` is Mathematica's transpose operator (which is displayed as a superscript T in Mathematica).
[Answer]
## Sage, 39
*Runs in the interactive prompt*
```
matrix(input()[::-1]).transpose()[::-1]
```
Sample input:
```
[[1,2,3],[3,4,5],[1,2,3]]
```
Sample output:
```
[3 5 3]
[2 4 2]
[1 3 1]
```
[Answer]
## GolfScript, 18 / 15 / 11 chars
```
~]-1%3/zip{' '*n}%
```
This is the straightforward implementation, following pretty much the exact steps given in the question. There's a clever arithmetic trick one could use instead, but it turns out to need more characters.
Sample input:
```
1 2 3
3 4 5
1 2 9
```
Sample output:
```
9 5 3
2 4 2
1 3 1
```
Ps. If I can use the same output format as in [ace's answer](https://codegolf.stackexchange.com/a/24895) (i.e. extra with square brackets around each row), I can save three chars for a total of **15 chars**:
```
~]-1%3/zip{`n}%
```
If a one-line output format like `[[9 5 3] [2 4 2] [1 3 1]]` is allowed, I can shrink that further to just **11 chars**:
```
~]-1%3/zip`
```
[Answer]
# J - 16 (?) char
Taking the 3x3 matrix as a grid from stdin, we get the 16 character:
```
|:&.|.".1!:1]3#1
```
This can be made shorter if the input is made more flexible, as in the Sage and APL answers:
```
|:&.|.".1!:1]1 NB. if stdin input form can be 1 2 3, 4 5 6,: 7 8 9
|:&.|. NB. if used as an expression like the APL answer
```
The key is in the `|:&.|.` portion: this is what transposes the matrix. It reads *Transpose* (`|:`) *Under* (`&.`) *Reverse* (`|.`), meaning you reverse the matrix, transpose it, and then undo your initial reverse.
Demo:
```
|:&.|.".1!:1]3#1 NB. three lines input, three output
1 2 3
4 5 6
7 8 9
9 6 3
8 5 2
7 4 1
1 2 3,3 4 5,:1 2 9 NB. a matrix
1 2 3
3 4 5
1 2 9
|:&.|. 1 2 3,3 4 5,:1 2 9 NB. the logic
9 5 3
2 4 2
1 3 1
```
[Answer]
# K, 3/7/20(?) bytes
K is similar enough to APL that a character-for-character transliteration of @mniip's solution works:
```
|+|3 3#
```
In action:
```
|+|3 3#1 2 3 3 4 5 1 2 9
(9 5 3
2 4 2
1 3 1)
```
This behaves identically, modulo the way output is prettyprinted. However, I should note that neither this solution nor the solution it is based on actually operate on `stdin`/`stdout`. To implement this as per a stricter interpretation of the spec in Kona-compatible K3 it's necessary to use `0:` and jump through some hoops:
```
`0:,/'2$|+|3 3#. 0:`
```
Write to stdout (``0:`) the join over each (`,/'`) of the two-wide string format (`2$`) of the anti-diagonal transpose (`|+|`) of the 3x3 reshape (`3 3#`) of the eval (`.`) of stdin (`0:``).
In action:
```
indigo:kona je$ ./k antidiag.k
K Console - Enter \ for help
1 2 3 3 4 5 1 2 9
9 5 3
2 4 2
1 3 1
```
There's a pretty good reason that APL-family programmers tend to avoid problems that force the use of stdin/stdout. Arguably, with flexible IO requirements, this could be solved with simply `|+|`:
```
|+|(1 2 3;3 4 5;1 2 9)
(9 5 3
2 4 2
1 3 1)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
RÞTR
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=R%C3%9ETR&inputs=%5B%5B9%2C6%2C3%5D%2C%5B8%2C5%2C2%5D%2C%5B7%2C4%2C1%5D%5D&header=&footer=)
```
R # Vectorised reverse
ÞT # Transpose
R # Vectorised reverse
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) `-c`, 2628 bytes
```
(()()()()){({}[()]<{(({}))((((()()()()){}){}){})({}[{}])((){[()](<{}({}<>)<>>)}{}){{}(<(<()>)>)}{}}{}({}<>)<>>)}{}(<>({})<>){(({}))((()()()()()){})({}[{}])((){[()](<{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}){{}(<(<()>)>)}{}}{}(<>({})<>)({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<><>{(({}))((((()()()()){}){}){})({}[{}])((){[()](<{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}){{}(<(<()>)>)}{}}{}{(({}))((()()()()()){})({}[{}])((){[()](<{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}){{}(<(<()>)>)}{}}{}{}{(({}))((((()()()()){}){}){})({}[{}])((){[()](<{}({}<>)<>>)}{}){{}(<(<()>)>)}{}}{}<>{(({}))((()()()()()){})({}[{}])((){[()](<{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}){{}(<(<()>)>)}{}}{}{(({}))((((()()()()){}){}){})({}[{}])((){[()](<{}({}<>)<>>)}{}){{}(<(<()>)>)}{}}{}([(((()()())()){}{}){}]{}){(({}))((((()()()()){}){}){})({}[{}])((){[()](<{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}){{}(<(<()>)>)}{}}{}({}<>){(({}))((()()()()()){})({}[{}])((){[()](<{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}){{}(<(<()>)>)}{}}{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>({}<>)<>(()()){({}[()]<{(({}))((((()()()()){}){}){})({}[{}])((){[()](<{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}){{}(<(<()>)>)}{}}{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}{(({}))((((()()()()){}){}){})({}[{}])((){[()](<{}({}<>)<>>)}{}){{}(<(<()>)>)}{}}{}({}<>)({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>{(({}))((((()()()()){}){}){})({}[{}])((){[()](<{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}){{}(<(<()>)>)}{}}{}<>{(({}))((((()()()()){}){}){})({}[{}])((){[()](<{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}){{}(<(<()>)>)}{}}{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>{(({}))((()()()()()){})({}[{}])((){[()](<{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}){{}(<(<()>)>)}{}}{}{(({}))((((()()()()){}){}){})({}[{}])((){[()](<{}({}<>)<>>)}{}){{}(<(<()>)>)}{}}{}({}<>)({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>{(({}))((((()()()()){}){}){})({}[{}])((){[()](<{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}){{}(<(<()>)>)}{}}{}<>([]){({}[()]<({}<>)<>>)}<>(()()()){({}[()]<{(({}))((((()()()()){}){}){})({}[{}])((){[()](<{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}){{}(<(<()>)>)}{}}{}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}
```
If it weren't for IO requirements this could have been 842 bytes but hey it was a good challenge :P I'm sure there's a lot that can be golfed here and I will see if I can find some of those spots later but right now I need to stop staring at brackets.
[Try it online!](https://tio.run/##3VTNCsMgDL7vKTwmhx7634L4IsVDNxiMjR12FZ/dmVpsN7YdVkultfiTxC9fQszx0V/uyfnWX40BQDdQgdIdoOQK7A4R6PNKPf5kpLS0WlRkDVxpK@MCuRCoycgKuB0ocBDoNwPggvCtYHKEc0ffXAB0Erma4Oisae@wufAhvDj8RcxzWeaANH8kbYWIts/pnEOoAprnd7O4wj@LzmM5sAFL0hxJNTm7CN7pIlh/IUCfiy64YVmrZS@jFkuC42ESKp876oG7qjPC@HRt7D077T7GpGnKsixjeZ4fiqJgZVmyqqoOdV2zpmlY27YmOT0B "Brain-Flak – Try It Online")
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 3 bytes
```
⌽˘⌽
```
[Try it online!](https://bqnpad.mechanize.systems/s?bqn=eyJkb2MiOiJpbiDihpAgM%2BKAvzPipYpbMSwgMiwgMywgMywgNCwgNSwgMSwgMiwgM11cbm91dCDihpAgM%2BKAvzPipYpbMywgNSwgMywgMiwgNCwgMiwgMSwgMywgMV1cblxu4oy9y5jijL1pblxuXG5vdXRcbuKAolNob3cg4oy9y5jijL1pbiIsInByZXZTZXNzaW9ucyI6W10sImN1cnJlbnRTZXNzaW9uIjp7ImNlbGxzIjpbXSwiY3JlYXRlZEF0IjoxNjc1MDA1ODcxMzM1fSwiY3VycmVudENlbGwiOnsiZnJvbSI6MCwidG8iOjk4LCJyZXN1bHQiOm51bGx9fQ%3D%3D)
### Explanation
```
⌽˘⌽
⌽ 1. Reverse over [leading axis][1]
⌽˘ 2. Reverse over "major cells"
```
[Answer]
# MATLAB, 15 bytes
Rotate the matrix 180 degrees, and transpose it. This takes the input where columns are space separated and rows are newline separated. Outputs on the same format.
```
@(A)rot90(A,2)'
ans([1 2 3
4 5 6
7 8 9])
ans =
9 6 3
8 5 2
7 4 1
```
[Answer]
### Racket, 42 bytes
```
(λ(m[r reverse])(r(apply map list(r m))))
```
Takes a list of lists of numbers as input, and outputs the same type.
Thought I might as well find a use case for some of the tips I'd written up some years ago!
[Try it online!](https://tio.run/##VY07DsIwEET7nGIkmt0iBSH8zoIorGRBFrZjrRdQzsYduFJIKJCYakZPeqOuu4lNq@DSFfodVUW9XHwSmLpU8lCkdsn8RO8XxZNC5SFa5Myk5HIOI6LLCL4YKSLPmXiWZBWzsc7qk9XdEO4xFTQt/8hTvQno/wWk4vrFQbRGgw1XoBZb7JayxwFH5g8)
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$6\log\_{256}(96)\approx\$ 4.94 bytes
```
.rZt.r
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbL9IqiSvSKIByo2IKd0dGGOkY6xrE60cY6JjqmQBrCj4UoAAA)
`.r` reverses each row; `Zt` transposes; `.r` reverses each row.
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 87 ~~98~~ ~~101~~ bytes
```
integer A(3,3);read*,((A(i,j),j=1,3),i=1,3);print'(3i3)',((A(4-i,4-j),i=1,3),j=1,3)
end
```
[Try it online!](https://tio.run/##NcrBDoIwEIThu08xN7Zke8Ctimk88CgkFLI9FLPh/QuinubP5JtX22wsfpm/UauWLS3JMJCwuGhpnFomGkg5O86v7nhZz4lvO3RDouKa0wSvHHz@gx@PqUy1Ah1wBQQXIAA34P7JB9ADT@w)
~~[98b](https://tio.run/##NYs7DoMwEAV7TvE61tG6IOv8QBQcBckGraWYyOH@DiGkeiO9mWnJax6TnacflKJpDXPI7PUZ0luXRMJi2nbochj9iYkGUo6GY99sB@s@1StvYU2iYurdcVbZ2fgXDr0LyZcCNMAZEFSAAy7A9Ys34A488AE)~~
~~[101bytes](https://tio.run/##LYzNDoMwDIPvfYoc2ykcuu6XigOPgpSAUmntFHj/rjAutmV/8lx00yl3y/wPtUreeGFFkg/nVUq2AYPr@zEqT3RBa0crmBymwbcB5TBDBdIQ0GPn41fbSSNPUM7eRc5EZddaPVwhgLnBHR5gnvCCN/wA "Fortran (GFortran) – Try It Online")~~
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 83 ~~97~~ bytes
>
> -14 bytes thanks to @noodleman !
>
>
>
Input and output are the matrixes exactly in the string format specified by OP.
This surely is the shortest JS answer using this format!
```
s=>s.split(/\s/).map((e,i,a)=>a[i+(2-i%3-(i/3|0))*4]+(i%3<2?` `:i>6?``:`
`)).join``
```
[Try it online!](https://tio.run/##bY1NTsMwEEb3PsUoEpJN/qidhjbCyUEo0lipi1yFJKqdigVbdhwBLteLhKGlEgtmM6M3M@/bm6Px7cGNIe2HrZ13eva69pkfOxd4vvG5yF7MyLlNXGKErs2ji7lM3Y1KucvV250Qt8VTzAk8yAYBK1eXDWKFDIXI9oPrEWd7NN1kgtXc9eMUEvs62jbYbXKwfuqC3l24oIB26P3Q2awbnjn/XWt9fWii0@f7po@q6PT1QV3ElxPB2DWDM1yABMUUFLBk5xlZwlDBkqgkKokqWCCjt795UfpT0X8yUkHJ7mEF67NsDSXRFVFJtDjL5m8 "JavaScript (Node.js) – Try It Online")
---
Let me explain a bit:
First we split the input string on all whitespaces, which gives us a **`one-dimensional array`**.
Then, we switch each item with their corresponding targets by transforming the current value of the (one-dimensional) index this way:
**`i+(2-i%3-(i/3|0))*4`**.
And finally, we concatenate all the elements while adding the and `\n` after the right items (but specifically not after the last item).
[Answer]
# R, 78
```
write.table(matrix(rev(unlist(strsplit(readLines(),' '),' ')),3),qu=F,r=F,c=F)
# Copy and paste the input
# If the prompt is not on a new line, press `enter` after the last line
# Type `Ctrl+D`
```
I discovered the `rev()` function on [SO](https://stackoverflow.com/a/16497058/2257664), it helped me to understand than the transformation is just reversing the input and putting it in the matrix from top to bottom, and left to right.
I also discovered that the argument `row.names=T` (T for `true`) can be shortened to `r=T`, saving 16 chars.
## Explanations:
* `readLines()` reads STDIN and return a vector with 3 elements (each one is a string)
* `strsplit()` splits the strings in the vector by using space as a separator
* `unlist()` makes a flat list from a vector
* `rev()` puts the list in reverse order
* `matrix([list], 3)` creates a matrix from the list, the argument `3` indicates that there is 3 elements per row
* `write.table([matrix], qu=F, r=F, c=F)` prints the matrix without quotes, rows and columns labels
[Answer]
## TI-BASIC, 50
```
Input A:rowSwap(A,1,dim(A
AnsT→A:rowSwap(A,1,dim(A
```
[Answer]
## CJam, 13 bytes
```
q~]W%3/zSf*N*
```
[Test it here.](http://cjam.aditsu.net/#code=q~%5DW%253%2FzSf*N*&input=1%202%203%0A4%205%206%0A7%208%209)
CJam is newer than this challenge. This solution is very similar to the GolfScript one.
### Explanation
```
q~ e# Read input and evaluate, pushing all 9 numbers on the stack.
] e# Wrap them in an array.
W% e# Reverse it - this performs a 180° rotation.
3/ e# Split into rows of length 3.
z e# Transpose.
Sf* e# Join integers in each row with spaces.
N* e# Join the rows with linefeeds.
```
If there was no constraint on 3x3 inputs, we could either compute the line width with a square root:
```
q~]W%_,mQ/zSf*N*
```
Or we could perform the anti-diagonal transpose as vertical flip, transpose, vertical flip (like my Mathematica answer does):
```
qN/Sf/W%zW%Sf*N*
```
In either case, we'd have 16 bytes.
[Answer]
# [R](https://www.r-project.org/), 37 bytes
```
write(scan()[rep(9:7,e=3)-3*0:2],1,3)
```
[Try it online!](https://tio.run/##K/qvbKhgpGAMhCYKpgoQtjIQmwKxEVDMCChmrGDIBVUGUmSmYK5goWAJVGYJZBsD2aZAOXOgnOH/8qLMklSN4uTEPA3N6KLUAg1LK3OdVFtjTV1jLQMro1gdQx1jzf9gs7jApnGB2f8B "R – Try It Online")
Simply changes the order of the elements of the input vector.
Well, actually a basic approach is shorter:
### [R](https://www.r-project.org/), 35 bytes
```
write(matrix(rev(scan()),3,,T),1,3)
```
[Try it online!](https://tio.run/##LYwxCoAwFEP3nuJDlxb@8vut2nt4AREHBx2qqLevsUoIhOSRXKxQIIUaivRlC0c4oAvolMT82Au11FFPCVhCVuSIrcMm5crLMbt1PPJyuzyfbp/GzXnPyjx4FlZf6pOpT6Y@lQc "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ṚZṚ
```
[Try it online!](https://tio.run/##y0rNyan8///hzllRQPz////oaEMdBSMdBeNYHYVoEx0FUx0FMxDTXEfBQkfBMjYWAA "Jelly – Try It Online")
Uses Python list format for I/O.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
yÔÔ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=t224&code=edTU&footer=Vm24tw&input=IjEgMiAzCjQgNSA2CjcgOCA5Ig)
```
yÔÔ :Implicit input of 2D array
y :Transpose
Ô :Reverse rows
Ô :Reverse array
```
[Answer]
# [Factor](https://factorcode.org/) + `math.matrices`, 27 bytes
```
[ anti-flip simple-table. ]
```
`anti-flip` postdates build 1525, the one TIO uses, so here's a picture of running this in Factor's REPL:
[](https://i.stack.imgur.com/zSXl0.gif)
Note that in a standard output context, `simple-table.` outputs its elements with spaces in between. In the REPL, it's a little fancier.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 (or 3) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
|€#øRí»
```
[Try it online.](https://tio.run/##yy9OTMpM/f@/5lHTGuXDO4IOrz20@/9/QwUjBWMuEwVTBTMucwULBUsA)
With less strict I/O rules it would be 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead, with I/O being a 3x3 matrix of integers:
```
øRí
```
[Try it online.](https://tio.run/##yy9OTMpM/f//8I6gw2v//4@ONtQx0jGO1Yk20THVMQPS5joWOpaxsQA)
**Explanation:**
```
# e.g. input = "1 2 3\n4 5 6\n7 8 9"
| # Take all input-lines as a list of strings
# STACK: ["1 2 3","4 5 6","7 8 9"]
€# # Split each line by spaces
# STACK: [["1","2","3"],["4","5","6"],["7","8","9"]]
ø # Zip the matrix, swapping rows with columns
# STACK: [["1","4","7"],["2","5","8"],["3","6","9"]]
R # Reverse the order of rows in the matrix
# STACK: [["3","6","9"],["2","5","8"],["1","4","7"]]
í # Reverse each row of the matrix
# STACK: [["9","6","3"],["8","5","2"],["7","4","1"]]
» # Join each row by spaces, and then everything by newlines
# STACK: "9 6 3\n8 5 2\n7 4 1"
# (after which it is output implicitly)
```
Here some alternatives with different order of operations:
```
øíR
Ríø
íRø
íøí
RøR
```
[Answer]
# [flax](https://github.com/Pygamer0/flax), 2 bytes
```
Ṙ∝
```
ATO doesn't have the lastest commit of flax (because I keep discovering bugs). So here is an image of it in action:
[](https://i.stack.imgur.com/XUlPV.png)
[Answer]
# JavaScript, 103 bytes
Expects string input and outputs string
```
s=>(s=s.split`
`.map(x=>x.split` `))[0].map((_,c)=>s.map((_,r)=>s[2-r][2-c])).map(x=>x.join` `).join`
`
```
Try it:
```
f=s=>(s=s.split`
`.map(x=>x.split` `))[0].map((_,c)=>s.map((_,r)=>s[2-r][2-c])).map(x=>x.join` `).join`
`
;[
`1 2 3
3 4 5
1 2 3`,
`1 2 3
4 5 6
7 8 9`
].forEach(x=>console.log(f(x)))
```
# JavaScript, 45 bytes
Expects 2D array input and outputs 2D array
```
m=>m[0].map((_,c)=>m.map((_,r)=>m[2-r][2-c]))
```
Try it:
```
f=m=>m[0].map((_,c)=>m.map((_,r)=>m[2-r][2-c]))
;[
[
[1, 2, 3],
[3, 4, 5],
[1, 2, 3]
],
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
].forEach(x=>console.log(JSON.stringify(f(x))))
```
] |
[Question]
[
*Alternatively: That one challenge I forgot I had in the sandbox and is about stuff from Discrete Mathematics I learned like 5-6 months ago and kinda don't remember*
Given a path of vertices that form a cycle on a graph, output a simple version of the cycle. That is, if a vertex appears twice, snip out the part in between the two appearances.
## Context
Let \$u\$ and \$v\$ be vertices of graph \$G\$. If there is a cycle from \$u\$ to \$v\$ of length \$n\$, then there exists a simple cycle from \$u\$ to \$v\$ with length \$\le n\$.
This is because any cycle \$v\_1, e\_1, v\_2, e\_2, ..., e\_m, v\_m\$ with a vertex visited twice (that is, \$v\_i = v\_j\$ for some \$v\_i\$ and \$v\_j\$ in \$G\$, where \$ i < j\$), can be reduced to \$v\_1, e\_1, ..., e\_i, v\_j, e\_{j+1}\$ and still be a valid cycle between \$u\$ and \$v\$.
For the sake of this challenge, the edges connecting vertices will be ignored, as the edge taken when going between vertices will be assumed arbitrary.
## Worked Example
Take the graph \$K\_5\$:
[](https://i.stack.imgur.com/FLNI8.png)
One cycle between vertices \$1\$ and \$3\$ might look like:
[](https://i.stack.imgur.com/JCt7m.png)
That is, the path taken is `[1, 2, 5, 4, 2, 3, 5]`. However, that cycle can be simplified to:
[](https://i.stack.imgur.com/Z6FXJ.png)
Which has path `[1, 2, 3, 5]`. This cycle is a simple cycle, as only the first and last vertices are equal.
Note that cycles are snipped in the order they come.
## Rules
* There will always be a simpler cycle in the input.
* The input will be a list of vertices in a graph. Whether you take those as numbers, characters or some other way is up to you.
* There will always be at least 2 vertices.
* Each vertex has degree >= 2.
* Input and output can be given in any reasonable and convenient format.
* As the input represents a cycle, the vertex that is the start and end of the cycle will not be in the input.
* There won't be multiple overlapping simplified paths in the input.
* There'll be one and only one output for each input.
Note that the simple cycle may not be the shortest cycle, and the shortest cycle may not be the simple cycle.
## Test Cases
*Assuming that numbers are used as vertex labels*
```
[1,2,3,4,2,5] -> [1,2,5]
[4,3,6,2,3,8,5,2,8,7] -> [4,3,8,7]
[1,1,2] -> [1,2]
[1,2,7,2,7,2,3,7] -> [1,2,3,7]
```
This is code golf, so make sure you simplify the byte count of your answers.
[Answer]
# Wolfram Mathematica, ~~36~~ 35 bytes
```
#//.{a___,b_,___,b_,c___}:>{a,b,c}&
```
-1 byte thanks to @att.
Explanation:
* `#` and `&` define an anonymous function, e.g., `#+1&` is a function that adds 1 to its argument.
* `//.` is `ReplaceRepeated`, and keeps applying the pattern on the right to the expression on the left until its no longer changing
* `:>` is pattern replacement, it replaces the expression on the left with the expression on the right
* Finally, `_` means "any element" and `___` means any sequence of elements (including empty sequences). The variable before `_` or `___` assigns the matched expression to the variable.
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), ~~43~~ 39 bytes
```
i:0(?v:l3p:l$4p
/2~/
1+>3g:?!;:nao:4g
```
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTowKD92OmwzcDpsJDRwXG4gIC8yfi9cbjErPjNnOj8hOzpuYW86NGciLCJpbnB1dCI6IjEsIDIsIDcsIDIsIDcsIDIsIDMsIDciLCJzdGFjayI6IiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJudW1iZXJzIn0=)
## Explanation
[](https://i.stack.imgur.com/HBMvw.png)
Top row copies every element. The raw data will be stored in the third row of the code box. (`:l2-3p`) The fourth row stores the last index each character is encountered. (`l2-$4p`).
The third row prints the data based on the value stored. First, get the number at the specified position. `3g`. Check if it's 0, if so exit. `?!;`. Print the number followed by a line break `nao`. Then we jump to the last occurrence of that character plus one `4g1+`
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ 7 bytes
```
≬h€÷↔∩h
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4omsaOKCrMO34oaU4oipaCIsIiIsIlsxLDIsMyw0LDIsNV1cbls0LDMsNiwyLDMsOCw1LDIsOCw3XVxuWzEsMSwyXVxuWzEsMiw3LDIsNywyLDMsN10iXQ==)
```
≬ # three element lambda:
h # head
€ # split by
÷ # push each item to stack
```
This lambda takes a list. If length > 0 it splits by the first element and returns the last chunk. If length == 0 it does nothing.
```
↔ # apply the lambda and collect results until the the result doesn't change
∩ # transpose
h # head
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 11 bytes
```
(\w).*\1
$1
```
[Try it online!](https://tio.run/##K0otycxL/P9fI6ZcU08rxpBLxfD//2hDHSMdYx0TIGkayxVtAmSbgUUsdEyBtIWOOVDUUAeoCkwb6ZhDsTFQBgA "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input as a list of letters (or digits or `_`). If input as a string of non-newline characters is acceptable, then for 10 bytes:
```
(.).*\1
$1
```
[Try it online!](https://tio.run/##K0otycxL/P9fQ09TTyvGkEvF8P9/QyNjEyNTLhNjMyNjC1MjC3MuQ0MjLkMjcyA0NgcA "Retina 0.8.2 – Try It Online") Link includes test cases.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 6 bytes (12 nibbles)
```
.`.$/%$/$$@/
```
Approach based on [AndrovT's Vyxal answer](https://codegolf.stackexchange.com/a/256928/95126): upvote that!
Vertices are represented by characters.
```
`. # iterate while unique
$ # (starting with input):
%$ # split the result-so-far
/$$ # on its first element
/ @ # and get the last part
. # now map over results of each iteration
/ # returning the first element each time.
```
[](https://i.stack.imgur.com/pbMZg.png)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 35 bytes
```
f=a=>a&&a[0]+f(a.split(a[0]).pop())
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbR1i5RTS0x2iBWO00jUa@4ICezRAPE1dQryC/Q0NT8n5yfV5yfk6qXk5@ukaahZGhkbGJkqqSpqQAC@voKQBFTJS40VSbGZkbGFqZGFuYglSBVJsZANroyQ0MjmElwwzAVGZkDobE5RCVEEZD3HwA "JavaScript (Node.js) – Try It Online") Link includes test cases. Takes input as a string of characters.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.œR.Δε¬Qθ}P}€н
```
[Try it online](https://tio.run/##yy9OTMpM/f9f7@jkIL1zU85tPbQm8NyO2oDaR01rLuz9/z/aUMdIx1THDEga65jGAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vaOTg/TOTTm39dCawHM7agNqHzWtubD3v87/6GhDHSMdUx0zIGmsYxqrA@Yb65iARIE8EyAbImcBVGUEJM3BaoCqoGrNodgYKBMLAA).
**Explanation:**
```
.œ # Get all partitions of the (implicit) input-list
R.Δ # Find the last one (first one of the reversed list) that's truthy for:
ε # Map over each part of the current partition:
¬ # Get the head (without popping the list)
Qθ # Check if it's equal to the last item in the list
}P # After the map: check if all parts were truthy by taking the product
}€ # After the findFirst, map over the parts of the found partition:
н # Only leave their first integer
# (after which this list is output implicitly as result)
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 67 bytes
```
f=lambda x,b=[]:x and f(x[len(x)-x[::-1].index(x[0]):],b+x[:1])or b
```
[Try it online!](https://tio.run/##PY/BboQgEEDvfsXEC5COm7JqNST2RywHrJglcZEoaejX29Hd7YGZ8HjDzITfeFt82YZ136duNvdhNJBw6HqtEhg/wsRTP1vPkyhSr1Qh9cX50SbC71oojcMbcanFssKwR7vFDTrI87yXeMUSK4q1huITTlDrrK8If5yPLdaUW2weQnWihhSJJP9XneCKzfOUL18@L9QtyyYa4GgPzp95u2xhdpGzL8@EysDhQoPdTeD2x8x4KC/j@IwJkUFYnY/c4YMgLe8EMpuC/Y52VAwXsf8B "Python 3.8 (pre-release) – Try It Online")
Reverse lookup approach. We find the last occurrence and jump to it
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 78 bytes
```
f=lambda x,b=[]:x and f(x[1:],(b[:b.index(x[0])]if x[0]in b else b)+x[:1])or b
```
[Try it online!](https://tio.run/##PZDdboQgEEbvfYqJN0I63ZRVqyGxL0K5kIopiYtESUOf3o7sbi/4O5xhvhB@4/fq6z5sxzEPy3gz0wgJzaC0TDD6CWaWlJAamVHSXJyfbCLyprl2M5wb58GAXXYLhr8kJYXm6wbmiHaPOwxQlqUSeMUaG5pbDa8fkEGrC9UQfs@XPba09tjdhSajjhSBJP9XZXDF7jHqpy8eB@pWFDMFONsDZcsxLntYXGTVp6@4LMDhSsFuY2D2Z1zwVJ7G@VjFeQFhcz4yh3eC9A@OY2VTsF/RTrLClR9/ "Python 3.8 (pre-release) – Try It Online")
Takes a list of integers.
Idea is if we encounter an element we already passed through, we prune all elements between them
[Answer]
# [Haskell](https://www.haskell.org/), 53 bytes
```
q(_,_:y)=f y
q(y,_)=f y
f(a:b)=a:q(break(==a)b)
f x=x
```
[Try it online!](https://tio.run/##JcZBCsIwEAXQfU7xFy4mMButFhqYk4iECTYYUquJLprTp6Bv9R76yfOy9F7Is3fNSkQzhRr7fyOpC1bUFQp11kwiaoM1EZts/alpheD@MsC7pvWLAyKuRz7xwGe@8PjbdOs7 "Haskell – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~53~~ 52 bytes
```
a=>a.filter(u=(x,i)=>a.lastIndexOf(u=+u||x)-i?0:u=a)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLy0zpyS1SKPUVqNCJ1MTJJKTWFzimZeSWuGfBhTWLq2pqdDUzbQ3sCq1TdT8n5yfV5yfk6qXk5@ukaYRbahjpGOsYwIkTWM1NRVgQF9fASxlGsuFpsEEqNwMrMlCxxRIW@iYgzSCNJiABc0xtBjqAI1CNh3FDizKjXTModgYYjqyk4yx2YBpOlxL7H8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~17~~ 13 bytes
```
WΦθ¬λ«ι≔⊟⪪θιθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDLTOnJLVIo1BHwS@/RCNHU1NToZqLM6AoM69EI1PTmovTsbg4Mz1PIyC/QCO4ICezBKQ0U1NTR6EQKFv7/7@JsZmRsYWpkYX5f92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
WΦθ¬λ«
```
Repeat until the input string is empty, but calculated as the input string excluding any characters with a non-zero index, so that the result of the calculation becomes the loop variable.
```
ι
```
Output the first character of the input string.
```
≔⊟⪪θιθ
```
Split the string on its first character and take the last part. Edit: Saved 4 bytes by copying this approach from @DominicvanEssen (who based it on another answer but I found his answer clearer).
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/index.html), 40 bytes
```
f(a:_++a:b?a:b)|notElem a b=a:f b
f[]=[]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m706ubSoqDK-IDE7uXjBgqWlJWm6Fjc10jQSreK1tROtkuyBWLMmL7_ENSc1VyFRIck20SpNIYkrLTrWNjoWon5XbmJmnoKtQppCtKGOkY45FBvrmEMVwAwGAA)
[Answer]
# [Scala](http://www.scala-lang.org/), 121 bytes
Golfed version, [try it online!](https://tio.run/##ZVDBasMwDL33K0TZwWZpoGu3jkALY6dCx6Bjp9KDljiph@sEWx0rJd@eyU5XOnaRn/TekyX5HA129cenygleUFs4DQAKVcKeE4Gu8hk8OYfHzRs5bautzODdaoJ5VAJ8oQFSnp7RK8/VlfYkIgM9Hidwl8AkgWkE9zK5ZqeRevjVPLIgYgazv0ruE1r9K7J4dhUnwRglchCfy3BpWTuF@Q5OoG1z4BUW51ZhB6f8wYS1ShFZeeYa3pqMFX64DOUMbiKdwDoaOO@dw97Qcmy7cMBSmCzMuFla2sq54e9NsVIliVBN1b6hY8@dBCZazhe6FJjmtSU@vRdaSkwLVzdrXe2IGaNsRbsRA/S0tIX6fuVZ5WgslfEKMLvVbdd2Pw)
```
def f(l:List[Int])=l.foldLeft(List.empty[Int]){(a,i)=>if(a.contains(i))a.dropRight(a.length-a.lastIndexOf(i)-1)else a:+i}
```
Ungolfed version
```
object Main {
def main(args: Array[String]): Unit = {
val testCases = List(
List(1, 2, 3, 4, 2, 5),
List(4, 3, 6, 2, 3, 8, 5, 2, 8, 7),
List(1, 1, 2),
List(1, 2, 7, 2, 7, 2, 3, 7)
)
testCases.foreach { input =>
val result = f(input)
println(s"Input: $input, Result: $result")
}
}
def f(input: List[Int]): List[Int] = {
input.foldLeft(List.empty[Int]) { (acc, item) =>
if (acc.contains(item)) {
acc.dropRight(acc.length - acc.lastIndexOf(item) - 1)
} else {
acc :+ item
}
}
}
}
```
[Answer]
# JavaScript (ES6), 53 bytes
### Version 1
```
f=(a,i=0,v=a[i])=>v?[v,...f(a,a.lastIndexOf(v)+1)]:[]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjUSfT1kCnzDYxOjNW09auzD66TEdPTy8NKJGol5NYXOKZl5Ja4Z@mUaapbagZaxUd@z85P684PydVLyc/XSNNI9pQx0jHWMcESJrGamoqwIC@vgJYyjSWC02DCVC5GViThY4pkLbQMQdpBGkwAQuaY2gx1AEahWw6ih1YlBvpmEOxMcR0ZCeBhP4DAA "JavaScript (Node.js) – Try It Online")
### Version 2
```
f=a=>a+a?[v=a[0],...f(a.slice(a.lastIndexOf(v)+1))]:a
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbR1i5RO9E@usw2MdogVkdPTy9NI1GvOCczORVI5yQWl3jmpaRW@KdplGlqG2pqxlol/k/OzyvOz0nVy8lP10jTiDbUMdIx1jEBkqaxmpoKMKCvrwCWMo3lQtNgAlRuBtZkoWMKpC10zEEaQRpMwILmGFoMdYBGIZuOYgcW5UY65lBsDDEd2Ukgof8A "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
## Problem
John bought 5 apples. You are given the weights of every group of four apples, and must then find the weights of the apples themselves.
For example, if all apples without the first one weigh 798 g, without the second - 794 g, without the third - 813 g, without the fourth - 806 g, and without the fifth - 789 g, the weights are 202, 206, 187, 194, and 211.
## Rules
1. The solution of the problem by enumeration is allowed
2. Consider the number of points as follows: the number of bytes in your code. The lower the number of points, the better.
Have fun!
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 3 (or 5) [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
Σ¼,
```
No idea why MathGolf has a single-byte `a//4` builtin, but it's pretty useful here. ;)
[Try it online.](https://tio.run/##y00syUjPz0n7///c4kN7dP7/jza3tNAxtzTRsTAw1rEwNNMxt7CMBQA)
With strict input of space-delimited values it would be 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) instead:
```
ê_Σ¼,
```
[Try it online.](https://tio.run/##y00syUjPz0n7///wqvhziw/t0fn/39zSQsHc0kTBwsBYwcLQTMHcwhIA)
**Explanation:**
```
# Optional for stricter space-delimited input:
ê # Push the inputs as integer-array
_ # Duplicate it
Σ # Sum the values together
¼ # Integer-divide it by 4
, # Subtract each value in the list from this sum//4
# (after which the entire stack is output implicitly)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ ~~7~~ ~~6~~ 5 bytes
```
∑4ḭ$-
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiJE04bitJC0iLCIiLCJbNzk4LDc5NCw4MDMsODE2LDc4OV0iXQ==)
## Explanation
```
∑4ḭ$-
# (implicit input)
∑ # Sum
4ḭ # Divide the sum by four
$- # Swap and subtract
```
*-2 bytes thanks to a stone arachnid*
*-1 byte thanks to ovs*
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/index.html), ~~8~~ 6 bytes
*Edit: -2 bytes thanks to ovs*
```
-+´÷⟜4
```
[Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=QXBwbGVzIOKGkCAtK8K0w7fin5w0CkFwcGxlcyA3OTjigL83OTTigL84MTPigL84MDbigL83ODkK)
```
÷⟜4 # divide each of the input values by 4
+´ # and then fold the 'plus' function across them
- # using the negative of the input as a list of starting values
# (so effectively we start the fold using each negative input value
# in parallel as a starting value)
```
[Answer]
# [Python](https://www.python.org), 32 bytes
```
lambda a:[sum(a)/4-x for x in a]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3FXISc5NSEhUSraKLS3M1EjX1TXQrFNLyixQqFDLzFBJjoepUCooy80o0tNI0os0tLXQUzC1NdBQsDIyBhKEZkGthGaupCVG7YAGEBgA)
[Answer]
# [Haskell](https://www.haskell.org), 18 bytes
```
map=<<(-).(/4).sum
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ0W0km5yQYFS7OI025ilpSVpuhabchMLbG1sNHQ19TT0TTT1iktzIRI39XMTM_MUbBVS8rkUFAqKMvNKFFQU0hSizS0tdBTMLU10FCwMjIGEoRmQa2EZC9G2YAGEBgA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
aWx÷4
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LW0&code=YVd49zQ&input=Wzc5OCw3OTQsODEzLDgwNiw3ODld)
[Answer]
# [λ-2d](https://l-2d.glitch.me/), 456 squares
the program can be imported in [the playground](https://l-2d.glitch.me/) with the following JSON file
```
{"41,13":"entry","41,18":"entry","41,23":"entry","41,28":"entry","41,32":"entry","42,13":"end_s","42,18":"end_s","42,23":"end_s","42,28":"end_s","42,32":"end_s","43,13":"end_e","43,18":"end_e","43,23":"end_e","43,28":"end_e","43,32":"end_e","39,15":"wire_nw","39,20":"wire_nw","39,25":"wire_nw","39,30":"wire_nw","39,34":"wire_nw","38,15":"wire_ne","38,20":"wire_ne","38,25":"wire_ne","38,30":"wire_ne","38,34":"wire_ne","44,13":"frame_tl","44,18":"frame_tl","44,23":"frame_tl","44,28":"frame_tl","44,32":"frame_tl","45,13":"wire_we","45,18":"wire_we","45,23":"wire_we","45,28":"wire_we","45,32":"wire_we","46,13":"wire_we","46,18":"wire_we","46,23":"wire_we","46,28":"wire_we","46,32":"wire_we","47,13":"wire_we","47,18":"wire_we","47,23":"wire_we","47,28":"wire_we","47,32":"wire_we","47,15":"wire_we","47,20":"wire_we","47,25":"wire_we","47,30":"wire_we","47,34":"wire_we","46,15":"wire_we","46,20":"wire_we","46,25":"wire_we","46,30":"wire_we","46,34":"wire_we","45,15":"wire_we","45,20":"wire_we","45,25":"wire_we","45,30":"wire_we","45,34":"wire_we","48,13":"wire_sw","48,18":"wire_sw","48,23":"wire_sw","48,28":"wire_sw","48,32":"wire_sw","48,15":"wire_nw","48,20":"wire_nw","48,25":"wire_nw","48,30":"wire_nw","48,34":"wire_nw","44,15":"wire_ne","44,20":"wire_ne","44,25":"wire_ne","44,30":"wire_ne","44,34":"wire_ne","44,14":"wire_ns","44,19":"wire_ns","44,24":"wire_ns","44,29":"wire_ns","44,33":"wire_ns","48,14":"wire_ns","48,19":"wire_ns","48,24":"wire_ns","48,29":"wire_ns","48,33":"wire_ns","42,14":"wire_nw","42,19":"wire_nw","42,24":"wire_nw","42,29":"wire_nw","42,33":"wire_nw","41,14":"wire_we","41,19":"wire_we","41,24":"wire_we","41,29":"wire_we","41,33":"wire_we","40,14":"wire_we","40,19":"wire_we","40,24":"wire_we","40,29":"wire_we","40,33":"wire_we","38,14":"wire_sw","38,19":"wire_sw","38,24":"wire_sw","38,29":"wire_sw","38,33":"wire_sw","39,14":"func_call","39,19":"func_call","39,24":"func_call","39,29":"func_call","39,33":"func_call","39,13":"joint_nsw","39,18":"joint_nsw","39,23":"joint_nsw","39,28":"joint_nsw","38,13":"wire_we","38,18":"wire_we","38,23":"wire_we","38,28":"wire_we","37,13":"wire_se","37,18":"wire_se","37,23":"wire_se","37,28":"wire_se","37,14":"wire_nswe","37,19":"wire_nswe","37,24":"wire_nswe","37,29":"wire_nswe","37,17":"wire_nw","37,22":"wire_nw","37,27":"wire_nw","37,32":"wire_nw","36,17":"wire_se","36,22":"wire_se","36,27":"wire_se","36,32":"wire_se","37,15":"wire_ns","37,20":"wire_ns","37,25":"wire_ns","37,30":"wire_ns","36,15":"wire_nw","36,20":"wire_nw","36,25":"wire_nw","36,30":"wire_nw","36,34":"wire_nw","35,15":"wire_ne","35,20":"wire_ne","35,25":"wire_ne","35,30":"wire_ne","35,34":"wire_ne","35,14":"wire_sw","35,19":"wire_sw","35,24":"wire_sw","35,29":"wire_sw","35,33":"wire_sw","36,14":"func_call","36,19":"func_call","36,24":"func_call","36,29":"func_call","36,33":"func_call","36,13":"joint_nsw","36,18":"joint_nsw","36,23":"joint_nsw","36,28":"joint_nsw","35,13":"wire_we","35,18":"wire_we","35,23":"wire_we","35,28":"wire_we","34,13":"wire_se","34,18":"wire_se","34,23":"wire_se","34,28":"wire_se","34,14":"wire_nswe","34,19":"wire_nswe","34,24":"wire_nswe","34,29":"wire_nswe","34,17":"wire_nw","34,22":"wire_nw","34,27":"wire_nw","34,32":"wire_nw","33,17":"wire_se","33,22":"wire_se","33,27":"wire_se","33,32":"wire_se","34,15":"wire_ns","34,20":"wire_ns","34,25":"wire_ns","34,30":"wire_ns","33,15":"wire_nw","33,20":"wire_nw","33,25":"wire_nw","33,30":"wire_nw","33,34":"wire_nw","32,15":"wire_ne","32,20":"wire_ne","32,25":"wire_ne","32,30":"wire_ne","32,34":"wire_ne","32,14":"wire_sw","32,19":"wire_sw","32,24":"wire_sw","32,29":"wire_sw","32,33":"wire_sw","33,14":"func_call","33,19":"func_call","33,24":"func_call","33,29":"func_call","33,33":"func_call","33,13":"joint_nsw","33,18":"joint_nsw","33,23":"joint_nsw","33,28":"joint_nsw","32,13":"wire_we","32,18":"wire_we","32,23":"wire_we","32,28":"wire_we","31,13":"wire_se","31,18":"wire_se","31,23":"wire_se","31,28":"wire_se","31,14":"wire_nswe","31,19":"wire_nswe","31,24":"wire_nswe","31,29":"wire_nswe","31,17":"wire_nw","31,22":"wire_nw","31,27":"wire_nw","31,32":"wire_nw","30,17":"wire_se","30,22":"wire_se","30,27":"wire_se","30,32":"wire_se","31,15":"wire_ns","31,20":"wire_ns","31,25":"wire_ns","31,30":"wire_ns","30,15":"wire_nw","30,20":"wire_nw","30,25":"wire_nw","30,30":"wire_nw","30,34":"wire_nw","29,15":"wire_ne","29,20":"wire_ne","29,25":"wire_ne","29,30":"wire_ne","29,34":"wire_ne","29,14":"wire_sw","29,19":"wire_sw","29,24":"wire_sw","29,29":"wire_sw","29,33":"wire_sw","30,14":"func_call","30,19":"func_call","30,24":"func_call","30,29":"func_call","30,33":"func_call","30,13":"joint_nsw","30,18":"joint_nsw","30,23":"joint_nsw","30,28":"joint_nsw","29,13":"wire_we","29,18":"wire_we","29,23":"wire_we","29,28":"wire_we","28,13":"wire_se","28,18":"wire_se","28,23":"wire_se","28,28":"wire_se","28,14":"wire_nswe","28,19":"wire_nswe","28,24":"wire_nswe","28,29":"wire_nswe","28,17":"wire_nw","28,22":"wire_nw","28,27":"wire_nw","28,32":"wire_nw","27,17":"wire_se","27,22":"wire_se","27,27":"wire_se","27,32":"wire_se","28,15":"wire_ns","28,20":"wire_ns","28,25":"wire_ns","28,30":"wire_ns","27,14":"func_call","27,19":"func_call","27,24":"func_call","27,29":"func_call","27,33":"func_call","27,13":"joint_nsw","27,18":"joint_nsw","27,23":"joint_nsw","27,28":"joint_nsw","26,13":"wire_se","26,18":"wire_se","26,23":"wire_se","26,28":"wire_se","26,14":"wire_ns","26,19":"wire_ns","26,24":"wire_ns","26,29":"wire_ns","26,15":"wire_ns","26,20":"wire_ns","26,25":"wire_ns","26,30":"wire_ns","26,16":"wire_ne","26,21":"wire_ne","26,26":"wire_ne","26,31":"wire_ne","27,16":"wire_we","27,21":"wire_we","27,26":"wire_we","27,31":"wire_we","29,16":"wire_we","29,21":"wire_we","29,26":"wire_we","29,31":"wire_we","30,16":"wire_we","30,21":"wire_we","30,26":"wire_we","30,31":"wire_we","32,16":"wire_we","32,21":"wire_we","32,26":"wire_we","32,31":"wire_we","33,16":"wire_we","33,21":"wire_we","33,26":"wire_we","33,31":"wire_we","35,16":"wire_we","35,21":"wire_we","35,26":"wire_we","35,31":"wire_we","36,16":"wire_we","36,21":"wire_we","36,26":"wire_we","36,31":"wire_we","39,16":"wire_sw","39,21":"wire_sw","39,26":"wire_sw","39,31":"wire_sw","39,17":"wire_ns","39,22":"wire_ns","39,27":"wire_ns","39,32":"wire_ns","38,16":"wire_we","38,21":"wire_we","38,26":"wire_we","38,31":"wire_we","28,16":"wire_nswe","28,21":"wire_nswe","28,26":"wire_nswe","28,31":"wire_nswe","31,16":"wire_nswe","31,21":"wire_nswe","31,26":"wire_nswe","31,31":"wire_nswe","34,16":"wire_nswe","34,21":"wire_nswe","34,26":"wire_nswe","34,31":"wire_nswe","37,16":"wire_nswe","37,21":"wire_nswe","37,26":"wire_nswe","37,31":"wire_nswe","28,33":"wire_we","31,33":"wire_we","34,33":"wire_we","37,33":"wire_we","39,12":"num_7","40,12":"num_8","41,12":"num_9","36,11":"num_8","37,11":"num_0","38,11":"num_6","33,12":"num_8","34,12":"num_1","35,12":"num_3","30,11":"num_7","31,11":"num_9","32,11":"num_4","28,12":"num_9","29,12":"num_8","27,12":"num_7","30,12":"wire_ns","36,12":"wire_ns","27,15":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"27,20":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"27,25":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"27,30":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"27,34":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"53,12":"func_def","55,12":"func_def","57,12":"func_def","59,12":"func_def","61,12":"func_def","54,12":"end_s","58,12":"end_s","56,12":"end_s","60,12":"end_s","62,12":"end_s","63,12":"end_e","54,11":"label","55,11":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"53,11":"wire_se","54,13":"joint_nse","55,16":"op_plus","57,16":"op_plus","59,16":"op_plus","61,16":"op_plus","55,15":"func_call","57,15":"func_call","59,15":"func_call","61,15":"func_call","56,13":"wire_nswe","58,13":"wire_nswe","61,13":"wire_we","60,13":"wire_nswe","62,13":"wire_nswe","59,13":"wire_we","57,13":"wire_we","55,13":"wire_we","55,14":"wire_sw","54,14":"wire_ne","56,15":"wire_nw","58,15":"wire_nw","60,15":"wire_nw","57,14":"wire_sw","59,14":"wire_sw","60,14":"func_call","61,14":"wire_sw","56,14":"func_call","58,14":"func_call","62,14":"func_call","62,15":"wire_nw","63,14":"wire_sw","63,15":"wire_ns","63,16":"func_call","63,17":"op_div","64,16":"wire_nw","64,15":"func_call","64,14":"num_4","65,15":"wire_sw","65,16":"func_call","65,17":"op_minus","66,16":"wire_nw","66,14":"func_call","67,14":"wire_nw","66,13":"wire_sw","67,12":"wire_sw","66,15":"wire_ns","67,13":"wire_ns","63,13":"wire_we","64,13":"wire_we","65,13":"wire_we","64,12":"wire_we","65,12":"wire_we","66,12":"wire_we"}
```
[](https://i.stack.imgur.com/aClTn.png)
the function in itself is the right structure, the left one being 5 calls to the function with the 5 arguments in differents orders
---
## js equivalent
```
a=798
b=794
c=813
d=806
e=789
f=v=>w>=>x=>y=>z=>((v+w+x+y+z)/4)-v
f(a)(b)(c)(d)(e)
f(b)(c)(d)(e)(a)
f(c)(d)(e)(a)(b)
f(d)(e)(a)(b)(c)
f(e)(a)(b)(c)(d)
```
---
Language explanation can be found in [the playground](https://l-2d.glitch.me/) by loading the *cheatsheet* example, or in the [release blog post](https://www.media.mit.edu/projects/2d-an-exploration-of-drawing-as-programming-language-featuring-ideas-from-lambda-calculus/overview/)
[Answer]
# Excel, 15 bytes
```
=SUM(A1#)/4-A1#
```
Input is in cell A1 as an array. For instance, `={798;794;813;806;789}`
[](https://i.stack.imgur.com/b7PhL.png) [](https://i.stack.imgur.com/ODCEq.png)
---
# Excel, 19 bytes
```
=SUM(A1:A5)/4-A1:A5
```
Input is in the cells `A1:A5`. Doesn't rely on array input. Output is wherever the formula is. It's not a very interesting solution.
[](https://i.stack.imgur.com/3arY0.png)
[Answer]
# TI-Basic, 7 bytes
```
sum(Ans)/4-Ans
```
Takes input in `Ans`. Output is stored in `Ans` and displayed.
[Answer]
# [Desmos](https://desmos.com/calculator), 16 bytes
```
f(l)=l.total/4-l
```
[Try It On Desmos!](https://www.desmos.com/calculator/iscwqjxvd9)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/kzetwyayfs)
[Answer]
# [LOLCODE](http://lolcode.org/), 216 bytes
```
HOW IZ I f YR a
I HAS A s ITZ 0
IM IN YR l UPPIN YR i TIL BOTH SAEM i 5
s R SUM OF s a'Z SRS i
IM OUTTA YR l
IM IN YR l UPPIN YR i TIL BOTH SAEM i 5
VISIBLE DIFF OF QUOSHUNT OF s 4 a'Z SRS i
IM OUTTA YR l
IF U SAY SO
```
[Try it online!](https://tio.run/##jZA9D4IwFEX3/oq7uRkQVBxLhPQFsUpbFTbiR0JCwsD/DxaqA4OJ23vn5Z7k3bZr793jOQhO8JfBIOQVVIHwQlmgZgTBFTh6kK7gMcpBx/HUwpxObmyg6YBYagHFk9zua9ajgDI5ZGqj9aKCKhSaMS6N1nwy/C27kKL4kGBPaToaz0YqYY7a2cPf/hTGWkooOXwfqadHOGKTZaRZ/cFj3JtO2100o/6HhjO6mmjkBTMaOOpvZjR0hmjHbJ22XFct8oyXLNPiFpfJ8AY "LOLCODE – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~9~~ 7 bytes
```
$+a/4-a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkGFUuyCpaUlaboWy1W0E_VNdBMhPKjgzmilaHNLC2tzSxNrCwNjawtDM2tzC8tYuC4A)
*-2 bytes thanks to DLosc*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4? 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
With a strict interpretation of Rule 1 (can't take as a program argument due to the "single line" part) - a full program that reads from STDIN and writes to STDOUT:
```
ɠḲVµS÷4_
```
[Try it online!](https://tio.run/##y0rNyan8///kgoc7NoUd2hp8eLtJ/P//5pYWCuaWJgoWhsYKFgZmCuYWlgA)
...or with site default IO instead - a monadic Link that accepts a list of five numbers and yields a list of five numbers:
```
S÷4_
```
**[Try it online!](https://tio.run/##y0rNyan8/z/48HaT@P///0ebW1roKJhbmugoWBgaAwkDMyDXwjIWAA "Jelly – Try It Online")**
### How?
```
ɠḲVµS÷4_ - Main Link: no arguments
ɠ - read a line from STDIN
Ḳ - split that at spaces
V - evaluate that as Jelly code -> list of the five four-apple-weights, W
µ - start a new monadic chain - f(W)
S - sum W
4 - four
÷ - divide -> sum(W)/4
_ - subtract W (vectorises) -> [sum(W)/4-w1, sum(W)/4-w2, sum(W)/4-w3, sum(W)/4-w4, sum(W)/4-w5]
- implicit print
```
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 23 bytes
```
[ dup Σ 4 / swap n-v ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkqFXmpeZnJ@SCuZARMpSQWqLFQqKUktKKguKMvNKFKy5uKoVzC0tgNhEwcLAWMHC0EzB3MJSoVbhf7RCSmmBwrnFCiYK@grF5YkFCnm6ZQqx/5MTc3IU9P4DAA "Factor – Try It Online")
## Explanation
```
! { 798 794 803 816 789 }
dup ! { 798 794 803 816 789 } { 798 794 803 816 789 }
Σ ! { 798 794 803 816 789 } 4000
4 ! { 798 794 803 816 789 } 4000 4
/ ! { 798 794 803 816 789 } 1000
swap ! 1000 { 798 794 803 816 789 }
n-v ! { 202 206 197 184 211 }
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 22 bytes
```
->a{a.map{a.sum/4-_1}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhbbdO0SqxP1chMLgGRxaa6-iW68YW0tRHJfgUJadLS5pYWOgrmliY6ChYExkDA0A3ItLGNjIYoWLIDQAA)
[Answer]
# [Julia 1.0](http://julialang.org/), 14 bytes
```
!l=sum(l/4).-l
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/XzHHtrg0VyNH30RTTzfnv0NxRn65gmK0uaWFjoK5pYmOgoWhMZAwMANyLSxj/wMA "Julia 1.0 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 4 bytes
```
O4÷α
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f3@Tw9nMb//@PNre00DG3NNGxMDDWsTA00zG3sIwFAA "05AB1E – Try It Online")
*-5 bytes thanks to Kevin Cruijssen*
[Answer]
# [R](https://www.r-project.org/), 14 bytes
```
\(x)sum(x)/4-x
```
[Try it online!](https://tio.run/##K/r/P600L7kkMz9Po0KzuDQXSOqb6Fb8/19ho5usYW5poaNgbmmio2BhaAwkDMyAXAtLTQA "R – Try It Online")
Uses the new lambda, `\`, introduced in R 4.1.
[Answer]
# [J](https://www.jsoftware.com), 7 bytes
```
-~4%~+/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8GCpaUlaboWa9IUbK0UdOtMVOu09SFCe1OTM_IVaqwU0hTMLS2A2ETBwsBYwcLQTMHcwhKiBqYdAA)
[Answer]
# [jq](https://stedolan.github.io/jq/), ~~20~~ 9 bytes
```
add/4-.[]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70oq3DBgqWlJWm6FisTU1L0TXT1omMhfKjwgp3R5pYWOgrmliY6ChaGxkDCwAzItbCEqgMA)
*-11 bytes thanks to @ovs*
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 9 bytes
```
J++4./j?-
```
[Try it online!](https://tio.run/##SyotykktLixN/V@Q@t9LW9tETz/LXvf//2pzSwsFc0sTBQtDYwULAzMFcwvLWgUA "Burlesque – Try It Online")
```
J # Duplicate
++ # Sum
4./ # Divide by 4
j # Swap
?- # Subtract from each
```
[Answer]
# [Halfwit](https://github.com/chunkybanana/halfwit/), 5 bytes
```
kJ>+<k+N+N
```
[Try it online.](https://dso.surge.sh/#@WyJoYWxmd2l0IixudWxsLCJrSj4rPGsrTitOIiwiIiwiW1s3OThuLDc5NG4sODAzbiw4MTZuLDc4OW5dXSIsIiJd)
Inputs as a list of BigInts.
**Explanation:**
```
kJ # Sum the (implicit) input-list
>+< # Push compressed BigInt 4n
k+ # Integer-divide the sum by this 4
N+N # Subtract the values in the (implicit) input-list from this value:
N # Negate the value
+ # Add it to each value in the (implicit) input-list
N # Negate each value in the list
# (after which the result is output implicitly)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~61~~ 58 bytes
```
n,i;f(int*a){for(i=10;i--;)i>4?n+=a[i%5]:(a[i]=n/4-a[i]);}
```
[Try it online!](https://tio.run/##JYxBCsIwEEX3OUUoFBI7wRYbmxijByldhEpkFkYp7kLOHqe4mTfw/3@req5rrQnQRYHpewgyx/cm0A@9Q6WcxNt4T50PM7Z6uQji4tNxVPsjXamvgEnIzGjMw6wXnydrYLIjmOEEpj/DZGxxLIog6e5uaiL3vHeEK9eEriPDZ6MkiqZ9AG/g72eFlfoD "C (gcc) – Try It Online")
*-3 bytes thanks to ceilingcat*
[Answer]
# x86 32-bit machine code, 32 bytes
```
00000000: 87ca 31c0 6a05 5903 448a fce2 fac1 e802 ..1.j.Y.D.......
00000010: 6a05 5950 2b44 8afc 8944 8afc 58e2 f4c3 j.YP+D...D..X...
```
## Assembly
```
section .text
global func
func: ;void func(int *ecx);
; int *edx=ecx; int eax=0;
xchg ecx, edx
xor eax,eax
; for(ecx=5;ecx>0;ecx--)eax+=edx[ecx-1]
push 0x5
pop ecx
add:
add eax, [edx + 4*ecx-4]
loop add
; eax = eax / 4
shr eax, 2
; for(ecx=5;ecx>0;ecx--)edx[ecx-1]=eax-edx[ecx-1];
push 0x5
pop ecx
sub:
push eax
sub eax, [edx + 4*ecx-4]
mov [edx + 4*ecx-4], eax
pop eax
loop sub
; return
ret
```
Takes a pointer to an array of 5 integers in ECX (fastcall convention), and modifies the array in place with the results.
[Try it online!](https://tio.run/##fVPbjpswEH3GXzGK1AoITrK5NBdCHqpu1ZdqPyAbRcaYhBXYCMyW1Wq/PR2b1SZp0yIx@MycMzP2mJjVxxNnGtbr@4fvsIGhLsohG7C6ONWC60xJGGjRauIcchWzHNJGcmLMyjFP@KyyxDrdTGrwBW@9kDghdChpI/R0SLA2GmGs5ccDoDcADCNUlQkF@BIjTFXlYjSahWg3I2Mp9TDaj5C/NfBuR5yyqY8wame4UqVJRxyWJCtrbT7YIh36MDU90SlKcoVMDNsySIHI2iFMiVMfuy5g/L8mPupHyKVnGN7sp27i1XvAbM7gf3RWqOc/nUGnscnMwjaPGWx7ldBNJYmD3xPOjZC/RljrJh5wgpMTlQQ7pP2eaV1lcaPFfu@6Kas1Z3nueR/j870QSMEy6XqvxDEzy2TZ6D2rqu1sh8f1Ol8ugvlyGixGk2Bx9yWYL5ZvAfiWhvEC8ynujkdeAJkddiEKXr64lhCc0@E5j8w9ea@MXovw1I0sW8/CrN/3ygp7SN3ep@RR9gJL22Y7ZL4Ru2uJ1xRoKvJ0Mr64uUBVh7hKxECRA@fXLhRcntIlGahUtMwE0GIyJip@4qp8AfoAcSZZhaun7n@40pzXyCJGlTRFCfQb0J/m6ov8ir75PCaCH7GWgN6j9H3/64sWwFUj9QpRzzJ@YdMc1tfJb2h/iNZUOwvbNrkhIlfbP/0G "Try It Online")
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 4 bytes (8 nibbles)
```
+/+$4*~
```
```
+ # sum of
$ # the input
/ # divided by
4 # 4
+ # added to
# (implicitly) each element of input
* # multiplied by
~ # -1
```
[Answer]
# [J](https://www.jsoftware.com), 7 bytes
```
-~4%~+/
```
Nothing new here.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxXLfORLVOWx_Cu2muyZWanJGvkKZgbmkBxCYKFgbGChaGZgrmFpYYUoZAKQOwFET7ggUQGgA)
```
-~4%~+/
+/ NB. sum
4%~ NB. divide result by 4
-~ NB. subtract result by input, vectorized
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes
```
I⁻÷Σθ⁴θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYwzOvxCWzLDMlVSO4NFejUFNHwQSICzU1Na3//4@ONre00FEwtzTRUbAwNAYSBmZAroVlbOx/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input list
Σ Take the sum
÷ Integer divided by
⁴ Literal integer `4`
⁻ Vectorised subtract
θ Input list
I Cast to string
Implicitly print
```
9 bytes for a version that works with two or more apples, not just five:
```
I⁻÷Σθ⊖Lθθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYwzOvxCWzLDMlVSO4NFejUFNHwSU1uSg1NzWvJDVFwyc1L70kAyisCZQAkdb//0dHm1ta6CiYW5roKFgYGgMJAzMg18IyNva/blkOAA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~34~~ 32 bytes
```
a=>a.map(e=>eval(a.join`+`)/4-e)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGiNNulpSVpuhY3FRJt7RL1chMLNFJt7VLLEnM0EvWy8jPzErQTNPVNdFM1oeo0k_PzivNzUvVy8tM10jSizS0tdBTMLU10FCwMjIGEoRmQa2EZqwnVsGABhAYA)
-2 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)
[Answer]
# [Red](http://www.red-lang.org), 28 bytes
```
func[v][v -((sum v)/ 4)* -1]
```
[Try it online!](https://tio.run/##BcFLCoAgAAXAq7x2GUhJktox2oqL8AMRWph6fZvJ3vXDO20Q9h5qsroZ3UDH8asRjczgZAJlpr/5SgUB8bw9mrflyQO0UBJCcchlhWQbhFSm/w "Red – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 60 bytes
```
b,c;f(*a){for(b=c=0;b<5;c+=a[b++]);for(;b--;a[b]=c/4-a[b]);}
```
[Try it online!](https://tio.run/##HY7NDoIwEITP8BQbEpPWFvkRBLL2SQyHtoA2QTSCJ8Kz49bLZHYmu/vZ2I56uu@7kRYHdtR8HV4fZpRVKZpriVYofTNCtBx9gSaOkYJW2aSIveG47U/tJsbXMHDTAks/L7eyVbBWTS2hagoJdXYmSS801s2GkCQwP17fsQPTA@RpLkmozeqKxG/oqYM8y05hMDB/kSM5AvAfHLE5YnNC8PeHkoFFhw4i@X/tCCnc9h8 "C (clang) – Try It Online") Takes an array of 5 integers and modifies the array in-place.
] |
[Question]
[
# Background:
Here's a little simple challenge. You want to be able to find out whether the arrays inside an array have the same length.
# Input:
Your input should consist of exactly one array *(this is the value passed to the function, not a user input)*. Your function takes exactly 1 parameter. It could contain arrays or be empty. No error checking needed, assume only list is ever passed in. Assume a 1-D array such as `[1]` or `[1,2,3,4,5]` is never passed in.
# Output:
Return `true` if all the list elements have the same length, `false` if they don't, and the parameter itself if the list is empty (or null if your language doesn't support multiple return types).
### Some test cases:
```
List: [] - [] (or null/your language equivalent)
List: [[1], [1], [2]] - True
List: [[1]] - True
List: [[1, 2, 3, 4]] - True
List: [[1, 2, 3, 4, 5], [2], [12, 314123]] - False
List: [[1, 2, 3, 4], [1]] - False
```
No std(in/out) input/output needed (however, it is allowed, just not required!), the function only needs to return boolean values `true` or `false`; or the parameter itself if the function is passed an empty list (or null/your language equivalent). Only one return value is returned.
# Rules:
Shortest byte count wins, only function is necessary (full programs are allowed if you desire).
[Answer]
# Python 2, 31
```
lambda l:l and l==zip(*zip(*l))
```
This requires the lists to be lists of tuples. `zip` Drops extra elements if the input was ragged, so double zipping is only a noop if the lists all have the same length.
[Try it here](https://ideone.com/r4t3Ib)
[Answer]
# Pyth - ~~7~~ 5 bytes
*Saved 2 bytes thanks to @FryAmTheEggman.*
And I was the one who told @issacg to remove the `q` default...
```
?QqCC
```
[Test Suite](http://pyth.herokuapp.com/?code=%3FQqCC&test_suite=1&test_suite_input=%5B%5D%0A%5B%5B1%5D%2C+%5B1%5D%2C+%5B2%5D%5D%0A%5B%5B1%5D%5D%0A%5B%5B1%2C+2%2C+3%2C+4%5D%5D%0A%5B%5B1%2C+2%2C+3%2C+4%2C+5%5D%2C+%5B2%5D%2C+%5B12%2C+314123%5D%5D%0A%5B%5B1%2C+2%2C+3%2C+4%5D%2C+%5B1%5D%5D&debug=0).
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
L€E⁸ȧ
```
[Try it online!](http://jelly.tryitonline.net/#code=TOKCrEXigbjIpwrDh-KCrMWS4bmY&input=&args=W10sIFtbMV0sIFsxXSwgWzJdXSwgW1sxXV0sIFtbMSwgMiwgMywgNF1dLCBbWzEsIDIsIDMsIDQsIDVdLCBbMl0sIFsxMiwgMzE0MTIzXV0sIFtbMSwgMiwgMywgNF0sIFsxXV0)
### How it works
```
L€E⁸ȧ Monadic link. Argument: A (list)
L€ Map length over the list.
E Test if all elements are equal.
⁸ȧ Take the logical AND of A and the resulting Boolean.
```
[Answer]
# [Perl 6](http://perl6.org), 17 bytes
```
{$_??[==] $_!!$_}
```
`[==] $_` does a reduce of the input (`$_`) with `&infix:<==>`. `&infix:<==>` is a Numeric operator so it coerces its inputs to Numeric. The rest is just the ternary operator `??` `!!`.
This is roughly equivalent to
```
sub ( $_ ) {
if $_ {
# the 「map」 is for clarity, it is not needed
$_.map(*.elems).reduce(&infix:<==>)
# 「[OP] List」 is actually smarter than 「List.reduce(&infix:«OP»)」
# as it takes into account operator chaining, and associativity
} else {
$_
}
}
```
### Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
# put it into the lexical namespace for clarity
my &same-elems = {$_??[==] $_!!$_}
my @tests = (
[] => [],
[[1], [1], [2]] => True,
[[1],] => True,
[[1, 2, 3, 4],] => True,
[[1, 2, 3, 4, 5], [2], [12, 314123]] => False,
[[1, 2, 3, 4], [1]] => False,
);
plan +@tests;
for @tests -> ( :key(@input), :value($expected) ) {
is same-elems(@input), $expected, @input.perl
}
```
```
1..6
ok 1 - []
ok 2 - [[1], [1], [2]]
ok 3 - [[1],]
ok 4 - [[1, 2, 3, 4],]
ok 5 - [[1, 2, 3, 4, 5], [2], [12, 314123]]
ok 6 - [[1, 2, 3, 4], [1]]
```
[Answer]
# Javascript ES6, ~~44~~ ~~43~~ 42 bytes
Saved 1 byte thanks to @Neil
```
a=>a[0]?!a.some(b=>b.length-a[0].length):a
```
Alternative solutions
```
a=>a[0]?a.every(b=>b.length==a[0].length):a // 43
a=>a[0]?new Set(a.map(b=>b.length)).size==1:a // 45
a=>a[0]?Math.max(...a.map(b=>b.length))==a[0].length:a // 54
a=>a[0]?[a[0].length,...a].reduce((b,d)=>b==d.length):a // 55, doesn't work as intended
```
Somehow the stacksnippet doesn't print `[]`, try it in your console for the actual result.
```
f=
a=>a[0]?a.every(b=>b.length==a[0].length):a
z.innerHTML = [
[],
[[1], [1], [2]],
[[1]],
[[1, 2, 3, 4]],
[[1, 2, 3, 4, 5], [2], [12, 314123]],
[[1, 2, 3, 4], [1]]
].map(m=>JSON.stringify(f(m))).join`<br>`
```
```
<pre id=z>
```
(yay for crossed out 44)
[Answer]
# [Swift 3](http://swift.sandbox.bluemix.net/#/repl/597a1a65dc0b5b77d1ce1f1e) - 47 Bytes
```
{$0.isEmpty ?nil:Set($0.map{$0.count}).count<2}
```
To invoke, first assign it to a variable:
```
let f: ([[Any]]) -> Bool? = {$0.isEmpty ?nil:Set($0.map{$0.count}).count<2}
f([[1], [1,2], [1,2,3]])
```
[Answer]
## Mathematica, 22 bytes
```
a@{}={};a@b_:=ArrayQ@b
```
The requirement of `a[{}] == {}` ruins everything and prevents a 6 byte solution of the built-in `ArrayQ`, since in Mathematica a zero length array is also an array.
[Answer]
# Julia, 33 bytes
```
!x=[]==x?x:diff(map(endof,x))⊆0
```
[Try it online!](http://julia.tryitonline.net/#code=IXg9W109PXg_eDpkaWZmKG1hcChlbmRvZix4KSniioYwCgpmb3IgeCBpbiAoCiAgICBBbnlbXSwKICAgIEFueVtbMV0sIFsxXSwgWzJdXSwKICAgIEFueVtbMV1dLAogICAgQW55W1sxLCAyLCAzLCA0XV0sCiAgICBBbnlbWzEsIDIsIDMsIDQsIDVdLCBbMl0sIFsxMiwgMzE0MTIzXV0sCiAgICBBbnlbWzEsIDIsIDMsIDRdLCBbMV1dCikKICAgIHByaW50bG4oIXgpCmVuZA&input=)
### How it works
We redefine the unary operator **!** for this task.
If **x** is the empty array, we simply return **x**.
Else, we map `endof` (equivalent to `length`) over the arrays in **x** and compute the differences of consecutive lengths with `diff`. If all length are equal, this will generate an array of **0**'s. Otherwise, there will be non-zero numbers in the result.
Finally, `⊆0` tests if all differences are **0** and return the corresponding Boolean.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
.v|:ladl1
```
Returns `true` or `false` or the empty list.
### Explanation
```
.v Unify the output with the input if it's the empty list
| Or
:la Apply length to each element of the input
d Remove all duplicates
l1 The length of the resulting list is 1
```
[Answer]
# Ruby, 27 bytes
`->i{!i.map(&:size).uniq[1]}`
### Test:
```
s = ->i{!i.map(&:size).uniq[1]}
s[[[1, 2, 3, 4], [1]]]
=> false
s[[[1, 2, 3, 4]]]
=> true
```
[Answer]
## PowerShell v2+, 53 bytes
```
param($a)if($a){($a|%{$_.count}|select -u).count-eq1}
```
This presumes that [standard I/O methods](http://meta.codegolf.stackexchange.com/q/2447/42963) and both [programs and functions](http://meta.codegolf.stackexchange.com/a/2422/42963) are allowed. Additionally, in PowerShell, the concept of "returning" an empty array is meaningless -- it's converted to `$null` as soon as it leaves scope -- and so it is the equivalent of returning nothing, which is what is done here.
We take input `$a`, and `if` it's non-empty we collect all the `.count`s of each sub-array. We pipe that to `Select-Object` with the `-u`nique flag, take *that* `.count` and verify that it's `-eq`ual to `1`. Returns Boolean `$true` or `$false`. If the input is the empty array, returns nothing (i.e., `$null`).
### Examples
```
PS C:\Tools\Scripts\golfing> .\same-length-sub-arrays.ps1 ((1),(2),(3))
True
PS C:\Tools\Scripts\golfing> .\same-length-sub-arrays.ps1 ((1),(2),(3,4))
False
PS C:\Tools\Scripts\golfing> .\same-length-sub-arrays.ps1 @()
PS C:\Tools\Scripts\golfing> (.\same-length-sub-arrays.ps1 @()).GetType()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ (.\same-length-sub-arrays.ps1 @()).GetType()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PS C:\Tools\Scripts\golfing> (.\same-length-sub-arrays.ps1 @())-eq$null
True
```
[Answer]
## Haskell, ~~48~~ 46 bytes
```
f[]=Nothing
f x|h:t<-length<$>x=Just$all(==h)t
```
Wraps the result in the `Maybe` type and returns `Nothing` if the input is the empty list and `Just True`/`Just False` otherwise.
Usage example:
```
*Main> map f [[],[[1],[2],[3]],[[1]],[[1,2,3,4]],[[1,2,3,4,5],[2],[12,314123]],[[1,2,3,4],[1]]]
[Nothing,Just True,Just True,Just True,Just False,Just False]
```
How it works:
```
f[]=Nothing -- empty input
f x -- otherwise
|(h:t)<-length<$>x -- map length function over the input and bind h
-- to the first element and t to rest of the list
= all(==h)t -- return whether all values in t equal h
Just$ -- wrapped in the Maybe type
```
Edit: @Lynn saved two bytes. Thanks!
[Answer]
# Java 10, ~~145~~ ~~129~~ ~~107~~ ~~106~~ ~~103~~ ~~93~~ 77 bytes
Loads of bytes saved thanks to *@Frozn*, and by using `Object` as return-type, we can comply with OP's rules of returning the input-array when the array is empty, despite Java's one-return-type-only nature regarding methods.
```
m->{int f=1;for(var a:m)f=m[0].length!=a.length?0:f;return m.length<1?m:f>0;}
```
[Try it online.](https://tio.run/##rU9Pa4MwFL/7Kd5uClaM7cnM9hOsPfQoHtI06XQmlhgtQ/LZ3XOVbofBEAohvOT3fv8q1rNVdf4Yec3aFt5YqQcPoNRWGMm4gP30BDicKsEtcB@RvMgLUAFFwHl4tZbZksMeNGQwqtV2wCWQGaGyMX7PDLBUBTJTeVxEtdAX@/6SsXnaxamkRtjOaFDz3yvZqVRuY@pGOhlcu1ONBrNP35RnUBjUP1pT6guGYcE95fGztUJFTWejK0K21r6OuK/FbWqE9niC7@D/7mLHuybAQFz4x5g4t0ALmcvWwyRch5tFpEfImfsr6k8BhMiGJOvnKD9aOc@NXw)
**Explanation:**
```
m->{ // Method with integer-matrix parameter and Object return-type
int f=1; // Flag-integer, starting at 1
for(var a:m) // Loop over the rows of the matrix
f=m[0].length!=a.length?
// If the length of the first and current row aren't the same:
0 // Change `f` to 0
: // Else:
f; // Leave `f` the same
return m.length<1? // If there is only one row:
m // Return the input-matrix as result
: // Else:
f>0;} // Return whether the flag `f` is still 1 as boolean
```
[Answer]
# Python, 45 bytes
```
lambda x:x and min(x,key=len)==max(x,key=len)
```
[Answer]
# Octave, 51 bytes
```
@(x)repmat(2>n(unique(cellfun(n=@numel,x))),n(x)>0)
```
[**Online Demo**](http://ideone.com/91oCds)
**Explanation**
Loops through the input (a cell array) and determines the number of elements in each entry `numel`, then from this array of the number of elements, we ensure that there is only one unique value: `2 > numel(unique(numberOfElements))`. This will give us the boolean we want. Unfortunately, it is difficult to yield an empty array efficiently so in order to deal with the case of an empty input, we use `repmat` to repeat this boolean value `N` times where `N` is the number of subarrays in the input. If the input is empty this repeats the boolean value `0` times leading to `[]`.
[Answer]
## Actually, 18 bytes
```
`♂l╔l;Y"[].⌂"£n=1`
```
[Try it online!](http://actually.tryitonline.net/#code=YOKZgmzilZRsO1kiW10u4oyCIsKjbj0xYMaS&input=W10) (calls the function with `ƒ`)
Explanation:
```
`♂l╔l;Y"[].⌂"£n=1` push a function:
♂l map length over input
╔l uniquify
;Y 1 if list is empty else 0
"[].⌂"£n call this function that many times:
[]. print an empty list
⌂ exit
=1 1 if length of unique list equals 1 else 0
```
If the function-only requirement is lifted, the equivalent program works for 15 bytes:
```
♂l╔l;Y`[].⌂`n=1
```
[Try it online!](http://actually.tryitonline.net/#code=4pmCbOKVlGw7WWBbXS7ijIJgbj0x&input=W10)
[Answer]
## 05Ab1E, 12 bytes
```
Dg0Qië€gÙg1Q
```
**Explained**
```
Dg0Qi # if empty list, return input
ë # else
€g # map length over list
Ùg1Q # check if length of uniquified list is 1
```
[Try it online](http://05ab1e.tryitonline.net/#code=RGcwUWnDq-KCrGfDmWcxUQ&input=W1sxXSwgWzFdLCBbMiwgM11d)
[Answer]
## F#, 78 bytes
```
function
|[]->None
|x->Seq.forall(fun y->Seq.length y=Seq.length x.[0])x|>Some
```
Output is the [F# Option type](https://msdn.microsoft.com/visualfsharpdocs/conceptual/core.option%5B%27t%5D-union-%5Bfsharp%5D "F# Option type"). If the input is empty output is None, else it's Some bool, where the bool value indicates whether all the sub-arrays are of equal length.
```
// F# Interactive
let f =
function
|[]->None
|x->Seq.forall(fun y->Seq.length y=Seq.length x.[0])x|>Some;;
val f : _arg1:#seq<'b> list -> bool option
> f [[0;1];[2];[3]];;
val it : bool option = Some false
> f [[0;1];[2;3];];;
val it : bool option = Some true
> f [];;
val it : bool option = None
```
[Answer]
# J, 26 bytes
```
]`(1=[:#@~.#@>@>)@.(*@#@>)
```
Since J doesn't support ragged arrays, I will use boxed arrays instead. It returns `1` for true, `0` for false, and the input if empty.
## Usage
```
f =: ]`(1=[:#@~.#@>@>)@.(*@#@>)
NB. Boxed array representing [[1, 2, 3, 4, 5], [2], [12, 314123]]
< 1 2 3 4 ; 2 ; 12 314123
┌─────────────────────┐
│┌───────┬─┬─────────┐│
││1 2 3 4│2│12 314123││
│└───────┴─┴─────────┘│
└─────────────────────┘
f < 1 2 3 4 ; 2 ; 12 314123
0
NB. The empty list
a:
┌┐
││
└┘
f a:
┌┐
││
└┘
f < 1 ; 1 ; 2
1
f < < 1
1
f < < 1 2 3 4
1
f < 1 2 3 4 ; 1
0
```
[Answer]
# Retina, 35 bytes
If only `[]` could return true or false. Returning a 3rd value makes it so much longer.
```
\[]
xx
\d|],
M`^\[(\[,*)\1*]]|x
2
```
[**Try it online**](http://retina.tryitonline.net/#code=XFtdCnh4ClxkfF0sCgpNYF5cWyhcWywqKVwxKl1dfHgKMgo&input=W1sxLDIsMyw0LDVdLFsyXSxbMTIsMzE0MTIzXV0)
This is the core program. It removes digits and occurrences of `],`, then matches if the number of commas is the same after each `[`. It would return `0` for `[]`. The code above varies because I added a check for an empty list to make it match twice, then I replace `2` with nothing for a null return.
```
\d|],
^\[(\[,*)\1*]]
```
[Answer]
## APL, 13 bytes
```
1=(×∘⍴⍴≢)∪≢¨⎕
```
In English:
* compute the unique of the tallies of each of the subarrays;
* reshape the result with the signum of its shape: if its an empty vector, it remains an empty vector;
* is it equal to 1?
[Answer]
## C#, 80 bytes
Im checking length 4 times in this golf. i wish there was a better way to be honest.
```
bool f(List<int[]>a){return a.Where(m=>m.Length==a[0].Length).Count()==a.Count;}
```
alternative version also 80 bytes..
```
bool f(List<int[]>a){return a.Where(m=>m.Length==a[0].Length).SequenceEqual(a);}
```
[Answer]
## Prolog, 40
```
m([],L).
m([H|T],L):-length(H,L),m(T,L).
```
Provide a true/false answer when calling `m(X,L)` for some input `X`.
[Answer]
# APL, 13 bytes
```
{(×⍴⍵)↑⍵≡↓↑⍵}
```
Explanation:
* `↓↑⍵`: turn the list of arrays into a matrix, and then turn the matrix back into a list of arrays. Because a matrix has to be rectangular, short arrays will be padded with zeroes to match the longest.
* `⍵≡`: see if the result is equal to the input. This is only the case if no zeroes have been added, which means all the sublists were the same length.
* `×⍴⍵`: take the sign of the length of `⍵`, which is `0` if `⍵` is empty and `1` if not.
* `↑`: take the first 0 or 1 items from the result depending on whether the array was empty or not.
[Answer]
## Clojure, 40 bytes
```
#(if(not-empty %)(apply =(map count %)))
```
Yay for suitable language features :)
] |
[Question]
[
**Task:**
Your task is to create two programs in different languages that can communicate one-way to each other. Your sending (tx) program will take input, for either stdin or a query, and send it along to the receiving (rx) program. Your rx program will then print out the data that it receives.
**Rules:**
* The two programs must communicate one way from the tx to the rx side, so anything typed in tx will appear in rx.
* They will be running on the same computer, in different shells/windows.
* They will be running in separate instances, and you are not allowed to chain them (in bash, `prog1 | prog2`)
* The programs must be written in different languages.
* They can use any data transfer method, but you must be able to transfer ASCII text.
* This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the most up voted answer wins.
+ Note to voters: look for creativity!
[Answer]
# C and PERL communicating via keyboard status lights
My friend and I got inspired by this one last night.
We use Perl for the sender program and C for the receiver.
The medium of exchange was the keybord status lights!
Three virtual signal lines were used: Caps Lock, Num Lock and Scroll lock, being used as Clock, Serial Data, and Start Of Byte signals.
[](https://i.stack.imgur.com/bUvnJ.png)
The sender program pulses those keyboard lights and the receiver polls them and checks the state. Data is sent serially as binary, in 8 bit bytes.
You can see the transmitter and receiver programs in operation, in the attached video, as well as the flashing of the lights during the transmission.
[Video of operation](https://i.stack.imgur.com/t1n1l.jpg)
Source for both programs is attached. Given the question requirements, we didn't try to minimize the size like we would in a normal golfing attempt.
## C Code (receiver)
```
#include <X11/Xlib.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
Display* dpy = XOpenDisplay(":0");
XKeyboardState x;
char keys_return[32];
int b = 0;
while (1) {
unsigned char output = 0;
printf(" \b");
fflush(stdout);
while (XQueryKeymap(dpy, keys_return)) //wait for start signal
if (keys_return[9] == 64) {
break;
}
for (b = 0; b < 8; b++) {
do {
XGetKeyboardControl(dpy, &x);
} while (!(x.led_mask & 1)); //wait for clock to be high
if (x.led_mask & 2)
output |= 128;
if (b != 7)
output >>= 1;
do {
XGetKeyboardControl(dpy, &x);
} while ((x.led_mask & 1)); //wait for clock to be low
}
printf("%c", output);
}
XCloseDisplay(dpy);
return 0;
}
```
## PERL code (transmitter)
```
use X11::Xlib ':all';
use strict;
use warnings;
use feature 'say';
use Time::HiRes qw(sleep);
use constant {
DATA => 77,
START => 78,
CLOCK => 66
};
my $display = X11::Xlib->new;
sub transmit_str {
my ($str) = @_;
foreach my $char ( split( //, $str ) ) {
my $ordchar = ord($char);
for my $i ( 0 .. 7 ) {
for my $j ( 0 .. 1 ) {
if ( $i == 0 ) {
$display->fake_key( START, !($j) );
}
if ( $ordchar & 1 ) {
$display->fake_key( DATA, 1 );
$display->fake_key( DATA, 0 );
}
$display->flush;
sleep(0.025) if(!$j);
$display->fake_key( CLOCK, 1 );
$display->fake_key( CLOCK, 0 );
$display->flush;
sleep(0.05);
}
$ordchar >>= 1;
}
}
}
while ( my $stdin = <STDIN> ) {
transmit_str($stdin);
}
```
[Answer]
# Original Lisp Eliza communicating with yes
Original Eliza [lisp code](http://elizagen.org/index.html) "communicating" with with unix `yes` utility.
First create a FIFO special file:
```
mkfifo in
```
Then we make the two programs communicate together (*which means that the patient will answer YES to all questions*).
```
clisp coselleliza1969and1972.lisp < in | tee out.txt | yes 'yes.' > in
```
Output is inifnite and starts with:
```
TELL ME YOUR PROBLEMS. PLEASE TERMINATE INPUT WITH A PERIOD OR A QUESTION MARK.
IS THERE SOMETHING BOTHERING YOU?
WHY ARE YOU SO SURE?
I SEE.
I UNDERSTAND.
CAN YOU BE MORE INFORMATIVE?
WHY ARE YOU SO SURE?
I SEE.
I UNDERSTAND.
PERHAPS YOU'D RATHER TALK ABOUT SOMETHING ELSE.
```
More variety if it communicates with another instance of itself:
```
clisp coselleliza1969and1972.lisp < in | clisp coselleliza1969and1972.lisp | tee out.txt > in
```
Output starts with:
```
TELL ME YOUR PROBLEMS. PLEASE TERMINATE INPUT WITH A PERIOD OR A QUESTION MARK.
WHY ARE YOU CONCERNED OVER MY PROBLEMS?
I AM NOT SURE I UNDERSTAND YOU FULLY.
SUPPOSE * WHY WERE NOT I CONCERNED OVER YOUR PROBLEMS.
IS IT BECAUSE YOU ARE NOT SURE YOU UNDERSTAND I FULLY THAT YOU CAME TO ME?
YOU SAY YOU CONCERNED OVER MY PROBLEMS?
POSSIBLY THAT IS FOR THE BETTER.
SUPPOSE YOU SAY I CONCERNED OVER YOUR PROBLEMS.
POSSIBLY * POSSIBLY THAT REALLY IS NOT FOR THE BETTER.
OH? I SAY YOU CONCERNED OVER MY PROBLEMS?
WHAT IF REALLY WERE FOR THE BETTER?
PLEASE GO ON.
CAN YOU ELABORATE ON THAT?
WHAT DOES THAT SUGGEST TO YOU?
TELL ME MORE ABOUT YOUR PROBLEMS.
WHAT MAKES YOU THINK I ELABORATE ON THAT?
PERHAPS THAT CONCERNS YOUR PROBLEMS.
WHAT ABOUT YOUR OWN PROBLEMS?
WHO ARE YOU REALLY TALKING ABOUT?
YOU DON'T SEEM QUITE CERTAIN.
EARLIER YOU SAID YOU WERE NOT SURE YOU UNDERSTAND I FULLY.
TELL ME MORE ABOUT * WHO.
SUPPOSE YOU DON'T SEEM QUITE CERTAIN.
OH? I SAID I WAS NOT SURE I UNDERSTAND YOU FULLY?
ARE YOU STILL NOT SURE YOU UNDERSTAND I FULLY?
WHAT MAKES YOU THINK I DON'T SEEM QUITE CERTAIN?
WOULD YOU LIKE TO DISCUSS YOUR PROBLEMS?
DO YOU SAY YOU SAID YOU WAS NOT SURE YOU UNDERSTAND I FULLY FOR SOME SPECIAL REASON?
DID YOU THINK * MIGHT NOT BE I STILL NOT SURE I UNDERSTAND YOU FULLY?
WHO ARE YOU REALLY TALKING ABOUT?
SUPPOSE YOU LIKE TO DISCUSS MY PROBLEMS.
OH? I SAY I SAID I WAS NOT SURE I UNDERSTAND YOU FULLY FOR SOME SPECIAL REASON?
WHAT MAKES YOU THINK I THINK * MIGHT NOT BE YOU STILL NOT SURE YOU UNDERSTAND I FULLY?
* WHO PERHAPS ARE I REALLY TALKING ABOUT.
WHO ARE YOU REALLY TALKING ABOUT?
WHAT ELSE WOULD YOU LIKE TO DISCUSS?
TELL ME MORE ABOUT YOURSELF?
SUPPOSE YOU THINK YOU THINK * MIGHT NOT BE I STILL NOT SURE I UNDERSTAND YOU FULLY.
WHY THE UNCERTAIN TONE?
SUPPOSE * WHO WERE NOT I REALLY TALKING ABOUT.
OH? I LIKE TO DISCUSS?
WHY DO YOU SAY THAT JUST NOW?
WHAT MAKES YOU THINK I THINK I THINK * MIGHT NOT BE YOU STILL NOT SURE YOU UNDERSTAND I FULLY?
I AM NOT SURE I UNDERSTAND YOU FULLY.
OH? YOU REALLY TALKING ABOUT?
PLEASE GO ON.
WHAT ELSE DO YOU LIKE?
WHO ARE YOU REALLY TALKING ABOUT?
SUPPOSE YOU THINK YOU THINK YOU THINK * MIGHT NOT BE I STILL NOT SURE I UNDERSTAND YOU FULLY.
HOW LONG HAVE YOU BEEN NOT SURE YOU UNDERSTAND I FULLY?
DID YOU TELL ME YOU WERE NOT SURE YOU UNDERSTAND I FULLY?
OH? I REALLY TALKING ABOUT?
MAYBE NOW WE CAN DISCUSS WHY YOU ARE NOT SURE YOU UNDERSTAND I FULLY.
WHAT MAKES YOU THINK I LIKE?
POSSIBLY * WHO REALLY ARE NOT I REALLY TALKING ABOUT.
WHO ARE YOU REALLY TALKING ABOUT?
SUPPOSE YOU BEEN NOT SURE I UNDERSTAND YOU FULLY.
OH? I TELL YOU I WAS NOT SURE I UNDERSTAND YOU FULLY?
WOULD YOU LIKE TO DISCUSS YOUR PROBLEMS?
THAT'S QUITE INTERESTING.
```
[Answer]
# Bash and GNU Awk communicating on TCP
Bash transmitter:
```
cat>/dev/tcp/localhost/8080
```
GNU Awk receiver:
```
BEGIN{getline<"/inet/tcp/8080/0/0";print}
```
Sample run:
Bash in terminal 1:
```
bash-4.2$ cat>/dev/tcp/localhost/8080
Bash says hello to Awk
^D
```
GNU Awk in terminal 2:
```
bash-4.2$ gawk 'BEGIN{getline<"/inet/tcp/8080/0/0";print}'
Bash says hello to Awk
```
Both `bash` and `gawk` provides special filenames ([/dev/tcp/*host*/*port*](http://www.gnu.org/software/bash/manual/bashref.html#Redirections) in `bash` since 2.04, [/*net-type*/*protocol*/*local-port*/*remote-host*/*remote-port*](http://www.gnu.org/software/gawk/manual/gawk.html#TCP_002fIP-Networking) in `gawk` since 3.1.0) for simple networking. These are extensions not specified in the POSIX shell and Awk language standards.
[Answer]
# PHP + Bash
Bash - rx.sh
```
#!/bin/bash
tail -f output
```
PHP - tx.php
```
<?php
$fd=fopen("output", "w");
$msg = print_r($_GET, true);
fputs($fd, $msg);
fclose($fd);
?>
```
Query the program with `rx.php?<message>` or alternately, using a third language,
query.html
```
<body>
Enter the message to send:
<form action="tx.php" method="get">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
</body>
```
[Answer]
# Perl and Rebol via `ps` (process status)
tx.pl
```
use strict;
use warnings;
my $line;
while (chomp(my $msg = <>)) {
$line++;
$0 = "!!$line!!$msg";
last if $msg eq 'q';
}
```
rx.reb
```
Rebol []
get-ps-msg: has [ps msg] [
ps: copy ""
call/output "ps" ps
parse ps [thru "!!" copy msg to #"^/"]
msg
]
print-msg: func [m /no-warning] [
unless no-warning [print-warning? m]
print next next find last m "!!"
]
print-warning?: func [m /local prev new] [
prev: first back back tail m
new: last m
prev: to-integer copy/part prev find prev "!!"
new: to-integer copy/part new find new "!!"
if new != (prev + 1) [print ["WARNING: Out of sequence, expected" prev + 1 "but got" new]]
]
messages: [] ; state: records all messages
until [not none? m: get-ps-msg] ; lets wait until first msg appears
print-msg/no-warning append messages m
; loop until messages disappear from ps
until [
if m != last messages [print-msg append messages m]
none? m: get-ps-msg
]
```
So whats going on here? Well if you start `tx.pl` and then look at `ps` in another session you will see something like this:
```
$ ps
PID TTY TIME CMD
32171 ttys001 0:00.02 -bash
32432 ttys001 0:00.01 perl tx.pl
```
Perl allows you to amend what appears in the CMD (Command) column of `ps` by amending the `$0` variable. So for e.g. if `tx.pl` was this:
```
$0 = "hello mum!";
sleep 10;
```
Then you'll see this in `ps` while the script is still running:
```
$ ps
PID TTY TIME CMD
32171 ttys001 0:00.02 -bash
32433 ttys001 0:00.01 hello mum!
```
So we can use this to send messages from one script to another. The Rebol receiving script simply monitors `ps` for all messages sent to `ps` from the Perl script.
NB. The Rebol script does contain some extra bits that aren't really necessary (see warnings & recording all messages).
Usage: Do `perl tx.pl` and `rebol -qws rx.reb` in separate sessions and everything you type into transmitting session will appear in the receiving session. Once the transmitting session is closed (enter 'q' or ^C) then the receiving script automatically quits.
Tested on Mac OSX 10.7. Requires Rebol 2 at this moment because `call/output` not currently implemented in Rebol 3.
[Answer]
# sh tx with awk rx connected by a fifo
tx in sh... make a fifo, read user input and send it to fifo, remove fifo.
Run this in one terminal, enter a line and start the receiver in a different terminal.
```
(yeti@aurora:4)~$ mkfifo F ; read X ; echo $X > F ; rm F
xyzzy
```
rx in awk ... read fifo, print line and terminate.
```
(yeti@aurora:5)~$ awk '1' F
xyzzy
```
A direct connection of tx and rx by a pipe would be shorter but far less interesting.
The fifo would allow tx and rx to be run by different UIDs if the fifo's permissions are set to alow read by others.
[Answer]
# Shell script and not-quite-HTML
Sending code:
```
#!/bin/sh
cat >> ~/receiver.html
```
Receiving code - must be located at `~/receiver.html`:
```
<meta http-equiv="Refresh" content="1">
```
[Answer]
# q and k
Receiver, `rx.q`, in q
```
\p 29010
```
Transmitter, `tx.k`, in k
```
.z.pi:{`::29010(-1;x)};
```
[Answer]
# C++
```
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char input[100];
cin>>input;
ofstream inputfile("temp.txt");
inputfile<<input;
inputfile.close();
return 0;
}
```
# C++11
```
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char output[100];
ifstream outputfile("temp.txt");
outputfile>>output;
inputfile.close();
cout<<output;
return 0;
}
```
They communicate through a text file. In C++ code the input is written in a text file and is then collected by C++11 code.
But, `C++ is a subset of C++11`
If the asker feels cheated please comment I'll delete this answer! sorry :P
[Answer]
# Prolog and PHP
Tx: `writer.pl`
```
start :-
open('file', write, Str),
read(In),
write(Str,In),
nl(Str),
close(Str).
```
Rx: `reader.php`
```
<?php
echo file_get_contents('file');
```
Usage:
```
$ gprolog
['writer.pl'].
start.
hello.
```
And then:
```
$ php reader.php
```
[Answer]
# VBS and Python
### communicating over microphone and speakers in cleartext
Works astonishingly well out of the box
## transmit
```
CreateObject("sapi.spvoice").Speak WScript.Arguments.Item(0)
```
## receive
```
import speech_recognition as sr
r = sr.Recognizer()
m = sr.Microphone()
try:
while True:
print("listening")
with m as source: audio = r.listen(source)
try:
value = r.recognize_google(audio)
print("repeating: " + value)
except sr.UnknownValueError:
print("¯\_(ツ)_/¯")
except KeyboardInterrupt:
pass
```
(this is 90% straight from the quickstart examples, might as well just run `python -m speech_recognition`)
[](https://i.stack.imgur.com/ThWZV.png)
] |
[Question]
[
[<< Prev](https://codegolf.stackexchange.com/questions/149861/advent-challenge-4-present-assembly-line) [Next >>](https://codegolf.stackexchange.com/questions/150028/advent-challenge-6-transport-dock-relabeling)
Thanks to the PPCG community, Santa has managed to remanufacture all of his presents and after the assembly line, the presents are now ready to be moved into the transport docks!
Each of Santa's transport docks only holds a range of present sizes because the transport sleighs are specialized for a specific size (any lighter and it would be wasteful, any heavier and the sleigh wouldn't be able to handle the load). Thus, he needs you to help him take his presents and sort them into the correct transport docks.
# Challenge
Given a list and the transport dock ranges, stably organize the presents into the correct order.
Let's take this for example: the presents are `[5, 3, 8, 6, 2, 7]` and the dock ranges are `[[1, 5] and [6, 10]]`.
The presents `5`, `3`, and `2` go into the first dock and the presents `8`, `6`, and `7` go into the second dock. This can be shown as `[[5, 3, 2], [8, 6, 7]]`. This list will be closer to being sorted than the input, but `stably` means that within each dock, the order of the presents must be the same as the order of the input (otherwise you could just sort the entire list).
Your final output for this case would be `[5, 3, 2, 8, 6, 7]` (as a flat list).
# Formatting Specifications
You will be given input as a flat list of integers and a list of ranges in any reasonable format (for example, the range for the above case could be given as `[[1, 5], [6, 10]]`, `[1, 5, 6, 10]`, or `[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]`). Your output should be a flat list of integers in any reasonable format.
The input can contain duplicate values; in this case, you need to return all instances of them. All present sizes will be in exactly one size range, and you can assume that the ranges will never overlap. There can be gaps in the ranges as long as all present sizes are covered.
# Rules
* Standard Loopholes Apply
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins
* No answer will be accepted
* You can assume that there will be no empty ranges (`[7, 4]` would be invalid because ranges go up)
# Test Cases
```
[1, 2, 3, 4, 5, 6, 7] ; [[1, 3], [4, 7]] => [1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7] ; [[4, 7], [1, 3]] => [4, 5, 6, 7, 1, 2, 3]
[7, 3, 5, 4, 6, 1, 2] ; [[1, 3], [4, 5], [6, 7]] => [3, 1, 2, 5, 4, 7, 6]
[4, 7, 6, 3, 5, 2, 1] ; [[1, 4], [5, 7]] => [4, 3, 2, 1, 7, 6, 5]
[1, 1, 3, 3, 6, 4, 7] ; [[1, 4], [6, 7]] => [1, 1, 3, 3, 4, 6, 7]
```
Note: I drew inspiration for this challenge series from [Advent Of Code](http://adventofcode.com/). I have no affiliation with this site
You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge [here](https://codegolf.stackexchange.com/questions/149660/advent-challenge-1-help-santa-unlock-his-present-vault).
[Answer]
# [Haskell](https://www.haskell.org/), 26 bytes
```
a#s=[x|r<-s,x<-a,elem x r]
```
[Try it online!](https://tio.run/##jc@xDoIwEAbg3af4ExyvTYAWFnmS5oYmkkgENODA4LtXOEAxONilSfP/310vvr@WdR2Cj/rCDc/upHoaTspTWZcNBnQcGl@1KHC@HXDvqvaBI1xMSAgpwRAsISPkjAjOxVqnTHBG65wZ61Hqd@cfUqiRFPqb/EQJS39L5uJZIbM5sdvSTrcMYyHTVZprI5FtyeVphcdc/CbNRNn9x42kE4HnsuXwAg "Haskell – Try It Online") Example usage: `[1,2,3,4,5,6,7] # [[1,2,3],[4,5,6,7]]` yields `[1,2,3,4,5,6,7]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
fЀẎ
```
[Try it online!](https://tio.run/##y0rNyan8/z/t8IRHTWse7ur7//9/tLmOgrGOgqmOgomOgpmOgqGOglHs/@hoEA2UidVRiAZKmIJooKx5bCwA "Jelly – Try It Online")
Takes input as present list, full ranges.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
δØ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3JbDzafn/P8fbaKjYK6jYKajYKyjYKqjYKSjYBjLFR1tCGYCxUxidRSiTcEqzGNjAQ "05AB1E – Try It Online") (thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) for letting me know `δ` exists, -1 byte)
### How it works
```
δØ | Full program.
δ | Double-vectorize the next command (something like an outer product).
à | List intersection. Since this is a dyad, the first input is automatically
| used to fill the missing argument (as far as I know).
˜ | Flatten.
```
[Answer]
# Mathematica, 39 bytes
```
x##&@@Cases[x,#|##&@@Range@##]&@@@#&
```
-22 bytes from JungHwan Min
-4 bytes from Martin
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73ys/M8/BQaPCVtnaObE4tTi6Qke5RllZzcEhKDEvPdVBWTkWyHZQNtJU@x9QlJlX4pAWXW2oY6RjrGOiY6pjpmNeq1MNFDAGUiZATm0sF25lJmAKpBhZmTlQkSlQmZkOUAOyaaZA0gzNTKARQIUgDUY6hhDFJkDKFKzsPwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), 5 bytes
```
s@Rvz
```
**[Try it here!](https://pyth.herokuapp.com/?code=s%40Rvz&input=%5B%5B1%2C+2%2C+3%2C+4%5D%2C+%5B5%2C+6%2C+7%5D%5D%0A%5B4%2C+7%2C+6%2C+3%2C+5%2C+2%2C+1%5D&debug=0)**
# [Pyth](https://pyth.readthedocs.io), 10 bytes
```
s.gx}LkQ1E
```
**[Try it here!](https://pyth.herokuapp.com/?code=s.gx%7DLkQ1E&input=%5B%5B1%2C+2%2C+3%2C+4%5D%2C+%5B5%2C+6%2C+7%5D%5D%0A%5B4%2C+7%2C+6%2C+3%2C+5%2C+2%2C+1%5D&debug=0)**
### How they work
```
s@Rvz | Full program.
R | Right map...
@ | ... Using intersection.
vz | Of the first input with the second.
s | Flatten by one level.
```
```
s.gx}LkQ1E | Full program.
.g E | Group the items in the second input by...
}LkQ | Map over the first input, and check if the current item is in the list.
x 1 | Take the index of the first truthy element.
s | Flatten.
```
Takes the docks first, with all the integers in the ranges, and then the presents on a new line.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~49~~ 46 bytes
thanks to [@HyperNeutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino) for -3 bytes
```
lambda p,b:[x for l in b for x in p if x in l]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFAJ8kqukIhLb9IIUchM08hCcysADELFDLTIKyc2P8FRZl5JQppGtGGOgpGOgrGOgomOgqmOgpmOgrmsToK0TBxEBtJJlaTi6BOVC7MHGSd5mBtpmCdQHUgJdjsBNEYtgIlzMG6ICYA1Rsi6wWaCeIi3PsfAA "Python 2 – Try It Online")
---
**Ungolfed**
```
def f(presents, groups):
result = []
for group in groups:
for present in presents:
if present in group:
result.append(present)
return result
```
[Try it online!](https://tio.run/##hY5BCoMwEEX3nuIvFYaCtlYo9CTiomDSCiWGGBeePp0khqa00FUy8/6bGb3Zx6wa50YhIUttxCKUXQh3M696qS4FwL31aXFFP3AlZxMhJrWnfCiC3fcojYoQmGROg5hQWnG4aS3UmK6owm67GrVzp83Euiz7mtAQjoQToSWcCd1A6FPf/zMyVMVf87NMc3KzC1obTM75yK@d/v3ayqALVpzA@Tp3eaYv3/e6Fw "Python 2 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~37~~ 36 bytes
```
O$`(\d+)(?=.*¶(.*)\[.*\b\1\b)
$2
G1`
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZxgrfDfXyVBIyZFW1PD3lZP69A2DT0tzZhoPa2YpBjDmCRNLhUjLnfDhP//ow11FIx0FIx1FEx0FEx1FMx0FMxjrRWiYeKxOgrRSDKxXDg1IHGBemDagRrMwapNwRqA0iAZbDaAaJgdQL45WDFEI1CZIbIWoFEg1aiOMgRLGIPFTNB8AdUAUQ0A "Retina – Try It Online") Takes input as a list of presents on the first line and a list of ranges on the second line; the link includes a header to split the test cases into the desired format. Edit: Saved 1 byte thanks to @MartinEnder. Explanation: The first stage matches the presents and finds the matching dock. The presents are sorted by the substring from the start of the line to the `[`, thus grouping the presents by dock. The second stage then deletes the docks.
[Answer]
# [Enlist](https://github.com/alexander-liao/enlist), 3 bytes
```
f₱Ẏ
```
[Try it online!](https://tio.run/##S83LySwu@f8/7VHTxoe7@v7//x9trqNgrKNgqqNgoqNgpqNgqKNgFPs/OhpEA2VidRSigRKmIBooax4bCwA "Enlist – Try It Online")
### How it works
```
f₱Ẏ | Full program.
₱ | Map over right argument.
f | Using list intersection, counting multiplicities.
Ẏ | Tighten (flatten by 1 level).
```
[Answer]
# APL+WIN, 29 bytes
```
(,⍉<\p←n∘.≤∊¯1↑¨⎕)/(×/⍴p)⍴n←⎕
```
Prompts for screen input for both the integers and ranges. The integers as a flat list and the ranges as a nested vector, e.g case 3:
```
(1 3) (4 5) (6 7)
```
Explanation:
```
(×/⍴p)⍴n←⎕ prompt for screen input of integers and replicate by the number of ranges
∊¯1↑¨⎕ prompt for screen input of ranges and select the top of each
p←n∘.≤ create a boolean matrix using outer product with less than the top of each range
,⍉<\ identify the first range which each element fits in and ravel into a partition vector
(.....)/.... use the partition vector to select the elements in each range in order
```
[Answer]
# C++, 127 bytes
Take input as two arrays represented by pairs of pointers `[start, end)`.
```
#import<algorithm>
[](int*A,int*x,int*B,int*y){for(;B!=y;B+=2)A=std::stable_partition(A,x,[&](int a){return a>=*B&&a<=B[1];});}
```
[Try it online!](https://tio.run/##VU/taoQwEPzvU2wpqLlLf9xHe2DMQfIaVkqa02tAE4kr3CE@u43eUeiyDMvM7DKru@7tqvU8v5q2cx5z1VydN/jTniM1oIOaF2VqLG4EXfC2olzxTsba@ZTJF35ncsv3RPAeL1nWo/puqq9OeTRonE0FvdEiXu@AIqOvcPAW1JlvZByrnMtiV7KJsImFHFY3w6WC3LgefaVCkGWtVcamJBojCLUQoiiBw7ijsKdwoHCk8EHhncJpYn8m@TAF7UQhWA9PrQ6RQMB2oWXoMB3JU3Ie1qAGMhAE1o@0GxDyPHABEkge1n9S8mkDPUXzLw "C++ (gcc) – Try It Online")
[Answer]
# J, 15 bytes
```
[/:[:I.e.&>"0 1
```
Takes the input as the *left* argument and the ranges as the *right* argument. The ranges are boxed lists of the complete ranges.
e.g. for the first range:
```
NB. This produces the range
(1 2 3 ; 4 5 6 7)
┌─────┬───────┐
│1 2 3│4 5 6 7│
└─────┴───────┘
```
[Try it online!](https://tio.run/##bY89D8IgEIZ3fsUbB6ODKFJKAtHBzcXFsZMfNI1p0sTY348HlMY2hoV73nvu4OV9feDV1lTmzB1fHhc7CMYuJ45r0/XtE3eHW9vi8@4dVmLN3KPpILCHRAGFEhobMwM1dUZgMxq83JDSf16@2hQNnoyVokZNKXmaUCjLGMz22clGSYmIngpmGhHsgEezIOv3pYKOjHz8YQJlnDDxguX9Fw)
# Explanation
```
[/:[:I.e.&>”0 1
>”0 1 Pair each element on the left with each range on the right
e. Is the element in the range?
I. Indices of ones
[/: Sort the elements by this array
```
[Answer]
# [J](http://jsoftware.com/), 26 24 bytes
2 bytes thanks to cole
```
[:;]<@#~1=-&1 0"1@[I."1]
```
# How it works:
The left argument holds the ranges.
`-&1 0"1@[` decreases the lower boundary of each range by 1
`I."1]` checks in which range fits each present
`1=` is it in the correct range
`]<@#~` copies and boxes the presents which are in the current range
`;` - raze (unboxing)
[Try it online!](https://tio.run/##hc5NCsJADAXgvad4VLAVRpnML4wWuvUMpcxCLMWNN/DqY@LoRgXJJpAvebmWMvdpTIfpOKzv1O82BN3QMJ72DU3lcl5u6AhWJYe4xQyCgYWDR0BcPect2tp0bFRi/Re@LnqVQj0b2XrWQfa@tVPJV8gRjAQb0E8Y3o9yCFeQlU@oBWaLTEKz4QZaossD "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~113~~ ~~48~~ ~~55~~ 41 bytes
A previous version didn't correctly sort objects when the docks weren't in increasing order.
```
function(P,D)for(d in D)cat(P[P%in%d],"")
```
[Try it online!](https://tio.run/##FYpBCoAgEADvvUIEYRe2gxQE0dEHeK8OoQhCbFD6fnNvw8y8LaltbKlyKPlh8OQwPS9ElVk5DFcBv3uT2cSTtMaWIIBdF6Q7f6XzLCxqQsRBfn2w7lSLfD3NtJClntsP "R – Try It Online")
Takes `D` as a list of vectors of ranges, i.e., `list(4:7,1:3)` would be `[[4, 7], [1, 3]]`.
Probably the naive answer I should have arrived at ages ago; prints to stdout.
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 6 bytes
```
ñ@VbøX
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=8UBWYvhY&input=WzcsMyw1LDQsNiwxLDJdCltbMSwyLDNdLFs0LDVdLFs2LDddXQotUQ==)
---
## Explanation
Implicit input of array `U` (presents) and 2d-array `V` (full ranges). Sort (`ñ`) the presents by passing them through a function (`@`) that gets the index of the first element (`b`) in `V` that contains (`ø`) the current present (`X`).
[Answer]
# Python 2, ~~97~~ 85 bytes
```
l,d=input()
k=lambda i,j=0:-~j*(d[j][0]<=i<=d[j][1])or k(i,j+1)
print sorted(l,key=k)
```
-11 bytes from [ovs](https://codegolf.stackexchange.com/users/64121/ovs)
-1 byte from [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
[Try it online!](https://tio.run/##Hcq9DsIgEADgvU9xI@iZlLZqYnpPQm6ooYn8WAji0MVXR3T7hi/t5RG3odaAhuyW3kXIzlNYnnezgEVH/e30cQdhtGPd80x2pr8Vy5jBi3aOSnYp263AK@ayGhHQrzt5WatWCAPCiDAhnBEuCFcGBK2nnxpaGJm/ "Python 2 – Try It Online")
Sorts the list using a recursive lambda as the key. Explanation ~~coming soon™~~ below.
Explanation:
```
l,d=input() # l is the lsit of presents, d is the list of ranges
k=lambda i,j=0:-~j*(d[j][0]<=i<=d[j][1])or k(i,j+1)# recursive lambda to sort with
k=lambda i,j=0: # i is the present
# j is the index in the list of ranges
-~j*(d[j][0]<=i<=d[j][1]) # return the index of the list of
# ranges(plus one) if the present is
# in the range
or k(i,j+1)# if the present is not in the range,
# try the next range
print sorted(i,key=k) # print the list of presents sorted by the lambda
```
[Answer]
# Javascript ES6, ~~53~~ ~~47~~ 45 bytes
```
p=>l=>l.map(d=>p.filter(a=>d.includes(a)))+''
```
[Try it online!](https://tio.run/##jY/BCsIwDIbvPkVuazEWps4dpHuRsUNZO6l2a1mn4NPXbjLoYYIQCEn@/@PPXbyEb0ftpoN3Wqqxt8NDvUPHg@OVicV64YjklWOdNpMaieCVZHpozVMqTwSldJ9lobWDt0YxY2@kI3WOcEQ4IZwRCoQLQtlQUq/7BqFOLg2l192fhGSMkJW3RSgXe7EQon6WbmWY@88UUVAu7i8p@vKUEdmzPf0jfAA "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 37 bytes
```
param($a,$b)$b|%{$i=$_;$a|?{$_-in$i}}
```
[Try it online!](https://tio.run/##HYq7CoAwDAB/JUOEBuLgozqI2D@RCIKF@kAHB/XbY3U77m5bz3E/pjEE1U12mQ0K40A43MmFvsW@Qbm7C/vUL@ifR1WdqRkKBstQMlQMGUNOUTvzUWzE4Exs9od41EQv "PowerShell – Try It Online")
Takes `$a` as a literal array of the presents and `$b` as an array of arrays, each of which are the full range (e.g., `@(1,2,3,4,5)` instead of `@(1,5)`). We then loop over each item in `$b` with `|%{...}`. Inside, we need to set a helper `$i` to be the current item, then use a `Where-Object` clause against `$a` to pull out only those items that are `-in` the current `$b` array.
Those are left on the pipeline and output is implicit. Since the default behavior of `Write-Output` inserts a newline between array elements, that's what we get. [Here](https://tio.run/##HYq9CoNAEAZfZYsVd@GziEYtJOTeRE4QcuIfWlioz765pBtmZl2Ofts//TiarX7zk7AHdyrcXcnJ4cVtw/56n9xmYeZw35oNS5hTpGbmpAYVoBL0BFWgByjXqJ38KDYFOYmt/EM8atUv "PowerShell – Try It Online") is a slightly tweaked version that is `-join`ed together via commas instead of a newline, just to show differences.
[Answer]
# [Red](http://www.red-lang.org), 73 bytes
```
f: func[b r][n: copy[]foreach p r[foreach a b[if find p a[append n a]]]n]
```
[Try it online!](https://tio.run/##dY7BCoMwEETv/Yr5AaHRqOBn9LrsIWpCvcQQ2kO/Pt2qaYPQyzLMvB0m2jnd7Azi5Aa4p59oRGTyA6Y1vIjdGq2Z7giIlLXBSIuDW/wsviETghXpYZjZcwpx8Q84kEKNBhotOvQM2g0R2eLLf/Yn96@C7YVshe0g0alX7qlZoxfy81FDfWlokccKlDOUZI34upi8wafaqkalcM0TNnGQVYMtZU5v "Red – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 50 + 18 bytes
```
a=>b=>b.SelectMany(x=>a.Where(y=>y>=x[0]&y<=x[1]))
```
+18 bytes from
```
using System.Linq;
```
It takes a collection for presents and a collection of arrays for docks.
[Try it online!](https://tio.run/##lVNdb9owFH3Pr7jjAWyRWQ1t4SEkUlVt0yQqVaNSH1AeTDBgKTjMdloixG@nNzHQZU0nzYoU59xzzv2wk5qvaa7FsTBSrWBaGis27D7PMpFamSvDfggltExDz1N8I8yWp@JMm0j129t7gCvNuDHwqPOV5psacXi1jOVWpvCSywU8cKmIsRqTzRLgemXohbf3LttqfS9UOv75TRUbofk8E2OpbOy3wrMEA39T4xiWEB15FM/xYVNRtfTAVUl2UczZ81poQcooLuNoN7tKuuUY30FC6TFsFuLKBam2hQ0bkde1zAQQUocggnscWJ4J9kvwBQ5HEErhSwSqyDLodp1DBXQ6tOGzb3xV64VrMNtM2ok01qB1rWXTCiK9sEfDVglH5rsMuzor/B49TYDsIIrRzrJHro0gO/ak5QYr/cQSD3rbdA3@y5U95Xda85J84j9HcyVeofI@nWUbdZlrwDlbkMi/CvE1rkvDu1ooiwpE@hEM6Aflx@FeWnOp8SLua6@ZTPzTBvoQJHAIW7VzdrdYENtS5aG1RS1MkVXJloRTMv/nSNr6dHo2EWpl1wj1@7S1rvP1e9bSCuJU2BP20vGh05KsIXAXtkk6vP8JrrWDdzgGPgx8uPbhxodbH4Y@jCCE4AyNvHZCFfJrmjeqo7c1YVhjgz8dThrPKYZnMnoGjuY4dSInuq5pN5dKnO/oDQ "C# (.NET Core) – Try It Online")
[Answer]
# Windows Batch (CMD), ~~90~~ 79 bytes
```
set/pX=||exit
set/pY=
for %%n in (%*)do if %X% LEQ %%n if %%n LEQ %Y% %%n
%0 %*
```
Use LF end-of-line format. Each end-of-line character can be counted as 1 byte.
No TIO (because TIO uses Linux)
Take the list from command line arguments, and ranges from `stdin`.
For example, if the program is run (assume the file is named `r1.cmd`)
```
r1 7 3 5 4 6 1 2
```
and with `stdin` input
```
1
3
4
5
6
7
```
, the program will output to `stderr` with format
```
'3' is not recognized as an internal or external command,
operable program or batch file.
'1' is not recognized as an internal or external command,
operable program or batch file.
'2' is not recognized as an internal or external command,
operable program or batch file.
'5' is not recognized as an internal or external command,
operable program or batch file.
'4' is not recognized as an internal or external command,
operable program or batch file.
'7' is not recognized as an internal or external command,
operable program or batch file.
'6' is not recognized as an internal or external command,
operable program or batch file.
```
(corresponds to output sequence `3 1 2 5 4 7 6`)
---
Explanation:
```
set /p X= Prompt for variable X (min range)
||exit If failed (end of file), exit - similar to short-circuit of logical OR
set /p Y= Prompt for variable Y
for %%n in (%*)do For each number %%n in all command-line arguments
if %X% LEQ %%n If X <= n
if %%n LEQ %Y% and n <= Y
%%n run command named "n", which lead to an error.
%0 %* Call itself, process other ranges
```
---
Ungolfed code (with interaction enabled if `true` is passed as argument 1; prompt for the list from `stdin`, use `goto` to avoid stack overflow - actually I've just tried to run a script that call itself over 70000 times without seeing any problem, so I guess it should be pretty safe):
```
@echo off
set INTERACTIVE=%1
if "%INTERACTIVE%" == "true" (
set rangeMinPrompt=Enter range min:
set rangeMaxPrompt=Enter range max:
set listPrompt=Enter list:
) else (
set rangeMinPrompt=
set rangeMaxPrompt=
set listPrompt=
)
set /p list=%listPrompt%
:loop_label
set /p rangeMin=%rangeMinPrompt%&& set /p rangeMax=%rangeMaxPrompt%|| exit /b
for %%n in (%list%) do (
if %rangeMin% LEQ %%n (
if %%n LEQ %rangeMax% (
echo %%n
)
)
)
goto :loop_label
```
[Answer]
# [Clean](http://clean.cs.ru.nl/Clean), 59 bytes
```
import StdEnv;f p l=flatten[[n\\n<-p|a<=n&&n<=b]\\[a,b]<-l]
```
[Try it online!](https://tio.run/##FYsxDsIwEAR7v2KrVJcCQkhjl7wg5fkKh9hSJOcSIUPF342pRprRPHMMWut@rO8csYdNzbafx6tgLutDPybhRHYph1KiMqv3avvzG6zTrlPrFvGeAy1i@yxmLqGtDgk8EQbCSLgR7oQL4SpgbhyEwM2Of7Y0idT6Aw "Clean – Try It Online")
Takes two lists, returns a list.
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes
```
r#~SortBy~{#&@@@r~Position~#&}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v@j9pIXKdcH5RSVOlXXVymoODg5FdQH5xZklmfl5dcpqtWr/A4oy80oc0qKrqw11jHSMa3WqTXRMdcx0zGtrY6MhYjowkVguhGqYmA5UH37VSGYDSZjp5kDVpkD1ZjpAeUz1OiZAtQi3mOiYA9kgHUY6hrWx/wE "Wolfram Language (Mathematica) – Try It Online")
`` is the `Function` operator.
This is an unnamed curried function which should be called first with the list of (expanded) dock ranges and then with the list of presents. For example, if you assign the function to `f`:
```
f[ {{4,5,6,7},{1,2,3}} ][ {1,2,3,4,5,6,7} ]
```
The list of presents simply sorted by the first-level position of the value in the list of dock ranges. We need to wrap the `SortBy` function in a list to make the sort stable.
[Answer]
# [Julia 0.6](http://julialang.org/), ~~31~~ 30 bytes
```
p%d=vcat((∩(p,x)for x=d)...)
```
[Try it online!](https://tio.run/##fZBdCsIwEITfc4qhKGQhFKrWglIvUvMgpkql1NJG8QhexWt5kbhNFeoP5iXZmXy7yRxOZbGZO1ePTXrebqyU9@tN1upCu2ODS2ooDENyNm9tixSZzCKFicJUYaYQK8wVEg2F7GVoPg8sTUvxBxrUXL5a9FDiidhDfKMzf07q9sEslhIP9DDfjN4w7tcRXw@MvDf18uzzV0/oSWghung4J0MoKvh4BHjVTVHZspLBqMYSI9laFvbSUBbFi7wymoC1TVdsceQUkGDRuQc "Julia 0.6 – Try It Online")
Redefines the `%` operator and maps the set intersection`∩()` over the docks `d` maintaining order and multiplicity of the first imput, the list of presents `p`. `vcat` with the input expanded to multiple arguments via `...` flattens the resulting nested array.
Edit, -1Byte: List comprehension instead of `map()`.
] |
[Question]
[
**This question already has answers here**:
[Shortest power set implementation](/questions/9045/shortest-power-set-implementation)
(47 answers)
Closed 7 years ago.
In almost every row nowadays, the people tends to order themselves as militaries would do.
# Challenge
Suppose `4` people where:
* person `1` has priority against person `2, 3 and 4`,
* person `2` has priority against person `3 and 4`,
* person `3` has priority against person `4`,
* person `4` has the lowest priority.
Then, when ordering those `1...4` people in a row, the possibilities are:
```
1
2
3
4
1 2
1 3
1 4
2 3
2 4
3 4
1 2 3
1 2 4
1 3 4
2 3 4
1 2 3 4
```
*Your mission is:*
Given as input the number `N` of people. Output all the possibilities for `1...N` people in the military order.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), then the shotest answer in bytes wins!
---
Input can be integer or string, followed by optional newline/whitespace, or an argument to your function. You can assume `1<=N<=10`.
The output should be every sequence in a row, in any order. For each row, output a list/array or any other valid way for the numbers in military order.
[Answer]
# Haskell, 41 bytes
```
f 0=[[]]
f n=[id,(++[n])]<*>f(n-1)
tail.f
```
[Answer]
# Japt, 5 bytes
(Yes, this is me, ETHproductions.)
```
1òU à
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=VfIxIOAgcVI=&input=NA==) (This version has a few extra bytes to pretty-print the output.)
### How it works
```
// Implicit: U = input integer
1òU // Generate the inclusive range [1..U].
à // Generate all combinations of this range.
// Implicit: output last expression
```
[Answer]
# Jelly, 4 bytes
```
RŒPḊ
```
Basically the same thing as Pyth. `R`ange, `ŒP`ower set, `Ḋ`equeue. [Try it here!](http://jelly.tryitonline.net/#code=UsWSUOG4ig&input=&args=NA)
[Answer]
## Pyth, ~~14~~ ~~9~~ 4 bytes
```
tySQ
```
[Try it here!](http://pyth.herokuapp.com/?code=tySQ&input=4&debug=0)
Thanks [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for showing me the `y` function :)
[Answer]
## Haskell, 38 bytes
```
f n=init$filter(>0)<$>mapM(:[0])[1..n]
```
The function `(:[0])` takes `x` to `[x,0]`. Doing `mapM` of this onto `[1..n]` takes the Cartesian product of `[[1,0],[2,0],...,[n,0]]`, giving each subset of `[1..n]` with missing elements replaced by `0`.
```
*Main> mapM(:[0])[1..3]
[[1,2,3],[1,2,0],[1,0,3],[1,0,0],[0,2,3],[0,2,0],[0,0,3],[0,0,0]]
```
Finally, zeroes are filtered out from each list and the empty list at the end is removed.
[Answer]
## Mathematica, 20 bytes
```
Rest@*Subsets@*Range
```
Composes an unnamed function that takes an integer and returns a list of lists. We need `Rest` because `Subsets` contains the empty list.
[Answer]
## Haskell, 44 bytes
```
import Data.List
f x=tail$subsequences[1..x]
```
As so often, the `import` ruins the score.
`tail` removes the first list (which is always the empty list) of all subsequences of the list from `1` to `x`.
[Answer]
# GAP, 21 bytes
```
Combinations([1..n]);
```
Not really a programming accomplishment, but it also includes the empty ordering...
[Answer]
## CJam, 18 bytes
```
L]ri{)1$f++}/:$1>p
```
[Test it here.](http://cjam.aditsu.net/#code=L%5Dri%7B)1%24f%2B%2B%7D%2F%3A%241%3Ep&input=4)
Uses a trick I learned from Dennis once upon a time to generate the powerset.
[Answer]
# Julia, 42 bytes
```
N->[collect(combinations(1:N,i))for i=1:N]
```
This is an anonymous function that accepts an integer and returns an array of arrays. We simply get the combinations of size `i` for each `i` from 1 to `N`. Because of the way `combinations` is implemented in Julia, the arrays are already sorted.
Example:
```
julia> f=N->[collect(combinations(1:N,i))for i=1:N]
(anonymous function)
julia> f(4)
4-element Array{Any,1}:
[[1],[2],[3],[4]]
[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
[[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
[[1,2,3,4]]
```
[Answer]
# MATLAB / Octave, 49 bytes
```
function f(n)
for r=1:n,disp(nchoosek(1:n,r));end
```
This generates the vector `[1,2,...,n]`. Then generates all subsets with `1` element, all subsets with `2` elements, ..., with `n` elements.
Example run:
```
>> f(4)
1
2
3
4
1 2
1 3
1 4
2 3
2 4
3 4
1 2 3
1 2 4
1 3 4
2 3 4
1 2 3 4
```
[Answer]
## CJam (18 bytes)
```
ri)e!{_0#<$}%_&1>`
```
is equivalent to
```
ri)e!_0f#.<:$_&1>`
```
and very different to
```
ri,:)Maf+:m*:e_);`
```
but they're all the same length.
[Answer]
# R, 36 bytes
```
function(x)sapply(1:n,combn,x=n,s=F)
```
`combn` returns all cmbinations of `x` taken `m` at a time. if `x` is a single integer, returns all combinations of `1:n`. `sapply` required to vectorize over `m`. `s=F` stops the results being simplified and thus returns a list as required.
[Answer]
# Python, 69 bytes
```
def f(n):print[[j+1for j in range(n)if 1&i>>j]for i in range(1,1<<n)]
```
The key here is that we're really just asking, in order, which bits are 1 for each number `i` in the set of all `n`-bit numbers.
[Answer]
## JavaScript (ES7 proposed), 78 bytes
```
n=>[for(i of Array(2**n).keys())if(i)[for(j of Array(n).keys())if(i&1<<j)j+1]]
```
Based on @MegaTom's binary power set answer. Only works up to n=32.
[Answer]
## Seriously, 11 bytes
```
,R;╗`╜╧i`Mi
```
~~This code is super gross. I'm disgusted at how it turned out. I really need to work on Seriously 2.~~ Actually I'm just an idiot. Still need to work on Seriously 2, though.
[Try it online!](http://seriously.tryitonline.net/#code=LFI74pWXYOKVnOKVp2lgTWk&input=NA)
Explanation:
```
,R;╗`╜╧i`Mi
,R;╗ get two copies of range(1, input+1), store one in register 0
` `M map:
╜╧ n-length permutations of range(1, input+1)
i flatten list
i flatten list
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 11 bytes
```
2i^q:B!"@!f
```
[**Try it online!**](http://matl.tryitonline.net/#code=MmlecTpCISJAIWY&input=NA)
```
2i^q % 2^n-1, where n is the input number
: % range [1,...,2^n-1]
B % convert to binary. Gives 2D array where each number is a row
! % transpose
" % for each column
@ % push that column
! % transpose into a row
f % indices of nonzero elements
% implicit end for each
% implicitly display stack contents
```
As an example, with input `3`, the code `2i^q:` gives the array `[1 2 3 4 5 6 7]`. Then `B!` gives the 2D array
```
[ 0 0 0 1 1 1 1;
0 1 1 0 0 1 1;
1 0 1 0 1 0 1 ]
```
and then the loop `"@!f` gives `3` in the first iteration, `2` in the second, `[2 3]` in the third etc.
[Answer]
# Python 3, 92
Saved 17 bytes thanks to mathmandan.
Stupid itertools and its long function names.
```
from itertools import*
lambda i:[y for n in range(i)for y in combinations(range(1,i+1),n+1)]
```
[Answer]
## Ruby, 47 bytes
```
->n{(r=*1..n).flat_map{|x|[*r.combination(x)]}}
```
```
->n{
(r=*1..n) # set r to [1, 2, 3, ..., n-1, n]
.flat_map{|x| # map and then flatten resulting array one level...
[* # a golfy variant of .to_a
r.combination(x) # combination as in combinatorics, conveniently already sorted
]}}
```
[Answer]
# Ruby, 50 bytes
A [shorter ruby solution](https://codegolf.stackexchange.com/a/74088/31203) exists, using a completely different method.
This solution uses the unique idea of looking at all the numbers from `1` to `2^n-1` and getting a list of which bits are `1`, for each number.
```
->n{(1...2**n).map{|i|(1..n).reject{|a|i[a-1]<1}}}
```
] |
[Question]
[
Write the shortest possible program or function that will join a list of columnar strings.
For this challenge, columnar strings are defined as one-character-wide strings **spanning across multiple lines**. Each character, except for the last one, is **separated by a newline character**. Some examples, separated by `---`:
```
a
b
c
d
---
h
e
l
l
o
---
c
o
d
e
g
o
l
f
---
"
q
u
o
t
e
s
"
```
Given a list of columnar strings, join them into a single string with multiple columns. If the columnar string is longer than its surroundings, it should be left-padded by spaces.
### Notes
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
* You may assume inputs are ASCII only.
* You may have trailing newlines.
* You may have trailing spaces.
* This is **not a transpose challenge**; each string in the input list of strings has newlines separating each character. The ["multi-line strings vs list of strings as input"](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/17095#17095) default does not apply here; each string in the test cases are separated by `---` and include newlines.
### Test Cases
```
Input:
---
a
b
c
d
---
h
e
l
l
o
---
c
o
d
e
g
o
l
f
---
"
q
u
o
t
e
s
"
---
Output: (note how `hello` and `code golf` are left-padded by spaces)
ahc"
beoq
cldu
dleo
o t
ge
os
l"
f
Input:
---
h
w
---
e
o
---
l
r
---
l
l
---
o
d
---
Output:
hello
world
Input:
---
p
f
---
b
m
v
---
t
s
---
d
n
z
---
k
x
---
g
N
h
---
Output:
pbtdkg
m n N
fvszxh
Input:
---
1
---
2
---
3
---
4
---
6
5
---
Output:
1 6
2
3
4
5
Input:
---
a
c
---
|
---
b
d
---
Output:
a|b
d
c
Input:
---
Output:
(empty output, or single newline)
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 39
Input is taken from files; 1 file per column; filenames passed as command-line parameters.
```
paste $@|expand|sed -r 's/(.) {7}/\1/g'
```
[Try it online!](https://tio.run/##TY6xDsIwDET3@woLIRWGNCogsVSIBVZ@gCVtQjtUpeAgVaJ8e3AJQ@Tl7Hs@uzLchtp4OlCR@9FTWdLpcoZBhRoWs472JrVbOHRS9wTYpkAtlhWI0IjqcEvAXQou8MBLEC8wSzfPwM6TUv@P4uGY/ltFGAx7R8vj5MbB9HZiZ0k9KWO9ytf03n/0tdBNFsIX "Bash – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 8 bytes
Anonymous tacit prefix function, taking list of strings with CR as newline.
```
⍉∘↑⎕FMT¨
```
[Try it online!](https://tio.run/##XU7LSgNBELz7FWEuq@AeNOoPCBIFI7i52TmsSTYBVzdW4ltPSvDBBD0IfoIHwYv5gXxK/8haM@NBFobp6urq6kqHedy9SvOiX5Zqn/TxQydvOn3f2m3NP8tMJ6837FjUzmr68lALXRzHd4tqp/p8r/ZL7c/8ux4Wk/1N/q3GdrJUZk69k@w1owOTCg4FHUHXLJuBoCfI/SvYky448ayg7zuOMo7ECE4FZ54be8WIImPa0cJ/f1peUN4LhlxGKDmL867qh@6SO8BUx4JzorGjRgQMciK4Jjpy1CUBMzUFg6rLikuIVf8L6n9VsEa0EaBgXVDdSx3foeg2JKjGa0e/ "APL (Dyalog Unicode) – Try It Online")
`¨` for each string:
`⎕FMT` ForMaT as character matrix, evaluating control characters for layout
`↑` mix into 3D array (layers: number of strings; rows: hight of longest string; columns: 1)
`∘` then:
`⍉` reverse order of axes (layers: 1; rows: hight of longest string; columns: number of strings)
---
## Pre spec-change solution, 2 bytes
```
⍉↑
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Fv56O2if/THrVNqH7UNxVIPerdqvCou0UBwtPV1a3VeNTb96ir@VHvmke9Ww6tNwZqAEoGBzkDyRAPz2DN/2kKj3pXHVqhnpiUnKKuoJ6RmpOTD6ST81NSFdLzc9KAbKXC0vyS1GIldS6Y4oxyoHAqSF1OEYjIARL5KQj5AgWQvqTcMiBZolAMJFPyqoBktkIFkEz3y0AoNQQKKBiBCAVjMKlgAqTMgLSpAkJVokIyULQGZCjYGgP9R11NQCl1dQA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 9 bytes
```
↵¤ðvVðÞṪṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwi4oa1wqTDsHZWw7DDnuG5quG5hSIsIiIsIlsnMScsJ1xcbjInLCdcXG5cXG4zJywnXFxuXFxuXFxuNCcsJzVcXG5cXG5cXG5cXG42J10iXQ==)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ε¶¡1ú€θ}ζ
```
Input as a list of multiline strings; output as a list of list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f//3NZD2w4tNDy861HTmnM7as9t@@91aPf/aCVDJR2lmDwjMBmTZwylY/JMgCwzCDMmz1QpFgA) or [verify all test cases](https://tio.run/##RU67TsNAEOz5CmvrowivAglFlFAgeq8LxzlIFLM29jnEUdLwJ/S0WAg60/sj@BEzdxsJ6XQ7Mzs7u0WdzpZ2XNONlI27jMi05oiuM9ekeVQ0TsVpOw4ffde/TX6@fl/fh8/90I1XdF9Z59rjslqKs/N/u7ntv03fTcc4ppRlxpKxzMnQgsWy5OEV4JALdKCCPAaCzgMIE8szSxM0F8ZqFiZKTBT7nBeYrKZgpNKSo/hAdZUYCGE44IllDeS8VANgJ9AWaOWlje6/Y1no7MTfICfhZzk9VJYzoAuFLOfqTT3O0NjprsN6SpI/). (The footer in the single-TIO is to join each inner list of characters; and then each string by newlines. Feel free to remove it to see the actual list output.)
**Explanation:**
```
ε # Map over each multiline string of the (implicit) input-list:
¶¡ # Split it on newlines
1ú€θ # Convert empty strings to spaces:
1ú # Pad each inner character with a leading space
€ # Map over each inner 1 or 2-char string
θ # Only keep its last character
}ζ # After the map: zip/transpose; swapping rows/columns, using " " as filler
# character if the lists are of unequal lengths
# (after which the resulting matrix of characters is output implicitly)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~1~~ 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Note that the spec states that "... *columnar strings are defined as one-character-wide strings* ...", so any empty lines in the test cases should contain a space character.
```
Õë
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&header=cVKyaS2zMSlt%2bg&code=1es&input=IjEKLS0tCgoyCi0tLQoKCjMKLS0tCgoKCjQKLS0tCjYKCgoKNSI) (header allows for input to be formatted as per the test cases) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&header=cVKyaS2zMSlt%2bg&code=1es&footer=VrdpVLDO51KzaS2zszE&input=WwonYQpiCmMKZAotLS0KaAplCmwKbApvCi0tLQpjCm8KZAplCgpnCm8KbApmCi0tLQoiCnEKdQpvCnQKZQpzCiInCgonaAp3Ci0tLQplCm8KLS0tCmwKcgotLS0KbApsCi0tLQpvCmQnCgoncAoKZgotLS0KYgptCnYKLS0tCnQKCnMKLS0tCmQKbgp6Ci0tLQprCgp4Ci0tLQpnCk4KaCcKCicxCi0tLQoKMgotLS0KCgozCi0tLQoKCgo0Ci0tLQo2CgoKCjUnCgonYQoKYwotLS0KfAotLS0KYgpkJwoKJycKXS1t)
```
Õë :Implicit input of array of multi-line strings
Õ :Transpose
ë :Remove every second element
:Implicit output joined with newlines
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes
```
FA«Pι→
```
[Try it online!](https://tio.run/##Nck7DsIwEATQmjmFlca2BBeAE1DQ0EYpjPOxpVU2GDsN4uzLNtFKo5m3MYUSOZDIzMW4@7q16rw3X5wejWreSl6ry/6mm/fJXZ95SVXnT6TvrbUBL0SM2s5GI2EC6fEBEYxREYsWwnx4hzeaUtXfB53KMMhlpz8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input in JSON-like format (but with Python string delimiters). Explanation:
```
FA«
```
Loop over all of the input strings.
```
Pι
```
Print the string to the canvas without moving the cursor.
```
→
```
Move the cursor one character to the right.
[Answer]
# Octave, ~~13~~ 61 bytes
*+48 bytes in order to properly account for newlines in columnar strings (@hakr14)*
```
@(b)reshape(strrep(b(:,1:2:end)',char(10),' '),[],size(b)(1))
```
Takes in columnar strings (with newline between characters), used as follows:
```
f = ans
a = ['a' newline 'b' newline 'c' newline 'd';
'h' newline 'e' newline 'l' newline 'l' newline 'o';
'c' newline 'o' newline 'd' newline 'e' newline newline newline 'g' newline 'o' newline 'l' newline 'f';
'"' newline 'q' newline 'u' newline 'o' newline 't' newline 'e' newline 's' newline '"']
f(a)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~123 121 137~~ 128 bytes
```
def f(l):l=[''.join(c or' 'for c in q.split('\n'))for q in l];[print(*x,sep='')for x in zip(*[s+max(map(len,l))*' 'for s in l])]
```
[Try it online!](https://tio.run/##RY3BDoMgEETv@xXEC4tVL7218UusBypQaRAQaKL9eYu2SbPJ7s6bZMavaXT2vG1CKqLQsItpO0qbp9MWB@ICJVS5QAaiLZmb6I1OSG@WMrbjecemv3Y@aJuwXKoofUvpYS67@dYeyy6eJr7gxD0aaSvDWPnLjd8A1m968i4kEtcICvNuYhLaNkFygexfXNf10b5xuMMAAjKAESSYPO5QQ74iEwKP/BlQBy1ghlfWKTsRig8 "Python 3 – Try It Online")
+16 bytes because it was failing for concurrent newlines (@hakr14)
Saved 9 bytes by using a trick from 97.100.97.108's answer where it outputs a lot of newlines at the end.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 25 bytes
```
j%2.t:R"(?<=\n)\n|^\n"+;b
```
[Try it online!](https://tio.run/##K6gsyfj/P0vVSK/EKkhJw97GNiZPMyavJi4mT0nbOun/fyVDJR2lmDwjMBmTZwylY/JMgCwzCDMmz1QJAA "Pyth – Try It Online")
Could save 2 bytes if [`re`](https://docs.python.org/3/library/re.html) supported alternations in lookbehinds.
##### Explanation:
```
j%2.t:R"(?<=\n)\n|^\n"+;b | Full program
j%2.t:R"(?<=\n)\n|^\n"+;bQ | with implicit varibles
---------------------------+-------------------------------------------------------------------------
R Q | For each string in the input,
: | Replace
"(?<=\n)\n|^\n" | Each newline preceded by another newline or by the start of the string
+;b | with " \n"
.t | Ragged transpose
%2 | Every other item (removes the newlines)
j | Join by newlines
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~77~~ 95 bytes
*+18 bytes in order to properly account for newlines inside of the columnar string (@hakr14)*
```
lambda l:"\n".join(map("".join,zip(*[s[::2].replace("\n"," ")+" "*max(map(len,l))for s in l])))
```
[Try it online!](https://tio.run/##JY5BDoMgFET3noKwASxx0W4aE08iLACh2nw/FG3S9vJWdDOZSWZeJn3XMeLtnvIWOrWBme1gCLRUIW2ecUI@m8Tp6eVvSrzul75tr7rJPoFxnpeqpISKyy71bD7HBDxKECLETBYyIQEthNhM1zNj3cAkYaMHiMW4OHiFjwihJPp6x9UvlOnK7m2F7PzhDpYrLKOrlCdceeB2h/4B "Python 3.8 (pre-release) – Try It Online")
Takes in lists of columnar strings (characters separated by newlines). Exploits the rule that you can have extra whitespace at the end.
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 51 bytes
```
"""."fold
over0:"."" "\ /#" ""."zip~
"^$"" "\ /# ++
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Takes input as a list of lists of single-character strings, and outputs as a list of row-based strings.
For testing purposes (`c<>` splits each string into a list of single-character strings):
```
["abcd" "hello" "code golf" "\"quotes\""] c<> ; n>< n>o
"""."fold
over0:"."" "\ /#" ""."zip~
"^$"" "\ /# ++
```
## Explanation
Prettified code:
```
"""."fold
over0:"."" "\ /#" ""."zip~
"^$"" "\ /# ++
```
* `"" \; fold` starting with the empty string, fold over each column...
+ `over 0: "." " "\ /#` get string of spaces with length of row built thus far as *x*
+ `" " ; zip~` zip with the following (placeholding *x* for empty accumulator elements and a single space for empty subsequent elements)...
- `"^$"" "\ /#` replace empty string with space
- `++` concatenate
[Answer]
# Excel 65 bytes
```
=LET(v,TEXTSPLIT(CONCAT(A:A),"-"),MID(v,SEQUENCE(MAX(LEN(v))),1))
```
[](https://i.stack.imgur.com/ktoEr.png)
[Answer]
# Excel (ms365), 120 bytes
[](https://i.stack.imgur.com/petM6.png)
Formula in `A1`:
```
=TEXTJOIN(CHAR(10),,MAP(SEQUENCE(ROUND(MAX(LEN(A2:A5))/2,),,,2),LAMBDA(a,LET(b,MID(A2:A5,a,1),CONCAT(IF(b=""," ",b))))))
```
I do know that since you allow for trailing spaces I could remove `ROUND()` and `/2` but it felt like cheating.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~139~~ 124 bytes
* -15 bytes thanks to ceilingcat and jdt
Takes wide character strings as input.
```
f(*s,**t,m,i){for(t=s,m=0;i=*t;)m=fmax(wcslen(*t++),m);for(;i<m;i-=~puts(""))for(t=s;*t;t++)putchar(i<wcslen(*t)?i[*t]:32);}
```
[Try it online!](https://tio.run/##bU9BTsMwELz3FZZPceJIpQUOuBYfqPhA3UNIm8Yi3pTapRUlPJ2w2WKEUKJVNDs7M7su87IpYNdbCMwVFpK31m4Eu0wYQypN/Wqth4axZOhXa3FZ8sLAs4HSwIZLtuS1ga2BhqolBkctTolnBnbU4rSiqeEGXg0ciQ0k8gYMx@G0k/@XYfqJbNuYjkGHCBoC7fWUEfeeDrjuxZtdDAvEe8J4Jxh4J/xC/Jkwnv1koB4PviEJamcRYM3/YKxbau9ji3U3HlbQsCT5R7x19EWRmOK/kyxN06AmiKv2kATtFcOehSyTbH8MPuGaPi4EuaokDUJNuh6Bl@iVTlpx@TFLp6fKakwQTleuOCen0jdbQFOWCemEGoTKLpyyuf68LsDouBuNgxD5si4OiV382sWjXaVh/TCfCdX1/VdZNcXO9/mpzxv3DQ "C (clang) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 45 bytes
```
x=>[...x+x].map((_,i)=>x.map(v=>v[i+i]||' '))
```
[Try it online!](https://tio.run/##HYxBCoMwEEX3cwrpJglq6LJQdOkFulSpaRJtSppoomLBu9tBZvH/ex/mI1YRZTDjnDuv9FEVx1aUNed8S7eWf8VI6TMzrCi3E9aiXGuTmnbfSUIYO@4gvYveam79QCsa9LSYoCnpI2E8aKEqY/Xj5yS9ZmSZ@xvqOFozd43L87xxHX4R8AIJClDAGzRYPH@SxFRoEhiwWehPe4EJFuQZlwiXPw "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 43 bytes
```
x=>[...x+x].map((_,i)=>x.map(v=>v[i]||' '))
```
[Try it online!](https://tio.run/##PYxBDoIwEEX3cwripm2ExqWJKUsu4BKI1FKwprZAgdSEu@OEhZnFn/dm8t9ylUFNZpgz51u9F2KPIi855/Eca/6RA6WP1DCRxwNWka@lqbeNJISx/QbKu@Ct5tb3tKCTHhczaUq6QBiftGwLY/X96xS9pGSZuyvqMFgzN5XLsqxyzVGrRK7@vmHYLOEJClrAJ3iBBovjD1KYLZoEetwsdIc9wQgL8oyXAKcf "JavaScript (Node.js) – Try It Online")
43 take input as array, which looks unallowed so I added the 45
] |
[Question]
[
Consider a `n x n` multiplication table and replace each item with its remainder of division by `n`. For example, here is a `6x6` table and its "modulo 6" structure: (The last column and row are ignored since both are null)
```
1 2 3 4 5 6 | 1 2 3 4 5
2 4 6 8 10 12 | 2 4 0 2 4
3 6 9 12 15 18 | 3 0 3 0 3
4 8 12 16 20 24 | 4 2 0 4 2
5 10 15 20 25 30 | 5 4 3 2 1
6 12 18 24 30 36 |
```
Now it is evident that the multiplication table modulo n is symmetric and can be reconstructed by one of its triangular quadrants:
```
1 2 3 4 5
4 0 2
3
```
## Challenge
Given a positive integer N, print the upper quadrant of multiplication table modulo N. Assume that there is no restriction on the width of string in your output environment. The alignment of numbers shall be preserved. This means, the output should look like a part of a **uniform** product table, where the cells have equal widths. So for example, if we have a two-digit number in the table, all single-digit entries are separated by two spaces.
## Rules
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Test cases
```
N = 1:
// no output is printed
N = 3:
1 2
N = 13:
1 2 3 4 5 6 7 8 9 10 11 12
4 6 8 10 12 1 3 5 7 9
9 12 2 5 8 11 1 4
3 7 11 2 6 10
12 4 9 1
10 3
```
[Sandbox](https://codegolf.meta.stackexchange.com/a/22426)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
’×þ%ɓoU¥⁺GµḶ⁶ẋ
```
[Try it online!](https://tio.run/##ASkA1v9qZWxsef//4oCZw5fDviXJk29VwqXigbpHwrXhuLbigbbhuov///8xMw "Jelly – Try It Online")
Outputs a bunch of trailing whitespace. Used the `’×þ%` trick from [hyper-neutrino's answer](https://codegolf.stackexchange.com/a/226784/66833), so be sure to give them an upvote
## How it works
```
’×þ%ɓoU¥⁺GµḶ⁶ẋ - Main link. Takes N on the left
’ - Decrement
×þ - Create a multiplication table for all integers from 1 to N-1 and 1 to N
% - Mod each by N. This leaves a trailing row of zeros.
Call this table T
Ḷ - Yield [0, 1, 2, ..., N-1]
⁶ẋ - Yield that many spaces for each
Call this list of spaces S
ɓ µ - New dyadic chain f(S, T):
¥ - Group the previous 2 links into a dyad g(S, T):
o - For each row in S and T, replace the first N elements of the row in T with spaces,
where N is the number of spaces in the row in S
U - Reverse each row
⁺ - Do it again
G - Format it as a grid and output
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
’×þ%µJ’⁶ẋoUµ⁺G
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw8zD0w/vUz201QvIfNS47eGu7vzQQ1sfNe5y////v6ExAA "Jelly – Try It Online")
I stole the idea to use logical OR to avoid needing to trim and re-pad the lists from caird. Go upvote [their solution](https://codegolf.stackexchange.com/a/226785/68942) too, please.
```
’×þ%µJ’⁶ẋoUµ⁺G Main Link; accepts x
’ x - 1
× using multiplication
þ create a product table (this does x - 1 by x)
% modulo x
----µ--------- start a new chain on this table
J range over length (1, 2, ..., N)
’ decrement (0, 1, 2, ..., N - 1)
⁶ẋ repeat " " by ^
o vectorized logical OR; basically fills the lower left triangle with spaces
U reverse each row
------µ⁺ duplicate the last chain, so this fills the lower left and flips horizontally twice, thus cutting the list to just the upper triangle
G format as grid
```
[Answer]
# [J](http://jsoftware.com/), 60 55 bytes
```
1}."1,/"2@((' ',.' ',":@,.){~(<|.)@(>/~)*1+#|>:*/>:)@i.
```
[Try it online!](https://tio.run/##ZY/LSgMxFIb3eYqPcZFJncnMyVxqgx0GBFfSha8gLdaNGxeCta8@JkdFpIGEk@@/hLwshbcHthFLRUtMu/bcPT7cL/LpC6maIsxlabGVz0cR58q7j3N5e/JuLqfm7FZyfXWa4qqZopuPfnFm//T8ygH5Hmxd21/UXaLxEklnjNm/H9@sNTu26R6NQIAOehhghDXcwAZpEUGCQcUx48ySXTQxqHeTdTQQtGtQo6ir/xHRwFpxyF3S/iloss8V6W/8W@lBuuUL "J – Try It Online")
-5 thanks to xash
I thought this would be a good challenge for J, and the essence of the problem is, but the formatting details destroyed me here.
[Answer]
# [R](https://www.r-project.org/) >= 4.1.0, ~~165~~ 152 bytes
```
\(n,`/`=sprintf){z=outer(1:n,1:n,\(x,y)(x*y)%%n[2-(pmin(y,n-y)>=x)]);z[is.na(z)]="";z[]="%%%ds"/nchar(n-1)/z;cat(apply(z,1,paste,collapse=" "),sep="
")}
```
[Try it online!](https://tio.run/##PYvBasMwEETv/QqzINgtqxq1txjlR5JAhGtRgbsWkgKWQr7ddVroYZh5MC9t3m7@JmMJi6Dwtb/aHFOQ4une7HIrU0JzEH7m/7dyJVxfKyklp3eN8TsIVhZd6WhXutDQTiG/icNGFwuw415Kqc8MvYxfLqFoQ30bRlfQxThXbGw4ulwmHpd5djFPFjogzlO08AL02PySMHRBOnMwH3R/qqC1PstZgAODPnZ/@1cBGjyGXfsB "R – Try It Online")
An anonymous function that takes an integer and prints the triangle to STDOUT. The TIO link replaces `\` with `function` since TIO is on an earlier version of R.
Thanks to @RobinRyder for saving 5 bytes, and @KirillL for saving a further 8!
[Answer]
# MATLAB/Octave, 117 bytes
```
function f(n)
r=1:n;m=num2str(mod(r'*r,n));s=(nnz(m(1,:))+2)/n;for k=1:n
m(k,1:k*s-s)=32;disp(m(k,1:(n-k)*s))
end
end
```
[Try it online!](https://tio.run/##RctBCoMwFATQfU7hzj9WKd9AF4ZcoXcoakBCfkqiXfTyKSrFxWzezMRxfX3mUtwm47pEqRwJVLI8iAlWttDnNVGIE6W6Sa0AJlsS@VIgbgfg1uMuxsVU@f2kAvmWB9/kLsPq3kxLftOJJJ1HkwE1y7SnHGX9tFxDOWKoP@gD9AWPAx4X8DlhjfID "Octave – Try It Online") This prints out quite a lot of trailing whitespaces. If we sacrifice 2 bytes to replace `k=1:n` with `k=1:n/2` the empty lines won't be printed though.
Despite my efforts to find more elegant solution using `triu` function (takes upper triangle of square matrix) this stayed the shortest solution I came up with.
Ungolfed/explained:
```
function f(n)
r=1:n;
m=num2str(mod(r'*r,n)); % modulo table transformed to char array
s=(length(m(1,:))+2)/n; % how many characters takes up one number
for k=1:n
m(k,1:k*s-s)=' '; % replace first k-1 numbers with spaces
disp(m(k,1:(n-k)*s)) % print first n-k numbers
end
end
```
[Answer]
# JavaScript (ES8), 92 bytes
Expects the input as a string.
```
n=>(g=k=>++k>n/2?'':(h=i=>++i>n-k?`
`:(i<k?'':i*k%n+'').padStart(n.length+1)+h(i))``+g(k))``
```
[Try it online!](https://tio.run/##XclBDsIgEEDRfe9hZpAUU01cNIUewgtAWgoIGZqWeH2UraufvP82H3MuR9hLT3m1dZOVpEIno1ScR0W3@wwwopehQVDUx1l3esQwxXbCNV6IAzCxm/VVzFGQRLLkiucD4x4DY1pzh7G1LpnOnKxI2eGG8ATGuj8bHj@sXw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~113~~ 96 bytes
```
def f(n):d=range(1,n);[print(*[f"{['',v*x%n][v>=x<=n-v]:{len(str(n-1))}}"for v in d])for x in d]
```
[Try it online!](https://tio.run/##JcZBCsIwEAXQvacIBelMaReh4KIaLxKyEJLRgvyWNIRI6dkj4lu99ZNeC8ZafRAlBJ68iQ88A@kefLVrnJGos9Lstm373JUznM13U24GQ3bT/g6gLUXCoJmPo5ElqqxmKO/49/J/FbrwSUiPXL8 "Python 3 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~43~~ ~~41~~ 35 bytes ([SBCS](https://github.com/abrudz/SBCS))
Anonymous prefix lambda.
```
{1↓⍕d⍪' '@{∨∘⌽⍨∘.>⍨⍳d}⍵|∘.×⍨⍳d←⍵-1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rwUdvkR71TUx71rlJXUHeoftSx4lHHjEc9ex/1ghh6diC6d3NK7aPerTUggcPToSKP2iYAxXQNa/@ngZl9j7qaH/WuedS75dB640dtEx/1TQ0OcgaSIR6ewf/TFAy5dHV1udIUjKC0MZQ2gdKmUNrQAMaA6TA0BgA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` "dfn"; N is `⍵`:
`d←⍵-1` let `d` be N minus one
`⍳` indices one through N
`∘.×⍨` multiplication table
`⍵|` that modulus N
`' '@{`…`}` replace with spaces **at** locations indicated by:
`⍳d` indices one through `d`
`∘.>⍨` greater-than table
`∨∘⌽⍨` logical OR with its own mirror image
`d⍪` prepend a row of `d`s (to size columns widths right)
`⍕` format to character matrix
`1↓` drop the first row
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes
```
E⊘θ⪫E⊖θ◧⎇‹›ιλ‹⁺ιλ⊖θI﹪×⊕ι⊕λIθωLθ
```
[Try it online!](https://tio.run/##VY27DsIwDEV/JerkSmVAjIwg8VCROvQHrMTQSG4CTlrE14eolNdk@fhcX92haI@cUiPWRTjhFfbIIxm4lZU6eusmtiUt1JOL86FBU9M5QkviUB5QUwiwE8JIArZSnJ2JNTyEN/h/UmaywZA7vRnYQ2t7CnBwX8dm43fnT@SVvk8l7hK7GRSqyHOd0nKVFiM/AQ "Charcoal – Try It Online") Link is to verbose version of code. Note: Trailing space. Explanation:
```
θ Input `n`
⊘ Halved
E Map over implicit range
θ Input `n`
⊖ Decremented
E Map over implicit range
⎇‹›ιλ‹⁺ιλ⊖θ If this entry is wanted
⊕ι Row value
× Multiplied by
⊕λ Column value
﹪ Modulo
Iθ `n` as an intger
I Cast to string
ω Otherwise the empty string
◧ Lθ Pad to length of `n`
⪫ Join with spaces
Implicitly print
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 bytes
```
’<þa⁶oU$o’×þ%ƊG
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw0ybw/sSHzVuyw9VyQfyDk8/vE/1WJf7////DY0B "Jelly – Try It Online")
Also outputs a ton of trailing whitespace
[Answer]
# [R](https://www.r-project.org/), 109 bytes
```
n=scan();m=(1:n%o%1:n%%n)[,-n];m[l<-lower.tri(m)]="";m[l[,n-1:n]]="";write.table(format(m,j="r"),,,F,r=F,c=F)
```
[Try it online!](https://tio.run/##HYpBCsMgEAD/Igi7sAZCb0336ifEgw0WUtwVtkKeb5teBmYYm1P5sxcF3IRhvavv/qJXTBQ0b5LaI7R@VluGHSCY2bmrJtLwO/PfTztGXUZ5tgqvblIGCL3ZmUMiimQcaeeIc73NLw "R – Try It Online")
A full program with some hacking around the built-in formatting/printing functionality to achieve the desired result. Here is the printing statement with all the formatting options ungolfed:
```
write.table(format(m,justify="right"),quote=FALSE,row.names=FALSE,col.names=FALSE)
```
If printing the numbers left-aligned is allowed after all, then we can save a few extra bytes by removing right-justification.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ù▼åU☻┐≈◘E╝ÖBñGRR
```
[Run and debug it](https://staxlang.xyz/#p=971f865502bff70845bc9942a4475252&i=13%0A1%0A3&m=2)
about as short as I could get it. centering the stuff took more bytes than i expected.
## Explanation
```
vc{*x%K{itiT|>Jm|Cm
vc decrement and duplicate input n
{ K cross-product map ranges (1..n-1) and (1..n-1)
* multiply the numbers
x% mod n
{ m map each row to
itiT iteration number trimmed from both sides
|> right align each number
J join with spaces
|C center
m print joined with newlines
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `CM`, ~~35~~ 30 bytes
```
ƛ⁰ɽƛ⁰ɽ*⁰%;$in(ṪḢ);ƛƛ:L⁰Lεð*p;Ṅ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=CM&code=%C6%9B%E2%81%B0%C9%BD%C6%9B%E2%81%B0%C9%BD*%E2%81%B0%25%3B%24in%28%E1%B9%AA%E1%B8%A2%29%3B%C6%9B%C6%9B%3AL%E2%81%B0L%CE%B5%C3%B0*p%3B%E1%B9%84&inputs=13&header=&footer=)
```
ƛ⁰ɽƛ⁰ɽ*⁰%;$in(ṪḢ);ƛƛ:L⁰Lεð*p;Ṅ
ƛ ; For each n in range(0,input):
⁰ɽƛ ; Generate the table: For each in range(1,input):
⁰ɽ* Multiply by range(1,input) to make a table.
⁰% Mod(input) everything
$i Make a triangle: Get the nth row of the table
n( ) Repeat n times:
ṪḢ Remove the head and tail
Align the numbers:
ƛ For each row of the triangular table:
ƛ ; For each number in that row:
:L⁰Lε Take difference of length(input) and length(number)
ð*p Prepend that many spaces
Ṅ Join each row on spaces
```
`C` centers the output, and `M` makes implicit ranges start from 0.
Improvements welcome.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Without trailing/leading spaces/newlines (**26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**):
```
L¨Dδ*s%εNF¦¨]DZg>jðδÛ˜õK.c?
```
[Try it online](https://tio.run/##ATEAzv8wNWFiMWX//0zCqETOtCpzJc61TkbCpsKoXURaZz5qw7DOtMOby5zDtUsuYz///zEz) or [verify all test cases](https://tio.run/##MzBNTDJM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VS6KP33ObTC5dwWrWLVc1v93A4tO7Qi1iUq3S7r8IZzWw7PPj3n8FZvvWT7/0p6YYe26fyPNtQx1jHTMTSOBQA).
With leading spaces and trailing spaces/newlines (**20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**):
```
L¨Dδ*s%εNF¦¨]DZg>j.c
```
[Try it online](https://tio.run/##MzBNTDJM/f/f59AKl3NbtIpVz231czu07NCKWJeodLssveT//w2NAQ) or [verify all test cases](https://tio.run/##MzBNTDJM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VS6KP33ObTC5dwWrWLVc1v93A4tO7Qi1iUq3S5LL/m/kl6YzqFtOv@jDXWMdcx0DI1jAQ).
**Explanation (of the longer version):**
```
L # Push a list in the range [1, (implicit) input]
¨ # Remove the final value to make the range [1, input)
# Create a multiplication table matrix:
D # Duplicate this list
δ # Apply double-vectorized:
* # Multiply
s # Swap so the (implicit) input is at the top of the stack
% # Modulo each value in the matrix by this
ε # Map over each row:
NF # Loop the (0-based) map-index amount of times:
¦¨ # And remove the leading/trailing items
]D # After both the inner loop and map: duplicate it
Z # Get the flattened maximum of this matrix (without popping)
g # Pop and get its length
> # Increase this length by 1
j # Prepend spaces in front of each integer up to that length+1,
# and then join every row together to a single string
δ # Map over each inner string:
ð Û # Strip leading spaces
˜ # Flatten this list (`δ` unfortunately wraps the strings in lists in the
# legacy version..)
õK # Remove all trailing empty strings
.c # Centralize this list of strings
? # And output it without trailing newline
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/) `-lm`, 96 bytes
-7 thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
w,i,j;f(a){w=log10(a)+2;for(i=0;i++<a;puts(""))for(j=i;j+i<=a;)printf("%*d",j++-i?w:w*i,i*j%a);}
```
[Try it online!](https://tio.run/##NYzLCoMwFET3fkUICLkmgnXpNfQjuu0maCM3PlFLoOKvN00Lnc0ZzsA0edc0IXhFyqEVBg6vh7m7FLHKEu28CtIFkpS1weW5b4JzgK92mtBJqrVBWFaadit4mrVcOSlzuvrKZ6Qoc6kBPEPc2WhoEnAkLOZ3HF3PNCswomZlpBW9lADsf3ij16NiaXufuOoBkzO8GzuYbgv5MH4A "C (gcc) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), ~~106~~ 103 bytes
-3 thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
w,i,j;f(a){for(w=2,i=a;i/=10;w++);for(;i++<a;puts(""))for(j=i;j+i<=a;)printf("%*d",j++-i?w:w*i,i*j%a);}
```
[Try it online!](https://tio.run/##NY3BCoMwEETvfsUSELImUuvRNfQjeu0laFM2UivWEqj47Wly6FwG3gwzQ/0YhhiDZu3JSYu7e60ymFazscQnc24oKIWUMbFSvaXls72lEIiZecPkFfepjcvK8@akKKtRaK9UzZfQhYo1V760SEdMOTwtzxL3ApLyQmYTGGgoWQ9tcien9InwH7zy995BOd5moSek4og/ "C (gcc) – Try It Online")
] |
[Question]
[
## Task:
Given sample index, x, calculate sample value f(x) of triangular wave, with period of 4 samples and amplitude 1. Offset can be negative and sample value could be either {0, 1, -1}.
## Test cases:
```
-5 -> -1
-4 -> 0
-3 -> 1
-2 -> 0
-1 -> -1
0 -> 0
1 -> 1
2 -> 0
3 -> -1
4 -> 0
5 -> 1
```
Personally I know two approaches in C - the first is using lookup table, the second is using conditional instructions. For brownie points, could you impress me with a pure "math" approach? (I mean a pure functional approach, e.g. not using conditional instructions or using memory for LUT.) But this is not an restriction. If you can't, or your language does not support it - just post any solution
[Answer]
# Mathematica, 8 bytes
```
Im[I^#]&
```
### Explanation
```
Im[I^#]&
I^# (* Raise the imaginary unit to the input power *)
Im[ ] (* Take the imaginary part *)
```
[Answer]
# TI-Basic, ~~7~~ ~~5~~ 4 bytes
```
sin(90Ans
```
(Degree mode)
-1 byte from @immibis from my old answer.
---
Old answer
```
imag(i^Ans
```
Pure-math approach on a calculator. :)
Just for fun, here's another pure-math (ish) solution for 9 bytes (In radian mode), or 8 bytes (Degree mode)
```
2/πsin-1sin(πAns/2 # Radians
90-1sin-1sin(90Ans # Degrees
```
[Answer]
# [Python 2](https://docs.python.org/2/), 20 bytes
```
lambda n:n%2-n%4/3*2
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQZ5WnaqSbp2qib6xl9L@gKDOvRCE3sUAjTUehKDEvPVVD10LHUlPzPwA "Python 2 – TIO Nexus")
I'm running a brute-force search for shorter arithmetic or bitwise expressions, I'll see if anything turns up. This one I hand-found.
[Answer]
# [Julia 0.5](http://julialang.org/), 12 bytes
```
!n=(2-n&3)%2
```
I like this approach because it's unlikely to be the shortest in any other language.
[Try it online!](https://tio.run/nexus/julia5#@6@YZ6thpJunZqypavQ/Lb9IIU8hM09BQ9fUylSTi9OhoCgzryRNQ0nVKEVB104BSMXkKeko5OkoKOZpcqXmpfwHAA "Julia 0.5 – TIO Nexus")
### How it works
Julia's operator precedence is a bit unusual: unlike most other languages, bitwise operators have the same precedence as their arithmetic counterparts, so `&` (bitwise multiplication) has the same precedence as `*`.
First, `n&3` takes the input modulo **4**, with positive sign.
The result – **0**, **1**, **2**, or **3** – is then subtracted from **2**, yielding **2**, **1**, **0**, or **-1**.
Finally, we take the signed remainder of the division by **2**, returning **0**, **1**, **0**, or **-1**.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ı*Ċ
```
[Try it online!](https://tio.run/nexus/jelly#@39ko9aRrv@6pkWmh7Ye3XO4/VHTGvf/AA "Jelly – TIO Nexus")
### How it works
```
ı*Ċ Main link. Argument: n
ı* Elevate i, the imaginary unit, to the n-th power.
Ċ Take the imaginary part of the result.
```
[Answer]
# dc, 13
Not sure if you count the modulo `%` operator as "pure math":
```
?1+d*v4%1-2%p
```
[Try it online](https://tio.run/nexus/bash#S8svUshUyMxTqNY11dMzrbVWSMnnUgCC1OSMfAWV6kx9fV39@FqFGoWUZAXdVPX/9obaKVplJqqGukaqBf/VuVLy81L/AwA). Note that `dc` uses `_` instead of `-` to indicate negative numbers.
### Explanation
```
? # read input
1+ # add 1
d*v # duplicate, multiply, square root (poor-mans abs())
4% # mod 4
1- # subtract 1
2% # mod 2
p # print
```
Note that `dc`'s `%` mod operator is the standard "CPU" version that maps negative values to negative values.
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 136 bytes
```
>,>++++<[>->+<[>]>[<+>-]<<[<]>-]>>>>-[>+<-----]>--[-<+>>>+>>>+>>>+<<<<<<<<]<->>>>>>->--[>+<++++++]>++<<<<<<<<<<[[->>>+<<<]>>>-]>[.[-]]>.
```
[Try it online!](https://tio.run/nexus/brainfuck#PYzRCQAxDEIH6tmf@xUXkew/RmtK6YMkYNSlTyPQgnqXzCEUaVauApwXmigwYpDe8FKEDmhT9HGo9PNh42a6OX2eRpXmWv8G "brainfuck – TIO Nexus")
There's probably a more trivial answer, but this essentially uses a table of values. Although brainfuck takes input as ASCII characters with positive values from 0 to 127, it still works as if it were able to accept negative values (to test, replace the `,` with `n` amount of `-` characters).
# How it works
```
>, take input (X)
>++++< take second input for modulo (4)
[>->+<[>]>[<+>-]<<[<]>-] calculate X mod 4
>>>>-[>+<-----]>-- create initial '1' character
[-<+>>>+>>>+>>>+<<<<<<<<] duplicate '1' four times as 1,1,1,1
<->>>>>>->--[>+<++++++]>++<<<<<<<<<< change 1,1,1,1 to 0,1,0,-1
[[->>>+<<<]>>>-]>[.[-]]>. move to the right X%4 * 3 times, then print the following two characters ( 0, 1, 0,-1)
```
[Answer]
# Python, ~~26~~ ~~24~~ 21 bytes
```
lambda x:(1j**x).imag
```
-2 bytes thanks to ValueInk for realizing that the mathematical method is actually longer than the trivial approach :P
-3 bytes thanks to Dennis for pointing out that I don't need the `int(...)`, thus making this shorter :)
[Answer]
# [Python](https://docs.python.org/), 20 bytes
```
lambda n:n%2*(2-n%4)
```
An unnamed function which returns the result.
**[Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqiQZ5WnaqSlYaSbp2qi@T8tv0ihJLW4RCEzT6EoMS89VUPXUkfB0EDTiouzoCgzr0QDJKujoK5rp66jkAbmaWr@BwA "Python 3 – TIO Nexus")**
[Answer]
# Mathematica, 18 bytes
```
#~JacobiSymbol~46&
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 12 bytes
```
n->imag(I^n)
```
[Try it online!](https://tio.run/nexus/pari-gp#S1OwVfifp2uXmZuYruEZl6f5Py2/SCMPKKprqqMARAVFmXklGnk6CkoKunYKSjoKaRp5mpqa/wE "Pari/GP – TIO Nexus")
[Answer]
# PHP, 20 bytes
```
<?=2<=>($argn&3?:2);
```
[Answer]
# [Haskell](https://www.haskell.org/), 19 bytes
Port of Dennis's Julia solution, just because he said it wouldn't be shortest in any other language. (Someone might still prove me wrong that it's shortest in Haskell.)
```
f n=rem(2-n`mod`4)2
```
[Try it online!](https://tio.run/nexus/haskell#Hcg7DoQgFAXQrdxiCi0uAcRf4V4kA2YseExQ4/Ix8ZQn@V2WXc5Y/Pf8XHLnEg6V/L85fvlWmyrRh1a9XTfIUmJqLGVNOayutbXSaHAGJ3AEB7AHHdiBFjTQMLDo4NBjwIgJM4x@AA "Haskell – TIO Nexus")
Haskell has two different remainder functions, one (`rem`) works like the Julia one, while the other (`mod`) gives a positive result even when the first argument is negative, and so is suitable for translating `&3`. (Haskell's *actual* `&`, called `.&.`, alas requires an `import Data.Bits`.)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 22 bytes
```
@(x)round(sin(x*pi/2))
```
[Try it online!](https://tio.run/nexus/octave#S7ON@e@gUaFZlF@al6JRnJmnUaFVkKlvpKn5P01D19TKVPM/AA "Octave – TIO Nexus")
[Answer]
# Ruby, 20 bytes
Simple and clean.
```
->x{[0,1,0,-1][x%4]}
```
[Answer]
# C99, 27 bytes
Assuming you want the wave to be centered at the origin:
```
f(n){return cpow(1i,n)/1i;}
```
otherwise `f(n){return cpow(1i,n);}` will do. I originally had a `cimag` in there, but apparently trying to return an `int` from a `_Complex int` yields the real part, so I used that. It makes sense, but it'snnothing I would have predicted. Behavior is the same in `gcc` and `clang`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
4%<Ä<
```
[Try it online!](https://tio.run/nexus/05ab1e#@2@ianO4xeb/f11DAA "05AB1E – TIO Nexus")
---
**The output is reversed, but from what I understood this is allowed:**
+1 byte to multiply output by -1 using `(`.
```
-5 -> 1
-4 -> 0
-3 -> -1
-2 -> 0
-1 -> 1
0 -> 0
1 -> -1
2 -> 0
3 -> 1
4 -> 0
5 -> -1
```
---
```
4% # Amplitude of 4...
< # Period of 1...
Ä # Absolute value...
< # Period of 1 centered at 0...
```
[Answer]
# Pyth - 7 bytes (possibly 6)
```
ta2%tQ4
```
[Try it](https://pyth.herokuapp.com/?code=ta2%25tQ4&input=3&test_suite=1&test_suite_input=-5%0A-4%0A-3%0A-2%0A-1%0A0%0A1%0A2%0A3%0A4%0A5%0A6%0A7&debug=0)
If the phase of the wave isn't important, 6 bytes:
```
ta2%Q4
```
[Try it](https://pyth.herokuapp.com/?code=ta2%25Q4&input=3&test_suite=1&test_suite_input=-5%0A-4%0A-3%0A-2%0A-1%0A0%0A1%0A2%0A3%0A4%0A5%0A6%0A7&debug=0)
Explanation:
```
ta2%tQ4
Q # The input
t # Subtract 1 to get the phase right (might not be necessary)
% 4 # Take mod 4
a2 # Absolute value of the result - 2
t # Subtract 1 so the result is in [-1,0,1]
```
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 26 bytes
```
{$0=(sqrt(($0%4)^2)-2)%2}1
```
[Try it online!](https://tio.run/nexus/awk#@1@tYmCrUVxYVKKhoWKgaqIZZ6Spa6SpalRr@P@/rimXrgmXrjGXrhGXriGXAZchlxGXMZcJlykA "AWK – TIO Nexus")
This is an alternate approach using trig functions without the modulus operator.
```
{$0=int(sin($0*atan2(0,-1)/2))}1
```
[Try it online !](https://tio.run/nexus/awk#BcExEoAgDATA/t5BQRxvTAKUPoaSJo10jm@Pu/kWvVfs@qyoRY@5Z3jVkyaXi3yWyQF2sIEOGhQGR0PH@AE "AWK – TIO Nexus")
[Answer]
# Javascript ES6, ~~18~~ 17 bytes
```
n=>n&1&&(++n&2)-1
```
Firstly, check if the input is even or odd and return 0 for all even values. For all odd inputs, increment and bitwise with `0b10` to remove any bits that don't interest us, then return the answer with an offset.
```
const f = n=>n&1&&(++n&2)-1;
for (let i = -5; i < 6; i++) {
document.body.appendChild(document.createElement('pre')).innerHTML = `f(${i}) => ${f(i)}`;
}
```
[Answer]
# JavaScript, 15 bytes
```
n=>n&3&&2-(n&3)
```
Bitwise and 3 is equivalent to modulo 4 except without the weird rule on JavaScript's modulos of negative numbers. I did polynomial regression on the first four points at first but then realized I was being dumb because (1, 1), (2, 0), and (3, -1) is just 2-n.
```
a=n=>n&1&&2-(n&3);
console.log([a(-5), a(-4), a(-3), a(-2), a(-1), a(0), a(1), a(2), a(3), a(4), a(5)])
```
[Answer]
# [R](https://www.r-project.org/), 19 bytes
```
function(n)Im(1i^n)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNP0zNXwzAzLk/zf5qGrqmVqeZ/AA "R – Try It Online")
A port of [JungHwan Min's Mathematica answer](https://codegolf.stackexchange.com/a/120752/67312).
] |
[Question]
[
Your function must accept 2 [strings](https://codegolf.meta.stackexchange.com/questions/2214/whats-a-string/8964#8964) which are correct numbers. It needs to sum them up (without rounding and floating point errors) and return the result (which is also a correct number) without any leading zeros in the integer part, trailing zeros in the decimal part and without minus if the answer is 0 i.e. `-0` is not allowed.
A correct number is a string which can start with a leading minus, contains only digits and can contain only one dot which will be between the digits:
```
'1234567890'
'-1234567890'
'12345.67890'
'-12345.67890'
```
In other words, it matches the regex `-?\d+(\.\d+)?`
Your input will always be valid so you don't need to think about empty strings, etc.
The input strings can be as large as possible in your programming language, but it is guaranteed that the length of the resulting string will not be larger than what is available in your programming language.
### Some test cases:
```
'1', '1' --> '2'
'0', '0' --> '0'
'9', '1' --> '10'
'001.002', '3.400' --> '4.402'
'5', '-5.0' --> '0'
'2', '-2.5' --> '-0.5'
'12345', '67890' --> '80235'
'-50.6', '20.53' --> '-30.07'
'-001.00', '00100' --> '99'
'-00.100', '-0.20' --> '-0.3'
'0.1', '0.2' --> '0.3'
'1000000000000', '-0.000000000001' --> '999999999999.999999999999'
```
The shortest code in each programming language wins!
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), ~~17~~ 15 bytes
```
$~*+*o**.FatRat
```
[Try it online!](https://tio.run/##TY/BbsIwDIbvfQofpgXCYpykLRQEu@0BtiNsUg8UTYKBSi9IqK/e2WlLm0MUf/9v@8/1UJ7S5nyH1wI20LzUeqYvWuNHXn3mVbOOzqvjfK8mqN@nezWv61t@h2LywN2PW9P3FK88ADZbwJ3U@FWVLSouJZx@/w63Rln1BnyBMVtQTkWKBFAHiEE2dlghRBaJnHCPMfXmmN8yIRHBJDgeEszGYdIxQ/yMlHU@DvZ0scx6/5KcF9EkhKmIjs2@b/SEtBC1TRHSkn2GyLJWQ9tqvMjRsNRLfAyfZqEPGDA3DKdrHRH7XDAcHBfqHw "Raku – Try It Online")
This converts both arguments to `FatRat`s (arbitrary sized bignums), before adding them together and stringifying the result. You could remove the `o**.FatRat` part, but this would use `Rat`s, which decay to floating point numbers once the precision needed is too high.
[Answer]
# Java 8, ~~103~~ 102 bytes
```
import java.math.*;a->b->new BigDecimal(a).add(new BigDecimal(b)).stripTrailingZeros().toPlainString()
```
[Try it online.](https://tio.run/##jZBNT8JAEIbv/IpJT12hw7ZQFFEOxngzMcGTyGGBFhe3H@luMYT0t@NsFxU92WTTeZ95dz52K3Yi2K7fjzIri8rAljRmwrzhxQT6feiGY1juTaI7KyW0hkch80MHQBth5MrZayMVpnW@MrLI8eEU3MxMJfNN718e959OIYXbowimy2CaJx9wJzf3yUpmQvmCoViv/T90yRhquls@V0IqKvGSVIX2GZriSdGorq7PjpMODV3WS0VDn2bfFXINGZl855ovBLOrAaRF5e9EBTIva6PhGmzXL9N8cTh4odej0/QOHqeIt9H4h/EQOY9ID3DIXTYmFcTohE0FEcatCKPB0GZHl1djlw5ijiMiEcd44IgraXvx8FSRGIYtCzhGjhGxHoxcZX72Od8ZoFkb1u4LMNtrk2RY1AZLWtOo3PdePa/rXmDOF12S3TMStgRuwbIURVmqvf/tZr9BuGDW7bEJtWs6zfET)
**Explanation:**
```
import java.math.*; // Required import for BigDecimal
a->b-> // Method with String as two parameters & return-type
new BigDecimal(a) // Convert the first input to a BigDecimal
.add( // Plus:
new BigDecimal(b)) // The second input as BigDecimal
.stripTrailingZeros() // Remove any no-op trailing 0s
.toPlainString() // Convert and return it as plain String (so no scientific
// notation)
```
* [Try it online without `.stripTrailingZeros()`](https://tio.run/##jZBLT4NAFIX3/IqbWYGU2xlaqrWWhTHuXHVZWQyvOpVXYKhpCL8dB6ZqdSUJ4Z7vnpw5w5GfuHOM3weRV2Ut4ag05ly@4c0G5nOw2RrCs0waI8p408ALF0VnADSSSxFpeytFhmlbRFKUBT5fhoedrEVxmP3Lo7@@DylsB@74oeMXyQc8isNTEomcZya3kMex@YeGlmUTMmwMValqw0xVujQ7lSKGXLU1dfY@4NZYHCAta/PEaxBF1coG7mHM/DLtg64jjMzU2886QtVEp2n9wyhDSl2lF7ikeusp5XioxbhyXPQmwdzFctyubu/Weu14FFeKuBS9hSY6cjyLskuiYsgm5lB0NVNk9KCrk@nVo31XQHXtrem@ALtzI5Mcy1Zipa4ps8Ikr4TY@g/saWAraV8RNhHYwshS5FWVnc1vt/UbsMAa3cTaqON6ox8@AQ) (fails for test cases `"5"+"-5.0" = "0.0"`; `"-001.00"+"00100" = "99.00"`; `"-00.100"+"-0.20" = "-0.300"`).
* [Try it online without `.toPlainString()`](https://tio.run/##jZBNT8JAEIbv/RWTPXUtHbaFoohwMMabJzyJHLal4GK/0m4xpOlvx2kXFT3ZZNN5n3l3PnYvD9Ldb95PKi3yUsOeNKZSv@HVDIZDcLwphEcdV1aUyKqCJ6myxgKotNQqMvZaqwS3dRZplWf4eA7ulrpU2W7wL4/5LxawhflJuovQXWTxB9yr3UMcqVQmtuQoNxv7Dw05x4ruFs@lVAmVeInLvLK5w9hpZtGcRR0mNOd53EOuNpDSCrZpuFpL3m0DsM1L@yBLUFlR6wpuoWv0ZVqtm4Z5bECnHTRMUCT6aPrDhIdC@KRHOBYmG5ByAzSiS7k@Br3w/NG4y06ub6Ym7QYCJ0R8gcHIEFOy6yW8c0Vi6PXMFegbRqTzoG8qi4vP@C4Azdryfl@A5bHScYp5rbGgNXWS2eyVMce8wEqsHZLOBfF6AnPo2BZlUSRH@9vNfwNvzTs34zNq11rt6RM) (fails for test case `"9"+"1" = "1E+1"`).
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$5\log\_{256}(96)\approx\$ 4.116 bytes
```
B+_x_
```
[Try it online!](https://fig.fly.dev/#WyJCK194XyIsIlwiMTAwMDAwMDBcIlxuXCItMC4wMDAwMDAwMDAwMDFcIiJd)
Since Fig uses `BigDecimal`s, this doesn't suffer from floating point issues as some other answers do.
```
B+_x_
_ # Convert first input to number
_x # Convert second input to number
+ # Add
B # Convert to string
```
[Answer]
# [Python](https://www.python.org), 84 bytes
```
lambda*x:(s:=str(sum(map(Decimal,x))))[-2:]=='.0'and s[:-2]or s
from decimal import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3Q3ISc5NSErUqrDSKrWyLS4o0iktzNXITCzRcUpMzcxNzdCo0gSBa18gq1tZWXc9APTEvRaE42krXKDa_SKGYK60oP1chBaJWITO3IL-oRAtqtlNBUWZeiUaahpKhARJQ0lHSNdBDEjBU0tTkgqs11QOrAFGamhCTFiyA0AA)
Normal numbers succumb to floating point inaccuracies, so we need to convert to `decimal.Decimal`.
[Answer]
# [bash](https://www.gnu.org/software/bash/), + [bc](https://www.gnu.org/software/bc/), 30 bytes
```
bc<<<$1+$2|sed -r "s/\.*0+$//"
```
[Try it online!](https://tio.run/##S0oszvifpqFZ/T8p2cbGRsVQW8Wopjg1RUG3SEGpWD9GT8tAW0VfX@l/LVeagrqugYGhnoGBuoI6kAGkQWJAGgHUQWr0kAQMwWog2oyAssZ6JlB9QLP0DGE6jCBiQBGQ2XpAlf8B "Bash – Try It Online")
## How?
This takes advantage of `bc` being an [arbitrary precision calculator language](https://www.gnu.org/software/bc/manual/html_mono/bc.html). It pipes the input (expected to be two arguments) to `bc` which adds them.
10 bytes to do the calculation, `bc<<<$1+$2`. 20 bytes to pipe to `sed` and remove trailing zeroes.
The golf-y bit is replacing `echo` with the bash here string (`<<<`), as in [this](https://codegolf.stackexchange.com/a/41182/115882) tip. The code is the equivalent of `echo $1+$2 | bc`. This is my first attempt at a challenge in a language other than R. I would be interested in tips to golf further.
[Try it online!](https://tio.run/##S0oszvj/PynZxsZGxVBbxej///@GBkjgv66BHhLXEAA "Bash – Try It Online")
## Example output
I am not exactly sure how to provide a list of string test cases on TIO. In the absence of that, here is the example output for the final test case on my machine (script is called `calc.sh`):
```
$ ./calc.sh '1000000000000' '-0.000000000001'
999999999999.999999999999
```
```
$ ./calc.sh '-00.100' '-0.20'
-.3
```
## [bash](https://www.gnu.org/software/bash/) + [bc](https://www.gnu.org/software/bc/), 31 bytes
This did not strip *all* trailing zeroes, as pointed out in the comments by @roblogic.
```
m=`bc<<<$1+$2`
echo ${m//[0$]/}
```
[Try it online!](https://tio.run/##S0oszvj/P9c2ISnZxsZGxVBbxSiBKzU5I19BpTpXXz/aQCVWv/b///@GBkjgv66BHhLXEAA "Bash – Try It Online")
## Answer which did not meet spec, 10 bytes
```
bc<<<$1+$2
```
Unfortunately, as pointed out by
Ismael Miguel
in the comments, the question says to
>
> return the result (which is also a correct number) without any leading zeros in the integer part, trailing zeros in the decimal part and without minus if the answer is 0
>
>
>
This did not remove all trailing zeroes.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~72~~ 69 bytes
```
≔E²Sθ≔Eθ∧№ι.⌕⮌ι.η≔ΣIEθ⁺⁻ι.×0⁻⌈η§ηκθ≔Xχ⌈ηη‹θ⁰I÷↔θη¿﹪θη«.W﹪↔θη«≧÷χηI÷ιη
```
[Try it online!](https://tio.run/##bY/BboMwDIbP4SkiTo4UUNprT6jTJKQhoXYvwEpWrEFSSEIrTX12lpSVddNyyMH@P/vzoamGg67aacqMwaOCojrBmtNcnZzd2wHVERjjtGeb6CHRc5qpGrbaKQvIaZzGPvSMvraToxyMBGRzOdDND713HWwrY@9jytYZKFD5f5nzip00EIuY07lTVBfsPNj4ZmZzVcsLNJx@sPn90iv1WQ6wEp5dqG@F0p9j4UUaEzYLtpRuQrmyTzhiLSF7M7p1VkJ/A0MO3ykUunatDqiv0c@IzHBw3kTk3GArl9DfESFO/Mmz5A6PzcNCToNuMCTkXyG8a5BrdJ2mRIh0JUSUiHQtpmRsvwA "Charcoal – Try It Online") Link is to verbose version of code. Feels very long somehow. Explanation:
```
≔E²Sθ
```
Input the two strings.
```
≔Eθ∧№ι.⌕⮌ι.η
```
See how many digits each has after the decimal (if any).
```
≔ΣIEθ⁺⁻ι.×0⁻⌈η§ηκθ
```
Scale them both to be integers and take the sum.
```
≔Xχ⌈ηη‹θ⁰I÷↔θη
```
Calculate the effect of the scaling and output the integer part of the result.
```
¿﹪θη«.
```
If the result is not an integer then output a `.`.
```
W﹪↔θη«≧÷χηI÷ιη
```
Output successive digits until the remainder is zero.
40 bytes by importing Python's `decimal.Decimal`:
```
≔IΣE²▷⪫⟦d¦.Dω⟧ecimalSθW›№θ.Σ§θ±¹≔…θ⊖Lθθθ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PU-9asMwEN7zFELTGWyjZCpkCk4IKW0JBLqEDIp8tQWybEvnJH2WLhla2qVP0ifo20Rq2t5wHN99P3cvH6qWTrXSnM9vAz1lN99fM-91ZaGQnmAzNHAvO5ikbHGQ5lE6uG21hS0vecp4Pg_9uAsTKt1Iw5OUrWw30IacthUksVLWJ9PRsdYGGSwdSkIHRTtYgj56RFHMmdHKlniK4ANWgQXjHz37O-hZGSzqtouMOSqHDVrCEu7QVlRD_5-1DuHBPJm--r3yv4-9b3l2MHz3mQmRj4UYZSKfiOvuAg "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation:
```
≔IΣE²▷⪫⟦d¦.Dω⟧ecimalSθ
```
Input the two strings, convert them to `decimal.Decimal`, take the sum, then cast back to string again.
```
W›№θ.Σ§θ±¹
```
Repeat while the string contains a `.` and does not end in a digit `1-9`...
```
≔…θ⊖Lθθ
```
... remove the last character.
```
θ
```
Output the final string.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 163 bytes
```
g(s)=eval(strjoin(t=strsplit(s,".")))/10^if(#t>1,#t[2])
h(n)=if(n*=10,Str(n\1,h(n-n\1)),"")
f(a,b)=Str(if(0>t=g(a)+g(b),t=-t;"-","")d=t\1,if(t-=d,Str("."h(t)),""))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZFBTsMwEEXFCqmniNyNB2wzdpvSCrmXYFla5FKSBkUhSgYkzsKmEkKcCU7DJHGleOM_b76_R_bnTx2a4jGvT6fvN8r08vcrly345_dQypaal9eikuRZtXVZkGyVMAIAbizuikxOaW3VlDZuC5OjrMAzq668RXVPjawerGKqeQdQQsAkk0HtwXdNduKafC4DXOdyD4q8pjuhRWc8eOKzbCHtD30WX3uUNMTAMOrfxWWo6_JDhkSvk7opKmIpukIkT6EsZaaSwEeSzUZYzrViy1ogSxzkakTRGkQnVCJmZo7RkHa1Tk0s-7Z2Jh1K62bz3rG4Xa6iRadoFh1zaNJZZEN4R1mds5kaO1CNxkXKrPcZF-_A0YreEeHpt_E9zl_4Dw)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 1, 3 or 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
None of these can handle the last test case as the decimal exceeds JavaScript's native number support. Links include all other test cases, taking input as an array of 2 strings.
Outputs an integer, subject to floating point inaccuracies.
```
x
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=eA&input=WwpbJzEnLCcxJ10KWycwJywnMCddClsnOScsJzEnXQpbJzAwMS4wMDInLCczLjQwMCddClsnNScsJy01LjAnXQpbJzInLCctMi41J10KWycxMjM0NScsJzY3ODkwJ10KWyctNTAuNicsJzIwLjUzJ10KWyctMDAxLjAwJywnMDAxMDAnXQpbJy0wMC4xMDAnLCctMC4yMCddClsnMC4xJywnMC4yJ10KXS1tUQ)
Outputs an string, subject to floating point inaccuracies.
```
x s
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=eCBz&input=WwpbJzEnLCcxJ10KWycwJywnMCddClsnOScsJzEnXQpbJzAwMS4wMDInLCczLjQwMCddClsnNScsJy01LjAnXQpbJzInLCctMi41J10KWycxMjM0NScsJzY3ODkwJ10KWyctNTAuNicsJzIwLjUzJ10KWyctMDAxLjAwJywnMDAxMDAnXQpbJy0wMC4xMDAnLCctMC4yMCddClsnMC4xJywnMC4yJ10KXS1tUQ)
Outputs a string, with no floating point inaccuracies.
```
x x¡X°s q. hP ÌÊÃrÔ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=eCB4oViwcyBxLiBoUCDMysNy1A&input=WwpbJzEnLCcxJ10KWycwJywnMCddClsnOScsJzEnXQpbJzAwMS4wMDInLCczLjQwMCddClsnNScsJy01LjAnXQpbJzInLCctMi41J10KWycxMjM0NScsJzY3ODkwJ10KWyctNTAuNicsJzIwLjUzJ10KWyctMDAxLjAwJywnMDAxMDAnXQpbJy0wMC4xMDAnLCctMC4yMCddClsnMC4xJywnMC4yJ10KXS1tUQ)
[Answer]
# Excel, ~~7~~ 9 bytes
```
=A1+B1&""
```
[Answer]
# PHP 8.x + [BC Math](https://www.php.net/manual/en/book.bc.php), 46 bytes
It's a bit longer than expected, but does the job.
```
fn($a,$b)=>rtrim(rtrim(bcadd($b,$a,99),0),'.')
```
This creates an anonymous function that returns the expected result.
---
# How does it work?
It uses the [`bcadd`](https://www.php.net/manual/en/function.bcadd.php) function to do all the math, using an obnoxiously high scale, just to be safe.
That function accepts 2 strings and returns a string with the calculations made.
After that, removes all 0's from the right, then the period (.).
If none is found, does nothing to the result.
---
You can try it on here - with testcases:
<https://onlinephp.io?s=VVHNSsNAED4byDvMIbAJbLabpH9RY_EgeBDswVsIkiYbItSmJNsiiG8gePGo7-Hz-AK-gpPduK17mJn9vvnmhzlfbOutbdnWaASX6zVI0Uko8k50tuU8QQKpbZ2kJCAUtAlJRhXE-99gBig2WYHBOA8Y52EPRmzMlWCMgakz6RF_wv6XUgI_ZJrl6AciCKOxAqezeaw0cx5GhvYnnE3VnKiJlDjijM8Mr-dRvXiggzg-YtkAYs_wL4jMMkxth5R2hkDR4Q2qIyTQbQ6PHX9IZlvZ2XCEu1pA0ZQCZJ1LKBvRQSd3VYXnqDZ4j2rjOjl1Vl5y0cr24dHVdlXkZek6K4pkHHuUe5Qw4qmqVdOKvKhdvGfegbP3nnFmpxXdbi2xotOX3Kc8o8ilQdaLTkRRN2BykqSnwgwWQL4_3n--3gicYvj52i8GPqAbkiksr5f3V7c3WOXlFw%2C%2C&v=8.2.1>
Extremely long URL to avoid saving it on the website
[Answer]
# [Dyalog APL](https://www.dyalog.com/dyalog/dyalog-versions/182.htm), 7 bytes
```
+/⍎¨
```
[Try it online!](https://tio.run/##bVA7UsMwEO05xXYuwEJW4nwukI6GyQVke@NoIiTHkif4AnTJ0FDScw6OkouElYOHxEEzkkbv7dO@t7LScdFKbcuTs9rA8e0d7h@P@8P316m/j4ePAHd8lERh311hPAr7Gpv/V8cTxrkgZsTGfKhICY9TNoRDeSxYOoATMRoHxWQ6mw8lccrZhDjBWToacmcTUefmxgOxLOnYmDMxZIkLOiYI33/Cco2gpfPgkY5cOgTlQEKmCKpVvmnBKZMjFLbJNEJVY66csiaUGesBjW3KdeixeO4mn4jZFM5fU8mL3CD9pzV46uSazOG2QeNhpa30ypRQWUVPW2FNb2scNORh28jir1efIFqIlCUiCs2elv0Q@cU6h74AKGwfs0bXaB98a1mX@OscvIWM4ilXadliAcqAyxVZVCuVh4idrQfqBjsSuYpMrVrAV5l73cLa7gK@kxQizMyCtnZz@gE "APL (Dyalog Unicode) – Try It Online")
**Explanation:**
```
+/⍎¨
¨ ⍝ Map each element in the array
⍎ ⍝ Execute expression, which converts from string to integer
/ ⍝ Reduce
+ ⍝ Sum
```
[Answer]
# [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), 162 bytes
```
x=a+b;y=x/1;if(y==x)x=y;if(x==0||x<=-1||x>=1){print x,"\n";return}
if(scale(x)>1&&x*10^length(x)%10==0){scale=1;y=x/1.0;x=y};if(x<0)print "-0",-x else print "0",x
```
[Try it online!](https://tio.run/##TVFBbtswELzrFQsbTc2WYpeSlcRxmEOPPfQFRRFZWscCDMoQ6YaC47e7K0tWxAuHMzucIbgpLiVtK0vgfJOX5SKXG3GKDk1lPcz@2NklmPz7Zt2a8EOvq@2iNSaIYNoOB2Pw4yM8m1jz9mK0OPXGIDvruiF/bOw54lFX5HtaBPGi7@7CN41/92Tf/I6ZLxr5GnG6ThjdJylcc8b5GvKMYqgT40zGAWjvCAaKmXD5bHuOouEdWmpxwyhxxKspjxyEiUzVElEAzGHJKLnJmYwz1fHDmgPepETGicqmUowqG7OTdJnJ@4fHVe@ewyMm6SjHGap7mbAhHeQ4RYUPo973krxda/HAajURFdOS85K@M6MU4OnzVUpLFsWktkrHajhZ3SWToxYQRXP4/fMJXjfFK2yPtvBVbR3k@/e8ddD/JyC878iC31EL7lgURCXktuyIhr46sDXwOPia1cOhIeeg8gp@HZ2H6s3WDQH9o4bNVNTsw8t/ "bc – Try It Online"). Adapted from a [great s.o answer](https://stackoverflow.com/a/29759278/148889).
Explanation
```
x=a+b starting out simple
y=x/1;if(y==x)x=y drop trailing 0's after the decimal
(99.00 --> 99 )
if(x==0||x<=-1||x>=1) if x==0 or abs(x)>=1 then just print it
return preferable to `else{...}`, IMO.
From now on x is between -1 and 1.
if(scale(x)>1 if x has an gnarly decimal
&&x*10^length(x)%10==0) and the last digit is 0
{scale=1;y=x/1.0;x=y} drop trailing 0's & keep significant digits
(-.300 --> -.3)
if(x<0)print "-0",-x (-.3 --> -0.3)
else print "0",x ( .5 --> 0.5)
```
[Answer]
# JavaScript, 210 bytes
```
(a,b)=>([a,c='']=a.split`.`,[b,d='']=b.split`.`,m=c[k='length'],e=(o=(g=i=>BigInt(i+c.padEnd(l=m>d[k]?m:d[k],0)))(a)+g(b,c=d)+'')[k]-l,h=o.slice(0,e),i=o.slice(e).replace(/0+$/,''),(!h|h=='-'?h+0:h)+(i&&'.'+i))
```
```
(a,b)=>( // Define function
[a,c='']=a.split`.`, // a - integer part of number a
// c - decimal part of number a (default value is '')
[b,d='']=b.split`.`, // b - integer part of number b
// d - decimal part of number b (default value is '')
m=c[k='length'], // m - length of c
// k - 'length' key
e=( // e - decimal point position
o= // o - sum of BigInts as string
(g=i=>BigInt( // g - function which convert string to BigInt
i+
c.padEnd(
l=m>d[k]?m:d[k], // l - the length of longest decimal part
0
)
))(a)+
// c.padEnd(l, '0') - adding to the end of decimal
// part as many zeros as it need to
// be the length of 'l'`
// i + c.padEnd(l, '0') - same number as in input
// without decimal point and possibly
// with trailing zeros
g(b,c=d)+ // now c is decimal part of number b
'' // added to convert BigInt to string
)[k]-l,
h=o.slice(0,e), // h - integer part of result
i=o.slice(e).replace(/0+$/,''), // i - decimal part of result
(!h|h=='-'?h+0:h) // if h is empty string or minus
// then add zero else do nothing
+ // concatenate of integer part of result
// and decimal part of result
(i&&'.'+i) // if i is empty string then
// return empty string else
) // add leading dot
```
Try it:
```
f=(a,b)=>([a,c='']=a.split`.`,[b,d='']=b.split`.`,m=c[k='length'],e=(o=(g=i=>BigInt(i+c.padEnd(l=m>d[k]?m:d[k],0)))(a)+g(b,c=d)+'')[k]-l,h=o.slice(0,e),i=o.slice(e).replace(/0+$/,''),(!h|h=='-'?h+0:h)+(i&&'.'+i))
;[
['1', '1'], // '2'
['0', '0'], // '0'
['9', '1'], // '10'
['001.002', '3.400'], // '4.402'
['5', '-5.0'], // '0'
['2', '-2.5'], // '-0.5'
['12345', '67890'], // '80235'
['-50.6', '20.53'], // '-30.07'
['-001.00', '00100'], // '99'
['-00.100', '-0.20'], // '-0.3'
['0.1', '0.2'], // '0.3'
['1000000000000', '-0.000000000001'], // '999999999999.999999999999'
].map(x => {
console.log(f(x[0], x[1]));
console.log(f(x[1], x[0]));
})
```
[Answer]
# [Factor](https://factorcode.org/) + `decimals`, 48 bytes
```
[ [ string>decimal ] bi@ D+ unparse " " split1 ]
```
[](https://i.stack.imgur.com/DvEoH.gif)
```
[ string>decimal ] bi@ ! convert both inputs to the decimal data type (arbitrary size decimals)
D+ ! add them together
unparse ! convert prettyprinted format to string
" " split1 ! remove DECIMAL: prefix
```
[Answer]
tcl:
expr $A+$B
Tcl has no concept of a "number"; everything is a string. Some strings can be interpreted as numbers, which is what "expr" does above.
Literally "take the contents of the variables "A" and "B", put a "+" between the two and treat the result as interpretable as an expression (and return the result of that expression)"
] |
[Question]
[
**SPECIFICATION**
Given `m` variables, create every combination up to order `n`. For example,
The output of mapping two variables (`a` and `b`) to order `1` would be:
* a
* b
* a b
The output of mapping two variables (`a` and `b`) to order `2` would be:
* a
* a2
* b
* b2
* a b
* a2 b
* a b2
* a2 b2
The output of mapping two variables (`a` and `b`) to order `3` would be:
* a
* a2
* a3
* b
* b2
* b3
* a b
* a2 b
* a3 b
* a3 b2
* a b2
* a b3
* a2 b3
* a2 b2
* a3 b3
The output of mapping three variables (`a`, `b`, and `c`) to order `1` would be:
* a
* b
* c
* a b
* b c
* a c
* a b c
The output of mapping `m` variables to order `n` would be:
* etc.
**WINNING CRITERIA**
Output every possible combination as outlined above. Order does not matter. Where in your code you print to the screen does not matter. All that matters is that what shows up in your output is correct.
[Answer]
# LATEX, 354 bytes
When I saw this I knew it had to be done in Latex. Equations just look so crisp and clean in Latex and I can't stand using `^` for power.
```
\documentclass{article}\input tikz\usepackage{intcalc}\usepackage{ifthen}\begin{document}\typein[\a]{}\typein[\b]{}\foreach\x in{1,...,\intcalcPow{\b+1}{\a}}{\begin{equation}\foreach[count=\i]\y in{a,...,z}{\ifthenelse{\(\i<\a\)\OR\(\i=\a\)}{\y^\intcalcDiv{\intcalcMod{\x}{\intcalcPow{\b+1}{\i}}}{\intcalcPow{\b+1}{\i-1}}}{}}\end{equation}}\end{document}
```
## Explanation
There are three main forces at work here `\typein` which is what allows us to take input from the command line, the `intcalc` package which is what allows us to make calculations with our variables, and the Latex`equation` environment.
---
Once we have taken in input we begin a loop we loop `\intcalcPow{\b+1}{\a}` times, once for each result we want to print. Each loop we begin an `equation` environment and loop through the alphabet keeping track of `\y` for the current letter and `\i` for the current number of runs. If `\i` is greater than or equal to `\a` we don't print anything at all (according to the specs this is not strictly necessary however Latex will overflow for values greater than 1 if we don't do this). We then print `\y` to our equation and raise it to the power of
```
\intcalcDiv{\intcalcMod{\x}{\intcalcPow{\b+1}{\i}}}{\intcalcPow{\b+1}{\i-1}}
```
That whole mess simply means take the `\i`th digit of `\x` in base `\b+1`. This ensures that the powers are decoded properly.
### Example output:
Here is the output for 3, 2
[](https://i.stack.imgur.com/hzX8M.png)
[Answer]
# Mathematica, ~~51~~ 50 bytes
```
Rest[1##&@@@PowerRange[1,#^#2,#]~Distribute~List]&
```
Assumes "given `m` variables" means the first input is a list of variables.
**If first input is an integer, 69 bytes**
```
Rest[1##&@@@PowerRange[v=Unique[]~Table~#;1,v^#2,v]~Distribute~List]&
```
The variables are in the form `$<integer>` (e.g. `$5`)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes
```
j₎o⊇ᵘb
```
Takes input as a couple, containing the list of variables and the order. Output is a list of lists of variables, where powers are represented by repeated variables. (e.g. "a²b" is ["a","a","b"])
[Try it online!](https://tio.run/nexus/brachylog2#@5/1qKkv/1FX@8OtM5L@/4@OVkpU0lFKUorVMYr9HwUA "Brachylog – TIO Nexus")
`j₎` joins the first input with itself as many times as stated by the second input. `o` orders the list obtained, and then `⊇ᵘ` finds all unique subsets of that ordered list. Finally, we remove the first element with `b`, since this will always be the empty answer, which is not contemplated by the challenge.
[Answer]
## Haskell, ~~71~~ ~~58~~ ~~54~~ 53 bytes
```
n#m=tail$concat<$>mapM(\x->(\i->x<$[1..i])<$>[0..n])m
```
Returns a list of strings and uses the output format `"aabbb"` for `"a^2 b^3"`.
Usage example: `3 # "ab"` -> `["b","bb","bbb","a","ab","abb","abbb","aa","aab","aabb","aabbb","aaa","aaab","aaabb","aaabbb"]`. [Try it online!](https://tio.run/nexus/haskell#@5@nnGtbkpiZo5Kcn5ecWGKjYpebWOCrEVOha6cRk6lrV2GjEm2op5cZqwmUijbQ08uL1cz9n5uYmadgqwBSqlBQWhJcUuSTp6CiYKygrKCUmJSs9B8A "Haskell – TIO Nexus").
Many bytes are spent for output formatting. A more flexible output, e.g. pairs of (variable, power) -> `[('a',2),('b',3),('c',1)]` for `"a^2 b^3 c^1"` would save a lot.
How it works
```
mapM(\x-> )m -- for each variable x in the input list m
\i->x<$[1..i] -- make i copies of x
<$>[0..n] -- for all numbers from 0 to n
-- in fact mapM makes all possible combinations hereof, i.e.
-- [["",""], ["", "b"], ["", "bb"] ... ["a",""], ["a","b"], ...]
concat<$> -- join all inner lists
-- e.g ["aa","bbb"] -> "aabbb"
tail -- drop the first (all powers = ^0)
```
With maximum flexibility, i.e. output format as (variable, power) pairs and including all-zero powers (`"a^0 b^0 c^0"`) it boils down to
### Haskell, 25 bytes:
```
f n=mapM((<$>[0..n]).(,))
```
Usage example: `f 2 "ab"`:
```
[[('a',0),('b',0)],
[('a',0),('b',1)],
[('a',0),('b',2)],
[('a',1),('b',0)],
[('a',1),('b',1)],
[('a',1),('b',2)],
[('a',2),('b',0)],
[('a',2),('b',1)],
[('a',2),('b',2)]]
```
Dropping all-zero powers costs 5 bytes for a total of 30: `f n=tail.mapM((<$>[0..n]).(,))`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṗj€“”Ṣ€
ŒPçЀj“”Q
```
A dyadic link (function) that accepts a list of variable names\* and the maximal order (an integer) and returns a list where each entry is a fully expanded representation of the multiplication (e.g. **foo0bar3bof2** would be `['bar', 'bar', 'bar', 'bof', 'bof']`.
\* the variable names may be a string of unique characters (strings become lists of characters).
**[Try it online!](https://tio.run/nexus/jelly#@/9w5/SsR01rHjXMedQw9@HORUA219FJAYeXH54AZGZBxAP/H17uDeRG/v8frZ6Wn6@uo56UWAQk0/KT1GP/mwAA)** - the footer calls the link as a dyad and then separates the resulting list of lists by line feeds and each entry by spaces for ease of reading.
*Note:* includes the **0** order (empty product) a dequeue, `Ḋ`, may be inserted here `...ŒPḊç...` to avoid that.
### How?
```
ṗj€“”Ṣ€ - Link 1, sorted results of a Cartesian power: elements, power
ṗ - Cartesian power of elements with given power
j€“” - join €ach with "" (flatten each by one level)
Ṣ€ - sort €ach
ŒPçЀj“”Q - Main link: variableNames, maximalOrder
ŒP - power-set of variableNames (e.g for ['a','b','c'] this would be ['','a','b','c','ab','ac','bc','abc'])
Ѐ - for €ach mapped over right argument (i.e. over the range [1,2,...,maximalOrder])
ç - call the last link (1) as a dyad (i.e. power-set results are the elements and one of the range values is the power)
j“” - join with "" (flatten by one level)
Q - unique values
```
---
13 byte version that will only work for a single string of unique characters (or a list of unique characters):
```
ŒPṗЀj“”F€Ṣ€Q
```
[try it](https://tio.run/nexus/jelly#@390UsDDndMPT3jUtCbrUcOcRw1z3YDMhzsXAcnA/4eXR/7/r56YlKz@3wgA)
[Answer]
## JavaScript (ES proposal), 142 bytes
```
f=
(v,n)=>[...Array(++v**n)].map((_,i)=>i.toString(v).padStart(n,0).replace(/./g,(c,j)=>(+c?(10+j).toString(36):``)+(c>1?c.sup():``))).join`<br>`
```
```
<div oninput=o.innerHTML=f(v.value,n.value)><input id=v type=number min=1 value=1><input id=n type=number min=1 value=1><span id=o><br>a
```
Requires a browser with both `**` and `padStart` support, so try Firefox 52 or Chrome 57.
[Answer]
# Mathematica 100 bytes
Surely there is a more efficient way to accomplish this!
Two variables to order 4:
```
(Times@@@(MapThread[Power,#]&/@Outer[List,{Alphabet[][[1;;#]]},Rest@Tuples[Range[0,#2],#],1][[1]])) &
```
[](https://i.stack.imgur.com/gIWb4.png)
[Answer]
# Bash + sed, 60
A different, shorter approach to my previous answer.
Input as command-line parameters - `m` is given as a comma-separated list of variable names, and `n` as an integer:
```
p=eval\ printf
$p -vc %s {$1}^\\{0..$2}
$p '%s\\n' $c|sed 1d
```
[Try it online](https://tio.run/nexus/bash#PYtBCoMwFAX3nuIRIm6MNHbX0pt8CmnypUJJgglurGdPLba@zTwYZggTMqdsTWKMHsK0D2ixs//xvLO1m7nChYrtM0AcHQn5/yQuosK2xBlK4RAl3ng2L0KcRp@HSkao2aJOWKRe70TLqetkv35FUyci30Dad2IH7YoLnssH).
---
Previous Answer:
# Bash + coreutils, 91
Welcome to eval-escape-brace hell. Sometimes shell-script really gives just the right tool for the job. This is **not** the case here, but it works.
Input as command-line parameters - `m` is given as a comma-separated list of variable names, and `n` as an integer. Output is written out longhand - e.g. `a^2` is actually written `aa`. This is acceptable as per [this comment](https://codegolf.stackexchange.com/questions/112611/create-every-combination-of-variable-groups-up-to-order-n?noredirect=1#comment274481_112611).
```
p=eval\ printf
$p -vc {%$[$2-1]s}
$p '%s\\n' $($p %s \{{$1}${c// /,}\\\,})|tr -d {}|sort -u
```
There may be shorter ways to do this.
[Try it online](https://tio.run/nexus/bash#PY29DsIwDIT3PsUpSgVIiarCBmJiYGXHDCVNoVJJqiQwEPLspfze8vl8sq@xDkH7oCqv0RqwShxRsg/nXy4@FOqd7Jw9uepyac1J7K73e6e92Nhai63tmvFmhdpmWp0t2P8zMf6biS1ZhlFeB0iJfzD0a32rOkLvWhOajPeQN4WY8z2fy/Lg02s1yT2RmYBPR5N7UIy8TDyqokAhEhGJNHsEB1kjpoe3bmy5DrU1engC).
# Explanation
* `printf -vc {%$[$2-1]s}` assigns the variable `c` to a string like `{ }`, where the number of spaces is the order `n` - 1, so if `n` = 1, the result is `{}`, if `n` = 2, the result is `{ }`, etc.
* `${a[$1]}` uses `m` as an index to the array `a`, so if `m` is 3, then the result is `c`
* `\{{a..${a[$1]}}${c// /,}\\,}` is a multi-part brace expansion:
+ `\{` - a literal `{`
+ `{$1}` is a is the brace expansion of the list `m`, e.g. `{a,b,c}` or `a b c`
+ `${c// /,}` replaces the spaces in `$c` with commas, e.g. `{,,}` for `n` = 3, which is also a brace expansion which effectively repeats each element of `{a..c}` `n` times
+ `\\\,}` - a literal `,}`
* So for `m` = "a,b" and `n` = 2, this expands to `{a,} {a,} {b,} {b,}`
* The inner `printf` removes the spaces to give `{a,}{a,}{b,}{b,}`, which itself is a brace expansion
* This expands to `aabb aab aab aa abb ab ab a abb ab ab a bb b b`
* The outer `printf` puts each of these elements on its own line
* `sort -u` removes the duplicates
* The `tr -d {}` is there to handle the case when `n` = 1. In this case the variable `c` will be `{}` which is not a brace expansion, but instead the literal characters are inserted. The `tr` removes them.
`eval`s and `\` escapes are placed *very* carefully to ensure that all the expansions occur in the necessary order.
[Answer]
# [Röda](https://github.com/fergusq/roda), ~~49~~ ~~48~~ 46 bytes
```
f n{r=[""]{|v|r=r...[seq(0,n)|[v.._]]}_;r[1:]}
```
[Try it online!](https://tio.run/nexus/roda#DcSxCoAgEADQub7iuEkhjmos@hIRKUhySOwqF/XbrTe8asEnXhSiTjlmXpiI1L1fou@8zCoSGa2LmVkNky71XJ2H1DbhvQ@BK3aAG0rIYGH8D@z8A6Yt9QM "Röda – TIO Nexus")
I think it is correct. It doesn't use any separator between a variable and its order. The previous version used `!`, but I realized that it isn't strictly required.
Explained:
```
function f(n) {
r := [""] /* r is a list with one empty string. */
/* Loops over the variable names in the stream. */
for var do
/* Concatenates every element in r to */
/* every element in the list that contains orders of */
/* variable var. */
r = r...[
push(var..x) for x in [seq(0, n)]
]
done
r[1:] /* Return elements of r not counting the first. */
}
```
[Answer]
# Python, 112 bytes
```
import itertools as t
f=lambda n,v:[''.join(map(str.__mul__,v,I))for I in t.product(range(n),repeat=len(v))][1:]
```
Usage:
```
for x in f(3, 'ab'):
print(x)
```
Output:
```
b
bb
a
ab
abb
aa
aab
aabb
```
Nicer format in **115 bytes**:
```
import itertools as t
f=lambda n,v:[''.join(map('{}^{}'.format,v,I))for I in t.product(range(n),repeat=len(v))][1:]
```
Output (same usage):
```
a^0b^1
a^0b^2
a^1b^0
a^1b^1
a^1b^2
a^2b^0
a^2b^1
a^2b^2
```
Even nicer in **125 bytes**:
```
import itertools as t
f=lambda n,v:[''.join(c+'^%s'%i for c,i in zip(v,I)if i)for I in t.product(range(n),repeat=len(v))][1:]
```
Output:
```
b^1
b^2
a^1
a^1b^1
a^1b^2
a^2
a^2b^1
a^2b^2
```
The last 4 bytes (`[1:]`) in all are for removing the empty product.
These work in both Python 2 and 3.
[Answer]
# C++14, ~~146~~ 140 bytes
-6 byte for simpler output format.
Unnamed lambda, assuming input `s` like `std::string` and `o` as `std::ostream`:
```
[](auto s,int n,auto&o){int l=s.size(),k,c,*p=new int[l]{1};while(!c){for(c=1,k=0;k<l;o<<s[k]<<"^"<<p[k],p[k++]*=!(c=(p[k]+=c)>n));o<<" ";}}
```
Usage and explanation:
```
#include<iostream>
#include<string>
auto f=
[](auto s, int n, auto&o){
int l=s.size(), //string length
k, //running variable for l
c, //carry for the increment
*p=new int[l]{1}; //init array with first elem 1
while(!c){ //if carry was leftover, break
for(
k=0,c=1; //always start with carry
k<l;
o<<s[k]<<"^"<<p[k], //output
p[k++]*=!(c=(p[k]+=c)>n)
// p[k]+=c //inc p[k]
// c=(p[k]+=c)>n //if value is greater than order
// p[k++]*=!(c=(p[k]+=c)>n) //set p[k] to 0 and inc k
);
o<<" ";
}
}
;
main(){
f(std::string("ab"),3,std::cout);
std::cout << "\n";
f(std::string("abc"),2,std::cout);
}
```
Output:
```
a^1b^0 a^2b^0 a^3b^0 a^0b^1 a^1b^1 a^2b^1 a^3b^1 a^0b^2 a^1b^2 a^2b^2 a^3b^2 a^0b^3 a^1b^3 a^2b^3 a^3b^3
a^1b^0c^0 a^0b^1c^0 a^1b^1c^0 a^0b^0c^1 a^1b^0c^1 a^0b^1c^1 a^1b^1c^1
```
] |
[Question]
[
**This question already has answers here**:
[Count the number of ones in an unsigned 16-bit integer](/questions/47870/count-the-number-of-ones-in-an-unsigned-16-bit-integer)
(77 answers)
Closed 7 years ago.
**The Challenge**
Given a non-empty string containing only lowercase or uppercase letters and no spaces:
* Sum up the [ASCII values](http://www.asciichart.com/) for each character instance in the input string.
* The sum will be converted to [binary](http://www.decimaltobinary.com/761-in-binary).
* And, the result will be the number of ones in the binary value.
**Input example:**
```
abcDeFAaB
```
1. Sum up the [ASCII values](http://www.asciichart.com/) for each character instance, so for this example: `97+98+99+68+101+70+65+97+66 = 761`.
2. Convert the sum (`761`) to [binary](http://www.decimaltobinary.com/761-in-binary). This will give `1011111001`.
3. The final result will be the number of ones (`7`).
So the output for this example is `7`.
**Winning Criterion**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
OSBS
```
**[TryItOnline](http://jelly.tryitonline.net/#code=T1NCUw&input=&args=ImFiY0RlRkFhQiI)**
How?
```
OSBS - Main link: s e.g. "abcDeFAaB"
O - ordinal (vectorises) [97, 98, 99, 68, 101, 70, 65, 97, 66]
S - sum 761
B - binary [1, 0, 1, 1, 1, 1, 1, 0, 0, 1]
S - sum 7
```
[Answer]
# Python3, ~~46~~ 40 bytes
```
lambda s:bin(sum(map(ord,s))).count("1")
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 3 bytes
```
sBs
```
[Try it online!](http://matl.tryitonline.net/#code=c0Jz&input=J2FiY0RlRkFhQic)
Shortest language for this challenge, I think: `s`um, `B`inary, `s`um.
[Answer]
# R, ~~65~~ ~~53~~ ~~43~~ 42 bytes
Counting the number of 1s in a binary representation is calculating the [Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight) of a number, a common procedure in cryptanalysis. There's an R package `boolfun`, described in [this journal article](https://journal.r-project.org/archive/2011-1/RJournal_2011-1_Lafitte~et~al.pdf), which handily has a function `weight` which computes the Hamming weight of any (base 10) integer. That makes our job a lot easier! The rest of the code just sums over the integer representation of STDIN, before sending that to `weight`.
```
boolfun::weight(sum(utf8ToInt(scan(,'')))
```
As an added bonus, this code works for UTF-8 as well as ASCII. There are 7 ones in the binary representation of the sum of 高尔夫 (that's *golf* in Mandarin).
A note for those playing along at home: unfortunately, `boolfun` is no longer hosted on CRAN, so if you don't already have it installed you'll have to do it manually with `install.packages("https://cran.r-project.org/src/contrib/Archive/boolfun/boolfun_0.2.8.tar.gz", repos = NULL, type = "source")`, rather than `install.packages(boolfun)`.
If you really don't want to use `boolfun`, you can achieve the same result with only two more bytes:
```
sum(intToBits(sum(utf8ToInt(scan(,''))))==1)
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes
```
ÇObSO
```
**Explanation**
```
Ç # convert to list of ascii values
O # sum
b # convert to binary
SO # sum as a list
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w4dPYlNP&input=YWJjRGVGQWFC)
[Answer]
# Bash + coreutils, ~~43~~ 49 bytes
**Edit:** corrected version based on [manatwork](/users/4198/manatwork)'s comments.
```
od -vAn -tuC|tr '\n ' +|dc -e?2op|grep -o 1|wc -l
```
**Explanation:**
The result is printed on STDOUT, with some warnings given on STDERR which can be ignored.
```
od -vAn -tuC # get the ASCII value for each string character
|tr '\n ' + # replace each whitespace with a plus (in dc, a warning will be
#raised for each consecutive plus)
|dc -e?2op # execute input, calculating the sum, then convert to binary
|grep -o 1|wc -l # count how many ones exist
```
**Run:**
```
echo -n "abcDeFAaB" | ./script.sh 2> /dev/null
```
**Output:**
```
7
```
A similar solution is presented below (51 bytes), that had the potential to be shorter, but with *xxd* I can't concatenate multiple flags and also *dc* only understands upper case hex letters.
```
xxd -c1 -u -p|tr \\n +|dc -e16i?2op|grep -o 1|wc -l
```
[Answer]
# Java 7,~~80~~,76 bytes
*Thanks to kevin for saving **4 bytes***
```
int f(char[]a){int s=0,c=0;for(char i:a)s+=i;for(;s>0;s&=s-1,c++);return c;}
```
# Ungolfed
```
int f(char[]a){
int s=0,c=0;
for(char i:a)
s+=i;
for(;s>0;s&=s-1,c++);
return c;
}
```
[Answer]
# PHP, ~~79~~ 76 bytes
```
foreach(str_split($argv[1])as$c)$s+=ord($c);echo substr_count(decbin($s),1);
```
[Test online](http://sandbox.onlinephpfunctions.com/code/aae09eeaf196a2b6535735607873c498dda0c0d6)
Ungolfed testing code:
```
$argv[1] = 'abcDeFAaB';
foreach(str_split($argv[1]) as $c){
$s += ord($c);
}
echo substr_count(decbin($s),1);
```
[Test online](http://sandbox.onlinephpfunctions.com/code/8aa06c5a54488e9c0785fe9fce94021b6a65cc70)
[Answer]
## R, 98 bytes
Was interested in how difficult this would be in R. Turns out you have to do a lot of conversions back and forth (in this solution at least) but I'm sure there should be a shortcut, especially if using packages (can't access any here at work).
```
sum(as.integer(rev(intToBits(sum(strtoi(sapply(strsplit(readline(),"")[[1]],charToRaw),16L)))))^2)
```
Could add an explanation if someone is interested.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 34 bytes
```
01\
(?\i:@+$0
?!\:2%:}-2,r+$:
n;\~
```
[Try it online!](http://fish.tryitonline.net/#code=MDFcCig_XGk6QCskMAo_IVw6MiU6fS0yLHIrJDoKbjtcfg&input=YWJjRGVGQWFC)
[Answer]
# Haskell, 47 bytes
```
g 0=0;g n=mod n 2+g(div n 2)
g.sum.map fromEnum
```
[Answer]
# Perl, 36 bytes
Includes +1 for `-p`
Run with input string ***without newline*** on STDIN:
```
echo -n abcDeFAaB | strsum.pl; echo
```
`strsum.pl`:
```
#!/usr/bin/perl -p
$_=unpack"%b*",pack N,unpack"%32W*"
```
If the sum of the ASCII values fits in a 16-bit integer you can leave out the `32` and gain 2 more bytes.
[Answer]
## Julia, 56 Bytes
```
f(s)=length(filter(i->i=='1',bin(sum(map(Int,[s...])))))
```
Convert to ascii value, sum up, filter for 1s, take length of result
[Answer]
## Common Lisp, 53
```
(lambda(s)(logcount(reduce'+(map'list'char-code s))))
```
[Answer]
## JavaScript ES6, ~~80~~ ~~78~~ 71 Bytes
```
g=
s=>[...s].map(c=>r+=c.charCodeAt(),r=0)|r.toString(2).split`1`.length-1
;
console.log(g.toString().length); // 71
console.log(g('abcDeFAaB')) // 7
```
Saved 7 Bytes thanks to @BassdropCumberwubwubwub
### Breakdown
```
[...s] // Split string into array of chars
.map(c=>r+=c.charCodeAt(),r=0) // Sum up ASCII values
|
r.toString(2) // Convert to binary (represented as string)
.split`1`.length-1 // Count occurences of 1
```
[Answer]
# PHP, 73 bytes
```
<?=substr_count(decbin(array_sum(array_map(ord,str_split($_GET[s])))),1);
```
save to file, call in browser with `<scriptpath>?s=<string>`
or
```
<?=substr_count(decbin(array_sum(array_map(ord,str_split($argv[1])))),1);
```
save to file, run with `php <scriptpath> <string>`
---
To run without a file, replace `<?=` with `echo<space>` in the second version
and run with `php -r '<code>' <string>`.
[Answer]
# C#, 51 50 bytes
```
s=>Convert.ToString(s.Sum(x=>x),2).Count(x=>x>48);
```
can be used like this:
```
Func<string, int> f=s=>Convert.ToString(s.Sum(x=>x),2).Count(x=>x>48);
f("abcDeFAaB") // == 7
```
would be so much shorter if Int32.ToString() had a to binary flag.
Edit: saved one byte by converting '0' to int
[Answer]
## Javascript (ES6), ~~72~~ 70 bytes
Saved 2 bytes thanks to ETHproductions:
```
f=
(s,p=([c,...d])=>c?c.charCodeAt()+p(d):0,q=n=>n&&n%2+q(n>>1))=>q(p(s))
;
console.log(f('abcDeFAaB'));
```
**Explanation:**
```
(s, //Input string
p=([c,...d])=>c?c.charCodeAt()+p(d):0, //Recursive method to sum up the ASCII values
q=n=>n&&n%2+q(n>>1) //Recursive method to count 1s in the binary form
)=>q(p(s))
```
---
**Previous solution (72 bytes):**
```
(s,p=([c,...d])=>c?c.charCodeAt()+p(d):0,q=n=>n&&(n&1)+q(n>>1))=>q(p(s))
```
[Answer]
# Pyth, 8 bytes
```
ssM.BsCM
```
[Try it online!](http://pyth.herokuapp.com/?code=ssM.BsCM&input=%22abcDeFAaB%22&debug=0)
Explanation:
```
CM (M)ap ordinals(C) over input
s (s)um
.B Binary string
sM map cast to integer
s sum
```
[Answer]
## Mathematica, ~~53~~ 37 bytes
not the best solution but hey...built-in's ftw
Shortened. Thanks to Martin Ender
```
DigitCount[Tr@ToCharacterCode@#,2,1]&
```
] |
[Question]
[
*This is the robbers' thread. The cops' thread is [here](https://codegolf.stackexchange.com/q/154741/61563).*
Your challenge is to take an uncracked submission from the cops' thread and try to find the original unredacted program. Please comment on the cop's submission when you've cracked their code.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), [Jo King](https://codegolf.stackexchange.com/a/154824/69059)
```
>>>>>+>,[>++++++[-<-------->]<+>,]<[-[█<█<]++++++++++<]>[-]>>██[>█>>█>]+[<]<<[<]>█<<+>>[>]█>[>]█+[<]<<[<]>-█>]>>[->]<[-[[<]<]++++++++++<]>[-]>[<█]>]>[>]<[[█]<]<<<<<[<]<<██>>[>]<█[->+<]<█>>[>]<[-[[<]<]++++++++++<]>███>[<<]>[[[>]>████[<]<[-[[<]<]++++++++++<]>[-]>[█<]>]>[>]<[[-]>+[>]<-<[<]<]+<<<<<[<]>[[>]+[[>]>]>[>]>[-<+>]<[<]<[>+[<]>>-<<<<<[[<]<]>>███████>[[█]>]<]<[[<]<]<[█]>]>>>[[>]<->>]]>[[>]>]<<[[[█]<]<]<<<[█]<<█>>>[>]█[-[[<]<]++++++++++<]>>[[>]+[------->++<]>.+.+++++.[---->+<]>+++.>>]>[>]+[------->++<]>++.++.---------.++++.--------.
>>>>>+>,[>++++++[-<-------->]<+>,]<[-[[<]<]++++++++++<]>[-]>>[[[>]>>[>]+[<]<<[<]>[<<+>>[>]>>[>]<+[<]<<[<]>-]>]>>[->]<[-[[<]<]++++++++++<]>[-]>[<<]>]>[>]<[[-]<]<<<<<[<]<<[>>>[>]<[[->+<]<]>>[>]<[-[[<]<]++++++++++<]>[-]>[<<]>[[[>]>[>]+[<]<[-[[<]<]++++++++++<]>[-]>[<<]>]>[>]<[[-]>+[>]<-<[<]<]+<<<<<[<]>[[>]+[[>]>]>[>]>[-<+>]<[<]<[>+[<]>>-<<<<<[[<]<]>>[[-]+>]>[[>]>]<]<[[<]<]<[<]>]>>>[[>]<->>]]>[[>]>]<<[[[-]<]<]<<<[<]<<]>>>[>]<[-[[<]<]++++++++++<]>>[[>]+[------->++<]>.+.+++++.[---->+<]>+++.>>]>[>]+[------->++<]>++.++.---------.++++.--------.
```
[Try it online!](https://tio.run/##jVFBCgJBDHtQnWHRa8lHSg8qCCJ4EHz/2HS2Kx4Ue9jdpkmmmT09jtf75Xm@jQGWYGeQLGva1oJrDFytmamry1bqsOaAmYEvuJChxoGGCoXrexACYrT96hhisii06CnVVMcDKBxC8dr@tJoL1n7/HgvhV9NJrhVg6UPDpIYyknqy4vbIQJtkW/cLL8EUgmHmIM2ccfIYwDdKMGZsr9iOHznXlep/Jdal57jbxAJih7qHD7KQ3OuHt1RubR9jvyyHFw "brainfuck – Try It Online")
This implements the sieve of Eratosthenes.
The initial `>>>>>+>,[>++++++[-<-------->]<+>,]` inputs each digit as an character code and subtracts 47 to put it in the range 1-10. This allows a cell value of 0 to denote spacing between numbers. The `+>` near the beginning of this section forces the number to be at least two digits, which will be important soon.
Next, and one of the first things I figured out, is the section `<[-[[<]<]++++++++++<]>[-]>`. This appears several times in the code, each with different patterns of redaction, but it was not hard to guess that all of those instances were probably the same code. This code requires three zeros to the left of the decimal number on the tape, and its effect is to decrement the number. The last iteration of the loop will put the value 10 two cells left of the number, but the `[-]` cleans it up.
If the decimal number was 0, there is no extraneous 10 created, and the cell zeroed by `[-]` is the most significant digit. The tape head is then at the second-most significant digit (which is why at least two digits are necessary). Most instances of this snippet are immediately followed by `[<<]>`, which places the head on a nonzero cell in normal conditions and a zero cell if the original decimal number was zero. It seems that in this program, the decimal representation of `n-1` is used to denote `n`, so that decrementing to `0` is caught instead of decrementing to `-1`.
The next part puts the numbers from n-1 (n) down to 0 (1) on the tape:
```
>[ until the number reaches zero:
[ for each digit:
[>]>>[>]+[<]<<[<]> create a placeholder for the next copy
[ while the original value of the digit is nonzero:
<<+ add 1 to copy two cells left (to keep one copy)
>>[>]>>[>]<+ go to new copy and increment that cell
[<]<<[<]>- go back to original digit and decrement
] (this is effectively the same as [<+>>+<-] but with the cells at variable locations)
>] next digit
>>[->] cancel the placeholder 1s that were used for the new copy
<[-[[<]<]++++++++++<]>[-]>[<<]> decrement
]
>[>]<[[-]<] clean up the trash 10s on the tape while ending at a known location relative to the last number
```
Now, these numbers are all on the tape with two zero cells separating them. `<<<<<[<]<<` puts us at the final cell of the penultimate number on the tape, which is where we will be in every iteration of the loop. The loop terminates when all numbers except the original have been handled.
At the start of the loop, we move the current number (last one still on the tape) one cell right to have room to decrement, and then go ahead and decrement:
```
[>>>[>]<[[->+<]<]>>[>]<[-[[<]<]++++++++++<]>[-]>[<<]>
```
If this decrement didn't underflow, we proceed to convert the number to unary:
```
[[[>]>[>]+[<]<[-[[<]<]++++++++++<]>[-]>[<<]>]
```
Note that this snipped has an unclosed `[`. As a result, the rest of this loop is skipped if the number was 0 (representing 1). After converting to unary, we clear out the leftover 10s, dragging the unary representation with us to the left:
```
>[>]<[[-]>+[>]<-<[<]<]+
```
I didn't notice until just now writing this, but the `+` at the end of this snippet is separated from the unary representation by a single 0. It is also a part of the unary representation: the sequence `1011...11` will represent 0 mod k. The following `<<<<<[<]>` puts us at the beginning of the number `k+1`, starting a new loop.
The inner loop here "marks" every number on the tape with a 1 on the cell immediately right, and uses the unary representation as a clock to determine which numbers are multiples of `k`.
```
[
[>]+ mark the current decimal number
[[>]>] move to end of decimal part of tape
>[>] move to 0 in middle of unary "clock"
>[-<+>] move the following 1 to the left if possible
<[<]< if a 1 was moved this will bring us back to a zero before the start of this "clock";
otherwise the looped move command doesn't move us at all and we are at the final 1
[ if there was no gap (happens every kth iteration):
>+[<]>>- reset to original position
<<<<<[[<]<]>> go to number that was just marked
[[-]+>] replace digits with 0s (cell value 1)
>[[>]>]< go back to where we would be without this conditional
]
<[[<]<]<[<]> return to first unmarked number
]
```
The `[[-]+>]` in that section was the last part I figured out. Before that, I assumed the program was just doing trial divisions, but I couldn't see where the result was used.
This loop ends two cells left of the far left number, and `>>>[[>]<->>]]` removes the markers placed on the tape and gets us to the end of the tape again. After that `>[[>]>]<<[[[-]<]<]` removes either the unary clock or, if this entire segment was skipped, the leftover 10s. The loop is set to its starting condition with `<<<[<]<<]`.
After this is just reading whether the input number was replaced by 1 at any point:
```
>>>[>]<[-[[<]<]++++++++++<]>> do the check
[[>]+[------->++<]>.+.+++++.[---->+<]>+++.>>] conditionally print "not "
>[>]+[------->++<]>++.++.---------.++++.--------. unconditionally print "prime"
```
Fortunately, the actual output was not redacted at all.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/)
Cracks [this answer](https://codegolf.stackexchange.com/a/154745/69850).
```
f[x_]:=(p=ToString@Boole@PrimeQ@x;StringMatchQ[p&@@Infinity,RegularExpression@"(\
\n{}\b+, )?1"])
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/19DiystuiI@1spW49G0DiAKyQ8uKcrMS4fwiETWED2@iSXJGYHRyDKeeWmZeZkllTpBqemlOYlFrhUFRanFxZn5eQ5KQOkYKK6G0to6CnCtSrGaXFqaXHD3FdjC3ObglJ@fk@oQUJSZmxroUIFqe4GagwM@WzViuGLyqmtjkoB2adobgmzhApqUVxKdFm1oYBgbi8QzQuEZA3n//wMA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Brain-Flak, MegaTom](https://codegolf.stackexchange.com/a/154817/69059)
```
(({████){██[████)█>(({}))<>}<>{}███{}((██({}))█████{}]██)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})██[██()██(()█[()]██{}██}{}<>{})
(({})<>){([[]]{})<>(({}))<>}<>{}{}{{}(([]({}))[({}[{}])])({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})}([][()])((){[()](<{}>)}{}<>{})
```
[Try it online!](https://tio.run/##JYwxDoAwDAO/4wxsjFU/EmUoAxICMbBaeXsxQalSy2dne8ZxL/s1zjkBprVuhHtE6bL0Z@tMDRPwKNO1nRkWJgX1lONf4McgoiZTT5eUlSOaulAQMH4CjdmtUsJzri8 "Brain-Flak – Try It Online")
This program performs trial divisions from n-2 down to 1, then outputs 1 if and only if this terminated with the factor 1.
[Answer]
# [8086 DOS COM by Joshua](https://codegolf.stackexchange.com/a/154868/55934)
`xxd` representation, because of encodings and null bytes and other scary stuffs:
```
00000000: 31c0 b90a 0031 dbbe 8100 ac3c 0d74 3c3c 1....1.....<.t<<
00000010: 2075 f7ac 3c0d 7410 2c30 7c2f 3c09 7f2b u..<.t.,0|/<..+
00000020: 93f7 e193 01c3 ebeb 83fb 027c 19c6 0653 ...........|...S
00000030: 0159 b902 0039 d974 1289 d831 d2f7 f109 .Y...9.t...1....
00000040: d274 0341 ebef c606 5301 4eb4 09ba 5301 .t.A....S.N...S.
00000050: cd21 c341 0d0a 24 .!.A..$
```
First disassembled the cop manually, then assembled using yasm. Some bytes have been corrupted by the conerter Joshua used, but I've just treated them like redacted bytes. I'm 99.72% certain about their actual content. It shouldn't take long to fix it if I'm wrong, though. Enjoy:
```
; A COM file is just a 16-bit flat binary
; loaded at 0x100 in some segment by DOS
org 0x100
bits 16
; Unsurprisingly, we start by converting
; the commandline string to a number. During
; the conversion, SI is a pointer to the
; string, CX is the base, and BX holds the
; partial result
parse_input:
; We'll read the input character by character
; into AL, but we need the resulting digit as
; a 16-bit number. Therefore, initialise AX to
; zero.
xor ax, ax
mov cx, 10
xor bx, bx
; When a DOS program is loaded, it's preceded
; in memory by the Program Segment Prefix,
; which holds the commandline arguments at
; offset 0x81, terminated by a carriage return
mov si, 0x81
.skip_prog_name:
; Load a character and move the pointer
lodsb
; If we find the terminator here, the program
; was not given any arguments.
cmp al, 13
je finish
cmp al, ' '
jne .skip_prog_name
.input_loop:
lodsb
cmp al, 13
je got_input
; If the ASCII value of the character is less
; than the one of '0', error out. Adjust the
; value in AL so that it holds the digit
; itself. This exploits the fact that the
; comparison instruction is just a subtraction
; that throws away the actual result.
sub al, '0'
jl finish
; If we have a value larger than 9, this
; character wasn't a digit.
cmp al, 9
jg finish
; Multiply the intermediate result by 10 and
; add the new digit to it.
xchg ax, bx
mul cx
xchg ax, bx
add bx, ax
jmp .input_loop
got_input:
; The loop below would go haywire when given a
; zero or a one, so make them a special case.
cmp bx, 2
jl composite
; Patch the output string to say that it's
; prime
mov byte[outstr], 'Y'
; BX = number being checked
; CX = loop counter, potential divisor of BX
mov cx, 2
.loop:
; If CX = BX, we looked everywhere and couldn't
; find a divisor, therefore the number is prime
cmp cx, bx
je finish
; DIV takes DX:AX as a 32-bit number for the
; dividend. We don't want nor need the extra
; precision, so we set DX to 0.
mov ax, bx
xor dx, dx
div cx
; DX now contains the remainder. To check if
; it's 0, we perform some noop operation, that
; happens to set the flags appropriately. AND
; and OR are commonly used for this purpose.
; Because of what's presumably a bug in the
; encoder used by Joshua, I do not yet know
; which for certain. However, I can make an
; educated guess. All other instances of the
; bug happened with a codepoint below 32.
; Moreover, no other bytes from that range
; occur in the code. Because an AND would be
; encoded as an exclamation mark, while OR -
; - as a tab, I am highly confident that Joshua
; used an OR.
or dx, dx
jz composite
; Increment the counter and loop again!
inc cx
jmp .loop
composite:
mov byte[outstr], 'N'
finish:
mov ah, 9
mov dx, outstr
int 0x21
ret
outstr:
db 'A', 13, 10, '$'
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly)
Cracks [this](https://codegolf.stackexchange.com/a/154759/69850) answer.
```
25██26█966836897364918299█0█1█65849159233270█02█837903312854349029387313█ị██v
```
```
250126,9668368973649182994001,658491592332700020837903312854349029387313ṖịØJv
```
[Try it online!](https://tio.run/##DcexDYNQDATQhSjOPn9/3wrsQYOokTJD@iirRCmZhEmcvO7t23E8un3APBdlFrM0mSErlwKwJUf9O@SkTwCO4hRI8xrBEFysSeP9ed3f5/Vez@6OHw "Jelly – Try It Online")
---
Explanation:
Looking at `ị` and `v`, I think of building a list of numbers, **`ị`**ndex it into some list and evaluate it.
The "trivial" way of checking primality in Jelly is `ÆP`, so (if it can cracks the submission):
* The list to be indexed to must contains `Æ` and `P`.
* The list of indices must be congruent modulo `256` with `[14, 81]`.
So... the list at the start of the program congruent to `[14, 81, 49]` mod 256 ([TIO](https://tio.run/##DcexEYAwDAPAaehSyJbtWAPRcCxAyViswyKB7/7Yz/NayxPmNVTVrNZkhaxdCsBGZf9NOekTgKM5BdK8MxiCiz1p3N77WesD)) and `Ṗ` pops the last element.
[Answer]
# sh + coreutils
Cracks [this answer](https://codegolf.stackexchange.com/a/154806/69850).
```
e█ec█s█ █c "██████WyAkKHNoIC1jICJg█WNobyBabUZqZEc5eWZIUnlJQ2█2SnlBblhHNG5m██JoYVd3Z0t6SjhkMk1nTFhjSyB8YmFzZTY0IC1kYCIpIC1lcSAxIF0K█b█se6███d`"
```
```
exec sh -c "`echo WyAkKHNoIC1jICJgZWNobyBabUZqZEc5eWZIUnlJQ2M2SnlBblhHNG5mSFJoYVd3Z0t6SjhkMk1nTFhjSyB8YmFzZTY0IC1kYCIpIC1lcSAxIF0K|base64 -d`"
```
No [Try it online!](https://tio.run/##DczBDoIgAADQX2He3dDSdVUXiU63hubgpCCLCUrNDtr6d/L0bo8Pq3JOblKAVQFfAK@XQlnQ7Yku89riLJhwVjxZV1u@pwNv2ZtdRSQ7htvFFPewCsliUm5UXt@imaDC0sd4YvATk0npSgdLg9RE9vRCZ/RlDYXHqWmGX4dGkGTDCJY/PqwyPgN/7D3nAvgH) this time because of some [issues](https://chat.stackexchange.com/transcript/message/42681132#42681132). However you can use [jdoodle](https://www.jdoodle.com/test-bash-shell-script-online).
Returns by exit code. `0` (success) for prime, `1` (error) for composite.
The actual command executed is
```
factor|tr ':' '\n'|tail +2|wc -w
```
### How to crack
1. Look at the code, recognize Base64.
2. Learn how to use `base64` command.
3. Know that `+` is a valid base64 character.
4. [Try to decode](https://tio.run/##DczBDoIgAADQX@nO2tDSdVUWii62hsbgBupigFqzQ/Tz5OndnlabiVGrbcrPh@MYIw@Fa2u6EpRYgpon4HTVoVS6l295HbKJS9IvvrmnIGWLL7U3Na2yGYBmFY/xJOEnZ9a4m0uWDhvLQnkRM/7JTsD9dAKR164fWPElGLZ/).
5. Apply the wrapper `sh -c "`echo ...|base64 -d`"` back to the [original program](https://tio.run/##S0oszvj/P7UiNVmhOENBN1lBKSE1OSNfIbzSMdvbwy/f09kwy9PZK/3RtI5wv/ykSqfEpNCowijXZNPU8CjP0Lwcr0AjoJxRcF6OU1JOhoefu2kukA9EXvmRYSnGUQYlZsFZGdm@2YZ5IW4ZWcGVThaRuW5VUSGRBkCzsyOdPQuAdE5ysGOFp5uBd01SYnGqmYmCbkqC0v//AA).
6. [Generate nested base64 from commands](https://tio.run/##PcpBCoMwEEbhq/wEIQYJqJQuvIpTyDhGUihKTcBN7p6KFHePjzdxDKV4CRvUCKrqGGAFpMhdWNXCKU8c/fNh8A/YmRwpA@u/6PBStx9tKQtL2vacduhBQ9Oqc@L3B02fDzmXHw).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 86 bytes, [Stewie Griffin](https://codegolf.stackexchange.com/a/154807/67312).
```
@(x)eval([(str2num(cell2mat([cellstr(reshape('0█1███1█0█0█00',████))])')█'█')','(x)'])
@(x)eval([(str2num(cell2mat([cellstr(reshape('04141113040800',2,[]))])')+'e')','(x)'])
```
[Try it online!](https://tio.run/##Fcw9CoAwDEDhq7glwVLS2sFF8B6lQ5GIQ/1Ba/H2VbfHN7x9yrFInZuh0VrXER@SEhN6vPJpt3vFSVKya8zo//oUT7mWeAgCO@OMMR077plBWeUDUSCgFgQIFHw7CFRntFRf "Octave – Try It Online")
This was a fun one! I struggled with this for a good couple of days.
The first clue was recognizing `eval([...,'(x)'])` as a construction creating a call to the `isprime` function, as concatenation of `ints` and `char` will implicitly convert the array to `char`, so the `...` needed to be either `isprime` or an array that had the ASCII values of `isprime`, `[105, 115, 112, 114, 105, 109, 101]`.
The rest of it was just slogging through documentation to figure out that `reshape` can take one unknown dimension with `[]`, although I suppose I could have done `reshape(...,2, 7)` at the same byte count.
Using `+'e'` (101) instead of `+'d'` (100) was a nice touch that threw me for another few minutes until I noticed the last digits (unobfuscated) were `00` rather than `01`, and with that it was easy.
[Answer]
# [JavaScript](https://codegolf.stackexchange.com/a/154805/31203)
```
x=>{if(x<4)return(!0);for(y=x>>>Math.log10(p=████;--y-1;(p=x/y%1)████if(██&&(███))break████return(███)}
x=>{if(x<4)return(!0);for(y=x>>>Math.log10(p=2-1);--y-1;(p=x/y%1)){;;if(!p&&(1<2))break;;;}return(!!p)}
```
[Try it online!](https://tio.run/##lY5NDoIwFIT3ngIWkr5FhaK7R7mBh0Bttf5AU9DQEPaewAN6kdpEROLO5C1eZibfzLG4FfXWKN3QWqudMJeqPAnrJHdx3PK8U5K02QqMaK6mJGECKCtDLG/zPF8XzWFxrvYsIZo/H/fxkFJLGXq1je2cwdTzwPcTRWQUATZGFKdpbmj8RvpZEPy1KKUMfpdAh@gBofbtLEuHXkTsP7xQQ@@0UWVDJGFLAPcC "JavaScript (SpiderMonkey) – Try It Online")
I somehow doubt this is exactly what you had in mind, but it works.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), [Esolanging fruit](https://codegolf.stackexchange.com/a/154952/76162)
```
:1@v>~~:?1n;█$-1<█?=2:}*{█@:$@:
```
to
```
:1@v>~~:?1n;
$-1</?=2:}*{%@:$@:
```
[Try it online!](https://tio.run/##S8sszvj/38rQocyurs7K3jDPmktF19BG397WyKpWq1rVwUrFwer///@6ZUYGBsYA "><> – Try It Online")
Clever use of redacting a newline confused me for a bit. Doesn't seem to work for 1 or 2 though.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), [Magic Octopus Urn](https://codegolf.stackexchange.com/a/155241/64121)
```
class X{public static void main(String[]args){System.out.println(new String(████████[Integer.parseInt(args[0])]).matches("█████████████")?███);}}
class X{public static void main(String[]args){System.out.println(new String(new char[Integer.parseInt(args[0])]).matches(".?|(..+?)\\1+")?0:1);}}
```
[Try it online!](https://tio.run/##JYvBDoIwEER/peHUhthAvOmBs2cvJsBhLRsoQmm6C8Yg315RTzNv8qaHBQ6TR9c3jxjNAETitvr5PlgjiIH3WCbbiBGsk1cO1rVlDaEltV5fxDjqaWbt950HJx0@xV/6VdNBKC@OscWgPQTCHeT3XWa1qpUegU2HJBNdvKXWaaGqKk8TVWSnXJ23LcaYHz8 "Java (OpenJDK 8) – Try It Online")
The code is taken from [RosettaCode](http://rosettacode.org/wiki/Primality_by_trial_division#By_Regular_Expression) and [explained on SO](https://stackoverflow.com/a/2795112/6346504).
[Answer]
# [Python 3](https://docs.python.org/3/), 44 bytes, [osuka\_](https://codegolf.stackexchange.com/a/155795/71546)
```
p=lambda x,i=2:i>=x or(x%i and p(x,i+1))or 0
```
[Try it online!](https://tio.run/##Dco5DoAgEEDR3lNMY8JECtCOBO8yBpdJdFhigadHml@8/PS9V5SlteRverZAUDX72fHqK8Si6shAEiCp7pNFjAVMO3ozsEAhOXdljUE3QCosr8q6zxmx/Q "Python 3 – Try It Online")
Does not work when x<2. The `or 0` can be replaced with `>0{2 spaces}` or even 4 spaces
For the x<2 problem, since `i>=x` must be put at the front (otherwise there will be an infinite loop), and the `i>=x` returns true immediately when x<2, so I think that's no fix with that.
[Answer]
# [M, dylnan](https://codegolf.stackexchange.com/a/155723/61563)
```
ÆPø“;;“»VOḣ2S⁵++3Ọ;”Pv
```
This probably wasn't the intended solution.
[Try it online!](https://tio.run/##y/3//3BbwOEdjxrmWFsDiUO7w/wf7lhsFPyocau2tvHD3T1A0bkBZf///zcCAA "M – Try It Online")
### How it works
`ÆP` is the built-in primality test.
`ø` beings a new, niladic chain. Since the previous return value (the result of `ÆP`) goes out of scope, this prints it implicitly.
`“;;“»` evaluates to the list of strings `["< Aalst" ""]`, and `V` tries to eval them. `s` tries to split its argument into chunks of length **0**, which causes the M interpreter to crash, suppressing further output.
[Answer]
# [Pyth, Mr. Xcoder](https://codegolf.stackexchange.com/a/154747/61563)
```
q]tQ #aQ{*MyP
```
[Answer]
# [Python 3](https://docs.python.org/3/), [user71546](https://codegolf.stackexchange.com/a/154744/69059)
```
import random
def f(z):
if z<4:return z>>1
d,s,n,e,c=~-z,0,z,0,50
while not d&1:d//=2;s+=1
while n>0:n//=2;e+=1
random.seed()
while c>0:
a=0
while a<2or a>z-1:
a,b=0,e
while b>0:a=a*2+random.randint(0,1);b-=1
x,r=pow(a,d,z),~-s
if ~-x and x!=~-z:
while r>0:
x,r=pow(x,2,z),~-r
if not ~-x:return 0
elif x==~-z:break
else:return 0
c-=1
else:return 1
```
[Try it online!](https://tio.run/##TZDPcoMgEMbvPMX20pFmbcA0PZjgu6DgxEkCDtqJ9eCrW8DYeGBYfvt9@4f2t79Yc5jn5t5a14OTRtk7UbqGOhlpTqCpYTx/5U73P87AWBScgMIODWqsxJSOyDCcIyPwuDQ3Dcb2oN55rvZ7kZ26neD/mYLlJlId6dLts9NaJXQVVV5EAKTwBZ9InjPrQBZjykMKJJaCoQ7hIii9Rwr5ke2eJcPVmD5hyOmpTEMzGNCJ1j4SiQpHilPaeejXm9IBvByGt7BO/qrqlklezgGzxeki9t6wq/ev38Mi1zefGUSsVjotryTCTm9lVRxqS/ncujBznWSUkjU@fvPNK2PsQOn8Bw "Python 3 – Try It Online")
] |
[Question]
[
Literally! [April 6th is National Teflon Day](http://www.nationaldaycalendar.com/days-2/national-teflon-day-april-6/), which is celebrated with Teflon-coated pans (what we will be making). So, given a positive integer `n`, create a Teflon pan. The "pan" section of the pan is an octagon with each of its sides consisting of `n` characters, which will vary depending on which side it is **except for the sides using the character `{` or `}`. Those sides will have a character length of one always.** If `n` is 1:
```
_
/ \
{ }
\_/
```
As you can see, each side consists of one character (either `{`, `}`, `/`, `\`, or `_`). If `n` is 2:
```
__
/ \
/ \
{ }
\ /
\__/
```
The handle will be created with `n+3` `=`'s and end with a zero (`0`).
---
If `n` is one:
```
_
/ \
{ }====0
\_/
```
`n` is 2:
```
__
/ \
/ \
{ }=====0
\ /
\__/
```
`n` is 3:
```
___
/ \
/ \
/ \
{ }======0
\ /
\ /
\___/
```
If `n` is 4:
```
____
/ \
/ \
/ \
/ \
{ }=======0
\ /
\ /
\ /
\____/
```
**Rules and Criterion**
* No loopholes allowed
* Handle comes out the right hand side (the side made of the `}` character)
* Input is a positive integer
* If the side does not consist of either `{` or `}` (not the left or right side), they will consist of `n` respective characters:
```
_
/ \
Left side { } Right side
\_/
```
* Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~41~~ ~~38~~ ~~36~~ ~~30~~ 28 bytes
*Thanks to @Emigna for helping to save two bytes, thanks to @ASCII-only for saving six bytes, and thanks to @Neil for saving another two bytes!*
```
Nη↙η↑←×_η↖η↗{↗η×_η↓↘η}×=⁺³η0
```
[Try it online!](https://tio.run/nexus/charcoal#@/9@z7pz2x@1TTu3/f2e5Y/aJpzbHv@obSYQndte/aht8qO2GSCZtY/aJh6eDpYDkrWHpz9q3HVo87nttu/3bDD4/98IAA)
**Explanation:**
```
Nη // Take the size of the pan as input.
↙η // Draw a line of η '\'s going down to the left.
↑←×_η // Move one step up and print η underscores to the left.
↖η↗{↗η // Print a line of η '\'s going up to the left.
// Then move one step north-east and print '{'.
// Then print a line of η '/'s going up to the right.
×_η↓ // Print '_' η times and move one step down.
↘η} // Draw a line of η '\'s going down to the right, then print '}'.
×=⁺³η // Print '=' η+3 times.
0 // Print '0'
```
[Answer]
## JavaScript (ES6), 171 bytes
```
f=
n=>(r=s=>s[0][0].repeat(n-1)+s)` `+r`_
`+r` `.replace(/ /g," $'/$' $`$`$`\\\n")+`{`+r` `+r` `+r` }`+r`====0`+r` `.replace(/ /g,"\n $`\\$` $'$'$'/").replace(/ +\/$/,r`_/`)
```
```
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>
```
The whole ~~pizza~~ pan is very repetitious so the r function (designed as a tagged template literal) repeats the first character of its input n times. This handles the top and middle and lines of the pan. The rest is repeated by replacing a string of blanks; the `$`` and `$'` subsitutions automatically correspond to increasing and decreasing numbers of blanks thus positioning the `/` and `\` appropriately. Finally the `_`s are filled in on the last line as it's subtly different from the second line in that respect.
[Answer]
## JavaScript + HTML, 575 bytes (451 bytes only JS) 376 bytes (482 bytes only JS)
```
y=document,y.y=y.getElementById,a=(b,c)=>{w="";for(z=0;z<b;z++)w+=c;return w},d=_=>{n=Number(y.y("n").value);s="";u=" ";j="<br>",m="\\",o="/";for(i=-2;i<=2*n;i++)-2==i?s+=a(n+1,u)+a(n,"_")+j:i<n-1?s+=a(n-i-1,u)+o+a(2*(i+1)+n,u)+m+j:i==n-1?s+="{"+a(3*n,u)+"}"+a(n+3,"=")+"0"+j:i+1==2*n?s+=a(n,u)+m+a(n,"_")+o:i+1<2*n&&(s+=a(i-n+1,u)+m+a(5*n-2*i-2,u)+o+j);y.y("p").innerHTML=s};
```
```
<input type="number" id='n'><button onclick='d()'>Do</button><p id='p' style='font-family:monospace;'></p>
```
Not a complicated approach: several string concatenations using conditions for the five different parts of the pan: the uppermost, lowermost and middle lines and the upper and lower halves.
I shortened as much as I could, but it was the limit with this method.
EDIT: it wasn't - additionally golfed by @programmer5000
[Answer]
# PHP, 174 bytes
```
echo($p=str_pad)("",-$i=-1-$n=$argn),$p(_,$n,_);for(;$i++<$n;)echo$p("
",1+$a=abs($i)),$i?$p("\/"[$i<0],1+$n*3-$a*2,"_ "[$i<$n])."\/"[$i>0]:$p("{",$n*3).$p("} ",5+$n,"="). 0;
```
Takes input from STDIN; run with `-nR` or [test it online](http://sandbox.onlinephpfunctions.com/code/3b943b22c2c03cb06242e5601516fd57135894c8).
**breakdown**
```
// first line
echo($p=str_pad)("",-$i=-1-$n=$argn),$p(_,$n,_);
// loop $i from -$n to $n
for(;$i++<$n;)echo
$p("\n",1+$a=abs($i)), // 1. left padding
$i? // if not middle line:
$p("\/"[$i<0],1+$n*3-$a*2,"_ "[$i<$n]) // 2. left edge and inner padding
."\/"[$i>0] // 3. right edge
: // else:
$p("{",$n*3) // 2. left edge and inner padding
.$p(" }",5+$n,"=") // 3. right edge
. 0 // 4. knob
;
```
[Answer]
# Python 3, 196 bytes
```
n=int(input())
p=print
s=' '
def m(i,f,b,c=s):p(s*(n-i)+f+c*(n+2*i)+b)
p(s*n+s+'_'*n)
for i in range(n):m(i,*'/\\')
p('{'+s*n*3+'}'+'='*(n+3)+'0')
for i in range(n-1,0,-1):m(i,*'\\/')
m(0,*'\\/_')
```
I used a few variables to shorten the code, but it's mostly straightforward. Here's a longer, more readable version:
```
n = int(input())
def middle_part(i, first_slash, second_slash, middle_char=' '):
print(' ' * (n-i) + first_slash + middle_char * (n + 2*i) + second_slash)
print(' ' * (n+1) + '_' * n)
for i in range(n):
middle_part(i, '/', '\\')
print('{' + ' ' * n*3 + '}' + '=' * (n+3) + '0')
for i in range(n-1, 0, -1):
middle_part(i, '\\', '/')
middle_part(0, '\\', '/', middle_char='_')
```
**Edit:** changed to read n from stdin, 181 → 196 bytes
[Answer]
# [Python 2](https://docs.python.org/2/), ~~180~~ 178 bytes
```
s,i=' ',input();R=range(i)
print'\n'.join([s+s*i+'_'*i]+[s*(i-a)+'/'+s*(i+a*2)+'\\'for a in R]+['{'+s*i*3+'}'+'='*(i+3)+'0']+[s*(i-c)+'\\'+'_ '[c>0]*(i+c*2)+'/'for c in R[::-1]])
```
[Try it online!](https://tio.run/nexus/python2#NcyxDoIwEMbx3afo9rU9EBQnDD4Ea2lM06g5h0IoTsZnxxbjdpf732@NBXcQKDhMr0Wqc9/NLjxuktVumjksGAL2z5GDNJGiZsIVmi2ZqCWXThEqUJ7J6WPahgH3cRZOcBB9yvDOZ9YN4QNCh5w2KazxR/zvLckCxl9qmxO/adWG@Q0zbVserFXrevoC "Python 2 – TIO Nexus")
[Answer]
# Python 2.7, ~~194~~ ~~195~~ ~~191~~ ~~187~~ 185 bytes
```
n=input();s=' ';a='\\';z='/'
def m(f,b,i,c=s):print(n-i)*s+f+c*(n+2*i)+b
m(s,s,0,'_')
for i in range(n):m(z,a,i)
print'{'+s*n*3+'}'+'='*(n+3)+'0';exec"m(a,z,i);i-=1;"*(n-1);m(a,z,0,'_')
```
[Try it online!](https://tio.run/nexus/python2#JY1BDoIwEEX3nKJxM512iCA7mt6ExBRszSwYCcXEYDw7omz/e3l/E88yPReNLntQ4IKHrgO3ejhDcYtJjTpRT0yDz9hOM8uipWQ02SY7GC32YhhtX4w6U6aK4ApYpMesWLGoOcg9asF21CsFYiz@CXiDzUZMY@EDFjz8Qg1aqMDFVxxOow607rrj0tfutOOyRnesx8e2NV8)
Open to edit suggestions to make it smaller. :)
Edit 1: +1 byte - Credits to [ElPedro](https://codegolf.stackexchange.com/users/56555/elpedro) for pointing out an error in the code, which made it 1 byte longer.
Edit 2: -4 bytes - Credits to [piyush-ravi](https://codegolf.stackexchange.com/users/67970/piyush-ravi) for removing unneccesary arguments.
Edit 3: -4 bytes - How did I not see that? :P
Edit 4: -2 bytes - Replacing '\n' with ';'
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 165 bytes
```
param($n)($a=' '*$n)+" "+($b='_'*$n);$n..1|%{' '*$_+"/"+' '*($n+2*$i++)+"\"};"{$($a*3)}$('='*($n+3))0";if($n-1){1..($n-1)|%{' '*$_+"\"+' '*($n+2*--$i)+"/"}};"$a\$b/"
```
[Try it online!](https://tio.run/nexus/powershell#TY0xDsMgDEWvElmOwFiQ0nRD3AQpIkMkhkZVV8rZqZMs2Z71/d/vn/zNb407acxRDcoIMgzAGteolvMOuDvnf2M984VhAj5Qavw0WJilkqAFqCgaM1NDreL1MBM9IJRN2Hqq3rmLbrp011mLhY6JJj7MCdcJeu@vPw "PowerShell – TIO Nexus")
Takes input `$n`, sets `$a` to a bunch of spaces, `$b` to a bunch of underscores, and string concatenates that with a space. That's left on the pipeline.
Loops from `$n` down to `1`. If `$n=1`, this will only execute once. Each iteration we do a string concatenation of spaces, a `/`, more spaces with counter `$i`, and a `\`. Those are all left on the pipeline.
Then comes the middle part with the handle, which *coincidentally* has `$a*3` spaces in the middle, and `$n+3` `=` signs, then a `0`. That's left on the pipeline.
If `$n` is bigger than `1`, then `$n-1` is truthy so we enter the conditional, where we loop the other direction to form the bottom of the pan. If `$n=1`, then we don't need this portion due to how the lines work. Those are all left on the pipeline. We finish off with the spaces and underlines with the `$a\$b/` bottom of the pan.
All those strings from the pipeline are sent via implicit `Write-Output` that prints them with newlines in between elements.
[Answer]
# JavaScript + HTML - 346 bytes
**JavaScript - 314 bytes, HTML - 32 bytes**
```
function o(a){a=parseInt(a),String.prototype.r=String.prototype.repeat;c=console.log,d=" ".r(a),e="_".r(a);c(" "+d+e);for(f=a-1,g=a;f>=0;f--,g+=2)c(" ".r(f+1)+"/"+" ".r(g)+"\\");c("{ }=0".replace(" "," ".r(3*a)).replace("=","=".r(a)));for(f=0,g=3*a;f<a-1;f++,g-=2)c(" ".r(f+1)+"\\"+" ".r(g-2)+"/");c(d+"\\"+e+"/")}
```
```
<input id=n onkeyup=o(n.value)>
```
# Un-golfed
```
function o(sides) {
String.prototype.r = String.prototype.repeat;
var middle = '{ }=0',
log = console.log,
ss = ' '.r(sides),
u = '_'.r(sides),
sides = parseInt(sides);
// top
log(' ' + ss + u);
// top mid
for (var i = sides - 1, j = sides; i >= 0; i--, j += 2) {
log(' '.r(i + 1) + '/' + ' '.r(j) + '\\');
}
// mid
log('{ }=0'.replace(' ', ' '.r(sides * 3)).replace('=', '='.r(sides)));
// bottom mid
for (var i = 0, j = sides * 3; i < sides - 1; i++, j -= 2) {
log(' '.r(i + 1) + '\\' + ' '.r(j - 2) + '/');
}
// bottom
log(ss + '\\' + u + '/');
}
```
```
<input id="n" onkeyup="o(n.value)">
```
[Answer]
# C, 249 bytes
```
o(c,a){for(;a--;)putchar(c);}s;p(n){o(32,n+1);o(95,n);o(10,1);for(s=0;s<n;s++)o(32,n-s),o(47,1),o(32,n+s*2),o(92,1),o(10,1);o(123,1);o(32,n*3);o(125,1);o(61,3+n);o(48,1);o(10,1);for(s=n-1;s>-1;s--)o(32,n-s),o(92,1),o(s?32:95,n+s*2),o(47,1),o(10,1);}
```
[Try it online](https://tio.run/nexus/c-gcc#VU/BbsMgDD3jr0CVJpkGpALNts7t9iO7oEzVOMxEoTtF@fYMRiNtFz/z/J6fWSHhoIOar2lCCsaQGr9vw2eYcFC0ZBqR1ZzQO82dVZTw1GuuaA@6vKstXw6Uz0y561RTmqx0wuNTUei7N@9d7U@ucc1d0PnWVNHeN6pv1KPVvvvNOj7f1X8y2VjKr7UY8y92i8hv3r3Ua7fs7Z62ZQH4CpFRwQwi8k1GAlFWS4wXSzKe@1LKj0CUuRinIrnibgwsHz7eeadlVFQH2BDEAgus6w8)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 69 bytes
```
›\_?*꘍,(nε\/꘍₴nd⁰+\\꘍,)\{₴3*\}꘍₴3+\=*0+,(n›\\꘍₴nε‹d+n›⁰=` _`$i$*₴\/,)
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%80%BA%5C_%3F*%EA%98%8D%2C%28n%CE%B5%5C%2F%EA%98%8D%E2%82%B4nd%E2%81%B0%2B%5C%5C%EA%98%8D%2C%29%5C%7B%E2%82%B43*%5C%7D%EA%98%8D%E2%82%B43%2B%5C%3D*0%2B%2C%28n%E2%80%BA%5C%5C%EA%98%8D%E2%82%B4n%CE%B5%E2%80%B9d%2Bn%E2%80%BA%E2%81%B0%3D%60%20_%60%24i%24*%E2%82%B4%5C%2F%2C%29&inputs=4&header=&footer=)
Unfortunate bytecount...
] |
[Question]
[
I'd like to see you create code (in any programming language) that output working BF (Brain\*\*\*k) code. Your program have a single character input on stdin. The input should be one digit ("0", "1", "2", "3", "4", "5", "6", "7", "8" or "9").
Your code should output BF-code that when interpreted with a normal BF-interpreter outputs a 5\*5 ascii version of the digit. The generated BF-code should not accept any input. The resulting output from the generated BF-code should be exactly this:
Input: '0'
Output BF-code that when interpreted generates the following output:
```
.---.
| /|
| / |
|/ |
'---'
```
Input: '1'
Output BF-code that when interpreted generates the following output:
```
.
/|
|
|
'
```
Input: '2'
Output BF-code that when interpreted generates the following output:
```
.---.
|
.---'
|
'---'
```
Input: '3'
Output BF-code that when interpreted generates the following output:
```
.---.
|
---|
|
'---'
```
Input: '4'
Output BF-code that when interpreted generates the following output:
```
. .
| |
'---|
|
'
```
Input: '5'
Output BF-code that when interpreted generates the following output:
```
.---
|
'---.
|
'---'
```
Input: '6'
Output BF-code that when interpreted generates the following output:
```
.---
|
|---.
| |
'---'
```
Input: '7'
Output BF-code that when interpreted generates the following output:
```
----.
/
/
/
'
```
Input: '8'
Output BF-code that when interpreted generates the following output:
```
.---.
| |
|---|
| |
'---'
```
Input: '9'
Output BF-code that when interpreted generates the following output:
```
.---.
| |
'---|
|
'---'
```
The output from your code must be 10 different BF sourcecodes, one for each digit you input. Your program should not output all 10 BF in one run, it must ask for a digit and output BF code for that and only that ascii representation.
The BF-code requirements:
* cell size: 8bit unsigned.
* Overflow is undefined.
* Array size: Max 30000 bytes (not circled)
* It can contain other characters than [],.+-<>, but they should all be ignored. It is only - the standard BF code without any extensions that counts.
* The EOF return 0
* Linefeed is chr(10)
The winning answer will be the one that scores that lowest code using this formula:
```
your code in number of bytes * 5 + sum of the 10 generated BF codes
```
So keep in mind that you need to generate GOLF'd BF-code to score better.
**Edit/Add (2011-08-25): You may omit or supply trailing spaces, as long as the digits displays the ASCII representation on a 80 column output, so the limit is 80 chars rows. Honor to the answers to generates exactly 5\*5 output for all digits.**
[Answer]
## BrainFuck (Score : 13073, BF : ~~2299~~ 2286, BF (generated) : 1643)
```
,>++++++++[<------>->>>+++++++++++>+++++++++++>+++++>++++++++>++++++++>++++++>++++++<<<<<<<<<]
>>>+++>+++++>+++>---->-->--->--<<<<........<<.>>>>>.<.<<.>>.<<....>>.<<......>>.<<......>>.<<.
..............>>.<<......>>.<<.....>.......<<.>>>.<<..>>..>..<.>...<.<<....>>.>.<.>.<<<<<<<<+<
[>-]>[>>>>>>....>>>.<<.>>...<<<.>>>.<<<..>>>.<<....>>.<<<...>>>..<<....>>.<<<.>>>.<<<....>>>.<
<....>>.<<<...>>>.<<....>>.<<<....>>>.<<...>>.<<<....>>>.<<....>>.<<.>>.<<<....>>>..<<...>>.<<
<....>>>.<<......>>.<<<...>>>...<<...>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>>>>.....>>>
.<<.>>.<<<..>>>.<<.....>>.<<<.>>>.<<<....>>>.<<.>>.<<...>>.<<<....>>>.<<.>>.<<...>>.<<<....>>>
.<<.>>.<<.....>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>>>>....>>>.<<.>>...<<<.>>>.<<<..>>
>.<<.>>....<<...>>.<<<....>>>.<<..>>.<<.>>...<<...>>.<<<......>>>.<<....>>.<<<....>>>.<<......
>>.<<<...>>>...<<...>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>>>>....>>>.<<.>>...<<<.>>>.<
<<..>>>.<<.>>....<<...>>.<<<....>>>.<<.>>.<<..>>...<<.>>.<<<....>>>.<<.>>....<<...>>.<<<....>>
>.<<......>>.<<<...>>>...<<...>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>>>>....>>>.<<<.>>>
...<<.>>.<<<..>>>.<<....>>.<<<...>>>...<<...>>.<<<....>>>.<<......>>.<<<...>>>...<<.>>.<<<....
>>>.<<.>>....<<...>>.<<<....>>>.<<.>>....<<.....>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>
>>>....>>>.<<.>>...<<<...>>>.<<....>>.<<<....>>>.<<......>>.<<<...>>>...<<<.>>>.<<<..>>>.<<.>>
....<<...>>.<<<....>>>.<<......>>.<<<...>>>...<<...>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[
>>>>>>....>>>.<<.>>...<<<...>>>.<<....>>.<<<....>>>.<<....>>.<<<.>>>...<<<.>>>.<<<..>>>.<<....
>>.<<<...>>>...<<...>>.<<<....>>>.<<......>>.<<<...>>>...<<...>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>
[-]<<[>-]>[>>>>>>...>>>....<<<.>>>.<<<..>>>.<<.>>...<<....>>.<<<.....>>>.<<.>>..<<....>>.<<<..
...>>>.<<.>>.<<....>>.<<<.....>>>.<<......>>.<<<<<<<<<->>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>>>>...
.>>>.<<.>>...<<<.>>>.<<<..>>>.<<....>>.<<<...>>>...<<...>>.<<<....>>>.<<....>>.<<<.>>>...<<.>>
.<<<....>>>.<<....>>.<<<...>>>...<<...>>.<<<....>>>.<<......>>.<<<...>>>...<<...>>.<<<<<<<<<->
>+<]>-[+<<<->[-]+>[-]<<[>-]>[>>>>>>....>>>.<<.>>...<<<.>>>.<<<..>>>.<<....>>.<<<...>>>...<<...
>>.<<<....>>>.<<......>>.<<<...>>>...<<.>>.<<<....>>>.<<.>>....<<...>>.<<<....>>>.<<......>>.<
<<...>>>...<<...>>.>]]]]]]]]]]
```
(FYI : over 90% of above code is generated by JS code to generate part of BrainFuck code generating part of BrainFuck code generating ASCII art.)
This program gets one ASCII character ('0'~'9') and print the BF code generating the ASCII art.
Generated BF codes :
```
#0
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<.<<.>>>>.<<<..>>>>.<.<<<<.>>>>.<<<.>>>>.<<<<.>>>.<<<<.>>>>.>.<<<<..>>>.<<<<.>>>>>>.<<<...>>>.
#1
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<<.>.<<.>>>>>.<.<<<<.>.>>>.<<<<.>.>>>.<<<<.>.>>>>>.
#2
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<.<<.>....>>>.<<<<.>>.>...>>>.<<<<<<.>>>>.<<<<.>>>>>>.<<<...>>>.
#3
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<.<<.>....>>>.<<<<.>.>>...>.<<<<.>....>>>.<<<<.>>>>>>.<<<...>>>.
#4
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.<...>.<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>.<<<<.>....>>>.<<<<.>....>>>>>.
#5
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<<<.>>>>.<<<<.>>>>>>.<<<...<.<<.>....>>>.<<<<.>>>>>>.<<<...>>>.
#6
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<<<.>>>>.<<<<.>>>>.<...<.<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>>>.
#7
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<....<.<<.>...>>>>.<<<<<.>..>>>>.<<<<<.>.>>>>.<<<<<.>>>>>>.
#8
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<.<<.>>>>.<<<...>>>.<<<<.>>>>.<...>.<<<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>>>.
#9
++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<<.>...<.<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>.<<<<.>....>>>.<<<<.>>>>>>.<<<...>>>.
```
Example output for 7 :
```
----.
/
/
/
'
```
[Answer]
## JavaScript (JS 455 \* 5 = 2275, BF = 3505, score = 5780)
The generated code builds a character table as it produces its ASCII art output to save thousands of plus/minus signs overall. Output is placed into the text box in a prompt window so that it can be copied and pasted into a BF interpreter. The consecutive spaces in this program must remain verbatim for it to work correctly; hopefully, posting the code here will work correctly. (Note: The JS code requires ES5 or JavaScript 1.6 support to work properly.)
```
M=prompt;S="3cb80kh77j31f4031m10g251p64d1064a20ionle3292032510".substr(5*M(A=[]),5).replace(/./g,function(a){return"'---'0 |0| |0.---.0|0'---|0.---0 |0|/ |0|---|0|---.0| / |0| /|0'---.0'0.---'0. .0/|0----.0 '0 .0 /0 ---|0 /0 /0 '".split(i=j=0)[parseInt(a,26)]+"\n"});for(O="";i<S.length;O+=".")D=A.indexOf(C=S.charCodeAt(i)),i++&&(d=-j+(j=D<0?A.length:D),O+=Array(d>0?1+d:1-d).join(d>0?">":"<")),D<0&&(O+=Array((A[j]=C)+1).join("+"));M(0,O)
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), (BF 1534 \* 5 = 7670, Generated BF = 1293, score = 8963)
```
+[-[>+<<]>-]>-.>>--[<+>++++++]<.>++++++>-[<+>---]<.<++..<.>--.>.<<--.>>++.<<++.>++.>.<<..>--..
........<.>..<.>++..>--.<<--.>--.<++.>......>++.<++...<.>..>--.<<--.>--.<++.>++..>++.<<.>--...
.>--.<<--.>........<++.>++.>++.<<--...>--.<<<<,+++>-[<->-----]+<[>-]>[->>>+++.-.+...---.+++.<.
>.<++..>.<.>..<--..>---.+++.<++.>.<--..>.<++..>.<.>.<--..>.<++..>.<--.>.<..>.<++..>.<--.>.<++.
.>..<--.>.<..>.<.>.<++..>-..+...<--..>.<<]<+<-[>-]>[->>++..>+++.<--..>.<.>.<++.>---.+++.<.>.<-
-..>.<++...>.<--.>.<..>.<++...>.<--.>.<..>.<++...>.<--....>.<<]<+<-[>-]>[->>>+++.-.+...---.+++
.<.>.<++...>....<--.>.<..>.<++.>.-.+...<--..>.<++.>.<..>.<--..>.<.>.<++..>...<--..>.<<]<+<-[>-
]>[->>>+++.-.+...---.+++.<.>.<++...>....<--.>.<..>.<++...>.<--..>-.+...<++.>.<--..>.<++...>...
.<--.>.<..>.<.>.<++..>...<--..>.<<]<+<-[>-]>[->>>+++.<++..>...<--..>.<.>.<++..>.<.>...<--.>.<.
.>.<.>.<++..>-.+...<.>.<--..>.<++...>....<--.>.<..>.<++...>....<--....>.<<]<+<-[>-]>[->>>+++.-
.+...<.>.<++..>.<--..>.<.>.<++..>...---.+++.<--.>.<++...>....<--.>.<..>.<.>.<++..>-.+...<--..>
.<<]<+<-[>-]>[->>>+++.-.+...<.>.<++..>.<--..>.<++..>.<--.>...---.+++.<.>.<++..>.<.>...<--.>.<.
.>.<.>.<++..>-.+...<--..>.<<]<+<-[>-]>[->>>++.+....---.+++.<.>.<++...>...<--..>---.+++.<.>.<++
...>..<--..>.<.>.<++...>.<--..>.<.>.<.>.<<]<+<-[>-]>[->>>+++.-.+...---.+++.<.>.<++..>.<.>...<-
-.>.<..>.<++..>.<--.>-.+...<++.>.<--..>.<++..>.<.>...<--.>.<..>.<.>.<++..>...<--..>.<<]<+<-[>-
]>[>>>+++.-.+...---.+++.<.>.<++..>.<.>...<--.>.<..>.<.>.<++..>-.+...<.>.<--..>.<++...>....<--.
>.<..>.<.>.<++..>...<--..>.<<]
```
Code here includes newlines for readability.
[Try it online!](https://tio.run/##nVPLasQwDPwgVboXhH7E5LAtFEphD4X9/qwkO47fbdaExJFG0owsf/zevu9fj8@ffYeAQYB5E9SHRBADg4CvjSntxK2IqCYGIFIPKpyY7aMo3enLNmYkd@elaH9ZpDlilG0c78tzGCCie5gHe6Ej@YnJhQ4OjnNUBDG/JRloMlQIcDDNAcXoAyFZbfWQ/RkHZyOJvOWS7I0y3VbCGkvsUG@JP5U/mzWB9yBl4o2BMTNNPYDsT3FS8S5YDGjMTTQquWpObHyTTRK6oHF4a9IePRF6ueqZP1XvjqgP@y@PDtQMx@wkj2Fes6itf50B19PUysjNOidtoRtXs7YuWg70/Nq8Vtbdk3NvLmLpa/vRtOjilI0UFKJnU7YUPlF9ncjlIRtT2Pf3Jw "brainfuck – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), (Python 403 \* 5 = 2015, BF = 1293, score = 3308)
```
def x(i,b=5):
a,i='',int(i,36)
while i:a+='<.>+-[]'[i%b];i//=b
return a
print(x("7vphe27p2e4voq0o43gf5n8vsm4zd01qsofpvobsaq",7)+x("20lzrlf5b9k8qf1kctot9x3et4id5d m1z11k8bye0q57c8owb 1houe4amyy3wu36tk00qz2 8o5y0gy19cx8cjsnjazb08seuk 5ypddsh5laklx2qj6sb2lxpu8cd aqma6z756nnzjalhd4fy5 aqma6z757wy8nhuw7uobp 4lbo9eqzud1ykb67x5f chin248p22jlefn4j0ottq13q chin248our8z29faeze411sy6".split()[int(input())]))
```
[Try it online!](https://tio.run/##PZDLjtsgAEX3@QoUqUqspDMGg41nJv2RKAsweIxNeNgQG34@TSu1u6tzdTbHpTBYUz2fQvZgO6ozv5DiYwfYWV0Oh7My4cWqutiBdVBaAvXBTpfD19uv08/r7XBVP/jtU72/X/gOzDLE2QC2c/MfbTvum4cbJGockvhhfWlx9d0TQx/LHWdRQr/Y3j0sX5jfn5vi9DJQqfOse8LbifoeTl2wod0qGbASRIA7zBBOlCdZetJ01K4cwMFGidk9pWqNVR2msvQZAWpJKr8TbLuNduNiRpZ5SRcZJ0CSE2IZiGaT3pAf64UjvblIOwGYv7M6N6Q2Jo9MDwL3ifynzZqoGeLaRMsdwJrbVvocBUwTr5uN9KAblEGYOoRGLXuDx9KG4GHl/z02zjSjtmcySwzhkur92@K0Csfi@re2cfG1i1tRPJ/Vbw "Python 3 – Try It Online")
[Answer]
## [GTB](http://timtechsoftware.com/gtb "GTB") (GTB, 888 \* 5 = 4440, BF = 1643, score = 6083)
Yes, this does run on your calculator!
```
~"++++++++[->+>++++>++++++>++++++>+++++++++++++++>++++++>+++++<<<<<<<]>++>>-->--->++++>->-<<<"→_`A@A=0~"<.>...<.<<.>>>>.<<<..>>>>.<.<<<<.>>>>.<<<.>>>>.<<<<.>>>.<<<<.>>>>.>.<<<<..>>>.<<<<.>>>>>>.<<<...>>>.@A=1~"<<.>.<<.>>>>>.<.<<<<.>.>>>.<<<<.>.>>>.<<<<.>.>>>>>.@A=2~"<.>...<.<<.>....>>>.<<<<.>>.>...>>>.<<<<<<.>>>>.<<<<.>>>>>>.<<<...>>>.@A=3~"<.>...<.<<.>....>>>.<<<<.>.>>...>.<<<<.>....>>>.<<<<.>>>>>>.<<<...>>>.@A=4~"<.<...>.<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>.<<<<.>....>>>.<<<<.>....>>>>>.@A=5"<.>...<<<.>>>>.<<<<.>>>>>>.<<<...<.<<.>....>>>.<<<<.>>>>>>.<<<...>>>.@A=6~"<.>...<<<.>>>>.<<<<.>>>>.<...<.<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>>>.@A=7~"....<.<<.>...>>>>.<<<<<.>..>>>>.<<<<<.>.>>>>.<<<<<.>>>>>>.@A=8~"<.>...<.<<.>>>>.<<<...>>>.<<<<.>>>>.<...>.<<<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>>>.@A=9~"<.>...<.<<.>>>>.<<<...>>>.<<<<.>>>>>>.<<<...>.<<<<.>....>>>.<<<<.>>>>>>.<<<...>>>.
```
[Answer]
## [Spoon](http://esolangs.org/wiki/Spoon) (Spoon, 7430 \* 5 = 37150, BF = 1643, score = 38793)
```
00101100101111111100100011000000000000000000010000010010010111111111110101111111111101011111010111111110101111111101011111101011111101101101101101101101101101100110100100101110101111101011101000000000000001000000001000000000001000000001101101101100101000101000101000101000101000101000101000101001101100101001001001001001000101001100101001101100101001001000101001101100101000101000101000101001001000101001101100101000101000101000101000101000101001001000101001101100101000101000101000101000101000101001001000101001101100101000101000101000101000101000101000101000101000101000101000101000101000101000101000101001001000101001101100101000101000101000101000101000101001001000101001101100101000101000101000101000101001000101000101000101000101000101000101000101001101100101001001001000101001101100101000101001001000101000101001000101000101001100101001000101000101000101001100101001101100101000101000101000101001001000101001000101001100101001000101001101101101101101101101110110010001000000110100010001001001001001001000101000101000101000101001001001000101001101100101001001000101000101000101001101101100101001001001000101001101101100101000101001001001000101001101100101000101000101000101001001000101001101101100101000101000101001001001000101000101001101100101000101000101000101001001000101001101101100101001001001000101001101101100101000101000101000101001001001000101001101100101000101000101000101001001000101001101101100101000101000101001001001000101001101100101000101000101000101001001000101001101101100101000101000101000101001001001000101001101100101000101000101001001000101001101101100101000101000101000101001001001000101001101100101000101000101000101001001000101001101100101001001000101001101101100101000101000101000101001001001000101000101001101100101000101000101001001000101001101101100101000101000101000101001001001000101001101100101000101000101000101000101000101001001000101001101101100101000101000101001001001000101000101000101001101100101000101000101001001000101001101101101101101101101101100001001010110011010000001001011011011000010001000000011101000100000001101101100100010000001101000100010010010010010010001010001010001010001010001010010010010001010011011001010010010001010011011011001010001010010010010001010011011001010001010001010001010001010010010001010011011011001010010010010001010011011011001010001010001010001010010010010001010011011001010010010001010011011001010001010001010010010001010011011011001010001010001010001010010010010001010011011001010010010001010011011001010001010001010010010001010011011011001010001010001010001010010010010001010011011001010010010001010011011001010001010001010001010001010010010001010011011011011011011011011011000010010101100110100000010010110110110000100010000000111010001000000011011011001000100000011010001000100100100100100100010100010100010100010100100100100010100110110010100100100010100010100010100110110110010100100100100010100110110110010100010100100100100010100110110010100100100010100010100010100010100110110010100010100010100100100010100110110110010100010100010100010100100100100010100110110010100010100100100010100110110010100100100010100010100010100110110010100010100010100100100010100110110110010100010100010100010100010100010100100100100010100110110010100010100010100010100100100010100110110110010100010100010100010100100100100010100110110010100010100010100010100010100010100100100010100110110110010100010100010100100100100010100010100010100110110010100010100010100100100010100110110110110110110110110110000100101011001101000000100101101101100001000100000001110100010000000110110110010001000000110100010001001001001001001000101000101000101000101001001001000101001101100101001001000101000101000101001101101100101001001001000101001101101100101000101001001001000101001101100101001001000101000101000101000101001101100101000101000101001001000101001101101100101000101000101000101001001001000101001101100101001001000101001101100101000101001001000101000101000101001101100101001001000101001101101100101000101000101000101001001001000101001101100101001001000101000101000101000101001101100101000101000101001001000101001101101100101000101000101000101001001001000101001101100101000101000101000101000101000101001001000101001101101100101000101000101001001001000101000101000101001101100101000101000101001001000101001101101101101101101101101100001001010110011010000001001011011011000010001000000011101000100000001101101100100010000001101000100010010010010010010001010001010001010001010010010010001010011011011001010010010010001010001010001010011011001010010010001010011011011001010001010010010010001010011011001010001010001010001010010010001010011011011001010001010001010010010010001010001010001010011011001010001010001010010010001010011011011001010001010001010001010010010010001010011011001010001010001010001010001010001010010010001010011011011001010001010001010010010010001010001010001010011011001010010010001010011011011001010001010001010001010010010010001010011011001010010010001010001010001010001010011011001010001010001010010010001010011011011001010001010001010001010010010010001010011011001010010010001010001010001010001010011011001010001010001010001010001010010010001010011011011011011011011011011000010010101100110100000010010110110110000100010000000111010001000000011011011001000100000011010001000100100100100100100010100010100010100010100100100100010100110110010100100100010100010100010100110110110010100010100010100100100100010100110110010100010100010100010100100100010100110110110010100010100010100010100100100100010100110110010100010100010100010100010100010100100100010100110110110010100010100010100100100100010100010100010100110110110010100100100100010100110110110010100010100100100100010100110110010100100100010100010100010100010100110110010100010100010100100100010100110110110010100010100010100010100100100100010100110110010100010100010100010100010100010100100100010100110110110010100010100010100100100100010100010100010100110110010100010100010100100100010100110110110110110110110110110000100101011001101000000100101101101100001000100000001110100010000000110110110010001000000110100010001001001001001001000101000101000101000101001001001000101001101100101001001000101000101000101001101101100101000101000101001001001000101001101100101000101000101000101001001000101001101101100101000101000101000101001001001000101001101100101000101000101000101001001000101001101101100101001001001000101000101000101001101101100101001001001000101001101101100101000101001001001000101001101100101000101000101000101001001000101001101101100101000101000101001001001000101000101000101001101100101000101000101001001000101001101101100101000101000101000101001001001000101001101100101000101000101000101000101000101001001000101001101101100101000101000101001001001000101000101000101001101100101000101000101001001000101001101101101101101101101101100001001010110011010000001001011011011000010001000000101001000000101100010000100100101001010010000011001001000000000101101100100000001011000001010010000101100001000000101000000000001000000000110000000000110000100001011000101000000000110001100000011000100011001100110000000000000001001000000110000010001001100011010001101101011001100000000100001000000100000011000000001000000110010011011001100001000000010110100000000001010000000000000000000000010010100101000000001011000000001011010000100010100000001010001000000101001000100000000000000110010010000110000010000000001000000101000110010000010000000000000000101000001101101000000000001001000000011011010000011
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score = 5×160 + 1305 = 2105
```
ị“¢N=⁵ḌƤṢ§UḌ“uçCçṗ³;nƝ“nƁǽ)|⁸jɠ9Ṁ“¡h6ịḃ⁸ƊFdṚ⁻ŀȥ“¤aijṇḃṚĠ;“&⁻3Ṃb½Ḟ\Ẇ“ÑṭȤv.Ṡ\ð⁸“¿bSumƒ¬ẹṡḢ€“¡][ḶṠ.\Ä£ḣ⁼“nƁµ[ḷSLBḃ$ŀ’ṃ“.<>”“ṁƙµ²ƭ^%n5ḅEœçs_ĊṚç⁽ƁhFġ⁷Ƈɱ’ṃ“+><-][”¤;
```
[Try it online!](https://tio.run/##PY9BS8NAFIT/jAoi5iIqktqDYk/ipXhqqlgUSqm5SAXBQ7ZVA9WLepCKSpJGcmlBLbG7rUHYTZb2Z7z9I/FFwdvyzbyZ2dpRvX6WpjC@VtYT93bWFQmB3kgfmMeDXXwib4hgUwTAHvhAN@UzElMSYfNo/lwRWps6a8Cs7N6trmAS0BZi2S4cAntUZJxYk9dM9Q/EBR8As9GASuzoSOfQsASsWeER0BcDRlcIxS2w/sQ/1YA5hnjDtOz@u1JsHMs73oMRA@YC9VSz91tbLgH9RK9mYEMXaFeRr7@VPERpWNzewM6ZBEd2gLVQ0nJ5ZWU/AUZkh4f8Q/b3Zs1loJdbyb0ITvbjNm4UgSKRJNVC7CoylPb0/T9hIZ9bLJcwhPt6mqarPw "Jelly – Try It Online")
The digit is to be put in a command-line argument.
## Explanation
```
ị“...’ṃ“.<>”“...’ṃ“+><-][”¤; Main monadic link
ị Index in
“...’ a list of 10 integers compressed in base 250
ṃ Base decompression using characters
“.<>” [base 3] 1->'.', 2->'<', 0->'>'
; Prepend
¤ (
“...’ an integer compressed in base 250
ṃ base decompressed using characters
“+><-][” [base 6] 1->'+', ..., 0->'['
¤ )
```
## Produced brainfuck programs
```
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...>.<<<.<.<..<.>>.>.<.<.<.>.>.>.<.<<.>..>.>.>.>...<.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+<<<<<.>>>>>.<<<.<<<.>>.>.<<.>.>.<<.>.>.<<.>>>.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...>.<<<.<<....>.>.>>>.<...<.<.<.>.>.>...<.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...>.<<<.<<....>.>.<<.>>>>...<<<.>.<<....>.>.>.>...<.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<<<<<...>>>>>.<<<.<.<...>.>.>.>...<<<.>.<<....>.>.<<....>>>.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...<<.<.>.>.>...>.<<<.<<....>.>.>.>...<.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...<<.<.>.<.>>>...>.<<<.<.<...>.>.>.>...<.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+<....>.<<<.<<...<.>>>.<<..<.>>>.<<.<.>>>.>.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...>.<<<.<.<...>.>.<.>>>...<<<.>.<.<...>.>.>.>...<.
+++[>+++++<-]>[>+++>++>++++++++>+>+++>+++>+++<<<<<<<-]>++>++>++++>----->------>>+.<...>.<<<.<.<...>.>.>.>...<<<.>.<<....>.>.>.>...<.
```
## Explanation of brainfuck programs
The common part adds the number 3, then multiplies by 5 to get 15, then multiplies by some constants and adds some constants to get all the characters used in the ASCII art. (I used a Python program to determine 15 as the optimal number.)
The differing parts simply walk around the characters and print them. The order of the characters was chosen to make the walk as short as possible.
] |
[Question]
[
The [Len(language,encoding)](https://esolangs.org/wiki/Len(language,encoding)) family of languages is a variety of [Lenguage](https://esolangs.org/wiki/Lenguage) derivatives. To encode a program into a Len language, you replace every character with its representation in a certain encoding, then turn that into a giant integer.
Your challenge is to write a function or program that encodes your language into a Len language. However, you can make up your own encoding, and it only needs to encompass the subset of your language that is used in your program. **But, you must have at least two distinct bytes in your program.**
# Rules
Your program must be able to take itself as input.
You can just output a number as the length of the compiled program, to avoid memory problems.
**Your program must be reversible.**
# Scoring
Your score is the result of your program run on itself. You're trying to minimise this.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7845~~ ~~535~~ 34
```
BC
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fyRmEAQ "05AB1E – Try It Online")
This converts the input from base `2` according to 05AB1E's codepage. `B` is mapped to 11 and `C` to 12. Digits larger or equal to the base are allowed and *"overflow"* into the next digit.
This can be inverted by iterating the digits of the output in reverse:
```
[D0Q# "loop while TOS != 0"\
2‰` "divmod 10"\
i "if the last digit was 1:"\
'Bˆ5- "append ö to global array and subtract 5 from TOS"\
ë "else:"\
'Cˆ6- "append T to global array and subtrac 6 from TOS"\
]¯RJ "after the loop: reverse global array and join"\
```
[Try it online!](https://tio.run/##fY89bsJAFIT7nGKyFKmQIIALJBpCRRPx00GkPONns9HCWrsLiI6Ky6RIKg4Ql75FLmLWGEVIkZhyNO97M9pSKLkoZoPGqAYvobROsVtKxZi@TvDYQ0PMH55/D9/vuEhEcrvSEZqlL3GVkDHckqHIOkQykQ47smh2fQhP/fzYqZcpSlNeR8hOcBqJ0iEpkDG0B3nbbkJnaOHQQWz0qizgz7PPvyesLFfEl/wY3BKn94AIbnlvP1/jYcWj2LGpevvZXRjesrH8H/Sh5VrMi6LVPgM "05AB1E – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), 40 bytes, score 0
```
grep -FqxfI $0&&od||od -An<I|tr -c 0-7 8
```
[Try it online!](https://tio.run/##qyrO@G/n@T@9KLVAQdetsCLNU0HFQE0tP6WmJj9FQdcxz8azpqRIQTdZwUDXXMHiP9EqAQ "Zsh – Try It Online")
Encodes itself as 0, and all other programs in some horrendous octal/decimal mishmash. Takes input from a file `I`.
* `grep`: search for a string that matches
+ `F`: exactly (non-regex)
+ `x`: the whole line
+ `fI`: the pattern taken from the `f`ile `I`
+ `q`: do not print the matching string; only exit with success or failure
+ `$0`: this source code file
* `&&od`: if the match succeeds, print `0000000`
* `||`: otherwise:
+ `od -An<I`: encode the input file in octal
+ `|tr -c 0-7 8`: replace all characters except `01234567`s with `8`s (ensures it's a valid number with no leading 0s)
Doesn't support newlines (nor null bytes).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~11 bytes, score 96697523013522~~ 14 bytes, score 10230313233344
```
⭆S⌕´S´⭆´⌕´´´ιι
```
[Try it online!](https://tio.run/##S85ILErOT8z5///R2rb3ezY/6pl6aAuQPrQFyAcSIC4Intt5bicxagA "Charcoal – Try It Online") Explanation: Now uses @AviFS's approach of looking up the possible characters in a table. However, the table itself more than triples the length of the code, which leaves no room to do base conversion, so instead I just output the digits individually as base 10, but fortunately it's still slightly lower than my original score.
[Answer]
# [R](https://www.r-project.org/), ~7.0689\*10^69
```
cat(utf8ToInt(scan(,''))-29,sep='')
```
[Try it online!](https://tio.run/##K/r/PzmxRKO0JM0iJN8zr0SjODkxT0NHXV1TU9fIUqc4tcAWyCZKDQA "R – Try It Online")
Converts the input to ASCII codepoints, subtracts 29, and concatenates all the 2-digit numbers obtained. I chose 29 because the lowest ASCII codepoint I need is 39 (for `'`); this ensures that all the numbers are between 10 and 98. Reversing is thus easy: split into groups of 2 digits, add 29 and convert back to characters.
Works on any string which does not include the characters `!"#$%&`.
A [more naïve implementation](https://tio.run/##K/r/PzmxRKO0JM0iJN8zr0SjODkxT0NHXV1TU6c4tcAWyCCsAAA) would omit the `-29` and use the plain ASCII codepoints; it is easy to convince oneself that this remains reversible even with some 3-digit numbers, but it leads to a score of 9.997\*10^75.
[Answer]
# [Dyalog APL](https://www.dyalog.com/), 2.7370885894231567 \* 10^18
This is the most naive algorithm I could come up with, so I suppose it sets a baseline. Given the structure `{n⊥n|⎕UCS⍵}`, I wrote a script to check the lowest that *n* could be, and 28 is our answer.
That is, the lowest that *n* could be and still yield a unique codepoint for each symbol in the program, when it's unicode is reduced mod *n*.
The program simply takes the unicode codepoint of each symbol, mods it by 28, and then converts it to base 28. It's not very clever or optimized, I challenge you to be less lazy!
```
{28⊥28|⎕UCS⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pAwKO2CcYmCo965yoEp5YoFBSlJmcWZ@bnKWRkpmcolOQrFKemKhQn5xel/k8DKq02snjUtdTIogaoN9Q5@FHv1lqQMUCZNHUscupgg/1LSwpKS6CmAAA)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 16 bytes, score 81040998233
```
`\`\\v\ḟ6\β`vḟ6β
```
[Try it online!](http://lyxal.pythonanywhere.com?flags=&code=%3F%60%3F%5C%60%5C%5Cv%5C%E1%B8%9F7%5C%CE%B2%60v%E1%B8%9F7%CE%B2&inputs=%3F%60%3F%5C%60%5C%5Cv%5C%E1%B8%9F7%5C%CE%B2%60v%E1%B8%9F7%CE%B2&header=&footer=)
There may be better languages to do this, but the idea is simple.
The other answers reduce the codepoints mod *n* where *n* is the smallest number that will yield unique codepoints. But that's rarely an efficient encoding. You usually end up with lots of numbers unused. Eg. your program becomes *[6,3,9,7,2]* rather than *[0,1,2,3,4]*.
This just packs every symbol used into a list, and for each symbol in the program, gets its index in the list. So you're guaranteed to get the lowest numbers you can: *[0..n]*. In addition, the symbols in the list are in the order they appear in the program, because we want the lower numbers to show up first. In every base, *[0,1,2,3]* is a much smaller number than *[3,2,1,0]*. Finally, I used 6 unique symbols, so I converted it to base 6.
**Example execution with `v6ḟ` as input:**
```
# Implicit input -> "v6ḟ"
`\`\\v\ḟ6\β` # This is just the string "`\vḟ6β" [1] -> "v6ḟ", "`\vḟ6β"
vḟ # Vectorized find index in list -> [2,4,3]
6β # Convert list to base 6 -> 99
# Implicit output
```
[1]: Unfortunately for this challenge, non-ASCII characters have an (really cool) encoding scheme in strings. So in order to have them interpreted literally, all the non-ASCII characters in the string are escaped, which adds many orders of magnitude to the score.
[Answer]
# [R](https://www.r-project.org/), 176 bytes, score=0
```
'->a;b=paste0(sQuote(a),a);s=readLines(,1);`if`(s==b,cat(0),cat(utf8ToInt(s)-24,sep=""))'->a;b=paste0(sQuote(a),a);s=readLines(,1);`if`(s==b,cat(0),cat(utf8ToInt(s)-24,sep=""))
```
[Try it online!](https://tio.run/##1ZDBSsNAEIbveYphPWQXttKKBzGsID0JuYgeBTtJJ3Gg3V12JoU@fUwVH8FDT8PMBx//P2XmeGLh7kD27Sy3QnpIPS5bj0pjKmcIYNrt53PbGg@/7HLaGufmevWETRcyitLayuuUlCw6j66RUAj3LUcS6zeu2fGwsxJC5xexXbufMenw8J5eolpxq7t7L5SDWcT/5b26wFV1ofVHrF11A4UyoUI3KegXCygfCUY@ESDseRioUFTIJY0Fj2CHVICjKMaePJhcePFvnHGAsoA86WN1dQ/5azF/Aw "R – Try It Online")
Despite the enormously increased byte-count, this is basically just an extension of [Robin Ryder's approach](https://codegolf.stackexchange.com/a/230013/95126), optimized for the challenge's scoring system instead of for `code-golf`.
We first construct a quine string of the program (`'...'->a;b=paste0(sQuote(a),a)`) in variable `b`, and then check if this is equal to the input (`s=readLines(,1);`if`(s==b,...`). If it is, we output zero (`cat(0)`): that is, we hard-code this particular progam as zero. Otherwise, we use [Robin's approach](https://codegolf.stackexchange.com/a/230013/95126) to output the program's numerical value, which can never be less than `10`.
Valid programs can only use characters with ASCII values 34-123: so, no newlines, and no "`|}~`" characters. The 'empty program' is not valid for this version (it also encodes to zero), but a [slight modification](https://tio.run/##3ZC/asMwEMZ3P8WhDtaBUpLSodS4UDIVvJR2LDSyc3YEsSR050Ce3rVTPPQFOng67vu4P98vjc5fHLv6TPrjyvdMcg6NnbrGCnUhXaEEVe2/X6tKGfj1ZmmvEMd882KLuoyWhbaa34cgpC0aiwWXieyxcp5Ymx0WB9ceNJelUmbarHdoFqW@CVu8lUHap8/w5kUzbh4eDVOcRhDxH0@tNFaWzXb@5XPM7iBRJCtQDwJycgzieoLOXQgsHF3bUiIvEFPoku1BtyGB8yzWN2RAxeT8/IJCsDwZcZDnbKXYlqx/@YVBptAwc5ETAfVRrguu1aLIxh8) can fix this, while keeping a score of zero for this challenge.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes, score 0 bytes
```
“Ṿ;⁾v,;⁾¥ ¤-iⱮḅL{ɗ⁼?ʋ/+1”v,¥
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO/dZP2rcV6YDIg8tVTi0RDfz0cZ1D3e0@lSfnP6ocY/9qW59bcNHDXPLdIDS/8nRBAA "Jelly – Try It Online")
Returns 0 when supplied itself as an input. Otherwise looks up the supplied input in the characters `“Ṿ;⁾v,;⁾¥ ¤-iⱮḅL{ɗ⁼?ʋ/+1”v,¥` and converts back from bijective base 29 before adding 1 (so that an empty input will result in 1 rather than being the same as the encoder itself).
Inspired by [@pxeger’s Zsh answer](https://codegolf.stackexchange.com/a/230016/42248) so be sure to upvote that one too (implementation quite different though).
[Decoder - Try It Online!](https://tio.run/##y0rNyan8//9Rw8yHO5qNLB/u7j7V/XDn7EM77R81zHm4c5/1o8Z9ZTog8tBShUNLdDMfbVz3cEerT/XJ6Y8a99if6tbXNnzUMBessmFOmQ5QFZB7aMn///@NDCzMzQA)
## Explanation
### Main link
```
“Ṿ…”v,¥ | Evaluate this string as a Jelly link with itself paired to the overall link’s argument (the program to encode)
```
### Code run within eval
```
ʋ/ | Reduce using the following:
Ṿ | - Uneval (effectively wraps the string in “”)
;⁾v,;⁾¥ ¤ | - Append "v,¥ " (thus restoring the source for the encoder)
⁼? | - If equal to the original argument (the program to encode):
- | - Then -1
ɗ | - Else:
iⱮ | - Indices of each character of program to encode in the string
ḅ | - Convert from base given by:
L{ | - The length of the string
+1 | Add 1
```
Note the program has a trailing space because of the need to use `⁾` within `“”` which takes a pair of characters.
---
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes, score 7842
```
OḄ
```
[Try it online!](https://tio.run/##y0rNyan8/3DnKmuHhzuaHu7uftS4z//hjhb/Y10Pdy30OLQ05liXyollhycc2u/2cOe0hzu6Hu7uebhz1n@Qov86h9sf7lzrcLjd6eGOHqAOMNvwyH4VLmOjhzu2OSHMO9yu8qhpjTcQR/4HAA "Jelly – Try It Online")
A monadic link that converts to Unicode code points and unbinaries. This is a similar approach as [@ovs’s 05AB1E answer](https://codegolf.stackexchange.com/a/230017/42248) so be sure to upvote that one too!
The TIO link includes a decoder in the header and generates a table of the first 32 possible programs including their decimal representation and the decoded program.
] |
[Question]
[
**This question already has answers here**:
[Find the prime factors](/questions/1979/find-the-prime-factors)
(26 answers)
Closed 10 years ago.
A whole program to find the prime factors of a given number. The number will be given on standard input.
[Answer]
## Bash Shell
**6 Chars**
`factor`
If `rot13` can be [allowed](https://codegolf.stackexchange.com/questions/4/rot-13-transform-standard-input/92#92), i don't see why this one is an issue...I'm sorry but this is very trivial.
[Answer]
## J - 2 characters
```
q:
```
Example:
```
q: 31415
5 61 103
```
[Answer]
## dc, 48 chars
```
[ldp0<x]sp?2sd[[dsrld~0=p]dsxxcld1+sdlrd1<y]dsyx
```
[Answer]
# Ruby - 50 49 47 44 42 chars
```
2.upto(n=gets.to_i){|i|n/=p i while n%i<1}
```
[Answer]
## Perl, 42 chars
```
map{$n/=$_,print$_,$/until$n%$_}2..($n=<>)
```
[Answer]
## Windows PowerShell, 46
Naïve solution.
```
2..($x=+"$input")|%{for(;!($x%$_)){$_;$x/=$_}}
```
[Answer]
## Python: 58
```
n=input()
for i in range(2,n+1):
while n%i<1:print i;n/=i
```
[Answer]
## Python (55)
based on marcog
```
n=input()
i=1
while~-n:
i+=1
while n%i<1:print i;n/=i
```
[Answer]
## Pure Bash Solution (60 characters)
Based on [F.Hauri](https://codegolf.stackexchange.com/users/9424)'s [solution](https://codegolf.stackexchange.com/questions/667/find-prime-factors/13026#13026) (thanks to him):
```
read p;for((i=2;p-1;));do((p%i++||(p/=--i)*0))||echo $i;done
```
[Answer]
## Javascript (54)
```
n=prompt()*1;for(i=2;n>1;n/=n%i?(++i,1):(alert(i),i));
```
[Answer]
# Mathematica, 26 chars
```
#&@@@FactorInteger@Input[]
```
[Answer]
## C (68)
Not the shortest, but I was curious to see how a C solution could compare.
```
d=2;main(n){scanf("%d",&n);for(;n>1;)n%d?++d:printf("%d\n",d,n/=d);}
```
[Answer]
## R, 72 characters
Just for the kicks, an attempt without using any preexisting function to prime-factorize:
```
n=scan(n=1);m=1:n;M=m[!n%%m&!m%in%c(1,n)];M[rowSums(!outer(M,M,`%%`))<2]
```
Ungolfed with explanations:
```
n <- scan(n=1) #Take one number from stdin
m <- 1:n
#Of which of the integers from 1 to n is n a multiple (excluding 1 and himself):
M <- m[!n%%m & !m%in%c(1,n)]
#Trim that list by excluding integers that are multiples of others in the list:
M[rowSums(!outer(M,M,`%%`))<2]
```
NB: Instead of checking if `n%%m==0`, use the fact the `0` coerce as `FALSE` when using `!`.
[Answer]
## 100% Pure [bash](/questions/tagged/bash "show questions tagged 'bash'"): 72 chars
```
read p;for((i=1;p>i++;));do while((p%i<1));do echo $i;((p/=i));done;done
```
or
```
read p;i=1;while((p>i++));do while((p%i<1));do o+=$i\ ;((p/=i));done;done ;echo $o
```
This seem longer, but in replacing `for` by `while`, I could make an overall loop and using `alias` to reduce then code:
```
alias D=done W=while
prime() { W read p;do i=1 o=;W((p>i++));do W((p%i<1));do o+=$i\ ;((p/=i));D;D;echo $o;D;}
unalias D W
```
This way, my (written) code **whith** the loop is 77 char length.
Anyway, the function is memorized with full command names:
```
declare -f prime
prime ()
{
while read p; do
i=1 o=;
while ((p>i++)); do
while ((p%i<1)); do
o+=$i\ ;
((p/=i));
done;
done;
echo $o;
done
}
```
[Answer]
## perl5.10: 36 chars
```
map{$p/=$_,say until$p%$_}2..($p=<>)
```
[Answer]
# Haskell 74 chars
```
s n=f((==0).mod n)[2..n]
main=readLn>>=print.f((==1).length.s).s
f=filter
```
## Example
```
12 -> [2,3]
128 -> [2]
60 -> [2,3,5]
```
[Answer]
# Octave, 17 chars
```
factor(input(''))
```
[Answer]
# Scala, 111 bytes:
```
def f(i:Int,c:Int=2):List[Int]=if(i==c)List(i)else
if(i%c==0)c::f(i/c,c)else f(i,c+1)
f(readInt).mkString(" ")
```
] |
[Question]
[
A port of my other question: [Double Prime Words](https://codegolf.stackexchange.com/questions/210733/double-prime-words)
Consider a word/string of `n` alphanumeric characters with sum of the characters, `s`, using their numeric position in the alphabet (`a=1, B=2, c=3,` etc.) or numeric value (0,1, 2, 3 - 9). Numeric characters should be taken at individual value. (`66` is two `6` characters for a sum of `12`)
A word is a Length-Sum Multiple if and only if `s` is a multiple of `n`, specifically `s/n` is a positive integer `{1,2,3,4...}`. In the case of `s=0`, and `n={0,00,000,...}`, 0 is a multiple of any `n` but it does not yield a positive integer. Hence an input of `{0,00,000,...}` is False.
Input can be any combination of numbers and upper or lower case alphabetic characters, as there is no numeric difference between `a` or `A`. Handling empty input, `n=s=0`, is not required.
Output is any appropriate logical format related to your language. i.e. True or False, T or F, 1 or 0, positive for truthy and 0 for falsy, etc. Specifying what format your output will appear is highly appreciated, but not required. (Output need not include n or s, but I include them below as demonstration and example)
Winning condition: In as few bytes as possible, write a function that is able to determine if a string is a Length-Sum Multiple.
### Examples
```
Input -> Output (n,s)
hello -> False (5, 52)
MuLtIpLe -> False (8, 108)
Junct10n -> False (8, 83)
Order66 -> False (7, 72)
CodeGolf -> False (8, 67)
SUM -> False (3, 53)
ID -> False (2, 13)
25 -> False (2, 7)
0 -> False (1, 0) 0/1 = 0 which is not a positive integer
10 -> False (2, 1)
hello2 -> True (6, 54)
5um -> True (3, 39)
length -> True (6, 66)
Order64 -> True (7, 70)
Covid19 -> True (7, 63)
Word -> True (4, 60)
APPLE -> True (5, 50)
lawYER -> True (6, 84)
abc123 -> True (6, 12)
is -> True (2, 28)
television -> True (10, 130)
19 -> True (2, 10)
234 -> True (3, 9)
a -> True (1, 1)
b -> True (1, 2)
C -> True (1, 3)
Z -> True (1, 26)
1 -> True (1, 1)
9 -> True (1, 9)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
þIáÇ32%«ODXgÖ*Ā
```
Input as a list of characters.
-1 byte implicitly thanks to *@ovs*.
[Try it online](https://tio.run/##yy9OTMpM/f//8D7PwwsPtxsbqR5a7e8SkX54mtaRhv//o5UylHSUUoE4B4rzgdhIKRYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWwS@j/w/siDi883G5spHpotb9LRPrhaVpHGv7r/I9WykjNyclX0lHyLfUp8SzwSQUyvUrzkksMDfKATP@ilNQiMzMgyzk/JdU9PycNyAwO9QWSni5AwsgUSBgAsSGIMIAQYApsrhGQYVqaCyRzUvPSSzLgJpqATSzLTDG0BLLC84tSgJRjQICPK0htYnmkaxCQkZiUbGhkDGRkFgOJktSc1LLM4sx8kMPA@oyMQeYkAnESyDwgjgJJAbGlUiwA).
**Explanation:**
```
þ # Only leave the digits of the (implicit) input-list
Iá # Push the input-list again, and only leave its letters
Ç # Convert each letter to its codepoint integer
32% # Take modulo-32 on each codepoint
« # Merge it to the list of digits
O # Sum this list
D # Duplicate this sum
Ig # Push the input-list again, and pop and push its length
Ö # Check if the sum is divisible by this length
* # Multiply it by the duplicated sum
Ā # And check that this is NOT 0
# (after which the result is output implicitly)
```
3 bytes (`D*Ā`) are used for edge-cases `0`/`00`/`000`/etc.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒlO%48Sȯ.%L
```
A monadic Link accepting a list of characters which yields zero (falsey) if the string is a *length-sum-multiple* or a non-zero number (truthy) if not.
**[Try it online!](https://tio.run/##y0rNyan8///opBx/VROL4BPr9VR9/v//r@RflJJaZGaiBAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///opBx/VROL4BPr9VR9/j9qmJOXX5D6qGEukFWZWqAIZB1ut3/UtAaI3P//j45WygDqy1fSUVDyLfUp8SzwSQWxvUrzkksMDfJAbP@ilNQiMzMQ0zk/JdU9PycNxA4O9QVRni4g0sgURBqACEMDpVguHai5RiAR09JcEJWTmpdekoEw0QRiYllmiqEliBmeX5QCoh0DAnxcwRoSyyNdg0CsxKRkQyNjECuzGESWpOaklmUWZ@aDHQjRbmQMNjARRCSBjQYRUWAFIMJSKTYWAA "Jelly – Try It Online").
### How?
```
ŒlO%48Sȯ.%L - Link: list of characters, w e.g. "ID" "10" "19" "0...0"
Œl - lower-case (w) "id" "10" "19" "0...0"
O - ordinals [105,100] [49,48] [49,57] [48,...,48]
48 - forty-eight 48 48 48 48
% - modulo [9,4] [1,0] [1,9] [0,...,0]
S - sum 13 1 10 0
. - a half 0.5 0.5 0.5 0.5
ȯ - logical OR 13 1 10 0.5
L - length (w) 2 2 2 length(w)
% - modulo 1 1 0 0.5
(nope nope yep! nope)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~73~~ \$\cdots\$ ~~63~~ 61 bytes
Saved ~~a~~ 3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
n;u;f(char*s){for(n=u=0;*s;++n)u+=*s&15+*s++/64*16;u*=u%n<1;}
```
[Try it online!](https://tio.run/##nVJta9swEP6eX6EaMvxWatmxGqN6MLowWlJaNsbYljBcW24MrhwsuwsN@e2p7uSlK2u/zJyfu5Pu5fH58uO7PN/vJe95aeerrHWVsy2b1pZpnwbcVdzzpNN7qave0dhzleedsIlLGe/dtB/LM8p3@0p25D6rpO2MtiOiHyxEOqG6X@rnkqRka61EXTeWT6yrft5drOcC7Mte5h0NJNjXbSFaxsA8bwrxqalLsL98vQJ18REwjAEDAIqIVUOw4v4eVC3kXbd6rjcx9R6qgiZgfmvaAvSHm5v5DBOy399nn8HKbnMaRmBVCrATtXioVNUgPZMeRlgwA7jF0gA/MAAgsXYcJwAjIWYC0kwg9skU5RQx8kmIQhEZnjC81TLxSYwuMzEBqgijX8i/7fqhHaZBR511Ch102SjRhxF2CDA/nphDBp31EQMSWsf6neo7ChynkBQYFskfwsCfoZO84CA2a5F3ojAsAmz0ltD/k6GfWbJ22K/FZhYuNsm5fnFJ/vIj@CmYoheb2MCzkoXY6LyAD@YZUdWjaErbLK1zMrju4HPieRjpELPizwyUrjOsOkYs@SFgGIkOOIzl9ZBMhxwdlbZudLhZt/qutK2xIsfvybggY7WAVVQ@yXz93VmaiuUQvxvt9k8 "C (gcc) – Try It Online")
Inputs a string and returns a truthy if it's a Length-Sum Multiple or a falsey otherwise.
[Answer]
# [J](http://jsoftware.com/), 29 24 bytes
```
#(|=0=])1#.48|64|96|3&u:
```
[Try it online!](https://tio.run/##Xc9Na4MwAMbxez9FmLCs0IlRK1XwMFw3OpRJSykt9OBLnI7MDF@6i9/dCuuhTw45/H@IefI9Pui0IL5HKFkQg3jTedZJsA3fRu1p8A3/PGeabq8Gxx5cZ7Aee2@cz2Y8K@X0qU8KQksuhKRAUR92m9@Qo370ddYxo0b9bHLeOA5iIHP@LkWButtHCJtXbHOJbWCyqW/b2d12k4It@x8EweuvrkT7X20jBvJS5cxFPMgmR3mJ43CtXJH8HddbtCTNmGmhVS12xwW/VG0la3R1hGkpUxPMVHkI5kn5OeZ01XgF "J – Try It Online")
*-5 bytes thanks to xash*
Inspired by [Neil's answer](https://codegolf.stackexchange.com/a/211431/15469) -- be sure to upvote him.
* `3&u:` turns the string into ascii codes
* `96|` mods the lowercase letters into the range 1-26
* `64|` mods the uppercase letters into the range 1-26
* `48|` mods the digits into the range 0-9
* `1#.` sum of all those converted digits
* `#` (on the far left) length of string
* `(|=0=])` First we check if the sum is zero `0=]` -- this will return `1` when it is and `0` otherwise. Then we check if sum mod the length `|` is equal to *that*. Thus for the entire phrase to return true it must be the case that the sum is *both* evenly divisible its length and nonzero.
*Why can't you just use a single 32 mod instead of doing a 96 followed by a 64?*
With 32, you'd be affecting the values 0-9 as well. With 96/64, you fix the letters without touching the digits, and now, since the letters are all 26 and under, when you fix the digits the already-fixed letters are unaffected.
[Answer]
# [Python 3](https://docs.python.org/3/), 54 bytes
```
lambda s:(sum(ord(c)%48for c in s.lower())or.5)%len(s)
```
An unnamed function accepting a string which returns zero (falsey) if the string is a length-sum-multiple or a non-zero number (truthy) if not.
**[Try it online!](https://tio.run/##DclLCoAgEADQq7gRZjZu@hBBZ@gCbSqVBJ2R0YhOb73ty2@9mLrml63FPR12V2WGcidgsXCi7ifPok4VSBUT@XECiCxmQB0dQcGWJVAFD4HyXf/Etop1MvYf "Python 3 – Try It Online")** Or see the [test-suite](https://tio.run/##TVDvS8MwEP3uX3EGBgmM0nbrcAM/iA6ZbDgUEcUv/XG1kTQpSbqxv772MkXz4d3jcvd497qTb4yeDfX1x6DytqhycCvu@pYbW/FSTOZXtbFQgtTgImWOaLkQxkaZmCjU3ImB/j0672iGX8D4OGtQKcOmwHb91m@6LRJ/6HXpk1gTf7QV2sWC6K2p8N6omvjzy47K5o4wzQhjgiRmYvpfO6Vu1rdURiOfvvlTnZ9VD7JKlkRfx1uo3uz323VYyI9v6ydieVEm6YyYdIQeFR6kkyaYPK@nsyCYExRBmuA9DBAsyZpYBXedldpzBiz6MlJzpk2HDGQNNaeMBKByCOyE3SWD3@QouJCgEMPPBd8 "Python 3 – Try It Online").
[Answer]
# [R](https://www.r-project.org/), ~~63~~ ~~62~~ ~~57~~ 56 bytes
*Edit: saved 1 byte thanks to Jonah*
```
function(s)!sum(i<-utf8ToInt(s)%%96%%64%%48)%%nchar(s)&i
```
[Try it online!](https://tio.run/##jZRdS8MwFIbv/RXHSaWFDpO2y1pQQfxiMnHoRBRhdF1mA1k62nT@/JkiXrTpGV42fZ7Tk5w3LfeSqy@dL6p6s9jUUout5Bf7da0yLQrlVt6xeeOK82Gt1/G8mCht1hwnYY7DIseJYvOgsjwtzfKp6KvmDnIuZTHw4ASGl3CXyoqDO/JhFHhw1Cs81lM92U55x4l9oCT2@p2HpmVKlO3EIaI8lSteMtYxxj6MA8S4Llb8vpBr@yNsjCgvr48dOvQhTBB6ctOBA7NnrP9gZMNYG6SDUh@IB@SMwgUQ@M5FloOoQBUaUtgWldBix0Eozb942V@Skp5ezUizVLuDTzOIIzwNwZ86L2tjMpOGCOFH9aYNHzq/30WrOGMHIxC1hSYBBE3ATqxoYgkMG9JbUa7adGRorPzVbDa9bePNTcFwmX6/3z5b242xs0yXGQ1Ci6dY3kXVZs2EA@wCai75TlTmr9F2KGkijO2ge5RNhjA2CCMrCVgQ0k4TTTT7yaVForffIrGhf9g1sQTSfzeaWGTi7X8A "R – Try It Online")
Output is Truthy list of one-or-more TRUEs, or Falsy list of one-or-more FALSEs.
[Answer]
# Scala, ~~71~~ ~~62~~ 46 bytes
* Fixed answer thanks to [@Mr Redstoner](https://codegolf.stackexchange.com/users/88701/mr-redstoner)
* Saved 9 bytes thanks to [@Dominic Van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)
* Saved 16 bytes! thanks to [the tip](https://codegolf.stackexchange.com/questions/211411/word-length-sum-multiples/211437#comment497885_211437) [@xash](https://codegolf.stackexchange.com/users/95594/xash) gave on [Jonah's answer](https://codegolf.stackexchange.com/a/211437/95792), which Dominic Van Essen suggested.
```
s=>{val x=(0/:s)(_+_%96%64%48);x>0&x%s.size<1}
```
[Try it online](https://scastie.scala-lang.org/1frIe3r4R6aJc0ILZoa7bg)
## 32 bytes if zero weren't falsey
```
s=>(0/:s)(_+_%96%64%48)%s.size<1
```
[Try it online](https://scastie.scala-lang.org/5I0NvWfqTZqCbrENOeS0jw)
[Answer]
# [Java](https://www.java.com/en/) ~~79~~ ~~77~~ ~~68~~ ~~66~~ 64 bytes
```
s->{int u=0;for(int c:s)u+=c%96%64%48;return u>0&u%s.length<1;};
```
[Try it here!](https://tio.run/##lZRta8IwEIA/r7@iCI4WZ7G@MVcVNueGQ5nMDRnih9imNS4mJbk4RPztrk43GMLwvh3J89zlciELsiJFmVKxiD52bJlKBfYiW/MMMO7FRoTApPAejkFghZxobY/7o1eqwd5YlgYCLLR/iGY4J2oyvbqTklMi2klrp4vtDRNgm1YpiKVy9nF4o11TaIX5Rj1fr@ar14GiYJSwTbt0afLa41QkMG/6wTbYndQYgWIi@a0Rt7ISiUfSlK8d7YHsZGe4VYqsHdcNrNTMeGYfk6wki@wlYcI5ZJlMiUq0u7EuLkZrDXTpSQNemm0BF058zJqbU85lzi3k7JhwTXNZ3v@FgelDL@1TjPO0b9AvCYzzrCKq6nWM0pERfZQ8xjijtwEG791j6HINQ5cwsH9CnzPo8rcEypxRoWaWCPrwrhHCYb5VhNGRKxb5DYQxlipC4LfDYb@L6Zl8vndfEAKZhX65ghCYRsBAOV0xnX0kCAl1n@UKZl7kL7u1trsv)
My first ever answer! The "0" test case messed me up, without it I could have had 51, (I wanted to try challenge the C answer, from which I've borrowed the char-to-number conversion). Now pretty much a port of the C answer.
```
s->s.chars().map(c->c%96%64%48).sum()%s.length()<1;
```
Still fairly proud of beating out some of current answers in languages like Python and JavaScript using the 'oh so verbose' Java.
Thanks to @user for a few extra bytes saved
@ceilingcat for a few more
@dominic-van-essen for 2 more using @xash's idea
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 59 bytes
```
lambda d:1>(x:=sum(int(c,36)-9*(c>'9')for c in d))%len(d)<x
```
[Try it online!](https://tio.run/##PZBRS8MwEMff@ynyIklkg7Xdih1uIDpk0uFQRHTuoWvSLZA2JU3nZOyz17uAPtzld/dP/sml@XEHU8c3je1LMiNfvc6rnciJmIZzdprO2q5iqnasGMQJH6bXrJjTlPLSWFIQVRPB@ZWWNRP89tQ72boWXDYbepBaGzqgqy5zyyaTgE9dXbhwVAM@WyFtkgDdGyEfjS4BX99WkJcPdDvY0GgCPIIIR772fhHUk66CDFfu3eHfaeydjkqEKdC7sQKWu/U6W@De/Ptj8QKQ74owigFUC8lJLY@qVQYf5M9F8djflQPv0BHiE0WIlG63QYBj763pGhzdTzsNCMEuFtj0KjYJaSx@XEnPqF3IcE7OJUPmF8qDP533vw "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
≔ΣE↧θ﹪℅ι⁴⁸η∧η¬﹪ηLθ
```
[Try it online!](https://tio.run/##LYyxCsMwDET3fkVGGdKtQyFT9qQttD8gbBELXKm1nfTzFQd6y/GOx/mI2Ssms7EUXgSe6xtm/MCkP8oeC8HX9d2sYU0K9xxYMAG36XJ1rlV0w@mRWSqMEiD23U0r/PVGE8lSY/s4Mpi9KNHGhVXsvKUd "Charcoal – Try It Online") Link is to verbose version of code. Output is a Charcoal boolean, i.e. `-` for a multiple, nothing if not. Explanation:
```
≔ΣE↧θ﹪℅ι⁴⁸η
```
Convert the string to lower case, take the code points of all the characters, reduce them modulo 48, then take the sum.
```
∧η¬﹪ηLθ
```
Check that the sum is a non-zero multiple of the length of the string.
[Answer]
# [Perl 5](https://www.perl.org/) + `-plF`, 32 bytes
-7 bytes thanks to [@Nahuel Fouilleul](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul)!
```
$s+=ord(lc)%48for@F;$_&&=1>$s%@F
```
[Try it online!](https://tio.run/##Lc3hC8FAHMbx98/fsYmkdrPJEhEmmogk3mi2w@pnt@5uk3/eWfL6@X56Ci7JN8@3pQbGUu2hkGmTkpbt9W9CjsOBdWk0hmxkKXscGvPgRALrMtLLIuJYlXmimZNjI1Muez1MRcoXgm7YH9ZYzuD6cMAc/JwLv3yCeH7Xj7/walFlKQtwrI8x2W6jOSh@neY7xNeEuV1kCpoTrzKViRx16XY9xLhiijMYgo8odL0o0yko/AI "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~101~~ 96 bytes
```
def f(s):x=sum([i-[48,96][i>96]for i in map(ord,s.lower())]);return not(x%len(s))and x//len(s)>0
```
[Try it online!](https://tio.run/##PZDbasMwDIbv8xS6GbYhXZP0wNrRwtjK6GhZ2RhjC7lIG6c1pHawnR4offZM9tguJH@S7F@y6rPdKdlr24KXUFLDxqeJafY0FZ20fxeOhlkqpuhLpUGAkLDPa6p0EZrbSh25poxl7F5z22gJUll6uqm4RB2WywJO3e5vNI1ay401MIE0JTteVYqEZNks7LxecMSXRm5sHEnEV11wPRwiPaqCP6uqRHz/WKKfP5EsTEkyQI7Q4sjHXi/BeNDs0WPLrd39K/W90kEU8QjpE4fH42G1Wszc3fz4NXtDyNebOOkhCIPO8oofhBHKDeTfJb2@75Ujr50i2rcroo1IlgWBW9FWq6Z2a/K/HQcALusCl/RVlwSotZCWluTialfoTOFSUsfsSljwV2ftDw "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
ØWiⱮ_³e€ØD¤%26Sµ;ọ³L¤$Ȧ
```
[Try it online!](https://tio.run/##ATYAyf9qZWxsef//w5hXaeKxrl/Cs2XigqzDmETCpCUyNlPCtTvhu43Cs0zCpCTIpv///0NvdmlkMTk "Jelly – Try It Online")
Golfed 1 byte and also made the program actually work (third time's a charm? it was still broken)
## Explanation
```
ØWiⱮ_³e€ØD¤%26Sµ;ọ³L¤$Ȧ Main Link
Ɱ For each character in the input
i find its index in
ØW "ABC...XYZabc...xyz0123456789_"
_ and subtract from each element
³e€ØD¤ the corresponding value, which is
³ if the original character
e€ is a member of
ØD the digits (this is to fix the one-off offset of the digits)
(the above nilad gets a list of 0 and 1 for if each character is a digit, and since Jelly's subtraction `_` is vectorized, this works as subtracting the corresponding element)
%26 modulo 26
Sµ take the sum; begin a new link with this value
; $ append
ọ the number of times the sum is divisible by (just plain "divisible by?" has the arguments in the opposite order which would take 1 extra byte to flip)
³L¤ the length of the input
Ȧ any and all - are both values truthy; that is, is the sum divisible and non-zero?
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~22~~ ~~17~~ 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Input is an array of characters.
Or [13 bytes](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=eMh2IGMgdTQ4w3ZVbA&input=WyIwIl0), without having to special-case `0`.
```
xÈv c u48
©vNÎl
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=eMh2IGMgdTQ4Cql2Ts5s&input=WyIwIl0)
```
;x@ÒBbXu)ªX\n©vNÎl :Implicit input of character array U
x :Reduce by addition
@ :After passing each X through the following function
Ò : Negate the bitwise NOT of
; B : Uppercase alphabet
b : 0-based index of
Xu : Uppercase X
) : End indexing
ªX : Logical OR with X, which gets coerced to an integer
\n :Reassign to U
© :Logical AND with
v : Is divisible by
N : Array of all inputs
Î : First element (i.e., the original U)
l : Length
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~54~~ 53 bytes
Returns **0** or **1**.
```
s=>Buffer(s).map(c=>t+=++k&&c%96%64%48,k=t=0)|t%k<!!t
```
[Try it online!](https://tio.run/##jdLvT4JAGAfw9/0V6obCLAVEFlu4lWmz4XL9WCvrxQmHEifHuIPW1v9ONCpB7wJess@@99x9nzeQAGJHXkhPAuzA1DVTYo4uYteFkUik3haEom2OaNfsdv122xYMXdA1QTs99k1qytInFfyzZpOmNg4IRrCH8FrsLKcAkY/XjnRU/O2KrQ1ECLckqZF//X7jW8J9No8tOgst@CN57DoObKrIQQW7iRwY6frvsTw2zu5/hZFbkXb3MN9dgM9ml0XFZeqwFpNLissUmZ1Wcp2XYHkfxXTDLUj9S8kSMnpwzjDe7r0BSyEYrOmmKitvRyu0w1JjnHiOYlSoRxw5hcE46nyxsCalJWROD96fJrdV04OVraiDKuWR/V5YikIEE494OF9ojto9wn9Z6kCr0RA4WCuWWtVS41rquZZSaimDqdIv "JavaScript (Node.js) – Try It Online")
[Answer]
Python 2 & Python 3 -- 69 Bytes
```
lambda a:0==sum(ord(s.upper())-[64,48][s.isdigit()]for s in a)%len(a)
```
Assuming the input as string on variable a, one can get down to 60 Bytes
```
0==sum(ord(s.upper())-[64,48][s.isdigit()]for s in a)%len(a)
```
[Answer]
# JavaScript, 107 bytes
```
a=>(b=a.toLowerCase().split('').reduce((c,d)=>c+(+(isNaN(d)?d.charCodeAt(0)-96:d)),0)/a.length,!(b?b%1:!b))
```
[Try it online!](https://tio.run/##jdJdT8IwGAXge3/FJDG0AeY2hUQSIEbRYPAjfsToXde@QLWsy9qh/nrkM0ZfTHt/ntPk9H1jM2Z4IXPbMLkUUEx19g5f81FnzjpdknZYaPVQf0BxxgwQGppcSUuqVRoWIEoOhPC6oJ0ur5EakeaG3RBBeyLkE1acaQGnlkS0cdJqC0rrET1koYJsbCf1fZL20oO4vZ9SOuc6M1pBqPSYVCaglA4ajW7Q/8yBWxDt4IIpA/XgHkypbDuo1EabXIXSvV/6uhzaQT4Ej4JtFHVclRm3cZR5dGyjqOO2WKzZanlUbJKoYTnfpVYjj4ptFHU8PF178GUK0cG5h1yEEEyabpc0EYs8nouQin1YjN3qeJI/9rEodx5ZgniznLrtIoTg@vrddp3756qO3X4T3HFUMyniE3fBJogKnnUh3HqZQvT07m7Yd9JVCu/GPl769x67rXKIs5THyZGbr3OIS@Om0iBmQcFMGqkzN//J4hv3@K4dP5UcedzJIoTH8tgJodSNUnyNHneI0KsbveINPSZEyGP31ezzbw)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 63 bytes
```
^
$.'$*1;
T`L`l
[j-z]
55$&
[t-z]
55$&
T`_l`ddd
\d
$*
^(1+);\1+$
```
[Try it online!](https://tio.run/##PctbD8EwAIbh@@931GlC1jGJuBIWmUwIExGnjhaVamU6En9@RMTde/E@qbBSJ3mhPGD5FqReIg7tIGYRU1hdaq8NfJ8UsbL/jNlOMc451hzEwbZMq5XOmlZJnp@FUgajLLLhLRIYZvpgqasxTrlIWy30DBcDo46YzUcI@/B8uKAuvs6Dn12hhD7Z8080P@IhOW1jYVKO7mQSBVDJcxlMkewP1GtA3mGFEg95l0bjc3qN5hs "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
^
$.'$*1;
```
Prefix the input with a unary copy of itself.
```
T`L`l
```
Convert it to lower case.
```
[j-z]
55$&
[t-z]
55$&
T`_l`ddd
```
Convert the letters to digits with the same digital sum.
```
\d
$*
```
Take the digital sum.
```
^(1+);\1+$
```
Check that it is a non-zero multiple of the length.
[Answer]
# [MAWP](https://esolangs.org/wiki/MAWP), 78 bytes
```
%|0/[!843WWP843WWWA/]~[!88WP88WWA/]~[!86WP86WWA/]_1A![1A~M~]%!~!~/P\WA{0:.}?1:
```
[Try it!](https://8dion8.github.io/MAWP/v1.1?code=%25%7C0%2F%5B!843WWP843WWWA%2F%5D%7E%5B!88WP88WWA%2F%5D%7E%5B!86WP86WWA%2F%5D_1A!%5B1A%7EM%7E%5D%25!%7E!%7E%2FP%5CWA%7B0%3A.%7D%3F1%3A&input=length)
Waiting for answer in 1+...
Uses the modulus method from Jonah's J answer.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~12~~ 11 bytes
```
k48\stGn\~*
```
Output is `0` if the input is length-sum multiple, or a positive number otherwise.
[Try it online!](https://tio.run/##y00syfn/P9vEIqa4xD0vpk7r/3/1jNScnHx1AA) Or [verify all test cases](https://tio.run/##PY5LC4JAFIX3/op2A618k8tIEUNJehCJi3xMKY1O6Git@ut2xqDFOfNd7szHNJlg03V6mKu0F36bfpaTm7yPE6koY5woJBpCETxDCtwObSE0tQXuupJ2tg3a8JL6nN2Ah1OEDlyUbqFURFPJQvnJdIzW0KAZbe@i@mvMWTPWpeaAzrwrcazjOPTk3ex18faALC803QDUPUpQRse6r7n8zfxON6QnQ3LpQxK5QhzyBQ).
### How it works
```
k % Implicit input. Convert to lowercase
48 % Push 48
\ % Modulus. Each character is first converted to its code-point
s % Sum. This gives "s"
t % Duplicate (*)
G % Push input again
n % Number of elements. This gives "n"
\ % Modulus
~ % Negate. This gives true if s mod n equals 0, or false otherwise (**)
* % Multiply (*) and (**)
% Implicit display. True and false are displayed as 1 and 0 respectively
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 54 bytes
```
Tr[a=FromDigits/@#/.a_/;a>9:>a-9]~Mod~Tr[1^#]==0<Tr@a&
```
[Try it online!](https://tio.run/##RY5dS8MwFIbv/RWlAy@K2o99QJ0dka7KRovFTURHlbM0XQNtI2k6L8T99doTEW@e83By8vLWoEpWg@IU@sII@q3cQXAnRb3kB65am4zsK3i357Dwrxdw6WenROSn4cp9G2VB4NxsJYHzfkOh2aWSN4pYBbHCEiRQxWRLrIiWIiNfZ4ZhmCWrKmFeGGbSxWr1ETP0dddQ5ToN@oPMmZzNUEORs3tRFeibp2QYOmK1xIU3RToIV1Mne2jTrsZRseagyv/MyV9AKI48d318eRYyx3mbpnGkP8HnS/SIBnvqemM03iIVq9iRt1wMNXXMb4I3nuhrxF63RrzqXgjf/J73Pw "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes a list of characters as input and returns `True` or `False` as output. The bulk of the work is done by `FromDigits`, which converts the characters 0-9, A-Z to the numbers 0-35.
] |
[Question]
[
[](https://i.stack.imgur.com/yT2lY.png)
Above is the picture of the flag of the country Nepal. Pretty cool.
What's cooler, is the aspect ratio, which is defined under the constitution as:
[](https://i.stack.imgur.com/eDvds.jpg)
That formula in copyable form:
$$ 1 : \frac{6136891429688-306253616715\sqrt{2}-\sqrt{118-48\sqrt{2}}(934861968+20332617192\sqrt{2})}{4506606337686} $$
Your task is to output at least the first 113 digits of the decimal expansion, in any format of your choosing.
These digits are:
1.2190103378294521845700248699309885665950123333195645737170955981267389324534409006970256858120588676151695966441
These digits form can be found in sequence [A230582](https://oeis.org/A230582).
This constant is algebraic, specifically quartic. In particular it is the least root of `243356742235044x⁴ - 1325568548812608x³ + 2700899847521244x² - 2439951444086880x + 824634725389225`.
This is `code-golf`, so shortest answer wins.
Related: [Let's draw the flag of Nepal](https://codegolf.stackexchange.com/questions/18664/lets-draw-the-flag-of-nepal)
[Answer]
# [Python 3](https://docs.python.org/3/), 100 bytes
```
from sympy import*
r=sqrt(2)
print(N((4-3/((7*r-3-sqrt(59-24*r))*(23-9*r)*16/9/(33-20*r)+r))/3,113))
```
[Try it online!](https://tio.run/##HckxEoQgDEDR3lNYJnEzCHF1KLyCx3C0QDDScHpk7P6fl0o@4iW17hpD/5SQSn@GFDVTp@tzawaHXdLzyrABTCwGYCFl4Q//nt1EikjghH0rsrPxBkTYjW2HZkZ@1gpirS8 "Python 3 – Try It Online")
This is longer than compressed hardcoding and definitely golfable, but I want to share a formula I simplified from one in [this thumbnail](https://i.ytimg.com/vi/APXaq6i_3hs/hqdefault.jpg) of [this video](https://www.youtube.com/watch?v=APXaq6i_3hs):
$$\begin{aligned}
v &= \frac{16 \cdot (7\sqrt{2}-3-\sqrt{59-24\sqrt{2}}) \cdot (23-9\sqrt{2})}{9 \cdot (33-20\sqrt{2})} \\
\text{ratio} &= \frac{4}{3}-\frac{1}{v+r}
\end{aligned}
$$
**92 bytes**
```
from sympy import*
r=5-sqrt(8)
print(N((4-6/((29-7*r-sqrt(48*r-4))*(8/r/9+8)/r+5-r))/3,113))
```
[Try it online!](https://tio.run/##JcmxDYAgEAXQ3iks71ByUVChcAXHMFog@KVhejSxe8lLJR/xMrXuiKF9SkilPUOKyKrBOunnRibHTcJ5ZdqIrJ6FaPR6UfjXuk@WWZETiO8cC7pJg1lMPwyGudYX "Python 3 – Try It Online")
**95 bytes** (@dingledooper)
```
from sympy import*
r=sqrt(2)
print(N((4-3/((7*r-3-sqrt(59-24*r))*(6384+2608*r)/2601+r))/3,113))
```
[Try it online!](https://tio.run/##HYm5EYAgEABzqzC8AxmEwy@wBctwNODxJKF6ZIx2djeVfMVAtZ4cff8Wn0p/@xQ5i4739@EMFrvEd8hwADhFGmARrEj9c9qUdYIRBcy0OmnncW2qG41sWdNgDCHW@gE "Python 3 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 48 bytes
```
¬ª Ä‚åàS¬´A0·∫á‚ü®ƒñ^·πñ*¬´)Œ†·πôvp‚âà‚Ä∫‚â•‚Ä∫Bƒñ‚â•·∫á‚Çà·∏ã·∫áŒ≤·∫ãV¬º¬ª16‚ܵœÑyNY‚àÜPh‚Å∫¬∞·∏û
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLCu8qA4oyIU8KrQTDhuofin6jEll7huZYqwqspzqDhuZl2cOKJiOKAuuKJpeKAukLEluKJpeG6h+KCiOG4i+G6h86y4bqLVsK8wrsxNuKGtc+EeU5Z4oiGUGjigbrCsOG4niIsIiIsIlsyNDMzNTY3NDIyMzUwNDQsIDEzMjU1Njg1NDg4MTI2MDgsIDI3MDA4OTk4NDc1MjEyNDQsIDI0Mzk5NTE0NDQwODY4ODAsIDgyNDYzNDcyNTM4OTIyNV0iXQ==)
Solves the stated polynomial.
```
»...» # Giant number
τ # Decompress from base
16↵ # 10^16
yNY # Negate every other term to get coefficients
∆P # Solve polynomial
h # First root
⁺°Ḟ # Format to 113 decimal places
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes
```
1.”)¶⌊G U9ι[abN↧Q∧≡⁻w⁼Ka5↧χ±ν∕§G\`U⊙Gφ2S4↖gλo0θ|Sψ◨N➙
```
[Try it online!](https://tio.run/##LY07CgJREASvIhtpoMyvZ6bxEl5h2URhURDx@s8X2FlRBb3d1/f2Wvcxbu/H83Nc9LKcroc/mFJU3KuNAdMOlIhFJ@nCbmSCEDWfUyJn4KUlBNhqWd50C3iEUCRZYsjGdILurFRoEsyM0Hk9xjh/9x8 "Charcoal – Try It Online") Link is to verbose version of code, for what it's worth. Explanation: Prints `1.` separately, because that improves the string compression of the remaining 112 digits.
120 bytes to actually calculate the 113 digits:
```
≔Xχ¹¹²θ≔▷math.isqrt⊗×θθη1.✂I÷⁻⁻×I”)¶↷ωrNL@”θ×I”)⧴↧≔Mmχ”η÷×▷math.isqrt⁻×¹¹⁸×θθ×⁴⁸×θη⁺×I”)¶u⁰»~”θ×I”)¶↗v⌊Hq”ηθI”)″“▷←ι2⊖”¹
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZHNSsQwEMfx6lOUnFLoLp2knabsSVwPHoSC4kU8ZLvVBrItbdL6Er6Blz0o-kw-jd02q0X2MjD5f8wP8vaVl7LNa6n3-4_OPi3E99nrhTHquaJZ_VK0FMLAA2B-4DX-6txJV73U97KlZCdtuVSmaS0JvHXdbXSxpXdqVxjaHBL-kCuHXNaqylICS_K73GqVF_RSGkuvK7tWvdoW9EZVnXFzqhkNBIGjSCFiKQpBRpjAmxt4iCzmCJhATMajw_jrnaynsefXAMSxd-I_btH8fSg_KJn-R5nySCAMiKcIWcg5Q0ggZQ7QdxcmPYpDxBA5T1AgGVXwV-9mkxv3NZ8PZNFr8ujWHw "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation:
```
≔Xχ¹¹²θ
```
Effectively set the calculation precision to `112` digits after the decimal point by multiplying everything by `10¹¹²`.
```
≔▷math.isqrt⊗×θθη
```
Calculate the square root of `2` to that precision.
```
1.
```
Output the `1.` separately as it's easier.
```
✂I÷⁻⁻×I”...”θ×I”...”η÷×▷math.isqrt⁻×¹¹⁸×θθ×⁴⁸×θη⁺×I”...”θ×I”...”ηθI”...”¹
```
Calculate and output the `112` digits after the decimal point, using compressed strings for the large numbers.
~~105~~ ~~96~~ ~~81~~ ~~80~~ ~~72~~ 71 bytes by importing `sympy` and using a golfed version of @xnor's original sympy answer:
```
≔⁻⁸▷sympy.sqrt¹⁸θ≔∕×⁻ײ⁰θ⁶¹⁺⁺⁶θX⁻×¹⁶θχ·⁵⁻×⁹⁶θ³²η▷sympy.N⟦∕∕⁺⁸η⁶⁺¹∕ηθ¹¹³
```
[Try it online!](https://tio.run/##XY4xD4IwEIV3f0Xj1CaVcBAJhslERw2DcTEODRJpUkBaxPDrawtnoi7vLvfe3X1FJXTRCmXt1hh5b@hBNk9DU072g1BnoenSjPVjDEyn@yUnkDLGSceyBeZ3cpC3kp5kXRpcnvso9DlOEnCSKzefJJmnefsq9U8e0IHQSRismX/0HdhgII68UzmEXMump3@gR0d5QSos0@PU7zicDw1wgnbl7/qbAPGVscxauxrUGw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁻⁸▷sympy.sqrt¹⁸θ
```
Save \$ 8 - \sqrt { 18 } \$ in a variable.
```
≔∕×⁻ײ⁰θ⁶¹⁺⁺⁶θX⁻×¹⁶θχ·⁵⁻×⁹⁶θ³²η
```
Save \$ \frac { 3 ( 33 - 20 \sqrt 2 ) ( 14 - 3 \sqrt 2 + \sqrt { 118 - 48 \sqrt 2 } ) } { 32 ( 23 - 9 \sqrt 2 ) } \$ in a variable. \$ 3 ( 33 - 20 \sqrt 2 ) = 20 ( 8 - \sqrt { 18 } ) - 61 \$, \$ 14 - 3 \sqrt 2 = 6 + 8 - \sqrt { 18 } \$, \$ 118 - 48 \sqrt 2 = 16 ( 8 - \sqrt { 18 } ) - 10 \$ and \$ 32 ( 23 - 9 \sqrt 2 ) = 96 ( 8 - \sqrt { 18 } ) - 32 \$. Also, I can use `Power(, 0.5)` instead of `sympy.sqrt` on an expression based on \$ \sqrt 2 \$.
```
▷sympy.N⟦∕∕⁺⁸η⁶⁺¹∕ηθ¹¹³
```
Calculate the desired result.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~69~~ ~~62~~ 57 bytes
Saved so many bytes thanks to the comment of [@Greg Martin](https://codegolf.stackexchange.com/users/56178/greg-martin) and the comment of [@att](https://codegolf.stackexchange.com/users/81203/att)
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/7/I9lHHLCNrE31jXcMES0t9jSJtDfMiXWNdoLCGqaWukUmRpqaGkbG@pW6RpqGZvoaxsa6RAVDs////ugVFmXklAA)
```
r=‚àö2;4/3-1`99/(r+(7r-3-‚àö(59-24r))(23/9-r)16/(33-20r))
```
[Answer]
# [Python 3](https://docs.python.org/3/), 80 bytes
Obligatory compressed hardcoding method. See [@xnor's answer](https://codegolf.stackexchange.com/a/263764/88546) for an actual mathematical computation.
```
print(1.2,*b'Zg%R^4-F\0Vc
bUB;2{!_@9%F_;QIY -"(Z\0EFD:x:VL_`@)',sep='')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Ew1DPSEcrSZ0xKl01KM5ESNctxkAiLFkuKdTJ2qhaUT7ewVKV0S3eOlDKM1JBV0kjKsbA1U3SxarCKsyHXyA@wUFTXac4tcBWXV3z/38A "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 86 bytes
```
"%,}#:g6F.mR}}1o|7{n[TK%::,QFb`_xTj3br9F;As}^_2]S%}Soe()xyYB".bytes{|i|$><<(i-25)%100}
```
[Try it online!](https://tio.run/##KypNqvz/X0lVp1bZKt3MTS83qLbWML/GvDovOsRb1cpKJ9AtKSG@IiTLOKnI0s3asbg2Lt4oNli1Njg/VUOzojLSSUkvqbIktbi6JrNGxc7GRiNT18hUU9XQwKD2/38A "Ruby – Try It Online")
Prints `the digits of the decimal expansion, in any format.` I interpret that to mean the decimal point is not required. It would cost a few bytes to add it in.
This simply decodes the ASCII codes of each character in the magic string to a number between `35-25`=10 and `125-25`=100, takes a modulo to convert the `100` into `0` where necessary, and prints the output, concatenated.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 50 bytes (100 nibbles)
```
"1."$ ~3a4898772b89091168fc7c6102ed1580a718bf8643e9be1c097cfadb7db934a09ad75c14a79b0262ce77978b500e9
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc25DQJBDADAVtCJFGTvZ7scfyshIRIgpRGSSxA1XTcEwDQwz_flZHbO67q-7rd54C0WPC773aNqY2GiYiwgiIOnkw-EkoGdQQnZJo9WUyzRQcinhlGY1KYgGtQdm5IYlFE8iYTYOkDK9_qV__oD)
Same approach as [Neil's first Charcoal answer](https://codegolf.stackexchange.com/a/263759/95126).
Nibbles can only handle integers, so outputting the initial `1.` and the decimal digits separately is essential.
[Answer]
# [Python 3](https://docs.python.org/3/), 109 bytes
```
print(f"1.{0x3a4898772b89091168fc7c6102ed1580a718bf8643e9be1c097cfadb7db934a09ad75c14a79b0262ce77978b500e9}")
```
[Try it online!](https://tio.run/##BcE7DgIxDAXAu2wFDbLze/ZxbCcRNMsKbQFCnD3MHJ/z/tzzWsfrsZ@XufHtS@9sRVSA5KKkzE1mIBpTGp2rkIHFp7SSh/rgIEVM647umouRWkcNLgZ1Si3FABTilWjob7uu9Qc "Python 3 – Try It Online")
Stores the decimal part in hex (thanks @xnor).
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `j`, 52 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
»¥\!ĖẸæṭṙ|«ɦ⁾‘cạḍ¬ṣ“},ịḤ)ṣ3_ßịạ⁷ƇR×XẏṢḋyi¡ẹ¿pĿ⁴8»`1.
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMiVCQiVDMiVBNSU1QyElQzQlOTYlRTElQkElQjglQzMlQTYlRTElQjklQUQlRTElQjklOTklN0MlQzIlQUIlQzklQTYlRTIlODElQkUlRTIlODAlOThjJUUxJUJBJUExJUUxJUI4JThEJUMyJUFDJUUxJUI5JUEzJUUyJTgwJTlDJTdEJTJDJUUxJUJCJThCJUUxJUI4JUE0KSVFMSVCOSVBMzNfJUMzJTlGJUUxJUJCJThCJUUxJUJBJUExJUUyJTgxJUI3JUM2JTg3UiVDMyU5N1glRTElQkElOEYlRTElQjklQTIlRTElQjglOEJ5aSVDMiVBMSVFMSVCQSVCOSVDMiVCRnAlQzQlQkYlRTIlODElQjQ4JUMyJUJCJTYwMS4mZm9vdGVyPSZpbnB1dD0mZmxhZ3M9ag==)
Just a compressed number with `1.` prepended.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 53 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•4₅XïMáô|û¡Žü%ÔÖ7àþ}iÙ°fàp!LÙÔ‡ĀΣH₁ù¸ê_+0×B<È„u•„1.ì
```
[Try it online.](https://tio.run/##AWYAmf9vc2FiaWX//@KAojTigoVYw4PCr03DocO0fMO7wqHFvcO8JcOUw5Y3w6DDvn1pw5nCsGbDoHAhTMOZw5TigKHEgM6jSOKCgcO5wrjDql8rMMOXQjzDiOKAnnXigKLigJ4xLsOs//8)
**Explanation:**
Straight-forward hard-coded approach. 05AB1E also only has 16 bits floating point precision anyway.
```
•4₅XïMáô|û¡Žü%ÔÖ7àþ}iÙ°fàp!LÙÔ‡ĀΣH₁ù¸ê_+0×B<È„u•
# Push compressed integer 2190103378294521845700248699309885665950123333195645737170955981267389324534409006970256858120588676151695966441
„1.ì # Prepend "1." in front of it
# (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 how the compression works.
[Answer]
# [CellTail](https://github.com/mousetail/CellTail), 133 Bytes
```
I=1,219010337,829452184,570024869,930988566,595012333,319564573,717095598,126738932,453440900,697025685,812058867,615169596,6441;O=N;
```
Outputs as a list of numbers, starting with the integer component.
[`I="Try it online!";O=C;`](https://mousetail.github.io/CellTail/#ST0xLDIxOTAxMDMzNyw4Mjk0NTIxODQsNTcwMDI0ODY5LDkzMDk4ODU2Niw1OTUwMTIzMzMsMzE5NTY0NTczLDcxNzA5NTU5OCwxMjY3Mzg5MzIsNDUzNDQwOTAwLDY5NzAyNTY4NSw4MTIwNTg4NjcsNjE1MTY5NTk2LDY0NDE7Tz1OOw==)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 53 bytes
```
“µŻ5(_PṛØY⁺Ɲ>Ŀḣ¦ḲḶaİçẸẒḋƙ⁷\ø%Sfø*ḤÑ[F]€ȮĠṆ5]Ẇ⁶rȦ’⁾1.;
```
[Try it online!](https://tio.run/##AW8AkP9qZWxsef//4oCcwrXFuzUoX1DhuZvDmFnigbrGnT7Ev@G4o8Km4biy4bi2YcSww6fhurjhupLhuIvGmeKBt1zDuCVTZsO4KuG4pMORW0Zd4oKsyK7EoOG5hjVd4bqG4oG2csim4oCZ4oG@MS47//8 "Jelly – Try It Online")
Straightforward hardcoding of the digits after the decimal point as a base-250 integer, then prepend "1."
Any calculation would have to be done using integers and fixed point arithmetic which is almost certainly longer than this.
Alternatively, Python and sympy can be used within Jelly. Here’s one version using [@xnor’s Python code](https://codegolf.stackexchange.com/a/263764/42248):
# [Jelly](https://github.com/DennisMitchell/jelly), 99 bytes
```
“YSZprint(ZN((4-3/((7*Y-3-S59-24*Y))*(23-9*Y)*16/9/(33-20*Y)+Y))/3,113))“S2)“Zsqrt(“sympy.”ṣḢ$j¥/ŒV
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5zI4KiCosy8Eo0oPw0NE11jfQ0Nc61IXWPdYFNLXSMTrUhNTS0NI2NdSyBLy9BM31Jfw9hY18gAyNUGyukb6xgaGmtqAk0KNgKRUcWFRSUaQEZxZW5Bpd6jhrkPdy5@uGORStahpfpHJ4X9/w8A "Jelly – Try It Online")
And here’s an approach that uses sympy to solve the aquatic equation in the OEIS, as suggested by @UnrelatedString:
# [Jelly](https://github.com/DennisMitchell/jelly), 113 bytes
```
“ẏ0P|Ẓ+“¥j^⁸øżk“½ÇṂY;Sṙ“®ẋ~⁽h`¹“£]iyi7ṭ’NÐeŒṘ“print(sympy.N(from_base(“,sympy.poly('x')).all_roots()[0],113))”jŒV
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHu/oNAmoe7pqkDeQcWpoV96hxx@EdR/dkg7h7D7c/3NkUaR38cOdMEH/dw13ddY8a92YkHNoJ4i@OzazMNH@4c@2jhpl@hyekHp30cOcMoERBUWZeiUZxZW5BpZ6fRlpRfm58UmJxqgZQSgciWpCfU6mhXqGuqamXmJMTX5SfX1KsoRltEKtjaGisqfmoYW7W0Ulh//8DAA "Jelly – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `·π™`, 52 bytes
```
‛1.»⟑]"Ȯ⁋æ≥ǔ}¼√ḋ¾d¯₴÷≤„~-↳§*≤4_⌐↳¯→ḟS∆Y↵Ḃ¥zjλ…°qẆ∷9»
```
String sum magic! La la la!
Ties with Thunno 2 and Charcoal. This seems optimal.
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyLhuaoiLCIiLCLigJsxLsK74p+RXVwiyK7igYvDpuKJpceUfcK84oia4biLwr5kwq/igrTDt+KJpOKAnn4t4oazwqcq4omkNF/ijJDihrPCr+KGkuG4n1PiiIZZ4oa14biCwqV6as674oCmwrBx4bqG4oi3OcK7IiwiIiwiIl0=)
## Explanation
```
‛1.»⟑]"Ȯ⁋æ≥ǔ}¼√ḋ¾d¯₴÷≤„~-↳§*≤4_⌐↳¯→ḟS∆Y↵Ḃ¥zjλ…°qẆ∷9»­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏⁠‎⁡⁠⁣⁡⁢‏⁠‎⁡⁠⁣⁡⁣‏⁠‎⁡⁠⁣⁡⁤‏⁠‎⁡⁠⁣⁢⁡‏⁠‎⁡⁠⁣⁢⁢‏⁠‎⁡⁠⁣⁢⁣‏⁠‎⁡⁠⁣⁢⁤‏⁠‎⁡⁠⁣⁣⁡‏⁠‎⁡⁠⁣⁣⁢‏⁠‎⁡⁠⁣⁣⁣‏⁠‎⁡⁠⁣⁣⁤‏⁠‎⁡⁠⁣⁤⁡‏⁠‎⁡⁠⁣⁤⁢‏⁠‎⁡⁠⁣⁤⁣‏⁠‎⁡⁠⁣⁤⁤‏⁠‎⁡⁠⁤⁡⁡‏⁠‎⁡⁠⁤⁡⁢‏⁠‎⁡⁠⁤⁡⁣‏⁠‎⁡⁠⁤⁡⁤‏‏​⁡⁠⁡‌⁣​‎‏​⁢⁠⁡‌­
‛1. # ‎⁡The two character string "1.".
»⟑]"Ȯ⁋æ≥ǔ}¼√ḋ¾d¯₴÷≤„~-↳§*≤4_⌐↳¯→ḟS∆Y↵Ḃ¥zjλ…°qẆ∷9» # ‎⁢The compressed number 2190103378294521845700248699309885665950123333195645737170955981267389324534409006970256858120588676151695966441.
# ‎⁣Due to some niece witchcraft, the Ṫ flag sums the string and the number to get the constant and then implicitly prints the result. String sum magic! La la la!
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# dc, 78 bytes
```
16iFFk594DB3BD338 2v474E23564B*-2v4BBEB1DE8*37B8DC90+76 2v30*-v*-41946AB7E96/p
```
It's a straight calculation, but with the constants specified in hexadecimal for brevity
Explanation:
```
16i # input in base 16
FFx # 255-digit precision
594DB3BD338 2v474E23564B*- # 6136891429688 - 306253616715‚àö2
2v4BBEB1DE8*37B8DC90+ # 934861968 + 20332617192‚àö2
76 2v30*-v # ‚àö(118 - 48‚àö2)
*- # complete the numerator
41946AB7E96/p # divide by 4506606337686 and print
```
Output:
```
1.2190103378294521845700248699309885665950123333195645737170955981267\
389324534409006970256858120588676151695966441384905283150985491649927\
585413642430469766180971720219688119745626955249584071432721758804516\
12949021847336692342653120129739301327854858381983
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 104 bytes
```
a=>'1.'+0x3a4898772b89091168fc7c6102ed1580a718bf8643e9be1c097cfadb7db934a09ad75c14a79b0262ce77978b500e9n
```
[Try it online!](https://tio.run/##BcEBCsIwDADA52xDHEnbNQlj/iVNW1HGKk7E39e7p371tPfj9bkeLZdet67bbcB5uMDPa2BhIpdYQBAjVyOLCK5kXBiUkFPlGHyRVNBAyKrmRDmJDwqimRbDoCQJXHRWiIQ4LQBFjr5aO862l3lv97GO07T2Pw "JavaScript (Node.js) – Try It Online")
Quite but not completely trivial
] |
[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/233405/edit).
Closed 2 years ago.
[Improve this question](/posts/233405/edit)
The Lisp language has a family of functions `car`, `cdr`, `cadr`, etc for accessing arrays. For each one, an `a` defines taking the first item of an array, and a `d` defines taking the rest.
For example, running `cadr` on `[[1,3,4],5,7]` will return `[3,4]` as the `a` gets the first item (`[1,3,4]`) and the `d` removes the first item.
We've already had a [challenge](https://codegolf.stackexchange.com/questions/221344/cadaddadadaddddaddddddr-linked-list-accessing) regarding running a `cadaddadadaddddaddddddr` on a list, but what about the reverse?
Your challenge is to, given a string of the type above (starting with a `c`, ending with a `r`, with only `ad` in the middle), and a single value, create an array such that running the string as a `cadaddadadaddddaddddddr` on the array returns said value.
For example, given the input `cadar, 1` a possible output could be `[[0,[1]]]` since running `cadar` on that gives 1.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
# Testcases
These are possible outputs, all that matters is that your program returns an array which works for the condition.
```
car, 3 => [3]
cdddar, 5 => [0,0,0,5]
cadadadadar, 4 => [[0,[0,[0,[0,[4]]]]]]
caaaaaaaaar, 2 => [[[[[[[[[[2]]]]]]]]]]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 40 bytes
```
f=lambda s,*l:s[3:]and f(s[1:],l,*l)or l
```
[Try it online!](https://tio.run/##TY3NjsIwDITvfQorJ0BF2vJziZQDD8Gp6sE4qRph3KppF@3Td50CEsll/M2MPfxNXS@HZWkd4@PmEVK5Y5vqo21QPLSbVFe2KVnpth@Bl2cXOUBlC02KizLM02ZbAIPL4VJUD2OUCbiAVhsEUSAv2VeNliC2QM4ZNHlYa1z/NKoDvy3/benx1Uthha/V5ip36Z8C1OGINIXRlECfw@ZCFFIKHn6R5wAxWbV5MYQ5dywMee9XfVaN/v0zOGXweRkc/gE "Python 2 – Try It Online")
Doesn't bother telling car from cdr. Instead, makes a big nested tuple where every path ends at the right value, assuming it has the right length and ends in `a`. For example,
```
f("cdddar", 5) = ((((5,), 5), (5,), 5), ((5,), 5), (5,), 5)
```
is the same as `f("caaaar", 5)` or `f("cdadar", 5)`. So, only the length of the input string matters.
This is done by repeating the transformation `l -> (l,*l)`, which puts `l` as both the car and cdr of the new tuple. This happens once for each character in `s` except the first three, starting from a singleton of the input value.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
RA"¸ Ć"‡.V
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/yFHp0A4FhSNtSo8aFuqF/bflUuIKSy3KTMtMTizJzM@zUlDS4Tq089CKQ8sUyhQq7ZUUdO0UlOwVKpUSU5SULuw9tAyi0bb2f3JiChQWcZkAAA "05AB1E – Try It Online")
```
R # reverse the input
A # push the lower case alphabet
"¸ Ć"‡ # transliterate, replace:
# - "a" with "¸" (wrap)
# - "c" with " " (noop)
# - "d" with "Ć" (enclose, append the first value)
.V # evaluate as 05AB1E code, the leading r reverses the empty stack
```
---
Porting [xnor's construction](https://codegolf.stackexchange.com/a/233416/64121) comes in at 5 bytes:
```
g<GDš
```
[Try it online!](https://tio.run/##AVMArP9vc2FiaWX//2c8R0TFof9dPQoiClZlcmlmaWNhdGlvbjogIiwKwrnCqMKmIHYgeT8iIC0@ICI/IHkiYWQiItC9wqYi4oChLlY9ff9jZGRkYXIKNQ "05AB1E – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~10~~ 9 bytes
```
(nH₂[w|⁰J
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E1%B8%A2%28nH%E2%82%82%5Bw%7CJ&inputs=car%0A2&header=&footer=)
Wow, using hexadecimal conversion actually helped save a byte. Exits with an error, but outputs the required list wrapped in a list.
## Explained
```
(nH₂[w|⁰J
( # for each character `n` in the remnants:
nH # convert to hexadecimal
₂ # is that divisible by 2?
[ # if so:
w # wrap the TOS in a list ([TOS])
| # else:
⁰J # join the TOS and the next input
```
[Answer]
# [J](http://jsoftware.com/), 47 41 bytes
```
4 :0
".'y',~(}.}:x)rplc a`,:`d,<'(,{.)'
)
```
[Try it online!](https://tio.run/##VYxNDoIwEIX3PcWLm6EJNgZxU@zGA3gBYgKhrWIMmEKMBvHqCCj@zGzmfZP3HbvOKhlCLthM0I38h9eKVl65O58ypIkvE@2vyfMbwYnxbrsRcOZiXGWgc2eyOi8L2NKhNlWdF3vWf5XEn/Euvs5IUtoI3YrexoaOEoglTHYoscNcIh78sIxRprVOHY1mrPr8Ccsh6PdOMBzgNBMMwNjoJqXodXn/XYuQIxrpT9ki4N0T "J – Try It Online")
* `(}.}:x)` Kill the c and r
* `rplc a`,:`d,<'(,{.)'` In what remains, replace `a` with enlist `,:` (another nesting level) and replace `d` with `(,{.)` (append first element)
* `".'y',~` Evaluate the resulting verb on the right arg `y`
[Answer]
# [Ruby](https://www.ruby-lang.org/), 48 bytes
```
f=->s,n{s[0]='';s<?r?s>?b?[0]+f[s,n]:[f[s,n]]:n}
```
[Try it online!](https://tio.run/##KypNqvz/P81W165YJ6@6ONog1lZd3brYxr7IvtjOPskeKKCdFg2Ui7WKhtCxVnm1/8szMnNSFdJTS4q5FBSKdRTyFGwVVOL1igtyMksU1HUU1IHCBQogDQp5eiX58ZmxXKl5Kf@TE4t0FIy5klNSUkAsU67kxBQoBHJNgFwYAHKNAA "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
F⮌η≡ιd≔⁺⟦⁰⟧θθa≔⟦θ⟧θP⭆¹θ
```
[Try it online!](https://tio.run/##RYq9CsIwFEb3PsUl0w1UUMTFTj5AQXQMGS5pbAKhP7lpHcRnjykK8nH4hnOMo2hGCjk/xgh4s6uNbNFJCfz0yThAL@FVGWILohNnuDD7fsBrWBjVXtcwy43ml9A/UbP@mnfVLiH5Kfoh4T2V61ua8LBZ2eSs1LGGU4mF6agsCp13a/gA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⮌η≡ι
```
Loop over the `cdadadr` string in reverse and switch on each character.
```
d≔⁺⟦⁰⟧θθ
```
If it's a `d` then prepend a `0`.
```
a≔⟦θ⟧θ
```
If it's an `a` then wrap the value in a list.
```
P⭆¹θ
```
Stringify the final result. (For some reason, outputting using Charcoal's default output format produces a meaningless result.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
W;$L}¡ḢḢ
```
[Try it online!](https://tio.run/##y0rNyan8/z/cWsWn9tDChzsWAdH////N/ienJKYkFgEA "Jelly – Try It Online")
Based on xnor's idea.
*-1 byte thanks to Jonathan Allan*
] |
[Question]
[
This question is similar to [Biggest Square in a grid](https://codegolf.stackexchange.com/questions/152305/biggest-square-in-a-grid).
**Challenge**
Given a matrix of `1` and `0` in a string format `"xxxx,xxxxx,xxxx,xx.."` or array format `["xxxx","xxxx","xxxx",...]`, You will create a function that determines the area of the largest square submatrix that contains all `1`.
A square submatrix is one of equal width and height, and your function should return the area of the largest submatrix that contains only `1`.
**For Example:**
Given `"10100,10111,11111,10010"`, this looks like the following matrix:
1 0 1 0 0
1 0 1 **1 1**
1 1 1 **1 1**
1 0 0 1 0
You can see the bolded `1` create the largest square submatrix of size 2x2, so your program should return the area which is 4.
**Rules**
* Submatrix must be one of equal width and height
* Submatrix must contains only values `1`
* Your function must return the area of the largest submatrix
* In case no submatrix is found, return `1`
* You can calculate the area of the submatrix by counting the number of `1` in the submatrix
**Test cases**
**Input:** `"10100,10111,11111,10010"` **Output:** `4`
**Input:** `"0111,1111,1111,1111"` **Output:** `9`
**Input** `"0111,1101,0111"` **Output:** `1`
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes win.
[Answer]
# [Haskell](https://www.haskell.org/), ~~113 121 118~~ 117 bytes
```
x!s=[0..length x-s]
t#d=take t.drop d
f x=last$1:[s*s|s<-min(x!0)$x!!0!0,i<-x!!0!s,j<-x!s,all(>'0')$s#i=<<(s#j)x,s>0]
```
[Try it online!](https://tio.run/##HcbBCoMgGADgu0/xS0I1TPQ6tBeJDrJsWWajX5iHvbtbO3zwLRY3F0IpmaIZpBDBxWdaIHc4klRNJtnNQRLTebxgIjNkEywmpu4D3vCDutt9bDKVLcuUSiq5191/yNdryG0ITV/LumVYeaN1g9XaZo69HMtufQQDPiZ32kcCBrgcbxAw/wQfHRaplCJKSUWufQE "Haskell – Try It Online")
-3 bytes thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni?tab=profile)!
-1 byte thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn?tab=profile)!
+8 bytes for the ridiculous requirement of returning 1 for no all-1s sub-matrix..
### Explanation/Ungolfed
The following helper function just creates offsets for `x` allowing to decrement them by `s`:
```
x!s=[0..length x-s]
```
`x#y` will drop `y` elements from a list and then take `x`:
```
t#d=take t.drop d
```
The function `f` loops over all possible sizes for sub-matrices in order, generates each sub-matrix of the corresponding size, tests whether it contains only `'1'`s and stores the size. Thus the solution will be the last entry in the list:
```
-- v prepend a 1 for no all-1s submatrices
f x= last $ 1 : [ s*s
-- all possible sizes are given by the minimum side-length
| s <- min(x!0)$x!!0!0
-- the horizontal offsets are [0..length(x!!0) - s]
, i <- x!!0!s
-- the vertical offsets are [0..length x - s]
, j <- x!s
-- test whether all are '1's
, all(>'0') $
-- from each row: drop first i elements and take s (concatenates them to a single string)
s#i =<<
-- drop the first j rows and take s from the remaining
(s#j) x
-- exclude size 0...........................................
, s>0
]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~35~~ ~~34~~ 32 bytes
```
{⌈/{×⍨⍵×1∊{∧/∊⍵}⌺⍵ ⍵⊢X}¨⍳⌊/⍴X←⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRT4d@9eHpj3pXPOrdeni64aOOrupHHcv1gTRQoPZRzy4gpQDEj7oWRdQeAqra/KinS/9R75aIR20TQEr@/3cDsqhgENejvqlAJtC0iRqGCgYKIGygCWUCIYhpiGAaQJRoAgA "APL (Dyalog Unicode) – Try It Online")
[Adám's SBCS has all of the characters in the code](https://github.com/abrudz/SBCS)
Explanation coming eventually!
[Answer]
# [Haskell](https://www.haskell.org/), ~~99~~ 97 bytes
```
b s@((_:_):_)=maximum$sum[length s^2|s==('1'<$s<$s)]:map b[init s,tail s,init<$>s,tail<$>s]
b _=1
```
Checks if input is a square matrix of just ones with `s==('1'<$s<$s)`, if it is, answer is length^2, else 0. Then recursively chops first/last column/row and takes the maximum value it finds anywhere.
[Try it online!](https://tio.run/##RYtNCoMwEIX3nmIoghFEki7FlF6gJxAbEio11KTiRNpF754mpliYv/e9N6PExzBN3ivAMyGiEWUobuRbm9XkuJpuGuzdjYDX4wc5JwUr2hxDlX1j5Ayq01Y7wMpJPYUVVZufko5HnykQnHkjtQUO4ecigMyLtq5W9eu53LDMAKA7MMZgb0oPkVaJ0o3@yN@BnQWX0ZjZkjT9hBlHyvT@Cw "Haskell – Try It Online")
[Answer]
# [K (ngn/k)](https://github.com/ngn/k), ~~33~~ 28 bytes
```
{*/2#+/|/',/'{0&':'0&':x}\x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlpL30hZW79GX11HX73aQE3dSh1EVNTGVNT@L7GqVomurCuySlOosE7Iz7bWSEhLzMyxrrCutC7SjK3lKonWMFQwUABhA2sICwitDRUM4SwDiLymtUksSDmaEnRa09oSQxmQbW0AkzaM/Q8A "K (ngn/k) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 33 27 bytes
-6 bytes thanks to FrownyFrog!
```
[:>./@,,~@#\(#**/)@,;._3"$]
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D/ayk5P30FHp85BOUZDWUtLX9NBx1ov3lhJJfa/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCsYKpiiHQCBCGkIYYECoD02KiYKKCTRkSRJiOqhTJhv8A "J – Try It Online")
## Explanation:
I'll use the first test case in my explanation:
```
] a =. 3 5$1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
```
I generate all the possible square submatrices with size from 1 to the number of rows of the input.
`,~@#\` creates a list of pairs for the sizes of the submatrices by stitching `,.` togehter the length of the successive prefixes `#\` of the input:
```
,~@#\ a
1 1
2 2
3 3
```
Then I use them to cut `x u ;. _3 y` the input into submatrices. I already have `x` (the list of sizes); `y` is the right argument `]` (the input).
```
((,~@#\)<;._3"$]) a
┌─────┬─────┬─────┬───┬─┐
│1 │0 │1 │0 │0│
│ │ │ │ │ │
│ │ │ │ │ │
├─────┼─────┼─────┼───┼─┤
│1 │0 │1 │1 │1│
│ │ │ │ │ │
├─────┼─────┼─────┼───┼─┤
│1 │1 │1 │1 │1│
└─────┴─────┴─────┴───┴─┘
┌─────┬─────┬─────┬───┬─┐
│1 0 │0 1 │1 0 │0 0│ │
│1 0 │0 1 │1 1 │1 1│ │
│ │ │ │ │ │
├─────┼─────┼─────┼───┼─┤
│1 0 │0 1 │1 1 │1 1│ │
│1 1 │1 1 │1 1 │1 1│ │
├─────┼─────┼─────┼───┼─┤
│ │ │ │ │ │
└─────┴─────┴─────┴───┴─┘
┌─────┬─────┬─────┬───┬─┐
│1 0 1│0 1 0│1 0 0│ │ │
│1 0 1│0 1 1│1 1 1│ │ │
│1 1 1│1 1 1│1 1 1│ │ │
├─────┼─────┼─────┼───┼─┤
│ │ │ │ │ │
│ │ │ │ │ │
├─────┼─────┼─────┼───┼─┤
│ │ │ │ │ │
└─────┴─────┴─────┴───┴─┘
```
For each submatrix I check if it consist entirely of 1s:
`(#**/)@,` - flatten the matrix, and mutiply the number of items by their product. If all items are 1s, the result will be their sum, otherwise - 0:
```
(#**/)@, 3 3$1 0 0 1 1 1 1 1 1
0
(#**/)@, 2 2$1 1 1 1
4
((,~@#\)(+/**/)@,;._3"$]) a
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
0 0 0 0 0
0 0 4 4 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
```
Finally I flatten the list of results for each submatrix and find the maximum:
`>./@,`
```
([:>./@,,~@#\(+/**/)@,;._3"$]) a
4
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 63 bytes
```
p (1..l=$_=~/,|$/).map{|i|/#{[?1*i]*i*(?.*(l-i+1))}/?i*i:1}.max
```
[Try it online!](https://tio.run/##KypNqvz/v0BBw1BPL8dWJd62Tl@nRkVfUy83saC6JrNGX7k62t5QKzNWK1NLw15PSyNHN1PbUFOzVt8@UyvTyrAWqLDi/39DA0MDAx0gaWioY2gIJg2AQlxwAQQBEzMw1DEAc//lF5Rk5ucV/9fNAwA "Ruby – Try It Online")
Ruby version of my [Python answer](https://codegolf.stackexchange.com/a/163441/78274). Golfier as a full program. Alternatively, an anonymous lambda:
# [Ruby](https://www.ruby-lang.org/), ~~70~~ 68 bytes
```
->s{(1..l=s=~/,|$/).map{|i|s=~/#{[?1*i]*i*(?.*(l-i+1))}/?i*i:1}.max}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664WsNQTy/Htti2Tl@nRkVfUy83saC6JrMGJKBcHW1vqJUZq5WppWGvp6WRo5upbaipWatvn6mVaWVYC1RbUfu/QCEtWsnQwNDAQAdIGhrqGBqCSQOgkFIsF1gaLo4g0KQMDHUMkEWVYv8DAA "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
+2 to handle no-all-1 sublist present output
```
ẆZṡ¥"L€$ẎȦÐfL€Ṁ²»1
```
**[Try it online!](https://tio.run/##y0rNyan8///hrraohzsXHlqq5POoaY3Kw119J5YdnpAG4jzc2XBo0////6OjDXUMdEDYIFYHygZCMNsQiW0AURUbCwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hrraohzsXHlqq5POoaY3Kw119J5YdnpAG4jzc2XBo06Hdhv8PtwN5//9HR0cb6hjogLBBrA6UDYRgtiES2wCiKjZWh0shOhpDFVYWNrUGYBZMLDYWAA "Jelly – Try It Online")
### How?
```
ẆZṡ¥"L€$ẎȦÐfL€Ṁ²»1 - Link: list of lists of 1s and 0s
Ẇ - all slices (lists of "rows") call these S = [s1,s2,...]
$ - last two links as a monad:
L€ - length of each (number of rows in each slice) call these X = [x1, x2, ...]
" - zip with (i.e. [f(s1,x1),f(s2,x2),...]):
¥ - last two links as a dyad:
Z - transpose (get the columns of the current slice)
ṡ - all slices of length xi (i.e. squares of he slice)
Ẏ - tighten (to get a list of the square sub-matrices)
Ðf - filter keep if:
Ȧ - any & all (all non-zero when flattened?)
L€ - length of €ach (the side length)
Ṁ - maximum
² - square (the maximal area)
»1 - maximum of that and 1 (to coerce a 0 found area to 1)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 143 bytes
```
%`$
,;#
+%(`(\d\d.+;#)#*
$1¶$&¶$&#
\G\d(\d+,)|\G((;#+¶|,)\d)\d+
$1$2
)r`((11)|\d\d)(\d*,;?#*)\G
$#2$3
1,
#
Lv$`(#+).*;\1
$.($.1*$1
N`
-1G`
^$
1
```
[Try it online!](https://tio.run/##RYw9DsIwDIV3X8Mucn6o8sqYgTEL4gQRClIZWBgqxNRz9QC9WEiRAMl@evr8ydPteX9cUTtNpXZFyEcm12nRPOaxd5ENWxKsi@y2Zcopj@3ovJlzUo3s1mX2Jo9tXDNlIDMVVaAJ7YdpsvXxyNbkRMKDHAiemE4vKcrO9DZmkPQqPayAzoX2SIUuQqgVASH4loAHPhkaoh/4x5cF@K29AQ "Retina – Try It Online") Link includes test cases. Takes input as comma-separated strings. Explanation:
```
%`$
,;#
```
Add a `,` to terminate the last string, a `;` to separate the strings from the `#`s and a `#` as a counter.
```
+%(`
)
```
Repeat the block until no more subsitutions happen (because each string is now only one digit long).
```
(\d\d.+;#)#*
$1¶$&¶$&#
```
Triplicate the line, setting the counter to 1 on the first line and incrementing it on the last line.
```
\G\d(\d+,)|\G((;#+¶|,)\d)\d+
$1$2
```
On the first line, delete the first digit of each string, while on the second line, delete all the digits but the first.
```
r`((11)|\d\d)(\d*,;?#*)\G
$#2$3
```
On the third line, bitwise and the first two digits together.
```
1,
#
```
At this point, each line consists of two values, a) a horizontal width counter and b) the bitwise and of that many bits taken from each string. Convert any remaining `1`s to `#`s so that they can be compared against the counter.
```
Lv$`(#+).*;\1
$.($.1*$1
```
Find any runs of bits (vertically) that match the counter (horizontally), corresponding to squares of `1`s in the original input, and square the length.
```
N`
```
Sort numerically.
```
-1G`
```
Take the largest.
```
^$
1
```
Special-case the zero matrix.
[Answer]
# JavaScript, 92 bytes
```
a=>(g=w=>a.match(Array(w).fill(`1{${w}}`).join(`..{${W-w}}`))?w*w:g(w-1))(W=a.indexOf`,`)||1
```
```
f=
a=>(g=w=>a.match(Array(w).fill(`1{${w}}`).join(`..{${W-w}}`))?w*w:g(w-1))(W=a.indexOf`,`)||1
console.log(f('0111,1111,1111,1111'));
console.log(f('10100,10111,11111,10010'));
console.log(f('0111,1101,0111'));
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~21~~ 20 bytes
```
×⍨{1∊⍵:1+∇2×/2×⌿⍵⋄0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Dk4emPeldUGz7q6HrUu9XKUPtRR7vR4en6QPyoZz9Q6FF3i0Ht//8lQKXVIG7nwiIgM@1R7y4r9fxsdaC0elpiZo46UAAoXVTLpfGot@/QikdtE9UNDQwNDNQVQLShIYg2hNIGQAl1zRIFEyTFSGrQKKBCS2wKDUCUAVSFIQA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~117~~ 109 bytes
Credit to @etene for pointing out an inefficiency that cost me an additional byte.
```
lambda s:max(i*i for i in range(len(s))if re.search(("."*(s.find(',')-i+1)).join(["1"*i]*i),s))or 1
import re
```
[Try it online!](https://tio.run/##bYyxDgIhEET7@wpCc7uIhLU08UvUAj3w1nhwgSv065FYnImxecW8mZlfy5jirobDqT7cdBmcKPvJPYEVi5CyYMFRZBdvHh4@QkHkILI3xbt8HQGkkQqKCRwH6HWPW94QorknjnCUJBWfFaNuu3ZGHU9zyks7qHPmuIgAkixZqxuJNNGHtkUSu7Wyui/@aEva/hqJ9Q0 "Python 2 – Try It Online")
Takes input as a comma-separated string. This is a regex-based approach that tries matching the input string against patterns of the form `111.....111.....111` for all possible sizes of the square.
In my calculations, doing this with an anonymous lambda is just a tad shorter than defined function or a full program. The `or 1` part in the end is only necessary to handle the strange edge case, where we must output `1` if there are no ones in the input.
[Answer]
# [Python 2](https://docs.python.org/2/), 116 115 117 109 bytes
*Credits to @Kirill for helping me golf it even more and for his clever & early solution*
*Edit*: Golfed 1 byte by using a lambda, I didn't know assigning it to a variable didn't count towards the byte count.
*Edit 2*: Kirill pointed out my solution didn't work for cases where the input only contains `1`s, I had to fix it and lost two precious bytes...
*Edit 3*: more golfing thanks to Kirill
Takes a comma separated string, returns an integer.
```
lambda g:max(i*i for i in range(len(g))if re.search(("."*(g.find(",")+1-i)).join(["1"*i]*i),g))or 1
import re
```
[Try it online!](https://tio.run/##TYzBDoIwDIbvPEXTU4eTrB5JfBL1MIVBDWxkctCnn8Mg2uT/k35pv@k198Efkjue02DHa2Ohq0f7JCkFXIggIB6i9V1LQ@upU0ocxLZ6tDbeeiKssKSucuIbQo1qx3tRqroH8XRCxlIupSid/7KMCxmnEOcsSJsc2bAxOjezZv60yQg14MZ@9YcNa/Ml2bBmWdfjJVgXkGeK4mcQDY5EpTc "Python 2 – Try It Online")
I independently found an answer that is close to Kiril's one, i.e regex based, except that I use `re.search` and a `def`.
It uses a regex built during each loop to match an incrementally larger square and returns the largest one, or 1.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~61~~ ~~60~~ 58 bytes
```
{(^$_ X.. ^$_).max({[~&](.[|$^r||*])~~/$(1 x$r)/&&+$r})²}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiNOJV4hQk9PAUhr6uUmVmhUR9epxWroRdeoxBXV1GjFatbV6atoGCpUqBRp6qupaasU1Woe2lT7vzixUiFNQ6@4ICezRENdR11TUyEtv4hLydDA0MBAB0gaGuoYGoJJA6CQkg6XElwMQSAJGxjqgFhK1v8B "Perl 6 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~138~~ 128 bytes
```
def f(m):j=''.join;L=j(m);k=map(j,zip(*m));return len(L)and max(len(L)*(len(m)**2*'1'==L),f(k[1:]),f(k[:-1]),f(m[1:]),f(m[:-1]))
```
[Try it online!](https://tio.run/##bY5BDoIwEEX3noLddBo0HZaQ3oAbEBYklEhxSkMwUS9fC9VojKv35/2/GH9fz7MrQujNkA2CsbQa4GTn0VW1tlFUk@bOC5s/Ri8kI1aLWa@Lyy7GiRo712fc3US65E5GKQsJBFrXmA9iaqhsUyiPtCd@K04Kg19Gt8YXGiBFSkG@kWgjvahiAS0ePtOvxQ/@z9QGlfrwBA "Python 2 – Try It Online")
---
Saved
* -10 bytes thanks to ovs
[Answer]
## Clojure, 193 bytes
```
#(apply max(for [f[(fn[a b](take-while seq(iterate a b)))]R(f next %)R(f butlast R)n[(count R)]c(for[i(range(-(count(first R))n -1)):when(apply = 1(for[r R c(subvec r i(+ i n))]c))](* n n))]c))
```
Wow, things escalated :o
Less golfed:
```
(def f #(for [rows (->> % (iterate next) (take-while seq)) ; row-postfixes
rows (->> rows (iterate butlast) (take-while seq)) ; row-suffixes
n [(count rows)]
c (for[i(range(-(count(first rows))n -1)):when(every? pos?(for [row rows col(subvec row i(+ i n))]col))](* n n))] ; rectangular subsections
c))
```
] |
[Question]
[
Given a list of scores (non-negative integers) pre-sorted from greatest to least:
```
[ 10, 10, 6, 6, 4, 0]
```
Assign each score an integer rank, beginning with 1 and ascending, such that equal scores have the same rank (i.e. they are tied):
```
[ 1, 1, 3, 3, 5, 6 ]
```
In the case of ties, ranks are "skipped," e.g. since the first and second-greatest scores (10 and 10) are tied, they both have rank 1, and rank 2 is "skipped," so the third-greatest score (6) has rank 3.
Output a list of non-descending ranks corresponding to the input scores.
## Examples
```
In: 10 10 6 6 4 0
Out: 1 1 3 3 5 6
```
```
In: 10 9 8
Out: 1 2 3
```
```
In: 0 0 0
Out: 1 1 1
```
```
In: 16 15 15 12 11 11 10 9 9 9 8 2 2 2 0
Out: 1 2 2 4 5 5 7 8 8 8 11 12 12 12 15
```
## Input
Assume all scores will be between 0 and 1,000 inclusive, and the input will have no more than 500 scores. Input can be in whatever format is convenient for your language of choice (including but not limited to STDIN, arguments to a function, an array already stored in a variable, etc.).
## Output
Return or store in a variable the resulting ordered list of ranks, or write it to STDOUT in a human-readable way (e.g. `1 2 3`, `[1,2,3]`, `1\n2\n3\n`, and `{ 1, 2, 3 }` are all fine; `123` is not, for want of a delimiter). The input scores may be stored/printed along with their corresponding output ranks, but that's not required.
## Restrictions
You may use any standard library your language offers. [Standard loopholes apply.](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny)
## Winning conditions
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the smallest program (in bytes) wins. In case of a tie, the answer with the most votes wins.
### Notes
This is based on a [Ruby question on SO](https://stackoverflow.com/q/25042260/179125) that generated some interesting answers, including one very short one. I encourage you to come up with your own solutions before looking there.
[Answer]
# J (~~7~~ 6)
EDIT: Oh, wait! It doesn't need to be a function!
```
>:i.~y
```
Thank god for `i.~`...
```
>:@:i.~
```
Or as a named function (3 chars more, but not functionally different):
```
f=:>:@:i.~
```
Run tests:
```
f=:>:@:i.~
f 10 10 6 6 4 0
1 1 3 3 5 6
f 10 9 8
1 2 3
f 0 0 0
1 1 1
f 16 15 15 12 11 11 10 9 9 9 8 2 2 2 0
1 2 2 4 5 5 7 8 8 8 11 12 12 12 15
```
[Answer]
## T-SQL (40)
```
SELECT RANK()OVER(ORDER BY B DESC)
FROM @
```
Assume `@` is a table containing the scores as rows.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 6
```
m'XYdY
```
List is stored in Y to begin with. This is functionally the same as the 22 character ruby solution: map over d in Y to index of d in Y plus 1, then print.
Example:
```
$ echo "=Y[16 15 15 12 11 11 10 9 9 9 8 2 2 2 0)m'XYdY" | python3 pyth.py
[1, 2, 2, 4, 5, 5, 7, 8, 8, 8, 11, 12, 12, 12, 15]
```
[Answer]
# Python (33 characters)
```
lambda x:[1+x.index(i)for i in x]
```
Functionally the same as my J answer.
[Answer]
## APL, 2 bytes
```
⍳⍨
```
In `⎕IO←1`. Dyadic iota searches its right argument into its left argument. The operator `⍨` copies the right argument to the left argument if the operand is used monadically. Hence the solution simply searches the position of each one of the elements of the vector given in itself.
Samples:
```
⍳⍨10 10 6 6 4 0
1 1 3 3 5 6
⍳⍨0 0 0
1 1 1
⍳⍨16 15 15 12 11 11 10 9 9 9 8 2 2 2 0
1 2 2 4 5 5 7 8 8 8 11 12 12 12 15
```
[Answer]
# STATA (16)
```
egen b=rank(c),f
```
Result is in b.
Assumes c is a variable in the dataset containing the input.
[Answer]
## Haskell (31)
```
f x=succ.(`elemIndexJust`x)<$>x -- Requires the Safe module
```
**Usage:**
```
f [10,10,6,6,4,0] --evaluates to [1,1,3,3,5,6]
```
[Answer]
So as to establish a baseline:
# Ruby (38)
Assuming `a` is an array:
```
r,i=1,0;a.map{|x|i+=1;x==a[i-2]?r:r=i}
```
(This is based on [falsetru's answer](https://stackoverflow.com/a/25042417/179125) on the original SO thread and isn't my original work. I know there's a Ruby solution that's 22 characters, but I'd like to see someone come up with one shorter than that in Ruby.)
[Answer]
# JavaScript (E6) 41
A function with an array argument, returning an array
```
F=s=>s.map((n,i)=>p-n?(p=n,r=i+1):r,p=-1)
```
**Test** In Firefox console
```
F([10,10,6,6,4,0])
```
Output: [1, 1, 3, 3, 5, 6]
```
F([16, 15, 15, 12, 11, 11, 10, 9, 9, 9, 8, 2, 2, 2, 0])
```
Output: [1, 2, 2, 4, 5, 5, 7, 8, 8, 8, 11, 12, 12, 12, 15]
[Answer]
## R, 15
with input stored as vector `x`,
```
rank(-x,T,"mi")
```
[Answer]
## Powershell (70)
```
$n=1;$c=0;$l=$a[0];$a|%{if($l-eq$_){$n}else{$n=$c+1;$n}$l=$a[$c];$c++}
```
It's only 51 characters if you take out the variable assignments at the beginning, which makes me feel slightly less inadequate.
Assumes $a is assigned and sorted as specified by the problem. $n tracks rank, $c is just a counter which works with $l, the last element checked in the array.
If there's anything I can do to improve this, I'd love to know.
[Answer]
# Java (57)
Using the same 'rules' as [Allbeert](https://codegolf.stackexchange.com/a/35543/23519):
Constant `i` is defined as `int[]` array and contains the input, `z` contains the size of the input. Others, `l`,`c`,`x` and `n`, are defined as `int`.
The left over snippet of code is:
```
l=0;c=1;for(x=0;x<z;x++){n=i[x];i[x]=n==l?c:(c=x+1);l=n;}
```
The result is in the input array.
[Answer]
# Ruby, 22
I haven't looked at the SO thread but I imagine this is what they came up with.
```
a.map{|i|a.index(i)+1}
```
Edit: Yep, it is. I doubt it's possible to get smaller in Ruby, unless you assume you're defining it as an Array method, then you can do it in 18 characters with
```
map{|i|index(i)+1)
```
But of course the full program around that snippet looks like
```
class Array
def ranks
map{|i|index(i)+1)
end
end
p [1, 2, 2, 4, 5, 5, 7, 8, 8, 8, 11, 12, 12, 12, 15].ranks
```
[Answer]
# [><>](http://esolangs.org/wiki/Fish) (47)
Not particularly optimized, just testing the water with my first golf.
```
r:1:nr2&>ao$:@=?vr~&:|
&1+&l3)?^; >r:nr
```
Assumes that the input is prepopulated in the stack, such that the first element of the input is the first to be popped off.
Testing:
```
fish.py ranks.fish -v 1 2 3 4 5 6 7 8 9 9 10 10
```
outputs
```
1
1
3
3
5
6
7
8
9
10
11
12
```
[Answer]
# Clojure, 35
With some Java interop mixed in:
```
(fn[l](map #(+ 1(.indexOf l %)) l))
```
REPL session:
```
golf> ((fn[l](map #(+ 1(.indexOf l %)) l)) [10 10 6 6 4 0])
(1 1 3 3 5 6)
golf> ((fn[l](map #(+ 1(.indexOf l %)) l)) [16 15 15 12 11 11 10 9 9 9 8 2 2 2 0])
(1 2 2 4 5 5 7 8 8 8 11 12 12 12 15)
```
[Answer]
# C - 62
As a code snippet, since there was no requirement for function or full program.
Assumes `a`, `n`, `j`, and `k` are already defined as `int*`, `int`, `int`, and `int` respectively, where `a` is an array containing the input, and `n` contains the length of the input.
This fails for input of length 0, in which case 3 more characters are needed.
```
printf("1");for(k=j=1;++j<=n;)printf(" %d",*a-*(a+++1)?k=j:k);
```
] |
[Question]
[
**Inputs**
A list (array) of numbers, or numerical strings if that makes it easier. You can assume there will always be at least two elements in the list and every element will be a natural number (integer larger than zero).
### Outputs
A single number, or again, a numerical string.
### Problem
The idea is to reduce the list of numbers by removing the last digit of the largest number at that current stage of the list, eventually ending with one number (only one number should be returned, even if there are multiple instances)
### Example
```
[123,343,121,76,465,786] -- The last digit in 786 is dropped, so it becomes 78
[123,343,121,76,465,78] -- New largest number is 465, so the 5 is dropped, making it 46
[123,343,121,76,46,78] -- Repeat until left with one number
[123,34,121,76,46,78]
[12,34,121,76,46,78]
[12,34,12,76,46,78]
[12,34,12,76,46,7]
[12,34,12,7,46,7]
[12,34,12,7,4,7]
[12,3,12,7,4,7]
[1,3,1,7,4,7] -- If there are multiple max numbers, you **must** remove the last digit from all of them
[1,3,1,4]
[1,3,1]
[1,1] -- You have your answer when there is one number, or multiple numbers that are equal
1 -- Result
```
### Loopholes
[Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
### Other constraints
Your program **must** work for any list of random numbers (within reason of course)
### Test Cases
```
[24,72,4]
[24,7,4]
[2,7,4]
[2,4]
[2]
2
[14, 7]
[1, 7]
[1]
1
[1278,232,98273,2334]
[1278,232,9827,2334]
[1278,232,982,2334]
[1278,232,982,233]
[127,232,982,233]
[127,232,98,233]
[127,232,98,23]
[127,23,98,23]
[12,23,98,23]
[12,23,9,23]
[12,2,9,2]
[1,2,9,2]
[1,2,2]
[1]
1
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in every language wins!
[Answer]
# [Haskell](https://www.haskell.org/), 16 bytes
```
minimum.map head
```
[Try it online!](https://tio.run/##HYtBC4IwAIXv/orHvBSo0BRmgoFIeKkQopMNGaRt5IaYnaLfvqaXB99735Pi/eqGwX5DH6fiUt2K6oiyrgE//Hl9lqG5zpMyT47wgFKKyevzu9XKKP3RkRYjZCceVgtlkMPxucVmdI8ZEfotGjSEJiQgjLpICEfgmp1rQBjhK1CWuo3Gi7FPKYtXiheZ2z8 "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 24 bytes
*-4 bytes thanks to notjagan.*
```
lambda l:min(zip(*l)[0])
```
[Try it online!](https://tio.run/##TY7BDoIwEETv/Yq9lRoOdou0kPAl2ANGiU1KIdCL/nyli4nuYSfzdibZ5RWfc8A0dtfkh@l2H8C3kwvF2y3FyYv@bEWKjy1u0EHPYJ@eS1S8BK4qEokyi67zruoLGVNzW37jWBFCuv@wPPAfQG0yQkXRxqBWh1d7jVnGxnkFBy4AfdRSb1ldiDAWTqQP "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~24, 21~~, 18 bytes
```
lambda l:min(l)[0]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHHKjczTyNHM9og9n9BUWZeiUaaRrSSoZGxko6CkrEJmDI0MgRR5mYg0sTMFMyxMFOK1dTkQugxMgGLG4EVockZQuTQRY3MLUDiRsZgTZYWRubGEL4x2ID/AA "Python 3 – Try It Online")
~~Three~~ Six bytes saved thanks to @totallyhuman!
[Answer]
# Mathematica, 29 bytes
```
Min[First@*IntegerDigits/@#]&
```
[Answer]
# [Japt](http://ethproductions.github.io/japt/), ~~8~~ ~~6~~ 5 bytes
*-1 byte thanks to @Shaggy*
```
n g g
```
Takes input as an array of numeric strings. [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=biBnIGc=&input=WyIxMjc4IiwiMjMyIiwiOTgyNzMiLCIyMzM0Il0=)
## Explanation
```
// implicit input: array of strings
n // sort the array
g // get the first element
g // get the first character
// implicit output
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
€нW
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UdOaC3vD//@PNjLRMTfSMYkFAA "05AB1E – Try It Online")
[Answer]
# [PHP](https://php.net/), 45 bytes
```
<?foreach($_GET as$v)$r[]=$v[0];echo min($r);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKUS7@4aYhutZGhkrKSjZGwCIg2NDIGkuRmQMDEzBTEtzJRirf@n5RelJiZnaID1KCQWq5RpqhRFx9qqlEUbxFqnJmfkK@Rm5mmoFGla//8PAA "PHP – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~11~~, 5 bytes
```
ÚxV}p
```
[Try it online!](https://tio.run/##K/v///CsirDagv//DY3MLbiMjI24LC2MzI2BLGMTAA "V – Try It Online")
I was making this *waaay* more complicated than it actually is. This answer simply sorts every line by ASCII values, and then returns the very first character. Since this is kind or a boring answer, here is a more interesting answer that actually implements the algorithm originally described:
# [V](https://github.com/DJMcMayhem/V), 11 bytes
```
òún
/äîä
Lx
```
[Try it online!](https://tio.run/##K/v///Cmw7vyuPQPLzm87vASLp@K//8NTbjMAQ "V – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~3~~ 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṂḢ
```
A full program which takes a list of lists of characters (strings) and prints the result.
**[Try it online!](https://tio.run/##y0rNyan8///hzqaHOxb9//8/WsnQyFhJR8nYBEQaGhkCSXMzIGFiZgpiWpgpxQIA "Jelly – Try It Online")**
### How?
We just need to return the smallest leading digit...
```
ṂḢ - Main link: list of lists of characters
Ṃ - minimum (lexicographical ordering ensures this will start with the minimal digit)
Ḣ - head (get that first digit character)
```
[Answer]
# JavaScript (ES6), 17 bytes
Takes input as an array of strings.
```
a=>a.sort()[0][0]
```
---
## Try it
Input a comma separated list of numbers.
```
o.innerText=(f=
a=>a.sort()[0][0]
)((i.value="1278,232,98273,2334").split`,`);oninput=_=>o.innerText=f(i.value.split`,`)
```
```
<input id=i><pre id=o>
```
[Answer]
# [,,,](https://github.com/totallyhuman/commata/), 3 [bytes](https://github.com/totallyhuman/commata/wiki/Code-page)
```
⫰1⊣
```
## Explanation
```
⫰1⊣
⫰ pop the whole stack and push the minimum element
1 push 1
⊣ pop the minimum and 1 and push the first character of it
```
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), 17 bytes
```
VVR{Mvd<M&$_R}vvx
```
[Try it online!](https://tio.run/##SypKzMxLz89J@/8/LCyo2rcsxcZXTSU@qLasrOL///@GRsb/jU2MgbThf3Oz/yZmpv/NLcwA "Braingolf – Try It Online")
## Explanation
```
VVR{Mvd<M&$_R}vvx Implicit input from commandline args
VVR Create stack2 and stack3, return to stack1
{.........} Foreach item in stack..
M ..Move item to next stack
v ..Switch to next stack
d ..Split item into digits
<M ..Move first item to next stack
&$_ ..Clear stack
R ..Return to stack1
vv Switch to stack3
x Reduce to lowest value
Implicit output of last item on stack
```
In other words, it constructs a stack consisting of only the first digit of each item, then outputs the lowest.
This challenge gave me a bunch of useful ideas for builtins to add to Braingolf, and now thanks to the addition of the "special" foreach loop, Braingolf can do it in 5 bytes:
# [Braingolf](https://github.com/gunnerwolf/braingolf), 5 bytes [non-competing]
```
(d<)x
```
## Explanation
```
(d<)x Implicit input from commandline args
(..) Special foreach loop, iterates over the stack, moving each item to a special
Sandboxed stack environment, and prepends the last item of the sandboxed
stack to the real stack at the end of each iteration
d< Split into digits, move first digit to end of stack
x Reduce to lowest value
Implicit output of last item on stack
```
[Try it online!](https://tio.run/##SypKzMxLz89J@/9fI8VGs@L///@mRv@NjM3/mxgBAA "Braingolf – Try It Online")
I'm normally against adding builtins *just* to complete one challenge, but I can see a plethora of uses for the new `(...)` foreach loop, so I don't really consider it adding a feature just for this challenge.
[Answer]
# [Funky](https://github.com/TehFlaminTaco/Funky), 18 bytes
```
x=>x::sort()[0][0]
```
Takes input as a list of strings.
[Try it online!](https://tio.run/##SyvNy678n2b7v8LWrsLKqji/qERDM9ogFoj@FxRl5pVopGlUK5kZKekoGRqZAkkLpVpNzf8A "Funky – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 5 bytes
Takes the list of input numbers as command-line arguments.
```
@@SSg
```
[Try it online!](https://tio.run/##K8gs@P/fwSE4OP3///@GRsb/jU2MgbThf3Oz/yZmpv/NLcwA "Pip – Try It Online")
Alternately:
```
MN@Zg
```
[Try it online!](https://tio.run/##K8gs@P/f188hKv3///@GRsb/jU2MgbThf3Oz/yZmpv/NLcwA "Pip – Try It Online")
### Explanations
In both programs, `g` is the list of command-line args.
```
@@SSg
```
`SS` sorts using string comparison, thus putting the numbers with smallest first digits first, regardless of their magnitudes. Unary `@` gives the first element of a list or scalar. We apply it twice to get the first digit of the first number after sorting.
```
g [24 72 491]
SS [24 491 72]
@ 24
@ 2
```
Alternately:
```
MN@Zg
```
`Z` is zip; its unary version can be used to transpose a list. The first element of the transposed list is a list of the first digits of all the numbers. `@` gets that list of digits; `MN` takes its minimum.
```
g [24 72 491]
Z [[2 7 4] [4 2 9]]
@ [2 7 4]
MN 2
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~9~~ 7 bytes
```
hSmsh`d
```
[Try it online!](https://pyth.herokuapp.com/?code=hSmsh%60d&input=%5B1278%2C232%2C98273%2C2334%5D&debug=0)
**Explanation**
This basically return the smallest leading digit.
```
Q # Implicit input
msh`d # For each number in Q, convert to string, take the first character, convert to integer
hS # Return the minimum
```
[Answer]
# [Python 3](https://docs.python.org/3/), 33 bytes
```
lambda l:min(str(x)[0]for x in l)
```
[Try it online!](https://tio.run/##VYsxDsIwDAB3XuExkTwQ28ShEi8pHUoRIlKaViFDeX2ABanb6XS3vutzydymy7Wlcb7dR0jdHLN51WI22x@Hx1Jgg5gh2baWmKuZTO@IkYXRkUP1KP6EGvxg7eGfkKASys45QdC9IQ1ITHgOpPwl/h3tAw "Python 3 – Try It Online")
@DJMcMayhem and @totallyhuman have a better solutions but mine assumes numerical input instead of string.
[Answer]
# **Pyth, 3 bytes**
```
hhS
```
Input is list of string representations of numbers.
[Try It Online](https://pyth.herokuapp.com/?code=hhS&test_suite=1&test_suite_input=%5B%2714%27%2C+%277%27%2C+%2713%27%2C+%2799%27%5D%0A%5B%2724%27%2C%2772%27%2C%274%27%5D%0A%5B%271278%27%2C%27232%27%2C%2798273%27%2C%272334%27%5D%0A%5B%27123%27%2C%27343%27%2C%27121%27%2C%2776%27%2C%27465%27%2C%27786%27%5D&debug=0)
**Explanation:**
```
hhS
# Q=input
S # Sort Q
h # First Element of sorted list
h # First element of string
# Implicitly print result
```
] |
[Question]
[
In March 25, 1821, Greece fought its great [war of independence](https://en.wikipedia.org/wiki/Greek_War_of_Independence). In order to honor this, your task is to print the Greek national anthem:
```
Σε γνωρίζω από την κόψη
του σπαθιού την τρομερή.
Σε γνωρίζω από την όψη
που με βιά μετράει τη γη.
Απ' τα κόκκαλα βγαλμένη,
των Ελλήνων τα ιερά!
Και σαν πρώτα ανδρειωμένη,
χαίρε ω χαίρε Λευτεριά!
Και σαν πρώτα ανδρειωμένη,
χαίρε ω χαίρε Λευτεριά!
Και σαν πρώτα ανδρειωμένη,
χαίρε ω χαίρε Λευτεριά!
```
This is my own version of the anthem (punctuation, capitalization), although the lyrics are the original.
* Any builtins printing or returning this text are forbidden, just in case.
* The printed text must be exactly as above, with an optional trailing newline.
* The output must be in UTF-8, unless it can't be supported at all, in which case the output must be encoded in the closest supported alternative.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~180~~ ~~174~~ 163 bytes
```
60r26;“WSNME‘ȷ_Ọ;“ ¶.',!”“¢Iç÷ṀDė3H⁷'UBV“ñẸḣY]ṭżẸ-dƒjṭ{^ṣ8ḞkƊK“ẈḊbƝÑk?Æ.)Aɱ3ẎƬṠ⁵ʂ÷Gẏp⁴ṇ1ẸR ¬,F°0>ST$[?ṘȦŀẎcFẈṃijȯÆḋ“¦ḟw2ðƊhSẏ¥ẏ5ƒẉɦ⁺Ʋ⁴Ɓ¦ÞIzƥṙḊOḊ-÷~øWḤ0ṃ’ṃ€6676ḃ4¤ị
```
[Try it online!](https://tio.run/nexus/jelly#FY5BSwJRFIX/ikEggcqkNQVBUpQlUUFTSUQF1aJ0E22CgphRsByjyE0KaZE6bSbSqOa9sdV7@Rj7F/f9kenO4h445977cXxVOY2rU1J/zGgry/NSr3rOHvRugiTEvmPhyJDU62jYS5q/cgeoPvf7kFiUhhPemN3EBe@CS4A0t3aAvvV/0EQPRSWL5mIXaHMSSCMnzCW8BPcaiLkv6vw@l@TF2MjMoJsA91bYQJ@l8fWX584CuHcn0vgEejWKqLUQsyMp1lGmtfXh7STQqmf1dfw5SAU0WjjOeu@8CKQcVLSAPJ3FeUeYRxpyWBtlXFTALQ0sabjiA8HCYBZvpM9FG2gN66ziRLlzyUkGSEtBpNRrgeZtVZ1QgRTGWAt6Zd//Bw "Jelly – TIO Nexus")
[Answer]
# [Python 3](https://docs.python.org/3/), 263 bytes
```
s="BT R\h`NUh P_k cV\ %skgV\n"
print(''.join(i if 47>ord(i)else chr(ord(i)+865)for i in s%"Y"+"c^d b_PWX^l cV\ c`^[T`M.\n"+s%""+"_^d [T QXK [Tc`KTX cV RV.\n0_' cP YkYYPZP QRPZ[L\V,\nch\ 4ZZM\h\ cP XT`K!"+"\n9PX bP\ _`mcP P\S`TXh[L\V,\nfPN`T h fPN`T :TdcT`XK!"*3))
```
[Try it online!](https://tio.run/nexus/python3#LczdToNAEAXge59i3KQBxDQm1t9EL7zFNlO64gITdtOluCt1MeD748R6dTKT75x5ehIvEnJyZvPmAHUPtiBYTP1HQUGcfY8@/MRRtPwcfIg9@A5Wd8/D2MY@ORynA1g3xqczvb@9SbphBFYBpoUoRSps08Je47tqjn/D1jS1NOslb6dMWGgWtYStyjisyaRiCHnB5EpHYBHKviyxQtjmWNWvVFxSsI5gVVVr4mShpMnOeYvCAyrYI4E2X/xH2hmp3H@pw42R4OCUj7K10ijuXVwnyTz/Ag "Python 3 – TIO Nexus")
Use the same repetition technique that [mbomb007 used](https://codegolf.stackexchange.com/a/113792), but I replaced all characters higher than 47 (all greek letters), u913~u974 with u48~u109 ,and then undo this before printing
[Answer]
# Java 7, ~~320~~ ~~319~~ ~~300~~ ~~294~~ 293 bytes
```
void Z(){String a="AS Q[g_MTg O^j bU[ ",b="8OW aO[ ^_lbO O[R_SWgZK[U,\neOM_S g eOM_S 9ScbS_WJ!\n";for(char C:(a+"XjfU\nb]c a^OVW]k bU[ b_]ZS_L.\n"+a+"jfU\n^]c ZS PWJ ZSb_JSW bU QU.\n/^' bO XjXXOYO PQOYZK[U,\nbg[ 3YYL[g[ bO WS_J!\n"+b+b+b).toCharArray())System.out.print((char)(C>46?C+866:C));}
```
[Try it online!](https://tio.run/nexus/java-openjdk#1VNBbxJBFL7vr3jupbsB4aBpagkaQkwMFre4xQUW2Mxu6RakS8suJg0hoWkbJakmHrzo0Su2oYpIW9J/8ObXeMY3SzWNF89mDm/em@/75nsvM06T@T6kupIfsKDuzF@16ptQUtSuHrTrngssKad0yJmuld1wQas2wM6bIEftpLyiGcA0E6pW09ZAM59buuGWnpr5aNmraVlLBxcW8YHu2LplZO6UPTmx1WorzjZrQ3pVYRG50NjKlz274gCrai@MysvwAtuqlHRrLUaECIFCTJUwJR3WjQwF28roBkEhlydQvLoE5KHQKBS0ogbrOa14Y8R2TbhXLK6ZFAlh6FboImKLpcaCVpqspNpttq@oqr7vB7WdWKsTxHap@0AJjapK@uH95UfpyMry8mpaVRO9@W7HbtYdWMwMwpntsLqnLIZmVpi/qXYl6WaGqWcbTx5nkzJ@xjHgV5zxAT/AM/zOB4Aj3ucnwI9wgjPAC37C3@Ck7FHhmh8DP@R9HOEPnFL69jeMHxH/Gq9wTPGU@v@38h/dfqgruIDnJDsM96HiEMc4DQlCayJ03/P@kqiMQmt4QWuElyI9J4jYXuEXnOEkKizzgejhA1Uv8VSYCb0K9DS0OqTR40ei0S2HFOi0zw/4uwWGcvxGKDJBzFu6r@noTBwAtXUrw0@kekxkoT3979XlhBSP//0Em55CvzFW2@uwpq8sXhI9QYmKCanXm//0Wncd5mzXfgE "Java (OpenJDK 8) – TIO Nexus")
This outputs the anthem with a trailing newline. I converted the function from returning a `String` to a `void` so that it would print the String instead of returning it and save bytes.
~~Will golf further in the morning~~ Golfers don't sleep :P
### Explanation (outdated)
```
String Z(){
// X contains the value of the Greek Anthem
String X="",
// a and b contain some repeated parts of the anthem
a="AS Q[g_MTg O^j bU[ ",
b="8OW aO[ ^_lbO O[R_SWgZK[U,\neOM_S g eOM_S 9ScbS_WJ!\n";
// Then we loop over every char in this string
for(char C: (a+"XjfU\nb]c a^OVW]k bU[ b_]ZS_L.\n"+a+"jfU\n^]c ZS PWJ ZSb_JSW bU QU.\n/^' bO XjXXOYO PQOYZK[U,\nbg[ 3YYL[g[ bO WS_J!\n"+b+b+b).toCharArray())
// Adding 866 to the char if it is greater than `.` 46
// (we also want to preserve the punctuation)
X+=(char)(C>46?C+866:C);
return X;
}
```
To get to this reduced String, I manually checked subtracting which numbers from the code points would be the best. These values would have to lie between and `~`. In order to make the detection of whether a char is punctuation (`.`, `'`, `!`, ) or not, it would be best if all the values lied above `.` (46). And there shouldn't be any `\`s in the String because otherwise Java thinks they are escape sequences, and so I have to escape them. Finally I came up with subtracting 866 from the Greek characters.
[Answer]
# Python 3, ~~350~~ 345 bytes
```
s="Σε γνωρίζω από την %sόψη\n"
print(s%'κ'+"του σπαθιού την τρομερή.\n"+s%''+"που με βιά μετράει τη γη.\nΑπ' τα κόκκαλα βγαλμένη,\nτων Ελλήνων τα ιερά!"+"\nΚαι σαν πρώτα ανδρειωμένη,\nχαίρε ω χαίρε Λευτεριά!"*3)
```
[**Try it online**](https://tio.run/nexus/python3#TZAxbsJAEEX7nGKzEnKIURpqbsIF0lhRnAMsAhQsOUgUaaCkdUAmGGMbixv8OZL5s1EktMXszPz3Z3a7eGSxRWHwi1YSmWCPkyQGuThJjcxQojW9WFJZoBxH9uHt/TX6eIp7AeogtBRcZW5kKg45zqiYfv1jMqPfFRcUjLsX0iE5pZyntGNwIJT5u9dnKFB5B92pJIWVuEAruUEtKWqeHI2mB0r0esEPWpSDcUSPhKPxzWqDnT7Kb6Lqyi@SPdrQ0nVNkoOmDBQ4mcjyT8YcRwq5B@E760@29tow/KG7DBsazwmrfaUDnof9rrsB)
[Answer]
## Windows 10 Batch, ~~424~~ 404 bytes
```
@chcp>nul 65001
@set s="Σε γνωρίζω από την κόψη"
@set t="Και σαν πρώτα ανδρειωμένη," "χαίρε ω χαίρε Λευτεριά!"
@for %%l in (%s% "του σπαθιού την τρομερή." %s:κ=% "που με βιά μετράει τη γη." "Απ' τα κόκκαλα βγαλμένη," "των Ελλήνων τα ιερά!" %t% %t% %t%) do @echo %%~l
```
Notes:
* Don't use Notepad to save this, it will add a BOM which will cause the script to fail.
* The `chcp` call fails if your Command Prompt is configured to use Raster Fonts. Change them to e.g. Lucida Console (does not require restart).
* The batch file seems to require a reasonably new version of Windows; Windows XP wasn't at all happy with `chcp 65001`.
Edit: Saved 20 bytes thanks to @ConorO'Brien.
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 190 bytes
```
0000000: d5 8e b5 61 04 51 10 43 f3 ad 62 9c 98 ed 16 cd ...a.Q.C..b.....
0000010: cc 4c a1 c3 e3 bb 65 ec 40 6a c9 9a 6f cc 1c df [[email protected]](/cdn-cgi/l/email-protection)...
0000020: f2 8c a4 b7 c2 3b 12 c3 0c 0d 4f b8 83 11 52 9e .....;....O...R.
0000030: 18 26 dc e6 b9 71 1f 19 1a 43 c9 73 1e 23 8b 34 .&...q...C.s.#.4
0000040: 77 3c 30 ee 71 1b 13 e4 28 34 5e 7c b9 f4 52 bc w<0.q...(4^|..R.
0000050: 43 8d 44 ef e1 66 f4 3f f7 9b ba 1d a8 9e 34 4c C.D..f.?......4L
0000060: 05 ed 87 ef c0 eb 23 41 11 fc 8e ca 44 bd e1 f6 ......#A....D...
0000070: 92 2f 26 a1 16 4a 9d 13 54 3e 4e e5 d0 a7 b2 03 ./&..J..T>N.....
0000080: 34 c8 d6 55 97 27 5e ff 01 95 ce 21 1a 1f bf b2 4..U.'^....!....
0000090: 45 a8 d9 5f 88 f0 8a 89 ff 62 4f 2f 89 db dc e1 E.._.....bO/....
00000a0: 65 b0 f8 8c 58 26 35 50 f0 97 7a 24 65 e4 7b e3 e...X&5P..z$e.{.
00000b0: 89 fd 99 f0 26 e6 81 b2 4e 2e e6 99 fd 01 ....&...N.....
```
[Try it online!](https://tio.run/nexus/bubblegum#TZJLaxVBFIT3/oqSSHR10u/pVvFB4kaCUVFwFennwo2IC0H979c6cy@JDTPQw/TXVXXqYI7rKUZEnmgRycIERAtrEDyWRx1IDqWjZMwBm9AHICJVPsilSBNdD3aQJap3hI5q0T2mR2tIEZMfDVJFLygVaelvtmMsoq4VMOXVN5HvdyhH1HLIRAW0Dd3BN1inWNNhBsJCy8ge1iJS4dxViTzT1w2fjyeUJ8pmuITRMRNawUaDC7bAVrVJVRs5E84jN/hA1DkJP/hcyk85k3BEBaK2Db7DG8y5c6iKTgNc1oORH7tesYKqah349dzspCfh9u@9qkgUr840EjAXpkVKesovrA2loVXYgZrVGslMFZdyJbLk5W5UwvURlYgyUaeTN0V1amvqJVgNZ3Udbq96URt60UqnrOTstb6v7mLfiCoObmlcHCLHHSrKUI@R2ibCxIwYBnVDczCeqAuG9Vbk04t3/5UhE0XZPWMkxIiywW2az1owFiWiM3CrI@As2lIagshneXyrlIf3qKJZRY1iFMSFnLEMckUuSmM/WQZq5na0fcoWeCPydZfTbi7uUZUoFrIZrKztinsxfEQ0yqTIrcKFvbQBW9MOY/L4l/P4XuT3oyl/TqhGlAoYKEXPksN2ZatGmJKbui37D/R7WqpEq3VM6nD4Bw "Bubblegum – TIO Nexus")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~332~~ ~~270~~ 261 bytes
```
-join([char[]]"$(($a='=O MWc[IPc KZf ^QW')) TfbQ
^Y_ ]ZKRSYg ^QW ^[YVO[H.
$a fbQ
ZY_ VO LSF VO^[FOS ^Q MQ.
+Z' ^K TfTTKUK LMKUVGWQ,
^cW /UUHWcW ^K SO[F!
$('4KS ]KW Z[h^K KWN[OScVGWQ,
aKI[O c aKI[O 5O_^O[SF!
'*3)"|%{([char](870+$_),$_)[+$_-in10,32,33,39,44,46]})
```
[Try it online!](https://tio.run/nexus/powershell#TVDLDsFQFNz3Ky5pchGxsfYx/uRKCU2QWNiwtC3SUlU0/mDOJ9Wci5C7OK@ZOXNu3QxbrXA4sNghNzihklhGOOIisUEqTuZGxihQ2Xbb4CZzmaEI2HrKxEgkDimuKFkuPkAGKjzxQM546AXh0HxpztN0ZJCRlfjcExLkKL2E2ih6AVbirDZSvxc3vhR3LTMiNH1gjwpFl34k5mas2bzjoFd4IwouvY@k0Qy6FhvyuCVi4NzJSJZvFGuciaMJcn/CU06O2jf8kL8KW8pOyFVxHtKwnX5dvwA "PowerShell – TIO Nexus")
This takes the munged string as a `char`-array, feeds it one at a time through a loop `|%{...}` each iteration either outputting the character straight `$_` or incrementing it by `870` before re-casting as a `char` (based on whether it's a punctuation or not). A few other tricks sets `$a` as a repeat phrase, and de-triplicates the last three stanzas. Those are all `-join`ed together into a full string and then output is implicit.
*Edit - Woo! This is the [1100th PowerShell answer](https://codegolf.stackexchange.com/search?tab=newest&q=powershell%20is%3aa) on the site! :D*
[Answer]
# Japt, ~~197~~ ~~196~~ 195 bytes
```
`0fxtc
pkq ol]¸ky2ci2mk?mZ.
0xtc
lkq ? ^eX ?pmXae2c _c.
=l'2] fxff]g] ^_]g1pui AggZiui2] eamX!`+`
F]e o]i lmzp] ]i\`µeu1s][µ u s][µ Gaqpa´X!`³ d0`Oa _ium[¿ ]lx2ci `1`hYic,
`2" p""[=F-~]"_c +852 d
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=YDBmeHRjCnBrcSBvbF24a3kyY2kybWuVbVouCjB4dGMKbGtxIJUgXmVYIJVwbVhhZTJjIF9jLgo9bCcyXSBmeGZmXWddIF5fXWcxcHVpIEFnZ1ppdWkyXSBlYW1YIWArYApGXWUgb11pIGxtenBdIF1pXGC1ZXUxc11btSB1IHNdW7UgR2FxcGG0WCFgsyBkMGBPYSBfaXVtW78gXWx4MmNpIGAxYGhZaWMsCmAyIiBwIiJbPUYtfl0iX2MgKzg1MiBk&input=) Contains three 0x95 bytes which have been replaced with `?`.
[Answer]
# [///](https://esolangs.org/wiki////), ~~324~~ 323 bytes
```
/P/ρ//p/π//n/η//z/Σε γνωρίζω από τnν //k/Και σαν pPώτα ανδPειωμένn,
χαίPε ω χαίPε ΛευτεPιά!/zκόψn
του σπαθιού τnν τPομεPή.
zόψn
pου με βιά μετράει τn γn.
Αp' τα κόκκαλα βγαλμένn,
των Ελλήνων τα ιεPά!kkk
```
[Try it online!](https://tio.run/nexus/slashes#RVAxTsNAEOz9ik1Fg7JfuX9Ysly7csRFYCkgUdBASWsSOcEJTjj5BzNPMrsOAl1xu3M7Mzs3aVCuVEtlrVooTqqV4h294IDEhivscGQj6FhzI4wFkqjmild0GIR3diUpA58Y0Yl3@AzoMbDBNz6QituM94bvDBWT@m/whp5r4/UBA9qFVjhzw4ciM2zk2tRZ2/CXvY58/HVnDBhN2kjbZVZdCeU876hg72JzzWgBWl/GuZapWGZ4Lm/kuquZ4Wynw8XbvWX28m/raBGS4MWwC7b@H7O9zw5u3y7yPJ@mHw "/// – TIO Nexus")
Maybe it could be golfed more, but I'm tired.
It works by replacing characters like `k` with longer text. I also made some character substitutions, because the Greek characters have more bytes than characters like `p`. Simple enough.
-1 byte thanks to @ErictheOutgolfer.
[Answer]
# Bash + GNU iconv, 214
```
a="�� ������� ��� ��� "
l="
��� ��� ����� �����������,
����� � ����� ��������!"
iconv -f GREEK<<<"$a����
��� ������� ��� �������.
$a���
��� �� ��� ������� �� ��.
��' �� ������� ��������,
��� ������� �� ����!$l$l$l"
```
This just uses the `iconv` utility to convert from the GREEK encoding (byte per char) to utf-8, along with removing a bit of redundancy by storing repetitions in variables.
Don't try to copy directly from the above - lots of unprintables get munged when pasting. Instead, create the script as follows:
```
base64 -d << EOF > greek.sh
YT0i0+Ug4+358d/m+SDh8Pwg9OftICIKbD0iCsrh6SDz4e0g8PH+9OEg4e3k8eXp+ezd7ecsCvfh
3/HlIPkg9+Hf8eUgy+X19OXx6dwhIgppY29udiAtZiBHUkVFSzw8PCIkYer8+OcK9O/1IPPw4ejp
7/0g9OftIPTx7+zl8d4uCiRh/PjnCvDv9SDs5SDi6dwg7OX08dzl6SD05yDj5y4KwfAnIPThIOr8
6urh6+Eg4uPh6+zd7ecsCvT57SDF6+ve7fntIPThIOnl8dwhJGwkbCRsIg==
EOF
```
[Answer]
# PHP, 296 Bytes
```
<?=gzinflate(base64_decode("1Y+9DoJAEIR7Et7hrGyMz3gEiJKgiYWNlrYIAUXkL7zB7Cs5e0ZDZ22u2Nvdme/mcEFtcMMoiQQo8JDEoBQrqZEIDUaDTlLZovE9DiaJjYRiUeKJlu3uI5OI/gkDatZ87Xv4Sf5yreOq16AiNnN3R8xQo3UGZTXKPYhd6qR00dDxlOi1rSjR64ArRjQrjSyJ/uHIaY9cw7isqm5d1GxB5Ik2vhKycGslkP1bwx53qhiCzhl3w1WhC8NvzTqcSY1pVnb75/QX"));
```
## PHP, 349 Bytes
```
echo$y="Σε γνωρίζω από την"," κόψη\nτου σπαθιού την τρομερή.\n$y όψη\nπου με βιά μετράει τη γη.\nΑπ' τα κόκκαλα βγαλμένη,\nτων Ελλήνων τα ιερά!\n".$z="Και σαν πρώτα ανδρειωμένη,\nχαίρε ω χαίρε Λευτεριά!\n",$z.$z;
```
[Answer]
# Python 2.7, 190 bytes
zlib abuse. Hexdump:
```
00000000: efbb bf70 7269 6e74 2278 9cbd 8cb1 0e82 ...print"x......
00000010: 4010 44fb fb8a b5b2 31fc 7f6b 61a3 252d @.D.....1..ka.%-
00000020: 4216 5ccf e5b8 701b 96e8 2568 5ca5 b4b7 B.\...p...%h\...
00000030: 7ac9 cc9b 2909 ba98 a5b9 66c0 b480 fa08 z...).....f.....
00000040: fdf2 f04e c719 a684 371e 9fdf 5065 1c48 ...N....7...Pe.H
00000050: eac2 95bf 838f 9fcc 1f08 5aae 0c2a 15b1 ..........Z..*..
00000060: 55d0 f9c2 edd3 1614 edb5 ef31 20b4 1d86 U..........1 ...
00000070: e11c fdce 698e 7008 a18e 4613 98a4 dab8 ....i.p...F.....
00000080: 2332 4c18 21c9 cb32 8c17 21ce ab7f c746 #2L.!..2..!....F
00000090: 0832 ac3c d1ac 24fc afc9 1bcf bfdc ec22 .2.<..$........"
000000a0: 2e64 6563 6f64 6528 227a 6970 2229 2e64 .decode("zip").d
000000b0: 6563 6f64 6528 2267 7265 656b 2229 ecode("greek")
```
As @Dennis points out, this needs to be run in a terminal in order for it to correctly produce UTF-8 output.
[Answer]
## [Retina](https://github.com/m-ender/retina), 199 bytes
```
:pkq olWdeky=ci=mkhamT._:lkq ha XeR hapmRae=c Yc._0l'=W fxffWgW XYWghSic,_pui 4ggTiui=W eamR!###
:
Ia YiumUbu Wlx=ci fxtc_
#
_9We oWi lmzpW WiZmaeuhSic,_;u ;AaqpameR!
=
p
;
sWUma
2=`f
T`w`¶Α-ώ
```
[Try it online!](https://tio.run/nexus/retina#JY0xbsJAEEX7OcUgF2nAiqI0sbUFJa1jNDjNeljW9so7YlGyCskhkLgMB@AAcCSzEtWX/tN/f4IijAfce9rZ8U8Zp2QcWOpcFz71A@PGVimCVGyVwcbk@tW/KMLu2HXUE24a6odPZ@Y6RIfvfV@76BK3LNUsyzIoYMXYuCjrbUTyx3SSxj9GQwb6gyzuyaGX/0BI7kvYxqeujFgu@RBYbDUDBRighG9aCyO8qbYDqNvf9nq5nRf30zQ9AA "Retina – TIO Nexus")
Woohoo, just under 200 bytes.
### Explanation
The main idea is to avoid the actual Unicode characters for the most part, because they just blow up the byte count if they are used everwhere. Instead, I represent each Greek letter by an ASCII letter or digit. It turns out that the relevant letters from `Α` (that's an alpha) to `ώ` span exactly 62 code points. That's 10 + 26 + 26, the number of ASCII digits and letters. The other Unicode character we've got is `¶`, which Retina uses to represent linefeeds. We can save a few more bytes by replacing that with `_`. Then the shorthand `w` in transliteration stages contains exactly the 63 characters we've used as substitutions, and we can represent the range this is mapped to using only 3 2-byte characters (`¶` and the two ends of the Greek letter range).
Hence, the code is fairly illegible for the most part, since this substitution is done in the very last stage. Let's undo this to make a bit more sense of the code:
```
:του σπαθιού=ην=ρομερή.¶:που με βιά μετράει=η γη.¶Απ'=α κόκκαλα βγαλμένη,¶των Ελλήνων=α ιερά!###
:
Σε γνωρίζω από=ην κόψη¶
#
¶Και σαν πρώτα ανδρειωμένη,¶;ω ;Λευτεριά!
=
τ
;
χαίρε
2=`κ
```
That looks a bit more like the stuff we want to output. The very first stage simply sets up the overall framework. It contains all the unique parts of the output as well as some more placeholders for repeated parts:
* `:` stands for the first and third line. They end up being *slightly* different, because the `κ` is missing from the third line, which is why the very last stage removes the second `κ` in the result.
* `#` stands for the last two lines, which are repeated three times.
* `;` stands for the repeated `χαίρε` in those lines.
* `=` stands for a word beginning with `τ` (and the space preceding it). There are *just* enough of those for this to save a single byte.
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~194~~ 187 bytes
```
00000000: d58e 3542 0541 1005 f33d c590 e070 45dc ..5B.A...=...pE.
00000010: dd2d 2444 d77d f706 f5ae c4f4 a019 f18f .-$D.}..........
00000020: daab 8b47 7247 4aaf 3dad f146 a13d 47ac ...GrGJ.=..F.=G.
00000030: 551d 3a6d 52d2 3b1a 1d6a 9732 f2f5 a82d U.:mR.;..j.2...-
00000040: a70d ad12 5351 fbf2 e87b 4b9b 5a63 a423 ....SQ...{K.Zc.#
00000050: d71a afcb d1ff dc6f ea6a a0da a523 a1e6 .......o.j...#..
00000060: 39e4 81f7 4c4e 1df6 0d55 7aea 9956 67ac 9...LN...Uz..Vg.
00000070: 1107 2d1a 1a62 5a2b 13d2 9076 bcd0 532e ..-..bZ+...v..S.
00000080: 7a5d ed99 fe15 2d2d aff4 567e ddd6 e486 z]....--..V~....
00000090: 9f8a b827 b617 1bc4 365c d59a 8ec3 8ad5 ...'....6\......
000000a0: 645a 3303 edfd a1ee 10f3 667d a73d f7a7 dZ3.......f}.=..
000000b0: e281 5c5b da0c e47a 92d9 1f ..\[...z...
```
You can reverse this hexdump with `xxd -r`.
Thanks Dennis for redirecting me to Zopfli :)
[Answer]
# Jolf, 187 bytes
Being encoded in the greek codepage helps.
```
ΆΆγ"Σε γνωρίζω από την κόψη
'του σπαθιού την τρομερή.
"-γ'κ«που με βιά μετράει τη γη.
Απ' τα κόκκαλα βγαλμένη,
των Ελλήνων τα ιερά!
»*3"Και σαν πρώτα ανδρειωμένη,
χαίρε ω χαίρε Λευτεριά!
```
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zobOhs6zIs6jzrUgzrPOvc-Jz4HOr862z4kgzrHPgM-MIM-EzrfOvSDOus-Mz4jOtwonz4TOv8-FIM-Dz4DOsc64zrnOv8-NIM-EzrfOvSDPhM-Bzr_OvM61z4HOri4KIi3OsyfOusKrz4DOv8-FIM68zrUgzrLOuc6sIM68zrXPhM-BzqzOtc65IM-EzrcgzrPOty4KzpHPgCcgz4TOsSDOus-MzrrOus6xzrvOsSDOss6zzrHOu868zq3Ovc63LArPhM-Jzr0gzpXOu867zq7Ovc-Jzr0gz4TOsSDOuc61z4HOrCEKwrsqMyLOms6xzrkgz4POsc69IM-Az4HPjs-EzrEgzrHOvc60z4HOtc65z4nOvM6tzr3OtywKz4fOsc6vz4HOtSDPiSDPh86xzq_Pgc61IM6bzrXPhc-EzrXPgc65zqwhCg) *It's all greek to me...*
[Answer]
# [Python 3](https://docs.python.org/3/), 246 bytes
```
q=b'Qc akwo]dw _nz rek '
print(''.join(chr(b+b//63*850)for b in
q+b'hzve\nrms qn_fgm{ rek romjco\.\n'+q+b"zve\nnms jc `gZ jcroZcg re ae.\n?n' r_ hzhh_i_ `a_ij[ke,\nrwk Cii\kwk r_ gcoZ!"+b'\nH_g q_k no|r_ _kbocgwj[ke,\nu_]oc w u_]oc IcsrcogZ!'*3))
```
[Try it online!](https://tio.run/nexus/python3#Lc0xT8NADAXgvb/C7XJJg1qkCsSCOnSBkTVc5eZMermcYpMrcFLgvwerML3B33uex0dnXgiamOX4lgF5gtRGMIv3FPijMGbTS@CCulS4ym2397v1w91teZYEDgIvxsqZbvpqLafhAiPj2Q/f14kkQ09iN5ZNpWp1RayoJzj5WiNJTV4tNK2qPRtICN3UdRgQTg2G/jW2N7qcIxxCsFFThSeplyv9a/kJPYwYgeVHDxidkM//rU88CkGGv3ymSyLx9dKsd2U5z78 "Python 3 – TIO Nexus")
My take on [Rod’s](https://codegolf.stackexchange.com/a/113795/3852) approach.
] |
[Question]
[
Given 3 bytes or RGB as input, calculate the nearest CMYK values, and output them.
* create either a function with parameters and return value or a program that operates on stdin/stdout
* use the color profile of your choice, but provide a reference
* input may be either separate numeric values in range [0;255] or a 6 digit hex string
* output should be separate numeric values ranging either [0;1] or [0;100]
* standard code golf: [no loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default), shortest code wins
* extravagant ideas are welcome
sample data:
```
input output
108,174,106 [0.3793103448275862, 0.0, 0.3908045977011494, 0.3176470588235294]
0,0,0 0,0,0,1
170,255,238 33,0,7,0
0x0088ff 1,0.4667,0,0
[250,235,215] [0,6,14,1.96]
#123456 .7907,.3953,0,.6627
```
* Uncalibrated mapping is fine and probably the easiest
* No input validation required; floats are allowed (ranging from 0 to 255), but may also be rounded
* Output format should be either clearly commented or obvious; i.e.:
1. CMYK in that order
2. does not matter if percentage [0;100] or pure numbers [0;1]
* Testing should include the trivial example [0,0,0].
[This site](http://codebeautify.org/rgb-to-cmyk-converter) has the most digits of online tools that I could find. Does anyone know a tool that gives more than 4 digits?
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~16~~ 15 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
```
1-⊢(÷,255÷⍨⊢)⌈/
```
1 minus `1-`
***X*** divided by `÷` ***Y***, followed by `,` 255 dividing `255÷⍨` ***Y*** `⊢`, where
***X*** is itself `⊢` (i.e. the list of RGB values), and
***Y*** is the max `/⌈` (of the RGB values).
$$
\begin{cases}
J = max(R,G,B)\\
C = 1-\frac{R}{J}\\
M = 1-\frac{G}{J}\\
Y = 1-\frac{B}{J}\\
K = 1-\frac{J}{255}\\
\end{cases}
$$
[TryAPL!](http://tryapl.org/?a=f%u21901-%u22A2%28%F7%2C255%F7%u2368%u22A2%29%u2308/%20%u22C4%20f%20108%20174%20106&run)
**Credits:**
∘ -1 byte by [ngn](https://codegolf.stackexchange.com/users/24908/ngn).
[Answer]
# [C#](https://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29), ~~88~~ ~~86~~ ~~85~~ 84 bytes
```
(r,g,b)=>{float[]a={r,g,b,1};var j=a.Max();a[3]=j*j/255;return a.Select(x=>1-x/j);};
```
output for `108,174,106`:
```
0.3793104
0
0.3908046
0.3176471
```
Since OP allows function I submitted only the lambda. You can find a running demo on [.NetFiddle](https://dotnetfiddle.net/alJ6Ah). I am not a golfer, I post for fun. Also, it is my first answer \o/. Feel free to comment any improvement :)
Kudos to Leaky Nun for the formula.
caveat: it doesn´t work for [0,0,0] (thank you Titus)
[Answer]
# Python, 46 bytes
```
lambda*c:[1-i/max(c)for i in c]+[1-max(c)/255]
```
Requires input to be floats in Python 2, fairly sure it doesn't in 3.
[Answer]
## JavaScript (ES6), ~~58~~ 51 bytes
```
a=>[...a.map(e=>1-e/m||1,m=Math.max(...a)),1-m/255]
```
Accepts an array `[R, G, B]` (add 7 bytes for separate parameters) and returns an array `[C, M, Y, K]` using the uncalibrated colour mapping.
[Answer]
## Mathematica, ~~36~~ ~~28~~ 33 bytes
```
List@@ColorConvert[{##}/255,"CMYK"]&
```
~~After liberalization of I/O formats, golfed further: `List@@#~ColorConvert~"CMYK"&`~~
Anonymous function, that does what is asked.
The old function takes three arguments from 0 to 255 (anything beyond this range will be automatically clipped to this range) and returns an array of "CMYK" values between `0.` and `1.`
Example (for old function):
```
List @@ ColorConvert[{##}/255, "CMYK"] &[108, 174, 106]
```
>
>
> ```
> {0.37931, 0., 0.390805, 0.320313}
>
> ```
>
>
Since arrays are allowed as input, **33 bytes:**
```
List@@ColorConvert[#/255,"CMYK"]&
```
*Of course* the *built-in* function handles `{0, 0, 0}` properly and returns `{0, 0, 0, 1}`.
[Answer]
# Bash + ImageMagick, 69 bytes
```
convert "xc:$1[1x1]" -colorspace cmyk txt:-|grep -o '([^)]*)'|head -1
```
Example:
```
$ ./rgb2cmyk.sh "#6CAE6A"
(38%,0%,39%,32%)
$ ./rgb2cmyk.sh "#000000"
(0%,0%,0%,100%)
$ ./rgb2cmyk.sh "#AAFFEE"
(33%,0%,7%,0%)
$ ./rgb2cmyk.sh "#0088ff"
(100%,47%,0%,0%)
$ ./rgb2cmyk.sh "#FAEBD7"
(0%,6%,14%,2%)
$ ./rgb2cmyk.sh "#123456"
(79%,40%,0%,66%)
```
[Answer]
# SmileBASIC, ~~73~~ 72 bytes
```
INPUT R,G,B
J=MAX(R,G,B)IF!J THEN?0,0,0,1 ELSE?1-R/J,1-G/J,1-B/J,1-J/255
```
Could be much shorter.
[Answer]
# Pyth, ~~24~~ ~~21~~ ~~18~~ ~~24~~ 21 bytes
Life is a round trip, indeed.
```
~~=cR255Q+mc--1dK-1JeSQJQK~~
~~=cR255Q+mc-JeSQdJQ-1J~~
~~+mc-JeSQdJQ-1cJ255~~
~~+mc-JeSQd+J^T\_15Q-1cJ255~~
+m-1?JeSQcdJ1Q-1cJ255
```
[Test suite.](http://pyth.herokuapp.com/?code=%2Bm-1%3FJeSQcdJ1Q-1cJ255&test_suite=1&test_suite_input=108%2C174%2C106%0A0%2C0%2C0&debug=0)
Sample input: `108,174,106`
Sample output: `[0.3793103448275862, 0.0, 0.3908045977011494, 0.3176470588235294]`
Sample input: `0,0,0`
Sample output: `[0, 0, 0, 1.0]`
Formula used:
$$
\begin{cases}
J = max(R,G,B)\\
C = 1-\frac{R}{J}\\
M = 1-\frac{G}{J}\\
Y = 1-\frac{B}{J}\\
K = 1-\frac{J}{255}\\
\end{cases}
$$
Old formula: <https://i.stack.imgur.com/ZtPD6.gif>
Old formula: <https://i.stack.imgur.com/Nqi9F.gif>
[Answer]
## [Lithp](https://github.com/andrakis/node-lithp), 114 bytes
```
#R,G,B::((var J(max R G B))(if(!= 0 J)((list(- 1(/ R J))(- 1(/ G J))(- 1(/ B J))(- 1(/ J 255))))((list 0 0 0 1))))
```
[Try it online!](https://andrakis.github.io/lithp-webide/?code=KAogICAgKGltcG9ydCBsaXN0cykKICAgIAogICAgJSBSZWFkYWJsZSB2ZXJzaW9uCiAgICAoZGVmIGNteWstcmVhZGJsZSAjUixHLEIgOjogKAogICAgICAgICh2YXIgSiAobWF4IFIgRyBCKSkKICAgICAgICAoaWYgKCE9IDAgSikgKAogICAgICAgICAgICAobGlzdCAoLSAxICgvIFIgSikpICAgICAlIEMgPSAxIC0gKFIgLyBKKQogICAgICAgICAgICAgICAgICAoLSAxICgvIEcgSikpICAgICAlIE0gPSAxIC0gKEcgLyBKKQogICAgICAgICAgICAgICAgICAoLSAxICgvIEIgSikpICAgICAlIFkgPSAxIC0gKEIgLyBKKQogICAgICAgICAgICAgICAgICAoLSAxICgvIEogMjU1KSkpICAlIEsgPSAxIC0gKEogLyAyNTUpCiAgICAgICAgKSAoKGxpc3QgMCAwIDAgMSkpKQogICAgKSkKICAgIAogICAgJSBnb2xmZWQKICAgIChkZWYgY215ayAjUixHLEI6OigodmFyIEoobWF4IFIgRyBCKSkoaWYoIT0gMCBKKSgobGlzdCgtIDEoLyBSIEopKSgtIDEoLyBHIEopKSgtIDEoLyBCIEopKSgtIDEoLyBKIDI1NSkpKSkoKGxpc3QgMCAwIDAgMSkpKSkpCiAgICAKICAgIChwcmludCAoY215ayAxMDggMTc0IDEwNikpCiAgICAocHJpbnQgKGNteWsgMCAwIDApKQogICAgKHByaW50IChjbXlrIDE3MCAyNTUgMjM4KSkKICAgIChwcmludCAoY215ayAyNTAgMjM1IDIxNSkpCik=)
* Saved 6 bytes (forgot that `max` takes any number of arguments)
I'm not quite sure this is right. The first two results with the sample data are correct, but the rest are not (see the [Try it online](https://andrakis.github.io/lithp-webide/?code=KAogICAgKGltcG9ydCBsaXN0cykKICAgIAogICAgJSBSZWFkYWJsZSB2ZXJzaW9uCiAgICAoZGVmIGNteWstcmVhZGJsZSAjUixHLEIgOjogKAogICAgICAgICh2YXIgSiAobWF4IFIgRyBCKSkKICAgICAgICAoaWYgKCE9IDAgSikgKAogICAgICAgICAgICAobGlzdCAoLSAxICgvIFIgSikpICAgICAlIEMgPSAxIC0gKFIgLyBKKQogICAgICAgICAgICAgICAgICAoLSAxICgvIEcgSikpICAgICAlIE0gPSAxIC0gKEcgLyBKKQogICAgICAgICAgICAgICAgICAoLSAxICgvIEIgSikpICAgICAlIFkgPSAxIC0gKEIgLyBKKQogICAgICAgICAgICAgICAgICAoLSAxICgvIEogMjU1KSkpICAlIEsgPSAxIC0gKEogLyAyNTUpCiAgICAgICAgKSAoKGxpc3QgMCAwIDAgMSkpKQogICAgKSkKICAgIAogICAgJSBnb2xmZWQKICAgIChkZWYgY215ayAjUixHLEI6OigodmFyIEoobWF4IFIgRyBCKSkoaWYoIT0gMCBKKSgobGlzdCgtIDEoLyBSIEopKSgtIDEoLyBHIEopKSgtIDEoLyBCIEopKSgtIDEoLyBKIDI1NSkpKSkoKGxpc3QgMCAwIDAgMSkpKSkpCiAgICAKICAgIChwcmludCAoY215ayAxMDggMTc0IDEwNikpCiAgICAocHJpbnQgKGNteWsgMCAwIDApKQogICAgKHByaW50IChjbXlrIDE3MCAyNTUgMjM4KSkKICAgIChwcmludCAoY215ayAyNTAgMjM1IDIxNSkpCik=).)
Uses the implementation described nicely as follows:
$$
\begin{cases}
J = max(R,G,B)\\
C = 1-\frac{R}{J}\\
M = 1-\frac{G}{J}\\
Y = 1-\frac{B}{J}\\
K = 1-\frac{J}{255}\\
\end{cases}
$$
[Answer]
# PHP 7, ~~123~~ ~~110~~ 105 bytes
**Input as RGB color `100 240 75`**
```
$j=max($h=$argv);echo strtr(@(1-$h[1]/$j).",".@(1-$h[2]/$j).",".@(1-$h[3]/$j).",".(1-$j/255),["NAN"=>0]);
```
Outputs CMYK values as decimal in `0...1` range.
Saved lots of bytes thanks to Titus.
Sample usage:
```
php -r '$j=max($h=$argv...' 100 240 75
0.58333333333333,0,0.6875,0.058823529411765
php -r '$j=max($h=$argv...' 255 255 255
0,0,0,0
php -r '$j=max($h=$argv...' 0 255 0
1,0,1,0
php -r '$j=max($h=$argv...' 0 0 0
0,0,0,1
```
[Test online](http://sandbox.onlinephpfunctions.com/code/d5a56352fd3f7cf7a6f75fdc9e3143b57af97425)
---
**Input as HEX color `#123456`, 202 bytes**
```
$h=str_split(substr($argv[1],-6),2);$j=max($r=hexdec($h[0]),$g=hexdec($h[1]),$b=hexdec($h[2]));echo z($r,$j),",",z($g,$j),",",z($b,$j),",",1-$j/255;function z($c,$y){return is_nan(@($c/$y))?0:1-$c/$y;}
```
54 bytes for function to prevent division by zero, probably golfable or removable.
Gets as input RGB color as HEX `#123456` and outputs CMYK as decimal in `0...1` range.
Sample usage:
```
php -r '$h=str_split...' '#000000'
0,0,0,1
php -r '$h=str_split...' '#ffffff'
0,0,0,0
php -r '$h=str_split...' '#123456'
0.7906976744186,0.3953488372093,0,0.66274509803922
php -r '$h=str_split...' '#ffff00'
0,0,1,0
```
[Answer]
# PHP, not competing
I was just too tempted to post my own.
**RGB input, 74 bytes**
```
for(;$i++<4;)echo$i<4?($j=max($argv))?1-$argv[$i]/$j:0:1-$j/255,","[$i>3];
```
or 68 bytes with a trailing comma in the output: remove `[$i>3]`.
Run with `php -r '<code>' <red-value> <green-value> <blue-value>`.
**HEX input, 100 bytes**
```
foreach($a=array_map(hexdec,str_split($argv[1],2))as$c)echo($j=max($a))?1-$c/$j:0,",";echo 1-$j/255;
```
Run with `php -nr '<code>' RRGGBB`.
That approach would take 75 bytes for RGB input:
replace `foreach($a=array_map...as$c)` with `foreach($a=$argv as$c)if($i++)`.
[Answer]
# C, 155 bytes
```
#define C(x) 1-x/(j>0?j:1)
#define F float
i=0;F j;f(F r,F g,F b){j=(r>g?r:g)>b?(r>g?r:g):b;for(;i++<4;)printf("%f\n",i>1?i>2?i>3?1-j/255:C(b):C(g):C(r));}
```
I'm trying to figure out how it's possible golf more.
## Usage:
```
#define C(x) 1-x/(j>0?j:1)
#define F float
i=0;F j;f(F r,F g,F b){j=(r>g?r:g)>b?(r>g?r:g):b;for(;i++<4;)printf("%f\n",i>1?i>2?i>3?1-j/255:C(b):C(g):C(r));}
main(){
f(108,174,106);
}
```
### Output:
```
0.379310
0.000000
0.390805
0.317647
```
[Answer]
## [Hoon](https://github.com/urbit/urbit), 110 bytes
```
=>
rs
|*
a/*
=+
[s=(cury sub .1) j=(roll a max)]
(welp (turn a |*(* (s (min .1 (div +< j))))) (s (div j .255)))
```
Use the single precision floating-point library.
Create a new generic function that takes `a`.
Set `s` to `sub` curried with `.1` for later, and `j` to folding over `a` with `max`.
Map over `a` by dividing each element with `j`, finding the minimum of that and 1 to normalize NaN, then subtract 1 with `s`. Add `1-j/255` to the end of that list.
```
> =f =>
rs
|*
a/*
=+
[s=(cury sub .1) j=(roll a max)]
(welp (turn a |*(* (s (min .1 (div +< j))))) (s (div j .255)))
> (f (limo ~[.108 .174 .106]))
[i=.3.7931037e-1 t=[i=.0 t=[i=.3.908046e-1 .3.1764704e-1]]]
> (f (limo ~[.0 .0 .0]))
[i=.0 t=[i=.0 t=[i=.0 .1]]]
```
] |
[Question]
[
## Background
Imagine that I'm creating a really long necklace, consisting of only two characters, `A` and `B`. You must count the number of occurrences of the substring `AB` in the string.
However, since it's a necklace, you must also consider if the last character and the first character join to make `AB`. For example, in `BBBA`, there would be 1 occurrence of `AB`, as the final `A` would join to the first `B`.
Finally, since I'm not finished making the chain, you must continually accept an input. Every successive input after the first is intended to be appended to the current necklace. You must also provide the output for the entire appended necklace after each input. Due to I/O limitations however, these inputs will be given as an array.
## Your Task
* Sample input: An array consisting of strings consisting of **any two different characters of your choosing**, only. You must clarify in your answer what the substring you're checking for is (which is of length two, and contains both of the distinct characters you're using). You may not use a boolean array.
* Output: The number of occurrences of the substring, as an array of outputs.
**Explained Examples**
```
Input => Output
ABABA => 2
ABABA => 4
The chain at the second output would be ABABAABABA, which contains 4 ABs.
```
```
Input => Output
BA => 1
BABA => 3
BB => 3
BAAAAB => 4
The chain at the second output would be BABABA, which contains 3 ABs including the A at the end and the B at the start.
The chain at the third output would be BABABABB, which contains 3 ABs
The chain at the fourth output would be BABABABBBAAAAB, which contains 4 ABs
```
**Test Cases**
```
Input => Output
ABABA => 2
ABABA => 4
//
BA => 1
BABA => 3
BB => 3
BAAAAB => 4
//
AB => 1
AAA => 1
B => 2
AB => 3
//
BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB => 1
A => 2
B => 2
A => 3
A => 3
B => 3
//
BABABABABABAB => 6
A => 7
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. (# of bytes)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
¦ƛǏ₀O
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLCpsabx4/igoBPIiwiIiwiW1wiMDFcIiwgXCIwMTAxXCIsIFwiMDBcIiwgXCIwMTExMFwiXSJd)
Uses the characters `1` and `0`, checks for substring `10`.
## Explained
```
¦ƛǏ₀O­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌­
¦ƛ # ‎⁡To each prefix of the input:
Ǐ # ‎⁢ Append the first character to the end
₀O # ‎⁣ And count the number of instances of "10" in that
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# JavaScript (ES6), 117 bytes
```
k=>{for(let i=1;i<=k.length;i++)console.log(((s=k.slice(0,i).join('')).match(/01/g)||[]).length+!(+s.at(-1)-~-s[0]))}
```
Uses `0` instead of A and `1` instead of B.
I could probably get rid of the first/last character special case by appending the first character at the end [like Vyxal did](https://codegolf.stackexchange.com/a/263244/95204) using `(k.slice(0,i).join('')+k[0][0]).match(/01/g)` instead of `(s=k.slice(0,i).join('')).match(/01/g)` but I can't be bothered to rewrite my terrible explanation
# Explained
```
// Take k ['01010', '01010']
// Convert it to s '01010'
// Then in the next loop s='0101001010'
// In s, count the occurences of 01
// Then count special case of first/last characters
// k has length N
k=>{for(let i=1;i<=k.length;i++) // Loop 'i' from 1 to N inclusive
console.log( // Output:
(
(s=k.slice(0,i).join('')) // Get bracelet up to current 'i'
.match(/01/g) // List of occurences of '01'
||[] // Default to empty list
).length // Get length
+
!(+s.at(-1)-~-s[0]) // Is +s.at(-1)-~-s[0] equal to 0?
// (implicitly) convert to number
)}
```
## But what is `!(+s.at(-1)-~-s[0])`?
`s.at(-1)` is the last element of s, and for the rest... well... I just threw a bunch of random stuff in there until it worked; please don't tell my coding teacher
## With test cases
```
const f=
k=>{for(let i=1;i<=k.length;i++)console.log(((s=k.slice(0,i).join('')).match(/01/g)||[]).length+!(+s.at(-1)-~-s[0]))}
`
ABABA => 2
ABABA => 4
//
BA => 1
BABA => 3
BB => 3
BAAAAB => 4
//
ABABA => 2
ABABA => 4
//
BA => 1
BABA => 3
BB => 3
BAAAAB => 4
//
AB => 1
AAA => 1
B => 2
AB => 3
//
BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB => 1
A => 2
B => 2
A => 3
A => 3
B => 3
//
BABABABABABAB => 6
A => 7
`.slice(1,-1).replaceAll('A','0').replaceAll('B','1').split('\n//\n').forEach(testCase => {
const parts = testCase.split('\n').map(x=>x.split(' => '));
const input_ = parts.map(x=>x[0]);
console.log('\n\nInput:',input_,'\nExpected output:');
parts.forEach(x=>console.log(+x[1]));
console.log('Output:');
f(input_);
});
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands/2649a799300cbf3770e2db37ce177d4a19035a25), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ηJεĆT¢
```
I/O as a list. Uses characters `1` and `0` for `A` and `B` respectively.
Uses the legacy version of 05AB1E, because the new version of 05AB1E has [a bug with multi-digit integers and the count builtin `¢`](https://github.com/Adriandmen/05AB1E/issues/164), so it would require an additional `§` after the `T`.
[Try it online!](https://tio.run/##MzBNTDJM/f//3Havc1uPtIUcWvT/f7SSgaGSDpCAUAZgNggYKMUCAA "05AB1E (legacy) – Try It Online") or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/c9u9zm090hZyaNH/Wp3/0dFKhgZAqKQDpWN1opXAXKiogQGYDQIGYElDkACQBxIG64JqIQzAymHa4GyIbiQIlomNBQA).
**Explanation:**
```
η # Get the prefixes of the (implicit) input-list
J # Join each inner list together to a single string
ε # Map over each string:
Ć # Enclose; append its first character at the end
T¢ # Count how many times "10" occurs in this string
# (after which the list of counts is output implicitly as result)
```
[Answer]
# [Scala](https://www.scala-lang.org/), ~~139~~ 61 bytes
Port of [@G√°bor Fekete's Python answer](https://codegolf.stackexchange.com/a/263254/110802) in Scala.
---
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=hVNLTsMwFFywM5d4ysqmEGjLT4UgtRJLVgg2CFXGdcDITSrHqVRVOQFHYNMN3KmchheHVG6CVFuK45mXmbH88vmdCa55f7W-UdNZaiy4fShSraWwKk3CaW75i5bh0Bi-GOVxLA0h6cs70nDHVQJLQgC-chsfXa4_5tyAiLzap3trVPL6TBmZyBhiqgYVwqKliqkIVXY7ndkFW4pOpAqpM7ncEsCSN8knHcWKq_q9WugJY2Gm1QTVaI9h6DyxdBxFwXAUsKKK9LO3D1A6TzEr5eY1G4BTr4OxATwkykKEBwEcc65B8ExmiLhC6mAAirI4g0PoscMWduphx8cInHiAq-huAQ7q-9CoCQxxjHZJuwpfGj9qmrUiN5z-ybt7tHwbLi3Xhmnr_LtDeRO584bYBXNbRtwSpwZoeY-PXOcSro-qS2V_twyw4cJxF5vDircNVZFQRoDoBjYowAxbxuqEBlEAB9A9Yx4n6ob561u2rTZuSJV9VnZdTP0k7B-zraQdCHB2_Pg9B16BkVmu7cDRthYqSP0sSEGqf2K1qtZf)
Saved 78 bytes thanks to the comment of [@corvus\_192](https://codegolf.stackexchange.com/users/46901/corvus-192)
```
var c="";def f(i:Any)={c+=i;(c+c(0))sliding 2 count(_=="AB")}
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=hVTNTuMwGLzsKU8xygHZWwi07A_qEqRW4rAHToi9rFaVcR3wyk0qx0FCKE_ChQs81D7NfnGa4iZIjaUomfn8zXzKxM9vpRRGnL68vFYuOzr79-lAr9aFdfB4IgtjlHS6yJNV5cStUcnMWvE4r7JM2Sgqbv8SjSuhczxFEfAgLOQUQdHva2d1fvcHaYgy3lQvVYaM6SnaGj7Fz9xR4RNxgM7AZKLLy9XaPfINCEiMUmj_Uvu7MqUK2F0dmdwrscQImgdb3uH2gZ1wnpRGL8kFm3Cau8odWyBNEc_mcbO17gyvaFgm7F25GbMbkNzf5Prd_oMwkKJUZeeIbSwyakkrPsSEHw6wLwF2fEzASQD4ivEO4KHTEJr3gRld832tfUXYmjb1xQaWe0of-N1_DXR7KgPVnuhg_v2mgkXct16z721SfEKBrLAUF_qOv4SpFM6P2o8a5LHjksWYwuHk_ZZqSTQWkF5giwJriowzOYvTGJ8x_soDrh9hvttt0WvV5KxJXcZCJ_wDsR2nI8S0RqH9iQd_wKqyMm7qadc1qre_Tx3VUXtcbE6N7vT4Dw)
```
import scala.collection.mutable.ArrayBuffer
object Main {
var c: ArrayBuffer[String] = ArrayBuffer()
def f(i: String): Int = {
if (c.isEmpty) {
c += i
}
else {
c = ArrayBuffer(c.head + i)
}
(c.head + c.head(0)).sliding(2).count(_ == "AB")
}
def main(args: Array[String]): Unit = {
val cases = Array(
("ABABA", 2),
("ABABA", 4),
("//", 0),
("BA", 1),
("BABA", 3),
("BB", 3),
("BAAAAB", 4),
("//", 0),
("AB", 1),
("AAA", 1),
("B", 2),
("AB", 3),
("//", 0),
("BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB", 1),
("A", 2),
("B", 2),
("A", 3),
("A", 3),
("B", 3),
("//", 0),
("BABABABABABAB", 6),
("A", 7)
)
for (caseValue <- cases) {
caseValue._1 match {
case "//" =>
println("=" * 15)
c = ArrayBuffer()
case _ =>
val t = f(caseValue._1)
println(caseValue._1 + " " + caseValue._2 + " ; result: " + t)
}
}
}
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
WS«≔⁺ωιωI№⁺ω§ω⁰ABD⎚
```
[Try it online!](https://tio.run/##hYs7CsMwEERr6xTC1S44kD6V5DTuDDmBcIQtUGSjTxQIOftGW6TOwAyveLNsJi678UR1c95KmMJR8i1HF1ZAlG/RqZTcGmD2JUEdpMNBVryIbm5OhtGkNntp@DNUnsLdvhjP2Oxe6R6RL9fyOIBh9NZEpg@RVv@jhRJcXjo9/Rc "Charcoal – Try It Online") Link is to verbose version of code. Fully interactive version, so when run from the command line it will prompt for the next piece of necklace and output the count of `AB`s so far. Explanation:
```
WS«
```
Keep accepting pieces but stop when an empty piece is entered.
```
≔⁺ωιω
```
Concatenate the piece to the necklace so far.
```
I№⁺ω§ω⁰ABD⎚
```
Output the number of `AB`s so far.
[Answer]
# Dyalog APL, 21 bytes
```
{∇⍵,⍞⊣⎕←+/'AB'⍷⍵,⊃⍵}⍞­⁡​‎‎⁡⁠⁢⁢⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁤⁣‏⁠⁠⁠⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌­
⍞ # ‎⁡Take a line from standard input, and pass it to the following function:
⎕← # ‎⁢ print
+/ # ‎⁣ how many times
'AB' # ‎⁤ the string AB
⍷ # ‎⁢⁡ appears in
⍵,⊃⍵ # ‎⁢⁢ the string formed by concatenating the input and its first element
⊣ # ‎⁢⁣ , then,
∇ # ‎⁢⁤ call the same function
⍵,⍞ # ‎⁣⁡ passing the input concatenated with another line from standard input
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# Swift 5.7 `-enable-bare-slash-regex`, 95 bytes
```
{var x=""
return $0.map{x+=$0
return x.ranges(of:/AB/).count+("B"==x.first&&"A"==x.last ?1:0)}}
```
[Try it on SwiftFiddle](https://swiftfiddle.com/d3z2tylllvbbrfrcgg64zr2rmi)! Without the `-enable-bare-slash-regex` flag, the regex literal `/AB/` would be spelled `#/AB/#` on macOS, or `try!Regex("AB")` on Linux, so the flag is obvious. SwiftFiddle enables it by default on Swift 5.7 and later.
The code should be fairly straightforward: append the new element to what's been seen so far, then count the ranges that match `/AB/`, and check whether it starts with "B" and ends with "A".
[Answer]
# [Python](https://www.python.org), ~~67~~ ~~65~~ 55 bytes
```
lambda i,c=[]:c.extend(i)or''.join(c+c[:1]).count('AB')
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVHNToQwEI7XPsXchmqF4N8aTE3gNXY3BlmINdiSUhJ9Fi8kRt_Hoz6NLQO7e3OaMNOvMx_fzLx_dW_uyejxo5Gbz8E157c_q7Z8edyVoEQl19usiutXV-tdpLixiPGzUTqqzqp1lm55XJlBuwjzAjmV_558V2Vf9yABEVle-APyHi4O4RVLEkZhyhbwkhXF7HNvxT6RwpR5cK5Y6Ch94vrfiAXYLGYhIY5FwRHj0QnoDeWsWGjKW6v01OPUa9x3rfJT2GjkjDXGQngGpSffZwy8hVCGT9w7q7qIT6hqQBtH-Uud9KNLEqSyYJ1VYcgST9NrvkfDdg4Xo53SQ02k4kFYL47-RtoAqdJ5vIn8bulK1EpYgXdg635oXYbCCfAiI8eDFjtvdhzJ_wE)
Using the default `list` argument to memorize the previous inputs.
edit: changed `extend` to `append` to save 2 bytes
edit: with the help of @Albert.Lang and @Jonathan Allan golfed an additional 10 bytes
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-nl`, ~~40~~ 38 bytes
```
a="#{a}#$_"
p (a+a[0]).scan('AB').size
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km5ejlLsgqWlJWm6FjfVEm2VlKsTa5VV4pW4ChQ0ErUTow1iNfWKkxPzNNQdndSBzMyqVIhqqKYFG50cuZwcQYQTkAYCJ4gEAA)
```
ruby -nl # -n loops program over each line of input
# -l automatically trims trailing newlines
a=" " # Set a to...
#{a} # a, if already set (empty string otherwise)
#$_ # plus most recent line of input
(a+a[0]) # Get a plus its first character
.scan('AB').size # and count all instances of AB
p # Print that number
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 7 bytes
```
;\ŒgẈ:2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FqusY45OSn-4q8PKaElxUnIxVPimVrRSdIySk2OMko4CiIaznGAiQABkxyrFQrUAAA)
Port of [my Nibbles answer](https://codegolf.stackexchange.com/a/263424/98955).
```
;\ŒgẈ:2
;\ Concatenate all prefixes
For each concatenated prefix:
Œg Group runs of equal elements
Ẉ Length
:2 Floor divide by two
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 6 bytes
```
`\$:/,`=+$$~
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWaxJiVKz0dRJstVVU6iBCUJmbWtFK0TFKTo4xSjoKIBrOcoKJAAGQHasUC9UCAA)
Works with any two distinct characters.
```
`\$:/,`=+$$~
For each p in
`\ : prefixes of
$ the input
, length of
`= $ group runs of identical elements in
+$ p concatenated
/ ~ floor-divided by 2
```
[Answer]
# Excel, 80 bytes
```
=MAP(SCAN("",A1#,LAMBDA(a,b,a&b)),LAMBDA(c,ROWS(TEXTSPLIT(RIGHT(c)&c,,"AB"))-1))
```
Input is *vertical* spilled range `#A1`.
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ƒıJẹTc
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWq45NOrLR6-GunSHJS4qTkouhwgv2RisZGCrpKABJKG0A4RkaGijFQhQBAA)
Uses `1` and `0`, and checks for the substring `10`, like Vyxal and 05AB1E.
#### Explanation
```
ƒıJẹTc # Implicit input
ƒı # Map over prefixes
J·∫π # Join and append first character
Tc # Count occurrences of "10"
# Implicit output
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
m/shBsd`T._
```
[Try it online!](https://tio.run/##K6gsyfj/P1e/OMOpOCUhRC/@//9oJUMDIFTSUYAyYgE "Pyth – Try It Online")
Uses characters "1" and "0" for "A" and "B" respectively.
### Explanation
```
m/shBsd`T._Q # implicitly add Q
# implicitly assign Q = eval(input())
._Q # prefixes of Q
m # map over lambda d
sd # concatenate list of strings
hB # bifurcate into [str, first_char(str)]
s # concatenate list of strings
/ `T # count occurrences of "10"
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 28 bytes
```
$,.=$_;$_=chop.$,;$_=s/AB//g
```
[Try it online!](https://tio.run/##K0gtyjH9/19FR89WJd5aJd42OSO/QE9FB8Qs1nd00tdP///fyZHLyRFEOAFpR0enf/kFJZn5ecX/dX1N9QwMDf7rFuQAAA "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
;\µṙ1<)§
```
[Try it online!](https://tio.run/##y0rNyan8/9865tDWhztnGtpoHlr@/@jkhzsXP2rcx8UFFNy9BcJtWvOoYY6CrZ3Co4a5UYfbHzXuCQOK1Z6crq8Z@f@/oxMQgmSNuOBMEy4uCMOQCyZkzOXkBKUdgcAJqgzCMOQCCkHVw4yCKIaoJgAgZihwQZ0BMwJiAsx2uHlIECRmBlFhDgA "Jelly – Try It Online")
Something cleverer still feels possible. Takes input as shown in the test cases, since counting substring occurrences is actually pretty expensive anyways.
```
;\ Scan by concatenate, creating a list of each cumulative necklace.
µ ) For each:
·πô1 rotate left once, and
§ count how many
< are less than in the corresponding original positions.
```
[Answer]
# [Scala 3](https://www.scala-lang.org/), 65 bytes
```
_.scanLeft("")(_+_).tail.map(s=>(s+s(0))sliding 2 count(_=="AB"))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVJPS8MwFAeP_RSPnPJYNrQTJ5sZtDdhnoYnGSV2zah0WW0yUWSfxMsu-p3005gma6048OWV9CW_Pw9e3j50Kgox3H-yzf1Dlhq4EbmC1yB4EgXIMcyzx7u5qXK1WvBpXVwrs-DvWyP7l59RMrB0NcukoYQgTXoJDozIi8FalFTzKdU9TU8RdZEvrQSEkG62ytCEcxLFBNELfZ2MJgEEsMwkrK0_FdVKjyGqKvHSuOMYblVugNvmwEbdXyp01uLoLNemQTNwVd0sLizHQagjAjgktQ3YRRgcftBzaMjOEdlvqMc1-Dj2lY24pZ0xGLr8y44c3qIdzTt2eTZDSz3i-n94uR_hTtlxCL2DzyM-neUFGu4FgxGig-MkcLvcVEBprsqtYZA9l_bRZEuEq74fBx7mcxhRPTDp0dicl3ZEplCUSEqgB-7S7gSBc6hPXDVpxd1Z6-RUdkH97QL_fvZ7v38D)
] |
[Question]
[
>
> Design a random number generator where the i th number has i% chance
> of occurring for all 0 < i < 14. 0 should have exactly 9% chance of
> occurring. The seed for the generator should be the system time.
> You cannot use a pre-defined function for random number generation.
>
>
>
Basically 1 has 1% chance of occurring, 2 has 2% chance and so on up to 13 having 13% chance of occurring. This is code-golf, so the shortest code wins.
[Answer]
# CJam, 14 bytes
```
E,_T9t\]ze~es=
```
[Test it here.](http://cjam.aditsu.net/#code=E%2C_T9t%5C%5Dze~es%3D)
## Explanation
```
E, e# Push [0 1 2 ... 12 13].
_ e# Make a copy.
T9t\ e# Set the first element to 9. Swap with the original range.
]z e# Wrap them in an array and transpose to get [[9 0] [1 1] [2 2] ... [13 13].
e~ e# Run-length decode to get `[0 0 0 0 0 0 0 0 0 1 2 2 3 3 3 ... 13 13 ... 13 13].
es= e# Use the current timestamp as a cyclic index into this array.
```
[Answer]
## Python 2, 54
```
import time
print((time.time()*1e4%800+1)**.5+1)//2%14
```
The expression `f(t) = ((8*t+1)**.5+1)//2` transforms a uniform distribution to a triangular integer distribution by mapping the intervals
```
[0,1) --> 1
[1,3) --> 2
[3,6) --> 3
[6,10) --> 4
...
```
We convert the millisecond digits of the time to a uniform float from 0 to 100 by doing `time.time()*1e4%100`. Actually, we do `%800` to replace multiplying by 8 in the conversion step. At the end, 14's are converted to 0's by doing `%14`.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 20 bytes
```
⊃(⌊.1×⊃⌽⎕TS)↓(/⍨⍳13)
```
`⍳13` integers 1 though 13
`(/⍨` … `)` replicate by itself, e.g. `/⍨3` is `3 3 3` and `/⍨2 3` is `2 2 3 3 3`
*n*`↓` … drop *n* elements (leaves empty list if *n* > length of list)
`⎕TS` system time stamp e.g. 2015 11 1 13 28 56 834
`⊃⌽` last element, i.e. current millisecond 0–999
`⌊.1×` multiply with 0.1 and round down
`⊃` first element, gives 0 if if data is empty
[Answer]
# Pyth - 14 bytes
```
@+mZ9smRd14.d8
```
Generates array with the specified distribution, then pick a random one.
[Try it online here](http://pyth.herokuapp.com/?code=%40%2BmZ9smRd14.d8&debug=0).
[Answer]
# Processing 3, 65 55 74 bytes
```
long i=0,c=8,r=System.nanoTime()%100;for(;r>c;i++,c+=i);print(i);
```
Get a random number from 0 to 99 (inclusive). If number is 0-8, print 0, if it is 9 print 1, if 10-11 print 2, if 12-14 print 3, etc...
No one noticed it, but the problem with the old code is that millis() returns the amount of time the application has been running, which would give very similar numbers on subsequent runs of the program. At least now we have nano precision!
[Answer]
# PHP, 50 bytes
```
<?for($t=microtime()*100;0<=$t-=++$i;)?><?=$i%14;
```
* `microtime` returns the time as a string like "0.04993000 1446409253", when I multiply this by 100, PHP coerces the string into 0.04993000, result 4.993000. So `$t` is initialized with a "random" number in `[0,100)`
* We subtract 1, 2, 3, ... from `$t` until it reaches 0
* The result is the last subtracted number, modulo 14
[Answer]
# Python3, 86 Bytes
straight forward:
```
import time;print(sum([[i]*i for i in range(1,14)],[0]*9)[int(str(time.time())[-2:])])
```
[Answer]
# J - 28 char
This one was silly.
```
{:({:1e3*6!:0'')$100{.#~i.14
```
`6!:0''` is the current `Y M D h m s` time as a 6-item list, where milliseconds are represented as fractions on the seconds—to get at them, we have to no choice but to multiply the seconds (`{:`) by `1e3`. Meanwhile, `#~i.14` is a list of zero 0s, one 1, two 2s, and so on through to thirteen 13s, and we pad that out to 100 items with `100{.`.
J doesn't have cyclic indexing, so it might be tempting to take the milliseconds modulo 100 before indexing the big list. However, we can save two characters by using `$` to instead *cyclically extend* the 100-item list to however many milliseconds we get (anywhere from 0 to [60999](https://en.wikipedia.org/wiki/Leap_second)) and take the last entry then.
Not that a 60000 element list is a whole lot of memory used or anything, it just feels like overkill :P
[Answer]
# JavaScript (ES6) 116
This is an adaptation of a *simple* seeded RNG that I have used instead of the standard RNG of javascript that cannot be seeded (and so is not repeateble)
```
R=(s=~new Date,p=[],i=0,j=9)=>{
while(p.push(i)<100)--j?0:j=++i;
return _=>(s=(1+Math.sin(s))*1e5,p[100*(s-~~s)|0])
};
// test
var rnd=R()
t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0];
rgb='000,444,666,888,aaa,ddd,f0f,ff0,0ff,0ff,0f0,00f,f00,fff'.split`,`
.map(v=>(v=parseInt(v,16),[(v&15)*17,(v>>4&15)*17,(v>>8)*17]))
cnt=400*300
//for (i=0;i<cnt;i++)t[rnd()]++;
ctx = C.getContext("2d");
img=ctx.getImageData(0, 0, 400, 300)
for(p=0,y=0;y<300;y++)for(x=0;x<400;x++)
v=rnd(),t[v]++,
img.data[p++]=rgb[v][0],img.data[p++]=rgb[v][1],
img.data[p++]=rgb[v][2],img.data[p++]=255
ctx.putImageData(img, 0, 0)
o=''
for(i=0;i<14;i++)
t[i]/=cnt, o+=`<p><i>${i}</i><b style="width:${t[i]*300}%">,</b>${(t[i]*100).toFixed(2)}%</p>`;
G.innerHTML=o
```
```
#G { width: 400px; font-size: 12px; border: 1px solid #000; }
p { margin: 0}
b { display: inline-block; font-size:80%; background: #08c; margin: 2px }
i { display: inline-block; width: 20px; text-align: right; padding: 0 4px }
#C { width: 400px; height: 300px; }
```
```
<div id=G></div>
<canvas id=C></canvas>
```
[Answer]
## TI-BASIC, 18 bytes
```
real(int(.5+2√(-4+50fPart(sub(getTime
```
`100fPart(sub(getTime` gets the random residue between 0 and 99. The (n-1)th triangular number is equal to `(N^2+N)/2`, so the inverse is equal to `√(2y+1)-.5`. Floor this after adjusting downwards by 9, and we have the result
The only problem is that for residues less than 8, we get an imaginary square root. So we take the real part to have the program output 0 instead.
[Answer]
## Perl 5, 51 bytes
50 bytes + 1 for `-E` instead of `-e`:
```
@_=(0)x 9;push@_,($_)x$_ for 0..13;say$_[time%100]
```
] |
[Question]
[
**This question already has answers here**:
[Choosing Languages for Golfing [closed]](/questions/2070/choosing-languages-for-golfing)
(6 answers)
Closed 8 years ago.
Which language usually produces shorter golfed code: Pyth, CJam or Golfscript?
In asking this, I do not mean which has a prettier syntax or which has the most useful commands, I mean overall, which one is usually the shortest? What types of problems would we expect each language to have an advantage in?
[Answer]
There is no simple answer to this question.
GolfScript almost never beats CJam. It has a lot less built-ins than CJam and the overall syntax is a bit more verbose. For example, `print` and `{+}*` become
`o` and `:+` in CJam.
The only exceptions are extremely trivial problems where the fact that GolfScript implicitly reads from STDIN is an advantage and the few occasions where block concatenation is useful ([example](https://codegolf.stackexchange.com/a/54054)).
With CJam and Pyth, it's a bit more complicated. Both languages can beat the other in particular challenges, although, by my completely unscientific observation, Pyth seems to have the upper hand on more occasions.
A few particular cases where picking one over the other is rather easy:
* Choose Pyth if it has a built-in that CJam lacks and significantly simplifies the task.
For example, Pyth has `r<iterable>2`, which is Python's `swapcase()`. If that's useful in a challenge ([example](https://codegolf.stackexchange.com/a/53898)), it will be hard to beat with CJam.
* On occasions, you have to build the output piece by piece. After finishing the program, CJam implicitly prints the entire stack, so you can just dump the pieces and let the interpreter do the rest.
For example, [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") challenges are usually won by CJam.
* The length of a single built-in may be a decisive factor in a challenge.
[Here](https://codegolf.stackexchange.com/a/54094), Pyth's `C`, which is shorter than CJam's `256b`, was enough to outgolf CJam.
[This](https://codegolf.stackexchange.com/a/54035) would be longer in Pyth, partly because trigonometric functions are 3-character built-ins in Pyth and 2-character built-ins in CJam.
To sum it up, there is no single language that will magically make you win all code golf competitions. You haven't even considered APL, J, K, O, Q, TI-BASIC, Retina, Perl, sed and Mathematica, which all have beaten both CJam and Pyth in a few occasions.
You have several options:
* Learn Pyth *and* CJam. Use the one that's more suited for each task.
* Learn the one (first) you like better.
Personally, I'm crazy about stack-based languages, which I find much more easier to write and read.
* Learn the one suited better for the challenges you enjoy.
[ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") is your thing? Go with CJam. Nothing beats [array-manipulation](/questions/tagged/array-manipulation "show questions tagged 'array-manipulation'")? Forget about both and learn J.
[Answer]
Doorknob posted the following statistics on Chat, which I understand are based on answers to existing challenges. All credit goes to him. They certainly agree what I would have imagined.
```
golfscript is shorter than pyth 6 times (~13.043%)
golfscript is shorter than cjam 16 times (~20.513%)
pyth is shorter than golfscript 39 times (~84.783%)
pyth is shorter than cjam 59 times (~60.204%)
cjam is shorter than golfscript 57 times (~73.077%)
cjam is shorter than pyth 31 times (~31.633%)
```
I was going to leave these to Doorknob to post, but I found them interesting and thought if the question is going to stay open a while longer, it would be nice to post them for posterity, before it gets closed.
Obviously the best language will depend on each specific challenge, and this data only considers the corpus of challenges that we have at the moment. A change in the type of challenges would alter the balance between the languages.
Additionally, this data reflects the state of the languages today (Aug 2015). The languages are still in development, so it will be interesting to see how they perform in later versions.
This only covers challenges where at least two of the languages participated, which is probably fairer than considering all challenges. Nevertheless, as in virtually any statistical analysis, it is arguable that there could be some selection bias. It's possible that many challenges were so suited to a particular language that the others were not even considered.
[Answer]
Considering that the point of code golf is to think in terms of a given language's kolmogerov complexity, in my opinion it doesn't matter much which language you use as long as you are clever. All of {Golfscript,CJam,Pyth,J} allow you to exercise creativity as do non-golfing languages. While code-golf technically claims "shortest code wins" this typically only really matters within each language. Often more important (as far as I can tell from looking at voting patterns, etc) is how creative or difficult your solution is.
For example HQ9+ while hilarious doesn't really win a 99 bottles of beer competition, because writing `9` isn't exactly showing effort. Meanwhile the Malbolge execution of 99 bottles of beer is considered incredibly cool despite being very lengthy due to its creative nature and the effort put in to make it. If HQ9+ did win we could merely define a language `L` which states: `L` outputs the solution to this problem, otherwise the code is compiled as C and executed.
This is why most old golfing sites still in operation are language-specific (Perl, Vim, C [if you count IOCCC]) because comparing code-sizes of different languages just doesn't make much sense. Most languages will have at least one challenge where they win. That doesn't make them 'better' than the alternatives.
Interestingly enough I have found that if you stretch the definition of language too much you get very creative/odd solutions to problems. (EG: many ASCII-art competitions could be won by a series of Vim keystrokes over at vimgolf.com).
If code-length is really all you care about, there are even more terse languages then the mentioned Golf-oriented languages. The reason they are often used for golfing is that their code-size is typically directly related to algorithmic complexity, whereas in for example C, you may sacrifice algorithmic complexity for shorter syntax to out-golf the competition. Meanwhile the even terser languages aren't really designed to be human programmable, and are more oriented to approximating kolmogorov complexity or theoretical applications.
My recommendation: learn whichever golfing language is based on a language you like. If you enjoy Python, learn Pyth. If you enjoy Ruby, learn GolfScript. If you like C/C++/Java learn CJam (and if you find you enjoy CJam you may wish to look into [Joy](http://www.kevinalbrecht.com/code/joy-mirror/joy.html) which is a similarly concatenative-stack-based language designed for usability rather than golfability)
] |
[Question]
[
You are given a polynomial function, in the following format:
\$x = (c\_0 \* y^0) + (c\_1 \* y^1) + (c\_2 \* y^2) + ... + (c\_n \* y^n)\$
where \$c\_n\$ stands for the coefficient of the \$n^{th}\$ power of \$y\$
You have to plot the equation on a \$10 \* 10\$ ASCII matrix. The value must be **floored** to an integer before plotting. If \$y < 0\$ or \$y > 9\$, then do not plot. For simplicity, we are assuming the top left corner to be \$(0,0)\$.
A `.` represents an empty space, and `*` represents a point on the graph. You can choose any characters to represent both of the things as per your convenience but do mention what you use in your answer.
You may take the input as a list/array of coefficients, or, as a string in the above specified format.
Examples:
```
Input -> x = (1 * y^1)
Output ->
*.........
.*........
..*.......
...*......
....*.....
.....*....
......*...
.......*..
........*.
.........*
Input -> x = (9 * y^0) + (-1 * y^1)
Output ->
.........*
........*.
.......*..
......*...
.....*....
....*.....
...*......
..*.......
.*........
*.........
Input -> x = (0.10 * y^2)
Output ->
*.........
*.........
*.........
*.........
.*........
..*.......
...*......
....*.....
......*...
........*.
Input -> x = (3 * y^1)
*.........
...*......
......*...
.........*
..........
..........
..........
..........
..........
..........
```
*Hint: eval can be helpful here.*
Inspired by a clash of code problem from <https://www.codingame.com/>
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 bytes
Full program. Takes list of coefficients in descending order. Returns Binary matrix. Requires 0-based indexing (`⎕IO←0`).
```
a∘.=⍨⌊⎕⊥⍨⍪a←⍳10
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862gv@Jz7qmKFn@6h3xaOeLqDUo66lIHbvqkSgkke9mw0N/gOV/VcAgwIuQwUDLl1dXS4Y/9B6QwVLFBEDPUMDBQM0ZcYKBgA "APL (Dyalog Unicode) – Try It Online")
`⍳10` **i**ndices 0…9
`a←` store as `a`
`⍪` make into column vector
`⎕⊥⍨` prompt for coefficients and evaluate the them as digits in base each-element-of-`a`
`⌊` floor
`a∘.=⍨` equality table with `a` horizontally
[Answer]
# [Factor](https://factorcode.org/) + `math.polynomials`, 73 bytes
```
[ 10 iota dup -rot '[ _ polyval 1 /i _ [ = pprint ] with each nl ] each ]
```
[Try it online!](https://tio.run/##XY/NDsIgEITvfYrx5F@srZ7UeDZevBhPjRpSMRIpIKVqY3z2usUao8uFWb6dZY4sddpWm/VytZgi55eCq5TnONoSZ24Vl8iYO4VGy1LpTDCZ@waM5c6VxgrlIDRmQfAIQPVAhBhP@Grhjjk6MXood3G3ASYYfIgGmHggQr9@@WGj@oQeb1hSkWdGX2b8t3D8MXlWCQgX2jEcCoOB1Q7tBHvUga5M0l@HgmRCY@adZouboICcpScoSdLftuTkVaozo3Puu9UL "Factor – Try It Online")
Takes a sequence of coefficients from low to high. `polyval` handles the actual evaluation of the polynomial; the rest is just data plumbing and output.
`1 /i` is to convert from a float to integer, as it is shorter than `>integer` (and `floor` doesn't produce an integer in Factor [AND `1 /i =` is shorter than `number=` by 1 byte]). I found a locals solution that was the same length, but couldn't save any bytes. You can save 2 bytes by using a modern version of Factor with `tuck`, but meh.
Prints `t` for a point on the graph and `f` for empty space.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
Eχ⭆χ⁼λ⌊↨ιθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDD0EBHIbgEyE2H8VwLSxNzijVydBTccvLzizScEotTNTJ1FAo1wcD6///oaAM9Qx0FoFqD2Nj/umU5AA "Charcoal – Try It Online") Takes input as a list of coefficients (in order of highest power of y down to 1) and outputs a binary matrix. Explanation:
```
χ Predefined variable 10
E Map over implicit range
χ Predefined variable 10
⭆ Map over implicit range and join
θ Input coefficients
ι Outer index
↨ Evaluate polynomial
⌊ Floor
λ Inner index
⁼ Do they equal?
Implicitly print
```
[Answer]
# [J](http://jsoftware.com/), 15 bytes
*-2 thanks to Jonah!*
```
(<.@p.=/])i.@10
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWz0HAr0bPVjNTP1HAwN/mtypdtapSZn5DtoWKcBOUClhkDSUiHeEMwBQj0Iy/g/AA "J – Try It Online")
Execute the left function with `i.@10` (`0 1 2 … 9`) as the right argument.
`<.@p.` apply polynomial (thanks J for the built-in!) to each `i.@10`, floor and compare each result to `i.@10` with `=/`.
[Answer]
# JavaScript (ES7), ~~87 85 83~~ 81 bytes
Expects an array of coefficients, from lowest to highest.
```
a=>(g=x=>y>9?'':`
*.`[x>9?x=++y-y:a.reduce((p,c,i)=>p+c*y**i)^x++?2:1]+g(x))(y=0)
```
[Try it online!](https://tio.run/##bcpBCoMwFATQvadw5/9JDNquFH48iFgMMYpFjGhbktOndluE2cybeeqPPsw@b698dYONI0VNCibypIKqmiyr@4TJvvVn8cR5yEOt5W6Ht7EAmzBiRlIbNywwNuPDc97c6rLjE3hECFRgNG493GLl4iYYoS1EWnaIyR9XIs2v/Lz/IsvieryfHL8 "JavaScript (Node.js) – Try It Online")
### Commented
```
a => ( // a[] = input array of coefficients
g = x => // g is a recursive function taking x
y > 9 ? // if this is the end of the graph:
'' // stop the recursion
: // else:
`\n*.`[ // lookup string: 0 = '\n', 1 = '*', 2 = '.'
x > 9 ? // if this is the end of the row:
x = ++y - y // increment y, set x to 0, yield 0
: // else:
a.reduce( // compute P(y)
(p, c, i) => // which is the sum of all
p + c * y ** i // a[i] * y ** i
) ^ x++ // test whether floor(P(y)) = x
? 2 // and yield 2 if it's not
: 1 // or 1 if it is
] + //
g(x) // do a recursive call
)(y = 0) // initial call with x = y = 0
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 20 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
éR▒Å╗←û%╞.A◄→⌐‼²GÑd,
```
[Run and debug it](https://staxlang.xyz/#p=8252b18fbb1b9625c62e41111aa913fd47a5642c&i=%5B0,1%5D%0A%5B9,-1%5D%0A%5B0,0,0.1%5D%0A%5B0,3%5D&m=2)
Very long, partly due to `floor` not working on integers.
uses 1 and 0 as the display chars.
[Answer]
# [Python 3](https://docs.python.org/3/), 86 bytes
```
lambda l,r=range(10):[[i==sum(c*x**n for n,c in enumerate(l))//1for i in r]for x in r]
```
[Try it online!](https://tio.run/##PU5LDoIwEN17igmrFiufsJKkJ6ldVGy1BgZSSoKnRwaUZBZv3m9m@MRXj9Xi5G1pTXd/GGhFkMHg07Ky4LVSXspx6liTzmmK4PoAKBrwCBanzgYTLWs5z/OSJE9C0ATnHS6Em946NxKhVCGg1ALUVcBlAytBk/2XSuv6BEPwGJlje5Tz03a69Wip5uBX58@aJNm798jUGAM7ew7HPxTS1LAb@fIF "Python 3 – Try It Online")
Takes a list of coefficients in ascending power. Outputs a list of lists of booleans.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~164~~ \$\cdots\$ ~~123~~ 111 bytes
Saved 2 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!!
```
y;i;f(l,n,x)float*l,x;{for(y=-1;x=y++<9;i=x>=1&x<11?x:0,puts(" *"+10-i))for(i=n;i--;)x+=l[i]*pow(y,i);}
```
[Try it online!](https://tio.run/##nVTRbpswFH3PV1xZ6oTBdDhkD4lD8zDtK5K0YhR3ZhQizFSziF8fM4YEQjKtKkpC7HPOPedeLCL3JYqapmKCcSslGVGYp3lY2ilR7MjzwqoClzIVVI6zXjIRqIeAflJrSjdq5ZHDr1JaCE6XjRzquQLjViiCjAnXZVg5QboVe/uQv1kVEZjVjchKeA1FZuHZcdYqjSmUsSyf6HYPARw9ArRmU3DegUsC7g3UP0vbz/0NxuLM8MegbVDZgV0K0hv2d7@/L3pZ24HZyDqRFL/jnFudFn/ul3a/JjDG5xN8PsH9Ce5P8MUEX@A@VPQjLGz9G0c/40LngjYZ2qlv851aftXfL4jAeO2j0xTyAqy2J5E9x0rLPNb/XY@t5aWzxAwcx/AwdA9yNNJUl@nGahh7dia0RlmP6gFO4UOhCdxCbQ6EL2UhL@PiSZZhUZqUg@mpg6RLn@jkWRsvGUczZThY6TbZT/dPmC6gK9xCx@Hu/HvK9ThNJXZFrSFOZTzUo/@tJ01Fu9I1R01uTFR4AG@DwAG0QuDqoayQpvHwu@w6@XeAd5o@3j1/xJdAcsv6aufyqdFLyUCvr47AapeNT4B5R@HrkxIM1yCoZ3XzJ@Jp@CIb961x09e/ "C (gcc) – Try It Online")
Uses the space () character for background and an asterisk (`*`) for plot points.
[Answer]
# [Haskell](https://www.haskell.org/), 200 bytes
```
p[]x=0;p(s:r)x=x*p r x+s
q f=[[b$map(subtract y.p f)[x,x+1/4..x+3/4]|y<-n]|x<-n]
b=(['⠀'..]!!).a.map c
n=[0..9]
c x|x<0=[0,0]|x<0.5=[1,0]|x<1=[0,1]|x>0=[0,0]
a[[l,r]]=l*8+r*16
a([l,r]:s)=2*a s+l+r*8
```
[Try it online!](https://tio.run/##dVDRTsIwFH3vVxwXEtcVyqZoYFrffTD63tSkjBIWyza2EYrhwU/x2/wR7ACNmnibtOeec0970oVuXoy1@30llRPxTRU2aU2dcFGFGo41ZIW5kHLaW2qvradtrbMWW15hTqXrO5YMR5w7djkcqd32dlConet2MhWhPP94fzvnXJ2dUa65vwEZKYSMOZ8oksH50di3/bgzxfxKyOSIk45NPLo76URLafu1UsJGY1ZHyTXR4YFJGyouIo2GWc@P90udF0hT3D8ipOTQCeRFaw7Be1gXNi9MA46sLDLdPvhUYWXL9qm026Jc5tp6rctaGz3zcFPWs4Z6cPARbBamNvjjyEoz99qpBILguwFShIGDCMDY6dEf4s@S8DN@mLFmUW6QMRYgwvb5izCeoME/5h1C088obgd4zSt0v6yOuaDorzSrI72PkZAJBgmJ4RfvzstP "Haskell – Try It Online")
The function `q` takes a list of polynomial-coefficients and generates braille dot-matrix characters. Example:
```
x = + (0.0 * y^0) + (0.0 * y^1) + (0.1 * y^2)
⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀
⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀
⢱⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠈⡆⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠘⡄⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠘⡄⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠘⢄⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠈⠢⡀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠑⢄⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠑⢄
```
[Answer]
# [Python 3](https://docs.python.org/3/), 112 bytes
```
def f(l,*m):
for x in range(10):
try:m=[*m,[0]*10];m[x][int(sum(y*x**z for y,z in l))]=1
except:1
return m
```
[Try it online!](https://tio.run/##pY1BDoIwEEX3nKJhNdOMhMpKDCdpuiDaag0tpJQEuDxS3bkyYTf5897/wxKfva@27a4NM9ARd1hnzPSBzcx6Flr/0CDKFLIYlto1kjuSpeKiVFcnZyWtjzBODhY@c75@3IXWZHeIqhG7qeebHmK9n0HHKXjmtoR11uvEGZAgSKBKM0NIhXlevHrrwbUDjDFQQhEx@34x@9UvVCLB6WBLIeh8xK/@mt/e "Python 3 – Try It Online")
-15 bytes thanks to @UnrelatedString
-3 bytes thanks to @ophact
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ ~~8~~ 7 bytes
```
⁵ḶɓḅḞ=€
```
[Try it online!](https://tio.run/##y0rNyan8//9R49aHO7adnPxwR@vDHfNsHzWt@X@4PVIFSGc9atzHxfX/f7ShjoJBrI5CtC6QYQli6IFEoILGIBoA "Jelly – Try It Online")
*-2 bytes because the output format was loosened, then I noticed another golf in the course of writing the explanation*
*-1 byte because why the hell didn't I already try that?*
Input as coefficients in descending order of power, output as binary matrix.
```
⁵Ḷɓ Let [0 .. 9] be the right argument to the following dyadic link:
ḅ evaluate the polynomial at each y in [0 .. 9],
Ḟ and floor each result.
€ For each result,
= is it equal to each x in [0 .. 9]?
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~46~~ 43 bytes
```
0<=#<1&/@(#-r)&/@FromDigits[#,r=0~Range~9]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b738DGVtnGUE3fQUNZt0gTSLsV5ee6ZKZnlhRHK@sU2RrUBSXmpafWWcaq/Q8oyswr0XdIc3BNzsgHyiop6aCoroxVi1WrC05OzKur5qo21DGo1eGq1jXUsQTRekA@RMQYSHHV/gcA "Wolfram Language (Mathematica) – Try It Online")
Input coefficients in descending order. Returns a 10x10 boolean matrix.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 78 bytes
```
->c{(a=0..9).map{|y|a.map{|x|z=1;x==c.reduce{|s,x|s+x*z*=y}.to_i ? ?*:?.}*''}}
```
[Try it online!](https://tio.run/##JcZBCoQgFADQq7irrD61rPh5kIhwnIIWUaSC5vfsxjDwFu@2H582TPWoQi6xAegKOOQVyJP8x9GD7eAQFdzr16o1kK4c6dLxh6OPYM5lZ4IJ3guIPMtiTJc1mm3T1FTsB9p5Ti8 "Ruby – Try It Online")
Returns an array of 10 strings
# [Ruby](https://www.ruby-lang.org/), 67 bytes
```
->c{(a=0..9).map{|y|a.map{|x|z=1;x==c.reduce{|s,x|s+x*z*=y}.to_i}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y65WiPR1kBPz1JTLzexoLqmsiYRwqioqbI1tK6wtU3WK0pNKU1Ora4p1qmoKdau0KrSsq2s1SvJj8@sra39X6CQFh1toKMAQnqGsbH/AQ "Ruby – Try It Online")
Return a matrix of booleans
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 42 bytes
```
p->matrix(10,,y,x,y--;floor(eval(p))==x--)
```
[Try it online!](https://tio.run/##TYrLCsIwEEV/ZZYzdkaSupKS/ogoZGFKINohFEm@Pvbhwt0591z1OcqkLYBrKuPLLzkWtIa5cuEqMoQ0zxmfH59QiZwrItS8aqqoICNoju9lTcNBimH7MdzQwgnqw66M1x0NQQcof7s5W7Nbv9nlF@7Uvg "Pari/GP – Try It Online")
] |
[Question]
[
Because I forgot to celebrate Pi Day (14.3), let's celebrate with \$\pi\$, \$e\$ (Euler's number) and music!
## Challenge
No, we don't have time to eat a pi-pizza, let's make a program.
What you need is \$500\$ digits of \$\pi\$, and \$10\$ digits of \$e\$.
The input is an integer \$n\$ between \$0\$ and \$499\$ inclusive.
Then you should loop through the first \$n\$ digits of \$\pi\$:
If the digit is:
* \$0\$ then the note is `C`
* \$1\$ then the note is `D`
* \$2\$ then the note is `E`
* \$3\$ then the note is `F`
* \$4\$ then the note is `G`
* \$5\$ then the note is `A`
* \$6\$ then the note is `B`
* \$7\$ then the note is `C'`
* \$8\$ then the note is `D'`
* \$9\$ then the note is `E'`
Next, for each digit in \$\pi\$, take a digit from \$e\$ based on this mapping:
* If the digit from \$\pi\$ is \$0\$, take the \$1\$st digit from \$e\$
* If the digit from \$\pi\$ is \$1\$, take the \$2\$st digit from \$e\$
* If the digit from \$\pi\$ is \$2\$, take the \$3\$st digit from \$e\$
* etc.
You need only \$10\$ digits of \$e\$, because the digits in \$\pi\$ are between \$0\$ and \$9\$.
Finally, take the note and the digit from \$e\$. Return a tuple (or equivalent) containing:
* the note
* the \$e\$ digit divided by \$4\$ (representing the beat)
## Test cases
```
In:10
Out:
('D', 0.25)
('G', 2.0)
('D', 0.25)
('A', 0.25)
("E'", 1.0)
('E', 2.0)
('B', 2.0)
('A', 0.25)
('F', 0.5)
('A', 0.25)
In:5
Out:
('D', 0.25)
('G', 2.0)
('D', 0.25)
('A', 0.25)
("E'", 1.0)
```
### Help
Here are \$500\$ digits of \$\pi\$:
```
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458700660631558817488152092096282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179310511854807446237996274956735188575272489122793818301194912
```
And \$10\$ digits of \$e\$:
```
2.7182818284
```
Note that '3.' and '2.' don't count in the digits of \$\pi\$ and \$e\$, and that we are using \$0\$ indexing (so the \$0\$th digit of \$\pi\$ is \$1\$ etc.).
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer wins.
* Optional; After every tuple or list output, there can be a trailing newline.
### As one week is over, here is an ungolfed code in Python 2:
# [Python 2](https://docs.python.org/2/), 526 bytes
```
def music_maker(n):
i=p=1;x=3*100**n
while x:x=x*i/-~i/4;i+=2;p+=x/i
pi_number=str(p)[:-1] #First 3 lines calculates Calculate Pi
euler='7182818284'
del x,i,p #You don't need those Variables any more. They were ment for calculating
for i in range(n):
current_pi = pi_number[i] #Current Pi
current_e = euler[int(current_pi)] #Current e
number_to_note = {0:"C", 1:"D",2:"E",3:"F",4:"G",5:"A",6:"B",7:"C'",8:"D'",9:"E'"} #Dict number to note
print((number_to_note[int(current_pi)], int(current_e)/4)) #Prints result
```
[Try it online!](https://tio.run/##ZZJPT8JAEMXv/RQvy6EUV6GAikt6UBSvHoyJIaapZZSJ7bbZbmOJ0a@OW/APxsNmJ7O/9@ZNsuXargo93GyW9IS8rjiN8@SFTFcHygNHZRROm2jUCweDXk97eF1xRmhUEzU97h9@cH885YNoOC0PoqbPHkqOdZ0/kokqa7plsFCH4QM6czaVxQgZa6qQJllaZ4l15ey7xI1TU505pX8aToaT9ox9D0vK0EiWJTr3RY1loX0LTbSEi14R7hLDyWPmvBK9Rl4YOsLtitZ4JUPISVs8FeZnJutnb9tgsIZJ9DPtlkVaG@PouGREv3ss2MWf7Z62GX84ctg28IK17f6qgz0BOX7nE9si1oVtRW8DJWZCIlTiUsihEldCjpSYCzlW4lrIYyXOhTxR4kLIU4f6Qk4c6q4zx/riHZ1LTu2XMWyB1thNKk2bpPt34L90EvsdCvrjIEDnptVWMFTVmd3sf4VwEHhbZ2@/exxsPgE "Python 2 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~150 ... 134~~ 133 bytes
*Saved 3 bytes thanks to @KevinCruijssen*
Expects a BigInt as input and prints the music to STDOUT. This also works for \$n>500\$.
```
n=>{for(k=p=1n,x=3n*100n**n;x;p+=x/k)x=x*k++/k++/4n;for(;x<n;)console.log('CDEFGABCDE'[d=(p+'')[x++]]+" '"[d/7|0]+'7182818284'[d]/4)}
```
[Try it online!](https://tio.run/##FY1LCsIwFACvIt3k89S0WmghPsH/IUoXpR/RlpfQigTUs8dmMcxmYJ7Vu5rq8WFfKzJN6zv0hPtPZ0beo8WElg63JJM4JilJO20BneqFQyd7ABVISYdeux1pURuazNCuB3Pn7HS@XG@H4yxWNMgtMCYKB1CWEC1YVDQq@8YlsCzJN3kgnbtSpeLnOx6ewv8B "JavaScript (Node.js) – Try It Online")
## How?
### Part 1: compute \$n\$ digits of \$\pi\$
This is based on the following formula:
$$\pi-3=\sum\_{n=1}^{\infty}\frac{3}{4^n}\left(\prod\_{k=1}^{n}\frac{2k-1}{2k}\right)\times\frac{1}{2n+1}$$
Instead of using floats -- whose precision is obviously far too limited -- we use a Big Integer \$x\$ initialized to \$3\$ times a large enough power of \$10\$ and process integer divisions until we have \$x=0\$.
For 500 digits, we could just use \$x=3\cdot10^{503}\$. We instead start with \$x=3\cdot100^n\$, which is more than enough to get \$n\$ correct digits and easier to golf.
```
for( // loop:
k = p = 1n, // start with k = p = 1
x = 3n * 100n ** n; // start with x = 3 * 100 ** n
x; // stop when x = 0
p += x / k // add x / k to p after each iteration
) //
x = // update x to:
x * k++ / k++ / 4n // x * k / (k + 1) / 4 (and increment k twice)
```
### Part 2: convert to music notes
```
for(; x < n;) // repeat as many times as requested:
console.log( // print:
'CDEFGABCDE'[ // string of notes
d = (p + '')[x++] // d = x-th digit of pi, extracted from p
] + //
" '"[d / 7 | 0] + // append a quote if d is greater than or equal to 7,
// or a space otherwise
'7182818284'[d] // get the d-th digit of e (using Math.E would be longer)
/ 4 // and divide it by 4 for the beat
) // end of console.log()
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~33~~ 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LεAuS7£ÀÀD3£''««žsyè©èžt¦®è4/‚
```
Outputs as a list of pairs in the `["string-note", beat-decimal]` format.
[Try it online.](https://tio.run/##ATsAxP9vc2FiaWX//0zOtUF1UzfCo8OAw4BEM8KjJyfCq8Krxb5zecOowqnDqMW@dMKmwq7DqDQv4oCa//8xMA)
**Explanation:**
```
L # Push a list in the range [1, (implicit) input]
ε # Map each integer to:
Au # Push the uppercase alphabet
S # Convert it to a list of characters
7£ # Only leave the first 7: ["A","B","C","D","E","F","G"]
ÀÀ # Rotate it twice towards the left: ["C","D","E","F","G","A","B"]
D # Duplicate it
3£ # Only leave the first 3 character of this copy: ["C","D","E"]
''« # Append a "'" to each: ["C'","D'","E'"]
« # Merge the two lists together:
# ["C","D","E","F","G","A","B","C'","D'","E'"]
žs # Push an infinite list of pi-digits: [3,1,4,1,5,...]
yè # Index the current integer into it (0-based, so leading 3 is skipped)
© # Store it in variable `®` (without popping)
è # Index this pi-digit into the notes string-list
žt # Push an infinite list of e-digits: [2,7,1,8,2,...]
¦ # Remove the leading 2
® # Push the pi-digit from variable `®`
è # Index it into the infinite list of decimal e-digits
4/ # Divide it by 4
‚ # Pair the pi-note and e-digit/4 together
# (after which the resulting list of pairs is output implicitly)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 97 bytes
```
Print[C[D,E,F,G,A,B,"C'","D'","E'"][[#]]|R[E,10,2+#][[1,-1]]/4]&/@#&@@R[Pi,10,#,-1]&
R=RealDigits
```
[Try it online!](https://tio.run/##FYqxDsIgFAB3PgMSOvhMi6ljE7Sga4MjeQMhrSWxNVE2tb@OsNxwd4uL87i4GLxLU5eGV1ij7a0CDRe4wgnOQPuKAlUFuqJoLUP8GqtBNHDYsSwE7AVi3SKvJeNSGjuEUlnxnJjOjO6hwj3Ed5qk9vMzb9vNu3X7kPyRFsixIb/0Bw "Wolfram Language (Mathematica) – Try It Online")
Prints notes as `[key] | [duration]`, with one note per line.
Since Mathematica's number->string functions are so bulky (`FromCharacterCode`, anyone?), hardcoding the keys' names as symbols seems to be shorter.
[Answer]
# [Perl 5](https://www.perl.org/) `-Mbignum=bpi`, ~~86~~ 84 bytes
```
say+(C..G,A..E)[$_],"'"x($_>6),$",((exp 1)=~/./g)[$_+3]/4for(substr bpi<>+1,2)=~/./g
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJbw1lPz13HUU/PVTNaJT5WR0ldqUJDJd7OTFNHRUlHQyO1okDBUNO2Tl9PPx2kQts4Vt8kLb9Io7g0qbikSCGpINPGTttQxwiq5v9/43/5BSWZ@XnF/3V9TfUMDA2AdFJmel5pri1QMQA "Perl 5 – Try It Online")
## How?
```
for # loop over
(substr # a substring of
bpi<>+1, # PI to the appropriate number of decimals
2) # starting after the second character
=~/./g # split into characters
say+ # output
(C..G,A..E)[$_], # the note letter
"'"x($_>6), # a ' if it is in the next octave higher
$", # a space
((exp 1) # Euler's number
=~/./g) # split into characters
[$_+3] # skipping the first 3 (2.7)
/4 # divided by 4 beats
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes
```
P×φψ¤≕Pi→→≔EKDN→Iιθ⎚Eθ⁺⁺⁺§…α⁷⁺²ι×'›ι⁶ ∕I§⪫74ײ1828ι⁴
```
[Try it online!](https://tio.run/##ZY9Ba8MwDIXv/RVGl8rgwVrKWpZTSVnpICOMsbubao2oa6e2E9ZfnzlZyw67CImn9@mpqrWvnDZ9X7QmcuPZRvzgMwX8UuIqZTZ5YWNwS/FTe9Z7QwglwyAUriN8fudjHf9N6xD4aLHQDZZEpw17qiI7izvbtPGtPe/Jo1TiZlAi1yEiy9Rdkj03pJOeTcox0IC5KFGaNuBfWcedPdA35tfKUF67BrUSS3nbmysx4n6fgSkosfWkY7rLSjzJQQMBqW644wPhmODOfHVsEZYLuAMSDmar@QoG3wheJITM@n722D905gc "Charcoal – Try It Online") Link is to verbose version of code. Actually works up to `n=998`. Explanation:
```
P×φψ¤≕Pi
```
Charcoal apparently has a built-in for π, but unfortunately the only way I know how to use it is copied from the Charcoal answer to [Bake a slice of Pi](https://codegolf.stackexchange.com/q/93615/17602) which involves using it as a flood fill. Here I just output `1,000` null characters which therefore gives me `998` decimals of π, well above the `499` required by the challenge.
```
→→≔EKDN→Iιθ
```
Now input the number of decimals required, read them from the canvas, and convert them to integers.
```
⎚
```
Clear the canvas ready for the actual output.
```
Eθ⁺⁺⁺
```
Map over the digits and concatenate...
```
§…α⁷⁺²ι
```
... the first `7` letters of the uppercase alphabet, cyclically indexed by 2 more than the digit...
```
×'›ι⁶
```
... an `'` if the digit is greater than 6...
```
```
... a space...
```
∕I§⪫74ײ1828ι⁴
```
... and the appropriate digit divided by 4, taken from the string `7182818284`, constructed by doubling the string `1828` and inserting it into the string `74`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~173~~ ~~164~~ ~~162~~ ~~156~~ ~~150~~ ~~149~~ ~~143~~ 141 bytes
```
def f(n):
i=p=1;x=3*100**n
while x:x=x*i/-~i/4;i+=2;p+=x/i
while x<n:i=int(`p`[x]);print"CDEFGAB"[i%7]+"'"[i<8:],1907986849/9**i%9/4.;x+=1
```
[Try it online.](https://tio.run/##PY1LCoMwFAD3niIIUk3axlipJvEt@j@ECC6q@KCkoQh93fTqqavuZmBg/Geenq4I4T6MbExdZiKG4EFZgh1Xec65i9h7wsfAyBAQR7n5oiwtCiisF0AS/0HjDAK6Oe1931KXWf9aLD6dL9fb4Ri3mFSdiFcLNLXp1krnla73daml5hwTLcutJQEqjOmyzsIP)
Prints the pairs newline-delimited to STDOUT in the format `string-note beat-decimal` (space-delimited).
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/206909/52210), so make sure to upvote him!
-6 bytes thanks to *@ovs*, which opened up -6 more bytes by switching to Python 2
-1 byte thanks to *@Arnauld*
-2 bytes thanks to *@Tanmay*
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 29 bytes
```
ƛkAf7Ẏ2Ǔ:3Ẏ\'vJJn∆iin∆i›∆ė4/"
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGm2tBZjfhuo4yx5M6M+G6jlxcJ3ZKSm7iiIZpaW7iiIZp4oC64oiGxJc0L1wiIiwiIiwiMTAiXQ==) or [Run both test cases!](https://vyxal.pythonanywhere.com/#WyJQaiIsIsabIiwixptrQWY34bqOMseTOjPhuo5cXCd2Skpu4oiGaWlu4oiGaeKAuuKIhsSXNC9cIiIsIjs7WsabYCA9PiBgaiIsIlsxMCw1XSJd)
Port of 05AB1E. If it can't output rationals instead of decimals, add `øḋ` before `"`. Then it will be as strings.
## How?
```
ƛkAf7Ẏ2Ǔ:3Ẏ\'vJJn∆iin∆i›∆ė4/"
ƛ # For each item `n` in the (implicit) inclusive one range of the (implicit) input
kA # Push the uppercase alphabet
f # Convert to list of characters
7Ẏ # Leave only the first seven letters: ["A","B","C","D","E","F","G"]
2Ǔ # Rotate left twice: ["C","D","E","F","G","A","B"]
: # Duplicate
3Ẏ # Leave only the first three letters of the duplicate: ["C","D","E"]
\'vJ # Append a single quotation mark to each letter: ["C'","D'","E'"]
J # Join these two lists together: ["C","D","E","F","G","A","B","C'","D'","E'"]
n∆i # Get the `n`th (zero-indexed) digit of pi
i # Index this into the list of notes
n∆i # Get the `n`th pi digit again
› # Increment it
∆ė # Get the zero-indexed E digit from that
4/ # Divide by four
" # Pair the pi-note and e-digit/4 together
```
[Answer]
# perl -MMath::BigFloat -pl, 170 bytes
```
$n=$_;$p=new Math::BigFloat;$p->accuracy(500);$_=$p->bpi;s/..//;s!.!'('.substr(CDEFGABCDE,$&,1).("'"x($&>6)).', '.((substr 7182818284,$&,1)/4).")\n"!eg;/(.+\n){$n}/;$_=$&
```
[Try it online!](https://tio.run/##VY7fCoIwHIVfRWW4jfQ3DS1xKPT/yjcIQkVMkDmcUhG9eivzqovDgY8PzpFV34ZaI5GgC0cyEdXNyPLhGsfbpj62XT58qZvmZTn2efkgoedRji7JBAvZcMUAGOPKBBMTDGos1NCT3f5wPG2233KQ7fgUiIWtO0F2uqIUsGNgIGR2jbUfLaMpweyygIJFz8Iyq5ozAouzoE8kXuw3a2vte@9ODk0nlHaz/6/ale0H "Perl 5 – Try It Online")
## How does this work?
```
$n = $_;
```
This gets the input (which is in `$_` due to the `-p` switch; the `-l` switch removes the newline).
```
$p = new Math::BigFloat;
$p -> accuracy (500);
$_ = $p -> bpi;
s/..//;
```
This gets us the 500 required digits from \$\pi\$. First we create a `Math::BigFloat` object, give it an accuracy of 500 (so, 500 decimals behind the comma). We then query the object to get \$\pi\$, which we store in `$_`. And we then remove the first two characters, to set rid of the leading `3.`.
```
s !.!
'(' . substr (CDEFGABCDE, $&, 1) . ("'" x ($& > 6)) .
', ' . ((substr 7182818284, $&, 1) / 4) .
")\n"
!eg
```
This does the majority of the work. We take each digit of \$\pi\$ and replace it with the result of the middle three lines of code above. During the replacement, the digit being replaced is in `$&`. We start with an opening paren, then we look up the note by using the current digit as in index into a string (`substr (CDEFGABCDE, $&, 1)`. If the digit is greater than 6, we need to add a prime (`("'" x ($& > 6))`). We then add a comma. Then, to get the beat, we index into the digits of \$\epsilon\$, and divide by four (`((substr 7182818284, $&, 1) / 4)`). Finally, we add an closing paren and a newline.
```
/(.+\n){$n}/;
$_ = $&
```
This trims the resulting string to the desired length. We're grabbing `n` times a group of non-newline characters followed by a newline character, and store the result into `$_`, which gets printed due to the `-p` command line switch.
] |
[Question]
[
The challenge is to write the shortest function/program to find a polynomial given the roots. The function or program should take valid input; that is, a list of integers representing the roots of the polynomial, and return valid output.
Output should return a sequence of numbers representing the polynomial.
For example:
`2, 3` represents `2x^1 - 3x^0 = 0`
`1, 6, 1, 8, 0, 3, 3` represents `1x^6 + 6x^5 + 1x^4 + 8x^3 + 0x^2 + 3x^1 + 3x^0 = 0`
`-1 0 5, -3` represents `-1x^3 + 0x^2 + 5x^1 + -3x^0 = 0`
I hope you get the idea.
**Example Usage**
For an input of `1, 2`, the output should be `1, -3, 2`, which represents the equation `1x^2 + -3x^1 + 2x^0 = 0`, or `x^2 - 3x + 2 = 0`.
For an input of `1, -1, 0`, the output should be `1, 0, -1, 0`.
For the input, duplicate values should be removed and order does not matter. For example, the result with input `3, 3, 6` should be the same as the result with input `6, 3`.
Float arguments are optional.
As this is code golf, the shortest entry in *characters* wins. Good luck!
[Answer]
# J, 8 bytes
A series of verbs:
```
|.p.1;~.
```
Call it like this:
```
|.p.1;~. 1 2
1 _3 2
```
J has a built-in verb [`p. (Roots)`](http://www.jsoftware.com/help/dictionary/dpdot.htm). It converts between polynomials like `2 _3 1` (reverse order from the problem) and a multiplier/root pair like `(1; 1 2)`.
From right-to-left, `~.` takes the unique elements, `1;` pairs the list with 1, meaning we want the *smallest* integer polynomial, `p.` does the actual work, and `|.` reverses the resulting list.
[Answer]
## Python 2, 71
```
P=[1]
for r in set(input()):P=map(lambda a,b:a-r*b,P+[0],[0]+P)
print P
```
Iteratively updates the polynomial `P` to add one root at a time. Adding the root `r` multiplies the polynomial as `P*(x-r)`. This requires shifting the polynomial list `P` by one index to represent multiplication by `x`, the subtracting `r` times the original list. This is handled by shifting a copy of the list, padding with zeroes, and mapping the function `a,b -> a-r*b`.
To remove duplicate roots, the input is made into a `set`.
Using `reduce` turned out one char longer (72):
```
lambda R:reduce(lambda P,r:map(lambda a,b:a-r*b,P+[0],[0]+P),set(R),[1])
```
Three lambdas though!
[Answer]
## Haskell, 70
Basically a port of the `reduce` version of my [Python solution](https://codegolf.stackexchange.com/a/55003/20260).
```
import Data.List
foldr(\x p->zipWith(\a b->a-b*x)(p++[0])(0:p))[1].nub
```
I tried to shorten the lambda expression `\a b->a-b*x` by making it point-free, but best I have is `(+).(*(-x))` on switched inputs (thanks to @isaacg), which is the same length.
The lengthy import for `nub` is for the requirement to ignore duplicate roots. Without it, we'd have 49:
```
foldr(\x p->zipWith(\a b->a-b*x)(p++[0])(0:p))[1]
```
[Answer]
## Matlab, 56 bytes
Polynomial multiplication is convolution of their coefficients:
```
function y=f(R)
y=1;for r=unique(R);y=conv(y,[1 -r]);end
```
Floating-point roots are supported.
Example:
```
>> f([1 2])
ans =
1 -3 2
>> f([1 2 1])
ans =
1 -3 2
>> f([1 2.1 -3.2])
ans =
1.0000 0.1000 -7.8200 6.7200
```
[Answer]
# Ruby 2.7+, 60 58 57 50 bytes
```
->i{p=*1;(i&i).map{|x|p<<z=0;p.map!{-x*z+z=_1}};p}
```
Requires ruby 2.7+ for numbered arguments to work. Based on [xnor's python answer](https://codegolf.stackexchange.com/a/55003/100752)
Takes input as an array of roots, and returns an array of coefficients.
Thanks to [@Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) for -2 bytes!
Thanks to [Lydxn](https://codegolf.stackexchange.com/users/88546/dingledooper) for -1 byte
Thanks to [JoKing](https://codegolf.stackexchange.com/users/76162/jo-king) for -7 bytes.
[Answer]
# Julia, 41 bytes
Note: this is assuming the list is what matters, not the input/output format.
```
s->foldl((i,j)->[0,i]j+[i,0],1,unique(s))
```
[Answer]
# Pyth, 17 bytes
```
u-V+G0*LH+0GS{Q]1
```
17 bytes. A reduce over the input set. `+G0` is essentially `*x`, and `*LH+0G` is essentially `*r`, and `-V` performs element by element subtraction to perform `*(x-r)`.
[Demonstration.](https://pyth.herokuapp.com/?code=u-V%2BG0*LH%2B0GS%7BQ%5D1&input=1%2C%200%2C%20-1%2C%201&debug=0)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
QÆṛ
```
[Try it online!](https://tio.run/##y0rNyan8/z/wcNvDnbP/H25/1LTm//9oQx0Fo1gdhWhjHQUgMgMxzYBMEA2U0gVig1gA "Jelly – Try It Online")
Outputs them in order from the zero coefficient first. [+1 byte](https://tio.run/##y0rNyan8/z/wcNvDnbND/x9uf9S05v//aEMdBaNYHYVoYx0FIDIDMc2ATBANlNIFYoNYAA) to go the other way
It would just be a builtin (`Æṛ`) aside from the fact that duplicates shouldn't matter. Therefore we deduplicate the input first with `Q`, then use the builtin
[Answer]
# CJam, ~~24~~ 21 bytes
```
1al~_&{W*1$f*0\+.+}/`
```
Input format is a list in square brackets (e.g. `[1 2]`). Output format is the same. This is a full program. It might get slightly shorter if I package it as an anonymous function.
The approach is fairly straightforward: It starts out with `1` for the polynom, which is described by a coefficient array of `[1]`. It then multiplies it with `x - a` for each root `a`. This results in two arrays of coefficients:
* One from the multiplication with `-a`, which simply multiplies each previous coefficient by this value.
* One from the multiplication with `x`, which shifts the array of coefficients by 1, padding the open position with 0.
The two are then combined with a vector addition. I actually don't have to do anything for the second array, since CJam uses remaining array elements of the longer array unchanged if the other array is shorter, so padding the second array with a 0 is redundant.
[Try it online](http://cjam.aditsu.net/#code=1al~_%26%7BW*1%24f*0%5C%2B.%2B%7D%2F%60&input=%5B1%202%5D)
Explanation:
```
1a Put starting coefficient array [1] on stack.
l~ Get and interpret input.
_& Uniquify input array, using setwise and with itself.
{ Loop over roots given in input.
W* Negate value.
1$ Get a copy of current coefficient array to top.
f* Multiply all values with root.
0\+ Add a leading zero to align it for vector addition.
.+ Vector add for the two coefficient array.
}/ End loop over roots.
` Convert array to string for output.
```
[Answer]
# Javascript, 121 bytes
```
r=>{o=[...r,0].fill(0);for(i=2**r.length;i--;)e=r.length,a=r.reduce((a,q,j)=>a*(i&1<<j?q:(e--,-1)),1),o[e]+=a;return o;}
```
## Explantation
Similar to other answers, we imagine a polynomial of the form:
```
(r_1 - x) * (r_2 - x) * ... * (r_n - x)
```
And we want to multiply it out to get the polynomial:
```
a_0 * x^n + ... + a_n * x^0
```
This program does that by looping over every permutation of the input brackets. We can do this by counting in binary from 0 to 2^n. The i-th bit of that count tells us whether to multiply by r\_i, or by -x.
## Ungolfed:
```
function make_poly(roots) {
o = [...roots, 0].fill(0);
for (i = 0; i < 2 ** roots.length; i++) {
a = 1;
t_index = roots.length;
for (j = 0; j < roots.length; j++) {
if (i & (1 << j)) {
a *= roots[j];
} else {
a *= -1;
t_index--;
}
}
o[t_index] += a;
}
return o;
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
FȯmΣ∂Ṫ*moe1_u
```
[Try it online!](https://tio.run/##yygtzv7/3@3E@txzix91ND3cuUorNz/VML70////0YY6uoY6BrEA "Husk – Try It Online")
### Explanation
The idea is to generate the polynomials `(x-r0),…,(x-rN)` for the roots `r0,…,rN` and simply multiply them out:
```
F(mΣ∂Ṫ*)m(e1_)u -- accepts a list of roots, example: [-1,1,-1]
u -- remove duplicates: [-1,1]
m( ) -- map the following (eg. on 1):
_ -- negate: -1
e1 -- create list together with 1: [1,-1]
F( ) -- fold the following function (which does polynomial multiplication),
-- one step with [1,-1] and [1,1]:
Ṫ* -- compute outer product: [[1,1],[-1,-1]]
∂ -- diagonals: [[1],[1,-1],[-1]]
mΣ -- map sum: [1,0,1]
```
] |
[Question]
[
Given two points \$(x\_1, y\_1)\$ and \$(x\_2, y\_2)\$ with integer coordinates, calculate the number of integer points (excluding the given points) that lie on the straight line segment joining these two points. Use any [maths formula](https://math.stackexchange.com/questions/301890/how-many-points-between-two-points) you like, such as
$$gcd(|x\_2 - x\_1|, |y\_2 - y\_1|) - 1$$
**Input**
Four integer coordinates of the two points: \$x\_1, y\_1, x\_2, y\_2\$.
**Output**
Number of integer points between the two given points.
# Test Cases
[](https://i.stack.imgur.com/HMNZ7.png)
| Integer Coordinates | In-between Points |
| --- | --- |
| (5,10),(10,5) | 4 |
| (-8,5),(0,5) | 7 |
| (-3,-3),(2,2) | 4 |
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 3 bytes
```
εġ‹
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCLOtcSh4oC5IiwiIiwiWy01LDVdXG5bMTAsLTVdIl0=)
Port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/269088/100664).
```
ε # Absolute difference - [|x1-x2|,|y1-y2|]
ġ # gcd of that list
‹ # decrement
```
[Answer]
# [Desmos](https://desmos.com/calculator), 17 bytes
```
f(A,B)=gcd(A-B)-1
```
Takes input as two two-element lists.
This uses the formula as stated in the question, but it seems like `gcd` is always positive even with negative numbers, so I don't need to take the absolute difference, but rather just regular difference.
[Try It On Desmos!](https://www.desmos.com/calculator/y4nexswqiy)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ạg/’
```
A dyadic Link that accepts a point as a pair on each side and yields the count.
**[Try it online!](https://tio.run/##y0rNyan8///hroXp@o8aZv7//z/axEBHQdc49n@0kYGpjoKhZSwA "Jelly – Try It Online")**
### How?
Implements the provided greatest common divisor formula.
```
ạg/’ - Link: pair of integers [x1, x2]; pair of integers [y1, y2]
ạ - absolute difference (vectorises) -> [|x1-y1|, |x2-y2|]
/ - reduce by:
g - greatest common divisor -> GCD(|x1-y1|, |x2-y2|)
’ - decrement -> GCD(|x1-y1|, |x2-y2|) - 1
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes
```
≈đG←
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FisfdXYcmej-qG3CkuKk5GKo6IKbGtGmOoYGsQrRhgY6prFc0boWQEohGsox1tE1BvKMdIxiIRoA)
Takes input as two pairs of numbers, e.g. `[-8,5] [0,5]`.
```
≈đG←
≈ Absolute difference (vectorized)
đ Unpair; get the two elements of a pair
G GCD
← Decrement
```
---
>
> I wonder how an approach that defines the solution to be an integer point on the line, and using `-n` for the final result. (I haven't really tried to learn Nekomata yet and somehow doubt it would be shorter for this problem, but seems interesting) – [noodle man](https://codegolf.stackexchange.com/users/108687/noodle-man)
>
>
>
The shortest I can get using this approach is 10 bytes:
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 10 bytes
```
≈:Ṁᵉ{~Z*}¦
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FhsfdXZYPdzZ8HBrZ3VdlFbtoWVLipOSi6GyC26aRZvqGBrEKkQbGuiYxnJF61oAKYVoKMdYR9cYyDPSMQLyDHTA6ox0DE1jIdoB)
```
≈:Ṁᵉ{~Z*}¦ Take [-8,5] [0,5] as an example
≈ Absolute difference (vectorized)
[-8,5] [0,5] -> [8,0]
: Duplicate
[8,0] -> [8,0] [8,0]
Ṁ Maximum
[8,0] [8,0] -> [8,0] 8
ᵉ{ Apply the following block and then push the original top of stack
~Z Choose any integer in [1,n)
[8,0] 8 -> [8,0] 1 or [8,0] 2 or ... or [8,0] 7
* Multiply
[8,0] 1 -> [8,0]
[8,0] 2 -> [16,0]
...
[8,0] 7 -> [56,0]
} End the block (ᵉ pushes the original top of stack)
[8,0] -> [8,0] 8
[16,0] -> [16,0] 8
...
[56,0] -> [56,0] 8
¦ Divide and check if the result is an integer
[8,0] 8 -> [1,0]
[16,0] 8 -> [2,0]
...
[56,0] 8 -> [7,0]
```
`-n` counts the number of solutions, so the output is `7`.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 7 bytes [SBCS](https://github.com/abrudz/SBCS)
```
¯1+∨/⍤-
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=O7TeUPtRxwr9R71LdAE&f=MzRQMFVIA2JDAy4I89B6CwVTLiMFIzDbGIQB&i=AwA&r=tryapl&l=apl-dyalog-extended&m=train&n=f)
A tacit function which takes vectors on the left and right and returns an integer.
I believe this solution also works in any dimension, not just 2D. It takes the difference of the points, GCD all of the differences, and adds -1.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
NθNη≧⁻Nθ≔∨⁻ηNθηILΦ↔η∧ι¬﹪×ιθη
```
[Try it online!](https://tio.run/##Xc3BCsIwDAbgu0@RYwYV3MnDTkMQBDdFfIFuK2ugtrNNff3a2cswtz98yT9q6UcnTUoXu0Tu42tQHt9Vs9tmnXMnlzYEmu2DZs3YkY1BwFZVAtbDovDmi0H9p35MwPrz7skynmRgvCo7s8YzGc6oHYIzkVVuFtDaCUlA73Krm6Jx@KSXCuuuPCrTpFTDEeoD1Gn/MV8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: No vectorised difference or gcd, so I have to do things the hard way.
```
NθNη
```
Input the first co-ordinate.
```
≧⁻Nθ≔∨⁻ηNθη
```
Subtract the second co-ordinate, but if it is horizontal then make it diagonal, which has the same number of intermediate points.
```
ILΦ↔θ∧ι¬﹪×ιηθ
```
Generate a list of intermediate y-coordinates and see how many x-coordinates are integers.
[Answer]
# [Uiua](https://uiua.org), 12 bytes [SBCS](https://www.uiua.org/pad?src=0_7_1__IyBTaW5nbGUtYnl0ZSBjaGFyYWN0ZXIgZW5jb2RpbmcgZm9yIFVpdWEgMC44LjAKIyBXcml0dGVuIGhhc3RpbHkgYnkgVG9ieSBCdXNpY2stV2FybmVyLCBAVGJ3IG9uIFN0YWNrIEV4Y2hhbmdlCiMgMjcgRGVjZW1iZXIgMjAyMwojIEFQTCdzICLijbUiIGlzIHVzZWQgYXMgYSBwbGFjZWhvbGRlci4KCkNPTlRST0wg4oaQICJcMOKNteKNteKNteKNteKNteKNteKNteKNteKNtVxu4o214o21XHLijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbUiClBSSU5UQUJMRSDihpAgIiAhXCIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0-P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX7ijbUiClVJVUEg4oaQICLiiJjCrMKxwq_ijLXiiJril4vijIrijIjigYXiiaDiiaTiiaXDl8O34pe_4oG_4oKZ4oan4oal4oig4oSC4qe74paz4oeh4oqi4oeM4pmtwqTii6_ijYnijY_ijZbiipriipviip3ilqHii5XiiY3iip_iioLiio_iiqHihq_imIfihpnihpjihrvil6vilr3ijJXiiIriipfiiKfiiLXiiaHiip7iiqDijaXiipXiipziipDii4XiipniiKnCsOKMheKNnOKKg-KqvuKKk-KLlOKNouKsmuKNo-KNpOKGrOKGq-Kags63z4DPhOKInuK4ruKGkOKVreKUgOKVt-KVr-KfpuKfp-KMnOKMn-KVk-KVn-KVnCIKQVNDSUkg4oaQIOKKgiBDT05UUk9MIFBSSU5UQUJMRQpTQkNTIOKGkCDiioIgQVNDSUkgVUlVQQoKRW5jb2RlIOKGkCDiipc6U0JDUwpEZWNvZGUg4oaQIOKKjzpTQkNTCgpQYXRoVUEg4oaQICJ0ZXN0MS51YSIKUGF0aFNCQ1Mg4oaQICJ0ZXN0Mi5zYmNzIgoKRW5jb2RlVUEg4oaQICZmd2EgUGF0aFNCQ1MgRW5jb2RlICZmcmFzCkRlY29kZVNCQ1Mg4oaQICZmd2EgUGF0aFVBIERlY29kZSAmZnJhYgoKIyBFeGFtcGxlczoKIwojIFdyaXRlIHRvIC51YSBmaWxlOgojICAgICAmZndhIFBhdGhVQSAi4oqP4o2PLuKKneKWveKJoOKHoeKnuyziipdAQi4iCiMgRW5jb2RlIHRvIGEgLnNiY3MgZmlsZToKIyAgICAgRW5jb2RlVUEgUGF0aFVBCiMgRGVjb2RlIGEgLnNiY3MgZmlsZToKIyAgICAgRGVjb2RlU0JDUyBQYXRoU0JDUwo=)
```
-1;⍢⊃◿∘±°⊟⌵-
```
[Try it!](https://uiua.org/pad?src=0_7_1__ZiDihpAgLTE74o2i4oqD4pe_4oiYwrHCsOKKn-KMtS0KCmYgNV8xMCAxMF81CmYgwq84XzUgMF81CmYgwq8zX8KvMyAyXzIK)
```
-1;⍢⊃◿∘±°⊟⌵-
- # difference
⌵ # absolute value
°⊟ # uncouple pair to stack
;⍢⊃◿∘± # GCD
-1 # decrement
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 97 bytes
```
,(.+),(.+),
,$2¶$1,
%O`[^,]+
\d+
$*
-(1+),(1+)
$1$2
(1+),-?\1|[^1¶]
mO^`^.*
^(1(1*))\1*¶\1*$
$.2
```
[Try it online!](https://tio.run/##JYo7CgIxFEX7u443kM9L8EUCdpaWs4DJhAhaWGghlq4rC8jGYmaEw@EeuO/75/G69kldSmflrf4LTKFVEsY0lyXzapFuFmTglGynIZBQwJ7unOS7ZGl1BZ5zLtkbZCVKjNZJTKtDBPKh98hy2IhwJ468jyMPAocf "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
,(.+),(.+),
,$2¶$1,
```
Exchange the first y-coordinate with the second x-coordinate and split the coordinates onto separate lines.
```
%O`[^,]+
```
Ensure that if either coordinate is negative then the first one is.
```
\d+
$*
```
Convert to unary.
```
-(1+),(1+)
$1$2
```
If the co-ordinates have different signs then add their absolute values together.
```
(1+),-?\1|[^1¶]
```
Otherwise take the absolute difference.
```
mO^`^.*
```
Sort them descending in case the first difference is zero.
```
^(1(1*))\1*¶\1*$
$.2
```
Calculate the decremented GCD.
[Answer]
# [R](https://www.r-project.org), 62 bytes
```
\(x,y)max((y=1:max(z<-abs(x-y)))[!z[1]%%y&!z[2]%%y|!all(z)])-1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY37WI0KnQqNXMTKzQ0Km0NrUCMKhvdxKRijQrdSk1NzWjFqmjDWFXVSjUgwwjEqFFMzMnRqNKM1dQ1hJqSm6aRrGGiY2ipqZOsYWikY2yqqckFEjPVMTQAixnowIR0LYBMoBCSiLGOrjFIyEjHCCpkomMCEgBRKAKmIE0QSxcsgNAA)
Base R has no built in for GCD.
[Answer]
# APL(NARS), 9 chars
```
¯1+∨/∣⎕-⎕
```
test&how use:
```
¯1+∨/∣⎕-⎕
⎕:
¯8 5
⎕:
0 5
7
~
¯1+∨/∣⎕-⎕
⎕:
5 10
⎕:
10 5
4
~
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 50 bytes
```
(p,q,r,s)=>(g=r=>s?g(s,s=r%s):r*r)(r-p,s-=q)**.5-1
```
[Try it online!](https://tio.run/##bY3BCoJAFEX3fcVsghm5I/OsQSnGvkVMpRBH34t@fzJahcJZ3cPhPpt3Iy0/5ped4r1LfUh6xgKGmFDrIXCo5TZogQQ@irlwxkaznSE2LCbLcm8ptXGSOHb5GAfdaw9yX7wx18O/shU89s0JKwWKrXJrQaCtWEdUKM77ye8mkSoVOUUf "JavaScript (Node.js) – Try It Online")
Basically based on the formula in the question. Calculate
$$ \sqrt{\left(\text{gcd}(x\_2-x\_1,y\_2-y\_1)\right)^2}-1 $$
where \$\text{gcd}\$ is defined as
$$ \text{gcd}(x,y)=\begin{cases}
x & y=0 \\
\text{gcd}(y,x \bmod y) & \text{otherwise}
\end{cases} $$
[Answer]
# C (gcc), 104 bytes
*-5 bytes, thanks to @ceilingcat*
```
g(a,b){return b?g(b,a%b):abs(a);}main(x,y,a,b){scanf("%d%d%d%d",&x,&y,&a,&b);printf("%u",g(x-a,y-b)-1);}
```
[Try it online!](https://tio.run/##JYzLCsIwEAB/JQQaNrALrY@D7cFv2Y02FDRI02KC@OuuL@Y4wwSKIahGYBT/mM/LOicjxwiC3IjvWTKwH55XnhIUrPjrcuA0gm1Ofyy6gq6iY3Tih9s8peWrV4sRCjFWEk/dZ6O6aw1tzabdm@6g@grjhWNWur8B)
] |
[Question]
[
As the [June 2021 Language of the Month](https://codegolf.meta.stackexchange.com/questions/22414/language-of-the-month-for-june-2021-red) is [Red](https://www.red-lang.org/), what are some general tips for golfing in Red language?
Please suggest tips that are at least somewhat specific to Red (e.g. "remove comments" isn't a valid tip here).
Please one tip per answer!
[Answer]
## Type casting:
In Red you usually use `to <type> <spec>` or the predifined `to-<type> value` functions:
```
>> to integer! 3.14
== 3
>> to-integer 2.71
== 2
>> to char! 65
== #"A"
>> to-integer #"A"
== 65
```
`<type>` can be a datatype or an example value (a prototype). That's why we can shorten the above examples as follows:
```
>> to 1 3.14
== 3
>> to 0 2.71
== 2
>> to sp 65 ; sp is space = #" "
== #"A"
>> to 1 #"A"
== 65
```
Of course this can be applied to all datatypes that have literal representation:
```
>> to[]123 ; to block! 123
== [123]
>> to""[123] ; to-string [123]
== "123"
>> to 1-1-1[2 6 2021]; to-date [2 6 2021]
== 2-Jun-2021
>> to now[2 6 2021]
== 2-Jun-2021
>> to 0.0.0[255 0 0] ; to tuple! [255 0 0]
== 255.0.0
>> to sky[255 228 196] ; sky is a predifined color 164.200.255 (a tuple!)
== 255.228.196
>> to 1x1[-10 42]; to-pair [-10 42]
== -10x42
>> to#{}"string"; to-binary "string"
== #{737472696E67}
```
[Answer]
## String conversion with `do`
`do` is Red's equivalent of an `eval` command. It evaluates code as a string. It is useful when wanting to convert a string to an integer (or any valid Red expression):
```
to-integer n # The obvious way
to 0 n # From @GalenIvanov's type casting tip
do n # `do` is shortest
```
[Answer]
## Flatten a list of lists:
`form` the block into a string (`form` returns a user-friendly string representation of a value), then `load` the string (`load` returns a value or block of values by reading and evaluating a source)
```
>> b: [1 [2 3] [4 [5 6] 7]]
>> form b
== "1 2 3 4 5 6 7"
>> load form b
== [1 2 3 4 5 6 7]
>> b: [a b [c d [e f [g]]]]
== [a b [c d [e f [g]]]]
>> form b
== "a b c d e f g"
>> load form b
== [a b c d e f g]
```
[Answer]
# The many uses of `collect` and `keep`
`collect`'s help page shows the following:
```
USAGE:
COLLECT body
DESCRIPTION:
Collect in a new block all the values passed to KEEP function from the body block.
COLLECT is a function! value.
ARGUMENTS:
body [block!] "Block to evaluate."
REFINEMENTS:
/into => Insert into a buffer instead (returns position after insert).
collected [series!] "The buffer series (modified)."
```
basically, `collect` takes all values passed to `keep` within its argument block and returns a series with those return values.
Effectively, it works as a way in which you can apply any block of code to a series and collect results from it.
You can use it as a map:
`collect[foreach i arr[keep i + 1]]` (increments each array element)
a filter:
`collect[foreach i arr [if i < 2 [keep i]]]` (keeps all array elements less than 2)
and much more. It finds use in any general place where you need to gather values for a code golf question. I have used it in [this answer](https://codegolf.stackexchange.com/a/229240/80214) as a flatmap, for example.
[Answer]
## More on type casting
Another non-universal alternative to type conversion is to use some arithmetic operation on the identity value (in the desired type) for the operation and the value to convert:
`integer!` to `float!`:
```
>> to-float 5
== 5.0
>> to 0.0 5
== 5.0
>> 0.0 + 5
== 5.0
```
`char!` to `integer!`:
```
>> to-integer #"A"
== 65
>> to 0 #"A"
== 65
>> 0 +#"A"
== 65
```
`integer!` to `pair!` (a pair with equal `x` and `y` values)
```
>> as-pair 5 5
== 5x5
>> to-pair[5 5]
== 5x5
>> as-pair 5 5
== 5x5
>> to 1x1 5
== 5x5
>> 1x1 * 5
== 5x5
```
`integer!` to `tuple!` (a tuple with all parts equal)
```
>> to-tuple[255 255 255]
== 255.255.255
>> to 0.0.0[255 255 255]
== 255.255.255
>> 0.0.0 + 255
== 255.255.255
```
`integer!` or `float!` to `percent!`:
```
>> to-percent 12
== 1200%
>> to 1% 12
== 1200%
>> 0%+ 12
== 1200%
```
[Answer]
## Use `any` to provide a default value
Some functions (`find`, `select` and so on) could return `none`. The long way to structure your code around their result is to use conditionals - `if`, `either` etc.
Let's find the number of occurences of each character in the string "Tips for golfing in Red". `h` is a `map!` that wiil hold the frequencies.
The verbose way is to use `either key[true-code][false-code]` - if the `key` exists do `true-code`, otherwise do `false-code` :
```
h: #()
s: "Tips for golfing in Red"
foreach c s[h/:c: 1 + either k: h/:c[k][0]]
h
== #(
#"T" 1
#"i" 3
#"p" 1
#"s" 1
#" " 4
#"f" 2
#"o...
```
We can achieve the same result with `any` - it evaluates and returns the first truthy value. The first value in the block is the value we want to test for existence, the seconf one - the default value. So, if the key doesn'r exist, `any` will return the default value:
```
h: #()
s: "Tips for golfing in Red"
foreach c s[h/:c: 1 + any[h/:c 0]]
h
== #(
#"T" 1
#"i" 3
#"p" 1
#"s" 1
#" " 4
#"f" 2
#"o...
```
[Answer]
## Use `alter` instead of append/insert
Sometimes it is certain that the value we are appending to a list, is not aleady present. In such case we can use `alter` instead of `append` for 1 byte less.
`alter` appends a value if it's not found in the series, otherwise, removes it from the series.
```
>> b: [1 2 3 4 5]
== [1 2 3 4 5]
>> alter b 6
== true
>> b
== [1 2 3 4 5 6]
```
[Answer]
## `forall` instead of `foreach`
If you reference the current value of the series only once, you can save a byte by using `forall` instead of `foreach` :
```
>> p: [3 1 4 1 5 9 2]
== [3 1 4 1 5 9 2]
>> foreach n p[prin n]
3141592
>> forall p[prin p/1]
3141592
```
[Answer]
## Use some of the predefined `char!` values
```
>> ? char!
null #"^@"
newline #"^/"
slash #"/"
escape #"^["
comma #","
lf #"^/"
cr #"^M"
space #" "
tab #"^-"
dot #"."
sp #" "
dbl-quote #"^""
```
`sp` for space (`#" "` or `" "`), `lf` for newline (`#"^/"` or `"^/"`), `tab` (`#"^-"` or `"^-"`) etc. can save you a byte if enclosed in brackets or between strings:
```
either a/1 = i[1][" "]
either a/1 = i[1][sp]
```
] |
[Question]
[
## Task
A Rotate-Left-Double number in base \$n\$ is a number \$m\$, when its base-\$n\$ digits are rotated left once, equals \$2m\$. The base-\$n\$ representation of \$m\$ cannot have leading zeros.
One example in base 7 is the number 480, or \$1254\_7\$. When rotated left once, the value becomes \$2541\_7 = 960\$.
Given the base \$n \ge 2\$, determine if there exists a Rotate-Left-Double number in base \$n\$.
You can use your language's convention to represent truthy/falsy, or use two distinct values for truthy and falsy respectively.
## Scoring and winning criterion
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins.
## Test cases
```
n -> answer (example if true)
-----------------------------
2 -> false
3 -> false
4 -> false
5 -> true (13 x 2 = 31)
6 -> false
7 -> true (1254 x 2 = 2541)
8 -> true (25 x 2 = 52)
9 -> true (125 x 2 = 251)
10 -> false
11 -> true [3,7]
12 -> true [2,4,9,7]
13 -> true [1,2,4,9,5,11,10,8,3,7]
14 -> true [4,9]
15 -> true [1,2,4,9,3,6,13,12,10,5,11,8]
16 -> true [2,4,9]
17 -> true [1,2,4,9]
```
[Reference implementation in Python.](https://tio.run/##bVFdb4IwFH3nV5xkWQSsRvBlqfGXNH2ga9VmeGEIW/317BbJcMlemvbm3PPV9t5fGirH0boT@sZUN5eSMJlMEHCE0gm@L752IEnC8sT6r2tjJ8wBYVu1rSOb2ixB5/qhIwQl5abQSSQ8dc31mXKGdM4O7y6tq6uxFYK4S4TcrO8CJLDLkuTUdDDwjKzo7NJSFG9xve089TAiwefgBhf9qaAR0WFBF6yl4U/M8IoSrr65f3GlMKLMfgNOlCwCYt7psW2bNmU7iGR/oiBn4uPxaagKqbEGKVloAQ47m6UDTOeqDyZ5mSd8jU784mTqhoWZk9XXUF4/3iFO5l9ZtNh4lscjgtgalZM6@4kbKrYv5wTz91A5p6jqOg1qs2c4qyu10/leQBleyfdPDU3bmVx6ZkOxyOjzEWNFTX/xdF6N4w8)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÍD<&Ā
```
-1 byte thanks to *@xnor* and *@Noodle9*.
[Try it online](https://tio.run/##yy9OTMpM/f//cK@LjdqRhv//DQ0A) or [verify the first \$[2,100]\$ test cases](https://tio.run/##yy9OTMpM/W90senojrJKeyUFXTsFJftKl/@He11s1I40/Nf5DwA).
**Explanation:**
```
Í # Decrease the (implicit) input-integer by 2
# Check that this input-2 is a power of 2 by:
D # Duplicating it
< # Decrease the copy by 1 (so integer-3)
& # Take the bitwise-AND of input-2 and input-3
Ā # Check that this is NOT 0
# (after which the result is output implicitly)
```
***But wait, I don't see any use of bases nor rotation!***
When I saw the challenge in the Sandbox and was working on a solution, I noticed that the only falsey values in the first \$n=[2,500]\$ bases formed the sequence [A056469](http://oeis.org/A056469): *number of elements in the continued fraction for \$\sum\_{k=0}^n (\frac{1}{2})^{2^k}\$*, which could be simplified to \$a(n)=\left\lfloor2^{n-1}+2\right\rfloor\$. Here a copy of the first 25 numbers in that sequence as reference:
```
2, 3, 4, 6, 10, 18, 34, 66, 130, 258, 514, 1026, 2050, 4098, 8194, 16386, 32770, 65538, 131074, 262146, 524290, 1048578, 2097154, 4194306, 8388610
```
It can also be note that all the numbers in this sequence are of the form \$a(n)=2^n+2\$, so checking whether \$n-2\$ is a power of \$2\$ will verify whether it's in this sequence. Since we want to do the invert here, and having a falsey result if it's in this sequence (or truthy if it's NOT in this sequence), we'll do just that, resulting in the code above.
**Mathematical proof that all falsey cases of the Left-Rotate-Double numbers are of the form \$2^n+2\$:**
[Quote from @saulspatz at the Math SE](https://math.stackexchange.com/a/3605418/368863), who provided me with this Mathematical proof to back up my theory I based on the first \$n=[2,500]\$ test cases. So all credit for this proof goes to him/her.
If \$m\$ is a \$(d+1)\$-digit Rotate-Left-Double number in base \$n\$, then $$m=xn^d+y\tag1$$ where \$d\geq1,\ 0<x<n,\ 0\leq y<n^d\$. (Includes the rule that the number can't start with \$0\$.) Rotating \$m\$ gives \$ny+x\$, so we have \$2xn^d+2y=ny+x\$ or $$(n-2)y=(2n^d-1)x\tag2$$ If \$n=2^k+2\$ then \$(2)\$ gives \$(n-2)|x\$ (which means \$x\$ is divisible by \$(n-2)\$), since \$2n^s-1\$ is odd. But then \$y\geq 2n^d-1\$ which contradicts \$y<n^d\$.
To show that these are the only falsey numbers, let \$p\$ be an odd prime dividing \$n-2\$. (Such a \$p\$ exists because \$n-2\$ is not a power of \$2\$.) In \$(2)\$ we can take \$x=\frac{n-2}p<n\$ and we have to show that there exist an exponent \$d>0\$ and \$0\leq y<n^d\$ such that $$py = 2n^d-1$$ If we can find a \$d\$ such that \$p|(2n^d-1)\$, we are done, for we can take \$y = \frac{2n^d-1}p<n^d\$.
By assumption, \$n-2\equiv0\pmod{p}\$ so \$n\equiv 2\pmod p\$. Therefore, $$2n^d\equiv1\iff 2\cdot2^d\equiv1 \iff 2^{d+1}\equiv 1\pmod p,$$ and by [Fermat's little theorem](https://en.wikipedia.org/wiki/Fermat%27s_little_theorem), which states that \$a^{p-1}\equiv 1\pmod p\$, we can take \$d=p-2\$, because $$2^{p-2+1}\equiv 1 \iff 2^{p-1}\equiv 1 \pmod p$$
This completes the proof.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~19~~ 18 bytes
Uses [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s [formula](https://codegolf.stackexchange.com/a/202945/9481).
Returns `True`/`False`.
Saved a byte thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!
```
lambda n:n-2&n-3>0
```
[Try it online!](https://tio.run/##ZZDBbsIwEETv/ooVh9qWFsTaCQGk8COQQ9omIhI1UexIQYhvT21CcVtu45l567XbizuejR7r/DCeyq/3zxLM1szVm5nr3XJ0kAPnnCmY76AuT7ZiOsokyjRI1/UVCNIwgPKgJslWsZL9qqg0eZS88rV1zFT6SFIl2eYP80Q8Qcs4mehZ22vMCkYqGgoT3NxNHU3CyU6RCGmJa5y4JFZ87I30ldG4QtJIKoD3AWtfXP270VvZC1uw8Jmuss76d@xFY5wYJAIPLQ6NgYuE@tzBgJdwEuXCtqfGCR5G8SkrQ@IW1nVNK@RP4WC4lAXr/FzR80OvsuSDI0ySNJcssA6rOx022DIIW9TCSQZtF3apZ1d3C1dd7Q2u3d7meVXcZnL8Bg "Python 3 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 21 bytes
```
.+
$*
^11(1(11)+)\1*$
```
[Try it online!](https://tio.run/##DcK7CYAwAEXR/s6hEBOQvHx1ApcQ0cLCxkLcP8o5z/le99F6s@xtdHSWTTI/DW5YZbvWApFEplCZmJFHQgFFlFBGBVU0oZngPw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: The first stage converts to unary, while the last stage uses @KevinCruijssen's observation that a solution exists if `n-2` has a nontrivial odd factor.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 bytes
```
⊃∧/⊤⎕-2 3
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@jruZHHcv1H3UtedQ3VddIwRgkzAXEJanFJVxWbvlFCpkKVp55Co96NxsacKVxWbnmpQBFQUr@c4IVGXEZc5lwmXKZcZlzWXBZcgGVGRoCAA "APL (Dyalog Extended) – Try It Online")
A full program that takes a single number \$n\$ from stdin, and prints 1 for true, 0 otherwise. APL doesn't have bitwise functions, so we need to explicitly convert to binary and apply boolean functions on each bit.
### How it works
```
⊃∧/⊤⎕-2 3 ⍝ Input: n (from stdin)
⎕-2 3 ⍝ [n-2, n-3]
⊤ ⍝ Convert to binary
⍝ (each number becomes a column in a matrix, aligned to bottom)
⊃∧/ ⍝ Check if the MSB of both numbers are 1,
⍝ i.e. the bit lengths of the two are the same
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 19 bytes
Uses [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s [formula](https://codegolf.stackexchange.com/a/202945/9481).
Returns \$1\$ for falsy and \$0\$ for truthy.
```
f(n){n=!(n-2&n-3);}
```
[Try it online!](https://tio.run/##ZY7BCsIwEETv@YqxUNnQBNp6EWL8kdqDpI304Cqtt5BvjwkiHoTHMAzLzDp9cy4lTywD2x2x7vesD9LEdL8uTDKIhV@YhxEWoVP40H61/fM/ohH@sYJKAdvegE/d0aBpWCIIlHjLrWXbCDzXHHiq6gn6jKxUT/LClQIrbBlr5yG/N@bjKGJ6Aw "C (gcc) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 14 bytes
Port of Kevin Cruijssen's answer, remember to upvote them!
```
->x{x-2&x-3>0}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf166iukLXSK1C19jOoPZ/Wn6RQqZCZp6CkZ6eoQGXAhAUlJYUK6RFZ8Zypeal/AcA "Ruby – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 5 bytes
In GolfScript 0 is falsy while any other value is truthy.
```
2-.(&
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPlvaP7fSFdPQ@3/fwA "GolfScript – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 10 bytes
In JS 0 is falsy and everything else is truthy. Again, another port of Kevin Cruijssen's answer!
```
x=>x-2&x-3
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@mYKvwv8LWrkLXSK1C1/h/Wn6RRqatkXWmjaGBdaa2tiaXAhAk5@cV5@ek6uXkp2ukaWRqav4HAA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~22~~ 20 bytes
Uses [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s [formula](https://codegolf.stackexchange.com/a/202945/9481).
Returns \$1\$ for falsy and \$0\$ for truthy.
Saved 2 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!
```
echo $[!($1-2&$1-3)]
```
[Try it online!](https://tio.run/##S0oszvifpqFZ/T81OSNfQSVaUUPFUNdIDUgYa8b@r@VKyy9SyFPIzFOoNtLTMzSvtVZIyedSgCjOU1DStVNSUNFIA7I1uVLy81L/AwA "Bash – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes
```
‹¹Σ⍘⊖⊖N²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMntbhYw1BHIbg0V8MpsTg1uAQonK7hkppclJqbmleSmoLC9swrKC3xK81NSi3S0NTU1FEwApKa1v//Gxr81y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if RLD numbers exist otherwise no output. Explanation:
```
N Input as a number
⊖⊖ Decremented twice
⍘ ² Converted to base 2
Σ Digital sum
‹¹ Is greater than 1
```
The only binary numbers with a digital sum of `1` or less are `0` and powers of `2`, so by @KevinCruijssen's proof a solution exists for all other values of `n`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
¬εΣḋ≠2
```
[Try it online!](https://tio.run/##ASIA3f9odXNr/8K2beKCgeKApjIgMTf/wqzOtc6j4biL4omgMv// "Husk – Try It Online")
This one got simplified *really* quickly.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
_2&’$
```
[Try it online!](https://tio.run/##y0rNyan8/z/eSO1Rw0yV/4fbHzWtOTrp4c4Z//@b6igYGgCxKQA "Jelly – Try It Online")
Uses the fact that a given \$n\$ returns \$0\$ iff \$n-2\$ is a power of \$2\$, as pointed out by [Kevin Cruijssen](https://codegolf.stackexchange.com/a/202945/66833) and the `n-2 & n-3` trick
## How they work
```
_2&’$ - Main link. Takes n on the left
_2 - n-2
$ - To n-2:
’ - Decrement; n-3
& - n-2 & n-3
```
] |
[Question]
[
# The Rundown
Given any input **x** and **y**, perform a complex operation, and print a corresponding result.
# How your program should work
1. Given an input **x** and **y** in the form **z = x+yi**, find **zi-z**
2. If the absolute real value of **zi-z** is larger than the absolute imaginary part, print the real part; vice versa for the other way around. If both values are equal, print one of the values.
# Example
```
x: 2
y: 0
```
Therefore:
```
z = 2
z^(i-z) ~= 0.192309 + 0.159740i
```
Since the real part has a larger absolute value than the imaginary part, the program returns
```
0.192309
```
### More examples
```
z = 1+i >> 0.5
z = i >> 1
z = 0.5 >> 1.08787
z = -2+8i >> 2.22964E7
z = -10i >> 3.13112E7
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 11 bytes
Thanks Johnathan Allan for updating the answer with the rules change.
```
ı_*@µĊ,ḞAÞṪ
```
[Try it online!](https://tio.run/nexus/jelly#ASUA2v//xLFfKkDCtcSKLOG4nkHDnuG5qv///y0yKzFq9W5vLWNhY2hl "Jelly – TIO Nexus")
```
ı_*@ z^(i-z)
µ new monadic link
Ċ,Ḟ pair real and imaginary parts
AÞṪ sort by absolute value and take last value
```
[Answer]
# Python 2, 45 bytes
```
def f(z):z=z**(1j-z);print max(z.real,z.imag)
```
[**Try it online**](https://tio.run/nexus/python2#HchBDsIgEADAO6/guFssYZuYGIyPIboopG0Iwdju56l6mcP0B0cdQdDLTYYBKI@C11LT2vQSNhBbOcwnsWkJT@yt7l7pzyvNrMlHSGt5N0BUvN25NO/6ZFxWZCgr98eefzFO5vKVXD4A) - *all test cases*
Programming languages often use `j` instead of `i`. That is the case in Python. See [this SO question](https://stackoverflow.com/q/24812444/2415524) for more information on why.
[Answer]
## Mathematica, 21 22 bytes
*Edit: Thanks to JungHwan Min for saving 3 btyes*
```
Max@ReIm[#^(I-#)]&
```
Pure function which expects a complex number as an argument. If an exact number is passed, then an exact number will be returned (e.g. `1/2` gives `Sqrt[2] Cos[Log[2]]`). The problem spec was edited after I posted my solution to specify that the absolute value should be used. The best I can come up with for that is `MaximalBy[ReIm[#^(I-#)],Abs][[1]]&` or `Last@MaximalBy[Abs]@ReIm[#^(I-#)]&`, both `34` bytes.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 29 bytes
```
@(z)max(real(z^(i-z)./[1 i]))
```
This defines an anonymous function. It works in MATLAB too.
[Try it online!](https://tio.run/nexus/octave#@@@gUaWZm1ihUZSamKNRFaeRqVulqacfbaiQGaup@T9NwVYhMa/YmitNw1A7U1NHIU0DQhqCSV0jbQsIX9fQIFPzPwA "Octave – TIO Nexus")
### Explanation
Element-wise dividing (`./`) the number `z^(i-z)` by the array `[1 i]` and taking the real part gives an array with the real and imaginary parts of `z^(i-z)`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
Jy-^&ZjhX>
```
[Try it online!](https://tio.run/nexus/matl#@@9VqRunFpWVEWH3/7@ukbZFJgA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/jvVakbpxaVlRFh998l5L@hdiZXJpchl66RtkUml66hQSYA).
### Explanation
Consider input `-2+8i` as an example.
```
J % Push i (imaginary unit)
% STACK: i
y % Implicit input. Duplicate from below
% STACK: -2+8i, i, -2+8i
- % Subtract
% STACK: -2+8i, 2-7i
^ % Power
% STACK: 3168271.58+22296434.47i
&Zj % Real and imaginary parts
% STACK: 3168271.58, 22296434.47
h % Concatenate
% STACK: [3168271.58 22296434.47]
X> % Maximum. Implicitly display
% STACK: 22296434.47
```
[Answer]
# TI-BASIC, ~~40~~, ~~32~~, ~~31~~ 29 bytes
*Saved a byte thanks to [@Conor O'Brien](https://codegolf.stackexchange.com/users/31957/conor-obrien)*
```
Z^(i-Z→A #Perform operation, store as A, 8 bytes
:real(A)>imag(A #Test if real part is greater than imaginary, 9 bytes
:Ansreal(A)+imag(Anot(Ans #Determine output and print, 12 bytes
```
Takes input as a complex number on the `Z` variable.
TI-BASIC uses its own encoding, you can find it [here](http://tibasicdev.wikidot.com/tokens).
[Answer]
# Pyth, 16 Bytes
```
=b^Q-Q.j;eS,ebsb
```
[Answer]
# [Perl 6](http://perl6.org/), 24 bytes
```
{($_**(i-$_)).reals.max}
```
`$_` is the possibly complex argument; `$_ ** (i - $_)` is the expression to be computed; `.reals` is a `Complex` method that returns a list of the real and imaginary parts; and finally `.max` returns the larger of the two.
[Answer]
# C (GCC), ~~93~~ 79 + 4 (`-lm`) = ~~97~~ 83 bytes
*Saved 14 bytes thanks to @ceilingcat!*
```
float f(_Complex z){z=cpow(z,csqrt(-1)-z);return cimag(z)>creal(z)?cimag(z):z;}
```
Including the header `complex.h` is longer than that ¯\\_(ツ)\_/¯
[Try it online!](https://tio.run/nexus/c-gcc#bY7NCsIwEITvPkUoCBvbSFMQxKIefA0hhJCUQH5qGrGk@OrWWvDUHmZ2@GYPMyrjeUQK2M3b1sgeJTyks2j9C1IhukeIQCgmCddBxmdwSGjLG0j4IoLkZgrXPzml@j1arh3goQ3aRQXZVt3dUlmxUVDhn9OcMdlH6TrtHWOI6hmvwnJ/mC@p8uNu9YPQclls8LTrI5ThTTcSY78 "C (gcc) – TIO Nexus")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~25~~ 35 bytes
**EDIT**: Fixed to comply with new absolute value rule.
```
->z{(z**(1i-z)).rect.max_by(&:abs)}
```
[Try it online!](https://tio.run/nexus/ruby#@69rV1WtUaWlpWGYqVulqalXlJpcopebWBGfVKmhZpWYVKxZ@/8/AA "Ruby – TIO Nexus")
This creates an anonymous function.
[Answer]
# TI-Basic, ~~19~~ 16 bytes
```
Ans^(i-Ans
max(real(Ans),imag(Ans
```
`real(` and `imag(` are two-byte tokens.
Run with `5+3i:prgmNAME` (`5+3i` being the argmuent, `NAME` being the program name.)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 bytes
18 bytes (<https://github.com/abrudz/SBCS/>)
28 bytes (UTF-8)
⍵ is a complex number ajb = a+bi
```
{⌈/9 11∘.○⍵*0j1-⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRT4e@pYKh4aOOGXqPpnc/6t2qZZBlqAuka///BwA "APL (Dyalog Unicode) – Try It Online")
[Answer]
## R, 38 bytes
```
pryr::f({z=z^(1i-z);max(Re(z),Im(z))})
```
Anonymous function. Takes a (possibly) complex number `z`, takes it to the specified power, and then returns the `max` of the `Re`al and `Im`aginary parts.
[Answer]
# Axiom, 60 bytes
```
f(z:Complex Float):Float==(y:=z^(%i-z);max(real(y),imag(y)))
```
test code and results; i follow as the other the precedent version of the question...
```
(28) -> [[k,f(k)] for k in [1+%i,%i,1,-2+8*%i,-10*%i]]
(28)
[[1.0 + %i,0.5], [%i,1.0], [1.0,1.0],
[- 2.0 + 8.0 %i,22296434.4737098688 53],
[- 10.0 %i,31311245.9804955291 66]]
```
[Answer]
# C# - 189 Bytes
```
double f(double x, double y){double r,t,m,c;r=Math.Sqrt(x*x+y*y);t=Math.Atan2(y,x);m=Math.Pow(r,-x)*Math.Exp(y*t-t);c=Math.Cos((1-y)*Math.Log(r)-t*x);return m*(2*c*c<1?Math.Sqrt(1-c*c):c);}
```
Readable:
```
double f(double x, double y){
double r, t, m, c;
r = Math.Sqrt(x * x + y * y);
t = Math.Atan2(y, x);
m = Math.Pow(r, -x) * Math.Exp(y * t - t);
c = Math.Cos((1 - y) * Math.Log(r) - t * x);
return m * (2 * c * c < 1 ? Math.Sqrt(1 - c * c) : c); }
```
Explanation: Decided not to use any Complex libraries.
$$
\begin{align}
z & = x + iy \\
& = r e^{it} \\
z^{i-z} & = (re^{it})^{(-x +i(1-y))} \\
& = r^{-x} r^{i(1-y)} e^{-xit} e^{t(y-1)} \\
& = r^{-x} e^{t(y-1)} e^{i((1-y)\ln(r)-xt)} \text{ (as }r^i = e^{i\ln(r)}\text{)}
\end{align}
$$
Let this be equal to \$me^{ia}\$ where
$$m = r^{-x} e^{t(y-1)}$$
$$a = (1-y)\ln(r)-xt$$
Then \$\Re(z^{i-z})=m \cos a\$ and \$\Im(z^{i-z})=m \sin a\$
The maximum absolute value can be determined by the \$\cos a\$ and \$\sin a\$ terms, with these being equal at \$\frac{1}{\sqrt{2}}\$ (hence the test \$2c^2 < 1\$).
As mentioned, raising to a complex exponent is dependent on choosing a particular branch cut ( e.g. \$z = 1\$ could be \$e^{i\pi}\$ or \$e^{3i\pi}\$ - raising this to \$i\$ gives a real part of \$e^{-\pi}\$ or \$e^{-3\pi}\$ respectively), however, I have just used the convention of \$t \in [0,2\pi)\$ as per the question.
] |
[Question]
[
Coordinates in the flat-Earth world consist of latitude (x) and longitude (y), which are integers in the range 0...9999. Much like [Gaussian integers](https://en.wikipedia.org/wiki/Gaussian_integer), but they are always written using this notation:
```
411S 370E
```
That is, with `S` or `N` appended to the latitude, and `E` or `W` appended to the longitude, with space(s) between the two components.
# Goal
Write a program (not a function) that reads two coordinates, separated by whitespace, and outputs their sum. The first coordinate is a starting point, the second one is a displacement, and the output is the resulting position.
# Input/Output
Since this challenge is partially about formatting, I'll try to define the input and output formats unambiguously.
The preferred input format has 1 space between the coordinate components, no leading zeros, and a newline character between the two coordinates. The program must be able to read the preferred format.
The output can contain any amount of whitespace and leading zeros. If it's different from the preferred input format, the program must be able to read this format too.
Just to make it clear, the input cannot (will not) contain any additional formatting characters. Just spaces and newlines where needed.
# Scoring
This is an experiment on a new winning condition. I'll choose the winner by accepting an answer in a few weeks. If a better answer appears afterwards, I'll change the accepted answer.
The score for the program is its byte count. The winning program is one that is shorter than 400 bytes, has the fewest byte count, but is written in the *most verbose* programming language. To determine the winner:
* Remove programs with byte count 400 or more (they can participate but cannot win)
* Consider only the *shortest* program for each programming language
* The *longest* program wins
Polyglots compete against programs in all languages in which they are valid (e.g. if a program is valid in both `bash` and `sh`, it competes against programs in both languages).
# Test cases
In the test cases, the first two lines are the input, and the third line is the output.
```
0S 0E
0S 0W
0N 0E
```
(the direction of zero doesn't matter, both in input and output)
---
```
0S 9999E
9999N 9999W
9999N 0E
```
(maximal values)
---
```
42S 314W
42N 2718W
0N 3032W
```
(the direction of zero doesn't matter in the output)
---
```
5555N 8888W
7777S 0E
2222S 8888W
```
(no negative values; change the direction if you need to change the sign)
---
```
0001N 4545W
0999N 5454W
1000N 9999W
```
(if the program outputs leading zeros and several spaces, it must be able to read them; it must also be able to read input that doesn't contain them)
---
```
8888N 8888W
9999N 9999W
```
(invalid input - any behavior is acceptable, including crash and infinite loop)
[Answer]
## JavaScript (ES6), 118 bytes
```
s=>(g=([i,j,k,l,m,n],[o,p])=>(i=(j>p?-i:+i)+(n>p?-j:+j))<0?-i+o:i+p)(a=s.match(/\d+|\w/g),"SN")+' '+g(a.slice(2),"WE")
```
[Answer]
# MATLAB, ~~327~~ ~~304~~ ~~296~~ ~~290~~ ~~282~~ ~~276~~ ~~267~~ ~~259~~ ~~255~~ 253 bytes
I think I'm closing in on a limit now. I've managed to remove ~~51, 60~~ ~~68~~ ~~72~~ 74 bytes from an answer I thought was well golfed. =)
Removed 8 bytes by taking the `input` inside the `strsplit`, thanks to Luis Mendo. Removed another 6 bytes by taking all the input into one cell array instead of two. Removed another 8 bytes by taking both last statements inside `disp()`. Removed 6 bytes by removing `char` and some brackets. This wasn't possible in a previous revision of the answer. Splitting the cell elements into four variables costed 15 bytes, but saved 24, thus 9 bytes saved! 8 additional bytes due to improved `disp` scheme. `5*~~s` saves two bytes compared to `(s>0)*5`. Thus 4 new bytes saved (for s and t). Taking the opposite of this last expression saves yet another 2 bytes, `83-5*~s` is shorter than `78+5*~~s`
Golfed code:
```
x=strsplit([input('','s'),' ',input('','s')]);[a,b,c,d]=x{:};f=@str2num;n=@num2str;i=@sign;s=f(a(1:end-1))*i(a(end)-79)+f(c(1:end-1))*i(c(end)-79);t=f(b(1:end-1))*i(b(end)-79)+f(d(1:end-1))*i(d(end)-79);disp([n(abs(s)),83-5*~s,32,n(abs(t)),87-18*~t,''])
```
Same code, but with line breaks:
```
x=strsplit([input('','s'),' ',input('','s')]);
[a,b,c,d]=x{:};
f=@str2num;
n=@num2str;
i=@sign;
s=f(a(1:end-1))*i(a(end)-79)+f(c(1:end-1))*i(c(end)-79);
t=f(b(1:end-1))*i(b(end)-79)+f(d(1:end-1))*i(d(end)-79);
disp([n(abs(s)),78+5*~~s,32,n(abs(t)),69+18*~~t,''])
```
**Test cases:**
Save the above as `flat_earth.m`
```
flat_earth
0S 0E
0S 0W
0N 0E
flat_earth
0S 9999E
9999N 9999W
9999N 0E
flat_earth
42S 314W
42N 2718W
0N 3032W
flat_earth
5555N 8888W
7777S 0E
2222S 8888W
flat_earth
0001N 4545W
0999N 5454W
1000N 9999W
```
[Answer]
# ABAP, ~~377~~ 365 bytes
```
REPORT r.PARAMETERS: x TYPE string,y TYPE string.DEFINE m.SHIFT &1 RIGHT CIRCULAR.TRANSLATE &1 USING 'W-E+S-N+'. END-OF-DEFINITION. DEFINE o.&1 = |{ &1 * 1 SIGN = RIGHTPLUS DECIMALS = 0 }|.TRANSLATE &1 using &2. END-OF-DEFINITION.
SPLIT: x AT space INTO DATA(a) DATA(b),y AT ' ' INTO DATA(c) DATA(d). m: a,b,c,d.a = a + c.b = b + d.o: a '-S+N',b '-W+E'.WRITE: a, b.
```
Ungolfed:
```
REPORT r.
PARAMETERS: x TYPE string,
y TYPE string.
DEFINE m.
SHIFT &1 RIGHT CIRCULAR.
TRANSLATE &1 USING 'W-E+S-N+'.
END-OF-DEFINITION.
DEFINE o.
&1 = |{ &1 * 1 SIGN = RIGHTPLUS DECIMALS = 0 }|.
TRANSLATE &1 using &2.
END-OF-DEFINITION.
SPLIT: x AT space INTO DATA(a) DATA(b),y AT ' ' INTO DATA(c) DATA(d).
m: a,b,c,d.
a = a + c.
b = b + d.
o: a '-S+N',b '-W+E'.
WRITE: a, b.
```
It was actually challenging to be within 400 characters.
Some notes:
* Original version had `ADD c TO a.` which is one of my favourite verbose statements.
* The built-in editor would not accept this as a 1 liner
* Using subroutines with `FORM` and `PERFORM` exploded the char count, so I kept to macros
* Chaining statements with colons is discouraged outside of data declarations, but was needed for saving bytes
* `+` without a preceding space is an offset operator, requiring many spaces in the code
* ABAP writes a space after numbers, hence the trick to just replace the sign
* In order to use `RIGHTPLUS` the expression needed to be a number, so the need to mulitply with 1, but then the format has decimals.. so hence `DECIMALS`
[Answer]
# R, 196 bytes
R is pretty verbose, by golfing standards. Let's see...
```
i=scan(,'');l=nchar(i);S=W=`-`;N=E=c;n=as.double(substr(i,1,l-1));d=substr(i,l,l);for(j in 1:4)n[j]=get(d[j])(n[j]);o=c(n[1]+n[3],n[2]+n[4]);cat(paste0(abs(o), ifelse(o<0,c("S", "W"),c("N","E"))))
```
Ungolfed:
```
input = scan(,'') # Take input from stdin, separating at newlines and spaces
length = nchar(input) # Get the number of characters in each input
S=W=`-` # These two lines create aliases of `-` (the minus function)
N=E=c # and c (the concatenate function).
# We will later treat the NSEW part of the coordinate
# as a call to a function, to ensure that the numbers
# are treated with the correct polarity.
numbers = as.double(substr(input, 1, length-1))
# Strip the last character off of every coordinate, convert
# to integer
directions = substr(input, length, length)
# Strip off the numbers and grab the cardinal directions
for(j in 1:4)
numbers[j] = get(directions[j])(numbers[j])
# For our four numbers, treat the cardinal direction as
# a function, which is mapped to `-` for south and west, and
# `c` for north and east (which is essentially identity)
output = c(numbers[1]+numbers[3], numbers[2]+numbers[4])
# Add together the numbers
cat(paste0(abs(output), ifelse(output<0, c("S", "W"), c("N","E"))))
# Output the absolute values of the new coordinates, followed
# by "S" or "W" if the number is negative and "N" or "E" if
# the number is positive
```
Edit to add: I just looked at the other answers, and I'm surprised that my entry is one of the shortest! Perhaps R isn't as verbose as I thought...
[Answer]
# Java, 372 bytes
```
import static java.lang.System.*;class A{public static void main(String[]v){String l=" ",s=console().readLine()+l+console().readLine();Integer i=0,n[]=new Integer[4],y;for(;i<4;i++)n[i]=i.parseInt(s.replaceAll("[A-Z] *",l).split(l)[i])*(s.replaceAll("\\d| ","").charAt(i)==(i%2<1?83:87)?1:-1);i=n[0]+n[2];y=n[1]+n[3];out.println((i<0?-i+"N":i+"S")+l+(y<0?-y+"E":y+"W"));}}
```
### Ungolfed
```
import static java.lang.System.console;
import static java.lang.System.out;
class A {
public static void main(String[] v) {
String l = " ", s = console().readLine() + l + console().readLine();
Integer i = 0, n[] = new Integer[4], y;
for (; i < 4; i++)
n[i] = i.parseInt(s.replaceAll("[A-Z] *", l).split(l)[i]) * (s.replaceAll("\\d| ", "").charAt(i) == (i % 2 < 1 ? 83 : 87) ? 1 : -1);
i = n[0] + n[2];
y = n[1] + n[3];
out.println((i < 0 ? -i + "N" : i + "S") + l + (y < 0 ? -y + "E" : y + "W"));
}
}
```
### Notes
* Save as `A.java`, compile with `javac A.java`, run with `java A`. Then enter the inputs line separated or as two separate inputs on stdin.
### Outputs:
```
0S 0E
0S 0W
0S 0W
0S 9999E
9999N 9999W
9999N 0W
42S 314W
42N 2718W
0S 3032W
5555N 8888W
7777S 0E
2222S 8888W
0001N 4545W
0999N 5454W
1000N 9999W
8888N 8888W
9999N 9999W
18887N 18887W
```
[Answer]
# SQL (PostGreSQL 9.4), 305 bytes
```
PREPARE p(char,char)AS
SELECT string_agg(abs(n)||substr('SNNEEW',i+sign(n)::int,1),' ')FROM(SELECT i,sum(to_number(v,'9999')*CASE right(v,1)WHEN'N'THEN 1 WHEN'E'THEN 1 ELSE -1 END)n
FROM(SELECT CASE WHEN v~'[NS]' THEN 2 ELSE 5 END i,v
FROM regexp_split_to_table($1||' '||$2,' ')v)i
GROUP BY i ORDER BY i)g
```
Implemented as a prepared statement that takes 2 character parameters. One parameter for each input line.
It is called as follows
```
execute p('0S 9999E','9999N 9999W');
```
and outputs a row containing a single character column for the result. `9999N 0E`
[Answer]
# Java, 308 bytes
```
import java.util.*;class x{public static void main(String[]a){Scanner r=new Scanner(System.in);int[]v=new int[2];int l,x,g,i;for(i=5;i-->1;System.out.println(i<3?""+x*g+"ENWS".charAt(i-g):"")){String s=r.next();x=Integer.parseInt(s.substring(0,l=s.length()-1));x=v[i%2]+=x*=s.charAt(l)>80?-1:1;g=x<0?-1:1;}}}
```
A more readable version:
```
import java.util.*;
class x
{
public static void main(String[]args)
{
Scanner r = new Scanner(System.in);
int[] v = new int[2];
for (int i = 5; i-->1; )
{
String s = r.next();
int l = s.length() - 1;
int x = Integer.parseInt(s.substring(0, l));
x = v[i%2] += x *= s.charAt(l) > 'N' ? -1 : 1;
int g = x < 0 ? -1 : 1;
System.out.println(i < 3?"" + x * g + "ENWS".charAt(i-g):"");
}
}
}
```
---
Golfing in Java is a special kind of fun. The following two lines of code do the same, but the first one is shorter:
```
(x<0?-x:x)
Math.abs(x)
```
---
The code reads 4 tokens from standard input. For each token, the part up to the last character is converted to `int`, and the last character optionally flips its sign.
Then it adds the value that was read 2 iterations ago. Java initializes arrays to 0, so at the first two iterations this will do the right thing.
Then it will format the values and print them. However, in the first two iterations, it prints the empty string instead (so two extra linebreaks appear in the output).
It uses some funky arithmetic so the iteration variable (4,3,2 or 1) and the sign (-1 or 1) can be combined to a zero-based index into the string `"ENWS"`.
[Answer]
# Perl 6, 130 bytes
```
my (\h,\v)=[Z+] lines».split(' ')».map: {m/(.*)(.)/;$1 eq'S'|'W'??-$0!!$0}
say "{abs h}{h <0??'S'!!'N'} {abs v}{v <0??'W'!!'E'}"
```
[Answer]
# Ruby, 186 bytes
It's too short, sorry. I did my best.
```
x=-1
puts gets.scan(/\d+\D/).map{|i|i.to_i*(i[-1]=~/[WS]/?-1:1)}.zip(gets.scan(/\d+\D/).map{|i|i.to_i*(i[-1]=~/[WS]/?-1:1)}).map{|a,b|a+b}.map{|s|s.abs.to_s+%w"NNS EEW"[x+=1][s<=>0]}*' '
```
[Answer]
# C - 267 bytes
I though C would be long... might as well just put it up. ;\_;
```
#include <stdio.h>
#include <stdlib.h>
int main(){int x,y,z,w;char m,n,o,p;scanf("%d%c %d%c",&x,&m,&y,&n);scanf("%d%c %d%c",&z,&o,&w,&p);int a=x*(m<'O'?1:-1)+z*(o<'O'?1:-1),b=y*(n<'F'?1:-1)+w*(p<'F'?1:-1);printf("%d%c %d%c\n",abs(a),a<0?'S':'N',abs(b),b<0?'W':'E');}
```
[Answer]
## [Befunge-93](https://esolangs.org/wiki/Befunge), 240 bytes
```
v
v$ <
>&>~:" "-!|
vp01p02 <
v$ <
>&>~:" "-!|
vp03p04 <
v$ <
>&>~:" "-!|
vp05p06 <
v$ <
>&>~:" "-!|
vp07p08 <
v>30g70g40g80g-!
_-:0` v1+
\v\g04_01-*80g
v>10g50g20g60g-!
_-:0` v1+
\v\g02_01-*60g
@>.," ",.,
```
Note that the [interpreter](http://www.quirkster.com/iano/js/befunge.html) has a single line input box. Pasting the *preferred format* replaces the newline with a space. Getting integer values with `&` already consumes leading spaces and zeros, so the *preferred format* can be read to the stack with `&~&~&~&~` alone. Adding steps to put the values in a blank line so that one can retrieve and compare the vectors one coordinate at a time, the following 136 byte program (excluding notes right of line) can be used:
```
v | blank line to store data
> &10p~20p&30p~40pv | read and store first vector
vp08~p07&p06~p05&< | (backwards) read and store second vector
v>30g70g40g80g-! | load E/W coordinates
_-:0` v1+ | subtract or add (based on direction)
\v\g04_01-*80g | change directions if negative
v>10g50g20g60g-! | load N/S coordinates
_-:0` v1+ | subtract or add (based on direction)
\v\g02_01-*60g | change directions if negative
@>.," ",., | output
```
**The Catch:** The output forces an additional space after integers, so it is impossible to output in the *preferred format*. For example, output will appears as `1000 N 9999 W` instead of `1000N 9999W`. To check for and ignore spaces before each coordinate's direction on input, four additional loops (one for each coordinate) are needed. A single loop is shown below:
```
v$ < | throw out " " and repeat
>&>~:" "-!| | (start read number) get and check character
vp01p02 < | store
```
The resulting program can have multiple spaces anywhere in the input (except between digits).
*Example Input:* `0001 N 4545 W 0999 N 5454 W`
[Answer]
# Lua, ~~333~~ 328 bytes
Features high-level invalid input system and absolutely innovative infinite loop for repeated use.
```
m=math.abs p=print::e::c={}for i=1,2 do for s in io.read():gmatch'%S+'do c[#c+1]=s end end for i=1,4 do n=c[i]:sub(1,-2)d=c[i]:sub(-1,-1)c[i]=d==("N"or"E")and n or-n end x=c[2]+c[4]y=c[1]+c[3]a=m(x)b=m(y)if(a or b)>9999 then p'Invalid input\n'goto e end x=x<0 and a.."W"or a.."E"y=y<0 and b.."S"or b.."N"p(y.." "..x.."\n")goto e
```
Enjoy ;)
Edit: saved 5 bytes from renaming `math.abs` as `m` and `print` as `p`
[Answer]
**PHP 291 Bytes.**
```
<?php $E=0;$N=0;$l=explode(PHP_EOL,STDIN);foreach($l as $i){ $x=explode(' ',$i); $s=(substr($x[0],-1,1)=='N')?1:-1; $N=$N+((substr($x[0],0,-1)*$s));$s=(substr($x[1],-1,1)=='E')?1:-1;$E=$E+((substr($x[1],0,-1))*$s);}$l=($E<=0)?'W':'E';$u=($N<=0)?'S':'N';echo'<br/>'.abs($N).$u.' '.abs($E).$l;
```
Does not do anything clever, just plods through the problem.
```
<?php
$lines = explode(PHP_EOL, STDIN);
foreach ($lines as $line) {
$bits = explode(' ', $line);
$sign = (substr($bits[0],-1, 1) == 'N')? 1 : -1;
$N = $N + ( (substr($bits[0],0,-1) * $sign) );
$sign = (substr($bits[1],-1, 1) == 'E')? 1 : -1;
$E = $E + ( (substr($bits[1],0,-1)) * $sign );
}
$side = ($E<=0)?'W':'E';
$up = ($N<=0)?'S':'N';
echo '<br />'.abs($N).$up.' '.abs($E).$side;
```
The rules should have an additional clause saying only the language with at least 2 entries can win.
[Answer]
# PHP, 169 bytes
Inspired by @Paul Drewett:
```
<?for($i=2;$i--;$e+=$p[1]*(substr($p[1],-1,1)<W?:-1))$n+=($p=explode(' ',trim(fgets(STDIN))))[0]*(substr($p[0],-1)<S?:-1);echo abs($n),'NS'[$n<0],' ',abs($e),'EW'[$e<0];
```
**breakdown**
```
for($i=2;$i--; // loop twice
$e+=$p[1]*(substr($p[1],-1,1)<W?:-1) // add longitude to result
)
$n+=
($p=explode(' ',trim(fgets(STDIN)))) // read line, split at blank
[0]*(substr($p[0],-1)<S?:-1) // add latitude to result
;
echo abs($n),'NS'[$n<0],' ',abs($e),'EW'[$e<0]; // print result
```
# PHP, ~~206~~ ~~197~~ 195 bytes
literally speaking, "moste verbose" would probably be Mathematica or Mathlab?
```
<?function i(){preg_match('#\d+(.) (\d+)(.)#',fgets(STDIN),$m);return[$m[0]*($m[1]<S?:-1),$m[2]*($m[3]<W?:-1)];}echo abs($v=($a=i())[0]+($b=i())[0]),'NS'[$v<0],' ',abs($v=$a[1]+$b[1]),'EW'[$v<0];
```
* output is pretty unformatted, not even a trainling newline
* prints large numbers for too large result
Now, how can I double the size of this ...
**breakdown**
```
function i()
// read a pair of coordinates from STDIN, return signed values
{
// read line from STDIN and take (number,character,number,character) from it
// will produce something like ["111N 222E","N","222","E"]
preg_match('#\d+(.) (\d+)(.)#',fgets(STDIN),$m);
return[
// using a numerical operation on $m[0] casts the string to number (int in this case)
$m[0]*($m[1]<S?:-1) // convert latitude to signed int: multiply with -1 for $m[1]=='S'
,
$m[2]*($m[3]<W?:-1) // convert longitude to signed int
];
}
$a=i();$b=i(); // read coordinates from STDIN
echo // output:
abs($v=$a[0]+$b[0]) // 1. unsigned sum of latitudes
,'NS'[$v<0] // 2. direction depending on sign
,' ', // 3. delimiter
abs($v=$a[1]+$b[1]), // 4. unsigned sum of longitudes
'EW'[$v<0] // 5. direction depending on sign
;
```
[Answer]
# [GolfScript](https://tio.run/##S8/PSStOLsosKPn/v7pOs9ZKKVjJSslVyboayPQDMsOVrJW4lPTroqvVFdT1o6v1dA1t6mJ0De0S6mr1Y2NqjbRiqzILoqurtWu1gAIaegY21YlJxerB6rXV6n7qtZlpQH3aDnUwcVeQeDhI/P9/E6NgBWNDk3AuEyM/BSNzQ4twAA) - 111 bytes
```
{~)}:"S":"E";{}:"N":"W";"
"/~[{' '/[{.-1<~\-1>`~}/]\}2*]zip[{{+}*}/](.0<{abs'S'}{'N'}if' '+@~.0<{abs'E'}{'W'}if
```
### Explanation
```
{~)}:"S":"E"; # Aliases these as *-1
{}:"N":"W"; # Alieses to nop
"\n"/~ # Splits lines
[{' '/[{.-1<~\-1>`~}/]\}2*]zip # Parses the input as vectors and applies the aliases
[{{+}*}/] # Vector sum
(.0<{abs'S'}{'N'}if' '+@ # Formats output
~.0<{abs'E'}{'W'}if
```
[Answer]
# Python 2.7 - ~~232~~ 175 bytes
Works for all of the test cases. Always inserts N or W for 0. I'm sure a better Python golfer than me could shave a good few more bytes off.
```
f=(raw_input().split(" ")+raw_input().split(" "))
for x in range(4):
i=f[x]
if "S" in i or "E" in i:i="-"+i
f[x]=int(i[:-1])
n=f[0]+f[2]
q=f[1]+f[3]
print str(abs(n))+("S" if n<0 else "N"),str(abs(q))+("E" if q<0 else "W")
```
**EDIT**
Golfed off a mighty 57 bytes due to some great tips from @mbomb007 and @Titus plus by spotting the fact that I could combine the two raw\_inputs with a space then just use one .split() which splits on the space without specifying it. The algorithm is the same but just much better golfed.
```
f=(raw_input()+" "+raw_input()).split()
for x in 0,1,2,3:
i=f[x]
if i[-1]in"SE":i="-"+i
f[x]=int(i[:-1])
n=f[0]+f[2]
q=f[1]+f[3]
print`abs(n)`+"NS"[n<0],`abs(q)`+"WE"[q<0]
```
] |
Subsets and Splits